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