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