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