]> ruderich.org/simon Gitweb - tlsproxy/tlsproxy.git/blob - tlsproxy.c
tlsproxy.c: Add more debug output.
[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 /* poll() */
34 #include <poll.h>
35
36
37 /* Maximum line of the request line. Longer request lines are aborted with an
38  * error. The standard doesn't specify a maximum line length but this should
39  * be a good limit to make processing simpler. */
40 #define MAX_REQUEST_LINE 4096
41
42
43 /* Proxy hostname and port if specified on the command line. */
44 static char *use_proxy_host;
45 static char *use_proxy_port;
46
47
48 static void handle_connection(int socket);
49 static int read_http_request(FILE *client_fd, char *request, size_t length);
50 static void send_close_bad_request(FILE *client_fd);
51 static void send_close_forwarding_failure(FILE *client_fd);
52
53 static void transfer_data(int client, int server);
54 static int read_from_write_to(int from, int to);
55
56 static int connect_to_host(const char *hostname, const char *port);
57
58 static int parse_request(const char *buffer, char *host, char *port,
59                                              int *version_minor);
60
61
62 int main(int argc, char **argv) {
63     int port;
64     int client_socket, server_socket;
65     struct sockaddr_in6 server_in;
66
67     if (2 != argc && 5 != argc) {
68         printf("Usage: %s [-proxy hostname port] port\n", argv[0]);
69         return EXIT_FAILURE;
70     }
71
72     port = atoi(argv[5 == argc ? 4 : 1]);
73     if (0 >= port || 0xffff < port) {
74         printf("Usage: %s [-proxy hostname port] port\n", argv[0]);
75         printf("\n");
76         printf("Invalid port: %s!\n", argv[5 == argc ? 4 : 1]);
77         return EXIT_FAILURE;
78     }
79
80     if (5 == argc) {
81         use_proxy_host = strdup(argv[2]);
82         use_proxy_port = strdup(argv[3]);
83         if (NULL == use_proxy_host || NULL == use_proxy_port) {
84             perror("strdup()");
85             return EXIT_FAILURE;
86         }
87 #ifdef DEBUG
88         printf("Using proxy: %s:%s.\n", use_proxy_host, use_proxy_port);
89 #endif
90     }
91
92     server_socket = socket(PF_INET6, SOCK_STREAM, 0);
93     if (-1 == server_socket) {
94         perror("socket()");
95         return EXIT_FAILURE;
96     }
97
98 #ifdef DEBUG
99     /* Fast rebinding for debug mode, could cause invalid packets. */
100     {
101         int socket_option = 1;
102         setsockopt(server_socket, SOL_SOCKET, SO_REUSEADDR,
103                    &socket_option, sizeof(socket_option));
104     }
105 #endif
106
107     /* Bind to the listen socket. */
108     memset(&server_in, 0, sizeof(server_in));
109     server_in.sin6_family = AF_INET6;              /* IPv6 (and IPv4) */
110     server_in.sin6_addr   = in6addr_any;           /* bind to any address */
111     server_in.sin6_port   = htons((uint16_t)port); /* port to bind to */
112     if (-1 == bind(server_socket, (struct sockaddr *)&server_in,
113                                   sizeof(server_in))) {
114         perror("bind()");
115         return EXIT_FAILURE;
116     }
117     /* And accept connections. */
118     if (-1 == listen(server_socket, 5)) {
119         perror("listen()");
120         return EXIT_FAILURE;
121     }
122
123 #ifdef DEBUG
124     printf("Listening for connections on port %d.\n", port);
125 #endif
126
127     for (;;) {
128         /* Accept new connection. */
129         client_socket = accept(server_socket, NULL, NULL);
130         if (-1 == client_socket) {
131             perror("accept()");
132             return EXIT_FAILURE;
133         }
134
135         handle_connection(client_socket);
136     }
137
138     return EXIT_SUCCESS;
139 }
140
141 static void handle_connection(int client_socket) {
142     int server_socket;
143     FILE *client_fd, *server_fd;
144
145     char buffer[MAX_REQUEST_LINE];
146     char host[MAX_REQUEST_LINE];
147     char port[5 + 1];
148
149     int version_minor;
150     int result;
151
152     client_fd = fdopen(client_socket, "a+");
153     if (NULL == client_fd) {
154         perror("fdopen()");
155         close(client_socket);
156         return;
157     }
158
159 #ifdef DEBUG
160     printf("New connection:\n");
161 #endif
162
163     /* Read request line (CONNECT ..) and headers (they are discarded). */
164     result = read_http_request(client_fd, buffer, sizeof(buffer));
165     if (result == -1) {
166         /* Read error. */
167         return;
168     } else if (result == -2) {
169         /* EOF */
170         send_close_bad_request(client_fd);
171         return;
172     }
173
174 #ifdef DEBUG
175     printf("  request: %s", buffer);
176 #endif
177
178     if (0 != parse_request(buffer, host, port, &version_minor)) {
179         send_close_bad_request(client_fd);
180 #ifdef DEBUG
181         printf("  bad request\n");
182 #endif
183         return;
184     }
185
186 #ifdef DEBUG
187     printf("  %s:%s (HTTP 1.%d)\n", host, port, version_minor);
188 #endif
189
190     /* Connect to proxy server or directly to server. */
191     if (NULL != use_proxy_host && NULL != use_proxy_port) {
192         server_socket = connect_to_host(use_proxy_host, use_proxy_port);
193     } else {
194         server_socket = connect_to_host(host, port);
195     }
196
197     if (-1 == server_socket) {
198         send_close_forwarding_failure(client_fd);
199         return;
200     }
201     server_fd = fdopen(server_socket, "a+");
202     if (NULL == server_fd) {
203         send_close_forwarding_failure(client_fd);
204         return;
205     }
206
207     /* Connect to proxy if requested (command line option). */
208     if (NULL != use_proxy_host && NULL != use_proxy_port) {
209         fprintf(server_fd, "CONNECT %s:%s HTTP/1.0\r\n", host, port);
210         fprintf(server_fd, "\r\n");
211
212         /* Read response line from proxy server. */
213         result = read_http_request(server_fd, buffer, sizeof(buffer));
214         if (result == -1) {
215             /* Read error. */
216             send_close_forwarding_failure(client_fd);
217             return;
218         } else if (result == -2) {
219             /* EOF */
220             fclose(server_fd);
221             send_close_forwarding_failure(client_fd);
222             return;
223         }
224
225         /* Check response of proxy server. */
226         if (0 != strncmp(buffer, "HTTP/1.0 200", 12)) {
227 #ifdef DEBUG
228             printf("  bad proxy response\n");
229 #endif
230             fclose(server_fd);
231             send_close_forwarding_failure(client_fd);
232             return;
233         }
234     }
235
236 #ifdef DEBUG
237     printf("  connection to server established\n");
238 #endif
239
240     /* We've established a connection, tell the client. */
241     fprintf(client_fd, "HTTP/1.0 200 Connection established\r\n");
242     fprintf(client_fd, "\r\n");
243     fflush(client_fd);
244
245     /* And transfer all data between client and server transparently. */
246     transfer_data(client_socket, server_socket);
247
248     fclose(client_fd);
249     fclose(server_fd);
250 }
251
252 /* Read HTTP request line and headers (ignored).
253  *
254  * On success 0 is returned, -1 on client error (we close client descriptor in
255  * this case), -2 on unexpected EOF.
256  */
257 static int read_http_request(FILE *client_fd, char *request, size_t length) {
258     char buffer[MAX_REQUEST_LINE];
259
260     if (NULL == fgets(request, (int)length, client_fd)) {
261         if (ferror(client_fd)) {
262             perror("fgets(), request");
263             fclose(client_fd);
264             return -1;
265         }
266
267         return -2;
268     }
269
270     while (NULL != fgets(buffer, MAX_REQUEST_LINE, client_fd)) {
271         /* End of header. */
272         if (0 == strcmp(buffer, "\n") || 0 == strcmp(buffer, "\r\n")) {
273             break;
274         }
275     }
276     if (ferror(client_fd)) {
277         perror("fgets(), header");
278         fclose(client_fd);
279         return -1;
280     }
281
282     return 0;
283 }
284
285 static void send_close_bad_request(FILE *client_fd) {
286     fprintf(client_fd, "HTTP/1.0 400 Bad Request\r\n");
287     fprintf(client_fd, "\r\n");
288     fclose(client_fd);
289 }
290 static void send_close_forwarding_failure(FILE *client_fd) {
291     fprintf(client_fd, "HTTP/1.0 503 Forwarding failure\r\n");
292     fprintf(client_fd, "\r\n");
293     fclose(client_fd);
294 }
295
296
297 /* Transfer data between client and server sockets until one closes the
298  * connection. */
299 static void transfer_data(int client, int server) {
300     struct pollfd fds[2];
301     fds[0].fd      = client;
302     fds[0].events  = POLLIN | POLLPRI | POLLHUP | POLLERR;
303     fds[0].revents = 0;
304     fds[1].fd      = server;
305     fds[1].events  = POLLIN | POLLPRI | POLLHUP | POLLERR;
306     fds[1].revents = 0;
307
308     for (;;) {
309         int result = poll(fds, 2, 0);
310         if (result < 0) {
311             perror("poll()");
312             return;
313         }
314
315         /* Data available from client. */
316         if (fds[0].revents & POLLIN || fds[0].revents & POLLPRI) {
317             if (0 != read_from_write_to(client, server)) {
318                 /* EOF (or other error) */
319                 break;
320             }
321         }
322         /* Data available from server. */
323         if (fds[1].revents & POLLIN || fds[1].revents & POLLPRI) {
324             if (0 != read_from_write_to(server, client)) {
325                 /* EOF (or other error) */
326                 break;
327             }
328         }
329
330         /* Client closed connection. */
331         if (fds[0].revents & POLLERR || fds[0].revents & POLLHUP) {
332             break;
333         }
334         /* Server closed connection. */
335         if (fds[1].revents & POLLERR || fds[1].revents & POLLHUP) {
336             break;
337         }
338     }
339 }
340
341 /* Read available data from socket from and write it to socket to. At maximum
342  * 4096 bytes are read/written. */
343 static int read_from_write_to(int from, int to) {
344     ssize_t size_read;
345     ssize_t size_written;
346     char buffer[4096];
347
348     size_read = read(from, buffer, sizeof(buffer));
349     if (0 > size_read) {
350         perror("read()");
351         return -1;
352     }
353     /* EOF */
354     if (0 == size_read) {
355         return -1;
356     }
357
358     size_written = write(to, buffer, (size_t)size_read);
359     if (0 > size_written) {
360         perror("write()");
361         return -1;
362     }
363     if (size_read != size_written) {
364         printf("only written %ld of %ld bytes!\n", size_read, size_written);
365         return -1;
366     }
367
368     return 0;
369 }
370
371
372 static int connect_to_host(const char *hostname, const char *port) {
373     struct addrinfo gai_hints;
374     struct addrinfo *gai_result;
375     int gai_return;
376
377     int server_socket;
378     struct addrinfo *server;
379
380     if (NULL == hostname || NULL == port) {
381         return -1;
382     }
383
384     /* Get IP of hostname server. */
385     memset(&gai_hints, 0, sizeof(gai_hints));
386     gai_hints.ai_family   = AF_UNSPEC;
387     gai_hints.ai_socktype = SOCK_STREAM;
388     gai_hints.ai_protocol = 0;
389     gai_hints.ai_flags    = AI_NUMERICSERV /* given port is numeric */
390                           | AI_ADDRCONFIG  /* supported by this computer */
391                           | AI_V4MAPPED;   /* support IPv4 through IPv6 */
392     gai_return = getaddrinfo(hostname, port, &gai_hints, &gai_result);
393     if (0 != gai_return) {
394         perror("getaddrinfo()");
395         return -1;
396     }
397
398     /* Now try to connect to each server returned by getaddrinfo(), use the
399      * first successful connect. */
400     for (server = gai_result; NULL != server; server = server->ai_next) {
401         server_socket = socket(server->ai_family,
402                                server->ai_socktype,
403                                server->ai_protocol);
404         if (-1 == server_socket) {
405             perror("socket(), trying next");
406             continue;
407         }
408
409         if (-1 != connect(server_socket, server->ai_addr,
410                                          server->ai_addrlen)) {
411             break;
412         }
413         perror("connect(), trying next");
414
415         close(server_socket);
416     }
417     /* Make sure we free the result from getaddrinfo(). */
418     freeaddrinfo(gai_result);
419
420     if (NULL == server) {
421         fprintf(stderr, "no server found, aborting\n");
422         return -1;
423     }
424
425     return server_socket;
426 }
427
428
429 /* Parse HTTP CONNECT request string and save its parameters.
430  *
431  * The following format is expected: "CONNECT host:port HTTP/1.y".
432  *
433  * request and host must have the same size! port must be at least 6 bytes
434  * long (5 + '\0').
435  */
436 static int parse_request(const char *request, char *host, char *port,
437                                               int *version_minor) {
438     int port_unused; /* just used to verify the port is numeric */
439     char *position;
440
441     /* scanf() doesn't check spaces. */
442     if (0 != strncmp(request, "CONNECT ", 8)) {
443         return -1;
444     }
445     /* Check request and extract data, "host:port" is not yet separated. */
446     if (2 != sscanf(request, "CONNECT %s HTTP/1.%d",
447                              host, version_minor)) {
448         return -1;
449     }
450     /* Make sure ":port" is there. */
451     if (NULL == (position = strchr(host, ':'))) {
452         return -1;
453     }
454     /* Make sure port is numeric. */
455     if (1 != sscanf(position + 1, "%d", &port_unused)) {
456         return -1;
457     }
458     /* Store it in *port. */
459     strncpy(port, position + 1, 5);
460     port[5] = '\0';
461     /* And remove port from host. */
462     *position = '\0';
463
464     return 0;
465 }