mbedTLS ssl_crt_verify_info(): Ditch trailing new line
[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_host_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_host_certificate(csp);
329    if (ret < 0)
330    {
331       log_error(LOG_LEVEL_ERROR,
332          "generate_host_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_host_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_host_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 (enforce_sane_certificate_state(cert_opt.output_file,
1314          cert_opt.subject_key))
1315    {
1316       freez(cert_opt.output_file);
1317       freez(cert_opt.subject_key);
1318
1319       return -1;
1320    }
1321
1322    if (file_exists(cert_opt.output_file) == 1)
1323    {
1324       /* The file exists, but is it valid? */
1325       if (ssl_certificate_is_invalid(cert_opt.output_file))
1326       {
1327          log_error(LOG_LEVEL_CONNECT,
1328             "Certificate %s is no longer valid. Removing it.",
1329             cert_opt.output_file);
1330          if (unlink(cert_opt.output_file))
1331          {
1332             log_error(LOG_LEVEL_ERROR, "Failed to unlink %s: %E",
1333                cert_opt.output_file);
1334
1335             freez(cert_opt.output_file);
1336             freez(cert_opt.subject_key);
1337
1338             return -1;
1339          }
1340          if (unlink(cert_opt.subject_key))
1341          {
1342             log_error(LOG_LEVEL_ERROR, "Failed to unlink %s: %E",
1343                cert_opt.subject_key);
1344
1345             freez(cert_opt.output_file);
1346             freez(cert_opt.subject_key);
1347
1348             return -1;
1349          }
1350       }
1351       else
1352       {
1353          freez(cert_opt.output_file);
1354          freez(cert_opt.subject_key);
1355
1356          return 0;
1357       }
1358    }
1359
1360    /*
1361     * Create key for requested host
1362     */
1363    int subject_key_len = generate_key(csp, &key_buf);
1364    if (subject_key_len < 0)
1365    {
1366       freez(cert_opt.output_file);
1367       freez(cert_opt.subject_key);
1368       log_error(LOG_LEVEL_ERROR, "Key generating failed");
1369       return -1;
1370    }
1371
1372    /*
1373     * Initializing structures for certificate generating
1374     */
1375    mbedtls_x509write_crt_init(&cert);
1376    mbedtls_x509write_crt_set_md_alg(&cert, CERT_SIGNATURE_ALGORITHM);
1377    mbedtls_pk_init(&loaded_issuer_key);
1378    mbedtls_pk_init(&loaded_subject_key);
1379    mbedtls_mpi_init(&serial);
1380    mbedtls_x509_crt_init(&issuer_cert);
1381
1382    /*
1383     * Presetting parameters for certificate. We must compute total length
1384     * of parameters.
1385     */
1386    size_t cert_params_len = strlen(CERT_PARAM_COMMON_NAME) +
1387       strlen(CERT_PARAM_ORGANIZATION) + strlen(CERT_PARAM_COUNTRY) +
1388       strlen(CERT_PARAM_ORG_UNIT) +
1389       3 * strlen(csp->http->host) + 1;
1390    char cert_params[cert_params_len];
1391    memset(cert_params, 0, cert_params_len);
1392
1393    /*
1394     * Converting unsigned long serial number to char * serial number.
1395     * We must compute length of serial number in string + terminating null.
1396     */
1397    unsigned long certificate_serial = get_certificate_serial(csp);
1398    unsigned long certificate_serial_time = (unsigned long)time(NULL);
1399    int serial_num_size = snprintf(NULL, 0, "%lu%lu",
1400       certificate_serial_time, certificate_serial) + 1;
1401    if (serial_num_size <= 0)
1402    {
1403       serial_num_size = 1;
1404    }
1405
1406    char serial_num_text[serial_num_size];  /* Buffer for serial number */
1407    ret = snprintf(serial_num_text, (size_t)serial_num_size, "%lu%lu",
1408       certificate_serial_time, certificate_serial);
1409    if (ret < 0 || ret >= serial_num_size)
1410    {
1411       log_error(LOG_LEVEL_ERROR,
1412          "Converting certificate serial number into string failed");
1413       ret = -1;
1414       goto exit;
1415    }
1416
1417    /*
1418     * Preparing parameters for certificate
1419     */
1420    strlcpy(cert_params, CERT_PARAM_COMMON_NAME,  cert_params_len);
1421    strlcat(cert_params, csp->http->host,         cert_params_len);
1422    strlcat(cert_params, CERT_PARAM_ORGANIZATION, cert_params_len);
1423    strlcat(cert_params, csp->http->host,         cert_params_len);
1424    strlcat(cert_params, CERT_PARAM_ORG_UNIT,     cert_params_len);
1425    strlcat(cert_params, csp->http->host,         cert_params_len);
1426    strlcat(cert_params, CERT_PARAM_COUNTRY,      cert_params_len);
1427
1428    cert_opt.issuer_crt = csp->config->ca_cert_file;
1429    cert_opt.issuer_key = csp->config->ca_key_file;
1430
1431    if (get_certificate_valid_from_date(cert_valid_from, sizeof(cert_valid_from), VALID_DATETIME_FMT)
1432     || get_certificate_valid_to_date(cert_valid_to, sizeof(cert_valid_to), VALID_DATETIME_FMT))
1433    {
1434       log_error(LOG_LEVEL_ERROR, "Generating one of the validity dates failed");
1435       ret = -1;
1436       goto exit;
1437    }
1438
1439    cert_opt.subject_pwd   = CERT_SUBJECT_PASSWORD;
1440    cert_opt.issuer_pwd    = csp->config->ca_password;
1441    cert_opt.subject_name  = cert_params;
1442    cert_opt.not_before    = cert_valid_from;
1443    cert_opt.not_after     = cert_valid_to;
1444    cert_opt.serial        = serial_num_text;
1445    cert_opt.is_ca         = 0;
1446    cert_opt.max_pathlen   = -1;
1447
1448    /*
1449     * Test if the private key was already created.
1450     * XXX: Can this still happen?
1451     */
1452    if (subject_key_len == 0)
1453    {
1454       log_error(LOG_LEVEL_ERROR, "Subject key was already created");
1455       ret = 0;
1456       goto exit;
1457    }
1458
1459    /*
1460     * Seed the PRNG
1461     */
1462    ret = seed_rng(csp);
1463    if (ret != 0)
1464    {
1465       ret = -1;
1466       goto exit;
1467    }
1468
1469    /*
1470     * Parse serial to MPI
1471     */
1472    ret = mbedtls_mpi_read_string(&serial, 10, cert_opt.serial);
1473    if (ret != 0)
1474    {
1475       mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1476       log_error(LOG_LEVEL_ERROR,
1477          "mbedtls_mpi_read_string failed: %s", err_buf);
1478       ret = -1;
1479       goto exit;
1480    }
1481
1482    /*
1483     * Loading certificates
1484     */
1485    ret = mbedtls_x509_crt_parse_file(&issuer_cert, cert_opt.issuer_crt);
1486    if (ret != 0)
1487    {
1488       mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1489       log_error(LOG_LEVEL_ERROR, "Loading issuer certificate %s failed: %s",
1490          cert_opt.issuer_crt, err_buf);
1491       ret = -1;
1492       goto exit;
1493    }
1494
1495    ret = mbedtls_x509_dn_gets(cert_opt.issuer_name,
1496       sizeof(cert_opt.issuer_name), &issuer_cert.subject);
1497    if (ret < 0)
1498    {
1499       mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1500       log_error(LOG_LEVEL_ERROR, "mbedtls_x509_dn_gets failed: %s", err_buf);
1501       ret = -1;
1502       goto exit;
1503    }
1504
1505    /*
1506     * Loading keys from file or from buffer
1507     */
1508    if (key_buf != NULL && subject_key_len > 0)
1509    {
1510       /* Key was created in this function and is stored in buffer */
1511       ret = mbedtls_pk_parse_key(&loaded_subject_key, key_buf,
1512          (size_t)(subject_key_len + 1), (unsigned const char *)
1513          cert_opt.subject_pwd, strlen(cert_opt.subject_pwd));
1514    }
1515    else
1516    {
1517       /* Key wasn't created in this function, because it already existed */
1518       ret = mbedtls_pk_parse_keyfile(&loaded_subject_key,
1519          cert_opt.subject_key, cert_opt.subject_pwd);
1520    }
1521
1522    if (ret != 0)
1523    {
1524       mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1525       log_error(LOG_LEVEL_ERROR, "Parsing subject key %s failed: %s",
1526          cert_opt.subject_key, err_buf);
1527       ret = -1;
1528       goto exit;
1529    }
1530
1531    ret = mbedtls_pk_parse_keyfile(&loaded_issuer_key, cert_opt.issuer_key,
1532       cert_opt.issuer_pwd);
1533    if (ret != 0)
1534    {
1535       mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1536       log_error(LOG_LEVEL_ERROR,
1537          "Parsing issuer key %s failed: %s", cert_opt.issuer_key, err_buf);
1538       ret = -1;
1539       goto exit;
1540    }
1541
1542    /*
1543     * Check if key and issuer certificate match
1544     */
1545    if (!mbedtls_pk_can_do(&issuer_cert.pk, MBEDTLS_PK_RSA) ||
1546       mbedtls_mpi_cmp_mpi(&mbedtls_pk_rsa(issuer_cert.pk)->N,
1547          &mbedtls_pk_rsa(*issuer_key)->N) != 0 ||
1548       mbedtls_mpi_cmp_mpi(&mbedtls_pk_rsa(issuer_cert.pk)->E,
1549          &mbedtls_pk_rsa(*issuer_key)->E) != 0)
1550    {
1551       log_error(LOG_LEVEL_ERROR,
1552          "Issuer key doesn't match issuer certificate");
1553       ret = -1;
1554       goto exit;
1555    }
1556
1557    mbedtls_x509write_crt_set_subject_key(&cert, subject_key);
1558    mbedtls_x509write_crt_set_issuer_key(&cert, issuer_key);
1559
1560    /*
1561     * Setting parameters of signed certificate
1562     */
1563    ret = mbedtls_x509write_crt_set_subject_name(&cert, cert_opt.subject_name);
1564    if (ret != 0)
1565    {
1566       mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1567       log_error(LOG_LEVEL_ERROR,
1568          "Setting subject name in signed certificate failed: %s", err_buf);
1569       ret = -1;
1570       goto exit;
1571    }
1572
1573    ret = mbedtls_x509write_crt_set_issuer_name(&cert, cert_opt.issuer_name);
1574    if (ret != 0)
1575    {
1576       mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1577       log_error(LOG_LEVEL_ERROR,
1578          "Setting issuer name in signed certificate failed: %s", err_buf);
1579       ret = -1;
1580       goto exit;
1581    }
1582
1583    ret = mbedtls_x509write_crt_set_serial(&cert, &serial);
1584    if (ret != 0)
1585    {
1586       mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1587       log_error(LOG_LEVEL_ERROR,
1588          "Setting serial number in signed certificate failed: %s", err_buf);
1589       ret = -1;
1590       goto exit;
1591    }
1592
1593    ret = mbedtls_x509write_crt_set_validity(&cert, cert_opt.not_before,
1594       cert_opt.not_after);
1595    if (ret != 0)
1596    {
1597       mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1598       log_error(LOG_LEVEL_ERROR,
1599          "Setting validity in signed certificate failed: %s", err_buf);
1600       ret = -1;
1601       goto exit;
1602    }
1603
1604    /*
1605     * Setting the basicConstraints extension for certificate
1606     */
1607    ret = mbedtls_x509write_crt_set_basic_constraints(&cert, cert_opt.is_ca,
1608       cert_opt.max_pathlen);
1609    if (ret != 0)
1610    {
1611       mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1612       log_error(LOG_LEVEL_ERROR, "Setting the basicConstraints extension "
1613          "in signed certificate failed: %s", err_buf);
1614       ret = -1;
1615       goto exit;
1616    }
1617
1618 #if defined(MBEDTLS_SHA1_C)
1619    /* Setting the subjectKeyIdentifier extension for certificate */
1620    ret = mbedtls_x509write_crt_set_subject_key_identifier(&cert);
1621    if (ret != 0)
1622    {
1623       mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1624       log_error(LOG_LEVEL_ERROR, "mbedtls_x509write_crt_set_subject_key_"
1625          "identifier failed: %s", err_buf);
1626       ret = -1;
1627       goto exit;
1628    }
1629
1630    /* Setting the authorityKeyIdentifier extension for certificate */
1631    ret = mbedtls_x509write_crt_set_authority_key_identifier(&cert);
1632    if (ret != 0)
1633    {
1634       mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1635       log_error(LOG_LEVEL_ERROR, "mbedtls_x509write_crt_set_authority_key_"
1636          "identifier failed: %s", err_buf);
1637       ret = -1;
1638       goto exit;
1639    }
1640 #endif /* MBEDTLS_SHA1_C */
1641
1642    if (!host_is_ip_address(csp->http->host) &&
1643       set_subject_alternative_name(&cert, csp->http->host))
1644    {
1645       /* Errors are already logged by set_subject_alternative_name() */
1646       ret = -1;
1647       goto exit;
1648    }
1649
1650    /*
1651     * Writing certificate into file
1652     */
1653    ret = write_certificate(&cert, cert_opt.output_file,
1654       mbedtls_ctr_drbg_random, &ctr_drbg);
1655    if (ret < 0)
1656    {
1657       log_error(LOG_LEVEL_ERROR, "Writing certificate into file failed");
1658       goto exit;
1659    }
1660
1661 exit:
1662    /*
1663     * Freeing used structures
1664     */
1665    mbedtls_x509write_crt_free(&cert);
1666    mbedtls_pk_free(&loaded_subject_key);
1667    mbedtls_pk_free(&loaded_issuer_key);
1668    mbedtls_mpi_free(&serial);
1669    mbedtls_x509_crt_free(&issuer_cert);
1670
1671    freez(cert_opt.subject_key);
1672    freez(cert_opt.output_file);
1673    freez(key_buf);
1674
1675    return ret;
1676 }
1677
1678 /*********************************************************************
1679  *
1680  * Function    :  ssl_verify_callback
1681  *
1682  * Description :  This is a callback function for certificate verification.
1683  *                It's called once for each certificate in the server's
1684  *                certificate trusted chain and prepares information about
1685  *                the certificate. The information can be used to inform
1686  *                the user about invalid certificates.
1687  *
1688  * Parameters  :
1689  *          1  :  csp_void = Current client state (buffers, headers, etc...)
1690  *          2  :  crt   = certificate from trusted chain
1691  *          3  :  depth = depth in trusted chain
1692  *          4  :  flags = certificate flags
1693  *
1694  * Returns     :  0 on success and negative value on error
1695  *
1696  *********************************************************************/
1697 static int ssl_verify_callback(void *csp_void, mbedtls_x509_crt *crt,
1698    int depth, uint32_t *flags)
1699 {
1700    struct client_state *csp  = (struct client_state *)csp_void;
1701    struct certs_chain  *last = &(csp->server_certs_chain);
1702    size_t olen = 0;
1703    int ret = 0;
1704
1705    /*
1706     * Searching for last item in certificates linked list
1707     */
1708    while (last->next != NULL)
1709    {
1710       last = last->next;
1711    }
1712
1713    /*
1714     * Preparing next item in linked list for next certificate
1715     */
1716    last->next = malloc_or_die(sizeof(struct certs_chain));
1717    last->next->next = NULL;
1718    memset(last->next->info_buf, 0, sizeof(last->next->info_buf));
1719    memset(last->next->file_buf, 0, sizeof(last->next->file_buf));
1720
1721    /*
1722     * Saving certificate file into buffer
1723     */
1724    if ((ret = mbedtls_pem_write_buffer(PEM_BEGIN_CRT, PEM_END_CRT,
1725       crt->raw.p, crt->raw.len, (unsigned char *)last->file_buf,
1726       sizeof(last->file_buf)-1, &olen)) != 0)
1727    {
1728       char err_buf[ERROR_BUF_SIZE];
1729
1730       mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1731       log_error(LOG_LEVEL_ERROR, "mbedtls_pem_write_buffer() failed: %s",
1732          err_buf);
1733
1734       return(ret);
1735    }
1736
1737    /*
1738     * Saving certificate information into buffer
1739     */
1740    {
1741       char buf[CERT_INFO_BUF_SIZE];
1742       char *encoded_text;
1743
1744       mbedtls_x509_crt_info(buf, sizeof(buf), CERT_INFO_PREFIX, crt);
1745       encoded_text = html_encode(buf);
1746       if (encoded_text == NULL)
1747       {
1748          log_error(LOG_LEVEL_ERROR,
1749             "Failed to HTML-encode the certificate information");
1750          return -1;
1751       }
1752       strlcpy(last->info_buf, encoded_text, sizeof(last->info_buf));
1753       freez(encoded_text);
1754    }
1755
1756    return 0;
1757 }
1758
1759
1760 /*********************************************************************
1761  *
1762  * Function    :  host_to_hash
1763  *
1764  * Description :  Creates MD5 hash from host name. Host name is loaded
1765  *                from structure csp and saved again into it.
1766  *
1767  * Parameters  :
1768  *          1  :  csp = Current client state (buffers, headers, etc...)
1769  *
1770  * Returns     :  1 => Error while creating hash
1771  *                0 => Hash created successfully
1772  *
1773  *********************************************************************/
1774 static int host_to_hash(struct client_state *csp)
1775 {
1776    int ret = 0;
1777
1778 #if !defined(MBEDTLS_MD5_C)
1779 #error mbedTLS needs to be compiled with md5 support
1780 #else
1781    memset(csp->http->hash_of_host, 0, sizeof(csp->http->hash_of_host));
1782    mbedtls_md5((unsigned char *)csp->http->host, strlen(csp->http->host),
1783       csp->http->hash_of_host);
1784
1785    /* Converting hash into string with hex */
1786    size_t i = 0;
1787    for (; i < 16; i++)
1788    {
1789       if ((ret = sprintf((char *)csp->http->hash_of_host_hex + 2 * i, "%02x",
1790          csp->http->hash_of_host[i])) < 0)
1791       {
1792          log_error(LOG_LEVEL_ERROR, "Sprintf return value: %d", ret);
1793          return -1;
1794       }
1795    }
1796
1797    return 0;
1798 #endif /* MBEDTLS_MD5_C */
1799 }
1800
1801 /*********************************************************************
1802  *
1803  * Function    :  seed_rng
1804  *
1805  * Description :  Seeding the RNG for all SSL uses
1806  *
1807  * Parameters  :
1808  *          1  :  csp = Current client state (buffers, headers, etc...)
1809  *
1810  * Returns     : -1 => RNG wasn't seed successfully
1811  *                0 => RNG is seeded successfully
1812  *
1813  *********************************************************************/
1814 static int seed_rng(struct client_state *csp)
1815 {
1816    int ret = 0;
1817    char err_buf[ERROR_BUF_SIZE];
1818
1819    if (rng_seeded == 0)
1820    {
1821       privoxy_mutex_lock(&ssl_init_mutex);
1822       if (rng_seeded == 0)
1823       {
1824          mbedtls_ctr_drbg_init(&ctr_drbg);
1825          mbedtls_entropy_init(&entropy);
1826          ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func,
1827             &entropy, NULL, 0);
1828          if (ret != 0)
1829          {
1830             mbedtls_strerror(ret, err_buf, sizeof(err_buf));
1831             log_error(LOG_LEVEL_ERROR,
1832                "mbedtls_ctr_drbg_seed failed: %s", err_buf);
1833             privoxy_mutex_unlock(&ssl_init_mutex);
1834             return -1;
1835          }
1836          rng_seeded = 1;
1837       }
1838       privoxy_mutex_unlock(&ssl_init_mutex);
1839    }
1840    return 0;
1841 }
1842
1843
1844 /*********************************************************************
1845  *
1846  * Function    :  ssl_base64_encode
1847  *
1848  * Description :  Encode a buffer into base64 format.
1849  *
1850  * Parameters  :
1851  *          1  :  dst = Destination buffer
1852  *          2  :  dlen = Destination buffer length
1853  *          3  :  olen = Number of bytes written
1854  *          4  :  src = Source buffer
1855  *          5  :  slen = Amount of data to be encoded
1856  *
1857  * Returns     :  0 on success, error code othervise
1858  *
1859  *********************************************************************/
1860 extern int ssl_base64_encode(unsigned char *dst, size_t dlen, size_t *olen,
1861                              const unsigned char *src, size_t slen)
1862 {
1863    return mbedtls_base64_encode(dst, dlen, olen, src, slen);
1864 }
1865
1866
1867 /*********************************************************************
1868  *
1869  * Function    :  ssl_crt_verify_info
1870  *
1871  * Description :  Returns an informational string about the verification
1872  *                status of a certificate.
1873  *
1874  * Parameters  :
1875  *          1  :  buf = Buffer to write to
1876  *          2  :  size = Maximum size of buffer
1877  *          3  :  csp = client state
1878  *
1879  * Returns     :  N/A
1880  *
1881  *********************************************************************/
1882 extern void ssl_crt_verify_info(char *buf, size_t size, struct client_state *csp)
1883 {
1884    char *last_byte;
1885
1886    mbedtls_x509_crt_verify_info(buf, size, "",
1887       csp->server_cert_verification_result);
1888    last_byte = buf + strlen(buf)-1;
1889    if (*last_byte == '\n')
1890    {
1891       /* Overwrite trailing new line character */
1892       *last_byte = '\0';
1893    }
1894 }
1895
1896
1897 /*********************************************************************
1898  *
1899  * Function    :  ssl_release
1900  *
1901  * Description :  Release all SSL resources
1902  *
1903  * Parameters  :
1904  *
1905  * Returns     :  N/A
1906  *
1907  *********************************************************************/
1908 extern void ssl_release(void)
1909 {
1910    if (rng_seeded == 1)
1911    {
1912       mbedtls_ctr_drbg_free(&ctr_drbg);
1913       mbedtls_entropy_free(&entropy);
1914    }
1915 }
1916
1917
1918 /*********************************************************************
1919  *
1920  * Function    :  get_ciphersuites_from_string
1921  *
1922  * Description :  Converts a string of ciphersuite names to
1923  *                an array of ciphersuite ids.
1924  *
1925  * Parameters  :
1926  *          1  :  ciphersuites_string = String containing allowed
1927  *                ciphersuites.
1928  *
1929  * Returns     :  Array of ciphersuite ids
1930  *
1931  *********************************************************************/
1932 static int *get_ciphersuites_from_string(const char *parameter_string)
1933 {
1934    char *ciphersuites_index;
1935    char *item_end;
1936    char *ciphersuites_string;
1937    int *ciphersuite_ids;
1938    size_t count = 2;
1939    int index = 0;
1940    const char separator = ':';
1941    size_t parameter_len = strlen(parameter_string);
1942
1943    ciphersuites_string = zalloc_or_die(parameter_len + 1);
1944    strncpy(ciphersuites_string, parameter_string, parameter_len);
1945    ciphersuites_index = ciphersuites_string;
1946
1947    while (*ciphersuites_index)
1948    {
1949       if (*ciphersuites_index++ == separator)
1950       {
1951          ++count;
1952       }
1953    }
1954
1955    ciphersuite_ids = zalloc_or_die(count * sizeof(int));
1956
1957    ciphersuites_index = ciphersuites_string;
1958    do
1959    {
1960       item_end = strchr(ciphersuites_index, separator);
1961       if (item_end != NULL)
1962       {
1963          *item_end = '\0';
1964       }
1965
1966       ciphersuite_ids[index] =
1967          mbedtls_ssl_get_ciphersuite_id(ciphersuites_index);
1968       if (ciphersuite_ids[index] == 0)
1969       {
1970          log_error(LOG_LEVEL_ERROR,
1971             "Failed to get ciphersuite id for %s", ciphersuites_index);
1972          freez(ciphersuite_ids);
1973          freez(ciphersuites_string);
1974          return NULL;
1975       }
1976       ciphersuites_index = item_end + 1;
1977       index++;
1978    } while (item_end != NULL);
1979
1980    ciphersuite_ids[index] = 0;
1981    freez(ciphersuites_string);
1982
1983    return ciphersuite_ids;
1984
1985 }