/*
* tlsproxy is a TLS proxy for HTTPS which intercepts the connections and
* ensures the server certificate doesn't change. Normally this isn't detected
* if a trusted CA for the new server certificate is installed.
*
* Copyright (C) 2011 Simon Ruderich
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
#include "tlsproxy.h"
#include "sem.h"
#include "connection.h"
/* socket(), bind(), accept(), listen() */
#include
#include
/* close() */
#include
/* htons() */
#include
/* sigaction() */
#include
/* errno */
#include
/* pthread_*() */
#include
/* For GnuTLS. */
#include
GCRY_THREAD_OPTION_PTHREAD_IMPL;
/* Size of ringbuffer. */
#define RINGBUFFER_SIZE 10
/* Bit size of Diffie-Hellman key exchange parameters. */
#define DH_SIZE 1024
/* For gnutls_*() functions. */
#define GNUTLS_ERROR_EXIT(error, message) \
if (GNUTLS_E_SUCCESS != error) { \
fprintf(stderr, "%s: %s\n", message, gnutls_strerror(error)); \
exit(EXIT_FAILURE); \
}
/* Server should shut down. Set by SIGINT handler. */
static volatile int done;
/* Number of threads. */
static size_t thread_count;
/* Synchronized ring buffer storing accept()ed client sockets. */
static int ringbuffer[RINGBUFFER_SIZE];
static int ringbuffer_read;
static int ringbuffer_write;
static SEM *ringbuffer_full; /* At least one element in the buffer? */
static SEM *ringbuffer_free; /* Space for another element in the buffer? */
static SEM *ringbuffer_lock; /* Read lock. */
static void sigint_handler(int signal);
static void parse_arguments(int argc, char **argv);
static void print_usage(const char *argv);
static void initialize_gnutls(void);
static void deinitialize_gnutls(void);
static void worker_thread(void);
int main(int argc, char **argv) {
int port;
int client_socket, server_socket;
struct sockaddr_in6 server_in;
size_t i;
pthread_t *threads;
struct sigaction action;
parse_arguments(argc, argv);
port = atoi(argv[argc - 1]);
if (0 >= port || 0xffff < port) {
print_usage(argv[0]);
fprintf(stderr, "\ninvalid port\n");
return EXIT_FAILURE;
}
/* Setup our SIGINT signal handler which allows a "normal" termination of
* the server. */
sigemptyset(&action.sa_mask);
action.sa_handler = sigint_handler;
action.sa_flags = 0;
sigaction(SIGINT, &action, NULL);
/* Ignore SIGPIPEs. */
action.sa_handler = SIG_IGN;
sigaction(SIGPIPE, &action, NULL);
/* Initialize ring buffer. */
ringbuffer_read = 0;
ringbuffer_write = 0;
ringbuffer_full = sem_init(0);
ringbuffer_free = sem_init(RINGBUFFER_SIZE);
ringbuffer_lock = sem_init(1);
if (NULL == ringbuffer_full
|| NULL == ringbuffer_free
|| NULL == ringbuffer_lock) {
perror("sem_init()");
return EXIT_FAILURE;
}
initialize_gnutls();
/* Spawn worker threads to handle requests. */
threads = (pthread_t *)malloc(thread_count * sizeof(pthread_t));
if (NULL == threads) {
perror("thread malloc failed");
return EXIT_FAILURE;
}
for (i = 0; i < thread_count; i++) {
int result;
pthread_t thread;
result = pthread_create(&thread, NULL,
(void * (*)(void *))&worker_thread,
NULL);
if (0 != result) {
printf("failed to create worker thread: %s\n", strerror(result));
return EXIT_FAILURE;
}
threads[i] = thread;
}
server_socket = socket(PF_INET6, SOCK_STREAM, 0);
if (-1 == server_socket) {
perror("socket()");
return EXIT_FAILURE;
}
#ifdef DEBUG
/* Fast rebinding for debug mode, could cause invalid packets. */
{
int socket_option = 1;
setsockopt(server_socket, SOL_SOCKET, SO_REUSEADDR,
&socket_option, sizeof(socket_option));
}
#endif
/* Bind to the listen socket. */
memset(&server_in, 0, sizeof(server_in));
server_in.sin6_family = AF_INET6; /* IPv6 (and IPv4) */
server_in.sin6_addr = in6addr_any; /* bind to any address */
server_in.sin6_port = htons((uint16_t)port); /* port to bind to */
if (-1 == bind(server_socket, (struct sockaddr *)&server_in,
sizeof(server_in))) {
perror("bind()");
return EXIT_FAILURE;
}
/* And accept connections. */
if (-1 == listen(server_socket, 5)) {
perror("listen()");
return EXIT_FAILURE;
}
if (LOG_DEBUG <= global_log_level) {
printf("Listening for connections on port %d.\n", port);
if (NULL != global_proxy_host && NULL != global_proxy_port) {
printf("Using proxy: %s:%s.\n", global_proxy_host,
global_proxy_port);
}
}
while (!done) {
/* Accept new connection. */
client_socket = accept(server_socket, NULL, NULL);
if (-1 == client_socket) {
perror("accept()");
break;
}
/* No lock, we only have one producer! */
P(ringbuffer_free);
ringbuffer[ringbuffer_write] = client_socket;
ringbuffer_write = (ringbuffer_write + 1) % RINGBUFFER_SIZE;
V(ringbuffer_full);
}
close(server_socket);
/* Poison all threads and shut them down. */
for (i = 0; i < thread_count; i++) {
P(ringbuffer_free);
ringbuffer[ringbuffer_write] = -1; /* poison */
ringbuffer_write = (ringbuffer_write + 1) % RINGBUFFER_SIZE;
V(ringbuffer_full);
}
for (i = 0; i < thread_count; i++) {
errno = pthread_join(threads[i], NULL);
if (0 != errno) {
perror("pthread_join()");
continue;
}
}
free(ringbuffer_full);
free(ringbuffer_free);
free(ringbuffer_lock);
free(threads);
deinitialize_gnutls();
free(global_proxy_host);
free(global_proxy_port);
return EXIT_FAILURE;
}
static void sigint_handler(int signal_number) {
(void)signal_number;
done = 1;
}
static void parse_arguments(int argc, char **argv) {
int option;
/* Default values. */
thread_count = 10;
#ifdef DEBUG
global_log_level = LOG_DEBUG;
#else
global_log_level = LOG_WARNING;
#endif
while (-1 != (option = getopt(argc, argv, "d:p:t:h?"))) {
switch (option) {
case 'd': {
if (0 > atoi(optarg)) {
print_usage(argv[0]);
fprintf(stderr, "\n-d positive number required\n");
exit(EXIT_FAILURE);
}
global_log_level = atoi(optarg);
break;
}
case 'p': {
char *position;
/* -p must have the format host:port. */
if (NULL == (position = strchr(optarg, ':'))
|| position == optarg
|| 0 == strlen(position + 1)
|| 0 >= atoi(position + 1)
|| 0xffff < atoi(position + 1)) {
print_usage(argv[0]);
fprintf(stderr, "\ninvalid -p, format host:port\n");
exit(EXIT_FAILURE);
}
global_proxy_host = malloc((size_t)(position - optarg) + 1);
if (NULL == global_proxy_host) {
perror("malloc()");
exit(EXIT_FAILURE);
}
memcpy(global_proxy_host, optarg, (size_t)(position - optarg));
global_proxy_host[position - optarg] = '\0';
global_proxy_port = malloc(strlen(position + 1) + 1);
if (NULL == global_proxy_port) {
perror("malloc()");
exit(EXIT_FAILURE);
}
strcpy(global_proxy_port, position + 1);
break;
}
case 't': {
if (0 >= atoi(optarg)) {
print_usage(argv[0]);
fprintf(stderr, "\n-t positive number required\n");
exit(EXIT_FAILURE);
}
thread_count = (size_t)atoi(optarg);
break;
}
case 'h':
default: /* '?' */
print_usage(argv[0]);
exit(EXIT_FAILURE);
}
}
if (optind >= argc) {
print_usage(argv[0]);
fprintf(stderr, "\nport missing\n");
exit(EXIT_FAILURE);
}
}
static void print_usage(const char *argv) {
fprintf(stderr, "Usage: %s [-d level] [-p host:port] [-t count] port\n",
argv);
fprintf(stderr, "\n");
fprintf(stderr, "-d debug level: 0=errors only, 2=debug [default: 1]\n");
fprintf(stderr, "-p proxy hostname and port\n");
fprintf(stderr, "-t number of threads [default: 10]\n");
}
static void initialize_gnutls(void) {
int result;
gcry_error_t error = 0;
/* Thread safe setup. Must be called before gnutls_global_init(). */
error = gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
if (error) {
fprintf(stderr, "gcry_control(): %s/%s\n", gcry_strsource(error),
gcry_strerror(error));
exit(EXIT_FAILURE);
}
/* Prevent usage of blocking /dev/random. */
error = gcry_control(GCRYCTL_ENABLE_QUICK_RANDOM, 0);
if (error) {
fprintf(stderr, "gcry_control(): %s/%s\n", gcry_strsource(error),
gcry_strerror(error));
exit(EXIT_FAILURE);
}
/* Initialize GnuTLS. */
result = gnutls_global_init();
GNUTLS_ERROR_EXIT(result, "gnutls_global_init()");
/* Setup GnuTLS cipher suites. */
result = gnutls_priority_init(&tls_priority_cache, "NORMAL", NULL);
GNUTLS_ERROR_EXIT(result, "gnutls_priority_init()");
/* Generate Diffie-Hellman parameters. */
result = gnutls_dh_params_init(&tls_dh_params);
GNUTLS_ERROR_EXIT(result, "gnutls_dh_params_init()");
result = gnutls_dh_params_generate2(tls_dh_params, DH_SIZE);
GNUTLS_ERROR_EXIT(result, "gnutls_dh_params_generate2()");
}
static void deinitialize_gnutls(void) {
gnutls_dh_params_deinit(tls_dh_params);
gnutls_priority_deinit(tls_priority_cache);
gnutls_global_deinit();
}
static void worker_thread(void) {
int client_socket;
for (;;) {
/* Get next element from ring buffer. */
P(ringbuffer_full);
P(ringbuffer_lock);
client_socket = ringbuffer[ringbuffer_read];
ringbuffer_read = (ringbuffer_read + 1) % RINGBUFFER_SIZE;
V(ringbuffer_lock);
V(ringbuffer_free);
/* Negative value indicates we should shut down our thread. */
if (0 > client_socket) {
break;
}
handle_connection(client_socket);
}
}