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