Generate the "valid from" and "valid to" date of certificates based on the current...
[privoxy.git] / ssl.c
1 /*********************************************************************
2  *
3  * File        :  $Source: /cvsroot/ijbswa/current/ssl.c,v $
4  *
5  * Purpose     :  File with TLS/SSL extension. Contains methods for
6  *                creating, using and closing TLS/SSL connections.
7  *
8  * Copyright   :  Written by and Copyright (c) 2017 Vaclav Svec. FIT CVUT.
9  *                Copyright (C) 2018-2020 by Fabian Keil <fk@fabiankeil.de>
10  *
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.
16  *
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.
22  *
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.
28  *
29  *********************************************************************/
30
31 #include <string.h>
32 #include <unistd.h>
33
34 #if !defined(MBEDTLS_CONFIG_FILE)
35 #  include "mbedtls/config.h"
36 #else
37 #  include MBEDTLS_CONFIG_FILE
38 #endif
39
40 #include "mbedtls/md5.h"
41 #include "mbedtls/pem.h"
42 #include "mbedtls/base64.h"
43 #include "mbedtls/error.h"
44
45 #include "config.h"
46 #include "project.h"
47 #include "miscutil.h"
48 #include "errlog.h"
49 #include "jcc.h"
50 #include "ssl.h"
51
52
53 /*
54  * Macros for searching begin and end of certificates.
55  * Necessary to convert structure mbedtls_x509_crt to crt file.
56  */
57 #define PEM_BEGIN_CRT     "-----BEGIN CERTIFICATE-----\n"
58 #define PEM_END_CRT       "-----END CERTIFICATE-----\n"
59
60 /*
61  * Macros for ssl.c
62  */
63 #define ERROR_BUF_SIZE                   1024              /* Size of buffer for error messages */
64 #define CERTIFICATE_BUF_SIZE             16384             /* Size of buffer to save certificate. Value 4096 is mbedtls library buffer size for certificate in DER form */
65 #define PRIVATE_KEY_BUF_SIZE             16000             /* Size of buffer to save private key. Value 16000 is taken from mbed TLS library examples. */
66 #define RSA_KEY_PUBLIC_EXPONENT          65537             /* Public exponent for RSA private key generating */
67 #define RSA_KEYSIZE                      2048              /* Size of generated RSA keys */
68 #define CERT_SIGNATURE_ALGORITHM         MBEDTLS_MD_SHA256 /* The MD algorithm to use for the signature */
69 #define CERT_SERIAL_NUM_LENGTH           4                 /* Bytes of hash to be used for creating serial number of certificate. Min=2 and max=16 */
70 #define INVALID_CERT_INFO_BUF_SIZE       2048              /* Size of buffer for message with information about reason of certificate invalidity. Data after the end of buffer will not be saved */
71 #define CERT_PARAM_COMMON_NAME           "CN="
72 #define CERT_PARAM_ORGANIZATION          ",O="
73 #define CERT_PARAM_ORG_UNIT              ",OU="
74 #define CERT_PARAM_COUNTRY               ",C=CZ"
75 #define KEY_FILE_TYPE                    ".pem"
76 #define CERT_FILE_TYPE                   ".crt"
77 #define CERT_SUBJECT_PASSWORD            ""
78 #define CERT_INFO_PREFIX                 ""
79
80 /*
81  * Properties of cert for generating
82  */
83 typedef struct {
84    char       *issuer_crt;                         /* filename of the issuer certificate       */
85    char       *subject_key;                        /* filename of the subject key file         */
86    char       *issuer_key;                         /* filename of the issuer key file          */
87    const char *subject_pwd;                        /* password for the subject key file        */
88    const char *issuer_pwd;                         /* password for the issuer key file         */
89    char       *output_file;                        /* where to store the constructed key file  */
90    const char *subject_name;                       /* subject name for certificate             */
91    char       issuer_name[ISSUER_NAME_BUF_SIZE];   /* issuer name for certificate              */
92    const char *not_before;                         /* validity period not before               */
93    const char *not_after;                          /* validity period not after                */
94    const char *serial;                             /* serial number string                     */
95    int        is_ca;                               /* is a CA certificate                      */
96    int        max_pathlen;                         /* maximum CA path length                   */
97 } cert_options;
98
99 /*
100  * Properties of key for generating
101  */
102 typedef struct {
103    mbedtls_pk_type_t type;   /* type of key to generate  */
104    int  rsa_keysize;         /* length of key in bits    */
105    char *key_file_path;      /* filename of the key file */
106 } key_options;
107
108 static int generate_webpage_certificate(struct client_state *csp);
109 static char *make_certs_path(const char *conf_dir, const char *file_name, const char *suffix);
110 static int file_exists(const char *path);
111 static int host_to_hash(struct client_state *csp);
112 static int ssl_verify_callback(void *data, mbedtls_x509_crt *crt, int depth, uint32_t *flags);
113 static void free_certificate_chain(struct client_state *csp);
114 static unsigned long  get_certificate_serial(struct client_state *csp);
115 static void free_client_ssl_structures(struct client_state *csp);
116 static void free_server_ssl_structures(struct client_state *csp);
117 static int seed_rng(struct client_state *csp);
118
119 /*********************************************************************
120  *
121  * Function    :  client_use_ssl
122  *
123  * Description :  Tests if client in current client state structure
124  *                should use SSL connection or standard connection.
125  *
126  * Parameters  :
127  *          1  :  csp = Current client state (buffers, headers, etc...)
128  *
129  * Returns     :  If client should use TLS/SSL connection, 1 is returned.
130  *                Otherwise 0 is returned.
131  *
132  *********************************************************************/
133 extern int client_use_ssl(const struct client_state *csp)
134 {
135    return csp->http->client_ssl;
136 }
137
138
139 /*********************************************************************
140  *
141  * Function    :  server_use_ssl
142  *
143  * Description :  Tests if server in current client state structure
144  *                should use SSL connection or standard connection.
145  *
146  * Parameters  :
147  *          1  :  csp = Current client state (buffers, headers, etc...)
148  *
149  * Returns     :  If server should use TLS/SSL connection, 1 is returned.
150  *                Otherwise 0 is returned.
151  *
152  *********************************************************************/
153 extern int server_use_ssl(const struct client_state *csp)
154 {
155    return csp->http->server_ssl;
156 }
157
158
159 /*********************************************************************
160  *
161  * Function    :  is_ssl_pending
162  *
163  * Description :  Tests if there are some waiting data on ssl connection
164  *
165  * Parameters  :
166  *          1  :  ssl = SSL context to test
167  *
168  * Returns     :   0 => No data are pending
169  *                >0 => Pending data length
170  *
171  *********************************************************************/
172 extern size_t is_ssl_pending(mbedtls_ssl_context *ssl)
173 {
174    if (ssl == NULL)
175    {
176       return 0;
177    }
178
179    return mbedtls_ssl_get_bytes_avail(ssl);
180 }
181
182
183 /*********************************************************************
184  *
185  * Function    :  ssl_send_data
186  *
187  * Description :  Sends the content of buf (for n bytes) to given SSL
188  *                connection context.
189  *
190  * Parameters  :
191  *          1  :  ssl = SSL context to send data to
192  *          2  :  buf = Pointer to data to be sent
193  *          3  :  len = Length of data to be sent to the SSL context
194  *
195  * Returns     :  Length of sent data or negative value on error.
196  *
197  *********************************************************************/
198 extern int ssl_send_data(mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len)
199 {
200    int ret = 0;
201    size_t max_fragment_size = 0;  /* Maximal length of data in one SSL fragment*/
202    int send_len             = 0;  /* length of one data part to send */
203    int pos                  = 0;  /* Position of unsent part in buffer */
204
205    if (len == 0)
206    {
207       return 0;
208    }
209
210    /* Getting maximal length of data sent in one fragment */
211    max_fragment_size = mbedtls_ssl_get_max_frag_len(ssl);
212
213    /*
214     * Whole buffer must be sent in many fragments, because each fragment
215     * has its maximal length.
216     */
217    while (pos < len)
218    {
219       /* Compute length of data, that can be send in next fragment */
220       if ((pos + (int)max_fragment_size) > len)
221       {
222          send_len = (int)len - pos;
223       }
224       else
225       {
226          send_len = (int)max_fragment_size;
227       }
228
229       log_error(LOG_LEVEL_WRITING, "TLS: %N", send_len, buf+pos);
230
231       /*
232        * Sending one part of the buffer
233        */
234       while ((ret = mbedtls_ssl_write(ssl,
235          (const unsigned char *)(buf + pos),
236          (size_t)send_len)) < 0)
237       {
238          if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
239              ret != MBEDTLS_ERR_SSL_WANT_WRITE)
240          {
241             char err_buf[ERROR_BUF_SIZE];
242
243             mbedtls_strerror(ret, err_buf, sizeof(err_buf));
244             log_error(LOG_LEVEL_ERROR,
245                "Sending data over TLS/SSL failed: %s", err_buf);
246             return -1;
247          }
248       }
249       /* Adding count of sent bytes to position in buffer */
250       pos = pos + send_len;
251    }
252
253    return (int)len;
254 }
255
256
257 /*********************************************************************
258  *
259  * Function    :  ssl_recv_data
260  *
261  * Description :  Receives data from given SSL context and puts
262  *                it into buffer.
263  *
264  * Parameters  :
265  *          1  :  ssl = SSL context to receive data from
266  *          2  :  buf = Pointer to buffer where data will be written
267  *          3  :  max_length = Maximum number of bytes to read
268  *
269  * Returns     :  Number of bytes read, 0 for EOF, or -1
270  *                on error.
271  *
272  *********************************************************************/
273 extern int ssl_recv_data(mbedtls_ssl_context *ssl, unsigned char *buf, size_t max_length)
274 {
275    int ret = 0;
276    memset(buf, 0, max_length);
277
278    /*
279     * Receiving data from SSL context into buffer
280     */
281    do
282    {
283       ret = mbedtls_ssl_read(ssl, buf, max_length);
284    } while (ret == MBEDTLS_ERR_SSL_WANT_READ
285       || ret == MBEDTLS_ERR_SSL_WANT_WRITE);
286
287    if (ret < 0)
288    {
289       char err_buf[ERROR_BUF_SIZE];
290
291       if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY)
292       {
293          log_error(LOG_LEVEL_CONNECT,
294             "The peer notified us that the connection is going to be closed");
295          return 0;
296       }
297       mbedtls_strerror(ret, err_buf, sizeof(err_buf));
298       log_error(LOG_LEVEL_ERROR,
299          "Receiving data over TLS/SSL failed: %s", err_buf);
300
301       return -1;
302    }
303
304    log_error(LOG_LEVEL_RECEIVED, "TLS: %N", ret, buf);
305
306    return ret;
307 }
308
309
310 /*********************************************************************
311  *
312  * Function    :  ssl_flush_socket
313  *
314  * Description :  Send any pending "buffered" content with given
315  *                SSL connection. Alternative to function flush_socket.
316  *
317  * Parameters  :
318  *          1  :  ssl = SSL context to send buffer to
319  *          2  :  iob = The I/O buffer to flush, usually csp->iob.
320  *
321  * Returns     :  On success, the number of bytes send are returned (zero
322  *                indicates nothing was sent).  On error, -1 is returned.
323  *
324  *********************************************************************/
325 extern long ssl_flush_socket(mbedtls_ssl_context *ssl, struct iob *iob)
326 {
327    /* Computing length of buffer part to send */
328    long len = iob->eod - iob->cur;
329
330    if (len <= 0)
331    {
332       return(0);
333    }
334
335    /* Sending data to given SSl context */
336    if (ssl_send_data(ssl, (const unsigned char *)iob->cur, (size_t)len) < 0)
337    {
338       return -1;
339    }
340    iob->eod = iob->cur = iob->buf;
341    return(len);
342 }
343
344
345 /*********************************************************************
346  *
347  * Function    :  ssl_debug_callback
348  *
349  * Description :  Debug callback function for mbedtls library.
350  *                Prints info into log file.
351  *
352  * Parameters  :
353  *          1  :  ctx   = File to save log in
354  *          2  :  level = Debug level
355  *          3  :  file  = File calling debug message
356  *          4  :  line  = Line calling debug message
357  *          5  :  str   = Debug message
358  *
359  * Returns     :  N/A
360  *
361  *********************************************************************/
362 static void ssl_debug_callback(void *ctx, int level, const char *file, int line, const char *str)
363 {
364    /*
365    ((void)level);
366    fprintf((FILE *)ctx, "%s:%04d: %s", file, line, str);
367    fflush((FILE *)ctx);
368    log_error(LOG_LEVEL_INFO, "SSL debug message: %s:%04d: %s", file, line, str);
369    */
370 }
371
372
373 /*********************************************************************
374  *
375  * Function    :  create_client_ssl_connection
376  *
377  * Description :  Creates TLS/SSL secured connection with client
378  *
379  * Parameters  :
380  *          1  :  csp = Current client state (buffers, headers, etc...)
381  *
382  * Returns     :  0 on success, negative value if connection wasn't created
383  *                successfully.
384  *
385  *********************************************************************/
386 extern int create_client_ssl_connection(struct client_state *csp)
387 {
388    /* Paths to certificates file and key file */
389    char *key_file  = NULL;
390    char *ca_file   = NULL;
391    char *cert_file = NULL;
392    int ret = 0;
393    char err_buf[ERROR_BUF_SIZE];
394
395    /*
396     * Initializing mbedtls structures for TLS/SSL connection
397     */
398    mbedtls_net_init(&(csp->mbedtls_client_attr.socket_fd));
399    mbedtls_ssl_init(&(csp->mbedtls_client_attr.ssl));
400    mbedtls_ssl_config_init(&(csp->mbedtls_client_attr.conf));
401    mbedtls_x509_crt_init(&(csp->mbedtls_client_attr.server_cert));
402    mbedtls_pk_init(&(csp->mbedtls_client_attr.prim_key));
403 #if defined(MBEDTLS_SSL_CACHE_C)
404    mbedtls_ssl_cache_init(&(csp->mbedtls_client_attr.cache));
405 #endif
406
407    /*
408     * Preparing hash of host for creating certificates
409     */
410    ret = host_to_hash(csp);
411    if (ret != 0)
412    {
413       log_error(LOG_LEVEL_ERROR, "Generating hash of host failed: %d", ret);
414       ret = -1;
415       goto exit;
416    }
417
418    /*
419     * Preparing paths to certificates files and key file
420     */
421    ca_file   = csp->config->ca_cert_file;
422    cert_file = make_certs_path(csp->config->certificate_directory,
423       (const char *)csp->http->hash_of_host_hex, CERT_FILE_TYPE);
424    key_file  = make_certs_path(csp->config->certificate_directory,
425       (const char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
426
427    if (cert_file == NULL || key_file == NULL)
428    {
429       ret = -1;
430       goto exit;
431    }
432
433    /*
434     * Generating certificate for requested host. Mutex to prevent
435     * certificate and key inconsistence must be locked.
436     */
437    privoxy_mutex_lock(&certificate_mutex);
438
439    ret = generate_webpage_certificate(csp);
440    if (ret < 0)
441    {
442       log_error(LOG_LEVEL_ERROR,
443          "Generate_webpage_certificate failed: %d", ret);
444       privoxy_mutex_unlock(&certificate_mutex);
445       ret = -1;
446       goto exit;
447    }
448    privoxy_mutex_unlock(&certificate_mutex);
449
450    /*
451     * Seed the RNG
452     */
453    ret = seed_rng(csp);
454    if (ret != 0)
455    {
456       ret = -1;
457       goto exit;
458    }
459
460    /*
461     * Loading CA file, webpage certificate and key files
462     */
463    ret = mbedtls_x509_crt_parse_file(&(csp->mbedtls_client_attr.server_cert),
464       cert_file);
465    if (ret != 0)
466    {
467       mbedtls_strerror(ret, err_buf, sizeof(err_buf));
468       log_error(LOG_LEVEL_ERROR,
469          "Loading webpage certificate %s failed: %s", cert_file, err_buf);
470       ret = -1;
471       goto exit;
472    }
473
474    ret = mbedtls_x509_crt_parse_file(&(csp->mbedtls_client_attr.server_cert),
475       ca_file);
476    if (ret != 0)
477    {
478       mbedtls_strerror(ret, err_buf, sizeof(err_buf));
479       log_error(LOG_LEVEL_ERROR,
480          "Loading CA certificate %s failed: %s", ca_file, err_buf);
481       ret = -1;
482       goto exit;
483    }
484
485    ret = mbedtls_pk_parse_keyfile(&(csp->mbedtls_client_attr.prim_key),
486       key_file, NULL);
487    if (ret != 0)
488    {
489       mbedtls_strerror(ret, err_buf, sizeof(err_buf));
490       log_error(LOG_LEVEL_ERROR,
491          "Loading and parsing webpage certificate private key %s failed: %s",
492          key_file, err_buf);
493       ret = -1;
494       goto exit;
495    }
496
497    /*
498     * Setting SSL parameters
499     */
500    ret = mbedtls_ssl_config_defaults(&(csp->mbedtls_client_attr.conf),
501       MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_TRANSPORT_STREAM,
502       MBEDTLS_SSL_PRESET_DEFAULT);
503    if (ret != 0)
504    {
505       mbedtls_strerror(ret, err_buf, sizeof(err_buf));
506       log_error(LOG_LEVEL_ERROR,
507          "mbedtls_ssl_config_defaults failed: %s", err_buf);
508       ret = -1;
509       goto exit;
510    }
511
512    mbedtls_ssl_conf_rng(&(csp->mbedtls_client_attr.conf),
513       mbedtls_ctr_drbg_random, &ctr_drbg);
514    mbedtls_ssl_conf_dbg(&(csp->mbedtls_client_attr.conf),
515       ssl_debug_callback, stdout);
516
517 #if defined(MBEDTLS_SSL_CACHE_C)
518    mbedtls_ssl_conf_session_cache(&(csp->mbedtls_client_attr.conf),
519       &(csp->mbedtls_client_attr.cache), mbedtls_ssl_cache_get,
520       mbedtls_ssl_cache_set);
521 #endif
522
523    /*
524     * Setting certificates
525     */
526    ret = mbedtls_ssl_conf_own_cert(&(csp->mbedtls_client_attr.conf),
527       &(csp->mbedtls_client_attr.server_cert),
528       &(csp->mbedtls_client_attr.prim_key));
529    if (ret != 0)
530    {
531       mbedtls_strerror(ret, err_buf, sizeof(err_buf));
532       log_error(LOG_LEVEL_ERROR,
533          "mbedtls_ssl_conf_own_cert failed: %s", err_buf);
534       ret = -1;
535       goto exit;
536    }
537
538    ret = mbedtls_ssl_setup(&(csp->mbedtls_client_attr.ssl),
539       &(csp->mbedtls_client_attr.conf));
540    if (ret != 0)
541    {
542       mbedtls_strerror(ret, err_buf, sizeof(err_buf));
543       log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_setup failed: %s", err_buf);
544       ret = -1;
545       goto exit;
546    }
547
548    mbedtls_ssl_set_bio(&(csp->mbedtls_client_attr.ssl),
549       &(csp->mbedtls_client_attr.socket_fd), mbedtls_net_send,
550       mbedtls_net_recv, NULL);
551    mbedtls_ssl_session_reset(&(csp->mbedtls_client_attr.ssl));
552
553    /*
554     * Setting socket fd in mbedtls_net_context structure. This structure
555     * can't be set by mbedtls functions, because we already have created
556     * a TCP connection when this function is called.
557     */
558    csp->mbedtls_client_attr.socket_fd.fd = csp->cfd;
559
560    /*
561     *  Handshake with client
562     */
563    log_error(LOG_LEVEL_CONNECT,
564       "Performing the TLS/SSL handshake with client. Hash of host: %s",
565       csp->http->hash_of_host_hex);
566    while ((ret = mbedtls_ssl_handshake(&(csp->mbedtls_client_attr.ssl))) != 0)
567    {
568       if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
569           ret != MBEDTLS_ERR_SSL_WANT_WRITE)
570       {
571          mbedtls_strerror(ret, err_buf, sizeof(err_buf));
572          log_error(LOG_LEVEL_ERROR,
573             "medtls_ssl_handshake with client failed: %s", err_buf);
574          ret = -1;
575          goto exit;
576       }
577    }
578
579    log_error(LOG_LEVEL_CONNECT, "Client successfully connected over TLS/SSL");
580    csp->ssl_with_client_is_opened = 1;
581
582 exit:
583    /*
584     * Freeing allocated paths to files
585     */
586    freez(cert_file);
587    freez(key_file);
588
589    /* Freeing structures if connection wasn't created successfully */
590    if (ret < 0)
591    {
592       free_client_ssl_structures(csp);
593    }
594    return ret;
595 }
596
597
598 /*********************************************************************
599  *
600  * Function    :  close_client_ssl_connection
601  *
602  * Description :  Closes TLS/SSL connection with client. This function
603  *                checks if this connection is already created.
604  *
605  * Parameters  :
606  *          1  :  csp = Current client state (buffers, headers, etc...)
607  *
608  * Returns     :  N/A
609  *
610  *********************************************************************/
611 extern void close_client_ssl_connection(struct client_state *csp)
612 {
613    int ret = 0;
614
615    if (csp->ssl_with_client_is_opened == 0)
616    {
617       return;
618    }
619
620    /*
621     * Notifying the peer that the connection is being closed.
622     */
623    do {
624       ret = mbedtls_ssl_close_notify(&(csp->mbedtls_client_attr.ssl));
625    } while (ret == MBEDTLS_ERR_SSL_WANT_WRITE);
626
627    free_client_ssl_structures(csp);
628    csp->ssl_with_client_is_opened = 0;
629 }
630
631
632 /*********************************************************************
633  *
634  * Function    :  free_client_ssl_structures
635  *
636  * Description :  Frees structures used for SSL communication with
637  *                client.
638  *
639  * Parameters  :
640  *          1  :  csp = Current client state (buffers, headers, etc...)
641  *
642  * Returns     :  N/A
643  *
644  *********************************************************************/
645 static void free_client_ssl_structures(struct client_state *csp)
646 {
647    /*
648    * We can't use function mbedtls_net_free, because this function
649    * inter alia close TCP connection on setted fd. Instead of this
650    * function, we change fd to -1, which is the same what does
651    * rest of mbedtls_net_free function.
652    */
653    csp->mbedtls_client_attr.socket_fd.fd = -1;
654
655    /* Freeing mbedtls structures */
656    mbedtls_x509_crt_free(&(csp->mbedtls_client_attr.server_cert));
657    mbedtls_pk_free(&(csp->mbedtls_client_attr.prim_key));
658    mbedtls_ssl_free(&(csp->mbedtls_client_attr.ssl));
659    mbedtls_ssl_config_free(&(csp->mbedtls_client_attr.conf));
660 #if defined(MBEDTLS_SSL_CACHE_C)
661    mbedtls_ssl_cache_free(&(csp->mbedtls_client_attr.cache));
662 #endif
663 }
664
665
666 /*********************************************************************
667  *
668  * Function    :  create_server_ssl_connection
669  *
670  * Description :  Creates TLS/SSL secured connection with server.
671  *
672  * Parameters  :
673  *          1  :  csp = Current client state (buffers, headers, etc...)
674  *
675  * Returns     :  0 on success, negative value if connection wasn't created
676  *                successfully.
677  *
678  *********************************************************************/
679 extern int create_server_ssl_connection(struct client_state *csp)
680 {
681    int ret = 0;
682    char err_buf[ERROR_BUF_SIZE];
683    char *trusted_cas_file = NULL;
684    int auth_mode = MBEDTLS_SSL_VERIFY_REQUIRED;
685
686    csp->server_cert_verification_result = SSL_CERT_NOT_VERIFIED;
687    csp->server_certs_chain.next = NULL;
688
689    /* Setting path to file with trusted CAs */
690    trusted_cas_file = csp->config->trusted_cas_file;
691
692    /*
693     * Initializing mbedtls structures for TLS/SSL connection
694     */
695    mbedtls_net_init(&(csp->mbedtls_server_attr.socket_fd));
696    mbedtls_ssl_init(&(csp->mbedtls_server_attr.ssl));
697    mbedtls_ssl_config_init(&(csp->mbedtls_server_attr.conf));
698    mbedtls_x509_crt_init(&(csp->mbedtls_server_attr.ca_cert));
699
700    /*
701    * Setting socket fd in mbedtls_net_context structure. This structure
702    * can't be set by mbedtls functions, because we already have created
703    * TCP connection when calling this function.
704    */
705    csp->mbedtls_server_attr.socket_fd.fd = csp->server_connection.sfd;
706
707    /*
708     * Seed the RNG
709     */
710    ret = seed_rng(csp);
711    if (ret != 0)
712    {
713       ret = -1;
714       goto exit;
715    }
716
717    /*
718     * Loading file with trusted CAs
719     */
720    ret = mbedtls_x509_crt_parse_file(&(csp->mbedtls_server_attr.ca_cert),
721       trusted_cas_file);
722    if (ret < 0)
723    {
724       mbedtls_strerror(ret, err_buf, sizeof(err_buf));
725       log_error(LOG_LEVEL_ERROR, "Loading trusted CAs file %s failed: %s",
726          trusted_cas_file, err_buf);
727       ret = -1;
728       goto exit;
729    }
730
731    /*
732     * Set TLS/SSL options
733     */
734    ret = mbedtls_ssl_config_defaults(&(csp->mbedtls_server_attr.conf),
735       MBEDTLS_SSL_IS_CLIENT,
736       MBEDTLS_SSL_TRANSPORT_STREAM,
737       MBEDTLS_SSL_PRESET_DEFAULT);
738    if (ret != 0)
739    {
740       mbedtls_strerror(ret, err_buf, sizeof(err_buf));
741       log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_config_defaults failed: %s",
742          err_buf);
743       ret = -1;
744       goto exit;
745    }
746
747    /*
748     * Setting how strict should certificate verification be and other
749     * parameters for certificate verification
750     */
751    if (csp->dont_verify_certificate)
752    {
753       auth_mode = MBEDTLS_SSL_VERIFY_NONE;
754    }
755
756    mbedtls_ssl_conf_authmode(&(csp->mbedtls_server_attr.conf), auth_mode);
757    mbedtls_ssl_conf_ca_chain(&(csp->mbedtls_server_attr.conf),
758       &(csp->mbedtls_server_attr.ca_cert), NULL);
759
760    /* Setting callback function for certificates verification */
761    mbedtls_ssl_conf_verify(&(csp->mbedtls_server_attr.conf),
762       ssl_verify_callback, (void *)csp);
763
764    mbedtls_ssl_conf_rng(&(csp->mbedtls_server_attr.conf),
765       mbedtls_ctr_drbg_random, &ctr_drbg);
766    mbedtls_ssl_conf_dbg(&(csp->mbedtls_server_attr.conf),
767       ssl_debug_callback, stdout);
768
769    ret = mbedtls_ssl_setup(&(csp->mbedtls_server_attr.ssl),
770       &(csp->mbedtls_server_attr.conf));
771    if (ret != 0)
772    {
773       mbedtls_strerror(ret, err_buf, sizeof(err_buf));
774       log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_setup failed: %s", err_buf);
775       ret = -1;
776       goto exit;
777    }
778
779    /*
780     * Set the hostname to check against the received server certificate
781     */
782    ret = mbedtls_ssl_set_hostname(&(csp->mbedtls_server_attr.ssl),
783       csp->http->host);
784    if (ret != 0)
785    {
786       mbedtls_strerror(ret, err_buf, sizeof(err_buf));
787       log_error(LOG_LEVEL_ERROR, "mbedtls_ssl_set_hostname failed: %s",
788          err_buf);
789       ret = -1;
790       goto exit;
791    }
792
793    mbedtls_ssl_set_bio(&(csp->mbedtls_server_attr.ssl),
794       &(csp->mbedtls_server_attr.socket_fd), mbedtls_net_send,
795       mbedtls_net_recv, NULL);
796
797    /*
798     * Handshake with server
799     */
800    log_error(LOG_LEVEL_CONNECT,
801       "Performing the TLS/SSL handshake with the server");
802
803    while ((ret = mbedtls_ssl_handshake(&(csp->mbedtls_server_attr.ssl))) != 0)
804    {
805       if (ret != MBEDTLS_ERR_SSL_WANT_READ
806        && ret != MBEDTLS_ERR_SSL_WANT_WRITE)
807       {
808          mbedtls_strerror(ret, err_buf, sizeof(err_buf));
809
810          if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED)
811          {
812             char reason[INVALID_CERT_INFO_BUF_SIZE];
813
814             csp->server_cert_verification_result =
815                mbedtls_ssl_get_verify_result(&(csp->mbedtls_server_attr.ssl));
816             mbedtls_x509_crt_verify_info(reason, sizeof(reason), "",
817                csp->server_cert_verification_result);
818
819             /* Log the reason without the trailing new line */
820             log_error(LOG_LEVEL_ERROR,
821                "X509 certificate verification for %s failed: %N",
822                csp->http->hostport, strlen(reason)-1, reason);
823             ret = -1;
824          }
825          else
826          {
827             log_error(LOG_LEVEL_ERROR,
828                "mbedtls_ssl_handshake with server failed: %s", err_buf);
829             ret = -1;
830          }
831          goto exit;
832       }
833    }
834
835    log_error(LOG_LEVEL_CONNECT, "Server successfully connected over TLS/SSL");
836
837    /*
838     * Server certificate chain is valid, so we can clean
839     * chain, because we will not send it to client.
840     */
841    free_certificate_chain(csp);
842
843    csp->ssl_with_server_is_opened = 1;
844    csp->server_cert_verification_result =
845       mbedtls_ssl_get_verify_result(&(csp->mbedtls_server_attr.ssl));
846
847 exit:
848    /* Freeing structures if connection wasn't created successfully */
849    if (ret < 0)
850    {
851       free_server_ssl_structures(csp);
852    }
853
854    return ret;
855 }
856
857
858 /*********************************************************************
859  *
860  * Function    :  close_server_ssl_connection
861  *
862  * Description :  Closes TLS/SSL connection with server. This function
863  *                checks if this connection is already opened.
864  *
865  * Parameters  :
866  *          1  :  csp = Current client state (buffers, headers, etc...)
867  *
868  * Returns     :  N/A
869  *
870  *********************************************************************/
871 static void close_server_ssl_connection(struct client_state *csp)
872 {
873    int ret = 0;
874
875    if (csp->ssl_with_server_is_opened == 0)
876    {
877       return;
878    }
879
880    /*
881    * Notifying the peer that the connection is being closed.
882    */
883    do {
884       ret = mbedtls_ssl_close_notify(&(csp->mbedtls_server_attr.ssl));
885    } while (ret == MBEDTLS_ERR_SSL_WANT_WRITE);
886
887    free_server_ssl_structures(csp);
888    csp->ssl_with_server_is_opened = 0;
889 }
890
891
892 /*********************************************************************
893  *
894  * Function    :  free_server_ssl_structures
895  *
896  * Description :  Frees structures used for SSL communication with server
897  *
898  * Parameters  :
899  *          1  :  csp = Current client state (buffers, headers, etc...)
900  *
901  * Returns     :  N/A
902  *
903  *********************************************************************/
904 static void free_server_ssl_structures(struct client_state *csp)
905 {
906    /*
907    * We can't use function mbedtls_net_free, because this function
908    * inter alia close TCP connection on setted fd. Instead of this
909    * function, we change fd to -1, which is the same what does
910    * rest of mbedtls_net_free function.
911    */
912    csp->mbedtls_server_attr.socket_fd.fd = -1;
913
914    mbedtls_x509_crt_free(&(csp->mbedtls_server_attr.ca_cert));
915    mbedtls_ssl_free(&(csp->mbedtls_server_attr.ssl));
916    mbedtls_ssl_config_free(&(csp->mbedtls_server_attr.conf));
917 }
918
919
920 /*********************************************************************
921  *
922  * Function    :  close_client_and_server_ssl_connections
923  *
924  * Description :  Checks if client or server should use secured
925  *                connection over SSL and if so, closes all of them.
926  *
927  * Parameters  :
928  *          1  :  csp = Current client state (buffers, headers, etc...)
929  *
930  * Returns     :  N/A
931  *
932  *********************************************************************/
933 extern void close_client_and_server_ssl_connections(struct client_state *csp)
934 {
935    if (client_use_ssl(csp) == 1)
936    {
937       close_client_ssl_connection(csp);
938    }
939    if (server_use_ssl(csp) == 1)
940    {
941       close_server_ssl_connection(csp);
942    }
943 }
944
945 /*====================== Certificates ======================*/
946
947 /*********************************************************************
948  *
949  * Function    :  write_certificate
950  *
951  * Description :  Writes certificate into file.
952  *
953  * Parameters  :
954  *          1  :  crt = certificate to write into file
955  *          2  :  output_file = path to save certificate file
956  *          3  :  f_rng = mbedtls_ctr_drbg_random
957  *          4  :  p_rng = mbedtls_ctr_drbg_context
958  *
959  * Returns     :  Length of written certificate on success or negative value
960  *                on error
961  *
962  *********************************************************************/
963 static int write_certificate(mbedtls_x509write_cert *crt, const char *output_file,
964    int(*f_rng)(void *, unsigned char *, size_t), void *p_rng)
965 {
966    FILE *f = NULL;
967    size_t len = 0;
968    unsigned char cert_buf[CERTIFICATE_BUF_SIZE + 1]; /* Buffer for certificate in PEM format + terminating NULL */
969    int ret = 0;
970    char err_buf[ERROR_BUF_SIZE];
971
972    memset(cert_buf, 0, sizeof(cert_buf));
973
974    /*
975     * Writing certificate into PEM string. If buffer is too small, function
976     * returns specific error and no buffer overflow can happen.
977     */
978    if ((ret = mbedtls_x509write_crt_pem(crt, cert_buf,
979       sizeof(cert_buf) - 1, f_rng, p_rng)) != 0)
980    {
981       mbedtls_strerror(ret, err_buf, sizeof(err_buf));
982       log_error(LOG_LEVEL_ERROR,
983          "Writing certificate into buffer failed: %s", err_buf);
984       return -1;
985    }
986
987    len = strlen((char *)cert_buf);
988
989    /*
990     * Saving certificate into file
991     */
992    if ((f = fopen(output_file, "w")) == NULL)
993    {
994       log_error(LOG_LEVEL_ERROR, "Opening file %s to save certificate failed",
995          output_file);
996       return -1;
997    }
998
999    if (fwrite(cert_buf, 1, len, f) != len)
1000    {
1001       log_error(LOG_LEVEL_ERROR,
1002          "Writing certificate into file %s failed", output_file);
1003       fclose(f);
1004       return -1;
1005    }
1006
1007    fclose(f);
1008
1009    return (int)len;
1010 }
1011
1012
1013 /*********************************************************************
1014  *
1015  * Function    :  write_private_key
1016  *
1017  * Description :  Writes private key into file and copies saved
1018  *                content into given pointer to string. If function
1019  *                returns 0 for success, this copy must be freed by
1020  *                caller.
1021  *
1022  * Parameters  :
1023  *          1  :  key = key to write into file
1024  *          2  :  ret_buf = pointer to string with created key file content
1025  *          3  :  key_file_path = path where to save key file
1026  *
1027  * Returns     :  Length of written private key on success or negative value
1028  *                on error
1029  *
1030  *********************************************************************/
1031 static int write_private_key(mbedtls_pk_context *key, unsigned char **ret_buf,
1032    const char *key_file_path)
1033 {
1034    size_t len = 0;                /* Length of created key    */
1035    FILE *f = NULL;                /* File to save certificate */
1036    int ret = 0;
1037    char err_buf[ERROR_BUF_SIZE];
1038
1039    /* Initializing buffer for key file content */
1040    *ret_buf = zalloc_or_die(PRIVATE_KEY_BUF_SIZE + 1);
1041
1042    /*
1043     * Writing private key into PEM string
1044     */
1045    if ((ret = mbedtls_pk_write_key_pem(key, *ret_buf, PRIVATE_KEY_BUF_SIZE)) != 0)
1046    {
1047       mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1048       log_error(LOG_LEVEL_ERROR,
1049          "Writing private key into PEM string failed: %s", err_buf);
1050       ret = -1;
1051       goto exit;
1052    }
1053    len = strlen((char *)*ret_buf);
1054
1055    /*
1056     * Saving key into file
1057     */
1058    if ((f = fopen(key_file_path, "wb")) == NULL)
1059    {
1060       log_error(LOG_LEVEL_ERROR,
1061          "Opening file %s to save private key failed: %E",
1062          key_file_path);
1063       ret = -1;
1064       goto exit;
1065    }
1066
1067    if (fwrite(*ret_buf, 1, len, f) != len)
1068    {
1069       fclose(f);
1070       log_error(LOG_LEVEL_ERROR,
1071          "Writing private key into file %s failed",
1072          key_file_path);
1073       ret = -1;
1074       goto exit;
1075    }
1076
1077    fclose(f);
1078
1079 exit:
1080    if (ret < 0)
1081    {
1082       freez(*ret_buf);
1083       *ret_buf = NULL;
1084       return ret;
1085    }
1086    return (int)len;
1087 }
1088
1089
1090 /*********************************************************************
1091  *
1092  * Function    :  generate_key
1093  *
1094  * Description : Tests if private key for host saved in csp already
1095  *               exists.  If this file doesn't exists, a new key is
1096  *               generated and saved in a file. The generated key is also
1097  *               copied into given parameter key_buf, which must be then
1098  *               freed by caller. If file with key exists, key_buf
1099  *               contain NULL and no private key is generated.
1100  *
1101  * Parameters  :
1102  *          1  :  csp = Current client state (buffers, headers, etc...)
1103  *          2  :  key_buf = buffer to save new generated key
1104  *
1105  * Returns     :  -1 => Error while generating private key
1106  *                 0 => Key already exists
1107  *                >0 => Length of generated private key
1108  *
1109  *********************************************************************/
1110 static int generate_key(struct client_state *csp, unsigned char **key_buf)
1111 {
1112    mbedtls_pk_context key;
1113    key_options key_opt;
1114    int ret = 0;
1115    char err_buf[ERROR_BUF_SIZE];
1116
1117    key_opt.key_file_path = NULL;
1118
1119    /*
1120     * Initializing structures for key generating
1121     */
1122    mbedtls_pk_init(&key);
1123
1124    /*
1125     * Preparing path for key file and other properties for generating key
1126     */
1127    key_opt.type        = MBEDTLS_PK_RSA;
1128    key_opt.rsa_keysize = RSA_KEYSIZE;
1129
1130    key_opt.key_file_path = make_certs_path(csp->config->certificate_directory,
1131       (char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
1132    if (key_opt.key_file_path == NULL)
1133    {
1134       ret = -1;
1135       goto exit;
1136    }
1137
1138    /*
1139     * Test if key already exists. If so, we don't have to create it again.
1140     */
1141    if (file_exists(key_opt.key_file_path) == 1)
1142    {
1143       ret = 0;
1144       goto exit;
1145    }
1146
1147    /*
1148     * Seed the RNG
1149     */
1150    ret = seed_rng(csp);
1151    if (ret != 0)
1152    {
1153       ret = -1;
1154       goto exit;
1155    }
1156
1157    /*
1158     * Setting attributes of private key and generating it
1159     */
1160    if ((ret = mbedtls_pk_setup(&key,
1161       mbedtls_pk_info_from_type(key_opt.type))) != 0)
1162    {
1163       mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1164       log_error(LOG_LEVEL_ERROR, "mbedtls_pk_setup failed: %s", err_buf);
1165       ret = -1;
1166       goto exit;
1167    }
1168
1169    ret = mbedtls_rsa_gen_key(mbedtls_pk_rsa(key), mbedtls_ctr_drbg_random,
1170       &ctr_drbg, (unsigned)key_opt.rsa_keysize, RSA_KEY_PUBLIC_EXPONENT);
1171    if (ret != 0)
1172    {
1173       mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1174       log_error(LOG_LEVEL_ERROR, "Key generating failed: %s", err_buf);
1175       ret = -1;
1176       goto exit;
1177    }
1178
1179    /*
1180     * Exporting private key into file
1181     */
1182    if ((ret = write_private_key(&key, key_buf, key_opt.key_file_path)) < 0)
1183    {
1184       log_error(LOG_LEVEL_ERROR,
1185          "Writing private key into file %s failed", key_opt.key_file_path);
1186       ret = -1;
1187       goto exit;
1188    }
1189
1190 exit:
1191    /*
1192     * Freeing used variables
1193     */
1194    freez(key_opt.key_file_path);
1195
1196    mbedtls_pk_free(&key);
1197
1198    return ret;
1199 }
1200
1201
1202 /*********************************************************************
1203  *
1204  * Function    :  ssl_certificate_is_invalid
1205  *
1206  * Description :  Checks whether or not a certificate is valid.
1207  *                Currently only checks that the certificate can be
1208  *                parsed and that the "valid to" date is in the future.
1209  *
1210  * Parameters  :
1211  *          1  :  cert_file = The certificate to check
1212  *
1213  * Returns     :   0 => The certificate is valid.
1214  *                 1 => The certificate is invalid
1215  *
1216  *********************************************************************/
1217 static int ssl_certificate_is_invalid(const char *cert_file)
1218 {
1219    mbedtls_x509_crt cert;
1220    int ret;
1221
1222    mbedtls_x509_crt_init(&cert);
1223
1224    ret = mbedtls_x509_crt_parse_file(&cert, cert_file);
1225    if (ret != 0)
1226    {
1227       char err_buf[ERROR_BUF_SIZE];
1228
1229       mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1230       log_error(LOG_LEVEL_ERROR,
1231          "Loading certificate %s to check validity failed: %s",
1232          cert_file, err_buf);
1233       mbedtls_x509_crt_free(&cert);
1234
1235       return 1;
1236    }
1237    if (mbedtls_x509_time_is_past(&cert.valid_to))
1238    {
1239       mbedtls_x509_crt_free(&cert);
1240
1241       return 1;
1242    }
1243
1244    mbedtls_x509_crt_free(&cert);
1245
1246    return 0;
1247
1248 }
1249
1250
1251 /*********************************************************************
1252  *
1253  * Function    :  generate_certificate_valid_date
1254  *
1255  * Description :  Turns a time_t into the format expected by mbedTLS.
1256  *
1257  * Parameters  :
1258  *          1  :  time_spec = The timestamp to convert
1259  *          2  :  buffer = The buffer to write the date to
1260  *          3  :  buffer_size = The size of the buffer
1261  *
1262  * Returns     :   0 => The conversion worked
1263  *                 1 => The conversion failed
1264  *
1265  *********************************************************************/
1266 static int generate_certificate_valid_date(time_t time_spec, char *buffer,
1267                                            size_t buffer_size)
1268 {
1269    struct tm valid_date;
1270    size_t ret;
1271
1272 #ifndef HAVE_GMTIME_R
1273 #error HTTP inspection currently requires gmtime_r() which seems to be missing
1274 #endif
1275    if (NULL == gmtime_r(&time_spec, &valid_date))
1276    {
1277       return 1;
1278    }
1279
1280    ret = strftime(buffer, buffer_size, "%Y%m%d%H%M%S", &valid_date);
1281    if (ret != 14)
1282    {
1283       return 1;
1284    }
1285
1286    return 0;
1287
1288 }
1289
1290
1291 /*********************************************************************
1292  *
1293  * Function    :  get_certificate_valid_from_date
1294  *
1295  * Description :  Generates a "valid from" date in the format
1296  *                expected by mbedTLS.
1297  *
1298  * Parameters  :
1299  *          1  :  buffer = The buffer to write the date to
1300  *          2  :  buffer_size = The size of the buffer
1301  *
1302  * Returns     :   0 => The generation worked
1303  *                 1 => The generation failed
1304  *
1305  *********************************************************************/
1306 static int get_certificate_valid_from_date(char *buffer, size_t buffer_size)
1307 {
1308    time_t time_spec;
1309
1310    time_spec = time(NULL);
1311    /* 1 month in the past */
1312    time_spec -= 30 * 24 * 60 * 60;
1313
1314    return generate_certificate_valid_date(time_spec, buffer, buffer_size);
1315
1316 }
1317
1318
1319 /*********************************************************************
1320  *
1321  * Function    :  get_certificate_valid_to_date
1322  *
1323  * Description :  Generates a "valid to" date in the format
1324  *                expected by mbedTLS.
1325  *
1326  * Parameters  :
1327  *          1  :  buffer = The buffer to write the date to
1328  *          2  :  buffer_size = The size of the buffer
1329  *
1330  * Returns     :   0 => The generation worked
1331  *                 1 => The generation failed
1332  *
1333  *********************************************************************/
1334 static int get_certificate_valid_to_date(char *buffer, size_t buffer_size)
1335 {
1336    time_t time_spec;
1337
1338    time_spec = time(NULL);
1339    /* Three months in the future */
1340    time_spec += 90 * 24 * 60 * 60;
1341
1342    return generate_certificate_valid_date(time_spec, buffer, buffer_size);
1343
1344 }
1345
1346
1347 /*********************************************************************
1348  *
1349  * Function    :  generate_webpage_certificate
1350  *
1351  * Description :  Creates certificate file in presetted directory.
1352  *                If certificate already exists, no other certificate
1353  *                will be created. Subject of certificate is named
1354  *                by csp->http->host from parameter. This function also
1355  *                triggers generating of private key for new certificate.
1356  *
1357  * Parameters  :
1358  *          1  :  csp = Current client state (buffers, headers, etc...)
1359  *
1360  * Returns     :  -1 => Error while creating certificate.
1361  *                 0 => Certificate already exists.
1362  *                >0 => Length of created certificate.
1363  *
1364  *********************************************************************/
1365 static int generate_webpage_certificate(struct client_state *csp)
1366 {
1367    mbedtls_x509_crt issuer_cert;
1368    mbedtls_pk_context loaded_issuer_key, loaded_subject_key;
1369    mbedtls_pk_context *issuer_key  = &loaded_issuer_key;
1370    mbedtls_pk_context *subject_key = &loaded_subject_key;
1371    mbedtls_x509write_cert cert;
1372    mbedtls_mpi serial;
1373
1374    unsigned char *key_buf = NULL;    /* Buffer for created key */
1375
1376    int ret = 0;
1377    char err_buf[ERROR_BUF_SIZE];
1378    cert_options cert_opt;
1379    char cert_valid_from[15];
1380    char cert_valid_to[15];
1381
1382    /* Paths to keys and certificates needed to create certificate */
1383    cert_opt.issuer_key  = NULL;
1384    cert_opt.subject_key = NULL;
1385    cert_opt.issuer_crt  = NULL;
1386    cert_opt.output_file = NULL;
1387
1388    /*
1389     * Create key for requested host
1390     */
1391    int subject_key_len = generate_key(csp, &key_buf);
1392    if (subject_key_len < 0)
1393    {
1394       log_error(LOG_LEVEL_ERROR, "Key generating failed");
1395       return -1;
1396    }
1397
1398    /*
1399     * Initializing structures for certificate generating
1400     */
1401    mbedtls_x509write_crt_init(&cert);
1402    mbedtls_x509write_crt_set_md_alg(&cert, CERT_SIGNATURE_ALGORITHM);
1403    mbedtls_pk_init(&loaded_issuer_key);
1404    mbedtls_pk_init(&loaded_subject_key);
1405    mbedtls_mpi_init(&serial);
1406    mbedtls_x509_crt_init(&issuer_cert);
1407
1408    /*
1409     * Presetting parameters for certificate. We must compute total length
1410     * of parameters.
1411     */
1412    size_t cert_params_len = strlen(CERT_PARAM_COMMON_NAME) +
1413       strlen(CERT_PARAM_ORGANIZATION) + strlen(CERT_PARAM_COUNTRY) +
1414       strlen(CERT_PARAM_ORG_UNIT) +
1415       3 * strlen(csp->http->host) + 1;
1416    char cert_params[cert_params_len];
1417    memset(cert_params, 0, cert_params_len);
1418
1419    /*
1420     * Converting unsigned long serial number to char * serial number.
1421     * We must compute length of serial number in string + terminating null.
1422     */
1423    unsigned long certificate_serial = get_certificate_serial(csp);
1424    int serial_num_size = snprintf(NULL, 0, "%lu", certificate_serial) + 1;
1425    if (serial_num_size <= 0)
1426    {
1427       serial_num_size = 1;
1428    }
1429
1430    char serial_num_text[serial_num_size];  /* Buffer for serial number */
1431    ret = snprintf(serial_num_text, (size_t)serial_num_size, "%lu", certificate_serial);
1432    if (ret < 0 || ret >= serial_num_size)
1433    {
1434       log_error(LOG_LEVEL_ERROR,
1435          "Converting certificate serial number into string failed");
1436       ret = -1;
1437       goto exit;
1438    }
1439
1440    /*
1441     * Preparing parameters for certificate
1442     */
1443    strlcpy(cert_params, CERT_PARAM_COMMON_NAME,  cert_params_len);
1444    strlcat(cert_params, csp->http->host,         cert_params_len);
1445    strlcat(cert_params, CERT_PARAM_ORGANIZATION, cert_params_len);
1446    strlcat(cert_params, csp->http->host,         cert_params_len);
1447    strlcat(cert_params, CERT_PARAM_ORG_UNIT,     cert_params_len);
1448    strlcat(cert_params, csp->http->host,         cert_params_len);
1449    strlcat(cert_params, CERT_PARAM_COUNTRY,      cert_params_len);
1450
1451    cert_opt.issuer_crt = csp->config->ca_cert_file;
1452    cert_opt.issuer_key = csp->config->ca_key_file;
1453    cert_opt.subject_key = make_certs_path(csp->config->certificate_directory,
1454       (const char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
1455    cert_opt.output_file = make_certs_path(csp->config->certificate_directory,
1456       (const char *)csp->http->hash_of_host_hex, CERT_FILE_TYPE);
1457
1458    if (cert_opt.subject_key == NULL || cert_opt.output_file == NULL)
1459    {
1460       ret = -1;
1461       goto exit;
1462    }
1463
1464    if (get_certificate_valid_from_date(cert_valid_from, sizeof(cert_valid_from))
1465     || get_certificate_valid_to_date(cert_valid_to, sizeof(cert_valid_to)))
1466    {
1467       log_error(LOG_LEVEL_ERROR, "Generating one of the validity dates failed");
1468       ret = -1;
1469       goto exit;
1470    }
1471
1472    cert_opt.subject_pwd   = CERT_SUBJECT_PASSWORD;
1473    cert_opt.issuer_pwd    = csp->config->ca_password;
1474    cert_opt.subject_name  = cert_params;
1475    cert_opt.not_before    = cert_valid_from;
1476    cert_opt.not_after     = cert_valid_to;
1477    cert_opt.serial        = serial_num_text;
1478    cert_opt.is_ca         = 0;
1479    cert_opt.max_pathlen   = -1;
1480
1481    /*
1482     * Test if certificate exists and private key was already created
1483     */
1484    if (file_exists(cert_opt.output_file) == 1 && subject_key_len == 0)
1485    {
1486       /* The file exists, but is it valid */
1487       if (ssl_certificate_is_invalid(cert_opt.output_file))
1488       {
1489          log_error(LOG_LEVEL_CONNECT,
1490             "Certificate %s is no longer valid. Removing.",
1491             cert_opt.output_file);
1492          if (unlink(cert_opt.output_file))
1493          {
1494             log_error(LOG_LEVEL_ERROR, "Failed to unlink %s: %E",
1495                cert_opt.output_file);
1496             ret = -1;
1497             goto exit;
1498          }
1499       }
1500       else
1501       {
1502          ret = 0;
1503          goto exit;
1504       }
1505    }
1506
1507    /*
1508     * Seed the PRNG
1509     */
1510    ret = seed_rng(csp);
1511    if (ret != 0)
1512    {
1513       ret = -1;
1514       goto exit;
1515    }
1516
1517    /*
1518     * Parse serial to MPI
1519     */
1520    ret = mbedtls_mpi_read_string(&serial, 10, cert_opt.serial);
1521    if (ret != 0)
1522    {
1523       mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1524       log_error(LOG_LEVEL_ERROR,
1525          "mbedtls_mpi_read_string failed: %s", err_buf);
1526       ret = -1;
1527       goto exit;
1528    }
1529
1530    /*
1531     * Loading certificates
1532     */
1533    ret = mbedtls_x509_crt_parse_file(&issuer_cert, cert_opt.issuer_crt);
1534    if (ret != 0)
1535    {
1536       mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1537       log_error(LOG_LEVEL_ERROR, "Loading issuer certificate %s failed: %s",
1538          cert_opt.issuer_crt, err_buf);
1539       ret = -1;
1540       goto exit;
1541    }
1542
1543    ret = mbedtls_x509_dn_gets(cert_opt.issuer_name,
1544       sizeof(cert_opt.issuer_name), &issuer_cert.subject);
1545    if (ret < 0)
1546    {
1547       mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1548       log_error(LOG_LEVEL_ERROR, "mbedtls_x509_dn_gets failed: %s", err_buf);
1549       ret = -1;
1550       goto exit;
1551    }
1552
1553    /*
1554     * Loading keys from file or from buffer
1555     */
1556    if (key_buf != NULL && subject_key_len > 0)
1557    {
1558       /* Key was created in this function and is stored in buffer */
1559       ret = mbedtls_pk_parse_key(&loaded_subject_key, key_buf,
1560          (size_t)(subject_key_len + 1), (unsigned const char *)
1561          cert_opt.subject_pwd, strlen(cert_opt.subject_pwd));
1562    }
1563    else
1564    {
1565       /* Key wasn't created in this function, because it already existed */
1566       ret = mbedtls_pk_parse_keyfile(&loaded_subject_key,
1567          cert_opt.subject_key, cert_opt.subject_pwd);
1568    }
1569
1570    if (ret != 0)
1571    {
1572       mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1573       log_error(LOG_LEVEL_ERROR, "Parsing subject key %s failed: %s",
1574          cert_opt.subject_key, err_buf);
1575       ret = -1;
1576       goto exit;
1577    }
1578
1579    ret = mbedtls_pk_parse_keyfile(&loaded_issuer_key, cert_opt.issuer_key,
1580       cert_opt.issuer_pwd);
1581    if (ret != 0)
1582    {
1583       mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1584       log_error(LOG_LEVEL_ERROR,
1585          "Parsing issuer key %s failed: %s", cert_opt.issuer_key, err_buf);
1586       ret = -1;
1587       goto exit;
1588    }
1589
1590    /*
1591     * Check if key and issuer certificate match
1592     */
1593    if (!mbedtls_pk_can_do(&issuer_cert.pk, MBEDTLS_PK_RSA) ||
1594       mbedtls_mpi_cmp_mpi(&mbedtls_pk_rsa(issuer_cert.pk)->N,
1595          &mbedtls_pk_rsa(*issuer_key)->N) != 0 ||
1596       mbedtls_mpi_cmp_mpi(&mbedtls_pk_rsa(issuer_cert.pk)->E,
1597          &mbedtls_pk_rsa(*issuer_key)->E) != 0)
1598    {
1599       log_error(LOG_LEVEL_ERROR,
1600          "Issuer key doesn't match issuer certificate");
1601       ret = -1;
1602       goto exit;
1603    }
1604
1605    mbedtls_x509write_crt_set_subject_key(&cert, subject_key);
1606    mbedtls_x509write_crt_set_issuer_key(&cert, issuer_key);
1607
1608    /*
1609     * Setting parameters of signed certificate
1610     */
1611    ret = mbedtls_x509write_crt_set_subject_name(&cert, cert_opt.subject_name);
1612    if (ret != 0)
1613    {
1614       mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1615       log_error(LOG_LEVEL_ERROR,
1616          "Setting subject name in signed certificate failed: %s", err_buf);
1617       ret = -1;
1618       goto exit;
1619    }
1620
1621    ret = mbedtls_x509write_crt_set_issuer_name(&cert, cert_opt.issuer_name);
1622    if (ret != 0)
1623    {
1624       mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1625       log_error(LOG_LEVEL_ERROR,
1626          "Setting issuer name in signed certificate failed: %s", err_buf);
1627       ret = -1;
1628       goto exit;
1629    }
1630
1631    ret = mbedtls_x509write_crt_set_serial(&cert, &serial);
1632    if (ret != 0)
1633    {
1634       mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1635       log_error(LOG_LEVEL_ERROR,
1636          "Setting serial number in signed certificate failed: %s", err_buf);
1637       ret = -1;
1638       goto exit;
1639    }
1640
1641    ret = mbedtls_x509write_crt_set_validity(&cert, cert_opt.not_before,
1642       cert_opt.not_after);
1643    if (ret != 0)
1644    {
1645       mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1646       log_error(LOG_LEVEL_ERROR,
1647          "Setting validity in signed certificate failed: %s", err_buf);
1648       ret = -1;
1649       goto exit;
1650    }
1651
1652    /*
1653     * Setting the basicConstraints extension for certificate
1654     */
1655    ret = mbedtls_x509write_crt_set_basic_constraints(&cert, cert_opt.is_ca,
1656       cert_opt.max_pathlen);
1657    if (ret != 0)
1658    {
1659       mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1660       log_error(LOG_LEVEL_ERROR, "Setting the basicConstraints extension "
1661          "in signed certificate failed: %s", err_buf);
1662       ret = -1;
1663       goto exit;
1664    }
1665
1666 #if defined(MBEDTLS_SHA1_C)
1667    /* Setting the subjectKeyIdentifier extension for certificate */
1668    ret = mbedtls_x509write_crt_set_subject_key_identifier(&cert);
1669    if (ret != 0)
1670    {
1671       mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1672       log_error(LOG_LEVEL_ERROR, "mbedtls_x509write_crt_set_subject_key_"
1673          "identifier failed: %s", err_buf);
1674       ret = -1;
1675       goto exit;
1676    }
1677
1678    /* Setting the authorityKeyIdentifier extension for certificate */
1679    ret = mbedtls_x509write_crt_set_authority_key_identifier(&cert);
1680    if (ret != 0)
1681    {
1682       mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1683       log_error(LOG_LEVEL_ERROR, "mbedtls_x509write_crt_set_authority_key_"
1684          "identifier failed: %s", err_buf);
1685       ret = -1;
1686       goto exit;
1687    }
1688 #endif /* MBEDTLS_SHA1_C */
1689
1690    /*
1691     * Writing certificate into file
1692     */
1693    ret = write_certificate(&cert, cert_opt.output_file,
1694       mbedtls_ctr_drbg_random, &ctr_drbg);
1695    if (ret < 0)
1696    {
1697       log_error(LOG_LEVEL_ERROR, "Writing certificate into file failed");
1698       goto exit;
1699    }
1700
1701 exit:
1702    /*
1703     * Freeing used structures
1704     */
1705    mbedtls_x509write_crt_free(&cert);
1706    mbedtls_pk_free(&loaded_subject_key);
1707    mbedtls_pk_free(&loaded_issuer_key);
1708    mbedtls_mpi_free(&serial);
1709    mbedtls_x509_crt_free(&issuer_cert);
1710
1711    freez(cert_opt.subject_key);
1712    freez(cert_opt.output_file);
1713    freez(key_buf);
1714
1715    return ret;
1716 }
1717
1718
1719 /*********************************************************************
1720  *
1721  * Function    :  make_certs_path
1722  *
1723  * Description : Creates path to file from three pieces. This function
1724  *               takes parameters and puts them in one new mallocated
1725  *               char * in correct order. Returned variable must be freed
1726  *               by caller. This function is mainly used for creating
1727  *               paths of certificates and keys files.
1728  *
1729  * Parameters  :
1730  *          1  :  conf_dir  = Name/path of directory where is the file.
1731  *                            '.' can be used for current directory.
1732  *          2  :  file_name = Name of file in conf_dir without suffix.
1733  *          3  :  suffix    = Suffix of given file_name.
1734  *
1735  * Returns     :  path => Path was built up successfully
1736  *                NULL => Path can't be built up
1737  *
1738  *********************************************************************/
1739 static char *make_certs_path(const char *conf_dir, const char *file_name,
1740    const char *suffix)
1741 {
1742    /* Test if all given parameters are valid */
1743    if (conf_dir == NULL || *conf_dir == '\0' || file_name == NULL ||
1744       *file_name == '\0' || suffix == NULL || *suffix == '\0')
1745    {
1746       log_error(LOG_LEVEL_ERROR,
1747          "make_certs_path failed: bad input parameters");
1748       return NULL;
1749    }
1750
1751    char *path = NULL;
1752    size_t path_size = strlen(conf_dir)
1753       + strlen(file_name) + strlen(suffix) + 2;
1754
1755    /* Setting delimiter and editing path length */
1756 #if defined(_WIN32) || defined(__OS2__)
1757    char delim[] = "\\";
1758    path_size += 1;
1759 #else /* ifndef _WIN32 || __OS2__ */
1760    char delim[] = "/";
1761 #endif /* ifndef _WIN32 || __OS2__ */
1762
1763    /*
1764     * Building up path from many parts
1765     */
1766 #if defined(unix)
1767    if (*conf_dir != '/' && basedir && *basedir)
1768    {
1769       /*
1770        * Replacing conf_dir with basedir. This new variable contains
1771        * absolute path to cwd.
1772        */
1773       path_size += strlen(basedir) + 2;
1774       path = zalloc_or_die(path_size);
1775
1776       strlcpy(path, basedir,   path_size);
1777       strlcat(path, delim,     path_size);
1778       strlcat(path, conf_dir,  path_size);
1779       strlcat(path, delim,     path_size);
1780       strlcat(path, file_name, path_size);
1781       strlcat(path, suffix,    path_size);
1782    }
1783    else
1784 #endif /* defined unix */
1785    {
1786       path = zalloc_or_die(path_size);
1787
1788       strlcpy(path, conf_dir,  path_size);
1789       strlcat(path, delim,     path_size);
1790       strlcat(path, file_name, path_size);
1791       strlcat(path, suffix,    path_size);
1792    }
1793
1794    return path;
1795 }
1796
1797
1798 /*********************************************************************
1799  *
1800  * Function    :  get_certificate_serial
1801  *
1802  * Description :  Computes serial number for new certificate from host
1803  *                name hash. This hash must be already saved in csp
1804  *                structure.
1805  *
1806  * Parameters  :
1807  *          1  :  csp = Current client state (buffers, headers, etc...)
1808  *
1809  * Returns     :  Serial number for new certificate
1810  *
1811  *********************************************************************/
1812 static unsigned long get_certificate_serial(struct client_state *csp)
1813 {
1814    unsigned long exp    = 1;
1815    unsigned long serial = 0;
1816
1817    int i = CERT_SERIAL_NUM_LENGTH;
1818    /* Length of hash is 16 bytes, we must avoid to read next chars */
1819    if (i > 16)
1820    {
1821       i = 16;
1822    }
1823    if (i < 2)
1824    {
1825       i = 2;
1826    }
1827
1828    for (; i >= 0; i--)
1829    {
1830       serial += exp * (unsigned)csp->http->hash_of_host[i];
1831       exp *= 256;
1832    }
1833    return serial;
1834 }
1835
1836
1837 /*********************************************************************
1838  *
1839  * Function    :  ssl_send_certificate_error
1840  *
1841  * Description :  Sends info about invalid server certificate to client.
1842  *                Sent message is including all trusted chain certificates,
1843  *                that can be downloaded in web browser.
1844  *
1845  * Parameters  :
1846  *          1  :  csp = Current client state (buffers, headers, etc...)
1847  *
1848  * Returns     :  N/A
1849  *
1850  *********************************************************************/
1851 extern void ssl_send_certificate_error(struct client_state *csp)
1852 {
1853    size_t message_len = 0;
1854    int ret = 0;
1855    struct certs_chain *cert = NULL;
1856
1857    /* Header of message with certificate informations */
1858    const char message_begin[] =
1859       "HTTP/1.1 200 OK\r\n"
1860       "Content-Type: text/html\r\n"
1861       "Connection: close\r\n\r\n"
1862       "<html><body><h1>Server certificate verification failed</h1><p>Reason: ";
1863    const char message_end[] = "</body></html>\r\n\r\n";
1864    char reason[INVALID_CERT_INFO_BUF_SIZE];
1865    memset(reason, 0, sizeof(reason));
1866
1867    /* Get verification message from verification return code */
1868    mbedtls_x509_crt_verify_info(reason, sizeof(reason), " ",
1869       csp->server_cert_verification_result);
1870
1871    /*
1872     * Computing total length of message with all certificates inside
1873     */
1874    message_len = strlen(message_begin) + strlen(message_end)
1875                  + strlen(reason) + strlen("</p>") + 1;
1876
1877    cert = &(csp->server_certs_chain);
1878    while (cert->next != NULL)
1879    {
1880       size_t base64_len = 4 * ((strlen(cert->file_buf) + 2) / 3) + 1;
1881
1882       message_len += strlen(cert->text_buf) + strlen("<pre></pre>\n")
1883                      +  base64_len + strlen("<a href=\"data:application"
1884                         "/x-x509-ca-cert;base64,\">Download certificate</a>");
1885       cert = cert->next;
1886    }
1887
1888    /*
1889     * Joining all blocks in one long message
1890     */
1891    char message[message_len];
1892    memset(message, 0, message_len);
1893
1894    strlcpy(message, message_begin, message_len);
1895    strlcat(message, reason       , message_len);
1896    strlcat(message, "</p>"       , message_len);
1897
1898    cert = &(csp->server_certs_chain);
1899    while (cert->next != NULL)
1900    {
1901       size_t olen = 0;
1902       size_t base64_len = 4 * ((strlen(cert->file_buf) + 2) / 3) + 1; /* +1 for terminating null*/
1903       char base64_buf[base64_len];
1904       memset(base64_buf, 0, base64_len);
1905
1906       /* Encoding certificate into base64 code */
1907       ret = mbedtls_base64_encode((unsigned char*)base64_buf,
1908                base64_len, &olen, (const unsigned char*)cert->file_buf,
1909                strlen(cert->file_buf));
1910       if (ret != 0)
1911       {
1912          log_error(LOG_LEVEL_ERROR,
1913             "Encoding to base64 failed, buffer is to small");
1914       }
1915
1916       strlcat(message, "<pre>",        message_len);
1917       strlcat(message, cert->text_buf, message_len);
1918       strlcat(message, "</pre>\n",     message_len);
1919
1920       if (ret == 0)
1921       {
1922          strlcat(message, "<a href=\"data:application/x-x509-ca-cert;base64,",
1923             message_len);
1924          strlcat(message, base64_buf, message_len);
1925          strlcat(message, "\">Download certificate</a>", message_len);
1926       }
1927
1928       cert = cert->next;
1929    }
1930    strlcat(message, message_end, message_len);
1931
1932    /*
1933     * Sending final message to client
1934     */
1935    ssl_send_data(&(csp->mbedtls_client_attr.ssl),
1936       (const unsigned char *)message, strlen(message));
1937
1938    free_certificate_chain(csp);
1939 }
1940
1941
1942 /*********************************************************************
1943  *
1944  * Function    :  ssl_verify_callback
1945  *
1946  * Description :  This is a callback function for certificate verification.
1947  *                It's called for all certificates in server certificate
1948  *                trusted chain and it's preparing information about this
1949  *                certificates. Prepared informations can be used to inform
1950  *                user about invalid certificates.
1951  *
1952  * Parameters  :
1953  *          1  :  csp_void = Current client state (buffers, headers, etc...)
1954  *          2  :  crt   = certificate from trusted chain
1955  *          3  :  depth = depth in trusted chain
1956  *          4  :  flags = certificate flags
1957  *
1958  * Returns     :  0 on success and negative value on error
1959  *
1960  *********************************************************************/
1961 static int ssl_verify_callback(void *csp_void, mbedtls_x509_crt *crt,
1962    int depth, uint32_t *flags)
1963 {
1964    struct client_state *csp  = (struct client_state *)csp_void;
1965    struct certs_chain  *last = &(csp->server_certs_chain);
1966    size_t olen = 0;
1967    int ret = 0;
1968
1969    /*
1970     * Searching for last item in certificates linked list
1971     */
1972    while (last->next != NULL)
1973    {
1974       last = last->next;
1975    }
1976
1977    /*
1978     * Preparing next item in linked list for next certificate
1979     */
1980    last->next = malloc_or_die(sizeof(struct certs_chain));
1981    last->next->next = NULL;
1982    memset(last->next->text_buf, 0, sizeof(last->next->text_buf));
1983    memset(last->next->file_buf, 0, sizeof(last->next->file_buf));
1984
1985    /*
1986     * Saving certificate file into buffer
1987     */
1988    if ((ret = mbedtls_pem_write_buffer(PEM_BEGIN_CRT, PEM_END_CRT,
1989       crt->raw.p, crt->raw.len, (unsigned char *)last->file_buf,
1990       sizeof(last->file_buf)-1, &olen)) != 0)
1991    {
1992       return(ret);
1993    }
1994
1995    /*
1996     * Saving certificate information into buffer
1997     */
1998    mbedtls_x509_crt_info(last->text_buf, sizeof(last->text_buf) - 1,
1999       CERT_INFO_PREFIX, crt);
2000
2001    return 0;
2002 }
2003
2004
2005 /*********************************************************************
2006  *
2007  * Function    :  free_certificate_chain
2008  *
2009  * Description :  Frees certificates linked list. This linked list is
2010  *                used to save informations about certificates in
2011  *                trusted chain.
2012  *
2013  * Parameters  :
2014  *          1  :  csp = Current client state (buffers, headers, etc...)
2015  *
2016  * Returns     :  N/A
2017  *
2018  *********************************************************************/
2019 static void free_certificate_chain(struct client_state *csp)
2020 {
2021    struct certs_chain *cert = csp->server_certs_chain.next;
2022
2023    /* Cleaning buffers */
2024    memset(csp->server_certs_chain.text_buf, 0,
2025       sizeof(csp->server_certs_chain.text_buf));
2026    memset(csp->server_certs_chain.file_buf, 0,
2027       sizeof(csp->server_certs_chain.file_buf));
2028    csp->server_certs_chain.next = NULL;
2029
2030    /* Freeing memory in whole linked list */
2031    if (cert != NULL)
2032    {
2033       do
2034       {
2035          struct certs_chain *cert_for_free = cert;
2036          cert = cert->next;
2037          freez(cert_for_free);
2038       } while (cert != NULL);
2039    }
2040 }
2041
2042
2043 /*********************************************************************
2044  *
2045  * Function    :  file_exists
2046  *
2047  * Description :  Tests if file exists and is readable.
2048  *
2049  * Parameters  :
2050  *          1  :  path = Path to tested file.
2051  *
2052  * Returns     :  1 => File exists and is readable.
2053  *                0 => File doesn't exist or is not readable.
2054  *
2055  *********************************************************************/
2056 static int file_exists(const char *path)
2057 {
2058    FILE *f;
2059    if ((f = fopen(path, "r")) != NULL)
2060    {
2061       fclose(f);
2062       return 1;
2063    }
2064
2065    return 0;
2066 }
2067
2068
2069 /*********************************************************************
2070  *
2071  * Function    :  host_to_hash
2072  *
2073  * Description :  Creates MD5 hash from host name. Host name is loaded
2074  *                from structure csp and saved again into it.
2075  *
2076  * Parameters  :
2077  *          1  :  csp = Current client state (buffers, headers, etc...)
2078  *
2079  * Returns     :  1 => Error while creating hash
2080  *                0 => Hash created successfully
2081  *
2082  *********************************************************************/
2083 static int host_to_hash(struct client_state *csp)
2084 {
2085    int ret = 0;
2086
2087 #if !defined(MBEDTLS_MD5_C)
2088 #error mbedTLS needs to be compiled with md5 support
2089 #else
2090    memset(csp->http->hash_of_host, 0, sizeof(csp->http->hash_of_host));
2091    mbedtls_md5((unsigned char *)csp->http->host, strlen(csp->http->host),
2092       csp->http->hash_of_host);
2093
2094    /* Converting hash into string with hex */
2095    size_t i = 0;
2096    for (; i < 16; i++)
2097    {
2098       if ((ret = sprintf((char *)csp->http->hash_of_host_hex + 2 * i, "%02x",
2099          csp->http->hash_of_host[i])) < 0)
2100       {
2101          log_error(LOG_LEVEL_ERROR, "Sprintf return value: %d", ret);
2102          return -1;
2103       }
2104    }
2105
2106    return 0;
2107 #endif /* MBEDTLS_MD5_C */
2108 }
2109
2110
2111 /*********************************************************************
2112  *
2113  * Function    :  tunnel_established_successfully
2114  *
2115  * Description :  Check if parent proxy server response contains
2116  *                informations about successfully created connection with
2117  *                destination server. (HTTP/... 2xx ...)
2118  *
2119  * Parameters  :
2120  *          1  :  server_response = Buffer with parent proxy server response
2121  *          2  :  response_len = Length of server_response
2122  *
2123  * Returns     :  1 => Connection created successfully
2124  *                0 => Connection wasn't created successfully
2125  *
2126  *********************************************************************/
2127 extern int tunnel_established_successfully(const char *server_response,
2128    unsigned int response_len)
2129 {
2130    unsigned int pos = 0;
2131
2132    if (server_response == NULL)
2133    {
2134       return 0;
2135    }
2136
2137    /* Tests if "HTTP/" string is at the begin of received response */
2138    if (strncmp(server_response, "HTTP/", 5) != 0)
2139    {
2140       return 0;
2141    }
2142
2143    for (pos = 0; pos < response_len; pos++)
2144    {
2145       if (server_response[pos] == ' ')
2146       {
2147          break;
2148       }
2149    }
2150
2151    /*
2152     * response_len -3 because of buffer end, response structure and 200 code.
2153     * There must be at least 3 chars after space.
2154     * End of buffer: ... 2xx'\0'
2155     *             pos = |
2156     */
2157    if (pos >= (response_len - 3))
2158    {
2159       return 0;
2160    }
2161
2162    /* Test HTTP status code */
2163    if (server_response[pos + 1] != '2')
2164    {
2165       return 0;
2166    }
2167
2168    return 1;
2169 }
2170
2171
2172 /*********************************************************************
2173  *
2174  * Function    :  seed_rng
2175  *
2176  * Description :  Seeding the RNG for all SSL uses
2177  *
2178  * Parameters  :
2179  *          1  :  csp = Current client state (buffers, headers, etc...)
2180  *
2181  * Returns     : -1 => RNG wasn't seed successfully
2182  *                0 => RNG is seeded successfully
2183  *
2184  *********************************************************************/
2185 static int seed_rng(struct client_state *csp)
2186 {
2187    int ret = 0;
2188    char err_buf[ERROR_BUF_SIZE];
2189
2190    if (rng_seeded == 0)
2191    {
2192       privoxy_mutex_lock(&rng_mutex);
2193       if (rng_seeded == 0)
2194       {
2195          mbedtls_ctr_drbg_init(&ctr_drbg);
2196          mbedtls_entropy_init(&entropy);
2197          ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func,
2198             &entropy, NULL, 0);
2199          if (ret != 0)
2200          {
2201             mbedtls_strerror(ret, err_buf, sizeof(err_buf));
2202             log_error(LOG_LEVEL_ERROR,
2203                "mbedtls_ctr_drbg_seed failed: %s", err_buf);
2204             privoxy_mutex_unlock(&rng_mutex);
2205             return -1;
2206          }
2207          rng_seeded = 1;
2208       }
2209       privoxy_mutex_unlock(&rng_mutex);
2210    }
2211    return 0;
2212 }