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