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.
6 * Copyright (C) 2011-2013 Simon Ruderich
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.
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.
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/>.
24 #include "connection.h"
26 #include <arpa/inet.h>
30 #include <sys/socket.h>
32 #include <sys/types.h>
35 #if GNUTLS_VERSION_NUMBER <= 0x020b00
36 /* Necessary for GnuTLS when used with threads. */
38 GCRY_THREAD_OPTION_PTHREAD_IMPL;
42 /* Size of ringbuffer. */
43 #define RINGBUFFER_SIZE 10
45 /* Bit size of Diffie-Hellman key exchange parameters. */
49 /* For gnutls_*() functions. */
50 #define GNUTLS_ERROR_EXIT(error, message) \
51 if (error != GNUTLS_E_SUCCESS) { \
52 fprintf(stderr, "%s: %s\n", message, gnutls_strerror(error)); \
57 /* Server should shut down. Set by SIGINT handler. */
58 static volatile int done; /* = 0 */
60 /* Number of threads. */
61 static size_t thread_count;
63 /* Synchronized ring buffer storing accept()ed client sockets. */
64 static int ringbuffer[RINGBUFFER_SIZE];
65 static int ringbuffer_read;
66 static int ringbuffer_write;
67 static SEM *ringbuffer_full; /* At least one element in the buffer? */
68 static SEM *ringbuffer_free; /* Space for another element in the buffer? */
69 static SEM *ringbuffer_lock; /* Read lock. */
73 static void sigint_handler(int signal);
76 static void parse_arguments(int argc, char **argv);
77 static void print_usage(const char *argv);
78 static char *slurp_file(const char *path);
80 static void initialize_gnutls(void);
81 static void deinitialize_gnutls(void);
83 static void *worker_thread(void *unused);
86 int main(int argc, char **argv) {
88 int client_socket, server_socket;
90 struct sockaddr_in server_in;
92 struct sockaddr_in6 server_in;
98 struct sigaction action;
100 /* Required in a few places. */
101 ct_assert(sizeof(size_t) >= sizeof(int));
102 ct_assert(sizeof(size_t) >= sizeof(ssize_t));
104 parse_arguments(argc, argv);
106 port = atoi(argv[argc - 1]);
107 if (port <= 0 || port > 0xffff ) {
108 fprintf(stderr, "invalid port: '%s'\n", argv[argc - 1]);
112 memset(&action, 0, sizeof(action));
113 sigemptyset(&action.sa_mask);
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);
120 /* Ignore SIGPIPEs. */
121 action.sa_handler = SIG_IGN;
122 sigaction(SIGPIPE, &action, NULL);
124 /* Initialize ring buffer. */
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()");
139 /* Spawn worker threads to handle requests. */
140 threads = malloc(thread_count * sizeof(*threads));
141 if (threads == NULL) {
142 perror("thread malloc failed");
145 for (i = 0; i < thread_count; i++) {
146 errno = pthread_create(threads + i, NULL, &worker_thread, NULL);
148 perror("failed to create worker thread");
154 server_socket = socket(PF_INET, SOCK_STREAM, 0);
156 server_socket = socket(PF_INET6, SOCK_STREAM, 0);
158 if (server_socket < 0) {
163 /* Fast rebinding for debug mode, could cause invalid packets. */
164 if (global_log_level >= LOG_DEBUG1_LEVEL) {
165 int socket_option = 1;
166 setsockopt(server_socket, SOL_SOCKET, SO_REUSEADDR,
167 &socket_option, sizeof(socket_option));
170 /* Bind to the listen socket. */
171 memset(&server_in, 0, sizeof(server_in));
173 server_in.sin_family = AF_INET; /* IPv4 only */
174 server_in.sin_addr.s_addr = htonl(INADDR_ANY); /* bind to any address */
175 server_in.sin_port = htons((uint16_t)port); /* port to bind to */
177 server_in.sin6_family = AF_INET6; /* IPv6 (and IPv4) */
178 server_in.sin6_addr = in6addr_any; /* bind to any address */
179 server_in.sin6_port = htons((uint16_t)port); /* port to bind to */
181 if (bind(server_socket, (struct sockaddr *)&server_in,
182 sizeof(server_in)) != 0) {
186 /* And accept connections. */
187 if (listen(server_socket, 5) != 0) {
192 if (global_log_level >= LOG_DEBUG1_LEVEL) {
193 printf("tlsproxy %s\n", VERSION);
194 printf("Listening for connections on port %d.\n", port);
196 if (global_proxy_host != NULL && global_proxy_port != NULL) {
197 printf("Using proxy: %s:%s.\n", global_proxy_host,
203 /* Accept new connection. */
204 client_socket = accept(server_socket, NULL, NULL);
205 if (client_socket < 0) {
210 /* No lock necessary, we only have one producer! */
212 ringbuffer[ringbuffer_write] = client_socket;
213 ringbuffer_write = (ringbuffer_write + 1) % RINGBUFFER_SIZE;
217 close(server_socket);
219 /* Poison all threads and shut them down. */
220 for (i = 0; i < thread_count; i++) {
222 ringbuffer[ringbuffer_write] = -1; /* poison */
223 ringbuffer_write = (ringbuffer_write + 1) % RINGBUFFER_SIZE;
226 for (i = 0; i < thread_count; i++) {
227 errno = pthread_join(threads[i], NULL);
229 perror("pthread_join()");
233 sem_del(ringbuffer_full);
234 sem_del(ringbuffer_free);
235 sem_del(ringbuffer_lock);
239 deinitialize_gnutls();
241 free(global_proxy_host);
242 free(global_proxy_port);
248 static void sigint_handler(int signal_number) {
255 static void parse_arguments(int argc, char **argv) {
258 /* Default values. */
261 global_log_level = LOG_DEBUG1_LEVEL;
263 global_log_level = LOG_WARNING_LEVEL;
265 global_passthrough_unknown = 0;
267 while ((option = getopt(argc, argv, "a:d:p:t:uh?")) != -1) {
270 http_digest_authorization = slurp_file(optarg);
271 if (http_digest_authorization == NULL) {
272 fprintf(stderr, "failed to open authorization file '%s': ",
276 } else if (strlen(http_digest_authorization) == 0) {
277 fprintf(stderr, "empty authorization file '%s'\n",
282 /* Just in case the file has a trailing newline. */
283 strtok(http_digest_authorization, "\r\n");
288 global_log_level = atoi(optarg);
289 if (global_log_level < 0) {
290 fprintf(stderr, "-d positive number required: '%s'\n",
299 /* -p must have the format host:port. */
300 if ((position = strchr(optarg, ':')) == NULL
301 || optarg == position
302 || strlen(position + 1) == 0
303 || atoi(position + 1) <= 0
304 || atoi(position + 1) > 0xffff) {
305 fprintf(stderr, "invalid -p: '%s', format host:port\n",
310 global_proxy_host = malloc((size_t)(position - optarg) + 1);
311 if (global_proxy_host == NULL) {
315 memcpy(global_proxy_host, optarg, (size_t)(position - optarg));
316 global_proxy_host[position - optarg] = '\0';
318 global_proxy_port = malloc(strlen(position + 1) + 1);
319 if (global_proxy_port == NULL) {
323 strcpy(global_proxy_port, position + 1);
328 if (atoi(optarg) <= 0) {
329 fprintf(stderr, "-t positive number required: '%s'\n",
333 thread_count = (size_t)atoi(optarg);
337 global_passthrough_unknown = 1;
342 print_usage(argv[0]);
347 if (optind >= argc) {
348 fprintf(stderr, "port missing\n");
352 static void print_usage(const char *argv) {
353 fprintf(stderr, "tlsproxy %s, a certificate checking TLS proxy\n",
355 fprintf(stderr, "Usage: %s [-a file] [-d level] [-p host:port] [-t count] [-u] port\n",
357 fprintf(stderr, "\n");
358 fprintf(stderr, "-a digest authentication file [default: none]\n");
359 fprintf(stderr, "-d debug level: 0=errors only, 2=debug [default: 1]\n");
360 fprintf(stderr, "-p proxy hostname and port\n");
361 fprintf(stderr, "-t number of threads [default: 10]\n");
362 fprintf(stderr, "-u passthrough connection if no certificate is stored \
363 [default: error]\n");
364 fprintf(stderr, " WARNING: might be a security problem!\n");
368 static void log_function_gnutls(int level, const char *string) {
370 fprintf(stderr, " => %s", string);
374 static void initialize_gnutls(void) {
376 /* Recent versions of GnuTLS automatically initialize the cryptography layer
377 * in gnutls_global_init(). */
378 #if GNUTLS_VERSION_NUMBER <= 0x020b00
381 /* Thread safe setup. Must be called before gnutls_global_init(). */
382 error = gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
384 fprintf(stderr, "gcry_control(): %s/%s\n", gcry_strsource(error),
385 gcry_strerror(error));
388 /* Prevent usage of blocking /dev/random. */
389 error = gcry_control(GCRYCTL_ENABLE_QUICK_RANDOM, 0);
391 fprintf(stderr, "gcry_control(): %s/%s\n", gcry_strsource(error),
392 gcry_strerror(error));
397 /* Initialize GnuTLS. */
398 result = gnutls_global_init();
399 GNUTLS_ERROR_EXIT(result, "gnutls_global_init()");
402 gnutls_global_set_log_level(10);
403 gnutls_global_set_log_function(log_function_gnutls);
406 /* Setup GnuTLS cipher suites. */
407 result = gnutls_priority_init(&global_tls_priority_cache, "NORMAL", NULL);
408 GNUTLS_ERROR_EXIT(result, "gnutls_priority_init()");
410 /* Generate Diffie-Hellman parameters. */
411 result = gnutls_dh_params_init(&global_tls_dh_params);
412 GNUTLS_ERROR_EXIT(result, "gnutls_dh_params_init()");
413 result = gnutls_dh_params_generate2(global_tls_dh_params, DH_SIZE);
414 GNUTLS_ERROR_EXIT(result, "gnutls_dh_params_generate2()");
416 static void deinitialize_gnutls(void) {
417 gnutls_dh_params_deinit(global_tls_dh_params);
418 gnutls_priority_deinit(global_tls_priority_cache);
420 gnutls_global_deinit();
423 static void *worker_thread(void *unused) {
429 /* Get next element from ring buffer. */
432 client_socket = ringbuffer[ringbuffer_read];
433 ringbuffer_read = (ringbuffer_read + 1) % RINGBUFFER_SIZE;
437 /* Negative value indicates we should shut down our thread. */
438 if (client_socket < 0) {
442 handle_connection(client_socket);
448 static char *slurp_file(const char *path) {
451 char *content = NULL;
453 FILE *file = fopen(path, "r");
458 ct_assert(sizeof(stat.st_size) <= sizeof(size_t));
460 if (fstat(fileno(file), &stat) != 0) {
463 if (stat.st_size < 0) { /* just in case ... */
465 } else if ((size_t)stat.st_size >= SIZE_MAX - 1) {
470 content = malloc((size_t)stat.st_size + 1);
471 if (content == NULL) {
476 size_read = fread(content, 1, (size_t)stat.st_size, file);
477 if (size_read != (size_t)stat.st_size) {
482 content[size_read] = '\0';