1 /*********************************************************************
3 * File : $Source: /cvsroot/ijbswa/current/ssl.c,v $
5 * Purpose : File with TLS/SSL extension. Contains methods for
6 * creating, using and closing TLS/SSL connections.
8 * Copyright : Written by and Copyright (c) 2017 Vaclav Svec. FIT CVUT.
9 * Copyright (C) 2018-2020 by Fabian Keil <fk@fabiankeil.de>
11 * This program is free software; you can redistribute it
12 * and/or modify it under the terms of the GNU General
13 * Public License as published by the Free Software
14 * Foundation; either version 2 of the License, or (at
15 * your option) any later version.
17 * This program is distributed in the hope that it will
18 * be useful, but WITHOUT ANY WARRANTY; without even the
19 * implied warranty of MERCHANTABILITY or FITNESS FOR A
20 * PARTICULAR PURPOSE. See the GNU General Public
21 * License for more details.
23 * The GNU General Public License should be included with
24 * this file. If not, you can view it at
25 * http://www.gnu.org/copyleft/gpl.html
26 * or write to the Free Software Foundation, Inc., 59
27 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
29 *********************************************************************/
34 #if !defined(MBEDTLS_CONFIG_FILE)
35 # include "mbedtls/config.h"
37 # include MBEDTLS_CONFIG_FILE
40 #include "mbedtls/md5.h"
41 #include "mbedtls/pem.h"
42 #include "mbedtls/base64.h"
43 #include "mbedtls/error.h"
44 #include "mbedtls/oid.h"
45 #include "mbedtls/asn1write.h"
57 * Macros for searching begin and end of certificates.
58 * Necessary to convert structure mbedtls_x509_crt to crt file.
60 #define PEM_BEGIN_CRT "-----BEGIN CERTIFICATE-----\n"
61 #define PEM_END_CRT "-----END CERTIFICATE-----\n"
66 #define ERROR_BUF_SIZE 1024 /* Size of buffer for error messages */
67 #define CERTIFICATE_BUF_SIZE 16384 /* Size of buffer to save certificate. Value 4096 is mbedtls library buffer size for certificate in DER form */
68 #define PRIVATE_KEY_BUF_SIZE 16000 /* Size of buffer to save private key. Value 16000 is taken from mbed TLS library examples. */
69 #define RSA_KEY_PUBLIC_EXPONENT 65537 /* Public exponent for RSA private key generating */
70 #define RSA_KEYSIZE 2048 /* Size of generated RSA keys */
71 #define CERT_SIGNATURE_ALGORITHM MBEDTLS_MD_SHA256 /* The MD algorithm to use for the signature */
72 #define CERT_SERIAL_NUM_LENGTH 4 /* Bytes of hash to be used for creating serial number of certificate. Min=2 and max=16 */
73 #define INVALID_CERT_INFO_BUF_SIZE 2048 /* Size of buffer for message with information about reason of certificate invalidity. Data after the end of buffer will not be saved */
74 #define CERT_PARAM_COMMON_NAME "CN="
75 #define CERT_PARAM_ORGANIZATION ",O="
76 #define CERT_PARAM_ORG_UNIT ",OU="
77 #define CERT_PARAM_COUNTRY ",C=CZ"
78 #define KEY_FILE_TYPE ".pem"
79 #define CERT_FILE_TYPE ".crt"
80 #define CERT_SUBJECT_PASSWORD ""
81 #define CERT_INFO_PREFIX ""
84 * Properties of cert for generating
87 char *issuer_crt; /* filename of the issuer certificate */
88 char *subject_key; /* filename of the subject key file */
89 char *issuer_key; /* filename of the issuer key file */
90 const char *subject_pwd; /* password for the subject key file */
91 const char *issuer_pwd; /* password for the issuer key file */
92 char *output_file; /* where to store the constructed key file */
93 const char *subject_name; /* subject name for certificate */
94 char issuer_name[ISSUER_NAME_BUF_SIZE]; /* issuer name for certificate */
95 const char *not_before; /* validity period not before */
96 const char *not_after; /* validity period not after */
97 const char *serial; /* serial number string */
98 int is_ca; /* is a CA certificate */
99 int max_pathlen; /* maximum CA path length */
103 * Properties of key for generating
106 mbedtls_pk_type_t type; /* type of key to generate */
107 int rsa_keysize; /* length of key in bits */
108 char *key_file_path; /* filename of the key file */
111 static int generate_webpage_certificate(struct client_state *csp);
112 static char *make_certs_path(const char *conf_dir, const char *file_name, const char *suffix);
113 static int file_exists(const char *path);
114 static int host_to_hash(struct client_state *csp);
115 static int ssl_verify_callback(void *data, mbedtls_x509_crt *crt, int depth, uint32_t *flags);
116 static void free_certificate_chain(struct client_state *csp);
117 static unsigned long get_certificate_serial(struct client_state *csp);
118 static void free_client_ssl_structures(struct client_state *csp);
119 static void free_server_ssl_structures(struct client_state *csp);
120 static int seed_rng(struct client_state *csp);
122 /*********************************************************************
124 * Function : client_use_ssl
126 * Description : Tests if client in current client state structure
127 * should use SSL connection or standard connection.
130 * 1 : csp = Current client state (buffers, headers, etc...)
132 * Returns : If client should use TLS/SSL connection, 1 is returned.
133 * Otherwise 0 is returned.
135 *********************************************************************/
136 extern int client_use_ssl(const struct client_state *csp)
138 return csp->http->client_ssl;
142 /*********************************************************************
144 * Function : server_use_ssl
146 * Description : Tests if server in current client state structure
147 * should use SSL connection or standard connection.
150 * 1 : csp = Current client state (buffers, headers, etc...)
152 * Returns : If server should use TLS/SSL connection, 1 is returned.
153 * Otherwise 0 is returned.
155 *********************************************************************/
156 extern int server_use_ssl(const struct client_state *csp)
158 return csp->http->server_ssl;
162 /*********************************************************************
164 * Function : is_ssl_pending
166 * Description : Tests if there are some waiting data on ssl connection.
167 * Only considers data that has actually been received
168 * locally and ignores data that is still on the fly
169 * or has not yet been sent by the remote end.
172 * 1 : ssl = SSL context to test
174 * Returns : 0 => No data are pending
175 * >0 => Pending data length
177 *********************************************************************/
178 extern size_t is_ssl_pending(mbedtls_ssl_context *ssl)
185 return mbedtls_ssl_get_bytes_avail(ssl);
189 /*********************************************************************
191 * Function : ssl_send_data
193 * Description : Sends the content of buf (for n bytes) to given SSL
194 * connection context.
197 * 1 : ssl = SSL context to send data to
198 * 2 : buf = Pointer to data to be sent
199 * 3 : len = Length of data to be sent to the SSL context
201 * Returns : Length of sent data or negative value on error.
203 *********************************************************************/
204 extern int ssl_send_data(mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len)
207 size_t max_fragment_size = 0; /* Maximal length of data in one SSL fragment*/
208 int send_len = 0; /* length of one data part to send */
209 int pos = 0; /* Position of unsent part in buffer */
216 /* Getting maximal length of data sent in one fragment */
217 max_fragment_size = mbedtls_ssl_get_max_frag_len(ssl);
220 * Whole buffer must be sent in many fragments, because each fragment
221 * has its maximal length.
225 /* Compute length of data, that can be send in next fragment */
226 if ((pos + (int)max_fragment_size) > len)
228 send_len = (int)len - pos;
232 send_len = (int)max_fragment_size;
235 log_error(LOG_LEVEL_WRITING, "TLS: %N", send_len, buf+pos);
238 * Sending one part of the buffer
240 while ((ret = mbedtls_ssl_write(ssl,
241 (const unsigned char *)(buf + pos),
242 (size_t)send_len)) < 0)
244 if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
245 ret != MBEDTLS_ERR_SSL_WANT_WRITE)
247 char err_buf[ERROR_BUF_SIZE];
249 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
250 log_error(LOG_LEVEL_ERROR,
251 "Sending data over TLS/SSL failed: %s", err_buf);
255 /* Adding count of sent bytes to position in buffer */
256 pos = pos + send_len;
263 /*********************************************************************
265 * Function : ssl_recv_data
267 * Description : Receives data from given SSL context and puts
271 * 1 : ssl = SSL context to receive data from
272 * 2 : buf = Pointer to buffer where data will be written
273 * 3 : max_length = Maximum number of bytes to read
275 * Returns : Number of bytes read, 0 for EOF, or -1
278 *********************************************************************/
279 extern int ssl_recv_data(mbedtls_ssl_context *ssl, unsigned char *buf, size_t max_length)
282 memset(buf, 0, max_length);
285 * Receiving data from SSL context into buffer
289 ret = mbedtls_ssl_read(ssl, buf, max_length);
290 } while (ret == MBEDTLS_ERR_SSL_WANT_READ
291 || ret == MBEDTLS_ERR_SSL_WANT_WRITE);
295 char err_buf[ERROR_BUF_SIZE];
297 if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY)
299 log_error(LOG_LEVEL_CONNECT,
300 "The peer notified us that the connection is going to be closed");
303 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
304 log_error(LOG_LEVEL_ERROR,
305 "Receiving data over TLS/SSL failed: %s", err_buf);
310 log_error(LOG_LEVEL_RECEIVED, "TLS: %N", ret, buf);
316 /*********************************************************************
318 * Function : ssl_flush_socket
320 * Description : Send any pending "buffered" content with given
321 * SSL connection. Alternative to function flush_socket.
324 * 1 : ssl = SSL context to send buffer to
325 * 2 : iob = The I/O buffer to flush, usually csp->iob.
327 * Returns : On success, the number of bytes send are returned (zero
328 * indicates nothing was sent). On error, -1 is returned.
330 *********************************************************************/
331 extern long ssl_flush_socket(mbedtls_ssl_context *ssl, struct iob *iob)
333 /* Computing length of buffer part to send */
334 long len = iob->eod - iob->cur;
341 /* Sending data to given SSl context */
342 if (ssl_send_data(ssl, (const unsigned char *)iob->cur, (size_t)len) < 0)
346 iob->eod = iob->cur = iob->buf;
351 /*********************************************************************
353 * Function : ssl_debug_callback
355 * Description : Debug callback function for mbedtls library.
356 * Prints info into log file.
359 * 1 : ctx = File to save log in
360 * 2 : level = Debug level
361 * 3 : file = File calling debug message
362 * 4 : line = Line calling debug message
363 * 5 : str = Debug message
367 *********************************************************************/
368 static void ssl_debug_callback(void *ctx, int level, const char *file, int line, const char *str)
372 fprintf((FILE *)ctx, "%s:%04d: %s", file, line, str);
374 log_error(LOG_LEVEL_INFO, "SSL debug message: %s:%04d: %s", file, line, str);
379 /*********************************************************************
381 * Function : create_client_ssl_connection
383 * Description : Creates TLS/SSL secured connection with client
386 * 1 : csp = Current client state (buffers, headers, etc...)
388 * Returns : 0 on success, negative value if connection wasn't created
391 *********************************************************************/
392 extern int create_client_ssl_connection(struct client_state *csp)
394 /* Paths to certificates file and key file */
395 char *key_file = NULL;
396 char *ca_file = NULL;
397 char *cert_file = NULL;
399 char err_buf[ERROR_BUF_SIZE];
402 * Initializing mbedtls structures for TLS/SSL connection
404 mbedtls_net_init(&(csp->mbedtls_client_attr.socket_fd));
405 mbedtls_ssl_init(&(csp->mbedtls_client_attr.ssl));
406 mbedtls_ssl_config_init(&(csp->mbedtls_client_attr.conf));
407 mbedtls_x509_crt_init(&(csp->mbedtls_client_attr.server_cert));
408 mbedtls_pk_init(&(csp->mbedtls_client_attr.prim_key));
409 #if defined(MBEDTLS_SSL_CACHE_C)
410 mbedtls_ssl_cache_init(&(csp->mbedtls_client_attr.cache));
414 * Preparing hash of host for creating certificates
416 ret = host_to_hash(csp);
419 log_error(LOG_LEVEL_ERROR, "Generating hash of host failed: %d", ret);
425 * Preparing paths to certificates files and key file
427 ca_file = csp->config->ca_cert_file;
428 cert_file = make_certs_path(csp->config->certificate_directory,
429 (const char *)csp->http->hash_of_host_hex, CERT_FILE_TYPE);
430 key_file = make_certs_path(csp->config->certificate_directory,
431 (const char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
433 if (cert_file == NULL || key_file == NULL)
440 * Generating certificate for requested host. Mutex to prevent
441 * certificate and key inconsistence must be locked.
443 privoxy_mutex_lock(&certificate_mutex);
445 ret = generate_webpage_certificate(csp);
448 log_error(LOG_LEVEL_ERROR,
449 "Generate_webpage_certificate failed: %d", ret);
450 privoxy_mutex_unlock(&certificate_mutex);
454 privoxy_mutex_unlock(&certificate_mutex);
467 * Loading CA file, webpage certificate and key files
469 ret = mbedtls_x509_crt_parse_file(&(csp->mbedtls_client_attr.server_cert),
473 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
474 log_error(LOG_LEVEL_ERROR,
475 "Loading webpage certificate %s failed: %s", cert_file, err_buf);
480 ret = mbedtls_x509_crt_parse_file(&(csp->mbedtls_client_attr.server_cert),
484 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
485 log_error(LOG_LEVEL_ERROR,
486 "Loading CA certificate %s failed: %s", ca_file, err_buf);
491 ret = mbedtls_pk_parse_keyfile(&(csp->mbedtls_client_attr.prim_key),
495 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
496 log_error(LOG_LEVEL_ERROR,
497 "Loading and parsing webpage certificate private key %s failed: %s",
504 * Setting SSL parameters
506 ret = mbedtls_ssl_config_defaults(&(csp->mbedtls_client_attr.conf),
507 MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_TRANSPORT_STREAM,
508 MBEDTLS_SSL_PRESET_DEFAULT);
511 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
512 log_error(LOG_LEVEL_ERROR,
513 "mbedtls_ssl_config_defaults failed: %s", err_buf);
518 mbedtls_ssl_conf_rng(&(csp->mbedtls_client_attr.conf),
519 mbedtls_ctr_drbg_random, &ctr_drbg);
520 mbedtls_ssl_conf_dbg(&(csp->mbedtls_client_attr.conf),
521 ssl_debug_callback, stdout);
523 #if defined(MBEDTLS_SSL_CACHE_C)
524 mbedtls_ssl_conf_session_cache(&(csp->mbedtls_client_attr.conf),
525 &(csp->mbedtls_client_attr.cache), mbedtls_ssl_cache_get,
526 mbedtls_ssl_cache_set);
530 * Setting certificates
532 ret = mbedtls_ssl_conf_own_cert(&(csp->mbedtls_client_attr.conf),
533 &(csp->mbedtls_client_attr.server_cert),
534 &(csp->mbedtls_client_attr.prim_key));
537 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
538 log_error(LOG_LEVEL_ERROR,
539 "mbedtls_ssl_conf_own_cert failed: %s", err_buf);
544 ret = mbedtls_ssl_setup(&(csp->mbedtls_client_attr.ssl),
545 &(csp->mbedtls_client_attr.conf));
548 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
549 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_setup failed: %s", err_buf);
554 mbedtls_ssl_set_bio(&(csp->mbedtls_client_attr.ssl),
555 &(csp->mbedtls_client_attr.socket_fd), mbedtls_net_send,
556 mbedtls_net_recv, NULL);
557 mbedtls_ssl_session_reset(&(csp->mbedtls_client_attr.ssl));
560 * Setting socket fd in mbedtls_net_context structure. This structure
561 * can't be set by mbedtls functions, because we already have created
562 * a TCP connection when this function is called.
564 csp->mbedtls_client_attr.socket_fd.fd = csp->cfd;
567 * Handshake with client
569 log_error(LOG_LEVEL_CONNECT,
570 "Performing the TLS/SSL handshake with client. Hash of host: %s",
571 csp->http->hash_of_host_hex);
572 while ((ret = mbedtls_ssl_handshake(&(csp->mbedtls_client_attr.ssl))) != 0)
574 if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
575 ret != MBEDTLS_ERR_SSL_WANT_WRITE)
577 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
578 log_error(LOG_LEVEL_ERROR,
579 "medtls_ssl_handshake with client failed: %s", err_buf);
585 log_error(LOG_LEVEL_CONNECT, "Client successfully connected over TLS/SSL");
586 csp->ssl_with_client_is_opened = 1;
590 * Freeing allocated paths to files
595 /* Freeing structures if connection wasn't created successfully */
598 free_client_ssl_structures(csp);
604 /*********************************************************************
606 * Function : close_client_ssl_connection
608 * Description : Closes TLS/SSL connection with client. This function
609 * checks if this connection is already created.
612 * 1 : csp = Current client state (buffers, headers, etc...)
616 *********************************************************************/
617 extern void close_client_ssl_connection(struct client_state *csp)
621 if (csp->ssl_with_client_is_opened == 0)
627 * Notifying the peer that the connection is being closed.
630 ret = mbedtls_ssl_close_notify(&(csp->mbedtls_client_attr.ssl));
631 } while (ret == MBEDTLS_ERR_SSL_WANT_WRITE);
633 free_client_ssl_structures(csp);
634 csp->ssl_with_client_is_opened = 0;
638 /*********************************************************************
640 * Function : free_client_ssl_structures
642 * Description : Frees structures used for SSL communication with
646 * 1 : csp = Current client state (buffers, headers, etc...)
650 *********************************************************************/
651 static void free_client_ssl_structures(struct client_state *csp)
654 * We can't use function mbedtls_net_free, because this function
655 * inter alia close TCP connection on set fd. Instead of this
656 * function, we change fd to -1, which is the same what does
657 * rest of mbedtls_net_free function.
659 csp->mbedtls_client_attr.socket_fd.fd = -1;
661 /* Freeing mbedtls structures */
662 mbedtls_x509_crt_free(&(csp->mbedtls_client_attr.server_cert));
663 mbedtls_pk_free(&(csp->mbedtls_client_attr.prim_key));
664 mbedtls_ssl_free(&(csp->mbedtls_client_attr.ssl));
665 mbedtls_ssl_config_free(&(csp->mbedtls_client_attr.conf));
666 #if defined(MBEDTLS_SSL_CACHE_C)
667 mbedtls_ssl_cache_free(&(csp->mbedtls_client_attr.cache));
672 /*********************************************************************
674 * Function : create_server_ssl_connection
676 * Description : Creates TLS/SSL secured connection with server.
679 * 1 : csp = Current client state (buffers, headers, etc...)
681 * Returns : 0 on success, negative value if connection wasn't created
684 *********************************************************************/
685 extern int create_server_ssl_connection(struct client_state *csp)
688 char err_buf[ERROR_BUF_SIZE];
689 char *trusted_cas_file = NULL;
690 int auth_mode = MBEDTLS_SSL_VERIFY_REQUIRED;
692 csp->server_cert_verification_result = SSL_CERT_NOT_VERIFIED;
693 csp->server_certs_chain.next = NULL;
695 /* Setting path to file with trusted CAs */
696 trusted_cas_file = csp->config->trusted_cas_file;
699 * Initializing mbedtls structures for TLS/SSL connection
701 mbedtls_net_init(&(csp->mbedtls_server_attr.socket_fd));
702 mbedtls_ssl_init(&(csp->mbedtls_server_attr.ssl));
703 mbedtls_ssl_config_init(&(csp->mbedtls_server_attr.conf));
704 mbedtls_x509_crt_init(&(csp->mbedtls_server_attr.ca_cert));
707 * Setting socket fd in mbedtls_net_context structure. This structure
708 * can't be set by mbedtls functions, because we already have created
709 * TCP connection when calling this function.
711 csp->mbedtls_server_attr.socket_fd.fd = csp->server_connection.sfd;
724 * Loading file with trusted CAs
726 ret = mbedtls_x509_crt_parse_file(&(csp->mbedtls_server_attr.ca_cert),
730 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
731 log_error(LOG_LEVEL_ERROR, "Loading trusted CAs file %s failed: %s",
732 trusted_cas_file, err_buf);
738 * Set TLS/SSL options
740 ret = mbedtls_ssl_config_defaults(&(csp->mbedtls_server_attr.conf),
741 MBEDTLS_SSL_IS_CLIENT,
742 MBEDTLS_SSL_TRANSPORT_STREAM,
743 MBEDTLS_SSL_PRESET_DEFAULT);
746 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
747 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_config_defaults failed: %s",
754 * Setting how strict should certificate verification be and other
755 * parameters for certificate verification
757 if (csp->dont_verify_certificate)
759 auth_mode = MBEDTLS_SSL_VERIFY_NONE;
762 mbedtls_ssl_conf_authmode(&(csp->mbedtls_server_attr.conf), auth_mode);
763 mbedtls_ssl_conf_ca_chain(&(csp->mbedtls_server_attr.conf),
764 &(csp->mbedtls_server_attr.ca_cert), NULL);
766 /* Setting callback function for certificates verification */
767 mbedtls_ssl_conf_verify(&(csp->mbedtls_server_attr.conf),
768 ssl_verify_callback, (void *)csp);
770 mbedtls_ssl_conf_rng(&(csp->mbedtls_server_attr.conf),
771 mbedtls_ctr_drbg_random, &ctr_drbg);
772 mbedtls_ssl_conf_dbg(&(csp->mbedtls_server_attr.conf),
773 ssl_debug_callback, stdout);
775 ret = mbedtls_ssl_setup(&(csp->mbedtls_server_attr.ssl),
776 &(csp->mbedtls_server_attr.conf));
779 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
780 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_setup failed: %s", err_buf);
786 * Set the hostname to check against the received server certificate
788 ret = mbedtls_ssl_set_hostname(&(csp->mbedtls_server_attr.ssl),
792 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
793 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_set_hostname failed: %s",
799 mbedtls_ssl_set_bio(&(csp->mbedtls_server_attr.ssl),
800 &(csp->mbedtls_server_attr.socket_fd), mbedtls_net_send,
801 mbedtls_net_recv, NULL);
804 * Handshake with server
806 log_error(LOG_LEVEL_CONNECT,
807 "Performing the TLS/SSL handshake with the server");
809 while ((ret = mbedtls_ssl_handshake(&(csp->mbedtls_server_attr.ssl))) != 0)
811 if (ret != MBEDTLS_ERR_SSL_WANT_READ
812 && ret != MBEDTLS_ERR_SSL_WANT_WRITE)
814 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
816 if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED)
818 char reason[INVALID_CERT_INFO_BUF_SIZE];
820 csp->server_cert_verification_result =
821 mbedtls_ssl_get_verify_result(&(csp->mbedtls_server_attr.ssl));
822 mbedtls_x509_crt_verify_info(reason, sizeof(reason), "",
823 csp->server_cert_verification_result);
825 /* Log the reason without the trailing new line */
826 log_error(LOG_LEVEL_ERROR,
827 "X509 certificate verification for %s failed: %N",
828 csp->http->hostport, strlen(reason)-1, reason);
833 log_error(LOG_LEVEL_ERROR,
834 "mbedtls_ssl_handshake with server failed: %s", err_buf);
835 free_certificate_chain(csp);
842 log_error(LOG_LEVEL_CONNECT, "Server successfully connected over TLS/SSL");
845 * Server certificate chain is valid, so we can clean
846 * chain, because we will not send it to client.
848 free_certificate_chain(csp);
850 csp->ssl_with_server_is_opened = 1;
851 csp->server_cert_verification_result =
852 mbedtls_ssl_get_verify_result(&(csp->mbedtls_server_attr.ssl));
855 /* Freeing structures if connection wasn't created successfully */
858 free_server_ssl_structures(csp);
865 /*********************************************************************
867 * Function : close_server_ssl_connection
869 * Description : Closes TLS/SSL connection with server. This function
870 * checks if this connection is already opened.
873 * 1 : csp = Current client state (buffers, headers, etc...)
877 *********************************************************************/
878 static void close_server_ssl_connection(struct client_state *csp)
882 if (csp->ssl_with_server_is_opened == 0)
888 * Notifying the peer that the connection is being closed.
891 ret = mbedtls_ssl_close_notify(&(csp->mbedtls_server_attr.ssl));
892 } while (ret == MBEDTLS_ERR_SSL_WANT_WRITE);
894 free_server_ssl_structures(csp);
895 csp->ssl_with_server_is_opened = 0;
899 /*********************************************************************
901 * Function : free_server_ssl_structures
903 * Description : Frees structures used for SSL communication with server
906 * 1 : csp = Current client state (buffers, headers, etc...)
910 *********************************************************************/
911 static void free_server_ssl_structures(struct client_state *csp)
914 * We can't use function mbedtls_net_free, because this function
915 * inter alia close TCP connection on set fd. Instead of this
916 * function, we change fd to -1, which is the same what does
917 * rest of mbedtls_net_free function.
919 csp->mbedtls_server_attr.socket_fd.fd = -1;
921 mbedtls_x509_crt_free(&(csp->mbedtls_server_attr.ca_cert));
922 mbedtls_ssl_free(&(csp->mbedtls_server_attr.ssl));
923 mbedtls_ssl_config_free(&(csp->mbedtls_server_attr.conf));
927 /*********************************************************************
929 * Function : close_client_and_server_ssl_connections
931 * Description : Checks if client or server should use secured
932 * connection over SSL and if so, closes all of them.
935 * 1 : csp = Current client state (buffers, headers, etc...)
939 *********************************************************************/
940 extern void close_client_and_server_ssl_connections(struct client_state *csp)
942 if (client_use_ssl(csp) == 1)
944 close_client_ssl_connection(csp);
946 if (server_use_ssl(csp) == 1)
948 close_server_ssl_connection(csp);
952 /*====================== Certificates ======================*/
954 /*********************************************************************
956 * Function : write_certificate
958 * Description : Writes certificate into file.
961 * 1 : crt = certificate to write into file
962 * 2 : output_file = path to save certificate file
963 * 3 : f_rng = mbedtls_ctr_drbg_random
964 * 4 : p_rng = mbedtls_ctr_drbg_context
966 * Returns : Length of written certificate on success or negative value
969 *********************************************************************/
970 static int write_certificate(mbedtls_x509write_cert *crt, const char *output_file,
971 int(*f_rng)(void *, unsigned char *, size_t), void *p_rng)
975 unsigned char cert_buf[CERTIFICATE_BUF_SIZE + 1]; /* Buffer for certificate in PEM format + terminating NULL */
977 char err_buf[ERROR_BUF_SIZE];
979 memset(cert_buf, 0, sizeof(cert_buf));
982 * Writing certificate into PEM string. If buffer is too small, function
983 * returns specific error and no buffer overflow can happen.
985 if ((ret = mbedtls_x509write_crt_pem(crt, cert_buf,
986 sizeof(cert_buf) - 1, f_rng, p_rng)) != 0)
988 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
989 log_error(LOG_LEVEL_ERROR,
990 "Writing certificate into buffer failed: %s", err_buf);
994 len = strlen((char *)cert_buf);
997 * Saving certificate into file
999 if ((f = fopen(output_file, "w")) == NULL)
1001 log_error(LOG_LEVEL_ERROR, "Opening file %s to save certificate failed",
1006 if (fwrite(cert_buf, 1, len, f) != len)
1008 log_error(LOG_LEVEL_ERROR,
1009 "Writing certificate into file %s failed", output_file);
1020 /*********************************************************************
1022 * Function : write_private_key
1024 * Description : Writes private key into file and copies saved
1025 * content into given pointer to string. If function
1026 * returns 0 for success, this copy must be freed by
1030 * 1 : key = key to write into file
1031 * 2 : ret_buf = pointer to string with created key file content
1032 * 3 : key_file_path = path where to save key file
1034 * Returns : Length of written private key on success or negative value
1037 *********************************************************************/
1038 static int write_private_key(mbedtls_pk_context *key, unsigned char **ret_buf,
1039 const char *key_file_path)
1041 size_t len = 0; /* Length of created key */
1042 FILE *f = NULL; /* File to save certificate */
1044 char err_buf[ERROR_BUF_SIZE];
1046 /* Initializing buffer for key file content */
1047 *ret_buf = zalloc_or_die(PRIVATE_KEY_BUF_SIZE + 1);
1050 * Writing private key into PEM string
1052 if ((ret = mbedtls_pk_write_key_pem(key, *ret_buf, PRIVATE_KEY_BUF_SIZE)) != 0)
1054 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1055 log_error(LOG_LEVEL_ERROR,
1056 "Writing private key into PEM string failed: %s", err_buf);
1060 len = strlen((char *)*ret_buf);
1063 * Saving key into file
1065 if ((f = fopen(key_file_path, "wb")) == NULL)
1067 log_error(LOG_LEVEL_ERROR,
1068 "Opening file %s to save private key failed: %E",
1074 if (fwrite(*ret_buf, 1, len, f) != len)
1077 log_error(LOG_LEVEL_ERROR,
1078 "Writing private key into file %s failed",
1097 /*********************************************************************
1099 * Function : generate_key
1101 * Description : Tests if private key for host saved in csp already
1102 * exists. If this file doesn't exists, a new key is
1103 * generated and saved in a file. The generated key is also
1104 * copied into given parameter key_buf, which must be then
1105 * freed by caller. If file with key exists, key_buf
1106 * contain NULL and no private key is generated.
1109 * 1 : csp = Current client state (buffers, headers, etc...)
1110 * 2 : key_buf = buffer to save new generated key
1112 * Returns : -1 => Error while generating private key
1113 * 0 => Key already exists
1114 * >0 => Length of generated private key
1116 *********************************************************************/
1117 static int generate_key(struct client_state *csp, unsigned char **key_buf)
1119 mbedtls_pk_context key;
1120 key_options key_opt;
1122 char err_buf[ERROR_BUF_SIZE];
1124 key_opt.key_file_path = NULL;
1127 * Initializing structures for key generating
1129 mbedtls_pk_init(&key);
1132 * Preparing path for key file and other properties for generating key
1134 key_opt.type = MBEDTLS_PK_RSA;
1135 key_opt.rsa_keysize = RSA_KEYSIZE;
1137 key_opt.key_file_path = make_certs_path(csp->config->certificate_directory,
1138 (char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
1139 if (key_opt.key_file_path == NULL)
1146 * Test if key already exists. If so, we don't have to create it again.
1148 if (file_exists(key_opt.key_file_path) == 1)
1157 ret = seed_rng(csp);
1165 * Setting attributes of private key and generating it
1167 if ((ret = mbedtls_pk_setup(&key,
1168 mbedtls_pk_info_from_type(key_opt.type))) != 0)
1170 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1171 log_error(LOG_LEVEL_ERROR, "mbedtls_pk_setup failed: %s", err_buf);
1176 ret = mbedtls_rsa_gen_key(mbedtls_pk_rsa(key), mbedtls_ctr_drbg_random,
1177 &ctr_drbg, (unsigned)key_opt.rsa_keysize, RSA_KEY_PUBLIC_EXPONENT);
1180 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1181 log_error(LOG_LEVEL_ERROR, "Key generating failed: %s", err_buf);
1187 * Exporting private key into file
1189 if ((ret = write_private_key(&key, key_buf, key_opt.key_file_path)) < 0)
1191 log_error(LOG_LEVEL_ERROR,
1192 "Writing private key into file %s failed", key_opt.key_file_path);
1199 * Freeing used variables
1201 freez(key_opt.key_file_path);
1203 mbedtls_pk_free(&key);
1209 /*********************************************************************
1211 * Function : ssl_certificate_is_invalid
1213 * Description : Checks whether or not a certificate is valid.
1214 * Currently only checks that the certificate can be
1215 * parsed and that the "valid to" date is in the future.
1218 * 1 : cert_file = The certificate to check
1220 * Returns : 0 => The certificate is valid.
1221 * 1 => The certificate is invalid
1223 *********************************************************************/
1224 static int ssl_certificate_is_invalid(const char *cert_file)
1226 mbedtls_x509_crt cert;
1229 mbedtls_x509_crt_init(&cert);
1231 ret = mbedtls_x509_crt_parse_file(&cert, cert_file);
1234 char err_buf[ERROR_BUF_SIZE];
1236 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1237 log_error(LOG_LEVEL_ERROR,
1238 "Loading certificate %s to check validity failed: %s",
1239 cert_file, err_buf);
1240 mbedtls_x509_crt_free(&cert);
1244 if (mbedtls_x509_time_is_past(&cert.valid_to))
1246 mbedtls_x509_crt_free(&cert);
1251 mbedtls_x509_crt_free(&cert);
1258 /*********************************************************************
1260 * Function : generate_certificate_valid_date
1262 * Description : Turns a time_t into the format expected by mbedTLS.
1265 * 1 : time_spec = The timestamp to convert
1266 * 2 : buffer = The buffer to write the date to
1267 * 3 : buffer_size = The size of the buffer
1269 * Returns : 0 => The conversion worked
1270 * 1 => The conversion failed
1272 *********************************************************************/
1273 static int generate_certificate_valid_date(time_t time_spec, char *buffer,
1276 struct tm valid_date;
1279 #ifndef HAVE_GMTIME_R
1280 #error HTTP inspection currently requires gmtime_r() which seems to be missing
1282 if (NULL == gmtime_r(&time_spec, &valid_date))
1287 ret = strftime(buffer, buffer_size, "%Y%m%d%H%M%S", &valid_date);
1298 /*********************************************************************
1300 * Function : get_certificate_valid_from_date
1302 * Description : Generates a "valid from" date in the format
1303 * expected by mbedTLS.
1306 * 1 : buffer = The buffer to write the date to
1307 * 2 : buffer_size = The size of the buffer
1309 * Returns : 0 => The generation worked
1310 * 1 => The generation failed
1312 *********************************************************************/
1313 static int get_certificate_valid_from_date(char *buffer, size_t buffer_size)
1317 time_spec = time(NULL);
1318 /* 1 month in the past */
1319 time_spec -= 30 * 24 * 60 * 60;
1321 return generate_certificate_valid_date(time_spec, buffer, buffer_size);
1326 /*********************************************************************
1328 * Function : get_certificate_valid_to_date
1330 * Description : Generates a "valid to" date in the format
1331 * expected by mbedTLS.
1334 * 1 : buffer = The buffer to write the date to
1335 * 2 : buffer_size = The size of the buffer
1337 * Returns : 0 => The generation worked
1338 * 1 => The generation failed
1340 *********************************************************************/
1341 static int get_certificate_valid_to_date(char *buffer, size_t buffer_size)
1345 time_spec = time(NULL);
1346 /* Three months in the future */
1347 time_spec += 90 * 24 * 60 * 60;
1349 return generate_certificate_valid_date(time_spec, buffer, buffer_size);
1354 /*********************************************************************
1356 * Function : set_subject_alternative_name
1358 * Description : Sets the Subject Alternative Name extension to a cert
1361 * 1 : cert = The certificate to modify
1362 * 2 : hostname = The hostname to add
1364 * Returns : <0 => Error while creating certificate.
1367 *********************************************************************/
1368 static int set_subject_alternative_name(mbedtls_x509write_cert *cert, const char *hostname)
1370 char err_buf[ERROR_BUF_SIZE];
1372 char *subject_alternative_name;
1373 size_t subject_alternative_name_len;
1374 #define MBEDTLS_SUBJECT_ALTERNATIVE_NAME_MAX_LEN 255
1375 unsigned char san_buf[MBEDTLS_SUBJECT_ALTERNATIVE_NAME_MAX_LEN + 1];
1379 subject_alternative_name_len = strlen(hostname) + 1;
1380 subject_alternative_name = zalloc_or_die(subject_alternative_name_len);
1382 strlcpy(subject_alternative_name, hostname, subject_alternative_name_len);
1384 memset(san_buf, 0, sizeof(san_buf));
1386 c = san_buf + sizeof(san_buf);
1389 ret = mbedtls_asn1_write_raw_buffer(&c, san_buf,
1390 (const unsigned char *)subject_alternative_name,
1391 strlen(subject_alternative_name));
1394 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1395 log_error(LOG_LEVEL_ERROR,
1396 "mbedtls_asn1_write_raw_buffer() failed: %s", err_buf);
1401 ret = mbedtls_asn1_write_len(&c, san_buf, strlen(subject_alternative_name));
1404 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1405 log_error(LOG_LEVEL_ERROR,
1406 "mbedtls_asn1_write_len() failed: %s", err_buf);
1411 ret = mbedtls_asn1_write_tag(&c, san_buf, MBEDTLS_ASN1_CONTEXT_SPECIFIC | 2);
1414 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1415 log_error(LOG_LEVEL_ERROR,
1416 "mbedtls_asn1_write_tag() failed: %s", err_buf);
1421 ret = mbedtls_asn1_write_len(&c, san_buf, (size_t)len);
1424 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1425 log_error(LOG_LEVEL_ERROR,
1426 "mbedtls_asn1_write_len() failed: %s", err_buf);
1431 ret = mbedtls_asn1_write_tag(&c, san_buf,
1432 MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE);
1435 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1436 log_error(LOG_LEVEL_ERROR,
1437 "mbedtls_asn1_write_tag() failed: %s", err_buf);
1442 ret = mbedtls_x509write_crt_set_extension(cert,
1443 MBEDTLS_OID_SUBJECT_ALT_NAME,
1444 MBEDTLS_OID_SIZE(MBEDTLS_OID_SUBJECT_ALT_NAME),
1445 0, san_buf + sizeof(san_buf) - len, (size_t)len);
1448 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1449 log_error(LOG_LEVEL_ERROR,
1450 "mbedtls_x509write_crt_set_extension() failed: %s", err_buf);
1454 freez(subject_alternative_name);
1460 /*********************************************************************
1462 * Function : generate_webpage_certificate
1464 * Description : Creates certificate file in presetted directory.
1465 * If certificate already exists, no other certificate
1466 * will be created. Subject of certificate is named
1467 * by csp->http->host from parameter. This function also
1468 * triggers generating of private key for new certificate.
1471 * 1 : csp = Current client state (buffers, headers, etc...)
1473 * Returns : -1 => Error while creating certificate.
1474 * 0 => Certificate already exists.
1475 * >0 => Length of created certificate.
1477 *********************************************************************/
1478 static int generate_webpage_certificate(struct client_state *csp)
1480 mbedtls_x509_crt issuer_cert;
1481 mbedtls_pk_context loaded_issuer_key, loaded_subject_key;
1482 mbedtls_pk_context *issuer_key = &loaded_issuer_key;
1483 mbedtls_pk_context *subject_key = &loaded_subject_key;
1484 mbedtls_x509write_cert cert;
1487 unsigned char *key_buf = NULL; /* Buffer for created key */
1490 char err_buf[ERROR_BUF_SIZE];
1491 cert_options cert_opt;
1492 char cert_valid_from[15];
1493 char cert_valid_to[15];
1495 /* Paths to keys and certificates needed to create certificate */
1496 cert_opt.issuer_key = NULL;
1497 cert_opt.subject_key = NULL;
1498 cert_opt.issuer_crt = NULL;
1500 cert_opt.output_file = make_certs_path(csp->config->certificate_directory,
1501 (const char *)csp->http->hash_of_host_hex, CERT_FILE_TYPE);
1502 if (cert_opt.output_file == NULL)
1507 cert_opt.subject_key = make_certs_path(csp->config->certificate_directory,
1508 (const char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
1509 if (cert_opt.subject_key == NULL)
1511 freez(cert_opt.output_file);
1515 if (file_exists(cert_opt.output_file) == 1)
1517 /* The file exists, but is it valid? */
1518 if (ssl_certificate_is_invalid(cert_opt.output_file))
1520 log_error(LOG_LEVEL_CONNECT,
1521 "Certificate %s is no longer valid. Removing it.",
1522 cert_opt.output_file);
1523 if (unlink(cert_opt.output_file))
1525 log_error(LOG_LEVEL_ERROR, "Failed to unlink %s: %E",
1526 cert_opt.output_file);
1528 freez(cert_opt.output_file);
1529 freez(cert_opt.subject_key);
1533 if (unlink(cert_opt.subject_key))
1535 log_error(LOG_LEVEL_ERROR, "Failed to unlink %s: %E",
1536 cert_opt.subject_key);
1538 freez(cert_opt.output_file);
1539 freez(cert_opt.subject_key);
1546 freez(cert_opt.output_file);
1547 freez(cert_opt.subject_key);
1554 * Create key for requested host
1556 int subject_key_len = generate_key(csp, &key_buf);
1557 if (subject_key_len < 0)
1559 freez(cert_opt.output_file);
1560 freez(cert_opt.subject_key);
1561 log_error(LOG_LEVEL_ERROR, "Key generating failed");
1566 * Initializing structures for certificate generating
1568 mbedtls_x509write_crt_init(&cert);
1569 mbedtls_x509write_crt_set_md_alg(&cert, CERT_SIGNATURE_ALGORITHM);
1570 mbedtls_pk_init(&loaded_issuer_key);
1571 mbedtls_pk_init(&loaded_subject_key);
1572 mbedtls_mpi_init(&serial);
1573 mbedtls_x509_crt_init(&issuer_cert);
1576 * Presetting parameters for certificate. We must compute total length
1579 size_t cert_params_len = strlen(CERT_PARAM_COMMON_NAME) +
1580 strlen(CERT_PARAM_ORGANIZATION) + strlen(CERT_PARAM_COUNTRY) +
1581 strlen(CERT_PARAM_ORG_UNIT) +
1582 3 * strlen(csp->http->host) + 1;
1583 char cert_params[cert_params_len];
1584 memset(cert_params, 0, cert_params_len);
1587 * Converting unsigned long serial number to char * serial number.
1588 * We must compute length of serial number in string + terminating null.
1590 unsigned long certificate_serial = get_certificate_serial(csp);
1591 unsigned long certificate_serial_time = (unsigned long)time(NULL);
1592 int serial_num_size = snprintf(NULL, 0, "%lu%lu",
1593 certificate_serial_time, certificate_serial) + 1;
1594 if (serial_num_size <= 0)
1596 serial_num_size = 1;
1599 char serial_num_text[serial_num_size]; /* Buffer for serial number */
1600 ret = snprintf(serial_num_text, (size_t)serial_num_size, "%lu%lu",
1601 certificate_serial_time, certificate_serial);
1602 if (ret < 0 || ret >= serial_num_size)
1604 log_error(LOG_LEVEL_ERROR,
1605 "Converting certificate serial number into string failed");
1611 * Preparing parameters for certificate
1613 strlcpy(cert_params, CERT_PARAM_COMMON_NAME, cert_params_len);
1614 strlcat(cert_params, csp->http->host, cert_params_len);
1615 strlcat(cert_params, CERT_PARAM_ORGANIZATION, cert_params_len);
1616 strlcat(cert_params, csp->http->host, cert_params_len);
1617 strlcat(cert_params, CERT_PARAM_ORG_UNIT, cert_params_len);
1618 strlcat(cert_params, csp->http->host, cert_params_len);
1619 strlcat(cert_params, CERT_PARAM_COUNTRY, cert_params_len);
1621 cert_opt.issuer_crt = csp->config->ca_cert_file;
1622 cert_opt.issuer_key = csp->config->ca_key_file;
1624 if (get_certificate_valid_from_date(cert_valid_from, sizeof(cert_valid_from))
1625 || get_certificate_valid_to_date(cert_valid_to, sizeof(cert_valid_to)))
1627 log_error(LOG_LEVEL_ERROR, "Generating one of the validity dates failed");
1632 cert_opt.subject_pwd = CERT_SUBJECT_PASSWORD;
1633 cert_opt.issuer_pwd = csp->config->ca_password;
1634 cert_opt.subject_name = cert_params;
1635 cert_opt.not_before = cert_valid_from;
1636 cert_opt.not_after = cert_valid_to;
1637 cert_opt.serial = serial_num_text;
1639 cert_opt.max_pathlen = -1;
1642 * Test if the private key was already created.
1643 * XXX: Can this still happen?
1645 if (subject_key_len == 0)
1647 log_error(LOG_LEVEL_ERROR, "Subject key was already created");
1655 ret = seed_rng(csp);
1663 * Parse serial to MPI
1665 ret = mbedtls_mpi_read_string(&serial, 10, cert_opt.serial);
1668 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1669 log_error(LOG_LEVEL_ERROR,
1670 "mbedtls_mpi_read_string failed: %s", err_buf);
1676 * Loading certificates
1678 ret = mbedtls_x509_crt_parse_file(&issuer_cert, cert_opt.issuer_crt);
1681 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1682 log_error(LOG_LEVEL_ERROR, "Loading issuer certificate %s failed: %s",
1683 cert_opt.issuer_crt, err_buf);
1688 ret = mbedtls_x509_dn_gets(cert_opt.issuer_name,
1689 sizeof(cert_opt.issuer_name), &issuer_cert.subject);
1692 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1693 log_error(LOG_LEVEL_ERROR, "mbedtls_x509_dn_gets failed: %s", err_buf);
1699 * Loading keys from file or from buffer
1701 if (key_buf != NULL && subject_key_len > 0)
1703 /* Key was created in this function and is stored in buffer */
1704 ret = mbedtls_pk_parse_key(&loaded_subject_key, key_buf,
1705 (size_t)(subject_key_len + 1), (unsigned const char *)
1706 cert_opt.subject_pwd, strlen(cert_opt.subject_pwd));
1710 /* Key wasn't created in this function, because it already existed */
1711 ret = mbedtls_pk_parse_keyfile(&loaded_subject_key,
1712 cert_opt.subject_key, cert_opt.subject_pwd);
1717 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1718 log_error(LOG_LEVEL_ERROR, "Parsing subject key %s failed: %s",
1719 cert_opt.subject_key, err_buf);
1724 ret = mbedtls_pk_parse_keyfile(&loaded_issuer_key, cert_opt.issuer_key,
1725 cert_opt.issuer_pwd);
1728 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1729 log_error(LOG_LEVEL_ERROR,
1730 "Parsing issuer key %s failed: %s", cert_opt.issuer_key, err_buf);
1736 * Check if key and issuer certificate match
1738 if (!mbedtls_pk_can_do(&issuer_cert.pk, MBEDTLS_PK_RSA) ||
1739 mbedtls_mpi_cmp_mpi(&mbedtls_pk_rsa(issuer_cert.pk)->N,
1740 &mbedtls_pk_rsa(*issuer_key)->N) != 0 ||
1741 mbedtls_mpi_cmp_mpi(&mbedtls_pk_rsa(issuer_cert.pk)->E,
1742 &mbedtls_pk_rsa(*issuer_key)->E) != 0)
1744 log_error(LOG_LEVEL_ERROR,
1745 "Issuer key doesn't match issuer certificate");
1750 mbedtls_x509write_crt_set_subject_key(&cert, subject_key);
1751 mbedtls_x509write_crt_set_issuer_key(&cert, issuer_key);
1754 * Setting parameters of signed certificate
1756 ret = mbedtls_x509write_crt_set_subject_name(&cert, cert_opt.subject_name);
1759 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1760 log_error(LOG_LEVEL_ERROR,
1761 "Setting subject name in signed certificate failed: %s", err_buf);
1766 ret = mbedtls_x509write_crt_set_issuer_name(&cert, cert_opt.issuer_name);
1769 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1770 log_error(LOG_LEVEL_ERROR,
1771 "Setting issuer name in signed certificate failed: %s", err_buf);
1776 ret = mbedtls_x509write_crt_set_serial(&cert, &serial);
1779 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1780 log_error(LOG_LEVEL_ERROR,
1781 "Setting serial number in signed certificate failed: %s", err_buf);
1786 ret = mbedtls_x509write_crt_set_validity(&cert, cert_opt.not_before,
1787 cert_opt.not_after);
1790 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1791 log_error(LOG_LEVEL_ERROR,
1792 "Setting validity in signed certificate failed: %s", err_buf);
1798 * Setting the basicConstraints extension for certificate
1800 ret = mbedtls_x509write_crt_set_basic_constraints(&cert, cert_opt.is_ca,
1801 cert_opt.max_pathlen);
1804 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1805 log_error(LOG_LEVEL_ERROR, "Setting the basicConstraints extension "
1806 "in signed certificate failed: %s", err_buf);
1811 #if defined(MBEDTLS_SHA1_C)
1812 /* Setting the subjectKeyIdentifier extension for certificate */
1813 ret = mbedtls_x509write_crt_set_subject_key_identifier(&cert);
1816 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1817 log_error(LOG_LEVEL_ERROR, "mbedtls_x509write_crt_set_subject_key_"
1818 "identifier failed: %s", err_buf);
1823 /* Setting the authorityKeyIdentifier extension for certificate */
1824 ret = mbedtls_x509write_crt_set_authority_key_identifier(&cert);
1827 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1828 log_error(LOG_LEVEL_ERROR, "mbedtls_x509write_crt_set_authority_key_"
1829 "identifier failed: %s", err_buf);
1833 #endif /* MBEDTLS_SHA1_C */
1835 if (set_subject_alternative_name(&cert, csp->http->host))
1837 /* Errors are already logged by set_subject_alternative_name() */
1843 * Writing certificate into file
1845 ret = write_certificate(&cert, cert_opt.output_file,
1846 mbedtls_ctr_drbg_random, &ctr_drbg);
1849 log_error(LOG_LEVEL_ERROR, "Writing certificate into file failed");
1855 * Freeing used structures
1857 mbedtls_x509write_crt_free(&cert);
1858 mbedtls_pk_free(&loaded_subject_key);
1859 mbedtls_pk_free(&loaded_issuer_key);
1860 mbedtls_mpi_free(&serial);
1861 mbedtls_x509_crt_free(&issuer_cert);
1863 freez(cert_opt.subject_key);
1864 freez(cert_opt.output_file);
1871 /*********************************************************************
1873 * Function : make_certs_path
1875 * Description : Creates path to file from three pieces. This function
1876 * takes parameters and puts them in one new mallocated
1877 * char * in correct order. Returned variable must be freed
1878 * by caller. This function is mainly used for creating
1879 * paths of certificates and keys files.
1882 * 1 : conf_dir = Name/path of directory where is the file.
1883 * '.' can be used for current directory.
1884 * 2 : file_name = Name of file in conf_dir without suffix.
1885 * 3 : suffix = Suffix of given file_name.
1887 * Returns : path => Path was built up successfully
1888 * NULL => Path can't be built up
1890 *********************************************************************/
1891 static char *make_certs_path(const char *conf_dir, const char *file_name,
1894 /* Test if all given parameters are valid */
1895 if (conf_dir == NULL || *conf_dir == '\0' || file_name == NULL ||
1896 *file_name == '\0' || suffix == NULL || *suffix == '\0')
1898 log_error(LOG_LEVEL_ERROR,
1899 "make_certs_path failed: bad input parameters");
1904 size_t path_size = strlen(conf_dir)
1905 + strlen(file_name) + strlen(suffix) + 2;
1907 /* Setting delimiter and editing path length */
1908 #if defined(_WIN32) || defined(__OS2__)
1909 char delim[] = "\\";
1911 #else /* ifndef _WIN32 || __OS2__ */
1913 #endif /* ifndef _WIN32 || __OS2__ */
1916 * Building up path from many parts
1919 if (*conf_dir != '/' && basedir && *basedir)
1922 * Replacing conf_dir with basedir. This new variable contains
1923 * absolute path to cwd.
1925 path_size += strlen(basedir) + 2;
1926 path = zalloc_or_die(path_size);
1928 strlcpy(path, basedir, path_size);
1929 strlcat(path, delim, path_size);
1930 strlcat(path, conf_dir, path_size);
1931 strlcat(path, delim, path_size);
1932 strlcat(path, file_name, path_size);
1933 strlcat(path, suffix, path_size);
1936 #endif /* defined unix */
1938 path = zalloc_or_die(path_size);
1940 strlcpy(path, conf_dir, path_size);
1941 strlcat(path, delim, path_size);
1942 strlcat(path, file_name, path_size);
1943 strlcat(path, suffix, path_size);
1950 /*********************************************************************
1952 * Function : get_certificate_serial
1954 * Description : Computes serial number for new certificate from host
1955 * name hash. This hash must be already saved in csp
1959 * 1 : csp = Current client state (buffers, headers, etc...)
1961 * Returns : Serial number for new certificate
1963 *********************************************************************/
1964 static unsigned long get_certificate_serial(struct client_state *csp)
1966 unsigned long exp = 1;
1967 unsigned long serial = 0;
1969 int i = CERT_SERIAL_NUM_LENGTH;
1973 serial += exp * (unsigned)csp->http->hash_of_host[i];
1980 /*********************************************************************
1982 * Function : ssl_send_certificate_error
1984 * Description : Sends info about invalid server certificate to client.
1985 * Sent message is including all trusted chain certificates,
1986 * that can be downloaded in web browser.
1989 * 1 : csp = Current client state (buffers, headers, etc...)
1993 *********************************************************************/
1994 extern void ssl_send_certificate_error(struct client_state *csp)
1996 size_t message_len = 0;
1998 struct certs_chain *cert = NULL;
2000 /* Header of message with certificate information */
2001 const char message_begin[] =
2002 "HTTP/1.1 200 OK\r\n"
2003 "Content-Type: text/html\r\n"
2004 "Connection: close\r\n\r\n"
2005 "<html><body><h1>Server certificate verification failed</h1><p>Reason: ";
2006 const char message_end[] = "</body></html>\r\n\r\n";
2007 char reason[INVALID_CERT_INFO_BUF_SIZE];
2008 memset(reason, 0, sizeof(reason));
2010 /* Get verification message from verification return code */
2011 mbedtls_x509_crt_verify_info(reason, sizeof(reason), " ",
2012 csp->server_cert_verification_result);
2015 * Computing total length of message with all certificates inside
2017 message_len = strlen(message_begin) + strlen(message_end)
2018 + strlen(reason) + strlen("</p>") + 1;
2020 cert = &(csp->server_certs_chain);
2021 while (cert->next != NULL)
2023 size_t base64_len = 4 * ((strlen(cert->file_buf) + 2) / 3) + 1;
2025 message_len += strlen(cert->info_buf) + strlen("<pre></pre>\n")
2026 + base64_len + strlen("<a href=\"data:application"
2027 "/x-x509-ca-cert;base64,\">Download certificate</a>");
2032 * Joining all blocks in one long message
2034 char message[message_len];
2035 memset(message, 0, message_len);
2037 strlcpy(message, message_begin, message_len);
2038 strlcat(message, reason , message_len);
2039 strlcat(message, "</p>" , message_len);
2041 cert = &(csp->server_certs_chain);
2042 while (cert->next != NULL)
2045 size_t base64_len = 4 * ((strlen(cert->file_buf) + 2) / 3) + 1; /* +1 for terminating null*/
2046 char base64_buf[base64_len];
2047 memset(base64_buf, 0, base64_len);
2049 /* Encoding certificate into base64 code */
2050 ret = mbedtls_base64_encode((unsigned char*)base64_buf,
2051 base64_len, &olen, (const unsigned char*)cert->file_buf,
2052 strlen(cert->file_buf));
2055 log_error(LOG_LEVEL_ERROR,
2056 "Encoding to base64 failed, buffer is to small");
2059 strlcat(message, "<pre>", message_len);
2060 strlcat(message, cert->info_buf, message_len);
2061 strlcat(message, "</pre>\n", message_len);
2065 strlcat(message, "<a href=\"data:application/x-x509-ca-cert;base64,",
2067 strlcat(message, base64_buf, message_len);
2068 strlcat(message, "\">Download certificate</a>", message_len);
2073 strlcat(message, message_end, message_len);
2076 * Sending final message to client
2078 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
2079 (const unsigned char *)message, strlen(message));
2081 free_certificate_chain(csp);
2085 /*********************************************************************
2087 * Function : ssl_verify_callback
2089 * Description : This is a callback function for certificate verification.
2090 * It's called once for each certificate in the server's
2091 * certificate trusted chain and prepares information about
2092 * the certificate. The information can be used to inform
2093 * the user about invalid certificates.
2096 * 1 : csp_void = Current client state (buffers, headers, etc...)
2097 * 2 : crt = certificate from trusted chain
2098 * 3 : depth = depth in trusted chain
2099 * 4 : flags = certificate flags
2101 * Returns : 0 on success and negative value on error
2103 *********************************************************************/
2104 static int ssl_verify_callback(void *csp_void, mbedtls_x509_crt *crt,
2105 int depth, uint32_t *flags)
2107 struct client_state *csp = (struct client_state *)csp_void;
2108 struct certs_chain *last = &(csp->server_certs_chain);
2113 * Searching for last item in certificates linked list
2115 while (last->next != NULL)
2121 * Preparing next item in linked list for next certificate
2123 last->next = malloc_or_die(sizeof(struct certs_chain));
2124 last->next->next = NULL;
2125 memset(last->next->info_buf, 0, sizeof(last->next->info_buf));
2126 memset(last->next->file_buf, 0, sizeof(last->next->file_buf));
2129 * Saving certificate file into buffer
2131 if ((ret = mbedtls_pem_write_buffer(PEM_BEGIN_CRT, PEM_END_CRT,
2132 crt->raw.p, crt->raw.len, (unsigned char *)last->file_buf,
2133 sizeof(last->file_buf)-1, &olen)) != 0)
2135 char err_buf[ERROR_BUF_SIZE];
2137 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
2138 log_error(LOG_LEVEL_ERROR, "mbedtls_pem_write_buffer() failed: %s",
2145 * Saving certificate information into buffer
2148 char buf[CERT_INFO_BUF_SIZE];
2151 mbedtls_x509_crt_info(buf, sizeof(buf), CERT_INFO_PREFIX, crt);
2152 encoded_text = html_encode(buf);
2153 strlcpy(last->info_buf, encoded_text, sizeof(last->info_buf));
2154 freez(encoded_text);
2161 /*********************************************************************
2163 * Function : free_certificate_chain
2165 * Description : Frees certificates linked list. This linked list is
2166 * used to save information about certificates in
2170 * 1 : csp = Current client state (buffers, headers, etc...)
2174 *********************************************************************/
2175 static void free_certificate_chain(struct client_state *csp)
2177 struct certs_chain *cert = csp->server_certs_chain.next;
2179 /* Cleaning buffers */
2180 memset(csp->server_certs_chain.info_buf, 0,
2181 sizeof(csp->server_certs_chain.info_buf));
2182 memset(csp->server_certs_chain.file_buf, 0,
2183 sizeof(csp->server_certs_chain.file_buf));
2184 csp->server_certs_chain.next = NULL;
2186 /* Freeing memory in whole linked list */
2187 while (cert != NULL)
2189 struct certs_chain *cert_for_free = cert;
2191 freez(cert_for_free);
2196 /*********************************************************************
2198 * Function : file_exists
2200 * Description : Tests if file exists and is readable.
2203 * 1 : path = Path to tested file.
2205 * Returns : 1 => File exists and is readable.
2206 * 0 => File doesn't exist or is not readable.
2208 *********************************************************************/
2209 static int file_exists(const char *path)
2212 if ((f = fopen(path, "r")) != NULL)
2222 /*********************************************************************
2224 * Function : host_to_hash
2226 * Description : Creates MD5 hash from host name. Host name is loaded
2227 * from structure csp and saved again into it.
2230 * 1 : csp = Current client state (buffers, headers, etc...)
2232 * Returns : 1 => Error while creating hash
2233 * 0 => Hash created successfully
2235 *********************************************************************/
2236 static int host_to_hash(struct client_state *csp)
2240 #if !defined(MBEDTLS_MD5_C)
2241 #error mbedTLS needs to be compiled with md5 support
2243 memset(csp->http->hash_of_host, 0, sizeof(csp->http->hash_of_host));
2244 mbedtls_md5((unsigned char *)csp->http->host, strlen(csp->http->host),
2245 csp->http->hash_of_host);
2247 /* Converting hash into string with hex */
2251 if ((ret = sprintf((char *)csp->http->hash_of_host_hex + 2 * i, "%02x",
2252 csp->http->hash_of_host[i])) < 0)
2254 log_error(LOG_LEVEL_ERROR, "Sprintf return value: %d", ret);
2260 #endif /* MBEDTLS_MD5_C */
2264 /*********************************************************************
2266 * Function : tunnel_established_successfully
2268 * Description : Check if parent proxy server response contains
2269 * information about successfully created connection with
2270 * destination server. (HTTP/... 2xx ...)
2273 * 1 : server_response = Buffer with parent proxy server response
2274 * 2 : response_len = Length of server_response
2276 * Returns : 1 => Connection created successfully
2277 * 0 => Connection wasn't created successfully
2279 *********************************************************************/
2280 extern int tunnel_established_successfully(const char *server_response,
2281 unsigned int response_len)
2283 unsigned int pos = 0;
2285 if (server_response == NULL)
2290 /* Tests if "HTTP/" string is at the begin of received response */
2291 if (strncmp(server_response, "HTTP/", 5) != 0)
2296 for (pos = 0; pos < response_len; pos++)
2298 if (server_response[pos] == ' ')
2305 * response_len -3 because of buffer end, response structure and 200 code.
2306 * There must be at least 3 chars after space.
2307 * End of buffer: ... 2xx'\0'
2310 if (pos >= (response_len - 3))
2315 /* Test HTTP status code */
2316 if (server_response[pos + 1] != '2')
2325 /*********************************************************************
2327 * Function : seed_rng
2329 * Description : Seeding the RNG for all SSL uses
2332 * 1 : csp = Current client state (buffers, headers, etc...)
2334 * Returns : -1 => RNG wasn't seed successfully
2335 * 0 => RNG is seeded successfully
2337 *********************************************************************/
2338 static int seed_rng(struct client_state *csp)
2341 char err_buf[ERROR_BUF_SIZE];
2343 if (rng_seeded == 0)
2345 privoxy_mutex_lock(&rng_mutex);
2346 if (rng_seeded == 0)
2348 mbedtls_ctr_drbg_init(&ctr_drbg);
2349 mbedtls_entropy_init(&entropy);
2350 ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func,
2354 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
2355 log_error(LOG_LEVEL_ERROR,
2356 "mbedtls_ctr_drbg_seed failed: %s", err_buf);
2357 privoxy_mutex_unlock(&rng_mutex);
2362 privoxy_mutex_unlock(&rng_mutex);