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-2020 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_host_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);
97 static int *get_ciphersuites_from_string(const char *ciphersuites_string);
99 /*********************************************************************
101 * Function : is_ssl_pending
103 * Description : Tests if there are some waiting data on ssl connection.
104 * Only considers data that has actually been received
105 * locally and ignores data that is still on the fly
106 * or has not yet been sent by the remote end.
109 * 1 : ssl_attr = SSL context to test
111 * Returns : 0 => No data are pending
112 * >0 => Pending data length
114 *********************************************************************/
115 extern size_t is_ssl_pending(struct ssl_attr *ssl_attr)
117 mbedtls_ssl_context *ssl = &ssl_attr->mbedtls_attr.ssl;
123 return mbedtls_ssl_get_bytes_avail(ssl);
127 /*********************************************************************
129 * Function : ssl_send_data
131 * Description : Sends the content of buf (for n bytes) to given SSL
132 * connection context.
135 * 1 : ssl_attr = SSL context to send data to
136 * 2 : buf = Pointer to data to be sent
137 * 3 : len = Length of data to be sent to the SSL context
139 * Returns : Length of sent data or negative value on error.
141 *********************************************************************/
142 extern int ssl_send_data(struct ssl_attr *ssl_attr, const unsigned char *buf, size_t len)
144 mbedtls_ssl_context *ssl = &ssl_attr->mbedtls_attr.ssl;
146 size_t max_fragment_size = 0; /* Maximal length of data in one SSL fragment*/
147 int send_len = 0; /* length of one data part to send */
148 int pos = 0; /* Position of unsent part in buffer */
155 /* Getting maximal length of data sent in one fragment */
156 max_fragment_size = mbedtls_ssl_get_max_frag_len(ssl);
159 * Whole buffer must be sent in many fragments, because each fragment
160 * has its maximal length.
164 /* Compute length of data, that can be send in next fragment */
165 if ((pos + (int)max_fragment_size) > len)
167 send_len = (int)len - pos;
171 send_len = (int)max_fragment_size;
174 log_error(LOG_LEVEL_WRITING, "TLS on socket %d: %N",
175 ssl_attr->mbedtls_attr.socket_fd.fd, send_len, buf+pos);
178 * Sending one part of the buffer
180 while ((ret = mbedtls_ssl_write(ssl,
181 (const unsigned char *)(buf + pos),
182 (size_t)send_len)) < 0)
184 if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
185 ret != MBEDTLS_ERR_SSL_WANT_WRITE)
187 char err_buf[ERROR_BUF_SIZE];
189 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
190 log_error(LOG_LEVEL_ERROR,
191 "Sending data on socket %d over TLS/SSL failed: %s",
192 ssl_attr->mbedtls_attr.socket_fd.fd, err_buf);
196 /* Adding count of sent bytes to position in buffer */
197 pos = pos + send_len;
204 /*********************************************************************
206 * Function : ssl_recv_data
208 * Description : Receives data from given SSL context and puts
212 * 1 : ssl_attr = SSL context to receive data from
213 * 2 : buf = Pointer to buffer where data will be written
214 * 3 : max_length = Maximum number of bytes to read
216 * Returns : Number of bytes read, 0 for EOF, or -1
219 *********************************************************************/
220 extern int ssl_recv_data(struct ssl_attr *ssl_attr, unsigned char *buf, size_t max_length)
222 mbedtls_ssl_context *ssl = &ssl_attr->mbedtls_attr.ssl;
224 memset(buf, 0, max_length);
227 * Receiving data from SSL context into buffer
231 ret = mbedtls_ssl_read(ssl, buf, max_length);
232 } while (ret == MBEDTLS_ERR_SSL_WANT_READ
233 || ret == MBEDTLS_ERR_SSL_WANT_WRITE);
237 char err_buf[ERROR_BUF_SIZE];
239 if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY)
241 log_error(LOG_LEVEL_CONNECT, "The peer notified us that "
242 "the connection on socket %d is going to be closed",
243 ssl_attr->mbedtls_attr.socket_fd.fd);
246 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
247 log_error(LOG_LEVEL_ERROR,
248 "Receiving data on socket %d over TLS/SSL failed: %s",
249 ssl_attr->mbedtls_attr.socket_fd.fd, err_buf);
254 log_error(LOG_LEVEL_RECEIVED, "TLS from socket %d: %N",
255 ssl_attr->mbedtls_attr.socket_fd.fd, ret, buf);
261 /*********************************************************************
263 * Function : create_client_ssl_connection
265 * Description : Creates TLS/SSL secured connection with client
268 * 1 : csp = Current client state (buffers, headers, etc...)
270 * Returns : 0 on success, negative value if connection wasn't created
273 *********************************************************************/
274 extern int create_client_ssl_connection(struct client_state *csp)
276 struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
277 /* Paths to certificates file and key file */
278 char *key_file = NULL;
279 char *ca_file = NULL;
280 char *cert_file = NULL;
282 char err_buf[ERROR_BUF_SIZE];
285 * Initializing mbedtls structures for TLS/SSL connection
287 mbedtls_net_init(&(ssl_attr->mbedtls_attr.socket_fd));
288 mbedtls_ssl_init(&(ssl_attr->mbedtls_attr.ssl));
289 mbedtls_ssl_config_init(&(ssl_attr->mbedtls_attr.conf));
290 mbedtls_x509_crt_init(&(ssl_attr->mbedtls_attr.server_cert));
291 mbedtls_pk_init(&(ssl_attr->mbedtls_attr.prim_key));
292 #if defined(MBEDTLS_SSL_CACHE_C)
293 mbedtls_ssl_cache_init(&(ssl_attr->mbedtls_attr.cache));
297 * Preparing hash of host for creating certificates
299 ret = host_to_hash(csp);
302 log_error(LOG_LEVEL_ERROR, "Generating hash of host failed: %d", ret);
308 * Preparing paths to certificates files and key file
310 ca_file = csp->config->ca_cert_file;
311 cert_file = make_certs_path(csp->config->certificate_directory,
312 (const char *)csp->http->hash_of_host_hex, CERT_FILE_TYPE);
313 key_file = make_certs_path(csp->config->certificate_directory,
314 (const char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
316 if (cert_file == NULL || key_file == NULL)
323 * Generating certificate for requested host. Mutex to prevent
324 * certificate and key inconsistence must be locked.
326 privoxy_mutex_lock(&certificate_mutex);
328 ret = generate_host_certificate(csp);
331 log_error(LOG_LEVEL_ERROR,
332 "generate_host_certificate failed: %d", ret);
333 privoxy_mutex_unlock(&certificate_mutex);
337 privoxy_mutex_unlock(&certificate_mutex);
350 * Loading CA file, webpage certificate and key files
352 ret = mbedtls_x509_crt_parse_file(&(ssl_attr->mbedtls_attr.server_cert),
356 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
357 log_error(LOG_LEVEL_ERROR,
358 "Loading webpage certificate %s failed: %s", cert_file, err_buf);
363 ret = mbedtls_x509_crt_parse_file(&(ssl_attr->mbedtls_attr.server_cert),
367 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
368 log_error(LOG_LEVEL_ERROR,
369 "Loading CA certificate %s failed: %s", ca_file, err_buf);
374 ret = mbedtls_pk_parse_keyfile(&(ssl_attr->mbedtls_attr.prim_key),
378 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
379 log_error(LOG_LEVEL_ERROR,
380 "Loading and parsing webpage certificate private key %s failed: %s",
387 * Setting SSL parameters
389 ret = mbedtls_ssl_config_defaults(&(ssl_attr->mbedtls_attr.conf),
390 MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_TRANSPORT_STREAM,
391 MBEDTLS_SSL_PRESET_DEFAULT);
394 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
395 log_error(LOG_LEVEL_ERROR,
396 "mbedtls_ssl_config_defaults failed: %s", err_buf);
401 mbedtls_ssl_conf_rng(&(ssl_attr->mbedtls_attr.conf),
402 mbedtls_ctr_drbg_random, &ctr_drbg);
404 #if defined(MBEDTLS_SSL_CACHE_C)
405 mbedtls_ssl_conf_session_cache(&(ssl_attr->mbedtls_attr.conf),
406 &(ssl_attr->mbedtls_attr.cache), mbedtls_ssl_cache_get,
407 mbedtls_ssl_cache_set);
411 * Setting certificates
413 ret = mbedtls_ssl_conf_own_cert(&(ssl_attr->mbedtls_attr.conf),
414 &(ssl_attr->mbedtls_attr.server_cert),
415 &(ssl_attr->mbedtls_attr.prim_key));
418 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
419 log_error(LOG_LEVEL_ERROR,
420 "mbedtls_ssl_conf_own_cert failed: %s", err_buf);
425 if (csp->config->cipher_list != NULL)
427 ssl_attr->mbedtls_attr.ciphersuites_list =
428 get_ciphersuites_from_string(csp->config->cipher_list);
429 if (ssl_attr->mbedtls_attr.ciphersuites_list == NULL)
431 log_error(LOG_LEVEL_ERROR,
432 "Setting the cipher list '%s' for the client connection failed",
433 csp->config->cipher_list);
437 mbedtls_ssl_conf_ciphersuites(&(ssl_attr->mbedtls_attr.conf),
438 ssl_attr->mbedtls_attr.ciphersuites_list);
441 ret = mbedtls_ssl_setup(&(ssl_attr->mbedtls_attr.ssl),
442 &(ssl_attr->mbedtls_attr.conf));
445 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
446 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_setup failed: %s", err_buf);
451 mbedtls_ssl_set_bio(&(ssl_attr->mbedtls_attr.ssl),
452 &(ssl_attr->mbedtls_attr.socket_fd), mbedtls_net_send,
453 mbedtls_net_recv, NULL);
454 mbedtls_ssl_session_reset(&(ssl_attr->mbedtls_attr.ssl));
457 * Setting socket fd in mbedtls_net_context structure. This structure
458 * can't be set by mbedtls functions, because we already have created
459 * a TCP connection when this function is called.
461 ssl_attr->mbedtls_attr.socket_fd.fd = csp->cfd;
464 * Handshake with client
466 log_error(LOG_LEVEL_CONNECT,
467 "Performing the TLS/SSL handshake with client. Hash of host: %s",
468 csp->http->hash_of_host_hex);
469 while ((ret = mbedtls_ssl_handshake(&(ssl_attr->mbedtls_attr.ssl))) != 0)
471 if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
472 ret != MBEDTLS_ERR_SSL_WANT_WRITE)
474 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
475 log_error(LOG_LEVEL_ERROR,
476 "medtls_ssl_handshake with client failed: %s", err_buf);
482 log_error(LOG_LEVEL_CONNECT, "Client successfully connected over TLS/SSL");
483 csp->ssl_with_client_is_opened = 1;
487 * Freeing allocated paths to files
492 /* Freeing structures if connection wasn't created successfully */
495 free_client_ssl_structures(csp);
501 /*********************************************************************
503 * Function : close_client_ssl_connection
505 * Description : Closes TLS/SSL connection with client. This function
506 * checks if this connection is already created.
509 * 1 : csp = Current client state (buffers, headers, etc...)
513 *********************************************************************/
514 extern void close_client_ssl_connection(struct client_state *csp)
516 struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
519 if (csp->ssl_with_client_is_opened == 0)
525 * Notifying the peer that the connection is being closed.
528 ret = mbedtls_ssl_close_notify(&(ssl_attr->mbedtls_attr.ssl));
529 } while (ret == MBEDTLS_ERR_SSL_WANT_WRITE);
531 free_client_ssl_structures(csp);
532 csp->ssl_with_client_is_opened = 0;
536 /*********************************************************************
538 * Function : free_client_ssl_structures
540 * Description : Frees structures used for SSL communication with
544 * 1 : csp = Current client state (buffers, headers, etc...)
548 *********************************************************************/
549 static void free_client_ssl_structures(struct client_state *csp)
551 struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
553 * We can't use function mbedtls_net_free, because this function
554 * inter alia close TCP connection on set fd. Instead of this
555 * function, we change fd to -1, which is the same what does
556 * rest of mbedtls_net_free function.
558 ssl_attr->mbedtls_attr.socket_fd.fd = -1;
560 /* Freeing mbedtls structures */
561 mbedtls_x509_crt_free(&(ssl_attr->mbedtls_attr.server_cert));
562 mbedtls_pk_free(&(ssl_attr->mbedtls_attr.prim_key));
563 mbedtls_ssl_free(&(ssl_attr->mbedtls_attr.ssl));
564 freez(ssl_attr->mbedtls_attr.ciphersuites_list);
565 mbedtls_ssl_config_free(&(ssl_attr->mbedtls_attr.conf));
566 #if defined(MBEDTLS_SSL_CACHE_C)
567 mbedtls_ssl_cache_free(&(ssl_attr->mbedtls_attr.cache));
572 /*********************************************************************
574 * Function : create_server_ssl_connection
576 * Description : Creates TLS/SSL secured connection with server.
579 * 1 : csp = Current client state (buffers, headers, etc...)
581 * Returns : 0 on success, negative value if connection wasn't created
584 *********************************************************************/
585 extern int create_server_ssl_connection(struct client_state *csp)
587 struct ssl_attr *ssl_attr = &csp->ssl_server_attr;
589 char err_buf[ERROR_BUF_SIZE];
590 char *trusted_cas_file = NULL;
591 int auth_mode = MBEDTLS_SSL_VERIFY_REQUIRED;
593 csp->server_cert_verification_result = SSL_CERT_NOT_VERIFIED;
594 csp->server_certs_chain.next = NULL;
596 /* Setting path to file with trusted CAs */
597 trusted_cas_file = csp->config->trusted_cas_file;
600 * Initializing mbedtls structures for TLS/SSL connection
602 mbedtls_net_init(&(ssl_attr->mbedtls_attr.socket_fd));
603 mbedtls_ssl_init(&(ssl_attr->mbedtls_attr.ssl));
604 mbedtls_ssl_config_init(&(ssl_attr->mbedtls_attr.conf));
605 mbedtls_x509_crt_init(&(ssl_attr->mbedtls_attr.ca_cert));
608 * Setting socket fd in mbedtls_net_context structure. This structure
609 * can't be set by mbedtls functions, because we already have created
610 * TCP connection when calling this function.
612 ssl_attr->mbedtls_attr.socket_fd.fd = csp->server_connection.sfd;
625 * Loading file with trusted CAs
627 ret = mbedtls_x509_crt_parse_file(&(ssl_attr->mbedtls_attr.ca_cert),
631 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
632 log_error(LOG_LEVEL_ERROR, "Loading trusted CAs file %s failed: %s",
633 trusted_cas_file, err_buf);
639 * Set TLS/SSL options
641 ret = mbedtls_ssl_config_defaults(&(ssl_attr->mbedtls_attr.conf),
642 MBEDTLS_SSL_IS_CLIENT,
643 MBEDTLS_SSL_TRANSPORT_STREAM,
644 MBEDTLS_SSL_PRESET_DEFAULT);
647 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
648 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_config_defaults failed: %s",
655 * Setting how strict should certificate verification be and other
656 * parameters for certificate verification
658 if (csp->dont_verify_certificate)
660 auth_mode = MBEDTLS_SSL_VERIFY_NONE;
663 mbedtls_ssl_conf_authmode(&(ssl_attr->mbedtls_attr.conf), auth_mode);
664 mbedtls_ssl_conf_ca_chain(&(ssl_attr->mbedtls_attr.conf),
665 &(ssl_attr->mbedtls_attr.ca_cert), NULL);
667 /* Setting callback function for certificates verification */
668 mbedtls_ssl_conf_verify(&(ssl_attr->mbedtls_attr.conf),
669 ssl_verify_callback, (void *)csp);
671 mbedtls_ssl_conf_rng(&(ssl_attr->mbedtls_attr.conf),
672 mbedtls_ctr_drbg_random, &ctr_drbg);
674 if (csp->config->cipher_list != NULL)
676 ssl_attr->mbedtls_attr.ciphersuites_list =
677 get_ciphersuites_from_string(csp->config->cipher_list);
678 if (ssl_attr->mbedtls_attr.ciphersuites_list == NULL)
680 log_error(LOG_LEVEL_ERROR,
681 "Setting the cipher list '%s' for the server connection failed",
682 csp->config->cipher_list);
686 mbedtls_ssl_conf_ciphersuites(&(ssl_attr->mbedtls_attr.conf),
687 ssl_attr->mbedtls_attr.ciphersuites_list);
690 ret = mbedtls_ssl_setup(&(ssl_attr->mbedtls_attr.ssl),
691 &(ssl_attr->mbedtls_attr.conf));
694 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
695 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_setup failed: %s", err_buf);
701 * Set the hostname to check against the received server certificate
703 ret = mbedtls_ssl_set_hostname(&(ssl_attr->mbedtls_attr.ssl),
707 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
708 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_set_hostname failed: %s",
714 mbedtls_ssl_set_bio(&(ssl_attr->mbedtls_attr.ssl),
715 &(ssl_attr->mbedtls_attr.socket_fd), mbedtls_net_send,
716 mbedtls_net_recv, NULL);
719 * Handshake with server
721 log_error(LOG_LEVEL_CONNECT,
722 "Performing the TLS/SSL handshake with the server");
724 while ((ret = mbedtls_ssl_handshake(&(ssl_attr->mbedtls_attr.ssl))) != 0)
726 if (ret != MBEDTLS_ERR_SSL_WANT_READ
727 && ret != MBEDTLS_ERR_SSL_WANT_WRITE)
729 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
731 if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED)
733 char reason[INVALID_CERT_INFO_BUF_SIZE];
735 csp->server_cert_verification_result =
736 mbedtls_ssl_get_verify_result(&(ssl_attr->mbedtls_attr.ssl));
737 mbedtls_x509_crt_verify_info(reason, sizeof(reason), "",
738 csp->server_cert_verification_result);
740 /* Log the reason without the trailing new line */
741 log_error(LOG_LEVEL_ERROR,
742 "X509 certificate verification for %s failed: %N",
743 csp->http->hostport, strlen(reason)-1, reason);
748 log_error(LOG_LEVEL_ERROR,
749 "mbedtls_ssl_handshake with server failed: %s", err_buf);
750 free_certificate_chain(csp);
757 log_error(LOG_LEVEL_CONNECT, "Server successfully connected over TLS/SSL");
760 * Server certificate chain is valid, so we can clean
761 * chain, because we will not send it to client.
763 free_certificate_chain(csp);
765 csp->ssl_with_server_is_opened = 1;
766 csp->server_cert_verification_result =
767 mbedtls_ssl_get_verify_result(&(ssl_attr->mbedtls_attr.ssl));
770 /* Freeing structures if connection wasn't created successfully */
773 free_server_ssl_structures(csp);
780 /*********************************************************************
782 * Function : close_server_ssl_connection
784 * Description : Closes TLS/SSL connection with server. This function
785 * checks if this connection is already opened.
788 * 1 : csp = Current client state (buffers, headers, etc...)
792 *********************************************************************/
793 extern void close_server_ssl_connection(struct client_state *csp)
795 struct ssl_attr *ssl_attr = &csp->ssl_server_attr;
798 if (csp->ssl_with_server_is_opened == 0)
804 * Notifying the peer that the connection is being closed.
807 ret = mbedtls_ssl_close_notify(&(ssl_attr->mbedtls_attr.ssl));
808 } while (ret == MBEDTLS_ERR_SSL_WANT_WRITE);
810 free_server_ssl_structures(csp);
811 csp->ssl_with_server_is_opened = 0;
815 /*********************************************************************
817 * Function : free_server_ssl_structures
819 * Description : Frees structures used for SSL communication with server
822 * 1 : csp = Current client state (buffers, headers, etc...)
826 *********************************************************************/
827 static void free_server_ssl_structures(struct client_state *csp)
829 struct ssl_attr *ssl_attr = &csp->ssl_server_attr;
831 * We can't use function mbedtls_net_free, because this function
832 * inter alia close TCP connection on set fd. Instead of this
833 * function, we change fd to -1, which is the same what does
834 * rest of mbedtls_net_free function.
836 ssl_attr->mbedtls_attr.socket_fd.fd = -1;
838 mbedtls_x509_crt_free(&(ssl_attr->mbedtls_attr.ca_cert));
839 mbedtls_ssl_free(&(ssl_attr->mbedtls_attr.ssl));
840 freez(ssl_attr->mbedtls_attr.ciphersuites_list);
841 mbedtls_ssl_config_free(&(ssl_attr->mbedtls_attr.conf));
845 /*====================== Certificates ======================*/
847 /*********************************************************************
849 * Function : write_certificate
851 * Description : Writes certificate into file.
854 * 1 : crt = certificate to write into file
855 * 2 : output_file = path to save certificate file
856 * 3 : f_rng = mbedtls_ctr_drbg_random
857 * 4 : p_rng = mbedtls_ctr_drbg_context
859 * Returns : Length of written certificate on success or negative value
862 *********************************************************************/
863 static int write_certificate(mbedtls_x509write_cert *crt, const char *output_file,
864 int(*f_rng)(void *, unsigned char *, size_t), void *p_rng)
868 unsigned char cert_buf[CERTIFICATE_BUF_SIZE + 1]; /* Buffer for certificate in PEM format + terminating NULL */
870 char err_buf[ERROR_BUF_SIZE];
872 memset(cert_buf, 0, sizeof(cert_buf));
875 * Writing certificate into PEM string. If buffer is too small, function
876 * returns specific error and no buffer overflow can happen.
878 if ((ret = mbedtls_x509write_crt_pem(crt, cert_buf,
879 sizeof(cert_buf) - 1, f_rng, p_rng)) != 0)
881 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
882 log_error(LOG_LEVEL_ERROR,
883 "Writing certificate into buffer failed: %s", err_buf);
887 len = strlen((char *)cert_buf);
890 * Saving certificate into file
892 if ((f = fopen(output_file, "w")) == NULL)
894 log_error(LOG_LEVEL_ERROR, "Opening file %s to save certificate failed",
899 if (fwrite(cert_buf, 1, len, f) != len)
901 log_error(LOG_LEVEL_ERROR,
902 "Writing certificate into file %s failed", output_file);
913 /*********************************************************************
915 * Function : write_private_key
917 * Description : Writes private key into file and copies saved
918 * content into given pointer to string. If function
919 * returns 0 for success, this copy must be freed by
923 * 1 : key = key to write into file
924 * 2 : ret_buf = pointer to string with created key file content
925 * 3 : key_file_path = path where to save key file
927 * Returns : Length of written private key on success or negative value
930 *********************************************************************/
931 static int write_private_key(mbedtls_pk_context *key, unsigned char **ret_buf,
932 const char *key_file_path)
934 size_t len = 0; /* Length of created key */
935 FILE *f = NULL; /* File to save certificate */
937 char err_buf[ERROR_BUF_SIZE];
939 /* Initializing buffer for key file content */
940 *ret_buf = zalloc_or_die(PRIVATE_KEY_BUF_SIZE + 1);
943 * Writing private key into PEM string
945 if ((ret = mbedtls_pk_write_key_pem(key, *ret_buf, PRIVATE_KEY_BUF_SIZE)) != 0)
947 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
948 log_error(LOG_LEVEL_ERROR,
949 "Writing private key into PEM string failed: %s", err_buf);
953 len = strlen((char *)*ret_buf);
956 * Saving key into file
958 if ((f = fopen(key_file_path, "wb")) == NULL)
960 log_error(LOG_LEVEL_ERROR,
961 "Opening file %s to save private key failed: %E",
967 if (fwrite(*ret_buf, 1, len, f) != len)
970 log_error(LOG_LEVEL_ERROR,
971 "Writing private key into file %s failed",
990 /*********************************************************************
992 * Function : generate_key
994 * Description : Tests if private key for host saved in csp already
995 * exists. If this file doesn't exists, a new key is
996 * generated and saved in a file. The generated key is also
997 * copied into given parameter key_buf, which must be then
998 * freed by caller. If file with key exists, key_buf
999 * contain NULL and no private key is generated.
1002 * 1 : csp = Current client state (buffers, headers, etc...)
1003 * 2 : key_buf = buffer to save new generated key
1005 * Returns : -1 => Error while generating private key
1006 * 0 => Key already exists
1007 * >0 => Length of generated private key
1009 *********************************************************************/
1010 static int generate_key(struct client_state *csp, unsigned char **key_buf)
1012 mbedtls_pk_context key;
1013 key_options key_opt;
1015 char err_buf[ERROR_BUF_SIZE];
1017 key_opt.key_file_path = NULL;
1020 * Initializing structures for key generating
1022 mbedtls_pk_init(&key);
1025 * Preparing path for key file and other properties for generating key
1027 key_opt.type = MBEDTLS_PK_RSA;
1028 key_opt.rsa_keysize = RSA_KEYSIZE;
1030 key_opt.key_file_path = make_certs_path(csp->config->certificate_directory,
1031 (char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
1032 if (key_opt.key_file_path == NULL)
1039 * Test if key already exists. If so, we don't have to create it again.
1041 if (file_exists(key_opt.key_file_path) == 1)
1050 ret = seed_rng(csp);
1058 * Setting attributes of private key and generating it
1060 if ((ret = mbedtls_pk_setup(&key,
1061 mbedtls_pk_info_from_type(key_opt.type))) != 0)
1063 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1064 log_error(LOG_LEVEL_ERROR, "mbedtls_pk_setup failed: %s", err_buf);
1069 ret = mbedtls_rsa_gen_key(mbedtls_pk_rsa(key), mbedtls_ctr_drbg_random,
1070 &ctr_drbg, (unsigned)key_opt.rsa_keysize, RSA_KEY_PUBLIC_EXPONENT);
1073 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1074 log_error(LOG_LEVEL_ERROR, "Key generating failed: %s", err_buf);
1080 * Exporting private key into file
1082 if ((ret = write_private_key(&key, key_buf, key_opt.key_file_path)) < 0)
1084 log_error(LOG_LEVEL_ERROR,
1085 "Writing private key into file %s failed", key_opt.key_file_path);
1092 * Freeing used variables
1094 freez(key_opt.key_file_path);
1096 mbedtls_pk_free(&key);
1102 /*********************************************************************
1104 * Function : ssl_certificate_is_invalid
1106 * Description : Checks whether or not a certificate is valid.
1107 * Currently only checks that the certificate can be
1108 * parsed and that the "valid to" date is in the future.
1111 * 1 : cert_file = The certificate to check
1113 * Returns : 0 => The certificate is valid.
1114 * 1 => The certificate is invalid
1116 *********************************************************************/
1117 static int ssl_certificate_is_invalid(const char *cert_file)
1119 mbedtls_x509_crt cert;
1122 mbedtls_x509_crt_init(&cert);
1124 ret = mbedtls_x509_crt_parse_file(&cert, cert_file);
1127 char err_buf[ERROR_BUF_SIZE];
1129 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1130 log_error(LOG_LEVEL_ERROR,
1131 "Loading certificate %s to check validity failed: %s",
1132 cert_file, err_buf);
1133 mbedtls_x509_crt_free(&cert);
1137 if (mbedtls_x509_time_is_past(&cert.valid_to))
1139 mbedtls_x509_crt_free(&cert);
1144 mbedtls_x509_crt_free(&cert);
1151 /*********************************************************************
1153 * Function : set_subject_alternative_name
1155 * Description : Sets the Subject Alternative Name extension to a cert
1158 * 1 : cert = The certificate to modify
1159 * 2 : hostname = The hostname to add
1161 * Returns : <0 => Error while creating certificate.
1164 *********************************************************************/
1165 static int set_subject_alternative_name(mbedtls_x509write_cert *cert, const char *hostname)
1167 char err_buf[ERROR_BUF_SIZE];
1169 char *subject_alternative_name;
1170 size_t subject_alternative_name_len;
1171 #define MBEDTLS_SUBJECT_ALTERNATIVE_NAME_MAX_LEN 255
1172 unsigned char san_buf[MBEDTLS_SUBJECT_ALTERNATIVE_NAME_MAX_LEN + 1];
1176 subject_alternative_name_len = strlen(hostname) + 1;
1177 subject_alternative_name = zalloc_or_die(subject_alternative_name_len);
1179 strlcpy(subject_alternative_name, hostname, subject_alternative_name_len);
1181 memset(san_buf, 0, sizeof(san_buf));
1183 c = san_buf + sizeof(san_buf);
1186 ret = mbedtls_asn1_write_raw_buffer(&c, san_buf,
1187 (const unsigned char *)subject_alternative_name,
1188 strlen(subject_alternative_name));
1191 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1192 log_error(LOG_LEVEL_ERROR,
1193 "mbedtls_asn1_write_raw_buffer() failed: %s", err_buf);
1198 ret = mbedtls_asn1_write_len(&c, san_buf, strlen(subject_alternative_name));
1201 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1202 log_error(LOG_LEVEL_ERROR,
1203 "mbedtls_asn1_write_len() failed: %s", err_buf);
1208 ret = mbedtls_asn1_write_tag(&c, san_buf, MBEDTLS_ASN1_CONTEXT_SPECIFIC | 2);
1211 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1212 log_error(LOG_LEVEL_ERROR,
1213 "mbedtls_asn1_write_tag() failed: %s", err_buf);
1218 ret = mbedtls_asn1_write_len(&c, san_buf, (size_t)len);
1221 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1222 log_error(LOG_LEVEL_ERROR,
1223 "mbedtls_asn1_write_len() failed: %s", err_buf);
1228 ret = mbedtls_asn1_write_tag(&c, san_buf,
1229 MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE);
1232 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1233 log_error(LOG_LEVEL_ERROR,
1234 "mbedtls_asn1_write_tag() failed: %s", err_buf);
1239 ret = mbedtls_x509write_crt_set_extension(cert,
1240 MBEDTLS_OID_SUBJECT_ALT_NAME,
1241 MBEDTLS_OID_SIZE(MBEDTLS_OID_SUBJECT_ALT_NAME),
1242 0, san_buf + sizeof(san_buf) - len, (size_t)len);
1245 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1246 log_error(LOG_LEVEL_ERROR,
1247 "mbedtls_x509write_crt_set_extension() failed: %s", err_buf);
1251 freez(subject_alternative_name);
1258 /*********************************************************************
1260 * Function : generate_host_certificate
1262 * Description : Creates certificate file in presetted directory.
1263 * If certificate already exists, no other certificate
1264 * will be created. Subject of certificate is named
1265 * by csp->http->host from parameter. This function also
1266 * triggers generating of private key for new certificate.
1269 * 1 : csp = Current client state (buffers, headers, etc...)
1271 * Returns : -1 => Error while creating certificate.
1272 * 0 => Certificate already exists.
1273 * >0 => Length of created certificate.
1275 *********************************************************************/
1276 static int generate_host_certificate(struct client_state *csp)
1278 mbedtls_x509_crt issuer_cert;
1279 mbedtls_pk_context loaded_issuer_key, loaded_subject_key;
1280 mbedtls_pk_context *issuer_key = &loaded_issuer_key;
1281 mbedtls_pk_context *subject_key = &loaded_subject_key;
1282 mbedtls_x509write_cert cert;
1285 unsigned char *key_buf = NULL; /* Buffer for created key */
1288 char err_buf[ERROR_BUF_SIZE];
1289 cert_options cert_opt;
1290 char cert_valid_from[VALID_DATETIME_BUFLEN];
1291 char cert_valid_to[VALID_DATETIME_BUFLEN];
1293 /* Paths to keys and certificates needed to create certificate */
1294 cert_opt.issuer_key = NULL;
1295 cert_opt.subject_key = NULL;
1296 cert_opt.issuer_crt = NULL;
1298 cert_opt.output_file = make_certs_path(csp->config->certificate_directory,
1299 (const char *)csp->http->hash_of_host_hex, CERT_FILE_TYPE);
1300 if (cert_opt.output_file == NULL)
1305 cert_opt.subject_key = make_certs_path(csp->config->certificate_directory,
1306 (const char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
1307 if (cert_opt.subject_key == NULL)
1309 freez(cert_opt.output_file);
1313 if (enforce_sane_certificate_state(cert_opt.output_file,
1314 cert_opt.subject_key))
1316 freez(cert_opt.output_file);
1317 freez(cert_opt.subject_key);
1322 if (file_exists(cert_opt.output_file) == 1)
1324 /* The file exists, but is it valid? */
1325 if (ssl_certificate_is_invalid(cert_opt.output_file))
1327 log_error(LOG_LEVEL_CONNECT,
1328 "Certificate %s is no longer valid. Removing it.",
1329 cert_opt.output_file);
1330 if (unlink(cert_opt.output_file))
1332 log_error(LOG_LEVEL_ERROR, "Failed to unlink %s: %E",
1333 cert_opt.output_file);
1335 freez(cert_opt.output_file);
1336 freez(cert_opt.subject_key);
1340 if (unlink(cert_opt.subject_key))
1342 log_error(LOG_LEVEL_ERROR, "Failed to unlink %s: %E",
1343 cert_opt.subject_key);
1345 freez(cert_opt.output_file);
1346 freez(cert_opt.subject_key);
1353 freez(cert_opt.output_file);
1354 freez(cert_opt.subject_key);
1361 * Create key for requested host
1363 int subject_key_len = generate_key(csp, &key_buf);
1364 if (subject_key_len < 0)
1366 freez(cert_opt.output_file);
1367 freez(cert_opt.subject_key);
1368 log_error(LOG_LEVEL_ERROR, "Key generating failed");
1373 * Initializing structures for certificate generating
1375 mbedtls_x509write_crt_init(&cert);
1376 mbedtls_x509write_crt_set_md_alg(&cert, CERT_SIGNATURE_ALGORITHM);
1377 mbedtls_pk_init(&loaded_issuer_key);
1378 mbedtls_pk_init(&loaded_subject_key);
1379 mbedtls_mpi_init(&serial);
1380 mbedtls_x509_crt_init(&issuer_cert);
1383 * Presetting parameters for certificate. We must compute total length
1386 size_t cert_params_len = strlen(CERT_PARAM_COMMON_NAME) +
1387 strlen(CERT_PARAM_ORGANIZATION) + strlen(CERT_PARAM_COUNTRY) +
1388 strlen(CERT_PARAM_ORG_UNIT) +
1389 3 * strlen(csp->http->host) + 1;
1390 char cert_params[cert_params_len];
1391 memset(cert_params, 0, cert_params_len);
1394 * Converting unsigned long serial number to char * serial number.
1395 * We must compute length of serial number in string + terminating null.
1397 unsigned long certificate_serial = get_certificate_serial(csp);
1398 unsigned long certificate_serial_time = (unsigned long)time(NULL);
1399 int serial_num_size = snprintf(NULL, 0, "%lu%lu",
1400 certificate_serial_time, certificate_serial) + 1;
1401 if (serial_num_size <= 0)
1403 serial_num_size = 1;
1406 char serial_num_text[serial_num_size]; /* Buffer for serial number */
1407 ret = snprintf(serial_num_text, (size_t)serial_num_size, "%lu%lu",
1408 certificate_serial_time, certificate_serial);
1409 if (ret < 0 || ret >= serial_num_size)
1411 log_error(LOG_LEVEL_ERROR,
1412 "Converting certificate serial number into string failed");
1418 * Preparing parameters for certificate
1420 strlcpy(cert_params, CERT_PARAM_COMMON_NAME, cert_params_len);
1421 strlcat(cert_params, csp->http->host, cert_params_len);
1422 strlcat(cert_params, CERT_PARAM_ORGANIZATION, cert_params_len);
1423 strlcat(cert_params, csp->http->host, cert_params_len);
1424 strlcat(cert_params, CERT_PARAM_ORG_UNIT, cert_params_len);
1425 strlcat(cert_params, csp->http->host, cert_params_len);
1426 strlcat(cert_params, CERT_PARAM_COUNTRY, cert_params_len);
1428 cert_opt.issuer_crt = csp->config->ca_cert_file;
1429 cert_opt.issuer_key = csp->config->ca_key_file;
1431 if (get_certificate_valid_from_date(cert_valid_from, sizeof(cert_valid_from), VALID_DATETIME_FMT)
1432 || get_certificate_valid_to_date(cert_valid_to, sizeof(cert_valid_to), VALID_DATETIME_FMT))
1434 log_error(LOG_LEVEL_ERROR, "Generating one of the validity dates failed");
1439 cert_opt.subject_pwd = CERT_SUBJECT_PASSWORD;
1440 cert_opt.issuer_pwd = csp->config->ca_password;
1441 cert_opt.subject_name = cert_params;
1442 cert_opt.not_before = cert_valid_from;
1443 cert_opt.not_after = cert_valid_to;
1444 cert_opt.serial = serial_num_text;
1446 cert_opt.max_pathlen = -1;
1449 * Test if the private key was already created.
1450 * XXX: Can this still happen?
1452 if (subject_key_len == 0)
1454 log_error(LOG_LEVEL_ERROR, "Subject key was already created");
1462 ret = seed_rng(csp);
1470 * Parse serial to MPI
1472 ret = mbedtls_mpi_read_string(&serial, 10, cert_opt.serial);
1475 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1476 log_error(LOG_LEVEL_ERROR,
1477 "mbedtls_mpi_read_string failed: %s", err_buf);
1483 * Loading certificates
1485 ret = mbedtls_x509_crt_parse_file(&issuer_cert, cert_opt.issuer_crt);
1488 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1489 log_error(LOG_LEVEL_ERROR, "Loading issuer certificate %s failed: %s",
1490 cert_opt.issuer_crt, err_buf);
1495 ret = mbedtls_x509_dn_gets(cert_opt.issuer_name,
1496 sizeof(cert_opt.issuer_name), &issuer_cert.subject);
1499 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1500 log_error(LOG_LEVEL_ERROR, "mbedtls_x509_dn_gets failed: %s", err_buf);
1506 * Loading keys from file or from buffer
1508 if (key_buf != NULL && subject_key_len > 0)
1510 /* Key was created in this function and is stored in buffer */
1511 ret = mbedtls_pk_parse_key(&loaded_subject_key, key_buf,
1512 (size_t)(subject_key_len + 1), (unsigned const char *)
1513 cert_opt.subject_pwd, strlen(cert_opt.subject_pwd));
1517 /* Key wasn't created in this function, because it already existed */
1518 ret = mbedtls_pk_parse_keyfile(&loaded_subject_key,
1519 cert_opt.subject_key, cert_opt.subject_pwd);
1524 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1525 log_error(LOG_LEVEL_ERROR, "Parsing subject key %s failed: %s",
1526 cert_opt.subject_key, err_buf);
1531 ret = mbedtls_pk_parse_keyfile(&loaded_issuer_key, cert_opt.issuer_key,
1532 cert_opt.issuer_pwd);
1535 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1536 log_error(LOG_LEVEL_ERROR,
1537 "Parsing issuer key %s failed: %s", cert_opt.issuer_key, err_buf);
1543 * Check if key and issuer certificate match
1545 if (!mbedtls_pk_can_do(&issuer_cert.pk, MBEDTLS_PK_RSA) ||
1546 mbedtls_mpi_cmp_mpi(&mbedtls_pk_rsa(issuer_cert.pk)->N,
1547 &mbedtls_pk_rsa(*issuer_key)->N) != 0 ||
1548 mbedtls_mpi_cmp_mpi(&mbedtls_pk_rsa(issuer_cert.pk)->E,
1549 &mbedtls_pk_rsa(*issuer_key)->E) != 0)
1551 log_error(LOG_LEVEL_ERROR,
1552 "Issuer key doesn't match issuer certificate");
1557 mbedtls_x509write_crt_set_subject_key(&cert, subject_key);
1558 mbedtls_x509write_crt_set_issuer_key(&cert, issuer_key);
1561 * Setting parameters of signed certificate
1563 ret = mbedtls_x509write_crt_set_subject_name(&cert, cert_opt.subject_name);
1566 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1567 log_error(LOG_LEVEL_ERROR,
1568 "Setting subject name in signed certificate failed: %s", err_buf);
1573 ret = mbedtls_x509write_crt_set_issuer_name(&cert, cert_opt.issuer_name);
1576 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1577 log_error(LOG_LEVEL_ERROR,
1578 "Setting issuer name in signed certificate failed: %s", err_buf);
1583 ret = mbedtls_x509write_crt_set_serial(&cert, &serial);
1586 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1587 log_error(LOG_LEVEL_ERROR,
1588 "Setting serial number in signed certificate failed: %s", err_buf);
1593 ret = mbedtls_x509write_crt_set_validity(&cert, cert_opt.not_before,
1594 cert_opt.not_after);
1597 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1598 log_error(LOG_LEVEL_ERROR,
1599 "Setting validity in signed certificate failed: %s", err_buf);
1605 * Setting the basicConstraints extension for certificate
1607 ret = mbedtls_x509write_crt_set_basic_constraints(&cert, cert_opt.is_ca,
1608 cert_opt.max_pathlen);
1611 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1612 log_error(LOG_LEVEL_ERROR, "Setting the basicConstraints extension "
1613 "in signed certificate failed: %s", err_buf);
1618 #if defined(MBEDTLS_SHA1_C)
1619 /* Setting the subjectKeyIdentifier extension for certificate */
1620 ret = mbedtls_x509write_crt_set_subject_key_identifier(&cert);
1623 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1624 log_error(LOG_LEVEL_ERROR, "mbedtls_x509write_crt_set_subject_key_"
1625 "identifier failed: %s", err_buf);
1630 /* Setting the authorityKeyIdentifier extension for certificate */
1631 ret = mbedtls_x509write_crt_set_authority_key_identifier(&cert);
1634 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1635 log_error(LOG_LEVEL_ERROR, "mbedtls_x509write_crt_set_authority_key_"
1636 "identifier failed: %s", err_buf);
1640 #endif /* MBEDTLS_SHA1_C */
1642 if (!host_is_ip_address(csp->http->host) &&
1643 set_subject_alternative_name(&cert, csp->http->host))
1645 /* Errors are already logged by set_subject_alternative_name() */
1651 * Writing certificate into file
1653 ret = write_certificate(&cert, cert_opt.output_file,
1654 mbedtls_ctr_drbg_random, &ctr_drbg);
1657 log_error(LOG_LEVEL_ERROR, "Writing certificate into file failed");
1663 * Freeing used structures
1665 mbedtls_x509write_crt_free(&cert);
1666 mbedtls_pk_free(&loaded_subject_key);
1667 mbedtls_pk_free(&loaded_issuer_key);
1668 mbedtls_mpi_free(&serial);
1669 mbedtls_x509_crt_free(&issuer_cert);
1671 freez(cert_opt.subject_key);
1672 freez(cert_opt.output_file);
1678 /*********************************************************************
1680 * Function : ssl_verify_callback
1682 * Description : This is a callback function for certificate verification.
1683 * It's called once for each certificate in the server's
1684 * certificate trusted chain and prepares information about
1685 * the certificate. The information can be used to inform
1686 * the user about invalid certificates.
1689 * 1 : csp_void = Current client state (buffers, headers, etc...)
1690 * 2 : crt = certificate from trusted chain
1691 * 3 : depth = depth in trusted chain
1692 * 4 : flags = certificate flags
1694 * Returns : 0 on success and negative value on error
1696 *********************************************************************/
1697 static int ssl_verify_callback(void *csp_void, mbedtls_x509_crt *crt,
1698 int depth, uint32_t *flags)
1700 struct client_state *csp = (struct client_state *)csp_void;
1701 struct certs_chain *last = &(csp->server_certs_chain);
1706 * Searching for last item in certificates linked list
1708 while (last->next != NULL)
1714 * Preparing next item in linked list for next certificate
1716 last->next = malloc_or_die(sizeof(struct certs_chain));
1717 last->next->next = NULL;
1718 memset(last->next->info_buf, 0, sizeof(last->next->info_buf));
1719 memset(last->next->file_buf, 0, sizeof(last->next->file_buf));
1722 * Saving certificate file into buffer
1724 if ((ret = mbedtls_pem_write_buffer(PEM_BEGIN_CRT, PEM_END_CRT,
1725 crt->raw.p, crt->raw.len, (unsigned char *)last->file_buf,
1726 sizeof(last->file_buf)-1, &olen)) != 0)
1728 char err_buf[ERROR_BUF_SIZE];
1730 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1731 log_error(LOG_LEVEL_ERROR, "mbedtls_pem_write_buffer() failed: %s",
1738 * Saving certificate information into buffer
1741 char buf[CERT_INFO_BUF_SIZE];
1743 #define CERT_INFO_PREFIX ""
1745 mbedtls_x509_crt_info(buf, sizeof(buf), CERT_INFO_PREFIX, crt);
1746 encoded_text = html_encode(buf);
1747 if (encoded_text == NULL)
1749 log_error(LOG_LEVEL_ERROR,
1750 "Failed to HTML-encode the certificate information");
1753 strlcpy(last->info_buf, encoded_text, sizeof(last->info_buf));
1754 freez(encoded_text);
1761 /*********************************************************************
1763 * Function : host_to_hash
1765 * Description : Creates MD5 hash from host name. Host name is loaded
1766 * from structure csp and saved again into it.
1769 * 1 : csp = Current client state (buffers, headers, etc...)
1771 * Returns : 1 => Error while creating hash
1772 * 0 => Hash created successfully
1774 *********************************************************************/
1775 static int host_to_hash(struct client_state *csp)
1779 #if !defined(MBEDTLS_MD5_C)
1780 #error mbedTLS needs to be compiled with md5 support
1782 memset(csp->http->hash_of_host, 0, sizeof(csp->http->hash_of_host));
1783 mbedtls_md5((unsigned char *)csp->http->host, strlen(csp->http->host),
1784 csp->http->hash_of_host);
1786 /* Converting hash into string with hex */
1790 if ((ret = sprintf((char *)csp->http->hash_of_host_hex + 2 * i, "%02x",
1791 csp->http->hash_of_host[i])) < 0)
1793 log_error(LOG_LEVEL_ERROR, "Sprintf return value: %d", ret);
1799 #endif /* MBEDTLS_MD5_C */
1802 /*********************************************************************
1804 * Function : seed_rng
1806 * Description : Seeding the RNG for all SSL uses
1809 * 1 : csp = Current client state (buffers, headers, etc...)
1811 * Returns : -1 => RNG wasn't seed successfully
1812 * 0 => RNG is seeded successfully
1814 *********************************************************************/
1815 static int seed_rng(struct client_state *csp)
1818 char err_buf[ERROR_BUF_SIZE];
1820 if (rng_seeded == 0)
1822 privoxy_mutex_lock(&ssl_init_mutex);
1823 if (rng_seeded == 0)
1825 mbedtls_ctr_drbg_init(&ctr_drbg);
1826 mbedtls_entropy_init(&entropy);
1827 ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func,
1831 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1832 log_error(LOG_LEVEL_ERROR,
1833 "mbedtls_ctr_drbg_seed failed: %s", err_buf);
1834 privoxy_mutex_unlock(&ssl_init_mutex);
1839 privoxy_mutex_unlock(&ssl_init_mutex);
1845 /*********************************************************************
1847 * Function : ssl_base64_encode
1849 * Description : Encode a buffer into base64 format.
1852 * 1 : dst = Destination buffer
1853 * 2 : dlen = Destination buffer length
1854 * 3 : olen = Number of bytes written
1855 * 4 : src = Source buffer
1856 * 5 : slen = Amount of data to be encoded
1858 * Returns : 0 on success, error code othervise
1860 *********************************************************************/
1861 extern int ssl_base64_encode(unsigned char *dst, size_t dlen, size_t *olen,
1862 const unsigned char *src, size_t slen)
1864 return mbedtls_base64_encode(dst, dlen, olen, src, slen);
1868 /*********************************************************************
1870 * Function : ssl_crt_verify_info
1872 * Description : Returns an informational string about the verification
1873 * status of a certificate.
1876 * 1 : buf = Buffer to write to
1877 * 2 : size = Maximum size of buffer
1878 * 3 : csp = client state
1882 *********************************************************************/
1883 extern void ssl_crt_verify_info(char *buf, size_t size, struct client_state *csp)
1887 mbedtls_x509_crt_verify_info(buf, size, "",
1888 csp->server_cert_verification_result);
1889 last_byte = buf + strlen(buf)-1;
1890 if (*last_byte == '\n')
1892 /* Overwrite trailing new line character */
1898 /*********************************************************************
1900 * Function : ssl_release
1902 * Description : Release all SSL resources
1908 *********************************************************************/
1909 extern void ssl_release(void)
1911 if (rng_seeded == 1)
1913 mbedtls_ctr_drbg_free(&ctr_drbg);
1914 mbedtls_entropy_free(&entropy);
1919 /*********************************************************************
1921 * Function : get_ciphersuites_from_string
1923 * Description : Converts a string of ciphersuite names to
1924 * an array of ciphersuite ids.
1927 * 1 : ciphersuites_string = String containing allowed
1930 * Returns : Array of ciphersuite ids
1932 *********************************************************************/
1933 static int *get_ciphersuites_from_string(const char *parameter_string)
1935 char *ciphersuites_index;
1937 char *ciphersuites_string;
1938 int *ciphersuite_ids;
1941 const char separator = ':';
1942 size_t parameter_len = strlen(parameter_string);
1944 ciphersuites_string = zalloc_or_die(parameter_len + 1);
1945 strncpy(ciphersuites_string, parameter_string, parameter_len);
1946 ciphersuites_index = ciphersuites_string;
1948 while (*ciphersuites_index)
1950 if (*ciphersuites_index++ == separator)
1956 ciphersuite_ids = zalloc_or_die(count * sizeof(int));
1958 ciphersuites_index = ciphersuites_string;
1961 item_end = strchr(ciphersuites_index, separator);
1962 if (item_end != NULL)
1967 ciphersuite_ids[index] =
1968 mbedtls_ssl_get_ciphersuite_id(ciphersuites_index);
1969 if (ciphersuite_ids[index] == 0)
1971 log_error(LOG_LEVEL_ERROR,
1972 "Failed to get ciphersuite id for %s", ciphersuites_index);
1973 freez(ciphersuite_ids);
1974 freez(ciphersuites_string);
1977 ciphersuites_index = item_end + 1;
1979 } while (item_end != NULL);
1981 ciphersuite_ids[index] = 0;
1982 freez(ciphersuites_string);
1984 return ciphersuite_ids;