]> ruderich.org/simon Gitweb - tlsproxy/tlsproxy.git/blob - src/tlsproxy.c
src/tlsproxy.c: Only handle SIGINT in DEBUG mode.
[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  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 /* socket(), bind(), accept(), listen() */
27 #include <sys/types.h>
28 #include <sys/socket.h>
29 /* close() */
30 #include <unistd.h>
31 /* htons() */
32 #include <arpa/inet.h>
33 /* sigaction() */
34 #include <signal.h>
35 /* errno */
36 #include <errno.h>
37 /* pthread_*() */
38 #include <pthread.h>
39
40 /* For GnuTLS. */
41 #include <gcrypt.h>
42
43 GCRY_THREAD_OPTION_PTHREAD_IMPL;
44
45
46 /* Size of ringbuffer. */
47 #define RINGBUFFER_SIZE 10
48
49 /* Bit size of Diffie-Hellman key exchange parameters. */
50 #define DH_SIZE 1024
51
52
53 /* For gnutls_*() functions. */
54 #define GNUTLS_ERROR_EXIT(error, message) \
55     if (GNUTLS_E_SUCCESS != error) { \
56         fprintf(stderr, "%s: %s\n", message, gnutls_strerror(error)); \
57         exit(EXIT_FAILURE); \
58     }
59
60
61 /* Server should shut down. Set by SIGINT handler. */
62 static volatile int done;
63
64 /* Number of threads. */
65 static size_t thread_count;
66
67 /* Synchronized ring buffer storing accept()ed client sockets. */
68 static int ringbuffer[RINGBUFFER_SIZE];
69 static int ringbuffer_read;
70 static int ringbuffer_write;
71 static SEM *ringbuffer_full; /* At least one element in the buffer? */
72 static SEM *ringbuffer_free; /* Space for another element in the buffer? */
73 static SEM *ringbuffer_lock; /* Read lock. */
74
75
76 #ifdef DEBUG
77 static void sigint_handler(int signal);
78 #endif
79
80 static void parse_arguments(int argc, char **argv);
81 static void print_usage(const char *argv);
82
83 static void initialize_gnutls(void);
84 static void deinitialize_gnutls(void);
85
86 static void worker_thread(void);
87
88
89 int main(int argc, char **argv) {
90     int port;
91     int client_socket, server_socket;
92     struct sockaddr_in6 server_in;
93
94     size_t i;
95     pthread_t *threads;
96
97     struct sigaction action;
98
99     parse_arguments(argc, argv);
100
101     port = atoi(argv[argc - 1]);
102     if (0 >= port || 0xffff < port) {
103         print_usage(argv[0]);
104         fprintf(stderr, "\ninvalid port\n");
105         return EXIT_FAILURE;
106     }
107
108     /* Setup our SIGINT signal handler which allows a "normal" termination of
109      * the server in DEBUG mode. */
110     sigemptyset(&action.sa_mask);
111     action.sa_flags   = 0;
112 #ifdef DEBUG
113     action.sa_handler = sigint_handler;
114     sigaction(SIGINT, &action, NULL);
115 #endif
116     /* Ignore SIGPIPEs. */
117     action.sa_handler = SIG_IGN;
118     sigaction(SIGPIPE, &action, NULL);
119
120     /* Initialize ring buffer. */
121     ringbuffer_read  = 0;
122     ringbuffer_write = 0;
123     ringbuffer_full  = sem_init(0);
124     ringbuffer_free  = sem_init(RINGBUFFER_SIZE);
125     ringbuffer_lock  = sem_init(1);
126     if (NULL == ringbuffer_full
127             || NULL == ringbuffer_free
128             || NULL == ringbuffer_lock) {
129         perror("sem_init()");
130         return EXIT_FAILURE;
131     }
132
133     initialize_gnutls();
134
135     /* Spawn worker threads to handle requests. */
136     threads = (pthread_t *)malloc(thread_count * sizeof(pthread_t));
137     if (NULL == threads) {
138         perror("thread malloc failed");
139         return EXIT_FAILURE;
140     }
141     for (i = 0; i < thread_count; i++) {
142         int result;
143         pthread_t thread;
144
145         result = pthread_create(&thread, NULL,
146                                 (void * (*)(void *))&worker_thread,
147                                 NULL);
148         if (0 != result) {
149             fprintf(stderr, "failed to create worker thread: %s\n",
150                             strerror(result));
151             return EXIT_FAILURE;
152         }
153
154         threads[i] = thread;
155     }
156
157     server_socket = socket(PF_INET6, SOCK_STREAM, 0);
158     if (-1 == server_socket) {
159         perror("socket()");
160         return EXIT_FAILURE;
161     }
162
163 #ifdef DEBUG
164     /* Fast rebinding for debug mode, could cause invalid packets. */
165     {
166         int socket_option = 1;
167         setsockopt(server_socket, SOL_SOCKET, SO_REUSEADDR,
168                    &socket_option, sizeof(socket_option));
169     }
170 #endif
171
172     /* Bind to the listen socket. */
173     memset(&server_in, 0, sizeof(server_in));
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     if (-1 == bind(server_socket, (struct sockaddr *)&server_in,
178                                   sizeof(server_in))) {
179         perror("bind()");
180         return EXIT_FAILURE;
181     }
182     /* And accept connections. */
183     if (-1 == listen(server_socket, 5)) {
184         perror("listen()");
185         return EXIT_FAILURE;
186     }
187
188     if (LOG_DEBUG <= global_log_level) {
189         printf("Listening for connections on port %d.\n", port);
190
191         if (NULL != global_proxy_host && NULL != global_proxy_port) {
192             printf("Using proxy: %s:%s.\n", global_proxy_host,
193                                             global_proxy_port);
194         }
195     }
196
197     while (!done) {
198         /* Accept new connection. */
199         client_socket = accept(server_socket, NULL, NULL);
200         if (-1 == client_socket) {
201             perror("accept()");
202             break;
203         }
204
205         /* No lock, we only have one producer! */
206         P(ringbuffer_free);
207         ringbuffer[ringbuffer_write] = client_socket;
208         ringbuffer_write = (ringbuffer_write + 1) % RINGBUFFER_SIZE;
209         V(ringbuffer_full);
210     }
211
212     close(server_socket);
213
214     /* Poison all threads and shut them down. */
215     for (i = 0; i < thread_count; i++) {
216         P(ringbuffer_free);
217         ringbuffer[ringbuffer_write] = -1; /* poison */
218         ringbuffer_write = (ringbuffer_write + 1) % RINGBUFFER_SIZE;
219         V(ringbuffer_full);
220     }
221     for (i = 0; i < thread_count; i++) {
222         errno = pthread_join(threads[i], NULL);
223         if (0 != errno) {
224             perror("pthread_join()");
225             continue;
226         }
227     }
228
229     free(ringbuffer_full);
230     free(ringbuffer_free);
231     free(ringbuffer_lock);
232
233     free(threads);
234
235     deinitialize_gnutls();
236
237     free(global_proxy_host);
238     free(global_proxy_port);
239
240     return EXIT_FAILURE;
241 }
242
243 #ifdef DEBUG
244 static void sigint_handler(int signal_number) {
245     (void)signal_number;
246
247     done = 1;
248 }
249 #endif
250
251 static void parse_arguments(int argc, char **argv) {
252     int option;
253
254     /* Default values. */
255     thread_count = 10;
256 #ifdef DEBUG
257     global_log_level = LOG_DEBUG;
258 #else
259     global_log_level = LOG_WARNING;
260 #endif
261
262     while (-1 != (option = getopt(argc, argv, "d:p:t:h?"))) {
263         switch (option) {
264             case 'd': {
265                 if (0 > atoi(optarg)) {
266                     print_usage(argv[0]);
267                     fprintf(stderr, "\n-d positive number required\n");
268                     exit(EXIT_FAILURE);
269                 }
270                 global_log_level = atoi(optarg);
271                 break;
272             }
273             case 'p': {
274                 char *position;
275
276                 /* -p must have the format host:port. */
277                 if (NULL == (position = strchr(optarg, ':'))
278                         || position == optarg
279                         || 0 == strlen(position + 1)
280                         || 0 >= atoi(position + 1)
281                         || 0xffff < atoi(position + 1)) {
282                     print_usage(argv[0]);
283                     fprintf(stderr, "\ninvalid -p, format host:port\n");
284                     exit(EXIT_FAILURE);
285                 }
286
287                 global_proxy_host = malloc((size_t)(position - optarg) + 1);
288                 if (NULL == global_proxy_host) {
289                     perror("malloc()");
290                     exit(EXIT_FAILURE);
291                 }
292                 memcpy(global_proxy_host, optarg, (size_t)(position - optarg));
293                 global_proxy_host[position - optarg] = '\0';
294
295                 global_proxy_port = malloc(strlen(position + 1) + 1);
296                 if (NULL == global_proxy_port) {
297                     perror("malloc()");
298                     exit(EXIT_FAILURE);
299                 }
300                 strcpy(global_proxy_port, position + 1);
301
302                 break;
303             }
304             case 't': {
305                 if (0 >= atoi(optarg)) {
306                     print_usage(argv[0]);
307                     fprintf(stderr, "\n-t positive number required\n");
308                     exit(EXIT_FAILURE);
309                 }
310                 thread_count = (size_t)atoi(optarg);
311                 break;
312             }
313             case 'h':
314             default: /* '?' */
315                 print_usage(argv[0]);
316                 exit(EXIT_FAILURE);
317         }
318     }
319
320     if (optind >= argc) {
321         print_usage(argv[0]);
322         fprintf(stderr, "\nport missing\n");
323         exit(EXIT_FAILURE);
324     }
325 }
326 static void print_usage(const char *argv) {
327     fprintf(stderr, "Usage: %s [-d level] [-p host:port] [-t count] port\n",
328                     argv);
329     fprintf(stderr, "\n");
330     fprintf(stderr, "-d debug level: 0=errors only, 2=debug [default: 1]\n");
331     fprintf(stderr, "-p proxy hostname and port\n");
332     fprintf(stderr, "-t number of threads [default: 10]\n");
333 }
334
335 static void initialize_gnutls(void) {
336     int result;
337     gcry_error_t error = 0;
338
339     /* Thread safe setup. Must be called before gnutls_global_init(). */
340     error = gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
341     if (error) {
342         fprintf(stderr, "gcry_control(): %s/%s\n", gcry_strsource(error),
343                                                    gcry_strerror(error));
344         exit(EXIT_FAILURE);
345     }
346     /* Prevent usage of blocking /dev/random. */
347     error = gcry_control(GCRYCTL_ENABLE_QUICK_RANDOM, 0);
348     if (error) {
349         fprintf(stderr, "gcry_control(): %s/%s\n", gcry_strsource(error),
350                                                    gcry_strerror(error));
351         exit(EXIT_FAILURE);
352     }
353
354     /* Initialize GnuTLS. */
355     result = gnutls_global_init();
356     GNUTLS_ERROR_EXIT(result, "gnutls_global_init()");
357
358     /* Setup GnuTLS cipher suites. */
359     result = gnutls_priority_init(&tls_priority_cache, "NORMAL", NULL);
360     GNUTLS_ERROR_EXIT(result, "gnutls_priority_init()");
361
362     /* Generate Diffie-Hellman parameters. */
363     result = gnutls_dh_params_init(&tls_dh_params);
364     GNUTLS_ERROR_EXIT(result, "gnutls_dh_params_init()");
365     result = gnutls_dh_params_generate2(tls_dh_params, DH_SIZE);
366     GNUTLS_ERROR_EXIT(result, "gnutls_dh_params_generate2()");
367 }
368 static void deinitialize_gnutls(void) {
369     gnutls_dh_params_deinit(tls_dh_params);
370     gnutls_priority_deinit(tls_priority_cache);
371
372     gnutls_global_deinit();
373 }
374
375 static void worker_thread(void) {
376     int client_socket;
377
378     for (;;) {
379         /* Get next element from ring buffer. */
380         P(ringbuffer_full);
381         P(ringbuffer_lock);
382         client_socket = ringbuffer[ringbuffer_read];
383         ringbuffer_read = (ringbuffer_read + 1) % RINGBUFFER_SIZE;
384         V(ringbuffer_lock);
385         V(ringbuffer_free);
386
387         /* Negative value indicates we should shut down our thread. */
388         if (0 > client_socket) {
389             break;
390         }
391
392         handle_connection(client_socket);
393     }
394 }