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