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