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
7 * using OpenSSL (or LibreSSL).
9 * Copyright : Written by and Copyright (c) 2020 Maxim Antonov <mantonov@gmail.com>
10 * Copyright (C) 2017 Vaclav Svec. FIT CVUT.
11 * Copyright (C) 2018-2022 by Fabian Keil <fk@fabiankeil.de>
13 * This program is free software; you can redistribute it
14 * and/or modify it under the terms of the GNU General
15 * Public License as published by the Free Software
16 * Foundation; either version 2 of the License, or (at
17 * your option) any later version.
19 * This program is distributed in the hope that it will
20 * be useful, but WITHOUT ANY WARRANTY; without even the
21 * implied warranty of MERCHANTABILITY or FITNESS FOR A
22 * PARTICULAR PURPOSE. See the GNU General Public
23 * License for more details.
25 * The GNU General Public License should be included with
26 * this file. If not, you can view it at
27 * http://www.gnu.org/copyleft/gpl.html
28 * or write to the Free Software Foundation, Inc., 59
29 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
31 *********************************************************************/
36 #include <openssl/bn.h>
37 #include <openssl/opensslv.h>
38 #include <openssl/pem.h>
39 #include <openssl/md5.h>
40 #include <openssl/x509v3.h>
49 #include "ssl_common.h"
52 * Macros for openssl.c
54 #define CERTIFICATE_BASIC_CONSTRAINTS "CA:FALSE"
55 #define CERTIFICATE_SUBJECT_KEY "hash"
56 #define CERTIFICATE_AUTHORITY_KEY "keyid:always"
57 #define CERTIFICATE_ALT_NAME_PREFIX "DNS:"
58 #define CERTIFICATE_VERSION 2
59 #define VALID_DATETIME_FMT "%y%m%d%H%M%SZ"
60 #define VALID_DATETIME_BUFLEN 16
62 static int generate_host_certificate(struct client_state *csp);
63 static void free_client_ssl_structures(struct client_state *csp);
64 static void free_server_ssl_structures(struct client_state *csp);
65 static int ssl_store_cert(struct client_state *csp, X509 *crt);
66 static void log_ssl_errors(int debuglevel, const char* fmt, ...) __attribute__((format(printf, 2, 3)));
68 static int ssl_inited = 0;
70 #if OPENSSL_VERSION_NUMBER < 0x10100000L
71 #define X509_set1_notBefore X509_set_notBefore
72 #define X509_set1_notAfter X509_set_notAfter
73 #define X509_get0_serialNumber X509_get_serialNumber
74 #define X509_get0_notBefore X509_get_notBefore
75 #define X509_get0_notAfter X509_get_notAfter
78 /*********************************************************************
80 * Function : openssl_init
82 * Description : Initializes OpenSSL library once
88 *********************************************************************/
89 static void openssl_init(void)
93 privoxy_mutex_lock(&ssl_init_mutex);
96 #if OPENSSL_VERSION_NUMBER < 0x10100000L
99 OPENSSL_init_ssl(0, NULL);
101 SSL_load_error_strings();
102 OpenSSL_add_ssl_algorithms();
105 privoxy_mutex_unlock(&ssl_init_mutex);
110 /*********************************************************************
112 * Function : is_ssl_pending
114 * Description : Tests if there are some waiting data on ssl connection.
115 * Only considers data that has actually been received
116 * locally and ignores data that is still on the fly
117 * or has not yet been sent by the remote end.
120 * 1 : ssl_attr = SSL context to test
122 * Returns : 0 => No data are pending
123 * >0 => Pending data length
125 *********************************************************************/
126 extern size_t is_ssl_pending(struct ssl_attr *ssl_attr)
128 BIO *bio = ssl_attr->openssl_attr.bio;
134 return (size_t)BIO_pending(bio);
138 /*********************************************************************
140 * Function : ssl_send_data
142 * Description : Sends the content of buf (for n bytes) to given SSL
143 * connection context.
146 * 1 : ssl_attr = SSL context to send data to
147 * 2 : buf = Pointer to data to be sent
148 * 3 : len = Length of data to be sent to the SSL context
150 * Returns : Length of sent data or negative value on error.
152 *********************************************************************/
153 extern int ssl_send_data(struct ssl_attr *ssl_attr, const unsigned char *buf, size_t len)
155 BIO *bio = ssl_attr->openssl_attr.bio;
158 int pos = 0; /* Position of unsent part in buffer */
166 if (BIO_get_ssl(bio, &ssl) == 1)
168 fd = SSL_get_fd(ssl);
173 int send_len = (int)len - pos;
175 log_error(LOG_LEVEL_WRITING, "TLS on socket %d: %N",
176 fd, send_len, buf+pos);
179 * Sending one part of the buffer
181 while ((ret = BIO_write(bio,
182 (const unsigned char *)(buf + pos),
185 if (!BIO_should_retry(bio))
187 log_ssl_errors(LOG_LEVEL_ERROR,
188 "Sending data on socket %d over TLS/SSL failed", fd);
192 /* Adding count of sent bytes to position in buffer */
200 /*********************************************************************
202 * Function : ssl_recv_data
204 * Description : Receives data from given SSL context and puts
208 * 1 : ssl_attr = SSL context to receive data from
209 * 2 : buf = Pointer to buffer where data will be written
210 * 3 : max_length = Maximum number of bytes to read
212 * Returns : Number of bytes read, 0 for EOF, or -1
215 *********************************************************************/
216 extern int ssl_recv_data(struct ssl_attr *ssl_attr, unsigned char *buf, size_t max_length)
218 BIO *bio = ssl_attr->openssl_attr.bio;
223 memset(buf, 0, max_length);
226 * Receiving data from SSL context into buffer
230 ret = BIO_read(bio, buf, (int)max_length);
231 } while (ret <= 0 && BIO_should_retry(bio));
233 if (BIO_get_ssl(bio, &ssl) == 1)
235 fd = SSL_get_fd(ssl);
240 log_ssl_errors(LOG_LEVEL_ERROR,
241 "Receiving data on socket %d over TLS/SSL failed", fd);
246 log_error(LOG_LEVEL_RECEIVED, "TLS from socket %d: %N",
253 /*********************************************************************
255 * Function : ssl_store_cert
257 * Description : This function is called once for each certificate in the
258 * server's certificate trusted chain and prepares
259 * information about the certificate. The information can
260 * be used to inform the user about invalid certificates.
263 * 1 : csp = Current client state (buffers, headers, etc...)
264 * 2 : crt = certificate from trusted chain
266 * Returns : 0 on success and negative value on error
268 *********************************************************************/
269 static int ssl_store_cert(struct client_state *csp, X509 *crt)
272 struct certs_chain *last = &(csp->server_certs_chain);
274 BIO *bio = BIO_new(BIO_s_mem());
275 EVP_PKEY *pkey = NULL;
276 char *bio_mem_data = NULL;
279 const ASN1_INTEGER *bs;
280 #if OPENSSL_VERSION_NUMBER > 0x10100000L
281 const X509_ALGOR *tsig_alg;
287 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_new() failed");
292 * Searching for last item in certificates linked list
294 while (last->next != NULL)
300 * Preparing next item in linked list for next certificate
302 last->next = malloc_or_die(sizeof(struct certs_chain));
303 last->next->next = NULL;
304 memset(last->next->info_buf, 0, sizeof(last->next->info_buf));
305 last->next->file_buf = NULL;
308 * Saving certificate file into buffer
310 if (!PEM_write_bio_X509(bio, crt))
312 log_ssl_errors(LOG_LEVEL_ERROR, "PEM_write_bio_X509() failed");
317 len = BIO_get_mem_data(bio, &bio_mem_data);
319 last->file_buf = malloc((size_t)len + 1);
320 if (last->file_buf == NULL)
322 log_error(LOG_LEVEL_ERROR,
323 "Failed to allocate %lu bytes to store the X509 PEM certificate",
329 strncpy(last->file_buf, bio_mem_data, (size_t)len);
330 last->file_buf[len] = '\0';
332 bio = BIO_new(BIO_s_mem());
335 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_new() failed");
341 * Saving certificate information into buffer
343 l = X509_get_version(crt);
344 if (l >= 0 && l <= 2)
346 if (BIO_printf(bio, "cert. version : %ld\n", l + 1) <= 0)
348 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for version failed");
355 if (BIO_printf(bio, "cert. version : Unknown (%ld)\n", l) <= 0)
357 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for version failed");
363 if (BIO_puts(bio, "serial number : ") <= 0)
365 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_puts() for serial failed");
369 bs = X509_get0_serialNumber(crt);
370 if (bs->length <= (int)sizeof(long))
373 l = ASN1_INTEGER_get(bs);
384 if (bs->type == V_ASN1_NEG_INTEGER)
386 ul = 0 - (unsigned long)l;
391 ul = (unsigned long)l;
394 if (BIO_printf(bio, "%s%lu (%s0x%lx)\n", neg, ul, neg, ul) <= 0)
396 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for serial failed");
404 if (bs->type == V_ASN1_NEG_INTEGER)
406 if (BIO_puts(bio, " (Negative)") < 0)
408 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_puts() for serial failed");
413 for (i = 0; i < bs->length; i++)
415 if (BIO_printf(bio, "%02x%c", bs->data[i],
416 ((i + 1 == bs->length) ? '\n' : ':')) <= 0)
418 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for serial failed");
425 if (BIO_puts(bio, "issuer name : ") <= 0)
427 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_puts() for issuer failed");
431 if (X509_NAME_print_ex(bio, X509_get_issuer_name(crt), 0, 0) < 0)
433 log_ssl_errors(LOG_LEVEL_ERROR, "X509_NAME_print_ex() for issuer failed");
438 if (BIO_puts(bio, "\nsubject name : ") <= 0)
440 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_puts() for subject failed");
444 if (X509_NAME_print_ex(bio, X509_get_subject_name(crt), 0, 0) < 0) {
445 log_ssl_errors(LOG_LEVEL_ERROR, "X509_NAME_print_ex() for subject failed");
450 if (BIO_puts(bio, "\nissued on : ") <= 0)
452 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_puts() for issued on failed");
456 if (!ASN1_TIME_print(bio, X509_get0_notBefore(crt)))
458 log_ssl_errors(LOG_LEVEL_ERROR, "ASN1_TIME_print() for issued on failed");
463 if (BIO_puts(bio, "\nexpires on : ") <= 0)
465 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_puts() for expires on failed");
469 if (!ASN1_TIME_print(bio, X509_get0_notAfter(crt)))
471 log_ssl_errors(LOG_LEVEL_ERROR, "ASN1_TIME_print() for expires on failed");
476 #if OPENSSL_VERSION_NUMBER > 0x10100000L
477 if (BIO_puts(bio, "\nsigned using : ") <= 0)
479 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_puts() for signed using failed");
483 tsig_alg = X509_get0_tbs_sigalg(crt);
484 if (!i2a_ASN1_OBJECT(bio, tsig_alg->algorithm))
486 log_ssl_errors(LOG_LEVEL_ERROR, "i2a_ASN1_OBJECT() for signed using failed");
491 pkey = X509_get_pubkey(crt);
494 log_ssl_errors(LOG_LEVEL_ERROR, "X509_get_pubkey() failed");
499 switch (EVP_PKEY_base_id(pkey))
502 ret = BIO_printf(bio, "\n%-" BC "s: %d bits", "RSA key size", EVP_PKEY_bits(pkey));
505 ret = BIO_printf(bio, "\n%-" BC "s: %d bits", "DSA key size", EVP_PKEY_bits(pkey));
508 ret = BIO_printf(bio, "\n%-" BC "s: %d bits", "EC key size", EVP_PKEY_bits(pkey));
511 ret = BIO_printf(bio, "\n%-" BC "s: %d bits", "non-RSA/DSA/EC key size",
512 EVP_PKEY_bits(pkey));
517 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for key size failed");
522 loc = X509_get_ext_by_NID(crt, NID_basic_constraints, -1);
525 X509_EXTENSION *ex = X509_get_ext(crt, loc);
526 if (BIO_puts(bio, "\nbasic constraints : ") <= 0)
528 log_ssl_errors(LOG_LEVEL_ERROR,
529 "BIO_printf() for basic constraints failed");
533 if (!X509V3_EXT_print(bio, ex, 0, 0))
535 if (!ASN1_STRING_print_ex(bio, X509_EXTENSION_get_data(ex), ASN1_STRFLGS_RFC2253))
537 log_ssl_errors(LOG_LEVEL_ERROR,
538 "ASN1_STRING_print_ex() for basic constraints failed");
545 loc = X509_get_ext_by_NID(crt, NID_subject_alt_name, -1);
548 X509_EXTENSION *ex = X509_get_ext(crt, loc);
549 if (BIO_puts(bio, "\nsubject alt name : ") <= 0)
551 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for alt name failed");
555 if (!X509V3_EXT_print(bio, ex, 0, 0))
557 if (!ASN1_STRING_print_ex(bio, X509_EXTENSION_get_data(ex),
558 ASN1_STRFLGS_RFC2253))
560 log_ssl_errors(LOG_LEVEL_ERROR,
561 "ASN1_STRING_print_ex() for alt name failed");
568 loc = X509_get_ext_by_NID(crt, NID_netscape_cert_type, -1);
571 X509_EXTENSION *ex = X509_get_ext(crt, loc);
572 if (BIO_puts(bio, "\ncert. type : ") <= 0)
574 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for cert type failed");
578 if (!X509V3_EXT_print(bio, ex, 0, 0))
580 if (!ASN1_STRING_print_ex(bio, X509_EXTENSION_get_data(ex),
581 ASN1_STRFLGS_RFC2253))
583 log_ssl_errors(LOG_LEVEL_ERROR,
584 "ASN1_STRING_print_ex() for cert type failed");
591 loc = X509_get_ext_by_NID(crt, NID_key_usage, -1);
594 X509_EXTENSION *ex = X509_get_ext(crt, loc);
595 if (BIO_puts(bio, "\nkey usage : ") <= 0)
597 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for key usage failed");
601 if (!X509V3_EXT_print(bio, ex, 0, 0))
603 if (!ASN1_STRING_print_ex(bio, X509_EXTENSION_get_data(ex),
604 ASN1_STRFLGS_RFC2253))
606 log_ssl_errors(LOG_LEVEL_ERROR,
607 "ASN1_STRING_print_ex() for key usage failed");
614 loc = X509_get_ext_by_NID(crt, NID_ext_key_usage, -1);
616 X509_EXTENSION *ex = X509_get_ext(crt, loc);
617 if (BIO_puts(bio, "\next key usage : ") <= 0)
619 log_ssl_errors(LOG_LEVEL_ERROR,
620 "BIO_printf() for ext key usage failed");
624 if (!X509V3_EXT_print(bio, ex, 0, 0))
626 if (!ASN1_STRING_print_ex(bio, X509_EXTENSION_get_data(ex),
627 ASN1_STRFLGS_RFC2253))
629 log_ssl_errors(LOG_LEVEL_ERROR,
630 "ASN1_STRING_print_ex() for ext key usage failed");
637 loc = X509_get_ext_by_NID(crt, NID_certificate_policies, -1);
640 X509_EXTENSION *ex = X509_get_ext(crt, loc);
641 if (BIO_puts(bio, "\ncertificate policies : ") <= 0)
643 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for certificate policies failed");
647 if (!X509V3_EXT_print(bio, ex, 0, 0))
649 if (!ASN1_STRING_print_ex(bio, X509_EXTENSION_get_data(ex),
650 ASN1_STRFLGS_RFC2253))
652 log_ssl_errors(LOG_LEVEL_ERROR,
653 "ASN1_STRING_print_ex() for certificate policies failed");
660 /* make valgrind happy */
661 static const char zero = 0;
662 BIO_write(bio, &zero, 1);
664 len = BIO_get_mem_data(bio, &bio_mem_data);
667 log_error(LOG_LEVEL_ERROR, "BIO_get_mem_data() returned %ld "
668 "while gathering certificate information", len);
672 encoded_text = html_encode(bio_mem_data);
673 if (encoded_text == NULL)
675 log_error(LOG_LEVEL_ERROR,
676 "Failed to HTML-encode the certificate information");
681 strlcpy(last->info_buf, encoded_text, sizeof(last->info_buf));
698 /*********************************************************************
700 * Function : host_to_hash
702 * Description : Creates MD5 hash from host name. Host name is loaded
703 * from structure csp and saved again into it.
706 * 1 : csp = Current client state (buffers, headers, etc...)
708 * Returns : -1 => Error while creating hash
709 * 0 => Hash created successfully
711 *********************************************************************/
712 static int host_to_hash(struct client_state *csp)
716 memset(csp->http->hash_of_host, 0, sizeof(csp->http->hash_of_host));
717 MD5((unsigned char *)csp->http->host, strlen(csp->http->host),
718 csp->http->hash_of_host);
720 /* Converting hash into string with hex */
724 if ((ret = sprintf((char *)csp->http->hash_of_host_hex + 2 * i, "%02x",
725 csp->http->hash_of_host[i])) < 0)
727 log_error(LOG_LEVEL_ERROR, "Sprintf return value: %d", ret);
736 /*********************************************************************
738 * Function : create_client_ssl_connection
740 * Description : Creates TLS/SSL secured connection with client
743 * 1 : csp = Current client state (buffers, headers, etc...)
745 * Returns : 0 on success, negative value if connection wasn't created
748 *********************************************************************/
749 extern int create_client_ssl_connection(struct client_state *csp)
751 struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
752 /* Paths to certificates file and key file */
753 char *key_file = NULL;
754 char *cert_file = NULL;
759 * Initializing OpenSSL structures for TLS/SSL connection
764 * Preparing hash of host for creating certificates
766 ret = host_to_hash(csp);
769 log_error(LOG_LEVEL_ERROR, "Generating hash of host failed: %d", ret);
775 * Preparing paths to certificates files and key file
777 cert_file = make_certs_path(csp->config->certificate_directory,
778 (const char *)csp->http->hash_of_host_hex, CERT_FILE_TYPE);
779 key_file = make_certs_path(csp->config->certificate_directory,
780 (const char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
782 if (cert_file == NULL || key_file == NULL)
789 * Generating certificate for requested host. Mutex to prevent
790 * certificate and key inconsistence must be locked.
792 privoxy_mutex_lock(&certificate_mutex);
794 ret = generate_host_certificate(csp);
797 log_error(LOG_LEVEL_ERROR,
798 "generate_host_certificate failed: %d", ret);
799 privoxy_mutex_unlock(&certificate_mutex);
803 privoxy_mutex_unlock(&certificate_mutex);
805 if (!(ssl_attr->openssl_attr.ctx = SSL_CTX_new(SSLv23_server_method())))
807 log_ssl_errors(LOG_LEVEL_ERROR, "Unable to create SSL context");
812 /* Set the key and cert */
813 if (SSL_CTX_use_certificate_file(ssl_attr->openssl_attr.ctx,
814 cert_file, SSL_FILETYPE_PEM) != 1)
816 log_ssl_errors(LOG_LEVEL_ERROR,
817 "Loading webpage certificate %s failed", cert_file);
822 if (SSL_CTX_use_PrivateKey_file(ssl_attr->openssl_attr.ctx,
823 key_file, SSL_FILETYPE_PEM) != 1)
825 log_ssl_errors(LOG_LEVEL_ERROR,
826 "Loading webpage certificate private key %s failed", key_file);
831 SSL_CTX_set_options(ssl_attr->openssl_attr.ctx, SSL_OP_NO_SSLv3);
833 if (!(ssl_attr->openssl_attr.bio = BIO_new_ssl(ssl_attr->openssl_attr.ctx, 0)))
835 log_ssl_errors(LOG_LEVEL_ERROR, "Unable to create BIO structure");
840 if (BIO_get_ssl(ssl_attr->openssl_attr.bio, &ssl) != 1)
842 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_get_ssl failed");
847 if (!SSL_set_fd(ssl, csp->cfd))
849 log_ssl_errors(LOG_LEVEL_ERROR, "SSL_set_fd failed");
854 if (csp->config->cipher_list != NULL)
856 if (!SSL_set_cipher_list(ssl, csp->config->cipher_list))
858 log_ssl_errors(LOG_LEVEL_ERROR,
859 "Setting the cipher list '%s' for the client connection failed",
860 csp->config->cipher_list);
867 * Handshake with client
869 log_error(LOG_LEVEL_CONNECT,
870 "Performing the TLS/SSL handshake with client. Hash of host: %s",
871 csp->http->hash_of_host_hex);
872 if (BIO_do_handshake(ssl_attr->openssl_attr.bio) != 1)
874 log_ssl_errors(LOG_LEVEL_ERROR,
875 "The TLS/SSL handshake with the client failed");
880 log_error(LOG_LEVEL_CONNECT, "Client successfully connected over %s (%s).",
881 SSL_get_version(ssl), SSL_get_cipher_name(ssl));
883 csp->ssl_with_client_is_opened = 1;
888 * Freeing allocated paths to files
893 /* Freeing structures if connection wasn't created successfully */
896 free_client_ssl_structures(csp);
902 /*********************************************************************
904 * Function : close_client_ssl_connection
906 * Description : Closes TLS/SSL connection with client. This function
907 * checks if this connection is already created.
910 * 1 : csp = Current client state (buffers, headers, etc...)
914 *********************************************************************/
915 extern void close_client_ssl_connection(struct client_state *csp)
917 struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
920 if (csp->ssl_with_client_is_opened == 0)
926 * Notifying the peer that the connection is being closed.
928 BIO_ssl_shutdown(ssl_attr->openssl_attr.bio);
929 if (BIO_get_ssl(ssl_attr->openssl_attr.bio, &ssl) != 1)
931 log_ssl_errors(LOG_LEVEL_ERROR,
932 "BIO_get_ssl() failed in close_client_ssl_connection()");
937 * Pretend we received a shutdown alert so
938 * the BIO_free_all() call later on returns
941 SSL_set_shutdown(ssl, SSL_RECEIVED_SHUTDOWN);
943 free_client_ssl_structures(csp);
944 csp->ssl_with_client_is_opened = 0;
948 /*********************************************************************
950 * Function : free_client_ssl_structures
952 * Description : Frees structures used for SSL communication with
956 * 1 : csp = Current client state (buffers, headers, etc...)
960 *********************************************************************/
961 static void free_client_ssl_structures(struct client_state *csp)
963 struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
965 if (ssl_attr->openssl_attr.bio)
967 BIO_free_all(ssl_attr->openssl_attr.bio);
969 if (ssl_attr->openssl_attr.ctx)
971 SSL_CTX_free(ssl_attr->openssl_attr.ctx);
976 /*********************************************************************
978 * Function : close_server_ssl_connection
980 * Description : Closes TLS/SSL connection with server. This function
981 * checks if this connection is already opened.
984 * 1 : csp = Current client state (buffers, headers, etc...)
988 *********************************************************************/
989 extern void close_server_ssl_connection(struct client_state *csp)
991 struct ssl_attr *ssl_attr = &csp->ssl_server_attr;
994 if (csp->ssl_with_server_is_opened == 0)
1000 * Notifying the peer that the connection is being closed.
1002 BIO_ssl_shutdown(ssl_attr->openssl_attr.bio);
1003 if (BIO_get_ssl(ssl_attr->openssl_attr.bio, &ssl) != 1)
1005 log_ssl_errors(LOG_LEVEL_ERROR,
1006 "BIO_get_ssl() failed in close_server_ssl_connection()");
1011 * Pretend we received a shutdown alert so
1012 * the BIO_free_all() call later on returns
1015 SSL_set_shutdown(ssl, SSL_RECEIVED_SHUTDOWN);
1017 free_server_ssl_structures(csp);
1018 csp->ssl_with_server_is_opened = 0;
1022 /*********************************************************************
1024 * Function : create_server_ssl_connection
1026 * Description : Creates TLS/SSL secured connection with server.
1029 * 1 : csp = Current client state (buffers, headers, etc...)
1031 * Returns : 0 on success, negative value if connection wasn't created
1034 *********************************************************************/
1035 extern int create_server_ssl_connection(struct client_state *csp)
1037 openssl_connection_attr *ssl_attrs = &csp->ssl_server_attr.openssl_attr;
1039 char *trusted_cas_file = NULL;
1040 STACK_OF(X509) *chain;
1043 csp->server_cert_verification_result = SSL_CERT_NOT_VERIFIED;
1044 csp->server_certs_chain.next = NULL;
1046 /* Setting path to file with trusted CAs */
1047 trusted_cas_file = csp->config->trusted_cas_file;
1049 ssl_attrs->ctx = SSL_CTX_new(SSLv23_method());
1050 if (!ssl_attrs->ctx)
1052 log_ssl_errors(LOG_LEVEL_ERROR, "SSL context creation failed");
1058 * Loading file with trusted CAs
1060 if (!SSL_CTX_load_verify_locations(ssl_attrs->ctx, trusted_cas_file, NULL))
1062 log_ssl_errors(LOG_LEVEL_ERROR, "Loading trusted CAs file %s failed",
1068 SSL_CTX_set_verify(ssl_attrs->ctx, SSL_VERIFY_NONE, NULL);
1069 SSL_CTX_set_options(ssl_attrs->ctx, SSL_OP_NO_SSLv3);
1071 if (!(ssl_attrs->bio = BIO_new_ssl(ssl_attrs->ctx, 1)))
1073 log_ssl_errors(LOG_LEVEL_ERROR, "Unable to create BIO structure");
1078 if (BIO_get_ssl(ssl_attrs->bio, &ssl) != 1)
1080 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_get_ssl failed");
1085 if (!SSL_set_fd(ssl, csp->server_connection.sfd))
1087 log_ssl_errors(LOG_LEVEL_ERROR, "SSL_set_fd failed");
1092 if (csp->config->cipher_list != NULL)
1094 if (!SSL_set_cipher_list(ssl, csp->config->cipher_list))
1096 log_ssl_errors(LOG_LEVEL_ERROR,
1097 "Setting the cipher list '%s' for the server connection failed",
1098 csp->config->cipher_list);
1105 * Set the hostname to check against the received server certificate
1107 #if OPENSSL_VERSION_NUMBER > 0x10100000L
1108 if (!SSL_set1_host(ssl, csp->http->host))
1110 log_ssl_errors(LOG_LEVEL_ERROR, "SSL_set1_host failed");
1115 if (host_is_ip_address(csp->http->host))
1117 if (X509_VERIFY_PARAM_set1_ip_asc(ssl->param, csp->http->host) != 1)
1119 log_ssl_errors(LOG_LEVEL_ERROR,
1120 "X509_VERIFY_PARAM_set1_ip_asc() failed");
1127 if (X509_VERIFY_PARAM_set1_host(ssl->param, csp->http->host, 0) != 1)
1129 log_ssl_errors(LOG_LEVEL_ERROR,
1130 "X509_VERIFY_PARAM_set1_host() failed");
1137 if (!SSL_set_tlsext_host_name(ssl, csp->http->host))
1139 log_ssl_errors(LOG_LEVEL_ERROR, "SSL_set_tlsext_host_name failed");
1145 * Handshake with server
1147 log_error(LOG_LEVEL_CONNECT,
1148 "Performing the TLS/SSL handshake with the server");
1150 if (BIO_do_handshake(ssl_attrs->bio) != 1)
1152 log_ssl_errors(LOG_LEVEL_ERROR,
1153 "The TLS/SSL handshake with the server failed");
1159 * XXX: Do we really have to do this always?
1160 * Probably it's sufficient to do if the verification fails
1161 * in which case we're sending the certificates to the client.
1163 chain = SSL_get_peer_cert_chain(ssl);
1167 for (i = 0; i < sk_X509_num(chain); i++)
1169 if (ssl_store_cert(csp, sk_X509_value(chain, i)) != 0)
1171 log_error(LOG_LEVEL_ERROR, "ssl_store_cert failed");
1178 if (!csp->dont_verify_certificate)
1180 long verify_result = SSL_get_verify_result(ssl);
1181 if (verify_result == X509_V_OK)
1184 csp->server_cert_verification_result = SSL_CERT_VALID;
1188 csp->server_cert_verification_result = verify_result;
1189 log_error(LOG_LEVEL_ERROR,
1190 "X509 certificate verification for %s failed: %s",
1191 csp->http->hostport, X509_verify_cert_error_string(verify_result));
1197 log_error(LOG_LEVEL_CONNECT, "Server successfully connected over %s (%s).",
1198 SSL_get_version(ssl), SSL_get_cipher_name(ssl));
1201 * Server certificate chain is valid, so we can clean
1202 * chain, because we will not send it to client.
1204 free_certificate_chain(csp);
1206 csp->ssl_with_server_is_opened = 1;
1208 /* Freeing structures if connection wasn't created successfully */
1211 free_server_ssl_structures(csp);
1218 /*********************************************************************
1220 * Function : free_server_ssl_structures
1222 * Description : Frees structures used for SSL communication with server
1225 * 1 : csp = Current client state (buffers, headers, etc...)
1229 *********************************************************************/
1230 static void free_server_ssl_structures(struct client_state *csp)
1232 struct ssl_attr *ssl_attr = &csp->ssl_server_attr;
1234 if (ssl_attr->openssl_attr.bio)
1236 BIO_free_all(ssl_attr->openssl_attr.bio);
1238 if (ssl_attr->openssl_attr.ctx)
1240 SSL_CTX_free(ssl_attr->openssl_attr.ctx);
1245 /*********************************************************************
1247 * Function : log_ssl_errors
1249 * Description : Log SSL errors
1252 * 1 : debuglevel = Debug level
1253 * 2 : desc = Error description
1257 *********************************************************************/
1258 static void log_ssl_errors(int debuglevel, const char* fmt, ...)
1260 unsigned long err_code;
1261 char prefix[ERROR_BUF_SIZE];
1263 va_start(args, fmt);
1264 vsnprintf(prefix, sizeof(prefix), fmt, args);
1267 while ((err_code = ERR_get_error()))
1269 char err_buf[ERROR_BUF_SIZE];
1271 ERR_error_string_n(err_code, err_buf, sizeof(err_buf));
1272 log_error(debuglevel, "%s: %s", prefix, err_buf);
1276 * In case if called by mistake and there were
1277 * no TLS/SSL errors let's report it to the log.
1281 log_error(debuglevel, "%s: no TLS/SSL errors detected", prefix);
1286 /*********************************************************************
1288 * Function : ssl_base64_encode
1290 * Description : Encode a buffer into base64 format.
1293 * 1 : dst = Destination buffer
1294 * 2 : dlen = Destination buffer length
1295 * 3 : olen = Number of bytes written
1296 * 4 : src = Source buffer
1297 * 5 : slen = Amount of data to be encoded
1299 * Returns : 0 on success, error code othervise
1301 *********************************************************************/
1302 extern int ssl_base64_encode(unsigned char *dst, size_t dlen, size_t *olen,
1303 const unsigned char *src, size_t slen)
1305 *olen = 4 * ((slen/3) + ((slen%3) ? 1 : 0)) + 1;
1310 *olen = (size_t)EVP_EncodeBlock(dst, src, (int)slen) + 1;
1315 /*********************************************************************
1317 * Function : close_file_stream
1319 * Description : Close file stream, report error on close error
1322 * 1 : f = file stream to close
1323 * 2 : path = path for error report
1327 *********************************************************************/
1328 static void close_file_stream(FILE *f, const char *path)
1332 log_error(LOG_LEVEL_ERROR,
1333 "Error closing file %s: %s", path, strerror(errno));
1338 /*********************************************************************
1340 * Function : write_certificate
1342 * Description : Writes certificate into file.
1345 * 1 : crt = certificate to write into file
1346 * 2 : output_file = path to save certificate file
1349 * Returns : 1 on success success or negative value
1351 *********************************************************************/
1352 static int write_certificate(X509 *crt, const char *output_file)
1358 * Saving certificate into file
1360 if ((f = fopen(output_file, "w")) == NULL)
1362 log_error(LOG_LEVEL_ERROR, "Opening file %s to save certificate failed",
1367 ret = PEM_write_X509(f, crt);
1370 log_ssl_errors(LOG_LEVEL_ERROR,
1371 "Writing certificate into file %s failed", output_file);
1375 close_file_stream(f, output_file);
1380 /*********************************************************************
1382 * Function : write_private_key
1384 * Description : Writes private key into file and copies saved
1385 * content into given pointer to string. If function
1386 * returns 0 for success, this copy must be freed by
1390 * 1 : key = key to write into file
1391 * 2 : ret_buf = pointer to string with created key file content
1392 * 3 : key_file_path = path where to save key file
1394 * Returns : Length of written private key on success or negative value
1397 *********************************************************************/
1398 static int write_private_key(EVP_PKEY *key, char **ret_buf,
1399 const char *key_file_path)
1401 size_t len = 0; /* Length of created key */
1402 FILE *f = NULL; /* File to save certificate */
1404 BIO *bio_mem = BIO_new(BIO_s_mem());
1405 char *bio_mem_data = 0;
1407 if (bio_mem == NULL)
1409 log_ssl_errors(LOG_LEVEL_ERROR, "write_private_key memory allocation failure");
1414 * Writing private key into PEM string
1416 if (!PEM_write_bio_PrivateKey(bio_mem, key, NULL, NULL, 0, NULL, NULL))
1418 log_ssl_errors(LOG_LEVEL_ERROR,
1419 "Writing private key into PEM string failed");
1424 len = (size_t)BIO_get_mem_data(bio_mem, &bio_mem_data);
1426 /* Initializing buffer for key file content */
1427 *ret_buf = zalloc_or_die(len + 1);
1428 (*ret_buf)[len] = 0;
1430 strncpy(*ret_buf, bio_mem_data, len);
1433 * Saving key into file
1435 if ((f = fopen(key_file_path, "wb")) == NULL)
1437 log_error(LOG_LEVEL_ERROR,
1438 "Opening file %s to save private key failed: %E",
1444 if (fwrite(*ret_buf, 1, len, f) != len)
1446 log_error(LOG_LEVEL_ERROR,
1447 "Writing private key into file %s failed",
1449 close_file_stream(f, key_file_path);
1454 close_file_stream(f, key_file_path);
1468 /*********************************************************************
1470 * Function : generate_key
1472 * Description : Tests if private key for host saved in csp already
1473 * exists. If this file doesn't exists, a new key is
1474 * generated and saved in a file. The generated key is also
1475 * copied into given parameter key_buf, which must be then
1476 * freed by caller. If file with key exists, key_buf
1477 * contain NULL and no private key is generated.
1480 * 1 : csp = Current client state (buffers, headers, etc...)
1481 * 2 : key_buf = buffer to save new generated key
1483 * Returns : -1 => Error while generating private key
1484 * 0 => Key already exists
1485 * >0 => Length of generated private key
1487 *********************************************************************/
1488 static int generate_key(struct client_state *csp, char **key_buf)
1491 char* key_file_path;
1496 key_file_path = make_certs_path(csp->config->certificate_directory,
1497 (char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
1498 if (key_file_path == NULL)
1504 * Test if key already exists. If so, we don't have to create it again.
1506 if (file_exists(key_file_path) == 1)
1508 freez(key_file_path);
1514 key = EVP_PKEY_new();
1515 if (exp == NULL || rsa == NULL || key == NULL)
1517 log_ssl_errors(LOG_LEVEL_ERROR, "RSA key memory allocation failure");
1522 if (BN_set_word(exp, RSA_KEY_PUBLIC_EXPONENT) != 1)
1524 log_ssl_errors(LOG_LEVEL_ERROR, "Setting RSA key exponent failed");
1529 ret = RSA_generate_key_ex(rsa, RSA_KEYSIZE, exp, NULL);
1532 log_ssl_errors(LOG_LEVEL_ERROR, "RSA key generation failure");
1537 if (!EVP_PKEY_set1_RSA(key, rsa))
1539 log_ssl_errors(LOG_LEVEL_ERROR,
1540 "Error assigning RSA key pair to PKEY structure");
1546 * Exporting private key into file
1548 if ((ret = write_private_key(key, key_buf, key_file_path)) < 0)
1550 log_error(LOG_LEVEL_ERROR,
1551 "Writing private key into file %s failed", key_file_path);
1558 * Freeing used variables
1572 freez(key_file_path);
1578 /*********************************************************************
1580 * Function : ssl_certificate_load
1582 * Description : Loads certificate from file.
1585 * 1 : cert_path = The certificate path to load
1587 * Returns : NULL => error loading certificate,
1588 * pointer to certificate instance otherwise
1590 *********************************************************************/
1591 static X509 *ssl_certificate_load(const char *cert_path)
1594 FILE *cert_f = NULL;
1596 if (!(cert_f = fopen(cert_path, "r")))
1598 log_error(LOG_LEVEL_ERROR,
1599 "Error opening certificate file %s: %s", cert_path, strerror(errno));
1603 if (!(cert = PEM_read_X509(cert_f, NULL, NULL, NULL)))
1605 log_ssl_errors(LOG_LEVEL_ERROR,
1606 "Error reading certificate file %s", cert_path);
1609 close_file_stream(cert_f, cert_path);
1614 /*********************************************************************
1616 * Function : ssl_certificate_is_invalid
1618 * Description : Checks whether or not a certificate is valid.
1619 * Currently only checks that the certificate can be
1620 * parsed and that the "valid to" date is in the future.
1623 * 1 : cert_file = The certificate to check
1625 * Returns : 0 => The certificate is valid.
1626 * 1 => The certificate is invalid
1628 *********************************************************************/
1629 static int ssl_certificate_is_invalid(const char *cert_file)
1635 if (!(cert = ssl_certificate_load(cert_file)))
1640 ret = X509_cmp_current_time(X509_get_notAfter(cert));
1643 log_ssl_errors(LOG_LEVEL_ERROR,
1644 "Error checking certificate %s validity", cert_file);
1650 return ret == -1 ? 1 : 0;
1654 /*********************************************************************
1656 * Function : set_x509_ext
1658 * Description : Sets the X509V3 extension data
1661 * 1 : cert = The certificate to modify
1662 * 2 : issuer = Issuer certificate
1663 * 3 : nid = OpenSSL NID
1664 * 4 : value = extension value
1666 * Returns : 0 => Error while setting extension data
1669 *********************************************************************/
1670 static int set_x509_ext(X509 *cert, X509 *issuer, int nid, char *value)
1672 X509_EXTENSION *ext = NULL;
1676 X509V3_set_ctx(&ctx, issuer, cert, NULL, NULL, 0);
1677 ext = X509V3_EXT_conf_nid(NULL, &ctx, nid, value);
1680 log_ssl_errors(LOG_LEVEL_ERROR, "X509V3_EXT_conf_nid failure");
1684 if (!X509_add_ext(cert, ext, -1))
1686 log_ssl_errors(LOG_LEVEL_ERROR, "X509_add_ext failure");
1694 X509_EXTENSION_free(ext);
1700 /*********************************************************************
1702 * Function : set_subject_alternative_name
1704 * Description : Sets the Subject Alternative Name extension to a cert
1707 * 1 : cert = The certificate to modify
1708 * 2 : issuer = Issuer certificate
1709 * 3 : hostname = The hostname to add
1711 * Returns : 0 => Error while creating certificate.
1714 *********************************************************************/
1715 static int set_subject_alternative_name(X509 *cert, X509 *issuer, const char *hostname)
1717 size_t altname_len = strlen(hostname) + sizeof(CERTIFICATE_ALT_NAME_PREFIX);
1718 char alt_name_buf[altname_len];
1720 snprintf(alt_name_buf, sizeof(alt_name_buf),
1721 CERTIFICATE_ALT_NAME_PREFIX"%s", hostname);
1722 return set_x509_ext(cert, issuer, NID_subject_alt_name, alt_name_buf);
1726 /*********************************************************************
1728 * Function : generate_host_certificate
1730 * Description : Creates certificate file in presetted directory.
1731 * If certificate already exists, no other certificate
1732 * will be created. Subject of certificate is named
1733 * by csp->http->host from parameter. This function also
1734 * triggers generating of private key for new certificate.
1737 * 1 : csp = Current client state (buffers, headers, etc...)
1739 * Returns : -1 => Error while creating certificate.
1740 * 0 => Certificate already exists.
1741 * 1 => Certificate created
1743 *********************************************************************/
1744 static int generate_host_certificate(struct client_state *csp)
1746 char *key_buf = NULL; /* Buffer for created key */
1747 X509 *issuer_cert = NULL;
1750 EVP_PKEY *loaded_subject_key = NULL;
1751 EVP_PKEY *loaded_issuer_key = NULL;
1752 X509_NAME *issuer_name;
1753 X509_NAME *subject_name = NULL;
1754 ASN1_TIME *asn_time = NULL;
1755 ASN1_INTEGER *serial = NULL;
1756 BIGNUM *serial_num = NULL;
1759 cert_options cert_opt;
1760 char cert_valid_from[VALID_DATETIME_BUFLEN];
1761 char cert_valid_to[VALID_DATETIME_BUFLEN];
1762 const char *common_name;
1763 enum { CERT_PARAM_COMMON_NAME_MAX = 64 };
1765 /* Paths to keys and certificates needed to create certificate */
1766 cert_opt.issuer_key = NULL;
1767 cert_opt.subject_key = NULL;
1768 cert_opt.issuer_crt = NULL;
1770 cert_opt.output_file = make_certs_path(csp->config->certificate_directory,
1771 (const char *)csp->http->hash_of_host_hex, CERT_FILE_TYPE);
1772 if (cert_opt.output_file == NULL)
1777 cert_opt.subject_key = make_certs_path(csp->config->certificate_directory,
1778 (const char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
1779 if (cert_opt.subject_key == NULL)
1781 freez(cert_opt.output_file);
1785 if (enforce_sane_certificate_state(cert_opt.output_file,
1786 cert_opt.subject_key))
1788 freez(cert_opt.output_file);
1789 freez(cert_opt.subject_key);
1794 if (file_exists(cert_opt.output_file) == 1)
1796 /* The file exists, but is it valid? */
1797 if (ssl_certificate_is_invalid(cert_opt.output_file))
1799 log_error(LOG_LEVEL_CONNECT,
1800 "Certificate %s is no longer valid. Removing it.",
1801 cert_opt.output_file);
1802 if (unlink(cert_opt.output_file))
1804 log_error(LOG_LEVEL_ERROR, "Failed to unlink %s: %E",
1805 cert_opt.output_file);
1807 freez(cert_opt.output_file);
1808 freez(cert_opt.subject_key);
1812 if (unlink(cert_opt.subject_key))
1814 log_error(LOG_LEVEL_ERROR, "Failed to unlink %s: %E",
1815 cert_opt.subject_key);
1817 freez(cert_opt.output_file);
1818 freez(cert_opt.subject_key);
1825 freez(cert_opt.output_file);
1826 freez(cert_opt.subject_key);
1833 * Create key for requested host
1835 int subject_key_len = generate_key(csp, &key_buf);
1836 if (subject_key_len < 0)
1838 freez(cert_opt.output_file);
1839 freez(cert_opt.subject_key);
1840 log_error(LOG_LEVEL_ERROR, "Key generating failed");
1845 * Converting unsigned long serial number to char * serial number.
1846 * We must compute length of serial number in string + terminating null.
1848 unsigned long certificate_serial = get_certificate_serial(csp);
1849 unsigned long certificate_serial_time = (unsigned long)time(NULL);
1850 int serial_num_size = snprintf(NULL, 0, "%lu%lu",
1851 certificate_serial_time, certificate_serial) + 1;
1852 if (serial_num_size <= 0)
1854 serial_num_size = 1;
1857 char serial_num_text[serial_num_size]; /* Buffer for serial number */
1858 ret = snprintf(serial_num_text, (size_t)serial_num_size, "%lu%lu",
1859 certificate_serial_time, certificate_serial);
1860 if (ret < 0 || ret >= serial_num_size)
1862 log_error(LOG_LEVEL_ERROR,
1863 "Converting certificate serial number into string failed");
1869 * Preparing parameters for certificate
1871 subject_name = X509_NAME_new();
1874 log_ssl_errors(LOG_LEVEL_ERROR, "X509 memory allocation failure");
1880 * Make sure OpenSSL doesn't reject the common name due to its length.
1881 * The clients should only care about the Subject Alternative Name anyway
1882 * and we always use the real host name for that.
1884 common_name = (strlen(csp->http->host) > CERT_PARAM_COMMON_NAME_MAX) ?
1885 CGI_SITE_2_HOST : csp->http->host;
1886 if (!X509_NAME_add_entry_by_txt(subject_name, CERT_PARAM_COMMON_NAME_FCODE,
1887 MBSTRING_ASC, (void *)common_name, -1, -1, 0))
1889 log_ssl_errors(LOG_LEVEL_ERROR,
1890 "X509 subject name (code: %s, val: %s) error",
1891 CERT_PARAM_COMMON_NAME_FCODE, csp->http->host);
1895 if (!X509_NAME_add_entry_by_txt(subject_name, CERT_PARAM_ORGANIZATION_FCODE,
1896 MBSTRING_ASC, (void *)common_name, -1, -1, 0))
1898 log_ssl_errors(LOG_LEVEL_ERROR,
1899 "X509 subject name (code: %s, val: %s) error",
1900 CERT_PARAM_ORGANIZATION_FCODE, csp->http->host);
1904 if (!X509_NAME_add_entry_by_txt(subject_name, CERT_PARAM_ORG_UNIT_FCODE,
1905 MBSTRING_ASC, (void *)common_name, -1, -1, 0))
1907 log_ssl_errors(LOG_LEVEL_ERROR,
1908 "X509 subject name (code: %s, val: %s) error",
1909 CERT_PARAM_ORG_UNIT_FCODE, csp->http->host);
1913 if (!X509_NAME_add_entry_by_txt(subject_name, CERT_PARAM_COUNTRY_FCODE,
1914 MBSTRING_ASC, (void *)CERT_PARAM_COUNTRY_CODE, -1, -1, 0))
1916 log_ssl_errors(LOG_LEVEL_ERROR,
1917 "X509 subject name (code: %s, val: %s) error",
1918 CERT_PARAM_COUNTRY_FCODE, CERT_PARAM_COUNTRY_CODE);
1923 cert_opt.issuer_crt = csp->config->ca_cert_file;
1924 cert_opt.issuer_key = csp->config->ca_key_file;
1926 if (get_certificate_valid_from_date(cert_valid_from,
1927 sizeof(cert_valid_from), VALID_DATETIME_FMT)
1928 || get_certificate_valid_to_date(cert_valid_to,
1929 sizeof(cert_valid_to), VALID_DATETIME_FMT))
1931 log_error(LOG_LEVEL_ERROR, "Generating one of the validity dates failed");
1936 cert_opt.subject_pwd = CERT_SUBJECT_PASSWORD;
1937 cert_opt.issuer_pwd = csp->config->ca_password;
1938 cert_opt.not_before = cert_valid_from;
1939 cert_opt.not_after = cert_valid_to;
1940 cert_opt.serial = serial_num_text;
1941 cert_opt.max_pathlen = -1;
1944 * Test if the private key was already created.
1945 * XXX: Can this still happen?
1947 if (subject_key_len == 0)
1949 log_error(LOG_LEVEL_ERROR, "Subject key was already created");
1955 * Parse serial to MPI
1957 serial_num = BN_new();
1960 log_error(LOG_LEVEL_ERROR, "generate_host_certificate: memory error");
1964 if (!BN_dec2bn(&serial_num, cert_opt.serial))
1966 log_ssl_errors(LOG_LEVEL_ERROR, "Failed to parse serial %s", cert_opt.serial);
1971 if (!(serial = BN_to_ASN1_INTEGER(serial_num, NULL)))
1973 log_ssl_errors(LOG_LEVEL_ERROR, "Failed to generate serial ASN1 representation");
1979 * Loading certificates
1981 if (!(issuer_cert = ssl_certificate_load(cert_opt.issuer_crt)))
1983 log_error(LOG_LEVEL_ERROR, "Loading issuer certificate %s failed",
1984 cert_opt.issuer_crt);
1989 issuer_name = X509_get_subject_name(issuer_cert);
1992 * Loading keys from file or from buffer
1994 if (key_buf != NULL && subject_key_len > 0)
1996 pk_bio = BIO_new_mem_buf(key_buf, subject_key_len);
1998 else if (!(pk_bio = BIO_new_file(cert_opt.subject_key, "r")))
2000 log_ssl_errors(LOG_LEVEL_ERROR,
2001 "Failure opening subject key %s BIO", cert_opt.subject_key);
2006 loaded_subject_key = PEM_read_bio_PrivateKey(pk_bio, NULL, NULL,
2007 (void *)cert_opt.subject_pwd);
2008 if (!loaded_subject_key)
2010 log_ssl_errors(LOG_LEVEL_ERROR, "Parsing subject key %s failed",
2011 cert_opt.subject_key);
2016 if (!BIO_free(pk_bio))
2018 log_ssl_errors(LOG_LEVEL_ERROR, "Error closing subject key BIO");
2021 if (!(pk_bio = BIO_new_file(cert_opt.issuer_key, "r")))
2023 log_ssl_errors(LOG_LEVEL_ERROR, "Failure opening issuer key %s BIO",
2024 cert_opt.issuer_key);
2029 loaded_issuer_key = PEM_read_bio_PrivateKey(pk_bio, NULL, NULL,
2030 (void *)cert_opt.issuer_pwd);
2031 if (!loaded_issuer_key)
2033 log_ssl_errors(LOG_LEVEL_ERROR, "Parsing issuer key %s failed",
2034 cert_opt.subject_key);
2042 log_ssl_errors(LOG_LEVEL_ERROR, "Certificate allocation error");
2047 if (!X509_set_version(cert, CERTIFICATE_VERSION))
2049 log_ssl_errors(LOG_LEVEL_ERROR, "X509_set_version failed");
2055 * Setting parameters of signed certificate
2057 if (!X509_set_pubkey(cert, loaded_subject_key))
2059 log_ssl_errors(LOG_LEVEL_ERROR,
2060 "Setting public key in signed certificate failed");
2065 if (!X509_set_subject_name(cert, subject_name))
2067 log_ssl_errors(LOG_LEVEL_ERROR,
2068 "Setting subject name in signed certificate failed");
2073 if (!X509_set_issuer_name(cert, issuer_name))
2075 log_ssl_errors(LOG_LEVEL_ERROR,
2076 "Setting issuer name in signed certificate failed");
2081 if (!X509_set_serialNumber(cert, serial))
2083 log_ssl_errors(LOG_LEVEL_ERROR,
2084 "Setting serial number in signed certificate failed");
2089 asn_time = ASN1_TIME_new();
2092 log_ssl_errors(LOG_LEVEL_ERROR, "ASN1 time memory allocation failure");
2097 if (!ASN1_TIME_set_string(asn_time, cert_opt.not_after))
2099 log_ssl_errors(LOG_LEVEL_ERROR, "ASN1 time [%s] encode error", cert_opt.not_after);
2104 if (!X509_set1_notAfter(cert, asn_time))
2106 log_ssl_errors(LOG_LEVEL_ERROR,
2107 "Setting valid not after in signed certificate failed");
2112 if (!ASN1_TIME_set_string(asn_time, cert_opt.not_before))
2114 log_ssl_errors(LOG_LEVEL_ERROR, "ASN1 time encode error");
2119 if (!X509_set1_notBefore(cert, asn_time))
2121 log_ssl_errors(LOG_LEVEL_ERROR,
2122 "Setting valid not before in signed certificate failed");
2127 if (!set_x509_ext(cert, issuer_cert, NID_basic_constraints, CERTIFICATE_BASIC_CONSTRAINTS))
2129 log_ssl_errors(LOG_LEVEL_ERROR, "Setting the basicConstraints extension "
2130 "in signed certificate failed");
2135 if (!set_x509_ext(cert, issuer_cert, NID_subject_key_identifier, CERTIFICATE_SUBJECT_KEY))
2137 log_ssl_errors(LOG_LEVEL_ERROR,
2138 "Setting the Subject Key Identifier extension failed");
2143 if (!set_x509_ext(cert, issuer_cert, NID_authority_key_identifier, CERTIFICATE_AUTHORITY_KEY))
2145 log_ssl_errors(LOG_LEVEL_ERROR,
2146 "Setting the Authority Key Identifier extension failed");
2151 if (!host_is_ip_address(csp->http->host) &&
2152 !set_subject_alternative_name(cert, issuer_cert, csp->http->host))
2154 log_ssl_errors(LOG_LEVEL_ERROR,
2155 "Setting the Subject Alt Name extension failed");
2160 if (!X509_sign(cert, loaded_issuer_key, EVP_sha256()))
2162 log_ssl_errors(LOG_LEVEL_ERROR, "Signing certificate failed");
2168 * Writing certificate into file
2170 if (write_certificate(cert, cert_opt.output_file) < 0)
2172 log_error(LOG_LEVEL_ERROR, "Writing certificate into file failed");
2181 * Freeing used structures
2185 X509_free(issuer_cert);
2191 if (pk_bio && !BIO_free(pk_bio))
2193 log_ssl_errors(LOG_LEVEL_ERROR, "Error closing pk BIO");
2195 if (loaded_subject_key)
2197 EVP_PKEY_free(loaded_subject_key);
2199 if (loaded_issuer_key)
2201 EVP_PKEY_free(loaded_issuer_key);
2205 X509_NAME_free(subject_name);
2209 ASN1_TIME_free(asn_time);
2213 BN_free(serial_num);
2217 ASN1_INTEGER_free(serial);
2219 freez(cert_opt.subject_key);
2220 freez(cert_opt.output_file);
2227 /*********************************************************************
2229 * Function : ssl_crt_verify_info
2231 * Description : Returns an informational string about the verification
2232 * status of a certificate.
2235 * 1 : buf = Buffer to write to
2236 * 2 : size = Maximum size of buffer
2237 * 3 : csp = client state
2241 *********************************************************************/
2242 extern void ssl_crt_verify_info(char *buf, size_t size, struct client_state *csp)
2244 strncpy(buf, X509_verify_cert_error_string(csp->server_cert_verification_result), size);
2249 #ifdef FEATURE_GRACEFUL_TERMINATION
2250 /*********************************************************************
2252 * Function : ssl_release
2254 * Description : Release all SSL resources
2260 *********************************************************************/
2261 extern void ssl_release(void)
2263 if (ssl_inited == 1)
2265 #if OPENSSL_VERSION_NUMBER >= 0x1000200fL
2266 #ifndef LIBRESSL_VERSION_NUMBER
2267 #ifndef OPENSSL_NO_COMP
2268 SSL_COMP_free_compression_methods();
2272 CONF_modules_free();
2273 CONF_modules_unload(1);
2274 #ifndef OPENSSL_NO_COMP
2275 COMP_zlib_cleanup();
2281 CRYPTO_cleanup_all_ex_data();
2284 #endif /* def FEATURE_GRACEFUL_TERMINATION */