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