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,
239 "The peer notified us that the connection is going to be closed");
242 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
243 log_error(LOG_LEVEL_ERROR,
244 "Receiving data over TLS/SSL failed: %s", err_buf);
249 log_error(LOG_LEVEL_RECEIVED, "TLS: %N", ret, buf);
255 /*********************************************************************
257 * Function : create_client_ssl_connection
259 * Description : Creates TLS/SSL secured connection with client
262 * 1 : csp = Current client state (buffers, headers, etc...)
264 * Returns : 0 on success, negative value if connection wasn't created
267 *********************************************************************/
268 extern int create_client_ssl_connection(struct client_state *csp)
270 struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
271 /* Paths to certificates file and key file */
272 char *key_file = NULL;
273 char *ca_file = NULL;
274 char *cert_file = NULL;
276 char err_buf[ERROR_BUF_SIZE];
279 * Initializing mbedtls structures for TLS/SSL connection
281 mbedtls_net_init(&(ssl_attr->mbedtls_attr.socket_fd));
282 mbedtls_ssl_init(&(ssl_attr->mbedtls_attr.ssl));
283 mbedtls_ssl_config_init(&(ssl_attr->mbedtls_attr.conf));
284 mbedtls_x509_crt_init(&(ssl_attr->mbedtls_attr.server_cert));
285 mbedtls_pk_init(&(ssl_attr->mbedtls_attr.prim_key));
286 #if defined(MBEDTLS_SSL_CACHE_C)
287 mbedtls_ssl_cache_init(&(ssl_attr->mbedtls_attr.cache));
291 * Preparing hash of host for creating certificates
293 ret = host_to_hash(csp);
296 log_error(LOG_LEVEL_ERROR, "Generating hash of host failed: %d", ret);
302 * Preparing paths to certificates files and key file
304 ca_file = csp->config->ca_cert_file;
305 cert_file = make_certs_path(csp->config->certificate_directory,
306 (const char *)csp->http->hash_of_host_hex, CERT_FILE_TYPE);
307 key_file = make_certs_path(csp->config->certificate_directory,
308 (const char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
310 if (cert_file == NULL || key_file == NULL)
317 * Generating certificate for requested host. Mutex to prevent
318 * certificate and key inconsistence must be locked.
320 privoxy_mutex_lock(&certificate_mutex);
322 ret = generate_webpage_certificate(csp);
325 log_error(LOG_LEVEL_ERROR,
326 "Generate_webpage_certificate failed: %d", ret);
327 privoxy_mutex_unlock(&certificate_mutex);
331 privoxy_mutex_unlock(&certificate_mutex);
344 * Loading CA file, webpage certificate and key files
346 ret = mbedtls_x509_crt_parse_file(&(ssl_attr->mbedtls_attr.server_cert),
350 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
351 log_error(LOG_LEVEL_ERROR,
352 "Loading webpage certificate %s failed: %s", cert_file, err_buf);
357 ret = mbedtls_x509_crt_parse_file(&(ssl_attr->mbedtls_attr.server_cert),
361 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
362 log_error(LOG_LEVEL_ERROR,
363 "Loading CA certificate %s failed: %s", ca_file, err_buf);
368 ret = mbedtls_pk_parse_keyfile(&(ssl_attr->mbedtls_attr.prim_key),
372 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
373 log_error(LOG_LEVEL_ERROR,
374 "Loading and parsing webpage certificate private key %s failed: %s",
381 * Setting SSL parameters
383 ret = mbedtls_ssl_config_defaults(&(ssl_attr->mbedtls_attr.conf),
384 MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_TRANSPORT_STREAM,
385 MBEDTLS_SSL_PRESET_DEFAULT);
388 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
389 log_error(LOG_LEVEL_ERROR,
390 "mbedtls_ssl_config_defaults failed: %s", err_buf);
395 mbedtls_ssl_conf_rng(&(ssl_attr->mbedtls_attr.conf),
396 mbedtls_ctr_drbg_random, &ctr_drbg);
398 #if defined(MBEDTLS_SSL_CACHE_C)
399 mbedtls_ssl_conf_session_cache(&(ssl_attr->mbedtls_attr.conf),
400 &(ssl_attr->mbedtls_attr.cache), mbedtls_ssl_cache_get,
401 mbedtls_ssl_cache_set);
405 * Setting certificates
407 ret = mbedtls_ssl_conf_own_cert(&(ssl_attr->mbedtls_attr.conf),
408 &(ssl_attr->mbedtls_attr.server_cert),
409 &(ssl_attr->mbedtls_attr.prim_key));
412 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
413 log_error(LOG_LEVEL_ERROR,
414 "mbedtls_ssl_conf_own_cert failed: %s", err_buf);
419 ret = mbedtls_ssl_setup(&(ssl_attr->mbedtls_attr.ssl),
420 &(ssl_attr->mbedtls_attr.conf));
423 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
424 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_setup failed: %s", err_buf);
429 mbedtls_ssl_set_bio(&(ssl_attr->mbedtls_attr.ssl),
430 &(ssl_attr->mbedtls_attr.socket_fd), mbedtls_net_send,
431 mbedtls_net_recv, NULL);
432 mbedtls_ssl_session_reset(&(ssl_attr->mbedtls_attr.ssl));
435 * Setting socket fd in mbedtls_net_context structure. This structure
436 * can't be set by mbedtls functions, because we already have created
437 * a TCP connection when this function is called.
439 ssl_attr->mbedtls_attr.socket_fd.fd = csp->cfd;
442 * Handshake with client
444 log_error(LOG_LEVEL_CONNECT,
445 "Performing the TLS/SSL handshake with client. Hash of host: %s",
446 csp->http->hash_of_host_hex);
447 while ((ret = mbedtls_ssl_handshake(&(ssl_attr->mbedtls_attr.ssl))) != 0)
449 if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
450 ret != MBEDTLS_ERR_SSL_WANT_WRITE)
452 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
453 log_error(LOG_LEVEL_ERROR,
454 "medtls_ssl_handshake with client failed: %s", err_buf);
460 log_error(LOG_LEVEL_CONNECT, "Client successfully connected over TLS/SSL");
461 csp->ssl_with_client_is_opened = 1;
465 * Freeing allocated paths to files
470 /* Freeing structures if connection wasn't created successfully */
473 free_client_ssl_structures(csp);
479 /*********************************************************************
481 * Function : close_client_ssl_connection
483 * Description : Closes TLS/SSL connection with client. This function
484 * checks if this connection is already created.
487 * 1 : csp = Current client state (buffers, headers, etc...)
491 *********************************************************************/
492 extern void close_client_ssl_connection(struct client_state *csp)
494 struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
497 if (csp->ssl_with_client_is_opened == 0)
503 * Notifying the peer that the connection is being closed.
506 ret = mbedtls_ssl_close_notify(&(ssl_attr->mbedtls_attr.ssl));
507 } while (ret == MBEDTLS_ERR_SSL_WANT_WRITE);
509 free_client_ssl_structures(csp);
510 csp->ssl_with_client_is_opened = 0;
514 /*********************************************************************
516 * Function : free_client_ssl_structures
518 * Description : Frees structures used for SSL communication with
522 * 1 : csp = Current client state (buffers, headers, etc...)
526 *********************************************************************/
527 static void free_client_ssl_structures(struct client_state *csp)
529 struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
531 * We can't use function mbedtls_net_free, because this function
532 * inter alia close TCP connection on set fd. Instead of this
533 * function, we change fd to -1, which is the same what does
534 * rest of mbedtls_net_free function.
536 ssl_attr->mbedtls_attr.socket_fd.fd = -1;
538 /* Freeing mbedtls structures */
539 mbedtls_x509_crt_free(&(ssl_attr->mbedtls_attr.server_cert));
540 mbedtls_pk_free(&(ssl_attr->mbedtls_attr.prim_key));
541 mbedtls_ssl_free(&(ssl_attr->mbedtls_attr.ssl));
542 mbedtls_ssl_config_free(&(ssl_attr->mbedtls_attr.conf));
543 #if defined(MBEDTLS_SSL_CACHE_C)
544 mbedtls_ssl_cache_free(&(ssl_attr->mbedtls_attr.cache));
549 /*********************************************************************
551 * Function : create_server_ssl_connection
553 * Description : Creates TLS/SSL secured connection with server.
556 * 1 : csp = Current client state (buffers, headers, etc...)
558 * Returns : 0 on success, negative value if connection wasn't created
561 *********************************************************************/
562 extern int create_server_ssl_connection(struct client_state *csp)
564 struct ssl_attr *ssl_attr = &csp->ssl_server_attr;
566 char err_buf[ERROR_BUF_SIZE];
567 char *trusted_cas_file = NULL;
568 int auth_mode = MBEDTLS_SSL_VERIFY_REQUIRED;
570 csp->server_cert_verification_result = SSL_CERT_NOT_VERIFIED;
571 csp->server_certs_chain.next = NULL;
573 /* Setting path to file with trusted CAs */
574 trusted_cas_file = csp->config->trusted_cas_file;
577 * Initializing mbedtls structures for TLS/SSL connection
579 mbedtls_net_init(&(ssl_attr->mbedtls_attr.socket_fd));
580 mbedtls_ssl_init(&(ssl_attr->mbedtls_attr.ssl));
581 mbedtls_ssl_config_init(&(ssl_attr->mbedtls_attr.conf));
582 mbedtls_x509_crt_init(&(ssl_attr->mbedtls_attr.ca_cert));
585 * Setting socket fd in mbedtls_net_context structure. This structure
586 * can't be set by mbedtls functions, because we already have created
587 * TCP connection when calling this function.
589 ssl_attr->mbedtls_attr.socket_fd.fd = csp->server_connection.sfd;
602 * Loading file with trusted CAs
604 ret = mbedtls_x509_crt_parse_file(&(ssl_attr->mbedtls_attr.ca_cert),
608 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
609 log_error(LOG_LEVEL_ERROR, "Loading trusted CAs file %s failed: %s",
610 trusted_cas_file, err_buf);
616 * Set TLS/SSL options
618 ret = mbedtls_ssl_config_defaults(&(ssl_attr->mbedtls_attr.conf),
619 MBEDTLS_SSL_IS_CLIENT,
620 MBEDTLS_SSL_TRANSPORT_STREAM,
621 MBEDTLS_SSL_PRESET_DEFAULT);
624 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
625 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_config_defaults failed: %s",
632 * Setting how strict should certificate verification be and other
633 * parameters for certificate verification
635 if (csp->dont_verify_certificate)
637 auth_mode = MBEDTLS_SSL_VERIFY_NONE;
640 mbedtls_ssl_conf_authmode(&(ssl_attr->mbedtls_attr.conf), auth_mode);
641 mbedtls_ssl_conf_ca_chain(&(ssl_attr->mbedtls_attr.conf),
642 &(ssl_attr->mbedtls_attr.ca_cert), NULL);
644 /* Setting callback function for certificates verification */
645 mbedtls_ssl_conf_verify(&(ssl_attr->mbedtls_attr.conf),
646 ssl_verify_callback, (void *)csp);
648 mbedtls_ssl_conf_rng(&(ssl_attr->mbedtls_attr.conf),
649 mbedtls_ctr_drbg_random, &ctr_drbg);
651 ret = mbedtls_ssl_setup(&(ssl_attr->mbedtls_attr.ssl),
652 &(ssl_attr->mbedtls_attr.conf));
655 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
656 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_setup failed: %s", err_buf);
662 * Set the hostname to check against the received server certificate
664 ret = mbedtls_ssl_set_hostname(&(ssl_attr->mbedtls_attr.ssl),
668 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
669 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_set_hostname failed: %s",
675 mbedtls_ssl_set_bio(&(ssl_attr->mbedtls_attr.ssl),
676 &(ssl_attr->mbedtls_attr.socket_fd), mbedtls_net_send,
677 mbedtls_net_recv, NULL);
680 * Handshake with server
682 log_error(LOG_LEVEL_CONNECT,
683 "Performing the TLS/SSL handshake with the server");
685 while ((ret = mbedtls_ssl_handshake(&(ssl_attr->mbedtls_attr.ssl))) != 0)
687 if (ret != MBEDTLS_ERR_SSL_WANT_READ
688 && ret != MBEDTLS_ERR_SSL_WANT_WRITE)
690 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
692 if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED)
694 char reason[INVALID_CERT_INFO_BUF_SIZE];
696 csp->server_cert_verification_result =
697 mbedtls_ssl_get_verify_result(&(ssl_attr->mbedtls_attr.ssl));
698 mbedtls_x509_crt_verify_info(reason, sizeof(reason), "",
699 csp->server_cert_verification_result);
701 /* Log the reason without the trailing new line */
702 log_error(LOG_LEVEL_ERROR,
703 "X509 certificate verification for %s failed: %N",
704 csp->http->hostport, strlen(reason)-1, reason);
709 log_error(LOG_LEVEL_ERROR,
710 "mbedtls_ssl_handshake with server failed: %s", err_buf);
711 free_certificate_chain(csp);
718 log_error(LOG_LEVEL_CONNECT, "Server successfully connected over TLS/SSL");
721 * Server certificate chain is valid, so we can clean
722 * chain, because we will not send it to client.
724 free_certificate_chain(csp);
726 csp->ssl_with_server_is_opened = 1;
727 csp->server_cert_verification_result =
728 mbedtls_ssl_get_verify_result(&(ssl_attr->mbedtls_attr.ssl));
731 /* Freeing structures if connection wasn't created successfully */
734 free_server_ssl_structures(csp);
741 /*********************************************************************
743 * Function : close_server_ssl_connection
745 * Description : Closes TLS/SSL connection with server. This function
746 * checks if this connection is already opened.
749 * 1 : csp = Current client state (buffers, headers, etc...)
753 *********************************************************************/
754 extern void close_server_ssl_connection(struct client_state *csp)
756 struct ssl_attr *ssl_attr = &csp->ssl_server_attr;
759 if (csp->ssl_with_server_is_opened == 0)
765 * Notifying the peer that the connection is being closed.
768 ret = mbedtls_ssl_close_notify(&(ssl_attr->mbedtls_attr.ssl));
769 } while (ret == MBEDTLS_ERR_SSL_WANT_WRITE);
771 free_server_ssl_structures(csp);
772 csp->ssl_with_server_is_opened = 0;
776 /*********************************************************************
778 * Function : free_server_ssl_structures
780 * Description : Frees structures used for SSL communication with server
783 * 1 : csp = Current client state (buffers, headers, etc...)
787 *********************************************************************/
788 static void free_server_ssl_structures(struct client_state *csp)
790 struct ssl_attr *ssl_attr = &csp->ssl_server_attr;
792 * We can't use function mbedtls_net_free, because this function
793 * inter alia close TCP connection on set fd. Instead of this
794 * function, we change fd to -1, which is the same what does
795 * rest of mbedtls_net_free function.
797 ssl_attr->mbedtls_attr.socket_fd.fd = -1;
799 mbedtls_x509_crt_free(&(ssl_attr->mbedtls_attr.ca_cert));
800 mbedtls_ssl_free(&(ssl_attr->mbedtls_attr.ssl));
801 mbedtls_ssl_config_free(&(ssl_attr->mbedtls_attr.conf));
805 /*====================== Certificates ======================*/
807 /*********************************************************************
809 * Function : write_certificate
811 * Description : Writes certificate into file.
814 * 1 : crt = certificate to write into file
815 * 2 : output_file = path to save certificate file
816 * 3 : f_rng = mbedtls_ctr_drbg_random
817 * 4 : p_rng = mbedtls_ctr_drbg_context
819 * Returns : Length of written certificate on success or negative value
822 *********************************************************************/
823 static int write_certificate(mbedtls_x509write_cert *crt, const char *output_file,
824 int(*f_rng)(void *, unsigned char *, size_t), void *p_rng)
828 unsigned char cert_buf[CERTIFICATE_BUF_SIZE + 1]; /* Buffer for certificate in PEM format + terminating NULL */
830 char err_buf[ERROR_BUF_SIZE];
832 memset(cert_buf, 0, sizeof(cert_buf));
835 * Writing certificate into PEM string. If buffer is too small, function
836 * returns specific error and no buffer overflow can happen.
838 if ((ret = mbedtls_x509write_crt_pem(crt, cert_buf,
839 sizeof(cert_buf) - 1, f_rng, p_rng)) != 0)
841 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
842 log_error(LOG_LEVEL_ERROR,
843 "Writing certificate into buffer failed: %s", err_buf);
847 len = strlen((char *)cert_buf);
850 * Saving certificate into file
852 if ((f = fopen(output_file, "w")) == NULL)
854 log_error(LOG_LEVEL_ERROR, "Opening file %s to save certificate failed",
859 if (fwrite(cert_buf, 1, len, f) != len)
861 log_error(LOG_LEVEL_ERROR,
862 "Writing certificate into file %s failed", output_file);
873 /*********************************************************************
875 * Function : write_private_key
877 * Description : Writes private key into file and copies saved
878 * content into given pointer to string. If function
879 * returns 0 for success, this copy must be freed by
883 * 1 : key = key to write into file
884 * 2 : ret_buf = pointer to string with created key file content
885 * 3 : key_file_path = path where to save key file
887 * Returns : Length of written private key on success or negative value
890 *********************************************************************/
891 static int write_private_key(mbedtls_pk_context *key, unsigned char **ret_buf,
892 const char *key_file_path)
894 size_t len = 0; /* Length of created key */
895 FILE *f = NULL; /* File to save certificate */
897 char err_buf[ERROR_BUF_SIZE];
899 /* Initializing buffer for key file content */
900 *ret_buf = zalloc_or_die(PRIVATE_KEY_BUF_SIZE + 1);
903 * Writing private key into PEM string
905 if ((ret = mbedtls_pk_write_key_pem(key, *ret_buf, PRIVATE_KEY_BUF_SIZE)) != 0)
907 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
908 log_error(LOG_LEVEL_ERROR,
909 "Writing private key into PEM string failed: %s", err_buf);
913 len = strlen((char *)*ret_buf);
916 * Saving key into file
918 if ((f = fopen(key_file_path, "wb")) == NULL)
920 log_error(LOG_LEVEL_ERROR,
921 "Opening file %s to save private key failed: %E",
927 if (fwrite(*ret_buf, 1, len, f) != len)
930 log_error(LOG_LEVEL_ERROR,
931 "Writing private key into file %s failed",
950 /*********************************************************************
952 * Function : generate_key
954 * Description : Tests if private key for host saved in csp already
955 * exists. If this file doesn't exists, a new key is
956 * generated and saved in a file. The generated key is also
957 * copied into given parameter key_buf, which must be then
958 * freed by caller. If file with key exists, key_buf
959 * contain NULL and no private key is generated.
962 * 1 : csp = Current client state (buffers, headers, etc...)
963 * 2 : key_buf = buffer to save new generated key
965 * Returns : -1 => Error while generating private key
966 * 0 => Key already exists
967 * >0 => Length of generated private key
969 *********************************************************************/
970 static int generate_key(struct client_state *csp, unsigned char **key_buf)
972 mbedtls_pk_context key;
975 char err_buf[ERROR_BUF_SIZE];
977 key_opt.key_file_path = NULL;
980 * Initializing structures for key generating
982 mbedtls_pk_init(&key);
985 * Preparing path for key file and other properties for generating key
987 key_opt.type = MBEDTLS_PK_RSA;
988 key_opt.rsa_keysize = RSA_KEYSIZE;
990 key_opt.key_file_path = make_certs_path(csp->config->certificate_directory,
991 (char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
992 if (key_opt.key_file_path == NULL)
999 * Test if key already exists. If so, we don't have to create it again.
1001 if (file_exists(key_opt.key_file_path) == 1)
1010 ret = seed_rng(csp);
1018 * Setting attributes of private key and generating it
1020 if ((ret = mbedtls_pk_setup(&key,
1021 mbedtls_pk_info_from_type(key_opt.type))) != 0)
1023 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1024 log_error(LOG_LEVEL_ERROR, "mbedtls_pk_setup failed: %s", err_buf);
1029 ret = mbedtls_rsa_gen_key(mbedtls_pk_rsa(key), mbedtls_ctr_drbg_random,
1030 &ctr_drbg, (unsigned)key_opt.rsa_keysize, RSA_KEY_PUBLIC_EXPONENT);
1033 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1034 log_error(LOG_LEVEL_ERROR, "Key generating failed: %s", err_buf);
1040 * Exporting private key into file
1042 if ((ret = write_private_key(&key, key_buf, key_opt.key_file_path)) < 0)
1044 log_error(LOG_LEVEL_ERROR,
1045 "Writing private key into file %s failed", key_opt.key_file_path);
1052 * Freeing used variables
1054 freez(key_opt.key_file_path);
1056 mbedtls_pk_free(&key);
1062 /*********************************************************************
1064 * Function : ssl_certificate_is_invalid
1066 * Description : Checks whether or not a certificate is valid.
1067 * Currently only checks that the certificate can be
1068 * parsed and that the "valid to" date is in the future.
1071 * 1 : cert_file = The certificate to check
1073 * Returns : 0 => The certificate is valid.
1074 * 1 => The certificate is invalid
1076 *********************************************************************/
1077 static int ssl_certificate_is_invalid(const char *cert_file)
1079 mbedtls_x509_crt cert;
1082 mbedtls_x509_crt_init(&cert);
1084 ret = mbedtls_x509_crt_parse_file(&cert, cert_file);
1087 char err_buf[ERROR_BUF_SIZE];
1089 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1090 log_error(LOG_LEVEL_ERROR,
1091 "Loading certificate %s to check validity failed: %s",
1092 cert_file, err_buf);
1093 mbedtls_x509_crt_free(&cert);
1097 if (mbedtls_x509_time_is_past(&cert.valid_to))
1099 mbedtls_x509_crt_free(&cert);
1104 mbedtls_x509_crt_free(&cert);
1111 /*********************************************************************
1113 * Function : set_subject_alternative_name
1115 * Description : Sets the Subject Alternative Name extension to a cert
1118 * 1 : cert = The certificate to modify
1119 * 2 : hostname = The hostname to add
1121 * Returns : <0 => Error while creating certificate.
1124 *********************************************************************/
1125 static int set_subject_alternative_name(mbedtls_x509write_cert *cert, const char *hostname)
1127 char err_buf[ERROR_BUF_SIZE];
1129 char *subject_alternative_name;
1130 size_t subject_alternative_name_len;
1131 #define MBEDTLS_SUBJECT_ALTERNATIVE_NAME_MAX_LEN 255
1132 unsigned char san_buf[MBEDTLS_SUBJECT_ALTERNATIVE_NAME_MAX_LEN + 1];
1136 subject_alternative_name_len = strlen(hostname) + 1;
1137 subject_alternative_name = zalloc_or_die(subject_alternative_name_len);
1139 strlcpy(subject_alternative_name, hostname, subject_alternative_name_len);
1141 memset(san_buf, 0, sizeof(san_buf));
1143 c = san_buf + sizeof(san_buf);
1146 ret = mbedtls_asn1_write_raw_buffer(&c, san_buf,
1147 (const unsigned char *)subject_alternative_name,
1148 strlen(subject_alternative_name));
1151 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1152 log_error(LOG_LEVEL_ERROR,
1153 "mbedtls_asn1_write_raw_buffer() failed: %s", err_buf);
1158 ret = mbedtls_asn1_write_len(&c, san_buf, strlen(subject_alternative_name));
1161 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1162 log_error(LOG_LEVEL_ERROR,
1163 "mbedtls_asn1_write_len() failed: %s", err_buf);
1168 ret = mbedtls_asn1_write_tag(&c, san_buf, MBEDTLS_ASN1_CONTEXT_SPECIFIC | 2);
1171 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1172 log_error(LOG_LEVEL_ERROR,
1173 "mbedtls_asn1_write_tag() failed: %s", err_buf);
1178 ret = mbedtls_asn1_write_len(&c, san_buf, (size_t)len);
1181 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1182 log_error(LOG_LEVEL_ERROR,
1183 "mbedtls_asn1_write_len() failed: %s", err_buf);
1188 ret = mbedtls_asn1_write_tag(&c, san_buf,
1189 MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE);
1192 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1193 log_error(LOG_LEVEL_ERROR,
1194 "mbedtls_asn1_write_tag() failed: %s", err_buf);
1199 ret = mbedtls_x509write_crt_set_extension(cert,
1200 MBEDTLS_OID_SUBJECT_ALT_NAME,
1201 MBEDTLS_OID_SIZE(MBEDTLS_OID_SUBJECT_ALT_NAME),
1202 0, san_buf + sizeof(san_buf) - len, (size_t)len);
1205 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1206 log_error(LOG_LEVEL_ERROR,
1207 "mbedtls_x509write_crt_set_extension() failed: %s", err_buf);
1211 freez(subject_alternative_name);
1218 /*********************************************************************
1220 * Function : generate_webpage_certificate
1222 * Description : Creates certificate file in presetted directory.
1223 * If certificate already exists, no other certificate
1224 * will be created. Subject of certificate is named
1225 * by csp->http->host from parameter. This function also
1226 * triggers generating of private key for new certificate.
1229 * 1 : csp = Current client state (buffers, headers, etc...)
1231 * Returns : -1 => Error while creating certificate.
1232 * 0 => Certificate already exists.
1233 * >0 => Length of created certificate.
1235 *********************************************************************/
1236 static int generate_webpage_certificate(struct client_state *csp)
1238 mbedtls_x509_crt issuer_cert;
1239 mbedtls_pk_context loaded_issuer_key, loaded_subject_key;
1240 mbedtls_pk_context *issuer_key = &loaded_issuer_key;
1241 mbedtls_pk_context *subject_key = &loaded_subject_key;
1242 mbedtls_x509write_cert cert;
1245 unsigned char *key_buf = NULL; /* Buffer for created key */
1248 char err_buf[ERROR_BUF_SIZE];
1249 cert_options cert_opt;
1250 char cert_valid_from[VALID_DATETIME_BUFLEN];
1251 char cert_valid_to[VALID_DATETIME_BUFLEN];
1253 /* Paths to keys and certificates needed to create certificate */
1254 cert_opt.issuer_key = NULL;
1255 cert_opt.subject_key = NULL;
1256 cert_opt.issuer_crt = NULL;
1258 cert_opt.output_file = make_certs_path(csp->config->certificate_directory,
1259 (const char *)csp->http->hash_of_host_hex, CERT_FILE_TYPE);
1260 if (cert_opt.output_file == NULL)
1265 cert_opt.subject_key = make_certs_path(csp->config->certificate_directory,
1266 (const char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
1267 if (cert_opt.subject_key == NULL)
1269 freez(cert_opt.output_file);
1273 if (file_exists(cert_opt.output_file) == 1)
1275 /* The file exists, but is it valid? */
1276 if (ssl_certificate_is_invalid(cert_opt.output_file))
1278 log_error(LOG_LEVEL_CONNECT,
1279 "Certificate %s is no longer valid. Removing it.",
1280 cert_opt.output_file);
1281 if (unlink(cert_opt.output_file))
1283 log_error(LOG_LEVEL_ERROR, "Failed to unlink %s: %E",
1284 cert_opt.output_file);
1286 freez(cert_opt.output_file);
1287 freez(cert_opt.subject_key);
1291 if (unlink(cert_opt.subject_key))
1293 log_error(LOG_LEVEL_ERROR, "Failed to unlink %s: %E",
1294 cert_opt.subject_key);
1296 freez(cert_opt.output_file);
1297 freez(cert_opt.subject_key);
1304 freez(cert_opt.output_file);
1305 freez(cert_opt.subject_key);
1312 * Create key for requested host
1314 int subject_key_len = generate_key(csp, &key_buf);
1315 if (subject_key_len < 0)
1317 freez(cert_opt.output_file);
1318 freez(cert_opt.subject_key);
1319 log_error(LOG_LEVEL_ERROR, "Key generating failed");
1324 * Initializing structures for certificate generating
1326 mbedtls_x509write_crt_init(&cert);
1327 mbedtls_x509write_crt_set_md_alg(&cert, CERT_SIGNATURE_ALGORITHM);
1328 mbedtls_pk_init(&loaded_issuer_key);
1329 mbedtls_pk_init(&loaded_subject_key);
1330 mbedtls_mpi_init(&serial);
1331 mbedtls_x509_crt_init(&issuer_cert);
1334 * Presetting parameters for certificate. We must compute total length
1337 size_t cert_params_len = strlen(CERT_PARAM_COMMON_NAME) +
1338 strlen(CERT_PARAM_ORGANIZATION) + strlen(CERT_PARAM_COUNTRY) +
1339 strlen(CERT_PARAM_ORG_UNIT) +
1340 3 * strlen(csp->http->host) + 1;
1341 char cert_params[cert_params_len];
1342 memset(cert_params, 0, cert_params_len);
1345 * Converting unsigned long serial number to char * serial number.
1346 * We must compute length of serial number in string + terminating null.
1348 unsigned long certificate_serial = get_certificate_serial(csp);
1349 unsigned long certificate_serial_time = (unsigned long)time(NULL);
1350 int serial_num_size = snprintf(NULL, 0, "%lu%lu",
1351 certificate_serial_time, certificate_serial) + 1;
1352 if (serial_num_size <= 0)
1354 serial_num_size = 1;
1357 char serial_num_text[serial_num_size]; /* Buffer for serial number */
1358 ret = snprintf(serial_num_text, (size_t)serial_num_size, "%lu%lu",
1359 certificate_serial_time, certificate_serial);
1360 if (ret < 0 || ret >= serial_num_size)
1362 log_error(LOG_LEVEL_ERROR,
1363 "Converting certificate serial number into string failed");
1369 * Preparing parameters for certificate
1371 strlcpy(cert_params, CERT_PARAM_COMMON_NAME, cert_params_len);
1372 strlcat(cert_params, csp->http->host, cert_params_len);
1373 strlcat(cert_params, CERT_PARAM_ORGANIZATION, cert_params_len);
1374 strlcat(cert_params, csp->http->host, cert_params_len);
1375 strlcat(cert_params, CERT_PARAM_ORG_UNIT, cert_params_len);
1376 strlcat(cert_params, csp->http->host, cert_params_len);
1377 strlcat(cert_params, CERT_PARAM_COUNTRY, cert_params_len);
1379 cert_opt.issuer_crt = csp->config->ca_cert_file;
1380 cert_opt.issuer_key = csp->config->ca_key_file;
1382 if (get_certificate_valid_from_date(cert_valid_from, sizeof(cert_valid_from), VALID_DATETIME_FMT)
1383 || get_certificate_valid_to_date(cert_valid_to, sizeof(cert_valid_to), VALID_DATETIME_FMT))
1385 log_error(LOG_LEVEL_ERROR, "Generating one of the validity dates failed");
1390 cert_opt.subject_pwd = CERT_SUBJECT_PASSWORD;
1391 cert_opt.issuer_pwd = csp->config->ca_password;
1392 cert_opt.subject_name = cert_params;
1393 cert_opt.not_before = cert_valid_from;
1394 cert_opt.not_after = cert_valid_to;
1395 cert_opt.serial = serial_num_text;
1397 cert_opt.max_pathlen = -1;
1400 * Test if the private key was already created.
1401 * XXX: Can this still happen?
1403 if (subject_key_len == 0)
1405 log_error(LOG_LEVEL_ERROR, "Subject key was already created");
1413 ret = seed_rng(csp);
1421 * Parse serial to MPI
1423 ret = mbedtls_mpi_read_string(&serial, 10, cert_opt.serial);
1426 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1427 log_error(LOG_LEVEL_ERROR,
1428 "mbedtls_mpi_read_string failed: %s", err_buf);
1434 * Loading certificates
1436 ret = mbedtls_x509_crt_parse_file(&issuer_cert, cert_opt.issuer_crt);
1439 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1440 log_error(LOG_LEVEL_ERROR, "Loading issuer certificate %s failed: %s",
1441 cert_opt.issuer_crt, err_buf);
1446 ret = mbedtls_x509_dn_gets(cert_opt.issuer_name,
1447 sizeof(cert_opt.issuer_name), &issuer_cert.subject);
1450 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1451 log_error(LOG_LEVEL_ERROR, "mbedtls_x509_dn_gets failed: %s", err_buf);
1457 * Loading keys from file or from buffer
1459 if (key_buf != NULL && subject_key_len > 0)
1461 /* Key was created in this function and is stored in buffer */
1462 ret = mbedtls_pk_parse_key(&loaded_subject_key, key_buf,
1463 (size_t)(subject_key_len + 1), (unsigned const char *)
1464 cert_opt.subject_pwd, strlen(cert_opt.subject_pwd));
1468 /* Key wasn't created in this function, because it already existed */
1469 ret = mbedtls_pk_parse_keyfile(&loaded_subject_key,
1470 cert_opt.subject_key, cert_opt.subject_pwd);
1475 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1476 log_error(LOG_LEVEL_ERROR, "Parsing subject key %s failed: %s",
1477 cert_opt.subject_key, err_buf);
1482 ret = mbedtls_pk_parse_keyfile(&loaded_issuer_key, cert_opt.issuer_key,
1483 cert_opt.issuer_pwd);
1486 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1487 log_error(LOG_LEVEL_ERROR,
1488 "Parsing issuer key %s failed: %s", cert_opt.issuer_key, err_buf);
1494 * Check if key and issuer certificate match
1496 if (!mbedtls_pk_can_do(&issuer_cert.pk, MBEDTLS_PK_RSA) ||
1497 mbedtls_mpi_cmp_mpi(&mbedtls_pk_rsa(issuer_cert.pk)->N,
1498 &mbedtls_pk_rsa(*issuer_key)->N) != 0 ||
1499 mbedtls_mpi_cmp_mpi(&mbedtls_pk_rsa(issuer_cert.pk)->E,
1500 &mbedtls_pk_rsa(*issuer_key)->E) != 0)
1502 log_error(LOG_LEVEL_ERROR,
1503 "Issuer key doesn't match issuer certificate");
1508 mbedtls_x509write_crt_set_subject_key(&cert, subject_key);
1509 mbedtls_x509write_crt_set_issuer_key(&cert, issuer_key);
1512 * Setting parameters of signed certificate
1514 ret = mbedtls_x509write_crt_set_subject_name(&cert, cert_opt.subject_name);
1517 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1518 log_error(LOG_LEVEL_ERROR,
1519 "Setting subject name in signed certificate failed: %s", err_buf);
1524 ret = mbedtls_x509write_crt_set_issuer_name(&cert, cert_opt.issuer_name);
1527 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1528 log_error(LOG_LEVEL_ERROR,
1529 "Setting issuer name in signed certificate failed: %s", err_buf);
1534 ret = mbedtls_x509write_crt_set_serial(&cert, &serial);
1537 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1538 log_error(LOG_LEVEL_ERROR,
1539 "Setting serial number in signed certificate failed: %s", err_buf);
1544 ret = mbedtls_x509write_crt_set_validity(&cert, cert_opt.not_before,
1545 cert_opt.not_after);
1548 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1549 log_error(LOG_LEVEL_ERROR,
1550 "Setting validity in signed certificate failed: %s", err_buf);
1556 * Setting the basicConstraints extension for certificate
1558 ret = mbedtls_x509write_crt_set_basic_constraints(&cert, cert_opt.is_ca,
1559 cert_opt.max_pathlen);
1562 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1563 log_error(LOG_LEVEL_ERROR, "Setting the basicConstraints extension "
1564 "in signed certificate failed: %s", err_buf);
1569 #if defined(MBEDTLS_SHA1_C)
1570 /* Setting the subjectKeyIdentifier extension for certificate */
1571 ret = mbedtls_x509write_crt_set_subject_key_identifier(&cert);
1574 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1575 log_error(LOG_LEVEL_ERROR, "mbedtls_x509write_crt_set_subject_key_"
1576 "identifier failed: %s", err_buf);
1581 /* Setting the authorityKeyIdentifier extension for certificate */
1582 ret = mbedtls_x509write_crt_set_authority_key_identifier(&cert);
1585 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1586 log_error(LOG_LEVEL_ERROR, "mbedtls_x509write_crt_set_authority_key_"
1587 "identifier failed: %s", err_buf);
1591 #endif /* MBEDTLS_SHA1_C */
1593 if (!host_is_ip_address(csp->http->host) &&
1594 set_subject_alternative_name(&cert, csp->http->host))
1596 /* Errors are already logged by set_subject_alternative_name() */
1602 * Writing certificate into file
1604 ret = write_certificate(&cert, cert_opt.output_file,
1605 mbedtls_ctr_drbg_random, &ctr_drbg);
1608 log_error(LOG_LEVEL_ERROR, "Writing certificate into file failed");
1614 * Freeing used structures
1616 mbedtls_x509write_crt_free(&cert);
1617 mbedtls_pk_free(&loaded_subject_key);
1618 mbedtls_pk_free(&loaded_issuer_key);
1619 mbedtls_mpi_free(&serial);
1620 mbedtls_x509_crt_free(&issuer_cert);
1622 freez(cert_opt.subject_key);
1623 freez(cert_opt.output_file);
1629 /*********************************************************************
1631 * Function : ssl_verify_callback
1633 * Description : This is a callback function for certificate verification.
1634 * It's called once for each certificate in the server's
1635 * certificate trusted chain and prepares information about
1636 * the certificate. The information can be used to inform
1637 * the user about invalid certificates.
1640 * 1 : csp_void = Current client state (buffers, headers, etc...)
1641 * 2 : crt = certificate from trusted chain
1642 * 3 : depth = depth in trusted chain
1643 * 4 : flags = certificate flags
1645 * Returns : 0 on success and negative value on error
1647 *********************************************************************/
1648 static int ssl_verify_callback(void *csp_void, mbedtls_x509_crt *crt,
1649 int depth, uint32_t *flags)
1651 struct client_state *csp = (struct client_state *)csp_void;
1652 struct certs_chain *last = &(csp->server_certs_chain);
1657 * Searching for last item in certificates linked list
1659 while (last->next != NULL)
1665 * Preparing next item in linked list for next certificate
1667 last->next = malloc_or_die(sizeof(struct certs_chain));
1668 last->next->next = NULL;
1669 memset(last->next->info_buf, 0, sizeof(last->next->info_buf));
1670 memset(last->next->file_buf, 0, sizeof(last->next->file_buf));
1673 * Saving certificate file into buffer
1675 if ((ret = mbedtls_pem_write_buffer(PEM_BEGIN_CRT, PEM_END_CRT,
1676 crt->raw.p, crt->raw.len, (unsigned char *)last->file_buf,
1677 sizeof(last->file_buf)-1, &olen)) != 0)
1679 char err_buf[ERROR_BUF_SIZE];
1681 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1682 log_error(LOG_LEVEL_ERROR, "mbedtls_pem_write_buffer() failed: %s",
1689 * Saving certificate information into buffer
1692 char buf[CERT_INFO_BUF_SIZE];
1695 mbedtls_x509_crt_info(buf, sizeof(buf), CERT_INFO_PREFIX, crt);
1696 encoded_text = html_encode(buf);
1697 if (encoded_text == NULL)
1699 log_error(LOG_LEVEL_ERROR,
1700 "Failed to HTML-encode the certificate information");
1703 strlcpy(last->info_buf, encoded_text, sizeof(last->info_buf));
1704 freez(encoded_text);
1711 /*********************************************************************
1713 * Function : host_to_hash
1715 * Description : Creates MD5 hash from host name. Host name is loaded
1716 * from structure csp and saved again into it.
1719 * 1 : csp = Current client state (buffers, headers, etc...)
1721 * Returns : 1 => Error while creating hash
1722 * 0 => Hash created successfully
1724 *********************************************************************/
1725 static int host_to_hash(struct client_state *csp)
1729 #if !defined(MBEDTLS_MD5_C)
1730 #error mbedTLS needs to be compiled with md5 support
1732 memset(csp->http->hash_of_host, 0, sizeof(csp->http->hash_of_host));
1733 mbedtls_md5((unsigned char *)csp->http->host, strlen(csp->http->host),
1734 csp->http->hash_of_host);
1736 /* Converting hash into string with hex */
1740 if ((ret = sprintf((char *)csp->http->hash_of_host_hex + 2 * i, "%02x",
1741 csp->http->hash_of_host[i])) < 0)
1743 log_error(LOG_LEVEL_ERROR, "Sprintf return value: %d", ret);
1749 #endif /* MBEDTLS_MD5_C */
1752 /*********************************************************************
1754 * Function : seed_rng
1756 * Description : Seeding the RNG for all SSL uses
1759 * 1 : csp = Current client state (buffers, headers, etc...)
1761 * Returns : -1 => RNG wasn't seed successfully
1762 * 0 => RNG is seeded successfully
1764 *********************************************************************/
1765 static int seed_rng(struct client_state *csp)
1768 char err_buf[ERROR_BUF_SIZE];
1770 if (rng_seeded == 0)
1772 privoxy_mutex_lock(&ssl_init_mutex);
1773 if (rng_seeded == 0)
1775 mbedtls_ctr_drbg_init(&ctr_drbg);
1776 mbedtls_entropy_init(&entropy);
1777 ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func,
1781 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1782 log_error(LOG_LEVEL_ERROR,
1783 "mbedtls_ctr_drbg_seed failed: %s", err_buf);
1784 privoxy_mutex_unlock(&ssl_init_mutex);
1789 privoxy_mutex_unlock(&ssl_init_mutex);
1795 /*********************************************************************
1797 * Function : ssl_base64_encode
1799 * Description : Encode a buffer into base64 format.
1802 * 1 : dst = Destination buffer
1803 * 2 : dlen = Destination buffer length
1804 * 3 : olen = Number of bytes written
1805 * 4 : src = Source buffer
1806 * 5 : slen = Amount of data to be encoded
1808 * Returns : 0 on success, error code othervise
1810 *********************************************************************/
1811 extern int ssl_base64_encode(unsigned char *dst, size_t dlen, size_t *olen,
1812 const unsigned char *src, size_t slen)
1814 return mbedtls_base64_encode(dst, dlen, olen, src, slen);
1818 /*********************************************************************
1820 * Function : ssl_crt_verify_info
1822 * Description : Returns an informational string about the verification
1823 * status of a certificate.
1826 * 1 : buf = Buffer to write to
1827 * 2 : size = Maximum size of buffer
1828 * 3 : csp = client state
1832 *********************************************************************/
1833 extern void ssl_crt_verify_info(char *buf, size_t size, struct client_state *csp)
1835 mbedtls_x509_crt_verify_info(buf, size, " ", csp->server_cert_verification_result);
1839 /*********************************************************************
1841 * Function : ssl_release
1843 * Description : Release all SSL resources
1849 *********************************************************************/
1850 extern void ssl_release(void)
1852 if (rng_seeded == 1)
1854 mbedtls_ctr_drbg_free(&ctr_drbg);
1855 mbedtls_entropy_free(&entropy);