1 /*********************************************************************
3 * File : $Source: /cvsroot/ijbswa/current/ssl.c,v $
5 * Purpose : File with TLS/SSL extension. Contains methods for
6 * creating, using and closing TLS/SSL connections
9 * Copyright : Written by and Copyright (c) 2017-2020 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 #if !defined(MBEDTLS_CONFIG_FILE)
36 # include "mbedtls/config.h"
38 # include MBEDTLS_CONFIG_FILE
41 #include "mbedtls/md5.h"
42 #include "mbedtls/pem.h"
43 #include "mbedtls/base64.h"
44 #include "mbedtls/error.h"
45 #include "mbedtls/oid.h"
46 #include "mbedtls/asn1write.h"
54 #include "ssl_common.h"
59 * Macros for searching begin and end of certificates.
60 * Necessary to convert structure mbedtls_x509_crt to crt file.
62 #define PEM_BEGIN_CRT "-----BEGIN CERTIFICATE-----\n"
63 #define PEM_END_CRT "-----END CERTIFICATE-----\n"
64 #define VALID_DATETIME_FMT "%Y%m%d%H%M%S"
65 #define VALID_DATETIME_BUFLEN 15
70 #define CERTIFICATE_BUF_SIZE 16384 /* Size of buffer to save certificate. Value 4096 is mbedtls library buffer size for certificate in DER form */
71 #define PRIVATE_KEY_BUF_SIZE 16000 /* Size of buffer to save private key. Value 16000 is taken from mbed TLS library examples. */
72 #define CERT_SIGNATURE_ALGORITHM MBEDTLS_MD_SHA256 /* The MD algorithm to use for the signature */
73 #define CERT_PARAM_COMMON_NAME CERT_PARAM_COMMON_NAME_FCODE"="
74 #define CERT_PARAM_ORGANIZATION ","CERT_PARAM_ORGANIZATION_FCODE"="
75 #define CERT_PARAM_ORG_UNIT ","CERT_PARAM_ORG_UNIT_FCODE"="
76 #define CERT_PARAM_COUNTRY ","CERT_PARAM_COUNTRY_FCODE"="CERT_PARAM_COUNTRY_CODE
79 * Properties of key for generating
82 mbedtls_pk_type_t type; /* type of key to generate */
83 int rsa_keysize; /* length of key in bits */
84 char *key_file_path; /* filename of the key file */
87 /* Variables for one common RNG for all SSL use */
88 static mbedtls_ctr_drbg_context ctr_drbg;
89 static mbedtls_entropy_context entropy;
90 static int rng_seeded;
92 static int generate_host_certificate(struct client_state *csp);
93 static int host_to_hash(struct client_state *csp);
94 static int ssl_verify_callback(void *data, mbedtls_x509_crt *crt, int depth, uint32_t *flags);
95 static void free_client_ssl_structures(struct client_state *csp);
96 static void free_server_ssl_structures(struct client_state *csp);
97 static int seed_rng(struct client_state *csp);
98 static int *get_ciphersuites_from_string(const char *ciphersuites_string);
100 /*********************************************************************
102 * Function : is_ssl_pending
104 * Description : Tests if there are some waiting data on ssl connection.
105 * Only considers data that has actually been received
106 * locally and ignores data that is still on the fly
107 * or has not yet been sent by the remote end.
110 * 1 : ssl_attr = SSL context to test
112 * Returns : 0 => No data are pending
113 * >0 => Pending data length
115 *********************************************************************/
116 extern size_t is_ssl_pending(struct ssl_attr *ssl_attr)
118 mbedtls_ssl_context *ssl = &ssl_attr->mbedtls_attr.ssl;
124 return mbedtls_ssl_get_bytes_avail(ssl);
128 /*********************************************************************
130 * Function : ssl_send_data
132 * Description : Sends the content of buf (for n bytes) to given SSL
133 * connection context.
136 * 1 : ssl_attr = SSL context to send data to
137 * 2 : buf = Pointer to data to be sent
138 * 3 : len = Length of data to be sent to the SSL context
140 * Returns : Length of sent data or negative value on error.
142 *********************************************************************/
143 extern int ssl_send_data(struct ssl_attr *ssl_attr, const unsigned char *buf, size_t len)
145 mbedtls_ssl_context *ssl = &ssl_attr->mbedtls_attr.ssl;
147 size_t max_fragment_size = 0; /* Maximal length of data in one SSL fragment*/
148 int send_len = 0; /* length of one data part to send */
149 int pos = 0; /* Position of unsent part in buffer */
156 /* Getting maximal length of data sent in one fragment */
157 max_fragment_size = mbedtls_ssl_get_max_frag_len(ssl);
160 * Whole buffer must be sent in many fragments, because each fragment
161 * has its maximal length.
165 /* Compute length of data, that can be send in next fragment */
166 if ((pos + (int)max_fragment_size) > len)
168 send_len = (int)len - pos;
172 send_len = (int)max_fragment_size;
175 log_error(LOG_LEVEL_WRITING, "TLS on socket %d: %N",
176 ssl_attr->mbedtls_attr.socket_fd.fd, send_len, buf+pos);
179 * Sending one part of the buffer
181 while ((ret = mbedtls_ssl_write(ssl,
182 (const unsigned char *)(buf + pos),
183 (size_t)send_len)) < 0)
185 if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
186 ret != MBEDTLS_ERR_SSL_WANT_WRITE)
188 char err_buf[ERROR_BUF_SIZE];
190 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
191 log_error(LOG_LEVEL_ERROR,
192 "Sending data on socket %d over TLS/SSL failed: %s",
193 ssl_attr->mbedtls_attr.socket_fd.fd, err_buf);
197 /* Adding count of sent bytes to position in buffer */
198 pos = pos + send_len;
205 /*********************************************************************
207 * Function : ssl_recv_data
209 * Description : Receives data from given SSL context and puts
213 * 1 : ssl_attr = SSL context to receive data from
214 * 2 : buf = Pointer to buffer where data will be written
215 * 3 : max_length = Maximum number of bytes to read
217 * Returns : Number of bytes read, 0 for EOF, or -1
220 *********************************************************************/
221 extern int ssl_recv_data(struct ssl_attr *ssl_attr, unsigned char *buf, size_t max_length)
223 mbedtls_ssl_context *ssl = &ssl_attr->mbedtls_attr.ssl;
225 memset(buf, 0, max_length);
228 * Receiving data from SSL context into buffer
232 ret = mbedtls_ssl_read(ssl, buf, max_length);
233 } while (ret == MBEDTLS_ERR_SSL_WANT_READ
234 || ret == MBEDTLS_ERR_SSL_WANT_WRITE);
238 char err_buf[ERROR_BUF_SIZE];
240 if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY)
242 log_error(LOG_LEVEL_CONNECT, "The peer notified us that "
243 "the connection on socket %d is going to be closed",
244 ssl_attr->mbedtls_attr.socket_fd.fd);
247 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
248 log_error(LOG_LEVEL_ERROR,
249 "Receiving data on socket %d over TLS/SSL failed: %s",
250 ssl_attr->mbedtls_attr.socket_fd.fd, err_buf);
255 log_error(LOG_LEVEL_RECEIVED, "TLS from socket %d: %N",
256 ssl_attr->mbedtls_attr.socket_fd.fd, ret, buf);
262 /*********************************************************************
264 * Function : create_client_ssl_connection
266 * Description : Creates TLS/SSL secured connection with client
269 * 1 : csp = Current client state (buffers, headers, etc...)
271 * Returns : 0 on success, negative value if connection wasn't created
274 *********************************************************************/
275 extern int create_client_ssl_connection(struct client_state *csp)
277 struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
278 /* Paths to certificates file and key file */
279 char *key_file = NULL;
280 char *ca_file = NULL;
281 char *cert_file = NULL;
283 char err_buf[ERROR_BUF_SIZE];
286 * Initializing mbedtls structures for TLS/SSL connection
288 mbedtls_net_init(&(ssl_attr->mbedtls_attr.socket_fd));
289 mbedtls_ssl_init(&(ssl_attr->mbedtls_attr.ssl));
290 mbedtls_ssl_config_init(&(ssl_attr->mbedtls_attr.conf));
291 mbedtls_x509_crt_init(&(ssl_attr->mbedtls_attr.server_cert));
292 mbedtls_pk_init(&(ssl_attr->mbedtls_attr.prim_key));
293 #if defined(MBEDTLS_SSL_CACHE_C)
294 mbedtls_ssl_cache_init(&(ssl_attr->mbedtls_attr.cache));
298 * Preparing hash of host for creating certificates
300 ret = host_to_hash(csp);
303 log_error(LOG_LEVEL_ERROR, "Generating hash of host failed: %d", ret);
309 * Preparing paths to certificates files and key file
311 ca_file = csp->config->ca_cert_file;
312 cert_file = make_certs_path(csp->config->certificate_directory,
313 (const char *)csp->http->hash_of_host_hex, CERT_FILE_TYPE);
314 key_file = make_certs_path(csp->config->certificate_directory,
315 (const char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
317 if (cert_file == NULL || key_file == NULL)
324 * Generating certificate for requested host. Mutex to prevent
325 * certificate and key inconsistence must be locked.
327 privoxy_mutex_lock(&certificate_mutex);
329 ret = generate_host_certificate(csp);
332 log_error(LOG_LEVEL_ERROR,
333 "generate_host_certificate failed: %d", ret);
334 privoxy_mutex_unlock(&certificate_mutex);
338 privoxy_mutex_unlock(&certificate_mutex);
351 * Loading CA file, webpage certificate and key files
353 ret = mbedtls_x509_crt_parse_file(&(ssl_attr->mbedtls_attr.server_cert),
357 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
358 log_error(LOG_LEVEL_ERROR,
359 "Loading webpage certificate %s failed: %s", cert_file, err_buf);
364 ret = mbedtls_x509_crt_parse_file(&(ssl_attr->mbedtls_attr.server_cert),
368 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
369 log_error(LOG_LEVEL_ERROR,
370 "Loading CA certificate %s failed: %s", ca_file, err_buf);
375 ret = mbedtls_pk_parse_keyfile(&(ssl_attr->mbedtls_attr.prim_key),
379 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
380 log_error(LOG_LEVEL_ERROR,
381 "Loading and parsing webpage certificate private key %s failed: %s",
388 * Setting SSL parameters
390 ret = mbedtls_ssl_config_defaults(&(ssl_attr->mbedtls_attr.conf),
391 MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_TRANSPORT_STREAM,
392 MBEDTLS_SSL_PRESET_DEFAULT);
395 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
396 log_error(LOG_LEVEL_ERROR,
397 "mbedtls_ssl_config_defaults failed: %s", err_buf);
402 mbedtls_ssl_conf_rng(&(ssl_attr->mbedtls_attr.conf),
403 mbedtls_ctr_drbg_random, &ctr_drbg);
405 #if defined(MBEDTLS_SSL_CACHE_C)
406 mbedtls_ssl_conf_session_cache(&(ssl_attr->mbedtls_attr.conf),
407 &(ssl_attr->mbedtls_attr.cache), mbedtls_ssl_cache_get,
408 mbedtls_ssl_cache_set);
412 * Setting certificates
414 ret = mbedtls_ssl_conf_own_cert(&(ssl_attr->mbedtls_attr.conf),
415 &(ssl_attr->mbedtls_attr.server_cert),
416 &(ssl_attr->mbedtls_attr.prim_key));
419 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
420 log_error(LOG_LEVEL_ERROR,
421 "mbedtls_ssl_conf_own_cert failed: %s", err_buf);
426 if (csp->config->cipher_list != NULL)
428 ssl_attr->mbedtls_attr.ciphersuites_list =
429 get_ciphersuites_from_string(csp->config->cipher_list);
430 if (ssl_attr->mbedtls_attr.ciphersuites_list == NULL)
432 log_error(LOG_LEVEL_ERROR,
433 "Setting the cipher list '%s' for the client connection failed",
434 csp->config->cipher_list);
438 mbedtls_ssl_conf_ciphersuites(&(ssl_attr->mbedtls_attr.conf),
439 ssl_attr->mbedtls_attr.ciphersuites_list);
442 ret = mbedtls_ssl_setup(&(ssl_attr->mbedtls_attr.ssl),
443 &(ssl_attr->mbedtls_attr.conf));
446 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
447 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_setup failed: %s", err_buf);
452 mbedtls_ssl_set_bio(&(ssl_attr->mbedtls_attr.ssl),
453 &(ssl_attr->mbedtls_attr.socket_fd), mbedtls_net_send,
454 mbedtls_net_recv, NULL);
455 mbedtls_ssl_session_reset(&(ssl_attr->mbedtls_attr.ssl));
458 * Setting socket fd in mbedtls_net_context structure. This structure
459 * can't be set by mbedtls functions, because we already have created
460 * a TCP connection when this function is called.
462 ssl_attr->mbedtls_attr.socket_fd.fd = csp->cfd;
465 * Handshake with client
467 log_error(LOG_LEVEL_CONNECT,
468 "Performing the TLS/SSL handshake with client. Hash of host: %s",
469 csp->http->hash_of_host_hex);
470 while ((ret = mbedtls_ssl_handshake(&(ssl_attr->mbedtls_attr.ssl))) != 0)
472 if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
473 ret != MBEDTLS_ERR_SSL_WANT_WRITE)
475 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
476 log_error(LOG_LEVEL_ERROR,
477 "medtls_ssl_handshake with client failed: %s", err_buf);
483 log_error(LOG_LEVEL_CONNECT, "Client successfully connected over %s (%s).",
484 mbedtls_ssl_get_version(&(ssl_attr->mbedtls_attr.ssl)),
485 mbedtls_ssl_get_ciphersuite(&(ssl_attr->mbedtls_attr.ssl)));
487 csp->ssl_with_client_is_opened = 1;
491 * Freeing allocated paths to files
496 /* Freeing structures if connection wasn't created successfully */
499 free_client_ssl_structures(csp);
505 /*********************************************************************
507 * Function : close_client_ssl_connection
509 * Description : Closes TLS/SSL connection with client. This function
510 * checks if this connection is already created.
513 * 1 : csp = Current client state (buffers, headers, etc...)
517 *********************************************************************/
518 extern void close_client_ssl_connection(struct client_state *csp)
520 struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
523 if (csp->ssl_with_client_is_opened == 0)
529 * Notifying the peer that the connection is being closed.
532 ret = mbedtls_ssl_close_notify(&(ssl_attr->mbedtls_attr.ssl));
533 } while (ret == MBEDTLS_ERR_SSL_WANT_WRITE);
535 free_client_ssl_structures(csp);
536 csp->ssl_with_client_is_opened = 0;
540 /*********************************************************************
542 * Function : free_client_ssl_structures
544 * Description : Frees structures used for SSL communication with
548 * 1 : csp = Current client state (buffers, headers, etc...)
552 *********************************************************************/
553 static void free_client_ssl_structures(struct client_state *csp)
555 struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
557 * We can't use function mbedtls_net_free, because this function
558 * inter alia close TCP connection on set fd. Instead of this
559 * function, we change fd to -1, which is the same what does
560 * rest of mbedtls_net_free function.
562 ssl_attr->mbedtls_attr.socket_fd.fd = -1;
564 /* Freeing mbedtls structures */
565 mbedtls_x509_crt_free(&(ssl_attr->mbedtls_attr.server_cert));
566 mbedtls_pk_free(&(ssl_attr->mbedtls_attr.prim_key));
567 mbedtls_ssl_free(&(ssl_attr->mbedtls_attr.ssl));
568 freez(ssl_attr->mbedtls_attr.ciphersuites_list);
569 mbedtls_ssl_config_free(&(ssl_attr->mbedtls_attr.conf));
570 #if defined(MBEDTLS_SSL_CACHE_C)
571 mbedtls_ssl_cache_free(&(ssl_attr->mbedtls_attr.cache));
576 /*********************************************************************
578 * Function : create_server_ssl_connection
580 * Description : Creates TLS/SSL secured connection with server.
583 * 1 : csp = Current client state (buffers, headers, etc...)
585 * Returns : 0 on success, negative value if connection wasn't created
588 *********************************************************************/
589 extern int create_server_ssl_connection(struct client_state *csp)
591 struct ssl_attr *ssl_attr = &csp->ssl_server_attr;
593 char err_buf[ERROR_BUF_SIZE];
594 char *trusted_cas_file = NULL;
595 int auth_mode = MBEDTLS_SSL_VERIFY_REQUIRED;
597 csp->server_cert_verification_result = SSL_CERT_NOT_VERIFIED;
598 csp->server_certs_chain.next = NULL;
600 /* Setting path to file with trusted CAs */
601 trusted_cas_file = csp->config->trusted_cas_file;
604 * Initializing mbedtls structures for TLS/SSL connection
606 mbedtls_net_init(&(ssl_attr->mbedtls_attr.socket_fd));
607 mbedtls_ssl_init(&(ssl_attr->mbedtls_attr.ssl));
608 mbedtls_ssl_config_init(&(ssl_attr->mbedtls_attr.conf));
609 mbedtls_x509_crt_init(&(ssl_attr->mbedtls_attr.ca_cert));
612 * Setting socket fd in mbedtls_net_context structure. This structure
613 * can't be set by mbedtls functions, because we already have created
614 * TCP connection when calling this function.
616 ssl_attr->mbedtls_attr.socket_fd.fd = csp->server_connection.sfd;
629 * Loading file with trusted CAs
631 ret = mbedtls_x509_crt_parse_file(&(ssl_attr->mbedtls_attr.ca_cert),
635 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
636 log_error(LOG_LEVEL_ERROR, "Loading trusted CAs file %s failed: %s",
637 trusted_cas_file, err_buf);
643 * Set TLS/SSL options
645 ret = mbedtls_ssl_config_defaults(&(ssl_attr->mbedtls_attr.conf),
646 MBEDTLS_SSL_IS_CLIENT,
647 MBEDTLS_SSL_TRANSPORT_STREAM,
648 MBEDTLS_SSL_PRESET_DEFAULT);
651 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
652 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_config_defaults failed: %s",
659 * Setting how strict should certificate verification be and other
660 * parameters for certificate verification
662 if (csp->dont_verify_certificate)
664 auth_mode = MBEDTLS_SSL_VERIFY_NONE;
667 mbedtls_ssl_conf_authmode(&(ssl_attr->mbedtls_attr.conf), auth_mode);
668 mbedtls_ssl_conf_ca_chain(&(ssl_attr->mbedtls_attr.conf),
669 &(ssl_attr->mbedtls_attr.ca_cert), NULL);
671 /* Setting callback function for certificates verification */
672 mbedtls_ssl_conf_verify(&(ssl_attr->mbedtls_attr.conf),
673 ssl_verify_callback, (void *)csp);
675 mbedtls_ssl_conf_rng(&(ssl_attr->mbedtls_attr.conf),
676 mbedtls_ctr_drbg_random, &ctr_drbg);
678 if (csp->config->cipher_list != NULL)
680 ssl_attr->mbedtls_attr.ciphersuites_list =
681 get_ciphersuites_from_string(csp->config->cipher_list);
682 if (ssl_attr->mbedtls_attr.ciphersuites_list == NULL)
684 log_error(LOG_LEVEL_ERROR,
685 "Setting the cipher list '%s' for the server connection failed",
686 csp->config->cipher_list);
690 mbedtls_ssl_conf_ciphersuites(&(ssl_attr->mbedtls_attr.conf),
691 ssl_attr->mbedtls_attr.ciphersuites_list);
694 ret = mbedtls_ssl_setup(&(ssl_attr->mbedtls_attr.ssl),
695 &(ssl_attr->mbedtls_attr.conf));
698 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
699 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_setup failed: %s", err_buf);
705 * Set the hostname to check against the received server certificate
707 ret = mbedtls_ssl_set_hostname(&(ssl_attr->mbedtls_attr.ssl),
711 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
712 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_set_hostname failed: %s",
718 mbedtls_ssl_set_bio(&(ssl_attr->mbedtls_attr.ssl),
719 &(ssl_attr->mbedtls_attr.socket_fd), mbedtls_net_send,
720 mbedtls_net_recv, NULL);
723 * Handshake with server
725 log_error(LOG_LEVEL_CONNECT,
726 "Performing the TLS/SSL handshake with the server");
728 while ((ret = mbedtls_ssl_handshake(&(ssl_attr->mbedtls_attr.ssl))) != 0)
730 if (ret != MBEDTLS_ERR_SSL_WANT_READ
731 && ret != MBEDTLS_ERR_SSL_WANT_WRITE)
733 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
735 if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED)
737 char reason[INVALID_CERT_INFO_BUF_SIZE];
739 csp->server_cert_verification_result =
740 mbedtls_ssl_get_verify_result(&(ssl_attr->mbedtls_attr.ssl));
741 mbedtls_x509_crt_verify_info(reason, sizeof(reason), "",
742 csp->server_cert_verification_result);
744 /* Log the reason without the trailing new line */
745 log_error(LOG_LEVEL_ERROR,
746 "X509 certificate verification for %s failed: %N",
747 csp->http->hostport, strlen(reason)-1, reason);
752 log_error(LOG_LEVEL_ERROR,
753 "mbedtls_ssl_handshake with server failed: %s", err_buf);
754 free_certificate_chain(csp);
761 log_error(LOG_LEVEL_CONNECT, "Server successfully connected over %s (%s).",
762 mbedtls_ssl_get_version(&(ssl_attr->mbedtls_attr.ssl)),
763 mbedtls_ssl_get_ciphersuite(&(ssl_attr->mbedtls_attr.ssl)));
766 * Server certificate chain is valid, so we can clean
767 * chain, because we will not send it to client.
769 free_certificate_chain(csp);
771 csp->ssl_with_server_is_opened = 1;
772 csp->server_cert_verification_result =
773 mbedtls_ssl_get_verify_result(&(ssl_attr->mbedtls_attr.ssl));
776 /* Freeing structures if connection wasn't created successfully */
779 free_server_ssl_structures(csp);
786 /*********************************************************************
788 * Function : close_server_ssl_connection
790 * Description : Closes TLS/SSL connection with server. This function
791 * checks if this connection is already opened.
794 * 1 : csp = Current client state (buffers, headers, etc...)
798 *********************************************************************/
799 extern void close_server_ssl_connection(struct client_state *csp)
801 struct ssl_attr *ssl_attr = &csp->ssl_server_attr;
804 if (csp->ssl_with_server_is_opened == 0)
810 * Notifying the peer that the connection is being closed.
813 ret = mbedtls_ssl_close_notify(&(ssl_attr->mbedtls_attr.ssl));
814 } while (ret == MBEDTLS_ERR_SSL_WANT_WRITE);
816 free_server_ssl_structures(csp);
817 csp->ssl_with_server_is_opened = 0;
821 /*********************************************************************
823 * Function : free_server_ssl_structures
825 * Description : Frees structures used for SSL communication with server
828 * 1 : csp = Current client state (buffers, headers, etc...)
832 *********************************************************************/
833 static void free_server_ssl_structures(struct client_state *csp)
835 struct ssl_attr *ssl_attr = &csp->ssl_server_attr;
837 * We can't use function mbedtls_net_free, because this function
838 * inter alia close TCP connection on set fd. Instead of this
839 * function, we change fd to -1, which is the same what does
840 * rest of mbedtls_net_free function.
842 ssl_attr->mbedtls_attr.socket_fd.fd = -1;
844 mbedtls_x509_crt_free(&(ssl_attr->mbedtls_attr.ca_cert));
845 mbedtls_ssl_free(&(ssl_attr->mbedtls_attr.ssl));
846 freez(ssl_attr->mbedtls_attr.ciphersuites_list);
847 mbedtls_ssl_config_free(&(ssl_attr->mbedtls_attr.conf));
851 /*====================== Certificates ======================*/
853 /*********************************************************************
855 * Function : write_certificate
857 * Description : Writes certificate into file.
860 * 1 : crt = certificate to write into file
861 * 2 : output_file = path to save certificate file
862 * 3 : f_rng = mbedtls_ctr_drbg_random
863 * 4 : p_rng = mbedtls_ctr_drbg_context
865 * Returns : Length of written certificate on success or negative value
868 *********************************************************************/
869 static int write_certificate(mbedtls_x509write_cert *crt, const char *output_file,
870 int(*f_rng)(void *, unsigned char *, size_t), void *p_rng)
874 unsigned char cert_buf[CERTIFICATE_BUF_SIZE + 1]; /* Buffer for certificate in PEM format + terminating NULL */
876 char err_buf[ERROR_BUF_SIZE];
878 memset(cert_buf, 0, sizeof(cert_buf));
881 * Writing certificate into PEM string. If buffer is too small, function
882 * returns specific error and no buffer overflow can happen.
884 if ((ret = mbedtls_x509write_crt_pem(crt, cert_buf,
885 sizeof(cert_buf) - 1, f_rng, p_rng)) != 0)
887 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
888 log_error(LOG_LEVEL_ERROR,
889 "Writing certificate into buffer failed: %s", err_buf);
893 len = strlen((char *)cert_buf);
896 * Saving certificate into file
898 if ((f = fopen(output_file, "w")) == NULL)
900 log_error(LOG_LEVEL_ERROR, "Opening file %s to save certificate failed",
905 if (fwrite(cert_buf, 1, len, f) != len)
907 log_error(LOG_LEVEL_ERROR,
908 "Writing certificate into file %s failed", output_file);
919 /*********************************************************************
921 * Function : write_private_key
923 * Description : Writes private key into file and copies saved
924 * content into given pointer to string. If function
925 * returns 0 for success, this copy must be freed by
929 * 1 : key = key to write into file
930 * 2 : ret_buf = pointer to string with created key file content
931 * 3 : key_file_path = path where to save key file
933 * Returns : Length of written private key on success or negative value
936 *********************************************************************/
937 static int write_private_key(mbedtls_pk_context *key, unsigned char **ret_buf,
938 const char *key_file_path)
940 size_t len = 0; /* Length of created key */
941 FILE *f = NULL; /* File to save certificate */
943 char err_buf[ERROR_BUF_SIZE];
945 /* Initializing buffer for key file content */
946 *ret_buf = zalloc_or_die(PRIVATE_KEY_BUF_SIZE + 1);
949 * Writing private key into PEM string
951 if ((ret = mbedtls_pk_write_key_pem(key, *ret_buf, PRIVATE_KEY_BUF_SIZE)) != 0)
953 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
954 log_error(LOG_LEVEL_ERROR,
955 "Writing private key into PEM string failed: %s", err_buf);
959 len = strlen((char *)*ret_buf);
962 * Saving key into file
964 if ((f = fopen(key_file_path, "wb")) == NULL)
966 log_error(LOG_LEVEL_ERROR,
967 "Opening file %s to save private key failed: %E",
973 if (fwrite(*ret_buf, 1, len, f) != len)
976 log_error(LOG_LEVEL_ERROR,
977 "Writing private key into file %s failed",
996 /*********************************************************************
998 * Function : generate_key
1000 * Description : Tests if private key for host saved in csp already
1001 * exists. If this file doesn't exists, a new key is
1002 * generated and saved in a file. The generated key is also
1003 * copied into given parameter key_buf, which must be then
1004 * freed by caller. If file with key exists, key_buf
1005 * contain NULL and no private key is generated.
1008 * 1 : csp = Current client state (buffers, headers, etc...)
1009 * 2 : key_buf = buffer to save new generated key
1011 * Returns : -1 => Error while generating private key
1012 * 0 => Key already exists
1013 * >0 => Length of generated private key
1015 *********************************************************************/
1016 static int generate_key(struct client_state *csp, unsigned char **key_buf)
1018 mbedtls_pk_context key;
1019 key_options key_opt;
1021 char err_buf[ERROR_BUF_SIZE];
1023 key_opt.key_file_path = NULL;
1026 * Initializing structures for key generating
1028 mbedtls_pk_init(&key);
1031 * Preparing path for key file and other properties for generating key
1033 key_opt.type = MBEDTLS_PK_RSA;
1034 key_opt.rsa_keysize = RSA_KEYSIZE;
1036 key_opt.key_file_path = make_certs_path(csp->config->certificate_directory,
1037 (char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
1038 if (key_opt.key_file_path == NULL)
1045 * Test if key already exists. If so, we don't have to create it again.
1047 if (file_exists(key_opt.key_file_path) == 1)
1056 ret = seed_rng(csp);
1064 * Setting attributes of private key and generating it
1066 if ((ret = mbedtls_pk_setup(&key,
1067 mbedtls_pk_info_from_type(key_opt.type))) != 0)
1069 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1070 log_error(LOG_LEVEL_ERROR, "mbedtls_pk_setup failed: %s", err_buf);
1075 ret = mbedtls_rsa_gen_key(mbedtls_pk_rsa(key), mbedtls_ctr_drbg_random,
1076 &ctr_drbg, (unsigned)key_opt.rsa_keysize, RSA_KEY_PUBLIC_EXPONENT);
1079 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1080 log_error(LOG_LEVEL_ERROR, "Key generating failed: %s", err_buf);
1086 * Exporting private key into file
1088 if ((ret = write_private_key(&key, key_buf, key_opt.key_file_path)) < 0)
1090 log_error(LOG_LEVEL_ERROR,
1091 "Writing private key into file %s failed", key_opt.key_file_path);
1098 * Freeing used variables
1100 freez(key_opt.key_file_path);
1102 mbedtls_pk_free(&key);
1108 /*********************************************************************
1110 * Function : ssl_certificate_is_invalid
1112 * Description : Checks whether or not a certificate is valid.
1113 * Currently only checks that the certificate can be
1114 * parsed and that the "valid to" date is in the future.
1117 * 1 : cert_file = The certificate to check
1119 * Returns : 0 => The certificate is valid.
1120 * 1 => The certificate is invalid
1122 *********************************************************************/
1123 static int ssl_certificate_is_invalid(const char *cert_file)
1125 mbedtls_x509_crt cert;
1128 mbedtls_x509_crt_init(&cert);
1130 ret = mbedtls_x509_crt_parse_file(&cert, cert_file);
1133 char err_buf[ERROR_BUF_SIZE];
1135 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1136 log_error(LOG_LEVEL_ERROR,
1137 "Loading certificate %s to check validity failed: %s",
1138 cert_file, err_buf);
1139 mbedtls_x509_crt_free(&cert);
1143 if (mbedtls_x509_time_is_past(&cert.valid_to))
1145 mbedtls_x509_crt_free(&cert);
1150 mbedtls_x509_crt_free(&cert);
1157 /*********************************************************************
1159 * Function : set_subject_alternative_name
1161 * Description : Sets the Subject Alternative Name extension to a cert
1164 * 1 : cert = The certificate to modify
1165 * 2 : hostname = The hostname to add
1167 * Returns : <0 => Error while creating certificate.
1170 *********************************************************************/
1171 static int set_subject_alternative_name(mbedtls_x509write_cert *cert, const char *hostname)
1173 char err_buf[ERROR_BUF_SIZE];
1175 char *subject_alternative_name;
1176 size_t subject_alternative_name_len;
1177 #define MBEDTLS_SUBJECT_ALTERNATIVE_NAME_MAX_LEN 255
1178 unsigned char san_buf[MBEDTLS_SUBJECT_ALTERNATIVE_NAME_MAX_LEN + 1];
1182 subject_alternative_name_len = strlen(hostname) + 1;
1183 subject_alternative_name = zalloc_or_die(subject_alternative_name_len);
1185 strlcpy(subject_alternative_name, hostname, subject_alternative_name_len);
1187 memset(san_buf, 0, sizeof(san_buf));
1189 c = san_buf + sizeof(san_buf);
1192 ret = mbedtls_asn1_write_raw_buffer(&c, san_buf,
1193 (const unsigned char *)subject_alternative_name,
1194 strlen(subject_alternative_name));
1197 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1198 log_error(LOG_LEVEL_ERROR,
1199 "mbedtls_asn1_write_raw_buffer() failed: %s", err_buf);
1204 ret = mbedtls_asn1_write_len(&c, san_buf, strlen(subject_alternative_name));
1207 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1208 log_error(LOG_LEVEL_ERROR,
1209 "mbedtls_asn1_write_len() failed: %s", err_buf);
1214 ret = mbedtls_asn1_write_tag(&c, san_buf, MBEDTLS_ASN1_CONTEXT_SPECIFIC | 2);
1217 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1218 log_error(LOG_LEVEL_ERROR,
1219 "mbedtls_asn1_write_tag() failed: %s", err_buf);
1224 ret = mbedtls_asn1_write_len(&c, san_buf, (size_t)len);
1227 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1228 log_error(LOG_LEVEL_ERROR,
1229 "mbedtls_asn1_write_len() failed: %s", err_buf);
1234 ret = mbedtls_asn1_write_tag(&c, san_buf,
1235 MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE);
1238 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1239 log_error(LOG_LEVEL_ERROR,
1240 "mbedtls_asn1_write_tag() failed: %s", err_buf);
1245 ret = mbedtls_x509write_crt_set_extension(cert,
1246 MBEDTLS_OID_SUBJECT_ALT_NAME,
1247 MBEDTLS_OID_SIZE(MBEDTLS_OID_SUBJECT_ALT_NAME),
1248 0, san_buf + sizeof(san_buf) - len, (size_t)len);
1251 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1252 log_error(LOG_LEVEL_ERROR,
1253 "mbedtls_x509write_crt_set_extension() failed: %s", err_buf);
1257 freez(subject_alternative_name);
1264 /*********************************************************************
1266 * Function : generate_host_certificate
1268 * Description : Creates certificate file in presetted directory.
1269 * If certificate already exists, no other certificate
1270 * will be created. Subject of certificate is named
1271 * by csp->http->host from parameter. This function also
1272 * triggers generating of private key for new certificate.
1275 * 1 : csp = Current client state (buffers, headers, etc...)
1277 * Returns : -1 => Error while creating certificate.
1278 * 0 => Certificate already exists.
1279 * >0 => Length of created certificate.
1281 *********************************************************************/
1282 static int generate_host_certificate(struct client_state *csp)
1284 mbedtls_x509_crt issuer_cert;
1285 mbedtls_pk_context loaded_issuer_key, loaded_subject_key;
1286 mbedtls_pk_context *issuer_key = &loaded_issuer_key;
1287 mbedtls_pk_context *subject_key = &loaded_subject_key;
1288 mbedtls_x509write_cert cert;
1291 unsigned char *key_buf = NULL; /* Buffer for created key */
1294 char err_buf[ERROR_BUF_SIZE];
1295 cert_options cert_opt;
1296 char cert_valid_from[VALID_DATETIME_BUFLEN];
1297 char cert_valid_to[VALID_DATETIME_BUFLEN];
1299 /* Paths to keys and certificates needed to create certificate */
1300 cert_opt.issuer_key = NULL;
1301 cert_opt.subject_key = NULL;
1302 cert_opt.issuer_crt = NULL;
1304 cert_opt.output_file = make_certs_path(csp->config->certificate_directory,
1305 (const char *)csp->http->hash_of_host_hex, CERT_FILE_TYPE);
1306 if (cert_opt.output_file == NULL)
1311 cert_opt.subject_key = make_certs_path(csp->config->certificate_directory,
1312 (const char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
1313 if (cert_opt.subject_key == NULL)
1315 freez(cert_opt.output_file);
1319 if (enforce_sane_certificate_state(cert_opt.output_file,
1320 cert_opt.subject_key))
1322 freez(cert_opt.output_file);
1323 freez(cert_opt.subject_key);
1328 if (file_exists(cert_opt.output_file) == 1)
1330 /* The file exists, but is it valid? */
1331 if (ssl_certificate_is_invalid(cert_opt.output_file))
1333 log_error(LOG_LEVEL_CONNECT,
1334 "Certificate %s is no longer valid. Removing it.",
1335 cert_opt.output_file);
1336 if (unlink(cert_opt.output_file))
1338 log_error(LOG_LEVEL_ERROR, "Failed to unlink %s: %E",
1339 cert_opt.output_file);
1341 freez(cert_opt.output_file);
1342 freez(cert_opt.subject_key);
1346 if (unlink(cert_opt.subject_key))
1348 log_error(LOG_LEVEL_ERROR, "Failed to unlink %s: %E",
1349 cert_opt.subject_key);
1351 freez(cert_opt.output_file);
1352 freez(cert_opt.subject_key);
1359 freez(cert_opt.output_file);
1360 freez(cert_opt.subject_key);
1367 * Create key for requested host
1369 int subject_key_len = generate_key(csp, &key_buf);
1370 if (subject_key_len < 0)
1372 freez(cert_opt.output_file);
1373 freez(cert_opt.subject_key);
1374 log_error(LOG_LEVEL_ERROR, "Key generating failed");
1379 * Initializing structures for certificate generating
1381 mbedtls_x509write_crt_init(&cert);
1382 mbedtls_x509write_crt_set_md_alg(&cert, CERT_SIGNATURE_ALGORITHM);
1383 mbedtls_pk_init(&loaded_issuer_key);
1384 mbedtls_pk_init(&loaded_subject_key);
1385 mbedtls_mpi_init(&serial);
1386 mbedtls_x509_crt_init(&issuer_cert);
1389 * Presetting parameters for certificate. We must compute total length
1392 size_t cert_params_len = strlen(CERT_PARAM_COMMON_NAME) +
1393 strlen(CERT_PARAM_ORGANIZATION) + strlen(CERT_PARAM_COUNTRY) +
1394 strlen(CERT_PARAM_ORG_UNIT) +
1395 3 * strlen(csp->http->host) + 1;
1396 char cert_params[cert_params_len];
1397 memset(cert_params, 0, cert_params_len);
1400 * Converting unsigned long serial number to char * serial number.
1401 * We must compute length of serial number in string + terminating null.
1403 unsigned long certificate_serial = get_certificate_serial(csp);
1404 unsigned long certificate_serial_time = (unsigned long)time(NULL);
1405 int serial_num_size = snprintf(NULL, 0, "%lu%lu",
1406 certificate_serial_time, certificate_serial) + 1;
1407 if (serial_num_size <= 0)
1409 serial_num_size = 1;
1412 char serial_num_text[serial_num_size]; /* Buffer for serial number */
1413 ret = snprintf(serial_num_text, (size_t)serial_num_size, "%lu%lu",
1414 certificate_serial_time, certificate_serial);
1415 if (ret < 0 || ret >= serial_num_size)
1417 log_error(LOG_LEVEL_ERROR,
1418 "Converting certificate serial number into string failed");
1424 * Preparing parameters for certificate
1426 strlcpy(cert_params, CERT_PARAM_COMMON_NAME, cert_params_len);
1427 strlcat(cert_params, csp->http->host, cert_params_len);
1428 strlcat(cert_params, CERT_PARAM_ORGANIZATION, cert_params_len);
1429 strlcat(cert_params, csp->http->host, cert_params_len);
1430 strlcat(cert_params, CERT_PARAM_ORG_UNIT, cert_params_len);
1431 strlcat(cert_params, csp->http->host, cert_params_len);
1432 strlcat(cert_params, CERT_PARAM_COUNTRY, cert_params_len);
1434 cert_opt.issuer_crt = csp->config->ca_cert_file;
1435 cert_opt.issuer_key = csp->config->ca_key_file;
1437 if (get_certificate_valid_from_date(cert_valid_from, sizeof(cert_valid_from), VALID_DATETIME_FMT)
1438 || get_certificate_valid_to_date(cert_valid_to, sizeof(cert_valid_to), VALID_DATETIME_FMT))
1440 log_error(LOG_LEVEL_ERROR, "Generating one of the validity dates failed");
1445 cert_opt.subject_pwd = CERT_SUBJECT_PASSWORD;
1446 cert_opt.issuer_pwd = csp->config->ca_password;
1447 cert_opt.subject_name = cert_params;
1448 cert_opt.not_before = cert_valid_from;
1449 cert_opt.not_after = cert_valid_to;
1450 cert_opt.serial = serial_num_text;
1452 cert_opt.max_pathlen = -1;
1455 * Test if the private key was already created.
1456 * XXX: Can this still happen?
1458 if (subject_key_len == 0)
1460 log_error(LOG_LEVEL_ERROR, "Subject key was already created");
1468 ret = seed_rng(csp);
1476 * Parse serial to MPI
1478 ret = mbedtls_mpi_read_string(&serial, 10, cert_opt.serial);
1481 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1482 log_error(LOG_LEVEL_ERROR,
1483 "mbedtls_mpi_read_string failed: %s", err_buf);
1489 * Loading certificates
1491 ret = mbedtls_x509_crt_parse_file(&issuer_cert, cert_opt.issuer_crt);
1494 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1495 log_error(LOG_LEVEL_ERROR, "Loading issuer certificate %s failed: %s",
1496 cert_opt.issuer_crt, err_buf);
1501 ret = mbedtls_x509_dn_gets(cert_opt.issuer_name,
1502 sizeof(cert_opt.issuer_name), &issuer_cert.subject);
1505 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1506 log_error(LOG_LEVEL_ERROR, "mbedtls_x509_dn_gets failed: %s", err_buf);
1512 * Loading keys from file or from buffer
1514 if (key_buf != NULL && subject_key_len > 0)
1516 /* Key was created in this function and is stored in buffer */
1517 ret = mbedtls_pk_parse_key(&loaded_subject_key, key_buf,
1518 (size_t)(subject_key_len + 1), (unsigned const char *)
1519 cert_opt.subject_pwd, strlen(cert_opt.subject_pwd));
1523 /* Key wasn't created in this function, because it already existed */
1524 ret = mbedtls_pk_parse_keyfile(&loaded_subject_key,
1525 cert_opt.subject_key, cert_opt.subject_pwd);
1530 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1531 log_error(LOG_LEVEL_ERROR, "Parsing subject key %s failed: %s",
1532 cert_opt.subject_key, err_buf);
1537 ret = mbedtls_pk_parse_keyfile(&loaded_issuer_key, cert_opt.issuer_key,
1538 cert_opt.issuer_pwd);
1541 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1542 log_error(LOG_LEVEL_ERROR,
1543 "Parsing issuer key %s failed: %s", cert_opt.issuer_key, err_buf);
1549 * Check if key and issuer certificate match
1551 if (!mbedtls_pk_can_do(&issuer_cert.pk, MBEDTLS_PK_RSA) ||
1552 mbedtls_mpi_cmp_mpi(&mbedtls_pk_rsa(issuer_cert.pk)->N,
1553 &mbedtls_pk_rsa(*issuer_key)->N) != 0 ||
1554 mbedtls_mpi_cmp_mpi(&mbedtls_pk_rsa(issuer_cert.pk)->E,
1555 &mbedtls_pk_rsa(*issuer_key)->E) != 0)
1557 log_error(LOG_LEVEL_ERROR,
1558 "Issuer key doesn't match issuer certificate");
1563 mbedtls_x509write_crt_set_subject_key(&cert, subject_key);
1564 mbedtls_x509write_crt_set_issuer_key(&cert, issuer_key);
1567 * Setting parameters of signed certificate
1569 ret = mbedtls_x509write_crt_set_subject_name(&cert, cert_opt.subject_name);
1572 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1573 log_error(LOG_LEVEL_ERROR,
1574 "Setting subject name in signed certificate failed: %s", err_buf);
1579 ret = mbedtls_x509write_crt_set_issuer_name(&cert, cert_opt.issuer_name);
1582 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1583 log_error(LOG_LEVEL_ERROR,
1584 "Setting issuer name in signed certificate failed: %s", err_buf);
1589 ret = mbedtls_x509write_crt_set_serial(&cert, &serial);
1592 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1593 log_error(LOG_LEVEL_ERROR,
1594 "Setting serial number in signed certificate failed: %s", err_buf);
1599 ret = mbedtls_x509write_crt_set_validity(&cert, cert_opt.not_before,
1600 cert_opt.not_after);
1603 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1604 log_error(LOG_LEVEL_ERROR,
1605 "Setting validity in signed certificate failed: %s", err_buf);
1611 * Setting the basicConstraints extension for certificate
1613 ret = mbedtls_x509write_crt_set_basic_constraints(&cert, cert_opt.is_ca,
1614 cert_opt.max_pathlen);
1617 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1618 log_error(LOG_LEVEL_ERROR, "Setting the basicConstraints extension "
1619 "in signed certificate failed: %s", err_buf);
1624 #if defined(MBEDTLS_SHA1_C)
1625 /* Setting the subjectKeyIdentifier extension for certificate */
1626 ret = mbedtls_x509write_crt_set_subject_key_identifier(&cert);
1629 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1630 log_error(LOG_LEVEL_ERROR, "mbedtls_x509write_crt_set_subject_key_"
1631 "identifier failed: %s", err_buf);
1636 /* Setting the authorityKeyIdentifier extension for certificate */
1637 ret = mbedtls_x509write_crt_set_authority_key_identifier(&cert);
1640 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1641 log_error(LOG_LEVEL_ERROR, "mbedtls_x509write_crt_set_authority_key_"
1642 "identifier failed: %s", err_buf);
1646 #endif /* MBEDTLS_SHA1_C */
1648 if (!host_is_ip_address(csp->http->host) &&
1649 set_subject_alternative_name(&cert, csp->http->host))
1651 /* Errors are already logged by set_subject_alternative_name() */
1657 * Writing certificate into file
1659 ret = write_certificate(&cert, cert_opt.output_file,
1660 mbedtls_ctr_drbg_random, &ctr_drbg);
1663 log_error(LOG_LEVEL_ERROR, "Writing certificate into file failed");
1669 * Freeing used structures
1671 mbedtls_x509write_crt_free(&cert);
1672 mbedtls_pk_free(&loaded_subject_key);
1673 mbedtls_pk_free(&loaded_issuer_key);
1674 mbedtls_mpi_free(&serial);
1675 mbedtls_x509_crt_free(&issuer_cert);
1677 freez(cert_opt.subject_key);
1678 freez(cert_opt.output_file);
1684 /*********************************************************************
1686 * Function : ssl_verify_callback
1688 * Description : This is a callback function for certificate verification.
1689 * It's called once for each certificate in the server's
1690 * certificate trusted chain and prepares information about
1691 * the certificate. The information can be used to inform
1692 * the user about invalid certificates.
1695 * 1 : csp_void = Current client state (buffers, headers, etc...)
1696 * 2 : crt = certificate from trusted chain
1697 * 3 : depth = depth in trusted chain
1698 * 4 : flags = certificate flags
1700 * Returns : 0 on success and negative value on error
1702 *********************************************************************/
1703 static int ssl_verify_callback(void *csp_void, mbedtls_x509_crt *crt,
1704 int depth, uint32_t *flags)
1706 struct client_state *csp = (struct client_state *)csp_void;
1707 struct certs_chain *last = &(csp->server_certs_chain);
1710 size_t pem_buffer_length;
1713 * Searching for last item in certificates linked list
1715 while (last->next != NULL)
1721 * Preparing next item in linked list for next certificate
1723 last->next = malloc_or_die(sizeof(struct certs_chain));
1724 last->next->next = NULL;
1725 memset(last->next->info_buf, 0, sizeof(last->next->info_buf));
1726 last->next->file_buf = NULL;
1728 ret = mbedtls_pem_write_buffer(PEM_BEGIN_CRT, PEM_END_CRT, crt->raw.p,
1729 crt->raw.len, NULL, 0, &olen);
1730 if (MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL != ret)
1732 log_error(LOG_LEVEL_ERROR,
1733 "Failed to figure out the required X509 PEM certificate buffer size");
1736 pem_buffer_length = olen;
1738 last->file_buf = malloc(pem_buffer_length);
1739 if (last->file_buf == NULL)
1741 log_error(LOG_LEVEL_ERROR,
1742 "Failed to allocate %lu bytes to store the X509 PEM certificate",
1748 * Saving certificate file into buffer
1750 if ((ret = mbedtls_pem_write_buffer(PEM_BEGIN_CRT, PEM_END_CRT,
1751 crt->raw.p, crt->raw.len, (unsigned char *)last->file_buf,
1752 pem_buffer_length, &olen)) != 0)
1754 char err_buf[ERROR_BUF_SIZE];
1756 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1757 log_error(LOG_LEVEL_ERROR, "mbedtls_pem_write_buffer() failed: %s",
1764 * Saving certificate information into buffer
1767 char buf[CERT_INFO_BUF_SIZE];
1769 #define CERT_INFO_PREFIX ""
1771 mbedtls_x509_crt_info(buf, sizeof(buf), CERT_INFO_PREFIX, crt);
1772 encoded_text = html_encode(buf);
1773 if (encoded_text == NULL)
1775 log_error(LOG_LEVEL_ERROR,
1776 "Failed to HTML-encode the certificate information");
1779 strlcpy(last->info_buf, encoded_text, sizeof(last->info_buf));
1780 freez(encoded_text);
1787 /*********************************************************************
1789 * Function : host_to_hash
1791 * Description : Creates MD5 hash from host name. Host name is loaded
1792 * from structure csp and saved again into it.
1795 * 1 : csp = Current client state (buffers, headers, etc...)
1797 * Returns : -1 => Error while creating hash
1798 * 0 => Hash created successfully
1800 *********************************************************************/
1801 static int host_to_hash(struct client_state *csp)
1805 #if !defined(MBEDTLS_MD5_C)
1806 #error mbedTLS needs to be compiled with md5 support
1808 memset(csp->http->hash_of_host, 0, sizeof(csp->http->hash_of_host));
1809 ret = mbedtls_md5_ret((unsigned char *)csp->http->host,
1810 strlen(csp->http->host), csp->http->hash_of_host);
1813 log_error(LOG_LEVEL_ERROR,
1814 "Failed to generate md5 hash of host %s: %d",
1815 csp->http->host, ret);
1819 /* Converting hash into string with hex */
1823 if ((ret = sprintf((char *)csp->http->hash_of_host_hex + 2 * i, "%02x",
1824 csp->http->hash_of_host[i])) < 0)
1826 log_error(LOG_LEVEL_ERROR, "Sprintf return value: %d", ret);
1832 #endif /* MBEDTLS_MD5_C */
1835 /*********************************************************************
1837 * Function : seed_rng
1839 * Description : Seeding the RNG for all SSL uses
1842 * 1 : csp = Current client state (buffers, headers, etc...)
1844 * Returns : -1 => RNG wasn't seed successfully
1845 * 0 => RNG is seeded successfully
1847 *********************************************************************/
1848 static int seed_rng(struct client_state *csp)
1851 char err_buf[ERROR_BUF_SIZE];
1853 if (rng_seeded == 0)
1855 privoxy_mutex_lock(&ssl_init_mutex);
1856 if (rng_seeded == 0)
1858 mbedtls_ctr_drbg_init(&ctr_drbg);
1859 mbedtls_entropy_init(&entropy);
1860 ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func,
1864 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1865 log_error(LOG_LEVEL_ERROR,
1866 "mbedtls_ctr_drbg_seed failed: %s", err_buf);
1867 privoxy_mutex_unlock(&ssl_init_mutex);
1872 privoxy_mutex_unlock(&ssl_init_mutex);
1878 /*********************************************************************
1880 * Function : ssl_base64_encode
1882 * Description : Encode a buffer into base64 format.
1885 * 1 : dst = Destination buffer
1886 * 2 : dlen = Destination buffer length
1887 * 3 : olen = Number of bytes written
1888 * 4 : src = Source buffer
1889 * 5 : slen = Amount of data to be encoded
1891 * Returns : 0 on success, error code othervise
1893 *********************************************************************/
1894 extern int ssl_base64_encode(unsigned char *dst, size_t dlen, size_t *olen,
1895 const unsigned char *src, size_t slen)
1897 return mbedtls_base64_encode(dst, dlen, olen, src, slen);
1901 /*********************************************************************
1903 * Function : ssl_crt_verify_info
1905 * Description : Returns an informational string about the verification
1906 * status of a certificate.
1909 * 1 : buf = Buffer to write to
1910 * 2 : size = Maximum size of buffer
1911 * 3 : csp = client state
1915 *********************************************************************/
1916 extern void ssl_crt_verify_info(char *buf, size_t size, struct client_state *csp)
1920 mbedtls_x509_crt_verify_info(buf, size, "",
1921 csp->server_cert_verification_result);
1922 last_byte = buf + strlen(buf)-1;
1923 if (*last_byte == '\n')
1925 /* Overwrite trailing new line character */
1931 #ifdef FEATURE_GRACEFUL_TERMINATION
1932 /*********************************************************************
1934 * Function : ssl_release
1936 * Description : Release all SSL resources
1942 *********************************************************************/
1943 extern void ssl_release(void)
1945 if (rng_seeded == 1)
1947 mbedtls_ctr_drbg_free(&ctr_drbg);
1948 mbedtls_entropy_free(&entropy);
1951 #endif /* def FEATURE_GRACEFUL_TERMINATION */
1954 /*********************************************************************
1956 * Function : get_ciphersuites_from_string
1958 * Description : Converts a string of ciphersuite names to
1959 * an array of ciphersuite ids.
1962 * 1 : ciphersuites_string = String containing allowed
1965 * Returns : Array of ciphersuite ids
1967 *********************************************************************/
1968 static int *get_ciphersuites_from_string(const char *parameter_string)
1970 char *ciphersuites_index;
1972 char *ciphersuites_string;
1973 int *ciphersuite_ids;
1976 const char separator = ':';
1977 size_t parameter_len = strlen(parameter_string);
1979 ciphersuites_string = zalloc_or_die(parameter_len + 1);
1980 strncpy(ciphersuites_string, parameter_string, parameter_len);
1981 ciphersuites_index = ciphersuites_string;
1983 while (*ciphersuites_index)
1985 if (*ciphersuites_index++ == separator)
1991 ciphersuite_ids = zalloc_or_die(count * sizeof(int));
1993 ciphersuites_index = ciphersuites_string;
1996 item_end = strchr(ciphersuites_index, separator);
1997 if (item_end != NULL)
2002 ciphersuite_ids[index] =
2003 mbedtls_ssl_get_ciphersuite_id(ciphersuites_index);
2004 if (ciphersuite_ids[index] == 0)
2006 log_error(LOG_LEVEL_ERROR,
2007 "Failed to get ciphersuite id for %s", ciphersuites_index);
2008 freez(ciphersuite_ids);
2009 freez(ciphersuites_string);
2012 ciphersuites_index = item_end + 1;
2014 } while (item_end != NULL);
2016 ciphersuite_ids[index] = 0;
2017 freez(ciphersuites_string);
2019 return ciphersuite_ids;