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