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
168 * 1 : ssl = SSL context to test
170 * Returns : 0 => No data are pending
171 * >0 => Pending data length
173 *********************************************************************/
174 extern size_t is_ssl_pending(mbedtls_ssl_context *ssl)
181 return mbedtls_ssl_get_bytes_avail(ssl);
185 /*********************************************************************
187 * Function : ssl_send_data
189 * Description : Sends the content of buf (for n bytes) to given SSL
190 * connection context.
193 * 1 : ssl = SSL context to send data to
194 * 2 : buf = Pointer to data to be sent
195 * 3 : len = Length of data to be sent to the SSL context
197 * Returns : Length of sent data or negative value on error.
199 *********************************************************************/
200 extern int ssl_send_data(mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len)
203 size_t max_fragment_size = 0; /* Maximal length of data in one SSL fragment*/
204 int send_len = 0; /* length of one data part to send */
205 int pos = 0; /* Position of unsent part in buffer */
212 /* Getting maximal length of data sent in one fragment */
213 max_fragment_size = mbedtls_ssl_get_max_frag_len(ssl);
216 * Whole buffer must be sent in many fragments, because each fragment
217 * has its maximal length.
221 /* Compute length of data, that can be send in next fragment */
222 if ((pos + (int)max_fragment_size) > len)
224 send_len = (int)len - pos;
228 send_len = (int)max_fragment_size;
231 log_error(LOG_LEVEL_WRITING, "TLS: %N", send_len, buf+pos);
234 * Sending one part of the buffer
236 while ((ret = mbedtls_ssl_write(ssl,
237 (const unsigned char *)(buf + pos),
238 (size_t)send_len)) < 0)
240 if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
241 ret != MBEDTLS_ERR_SSL_WANT_WRITE)
243 char err_buf[ERROR_BUF_SIZE];
245 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
246 log_error(LOG_LEVEL_ERROR,
247 "Sending data over TLS/SSL failed: %s", err_buf);
251 /* Adding count of sent bytes to position in buffer */
252 pos = pos + send_len;
259 /*********************************************************************
261 * Function : ssl_recv_data
263 * Description : Receives data from given SSL context and puts
267 * 1 : ssl = SSL context to receive data from
268 * 2 : buf = Pointer to buffer where data will be written
269 * 3 : max_length = Maximum number of bytes to read
271 * Returns : Number of bytes read, 0 for EOF, or -1
274 *********************************************************************/
275 extern int ssl_recv_data(mbedtls_ssl_context *ssl, unsigned char *buf, size_t max_length)
278 memset(buf, 0, max_length);
281 * Receiving data from SSL context into buffer
285 ret = mbedtls_ssl_read(ssl, buf, max_length);
286 } while (ret == MBEDTLS_ERR_SSL_WANT_READ
287 || ret == MBEDTLS_ERR_SSL_WANT_WRITE);
291 char err_buf[ERROR_BUF_SIZE];
293 if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY)
295 log_error(LOG_LEVEL_CONNECT,
296 "The peer notified us that the connection is going to be closed");
299 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
300 log_error(LOG_LEVEL_ERROR,
301 "Receiving data over TLS/SSL failed: %s", err_buf);
306 log_error(LOG_LEVEL_RECEIVED, "TLS: %N", ret, buf);
312 /*********************************************************************
314 * Function : ssl_flush_socket
316 * Description : Send any pending "buffered" content with given
317 * SSL connection. Alternative to function flush_socket.
320 * 1 : ssl = SSL context to send buffer to
321 * 2 : iob = The I/O buffer to flush, usually csp->iob.
323 * Returns : On success, the number of bytes send are returned (zero
324 * indicates nothing was sent). On error, -1 is returned.
326 *********************************************************************/
327 extern long ssl_flush_socket(mbedtls_ssl_context *ssl, struct iob *iob)
329 /* Computing length of buffer part to send */
330 long len = iob->eod - iob->cur;
337 /* Sending data to given SSl context */
338 if (ssl_send_data(ssl, (const unsigned char *)iob->cur, (size_t)len) < 0)
342 iob->eod = iob->cur = iob->buf;
347 /*********************************************************************
349 * Function : ssl_debug_callback
351 * Description : Debug callback function for mbedtls library.
352 * Prints info into log file.
355 * 1 : ctx = File to save log in
356 * 2 : level = Debug level
357 * 3 : file = File calling debug message
358 * 4 : line = Line calling debug message
359 * 5 : str = Debug message
363 *********************************************************************/
364 static void ssl_debug_callback(void *ctx, int level, const char *file, int line, const char *str)
368 fprintf((FILE *)ctx, "%s:%04d: %s", file, line, str);
370 log_error(LOG_LEVEL_INFO, "SSL debug message: %s:%04d: %s", file, line, str);
375 /*********************************************************************
377 * Function : create_client_ssl_connection
379 * Description : Creates TLS/SSL secured connection with client
382 * 1 : csp = Current client state (buffers, headers, etc...)
384 * Returns : 0 on success, negative value if connection wasn't created
387 *********************************************************************/
388 extern int create_client_ssl_connection(struct client_state *csp)
390 /* Paths to certificates file and key file */
391 char *key_file = NULL;
392 char *ca_file = NULL;
393 char *cert_file = NULL;
395 char err_buf[ERROR_BUF_SIZE];
398 * Initializing mbedtls structures for TLS/SSL connection
400 mbedtls_net_init(&(csp->mbedtls_client_attr.socket_fd));
401 mbedtls_ssl_init(&(csp->mbedtls_client_attr.ssl));
402 mbedtls_ssl_config_init(&(csp->mbedtls_client_attr.conf));
403 mbedtls_x509_crt_init(&(csp->mbedtls_client_attr.server_cert));
404 mbedtls_pk_init(&(csp->mbedtls_client_attr.prim_key));
405 #if defined(MBEDTLS_SSL_CACHE_C)
406 mbedtls_ssl_cache_init(&(csp->mbedtls_client_attr.cache));
410 * Preparing hash of host for creating certificates
412 ret = host_to_hash(csp);
415 log_error(LOG_LEVEL_ERROR, "Generating hash of host failed: %d", ret);
421 * Preparing paths to certificates files and key file
423 ca_file = csp->config->ca_cert_file;
424 cert_file = make_certs_path(csp->config->certificate_directory,
425 (const char *)csp->http->hash_of_host_hex, CERT_FILE_TYPE);
426 key_file = make_certs_path(csp->config->certificate_directory,
427 (const char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
429 if (cert_file == NULL || key_file == NULL)
436 * Generating certificate for requested host. Mutex to prevent
437 * certificate and key inconsistence must be locked.
439 privoxy_mutex_lock(&certificate_mutex);
441 ret = generate_webpage_certificate(csp);
444 log_error(LOG_LEVEL_ERROR,
445 "Generate_webpage_certificate failed: %d", ret);
446 privoxy_mutex_unlock(&certificate_mutex);
450 privoxy_mutex_unlock(&certificate_mutex);
463 * Loading CA file, webpage certificate and key files
465 ret = mbedtls_x509_crt_parse_file(&(csp->mbedtls_client_attr.server_cert),
469 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
470 log_error(LOG_LEVEL_ERROR,
471 "Loading webpage certificate %s failed: %s", cert_file, err_buf);
476 ret = mbedtls_x509_crt_parse_file(&(csp->mbedtls_client_attr.server_cert),
480 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
481 log_error(LOG_LEVEL_ERROR,
482 "Loading CA certificate %s failed: %s", ca_file, err_buf);
487 ret = mbedtls_pk_parse_keyfile(&(csp->mbedtls_client_attr.prim_key),
491 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
492 log_error(LOG_LEVEL_ERROR,
493 "Loading and parsing webpage certificate private key %s failed: %s",
500 * Setting SSL parameters
502 ret = mbedtls_ssl_config_defaults(&(csp->mbedtls_client_attr.conf),
503 MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_TRANSPORT_STREAM,
504 MBEDTLS_SSL_PRESET_DEFAULT);
507 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
508 log_error(LOG_LEVEL_ERROR,
509 "mbedtls_ssl_config_defaults failed: %s", err_buf);
514 mbedtls_ssl_conf_rng(&(csp->mbedtls_client_attr.conf),
515 mbedtls_ctr_drbg_random, &ctr_drbg);
516 mbedtls_ssl_conf_dbg(&(csp->mbedtls_client_attr.conf),
517 ssl_debug_callback, stdout);
519 #if defined(MBEDTLS_SSL_CACHE_C)
520 mbedtls_ssl_conf_session_cache(&(csp->mbedtls_client_attr.conf),
521 &(csp->mbedtls_client_attr.cache), mbedtls_ssl_cache_get,
522 mbedtls_ssl_cache_set);
526 * Setting certificates
528 ret = mbedtls_ssl_conf_own_cert(&(csp->mbedtls_client_attr.conf),
529 &(csp->mbedtls_client_attr.server_cert),
530 &(csp->mbedtls_client_attr.prim_key));
533 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
534 log_error(LOG_LEVEL_ERROR,
535 "mbedtls_ssl_conf_own_cert failed: %s", err_buf);
540 ret = mbedtls_ssl_setup(&(csp->mbedtls_client_attr.ssl),
541 &(csp->mbedtls_client_attr.conf));
544 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
545 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_setup failed: %s", err_buf);
550 mbedtls_ssl_set_bio(&(csp->mbedtls_client_attr.ssl),
551 &(csp->mbedtls_client_attr.socket_fd), mbedtls_net_send,
552 mbedtls_net_recv, NULL);
553 mbedtls_ssl_session_reset(&(csp->mbedtls_client_attr.ssl));
556 * Setting socket fd in mbedtls_net_context structure. This structure
557 * can't be set by mbedtls functions, because we already have created
558 * a TCP connection when this function is called.
560 csp->mbedtls_client_attr.socket_fd.fd = csp->cfd;
563 * Handshake with client
565 log_error(LOG_LEVEL_CONNECT,
566 "Performing the TLS/SSL handshake with client. Hash of host: %s",
567 csp->http->hash_of_host_hex);
568 while ((ret = mbedtls_ssl_handshake(&(csp->mbedtls_client_attr.ssl))) != 0)
570 if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
571 ret != MBEDTLS_ERR_SSL_WANT_WRITE)
573 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
574 log_error(LOG_LEVEL_ERROR,
575 "medtls_ssl_handshake with client failed: %s", err_buf);
581 log_error(LOG_LEVEL_CONNECT, "Client successfully connected over TLS/SSL");
582 csp->ssl_with_client_is_opened = 1;
586 * Freeing allocated paths to files
591 /* Freeing structures if connection wasn't created successfully */
594 free_client_ssl_structures(csp);
600 /*********************************************************************
602 * Function : close_client_ssl_connection
604 * Description : Closes TLS/SSL connection with client. This function
605 * checks if this connection is already created.
608 * 1 : csp = Current client state (buffers, headers, etc...)
612 *********************************************************************/
613 extern void close_client_ssl_connection(struct client_state *csp)
617 if (csp->ssl_with_client_is_opened == 0)
623 * Notifying the peer that the connection is being closed.
626 ret = mbedtls_ssl_close_notify(&(csp->mbedtls_client_attr.ssl));
627 } while (ret == MBEDTLS_ERR_SSL_WANT_WRITE);
629 free_client_ssl_structures(csp);
630 csp->ssl_with_client_is_opened = 0;
634 /*********************************************************************
636 * Function : free_client_ssl_structures
638 * Description : Frees structures used for SSL communication with
642 * 1 : csp = Current client state (buffers, headers, etc...)
646 *********************************************************************/
647 static void free_client_ssl_structures(struct client_state *csp)
650 * We can't use function mbedtls_net_free, because this function
651 * inter alia close TCP connection on setted fd. Instead of this
652 * function, we change fd to -1, which is the same what does
653 * rest of mbedtls_net_free function.
655 csp->mbedtls_client_attr.socket_fd.fd = -1;
657 /* Freeing mbedtls structures */
658 mbedtls_x509_crt_free(&(csp->mbedtls_client_attr.server_cert));
659 mbedtls_pk_free(&(csp->mbedtls_client_attr.prim_key));
660 mbedtls_ssl_free(&(csp->mbedtls_client_attr.ssl));
661 mbedtls_ssl_config_free(&(csp->mbedtls_client_attr.conf));
662 #if defined(MBEDTLS_SSL_CACHE_C)
663 mbedtls_ssl_cache_free(&(csp->mbedtls_client_attr.cache));
668 /*********************************************************************
670 * Function : create_server_ssl_connection
672 * Description : Creates TLS/SSL secured connection with server.
675 * 1 : csp = Current client state (buffers, headers, etc...)
677 * Returns : 0 on success, negative value if connection wasn't created
680 *********************************************************************/
681 extern int create_server_ssl_connection(struct client_state *csp)
684 char err_buf[ERROR_BUF_SIZE];
685 char *trusted_cas_file = NULL;
686 int auth_mode = MBEDTLS_SSL_VERIFY_REQUIRED;
688 csp->server_cert_verification_result = SSL_CERT_NOT_VERIFIED;
689 csp->server_certs_chain.next = NULL;
691 /* Setting path to file with trusted CAs */
692 trusted_cas_file = csp->config->trusted_cas_file;
695 * Initializing mbedtls structures for TLS/SSL connection
697 mbedtls_net_init(&(csp->mbedtls_server_attr.socket_fd));
698 mbedtls_ssl_init(&(csp->mbedtls_server_attr.ssl));
699 mbedtls_ssl_config_init(&(csp->mbedtls_server_attr.conf));
700 mbedtls_x509_crt_init(&(csp->mbedtls_server_attr.ca_cert));
703 * Setting socket fd in mbedtls_net_context structure. This structure
704 * can't be set by mbedtls functions, because we already have created
705 * TCP connection when calling this function.
707 csp->mbedtls_server_attr.socket_fd.fd = csp->server_connection.sfd;
720 * Loading file with trusted CAs
722 ret = mbedtls_x509_crt_parse_file(&(csp->mbedtls_server_attr.ca_cert),
726 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
727 log_error(LOG_LEVEL_ERROR, "Loading trusted CAs file %s failed: %s",
728 trusted_cas_file, err_buf);
734 * Set TLS/SSL options
736 ret = mbedtls_ssl_config_defaults(&(csp->mbedtls_server_attr.conf),
737 MBEDTLS_SSL_IS_CLIENT,
738 MBEDTLS_SSL_TRANSPORT_STREAM,
739 MBEDTLS_SSL_PRESET_DEFAULT);
742 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
743 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_config_defaults failed: %s",
750 * Setting how strict should certificate verification be and other
751 * parameters for certificate verification
753 if (csp->dont_verify_certificate)
755 auth_mode = MBEDTLS_SSL_VERIFY_NONE;
758 mbedtls_ssl_conf_authmode(&(csp->mbedtls_server_attr.conf), auth_mode);
759 mbedtls_ssl_conf_ca_chain(&(csp->mbedtls_server_attr.conf),
760 &(csp->mbedtls_server_attr.ca_cert), NULL);
762 /* Setting callback function for certificates verification */
763 mbedtls_ssl_conf_verify(&(csp->mbedtls_server_attr.conf),
764 ssl_verify_callback, (void *)csp);
766 mbedtls_ssl_conf_rng(&(csp->mbedtls_server_attr.conf),
767 mbedtls_ctr_drbg_random, &ctr_drbg);
768 mbedtls_ssl_conf_dbg(&(csp->mbedtls_server_attr.conf),
769 ssl_debug_callback, stdout);
771 ret = mbedtls_ssl_setup(&(csp->mbedtls_server_attr.ssl),
772 &(csp->mbedtls_server_attr.conf));
775 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
776 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_setup failed: %s", err_buf);
782 * Set the hostname to check against the received server certificate
784 ret = mbedtls_ssl_set_hostname(&(csp->mbedtls_server_attr.ssl),
788 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
789 log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_set_hostname failed: %s",
795 mbedtls_ssl_set_bio(&(csp->mbedtls_server_attr.ssl),
796 &(csp->mbedtls_server_attr.socket_fd), mbedtls_net_send,
797 mbedtls_net_recv, NULL);
800 * Handshake with server
802 log_error(LOG_LEVEL_CONNECT,
803 "Performing the TLS/SSL handshake with the server");
805 while ((ret = mbedtls_ssl_handshake(&(csp->mbedtls_server_attr.ssl))) != 0)
807 if (ret != MBEDTLS_ERR_SSL_WANT_READ
808 && ret != MBEDTLS_ERR_SSL_WANT_WRITE)
810 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
812 if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED)
814 char reason[INVALID_CERT_INFO_BUF_SIZE];
816 csp->server_cert_verification_result =
817 mbedtls_ssl_get_verify_result(&(csp->mbedtls_server_attr.ssl));
818 mbedtls_x509_crt_verify_info(reason, sizeof(reason), "",
819 csp->server_cert_verification_result);
821 /* Log the reason without the trailing new line */
822 log_error(LOG_LEVEL_ERROR,
823 "X509 certificate verification for %s failed: %N",
824 csp->http->hostport, strlen(reason)-1, reason);
829 log_error(LOG_LEVEL_ERROR,
830 "mbedtls_ssl_handshake with server failed: %s", err_buf);
837 log_error(LOG_LEVEL_CONNECT, "Server successfully connected over TLS/SSL");
840 * Server certificate chain is valid, so we can clean
841 * chain, because we will not send it to client.
843 free_certificate_chain(csp);
845 csp->ssl_with_server_is_opened = 1;
846 csp->server_cert_verification_result =
847 mbedtls_ssl_get_verify_result(&(csp->mbedtls_server_attr.ssl));
850 /* Freeing structures if connection wasn't created successfully */
853 free_server_ssl_structures(csp);
860 /*********************************************************************
862 * Function : close_server_ssl_connection
864 * Description : Closes TLS/SSL connection with server. This function
865 * checks if this connection is already opened.
868 * 1 : csp = Current client state (buffers, headers, etc...)
872 *********************************************************************/
873 static void close_server_ssl_connection(struct client_state *csp)
877 if (csp->ssl_with_server_is_opened == 0)
883 * Notifying the peer that the connection is being closed.
886 ret = mbedtls_ssl_close_notify(&(csp->mbedtls_server_attr.ssl));
887 } while (ret == MBEDTLS_ERR_SSL_WANT_WRITE);
889 free_server_ssl_structures(csp);
890 csp->ssl_with_server_is_opened = 0;
894 /*********************************************************************
896 * Function : free_server_ssl_structures
898 * Description : Frees structures used for SSL communication with server
901 * 1 : csp = Current client state (buffers, headers, etc...)
905 *********************************************************************/
906 static void free_server_ssl_structures(struct client_state *csp)
909 * We can't use function mbedtls_net_free, because this function
910 * inter alia close TCP connection on setted fd. Instead of this
911 * function, we change fd to -1, which is the same what does
912 * rest of mbedtls_net_free function.
914 csp->mbedtls_server_attr.socket_fd.fd = -1;
916 mbedtls_x509_crt_free(&(csp->mbedtls_server_attr.ca_cert));
917 mbedtls_ssl_free(&(csp->mbedtls_server_attr.ssl));
918 mbedtls_ssl_config_free(&(csp->mbedtls_server_attr.conf));
922 /*********************************************************************
924 * Function : close_client_and_server_ssl_connections
926 * Description : Checks if client or server should use secured
927 * connection over SSL and if so, closes all of them.
930 * 1 : csp = Current client state (buffers, headers, etc...)
934 *********************************************************************/
935 extern void close_client_and_server_ssl_connections(struct client_state *csp)
937 if (client_use_ssl(csp) == 1)
939 close_client_ssl_connection(csp);
941 if (server_use_ssl(csp) == 1)
943 close_server_ssl_connection(csp);
947 /*====================== Certificates ======================*/
949 /*********************************************************************
951 * Function : write_certificate
953 * Description : Writes certificate into file.
956 * 1 : crt = certificate to write into file
957 * 2 : output_file = path to save certificate file
958 * 3 : f_rng = mbedtls_ctr_drbg_random
959 * 4 : p_rng = mbedtls_ctr_drbg_context
961 * Returns : Length of written certificate on success or negative value
964 *********************************************************************/
965 static int write_certificate(mbedtls_x509write_cert *crt, const char *output_file,
966 int(*f_rng)(void *, unsigned char *, size_t), void *p_rng)
970 unsigned char cert_buf[CERTIFICATE_BUF_SIZE + 1]; /* Buffer for certificate in PEM format + terminating NULL */
972 char err_buf[ERROR_BUF_SIZE];
974 memset(cert_buf, 0, sizeof(cert_buf));
977 * Writing certificate into PEM string. If buffer is too small, function
978 * returns specific error and no buffer overflow can happen.
980 if ((ret = mbedtls_x509write_crt_pem(crt, cert_buf,
981 sizeof(cert_buf) - 1, f_rng, p_rng)) != 0)
983 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
984 log_error(LOG_LEVEL_ERROR,
985 "Writing certificate into buffer failed: %s", err_buf);
989 len = strlen((char *)cert_buf);
992 * Saving certificate into file
994 if ((f = fopen(output_file, "w")) == NULL)
996 log_error(LOG_LEVEL_ERROR, "Opening file %s to save certificate failed",
1001 if (fwrite(cert_buf, 1, len, f) != len)
1003 log_error(LOG_LEVEL_ERROR,
1004 "Writing certificate into file %s failed", output_file);
1015 /*********************************************************************
1017 * Function : write_private_key
1019 * Description : Writes private key into file and copies saved
1020 * content into given pointer to string. If function
1021 * returns 0 for success, this copy must be freed by
1025 * 1 : key = key to write into file
1026 * 2 : ret_buf = pointer to string with created key file content
1027 * 3 : key_file_path = path where to save key file
1029 * Returns : Length of written private key on success or negative value
1032 *********************************************************************/
1033 static int write_private_key(mbedtls_pk_context *key, unsigned char **ret_buf,
1034 const char *key_file_path)
1036 size_t len = 0; /* Length of created key */
1037 FILE *f = NULL; /* File to save certificate */
1039 char err_buf[ERROR_BUF_SIZE];
1041 /* Initializing buffer for key file content */
1042 *ret_buf = zalloc_or_die(PRIVATE_KEY_BUF_SIZE + 1);
1045 * Writing private key into PEM string
1047 if ((ret = mbedtls_pk_write_key_pem(key, *ret_buf, PRIVATE_KEY_BUF_SIZE)) != 0)
1049 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1050 log_error(LOG_LEVEL_ERROR,
1051 "Writing private key into PEM string failed: %s", err_buf);
1055 len = strlen((char *)*ret_buf);
1058 * Saving key into file
1060 if ((f = fopen(key_file_path, "wb")) == NULL)
1062 log_error(LOG_LEVEL_ERROR,
1063 "Opening file %s to save private key failed: %E",
1069 if (fwrite(*ret_buf, 1, len, f) != len)
1072 log_error(LOG_LEVEL_ERROR,
1073 "Writing private key into file %s failed",
1092 /*********************************************************************
1094 * Function : generate_key
1096 * Description : Tests if private key for host saved in csp already
1097 * exists. If this file doesn't exists, a new key is
1098 * generated and saved in a file. The generated key is also
1099 * copied into given parameter key_buf, which must be then
1100 * freed by caller. If file with key exists, key_buf
1101 * contain NULL and no private key is generated.
1104 * 1 : csp = Current client state (buffers, headers, etc...)
1105 * 2 : key_buf = buffer to save new generated key
1107 * Returns : -1 => Error while generating private key
1108 * 0 => Key already exists
1109 * >0 => Length of generated private key
1111 *********************************************************************/
1112 static int generate_key(struct client_state *csp, unsigned char **key_buf)
1114 mbedtls_pk_context key;
1115 key_options key_opt;
1117 char err_buf[ERROR_BUF_SIZE];
1119 key_opt.key_file_path = NULL;
1122 * Initializing structures for key generating
1124 mbedtls_pk_init(&key);
1127 * Preparing path for key file and other properties for generating key
1129 key_opt.type = MBEDTLS_PK_RSA;
1130 key_opt.rsa_keysize = RSA_KEYSIZE;
1132 key_opt.key_file_path = make_certs_path(csp->config->certificate_directory,
1133 (char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
1134 if (key_opt.key_file_path == NULL)
1141 * Test if key already exists. If so, we don't have to create it again.
1143 if (file_exists(key_opt.key_file_path) == 1)
1152 ret = seed_rng(csp);
1160 * Setting attributes of private key and generating it
1162 if ((ret = mbedtls_pk_setup(&key,
1163 mbedtls_pk_info_from_type(key_opt.type))) != 0)
1165 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1166 log_error(LOG_LEVEL_ERROR, "mbedtls_pk_setup failed: %s", err_buf);
1171 ret = mbedtls_rsa_gen_key(mbedtls_pk_rsa(key), mbedtls_ctr_drbg_random,
1172 &ctr_drbg, (unsigned)key_opt.rsa_keysize, RSA_KEY_PUBLIC_EXPONENT);
1175 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1176 log_error(LOG_LEVEL_ERROR, "Key generating failed: %s", err_buf);
1182 * Exporting private key into file
1184 if ((ret = write_private_key(&key, key_buf, key_opt.key_file_path)) < 0)
1186 log_error(LOG_LEVEL_ERROR,
1187 "Writing private key into file %s failed", key_opt.key_file_path);
1194 * Freeing used variables
1196 freez(key_opt.key_file_path);
1198 mbedtls_pk_free(&key);
1204 /*********************************************************************
1206 * Function : ssl_certificate_is_invalid
1208 * Description : Checks whether or not a certificate is valid.
1209 * Currently only checks that the certificate can be
1210 * parsed and that the "valid to" date is in the future.
1213 * 1 : cert_file = The certificate to check
1215 * Returns : 0 => The certificate is valid.
1216 * 1 => The certificate is invalid
1218 *********************************************************************/
1219 static int ssl_certificate_is_invalid(const char *cert_file)
1221 mbedtls_x509_crt cert;
1224 mbedtls_x509_crt_init(&cert);
1226 ret = mbedtls_x509_crt_parse_file(&cert, cert_file);
1229 char err_buf[ERROR_BUF_SIZE];
1231 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1232 log_error(LOG_LEVEL_ERROR,
1233 "Loading certificate %s to check validity failed: %s",
1234 cert_file, err_buf);
1235 mbedtls_x509_crt_free(&cert);
1239 if (mbedtls_x509_time_is_past(&cert.valid_to))
1241 mbedtls_x509_crt_free(&cert);
1246 mbedtls_x509_crt_free(&cert);
1253 /*********************************************************************
1255 * Function : generate_certificate_valid_date
1257 * Description : Turns a time_t into the format expected by mbedTLS.
1260 * 1 : time_spec = The timestamp to convert
1261 * 2 : buffer = The buffer to write the date to
1262 * 3 : buffer_size = The size of the buffer
1264 * Returns : 0 => The conversion worked
1265 * 1 => The conversion failed
1267 *********************************************************************/
1268 static int generate_certificate_valid_date(time_t time_spec, char *buffer,
1271 struct tm valid_date;
1274 #ifndef HAVE_GMTIME_R
1275 #error HTTP inspection currently requires gmtime_r() which seems to be missing
1277 if (NULL == gmtime_r(&time_spec, &valid_date))
1282 ret = strftime(buffer, buffer_size, "%Y%m%d%H%M%S", &valid_date);
1293 /*********************************************************************
1295 * Function : get_certificate_valid_from_date
1297 * Description : Generates a "valid from" date in the format
1298 * expected by mbedTLS.
1301 * 1 : buffer = The buffer to write the date to
1302 * 2 : buffer_size = The size of the buffer
1304 * Returns : 0 => The generation worked
1305 * 1 => The generation failed
1307 *********************************************************************/
1308 static int get_certificate_valid_from_date(char *buffer, size_t buffer_size)
1312 time_spec = time(NULL);
1313 /* 1 month in the past */
1314 time_spec -= 30 * 24 * 60 * 60;
1316 return generate_certificate_valid_date(time_spec, buffer, buffer_size);
1321 /*********************************************************************
1323 * Function : get_certificate_valid_to_date
1325 * Description : Generates a "valid to" date in the format
1326 * expected by mbedTLS.
1329 * 1 : buffer = The buffer to write the date to
1330 * 2 : buffer_size = The size of the buffer
1332 * Returns : 0 => The generation worked
1333 * 1 => The generation failed
1335 *********************************************************************/
1336 static int get_certificate_valid_to_date(char *buffer, size_t buffer_size)
1340 time_spec = time(NULL);
1341 /* Three months in the future */
1342 time_spec += 90 * 24 * 60 * 60;
1344 return generate_certificate_valid_date(time_spec, buffer, buffer_size);
1349 /*********************************************************************
1351 * Function : set_subject_alternative_name
1353 * Description : Sets the Subject Alternative Name extension to a cert
1356 * 1 : cert = The certificate to modify
1357 * 2 : hostname = The hostname to add
1359 * Returns : <0 => Error while creating certificate.
1362 *********************************************************************/
1363 static int set_subject_alternative_name(mbedtls_x509write_cert *cert, const char *hostname)
1365 char err_buf[ERROR_BUF_SIZE];
1367 char *subject_alternative_name;
1368 size_t subject_alternative_name_len;
1369 #define MBEDTLS_SUBJECT_ALTERNATIVE_NAME_MAX_LEN 255
1370 unsigned char san_buf[MBEDTLS_SUBJECT_ALTERNATIVE_NAME_MAX_LEN + 1];
1374 subject_alternative_name_len = strlen(hostname) + 1;
1375 subject_alternative_name = zalloc_or_die(subject_alternative_name_len);
1377 strlcpy(subject_alternative_name, hostname, subject_alternative_name_len);
1379 memset(san_buf, 0, sizeof(san_buf));
1381 c = san_buf + sizeof(san_buf);
1384 ret = mbedtls_asn1_write_raw_buffer(&c, san_buf,
1385 (const unsigned char *)subject_alternative_name,
1386 strlen(subject_alternative_name));
1389 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1390 log_error(LOG_LEVEL_ERROR,
1391 "mbedtls_asn1_write_raw_buffer() failed: %s", err_buf);
1396 ret = mbedtls_asn1_write_len(&c, san_buf, strlen(subject_alternative_name));
1399 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1400 log_error(LOG_LEVEL_ERROR,
1401 "mbedtls_asn1_write_len() failed: %s", err_buf);
1406 ret = mbedtls_asn1_write_tag(&c, san_buf, MBEDTLS_ASN1_CONTEXT_SPECIFIC | 2);
1409 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1410 log_error(LOG_LEVEL_ERROR,
1411 "mbedtls_asn1_write_tag() failed: %s", err_buf);
1416 ret = mbedtls_asn1_write_len(&c, san_buf, (size_t)len);
1419 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1420 log_error(LOG_LEVEL_ERROR,
1421 "mbedtls_asn1_write_len() failed: %s", err_buf);
1426 ret = mbedtls_asn1_write_tag(&c, san_buf,
1427 MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE);
1430 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1431 log_error(LOG_LEVEL_ERROR,
1432 "mbedtls_asn1_write_tag() failed: %s", err_buf);
1437 ret = mbedtls_x509write_crt_set_extension(cert,
1438 MBEDTLS_OID_SUBJECT_ALT_NAME,
1439 MBEDTLS_OID_SIZE(MBEDTLS_OID_SUBJECT_ALT_NAME),
1440 0, san_buf + sizeof(san_buf) - len, (size_t)len);
1443 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1444 log_error(LOG_LEVEL_ERROR,
1445 "mbedtls_x509write_crt_set_extension() failed: %s", err_buf);
1449 freez(subject_alternative_name);
1455 /*********************************************************************
1457 * Function : generate_webpage_certificate
1459 * Description : Creates certificate file in presetted directory.
1460 * If certificate already exists, no other certificate
1461 * will be created. Subject of certificate is named
1462 * by csp->http->host from parameter. This function also
1463 * triggers generating of private key for new certificate.
1466 * 1 : csp = Current client state (buffers, headers, etc...)
1468 * Returns : -1 => Error while creating certificate.
1469 * 0 => Certificate already exists.
1470 * >0 => Length of created certificate.
1472 *********************************************************************/
1473 static int generate_webpage_certificate(struct client_state *csp)
1475 mbedtls_x509_crt issuer_cert;
1476 mbedtls_pk_context loaded_issuer_key, loaded_subject_key;
1477 mbedtls_pk_context *issuer_key = &loaded_issuer_key;
1478 mbedtls_pk_context *subject_key = &loaded_subject_key;
1479 mbedtls_x509write_cert cert;
1482 unsigned char *key_buf = NULL; /* Buffer for created key */
1485 char err_buf[ERROR_BUF_SIZE];
1486 cert_options cert_opt;
1487 char cert_valid_from[15];
1488 char cert_valid_to[15];
1490 /* Paths to keys and certificates needed to create certificate */
1491 cert_opt.issuer_key = NULL;
1492 cert_opt.subject_key = NULL;
1493 cert_opt.issuer_crt = NULL;
1495 cert_opt.output_file = make_certs_path(csp->config->certificate_directory,
1496 (const char *)csp->http->hash_of_host_hex, CERT_FILE_TYPE);
1497 if (cert_opt.output_file == NULL)
1502 cert_opt.subject_key = make_certs_path(csp->config->certificate_directory,
1503 (const char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
1504 if (cert_opt.subject_key == NULL)
1506 freez(cert_opt.output_file);
1510 if (file_exists(cert_opt.output_file) == 1)
1512 /* The file exists, but is it valid? */
1513 if (ssl_certificate_is_invalid(cert_opt.output_file))
1515 log_error(LOG_LEVEL_CONNECT,
1516 "Certificate %s is no longer valid. Removing it.",
1517 cert_opt.output_file);
1518 if (unlink(cert_opt.output_file))
1520 log_error(LOG_LEVEL_ERROR, "Failed to unlink %s: %E",
1521 cert_opt.output_file);
1523 freez(cert_opt.output_file);
1524 freez(cert_opt.subject_key);
1528 if (unlink(cert_opt.subject_key))
1530 log_error(LOG_LEVEL_ERROR, "Failed to unlink %s: %E",
1531 cert_opt.subject_key);
1533 freez(cert_opt.output_file);
1534 freez(cert_opt.subject_key);
1541 freez(cert_opt.output_file);
1542 freez(cert_opt.subject_key);
1549 * Create key for requested host
1551 int subject_key_len = generate_key(csp, &key_buf);
1552 if (subject_key_len < 0)
1554 freez(cert_opt.output_file);
1555 freez(cert_opt.subject_key);
1556 log_error(LOG_LEVEL_ERROR, "Key generating failed");
1561 * Initializing structures for certificate generating
1563 mbedtls_x509write_crt_init(&cert);
1564 mbedtls_x509write_crt_set_md_alg(&cert, CERT_SIGNATURE_ALGORITHM);
1565 mbedtls_pk_init(&loaded_issuer_key);
1566 mbedtls_pk_init(&loaded_subject_key);
1567 mbedtls_mpi_init(&serial);
1568 mbedtls_x509_crt_init(&issuer_cert);
1571 * Presetting parameters for certificate. We must compute total length
1574 size_t cert_params_len = strlen(CERT_PARAM_COMMON_NAME) +
1575 strlen(CERT_PARAM_ORGANIZATION) + strlen(CERT_PARAM_COUNTRY) +
1576 strlen(CERT_PARAM_ORG_UNIT) +
1577 3 * strlen(csp->http->host) + 1;
1578 char cert_params[cert_params_len];
1579 memset(cert_params, 0, cert_params_len);
1582 * Converting unsigned long serial number to char * serial number.
1583 * We must compute length of serial number in string + terminating null.
1585 unsigned long certificate_serial = get_certificate_serial(csp);
1586 unsigned long certificate_serial_time = (unsigned long)time(NULL);
1587 int serial_num_size = snprintf(NULL, 0, "%lu%lu",
1588 certificate_serial_time, certificate_serial) + 1;
1589 if (serial_num_size <= 0)
1591 serial_num_size = 1;
1594 char serial_num_text[serial_num_size]; /* Buffer for serial number */
1595 ret = snprintf(serial_num_text, (size_t)serial_num_size, "%lu%lu",
1596 certificate_serial_time, certificate_serial);
1597 if (ret < 0 || ret >= serial_num_size)
1599 log_error(LOG_LEVEL_ERROR,
1600 "Converting certificate serial number into string failed");
1606 * Preparing parameters for certificate
1608 strlcpy(cert_params, CERT_PARAM_COMMON_NAME, cert_params_len);
1609 strlcat(cert_params, csp->http->host, cert_params_len);
1610 strlcat(cert_params, CERT_PARAM_ORGANIZATION, cert_params_len);
1611 strlcat(cert_params, csp->http->host, cert_params_len);
1612 strlcat(cert_params, CERT_PARAM_ORG_UNIT, cert_params_len);
1613 strlcat(cert_params, csp->http->host, cert_params_len);
1614 strlcat(cert_params, CERT_PARAM_COUNTRY, cert_params_len);
1616 cert_opt.issuer_crt = csp->config->ca_cert_file;
1617 cert_opt.issuer_key = csp->config->ca_key_file;
1619 if (get_certificate_valid_from_date(cert_valid_from, sizeof(cert_valid_from))
1620 || get_certificate_valid_to_date(cert_valid_to, sizeof(cert_valid_to)))
1622 log_error(LOG_LEVEL_ERROR, "Generating one of the validity dates failed");
1627 cert_opt.subject_pwd = CERT_SUBJECT_PASSWORD;
1628 cert_opt.issuer_pwd = csp->config->ca_password;
1629 cert_opt.subject_name = cert_params;
1630 cert_opt.not_before = cert_valid_from;
1631 cert_opt.not_after = cert_valid_to;
1632 cert_opt.serial = serial_num_text;
1634 cert_opt.max_pathlen = -1;
1637 * Test if the private key was already created.
1638 * XXX: Can this still happen?
1640 if (subject_key_len == 0)
1642 log_error(LOG_LEVEL_ERROR, "Subject key was already created");
1650 ret = seed_rng(csp);
1658 * Parse serial to MPI
1660 ret = mbedtls_mpi_read_string(&serial, 10, cert_opt.serial);
1663 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1664 log_error(LOG_LEVEL_ERROR,
1665 "mbedtls_mpi_read_string failed: %s", err_buf);
1671 * Loading certificates
1673 ret = mbedtls_x509_crt_parse_file(&issuer_cert, cert_opt.issuer_crt);
1676 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1677 log_error(LOG_LEVEL_ERROR, "Loading issuer certificate %s failed: %s",
1678 cert_opt.issuer_crt, err_buf);
1683 ret = mbedtls_x509_dn_gets(cert_opt.issuer_name,
1684 sizeof(cert_opt.issuer_name), &issuer_cert.subject);
1687 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1688 log_error(LOG_LEVEL_ERROR, "mbedtls_x509_dn_gets failed: %s", err_buf);
1694 * Loading keys from file or from buffer
1696 if (key_buf != NULL && subject_key_len > 0)
1698 /* Key was created in this function and is stored in buffer */
1699 ret = mbedtls_pk_parse_key(&loaded_subject_key, key_buf,
1700 (size_t)(subject_key_len + 1), (unsigned const char *)
1701 cert_opt.subject_pwd, strlen(cert_opt.subject_pwd));
1705 /* Key wasn't created in this function, because it already existed */
1706 ret = mbedtls_pk_parse_keyfile(&loaded_subject_key,
1707 cert_opt.subject_key, cert_opt.subject_pwd);
1712 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1713 log_error(LOG_LEVEL_ERROR, "Parsing subject key %s failed: %s",
1714 cert_opt.subject_key, err_buf);
1719 ret = mbedtls_pk_parse_keyfile(&loaded_issuer_key, cert_opt.issuer_key,
1720 cert_opt.issuer_pwd);
1723 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1724 log_error(LOG_LEVEL_ERROR,
1725 "Parsing issuer key %s failed: %s", cert_opt.issuer_key, err_buf);
1731 * Check if key and issuer certificate match
1733 if (!mbedtls_pk_can_do(&issuer_cert.pk, MBEDTLS_PK_RSA) ||
1734 mbedtls_mpi_cmp_mpi(&mbedtls_pk_rsa(issuer_cert.pk)->N,
1735 &mbedtls_pk_rsa(*issuer_key)->N) != 0 ||
1736 mbedtls_mpi_cmp_mpi(&mbedtls_pk_rsa(issuer_cert.pk)->E,
1737 &mbedtls_pk_rsa(*issuer_key)->E) != 0)
1739 log_error(LOG_LEVEL_ERROR,
1740 "Issuer key doesn't match issuer certificate");
1745 mbedtls_x509write_crt_set_subject_key(&cert, subject_key);
1746 mbedtls_x509write_crt_set_issuer_key(&cert, issuer_key);
1749 * Setting parameters of signed certificate
1751 ret = mbedtls_x509write_crt_set_subject_name(&cert, cert_opt.subject_name);
1754 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1755 log_error(LOG_LEVEL_ERROR,
1756 "Setting subject name in signed certificate failed: %s", err_buf);
1761 ret = mbedtls_x509write_crt_set_issuer_name(&cert, cert_opt.issuer_name);
1764 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1765 log_error(LOG_LEVEL_ERROR,
1766 "Setting issuer name in signed certificate failed: %s", err_buf);
1771 ret = mbedtls_x509write_crt_set_serial(&cert, &serial);
1774 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1775 log_error(LOG_LEVEL_ERROR,
1776 "Setting serial number in signed certificate failed: %s", err_buf);
1781 ret = mbedtls_x509write_crt_set_validity(&cert, cert_opt.not_before,
1782 cert_opt.not_after);
1785 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1786 log_error(LOG_LEVEL_ERROR,
1787 "Setting validity in signed certificate failed: %s", err_buf);
1793 * Setting the basicConstraints extension for certificate
1795 ret = mbedtls_x509write_crt_set_basic_constraints(&cert, cert_opt.is_ca,
1796 cert_opt.max_pathlen);
1799 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1800 log_error(LOG_LEVEL_ERROR, "Setting the basicConstraints extension "
1801 "in signed certificate failed: %s", err_buf);
1806 #if defined(MBEDTLS_SHA1_C)
1807 /* Setting the subjectKeyIdentifier extension for certificate */
1808 ret = mbedtls_x509write_crt_set_subject_key_identifier(&cert);
1811 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1812 log_error(LOG_LEVEL_ERROR, "mbedtls_x509write_crt_set_subject_key_"
1813 "identifier failed: %s", err_buf);
1818 /* Setting the authorityKeyIdentifier extension for certificate */
1819 ret = mbedtls_x509write_crt_set_authority_key_identifier(&cert);
1822 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1823 log_error(LOG_LEVEL_ERROR, "mbedtls_x509write_crt_set_authority_key_"
1824 "identifier failed: %s", err_buf);
1828 #endif /* MBEDTLS_SHA1_C */
1830 if (set_subject_alternative_name(&cert, csp->http->host))
1832 /* Errors are already logged by set_subject_alternative_name() */
1838 * Writing certificate into file
1840 ret = write_certificate(&cert, cert_opt.output_file,
1841 mbedtls_ctr_drbg_random, &ctr_drbg);
1844 log_error(LOG_LEVEL_ERROR, "Writing certificate into file failed");
1850 * Freeing used structures
1852 mbedtls_x509write_crt_free(&cert);
1853 mbedtls_pk_free(&loaded_subject_key);
1854 mbedtls_pk_free(&loaded_issuer_key);
1855 mbedtls_mpi_free(&serial);
1856 mbedtls_x509_crt_free(&issuer_cert);
1858 freez(cert_opt.subject_key);
1859 freez(cert_opt.output_file);
1866 /*********************************************************************
1868 * Function : make_certs_path
1870 * Description : Creates path to file from three pieces. This function
1871 * takes parameters and puts them in one new mallocated
1872 * char * in correct order. Returned variable must be freed
1873 * by caller. This function is mainly used for creating
1874 * paths of certificates and keys files.
1877 * 1 : conf_dir = Name/path of directory where is the file.
1878 * '.' can be used for current directory.
1879 * 2 : file_name = Name of file in conf_dir without suffix.
1880 * 3 : suffix = Suffix of given file_name.
1882 * Returns : path => Path was built up successfully
1883 * NULL => Path can't be built up
1885 *********************************************************************/
1886 static char *make_certs_path(const char *conf_dir, const char *file_name,
1889 /* Test if all given parameters are valid */
1890 if (conf_dir == NULL || *conf_dir == '\0' || file_name == NULL ||
1891 *file_name == '\0' || suffix == NULL || *suffix == '\0')
1893 log_error(LOG_LEVEL_ERROR,
1894 "make_certs_path failed: bad input parameters");
1899 size_t path_size = strlen(conf_dir)
1900 + strlen(file_name) + strlen(suffix) + 2;
1902 /* Setting delimiter and editing path length */
1903 #if defined(_WIN32) || defined(__OS2__)
1904 char delim[] = "\\";
1906 #else /* ifndef _WIN32 || __OS2__ */
1908 #endif /* ifndef _WIN32 || __OS2__ */
1911 * Building up path from many parts
1914 if (*conf_dir != '/' && basedir && *basedir)
1917 * Replacing conf_dir with basedir. This new variable contains
1918 * absolute path to cwd.
1920 path_size += strlen(basedir) + 2;
1921 path = zalloc_or_die(path_size);
1923 strlcpy(path, basedir, path_size);
1924 strlcat(path, delim, path_size);
1925 strlcat(path, conf_dir, path_size);
1926 strlcat(path, delim, path_size);
1927 strlcat(path, file_name, path_size);
1928 strlcat(path, suffix, path_size);
1931 #endif /* defined unix */
1933 path = zalloc_or_die(path_size);
1935 strlcpy(path, conf_dir, path_size);
1936 strlcat(path, delim, path_size);
1937 strlcat(path, file_name, path_size);
1938 strlcat(path, suffix, path_size);
1945 /*********************************************************************
1947 * Function : get_certificate_serial
1949 * Description : Computes serial number for new certificate from host
1950 * name hash. This hash must be already saved in csp
1954 * 1 : csp = Current client state (buffers, headers, etc...)
1956 * Returns : Serial number for new certificate
1958 *********************************************************************/
1959 static unsigned long get_certificate_serial(struct client_state *csp)
1961 unsigned long exp = 1;
1962 unsigned long serial = 0;
1964 int i = CERT_SERIAL_NUM_LENGTH;
1968 serial += exp * (unsigned)csp->http->hash_of_host[i];
1975 /*********************************************************************
1977 * Function : ssl_send_certificate_error
1979 * Description : Sends info about invalid server certificate to client.
1980 * Sent message is including all trusted chain certificates,
1981 * that can be downloaded in web browser.
1984 * 1 : csp = Current client state (buffers, headers, etc...)
1988 *********************************************************************/
1989 extern void ssl_send_certificate_error(struct client_state *csp)
1991 size_t message_len = 0;
1993 struct certs_chain *cert = NULL;
1995 /* Header of message with certificate informations */
1996 const char message_begin[] =
1997 "HTTP/1.1 200 OK\r\n"
1998 "Content-Type: text/html\r\n"
1999 "Connection: close\r\n\r\n"
2000 "<html><body><h1>Server certificate verification failed</h1><p>Reason: ";
2001 const char message_end[] = "</body></html>\r\n\r\n";
2002 char reason[INVALID_CERT_INFO_BUF_SIZE];
2003 memset(reason, 0, sizeof(reason));
2005 /* Get verification message from verification return code */
2006 mbedtls_x509_crt_verify_info(reason, sizeof(reason), " ",
2007 csp->server_cert_verification_result);
2010 * Computing total length of message with all certificates inside
2012 message_len = strlen(message_begin) + strlen(message_end)
2013 + strlen(reason) + strlen("</p>") + 1;
2015 cert = &(csp->server_certs_chain);
2016 while (cert->next != NULL)
2018 size_t base64_len = 4 * ((strlen(cert->file_buf) + 2) / 3) + 1;
2020 message_len += strlen(cert->text_buf) + strlen("<pre></pre>\n")
2021 + base64_len + strlen("<a href=\"data:application"
2022 "/x-x509-ca-cert;base64,\">Download certificate</a>");
2027 * Joining all blocks in one long message
2029 char message[message_len];
2030 memset(message, 0, message_len);
2032 strlcpy(message, message_begin, message_len);
2033 strlcat(message, reason , message_len);
2034 strlcat(message, "</p>" , message_len);
2036 cert = &(csp->server_certs_chain);
2037 while (cert->next != NULL)
2040 size_t base64_len = 4 * ((strlen(cert->file_buf) + 2) / 3) + 1; /* +1 for terminating null*/
2041 char base64_buf[base64_len];
2042 memset(base64_buf, 0, base64_len);
2044 /* Encoding certificate into base64 code */
2045 ret = mbedtls_base64_encode((unsigned char*)base64_buf,
2046 base64_len, &olen, (const unsigned char*)cert->file_buf,
2047 strlen(cert->file_buf));
2050 log_error(LOG_LEVEL_ERROR,
2051 "Encoding to base64 failed, buffer is to small");
2054 strlcat(message, "<pre>", message_len);
2055 strlcat(message, cert->text_buf, message_len);
2056 strlcat(message, "</pre>\n", message_len);
2060 strlcat(message, "<a href=\"data:application/x-x509-ca-cert;base64,",
2062 strlcat(message, base64_buf, message_len);
2063 strlcat(message, "\">Download certificate</a>", message_len);
2068 strlcat(message, message_end, message_len);
2071 * Sending final message to client
2073 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
2074 (const unsigned char *)message, strlen(message));
2076 free_certificate_chain(csp);
2080 /*********************************************************************
2082 * Function : ssl_verify_callback
2084 * Description : This is a callback function for certificate verification.
2085 * It's called for all certificates in server certificate
2086 * trusted chain and it's preparing information about this
2087 * certificates. Prepared informations can be used to inform
2088 * user about invalid certificates.
2091 * 1 : csp_void = Current client state (buffers, headers, etc...)
2092 * 2 : crt = certificate from trusted chain
2093 * 3 : depth = depth in trusted chain
2094 * 4 : flags = certificate flags
2096 * Returns : 0 on success and negative value on error
2098 *********************************************************************/
2099 static int ssl_verify_callback(void *csp_void, mbedtls_x509_crt *crt,
2100 int depth, uint32_t *flags)
2102 struct client_state *csp = (struct client_state *)csp_void;
2103 struct certs_chain *last = &(csp->server_certs_chain);
2108 * Searching for last item in certificates linked list
2110 while (last->next != NULL)
2116 * Preparing next item in linked list for next certificate
2118 last->next = malloc_or_die(sizeof(struct certs_chain));
2119 last->next->next = NULL;
2120 memset(last->next->text_buf, 0, sizeof(last->next->text_buf));
2121 memset(last->next->file_buf, 0, sizeof(last->next->file_buf));
2124 * Saving certificate file into buffer
2126 if ((ret = mbedtls_pem_write_buffer(PEM_BEGIN_CRT, PEM_END_CRT,
2127 crt->raw.p, crt->raw.len, (unsigned char *)last->file_buf,
2128 sizeof(last->file_buf)-1, &olen)) != 0)
2134 * Saving certificate information into buffer
2136 mbedtls_x509_crt_info(last->text_buf, sizeof(last->text_buf) - 1,
2137 CERT_INFO_PREFIX, crt);
2143 /*********************************************************************
2145 * Function : free_certificate_chain
2147 * Description : Frees certificates linked list. This linked list is
2148 * used to save informations about certificates in
2152 * 1 : csp = Current client state (buffers, headers, etc...)
2156 *********************************************************************/
2157 static void free_certificate_chain(struct client_state *csp)
2159 struct certs_chain *cert = csp->server_certs_chain.next;
2161 /* Cleaning buffers */
2162 memset(csp->server_certs_chain.text_buf, 0,
2163 sizeof(csp->server_certs_chain.text_buf));
2164 memset(csp->server_certs_chain.file_buf, 0,
2165 sizeof(csp->server_certs_chain.file_buf));
2166 csp->server_certs_chain.next = NULL;
2168 /* Freeing memory in whole linked list */
2173 struct certs_chain *cert_for_free = cert;
2175 freez(cert_for_free);
2176 } while (cert != NULL);
2181 /*********************************************************************
2183 * Function : file_exists
2185 * Description : Tests if file exists and is readable.
2188 * 1 : path = Path to tested file.
2190 * Returns : 1 => File exists and is readable.
2191 * 0 => File doesn't exist or is not readable.
2193 *********************************************************************/
2194 static int file_exists(const char *path)
2197 if ((f = fopen(path, "r")) != NULL)
2207 /*********************************************************************
2209 * Function : host_to_hash
2211 * Description : Creates MD5 hash from host name. Host name is loaded
2212 * from structure csp and saved again into it.
2215 * 1 : csp = Current client state (buffers, headers, etc...)
2217 * Returns : 1 => Error while creating hash
2218 * 0 => Hash created successfully
2220 *********************************************************************/
2221 static int host_to_hash(struct client_state *csp)
2225 #if !defined(MBEDTLS_MD5_C)
2226 #error mbedTLS needs to be compiled with md5 support
2228 memset(csp->http->hash_of_host, 0, sizeof(csp->http->hash_of_host));
2229 mbedtls_md5((unsigned char *)csp->http->host, strlen(csp->http->host),
2230 csp->http->hash_of_host);
2232 /* Converting hash into string with hex */
2236 if ((ret = sprintf((char *)csp->http->hash_of_host_hex + 2 * i, "%02x",
2237 csp->http->hash_of_host[i])) < 0)
2239 log_error(LOG_LEVEL_ERROR, "Sprintf return value: %d", ret);
2245 #endif /* MBEDTLS_MD5_C */
2249 /*********************************************************************
2251 * Function : tunnel_established_successfully
2253 * Description : Check if parent proxy server response contains
2254 * informations about successfully created connection with
2255 * destination server. (HTTP/... 2xx ...)
2258 * 1 : server_response = Buffer with parent proxy server response
2259 * 2 : response_len = Length of server_response
2261 * Returns : 1 => Connection created successfully
2262 * 0 => Connection wasn't created successfully
2264 *********************************************************************/
2265 extern int tunnel_established_successfully(const char *server_response,
2266 unsigned int response_len)
2268 unsigned int pos = 0;
2270 if (server_response == NULL)
2275 /* Tests if "HTTP/" string is at the begin of received response */
2276 if (strncmp(server_response, "HTTP/", 5) != 0)
2281 for (pos = 0; pos < response_len; pos++)
2283 if (server_response[pos] == ' ')
2290 * response_len -3 because of buffer end, response structure and 200 code.
2291 * There must be at least 3 chars after space.
2292 * End of buffer: ... 2xx'\0'
2295 if (pos >= (response_len - 3))
2300 /* Test HTTP status code */
2301 if (server_response[pos + 1] != '2')
2310 /*********************************************************************
2312 * Function : seed_rng
2314 * Description : Seeding the RNG for all SSL uses
2317 * 1 : csp = Current client state (buffers, headers, etc...)
2319 * Returns : -1 => RNG wasn't seed successfully
2320 * 0 => RNG is seeded successfully
2322 *********************************************************************/
2323 static int seed_rng(struct client_state *csp)
2326 char err_buf[ERROR_BUF_SIZE];
2328 if (rng_seeded == 0)
2330 privoxy_mutex_lock(&rng_mutex);
2331 if (rng_seeded == 0)
2333 mbedtls_ctr_drbg_init(&ctr_drbg);
2334 mbedtls_entropy_init(&entropy);
2335 ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func,
2339 mbedtls_strerror(ret, err_buf, sizeof(err_buf));
2340 log_error(LOG_LEVEL_ERROR,
2341 "mbedtls_ctr_drbg_seed failed: %s", err_buf);
2342 privoxy_mutex_unlock(&rng_mutex);
2347 privoxy_mutex_unlock(&rng_mutex);