1 /*********************************************************************
3 * File : $Source: /cvsroot/ijbswa/current/openssl.c,v $
5 * Purpose : File with TLS/SSL extension. Contains methods for
6 * creating, using and closing TLS/SSL connections.
8 * Copyright : Written by and Copyright (c) 2020 Maxim Antonov <mantonov@gmail.com>
9 * Copyright (C) 2017 Vaclav Svec. FIT CVUT.
10 * Copyright (C) 2018-2020 by Fabian Keil <fk@fabiankeil.de>
12 * This program is free software; you can redistribute it
13 * and/or modify it under the terms of the GNU General
14 * Public License as published by the Free Software
15 * Foundation; either version 2 of the License, or (at
16 * your option) any later version.
18 * This program is distributed in the hope that it will
19 * be useful, but WITHOUT ANY WARRANTY; without even the
20 * implied warranty of MERCHANTABILITY or FITNESS FOR A
21 * PARTICULAR PURPOSE. See the GNU General Public
22 * License for more details.
24 * The GNU General Public License should be included with
25 * this file. If not, you can view it at
26 * http://www.gnu.org/copyleft/gpl.html
27 * or write to the Free Software Foundation, Inc., 59
28 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
30 *********************************************************************/
35 #include <openssl/bn.h>
36 #include <openssl/opensslv.h>
37 #include <openssl/pem.h>
38 #include <openssl/md5.h>
39 #include <openssl/x509v3.h>
48 #include "ssl_common.h"
51 * Macros for openssl.c
53 #define CERTIFICATE_BASIC_CONSTRAINTS "CA:FALSE"
54 #define CERTIFICATE_SUBJECT_KEY "hash"
55 #define CERTIFICATE_AUTHORITY_KEY "keyid:always"
56 #define CERTIFICATE_ALT_NAME_PREFIX "DNS:"
57 #define CERTIFICATE_VERSION 2
58 #define VALID_DATETIME_FMT "%y%m%d%H%M%SZ"
59 #define VALID_DATETIME_BUFLEN 16
61 static int generate_webpage_certificate(struct client_state *csp);
62 static void free_client_ssl_structures(struct client_state *csp);
63 static void free_server_ssl_structures(struct client_state *csp);
64 static int ssl_store_cert(struct client_state *csp, X509* crt);
65 static void log_ssl_errors(int debuglevel, const char* fmt, ...) __attribute__((format(printf, 2, 3)));
67 static int ssl_inited = 0;
69 #if OPENSSL_VERSION_NUMBER < 0x10100000L
70 #define X509_set1_notBefore X509_set_notBefore
71 #define X509_set1_notAfter X509_set_notAfter
72 #define X509_get0_serialNumber X509_get_serialNumber
73 #define X509_get0_notBefore X509_get_notBefore
74 #define X509_get0_notAfter X509_get_notAfter
77 /*********************************************************************
79 * Function : openssl_init
81 * Description : Initializes OpenSSL library once
87 *********************************************************************/
88 static void openssl_init(void)
92 privoxy_mutex_lock(&ssl_init_mutex);
95 #if OPENSSL_VERSION_NUMBER < 0x10100000L
98 OPENSSL_init_ssl(0, NULL);
100 SSL_load_error_strings();
101 OpenSSL_add_ssl_algorithms();
104 privoxy_mutex_unlock(&ssl_init_mutex);
109 /*********************************************************************
111 * Function : is_ssl_pending
113 * Description : Tests if there are some waiting data on ssl connection.
114 * Only considers data that has actually been received
115 * locally and ignores data that is still on the fly
116 * or has not yet been sent by the remote end.
119 * 1 : ssl_attr = SSL context to test
121 * Returns : 0 => No data are pending
122 * >0 => Pending data length
124 *********************************************************************/
125 extern size_t is_ssl_pending(struct ssl_attr *ssl_attr)
127 BIO *bio = ssl_attr->openssl_attr.bio;
133 return (size_t)BIO_pending(bio);
137 /*********************************************************************
139 * Function : ssl_send_data
141 * Description : Sends the content of buf (for n bytes) to given SSL
142 * connection context.
145 * 1 : ssl_attr = SSL context to send data to
146 * 2 : buf = Pointer to data to be sent
147 * 3 : len = Length of data to be sent to the SSL context
149 * Returns : Length of sent data or negative value on error.
151 *********************************************************************/
152 extern int ssl_send_data(struct ssl_attr *ssl_attr, const unsigned char *buf, size_t len)
154 BIO *bio = ssl_attr->openssl_attr.bio;
157 int pos = 0; /* Position of unsent part in buffer */
165 if (BIO_get_ssl(bio, &ssl) == 1)
167 fd = SSL_get_fd(ssl);
172 int send_len = (int)len - pos;
174 log_error(LOG_LEVEL_WRITING, "TLS on socket %d: %N",
175 fd, send_len, buf+pos);
178 * Sending one part of the buffer
180 while ((ret = BIO_write(bio,
181 (const unsigned char *)(buf + pos),
184 if (!BIO_should_retry(bio))
186 log_ssl_errors(LOG_LEVEL_ERROR,
187 "Sending data on socket %d over TLS/SSL failed", fd);
191 /* Adding count of sent bytes to position in buffer */
199 /*********************************************************************
201 * Function : ssl_recv_data
203 * Description : Receives data from given SSL context and puts
207 * 1 : ssl_attr = SSL context to receive data from
208 * 2 : buf = Pointer to buffer where data will be written
209 * 3 : max_length = Maximum number of bytes to read
211 * Returns : Number of bytes read, 0 for EOF, or -1
214 *********************************************************************/
215 extern int ssl_recv_data(struct ssl_attr *ssl_attr, unsigned char *buf, size_t max_length)
217 BIO *bio = ssl_attr->openssl_attr.bio;
222 memset(buf, 0, max_length);
225 * Receiving data from SSL context into buffer
229 ret = BIO_read(bio, buf, (int)max_length);
230 } while (ret <= 0 && BIO_should_retry(bio));
234 log_ssl_errors(LOG_LEVEL_ERROR,
235 "Receiving data on socket %d over TLS/SSL failed", fd);
240 if (BIO_get_ssl(bio, &ssl) == 1)
242 fd = SSL_get_fd(ssl);
245 log_error(LOG_LEVEL_RECEIVED, "TLS from socket %d: %N",
252 /*********************************************************************
254 * Function : ssl_store_cert
256 * Description : This function is called once for each certificate in the
257 * server's certificate trusted chain and prepares
258 * information about the certificate. The information can
259 * be used to inform the user about invalid certificates.
262 * 1 : csp = Current client state (buffers, headers, etc...)
263 * 2 : crt = certificate from trusted chain
265 * Returns : 0 on success and negative value on error
267 *********************************************************************/
268 static int ssl_store_cert(struct client_state *csp, X509* crt)
271 struct certs_chain *last = &(csp->server_certs_chain);
273 BIO *bio = BIO_new(BIO_s_mem());
274 EVP_PKEY *pkey = NULL;
275 char *bio_mem_data = 0;
278 const ASN1_INTEGER *bs;
279 #if OPENSSL_VERSION_NUMBER > 0x10100000L
280 const X509_ALGOR *tsig_alg;
286 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_new_mem_buf() failed");
291 * Searching for last item in certificates linked list
293 while (last->next != NULL)
299 * Preparing next item in linked list for next certificate
301 last->next = malloc_or_die(sizeof(struct certs_chain));
302 last->next->next = NULL;
303 memset(last->next->info_buf, 0, sizeof(last->next->info_buf));
304 memset(last->next->file_buf, 0, sizeof(last->next->file_buf));
307 * Saving certificate file into buffer
309 if (!PEM_write_bio_X509(bio, crt))
311 log_ssl_errors(LOG_LEVEL_ERROR, "PEM_write_X509() failed");
316 len = BIO_get_mem_data(bio, &bio_mem_data);
318 if (len > (sizeof(last->file_buf) - 1))
320 log_error(LOG_LEVEL_ERROR,
321 "X509 PEM cert len %ld is larger than buffer len %lu",
322 len, sizeof(last->file_buf) - 1);
323 len = sizeof(last->file_buf) - 1;
326 strncpy(last->file_buf, bio_mem_data, (size_t)len);
328 bio = BIO_new(BIO_s_mem());
331 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_new_mem_buf() failed");
337 * Saving certificate information into buffer
339 l = X509_get_version(crt);
340 if (l >= 0 && l <= 2)
342 if (BIO_printf(bio, "cert. version : %ld\n", l + 1) <= 0)
344 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for version failed");
351 if (BIO_printf(bio, "cert. version : Unknown (%ld)\n", l) <= 0)
353 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for version failed");
359 if (BIO_puts(bio, "serial number : ") <= 0)
361 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_puts() for serial failed");
365 bs = X509_get0_serialNumber(crt);
366 if (bs->length <= (int)sizeof(long))
369 l = ASN1_INTEGER_get(bs);
380 if (bs->type == V_ASN1_NEG_INTEGER)
382 ul = 0 - (unsigned long)l;
387 ul = (unsigned long)l;
390 if (BIO_printf(bio, " %s%lu (%s0x%lx)\n", neg, ul, neg, ul) <= 0)
392 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for serial failed");
399 if (bs->type == V_ASN1_NEG_INTEGER)
401 if (BIO_puts(bio, " (Negative)") < 0)
403 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_puts() for serial failed");
408 for (int i = 0; i < bs->length; i++)
410 if (BIO_printf(bio, "%02x%c", bs->data[i],
411 ((i + 1 == bs->length) ? '\n' : ':')) <= 0)
413 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for serial failed");
420 if (BIO_puts(bio, "issuer name : ") <= 0)
422 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_puts() for issuer failed");
426 if (X509_NAME_print_ex(bio, X509_get_issuer_name(crt), 0, 0) < 0)
428 log_ssl_errors(LOG_LEVEL_ERROR, "X509_NAME_print_ex() for issuer failed");
433 if (BIO_puts(bio, "\nsubject name : ") <= 0)
435 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_puts() for subject failed");
439 if (X509_NAME_print_ex(bio, X509_get_subject_name(crt), 0, 0) < 0) {
440 log_ssl_errors(LOG_LEVEL_ERROR, "X509_NAME_print_ex() for subject failed");
445 if (BIO_puts(bio, "\nissued on : ") <= 0)
447 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_puts() for issued on failed");
451 if (!ASN1_TIME_print(bio, X509_get0_notBefore(crt)))
453 log_ssl_errors(LOG_LEVEL_ERROR, "ASN1_TIME_print() for issued on failed");
458 if (BIO_puts(bio, "\nexpires on : ") <= 0)
460 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_puts() for expires on failed");
464 if (!ASN1_TIME_print(bio, X509_get0_notAfter(crt)))
466 log_ssl_errors(LOG_LEVEL_ERROR, "ASN1_TIME_print() for expires on failed");
471 #if OPENSSL_VERSION_NUMBER > 0x10100000L
472 if (BIO_puts(bio, "\nsigned using : ") <= 0)
474 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_puts() for signed using failed");
478 tsig_alg = X509_get0_tbs_sigalg(crt);
479 if (!i2a_ASN1_OBJECT(bio, tsig_alg->algorithm))
481 log_ssl_errors(LOG_LEVEL_ERROR, "i2a_ASN1_OBJECT() for signed using failed");
486 pkey = X509_get_pubkey(crt);
489 log_ssl_errors(LOG_LEVEL_ERROR, "X509_get_pubkey() failed");
494 switch (EVP_PKEY_base_id(pkey))
497 ret = BIO_printf(bio, "\n%-" BC "s: %d bits", "RSA key size", EVP_PKEY_bits(pkey));
500 ret = BIO_printf(bio, "\n%-" BC "s: %d bits", "DSA key size", EVP_PKEY_bits(pkey));
503 ret = BIO_printf(bio, "\n%-" BC "s: %d bits", "non-RSA/DSA key size", EVP_PKEY_bits(pkey));
508 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for key size failed");
513 loc = X509_get_ext_by_NID(crt, NID_basic_constraints, -1);
516 X509_EXTENSION *ex = X509_get_ext(crt, loc);
517 if (BIO_puts(bio, "\nbasic constraints : ") <= 0)
519 log_ssl_errors(LOG_LEVEL_ERROR,
520 "BIO_printf() for basic constraints failed");
524 if (!X509V3_EXT_print(bio, ex, 0, 0))
526 if (!ASN1_STRING_print_ex(bio, X509_EXTENSION_get_data(ex), ASN1_STRFLGS_RFC2253))
528 log_ssl_errors(LOG_LEVEL_ERROR,
529 "ASN1_STRING_print_ex() for basic constraints failed");
536 loc = X509_get_ext_by_NID(crt, NID_subject_alt_name, -1);
539 X509_EXTENSION *ex = X509_get_ext(crt, loc);
540 if (BIO_puts(bio, "\nsubject alt name : ") <= 0)
542 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for alt name failed");
546 if (!X509V3_EXT_print(bio, ex, 0, 0))
548 if (!ASN1_STRING_print_ex(bio, X509_EXTENSION_get_data(ex),
549 ASN1_STRFLGS_RFC2253))
551 log_ssl_errors(LOG_LEVEL_ERROR,
552 "ASN1_STRING_print_ex() for alt name failed");
559 loc = X509_get_ext_by_NID(crt, NID_netscape_cert_type, -1);
562 X509_EXTENSION *ex = X509_get_ext(crt, loc);
563 if (BIO_puts(bio, "\ncert. type : ") <= 0)
565 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for cert type failed");
569 if (!X509V3_EXT_print(bio, ex, 0, 0))
571 if (!ASN1_STRING_print_ex(bio, X509_EXTENSION_get_data(ex),
572 ASN1_STRFLGS_RFC2253))
574 log_ssl_errors(LOG_LEVEL_ERROR,
575 "ASN1_STRING_print_ex() for cert type failed");
582 loc = X509_get_ext_by_NID(crt, NID_key_usage, -1);
585 X509_EXTENSION *ex = X509_get_ext(crt, loc);
586 if (BIO_puts(bio, "\nkey usage : ") <= 0)
588 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for key usage failed");
592 if (!X509V3_EXT_print(bio, ex, 0, 0))
594 if (!ASN1_STRING_print_ex(bio, X509_EXTENSION_get_data(ex),
595 ASN1_STRFLGS_RFC2253))
597 log_ssl_errors(LOG_LEVEL_ERROR,
598 "ASN1_STRING_print_ex() for key usage failed");
605 loc = X509_get_ext_by_NID(crt, NID_ext_key_usage, -1);
607 X509_EXTENSION *ex = X509_get_ext(crt, loc);
608 if (BIO_puts(bio, "\next key usage : ") <= 0)
610 log_ssl_errors(LOG_LEVEL_ERROR,
611 "BIO_printf() for ext key usage failed");
615 if (!X509V3_EXT_print(bio, ex, 0, 0))
617 if (!ASN1_STRING_print_ex(bio, X509_EXTENSION_get_data(ex),
618 ASN1_STRFLGS_RFC2253))
620 log_ssl_errors(LOG_LEVEL_ERROR,
621 "ASN1_STRING_print_ex() for ext key usage failed");
628 loc = X509_get_ext_by_NID(crt, NID_certificate_policies, -1);
631 X509_EXTENSION *ex = X509_get_ext(crt, loc);
632 if (BIO_puts(bio, "\ncertificate policies : ") <= 0)
634 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for certificate policies failed");
638 if (!X509V3_EXT_print(bio, ex, 0, 0))
640 if (!ASN1_STRING_print_ex(bio, X509_EXTENSION_get_data(ex),
641 ASN1_STRFLGS_RFC2253))
643 log_ssl_errors(LOG_LEVEL_ERROR,
644 "ASN1_STRING_print_ex() for certificate policies failed");
651 /* make valgrind happy */
652 static const char zero = 0;
653 BIO_write(bio, &zero, 1);
655 len = BIO_get_mem_data(bio, &bio_mem_data);
656 encoded_text = html_encode(bio_mem_data);
657 if (encoded_text == NULL)
659 log_error(LOG_LEVEL_ERROR,
660 "Failed to HTML-encode the certificate information");
665 strlcpy(last->info_buf, encoded_text, sizeof(last->info_buf));
682 /*********************************************************************
684 * Function : host_to_hash
686 * Description : Creates MD5 hash from host name. Host name is loaded
687 * from structure csp and saved again into it.
690 * 1 : csp = Current client state (buffers, headers, etc...)
692 * Returns : 1 => Error while creating hash
693 * 0 => Hash created successfully
695 *********************************************************************/
696 static int host_to_hash(struct client_state *csp)
700 memset(csp->http->hash_of_host, 0, sizeof(csp->http->hash_of_host));
701 MD5((unsigned char *)csp->http->host, strlen(csp->http->host),
702 csp->http->hash_of_host);
704 /* Converting hash into string with hex */
708 if ((ret = sprintf((char *)csp->http->hash_of_host_hex + 2 * i, "%02x",
709 csp->http->hash_of_host[i])) < 0)
711 log_error(LOG_LEVEL_ERROR, "Sprintf return value: %d", ret);
720 /*********************************************************************
722 * Function : create_client_ssl_connection
724 * Description : Creates TLS/SSL secured connection with client
727 * 1 : csp = Current client state (buffers, headers, etc...)
729 * Returns : 0 on success, negative value if connection wasn't created
732 *********************************************************************/
733 extern int create_client_ssl_connection(struct client_state *csp)
735 struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
736 /* Paths to certificates file and key file */
737 char *key_file = NULL;
738 char *ca_file = NULL;
739 char *cert_file = NULL;
744 * Initializing OpenSSL structures for TLS/SSL connection
749 * Preparing hash of host for creating certificates
751 ret = host_to_hash(csp);
754 log_error(LOG_LEVEL_ERROR, "Generating hash of host failed: %d", ret);
760 * Preparing paths to certificates files and key file
762 ca_file = csp->config->ca_cert_file;
763 cert_file = make_certs_path(csp->config->certificate_directory,
764 (const char *)csp->http->hash_of_host_hex, CERT_FILE_TYPE);
765 key_file = make_certs_path(csp->config->certificate_directory,
766 (const char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
768 if (cert_file == NULL || key_file == NULL)
775 * Generating certificate for requested host. Mutex to prevent
776 * certificate and key inconsistence must be locked.
778 privoxy_mutex_lock(&certificate_mutex);
780 ret = generate_webpage_certificate(csp);
783 log_error(LOG_LEVEL_ERROR,
784 "Generate_webpage_certificate failed: %d", ret);
785 privoxy_mutex_unlock(&certificate_mutex);
789 privoxy_mutex_unlock(&certificate_mutex);
791 if (!(ssl_attr->openssl_attr.ctx = SSL_CTX_new(SSLv23_server_method())))
793 log_ssl_errors(LOG_LEVEL_ERROR, "Unable to create SSL context");
798 /* Set the key and cert */
799 if (SSL_CTX_use_certificate_file(ssl_attr->openssl_attr.ctx,
800 cert_file, SSL_FILETYPE_PEM) != 1)
802 log_ssl_errors(LOG_LEVEL_ERROR,
803 "Loading webpage certificate %s failed", cert_file);
808 if (SSL_CTX_use_PrivateKey_file(ssl_attr->openssl_attr.ctx,
809 key_file, SSL_FILETYPE_PEM) != 1)
811 log_ssl_errors(LOG_LEVEL_ERROR,
812 "Loading webpage certificate private key %s failed", key_file);
817 SSL_CTX_set_options(ssl_attr->openssl_attr.ctx, SSL_OP_NO_SSLv3);
819 if (!(ssl_attr->openssl_attr.bio = BIO_new_ssl(ssl_attr->openssl_attr.ctx, 0)))
821 log_ssl_errors(LOG_LEVEL_ERROR, "Unable to create BIO structure");
826 if (BIO_get_ssl(ssl_attr->openssl_attr.bio, &ssl) != 1)
828 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_get_ssl failed");
833 if (!SSL_set_fd(ssl, csp->cfd))
835 log_ssl_errors(LOG_LEVEL_ERROR, "SSL_set_fd failed");
840 if (csp->config->cipher_list != NULL)
842 if (!SSL_set_cipher_list(ssl, csp->config->cipher_list))
844 log_ssl_errors(LOG_LEVEL_ERROR,
845 "Setting the cipher list '%s' for the client connection failed",
846 csp->config->cipher_list);
853 * Handshake with client
855 log_error(LOG_LEVEL_CONNECT,
856 "Performing the TLS/SSL handshake with client. Hash of host: %s",
857 csp->http->hash_of_host_hex);
858 if (BIO_do_handshake(ssl_attr->openssl_attr.bio) != 1)
860 log_ssl_errors(LOG_LEVEL_ERROR,
861 "The TLS/SSL handshake with the client failed");
866 log_error(LOG_LEVEL_CONNECT, "Client successfully connected over TLS/SSL");
867 csp->ssl_with_client_is_opened = 1;
872 * Freeing allocated paths to files
877 /* Freeing structures if connection wasn't created successfully */
880 free_client_ssl_structures(csp);
886 /*********************************************************************
888 * Function : close_client_ssl_connection
890 * Description : Closes TLS/SSL connection with client. This function
891 * checks if this connection is already created.
894 * 1 : csp = Current client state (buffers, headers, etc...)
898 *********************************************************************/
899 extern void close_client_ssl_connection(struct client_state *csp)
901 struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
904 if (csp->ssl_with_client_is_opened == 0)
910 * Notifying the peer that the connection is being closed.
912 BIO_ssl_shutdown(ssl_attr->openssl_attr.bio);
913 if (BIO_get_ssl(ssl_attr->openssl_attr.bio, &ssl) != 1)
915 log_ssl_errors(LOG_LEVEL_ERROR,
916 "BIO_get_ssl() failed in close_client_ssl_connection()");
921 * Pretend we received a shutdown alert so
922 * the BIO_free_all() call later on returns
925 SSL_set_shutdown(ssl, SSL_RECEIVED_SHUTDOWN);
927 free_client_ssl_structures(csp);
928 csp->ssl_with_client_is_opened = 0;
932 /*********************************************************************
934 * Function : free_client_ssl_structures
936 * Description : Frees structures used for SSL communication with
940 * 1 : csp = Current client state (buffers, headers, etc...)
944 *********************************************************************/
945 static void free_client_ssl_structures(struct client_state *csp)
947 struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
949 if (ssl_attr->openssl_attr.bio)
951 BIO_free_all(ssl_attr->openssl_attr.bio);
953 if (ssl_attr->openssl_attr.ctx)
955 SSL_CTX_free(ssl_attr->openssl_attr.ctx);
960 /*********************************************************************
962 * Function : close_server_ssl_connection
964 * Description : Closes TLS/SSL connection with server. This function
965 * checks if this connection is already opened.
968 * 1 : csp = Current client state (buffers, headers, etc...)
972 *********************************************************************/
973 extern void close_server_ssl_connection(struct client_state *csp)
975 struct ssl_attr *ssl_attr = &csp->ssl_server_attr;
978 if (csp->ssl_with_server_is_opened == 0)
984 * Notifying the peer that the connection is being closed.
986 BIO_ssl_shutdown(ssl_attr->openssl_attr.bio);
987 if (BIO_get_ssl(ssl_attr->openssl_attr.bio, &ssl) != 1)
989 log_ssl_errors(LOG_LEVEL_ERROR,
990 "BIO_get_ssl() failed in close_server_ssl_connection()");
995 * Pretend we received a shutdown alert so
996 * the BIO_free_all() call later on returns
999 SSL_set_shutdown(ssl, SSL_RECEIVED_SHUTDOWN);
1001 free_server_ssl_structures(csp);
1002 csp->ssl_with_server_is_opened = 0;
1006 /*********************************************************************
1008 * Function : create_server_ssl_connection
1010 * Description : Creates TLS/SSL secured connection with server.
1013 * 1 : csp = Current client state (buffers, headers, etc...)
1015 * Returns : 0 on success, negative value if connection wasn't created
1018 *********************************************************************/
1019 extern int create_server_ssl_connection(struct client_state *csp)
1021 openssl_connection_attr *ssl_attrs = &csp->ssl_server_attr.openssl_attr;
1023 char *trusted_cas_file = NULL;
1024 STACK_OF(X509) *chain;
1027 csp->server_cert_verification_result = SSL_CERT_NOT_VERIFIED;
1028 csp->server_certs_chain.next = NULL;
1030 /* Setting path to file with trusted CAs */
1031 trusted_cas_file = csp->config->trusted_cas_file;
1033 ssl_attrs->ctx = SSL_CTX_new(SSLv23_method());
1034 if (!ssl_attrs->ctx)
1036 log_ssl_errors(LOG_LEVEL_ERROR, "SSL context creation failed");
1042 * Loading file with trusted CAs
1044 if (!SSL_CTX_load_verify_locations(ssl_attrs->ctx, trusted_cas_file, NULL))
1046 log_ssl_errors(LOG_LEVEL_ERROR, "Loading trusted CAs file %s failed",
1052 SSL_CTX_set_verify(ssl_attrs->ctx, SSL_VERIFY_NONE, NULL);
1053 SSL_CTX_set_options(ssl_attrs->ctx, SSL_OP_NO_SSLv3);
1055 if (!(ssl_attrs->bio = BIO_new_ssl(ssl_attrs->ctx, 1)))
1057 log_ssl_errors(LOG_LEVEL_ERROR, "Unable to create BIO structure");
1062 if (BIO_get_ssl(ssl_attrs->bio, &ssl) != 1)
1064 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_get_ssl failed");
1069 if (!SSL_set_fd(ssl, csp->server_connection.sfd))
1071 log_ssl_errors(LOG_LEVEL_ERROR, "SSL_set_fd failed");
1076 if (csp->config->cipher_list != NULL)
1078 if (!SSL_set_cipher_list(ssl, csp->config->cipher_list))
1080 log_ssl_errors(LOG_LEVEL_ERROR,
1081 "Setting the cipher list '%s' for the server connection failed",
1082 csp->config->cipher_list);
1089 * Set the hostname to check against the received server certificate
1091 #if OPENSSL_VERSION_NUMBER > 0x10100000L
1092 if (!SSL_set1_host(ssl, csp->http->host))
1094 log_ssl_errors(LOG_LEVEL_ERROR, "SSL_set1_host failed");
1099 if (host_is_ip_address(csp->http->host))
1101 if (X509_VERIFY_PARAM_set1_ip_asc(ssl->param, csp->http->host) != 1)
1103 log_ssl_errors(LOG_LEVEL_ERROR,
1104 "X509_VERIFY_PARAM_set1_ip_asc() failed");
1111 if (X509_VERIFY_PARAM_set1_host(ssl->param, csp->http->host, 0) != 1)
1113 log_ssl_errors(LOG_LEVEL_ERROR,
1114 "X509_VERIFY_PARAM_set1_host() failed");
1121 if (!SSL_set_tlsext_host_name(ssl, csp->http->host))
1123 log_ssl_errors(LOG_LEVEL_ERROR, "SSL_set_tlsext_host_name failed");
1129 * Handshake with server
1131 log_error(LOG_LEVEL_CONNECT,
1132 "Performing the TLS/SSL handshake with the server");
1134 if (BIO_do_handshake(ssl_attrs->bio) != 1)
1136 log_ssl_errors(LOG_LEVEL_ERROR,
1137 "The TLS/SSL handshake with the server failed");
1142 chain = SSL_get_peer_cert_chain(ssl);
1145 for (int i = 0; i < sk_X509_num(chain); i++)
1147 if (ssl_store_cert(csp, sk_X509_value(chain, i)) != 0)
1149 log_error(LOG_LEVEL_ERROR, "ssl_store_cert failed");
1156 if (!csp->dont_verify_certificate)
1158 long verify_result = SSL_get_verify_result(ssl);
1159 if (verify_result == X509_V_OK)
1162 csp->server_cert_verification_result = SSL_CERT_VALID;
1166 csp->server_cert_verification_result = verify_result;
1167 log_error(LOG_LEVEL_ERROR,
1168 "X509 certificate verification for %s failed: %s",
1169 csp->http->hostport, X509_verify_cert_error_string(verify_result));
1175 log_error(LOG_LEVEL_CONNECT, "Server successfully connected over TLS/SSL");
1178 * Server certificate chain is valid, so we can clean
1179 * chain, because we will not send it to client.
1181 free_certificate_chain(csp);
1183 csp->ssl_with_server_is_opened = 1;
1185 /* Freeing structures if connection wasn't created successfully */
1188 free_server_ssl_structures(csp);
1195 /*********************************************************************
1197 * Function : free_server_ssl_structures
1199 * Description : Frees structures used for SSL communication with server
1202 * 1 : csp = Current client state (buffers, headers, etc...)
1206 *********************************************************************/
1207 static void free_server_ssl_structures(struct client_state *csp)
1209 struct ssl_attr *ssl_attr = &csp->ssl_server_attr;
1211 if (ssl_attr->openssl_attr.bio)
1213 BIO_free_all(ssl_attr->openssl_attr.bio);
1215 if (ssl_attr->openssl_attr.ctx)
1217 SSL_CTX_free(ssl_attr->openssl_attr.ctx);
1222 /*********************************************************************
1224 * Function : log_ssl_errors
1226 * Description : Log SSL errors
1229 * 1 : debuglevel = Debug level
1230 * 2 : desc = Error description
1234 *********************************************************************/
1235 static void log_ssl_errors(int debuglevel, const char* fmt, ...)
1237 unsigned long err_code;
1238 char prefix[ERROR_BUF_SIZE];
1240 va_start(args, fmt);
1241 vsnprintf(prefix, sizeof(prefix), fmt, args);
1244 while ((err_code = ERR_get_error()))
1246 char err_buf[ERROR_BUF_SIZE];
1248 ERR_error_string_n(err_code, err_buf, sizeof(err_buf));
1249 log_error(debuglevel, "%s: %s", prefix, err_buf);
1253 * In case if called by mistake and there were
1254 * no TLS/SSL errors let's report it to the log.
1258 log_error(debuglevel, "%s: no TLS/SSL errors detected", prefix);
1263 /*********************************************************************
1265 * Function : ssl_base64_encode
1267 * Description : Encode a buffer into base64 format.
1270 * 1 : dst = Destination buffer
1271 * 2 : dlen = Destination buffer length
1272 * 3 : olen = Number of bytes written
1273 * 4 : src = Source buffer
1274 * 5 : slen = Amount of data to be encoded
1276 * Returns : 0 on success, error code othervise
1278 *********************************************************************/
1279 extern int ssl_base64_encode(unsigned char *dst, size_t dlen, size_t *olen,
1280 const unsigned char *src, size_t slen)
1282 *olen = 4 * ((slen/3) + ((slen%3) ? 1 : 0)) + 1;
1287 *olen = (size_t)EVP_EncodeBlock(dst, src, (int)slen) + 1;
1292 /*********************************************************************
1294 * Function : close_file_stream
1296 * Description : Close file stream, report error on close error
1299 * 1 : f = file stream to close
1300 * 2 : path = path for error report
1304 *********************************************************************/
1305 static void close_file_stream(FILE *f, const char *path)
1309 log_error(LOG_LEVEL_ERROR,
1310 "Error closing file %s: %s", path, strerror(errno));
1315 /*********************************************************************
1317 * Function : write_certificate
1319 * Description : Writes certificate into file.
1322 * 1 : crt = certificate to write into file
1323 * 2 : output_file = path to save certificate file
1326 * Returns : 1 on success success or negative value
1328 *********************************************************************/
1329 static int write_certificate(X509 *crt, const char *output_file)
1335 * Saving certificate into file
1337 if ((f = fopen(output_file, "w")) == NULL)
1339 log_error(LOG_LEVEL_ERROR, "Opening file %s to save certificate failed",
1344 ret = PEM_write_X509(f, crt);
1347 log_ssl_errors(LOG_LEVEL_ERROR,
1348 "Writing certificate into file %s failed", output_file);
1352 close_file_stream(f, output_file);
1357 /*********************************************************************
1359 * Function : write_private_key
1361 * Description : Writes private key into file and copies saved
1362 * content into given pointer to string. If function
1363 * returns 0 for success, this copy must be freed by
1367 * 1 : key = key to write into file
1368 * 2 : ret_buf = pointer to string with created key file content
1369 * 3 : key_file_path = path where to save key file
1371 * Returns : Length of written private key on success or negative value
1374 *********************************************************************/
1375 static int write_private_key(EVP_PKEY *key, char **ret_buf,
1376 const char *key_file_path)
1378 size_t len = 0; /* Length of created key */
1379 FILE *f = NULL; /* File to save certificate */
1381 BIO *bio_mem = BIO_new(BIO_s_mem());
1382 char *bio_mem_data = 0;
1384 if (bio_mem == NULL)
1386 log_ssl_errors(LOG_LEVEL_ERROR, "write_private_key memory allocation failure");
1391 * Writing private key into PEM string
1393 if (!PEM_write_bio_PrivateKey(bio_mem, key, NULL, NULL, 0, NULL, NULL))
1395 log_ssl_errors(LOG_LEVEL_ERROR,
1396 "Writing private key into PEM string failed");
1401 len = (size_t)BIO_get_mem_data(bio_mem, &bio_mem_data);
1403 /* Initializing buffer for key file content */
1404 *ret_buf = zalloc_or_die(len + 1);
1405 (*ret_buf)[len] = 0;
1407 strncpy(*ret_buf, bio_mem_data, len);
1410 * Saving key into file
1412 if ((f = fopen(key_file_path, "wb")) == NULL)
1414 log_error(LOG_LEVEL_ERROR,
1415 "Opening file %s to save private key failed: %E",
1421 if (fwrite(*ret_buf, 1, len, f) != len)
1423 log_error(LOG_LEVEL_ERROR,
1424 "Writing private key into file %s failed",
1426 close_file_stream(f, key_file_path);
1431 close_file_stream(f, key_file_path);
1445 /*********************************************************************
1447 * Function : generate_key
1449 * Description : Tests if private key for host saved in csp already
1450 * exists. If this file doesn't exists, a new key is
1451 * generated and saved in a file. The generated key is also
1452 * copied into given parameter key_buf, which must be then
1453 * freed by caller. If file with key exists, key_buf
1454 * contain NULL and no private key is generated.
1457 * 1 : csp = Current client state (buffers, headers, etc...)
1458 * 2 : key_buf = buffer to save new generated key
1460 * Returns : -1 => Error while generating private key
1461 * 0 => Key already exists
1462 * >0 => Length of generated private key
1464 *********************************************************************/
1465 static int generate_key(struct client_state *csp, char **key_buf)
1468 char* key_file_path = NULL;
1469 BIGNUM *exp = BN_new();
1470 RSA *rsa = RSA_new();
1471 EVP_PKEY *key = EVP_PKEY_new();
1473 if (exp == NULL || rsa == NULL || key == NULL)
1475 log_ssl_errors(LOG_LEVEL_ERROR, "RSA key memory allocation failure");
1480 if (BN_set_word(exp, RSA_KEY_PUBLIC_EXPONENT) != 1)
1482 log_ssl_errors(LOG_LEVEL_ERROR, "Setting RSA key exponent failed");
1487 key_file_path = make_certs_path(csp->config->certificate_directory,
1488 (char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
1489 if (key_file_path == NULL)
1496 * Test if key already exists. If so, we don't have to create it again.
1498 if (file_exists(key_file_path) == 1)
1504 ret = RSA_generate_key_ex(rsa, RSA_KEYSIZE, exp, NULL);
1507 log_ssl_errors(LOG_LEVEL_ERROR, "RSA key generation failure");
1512 if (!EVP_PKEY_set1_RSA(key, rsa))
1514 log_ssl_errors(LOG_LEVEL_ERROR,
1515 "Error assigning RSA key pair to PKEY structure");
1521 * Exporting private key into file
1523 if ((ret = write_private_key(key, key_buf, key_file_path)) < 0)
1525 log_error(LOG_LEVEL_ERROR,
1526 "Writing private key into file %s failed", key_file_path);
1533 * Freeing used variables
1547 freez(key_file_path);
1553 /*********************************************************************
1555 * Function : ssl_certificate_load
1557 * Description : Loads certificate from file.
1560 * 1 : cert_path = The certificate path to load
1562 * Returns : NULL => error loading certificate,
1563 * pointer to certificate instance otherwise
1565 *********************************************************************/
1566 static X509* ssl_certificate_load(const char *cert_path)
1569 FILE *cert_f = NULL;
1571 if (!(cert_f = fopen(cert_path, "r")))
1573 log_error(LOG_LEVEL_ERROR,
1574 "Error opening certificate file %s: %s", cert_path, strerror(errno));
1578 if (!(cert = PEM_read_X509(cert_f, NULL, NULL, NULL)))
1580 log_ssl_errors(LOG_LEVEL_ERROR,
1581 "Error reading certificate file %s", cert_path);
1584 close_file_stream(cert_f, cert_path);
1589 /*********************************************************************
1591 * Function : ssl_certificate_is_invalid
1593 * Description : Checks whether or not a certificate is valid.
1594 * Currently only checks that the certificate can be
1595 * parsed and that the "valid to" date is in the future.
1598 * 1 : cert_file = The certificate to check
1600 * Returns : 0 => The certificate is valid.
1601 * 1 => The certificate is invalid
1603 *********************************************************************/
1604 static int ssl_certificate_is_invalid(const char *cert_file)
1610 if (!(cert = ssl_certificate_load(cert_file)))
1612 log_ssl_errors(LOG_LEVEL_ERROR,
1613 "Error reading certificate file %s", cert_file);
1617 ret = X509_cmp_current_time(X509_get_notAfter(cert));
1620 log_ssl_errors(LOG_LEVEL_ERROR,
1621 "Error checking certificate %s validity", cert_file);
1627 return ret == -1 ? 1 : 0;
1631 /*********************************************************************
1633 * Function : set_x509_ext
1635 * Description : Sets the X509V3 extension data
1638 * 1 : cert = The certificate to modify
1639 * 2 : issuer = Issuer certificate
1640 * 3 : nid = OpenSSL NID
1641 * 4 : value = extension value
1643 * Returns : 0 => Error while setting extensuon data
1646 *********************************************************************/
1647 static int set_x509_ext(X509 *cert, X509 *issuer, int nid, char *value)
1649 X509_EXTENSION *ext = NULL;
1653 X509V3_set_ctx(&ctx, issuer, cert, NULL, NULL, 0);
1654 ext = X509V3_EXT_conf_nid(NULL, &ctx, nid, value);
1657 log_ssl_errors(LOG_LEVEL_ERROR, "X509V3_EXT_conf_nid failure");
1661 if (!X509_add_ext(cert, ext, -1))
1663 log_ssl_errors(LOG_LEVEL_ERROR, "X509_add_ext failure");
1671 X509_EXTENSION_free(ext);
1677 /*********************************************************************
1679 * Function : set_subject_alternative_name
1681 * Description : Sets the Subject Alternative Name extension to a cert
1684 * 1 : cert = The certificate to modify
1685 * 2 : issuer = Issuer certificate
1686 * 3 : hostname = The hostname to add
1688 * Returns : 0 => Error while creating certificate.
1691 *********************************************************************/
1692 static int set_subject_alternative_name(X509 *cert, X509 *issuer, const char *hostname)
1694 size_t altname_len = strlen(hostname) + sizeof(CERTIFICATE_ALT_NAME_PREFIX);
1695 char alt_name_buf[altname_len];
1697 snprintf(alt_name_buf, sizeof(alt_name_buf),
1698 CERTIFICATE_ALT_NAME_PREFIX"%s", hostname);
1699 return set_x509_ext(cert, issuer, NID_subject_alt_name, alt_name_buf);
1703 /*********************************************************************
1705 * Function : generate_webpage_certificate
1707 * Description : Creates certificate file in presetted directory.
1708 * If certificate already exists, no other certificate
1709 * will be created. Subject of certificate is named
1710 * by csp->http->host from parameter. This function also
1711 * triggers generating of private key for new certificate.
1714 * 1 : csp = Current client state (buffers, headers, etc...)
1716 * Returns : -1 => Error while creating certificate.
1717 * 0 => Certificate already exists.
1718 * 1 => Certificate created
1720 *********************************************************************/
1721 static int generate_webpage_certificate(struct client_state *csp)
1723 char *key_buf = NULL; /* Buffer for created key */
1724 X509 *issuer_cert = NULL;
1727 EVP_PKEY *loaded_subject_key = NULL;
1728 EVP_PKEY *loaded_issuer_key = NULL;
1729 X509_NAME *issuer_name;
1730 X509_NAME *subject_name = NULL;
1731 ASN1_TIME *asn_time = NULL;
1732 ASN1_INTEGER *serial = NULL;
1733 BIGNUM *serial_num = NULL;
1736 cert_options cert_opt;
1737 char cert_valid_from[VALID_DATETIME_BUFLEN];
1738 char cert_valid_to[VALID_DATETIME_BUFLEN];
1740 /* Paths to keys and certificates needed to create certificate */
1741 cert_opt.issuer_key = NULL;
1742 cert_opt.subject_key = NULL;
1743 cert_opt.issuer_crt = NULL;
1745 cert_opt.output_file = make_certs_path(csp->config->certificate_directory,
1746 (const char *)csp->http->hash_of_host_hex, CERT_FILE_TYPE);
1747 if (cert_opt.output_file == NULL)
1752 cert_opt.subject_key = make_certs_path(csp->config->certificate_directory,
1753 (const char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
1754 if (cert_opt.subject_key == NULL)
1756 freez(cert_opt.output_file);
1760 if (file_exists(cert_opt.output_file) == 1)
1762 /* The file exists, but is it valid? */
1763 if (ssl_certificate_is_invalid(cert_opt.output_file))
1765 log_error(LOG_LEVEL_CONNECT,
1766 "Certificate %s is no longer valid. Removing it.",
1767 cert_opt.output_file);
1768 if (unlink(cert_opt.output_file))
1770 log_error(LOG_LEVEL_ERROR, "Failed to unlink %s: %E",
1771 cert_opt.output_file);
1773 freez(cert_opt.output_file);
1774 freez(cert_opt.subject_key);
1778 if (unlink(cert_opt.subject_key))
1780 log_error(LOG_LEVEL_ERROR, "Failed to unlink %s: %E",
1781 cert_opt.subject_key);
1783 freez(cert_opt.output_file);
1784 freez(cert_opt.subject_key);
1791 freez(cert_opt.output_file);
1792 freez(cert_opt.subject_key);
1799 * Create key for requested host
1801 int subject_key_len = generate_key(csp, &key_buf);
1802 if (subject_key_len < 0)
1804 freez(cert_opt.output_file);
1805 freez(cert_opt.subject_key);
1806 log_error(LOG_LEVEL_ERROR, "Key generating failed");
1811 * Converting unsigned long serial number to char * serial number.
1812 * We must compute length of serial number in string + terminating null.
1814 unsigned long certificate_serial = get_certificate_serial(csp);
1815 unsigned long certificate_serial_time = (unsigned long)time(NULL);
1816 int serial_num_size = snprintf(NULL, 0, "%lu%lu",
1817 certificate_serial_time, certificate_serial) + 1;
1818 if (serial_num_size <= 0)
1820 serial_num_size = 1;
1823 char serial_num_text[serial_num_size]; /* Buffer for serial number */
1824 ret = snprintf(serial_num_text, (size_t)serial_num_size, "%lu%lu",
1825 certificate_serial_time, certificate_serial);
1826 if (ret < 0 || ret >= serial_num_size)
1828 log_error(LOG_LEVEL_ERROR,
1829 "Converting certificate serial number into string failed");
1835 * Preparing parameters for certificate
1837 subject_name = X509_NAME_new();
1840 log_ssl_errors(LOG_LEVEL_ERROR, "RSA key memory allocation failure");
1845 if (!X509_NAME_add_entry_by_txt(subject_name, CERT_PARAM_COMMON_NAME_FCODE,
1846 MBSTRING_ASC, (void *)csp->http->host, -1, -1, 0))
1848 log_ssl_errors(LOG_LEVEL_ERROR,
1849 "X509 subject name (code: %s, val: %s) error",
1850 CERT_PARAM_COMMON_NAME_FCODE, csp->http->host);
1854 if (!X509_NAME_add_entry_by_txt(subject_name, CERT_PARAM_ORGANIZATION_FCODE,
1855 MBSTRING_ASC, (void *)csp->http->host, -1, -1, 0))
1857 log_ssl_errors(LOG_LEVEL_ERROR,
1858 "X509 subject name (code: %s, val: %s) error",
1859 CERT_PARAM_ORGANIZATION_FCODE, csp->http->host);
1863 if (!X509_NAME_add_entry_by_txt(subject_name, CERT_PARAM_ORG_UNIT_FCODE,
1864 MBSTRING_ASC, (void *)csp->http->host, -1, -1, 0))
1866 log_ssl_errors(LOG_LEVEL_ERROR,
1867 "X509 subject name (code: %s, val: %s) error",
1868 CERT_PARAM_ORG_UNIT_FCODE, csp->http->host);
1872 if (!X509_NAME_add_entry_by_txt(subject_name, CERT_PARAM_COUNTRY_FCODE,
1873 MBSTRING_ASC, (void *)CERT_PARAM_COUNTRY_CODE, -1, -1, 0))
1875 log_ssl_errors(LOG_LEVEL_ERROR,
1876 "X509 subject name (code: %s, val: %s) error",
1877 CERT_PARAM_COUNTRY_FCODE, csp->http->host);
1882 cert_opt.issuer_crt = csp->config->ca_cert_file;
1883 cert_opt.issuer_key = csp->config->ca_key_file;
1885 if (get_certificate_valid_from_date(cert_valid_from,
1886 sizeof(cert_valid_from), VALID_DATETIME_FMT)
1887 || get_certificate_valid_to_date(cert_valid_to,
1888 sizeof(cert_valid_to), VALID_DATETIME_FMT))
1890 log_error(LOG_LEVEL_ERROR, "Generating one of the validity dates failed");
1895 cert_opt.subject_pwd = CERT_SUBJECT_PASSWORD;
1896 cert_opt.issuer_pwd = csp->config->ca_password;
1897 cert_opt.not_before = cert_valid_from;
1898 cert_opt.not_after = cert_valid_to;
1899 cert_opt.serial = serial_num_text;
1900 cert_opt.max_pathlen = -1;
1903 * Test if the private key was already created.
1904 * XXX: Can this still happen?
1906 if (subject_key_len == 0)
1908 log_error(LOG_LEVEL_ERROR, "Subject key was already created");
1914 * Parse serial to MPI
1916 serial_num = BN_new();
1919 log_error(LOG_LEVEL_ERROR, "generate_webpage_certificate: memory error");
1923 if (!BN_dec2bn(&serial_num, cert_opt.serial))
1925 log_ssl_errors(LOG_LEVEL_ERROR, "Failed to parse serial %s", cert_opt.serial);
1930 if (!(serial = BN_to_ASN1_INTEGER(serial_num, NULL)))
1932 log_ssl_errors(LOG_LEVEL_ERROR, "Failed to generate serial ASN1 representation");
1938 * Loading certificates
1940 if (!(issuer_cert = ssl_certificate_load(cert_opt.issuer_crt)))
1942 log_error(LOG_LEVEL_ERROR, "Loading issuer certificate %s failed",
1943 cert_opt.issuer_crt);
1948 issuer_name = X509_get_issuer_name(issuer_cert);
1951 * Loading keys from file or from buffer
1953 if (key_buf != NULL && subject_key_len > 0)
1955 pk_bio = BIO_new_mem_buf(key_buf, subject_key_len);
1957 else if (!(pk_bio = BIO_new_file(cert_opt.subject_key, "r")))
1959 log_ssl_errors(LOG_LEVEL_ERROR,
1960 "Failure opening subject key %s BIO", cert_opt.subject_key);
1965 loaded_subject_key = PEM_read_bio_PrivateKey(pk_bio, NULL, NULL,
1966 (void *)cert_opt.subject_pwd);
1967 if (!loaded_subject_key)
1969 log_ssl_errors(LOG_LEVEL_ERROR, "Parsing subject key %s failed",
1970 cert_opt.subject_key);
1975 if (!BIO_free(pk_bio))
1977 log_ssl_errors(LOG_LEVEL_ERROR, "Error closing subject key BIO");
1980 if (!(pk_bio = BIO_new_file(cert_opt.issuer_key, "r")))
1982 log_ssl_errors(LOG_LEVEL_ERROR, "Failure opening issuer key %s BIO",
1983 cert_opt.issuer_key);
1988 loaded_issuer_key = PEM_read_bio_PrivateKey(pk_bio, NULL, NULL,
1989 (void *)cert_opt.issuer_pwd);
1990 if (!loaded_issuer_key)
1992 log_ssl_errors(LOG_LEVEL_ERROR, "Parsing issuer key %s failed",
1993 cert_opt.subject_key);
2001 log_ssl_errors(LOG_LEVEL_ERROR, "Certificate allocation error");
2006 if (!X509_set_version(cert, CERTIFICATE_VERSION))
2008 log_ssl_errors(LOG_LEVEL_ERROR, "X509_set_version failed");
2014 * Setting parameters of signed certificate
2016 if (!X509_set_pubkey(cert, loaded_subject_key))
2018 log_ssl_errors(LOG_LEVEL_ERROR,
2019 "Setting public key in signed certificate failed");
2024 if (!X509_set_subject_name(cert, subject_name))
2026 log_ssl_errors(LOG_LEVEL_ERROR,
2027 "Setting subject name in signed certificate failed");
2032 if (!X509_set_issuer_name(cert, issuer_name))
2034 log_ssl_errors(LOG_LEVEL_ERROR,
2035 "Setting issuer name in signed certificate failed");
2040 if (!X509_set_serialNumber(cert, serial))
2042 log_ssl_errors(LOG_LEVEL_ERROR,
2043 "Setting serial number in signed certificate failed");
2048 asn_time = ASN1_TIME_new();
2051 log_ssl_errors(LOG_LEVEL_ERROR, "ASN1 time memory allocation failure");
2056 if (!ASN1_TIME_set_string(asn_time, cert_opt.not_after))
2058 log_ssl_errors(LOG_LEVEL_ERROR, "ASN1 time [%s] encode error", cert_opt.not_after);
2063 if (!X509_set1_notAfter(cert, asn_time))
2065 log_ssl_errors(LOG_LEVEL_ERROR,
2066 "Setting valid not after in signed certificate failed");
2071 if (!ASN1_TIME_set_string(asn_time, cert_opt.not_before))
2073 log_ssl_errors(LOG_LEVEL_ERROR, "ASN1 time encode error");
2078 if (!X509_set1_notBefore(cert, asn_time))
2080 log_ssl_errors(LOG_LEVEL_ERROR,
2081 "Setting valid not before in signed certificate failed");
2086 if (!set_x509_ext(cert, issuer_cert, NID_basic_constraints, CERTIFICATE_BASIC_CONSTRAINTS))
2088 log_ssl_errors(LOG_LEVEL_ERROR, "Setting the basicConstraints extension "
2089 "in signed certificate failed");
2094 if (!set_x509_ext(cert, issuer_cert, NID_subject_key_identifier, CERTIFICATE_SUBJECT_KEY))
2096 log_ssl_errors(LOG_LEVEL_ERROR,
2097 "Setting the Subject Key Identifier extension failed");
2102 if (!set_x509_ext(cert, issuer_cert, NID_authority_key_identifier, CERTIFICATE_AUTHORITY_KEY))
2104 log_ssl_errors(LOG_LEVEL_ERROR,
2105 "Setting the Authority Key Identifier extension failed");
2110 if (!host_is_ip_address(csp->http->host) &&
2111 !set_subject_alternative_name(cert, issuer_cert, csp->http->host))
2113 log_ssl_errors(LOG_LEVEL_ERROR,
2114 "Setting the Subject Alt Name extension failed");
2119 if (!X509_sign(cert, loaded_issuer_key, EVP_sha256()))
2121 log_ssl_errors(LOG_LEVEL_ERROR, "Signing certificate failed");
2127 * Writing certificate into file
2129 if (write_certificate(cert, cert_opt.output_file) < 0)
2131 log_error(LOG_LEVEL_ERROR, "Writing certificate into file failed");
2140 * Freeing used structures
2144 X509_free(issuer_cert);
2150 if (pk_bio && !BIO_free(pk_bio))
2152 log_ssl_errors(LOG_LEVEL_ERROR, "Error closing pk BIO");
2154 if (loaded_subject_key)
2156 EVP_PKEY_free(loaded_subject_key);
2158 if (loaded_issuer_key)
2160 EVP_PKEY_free(loaded_issuer_key);
2164 X509_NAME_free(subject_name);
2168 ASN1_TIME_free(asn_time);
2172 BN_free(serial_num);
2176 ASN1_INTEGER_free(serial);
2178 freez(cert_opt.subject_key);
2179 freez(cert_opt.output_file);
2186 /*********************************************************************
2188 * Function : ssl_crt_verify_info
2190 * Description : Returns an informational string about the verification
2191 * status of a certificate.
2194 * 1 : buf = Buffer to write to
2195 * 2 : size = Maximum size of buffer
2196 * 3 : csp = client state
2200 *********************************************************************/
2201 extern void ssl_crt_verify_info(char *buf, size_t size, struct client_state *csp)
2203 strncpy(buf, X509_verify_cert_error_string(csp->server_cert_verification_result), size);
2208 /*********************************************************************
2210 * Function : ssl_release
2212 * Description : Release all SSL resources
2218 *********************************************************************/
2219 extern void ssl_release(void)
2221 if (ssl_inited == 1)
2223 #ifndef OPENSSL_NO_COMP
2224 SSL_COMP_free_compression_methods();
2226 CONF_modules_free();
2227 CONF_modules_unload(1);
2228 #ifndef OPENSSL_NO_COMP
2229 COMP_zlib_cleanup();
2235 CRYPTO_cleanup_all_ex_data();