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