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