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 : ssl_debug_callback
259 * Description : Debug callback function for mbedtls library.
260 * Prints info into log file.
263 * 1 : ctx = File to save log in
264 * 2 : level = Debug level
265 * 3 : file = File calling debug message
266 * 4 : line = Line calling debug message
267 * 5 : str = Debug message
271 *********************************************************************/
272 static void ssl_debug_callback(void *ctx, int level, const char *file, int line, const char *str)
276 fprintf((FILE *)ctx, "%s:%04d: %s", file, line, str);
278 log_error(LOG_LEVEL_INFO, "SSL debug message: %s:%04d: %s", file, line, str);
283 /*********************************************************************
285 * Function : create_client_ssl_connection
287 * Description : Creates TLS/SSL secured connection with client
290 * 1 : csp = Current client state (buffers, headers, etc...)
292 * Returns : 0 on success, negative value if connection wasn't created
295 *********************************************************************/
296 extern int create_client_ssl_connection(struct client_state *csp)
298 struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
299 /* Paths to certificates file and key file */
300 char *key_file = NULL;
301 char *ca_file = NULL;
302 char *cert_file = NULL;
304 char err_buf[ERROR_BUF_SIZE];
307 * Initializing mbedtls structures for TLS/SSL connection
309 mbedtls_net_init(&(ssl_attr->mbedtls_attr.socket_fd));
310 mbedtls_ssl_init(&(ssl_attr->mbedtls_attr.ssl));
311 mbedtls_ssl_config_init(&(ssl_attr->mbedtls_attr.conf));
312 mbedtls_x509_crt_init(&(ssl_attr->mbedtls_attr.server_cert));
313 mbedtls_pk_init(&(ssl_attr->mbedtls_attr.prim_key));
314 #if defined(MBEDTLS_SSL_CACHE_C)
315 mbedtls_ssl_cache_init(&(ssl_attr->mbedtls_attr.cache));
319 * Preparing hash of host for creating certificates
321 ret = host_to_hash(csp);
324 log_error(LOG_LEVEL_ERROR, "Generating hash of host failed: %d", ret);
330 * Preparing paths to certificates files and key file
332 ca_file = csp->config->ca_cert_file;
333 cert_file = make_certs_path(csp->config->certificate_directory,
334 (const char *)csp->http->hash_of_host_hex, CERT_FILE_TYPE);
335 key_file = make_certs_path(csp->config->certificate_directory,
336 (const char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
338 if (cert_file == NULL || key_file == NULL)
345 * Generating certificate for requested host. Mutex to prevent
346 * certificate and key inconsistence must be locked.
348 privoxy_mutex_lock(&certificate_mutex);
350 ret = generate_webpage_certificate(csp);
353 log_error(LOG_LEVEL_ERROR,
354 "Generate_webpage_certificate failed: %d", ret);
355 privoxy_mutex_unlock(&certificate_mutex);
359 privoxy_mutex_unlock(&certificate_mutex);
372 * Loading CA file, webpage certificate and key files
374 ret = mbedtls_x509_crt_parse_file(&(ssl_attr->mbedtls_attr.server_cert),
378 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
379 log_error(LOG_LEVEL_ERROR,
380 "Loading webpage certificate %s failed: %s", cert_file, err_buf);
385 ret = mbedtls_x509_crt_parse_file(&(ssl_attr->mbedtls_attr.server_cert),
389 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
390 log_error(LOG_LEVEL_ERROR,
391 "Loading CA certificate %s failed: %s", ca_file, err_buf);
396 ret = mbedtls_pk_parse_keyfile(&(ssl_attr->mbedtls_attr.prim_key),
400 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
401 log_error(LOG_LEVEL_ERROR,
402 "Loading and parsing webpage certificate private key %s failed: %s",
409 * Setting SSL parameters
411 ret = mbedtls_ssl_config_defaults(&(ssl_attr->mbedtls_attr.conf),
412 MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_TRANSPORT_STREAM,
413 MBEDTLS_SSL_PRESET_DEFAULT);
416 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
417 log_error(LOG_LEVEL_ERROR,
418 "mbedtls_ssl_config_defaults failed: %s", err_buf);
423 mbedtls_ssl_conf_rng(&(ssl_attr->mbedtls_attr.conf),
424 mbedtls_ctr_drbg_random, &ctr_drbg);
425 mbedtls_ssl_conf_dbg(&(ssl_attr->mbedtls_attr.conf),
426 ssl_debug_callback, stdout);
428 #if defined(MBEDTLS_SSL_CACHE_C)
429 mbedtls_ssl_conf_session_cache(&(ssl_attr->mbedtls_attr.conf),
430 &(ssl_attr->mbedtls_attr.cache), mbedtls_ssl_cache_get,
431 mbedtls_ssl_cache_set);
435 * Setting certificates
437 ret = mbedtls_ssl_conf_own_cert(&(ssl_attr->mbedtls_attr.conf),
438 &(ssl_attr->mbedtls_attr.server_cert),
439 &(ssl_attr->mbedtls_attr.prim_key));
442 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
443 log_error(LOG_LEVEL_ERROR,
444 "mbedtls_ssl_conf_own_cert failed: %s", err_buf);
449 ret = mbedtls_ssl_setup(&(ssl_attr->mbedtls_attr.ssl),
450 &(ssl_attr->mbedtls_attr.conf));
453 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
454 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_setup failed: %s", err_buf);
459 mbedtls_ssl_set_bio(&(ssl_attr->mbedtls_attr.ssl),
460 &(ssl_attr->mbedtls_attr.socket_fd), mbedtls_net_send,
461 mbedtls_net_recv, NULL);
462 mbedtls_ssl_session_reset(&(ssl_attr->mbedtls_attr.ssl));
465 * Setting socket fd in mbedtls_net_context structure. This structure
466 * can't be set by mbedtls functions, because we already have created
467 * a TCP connection when this function is called.
469 ssl_attr->mbedtls_attr.socket_fd.fd = csp->cfd;
472 * Handshake with client
474 log_error(LOG_LEVEL_CONNECT,
475 "Performing the TLS/SSL handshake with client. Hash of host: %s",
476 csp->http->hash_of_host_hex);
477 while ((ret = mbedtls_ssl_handshake(&(ssl_attr->mbedtls_attr.ssl))) != 0)
479 if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
480 ret != MBEDTLS_ERR_SSL_WANT_WRITE)
482 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
483 log_error(LOG_LEVEL_ERROR,
484 "medtls_ssl_handshake with client failed: %s", err_buf);
490 log_error(LOG_LEVEL_CONNECT, "Client successfully connected over TLS/SSL");
491 csp->ssl_with_client_is_opened = 1;
495 * Freeing allocated paths to files
500 /* Freeing structures if connection wasn't created successfully */
503 free_client_ssl_structures(csp);
509 /*********************************************************************
511 * Function : close_client_ssl_connection
513 * Description : Closes TLS/SSL connection with client. This function
514 * checks if this connection is already created.
517 * 1 : csp = Current client state (buffers, headers, etc...)
521 *********************************************************************/
522 extern void close_client_ssl_connection(struct client_state *csp)
524 struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
527 if (csp->ssl_with_client_is_opened == 0)
533 * Notifying the peer that the connection is being closed.
536 ret = mbedtls_ssl_close_notify(&(ssl_attr->mbedtls_attr.ssl));
537 } while (ret == MBEDTLS_ERR_SSL_WANT_WRITE);
539 free_client_ssl_structures(csp);
540 csp->ssl_with_client_is_opened = 0;
544 /*********************************************************************
546 * Function : free_client_ssl_structures
548 * Description : Frees structures used for SSL communication with
552 * 1 : csp = Current client state (buffers, headers, etc...)
556 *********************************************************************/
557 static void free_client_ssl_structures(struct client_state *csp)
559 struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
561 * We can't use function mbedtls_net_free, because this function
562 * inter alia close TCP connection on set fd. Instead of this
563 * function, we change fd to -1, which is the same what does
564 * rest of mbedtls_net_free function.
566 ssl_attr->mbedtls_attr.socket_fd.fd = -1;
568 /* Freeing mbedtls structures */
569 mbedtls_x509_crt_free(&(ssl_attr->mbedtls_attr.server_cert));
570 mbedtls_pk_free(&(ssl_attr->mbedtls_attr.prim_key));
571 mbedtls_ssl_free(&(ssl_attr->mbedtls_attr.ssl));
572 mbedtls_ssl_config_free(&(ssl_attr->mbedtls_attr.conf));
573 #if defined(MBEDTLS_SSL_CACHE_C)
574 mbedtls_ssl_cache_free(&(ssl_attr->mbedtls_attr.cache));
579 /*********************************************************************
581 * Function : create_server_ssl_connection
583 * Description : Creates TLS/SSL secured connection with server.
586 * 1 : csp = Current client state (buffers, headers, etc...)
588 * Returns : 0 on success, negative value if connection wasn't created
591 *********************************************************************/
592 extern int create_server_ssl_connection(struct client_state *csp)
594 struct ssl_attr *ssl_attr = &csp->ssl_server_attr;
596 char err_buf[ERROR_BUF_SIZE];
597 char *trusted_cas_file = NULL;
598 int auth_mode = MBEDTLS_SSL_VERIFY_REQUIRED;
600 csp->server_cert_verification_result = SSL_CERT_NOT_VERIFIED;
601 csp->server_certs_chain.next = NULL;
603 /* Setting path to file with trusted CAs */
604 trusted_cas_file = csp->config->trusted_cas_file;
607 * Initializing mbedtls structures for TLS/SSL connection
609 mbedtls_net_init(&(ssl_attr->mbedtls_attr.socket_fd));
610 mbedtls_ssl_init(&(ssl_attr->mbedtls_attr.ssl));
611 mbedtls_ssl_config_init(&(ssl_attr->mbedtls_attr.conf));
612 mbedtls_x509_crt_init(&(ssl_attr->mbedtls_attr.ca_cert));
615 * Setting socket fd in mbedtls_net_context structure. This structure
616 * can't be set by mbedtls functions, because we already have created
617 * TCP connection when calling this function.
619 ssl_attr->mbedtls_attr.socket_fd.fd = csp->server_connection.sfd;
632 * Loading file with trusted CAs
634 ret = mbedtls_x509_crt_parse_file(&(ssl_attr->mbedtls_attr.ca_cert),
638 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
639 log_error(LOG_LEVEL_ERROR, "Loading trusted CAs file %s failed: %s",
640 trusted_cas_file, err_buf);
646 * Set TLS/SSL options
648 ret = mbedtls_ssl_config_defaults(&(ssl_attr->mbedtls_attr.conf),
649 MBEDTLS_SSL_IS_CLIENT,
650 MBEDTLS_SSL_TRANSPORT_STREAM,
651 MBEDTLS_SSL_PRESET_DEFAULT);
654 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
655 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_config_defaults failed: %s",
662 * Setting how strict should certificate verification be and other
663 * parameters for certificate verification
665 if (csp->dont_verify_certificate)
667 auth_mode = MBEDTLS_SSL_VERIFY_NONE;
670 mbedtls_ssl_conf_authmode(&(ssl_attr->mbedtls_attr.conf), auth_mode);
671 mbedtls_ssl_conf_ca_chain(&(ssl_attr->mbedtls_attr.conf),
672 &(ssl_attr->mbedtls_attr.ca_cert), NULL);
674 /* Setting callback function for certificates verification */
675 mbedtls_ssl_conf_verify(&(ssl_attr->mbedtls_attr.conf),
676 ssl_verify_callback, (void *)csp);
678 mbedtls_ssl_conf_rng(&(ssl_attr->mbedtls_attr.conf),
679 mbedtls_ctr_drbg_random, &ctr_drbg);
680 mbedtls_ssl_conf_dbg(&(ssl_attr->mbedtls_attr.conf),
681 ssl_debug_callback, stdout);
683 ret = mbedtls_ssl_setup(&(ssl_attr->mbedtls_attr.ssl),
684 &(ssl_attr->mbedtls_attr.conf));
687 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
688 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_setup failed: %s", err_buf);
694 * Set the hostname to check against the received server certificate
696 ret = mbedtls_ssl_set_hostname(&(ssl_attr->mbedtls_attr.ssl),
700 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
701 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_set_hostname failed: %s",
707 mbedtls_ssl_set_bio(&(ssl_attr->mbedtls_attr.ssl),
708 &(ssl_attr->mbedtls_attr.socket_fd), mbedtls_net_send,
709 mbedtls_net_recv, NULL);
712 * Handshake with server
714 log_error(LOG_LEVEL_CONNECT,
715 "Performing the TLS/SSL handshake with the server");
717 while ((ret = mbedtls_ssl_handshake(&(ssl_attr->mbedtls_attr.ssl))) != 0)
719 if (ret != MBEDTLS_ERR_SSL_WANT_READ
720 && ret != MBEDTLS_ERR_SSL_WANT_WRITE)
722 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
724 if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED)
726 char reason[INVALID_CERT_INFO_BUF_SIZE];
728 csp->server_cert_verification_result =
729 mbedtls_ssl_get_verify_result(&(ssl_attr->mbedtls_attr.ssl));
730 mbedtls_x509_crt_verify_info(reason, sizeof(reason), "",
731 csp->server_cert_verification_result);
733 /* Log the reason without the trailing new line */
734 log_error(LOG_LEVEL_ERROR,
735 "X509 certificate verification for %s failed: %N",
736 csp->http->hostport, strlen(reason)-1, reason);
741 log_error(LOG_LEVEL_ERROR,
742 "mbedtls_ssl_handshake with server failed: %s", err_buf);
743 free_certificate_chain(csp);
750 log_error(LOG_LEVEL_CONNECT, "Server successfully connected over TLS/SSL");
753 * Server certificate chain is valid, so we can clean
754 * chain, because we will not send it to client.
756 free_certificate_chain(csp);
758 csp->ssl_with_server_is_opened = 1;
759 csp->server_cert_verification_result =
760 mbedtls_ssl_get_verify_result(&(ssl_attr->mbedtls_attr.ssl));
763 /* Freeing structures if connection wasn't created successfully */
766 free_server_ssl_structures(csp);
773 /*********************************************************************
775 * Function : close_server_ssl_connection
777 * Description : Closes TLS/SSL connection with server. This function
778 * checks if this connection is already opened.
781 * 1 : csp = Current client state (buffers, headers, etc...)
785 *********************************************************************/
786 extern void close_server_ssl_connection(struct client_state *csp)
788 struct ssl_attr *ssl_attr = &csp->ssl_server_attr;
791 if (csp->ssl_with_server_is_opened == 0)
797 * Notifying the peer that the connection is being closed.
800 ret = mbedtls_ssl_close_notify(&(ssl_attr->mbedtls_attr.ssl));
801 } while (ret == MBEDTLS_ERR_SSL_WANT_WRITE);
803 free_server_ssl_structures(csp);
804 csp->ssl_with_server_is_opened = 0;
808 /*********************************************************************
810 * Function : free_server_ssl_structures
812 * Description : Frees structures used for SSL communication with server
815 * 1 : csp = Current client state (buffers, headers, etc...)
819 *********************************************************************/
820 static void free_server_ssl_structures(struct client_state *csp)
822 struct ssl_attr *ssl_attr = &csp->ssl_server_attr;
824 * We can't use function mbedtls_net_free, because this function
825 * inter alia close TCP connection on set fd. Instead of this
826 * function, we change fd to -1, which is the same what does
827 * rest of mbedtls_net_free function.
829 ssl_attr->mbedtls_attr.socket_fd.fd = -1;
831 mbedtls_x509_crt_free(&(ssl_attr->mbedtls_attr.ca_cert));
832 mbedtls_ssl_free(&(ssl_attr->mbedtls_attr.ssl));
833 mbedtls_ssl_config_free(&(ssl_attr->mbedtls_attr.conf));
837 /*====================== Certificates ======================*/
839 /*********************************************************************
841 * Function : write_certificate
843 * Description : Writes certificate into file.
846 * 1 : crt = certificate to write into file
847 * 2 : output_file = path to save certificate file
848 * 3 : f_rng = mbedtls_ctr_drbg_random
849 * 4 : p_rng = mbedtls_ctr_drbg_context
851 * Returns : Length of written certificate on success or negative value
854 *********************************************************************/
855 static int write_certificate(mbedtls_x509write_cert *crt, const char *output_file,
856 int(*f_rng)(void *, unsigned char *, size_t), void *p_rng)
860 unsigned char cert_buf[CERTIFICATE_BUF_SIZE + 1]; /* Buffer for certificate in PEM format + terminating NULL */
862 char err_buf[ERROR_BUF_SIZE];
864 memset(cert_buf, 0, sizeof(cert_buf));
867 * Writing certificate into PEM string. If buffer is too small, function
868 * returns specific error and no buffer overflow can happen.
870 if ((ret = mbedtls_x509write_crt_pem(crt, cert_buf,
871 sizeof(cert_buf) - 1, f_rng, p_rng)) != 0)
873 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
874 log_error(LOG_LEVEL_ERROR,
875 "Writing certificate into buffer failed: %s", err_buf);
879 len = strlen((char *)cert_buf);
882 * Saving certificate into file
884 if ((f = fopen(output_file, "w")) == NULL)
886 log_error(LOG_LEVEL_ERROR, "Opening file %s to save certificate failed",
891 if (fwrite(cert_buf, 1, len, f) != len)
893 log_error(LOG_LEVEL_ERROR,
894 "Writing certificate into file %s failed", output_file);
905 /*********************************************************************
907 * Function : write_private_key
909 * Description : Writes private key into file and copies saved
910 * content into given pointer to string. If function
911 * returns 0 for success, this copy must be freed by
915 * 1 : key = key to write into file
916 * 2 : ret_buf = pointer to string with created key file content
917 * 3 : key_file_path = path where to save key file
919 * Returns : Length of written private key on success or negative value
922 *********************************************************************/
923 static int write_private_key(mbedtls_pk_context *key, unsigned char **ret_buf,
924 const char *key_file_path)
926 size_t len = 0; /* Length of created key */
927 FILE *f = NULL; /* File to save certificate */
929 char err_buf[ERROR_BUF_SIZE];
931 /* Initializing buffer for key file content */
932 *ret_buf = zalloc_or_die(PRIVATE_KEY_BUF_SIZE + 1);
935 * Writing private key into PEM string
937 if ((ret = mbedtls_pk_write_key_pem(key, *ret_buf, PRIVATE_KEY_BUF_SIZE)) != 0)
939 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
940 log_error(LOG_LEVEL_ERROR,
941 "Writing private key into PEM string failed: %s", err_buf);
945 len = strlen((char *)*ret_buf);
948 * Saving key into file
950 if ((f = fopen(key_file_path, "wb")) == NULL)
952 log_error(LOG_LEVEL_ERROR,
953 "Opening file %s to save private key failed: %E",
959 if (fwrite(*ret_buf, 1, len, f) != len)
962 log_error(LOG_LEVEL_ERROR,
963 "Writing private key into file %s failed",
982 /*********************************************************************
984 * Function : generate_key
986 * Description : Tests if private key for host saved in csp already
987 * exists. If this file doesn't exists, a new key is
988 * generated and saved in a file. The generated key is also
989 * copied into given parameter key_buf, which must be then
990 * freed by caller. If file with key exists, key_buf
991 * contain NULL and no private key is generated.
994 * 1 : csp = Current client state (buffers, headers, etc...)
995 * 2 : key_buf = buffer to save new generated key
997 * Returns : -1 => Error while generating private key
998 * 0 => Key already exists
999 * >0 => Length of generated private key
1001 *********************************************************************/
1002 static int generate_key(struct client_state *csp, unsigned char **key_buf)
1004 mbedtls_pk_context key;
1005 key_options key_opt;
1007 char err_buf[ERROR_BUF_SIZE];
1009 key_opt.key_file_path = NULL;
1012 * Initializing structures for key generating
1014 mbedtls_pk_init(&key);
1017 * Preparing path for key file and other properties for generating key
1019 key_opt.type = MBEDTLS_PK_RSA;
1020 key_opt.rsa_keysize = RSA_KEYSIZE;
1022 key_opt.key_file_path = make_certs_path(csp->config->certificate_directory,
1023 (char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
1024 if (key_opt.key_file_path == NULL)
1031 * Test if key already exists. If so, we don't have to create it again.
1033 if (file_exists(key_opt.key_file_path) == 1)
1042 ret = seed_rng(csp);
1050 * Setting attributes of private key and generating it
1052 if ((ret = mbedtls_pk_setup(&key,
1053 mbedtls_pk_info_from_type(key_opt.type))) != 0)
1055 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1056 log_error(LOG_LEVEL_ERROR, "mbedtls_pk_setup failed: %s", err_buf);
1061 ret = mbedtls_rsa_gen_key(mbedtls_pk_rsa(key), mbedtls_ctr_drbg_random,
1062 &ctr_drbg, (unsigned)key_opt.rsa_keysize, RSA_KEY_PUBLIC_EXPONENT);
1065 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1066 log_error(LOG_LEVEL_ERROR, "Key generating failed: %s", err_buf);
1072 * Exporting private key into file
1074 if ((ret = write_private_key(&key, key_buf, key_opt.key_file_path)) < 0)
1076 log_error(LOG_LEVEL_ERROR,
1077 "Writing private key into file %s failed", key_opt.key_file_path);
1084 * Freeing used variables
1086 freez(key_opt.key_file_path);
1088 mbedtls_pk_free(&key);
1094 /*********************************************************************
1096 * Function : ssl_certificate_is_invalid
1098 * Description : Checks whether or not a certificate is valid.
1099 * Currently only checks that the certificate can be
1100 * parsed and that the "valid to" date is in the future.
1103 * 1 : cert_file = The certificate to check
1105 * Returns : 0 => The certificate is valid.
1106 * 1 => The certificate is invalid
1108 *********************************************************************/
1109 static int ssl_certificate_is_invalid(const char *cert_file)
1111 mbedtls_x509_crt cert;
1114 mbedtls_x509_crt_init(&cert);
1116 ret = mbedtls_x509_crt_parse_file(&cert, cert_file);
1119 char err_buf[ERROR_BUF_SIZE];
1121 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1122 log_error(LOG_LEVEL_ERROR,
1123 "Loading certificate %s to check validity failed: %s",
1124 cert_file, err_buf);
1125 mbedtls_x509_crt_free(&cert);
1129 if (mbedtls_x509_time_is_past(&cert.valid_to))
1131 mbedtls_x509_crt_free(&cert);
1136 mbedtls_x509_crt_free(&cert);
1143 /*********************************************************************
1145 * Function : set_subject_alternative_name
1147 * Description : Sets the Subject Alternative Name extension to a cert
1150 * 1 : cert = The certificate to modify
1151 * 2 : hostname = The hostname to add
1153 * Returns : <0 => Error while creating certificate.
1156 *********************************************************************/
1157 static int set_subject_alternative_name(mbedtls_x509write_cert *cert, const char *hostname)
1159 char err_buf[ERROR_BUF_SIZE];
1161 char *subject_alternative_name;
1162 size_t subject_alternative_name_len;
1163 #define MBEDTLS_SUBJECT_ALTERNATIVE_NAME_MAX_LEN 255
1164 unsigned char san_buf[MBEDTLS_SUBJECT_ALTERNATIVE_NAME_MAX_LEN + 1];
1168 subject_alternative_name_len = strlen(hostname) + 1;
1169 subject_alternative_name = zalloc_or_die(subject_alternative_name_len);
1171 strlcpy(subject_alternative_name, hostname, subject_alternative_name_len);
1173 memset(san_buf, 0, sizeof(san_buf));
1175 c = san_buf + sizeof(san_buf);
1178 ret = mbedtls_asn1_write_raw_buffer(&c, san_buf,
1179 (const unsigned char *)subject_alternative_name,
1180 strlen(subject_alternative_name));
1183 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1184 log_error(LOG_LEVEL_ERROR,
1185 "mbedtls_asn1_write_raw_buffer() failed: %s", err_buf);
1190 ret = mbedtls_asn1_write_len(&c, san_buf, strlen(subject_alternative_name));
1193 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1194 log_error(LOG_LEVEL_ERROR,
1195 "mbedtls_asn1_write_len() failed: %s", err_buf);
1200 ret = mbedtls_asn1_write_tag(&c, san_buf, MBEDTLS_ASN1_CONTEXT_SPECIFIC | 2);
1203 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1204 log_error(LOG_LEVEL_ERROR,
1205 "mbedtls_asn1_write_tag() failed: %s", err_buf);
1210 ret = mbedtls_asn1_write_len(&c, san_buf, (size_t)len);
1213 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1214 log_error(LOG_LEVEL_ERROR,
1215 "mbedtls_asn1_write_len() failed: %s", err_buf);
1220 ret = mbedtls_asn1_write_tag(&c, san_buf,
1221 MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE);
1224 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1225 log_error(LOG_LEVEL_ERROR,
1226 "mbedtls_asn1_write_tag() failed: %s", err_buf);
1231 ret = mbedtls_x509write_crt_set_extension(cert,
1232 MBEDTLS_OID_SUBJECT_ALT_NAME,
1233 MBEDTLS_OID_SIZE(MBEDTLS_OID_SUBJECT_ALT_NAME),
1234 0, san_buf + sizeof(san_buf) - len, (size_t)len);
1237 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1238 log_error(LOG_LEVEL_ERROR,
1239 "mbedtls_x509write_crt_set_extension() failed: %s", err_buf);
1243 freez(subject_alternative_name);
1250 /*********************************************************************
1252 * Function : generate_webpage_certificate
1254 * Description : Creates certificate file in presetted directory.
1255 * If certificate already exists, no other certificate
1256 * will be created. Subject of certificate is named
1257 * by csp->http->host from parameter. This function also
1258 * triggers generating of private key for new certificate.
1261 * 1 : csp = Current client state (buffers, headers, etc...)
1263 * Returns : -1 => Error while creating certificate.
1264 * 0 => Certificate already exists.
1265 * >0 => Length of created certificate.
1267 *********************************************************************/
1268 static int generate_webpage_certificate(struct client_state *csp)
1270 mbedtls_x509_crt issuer_cert;
1271 mbedtls_pk_context loaded_issuer_key, loaded_subject_key;
1272 mbedtls_pk_context *issuer_key = &loaded_issuer_key;
1273 mbedtls_pk_context *subject_key = &loaded_subject_key;
1274 mbedtls_x509write_cert cert;
1277 unsigned char *key_buf = NULL; /* Buffer for created key */
1280 char err_buf[ERROR_BUF_SIZE];
1281 cert_options cert_opt;
1282 char cert_valid_from[VALID_DATETIME_BUFLEN];
1283 char cert_valid_to[VALID_DATETIME_BUFLEN];
1285 /* Paths to keys and certificates needed to create certificate */
1286 cert_opt.issuer_key = NULL;
1287 cert_opt.subject_key = NULL;
1288 cert_opt.issuer_crt = NULL;
1290 cert_opt.output_file = make_certs_path(csp->config->certificate_directory,
1291 (const char *)csp->http->hash_of_host_hex, CERT_FILE_TYPE);
1292 if (cert_opt.output_file == NULL)
1297 cert_opt.subject_key = make_certs_path(csp->config->certificate_directory,
1298 (const char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
1299 if (cert_opt.subject_key == NULL)
1301 freez(cert_opt.output_file);
1305 if (file_exists(cert_opt.output_file) == 1)
1307 /* The file exists, but is it valid? */
1308 if (ssl_certificate_is_invalid(cert_opt.output_file))
1310 log_error(LOG_LEVEL_CONNECT,
1311 "Certificate %s is no longer valid. Removing it.",
1312 cert_opt.output_file);
1313 if (unlink(cert_opt.output_file))
1315 log_error(LOG_LEVEL_ERROR, "Failed to unlink %s: %E",
1316 cert_opt.output_file);
1318 freez(cert_opt.output_file);
1319 freez(cert_opt.subject_key);
1323 if (unlink(cert_opt.subject_key))
1325 log_error(LOG_LEVEL_ERROR, "Failed to unlink %s: %E",
1326 cert_opt.subject_key);
1328 freez(cert_opt.output_file);
1329 freez(cert_opt.subject_key);
1336 freez(cert_opt.output_file);
1337 freez(cert_opt.subject_key);
1344 * Create key for requested host
1346 int subject_key_len = generate_key(csp, &key_buf);
1347 if (subject_key_len < 0)
1349 freez(cert_opt.output_file);
1350 freez(cert_opt.subject_key);
1351 log_error(LOG_LEVEL_ERROR, "Key generating failed");
1356 * Initializing structures for certificate generating
1358 mbedtls_x509write_crt_init(&cert);
1359 mbedtls_x509write_crt_set_md_alg(&cert, CERT_SIGNATURE_ALGORITHM);
1360 mbedtls_pk_init(&loaded_issuer_key);
1361 mbedtls_pk_init(&loaded_subject_key);
1362 mbedtls_mpi_init(&serial);
1363 mbedtls_x509_crt_init(&issuer_cert);
1366 * Presetting parameters for certificate. We must compute total length
1369 size_t cert_params_len = strlen(CERT_PARAM_COMMON_NAME) +
1370 strlen(CERT_PARAM_ORGANIZATION) + strlen(CERT_PARAM_COUNTRY) +
1371 strlen(CERT_PARAM_ORG_UNIT) +
1372 3 * strlen(csp->http->host) + 1;
1373 char cert_params[cert_params_len];
1374 memset(cert_params, 0, cert_params_len);
1377 * Converting unsigned long serial number to char * serial number.
1378 * We must compute length of serial number in string + terminating null.
1380 unsigned long certificate_serial = get_certificate_serial(csp);
1381 unsigned long certificate_serial_time = (unsigned long)time(NULL);
1382 int serial_num_size = snprintf(NULL, 0, "%lu%lu",
1383 certificate_serial_time, certificate_serial) + 1;
1384 if (serial_num_size <= 0)
1386 serial_num_size = 1;
1389 char serial_num_text[serial_num_size]; /* Buffer for serial number */
1390 ret = snprintf(serial_num_text, (size_t)serial_num_size, "%lu%lu",
1391 certificate_serial_time, certificate_serial);
1392 if (ret < 0 || ret >= serial_num_size)
1394 log_error(LOG_LEVEL_ERROR,
1395 "Converting certificate serial number into string failed");
1401 * Preparing parameters for certificate
1403 strlcpy(cert_params, CERT_PARAM_COMMON_NAME, cert_params_len);
1404 strlcat(cert_params, csp->http->host, cert_params_len);
1405 strlcat(cert_params, CERT_PARAM_ORGANIZATION, cert_params_len);
1406 strlcat(cert_params, csp->http->host, cert_params_len);
1407 strlcat(cert_params, CERT_PARAM_ORG_UNIT, cert_params_len);
1408 strlcat(cert_params, csp->http->host, cert_params_len);
1409 strlcat(cert_params, CERT_PARAM_COUNTRY, cert_params_len);
1411 cert_opt.issuer_crt = csp->config->ca_cert_file;
1412 cert_opt.issuer_key = csp->config->ca_key_file;
1414 if (get_certificate_valid_from_date(cert_valid_from, sizeof(cert_valid_from), VALID_DATETIME_FMT)
1415 || get_certificate_valid_to_date(cert_valid_to, sizeof(cert_valid_to), VALID_DATETIME_FMT))
1417 log_error(LOG_LEVEL_ERROR, "Generating one of the validity dates failed");
1422 cert_opt.subject_pwd = CERT_SUBJECT_PASSWORD;
1423 cert_opt.issuer_pwd = csp->config->ca_password;
1424 cert_opt.subject_name = cert_params;
1425 cert_opt.not_before = cert_valid_from;
1426 cert_opt.not_after = cert_valid_to;
1427 cert_opt.serial = serial_num_text;
1429 cert_opt.max_pathlen = -1;
1432 * Test if the private key was already created.
1433 * XXX: Can this still happen?
1435 if (subject_key_len == 0)
1437 log_error(LOG_LEVEL_ERROR, "Subject key was already created");
1445 ret = seed_rng(csp);
1453 * Parse serial to MPI
1455 ret = mbedtls_mpi_read_string(&serial, 10, cert_opt.serial);
1458 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1459 log_error(LOG_LEVEL_ERROR,
1460 "mbedtls_mpi_read_string failed: %s", err_buf);
1466 * Loading certificates
1468 ret = mbedtls_x509_crt_parse_file(&issuer_cert, cert_opt.issuer_crt);
1471 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1472 log_error(LOG_LEVEL_ERROR, "Loading issuer certificate %s failed: %s",
1473 cert_opt.issuer_crt, err_buf);
1478 ret = mbedtls_x509_dn_gets(cert_opt.issuer_name,
1479 sizeof(cert_opt.issuer_name), &issuer_cert.subject);
1482 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1483 log_error(LOG_LEVEL_ERROR, "mbedtls_x509_dn_gets failed: %s", err_buf);
1489 * Loading keys from file or from buffer
1491 if (key_buf != NULL && subject_key_len > 0)
1493 /* Key was created in this function and is stored in buffer */
1494 ret = mbedtls_pk_parse_key(&loaded_subject_key, key_buf,
1495 (size_t)(subject_key_len + 1), (unsigned const char *)
1496 cert_opt.subject_pwd, strlen(cert_opt.subject_pwd));
1500 /* Key wasn't created in this function, because it already existed */
1501 ret = mbedtls_pk_parse_keyfile(&loaded_subject_key,
1502 cert_opt.subject_key, cert_opt.subject_pwd);
1507 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1508 log_error(LOG_LEVEL_ERROR, "Parsing subject key %s failed: %s",
1509 cert_opt.subject_key, err_buf);
1514 ret = mbedtls_pk_parse_keyfile(&loaded_issuer_key, cert_opt.issuer_key,
1515 cert_opt.issuer_pwd);
1518 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1519 log_error(LOG_LEVEL_ERROR,
1520 "Parsing issuer key %s failed: %s", cert_opt.issuer_key, err_buf);
1526 * Check if key and issuer certificate match
1528 if (!mbedtls_pk_can_do(&issuer_cert.pk, MBEDTLS_PK_RSA) ||
1529 mbedtls_mpi_cmp_mpi(&mbedtls_pk_rsa(issuer_cert.pk)->N,
1530 &mbedtls_pk_rsa(*issuer_key)->N) != 0 ||
1531 mbedtls_mpi_cmp_mpi(&mbedtls_pk_rsa(issuer_cert.pk)->E,
1532 &mbedtls_pk_rsa(*issuer_key)->E) != 0)
1534 log_error(LOG_LEVEL_ERROR,
1535 "Issuer key doesn't match issuer certificate");
1540 mbedtls_x509write_crt_set_subject_key(&cert, subject_key);
1541 mbedtls_x509write_crt_set_issuer_key(&cert, issuer_key);
1544 * Setting parameters of signed certificate
1546 ret = mbedtls_x509write_crt_set_subject_name(&cert, cert_opt.subject_name);
1549 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1550 log_error(LOG_LEVEL_ERROR,
1551 "Setting subject name in signed certificate failed: %s", err_buf);
1556 ret = mbedtls_x509write_crt_set_issuer_name(&cert, cert_opt.issuer_name);
1559 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1560 log_error(LOG_LEVEL_ERROR,
1561 "Setting issuer name in signed certificate failed: %s", err_buf);
1566 ret = mbedtls_x509write_crt_set_serial(&cert, &serial);
1569 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1570 log_error(LOG_LEVEL_ERROR,
1571 "Setting serial number in signed certificate failed: %s", err_buf);
1576 ret = mbedtls_x509write_crt_set_validity(&cert, cert_opt.not_before,
1577 cert_opt.not_after);
1580 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1581 log_error(LOG_LEVEL_ERROR,
1582 "Setting validity in signed certificate failed: %s", err_buf);
1588 * Setting the basicConstraints extension for certificate
1590 ret = mbedtls_x509write_crt_set_basic_constraints(&cert, cert_opt.is_ca,
1591 cert_opt.max_pathlen);
1594 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1595 log_error(LOG_LEVEL_ERROR, "Setting the basicConstraints extension "
1596 "in signed certificate failed: %s", err_buf);
1601 #if defined(MBEDTLS_SHA1_C)
1602 /* Setting the subjectKeyIdentifier extension for certificate */
1603 ret = mbedtls_x509write_crt_set_subject_key_identifier(&cert);
1606 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1607 log_error(LOG_LEVEL_ERROR, "mbedtls_x509write_crt_set_subject_key_"
1608 "identifier failed: %s", err_buf);
1613 /* Setting the authorityKeyIdentifier extension for certificate */
1614 ret = mbedtls_x509write_crt_set_authority_key_identifier(&cert);
1617 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1618 log_error(LOG_LEVEL_ERROR, "mbedtls_x509write_crt_set_authority_key_"
1619 "identifier failed: %s", err_buf);
1623 #endif /* MBEDTLS_SHA1_C */
1625 if (!host_is_ip_address(csp->http->host) &&
1626 set_subject_alternative_name(&cert, csp->http->host))
1628 /* Errors are already logged by set_subject_alternative_name() */
1634 * Writing certificate into file
1636 ret = write_certificate(&cert, cert_opt.output_file,
1637 mbedtls_ctr_drbg_random, &ctr_drbg);
1640 log_error(LOG_LEVEL_ERROR, "Writing certificate into file failed");
1646 * Freeing used structures
1648 mbedtls_x509write_crt_free(&cert);
1649 mbedtls_pk_free(&loaded_subject_key);
1650 mbedtls_pk_free(&loaded_issuer_key);
1651 mbedtls_mpi_free(&serial);
1652 mbedtls_x509_crt_free(&issuer_cert);
1654 freez(cert_opt.subject_key);
1655 freez(cert_opt.output_file);
1661 /*********************************************************************
1663 * Function : ssl_verify_callback
1665 * Description : This is a callback function for certificate verification.
1666 * It's called once for each certificate in the server's
1667 * certificate trusted chain and prepares information about
1668 * the certificate. The information can be used to inform
1669 * the user about invalid certificates.
1672 * 1 : csp_void = Current client state (buffers, headers, etc...)
1673 * 2 : crt = certificate from trusted chain
1674 * 3 : depth = depth in trusted chain
1675 * 4 : flags = certificate flags
1677 * Returns : 0 on success and negative value on error
1679 *********************************************************************/
1680 static int ssl_verify_callback(void *csp_void, mbedtls_x509_crt *crt,
1681 int depth, uint32_t *flags)
1683 struct client_state *csp = (struct client_state *)csp_void;
1684 struct certs_chain *last = &(csp->server_certs_chain);
1689 * Searching for last item in certificates linked list
1691 while (last->next != NULL)
1697 * Preparing next item in linked list for next certificate
1699 last->next = malloc_or_die(sizeof(struct certs_chain));
1700 last->next->next = NULL;
1701 memset(last->next->info_buf, 0, sizeof(last->next->info_buf));
1702 memset(last->next->file_buf, 0, sizeof(last->next->file_buf));
1705 * Saving certificate file into buffer
1707 if ((ret = mbedtls_pem_write_buffer(PEM_BEGIN_CRT, PEM_END_CRT,
1708 crt->raw.p, crt->raw.len, (unsigned char *)last->file_buf,
1709 sizeof(last->file_buf)-1, &olen)) != 0)
1711 char err_buf[ERROR_BUF_SIZE];
1713 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1714 log_error(LOG_LEVEL_ERROR, "mbedtls_pem_write_buffer() failed: %s",
1721 * Saving certificate information into buffer
1724 char buf[CERT_INFO_BUF_SIZE];
1727 mbedtls_x509_crt_info(buf, sizeof(buf), CERT_INFO_PREFIX, crt);
1728 encoded_text = html_encode(buf);
1729 if (encoded_text == NULL)
1731 log_error(LOG_LEVEL_ERROR,
1732 "Failed to HTML-encode the certificate information");
1735 strlcpy(last->info_buf, encoded_text, sizeof(last->info_buf));
1736 freez(encoded_text);
1743 /*********************************************************************
1745 * Function : host_to_hash
1747 * Description : Creates MD5 hash from host name. Host name is loaded
1748 * from structure csp and saved again into it.
1751 * 1 : csp = Current client state (buffers, headers, etc...)
1753 * Returns : 1 => Error while creating hash
1754 * 0 => Hash created successfully
1756 *********************************************************************/
1757 static int host_to_hash(struct client_state *csp)
1761 #if !defined(MBEDTLS_MD5_C)
1762 #error mbedTLS needs to be compiled with md5 support
1764 memset(csp->http->hash_of_host, 0, sizeof(csp->http->hash_of_host));
1765 mbedtls_md5((unsigned char *)csp->http->host, strlen(csp->http->host),
1766 csp->http->hash_of_host);
1768 /* Converting hash into string with hex */
1772 if ((ret = sprintf((char *)csp->http->hash_of_host_hex + 2 * i, "%02x",
1773 csp->http->hash_of_host[i])) < 0)
1775 log_error(LOG_LEVEL_ERROR, "Sprintf return value: %d", ret);
1781 #endif /* MBEDTLS_MD5_C */
1784 /*********************************************************************
1786 * Function : seed_rng
1788 * Description : Seeding the RNG for all SSL uses
1791 * 1 : csp = Current client state (buffers, headers, etc...)
1793 * Returns : -1 => RNG wasn't seed successfully
1794 * 0 => RNG is seeded successfully
1796 *********************************************************************/
1797 static int seed_rng(struct client_state *csp)
1800 char err_buf[ERROR_BUF_SIZE];
1802 if (rng_seeded == 0)
1804 privoxy_mutex_lock(&ssl_init_mutex);
1805 if (rng_seeded == 0)
1807 mbedtls_ctr_drbg_init(&ctr_drbg);
1808 mbedtls_entropy_init(&entropy);
1809 ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func,
1813 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1814 log_error(LOG_LEVEL_ERROR,
1815 "mbedtls_ctr_drbg_seed failed: %s", err_buf);
1816 privoxy_mutex_unlock(&ssl_init_mutex);
1821 privoxy_mutex_unlock(&ssl_init_mutex);
1827 /*********************************************************************
1829 * Function : ssl_base64_encode
1831 * Description : Encode a buffer into base64 format.
1834 * 1 : dst = Destination buffer
1835 * 2 : dlen = Destination buffer length
1836 * 3 : olen = Number of bytes written
1837 * 4 : src = Source buffer
1838 * 5 : slen = Amount of data to be encoded
1840 * Returns : 0 on success, error code othervise
1842 *********************************************************************/
1843 extern int ssl_base64_encode(unsigned char *dst, size_t dlen, size_t *olen,
1844 const unsigned char *src, size_t slen)
1846 return mbedtls_base64_encode(dst, dlen, olen, src, slen);
1850 /*********************************************************************
1852 * Function : ssl_crt_verify_info
1854 * Description : Returns an informational string about the verification
1855 * status of a certificate.
1858 * 1 : buf = Buffer to write to
1859 * 2 : size = Maximum size of buffer
1860 * 3 : csp = client state
1864 *********************************************************************/
1865 extern void ssl_crt_verify_info(char *buf, size_t size, struct client_state *csp)
1867 mbedtls_x509_crt_verify_info(buf, size, " ", csp->server_cert_verification_result);
1871 /*********************************************************************
1873 * Function : ssl_release
1875 * Description : Release all SSL resources
1881 *********************************************************************/
1882 extern void ssl_release(void)
1884 if (rng_seeded == 1)
1886 mbedtls_ctr_drbg_free(&ctr_drbg);
1887 mbedtls_entropy_free(&entropy);