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