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