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"
56 * Macros for searching begin and end of certificates.
57 * Necessary to convert structure mbedtls_x509_crt to crt file.
59 #define PEM_BEGIN_CRT "-----BEGIN CERTIFICATE-----\n"
60 #define PEM_END_CRT "-----END CERTIFICATE-----\n"
65 #define ERROR_BUF_SIZE 1024 /* Size of buffer for error messages */
66 #define CERTIFICATE_BUF_SIZE 16384 /* Size of buffer to save certificate. Value 4096 is mbedtls library buffer size for certificate in DER form */
67 #define PRIVATE_KEY_BUF_SIZE 16000 /* Size of buffer to save private key. Value 16000 is taken from mbed TLS library examples. */
68 #define RSA_KEY_PUBLIC_EXPONENT 65537 /* Public exponent for RSA private key generating */
69 #define RSA_KEYSIZE 2048 /* Size of generated RSA keys */
70 #define CERT_SIGNATURE_ALGORITHM MBEDTLS_MD_SHA256 /* The MD algorithm to use for the signature */
71 #define CERT_SERIAL_NUM_LENGTH 4 /* Bytes of hash to be used for creating serial number of certificate. Min=2 and max=16 */
72 #define INVALID_CERT_INFO_BUF_SIZE 2048 /* Size of buffer for message with information about reason of certificate invalidity. Data after the end of buffer will not be saved */
73 #define CERT_PARAM_COMMON_NAME "CN="
74 #define CERT_PARAM_ORGANIZATION ",O="
75 #define CERT_PARAM_ORG_UNIT ",OU="
76 #define CERT_PARAM_COUNTRY ",C=CZ"
77 #define KEY_FILE_TYPE ".pem"
78 #define CERT_FILE_TYPE ".crt"
79 #define CERT_SUBJECT_PASSWORD ""
80 #define CERT_INFO_PREFIX ""
83 * Properties of cert for generating
86 char *issuer_crt; /* filename of the issuer certificate */
87 char *subject_key; /* filename of the subject key file */
88 char *issuer_key; /* filename of the issuer key file */
89 const char *subject_pwd; /* password for the subject key file */
90 const char *issuer_pwd; /* password for the issuer key file */
91 char *output_file; /* where to store the constructed key file */
92 const char *subject_name; /* subject name for certificate */
93 char issuer_name[ISSUER_NAME_BUF_SIZE]; /* issuer name for certificate */
94 const char *not_before; /* validity period not before */
95 const char *not_after; /* validity period not after */
96 const char *serial; /* serial number string */
97 int is_ca; /* is a CA certificate */
98 int max_pathlen; /* maximum CA path length */
102 * Properties of key for generating
105 mbedtls_pk_type_t type; /* type of key to generate */
106 int rsa_keysize; /* length of key in bits */
107 char *key_file_path; /* filename of the key file */
110 static int generate_webpage_certificate(struct client_state *csp);
111 static char *make_certs_path(const char *conf_dir, const char *file_name, const char *suffix);
112 static int file_exists(const char *path);
113 static int host_to_hash(struct client_state *csp);
114 static int ssl_verify_callback(void *data, mbedtls_x509_crt *crt, int depth, uint32_t *flags);
115 static void free_certificate_chain(struct client_state *csp);
116 static unsigned long get_certificate_serial(struct client_state *csp);
117 static void free_client_ssl_structures(struct client_state *csp);
118 static void free_server_ssl_structures(struct client_state *csp);
119 static int seed_rng(struct client_state *csp);
121 /*********************************************************************
123 * Function : client_use_ssl
125 * Description : Tests if client in current client state structure
126 * should use SSL connection or standard connection.
129 * 1 : csp = Current client state (buffers, headers, etc...)
131 * Returns : If client should use TLS/SSL connection, 1 is returned.
132 * Otherwise 0 is returned.
134 *********************************************************************/
135 extern int client_use_ssl(const struct client_state *csp)
137 return csp->http->client_ssl;
141 /*********************************************************************
143 * Function : server_use_ssl
145 * Description : Tests if server in current client state structure
146 * should use SSL connection or standard connection.
149 * 1 : csp = Current client state (buffers, headers, etc...)
151 * Returns : If server should use TLS/SSL connection, 1 is returned.
152 * Otherwise 0 is returned.
154 *********************************************************************/
155 extern int server_use_ssl(const struct client_state *csp)
157 return csp->http->server_ssl;
161 /*********************************************************************
163 * Function : is_ssl_pending
165 * Description : Tests if there are some waiting data on ssl connection.
166 * Only considers data that has actually been received
167 * locally and ignores data that is still on the fly
168 * or has not yet been sent by the remote end.
171 * 1 : ssl = SSL context to test
173 * Returns : 0 => No data are pending
174 * >0 => Pending data length
176 *********************************************************************/
177 extern size_t is_ssl_pending(mbedtls_ssl_context *ssl)
184 return mbedtls_ssl_get_bytes_avail(ssl);
188 /*********************************************************************
190 * Function : ssl_send_data
192 * Description : Sends the content of buf (for n bytes) to given SSL
193 * connection context.
196 * 1 : ssl = SSL context to send data to
197 * 2 : buf = Pointer to data to be sent
198 * 3 : len = Length of data to be sent to the SSL context
200 * Returns : Length of sent data or negative value on error.
202 *********************************************************************/
203 extern int ssl_send_data(mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len)
206 size_t max_fragment_size = 0; /* Maximal length of data in one SSL fragment*/
207 int send_len = 0; /* length of one data part to send */
208 int pos = 0; /* Position of unsent part in buffer */
215 /* Getting maximal length of data sent in one fragment */
216 max_fragment_size = mbedtls_ssl_get_max_frag_len(ssl);
219 * Whole buffer must be sent in many fragments, because each fragment
220 * has its maximal length.
224 /* Compute length of data, that can be send in next fragment */
225 if ((pos + (int)max_fragment_size) > len)
227 send_len = (int)len - pos;
231 send_len = (int)max_fragment_size;
234 log_error(LOG_LEVEL_WRITING, "TLS: %N", send_len, buf+pos);
237 * Sending one part of the buffer
239 while ((ret = mbedtls_ssl_write(ssl,
240 (const unsigned char *)(buf + pos),
241 (size_t)send_len)) < 0)
243 if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
244 ret != MBEDTLS_ERR_SSL_WANT_WRITE)
246 char err_buf[ERROR_BUF_SIZE];
248 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
249 log_error(LOG_LEVEL_ERROR,
250 "Sending data over TLS/SSL failed: %s", err_buf);
254 /* Adding count of sent bytes to position in buffer */
255 pos = pos + send_len;
262 /*********************************************************************
264 * Function : ssl_recv_data
266 * Description : Receives data from given SSL context and puts
270 * 1 : ssl = SSL context to receive data from
271 * 2 : buf = Pointer to buffer where data will be written
272 * 3 : max_length = Maximum number of bytes to read
274 * Returns : Number of bytes read, 0 for EOF, or -1
277 *********************************************************************/
278 extern int ssl_recv_data(mbedtls_ssl_context *ssl, unsigned char *buf, size_t max_length)
281 memset(buf, 0, max_length);
284 * Receiving data from SSL context into buffer
288 ret = mbedtls_ssl_read(ssl, buf, max_length);
289 } while (ret == MBEDTLS_ERR_SSL_WANT_READ
290 || ret == MBEDTLS_ERR_SSL_WANT_WRITE);
294 char err_buf[ERROR_BUF_SIZE];
296 if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY)
298 log_error(LOG_LEVEL_CONNECT,
299 "The peer notified us that the connection is going to be closed");
302 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
303 log_error(LOG_LEVEL_ERROR,
304 "Receiving data over TLS/SSL failed: %s", err_buf);
309 log_error(LOG_LEVEL_RECEIVED, "TLS: %N", ret, buf);
315 /*********************************************************************
317 * Function : ssl_flush_socket
319 * Description : Send any pending "buffered" content with given
320 * SSL connection. Alternative to function flush_socket.
323 * 1 : ssl = SSL context to send buffer to
324 * 2 : iob = The I/O buffer to flush, usually csp->iob.
326 * Returns : On success, the number of bytes send are returned (zero
327 * indicates nothing was sent). On error, -1 is returned.
329 *********************************************************************/
330 extern long ssl_flush_socket(mbedtls_ssl_context *ssl, struct iob *iob)
332 /* Computing length of buffer part to send */
333 long len = iob->eod - iob->cur;
340 /* Sending data to given SSl context */
341 if (ssl_send_data(ssl, (const unsigned char *)iob->cur, (size_t)len) < 0)
345 iob->eod = iob->cur = iob->buf;
350 /*********************************************************************
352 * Function : ssl_debug_callback
354 * Description : Debug callback function for mbedtls library.
355 * Prints info into log file.
358 * 1 : ctx = File to save log in
359 * 2 : level = Debug level
360 * 3 : file = File calling debug message
361 * 4 : line = Line calling debug message
362 * 5 : str = Debug message
366 *********************************************************************/
367 static void ssl_debug_callback(void *ctx, int level, const char *file, int line, const char *str)
371 fprintf((FILE *)ctx, "%s:%04d: %s", file, line, str);
373 log_error(LOG_LEVEL_INFO, "SSL debug message: %s:%04d: %s", file, line, str);
378 /*********************************************************************
380 * Function : create_client_ssl_connection
382 * Description : Creates TLS/SSL secured connection with client
385 * 1 : csp = Current client state (buffers, headers, etc...)
387 * Returns : 0 on success, negative value if connection wasn't created
390 *********************************************************************/
391 extern int create_client_ssl_connection(struct client_state *csp)
393 /* Paths to certificates file and key file */
394 char *key_file = NULL;
395 char *ca_file = NULL;
396 char *cert_file = NULL;
398 char err_buf[ERROR_BUF_SIZE];
401 * Initializing mbedtls structures for TLS/SSL connection
403 mbedtls_net_init(&(csp->mbedtls_client_attr.socket_fd));
404 mbedtls_ssl_init(&(csp->mbedtls_client_attr.ssl));
405 mbedtls_ssl_config_init(&(csp->mbedtls_client_attr.conf));
406 mbedtls_x509_crt_init(&(csp->mbedtls_client_attr.server_cert));
407 mbedtls_pk_init(&(csp->mbedtls_client_attr.prim_key));
408 #if defined(MBEDTLS_SSL_CACHE_C)
409 mbedtls_ssl_cache_init(&(csp->mbedtls_client_attr.cache));
413 * Preparing hash of host for creating certificates
415 ret = host_to_hash(csp);
418 log_error(LOG_LEVEL_ERROR, "Generating hash of host failed: %d", ret);
424 * Preparing paths to certificates files and key file
426 ca_file = csp->config->ca_cert_file;
427 cert_file = make_certs_path(csp->config->certificate_directory,
428 (const char *)csp->http->hash_of_host_hex, CERT_FILE_TYPE);
429 key_file = make_certs_path(csp->config->certificate_directory,
430 (const char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
432 if (cert_file == NULL || key_file == NULL)
439 * Generating certificate for requested host. Mutex to prevent
440 * certificate and key inconsistence must be locked.
442 privoxy_mutex_lock(&certificate_mutex);
444 ret = generate_webpage_certificate(csp);
447 log_error(LOG_LEVEL_ERROR,
448 "Generate_webpage_certificate failed: %d", ret);
449 privoxy_mutex_unlock(&certificate_mutex);
453 privoxy_mutex_unlock(&certificate_mutex);
466 * Loading CA file, webpage certificate and key files
468 ret = mbedtls_x509_crt_parse_file(&(csp->mbedtls_client_attr.server_cert),
472 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
473 log_error(LOG_LEVEL_ERROR,
474 "Loading webpage certificate %s failed: %s", cert_file, err_buf);
479 ret = mbedtls_x509_crt_parse_file(&(csp->mbedtls_client_attr.server_cert),
483 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
484 log_error(LOG_LEVEL_ERROR,
485 "Loading CA certificate %s failed: %s", ca_file, err_buf);
490 ret = mbedtls_pk_parse_keyfile(&(csp->mbedtls_client_attr.prim_key),
494 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
495 log_error(LOG_LEVEL_ERROR,
496 "Loading and parsing webpage certificate private key %s failed: %s",
503 * Setting SSL parameters
505 ret = mbedtls_ssl_config_defaults(&(csp->mbedtls_client_attr.conf),
506 MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_TRANSPORT_STREAM,
507 MBEDTLS_SSL_PRESET_DEFAULT);
510 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
511 log_error(LOG_LEVEL_ERROR,
512 "mbedtls_ssl_config_defaults failed: %s", err_buf);
517 mbedtls_ssl_conf_rng(&(csp->mbedtls_client_attr.conf),
518 mbedtls_ctr_drbg_random, &ctr_drbg);
519 mbedtls_ssl_conf_dbg(&(csp->mbedtls_client_attr.conf),
520 ssl_debug_callback, stdout);
522 #if defined(MBEDTLS_SSL_CACHE_C)
523 mbedtls_ssl_conf_session_cache(&(csp->mbedtls_client_attr.conf),
524 &(csp->mbedtls_client_attr.cache), mbedtls_ssl_cache_get,
525 mbedtls_ssl_cache_set);
529 * Setting certificates
531 ret = mbedtls_ssl_conf_own_cert(&(csp->mbedtls_client_attr.conf),
532 &(csp->mbedtls_client_attr.server_cert),
533 &(csp->mbedtls_client_attr.prim_key));
536 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
537 log_error(LOG_LEVEL_ERROR,
538 "mbedtls_ssl_conf_own_cert failed: %s", err_buf);
543 ret = mbedtls_ssl_setup(&(csp->mbedtls_client_attr.ssl),
544 &(csp->mbedtls_client_attr.conf));
547 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
548 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_setup failed: %s", err_buf);
553 mbedtls_ssl_set_bio(&(csp->mbedtls_client_attr.ssl),
554 &(csp->mbedtls_client_attr.socket_fd), mbedtls_net_send,
555 mbedtls_net_recv, NULL);
556 mbedtls_ssl_session_reset(&(csp->mbedtls_client_attr.ssl));
559 * Setting socket fd in mbedtls_net_context structure. This structure
560 * can't be set by mbedtls functions, because we already have created
561 * a TCP connection when this function is called.
563 csp->mbedtls_client_attr.socket_fd.fd = csp->cfd;
566 * Handshake with client
568 log_error(LOG_LEVEL_CONNECT,
569 "Performing the TLS/SSL handshake with client. Hash of host: %s",
570 csp->http->hash_of_host_hex);
571 while ((ret = mbedtls_ssl_handshake(&(csp->mbedtls_client_attr.ssl))) != 0)
573 if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
574 ret != MBEDTLS_ERR_SSL_WANT_WRITE)
576 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
577 log_error(LOG_LEVEL_ERROR,
578 "medtls_ssl_handshake with client failed: %s", err_buf);
584 log_error(LOG_LEVEL_CONNECT, "Client successfully connected over TLS/SSL");
585 csp->ssl_with_client_is_opened = 1;
589 * Freeing allocated paths to files
594 /* Freeing structures if connection wasn't created successfully */
597 free_client_ssl_structures(csp);
603 /*********************************************************************
605 * Function : close_client_ssl_connection
607 * Description : Closes TLS/SSL connection with client. This function
608 * checks if this connection is already created.
611 * 1 : csp = Current client state (buffers, headers, etc...)
615 *********************************************************************/
616 extern void close_client_ssl_connection(struct client_state *csp)
620 if (csp->ssl_with_client_is_opened == 0)
626 * Notifying the peer that the connection is being closed.
629 ret = mbedtls_ssl_close_notify(&(csp->mbedtls_client_attr.ssl));
630 } while (ret == MBEDTLS_ERR_SSL_WANT_WRITE);
632 free_client_ssl_structures(csp);
633 csp->ssl_with_client_is_opened = 0;
637 /*********************************************************************
639 * Function : free_client_ssl_structures
641 * Description : Frees structures used for SSL communication with
645 * 1 : csp = Current client state (buffers, headers, etc...)
649 *********************************************************************/
650 static void free_client_ssl_structures(struct client_state *csp)
653 * We can't use function mbedtls_net_free, because this function
654 * inter alia close TCP connection on setted fd. Instead of this
655 * function, we change fd to -1, which is the same what does
656 * rest of mbedtls_net_free function.
658 csp->mbedtls_client_attr.socket_fd.fd = -1;
660 /* Freeing mbedtls structures */
661 mbedtls_x509_crt_free(&(csp->mbedtls_client_attr.server_cert));
662 mbedtls_pk_free(&(csp->mbedtls_client_attr.prim_key));
663 mbedtls_ssl_free(&(csp->mbedtls_client_attr.ssl));
664 mbedtls_ssl_config_free(&(csp->mbedtls_client_attr.conf));
665 #if defined(MBEDTLS_SSL_CACHE_C)
666 mbedtls_ssl_cache_free(&(csp->mbedtls_client_attr.cache));
671 /*********************************************************************
673 * Function : create_server_ssl_connection
675 * Description : Creates TLS/SSL secured connection with server.
678 * 1 : csp = Current client state (buffers, headers, etc...)
680 * Returns : 0 on success, negative value if connection wasn't created
683 *********************************************************************/
684 extern int create_server_ssl_connection(struct client_state *csp)
687 char err_buf[ERROR_BUF_SIZE];
688 char *trusted_cas_file = NULL;
689 int auth_mode = MBEDTLS_SSL_VERIFY_REQUIRED;
691 csp->server_cert_verification_result = SSL_CERT_NOT_VERIFIED;
692 csp->server_certs_chain.next = NULL;
694 /* Setting path to file with trusted CAs */
695 trusted_cas_file = csp->config->trusted_cas_file;
698 * Initializing mbedtls structures for TLS/SSL connection
700 mbedtls_net_init(&(csp->mbedtls_server_attr.socket_fd));
701 mbedtls_ssl_init(&(csp->mbedtls_server_attr.ssl));
702 mbedtls_ssl_config_init(&(csp->mbedtls_server_attr.conf));
703 mbedtls_x509_crt_init(&(csp->mbedtls_server_attr.ca_cert));
706 * Setting socket fd in mbedtls_net_context structure. This structure
707 * can't be set by mbedtls functions, because we already have created
708 * TCP connection when calling this function.
710 csp->mbedtls_server_attr.socket_fd.fd = csp->server_connection.sfd;
723 * Loading file with trusted CAs
725 ret = mbedtls_x509_crt_parse_file(&(csp->mbedtls_server_attr.ca_cert),
729 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
730 log_error(LOG_LEVEL_ERROR, "Loading trusted CAs file %s failed: %s",
731 trusted_cas_file, err_buf);
737 * Set TLS/SSL options
739 ret = mbedtls_ssl_config_defaults(&(csp->mbedtls_server_attr.conf),
740 MBEDTLS_SSL_IS_CLIENT,
741 MBEDTLS_SSL_TRANSPORT_STREAM,
742 MBEDTLS_SSL_PRESET_DEFAULT);
745 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
746 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_config_defaults failed: %s",
753 * Setting how strict should certificate verification be and other
754 * parameters for certificate verification
756 if (csp->dont_verify_certificate)
758 auth_mode = MBEDTLS_SSL_VERIFY_NONE;
761 mbedtls_ssl_conf_authmode(&(csp->mbedtls_server_attr.conf), auth_mode);
762 mbedtls_ssl_conf_ca_chain(&(csp->mbedtls_server_attr.conf),
763 &(csp->mbedtls_server_attr.ca_cert), NULL);
765 /* Setting callback function for certificates verification */
766 mbedtls_ssl_conf_verify(&(csp->mbedtls_server_attr.conf),
767 ssl_verify_callback, (void *)csp);
769 mbedtls_ssl_conf_rng(&(csp->mbedtls_server_attr.conf),
770 mbedtls_ctr_drbg_random, &ctr_drbg);
771 mbedtls_ssl_conf_dbg(&(csp->mbedtls_server_attr.conf),
772 ssl_debug_callback, stdout);
774 ret = mbedtls_ssl_setup(&(csp->mbedtls_server_attr.ssl),
775 &(csp->mbedtls_server_attr.conf));
778 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
779 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_setup failed: %s", err_buf);
785 * Set the hostname to check against the received server certificate
787 ret = mbedtls_ssl_set_hostname(&(csp->mbedtls_server_attr.ssl),
791 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
792 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_set_hostname failed: %s",
798 mbedtls_ssl_set_bio(&(csp->mbedtls_server_attr.ssl),
799 &(csp->mbedtls_server_attr.socket_fd), mbedtls_net_send,
800 mbedtls_net_recv, NULL);
803 * Handshake with server
805 log_error(LOG_LEVEL_CONNECT,
806 "Performing the TLS/SSL handshake with the server");
808 while ((ret = mbedtls_ssl_handshake(&(csp->mbedtls_server_attr.ssl))) != 0)
810 if (ret != MBEDTLS_ERR_SSL_WANT_READ
811 && ret != MBEDTLS_ERR_SSL_WANT_WRITE)
813 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
815 if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED)
817 char reason[INVALID_CERT_INFO_BUF_SIZE];
819 csp->server_cert_verification_result =
820 mbedtls_ssl_get_verify_result(&(csp->mbedtls_server_attr.ssl));
821 mbedtls_x509_crt_verify_info(reason, sizeof(reason), "",
822 csp->server_cert_verification_result);
824 /* Log the reason without the trailing new line */
825 log_error(LOG_LEVEL_ERROR,
826 "X509 certificate verification for %s failed: %N",
827 csp->http->hostport, strlen(reason)-1, reason);
832 log_error(LOG_LEVEL_ERROR,
833 "mbedtls_ssl_handshake with server failed: %s", err_buf);
834 free_certificate_chain(csp);
841 log_error(LOG_LEVEL_CONNECT, "Server successfully connected over TLS/SSL");
844 * Server certificate chain is valid, so we can clean
845 * chain, because we will not send it to client.
847 free_certificate_chain(csp);
849 csp->ssl_with_server_is_opened = 1;
850 csp->server_cert_verification_result =
851 mbedtls_ssl_get_verify_result(&(csp->mbedtls_server_attr.ssl));
854 /* Freeing structures if connection wasn't created successfully */
857 free_server_ssl_structures(csp);
864 /*********************************************************************
866 * Function : close_server_ssl_connection
868 * Description : Closes TLS/SSL connection with server. This function
869 * checks if this connection is already opened.
872 * 1 : csp = Current client state (buffers, headers, etc...)
876 *********************************************************************/
877 static void close_server_ssl_connection(struct client_state *csp)
881 if (csp->ssl_with_server_is_opened == 0)
887 * Notifying the peer that the connection is being closed.
890 ret = mbedtls_ssl_close_notify(&(csp->mbedtls_server_attr.ssl));
891 } while (ret == MBEDTLS_ERR_SSL_WANT_WRITE);
893 free_server_ssl_structures(csp);
894 csp->ssl_with_server_is_opened = 0;
898 /*********************************************************************
900 * Function : free_server_ssl_structures
902 * Description : Frees structures used for SSL communication with server
905 * 1 : csp = Current client state (buffers, headers, etc...)
909 *********************************************************************/
910 static void free_server_ssl_structures(struct client_state *csp)
913 * We can't use function mbedtls_net_free, because this function
914 * inter alia close TCP connection on setted fd. Instead of this
915 * function, we change fd to -1, which is the same what does
916 * rest of mbedtls_net_free function.
918 csp->mbedtls_server_attr.socket_fd.fd = -1;
920 mbedtls_x509_crt_free(&(csp->mbedtls_server_attr.ca_cert));
921 mbedtls_ssl_free(&(csp->mbedtls_server_attr.ssl));
922 mbedtls_ssl_config_free(&(csp->mbedtls_server_attr.conf));
926 /*********************************************************************
928 * Function : close_client_and_server_ssl_connections
930 * Description : Checks if client or server should use secured
931 * connection over SSL and if so, closes all of them.
934 * 1 : csp = Current client state (buffers, headers, etc...)
938 *********************************************************************/
939 extern void close_client_and_server_ssl_connections(struct client_state *csp)
941 if (client_use_ssl(csp) == 1)
943 close_client_ssl_connection(csp);
945 if (server_use_ssl(csp) == 1)
947 close_server_ssl_connection(csp);
951 /*====================== Certificates ======================*/
953 /*********************************************************************
955 * Function : write_certificate
957 * Description : Writes certificate into file.
960 * 1 : crt = certificate to write into file
961 * 2 : output_file = path to save certificate file
962 * 3 : f_rng = mbedtls_ctr_drbg_random
963 * 4 : p_rng = mbedtls_ctr_drbg_context
965 * Returns : Length of written certificate on success or negative value
968 *********************************************************************/
969 static int write_certificate(mbedtls_x509write_cert *crt, const char *output_file,
970 int(*f_rng)(void *, unsigned char *, size_t), void *p_rng)
974 unsigned char cert_buf[CERTIFICATE_BUF_SIZE + 1]; /* Buffer for certificate in PEM format + terminating NULL */
976 char err_buf[ERROR_BUF_SIZE];
978 memset(cert_buf, 0, sizeof(cert_buf));
981 * Writing certificate into PEM string. If buffer is too small, function
982 * returns specific error and no buffer overflow can happen.
984 if ((ret = mbedtls_x509write_crt_pem(crt, cert_buf,
985 sizeof(cert_buf) - 1, f_rng, p_rng)) != 0)
987 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
988 log_error(LOG_LEVEL_ERROR,
989 "Writing certificate into buffer failed: %s", err_buf);
993 len = strlen((char *)cert_buf);
996 * Saving certificate into file
998 if ((f = fopen(output_file, "w")) == NULL)
1000 log_error(LOG_LEVEL_ERROR, "Opening file %s to save certificate failed",
1005 if (fwrite(cert_buf, 1, len, f) != len)
1007 log_error(LOG_LEVEL_ERROR,
1008 "Writing certificate into file %s failed", output_file);
1019 /*********************************************************************
1021 * Function : write_private_key
1023 * Description : Writes private key into file and copies saved
1024 * content into given pointer to string. If function
1025 * returns 0 for success, this copy must be freed by
1029 * 1 : key = key to write into file
1030 * 2 : ret_buf = pointer to string with created key file content
1031 * 3 : key_file_path = path where to save key file
1033 * Returns : Length of written private key on success or negative value
1036 *********************************************************************/
1037 static int write_private_key(mbedtls_pk_context *key, unsigned char **ret_buf,
1038 const char *key_file_path)
1040 size_t len = 0; /* Length of created key */
1041 FILE *f = NULL; /* File to save certificate */
1043 char err_buf[ERROR_BUF_SIZE];
1045 /* Initializing buffer for key file content */
1046 *ret_buf = zalloc_or_die(PRIVATE_KEY_BUF_SIZE + 1);
1049 * Writing private key into PEM string
1051 if ((ret = mbedtls_pk_write_key_pem(key, *ret_buf, PRIVATE_KEY_BUF_SIZE)) != 0)
1053 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1054 log_error(LOG_LEVEL_ERROR,
1055 "Writing private key into PEM string failed: %s", err_buf);
1059 len = strlen((char *)*ret_buf);
1062 * Saving key into file
1064 if ((f = fopen(key_file_path, "wb")) == NULL)
1066 log_error(LOG_LEVEL_ERROR,
1067 "Opening file %s to save private key failed: %E",
1073 if (fwrite(*ret_buf, 1, len, f) != len)
1076 log_error(LOG_LEVEL_ERROR,
1077 "Writing private key into file %s failed",
1096 /*********************************************************************
1098 * Function : generate_key
1100 * Description : Tests if private key for host saved in csp already
1101 * exists. If this file doesn't exists, a new key is
1102 * generated and saved in a file. The generated key is also
1103 * copied into given parameter key_buf, which must be then
1104 * freed by caller. If file with key exists, key_buf
1105 * contain NULL and no private key is generated.
1108 * 1 : csp = Current client state (buffers, headers, etc...)
1109 * 2 : key_buf = buffer to save new generated key
1111 * Returns : -1 => Error while generating private key
1112 * 0 => Key already exists
1113 * >0 => Length of generated private key
1115 *********************************************************************/
1116 static int generate_key(struct client_state *csp, unsigned char **key_buf)
1118 mbedtls_pk_context key;
1119 key_options key_opt;
1121 char err_buf[ERROR_BUF_SIZE];
1123 key_opt.key_file_path = NULL;
1126 * Initializing structures for key generating
1128 mbedtls_pk_init(&key);
1131 * Preparing path for key file and other properties for generating key
1133 key_opt.type = MBEDTLS_PK_RSA;
1134 key_opt.rsa_keysize = RSA_KEYSIZE;
1136 key_opt.key_file_path = make_certs_path(csp->config->certificate_directory,
1137 (char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
1138 if (key_opt.key_file_path == NULL)
1145 * Test if key already exists. If so, we don't have to create it again.
1147 if (file_exists(key_opt.key_file_path) == 1)
1156 ret = seed_rng(csp);
1164 * Setting attributes of private key and generating it
1166 if ((ret = mbedtls_pk_setup(&key,
1167 mbedtls_pk_info_from_type(key_opt.type))) != 0)
1169 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1170 log_error(LOG_LEVEL_ERROR, "mbedtls_pk_setup failed: %s", err_buf);
1175 ret = mbedtls_rsa_gen_key(mbedtls_pk_rsa(key), mbedtls_ctr_drbg_random,
1176 &ctr_drbg, (unsigned)key_opt.rsa_keysize, RSA_KEY_PUBLIC_EXPONENT);
1179 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1180 log_error(LOG_LEVEL_ERROR, "Key generating failed: %s", err_buf);
1186 * Exporting private key into file
1188 if ((ret = write_private_key(&key, key_buf, key_opt.key_file_path)) < 0)
1190 log_error(LOG_LEVEL_ERROR,
1191 "Writing private key into file %s failed", key_opt.key_file_path);
1198 * Freeing used variables
1200 freez(key_opt.key_file_path);
1202 mbedtls_pk_free(&key);
1208 /*********************************************************************
1210 * Function : ssl_certificate_is_invalid
1212 * Description : Checks whether or not a certificate is valid.
1213 * Currently only checks that the certificate can be
1214 * parsed and that the "valid to" date is in the future.
1217 * 1 : cert_file = The certificate to check
1219 * Returns : 0 => The certificate is valid.
1220 * 1 => The certificate is invalid
1222 *********************************************************************/
1223 static int ssl_certificate_is_invalid(const char *cert_file)
1225 mbedtls_x509_crt cert;
1228 mbedtls_x509_crt_init(&cert);
1230 ret = mbedtls_x509_crt_parse_file(&cert, cert_file);
1233 char err_buf[ERROR_BUF_SIZE];
1235 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1236 log_error(LOG_LEVEL_ERROR,
1237 "Loading certificate %s to check validity failed: %s",
1238 cert_file, err_buf);
1239 mbedtls_x509_crt_free(&cert);
1243 if (mbedtls_x509_time_is_past(&cert.valid_to))
1245 mbedtls_x509_crt_free(&cert);
1250 mbedtls_x509_crt_free(&cert);
1257 /*********************************************************************
1259 * Function : generate_certificate_valid_date
1261 * Description : Turns a time_t into the format expected by mbedTLS.
1264 * 1 : time_spec = The timestamp to convert
1265 * 2 : buffer = The buffer to write the date to
1266 * 3 : buffer_size = The size of the buffer
1268 * Returns : 0 => The conversion worked
1269 * 1 => The conversion failed
1271 *********************************************************************/
1272 static int generate_certificate_valid_date(time_t time_spec, char *buffer,
1275 struct tm valid_date;
1278 #ifndef HAVE_GMTIME_R
1279 #error HTTP inspection currently requires gmtime_r() which seems to be missing
1281 if (NULL == gmtime_r(&time_spec, &valid_date))
1286 ret = strftime(buffer, buffer_size, "%Y%m%d%H%M%S", &valid_date);
1297 /*********************************************************************
1299 * Function : get_certificate_valid_from_date
1301 * Description : Generates a "valid from" date in the format
1302 * expected by mbedTLS.
1305 * 1 : buffer = The buffer to write the date to
1306 * 2 : buffer_size = The size of the buffer
1308 * Returns : 0 => The generation worked
1309 * 1 => The generation failed
1311 *********************************************************************/
1312 static int get_certificate_valid_from_date(char *buffer, size_t buffer_size)
1316 time_spec = time(NULL);
1317 /* 1 month in the past */
1318 time_spec -= 30 * 24 * 60 * 60;
1320 return generate_certificate_valid_date(time_spec, buffer, buffer_size);
1325 /*********************************************************************
1327 * Function : get_certificate_valid_to_date
1329 * Description : Generates a "valid to" date in the format
1330 * expected by mbedTLS.
1333 * 1 : buffer = The buffer to write the date to
1334 * 2 : buffer_size = The size of the buffer
1336 * Returns : 0 => The generation worked
1337 * 1 => The generation failed
1339 *********************************************************************/
1340 static int get_certificate_valid_to_date(char *buffer, size_t buffer_size)
1344 time_spec = time(NULL);
1345 /* Three months in the future */
1346 time_spec += 90 * 24 * 60 * 60;
1348 return generate_certificate_valid_date(time_spec, buffer, buffer_size);
1353 /*********************************************************************
1355 * Function : set_subject_alternative_name
1357 * Description : Sets the Subject Alternative Name extension to a cert
1360 * 1 : cert = The certificate to modify
1361 * 2 : hostname = The hostname to add
1363 * Returns : <0 => Error while creating certificate.
1366 *********************************************************************/
1367 static int set_subject_alternative_name(mbedtls_x509write_cert *cert, const char *hostname)
1369 char err_buf[ERROR_BUF_SIZE];
1371 char *subject_alternative_name;
1372 size_t subject_alternative_name_len;
1373 #define MBEDTLS_SUBJECT_ALTERNATIVE_NAME_MAX_LEN 255
1374 unsigned char san_buf[MBEDTLS_SUBJECT_ALTERNATIVE_NAME_MAX_LEN + 1];
1378 subject_alternative_name_len = strlen(hostname) + 1;
1379 subject_alternative_name = zalloc_or_die(subject_alternative_name_len);
1381 strlcpy(subject_alternative_name, hostname, subject_alternative_name_len);
1383 memset(san_buf, 0, sizeof(san_buf));
1385 c = san_buf + sizeof(san_buf);
1388 ret = mbedtls_asn1_write_raw_buffer(&c, san_buf,
1389 (const unsigned char *)subject_alternative_name,
1390 strlen(subject_alternative_name));
1393 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1394 log_error(LOG_LEVEL_ERROR,
1395 "mbedtls_asn1_write_raw_buffer() failed: %s", err_buf);
1400 ret = mbedtls_asn1_write_len(&c, san_buf, strlen(subject_alternative_name));
1403 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1404 log_error(LOG_LEVEL_ERROR,
1405 "mbedtls_asn1_write_len() failed: %s", err_buf);
1410 ret = mbedtls_asn1_write_tag(&c, san_buf, MBEDTLS_ASN1_CONTEXT_SPECIFIC | 2);
1413 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1414 log_error(LOG_LEVEL_ERROR,
1415 "mbedtls_asn1_write_tag() failed: %s", err_buf);
1420 ret = mbedtls_asn1_write_len(&c, san_buf, (size_t)len);
1423 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1424 log_error(LOG_LEVEL_ERROR,
1425 "mbedtls_asn1_write_len() failed: %s", err_buf);
1430 ret = mbedtls_asn1_write_tag(&c, san_buf,
1431 MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE);
1434 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1435 log_error(LOG_LEVEL_ERROR,
1436 "mbedtls_asn1_write_tag() failed: %s", err_buf);
1441 ret = mbedtls_x509write_crt_set_extension(cert,
1442 MBEDTLS_OID_SUBJECT_ALT_NAME,
1443 MBEDTLS_OID_SIZE(MBEDTLS_OID_SUBJECT_ALT_NAME),
1444 0, san_buf + sizeof(san_buf) - len, (size_t)len);
1447 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1448 log_error(LOG_LEVEL_ERROR,
1449 "mbedtls_x509write_crt_set_extension() failed: %s", err_buf);
1453 freez(subject_alternative_name);
1459 /*********************************************************************
1461 * Function : generate_webpage_certificate
1463 * Description : Creates certificate file in presetted directory.
1464 * If certificate already exists, no other certificate
1465 * will be created. Subject of certificate is named
1466 * by csp->http->host from parameter. This function also
1467 * triggers generating of private key for new certificate.
1470 * 1 : csp = Current client state (buffers, headers, etc...)
1472 * Returns : -1 => Error while creating certificate.
1473 * 0 => Certificate already exists.
1474 * >0 => Length of created certificate.
1476 *********************************************************************/
1477 static int generate_webpage_certificate(struct client_state *csp)
1479 mbedtls_x509_crt issuer_cert;
1480 mbedtls_pk_context loaded_issuer_key, loaded_subject_key;
1481 mbedtls_pk_context *issuer_key = &loaded_issuer_key;
1482 mbedtls_pk_context *subject_key = &loaded_subject_key;
1483 mbedtls_x509write_cert cert;
1486 unsigned char *key_buf = NULL; /* Buffer for created key */
1489 char err_buf[ERROR_BUF_SIZE];
1490 cert_options cert_opt;
1491 char cert_valid_from[15];
1492 char cert_valid_to[15];
1494 /* Paths to keys and certificates needed to create certificate */
1495 cert_opt.issuer_key = NULL;
1496 cert_opt.subject_key = NULL;
1497 cert_opt.issuer_crt = NULL;
1499 cert_opt.output_file = make_certs_path(csp->config->certificate_directory,
1500 (const char *)csp->http->hash_of_host_hex, CERT_FILE_TYPE);
1501 if (cert_opt.output_file == NULL)
1506 cert_opt.subject_key = make_certs_path(csp->config->certificate_directory,
1507 (const char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
1508 if (cert_opt.subject_key == NULL)
1510 freez(cert_opt.output_file);
1514 if (file_exists(cert_opt.output_file) == 1)
1516 /* The file exists, but is it valid? */
1517 if (ssl_certificate_is_invalid(cert_opt.output_file))
1519 log_error(LOG_LEVEL_CONNECT,
1520 "Certificate %s is no longer valid. Removing it.",
1521 cert_opt.output_file);
1522 if (unlink(cert_opt.output_file))
1524 log_error(LOG_LEVEL_ERROR, "Failed to unlink %s: %E",
1525 cert_opt.output_file);
1527 freez(cert_opt.output_file);
1528 freez(cert_opt.subject_key);
1532 if (unlink(cert_opt.subject_key))
1534 log_error(LOG_LEVEL_ERROR, "Failed to unlink %s: %E",
1535 cert_opt.subject_key);
1537 freez(cert_opt.output_file);
1538 freez(cert_opt.subject_key);
1545 freez(cert_opt.output_file);
1546 freez(cert_opt.subject_key);
1553 * Create key for requested host
1555 int subject_key_len = generate_key(csp, &key_buf);
1556 if (subject_key_len < 0)
1558 freez(cert_opt.output_file);
1559 freez(cert_opt.subject_key);
1560 log_error(LOG_LEVEL_ERROR, "Key generating failed");
1565 * Initializing structures for certificate generating
1567 mbedtls_x509write_crt_init(&cert);
1568 mbedtls_x509write_crt_set_md_alg(&cert, CERT_SIGNATURE_ALGORITHM);
1569 mbedtls_pk_init(&loaded_issuer_key);
1570 mbedtls_pk_init(&loaded_subject_key);
1571 mbedtls_mpi_init(&serial);
1572 mbedtls_x509_crt_init(&issuer_cert);
1575 * Presetting parameters for certificate. We must compute total length
1578 size_t cert_params_len = strlen(CERT_PARAM_COMMON_NAME) +
1579 strlen(CERT_PARAM_ORGANIZATION) + strlen(CERT_PARAM_COUNTRY) +
1580 strlen(CERT_PARAM_ORG_UNIT) +
1581 3 * strlen(csp->http->host) + 1;
1582 char cert_params[cert_params_len];
1583 memset(cert_params, 0, cert_params_len);
1586 * Converting unsigned long serial number to char * serial number.
1587 * We must compute length of serial number in string + terminating null.
1589 unsigned long certificate_serial = get_certificate_serial(csp);
1590 unsigned long certificate_serial_time = (unsigned long)time(NULL);
1591 int serial_num_size = snprintf(NULL, 0, "%lu%lu",
1592 certificate_serial_time, certificate_serial) + 1;
1593 if (serial_num_size <= 0)
1595 serial_num_size = 1;
1598 char serial_num_text[serial_num_size]; /* Buffer for serial number */
1599 ret = snprintf(serial_num_text, (size_t)serial_num_size, "%lu%lu",
1600 certificate_serial_time, certificate_serial);
1601 if (ret < 0 || ret >= serial_num_size)
1603 log_error(LOG_LEVEL_ERROR,
1604 "Converting certificate serial number into string failed");
1610 * Preparing parameters for certificate
1612 strlcpy(cert_params, CERT_PARAM_COMMON_NAME, cert_params_len);
1613 strlcat(cert_params, csp->http->host, cert_params_len);
1614 strlcat(cert_params, CERT_PARAM_ORGANIZATION, cert_params_len);
1615 strlcat(cert_params, csp->http->host, cert_params_len);
1616 strlcat(cert_params, CERT_PARAM_ORG_UNIT, cert_params_len);
1617 strlcat(cert_params, csp->http->host, cert_params_len);
1618 strlcat(cert_params, CERT_PARAM_COUNTRY, cert_params_len);
1620 cert_opt.issuer_crt = csp->config->ca_cert_file;
1621 cert_opt.issuer_key = csp->config->ca_key_file;
1623 if (get_certificate_valid_from_date(cert_valid_from, sizeof(cert_valid_from))
1624 || get_certificate_valid_to_date(cert_valid_to, sizeof(cert_valid_to)))
1626 log_error(LOG_LEVEL_ERROR, "Generating one of the validity dates failed");
1631 cert_opt.subject_pwd = CERT_SUBJECT_PASSWORD;
1632 cert_opt.issuer_pwd = csp->config->ca_password;
1633 cert_opt.subject_name = cert_params;
1634 cert_opt.not_before = cert_valid_from;
1635 cert_opt.not_after = cert_valid_to;
1636 cert_opt.serial = serial_num_text;
1638 cert_opt.max_pathlen = -1;
1641 * Test if the private key was already created.
1642 * XXX: Can this still happen?
1644 if (subject_key_len == 0)
1646 log_error(LOG_LEVEL_ERROR, "Subject key was already created");
1654 ret = seed_rng(csp);
1662 * Parse serial to MPI
1664 ret = mbedtls_mpi_read_string(&serial, 10, cert_opt.serial);
1667 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1668 log_error(LOG_LEVEL_ERROR,
1669 "mbedtls_mpi_read_string failed: %s", err_buf);
1675 * Loading certificates
1677 ret = mbedtls_x509_crt_parse_file(&issuer_cert, cert_opt.issuer_crt);
1680 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1681 log_error(LOG_LEVEL_ERROR, "Loading issuer certificate %s failed: %s",
1682 cert_opt.issuer_crt, err_buf);
1687 ret = mbedtls_x509_dn_gets(cert_opt.issuer_name,
1688 sizeof(cert_opt.issuer_name), &issuer_cert.subject);
1691 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1692 log_error(LOG_LEVEL_ERROR, "mbedtls_x509_dn_gets failed: %s", err_buf);
1698 * Loading keys from file or from buffer
1700 if (key_buf != NULL && subject_key_len > 0)
1702 /* Key was created in this function and is stored in buffer */
1703 ret = mbedtls_pk_parse_key(&loaded_subject_key, key_buf,
1704 (size_t)(subject_key_len + 1), (unsigned const char *)
1705 cert_opt.subject_pwd, strlen(cert_opt.subject_pwd));
1709 /* Key wasn't created in this function, because it already existed */
1710 ret = mbedtls_pk_parse_keyfile(&loaded_subject_key,
1711 cert_opt.subject_key, cert_opt.subject_pwd);
1716 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1717 log_error(LOG_LEVEL_ERROR, "Parsing subject key %s failed: %s",
1718 cert_opt.subject_key, err_buf);
1723 ret = mbedtls_pk_parse_keyfile(&loaded_issuer_key, cert_opt.issuer_key,
1724 cert_opt.issuer_pwd);
1727 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1728 log_error(LOG_LEVEL_ERROR,
1729 "Parsing issuer key %s failed: %s", cert_opt.issuer_key, err_buf);
1735 * Check if key and issuer certificate match
1737 if (!mbedtls_pk_can_do(&issuer_cert.pk, MBEDTLS_PK_RSA) ||
1738 mbedtls_mpi_cmp_mpi(&mbedtls_pk_rsa(issuer_cert.pk)->N,
1739 &mbedtls_pk_rsa(*issuer_key)->N) != 0 ||
1740 mbedtls_mpi_cmp_mpi(&mbedtls_pk_rsa(issuer_cert.pk)->E,
1741 &mbedtls_pk_rsa(*issuer_key)->E) != 0)
1743 log_error(LOG_LEVEL_ERROR,
1744 "Issuer key doesn't match issuer certificate");
1749 mbedtls_x509write_crt_set_subject_key(&cert, subject_key);
1750 mbedtls_x509write_crt_set_issuer_key(&cert, issuer_key);
1753 * Setting parameters of signed certificate
1755 ret = mbedtls_x509write_crt_set_subject_name(&cert, cert_opt.subject_name);
1758 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1759 log_error(LOG_LEVEL_ERROR,
1760 "Setting subject name in signed certificate failed: %s", err_buf);
1765 ret = mbedtls_x509write_crt_set_issuer_name(&cert, cert_opt.issuer_name);
1768 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1769 log_error(LOG_LEVEL_ERROR,
1770 "Setting issuer name in signed certificate failed: %s", err_buf);
1775 ret = mbedtls_x509write_crt_set_serial(&cert, &serial);
1778 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1779 log_error(LOG_LEVEL_ERROR,
1780 "Setting serial number in signed certificate failed: %s", err_buf);
1785 ret = mbedtls_x509write_crt_set_validity(&cert, cert_opt.not_before,
1786 cert_opt.not_after);
1789 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1790 log_error(LOG_LEVEL_ERROR,
1791 "Setting validity in signed certificate failed: %s", err_buf);
1797 * Setting the basicConstraints extension for certificate
1799 ret = mbedtls_x509write_crt_set_basic_constraints(&cert, cert_opt.is_ca,
1800 cert_opt.max_pathlen);
1803 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1804 log_error(LOG_LEVEL_ERROR, "Setting the basicConstraints extension "
1805 "in signed certificate failed: %s", err_buf);
1810 #if defined(MBEDTLS_SHA1_C)
1811 /* Setting the subjectKeyIdentifier extension for certificate */
1812 ret = mbedtls_x509write_crt_set_subject_key_identifier(&cert);
1815 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1816 log_error(LOG_LEVEL_ERROR, "mbedtls_x509write_crt_set_subject_key_"
1817 "identifier failed: %s", err_buf);
1822 /* Setting the authorityKeyIdentifier extension for certificate */
1823 ret = mbedtls_x509write_crt_set_authority_key_identifier(&cert);
1826 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1827 log_error(LOG_LEVEL_ERROR, "mbedtls_x509write_crt_set_authority_key_"
1828 "identifier failed: %s", err_buf);
1832 #endif /* MBEDTLS_SHA1_C */
1834 if (set_subject_alternative_name(&cert, csp->http->host))
1836 /* Errors are already logged by set_subject_alternative_name() */
1842 * Writing certificate into file
1844 ret = write_certificate(&cert, cert_opt.output_file,
1845 mbedtls_ctr_drbg_random, &ctr_drbg);
1848 log_error(LOG_LEVEL_ERROR, "Writing certificate into file failed");
1854 * Freeing used structures
1856 mbedtls_x509write_crt_free(&cert);
1857 mbedtls_pk_free(&loaded_subject_key);
1858 mbedtls_pk_free(&loaded_issuer_key);
1859 mbedtls_mpi_free(&serial);
1860 mbedtls_x509_crt_free(&issuer_cert);
1862 freez(cert_opt.subject_key);
1863 freez(cert_opt.output_file);
1870 /*********************************************************************
1872 * Function : make_certs_path
1874 * Description : Creates path to file from three pieces. This function
1875 * takes parameters and puts them in one new mallocated
1876 * char * in correct order. Returned variable must be freed
1877 * by caller. This function is mainly used for creating
1878 * paths of certificates and keys files.
1881 * 1 : conf_dir = Name/path of directory where is the file.
1882 * '.' can be used for current directory.
1883 * 2 : file_name = Name of file in conf_dir without suffix.
1884 * 3 : suffix = Suffix of given file_name.
1886 * Returns : path => Path was built up successfully
1887 * NULL => Path can't be built up
1889 *********************************************************************/
1890 static char *make_certs_path(const char *conf_dir, const char *file_name,
1893 /* Test if all given parameters are valid */
1894 if (conf_dir == NULL || *conf_dir == '\0' || file_name == NULL ||
1895 *file_name == '\0' || suffix == NULL || *suffix == '\0')
1897 log_error(LOG_LEVEL_ERROR,
1898 "make_certs_path failed: bad input parameters");
1903 size_t path_size = strlen(conf_dir)
1904 + strlen(file_name) + strlen(suffix) + 2;
1906 /* Setting delimiter and editing path length */
1907 #if defined(_WIN32) || defined(__OS2__)
1908 char delim[] = "\\";
1910 #else /* ifndef _WIN32 || __OS2__ */
1912 #endif /* ifndef _WIN32 || __OS2__ */
1915 * Building up path from many parts
1918 if (*conf_dir != '/' && basedir && *basedir)
1921 * Replacing conf_dir with basedir. This new variable contains
1922 * absolute path to cwd.
1924 path_size += strlen(basedir) + 2;
1925 path = zalloc_or_die(path_size);
1927 strlcpy(path, basedir, path_size);
1928 strlcat(path, delim, path_size);
1929 strlcat(path, conf_dir, path_size);
1930 strlcat(path, delim, path_size);
1931 strlcat(path, file_name, path_size);
1932 strlcat(path, suffix, path_size);
1935 #endif /* defined unix */
1937 path = zalloc_or_die(path_size);
1939 strlcpy(path, conf_dir, path_size);
1940 strlcat(path, delim, path_size);
1941 strlcat(path, file_name, path_size);
1942 strlcat(path, suffix, path_size);
1949 /*********************************************************************
1951 * Function : get_certificate_serial
1953 * Description : Computes serial number for new certificate from host
1954 * name hash. This hash must be already saved in csp
1958 * 1 : csp = Current client state (buffers, headers, etc...)
1960 * Returns : Serial number for new certificate
1962 *********************************************************************/
1963 static unsigned long get_certificate_serial(struct client_state *csp)
1965 unsigned long exp = 1;
1966 unsigned long serial = 0;
1968 int i = CERT_SERIAL_NUM_LENGTH;
1972 serial += exp * (unsigned)csp->http->hash_of_host[i];
1979 /*********************************************************************
1981 * Function : ssl_send_certificate_error
1983 * Description : Sends info about invalid server certificate to client.
1984 * Sent message is including all trusted chain certificates,
1985 * that can be downloaded in web browser.
1988 * 1 : csp = Current client state (buffers, headers, etc...)
1992 *********************************************************************/
1993 extern void ssl_send_certificate_error(struct client_state *csp)
1995 size_t message_len = 0;
1997 struct certs_chain *cert = NULL;
1999 /* Header of message with certificate informations */
2000 const char message_begin[] =
2001 "HTTP/1.1 200 OK\r\n"
2002 "Content-Type: text/html\r\n"
2003 "Connection: close\r\n\r\n"
2004 "<html><body><h1>Server certificate verification failed</h1><p>Reason: ";
2005 const char message_end[] = "</body></html>\r\n\r\n";
2006 char reason[INVALID_CERT_INFO_BUF_SIZE];
2007 memset(reason, 0, sizeof(reason));
2009 /* Get verification message from verification return code */
2010 mbedtls_x509_crt_verify_info(reason, sizeof(reason), " ",
2011 csp->server_cert_verification_result);
2014 * Computing total length of message with all certificates inside
2016 message_len = strlen(message_begin) + strlen(message_end)
2017 + strlen(reason) + strlen("</p>") + 1;
2019 cert = &(csp->server_certs_chain);
2020 while (cert->next != NULL)
2022 size_t base64_len = 4 * ((strlen(cert->file_buf) + 2) / 3) + 1;
2024 message_len += strlen(cert->text_buf) + strlen("<pre></pre>\n")
2025 + base64_len + strlen("<a href=\"data:application"
2026 "/x-x509-ca-cert;base64,\">Download certificate</a>");
2031 * Joining all blocks in one long message
2033 char message[message_len];
2034 memset(message, 0, message_len);
2036 strlcpy(message, message_begin, message_len);
2037 strlcat(message, reason , message_len);
2038 strlcat(message, "</p>" , message_len);
2040 cert = &(csp->server_certs_chain);
2041 while (cert->next != NULL)
2044 size_t base64_len = 4 * ((strlen(cert->file_buf) + 2) / 3) + 1; /* +1 for terminating null*/
2045 char base64_buf[base64_len];
2046 memset(base64_buf, 0, base64_len);
2048 /* Encoding certificate into base64 code */
2049 ret = mbedtls_base64_encode((unsigned char*)base64_buf,
2050 base64_len, &olen, (const unsigned char*)cert->file_buf,
2051 strlen(cert->file_buf));
2054 log_error(LOG_LEVEL_ERROR,
2055 "Encoding to base64 failed, buffer is to small");
2058 strlcat(message, "<pre>", message_len);
2059 strlcat(message, cert->text_buf, message_len);
2060 strlcat(message, "</pre>\n", message_len);
2064 strlcat(message, "<a href=\"data:application/x-x509-ca-cert;base64,",
2066 strlcat(message, base64_buf, message_len);
2067 strlcat(message, "\">Download certificate</a>", message_len);
2072 strlcat(message, message_end, message_len);
2075 * Sending final message to client
2077 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
2078 (const unsigned char *)message, strlen(message));
2080 free_certificate_chain(csp);
2084 /*********************************************************************
2086 * Function : ssl_verify_callback
2088 * Description : This is a callback function for certificate verification.
2089 * It's called once for each certificate in the server's
2090 * certificate trusted chain and prepares information about
2091 * the certificate. The information can be used to inform
2092 * the user about invalid certificates.
2095 * 1 : csp_void = Current client state (buffers, headers, etc...)
2096 * 2 : crt = certificate from trusted chain
2097 * 3 : depth = depth in trusted chain
2098 * 4 : flags = certificate flags
2100 * Returns : 0 on success and negative value on error
2102 *********************************************************************/
2103 static int ssl_verify_callback(void *csp_void, mbedtls_x509_crt *crt,
2104 int depth, uint32_t *flags)
2106 struct client_state *csp = (struct client_state *)csp_void;
2107 struct certs_chain *last = &(csp->server_certs_chain);
2112 * Searching for last item in certificates linked list
2114 while (last->next != NULL)
2120 * Preparing next item in linked list for next certificate
2122 last->next = malloc_or_die(sizeof(struct certs_chain));
2123 last->next->next = NULL;
2124 memset(last->next->text_buf, 0, sizeof(last->next->text_buf));
2125 memset(last->next->file_buf, 0, sizeof(last->next->file_buf));
2128 * Saving certificate file into buffer
2130 if ((ret = mbedtls_pem_write_buffer(PEM_BEGIN_CRT, PEM_END_CRT,
2131 crt->raw.p, crt->raw.len, (unsigned char *)last->file_buf,
2132 sizeof(last->file_buf)-1, &olen)) != 0)
2134 char err_buf[ERROR_BUF_SIZE];
2136 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
2137 log_error(LOG_LEVEL_ERROR, "mbedtls_pem_write_buffer() failed: %s",
2144 * Saving certificate information into buffer
2146 mbedtls_x509_crt_info(last->text_buf, sizeof(last->text_buf) - 1,
2147 CERT_INFO_PREFIX, crt);
2153 /*********************************************************************
2155 * Function : free_certificate_chain
2157 * Description : Frees certificates linked list. This linked list is
2158 * used to save informations about certificates in
2162 * 1 : csp = Current client state (buffers, headers, etc...)
2166 *********************************************************************/
2167 static void free_certificate_chain(struct client_state *csp)
2169 struct certs_chain *cert = csp->server_certs_chain.next;
2171 /* Cleaning buffers */
2172 memset(csp->server_certs_chain.text_buf, 0,
2173 sizeof(csp->server_certs_chain.text_buf));
2174 memset(csp->server_certs_chain.file_buf, 0,
2175 sizeof(csp->server_certs_chain.file_buf));
2176 csp->server_certs_chain.next = NULL;
2178 /* Freeing memory in whole linked list */
2179 while (cert != NULL)
2181 struct certs_chain *cert_for_free = cert;
2183 freez(cert_for_free);
2188 /*********************************************************************
2190 * Function : file_exists
2192 * Description : Tests if file exists and is readable.
2195 * 1 : path = Path to tested file.
2197 * Returns : 1 => File exists and is readable.
2198 * 0 => File doesn't exist or is not readable.
2200 *********************************************************************/
2201 static int file_exists(const char *path)
2204 if ((f = fopen(path, "r")) != NULL)
2214 /*********************************************************************
2216 * Function : host_to_hash
2218 * Description : Creates MD5 hash from host name. Host name is loaded
2219 * from structure csp and saved again into it.
2222 * 1 : csp = Current client state (buffers, headers, etc...)
2224 * Returns : 1 => Error while creating hash
2225 * 0 => Hash created successfully
2227 *********************************************************************/
2228 static int host_to_hash(struct client_state *csp)
2232 #if !defined(MBEDTLS_MD5_C)
2233 #error mbedTLS needs to be compiled with md5 support
2235 memset(csp->http->hash_of_host, 0, sizeof(csp->http->hash_of_host));
2236 mbedtls_md5((unsigned char *)csp->http->host, strlen(csp->http->host),
2237 csp->http->hash_of_host);
2239 /* Converting hash into string with hex */
2243 if ((ret = sprintf((char *)csp->http->hash_of_host_hex + 2 * i, "%02x",
2244 csp->http->hash_of_host[i])) < 0)
2246 log_error(LOG_LEVEL_ERROR, "Sprintf return value: %d", ret);
2252 #endif /* MBEDTLS_MD5_C */
2256 /*********************************************************************
2258 * Function : tunnel_established_successfully
2260 * Description : Check if parent proxy server response contains
2261 * informations about successfully created connection with
2262 * destination server. (HTTP/... 2xx ...)
2265 * 1 : server_response = Buffer with parent proxy server response
2266 * 2 : response_len = Length of server_response
2268 * Returns : 1 => Connection created successfully
2269 * 0 => Connection wasn't created successfully
2271 *********************************************************************/
2272 extern int tunnel_established_successfully(const char *server_response,
2273 unsigned int response_len)
2275 unsigned int pos = 0;
2277 if (server_response == NULL)
2282 /* Tests if "HTTP/" string is at the begin of received response */
2283 if (strncmp(server_response, "HTTP/", 5) != 0)
2288 for (pos = 0; pos < response_len; pos++)
2290 if (server_response[pos] == ' ')
2297 * response_len -3 because of buffer end, response structure and 200 code.
2298 * There must be at least 3 chars after space.
2299 * End of buffer: ... 2xx'\0'
2302 if (pos >= (response_len - 3))
2307 /* Test HTTP status code */
2308 if (server_response[pos + 1] != '2')
2317 /*********************************************************************
2319 * Function : seed_rng
2321 * Description : Seeding the RNG for all SSL uses
2324 * 1 : csp = Current client state (buffers, headers, etc...)
2326 * Returns : -1 => RNG wasn't seed successfully
2327 * 0 => RNG is seeded successfully
2329 *********************************************************************/
2330 static int seed_rng(struct client_state *csp)
2333 char err_buf[ERROR_BUF_SIZE];
2335 if (rng_seeded == 0)
2337 privoxy_mutex_lock(&rng_mutex);
2338 if (rng_seeded == 0)
2340 mbedtls_ctr_drbg_init(&ctr_drbg);
2341 mbedtls_entropy_init(&entropy);
2342 ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func,
2346 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
2347 log_error(LOG_LEVEL_ERROR,
2348 "mbedtls_ctr_drbg_seed failed: %s", err_buf);
2349 privoxy_mutex_unlock(&rng_mutex);
2354 privoxy_mutex_unlock(&rng_mutex);