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