Add OpenSSL support
authorMaxim Antonov <mantonov@gmail.com>
Mon, 3 Aug 2020 11:11:37 +0000 (18:11 +0700)
committerFabian Keil <fk@fabiankeil.de>
Tue, 1 Sep 2020 10:22:42 +0000 (12:22 +0200)
To enable it, configure with "--with-openssl".

This is mainly useful for platforms that ship with
OpenSSL in the base so the "special exception" from
section 3 of the GPLv2 applies.

The author (Maxim Antonov) reports about 100% more requests
per second when using OpenSSL instead of MbedTLS which the
committer could confirm. For details see:
https://sourceforge.net/p/ijbswa/patches/143/

This commit has a couple of issues that will be addressed
in follow-up commits.

GNUmakefile.in
configure.in
jcc.c
jcc.h
openssl.c [new file with mode: 0644]
project.h
ssl.c
ssl.h
ssl_common.c [new file with mode: 0644]
ssl_common.h [new file with mode: 0644]

index 304c3a0..b9bdb90 100644 (file)
@@ -231,10 +231,18 @@ W32_HDRS  = @WIN_ONLY@w32log.h w32taskbar.h win32.h w32res.h w32svrapi.h
 W32_LIB   = @WIN_ONLY@-lwsock32 -lcomctl32
 W32_INIS  = @WIN_ONLY@config.txt trust.txt
 
 W32_LIB   = @WIN_ONLY@-lwsock32 -lcomctl32
 W32_INIS  = @WIN_ONLY@config.txt trust.txt
 
-SSL_SRC      = @FEATURE_HTTPS_INSPECTION_ONLY@ssl.c
+SSL_SRC      = @FEATURE_HTTPS_INSPECTION_ONLY@ssl_common.c
 SSL_OBJS     = @FEATURE_HTTPS_INSPECTION_ONLY@$(SSL_SRC:.c=.o)
 SSL_HDRS     = @FEATURE_HTTPS_INSPECTION_ONLY@$(SSL_SRC:.c=.h) project.h
 
 SSL_OBJS     = @FEATURE_HTTPS_INSPECTION_ONLY@$(SSL_SRC:.c=.o)
 SSL_HDRS     = @FEATURE_HTTPS_INSPECTION_ONLY@$(SSL_SRC:.c=.h) project.h
 
+MBEDTLS_SRC      = @FEATURE_HTTPS_INSPECTION_ONLY_MBEDTLS@ssl.c
+MBEDTLS_OBJS     = @FEATURE_HTTPS_INSPECTION_ONLY_MBEDTLS@$(MBEDTLS_SRC:.c=.o)
+MBEDTLS_HDRS     = @FEATURE_HTTPS_INSPECTION_ONLY_MBEDTLS@$(MBEDTLS_SRC:.c=.h)
+
+OPENSSL_SRC      = @FEATURE_HTTPS_INSPECTION_ONLY_OPENSSL@openssl.c
+OPENSSL_OBJS     = @FEATURE_HTTPS_INSPECTION_ONLY_OPENSSL@$(OPENSSL_SRC:.c=.o)
+OPENSSL_HDRS     = @FEATURE_HTTPS_INSPECTION_ONLY_OPENSSL@$(OPENSSL_SRC:.c=.h)
+
 PCRS_SRC     = @STATIC_PCRS_ONLY@pcrs.c
 PCRS_OBJS    = @STATIC_PCRS_ONLY@$(PCRS_SRC:.c=.@OBJEXT@)
 PCRS_HDRS    = @STATIC_PCRS_ONLY@$(PCRS_SRC:.c=.h)
 PCRS_SRC     = @STATIC_PCRS_ONLY@pcrs.c
 PCRS_OBJS    = @STATIC_PCRS_ONLY@$(PCRS_SRC:.c=.@OBJEXT@)
 PCRS_HDRS    = @STATIC_PCRS_ONLY@$(PCRS_SRC:.c=.h)
@@ -259,9 +267,9 @@ SOCKET_LIB   = @SOCKET_LIB@
 # PThreads library, if needed.
 PTHREAD_LIB  = @PTHREAD_ONLY@@PTHREAD_LIB@
 
 # PThreads library, if needed.
 PTHREAD_LIB  = @PTHREAD_ONLY@@PTHREAD_LIB@
 
-SRCS         = $(C_SRC) $(CLIENT_TAG_SRC) $(FUZZ_SRC) $(W32_SRC)  $(PCRS_SRC)  $(PCRE_SRC)  $(REGEX_SRC) $(SSL_SRC)
-OBJS         = $(C_OBJS) $(CLIENT_TAG_OBJS) $(FUZZ_OBJS) $(W32_OBJS) $(PCRS_OBJS) $(PCRE_OBJS) $(REGEX_OBJS) $(SSL_OBJS)
-HDRS         = $(C_HDRS) $(W32_HDRS) $(PCRS_HDRS) $(PCRE_OBJS) $(REGEX_HDRS) $(SSL_HDRS)
+SRCS         = $(C_SRC) $(CLIENT_TAG_SRC) $(FUZZ_SRC) $(W32_SRC)  $(PCRS_SRC)  $(PCRE_SRC)  $(REGEX_SRC) $(SSL_SRC) $(MBEDTLS_SRC) $(OPENSSL_SRC)
+OBJS         = $(C_OBJS) $(CLIENT_TAG_OBJS) $(FUZZ_OBJS) $(W32_OBJS) $(PCRS_OBJS) $(PCRE_OBJS) $(REGEX_OBJS) $(SSL_OBJS) $(MBEDTLS_OBJS) $(OPENSSL_OBJS)
+HDRS         = $(C_HDRS) $(W32_HDRS) $(PCRS_HDRS) $(PCRE_OBJS) $(REGEX_HDRS) $(SSL_HDRS) $(MBEDTLS_HDRS) $(OPENSSL_HDRS)
 LIBS         = @LIBS@ $(W32_LIB) $(SOCKET_LIB) $(PTHREAD_LIB)
 
 
 LIBS         = @LIBS@ $(W32_LIB) $(SOCKET_LIB) $(PTHREAD_LIB)
 
 
index a064073..6f772f0 100644 (file)
@@ -1133,10 +1133,11 @@ dnl fi
 AC_SUBST(STATIC_PCRE_ONLY)
 AC_SUBST(STATIC_PCRS_ONLY)
 
 AC_SUBST(STATIC_PCRE_ONLY)
 AC_SUBST(STATIC_PCRS_ONLY)
 
+FEATURE_HTTPS_INSPECTION_ONLY=#
 dnl ========================================================
 dnl check for mbedTLS which is required for https inspection
 dnl ========================================================
 dnl ========================================================
 dnl check for mbedTLS which is required for https inspection
 dnl ========================================================
-FEATURE_HTTPS_INSPECTION_ONLY=#
+FEATURE_HTTPS_INSPECTION_ONLY_MBEDTLS=#
 OPT_MBEDTLS=no
 AC_ARG_WITH(mbedtls,dnl
 AC_HELP_STRING([--with-mbedtls], [Enable mbedTLS detection for https inspection.])
 OPT_MBEDTLS=no
 AC_ARG_WITH(mbedtls,dnl
 AC_HELP_STRING([--with-mbedtls], [Enable mbedTLS detection for https inspection.])
@@ -1147,22 +1148,71 @@ if test X"$OPT_MBEDTLS" != Xno; then
 
   AC_CHECK_LIB(mbedtls, mbedtls_ssl_init,
    [
 
   AC_CHECK_LIB(mbedtls, mbedtls_ssl_init,
    [
-     AC_DEFINE(FEATURE_HTTPS_INSPECTION, 1, [if mbedTLS is enabled])
-     AC_SUBST(FEATURE_HTTPS_INSPECTION, [1])
-     FEATURE_HTTPS_INSPECTION="yes"
+     AC_DEFINE(FEATURE_HTTPS_INSPECTION, 1, [if SSL/TLS is enabled])
+     AC_DEFINE(FEATURE_HTTPS_INSPECTION_MBEDTLS, 1, [if mbedTLS is enabled])
+     AC_SUBST(FEATURE_HTTPS_INSPECTION_MBEDTLS, [1])
+     FEATURE_HTTPS_INSPECTION_MBEDTLS="yes"
    ], [], -lmbedx509 -lmbedcrypto)
 
    ], [], -lmbedx509 -lmbedcrypto)
 
-  if test "x$FEATURE_HTTPS_INSPECTION" = "xyes"; then
+  if test "x$FEATURE_HTTPS_INSPECTION_MBEDTLS" = "xyes"; then
     AC_MSG_NOTICE([Detected mbedTLS. Enabling https inspection.])
 
     LIBS="-lmbedtls -lmbedx509 -lmbedcrypto $LIBS"
     old_CFLAGS_nospecial="-Imbedtls/include $old_CFLAGS_nospecial"
 
     FEATURE_HTTPS_INSPECTION_ONLY=
     AC_MSG_NOTICE([Detected mbedTLS. Enabling https inspection.])
 
     LIBS="-lmbedtls -lmbedx509 -lmbedcrypto $LIBS"
     old_CFLAGS_nospecial="-Imbedtls/include $old_CFLAGS_nospecial"
 
     FEATURE_HTTPS_INSPECTION_ONLY=
+    FEATURE_HTTPS_INSPECTION_ONLY_MBEDTLS=
   fi
 fi
   fi
 fi
-AC_SUBST(FEATURE_HTTPS_INSPECTION_ONLY)
+AC_SUBST(FEATURE_HTTPS_INSPECTION_ONLY_MBEDTLS)
+
+dnl ========================================================
+dnl check for OpenSSL which is required for https inspection
+dnl ========================================================
+FEATURE_HTTPS_INSPECTION_ONLY_OPENSSL=#
+OPT_OPENSSL=no
+AC_ARG_WITH(openssl,dnl
+AC_HELP_STRING([--with-openssl], [Enable OpenSSL detection for https inspection.])
+AC_HELP_STRING([--without-openssl], [Disable OpenSSL detection]),
+  OPT_OPENSSL=$withval)
+
+if test X"$OPT_OPENSSL" != Xno; then
+  if test "$PORTNAME" != "win32"; then
+     AC_CHECK_LIB(crypto, CRYPTO_new_ex_data, [], [AC_MSG_ERROR([library 'crypto' is required for OpenSSL])])
+     FOUND_SSL_LIB="no"
+     AC_CHECK_LIB(ssl, OPENSSL_init_ssl, [FOUND_SSL_LIB="yes"])
+     AC_CHECK_LIB(ssl, SSL_library_init, [FOUND_SSL_LIB="yes"])
+     AS_IF([test "x$FOUND_SSL_LIB" = xno], [AC_MSG_ERROR([library 'ssl' is required for OpenSSL])])
+  else
+     AC_SEARCH_LIBS(CRYPTO_new_ex_data, eay32 crypto, [], [AC_MSG_ERROR([library 'eay32' or 'crypto' is required for OpenSSL])])
+     FOUND_SSL_LIB="no"
+     AC_SEARCH_LIBS(OPENSSL_init_ssl, ssleay32 ssl, [FOUND_SSL_LIB="yes"])
+     AC_SEARCH_LIBS(SSL_library_init, ssleay32 ssl, [FOUND_SSL_LIB="yes"])
+     AS_IF([test "x$FOUND_SSL_LIB" = xno], [AC_MSG_ERROR([library 'ssleay32' or 'ssl' is required for OpenSSL])])
+  fi
 
 
+  if test "x$FOUND_SSL_LIB" = xyes; then
+     AC_DEFINE(FEATURE_HTTPS_INSPECTION, 1, [if SSL/TLS is enabled])
+     AC_DEFINE(FEATURE_HTTPS_INSPECTION_OPENSSL, 1, [if OpenSSL is enabled])
+     AC_SUBST(FEATURE_HTTPS_INSPECTION_OPENSSL, [1])
+     FEATURE_HTTPS_INSPECTION="yes"
+     FEATURE_HTTPS_INSPECTION_OPENSSL="yes"
+  fi
+
+  if test "x$FEATURE_HTTPS_INSPECTION_OPENSSL" = "xyes"; then
+    AC_MSG_NOTICE([Detected OpenSSL. Enabling https inspection.])
+
+    LIBS="$LIBS -lssl -lcrypto"
+#    old_CFLAGS_nospecial="-Imbedtls/include $old_CFLAGS_nospecial"
+    old_CFLAGS_nospecial="$old_CFLAGS_nospecial"
+
+    FEATURE_HTTPS_INSPECTION_ONLY=
+    FEATURE_HTTPS_INSPECTION_ONLY_OPENSSL=
+  fi
+fi
+AC_SUBST(FEATURE_HTTPS_INSPECTION_ONLY_OPENSSL)
+
+AC_SUBST(FEATURE_HTTPS_INSPECTION_ONLY)
 
 dnl ========================================================
 dnl Check for Brotli which can be used for decompression
 
 dnl ========================================================
 dnl Check for Brotli which can be used for decompression
diff --git a/jcc.c b/jcc.c
index 1380100..93af901 100644 (file)
--- a/jcc.c
+++ b/jcc.c
@@ -195,7 +195,7 @@ privoxy_mutex_t connection_reuse_mutex;
 
 #ifdef FEATURE_HTTPS_INSPECTION
 privoxy_mutex_t certificate_mutex;
 
 #ifdef FEATURE_HTTPS_INSPECTION
 privoxy_mutex_t certificate_mutex;
-privoxy_mutex_t rng_mutex;
+privoxy_mutex_t ssl_init_mutex;
 #endif
 
 #ifdef FEATURE_EXTERNAL_FILTERS
 #endif
 
 #ifdef FEATURE_EXTERNAL_FILTERS
@@ -489,7 +489,7 @@ static int client_protocol_is_unsupported(struct client_state *csp, char *req)
 #ifdef FEATURE_HTTPS_INSPECTION
       if (client_use_ssl(csp))
       {
 #ifdef FEATURE_HTTPS_INSPECTION
       if (client_use_ssl(csp))
       {
-         ssl_send_data_delayed(&(csp->mbedtls_client_attr.ssl),
+         ssl_send_data_delayed(&(csp->ssl_client_attr),
             (const unsigned char *)response, strlen(response),
             get_write_delay(csp));
       }
             (const unsigned char *)response, strlen(response),
             get_write_delay(csp));
       }
@@ -871,10 +871,10 @@ static void send_crunch_response(struct client_state *csp, struct http_response
 #ifdef FEATURE_HTTPS_INSPECTION
       if (client_use_ssl(csp))
       {
 #ifdef FEATURE_HTTPS_INSPECTION
       if (client_use_ssl(csp))
       {
-         if ((ssl_send_data_delayed(&(csp->mbedtls_client_attr.ssl),
+         if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
                 (const unsigned char *)rsp->head, rsp->head_length,
                 get_write_delay(csp)) < 0)
                 (const unsigned char *)rsp->head, rsp->head_length,
                 get_write_delay(csp)) < 0)
-          || (ssl_send_data_delayed(&(csp->mbedtls_client_attr.ssl),
+          || (ssl_send_data_delayed(&(csp->ssl_client_attr),
                 (const unsigned char *)rsp->body, rsp->content_length,
                 get_write_delay(csp)) < 0))
          {
                 (const unsigned char *)rsp->body, rsp->content_length,
                 get_write_delay(csp)) < 0))
          {
@@ -2058,7 +2058,7 @@ static int receive_and_send_encrypted_post_data(struct client_state *csp)
 {
    int content_length_known = csp->expected_client_content_length != 0;
 
 {
    int content_length_known = csp->expected_client_content_length != 0;
 
-   while (is_ssl_pending(&(csp->mbedtls_client_attr.ssl))
+   while (is_ssl_pending(&(csp->ssl_client_attr))
       || (content_length_known && csp->expected_client_content_length != 0))
    {
       unsigned char buf[BUFFER_SIZE];
       || (content_length_known && csp->expected_client_content_length != 0))
    {
       unsigned char buf[BUFFER_SIZE];
@@ -2072,7 +2072,7 @@ static int receive_and_send_encrypted_post_data(struct client_state *csp)
       log_error(LOG_LEVEL_CONNECT,
          "Waiting for up to %d bytes of POST data from the client.",
          max_bytes_to_read);
       log_error(LOG_LEVEL_CONNECT,
          "Waiting for up to %d bytes of POST data from the client.",
          max_bytes_to_read);
-      len = ssl_recv_data(&(csp->mbedtls_client_attr.ssl), buf,
+      len = ssl_recv_data(&(csp->ssl_client_attr), buf,
          (unsigned)max_bytes_to_read);
       if (len == -1)
       {
          (unsigned)max_bytes_to_read);
       if (len == -1)
       {
@@ -2085,7 +2085,7 @@ static int receive_and_send_encrypted_post_data(struct client_state *csp)
       }
       log_error(LOG_LEVEL_CONNECT, "Forwarding %d bytes of encrypted POST data",
          len);
       }
       log_error(LOG_LEVEL_CONNECT, "Forwarding %d bytes of encrypted POST data",
          len);
-      len = ssl_send_data(&(csp->mbedtls_server_attr.ssl), buf, (size_t)len);
+      len = ssl_send_data(&(csp->ssl_server_attr), buf, (size_t)len);
       if (len == -1)
       {
          return 1;
       if (len == -1)
       {
          return 1;
@@ -2142,7 +2142,7 @@ static int send_https_request(struct client_state *csp)
     * Write the client's (modified) header to the server
     * (along with anything else that may be in the buffer)
     */
     * Write the client's (modified) header to the server
     * (along with anything else that may be in the buffer)
     */
-   ret = ssl_send_data(&(csp->mbedtls_server_attr.ssl),
+   ret = ssl_send_data(&(csp->ssl_server_attr),
       (const unsigned char *)hdr, strlen(hdr));
    freez(hdr);
 
       (const unsigned char *)hdr, strlen(hdr));
    freez(hdr);
 
@@ -2156,7 +2156,7 @@ static int send_https_request(struct client_state *csp)
    }
 
    if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
    }
 
    if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
-      && ((flushed = ssl_flush_socket(&(csp->mbedtls_server_attr.ssl),
+      && ((flushed = ssl_flush_socket(&(csp->ssl_server_attr),
             csp->client_iob)) < 0))
    {
       log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
             csp->client_iob)) < 0))
    {
       log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
@@ -2222,14 +2222,14 @@ static jb_err receive_encrypted_request(struct client_state *csp)
    do
    {
       log_error(LOG_LEVEL_HEADER, "Reading encrypted headers");
    do
    {
       log_error(LOG_LEVEL_HEADER, "Reading encrypted headers");
-      if (!is_ssl_pending(&(csp->mbedtls_client_attr.ssl)) &&
+      if (!is_ssl_pending(&(csp->ssl_client_attr)) &&
           !data_is_available(csp->cfd, csp->config->socket_timeout))
       {
          log_error(LOG_LEVEL_CONNECT,
             "Socket %d timed out while waiting for client headers", csp->cfd);
          return JB_ERR_PARSE;
       }
           !data_is_available(csp->cfd, csp->config->socket_timeout))
       {
          log_error(LOG_LEVEL_CONNECT,
             "Socket %d timed out while waiting for client headers", csp->cfd);
          return JB_ERR_PARSE;
       }
-      len = ssl_recv_data(&(csp->mbedtls_client_attr.ssl),
+      len = ssl_recv_data(&(csp->ssl_client_attr),
          (unsigned char *)buf, sizeof(buf));
       if (len == -1)
       {
          (unsigned char *)buf, sizeof(buf));
       if (len == -1)
       {
@@ -2276,7 +2276,7 @@ static jb_err process_encrypted_request(struct client_state *csp)
       /* XXX: Also used for JB_ERR_MEMORY */
       log_error(LOG_LEVEL_ERROR, "Failed to receive encrypted request: %s",
          jb_err_to_string(err));
       /* XXX: Also used for JB_ERR_MEMORY */
       log_error(LOG_LEVEL_ERROR, "Failed to receive encrypted request: %s",
          jb_err_to_string(err));
-      ssl_send_data_delayed(&(csp->mbedtls_client_attr.ssl),
+      ssl_send_data_delayed(&(csp->ssl_client_attr),
          (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
       return err;
    }
          (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
       return err;
    }
@@ -2286,7 +2286,7 @@ static jb_err process_encrypted_request(struct client_state *csp)
    if (request_line == NULL)
    {
       log_error(LOG_LEVEL_ERROR, "Failed to get the encrypted request line");
    if (request_line == NULL)
    {
       log_error(LOG_LEVEL_ERROR, "Failed to get the encrypted request line");
-      ssl_send_data_delayed(&(csp->mbedtls_client_attr.ssl),
+      ssl_send_data_delayed(&(csp->ssl_client_attr),
          (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
       return JB_ERR_PARSE;
    }
          (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
       return JB_ERR_PARSE;
    }
@@ -2319,7 +2319,7 @@ static jb_err process_encrypted_request(struct client_state *csp)
    freez(request_line);
    if (JB_ERR_OK != err)
    {
    freez(request_line);
    if (JB_ERR_OK != err)
    {
-      ssl_send_data_delayed(&(csp->mbedtls_client_attr.ssl),
+      ssl_send_data_delayed(&(csp->ssl_client_attr),
          (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
       /* XXX: Use correct size */
       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
          (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
       /* XXX: Use correct size */
       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
@@ -2354,7 +2354,7 @@ static jb_err process_encrypted_request(struct client_state *csp)
        */
       log_error(LOG_LEVEL_ERROR,
          "Failed to get the encrypted request destination");
        */
       log_error(LOG_LEVEL_ERROR,
          "Failed to get the encrypted request destination");
-      ssl_send_data_delayed(&(csp->mbedtls_client_attr.ssl),
+      ssl_send_data_delayed(&(csp->ssl_client_attr),
          (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
       return JB_ERR_PARSE;
    }
          (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
       return JB_ERR_PARSE;
    }
@@ -2390,7 +2390,7 @@ static jb_err process_encrypted_request(struct client_state *csp)
    err = sed_https(csp);
    if (JB_ERR_OK != err)
    {
    err = sed_https(csp);
    if (JB_ERR_OK != err)
    {
-      ssl_send_data_delayed(&(csp->mbedtls_client_attr.ssl),
+      ssl_send_data_delayed(&(csp->ssl_client_attr),
          (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
       log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
          csp->ip_addr_str);
          (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
       log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
          csp->ip_addr_str);
@@ -2799,7 +2799,7 @@ static void handle_established_connection(struct client_state *csp)
           */
          if (server_use_ssl(csp))
          {
           */
          if (server_use_ssl(csp))
          {
-            len = ssl_recv_data(&(csp->mbedtls_server_attr.ssl),
+            len = ssl_recv_data(&(csp->ssl_server_attr),
                (unsigned char *)csp->receive_buffer, csp->receive_buffer_size);
          }
          else
                (unsigned char *)csp->receive_buffer, csp->receive_buffer_size);
          }
          else
@@ -2965,10 +2965,10 @@ static void handle_established_connection(struct client_state *csp)
                    */
                   if (client_use_ssl(csp))
                   {
                    */
                   if (client_use_ssl(csp))
                   {
-                     if ((ssl_send_data_delayed(&(csp->mbedtls_client_attr.ssl),
+                     if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
                               (const unsigned char *)hdr, strlen(hdr),
                               get_write_delay(csp)) < 0)
                               (const unsigned char *)hdr, strlen(hdr),
                               get_write_delay(csp)) < 0)
-                        || (ssl_send_data_delayed(&(csp->mbedtls_client_attr.ssl),
+                        || (ssl_send_data_delayed(&(csp->ssl_client_attr),
                               (const unsigned char *) ((p != NULL) ? p : csp->iob->cur),
                               csp->content_length, get_write_delay(csp)) < 0))
                      {
                               (const unsigned char *) ((p != NULL) ? p : csp->iob->cur),
                               csp->content_length, get_write_delay(csp)) < 0))
                      {
@@ -3068,11 +3068,11 @@ static void handle_established_connection(struct client_state *csp)
                    */
                   if (client_use_ssl(csp))
                   {
                    */
                   if (client_use_ssl(csp))
                   {
-                     if ((ssl_send_data_delayed(&(csp->mbedtls_client_attr.ssl),
+                     if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
                              (const unsigned char *)hdr, hdrlen, get_write_delay(csp)) < 0)
                              (const unsigned char *)hdr, hdrlen, get_write_delay(csp)) < 0)
-                        || ((flushed = ssl_flush_socket(&(csp->mbedtls_client_attr.ssl),
+                        || ((flushed = ssl_flush_socket(&(csp->ssl_client_attr),
                                 csp->iob)) < 0)
                                 csp->iob)) < 0)
-                        || (ssl_send_data_delayed(&(csp->mbedtls_client_attr.ssl),
+                        || (ssl_send_data_delayed(&(csp->ssl_client_attr),
                               (const unsigned char *)csp->receive_buffer, (size_t)len,
                               get_write_delay(csp)) < 0))
                      {
                               (const unsigned char *)csp->receive_buffer, (size_t)len,
                               get_write_delay(csp)) < 0))
                      {
@@ -3119,7 +3119,7 @@ static void handle_established_connection(struct client_state *csp)
                 */
                if (client_use_ssl(csp))
                {
                 */
                if (client_use_ssl(csp))
                {
-                  ret = ssl_send_data_delayed(&(csp->mbedtls_client_attr.ssl),
+                  ret = ssl_send_data_delayed(&(csp->ssl_client_attr),
                      (const unsigned char *)csp->receive_buffer, (size_t)len,
                      get_write_delay(csp));
                   if (ret < 0)
                      (const unsigned char *)csp->receive_buffer, (size_t)len,
                      get_write_delay(csp));
                   if (ret < 0)
@@ -3185,7 +3185,7 @@ static void handle_established_connection(struct client_state *csp)
                    */
                   if (client_use_ssl(csp))
                   {
                    */
                   if (client_use_ssl(csp))
                   {
-                     ssl_send_data_delayed(&(csp->mbedtls_client_attr.ssl),
+                     ssl_send_data_delayed(&(csp->ssl_client_attr),
                         (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
                         strlen(INVALID_SERVER_HEADERS_RESPONSE), get_write_delay(csp));
                   }
                         (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
                         strlen(INVALID_SERVER_HEADERS_RESPONSE), get_write_delay(csp));
                   }
@@ -3279,7 +3279,7 @@ static void handle_established_connection(struct client_state *csp)
                 */
                if (client_use_ssl(csp))
                {
                 */
                if (client_use_ssl(csp))
                {
-                  ssl_send_data_delayed(&(csp->mbedtls_client_attr.ssl),
+                  ssl_send_data_delayed(&(csp->ssl_client_attr),
                      (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
                      strlen(INVALID_SERVER_HEADERS_RESPONSE),
                      get_write_delay(csp));
                      (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
                      strlen(INVALID_SERVER_HEADERS_RESPONSE),
                      get_write_delay(csp));
@@ -3312,7 +3312,7 @@ static void handle_established_connection(struct client_state *csp)
                 */
                if (client_use_ssl(csp))
                {
                 */
                if (client_use_ssl(csp))
                {
-                  ssl_send_data_delayed(&(csp->mbedtls_client_attr.ssl),
+                  ssl_send_data_delayed(&(csp->ssl_client_attr),
                      (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
                      strlen(INVALID_SERVER_HEADERS_RESPONSE),
                      get_write_delay(csp));
                      (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
                      strlen(INVALID_SERVER_HEADERS_RESPONSE),
                      get_write_delay(csp));
@@ -3382,10 +3382,10 @@ static void handle_established_connection(struct client_state *csp)
 #ifdef FEATURE_HTTPS_INSPECTION
                if (client_use_ssl(csp))
                {
 #ifdef FEATURE_HTTPS_INSPECTION
                if (client_use_ssl(csp))
                {
-                  if ((ssl_send_data_delayed(&(csp->mbedtls_client_attr.ssl),
+                  if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
                           (const unsigned char *)hdr, strlen(hdr),
                           get_write_delay(csp)) < 0)
                           (const unsigned char *)hdr, strlen(hdr),
                           get_write_delay(csp)) < 0)
-                     || (len = ssl_flush_socket(&(csp->mbedtls_client_attr.ssl),
+                     || (len = ssl_flush_socket(&(csp->ssl_client_attr),
                             csp->iob) < 0))
                   {
                      log_error(LOG_LEVEL_CONNECT, "Write header to client failed");
                             csp->iob) < 0))
                   {
                      log_error(LOG_LEVEL_CONNECT, "Write header to client failed");
@@ -3444,7 +3444,7 @@ static void handle_established_connection(struct client_state *csp)
                 */
                if (client_use_ssl(csp))
                {
                 */
                if (client_use_ssl(csp))
                {
-                  ssl_send_data_delayed(&(csp->mbedtls_client_attr.ssl),
+                  ssl_send_data_delayed(&(csp->ssl_client_attr),
                      (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
                      strlen(INVALID_SERVER_HEADERS_RESPONSE),
                      get_write_delay(csp));
                      (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
                      strlen(INVALID_SERVER_HEADERS_RESPONSE),
                      get_write_delay(csp));
@@ -4559,7 +4559,7 @@ static void initialize_mutexes(void)
 
 #ifdef FEATURE_HTTPS_INSPECTION
    privoxy_mutex_init(&certificate_mutex);
 
 #ifdef FEATURE_HTTPS_INSPECTION
    privoxy_mutex_init(&certificate_mutex);
-   privoxy_mutex_init(&rng_mutex);
+   privoxy_mutex_init(&ssl_init_mutex);
 #endif
 
    privoxy_mutex_init(&log_mutex);
 #endif
 
    privoxy_mutex_init(&log_mutex);
@@ -5603,11 +5603,7 @@ static void listen_loop(void)
 
 #ifdef FEATURE_HTTPS_INSPECTION
    /* Clean up.  Aim: free all memory (no leaks) */
 
 #ifdef FEATURE_HTTPS_INSPECTION
    /* Clean up.  Aim: free all memory (no leaks) */
-   if (rng_seeded == 1)
-   {
-      mbedtls_ctr_drbg_free(&ctr_drbg);
-      mbedtls_entropy_free(&entropy);
-   }
+   ssl_release();
 #endif
 
 #ifdef FEATURE_GRACEFUL_TERMINATION
 #endif
 
 #ifdef FEATURE_GRACEFUL_TERMINATION
diff --git a/jcc.h b/jcc.h
index ad68f42..3e17042 100644 (file)
--- a/jcc.h
+++ b/jcc.h
@@ -109,7 +109,7 @@ extern privoxy_mutex_t rand_mutex;
 
 #ifdef FEATURE_HTTPS_INSPECTION
 extern privoxy_mutex_t certificate_mutex;
 
 #ifdef FEATURE_HTTPS_INSPECTION
 extern privoxy_mutex_t certificate_mutex;
-extern privoxy_mutex_t rng_mutex;
+extern privoxy_mutex_t ssl_init_mutex;
 #endif
 
 #endif /* FEATURE_PTHREAD */
 #endif
 
 #endif /* FEATURE_PTHREAD */
diff --git a/openssl.c b/openssl.c
new file mode 100644 (file)
index 0000000..bf8f3fe
--- /dev/null
+++ b/openssl.c
@@ -0,0 +1,1918 @@
+/*********************************************************************
+ *
+ * File        :  $Source: $
+ *
+ * Purpose     :  File with TLS/SSL extension. Contains methods for
+ *                creating, using and closing TLS/SSL connections.
+ *
+ * Copyright   :  Written by and Copyright (c) 2020 Maxim Antonov <mantonov@gmail.com>
+ *
+ *                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 2 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.
+ *
+ *                The GNU General Public License should be included with
+ *                this file.  If not, you can view it at
+ *                http://www.gnu.org/copyleft/gpl.html
+ *                or write to the Free Software Foundation, Inc., 59
+ *                Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ *
+ *********************************************************************/
+
+#include <string.h>
+#include <unistd.h>
+
+#include <openssl/bn.h>
+#include <openssl/opensslv.h>
+#include <openssl/pem.h>
+#include <openssl/md5.h>
+#include <openssl/x509v3.h>
+
+#include "config.h"
+#include "project.h"
+#include "miscutil.h"
+#include "errlog.h"
+#include "encode.h"
+#include "jcc.h"
+#include "ssl.h"
+#include "ssl_common.h"
+
+/*
+ * Macros for openssl.c
+ */
+#define CERTIFICATE_BASIC_CONSTRAINTS            "CA:FALSE"
+#define CERTIFICATE_SUBJECT_KEY                  "hash"
+#define CERTIFICATE_AUTHORITY_KEY                "keyid:always"
+#define CERTIFICATE_ALT_NAME_PREFIX              "DNS:"
+#define CERTIFICATE_VERSION                      2
+#define VALID_DATETIME_FMT                       "%Y%m%d%H%M%SZ"
+#define VALID_DATETIME_BUFLEN                    16
+
+static int generate_webpage_certificate(struct client_state *csp);
+static void free_client_ssl_structures(struct client_state *csp);
+static void free_server_ssl_structures(struct client_state *csp);
+static int ssl_store_cert(struct client_state *csp, X509* crt);
+static void log_ssl_errors(int debuglevel, const char* fmt, ...) __attribute__((format(printf, 2, 3)));
+
+static int ssl_inited = 0;
+
+/*********************************************************************
+ *
+ * Function    :  openssl_init
+ *
+ * Description :  INitializes OpenSSL library once
+ *
+ * Parameters  :  N/A
+ *
+ * Returns     :  N/A
+ *
+ *********************************************************************/
+static void openssl_init(void)
+{
+   if (ssl_inited == 0)
+   {
+      privoxy_mutex_lock(&ssl_init_mutex);
+      if (ssl_inited == 0)
+      {
+#if OPENSSL_VERSION_NUMBER < 0x10100000L
+         SSL_library_init();
+#else
+         OPENSSL_init_ssl(0, NULL);
+#endif
+         SSL_load_error_strings();
+         OpenSSL_add_ssl_algorithms();
+         ssl_inited = 1;
+      }
+      privoxy_mutex_unlock(&ssl_init_mutex);
+   }
+}
+
+
+/*********************************************************************
+ *
+ * Function    :  is_ssl_pending
+ *
+ * Description :  Tests if there are some waiting data on ssl connection.
+ *                Only considers data that has actually been received
+ *                locally and ignores data that is still on the fly
+ *                or has not yet been sent by the remote end.
+ *
+ * Parameters  :
+ *          1  :  ssl = SSL context to test
+ *
+ * Returns     :   0 => No data are pending
+ *                >0 => Pending data length
+ *
+ *********************************************************************/
+extern size_t is_ssl_pending(struct ssl_attr *ssl_attr)
+{
+   BIO *bio = ssl_attr->openssl_attr.bio;
+   if (bio == NULL)
+   {
+      return 0;
+   }
+
+   return (size_t)BIO_pending(bio);
+}
+
+
+/*********************************************************************
+ *
+ * Function    :  ssl_send_data
+ *
+ * Description :  Sends the content of buf (for n bytes) to given SSL
+ *                connection context.
+ *
+ * Parameters  :
+ *          1  :  ssl = SSL context to send data to
+ *          2  :  buf = Pointer to data to be sent
+ *          3  :  len = Length of data to be sent to the SSL context
+ *
+ * Returns     :  Length of sent data or negative value on error.
+ *
+ *********************************************************************/
+extern int ssl_send_data(struct ssl_attr *ssl_attr, const unsigned char *buf, size_t len)
+{
+   BIO *bio = ssl_attr->openssl_attr.bio;
+   int ret = 0;
+   int pos                  = 0;  /* Position of unsent part in buffer */
+
+   if (len == 0)
+   {
+      return 0;
+   }
+
+   while (pos < len)
+   {
+      int send_len = (int)len - pos;
+
+      log_error(LOG_LEVEL_WRITING, "TLS: %N", send_len, buf+pos);
+
+      /*
+       * Sending one part of the buffer
+       */
+      while ((ret = BIO_write(bio,
+         (const unsigned char *)(buf + pos),
+         send_len)) < 0)
+      {
+         if (!BIO_should_retry(bio))
+         {
+            log_ssl_errors(LOG_LEVEL_ERROR,
+               "Sending data over TLS/SSL failed");
+            return -1;
+         }
+      }
+      /* Adding count of sent bytes to position in buffer */
+      pos = pos + ret;
+   }
+
+   return (int)len;
+}
+
+
+/*********************************************************************
+ *
+ * Function    :  ssl_recv_data
+ *
+ * Description :  Receives data from given SSL context and puts
+ *                it into buffer.
+ *
+ * Parameters  :
+ *          1  :  ssl = SSL context to receive data from
+ *          2  :  buf = Pointer to buffer where data will be written
+ *          3  :  max_length = Maximum number of bytes to read
+ *
+ * Returns     :  Number of bytes read, 0 for EOF, or -1
+ *                on error.
+ *
+ *********************************************************************/
+extern int ssl_recv_data(struct ssl_attr *ssl_attr, unsigned char *buf, size_t max_length)
+{
+   BIO *bio = ssl_attr->openssl_attr.bio;
+   int ret = 0;
+   memset(buf, 0, max_length);
+
+   /*
+    * Receiving data from SSL context into buffer
+    */
+   do
+   {
+      ret = BIO_read(bio, buf, (int)max_length);
+   } while (ret <= 0 && BIO_should_retry(bio));
+
+   if (ret < 0)
+   {
+      log_ssl_errors(LOG_LEVEL_ERROR,
+         "Receiving data over TLS/SSL failed");
+
+      return -1;
+   }
+
+   log_error(LOG_LEVEL_RECEIVED, "TLS: %N", ret, buf);
+
+   return ret;
+}
+
+
+/*********************************************************************
+ *
+ * Function    :  ssl_store_cert
+ *
+ * Description :  This is a callback function for certificate verification.
+ *                It's called once for each certificate in the server's
+ *                certificate trusted chain and prepares information about
+ *                the certificate. The information can be used to inform
+ *                the user about invalid certificates.
+ *
+ * Parameters  :
+ *          1  :  csp = Current client state (buffers, headers, etc...)
+ *          2  :  crt   = certificate from trusted chain
+ *
+ * Returns     :  0 on success and negative value on error
+ *
+ *********************************************************************/
+static int ssl_store_cert(struct client_state *csp, X509* crt)
+{
+   long len = 0;
+   struct certs_chain  *last = &(csp->server_certs_chain);
+   int ret = 0;
+   BIO *bio = BIO_new(BIO_s_mem());
+   EVP_PKEY *pkey = NULL;
+   char *bio_mem_data = 0;
+   char *encoded_text;
+   long l;
+   const ASN1_INTEGER *bs;
+   const X509_ALGOR *tsig_alg;
+   int loc;
+
+   if (!bio)
+   {
+      log_ssl_errors(LOG_LEVEL_ERROR, "BIO_new_mem_buf() failed");
+      return -1;
+   }
+
+   /*
+    * Searching for last item in certificates linked list
+    */
+   while (last->next != NULL)
+   {
+      last = last->next;
+   }
+
+   /*
+    * Preparing next item in linked list for next certificate
+    */
+   last->next = malloc_or_die(sizeof(struct certs_chain));
+   last->next->next = NULL;
+   memset(last->next->info_buf, 0, sizeof(last->next->info_buf));
+   memset(last->next->file_buf, 0, sizeof(last->next->file_buf));
+
+   /*
+    * Saving certificate file into buffer
+    */
+   if (!PEM_write_bio_X509(bio, crt))
+   {
+      log_ssl_errors(LOG_LEVEL_ERROR, "PEM_write_X509() failed");
+      ret = -1;
+      goto exit;
+   }
+
+   len = BIO_get_mem_data(bio, &bio_mem_data);
+
+   if (len > (sizeof(last->file_buf) - 1))
+   {
+      log_error(LOG_LEVEL_ERROR,
+                "X509 PEM cert len %d is larger then buffer len %s", len, sizeof(last->file_buf) - 1);
+      len = sizeof(last->file_buf) - 1;
+   }
+
+   strncpy(last->file_buf, bio_mem_data, (size_t)len);
+   BIO_free(bio);
+   bio = BIO_new(BIO_s_mem());
+   if (!bio)
+   {
+      log_ssl_errors(LOG_LEVEL_ERROR, "BIO_new_mem_buf() failed");
+      ret = -1;
+      goto exit;
+   }
+
+   /*
+    * Saving certificate information into buffer
+    */
+   l = X509_get_version(crt);
+   if (l >= 0 && l <= 2) {
+      if (BIO_printf(bio, "cert. version     : %ld\n", l + 1) <= 0) {
+         log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for version failed");
+         ret = -1;
+         goto exit;
+      }
+   } else {
+      if (BIO_printf(bio, "cert. version     : Unknown (%ld)\n", l) <= 0) {
+         log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for version failed");
+         ret = -1;
+         goto exit;
+      }
+   }
+
+   if (BIO_puts(bio, "serial number     : ") <= 0) {
+      log_ssl_errors(LOG_LEVEL_ERROR, "BIO_write() for serial failed");
+      ret = -1;
+      goto exit;
+   }
+   bs = X509_get0_serialNumber(crt);
+   if (bs->length <= (int)sizeof(long)) {
+      ERR_set_mark();
+      l = ASN1_INTEGER_get(bs);
+      ERR_pop_to_mark();
+   } else {
+      l = -1;
+   }
+   if (l != -1) {
+      unsigned long ul;
+      const char *neg;
+      if (bs->type == V_ASN1_NEG_INTEGER) {
+         ul = 0 - (unsigned long)l;
+         neg = "-";
+      } else {
+         ul = (unsigned long)l;
+         neg = "";
+      }
+      if (BIO_printf(bio, " %s%lu (%s0x%lx)\n", neg, ul, neg, ul) <= 0) {
+         log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for serial failed");
+         ret = -1;
+         goto exit;
+      }
+   } else {
+      if (bs->type == V_ASN1_NEG_INTEGER) {
+         if (BIO_puts(bio, " (Negative)") < 0) {
+            log_ssl_errors(LOG_LEVEL_ERROR, "BIO_puts() for serial failed");
+            ret = -1;
+            goto exit;
+         }
+      }
+      for (int i = 0; i < bs->length; i++) {
+         if (BIO_printf(bio, "%02x%c", bs->data[i],
+                        ((i + 1 == bs->length) ? '\n' : ':')) <= 0) {
+            log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for serial failed");
+            ret = -1;
+            goto exit;
+         }
+      }
+   }
+
+   if (BIO_puts(bio, "issuer name       : ") <= 0) {
+      log_ssl_errors(LOG_LEVEL_ERROR, "BIO_puts() for issuer failed");
+      ret = -1;
+      goto exit;
+   }
+   if (X509_NAME_print_ex(bio, X509_get_issuer_name(crt), 0, 0) < 0) {
+      log_ssl_errors(LOG_LEVEL_ERROR, "X509_NAME_print_ex() for issuer failed");
+      ret = -1;
+      goto exit;
+   }
+
+   if (BIO_puts(bio, "\nsubject name      : ") <= 0) {
+      log_ssl_errors(LOG_LEVEL_ERROR, "BIO_puts() for sublect failed");
+      ret = -1;
+      goto exit;
+   }
+   if (X509_NAME_print_ex(bio, X509_get_subject_name(crt), 0, 0) < 0) {
+      log_ssl_errors(LOG_LEVEL_ERROR, "X509_NAME_print_ex() for subject failed");
+      ret = -1;
+      goto exit;
+   }
+
+   if (BIO_puts(bio, "\nissued  on        : ") <= 0) {
+      log_ssl_errors(LOG_LEVEL_ERROR, "BIO_puts() for issued on failed");
+      ret = -1;
+      goto exit;
+   }
+   if (!ASN1_TIME_print(bio, X509_get0_notBefore(crt))) {
+      log_ssl_errors(LOG_LEVEL_ERROR, "ASN1_TIME_print() for issued on failed");
+      ret = -1;
+      goto exit;
+   }
+
+   if (BIO_puts(bio, "\nexpires on        : ") <= 0) {
+      log_ssl_errors(LOG_LEVEL_ERROR, "BIO_puts() for expires on failed");
+      ret = -1;
+      goto exit;
+   }
+   if (!ASN1_TIME_print(bio, X509_get0_notAfter(crt))) {
+      log_ssl_errors(LOG_LEVEL_ERROR, "ASN1_TIME_print() for expires on failed");
+      ret = -1;
+      goto exit;
+   }
+
+   if (BIO_puts(bio, "\nsigned using      : ") <= 0) {
+      log_ssl_errors(LOG_LEVEL_ERROR, "BIO_puts() for signed using failed");
+      ret = -1;
+      goto exit;
+   }
+   tsig_alg = X509_get0_tbs_sigalg(crt);
+   if (!i2a_ASN1_OBJECT(bio, tsig_alg->algorithm)) {
+      log_ssl_errors(LOG_LEVEL_ERROR, "i2a_ASN1_OBJECT() for signed using on failed");
+      ret = -1;
+      goto exit;
+   }
+   pkey = X509_get_pubkey(crt);
+   if (!pkey) {
+      log_ssl_errors(LOG_LEVEL_ERROR, "X509_get_pubkey() failed");
+      ret = -1;
+      goto exit;
+   }
+#define BC              "18"
+   switch (EVP_PKEY_base_id(pkey)) {
+   case EVP_PKEY_RSA:
+      ret = BIO_printf(bio, "\n%-" BC "s: %d bits", "RSA key size", EVP_PKEY_bits(pkey));
+      break;
+   case EVP_PKEY_DSA:
+      ret = BIO_printf(bio, "\n%-" BC "s: %d bits", "DSA key size", EVP_PKEY_bits(pkey));
+      break;
+   default:
+      ret = BIO_printf(bio, "\n%-" BC "s: %d bits", "non-RSA/DSA key size", EVP_PKEY_bits(pkey));
+      break;
+   }
+   if (ret <= 0) {
+      log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for key size failed");
+      ret = -1;
+      goto exit;
+   }
+
+   loc = X509_get_ext_by_NID(crt, NID_basic_constraints, -1);
+   if (loc != -1) {
+      X509_EXTENSION *ex = X509_get_ext(crt, loc);
+      if (BIO_puts(bio, "\nbasic constraints : ") <= 0) {
+         log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for basic constraints failed");
+         ret = -1;
+         goto exit;
+      }
+      if (!X509V3_EXT_print(bio, ex, 0, 0)) {
+         if (!ASN1_STRING_print_ex(bio, X509_EXTENSION_get_data(ex), ASN1_STRFLGS_RFC2253)) {
+            log_ssl_errors(LOG_LEVEL_ERROR, "ASN1_STRING_print_ex() for basic constraints failed");
+            ret = -1;
+            goto exit;
+         }
+      }
+   }
+
+   loc = X509_get_ext_by_NID(crt, NID_subject_alt_name, -1);
+   if (loc != -1) {
+      X509_EXTENSION *ex = X509_get_ext(crt, loc);
+      if (BIO_puts(bio, "\nsubject alt name  : ") <= 0) {
+         log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for alt name failed");
+         ret = -1;
+         goto exit;
+      }
+      if (!X509V3_EXT_print(bio, ex, 0, 0)) {
+         if (!ASN1_STRING_print_ex(bio, X509_EXTENSION_get_data(ex), ASN1_STRFLGS_RFC2253)) {
+            log_ssl_errors(LOG_LEVEL_ERROR, "ASN1_STRING_print_ex() for alt name failed");
+            ret = -1;
+            goto exit;
+         }
+      }
+   }
+
+   loc = X509_get_ext_by_NID(crt, NID_netscape_cert_type, -1);
+   if (loc != -1) {
+      X509_EXTENSION *ex = X509_get_ext(crt, loc);
+      if (BIO_puts(bio, "\ncert. type        : ") <= 0) {
+         log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for cert type failed");
+         ret = -1;
+         goto exit;
+      }
+      if (!X509V3_EXT_print(bio, ex, 0, 0)) {
+         if (!ASN1_STRING_print_ex(bio, X509_EXTENSION_get_data(ex), ASN1_STRFLGS_RFC2253)) {
+            log_ssl_errors(LOG_LEVEL_ERROR, "ASN1_STRING_print_ex() for cert type failed");
+            ret = -1;
+            goto exit;
+         }
+      }
+   }
+
+   loc = X509_get_ext_by_NID(crt, NID_key_usage, -1);
+   if (loc != -1) {
+      X509_EXTENSION *ex = X509_get_ext(crt, loc);
+      if (BIO_puts(bio, "\nkey usage         : ") <= 0) {
+         log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for key usage failed");
+         ret = -1;
+         goto exit;
+      }
+      if (!X509V3_EXT_print(bio, ex, 0, 0)) {
+         if (!ASN1_STRING_print_ex(bio, X509_EXTENSION_get_data(ex), ASN1_STRFLGS_RFC2253)) {
+            log_ssl_errors(LOG_LEVEL_ERROR, "ASN1_STRING_print_ex() for key usage failed");
+            ret = -1;
+            goto exit;
+         }
+      }
+   }
+
+   loc = X509_get_ext_by_NID(crt, NID_ext_key_usage, -1);
+   if (loc != -1) {
+      X509_EXTENSION *ex = X509_get_ext(crt, loc);
+      if (BIO_puts(bio, "\next key usage     : ") <= 0) {
+         log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for ext key usage failed");
+         ret = -1;
+         goto exit;
+      }
+      if (!X509V3_EXT_print(bio, ex, 0, 0)) {
+         if (!ASN1_STRING_print_ex(bio, X509_EXTENSION_get_data(ex), ASN1_STRFLGS_RFC2253)) {
+            log_ssl_errors(LOG_LEVEL_ERROR, "ASN1_STRING_print_ex() for ext key usage failed");
+            ret = -1;
+            goto exit;
+         }
+      }
+   }
+
+   loc = X509_get_ext_by_NID(crt, NID_certificate_policies, -1);
+   if (loc != -1) {
+      X509_EXTENSION *ex = X509_get_ext(crt, loc);
+      if (BIO_puts(bio, "\ncertificate policies : ") <= 0) {
+         log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for certificate policies failed");
+         ret = -1;
+         goto exit;
+      }
+      if (!X509V3_EXT_print(bio, ex, 0, 0)) {
+         if (!ASN1_STRING_print_ex(bio, X509_EXTENSION_get_data(ex), ASN1_STRFLGS_RFC2253)) {
+            log_ssl_errors(LOG_LEVEL_ERROR, "ASN1_STRING_print_ex() for certificate policies failed");
+            ret = -1;
+            goto exit;
+         }
+      }
+   }
+
+   /* make valgrind happy */
+   static const char zero = 0;
+   BIO_write(bio, &zero, 1);
+
+   len = BIO_get_mem_data(bio, &bio_mem_data);
+   encoded_text = html_encode(bio_mem_data);
+   strlcpy(last->info_buf, encoded_text, sizeof(last->info_buf));
+   freez(encoded_text);
+   ret = 0;
+
+exit:
+   if (bio) BIO_free(bio);
+   if (pkey) EVP_PKEY_free(pkey);
+   return ret;
+}
+
+/*********************************************************************
+ *
+ * Function    :  host_to_hash
+ *
+ * Description :  Creates MD5 hash from host name. Host name is loaded
+ *                from structure csp and saved again into it.
+ *
+ * Parameters  :
+ *          1  :  csp = Current client state (buffers, headers, etc...)
+ *
+ * Returns     :  1 => Error while creating hash
+ *                0 => Hash created successfully
+ *
+ *********************************************************************/
+static int host_to_hash(struct client_state *csp)
+{
+   int ret = 0;
+
+   memset(csp->http->hash_of_host, 0, sizeof(csp->http->hash_of_host));
+   MD5((unsigned char *)csp->http->host, strlen(csp->http->host),
+      csp->http->hash_of_host);
+
+   /* Converting hash into string with hex */
+   size_t i = 0;
+   for (; i < 16; i++)
+   {
+      if ((ret = sprintf((char *)csp->http->hash_of_host_hex + 2 * i, "%02x",
+         csp->http->hash_of_host[i])) < 0)
+      {
+         log_error(LOG_LEVEL_ERROR, "Sprintf return value: %d", ret);
+         return -1;
+      }
+   }
+
+   return 0;
+}
+
+/*********************************************************************
+ *
+ * Function    :  create_client_ssl_connection
+ *
+ * Description :  Creates TLS/SSL secured connection with client
+ *
+ * Parameters  :
+ *          1  :  csp = Current client state (buffers, headers, etc...)
+ *
+ * Returns     :  0 on success, negative value if connection wasn't created
+ *                successfully.
+ *
+ *********************************************************************/
+extern int create_client_ssl_connection(struct client_state *csp)
+{
+   struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
+   /* Paths to certificates file and key file */
+   char *key_file  = NULL;
+   char *ca_file   = NULL;
+   char *cert_file = NULL;
+   int ret = 0;
+   SSL* ssl;
+
+   /*
+    * Initializing mbedtls structures for TLS/SSL connection
+    */
+   openssl_init();
+
+   /*
+    * Preparing hash of host for creating certificates
+    */
+   ret = host_to_hash(csp);
+   if (ret != 0)
+   {
+      log_error(LOG_LEVEL_ERROR, "Generating hash of host failed: %d", ret);
+      ret = -1;
+      goto exit;
+   }
+
+   /*
+    * Preparing paths to certificates files and key file
+    */
+   ca_file   = csp->config->ca_cert_file;
+   cert_file = make_certs_path(csp->config->certificate_directory,
+      (const char *)csp->http->hash_of_host_hex, CERT_FILE_TYPE);
+   key_file  = make_certs_path(csp->config->certificate_directory,
+      (const char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
+
+   if (cert_file == NULL || key_file == NULL)
+   {
+      ret = -1;
+      goto exit;
+   }
+
+   /*
+    * Generating certificate for requested host. Mutex to prevent
+    * certificate and key inconsistence must be locked.
+    */
+   privoxy_mutex_lock(&certificate_mutex);
+
+   ret = generate_webpage_certificate(csp);
+   if (ret < 0)
+   {
+      log_error(LOG_LEVEL_ERROR,
+         "Generate_webpage_certificate failed: %d", ret);
+      privoxy_mutex_unlock(&certificate_mutex);
+      ret = -1;
+      goto exit;
+   }
+   privoxy_mutex_unlock(&certificate_mutex);
+
+   if (!(ssl_attr->openssl_attr.ctx = SSL_CTX_new(SSLv23_server_method()))) {
+      log_ssl_errors(LOG_LEVEL_ERROR, "Unable to create SSL context");
+      ret = -1;
+      goto exit;
+   }
+
+      /* Set the key and cert */
+   if (SSL_CTX_use_certificate_file(ssl_attr->openssl_attr.ctx,
+                                    cert_file, SSL_FILETYPE_PEM) != 1) {
+      log_ssl_errors(LOG_LEVEL_ERROR, "Loading webpage certificate %s failed", cert_file);
+      ret = -1;
+      goto exit;
+   }
+
+   if (SSL_CTX_use_PrivateKey_file(ssl_attr->openssl_attr.ctx, key_file, SSL_FILETYPE_PEM) != 1) {
+      log_ssl_errors(LOG_LEVEL_ERROR, "Loading webpage certificate private key %s failed", key_file);
+      ret = -1;
+      goto exit;
+   }
+
+   SSL_CTX_set_options(ssl_attr->openssl_attr.ctx, SSL_OP_NO_SSLv3);
+
+   if (!(ssl_attr->openssl_attr.bio = BIO_new_ssl(ssl_attr->openssl_attr.ctx, 0))) {
+      log_ssl_errors(LOG_LEVEL_ERROR, "Unable to create BIO structure");
+      ret = -1;
+      goto exit;
+   }
+
+   if (BIO_get_ssl(ssl_attr->openssl_attr.bio, &ssl) != 1)
+   {
+      log_ssl_errors(LOG_LEVEL_ERROR, "BIO_get_ssl failed");
+      ret = -1;
+      goto exit;
+   }
+
+   if(!SSL_set_fd(ssl, csp->cfd))
+   {
+      log_ssl_errors(LOG_LEVEL_ERROR, "SSL_set_fd failed");
+      ret = -1;
+      goto exit;
+   }
+
+   /*
+    *  Handshake with client
+    */
+   log_error(LOG_LEVEL_CONNECT,
+      "Performing the TLS/SSL handshake with client. Hash of host: %s",
+      csp->http->hash_of_host_hex);
+   if (BIO_do_handshake(ssl_attr->openssl_attr.bio) != 1) {
+       log_ssl_errors(LOG_LEVEL_ERROR, "BIO_do_handshake failed");
+       ret = -1;
+       goto exit;
+   }
+
+   log_error(LOG_LEVEL_CONNECT, "Client successfully connected over TLS/SSL");
+   csp->ssl_with_client_is_opened = 1;
+   ret = 0;
+
+exit:
+   /*
+    * Freeing allocated paths to files
+    */
+   freez(cert_file);
+   freez(key_file);
+
+   /* Freeing structures if connection wasn't created successfully */
+   if (ret < 0)
+   {
+      free_client_ssl_structures(csp);
+   }
+   return ret;
+}
+
+
+/*********************************************************************
+ *
+ * Function    :  close_client_ssl_connection
+ *
+ * Description :  Closes TLS/SSL connection with client. This function
+ *                checks if this connection is already created.
+ *
+ * Parameters  :
+ *          1  :  csp = Current client state (buffers, headers, etc...)
+ *
+ * Returns     :  N/A
+ *
+ *********************************************************************/
+extern void close_client_ssl_connection(struct client_state *csp)
+{
+   struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
+
+   if (csp->ssl_with_client_is_opened == 0)
+   {
+      return;
+   }
+
+   /*
+    * Notifying the peer that the connection is being closed.
+    */
+   BIO_ssl_shutdown(ssl_attr->openssl_attr.bio);
+   free_client_ssl_structures(csp);
+   csp->ssl_with_client_is_opened = 0;
+}
+
+
+/*********************************************************************
+ *
+ * Function    :  free_client_ssl_structures
+ *
+ * Description :  Frees structures used for SSL communication with
+ *                client.
+ *
+ * Parameters  :
+ *          1  :  csp = Current client state (buffers, headers, etc...)
+ *
+ * Returns     :  N/A
+ *
+ *********************************************************************/
+static void free_client_ssl_structures(struct client_state *csp)
+{
+   struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
+
+   if (ssl_attr->openssl_attr.bio) BIO_free_all(ssl_attr->openssl_attr.bio);
+   if (ssl_attr->openssl_attr.ctx) SSL_CTX_free(ssl_attr->openssl_attr.ctx);
+}
+
+
+/*********************************************************************
+ *
+ * Function    :  close_server_ssl_connection
+ *
+ * Description :  Closes TLS/SSL connection with server. This function
+ *                checks if this connection is already opened.
+ *
+ * Parameters  :
+ *          1  :  csp = Current client state (buffers, headers, etc...)
+ *
+ * Returns     :  N/A
+ *
+ *********************************************************************/
+extern void close_server_ssl_connection(struct client_state *csp)
+{
+   struct ssl_attr *ssl_attr = &csp->ssl_server_attr;
+
+   if (csp->ssl_with_server_is_opened == 0)
+   {
+      return;
+   }
+
+   /*
+   * Notifying the peer that the connection is being closed.
+   */
+   BIO_ssl_shutdown(ssl_attr->openssl_attr.bio);
+   free_server_ssl_structures(csp);
+   csp->ssl_with_server_is_opened = 0;
+}
+
+
+/*********************************************************************
+ *
+ * Function    :  create_server_ssl_connection
+ *
+ * Description :  Creates TLS/SSL secured connection with server.
+ *
+ * Parameters  :
+ *          1  :  csp = Current client state (buffers, headers, etc...)
+ *
+ * Returns     :  0 on success, negative value if connection wasn't created
+ *                successfully.
+ *
+ *********************************************************************/
+extern int create_server_ssl_connection(struct client_state *csp)
+{
+   openssl_connection_attr *ssl_attrs = &csp->ssl_server_attr.openssl_attr;
+   int ret = 0;
+   char *trusted_cas_file = NULL;
+   STACK_OF(X509) *chain;
+   SSL *ssl;
+
+   csp->server_cert_verification_result = SSL_CERT_NOT_VERIFIED;
+   csp->server_certs_chain.next = NULL;
+
+   /* Setting path to file with trusted CAs */
+   trusted_cas_file = csp->config->trusted_cas_file;
+
+
+   ssl_attrs->ctx = SSL_CTX_new(SSLv23_method());
+   if (!ssl_attrs->ctx)
+   {
+      log_ssl_errors(LOG_LEVEL_ERROR, "SSL context creation failed");
+      ret = -1;
+      goto exit;
+   }
+
+   /*
+    * Loading file with trusted CAs
+    */
+   if(!SSL_CTX_load_verify_locations(ssl_attrs->ctx, trusted_cas_file, NULL))
+   {
+      log_ssl_errors(LOG_LEVEL_ERROR, "Loading trusted CAs file %s failed",
+         trusted_cas_file);
+      ret = -1;
+      goto exit;
+   }
+
+   SSL_CTX_set_verify(ssl_attrs->ctx, SSL_VERIFY_NONE, NULL);
+   SSL_CTX_set_options(ssl_attrs->ctx, SSL_OP_NO_SSLv3);
+
+   if (!(ssl_attrs->bio = BIO_new_ssl(ssl_attrs->ctx, 1))) {
+      log_ssl_errors(LOG_LEVEL_ERROR, "Unable to create BIO structure");
+      ret = -1;
+      goto exit;
+   }
+
+   if (BIO_get_ssl(ssl_attrs->bio, &ssl) != 1)
+   {
+      log_ssl_errors(LOG_LEVEL_ERROR, "BIO_get_ssl failed");
+      ret = -1;
+      goto exit;
+   }
+
+   if (!SSL_set_fd(ssl, csp->server_connection.sfd))
+   {
+      log_ssl_errors(LOG_LEVEL_ERROR, "SSL_set_fd failed");
+      ret = -1;
+      goto exit;
+   }
+
+   /*
+    * Set the hostname to check against the received server certificate
+    */
+   if (!SSL_set1_host(ssl, csp->http->host))
+   {
+      log_ssl_errors(LOG_LEVEL_ERROR, "SSL_set1_host failed");
+      ret = -1;
+      goto exit;
+   }
+
+   /* SNI extension */
+   if (!SSL_set_tlsext_host_name(ssl, csp->http->host))
+   {
+      log_ssl_errors(LOG_LEVEL_ERROR, "SSL_set_tlsext_host_name failed");
+      ret = -1;
+      goto exit;
+   }
+
+   /*
+    * Handshake with server
+    */
+   log_error(LOG_LEVEL_CONNECT,
+      "Performing the TLS/SSL handshake with the server");
+
+   if (BIO_do_handshake(ssl_attrs->bio) != 1)
+   {
+      log_ssl_errors(LOG_LEVEL_ERROR, "BIO_do_handshake failed");
+      ret = -1;
+      goto exit;
+   }
+
+   chain = SSL_get_peer_cert_chain(ssl);
+   if (chain) {
+      for (int i = 0; i < sk_X509_num(chain); i++) {
+         if (ssl_store_cert(csp, sk_X509_value(chain, i)) != 0) {
+            log_error(LOG_LEVEL_ERROR, "ssl_store_cert failed");
+            ret = -1;
+            goto exit;
+         }
+      }
+   }
+
+   if (!csp->dont_verify_certificate)
+   {
+      long verify_result = SSL_get_verify_result(ssl);
+      if (verify_result == X509_V_OK)
+      {
+         ret = 0;
+         csp->server_cert_verification_result = SSL_CERT_VALID;
+      } else {
+         csp->server_cert_verification_result = verify_result;
+         log_error(LOG_LEVEL_ERROR, "SSL_get_verify_result failed: %s",
+                    X509_verify_cert_error_string(verify_result));
+         ret = -1;
+         goto exit;
+      }
+   }
+
+   log_error(LOG_LEVEL_CONNECT, "Server successfully connected over TLS/SSL");
+
+   /*
+    * Server certificate chain is valid, so we can clean
+    * chain, because we will not send it to client.
+    */
+   free_certificate_chain(csp);
+
+   csp->ssl_with_server_is_opened = 1;
+exit:
+   /* Freeing structures if connection wasn't created successfully */
+   if (ret < 0)
+   {
+      free_server_ssl_structures(csp);
+   }
+
+   return ret;
+}
+
+
+/*********************************************************************
+ *
+ * Function    :  free_server_ssl_structures
+ *
+ * Description :  Frees structures used for SSL communication with server
+ *
+ * Parameters  :
+ *          1  :  csp = Current client state (buffers, headers, etc...)
+ *
+ * Returns     :  N/A
+ *
+ *********************************************************************/
+static void free_server_ssl_structures(struct client_state *csp)
+{
+   struct ssl_attr *ssl_attr = &csp->ssl_server_attr;
+
+   if (ssl_attr->openssl_attr.bio) BIO_free_all(ssl_attr->openssl_attr.bio);
+   if (ssl_attr->openssl_attr.ctx) SSL_CTX_free(ssl_attr->openssl_attr.ctx);
+}
+
+
+/*********************************************************************
+ *
+ * Function    :  log_ssl_errors
+ *
+ * Description :  Log SSL errors
+ *
+ * Parameters  :
+ *          1  :  debuglevel = Debug level
+ *          2  :  desc = Error description
+ *
+ * Returns     :  N/A
+ *
+ *********************************************************************/
+static void log_ssl_errors(int debuglevel, const char* fmt, ...)
+{
+   unsigned long err_code;
+   char prefix[ERROR_BUF_SIZE];
+   va_list args;
+   va_start(args, fmt);
+   vsnprintf(prefix, sizeof(prefix), fmt, args);
+   int reported = 0;
+
+   while ((err_code = ERR_get_error())) {
+      char err_buf[ERROR_BUF_SIZE];
+      reported = 1;
+      ERR_error_string_n(err_code, err_buf, sizeof(err_buf));
+      log_error(debuglevel, "%s: %s", prefix, err_buf);
+   }
+   va_end(args);
+   /* in case if called by mistake and there were no SSL errors let's report it to the log */
+   if (!reported)
+      log_error(debuglevel, "%s: no ssl errors detected", prefix);
+}
+
+
+/*********************************************************************
+ *
+ * Function    :  ssl_base64_encode
+ *
+ * Description :  Encode a buffer into base64 format.
+ *
+ * Parameters  :
+ *          1  :  dst = Destination buffer
+ *          2  :  dlen = Destination buffer length
+ *          3  :  olen = Number of bytes written
+ *          4  :  src = Source buffer
+ *          5  :  slen = Amount of data to be encoded
+ *
+ * Returns     :  0 on success, error code othervise
+ *
+ *********************************************************************/
+extern int ssl_base64_encode(unsigned char *dst, size_t dlen, size_t *olen,
+                              const unsigned char *src, size_t slen )
+{
+   *olen = 4 * ((slen/3)  + ((slen%3) ? 1 : 0)) + 1; 
+   if (*olen < dlen)
+      return ENOBUFS;
+   *olen = (size_t)EVP_EncodeBlock(dst, src, (int)slen) + 1;
+   return 0;
+}
+
+
+/*********************************************************************
+ *
+ * Function    :  close_file_stream
+ *
+ * Description :  Close file stream, report error on close error
+ *
+ * Parameters  :
+ *          1  :  f = file stream to close
+ *          2  :  path = path for error report
+ *
+ * Returns     :  N/A
+ *
+ *********************************************************************/
+static void close_file_stream(FILE *f, const char* path) {
+   if (fclose(f) != 0) {
+      log_error(LOG_LEVEL_ERROR, "Error closing file %s: %s", path, strerror(errno));
+   }
+}
+
+
+/*********************************************************************
+ *
+ * Function    :  write_certificate
+ *
+ * Description :  Writes certificate into file.
+ *
+ * Parameters  :
+ *          1  :  crt = certificate to write into file
+ *          2  :  output_file = path to save certificate file
+ *
+ *                on error
+ * Returns     :  1 on success success or negative value
+ *
+ *********************************************************************/
+static int write_certificate(X509 *crt, const char *output_file)
+{
+   FILE *f = NULL;
+   int ret = -1;
+
+   /*
+    * Saving certificate into file
+    */
+   if ((f = fopen(output_file, "w")) == NULL)
+   {
+      log_error(LOG_LEVEL_ERROR, "Opening file %s to save certificate failed",
+         output_file);
+      return ret;
+   }
+
+   ret = PEM_write_X509(f, crt);
+   if (!ret)
+   {
+      log_ssl_errors(LOG_LEVEL_ERROR,
+         "Writing certificate into file %s failed", output_file);
+      ret = -1;
+   }
+
+   close_file_stream(f, output_file);
+
+   return ret;
+}
+
+/*********************************************************************
+ *
+ * Function    :  write_private_key
+ *
+ * Description :  Writes private key into file and copies saved
+ *                content into given pointer to string. If function
+ *                returns 0 for success, this copy must be freed by
+ *                caller.
+ *
+ * Parameters  :
+ *          1  :  key = key to write into file
+ *          2  :  ret_buf = pointer to string with created key file content
+ *          3  :  key_file_path = path where to save key file
+ *
+ * Returns     :  Length of written private key on success or negative value
+ *                on error
+ *
+ *********************************************************************/
+static int write_private_key(EVP_PKEY *key, char **ret_buf,
+   const char *key_file_path)
+{
+   size_t len = 0;                /* Length of created key    */
+   FILE *f = NULL;                /* File to save certificate */
+   int ret = 0;
+   BIO *bio_mem = BIO_new(BIO_s_mem());
+   char *bio_mem_data = 0;
+
+   if (bio_mem == NULL) {
+      log_ssl_errors(LOG_LEVEL_ERROR, "write_private_key memory allocation failure");
+      return -1;
+   }
+
+   /*
+    * Writing private key into PEM string
+    */
+   if (!PEM_write_bio_PrivateKey(bio_mem, key, NULL, NULL, 0, NULL, NULL)) {
+      log_ssl_errors(LOG_LEVEL_ERROR, "Writing private key into PEM string failed");
+      ret = -1;
+      goto exit;
+   }
+
+   len = (size_t)BIO_get_mem_data(bio_mem, &bio_mem_data);
+
+   /* Initializing buffer for key file content */
+   *ret_buf = zalloc_or_die(len + 1);
+   (*ret_buf)[len] = 0;
+
+   strncpy(*ret_buf, bio_mem_data, len);
+
+   /*
+    * Saving key into file
+    */
+   if ((f = fopen(key_file_path, "wb")) == NULL)
+   {
+      log_error(LOG_LEVEL_ERROR,
+         "Opening file %s to save private key failed: %E",
+         key_file_path);
+      ret = -1;
+      goto exit;
+   }
+
+   if (fwrite(*ret_buf, 1, len, f) != len)
+   {
+      log_error(LOG_LEVEL_ERROR,
+         "Writing private key into file %s failed",
+         key_file_path);
+      close_file_stream(f, key_file_path);
+      ret = -1;
+      goto exit;
+   }
+
+   close_file_stream(f, key_file_path);
+
+exit:
+   BIO_free(bio_mem);
+   if (ret < 0)
+   {
+      freez(*ret_buf);
+      *ret_buf = NULL;
+      return ret;
+   }
+   return (int)len;
+}
+
+
+/*********************************************************************
+ *
+ * Function    :  generate_key
+ *
+ * Description : Tests if private key for host saved in csp already
+ *               exists.  If this file doesn't exists, a new key is
+ *               generated and saved in a file. The generated key is also
+ *               copied into given parameter key_buf, which must be then
+ *               freed by caller. If file with key exists, key_buf
+ *               contain NULL and no private key is generated.
+ *
+ * Parameters  :
+ *          1  :  csp = Current client state (buffers, headers, etc...)
+ *          2  :  key_buf = buffer to save new generated key
+ *
+ * Returns     :  -1 => Error while generating private key
+ *                 0 => Key already exists
+ *                >0 => Length of generated private key
+ *
+ *********************************************************************/
+static int generate_key(struct client_state *csp, char **key_buf)
+{
+   int ret = 0;
+   char* key_file_path = NULL;
+   BIGNUM *exp = BN_new();
+   RSA *rsa = RSA_new();
+   EVP_PKEY *key = EVP_PKEY_new();
+
+   if (exp == NULL || rsa == NULL || key == NULL) {
+      log_ssl_errors(LOG_LEVEL_ERROR, "RSA key memory allocation failure");
+      ret = -1;
+      goto exit;
+   }
+
+   BN_set_word(exp, RSA_KEY_PUBLIC_EXPONENT);
+
+   key_file_path = make_certs_path(csp->config->certificate_directory,
+      (char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
+   if (key_file_path == NULL)
+   {
+      ret = -1;
+      goto exit;
+   }
+
+   /*
+    * Test if key already exists. If so, we don't have to create it again.
+    */
+   if (file_exists(key_file_path) == 1)
+   {
+      ret = 0;
+      goto exit;
+   }
+
+   ret = RSA_generate_key_ex(rsa, RSA_KEYSIZE, exp, NULL);
+   if (ret == 0) {
+      log_ssl_errors(LOG_LEVEL_ERROR, "RSA key generation failure");
+      ret = -1;
+      goto exit;
+   }
+
+   if (!EVP_PKEY_set1_RSA(key, rsa)) {
+      log_ssl_errors(LOG_LEVEL_ERROR, "Error assigning RSA key pair to PKEY structure");
+      ret = -1;
+      goto exit;
+   }
+
+   /*
+    * Exporting private key into file
+    */
+   if ((ret = write_private_key(key, key_buf, key_file_path)) < 0)
+   {
+      log_error(LOG_LEVEL_ERROR,
+         "Writing private key into file %s failed", key_file_path);
+      ret = -1;
+      goto exit;
+   }
+
+exit:
+   /*
+    * Freeing used variables
+    */
+   if (exp) BN_free(exp);
+   if (rsa) RSA_free(rsa);
+   if (key) EVP_PKEY_free(key);
+   freez(key_file_path);
+
+   return ret;
+}
+
+/*********************************************************************
+ *
+ * Function    :  ssl_certificate_load
+ *
+ * Description :  Loads certificate from file.
+ *
+ * Parameters  :
+ *          1  :  cert_path = The certificate path to load
+ *
+ * Returns     :   NULL => error loading certificate,
+ *                   pointer to certificate instance otherwise
+ *
+ *********************************************************************/
+static X509* ssl_certificate_load(const char *cert_path)
+{
+   X509 *cert = NULL;
+   FILE *cert_f = NULL;
+
+   if (!(cert_f = fopen(cert_path, "r"))) {
+      log_error(LOG_LEVEL_ERROR, "Error opening certificate file %s: %s", cert_path, strerror(errno));
+      return NULL;
+   }
+
+   if (!(cert = PEM_read_X509(cert_f, NULL, NULL, NULL))) {
+      log_ssl_errors(LOG_LEVEL_ERROR, "Error reading certificate file %s", cert_path);
+   }
+
+   close_file_stream(cert_f, cert_path);
+   return cert;
+}
+
+
+/*********************************************************************
+ *
+ * Function    :  ssl_certificate_is_invalid
+ *
+ * Description :  Checks whether or not a certificate is valid.
+ *                Currently only checks that the certificate can be
+ *                parsed and that the "valid to" date is in the future.
+ *
+ * Parameters  :
+ *          1  :  cert_file = The certificate to check
+ *
+ * Returns     :   0 => The certificate is valid.
+ *                 1 => The certificate is invalid
+ *
+ *********************************************************************/
+static int ssl_certificate_is_invalid(const char *cert_file)
+{
+   int ret;
+
+   X509 *cert = NULL;
+
+   if (!(cert = ssl_certificate_load(cert_file))) {
+      log_ssl_errors(LOG_LEVEL_ERROR, "Error reading certificate file %s", cert_file);
+      return 1;
+   }
+
+   ret = X509_cmp_current_time(X509_get_notAfter(cert));
+   if (ret == 0) {
+      log_ssl_errors(LOG_LEVEL_ERROR, "Error checking certificate %s validity", cert_file);
+   }
+
+   X509_free(cert);
+
+   return ret == -1 ? 1 : 0;
+}
+
+/*********************************************************************
+ *
+ * Function    :  set_x509_ext
+ *
+ * Description :  Sets the X509V3 extension data
+ *
+ * Parameters  :
+ *          1  :  cert = The certificate to modify
+ *          2  :  issuer = Issuer certificate
+ *          3  :  nid = OpenSSL NID
+ *          2  :  data = extension value
+ *
+ * Returns     :   0 => Error while setting extensuon data
+ *                 1 => It worked
+ *
+ *********************************************************************/
+static int set_x509_ext(X509 *cert, X509 *issuer, int nid, const char *value)
+{
+   X509_EXTENSION * ext = NULL;
+   X509V3_CTX ctx;
+   int ret = 0;
+
+   X509V3_set_ctx(&ctx, issuer, cert, NULL, NULL, 0);
+   ext = X509V3_EXT_conf_nid(NULL, &ctx, nid, value);
+   if (!ext)
+   {
+      log_ssl_errors(LOG_LEVEL_ERROR, "X509V3_EXT_conf_nid failure");
+      goto exit;
+   }
+
+   if (!X509_add_ext(cert, ext, -1))
+   {
+      log_ssl_errors(LOG_LEVEL_ERROR, "X509_add_ext failure");
+      goto exit;
+   }
+
+   ret = 1;
+exit:
+   if (ext) X509_EXTENSION_free(ext);
+   return ret;
+}
+
+
+/*********************************************************************
+ *
+ * Function    :  set_subject_alternative_name
+ *
+ * Description :  Sets the Subject Alternative Name extension to a cert
+ *
+ * Parameters  :
+ *          1  :  cert = The certificate to modify
+ *          2  :  issuer = Issuer certificate
+ *          2  :  hostname = The hostname to add
+ *
+ * Returns     :   0 => Error while creating certificate.
+ *                 1 => It worked
+ *
+ *********************************************************************/
+static int set_subject_alternative_name(X509 *cert, X509 *issuer, const char *hostname)
+{
+   size_t altname_len = strlen(hostname) + sizeof(CERTIFICATE_ALT_NAME_PREFIX);
+   char alt_name_buf[altname_len];
+
+   snprintf(alt_name_buf, sizeof(alt_name_buf), CERTIFICATE_ALT_NAME_PREFIX"%s", hostname);
+   return set_x509_ext(cert, issuer, NID_subject_alt_name, alt_name_buf);
+}
+
+
+/*********************************************************************
+ *
+ * Function    :  generate_webpage_certificate
+ *
+ * Description :  Creates certificate file in presetted directory.
+ *                If certificate already exists, no other certificate
+ *                will be created. Subject of certificate is named
+ *                by csp->http->host from parameter. This function also
+ *                triggers generating of private key for new certificate.
+ *
+ * Parameters  :
+ *          1  :  csp = Current client state (buffers, headers, etc...)
+ *
+ * Returns     :  -1 => Error while creating certificate.
+ *                 0 => Certificate already exists.
+ *                 1 => Certificate created
+ *
+ *********************************************************************/
+static int generate_webpage_certificate(struct client_state *csp)
+{
+   char *key_buf = NULL;    /* Buffer for created key */
+   X509* issuer_cert = NULL;
+   X509* cert = NULL;
+   BIO* pk_bio = NULL;
+   EVP_PKEY *loaded_subject_key = NULL;
+   EVP_PKEY *loaded_issuer_key = NULL;
+   X509_NAME* issuer_name;
+   X509_NAME* subject_name = NULL;
+   ASN1_TIME* asn_time = NULL;
+   ASN1_INTEGER *serial = NULL;
+   BIGNUM *serial_num = NULL;
+
+   int ret = 0;
+   cert_options cert_opt;
+   char cert_valid_from[VALID_DATETIME_BUFLEN];
+   char cert_valid_to[VALID_DATETIME_BUFLEN];
+
+   /* Paths to keys and certificates needed to create certificate */
+   cert_opt.issuer_key  = NULL;
+   cert_opt.subject_key = NULL;
+   cert_opt.issuer_crt  = NULL;
+
+   cert_opt.output_file = make_certs_path(csp->config->certificate_directory,
+      (const char *)csp->http->hash_of_host_hex, CERT_FILE_TYPE);
+   if (cert_opt.output_file == NULL)
+   {
+      return -1;
+   }
+
+   cert_opt.subject_key = make_certs_path(csp->config->certificate_directory,
+      (const char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
+   if (cert_opt.subject_key == NULL)
+   {
+      freez(cert_opt.output_file);
+      return -1;
+   }
+
+   if (file_exists(cert_opt.output_file) == 1)
+   {
+      /* The file exists, but is it valid? */
+      if (ssl_certificate_is_invalid(cert_opt.output_file))
+      {
+         log_error(LOG_LEVEL_CONNECT,
+            "Certificate %s is no longer valid. Removing it.",
+            cert_opt.output_file);
+         if (unlink(cert_opt.output_file))
+         {
+            log_error(LOG_LEVEL_ERROR, "Failed to unlink %s: %E",
+               cert_opt.output_file);
+
+            freez(cert_opt.output_file);
+            freez(cert_opt.subject_key);
+
+            return -1;
+         }
+         if (unlink(cert_opt.subject_key))
+         {
+            log_error(LOG_LEVEL_ERROR, "Failed to unlink %s: %E",
+               cert_opt.subject_key);
+
+            freez(cert_opt.output_file);
+            freez(cert_opt.subject_key);
+
+            return -1;
+         }
+      }
+      else
+      {
+         freez(cert_opt.output_file);
+         freez(cert_opt.subject_key);
+
+         return 0;
+      }
+   }
+
+   /*
+    * Create key for requested host
+    */
+   int subject_key_len = generate_key(csp, &key_buf);
+   if (subject_key_len < 0)
+   {
+      freez(cert_opt.output_file);
+      freez(cert_opt.subject_key);
+      log_error(LOG_LEVEL_ERROR, "Key generating failed");
+      return -1;
+   }
+
+   /*
+    * Converting unsigned long serial number to char * serial number.
+    * We must compute length of serial number in string + terminating null.
+    */
+   unsigned long certificate_serial = get_certificate_serial(csp);
+   unsigned long certificate_serial_time = (unsigned long)time(NULL);
+   int serial_num_size = snprintf(NULL, 0, "%lu%lu",
+      certificate_serial_time, certificate_serial) + 1;
+   if (serial_num_size <= 0)
+   {
+      serial_num_size = 1;
+   }
+
+   char serial_num_text[serial_num_size];  /* Buffer for serial number */
+   ret = snprintf(serial_num_text, (size_t)serial_num_size, "%lu%lu",
+      certificate_serial_time, certificate_serial);
+   if (ret < 0 || ret >= serial_num_size)
+   {
+      log_error(LOG_LEVEL_ERROR,
+         "Converting certificate serial number into string failed");
+      ret = -1;
+      goto exit;
+   }
+
+   /*
+    * Preparing parameters for certificate
+    */
+   subject_name = X509_NAME_new();
+   if (!subject_name)
+   {
+      log_ssl_errors(LOG_LEVEL_ERROR, "RSA key memory allocation failure");
+      ret = -1;
+      goto exit;
+   }
+
+   if (!X509_NAME_add_entry_by_txt(subject_name, CERT_PARAM_COMMON_NAME_FCODE, MBSTRING_ASC,
+                                    (void*)csp->http->host, -1, -1, 0))
+   {
+      log_ssl_errors(LOG_LEVEL_ERROR, "X509 subject name (code: %s, val: %s) error",
+                     CERT_PARAM_COMMON_NAME_FCODE, csp->http->host);
+      ret = -1;
+      goto exit;
+   }
+   if (!X509_NAME_add_entry_by_txt(subject_name, CERT_PARAM_ORGANIZATION_FCODE, MBSTRING_ASC,
+                                    (void*)csp->http->host, -1, -1, 0))
+   {
+      log_ssl_errors(LOG_LEVEL_ERROR, "X509 subject name (code: %s, val: %s) error",
+                     CERT_PARAM_COMMON_NAME_FCODE, csp->http->host);
+      ret = -1;
+      goto exit;
+   }
+   if (!X509_NAME_add_entry_by_txt(subject_name, CERT_PARAM_ORG_UNIT_FCODE, MBSTRING_ASC,
+                                    (void*)csp->http->host, -1, -1, 0))
+   {
+      log_ssl_errors(LOG_LEVEL_ERROR, "X509 subject name (code: %s, val: %s) error",
+                     CERT_PARAM_COMMON_NAME_FCODE, csp->http->host);
+      ret = -1;
+      goto exit;
+   }
+   if (!X509_NAME_add_entry_by_txt(subject_name, CERT_PARAM_COUNTRY_FCODE, MBSTRING_ASC,
+                                    (void*)CERT_PARAM_COUNTRY_CODE, -1, -1, 0))
+   {
+      log_ssl_errors(LOG_LEVEL_ERROR, "X509 subject name (code: %s, val: %s) error",
+                     CERT_PARAM_COMMON_NAME_FCODE, csp->http->host);
+      ret = -1;
+      goto exit;
+   }
+
+   cert_opt.issuer_crt = csp->config->ca_cert_file;
+   cert_opt.issuer_key = csp->config->ca_key_file;
+
+   if (get_certificate_valid_from_date(cert_valid_from, sizeof(cert_valid_from), VALID_DATETIME_FMT)
+    || get_certificate_valid_to_date(cert_valid_to, sizeof(cert_valid_to), VALID_DATETIME_FMT))
+   {
+      log_error(LOG_LEVEL_ERROR, "Generating one of the validity dates failed");
+      ret = -1;
+      goto exit;
+   }
+
+   cert_opt.subject_pwd   = CERT_SUBJECT_PASSWORD;
+   cert_opt.issuer_pwd    = csp->config->ca_password;
+   cert_opt.not_before    = cert_valid_from;
+   cert_opt.not_after     = cert_valid_to;
+   cert_opt.serial        = serial_num_text;
+   cert_opt.max_pathlen   = -1;
+
+   /*
+    * Test if the private key was already created.
+    * XXX: Can this still happen?
+    */
+   if (subject_key_len == 0)
+   {
+      log_error(LOG_LEVEL_ERROR, "Subject key was already created");
+      ret = 0;
+      goto exit;
+   }
+
+   /*
+    * Parse serial to MPI
+    */
+   serial_num = BN_new();
+   if (!serial_num)
+   {
+      log_error(LOG_LEVEL_ERROR, "generate_webpage_certificate: memory error");
+      ret = -1;
+      goto exit;
+   }
+   if (!BN_dec2bn(&serial_num, cert_opt.serial))
+   {
+      log_ssl_errors(LOG_LEVEL_ERROR, "Failed to parse serial %s", cert_opt.serial);
+      ret = -1;
+      goto exit;
+   }
+
+   if (!(serial = BN_to_ASN1_INTEGER(serial_num, NULL)))
+   {
+      log_ssl_errors(LOG_LEVEL_ERROR, "Failed to generate serial ASN1 representation");
+      ret = -1;
+      goto exit;
+   }
+
+   /*
+    * Loading certificates
+    */
+   if (!(issuer_cert = ssl_certificate_load(cert_opt.issuer_crt)))
+   {
+      log_error(LOG_LEVEL_ERROR, "Loading issuer certificate %s failed", cert_opt.issuer_crt);
+      ret = -1;
+      goto exit;
+   }
+
+   issuer_name = X509_get_issuer_name(issuer_cert);
+
+   /*
+    * Loading keys from file or from buffer
+    */
+   if (key_buf != NULL && subject_key_len > 0)
+   {
+      pk_bio = BIO_new_mem_buf(key_buf, subject_key_len);
+   }
+   else if (!(pk_bio = BIO_new_file(cert_opt.subject_key, "r")))
+   {
+         log_ssl_errors(LOG_LEVEL_ERROR, "Failure opening subject key %s BIO", cert_opt.subject_key);
+         ret = -1;
+         goto exit;
+   }
+
+   loaded_subject_key = PEM_read_bio_PrivateKey(pk_bio, NULL, NULL, (void*)cert_opt.subject_pwd);
+   if (!loaded_subject_key)
+   {
+      log_ssl_errors(LOG_LEVEL_ERROR, "Parsing subject key %s failed", cert_opt.subject_key);
+      ret = -1;
+      goto exit;
+   }
+
+   if (!BIO_free(pk_bio)) {
+      log_ssl_errors(LOG_LEVEL_ERROR, "Error closing subject key BIO");
+   }
+
+   if (!(pk_bio = BIO_new_file(cert_opt.issuer_key, "r")))
+   {
+         log_ssl_errors(LOG_LEVEL_ERROR, "Failure opening issuer key %s BIO", cert_opt.issuer_key);
+         ret = -1;
+         goto exit;
+   }
+
+   loaded_issuer_key = PEM_read_bio_PrivateKey(pk_bio, NULL, NULL, (void*)cert_opt.issuer_pwd);
+   if (!loaded_issuer_key)
+   {
+      log_ssl_errors(LOG_LEVEL_ERROR, "Parsing issuer key %s failed", cert_opt.subject_key);
+      ret = -1;
+      goto exit;
+   }
+
+   cert = X509_new();
+   if (!cert)
+   {
+      log_ssl_errors(LOG_LEVEL_ERROR, "Certificate allocation error");
+      ret = -1;
+      goto exit;
+   }
+
+   if (!X509_set_version(cert, CERTIFICATE_VERSION))
+   {
+      log_ssl_errors(LOG_LEVEL_ERROR, "X509_set_version failed");
+      ret = -1;
+      goto exit;
+   }
+
+   /*
+    * Setting parameters of signed certificate
+    */
+   if (!X509_set_pubkey(cert, loaded_subject_key)) {
+      log_ssl_errors(LOG_LEVEL_ERROR, "Setting issuer name in signed certificate failed");
+      ret = -1;
+      goto exit;
+   }
+
+   if (!X509_set_subject_name(cert, subject_name))
+   {
+      log_ssl_errors(LOG_LEVEL_ERROR, "Setting issuer name in signed certificate failed");
+      ret = -1;
+      goto exit;
+   }
+
+   if (!X509_set_issuer_name(cert, issuer_name))
+   {
+      log_ssl_errors(LOG_LEVEL_ERROR, "Setting issuer name in signed certificate failed");
+      ret = -1;
+      goto exit;
+   }
+
+   if (!X509_set_serialNumber(cert, serial))
+   {
+      log_ssl_errors(LOG_LEVEL_ERROR, "Setting serial number in signed certificate failed");
+      ret = -1;
+      goto exit;
+   }
+
+   asn_time = ASN1_TIME_new();
+   if (!asn_time) {
+      log_ssl_errors(LOG_LEVEL_ERROR, "ASN1 time memory allocation failure");
+      ret = -1;
+      goto exit;
+   }
+
+   if (!ASN1_TIME_set_string(asn_time, cert_opt.not_after)) {
+      log_ssl_errors(LOG_LEVEL_ERROR, "ASN1 time [%s] encode error", cert_opt.not_after);
+      ret = -1;
+      goto exit;
+   }
+
+   if (!X509_set1_notAfter(cert, asn_time))
+   {
+      log_ssl_errors(LOG_LEVEL_ERROR, "Setting valid not after in signed certificate failed");
+      ret = -1;
+      goto exit;
+   }
+
+   if (!ASN1_TIME_set_string(asn_time, cert_opt.not_before)) {
+      log_ssl_errors(LOG_LEVEL_ERROR, "ASN1 time encode error");
+      ret = -1;
+      goto exit;
+   }
+
+   if (!X509_set1_notBefore(cert, asn_time))
+   {
+      log_ssl_errors(LOG_LEVEL_ERROR, "Setting valid not befre in signed certificate failed");
+      ret = -1;
+      goto exit;
+   }
+
+   if(!set_x509_ext(cert, issuer_cert, NID_basic_constraints, CERTIFICATE_BASIC_CONSTRAINTS))
+   {
+      log_ssl_errors(LOG_LEVEL_ERROR, "Setting the basicConstraints extension "
+         "in signed certificate failed");
+      ret = -1;
+      goto exit;
+   }
+
+   if (!set_x509_ext(cert, issuer_cert, NID_subject_key_identifier, CERTIFICATE_SUBJECT_KEY))
+   {
+      log_ssl_errors(LOG_LEVEL_ERROR, "Setting the Subject Key Identifie extension failed");
+      ret = -1;
+      goto exit;
+   }
+
+   if (!set_x509_ext(cert, issuer_cert, NID_authority_key_identifier, CERTIFICATE_AUTHORITY_KEY))
+   {
+      log_ssl_errors(LOG_LEVEL_ERROR, "Setting the Authority Key Identifier extension failed");
+      ret = -1;
+      goto exit;
+   }
+
+   if (!host_is_ip_address(csp->http->host) &&
+       !set_subject_alternative_name(cert, issuer_cert, csp->http->host))
+   {
+      log_ssl_errors(LOG_LEVEL_ERROR, "Setting the Subject Alt Nameextension failed");
+      ret = -1;
+      goto exit;
+   }
+
+   if (!X509_sign(cert, loaded_issuer_key, EVP_sha256()))
+   {
+      log_ssl_errors(LOG_LEVEL_ERROR, "Signing certificate failed");
+      ret = -1;
+      goto exit;
+   }
+
+   /*
+    * Writing certificate into file
+    */
+   if (write_certificate(cert, cert_opt.output_file) < 0)
+   {
+      log_error(LOG_LEVEL_ERROR, "Writing certificate into file failed");
+      ret = -1;
+      goto exit;
+   }
+
+   ret = 1;
+
+exit:
+   /*
+    * Freeing used structures
+    */
+   if (issuer_cert) X509_free(issuer_cert);
+   if (cert) X509_free(cert);
+   if (pk_bio && !BIO_free(pk_bio)) {
+      log_ssl_errors(LOG_LEVEL_ERROR, "Error closing pk BIO");
+   }
+   if (loaded_subject_key) EVP_PKEY_free(loaded_subject_key);
+   if (loaded_issuer_key) EVP_PKEY_free(loaded_issuer_key);
+   if (subject_name) X509_NAME_free(subject_name);
+   if (asn_time) ASN1_TIME_free(asn_time);
+   if (serial_num) BN_free(serial_num);
+   if (serial) ASN1_INTEGER_free(serial);
+   freez(cert_opt.subject_key);
+   freez(cert_opt.output_file);
+   freez(key_buf);
+
+   return ret;
+}
+
+
+/*********************************************************************
+ *
+ * Function    :  ssl_crt_verify_info
+ *
+ * Description :  Returns an informational string about the verification
+ *                status of a certificate.
+ *
+ * Parameters  :
+ *          1  :  buf = Buffer to write to
+ *          2  :  size = Maximum size of buffer
+ *          3  :  csp = client state
+ *
+ * Returns     :  N/A
+ *
+ *********************************************************************/
+extern void ssl_crt_verify_info(char *buf, size_t size, struct client_state *csp)
+{
+   strncpy(buf, X509_verify_cert_error_string(csp->server_cert_verification_result), size);
+   buf[size - 1] = 0;
+}
+
+
+/*********************************************************************
+ *
+ * Function    :  ssl_release
+ *
+ * Description :  Release all SSL resources
+ *
+ * Parameters  :
+ *
+ * Returns     :  N/A
+ *
+ *********************************************************************/
+extern void ssl_release(void)
+{
+   if (ssl_inited == 1)
+   {
+      SSL_COMP_free_compression_methods();
+
+      CONF_modules_free();
+      CONF_modules_unload(1);
+
+      COMP_zlib_cleanup();
+
+      ERR_free_strings();
+      EVP_cleanup();
+
+      CRYPTO_cleanup_all_ex_data();
+   }
+}
+
index 4c594ff..0999e80 100644 (file)
--- a/project.h
+++ b/project.h
 #include "config.h"
 
 #ifdef FEATURE_HTTPS_INSPECTION
 #include "config.h"
 
 #ifdef FEATURE_HTTPS_INSPECTION
+/*
+* Macros for SSL structures
+*/
+#define CERT_INFO_BUF_SIZE         4096
+#define CERT_FILE_BUF_SIZE         16384
+#define ISSUER_NAME_BUF_SIZE       2048
+#define HASH_OF_HOST_BUF_SIZE      16
+#endif /* FEATURE_HTTPS_INSPECTION */
+
 #ifdef FEATURE_PTHREAD
 #  include <pthread.h>
    typedef pthread_mutex_t privoxy_mutex_t;
 #ifdef FEATURE_PTHREAD
 #  include <pthread.h>
    typedef pthread_mutex_t privoxy_mutex_t;
@@ -55,6 +64,7 @@
    typedef CRITICAL_SECTION privoxy_mutex_t;
 #endif
 
    typedef CRITICAL_SECTION privoxy_mutex_t;
 #endif
 
+#ifdef FEATURE_HTTPS_INSPECTION_MBEDTLS
 #include "mbedtls/net_sockets.h"
 #include "mbedtls/entropy.h"
 #include "mbedtls/ctr_drbg.h"
 #include "mbedtls/net_sockets.h"
 #include "mbedtls/entropy.h"
 #include "mbedtls/ctr_drbg.h"
 #if defined(MBEDTLS_SSL_CACHE_C)
 #include "mbedtls/ssl_cache.h"
 #endif
 #if defined(MBEDTLS_SSL_CACHE_C)
 #include "mbedtls/ssl_cache.h"
 #endif
+#endif /* FEATURE_HTTPS_INSPECTION_MBEDTLS */
 
 
-/*
-* Macros for SSL structures
-*/
-#define CERT_INFO_BUF_SIZE         4096
-#define CERT_FILE_BUF_SIZE         16384
-#define ISSUER_NAME_BUF_SIZE       2048
-#define HASH_OF_HOST_BUF_SIZE      16
-#endif
+#ifdef FEATURE_HTTPS_INSPECTION_OPENSSL
+#include <openssl/ssl.h>
+#include <openssl/bio.h>
+#include <openssl/err.h>
+#endif /* FEATURE_HTTPS_INSPECTION_OPENSSL */
 
 /* Need for struct sockaddr_storage */
 #ifdef HAVE_RFC2553
 
 /* Need for struct sockaddr_storage */
 #ifdef HAVE_RFC2553
@@ -287,7 +295,7 @@ struct map
    struct map_entry *last;
 };
 
    struct map_entry *last;
 };
 
-#ifdef FEATURE_HTTPS_INSPECTION
+#ifdef FEATURE_HTTPS_INSPECTION_MBEDTLS
 /*
  * Struct of attributes necessary for TLS/SSL connection
  */
 /*
  * Struct of attributes necessary for TLS/SSL connection
  */
@@ -303,8 +311,17 @@ typedef struct {
       mbedtls_ssl_cache_context cache;
    #endif
 } mbedtls_connection_attr;
       mbedtls_ssl_cache_context cache;
    #endif
 } mbedtls_connection_attr;
-#endif
+#endif /* FEATURE_HTTPS_INSPECTION_MBEDTLS */
 
 
+#ifdef FEATURE_HTTPS_INSPECTION_OPENSSL
+/*
+ * Struct of attributes necessary for TLS/SSL connection
+ */
+typedef struct {
+   SSL_CTX* ctx;
+   BIO *bio;
+} openssl_connection_attr;
+#endif /* FEATURE_HTTPS_INSPECTION_OPENSSL */
 /**
  * A HTTP request.  This includes the method (GET, POST) and
  * the parsed URL.
 /**
  * A HTTP request.  This includes the method (GET, POST) and
  * the parsed URL.
@@ -960,6 +977,14 @@ struct reusable_connection
  */
 #define MAX_LISTENING_SOCKETS 10
 
  */
 #define MAX_LISTENING_SOCKETS 10
 
+struct ssl_attr {
+#ifdef FEATURE_HTTPS_INSPECTION_MBEDTLS
+   mbedtls_connection_attr  mbedtls_attr; /* Mbed TLS attrs*/
+#endif /* FEATURE_HTTPS_INSPECTION_MBEDTLS */
+#ifdef FEATURE_HTTPS_INSPECTION_OPENSSL
+   openssl_connection_attr  openssl_attr; /* OpenSSL atrrs */
+#endif /* FEATURE_HTTPS_INSPECTION_OPENSSL */
+};
 /**
  * The state of a Privoxy processing thread.
  */
 /**
  * The state of a Privoxy processing thread.
  */
@@ -1014,10 +1039,8 @@ struct client_state
    /* XXX: should be renamed to server_iob */
    struct iob iob[1];
 
    /* XXX: should be renamed to server_iob */
    struct iob iob[1];
 
-#ifdef FEATURE_HTTPS_INSPECTION
-   mbedtls_connection_attr  mbedtls_server_attr; /* attributes for connection to server */
-   mbedtls_connection_attr  mbedtls_client_attr; /* attributes for connection to client */
-#endif
+   struct ssl_attr ssl_server_attr; /* attributes for connection to server */
+   struct ssl_attr ssl_client_attr; /* attributes for connection to client */
 
    /** An I/O buffer used for buffering data read from the client */
    struct iob client_iob[1];
 
    /** An I/O buffer used for buffering data read from the client */
    struct iob client_iob[1];
@@ -1088,8 +1111,24 @@ struct client_state
    char *error_message;
 
 #ifdef FEATURE_HTTPS_INSPECTION
    char *error_message;
 
 #ifdef FEATURE_HTTPS_INSPECTION
-   /* Result of server certificate verification */
+   /* Result of server certificate verification
+    *
+    * Values for flag determining certificate validity
+    * are compatible with return value of function
+    * mbedtls_ssl_get_verify_result() for mbedtls
+    * and SSL_get_verify_result() for openssl.
+    * There are no values for "invalid certificate", they are
+    * set by the functions mentioned above.
+    */
+#define SSL_CERT_VALID          0
+#ifdef FEATURE_HTTPS_INSPECTION_MBEDTLS
+#define SSL_CERT_NOT_VERIFIED   0xFFFFFFFF
    uint32_t server_cert_verification_result;
    uint32_t server_cert_verification_result;
+#endif /* FEATURE_HTTPS_INSPECTION_MBEDTLS */
+#ifdef FEATURE_HTTPS_INSPECTION_OPENSSL
+#define SSL_CERT_NOT_VERIFIED    ~0L
+   long server_cert_verification_result;
+#endif /* FEATURE_HTTPS_INSPECTION_OPENSSL */
 
    /* Flag for certificate validity checking */
    int dont_verify_certificate;
 
    /* Flag for certificate validity checking */
    int dont_verify_certificate;
diff --git a/ssl.c b/ssl.c
index 85701ce..6eb5945 100644 (file)
--- a/ssl.c
+++ b/ssl.c
@@ -28,7 +28,6 @@
  *
  *********************************************************************/
 
  *
  *********************************************************************/
 
-#include <ctype.h>
 #include <string.h>
 #include <unistd.h>
 
 #include <string.h>
 #include <unistd.h>
 
@@ -51,6 +50,7 @@
 #include "errlog.h"
 #include "jcc.h"
 #include "ssl.h"
 #include "errlog.h"
 #include "jcc.h"
 #include "ssl.h"
+#include "ssl_common.h"
 #include "encode.h"
 
 
 #include "encode.h"
 
 
  */
 #define PEM_BEGIN_CRT     "-----BEGIN CERTIFICATE-----\n"
 #define PEM_END_CRT       "-----END CERTIFICATE-----\n"
  */
 #define PEM_BEGIN_CRT     "-----BEGIN CERTIFICATE-----\n"
 #define PEM_END_CRT       "-----END CERTIFICATE-----\n"
+#define VALID_DATETIME_FMT    "%Y%m%d%H%M%S"
+#define VALID_DATETIME_BUFLEN 15
 
 /*
  * Macros for ssl.c
  */
 
 /*
  * Macros for ssl.c
  */
-#define ERROR_BUF_SIZE                   1024              /* Size of buffer for error messages */
 #define CERTIFICATE_BUF_SIZE             16384             /* Size of buffer to save certificate. Value 4096 is mbedtls library buffer size for certificate in DER form */
 #define PRIVATE_KEY_BUF_SIZE             16000             /* Size of buffer to save private key. Value 16000 is taken from mbed TLS library examples. */
 #define CERTIFICATE_BUF_SIZE             16384             /* Size of buffer to save certificate. Value 4096 is mbedtls library buffer size for certificate in DER form */
 #define PRIVATE_KEY_BUF_SIZE             16000             /* Size of buffer to save private key. Value 16000 is taken from mbed TLS library examples. */
-#define RSA_KEY_PUBLIC_EXPONENT          65537             /* Public exponent for RSA private key generating */
-#define RSA_KEYSIZE                      2048              /* Size of generated RSA keys */
 #define CERT_SIGNATURE_ALGORITHM         MBEDTLS_MD_SHA256 /* The MD algorithm to use for the signature */
 #define CERT_SIGNATURE_ALGORITHM         MBEDTLS_MD_SHA256 /* The MD algorithm to use for the signature */
-#define CERT_SERIAL_NUM_LENGTH           4                 /* Bytes of hash to be used for creating serial number of certificate. Min=2 and max=16 */
-#define INVALID_CERT_INFO_BUF_SIZE       2048              /* Size of buffer for message with information about reason of certificate invalidity. Data after the end of buffer will not be saved */
-#define CERT_PARAM_COMMON_NAME           "CN="
-#define CERT_PARAM_ORGANIZATION          ",O="
-#define CERT_PARAM_ORG_UNIT              ",OU="
-#define CERT_PARAM_COUNTRY               ",C=CZ"
-#define KEY_FILE_TYPE                    ".pem"
-#define CERT_FILE_TYPE                   ".crt"
-#define CERT_SUBJECT_PASSWORD            ""
-#define CERT_INFO_PREFIX                 ""
-
-/*
- * Properties of cert for generating
- */
-typedef struct {
-   char       *issuer_crt;                         /* filename of the issuer certificate       */
-   char       *subject_key;                        /* filename of the subject key file         */
-   char       *issuer_key;                         /* filename of the issuer key file          */
-   const char *subject_pwd;                        /* password for the subject key file        */
-   const char *issuer_pwd;                         /* password for the issuer key file         */
-   char       *output_file;                        /* where to store the constructed key file  */
-   const char *subject_name;                       /* subject name for certificate             */
-   char       issuer_name[ISSUER_NAME_BUF_SIZE];   /* issuer name for certificate              */
-   const char *not_before;                         /* validity period not before               */
-   const char *not_after;                          /* validity period not after                */
-   const char *serial;                             /* serial number string                     */
-   int        is_ca;                               /* is a CA certificate                      */
-   int        max_pathlen;                         /* maximum CA path length                   */
-} cert_options;
+#define CERT_PARAM_COMMON_NAME           CERT_PARAM_COMMON_NAME_FCODE"="
+#define CERT_PARAM_ORGANIZATION          ","CERT_PARAM_ORGANIZATION_FCODE"="
+#define CERT_PARAM_ORG_UNIT              ","CERT_PARAM_ORG_UNIT_FCODE"="
+#define CERT_PARAM_COUNTRY               ","CERT_PARAM_COUNTRY_FCODE"="CERT_PARAM_COUNTRY_CODE
 
 /*
  * Properties of key for generating
 
 /*
  * Properties of key for generating
@@ -109,57 +83,18 @@ typedef struct {
    char *key_file_path;      /* filename of the key file */
 } key_options;
 
    char *key_file_path;      /* filename of the key file */
 } key_options;
 
+/* Variables for one common RNG for all SSL use */
+static mbedtls_ctr_drbg_context ctr_drbg;
+static mbedtls_entropy_context  entropy;
+static int rng_seeded;
+
 static int generate_webpage_certificate(struct client_state *csp);
 static int generate_webpage_certificate(struct client_state *csp);
-static char *make_certs_path(const char *conf_dir, const char *file_name, const char *suffix);
-static int file_exists(const char *path);
 static int host_to_hash(struct client_state *csp);
 static int ssl_verify_callback(void *data, mbedtls_x509_crt *crt, int depth, uint32_t *flags);
 static int host_to_hash(struct client_state *csp);
 static int ssl_verify_callback(void *data, mbedtls_x509_crt *crt, int depth, uint32_t *flags);
-static void free_certificate_chain(struct client_state *csp);
-static unsigned long  get_certificate_serial(struct client_state *csp);
 static void free_client_ssl_structures(struct client_state *csp);
 static void free_server_ssl_structures(struct client_state *csp);
 static int seed_rng(struct client_state *csp);
 
 static void free_client_ssl_structures(struct client_state *csp);
 static void free_server_ssl_structures(struct client_state *csp);
 static int seed_rng(struct client_state *csp);
 
-/*********************************************************************
- *
- * Function    :  client_use_ssl
- *
- * Description :  Tests if client in current client state structure
- *                should use SSL connection or standard connection.
- *
- * Parameters  :
- *          1  :  csp = Current client state (buffers, headers, etc...)
- *
- * Returns     :  If client should use TLS/SSL connection, 1 is returned.
- *                Otherwise 0 is returned.
- *
- *********************************************************************/
-extern int client_use_ssl(const struct client_state *csp)
-{
-   return csp->http->client_ssl;
-}
-
-
-/*********************************************************************
- *
- * Function    :  server_use_ssl
- *
- * Description :  Tests if server in current client state structure
- *                should use SSL connection or standard connection.
- *
- * Parameters  :
- *          1  :  csp = Current client state (buffers, headers, etc...)
- *
- * Returns     :  If server should use TLS/SSL connection, 1 is returned.
- *                Otherwise 0 is returned.
- *
- *********************************************************************/
-extern int server_use_ssl(const struct client_state *csp)
-{
-   return csp->http->server_ssl;
-}
-
-
 /*********************************************************************
  *
  * Function    :  is_ssl_pending
 /*********************************************************************
  *
  * Function    :  is_ssl_pending
@@ -176,8 +111,9 @@ extern int server_use_ssl(const struct client_state *csp)
  *                >0 => Pending data length
  *
  *********************************************************************/
  *                >0 => Pending data length
  *
  *********************************************************************/
-extern size_t is_ssl_pending(mbedtls_ssl_context *ssl)
+extern size_t is_ssl_pending(struct ssl_attr *ssl_attr)
 {
 {
+   mbedtls_ssl_context *ssl = &ssl_attr->mbedtls_attr.ssl;
    if (ssl == NULL)
    {
       return 0;
    if (ssl == NULL)
    {
       return 0;
@@ -202,8 +138,9 @@ extern size_t is_ssl_pending(mbedtls_ssl_context *ssl)
  * Returns     :  Length of sent data or negative value on error.
  *
  *********************************************************************/
  * Returns     :  Length of sent data or negative value on error.
  *
  *********************************************************************/
-extern int ssl_send_data(mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len)
+extern int ssl_send_data(struct ssl_attr *ssl_attr, const unsigned char *buf, size_t len)
 {
 {
+   mbedtls_ssl_context *ssl = &ssl_attr->mbedtls_attr.ssl;
    int ret = 0;
    size_t max_fragment_size = 0;  /* Maximal length of data in one SSL fragment*/
    int send_len             = 0;  /* length of one data part to send */
    int ret = 0;
    size_t max_fragment_size = 0;  /* Maximal length of data in one SSL fragment*/
    int send_len             = 0;  /* length of one data part to send */
@@ -261,69 +198,6 @@ extern int ssl_send_data(mbedtls_ssl_context *ssl, const unsigned char *buf, siz
 }
 
 
 }
 
 
-/*********************************************************************
- *
- * Function    :  ssl_send_data_delayed
- *
- * Description :  Sends the contents of buf (for n bytes) to given SSL
- *                connection, optionally delaying the operation.
- *
- * Parameters  :
- *          1  :  ssl = SSL context to send data to
- *          2  :  buf = Pointer to data to be sent
- *          3  :  len = Length of data to be sent to the SSL context
- *          4  :  delay = Delay in milliseconds.
- *
- * Returns     :  0 on success (entire buffer sent).
- *                nonzero on error.
- *
- *********************************************************************/
-extern int ssl_send_data_delayed(mbedtls_ssl_context *ssl,
-                                 const unsigned char *buf, size_t len,
-                                 unsigned int delay)
-{
-   size_t i = 0;
-
-   if (delay == 0)
-   {
-      if (ssl_send_data(ssl, buf, len) < 0)
-      {
-         return -1;
-      }
-      else
-      {
-         return 0;
-      }
-   }
-
-   while (i < len)
-   {
-      size_t write_length;
-      enum { MAX_WRITE_LENGTH = 10 };
-
-      if ((i + MAX_WRITE_LENGTH) > len)
-      {
-         write_length = len - i;
-      }
-      else
-      {
-         write_length = MAX_WRITE_LENGTH;
-      }
-
-      privoxy_millisleep(delay);
-
-      if (ssl_send_data(ssl, buf + i, write_length) < 0)
-      {
-         return -1;
-      }
-      i += write_length;
-   }
-
-   return 0;
-
-}
-
-
 /*********************************************************************
  *
  * Function    :  ssl_recv_data
 /*********************************************************************
  *
  * Function    :  ssl_recv_data
@@ -340,8 +214,9 @@ extern int ssl_send_data_delayed(mbedtls_ssl_context *ssl,
  *                on error.
  *
  *********************************************************************/
  *                on error.
  *
  *********************************************************************/
-extern int ssl_recv_data(mbedtls_ssl_context *ssl, unsigned char *buf, size_t max_length)
+extern int ssl_recv_data(struct ssl_attr *ssl_attr, unsigned char *buf, size_t max_length)
 {
 {
+   mbedtls_ssl_context *ssl = &ssl_attr->mbedtls_attr.ssl;
    int ret = 0;
    memset(buf, 0, max_length);
 
    int ret = 0;
    memset(buf, 0, max_length);
 
@@ -377,41 +252,6 @@ extern int ssl_recv_data(mbedtls_ssl_context *ssl, unsigned char *buf, size_t ma
 }
 
 
 }
 
 
-/*********************************************************************
- *
- * Function    :  ssl_flush_socket
- *
- * Description :  Send any pending "buffered" content with given
- *                SSL connection. Alternative to function flush_socket.
- *
- * Parameters  :
- *          1  :  ssl = SSL context to send buffer to
- *          2  :  iob = The I/O buffer to flush, usually csp->iob.
- *
- * Returns     :  On success, the number of bytes send are returned (zero
- *                indicates nothing was sent).  On error, -1 is returned.
- *
- *********************************************************************/
-extern long ssl_flush_socket(mbedtls_ssl_context *ssl, struct iob *iob)
-{
-   /* Computing length of buffer part to send */
-   long len = iob->eod - iob->cur;
-
-   if (len <= 0)
-   {
-      return(0);
-   }
-
-   /* Sending data to given SSl context */
-   if (ssl_send_data(ssl, (const unsigned char *)iob->cur, (size_t)len) < 0)
-   {
-      return -1;
-   }
-   iob->eod = iob->cur = iob->buf;
-   return(len);
-}
-
-
 /*********************************************************************
  *
  * Function    :  ssl_debug_callback
 /*********************************************************************
  *
  * Function    :  ssl_debug_callback
@@ -455,6 +295,7 @@ static void ssl_debug_callback(void *ctx, int level, const char *file, int line,
  *********************************************************************/
 extern int create_client_ssl_connection(struct client_state *csp)
 {
  *********************************************************************/
 extern int create_client_ssl_connection(struct client_state *csp)
 {
+   struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
    /* Paths to certificates file and key file */
    char *key_file  = NULL;
    char *ca_file   = NULL;
    /* Paths to certificates file and key file */
    char *key_file  = NULL;
    char *ca_file   = NULL;
@@ -465,13 +306,13 @@ extern int create_client_ssl_connection(struct client_state *csp)
    /*
     * Initializing mbedtls structures for TLS/SSL connection
     */
    /*
     * Initializing mbedtls structures for TLS/SSL connection
     */
-   mbedtls_net_init(&(csp->mbedtls_client_attr.socket_fd));
-   mbedtls_ssl_init(&(csp->mbedtls_client_attr.ssl));
-   mbedtls_ssl_config_init(&(csp->mbedtls_client_attr.conf));
-   mbedtls_x509_crt_init(&(csp->mbedtls_client_attr.server_cert));
-   mbedtls_pk_init(&(csp->mbedtls_client_attr.prim_key));
+   mbedtls_net_init(&(ssl_attr->mbedtls_attr.socket_fd));
+   mbedtls_ssl_init(&(ssl_attr->mbedtls_attr.ssl));
+   mbedtls_ssl_config_init(&(ssl_attr->mbedtls_attr.conf));
+   mbedtls_x509_crt_init(&(ssl_attr->mbedtls_attr.server_cert));
+   mbedtls_pk_init(&(ssl_attr->mbedtls_attr.prim_key));
 #if defined(MBEDTLS_SSL_CACHE_C)
 #if defined(MBEDTLS_SSL_CACHE_C)
-   mbedtls_ssl_cache_init(&(csp->mbedtls_client_attr.cache));
+   mbedtls_ssl_cache_init(&(ssl_attr->mbedtls_attr.cache));
 #endif
 
    /*
 #endif
 
    /*
@@ -530,7 +371,7 @@ extern int create_client_ssl_connection(struct client_state *csp)
    /*
     * Loading CA file, webpage certificate and key files
     */
    /*
     * Loading CA file, webpage certificate and key files
     */
-   ret = mbedtls_x509_crt_parse_file(&(csp->mbedtls_client_attr.server_cert),
+   ret = mbedtls_x509_crt_parse_file(&(ssl_attr->mbedtls_attr.server_cert),
       cert_file);
    if (ret != 0)
    {
       cert_file);
    if (ret != 0)
    {
@@ -541,7 +382,7 @@ extern int create_client_ssl_connection(struct client_state *csp)
       goto exit;
    }
 
       goto exit;
    }
 
-   ret = mbedtls_x509_crt_parse_file(&(csp->mbedtls_client_attr.server_cert),
+   ret = mbedtls_x509_crt_parse_file(&(ssl_attr->mbedtls_attr.server_cert),
       ca_file);
    if (ret != 0)
    {
       ca_file);
    if (ret != 0)
    {
@@ -552,7 +393,7 @@ extern int create_client_ssl_connection(struct client_state *csp)
       goto exit;
    }
 
       goto exit;
    }
 
-   ret = mbedtls_pk_parse_keyfile(&(csp->mbedtls_client_attr.prim_key),
+   ret = mbedtls_pk_parse_keyfile(&(ssl_attr->mbedtls_attr.prim_key),
       key_file, NULL);
    if (ret != 0)
    {
       key_file, NULL);
    if (ret != 0)
    {
@@ -567,7 +408,7 @@ extern int create_client_ssl_connection(struct client_state *csp)
    /*
     * Setting SSL parameters
     */
    /*
     * Setting SSL parameters
     */
-   ret = mbedtls_ssl_config_defaults(&(csp->mbedtls_client_attr.conf),
+   ret = mbedtls_ssl_config_defaults(&(ssl_attr->mbedtls_attr.conf),
       MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_TRANSPORT_STREAM,
       MBEDTLS_SSL_PRESET_DEFAULT);
    if (ret != 0)
       MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_TRANSPORT_STREAM,
       MBEDTLS_SSL_PRESET_DEFAULT);
    if (ret != 0)
@@ -579,23 +420,23 @@ extern int create_client_ssl_connection(struct client_state *csp)
       goto exit;
    }
 
       goto exit;
    }
 
-   mbedtls_ssl_conf_rng(&(csp->mbedtls_client_attr.conf),
+   mbedtls_ssl_conf_rng(&(ssl_attr->mbedtls_attr.conf),
       mbedtls_ctr_drbg_random, &ctr_drbg);
       mbedtls_ctr_drbg_random, &ctr_drbg);
-   mbedtls_ssl_conf_dbg(&(csp->mbedtls_client_attr.conf),
+   mbedtls_ssl_conf_dbg(&(ssl_attr->mbedtls_attr.conf),
       ssl_debug_callback, stdout);
 
 #if defined(MBEDTLS_SSL_CACHE_C)
       ssl_debug_callback, stdout);
 
 #if defined(MBEDTLS_SSL_CACHE_C)
-   mbedtls_ssl_conf_session_cache(&(csp->mbedtls_client_attr.conf),
-      &(csp->mbedtls_client_attr.cache), mbedtls_ssl_cache_get,
+   mbedtls_ssl_conf_session_cache(&(ssl_attr->mbedtls_attr.conf),
+      &(ssl_attr->mbedtls_attr.cache), mbedtls_ssl_cache_get,
       mbedtls_ssl_cache_set);
 #endif
 
    /*
     * Setting certificates
     */
       mbedtls_ssl_cache_set);
 #endif
 
    /*
     * Setting certificates
     */
-   ret = mbedtls_ssl_conf_own_cert(&(csp->mbedtls_client_attr.conf),
-      &(csp->mbedtls_client_attr.server_cert),
-      &(csp->mbedtls_client_attr.prim_key));
+   ret = mbedtls_ssl_conf_own_cert(&(ssl_attr->mbedtls_attr.conf),
+      &(ssl_attr->mbedtls_attr.server_cert),
+      &(ssl_attr->mbedtls_attr.prim_key));
    if (ret != 0)
    {
       mbedtls_strerror(ret, err_buf, sizeof(err_buf));
    if (ret != 0)
    {
       mbedtls_strerror(ret, err_buf, sizeof(err_buf));
@@ -605,8 +446,8 @@ extern int create_client_ssl_connection(struct client_state *csp)
       goto exit;
    }
 
       goto exit;
    }
 
-   ret = mbedtls_ssl_setup(&(csp->mbedtls_client_attr.ssl),
-      &(csp->mbedtls_client_attr.conf));
+   ret = mbedtls_ssl_setup(&(ssl_attr->mbedtls_attr.ssl),
+      &(ssl_attr->mbedtls_attr.conf));
    if (ret != 0)
    {
       mbedtls_strerror(ret, err_buf, sizeof(err_buf));
    if (ret != 0)
    {
       mbedtls_strerror(ret, err_buf, sizeof(err_buf));
@@ -615,17 +456,17 @@ extern int create_client_ssl_connection(struct client_state *csp)
       goto exit;
    }
 
       goto exit;
    }
 
-   mbedtls_ssl_set_bio(&(csp->mbedtls_client_attr.ssl),
-      &(csp->mbedtls_client_attr.socket_fd), mbedtls_net_send,
+   mbedtls_ssl_set_bio(&(ssl_attr->mbedtls_attr.ssl),
+      &(ssl_attr->mbedtls_attr.socket_fd), mbedtls_net_send,
       mbedtls_net_recv, NULL);
       mbedtls_net_recv, NULL);
-   mbedtls_ssl_session_reset(&(csp->mbedtls_client_attr.ssl));
+   mbedtls_ssl_session_reset(&(ssl_attr->mbedtls_attr.ssl));
 
    /*
     * Setting socket fd in mbedtls_net_context structure. This structure
     * can't be set by mbedtls functions, because we already have created
     * a TCP connection when this function is called.
     */
 
    /*
     * Setting socket fd in mbedtls_net_context structure. This structure
     * can't be set by mbedtls functions, because we already have created
     * a TCP connection when this function is called.
     */
-   csp->mbedtls_client_attr.socket_fd.fd = csp->cfd;
+   ssl_attr->mbedtls_attr.socket_fd.fd = csp->cfd;
 
    /*
     *  Handshake with client
 
    /*
     *  Handshake with client
@@ -633,7 +474,7 @@ extern int create_client_ssl_connection(struct client_state *csp)
    log_error(LOG_LEVEL_CONNECT,
       "Performing the TLS/SSL handshake with client. Hash of host: %s",
       csp->http->hash_of_host_hex);
    log_error(LOG_LEVEL_CONNECT,
       "Performing the TLS/SSL handshake with client. Hash of host: %s",
       csp->http->hash_of_host_hex);
-   while ((ret = mbedtls_ssl_handshake(&(csp->mbedtls_client_attr.ssl))) != 0)
+   while ((ret = mbedtls_ssl_handshake(&(ssl_attr->mbedtls_attr.ssl))) != 0)
    {
       if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
           ret != MBEDTLS_ERR_SSL_WANT_WRITE)
    {
       if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
           ret != MBEDTLS_ERR_SSL_WANT_WRITE)
@@ -680,6 +521,7 @@ exit:
  *********************************************************************/
 extern void close_client_ssl_connection(struct client_state *csp)
 {
  *********************************************************************/
 extern void close_client_ssl_connection(struct client_state *csp)
 {
+   struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
    int ret = 0;
 
    if (csp->ssl_with_client_is_opened == 0)
    int ret = 0;
 
    if (csp->ssl_with_client_is_opened == 0)
@@ -691,7 +533,7 @@ extern void close_client_ssl_connection(struct client_state *csp)
     * Notifying the peer that the connection is being closed.
     */
    do {
     * Notifying the peer that the connection is being closed.
     */
    do {
-      ret = mbedtls_ssl_close_notify(&(csp->mbedtls_client_attr.ssl));
+      ret = mbedtls_ssl_close_notify(&(ssl_attr->mbedtls_attr.ssl));
    } while (ret == MBEDTLS_ERR_SSL_WANT_WRITE);
 
    free_client_ssl_structures(csp);
    } while (ret == MBEDTLS_ERR_SSL_WANT_WRITE);
 
    free_client_ssl_structures(csp);
@@ -714,21 +556,22 @@ extern void close_client_ssl_connection(struct client_state *csp)
  *********************************************************************/
 static void free_client_ssl_structures(struct client_state *csp)
 {
  *********************************************************************/
 static void free_client_ssl_structures(struct client_state *csp)
 {
+   struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
    /*
    * We can't use function mbedtls_net_free, because this function
    * inter alia close TCP connection on set fd. Instead of this
    * function, we change fd to -1, which is the same what does
    * rest of mbedtls_net_free function.
    */
    /*
    * We can't use function mbedtls_net_free, because this function
    * inter alia close TCP connection on set fd. Instead of this
    * function, we change fd to -1, which is the same what does
    * rest of mbedtls_net_free function.
    */
-   csp->mbedtls_client_attr.socket_fd.fd = -1;
+   ssl_attr->mbedtls_attr.socket_fd.fd = -1;
 
    /* Freeing mbedtls structures */
 
    /* Freeing mbedtls structures */
-   mbedtls_x509_crt_free(&(csp->mbedtls_client_attr.server_cert));
-   mbedtls_pk_free(&(csp->mbedtls_client_attr.prim_key));
-   mbedtls_ssl_free(&(csp->mbedtls_client_attr.ssl));
-   mbedtls_ssl_config_free(&(csp->mbedtls_client_attr.conf));
+   mbedtls_x509_crt_free(&(ssl_attr->mbedtls_attr.server_cert));
+   mbedtls_pk_free(&(ssl_attr->mbedtls_attr.prim_key));
+   mbedtls_ssl_free(&(ssl_attr->mbedtls_attr.ssl));
+   mbedtls_ssl_config_free(&(ssl_attr->mbedtls_attr.conf));
 #if defined(MBEDTLS_SSL_CACHE_C)
 #if defined(MBEDTLS_SSL_CACHE_C)
-   mbedtls_ssl_cache_free(&(csp->mbedtls_client_attr.cache));
+   mbedtls_ssl_cache_free(&(ssl_attr->mbedtls_attr.cache));
 #endif
 }
 
 #endif
 }
 
@@ -748,6 +591,7 @@ static void free_client_ssl_structures(struct client_state *csp)
  *********************************************************************/
 extern int create_server_ssl_connection(struct client_state *csp)
 {
  *********************************************************************/
 extern int create_server_ssl_connection(struct client_state *csp)
 {
+   struct ssl_attr *ssl_attr = &csp->ssl_server_attr;
    int ret = 0;
    char err_buf[ERROR_BUF_SIZE];
    char *trusted_cas_file = NULL;
    int ret = 0;
    char err_buf[ERROR_BUF_SIZE];
    char *trusted_cas_file = NULL;
@@ -762,17 +606,17 @@ extern int create_server_ssl_connection(struct client_state *csp)
    /*
     * Initializing mbedtls structures for TLS/SSL connection
     */
    /*
     * Initializing mbedtls structures for TLS/SSL connection
     */
-   mbedtls_net_init(&(csp->mbedtls_server_attr.socket_fd));
-   mbedtls_ssl_init(&(csp->mbedtls_server_attr.ssl));
-   mbedtls_ssl_config_init(&(csp->mbedtls_server_attr.conf));
-   mbedtls_x509_crt_init(&(csp->mbedtls_server_attr.ca_cert));
+   mbedtls_net_init(&(ssl_attr->mbedtls_attr.socket_fd));
+   mbedtls_ssl_init(&(ssl_attr->mbedtls_attr.ssl));
+   mbedtls_ssl_config_init(&(ssl_attr->mbedtls_attr.conf));
+   mbedtls_x509_crt_init(&(ssl_attr->mbedtls_attr.ca_cert));
 
    /*
    * Setting socket fd in mbedtls_net_context structure. This structure
    * can't be set by mbedtls functions, because we already have created
    * TCP connection when calling this function.
    */
 
    /*
    * Setting socket fd in mbedtls_net_context structure. This structure
    * can't be set by mbedtls functions, because we already have created
    * TCP connection when calling this function.
    */
-   csp->mbedtls_server_attr.socket_fd.fd = csp->server_connection.sfd;
+   ssl_attr->mbedtls_attr.socket_fd.fd = csp->server_connection.sfd;
 
    /*
     * Seed the RNG
 
    /*
     * Seed the RNG
@@ -787,7 +631,7 @@ extern int create_server_ssl_connection(struct client_state *csp)
    /*
     * Loading file with trusted CAs
     */
    /*
     * Loading file with trusted CAs
     */
-   ret = mbedtls_x509_crt_parse_file(&(csp->mbedtls_server_attr.ca_cert),
+   ret = mbedtls_x509_crt_parse_file(&(ssl_attr->mbedtls_attr.ca_cert),
       trusted_cas_file);
    if (ret < 0)
    {
       trusted_cas_file);
    if (ret < 0)
    {
@@ -801,7 +645,7 @@ extern int create_server_ssl_connection(struct client_state *csp)
    /*
     * Set TLS/SSL options
     */
    /*
     * Set TLS/SSL options
     */
-   ret = mbedtls_ssl_config_defaults(&(csp->mbedtls_server_attr.conf),
+   ret = mbedtls_ssl_config_defaults(&(ssl_attr->mbedtls_attr.conf),
       MBEDTLS_SSL_IS_CLIENT,
       MBEDTLS_SSL_TRANSPORT_STREAM,
       MBEDTLS_SSL_PRESET_DEFAULT);
       MBEDTLS_SSL_IS_CLIENT,
       MBEDTLS_SSL_TRANSPORT_STREAM,
       MBEDTLS_SSL_PRESET_DEFAULT);
@@ -823,21 +667,21 @@ extern int create_server_ssl_connection(struct client_state *csp)
       auth_mode = MBEDTLS_SSL_VERIFY_NONE;
    }
 
       auth_mode = MBEDTLS_SSL_VERIFY_NONE;
    }
 
-   mbedtls_ssl_conf_authmode(&(csp->mbedtls_server_attr.conf), auth_mode);
-   mbedtls_ssl_conf_ca_chain(&(csp->mbedtls_server_attr.conf),
-      &(csp->mbedtls_server_attr.ca_cert), NULL);
+   mbedtls_ssl_conf_authmode(&(ssl_attr->mbedtls_attr.conf), auth_mode);
+   mbedtls_ssl_conf_ca_chain(&(ssl_attr->mbedtls_attr.conf),
+      &(ssl_attr->mbedtls_attr.ca_cert), NULL);
 
    /* Setting callback function for certificates verification */
 
    /* Setting callback function for certificates verification */
-   mbedtls_ssl_conf_verify(&(csp->mbedtls_server_attr.conf),
+   mbedtls_ssl_conf_verify(&(ssl_attr->mbedtls_attr.conf),
       ssl_verify_callback, (void *)csp);
 
       ssl_verify_callback, (void *)csp);
 
-   mbedtls_ssl_conf_rng(&(csp->mbedtls_server_attr.conf),
+   mbedtls_ssl_conf_rng(&(ssl_attr->mbedtls_attr.conf),
       mbedtls_ctr_drbg_random, &ctr_drbg);
       mbedtls_ctr_drbg_random, &ctr_drbg);
-   mbedtls_ssl_conf_dbg(&(csp->mbedtls_server_attr.conf),
+   mbedtls_ssl_conf_dbg(&(ssl_attr->mbedtls_attr.conf),
       ssl_debug_callback, stdout);
 
       ssl_debug_callback, stdout);
 
-   ret = mbedtls_ssl_setup(&(csp->mbedtls_server_attr.ssl),
-      &(csp->mbedtls_server_attr.conf));
+   ret = mbedtls_ssl_setup(&(ssl_attr->mbedtls_attr.ssl),
+      &(ssl_attr->mbedtls_attr.conf));
    if (ret != 0)
    {
       mbedtls_strerror(ret, err_buf, sizeof(err_buf));
    if (ret != 0)
    {
       mbedtls_strerror(ret, err_buf, sizeof(err_buf));
@@ -849,7 +693,7 @@ extern int create_server_ssl_connection(struct client_state *csp)
    /*
     * Set the hostname to check against the received server certificate
     */
    /*
     * Set the hostname to check against the received server certificate
     */
-   ret = mbedtls_ssl_set_hostname(&(csp->mbedtls_server_attr.ssl),
+   ret = mbedtls_ssl_set_hostname(&(ssl_attr->mbedtls_attr.ssl),
       csp->http->host);
    if (ret != 0)
    {
       csp->http->host);
    if (ret != 0)
    {
@@ -860,8 +704,8 @@ extern int create_server_ssl_connection(struct client_state *csp)
       goto exit;
    }
 
       goto exit;
    }
 
-   mbedtls_ssl_set_bio(&(csp->mbedtls_server_attr.ssl),
-      &(csp->mbedtls_server_attr.socket_fd), mbedtls_net_send,
+   mbedtls_ssl_set_bio(&(ssl_attr->mbedtls_attr.ssl),
+      &(ssl_attr->mbedtls_attr.socket_fd), mbedtls_net_send,
       mbedtls_net_recv, NULL);
 
    /*
       mbedtls_net_recv, NULL);
 
    /*
@@ -870,7 +714,7 @@ extern int create_server_ssl_connection(struct client_state *csp)
    log_error(LOG_LEVEL_CONNECT,
       "Performing the TLS/SSL handshake with the server");
 
    log_error(LOG_LEVEL_CONNECT,
       "Performing the TLS/SSL handshake with the server");
 
-   while ((ret = mbedtls_ssl_handshake(&(csp->mbedtls_server_attr.ssl))) != 0)
+   while ((ret = mbedtls_ssl_handshake(&(ssl_attr->mbedtls_attr.ssl))) != 0)
    {
       if (ret != MBEDTLS_ERR_SSL_WANT_READ
        && ret != MBEDTLS_ERR_SSL_WANT_WRITE)
    {
       if (ret != MBEDTLS_ERR_SSL_WANT_READ
        && ret != MBEDTLS_ERR_SSL_WANT_WRITE)
@@ -882,7 +726,7 @@ extern int create_server_ssl_connection(struct client_state *csp)
             char reason[INVALID_CERT_INFO_BUF_SIZE];
 
             csp->server_cert_verification_result =
             char reason[INVALID_CERT_INFO_BUF_SIZE];
 
             csp->server_cert_verification_result =
-               mbedtls_ssl_get_verify_result(&(csp->mbedtls_server_attr.ssl));
+               mbedtls_ssl_get_verify_result(&(ssl_attr->mbedtls_attr.ssl));
             mbedtls_x509_crt_verify_info(reason, sizeof(reason), "",
                csp->server_cert_verification_result);
 
             mbedtls_x509_crt_verify_info(reason, sizeof(reason), "",
                csp->server_cert_verification_result);
 
@@ -913,7 +757,7 @@ extern int create_server_ssl_connection(struct client_state *csp)
 
    csp->ssl_with_server_is_opened = 1;
    csp->server_cert_verification_result =
 
    csp->ssl_with_server_is_opened = 1;
    csp->server_cert_verification_result =
-      mbedtls_ssl_get_verify_result(&(csp->mbedtls_server_attr.ssl));
+      mbedtls_ssl_get_verify_result(&(ssl_attr->mbedtls_attr.ssl));
 
 exit:
    /* Freeing structures if connection wasn't created successfully */
 
 exit:
    /* Freeing structures if connection wasn't created successfully */
@@ -939,8 +783,9 @@ exit:
  * Returns     :  N/A
  *
  *********************************************************************/
  * Returns     :  N/A
  *
  *********************************************************************/
-static void close_server_ssl_connection(struct client_state *csp)
+extern void close_server_ssl_connection(struct client_state *csp)
 {
 {
+   struct ssl_attr *ssl_attr = &csp->ssl_server_attr;
    int ret = 0;
 
    if (csp->ssl_with_server_is_opened == 0)
    int ret = 0;
 
    if (csp->ssl_with_server_is_opened == 0)
@@ -952,7 +797,7 @@ static void close_server_ssl_connection(struct client_state *csp)
    * Notifying the peer that the connection is being closed.
    */
    do {
    * Notifying the peer that the connection is being closed.
    */
    do {
-      ret = mbedtls_ssl_close_notify(&(csp->mbedtls_server_attr.ssl));
+      ret = mbedtls_ssl_close_notify(&(ssl_attr->mbedtls_attr.ssl));
    } while (ret == MBEDTLS_ERR_SSL_WANT_WRITE);
 
    free_server_ssl_structures(csp);
    } while (ret == MBEDTLS_ERR_SSL_WANT_WRITE);
 
    free_server_ssl_structures(csp);
@@ -974,45 +819,21 @@ static void close_server_ssl_connection(struct client_state *csp)
  *********************************************************************/
 static void free_server_ssl_structures(struct client_state *csp)
 {
  *********************************************************************/
 static void free_server_ssl_structures(struct client_state *csp)
 {
+   struct ssl_attr *ssl_attr = &csp->ssl_server_attr;
    /*
    * We can't use function mbedtls_net_free, because this function
    * inter alia close TCP connection on set fd. Instead of this
    * function, we change fd to -1, which is the same what does
    * rest of mbedtls_net_free function.
    */
    /*
    * We can't use function mbedtls_net_free, because this function
    * inter alia close TCP connection on set fd. Instead of this
    * function, we change fd to -1, which is the same what does
    * rest of mbedtls_net_free function.
    */
-   csp->mbedtls_server_attr.socket_fd.fd = -1;
+   ssl_attr->mbedtls_attr.socket_fd.fd = -1;
 
 
-   mbedtls_x509_crt_free(&(csp->mbedtls_server_attr.ca_cert));
-   mbedtls_ssl_free(&(csp->mbedtls_server_attr.ssl));
-   mbedtls_ssl_config_free(&(csp->mbedtls_server_attr.conf));
+   mbedtls_x509_crt_free(&(ssl_attr->mbedtls_attr.ca_cert));
+   mbedtls_ssl_free(&(ssl_attr->mbedtls_attr.ssl));
+   mbedtls_ssl_config_free(&(ssl_attr->mbedtls_attr.conf));
 }
 
 
 }
 
 
-/*********************************************************************
- *
- * Function    :  close_client_and_server_ssl_connections
- *
- * Description :  Checks if client or server should use secured
- *                connection over SSL and if so, closes all of them.
- *
- * Parameters  :
- *          1  :  csp = Current client state (buffers, headers, etc...)
- *
- * Returns     :  N/A
- *
- *********************************************************************/
-extern void close_client_and_server_ssl_connections(struct client_state *csp)
-{
-   if (client_use_ssl(csp) == 1)
-   {
-      close_client_ssl_connection(csp);
-   }
-   if (server_use_ssl(csp) == 1)
-   {
-      close_server_ssl_connection(csp);
-   }
-}
-
 /*====================== Certificates ======================*/
 
 /*********************************************************************
 /*====================== Certificates ======================*/
 
 /*********************************************************************
@@ -1319,101 +1140,6 @@ static int ssl_certificate_is_invalid(const char *cert_file)
 }
 
 
 }
 
 
-/*********************************************************************
- *
- * Function    :  generate_certificate_valid_date
- *
- * Description :  Turns a time_t into the format expected by mbedTLS.
- *
- * Parameters  :
- *          1  :  time_spec = The timestamp to convert
- *          2  :  buffer = The buffer to write the date to
- *          3  :  buffer_size = The size of the buffer
- *
- * Returns     :   0 => The conversion worked
- *                 1 => The conversion failed
- *
- *********************************************************************/
-static int generate_certificate_valid_date(time_t time_spec, char *buffer,
-                                           size_t buffer_size)
-{
-   struct tm valid_date;
-   struct tm *timeptr;
-   size_t ret;
-
-   timeptr = privoxy_gmtime_r(&time_spec, &valid_date);
-   if (NULL == timeptr)
-   {
-      return 1;
-   }
-
-   ret = strftime(buffer, buffer_size, "%Y%m%d%H%M%S", timeptr);
-   if (ret != 14)
-   {
-      return 1;
-   }
-
-   return 0;
-
-}
-
-
-/*********************************************************************
- *
- * Function    :  get_certificate_valid_from_date
- *
- * Description :  Generates a "valid from" date in the format
- *                expected by mbedTLS.
- *
- * Parameters  :
- *          1  :  buffer = The buffer to write the date to
- *          2  :  buffer_size = The size of the buffer
- *
- * Returns     :   0 => The generation worked
- *                 1 => The generation failed
- *
- *********************************************************************/
-static int get_certificate_valid_from_date(char *buffer, size_t buffer_size)
-{
-   time_t time_spec;
-
-   time_spec = time(NULL);
-   /* 1 month in the past */
-   time_spec -= 30 * 24 * 60 * 60;
-
-   return generate_certificate_valid_date(time_spec, buffer, buffer_size);
-
-}
-
-
-/*********************************************************************
- *
- * Function    :  get_certificate_valid_to_date
- *
- * Description :  Generates a "valid to" date in the format
- *                expected by mbedTLS.
- *
- * Parameters  :
- *          1  :  buffer = The buffer to write the date to
- *          2  :  buffer_size = The size of the buffer
- *
- * Returns     :   0 => The generation worked
- *                 1 => The generation failed
- *
- *********************************************************************/
-static int get_certificate_valid_to_date(char *buffer, size_t buffer_size)
-{
-   time_t time_spec;
-
-   time_spec = time(NULL);
-   /* Three months in the future */
-   time_spec += 90 * 24 * 60 * 60;
-
-   return generate_certificate_valid_date(time_spec, buffer, buffer_size);
-
-}
-
-
 /*********************************************************************
  *
  * Function    :  set_subject_alternative_name
 /*********************************************************************
  *
  * Function    :  set_subject_alternative_name
@@ -1521,49 +1247,6 @@ exit:
 }
 
 
 }
 
 
-/*********************************************************************
- *
- * Function    :  host_is_ip_address
- *
- * Description :  Checks whether or not a host is specified by
- *                IP address. Does not actually validate the
- *                address.
- *
- * Parameters  :
- *          1  :  host = The host name to check
- *
- * Returns     :   1 => Yes
- *                 0 => No
- *
- *********************************************************************/
-static int host_is_ip_address(const char *host)
-{
-   const char *p;
-
-   if (NULL != strstr(host, ":"))
-   {
-      /* Assume an IPv6 address. */
-      return 1;
-   }
-
-   for (p = host; *p; p++)
-   {
-      if ((*p != '.') && !privoxy_isdigit(*p))
-      {
-         /* Not a dot or digit so it can't be an IPv4 address. */
-         return 0;
-      }
-   }
-
-   /*
-    * Host only consists of dots and digits so
-    * assume that is an IPv4 address.
-    */
-   return 1;
-
-}
-
-
 /*********************************************************************
  *
  * Function    :  generate_webpage_certificate
 /*********************************************************************
  *
  * Function    :  generate_webpage_certificate
@@ -1596,8 +1279,8 @@ static int generate_webpage_certificate(struct client_state *csp)
    int ret = 0;
    char err_buf[ERROR_BUF_SIZE];
    cert_options cert_opt;
    int ret = 0;
    char err_buf[ERROR_BUF_SIZE];
    cert_options cert_opt;
-   char cert_valid_from[15];
-   char cert_valid_to[15];
+   char cert_valid_from[VALID_DATETIME_BUFLEN];
+   char cert_valid_to[VALID_DATETIME_BUFLEN];
 
    /* Paths to keys and certificates needed to create certificate */
    cert_opt.issuer_key  = NULL;
 
    /* Paths to keys and certificates needed to create certificate */
    cert_opt.issuer_key  = NULL;
@@ -1728,8 +1411,8 @@ static int generate_webpage_certificate(struct client_state *csp)
    cert_opt.issuer_crt = csp->config->ca_cert_file;
    cert_opt.issuer_key = csp->config->ca_key_file;
 
    cert_opt.issuer_crt = csp->config->ca_cert_file;
    cert_opt.issuer_key = csp->config->ca_key_file;
 
-   if (get_certificate_valid_from_date(cert_valid_from, sizeof(cert_valid_from))
-    || get_certificate_valid_to_date(cert_valid_to, sizeof(cert_valid_to)))
+   if (get_certificate_valid_from_date(cert_valid_from, sizeof(cert_valid_from), VALID_DATETIME_FMT)
+    || get_certificate_valid_to_date(cert_valid_to, sizeof(cert_valid_to), VALID_DATETIME_FMT))
    {
       log_error(LOG_LEVEL_ERROR, "Generating one of the validity dates failed");
       ret = -1;
    {
       log_error(LOG_LEVEL_ERROR, "Generating one of the validity dates failed");
       ret = -1;
@@ -1975,226 +1658,6 @@ exit:
    return ret;
 }
 
    return ret;
 }
 
-
-/*********************************************************************
- *
- * Function    :  make_certs_path
- *
- * Description : Creates path to file from three pieces. This function
- *               takes parameters and puts them in one new mallocated
- *               char * in correct order. Returned variable must be freed
- *               by caller. This function is mainly used for creating
- *               paths of certificates and keys files.
- *
- * Parameters  :
- *          1  :  conf_dir  = Name/path of directory where is the file.
- *                            '.' can be used for current directory.
- *          2  :  file_name = Name of file in conf_dir without suffix.
- *          3  :  suffix    = Suffix of given file_name.
- *
- * Returns     :  path => Path was built up successfully
- *                NULL => Path can't be built up
- *
- *********************************************************************/
-static char *make_certs_path(const char *conf_dir, const char *file_name,
-   const char *suffix)
-{
-   /* Test if all given parameters are valid */
-   if (conf_dir == NULL || *conf_dir == '\0' || file_name == NULL ||
-      *file_name == '\0' || suffix == NULL || *suffix == '\0')
-   {
-      log_error(LOG_LEVEL_ERROR,
-         "make_certs_path failed: bad input parameters");
-      return NULL;
-   }
-
-   char *path = NULL;
-   size_t path_size = strlen(conf_dir)
-      + strlen(file_name) + strlen(suffix) + 2;
-
-   /* Setting delimiter and editing path length */
-#if defined(_WIN32) || defined(__OS2__)
-   char delim[] = "\\";
-   path_size += 1;
-#else /* ifndef _WIN32 || __OS2__ */
-   char delim[] = "/";
-#endif /* ifndef _WIN32 || __OS2__ */
-
-   /*
-    * Building up path from many parts
-    */
-#if defined(unix)
-   if (*conf_dir != '/' && basedir && *basedir)
-   {
-      /*
-       * Replacing conf_dir with basedir. This new variable contains
-       * absolute path to cwd.
-       */
-      path_size += strlen(basedir) + 2;
-      path = zalloc_or_die(path_size);
-
-      strlcpy(path, basedir,   path_size);
-      strlcat(path, delim,     path_size);
-      strlcat(path, conf_dir,  path_size);
-      strlcat(path, delim,     path_size);
-      strlcat(path, file_name, path_size);
-      strlcat(path, suffix,    path_size);
-   }
-   else
-#endif /* defined unix */
-   {
-      path = zalloc_or_die(path_size);
-
-      strlcpy(path, conf_dir,  path_size);
-      strlcat(path, delim,     path_size);
-      strlcat(path, file_name, path_size);
-      strlcat(path, suffix,    path_size);
-   }
-
-   return path;
-}
-
-
-/*********************************************************************
- *
- * Function    :  get_certificate_serial
- *
- * Description :  Computes serial number for new certificate from host
- *                name hash. This hash must be already saved in csp
- *                structure.
- *
- * Parameters  :
- *          1  :  csp = Current client state (buffers, headers, etc...)
- *
- * Returns     :  Serial number for new certificate
- *
- *********************************************************************/
-static unsigned long get_certificate_serial(struct client_state *csp)
-{
-   unsigned long exp    = 1;
-   unsigned long serial = 0;
-
-   int i = CERT_SERIAL_NUM_LENGTH;
-
-   for (; i >= 0; i--)
-   {
-      serial += exp * (unsigned)csp->http->hash_of_host[i];
-      exp *= 256;
-   }
-   return serial;
-}
-
-
-/*********************************************************************
- *
- * Function    :  ssl_send_certificate_error
- *
- * Description :  Sends info about invalid server certificate to client.
- *                Sent message is including all trusted chain certificates,
- *                that can be downloaded in web browser.
- *
- * Parameters  :
- *          1  :  csp = Current client state (buffers, headers, etc...)
- *
- * Returns     :  N/A
- *
- *********************************************************************/
-extern void ssl_send_certificate_error(struct client_state *csp)
-{
-   size_t message_len = 0;
-   int ret = 0;
-   struct certs_chain *cert = NULL;
-
-   /* Header of message with certificate information */
-   const char message_begin[] =
-      "HTTP/1.1 200 OK\r\n"
-      "Content-Type: text/html\r\n"
-      "Connection: close\r\n\r\n"
-      "<!DOCTYPE html>\n"
-      "<html><head><title>Server certificate verification failed</title></head>\n"
-      "<body><h1>Server certificate verification failed</h1>\n"
-      "<p><a href=\"https://" CGI_SITE_2_HOST "/\">Privoxy</a> was unable "
-      "to securely connnect to the destination server.</p>"
-      "<p>Reason: ";
-   const char message_end[] = "</body></html>\r\n\r\n";
-   char reason[INVALID_CERT_INFO_BUF_SIZE];
-   memset(reason, 0, sizeof(reason));
-
-   /* Get verification message from verification return code */
-   mbedtls_x509_crt_verify_info(reason, sizeof(reason), " ",
-      csp->server_cert_verification_result);
-
-   /*
-    * Computing total length of message with all certificates inside
-    */
-   message_len = strlen(message_begin) + strlen(message_end)
-                 + strlen(reason) + strlen("</p>") + 1;
-
-   cert = &(csp->server_certs_chain);
-   while (cert->next != NULL)
-   {
-      size_t base64_len = 4 * ((strlen(cert->file_buf) + 2) / 3) + 1;
-
-      message_len += strlen(cert->info_buf) + strlen("<pre></pre>\n")
-                     +  base64_len + strlen("<a href=\"data:application"
-                        "/x-x509-ca-cert;base64,\">Download certificate</a>");
-      cert = cert->next;
-   }
-
-   /*
-    * Joining all blocks in one long message
-    */
-   char message[message_len];
-   memset(message, 0, message_len);
-
-   strlcpy(message, message_begin, message_len);
-   strlcat(message, reason       , message_len);
-   strlcat(message, "</p>"       , message_len);
-
-   cert = &(csp->server_certs_chain);
-   while (cert->next != NULL)
-   {
-      size_t olen = 0;
-      size_t base64_len = 4 * ((strlen(cert->file_buf) + 2) / 3) + 1; /* +1 for terminating null*/
-      char base64_buf[base64_len];
-      memset(base64_buf, 0, base64_len);
-
-      /* Encoding certificate into base64 code */
-      ret = mbedtls_base64_encode((unsigned char*)base64_buf,
-               base64_len, &olen, (const unsigned char*)cert->file_buf,
-               strlen(cert->file_buf));
-      if (ret != 0)
-      {
-         log_error(LOG_LEVEL_ERROR,
-            "Encoding to base64 failed, buffer is to small");
-      }
-
-      strlcat(message, "<pre>",        message_len);
-      strlcat(message, cert->info_buf, message_len);
-      strlcat(message, "</pre>\n",     message_len);
-
-      if (ret == 0)
-      {
-         strlcat(message, "<a href=\"data:application/x-x509-ca-cert;base64,",
-            message_len);
-         strlcat(message, base64_buf, message_len);
-         strlcat(message, "\">Download certificate</a>", message_len);
-      }
-
-      cert = cert->next;
-   }
-   strlcat(message, message_end, message_len);
-
-   /*
-    * Sending final message to client
-    */
-   ssl_send_data(&(csp->mbedtls_client_attr.ssl),
-      (const unsigned char *)message, strlen(message));
-
-   free_certificate_chain(csp);
-}
-
-
 /*********************************************************************
  *
  * Function    :  ssl_verify_callback
 /*********************************************************************
  *
  * Function    :  ssl_verify_callback
@@ -2271,67 +1734,6 @@ static int ssl_verify_callback(void *csp_void, mbedtls_x509_crt *crt,
 }
 
 
 }
 
 
-/*********************************************************************
- *
- * Function    :  free_certificate_chain
- *
- * Description :  Frees certificates linked list. This linked list is
- *                used to save information about certificates in
- *                trusted chain.
- *
- * Parameters  :
- *          1  :  csp = Current client state (buffers, headers, etc...)
- *
- * Returns     :  N/A
- *
- *********************************************************************/
-static void free_certificate_chain(struct client_state *csp)
-{
-   struct certs_chain *cert = csp->server_certs_chain.next;
-
-   /* Cleaning buffers */
-   memset(csp->server_certs_chain.info_buf, 0,
-      sizeof(csp->server_certs_chain.info_buf));
-   memset(csp->server_certs_chain.file_buf, 0,
-      sizeof(csp->server_certs_chain.file_buf));
-   csp->server_certs_chain.next = NULL;
-
-   /* Freeing memory in whole linked list */
-   while (cert != NULL)
-   {
-      struct certs_chain *cert_for_free = cert;
-      cert = cert->next;
-      freez(cert_for_free);
-   }
-}
-
-
-/*********************************************************************
- *
- * Function    :  file_exists
- *
- * Description :  Tests if file exists and is readable.
- *
- * Parameters  :
- *          1  :  path = Path to tested file.
- *
- * Returns     :  1 => File exists and is readable.
- *                0 => File doesn't exist or is not readable.
- *
- *********************************************************************/
-static int file_exists(const char *path)
-{
-   FILE *f;
-   if ((f = fopen(path, "r")) != NULL)
-   {
-      fclose(f);
-      return 1;
-   }
-
-   return 0;
-}
-
-
 /*********************************************************************
  *
  * Function    :  host_to_hash
 /*********************************************************************
  *
  * Function    :  host_to_hash
@@ -2373,68 +1775,6 @@ static int host_to_hash(struct client_state *csp)
 #endif /* MBEDTLS_MD5_C */
 }
 
 #endif /* MBEDTLS_MD5_C */
 }
 
-
-/*********************************************************************
- *
- * Function    :  tunnel_established_successfully
- *
- * Description :  Check if parent proxy server response contains
- *                information about successfully created connection with
- *                destination server. (HTTP/... 2xx ...)
- *
- * Parameters  :
- *          1  :  server_response = Buffer with parent proxy server response
- *          2  :  response_len = Length of server_response
- *
- * Returns     :  1 => Connection created successfully
- *                0 => Connection wasn't created successfully
- *
- *********************************************************************/
-extern int tunnel_established_successfully(const char *server_response,
-   unsigned int response_len)
-{
-   unsigned int pos = 0;
-
-   if (server_response == NULL)
-   {
-      return 0;
-   }
-
-   /* Tests if "HTTP/" string is at the begin of received response */
-   if (strncmp(server_response, "HTTP/", 5) != 0)
-   {
-      return 0;
-   }
-
-   for (pos = 0; pos < response_len; pos++)
-   {
-      if (server_response[pos] == ' ')
-      {
-         break;
-      }
-   }
-
-   /*
-    * response_len -3 because of buffer end, response structure and 200 code.
-    * There must be at least 3 chars after space.
-    * End of buffer: ... 2xx'\0'
-    *             pos = |
-    */
-   if (pos >= (response_len - 3))
-   {
-      return 0;
-   }
-
-   /* Test HTTP status code */
-   if (server_response[pos + 1] != '2')
-   {
-      return 0;
-   }
-
-   return 1;
-}
-
-
 /*********************************************************************
  *
  * Function    :  seed_rng
 /*********************************************************************
  *
  * Function    :  seed_rng
@@ -2455,7 +1795,7 @@ static int seed_rng(struct client_state *csp)
 
    if (rng_seeded == 0)
    {
 
    if (rng_seeded == 0)
    {
-      privoxy_mutex_lock(&rng_mutex);
+      privoxy_mutex_lock(&ssl_init_mutex);
       if (rng_seeded == 0)
       {
          mbedtls_ctr_drbg_init(&ctr_drbg);
       if (rng_seeded == 0)
       {
          mbedtls_ctr_drbg_init(&ctr_drbg);
@@ -2467,12 +1807,77 @@ static int seed_rng(struct client_state *csp)
             mbedtls_strerror(ret, err_buf, sizeof(err_buf));
             log_error(LOG_LEVEL_ERROR,
                "mbedtls_ctr_drbg_seed failed: %s", err_buf);
             mbedtls_strerror(ret, err_buf, sizeof(err_buf));
             log_error(LOG_LEVEL_ERROR,
                "mbedtls_ctr_drbg_seed failed: %s", err_buf);
-            privoxy_mutex_unlock(&rng_mutex);
+            privoxy_mutex_unlock(&ssl_init_mutex);
             return -1;
          }
          rng_seeded = 1;
       }
             return -1;
          }
          rng_seeded = 1;
       }
-      privoxy_mutex_unlock(&rng_mutex);
+      privoxy_mutex_unlock(&ssl_init_mutex);
    }
    return 0;
 }
    }
    return 0;
 }
+
+
+/*********************************************************************
+ *
+ * Function    :  ssl_base64_encode
+ *
+ * Description :  Encode a buffer into base64 format.
+ *
+ * Parameters  :
+ *          1  :  dst = Destination buffer
+ *          2  :  dlen = Destination buffer length
+ *          3  :  olen = Number of bytes written
+ *          4  :  src = Source buffer
+ *          5  :  slen = Amount of data to be encoded
+ *
+ * Returns     :  0 on success, error code othervise
+ *
+ *********************************************************************/
+extern int ssl_base64_encode(unsigned char *dst, size_t dlen, size_t *olen,
+                              const unsigned char *src, size_t slen )
+{
+   return mbedtls_base64_encode(dst, dlen, olen, src, slen);
+}
+
+
+/*********************************************************************
+ *
+ * Function    :  ssl_crt_verify_info
+ *
+ * Description :  Returns an informational string about the verification
+ *                status of a certificate.
+ *
+ * Parameters  :
+ *          1  :  buf = Buffer to write to
+ *          2  :  size = Maximum size of buffer
+ *          3  :  csp = client state
+ *
+ * Returns     :  N/A
+ *
+ *********************************************************************/
+extern void ssl_crt_verify_info(char *buf, size_t size, struct client_state *csp)
+{
+   mbedtls_x509_crt_verify_info(buf, size, " ", csp->server_cert_verification_result);
+}
+
+
+/*********************************************************************
+ *
+ * Function    :  ssl_release
+ *
+ * Description :  Release all SSL resources
+ *
+ * Parameters  :
+ *
+ * Returns     :  N/A
+ *
+ *********************************************************************/
+extern void ssl_release(void)
+{
+   if (rng_seeded == 1)
+   {
+      mbedtls_ctr_drbg_free(&ctr_drbg);
+      mbedtls_entropy_free(&entropy);
+   }
+}
diff --git a/ssl.h b/ssl.h
index f62f973..f4f69a6 100644 (file)
--- a/ssl.h
+++ b/ssl.h
@@ -2,7 +2,7 @@
 #define SSL_H_INCLUDED
 /*********************************************************************
 *
 #define SSL_H_INCLUDED
 /*********************************************************************
 *
-* File        :  $Source: /cvsroot/ijbswa/current/ssl.h,v $
+* File        :  $Source: $
 *
 * Purpose     :  File with TLS/SSL extension. Contains methods for
 *                creating, using and closing TLS/SSL connections.
 *
 * Purpose     :  File with TLS/SSL extension. Contains methods for
 *                creating, using and closing TLS/SSL connections.
 
 #include "project.h"
 
 
 #include "project.h"
 
-/*
- * Values for flag determining certificate validity.
- * These values are compatible with return value of function
- * mbedtls_ssl_get_verify_result(). There is no value for
- * "invalid certificate", this value is set by the function
- * mbedtls_ssl_get_verify_result().
- */
-#define SSL_CERT_VALID          0
-#define SSL_CERT_NOT_VERIFIED   0xFFFFFFFF
-
-/* Variables for one common RNG for all SSL use */
-static mbedtls_ctr_drbg_context ctr_drbg;
-static mbedtls_entropy_context  entropy;
-static int rng_seeded;
-
 /* Boolean functions to get information about TLS/SSL connections */
 extern int    client_use_ssl(const struct client_state *csp);
 extern int    server_use_ssl(const struct client_state *csp);
 /* Boolean functions to get information about TLS/SSL connections */
 extern int    client_use_ssl(const struct client_state *csp);
 extern int    server_use_ssl(const struct client_state *csp);
-extern size_t is_ssl_pending(mbedtls_ssl_context *ssl);
+extern size_t is_ssl_pending(struct ssl_attr *ssl_attr);
 extern int tunnel_established_successfully(const char *response, unsigned int response_len);
 
 /* Functions for sending and receiving data over TLS/SSL connections */
 extern int tunnel_established_successfully(const char *response, unsigned int response_len);
 
 /* Functions for sending and receiving data over TLS/SSL connections */
-extern int  ssl_send_data(mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len);
-extern int ssl_send_data_delayed(mbedtls_ssl_context *ssl, const unsigned char *buf,
+extern int  ssl_send_data(struct ssl_attr *ssl_attr, const unsigned char *buf, size_t len);
+extern int ssl_send_data_delayed(struct ssl_attr *ssl_attr, const unsigned char *buf,
                                  size_t len, unsigned int delay);
                                  size_t len, unsigned int delay);
-extern int  ssl_recv_data(mbedtls_ssl_context *ssl, unsigned char *buf, size_t maxLen);
-extern long ssl_flush_socket(mbedtls_ssl_context *ssl, struct iob *iob);
+extern int  ssl_recv_data(struct ssl_attr *ssl_attr, unsigned char *buf, size_t maxLen);
+extern long ssl_flush_socket(struct ssl_attr *ssl_attr, struct iob *iob);
 extern void ssl_send_certificate_error(struct client_state *csp);
 
 /* Functions for opening and closing TLS/SSL connections */
 extern int  create_client_ssl_connection(struct client_state *csp);
 extern int  create_server_ssl_connection(struct client_state *csp);
 extern void close_client_and_server_ssl_connections(struct client_state *csp);
 extern void ssl_send_certificate_error(struct client_state *csp);
 
 /* Functions for opening and closing TLS/SSL connections */
 extern int  create_client_ssl_connection(struct client_state *csp);
 extern int  create_server_ssl_connection(struct client_state *csp);
 extern void close_client_and_server_ssl_connections(struct client_state *csp);
+extern void close_server_ssl_connection(struct client_state *csp);
 extern void close_client_ssl_connection(struct client_state *csp);
 
 extern void close_client_ssl_connection(struct client_state *csp);
 
+/* misc helper functions */
+extern int ssl_base64_encode(unsigned char *dst, size_t dlen, size_t *olen,
+                             const unsigned char *src, size_t slen );
+extern void ssl_crt_verify_info(char *buf, size_t size, struct client_state *csp);
+extern void ssl_release(void);
+
 #endif /* ndef SSL_H_INCLUDED */
 #endif /* ndef SSL_H_INCLUDED */
diff --git a/ssl_common.c b/ssl_common.c
new file mode 100644 (file)
index 0000000..1aa1336
--- /dev/null
@@ -0,0 +1,688 @@
+/*********************************************************************
+ *
+ * File        :  $Source: /cvsroot/ijbswa/current/ssl.c,v $
+ *
+ * Purpose     :  File with TLS/SSL extension. Contains methods for
+ *                creating, using and closing TLS/SSL connections that do
+ *                not depend on particular TLS/SSL library.
+ *
+ * Copyright   :  Written by and Copyright (c) 2017 Vaclav Svec. FIT CVUT.
+ *                Copyright (C) 2018-2020 by Fabian Keil <fk@fabiankeil.de>
+ *
+ *                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 2 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.
+ *
+ *                The GNU General Public License should be included with
+ *                this file.  If not, you can view it at
+ *                http://www.gnu.org/copyleft/gpl.html
+ *                or write to the Free Software Foundation, Inc., 59
+ *                Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ *
+ *********************************************************************/
+#include <string.h>
+
+#include <ctype.h>
+#include "config.h"
+#include "project.h"
+#include "miscutil.h"
+#include "errlog.h"
+#include "ssl.h"
+#include "ssl_common.h"
+
+/*
+ * Macros for ssl_common.c
+ */
+#define CERT_SERIAL_NUM_LENGTH           4                 /* Bytes of hash to be used for creating serial number of certificate. Min=2 and max=16 */
+
+/*********************************************************************
+ *
+ * Function    :  client_use_ssl
+ *
+ * Description :  Tests if client in current client state structure
+ *                should use SSL connection or standard connection.
+ *
+ * Parameters  :
+ *          1  :  csp = Current client state (buffers, headers, etc...)
+ *
+ * Returns     :  If client should use TLS/SSL connection, 1 is returned.
+ *                Otherwise 0 is returned.
+ *
+ *********************************************************************/
+extern int client_use_ssl(const struct client_state *csp)
+{
+   return csp->http->client_ssl;
+}
+
+
+/*********************************************************************
+ *
+ * Function    :  server_use_ssl
+ *
+ * Description :  Tests if server in current client state structure
+ *                should use SSL connection or standard connection.
+ *
+ * Parameters  :
+ *          1  :  csp = Current client state (buffers, headers, etc...)
+ *
+ * Returns     :  If server should use TLS/SSL connection, 1 is returned.
+ *                Otherwise 0 is returned.
+ *
+ *********************************************************************/
+extern int server_use_ssl(const struct client_state *csp)
+{
+   return csp->http->server_ssl;
+}
+
+
+/*********************************************************************
+ *
+ * Function    :  ssl_send_data_delayed
+ *
+ * Description :  Sends the contents of buf (for n bytes) to given SSL
+ *                connection, optionally delaying the operation.
+ *
+ * Parameters  :
+ *          1  :  ssl = SSL context to send data to
+ *          2  :  buf = Pointer to data to be sent
+ *          3  :  len = Length of data to be sent to the SSL context
+ *          4  :  delay = Delay in milliseconds.
+ *
+ * Returns     :  0 on success (entire buffer sent).
+ *                nonzero on error.
+ *
+ *********************************************************************/
+extern int ssl_send_data_delayed(struct ssl_attr* ssl_attr,
+                                 const unsigned char *buf, size_t len,
+                                 unsigned int delay)
+{
+   size_t i = 0;
+
+   if (delay == 0)
+   {
+      if (ssl_send_data(ssl_attr, buf, len) < 0)
+      {
+         return -1;
+      }
+      else
+      {
+         return 0;
+      }
+   }
+
+   while (i < len)
+   {
+      size_t write_length;
+      enum { MAX_WRITE_LENGTH = 10 };
+
+      if ((i + MAX_WRITE_LENGTH) > len)
+      {
+         write_length = len - i;
+      }
+      else
+      {
+         write_length = MAX_WRITE_LENGTH;
+      }
+
+      privoxy_millisleep(delay);
+
+      if (ssl_send_data(ssl_attr, buf + i, write_length) < 0)
+      {
+         return -1;
+      }
+      i += write_length;
+   }
+
+   return 0;
+
+}
+
+
+/*********************************************************************
+ *
+ * Function    :  ssl_flush_socket
+ *
+ * Description :  Send any pending "buffered" content with given
+ *                SSL connection. Alternative to function flush_socket.
+ *
+ * Parameters  :
+ *          1  :  ssl = SSL context to send buffer to
+ *          2  :  iob = The I/O buffer to flush, usually csp->iob.
+ *
+ * Returns     :  On success, the number of bytes send are returned (zero
+ *                indicates nothing was sent).  On error, -1 is returned.
+ *
+ *********************************************************************/
+extern long ssl_flush_socket(struct ssl_attr *ssl_attr, struct iob *iob)
+{
+   /* Computing length of buffer part to send */
+   long len = iob->eod - iob->cur;
+
+   if (len <= 0)
+   {
+      return(0);
+   }
+
+   /* Sending data to given SSl context */
+   if (ssl_send_data(ssl_attr, (const unsigned char *)iob->cur, (size_t)len) < 0)
+   {
+      return -1;
+   }
+   iob->eod = iob->cur = iob->buf;
+   return(len);
+}
+
+
+/*********************************************************************
+ *
+ * Function    :  close_client_and_server_ssl_connections
+ *
+ * Description :  Checks if client or server should use secured
+ *                connection over SSL and if so, closes all of them.
+ *
+ * Parameters  :
+ *          1  :  csp = Current client state (buffers, headers, etc...)
+ *
+ * Returns     :  N/A
+ *
+ *********************************************************************/
+extern void close_client_and_server_ssl_connections(struct client_state *csp)
+{
+   if (client_use_ssl(csp) == 1)
+   {
+      close_client_ssl_connection(csp);
+   }
+   if (server_use_ssl(csp) == 1)
+   {
+      close_server_ssl_connection(csp);
+   }
+}
+
+
+/*********************************************************************
+ *
+ * Function    :  tunnel_established_successfully
+ *
+ * Description :  Check if parent proxy server response contains
+ *                information about successfully created connection with
+ *                destination server. (HTTP/... 2xx ...)
+ *
+ * Parameters  :
+ *          1  :  server_response = Buffer with parent proxy server response
+ *          2  :  response_len = Length of server_response
+ *
+ * Returns     :  1 => Connection created successfully
+ *                0 => Connection wasn't created successfully
+ *
+ *********************************************************************/
+extern int tunnel_established_successfully(const char *server_response,
+   unsigned int response_len)
+{
+   unsigned int pos = 0;
+
+   if (server_response == NULL)
+   {
+      return 0;
+   }
+
+   /* Tests if "HTTP/" string is at the begin of received response */
+   if (strncmp(server_response, "HTTP/", 5) != 0)
+   {
+      return 0;
+   }
+
+   for (pos = 0; pos < response_len; pos++)
+   {
+      if (server_response[pos] == ' ')
+      {
+         break;
+      }
+   }
+
+   /*
+    * response_len -3 because of buffer end, response structure and 200 code.
+    * There must be at least 3 chars after space.
+    * End of buffer: ... 2xx'\0'
+    *             pos = |
+    */
+   if (pos >= (response_len - 3))
+   {
+      return 0;
+   }
+
+   /* Test HTTP status code */
+   if (server_response[pos + 1] != '2')
+   {
+      return 0;
+   }
+
+   return 1;
+}
+
+
+/*********************************************************************
+ *
+ * Function    :  free_certificate_chain
+ *
+ * Description :  Frees certificates linked list. This linked list is
+ *                used to save information about certificates in
+ *                trusted chain.
+ *
+ * Parameters  :
+ *          1  :  csp = Current client state (buffers, headers, etc...)
+ *
+ * Returns     :  N/A
+ *
+ *********************************************************************/
+extern void free_certificate_chain(struct client_state *csp)
+{
+   struct certs_chain *cert = csp->server_certs_chain.next;
+
+   /* Cleaning buffers */
+   memset(csp->server_certs_chain.info_buf, 0,
+      sizeof(csp->server_certs_chain.info_buf));
+   memset(csp->server_certs_chain.file_buf, 0,
+      sizeof(csp->server_certs_chain.file_buf));
+   csp->server_certs_chain.next = NULL;
+
+   /* Freeing memory in whole linked list */
+   while (cert != NULL)
+   {
+      struct certs_chain *cert_for_free = cert;
+      cert = cert->next;
+      freez(cert_for_free);
+   }
+}
+
+
+/*********************************************************************
+ *
+ * Function    :  ssl_send_certificate_error
+ *
+ * Description :  Sends info about invalid server certificate to client.
+ *                Sent message is including all trusted chain certificates,
+ *                that can be downloaded in web browser.
+ *
+ * Parameters  :
+ *          1  :  csp = Current client state (buffers, headers, etc...)
+ *
+ * Returns     :  N/A
+ *
+ *********************************************************************/
+extern void ssl_send_certificate_error(struct client_state *csp)
+{
+   struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
+   size_t message_len = 0;
+   int ret = 0;
+   struct certs_chain *cert = NULL;
+
+   /* Header of message with certificate information */
+   const char message_begin[] =
+      "HTTP/1.1 200 OK\r\n"
+      "Content-Type: text/html\r\n"
+      "Connection: close\r\n\r\n"
+      "<!DOCTYPE html>\n"
+      "<html><head><title>Server certificate verification failed</title></head>\n"
+      "<body><h1>Server certificate verification failed</h1>\n"
+      "<p><a href=\"https://" CGI_SITE_2_HOST "/\">Privoxy</a> was unable "
+      "to securely connnect to the destination server.</p>"
+      "<p>Reason: ";
+   const char message_end[] = "</body></html>\r\n\r\n";
+   char reason[INVALID_CERT_INFO_BUF_SIZE];
+   memset(reason, 0, sizeof(reason));
+
+   /* Get verification message from verification return code */
+   ssl_crt_verify_info(reason, sizeof(reason), csp);
+
+   /*
+    * Computing total length of message with all certificates inside
+    */
+   message_len = strlen(message_begin) + strlen(message_end)
+                 + strlen(reason) + strlen("</p>") + 1;
+
+   cert = &(csp->server_certs_chain);
+   while (cert->next != NULL)
+   {
+      size_t base64_len = 4 * ((strlen(cert->file_buf) + 2) / 3) + 1;
+
+      message_len += strlen(cert->info_buf) + strlen("<pre></pre>\n")
+                     +  base64_len + strlen("<a href=\"data:application"
+                        "/x-x509-ca-cert;base64,\">Download certificate</a>");
+      cert = cert->next;
+   }
+
+   /*
+    * Joining all blocks in one long message
+    */
+   char message[message_len];
+   memset(message, 0, message_len);
+
+   strlcpy(message, message_begin, message_len);
+   strlcat(message, reason       , message_len);
+   strlcat(message, "</p>"       , message_len);
+
+   cert = &(csp->server_certs_chain);
+   while (cert->next != NULL)
+   {
+      size_t olen = 0;
+      size_t base64_len = 4 * ((strlen(cert->file_buf) + 2) / 3) + 1; /* +1 for terminating null*/
+      char base64_buf[base64_len];
+      memset(base64_buf, 0, base64_len);
+
+      /* Encoding certificate into base64 code */
+      ret = ssl_base64_encode((unsigned char*)base64_buf,
+               base64_len, &olen, (const unsigned char*)cert->file_buf,
+               strlen(cert->file_buf));
+      if (ret != 0)
+      {
+         log_error(LOG_LEVEL_ERROR,
+            "Encoding to base64 failed, buffer is to small");
+      }
+
+      strlcat(message, "<pre>",        message_len);
+      strlcat(message, cert->info_buf, message_len);
+      strlcat(message, "</pre>\n",     message_len);
+
+      if (ret == 0)
+      {
+         strlcat(message, "<a href=\"data:application/x-x509-ca-cert;base64,",
+            message_len);
+         strlcat(message, base64_buf, message_len);
+         strlcat(message, "\">Download certificate</a>", message_len);
+      }
+
+      cert = cert->next;
+   }
+   strlcat(message, message_end, message_len);
+
+   /*
+    * Sending final message to client
+    */
+   ssl_send_data(ssl_attr, (const unsigned char *)message, strlen(message));
+
+   free_certificate_chain(csp);
+}
+
+
+/*********************************************************************
+ *
+ * Function    :  file_exists
+ *
+ * Description :  Tests if file exists and is readable.
+ *
+ * Parameters  :
+ *          1  :  path = Path to tested file.
+ *
+ * Returns     :  1 => File exists and is readable.
+ *                0 => File doesn't exist or is not readable.
+ *
+ *********************************************************************/
+extern int file_exists(const char *path)
+{
+   FILE *f;
+   if ((f = fopen(path, "r")) != NULL)
+   {
+      fclose(f);
+      return 1;
+   }
+
+   return 0;
+}
+
+
+/*********************************************************************
+ *
+ * Function    :  make_certs_path
+ *
+ * Description : Creates path to file from three pieces. This function
+ *               takes parameters and puts them in one new mallocated
+ *               char * in correct order. Returned variable must be freed
+ *               by caller. This function is mainly used for creating
+ *               paths of certificates and keys files.
+ *
+ * Parameters  :
+ *          1  :  conf_dir  = Name/path of directory where is the file.
+ *                            '.' can be used for current directory.
+ *          2  :  file_name = Name of file in conf_dir without suffix.
+ *          3  :  suffix    = Suffix of given file_name.
+ *
+ * Returns     :  path => Path was built up successfully
+ *                NULL => Path can't be built up
+ *
+ *********************************************************************/
+extern char *make_certs_path(const char *conf_dir, const char *file_name,
+   const char *suffix)
+{
+   /* Test if all given parameters are valid */
+   if (conf_dir == NULL || *conf_dir == '\0' || file_name == NULL ||
+      *file_name == '\0' || suffix == NULL || *suffix == '\0')
+   {
+      log_error(LOG_LEVEL_ERROR,
+         "make_certs_path failed: bad input parameters");
+      return NULL;
+   }
+
+   char *path = NULL;
+   size_t path_size = strlen(conf_dir)
+      + strlen(file_name) + strlen(suffix) + 2;
+
+   /* Setting delimiter and editing path length */
+#if defined(_WIN32) || defined(__OS2__)
+   char delim[] = "\\";
+   path_size += 1;
+#else /* ifndef _WIN32 || __OS2__ */
+   char delim[] = "/";
+#endif /* ifndef _WIN32 || __OS2__ */
+
+   /*
+    * Building up path from many parts
+    */
+#if defined(unix)
+   if (*conf_dir != '/' && basedir && *basedir)
+   {
+      /*
+       * Replacing conf_dir with basedir. This new variable contains
+       * absolute path to cwd.
+       */
+      path_size += strlen(basedir) + 2;
+      path = zalloc_or_die(path_size);
+
+      strlcpy(path, basedir,   path_size);
+      strlcat(path, delim,     path_size);
+      strlcat(path, conf_dir,  path_size);
+      strlcat(path, delim,     path_size);
+      strlcat(path, file_name, path_size);
+      strlcat(path, suffix,    path_size);
+   }
+   else
+#endif /* defined unix */
+   {
+      path = zalloc_or_die(path_size);
+
+      strlcpy(path, conf_dir,  path_size);
+      strlcat(path, delim,     path_size);
+      strlcat(path, file_name, path_size);
+      strlcat(path, suffix,    path_size);
+   }
+
+   return path;
+}
+
+
+/*********************************************************************
+ *
+ * Function    :  get_certificate_serial
+ *
+ * Description :  Computes serial number for new certificate from host
+ *                name hash. This hash must be already saved in csp
+ *                structure.
+ *
+ * Parameters  :
+ *          1  :  csp = Current client state (buffers, headers, etc...)
+ *
+ * Returns     :  Serial number for new certificate
+ *
+ *********************************************************************/
+extern unsigned long get_certificate_serial(struct client_state *csp)
+{
+   unsigned long exp    = 1;
+   unsigned long serial = 0;
+
+   int i = CERT_SERIAL_NUM_LENGTH;
+
+   for (; i >= 0; i--)
+   {
+      serial += exp * (unsigned)csp->http->hash_of_host[i];
+      exp *= 256;
+   }
+   return serial;
+}
+
+
+/*********************************************************************
+ *
+ * Function    :  generate_certificate_valid_date
+ *
+ * Description :  Turns a time_t into the format expected by mbedTLS.
+ *
+ * Parameters  :
+ *          1  :  time_spec = The timestamp to convert
+ *          2  :  buffer = The buffer to write the date to
+ *          3  :  buffer_size = The size of the buffer
+ *          4  :  fmt = format
+ *
+ * Returns     :   0 => The conversion worked
+ *                 1 => The conversion failed
+ *
+ *********************************************************************/
+static int generate_certificate_valid_date(time_t time_spec, char *buffer,
+                                           size_t buffer_size, const char *fmt)
+{
+   struct tm valid_date;
+   struct tm *timeptr;
+   size_t ret;
+
+   timeptr = privoxy_gmtime_r(&time_spec, &valid_date);
+   if (NULL == timeptr)
+   {
+      return 1;
+   }
+
+   ret = strftime(buffer, buffer_size, fmt, timeptr);
+   if (ret <= 0)
+   {
+      return 1;
+   }
+
+   return 0;
+
+}
+
+
+/*********************************************************************
+ *
+ * Function    :  get_certificate_valid_from_date
+ *
+ * Description :  Generates a "valid from" date in the format
+ *                expected by mbedTLS.
+ *
+ * Parameters  :
+ *          1  :  buffer = The buffer to write the date to
+ *          2  :  buffer_size = The size of the buffer
+ *          3  :  fmt = format
+ *
+ * Returns     :   0 => The generation worked
+ *                 1 => The generation failed
+ *
+ *********************************************************************/
+extern int get_certificate_valid_from_date(char *buffer, size_t buffer_size, const char *fmt)
+{
+   time_t time_spec;
+
+   time_spec = time(NULL);
+   /* 1 month in the past */
+   time_spec -= 30 * 24 * 60 * 60;
+
+   return generate_certificate_valid_date(time_spec, buffer, buffer_size, fmt);
+
+}
+
+
+/*********************************************************************
+ *
+ * Function    :  get_certificate_valid_to_date
+ *
+ * Description :  Generates a "valid to" date in the format
+ *                expected by mbedTLS.
+ *
+ * Parameters  :
+ *          1  :  buffer = The buffer to write the date to
+ *          2  :  buffer_size = The size of the buffer
+ *          3  :  fmt = format
+ *
+ * Returns     :   0 => The generation worked
+ *                 1 => The generation failed
+ *
+ *********************************************************************/
+extern int get_certificate_valid_to_date(char *buffer, size_t buffer_size, const char *fmt)
+{
+   time_t time_spec;
+
+   time_spec = time(NULL);
+   /* Three months in the future */
+   time_spec += 90 * 24 * 60 * 60;
+
+   return generate_certificate_valid_date(time_spec, buffer, buffer_size, fmt);
+
+}
+
+
+/*********************************************************************
+ *
+ * Function    :  host_is_ip_address
+ *
+ * Description :  Checks whether or not a host is specified by
+ *                IP address. Does not actually validate the
+ *                address.
+ *
+ * Parameters  :
+ *          1  :  host = The host name to check
+ *
+ * Returns     :   1 => Yes
+ *                 0 => No
+ *
+ *********************************************************************/
+extern int host_is_ip_address(const char *host)
+{
+   const char *p;
+
+   if (NULL != strstr(host, ":"))
+   {
+      /* Assume an IPv6 address. */
+      return 1;
+   }
+
+   for (p = host; *p; p++)
+   {
+      if ((*p != '.') && !privoxy_isdigit(*p))
+      {
+         /* Not a dot or digit so it can't be an IPv4 address. */
+         return 0;
+      }
+   }
+
+   /*
+    * Host only consists of dots and digits so
+    * assume that is an IPv4 address.
+    */
+   return 1;
+
+}
diff --git a/ssl_common.h b/ssl_common.h
new file mode 100644 (file)
index 0000000..86dab98
--- /dev/null
@@ -0,0 +1,78 @@
+#ifndef SSL_COMMON_H_INCLUDED
+#define SSL_COMMON_H_INCLUDED
+/*********************************************************************
+*
+* File        :  $Source: /cvsroot/ijbswa/current/ssl.h,v $
+*
+* Purpose     :  File with TLS/SSL extension. Contains methods for
+*                creating, using and closing TLS/SSL connections that do
+*                not depend on particular TLS/SSL library.
+*
+* Copyright   :  Written by and Copyright (c) 2017 Vaclav Svec. FIT CVUT.
+*
+*                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 2 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.
+*
+*                The GNU General Public License should be included with
+*                this file.  If not, you can view it at
+*                http://www.gnu.org/copyleft/gpl.html
+*                or write to the Free Software Foundation, Inc., 59
+*                Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+*
+*********************************************************************/
+
+#include "project.h"
+
+#define RSA_KEY_PUBLIC_EXPONENT          65537             /* Public exponent for RSA private key generating */
+#define RSA_KEYSIZE                      2048              /* Size of generated RSA keys */
+#define ERROR_BUF_SIZE                   1024              /* Size of buffer for error messages */
+#define INVALID_CERT_INFO_BUF_SIZE       2048              /* Size of buffer for message with information about reason of certificate invalidity. Data after the end of buffer will not be saved */
+#define KEY_FILE_TYPE                    ".pem"
+#define CERT_FILE_TYPE                   ".crt"
+
+#define CERT_PARAM_COMMON_NAME_FCODE      "CN"
+#define CERT_PARAM_ORGANIZATION_FCODE     "O"
+#define CERT_PARAM_ORG_UNIT_FCODE         "OU"
+#define CERT_PARAM_COUNTRY_FCODE          "C"
+#define CERT_PARAM_COUNTRY_CODE           "CZ"
+#define CERT_SUBJECT_PASSWORD            ""
+#define CERT_INFO_PREFIX                 ""
+
+/*
+ * Properties of cert for generating
+ */
+typedef struct {
+   char       *issuer_crt;                         /* filename of the issuer certificate       */
+   char       *subject_key;                        /* filename of the subject key file         */
+   char       *issuer_key;                         /* filename of the issuer key file          */
+   const char *subject_pwd;                        /* password for the subject key file        */
+   const char *issuer_pwd;                         /* password for the issuer key file         */
+   char       *output_file;                        /* where to store the constructed key file  */
+   const char *subject_name;                       /* subject name for certificate             */
+   char       issuer_name[ISSUER_NAME_BUF_SIZE];   /* issuer name for certificate              */
+   const char *not_before;                         /* validity period not before               */
+   const char *not_after;                          /* validity period not after                */
+   const char *serial;                             /* serial number string                     */
+   int        is_ca;                               /* is a CA certificate                      */
+   int        max_pathlen;                         /* maximum CA path length                   */
+} cert_options;
+
+extern void free_certificate_chain(struct client_state *csp);
+extern int file_exists(const char *path);
+extern char *make_certs_path(const char *conf_dir, const char *file_name,
+   const char *suffix);
+extern unsigned long get_certificate_serial(struct client_state *csp);
+extern int get_certificate_valid_from_date(char *buffer, size_t buffer_size, const char *fmt);
+extern int get_certificate_valid_to_date(char *buffer, size_t buffer_size, const char *fmt);
+extern int host_is_ip_address(const char *host);
+
+#endif /* ndef SSL_COMMON_H_INCLUDED */