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;
156 int pos = 0; /* Position of unsent part in buffer */
165 int send_len = (int)len - pos;
167 log_error(LOG_LEVEL_WRITING, "TLS: %N", send_len, buf+pos);
170 * Sending one part of the buffer
172 while ((ret = BIO_write(bio,
173 (const unsigned char *)(buf + pos),
176 if (!BIO_should_retry(bio))
178 log_ssl_errors(LOG_LEVEL_ERROR,
179 "Sending data over TLS/SSL failed");
183 /* Adding count of sent bytes to position in buffer */
191 /*********************************************************************
193 * Function : ssl_recv_data
195 * Description : Receives data from given SSL context and puts
199 * 1 : ssl_attr = SSL context to receive data from
200 * 2 : buf = Pointer to buffer where data will be written
201 * 3 : max_length = Maximum number of bytes to read
203 * Returns : Number of bytes read, 0 for EOF, or -1
206 *********************************************************************/
207 extern int ssl_recv_data(struct ssl_attr *ssl_attr, unsigned char *buf, size_t max_length)
209 BIO *bio = ssl_attr->openssl_attr.bio;
214 memset(buf, 0, max_length);
217 * Receiving data from SSL context into buffer
221 ret = BIO_read(bio, buf, (int)max_length);
222 } while (ret <= 0 && BIO_should_retry(bio));
226 log_ssl_errors(LOG_LEVEL_ERROR,
227 "Receiving data on socket %d over TLS/SSL failed", fd);
232 if (BIO_get_ssl(bio, &ssl) == 1)
234 fd = SSL_get_fd(ssl);
237 log_error(LOG_LEVEL_RECEIVED, "TLS from socket %d: %N",
244 /*********************************************************************
246 * Function : ssl_store_cert
248 * Description : This function is called once for each certificate in the
249 * server's certificate trusted chain and prepares
250 * information about the certificate. The information can
251 * be used to inform the user about invalid certificates.
254 * 1 : csp = Current client state (buffers, headers, etc...)
255 * 2 : crt = certificate from trusted chain
257 * Returns : 0 on success and negative value on error
259 *********************************************************************/
260 static int ssl_store_cert(struct client_state *csp, X509* crt)
263 struct certs_chain *last = &(csp->server_certs_chain);
265 BIO *bio = BIO_new(BIO_s_mem());
266 EVP_PKEY *pkey = NULL;
267 char *bio_mem_data = 0;
270 const ASN1_INTEGER *bs;
271 #if OPENSSL_VERSION_NUMBER > 0x10100000L
272 const X509_ALGOR *tsig_alg;
278 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_new_mem_buf() failed");
283 * Searching for last item in certificates linked list
285 while (last->next != NULL)
291 * Preparing next item in linked list for next certificate
293 last->next = malloc_or_die(sizeof(struct certs_chain));
294 last->next->next = NULL;
295 memset(last->next->info_buf, 0, sizeof(last->next->info_buf));
296 memset(last->next->file_buf, 0, sizeof(last->next->file_buf));
299 * Saving certificate file into buffer
301 if (!PEM_write_bio_X509(bio, crt))
303 log_ssl_errors(LOG_LEVEL_ERROR, "PEM_write_X509() failed");
308 len = BIO_get_mem_data(bio, &bio_mem_data);
310 if (len > (sizeof(last->file_buf) - 1))
312 log_error(LOG_LEVEL_ERROR,
313 "X509 PEM cert len %ld is larger than buffer len %lu",
314 len, sizeof(last->file_buf) - 1);
315 len = sizeof(last->file_buf) - 1;
318 strncpy(last->file_buf, bio_mem_data, (size_t)len);
320 bio = BIO_new(BIO_s_mem());
323 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_new_mem_buf() failed");
329 * Saving certificate information into buffer
331 l = X509_get_version(crt);
332 if (l >= 0 && l <= 2)
334 if (BIO_printf(bio, "cert. version : %ld\n", l + 1) <= 0)
336 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for version failed");
343 if (BIO_printf(bio, "cert. version : Unknown (%ld)\n", l) <= 0)
345 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for version failed");
351 if (BIO_puts(bio, "serial number : ") <= 0)
353 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_puts() for serial failed");
357 bs = X509_get0_serialNumber(crt);
358 if (bs->length <= (int)sizeof(long))
361 l = ASN1_INTEGER_get(bs);
372 if (bs->type == V_ASN1_NEG_INTEGER)
374 ul = 0 - (unsigned long)l;
379 ul = (unsigned long)l;
382 if (BIO_printf(bio, " %s%lu (%s0x%lx)\n", neg, ul, neg, ul) <= 0)
384 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for serial failed");
391 if (bs->type == V_ASN1_NEG_INTEGER)
393 if (BIO_puts(bio, " (Negative)") < 0)
395 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_puts() for serial failed");
400 for (int i = 0; i < bs->length; i++)
402 if (BIO_printf(bio, "%02x%c", bs->data[i],
403 ((i + 1 == bs->length) ? '\n' : ':')) <= 0)
405 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for serial failed");
412 if (BIO_puts(bio, "issuer name : ") <= 0)
414 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_puts() for issuer failed");
418 if (X509_NAME_print_ex(bio, X509_get_issuer_name(crt), 0, 0) < 0)
420 log_ssl_errors(LOG_LEVEL_ERROR, "X509_NAME_print_ex() for issuer failed");
425 if (BIO_puts(bio, "\nsubject name : ") <= 0)
427 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_puts() for subject failed");
431 if (X509_NAME_print_ex(bio, X509_get_subject_name(crt), 0, 0) < 0) {
432 log_ssl_errors(LOG_LEVEL_ERROR, "X509_NAME_print_ex() for subject failed");
437 if (BIO_puts(bio, "\nissued on : ") <= 0)
439 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_puts() for issued on failed");
443 if (!ASN1_TIME_print(bio, X509_get0_notBefore(crt)))
445 log_ssl_errors(LOG_LEVEL_ERROR, "ASN1_TIME_print() for issued on failed");
450 if (BIO_puts(bio, "\nexpires on : ") <= 0)
452 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_puts() for expires on failed");
456 if (!ASN1_TIME_print(bio, X509_get0_notAfter(crt)))
458 log_ssl_errors(LOG_LEVEL_ERROR, "ASN1_TIME_print() for expires on failed");
463 #if OPENSSL_VERSION_NUMBER > 0x10100000L
464 if (BIO_puts(bio, "\nsigned using : ") <= 0)
466 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_puts() for signed using failed");
470 tsig_alg = X509_get0_tbs_sigalg(crt);
471 if (!i2a_ASN1_OBJECT(bio, tsig_alg->algorithm))
473 log_ssl_errors(LOG_LEVEL_ERROR, "i2a_ASN1_OBJECT() for signed using failed");
478 pkey = X509_get_pubkey(crt);
481 log_ssl_errors(LOG_LEVEL_ERROR, "X509_get_pubkey() failed");
486 switch (EVP_PKEY_base_id(pkey))
489 ret = BIO_printf(bio, "\n%-" BC "s: %d bits", "RSA key size", EVP_PKEY_bits(pkey));
492 ret = BIO_printf(bio, "\n%-" BC "s: %d bits", "DSA key size", EVP_PKEY_bits(pkey));
495 ret = BIO_printf(bio, "\n%-" BC "s: %d bits", "non-RSA/DSA key size", EVP_PKEY_bits(pkey));
500 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for key size failed");
505 loc = X509_get_ext_by_NID(crt, NID_basic_constraints, -1);
508 X509_EXTENSION *ex = X509_get_ext(crt, loc);
509 if (BIO_puts(bio, "\nbasic constraints : ") <= 0)
511 log_ssl_errors(LOG_LEVEL_ERROR,
512 "BIO_printf() for basic constraints failed");
516 if (!X509V3_EXT_print(bio, ex, 0, 0))
518 if (!ASN1_STRING_print_ex(bio, X509_EXTENSION_get_data(ex), ASN1_STRFLGS_RFC2253))
520 log_ssl_errors(LOG_LEVEL_ERROR,
521 "ASN1_STRING_print_ex() for basic constraints failed");
528 loc = X509_get_ext_by_NID(crt, NID_subject_alt_name, -1);
531 X509_EXTENSION *ex = X509_get_ext(crt, loc);
532 if (BIO_puts(bio, "\nsubject alt name : ") <= 0)
534 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for alt name failed");
538 if (!X509V3_EXT_print(bio, ex, 0, 0))
540 if (!ASN1_STRING_print_ex(bio, X509_EXTENSION_get_data(ex),
541 ASN1_STRFLGS_RFC2253))
543 log_ssl_errors(LOG_LEVEL_ERROR,
544 "ASN1_STRING_print_ex() for alt name failed");
551 loc = X509_get_ext_by_NID(crt, NID_netscape_cert_type, -1);
554 X509_EXTENSION *ex = X509_get_ext(crt, loc);
555 if (BIO_puts(bio, "\ncert. type : ") <= 0)
557 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for cert type failed");
561 if (!X509V3_EXT_print(bio, ex, 0, 0))
563 if (!ASN1_STRING_print_ex(bio, X509_EXTENSION_get_data(ex),
564 ASN1_STRFLGS_RFC2253))
566 log_ssl_errors(LOG_LEVEL_ERROR,
567 "ASN1_STRING_print_ex() for cert type failed");
574 loc = X509_get_ext_by_NID(crt, NID_key_usage, -1);
577 X509_EXTENSION *ex = X509_get_ext(crt, loc);
578 if (BIO_puts(bio, "\nkey usage : ") <= 0)
580 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for key usage failed");
584 if (!X509V3_EXT_print(bio, ex, 0, 0))
586 if (!ASN1_STRING_print_ex(bio, X509_EXTENSION_get_data(ex),
587 ASN1_STRFLGS_RFC2253))
589 log_ssl_errors(LOG_LEVEL_ERROR,
590 "ASN1_STRING_print_ex() for key usage failed");
597 loc = X509_get_ext_by_NID(crt, NID_ext_key_usage, -1);
599 X509_EXTENSION *ex = X509_get_ext(crt, loc);
600 if (BIO_puts(bio, "\next key usage : ") <= 0)
602 log_ssl_errors(LOG_LEVEL_ERROR,
603 "BIO_printf() for ext key usage failed");
607 if (!X509V3_EXT_print(bio, ex, 0, 0))
609 if (!ASN1_STRING_print_ex(bio, X509_EXTENSION_get_data(ex),
610 ASN1_STRFLGS_RFC2253))
612 log_ssl_errors(LOG_LEVEL_ERROR,
613 "ASN1_STRING_print_ex() for ext key usage failed");
620 loc = X509_get_ext_by_NID(crt, NID_certificate_policies, -1);
623 X509_EXTENSION *ex = X509_get_ext(crt, loc);
624 if (BIO_puts(bio, "\ncertificate policies : ") <= 0)
626 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for certificate policies failed");
630 if (!X509V3_EXT_print(bio, ex, 0, 0))
632 if (!ASN1_STRING_print_ex(bio, X509_EXTENSION_get_data(ex),
633 ASN1_STRFLGS_RFC2253))
635 log_ssl_errors(LOG_LEVEL_ERROR,
636 "ASN1_STRING_print_ex() for certificate policies failed");
643 /* make valgrind happy */
644 static const char zero = 0;
645 BIO_write(bio, &zero, 1);
647 len = BIO_get_mem_data(bio, &bio_mem_data);
648 encoded_text = html_encode(bio_mem_data);
649 if (encoded_text == NULL)
651 log_error(LOG_LEVEL_ERROR,
652 "Failed to HTML-encode the certificate information");
657 strlcpy(last->info_buf, encoded_text, sizeof(last->info_buf));
674 /*********************************************************************
676 * Function : host_to_hash
678 * Description : Creates MD5 hash from host name. Host name is loaded
679 * from structure csp and saved again into it.
682 * 1 : csp = Current client state (buffers, headers, etc...)
684 * Returns : 1 => Error while creating hash
685 * 0 => Hash created successfully
687 *********************************************************************/
688 static int host_to_hash(struct client_state *csp)
692 memset(csp->http->hash_of_host, 0, sizeof(csp->http->hash_of_host));
693 MD5((unsigned char *)csp->http->host, strlen(csp->http->host),
694 csp->http->hash_of_host);
696 /* Converting hash into string with hex */
700 if ((ret = sprintf((char *)csp->http->hash_of_host_hex + 2 * i, "%02x",
701 csp->http->hash_of_host[i])) < 0)
703 log_error(LOG_LEVEL_ERROR, "Sprintf return value: %d", ret);
712 /*********************************************************************
714 * Function : create_client_ssl_connection
716 * Description : Creates TLS/SSL secured connection with client
719 * 1 : csp = Current client state (buffers, headers, etc...)
721 * Returns : 0 on success, negative value if connection wasn't created
724 *********************************************************************/
725 extern int create_client_ssl_connection(struct client_state *csp)
727 struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
728 /* Paths to certificates file and key file */
729 char *key_file = NULL;
730 char *ca_file = NULL;
731 char *cert_file = NULL;
736 * Initializing OpenSSL structures for TLS/SSL connection
741 * Preparing hash of host for creating certificates
743 ret = host_to_hash(csp);
746 log_error(LOG_LEVEL_ERROR, "Generating hash of host failed: %d", ret);
752 * Preparing paths to certificates files and key file
754 ca_file = csp->config->ca_cert_file;
755 cert_file = make_certs_path(csp->config->certificate_directory,
756 (const char *)csp->http->hash_of_host_hex, CERT_FILE_TYPE);
757 key_file = make_certs_path(csp->config->certificate_directory,
758 (const char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
760 if (cert_file == NULL || key_file == NULL)
767 * Generating certificate for requested host. Mutex to prevent
768 * certificate and key inconsistence must be locked.
770 privoxy_mutex_lock(&certificate_mutex);
772 ret = generate_webpage_certificate(csp);
775 log_error(LOG_LEVEL_ERROR,
776 "Generate_webpage_certificate failed: %d", ret);
777 privoxy_mutex_unlock(&certificate_mutex);
781 privoxy_mutex_unlock(&certificate_mutex);
783 if (!(ssl_attr->openssl_attr.ctx = SSL_CTX_new(SSLv23_server_method())))
785 log_ssl_errors(LOG_LEVEL_ERROR, "Unable to create SSL context");
790 /* Set the key and cert */
791 if (SSL_CTX_use_certificate_file(ssl_attr->openssl_attr.ctx,
792 cert_file, SSL_FILETYPE_PEM) != 1)
794 log_ssl_errors(LOG_LEVEL_ERROR,
795 "Loading webpage certificate %s failed", cert_file);
800 if (SSL_CTX_use_PrivateKey_file(ssl_attr->openssl_attr.ctx,
801 key_file, SSL_FILETYPE_PEM) != 1)
803 log_ssl_errors(LOG_LEVEL_ERROR,
804 "Loading webpage certificate private key %s failed", key_file);
809 SSL_CTX_set_options(ssl_attr->openssl_attr.ctx, SSL_OP_NO_SSLv3);
811 if (!(ssl_attr->openssl_attr.bio = BIO_new_ssl(ssl_attr->openssl_attr.ctx, 0)))
813 log_ssl_errors(LOG_LEVEL_ERROR, "Unable to create BIO structure");
818 if (BIO_get_ssl(ssl_attr->openssl_attr.bio, &ssl) != 1)
820 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_get_ssl failed");
825 if (!SSL_set_fd(ssl, csp->cfd))
827 log_ssl_errors(LOG_LEVEL_ERROR, "SSL_set_fd failed");
833 * Handshake with client
835 log_error(LOG_LEVEL_CONNECT,
836 "Performing the TLS/SSL handshake with client. Hash of host: %s",
837 csp->http->hash_of_host_hex);
838 if (BIO_do_handshake(ssl_attr->openssl_attr.bio) != 1)
840 log_ssl_errors(LOG_LEVEL_ERROR,
841 "The TLS/SSL handshake with the client failed");
846 log_error(LOG_LEVEL_CONNECT, "Client successfully connected over TLS/SSL");
847 csp->ssl_with_client_is_opened = 1;
852 * Freeing allocated paths to files
857 /* Freeing structures if connection wasn't created successfully */
860 free_client_ssl_structures(csp);
866 /*********************************************************************
868 * Function : close_client_ssl_connection
870 * Description : Closes TLS/SSL connection with client. This function
871 * checks if this connection is already created.
874 * 1 : csp = Current client state (buffers, headers, etc...)
878 *********************************************************************/
879 extern void close_client_ssl_connection(struct client_state *csp)
881 struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
884 if (csp->ssl_with_client_is_opened == 0)
890 * Notifying the peer that the connection is being closed.
892 BIO_ssl_shutdown(ssl_attr->openssl_attr.bio);
893 if (BIO_get_ssl(ssl_attr->openssl_attr.bio, &ssl) != 1)
895 log_ssl_errors(LOG_LEVEL_ERROR,
896 "BIO_get_ssl() failed in close_client_ssl_connection()");
901 * Pretend we received a shutdown alert so
902 * the BIO_free_all() call later on returns
905 SSL_set_shutdown(ssl, SSL_RECEIVED_SHUTDOWN);
907 free_client_ssl_structures(csp);
908 csp->ssl_with_client_is_opened = 0;
912 /*********************************************************************
914 * Function : free_client_ssl_structures
916 * Description : Frees structures used for SSL communication with
920 * 1 : csp = Current client state (buffers, headers, etc...)
924 *********************************************************************/
925 static void free_client_ssl_structures(struct client_state *csp)
927 struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
929 if (ssl_attr->openssl_attr.bio)
931 BIO_free_all(ssl_attr->openssl_attr.bio);
933 if (ssl_attr->openssl_attr.ctx)
935 SSL_CTX_free(ssl_attr->openssl_attr.ctx);
940 /*********************************************************************
942 * Function : close_server_ssl_connection
944 * Description : Closes TLS/SSL connection with server. This function
945 * checks if this connection is already opened.
948 * 1 : csp = Current client state (buffers, headers, etc...)
952 *********************************************************************/
953 extern void close_server_ssl_connection(struct client_state *csp)
955 struct ssl_attr *ssl_attr = &csp->ssl_server_attr;
958 if (csp->ssl_with_server_is_opened == 0)
964 * Notifying the peer that the connection is being closed.
966 BIO_ssl_shutdown(ssl_attr->openssl_attr.bio);
967 if (BIO_get_ssl(ssl_attr->openssl_attr.bio, &ssl) != 1)
969 log_ssl_errors(LOG_LEVEL_ERROR,
970 "BIO_get_ssl() failed in close_server_ssl_connection()");
975 * Pretend we received a shutdown alert so
976 * the BIO_free_all() call later on returns
979 SSL_set_shutdown(ssl, SSL_RECEIVED_SHUTDOWN);
981 free_server_ssl_structures(csp);
982 csp->ssl_with_server_is_opened = 0;
986 /*********************************************************************
988 * Function : create_server_ssl_connection
990 * Description : Creates TLS/SSL secured connection with server.
993 * 1 : csp = Current client state (buffers, headers, etc...)
995 * Returns : 0 on success, negative value if connection wasn't created
998 *********************************************************************/
999 extern int create_server_ssl_connection(struct client_state *csp)
1001 openssl_connection_attr *ssl_attrs = &csp->ssl_server_attr.openssl_attr;
1003 char *trusted_cas_file = NULL;
1004 STACK_OF(X509) *chain;
1007 csp->server_cert_verification_result = SSL_CERT_NOT_VERIFIED;
1008 csp->server_certs_chain.next = NULL;
1010 /* Setting path to file with trusted CAs */
1011 trusted_cas_file = csp->config->trusted_cas_file;
1013 ssl_attrs->ctx = SSL_CTX_new(SSLv23_method());
1014 if (!ssl_attrs->ctx)
1016 log_ssl_errors(LOG_LEVEL_ERROR, "SSL context creation failed");
1022 * Loading file with trusted CAs
1024 if (!SSL_CTX_load_verify_locations(ssl_attrs->ctx, trusted_cas_file, NULL))
1026 log_ssl_errors(LOG_LEVEL_ERROR, "Loading trusted CAs file %s failed",
1032 SSL_CTX_set_verify(ssl_attrs->ctx, SSL_VERIFY_NONE, NULL);
1033 SSL_CTX_set_options(ssl_attrs->ctx, SSL_OP_NO_SSLv3);
1035 if (!(ssl_attrs->bio = BIO_new_ssl(ssl_attrs->ctx, 1)))
1037 log_ssl_errors(LOG_LEVEL_ERROR, "Unable to create BIO structure");
1042 if (BIO_get_ssl(ssl_attrs->bio, &ssl) != 1)
1044 log_ssl_errors(LOG_LEVEL_ERROR, "BIO_get_ssl failed");
1049 if (!SSL_set_fd(ssl, csp->server_connection.sfd))
1051 log_ssl_errors(LOG_LEVEL_ERROR, "SSL_set_fd failed");
1057 * Set the hostname to check against the received server certificate
1059 #if OPENSSL_VERSION_NUMBER > 0x10100000L
1060 if (!SSL_set1_host(ssl, csp->http->host))
1062 log_ssl_errors(LOG_LEVEL_ERROR, "SSL_set1_host failed");
1067 if (host_is_ip_address(csp->http->host))
1069 if (X509_VERIFY_PARAM_set1_ip_asc(ssl->param, csp->http->host) != 1)
1071 log_ssl_errors(LOG_LEVEL_ERROR,
1072 "X509_VERIFY_PARAM_set1_ip_asc() failed");
1079 if (X509_VERIFY_PARAM_set1_host(ssl->param, csp->http->host, 0) != 1)
1081 log_ssl_errors(LOG_LEVEL_ERROR,
1082 "X509_VERIFY_PARAM_set1_host() failed");
1089 if (!SSL_set_tlsext_host_name(ssl, csp->http->host))
1091 log_ssl_errors(LOG_LEVEL_ERROR, "SSL_set_tlsext_host_name failed");
1097 * Handshake with server
1099 log_error(LOG_LEVEL_CONNECT,
1100 "Performing the TLS/SSL handshake with the server");
1102 if (BIO_do_handshake(ssl_attrs->bio) != 1)
1104 log_ssl_errors(LOG_LEVEL_ERROR,
1105 "The TLS/SSL handshake with the server failed");
1110 chain = SSL_get_peer_cert_chain(ssl);
1113 for (int i = 0; i < sk_X509_num(chain); i++)
1115 if (ssl_store_cert(csp, sk_X509_value(chain, i)) != 0)
1117 log_error(LOG_LEVEL_ERROR, "ssl_store_cert failed");
1124 if (!csp->dont_verify_certificate)
1126 long verify_result = SSL_get_verify_result(ssl);
1127 if (verify_result == X509_V_OK)
1130 csp->server_cert_verification_result = SSL_CERT_VALID;
1134 csp->server_cert_verification_result = verify_result;
1135 log_error(LOG_LEVEL_ERROR,
1136 "X509 certificate verification for %s failed: %s",
1137 csp->http->hostport, X509_verify_cert_error_string(verify_result));
1143 log_error(LOG_LEVEL_CONNECT, "Server successfully connected over TLS/SSL");
1146 * Server certificate chain is valid, so we can clean
1147 * chain, because we will not send it to client.
1149 free_certificate_chain(csp);
1151 csp->ssl_with_server_is_opened = 1;
1153 /* Freeing structures if connection wasn't created successfully */
1156 free_server_ssl_structures(csp);
1163 /*********************************************************************
1165 * Function : free_server_ssl_structures
1167 * Description : Frees structures used for SSL communication with server
1170 * 1 : csp = Current client state (buffers, headers, etc...)
1174 *********************************************************************/
1175 static void free_server_ssl_structures(struct client_state *csp)
1177 struct ssl_attr *ssl_attr = &csp->ssl_server_attr;
1179 if (ssl_attr->openssl_attr.bio)
1181 BIO_free_all(ssl_attr->openssl_attr.bio);
1183 if (ssl_attr->openssl_attr.ctx)
1185 SSL_CTX_free(ssl_attr->openssl_attr.ctx);
1190 /*********************************************************************
1192 * Function : log_ssl_errors
1194 * Description : Log SSL errors
1197 * 1 : debuglevel = Debug level
1198 * 2 : desc = Error description
1202 *********************************************************************/
1203 static void log_ssl_errors(int debuglevel, const char* fmt, ...)
1205 unsigned long err_code;
1206 char prefix[ERROR_BUF_SIZE];
1208 va_start(args, fmt);
1209 vsnprintf(prefix, sizeof(prefix), fmt, args);
1212 while ((err_code = ERR_get_error()))
1214 char err_buf[ERROR_BUF_SIZE];
1216 ERR_error_string_n(err_code, err_buf, sizeof(err_buf));
1217 log_error(debuglevel, "%s: %s", prefix, err_buf);
1221 * In case if called by mistake and there were
1222 * no TLS/SSL errors let's report it to the log.
1226 log_error(debuglevel, "%s: no TLS/SSL errors detected", prefix);
1231 /*********************************************************************
1233 * Function : ssl_base64_encode
1235 * Description : Encode a buffer into base64 format.
1238 * 1 : dst = Destination buffer
1239 * 2 : dlen = Destination buffer length
1240 * 3 : olen = Number of bytes written
1241 * 4 : src = Source buffer
1242 * 5 : slen = Amount of data to be encoded
1244 * Returns : 0 on success, error code othervise
1246 *********************************************************************/
1247 extern int ssl_base64_encode(unsigned char *dst, size_t dlen, size_t *olen,
1248 const unsigned char *src, size_t slen)
1250 *olen = 4 * ((slen/3) + ((slen%3) ? 1 : 0)) + 1;
1255 *olen = (size_t)EVP_EncodeBlock(dst, src, (int)slen) + 1;
1260 /*********************************************************************
1262 * Function : close_file_stream
1264 * Description : Close file stream, report error on close error
1267 * 1 : f = file stream to close
1268 * 2 : path = path for error report
1272 *********************************************************************/
1273 static void close_file_stream(FILE *f, const char *path)
1277 log_error(LOG_LEVEL_ERROR,
1278 "Error closing file %s: %s", path, strerror(errno));
1283 /*********************************************************************
1285 * Function : write_certificate
1287 * Description : Writes certificate into file.
1290 * 1 : crt = certificate to write into file
1291 * 2 : output_file = path to save certificate file
1294 * Returns : 1 on success success or negative value
1296 *********************************************************************/
1297 static int write_certificate(X509 *crt, const char *output_file)
1303 * Saving certificate into file
1305 if ((f = fopen(output_file, "w")) == NULL)
1307 log_error(LOG_LEVEL_ERROR, "Opening file %s to save certificate failed",
1312 ret = PEM_write_X509(f, crt);
1315 log_ssl_errors(LOG_LEVEL_ERROR,
1316 "Writing certificate into file %s failed", output_file);
1320 close_file_stream(f, output_file);
1325 /*********************************************************************
1327 * Function : write_private_key
1329 * Description : Writes private key into file and copies saved
1330 * content into given pointer to string. If function
1331 * returns 0 for success, this copy must be freed by
1335 * 1 : key = key to write into file
1336 * 2 : ret_buf = pointer to string with created key file content
1337 * 3 : key_file_path = path where to save key file
1339 * Returns : Length of written private key on success or negative value
1342 *********************************************************************/
1343 static int write_private_key(EVP_PKEY *key, char **ret_buf,
1344 const char *key_file_path)
1346 size_t len = 0; /* Length of created key */
1347 FILE *f = NULL; /* File to save certificate */
1349 BIO *bio_mem = BIO_new(BIO_s_mem());
1350 char *bio_mem_data = 0;
1352 if (bio_mem == NULL)
1354 log_ssl_errors(LOG_LEVEL_ERROR, "write_private_key memory allocation failure");
1359 * Writing private key into PEM string
1361 if (!PEM_write_bio_PrivateKey(bio_mem, key, NULL, NULL, 0, NULL, NULL))
1363 log_ssl_errors(LOG_LEVEL_ERROR,
1364 "Writing private key into PEM string failed");
1369 len = (size_t)BIO_get_mem_data(bio_mem, &bio_mem_data);
1371 /* Initializing buffer for key file content */
1372 *ret_buf = zalloc_or_die(len + 1);
1373 (*ret_buf)[len] = 0;
1375 strncpy(*ret_buf, bio_mem_data, len);
1378 * Saving key into file
1380 if ((f = fopen(key_file_path, "wb")) == NULL)
1382 log_error(LOG_LEVEL_ERROR,
1383 "Opening file %s to save private key failed: %E",
1389 if (fwrite(*ret_buf, 1, len, f) != len)
1391 log_error(LOG_LEVEL_ERROR,
1392 "Writing private key into file %s failed",
1394 close_file_stream(f, key_file_path);
1399 close_file_stream(f, key_file_path);
1413 /*********************************************************************
1415 * Function : generate_key
1417 * Description : Tests if private key for host saved in csp already
1418 * exists. If this file doesn't exists, a new key is
1419 * generated and saved in a file. The generated key is also
1420 * copied into given parameter key_buf, which must be then
1421 * freed by caller. If file with key exists, key_buf
1422 * contain NULL and no private key is generated.
1425 * 1 : csp = Current client state (buffers, headers, etc...)
1426 * 2 : key_buf = buffer to save new generated key
1428 * Returns : -1 => Error while generating private key
1429 * 0 => Key already exists
1430 * >0 => Length of generated private key
1432 *********************************************************************/
1433 static int generate_key(struct client_state *csp, char **key_buf)
1436 char* key_file_path = NULL;
1437 BIGNUM *exp = BN_new();
1438 RSA *rsa = RSA_new();
1439 EVP_PKEY *key = EVP_PKEY_new();
1441 if (exp == NULL || rsa == NULL || key == NULL)
1443 log_ssl_errors(LOG_LEVEL_ERROR, "RSA key memory allocation failure");
1448 if (BN_set_word(exp, RSA_KEY_PUBLIC_EXPONENT) != 1)
1450 log_ssl_errors(LOG_LEVEL_ERROR, "Setting RSA key exponent failed");
1455 key_file_path = make_certs_path(csp->config->certificate_directory,
1456 (char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
1457 if (key_file_path == NULL)
1464 * Test if key already exists. If so, we don't have to create it again.
1466 if (file_exists(key_file_path) == 1)
1472 ret = RSA_generate_key_ex(rsa, RSA_KEYSIZE, exp, NULL);
1475 log_ssl_errors(LOG_LEVEL_ERROR, "RSA key generation failure");
1480 if (!EVP_PKEY_set1_RSA(key, rsa))
1482 log_ssl_errors(LOG_LEVEL_ERROR,
1483 "Error assigning RSA key pair to PKEY structure");
1489 * Exporting private key into file
1491 if ((ret = write_private_key(key, key_buf, key_file_path)) < 0)
1493 log_error(LOG_LEVEL_ERROR,
1494 "Writing private key into file %s failed", key_file_path);
1501 * Freeing used variables
1515 freez(key_file_path);
1521 /*********************************************************************
1523 * Function : ssl_certificate_load
1525 * Description : Loads certificate from file.
1528 * 1 : cert_path = The certificate path to load
1530 * Returns : NULL => error loading certificate,
1531 * pointer to certificate instance otherwise
1533 *********************************************************************/
1534 static X509* ssl_certificate_load(const char *cert_path)
1537 FILE *cert_f = NULL;
1539 if (!(cert_f = fopen(cert_path, "r")))
1541 log_error(LOG_LEVEL_ERROR,
1542 "Error opening certificate file %s: %s", cert_path, strerror(errno));
1546 if (!(cert = PEM_read_X509(cert_f, NULL, NULL, NULL)))
1548 log_ssl_errors(LOG_LEVEL_ERROR,
1549 "Error reading certificate file %s", cert_path);
1552 close_file_stream(cert_f, cert_path);
1557 /*********************************************************************
1559 * Function : ssl_certificate_is_invalid
1561 * Description : Checks whether or not a certificate is valid.
1562 * Currently only checks that the certificate can be
1563 * parsed and that the "valid to" date is in the future.
1566 * 1 : cert_file = The certificate to check
1568 * Returns : 0 => The certificate is valid.
1569 * 1 => The certificate is invalid
1571 *********************************************************************/
1572 static int ssl_certificate_is_invalid(const char *cert_file)
1578 if (!(cert = ssl_certificate_load(cert_file)))
1580 log_ssl_errors(LOG_LEVEL_ERROR,
1581 "Error reading certificate file %s", cert_file);
1585 ret = X509_cmp_current_time(X509_get_notAfter(cert));
1588 log_ssl_errors(LOG_LEVEL_ERROR,
1589 "Error checking certificate %s validity", cert_file);
1595 return ret == -1 ? 1 : 0;
1599 /*********************************************************************
1601 * Function : set_x509_ext
1603 * Description : Sets the X509V3 extension data
1606 * 1 : cert = The certificate to modify
1607 * 2 : issuer = Issuer certificate
1608 * 3 : nid = OpenSSL NID
1609 * 4 : value = extension value
1611 * Returns : 0 => Error while setting extensuon data
1614 *********************************************************************/
1615 static int set_x509_ext(X509 *cert, X509 *issuer, int nid, char *value)
1617 X509_EXTENSION *ext = NULL;
1621 X509V3_set_ctx(&ctx, issuer, cert, NULL, NULL, 0);
1622 ext = X509V3_EXT_conf_nid(NULL, &ctx, nid, value);
1625 log_ssl_errors(LOG_LEVEL_ERROR, "X509V3_EXT_conf_nid failure");
1629 if (!X509_add_ext(cert, ext, -1))
1631 log_ssl_errors(LOG_LEVEL_ERROR, "X509_add_ext failure");
1639 X509_EXTENSION_free(ext);
1645 /*********************************************************************
1647 * Function : set_subject_alternative_name
1649 * Description : Sets the Subject Alternative Name extension to a cert
1652 * 1 : cert = The certificate to modify
1653 * 2 : issuer = Issuer certificate
1654 * 3 : hostname = The hostname to add
1656 * Returns : 0 => Error while creating certificate.
1659 *********************************************************************/
1660 static int set_subject_alternative_name(X509 *cert, X509 *issuer, const char *hostname)
1662 size_t altname_len = strlen(hostname) + sizeof(CERTIFICATE_ALT_NAME_PREFIX);
1663 char alt_name_buf[altname_len];
1665 snprintf(alt_name_buf, sizeof(alt_name_buf),
1666 CERTIFICATE_ALT_NAME_PREFIX"%s", hostname);
1667 return set_x509_ext(cert, issuer, NID_subject_alt_name, alt_name_buf);
1671 /*********************************************************************
1673 * Function : generate_webpage_certificate
1675 * Description : Creates certificate file in presetted directory.
1676 * If certificate already exists, no other certificate
1677 * will be created. Subject of certificate is named
1678 * by csp->http->host from parameter. This function also
1679 * triggers generating of private key for new certificate.
1682 * 1 : csp = Current client state (buffers, headers, etc...)
1684 * Returns : -1 => Error while creating certificate.
1685 * 0 => Certificate already exists.
1686 * 1 => Certificate created
1688 *********************************************************************/
1689 static int generate_webpage_certificate(struct client_state *csp)
1691 char *key_buf = NULL; /* Buffer for created key */
1692 X509 *issuer_cert = NULL;
1695 EVP_PKEY *loaded_subject_key = NULL;
1696 EVP_PKEY *loaded_issuer_key = NULL;
1697 X509_NAME *issuer_name;
1698 X509_NAME *subject_name = NULL;
1699 ASN1_TIME *asn_time = NULL;
1700 ASN1_INTEGER *serial = NULL;
1701 BIGNUM *serial_num = NULL;
1704 cert_options cert_opt;
1705 char cert_valid_from[VALID_DATETIME_BUFLEN];
1706 char cert_valid_to[VALID_DATETIME_BUFLEN];
1708 /* Paths to keys and certificates needed to create certificate */
1709 cert_opt.issuer_key = NULL;
1710 cert_opt.subject_key = NULL;
1711 cert_opt.issuer_crt = NULL;
1713 cert_opt.output_file = make_certs_path(csp->config->certificate_directory,
1714 (const char *)csp->http->hash_of_host_hex, CERT_FILE_TYPE);
1715 if (cert_opt.output_file == NULL)
1720 cert_opt.subject_key = make_certs_path(csp->config->certificate_directory,
1721 (const char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
1722 if (cert_opt.subject_key == NULL)
1724 freez(cert_opt.output_file);
1728 if (file_exists(cert_opt.output_file) == 1)
1730 /* The file exists, but is it valid? */
1731 if (ssl_certificate_is_invalid(cert_opt.output_file))
1733 log_error(LOG_LEVEL_CONNECT,
1734 "Certificate %s is no longer valid. Removing it.",
1735 cert_opt.output_file);
1736 if (unlink(cert_opt.output_file))
1738 log_error(LOG_LEVEL_ERROR, "Failed to unlink %s: %E",
1739 cert_opt.output_file);
1741 freez(cert_opt.output_file);
1742 freez(cert_opt.subject_key);
1746 if (unlink(cert_opt.subject_key))
1748 log_error(LOG_LEVEL_ERROR, "Failed to unlink %s: %E",
1749 cert_opt.subject_key);
1751 freez(cert_opt.output_file);
1752 freez(cert_opt.subject_key);
1759 freez(cert_opt.output_file);
1760 freez(cert_opt.subject_key);
1767 * Create key for requested host
1769 int subject_key_len = generate_key(csp, &key_buf);
1770 if (subject_key_len < 0)
1772 freez(cert_opt.output_file);
1773 freez(cert_opt.subject_key);
1774 log_error(LOG_LEVEL_ERROR, "Key generating failed");
1779 * Converting unsigned long serial number to char * serial number.
1780 * We must compute length of serial number in string + terminating null.
1782 unsigned long certificate_serial = get_certificate_serial(csp);
1783 unsigned long certificate_serial_time = (unsigned long)time(NULL);
1784 int serial_num_size = snprintf(NULL, 0, "%lu%lu",
1785 certificate_serial_time, certificate_serial) + 1;
1786 if (serial_num_size <= 0)
1788 serial_num_size = 1;
1791 char serial_num_text[serial_num_size]; /* Buffer for serial number */
1792 ret = snprintf(serial_num_text, (size_t)serial_num_size, "%lu%lu",
1793 certificate_serial_time, certificate_serial);
1794 if (ret < 0 || ret >= serial_num_size)
1796 log_error(LOG_LEVEL_ERROR,
1797 "Converting certificate serial number into string failed");
1803 * Preparing parameters for certificate
1805 subject_name = X509_NAME_new();
1808 log_ssl_errors(LOG_LEVEL_ERROR, "RSA key memory allocation failure");
1813 if (!X509_NAME_add_entry_by_txt(subject_name, CERT_PARAM_COMMON_NAME_FCODE,
1814 MBSTRING_ASC, (void *)csp->http->host, -1, -1, 0))
1816 log_ssl_errors(LOG_LEVEL_ERROR,
1817 "X509 subject name (code: %s, val: %s) error",
1818 CERT_PARAM_COMMON_NAME_FCODE, csp->http->host);
1822 if (!X509_NAME_add_entry_by_txt(subject_name, CERT_PARAM_ORGANIZATION_FCODE,
1823 MBSTRING_ASC, (void *)csp->http->host, -1, -1, 0))
1825 log_ssl_errors(LOG_LEVEL_ERROR,
1826 "X509 subject name (code: %s, val: %s) error",
1827 CERT_PARAM_ORGANIZATION_FCODE, csp->http->host);
1831 if (!X509_NAME_add_entry_by_txt(subject_name, CERT_PARAM_ORG_UNIT_FCODE,
1832 MBSTRING_ASC, (void *)csp->http->host, -1, -1, 0))
1834 log_ssl_errors(LOG_LEVEL_ERROR,
1835 "X509 subject name (code: %s, val: %s) error",
1836 CERT_PARAM_ORG_UNIT_FCODE, csp->http->host);
1840 if (!X509_NAME_add_entry_by_txt(subject_name, CERT_PARAM_COUNTRY_FCODE,
1841 MBSTRING_ASC, (void *)CERT_PARAM_COUNTRY_CODE, -1, -1, 0))
1843 log_ssl_errors(LOG_LEVEL_ERROR,
1844 "X509 subject name (code: %s, val: %s) error",
1845 CERT_PARAM_COUNTRY_FCODE, csp->http->host);
1850 cert_opt.issuer_crt = csp->config->ca_cert_file;
1851 cert_opt.issuer_key = csp->config->ca_key_file;
1853 if (get_certificate_valid_from_date(cert_valid_from,
1854 sizeof(cert_valid_from), VALID_DATETIME_FMT)
1855 || get_certificate_valid_to_date(cert_valid_to,
1856 sizeof(cert_valid_to), VALID_DATETIME_FMT))
1858 log_error(LOG_LEVEL_ERROR, "Generating one of the validity dates failed");
1863 cert_opt.subject_pwd = CERT_SUBJECT_PASSWORD;
1864 cert_opt.issuer_pwd = csp->config->ca_password;
1865 cert_opt.not_before = cert_valid_from;
1866 cert_opt.not_after = cert_valid_to;
1867 cert_opt.serial = serial_num_text;
1868 cert_opt.max_pathlen = -1;
1871 * Test if the private key was already created.
1872 * XXX: Can this still happen?
1874 if (subject_key_len == 0)
1876 log_error(LOG_LEVEL_ERROR, "Subject key was already created");
1882 * Parse serial to MPI
1884 serial_num = BN_new();
1887 log_error(LOG_LEVEL_ERROR, "generate_webpage_certificate: memory error");
1891 if (!BN_dec2bn(&serial_num, cert_opt.serial))
1893 log_ssl_errors(LOG_LEVEL_ERROR, "Failed to parse serial %s", cert_opt.serial);
1898 if (!(serial = BN_to_ASN1_INTEGER(serial_num, NULL)))
1900 log_ssl_errors(LOG_LEVEL_ERROR, "Failed to generate serial ASN1 representation");
1906 * Loading certificates
1908 if (!(issuer_cert = ssl_certificate_load(cert_opt.issuer_crt)))
1910 log_error(LOG_LEVEL_ERROR, "Loading issuer certificate %s failed",
1911 cert_opt.issuer_crt);
1916 issuer_name = X509_get_issuer_name(issuer_cert);
1919 * Loading keys from file or from buffer
1921 if (key_buf != NULL && subject_key_len > 0)
1923 pk_bio = BIO_new_mem_buf(key_buf, subject_key_len);
1925 else if (!(pk_bio = BIO_new_file(cert_opt.subject_key, "r")))
1927 log_ssl_errors(LOG_LEVEL_ERROR,
1928 "Failure opening subject key %s BIO", cert_opt.subject_key);
1933 loaded_subject_key = PEM_read_bio_PrivateKey(pk_bio, NULL, NULL,
1934 (void *)cert_opt.subject_pwd);
1935 if (!loaded_subject_key)
1937 log_ssl_errors(LOG_LEVEL_ERROR, "Parsing subject key %s failed",
1938 cert_opt.subject_key);
1943 if (!BIO_free(pk_bio))
1945 log_ssl_errors(LOG_LEVEL_ERROR, "Error closing subject key BIO");
1948 if (!(pk_bio = BIO_new_file(cert_opt.issuer_key, "r")))
1950 log_ssl_errors(LOG_LEVEL_ERROR, "Failure opening issuer key %s BIO",
1951 cert_opt.issuer_key);
1956 loaded_issuer_key = PEM_read_bio_PrivateKey(pk_bio, NULL, NULL,
1957 (void *)cert_opt.issuer_pwd);
1958 if (!loaded_issuer_key)
1960 log_ssl_errors(LOG_LEVEL_ERROR, "Parsing issuer key %s failed",
1961 cert_opt.subject_key);
1969 log_ssl_errors(LOG_LEVEL_ERROR, "Certificate allocation error");
1974 if (!X509_set_version(cert, CERTIFICATE_VERSION))
1976 log_ssl_errors(LOG_LEVEL_ERROR, "X509_set_version failed");
1982 * Setting parameters of signed certificate
1984 if (!X509_set_pubkey(cert, loaded_subject_key))
1986 log_ssl_errors(LOG_LEVEL_ERROR,
1987 "Setting public key in signed certificate failed");
1992 if (!X509_set_subject_name(cert, subject_name))
1994 log_ssl_errors(LOG_LEVEL_ERROR,
1995 "Setting subject name in signed certificate failed");
2000 if (!X509_set_issuer_name(cert, issuer_name))
2002 log_ssl_errors(LOG_LEVEL_ERROR,
2003 "Setting issuer name in signed certificate failed");
2008 if (!X509_set_serialNumber(cert, serial))
2010 log_ssl_errors(LOG_LEVEL_ERROR,
2011 "Setting serial number in signed certificate failed");
2016 asn_time = ASN1_TIME_new();
2019 log_ssl_errors(LOG_LEVEL_ERROR, "ASN1 time memory allocation failure");
2024 if (!ASN1_TIME_set_string(asn_time, cert_opt.not_after))
2026 log_ssl_errors(LOG_LEVEL_ERROR, "ASN1 time [%s] encode error", cert_opt.not_after);
2031 if (!X509_set1_notAfter(cert, asn_time))
2033 log_ssl_errors(LOG_LEVEL_ERROR,
2034 "Setting valid not after in signed certificate failed");
2039 if (!ASN1_TIME_set_string(asn_time, cert_opt.not_before))
2041 log_ssl_errors(LOG_LEVEL_ERROR, "ASN1 time encode error");
2046 if (!X509_set1_notBefore(cert, asn_time))
2048 log_ssl_errors(LOG_LEVEL_ERROR,
2049 "Setting valid not before in signed certificate failed");
2054 if (!set_x509_ext(cert, issuer_cert, NID_basic_constraints, CERTIFICATE_BASIC_CONSTRAINTS))
2056 log_ssl_errors(LOG_LEVEL_ERROR, "Setting the basicConstraints extension "
2057 "in signed certificate failed");
2062 if (!set_x509_ext(cert, issuer_cert, NID_subject_key_identifier, CERTIFICATE_SUBJECT_KEY))
2064 log_ssl_errors(LOG_LEVEL_ERROR,
2065 "Setting the Subject Key Identifier extension failed");
2070 if (!set_x509_ext(cert, issuer_cert, NID_authority_key_identifier, CERTIFICATE_AUTHORITY_KEY))
2072 log_ssl_errors(LOG_LEVEL_ERROR,
2073 "Setting the Authority Key Identifier extension failed");
2078 if (!host_is_ip_address(csp->http->host) &&
2079 !set_subject_alternative_name(cert, issuer_cert, csp->http->host))
2081 log_ssl_errors(LOG_LEVEL_ERROR,
2082 "Setting the Subject Alt Name extension failed");
2087 if (!X509_sign(cert, loaded_issuer_key, EVP_sha256()))
2089 log_ssl_errors(LOG_LEVEL_ERROR, "Signing certificate failed");
2095 * Writing certificate into file
2097 if (write_certificate(cert, cert_opt.output_file) < 0)
2099 log_error(LOG_LEVEL_ERROR, "Writing certificate into file failed");
2108 * Freeing used structures
2112 X509_free(issuer_cert);
2118 if (pk_bio && !BIO_free(pk_bio))
2120 log_ssl_errors(LOG_LEVEL_ERROR, "Error closing pk BIO");
2122 if (loaded_subject_key)
2124 EVP_PKEY_free(loaded_subject_key);
2126 if (loaded_issuer_key)
2128 EVP_PKEY_free(loaded_issuer_key);
2132 X509_NAME_free(subject_name);
2136 ASN1_TIME_free(asn_time);
2140 BN_free(serial_num);
2144 ASN1_INTEGER_free(serial);
2146 freez(cert_opt.subject_key);
2147 freez(cert_opt.output_file);
2154 /*********************************************************************
2156 * Function : ssl_crt_verify_info
2158 * Description : Returns an informational string about the verification
2159 * status of a certificate.
2162 * 1 : buf = Buffer to write to
2163 * 2 : size = Maximum size of buffer
2164 * 3 : csp = client state
2168 *********************************************************************/
2169 extern void ssl_crt_verify_info(char *buf, size_t size, struct client_state *csp)
2171 strncpy(buf, X509_verify_cert_error_string(csp->server_cert_verification_result), size);
2176 /*********************************************************************
2178 * Function : ssl_release
2180 * Description : Release all SSL resources
2186 *********************************************************************/
2187 extern void ssl_release(void)
2189 if (ssl_inited == 1)
2191 #ifndef OPENSSL_NO_COMP
2192 SSL_COMP_free_compression_methods();
2194 CONF_modules_free();
2195 CONF_modules_unload(1);
2196 #ifndef OPENSSL_NO_COMP
2197 COMP_zlib_cleanup();
2203 CRYPTO_cleanup_all_ex_data();