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