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