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