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.
8 * Copyright : Written by and Copyright (c) 2017 Vaclav Svec. FIT CVUT.
9 * Copyright (C) 2018-2020 by Fabian Keil <fk@fabiankeil.de>
11 * This program is free software; you can redistribute it
12 * and/or modify it under the terms of the GNU General
13 * Public License as published by the Free Software
14 * Foundation; either version 2 of the License, or (at
15 * your option) any later version.
17 * This program is distributed in the hope that it will
18 * be useful, but WITHOUT ANY WARRANTY; without even the
19 * implied warranty of MERCHANTABILITY or FITNESS FOR A
20 * PARTICULAR PURPOSE. See the GNU General Public
21 * License for more details.
23 * The GNU General Public License should be included with
24 * this file. If not, you can view it at
25 * http://www.gnu.org/copyleft/gpl.html
26 * or write to the Free Software Foundation, Inc., 59
27 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
29 *********************************************************************/
34 #if !defined(MBEDTLS_CONFIG_FILE)
35 # include "mbedtls/config.h"
37 # include MBEDTLS_CONFIG_FILE
40 #include "mbedtls/md5.h"
41 #include "mbedtls/pem.h"
42 #include "mbedtls/base64.h"
43 #include "mbedtls/error.h"
44 #include "mbedtls/oid.h"
45 #include "mbedtls/asn1write.h"
53 #include "ssl_common.h"
58 * Macros for searching begin and end of certificates.
59 * Necessary to convert structure mbedtls_x509_crt to crt file.
61 #define PEM_BEGIN_CRT "-----BEGIN CERTIFICATE-----\n"
62 #define PEM_END_CRT "-----END CERTIFICATE-----\n"
63 #define VALID_DATETIME_FMT "%Y%m%d%H%M%S"
64 #define VALID_DATETIME_BUFLEN 15
69 #define CERTIFICATE_BUF_SIZE 16384 /* Size of buffer to save certificate. Value 4096 is mbedtls library buffer size for certificate in DER form */
70 #define PRIVATE_KEY_BUF_SIZE 16000 /* Size of buffer to save private key. Value 16000 is taken from mbed TLS library examples. */
71 #define CERT_SIGNATURE_ALGORITHM MBEDTLS_MD_SHA256 /* The MD algorithm to use for the signature */
72 #define CERT_PARAM_COMMON_NAME CERT_PARAM_COMMON_NAME_FCODE"="
73 #define CERT_PARAM_ORGANIZATION ","CERT_PARAM_ORGANIZATION_FCODE"="
74 #define CERT_PARAM_ORG_UNIT ","CERT_PARAM_ORG_UNIT_FCODE"="
75 #define CERT_PARAM_COUNTRY ","CERT_PARAM_COUNTRY_FCODE"="CERT_PARAM_COUNTRY_CODE
78 * Properties of key for generating
81 mbedtls_pk_type_t type; /* type of key to generate */
82 int rsa_keysize; /* length of key in bits */
83 char *key_file_path; /* filename of the key file */
86 /* Variables for one common RNG for all SSL use */
87 static mbedtls_ctr_drbg_context ctr_drbg;
88 static mbedtls_entropy_context entropy;
89 static int rng_seeded;
91 static int generate_webpage_certificate(struct client_state *csp);
92 static int host_to_hash(struct client_state *csp);
93 static int ssl_verify_callback(void *data, mbedtls_x509_crt *crt, int depth, uint32_t *flags);
94 static void free_client_ssl_structures(struct client_state *csp);
95 static void free_server_ssl_structures(struct client_state *csp);
96 static int seed_rng(struct client_state *csp);
98 /*********************************************************************
100 * Function : is_ssl_pending
102 * Description : Tests if there are some waiting data on ssl connection.
103 * Only considers data that has actually been received
104 * locally and ignores data that is still on the fly
105 * or has not yet been sent by the remote end.
108 * 1 : ssl_attr = SSL context to test
110 * Returns : 0 => No data are pending
111 * >0 => Pending data length
113 *********************************************************************/
114 extern size_t is_ssl_pending(struct ssl_attr *ssl_attr)
116 mbedtls_ssl_context *ssl = &ssl_attr->mbedtls_attr.ssl;
122 return mbedtls_ssl_get_bytes_avail(ssl);
126 /*********************************************************************
128 * Function : ssl_send_data
130 * Description : Sends the content of buf (for n bytes) to given SSL
131 * connection context.
134 * 1 : ssl_attr = SSL context to send data to
135 * 2 : buf = Pointer to data to be sent
136 * 3 : len = Length of data to be sent to the SSL context
138 * Returns : Length of sent data or negative value on error.
140 *********************************************************************/
141 extern int ssl_send_data(struct ssl_attr *ssl_attr, const unsigned char *buf, size_t len)
143 mbedtls_ssl_context *ssl = &ssl_attr->mbedtls_attr.ssl;
145 size_t max_fragment_size = 0; /* Maximal length of data in one SSL fragment*/
146 int send_len = 0; /* length of one data part to send */
147 int pos = 0; /* Position of unsent part in buffer */
154 /* Getting maximal length of data sent in one fragment */
155 max_fragment_size = mbedtls_ssl_get_max_frag_len(ssl);
158 * Whole buffer must be sent in many fragments, because each fragment
159 * has its maximal length.
163 /* Compute length of data, that can be send in next fragment */
164 if ((pos + (int)max_fragment_size) > len)
166 send_len = (int)len - pos;
170 send_len = (int)max_fragment_size;
173 log_error(LOG_LEVEL_WRITING, "TLS: %N", send_len, buf+pos);
176 * Sending one part of the buffer
178 while ((ret = mbedtls_ssl_write(ssl,
179 (const unsigned char *)(buf + pos),
180 (size_t)send_len)) < 0)
182 if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
183 ret != MBEDTLS_ERR_SSL_WANT_WRITE)
185 char err_buf[ERROR_BUF_SIZE];
187 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
188 log_error(LOG_LEVEL_ERROR,
189 "Sending data over TLS/SSL failed: %s", err_buf);
193 /* Adding count of sent bytes to position in buffer */
194 pos = pos + send_len;
201 /*********************************************************************
203 * Function : ssl_recv_data
205 * Description : Receives data from given SSL context and puts
209 * 1 : ssl_attr = SSL context to receive data from
210 * 2 : buf = Pointer to buffer where data will be written
211 * 3 : max_length = Maximum number of bytes to read
213 * Returns : Number of bytes read, 0 for EOF, or -1
216 *********************************************************************/
217 extern int ssl_recv_data(struct ssl_attr *ssl_attr, unsigned char *buf, size_t max_length)
219 mbedtls_ssl_context *ssl = &ssl_attr->mbedtls_attr.ssl;
221 memset(buf, 0, max_length);
224 * Receiving data from SSL context into buffer
228 ret = mbedtls_ssl_read(ssl, buf, max_length);
229 } while (ret == MBEDTLS_ERR_SSL_WANT_READ
230 || ret == MBEDTLS_ERR_SSL_WANT_WRITE);
234 char err_buf[ERROR_BUF_SIZE];
236 if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY)
238 log_error(LOG_LEVEL_CONNECT, "The peer notified us that "
239 "the connection on socket %d is going to be closed",
240 ssl_attr->mbedtls_attr.socket_fd.fd);
243 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
244 log_error(LOG_LEVEL_ERROR,
245 "Receiving data on socket %d over TLS/SSL failed: %s",
246 ssl_attr->mbedtls_attr.socket_fd.fd, err_buf);
251 log_error(LOG_LEVEL_RECEIVED, "TLS from socket %d: %N",
252 ssl_attr->mbedtls_attr.socket_fd.fd, ret, buf);
258 /*********************************************************************
260 * Function : create_client_ssl_connection
262 * Description : Creates TLS/SSL secured connection with client
265 * 1 : csp = Current client state (buffers, headers, etc...)
267 * Returns : 0 on success, negative value if connection wasn't created
270 *********************************************************************/
271 extern int create_client_ssl_connection(struct client_state *csp)
273 struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
274 /* Paths to certificates file and key file */
275 char *key_file = NULL;
276 char *ca_file = NULL;
277 char *cert_file = NULL;
279 char err_buf[ERROR_BUF_SIZE];
282 * Initializing mbedtls structures for TLS/SSL connection
284 mbedtls_net_init(&(ssl_attr->mbedtls_attr.socket_fd));
285 mbedtls_ssl_init(&(ssl_attr->mbedtls_attr.ssl));
286 mbedtls_ssl_config_init(&(ssl_attr->mbedtls_attr.conf));
287 mbedtls_x509_crt_init(&(ssl_attr->mbedtls_attr.server_cert));
288 mbedtls_pk_init(&(ssl_attr->mbedtls_attr.prim_key));
289 #if defined(MBEDTLS_SSL_CACHE_C)
290 mbedtls_ssl_cache_init(&(ssl_attr->mbedtls_attr.cache));
294 * Preparing hash of host for creating certificates
296 ret = host_to_hash(csp);
299 log_error(LOG_LEVEL_ERROR, "Generating hash of host failed: %d", ret);
305 * Preparing paths to certificates files and key file
307 ca_file = csp->config->ca_cert_file;
308 cert_file = make_certs_path(csp->config->certificate_directory,
309 (const char *)csp->http->hash_of_host_hex, CERT_FILE_TYPE);
310 key_file = make_certs_path(csp->config->certificate_directory,
311 (const char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
313 if (cert_file == NULL || key_file == NULL)
320 * Generating certificate for requested host. Mutex to prevent
321 * certificate and key inconsistence must be locked.
323 privoxy_mutex_lock(&certificate_mutex);
325 ret = generate_webpage_certificate(csp);
328 log_error(LOG_LEVEL_ERROR,
329 "Generate_webpage_certificate failed: %d", ret);
330 privoxy_mutex_unlock(&certificate_mutex);
334 privoxy_mutex_unlock(&certificate_mutex);
347 * Loading CA file, webpage certificate and key files
349 ret = mbedtls_x509_crt_parse_file(&(ssl_attr->mbedtls_attr.server_cert),
353 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
354 log_error(LOG_LEVEL_ERROR,
355 "Loading webpage certificate %s failed: %s", cert_file, err_buf);
360 ret = mbedtls_x509_crt_parse_file(&(ssl_attr->mbedtls_attr.server_cert),
364 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
365 log_error(LOG_LEVEL_ERROR,
366 "Loading CA certificate %s failed: %s", ca_file, err_buf);
371 ret = mbedtls_pk_parse_keyfile(&(ssl_attr->mbedtls_attr.prim_key),
375 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
376 log_error(LOG_LEVEL_ERROR,
377 "Loading and parsing webpage certificate private key %s failed: %s",
384 * Setting SSL parameters
386 ret = mbedtls_ssl_config_defaults(&(ssl_attr->mbedtls_attr.conf),
387 MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_TRANSPORT_STREAM,
388 MBEDTLS_SSL_PRESET_DEFAULT);
391 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
392 log_error(LOG_LEVEL_ERROR,
393 "mbedtls_ssl_config_defaults failed: %s", err_buf);
398 mbedtls_ssl_conf_rng(&(ssl_attr->mbedtls_attr.conf),
399 mbedtls_ctr_drbg_random, &ctr_drbg);
401 #if defined(MBEDTLS_SSL_CACHE_C)
402 mbedtls_ssl_conf_session_cache(&(ssl_attr->mbedtls_attr.conf),
403 &(ssl_attr->mbedtls_attr.cache), mbedtls_ssl_cache_get,
404 mbedtls_ssl_cache_set);
408 * Setting certificates
410 ret = mbedtls_ssl_conf_own_cert(&(ssl_attr->mbedtls_attr.conf),
411 &(ssl_attr->mbedtls_attr.server_cert),
412 &(ssl_attr->mbedtls_attr.prim_key));
415 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
416 log_error(LOG_LEVEL_ERROR,
417 "mbedtls_ssl_conf_own_cert failed: %s", err_buf);
422 ret = mbedtls_ssl_setup(&(ssl_attr->mbedtls_attr.ssl),
423 &(ssl_attr->mbedtls_attr.conf));
426 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
427 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_setup failed: %s", err_buf);
432 mbedtls_ssl_set_bio(&(ssl_attr->mbedtls_attr.ssl),
433 &(ssl_attr->mbedtls_attr.socket_fd), mbedtls_net_send,
434 mbedtls_net_recv, NULL);
435 mbedtls_ssl_session_reset(&(ssl_attr->mbedtls_attr.ssl));
438 * Setting socket fd in mbedtls_net_context structure. This structure
439 * can't be set by mbedtls functions, because we already have created
440 * a TCP connection when this function is called.
442 ssl_attr->mbedtls_attr.socket_fd.fd = csp->cfd;
445 * Handshake with client
447 log_error(LOG_LEVEL_CONNECT,
448 "Performing the TLS/SSL handshake with client. Hash of host: %s",
449 csp->http->hash_of_host_hex);
450 while ((ret = mbedtls_ssl_handshake(&(ssl_attr->mbedtls_attr.ssl))) != 0)
452 if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
453 ret != MBEDTLS_ERR_SSL_WANT_WRITE)
455 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
456 log_error(LOG_LEVEL_ERROR,
457 "medtls_ssl_handshake with client failed: %s", err_buf);
463 log_error(LOG_LEVEL_CONNECT, "Client successfully connected over TLS/SSL");
464 csp->ssl_with_client_is_opened = 1;
468 * Freeing allocated paths to files
473 /* Freeing structures if connection wasn't created successfully */
476 free_client_ssl_structures(csp);
482 /*********************************************************************
484 * Function : close_client_ssl_connection
486 * Description : Closes TLS/SSL connection with client. This function
487 * checks if this connection is already created.
490 * 1 : csp = Current client state (buffers, headers, etc...)
494 *********************************************************************/
495 extern void close_client_ssl_connection(struct client_state *csp)
497 struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
500 if (csp->ssl_with_client_is_opened == 0)
506 * Notifying the peer that the connection is being closed.
509 ret = mbedtls_ssl_close_notify(&(ssl_attr->mbedtls_attr.ssl));
510 } while (ret == MBEDTLS_ERR_SSL_WANT_WRITE);
512 free_client_ssl_structures(csp);
513 csp->ssl_with_client_is_opened = 0;
517 /*********************************************************************
519 * Function : free_client_ssl_structures
521 * Description : Frees structures used for SSL communication with
525 * 1 : csp = Current client state (buffers, headers, etc...)
529 *********************************************************************/
530 static void free_client_ssl_structures(struct client_state *csp)
532 struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
534 * We can't use function mbedtls_net_free, because this function
535 * inter alia close TCP connection on set fd. Instead of this
536 * function, we change fd to -1, which is the same what does
537 * rest of mbedtls_net_free function.
539 ssl_attr->mbedtls_attr.socket_fd.fd = -1;
541 /* Freeing mbedtls structures */
542 mbedtls_x509_crt_free(&(ssl_attr->mbedtls_attr.server_cert));
543 mbedtls_pk_free(&(ssl_attr->mbedtls_attr.prim_key));
544 mbedtls_ssl_free(&(ssl_attr->mbedtls_attr.ssl));
545 mbedtls_ssl_config_free(&(ssl_attr->mbedtls_attr.conf));
546 #if defined(MBEDTLS_SSL_CACHE_C)
547 mbedtls_ssl_cache_free(&(ssl_attr->mbedtls_attr.cache));
552 /*********************************************************************
554 * Function : create_server_ssl_connection
556 * Description : Creates TLS/SSL secured connection with server.
559 * 1 : csp = Current client state (buffers, headers, etc...)
561 * Returns : 0 on success, negative value if connection wasn't created
564 *********************************************************************/
565 extern int create_server_ssl_connection(struct client_state *csp)
567 struct ssl_attr *ssl_attr = &csp->ssl_server_attr;
569 char err_buf[ERROR_BUF_SIZE];
570 char *trusted_cas_file = NULL;
571 int auth_mode = MBEDTLS_SSL_VERIFY_REQUIRED;
573 csp->server_cert_verification_result = SSL_CERT_NOT_VERIFIED;
574 csp->server_certs_chain.next = NULL;
576 /* Setting path to file with trusted CAs */
577 trusted_cas_file = csp->config->trusted_cas_file;
580 * Initializing mbedtls structures for TLS/SSL connection
582 mbedtls_net_init(&(ssl_attr->mbedtls_attr.socket_fd));
583 mbedtls_ssl_init(&(ssl_attr->mbedtls_attr.ssl));
584 mbedtls_ssl_config_init(&(ssl_attr->mbedtls_attr.conf));
585 mbedtls_x509_crt_init(&(ssl_attr->mbedtls_attr.ca_cert));
588 * Setting socket fd in mbedtls_net_context structure. This structure
589 * can't be set by mbedtls functions, because we already have created
590 * TCP connection when calling this function.
592 ssl_attr->mbedtls_attr.socket_fd.fd = csp->server_connection.sfd;
605 * Loading file with trusted CAs
607 ret = mbedtls_x509_crt_parse_file(&(ssl_attr->mbedtls_attr.ca_cert),
611 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
612 log_error(LOG_LEVEL_ERROR, "Loading trusted CAs file %s failed: %s",
613 trusted_cas_file, err_buf);
619 * Set TLS/SSL options
621 ret = mbedtls_ssl_config_defaults(&(ssl_attr->mbedtls_attr.conf),
622 MBEDTLS_SSL_IS_CLIENT,
623 MBEDTLS_SSL_TRANSPORT_STREAM,
624 MBEDTLS_SSL_PRESET_DEFAULT);
627 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
628 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_config_defaults failed: %s",
635 * Setting how strict should certificate verification be and other
636 * parameters for certificate verification
638 if (csp->dont_verify_certificate)
640 auth_mode = MBEDTLS_SSL_VERIFY_NONE;
643 mbedtls_ssl_conf_authmode(&(ssl_attr->mbedtls_attr.conf), auth_mode);
644 mbedtls_ssl_conf_ca_chain(&(ssl_attr->mbedtls_attr.conf),
645 &(ssl_attr->mbedtls_attr.ca_cert), NULL);
647 /* Setting callback function for certificates verification */
648 mbedtls_ssl_conf_verify(&(ssl_attr->mbedtls_attr.conf),
649 ssl_verify_callback, (void *)csp);
651 mbedtls_ssl_conf_rng(&(ssl_attr->mbedtls_attr.conf),
652 mbedtls_ctr_drbg_random, &ctr_drbg);
654 ret = mbedtls_ssl_setup(&(ssl_attr->mbedtls_attr.ssl),
655 &(ssl_attr->mbedtls_attr.conf));
658 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
659 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_setup failed: %s", err_buf);
665 * Set the hostname to check against the received server certificate
667 ret = mbedtls_ssl_set_hostname(&(ssl_attr->mbedtls_attr.ssl),
671 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
672 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_set_hostname failed: %s",
678 mbedtls_ssl_set_bio(&(ssl_attr->mbedtls_attr.ssl),
679 &(ssl_attr->mbedtls_attr.socket_fd), mbedtls_net_send,
680 mbedtls_net_recv, NULL);
683 * Handshake with server
685 log_error(LOG_LEVEL_CONNECT,
686 "Performing the TLS/SSL handshake with the server");
688 while ((ret = mbedtls_ssl_handshake(&(ssl_attr->mbedtls_attr.ssl))) != 0)
690 if (ret != MBEDTLS_ERR_SSL_WANT_READ
691 && ret != MBEDTLS_ERR_SSL_WANT_WRITE)
693 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
695 if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED)
697 char reason[INVALID_CERT_INFO_BUF_SIZE];
699 csp->server_cert_verification_result =
700 mbedtls_ssl_get_verify_result(&(ssl_attr->mbedtls_attr.ssl));
701 mbedtls_x509_crt_verify_info(reason, sizeof(reason), "",
702 csp->server_cert_verification_result);
704 /* Log the reason without the trailing new line */
705 log_error(LOG_LEVEL_ERROR,
706 "X509 certificate verification for %s failed: %N",
707 csp->http->hostport, strlen(reason)-1, reason);
712 log_error(LOG_LEVEL_ERROR,
713 "mbedtls_ssl_handshake with server failed: %s", err_buf);
714 free_certificate_chain(csp);
721 log_error(LOG_LEVEL_CONNECT, "Server successfully connected over TLS/SSL");
724 * Server certificate chain is valid, so we can clean
725 * chain, because we will not send it to client.
727 free_certificate_chain(csp);
729 csp->ssl_with_server_is_opened = 1;
730 csp->server_cert_verification_result =
731 mbedtls_ssl_get_verify_result(&(ssl_attr->mbedtls_attr.ssl));
734 /* Freeing structures if connection wasn't created successfully */
737 free_server_ssl_structures(csp);
744 /*********************************************************************
746 * Function : close_server_ssl_connection
748 * Description : Closes TLS/SSL connection with server. This function
749 * checks if this connection is already opened.
752 * 1 : csp = Current client state (buffers, headers, etc...)
756 *********************************************************************/
757 extern void close_server_ssl_connection(struct client_state *csp)
759 struct ssl_attr *ssl_attr = &csp->ssl_server_attr;
762 if (csp->ssl_with_server_is_opened == 0)
768 * Notifying the peer that the connection is being closed.
771 ret = mbedtls_ssl_close_notify(&(ssl_attr->mbedtls_attr.ssl));
772 } while (ret == MBEDTLS_ERR_SSL_WANT_WRITE);
774 free_server_ssl_structures(csp);
775 csp->ssl_with_server_is_opened = 0;
779 /*********************************************************************
781 * Function : free_server_ssl_structures
783 * Description : Frees structures used for SSL communication with server
786 * 1 : csp = Current client state (buffers, headers, etc...)
790 *********************************************************************/
791 static void free_server_ssl_structures(struct client_state *csp)
793 struct ssl_attr *ssl_attr = &csp->ssl_server_attr;
795 * We can't use function mbedtls_net_free, because this function
796 * inter alia close TCP connection on set fd. Instead of this
797 * function, we change fd to -1, which is the same what does
798 * rest of mbedtls_net_free function.
800 ssl_attr->mbedtls_attr.socket_fd.fd = -1;
802 mbedtls_x509_crt_free(&(ssl_attr->mbedtls_attr.ca_cert));
803 mbedtls_ssl_free(&(ssl_attr->mbedtls_attr.ssl));
804 mbedtls_ssl_config_free(&(ssl_attr->mbedtls_attr.conf));
808 /*====================== Certificates ======================*/
810 /*********************************************************************
812 * Function : write_certificate
814 * Description : Writes certificate into file.
817 * 1 : crt = certificate to write into file
818 * 2 : output_file = path to save certificate file
819 * 3 : f_rng = mbedtls_ctr_drbg_random
820 * 4 : p_rng = mbedtls_ctr_drbg_context
822 * Returns : Length of written certificate on success or negative value
825 *********************************************************************/
826 static int write_certificate(mbedtls_x509write_cert *crt, const char *output_file,
827 int(*f_rng)(void *, unsigned char *, size_t), void *p_rng)
831 unsigned char cert_buf[CERTIFICATE_BUF_SIZE + 1]; /* Buffer for certificate in PEM format + terminating NULL */
833 char err_buf[ERROR_BUF_SIZE];
835 memset(cert_buf, 0, sizeof(cert_buf));
838 * Writing certificate into PEM string. If buffer is too small, function
839 * returns specific error and no buffer overflow can happen.
841 if ((ret = mbedtls_x509write_crt_pem(crt, cert_buf,
842 sizeof(cert_buf) - 1, f_rng, p_rng)) != 0)
844 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
845 log_error(LOG_LEVEL_ERROR,
846 "Writing certificate into buffer failed: %s", err_buf);
850 len = strlen((char *)cert_buf);
853 * Saving certificate into file
855 if ((f = fopen(output_file, "w")) == NULL)
857 log_error(LOG_LEVEL_ERROR, "Opening file %s to save certificate failed",
862 if (fwrite(cert_buf, 1, len, f) != len)
864 log_error(LOG_LEVEL_ERROR,
865 "Writing certificate into file %s failed", output_file);
876 /*********************************************************************
878 * Function : write_private_key
880 * Description : Writes private key into file and copies saved
881 * content into given pointer to string. If function
882 * returns 0 for success, this copy must be freed by
886 * 1 : key = key to write into file
887 * 2 : ret_buf = pointer to string with created key file content
888 * 3 : key_file_path = path where to save key file
890 * Returns : Length of written private key on success or negative value
893 *********************************************************************/
894 static int write_private_key(mbedtls_pk_context *key, unsigned char **ret_buf,
895 const char *key_file_path)
897 size_t len = 0; /* Length of created key */
898 FILE *f = NULL; /* File to save certificate */
900 char err_buf[ERROR_BUF_SIZE];
902 /* Initializing buffer for key file content */
903 *ret_buf = zalloc_or_die(PRIVATE_KEY_BUF_SIZE + 1);
906 * Writing private key into PEM string
908 if ((ret = mbedtls_pk_write_key_pem(key, *ret_buf, PRIVATE_KEY_BUF_SIZE)) != 0)
910 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
911 log_error(LOG_LEVEL_ERROR,
912 "Writing private key into PEM string failed: %s", err_buf);
916 len = strlen((char *)*ret_buf);
919 * Saving key into file
921 if ((f = fopen(key_file_path, "wb")) == NULL)
923 log_error(LOG_LEVEL_ERROR,
924 "Opening file %s to save private key failed: %E",
930 if (fwrite(*ret_buf, 1, len, f) != len)
933 log_error(LOG_LEVEL_ERROR,
934 "Writing private key into file %s failed",
953 /*********************************************************************
955 * Function : generate_key
957 * Description : Tests if private key for host saved in csp already
958 * exists. If this file doesn't exists, a new key is
959 * generated and saved in a file. The generated key is also
960 * copied into given parameter key_buf, which must be then
961 * freed by caller. If file with key exists, key_buf
962 * contain NULL and no private key is generated.
965 * 1 : csp = Current client state (buffers, headers, etc...)
966 * 2 : key_buf = buffer to save new generated key
968 * Returns : -1 => Error while generating private key
969 * 0 => Key already exists
970 * >0 => Length of generated private key
972 *********************************************************************/
973 static int generate_key(struct client_state *csp, unsigned char **key_buf)
975 mbedtls_pk_context key;
978 char err_buf[ERROR_BUF_SIZE];
980 key_opt.key_file_path = NULL;
983 * Initializing structures for key generating
985 mbedtls_pk_init(&key);
988 * Preparing path for key file and other properties for generating key
990 key_opt.type = MBEDTLS_PK_RSA;
991 key_opt.rsa_keysize = RSA_KEYSIZE;
993 key_opt.key_file_path = make_certs_path(csp->config->certificate_directory,
994 (char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
995 if (key_opt.key_file_path == NULL)
1002 * Test if key already exists. If so, we don't have to create it again.
1004 if (file_exists(key_opt.key_file_path) == 1)
1013 ret = seed_rng(csp);
1021 * Setting attributes of private key and generating it
1023 if ((ret = mbedtls_pk_setup(&key,
1024 mbedtls_pk_info_from_type(key_opt.type))) != 0)
1026 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1027 log_error(LOG_LEVEL_ERROR, "mbedtls_pk_setup failed: %s", err_buf);
1032 ret = mbedtls_rsa_gen_key(mbedtls_pk_rsa(key), mbedtls_ctr_drbg_random,
1033 &ctr_drbg, (unsigned)key_opt.rsa_keysize, RSA_KEY_PUBLIC_EXPONENT);
1036 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1037 log_error(LOG_LEVEL_ERROR, "Key generating failed: %s", err_buf);
1043 * Exporting private key into file
1045 if ((ret = write_private_key(&key, key_buf, key_opt.key_file_path)) < 0)
1047 log_error(LOG_LEVEL_ERROR,
1048 "Writing private key into file %s failed", key_opt.key_file_path);
1055 * Freeing used variables
1057 freez(key_opt.key_file_path);
1059 mbedtls_pk_free(&key);
1065 /*********************************************************************
1067 * Function : ssl_certificate_is_invalid
1069 * Description : Checks whether or not a certificate is valid.
1070 * Currently only checks that the certificate can be
1071 * parsed and that the "valid to" date is in the future.
1074 * 1 : cert_file = The certificate to check
1076 * Returns : 0 => The certificate is valid.
1077 * 1 => The certificate is invalid
1079 *********************************************************************/
1080 static int ssl_certificate_is_invalid(const char *cert_file)
1082 mbedtls_x509_crt cert;
1085 mbedtls_x509_crt_init(&cert);
1087 ret = mbedtls_x509_crt_parse_file(&cert, cert_file);
1090 char err_buf[ERROR_BUF_SIZE];
1092 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1093 log_error(LOG_LEVEL_ERROR,
1094 "Loading certificate %s to check validity failed: %s",
1095 cert_file, err_buf);
1096 mbedtls_x509_crt_free(&cert);
1100 if (mbedtls_x509_time_is_past(&cert.valid_to))
1102 mbedtls_x509_crt_free(&cert);
1107 mbedtls_x509_crt_free(&cert);
1114 /*********************************************************************
1116 * Function : set_subject_alternative_name
1118 * Description : Sets the Subject Alternative Name extension to a cert
1121 * 1 : cert = The certificate to modify
1122 * 2 : hostname = The hostname to add
1124 * Returns : <0 => Error while creating certificate.
1127 *********************************************************************/
1128 static int set_subject_alternative_name(mbedtls_x509write_cert *cert, const char *hostname)
1130 char err_buf[ERROR_BUF_SIZE];
1132 char *subject_alternative_name;
1133 size_t subject_alternative_name_len;
1134 #define MBEDTLS_SUBJECT_ALTERNATIVE_NAME_MAX_LEN 255
1135 unsigned char san_buf[MBEDTLS_SUBJECT_ALTERNATIVE_NAME_MAX_LEN + 1];
1139 subject_alternative_name_len = strlen(hostname) + 1;
1140 subject_alternative_name = zalloc_or_die(subject_alternative_name_len);
1142 strlcpy(subject_alternative_name, hostname, subject_alternative_name_len);
1144 memset(san_buf, 0, sizeof(san_buf));
1146 c = san_buf + sizeof(san_buf);
1149 ret = mbedtls_asn1_write_raw_buffer(&c, san_buf,
1150 (const unsigned char *)subject_alternative_name,
1151 strlen(subject_alternative_name));
1154 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1155 log_error(LOG_LEVEL_ERROR,
1156 "mbedtls_asn1_write_raw_buffer() failed: %s", err_buf);
1161 ret = mbedtls_asn1_write_len(&c, san_buf, strlen(subject_alternative_name));
1164 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1165 log_error(LOG_LEVEL_ERROR,
1166 "mbedtls_asn1_write_len() failed: %s", err_buf);
1171 ret = mbedtls_asn1_write_tag(&c, san_buf, MBEDTLS_ASN1_CONTEXT_SPECIFIC | 2);
1174 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1175 log_error(LOG_LEVEL_ERROR,
1176 "mbedtls_asn1_write_tag() failed: %s", err_buf);
1181 ret = mbedtls_asn1_write_len(&c, san_buf, (size_t)len);
1184 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1185 log_error(LOG_LEVEL_ERROR,
1186 "mbedtls_asn1_write_len() failed: %s", err_buf);
1191 ret = mbedtls_asn1_write_tag(&c, san_buf,
1192 MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE);
1195 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1196 log_error(LOG_LEVEL_ERROR,
1197 "mbedtls_asn1_write_tag() failed: %s", err_buf);
1202 ret = mbedtls_x509write_crt_set_extension(cert,
1203 MBEDTLS_OID_SUBJECT_ALT_NAME,
1204 MBEDTLS_OID_SIZE(MBEDTLS_OID_SUBJECT_ALT_NAME),
1205 0, san_buf + sizeof(san_buf) - len, (size_t)len);
1208 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1209 log_error(LOG_LEVEL_ERROR,
1210 "mbedtls_x509write_crt_set_extension() failed: %s", err_buf);
1214 freez(subject_alternative_name);
1221 /*********************************************************************
1223 * Function : generate_webpage_certificate
1225 * Description : Creates certificate file in presetted directory.
1226 * If certificate already exists, no other certificate
1227 * will be created. Subject of certificate is named
1228 * by csp->http->host from parameter. This function also
1229 * triggers generating of private key for new certificate.
1232 * 1 : csp = Current client state (buffers, headers, etc...)
1234 * Returns : -1 => Error while creating certificate.
1235 * 0 => Certificate already exists.
1236 * >0 => Length of created certificate.
1238 *********************************************************************/
1239 static int generate_webpage_certificate(struct client_state *csp)
1241 mbedtls_x509_crt issuer_cert;
1242 mbedtls_pk_context loaded_issuer_key, loaded_subject_key;
1243 mbedtls_pk_context *issuer_key = &loaded_issuer_key;
1244 mbedtls_pk_context *subject_key = &loaded_subject_key;
1245 mbedtls_x509write_cert cert;
1248 unsigned char *key_buf = NULL; /* Buffer for created key */
1251 char err_buf[ERROR_BUF_SIZE];
1252 cert_options cert_opt;
1253 char cert_valid_from[VALID_DATETIME_BUFLEN];
1254 char cert_valid_to[VALID_DATETIME_BUFLEN];
1256 /* Paths to keys and certificates needed to create certificate */
1257 cert_opt.issuer_key = NULL;
1258 cert_opt.subject_key = NULL;
1259 cert_opt.issuer_crt = NULL;
1261 cert_opt.output_file = make_certs_path(csp->config->certificate_directory,
1262 (const char *)csp->http->hash_of_host_hex, CERT_FILE_TYPE);
1263 if (cert_opt.output_file == NULL)
1268 cert_opt.subject_key = make_certs_path(csp->config->certificate_directory,
1269 (const char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
1270 if (cert_opt.subject_key == NULL)
1272 freez(cert_opt.output_file);
1276 if (file_exists(cert_opt.output_file) == 1)
1278 /* The file exists, but is it valid? */
1279 if (ssl_certificate_is_invalid(cert_opt.output_file))
1281 log_error(LOG_LEVEL_CONNECT,
1282 "Certificate %s is no longer valid. Removing it.",
1283 cert_opt.output_file);
1284 if (unlink(cert_opt.output_file))
1286 log_error(LOG_LEVEL_ERROR, "Failed to unlink %s: %E",
1287 cert_opt.output_file);
1289 freez(cert_opt.output_file);
1290 freez(cert_opt.subject_key);
1294 if (unlink(cert_opt.subject_key))
1296 log_error(LOG_LEVEL_ERROR, "Failed to unlink %s: %E",
1297 cert_opt.subject_key);
1299 freez(cert_opt.output_file);
1300 freez(cert_opt.subject_key);
1307 freez(cert_opt.output_file);
1308 freez(cert_opt.subject_key);
1315 * Create key for requested host
1317 int subject_key_len = generate_key(csp, &key_buf);
1318 if (subject_key_len < 0)
1320 freez(cert_opt.output_file);
1321 freez(cert_opt.subject_key);
1322 log_error(LOG_LEVEL_ERROR, "Key generating failed");
1327 * Initializing structures for certificate generating
1329 mbedtls_x509write_crt_init(&cert);
1330 mbedtls_x509write_crt_set_md_alg(&cert, CERT_SIGNATURE_ALGORITHM);
1331 mbedtls_pk_init(&loaded_issuer_key);
1332 mbedtls_pk_init(&loaded_subject_key);
1333 mbedtls_mpi_init(&serial);
1334 mbedtls_x509_crt_init(&issuer_cert);
1337 * Presetting parameters for certificate. We must compute total length
1340 size_t cert_params_len = strlen(CERT_PARAM_COMMON_NAME) +
1341 strlen(CERT_PARAM_ORGANIZATION) + strlen(CERT_PARAM_COUNTRY) +
1342 strlen(CERT_PARAM_ORG_UNIT) +
1343 3 * strlen(csp->http->host) + 1;
1344 char cert_params[cert_params_len];
1345 memset(cert_params, 0, cert_params_len);
1348 * Converting unsigned long serial number to char * serial number.
1349 * We must compute length of serial number in string + terminating null.
1351 unsigned long certificate_serial = get_certificate_serial(csp);
1352 unsigned long certificate_serial_time = (unsigned long)time(NULL);
1353 int serial_num_size = snprintf(NULL, 0, "%lu%lu",
1354 certificate_serial_time, certificate_serial) + 1;
1355 if (serial_num_size <= 0)
1357 serial_num_size = 1;
1360 char serial_num_text[serial_num_size]; /* Buffer for serial number */
1361 ret = snprintf(serial_num_text, (size_t)serial_num_size, "%lu%lu",
1362 certificate_serial_time, certificate_serial);
1363 if (ret < 0 || ret >= serial_num_size)
1365 log_error(LOG_LEVEL_ERROR,
1366 "Converting certificate serial number into string failed");
1372 * Preparing parameters for certificate
1374 strlcpy(cert_params, CERT_PARAM_COMMON_NAME, cert_params_len);
1375 strlcat(cert_params, csp->http->host, cert_params_len);
1376 strlcat(cert_params, CERT_PARAM_ORGANIZATION, cert_params_len);
1377 strlcat(cert_params, csp->http->host, cert_params_len);
1378 strlcat(cert_params, CERT_PARAM_ORG_UNIT, cert_params_len);
1379 strlcat(cert_params, csp->http->host, cert_params_len);
1380 strlcat(cert_params, CERT_PARAM_COUNTRY, cert_params_len);
1382 cert_opt.issuer_crt = csp->config->ca_cert_file;
1383 cert_opt.issuer_key = csp->config->ca_key_file;
1385 if (get_certificate_valid_from_date(cert_valid_from, sizeof(cert_valid_from), VALID_DATETIME_FMT)
1386 || get_certificate_valid_to_date(cert_valid_to, sizeof(cert_valid_to), VALID_DATETIME_FMT))
1388 log_error(LOG_LEVEL_ERROR, "Generating one of the validity dates failed");
1393 cert_opt.subject_pwd = CERT_SUBJECT_PASSWORD;
1394 cert_opt.issuer_pwd = csp->config->ca_password;
1395 cert_opt.subject_name = cert_params;
1396 cert_opt.not_before = cert_valid_from;
1397 cert_opt.not_after = cert_valid_to;
1398 cert_opt.serial = serial_num_text;
1400 cert_opt.max_pathlen = -1;
1403 * Test if the private key was already created.
1404 * XXX: Can this still happen?
1406 if (subject_key_len == 0)
1408 log_error(LOG_LEVEL_ERROR, "Subject key was already created");
1416 ret = seed_rng(csp);
1424 * Parse serial to MPI
1426 ret = mbedtls_mpi_read_string(&serial, 10, cert_opt.serial);
1429 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1430 log_error(LOG_LEVEL_ERROR,
1431 "mbedtls_mpi_read_string failed: %s", err_buf);
1437 * Loading certificates
1439 ret = mbedtls_x509_crt_parse_file(&issuer_cert, cert_opt.issuer_crt);
1442 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1443 log_error(LOG_LEVEL_ERROR, "Loading issuer certificate %s failed: %s",
1444 cert_opt.issuer_crt, err_buf);
1449 ret = mbedtls_x509_dn_gets(cert_opt.issuer_name,
1450 sizeof(cert_opt.issuer_name), &issuer_cert.subject);
1453 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1454 log_error(LOG_LEVEL_ERROR, "mbedtls_x509_dn_gets failed: %s", err_buf);
1460 * Loading keys from file or from buffer
1462 if (key_buf != NULL && subject_key_len > 0)
1464 /* Key was created in this function and is stored in buffer */
1465 ret = mbedtls_pk_parse_key(&loaded_subject_key, key_buf,
1466 (size_t)(subject_key_len + 1), (unsigned const char *)
1467 cert_opt.subject_pwd, strlen(cert_opt.subject_pwd));
1471 /* Key wasn't created in this function, because it already existed */
1472 ret = mbedtls_pk_parse_keyfile(&loaded_subject_key,
1473 cert_opt.subject_key, cert_opt.subject_pwd);
1478 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1479 log_error(LOG_LEVEL_ERROR, "Parsing subject key %s failed: %s",
1480 cert_opt.subject_key, err_buf);
1485 ret = mbedtls_pk_parse_keyfile(&loaded_issuer_key, cert_opt.issuer_key,
1486 cert_opt.issuer_pwd);
1489 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1490 log_error(LOG_LEVEL_ERROR,
1491 "Parsing issuer key %s failed: %s", cert_opt.issuer_key, err_buf);
1497 * Check if key and issuer certificate match
1499 if (!mbedtls_pk_can_do(&issuer_cert.pk, MBEDTLS_PK_RSA) ||
1500 mbedtls_mpi_cmp_mpi(&mbedtls_pk_rsa(issuer_cert.pk)->N,
1501 &mbedtls_pk_rsa(*issuer_key)->N) != 0 ||
1502 mbedtls_mpi_cmp_mpi(&mbedtls_pk_rsa(issuer_cert.pk)->E,
1503 &mbedtls_pk_rsa(*issuer_key)->E) != 0)
1505 log_error(LOG_LEVEL_ERROR,
1506 "Issuer key doesn't match issuer certificate");
1511 mbedtls_x509write_crt_set_subject_key(&cert, subject_key);
1512 mbedtls_x509write_crt_set_issuer_key(&cert, issuer_key);
1515 * Setting parameters of signed certificate
1517 ret = mbedtls_x509write_crt_set_subject_name(&cert, cert_opt.subject_name);
1520 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1521 log_error(LOG_LEVEL_ERROR,
1522 "Setting subject name in signed certificate failed: %s", err_buf);
1527 ret = mbedtls_x509write_crt_set_issuer_name(&cert, cert_opt.issuer_name);
1530 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1531 log_error(LOG_LEVEL_ERROR,
1532 "Setting issuer name in signed certificate failed: %s", err_buf);
1537 ret = mbedtls_x509write_crt_set_serial(&cert, &serial);
1540 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1541 log_error(LOG_LEVEL_ERROR,
1542 "Setting serial number in signed certificate failed: %s", err_buf);
1547 ret = mbedtls_x509write_crt_set_validity(&cert, cert_opt.not_before,
1548 cert_opt.not_after);
1551 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1552 log_error(LOG_LEVEL_ERROR,
1553 "Setting validity in signed certificate failed: %s", err_buf);
1559 * Setting the basicConstraints extension for certificate
1561 ret = mbedtls_x509write_crt_set_basic_constraints(&cert, cert_opt.is_ca,
1562 cert_opt.max_pathlen);
1565 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1566 log_error(LOG_LEVEL_ERROR, "Setting the basicConstraints extension "
1567 "in signed certificate failed: %s", err_buf);
1572 #if defined(MBEDTLS_SHA1_C)
1573 /* Setting the subjectKeyIdentifier extension for certificate */
1574 ret = mbedtls_x509write_crt_set_subject_key_identifier(&cert);
1577 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1578 log_error(LOG_LEVEL_ERROR, "mbedtls_x509write_crt_set_subject_key_"
1579 "identifier failed: %s", err_buf);
1584 /* Setting the authorityKeyIdentifier extension for certificate */
1585 ret = mbedtls_x509write_crt_set_authority_key_identifier(&cert);
1588 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1589 log_error(LOG_LEVEL_ERROR, "mbedtls_x509write_crt_set_authority_key_"
1590 "identifier failed: %s", err_buf);
1594 #endif /* MBEDTLS_SHA1_C */
1596 if (!host_is_ip_address(csp->http->host) &&
1597 set_subject_alternative_name(&cert, csp->http->host))
1599 /* Errors are already logged by set_subject_alternative_name() */
1605 * Writing certificate into file
1607 ret = write_certificate(&cert, cert_opt.output_file,
1608 mbedtls_ctr_drbg_random, &ctr_drbg);
1611 log_error(LOG_LEVEL_ERROR, "Writing certificate into file failed");
1617 * Freeing used structures
1619 mbedtls_x509write_crt_free(&cert);
1620 mbedtls_pk_free(&loaded_subject_key);
1621 mbedtls_pk_free(&loaded_issuer_key);
1622 mbedtls_mpi_free(&serial);
1623 mbedtls_x509_crt_free(&issuer_cert);
1625 freez(cert_opt.subject_key);
1626 freez(cert_opt.output_file);
1632 /*********************************************************************
1634 * Function : ssl_verify_callback
1636 * Description : This is a callback function for certificate verification.
1637 * It's called once for each certificate in the server's
1638 * certificate trusted chain and prepares information about
1639 * the certificate. The information can be used to inform
1640 * the user about invalid certificates.
1643 * 1 : csp_void = Current client state (buffers, headers, etc...)
1644 * 2 : crt = certificate from trusted chain
1645 * 3 : depth = depth in trusted chain
1646 * 4 : flags = certificate flags
1648 * Returns : 0 on success and negative value on error
1650 *********************************************************************/
1651 static int ssl_verify_callback(void *csp_void, mbedtls_x509_crt *crt,
1652 int depth, uint32_t *flags)
1654 struct client_state *csp = (struct client_state *)csp_void;
1655 struct certs_chain *last = &(csp->server_certs_chain);
1660 * Searching for last item in certificates linked list
1662 while (last->next != NULL)
1668 * Preparing next item in linked list for next certificate
1670 last->next = malloc_or_die(sizeof(struct certs_chain));
1671 last->next->next = NULL;
1672 memset(last->next->info_buf, 0, sizeof(last->next->info_buf));
1673 memset(last->next->file_buf, 0, sizeof(last->next->file_buf));
1676 * Saving certificate file into buffer
1678 if ((ret = mbedtls_pem_write_buffer(PEM_BEGIN_CRT, PEM_END_CRT,
1679 crt->raw.p, crt->raw.len, (unsigned char *)last->file_buf,
1680 sizeof(last->file_buf)-1, &olen)) != 0)
1682 char err_buf[ERROR_BUF_SIZE];
1684 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1685 log_error(LOG_LEVEL_ERROR, "mbedtls_pem_write_buffer() failed: %s",
1692 * Saving certificate information into buffer
1695 char buf[CERT_INFO_BUF_SIZE];
1698 mbedtls_x509_crt_info(buf, sizeof(buf), CERT_INFO_PREFIX, crt);
1699 encoded_text = html_encode(buf);
1700 if (encoded_text == NULL)
1702 log_error(LOG_LEVEL_ERROR,
1703 "Failed to HTML-encode the certificate information");
1706 strlcpy(last->info_buf, encoded_text, sizeof(last->info_buf));
1707 freez(encoded_text);
1714 /*********************************************************************
1716 * Function : host_to_hash
1718 * Description : Creates MD5 hash from host name. Host name is loaded
1719 * from structure csp and saved again into it.
1722 * 1 : csp = Current client state (buffers, headers, etc...)
1724 * Returns : 1 => Error while creating hash
1725 * 0 => Hash created successfully
1727 *********************************************************************/
1728 static int host_to_hash(struct client_state *csp)
1732 #if !defined(MBEDTLS_MD5_C)
1733 #error mbedTLS needs to be compiled with md5 support
1735 memset(csp->http->hash_of_host, 0, sizeof(csp->http->hash_of_host));
1736 mbedtls_md5((unsigned char *)csp->http->host, strlen(csp->http->host),
1737 csp->http->hash_of_host);
1739 /* Converting hash into string with hex */
1743 if ((ret = sprintf((char *)csp->http->hash_of_host_hex + 2 * i, "%02x",
1744 csp->http->hash_of_host[i])) < 0)
1746 log_error(LOG_LEVEL_ERROR, "Sprintf return value: %d", ret);
1752 #endif /* MBEDTLS_MD5_C */
1755 /*********************************************************************
1757 * Function : seed_rng
1759 * Description : Seeding the RNG for all SSL uses
1762 * 1 : csp = Current client state (buffers, headers, etc...)
1764 * Returns : -1 => RNG wasn't seed successfully
1765 * 0 => RNG is seeded successfully
1767 *********************************************************************/
1768 static int seed_rng(struct client_state *csp)
1771 char err_buf[ERROR_BUF_SIZE];
1773 if (rng_seeded == 0)
1775 privoxy_mutex_lock(&ssl_init_mutex);
1776 if (rng_seeded == 0)
1778 mbedtls_ctr_drbg_init(&ctr_drbg);
1779 mbedtls_entropy_init(&entropy);
1780 ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func,
1784 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1785 log_error(LOG_LEVEL_ERROR,
1786 "mbedtls_ctr_drbg_seed failed: %s", err_buf);
1787 privoxy_mutex_unlock(&ssl_init_mutex);
1792 privoxy_mutex_unlock(&ssl_init_mutex);
1798 /*********************************************************************
1800 * Function : ssl_base64_encode
1802 * Description : Encode a buffer into base64 format.
1805 * 1 : dst = Destination buffer
1806 * 2 : dlen = Destination buffer length
1807 * 3 : olen = Number of bytes written
1808 * 4 : src = Source buffer
1809 * 5 : slen = Amount of data to be encoded
1811 * Returns : 0 on success, error code othervise
1813 *********************************************************************/
1814 extern int ssl_base64_encode(unsigned char *dst, size_t dlen, size_t *olen,
1815 const unsigned char *src, size_t slen)
1817 return mbedtls_base64_encode(dst, dlen, olen, src, slen);
1821 /*********************************************************************
1823 * Function : ssl_crt_verify_info
1825 * Description : Returns an informational string about the verification
1826 * status of a certificate.
1829 * 1 : buf = Buffer to write to
1830 * 2 : size = Maximum size of buffer
1831 * 3 : csp = client state
1835 *********************************************************************/
1836 extern void ssl_crt_verify_info(char *buf, size_t size, struct client_state *csp)
1838 mbedtls_x509_crt_verify_info(buf, size, " ", csp->server_cert_verification_result);
1842 /*********************************************************************
1844 * Function : ssl_release
1846 * Description : Release all SSL resources
1852 *********************************************************************/
1853 extern void ssl_release(void)
1855 if (rng_seeded == 1)
1857 mbedtls_ctr_drbg_free(&ctr_drbg);
1858 mbedtls_entropy_free(&entropy);