]> ruderich.org/simon Gitweb - tlsproxy/tlsproxy.git/blobdiff - src/connection.c
Update copyright year.
[tlsproxy/tlsproxy.git] / src / connection.c
index 520ce40e031a0052581a7c2dc27e93c649fbf74f..184ee5a4231a302ee520dfecb05b845cdde0e4bb 100644 (file)
@@ -1,7 +1,7 @@
 /*
  * Handle connections.
  *
- * Copyright (C) 2011  Simon Ruderich
+ * Copyright (C) 2011-2014  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
 
 #include "tlsproxy.h"
 #include "connection.h"
+#include "verify.h"
 
-/* close() */
-#include <unistd.h>
-/* getaddrinfo() */
+#include <assert.h>
+#include <errno.h>
+#include <limits.h>
 #include <netdb.h>
-/* poll() */
 #include <poll.h>
-/* errno */
-#include <errno.h>
+#include <sys/socket.h>
+#include <unistd.h>
+
+#include <gnutls/x509.h>
 
 
-/* Maximum line of a HTTP request line. Longer request lines are aborted with
- * an error. The standard doesn't specify a maximum line length but this
- * should be a good limit to make processing simpler. */
+/* Maximum length of a HTTP request line. Longer request lines are aborted
+ * with an error. The standard doesn't specify a maximum line length but this
+ * should be a good limit to make processing simpler. As HTTPS is used this
+ * doesn't limit long GET requests. */
 #define MAX_REQUEST_LINE 4096
 
+/* Format string used to send HTTP/1.0 error responses to the client.
+ *
+ * %s is used 5 times, first is the error code, then additional headers, next
+ * two are the error code (no %n$s which is not in C98!), the last is the
+ * message. */
+#define HTTP_RESPONSE_FORMAT "HTTP/1.0 %s\r\n\
+Content-Type: text/html; charset=US-ASCII\r\n\
+%s\r\n\
+<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n\
+<html>\n\
+<head><title>%s</title></head>\n\
+<body>\n\
+<h1>%s</h1>\n\
+<p>%s</p>\n\
+</body>\n\
+</html>\n"
+
 
 static int initialize_tls_session_client(int peer_socket,
         const char *hostname,
@@ -43,35 +63,43 @@ static int initialize_tls_session_client(int peer_socket,
 static int initialize_tls_session_server(int peer_socket,
         gnutls_session_t *session,
         gnutls_certificate_credentials_t *x509_cred);
+static int initialize_tls_session_both(unsigned int flags,
+        int peer_socket,
+        gnutls_session_t *session,
+        gnutls_certificate_credentials_t *x509_cred);
 
+static int fdopen_read_write(int socket, FILE **read_fd, FILE **write_fd);
 static int read_http_request(FILE *client_fd, char *request, size_t length);
 static void send_bad_request(FILE *client_fd);
+static void send_authentication_required(FILE *client_fd);
 static void send_forwarding_failure(FILE *client_fd);
+static void tls_send_invalid_cert_message(gnutls_session_t session);
 
-#if 0
 static void transfer_data(int client, int server);
 static int read_from_write_to(int from, int to);
-#endif
 static void transfer_data_tls(int client, int server,
                               gnutls_session_t client_session,
                               gnutls_session_t server_session);
-static int read_from_write_to_tls(gnutls_session_t from, gnutls_session_t to);
+static int read_from_write_to_tls(gnutls_session_t from, gnutls_session_t to,
+                                  size_t buffer_size);
 
 static int connect_to_host(const char *hostname, const char *port);
 
 static int parse_request(const char *buffer, char *host, char *port,
                                              int *version_minor);
 
+static void log_session_information(gnutls_session_t session);
+
 
 void handle_connection(int client_socket) {
     int server_socket;
-    FILE *client_fd, *server_fd;
+    FILE *client_fd_read, *client_fd_write, *server_fd_read, *server_fd_write;
 
     char buffer[MAX_REQUEST_LINE];
     char host[MAX_REQUEST_LINE];
     char port[5 + 1];
 
-    int version_minor;
+    int version_minor; /* x in HTTP/1.x */
     int result;
 
     /* client_x509_cred is used when talking to the client (acting as a TSL
@@ -84,194 +112,270 @@ void handle_connection(int client_socket) {
     int client_session_init, server_session_init;
     /* gnutls_handshake() called? - used for goto out */
     int client_session_started, server_session_started;
+    /* Validation failed? If yes we need to send the special "invalid"
+     * certificate. */
+    int validation_failed;
 
-    LOG(LOG_DEBUG, "new connection");
+    LOG(DEBUG1, "new connection");
 
     server_socket = -1;
-    client_fd = NULL;
-    server_fd = NULL;
+    client_fd_read = NULL;
+    client_fd_write = NULL;
+    server_fd_read = NULL;
+    server_fd_write = NULL;
     client_session_init = 0;
     server_session_init = 0;
     client_session_started = 0;
     server_session_started = 0;
+    validation_failed = 0;
 
-    client_fd = fdopen(client_socket, "a+");
-    if (NULL == client_fd) {
-        LOG_PERROR(LOG_WARNING, "fdopen(): client failed");
+    if (fdopen_read_write(client_socket, &client_fd_read,
+                                         &client_fd_write) != 0) {
         goto out;
     }
 
     /* Read request line (CONNECT ..) and headers (they are discarded). */
-    result = read_http_request(client_fd, buffer, sizeof(buffer));
-    if (-1 == result) {
-        /* Read error. */
-        LOG(LOG_WARNING, "read_http_request(): client read error");
+    result = read_http_request(client_fd_read, buffer, sizeof(buffer));
+    if (result == -1) {
+        LOG(WARNING, "read_http_request(): client read error");
         goto out;
-    } else if (-2 == result) {
-        /* EOF */
-        LOG(LOG_WARNING, "read_http_request(): client EOF");
-        send_bad_request(client_fd);
+    } else if (result == -2) {
+        LOG(WARNING, "read_http_request(): client EOF");
+        send_bad_request(client_fd_write);
+        goto out;
+    } else if (result == -3) {
+        LOG(WARNING, "read_http_request(): proxy authentication failed");
+        send_authentication_required(client_fd_write);
         goto out;
     }
 
-    if (0 != parse_request(buffer, host, port, &version_minor)) {
-        LOG(LOG_WARNING, "bad request: %s", buffer);
-        send_bad_request(client_fd);
+    if (parse_request(buffer, host, port, &version_minor) != 0) {
+        LOG(WARNING, "bad request: >%s<", buffer);
+        send_bad_request(client_fd_write);
         goto out;
     }
 
-    LOG(LOG_DEBUG, "target: %s:%s (HTTP 1.%d)", host, port, version_minor);
+    LOG(DEBUG2, "target: %s:%s (HTTP 1.%d)", host, port, version_minor);
 
     /* Connect to proxy server or directly to server. */
-    if (NULL != global_proxy_host && NULL != global_proxy_port) {
-        LOG(LOG_DEBUG, "connecting to %s:%s", global_proxy_host,
-                                              global_proxy_port);
+    if (global_proxy_host != NULL && global_proxy_port != NULL) {
+        LOG(DEBUG1, "connecting to %s:%s", global_proxy_host,
+                                           global_proxy_port);
         server_socket = connect_to_host(global_proxy_host, global_proxy_port);
     } else {
-        LOG(LOG_DEBUG, "connecting to %s:%s", host, port);
+        LOG(DEBUG1, "connecting to %s:%s", host, port);
         server_socket = connect_to_host(host, port);
     }
 
-    if (-1 == server_socket) {
-        LOG(LOG_WARNING, "failed to connect to server");
-        send_forwarding_failure(client_fd);
+    if (server_socket < 0) {
+        LOG(WARNING, "failed to connect to server");
+        send_forwarding_failure(client_fd_write);
         goto out;
     }
-    server_fd = fdopen(server_socket, "a+");
-    if (NULL == server_fd) {
-        LOG_PERROR(LOG_WARNING, "fdopen(): server failed");
-        send_forwarding_failure(client_fd);
+    if (fdopen_read_write(server_socket, &server_fd_read,
+                                         &server_fd_write) != 0) {
+        send_forwarding_failure(client_fd_write);
         goto out;
     }
 
     /* Connect to proxy if requested (command line option). */
-    if (NULL != global_proxy_host && NULL != global_proxy_port) {
-        fprintf(server_fd, "CONNECT %s:%s HTTP/1.0\r\n", host, port);
-        fprintf(server_fd, "\r\n");
+    if (global_proxy_host != NULL && global_proxy_port != NULL) {
+        fprintf(server_fd_write, "CONNECT %s:%s HTTP/1.0\r\n", host, port);
+        fprintf(server_fd_write, "\r\n");
+        fflush(server_fd_write);
 
         /* Read response line from proxy server. */
-        result = read_http_request(server_fd, buffer, sizeof(buffer));
-        if (-1 == result) {
-            /* Read error. */
-            LOG(LOG_WARNING, "read_http_request(): proxy read error");
-            send_forwarding_failure(client_fd);
+        result = read_http_request(server_fd_read, buffer, sizeof(buffer));
+        if (result == -1) {
+            LOG(WARNING, "read_http_request(): proxy read error");
+            send_forwarding_failure(client_fd_write);
             goto out;
-        } else if (-2 == result) {
-            /* EOF */
-            LOG(LOG_WARNING, "read_http_request(): proxy EOF");
-            send_forwarding_failure(client_fd);
+        } else if (result == -2) {
+            LOG(WARNING, "read_http_request(): proxy EOF");
+            send_forwarding_failure(client_fd_write);
             goto out;
         }
 
         /* Check response of proxy server. */
-        if (0 != strncmp(buffer, "HTTP/1.0 200", 12)) {
-            LOG(LOG_WARNING, "bad proxy response: %s", buffer);
-            send_forwarding_failure(client_fd);
+        if (strncmp(buffer, "HTTP/1.0 200", 12)) {
+            LOG(WARNING, "bad proxy response: >%s<", buffer);
+            send_forwarding_failure(client_fd_write);
             goto out;
         }
     }
 
-    LOG(LOG_DEBUG, "connection to server established");
+    LOG(DEBUG1, "connection to server established");
 
-    /* We've established a connection, tell the client. */
-    fprintf(client_fd, "HTTP/1.0 200 Connection established\r\n");
-    fprintf(client_fd, "\r\n");
-    fflush(client_fd);
+    /* If the -u option is used and we don't know this hostname's server
+     * certificate, then just pass through the connection and let the client
+     * verify the server certificate. */
+    if (global_passthrough_unknown) {
+        char path[TLSPROXY_MAX_PATH_LENGTH];
+        FILE *file = NULL;
+
+        if (server_certificate_file(&file, host, path, sizeof(path)) == -2) {
+            /* We've established a connection, tell the client. */
+            fprintf(client_fd_write, "HTTP/1.0 200 Connection established\r\n");
+            fprintf(client_fd_write, "\r\n");
+            fflush(client_fd_write);
+
+            LOG(DEBUG1, "transferring data");
+
+            /* Proxy data between client and server until one side is done
+             * (EOF or error). */
+            transfer_data(client_socket, server_socket);
+
+            LOG(DEBUG1, "finished transferring data");
+
+            goto out;
+        }
+        /* server_certificate_file() may have opened the file, close it. */
+        if (file != NULL) {
+            fclose(file);
+        }
+    }
+
+    /* Initialize TLS client credentials to talk to the server. */
+    result = initialize_tls_session_server(server_socket, &server_session,
+                                                          &server_x509_cred);
+    if (result != 0) {
+        LOG(WARNING, "initialize_tls_session_server() failed");
+        send_forwarding_failure(client_fd_write);
+        goto out;
+    }
+    server_session_init = 1;
+
+    LOG(DEBUG1, "starting server TLS handshake");
+
+    /* Try to establish TLS handshake between us and server. */
+    result = gnutls_handshake(server_session);
+    if (result != GNUTLS_E_SUCCESS) {
+        LOG(WARNING, "server TLS handshake failed: %s",
+                     gnutls_strerror(result));
+        send_forwarding_failure(client_fd_write);
+        goto out;
+    }
+    server_session_started = 1;
+
+    LOG(DEBUG1, "server TLS handshake finished");
+
+    if (global_log_level >= LOG_DEBUG2_LEVEL) {
+        log_session_information(server_session);
+    }
+
+    /* Make sure the server certificate is valid and known. */
+    if (verify_tls_connection(server_session, host) != 0) {
+        LOG(ERROR, "server certificate validation failed!");
+        /* We'll send the error message over our TLS connection to the client,
+         * but with an invalid certificate. No data is transfered from/to the
+         * target server. */
+        validation_failed = 1;
+    }
 
     /* Initialize TLS server credentials to talk to the client. */
-    result = initialize_tls_session_client(client_socket, host,
+    result = initialize_tls_session_client(client_socket,
+                                           /* use a special host if the server
+                                            * certificate was invalid */
+                                           (validation_failed) ? "invalid"
+                                                               : host,
                                            &client_session,
                                            &client_x509_cred);
-    if (0 != result) {
-        LOG(LOG_WARNING, "initialize_tls_session_client() failed");
-        send_forwarding_failure(client_fd);
+    if (result != 0) {
+        LOG(WARNING, "initialize_tls_session_client() failed");
+        send_forwarding_failure(client_fd_write);
         goto out;
     }
     client_session_init = 1;
 
-    LOG(LOG_DEBUG, "starting client TLS handshake");
+    /* We've established a connection, tell the client. */
+    fprintf(client_fd_write, "HTTP/1.0 200 Connection established\r\n");
+    fprintf(client_fd_write, "\r\n");
+    fflush(client_fd_write);
+
+    LOG(DEBUG1, "starting client TLS handshake");
 
     /* Try to establish TLS handshake between client and us. */
     result = gnutls_handshake(client_session);
-    if (GNUTLS_E_SUCCESS != result) {
-        LOG(LOG_WARNING, "client TLS handshake failed: %s",
-                         gnutls_strerror(result));
-        send_forwarding_failure(client_fd);
+    if (result != GNUTLS_E_SUCCESS) {
+        LOG(WARNING, "client TLS handshake failed: %s",
+                     gnutls_strerror(result));
+        send_forwarding_failure(client_fd_write);
         goto out;
     }
     client_session_started = 1;
 
-    LOG(LOG_DEBUG, "client TLS handshake finished");
+    LOG(DEBUG1, "client TLS handshake finished");
 
-    result = initialize_tls_session_server(server_socket, &server_session,
-                                                          &server_x509_cred);
-    /* Initialize TLS client credentials to talk to the server. */
-    if (0 != result) {
-        LOG(LOG_WARNING, "initialize_tls_session_server() failed");
-        send_forwarding_failure(client_fd);
-        goto out;
+    if (global_log_level >= LOG_DEBUG2_LEVEL) {
+        log_session_information(client_session);
     }
-    server_session_init = 1;
 
-    LOG(LOG_DEBUG, "starting server TLS handshake");
-
-    /* Try to establish TLS handshake between us and server. */
-    result = gnutls_handshake(server_session);
-    if (GNUTLS_E_SUCCESS != result) {
-        LOG(LOG_WARNING, "server TLS handshake failed: %s",
-                         gnutls_strerror(result));
-        send_forwarding_failure(client_fd);
+    /* Tell the client that the verification failed. Shouldn't be necessary as
+     * the client should terminate the connection because he received the
+     * invalid certificate but better be sure. */
+    if (validation_failed) {
+        tls_send_invalid_cert_message(client_session);
         goto out;
     }
-    server_session_started = 1;
-
-    LOG(LOG_DEBUG, "server TLS handshake finished, transferring data");
 
-    /* FIXME: verify server's fingerprint */
+    LOG(DEBUG1, "transferring TLS data");
 
-    /* Proxy data between client and server until one suite is done (EOF or
+    /* Proxy data between client and server until one side is done (EOF or
      * error). */
     transfer_data_tls(client_socket, server_socket,
                       client_session, server_session);
 
-    LOG(LOG_DEBUG, "finished transferring data");
+    LOG(DEBUG1, "finished transferring TLS data");
 
 out:
     /* Close TLS sessions if necessary. Use GNUTLS_SHUT_RDWR so the data is
      * reliable transmitted. */
-    if (0 != server_session_started) {
-        gnutls_bye(server_session, GNUTLS_SHUT_RDWR);
-    }
-    if (0 != client_session_started) {
+    if (server_session_started) {
+        /* Recent gnutls-serv (used in the test-suite) won't terminate the
+         * connection when gnutls_bye(session, GNUTLS_SHUT_RDWR) is used
+         * before any other data was received. If the validation failed just
+         * close the connection without waiting for data, we won't read it
+         * anyway.
+         *
+         * For verified connections GNUTLS_SHUT_RDWR is important or we might
+         * lose data. */
+        gnutls_bye(server_session, validation_failed ? GNUTLS_SHUT_WR
+                                                     : GNUTLS_SHUT_RDWR);
+    }
+    if (client_session_started) {
         gnutls_bye(client_session, GNUTLS_SHUT_RDWR);
     }
-    if (0 != server_session_init) {
+    if (server_session_init) {
         gnutls_deinit(server_session);
         gnutls_certificate_free_credentials(server_x509_cred);
     }
-    if (0 != client_session_init) {
+    if (client_session_init) {
         gnutls_deinit(client_session);
-        gnutls_certificate_free_cas(client_x509_cred);
-        gnutls_certificate_free_keys(client_x509_cred);
         gnutls_certificate_free_credentials(client_x509_cred);
     }
 
     /* Close connection to server/proxy. */
-    if (NULL != server_fd) {
-        fclose(server_fd);
-    } else if (-1 != server_socket) {
+    if (server_fd_read != NULL) {
+        if (server_fd_write != NULL) {
+            fclose(server_fd_write);
+        }
+        fclose(server_fd_read);
+    } else if (server_socket != -1) {
         close(server_socket);
     }
-    LOG(LOG_DEBUG, "connection to server closed");
+    LOG(DEBUG1, "connection to server closed");
     /* Close connection to client. */
-    if (NULL != client_fd) {
-        fclose(client_fd);
+    if (client_fd_read != NULL) {
+        if (client_fd_write != NULL) {
+            fclose(client_fd_write);
+        }
+        fclose(client_fd_read);
     } else {
         close(client_socket);
     }
-    LOG(LOG_DEBUG, "connection to client closed");
+    LOG(DEBUG1, "connection to client closed");
 
-    LOG(LOG_DEBUG, "connection finished");
+    LOG(DEBUG1, "connection finished");
 }
 
 
@@ -280,84 +384,78 @@ static int initialize_tls_session_client(int peer_socket,
         gnutls_session_t *session,
         gnutls_certificate_credentials_t *x509_cred) {
     int result;
-    char path[1024];
+    int use_invalid_cert;
+    char path[TLSPROXY_MAX_PATH_LENGTH];
 
-    /* Hostname too long. */
-    if (sizeof(path) - strlen(PROXY_SERVER_CERT_FORMAT) <= strlen(hostname)) {
-        LOG(LOG_WARNING,
-            "initialize_tls_session_client(): hostname too long: '%s'",
-            hostname);
-        return -1;
-    }
-    /* Try to prevent path traversals in hostnames. */
-    if (NULL != strstr(hostname, "..")) {
-        LOG(LOG_WARNING,
-            "initialize_tls_session_client(): possible path traversal: '%s'",
-            hostname);
+    /* The "invalid" hostname is special. If it's used we send an invalid
+     * certificate to let the client know something is wrong. */
+    use_invalid_cert = (!strcmp(hostname, "invalid"));
+
+    if (proxy_certificate_path(hostname, path, sizeof(path)) != 0) {
+        LOG(ERROR,
+            "initialize_tls_session_client(): "
+            "failed to get proxy certificate path");
         return -1;
     }
-    snprintf(path, sizeof(path), PROXY_SERVER_CERT_FORMAT, hostname);
 
     result = gnutls_certificate_allocate_credentials(x509_cred);
-    if (GNUTLS_E_SUCCESS != result) {
-        LOG(LOG_ERROR,
-            "initialize_tls_session_client(): \
-gnutls_certificate_allocate_credentials(): %s",
+    if (result != GNUTLS_E_SUCCESS) {
+        LOG(ERROR,
+            "initialize_tls_session_client(): "
+            "gnutls_certificate_allocate_credentials(): %s",
             gnutls_strerror(result));
         return -1;
     }
 
     /* Load proxy CA file, this CA "list" is send to the client. */
-    result = gnutls_certificate_set_x509_trust_file(*x509_cred,
-                                                    PROXY_CA_FILE,
-                                                    GNUTLS_X509_FMT_PEM);
-    if (0 >= result) {
-        LOG(LOG_ERROR,
-            "initialize_tls_session_client(): can't read CA file: '%s'",
-            PROXY_CA_FILE);
-        return -1;
+    if (!use_invalid_cert) {
+        result = gnutls_certificate_set_x509_trust_file(*x509_cred,
+                                                        PROXY_CA_PATH,
+                                                        GNUTLS_X509_FMT_PEM);
+        if (result <= 0) {
+            LOG(ERROR,
+                "initialize_tls_session_client(): can't read CA file: '%s'",
+                PROXY_CA_PATH);
+            gnutls_certificate_free_credentials(*x509_cred);
+            return -1;
+        } else if (result != 1) {
+            /* Must contain only one CA, our proxy CA. */
+            LOG(ERROR, "initialize_tls_session_client(): multiple CAs found");
+            gnutls_certificate_free_credentials(*x509_cred);
+            return -1;
+        }
     }
+    /* If the invalid hostname was specified do nothing, we use a self-signed
+     * certificate in this case. */
+
     /* And certificate for this website and proxy's private key. */
-    result = gnutls_certificate_set_x509_key_file(*x509_cred,
-                                                  path, PROXY_KEY_FILE,
-                                                  GNUTLS_X509_FMT_PEM);
-    if (GNUTLS_E_SUCCESS != result) {
-        LOG(LOG_ERROR,
-            "initialize_tls_session_client(): \
-can't read server certificate ('%s') or key file ('%s'): %s",
-            path, PROXY_KEY_FILE, gnutls_strerror(result));
+    if (!use_invalid_cert) {
+        result = gnutls_certificate_set_x509_key_file(*x509_cred,
+                                                      path,
+                                                      PROXY_KEY_PATH,
+                                                      GNUTLS_X509_FMT_PEM);
+    /* If the invalid hostname was specified load our special "invalid"
+     * certificate. */
+    } else {
+        result = gnutls_certificate_set_x509_key_file(*x509_cred,
+                                                      PROXY_INVALID_CERT_PATH,
+                                                      PROXY_KEY_PATH,
+                                                      GNUTLS_X509_FMT_PEM);
+    }
+    if (result != GNUTLS_E_SUCCESS) {
+        LOG(ERROR,
+            "initialize_tls_session_client(): "
+            "can't read server certificate ('%s') or key file ('%s'): %s",
+            path, PROXY_KEY_PATH, gnutls_strerror(result));
+        gnutls_certificate_free_credentials(*x509_cred);
         /* Could be a missing certificate. */
         return -2;
     }
 
-    gnutls_certificate_set_dh_params(*x509_cred, tls_dh_params);
-
-    result = gnutls_init(session, GNUTLS_SERVER);
-    if (GNUTLS_E_SUCCESS != result) {
-        LOG(LOG_ERROR,
-            "initialize_tls_session_client(): gnutls_init(): %s",
-            gnutls_strerror(result));
-        return -1;
-    }
-    result = gnutls_priority_set(*session, tls_priority_cache);
-    if (GNUTLS_E_SUCCESS != result) {
-        LOG(LOG_ERROR,
-            "initialize_tls_session_client(): gnutls_priority_set(): %s",
-            gnutls_strerror(result));
-        return -1;
-    }
-    result = gnutls_credentials_set(*session,
-                                    GNUTLS_CRD_CERTIFICATE, *x509_cred);
-    if (GNUTLS_E_SUCCESS != result) {
-        LOG(LOG_ERROR,
-            "initialize_tls_session_client(): gnutls_credentials_set(): %s",
-            gnutls_strerror(result));
-        return -1;
-    }
+    gnutls_certificate_set_dh_params(*x509_cred, global_tls_dh_params);
 
-    gnutls_transport_set_ptr(*session, (gnutls_transport_ptr_t)peer_socket);
-
-    return 0;
+    return initialize_tls_session_both(GNUTLS_SERVER,
+                                       peer_socket, session, x509_cred);
 }
 static int initialize_tls_session_server(int peer_socket,
         gnutls_session_t *session,
@@ -365,84 +463,179 @@ static int initialize_tls_session_server(int peer_socket,
     int result;
 
     result = gnutls_certificate_allocate_credentials(x509_cred);
-    if (GNUTLS_E_SUCCESS != result) {
-        LOG(LOG_ERROR,
-            "initialize_tls_session_server(): \
-gnutls_certificate_allocate_credentials(): %s",
+    if (result != GNUTLS_E_SUCCESS) {
+        LOG(ERROR,
+            "initialize_tls_session_server(): "
+            "gnutls_certificate_allocate_credentials(): %s",
             gnutls_strerror(result));
         return -1;
     }
 
-    result = gnutls_init(session, GNUTLS_CLIENT);
-    if (GNUTLS_E_SUCCESS != result) {
-        LOG(LOG_ERROR,
-            "initialize_tls_session_server(): gnutls_init(): %s",
+    return initialize_tls_session_both(GNUTLS_CLIENT,
+                                       peer_socket, session, x509_cred);
+}
+static int initialize_tls_session_both(unsigned int flags,
+        int peer_socket,
+        gnutls_session_t *session,
+        gnutls_certificate_credentials_t *x509_cred) {
+    int result;
+
+    *session = NULL;
+
+    result = gnutls_init(session, flags);
+    if (result != GNUTLS_E_SUCCESS) {
+        LOG(ERROR,
+            "initialize_tls_session_both(): gnutls_init(): %s",
             gnutls_strerror(result));
-        return -1;
+        goto err;
     }
-    gnutls_priority_set(*session, tls_priority_cache);
-    if (GNUTLS_E_SUCCESS != result) {
-        LOG(LOG_ERROR,
-            "initialize_tls_session_server(): gnutls_priority_set(): %s",
+    result = gnutls_priority_set(*session, global_tls_priority_cache);
+    if (result != GNUTLS_E_SUCCESS) {
+        LOG(ERROR,
+            "initialize_tls_session_both(): gnutls_priority_set(): %s",
             gnutls_strerror(result));
-        return -1;
+        goto err;
     }
     result = gnutls_credentials_set(*session,
                                     GNUTLS_CRD_CERTIFICATE, *x509_cred);
-    if (GNUTLS_E_SUCCESS != result) {
-        LOG(LOG_ERROR,
-            "initialize_tls_session_server(): gnutls_credentials_set(): %s",
+    if (result != GNUTLS_E_SUCCESS) {
+        LOG(ERROR,
+            "initialize_tls_session_both(): gnutls_credentials_set(): %s",
             gnutls_strerror(result));
-        return -1;
+        goto err;
     }
 
+#ifdef HAVE_GNUTLS_TRANSPORT_SET_INT2
+    /* gnutls_transport_set_int() is a macro. */
+    gnutls_transport_set_int(*session, peer_socket);
+#else
     gnutls_transport_set_ptr(*session, (gnutls_transport_ptr_t)peer_socket);
+#endif
 
     return 0;
+
+err:
+    if (*session) {
+        gnutls_deinit(*session);
+    }
+    gnutls_certificate_free_credentials(*x509_cred);
+    return -1;
 }
 
 
+static int fdopen_read_write(int socket, FILE **read_fd, FILE **write_fd) {
+    *read_fd = fdopen(socket, "r");
+    if (*read_fd == NULL) {
+        LOG_PERROR(WARNING, "fdopen_read_write(): fdopen(\"r\") failed");
+        return -1;
+    }
+
+    *write_fd = fdopen(dup(socket), "w");
+    if (*write_fd == NULL) {
+        LOG_PERROR(WARNING, "fdopen_read_write(): fdopen(\"w\") failed");
+        fclose(*read_fd);
+        *read_fd = NULL; /* "tell" caller read_fd is already closed */
+        return -1;
+    }
+
+    return 0;
+}
+
 /* Read HTTP request line and headers (ignored).
  *
  * On success 0 is returned, -1 on client error, -2 on unexpected EOF.
  */
 static int read_http_request(FILE *client_fd, char *request, size_t length) {
     char buffer[MAX_REQUEST_LINE];
+    int found_proxy_authorization;
 
-    if (NULL == fgets(request, (int)length, client_fd)) {
+    assert(length <= INT_MAX);
+    if (fgets(request, (int)length, client_fd) == NULL) {
         if (ferror(client_fd)) {
-            LOG_PERROR(LOG_WARNING, "read_http_request(): fgets()");
+            LOG_PERROR(WARNING, "read_http_request(): fgets()");
             return -1;
         }
-
+        /* EOF */
         return -2;
     }
 
-    while (NULL != fgets(buffer, MAX_REQUEST_LINE, client_fd)) {
+    found_proxy_authorization = 0;
+    while (fgets(buffer, sizeof(buffer), client_fd) != NULL) {
+        const char *authentication = "Proxy-Authorization: Basic ";
+
+        if (global_http_digest_authorization != NULL
+                && !strncmp(buffer, authentication, strlen(authentication))) {
+            found_proxy_authorization = 1;
+
+            /* Check if the passphrase matches. */
+            strtok(buffer, "\r\n");
+            if (strcmp(buffer + strlen(authentication),
+                       global_http_digest_authorization)) {
+                return -3;
+            }
+        }
+
         /* End of header. */
-        if (0 == strcmp(buffer, "\n") || 0 == strcmp(buffer, "\r\n")) {
+        if (!strcmp(buffer, "\n") || !strcmp(buffer, "\r\n")) {
             break;
         }
     }
     if (ferror(client_fd)) {
-        LOG_PERROR(LOG_WARNING, "read_http_request(): fgets()");
+        LOG_PERROR(WARNING, "read_http_request(): fgets()");
         return -1;
+    } else if (feof(client_fd)) {
+        return -2;
+    }
+
+    if (global_http_digest_authorization != NULL && !found_proxy_authorization) {
+        return -3;
     }
 
     return 0;
 }
 
 static void send_bad_request(FILE *client_fd) {
-    fprintf(client_fd, "HTTP/1.0 400 Bad Request\r\n");
-    fprintf(client_fd, "\r\n");
+    const char error[] = "400 Bad Request";
+    const char msg[]   = "Your browser sent an invalid request.";
+    fprintf(client_fd, HTTP_RESPONSE_FORMAT, error, "", error, error, msg);
+    fflush(client_fd);
+}
+static void send_authentication_required(FILE *client_fd) {
+    const char error[] = "407 Proxy Authentication Required";
+    const char auth[]  = "Proxy-Authenticate: Basic realm=\"tlsproxy\"\r\n";
+    const char msg[]   = "TODO";
+    fprintf(client_fd, HTTP_RESPONSE_FORMAT, error, auth, error, error, msg);
+    fflush(client_fd);
 }
 static void send_forwarding_failure(FILE *client_fd) {
-    fprintf(client_fd, "HTTP/1.0 503 Forwarding failure\r\n");
-    fprintf(client_fd, "\r\n");
+    const char error[] = "503 Forwarding failure";
+    const char msg[]   = "Failed to connect to server, check logs.";
+    fprintf(client_fd, HTTP_RESPONSE_FORMAT, error, "", error, error, msg);
+    fflush(client_fd);
+}
+static void tls_send_invalid_cert_message(gnutls_session_t session) {
+    const char error[] = "500 Internal Server Error";
+    const char msg[]   = "Server certificate validation failed, check logs.";
+
+    int result;
+    ssize_t size_written;
+    char buffer[sizeof(HTTP_RESPONSE_FORMAT)
+                + 3 * sizeof(error) + sizeof(msg)];
+
+    result = snprintf(buffer, sizeof(buffer), HTTP_RESPONSE_FORMAT,
+                                              error, "", error, error, msg);
+    assert(result > 0 && (size_t)result < sizeof(buffer));
+
+    size_written = gnutls_record_send(session, buffer, strlen(buffer));
+    if (size_written < 0) {
+        LOG(WARNING, "tls_send_invalid_cert_message(): "
+                     "gnutls_record_send(): %s",
+                     gnutls_strerror((int)size_written));
+    }
+    /* Just an error message, no need to check if everything was written. */
 }
 
 
-#if 0
 /* Transfer data between client and server sockets until one closes the
  * connection. */
 static void transfer_data(int client, int server) {
@@ -454,23 +647,25 @@ static void transfer_data(int client, int server) {
     fds[1].events  = POLLIN | POLLPRI | POLLHUP | POLLERR;
     fds[1].revents = 0;
 
+    LOG(DEBUG2, "transfer_data(): %d -> %d", client, server);
+
     for (;;) {
-        int result = poll(fds, 2, -1 /* no timeout */);
+        int result = poll(fds, 2 /* fd count */, -1 /* no timeout */);
         if (result < 0) {
-            LOG_PERROR(LOG_ERROR, "transfer_data(): poll()");
+            LOG_PERROR(ERROR, "transfer_data(): poll()");
             return;
         }
 
         /* Data available from client. */
         if (fds[0].revents & POLLIN || fds[0].revents & POLLPRI) {
-            if (0 != read_from_write_to(client, server)) {
+            if (read_from_write_to(client, server) != 0) {
                 /* EOF (or other error) */
                 break;
             }
         }
         /* Data available from server. */
         if (fds[1].revents & POLLIN || fds[1].revents & POLLPRI) {
-            if (0 != read_from_write_to(server, client)) {
+            if (read_from_write_to(server, client) != 0) {
                 /* EOF (or other error) */
                 break;
             }
@@ -495,35 +690,35 @@ static int read_from_write_to(int from, int to) {
     char buffer[4096];
 
     size_read = read(from, buffer, sizeof(buffer));
-    if (0 > size_read) {
-        LOG_PERROR(LOG_WARNING, "read_from_write_to(): read()");
+    if (size_read < 0) {
+        LOG_PERROR(WARNING, "read_from_write_to(): read()");
         return -1;
-    }
     /* EOF */
-    if (0 == size_read) {
+    } else if (size_read == 0) {
         return -1;
     }
 
     size_written = write(to, buffer, (size_t)size_read);
-    if (0 > size_written) {
-        LOG_PERROR(LOG_WARNING, "read_from_write_to(): write()");
+    if (size_written < 0) {
+        LOG_PERROR(WARNING, "read_from_write_to(): write()");
         return -1;
     }
     if (size_read != size_written) {
-        LOG(LOG_ERROR, "read_from_write_to(): only written %ld of %ld bytes!",
-                       (long int)size_written, (long int)size_read);
+        LOG(ERROR, "read_from_write_to(): only written %zu of %zu bytes!",
+                   size_written, size_read);
         return -1;
     }
 
     return 0;
 }
-#endif
 
 /* Transfer data between client and server TLS connection until one closes the
  * connection. */
 static void transfer_data_tls(int client, int server,
                               gnutls_session_t client_session,
                               gnutls_session_t server_session) {
+    size_t buffer_size;
+
     struct pollfd fds[2];
     fds[0].fd      = client;
     fds[0].events  = POLLIN | POLLPRI | POLLHUP | POLLERR;
@@ -532,23 +727,33 @@ static void transfer_data_tls(int client, int server,
     fds[1].events  = POLLIN | POLLPRI | POLLHUP | POLLERR;
     fds[1].revents = 0;
 
+    /* Get maximum possible buffer size. */
+    buffer_size = gnutls_record_get_max_size(client_session);
+    if (gnutls_record_get_max_size(server_session) < buffer_size) {
+        buffer_size = gnutls_record_get_max_size(server_session);
+    }
+    LOG(DEBUG2, "transfer_data_tls(): suggested buffer size: %zu",
+                buffer_size);
+
     for (;;) {
-        int result = poll(fds, 2, -1 /* no timeout */);
+        int result = poll(fds, 2 /* fd count */, -1 /* no timeout */);
         if (result < 0) {
-            LOG_PERROR(LOG_ERROR, "transfer_data(): poll()");
+            LOG_PERROR(ERROR, "transfer_data(): poll()");
             return;
         }
 
         /* Data available from client. */
         if (fds[0].revents & POLLIN || fds[0].revents & POLLPRI) {
-            if (0 != read_from_write_to_tls(client_session, server_session)) {
+            if (read_from_write_to_tls(client_session, server_session,
+                                       buffer_size) != 0) {
                 /* EOF (or other error) */
                 break;
             }
         }
         /* Data available from server. */
         if (fds[1].revents & POLLIN || fds[1].revents & POLLPRI) {
-            if (0 != read_from_write_to_tls(server_session, client_session)) {
+            if (read_from_write_to_tls(server_session, client_session,
+                                       buffer_size) != 0) {
                 /* EOF (or other error) */
                 break;
             }
@@ -567,45 +772,53 @@ static void transfer_data_tls(int client, int server,
 
 /* Read available data from session from and write to session to. */
 static int read_from_write_to_tls(gnutls_session_t from,
-                                  gnutls_session_t to) {
-    size_t size;
+                                  gnutls_session_t to,
+                                  size_t buffer_size) {
     ssize_t size_read;
     ssize_t size_written;
-    char buffer[16384];
+    char buffer[16384]; /* GnuTLS default maximum */
 
-    /* Get maximum possible buffer size. */
-    size = gnutls_record_get_max_size(from);
-    LOG(LOG_DEBUG, "read_from_write_to_tls(): suggested buffer size: %ld",
-                   (long int)size);
-    if (size > gnutls_record_get_max_size(to)) {
-        size = gnutls_record_get_max_size(to);
-    }
-    if (size > sizeof(buffer)) {
-        size = sizeof(buffer);
-    }
-    LOG(LOG_DEBUG, "read_from_write_to_tls(): used buffer size: %ld",
-                   (long int)size);
-
-    size_read = gnutls_record_recv(from, buffer, size);
-    if (0 > size_read) {
-        LOG(LOG_WARNING, "read_from_write_to_tls(): gnutls_record_recv(): %s",
-                         gnutls_strerror((int)size_read));
-        return -1;
+    if (buffer_size > sizeof(buffer)) {
+        LOG(WARNING, "read_from_write_to_tls(): reduced buffer size to %zu",
+                     sizeof(buffer));
+        buffer_size = sizeof(buffer);
     }
+
+    size_read = gnutls_record_recv(from, buffer, buffer_size);
+    if (size_read < 0) {
+        /* Allow rehandshakes. As handshakes might be insecure make sure that
+         * %SAFE_RENEGOTIATION is used in GnuTLS's priority string. */
+        if (size_read == GNUTLS_E_REHANDSHAKE) {
+            int result;
+
+            LOG(DEBUG1, "server requested TLS rehandshake");
+
+            result = gnutls_handshake(from);
+            if (result != GNUTLS_E_SUCCESS) {
+                LOG(WARNING, "server TLS rehandshake failed: %s",
+                             gnutls_strerror(result));
+                return -1;
+            }
+            return 0;
+        }
+
+        LOG(WARNING, "read_from_write_to_tls(): gnutls_record_recv(): %s",
+                     gnutls_strerror((int)size_read));
+        return -1;
     /* EOF */
-    if (0 == size_read) {
+    } else if (size_read == 0) {
         return -1;
     }
 
     size_written = gnutls_record_send(to, buffer, (size_t)size_read);
-    if (0 > size_written) {
-        LOG(LOG_WARNING, "read_from_write_to_tls(): gnutls_record_send(): %s",
-                         gnutls_strerror((int)size_written));
+    if (size_written < 0) {
+        LOG(WARNING, "read_from_write_to_tls(): gnutls_record_send(): %s",
+                     gnutls_strerror((int)size_written));
         return -1;
     }
     if (size_read != size_written) {
-        LOG(LOG_ERROR, "read_from_write_to_tls(): only written %ld of %ld bytes!",
-                       (long int)size_written, (long int)size_read);
+        LOG(ERROR, "read_from_write_to_tls(): only written %zu of %zu bytes!",
+                   size_written, size_read);
         return -1;
     }
 
@@ -621,7 +834,7 @@ static int connect_to_host(const char *hostname, const char *port) {
     int server_socket;
     struct addrinfo *server;
 
-    if (NULL == hostname || NULL == port) {
+    if (hostname == NULL || port == NULL) {
         return -1;
     }
 
@@ -631,38 +844,44 @@ static int connect_to_host(const char *hostname, const char *port) {
     gai_hints.ai_socktype = SOCK_STREAM;
     gai_hints.ai_protocol = 0;
     gai_hints.ai_flags    = AI_NUMERICSERV /* given port is numeric */
+#ifdef AI_ADDRCONFIG
                           | AI_ADDRCONFIG  /* supported by this computer */
-                          | AI_V4MAPPED;   /* support IPv4 through IPv6 */
+#endif
+                          ;
     gai_return = getaddrinfo(hostname, port, &gai_hints, &gai_result);
-    if (0 != gai_return) {
-        LOG_PERROR(LOG_WARNING, "connect_to_host(): getaddrinfo()");
+    if (gai_return != 0) {
+        if (gai_return == EAI_SYSTEM) {
+            LOG_PERROR(WARNING, "connect_to_host(): getaddrinfo()");
+        } else {
+            LOG(WARNING, "connect_to_host(): getaddrinfo(): %s",
+                         gai_strerror(gai_return));
+        }
         return -1;
     }
 
     /* Now try to connect to each server returned by getaddrinfo(), use the
      * first successful connect. */
-    for (server = gai_result; NULL != server; server = server->ai_next) {
+    for (server = gai_result; server != NULL; server = server->ai_next) {
         server_socket = socket(server->ai_family,
                                server->ai_socktype,
                                server->ai_protocol);
-        if (-1 == server_socket) {
-            LOG_PERROR(LOG_DEBUG, "connect_to_host(): socket(), trying next");
+        if (server_socket < 0) {
+            LOG_PERROR(DEBUG1, "connect_to_host(): socket(), trying next");
             continue;
         }
 
-        if (-1 != connect(server_socket, server->ai_addr,
-                                         server->ai_addrlen)) {
+        if (connect(server_socket, server->ai_addr, server->ai_addrlen) == 0) {
             break;
         }
-        LOG_PERROR(LOG_DEBUG, "connect_to_host(): connect(), trying next");
+        LOG_PERROR(DEBUG1, "connect_to_host(): connect(), trying next");
 
         close(server_socket);
     }
     /* Make sure we free the result from getaddrinfo(). */
     freeaddrinfo(gai_result);
 
-    if (NULL == server) {
-        LOG_PERROR(LOG_WARNING, "connect_to_host(): no server found, abort");
+    if (server == NULL) {
+        LOG_PERROR(WARNING, "connect_to_host(): no server found, abort");
         return -1;
     }
 
@@ -683,20 +902,19 @@ static int parse_request(const char *request, char *host, char *port,
     char *position;
 
     /* scanf() doesn't check spaces. */
-    if (0 != strncmp(request, "CONNECT ", 8)) {
+    if (strncmp(request, "CONNECT ", 8)) {
         return -1;
     }
     /* Check request and extract data, "host:port" is not yet separated. */
-    if (2 != sscanf(request, "CONNECT %s HTTP/1.%d",
-                             host, version_minor)) {
+    if (sscanf(request, "CONNECT %s HTTP/1.%d", host, version_minor) != 2) {
         return -1;
     }
     /* Make sure ":port" is there. */
-    if (NULL == (position = strchr(host, ':'))) {
+    if ((position = strchr(host, ':')) == NULL) {
         return -1;
     }
     /* Make sure port is numeric. */
-    if (1 != sscanf(position + 1, "%d", &port_unused)) {
+    if (sscanf(position + 1, "%d", &port_unused) != 1) {
         return -1;
     }
     /* Store it in *port. */
@@ -707,3 +925,72 @@ static int parse_request(const char *request, char *host, char *port,
 
     return 0;
 }
+
+
+static void log_session_information(gnutls_session_t session) {
+    /* From doc/examples/ex-session-info.c of GnuTLS 3.2.3's tarball and
+     * modified, thanks. */
+
+    const char *tmp;
+    gnutls_credentials_type_t cred;
+    gnutls_kx_algorithm_t kx;
+    int dhe, ecdh;
+
+    dhe = 0;
+    ecdh = 0;
+
+    /* Key exchange algorithm. */
+    kx = gnutls_kx_get(session);
+    LOG(DEBUG2, "- key exchange: %s", gnutls_kx_get_name(kx));
+
+    /* Authentication type. */
+    cred = gnutls_auth_get_type(session);
+    switch (cred) {
+        case GNUTLS_CRD_CERTIFICATE:
+            if (kx == GNUTLS_KX_DHE_RSA
+                    || kx == GNUTLS_KX_DHE_DSS) {
+                dhe = 1;
+#ifdef GNUTLS_KX_ECDHE_RSA
+            } else if (kx == GNUTLS_KX_ECDHE_RSA
+                    || kx == GNUTLS_KX_ECDHE_ECDSA) {
+                ecdh = 1;
+#endif
+            }
+            break;
+
+        case GNUTLS_CRD_IA:
+        case GNUTLS_CRD_SRP:
+        case GNUTLS_CRD_PSK:
+        case GNUTLS_CRD_ANON:
+        default:
+            /* This shouldn't occur. */
+            LOG(WARNING, "unexpected authentication method: %d", cred);
+            break;
+    }
+
+    /* Information about key exchange. */
+    if (dhe) {
+        LOG(DEBUG2, "- ephemeral DH using prime of %d bits",
+                    gnutls_dh_get_prime_bits(session));
+    } else if (ecdh) {
+#ifdef GNUTLS_KX_ECDHE_RSA
+        LOG(DEBUG2, "- ephemeral ECDH using curve %s",
+                    gnutls_ecc_curve_get_name(gnutls_ecc_curve_get(session)));
+#endif
+    }
+
+    tmp = gnutls_protocol_get_name(gnutls_protocol_get_version(session));
+    LOG(DEBUG2, "- protocol: %s", tmp); /* e.g. TLS 1.0 */
+
+    tmp = gnutls_certificate_type_get_name(gnutls_certificate_type_get(session));
+    LOG(DEBUG2, "- certificate type: %s", tmp);
+
+    tmp = gnutls_compression_get_name(gnutls_compression_get(session));
+    LOG(DEBUG2, "- compression: %s", tmp);
+
+    tmp = gnutls_cipher_get_name(gnutls_cipher_get(session));
+    LOG(DEBUG2, "- cipher: %s", tmp);
+
+    tmp = gnutls_mac_get_name(gnutls_mac_get(session));
+    LOG(DEBUG2, "- MAC: %s", tmp);
+}