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 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;
233 * Sending one part of the buffer
235 while ((ret = mbedtls_ssl_write(ssl,
236 (const unsigned char *)(buf + pos),
237 (size_t)send_len)) < 0)
239 if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
240 ret != MBEDTLS_ERR_SSL_WANT_WRITE)
242 char err_buf[ERROR_BUF_SIZE];
244 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
245 log_error(LOG_LEVEL_ERROR,
246 "Sending data over TLS/SSL failed: %s", err_buf);
250 /* Adding count of sent bytes to position in buffer */
251 pos = pos + send_len;
258 /*********************************************************************
260 * Function : ssl_recv_data
262 * Description : Receives data from given SSL context and puts
266 * 1 : ssl = SSL context to receive data from
267 * 2 : buf = Pointer to buffer where data will be written
268 * 3 : max_length = Maximum number of bytes to read
270 * Returns : Number of bytes read, 0 for EOF, or negative
273 *********************************************************************/
274 extern int ssl_recv_data(mbedtls_ssl_context *ssl, unsigned char *buf, size_t max_length)
277 memset(buf, 0, max_length);
280 * Receiving data from SSL context into buffer
284 ret = mbedtls_ssl_read(ssl, buf, max_length);
285 } while (ret == MBEDTLS_ERR_SSL_WANT_READ
286 || ret == MBEDTLS_ERR_SSL_WANT_WRITE);
290 char err_buf[ERROR_BUF_SIZE];
292 if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY)
294 log_error(LOG_LEVEL_CONNECT,
295 "The peer notified us that the connection is going to be closed");
298 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
299 log_error(LOG_LEVEL_ERROR,
300 "Receiving data over TLS/SSL failed: %s", err_buf);
307 /*********************************************************************
309 * Function : ssl_flush_socket
311 * Description : Send any pending "buffered" content with given
312 * SSL connection. Alternative to function flush_socket.
315 * 1 : ssl = SSL context to send buffer to
316 * 2 : iob = The I/O buffer to flush, usually csp->iob.
318 * Returns : On success, the number of bytes send are returned (zero
319 * indicates nothing was sent). On error, -1 is returned.
321 *********************************************************************/
322 extern long ssl_flush_socket(mbedtls_ssl_context *ssl, struct iob *iob)
324 /* Computing length of buffer part to send */
325 long len = iob->eod - iob->cur;
332 /* Sending data to given SSl context */
333 if (ssl_send_data(ssl, (const unsigned char *)iob->cur, (size_t)len) < 0)
337 iob->eod = iob->cur = iob->buf;
342 /*********************************************************************
344 * Function : ssl_debug_callback
346 * Description : Debug callback function for mbedtls library.
347 * Prints info into log file.
350 * 1 : ctx = File to save log in
351 * 2 : level = Debug level
352 * 3 : file = File calling debug message
353 * 4 : line = Line calling debug message
354 * 5 : str = Debug message
358 *********************************************************************/
359 static void ssl_debug_callback(void *ctx, int level, const char *file, int line, const char *str)
363 fprintf((FILE *)ctx, "%s:%04d: %s", file, line, str);
365 log_error(LOG_LEVEL_INFO, "SSL debug message: %s:%04d: %s", file, line, str);
370 /*********************************************************************
372 * Function : create_client_ssl_connection
374 * Description : Creates TLS/SSL secured connection with client
377 * 1 : csp = Current client state (buffers, headers, etc...)
379 * Returns : 0 on success, negative value if connection wasn't created
382 *********************************************************************/
383 extern int create_client_ssl_connection(struct client_state *csp)
385 /* Paths to certificates file and key file */
386 char *key_file = NULL;
387 char *ca_file = NULL;
388 char *cert_file = NULL;
390 char err_buf[ERROR_BUF_SIZE];
393 * Initializing mbedtls structures for TLS/SSL connection
395 mbedtls_net_init(&(csp->mbedtls_client_attr.socket_fd));
396 mbedtls_ssl_init(&(csp->mbedtls_client_attr.ssl));
397 mbedtls_ssl_config_init(&(csp->mbedtls_client_attr.conf));
398 mbedtls_x509_crt_init(&(csp->mbedtls_client_attr.server_cert));
399 mbedtls_pk_init(&(csp->mbedtls_client_attr.prim_key));
400 #if defined(MBEDTLS_SSL_CACHE_C)
401 mbedtls_ssl_cache_init(&(csp->mbedtls_client_attr.cache));
405 * Preparing hash of host for creating certificates
407 ret = host_to_hash(csp);
410 log_error(LOG_LEVEL_ERROR, "Generating hash of host failed: %d", ret);
416 * Preparing paths to certificates files and key file
418 ca_file = csp->config->ca_cert_file;
419 cert_file = make_certs_path(csp->config->certificate_directory,
420 (const char *)csp->http->hash_of_host_hex, CERT_FILE_TYPE);
421 key_file = make_certs_path(csp->config->certificate_directory,
422 (const char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
424 if (cert_file == NULL || key_file == NULL)
431 * Generating certificate for requested host. Mutex to prevent
432 * certificate and key inconsistence must be locked.
434 unsigned int cert_mutex_id = get_certificate_mutex_id(csp);
435 privoxy_mutex_lock(&(certificates_mutexes[cert_mutex_id]));
437 ret = generate_webpage_certificate(csp);
440 log_error(LOG_LEVEL_ERROR,
441 "Generate_webpage_certificate failed: %d", ret);
442 privoxy_mutex_unlock(&(certificates_mutexes[cert_mutex_id]));
446 privoxy_mutex_unlock(&(certificates_mutexes[cert_mutex_id]));
459 * Loading CA file, webpage certificate and key files
461 ret = mbedtls_x509_crt_parse_file(&(csp->mbedtls_client_attr.server_cert),
465 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
466 log_error(LOG_LEVEL_ERROR,
467 "Loading webpage certificate %s failed: %s", cert_file, err_buf);
472 ret = mbedtls_x509_crt_parse_file(&(csp->mbedtls_client_attr.server_cert),
476 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
477 log_error(LOG_LEVEL_ERROR,
478 "Loading CA certificate %s failed: %s", ca_file, err_buf);
483 ret = mbedtls_pk_parse_keyfile(&(csp->mbedtls_client_attr.prim_key),
487 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
488 log_error(LOG_LEVEL_ERROR,
489 "Loading and parsing webpage certificate private key %s failed: %s",
496 * Setting SSL parameters
498 ret = mbedtls_ssl_config_defaults(&(csp->mbedtls_client_attr.conf),
499 MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_TRANSPORT_STREAM,
500 MBEDTLS_SSL_PRESET_DEFAULT);
503 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
504 log_error(LOG_LEVEL_ERROR,
505 "mbedtls_ssl_config_defaults failed: %s", err_buf);
510 mbedtls_ssl_conf_rng(&(csp->mbedtls_client_attr.conf),
511 mbedtls_ctr_drbg_random, &ctr_drbg);
512 mbedtls_ssl_conf_dbg(&(csp->mbedtls_client_attr.conf),
513 ssl_debug_callback, stdout);
515 #if defined(MBEDTLS_SSL_CACHE_C)
516 mbedtls_ssl_conf_session_cache(&(csp->mbedtls_client_attr.conf),
517 &(csp->mbedtls_client_attr.cache), mbedtls_ssl_cache_get,
518 mbedtls_ssl_cache_set);
522 * Setting certificates
524 ret = mbedtls_ssl_conf_own_cert(&(csp->mbedtls_client_attr.conf),
525 &(csp->mbedtls_client_attr.server_cert),
526 &(csp->mbedtls_client_attr.prim_key));
529 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
530 log_error(LOG_LEVEL_ERROR,
531 "mbedtls_ssl_conf_own_cert failed: %s", err_buf);
536 ret = mbedtls_ssl_setup(&(csp->mbedtls_client_attr.ssl),
537 &(csp->mbedtls_client_attr.conf));
540 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
541 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_setup failed: %s", err_buf);
546 mbedtls_ssl_set_bio(&(csp->mbedtls_client_attr.ssl),
547 &(csp->mbedtls_client_attr.socket_fd), mbedtls_net_send,
548 mbedtls_net_recv, NULL);
549 mbedtls_ssl_session_reset(&(csp->mbedtls_client_attr.ssl));
552 * Setting socket fd in mbedtls_net_context structure. This structure
553 * can't be set by mbedtls functions, because we already have created
554 * a TCP connection when this function is called.
556 csp->mbedtls_client_attr.socket_fd.fd = csp->cfd;
559 * Handshake with client
561 log_error(LOG_LEVEL_CONNECT,
562 "Performing the TLS/SSL handshake with client. Hash of host: %s",
563 csp->http->hash_of_host_hex);
564 while ((ret = mbedtls_ssl_handshake(&(csp->mbedtls_client_attr.ssl))) != 0)
566 if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
567 ret != MBEDTLS_ERR_SSL_WANT_WRITE)
569 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
570 log_error(LOG_LEVEL_ERROR,
571 "medtls_ssl_handshake with client failed: %s", err_buf);
577 log_error(LOG_LEVEL_CONNECT, "Client successfully connected over TLS/SSL");
578 csp->ssl_with_client_is_opened = 1;
582 * Freeing allocated paths to files
587 /* Freeing structures if connection wasn't created successfully */
590 free_client_ssl_structures(csp);
596 /*********************************************************************
598 * Function : close_client_ssl_connection
600 * Description : Closes TLS/SSL connection with client. This function
601 * checks if this connection is already created.
604 * 1 : csp = Current client state (buffers, headers, etc...)
608 *********************************************************************/
609 extern void close_client_ssl_connection(struct client_state *csp)
613 if (csp->ssl_with_client_is_opened == 0)
619 * Notifying the peer that the connection is being closed.
622 ret = mbedtls_ssl_close_notify(&(csp->mbedtls_client_attr.ssl));
623 } while (ret == MBEDTLS_ERR_SSL_WANT_WRITE);
625 free_client_ssl_structures(csp);
626 csp->ssl_with_client_is_opened = 0;
630 /*********************************************************************
632 * Function : free_client_ssl_structures
634 * Description : Frees structures used for SSL communication with
638 * 1 : csp = Current client state (buffers, headers, etc...)
642 *********************************************************************/
643 static void free_client_ssl_structures(struct client_state *csp)
646 * We can't use function mbedtls_net_free, because this function
647 * inter alia close TCP connection on setted fd. Instead of this
648 * function, we change fd to -1, which is the same what does
649 * rest of mbedtls_net_free function.
651 csp->mbedtls_client_attr.socket_fd.fd = -1;
653 /* Freeing mbedtls structures */
654 mbedtls_x509_crt_free(&(csp->mbedtls_client_attr.server_cert));
655 mbedtls_pk_free(&(csp->mbedtls_client_attr.prim_key));
656 mbedtls_ssl_free(&(csp->mbedtls_client_attr.ssl));
657 mbedtls_ssl_config_free(&(csp->mbedtls_client_attr.conf));
658 #if defined(MBEDTLS_SSL_CACHE_C)
659 mbedtls_ssl_cache_free(&(csp->mbedtls_client_attr.cache));
664 /*********************************************************************
666 * Function : create_server_ssl_connection
668 * Description : Creates TLS/SSL secured connection with server.
671 * 1 : csp = Current client state (buffers, headers, etc...)
673 * Returns : 0 on success, negative value if connection wasn't created
676 *********************************************************************/
677 extern int create_server_ssl_connection(struct client_state *csp)
680 char err_buf[ERROR_BUF_SIZE];
681 char *trusted_cas_file = NULL;
682 int auth_mode = MBEDTLS_SSL_VERIFY_REQUIRED;
684 csp->server_cert_verification_result = SSL_CERT_NOT_VERIFIED;
685 csp->server_certs_chain.next = NULL;
687 /* Setting path to file with trusted CAs */
688 trusted_cas_file = csp->config->trusted_cas_file;
691 * Initializing mbedtls structures for TLS/SSL connection
693 mbedtls_net_init(&(csp->mbedtls_server_attr.socket_fd));
694 mbedtls_ssl_init(&(csp->mbedtls_server_attr.ssl));
695 mbedtls_ssl_config_init(&(csp->mbedtls_server_attr.conf));
696 mbedtls_x509_crt_init(&(csp->mbedtls_server_attr.ca_cert));
699 * Setting socket fd in mbedtls_net_context structure. This structure
700 * can't be set by mbedtls functions, because we already have created
701 * TCP connection when calling this function.
703 csp->mbedtls_server_attr.socket_fd.fd = csp->server_connection.sfd;
716 * Loading file with trusted CAs
718 ret = mbedtls_x509_crt_parse_file(&(csp->mbedtls_server_attr.ca_cert),
722 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
723 log_error(LOG_LEVEL_ERROR, "Loading trusted CAs file %s failed: %s",
724 trusted_cas_file, err_buf);
730 * Set TLS/SSL options
732 ret = mbedtls_ssl_config_defaults(&(csp->mbedtls_server_attr.conf),
733 MBEDTLS_SSL_IS_CLIENT,
734 MBEDTLS_SSL_TRANSPORT_STREAM,
735 MBEDTLS_SSL_PRESET_DEFAULT);
738 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
739 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_config_defaults failed: %s",
746 * Setting how strict should certificate verification be and other
747 * parameters for certificate verification
749 if (csp->dont_verify_certificate)
751 auth_mode = MBEDTLS_SSL_VERIFY_NONE;
754 mbedtls_ssl_conf_authmode(&(csp->mbedtls_server_attr.conf), auth_mode);
755 mbedtls_ssl_conf_ca_chain(&(csp->mbedtls_server_attr.conf),
756 &(csp->mbedtls_server_attr.ca_cert), NULL);
758 /* Setting callback function for certificates verification */
759 mbedtls_ssl_conf_verify(&(csp->mbedtls_server_attr.conf),
760 ssl_verify_callback, (void *)csp);
762 mbedtls_ssl_conf_rng(&(csp->mbedtls_server_attr.conf),
763 mbedtls_ctr_drbg_random, &ctr_drbg);
764 mbedtls_ssl_conf_dbg(&(csp->mbedtls_server_attr.conf),
765 ssl_debug_callback, stdout);
767 ret = mbedtls_ssl_setup(&(csp->mbedtls_server_attr.ssl),
768 &(csp->mbedtls_server_attr.conf));
771 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
772 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_setup failed: %s", err_buf);
778 * Set the hostname to check against the received server certificate
780 ret = mbedtls_ssl_set_hostname(&(csp->mbedtls_server_attr.ssl),
784 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
785 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_set_hostname failed: %s",
791 mbedtls_ssl_set_bio(&(csp->mbedtls_server_attr.ssl),
792 &(csp->mbedtls_server_attr.socket_fd), mbedtls_net_send,
793 mbedtls_net_recv, NULL);
796 * Handshake with server
798 log_error(LOG_LEVEL_CONNECT,
799 "Performing the TLS/SSL handshake with server");
801 while ((ret = mbedtls_ssl_handshake(&(csp->mbedtls_server_attr.ssl))) != 0)
803 if (ret != MBEDTLS_ERR_SSL_WANT_READ
804 && ret != MBEDTLS_ERR_SSL_WANT_WRITE)
806 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
808 if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED)
810 log_error(LOG_LEVEL_ERROR,
811 "Server certificate verification failed: %s", err_buf);
812 csp->server_cert_verification_result =
813 mbedtls_ssl_get_verify_result(&(csp->mbedtls_server_attr.ssl));
819 log_error(LOG_LEVEL_ERROR,
820 "mbedtls_ssl_handshake with server failed: %s", err_buf);
827 log_error(LOG_LEVEL_CONNECT, "Server successfully connected over TLS/SSL");
830 * Server certificate chain is valid, so we can clean
831 * chain, because we will not send it to client.
833 free_certificate_chain(csp);
835 csp->ssl_with_server_is_opened = 1;
836 csp->server_cert_verification_result =
837 mbedtls_ssl_get_verify_result(&(csp->mbedtls_server_attr.ssl));
840 /* Freeing structures if connection wasn't created successfully */
843 free_server_ssl_structures(csp);
850 /*********************************************************************
852 * Function : close_server_ssl_connection
854 * Description : Closes TLS/SSL connection with server. This function
855 * checks if this connection is already opened.
858 * 1 : csp = Current client state (buffers, headers, etc...)
862 *********************************************************************/
863 static void close_server_ssl_connection(struct client_state *csp)
867 if (csp->ssl_with_server_is_opened == 0)
873 * Notifying the peer that the connection is being closed.
876 ret = mbedtls_ssl_close_notify(&(csp->mbedtls_server_attr.ssl));
877 } while (ret == MBEDTLS_ERR_SSL_WANT_WRITE);
879 free_server_ssl_structures(csp);
880 csp->ssl_with_server_is_opened = 0;
884 /*********************************************************************
886 * Function : free_server_ssl_structures
888 * Description : Frees structures used for SSL communication with server
891 * 1 : csp = Current client state (buffers, headers, etc...)
895 *********************************************************************/
896 static void free_server_ssl_structures(struct client_state *csp)
899 * We can't use function mbedtls_net_free, because this function
900 * inter alia close TCP connection on setted fd. Instead of this
901 * function, we change fd to -1, which is the same what does
902 * rest of mbedtls_net_free function.
904 csp->mbedtls_client_attr.socket_fd.fd = -1;
906 mbedtls_x509_crt_free(&(csp->mbedtls_server_attr.ca_cert));
907 mbedtls_ssl_free(&(csp->mbedtls_server_attr.ssl));
908 mbedtls_ssl_config_free(&(csp->mbedtls_server_attr.conf));
912 /*********************************************************************
914 * Function : close_client_and_server_ssl_connections
916 * Description : Checks if client or server should use secured
917 * connection over SSL and if so, closes all of them.
920 * 1 : csp = Current client state (buffers, headers, etc...)
924 *********************************************************************/
925 extern void close_client_and_server_ssl_connections(struct client_state *csp)
927 if (client_use_ssl(csp) == 1)
929 close_client_ssl_connection(csp);
931 if (server_use_ssl(csp) == 1)
933 close_server_ssl_connection(csp);
937 /*====================== Certificates ======================*/
939 /*********************************************************************
941 * Function : write_certificate
943 * Description : Writes certificate into file.
946 * 1 : crt = certificate to write into file
947 * 2 : output_file = path to save certificate file
948 * 3 : f_rng = mbedtls_ctr_drbg_random
949 * 4 : p_rng = mbedtls_ctr_drbg_context
951 * Returns : Length of written certificate on success or negative value
954 *********************************************************************/
955 static int write_certificate(mbedtls_x509write_cert *crt, const char *output_file,
956 int(*f_rng)(void *, unsigned char *, size_t), void *p_rng)
960 unsigned char cert_buf[CERTIFICATE_BUF_SIZE + 1]; /* Buffer for certificate in PEM format + terminating NULL */
962 char err_buf[ERROR_BUF_SIZE];
964 memset(cert_buf, 0, sizeof(cert_buf));
967 * Writing certificate into PEM string. If buffer is too small, function
968 * returns specific error and no buffer overflow can happen.
970 if ((ret = mbedtls_x509write_crt_pem(crt, cert_buf,
971 sizeof(cert_buf) - 1, f_rng, p_rng)) != 0)
973 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
974 log_error(LOG_LEVEL_ERROR,
975 "Writing certificate into buffer failed: %s", err_buf);
979 len = strlen((char *)cert_buf);
982 * Saving certificate into file
984 if ((f = fopen(output_file, "w")) == NULL)
986 log_error(LOG_LEVEL_ERROR, "Opening file %s to save certificate failed",
991 if (fwrite(cert_buf, 1, len, f) != len)
993 log_error(LOG_LEVEL_ERROR,
994 "Writing certificate into file %s failed", output_file);
1005 /*********************************************************************
1007 * Function : write_private_key
1009 * Description : Writes private key into file and copies saved
1010 * content into given pointer to string. If function
1011 * returns 0 for success, this copy must be freed by
1015 * 1 : key = key to write into file
1016 * 2 : ret_buf = pointer to string with created key file content
1017 * 3 : key_file_path = path where to save key file
1019 * Returns : Length of written private key on success or negative value
1022 *********************************************************************/
1023 static int write_private_key(mbedtls_pk_context *key, unsigned char **ret_buf,
1024 const char *key_file_path)
1026 size_t len = 0; /* Length of created key */
1027 FILE *f = NULL; /* File to save certificate */
1029 char err_buf[ERROR_BUF_SIZE];
1031 /* Initializing buffer for key file content */
1032 *ret_buf = zalloc_or_die(PRIVATE_KEY_BUF_SIZE + 1);
1035 * Writing private key into PEM string
1037 if ((ret = mbedtls_pk_write_key_pem(key, *ret_buf, PRIVATE_KEY_BUF_SIZE)) != 0)
1039 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1040 log_error(LOG_LEVEL_ERROR,
1041 "Writing private key into PEM string failed: %s", err_buf);
1045 len = strlen((char *)*ret_buf);
1048 * Saving key into file
1050 if ((f = fopen(key_file_path, "wb")) == NULL)
1052 log_error(LOG_LEVEL_ERROR,
1053 "Opening file %s to save private key failed: %E",
1059 if (fwrite(*ret_buf, 1, len, f) != len)
1062 log_error(LOG_LEVEL_ERROR,
1063 "Writing private key into file %s failed",
1082 /*********************************************************************
1084 * Function : generate_key
1086 * Description : Tests if private key for host saved in csp already
1087 * exists. If this file doesn't exists, a new key is
1088 * generated and saved in a file. The generated key is also
1089 * copied into given parameter key_buf, which must be then
1090 * freed by caller. If file with key exists, key_buf
1091 * contain NULL and no private key is generated.
1094 * 1 : csp = Current client state (buffers, headers, etc...)
1095 * 2 : key_buf = buffer to save new generated key
1097 * Returns : -1 => Error while generating private key
1098 * 0 => Key already exists
1099 * >0 => Length of generated private key
1101 *********************************************************************/
1102 static int generate_key(struct client_state *csp, unsigned char **key_buf)
1104 mbedtls_pk_context key;
1105 key_options key_opt;
1107 char err_buf[ERROR_BUF_SIZE];
1109 key_opt.key_file_path = NULL;
1112 * Initializing structures for key generating
1114 mbedtls_pk_init(&key);
1117 * Preparing path for key file and other properties for generating key
1119 key_opt.type = MBEDTLS_PK_RSA;
1120 key_opt.rsa_keysize = RSA_KEYSIZE;
1122 key_opt.key_file_path = make_certs_path(csp->config->certificate_directory,
1123 (char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
1124 if (key_opt.key_file_path == NULL)
1131 * Test if key already exists. If so, we don't have to create it again.
1133 if (file_exists(key_opt.key_file_path) == 1)
1142 ret = seed_rng(csp);
1150 * Setting attributes of private key and generating it
1152 if ((ret = mbedtls_pk_setup(&key,
1153 mbedtls_pk_info_from_type(key_opt.type))) != 0)
1155 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1156 log_error(LOG_LEVEL_ERROR, "mbedtls_pk_setup failed: %s", err_buf);
1161 ret = mbedtls_rsa_gen_key(mbedtls_pk_rsa(key), mbedtls_ctr_drbg_random,
1162 &ctr_drbg, (unsigned)key_opt.rsa_keysize, RSA_KEY_PUBLIC_EXPONENT);
1165 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1166 log_error(LOG_LEVEL_ERROR, "Key generating failed: %s", err_buf);
1172 * Exporting private key into file
1174 if ((ret = write_private_key(&key, key_buf, key_opt.key_file_path)) < 0)
1176 log_error(LOG_LEVEL_ERROR,
1177 "Writing private key into file %s failed", key_opt.key_file_path);
1184 * Freeing used variables
1186 freez(key_opt.key_file_path);
1188 mbedtls_pk_free(&key);
1194 /*********************************************************************
1196 * Function : generate_webpage_certificate
1198 * Description : Creates certificate file in presetted directory.
1199 * If certificate already exists, no other certificate
1200 * will be created. Subject of certificate is named
1201 * by csp->http->host from parameter. This function also
1202 * triggers generating of private key for new certificate.
1205 * 1 : csp = Current client state (buffers, headers, etc...)
1207 * Returns : -1 => Error while creating certificate.
1208 * 0 => Certificate already exists.
1209 * >0 => Length of created certificate.
1211 *********************************************************************/
1212 static int generate_webpage_certificate(struct client_state *csp)
1214 mbedtls_x509_crt issuer_cert;
1215 mbedtls_pk_context loaded_issuer_key, loaded_subject_key;
1216 mbedtls_pk_context *issuer_key = &loaded_issuer_key;
1217 mbedtls_pk_context *subject_key = &loaded_subject_key;
1218 mbedtls_x509write_cert cert;
1221 unsigned char *key_buf = NULL; /* Buffer for created key */
1224 char err_buf[ERROR_BUF_SIZE];
1225 cert_options cert_opt;
1227 /* Paths to keys and certificates needed to create certificate */
1228 cert_opt.issuer_key = NULL;
1229 cert_opt.subject_key = NULL;
1230 cert_opt.issuer_crt = NULL;
1231 cert_opt.output_file = NULL;
1234 * Create key for requested host
1236 int subject_key_len = generate_key(csp, &key_buf);
1237 if (subject_key_len < 0)
1239 log_error(LOG_LEVEL_ERROR, "Key generating failed");
1244 * Initializing structures for certificate generating
1246 mbedtls_x509write_crt_init(&cert);
1247 mbedtls_x509write_crt_set_md_alg(&cert, CERT_SIGNATURE_ALGORITHM);
1248 mbedtls_pk_init(&loaded_issuer_key);
1249 mbedtls_pk_init(&loaded_subject_key);
1250 mbedtls_mpi_init(&serial);
1251 mbedtls_x509_crt_init(&issuer_cert);
1254 * Presetting parameters for certificate. We must compute total length
1257 size_t cert_params_len = strlen(CERT_PARAM_COMMON_NAME) +
1258 strlen(CERT_PARAM_ORGANIZATION) + strlen(CERT_PARAM_COUNTRY) +
1259 strlen(CERT_PARAM_ORG_UNIT) +
1260 3 * strlen(csp->http->host) + 1;
1261 char cert_params[cert_params_len];
1262 memset(cert_params, 0, cert_params_len);
1265 * Converting unsigned long serial number to char * serial number.
1266 * We must compute length of serial number in string + terminating null.
1268 unsigned long certificate_serial = get_certificate_serial(csp);
1269 int serial_num_size = snprintf(NULL, 0, "%lu", certificate_serial) + 1;
1270 if (serial_num_size <= 0)
1272 serial_num_size = 1;
1275 char serial_num_text[serial_num_size]; /* Buffer for serial number */
1276 ret = snprintf(serial_num_text, (size_t)serial_num_size, "%lu", certificate_serial);
1277 if (ret < 0 || ret >= serial_num_size)
1279 log_error(LOG_LEVEL_ERROR,
1280 "Converting certificate serial number into string failed");
1286 * Preparing parameters for certificate
1288 strlcpy(cert_params, CERT_PARAM_COMMON_NAME, cert_params_len);
1289 strlcat(cert_params, csp->http->host, cert_params_len);
1290 strlcat(cert_params, CERT_PARAM_ORGANIZATION, cert_params_len);
1291 strlcat(cert_params, csp->http->host, cert_params_len);
1292 strlcat(cert_params, CERT_PARAM_ORG_UNIT, cert_params_len);
1293 strlcat(cert_params, csp->http->host, cert_params_len);
1294 strlcat(cert_params, CERT_PARAM_COUNTRY, cert_params_len);
1296 cert_opt.issuer_crt = csp->config->ca_cert_file;
1297 cert_opt.issuer_key = csp->config->ca_key_file;
1298 cert_opt.subject_key = make_certs_path(csp->config->certificate_directory,
1299 (const char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
1300 cert_opt.output_file = make_certs_path(csp->config->certificate_directory,
1301 (const char *)csp->http->hash_of_host_hex, CERT_FILE_TYPE);
1303 if (cert_opt.subject_key == NULL || cert_opt.output_file == NULL)
1309 cert_opt.subject_pwd = CERT_SUBJECT_PASSWORD;
1310 cert_opt.issuer_pwd = csp->config->ca_password;
1311 cert_opt.subject_name = cert_params;
1312 cert_opt.not_before = GENERATED_CERT_VALID_FROM;
1313 cert_opt.not_after = GENERATED_CERT_VALID_TO;
1314 cert_opt.serial = serial_num_text;
1316 cert_opt.max_pathlen = -1;
1319 * Test if certificate exists and private key was already created
1321 if (file_exists(cert_opt.output_file) == 1 && subject_key_len == 0)
1330 ret = seed_rng(csp);
1338 * Parse serial to MPI
1340 ret = mbedtls_mpi_read_string(&serial, 10, cert_opt.serial);
1343 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1344 log_error(LOG_LEVEL_ERROR,
1345 "mbedtls_mpi_read_string failed: %s", err_buf);
1351 * Loading certificates
1353 ret = mbedtls_x509_crt_parse_file(&issuer_cert, cert_opt.issuer_crt);
1356 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1357 log_error(LOG_LEVEL_ERROR, "Loading issuer certificate %s failed: %s",
1358 cert_opt.issuer_crt, err_buf);
1363 ret = mbedtls_x509_dn_gets(cert_opt.issuer_name,
1364 sizeof(cert_opt.issuer_name), &issuer_cert.subject);
1367 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1368 log_error(LOG_LEVEL_ERROR, "mbedtls_x509_dn_gets failed: %s", err_buf);
1374 * Loading keys from file or from buffer
1376 if (key_buf != NULL && subject_key_len > 0)
1378 /* Key was created in this function and is stored in buffer */
1379 ret = mbedtls_pk_parse_key(&loaded_subject_key, key_buf,
1380 (size_t)(subject_key_len + 1), (unsigned const char *)
1381 cert_opt.subject_pwd, strlen(cert_opt.subject_pwd));
1385 /* Key wasn't created in this function, because it already existed */
1386 ret = mbedtls_pk_parse_keyfile(&loaded_subject_key,
1387 cert_opt.subject_key, cert_opt.subject_pwd);
1392 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1393 log_error(LOG_LEVEL_ERROR, "Parsing subject key %s failed: %s",
1394 cert_opt.subject_key, err_buf);
1399 ret = mbedtls_pk_parse_keyfile(&loaded_issuer_key, cert_opt.issuer_key,
1400 cert_opt.issuer_pwd);
1403 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1404 log_error(LOG_LEVEL_ERROR,
1405 "Parsing issuer key %s failed: %s", cert_opt.issuer_key, err_buf);
1411 * Check if key and issuer certificate match
1413 if (!mbedtls_pk_can_do(&issuer_cert.pk, MBEDTLS_PK_RSA) ||
1414 mbedtls_mpi_cmp_mpi(&mbedtls_pk_rsa(issuer_cert.pk)->N,
1415 &mbedtls_pk_rsa(*issuer_key)->N) != 0 ||
1416 mbedtls_mpi_cmp_mpi(&mbedtls_pk_rsa(issuer_cert.pk)->E,
1417 &mbedtls_pk_rsa(*issuer_key)->E) != 0)
1419 log_error(LOG_LEVEL_ERROR,
1420 "Issuer key doesn't match issuer certificate");
1425 mbedtls_x509write_crt_set_subject_key(&cert, subject_key);
1426 mbedtls_x509write_crt_set_issuer_key(&cert, issuer_key);
1429 * Setting parameters of signed certificate
1431 ret = mbedtls_x509write_crt_set_subject_name(&cert, cert_opt.subject_name);
1434 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1435 log_error(LOG_LEVEL_ERROR,
1436 "Setting subject name in signed certificate failed: %s", err_buf);
1441 ret = mbedtls_x509write_crt_set_issuer_name(&cert, cert_opt.issuer_name);
1444 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1445 log_error(LOG_LEVEL_ERROR,
1446 "Setting issuer name in signed certificate failed: %s", err_buf);
1451 ret = mbedtls_x509write_crt_set_serial(&cert, &serial);
1454 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1455 log_error(LOG_LEVEL_ERROR,
1456 "Setting serial number in signed certificate failed: %s", err_buf);
1461 ret = mbedtls_x509write_crt_set_validity(&cert, cert_opt.not_before,
1462 cert_opt.not_after);
1465 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1466 log_error(LOG_LEVEL_ERROR,
1467 "Setting validity in signed certificate failed: %s", err_buf);
1473 * Setting the basicConstraints extension for certificate
1475 ret = mbedtls_x509write_crt_set_basic_constraints(&cert, cert_opt.is_ca,
1476 cert_opt.max_pathlen);
1479 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1480 log_error(LOG_LEVEL_ERROR, "Setting the basicConstraints extension "
1481 "in signed certificate failed: %s", err_buf);
1486 #if defined(MBEDTLS_SHA1_C)
1487 /* Setting the subjectKeyIdentifier extension for certificate */
1488 ret = mbedtls_x509write_crt_set_subject_key_identifier(&cert);
1491 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1492 log_error(LOG_LEVEL_ERROR, "mbedtls_x509write_crt_set_subject_key_"
1493 "identifier failed: %s", err_buf);
1498 /* Setting the authorityKeyIdentifier extension for certificate */
1499 ret = mbedtls_x509write_crt_set_authority_key_identifier(&cert);
1502 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1503 log_error(LOG_LEVEL_ERROR, "mbedtls_x509write_crt_set_authority_key_"
1504 "identifier failed: %s", err_buf);
1508 #endif /* MBEDTLS_SHA1_C */
1511 * Writing certificate into file
1513 ret = write_certificate(&cert, cert_opt.output_file,
1514 mbedtls_ctr_drbg_random, &ctr_drbg);
1517 log_error(LOG_LEVEL_ERROR, "Writing certificate into file failed");
1523 * Freeing used structures
1525 mbedtls_x509write_crt_free(&cert);
1526 mbedtls_pk_free(&loaded_subject_key);
1527 mbedtls_pk_free(&loaded_issuer_key);
1528 mbedtls_mpi_free(&serial);
1529 mbedtls_x509_crt_free(&issuer_cert);
1531 freez(cert_opt.subject_key);
1532 freez(cert_opt.output_file);
1539 /*********************************************************************
1541 * Function : make_certs_path
1543 * Description : Creates path to file from three pieces. This fuction
1544 * takes parameters and puts them in one new mallocated
1545 * char * in correct order. Returned variable must be freed
1546 * by caller. This function is mainly used for creating
1547 * paths of certificates and keys files.
1550 * 1 : conf_dir = Name/path of directory where is the file.
1551 * '.' can be used for current directory.
1552 * 2 : file_name = Name of file in conf_dir without suffix.
1553 * 3 : suffix = Suffix of given file_name.
1555 * Returns : path => Path was built up successfully
1556 * NULL => Path can't be built up
1558 *********************************************************************/
1559 static char *make_certs_path(const char *conf_dir, const char *file_name,
1562 /* Test if all given parameters are valid */
1563 if (conf_dir == NULL || *conf_dir == '\0' || file_name == NULL ||
1564 *file_name == '\0' || suffix == NULL || *suffix == '\0')
1566 log_error(LOG_LEVEL_ERROR,
1567 "make_certs_path failed: bad input parameters");
1572 size_t path_size = strlen(conf_dir)
1573 + strlen(file_name) + strlen(suffix) + 2;
1575 /* Setting delimiter and editing path length */
1576 #if defined(_WIN32) || defined(__OS2__)
1577 char delim[] = "\\";
1579 #else /* ifndef _WIN32 || __OS2__ */
1581 #endif /* ifndef _WIN32 || __OS2__ */
1584 * Building up path from many parts
1587 if (*conf_dir != '/' && basedir && *basedir)
1590 * Replacing conf_dir with basedir. This new variable contains
1591 * absolute path to cwd.
1593 path_size += strlen(basedir) + 2;
1594 path = zalloc_or_die(path_size);
1596 strlcpy(path, basedir, path_size);
1597 strlcat(path, delim, path_size);
1598 strlcat(path, conf_dir, path_size);
1599 strlcat(path, delim, path_size);
1600 strlcat(path, file_name, path_size);
1601 strlcat(path, suffix, path_size);
1604 #endif /* defined unix */
1606 path = zalloc_or_die(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 don'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
1827 last->next = malloc_or_die(sizeof(struct certs_chain));
1828 last->next->next = NULL;
1829 memset(last->next->text_buf, 0, sizeof(last->next->text_buf));
1830 memset(last->next->file_buf, 0, sizeof(last->next->file_buf));
1833 * Saving certificate file into buffer
1835 if ((ret = mbedtls_pem_write_buffer(PEM_BEGIN_CRT, PEM_END_CRT,
1836 crt->raw.p, crt->raw.len, (unsigned char *)last->file_buf,
1837 sizeof(last->file_buf)-1, &olen)) != 0)
1843 * Saving certificate information into buffer
1845 mbedtls_x509_crt_info(last->text_buf, sizeof(last->text_buf) - 1,
1846 CERT_INFO_PREFIX, crt);
1852 /*********************************************************************
1854 * Function : free_certificate_chain
1856 * Description : Frees certificates linked list. This linked list is
1857 * used to save informations about certificates in
1861 * 1 : csp = Current client state (buffers, headers, etc...)
1865 *********************************************************************/
1866 static void free_certificate_chain(struct client_state *csp)
1868 struct certs_chain *cert = csp->server_certs_chain.next;
1870 /* Cleaning buffers */
1871 memset(csp->server_certs_chain.text_buf, 0,
1872 sizeof(csp->server_certs_chain.text_buf));
1873 memset(csp->server_certs_chain.file_buf, 0,
1874 sizeof(csp->server_certs_chain.file_buf));
1875 csp->server_certs_chain.next = NULL;
1877 /* Freeing memory in whole linked list */
1882 struct certs_chain *cert_for_free = cert;
1884 freez(cert_for_free);
1885 } while (cert != NULL);
1890 /*********************************************************************
1892 * Function : file_exists
1894 * Description : Tests if file exists and is readable.
1897 * 1 : path = Path to tested file.
1899 * Returns : 1 => File exists and is readable.
1900 * 0 => File doesn't exist or is not readable.
1902 *********************************************************************/
1903 static int file_exists(const char *path)
1906 if ((f = fopen(path, "r")) != NULL)
1916 /*********************************************************************
1918 * Function : host_to_hash
1920 * Description : Creates MD5 hash from host name. Host name is loaded
1921 * from structure csp and saved again into it.
1924 * 1 : csp = Current client state (buffers, headers, etc...)
1926 * Returns : 1 => Error while creating hash
1927 * 0 => Hash created successfully
1929 *********************************************************************/
1930 static int host_to_hash(struct client_state *csp)
1934 #if !defined(MBEDTLS_MD5_C)
1935 log_error(LOG_LEVEL_ERROR, "MBEDTLS_MD5_C is not defined. Can't create"
1936 "MD5 hash for certificate and key name.");
1939 memset(csp->http->hash_of_host, 0, sizeof(csp->http->hash_of_host));
1940 mbedtls_md5((unsigned char *)csp->http->host, strlen(csp->http->host),
1941 csp->http->hash_of_host);
1943 /* Converting hash into string with hex */
1947 if ((ret = sprintf((char *)csp->http->hash_of_host_hex + 2 * i, "%02x",
1948 csp->http->hash_of_host[i])) < 0)
1950 log_error(LOG_LEVEL_ERROR, "Sprintf return value: %d", ret);
1956 #endif /* MBEDTLS_MD5_C */
1960 /*********************************************************************
1962 * Function : tunnel_established_successfully
1964 * Description : Check if parent proxy server response contains
1965 * informations about successfully created connection with
1966 * destination server. (HTTP/... 2xx ...)
1969 * 1 : server_response = Buffer with parent proxy server response
1970 * 2 : response_len = Length of server_response
1972 * Returns : 1 => Connection created successfully
1973 * 0 => Connection wasn't created successfully
1975 *********************************************************************/
1976 extern int tunnel_established_successfully(const char *server_response,
1977 unsigned int response_len)
1979 unsigned int pos = 0;
1981 if (server_response == NULL)
1986 /* Tests if "HTTP/" string is at the begin of received response */
1987 if (strncmp(server_response, "HTTP/", 5) != 0)
1992 for (pos = 0; pos < response_len; pos++)
1994 if (server_response[pos] == ' ')
2001 * response_len -3 because of buffer end, response structure and 200 code.
2002 * There must be at least 3 chars after space.
2003 * End of buffer: ... 2xx'\0'
2006 if (pos >= (response_len - 3))
2011 /* Test HTTP status code */
2012 if (server_response[pos + 1] != '2')
2021 /*********************************************************************
2023 * Function : seed_rng
2025 * Description : Seeding the RNG for all SSL uses
2028 * 1 : csp = Current client state (buffers, headers, etc...)
2030 * Returns : -1 => RNG wasn't seed successfully
2031 * 0 => RNG is seeded successfully
2033 *********************************************************************/
2034 static int seed_rng(struct client_state *csp)
2037 char err_buf[ERROR_BUF_SIZE];
2039 if (rng_seeded == 0)
2041 privoxy_mutex_lock(&rng_mutex);
2042 if (rng_seeded == 0)
2044 mbedtls_ctr_drbg_init(&ctr_drbg);
2045 mbedtls_entropy_init(&entropy);
2046 ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func,
2050 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
2051 log_error(LOG_LEVEL_ERROR,
2052 "mbedtls_ctr_drbg_seed failed: %s", err_buf);
2053 privoxy_mutex_unlock(&rng_mutex);
2058 privoxy_mutex_unlock(&rng_mutex);