]> ruderich.org/simon Gitweb - tlsproxy/tlsproxy.git/blob - src/tlsproxy.c
Minor documentation updates.
[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/types.h>
32 #include <unistd.h>
33
34 /* Necessary for GnuTLS when used with threads. */
35 #include <gcrypt.h>
36 GCRY_THREAD_OPTION_PTHREAD_IMPL;
37
38
39 /* Size of ringbuffer. */
40 #define RINGBUFFER_SIZE 10
41
42 /* Bit size of Diffie-Hellman key exchange parameters. */
43 #define DH_SIZE 1024
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
76 static void initialize_gnutls(void);
77 static void deinitialize_gnutls(void);
78
79 static void worker_thread(void);
80
81
82 int main(int argc, char **argv) {
83     int port;
84     int client_socket, server_socket;
85 #ifdef USE_IPV4_ONLY
86     struct sockaddr_in server_in;
87 #else
88     struct sockaddr_in6 server_in;
89 #endif
90
91     size_t i;
92     pthread_t *threads;
93
94     struct sigaction action;
95
96     parse_arguments(argc, argv);
97
98     port = atoi(argv[argc - 1]);
99     if (port <= 0 || port > 0xffff ) {
100         print_usage(argv[0]);
101         fprintf(stderr, "\ninvalid port: '%s'\n", argv[argc - 1]);
102         return EXIT_FAILURE;
103     }
104
105     sigemptyset(&action.sa_mask);
106     action.sa_flags   = 0;
107 #ifdef DEBUG
108     /* Setup our SIGINT signal handler which allows a "normal" termination of
109      * the server in DEBUG mode. */
110     action.sa_handler = sigint_handler;
111     sigaction(SIGINT, &action, NULL);
112 #endif
113     /* Ignore SIGPIPEs. */
114     action.sa_handler = SIG_IGN;
115     sigaction(SIGPIPE, &action, NULL);
116
117     /* Initialize ring buffer. */
118     ringbuffer_read  = 0;
119     ringbuffer_write = 0;
120     ringbuffer_full  = sem_init(0);
121     ringbuffer_free  = sem_init(RINGBUFFER_SIZE);
122     ringbuffer_lock  = sem_init(1);
123     if (NULL == ringbuffer_full
124             || NULL == ringbuffer_free
125             || NULL == ringbuffer_lock) {
126         perror("sem_init()");
127         return EXIT_FAILURE;
128     }
129
130     initialize_gnutls();
131
132     /* Spawn worker threads to handle requests. */
133     threads = malloc(thread_count * sizeof(*threads));
134     if (threads == NULL) {
135         perror("thread malloc failed");
136         return EXIT_FAILURE;
137     }
138     for (i = 0; i < thread_count; i++) {
139         int result;
140         pthread_t thread;
141
142         result = pthread_create(&thread, NULL,
143                                 (void * (*)(void *))&worker_thread,
144                                 NULL);
145         if (result != 0) {
146             fprintf(stderr, "failed to create worker thread: %s\n",
147                             strerror(result));
148             return EXIT_FAILURE;
149         }
150
151         threads[i] = thread;
152     }
153
154 #ifdef USE_IPV4_ONLY
155     server_socket = socket(PF_INET, SOCK_STREAM, 0);
156 #else
157     server_socket = socket(PF_INET6, SOCK_STREAM, 0);
158 #endif
159     if (server_socket == -1) {
160         perror("socket()");
161         return EXIT_FAILURE;
162     }
163
164     /* Fast rebinding for debug mode, could cause invalid packets. */
165     if (global_log_level >= LOG_DEBUG_LEVEL) {
166         int socket_option = 1;
167         setsockopt(server_socket, SOL_SOCKET, SO_REUSEADDR,
168                    &socket_option, sizeof(socket_option));
169     }
170
171     /* Bind to the listen socket. */
172     memset(&server_in, 0, sizeof(server_in));
173 #ifdef USE_IPV4_ONLY
174     server_in.sin_family      = AF_INET;               /* IPv4 only */
175     server_in.sin_addr.s_addr = htonl(INADDR_ANY);     /* bind to any address */
176     server_in.sin_port        = htons((uint16_t)port); /* port to bind to */
177 #else
178     server_in.sin6_family = AF_INET6;              /* IPv6 (and IPv4) */
179     server_in.sin6_addr   = in6addr_any;           /* bind to any address */
180     server_in.sin6_port   = htons((uint16_t)port); /* port to bind to */
181 #endif
182     if (bind(server_socket, (struct sockaddr *)&server_in,
183                             sizeof(server_in)) == -1) {
184         perror("bind()");
185         return EXIT_FAILURE;
186     }
187     /* And accept connections. */
188     if (listen(server_socket, 5) == -1) {
189         perror("listen()");
190         return EXIT_FAILURE;
191     }
192
193     if (global_log_level >= LOG_DEBUG_LEVEL) {
194         printf("tlsproxy %s\n", VERSION);
195         printf("Listening for connections on port %d.\n", port);
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 == -1) {
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     free(ringbuffer_full);
235     free(ringbuffer_free);
236     free(ringbuffer_lock);
237
238     free(threads);
239
240     deinitialize_gnutls();
241
242     free(global_proxy_host);
243     free(global_proxy_port);
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_DEBUG_LEVEL;
263 #else
264     global_log_level = LOG_WARNING_LEVEL;
265 #endif
266     global_passthrough_unknown = 0;
267
268     while ((option = getopt(argc, argv, "d:p:t:uh?")) != -1) {
269         switch (option) {
270             case 'd': {
271                 if (atoi(optarg) < 0) {
272                     print_usage(argv[0]);
273                     fprintf(stderr, "\n-d positive number required: '%s'\n",
274                                     optarg);
275                     exit(EXIT_FAILURE);
276                 }
277                 global_log_level = atoi(optarg);
278                 break;
279             }
280             case 'p': {
281                 char *position;
282
283                 /* -p must have the format host:port. */
284                 if ((position = strchr(optarg, ':')) == NULL
285                         || optarg == position
286                         || strlen(position + 1) == 0
287                         || atoi(position + 1) <= 0
288                         || atoi(position + 1) > 0xffff) {
289                     print_usage(argv[0]);
290                     fprintf(stderr, "\ninvalid -p: '%s', format host:port\n",
291                             optarg);
292                     exit(EXIT_FAILURE);
293                 }
294
295                 global_proxy_host = malloc((size_t)(position - optarg) + 1);
296                 if (global_proxy_host == NULL) {
297                     perror("malloc()");
298                     exit(EXIT_FAILURE);
299                 }
300                 memcpy(global_proxy_host, optarg, (size_t)(position - optarg));
301                 global_proxy_host[position - optarg] = '\0';
302
303                 global_proxy_port = malloc(strlen(position + 1) + 1);
304                 if (global_proxy_port == NULL) {
305                     perror("malloc()");
306                     exit(EXIT_FAILURE);
307                 }
308                 strcpy(global_proxy_port, position + 1);
309
310                 break;
311             }
312             case 't': {
313                 if (atoi(optarg) <= 0) {
314                     print_usage(argv[0]);
315                     fprintf(stderr, "\n-t positive number required: '%s'\n",
316                                     optarg);
317                     exit(EXIT_FAILURE);
318                 }
319                 thread_count = (size_t)atoi(optarg);
320                 break;
321             }
322             case 'u': {
323                 global_passthrough_unknown = 1;
324                 break;
325             }
326             case 'h':
327             default: /* '?' */
328                 print_usage(argv[0]);
329                 exit(EXIT_FAILURE);
330         }
331     }
332
333     if (optind >= argc) {
334         print_usage(argv[0]);
335         fprintf(stderr, "\nport missing\n");
336         exit(EXIT_FAILURE);
337     }
338 }
339 static void print_usage(const char *argv) {
340     fprintf(stderr, "tlsproxy %s, a certificate checking TLS proxy\n",
341                     VERSION);
342     fprintf(stderr, "Usage: %s [-d level] [-p host:port] [-t count] [-u] port\n",
343                     argv);
344     fprintf(stderr, "\n");
345     fprintf(stderr, "-d debug level: 0=errors only, 2=debug [default: 1]\n");
346     fprintf(stderr, "-p proxy hostname and port\n");
347     fprintf(stderr, "-t number of threads [default: 10]\n");
348     fprintf(stderr, "-u passthrough connection if no certificate is stored \
349 [default: error]\n");
350     fprintf(stderr, "   WARNING: might be a security problem!\n");
351 }
352
353 static void initialize_gnutls(void) {
354     int result;
355     gcry_error_t error = 0;
356
357     /* Thread safe setup. Must be called before gnutls_global_init(). */
358     error = gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
359     if (error) {
360         fprintf(stderr, "gcry_control(): %s/%s\n", gcry_strsource(error),
361                                                    gcry_strerror(error));
362         exit(EXIT_FAILURE);
363     }
364     /* Prevent usage of blocking /dev/random. */
365     error = gcry_control(GCRYCTL_ENABLE_QUICK_RANDOM, 0);
366     if (error) {
367         fprintf(stderr, "gcry_control(): %s/%s\n", gcry_strsource(error),
368                                                    gcry_strerror(error));
369         exit(EXIT_FAILURE);
370     }
371
372     /* Initialize GnuTLS. */
373     result = gnutls_global_init();
374     GNUTLS_ERROR_EXIT(result, "gnutls_global_init()");
375
376     /* Setup GnuTLS cipher suites. */
377     result = gnutls_priority_init(&global_tls_priority_cache, "NORMAL", NULL);
378     GNUTLS_ERROR_EXIT(result, "gnutls_priority_init()");
379
380     /* Generate Diffie-Hellman parameters. */
381     result = gnutls_dh_params_init(&global_tls_dh_params);
382     GNUTLS_ERROR_EXIT(result, "gnutls_dh_params_init()");
383     result = gnutls_dh_params_generate2(global_tls_dh_params, DH_SIZE);
384     GNUTLS_ERROR_EXIT(result, "gnutls_dh_params_generate2()");
385 }
386 static void deinitialize_gnutls(void) {
387     gnutls_dh_params_deinit(global_tls_dh_params);
388     gnutls_priority_deinit(global_tls_priority_cache);
389
390     gnutls_global_deinit();
391 }
392
393 static void worker_thread(void) {
394     int client_socket;
395
396     for (;;) {
397         /* Get next element from ring buffer. */
398         P(ringbuffer_full);
399         P(ringbuffer_lock);
400         client_socket = ringbuffer[ringbuffer_read];
401         ringbuffer_read = (ringbuffer_read + 1) % RINGBUFFER_SIZE;
402         V(ringbuffer_lock);
403         V(ringbuffer_free);
404
405         /* Negative value indicates we should shut down our thread. */
406         if (client_socket < 0) {
407             break;
408         }
409
410         handle_connection(client_socket);
411     }
412 }