]> ruderich.org/simon Gitweb - tlsproxy/tlsproxy.git/blob - src/tlsproxy.c
0257d6788f79d121832a04117e67b98a95ce84ad
[tlsproxy/tlsproxy.git] / src / tlsproxy.c
1 /*
2  * tlsproxy is a TLS proxy for HTTPS which intercepts the connections and
3  * ensures the server certificate doesn't change. Normally this isn't detected
4  * if a trusted CA for the new server certificate is installed.
5  *
6  * Copyright (C) 2011-2013  Simon Ruderich
7  *
8  * This program is free software: you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation, either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
20  */
21
22 #include "tlsproxy.h"
23 #include "sem.h"
24 #include "connection.h"
25
26 #include <arpa/inet.h>
27 #include <errno.h>
28 #include <pthread.h>
29 #include <signal.h>
30 #include <sys/socket.h>
31 #include <sys/stat.h>
32 #include <sys/types.h>
33 #include <unistd.h>
34
35 /* Necessary for GnuTLS when used with threads. */
36 #include <gcrypt.h>
37 GCRY_THREAD_OPTION_PTHREAD_IMPL;
38
39
40 /* Size of ringbuffer. */
41 #define RINGBUFFER_SIZE 10
42
43 /* Bit size of Diffie-Hellman key exchange parameters. */
44 #define DH_SIZE 1024
45
46
47 /* For gnutls_*() functions. */
48 #define GNUTLS_ERROR_EXIT(error, message) \
49     if (error != GNUTLS_E_SUCCESS) { \
50         fprintf(stderr, "%s: %s\n", message, gnutls_strerror(error)); \
51         exit(EXIT_FAILURE); \
52     }
53
54
55 /* Server should shut down. Set by SIGINT handler. */
56 static volatile int done; /* = 0 */
57
58 /* Number of threads. */
59 static size_t thread_count;
60
61 /* Synchronized ring buffer storing accept()ed client sockets. */
62 static int ringbuffer[RINGBUFFER_SIZE];
63 static int ringbuffer_read;
64 static int ringbuffer_write;
65 static SEM *ringbuffer_full; /* At least one element in the buffer? */
66 static SEM *ringbuffer_free; /* Space for another element in the buffer? */
67 static SEM *ringbuffer_lock; /* Read lock. */
68
69
70 #ifdef DEBUG
71 static void sigint_handler(int signal);
72 #endif
73
74 static void parse_arguments(int argc, char **argv);
75 static void print_usage(const char *argv);
76 static char *slurp_file(const char *path);
77
78 static void initialize_gnutls(void);
79 static void deinitialize_gnutls(void);
80
81 static void *worker_thread(void *unused);
82
83
84 int main(int argc, char **argv) {
85     int port;
86     int client_socket, server_socket;
87 #ifdef USE_IPV4_ONLY
88     struct sockaddr_in server_in;
89 #else
90     struct sockaddr_in6 server_in;
91 #endif
92
93     size_t i;
94     pthread_t *threads;
95
96     struct sigaction action;
97
98     /* Required in a few places. */
99     ct_assert(sizeof(size_t) >= sizeof(int));
100     ct_assert(sizeof(size_t) >= sizeof(ssize_t));
101
102     parse_arguments(argc, argv);
103
104     port = atoi(argv[argc - 1]);
105     if (port <= 0 || port > 0xffff ) {
106         fprintf(stderr, "invalid port: '%s'\n", argv[argc - 1]);
107         return EXIT_FAILURE;
108     }
109
110     memset(&action, 0, sizeof(action));
111     sigemptyset(&action.sa_mask);
112 #ifdef DEBUG
113     /* Setup our SIGINT signal handler which allows a "normal" termination of
114      * the server in DEBUG mode. */
115     action.sa_handler = sigint_handler;
116     sigaction(SIGINT, &action, NULL);
117 #endif
118     /* Ignore SIGPIPEs. */
119     action.sa_handler = SIG_IGN;
120     sigaction(SIGPIPE, &action, NULL);
121
122     /* Initialize ring buffer. */
123     ringbuffer_read  = 0;
124     ringbuffer_write = 0;
125     ringbuffer_full  = sem_init(0);
126     ringbuffer_free  = sem_init(RINGBUFFER_SIZE);
127     ringbuffer_lock  = sem_init(1);
128     if (NULL == ringbuffer_full
129             || NULL == ringbuffer_free
130             || NULL == ringbuffer_lock) {
131         perror("sem_init()");
132         return EXIT_FAILURE;
133     }
134
135     initialize_gnutls();
136
137     /* Spawn worker threads to handle requests. */
138     threads = malloc(thread_count * sizeof(*threads));
139     if (threads == NULL) {
140         perror("thread malloc failed");
141         return EXIT_FAILURE;
142     }
143     for (i = 0; i < thread_count; i++) {
144         errno = pthread_create(threads + i, NULL, &worker_thread, NULL);
145         if (errno != 0) {
146             perror("failed to create worker thread");
147             return EXIT_FAILURE;
148         }
149     }
150
151 #ifdef USE_IPV4_ONLY
152     server_socket = socket(PF_INET, SOCK_STREAM, 0);
153 #else
154     server_socket = socket(PF_INET6, SOCK_STREAM, 0);
155 #endif
156     if (server_socket < 0) {
157         perror("socket()");
158         return EXIT_FAILURE;
159     }
160
161     /* Fast rebinding for debug mode, could cause invalid packets. */
162     if (global_log_level >= LOG_DEBUG1_LEVEL) {
163         int socket_option = 1;
164         setsockopt(server_socket, SOL_SOCKET, SO_REUSEADDR,
165                    &socket_option, sizeof(socket_option));
166     }
167
168     /* Bind to the listen socket. */
169     memset(&server_in, 0, sizeof(server_in));
170 #ifdef USE_IPV4_ONLY
171     server_in.sin_family      = AF_INET;               /* IPv4 only */
172     server_in.sin_addr.s_addr = htonl(INADDR_ANY);     /* bind to any address */
173     server_in.sin_port        = htons((uint16_t)port); /* port to bind to */
174 #else
175     server_in.sin6_family = AF_INET6;              /* IPv6 (and IPv4) */
176     server_in.sin6_addr   = in6addr_any;           /* bind to any address */
177     server_in.sin6_port   = htons((uint16_t)port); /* port to bind to */
178 #endif
179     if (bind(server_socket, (struct sockaddr *)&server_in,
180                             sizeof(server_in)) != 0) {
181         perror("bind()");
182         return EXIT_FAILURE;
183     }
184     /* And accept connections. */
185     if (listen(server_socket, 5) != 0) {
186         perror("listen()");
187         return EXIT_FAILURE;
188     }
189
190     if (global_log_level >= LOG_DEBUG1_LEVEL) {
191         printf("tlsproxy %s\n", VERSION);
192         printf("Listening for connections on port %d.\n", port);
193
194         if (global_proxy_host != NULL && global_proxy_port != NULL) {
195             printf("Using proxy: %s:%s.\n", global_proxy_host,
196                                             global_proxy_port);
197         }
198     }
199
200     while (!done) {
201         /* Accept new connection. */
202         client_socket = accept(server_socket, NULL, NULL);
203         if (client_socket < 0) {
204             perror("accept()");
205             break;
206         }
207
208         /* No lock necessary, we only have one producer! */
209         P(ringbuffer_free);
210         ringbuffer[ringbuffer_write] = client_socket;
211         ringbuffer_write = (ringbuffer_write + 1) % RINGBUFFER_SIZE;
212         V(ringbuffer_full);
213     }
214
215     close(server_socket);
216
217     /* Poison all threads and shut them down. */
218     for (i = 0; i < thread_count; i++) {
219         P(ringbuffer_free);
220         ringbuffer[ringbuffer_write] = -1; /* poison */
221         ringbuffer_write = (ringbuffer_write + 1) % RINGBUFFER_SIZE;
222         V(ringbuffer_full);
223     }
224     for (i = 0; i < thread_count; i++) {
225         errno = pthread_join(threads[i], NULL);
226         if (errno != 0) {
227             perror("pthread_join()");
228         }
229     }
230
231     sem_del(ringbuffer_full);
232     sem_del(ringbuffer_free);
233     sem_del(ringbuffer_lock);
234
235     free(threads);
236
237     deinitialize_gnutls();
238
239     free(global_proxy_host);
240     free(global_proxy_port);
241
242     return EXIT_FAILURE;
243 }
244
245 #ifdef DEBUG
246 static void sigint_handler(int signal_number) {
247     (void)signal_number;
248
249     done = 1;
250 }
251 #endif
252
253 static void parse_arguments(int argc, char **argv) {
254     int option;
255
256     /* Default values. */
257     thread_count = 10;
258 #ifdef DEBUG
259     global_log_level = LOG_DEBUG_LEVEL;
260 #else
261     global_log_level = LOG_WARNING_LEVEL;
262 #endif
263     global_passthrough_unknown = 0;
264
265     while ((option = getopt(argc, argv, "a:d:p:t:uh?")) != -1) {
266         switch (option) {
267             case 'a': {
268                 http_digest_authorization = slurp_file(optarg);
269                 if (http_digest_authorization == NULL) {
270                     fprintf(stderr, "failed to open authorization file '%s': ",
271                                     optarg);
272                     perror("");
273                     exit(EXIT_FAILURE);
274                 } else if (strlen(http_digest_authorization) == 0) {
275                     fprintf(stderr, "empty authorization file '%s'\n",
276                                     optarg);
277                     exit(EXIT_FAILURE);
278                 }
279
280                 /* Just in case the file has a trailing newline. */
281                 strtok(http_digest_authorization, "\r\n");
282
283                 break;
284             }
285             case 'd': {
286                 global_log_level = atoi(optarg);
287                 if (global_log_level < 0) {
288                     fprintf(stderr, "-d positive number required: '%s'\n",
289                                     optarg);
290                     exit(EXIT_FAILURE);
291                 }
292                 break;
293             }
294             case 'p': {
295                 char *position;
296
297                 /* -p must have the format host:port. */
298                 if ((position = strchr(optarg, ':')) == NULL
299                         || optarg == position
300                         || strlen(position + 1) == 0
301                         || atoi(position + 1) <= 0
302                         || atoi(position + 1) > 0xffff) {
303                     fprintf(stderr, "invalid -p: '%s', format host:port\n",
304                                     optarg);
305                     exit(EXIT_FAILURE);
306                 }
307
308                 global_proxy_host = malloc((size_t)(position - optarg) + 1);
309                 if (global_proxy_host == NULL) {
310                     perror("malloc()");
311                     exit(EXIT_FAILURE);
312                 }
313                 memcpy(global_proxy_host, optarg, (size_t)(position - optarg));
314                 global_proxy_host[position - optarg] = '\0';
315
316                 global_proxy_port = malloc(strlen(position + 1) + 1);
317                 if (global_proxy_port == NULL) {
318                     perror("malloc()");
319                     exit(EXIT_FAILURE);
320                 }
321                 strcpy(global_proxy_port, position + 1);
322
323                 break;
324             }
325             case 't': {
326                 if (atoi(optarg) <= 0) {
327                     fprintf(stderr, "-t positive number required: '%s'\n",
328                                     optarg);
329                     exit(EXIT_FAILURE);
330                 }
331                 thread_count = (size_t)atoi(optarg);
332                 break;
333             }
334             case 'u': {
335                 global_passthrough_unknown = 1;
336                 break;
337             }
338             case 'h':
339             default: /* '?' */
340                 print_usage(argv[0]);
341                 exit(EXIT_FAILURE);
342         }
343     }
344
345     if (optind >= argc) {
346         fprintf(stderr, "port missing\n");
347         exit(EXIT_FAILURE);
348     }
349 }
350 static void print_usage(const char *argv) {
351     fprintf(stderr, "tlsproxy %s, a certificate checking TLS proxy\n",
352                     VERSION);
353     fprintf(stderr, "Usage: %s [-a file] [-d level] [-p host:port] [-t count] [-u] port\n",
354                     argv);
355     fprintf(stderr, "\n");
356     fprintf(stderr, "-a digest authentication file [default: none]\n");
357     fprintf(stderr, "-d debug level: 0=errors only, 2=debug [default: 1]\n");
358     fprintf(stderr, "-p proxy hostname and port\n");
359     fprintf(stderr, "-t number of threads [default: 10]\n");
360     fprintf(stderr, "-u passthrough connection if no certificate is stored \
361 [default: error]\n");
362     fprintf(stderr, "   WARNING: might be a security problem!\n");
363 }
364
365 static void initialize_gnutls(void) {
366     int result;
367     gcry_error_t error;
368
369     /* Thread safe setup. Must be called before gnutls_global_init(). */
370     error = gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
371     if (error != 0) {
372         fprintf(stderr, "gcry_control(): %s/%s\n", gcry_strsource(error),
373                                                    gcry_strerror(error));
374         exit(EXIT_FAILURE);
375     }
376     /* Prevent usage of blocking /dev/random. */
377     error = gcry_control(GCRYCTL_ENABLE_QUICK_RANDOM, 0);
378     if (error != 0) {
379         fprintf(stderr, "gcry_control(): %s/%s\n", gcry_strsource(error),
380                                                    gcry_strerror(error));
381         exit(EXIT_FAILURE);
382     }
383
384     /* Initialize GnuTLS. */
385     result = gnutls_global_init();
386     GNUTLS_ERROR_EXIT(result, "gnutls_global_init()");
387
388     /* Setup GnuTLS cipher suites. */
389     result = gnutls_priority_init(&global_tls_priority_cache, "NORMAL", NULL);
390     GNUTLS_ERROR_EXIT(result, "gnutls_priority_init()");
391
392     /* Generate Diffie-Hellman parameters. */
393     result = gnutls_dh_params_init(&global_tls_dh_params);
394     GNUTLS_ERROR_EXIT(result, "gnutls_dh_params_init()");
395     result = gnutls_dh_params_generate2(global_tls_dh_params, DH_SIZE);
396     GNUTLS_ERROR_EXIT(result, "gnutls_dh_params_generate2()");
397 }
398 static void deinitialize_gnutls(void) {
399     gnutls_dh_params_deinit(global_tls_dh_params);
400     gnutls_priority_deinit(global_tls_priority_cache);
401
402     gnutls_global_deinit();
403 }
404
405 static void *worker_thread(void *unused) {
406     int client_socket;
407
408     (void)unused;
409
410     for (;;) {
411         /* Get next element from ring buffer. */
412         P(ringbuffer_full);
413         P(ringbuffer_lock);
414         client_socket = ringbuffer[ringbuffer_read];
415         ringbuffer_read = (ringbuffer_read + 1) % RINGBUFFER_SIZE;
416         V(ringbuffer_lock);
417         V(ringbuffer_free);
418
419         /* Negative value indicates we should shut down our thread. */
420         if (client_socket < 0) {
421             break;
422         }
423
424         handle_connection(client_socket);
425     }
426
427     return NULL;
428 }
429
430 static char *slurp_file(const char *path) {
431     struct stat stat;
432     size_t size_read;
433     char *content = NULL;
434
435     FILE *file = fopen(path, "r");
436     if (file == NULL) {
437         return NULL;
438     }
439
440     ct_assert(sizeof(stat.st_size) <= sizeof(size_t));
441
442     if (fstat(fileno(file), &stat) != 0) {
443         goto out;
444     }
445     if (stat.st_size < 0) { /* just in case ... */
446         abort();
447     } else if ((size_t)stat.st_size >= SIZE_MAX - 1) {
448         errno = 0;
449         goto out;
450     }
451
452     content = malloc((size_t)stat.st_size + 1);
453     if (content == NULL) {
454         goto out;
455     }
456
457     errno = 0;
458     size_read = fread(content, 1, (size_t)stat.st_size, file);
459     if (size_read != (size_t)stat.st_size) {
460         free(content);
461         content = NULL;
462         goto out;
463     }
464     content[size_read] = '\0';
465
466 out:
467     fclose(file);
468
469     return content;
470 }