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