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