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-2019 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"
54 * Macros for searching begin and end of certificates.
55 * Necessary to convert structure mbedtls_x509_crt to crt file.
57 #define PEM_BEGIN_CRT "-----BEGIN CERTIFICATE-----\n"
58 #define PEM_END_CRT "-----END CERTIFICATE-----\n"
63 #define ERROR_BUF_SIZE 1024 /* Size of buffer for error messages */
64 #define CERTIFICATE_BUF_SIZE 16384 /* Size of buffer to save certificate. Value 4096 is mbedtls library buffer size for certificate in DER form */
65 #define PRIVATE_KEY_BUF_SIZE 16000 /* Size of buffer to save private key. Value 16000 is taken from mbed TLS library examples. */
66 #define RSA_KEY_PUBLIC_EXPONENT 65537 /* Public exponent for RSA private key generating */
67 #define RSA_KEYSIZE 2048 /* Size of generated RSA keys */
68 #define GENERATED_CERT_VALID_FROM "20100101000000" /* Date and time, which will be set in generated certificates as parameter valid from */
69 #define GENERATED_CERT_VALID_TO "20401231235959" /* Date and time, which will be setted in generated certificates as parameter valid to */
70 #define CERT_SIGNATURE_ALGORITHM MBEDTLS_MD_SHA256 /* The MD algorithm to use for the signature */
71 #define CERT_SERIAL_NUM_LENGTH 4 /* Bytes of hash to be used for creating serial number of certificate. Min=2 and max=16 */
72 #define LIMIT_MUTEX_NUMBER /* If this macro is defined, mutexes count for generating private keys is changed from 65536 to 32 */
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 extern int generate_webpage_certificate(struct client_state * csp);
85 static char * make_certs_path(const char * conf_dir, const char * file_name, const char * suffix);
86 static int file_exists(const char * path);
87 static int host_to_hash(struct client_state *csp);
88 static int ssl_verify_callback(void *data, mbedtls_x509_crt *crt, int depth, uint32_t *flags);
89 static void free_certificate_chain(struct client_state *csp);
90 static unsigned int get_certificate_mutex_id(struct client_state *csp);
91 static unsigned long get_certificate_serial(struct client_state *csp);
92 static void free_client_ssl_structures(struct client_state *csp);
93 static void free_server_ssl_structures(struct client_state *csp);
94 static int seed_rng(struct client_state *csp);
96 /*********************************************************************
98 * Function : client_use_ssl
100 * Description : Tests if client in current client state structure
101 * should use SSL connection or standard connection.
104 * 1 : csp = Current client state (buffers, headers, etc...)
106 * Returns : If client should use TLS/SSL connection, 1 is returned.
107 * Otherwise 0 is returned.
109 *********************************************************************/
110 extern int client_use_ssl(const struct client_state *csp)
112 return csp->http->client_ssl;
116 /*********************************************************************
118 * Function : server_use_ssl
120 * Description : Tests if server in current client state structure
121 * should use SSL connection or standard connection.
124 * 1 : csp = Current client state (buffers, headers, etc...)
126 * Returns : If server should use TLS/SSL connection, 1 is returned.
127 * Otherwise 0 is returned.
129 *********************************************************************/
130 extern int server_use_ssl(const struct client_state *csp)
132 return csp->http->server_ssl;
136 /*********************************************************************
138 * Function : is_ssl_pending
140 * Description : Tests if there are some waitting data on ssl connection
143 * 1 : ssl = SSL context to test
145 * Returns : 0 => No data are pending
146 * >0 => Pending data length
148 *********************************************************************/
149 extern size_t is_ssl_pending(mbedtls_ssl_context *ssl)
156 return mbedtls_ssl_get_bytes_avail(ssl);
160 /*********************************************************************
162 * Function : ssl_send_data
164 * Description : Sends the content of buf (for n bytes) to given SSL
165 * connection context.
168 * 1 : ssl = SSL context to send data to
169 * 2 : buf = Pointer to data to be sent
170 * 3 : len = Length of data to be sent to the SSL context
172 * Returns : Length of sent data or negative value on error.
174 *********************************************************************/
175 extern int ssl_send_data(mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len)
178 size_t max_fragment_size = 0; /* Maximal length of data in one SSL fragment*/
179 int send_len = 0; /* length of one data part to send */
180 int pos = 0; /* Position of unsent part in buffer */
187 /* Getting maximal length of data sent in one fragment */
188 max_fragment_size = mbedtls_ssl_get_max_frag_len(ssl);
191 * Whole buffer must be sent in many fragments, because each fragment
192 * has its maximal length.
196 /* Compute length of data, that can be send in next fragment */
197 if ((pos + (int)max_fragment_size) > len)
199 send_len = (int)len - pos;
203 send_len = (int)max_fragment_size;
207 * Sending one part of the buffer
209 while ((ret = mbedtls_ssl_write(ssl,
210 (const unsigned char *)(buf + pos),
211 (size_t)send_len)) < 0)
213 if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
214 ret != MBEDTLS_ERR_SSL_WANT_WRITE)
216 char err_buf[ERROR_BUF_SIZE];
218 memset(err_buf, 0, sizeof(err_buf));
219 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
220 log_error(LOG_LEVEL_ERROR,
221 "Sending data over TLS/SSL failed: %s", err_buf);
225 /* Adding count of sent bytes to position in buffer */
226 pos = pos + send_len;
233 /*********************************************************************
235 * Function : ssl_recv_data
237 * Description : Receives data from given SSL context and puts
241 * 1 : ssl = SSL context to receive data from
242 * 2 : buf = Pointer to buffer where data will be written
243 * 3 : max_length = Maximum number of bytes to read
245 * Returns : Number of bytes read, 0 for EOF, or negative
248 *********************************************************************/
249 extern int ssl_recv_data(mbedtls_ssl_context *ssl, unsigned char *buf, size_t max_length)
252 memset(buf, 0, max_length);
255 * Receiving data from SSL context into buffer
259 ret = mbedtls_ssl_read(ssl, buf, max_length);
260 } while (ret == MBEDTLS_ERR_SSL_WANT_READ
261 || ret == MBEDTLS_ERR_SSL_WANT_WRITE);
265 char err_buf[ERROR_BUF_SIZE];
267 memset(err_buf, 0, sizeof(err_buf));
268 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
269 log_error(LOG_LEVEL_ERROR,
270 "Receiving data over TLS/SSL failed: %s", err_buf);
277 /*********************************************************************
279 * Function : ssl_flush_socket
281 * Description : Send any pending "buffered" content with given
282 * SSL connection. Alternative to function flush_socket.
285 * 1 : ssl = SSL context to send buffer to
286 * 2 : iob = The I/O buffer to flush, usually csp->iob.
288 * Returns : On success, the number of bytes send are returned (zero
289 * indicates nothing was sent). On error, -1 is returned.
291 *********************************************************************/
292 extern long ssl_flush_socket(mbedtls_ssl_context *ssl, struct iob *iob)
294 /* Computing length of buffer part to send */
295 long len = iob->eod - iob->cur;
302 /* Sending data to given SSl context */
303 if (ssl_send_data(ssl, (const unsigned char *)iob->cur, (size_t)len) < 0)
307 iob->eod = iob->cur = iob->buf;
312 /*********************************************************************
314 * Function : ssl_debug_callback
316 * Description : Debug callback function for mbedtls library.
317 * Prints info into log file.
320 * 1 : ctx = File to save log in
321 * 2 : level = Debug level
322 * 3 : file = File calling debug message
323 * 4 : line = Line calling debug message
324 * 5 : str = Debug message
328 *********************************************************************/
329 static void ssl_debug_callback(void *ctx, int level, const char *file, int line, const char *str)
333 fprintf((FILE *)ctx, "%s:%04d: %s", file, line, str);
335 log_error(LOG_LEVEL_INFO, "SSL debug message: %s:%04d: %s", file, line, str);
340 /*********************************************************************
342 * Function : create_client_ssl_connection
344 * Description : Creates TLS/SSL secured connection with client
347 * 1 : csp = Current client state (buffers, headers, etc...)
349 * Returns : 0 on success, negative value if connection wasn't created
352 *********************************************************************/
353 extern int create_client_ssl_connection(struct client_state *csp)
355 /* Paths to certificates file and key file */
356 char *key_file = NULL;
357 char *ca_file = NULL;
358 char *cert_file = NULL;
360 char err_buf[ERROR_BUF_SIZE];
362 memset(err_buf, 0, sizeof(err_buf));
365 * Initializing mbedtls structures for TLS/SSL connection
367 mbedtls_net_init(&(csp->mbedtls_client_attr.socket_fd));
368 mbedtls_ssl_init(&(csp->mbedtls_client_attr.ssl));
369 mbedtls_ssl_config_init(&(csp->mbedtls_client_attr.conf));
370 mbedtls_x509_crt_init(&(csp->mbedtls_client_attr.server_cert));
371 mbedtls_pk_init(&(csp->mbedtls_client_attr.prim_key));
372 #if defined(MBEDTLS_SSL_CACHE_C)
373 mbedtls_ssl_cache_init(&(csp->mbedtls_client_attr.cache));
377 * Preparing hash of host for creating certificates
379 ret = host_to_hash(csp);
382 log_error(LOG_LEVEL_ERROR, "Generating hash of host failed: %d", ret);
388 * Preparing paths to certificates files and key file
390 ca_file = csp->config->ca_cert_file;
391 cert_file = make_certs_path(csp->config->certificate_directory,
392 (const char *)csp->http->hash_of_host_hex, CERT_FILE_TYPE);
393 key_file = make_certs_path(csp->config->certificate_directory,
394 (const char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
396 if (cert_file == NULL || key_file == NULL)
403 * Generating certificate for requested host. Mutex to prevent
404 * certificate and key inconsistence must be locked.
406 unsigned int cert_mutex_id = get_certificate_mutex_id(csp);
407 privoxy_mutex_lock(&(certificates_mutexes[cert_mutex_id]));
409 ret = generate_webpage_certificate(csp);
412 log_error(LOG_LEVEL_ERROR,
413 "Generate_webpage_certificate failed: %d", ret);
414 privoxy_mutex_unlock(&(certificates_mutexes[cert_mutex_id]));
418 privoxy_mutex_unlock(&(certificates_mutexes[cert_mutex_id]));
431 * Loading CA file, webpage certificate and key files
433 ret = mbedtls_x509_crt_parse_file(&(csp->mbedtls_client_attr.server_cert),
437 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
438 log_error(LOG_LEVEL_ERROR,
439 "Loading webpage certificate %s failed: %s", cert_file, err_buf);
444 ret = mbedtls_x509_crt_parse_file(&(csp->mbedtls_client_attr.server_cert),
448 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
449 log_error(LOG_LEVEL_ERROR,
450 "Loading CA certificate %s failed: %s", ca_file, err_buf);
455 ret = mbedtls_pk_parse_keyfile(&(csp->mbedtls_client_attr.prim_key),
459 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
460 log_error(LOG_LEVEL_ERROR,
461 "Loading and parsing webpage certificate private key %s failed: %s",
468 * Setting SSL parameters
470 ret = mbedtls_ssl_config_defaults(&(csp->mbedtls_client_attr.conf),
471 MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_TRANSPORT_STREAM,
472 MBEDTLS_SSL_PRESET_DEFAULT);
475 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
476 log_error(LOG_LEVEL_ERROR,
477 "mbedtls_ssl_config_defaults failed: %s", err_buf);
482 mbedtls_ssl_conf_rng(&(csp->mbedtls_client_attr.conf),
483 mbedtls_ctr_drbg_random, &ctr_drbg);
484 mbedtls_ssl_conf_dbg(&(csp->mbedtls_client_attr.conf),
485 ssl_debug_callback, stdout);
487 #if defined(MBEDTLS_SSL_CACHE_C)
488 mbedtls_ssl_conf_session_cache(&(csp->mbedtls_client_attr.conf),
489 &(csp->mbedtls_client_attr.cache), mbedtls_ssl_cache_get,
490 mbedtls_ssl_cache_set);
494 * Setting certificates
496 ret = mbedtls_ssl_conf_own_cert(&(csp->mbedtls_client_attr.conf),
497 &(csp->mbedtls_client_attr.server_cert),
498 &(csp->mbedtls_client_attr.prim_key));
501 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
502 log_error(LOG_LEVEL_ERROR,
503 "mbedtls_ssl_conf_own_cert failed: %s", err_buf);
508 ret = mbedtls_ssl_setup(&(csp->mbedtls_client_attr.ssl),
509 &(csp->mbedtls_client_attr.conf));
512 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
513 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_setup failed: %s", err_buf);
518 mbedtls_ssl_set_bio(&(csp->mbedtls_client_attr.ssl),
519 &(csp->mbedtls_client_attr.socket_fd), mbedtls_net_send,
520 mbedtls_net_recv, NULL);
521 mbedtls_ssl_session_reset(&(csp->mbedtls_client_attr.ssl));
524 * Setting socket fd in mbedtls_net_context structure. This structure
525 * can't be set by mbedtls functions, because we already have created
526 * a TCP connection when this function is called.
528 csp->mbedtls_client_attr.socket_fd.fd = csp->cfd;
531 * Handshake with client
533 log_error(LOG_LEVEL_CONNECT,
534 "Performing the TLS/SSL handshake with client. Hash of host: %s",
535 csp->http->hash_of_host_hex);
536 while ((ret = mbedtls_ssl_handshake(&(csp->mbedtls_client_attr.ssl))) != 0)
538 if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
539 ret != MBEDTLS_ERR_SSL_WANT_WRITE)
541 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
542 log_error(LOG_LEVEL_ERROR,
543 "medtls_ssl_handshake with client failed: %s", err_buf);
549 log_error(LOG_LEVEL_CONNECT, "Client successfully connected over TLS/SSL");
550 csp->ssl_with_client_is_opened = 1;
554 * Freeing allocated paths to files
559 /* Freeing structures if connection wasn't created successfully */
562 free_client_ssl_structures(csp);
568 /*********************************************************************
570 * Function : close_client_ssl_connection
572 * Description : Closes TLS/SSL connection with client. This function
573 * checks if this connection is already created.
576 * 1 : csp = Current client state (buffers, headers, etc...)
580 *********************************************************************/
581 extern void close_client_ssl_connection(struct client_state *csp)
585 if (csp->ssl_with_client_is_opened == 0)
591 * Notifying the peer that the connection is being closed.
594 ret = mbedtls_ssl_close_notify(&(csp->mbedtls_client_attr.ssl));
595 } while (ret == MBEDTLS_ERR_SSL_WANT_WRITE);
597 free_client_ssl_structures(csp);
598 csp->ssl_with_client_is_opened = 0;
602 /*********************************************************************
604 * Function : free_client_ssl_structures
606 * Description : Frees structures used for SSL communication with
610 * 1 : csp = Current client state (buffers, headers, etc...)
614 *********************************************************************/
615 static void free_client_ssl_structures(struct client_state *csp)
618 * We can't use function mbedtls_net_free, because this function
619 * inter alia close TCP connection on setted fd. Instead of this
620 * function, we change fd to -1, which is the same what does
621 * rest of mbedtls_net_free function.
623 csp->mbedtls_client_attr.socket_fd.fd = -1;
625 /* Freeing mbedtls structures */
626 mbedtls_x509_crt_free(&(csp->mbedtls_client_attr.server_cert));
627 mbedtls_pk_free(&(csp->mbedtls_client_attr.prim_key));
628 mbedtls_ssl_free(&(csp->mbedtls_client_attr.ssl));
629 mbedtls_ssl_config_free(&(csp->mbedtls_client_attr.conf));
630 #if defined(MBEDTLS_SSL_CACHE_C)
631 mbedtls_ssl_cache_free(&(csp->mbedtls_client_attr.cache));
636 /*********************************************************************
638 * Function : create_server_ssl_connection
640 * Description : Creates TLS/SSL secured connection with server.
643 * 1 : csp = Current client state (buffers, headers, etc...)
645 * Returns : 0 on success, negative value if connection wasn't created
648 *********************************************************************/
649 extern int create_server_ssl_connection(struct client_state *csp)
652 char err_buf[ERROR_BUF_SIZE];
653 char *trusted_cas_file = NULL;
654 int auth_mode = MBEDTLS_SSL_VERIFY_REQUIRED;
656 memset(err_buf, 0, sizeof(err_buf));
658 csp->server_cert_verification_result = SSL_CERT_NOT_VERIFIED;
659 csp->server_certs_chain.next = NULL;
661 /* Setting path to file with trusted CAs */
662 trusted_cas_file = csp->config->trusted_cas_file;
665 * Initializing mbedtls structures for TLS/SSL connection
667 mbedtls_net_init(&(csp->mbedtls_server_attr.socket_fd));
668 mbedtls_ssl_init(&(csp->mbedtls_server_attr.ssl));
669 mbedtls_ssl_config_init(&(csp->mbedtls_server_attr.conf));
670 mbedtls_x509_crt_init( &(csp->mbedtls_server_attr.ca_cert));
673 * Setting socket fd in mbedtls_net_context structure. This structure
674 * can't be set by mbedtls functions, because we already have created
675 * TCP connection when calling this function.
677 csp->mbedtls_server_attr.socket_fd.fd = csp->server_connection.sfd;
690 * Loading file with trusted CAs
692 ret = mbedtls_x509_crt_parse_file(&(csp->mbedtls_server_attr.ca_cert),
696 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
697 log_error(LOG_LEVEL_ERROR, "Loading trusted CAs file %s failed: %s",
698 trusted_cas_file, err_buf);
704 * Set TLS/SSL options
706 ret = mbedtls_ssl_config_defaults(&(csp->mbedtls_server_attr.conf),
707 MBEDTLS_SSL_IS_CLIENT,
708 MBEDTLS_SSL_TRANSPORT_STREAM,
709 MBEDTLS_SSL_PRESET_DEFAULT);
712 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
713 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_config_defaults failed: %s",
720 * Setting how strict should certificate verification be and other
721 * parameters for certificate verification
723 if (csp->dont_verify_certificate)
725 auth_mode = MBEDTLS_SSL_VERIFY_NONE;
728 mbedtls_ssl_conf_authmode(&(csp->mbedtls_server_attr.conf), auth_mode);
729 mbedtls_ssl_conf_ca_chain(&(csp->mbedtls_server_attr.conf),
730 &(csp->mbedtls_server_attr.ca_cert), NULL);
732 /* Setting callback function for certificates verification */
733 mbedtls_ssl_conf_verify(&(csp->mbedtls_server_attr.conf),
734 ssl_verify_callback, (void *)csp);
736 mbedtls_ssl_conf_rng(&(csp->mbedtls_server_attr.conf),
737 mbedtls_ctr_drbg_random, &ctr_drbg);
738 mbedtls_ssl_conf_dbg(&(csp->mbedtls_server_attr.conf),
739 ssl_debug_callback, stdout);
741 ret = mbedtls_ssl_setup(&(csp->mbedtls_server_attr.ssl),
742 &(csp->mbedtls_server_attr.conf));
745 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
746 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_setup failed: %s", err_buf);
752 * Set the hostname to check against the received server certificate
754 ret = mbedtls_ssl_set_hostname(&(csp->mbedtls_server_attr.ssl),
758 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
759 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_set_hostname failed: %s",
765 mbedtls_ssl_set_bio(&(csp->mbedtls_server_attr.ssl),
766 &(csp->mbedtls_server_attr.socket_fd), mbedtls_net_send,
767 mbedtls_net_recv, NULL);
770 * Handshake with server
772 log_error(LOG_LEVEL_CONNECT,
773 "Performing the TLS/SSL handshake with server");
775 while ((ret = mbedtls_ssl_handshake(&(csp->mbedtls_server_attr.ssl))) != 0)
777 if (ret != MBEDTLS_ERR_SSL_WANT_READ
778 && ret != MBEDTLS_ERR_SSL_WANT_WRITE)
780 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
782 if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED)
784 log_error(LOG_LEVEL_ERROR,
785 "Server certificate verification failed: %s", err_buf);
786 csp->server_cert_verification_result =
787 mbedtls_ssl_get_verify_result(&(csp->mbedtls_server_attr.ssl));
793 log_error(LOG_LEVEL_ERROR,
794 "mbedtls_ssl_handshake with server failed: %s", err_buf);
801 log_error(LOG_LEVEL_CONNECT, "Server successfully connected over TLS/SSL");
804 * Server certificate chain is valid, so we can clean
805 * chain, because we will not send it to client.
807 free_certificate_chain(csp);
809 csp->ssl_with_server_is_opened = 1;
810 csp->server_cert_verification_result =
811 mbedtls_ssl_get_verify_result(&(csp->mbedtls_server_attr.ssl));
814 /* Freeing structures if connection wasn't created successfully */
817 free_server_ssl_structures(csp);
824 /*********************************************************************
826 * Function : close_server_ssl_connection
828 * Description : Closes TLS/SSL connection with server. This function
829 * checks if this connection is already opened.
832 * 1 : csp = Current client state (buffers, headers, etc...)
836 *********************************************************************/
837 static void close_server_ssl_connection(struct client_state *csp)
841 if (csp->ssl_with_server_is_opened == 0)
847 * Notifying the peer that the connection is being closed.
850 ret = mbedtls_ssl_close_notify(&(csp->mbedtls_server_attr.ssl));
851 } while (ret == MBEDTLS_ERR_SSL_WANT_WRITE);
853 free_server_ssl_structures(csp);
854 csp->ssl_with_server_is_opened = 0;
858 /*********************************************************************
860 * Function : free_server_ssl_structures
862 * Description : Frees structures used for SSL communication with server
865 * 1 : csp = Current client state (buffers, headers, etc...)
869 *********************************************************************/
870 static void free_server_ssl_structures(struct client_state *csp)
873 * We can't use function mbedtls_net_free, because this function
874 * inter alia close TCP connection on setted fd. Instead of this
875 * function, we change fd to -1, which is the same what does
876 * rest of mbedtls_net_free function.
878 csp->mbedtls_client_attr.socket_fd.fd = -1;
880 mbedtls_x509_crt_free(&(csp->mbedtls_server_attr.ca_cert));
881 mbedtls_ssl_free(&(csp->mbedtls_server_attr.ssl));
882 mbedtls_ssl_config_free(&(csp->mbedtls_server_attr.conf));
886 /*********************************************************************
888 * Function : close_client_and_server_ssl_connections
890 * Description : Checks if client or server should use secured
891 * connection over SSL and if so, closes all of them.
894 * 1 : csp = Current client state (buffers, headers, etc...)
898 *********************************************************************/
899 extern void close_client_and_server_ssl_connections(struct client_state *csp)
901 if (client_use_ssl(csp) == 1)
903 close_client_ssl_connection(csp);
905 if (server_use_ssl(csp) == 1)
907 close_server_ssl_connection(csp);
911 /*====================== Certificates ======================*/
913 /*********************************************************************
915 * Function : write_certificate
917 * Description : Writes certificate into file.
920 * 1 : crt = certificate to write into file
921 * 2 : output_file = path to save certificate file
922 * 3 : f_rng = mbedtls_ctr_drbg_random
923 * 4 : p_rng = mbedtls_ctr_drbg_context
925 * Returns : Length of written certificate on success or negative value
928 *********************************************************************/
929 static int write_certificate(mbedtls_x509write_cert *crt, const char *output_file,
930 int(*f_rng)(void *, unsigned char *, size_t), void *p_rng)
934 unsigned char cert_buf[CERTIFICATE_BUF_SIZE + 1]; /* Buffer for certificate in PEM format + terminating NULL */
936 char err_buf[ERROR_BUF_SIZE];
938 memset(err_buf, 0, sizeof(err_buf));
939 memset(cert_buf, 0, sizeof(cert_buf));
942 * Writing certificate into PEM string. If buffer is too small, fuction
943 * returns specific error and no buffer overflow can happen.
945 if ((ret = mbedtls_x509write_crt_pem(crt, cert_buf,
946 sizeof(cert_buf) - 1, f_rng, p_rng)) != 0)
948 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
949 log_error(LOG_LEVEL_ERROR,
950 "Writing certificate into buffer failed: %s", err_buf);
954 len = strlen((char *)cert_buf);
957 * Saving certificate into file
959 if ((f = fopen(output_file, "w")) == NULL)
961 log_error(LOG_LEVEL_ERROR, "Opening file %s to save certificate failed",
966 if (fwrite(cert_buf, 1, len, f) != len)
968 log_error(LOG_LEVEL_ERROR,
969 "Writing certificate into file %s failed", output_file);
980 /*********************************************************************
982 * Function : write_private_key
984 * Description : Writes private key into file and copies saved
985 * content into given pointer to string. If function
986 * returns 0 for success, this copy must be freed by
990 * 1 : key = key to write into file
991 * 2 : ret_buf = pointer to string with created key file content
992 * 3 : key_file_path = path where to save key file
994 * Returns : Length of written private key on success or negative value
997 *********************************************************************/
998 static int write_private_key(mbedtls_pk_context *key, unsigned char **ret_buf,
999 const char *key_file_path)
1001 size_t len = 0; /* Length of created key */
1002 FILE *f = NULL; /* File to save certificate */
1004 char err_buf[ERROR_BUF_SIZE];
1006 memset(err_buf, 0, sizeof(err_buf));
1008 /* Initializing buffer for key file content */
1009 *ret_buf = (unsigned char *)malloc(PRIVATE_KEY_BUF_SIZE + 1);
1010 if (*ret_buf == NULL)
1012 log_error(LOG_LEVEL_ERROR,
1013 "Creating buffer for private key failed: malloc fail");
1017 memset(*ret_buf, 0, PRIVATE_KEY_BUF_SIZE + 1);
1020 * Writing private key into PEM string
1022 if ((ret = mbedtls_pk_write_key_pem(key, *ret_buf, PRIVATE_KEY_BUF_SIZE)) != 0)
1024 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1025 log_error(LOG_LEVEL_ERROR,
1026 "Writing private key into PEM string failed: %s", err_buf);
1030 len = strlen((char *)*ret_buf);
1033 * Saving key into file
1035 if ((f = fopen(key_file_path, "wb")) == NULL)
1037 log_error(LOG_LEVEL_ERROR,
1038 "Opening file %s to save private key failed: %E",
1044 if (fwrite(*ret_buf, 1, len, f) != len)
1047 log_error(LOG_LEVEL_ERROR,
1048 "Writing private key into file %s failed",
1067 /*********************************************************************
1069 * Function : generate_key
1071 * Description : Tests if private key for host saved in csp already
1072 * exists. If this file doesn't exists, a new key is
1073 * generated and saved in a file. The generated key is also
1074 * copied into given parameter key_buf, which must be then
1075 * freed by caller. If file with key exists, key_buf
1076 * contain NULL and no private key is generated.
1079 * 1 : key_buf = buffer to save new generated key
1080 * 2 : csp = Current client state (buffers, headers, etc...)
1082 * Returns : -1 => Error while generating private key
1083 * 0 => Key already exists
1084 * >0 => Length of generated private key
1086 *********************************************************************/
1087 static int generate_key(unsigned char **key_buf, struct client_state *csp)
1089 mbedtls_pk_context key;
1090 key_options key_opt;
1092 char err_buf[ERROR_BUF_SIZE];
1094 key_opt.key_file_path = NULL;
1095 memset(err_buf, 0, sizeof(err_buf));
1098 * Initializing structures for key generating
1100 mbedtls_pk_init(&key);
1103 * Preparing path for key file and other properties for generating key
1105 key_opt.type = MBEDTLS_PK_RSA;
1106 key_opt.rsa_keysize = RSA_KEYSIZE;
1108 key_opt.key_file_path = make_certs_path(csp->config->certificate_directory,
1109 (char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
1110 if (key_opt.key_file_path == NULL)
1117 * Test if key already exists. If so, we don't have to create it again.
1119 if (file_exists(key_opt.key_file_path) == 1)
1128 ret = seed_rng(csp);
1136 * Setting attributes of private key and generating it
1138 if ((ret = mbedtls_pk_setup(&key,
1139 mbedtls_pk_info_from_type(key_opt.type))) != 0)
1141 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1142 log_error(LOG_LEVEL_ERROR, "mbedtls_pk_setup failed: %s", err_buf);
1147 ret = mbedtls_rsa_gen_key(mbedtls_pk_rsa(key), mbedtls_ctr_drbg_random,
1148 &ctr_drbg, (unsigned)key_opt.rsa_keysize, RSA_KEY_PUBLIC_EXPONENT);
1151 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1152 log_error(LOG_LEVEL_ERROR, "Key generating failed: %s", err_buf);
1158 * Exporting private key into file
1160 if ((ret = write_private_key(&key, key_buf, key_opt.key_file_path)) < 0)
1162 log_error(LOG_LEVEL_ERROR,
1163 "Writing private key into file %s failed", key_opt.key_file_path);
1170 * Freeing used variables
1172 freez(key_opt.key_file_path);
1174 mbedtls_pk_free(&key);
1180 /*********************************************************************
1182 * Function : generate_webpage_certificate
1184 * Description : Creates certificate file in presetted directory.
1185 * If certificate already exists, no other certificate
1186 * will be created. Subject of certificate is named
1187 * by csp->http->host from parameter. This function also
1188 * triggers generating of private key for new certificate.
1191 * 1 : csp = Current client state (buffers, headers, etc...)
1193 * Returns : -1 => Error while creating certificate.
1194 * 0 => Certificate alreaday exist.
1195 * >0 => Length of created certificate.
1197 *********************************************************************/
1198 extern int generate_webpage_certificate(struct client_state * csp)
1200 mbedtls_x509_crt issuer_cert;
1201 mbedtls_pk_context loaded_issuer_key, loaded_subject_key;
1202 mbedtls_pk_context *issuer_key = &loaded_issuer_key;
1203 mbedtls_pk_context *subject_key = &loaded_subject_key;
1204 mbedtls_x509write_cert cert;
1207 unsigned char *key_buf = NULL; /* Buffer for created key */
1210 char err_buf[ERROR_BUF_SIZE];
1211 cert_options cert_opt;
1213 memset(err_buf, 0, sizeof(err_buf));
1215 /* Paths to keys and certificates needed to create certificate */
1216 cert_opt.issuer_key = NULL;
1217 cert_opt.subject_key = NULL;
1218 cert_opt.issuer_crt = NULL;
1219 cert_opt.output_file = NULL;
1222 * Create key for requested host
1224 int subject_key_len = generate_key(&key_buf, csp);
1225 if (subject_key_len < 0)
1227 log_error(LOG_LEVEL_ERROR, "Key generating failed");
1232 * Initializing structures for certificate generating
1234 mbedtls_x509write_crt_init(&cert);
1235 mbedtls_x509write_crt_set_md_alg( &cert, CERT_SIGNATURE_ALGORITHM);
1236 mbedtls_pk_init(&loaded_issuer_key);
1237 mbedtls_pk_init(&loaded_subject_key);
1238 mbedtls_mpi_init(&serial);
1239 mbedtls_x509_crt_init(&issuer_cert);
1242 * Presetting parameters for certificate. We must compute total length
1245 size_t cert_params_len = strlen(CERT_PARAM_COMMON_NAME) +
1246 strlen(CERT_PARAM_ORGANIZATION) + strlen(CERT_PARAM_COUNTRY) +
1247 strlen(CERT_PARAM_ORG_UNIT) +
1248 3 * strlen(csp->http->host) + 1;
1249 char cert_params[cert_params_len];
1250 memset(cert_params, 0, cert_params_len);
1253 * Converting unsigned long serial number to char * serial number.
1254 * We must compute length of serial number in string + terminating null.
1256 unsigned long certificate_serial = get_certificate_serial(csp);
1257 int serial_num_size = snprintf(NULL, 0, "%lu", certificate_serial) + 1;
1258 if (serial_num_size <= 0)
1260 serial_num_size = 1;
1263 char serial_num_text[serial_num_size]; /* Buffer for serial number */
1264 ret = snprintf(serial_num_text, (size_t)serial_num_size, "%lu", certificate_serial);
1265 if (ret < 0 || ret >= serial_num_size)
1267 log_error(LOG_LEVEL_ERROR,
1268 "Converting certificate serial number into string failed");
1274 * Preparing parameters for certificate
1276 strlcpy(cert_params, CERT_PARAM_COMMON_NAME, cert_params_len);
1277 strlcat(cert_params, csp->http->host, cert_params_len);
1278 strlcat(cert_params, CERT_PARAM_ORGANIZATION, cert_params_len);
1279 strlcat(cert_params, csp->http->host, cert_params_len);
1280 strlcat(cert_params, CERT_PARAM_ORG_UNIT, cert_params_len);
1281 strlcat(cert_params, csp->http->host, cert_params_len);
1282 strlcat(cert_params, CERT_PARAM_COUNTRY, cert_params_len);
1284 cert_opt.issuer_crt = csp->config->ca_cert_file;
1285 cert_opt.issuer_key = csp->config->ca_key_file;
1286 cert_opt.subject_key = make_certs_path(csp->config->certificate_directory,
1287 (const char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
1288 cert_opt.output_file = make_certs_path(csp->config->certificate_directory,
1289 (const char *)csp->http->hash_of_host_hex, CERT_FILE_TYPE);
1291 if (cert_opt.subject_key == NULL || cert_opt.output_file == NULL)
1297 cert_opt.subject_pwd = CERT_SUBJECT_PASSWORD;
1298 cert_opt.issuer_pwd = csp->config->ca_password;
1299 cert_opt.subject_name = cert_params;
1300 cert_opt.not_before = GENERATED_CERT_VALID_FROM;
1301 cert_opt.not_after = GENERATED_CERT_VALID_TO;
1302 cert_opt.serial = serial_num_text;
1304 cert_opt.max_pathlen = -1;
1307 * Test if certificate exists and private key was already created
1309 if (file_exists(cert_opt.output_file) == 1 && subject_key_len == 0)
1318 ret = seed_rng(csp);
1326 * Parse serial to MPI
1328 ret = mbedtls_mpi_read_string(&serial, 10, cert_opt.serial);
1331 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1332 log_error(LOG_LEVEL_ERROR,
1333 "mbedtls_mpi_read_string failed: %s", err_buf);
1339 * Loading certificates
1341 ret = mbedtls_x509_crt_parse_file(&issuer_cert, cert_opt.issuer_crt);
1344 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1345 log_error(LOG_LEVEL_ERROR, "Loading issuer certificate %s failed: %s",
1346 cert_opt.issuer_crt, err_buf);
1351 ret = mbedtls_x509_dn_gets(cert_opt.issuer_name,
1352 sizeof(cert_opt.issuer_name), &issuer_cert.subject);
1355 mbedtls_strerror( ret, err_buf, sizeof(err_buf));
1356 log_error(LOG_LEVEL_ERROR, "mbedtls_x509_dn_gets failed: %s", err_buf);
1362 * Loading keys from file or from buffer
1364 if (key_buf != NULL && subject_key_len > 0)
1366 /* Key was created in this function and is stored in buffer */
1367 ret = mbedtls_pk_parse_key(&loaded_subject_key, key_buf,
1368 (size_t)(subject_key_len + 1), (unsigned const char *)
1369 cert_opt.subject_pwd, strlen(cert_opt.subject_pwd));
1373 /* Key wasn't created in this function, because it already existed */
1374 ret = mbedtls_pk_parse_keyfile(&loaded_subject_key,
1375 cert_opt.subject_key, cert_opt.subject_pwd);
1380 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1381 log_error(LOG_LEVEL_ERROR, "Parsing subject key %s failed: %s",
1382 cert_opt.subject_key, err_buf);
1387 ret = mbedtls_pk_parse_keyfile(&loaded_issuer_key, cert_opt.issuer_key,
1388 cert_opt.issuer_pwd);
1391 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1392 log_error(LOG_LEVEL_ERROR,
1393 "Parsing issuer key %s failed: %s", cert_opt.issuer_key, err_buf);
1399 * Check if key and issuer certificate match
1401 if (!mbedtls_pk_can_do(&issuer_cert.pk, MBEDTLS_PK_RSA) ||
1402 mbedtls_mpi_cmp_mpi(&mbedtls_pk_rsa(issuer_cert.pk)->N,
1403 &mbedtls_pk_rsa(*issuer_key)->N) != 0 ||
1404 mbedtls_mpi_cmp_mpi( &mbedtls_pk_rsa(issuer_cert.pk)->E,
1405 &mbedtls_pk_rsa(*issuer_key )->E) != 0)
1407 log_error(LOG_LEVEL_ERROR,
1408 "Issuer key doesn't match issuer certificate");
1413 mbedtls_x509write_crt_set_subject_key(&cert, subject_key);
1414 mbedtls_x509write_crt_set_issuer_key(&cert, issuer_key);
1417 * Setting parameters of signed certificate
1419 ret = mbedtls_x509write_crt_set_subject_name(&cert, cert_opt.subject_name);
1422 mbedtls_strerror( ret, err_buf, sizeof(err_buf));
1423 log_error(LOG_LEVEL_ERROR,
1424 "Setting subject name in signed certificate failed: %s", err_buf);
1429 ret = mbedtls_x509write_crt_set_issuer_name(&cert, cert_opt.issuer_name);
1432 mbedtls_strerror( ret, err_buf, sizeof(err_buf));
1433 log_error(LOG_LEVEL_ERROR,
1434 "Setting issuer name in signed certificate failed: %s", err_buf);
1439 ret = mbedtls_x509write_crt_set_serial(&cert, &serial);
1442 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1443 log_error(LOG_LEVEL_ERROR,
1444 "Setting serial number in signed certificate failed: %s", err_buf);
1449 ret = mbedtls_x509write_crt_set_validity(&cert, cert_opt.not_before,
1450 cert_opt.not_after);
1453 mbedtls_strerror( ret, err_buf, sizeof(err_buf));
1454 log_error(LOG_LEVEL_ERROR,
1455 "Setting validity in signed certificate failed: %s", err_buf);
1461 * Setting the basicConstraints extension for certificate
1463 ret = mbedtls_x509write_crt_set_basic_constraints(&cert, cert_opt.is_ca,
1464 cert_opt.max_pathlen);
1467 mbedtls_strerror( ret, err_buf, sizeof(err_buf));
1468 log_error(LOG_LEVEL_ERROR, "Setting the basicConstraints extension "
1469 "in signed certificate failed: %s", err_buf);
1474 #if defined(MBEDTLS_SHA1_C)
1475 /* Setting the subjectKeyIdentifier extension for certificate */
1476 ret = mbedtls_x509write_crt_set_subject_key_identifier(&cert);
1479 mbedtls_strerror( ret, err_buf, sizeof(err_buf));
1480 log_error(LOG_LEVEL_ERROR, "mbedtls_x509write_crt_set_subject_key_"
1481 "identifier failed: %s", err_buf);
1486 /* Setting the authorityKeyIdentifier extension for certificate */
1487 ret = mbedtls_x509write_crt_set_authority_key_identifier(&cert);
1490 mbedtls_strerror( ret, err_buf, sizeof(err_buf));
1491 log_error(LOG_LEVEL_ERROR, "mbedtls_x509write_crt_set_authority_key_"
1492 "identifier failed: %s", err_buf);
1496 #endif /* MBEDTLS_SHA1_C */
1499 * Writing certificate into file
1501 ret = write_certificate(&cert, cert_opt.output_file,
1502 mbedtls_ctr_drbg_random, &ctr_drbg);
1505 log_error(LOG_LEVEL_ERROR, "Writing certificate into file failed");
1511 * Freeing used structures
1513 mbedtls_x509write_crt_free(&cert);
1514 mbedtls_pk_free(&loaded_subject_key);
1515 mbedtls_pk_free(&loaded_issuer_key);
1516 mbedtls_mpi_free(&serial);
1517 mbedtls_x509_crt_free(&issuer_cert);
1519 freez(cert_opt.subject_key);
1520 freez(cert_opt.output_file);
1527 /*********************************************************************
1529 * Function : make_certs_path
1531 * Description : Creates path to file from three pieces. This fuction
1532 * takes parameters and puts them in one new mallocated
1533 * char * in correct order. Returned variable must be freed
1534 * by caller. This function is mainly used for creating
1535 * paths of certificates and keys files.
1538 * 1 : conf_dir = Name/path of directory where is the file.
1539 * '.' can be used for current directory.
1540 * 2 : file_name = Name of file in conf_dir without suffix.
1541 * 3 : suffix = Suffix of given file_name.
1543 * Returns : path => Path was built up successfully
1544 * NULL => Path can't be built up
1546 *********************************************************************/
1547 static char *make_certs_path(const char *conf_dir, const char *file_name,
1550 /* Test if all given parameters are valid */
1551 if (conf_dir == NULL || *conf_dir == '\0' || file_name == NULL ||
1552 *file_name == '\0' || suffix == NULL || *suffix == '\0')
1554 log_error(LOG_LEVEL_ERROR,
1555 "make_certs_path failed: bad input parameters");
1560 size_t path_size = strlen(conf_dir)
1561 + strlen(file_name) + strlen(suffix) + 2;
1563 /* Setting delimiter and editing path length */
1564 #if defined(_WIN32) || defined(__OS2__)
1565 char delim[] = "\\";
1567 #else /* ifndef _WIN32 || __OS2__ */
1569 #endif /* ifndef _WIN32 || __OS2__ */
1572 * Building up path from many parts
1575 if (*conf_dir != '/' && basedir && *basedir)
1578 * Replacing conf_dir with basedir. This new variable contains
1579 * absolute path to cwd.
1581 path_size += strlen(basedir) + 2;
1582 path = (char *)malloc(path_size);
1585 log_error(LOG_LEVEL_ERROR, "make_certs_path failed: malloc fail");
1588 memset(path, 0, path_size);
1590 strlcpy(path, basedir, path_size);
1591 strlcat(path, delim, path_size);
1592 strlcat(path, conf_dir, path_size);
1593 strlcat(path, delim, path_size);
1594 strlcat(path, file_name, path_size);
1595 strlcat(path, suffix, path_size);
1598 #endif /* defined unix */
1600 path = (char *)malloc(path_size);
1603 log_error(LOG_LEVEL_ERROR, "make_certs_path failed: malloc fail");
1606 memset(path, 0, path_size);
1608 strlcpy(path, conf_dir, path_size);
1609 strlcat(path, delim, path_size);
1610 strlcat(path, file_name, path_size);
1611 strlcat(path, suffix, path_size);
1618 /*********************************************************************
1620 * Function : get_certificate_mutex_id
1622 * Description : Computes mutex id from host name hash. This hash must
1623 * be already saved in csp structure
1626 * 1 : csp = Current client state (buffers, headers, etc...)
1628 * Returns : Mutex id for given host name
1630 *********************************************************************/
1631 static unsigned int get_certificate_mutex_id(struct client_state *csp) {
1632 #ifdef LIMIT_MUTEX_NUMBER
1633 return (unsigned int)(csp->http->hash_of_host[0] % 32);
1635 return (unsigned int)(csp->http->hash_of_host[1]
1636 + 256 * (int)csp->http->hash_of_host[0]);
1637 #endif /* LIMIT_MUTEX_NUMBER */
1641 /*********************************************************************
1643 * Function : get_certificate_serial
1645 * Description : Computes serial number for new certificate from host
1646 * name hash. This hash must be already saved in csp
1650 * 1 : csp = Current client state (buffers, headers, etc...)
1652 * Returns : Serial number for new certificate
1654 *********************************************************************/
1655 static unsigned long get_certificate_serial(struct client_state *csp) {
1656 unsigned long exp = 1;
1657 unsigned long serial = 0;
1659 int i = CERT_SERIAL_NUM_LENGTH;
1660 /* Length of hash is 16 bytes, we must avoid to read next chars */
1672 serial += exp * (unsigned)csp->http->hash_of_host[i];
1679 /*********************************************************************
1681 * Function : ssl_send_certificate_error
1683 * Description : Sends info about invalid server certificate to client.
1684 * Sent message is including all trusted chain certificates,
1685 * that can be downloaded in web browser.
1688 * 1 : csp = Current client state (buffers, headers, etc...)
1692 *********************************************************************/
1693 extern void ssl_send_certificate_error(struct client_state *csp)
1695 size_t message_len = 0;
1697 struct certs_chain *cert = NULL;
1699 /* Header of message with certificate informations */
1700 const char message_begin[] =
1701 "HTTP/1.1 200 OK\r\n"
1702 "Content-Type: text/html\r\n"
1703 "Connection: close\r\n\r\n"
1704 "<html><body><h1>Invalid server certificate</h1><p>Reason: ";
1705 const char message_end[] = "</body></html>\r\n\r\n";
1706 char reason[INVALID_CERT_INFO_BUF_SIZE];
1707 memset(reason, 0, sizeof(reason));
1709 /* Get verification message from verification return code */
1710 mbedtls_x509_crt_verify_info(reason, sizeof(reason), " ",
1711 csp->server_cert_verification_result);
1714 * Computing total length of message with all certificates inside
1716 message_len = strlen(message_begin) + strlen(message_end)
1717 + strlen(reason) + strlen("</p>") + 1;
1719 cert = &(csp->server_certs_chain);
1720 while (cert->next != NULL)
1722 size_t base64_len = 4 * ((strlen(cert->file_buf) + 2) / 3) + 1;
1724 message_len += strlen(cert->text_buf) + strlen("<pre></pre>\n")
1725 + base64_len + strlen("<a href=\"data:application"
1726 "/x-x509-ca-cert;base64,\">Download certificate</a>");
1731 * Joining all blocks in one long message
1733 char message[message_len];
1734 memset(message, 0, message_len);
1736 strlcpy(message, message_begin, message_len);
1737 strlcat(message, reason , message_len);
1738 strlcat(message, "</p>" , message_len);
1740 cert = &(csp->server_certs_chain);
1741 while (cert->next != NULL)
1744 size_t base64_len = 4 * ((strlen(cert->file_buf) + 2) / 3) + 1; /* +1 for terminating null*/
1745 char base64_buf[base64_len];
1746 memset(base64_buf, 0, base64_len);
1748 /* Encoding certificate into base64 code */
1749 ret = mbedtls_base64_encode((unsigned char*)base64_buf,
1750 base64_len, &olen, (const unsigned char*)cert->file_buf,
1751 strlen(cert->file_buf));
1754 log_error(LOG_LEVEL_ERROR,
1755 "Encoding to base64 failed, buffer is to small");
1758 strlcat(message, "<pre>", message_len);
1759 strlcat(message, cert->text_buf, message_len);
1760 strlcat(message, "</pre>\n", message_len);
1764 strlcat(message, "<a href=\"data:application/x-x509-ca-cert;base64,",
1766 strlcat(message, base64_buf, message_len);
1767 strlcat(message, "\">Download certificate</a>", message_len);
1772 strlcat(message, message_end, message_len);
1775 * Sending final message to client
1777 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
1778 (const unsigned char *)message, strlen(message));
1780 * Waiting before closing connection. Some browsers doesn't show received
1781 * message if there isn't this delay.
1785 free_certificate_chain(csp);
1789 /*********************************************************************
1791 * Function : ssl_verify_callback
1793 * Description : This is a callback function for certificate verification.
1794 * It's called for all certificates in server certificate
1795 * trusted chain and it's preparing information about this
1796 * certificates. Prepared informations can be used to inform
1797 * user about invalid certificates.
1800 * 1 : csp_void = Current client state (buffers, headers, etc...)
1801 * 2 : crt = certificate from trusted chain
1802 * 3 : depth = depth in trusted chain
1803 * 4 : flags = certificate flags
1805 * Returns : 0 on success and negative value on error
1807 *********************************************************************/
1808 static int ssl_verify_callback(void *csp_void, mbedtls_x509_crt *crt,
1809 int depth, uint32_t *flags)
1811 struct client_state *csp = (struct client_state *)csp_void;
1812 struct certs_chain *last = &(csp->server_certs_chain);
1817 * Searching for last item in certificates linked list
1819 while (last->next != NULL)
1825 * Preparing next item in linked list for next certificate
1826 * If malloc fails, we are continuing without this certificate
1828 last->next = (struct certs_chain *)malloc(sizeof(struct certs_chain));
1829 if (last->next != NULL)
1831 last->next->next = NULL;
1832 memset(last->next->text_buf, 0, sizeof(last->next->text_buf));
1833 memset(last->next->file_buf, 0, sizeof(last->next->file_buf));
1836 * Saving certificate file into buffer
1838 if ((ret = mbedtls_pem_write_buffer(PEM_BEGIN_CRT, PEM_END_CRT,
1839 crt->raw.p, crt->raw.len, (unsigned char *)last->file_buf,
1840 sizeof(last->file_buf)-1, &olen)) != 0)
1846 * Saving certificate information into buffer
1848 mbedtls_x509_crt_info(last->text_buf, sizeof(last->text_buf) - 1,
1849 CERT_INFO_PREFIX, crt);
1853 log_error(LOG_LEVEL_ERROR,
1854 "Malloc memory for server certificate informations failed");
1862 /*********************************************************************
1864 * Function : free_certificate_chain
1866 * Description : Frees certificates linked list. This linked list is
1867 * used to save informations about certificates in
1871 * 1 : csp = Current client state (buffers, headers, etc...)
1875 *********************************************************************/
1876 static void free_certificate_chain(struct client_state *csp)
1878 struct certs_chain *cert = csp->server_certs_chain.next;
1880 /* Cleaning buffers */
1881 memset(csp->server_certs_chain.text_buf, 0,
1882 sizeof(csp->server_certs_chain.text_buf));
1883 memset(csp->server_certs_chain.text_buf, 0,
1884 sizeof(csp->server_certs_chain.file_buf));
1885 csp->server_certs_chain.next = NULL;
1887 /* Freeing memory in whole linked list */
1892 struct certs_chain *cert_for_free = cert;
1894 freez(cert_for_free);
1895 } while (cert != NULL);
1900 /*********************************************************************
1902 * Function : file_exists
1904 * Description : Tests if file exists and is readable.
1907 * 1 : path = Path to tested file.
1909 * Returns : 1 => File exists and is readable.
1910 * 0 => File doesn't exist or is not readable.
1912 *********************************************************************/
1913 static int file_exists(const char *path)
1916 if ((f = fopen(path, "r")) != NULL)
1926 /*********************************************************************
1928 * Function : host_to_hash
1930 * Description : Creates MD5 hash from host name. Host name is loaded
1931 * from structure csp and saved again into it.
1934 * 1 : csp = Current client state (buffers, headers, etc...)
1936 * Returns : 1 => Error while creating hash
1937 * 0 => Hash created successfully
1939 *********************************************************************/
1940 static int host_to_hash(struct client_state * csp)
1944 #if !defined(MBEDTLS_MD5_C)
1945 log_error(LOG_LEVEL_ERROR, "MBEDTLS_MD5_C is not defined. Can't create"
1946 "MD5 hash for certificate and key name.");
1949 memset(csp->http->hash_of_host, 0, sizeof(csp->http->hash_of_host));
1950 mbedtls_md5((unsigned char *)csp->http->host, strlen(csp->http->host),
1951 csp->http->hash_of_host);
1953 /* Converting hash into string with hex */
1957 if ((ret = sprintf((char *)csp->http->hash_of_host_hex + 2 * i, "%02x",
1958 csp->http->hash_of_host[i])) < 0)
1960 log_error(LOG_LEVEL_ERROR, "Sprintf return value: %d", ret);
1966 #endif /* MBEDTLS_MD5_C */
1970 /*********************************************************************
1972 * Function : tunnel_established_successfully
1974 * Description : Check if parent proxy server response contains
1975 * informations about successfully created connection with
1976 * destination server. (HTTP/... 2xx ...)
1979 * 1 : server_response = Buffer with parent proxy server response
1980 * 2 : response_len = Length of server_response
1982 * Returns : 1 => Connection created successfully
1983 * 0 => Connection wasn't created successfully
1985 *********************************************************************/
1986 extern int tunnel_established_successfully(const char *server_response,
1987 unsigned int response_len)
1989 unsigned int pos = 0;
1991 if (server_response == NULL)
1996 /* Tests if "HTTP/" string is at the begin of received response */
1997 if (strncmp(server_response, "HTTP/", 5) != 0)
2002 for (pos = 0; pos < response_len; pos++)
2004 if (server_response[pos] == ' ')
2011 * response_len -3 because of buffer end, response structure and 200 code.
2012 * There must be at least 3 chars after space.
2013 * End of buffer: ... 2xx'\0'
2016 if (pos >= (response_len - 3))
2021 /* Test HTTP status code */
2022 if (server_response[pos + 1] != '2')
2031 /*********************************************************************
2033 * Function : seed_rng
2035 * Description : Seeding the RNG for all SSL uses
2038 * 1 : csp = Current client state (buffers, headers, etc...)
2040 * Returns : -1 => RNG wasn't seed successfully
2041 * 0 => RNG is seeded successfully
2043 *********************************************************************/
2044 static int seed_rng(struct client_state *csp)
2047 char err_buf[ERROR_BUF_SIZE];
2049 memset(err_buf, 0, sizeof(err_buf));
2051 if (rng_seeded == 0)
2053 privoxy_mutex_lock(&rng_mutex);
2054 if (rng_seeded == 0)
2056 mbedtls_ctr_drbg_init(&ctr_drbg);
2057 mbedtls_entropy_init(&entropy);
2058 ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func,
2062 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
2063 log_error(LOG_LEVEL_ERROR,
2064 "mbedtls_ctr_drbg_seed failed: %s", err_buf);
2065 privoxy_mutex_unlock(&rng_mutex);
2070 privoxy_mutex_unlock(&rng_mutex);