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