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 on socket %d: %N",
174 ssl_attr->mbedtls_attr.socket_fd.fd, send_len, buf+pos);
177 * Sending one part of the buffer
179 while ((ret = mbedtls_ssl_write(ssl,
180 (const unsigned char *)(buf + pos),
181 (size_t)send_len)) < 0)
183 if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
184 ret != MBEDTLS_ERR_SSL_WANT_WRITE)
186 char err_buf[ERROR_BUF_SIZE];
188 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
189 log_error(LOG_LEVEL_ERROR,
190 "Sending data on socket %d over TLS/SSL failed: %s",
191 ssl_attr->mbedtls_attr.socket_fd.fd, err_buf);
195 /* Adding count of sent bytes to position in buffer */
196 pos = pos + send_len;
203 /*********************************************************************
205 * Function : ssl_recv_data
207 * Description : Receives data from given SSL context and puts
211 * 1 : ssl_attr = SSL context to receive data from
212 * 2 : buf = Pointer to buffer where data will be written
213 * 3 : max_length = Maximum number of bytes to read
215 * Returns : Number of bytes read, 0 for EOF, or -1
218 *********************************************************************/
219 extern int ssl_recv_data(struct ssl_attr *ssl_attr, unsigned char *buf, size_t max_length)
221 mbedtls_ssl_context *ssl = &ssl_attr->mbedtls_attr.ssl;
223 memset(buf, 0, max_length);
226 * Receiving data from SSL context into buffer
230 ret = mbedtls_ssl_read(ssl, buf, max_length);
231 } while (ret == MBEDTLS_ERR_SSL_WANT_READ
232 || ret == MBEDTLS_ERR_SSL_WANT_WRITE);
236 char err_buf[ERROR_BUF_SIZE];
238 if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY)
240 log_error(LOG_LEVEL_CONNECT, "The peer notified us that "
241 "the connection on socket %d is going to be closed",
242 ssl_attr->mbedtls_attr.socket_fd.fd);
245 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
246 log_error(LOG_LEVEL_ERROR,
247 "Receiving data on socket %d over TLS/SSL failed: %s",
248 ssl_attr->mbedtls_attr.socket_fd.fd, err_buf);
253 log_error(LOG_LEVEL_RECEIVED, "TLS from socket %d: %N",
254 ssl_attr->mbedtls_attr.socket_fd.fd, ret, buf);
260 /*********************************************************************
262 * Function : create_client_ssl_connection
264 * Description : Creates TLS/SSL secured connection with client
267 * 1 : csp = Current client state (buffers, headers, etc...)
269 * Returns : 0 on success, negative value if connection wasn't created
272 *********************************************************************/
273 extern int create_client_ssl_connection(struct client_state *csp)
275 struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
276 /* Paths to certificates file and key file */
277 char *key_file = NULL;
278 char *ca_file = NULL;
279 char *cert_file = NULL;
281 char err_buf[ERROR_BUF_SIZE];
284 * Initializing mbedtls structures for TLS/SSL connection
286 mbedtls_net_init(&(ssl_attr->mbedtls_attr.socket_fd));
287 mbedtls_ssl_init(&(ssl_attr->mbedtls_attr.ssl));
288 mbedtls_ssl_config_init(&(ssl_attr->mbedtls_attr.conf));
289 mbedtls_x509_crt_init(&(ssl_attr->mbedtls_attr.server_cert));
290 mbedtls_pk_init(&(ssl_attr->mbedtls_attr.prim_key));
291 #if defined(MBEDTLS_SSL_CACHE_C)
292 mbedtls_ssl_cache_init(&(ssl_attr->mbedtls_attr.cache));
296 * Preparing hash of host for creating certificates
298 ret = host_to_hash(csp);
301 log_error(LOG_LEVEL_ERROR, "Generating hash of host failed: %d", ret);
307 * Preparing paths to certificates files and key file
309 ca_file = csp->config->ca_cert_file;
310 cert_file = make_certs_path(csp->config->certificate_directory,
311 (const char *)csp->http->hash_of_host_hex, CERT_FILE_TYPE);
312 key_file = make_certs_path(csp->config->certificate_directory,
313 (const char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
315 if (cert_file == NULL || key_file == NULL)
322 * Generating certificate for requested host. Mutex to prevent
323 * certificate and key inconsistence must be locked.
325 privoxy_mutex_lock(&certificate_mutex);
327 ret = generate_webpage_certificate(csp);
330 log_error(LOG_LEVEL_ERROR,
331 "Generate_webpage_certificate failed: %d", ret);
332 privoxy_mutex_unlock(&certificate_mutex);
336 privoxy_mutex_unlock(&certificate_mutex);
349 * Loading CA file, webpage certificate and key files
351 ret = mbedtls_x509_crt_parse_file(&(ssl_attr->mbedtls_attr.server_cert),
355 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
356 log_error(LOG_LEVEL_ERROR,
357 "Loading webpage certificate %s failed: %s", cert_file, err_buf);
362 ret = mbedtls_x509_crt_parse_file(&(ssl_attr->mbedtls_attr.server_cert),
366 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
367 log_error(LOG_LEVEL_ERROR,
368 "Loading CA certificate %s failed: %s", ca_file, err_buf);
373 ret = mbedtls_pk_parse_keyfile(&(ssl_attr->mbedtls_attr.prim_key),
377 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
378 log_error(LOG_LEVEL_ERROR,
379 "Loading and parsing webpage certificate private key %s failed: %s",
386 * Setting SSL parameters
388 ret = mbedtls_ssl_config_defaults(&(ssl_attr->mbedtls_attr.conf),
389 MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_TRANSPORT_STREAM,
390 MBEDTLS_SSL_PRESET_DEFAULT);
393 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
394 log_error(LOG_LEVEL_ERROR,
395 "mbedtls_ssl_config_defaults failed: %s", err_buf);
400 mbedtls_ssl_conf_rng(&(ssl_attr->mbedtls_attr.conf),
401 mbedtls_ctr_drbg_random, &ctr_drbg);
403 #if defined(MBEDTLS_SSL_CACHE_C)
404 mbedtls_ssl_conf_session_cache(&(ssl_attr->mbedtls_attr.conf),
405 &(ssl_attr->mbedtls_attr.cache), mbedtls_ssl_cache_get,
406 mbedtls_ssl_cache_set);
410 * Setting certificates
412 ret = mbedtls_ssl_conf_own_cert(&(ssl_attr->mbedtls_attr.conf),
413 &(ssl_attr->mbedtls_attr.server_cert),
414 &(ssl_attr->mbedtls_attr.prim_key));
417 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
418 log_error(LOG_LEVEL_ERROR,
419 "mbedtls_ssl_conf_own_cert failed: %s", err_buf);
424 ret = mbedtls_ssl_setup(&(ssl_attr->mbedtls_attr.ssl),
425 &(ssl_attr->mbedtls_attr.conf));
428 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
429 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_setup failed: %s", err_buf);
434 mbedtls_ssl_set_bio(&(ssl_attr->mbedtls_attr.ssl),
435 &(ssl_attr->mbedtls_attr.socket_fd), mbedtls_net_send,
436 mbedtls_net_recv, NULL);
437 mbedtls_ssl_session_reset(&(ssl_attr->mbedtls_attr.ssl));
440 * Setting socket fd in mbedtls_net_context structure. This structure
441 * can't be set by mbedtls functions, because we already have created
442 * a TCP connection when this function is called.
444 ssl_attr->mbedtls_attr.socket_fd.fd = csp->cfd;
447 * Handshake with client
449 log_error(LOG_LEVEL_CONNECT,
450 "Performing the TLS/SSL handshake with client. Hash of host: %s",
451 csp->http->hash_of_host_hex);
452 while ((ret = mbedtls_ssl_handshake(&(ssl_attr->mbedtls_attr.ssl))) != 0)
454 if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
455 ret != MBEDTLS_ERR_SSL_WANT_WRITE)
457 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
458 log_error(LOG_LEVEL_ERROR,
459 "medtls_ssl_handshake with client failed: %s", err_buf);
465 log_error(LOG_LEVEL_CONNECT, "Client successfully connected over TLS/SSL");
466 csp->ssl_with_client_is_opened = 1;
470 * Freeing allocated paths to files
475 /* Freeing structures if connection wasn't created successfully */
478 free_client_ssl_structures(csp);
484 /*********************************************************************
486 * Function : close_client_ssl_connection
488 * Description : Closes TLS/SSL connection with client. This function
489 * checks if this connection is already created.
492 * 1 : csp = Current client state (buffers, headers, etc...)
496 *********************************************************************/
497 extern void close_client_ssl_connection(struct client_state *csp)
499 struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
502 if (csp->ssl_with_client_is_opened == 0)
508 * Notifying the peer that the connection is being closed.
511 ret = mbedtls_ssl_close_notify(&(ssl_attr->mbedtls_attr.ssl));
512 } while (ret == MBEDTLS_ERR_SSL_WANT_WRITE);
514 free_client_ssl_structures(csp);
515 csp->ssl_with_client_is_opened = 0;
519 /*********************************************************************
521 * Function : free_client_ssl_structures
523 * Description : Frees structures used for SSL communication with
527 * 1 : csp = Current client state (buffers, headers, etc...)
531 *********************************************************************/
532 static void free_client_ssl_structures(struct client_state *csp)
534 struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
536 * We can't use function mbedtls_net_free, because this function
537 * inter alia close TCP connection on set fd. Instead of this
538 * function, we change fd to -1, which is the same what does
539 * rest of mbedtls_net_free function.
541 ssl_attr->mbedtls_attr.socket_fd.fd = -1;
543 /* Freeing mbedtls structures */
544 mbedtls_x509_crt_free(&(ssl_attr->mbedtls_attr.server_cert));
545 mbedtls_pk_free(&(ssl_attr->mbedtls_attr.prim_key));
546 mbedtls_ssl_free(&(ssl_attr->mbedtls_attr.ssl));
547 mbedtls_ssl_config_free(&(ssl_attr->mbedtls_attr.conf));
548 #if defined(MBEDTLS_SSL_CACHE_C)
549 mbedtls_ssl_cache_free(&(ssl_attr->mbedtls_attr.cache));
554 /*********************************************************************
556 * Function : create_server_ssl_connection
558 * Description : Creates TLS/SSL secured connection with server.
561 * 1 : csp = Current client state (buffers, headers, etc...)
563 * Returns : 0 on success, negative value if connection wasn't created
566 *********************************************************************/
567 extern int create_server_ssl_connection(struct client_state *csp)
569 struct ssl_attr *ssl_attr = &csp->ssl_server_attr;
571 char err_buf[ERROR_BUF_SIZE];
572 char *trusted_cas_file = NULL;
573 int auth_mode = MBEDTLS_SSL_VERIFY_REQUIRED;
575 csp->server_cert_verification_result = SSL_CERT_NOT_VERIFIED;
576 csp->server_certs_chain.next = NULL;
578 /* Setting path to file with trusted CAs */
579 trusted_cas_file = csp->config->trusted_cas_file;
582 * Initializing mbedtls structures for TLS/SSL connection
584 mbedtls_net_init(&(ssl_attr->mbedtls_attr.socket_fd));
585 mbedtls_ssl_init(&(ssl_attr->mbedtls_attr.ssl));
586 mbedtls_ssl_config_init(&(ssl_attr->mbedtls_attr.conf));
587 mbedtls_x509_crt_init(&(ssl_attr->mbedtls_attr.ca_cert));
590 * Setting socket fd in mbedtls_net_context structure. This structure
591 * can't be set by mbedtls functions, because we already have created
592 * TCP connection when calling this function.
594 ssl_attr->mbedtls_attr.socket_fd.fd = csp->server_connection.sfd;
607 * Loading file with trusted CAs
609 ret = mbedtls_x509_crt_parse_file(&(ssl_attr->mbedtls_attr.ca_cert),
613 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
614 log_error(LOG_LEVEL_ERROR, "Loading trusted CAs file %s failed: %s",
615 trusted_cas_file, err_buf);
621 * Set TLS/SSL options
623 ret = mbedtls_ssl_config_defaults(&(ssl_attr->mbedtls_attr.conf),
624 MBEDTLS_SSL_IS_CLIENT,
625 MBEDTLS_SSL_TRANSPORT_STREAM,
626 MBEDTLS_SSL_PRESET_DEFAULT);
629 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
630 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_config_defaults failed: %s",
637 * Setting how strict should certificate verification be and other
638 * parameters for certificate verification
640 if (csp->dont_verify_certificate)
642 auth_mode = MBEDTLS_SSL_VERIFY_NONE;
645 mbedtls_ssl_conf_authmode(&(ssl_attr->mbedtls_attr.conf), auth_mode);
646 mbedtls_ssl_conf_ca_chain(&(ssl_attr->mbedtls_attr.conf),
647 &(ssl_attr->mbedtls_attr.ca_cert), NULL);
649 /* Setting callback function for certificates verification */
650 mbedtls_ssl_conf_verify(&(ssl_attr->mbedtls_attr.conf),
651 ssl_verify_callback, (void *)csp);
653 mbedtls_ssl_conf_rng(&(ssl_attr->mbedtls_attr.conf),
654 mbedtls_ctr_drbg_random, &ctr_drbg);
656 ret = mbedtls_ssl_setup(&(ssl_attr->mbedtls_attr.ssl),
657 &(ssl_attr->mbedtls_attr.conf));
660 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
661 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_setup failed: %s", err_buf);
667 * Set the hostname to check against the received server certificate
669 ret = mbedtls_ssl_set_hostname(&(ssl_attr->mbedtls_attr.ssl),
673 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
674 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_set_hostname failed: %s",
680 mbedtls_ssl_set_bio(&(ssl_attr->mbedtls_attr.ssl),
681 &(ssl_attr->mbedtls_attr.socket_fd), mbedtls_net_send,
682 mbedtls_net_recv, NULL);
685 * Handshake with server
687 log_error(LOG_LEVEL_CONNECT,
688 "Performing the TLS/SSL handshake with the server");
690 while ((ret = mbedtls_ssl_handshake(&(ssl_attr->mbedtls_attr.ssl))) != 0)
692 if (ret != MBEDTLS_ERR_SSL_WANT_READ
693 && ret != MBEDTLS_ERR_SSL_WANT_WRITE)
695 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
697 if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED)
699 char reason[INVALID_CERT_INFO_BUF_SIZE];
701 csp->server_cert_verification_result =
702 mbedtls_ssl_get_verify_result(&(ssl_attr->mbedtls_attr.ssl));
703 mbedtls_x509_crt_verify_info(reason, sizeof(reason), "",
704 csp->server_cert_verification_result);
706 /* Log the reason without the trailing new line */
707 log_error(LOG_LEVEL_ERROR,
708 "X509 certificate verification for %s failed: %N",
709 csp->http->hostport, strlen(reason)-1, reason);
714 log_error(LOG_LEVEL_ERROR,
715 "mbedtls_ssl_handshake with server failed: %s", err_buf);
716 free_certificate_chain(csp);
723 log_error(LOG_LEVEL_CONNECT, "Server successfully connected over TLS/SSL");
726 * Server certificate chain is valid, so we can clean
727 * chain, because we will not send it to client.
729 free_certificate_chain(csp);
731 csp->ssl_with_server_is_opened = 1;
732 csp->server_cert_verification_result =
733 mbedtls_ssl_get_verify_result(&(ssl_attr->mbedtls_attr.ssl));
736 /* Freeing structures if connection wasn't created successfully */
739 free_server_ssl_structures(csp);
746 /*********************************************************************
748 * Function : close_server_ssl_connection
750 * Description : Closes TLS/SSL connection with server. This function
751 * checks if this connection is already opened.
754 * 1 : csp = Current client state (buffers, headers, etc...)
758 *********************************************************************/
759 extern void close_server_ssl_connection(struct client_state *csp)
761 struct ssl_attr *ssl_attr = &csp->ssl_server_attr;
764 if (csp->ssl_with_server_is_opened == 0)
770 * Notifying the peer that the connection is being closed.
773 ret = mbedtls_ssl_close_notify(&(ssl_attr->mbedtls_attr.ssl));
774 } while (ret == MBEDTLS_ERR_SSL_WANT_WRITE);
776 free_server_ssl_structures(csp);
777 csp->ssl_with_server_is_opened = 0;
781 /*********************************************************************
783 * Function : free_server_ssl_structures
785 * Description : Frees structures used for SSL communication with server
788 * 1 : csp = Current client state (buffers, headers, etc...)
792 *********************************************************************/
793 static void free_server_ssl_structures(struct client_state *csp)
795 struct ssl_attr *ssl_attr = &csp->ssl_server_attr;
797 * We can't use function mbedtls_net_free, because this function
798 * inter alia close TCP connection on set fd. Instead of this
799 * function, we change fd to -1, which is the same what does
800 * rest of mbedtls_net_free function.
802 ssl_attr->mbedtls_attr.socket_fd.fd = -1;
804 mbedtls_x509_crt_free(&(ssl_attr->mbedtls_attr.ca_cert));
805 mbedtls_ssl_free(&(ssl_attr->mbedtls_attr.ssl));
806 mbedtls_ssl_config_free(&(ssl_attr->mbedtls_attr.conf));
810 /*====================== Certificates ======================*/
812 /*********************************************************************
814 * Function : write_certificate
816 * Description : Writes certificate into file.
819 * 1 : crt = certificate to write into file
820 * 2 : output_file = path to save certificate file
821 * 3 : f_rng = mbedtls_ctr_drbg_random
822 * 4 : p_rng = mbedtls_ctr_drbg_context
824 * Returns : Length of written certificate on success or negative value
827 *********************************************************************/
828 static int write_certificate(mbedtls_x509write_cert *crt, const char *output_file,
829 int(*f_rng)(void *, unsigned char *, size_t), void *p_rng)
833 unsigned char cert_buf[CERTIFICATE_BUF_SIZE + 1]; /* Buffer for certificate in PEM format + terminating NULL */
835 char err_buf[ERROR_BUF_SIZE];
837 memset(cert_buf, 0, sizeof(cert_buf));
840 * Writing certificate into PEM string. If buffer is too small, function
841 * returns specific error and no buffer overflow can happen.
843 if ((ret = mbedtls_x509write_crt_pem(crt, cert_buf,
844 sizeof(cert_buf) - 1, f_rng, p_rng)) != 0)
846 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
847 log_error(LOG_LEVEL_ERROR,
848 "Writing certificate into buffer failed: %s", err_buf);
852 len = strlen((char *)cert_buf);
855 * Saving certificate into file
857 if ((f = fopen(output_file, "w")) == NULL)
859 log_error(LOG_LEVEL_ERROR, "Opening file %s to save certificate failed",
864 if (fwrite(cert_buf, 1, len, f) != len)
866 log_error(LOG_LEVEL_ERROR,
867 "Writing certificate into file %s failed", output_file);
878 /*********************************************************************
880 * Function : write_private_key
882 * Description : Writes private key into file and copies saved
883 * content into given pointer to string. If function
884 * returns 0 for success, this copy must be freed by
888 * 1 : key = key to write into file
889 * 2 : ret_buf = pointer to string with created key file content
890 * 3 : key_file_path = path where to save key file
892 * Returns : Length of written private key on success or negative value
895 *********************************************************************/
896 static int write_private_key(mbedtls_pk_context *key, unsigned char **ret_buf,
897 const char *key_file_path)
899 size_t len = 0; /* Length of created key */
900 FILE *f = NULL; /* File to save certificate */
902 char err_buf[ERROR_BUF_SIZE];
904 /* Initializing buffer for key file content */
905 *ret_buf = zalloc_or_die(PRIVATE_KEY_BUF_SIZE + 1);
908 * Writing private key into PEM string
910 if ((ret = mbedtls_pk_write_key_pem(key, *ret_buf, PRIVATE_KEY_BUF_SIZE)) != 0)
912 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
913 log_error(LOG_LEVEL_ERROR,
914 "Writing private key into PEM string failed: %s", err_buf);
918 len = strlen((char *)*ret_buf);
921 * Saving key into file
923 if ((f = fopen(key_file_path, "wb")) == NULL)
925 log_error(LOG_LEVEL_ERROR,
926 "Opening file %s to save private key failed: %E",
932 if (fwrite(*ret_buf, 1, len, f) != len)
935 log_error(LOG_LEVEL_ERROR,
936 "Writing private key into file %s failed",
955 /*********************************************************************
957 * Function : generate_key
959 * Description : Tests if private key for host saved in csp already
960 * exists. If this file doesn't exists, a new key is
961 * generated and saved in a file. The generated key is also
962 * copied into given parameter key_buf, which must be then
963 * freed by caller. If file with key exists, key_buf
964 * contain NULL and no private key is generated.
967 * 1 : csp = Current client state (buffers, headers, etc...)
968 * 2 : key_buf = buffer to save new generated key
970 * Returns : -1 => Error while generating private key
971 * 0 => Key already exists
972 * >0 => Length of generated private key
974 *********************************************************************/
975 static int generate_key(struct client_state *csp, unsigned char **key_buf)
977 mbedtls_pk_context key;
980 char err_buf[ERROR_BUF_SIZE];
982 key_opt.key_file_path = NULL;
985 * Initializing structures for key generating
987 mbedtls_pk_init(&key);
990 * Preparing path for key file and other properties for generating key
992 key_opt.type = MBEDTLS_PK_RSA;
993 key_opt.rsa_keysize = RSA_KEYSIZE;
995 key_opt.key_file_path = make_certs_path(csp->config->certificate_directory,
996 (char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
997 if (key_opt.key_file_path == NULL)
1004 * Test if key already exists. If so, we don't have to create it again.
1006 if (file_exists(key_opt.key_file_path) == 1)
1015 ret = seed_rng(csp);
1023 * Setting attributes of private key and generating it
1025 if ((ret = mbedtls_pk_setup(&key,
1026 mbedtls_pk_info_from_type(key_opt.type))) != 0)
1028 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1029 log_error(LOG_LEVEL_ERROR, "mbedtls_pk_setup failed: %s", err_buf);
1034 ret = mbedtls_rsa_gen_key(mbedtls_pk_rsa(key), mbedtls_ctr_drbg_random,
1035 &ctr_drbg, (unsigned)key_opt.rsa_keysize, RSA_KEY_PUBLIC_EXPONENT);
1038 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1039 log_error(LOG_LEVEL_ERROR, "Key generating failed: %s", err_buf);
1045 * Exporting private key into file
1047 if ((ret = write_private_key(&key, key_buf, key_opt.key_file_path)) < 0)
1049 log_error(LOG_LEVEL_ERROR,
1050 "Writing private key into file %s failed", key_opt.key_file_path);
1057 * Freeing used variables
1059 freez(key_opt.key_file_path);
1061 mbedtls_pk_free(&key);
1067 /*********************************************************************
1069 * Function : ssl_certificate_is_invalid
1071 * Description : Checks whether or not a certificate is valid.
1072 * Currently only checks that the certificate can be
1073 * parsed and that the "valid to" date is in the future.
1076 * 1 : cert_file = The certificate to check
1078 * Returns : 0 => The certificate is valid.
1079 * 1 => The certificate is invalid
1081 *********************************************************************/
1082 static int ssl_certificate_is_invalid(const char *cert_file)
1084 mbedtls_x509_crt cert;
1087 mbedtls_x509_crt_init(&cert);
1089 ret = mbedtls_x509_crt_parse_file(&cert, cert_file);
1092 char err_buf[ERROR_BUF_SIZE];
1094 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1095 log_error(LOG_LEVEL_ERROR,
1096 "Loading certificate %s to check validity failed: %s",
1097 cert_file, err_buf);
1098 mbedtls_x509_crt_free(&cert);
1102 if (mbedtls_x509_time_is_past(&cert.valid_to))
1104 mbedtls_x509_crt_free(&cert);
1109 mbedtls_x509_crt_free(&cert);
1116 /*********************************************************************
1118 * Function : set_subject_alternative_name
1120 * Description : Sets the Subject Alternative Name extension to a cert
1123 * 1 : cert = The certificate to modify
1124 * 2 : hostname = The hostname to add
1126 * Returns : <0 => Error while creating certificate.
1129 *********************************************************************/
1130 static int set_subject_alternative_name(mbedtls_x509write_cert *cert, const char *hostname)
1132 char err_buf[ERROR_BUF_SIZE];
1134 char *subject_alternative_name;
1135 size_t subject_alternative_name_len;
1136 #define MBEDTLS_SUBJECT_ALTERNATIVE_NAME_MAX_LEN 255
1137 unsigned char san_buf[MBEDTLS_SUBJECT_ALTERNATIVE_NAME_MAX_LEN + 1];
1141 subject_alternative_name_len = strlen(hostname) + 1;
1142 subject_alternative_name = zalloc_or_die(subject_alternative_name_len);
1144 strlcpy(subject_alternative_name, hostname, subject_alternative_name_len);
1146 memset(san_buf, 0, sizeof(san_buf));
1148 c = san_buf + sizeof(san_buf);
1151 ret = mbedtls_asn1_write_raw_buffer(&c, san_buf,
1152 (const unsigned char *)subject_alternative_name,
1153 strlen(subject_alternative_name));
1156 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1157 log_error(LOG_LEVEL_ERROR,
1158 "mbedtls_asn1_write_raw_buffer() failed: %s", err_buf);
1163 ret = mbedtls_asn1_write_len(&c, san_buf, strlen(subject_alternative_name));
1166 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1167 log_error(LOG_LEVEL_ERROR,
1168 "mbedtls_asn1_write_len() failed: %s", err_buf);
1173 ret = mbedtls_asn1_write_tag(&c, san_buf, MBEDTLS_ASN1_CONTEXT_SPECIFIC | 2);
1176 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1177 log_error(LOG_LEVEL_ERROR,
1178 "mbedtls_asn1_write_tag() failed: %s", err_buf);
1183 ret = mbedtls_asn1_write_len(&c, san_buf, (size_t)len);
1186 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1187 log_error(LOG_LEVEL_ERROR,
1188 "mbedtls_asn1_write_len() failed: %s", err_buf);
1193 ret = mbedtls_asn1_write_tag(&c, san_buf,
1194 MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE);
1197 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1198 log_error(LOG_LEVEL_ERROR,
1199 "mbedtls_asn1_write_tag() failed: %s", err_buf);
1204 ret = mbedtls_x509write_crt_set_extension(cert,
1205 MBEDTLS_OID_SUBJECT_ALT_NAME,
1206 MBEDTLS_OID_SIZE(MBEDTLS_OID_SUBJECT_ALT_NAME),
1207 0, san_buf + sizeof(san_buf) - len, (size_t)len);
1210 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1211 log_error(LOG_LEVEL_ERROR,
1212 "mbedtls_x509write_crt_set_extension() failed: %s", err_buf);
1216 freez(subject_alternative_name);
1223 /*********************************************************************
1225 * Function : generate_webpage_certificate
1227 * Description : Creates certificate file in presetted directory.
1228 * If certificate already exists, no other certificate
1229 * will be created. Subject of certificate is named
1230 * by csp->http->host from parameter. This function also
1231 * triggers generating of private key for new certificate.
1234 * 1 : csp = Current client state (buffers, headers, etc...)
1236 * Returns : -1 => Error while creating certificate.
1237 * 0 => Certificate already exists.
1238 * >0 => Length of created certificate.
1240 *********************************************************************/
1241 static int generate_webpage_certificate(struct client_state *csp)
1243 mbedtls_x509_crt issuer_cert;
1244 mbedtls_pk_context loaded_issuer_key, loaded_subject_key;
1245 mbedtls_pk_context *issuer_key = &loaded_issuer_key;
1246 mbedtls_pk_context *subject_key = &loaded_subject_key;
1247 mbedtls_x509write_cert cert;
1250 unsigned char *key_buf = NULL; /* Buffer for created key */
1253 char err_buf[ERROR_BUF_SIZE];
1254 cert_options cert_opt;
1255 char cert_valid_from[VALID_DATETIME_BUFLEN];
1256 char cert_valid_to[VALID_DATETIME_BUFLEN];
1258 /* Paths to keys and certificates needed to create certificate */
1259 cert_opt.issuer_key = NULL;
1260 cert_opt.subject_key = NULL;
1261 cert_opt.issuer_crt = NULL;
1263 cert_opt.output_file = make_certs_path(csp->config->certificate_directory,
1264 (const char *)csp->http->hash_of_host_hex, CERT_FILE_TYPE);
1265 if (cert_opt.output_file == NULL)
1270 cert_opt.subject_key = make_certs_path(csp->config->certificate_directory,
1271 (const char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
1272 if (cert_opt.subject_key == NULL)
1274 freez(cert_opt.output_file);
1278 if (file_exists(cert_opt.output_file) == 1)
1280 /* The file exists, but is it valid? */
1281 if (ssl_certificate_is_invalid(cert_opt.output_file))
1283 log_error(LOG_LEVEL_CONNECT,
1284 "Certificate %s is no longer valid. Removing it.",
1285 cert_opt.output_file);
1286 if (unlink(cert_opt.output_file))
1288 log_error(LOG_LEVEL_ERROR, "Failed to unlink %s: %E",
1289 cert_opt.output_file);
1291 freez(cert_opt.output_file);
1292 freez(cert_opt.subject_key);
1296 if (unlink(cert_opt.subject_key))
1298 log_error(LOG_LEVEL_ERROR, "Failed to unlink %s: %E",
1299 cert_opt.subject_key);
1301 freez(cert_opt.output_file);
1302 freez(cert_opt.subject_key);
1309 freez(cert_opt.output_file);
1310 freez(cert_opt.subject_key);
1317 * Create key for requested host
1319 int subject_key_len = generate_key(csp, &key_buf);
1320 if (subject_key_len < 0)
1322 freez(cert_opt.output_file);
1323 freez(cert_opt.subject_key);
1324 log_error(LOG_LEVEL_ERROR, "Key generating failed");
1329 * Initializing structures for certificate generating
1331 mbedtls_x509write_crt_init(&cert);
1332 mbedtls_x509write_crt_set_md_alg(&cert, CERT_SIGNATURE_ALGORITHM);
1333 mbedtls_pk_init(&loaded_issuer_key);
1334 mbedtls_pk_init(&loaded_subject_key);
1335 mbedtls_mpi_init(&serial);
1336 mbedtls_x509_crt_init(&issuer_cert);
1339 * Presetting parameters for certificate. We must compute total length
1342 size_t cert_params_len = strlen(CERT_PARAM_COMMON_NAME) +
1343 strlen(CERT_PARAM_ORGANIZATION) + strlen(CERT_PARAM_COUNTRY) +
1344 strlen(CERT_PARAM_ORG_UNIT) +
1345 3 * strlen(csp->http->host) + 1;
1346 char cert_params[cert_params_len];
1347 memset(cert_params, 0, cert_params_len);
1350 * Converting unsigned long serial number to char * serial number.
1351 * We must compute length of serial number in string + terminating null.
1353 unsigned long certificate_serial = get_certificate_serial(csp);
1354 unsigned long certificate_serial_time = (unsigned long)time(NULL);
1355 int serial_num_size = snprintf(NULL, 0, "%lu%lu",
1356 certificate_serial_time, certificate_serial) + 1;
1357 if (serial_num_size <= 0)
1359 serial_num_size = 1;
1362 char serial_num_text[serial_num_size]; /* Buffer for serial number */
1363 ret = snprintf(serial_num_text, (size_t)serial_num_size, "%lu%lu",
1364 certificate_serial_time, certificate_serial);
1365 if (ret < 0 || ret >= serial_num_size)
1367 log_error(LOG_LEVEL_ERROR,
1368 "Converting certificate serial number into string failed");
1374 * Preparing parameters for certificate
1376 strlcpy(cert_params, CERT_PARAM_COMMON_NAME, cert_params_len);
1377 strlcat(cert_params, csp->http->host, cert_params_len);
1378 strlcat(cert_params, CERT_PARAM_ORGANIZATION, cert_params_len);
1379 strlcat(cert_params, csp->http->host, cert_params_len);
1380 strlcat(cert_params, CERT_PARAM_ORG_UNIT, cert_params_len);
1381 strlcat(cert_params, csp->http->host, cert_params_len);
1382 strlcat(cert_params, CERT_PARAM_COUNTRY, cert_params_len);
1384 cert_opt.issuer_crt = csp->config->ca_cert_file;
1385 cert_opt.issuer_key = csp->config->ca_key_file;
1387 if (get_certificate_valid_from_date(cert_valid_from, sizeof(cert_valid_from), VALID_DATETIME_FMT)
1388 || get_certificate_valid_to_date(cert_valid_to, sizeof(cert_valid_to), VALID_DATETIME_FMT))
1390 log_error(LOG_LEVEL_ERROR, "Generating one of the validity dates failed");
1395 cert_opt.subject_pwd = CERT_SUBJECT_PASSWORD;
1396 cert_opt.issuer_pwd = csp->config->ca_password;
1397 cert_opt.subject_name = cert_params;
1398 cert_opt.not_before = cert_valid_from;
1399 cert_opt.not_after = cert_valid_to;
1400 cert_opt.serial = serial_num_text;
1402 cert_opt.max_pathlen = -1;
1405 * Test if the private key was already created.
1406 * XXX: Can this still happen?
1408 if (subject_key_len == 0)
1410 log_error(LOG_LEVEL_ERROR, "Subject key was already created");
1418 ret = seed_rng(csp);
1426 * Parse serial to MPI
1428 ret = mbedtls_mpi_read_string(&serial, 10, cert_opt.serial);
1431 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1432 log_error(LOG_LEVEL_ERROR,
1433 "mbedtls_mpi_read_string failed: %s", err_buf);
1439 * Loading certificates
1441 ret = mbedtls_x509_crt_parse_file(&issuer_cert, cert_opt.issuer_crt);
1444 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1445 log_error(LOG_LEVEL_ERROR, "Loading issuer certificate %s failed: %s",
1446 cert_opt.issuer_crt, err_buf);
1451 ret = mbedtls_x509_dn_gets(cert_opt.issuer_name,
1452 sizeof(cert_opt.issuer_name), &issuer_cert.subject);
1455 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1456 log_error(LOG_LEVEL_ERROR, "mbedtls_x509_dn_gets failed: %s", err_buf);
1462 * Loading keys from file or from buffer
1464 if (key_buf != NULL && subject_key_len > 0)
1466 /* Key was created in this function and is stored in buffer */
1467 ret = mbedtls_pk_parse_key(&loaded_subject_key, key_buf,
1468 (size_t)(subject_key_len + 1), (unsigned const char *)
1469 cert_opt.subject_pwd, strlen(cert_opt.subject_pwd));
1473 /* Key wasn't created in this function, because it already existed */
1474 ret = mbedtls_pk_parse_keyfile(&loaded_subject_key,
1475 cert_opt.subject_key, cert_opt.subject_pwd);
1480 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1481 log_error(LOG_LEVEL_ERROR, "Parsing subject key %s failed: %s",
1482 cert_opt.subject_key, err_buf);
1487 ret = mbedtls_pk_parse_keyfile(&loaded_issuer_key, cert_opt.issuer_key,
1488 cert_opt.issuer_pwd);
1491 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1492 log_error(LOG_LEVEL_ERROR,
1493 "Parsing issuer key %s failed: %s", cert_opt.issuer_key, err_buf);
1499 * Check if key and issuer certificate match
1501 if (!mbedtls_pk_can_do(&issuer_cert.pk, MBEDTLS_PK_RSA) ||
1502 mbedtls_mpi_cmp_mpi(&mbedtls_pk_rsa(issuer_cert.pk)->N,
1503 &mbedtls_pk_rsa(*issuer_key)->N) != 0 ||
1504 mbedtls_mpi_cmp_mpi(&mbedtls_pk_rsa(issuer_cert.pk)->E,
1505 &mbedtls_pk_rsa(*issuer_key)->E) != 0)
1507 log_error(LOG_LEVEL_ERROR,
1508 "Issuer key doesn't match issuer certificate");
1513 mbedtls_x509write_crt_set_subject_key(&cert, subject_key);
1514 mbedtls_x509write_crt_set_issuer_key(&cert, issuer_key);
1517 * Setting parameters of signed certificate
1519 ret = mbedtls_x509write_crt_set_subject_name(&cert, cert_opt.subject_name);
1522 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1523 log_error(LOG_LEVEL_ERROR,
1524 "Setting subject name in signed certificate failed: %s", err_buf);
1529 ret = mbedtls_x509write_crt_set_issuer_name(&cert, cert_opt.issuer_name);
1532 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1533 log_error(LOG_LEVEL_ERROR,
1534 "Setting issuer name in signed certificate failed: %s", err_buf);
1539 ret = mbedtls_x509write_crt_set_serial(&cert, &serial);
1542 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1543 log_error(LOG_LEVEL_ERROR,
1544 "Setting serial number in signed certificate failed: %s", err_buf);
1549 ret = mbedtls_x509write_crt_set_validity(&cert, cert_opt.not_before,
1550 cert_opt.not_after);
1553 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1554 log_error(LOG_LEVEL_ERROR,
1555 "Setting validity in signed certificate failed: %s", err_buf);
1561 * Setting the basicConstraints extension for certificate
1563 ret = mbedtls_x509write_crt_set_basic_constraints(&cert, cert_opt.is_ca,
1564 cert_opt.max_pathlen);
1567 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1568 log_error(LOG_LEVEL_ERROR, "Setting the basicConstraints extension "
1569 "in signed certificate failed: %s", err_buf);
1574 #if defined(MBEDTLS_SHA1_C)
1575 /* Setting the subjectKeyIdentifier extension for certificate */
1576 ret = mbedtls_x509write_crt_set_subject_key_identifier(&cert);
1579 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1580 log_error(LOG_LEVEL_ERROR, "mbedtls_x509write_crt_set_subject_key_"
1581 "identifier failed: %s", err_buf);
1586 /* Setting the authorityKeyIdentifier extension for certificate */
1587 ret = mbedtls_x509write_crt_set_authority_key_identifier(&cert);
1590 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1591 log_error(LOG_LEVEL_ERROR, "mbedtls_x509write_crt_set_authority_key_"
1592 "identifier failed: %s", err_buf);
1596 #endif /* MBEDTLS_SHA1_C */
1598 if (!host_is_ip_address(csp->http->host) &&
1599 set_subject_alternative_name(&cert, csp->http->host))
1601 /* Errors are already logged by set_subject_alternative_name() */
1607 * Writing certificate into file
1609 ret = write_certificate(&cert, cert_opt.output_file,
1610 mbedtls_ctr_drbg_random, &ctr_drbg);
1613 log_error(LOG_LEVEL_ERROR, "Writing certificate into file failed");
1619 * Freeing used structures
1621 mbedtls_x509write_crt_free(&cert);
1622 mbedtls_pk_free(&loaded_subject_key);
1623 mbedtls_pk_free(&loaded_issuer_key);
1624 mbedtls_mpi_free(&serial);
1625 mbedtls_x509_crt_free(&issuer_cert);
1627 freez(cert_opt.subject_key);
1628 freez(cert_opt.output_file);
1634 /*********************************************************************
1636 * Function : ssl_verify_callback
1638 * Description : This is a callback function for certificate verification.
1639 * It's called once for each certificate in the server's
1640 * certificate trusted chain and prepares information about
1641 * the certificate. The information can be used to inform
1642 * the user about invalid certificates.
1645 * 1 : csp_void = Current client state (buffers, headers, etc...)
1646 * 2 : crt = certificate from trusted chain
1647 * 3 : depth = depth in trusted chain
1648 * 4 : flags = certificate flags
1650 * Returns : 0 on success and negative value on error
1652 *********************************************************************/
1653 static int ssl_verify_callback(void *csp_void, mbedtls_x509_crt *crt,
1654 int depth, uint32_t *flags)
1656 struct client_state *csp = (struct client_state *)csp_void;
1657 struct certs_chain *last = &(csp->server_certs_chain);
1662 * Searching for last item in certificates linked list
1664 while (last->next != NULL)
1670 * Preparing next item in linked list for next certificate
1672 last->next = malloc_or_die(sizeof(struct certs_chain));
1673 last->next->next = NULL;
1674 memset(last->next->info_buf, 0, sizeof(last->next->info_buf));
1675 memset(last->next->file_buf, 0, sizeof(last->next->file_buf));
1678 * Saving certificate file into buffer
1680 if ((ret = mbedtls_pem_write_buffer(PEM_BEGIN_CRT, PEM_END_CRT,
1681 crt->raw.p, crt->raw.len, (unsigned char *)last->file_buf,
1682 sizeof(last->file_buf)-1, &olen)) != 0)
1684 char err_buf[ERROR_BUF_SIZE];
1686 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1687 log_error(LOG_LEVEL_ERROR, "mbedtls_pem_write_buffer() failed: %s",
1694 * Saving certificate information into buffer
1697 char buf[CERT_INFO_BUF_SIZE];
1700 mbedtls_x509_crt_info(buf, sizeof(buf), CERT_INFO_PREFIX, crt);
1701 encoded_text = html_encode(buf);
1702 if (encoded_text == NULL)
1704 log_error(LOG_LEVEL_ERROR,
1705 "Failed to HTML-encode the certificate information");
1708 strlcpy(last->info_buf, encoded_text, sizeof(last->info_buf));
1709 freez(encoded_text);
1716 /*********************************************************************
1718 * Function : host_to_hash
1720 * Description : Creates MD5 hash from host name. Host name is loaded
1721 * from structure csp and saved again into it.
1724 * 1 : csp = Current client state (buffers, headers, etc...)
1726 * Returns : 1 => Error while creating hash
1727 * 0 => Hash created successfully
1729 *********************************************************************/
1730 static int host_to_hash(struct client_state *csp)
1734 #if !defined(MBEDTLS_MD5_C)
1735 #error mbedTLS needs to be compiled with md5 support
1737 memset(csp->http->hash_of_host, 0, sizeof(csp->http->hash_of_host));
1738 mbedtls_md5((unsigned char *)csp->http->host, strlen(csp->http->host),
1739 csp->http->hash_of_host);
1741 /* Converting hash into string with hex */
1745 if ((ret = sprintf((char *)csp->http->hash_of_host_hex + 2 * i, "%02x",
1746 csp->http->hash_of_host[i])) < 0)
1748 log_error(LOG_LEVEL_ERROR, "Sprintf return value: %d", ret);
1754 #endif /* MBEDTLS_MD5_C */
1757 /*********************************************************************
1759 * Function : seed_rng
1761 * Description : Seeding the RNG for all SSL uses
1764 * 1 : csp = Current client state (buffers, headers, etc...)
1766 * Returns : -1 => RNG wasn't seed successfully
1767 * 0 => RNG is seeded successfully
1769 *********************************************************************/
1770 static int seed_rng(struct client_state *csp)
1773 char err_buf[ERROR_BUF_SIZE];
1775 if (rng_seeded == 0)
1777 privoxy_mutex_lock(&ssl_init_mutex);
1778 if (rng_seeded == 0)
1780 mbedtls_ctr_drbg_init(&ctr_drbg);
1781 mbedtls_entropy_init(&entropy);
1782 ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func,
1786 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1787 log_error(LOG_LEVEL_ERROR,
1788 "mbedtls_ctr_drbg_seed failed: %s", err_buf);
1789 privoxy_mutex_unlock(&ssl_init_mutex);
1794 privoxy_mutex_unlock(&ssl_init_mutex);
1800 /*********************************************************************
1802 * Function : ssl_base64_encode
1804 * Description : Encode a buffer into base64 format.
1807 * 1 : dst = Destination buffer
1808 * 2 : dlen = Destination buffer length
1809 * 3 : olen = Number of bytes written
1810 * 4 : src = Source buffer
1811 * 5 : slen = Amount of data to be encoded
1813 * Returns : 0 on success, error code othervise
1815 *********************************************************************/
1816 extern int ssl_base64_encode(unsigned char *dst, size_t dlen, size_t *olen,
1817 const unsigned char *src, size_t slen)
1819 return mbedtls_base64_encode(dst, dlen, olen, src, slen);
1823 /*********************************************************************
1825 * Function : ssl_crt_verify_info
1827 * Description : Returns an informational string about the verification
1828 * status of a certificate.
1831 * 1 : buf = Buffer to write to
1832 * 2 : size = Maximum size of buffer
1833 * 3 : csp = client state
1837 *********************************************************************/
1838 extern void ssl_crt_verify_info(char *buf, size_t size, struct client_state *csp)
1840 mbedtls_x509_crt_verify_info(buf, size, " ", csp->server_cert_verification_result);
1844 /*********************************************************************
1846 * Function : ssl_release
1848 * Description : Release all SSL resources
1854 *********************************************************************/
1855 extern void ssl_release(void)
1857 if (rng_seeded == 1)
1859 mbedtls_ctr_drbg_free(&ctr_drbg);
1860 mbedtls_entropy_free(&entropy);