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