OpenSSL generate_key(): Check EVP_RSA_gen()'s return value
[privoxy.git] / openssl.c
index 507c3f8..ba2fc3e 100644 (file)
--- a/openssl.c
+++ b/openssl.c
@@ -8,7 +8,7 @@
  *
  * Copyright   :  Written by and Copyright (c) 2020 Maxim Antonov <mantonov@gmail.com>
  *                Copyright (C) 2017 Vaclav Svec. FIT CVUT.
- *                Copyright (C) 2018-2020 by Fabian Keil <fk@fabiankeil.de>
+ *                Copyright (C) 2018-2022 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
 #include <openssl/bn.h>
 #include <openssl/opensslv.h>
 #include <openssl/pem.h>
-#include <openssl/md5.h>
+#include <openssl/sha.h>
 #include <openssl/x509v3.h>
+#ifdef _WIN32
+/* https://www.openssl.org/docs/faq.html
+   I’ve compiled a program under Windows and it crashes: Why?
+   tl,dr: because it needs this include:
+*/
+#include <openssl/applink.c>
+#endif /* _WIN32 */
 
 #include "config.h"
 #include "project.h"
@@ -268,12 +275,12 @@ extern int ssl_recv_data(struct ssl_attr *ssl_attr, unsigned char *buf, size_t m
  *********************************************************************/
 static int ssl_store_cert(struct client_state *csp, X509 *crt)
 {
-   long len = 0;
+   long len;
    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 *bio_mem_data = NULL;
    char *encoded_text;
    long l;
    const ASN1_INTEGER *bs;
@@ -302,7 +309,7 @@ static int ssl_store_cert(struct client_state *csp, X509 *crt)
    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));
+   last->next->file_buf = NULL;
 
    /*
     * Saving certificate file into buffer
@@ -316,15 +323,18 @@ static int ssl_store_cert(struct client_state *csp, X509 *crt)
 
    len = BIO_get_mem_data(bio, &bio_mem_data);
 
-   if (len > (sizeof(last->file_buf) - 1))
+   last->file_buf = malloc((size_t)len + 1);
+   if (last->file_buf == NULL)
    {
       log_error(LOG_LEVEL_ERROR,
-         "X509 PEM cert len %ld is larger than buffer len %lu",
-         len, sizeof(last->file_buf) - 1);
-      len = sizeof(last->file_buf) - 1;
+         "Failed to allocate %lu bytes to store the X509 PEM certificate",
+         len + 1);
+      ret = -1;
+      goto exit;
    }
 
    strncpy(last->file_buf, bio_mem_data, (size_t)len);
+   last->file_buf[len] = '\0';
    BIO_free(bio);
    bio = BIO_new(BIO_s_mem());
    if (!bio)
@@ -501,8 +511,12 @@ static int ssl_store_cert(struct client_state *csp, X509 *crt)
       case EVP_PKEY_DSA:
          ret = BIO_printf(bio, "\n%-" BC "s: %d bits", "DSA key size", EVP_PKEY_bits(pkey));
          break;
+      case EVP_PKEY_EC:
+         ret = BIO_printf(bio, "\n%-" BC "s: %d bits", "EC 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));
+         ret = BIO_printf(bio, "\n%-" BC "s: %d bits", "non-RSA/DSA/EC key size",
+            EVP_PKEY_bits(pkey));
          break;
    }
    if (ret <= 0)
@@ -692,8 +706,8 @@ exit:
  *
  * Function    :  host_to_hash
  *
- * Description :  Creates MD5 hash from host name. Host name is loaded
- *                from structure csp and saved again into it.
+ * Description :  Creates a sha256 hash from host name. The host name
+ *                is taken from the csp structure and stored into it.
  *
  * Parameters  :
  *          1  :  csp = Current client state (buffers, headers, etc...)
@@ -704,25 +718,11 @@ exit:
  *********************************************************************/
 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),
+   SHA256((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 create_hexadecimal_hash_of_host(csp);
 
-   return 0;
 }
 
 
@@ -783,17 +783,16 @@ extern int create_client_ssl_connection(struct client_state *csp)
     * certificate and key inconsistence must be locked.
     */
    privoxy_mutex_lock(&certificate_mutex);
-
    ret = generate_host_certificate(csp);
+   privoxy_mutex_unlock(&certificate_mutex);
+
    if (ret < 0)
    {
       log_error(LOG_LEVEL_ERROR,
-         "generate_host_certificate failed: %d", ret);
-      privoxy_mutex_unlock(&certificate_mutex);
+         "generate_host_certificate() failed: %d", ret);
       ret = -1;
       goto exit;
    }
-   privoxy_mutex_unlock(&certificate_mutex);
 
    if (!(ssl_attr->openssl_attr.ctx = SSL_CTX_new(SSLv23_server_method())))
    {
@@ -1148,6 +1147,11 @@ extern int create_server_ssl_connection(struct client_state *csp)
       goto exit;
    }
 
+   /*
+    * XXX: Do we really have to do this always?
+    *      Probably it's sufficient to do if the verification fails
+    *      in which case we're sending the certificates to the client.
+    */
    chain = SSL_get_peer_cert_chain(ssl);
    if (chain)
    {
@@ -1477,8 +1481,10 @@ static int generate_key(struct client_state *csp, char **key_buf)
 {
    int ret = 0;
    char* key_file_path;
+#if (OPENSSL_VERSION_NUMBER < 0x30000000L)
    BIGNUM *exp;
    RSA *rsa;
+#endif
    EVP_PKEY *key;
 
    key_file_path = make_certs_path(csp->config->certificate_directory,
@@ -1497,6 +1503,7 @@ static int generate_key(struct client_state *csp, char **key_buf)
       return 0;
    }
 
+#if (OPENSSL_VERSION_NUMBER < 0x30000000L)
    exp = BN_new();
    rsa = RSA_new();
    key = EVP_PKEY_new();
@@ -1529,6 +1536,15 @@ static int generate_key(struct client_state *csp, char **key_buf)
       ret = -1;
       goto exit;
    }
+#else
+   key = EVP_RSA_gen(RSA_KEYSIZE);
+   if (key == NULL)
+   {
+      log_error(LOG_LEVEL_ERROR, "EVP_RSA_gen() failed");
+      ret = -1;
+      goto exit;
+   }
+#endif
 
    /*
     * Exporting private key into file
@@ -1545,6 +1561,7 @@ exit:
    /*
     * Freeing used variables
     */
+#if (OPENSSL_VERSION_NUMBER < 0x30000000L)
    if (exp)
    {
       BN_free(exp);
@@ -1553,6 +1570,7 @@ exit:
    {
       RSA_free(rsa);
    }
+#endif
    if (key)
    {
       EVP_PKEY_free(key);
@@ -1747,6 +1765,8 @@ static int generate_host_certificate(struct client_state *csp)
    cert_options cert_opt;
    char cert_valid_from[VALID_DATETIME_BUFLEN];
    char cert_valid_to[VALID_DATETIME_BUFLEN];
+   const char *common_name;
+   enum { CERT_PARAM_COMMON_NAME_MAX = 64 };
 
    /* Paths to keys and certificates needed to create certificate */
    cert_opt.issuer_key  = NULL;
@@ -1857,13 +1877,20 @@ static int generate_host_certificate(struct client_state *csp)
    subject_name = X509_NAME_new();
    if (!subject_name)
    {
-      log_ssl_errors(LOG_LEVEL_ERROR, "RSA key memory allocation failure");
+      log_ssl_errors(LOG_LEVEL_ERROR, "X509 memory allocation failure");
       ret = -1;
       goto exit;
    }
 
+   /*
+    * Make sure OpenSSL doesn't reject the common name due to its length.
+    * The clients should only care about the Subject Alternative Name anyway
+    * and we always use the real host name for that.
+    */
+   common_name = (strlen(csp->http->host) > CERT_PARAM_COMMON_NAME_MAX) ?
+      CGI_SITE_2_HOST : csp->http->host;
    if (!X509_NAME_add_entry_by_txt(subject_name, CERT_PARAM_COMMON_NAME_FCODE,
-         MBSTRING_ASC, (void *)csp->http->host, -1, -1, 0))
+         MBSTRING_ASC, (void *)common_name, -1, -1, 0))
    {
       log_ssl_errors(LOG_LEVEL_ERROR,
          "X509 subject name (code: %s, val: %s) error",
@@ -1872,7 +1899,7 @@ static int generate_host_certificate(struct client_state *csp)
       goto exit;
    }
    if (!X509_NAME_add_entry_by_txt(subject_name, CERT_PARAM_ORGANIZATION_FCODE,
-         MBSTRING_ASC, (void *)csp->http->host, -1, -1, 0))
+         MBSTRING_ASC, (void *)common_name, -1, -1, 0))
    {
       log_ssl_errors(LOG_LEVEL_ERROR,
          "X509 subject name (code: %s, val: %s) error",
@@ -1881,7 +1908,7 @@ static int generate_host_certificate(struct client_state *csp)
       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))
+         MBSTRING_ASC, (void *)common_name, -1, -1, 0))
    {
       log_ssl_errors(LOG_LEVEL_ERROR,
          "X509 subject name (code: %s, val: %s) error",
@@ -1894,7 +1921,7 @@ static int generate_host_certificate(struct client_state *csp)
    {
       log_ssl_errors(LOG_LEVEL_ERROR,
          "X509 subject name (code: %s, val: %s) error",
-         CERT_PARAM_COUNTRY_FCODE, csp->http->host);
+         CERT_PARAM_COUNTRY_FCODE, CERT_PARAM_COUNTRY_CODE);
       ret = -1;
       goto exit;
    }
@@ -1965,7 +1992,7 @@ static int generate_host_certificate(struct client_state *csp)
       goto exit;
    }
 
-   issuer_name = X509_get_issuer_name(issuer_cert);
+   issuer_name = X509_get_subject_name(issuer_cert);
 
    /*
     * Loading keys from file or from buffer