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