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