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