]> ruderich.org/simon Gitweb - tlsproxy/tlsproxy.git/blob - src/tlsproxy.c
Use better readable order of arguments in if.
[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 /* 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 (error != GNUTLS_E_SUCCESS) { \
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 = 0;
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 #ifdef USE_IPV4_ONLY
93     struct sockaddr_in server_in;
94 #else
95     struct sockaddr_in6 server_in;
96 #endif
97
98     size_t i;
99     pthread_t *threads;
100
101     struct sigaction action;
102
103     parse_arguments(argc, argv);
104
105     port = atoi(argv[argc - 1]);
106     if (port <= 0 || port > 0xffff ) {
107         print_usage(argv[0]);
108         fprintf(stderr, "\ninvalid port: '%s'\n", argv[argc - 1]);
109         return EXIT_FAILURE;
110     }
111
112     sigemptyset(&action.sa_mask);
113     action.sa_flags   = 0;
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         int result;
147         pthread_t thread;
148
149         result = pthread_create(&thread, NULL,
150                                 (void * (*)(void *))&worker_thread,
151                                 NULL);
152         if (result != 0) {
153             fprintf(stderr, "failed to create worker thread: %s\n",
154                             strerror(result));
155             return EXIT_FAILURE;
156         }
157
158         threads[i] = thread;
159     }
160
161 #ifdef USE_IPV4_ONLY
162     server_socket = socket(PF_INET, SOCK_STREAM, 0);
163 #else
164     server_socket = socket(PF_INET6, SOCK_STREAM, 0);
165 #endif
166     if (server_socket == -1) {
167         perror("socket()");
168         return EXIT_FAILURE;
169     }
170
171     /* Fast rebinding for debug mode, could cause invalid packets. */
172     if (global_log_level >= LOG_DEBUG_LEVEL) {
173         int socket_option = 1;
174         setsockopt(server_socket, SOL_SOCKET, SO_REUSEADDR,
175                    &socket_option, sizeof(socket_option));
176     }
177
178     /* Bind to the listen socket. */
179     memset(&server_in, 0, sizeof(server_in));
180 #ifdef USE_IPV4_ONLY
181     server_in.sin_family      = AF_INET;               /* IPv4 only */
182     server_in.sin_addr.s_addr = htonl(INADDR_ANY);     /* bind to any address */
183     server_in.sin_port        = htons((uint16_t)port); /* port to bind to */
184 #else
185     server_in.sin6_family = AF_INET6;              /* IPv6 (and IPv4) */
186     server_in.sin6_addr   = in6addr_any;           /* bind to any address */
187     server_in.sin6_port   = htons((uint16_t)port); /* port to bind to */
188 #endif
189     if (bind(server_socket, (struct sockaddr *)&server_in,
190                             sizeof(server_in)) == -1) {
191         perror("bind()");
192         return EXIT_FAILURE;
193     }
194     /* And accept connections. */
195     if (listen(server_socket, 5) == -1) {
196         perror("listen()");
197         return EXIT_FAILURE;
198     }
199
200     if (global_log_level >= LOG_DEBUG_LEVEL) {
201         printf("tlsproxy %s\n", VERSION);
202         printf("Listening for connections on port %d.\n", port);
203
204         if (global_proxy_host != NULL && global_proxy_port != NULL) {
205             printf("Using proxy: %s:%s.\n", global_proxy_host,
206                                             global_proxy_port);
207         }
208     }
209
210     while (!done) {
211         /* Accept new connection. */
212         client_socket = accept(server_socket, NULL, NULL);
213         if (client_socket == -1) {
214             perror("accept()");
215             break;
216         }
217
218         /* No lock necessary, we only have one producer! */
219         P(ringbuffer_free);
220         ringbuffer[ringbuffer_write] = client_socket;
221         ringbuffer_write = (ringbuffer_write + 1) % RINGBUFFER_SIZE;
222         V(ringbuffer_full);
223     }
224
225     close(server_socket);
226
227     /* Poison all threads and shut them down. */
228     for (i = 0; i < thread_count; i++) {
229         P(ringbuffer_free);
230         ringbuffer[ringbuffer_write] = -1; /* poison */
231         ringbuffer_write = (ringbuffer_write + 1) % RINGBUFFER_SIZE;
232         V(ringbuffer_full);
233     }
234     for (i = 0; i < thread_count; i++) {
235         errno = pthread_join(threads[i], NULL);
236         if (errno != 0) {
237             perror("pthread_join()");
238         }
239     }
240
241     free(ringbuffer_full);
242     free(ringbuffer_free);
243     free(ringbuffer_lock);
244
245     free(threads);
246
247     deinitialize_gnutls();
248
249     free(global_proxy_host);
250     free(global_proxy_port);
251
252     return EXIT_FAILURE;
253 }
254
255 #ifdef DEBUG
256 static void sigint_handler(int signal_number) {
257     (void)signal_number;
258
259     done = 1;
260 }
261 #endif
262
263 static void parse_arguments(int argc, char **argv) {
264     int option;
265
266     /* Default values. */
267     thread_count = 10;
268 #ifdef DEBUG
269     global_log_level = LOG_DEBUG_LEVEL;
270 #else
271     global_log_level = LOG_WARNING_LEVEL;
272 #endif
273     global_passthrough_unknown = 0;
274
275     while ((option = getopt(argc, argv, "d:p:t:uh?")) != -1) {
276         switch (option) {
277             case 'd': {
278                 if (atoi(optarg) < 0) {
279                     print_usage(argv[0]);
280                     fprintf(stderr, "\n-d positive number required: '%s'\n",
281                                     optarg);
282                     exit(EXIT_FAILURE);
283                 }
284                 global_log_level = atoi(optarg);
285                 break;
286             }
287             case 'p': {
288                 char *position;
289
290                 /* -p must have the format host:port. */
291                 if ((position = strchr(optarg, ':')) == NULL
292                         || optarg == position
293                         || strlen(position + 1) == 0
294                         || atoi(position + 1) <= 0
295                         || atoi(position + 1) > 0xffff) {
296                     print_usage(argv[0]);
297                     fprintf(stderr, "\ninvalid -p: '%s', format host:port\n",
298                             optarg);
299                     exit(EXIT_FAILURE);
300                 }
301
302                 global_proxy_host = malloc((size_t)(position - optarg) + 1);
303                 if (global_proxy_host == NULL) {
304                     perror("malloc()");
305                     exit(EXIT_FAILURE);
306                 }
307                 memcpy(global_proxy_host, optarg, (size_t)(position - optarg));
308                 global_proxy_host[position - optarg] = '\0';
309
310                 global_proxy_port = malloc(strlen(position + 1) + 1);
311                 if (global_proxy_port == NULL) {
312                     perror("malloc()");
313                     exit(EXIT_FAILURE);
314                 }
315                 strcpy(global_proxy_port, position + 1);
316
317                 break;
318             }
319             case 't': {
320                 if (atoi(optarg) <= 0) {
321                     print_usage(argv[0]);
322                     fprintf(stderr, "\n-t positive number required: '%s'\n",
323                                     optarg);
324                     exit(EXIT_FAILURE);
325                 }
326                 thread_count = (size_t)atoi(optarg);
327                 break;
328             }
329             case 'u': {
330                 global_passthrough_unknown = 1;
331                 break;
332             }
333             case 'h':
334             default: /* '?' */
335                 print_usage(argv[0]);
336                 exit(EXIT_FAILURE);
337         }
338     }
339
340     if (optind >= argc) {
341         print_usage(argv[0]);
342         fprintf(stderr, "\nport missing\n");
343         exit(EXIT_FAILURE);
344     }
345 }
346 static void print_usage(const char *argv) {
347     fprintf(stderr, "tlsproxy %s, a certificate checking TLS proxy\n",
348                     VERSION);
349     fprintf(stderr, "Usage: %s [-d level] [-p host:port] [-t count] [-u] port\n",
350                     argv);
351     fprintf(stderr, "\n");
352     fprintf(stderr, "-d debug level: 0=errors only, 2=debug [default: 1]\n");
353     fprintf(stderr, "-p proxy hostname and port\n");
354     fprintf(stderr, "-t number of threads [default: 10]\n");
355     fprintf(stderr, "-u passthrough connection if no certificate is stored \
356 [default: error]\n");
357     fprintf(stderr, "   WARNING: might be a security problem!\n");
358 }
359
360 static void initialize_gnutls(void) {
361     int result;
362     gcry_error_t error = 0;
363
364     /* Thread safe setup. Must be called before gnutls_global_init(). */
365     error = gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
366     if (error) {
367         fprintf(stderr, "gcry_control(): %s/%s\n", gcry_strsource(error),
368                                                    gcry_strerror(error));
369         exit(EXIT_FAILURE);
370     }
371     /* Prevent usage of blocking /dev/random. */
372     error = gcry_control(GCRYCTL_ENABLE_QUICK_RANDOM, 0);
373     if (error) {
374         fprintf(stderr, "gcry_control(): %s/%s\n", gcry_strsource(error),
375                                                    gcry_strerror(error));
376         exit(EXIT_FAILURE);
377     }
378
379     /* Initialize GnuTLS. */
380     result = gnutls_global_init();
381     GNUTLS_ERROR_EXIT(result, "gnutls_global_init()");
382
383     /* Setup GnuTLS cipher suites. */
384     result = gnutls_priority_init(&global_tls_priority_cache, "NORMAL", NULL);
385     GNUTLS_ERROR_EXIT(result, "gnutls_priority_init()");
386
387     /* Generate Diffie-Hellman parameters. */
388     result = gnutls_dh_params_init(&global_tls_dh_params);
389     GNUTLS_ERROR_EXIT(result, "gnutls_dh_params_init()");
390     result = gnutls_dh_params_generate2(global_tls_dh_params, DH_SIZE);
391     GNUTLS_ERROR_EXIT(result, "gnutls_dh_params_generate2()");
392 }
393 static void deinitialize_gnutls(void) {
394     gnutls_dh_params_deinit(global_tls_dh_params);
395     gnutls_priority_deinit(global_tls_priority_cache);
396
397     gnutls_global_deinit();
398 }
399
400 static void worker_thread(void) {
401     int client_socket;
402
403     for (;;) {
404         /* Get next element from ring buffer. */
405         P(ringbuffer_full);
406         P(ringbuffer_lock);
407         client_socket = ringbuffer[ringbuffer_read];
408         ringbuffer_read = (ringbuffer_read + 1) % RINGBUFFER_SIZE;
409         V(ringbuffer_lock);
410         V(ringbuffer_free);
411
412         /* Negative value indicates we should shut down our thread. */
413         if (client_socket < 0) {
414             break;
415         }
416
417         handle_connection(client_socket);
418     }
419 }