]> ruderich.org/simon Gitweb - tlsproxy/tlsproxy.git/blob - tlsproxy.c
tlsproxy.c: Add -proxy command line option to use another TLS proxy.
[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     for (;;) {
124         /* Accept new connection. */
125         client_socket = accept(server_socket, NULL, NULL);
126         if (-1 == client_socket) {
127             perror("accept()");
128             return EXIT_FAILURE;
129         }
130
131         handle_connection(client_socket);
132     }
133
134     return EXIT_SUCCESS;
135 }
136
137 static void handle_connection(int client_socket) {
138     int server_socket;
139     FILE *client_fd, *server_fd;
140
141     char buffer[MAX_REQUEST_LINE];
142     char host[MAX_REQUEST_LINE];
143     char port[5 + 1];
144
145     int version_minor;
146     int result;
147
148     client_fd = fdopen(client_socket, "a+");
149     if (NULL == client_fd) {
150         perror("fdopen()");
151         close(client_socket);
152         return;
153     }
154
155 #ifdef DEBUG
156     printf("New connection:\n");
157 #endif
158
159     /* Read request line (CONNECT ..) and headers (they are discarded). */
160     result = read_http_request(client_fd, buffer, sizeof(buffer));
161     if (result == -1) {
162         /* Read error. */
163         return;
164     } else if (result == -2) {
165         /* EOF */
166         send_close_bad_request(client_fd);
167         return;
168     }
169
170 #ifdef DEBUG
171     printf("  request: %s", buffer);
172 #endif
173
174     if (0 != parse_request(buffer, host, port, &version_minor)) {
175         send_close_bad_request(client_fd);
176 #ifdef DEBUG
177         printf("  bad request\n");
178 #endif
179         return;
180     }
181
182 #ifdef DEBUG
183     printf("  %s:%s (HTTP 1.%d)\n", host, port, version_minor);
184 #endif
185
186     /* Connect to proxy server or directly to server. */
187     if (NULL != use_proxy_host && NULL != use_proxy_port) {
188         server_socket = connect_to_host(use_proxy_host, use_proxy_port);
189     } else {
190         server_socket = connect_to_host(host, port);
191     }
192
193     if (-1 == server_socket) {
194         send_close_forwarding_failure(client_fd);
195         return;
196     }
197     server_fd = fdopen(server_socket, "a+");
198     if (NULL == server_fd) {
199         send_close_forwarding_failure(client_fd);
200         return;
201     }
202
203     /* Connect to proxy if requested (command line option). */
204     if (NULL != use_proxy_host && NULL != use_proxy_port) {
205         fprintf(server_fd, "CONNECT %s:%s HTTP/1.0\r\n", host, port);
206         fprintf(server_fd, "\r\n");
207
208         /* Read response line from proxy server. */
209         result = read_http_request(server_fd, buffer, sizeof(buffer));
210         if (result == -1) {
211             /* Read error. */
212             send_close_forwarding_failure(client_fd);
213             return;
214         } else if (result == -2) {
215             /* EOF */
216             fclose(server_fd);
217             send_close_forwarding_failure(client_fd);
218             return;
219         }
220
221         /* Check response of proxy server. */
222         if (0 != strncmp(buffer, "HTTP/1.0 200", 12)) {
223 #ifdef DEBUG
224             printf("  bad proxy response\n");
225 #endif
226             fclose(server_fd);
227             send_close_forwarding_failure(client_fd);
228             return;
229         }
230     }
231
232 #ifdef DEBUG
233     printf("  connection to server established\n");
234 #endif
235
236     /* We've established a connection, tell the client. */
237     fprintf(client_fd, "HTTP/1.0 200 Connection established\r\n");
238     fprintf(client_fd, "\r\n");
239     fflush(client_fd);
240
241     /* And transfer all data between client and server transparently. */
242     transfer_data(client_socket, server_socket);
243
244     fclose(client_fd);
245     fclose(server_fd);
246 }
247
248 /* Read HTTP request line and headers (ignored).
249  *
250  * On success 0 is returned, -1 on client error (we close client descriptor in
251  * this case), -2 on unexpected EOF.
252  */
253 static int read_http_request(FILE *client_fd, char *request, size_t length) {
254     char buffer[MAX_REQUEST_LINE];
255
256     if (NULL == fgets(request, (int)length, client_fd)) {
257         if (ferror(client_fd)) {
258             perror("fgets(), request");
259             fclose(client_fd);
260             return -1;
261         }
262
263         return -2;
264     }
265
266     while (NULL != fgets(buffer, MAX_REQUEST_LINE, client_fd)) {
267         /* End of header. */
268         if (0 == strcmp(buffer, "\n") || 0 == strcmp(buffer, "\r\n")) {
269             break;
270         }
271     }
272     if (ferror(client_fd)) {
273         perror("fgets(), header");
274         fclose(client_fd);
275         return -1;
276     }
277
278     return 0;
279 }
280
281 static void send_close_bad_request(FILE *client_fd) {
282     fprintf(client_fd, "HTTP/1.0 400 Bad Request\r\n");
283     fprintf(client_fd, "\r\n");
284     fclose(client_fd);
285 }
286 static void send_close_forwarding_failure(FILE *client_fd) {
287     fprintf(client_fd, "HTTP/1.0 503 Forwarding failure\r\n");
288     fprintf(client_fd, "\r\n");
289     fclose(client_fd);
290 }
291
292
293 /* Transfer data between client and server sockets until one closes the
294  * connection. */
295 static void transfer_data(int client, int server) {
296     struct pollfd fds[2];
297     fds[0].fd      = client;
298     fds[0].events  = POLLIN | POLLPRI | POLLHUP | POLLERR;
299     fds[0].revents = 0;
300     fds[1].fd      = server;
301     fds[1].events  = POLLIN | POLLPRI | POLLHUP | POLLERR;
302     fds[1].revents = 0;
303
304     for (;;) {
305         int result = poll(fds, 2, 0);
306         if (result < 0) {
307             perror("poll()");
308             return;
309         }
310
311         /* Data available from client. */
312         if (fds[0].revents & POLLIN || fds[0].revents & POLLPRI) {
313             if (0 != read_from_write_to(client, server)) {
314                 /* EOF (or other error) */
315                 break;
316             }
317         }
318         /* Data available from server. */
319         if (fds[1].revents & POLLIN || fds[1].revents & POLLPRI) {
320             if (0 != read_from_write_to(server, client)) {
321                 /* EOF (or other error) */
322                 break;
323             }
324         }
325
326         /* Client closed connection. */
327         if (fds[0].revents & POLLERR || fds[0].revents & POLLHUP) {
328             break;
329         }
330         /* Server closed connection. */
331         if (fds[1].revents & POLLERR || fds[1].revents & POLLHUP) {
332             break;
333         }
334     }
335 }
336
337 /* Read available data from socket from and write it to socket to. At maximum
338  * 4096 bytes are read/written. */
339 static int read_from_write_to(int from, int to) {
340     ssize_t size_read;
341     ssize_t size_written;
342     char buffer[4096];
343
344     size_read = read(from, buffer, sizeof(buffer));
345     if (0 > size_read) {
346         perror("read()");
347         return -1;
348     }
349     /* EOF */
350     if (0 == size_read) {
351         return -1;
352     }
353
354     size_written = write(to, buffer, (size_t)size_read);
355     if (0 > size_written) {
356         perror("write()");
357         return -1;
358     }
359     if (size_read != size_written) {
360         printf("only written %ld of %ld bytes!\n", size_read, size_written);
361         return -1;
362     }
363
364     return 0;
365 }
366
367
368 static int connect_to_host(const char *hostname, const char *port) {
369     struct addrinfo gai_hints;
370     struct addrinfo *gai_result;
371     int gai_return;
372
373     int server_socket;
374     struct addrinfo *server;
375
376     if (NULL == hostname || NULL == port) {
377         return -1;
378     }
379
380     /* Get IP of hostname server. */
381     memset(&gai_hints, 0, sizeof(gai_hints));
382     gai_hints.ai_family   = AF_UNSPEC;
383     gai_hints.ai_socktype = SOCK_STREAM;
384     gai_hints.ai_protocol = 0;
385     gai_hints.ai_flags    = AI_NUMERICSERV /* given port is numeric */
386                           | AI_ADDRCONFIG  /* supported by this computer */
387                           | AI_V4MAPPED;   /* support IPv4 through IPv6 */
388     gai_return = getaddrinfo(hostname, port, &gai_hints, &gai_result);
389     if (0 != gai_return) {
390         perror("getaddrinfo()");
391         return -1;
392     }
393
394     /* Now try to connect to each server returned by getaddrinfo(), use the
395      * first successful connect. */
396     for (server = gai_result; NULL != server; server = server->ai_next) {
397         server_socket = socket(server->ai_family,
398                                server->ai_socktype,
399                                server->ai_protocol);
400         if (-1 == server_socket) {
401             perror("socket(), trying next");
402             continue;
403         }
404
405         if (-1 != connect(server_socket, server->ai_addr,
406                                          server->ai_addrlen)) {
407             break;
408         }
409         perror("connect(), trying next");
410
411         close(server_socket);
412     }
413     /* Make sure we free the result from getaddrinfo(). */
414     freeaddrinfo(gai_result);
415
416     if (NULL == server) {
417         fprintf(stderr, "no server found, aborting\n");
418         return -1;
419     }
420
421     return server_socket;
422 }
423
424
425 /* Parse HTTP CONNECT request string and save its parameters.
426  *
427  * The following format is expected: "CONNECT host:port HTTP/1.y".
428  *
429  * request and host must have the same size! port must be at least 6 bytes
430  * long (5 + '\0').
431  */
432 static int parse_request(const char *request, char *host, char *port,
433                                               int *version_minor) {
434     int port_unused; /* just used to verify the port is numeric */
435     char *position;
436
437     /* scanf() doesn't check spaces. */
438     if (0 != strncmp(request, "CONNECT ", 8)) {
439         return -1;
440     }
441     /* Check request and extract data, "host:port" is not yet separated. */
442     if (2 != sscanf(request, "CONNECT %s HTTP/1.%d",
443                              host, version_minor)) {
444         return -1;
445     }
446     /* Make sure ":port" is there. */
447     if (NULL == (position = strchr(host, ':'))) {
448         return -1;
449     }
450     /* Make sure port is numeric. */
451     if (1 != sscanf(position + 1, "%d", &port_unused)) {
452         return -1;
453     }
454     /* Store it in *port. */
455     strncpy(port, position + 1, 5);
456     port[5] = '\0';
457     /* And remove port from host. */
458     *position = '\0';
459
460     return 0;
461 }