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"
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 set 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 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 */
73 #define CERT_PARAM_COMMON_NAME "CN="
74 #define CERT_PARAM_ORGANIZATION ",O="
75 #define CERT_PARAM_ORG_UNIT ",OU="
76 #define CERT_PARAM_COUNTRY ",C=CZ"
77 #define KEY_FILE_TYPE ".pem"
78 #define CERT_FILE_TYPE ".crt"
79 #define CERT_SUBJECT_PASSWORD ""
80 #define CERT_INFO_PREFIX ""
83 * Properties of cert for generating
86 char *issuer_crt; /* filename of the issuer certificate */
87 char *subject_key; /* filename of the subject key file */
88 char *issuer_key; /* filename of the issuer key file */
89 const char *subject_pwd; /* password for the subject key file */
90 const char *issuer_pwd; /* password for the issuer key file */
91 char *output_file; /* where to store the constructed key file */
92 const char *subject_name; /* subject name for certificate */
93 char issuer_name[ISSUER_NAME_BUF_SIZE]; /* issuer name for certificate */
94 const char *not_before; /* validity period not before */
95 const char *not_after; /* validity period not after */
96 const char *serial; /* serial number string */
97 int is_ca; /* is a CA certificate */
98 int max_pathlen; /* maximum CA path length */
102 * Properties of key for generating
105 mbedtls_pk_type_t type; /* type of key to generate */
106 int rsa_keysize; /* length of key in bits */
107 char *key_file_path; /* filename of the key file */
110 static int generate_webpage_certificate(struct client_state *csp);
111 static char *make_certs_path(const char *conf_dir, const char *file_name, const char *suffix);
112 static int file_exists(const char *path);
113 static int host_to_hash(struct client_state *csp);
114 static int ssl_verify_callback(void *data, mbedtls_x509_crt *crt, int depth, uint32_t *flags);
115 static void free_certificate_chain(struct client_state *csp);
116 static unsigned int get_certificate_mutex_id(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
169 * 1 : ssl = SSL context to test
171 * Returns : 0 => No data are pending
172 * >0 => Pending data length
174 *********************************************************************/
175 extern size_t is_ssl_pending(mbedtls_ssl_context *ssl)
182 return mbedtls_ssl_get_bytes_avail(ssl);
186 /*********************************************************************
188 * Function : ssl_send_data
190 * Description : Sends the content of buf (for n bytes) to given SSL
191 * connection context.
194 * 1 : ssl = SSL context to send data to
195 * 2 : buf = Pointer to data to be sent
196 * 3 : len = Length of data to be sent to the SSL context
198 * Returns : Length of sent data or negative value on error.
200 *********************************************************************/
201 extern int ssl_send_data(mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len)
204 size_t max_fragment_size = 0; /* Maximal length of data in one SSL fragment*/
205 int send_len = 0; /* length of one data part to send */
206 int pos = 0; /* Position of unsent part in buffer */
213 /* Getting maximal length of data sent in one fragment */
214 max_fragment_size = mbedtls_ssl_get_max_frag_len(ssl);
217 * Whole buffer must be sent in many fragments, because each fragment
218 * has its maximal length.
222 /* Compute length of data, that can be send in next fragment */
223 if ((pos + (int)max_fragment_size) > len)
225 send_len = (int)len - pos;
229 send_len = (int)max_fragment_size;
232 log_error(LOG_LEVEL_WRITING, "TLS: %N", send_len, buf+pos);
235 * Sending one part of the buffer
237 while ((ret = mbedtls_ssl_write(ssl,
238 (const unsigned char *)(buf + pos),
239 (size_t)send_len)) < 0)
241 if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
242 ret != MBEDTLS_ERR_SSL_WANT_WRITE)
244 char err_buf[ERROR_BUF_SIZE];
246 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
247 log_error(LOG_LEVEL_ERROR,
248 "Sending data over TLS/SSL failed: %s", err_buf);
252 /* Adding count of sent bytes to position in buffer */
253 pos = pos + send_len;
260 /*********************************************************************
262 * Function : ssl_recv_data
264 * Description : Receives data from given SSL context and puts
268 * 1 : ssl = SSL context to receive data from
269 * 2 : buf = Pointer to buffer where data will be written
270 * 3 : max_length = Maximum number of bytes to read
272 * Returns : Number of bytes read, 0 for EOF, or -1
275 *********************************************************************/
276 extern int ssl_recv_data(mbedtls_ssl_context *ssl, unsigned char *buf, size_t max_length)
279 memset(buf, 0, max_length);
282 * Receiving data from SSL context into buffer
286 ret = mbedtls_ssl_read(ssl, buf, max_length);
287 } while (ret == MBEDTLS_ERR_SSL_WANT_READ
288 || ret == MBEDTLS_ERR_SSL_WANT_WRITE);
292 char err_buf[ERROR_BUF_SIZE];
294 if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY)
296 log_error(LOG_LEVEL_CONNECT,
297 "The peer notified us that the connection is going to be closed");
300 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
301 log_error(LOG_LEVEL_ERROR,
302 "Receiving data over TLS/SSL failed: %s", err_buf);
307 log_error(LOG_LEVEL_RECEIVED, "TLS: %N", ret, buf);
313 /*********************************************************************
315 * Function : ssl_flush_socket
317 * Description : Send any pending "buffered" content with given
318 * SSL connection. Alternative to function flush_socket.
321 * 1 : ssl = SSL context to send buffer to
322 * 2 : iob = The I/O buffer to flush, usually csp->iob.
324 * Returns : On success, the number of bytes send are returned (zero
325 * indicates nothing was sent). On error, -1 is returned.
327 *********************************************************************/
328 extern long ssl_flush_socket(mbedtls_ssl_context *ssl, struct iob *iob)
330 /* Computing length of buffer part to send */
331 long len = iob->eod - iob->cur;
338 /* Sending data to given SSl context */
339 if (ssl_send_data(ssl, (const unsigned char *)iob->cur, (size_t)len) < 0)
343 iob->eod = iob->cur = iob->buf;
348 /*********************************************************************
350 * Function : ssl_debug_callback
352 * Description : Debug callback function for mbedtls library.
353 * Prints info into log file.
356 * 1 : ctx = File to save log in
357 * 2 : level = Debug level
358 * 3 : file = File calling debug message
359 * 4 : line = Line calling debug message
360 * 5 : str = Debug message
364 *********************************************************************/
365 static void ssl_debug_callback(void *ctx, int level, const char *file, int line, const char *str)
369 fprintf((FILE *)ctx, "%s:%04d: %s", file, line, str);
371 log_error(LOG_LEVEL_INFO, "SSL debug message: %s:%04d: %s", file, line, str);
376 /*********************************************************************
378 * Function : create_client_ssl_connection
380 * Description : Creates TLS/SSL secured connection with client
383 * 1 : csp = Current client state (buffers, headers, etc...)
385 * Returns : 0 on success, negative value if connection wasn't created
388 *********************************************************************/
389 extern int create_client_ssl_connection(struct client_state *csp)
391 /* Paths to certificates file and key file */
392 char *key_file = NULL;
393 char *ca_file = NULL;
394 char *cert_file = NULL;
396 char err_buf[ERROR_BUF_SIZE];
399 * Initializing mbedtls structures for TLS/SSL connection
401 mbedtls_net_init(&(csp->mbedtls_client_attr.socket_fd));
402 mbedtls_ssl_init(&(csp->mbedtls_client_attr.ssl));
403 mbedtls_ssl_config_init(&(csp->mbedtls_client_attr.conf));
404 mbedtls_x509_crt_init(&(csp->mbedtls_client_attr.server_cert));
405 mbedtls_pk_init(&(csp->mbedtls_client_attr.prim_key));
406 #if defined(MBEDTLS_SSL_CACHE_C)
407 mbedtls_ssl_cache_init(&(csp->mbedtls_client_attr.cache));
411 * Preparing hash of host for creating certificates
413 ret = host_to_hash(csp);
416 log_error(LOG_LEVEL_ERROR, "Generating hash of host failed: %d", ret);
422 * Preparing paths to certificates files and key file
424 ca_file = csp->config->ca_cert_file;
425 cert_file = make_certs_path(csp->config->certificate_directory,
426 (const char *)csp->http->hash_of_host_hex, CERT_FILE_TYPE);
427 key_file = make_certs_path(csp->config->certificate_directory,
428 (const char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
430 if (cert_file == NULL || key_file == NULL)
437 * Generating certificate for requested host. Mutex to prevent
438 * certificate and key inconsistence must be locked.
440 unsigned int cert_mutex_id = get_certificate_mutex_id(csp);
441 privoxy_mutex_lock(&(certificates_mutexes[cert_mutex_id]));
443 ret = generate_webpage_certificate(csp);
446 log_error(LOG_LEVEL_ERROR,
447 "Generate_webpage_certificate failed: %d", ret);
448 privoxy_mutex_unlock(&(certificates_mutexes[cert_mutex_id]));
452 privoxy_mutex_unlock(&(certificates_mutexes[cert_mutex_id]));
465 * Loading CA file, webpage certificate and key files
467 ret = mbedtls_x509_crt_parse_file(&(csp->mbedtls_client_attr.server_cert),
471 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
472 log_error(LOG_LEVEL_ERROR,
473 "Loading webpage certificate %s failed: %s", cert_file, err_buf);
478 ret = mbedtls_x509_crt_parse_file(&(csp->mbedtls_client_attr.server_cert),
482 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
483 log_error(LOG_LEVEL_ERROR,
484 "Loading CA certificate %s failed: %s", ca_file, err_buf);
489 ret = mbedtls_pk_parse_keyfile(&(csp->mbedtls_client_attr.prim_key),
493 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
494 log_error(LOG_LEVEL_ERROR,
495 "Loading and parsing webpage certificate private key %s failed: %s",
502 * Setting SSL parameters
504 ret = mbedtls_ssl_config_defaults(&(csp->mbedtls_client_attr.conf),
505 MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_TRANSPORT_STREAM,
506 MBEDTLS_SSL_PRESET_DEFAULT);
509 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
510 log_error(LOG_LEVEL_ERROR,
511 "mbedtls_ssl_config_defaults failed: %s", err_buf);
516 mbedtls_ssl_conf_rng(&(csp->mbedtls_client_attr.conf),
517 mbedtls_ctr_drbg_random, &ctr_drbg);
518 mbedtls_ssl_conf_dbg(&(csp->mbedtls_client_attr.conf),
519 ssl_debug_callback, stdout);
521 #if defined(MBEDTLS_SSL_CACHE_C)
522 mbedtls_ssl_conf_session_cache(&(csp->mbedtls_client_attr.conf),
523 &(csp->mbedtls_client_attr.cache), mbedtls_ssl_cache_get,
524 mbedtls_ssl_cache_set);
528 * Setting certificates
530 ret = mbedtls_ssl_conf_own_cert(&(csp->mbedtls_client_attr.conf),
531 &(csp->mbedtls_client_attr.server_cert),
532 &(csp->mbedtls_client_attr.prim_key));
535 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
536 log_error(LOG_LEVEL_ERROR,
537 "mbedtls_ssl_conf_own_cert failed: %s", err_buf);
542 ret = mbedtls_ssl_setup(&(csp->mbedtls_client_attr.ssl),
543 &(csp->mbedtls_client_attr.conf));
546 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
547 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_setup failed: %s", err_buf);
552 mbedtls_ssl_set_bio(&(csp->mbedtls_client_attr.ssl),
553 &(csp->mbedtls_client_attr.socket_fd), mbedtls_net_send,
554 mbedtls_net_recv, NULL);
555 mbedtls_ssl_session_reset(&(csp->mbedtls_client_attr.ssl));
558 * Setting socket fd in mbedtls_net_context structure. This structure
559 * can't be set by mbedtls functions, because we already have created
560 * a TCP connection when this function is called.
562 csp->mbedtls_client_attr.socket_fd.fd = csp->cfd;
565 * Handshake with client
567 log_error(LOG_LEVEL_CONNECT,
568 "Performing the TLS/SSL handshake with client. Hash of host: %s",
569 csp->http->hash_of_host_hex);
570 while ((ret = mbedtls_ssl_handshake(&(csp->mbedtls_client_attr.ssl))) != 0)
572 if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
573 ret != MBEDTLS_ERR_SSL_WANT_WRITE)
575 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
576 log_error(LOG_LEVEL_ERROR,
577 "medtls_ssl_handshake with client failed: %s", err_buf);
583 log_error(LOG_LEVEL_CONNECT, "Client successfully connected over TLS/SSL");
584 csp->ssl_with_client_is_opened = 1;
588 * Freeing allocated paths to files
593 /* Freeing structures if connection wasn't created successfully */
596 free_client_ssl_structures(csp);
602 /*********************************************************************
604 * Function : close_client_ssl_connection
606 * Description : Closes TLS/SSL connection with client. This function
607 * checks if this connection is already created.
610 * 1 : csp = Current client state (buffers, headers, etc...)
614 *********************************************************************/
615 extern void close_client_ssl_connection(struct client_state *csp)
619 if (csp->ssl_with_client_is_opened == 0)
625 * Notifying the peer that the connection is being closed.
628 ret = mbedtls_ssl_close_notify(&(csp->mbedtls_client_attr.ssl));
629 } while (ret == MBEDTLS_ERR_SSL_WANT_WRITE);
631 free_client_ssl_structures(csp);
632 csp->ssl_with_client_is_opened = 0;
636 /*********************************************************************
638 * Function : free_client_ssl_structures
640 * Description : Frees structures used for SSL communication with
644 * 1 : csp = Current client state (buffers, headers, etc...)
648 *********************************************************************/
649 static void free_client_ssl_structures(struct client_state *csp)
652 * We can't use function mbedtls_net_free, because this function
653 * inter alia close TCP connection on setted fd. Instead of this
654 * function, we change fd to -1, which is the same what does
655 * rest of mbedtls_net_free function.
657 csp->mbedtls_client_attr.socket_fd.fd = -1;
659 /* Freeing mbedtls structures */
660 mbedtls_x509_crt_free(&(csp->mbedtls_client_attr.server_cert));
661 mbedtls_pk_free(&(csp->mbedtls_client_attr.prim_key));
662 mbedtls_ssl_free(&(csp->mbedtls_client_attr.ssl));
663 mbedtls_ssl_config_free(&(csp->mbedtls_client_attr.conf));
664 #if defined(MBEDTLS_SSL_CACHE_C)
665 mbedtls_ssl_cache_free(&(csp->mbedtls_client_attr.cache));
670 /*********************************************************************
672 * Function : create_server_ssl_connection
674 * Description : Creates TLS/SSL secured connection with server.
677 * 1 : csp = Current client state (buffers, headers, etc...)
679 * Returns : 0 on success, negative value if connection wasn't created
682 *********************************************************************/
683 extern int create_server_ssl_connection(struct client_state *csp)
686 char err_buf[ERROR_BUF_SIZE];
687 char *trusted_cas_file = NULL;
688 int auth_mode = MBEDTLS_SSL_VERIFY_REQUIRED;
690 csp->server_cert_verification_result = SSL_CERT_NOT_VERIFIED;
691 csp->server_certs_chain.next = NULL;
693 /* Setting path to file with trusted CAs */
694 trusted_cas_file = csp->config->trusted_cas_file;
697 * Initializing mbedtls structures for TLS/SSL connection
699 mbedtls_net_init(&(csp->mbedtls_server_attr.socket_fd));
700 mbedtls_ssl_init(&(csp->mbedtls_server_attr.ssl));
701 mbedtls_ssl_config_init(&(csp->mbedtls_server_attr.conf));
702 mbedtls_x509_crt_init(&(csp->mbedtls_server_attr.ca_cert));
705 * Setting socket fd in mbedtls_net_context structure. This structure
706 * can't be set by mbedtls functions, because we already have created
707 * TCP connection when calling this function.
709 csp->mbedtls_server_attr.socket_fd.fd = csp->server_connection.sfd;
722 * Loading file with trusted CAs
724 ret = mbedtls_x509_crt_parse_file(&(csp->mbedtls_server_attr.ca_cert),
728 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
729 log_error(LOG_LEVEL_ERROR, "Loading trusted CAs file %s failed: %s",
730 trusted_cas_file, err_buf);
736 * Set TLS/SSL options
738 ret = mbedtls_ssl_config_defaults(&(csp->mbedtls_server_attr.conf),
739 MBEDTLS_SSL_IS_CLIENT,
740 MBEDTLS_SSL_TRANSPORT_STREAM,
741 MBEDTLS_SSL_PRESET_DEFAULT);
744 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
745 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_config_defaults failed: %s",
752 * Setting how strict should certificate verification be and other
753 * parameters for certificate verification
755 if (csp->dont_verify_certificate)
757 auth_mode = MBEDTLS_SSL_VERIFY_NONE;
760 mbedtls_ssl_conf_authmode(&(csp->mbedtls_server_attr.conf), auth_mode);
761 mbedtls_ssl_conf_ca_chain(&(csp->mbedtls_server_attr.conf),
762 &(csp->mbedtls_server_attr.ca_cert), NULL);
764 /* Setting callback function for certificates verification */
765 mbedtls_ssl_conf_verify(&(csp->mbedtls_server_attr.conf),
766 ssl_verify_callback, (void *)csp);
768 mbedtls_ssl_conf_rng(&(csp->mbedtls_server_attr.conf),
769 mbedtls_ctr_drbg_random, &ctr_drbg);
770 mbedtls_ssl_conf_dbg(&(csp->mbedtls_server_attr.conf),
771 ssl_debug_callback, stdout);
773 ret = mbedtls_ssl_setup(&(csp->mbedtls_server_attr.ssl),
774 &(csp->mbedtls_server_attr.conf));
777 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
778 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_setup failed: %s", err_buf);
784 * Set the hostname to check against the received server certificate
786 ret = mbedtls_ssl_set_hostname(&(csp->mbedtls_server_attr.ssl),
790 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
791 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_set_hostname failed: %s",
797 mbedtls_ssl_set_bio(&(csp->mbedtls_server_attr.ssl),
798 &(csp->mbedtls_server_attr.socket_fd), mbedtls_net_send,
799 mbedtls_net_recv, NULL);
802 * Handshake with server
804 log_error(LOG_LEVEL_CONNECT,
805 "Performing the TLS/SSL handshake with the server");
807 while ((ret = mbedtls_ssl_handshake(&(csp->mbedtls_server_attr.ssl))) != 0)
809 if (ret != MBEDTLS_ERR_SSL_WANT_READ
810 && ret != MBEDTLS_ERR_SSL_WANT_WRITE)
812 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
814 if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED)
816 log_error(LOG_LEVEL_ERROR,
817 "Server certificate verification failed: %s", err_buf);
818 csp->server_cert_verification_result =
819 mbedtls_ssl_get_verify_result(&(csp->mbedtls_server_attr.ssl));
825 log_error(LOG_LEVEL_ERROR,
826 "mbedtls_ssl_handshake with server failed: %s", err_buf);
833 log_error(LOG_LEVEL_CONNECT, "Server successfully connected over TLS/SSL");
836 * Server certificate chain is valid, so we can clean
837 * chain, because we will not send it to client.
839 free_certificate_chain(csp);
841 csp->ssl_with_server_is_opened = 1;
842 csp->server_cert_verification_result =
843 mbedtls_ssl_get_verify_result(&(csp->mbedtls_server_attr.ssl));
846 /* Freeing structures if connection wasn't created successfully */
849 free_server_ssl_structures(csp);
856 /*********************************************************************
858 * Function : close_server_ssl_connection
860 * Description : Closes TLS/SSL connection with server. This function
861 * checks if this connection is already opened.
864 * 1 : csp = Current client state (buffers, headers, etc...)
868 *********************************************************************/
869 static void close_server_ssl_connection(struct client_state *csp)
873 if (csp->ssl_with_server_is_opened == 0)
879 * Notifying the peer that the connection is being closed.
882 ret = mbedtls_ssl_close_notify(&(csp->mbedtls_server_attr.ssl));
883 } while (ret == MBEDTLS_ERR_SSL_WANT_WRITE);
885 free_server_ssl_structures(csp);
886 csp->ssl_with_server_is_opened = 0;
890 /*********************************************************************
892 * Function : free_server_ssl_structures
894 * Description : Frees structures used for SSL communication with server
897 * 1 : csp = Current client state (buffers, headers, etc...)
901 *********************************************************************/
902 static void free_server_ssl_structures(struct client_state *csp)
905 * We can't use function mbedtls_net_free, because this function
906 * inter alia close TCP connection on setted fd. Instead of this
907 * function, we change fd to -1, which is the same what does
908 * rest of mbedtls_net_free function.
910 csp->mbedtls_client_attr.socket_fd.fd = -1;
912 mbedtls_x509_crt_free(&(csp->mbedtls_server_attr.ca_cert));
913 mbedtls_ssl_free(&(csp->mbedtls_server_attr.ssl));
914 mbedtls_ssl_config_free(&(csp->mbedtls_server_attr.conf));
918 /*********************************************************************
920 * Function : close_client_and_server_ssl_connections
922 * Description : Checks if client or server should use secured
923 * connection over SSL and if so, closes all of them.
926 * 1 : csp = Current client state (buffers, headers, etc...)
930 *********************************************************************/
931 extern void close_client_and_server_ssl_connections(struct client_state *csp)
933 if (client_use_ssl(csp) == 1)
935 close_client_ssl_connection(csp);
937 if (server_use_ssl(csp) == 1)
939 close_server_ssl_connection(csp);
943 /*====================== Certificates ======================*/
945 /*********************************************************************
947 * Function : write_certificate
949 * Description : Writes certificate into file.
952 * 1 : crt = certificate to write into file
953 * 2 : output_file = path to save certificate file
954 * 3 : f_rng = mbedtls_ctr_drbg_random
955 * 4 : p_rng = mbedtls_ctr_drbg_context
957 * Returns : Length of written certificate on success or negative value
960 *********************************************************************/
961 static int write_certificate(mbedtls_x509write_cert *crt, const char *output_file,
962 int(*f_rng)(void *, unsigned char *, size_t), void *p_rng)
966 unsigned char cert_buf[CERTIFICATE_BUF_SIZE + 1]; /* Buffer for certificate in PEM format + terminating NULL */
968 char err_buf[ERROR_BUF_SIZE];
970 memset(cert_buf, 0, sizeof(cert_buf));
973 * Writing certificate into PEM string. If buffer is too small, function
974 * returns specific error and no buffer overflow can happen.
976 if ((ret = mbedtls_x509write_crt_pem(crt, cert_buf,
977 sizeof(cert_buf) - 1, f_rng, p_rng)) != 0)
979 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
980 log_error(LOG_LEVEL_ERROR,
981 "Writing certificate into buffer failed: %s", err_buf);
985 len = strlen((char *)cert_buf);
988 * Saving certificate into file
990 if ((f = fopen(output_file, "w")) == NULL)
992 log_error(LOG_LEVEL_ERROR, "Opening file %s to save certificate failed",
997 if (fwrite(cert_buf, 1, len, f) != len)
999 log_error(LOG_LEVEL_ERROR,
1000 "Writing certificate into file %s failed", output_file);
1011 /*********************************************************************
1013 * Function : write_private_key
1015 * Description : Writes private key into file and copies saved
1016 * content into given pointer to string. If function
1017 * returns 0 for success, this copy must be freed by
1021 * 1 : key = key to write into file
1022 * 2 : ret_buf = pointer to string with created key file content
1023 * 3 : key_file_path = path where to save key file
1025 * Returns : Length of written private key on success or negative value
1028 *********************************************************************/
1029 static int write_private_key(mbedtls_pk_context *key, unsigned char **ret_buf,
1030 const char *key_file_path)
1032 size_t len = 0; /* Length of created key */
1033 FILE *f = NULL; /* File to save certificate */
1035 char err_buf[ERROR_BUF_SIZE];
1037 /* Initializing buffer for key file content */
1038 *ret_buf = zalloc_or_die(PRIVATE_KEY_BUF_SIZE + 1);
1041 * Writing private key into PEM string
1043 if ((ret = mbedtls_pk_write_key_pem(key, *ret_buf, PRIVATE_KEY_BUF_SIZE)) != 0)
1045 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1046 log_error(LOG_LEVEL_ERROR,
1047 "Writing private key into PEM string failed: %s", err_buf);
1051 len = strlen((char *)*ret_buf);
1054 * Saving key into file
1056 if ((f = fopen(key_file_path, "wb")) == NULL)
1058 log_error(LOG_LEVEL_ERROR,
1059 "Opening file %s to save private key failed: %E",
1065 if (fwrite(*ret_buf, 1, len, f) != len)
1068 log_error(LOG_LEVEL_ERROR,
1069 "Writing private key into file %s failed",
1088 /*********************************************************************
1090 * Function : generate_key
1092 * Description : Tests if private key for host saved in csp already
1093 * exists. If this file doesn't exists, a new key is
1094 * generated and saved in a file. The generated key is also
1095 * copied into given parameter key_buf, which must be then
1096 * freed by caller. If file with key exists, key_buf
1097 * contain NULL and no private key is generated.
1100 * 1 : csp = Current client state (buffers, headers, etc...)
1101 * 2 : key_buf = buffer to save new generated key
1103 * Returns : -1 => Error while generating private key
1104 * 0 => Key already exists
1105 * >0 => Length of generated private key
1107 *********************************************************************/
1108 static int generate_key(struct client_state *csp, unsigned char **key_buf)
1110 mbedtls_pk_context key;
1111 key_options key_opt;
1113 char err_buf[ERROR_BUF_SIZE];
1115 key_opt.key_file_path = NULL;
1118 * Initializing structures for key generating
1120 mbedtls_pk_init(&key);
1123 * Preparing path for key file and other properties for generating key
1125 key_opt.type = MBEDTLS_PK_RSA;
1126 key_opt.rsa_keysize = RSA_KEYSIZE;
1128 key_opt.key_file_path = make_certs_path(csp->config->certificate_directory,
1129 (char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
1130 if (key_opt.key_file_path == NULL)
1137 * Test if key already exists. If so, we don't have to create it again.
1139 if (file_exists(key_opt.key_file_path) == 1)
1148 ret = seed_rng(csp);
1156 * Setting attributes of private key and generating it
1158 if ((ret = mbedtls_pk_setup(&key,
1159 mbedtls_pk_info_from_type(key_opt.type))) != 0)
1161 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1162 log_error(LOG_LEVEL_ERROR, "mbedtls_pk_setup failed: %s", err_buf);
1167 ret = mbedtls_rsa_gen_key(mbedtls_pk_rsa(key), mbedtls_ctr_drbg_random,
1168 &ctr_drbg, (unsigned)key_opt.rsa_keysize, RSA_KEY_PUBLIC_EXPONENT);
1171 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1172 log_error(LOG_LEVEL_ERROR, "Key generating failed: %s", err_buf);
1178 * Exporting private key into file
1180 if ((ret = write_private_key(&key, key_buf, key_opt.key_file_path)) < 0)
1182 log_error(LOG_LEVEL_ERROR,
1183 "Writing private key into file %s failed", key_opt.key_file_path);
1190 * Freeing used variables
1192 freez(key_opt.key_file_path);
1194 mbedtls_pk_free(&key);
1200 /*********************************************************************
1202 * Function : generate_webpage_certificate
1204 * Description : Creates certificate file in presetted directory.
1205 * If certificate already exists, no other certificate
1206 * will be created. Subject of certificate is named
1207 * by csp->http->host from parameter. This function also
1208 * triggers generating of private key for new certificate.
1211 * 1 : csp = Current client state (buffers, headers, etc...)
1213 * Returns : -1 => Error while creating certificate.
1214 * 0 => Certificate already exists.
1215 * >0 => Length of created certificate.
1217 *********************************************************************/
1218 static int generate_webpage_certificate(struct client_state *csp)
1220 mbedtls_x509_crt issuer_cert;
1221 mbedtls_pk_context loaded_issuer_key, loaded_subject_key;
1222 mbedtls_pk_context *issuer_key = &loaded_issuer_key;
1223 mbedtls_pk_context *subject_key = &loaded_subject_key;
1224 mbedtls_x509write_cert cert;
1227 unsigned char *key_buf = NULL; /* Buffer for created key */
1230 char err_buf[ERROR_BUF_SIZE];
1231 cert_options cert_opt;
1233 /* Paths to keys and certificates needed to create certificate */
1234 cert_opt.issuer_key = NULL;
1235 cert_opt.subject_key = NULL;
1236 cert_opt.issuer_crt = NULL;
1237 cert_opt.output_file = NULL;
1240 * Create key for requested host
1242 int subject_key_len = generate_key(csp, &key_buf);
1243 if (subject_key_len < 0)
1245 log_error(LOG_LEVEL_ERROR, "Key generating failed");
1250 * Initializing structures for certificate generating
1252 mbedtls_x509write_crt_init(&cert);
1253 mbedtls_x509write_crt_set_md_alg(&cert, CERT_SIGNATURE_ALGORITHM);
1254 mbedtls_pk_init(&loaded_issuer_key);
1255 mbedtls_pk_init(&loaded_subject_key);
1256 mbedtls_mpi_init(&serial);
1257 mbedtls_x509_crt_init(&issuer_cert);
1260 * Presetting parameters for certificate. We must compute total length
1263 size_t cert_params_len = strlen(CERT_PARAM_COMMON_NAME) +
1264 strlen(CERT_PARAM_ORGANIZATION) + strlen(CERT_PARAM_COUNTRY) +
1265 strlen(CERT_PARAM_ORG_UNIT) +
1266 3 * strlen(csp->http->host) + 1;
1267 char cert_params[cert_params_len];
1268 memset(cert_params, 0, cert_params_len);
1271 * Converting unsigned long serial number to char * serial number.
1272 * We must compute length of serial number in string + terminating null.
1274 unsigned long certificate_serial = get_certificate_serial(csp);
1275 int serial_num_size = snprintf(NULL, 0, "%lu", certificate_serial) + 1;
1276 if (serial_num_size <= 0)
1278 serial_num_size = 1;
1281 char serial_num_text[serial_num_size]; /* Buffer for serial number */
1282 ret = snprintf(serial_num_text, (size_t)serial_num_size, "%lu", certificate_serial);
1283 if (ret < 0 || ret >= serial_num_size)
1285 log_error(LOG_LEVEL_ERROR,
1286 "Converting certificate serial number into string failed");
1292 * Preparing parameters for certificate
1294 strlcpy(cert_params, CERT_PARAM_COMMON_NAME, cert_params_len);
1295 strlcat(cert_params, csp->http->host, cert_params_len);
1296 strlcat(cert_params, CERT_PARAM_ORGANIZATION, cert_params_len);
1297 strlcat(cert_params, csp->http->host, cert_params_len);
1298 strlcat(cert_params, CERT_PARAM_ORG_UNIT, cert_params_len);
1299 strlcat(cert_params, csp->http->host, cert_params_len);
1300 strlcat(cert_params, CERT_PARAM_COUNTRY, cert_params_len);
1302 cert_opt.issuer_crt = csp->config->ca_cert_file;
1303 cert_opt.issuer_key = csp->config->ca_key_file;
1304 cert_opt.subject_key = make_certs_path(csp->config->certificate_directory,
1305 (const char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
1306 cert_opt.output_file = make_certs_path(csp->config->certificate_directory,
1307 (const char *)csp->http->hash_of_host_hex, CERT_FILE_TYPE);
1309 if (cert_opt.subject_key == NULL || cert_opt.output_file == NULL)
1315 cert_opt.subject_pwd = CERT_SUBJECT_PASSWORD;
1316 cert_opt.issuer_pwd = csp->config->ca_password;
1317 cert_opt.subject_name = cert_params;
1318 cert_opt.not_before = GENERATED_CERT_VALID_FROM;
1319 cert_opt.not_after = GENERATED_CERT_VALID_TO;
1320 cert_opt.serial = serial_num_text;
1322 cert_opt.max_pathlen = -1;
1325 * Test if certificate exists and private key was already created
1327 if (file_exists(cert_opt.output_file) == 1 && subject_key_len == 0)
1336 ret = seed_rng(csp);
1344 * Parse serial to MPI
1346 ret = mbedtls_mpi_read_string(&serial, 10, cert_opt.serial);
1349 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1350 log_error(LOG_LEVEL_ERROR,
1351 "mbedtls_mpi_read_string failed: %s", err_buf);
1357 * Loading certificates
1359 ret = mbedtls_x509_crt_parse_file(&issuer_cert, cert_opt.issuer_crt);
1362 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1363 log_error(LOG_LEVEL_ERROR, "Loading issuer certificate %s failed: %s",
1364 cert_opt.issuer_crt, err_buf);
1369 ret = mbedtls_x509_dn_gets(cert_opt.issuer_name,
1370 sizeof(cert_opt.issuer_name), &issuer_cert.subject);
1373 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1374 log_error(LOG_LEVEL_ERROR, "mbedtls_x509_dn_gets failed: %s", err_buf);
1380 * Loading keys from file or from buffer
1382 if (key_buf != NULL && subject_key_len > 0)
1384 /* Key was created in this function and is stored in buffer */
1385 ret = mbedtls_pk_parse_key(&loaded_subject_key, key_buf,
1386 (size_t)(subject_key_len + 1), (unsigned const char *)
1387 cert_opt.subject_pwd, strlen(cert_opt.subject_pwd));
1391 /* Key wasn't created in this function, because it already existed */
1392 ret = mbedtls_pk_parse_keyfile(&loaded_subject_key,
1393 cert_opt.subject_key, cert_opt.subject_pwd);
1398 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1399 log_error(LOG_LEVEL_ERROR, "Parsing subject key %s failed: %s",
1400 cert_opt.subject_key, err_buf);
1405 ret = mbedtls_pk_parse_keyfile(&loaded_issuer_key, cert_opt.issuer_key,
1406 cert_opt.issuer_pwd);
1409 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1410 log_error(LOG_LEVEL_ERROR,
1411 "Parsing issuer key %s failed: %s", cert_opt.issuer_key, err_buf);
1417 * Check if key and issuer certificate match
1419 if (!mbedtls_pk_can_do(&issuer_cert.pk, MBEDTLS_PK_RSA) ||
1420 mbedtls_mpi_cmp_mpi(&mbedtls_pk_rsa(issuer_cert.pk)->N,
1421 &mbedtls_pk_rsa(*issuer_key)->N) != 0 ||
1422 mbedtls_mpi_cmp_mpi(&mbedtls_pk_rsa(issuer_cert.pk)->E,
1423 &mbedtls_pk_rsa(*issuer_key)->E) != 0)
1425 log_error(LOG_LEVEL_ERROR,
1426 "Issuer key doesn't match issuer certificate");
1431 mbedtls_x509write_crt_set_subject_key(&cert, subject_key);
1432 mbedtls_x509write_crt_set_issuer_key(&cert, issuer_key);
1435 * Setting parameters of signed certificate
1437 ret = mbedtls_x509write_crt_set_subject_name(&cert, cert_opt.subject_name);
1440 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1441 log_error(LOG_LEVEL_ERROR,
1442 "Setting subject name in signed certificate failed: %s", err_buf);
1447 ret = mbedtls_x509write_crt_set_issuer_name(&cert, cert_opt.issuer_name);
1450 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1451 log_error(LOG_LEVEL_ERROR,
1452 "Setting issuer name in signed certificate failed: %s", err_buf);
1457 ret = mbedtls_x509write_crt_set_serial(&cert, &serial);
1460 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1461 log_error(LOG_LEVEL_ERROR,
1462 "Setting serial number in signed certificate failed: %s", err_buf);
1467 ret = mbedtls_x509write_crt_set_validity(&cert, cert_opt.not_before,
1468 cert_opt.not_after);
1471 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1472 log_error(LOG_LEVEL_ERROR,
1473 "Setting validity in signed certificate failed: %s", err_buf);
1479 * Setting the basicConstraints extension for certificate
1481 ret = mbedtls_x509write_crt_set_basic_constraints(&cert, cert_opt.is_ca,
1482 cert_opt.max_pathlen);
1485 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1486 log_error(LOG_LEVEL_ERROR, "Setting the basicConstraints extension "
1487 "in signed certificate failed: %s", err_buf);
1492 #if defined(MBEDTLS_SHA1_C)
1493 /* Setting the subjectKeyIdentifier extension for certificate */
1494 ret = mbedtls_x509write_crt_set_subject_key_identifier(&cert);
1497 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1498 log_error(LOG_LEVEL_ERROR, "mbedtls_x509write_crt_set_subject_key_"
1499 "identifier failed: %s", err_buf);
1504 /* Setting the authorityKeyIdentifier extension for certificate */
1505 ret = mbedtls_x509write_crt_set_authority_key_identifier(&cert);
1508 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1509 log_error(LOG_LEVEL_ERROR, "mbedtls_x509write_crt_set_authority_key_"
1510 "identifier failed: %s", err_buf);
1514 #endif /* MBEDTLS_SHA1_C */
1517 * Writing certificate into file
1519 ret = write_certificate(&cert, cert_opt.output_file,
1520 mbedtls_ctr_drbg_random, &ctr_drbg);
1523 log_error(LOG_LEVEL_ERROR, "Writing certificate into file failed");
1529 * Freeing used structures
1531 mbedtls_x509write_crt_free(&cert);
1532 mbedtls_pk_free(&loaded_subject_key);
1533 mbedtls_pk_free(&loaded_issuer_key);
1534 mbedtls_mpi_free(&serial);
1535 mbedtls_x509_crt_free(&issuer_cert);
1537 freez(cert_opt.subject_key);
1538 freez(cert_opt.output_file);
1545 /*********************************************************************
1547 * Function : make_certs_path
1549 * Description : Creates path to file from three pieces. This function
1550 * takes parameters and puts them in one new mallocated
1551 * char * in correct order. Returned variable must be freed
1552 * by caller. This function is mainly used for creating
1553 * paths of certificates and keys files.
1556 * 1 : conf_dir = Name/path of directory where is the file.
1557 * '.' can be used for current directory.
1558 * 2 : file_name = Name of file in conf_dir without suffix.
1559 * 3 : suffix = Suffix of given file_name.
1561 * Returns : path => Path was built up successfully
1562 * NULL => Path can't be built up
1564 *********************************************************************/
1565 static char *make_certs_path(const char *conf_dir, const char *file_name,
1568 /* Test if all given parameters are valid */
1569 if (conf_dir == NULL || *conf_dir == '\0' || file_name == NULL ||
1570 *file_name == '\0' || suffix == NULL || *suffix == '\0')
1572 log_error(LOG_LEVEL_ERROR,
1573 "make_certs_path failed: bad input parameters");
1578 size_t path_size = strlen(conf_dir)
1579 + strlen(file_name) + strlen(suffix) + 2;
1581 /* Setting delimiter and editing path length */
1582 #if defined(_WIN32) || defined(__OS2__)
1583 char delim[] = "\\";
1585 #else /* ifndef _WIN32 || __OS2__ */
1587 #endif /* ifndef _WIN32 || __OS2__ */
1590 * Building up path from many parts
1593 if (*conf_dir != '/' && basedir && *basedir)
1596 * Replacing conf_dir with basedir. This new variable contains
1597 * absolute path to cwd.
1599 path_size += strlen(basedir) + 2;
1600 path = zalloc_or_die(path_size);
1602 strlcpy(path, basedir, path_size);
1603 strlcat(path, delim, path_size);
1604 strlcat(path, conf_dir, path_size);
1605 strlcat(path, delim, path_size);
1606 strlcat(path, file_name, path_size);
1607 strlcat(path, suffix, path_size);
1610 #endif /* defined unix */
1612 path = zalloc_or_die(path_size);
1614 strlcpy(path, conf_dir, path_size);
1615 strlcat(path, delim, path_size);
1616 strlcat(path, file_name, path_size);
1617 strlcat(path, suffix, path_size);
1624 /*********************************************************************
1626 * Function : get_certificate_mutex_id
1628 * Description : Computes mutex id from host name hash. This hash must
1629 * be already saved in csp structure
1632 * 1 : csp = Current client state (buffers, headers, etc...)
1634 * Returns : Mutex id for given host name
1636 *********************************************************************/
1637 static unsigned int get_certificate_mutex_id(struct client_state *csp) {
1638 #ifdef LIMIT_MUTEX_NUMBER
1639 return (unsigned int)(csp->http->hash_of_host[0] % 32);
1641 return (unsigned int)(csp->http->hash_of_host[1]
1642 + 256 * (int)csp->http->hash_of_host[0]);
1643 #endif /* LIMIT_MUTEX_NUMBER */
1647 /*********************************************************************
1649 * Function : get_certificate_serial
1651 * Description : Computes serial number for new certificate from host
1652 * name hash. This hash must be already saved in csp
1656 * 1 : csp = Current client state (buffers, headers, etc...)
1658 * Returns : Serial number for new certificate
1660 *********************************************************************/
1661 static unsigned long get_certificate_serial(struct client_state *csp) {
1662 unsigned long exp = 1;
1663 unsigned long serial = 0;
1665 int i = CERT_SERIAL_NUM_LENGTH;
1666 /* Length of hash is 16 bytes, we must avoid to read next chars */
1678 serial += exp * (unsigned)csp->http->hash_of_host[i];
1685 /*********************************************************************
1687 * Function : ssl_send_certificate_error
1689 * Description : Sends info about invalid server certificate to client.
1690 * Sent message is including all trusted chain certificates,
1691 * that can be downloaded in web browser.
1694 * 1 : csp = Current client state (buffers, headers, etc...)
1698 *********************************************************************/
1699 extern void ssl_send_certificate_error(struct client_state *csp)
1701 size_t message_len = 0;
1703 struct certs_chain *cert = NULL;
1705 /* Header of message with certificate informations */
1706 const char message_begin[] =
1707 "HTTP/1.1 200 OK\r\n"
1708 "Content-Type: text/html\r\n"
1709 "Connection: close\r\n\r\n"
1710 "<html><body><h1>Invalid server certificate</h1><p>Reason: ";
1711 const char message_end[] = "</body></html>\r\n\r\n";
1712 char reason[INVALID_CERT_INFO_BUF_SIZE];
1713 memset(reason, 0, sizeof(reason));
1715 /* Get verification message from verification return code */
1716 mbedtls_x509_crt_verify_info(reason, sizeof(reason), " ",
1717 csp->server_cert_verification_result);
1720 * Computing total length of message with all certificates inside
1722 message_len = strlen(message_begin) + strlen(message_end)
1723 + strlen(reason) + strlen("</p>") + 1;
1725 cert = &(csp->server_certs_chain);
1726 while (cert->next != NULL)
1728 size_t base64_len = 4 * ((strlen(cert->file_buf) + 2) / 3) + 1;
1730 message_len += strlen(cert->text_buf) + strlen("<pre></pre>\n")
1731 + base64_len + strlen("<a href=\"data:application"
1732 "/x-x509-ca-cert;base64,\">Download certificate</a>");
1737 * Joining all blocks in one long message
1739 char message[message_len];
1740 memset(message, 0, message_len);
1742 strlcpy(message, message_begin, message_len);
1743 strlcat(message, reason , message_len);
1744 strlcat(message, "</p>" , message_len);
1746 cert = &(csp->server_certs_chain);
1747 while (cert->next != NULL)
1750 size_t base64_len = 4 * ((strlen(cert->file_buf) + 2) / 3) + 1; /* +1 for terminating null*/
1751 char base64_buf[base64_len];
1752 memset(base64_buf, 0, base64_len);
1754 /* Encoding certificate into base64 code */
1755 ret = mbedtls_base64_encode((unsigned char*)base64_buf,
1756 base64_len, &olen, (const unsigned char*)cert->file_buf,
1757 strlen(cert->file_buf));
1760 log_error(LOG_LEVEL_ERROR,
1761 "Encoding to base64 failed, buffer is to small");
1764 strlcat(message, "<pre>", message_len);
1765 strlcat(message, cert->text_buf, message_len);
1766 strlcat(message, "</pre>\n", message_len);
1770 strlcat(message, "<a href=\"data:application/x-x509-ca-cert;base64,",
1772 strlcat(message, base64_buf, message_len);
1773 strlcat(message, "\">Download certificate</a>", message_len);
1778 strlcat(message, message_end, message_len);
1781 * Sending final message to client
1783 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
1784 (const unsigned char *)message, strlen(message));
1786 * Waiting before closing connection. Some browsers don't show received
1787 * message if there isn't this delay.
1791 free_certificate_chain(csp);
1795 /*********************************************************************
1797 * Function : ssl_verify_callback
1799 * Description : This is a callback function for certificate verification.
1800 * It's called for all certificates in server certificate
1801 * trusted chain and it's preparing information about this
1802 * certificates. Prepared informations can be used to inform
1803 * user about invalid certificates.
1806 * 1 : csp_void = Current client state (buffers, headers, etc...)
1807 * 2 : crt = certificate from trusted chain
1808 * 3 : depth = depth in trusted chain
1809 * 4 : flags = certificate flags
1811 * Returns : 0 on success and negative value on error
1813 *********************************************************************/
1814 static int ssl_verify_callback(void *csp_void, mbedtls_x509_crt *crt,
1815 int depth, uint32_t *flags)
1817 struct client_state *csp = (struct client_state *)csp_void;
1818 struct certs_chain *last = &(csp->server_certs_chain);
1823 * Searching for last item in certificates linked list
1825 while (last->next != NULL)
1831 * Preparing next item in linked list for next certificate
1833 last->next = malloc_or_die(sizeof(struct certs_chain));
1834 last->next->next = NULL;
1835 memset(last->next->text_buf, 0, sizeof(last->next->text_buf));
1836 memset(last->next->file_buf, 0, sizeof(last->next->file_buf));
1839 * Saving certificate file into buffer
1841 if ((ret = mbedtls_pem_write_buffer(PEM_BEGIN_CRT, PEM_END_CRT,
1842 crt->raw.p, crt->raw.len, (unsigned char *)last->file_buf,
1843 sizeof(last->file_buf)-1, &olen)) != 0)
1849 * Saving certificate information into buffer
1851 mbedtls_x509_crt_info(last->text_buf, sizeof(last->text_buf) - 1,
1852 CERT_INFO_PREFIX, crt);
1858 /*********************************************************************
1860 * Function : free_certificate_chain
1862 * Description : Frees certificates linked list. This linked list is
1863 * used to save informations about certificates in
1867 * 1 : csp = Current client state (buffers, headers, etc...)
1871 *********************************************************************/
1872 static void free_certificate_chain(struct client_state *csp)
1874 struct certs_chain *cert = csp->server_certs_chain.next;
1876 /* Cleaning buffers */
1877 memset(csp->server_certs_chain.text_buf, 0,
1878 sizeof(csp->server_certs_chain.text_buf));
1879 memset(csp->server_certs_chain.file_buf, 0,
1880 sizeof(csp->server_certs_chain.file_buf));
1881 csp->server_certs_chain.next = NULL;
1883 /* Freeing memory in whole linked list */
1888 struct certs_chain *cert_for_free = cert;
1890 freez(cert_for_free);
1891 } while (cert != NULL);
1896 /*********************************************************************
1898 * Function : file_exists
1900 * Description : Tests if file exists and is readable.
1903 * 1 : path = Path to tested file.
1905 * Returns : 1 => File exists and is readable.
1906 * 0 => File doesn't exist or is not readable.
1908 *********************************************************************/
1909 static int file_exists(const char *path)
1912 if ((f = fopen(path, "r")) != NULL)
1922 /*********************************************************************
1924 * Function : host_to_hash
1926 * Description : Creates MD5 hash from host name. Host name is loaded
1927 * from structure csp and saved again into it.
1930 * 1 : csp = Current client state (buffers, headers, etc...)
1932 * Returns : 1 => Error while creating hash
1933 * 0 => Hash created successfully
1935 *********************************************************************/
1936 static int host_to_hash(struct client_state *csp)
1940 #if !defined(MBEDTLS_MD5_C)
1941 log_error(LOG_LEVEL_ERROR, "MBEDTLS_MD5_C is not defined. Can't create"
1942 "MD5 hash for certificate and key name.");
1945 memset(csp->http->hash_of_host, 0, sizeof(csp->http->hash_of_host));
1946 mbedtls_md5((unsigned char *)csp->http->host, strlen(csp->http->host),
1947 csp->http->hash_of_host);
1949 /* Converting hash into string with hex */
1953 if ((ret = sprintf((char *)csp->http->hash_of_host_hex + 2 * i, "%02x",
1954 csp->http->hash_of_host[i])) < 0)
1956 log_error(LOG_LEVEL_ERROR, "Sprintf return value: %d", ret);
1962 #endif /* MBEDTLS_MD5_C */
1966 /*********************************************************************
1968 * Function : tunnel_established_successfully
1970 * Description : Check if parent proxy server response contains
1971 * informations about successfully created connection with
1972 * destination server. (HTTP/... 2xx ...)
1975 * 1 : server_response = Buffer with parent proxy server response
1976 * 2 : response_len = Length of server_response
1978 * Returns : 1 => Connection created successfully
1979 * 0 => Connection wasn't created successfully
1981 *********************************************************************/
1982 extern int tunnel_established_successfully(const char *server_response,
1983 unsigned int response_len)
1985 unsigned int pos = 0;
1987 if (server_response == NULL)
1992 /* Tests if "HTTP/" string is at the begin of received response */
1993 if (strncmp(server_response, "HTTP/", 5) != 0)
1998 for (pos = 0; pos < response_len; pos++)
2000 if (server_response[pos] == ' ')
2007 * response_len -3 because of buffer end, response structure and 200 code.
2008 * There must be at least 3 chars after space.
2009 * End of buffer: ... 2xx'\0'
2012 if (pos >= (response_len - 3))
2017 /* Test HTTP status code */
2018 if (server_response[pos + 1] != '2')
2027 /*********************************************************************
2029 * Function : seed_rng
2031 * Description : Seeding the RNG for all SSL uses
2034 * 1 : csp = Current client state (buffers, headers, etc...)
2036 * Returns : -1 => RNG wasn't seed successfully
2037 * 0 => RNG is seeded successfully
2039 *********************************************************************/
2040 static int seed_rng(struct client_state *csp)
2043 char err_buf[ERROR_BUF_SIZE];
2045 if (rng_seeded == 0)
2047 privoxy_mutex_lock(&rng_mutex);
2048 if (rng_seeded == 0)
2050 mbedtls_ctr_drbg_init(&ctr_drbg);
2051 mbedtls_entropy_init(&entropy);
2052 ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func,
2056 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
2057 log_error(LOG_LEVEL_ERROR,
2058 "mbedtls_ctr_drbg_seed failed: %s", err_buf);
2059 privoxy_mutex_unlock(&rng_mutex);
2064 privoxy_mutex_unlock(&rng_mutex);