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