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