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"
57 * Macros for searching begin and end of certificates.
58 * Necessary to convert structure mbedtls_x509_crt to crt file.
60 #define PEM_BEGIN_CRT "-----BEGIN CERTIFICATE-----\n"
61 #define PEM_END_CRT "-----END CERTIFICATE-----\n"
66 #define ERROR_BUF_SIZE 1024 /* Size of buffer for error messages */
67 #define CERTIFICATE_BUF_SIZE 16384 /* Size of buffer to save certificate. Value 4096 is mbedtls library buffer size for certificate in DER form */
68 #define PRIVATE_KEY_BUF_SIZE 16000 /* Size of buffer to save private key. Value 16000 is taken from mbed TLS library examples. */
69 #define RSA_KEY_PUBLIC_EXPONENT 65537 /* Public exponent for RSA private key generating */
70 #define RSA_KEYSIZE 2048 /* Size of generated RSA keys */
71 #define CERT_SIGNATURE_ALGORITHM MBEDTLS_MD_SHA256 /* The MD algorithm to use for the signature */
72 #define CERT_SERIAL_NUM_LENGTH 4 /* Bytes of hash to be used for creating serial number of certificate. Min=2 and max=16 */
73 #define INVALID_CERT_INFO_BUF_SIZE 2048 /* Size of buffer for message with information about reason of certificate invalidity. Data after the end of buffer will not be saved */
74 #define CERT_PARAM_COMMON_NAME "CN="
75 #define CERT_PARAM_ORGANIZATION ",O="
76 #define CERT_PARAM_ORG_UNIT ",OU="
77 #define CERT_PARAM_COUNTRY ",C=CZ"
78 #define KEY_FILE_TYPE ".pem"
79 #define CERT_FILE_TYPE ".crt"
80 #define CERT_SUBJECT_PASSWORD ""
81 #define CERT_INFO_PREFIX ""
84 * Properties of cert for generating
87 char *issuer_crt; /* filename of the issuer certificate */
88 char *subject_key; /* filename of the subject key file */
89 char *issuer_key; /* filename of the issuer key file */
90 const char *subject_pwd; /* password for the subject key file */
91 const char *issuer_pwd; /* password for the issuer key file */
92 char *output_file; /* where to store the constructed key file */
93 const char *subject_name; /* subject name for certificate */
94 char issuer_name[ISSUER_NAME_BUF_SIZE]; /* issuer name for certificate */
95 const char *not_before; /* validity period not before */
96 const char *not_after; /* validity period not after */
97 const char *serial; /* serial number string */
98 int is_ca; /* is a CA certificate */
99 int max_pathlen; /* maximum CA path length */
103 * Properties of key for generating
106 mbedtls_pk_type_t type; /* type of key to generate */
107 int rsa_keysize; /* length of key in bits */
108 char *key_file_path; /* filename of the key file */
111 static int generate_webpage_certificate(struct client_state *csp);
112 static char *make_certs_path(const char *conf_dir, const char *file_name, const char *suffix);
113 static int file_exists(const char *path);
114 static int host_to_hash(struct client_state *csp);
115 static int ssl_verify_callback(void *data, mbedtls_x509_crt *crt, int depth, uint32_t *flags);
116 static void free_certificate_chain(struct client_state *csp);
117 static unsigned long get_certificate_serial(struct client_state *csp);
118 static void free_client_ssl_structures(struct client_state *csp);
119 static void free_server_ssl_structures(struct client_state *csp);
120 static int seed_rng(struct client_state *csp);
122 /*********************************************************************
124 * Function : client_use_ssl
126 * Description : Tests if client in current client state structure
127 * should use SSL connection or standard connection.
130 * 1 : csp = Current client state (buffers, headers, etc...)
132 * Returns : If client should use TLS/SSL connection, 1 is returned.
133 * Otherwise 0 is returned.
135 *********************************************************************/
136 extern int client_use_ssl(const struct client_state *csp)
138 return csp->http->client_ssl;
142 /*********************************************************************
144 * Function : server_use_ssl
146 * Description : Tests if server in current client state structure
147 * should use SSL connection or standard connection.
150 * 1 : csp = Current client state (buffers, headers, etc...)
152 * Returns : If server should use TLS/SSL connection, 1 is returned.
153 * Otherwise 0 is returned.
155 *********************************************************************/
156 extern int server_use_ssl(const struct client_state *csp)
158 return csp->http->server_ssl;
162 /*********************************************************************
164 * Function : is_ssl_pending
166 * Description : Tests if there are some waiting data on ssl connection.
167 * Only considers data that has actually been received
168 * locally and ignores data that is still on the fly
169 * or has not yet been sent by the remote end.
172 * 1 : ssl = SSL context to test
174 * Returns : 0 => No data are pending
175 * >0 => Pending data length
177 *********************************************************************/
178 extern size_t is_ssl_pending(mbedtls_ssl_context *ssl)
185 return mbedtls_ssl_get_bytes_avail(ssl);
189 /*********************************************************************
191 * Function : ssl_send_data
193 * Description : Sends the content of buf (for n bytes) to given SSL
194 * connection context.
197 * 1 : ssl = SSL context to send data to
198 * 2 : buf = Pointer to data to be sent
199 * 3 : len = Length of data to be sent to the SSL context
201 * Returns : Length of sent data or negative value on error.
203 *********************************************************************/
204 extern int ssl_send_data(mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len)
207 size_t max_fragment_size = 0; /* Maximal length of data in one SSL fragment*/
208 int send_len = 0; /* length of one data part to send */
209 int pos = 0; /* Position of unsent part in buffer */
216 /* Getting maximal length of data sent in one fragment */
217 max_fragment_size = mbedtls_ssl_get_max_frag_len(ssl);
220 * Whole buffer must be sent in many fragments, because each fragment
221 * has its maximal length.
225 /* Compute length of data, that can be send in next fragment */
226 if ((pos + (int)max_fragment_size) > len)
228 send_len = (int)len - pos;
232 send_len = (int)max_fragment_size;
235 log_error(LOG_LEVEL_WRITING, "TLS: %N", send_len, buf+pos);
238 * Sending one part of the buffer
240 while ((ret = mbedtls_ssl_write(ssl,
241 (const unsigned char *)(buf + pos),
242 (size_t)send_len)) < 0)
244 if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
245 ret != MBEDTLS_ERR_SSL_WANT_WRITE)
247 char err_buf[ERROR_BUF_SIZE];
249 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
250 log_error(LOG_LEVEL_ERROR,
251 "Sending data over TLS/SSL failed: %s", err_buf);
255 /* Adding count of sent bytes to position in buffer */
256 pos = pos + send_len;
263 /*********************************************************************
265 * Function : ssl_send_data_delayed
267 * Description : Sends the contents of buf (for n bytes) to given SSL
268 * connection, optionally delaying the operation.
271 * 1 : ssl = SSL context to send data to
272 * 2 : buf = Pointer to data to be sent
273 * 3 : len = Length of data to be sent to the SSL context
274 * 4 : delay = Delay in milliseconds.
276 * Returns : 0 on success (entire buffer sent).
279 *********************************************************************/
280 extern int ssl_send_data_delayed(mbedtls_ssl_context *ssl,
281 const unsigned char *buf, size_t len,
288 if (ssl_send_data(ssl, buf, len) < 0)
301 enum { MAX_WRITE_LENGTH = 10 };
303 if ((i + MAX_WRITE_LENGTH) > len)
305 write_length = len - i;
309 write_length = MAX_WRITE_LENGTH;
312 privoxy_millisleep(delay);
314 if (ssl_send_data(ssl, buf + i, write_length) < 0)
326 /*********************************************************************
328 * Function : ssl_recv_data
330 * Description : Receives data from given SSL context and puts
334 * 1 : ssl = SSL context to receive data from
335 * 2 : buf = Pointer to buffer where data will be written
336 * 3 : max_length = Maximum number of bytes to read
338 * Returns : Number of bytes read, 0 for EOF, or -1
341 *********************************************************************/
342 extern int ssl_recv_data(mbedtls_ssl_context *ssl, unsigned char *buf, size_t max_length)
345 memset(buf, 0, max_length);
348 * Receiving data from SSL context into buffer
352 ret = mbedtls_ssl_read(ssl, buf, max_length);
353 } while (ret == MBEDTLS_ERR_SSL_WANT_READ
354 || ret == MBEDTLS_ERR_SSL_WANT_WRITE);
358 char err_buf[ERROR_BUF_SIZE];
360 if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY)
362 log_error(LOG_LEVEL_CONNECT,
363 "The peer notified us that the connection is going to be closed");
366 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
367 log_error(LOG_LEVEL_ERROR,
368 "Receiving data over TLS/SSL failed: %s", err_buf);
373 log_error(LOG_LEVEL_RECEIVED, "TLS: %N", ret, buf);
379 /*********************************************************************
381 * Function : ssl_flush_socket
383 * Description : Send any pending "buffered" content with given
384 * SSL connection. Alternative to function flush_socket.
387 * 1 : ssl = SSL context to send buffer to
388 * 2 : iob = The I/O buffer to flush, usually csp->iob.
390 * Returns : On success, the number of bytes send are returned (zero
391 * indicates nothing was sent). On error, -1 is returned.
393 *********************************************************************/
394 extern long ssl_flush_socket(mbedtls_ssl_context *ssl, struct iob *iob)
396 /* Computing length of buffer part to send */
397 long len = iob->eod - iob->cur;
404 /* Sending data to given SSl context */
405 if (ssl_send_data(ssl, (const unsigned char *)iob->cur, (size_t)len) < 0)
409 iob->eod = iob->cur = iob->buf;
414 /*********************************************************************
416 * Function : ssl_debug_callback
418 * Description : Debug callback function for mbedtls library.
419 * Prints info into log file.
422 * 1 : ctx = File to save log in
423 * 2 : level = Debug level
424 * 3 : file = File calling debug message
425 * 4 : line = Line calling debug message
426 * 5 : str = Debug message
430 *********************************************************************/
431 static void ssl_debug_callback(void *ctx, int level, const char *file, int line, const char *str)
435 fprintf((FILE *)ctx, "%s:%04d: %s", file, line, str);
437 log_error(LOG_LEVEL_INFO, "SSL debug message: %s:%04d: %s", file, line, str);
442 /*********************************************************************
444 * Function : create_client_ssl_connection
446 * Description : Creates TLS/SSL secured connection with client
449 * 1 : csp = Current client state (buffers, headers, etc...)
451 * Returns : 0 on success, negative value if connection wasn't created
454 *********************************************************************/
455 extern int create_client_ssl_connection(struct client_state *csp)
457 /* Paths to certificates file and key file */
458 char *key_file = NULL;
459 char *ca_file = NULL;
460 char *cert_file = NULL;
462 char err_buf[ERROR_BUF_SIZE];
465 * Initializing mbedtls structures for TLS/SSL connection
467 mbedtls_net_init(&(csp->mbedtls_client_attr.socket_fd));
468 mbedtls_ssl_init(&(csp->mbedtls_client_attr.ssl));
469 mbedtls_ssl_config_init(&(csp->mbedtls_client_attr.conf));
470 mbedtls_x509_crt_init(&(csp->mbedtls_client_attr.server_cert));
471 mbedtls_pk_init(&(csp->mbedtls_client_attr.prim_key));
472 #if defined(MBEDTLS_SSL_CACHE_C)
473 mbedtls_ssl_cache_init(&(csp->mbedtls_client_attr.cache));
477 * Preparing hash of host for creating certificates
479 ret = host_to_hash(csp);
482 log_error(LOG_LEVEL_ERROR, "Generating hash of host failed: %d", ret);
488 * Preparing paths to certificates files and key file
490 ca_file = csp->config->ca_cert_file;
491 cert_file = make_certs_path(csp->config->certificate_directory,
492 (const char *)csp->http->hash_of_host_hex, CERT_FILE_TYPE);
493 key_file = make_certs_path(csp->config->certificate_directory,
494 (const char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
496 if (cert_file == NULL || key_file == NULL)
503 * Generating certificate for requested host. Mutex to prevent
504 * certificate and key inconsistence must be locked.
506 privoxy_mutex_lock(&certificate_mutex);
508 ret = generate_webpage_certificate(csp);
511 log_error(LOG_LEVEL_ERROR,
512 "Generate_webpage_certificate failed: %d", ret);
513 privoxy_mutex_unlock(&certificate_mutex);
517 privoxy_mutex_unlock(&certificate_mutex);
530 * Loading CA file, webpage certificate and key files
532 ret = mbedtls_x509_crt_parse_file(&(csp->mbedtls_client_attr.server_cert),
536 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
537 log_error(LOG_LEVEL_ERROR,
538 "Loading webpage certificate %s failed: %s", cert_file, err_buf);
543 ret = mbedtls_x509_crt_parse_file(&(csp->mbedtls_client_attr.server_cert),
547 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
548 log_error(LOG_LEVEL_ERROR,
549 "Loading CA certificate %s failed: %s", ca_file, err_buf);
554 ret = mbedtls_pk_parse_keyfile(&(csp->mbedtls_client_attr.prim_key),
558 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
559 log_error(LOG_LEVEL_ERROR,
560 "Loading and parsing webpage certificate private key %s failed: %s",
567 * Setting SSL parameters
569 ret = mbedtls_ssl_config_defaults(&(csp->mbedtls_client_attr.conf),
570 MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_TRANSPORT_STREAM,
571 MBEDTLS_SSL_PRESET_DEFAULT);
574 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
575 log_error(LOG_LEVEL_ERROR,
576 "mbedtls_ssl_config_defaults failed: %s", err_buf);
581 mbedtls_ssl_conf_rng(&(csp->mbedtls_client_attr.conf),
582 mbedtls_ctr_drbg_random, &ctr_drbg);
583 mbedtls_ssl_conf_dbg(&(csp->mbedtls_client_attr.conf),
584 ssl_debug_callback, stdout);
586 #if defined(MBEDTLS_SSL_CACHE_C)
587 mbedtls_ssl_conf_session_cache(&(csp->mbedtls_client_attr.conf),
588 &(csp->mbedtls_client_attr.cache), mbedtls_ssl_cache_get,
589 mbedtls_ssl_cache_set);
593 * Setting certificates
595 ret = mbedtls_ssl_conf_own_cert(&(csp->mbedtls_client_attr.conf),
596 &(csp->mbedtls_client_attr.server_cert),
597 &(csp->mbedtls_client_attr.prim_key));
600 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
601 log_error(LOG_LEVEL_ERROR,
602 "mbedtls_ssl_conf_own_cert failed: %s", err_buf);
607 ret = mbedtls_ssl_setup(&(csp->mbedtls_client_attr.ssl),
608 &(csp->mbedtls_client_attr.conf));
611 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
612 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_setup failed: %s", err_buf);
617 mbedtls_ssl_set_bio(&(csp->mbedtls_client_attr.ssl),
618 &(csp->mbedtls_client_attr.socket_fd), mbedtls_net_send,
619 mbedtls_net_recv, NULL);
620 mbedtls_ssl_session_reset(&(csp->mbedtls_client_attr.ssl));
623 * Setting socket fd in mbedtls_net_context structure. This structure
624 * can't be set by mbedtls functions, because we already have created
625 * a TCP connection when this function is called.
627 csp->mbedtls_client_attr.socket_fd.fd = csp->cfd;
630 * Handshake with client
632 log_error(LOG_LEVEL_CONNECT,
633 "Performing the TLS/SSL handshake with client. Hash of host: %s",
634 csp->http->hash_of_host_hex);
635 while ((ret = mbedtls_ssl_handshake(&(csp->mbedtls_client_attr.ssl))) != 0)
637 if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
638 ret != MBEDTLS_ERR_SSL_WANT_WRITE)
640 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
641 log_error(LOG_LEVEL_ERROR,
642 "medtls_ssl_handshake with client failed: %s", err_buf);
648 log_error(LOG_LEVEL_CONNECT, "Client successfully connected over TLS/SSL");
649 csp->ssl_with_client_is_opened = 1;
653 * Freeing allocated paths to files
658 /* Freeing structures if connection wasn't created successfully */
661 free_client_ssl_structures(csp);
667 /*********************************************************************
669 * Function : close_client_ssl_connection
671 * Description : Closes TLS/SSL connection with client. This function
672 * checks if this connection is already created.
675 * 1 : csp = Current client state (buffers, headers, etc...)
679 *********************************************************************/
680 extern void close_client_ssl_connection(struct client_state *csp)
684 if (csp->ssl_with_client_is_opened == 0)
690 * Notifying the peer that the connection is being closed.
693 ret = mbedtls_ssl_close_notify(&(csp->mbedtls_client_attr.ssl));
694 } while (ret == MBEDTLS_ERR_SSL_WANT_WRITE);
696 free_client_ssl_structures(csp);
697 csp->ssl_with_client_is_opened = 0;
701 /*********************************************************************
703 * Function : free_client_ssl_structures
705 * Description : Frees structures used for SSL communication with
709 * 1 : csp = Current client state (buffers, headers, etc...)
713 *********************************************************************/
714 static void free_client_ssl_structures(struct client_state *csp)
717 * We can't use function mbedtls_net_free, because this function
718 * inter alia close TCP connection on set fd. Instead of this
719 * function, we change fd to -1, which is the same what does
720 * rest of mbedtls_net_free function.
722 csp->mbedtls_client_attr.socket_fd.fd = -1;
724 /* Freeing mbedtls structures */
725 mbedtls_x509_crt_free(&(csp->mbedtls_client_attr.server_cert));
726 mbedtls_pk_free(&(csp->mbedtls_client_attr.prim_key));
727 mbedtls_ssl_free(&(csp->mbedtls_client_attr.ssl));
728 mbedtls_ssl_config_free(&(csp->mbedtls_client_attr.conf));
729 #if defined(MBEDTLS_SSL_CACHE_C)
730 mbedtls_ssl_cache_free(&(csp->mbedtls_client_attr.cache));
735 /*********************************************************************
737 * Function : create_server_ssl_connection
739 * Description : Creates TLS/SSL secured connection with server.
742 * 1 : csp = Current client state (buffers, headers, etc...)
744 * Returns : 0 on success, negative value if connection wasn't created
747 *********************************************************************/
748 extern int create_server_ssl_connection(struct client_state *csp)
751 char err_buf[ERROR_BUF_SIZE];
752 char *trusted_cas_file = NULL;
753 int auth_mode = MBEDTLS_SSL_VERIFY_REQUIRED;
755 csp->server_cert_verification_result = SSL_CERT_NOT_VERIFIED;
756 csp->server_certs_chain.next = NULL;
758 /* Setting path to file with trusted CAs */
759 trusted_cas_file = csp->config->trusted_cas_file;
762 * Initializing mbedtls structures for TLS/SSL connection
764 mbedtls_net_init(&(csp->mbedtls_server_attr.socket_fd));
765 mbedtls_ssl_init(&(csp->mbedtls_server_attr.ssl));
766 mbedtls_ssl_config_init(&(csp->mbedtls_server_attr.conf));
767 mbedtls_x509_crt_init(&(csp->mbedtls_server_attr.ca_cert));
770 * Setting socket fd in mbedtls_net_context structure. This structure
771 * can't be set by mbedtls functions, because we already have created
772 * TCP connection when calling this function.
774 csp->mbedtls_server_attr.socket_fd.fd = csp->server_connection.sfd;
787 * Loading file with trusted CAs
789 ret = mbedtls_x509_crt_parse_file(&(csp->mbedtls_server_attr.ca_cert),
793 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
794 log_error(LOG_LEVEL_ERROR, "Loading trusted CAs file %s failed: %s",
795 trusted_cas_file, err_buf);
801 * Set TLS/SSL options
803 ret = mbedtls_ssl_config_defaults(&(csp->mbedtls_server_attr.conf),
804 MBEDTLS_SSL_IS_CLIENT,
805 MBEDTLS_SSL_TRANSPORT_STREAM,
806 MBEDTLS_SSL_PRESET_DEFAULT);
809 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
810 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_config_defaults failed: %s",
817 * Setting how strict should certificate verification be and other
818 * parameters for certificate verification
820 if (csp->dont_verify_certificate)
822 auth_mode = MBEDTLS_SSL_VERIFY_NONE;
825 mbedtls_ssl_conf_authmode(&(csp->mbedtls_server_attr.conf), auth_mode);
826 mbedtls_ssl_conf_ca_chain(&(csp->mbedtls_server_attr.conf),
827 &(csp->mbedtls_server_attr.ca_cert), NULL);
829 /* Setting callback function for certificates verification */
830 mbedtls_ssl_conf_verify(&(csp->mbedtls_server_attr.conf),
831 ssl_verify_callback, (void *)csp);
833 mbedtls_ssl_conf_rng(&(csp->mbedtls_server_attr.conf),
834 mbedtls_ctr_drbg_random, &ctr_drbg);
835 mbedtls_ssl_conf_dbg(&(csp->mbedtls_server_attr.conf),
836 ssl_debug_callback, stdout);
838 ret = mbedtls_ssl_setup(&(csp->mbedtls_server_attr.ssl),
839 &(csp->mbedtls_server_attr.conf));
842 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
843 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_setup failed: %s", err_buf);
849 * Set the hostname to check against the received server certificate
851 ret = mbedtls_ssl_set_hostname(&(csp->mbedtls_server_attr.ssl),
855 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
856 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_set_hostname failed: %s",
862 mbedtls_ssl_set_bio(&(csp->mbedtls_server_attr.ssl),
863 &(csp->mbedtls_server_attr.socket_fd), mbedtls_net_send,
864 mbedtls_net_recv, NULL);
867 * Handshake with server
869 log_error(LOG_LEVEL_CONNECT,
870 "Performing the TLS/SSL handshake with the server");
872 while ((ret = mbedtls_ssl_handshake(&(csp->mbedtls_server_attr.ssl))) != 0)
874 if (ret != MBEDTLS_ERR_SSL_WANT_READ
875 && ret != MBEDTLS_ERR_SSL_WANT_WRITE)
877 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
879 if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED)
881 char reason[INVALID_CERT_INFO_BUF_SIZE];
883 csp->server_cert_verification_result =
884 mbedtls_ssl_get_verify_result(&(csp->mbedtls_server_attr.ssl));
885 mbedtls_x509_crt_verify_info(reason, sizeof(reason), "",
886 csp->server_cert_verification_result);
888 /* Log the reason without the trailing new line */
889 log_error(LOG_LEVEL_ERROR,
890 "X509 certificate verification for %s failed: %N",
891 csp->http->hostport, strlen(reason)-1, reason);
896 log_error(LOG_LEVEL_ERROR,
897 "mbedtls_ssl_handshake with server failed: %s", err_buf);
898 free_certificate_chain(csp);
905 log_error(LOG_LEVEL_CONNECT, "Server successfully connected over TLS/SSL");
908 * Server certificate chain is valid, so we can clean
909 * chain, because we will not send it to client.
911 free_certificate_chain(csp);
913 csp->ssl_with_server_is_opened = 1;
914 csp->server_cert_verification_result =
915 mbedtls_ssl_get_verify_result(&(csp->mbedtls_server_attr.ssl));
918 /* Freeing structures if connection wasn't created successfully */
921 free_server_ssl_structures(csp);
928 /*********************************************************************
930 * Function : close_server_ssl_connection
932 * Description : Closes TLS/SSL connection with server. This function
933 * checks if this connection is already opened.
936 * 1 : csp = Current client state (buffers, headers, etc...)
940 *********************************************************************/
941 static void close_server_ssl_connection(struct client_state *csp)
945 if (csp->ssl_with_server_is_opened == 0)
951 * Notifying the peer that the connection is being closed.
954 ret = mbedtls_ssl_close_notify(&(csp->mbedtls_server_attr.ssl));
955 } while (ret == MBEDTLS_ERR_SSL_WANT_WRITE);
957 free_server_ssl_structures(csp);
958 csp->ssl_with_server_is_opened = 0;
962 /*********************************************************************
964 * Function : free_server_ssl_structures
966 * Description : Frees structures used for SSL communication with server
969 * 1 : csp = Current client state (buffers, headers, etc...)
973 *********************************************************************/
974 static void free_server_ssl_structures(struct client_state *csp)
977 * We can't use function mbedtls_net_free, because this function
978 * inter alia close TCP connection on set fd. Instead of this
979 * function, we change fd to -1, which is the same what does
980 * rest of mbedtls_net_free function.
982 csp->mbedtls_server_attr.socket_fd.fd = -1;
984 mbedtls_x509_crt_free(&(csp->mbedtls_server_attr.ca_cert));
985 mbedtls_ssl_free(&(csp->mbedtls_server_attr.ssl));
986 mbedtls_ssl_config_free(&(csp->mbedtls_server_attr.conf));
990 /*********************************************************************
992 * Function : close_client_and_server_ssl_connections
994 * Description : Checks if client or server should use secured
995 * connection over SSL and if so, closes all of them.
998 * 1 : csp = Current client state (buffers, headers, etc...)
1002 *********************************************************************/
1003 extern void close_client_and_server_ssl_connections(struct client_state *csp)
1005 if (client_use_ssl(csp) == 1)
1007 close_client_ssl_connection(csp);
1009 if (server_use_ssl(csp) == 1)
1011 close_server_ssl_connection(csp);
1015 /*====================== Certificates ======================*/
1017 /*********************************************************************
1019 * Function : write_certificate
1021 * Description : Writes certificate into file.
1024 * 1 : crt = certificate to write into file
1025 * 2 : output_file = path to save certificate file
1026 * 3 : f_rng = mbedtls_ctr_drbg_random
1027 * 4 : p_rng = mbedtls_ctr_drbg_context
1029 * Returns : Length of written certificate on success or negative value
1032 *********************************************************************/
1033 static int write_certificate(mbedtls_x509write_cert *crt, const char *output_file,
1034 int(*f_rng)(void *, unsigned char *, size_t), void *p_rng)
1038 unsigned char cert_buf[CERTIFICATE_BUF_SIZE + 1]; /* Buffer for certificate in PEM format + terminating NULL */
1040 char err_buf[ERROR_BUF_SIZE];
1042 memset(cert_buf, 0, sizeof(cert_buf));
1045 * Writing certificate into PEM string. If buffer is too small, function
1046 * returns specific error and no buffer overflow can happen.
1048 if ((ret = mbedtls_x509write_crt_pem(crt, cert_buf,
1049 sizeof(cert_buf) - 1, f_rng, p_rng)) != 0)
1051 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1052 log_error(LOG_LEVEL_ERROR,
1053 "Writing certificate into buffer failed: %s", err_buf);
1057 len = strlen((char *)cert_buf);
1060 * Saving certificate into file
1062 if ((f = fopen(output_file, "w")) == NULL)
1064 log_error(LOG_LEVEL_ERROR, "Opening file %s to save certificate failed",
1069 if (fwrite(cert_buf, 1, len, f) != len)
1071 log_error(LOG_LEVEL_ERROR,
1072 "Writing certificate into file %s failed", output_file);
1083 /*********************************************************************
1085 * Function : write_private_key
1087 * Description : Writes private key into file and copies saved
1088 * content into given pointer to string. If function
1089 * returns 0 for success, this copy must be freed by
1093 * 1 : key = key to write into file
1094 * 2 : ret_buf = pointer to string with created key file content
1095 * 3 : key_file_path = path where to save key file
1097 * Returns : Length of written private key on success or negative value
1100 *********************************************************************/
1101 static int write_private_key(mbedtls_pk_context *key, unsigned char **ret_buf,
1102 const char *key_file_path)
1104 size_t len = 0; /* Length of created key */
1105 FILE *f = NULL; /* File to save certificate */
1107 char err_buf[ERROR_BUF_SIZE];
1109 /* Initializing buffer for key file content */
1110 *ret_buf = zalloc_or_die(PRIVATE_KEY_BUF_SIZE + 1);
1113 * Writing private key into PEM string
1115 if ((ret = mbedtls_pk_write_key_pem(key, *ret_buf, PRIVATE_KEY_BUF_SIZE)) != 0)
1117 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1118 log_error(LOG_LEVEL_ERROR,
1119 "Writing private key into PEM string failed: %s", err_buf);
1123 len = strlen((char *)*ret_buf);
1126 * Saving key into file
1128 if ((f = fopen(key_file_path, "wb")) == NULL)
1130 log_error(LOG_LEVEL_ERROR,
1131 "Opening file %s to save private key failed: %E",
1137 if (fwrite(*ret_buf, 1, len, f) != len)
1140 log_error(LOG_LEVEL_ERROR,
1141 "Writing private key into file %s failed",
1160 /*********************************************************************
1162 * Function : generate_key
1164 * Description : Tests if private key for host saved in csp already
1165 * exists. If this file doesn't exists, a new key is
1166 * generated and saved in a file. The generated key is also
1167 * copied into given parameter key_buf, which must be then
1168 * freed by caller. If file with key exists, key_buf
1169 * contain NULL and no private key is generated.
1172 * 1 : csp = Current client state (buffers, headers, etc...)
1173 * 2 : key_buf = buffer to save new generated key
1175 * Returns : -1 => Error while generating private key
1176 * 0 => Key already exists
1177 * >0 => Length of generated private key
1179 *********************************************************************/
1180 static int generate_key(struct client_state *csp, unsigned char **key_buf)
1182 mbedtls_pk_context key;
1183 key_options key_opt;
1185 char err_buf[ERROR_BUF_SIZE];
1187 key_opt.key_file_path = NULL;
1190 * Initializing structures for key generating
1192 mbedtls_pk_init(&key);
1195 * Preparing path for key file and other properties for generating key
1197 key_opt.type = MBEDTLS_PK_RSA;
1198 key_opt.rsa_keysize = RSA_KEYSIZE;
1200 key_opt.key_file_path = make_certs_path(csp->config->certificate_directory,
1201 (char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
1202 if (key_opt.key_file_path == NULL)
1209 * Test if key already exists. If so, we don't have to create it again.
1211 if (file_exists(key_opt.key_file_path) == 1)
1220 ret = seed_rng(csp);
1228 * Setting attributes of private key and generating it
1230 if ((ret = mbedtls_pk_setup(&key,
1231 mbedtls_pk_info_from_type(key_opt.type))) != 0)
1233 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1234 log_error(LOG_LEVEL_ERROR, "mbedtls_pk_setup failed: %s", err_buf);
1239 ret = mbedtls_rsa_gen_key(mbedtls_pk_rsa(key), mbedtls_ctr_drbg_random,
1240 &ctr_drbg, (unsigned)key_opt.rsa_keysize, RSA_KEY_PUBLIC_EXPONENT);
1243 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1244 log_error(LOG_LEVEL_ERROR, "Key generating failed: %s", err_buf);
1250 * Exporting private key into file
1252 if ((ret = write_private_key(&key, key_buf, key_opt.key_file_path)) < 0)
1254 log_error(LOG_LEVEL_ERROR,
1255 "Writing private key into file %s failed", key_opt.key_file_path);
1262 * Freeing used variables
1264 freez(key_opt.key_file_path);
1266 mbedtls_pk_free(&key);
1272 /*********************************************************************
1274 * Function : ssl_certificate_is_invalid
1276 * Description : Checks whether or not a certificate is valid.
1277 * Currently only checks that the certificate can be
1278 * parsed and that the "valid to" date is in the future.
1281 * 1 : cert_file = The certificate to check
1283 * Returns : 0 => The certificate is valid.
1284 * 1 => The certificate is invalid
1286 *********************************************************************/
1287 static int ssl_certificate_is_invalid(const char *cert_file)
1289 mbedtls_x509_crt cert;
1292 mbedtls_x509_crt_init(&cert);
1294 ret = mbedtls_x509_crt_parse_file(&cert, cert_file);
1297 char err_buf[ERROR_BUF_SIZE];
1299 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1300 log_error(LOG_LEVEL_ERROR,
1301 "Loading certificate %s to check validity failed: %s",
1302 cert_file, err_buf);
1303 mbedtls_x509_crt_free(&cert);
1307 if (mbedtls_x509_time_is_past(&cert.valid_to))
1309 mbedtls_x509_crt_free(&cert);
1314 mbedtls_x509_crt_free(&cert);
1321 /*********************************************************************
1323 * Function : generate_certificate_valid_date
1325 * Description : Turns a time_t into the format expected by mbedTLS.
1328 * 1 : time_spec = The timestamp to convert
1329 * 2 : buffer = The buffer to write the date to
1330 * 3 : buffer_size = The size of the buffer
1332 * Returns : 0 => The conversion worked
1333 * 1 => The conversion failed
1335 *********************************************************************/
1336 static int generate_certificate_valid_date(time_t time_spec, char *buffer,
1339 struct tm valid_date;
1343 timeptr = privoxy_gmtime_r(&time_spec, &valid_date);
1344 if (NULL == timeptr)
1349 ret = strftime(buffer, buffer_size, "%Y%m%d%H%M%S", timeptr);
1360 /*********************************************************************
1362 * Function : get_certificate_valid_from_date
1364 * Description : Generates a "valid from" date in the format
1365 * expected by mbedTLS.
1368 * 1 : buffer = The buffer to write the date to
1369 * 2 : buffer_size = The size of the buffer
1371 * Returns : 0 => The generation worked
1372 * 1 => The generation failed
1374 *********************************************************************/
1375 static int get_certificate_valid_from_date(char *buffer, size_t buffer_size)
1379 time_spec = time(NULL);
1380 /* 1 month in the past */
1381 time_spec -= 30 * 24 * 60 * 60;
1383 return generate_certificate_valid_date(time_spec, buffer, buffer_size);
1388 /*********************************************************************
1390 * Function : get_certificate_valid_to_date
1392 * Description : Generates a "valid to" date in the format
1393 * expected by mbedTLS.
1396 * 1 : buffer = The buffer to write the date to
1397 * 2 : buffer_size = The size of the buffer
1399 * Returns : 0 => The generation worked
1400 * 1 => The generation failed
1402 *********************************************************************/
1403 static int get_certificate_valid_to_date(char *buffer, size_t buffer_size)
1407 time_spec = time(NULL);
1408 /* Three months in the future */
1409 time_spec += 90 * 24 * 60 * 60;
1411 return generate_certificate_valid_date(time_spec, buffer, buffer_size);
1416 /*********************************************************************
1418 * Function : set_subject_alternative_name
1420 * Description : Sets the Subject Alternative Name extension to a cert
1423 * 1 : cert = The certificate to modify
1424 * 2 : hostname = The hostname to add
1426 * Returns : <0 => Error while creating certificate.
1429 *********************************************************************/
1430 static int set_subject_alternative_name(mbedtls_x509write_cert *cert, const char *hostname)
1432 char err_buf[ERROR_BUF_SIZE];
1434 char *subject_alternative_name;
1435 size_t subject_alternative_name_len;
1436 #define MBEDTLS_SUBJECT_ALTERNATIVE_NAME_MAX_LEN 255
1437 unsigned char san_buf[MBEDTLS_SUBJECT_ALTERNATIVE_NAME_MAX_LEN + 1];
1441 subject_alternative_name_len = strlen(hostname) + 1;
1442 subject_alternative_name = zalloc_or_die(subject_alternative_name_len);
1444 strlcpy(subject_alternative_name, hostname, subject_alternative_name_len);
1446 memset(san_buf, 0, sizeof(san_buf));
1448 c = san_buf + sizeof(san_buf);
1451 ret = mbedtls_asn1_write_raw_buffer(&c, san_buf,
1452 (const unsigned char *)subject_alternative_name,
1453 strlen(subject_alternative_name));
1456 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1457 log_error(LOG_LEVEL_ERROR,
1458 "mbedtls_asn1_write_raw_buffer() failed: %s", err_buf);
1463 ret = mbedtls_asn1_write_len(&c, san_buf, strlen(subject_alternative_name));
1466 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1467 log_error(LOG_LEVEL_ERROR,
1468 "mbedtls_asn1_write_len() failed: %s", err_buf);
1473 ret = mbedtls_asn1_write_tag(&c, san_buf, MBEDTLS_ASN1_CONTEXT_SPECIFIC | 2);
1476 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1477 log_error(LOG_LEVEL_ERROR,
1478 "mbedtls_asn1_write_tag() failed: %s", err_buf);
1483 ret = mbedtls_asn1_write_len(&c, san_buf, (size_t)len);
1486 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1487 log_error(LOG_LEVEL_ERROR,
1488 "mbedtls_asn1_write_len() failed: %s", err_buf);
1493 ret = mbedtls_asn1_write_tag(&c, san_buf,
1494 MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE);
1497 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1498 log_error(LOG_LEVEL_ERROR,
1499 "mbedtls_asn1_write_tag() failed: %s", err_buf);
1504 ret = mbedtls_x509write_crt_set_extension(cert,
1505 MBEDTLS_OID_SUBJECT_ALT_NAME,
1506 MBEDTLS_OID_SIZE(MBEDTLS_OID_SUBJECT_ALT_NAME),
1507 0, san_buf + sizeof(san_buf) - len, (size_t)len);
1510 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1511 log_error(LOG_LEVEL_ERROR,
1512 "mbedtls_x509write_crt_set_extension() failed: %s", err_buf);
1516 freez(subject_alternative_name);
1522 /*********************************************************************
1524 * Function : generate_webpage_certificate
1526 * Description : Creates certificate file in presetted directory.
1527 * If certificate already exists, no other certificate
1528 * will be created. Subject of certificate is named
1529 * by csp->http->host from parameter. This function also
1530 * triggers generating of private key for new certificate.
1533 * 1 : csp = Current client state (buffers, headers, etc...)
1535 * Returns : -1 => Error while creating certificate.
1536 * 0 => Certificate already exists.
1537 * >0 => Length of created certificate.
1539 *********************************************************************/
1540 static int generate_webpage_certificate(struct client_state *csp)
1542 mbedtls_x509_crt issuer_cert;
1543 mbedtls_pk_context loaded_issuer_key, loaded_subject_key;
1544 mbedtls_pk_context *issuer_key = &loaded_issuer_key;
1545 mbedtls_pk_context *subject_key = &loaded_subject_key;
1546 mbedtls_x509write_cert cert;
1549 unsigned char *key_buf = NULL; /* Buffer for created key */
1552 char err_buf[ERROR_BUF_SIZE];
1553 cert_options cert_opt;
1554 char cert_valid_from[15];
1555 char cert_valid_to[15];
1557 /* Paths to keys and certificates needed to create certificate */
1558 cert_opt.issuer_key = NULL;
1559 cert_opt.subject_key = NULL;
1560 cert_opt.issuer_crt = NULL;
1562 cert_opt.output_file = make_certs_path(csp->config->certificate_directory,
1563 (const char *)csp->http->hash_of_host_hex, CERT_FILE_TYPE);
1564 if (cert_opt.output_file == NULL)
1569 cert_opt.subject_key = make_certs_path(csp->config->certificate_directory,
1570 (const char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
1571 if (cert_opt.subject_key == NULL)
1573 freez(cert_opt.output_file);
1577 if (file_exists(cert_opt.output_file) == 1)
1579 /* The file exists, but is it valid? */
1580 if (ssl_certificate_is_invalid(cert_opt.output_file))
1582 log_error(LOG_LEVEL_CONNECT,
1583 "Certificate %s is no longer valid. Removing it.",
1584 cert_opt.output_file);
1585 if (unlink(cert_opt.output_file))
1587 log_error(LOG_LEVEL_ERROR, "Failed to unlink %s: %E",
1588 cert_opt.output_file);
1590 freez(cert_opt.output_file);
1591 freez(cert_opt.subject_key);
1595 if (unlink(cert_opt.subject_key))
1597 log_error(LOG_LEVEL_ERROR, "Failed to unlink %s: %E",
1598 cert_opt.subject_key);
1600 freez(cert_opt.output_file);
1601 freez(cert_opt.subject_key);
1608 freez(cert_opt.output_file);
1609 freez(cert_opt.subject_key);
1616 * Create key for requested host
1618 int subject_key_len = generate_key(csp, &key_buf);
1619 if (subject_key_len < 0)
1621 freez(cert_opt.output_file);
1622 freez(cert_opt.subject_key);
1623 log_error(LOG_LEVEL_ERROR, "Key generating failed");
1628 * Initializing structures for certificate generating
1630 mbedtls_x509write_crt_init(&cert);
1631 mbedtls_x509write_crt_set_md_alg(&cert, CERT_SIGNATURE_ALGORITHM);
1632 mbedtls_pk_init(&loaded_issuer_key);
1633 mbedtls_pk_init(&loaded_subject_key);
1634 mbedtls_mpi_init(&serial);
1635 mbedtls_x509_crt_init(&issuer_cert);
1638 * Presetting parameters for certificate. We must compute total length
1641 size_t cert_params_len = strlen(CERT_PARAM_COMMON_NAME) +
1642 strlen(CERT_PARAM_ORGANIZATION) + strlen(CERT_PARAM_COUNTRY) +
1643 strlen(CERT_PARAM_ORG_UNIT) +
1644 3 * strlen(csp->http->host) + 1;
1645 char cert_params[cert_params_len];
1646 memset(cert_params, 0, cert_params_len);
1649 * Converting unsigned long serial number to char * serial number.
1650 * We must compute length of serial number in string + terminating null.
1652 unsigned long certificate_serial = get_certificate_serial(csp);
1653 unsigned long certificate_serial_time = (unsigned long)time(NULL);
1654 int serial_num_size = snprintf(NULL, 0, "%lu%lu",
1655 certificate_serial_time, certificate_serial) + 1;
1656 if (serial_num_size <= 0)
1658 serial_num_size = 1;
1661 char serial_num_text[serial_num_size]; /* Buffer for serial number */
1662 ret = snprintf(serial_num_text, (size_t)serial_num_size, "%lu%lu",
1663 certificate_serial_time, certificate_serial);
1664 if (ret < 0 || ret >= serial_num_size)
1666 log_error(LOG_LEVEL_ERROR,
1667 "Converting certificate serial number into string failed");
1673 * Preparing parameters for certificate
1675 strlcpy(cert_params, CERT_PARAM_COMMON_NAME, cert_params_len);
1676 strlcat(cert_params, csp->http->host, cert_params_len);
1677 strlcat(cert_params, CERT_PARAM_ORGANIZATION, cert_params_len);
1678 strlcat(cert_params, csp->http->host, cert_params_len);
1679 strlcat(cert_params, CERT_PARAM_ORG_UNIT, cert_params_len);
1680 strlcat(cert_params, csp->http->host, cert_params_len);
1681 strlcat(cert_params, CERT_PARAM_COUNTRY, cert_params_len);
1683 cert_opt.issuer_crt = csp->config->ca_cert_file;
1684 cert_opt.issuer_key = csp->config->ca_key_file;
1686 if (get_certificate_valid_from_date(cert_valid_from, sizeof(cert_valid_from))
1687 || get_certificate_valid_to_date(cert_valid_to, sizeof(cert_valid_to)))
1689 log_error(LOG_LEVEL_ERROR, "Generating one of the validity dates failed");
1694 cert_opt.subject_pwd = CERT_SUBJECT_PASSWORD;
1695 cert_opt.issuer_pwd = csp->config->ca_password;
1696 cert_opt.subject_name = cert_params;
1697 cert_opt.not_before = cert_valid_from;
1698 cert_opt.not_after = cert_valid_to;
1699 cert_opt.serial = serial_num_text;
1701 cert_opt.max_pathlen = -1;
1704 * Test if the private key was already created.
1705 * XXX: Can this still happen?
1707 if (subject_key_len == 0)
1709 log_error(LOG_LEVEL_ERROR, "Subject key was already created");
1717 ret = seed_rng(csp);
1725 * Parse serial to MPI
1727 ret = mbedtls_mpi_read_string(&serial, 10, cert_opt.serial);
1730 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1731 log_error(LOG_LEVEL_ERROR,
1732 "mbedtls_mpi_read_string failed: %s", err_buf);
1738 * Loading certificates
1740 ret = mbedtls_x509_crt_parse_file(&issuer_cert, cert_opt.issuer_crt);
1743 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1744 log_error(LOG_LEVEL_ERROR, "Loading issuer certificate %s failed: %s",
1745 cert_opt.issuer_crt, err_buf);
1750 ret = mbedtls_x509_dn_gets(cert_opt.issuer_name,
1751 sizeof(cert_opt.issuer_name), &issuer_cert.subject);
1754 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1755 log_error(LOG_LEVEL_ERROR, "mbedtls_x509_dn_gets failed: %s", err_buf);
1761 * Loading keys from file or from buffer
1763 if (key_buf != NULL && subject_key_len > 0)
1765 /* Key was created in this function and is stored in buffer */
1766 ret = mbedtls_pk_parse_key(&loaded_subject_key, key_buf,
1767 (size_t)(subject_key_len + 1), (unsigned const char *)
1768 cert_opt.subject_pwd, strlen(cert_opt.subject_pwd));
1772 /* Key wasn't created in this function, because it already existed */
1773 ret = mbedtls_pk_parse_keyfile(&loaded_subject_key,
1774 cert_opt.subject_key, cert_opt.subject_pwd);
1779 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1780 log_error(LOG_LEVEL_ERROR, "Parsing subject key %s failed: %s",
1781 cert_opt.subject_key, err_buf);
1786 ret = mbedtls_pk_parse_keyfile(&loaded_issuer_key, cert_opt.issuer_key,
1787 cert_opt.issuer_pwd);
1790 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1791 log_error(LOG_LEVEL_ERROR,
1792 "Parsing issuer key %s failed: %s", cert_opt.issuer_key, err_buf);
1798 * Check if key and issuer certificate match
1800 if (!mbedtls_pk_can_do(&issuer_cert.pk, MBEDTLS_PK_RSA) ||
1801 mbedtls_mpi_cmp_mpi(&mbedtls_pk_rsa(issuer_cert.pk)->N,
1802 &mbedtls_pk_rsa(*issuer_key)->N) != 0 ||
1803 mbedtls_mpi_cmp_mpi(&mbedtls_pk_rsa(issuer_cert.pk)->E,
1804 &mbedtls_pk_rsa(*issuer_key)->E) != 0)
1806 log_error(LOG_LEVEL_ERROR,
1807 "Issuer key doesn't match issuer certificate");
1812 mbedtls_x509write_crt_set_subject_key(&cert, subject_key);
1813 mbedtls_x509write_crt_set_issuer_key(&cert, issuer_key);
1816 * Setting parameters of signed certificate
1818 ret = mbedtls_x509write_crt_set_subject_name(&cert, cert_opt.subject_name);
1821 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1822 log_error(LOG_LEVEL_ERROR,
1823 "Setting subject name in signed certificate failed: %s", err_buf);
1828 ret = mbedtls_x509write_crt_set_issuer_name(&cert, cert_opt.issuer_name);
1831 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1832 log_error(LOG_LEVEL_ERROR,
1833 "Setting issuer name in signed certificate failed: %s", err_buf);
1838 ret = mbedtls_x509write_crt_set_serial(&cert, &serial);
1841 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1842 log_error(LOG_LEVEL_ERROR,
1843 "Setting serial number in signed certificate failed: %s", err_buf);
1848 ret = mbedtls_x509write_crt_set_validity(&cert, cert_opt.not_before,
1849 cert_opt.not_after);
1852 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1853 log_error(LOG_LEVEL_ERROR,
1854 "Setting validity in signed certificate failed: %s", err_buf);
1860 * Setting the basicConstraints extension for certificate
1862 ret = mbedtls_x509write_crt_set_basic_constraints(&cert, cert_opt.is_ca,
1863 cert_opt.max_pathlen);
1866 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1867 log_error(LOG_LEVEL_ERROR, "Setting the basicConstraints extension "
1868 "in signed certificate failed: %s", err_buf);
1873 #if defined(MBEDTLS_SHA1_C)
1874 /* Setting the subjectKeyIdentifier extension for certificate */
1875 ret = mbedtls_x509write_crt_set_subject_key_identifier(&cert);
1878 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1879 log_error(LOG_LEVEL_ERROR, "mbedtls_x509write_crt_set_subject_key_"
1880 "identifier failed: %s", err_buf);
1885 /* Setting the authorityKeyIdentifier extension for certificate */
1886 ret = mbedtls_x509write_crt_set_authority_key_identifier(&cert);
1889 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1890 log_error(LOG_LEVEL_ERROR, "mbedtls_x509write_crt_set_authority_key_"
1891 "identifier failed: %s", err_buf);
1895 #endif /* MBEDTLS_SHA1_C */
1897 if (set_subject_alternative_name(&cert, csp->http->host))
1899 /* Errors are already logged by set_subject_alternative_name() */
1905 * Writing certificate into file
1907 ret = write_certificate(&cert, cert_opt.output_file,
1908 mbedtls_ctr_drbg_random, &ctr_drbg);
1911 log_error(LOG_LEVEL_ERROR, "Writing certificate into file failed");
1917 * Freeing used structures
1919 mbedtls_x509write_crt_free(&cert);
1920 mbedtls_pk_free(&loaded_subject_key);
1921 mbedtls_pk_free(&loaded_issuer_key);
1922 mbedtls_mpi_free(&serial);
1923 mbedtls_x509_crt_free(&issuer_cert);
1925 freez(cert_opt.subject_key);
1926 freez(cert_opt.output_file);
1933 /*********************************************************************
1935 * Function : make_certs_path
1937 * Description : Creates path to file from three pieces. This function
1938 * takes parameters and puts them in one new mallocated
1939 * char * in correct order. Returned variable must be freed
1940 * by caller. This function is mainly used for creating
1941 * paths of certificates and keys files.
1944 * 1 : conf_dir = Name/path of directory where is the file.
1945 * '.' can be used for current directory.
1946 * 2 : file_name = Name of file in conf_dir without suffix.
1947 * 3 : suffix = Suffix of given file_name.
1949 * Returns : path => Path was built up successfully
1950 * NULL => Path can't be built up
1952 *********************************************************************/
1953 static char *make_certs_path(const char *conf_dir, const char *file_name,
1956 /* Test if all given parameters are valid */
1957 if (conf_dir == NULL || *conf_dir == '\0' || file_name == NULL ||
1958 *file_name == '\0' || suffix == NULL || *suffix == '\0')
1960 log_error(LOG_LEVEL_ERROR,
1961 "make_certs_path failed: bad input parameters");
1966 size_t path_size = strlen(conf_dir)
1967 + strlen(file_name) + strlen(suffix) + 2;
1969 /* Setting delimiter and editing path length */
1970 #if defined(_WIN32) || defined(__OS2__)
1971 char delim[] = "\\";
1973 #else /* ifndef _WIN32 || __OS2__ */
1975 #endif /* ifndef _WIN32 || __OS2__ */
1978 * Building up path from many parts
1981 if (*conf_dir != '/' && basedir && *basedir)
1984 * Replacing conf_dir with basedir. This new variable contains
1985 * absolute path to cwd.
1987 path_size += strlen(basedir) + 2;
1988 path = zalloc_or_die(path_size);
1990 strlcpy(path, basedir, path_size);
1991 strlcat(path, delim, path_size);
1992 strlcat(path, conf_dir, path_size);
1993 strlcat(path, delim, path_size);
1994 strlcat(path, file_name, path_size);
1995 strlcat(path, suffix, path_size);
1998 #endif /* defined unix */
2000 path = zalloc_or_die(path_size);
2002 strlcpy(path, conf_dir, path_size);
2003 strlcat(path, delim, path_size);
2004 strlcat(path, file_name, path_size);
2005 strlcat(path, suffix, path_size);
2012 /*********************************************************************
2014 * Function : get_certificate_serial
2016 * Description : Computes serial number for new certificate from host
2017 * name hash. This hash must be already saved in csp
2021 * 1 : csp = Current client state (buffers, headers, etc...)
2023 * Returns : Serial number for new certificate
2025 *********************************************************************/
2026 static unsigned long get_certificate_serial(struct client_state *csp)
2028 unsigned long exp = 1;
2029 unsigned long serial = 0;
2031 int i = CERT_SERIAL_NUM_LENGTH;
2035 serial += exp * (unsigned)csp->http->hash_of_host[i];
2042 /*********************************************************************
2044 * Function : ssl_send_certificate_error
2046 * Description : Sends info about invalid server certificate to client.
2047 * Sent message is including all trusted chain certificates,
2048 * that can be downloaded in web browser.
2051 * 1 : csp = Current client state (buffers, headers, etc...)
2055 *********************************************************************/
2056 extern void ssl_send_certificate_error(struct client_state *csp)
2058 size_t message_len = 0;
2060 struct certs_chain *cert = NULL;
2062 /* Header of message with certificate information */
2063 const char message_begin[] =
2064 "HTTP/1.1 200 OK\r\n"
2065 "Content-Type: text/html\r\n"
2066 "Connection: close\r\n\r\n"
2067 "<html><body><h1>Server certificate verification failed</h1>"
2068 "<p><a href=\"https://" CGI_SITE_2_HOST "/\">Privoxy</a> was unable "
2069 "to securely connnect to the destination server.</p>"
2071 const char message_end[] = "</body></html>\r\n\r\n";
2072 char reason[INVALID_CERT_INFO_BUF_SIZE];
2073 memset(reason, 0, sizeof(reason));
2075 /* Get verification message from verification return code */
2076 mbedtls_x509_crt_verify_info(reason, sizeof(reason), " ",
2077 csp->server_cert_verification_result);
2080 * Computing total length of message with all certificates inside
2082 message_len = strlen(message_begin) + strlen(message_end)
2083 + strlen(reason) + strlen("</p>") + 1;
2085 cert = &(csp->server_certs_chain);
2086 while (cert->next != NULL)
2088 size_t base64_len = 4 * ((strlen(cert->file_buf) + 2) / 3) + 1;
2090 message_len += strlen(cert->info_buf) + strlen("<pre></pre>\n")
2091 + base64_len + strlen("<a href=\"data:application"
2092 "/x-x509-ca-cert;base64,\">Download certificate</a>");
2097 * Joining all blocks in one long message
2099 char message[message_len];
2100 memset(message, 0, message_len);
2102 strlcpy(message, message_begin, message_len);
2103 strlcat(message, reason , message_len);
2104 strlcat(message, "</p>" , message_len);
2106 cert = &(csp->server_certs_chain);
2107 while (cert->next != NULL)
2110 size_t base64_len = 4 * ((strlen(cert->file_buf) + 2) / 3) + 1; /* +1 for terminating null*/
2111 char base64_buf[base64_len];
2112 memset(base64_buf, 0, base64_len);
2114 /* Encoding certificate into base64 code */
2115 ret = mbedtls_base64_encode((unsigned char*)base64_buf,
2116 base64_len, &olen, (const unsigned char*)cert->file_buf,
2117 strlen(cert->file_buf));
2120 log_error(LOG_LEVEL_ERROR,
2121 "Encoding to base64 failed, buffer is to small");
2124 strlcat(message, "<pre>", message_len);
2125 strlcat(message, cert->info_buf, message_len);
2126 strlcat(message, "</pre>\n", message_len);
2130 strlcat(message, "<a href=\"data:application/x-x509-ca-cert;base64,",
2132 strlcat(message, base64_buf, message_len);
2133 strlcat(message, "\">Download certificate</a>", message_len);
2138 strlcat(message, message_end, message_len);
2141 * Sending final message to client
2143 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
2144 (const unsigned char *)message, strlen(message));
2146 free_certificate_chain(csp);
2150 /*********************************************************************
2152 * Function : ssl_verify_callback
2154 * Description : This is a callback function for certificate verification.
2155 * It's called once for each certificate in the server's
2156 * certificate trusted chain and prepares information about
2157 * the certificate. The information can be used to inform
2158 * the user about invalid certificates.
2161 * 1 : csp_void = Current client state (buffers, headers, etc...)
2162 * 2 : crt = certificate from trusted chain
2163 * 3 : depth = depth in trusted chain
2164 * 4 : flags = certificate flags
2166 * Returns : 0 on success and negative value on error
2168 *********************************************************************/
2169 static int ssl_verify_callback(void *csp_void, mbedtls_x509_crt *crt,
2170 int depth, uint32_t *flags)
2172 struct client_state *csp = (struct client_state *)csp_void;
2173 struct certs_chain *last = &(csp->server_certs_chain);
2178 * Searching for last item in certificates linked list
2180 while (last->next != NULL)
2186 * Preparing next item in linked list for next certificate
2188 last->next = malloc_or_die(sizeof(struct certs_chain));
2189 last->next->next = NULL;
2190 memset(last->next->info_buf, 0, sizeof(last->next->info_buf));
2191 memset(last->next->file_buf, 0, sizeof(last->next->file_buf));
2194 * Saving certificate file into buffer
2196 if ((ret = mbedtls_pem_write_buffer(PEM_BEGIN_CRT, PEM_END_CRT,
2197 crt->raw.p, crt->raw.len, (unsigned char *)last->file_buf,
2198 sizeof(last->file_buf)-1, &olen)) != 0)
2200 char err_buf[ERROR_BUF_SIZE];
2202 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
2203 log_error(LOG_LEVEL_ERROR, "mbedtls_pem_write_buffer() failed: %s",
2210 * Saving certificate information into buffer
2213 char buf[CERT_INFO_BUF_SIZE];
2216 mbedtls_x509_crt_info(buf, sizeof(buf), CERT_INFO_PREFIX, crt);
2217 encoded_text = html_encode(buf);
2218 strlcpy(last->info_buf, encoded_text, sizeof(last->info_buf));
2219 freez(encoded_text);
2226 /*********************************************************************
2228 * Function : free_certificate_chain
2230 * Description : Frees certificates linked list. This linked list is
2231 * used to save information about certificates in
2235 * 1 : csp = Current client state (buffers, headers, etc...)
2239 *********************************************************************/
2240 static void free_certificate_chain(struct client_state *csp)
2242 struct certs_chain *cert = csp->server_certs_chain.next;
2244 /* Cleaning buffers */
2245 memset(csp->server_certs_chain.info_buf, 0,
2246 sizeof(csp->server_certs_chain.info_buf));
2247 memset(csp->server_certs_chain.file_buf, 0,
2248 sizeof(csp->server_certs_chain.file_buf));
2249 csp->server_certs_chain.next = NULL;
2251 /* Freeing memory in whole linked list */
2252 while (cert != NULL)
2254 struct certs_chain *cert_for_free = cert;
2256 freez(cert_for_free);
2261 /*********************************************************************
2263 * Function : file_exists
2265 * Description : Tests if file exists and is readable.
2268 * 1 : path = Path to tested file.
2270 * Returns : 1 => File exists and is readable.
2271 * 0 => File doesn't exist or is not readable.
2273 *********************************************************************/
2274 static int file_exists(const char *path)
2277 if ((f = fopen(path, "r")) != NULL)
2287 /*********************************************************************
2289 * Function : host_to_hash
2291 * Description : Creates MD5 hash from host name. Host name is loaded
2292 * from structure csp and saved again into it.
2295 * 1 : csp = Current client state (buffers, headers, etc...)
2297 * Returns : 1 => Error while creating hash
2298 * 0 => Hash created successfully
2300 *********************************************************************/
2301 static int host_to_hash(struct client_state *csp)
2305 #if !defined(MBEDTLS_MD5_C)
2306 #error mbedTLS needs to be compiled with md5 support
2308 memset(csp->http->hash_of_host, 0, sizeof(csp->http->hash_of_host));
2309 mbedtls_md5((unsigned char *)csp->http->host, strlen(csp->http->host),
2310 csp->http->hash_of_host);
2312 /* Converting hash into string with hex */
2316 if ((ret = sprintf((char *)csp->http->hash_of_host_hex + 2 * i, "%02x",
2317 csp->http->hash_of_host[i])) < 0)
2319 log_error(LOG_LEVEL_ERROR, "Sprintf return value: %d", ret);
2325 #endif /* MBEDTLS_MD5_C */
2329 /*********************************************************************
2331 * Function : tunnel_established_successfully
2333 * Description : Check if parent proxy server response contains
2334 * information about successfully created connection with
2335 * destination server. (HTTP/... 2xx ...)
2338 * 1 : server_response = Buffer with parent proxy server response
2339 * 2 : response_len = Length of server_response
2341 * Returns : 1 => Connection created successfully
2342 * 0 => Connection wasn't created successfully
2344 *********************************************************************/
2345 extern int tunnel_established_successfully(const char *server_response,
2346 unsigned int response_len)
2348 unsigned int pos = 0;
2350 if (server_response == NULL)
2355 /* Tests if "HTTP/" string is at the begin of received response */
2356 if (strncmp(server_response, "HTTP/", 5) != 0)
2361 for (pos = 0; pos < response_len; pos++)
2363 if (server_response[pos] == ' ')
2370 * response_len -3 because of buffer end, response structure and 200 code.
2371 * There must be at least 3 chars after space.
2372 * End of buffer: ... 2xx'\0'
2375 if (pos >= (response_len - 3))
2380 /* Test HTTP status code */
2381 if (server_response[pos + 1] != '2')
2390 /*********************************************************************
2392 * Function : seed_rng
2394 * Description : Seeding the RNG for all SSL uses
2397 * 1 : csp = Current client state (buffers, headers, etc...)
2399 * Returns : -1 => RNG wasn't seed successfully
2400 * 0 => RNG is seeded successfully
2402 *********************************************************************/
2403 static int seed_rng(struct client_state *csp)
2406 char err_buf[ERROR_BUF_SIZE];
2408 if (rng_seeded == 0)
2410 privoxy_mutex_lock(&rng_mutex);
2411 if (rng_seeded == 0)
2413 mbedtls_ctr_drbg_init(&ctr_drbg);
2414 mbedtls_entropy_init(&entropy);
2415 ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func,
2419 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
2420 log_error(LOG_LEVEL_ERROR,
2421 "mbedtls_ctr_drbg_seed failed: %s", err_buf);
2422 privoxy_mutex_unlock(&rng_mutex);
2427 privoxy_mutex_unlock(&rng_mutex);