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-2021 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);
328 ret = generate_host_certificate(csp);
329 privoxy_mutex_unlock(&certificate_mutex);
333 log_error(LOG_LEVEL_ERROR,
334 "generate_host_certificate failed: %d", ret);
350 * Loading CA file, webpage certificate and key files
352 ret = mbedtls_x509_crt_parse_file(&(ssl_attr->mbedtls_attr.server_cert),
356 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
357 log_error(LOG_LEVEL_ERROR,
358 "Loading webpage certificate %s failed: %s", cert_file, err_buf);
363 ret = mbedtls_x509_crt_parse_file(&(ssl_attr->mbedtls_attr.server_cert),
367 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
368 log_error(LOG_LEVEL_ERROR,
369 "Loading CA certificate %s failed: %s", ca_file, err_buf);
374 ret = mbedtls_pk_parse_keyfile(&(ssl_attr->mbedtls_attr.prim_key),
378 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
379 log_error(LOG_LEVEL_ERROR,
380 "Loading and parsing webpage certificate private key %s failed: %s",
387 * Setting SSL parameters
389 ret = mbedtls_ssl_config_defaults(&(ssl_attr->mbedtls_attr.conf),
390 MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_TRANSPORT_STREAM,
391 MBEDTLS_SSL_PRESET_DEFAULT);
394 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
395 log_error(LOG_LEVEL_ERROR,
396 "mbedtls_ssl_config_defaults failed: %s", err_buf);
401 mbedtls_ssl_conf_rng(&(ssl_attr->mbedtls_attr.conf),
402 mbedtls_ctr_drbg_random, &ctr_drbg);
404 #if defined(MBEDTLS_SSL_CACHE_C)
405 mbedtls_ssl_conf_session_cache(&(ssl_attr->mbedtls_attr.conf),
406 &(ssl_attr->mbedtls_attr.cache), mbedtls_ssl_cache_get,
407 mbedtls_ssl_cache_set);
411 * Setting certificates
413 ret = mbedtls_ssl_conf_own_cert(&(ssl_attr->mbedtls_attr.conf),
414 &(ssl_attr->mbedtls_attr.server_cert),
415 &(ssl_attr->mbedtls_attr.prim_key));
418 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
419 log_error(LOG_LEVEL_ERROR,
420 "mbedtls_ssl_conf_own_cert failed: %s", err_buf);
425 if (csp->config->cipher_list != NULL)
427 ssl_attr->mbedtls_attr.ciphersuites_list =
428 get_ciphersuites_from_string(csp->config->cipher_list);
429 if (ssl_attr->mbedtls_attr.ciphersuites_list == NULL)
431 log_error(LOG_LEVEL_ERROR,
432 "Setting the cipher list '%s' for the client connection failed",
433 csp->config->cipher_list);
437 mbedtls_ssl_conf_ciphersuites(&(ssl_attr->mbedtls_attr.conf),
438 ssl_attr->mbedtls_attr.ciphersuites_list);
441 ret = mbedtls_ssl_setup(&(ssl_attr->mbedtls_attr.ssl),
442 &(ssl_attr->mbedtls_attr.conf));
445 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
446 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_setup failed: %s", err_buf);
451 mbedtls_ssl_set_bio(&(ssl_attr->mbedtls_attr.ssl),
452 &(ssl_attr->mbedtls_attr.socket_fd), mbedtls_net_send,
453 mbedtls_net_recv, NULL);
454 mbedtls_ssl_session_reset(&(ssl_attr->mbedtls_attr.ssl));
457 * Setting socket fd in mbedtls_net_context structure. This structure
458 * can't be set by mbedtls functions, because we already have created
459 * a TCP connection when this function is called.
461 ssl_attr->mbedtls_attr.socket_fd.fd = csp->cfd;
464 * Handshake with client
466 log_error(LOG_LEVEL_CONNECT,
467 "Performing the TLS/SSL handshake with client. Hash of host: %s",
468 csp->http->hash_of_host_hex);
469 while ((ret = mbedtls_ssl_handshake(&(ssl_attr->mbedtls_attr.ssl))) != 0)
471 if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
472 ret != MBEDTLS_ERR_SSL_WANT_WRITE)
474 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
475 log_error(LOG_LEVEL_ERROR,
476 "medtls_ssl_handshake with client failed: %s", err_buf);
482 log_error(LOG_LEVEL_CONNECT, "Client successfully connected over %s (%s).",
483 mbedtls_ssl_get_version(&(ssl_attr->mbedtls_attr.ssl)),
484 mbedtls_ssl_get_ciphersuite(&(ssl_attr->mbedtls_attr.ssl)));
486 csp->ssl_with_client_is_opened = 1;
490 * Freeing allocated paths to files
495 /* Freeing structures if connection wasn't created successfully */
498 free_client_ssl_structures(csp);
504 /*********************************************************************
506 * Function : close_client_ssl_connection
508 * Description : Closes TLS/SSL connection with client. This function
509 * checks if this connection is already created.
512 * 1 : csp = Current client state (buffers, headers, etc...)
516 *********************************************************************/
517 extern void close_client_ssl_connection(struct client_state *csp)
519 struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
522 if (csp->ssl_with_client_is_opened == 0)
528 * Notifying the peer that the connection is being closed.
531 ret = mbedtls_ssl_close_notify(&(ssl_attr->mbedtls_attr.ssl));
532 } while (ret == MBEDTLS_ERR_SSL_WANT_WRITE);
534 free_client_ssl_structures(csp);
535 csp->ssl_with_client_is_opened = 0;
539 /*********************************************************************
541 * Function : free_client_ssl_structures
543 * Description : Frees structures used for SSL communication with
547 * 1 : csp = Current client state (buffers, headers, etc...)
551 *********************************************************************/
552 static void free_client_ssl_structures(struct client_state *csp)
554 struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
556 * We can't use function mbedtls_net_free, because this function
557 * inter alia close TCP connection on set fd. Instead of this
558 * function, we change fd to -1, which is the same what does
559 * rest of mbedtls_net_free function.
561 ssl_attr->mbedtls_attr.socket_fd.fd = -1;
563 /* Freeing mbedtls structures */
564 mbedtls_x509_crt_free(&(ssl_attr->mbedtls_attr.server_cert));
565 mbedtls_pk_free(&(ssl_attr->mbedtls_attr.prim_key));
566 mbedtls_ssl_free(&(ssl_attr->mbedtls_attr.ssl));
567 freez(ssl_attr->mbedtls_attr.ciphersuites_list);
568 mbedtls_ssl_config_free(&(ssl_attr->mbedtls_attr.conf));
569 #if defined(MBEDTLS_SSL_CACHE_C)
570 mbedtls_ssl_cache_free(&(ssl_attr->mbedtls_attr.cache));
575 /*********************************************************************
577 * Function : create_server_ssl_connection
579 * Description : Creates TLS/SSL secured connection with server.
582 * 1 : csp = Current client state (buffers, headers, etc...)
584 * Returns : 0 on success, negative value if connection wasn't created
587 *********************************************************************/
588 extern int create_server_ssl_connection(struct client_state *csp)
590 struct ssl_attr *ssl_attr = &csp->ssl_server_attr;
592 char err_buf[ERROR_BUF_SIZE];
593 char *trusted_cas_file = NULL;
594 int auth_mode = MBEDTLS_SSL_VERIFY_REQUIRED;
596 csp->server_cert_verification_result = SSL_CERT_NOT_VERIFIED;
597 csp->server_certs_chain.next = NULL;
599 /* Setting path to file with trusted CAs */
600 trusted_cas_file = csp->config->trusted_cas_file;
603 * Initializing mbedtls structures for TLS/SSL connection
605 mbedtls_net_init(&(ssl_attr->mbedtls_attr.socket_fd));
606 mbedtls_ssl_init(&(ssl_attr->mbedtls_attr.ssl));
607 mbedtls_ssl_config_init(&(ssl_attr->mbedtls_attr.conf));
608 mbedtls_x509_crt_init(&(ssl_attr->mbedtls_attr.ca_cert));
611 * Setting socket fd in mbedtls_net_context structure. This structure
612 * can't be set by mbedtls functions, because we already have created
613 * TCP connection when calling this function.
615 ssl_attr->mbedtls_attr.socket_fd.fd = csp->server_connection.sfd;
628 * Loading file with trusted CAs
630 ret = mbedtls_x509_crt_parse_file(&(ssl_attr->mbedtls_attr.ca_cert),
634 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
635 log_error(LOG_LEVEL_ERROR, "Loading trusted CAs file %s failed: %s",
636 trusted_cas_file, err_buf);
642 * Set TLS/SSL options
644 ret = mbedtls_ssl_config_defaults(&(ssl_attr->mbedtls_attr.conf),
645 MBEDTLS_SSL_IS_CLIENT,
646 MBEDTLS_SSL_TRANSPORT_STREAM,
647 MBEDTLS_SSL_PRESET_DEFAULT);
650 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
651 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_config_defaults failed: %s",
658 * Setting how strict should certificate verification be and other
659 * parameters for certificate verification
661 if (csp->dont_verify_certificate)
663 auth_mode = MBEDTLS_SSL_VERIFY_NONE;
666 mbedtls_ssl_conf_authmode(&(ssl_attr->mbedtls_attr.conf), auth_mode);
667 mbedtls_ssl_conf_ca_chain(&(ssl_attr->mbedtls_attr.conf),
668 &(ssl_attr->mbedtls_attr.ca_cert), NULL);
670 /* Setting callback function for certificates verification */
671 mbedtls_ssl_conf_verify(&(ssl_attr->mbedtls_attr.conf),
672 ssl_verify_callback, (void *)csp);
674 mbedtls_ssl_conf_rng(&(ssl_attr->mbedtls_attr.conf),
675 mbedtls_ctr_drbg_random, &ctr_drbg);
677 if (csp->config->cipher_list != NULL)
679 ssl_attr->mbedtls_attr.ciphersuites_list =
680 get_ciphersuites_from_string(csp->config->cipher_list);
681 if (ssl_attr->mbedtls_attr.ciphersuites_list == NULL)
683 log_error(LOG_LEVEL_ERROR,
684 "Setting the cipher list '%s' for the server connection failed",
685 csp->config->cipher_list);
689 mbedtls_ssl_conf_ciphersuites(&(ssl_attr->mbedtls_attr.conf),
690 ssl_attr->mbedtls_attr.ciphersuites_list);
693 ret = mbedtls_ssl_setup(&(ssl_attr->mbedtls_attr.ssl),
694 &(ssl_attr->mbedtls_attr.conf));
697 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
698 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_setup failed: %s", err_buf);
704 * Set the hostname to check against the received server certificate
706 ret = mbedtls_ssl_set_hostname(&(ssl_attr->mbedtls_attr.ssl),
710 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
711 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_set_hostname failed: %s",
717 mbedtls_ssl_set_bio(&(ssl_attr->mbedtls_attr.ssl),
718 &(ssl_attr->mbedtls_attr.socket_fd), mbedtls_net_send,
719 mbedtls_net_recv, NULL);
722 * Handshake with server
724 log_error(LOG_LEVEL_CONNECT,
725 "Performing the TLS/SSL handshake with the server");
727 while ((ret = mbedtls_ssl_handshake(&(ssl_attr->mbedtls_attr.ssl))) != 0)
729 if (ret != MBEDTLS_ERR_SSL_WANT_READ
730 && ret != MBEDTLS_ERR_SSL_WANT_WRITE)
732 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
734 if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED)
736 char reason[INVALID_CERT_INFO_BUF_SIZE];
738 csp->server_cert_verification_result =
739 mbedtls_ssl_get_verify_result(&(ssl_attr->mbedtls_attr.ssl));
740 mbedtls_x509_crt_verify_info(reason, sizeof(reason), "",
741 csp->server_cert_verification_result);
743 /* Log the reason without the trailing new line */
744 log_error(LOG_LEVEL_ERROR,
745 "X509 certificate verification for %s failed: %N",
746 csp->http->hostport, strlen(reason)-1, reason);
751 log_error(LOG_LEVEL_ERROR,
752 "mbedtls_ssl_handshake with server failed: %s", err_buf);
753 free_certificate_chain(csp);
760 log_error(LOG_LEVEL_CONNECT, "Server successfully connected over %s (%s).",
761 mbedtls_ssl_get_version(&(ssl_attr->mbedtls_attr.ssl)),
762 mbedtls_ssl_get_ciphersuite(&(ssl_attr->mbedtls_attr.ssl)));
765 * Server certificate chain is valid, so we can clean
766 * chain, because we will not send it to client.
768 free_certificate_chain(csp);
770 csp->ssl_with_server_is_opened = 1;
771 csp->server_cert_verification_result =
772 mbedtls_ssl_get_verify_result(&(ssl_attr->mbedtls_attr.ssl));
775 /* Freeing structures if connection wasn't created successfully */
778 free_server_ssl_structures(csp);
785 /*********************************************************************
787 * Function : close_server_ssl_connection
789 * Description : Closes TLS/SSL connection with server. This function
790 * checks if this connection is already opened.
793 * 1 : csp = Current client state (buffers, headers, etc...)
797 *********************************************************************/
798 extern void close_server_ssl_connection(struct client_state *csp)
800 struct ssl_attr *ssl_attr = &csp->ssl_server_attr;
803 if (csp->ssl_with_server_is_opened == 0)
809 * Notifying the peer that the connection is being closed.
812 ret = mbedtls_ssl_close_notify(&(ssl_attr->mbedtls_attr.ssl));
813 } while (ret == MBEDTLS_ERR_SSL_WANT_WRITE);
815 free_server_ssl_structures(csp);
816 csp->ssl_with_server_is_opened = 0;
820 /*********************************************************************
822 * Function : free_server_ssl_structures
824 * Description : Frees structures used for SSL communication with server
827 * 1 : csp = Current client state (buffers, headers, etc...)
831 *********************************************************************/
832 static void free_server_ssl_structures(struct client_state *csp)
834 struct ssl_attr *ssl_attr = &csp->ssl_server_attr;
836 * We can't use function mbedtls_net_free, because this function
837 * inter alia close TCP connection on set fd. Instead of this
838 * function, we change fd to -1, which is the same what does
839 * rest of mbedtls_net_free function.
841 ssl_attr->mbedtls_attr.socket_fd.fd = -1;
843 mbedtls_x509_crt_free(&(ssl_attr->mbedtls_attr.ca_cert));
844 mbedtls_ssl_free(&(ssl_attr->mbedtls_attr.ssl));
845 freez(ssl_attr->mbedtls_attr.ciphersuites_list);
846 mbedtls_ssl_config_free(&(ssl_attr->mbedtls_attr.conf));
850 /*====================== Certificates ======================*/
852 /*********************************************************************
854 * Function : write_certificate
856 * Description : Writes certificate into file.
859 * 1 : crt = certificate to write into file
860 * 2 : output_file = path to save certificate file
861 * 3 : f_rng = mbedtls_ctr_drbg_random
862 * 4 : p_rng = mbedtls_ctr_drbg_context
864 * Returns : Length of written certificate on success or negative value
867 *********************************************************************/
868 static int write_certificate(mbedtls_x509write_cert *crt, const char *output_file,
869 int(*f_rng)(void *, unsigned char *, size_t), void *p_rng)
873 unsigned char cert_buf[CERTIFICATE_BUF_SIZE + 1]; /* Buffer for certificate in PEM format + terminating NULL */
875 char err_buf[ERROR_BUF_SIZE];
877 memset(cert_buf, 0, sizeof(cert_buf));
880 * Writing certificate into PEM string. If buffer is too small, function
881 * returns specific error and no buffer overflow can happen.
883 if ((ret = mbedtls_x509write_crt_pem(crt, cert_buf,
884 sizeof(cert_buf) - 1, f_rng, p_rng)) != 0)
886 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
887 log_error(LOG_LEVEL_ERROR,
888 "Writing certificate into buffer failed: %s", err_buf);
892 len = strlen((char *)cert_buf);
895 * Saving certificate into file
897 if ((f = fopen(output_file, "w")) == NULL)
899 log_error(LOG_LEVEL_ERROR, "Opening file %s to save certificate failed",
904 if (fwrite(cert_buf, 1, len, f) != len)
906 log_error(LOG_LEVEL_ERROR,
907 "Writing certificate into file %s failed", output_file);
918 /*********************************************************************
920 * Function : write_private_key
922 * Description : Writes private key into file and copies saved
923 * content into given pointer to string. If function
924 * returns 0 for success, this copy must be freed by
928 * 1 : key = key to write into file
929 * 2 : ret_buf = pointer to string with created key file content
930 * 3 : key_file_path = path where to save key file
932 * Returns : Length of written private key on success or negative value
935 *********************************************************************/
936 static int write_private_key(mbedtls_pk_context *key, unsigned char **ret_buf,
937 const char *key_file_path)
939 size_t len = 0; /* Length of created key */
940 FILE *f = NULL; /* File to save certificate */
942 char err_buf[ERROR_BUF_SIZE];
944 /* Initializing buffer for key file content */
945 *ret_buf = zalloc_or_die(PRIVATE_KEY_BUF_SIZE + 1);
948 * Writing private key into PEM string
950 if ((ret = mbedtls_pk_write_key_pem(key, *ret_buf, PRIVATE_KEY_BUF_SIZE)) != 0)
952 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
953 log_error(LOG_LEVEL_ERROR,
954 "Writing private key into PEM string failed: %s", err_buf);
958 len = strlen((char *)*ret_buf);
961 * Saving key into file
963 if ((f = fopen(key_file_path, "wb")) == NULL)
965 log_error(LOG_LEVEL_ERROR,
966 "Opening file %s to save private key failed: %E",
972 if (fwrite(*ret_buf, 1, len, f) != len)
975 log_error(LOG_LEVEL_ERROR,
976 "Writing private key into file %s failed",
995 /*********************************************************************
997 * Function : generate_key
999 * Description : Tests if private key for host saved in csp already
1000 * exists. If this file doesn't exists, a new key is
1001 * generated and saved in a file. The generated key is also
1002 * copied into given parameter key_buf, which must be then
1003 * freed by caller. If file with key exists, key_buf
1004 * contain NULL and no private key is generated.
1007 * 1 : csp = Current client state (buffers, headers, etc...)
1008 * 2 : key_buf = buffer to save new generated key
1010 * Returns : -1 => Error while generating private key
1011 * 0 => Key already exists
1012 * >0 => Length of generated private key
1014 *********************************************************************/
1015 static int generate_key(struct client_state *csp, unsigned char **key_buf)
1017 mbedtls_pk_context key;
1018 key_options key_opt;
1020 char err_buf[ERROR_BUF_SIZE];
1022 key_opt.key_file_path = NULL;
1025 * Initializing structures for key generating
1027 mbedtls_pk_init(&key);
1030 * Preparing path for key file and other properties for generating key
1032 key_opt.type = MBEDTLS_PK_RSA;
1033 key_opt.rsa_keysize = RSA_KEYSIZE;
1035 key_opt.key_file_path = make_certs_path(csp->config->certificate_directory,
1036 (char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
1037 if (key_opt.key_file_path == NULL)
1044 * Test if key already exists. If so, we don't have to create it again.
1046 if (file_exists(key_opt.key_file_path) == 1)
1055 ret = seed_rng(csp);
1063 * Setting attributes of private key and generating it
1065 if ((ret = mbedtls_pk_setup(&key,
1066 mbedtls_pk_info_from_type(key_opt.type))) != 0)
1068 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1069 log_error(LOG_LEVEL_ERROR, "mbedtls_pk_setup failed: %s", err_buf);
1074 ret = mbedtls_rsa_gen_key(mbedtls_pk_rsa(key), mbedtls_ctr_drbg_random,
1075 &ctr_drbg, (unsigned)key_opt.rsa_keysize, RSA_KEY_PUBLIC_EXPONENT);
1078 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1079 log_error(LOG_LEVEL_ERROR, "Key generating failed: %s", err_buf);
1085 * Exporting private key into file
1087 if ((ret = write_private_key(&key, key_buf, key_opt.key_file_path)) < 0)
1089 log_error(LOG_LEVEL_ERROR,
1090 "Writing private key into file %s failed", key_opt.key_file_path);
1097 * Freeing used variables
1099 freez(key_opt.key_file_path);
1101 mbedtls_pk_free(&key);
1107 /*********************************************************************
1109 * Function : ssl_certificate_is_invalid
1111 * Description : Checks whether or not a certificate is valid.
1112 * Currently only checks that the certificate can be
1113 * parsed and that the "valid to" date is in the future.
1116 * 1 : cert_file = The certificate to check
1118 * Returns : 0 => The certificate is valid.
1119 * 1 => The certificate is invalid
1121 *********************************************************************/
1122 static int ssl_certificate_is_invalid(const char *cert_file)
1124 mbedtls_x509_crt cert;
1127 mbedtls_x509_crt_init(&cert);
1129 ret = mbedtls_x509_crt_parse_file(&cert, cert_file);
1132 char err_buf[ERROR_BUF_SIZE];
1134 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1135 log_error(LOG_LEVEL_ERROR,
1136 "Loading certificate %s to check validity failed: %s",
1137 cert_file, err_buf);
1138 mbedtls_x509_crt_free(&cert);
1142 if (mbedtls_x509_time_is_past(&cert.valid_to))
1144 mbedtls_x509_crt_free(&cert);
1149 mbedtls_x509_crt_free(&cert);
1156 /*********************************************************************
1158 * Function : set_subject_alternative_name
1160 * Description : Sets the Subject Alternative Name extension to a cert
1163 * 1 : cert = The certificate to modify
1164 * 2 : hostname = The hostname to add
1166 * Returns : <0 => Error while creating certificate.
1169 *********************************************************************/
1170 static int set_subject_alternative_name(mbedtls_x509write_cert *cert, const char *hostname)
1172 char err_buf[ERROR_BUF_SIZE];
1174 char *subject_alternative_name;
1175 size_t subject_alternative_name_len;
1176 #define MBEDTLS_SUBJECT_ALTERNATIVE_NAME_MAX_LEN 255
1177 unsigned char san_buf[MBEDTLS_SUBJECT_ALTERNATIVE_NAME_MAX_LEN + 1];
1181 subject_alternative_name_len = strlen(hostname) + 1;
1182 subject_alternative_name = zalloc_or_die(subject_alternative_name_len);
1184 strlcpy(subject_alternative_name, hostname, subject_alternative_name_len);
1186 memset(san_buf, 0, sizeof(san_buf));
1188 c = san_buf + sizeof(san_buf);
1191 ret = mbedtls_asn1_write_raw_buffer(&c, san_buf,
1192 (const unsigned char *)subject_alternative_name,
1193 strlen(subject_alternative_name));
1196 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1197 log_error(LOG_LEVEL_ERROR,
1198 "mbedtls_asn1_write_raw_buffer() failed: %s", err_buf);
1203 ret = mbedtls_asn1_write_len(&c, san_buf, strlen(subject_alternative_name));
1206 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1207 log_error(LOG_LEVEL_ERROR,
1208 "mbedtls_asn1_write_len() failed: %s", err_buf);
1213 ret = mbedtls_asn1_write_tag(&c, san_buf, MBEDTLS_ASN1_CONTEXT_SPECIFIC | 2);
1216 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1217 log_error(LOG_LEVEL_ERROR,
1218 "mbedtls_asn1_write_tag() failed: %s", err_buf);
1223 ret = mbedtls_asn1_write_len(&c, san_buf, (size_t)len);
1226 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1227 log_error(LOG_LEVEL_ERROR,
1228 "mbedtls_asn1_write_len() failed: %s", err_buf);
1233 ret = mbedtls_asn1_write_tag(&c, san_buf,
1234 MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE);
1237 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1238 log_error(LOG_LEVEL_ERROR,
1239 "mbedtls_asn1_write_tag() failed: %s", err_buf);
1244 ret = mbedtls_x509write_crt_set_extension(cert,
1245 MBEDTLS_OID_SUBJECT_ALT_NAME,
1246 MBEDTLS_OID_SIZE(MBEDTLS_OID_SUBJECT_ALT_NAME),
1247 0, san_buf + sizeof(san_buf) - len, (size_t)len);
1250 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1251 log_error(LOG_LEVEL_ERROR,
1252 "mbedtls_x509write_crt_set_extension() failed: %s", err_buf);
1256 freez(subject_alternative_name);
1263 /*********************************************************************
1265 * Function : generate_host_certificate
1267 * Description : Creates certificate file in presetted directory.
1268 * If certificate already exists, no other certificate
1269 * will be created. Subject of certificate is named
1270 * by csp->http->host from parameter. This function also
1271 * triggers generating of private key for new certificate.
1274 * 1 : csp = Current client state (buffers, headers, etc...)
1276 * Returns : -1 => Error while creating certificate.
1277 * 0 => Certificate already exists.
1278 * >0 => Length of created certificate.
1280 *********************************************************************/
1281 static int generate_host_certificate(struct client_state *csp)
1283 mbedtls_x509_crt issuer_cert;
1284 mbedtls_pk_context loaded_issuer_key, loaded_subject_key;
1285 mbedtls_pk_context *issuer_key = &loaded_issuer_key;
1286 mbedtls_pk_context *subject_key = &loaded_subject_key;
1287 mbedtls_x509write_cert cert;
1290 unsigned char *key_buf = NULL; /* Buffer for created key */
1293 char err_buf[ERROR_BUF_SIZE];
1294 cert_options cert_opt;
1295 char cert_valid_from[VALID_DATETIME_BUFLEN];
1296 char cert_valid_to[VALID_DATETIME_BUFLEN];
1298 /* Paths to keys and certificates needed to create certificate */
1299 cert_opt.issuer_key = NULL;
1300 cert_opt.subject_key = NULL;
1301 cert_opt.issuer_crt = NULL;
1303 cert_opt.output_file = make_certs_path(csp->config->certificate_directory,
1304 (const char *)csp->http->hash_of_host_hex, CERT_FILE_TYPE);
1305 if (cert_opt.output_file == NULL)
1310 cert_opt.subject_key = make_certs_path(csp->config->certificate_directory,
1311 (const char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
1312 if (cert_opt.subject_key == NULL)
1314 freez(cert_opt.output_file);
1318 if (enforce_sane_certificate_state(cert_opt.output_file,
1319 cert_opt.subject_key))
1321 freez(cert_opt.output_file);
1322 freez(cert_opt.subject_key);
1327 if (file_exists(cert_opt.output_file) == 1)
1329 /* The file exists, but is it valid? */
1330 if (ssl_certificate_is_invalid(cert_opt.output_file))
1332 log_error(LOG_LEVEL_CONNECT,
1333 "Certificate %s is no longer valid. Removing it.",
1334 cert_opt.output_file);
1335 if (unlink(cert_opt.output_file))
1337 log_error(LOG_LEVEL_ERROR, "Failed to unlink %s: %E",
1338 cert_opt.output_file);
1340 freez(cert_opt.output_file);
1341 freez(cert_opt.subject_key);
1345 if (unlink(cert_opt.subject_key))
1347 log_error(LOG_LEVEL_ERROR, "Failed to unlink %s: %E",
1348 cert_opt.subject_key);
1350 freez(cert_opt.output_file);
1351 freez(cert_opt.subject_key);
1358 freez(cert_opt.output_file);
1359 freez(cert_opt.subject_key);
1366 * Create key for requested host
1368 int subject_key_len = generate_key(csp, &key_buf);
1369 if (subject_key_len < 0)
1371 freez(cert_opt.output_file);
1372 freez(cert_opt.subject_key);
1373 log_error(LOG_LEVEL_ERROR, "Key generating failed");
1378 * Initializing structures for certificate generating
1380 mbedtls_x509write_crt_init(&cert);
1381 mbedtls_x509write_crt_set_md_alg(&cert, CERT_SIGNATURE_ALGORITHM);
1382 mbedtls_pk_init(&loaded_issuer_key);
1383 mbedtls_pk_init(&loaded_subject_key);
1384 mbedtls_mpi_init(&serial);
1385 mbedtls_x509_crt_init(&issuer_cert);
1388 * Presetting parameters for certificate. We must compute total length
1391 size_t cert_params_len = strlen(CERT_PARAM_COMMON_NAME) +
1392 strlen(CERT_PARAM_ORGANIZATION) + strlen(CERT_PARAM_COUNTRY) +
1393 strlen(CERT_PARAM_ORG_UNIT) +
1394 3 * strlen(csp->http->host) + 1;
1395 char cert_params[cert_params_len];
1396 memset(cert_params, 0, cert_params_len);
1399 * Converting unsigned long serial number to char * serial number.
1400 * We must compute length of serial number in string + terminating null.
1402 unsigned long certificate_serial = get_certificate_serial(csp);
1403 unsigned long certificate_serial_time = (unsigned long)time(NULL);
1404 int serial_num_size = snprintf(NULL, 0, "%lu%lu",
1405 certificate_serial_time, certificate_serial) + 1;
1406 if (serial_num_size <= 0)
1408 serial_num_size = 1;
1411 char serial_num_text[serial_num_size]; /* Buffer for serial number */
1412 ret = snprintf(serial_num_text, (size_t)serial_num_size, "%lu%lu",
1413 certificate_serial_time, certificate_serial);
1414 if (ret < 0 || ret >= serial_num_size)
1416 log_error(LOG_LEVEL_ERROR,
1417 "Converting certificate serial number into string failed");
1423 * Preparing parameters for certificate
1425 strlcpy(cert_params, CERT_PARAM_COMMON_NAME, cert_params_len);
1426 strlcat(cert_params, csp->http->host, cert_params_len);
1427 strlcat(cert_params, CERT_PARAM_ORGANIZATION, cert_params_len);
1428 strlcat(cert_params, csp->http->host, cert_params_len);
1429 strlcat(cert_params, CERT_PARAM_ORG_UNIT, cert_params_len);
1430 strlcat(cert_params, csp->http->host, cert_params_len);
1431 strlcat(cert_params, CERT_PARAM_COUNTRY, cert_params_len);
1433 cert_opt.issuer_crt = csp->config->ca_cert_file;
1434 cert_opt.issuer_key = csp->config->ca_key_file;
1436 if (get_certificate_valid_from_date(cert_valid_from, sizeof(cert_valid_from), VALID_DATETIME_FMT)
1437 || get_certificate_valid_to_date(cert_valid_to, sizeof(cert_valid_to), VALID_DATETIME_FMT))
1439 log_error(LOG_LEVEL_ERROR, "Generating one of the validity dates failed");
1444 cert_opt.subject_pwd = CERT_SUBJECT_PASSWORD;
1445 cert_opt.issuer_pwd = csp->config->ca_password;
1446 cert_opt.subject_name = cert_params;
1447 cert_opt.not_before = cert_valid_from;
1448 cert_opt.not_after = cert_valid_to;
1449 cert_opt.serial = serial_num_text;
1451 cert_opt.max_pathlen = -1;
1454 * Test if the private key was already created.
1455 * XXX: Can this still happen?
1457 if (subject_key_len == 0)
1459 log_error(LOG_LEVEL_ERROR, "Subject key was already created");
1467 ret = seed_rng(csp);
1475 * Parse serial to MPI
1477 ret = mbedtls_mpi_read_string(&serial, 10, cert_opt.serial);
1480 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1481 log_error(LOG_LEVEL_ERROR,
1482 "mbedtls_mpi_read_string failed: %s", err_buf);
1488 * Loading certificates
1490 ret = mbedtls_x509_crt_parse_file(&issuer_cert, cert_opt.issuer_crt);
1493 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1494 log_error(LOG_LEVEL_ERROR, "Loading issuer certificate %s failed: %s",
1495 cert_opt.issuer_crt, err_buf);
1500 ret = mbedtls_x509_dn_gets(cert_opt.issuer_name,
1501 sizeof(cert_opt.issuer_name), &issuer_cert.subject);
1504 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1505 log_error(LOG_LEVEL_ERROR, "mbedtls_x509_dn_gets failed: %s", err_buf);
1511 * Loading keys from file or from buffer
1513 if (key_buf != NULL && subject_key_len > 0)
1515 /* Key was created in this function and is stored in buffer */
1516 ret = mbedtls_pk_parse_key(&loaded_subject_key, key_buf,
1517 (size_t)(subject_key_len + 1), (unsigned const char *)
1518 cert_opt.subject_pwd, strlen(cert_opt.subject_pwd));
1522 /* Key wasn't created in this function, because it already existed */
1523 ret = mbedtls_pk_parse_keyfile(&loaded_subject_key,
1524 cert_opt.subject_key, cert_opt.subject_pwd);
1529 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1530 log_error(LOG_LEVEL_ERROR, "Parsing subject key %s failed: %s",
1531 cert_opt.subject_key, err_buf);
1536 ret = mbedtls_pk_parse_keyfile(&loaded_issuer_key, cert_opt.issuer_key,
1537 cert_opt.issuer_pwd);
1540 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1541 log_error(LOG_LEVEL_ERROR,
1542 "Parsing issuer key %s failed: %s", cert_opt.issuer_key, err_buf);
1548 * Check if key and issuer certificate match
1550 if (!mbedtls_pk_can_do(&issuer_cert.pk, MBEDTLS_PK_RSA) ||
1551 mbedtls_mpi_cmp_mpi(&mbedtls_pk_rsa(issuer_cert.pk)->N,
1552 &mbedtls_pk_rsa(*issuer_key)->N) != 0 ||
1553 mbedtls_mpi_cmp_mpi(&mbedtls_pk_rsa(issuer_cert.pk)->E,
1554 &mbedtls_pk_rsa(*issuer_key)->E) != 0)
1556 log_error(LOG_LEVEL_ERROR,
1557 "Issuer key doesn't match issuer certificate");
1562 mbedtls_x509write_crt_set_subject_key(&cert, subject_key);
1563 mbedtls_x509write_crt_set_issuer_key(&cert, issuer_key);
1566 * Setting parameters of signed certificate
1568 ret = mbedtls_x509write_crt_set_subject_name(&cert, cert_opt.subject_name);
1571 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1572 log_error(LOG_LEVEL_ERROR,
1573 "Setting subject name in signed certificate failed: %s", err_buf);
1578 ret = mbedtls_x509write_crt_set_issuer_name(&cert, cert_opt.issuer_name);
1581 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1582 log_error(LOG_LEVEL_ERROR,
1583 "Setting issuer name in signed certificate failed: %s", err_buf);
1588 ret = mbedtls_x509write_crt_set_serial(&cert, &serial);
1591 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1592 log_error(LOG_LEVEL_ERROR,
1593 "Setting serial number in signed certificate failed: %s", err_buf);
1598 ret = mbedtls_x509write_crt_set_validity(&cert, cert_opt.not_before,
1599 cert_opt.not_after);
1602 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1603 log_error(LOG_LEVEL_ERROR,
1604 "Setting validity in signed certificate failed: %s", err_buf);
1610 * Setting the basicConstraints extension for certificate
1612 ret = mbedtls_x509write_crt_set_basic_constraints(&cert, cert_opt.is_ca,
1613 cert_opt.max_pathlen);
1616 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1617 log_error(LOG_LEVEL_ERROR, "Setting the basicConstraints extension "
1618 "in signed certificate failed: %s", err_buf);
1623 #if defined(MBEDTLS_SHA1_C)
1624 /* Setting the subjectKeyIdentifier extension for certificate */
1625 ret = mbedtls_x509write_crt_set_subject_key_identifier(&cert);
1628 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1629 log_error(LOG_LEVEL_ERROR, "mbedtls_x509write_crt_set_subject_key_"
1630 "identifier failed: %s", err_buf);
1635 /* Setting the authorityKeyIdentifier extension for certificate */
1636 ret = mbedtls_x509write_crt_set_authority_key_identifier(&cert);
1639 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1640 log_error(LOG_LEVEL_ERROR, "mbedtls_x509write_crt_set_authority_key_"
1641 "identifier failed: %s", err_buf);
1645 #endif /* MBEDTLS_SHA1_C */
1647 if (!host_is_ip_address(csp->http->host) &&
1648 set_subject_alternative_name(&cert, csp->http->host))
1650 /* Errors are already logged by set_subject_alternative_name() */
1656 * Writing certificate into file
1658 ret = write_certificate(&cert, cert_opt.output_file,
1659 mbedtls_ctr_drbg_random, &ctr_drbg);
1662 log_error(LOG_LEVEL_ERROR, "Writing certificate into file failed");
1668 * Freeing used structures
1670 mbedtls_x509write_crt_free(&cert);
1671 mbedtls_pk_free(&loaded_subject_key);
1672 mbedtls_pk_free(&loaded_issuer_key);
1673 mbedtls_mpi_free(&serial);
1674 mbedtls_x509_crt_free(&issuer_cert);
1676 freez(cert_opt.subject_key);
1677 freez(cert_opt.output_file);
1683 /*********************************************************************
1685 * Function : ssl_verify_callback
1687 * Description : This is a callback function for certificate verification.
1688 * It's called once for each certificate in the server's
1689 * certificate trusted chain and prepares information about
1690 * the certificate. The information can be used to inform
1691 * the user about invalid certificates.
1694 * 1 : csp_void = Current client state (buffers, headers, etc...)
1695 * 2 : crt = certificate from trusted chain
1696 * 3 : depth = depth in trusted chain
1697 * 4 : flags = certificate flags
1699 * Returns : 0 on success and negative value on error
1701 *********************************************************************/
1702 static int ssl_verify_callback(void *csp_void, mbedtls_x509_crt *crt,
1703 int depth, uint32_t *flags)
1705 struct client_state *csp = (struct client_state *)csp_void;
1706 struct certs_chain *last = &(csp->server_certs_chain);
1709 size_t pem_buffer_length;
1712 * Searching for last item in certificates linked list
1714 while (last->next != NULL)
1720 * Preparing next item in linked list for next certificate
1722 last->next = malloc_or_die(sizeof(struct certs_chain));
1723 last->next->next = NULL;
1724 memset(last->next->info_buf, 0, sizeof(last->next->info_buf));
1725 last->next->file_buf = NULL;
1727 ret = mbedtls_pem_write_buffer(PEM_BEGIN_CRT, PEM_END_CRT, crt->raw.p,
1728 crt->raw.len, NULL, 0, &olen);
1729 if (MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL != ret)
1731 log_error(LOG_LEVEL_ERROR,
1732 "Failed to figure out the required X509 PEM certificate buffer size");
1735 pem_buffer_length = olen;
1737 last->file_buf = malloc(pem_buffer_length);
1738 if (last->file_buf == NULL)
1740 log_error(LOG_LEVEL_ERROR,
1741 "Failed to allocate %lu bytes to store the X509 PEM certificate",
1747 * Saving certificate file into buffer
1749 if ((ret = mbedtls_pem_write_buffer(PEM_BEGIN_CRT, PEM_END_CRT,
1750 crt->raw.p, crt->raw.len, (unsigned char *)last->file_buf,
1751 pem_buffer_length, &olen)) != 0)
1753 char err_buf[ERROR_BUF_SIZE];
1755 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1756 log_error(LOG_LEVEL_ERROR, "mbedtls_pem_write_buffer() failed: %s",
1763 * Saving certificate information into buffer
1766 char buf[CERT_INFO_BUF_SIZE];
1768 #define CERT_INFO_PREFIX ""
1770 mbedtls_x509_crt_info(buf, sizeof(buf), CERT_INFO_PREFIX, crt);
1771 encoded_text = html_encode(buf);
1772 if (encoded_text == NULL)
1774 log_error(LOG_LEVEL_ERROR,
1775 "Failed to HTML-encode the certificate information");
1778 strlcpy(last->info_buf, encoded_text, sizeof(last->info_buf));
1779 freez(encoded_text);
1786 /*********************************************************************
1788 * Function : host_to_hash
1790 * Description : Creates MD5 hash from host name. Host name is loaded
1791 * from structure csp and saved again into it.
1794 * 1 : csp = Current client state (buffers, headers, etc...)
1796 * Returns : -1 => Error while creating hash
1797 * 0 => Hash created successfully
1799 *********************************************************************/
1800 static int host_to_hash(struct client_state *csp)
1804 #if !defined(MBEDTLS_MD5_C)
1805 #error mbedTLS needs to be compiled with md5 support
1807 memset(csp->http->hash_of_host, 0, sizeof(csp->http->hash_of_host));
1808 ret = mbedtls_md5_ret((unsigned char *)csp->http->host,
1809 strlen(csp->http->host), csp->http->hash_of_host);
1812 log_error(LOG_LEVEL_ERROR,
1813 "Failed to generate md5 hash of host %s: %d",
1814 csp->http->host, ret);
1818 /* Converting hash into string with hex */
1822 if ((ret = sprintf((char *)csp->http->hash_of_host_hex + 2 * i, "%02x",
1823 csp->http->hash_of_host[i])) < 0)
1825 log_error(LOG_LEVEL_ERROR, "Sprintf return value: %d", ret);
1831 #endif /* MBEDTLS_MD5_C */
1834 /*********************************************************************
1836 * Function : seed_rng
1838 * Description : Seeding the RNG for all SSL uses
1841 * 1 : csp = Current client state (buffers, headers, etc...)
1843 * Returns : -1 => RNG wasn't seed successfully
1844 * 0 => RNG is seeded successfully
1846 *********************************************************************/
1847 static int seed_rng(struct client_state *csp)
1850 char err_buf[ERROR_BUF_SIZE];
1852 if (rng_seeded == 0)
1854 privoxy_mutex_lock(&ssl_init_mutex);
1855 if (rng_seeded == 0)
1857 mbedtls_ctr_drbg_init(&ctr_drbg);
1858 mbedtls_entropy_init(&entropy);
1859 ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func,
1863 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1864 log_error(LOG_LEVEL_ERROR,
1865 "mbedtls_ctr_drbg_seed failed: %s", err_buf);
1866 privoxy_mutex_unlock(&ssl_init_mutex);
1871 privoxy_mutex_unlock(&ssl_init_mutex);
1877 /*********************************************************************
1879 * Function : ssl_base64_encode
1881 * Description : Encode a buffer into base64 format.
1884 * 1 : dst = Destination buffer
1885 * 2 : dlen = Destination buffer length
1886 * 3 : olen = Number of bytes written
1887 * 4 : src = Source buffer
1888 * 5 : slen = Amount of data to be encoded
1890 * Returns : 0 on success, error code othervise
1892 *********************************************************************/
1893 extern int ssl_base64_encode(unsigned char *dst, size_t dlen, size_t *olen,
1894 const unsigned char *src, size_t slen)
1896 return mbedtls_base64_encode(dst, dlen, olen, src, slen);
1900 /*********************************************************************
1902 * Function : ssl_crt_verify_info
1904 * Description : Returns an informational string about the verification
1905 * status of a certificate.
1908 * 1 : buf = Buffer to write to
1909 * 2 : size = Maximum size of buffer
1910 * 3 : csp = client state
1914 *********************************************************************/
1915 extern void ssl_crt_verify_info(char *buf, size_t size, struct client_state *csp)
1919 mbedtls_x509_crt_verify_info(buf, size, "",
1920 csp->server_cert_verification_result);
1921 last_byte = buf + strlen(buf)-1;
1922 if (*last_byte == '\n')
1924 /* Overwrite trailing new line character */
1930 #ifdef FEATURE_GRACEFUL_TERMINATION
1931 /*********************************************************************
1933 * Function : ssl_release
1935 * Description : Release all SSL resources
1941 *********************************************************************/
1942 extern void ssl_release(void)
1944 if (rng_seeded == 1)
1946 mbedtls_ctr_drbg_free(&ctr_drbg);
1947 mbedtls_entropy_free(&entropy);
1950 #endif /* def FEATURE_GRACEFUL_TERMINATION */
1953 /*********************************************************************
1955 * Function : get_ciphersuites_from_string
1957 * Description : Converts a string of ciphersuite names to
1958 * an array of ciphersuite ids.
1961 * 1 : ciphersuites_string = String containing allowed
1964 * Returns : Array of ciphersuite ids
1966 *********************************************************************/
1967 static int *get_ciphersuites_from_string(const char *parameter_string)
1969 char *ciphersuites_index;
1971 char *ciphersuites_string;
1972 int *ciphersuite_ids;
1975 const char separator = ':';
1976 size_t parameter_len = strlen(parameter_string);
1978 ciphersuites_string = zalloc_or_die(parameter_len + 1);
1979 strlcpy(ciphersuites_string, parameter_string, parameter_len + 1);
1980 ciphersuites_index = ciphersuites_string;
1982 while (*ciphersuites_index)
1984 if (*ciphersuites_index++ == separator)
1990 ciphersuite_ids = zalloc_or_die(count * sizeof(int));
1992 ciphersuites_index = ciphersuites_string;
1995 item_end = strchr(ciphersuites_index, separator);
1996 if (item_end != NULL)
2001 ciphersuite_ids[index] =
2002 mbedtls_ssl_get_ciphersuite_id(ciphersuites_index);
2003 if (ciphersuite_ids[index] == 0)
2005 log_error(LOG_LEVEL_ERROR,
2006 "Failed to get ciphersuite id for %s", ciphersuites_index);
2007 freez(ciphersuite_ids);
2008 freez(ciphersuites_string);
2011 ciphersuites_index = item_end + 1;
2013 } while (item_end != NULL);
2015 ciphersuite_ids[index] = 0;
2016 freez(ciphersuites_string);
2018 return ciphersuite_ids;