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