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