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 CERT_SIGNATURE_ALGORITHM MBEDTLS_MD_SHA256 /* The MD algorithm to use for the signature */
69 #define CERT_SERIAL_NUM_LENGTH 4 /* Bytes of hash to be used for creating serial number of certificate. Min=2 and max=16 */
70 #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 */
71 #define CERT_PARAM_COMMON_NAME "CN="
72 #define CERT_PARAM_ORGANIZATION ",O="
73 #define CERT_PARAM_ORG_UNIT ",OU="
74 #define CERT_PARAM_COUNTRY ",C=CZ"
75 #define KEY_FILE_TYPE ".pem"
76 #define CERT_FILE_TYPE ".crt"
77 #define CERT_SUBJECT_PASSWORD ""
78 #define CERT_INFO_PREFIX ""
81 * Properties of cert for generating
84 char *issuer_crt; /* filename of the issuer certificate */
85 char *subject_key; /* filename of the subject key file */
86 char *issuer_key; /* filename of the issuer key file */
87 const char *subject_pwd; /* password for the subject key file */
88 const char *issuer_pwd; /* password for the issuer key file */
89 char *output_file; /* where to store the constructed key file */
90 const char *subject_name; /* subject name for certificate */
91 char issuer_name[ISSUER_NAME_BUF_SIZE]; /* issuer name for certificate */
92 const char *not_before; /* validity period not before */
93 const char *not_after; /* validity period not after */
94 const char *serial; /* serial number string */
95 int is_ca; /* is a CA certificate */
96 int max_pathlen; /* maximum CA path length */
100 * Properties of key for generating
103 mbedtls_pk_type_t type; /* type of key to generate */
104 int rsa_keysize; /* length of key in bits */
105 char *key_file_path; /* filename of the key file */
108 static int generate_webpage_certificate(struct client_state *csp);
109 static char *make_certs_path(const char *conf_dir, const char *file_name, const char *suffix);
110 static int file_exists(const char *path);
111 static int host_to_hash(struct client_state *csp);
112 static int ssl_verify_callback(void *data, mbedtls_x509_crt *crt, int depth, uint32_t *flags);
113 static void free_certificate_chain(struct client_state *csp);
114 static unsigned long get_certificate_serial(struct client_state *csp);
115 static void free_client_ssl_structures(struct client_state *csp);
116 static void free_server_ssl_structures(struct client_state *csp);
117 static int seed_rng(struct client_state *csp);
119 /*********************************************************************
121 * Function : client_use_ssl
123 * Description : Tests if client in current client state structure
124 * should use SSL connection or standard connection.
127 * 1 : csp = Current client state (buffers, headers, etc...)
129 * Returns : If client should use TLS/SSL connection, 1 is returned.
130 * Otherwise 0 is returned.
132 *********************************************************************/
133 extern int client_use_ssl(const struct client_state *csp)
135 return csp->http->client_ssl;
139 /*********************************************************************
141 * Function : server_use_ssl
143 * Description : Tests if server in current client state structure
144 * should use SSL connection or standard connection.
147 * 1 : csp = Current client state (buffers, headers, etc...)
149 * Returns : If server should use TLS/SSL connection, 1 is returned.
150 * Otherwise 0 is returned.
152 *********************************************************************/
153 extern int server_use_ssl(const struct client_state *csp)
155 return csp->http->server_ssl;
159 /*********************************************************************
161 * Function : is_ssl_pending
163 * Description : Tests if there are some waiting data on ssl connection
166 * 1 : ssl = SSL context to test
168 * Returns : 0 => No data are pending
169 * >0 => Pending data length
171 *********************************************************************/
172 extern size_t is_ssl_pending(mbedtls_ssl_context *ssl)
179 return mbedtls_ssl_get_bytes_avail(ssl);
183 /*********************************************************************
185 * Function : ssl_send_data
187 * Description : Sends the content of buf (for n bytes) to given SSL
188 * connection context.
191 * 1 : ssl = SSL context to send data to
192 * 2 : buf = Pointer to data to be sent
193 * 3 : len = Length of data to be sent to the SSL context
195 * Returns : Length of sent data or negative value on error.
197 *********************************************************************/
198 extern int ssl_send_data(mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len)
201 size_t max_fragment_size = 0; /* Maximal length of data in one SSL fragment*/
202 int send_len = 0; /* length of one data part to send */
203 int pos = 0; /* Position of unsent part in buffer */
210 /* Getting maximal length of data sent in one fragment */
211 max_fragment_size = mbedtls_ssl_get_max_frag_len(ssl);
214 * Whole buffer must be sent in many fragments, because each fragment
215 * has its maximal length.
219 /* Compute length of data, that can be send in next fragment */
220 if ((pos + (int)max_fragment_size) > len)
222 send_len = (int)len - pos;
226 send_len = (int)max_fragment_size;
229 log_error(LOG_LEVEL_WRITING, "TLS: %N", send_len, buf+pos);
232 * Sending one part of the buffer
234 while ((ret = mbedtls_ssl_write(ssl,
235 (const unsigned char *)(buf + pos),
236 (size_t)send_len)) < 0)
238 if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
239 ret != MBEDTLS_ERR_SSL_WANT_WRITE)
241 char err_buf[ERROR_BUF_SIZE];
243 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
244 log_error(LOG_LEVEL_ERROR,
245 "Sending data over TLS/SSL failed: %s", err_buf);
249 /* Adding count of sent bytes to position in buffer */
250 pos = pos + send_len;
257 /*********************************************************************
259 * Function : ssl_recv_data
261 * Description : Receives data from given SSL context and puts
265 * 1 : ssl = SSL context to receive data from
266 * 2 : buf = Pointer to buffer where data will be written
267 * 3 : max_length = Maximum number of bytes to read
269 * Returns : Number of bytes read, 0 for EOF, or -1
272 *********************************************************************/
273 extern int ssl_recv_data(mbedtls_ssl_context *ssl, unsigned char *buf, size_t max_length)
276 memset(buf, 0, max_length);
279 * Receiving data from SSL context into buffer
283 ret = mbedtls_ssl_read(ssl, buf, max_length);
284 } while (ret == MBEDTLS_ERR_SSL_WANT_READ
285 || ret == MBEDTLS_ERR_SSL_WANT_WRITE);
289 char err_buf[ERROR_BUF_SIZE];
291 if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY)
293 log_error(LOG_LEVEL_CONNECT,
294 "The peer notified us that the connection is going to be closed");
297 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
298 log_error(LOG_LEVEL_ERROR,
299 "Receiving data over TLS/SSL failed: %s", err_buf);
304 log_error(LOG_LEVEL_RECEIVED, "TLS: %N", ret, buf);
310 /*********************************************************************
312 * Function : ssl_flush_socket
314 * Description : Send any pending "buffered" content with given
315 * SSL connection. Alternative to function flush_socket.
318 * 1 : ssl = SSL context to send buffer to
319 * 2 : iob = The I/O buffer to flush, usually csp->iob.
321 * Returns : On success, the number of bytes send are returned (zero
322 * indicates nothing was sent). On error, -1 is returned.
324 *********************************************************************/
325 extern long ssl_flush_socket(mbedtls_ssl_context *ssl, struct iob *iob)
327 /* Computing length of buffer part to send */
328 long len = iob->eod - iob->cur;
335 /* Sending data to given SSl context */
336 if (ssl_send_data(ssl, (const unsigned char *)iob->cur, (size_t)len) < 0)
340 iob->eod = iob->cur = iob->buf;
345 /*********************************************************************
347 * Function : ssl_debug_callback
349 * Description : Debug callback function for mbedtls library.
350 * Prints info into log file.
353 * 1 : ctx = File to save log in
354 * 2 : level = Debug level
355 * 3 : file = File calling debug message
356 * 4 : line = Line calling debug message
357 * 5 : str = Debug message
361 *********************************************************************/
362 static void ssl_debug_callback(void *ctx, int level, const char *file, int line, const char *str)
366 fprintf((FILE *)ctx, "%s:%04d: %s", file, line, str);
368 log_error(LOG_LEVEL_INFO, "SSL debug message: %s:%04d: %s", file, line, str);
373 /*********************************************************************
375 * Function : create_client_ssl_connection
377 * Description : Creates TLS/SSL secured connection with client
380 * 1 : csp = Current client state (buffers, headers, etc...)
382 * Returns : 0 on success, negative value if connection wasn't created
385 *********************************************************************/
386 extern int create_client_ssl_connection(struct client_state *csp)
388 /* Paths to certificates file and key file */
389 char *key_file = NULL;
390 char *ca_file = NULL;
391 char *cert_file = NULL;
393 char err_buf[ERROR_BUF_SIZE];
396 * Initializing mbedtls structures for TLS/SSL connection
398 mbedtls_net_init(&(csp->mbedtls_client_attr.socket_fd));
399 mbedtls_ssl_init(&(csp->mbedtls_client_attr.ssl));
400 mbedtls_ssl_config_init(&(csp->mbedtls_client_attr.conf));
401 mbedtls_x509_crt_init(&(csp->mbedtls_client_attr.server_cert));
402 mbedtls_pk_init(&(csp->mbedtls_client_attr.prim_key));
403 #if defined(MBEDTLS_SSL_CACHE_C)
404 mbedtls_ssl_cache_init(&(csp->mbedtls_client_attr.cache));
408 * Preparing hash of host for creating certificates
410 ret = host_to_hash(csp);
413 log_error(LOG_LEVEL_ERROR, "Generating hash of host failed: %d", ret);
419 * Preparing paths to certificates files and key file
421 ca_file = csp->config->ca_cert_file;
422 cert_file = make_certs_path(csp->config->certificate_directory,
423 (const char *)csp->http->hash_of_host_hex, CERT_FILE_TYPE);
424 key_file = make_certs_path(csp->config->certificate_directory,
425 (const char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
427 if (cert_file == NULL || key_file == NULL)
434 * Generating certificate for requested host. Mutex to prevent
435 * certificate and key inconsistence must be locked.
437 privoxy_mutex_lock(&certificate_mutex);
439 ret = generate_webpage_certificate(csp);
442 log_error(LOG_LEVEL_ERROR,
443 "Generate_webpage_certificate failed: %d", ret);
444 privoxy_mutex_unlock(&certificate_mutex);
448 privoxy_mutex_unlock(&certificate_mutex);
461 * Loading CA file, webpage certificate and key files
463 ret = mbedtls_x509_crt_parse_file(&(csp->mbedtls_client_attr.server_cert),
467 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
468 log_error(LOG_LEVEL_ERROR,
469 "Loading webpage certificate %s failed: %s", cert_file, err_buf);
474 ret = mbedtls_x509_crt_parse_file(&(csp->mbedtls_client_attr.server_cert),
478 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
479 log_error(LOG_LEVEL_ERROR,
480 "Loading CA certificate %s failed: %s", ca_file, err_buf);
485 ret = mbedtls_pk_parse_keyfile(&(csp->mbedtls_client_attr.prim_key),
489 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
490 log_error(LOG_LEVEL_ERROR,
491 "Loading and parsing webpage certificate private key %s failed: %s",
498 * Setting SSL parameters
500 ret = mbedtls_ssl_config_defaults(&(csp->mbedtls_client_attr.conf),
501 MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_TRANSPORT_STREAM,
502 MBEDTLS_SSL_PRESET_DEFAULT);
505 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
506 log_error(LOG_LEVEL_ERROR,
507 "mbedtls_ssl_config_defaults failed: %s", err_buf);
512 mbedtls_ssl_conf_rng(&(csp->mbedtls_client_attr.conf),
513 mbedtls_ctr_drbg_random, &ctr_drbg);
514 mbedtls_ssl_conf_dbg(&(csp->mbedtls_client_attr.conf),
515 ssl_debug_callback, stdout);
517 #if defined(MBEDTLS_SSL_CACHE_C)
518 mbedtls_ssl_conf_session_cache(&(csp->mbedtls_client_attr.conf),
519 &(csp->mbedtls_client_attr.cache), mbedtls_ssl_cache_get,
520 mbedtls_ssl_cache_set);
524 * Setting certificates
526 ret = mbedtls_ssl_conf_own_cert(&(csp->mbedtls_client_attr.conf),
527 &(csp->mbedtls_client_attr.server_cert),
528 &(csp->mbedtls_client_attr.prim_key));
531 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
532 log_error(LOG_LEVEL_ERROR,
533 "mbedtls_ssl_conf_own_cert failed: %s", err_buf);
538 ret = mbedtls_ssl_setup(&(csp->mbedtls_client_attr.ssl),
539 &(csp->mbedtls_client_attr.conf));
542 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
543 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_setup failed: %s", err_buf);
548 mbedtls_ssl_set_bio(&(csp->mbedtls_client_attr.ssl),
549 &(csp->mbedtls_client_attr.socket_fd), mbedtls_net_send,
550 mbedtls_net_recv, NULL);
551 mbedtls_ssl_session_reset(&(csp->mbedtls_client_attr.ssl));
554 * Setting socket fd in mbedtls_net_context structure. This structure
555 * can't be set by mbedtls functions, because we already have created
556 * a TCP connection when this function is called.
558 csp->mbedtls_client_attr.socket_fd.fd = csp->cfd;
561 * Handshake with client
563 log_error(LOG_LEVEL_CONNECT,
564 "Performing the TLS/SSL handshake with client. Hash of host: %s",
565 csp->http->hash_of_host_hex);
566 while ((ret = mbedtls_ssl_handshake(&(csp->mbedtls_client_attr.ssl))) != 0)
568 if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
569 ret != MBEDTLS_ERR_SSL_WANT_WRITE)
571 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
572 log_error(LOG_LEVEL_ERROR,
573 "medtls_ssl_handshake with client failed: %s", err_buf);
579 log_error(LOG_LEVEL_CONNECT, "Client successfully connected over TLS/SSL");
580 csp->ssl_with_client_is_opened = 1;
584 * Freeing allocated paths to files
589 /* Freeing structures if connection wasn't created successfully */
592 free_client_ssl_structures(csp);
598 /*********************************************************************
600 * Function : close_client_ssl_connection
602 * Description : Closes TLS/SSL connection with client. This function
603 * checks if this connection is already created.
606 * 1 : csp = Current client state (buffers, headers, etc...)
610 *********************************************************************/
611 extern void close_client_ssl_connection(struct client_state *csp)
615 if (csp->ssl_with_client_is_opened == 0)
621 * Notifying the peer that the connection is being closed.
624 ret = mbedtls_ssl_close_notify(&(csp->mbedtls_client_attr.ssl));
625 } while (ret == MBEDTLS_ERR_SSL_WANT_WRITE);
627 free_client_ssl_structures(csp);
628 csp->ssl_with_client_is_opened = 0;
632 /*********************************************************************
634 * Function : free_client_ssl_structures
636 * Description : Frees structures used for SSL communication with
640 * 1 : csp = Current client state (buffers, headers, etc...)
644 *********************************************************************/
645 static void free_client_ssl_structures(struct client_state *csp)
648 * We can't use function mbedtls_net_free, because this function
649 * inter alia close TCP connection on setted fd. Instead of this
650 * function, we change fd to -1, which is the same what does
651 * rest of mbedtls_net_free function.
653 csp->mbedtls_client_attr.socket_fd.fd = -1;
655 /* Freeing mbedtls structures */
656 mbedtls_x509_crt_free(&(csp->mbedtls_client_attr.server_cert));
657 mbedtls_pk_free(&(csp->mbedtls_client_attr.prim_key));
658 mbedtls_ssl_free(&(csp->mbedtls_client_attr.ssl));
659 mbedtls_ssl_config_free(&(csp->mbedtls_client_attr.conf));
660 #if defined(MBEDTLS_SSL_CACHE_C)
661 mbedtls_ssl_cache_free(&(csp->mbedtls_client_attr.cache));
666 /*********************************************************************
668 * Function : create_server_ssl_connection
670 * Description : Creates TLS/SSL secured connection with server.
673 * 1 : csp = Current client state (buffers, headers, etc...)
675 * Returns : 0 on success, negative value if connection wasn't created
678 *********************************************************************/
679 extern int create_server_ssl_connection(struct client_state *csp)
682 char err_buf[ERROR_BUF_SIZE];
683 char *trusted_cas_file = NULL;
684 int auth_mode = MBEDTLS_SSL_VERIFY_REQUIRED;
686 csp->server_cert_verification_result = SSL_CERT_NOT_VERIFIED;
687 csp->server_certs_chain.next = NULL;
689 /* Setting path to file with trusted CAs */
690 trusted_cas_file = csp->config->trusted_cas_file;
693 * Initializing mbedtls structures for TLS/SSL connection
695 mbedtls_net_init(&(csp->mbedtls_server_attr.socket_fd));
696 mbedtls_ssl_init(&(csp->mbedtls_server_attr.ssl));
697 mbedtls_ssl_config_init(&(csp->mbedtls_server_attr.conf));
698 mbedtls_x509_crt_init(&(csp->mbedtls_server_attr.ca_cert));
701 * Setting socket fd in mbedtls_net_context structure. This structure
702 * can't be set by mbedtls functions, because we already have created
703 * TCP connection when calling this function.
705 csp->mbedtls_server_attr.socket_fd.fd = csp->server_connection.sfd;
718 * Loading file with trusted CAs
720 ret = mbedtls_x509_crt_parse_file(&(csp->mbedtls_server_attr.ca_cert),
724 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
725 log_error(LOG_LEVEL_ERROR, "Loading trusted CAs file %s failed: %s",
726 trusted_cas_file, err_buf);
732 * Set TLS/SSL options
734 ret = mbedtls_ssl_config_defaults(&(csp->mbedtls_server_attr.conf),
735 MBEDTLS_SSL_IS_CLIENT,
736 MBEDTLS_SSL_TRANSPORT_STREAM,
737 MBEDTLS_SSL_PRESET_DEFAULT);
740 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
741 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_config_defaults failed: %s",
748 * Setting how strict should certificate verification be and other
749 * parameters for certificate verification
751 if (csp->dont_verify_certificate)
753 auth_mode = MBEDTLS_SSL_VERIFY_NONE;
756 mbedtls_ssl_conf_authmode(&(csp->mbedtls_server_attr.conf), auth_mode);
757 mbedtls_ssl_conf_ca_chain(&(csp->mbedtls_server_attr.conf),
758 &(csp->mbedtls_server_attr.ca_cert), NULL);
760 /* Setting callback function for certificates verification */
761 mbedtls_ssl_conf_verify(&(csp->mbedtls_server_attr.conf),
762 ssl_verify_callback, (void *)csp);
764 mbedtls_ssl_conf_rng(&(csp->mbedtls_server_attr.conf),
765 mbedtls_ctr_drbg_random, &ctr_drbg);
766 mbedtls_ssl_conf_dbg(&(csp->mbedtls_server_attr.conf),
767 ssl_debug_callback, stdout);
769 ret = mbedtls_ssl_setup(&(csp->mbedtls_server_attr.ssl),
770 &(csp->mbedtls_server_attr.conf));
773 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
774 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_setup failed: %s", err_buf);
780 * Set the hostname to check against the received server certificate
782 ret = mbedtls_ssl_set_hostname(&(csp->mbedtls_server_attr.ssl),
786 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
787 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_set_hostname failed: %s",
793 mbedtls_ssl_set_bio(&(csp->mbedtls_server_attr.ssl),
794 &(csp->mbedtls_server_attr.socket_fd), mbedtls_net_send,
795 mbedtls_net_recv, NULL);
798 * Handshake with server
800 log_error(LOG_LEVEL_CONNECT,
801 "Performing the TLS/SSL handshake with the server");
803 while ((ret = mbedtls_ssl_handshake(&(csp->mbedtls_server_attr.ssl))) != 0)
805 if (ret != MBEDTLS_ERR_SSL_WANT_READ
806 && ret != MBEDTLS_ERR_SSL_WANT_WRITE)
808 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
810 if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED)
812 char reason[INVALID_CERT_INFO_BUF_SIZE];
814 csp->server_cert_verification_result =
815 mbedtls_ssl_get_verify_result(&(csp->mbedtls_server_attr.ssl));
816 mbedtls_x509_crt_verify_info(reason, sizeof(reason), "",
817 csp->server_cert_verification_result);
819 /* Log the reason without the trailing new line */
820 log_error(LOG_LEVEL_ERROR,
821 "X509 certificate verification for %s failed: %N",
822 csp->http->hostport, strlen(reason)-1, reason);
827 log_error(LOG_LEVEL_ERROR,
828 "mbedtls_ssl_handshake with server failed: %s", err_buf);
835 log_error(LOG_LEVEL_CONNECT, "Server successfully connected over TLS/SSL");
838 * Server certificate chain is valid, so we can clean
839 * chain, because we will not send it to client.
841 free_certificate_chain(csp);
843 csp->ssl_with_server_is_opened = 1;
844 csp->server_cert_verification_result =
845 mbedtls_ssl_get_verify_result(&(csp->mbedtls_server_attr.ssl));
848 /* Freeing structures if connection wasn't created successfully */
851 free_server_ssl_structures(csp);
858 /*********************************************************************
860 * Function : close_server_ssl_connection
862 * Description : Closes TLS/SSL connection with server. This function
863 * checks if this connection is already opened.
866 * 1 : csp = Current client state (buffers, headers, etc...)
870 *********************************************************************/
871 static void close_server_ssl_connection(struct client_state *csp)
875 if (csp->ssl_with_server_is_opened == 0)
881 * Notifying the peer that the connection is being closed.
884 ret = mbedtls_ssl_close_notify(&(csp->mbedtls_server_attr.ssl));
885 } while (ret == MBEDTLS_ERR_SSL_WANT_WRITE);
887 free_server_ssl_structures(csp);
888 csp->ssl_with_server_is_opened = 0;
892 /*********************************************************************
894 * Function : free_server_ssl_structures
896 * Description : Frees structures used for SSL communication with server
899 * 1 : csp = Current client state (buffers, headers, etc...)
903 *********************************************************************/
904 static void free_server_ssl_structures(struct client_state *csp)
907 * We can't use function mbedtls_net_free, because this function
908 * inter alia close TCP connection on setted fd. Instead of this
909 * function, we change fd to -1, which is the same what does
910 * rest of mbedtls_net_free function.
912 csp->mbedtls_server_attr.socket_fd.fd = -1;
914 mbedtls_x509_crt_free(&(csp->mbedtls_server_attr.ca_cert));
915 mbedtls_ssl_free(&(csp->mbedtls_server_attr.ssl));
916 mbedtls_ssl_config_free(&(csp->mbedtls_server_attr.conf));
920 /*********************************************************************
922 * Function : close_client_and_server_ssl_connections
924 * Description : Checks if client or server should use secured
925 * connection over SSL and if so, closes all of them.
928 * 1 : csp = Current client state (buffers, headers, etc...)
932 *********************************************************************/
933 extern void close_client_and_server_ssl_connections(struct client_state *csp)
935 if (client_use_ssl(csp) == 1)
937 close_client_ssl_connection(csp);
939 if (server_use_ssl(csp) == 1)
941 close_server_ssl_connection(csp);
945 /*====================== Certificates ======================*/
947 /*********************************************************************
949 * Function : write_certificate
951 * Description : Writes certificate into file.
954 * 1 : crt = certificate to write into file
955 * 2 : output_file = path to save certificate file
956 * 3 : f_rng = mbedtls_ctr_drbg_random
957 * 4 : p_rng = mbedtls_ctr_drbg_context
959 * Returns : Length of written certificate on success or negative value
962 *********************************************************************/
963 static int write_certificate(mbedtls_x509write_cert *crt, const char *output_file,
964 int(*f_rng)(void *, unsigned char *, size_t), void *p_rng)
968 unsigned char cert_buf[CERTIFICATE_BUF_SIZE + 1]; /* Buffer for certificate in PEM format + terminating NULL */
970 char err_buf[ERROR_BUF_SIZE];
972 memset(cert_buf, 0, sizeof(cert_buf));
975 * Writing certificate into PEM string. If buffer is too small, function
976 * returns specific error and no buffer overflow can happen.
978 if ((ret = mbedtls_x509write_crt_pem(crt, cert_buf,
979 sizeof(cert_buf) - 1, f_rng, p_rng)) != 0)
981 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
982 log_error(LOG_LEVEL_ERROR,
983 "Writing certificate into buffer failed: %s", err_buf);
987 len = strlen((char *)cert_buf);
990 * Saving certificate into file
992 if ((f = fopen(output_file, "w")) == NULL)
994 log_error(LOG_LEVEL_ERROR, "Opening file %s to save certificate failed",
999 if (fwrite(cert_buf, 1, len, f) != len)
1001 log_error(LOG_LEVEL_ERROR,
1002 "Writing certificate into file %s failed", output_file);
1013 /*********************************************************************
1015 * Function : write_private_key
1017 * Description : Writes private key into file and copies saved
1018 * content into given pointer to string. If function
1019 * returns 0 for success, this copy must be freed by
1023 * 1 : key = key to write into file
1024 * 2 : ret_buf = pointer to string with created key file content
1025 * 3 : key_file_path = path where to save key file
1027 * Returns : Length of written private key on success or negative value
1030 *********************************************************************/
1031 static int write_private_key(mbedtls_pk_context *key, unsigned char **ret_buf,
1032 const char *key_file_path)
1034 size_t len = 0; /* Length of created key */
1035 FILE *f = NULL; /* File to save certificate */
1037 char err_buf[ERROR_BUF_SIZE];
1039 /* Initializing buffer for key file content */
1040 *ret_buf = zalloc_or_die(PRIVATE_KEY_BUF_SIZE + 1);
1043 * Writing private key into PEM string
1045 if ((ret = mbedtls_pk_write_key_pem(key, *ret_buf, PRIVATE_KEY_BUF_SIZE)) != 0)
1047 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1048 log_error(LOG_LEVEL_ERROR,
1049 "Writing private key into PEM string failed: %s", err_buf);
1053 len = strlen((char *)*ret_buf);
1056 * Saving key into file
1058 if ((f = fopen(key_file_path, "wb")) == NULL)
1060 log_error(LOG_LEVEL_ERROR,
1061 "Opening file %s to save private key failed: %E",
1067 if (fwrite(*ret_buf, 1, len, f) != len)
1070 log_error(LOG_LEVEL_ERROR,
1071 "Writing private key into file %s failed",
1090 /*********************************************************************
1092 * Function : generate_key
1094 * Description : Tests if private key for host saved in csp already
1095 * exists. If this file doesn't exists, a new key is
1096 * generated and saved in a file. The generated key is also
1097 * copied into given parameter key_buf, which must be then
1098 * freed by caller. If file with key exists, key_buf
1099 * contain NULL and no private key is generated.
1102 * 1 : csp = Current client state (buffers, headers, etc...)
1103 * 2 : key_buf = buffer to save new generated key
1105 * Returns : -1 => Error while generating private key
1106 * 0 => Key already exists
1107 * >0 => Length of generated private key
1109 *********************************************************************/
1110 static int generate_key(struct client_state *csp, unsigned char **key_buf)
1112 mbedtls_pk_context key;
1113 key_options key_opt;
1115 char err_buf[ERROR_BUF_SIZE];
1117 key_opt.key_file_path = NULL;
1120 * Initializing structures for key generating
1122 mbedtls_pk_init(&key);
1125 * Preparing path for key file and other properties for generating key
1127 key_opt.type = MBEDTLS_PK_RSA;
1128 key_opt.rsa_keysize = RSA_KEYSIZE;
1130 key_opt.key_file_path = make_certs_path(csp->config->certificate_directory,
1131 (char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
1132 if (key_opt.key_file_path == NULL)
1139 * Test if key already exists. If so, we don't have to create it again.
1141 if (file_exists(key_opt.key_file_path) == 1)
1150 ret = seed_rng(csp);
1158 * Setting attributes of private key and generating it
1160 if ((ret = mbedtls_pk_setup(&key,
1161 mbedtls_pk_info_from_type(key_opt.type))) != 0)
1163 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1164 log_error(LOG_LEVEL_ERROR, "mbedtls_pk_setup failed: %s", err_buf);
1169 ret = mbedtls_rsa_gen_key(mbedtls_pk_rsa(key), mbedtls_ctr_drbg_random,
1170 &ctr_drbg, (unsigned)key_opt.rsa_keysize, RSA_KEY_PUBLIC_EXPONENT);
1173 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1174 log_error(LOG_LEVEL_ERROR, "Key generating failed: %s", err_buf);
1180 * Exporting private key into file
1182 if ((ret = write_private_key(&key, key_buf, key_opt.key_file_path)) < 0)
1184 log_error(LOG_LEVEL_ERROR,
1185 "Writing private key into file %s failed", key_opt.key_file_path);
1192 * Freeing used variables
1194 freez(key_opt.key_file_path);
1196 mbedtls_pk_free(&key);
1202 /*********************************************************************
1204 * Function : ssl_certificate_is_invalid
1206 * Description : Checks whether or not a certificate is valid.
1207 * Currently only checks that the certificate can be
1208 * parsed and that the "valid to" date is in the future.
1211 * 1 : cert_file = The certificate to check
1213 * Returns : 0 => The certificate is valid.
1214 * 1 => The certificate is invalid
1216 *********************************************************************/
1217 static int ssl_certificate_is_invalid(const char *cert_file)
1219 mbedtls_x509_crt cert;
1222 mbedtls_x509_crt_init(&cert);
1224 ret = mbedtls_x509_crt_parse_file(&cert, cert_file);
1227 char err_buf[ERROR_BUF_SIZE];
1229 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1230 log_error(LOG_LEVEL_ERROR,
1231 "Loading certificate %s to check validity failed: %s",
1232 cert_file, err_buf);
1233 mbedtls_x509_crt_free(&cert);
1237 if (mbedtls_x509_time_is_past(&cert.valid_to))
1239 mbedtls_x509_crt_free(&cert);
1244 mbedtls_x509_crt_free(&cert);
1251 /*********************************************************************
1253 * Function : generate_certificate_valid_date
1255 * Description : Turns a time_t into the format expected by mbedTLS.
1258 * 1 : time_spec = The timestamp to convert
1259 * 2 : buffer = The buffer to write the date to
1260 * 3 : buffer_size = The size of the buffer
1262 * Returns : 0 => The conversion worked
1263 * 1 => The conversion failed
1265 *********************************************************************/
1266 static int generate_certificate_valid_date(time_t time_spec, char *buffer,
1269 struct tm valid_date;
1272 #ifndef HAVE_GMTIME_R
1273 #error HTTP inspection currently requires gmtime_r() which seems to be missing
1275 if (NULL == gmtime_r(&time_spec, &valid_date))
1280 ret = strftime(buffer, buffer_size, "%Y%m%d%H%M%S", &valid_date);
1291 /*********************************************************************
1293 * Function : get_certificate_valid_from_date
1295 * Description : Generates a "valid from" date in the format
1296 * expected by mbedTLS.
1299 * 1 : buffer = The buffer to write the date to
1300 * 2 : buffer_size = The size of the buffer
1302 * Returns : 0 => The generation worked
1303 * 1 => The generation failed
1305 *********************************************************************/
1306 static int get_certificate_valid_from_date(char *buffer, size_t buffer_size)
1310 time_spec = time(NULL);
1311 /* 1 month in the past */
1312 time_spec -= 30 * 24 * 60 * 60;
1314 return generate_certificate_valid_date(time_spec, buffer, buffer_size);
1319 /*********************************************************************
1321 * Function : get_certificate_valid_to_date
1323 * Description : Generates a "valid to" date in the format
1324 * expected by mbedTLS.
1327 * 1 : buffer = The buffer to write the date to
1328 * 2 : buffer_size = The size of the buffer
1330 * Returns : 0 => The generation worked
1331 * 1 => The generation failed
1333 *********************************************************************/
1334 static int get_certificate_valid_to_date(char *buffer, size_t buffer_size)
1338 time_spec = time(NULL);
1339 /* Three months in the future */
1340 time_spec += 90 * 24 * 60 * 60;
1342 return generate_certificate_valid_date(time_spec, buffer, buffer_size);
1347 /*********************************************************************
1349 * Function : generate_webpage_certificate
1351 * Description : Creates certificate file in presetted directory.
1352 * If certificate already exists, no other certificate
1353 * will be created. Subject of certificate is named
1354 * by csp->http->host from parameter. This function also
1355 * triggers generating of private key for new certificate.
1358 * 1 : csp = Current client state (buffers, headers, etc...)
1360 * Returns : -1 => Error while creating certificate.
1361 * 0 => Certificate already exists.
1362 * >0 => Length of created certificate.
1364 *********************************************************************/
1365 static int generate_webpage_certificate(struct client_state *csp)
1367 mbedtls_x509_crt issuer_cert;
1368 mbedtls_pk_context loaded_issuer_key, loaded_subject_key;
1369 mbedtls_pk_context *issuer_key = &loaded_issuer_key;
1370 mbedtls_pk_context *subject_key = &loaded_subject_key;
1371 mbedtls_x509write_cert cert;
1374 unsigned char *key_buf = NULL; /* Buffer for created key */
1377 char err_buf[ERROR_BUF_SIZE];
1378 cert_options cert_opt;
1379 char cert_valid_from[15];
1380 char cert_valid_to[15];
1382 /* Paths to keys and certificates needed to create certificate */
1383 cert_opt.issuer_key = NULL;
1384 cert_opt.subject_key = NULL;
1385 cert_opt.issuer_crt = NULL;
1387 cert_opt.output_file = make_certs_path(csp->config->certificate_directory,
1388 (const char *)csp->http->hash_of_host_hex, CERT_FILE_TYPE);
1389 if (cert_opt.output_file == NULL)
1394 cert_opt.subject_key = make_certs_path(csp->config->certificate_directory,
1395 (const char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
1396 if (cert_opt.subject_key == NULL)
1398 freez(cert_opt.output_file);
1402 if (file_exists(cert_opt.output_file) == 1)
1404 /* The file exists, but is it valid? */
1405 if (ssl_certificate_is_invalid(cert_opt.output_file))
1407 log_error(LOG_LEVEL_CONNECT,
1408 "Certificate %s is no longer valid. Removing it.",
1409 cert_opt.output_file);
1410 if (unlink(cert_opt.output_file))
1412 log_error(LOG_LEVEL_ERROR, "Failed to unlink %s: %E",
1413 cert_opt.output_file);
1415 freez(cert_opt.output_file);
1416 freez(cert_opt.subject_key);
1420 if (unlink(cert_opt.subject_key))
1422 log_error(LOG_LEVEL_ERROR, "Failed to unlink %s: %E",
1423 cert_opt.subject_key);
1425 freez(cert_opt.output_file);
1426 freez(cert_opt.subject_key);
1433 freez(cert_opt.output_file);
1434 freez(cert_opt.subject_key);
1441 * Create key for requested host
1443 int subject_key_len = generate_key(csp, &key_buf);
1444 if (subject_key_len < 0)
1446 freez(cert_opt.output_file);
1447 freez(cert_opt.subject_key);
1448 log_error(LOG_LEVEL_ERROR, "Key generating failed");
1453 * Initializing structures for certificate generating
1455 mbedtls_x509write_crt_init(&cert);
1456 mbedtls_x509write_crt_set_md_alg(&cert, CERT_SIGNATURE_ALGORITHM);
1457 mbedtls_pk_init(&loaded_issuer_key);
1458 mbedtls_pk_init(&loaded_subject_key);
1459 mbedtls_mpi_init(&serial);
1460 mbedtls_x509_crt_init(&issuer_cert);
1463 * Presetting parameters for certificate. We must compute total length
1466 size_t cert_params_len = strlen(CERT_PARAM_COMMON_NAME) +
1467 strlen(CERT_PARAM_ORGANIZATION) + strlen(CERT_PARAM_COUNTRY) +
1468 strlen(CERT_PARAM_ORG_UNIT) +
1469 3 * strlen(csp->http->host) + 1;
1470 char cert_params[cert_params_len];
1471 memset(cert_params, 0, cert_params_len);
1474 * Converting unsigned long serial number to char * serial number.
1475 * We must compute length of serial number in string + terminating null.
1477 unsigned long certificate_serial = get_certificate_serial(csp);
1478 unsigned long certificate_serial_time = (unsigned long)time(NULL);
1479 int serial_num_size = snprintf(NULL, 0, "%lu%lu",
1480 certificate_serial_time, certificate_serial) + 1;
1481 if (serial_num_size <= 0)
1483 serial_num_size = 1;
1486 char serial_num_text[serial_num_size]; /* Buffer for serial number */
1487 ret = snprintf(serial_num_text, (size_t)serial_num_size, "%lu%lu",
1488 certificate_serial_time, certificate_serial);
1489 if (ret < 0 || ret >= serial_num_size)
1491 log_error(LOG_LEVEL_ERROR,
1492 "Converting certificate serial number into string failed");
1498 * Preparing parameters for certificate
1500 strlcpy(cert_params, CERT_PARAM_COMMON_NAME, cert_params_len);
1501 strlcat(cert_params, csp->http->host, cert_params_len);
1502 strlcat(cert_params, CERT_PARAM_ORGANIZATION, cert_params_len);
1503 strlcat(cert_params, csp->http->host, cert_params_len);
1504 strlcat(cert_params, CERT_PARAM_ORG_UNIT, cert_params_len);
1505 strlcat(cert_params, csp->http->host, cert_params_len);
1506 strlcat(cert_params, CERT_PARAM_COUNTRY, cert_params_len);
1508 cert_opt.issuer_crt = csp->config->ca_cert_file;
1509 cert_opt.issuer_key = csp->config->ca_key_file;
1511 if (get_certificate_valid_from_date(cert_valid_from, sizeof(cert_valid_from))
1512 || get_certificate_valid_to_date(cert_valid_to, sizeof(cert_valid_to)))
1514 log_error(LOG_LEVEL_ERROR, "Generating one of the validity dates failed");
1519 cert_opt.subject_pwd = CERT_SUBJECT_PASSWORD;
1520 cert_opt.issuer_pwd = csp->config->ca_password;
1521 cert_opt.subject_name = cert_params;
1522 cert_opt.not_before = cert_valid_from;
1523 cert_opt.not_after = cert_valid_to;
1524 cert_opt.serial = serial_num_text;
1526 cert_opt.max_pathlen = -1;
1529 * Test if the private key was already created.
1530 * XXX: Can this still happen?
1532 if (subject_key_len == 0)
1534 log_error(LOG_LEVEL_ERROR, "Subject key was already created");
1542 ret = seed_rng(csp);
1550 * Parse serial to MPI
1552 ret = mbedtls_mpi_read_string(&serial, 10, cert_opt.serial);
1555 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1556 log_error(LOG_LEVEL_ERROR,
1557 "mbedtls_mpi_read_string failed: %s", err_buf);
1563 * Loading certificates
1565 ret = mbedtls_x509_crt_parse_file(&issuer_cert, cert_opt.issuer_crt);
1568 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1569 log_error(LOG_LEVEL_ERROR, "Loading issuer certificate %s failed: %s",
1570 cert_opt.issuer_crt, err_buf);
1575 ret = mbedtls_x509_dn_gets(cert_opt.issuer_name,
1576 sizeof(cert_opt.issuer_name), &issuer_cert.subject);
1579 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1580 log_error(LOG_LEVEL_ERROR, "mbedtls_x509_dn_gets failed: %s", err_buf);
1586 * Loading keys from file or from buffer
1588 if (key_buf != NULL && subject_key_len > 0)
1590 /* Key was created in this function and is stored in buffer */
1591 ret = mbedtls_pk_parse_key(&loaded_subject_key, key_buf,
1592 (size_t)(subject_key_len + 1), (unsigned const char *)
1593 cert_opt.subject_pwd, strlen(cert_opt.subject_pwd));
1597 /* Key wasn't created in this function, because it already existed */
1598 ret = mbedtls_pk_parse_keyfile(&loaded_subject_key,
1599 cert_opt.subject_key, cert_opt.subject_pwd);
1604 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1605 log_error(LOG_LEVEL_ERROR, "Parsing subject key %s failed: %s",
1606 cert_opt.subject_key, err_buf);
1611 ret = mbedtls_pk_parse_keyfile(&loaded_issuer_key, cert_opt.issuer_key,
1612 cert_opt.issuer_pwd);
1615 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1616 log_error(LOG_LEVEL_ERROR,
1617 "Parsing issuer key %s failed: %s", cert_opt.issuer_key, err_buf);
1623 * Check if key and issuer certificate match
1625 if (!mbedtls_pk_can_do(&issuer_cert.pk, MBEDTLS_PK_RSA) ||
1626 mbedtls_mpi_cmp_mpi(&mbedtls_pk_rsa(issuer_cert.pk)->N,
1627 &mbedtls_pk_rsa(*issuer_key)->N) != 0 ||
1628 mbedtls_mpi_cmp_mpi(&mbedtls_pk_rsa(issuer_cert.pk)->E,
1629 &mbedtls_pk_rsa(*issuer_key)->E) != 0)
1631 log_error(LOG_LEVEL_ERROR,
1632 "Issuer key doesn't match issuer certificate");
1637 mbedtls_x509write_crt_set_subject_key(&cert, subject_key);
1638 mbedtls_x509write_crt_set_issuer_key(&cert, issuer_key);
1641 * Setting parameters of signed certificate
1643 ret = mbedtls_x509write_crt_set_subject_name(&cert, cert_opt.subject_name);
1646 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1647 log_error(LOG_LEVEL_ERROR,
1648 "Setting subject name in signed certificate failed: %s", err_buf);
1653 ret = mbedtls_x509write_crt_set_issuer_name(&cert, cert_opt.issuer_name);
1656 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1657 log_error(LOG_LEVEL_ERROR,
1658 "Setting issuer name in signed certificate failed: %s", err_buf);
1663 ret = mbedtls_x509write_crt_set_serial(&cert, &serial);
1666 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1667 log_error(LOG_LEVEL_ERROR,
1668 "Setting serial number in signed certificate failed: %s", err_buf);
1673 ret = mbedtls_x509write_crt_set_validity(&cert, cert_opt.not_before,
1674 cert_opt.not_after);
1677 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1678 log_error(LOG_LEVEL_ERROR,
1679 "Setting validity in signed certificate failed: %s", err_buf);
1685 * Setting the basicConstraints extension for certificate
1687 ret = mbedtls_x509write_crt_set_basic_constraints(&cert, cert_opt.is_ca,
1688 cert_opt.max_pathlen);
1691 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1692 log_error(LOG_LEVEL_ERROR, "Setting the basicConstraints extension "
1693 "in signed certificate failed: %s", err_buf);
1698 #if defined(MBEDTLS_SHA1_C)
1699 /* Setting the subjectKeyIdentifier extension for certificate */
1700 ret = mbedtls_x509write_crt_set_subject_key_identifier(&cert);
1703 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1704 log_error(LOG_LEVEL_ERROR, "mbedtls_x509write_crt_set_subject_key_"
1705 "identifier failed: %s", err_buf);
1710 /* Setting the authorityKeyIdentifier extension for certificate */
1711 ret = mbedtls_x509write_crt_set_authority_key_identifier(&cert);
1714 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1715 log_error(LOG_LEVEL_ERROR, "mbedtls_x509write_crt_set_authority_key_"
1716 "identifier failed: %s", err_buf);
1720 #endif /* MBEDTLS_SHA1_C */
1723 * Writing certificate into file
1725 ret = write_certificate(&cert, cert_opt.output_file,
1726 mbedtls_ctr_drbg_random, &ctr_drbg);
1729 log_error(LOG_LEVEL_ERROR, "Writing certificate into file failed");
1735 * Freeing used structures
1737 mbedtls_x509write_crt_free(&cert);
1738 mbedtls_pk_free(&loaded_subject_key);
1739 mbedtls_pk_free(&loaded_issuer_key);
1740 mbedtls_mpi_free(&serial);
1741 mbedtls_x509_crt_free(&issuer_cert);
1743 freez(cert_opt.subject_key);
1744 freez(cert_opt.output_file);
1751 /*********************************************************************
1753 * Function : make_certs_path
1755 * Description : Creates path to file from three pieces. This function
1756 * takes parameters and puts them in one new mallocated
1757 * char * in correct order. Returned variable must be freed
1758 * by caller. This function is mainly used for creating
1759 * paths of certificates and keys files.
1762 * 1 : conf_dir = Name/path of directory where is the file.
1763 * '.' can be used for current directory.
1764 * 2 : file_name = Name of file in conf_dir without suffix.
1765 * 3 : suffix = Suffix of given file_name.
1767 * Returns : path => Path was built up successfully
1768 * NULL => Path can't be built up
1770 *********************************************************************/
1771 static char *make_certs_path(const char *conf_dir, const char *file_name,
1774 /* Test if all given parameters are valid */
1775 if (conf_dir == NULL || *conf_dir == '\0' || file_name == NULL ||
1776 *file_name == '\0' || suffix == NULL || *suffix == '\0')
1778 log_error(LOG_LEVEL_ERROR,
1779 "make_certs_path failed: bad input parameters");
1784 size_t path_size = strlen(conf_dir)
1785 + strlen(file_name) + strlen(suffix) + 2;
1787 /* Setting delimiter and editing path length */
1788 #if defined(_WIN32) || defined(__OS2__)
1789 char delim[] = "\\";
1791 #else /* ifndef _WIN32 || __OS2__ */
1793 #endif /* ifndef _WIN32 || __OS2__ */
1796 * Building up path from many parts
1799 if (*conf_dir != '/' && basedir && *basedir)
1802 * Replacing conf_dir with basedir. This new variable contains
1803 * absolute path to cwd.
1805 path_size += strlen(basedir) + 2;
1806 path = zalloc_or_die(path_size);
1808 strlcpy(path, basedir, path_size);
1809 strlcat(path, delim, path_size);
1810 strlcat(path, conf_dir, path_size);
1811 strlcat(path, delim, path_size);
1812 strlcat(path, file_name, path_size);
1813 strlcat(path, suffix, path_size);
1816 #endif /* defined unix */
1818 path = zalloc_or_die(path_size);
1820 strlcpy(path, conf_dir, path_size);
1821 strlcat(path, delim, path_size);
1822 strlcat(path, file_name, path_size);
1823 strlcat(path, suffix, path_size);
1830 /*********************************************************************
1832 * Function : get_certificate_serial
1834 * Description : Computes serial number for new certificate from host
1835 * name hash. This hash must be already saved in csp
1839 * 1 : csp = Current client state (buffers, headers, etc...)
1841 * Returns : Serial number for new certificate
1843 *********************************************************************/
1844 static unsigned long get_certificate_serial(struct client_state *csp)
1846 unsigned long exp = 1;
1847 unsigned long serial = 0;
1849 int i = CERT_SERIAL_NUM_LENGTH;
1850 /* Length of hash is 16 bytes, we must avoid to read next chars */
1862 serial += exp * (unsigned)csp->http->hash_of_host[i];
1869 /*********************************************************************
1871 * Function : ssl_send_certificate_error
1873 * Description : Sends info about invalid server certificate to client.
1874 * Sent message is including all trusted chain certificates,
1875 * that can be downloaded in web browser.
1878 * 1 : csp = Current client state (buffers, headers, etc...)
1882 *********************************************************************/
1883 extern void ssl_send_certificate_error(struct client_state *csp)
1885 size_t message_len = 0;
1887 struct certs_chain *cert = NULL;
1889 /* Header of message with certificate informations */
1890 const char message_begin[] =
1891 "HTTP/1.1 200 OK\r\n"
1892 "Content-Type: text/html\r\n"
1893 "Connection: close\r\n\r\n"
1894 "<html><body><h1>Server certificate verification failed</h1><p>Reason: ";
1895 const char message_end[] = "</body></html>\r\n\r\n";
1896 char reason[INVALID_CERT_INFO_BUF_SIZE];
1897 memset(reason, 0, sizeof(reason));
1899 /* Get verification message from verification return code */
1900 mbedtls_x509_crt_verify_info(reason, sizeof(reason), " ",
1901 csp->server_cert_verification_result);
1904 * Computing total length of message with all certificates inside
1906 message_len = strlen(message_begin) + strlen(message_end)
1907 + strlen(reason) + strlen("</p>") + 1;
1909 cert = &(csp->server_certs_chain);
1910 while (cert->next != NULL)
1912 size_t base64_len = 4 * ((strlen(cert->file_buf) + 2) / 3) + 1;
1914 message_len += strlen(cert->text_buf) + strlen("<pre></pre>\n")
1915 + base64_len + strlen("<a href=\"data:application"
1916 "/x-x509-ca-cert;base64,\">Download certificate</a>");
1921 * Joining all blocks in one long message
1923 char message[message_len];
1924 memset(message, 0, message_len);
1926 strlcpy(message, message_begin, message_len);
1927 strlcat(message, reason , message_len);
1928 strlcat(message, "</p>" , message_len);
1930 cert = &(csp->server_certs_chain);
1931 while (cert->next != NULL)
1934 size_t base64_len = 4 * ((strlen(cert->file_buf) + 2) / 3) + 1; /* +1 for terminating null*/
1935 char base64_buf[base64_len];
1936 memset(base64_buf, 0, base64_len);
1938 /* Encoding certificate into base64 code */
1939 ret = mbedtls_base64_encode((unsigned char*)base64_buf,
1940 base64_len, &olen, (const unsigned char*)cert->file_buf,
1941 strlen(cert->file_buf));
1944 log_error(LOG_LEVEL_ERROR,
1945 "Encoding to base64 failed, buffer is to small");
1948 strlcat(message, "<pre>", message_len);
1949 strlcat(message, cert->text_buf, message_len);
1950 strlcat(message, "</pre>\n", message_len);
1954 strlcat(message, "<a href=\"data:application/x-x509-ca-cert;base64,",
1956 strlcat(message, base64_buf, message_len);
1957 strlcat(message, "\">Download certificate</a>", message_len);
1962 strlcat(message, message_end, message_len);
1965 * Sending final message to client
1967 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
1968 (const unsigned char *)message, strlen(message));
1970 free_certificate_chain(csp);
1974 /*********************************************************************
1976 * Function : ssl_verify_callback
1978 * Description : This is a callback function for certificate verification.
1979 * It's called for all certificates in server certificate
1980 * trusted chain and it's preparing information about this
1981 * certificates. Prepared informations can be used to inform
1982 * user about invalid certificates.
1985 * 1 : csp_void = Current client state (buffers, headers, etc...)
1986 * 2 : crt = certificate from trusted chain
1987 * 3 : depth = depth in trusted chain
1988 * 4 : flags = certificate flags
1990 * Returns : 0 on success and negative value on error
1992 *********************************************************************/
1993 static int ssl_verify_callback(void *csp_void, mbedtls_x509_crt *crt,
1994 int depth, uint32_t *flags)
1996 struct client_state *csp = (struct client_state *)csp_void;
1997 struct certs_chain *last = &(csp->server_certs_chain);
2002 * Searching for last item in certificates linked list
2004 while (last->next != NULL)
2010 * Preparing next item in linked list for next certificate
2012 last->next = malloc_or_die(sizeof(struct certs_chain));
2013 last->next->next = NULL;
2014 memset(last->next->text_buf, 0, sizeof(last->next->text_buf));
2015 memset(last->next->file_buf, 0, sizeof(last->next->file_buf));
2018 * Saving certificate file into buffer
2020 if ((ret = mbedtls_pem_write_buffer(PEM_BEGIN_CRT, PEM_END_CRT,
2021 crt->raw.p, crt->raw.len, (unsigned char *)last->file_buf,
2022 sizeof(last->file_buf)-1, &olen)) != 0)
2028 * Saving certificate information into buffer
2030 mbedtls_x509_crt_info(last->text_buf, sizeof(last->text_buf) - 1,
2031 CERT_INFO_PREFIX, crt);
2037 /*********************************************************************
2039 * Function : free_certificate_chain
2041 * Description : Frees certificates linked list. This linked list is
2042 * used to save informations about certificates in
2046 * 1 : csp = Current client state (buffers, headers, etc...)
2050 *********************************************************************/
2051 static void free_certificate_chain(struct client_state *csp)
2053 struct certs_chain *cert = csp->server_certs_chain.next;
2055 /* Cleaning buffers */
2056 memset(csp->server_certs_chain.text_buf, 0,
2057 sizeof(csp->server_certs_chain.text_buf));
2058 memset(csp->server_certs_chain.file_buf, 0,
2059 sizeof(csp->server_certs_chain.file_buf));
2060 csp->server_certs_chain.next = NULL;
2062 /* Freeing memory in whole linked list */
2067 struct certs_chain *cert_for_free = cert;
2069 freez(cert_for_free);
2070 } while (cert != NULL);
2075 /*********************************************************************
2077 * Function : file_exists
2079 * Description : Tests if file exists and is readable.
2082 * 1 : path = Path to tested file.
2084 * Returns : 1 => File exists and is readable.
2085 * 0 => File doesn't exist or is not readable.
2087 *********************************************************************/
2088 static int file_exists(const char *path)
2091 if ((f = fopen(path, "r")) != NULL)
2101 /*********************************************************************
2103 * Function : host_to_hash
2105 * Description : Creates MD5 hash from host name. Host name is loaded
2106 * from structure csp and saved again into it.
2109 * 1 : csp = Current client state (buffers, headers, etc...)
2111 * Returns : 1 => Error while creating hash
2112 * 0 => Hash created successfully
2114 *********************************************************************/
2115 static int host_to_hash(struct client_state *csp)
2119 #if !defined(MBEDTLS_MD5_C)
2120 #error mbedTLS needs to be compiled with md5 support
2122 memset(csp->http->hash_of_host, 0, sizeof(csp->http->hash_of_host));
2123 mbedtls_md5((unsigned char *)csp->http->host, strlen(csp->http->host),
2124 csp->http->hash_of_host);
2126 /* Converting hash into string with hex */
2130 if ((ret = sprintf((char *)csp->http->hash_of_host_hex + 2 * i, "%02x",
2131 csp->http->hash_of_host[i])) < 0)
2133 log_error(LOG_LEVEL_ERROR, "Sprintf return value: %d", ret);
2139 #endif /* MBEDTLS_MD5_C */
2143 /*********************************************************************
2145 * Function : tunnel_established_successfully
2147 * Description : Check if parent proxy server response contains
2148 * informations about successfully created connection with
2149 * destination server. (HTTP/... 2xx ...)
2152 * 1 : server_response = Buffer with parent proxy server response
2153 * 2 : response_len = Length of server_response
2155 * Returns : 1 => Connection created successfully
2156 * 0 => Connection wasn't created successfully
2158 *********************************************************************/
2159 extern int tunnel_established_successfully(const char *server_response,
2160 unsigned int response_len)
2162 unsigned int pos = 0;
2164 if (server_response == NULL)
2169 /* Tests if "HTTP/" string is at the begin of received response */
2170 if (strncmp(server_response, "HTTP/", 5) != 0)
2175 for (pos = 0; pos < response_len; pos++)
2177 if (server_response[pos] == ' ')
2184 * response_len -3 because of buffer end, response structure and 200 code.
2185 * There must be at least 3 chars after space.
2186 * End of buffer: ... 2xx'\0'
2189 if (pos >= (response_len - 3))
2194 /* Test HTTP status code */
2195 if (server_response[pos + 1] != '2')
2204 /*********************************************************************
2206 * Function : seed_rng
2208 * Description : Seeding the RNG for all SSL uses
2211 * 1 : csp = Current client state (buffers, headers, etc...)
2213 * Returns : -1 => RNG wasn't seed successfully
2214 * 0 => RNG is seeded successfully
2216 *********************************************************************/
2217 static int seed_rng(struct client_state *csp)
2220 char err_buf[ERROR_BUF_SIZE];
2222 if (rng_seeded == 0)
2224 privoxy_mutex_lock(&rng_mutex);
2225 if (rng_seeded == 0)
2227 mbedtls_ctr_drbg_init(&ctr_drbg);
2228 mbedtls_entropy_init(&entropy);
2229 ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func,
2233 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
2234 log_error(LOG_LEVEL_ERROR,
2235 "mbedtls_ctr_drbg_seed failed: %s", err_buf);
2236 privoxy_mutex_unlock(&rng_mutex);
2241 privoxy_mutex_unlock(&rng_mutex);