]> ruderich.org/simon Gitweb - tlsproxy/tlsproxy.git/blob - tlsproxy.c
tlsproxy.c: Free resources when receiving SIGINT.
[tlsproxy/tlsproxy.git] / tlsproxy.c
1 /*
2  * tlsproxy is a transparent TLS proxy for HTTPS connections.
3  *
4  * Copyright (C) 2011  Simon Ruderich
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 #include <stdlib.h>
21 #include <stdio.h>
22 /* socket(), bind(), accept(), listen() */
23 #include <sys/types.h>
24 #include <sys/socket.h>
25 /* close() */
26 #include <unistd.h>
27 /* htons() */
28 #include <arpa/inet.h>
29 /* getaddrinfo() */
30 #include <netdb.h>
31 /* strncmp() */
32 #include <string.h>
33 /* sigaction() */
34 #include <signal.h>
35 /* poll() */
36 #include <poll.h>
37
38
39 /* Maximum line of the request line. Longer request lines are aborted with an
40  * error. The standard doesn't specify a maximum line length but this should
41  * be a good limit to make processing simpler. */
42 #define MAX_REQUEST_LINE 4096
43
44
45 /* Server should shut down. Set by SIGINT handler. */
46 static volatile int done;
47
48 /* Proxy hostname and port if specified on the command line. */
49 static char *use_proxy_host;
50 static char *use_proxy_port;
51
52
53 static void sigint_handler(int signal);
54
55 static void parse_arguments(int argc, char **argv);
56 static void print_usage(const char *argv);
57
58 static void handle_connection(int socket);
59 static int read_http_request(FILE *client_fd, char *request, size_t length);
60 static void send_close_bad_request(FILE *client_fd);
61 static void send_close_forwarding_failure(FILE *client_fd);
62
63 static void transfer_data(int client, int server);
64 static int read_from_write_to(int from, int to);
65
66 static int connect_to_host(const char *hostname, const char *port);
67
68 static int parse_request(const char *buffer, char *host, char *port,
69                                              int *version_minor);
70
71
72 int main(int argc, char **argv) {
73     int port;
74     int client_socket, server_socket;
75     struct sockaddr_in6 server_in;
76
77     struct sigaction action;
78
79     parse_arguments(argc, argv);
80
81     port = atoi(argv[argc - 1]);
82     if (0 >= port || 0xffff < port) {
83         print_usage(argv[0]);
84         fprintf(stderr, "\ninvalid port");
85         return EXIT_FAILURE;
86     }
87
88     /* Setup our SIGINT signal handler which allows a "normal" termination of
89      * the server. */
90     sigemptyset(&action.sa_mask);
91     action.sa_handler = sigint_handler;
92     action.sa_flags   = 0;
93     sigaction(SIGINT, &action, NULL);
94
95     server_socket = socket(PF_INET6, SOCK_STREAM, 0);
96     if (-1 == server_socket) {
97         perror("socket()");
98         return EXIT_FAILURE;
99     }
100
101 #ifdef DEBUG
102     /* Fast rebinding for debug mode, could cause invalid packets. */
103     {
104         int socket_option = 1;
105         setsockopt(server_socket, SOL_SOCKET, SO_REUSEADDR,
106                    &socket_option, sizeof(socket_option));
107     }
108 #endif
109
110     /* Bind to the listen socket. */
111     memset(&server_in, 0, sizeof(server_in));
112     server_in.sin6_family = AF_INET6;              /* IPv6 (and IPv4) */
113     server_in.sin6_addr   = in6addr_any;           /* bind to any address */
114     server_in.sin6_port   = htons((uint16_t)port); /* port to bind to */
115     if (-1 == bind(server_socket, (struct sockaddr *)&server_in,
116                                   sizeof(server_in))) {
117         perror("bind()");
118         return EXIT_FAILURE;
119     }
120     /* And accept connections. */
121     if (-1 == listen(server_socket, 5)) {
122         perror("listen()");
123         return EXIT_FAILURE;
124     }
125
126 #ifdef DEBUG
127     printf("Listening for connections on port %d.\n", port);
128
129     if (NULL != use_proxy_host && NULL != use_proxy_port) {
130         printf("Using proxy: %s:%s.\n", use_proxy_host, use_proxy_port);
131     }
132 #endif
133
134     while (!done) {
135         /* Accept new connection. */
136         client_socket = accept(server_socket, NULL, NULL);
137         if (-1 == client_socket) {
138             perror("accept()");
139             break;
140         }
141
142         handle_connection(client_socket);
143     }
144
145     close(server_socket);
146
147     free(use_proxy_host);
148     free(use_proxy_port);
149
150     return EXIT_FAILURE;
151 }
152
153 static void sigint_handler(int signal_number) {
154     (void)signal_number;
155
156     done = 1;
157 }
158
159 static void parse_arguments(int argc, char **argv) {
160     int option;
161
162     while (-1 != (option = getopt(argc, argv, "p:h?"))) {
163         switch (option) {
164             case 'p': {
165                 char *position;
166
167                 /* -p must have the format host:port. */
168                 if (NULL == (position = strchr(optarg, ':'))
169                         || position == optarg
170                         || 0 == strlen(position + 1)
171                         || 0 >= atoi(position + 1)
172                         || 0xffff < atoi(position + 1)) {
173                     fprintf(stderr, "-p host:port\n");
174                     exit(EXIT_FAILURE);
175                 }
176
177                 use_proxy_host = malloc((size_t)(position - optarg) + 1);
178                 if (NULL == use_proxy_host) {
179                     perror("malloc()");
180                     exit(EXIT_FAILURE);
181                 }
182                 memcpy(use_proxy_host, optarg, (size_t)(position - optarg));
183                 use_proxy_host[position - optarg] = '\0';
184
185                 use_proxy_port = malloc(strlen(position + 1) + 1);
186                 if (NULL == use_proxy_port) {
187                     perror("malloc()");
188                     exit(EXIT_FAILURE);
189                 }
190                 strcpy(use_proxy_port, position + 1);
191
192                 break;
193             }
194             case 'h':
195             default: /* '?' */
196                 print_usage(argv[0]);
197                 exit(EXIT_FAILURE);
198         }
199     }
200
201     if (optind >= argc) {
202         print_usage(argv[0]);
203         exit(EXIT_FAILURE);
204     }
205 }
206 static void print_usage(const char *argv) {
207     fprintf(stderr, "Usage: %s [-p host:port] port\n", argv);
208     fprintf(stderr, "\n");
209     fprintf(stderr, "-p proxy hostname and port\n");
210 }
211
212 static void handle_connection(int client_socket) {
213     int server_socket;
214     FILE *client_fd, *server_fd;
215
216     char buffer[MAX_REQUEST_LINE];
217     char host[MAX_REQUEST_LINE];
218     char port[5 + 1];
219
220     int version_minor;
221     int result;
222
223     client_fd = fdopen(client_socket, "a+");
224     if (NULL == client_fd) {
225         perror("fdopen()");
226         close(client_socket);
227         return;
228     }
229
230 #ifdef DEBUG
231     printf("New connection:\n");
232 #endif
233
234     /* Read request line (CONNECT ..) and headers (they are discarded). */
235     result = read_http_request(client_fd, buffer, sizeof(buffer));
236     if (result == -1) {
237         /* Read error. */
238         return;
239     } else if (result == -2) {
240         /* EOF */
241         send_close_bad_request(client_fd);
242         return;
243     }
244
245 #ifdef DEBUG
246     printf("  request: %s", buffer);
247 #endif
248
249     if (0 != parse_request(buffer, host, port, &version_minor)) {
250         send_close_bad_request(client_fd);
251 #ifdef DEBUG
252         printf("  bad request\n");
253 #endif
254         return;
255     }
256
257 #ifdef DEBUG
258     printf("  %s:%s (HTTP 1.%d)\n", host, port, version_minor);
259 #endif
260
261     /* Connect to proxy server or directly to server. */
262     if (NULL != use_proxy_host && NULL != use_proxy_port) {
263         server_socket = connect_to_host(use_proxy_host, use_proxy_port);
264     } else {
265         server_socket = connect_to_host(host, port);
266     }
267
268     if (-1 == server_socket) {
269         send_close_forwarding_failure(client_fd);
270         return;
271     }
272     server_fd = fdopen(server_socket, "a+");
273     if (NULL == server_fd) {
274         send_close_forwarding_failure(client_fd);
275         return;
276     }
277
278     /* Connect to proxy if requested (command line option). */
279     if (NULL != use_proxy_host && NULL != use_proxy_port) {
280         fprintf(server_fd, "CONNECT %s:%s HTTP/1.0\r\n", host, port);
281         fprintf(server_fd, "\r\n");
282
283         /* Read response line from proxy server. */
284         result = read_http_request(server_fd, buffer, sizeof(buffer));
285         if (result == -1) {
286             /* Read error. */
287             send_close_forwarding_failure(client_fd);
288             return;
289         } else if (result == -2) {
290             /* EOF */
291             fclose(server_fd);
292             send_close_forwarding_failure(client_fd);
293             return;
294         }
295
296         /* Check response of proxy server. */
297         if (0 != strncmp(buffer, "HTTP/1.0 200", 12)) {
298 #ifdef DEBUG
299             printf("  bad proxy response\n");
300 #endif
301             fclose(server_fd);
302             send_close_forwarding_failure(client_fd);
303             return;
304         }
305     }
306
307 #ifdef DEBUG
308     printf("  connection to server established\n");
309 #endif
310
311     /* We've established a connection, tell the client. */
312     fprintf(client_fd, "HTTP/1.0 200 Connection established\r\n");
313     fprintf(client_fd, "\r\n");
314     fflush(client_fd);
315
316     /* And transfer all data between client and server transparently. */
317     transfer_data(client_socket, server_socket);
318
319     fclose(client_fd);
320     fclose(server_fd);
321 }
322
323 /* Read HTTP request line and headers (ignored).
324  *
325  * On success 0 is returned, -1 on client error (we close client descriptor in
326  * this case), -2 on unexpected EOF.
327  */
328 static int read_http_request(FILE *client_fd, char *request, size_t length) {
329     char buffer[MAX_REQUEST_LINE];
330
331     if (NULL == fgets(request, (int)length, client_fd)) {
332         if (ferror(client_fd)) {
333             perror("fgets(), request");
334             fclose(client_fd);
335             return -1;
336         }
337
338         return -2;
339     }
340
341     while (NULL != fgets(buffer, MAX_REQUEST_LINE, client_fd)) {
342         /* End of header. */
343         if (0 == strcmp(buffer, "\n") || 0 == strcmp(buffer, "\r\n")) {
344             break;
345         }
346     }
347     if (ferror(client_fd)) {
348         perror("fgets(), header");
349         fclose(client_fd);
350         return -1;
351     }
352
353     return 0;
354 }
355
356 static void send_close_bad_request(FILE *client_fd) {
357     fprintf(client_fd, "HTTP/1.0 400 Bad Request\r\n");
358     fprintf(client_fd, "\r\n");
359     fclose(client_fd);
360 }
361 static void send_close_forwarding_failure(FILE *client_fd) {
362     fprintf(client_fd, "HTTP/1.0 503 Forwarding failure\r\n");
363     fprintf(client_fd, "\r\n");
364     fclose(client_fd);
365 }
366
367
368 /* Transfer data between client and server sockets until one closes the
369  * connection. */
370 static void transfer_data(int client, int server) {
371     struct pollfd fds[2];
372     fds[0].fd      = client;
373     fds[0].events  = POLLIN | POLLPRI | POLLHUP | POLLERR;
374     fds[0].revents = 0;
375     fds[1].fd      = server;
376     fds[1].events  = POLLIN | POLLPRI | POLLHUP | POLLERR;
377     fds[1].revents = 0;
378
379     for (;;) {
380         int result = poll(fds, 2, 0);
381         if (result < 0) {
382             perror("poll()");
383             return;
384         }
385
386         /* Data available from client. */
387         if (fds[0].revents & POLLIN || fds[0].revents & POLLPRI) {
388             if (0 != read_from_write_to(client, server)) {
389                 /* EOF (or other error) */
390                 break;
391             }
392         }
393         /* Data available from server. */
394         if (fds[1].revents & POLLIN || fds[1].revents & POLLPRI) {
395             if (0 != read_from_write_to(server, client)) {
396                 /* EOF (or other error) */
397                 break;
398             }
399         }
400
401         /* Client closed connection. */
402         if (fds[0].revents & POLLERR || fds[0].revents & POLLHUP) {
403             break;
404         }
405         /* Server closed connection. */
406         if (fds[1].revents & POLLERR || fds[1].revents & POLLHUP) {
407             break;
408         }
409     }
410 }
411
412 /* Read available data from socket from and write it to socket to. At maximum
413  * 4096 bytes are read/written. */
414 static int read_from_write_to(int from, int to) {
415     ssize_t size_read;
416     ssize_t size_written;
417     char buffer[4096];
418
419     size_read = read(from, buffer, sizeof(buffer));
420     if (0 > size_read) {
421         perror("read()");
422         return -1;
423     }
424     /* EOF */
425     if (0 == size_read) {
426         return -1;
427     }
428
429     size_written = write(to, buffer, (size_t)size_read);
430     if (0 > size_written) {
431         perror("write()");
432         return -1;
433     }
434     if (size_read != size_written) {
435         printf("only written %ld of %ld bytes!\n", size_read, size_written);
436         return -1;
437     }
438
439     return 0;
440 }
441
442
443 static int connect_to_host(const char *hostname, const char *port) {
444     struct addrinfo gai_hints;
445     struct addrinfo *gai_result;
446     int gai_return;
447
448     int server_socket;
449     struct addrinfo *server;
450
451     if (NULL == hostname || NULL == port) {
452         return -1;
453     }
454
455     /* Get IP of hostname server. */
456     memset(&gai_hints, 0, sizeof(gai_hints));
457     gai_hints.ai_family   = AF_UNSPEC;
458     gai_hints.ai_socktype = SOCK_STREAM;
459     gai_hints.ai_protocol = 0;
460     gai_hints.ai_flags    = AI_NUMERICSERV /* given port is numeric */
461                           | AI_ADDRCONFIG  /* supported by this computer */
462                           | AI_V4MAPPED;   /* support IPv4 through IPv6 */
463     gai_return = getaddrinfo(hostname, port, &gai_hints, &gai_result);
464     if (0 != gai_return) {
465         perror("getaddrinfo()");
466         return -1;
467     }
468
469     /* Now try to connect to each server returned by getaddrinfo(), use the
470      * first successful connect. */
471     for (server = gai_result; NULL != server; server = server->ai_next) {
472         server_socket = socket(server->ai_family,
473                                server->ai_socktype,
474                                server->ai_protocol);
475         if (-1 == server_socket) {
476             perror("socket(), trying next");
477             continue;
478         }
479
480         if (-1 != connect(server_socket, server->ai_addr,
481                                          server->ai_addrlen)) {
482             break;
483         }
484         perror("connect(), trying next");
485
486         close(server_socket);
487     }
488     /* Make sure we free the result from getaddrinfo(). */
489     freeaddrinfo(gai_result);
490
491     if (NULL == server) {
492         fprintf(stderr, "no server found, aborting\n");
493         return -1;
494     }
495
496     return server_socket;
497 }
498
499
500 /* Parse HTTP CONNECT request string and save its parameters.
501  *
502  * The following format is expected: "CONNECT host:port HTTP/1.y".
503  *
504  * request and host must have the same size! port must be at least 6 bytes
505  * long (5 + '\0').
506  */
507 static int parse_request(const char *request, char *host, char *port,
508                                               int *version_minor) {
509     int port_unused; /* just used to verify the port is numeric */
510     char *position;
511
512     /* scanf() doesn't check spaces. */
513     if (0 != strncmp(request, "CONNECT ", 8)) {
514         return -1;
515     }
516     /* Check request and extract data, "host:port" is not yet separated. */
517     if (2 != sscanf(request, "CONNECT %s HTTP/1.%d",
518                              host, version_minor)) {
519         return -1;
520     }
521     /* Make sure ":port" is there. */
522     if (NULL == (position = strchr(host, ':'))) {
523         return -1;
524     }
525     /* Make sure port is numeric. */
526     if (1 != sscanf(position + 1, "%d", &port_unused)) {
527         return -1;
528     }
529     /* Store it in *port. */
530     strncpy(port, position + 1, 5);
531     port[5] = '\0';
532     /* And remove port from host. */
533     *position = '\0';
534
535     return 0;
536 }