51fcad588a12f44c5a761c5479693f3c21829031
[privoxy.git] / openssl.c
1 /*********************************************************************
2  *
3  * File        :  $Source: /cvsroot/ijbswa/current/openssl.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) 2020 Maxim Antonov <mantonov@gmail.com>
9  *                Copyright (C) 2017 Vaclav Svec. FIT CVUT.
10  *                Copyright (C) 2018-2020 by Fabian Keil <fk@fabiankeil.de>
11  *
12  *                This program is free software; you can redistribute it
13  *                and/or modify it under the terms of the GNU General
14  *                Public License as published by the Free Software
15  *                Foundation; either version 2 of the License, or (at
16  *                your option) any later version.
17  *
18  *                This program is distributed in the hope that it will
19  *                be useful, but WITHOUT ANY WARRANTY; without even the
20  *                implied warranty of MERCHANTABILITY or FITNESS FOR A
21  *                PARTICULAR PURPOSE.  See the GNU General Public
22  *                License for more details.
23  *
24  *                The GNU General Public License should be included with
25  *                this file.  If not, you can view it at
26  *                http://www.gnu.org/copyleft/gpl.html
27  *                or write to the Free Software Foundation, Inc., 59
28  *                Temple Place - Suite 330, Boston, MA  02111-1307, USA.
29  *
30  *********************************************************************/
31
32 #include <string.h>
33 #include <unistd.h>
34
35 #include <openssl/bn.h>
36 #include <openssl/opensslv.h>
37 #include <openssl/pem.h>
38 #include <openssl/md5.h>
39 #include <openssl/x509v3.h>
40
41 #include "config.h"
42 #include "project.h"
43 #include "miscutil.h"
44 #include "errlog.h"
45 #include "encode.h"
46 #include "jcc.h"
47 #include "ssl.h"
48 #include "ssl_common.h"
49
50 /*
51  * Macros for openssl.c
52  */
53 #define CERTIFICATE_BASIC_CONSTRAINTS            "CA:FALSE"
54 #define CERTIFICATE_SUBJECT_KEY                  "hash"
55 #define CERTIFICATE_AUTHORITY_KEY                "keyid:always"
56 #define CERTIFICATE_ALT_NAME_PREFIX              "DNS:"
57 #define CERTIFICATE_VERSION                      2
58 #define VALID_DATETIME_FMT                       "%Y%m%d%H%M%SZ"
59 #define VALID_DATETIME_BUFLEN                    16
60
61 static int generate_webpage_certificate(struct client_state *csp);
62 static void free_client_ssl_structures(struct client_state *csp);
63 static void free_server_ssl_structures(struct client_state *csp);
64 static int ssl_store_cert(struct client_state *csp, X509* crt);
65 static void log_ssl_errors(int debuglevel, const char* fmt, ...) __attribute__((format(printf, 2, 3)));
66
67 static int ssl_inited = 0;
68
69 #if OPENSSL_VERSION_NUMBER < 0x10100000L
70 #define X509_set1_notBefore X509_set_notBefore
71 #define X509_set1_notAfter X509_set_notAfter
72 #define X509_get0_serialNumber X509_get_serialNumber
73 #define X509_get0_notBefore X509_get_notBefore
74 #define X509_get0_notAfter X509_get_notAfter
75 #endif
76
77 /*********************************************************************
78  *
79  * Function    :  openssl_init
80  *
81  * Description :  Initializes OpenSSL library once
82  *
83  * Parameters  :  N/A
84  *
85  * Returns     :  N/A
86  *
87  *********************************************************************/
88 static void openssl_init(void)
89 {
90    if (ssl_inited == 0)
91    {
92       privoxy_mutex_lock(&ssl_init_mutex);
93       if (ssl_inited == 0)
94       {
95 #if OPENSSL_VERSION_NUMBER < 0x10100000L
96          SSL_library_init();
97 #else
98          OPENSSL_init_ssl(0, NULL);
99 #endif
100          SSL_load_error_strings();
101          OpenSSL_add_ssl_algorithms();
102          ssl_inited = 1;
103       }
104       privoxy_mutex_unlock(&ssl_init_mutex);
105    }
106 }
107
108
109 /*********************************************************************
110  *
111  * Function    :  is_ssl_pending
112  *
113  * Description :  Tests if there are some waiting data on ssl connection.
114  *                Only considers data that has actually been received
115  *                locally and ignores data that is still on the fly
116  *                or has not yet been sent by the remote end.
117  *
118  * Parameters  :
119  *          1  :  ssl_attr = SSL context to test
120  *
121  * Returns     :   0 => No data are pending
122  *                >0 => Pending data length
123  *
124  *********************************************************************/
125 extern size_t is_ssl_pending(struct ssl_attr *ssl_attr)
126 {
127    BIO *bio = ssl_attr->openssl_attr.bio;
128    if (bio == NULL)
129    {
130       return 0;
131    }
132
133    return (size_t)BIO_pending(bio);
134 }
135
136
137 /*********************************************************************
138  *
139  * Function    :  ssl_send_data
140  *
141  * Description :  Sends the content of buf (for n bytes) to given SSL
142  *                connection context.
143  *
144  * Parameters  :
145  *          1  :  ssl_attr = SSL context to send data to
146  *          2  :  buf = Pointer to data to be sent
147  *          3  :  len = Length of data to be sent to the SSL context
148  *
149  * Returns     :  Length of sent data or negative value on error.
150  *
151  *********************************************************************/
152 extern int ssl_send_data(struct ssl_attr *ssl_attr, const unsigned char *buf, size_t len)
153 {
154    BIO *bio = ssl_attr->openssl_attr.bio;
155    int ret = 0;
156    int pos = 0; /* Position of unsent part in buffer */
157
158    if (len == 0)
159    {
160       return 0;
161    }
162
163    while (pos < len)
164    {
165       int send_len = (int)len - pos;
166
167       log_error(LOG_LEVEL_WRITING, "TLS: %N", send_len, buf+pos);
168
169       /*
170        * Sending one part of the buffer
171        */
172       while ((ret = BIO_write(bio,
173          (const unsigned char *)(buf + pos),
174          send_len)) < 0)
175       {
176          if (!BIO_should_retry(bio))
177          {
178             log_ssl_errors(LOG_LEVEL_ERROR,
179                "Sending data over TLS/SSL failed");
180             return -1;
181          }
182       }
183       /* Adding count of sent bytes to position in buffer */
184       pos = pos + ret;
185    }
186
187    return (int)len;
188 }
189
190
191 /*********************************************************************
192  *
193  * Function    :  ssl_recv_data
194  *
195  * Description :  Receives data from given SSL context and puts
196  *                it into buffer.
197  *
198  * Parameters  :
199  *          1  :  ssl_attr = SSL context to receive data from
200  *          2  :  buf = Pointer to buffer where data will be written
201  *          3  :  max_length = Maximum number of bytes to read
202  *
203  * Returns     :  Number of bytes read, 0 for EOF, or -1
204  *                on error.
205  *
206  *********************************************************************/
207 extern int ssl_recv_data(struct ssl_attr *ssl_attr, unsigned char *buf, size_t max_length)
208 {
209    BIO *bio = ssl_attr->openssl_attr.bio;
210    int ret = 0;
211    memset(buf, 0, max_length);
212
213    /*
214     * Receiving data from SSL context into buffer
215     */
216    do
217    {
218       ret = BIO_read(bio, buf, (int)max_length);
219    } while (ret <= 0 && BIO_should_retry(bio));
220
221    if (ret < 0)
222    {
223       log_ssl_errors(LOG_LEVEL_ERROR,
224          "Receiving data over TLS/SSL failed");
225
226       return -1;
227    }
228
229    log_error(LOG_LEVEL_RECEIVED, "TLS: %N", ret, buf);
230
231    return ret;
232 }
233
234
235 /*********************************************************************
236  *
237  * Function    :  ssl_store_cert
238  *
239  * Description :  This is a callback function for certificate verification.
240  *                It's called once for each certificate in the server's
241  *                certificate trusted chain and prepares information about
242  *                the certificate. The information can be used to inform
243  *                the user about invalid certificates.
244  *
245  * Parameters  :
246  *          1  :  csp = Current client state (buffers, headers, etc...)
247  *          2  :  crt   = certificate from trusted chain
248  *
249  * Returns     :  0 on success and negative value on error
250  *
251  *********************************************************************/
252 static int ssl_store_cert(struct client_state *csp, X509* crt)
253 {
254    long len = 0;
255    struct certs_chain  *last = &(csp->server_certs_chain);
256    int ret = 0;
257    BIO *bio = BIO_new(BIO_s_mem());
258    EVP_PKEY *pkey = NULL;
259    char *bio_mem_data = 0;
260    char *encoded_text;
261    long l;
262    const ASN1_INTEGER *bs;
263 #if OPENSSL_VERSION_NUMBER > 0x10100000L
264    const X509_ALGOR *tsig_alg;
265 #endif
266    int loc;
267
268    if (!bio)
269    {
270       log_ssl_errors(LOG_LEVEL_ERROR, "BIO_new_mem_buf() failed");
271       return -1;
272    }
273
274    /*
275     * Searching for last item in certificates linked list
276     */
277    while (last->next != NULL)
278    {
279       last = last->next;
280    }
281
282    /*
283     * Preparing next item in linked list for next certificate
284     */
285    last->next = malloc_or_die(sizeof(struct certs_chain));
286    last->next->next = NULL;
287    memset(last->next->info_buf, 0, sizeof(last->next->info_buf));
288    memset(last->next->file_buf, 0, sizeof(last->next->file_buf));
289
290    /*
291     * Saving certificate file into buffer
292     */
293    if (!PEM_write_bio_X509(bio, crt))
294    {
295       log_ssl_errors(LOG_LEVEL_ERROR, "PEM_write_X509() failed");
296       ret = -1;
297       goto exit;
298    }
299
300    len = BIO_get_mem_data(bio, &bio_mem_data);
301
302    if (len > (sizeof(last->file_buf) - 1))
303    {
304       log_error(LOG_LEVEL_ERROR,
305          "X509 PEM cert len %d is larger then buffer len %s",
306          len, sizeof(last->file_buf) - 1);
307       len = sizeof(last->file_buf) - 1;
308    }
309
310    strncpy(last->file_buf, bio_mem_data, (size_t)len);
311    BIO_free(bio);
312    bio = BIO_new(BIO_s_mem());
313    if (!bio)
314    {
315       log_ssl_errors(LOG_LEVEL_ERROR, "BIO_new_mem_buf() failed");
316       ret = -1;
317       goto exit;
318    }
319
320    /*
321     * Saving certificate information into buffer
322     */
323    l = X509_get_version(crt);
324    if (l >= 0 && l <= 2)
325    {
326       if (BIO_printf(bio, "cert. version     : %ld\n", l + 1) <= 0)
327       {
328          log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for version failed");
329          ret = -1;
330          goto exit;
331       }
332    }
333    else
334    {
335       if (BIO_printf(bio, "cert. version     : Unknown (%ld)\n", l) <= 0)
336       {
337          log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for version failed");
338          ret = -1;
339          goto exit;
340       }
341    }
342
343    if (BIO_puts(bio, "serial number     : ") <= 0)
344    {
345       log_ssl_errors(LOG_LEVEL_ERROR, "BIO_write() for serial failed");
346       ret = -1;
347       goto exit;
348    }
349    bs = X509_get0_serialNumber(crt);
350    if (bs->length <= (int)sizeof(long))
351    {
352       ERR_set_mark();
353       l = ASN1_INTEGER_get(bs);
354       ERR_pop_to_mark();
355    }
356    else
357    {
358       l = -1;
359    }
360    if (l != -1)
361    {
362       unsigned long ul;
363       const char *neg;
364       if (bs->type == V_ASN1_NEG_INTEGER)
365       {
366          ul = 0 - (unsigned long)l;
367          neg = "-";
368       }
369       else
370       {
371          ul = (unsigned long)l;
372          neg = "";
373       }
374       if (BIO_printf(bio, " %s%lu (%s0x%lx)\n", neg, ul, neg, ul) <= 0)
375       {
376          log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for serial failed");
377          ret = -1;
378          goto exit;
379       }
380    }
381    else
382    {
383       if (bs->type == V_ASN1_NEG_INTEGER)
384       {
385          if (BIO_puts(bio, " (Negative)") < 0)
386          {
387             log_ssl_errors(LOG_LEVEL_ERROR, "BIO_puts() for serial failed");
388             ret = -1;
389             goto exit;
390          }
391       }
392       for (int i = 0; i < bs->length; i++)
393       {
394          if (BIO_printf(bio, "%02x%c", bs->data[i],
395                ((i + 1 == bs->length) ? '\n' : ':')) <= 0)
396          {
397             log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for serial failed");
398             ret = -1;
399             goto exit;
400          }
401       }
402    }
403
404    if (BIO_puts(bio, "issuer name       : ") <= 0)
405    {
406       log_ssl_errors(LOG_LEVEL_ERROR, "BIO_puts() for issuer failed");
407       ret = -1;
408       goto exit;
409    }
410    if (X509_NAME_print_ex(bio, X509_get_issuer_name(crt), 0, 0) < 0)
411    {
412       log_ssl_errors(LOG_LEVEL_ERROR, "X509_NAME_print_ex() for issuer failed");
413       ret = -1;
414       goto exit;
415    }
416
417    if (BIO_puts(bio, "\nsubject name      : ") <= 0)
418    {
419       log_ssl_errors(LOG_LEVEL_ERROR, "BIO_puts() for subject failed");
420       ret = -1;
421       goto exit;
422    }
423    if (X509_NAME_print_ex(bio, X509_get_subject_name(crt), 0, 0) < 0) {
424       log_ssl_errors(LOG_LEVEL_ERROR, "X509_NAME_print_ex() for subject failed");
425       ret = -1;
426       goto exit;
427    }
428
429    if (BIO_puts(bio, "\nissued  on        : ") <= 0)
430    {
431       log_ssl_errors(LOG_LEVEL_ERROR, "BIO_puts() for issued on failed");
432       ret = -1;
433       goto exit;
434    }
435    if (!ASN1_TIME_print(bio, X509_get0_notBefore(crt)))
436    {
437       log_ssl_errors(LOG_LEVEL_ERROR, "ASN1_TIME_print() for issued on failed");
438       ret = -1;
439       goto exit;
440    }
441
442    if (BIO_puts(bio, "\nexpires on        : ") <= 0)
443    {
444       log_ssl_errors(LOG_LEVEL_ERROR, "BIO_puts() for expires on failed");
445       ret = -1;
446       goto exit;
447    }
448    if (!ASN1_TIME_print(bio, X509_get0_notAfter(crt)))
449    {
450       log_ssl_errors(LOG_LEVEL_ERROR, "ASN1_TIME_print() for expires on failed");
451       ret = -1;
452       goto exit;
453    }
454
455 #if OPENSSL_VERSION_NUMBER > 0x10100000L
456    if (BIO_puts(bio, "\nsigned using      : ") <= 0)
457    {
458       log_ssl_errors(LOG_LEVEL_ERROR, "BIO_puts() for signed using failed");
459       ret = -1;
460       goto exit;
461    }
462    tsig_alg = X509_get0_tbs_sigalg(crt);
463    if (!i2a_ASN1_OBJECT(bio, tsig_alg->algorithm))
464    {
465       log_ssl_errors(LOG_LEVEL_ERROR, "i2a_ASN1_OBJECT() for signed using on failed");
466       ret = -1;
467       goto exit;
468    }
469 #endif
470    pkey = X509_get_pubkey(crt);
471    if (!pkey)
472    {
473       log_ssl_errors(LOG_LEVEL_ERROR, "X509_get_pubkey() failed");
474       ret = -1;
475       goto exit;
476    }
477 #define BC              "18"
478    switch (EVP_PKEY_base_id(pkey))
479    {
480       case EVP_PKEY_RSA:
481          ret = BIO_printf(bio, "\n%-" BC "s: %d bits", "RSA key size", EVP_PKEY_bits(pkey));
482          break;
483       case EVP_PKEY_DSA:
484          ret = BIO_printf(bio, "\n%-" BC "s: %d bits", "DSA key size", EVP_PKEY_bits(pkey));
485          break;
486       default:
487          ret = BIO_printf(bio, "\n%-" BC "s: %d bits", "non-RSA/DSA key size", EVP_PKEY_bits(pkey));
488          break;
489    }
490    if (ret <= 0)
491    {
492       log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for key size failed");
493       ret = -1;
494       goto exit;
495    }
496
497    loc = X509_get_ext_by_NID(crt, NID_basic_constraints, -1);
498    if (loc != -1)
499    {
500       X509_EXTENSION *ex = X509_get_ext(crt, loc);
501       if (BIO_puts(bio, "\nbasic constraints : ") <= 0)
502       {
503          log_ssl_errors(LOG_LEVEL_ERROR,
504             "BIO_printf() for basic constraints failed");
505          ret = -1;
506          goto exit;
507       }
508       if (!X509V3_EXT_print(bio, ex, 0, 0))
509       {
510          if (!ASN1_STRING_print_ex(bio, X509_EXTENSION_get_data(ex), ASN1_STRFLGS_RFC2253))
511          {
512             log_ssl_errors(LOG_LEVEL_ERROR,
513                "ASN1_STRING_print_ex() for basic constraints failed");
514             ret = -1;
515             goto exit;
516          }
517       }
518    }
519
520    loc = X509_get_ext_by_NID(crt, NID_subject_alt_name, -1);
521    if (loc != -1)
522    {
523       X509_EXTENSION *ex = X509_get_ext(crt, loc);
524       if (BIO_puts(bio, "\nsubject alt name  : ") <= 0)
525       {
526          log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for alt name failed");
527          ret = -1;
528          goto exit;
529       }
530       if (!X509V3_EXT_print(bio, ex, 0, 0))
531       {
532          if (!ASN1_STRING_print_ex(bio, X509_EXTENSION_get_data(ex),
533                ASN1_STRFLGS_RFC2253))
534          {
535             log_ssl_errors(LOG_LEVEL_ERROR,
536                "ASN1_STRING_print_ex() for alt name failed");
537             ret = -1;
538             goto exit;
539          }
540       }
541    }
542
543    loc = X509_get_ext_by_NID(crt, NID_netscape_cert_type, -1);
544    if (loc != -1)
545    {
546       X509_EXTENSION *ex = X509_get_ext(crt, loc);
547       if (BIO_puts(bio, "\ncert. type        : ") <= 0)
548       {
549          log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for cert type failed");
550          ret = -1;
551          goto exit;
552       }
553       if (!X509V3_EXT_print(bio, ex, 0, 0))
554       {
555          if (!ASN1_STRING_print_ex(bio, X509_EXTENSION_get_data(ex),
556                ASN1_STRFLGS_RFC2253))
557          {
558             log_ssl_errors(LOG_LEVEL_ERROR,
559                "ASN1_STRING_print_ex() for cert type failed");
560             ret = -1;
561             goto exit;
562          }
563       }
564    }
565
566    loc = X509_get_ext_by_NID(crt, NID_key_usage, -1);
567    if (loc != -1)
568    {
569       X509_EXTENSION *ex = X509_get_ext(crt, loc);
570       if (BIO_puts(bio, "\nkey usage         : ") <= 0)
571       {
572          log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for key usage failed");
573          ret = -1;
574          goto exit;
575       }
576       if (!X509V3_EXT_print(bio, ex, 0, 0))
577       {
578          if (!ASN1_STRING_print_ex(bio, X509_EXTENSION_get_data(ex),
579                ASN1_STRFLGS_RFC2253))
580          {
581             log_ssl_errors(LOG_LEVEL_ERROR,
582                "ASN1_STRING_print_ex() for key usage failed");
583             ret = -1;
584             goto exit;
585          }
586       }
587    }
588
589    loc = X509_get_ext_by_NID(crt, NID_ext_key_usage, -1);
590    if (loc != -1) {
591       X509_EXTENSION *ex = X509_get_ext(crt, loc);
592       if (BIO_puts(bio, "\next key usage     : ") <= 0)
593       {
594          log_ssl_errors(LOG_LEVEL_ERROR,
595             "BIO_printf() for ext key usage failed");
596          ret = -1;
597          goto exit;
598       }
599       if (!X509V3_EXT_print(bio, ex, 0, 0))
600       {
601          if (!ASN1_STRING_print_ex(bio, X509_EXTENSION_get_data(ex),
602                ASN1_STRFLGS_RFC2253))
603          {
604             log_ssl_errors(LOG_LEVEL_ERROR,
605                "ASN1_STRING_print_ex() for ext key usage failed");
606             ret = -1;
607             goto exit;
608          }
609       }
610    }
611
612    loc = X509_get_ext_by_NID(crt, NID_certificate_policies, -1);
613    if (loc != -1)
614    {
615       X509_EXTENSION *ex = X509_get_ext(crt, loc);
616       if (BIO_puts(bio, "\ncertificate policies : ") <= 0)
617       {
618          log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for certificate policies failed");
619          ret = -1;
620          goto exit;
621       }
622       if (!X509V3_EXT_print(bio, ex, 0, 0))
623       {
624          if (!ASN1_STRING_print_ex(bio, X509_EXTENSION_get_data(ex),
625                ASN1_STRFLGS_RFC2253))
626          {
627             log_ssl_errors(LOG_LEVEL_ERROR,
628                "ASN1_STRING_print_ex() for certificate policies failed");
629             ret = -1;
630             goto exit;
631          }
632       }
633    }
634
635    /* make valgrind happy */
636    static const char zero = 0;
637    BIO_write(bio, &zero, 1);
638
639    len = BIO_get_mem_data(bio, &bio_mem_data);
640    encoded_text = html_encode(bio_mem_data);
641    strlcpy(last->info_buf, encoded_text, sizeof(last->info_buf));
642    freez(encoded_text);
643    ret = 0;
644
645 exit:
646    if (bio)
647    {
648       BIO_free(bio);
649    }
650    if (pkey)
651    {
652       EVP_PKEY_free(pkey);
653    }
654    return ret;
655 }
656
657
658 /*********************************************************************
659  *
660  * Function    :  host_to_hash
661  *
662  * Description :  Creates MD5 hash from host name. Host name is loaded
663  *                from structure csp and saved again into it.
664  *
665  * Parameters  :
666  *          1  :  csp = Current client state (buffers, headers, etc...)
667  *
668  * Returns     :  1 => Error while creating hash
669  *                0 => Hash created successfully
670  *
671  *********************************************************************/
672 static int host_to_hash(struct client_state *csp)
673 {
674    int ret = 0;
675
676    memset(csp->http->hash_of_host, 0, sizeof(csp->http->hash_of_host));
677    MD5((unsigned char *)csp->http->host, strlen(csp->http->host),
678       csp->http->hash_of_host);
679
680    /* Converting hash into string with hex */
681    size_t i = 0;
682    for (; i < 16; i++)
683    {
684       if ((ret = sprintf((char *)csp->http->hash_of_host_hex + 2 * i, "%02x",
685          csp->http->hash_of_host[i])) < 0)
686       {
687          log_error(LOG_LEVEL_ERROR, "Sprintf return value: %d", ret);
688          return -1;
689       }
690    }
691
692    return 0;
693 }
694
695
696 /*********************************************************************
697  *
698  * Function    :  create_client_ssl_connection
699  *
700  * Description :  Creates TLS/SSL secured connection with client
701  *
702  * Parameters  :
703  *          1  :  csp = Current client state (buffers, headers, etc...)
704  *
705  * Returns     :  0 on success, negative value if connection wasn't created
706  *                successfully.
707  *
708  *********************************************************************/
709 extern int create_client_ssl_connection(struct client_state *csp)
710 {
711    struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
712    /* Paths to certificates file and key file */
713    char *key_file  = NULL;
714    char *ca_file   = NULL;
715    char *cert_file = NULL;
716    int ret = 0;
717    SSL* ssl;
718
719    /*
720     * Initializing OpenSSL structures for TLS/SSL connection
721     */
722    openssl_init();
723
724    /*
725     * Preparing hash of host for creating certificates
726     */
727    ret = host_to_hash(csp);
728    if (ret != 0)
729    {
730       log_error(LOG_LEVEL_ERROR, "Generating hash of host failed: %d", ret);
731       ret = -1;
732       goto exit;
733    }
734
735    /*
736     * Preparing paths to certificates files and key file
737     */
738    ca_file   = csp->config->ca_cert_file;
739    cert_file = make_certs_path(csp->config->certificate_directory,
740       (const char *)csp->http->hash_of_host_hex, CERT_FILE_TYPE);
741    key_file  = make_certs_path(csp->config->certificate_directory,
742       (const char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
743
744    if (cert_file == NULL || key_file == NULL)
745    {
746       ret = -1;
747       goto exit;
748    }
749
750    /*
751     * Generating certificate for requested host. Mutex to prevent
752     * certificate and key inconsistence must be locked.
753     */
754    privoxy_mutex_lock(&certificate_mutex);
755
756    ret = generate_webpage_certificate(csp);
757    if (ret < 0)
758    {
759       log_error(LOG_LEVEL_ERROR,
760          "Generate_webpage_certificate failed: %d", ret);
761       privoxy_mutex_unlock(&certificate_mutex);
762       ret = -1;
763       goto exit;
764    }
765    privoxy_mutex_unlock(&certificate_mutex);
766
767    if (!(ssl_attr->openssl_attr.ctx = SSL_CTX_new(SSLv23_server_method())))
768    {
769       log_ssl_errors(LOG_LEVEL_ERROR, "Unable to create SSL context");
770       ret = -1;
771       goto exit;
772    }
773
774    /* Set the key and cert */
775    if (SSL_CTX_use_certificate_file(ssl_attr->openssl_attr.ctx,
776          cert_file, SSL_FILETYPE_PEM) != 1)
777    {
778       log_ssl_errors(LOG_LEVEL_ERROR,
779          "Loading webpage certificate %s failed", cert_file);
780       ret = -1;
781       goto exit;
782    }
783
784    if (SSL_CTX_use_PrivateKey_file(ssl_attr->openssl_attr.ctx,
785          key_file, SSL_FILETYPE_PEM) != 1)
786    {
787       log_ssl_errors(LOG_LEVEL_ERROR,
788          "Loading webpage certificate private key %s failed", key_file);
789       ret = -1;
790       goto exit;
791    }
792
793    SSL_CTX_set_options(ssl_attr->openssl_attr.ctx, SSL_OP_NO_SSLv3);
794
795    if (!(ssl_attr->openssl_attr.bio = BIO_new_ssl(ssl_attr->openssl_attr.ctx, 0)))
796    {
797       log_ssl_errors(LOG_LEVEL_ERROR, "Unable to create BIO structure");
798       ret = -1;
799       goto exit;
800    }
801
802    if (BIO_get_ssl(ssl_attr->openssl_attr.bio, &ssl) != 1)
803    {
804       log_ssl_errors(LOG_LEVEL_ERROR, "BIO_get_ssl failed");
805       ret = -1;
806       goto exit;
807    }
808
809    if (!SSL_set_fd(ssl, csp->cfd))
810    {
811       log_ssl_errors(LOG_LEVEL_ERROR, "SSL_set_fd failed");
812       ret = -1;
813       goto exit;
814    }
815
816    /*
817     *  Handshake with client
818     */
819    log_error(LOG_LEVEL_CONNECT,
820       "Performing the TLS/SSL handshake with client. Hash of host: %s",
821       csp->http->hash_of_host_hex);
822    if (BIO_do_handshake(ssl_attr->openssl_attr.bio) != 1)
823    {
824        log_ssl_errors(LOG_LEVEL_ERROR, "BIO_do_handshake failed");
825        ret = -1;
826        goto exit;
827    }
828
829    log_error(LOG_LEVEL_CONNECT, "Client successfully connected over TLS/SSL");
830    csp->ssl_with_client_is_opened = 1;
831    ret = 0;
832
833 exit:
834    /*
835     * Freeing allocated paths to files
836     */
837    freez(cert_file);
838    freez(key_file);
839
840    /* Freeing structures if connection wasn't created successfully */
841    if (ret < 0)
842    {
843       free_client_ssl_structures(csp);
844    }
845    return ret;
846 }
847
848
849 /*********************************************************************
850  *
851  * Function    :  close_client_ssl_connection
852  *
853  * Description :  Closes TLS/SSL connection with client. This function
854  *                checks if this connection is already created.
855  *
856  * Parameters  :
857  *          1  :  csp = Current client state (buffers, headers, etc...)
858  *
859  * Returns     :  N/A
860  *
861  *********************************************************************/
862 extern void close_client_ssl_connection(struct client_state *csp)
863 {
864    struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
865
866    if (csp->ssl_with_client_is_opened == 0)
867    {
868       return;
869    }
870
871    /*
872     * Notifying the peer that the connection is being closed.
873     */
874    BIO_ssl_shutdown(ssl_attr->openssl_attr.bio);
875    free_client_ssl_structures(csp);
876    csp->ssl_with_client_is_opened = 0;
877 }
878
879
880 /*********************************************************************
881  *
882  * Function    :  free_client_ssl_structures
883  *
884  * Description :  Frees structures used for SSL communication with
885  *                client.
886  *
887  * Parameters  :
888  *          1  :  csp = Current client state (buffers, headers, etc...)
889  *
890  * Returns     :  N/A
891  *
892  *********************************************************************/
893 static void free_client_ssl_structures(struct client_state *csp)
894 {
895    struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
896
897    if (ssl_attr->openssl_attr.bio)
898    {
899       BIO_free_all(ssl_attr->openssl_attr.bio);
900    }
901    if (ssl_attr->openssl_attr.ctx)
902    {
903       SSL_CTX_free(ssl_attr->openssl_attr.ctx);
904    }
905 }
906
907
908 /*********************************************************************
909  *
910  * Function    :  close_server_ssl_connection
911  *
912  * Description :  Closes TLS/SSL connection with server. This function
913  *                checks if this connection is already opened.
914  *
915  * Parameters  :
916  *          1  :  csp = Current client state (buffers, headers, etc...)
917  *
918  * Returns     :  N/A
919  *
920  *********************************************************************/
921 extern void close_server_ssl_connection(struct client_state *csp)
922 {
923    struct ssl_attr *ssl_attr = &csp->ssl_server_attr;
924
925    if (csp->ssl_with_server_is_opened == 0)
926    {
927       return;
928    }
929
930    /*
931    * Notifying the peer that the connection is being closed.
932    */
933    BIO_ssl_shutdown(ssl_attr->openssl_attr.bio);
934    free_server_ssl_structures(csp);
935    csp->ssl_with_server_is_opened = 0;
936 }
937
938
939 /*********************************************************************
940  *
941  * Function    :  create_server_ssl_connection
942  *
943  * Description :  Creates TLS/SSL secured connection with server.
944  *
945  * Parameters  :
946  *          1  :  csp = Current client state (buffers, headers, etc...)
947  *
948  * Returns     :  0 on success, negative value if connection wasn't created
949  *                successfully.
950  *
951  *********************************************************************/
952 extern int create_server_ssl_connection(struct client_state *csp)
953 {
954    openssl_connection_attr *ssl_attrs = &csp->ssl_server_attr.openssl_attr;
955    int ret = 0;
956    char *trusted_cas_file = NULL;
957    STACK_OF(X509) *chain;
958    SSL *ssl;
959
960    csp->server_cert_verification_result = SSL_CERT_NOT_VERIFIED;
961    csp->server_certs_chain.next = NULL;
962
963    /* Setting path to file with trusted CAs */
964    trusted_cas_file = csp->config->trusted_cas_file;
965
966    ssl_attrs->ctx = SSL_CTX_new(SSLv23_method());
967    if (!ssl_attrs->ctx)
968    {
969       log_ssl_errors(LOG_LEVEL_ERROR, "SSL context creation failed");
970       ret = -1;
971       goto exit;
972    }
973
974    /*
975     * Loading file with trusted CAs
976     */
977    if (!SSL_CTX_load_verify_locations(ssl_attrs->ctx, trusted_cas_file, NULL))
978    {
979       log_ssl_errors(LOG_LEVEL_ERROR, "Loading trusted CAs file %s failed",
980          trusted_cas_file);
981       ret = -1;
982       goto exit;
983    }
984
985    SSL_CTX_set_verify(ssl_attrs->ctx, SSL_VERIFY_NONE, NULL);
986    SSL_CTX_set_options(ssl_attrs->ctx, SSL_OP_NO_SSLv3);
987
988    if (!(ssl_attrs->bio = BIO_new_ssl(ssl_attrs->ctx, 1)))
989    {
990       log_ssl_errors(LOG_LEVEL_ERROR, "Unable to create BIO structure");
991       ret = -1;
992       goto exit;
993    }
994
995    if (BIO_get_ssl(ssl_attrs->bio, &ssl) != 1)
996    {
997       log_ssl_errors(LOG_LEVEL_ERROR, "BIO_get_ssl failed");
998       ret = -1;
999       goto exit;
1000    }
1001
1002    if (!SSL_set_fd(ssl, csp->server_connection.sfd))
1003    {
1004       log_ssl_errors(LOG_LEVEL_ERROR, "SSL_set_fd failed");
1005       ret = -1;
1006       goto exit;
1007    }
1008
1009    /*
1010     * Set the hostname to check against the received server certificate
1011     */
1012 #if OPENSSL_VERSION_NUMBER > 0x10100000L
1013    if (!SSL_set1_host(ssl, csp->http->host))
1014    {
1015       log_ssl_errors(LOG_LEVEL_ERROR, "SSL_set1_host failed");
1016       ret = -1;
1017       goto exit;
1018    }
1019 #else
1020    if (host_is_ip_address(csp->http->host))
1021    {
1022       if (X509_VERIFY_PARAM_set1_ip_asc(ssl->param,  csp->http->host) != 1)
1023       {
1024          log_ssl_errors(LOG_LEVEL_ERROR,
1025             "X509_VERIFY_PARAM_set1_ip_asc() failed");
1026          ret = -1;
1027          goto exit;
1028       }
1029    }
1030    else
1031    {
1032       if (X509_VERIFY_PARAM_set1_host(ssl->param,  csp->http->host, 0) != 1)
1033       {
1034          log_ssl_errors(LOG_LEVEL_ERROR,
1035             "X509_VERIFY_PARAM_set1_host() failed");
1036          ret = -1;
1037          goto exit;
1038       }
1039    }
1040 #endif
1041    /* SNI extension */
1042    if (!SSL_set_tlsext_host_name(ssl, csp->http->host))
1043    {
1044       log_ssl_errors(LOG_LEVEL_ERROR, "SSL_set_tlsext_host_name failed");
1045       ret = -1;
1046       goto exit;
1047    }
1048
1049    /*
1050     * Handshake with server
1051     */
1052    log_error(LOG_LEVEL_CONNECT,
1053       "Performing the TLS/SSL handshake with the server");
1054
1055    if (BIO_do_handshake(ssl_attrs->bio) != 1)
1056    {
1057       log_ssl_errors(LOG_LEVEL_ERROR, "BIO_do_handshake failed");
1058       ret = -1;
1059       goto exit;
1060    }
1061
1062    chain = SSL_get_peer_cert_chain(ssl);
1063    if (chain)
1064    {
1065       for (int i = 0; i < sk_X509_num(chain); i++)
1066       {
1067          if (ssl_store_cert(csp, sk_X509_value(chain, i)) != 0)
1068          {
1069             log_error(LOG_LEVEL_ERROR, "ssl_store_cert failed");
1070             ret = -1;
1071             goto exit;
1072          }
1073       }
1074    }
1075
1076    if (!csp->dont_verify_certificate)
1077    {
1078       long verify_result = SSL_get_verify_result(ssl);
1079       if (verify_result == X509_V_OK)
1080       {
1081          ret = 0;
1082          csp->server_cert_verification_result = SSL_CERT_VALID;
1083       }
1084       else
1085       {
1086          csp->server_cert_verification_result = verify_result;
1087          log_error(LOG_LEVEL_ERROR, "SSL_get_verify_result failed: %s",
1088             X509_verify_cert_error_string(verify_result));
1089          ret = -1;
1090          goto exit;
1091       }
1092    }
1093
1094    log_error(LOG_LEVEL_CONNECT, "Server successfully connected over TLS/SSL");
1095
1096    /*
1097     * Server certificate chain is valid, so we can clean
1098     * chain, because we will not send it to client.
1099     */
1100    free_certificate_chain(csp);
1101
1102    csp->ssl_with_server_is_opened = 1;
1103 exit:
1104    /* Freeing structures if connection wasn't created successfully */
1105    if (ret < 0)
1106    {
1107       free_server_ssl_structures(csp);
1108    }
1109
1110    return ret;
1111 }
1112
1113
1114 /*********************************************************************
1115  *
1116  * Function    :  free_server_ssl_structures
1117  *
1118  * Description :  Frees structures used for SSL communication with server
1119  *
1120  * Parameters  :
1121  *          1  :  csp = Current client state (buffers, headers, etc...)
1122  *
1123  * Returns     :  N/A
1124  *
1125  *********************************************************************/
1126 static void free_server_ssl_structures(struct client_state *csp)
1127 {
1128    struct ssl_attr *ssl_attr = &csp->ssl_server_attr;
1129
1130    if (ssl_attr->openssl_attr.bio)
1131    {
1132       BIO_free_all(ssl_attr->openssl_attr.bio);
1133    }
1134    if (ssl_attr->openssl_attr.ctx)
1135    {
1136       SSL_CTX_free(ssl_attr->openssl_attr.ctx);
1137    }
1138 }
1139
1140
1141 /*********************************************************************
1142  *
1143  * Function    :  log_ssl_errors
1144  *
1145  * Description :  Log SSL errors
1146  *
1147  * Parameters  :
1148  *          1  :  debuglevel = Debug level
1149  *          2  :  desc = Error description
1150  *
1151  * Returns     :  N/A
1152  *
1153  *********************************************************************/
1154 static void log_ssl_errors(int debuglevel, const char* fmt, ...)
1155 {
1156    unsigned long err_code;
1157    char prefix[ERROR_BUF_SIZE];
1158    va_list args;
1159    va_start(args, fmt);
1160    vsnprintf(prefix, sizeof(prefix), fmt, args);
1161    int reported = 0;
1162
1163    while ((err_code = ERR_get_error()))
1164    {
1165       char err_buf[ERROR_BUF_SIZE];
1166       reported = 1;
1167       ERR_error_string_n(err_code, err_buf, sizeof(err_buf));
1168       log_error(debuglevel, "%s: %s", prefix, err_buf);
1169    }
1170    va_end(args);
1171    /*
1172     * In case if called by mistake and there were
1173     * no TLS/SSL errors let's report it to the log.
1174     */
1175    if (!reported)
1176    {
1177       log_error(debuglevel, "%s: no TLS/SSL errors detected", prefix);
1178    }
1179 }
1180
1181
1182 /*********************************************************************
1183  *
1184  * Function    :  ssl_base64_encode
1185  *
1186  * Description :  Encode a buffer into base64 format.
1187  *
1188  * Parameters  :
1189  *          1  :  dst = Destination buffer
1190  *          2  :  dlen = Destination buffer length
1191  *          3  :  olen = Number of bytes written
1192  *          4  :  src = Source buffer
1193  *          5  :  slen = Amount of data to be encoded
1194  *
1195  * Returns     :  0 on success, error code othervise
1196  *
1197  *********************************************************************/
1198 extern int ssl_base64_encode(unsigned char *dst, size_t dlen, size_t *olen,
1199                              const unsigned char *src, size_t slen)
1200 {
1201    *olen = 4 * ((slen/3)  + ((slen%3) ? 1 : 0)) + 1;
1202    if (*olen < dlen)
1203    {
1204       return ENOBUFS;
1205    }
1206    *olen = (size_t)EVP_EncodeBlock(dst, src, (int)slen) + 1;
1207    return 0;
1208 }
1209
1210
1211 /*********************************************************************
1212  *
1213  * Function    :  close_file_stream
1214  *
1215  * Description :  Close file stream, report error on close error
1216  *
1217  * Parameters  :
1218  *          1  :  f = file stream to close
1219  *          2  :  path = path for error report
1220  *
1221  * Returns     :  N/A
1222  *
1223  *********************************************************************/
1224 static void close_file_stream(FILE *f, const char *path)
1225 {
1226    if (fclose(f) != 0)
1227    {
1228       log_error(LOG_LEVEL_ERROR,
1229          "Error closing file %s: %s", path, strerror(errno));
1230    }
1231 }
1232
1233
1234 /*********************************************************************
1235  *
1236  * Function    :  write_certificate
1237  *
1238  * Description :  Writes certificate into file.
1239  *
1240  * Parameters  :
1241  *          1  :  crt = certificate to write into file
1242  *          2  :  output_file = path to save certificate file
1243  *
1244  *                on error
1245  * Returns     :  1 on success success or negative value
1246  *
1247  *********************************************************************/
1248 static int write_certificate(X509 *crt, const char *output_file)
1249 {
1250    FILE *f = NULL;
1251    int ret = -1;
1252
1253    /*
1254     * Saving certificate into file
1255     */
1256    if ((f = fopen(output_file, "w")) == NULL)
1257    {
1258       log_error(LOG_LEVEL_ERROR, "Opening file %s to save certificate failed",
1259          output_file);
1260       return ret;
1261    }
1262
1263    ret = PEM_write_X509(f, crt);
1264    if (!ret)
1265    {
1266       log_ssl_errors(LOG_LEVEL_ERROR,
1267          "Writing certificate into file %s failed", output_file);
1268       ret = -1;
1269    }
1270
1271    close_file_stream(f, output_file);
1272
1273    return ret;
1274 }
1275
1276 /*********************************************************************
1277  *
1278  * Function    :  write_private_key
1279  *
1280  * Description :  Writes private key into file and copies saved
1281  *                content into given pointer to string. If function
1282  *                returns 0 for success, this copy must be freed by
1283  *                caller.
1284  *
1285  * Parameters  :
1286  *          1  :  key = key to write into file
1287  *          2  :  ret_buf = pointer to string with created key file content
1288  *          3  :  key_file_path = path where to save key file
1289  *
1290  * Returns     :  Length of written private key on success or negative value
1291  *                on error
1292  *
1293  *********************************************************************/
1294 static int write_private_key(EVP_PKEY *key, char **ret_buf,
1295                              const char *key_file_path)
1296 {
1297    size_t len = 0;                /* Length of created key    */
1298    FILE *f = NULL;                /* File to save certificate */
1299    int ret = 0;
1300    BIO *bio_mem = BIO_new(BIO_s_mem());
1301    char *bio_mem_data = 0;
1302
1303    if (bio_mem == NULL)
1304    {
1305       log_ssl_errors(LOG_LEVEL_ERROR, "write_private_key memory allocation failure");
1306       return -1;
1307    }
1308
1309    /*
1310     * Writing private key into PEM string
1311     */
1312    if (!PEM_write_bio_PrivateKey(bio_mem, key, NULL, NULL, 0, NULL, NULL))
1313    {
1314       log_ssl_errors(LOG_LEVEL_ERROR,
1315          "Writing private key into PEM string failed");
1316       ret = -1;
1317       goto exit;
1318    }
1319
1320    len = (size_t)BIO_get_mem_data(bio_mem, &bio_mem_data);
1321
1322    /* Initializing buffer for key file content */
1323    *ret_buf = zalloc_or_die(len + 1);
1324    (*ret_buf)[len] = 0;
1325
1326    strncpy(*ret_buf, bio_mem_data, len);
1327
1328    /*
1329     * Saving key into file
1330     */
1331    if ((f = fopen(key_file_path, "wb")) == NULL)
1332    {
1333       log_error(LOG_LEVEL_ERROR,
1334          "Opening file %s to save private key failed: %E",
1335          key_file_path);
1336       ret = -1;
1337       goto exit;
1338    }
1339
1340    if (fwrite(*ret_buf, 1, len, f) != len)
1341    {
1342       log_error(LOG_LEVEL_ERROR,
1343          "Writing private key into file %s failed",
1344          key_file_path);
1345       close_file_stream(f, key_file_path);
1346       ret = -1;
1347       goto exit;
1348    }
1349
1350    close_file_stream(f, key_file_path);
1351
1352 exit:
1353    BIO_free(bio_mem);
1354    if (ret < 0)
1355    {
1356       freez(*ret_buf);
1357       *ret_buf = NULL;
1358       return ret;
1359    }
1360    return (int)len;
1361 }
1362
1363
1364 /*********************************************************************
1365  *
1366  * Function    :  generate_key
1367  *
1368  * Description : Tests if private key for host saved in csp already
1369  *               exists.  If this file doesn't exists, a new key is
1370  *               generated and saved in a file. The generated key is also
1371  *               copied into given parameter key_buf, which must be then
1372  *               freed by caller. If file with key exists, key_buf
1373  *               contain NULL and no private key is generated.
1374  *
1375  * Parameters  :
1376  *          1  :  csp = Current client state (buffers, headers, etc...)
1377  *          2  :  key_buf = buffer to save new generated key
1378  *
1379  * Returns     :  -1 => Error while generating private key
1380  *                 0 => Key already exists
1381  *                >0 => Length of generated private key
1382  *
1383  *********************************************************************/
1384 static int generate_key(struct client_state *csp, char **key_buf)
1385 {
1386    int ret = 0;
1387    char* key_file_path = NULL;
1388    BIGNUM *exp = BN_new();
1389    RSA *rsa = RSA_new();
1390    EVP_PKEY *key = EVP_PKEY_new();
1391
1392    if (exp == NULL || rsa == NULL || key == NULL)
1393    {
1394       log_ssl_errors(LOG_LEVEL_ERROR, "RSA key memory allocation failure");
1395       ret = -1;
1396       goto exit;
1397    }
1398
1399    BN_set_word(exp, RSA_KEY_PUBLIC_EXPONENT);
1400
1401    key_file_path = make_certs_path(csp->config->certificate_directory,
1402       (char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
1403    if (key_file_path == NULL)
1404    {
1405       ret = -1;
1406       goto exit;
1407    }
1408
1409    /*
1410     * Test if key already exists. If so, we don't have to create it again.
1411     */
1412    if (file_exists(key_file_path) == 1)
1413    {
1414       ret = 0;
1415       goto exit;
1416    }
1417
1418    ret = RSA_generate_key_ex(rsa, RSA_KEYSIZE, exp, NULL);
1419    if (ret == 0)
1420    {
1421       log_ssl_errors(LOG_LEVEL_ERROR, "RSA key generation failure");
1422       ret = -1;
1423       goto exit;
1424    }
1425
1426    if (!EVP_PKEY_set1_RSA(key, rsa))
1427    {
1428       log_ssl_errors(LOG_LEVEL_ERROR,
1429          "Error assigning RSA key pair to PKEY structure");
1430       ret = -1;
1431       goto exit;
1432    }
1433
1434    /*
1435     * Exporting private key into file
1436     */
1437    if ((ret = write_private_key(key, key_buf, key_file_path)) < 0)
1438    {
1439       log_error(LOG_LEVEL_ERROR,
1440          "Writing private key into file %s failed", key_file_path);
1441       ret = -1;
1442       goto exit;
1443    }
1444
1445 exit:
1446    /*
1447     * Freeing used variables
1448     */
1449    if (exp)
1450    {
1451       BN_free(exp);
1452    }
1453    if (rsa)
1454    {
1455       RSA_free(rsa);
1456    }
1457    if (key)
1458    {
1459       EVP_PKEY_free(key);
1460    }
1461    freez(key_file_path);
1462
1463    return ret;
1464 }
1465
1466
1467 /*********************************************************************
1468  *
1469  * Function    :  ssl_certificate_load
1470  *
1471  * Description :  Loads certificate from file.
1472  *
1473  * Parameters  :
1474  *          1  :  cert_path = The certificate path to load
1475  *
1476  * Returns     :   NULL => error loading certificate,
1477  *                   pointer to certificate instance otherwise
1478  *
1479  *********************************************************************/
1480 static X509* ssl_certificate_load(const char *cert_path)
1481 {
1482    X509 *cert = NULL;
1483    FILE *cert_f = NULL;
1484
1485    if (!(cert_f = fopen(cert_path, "r")))
1486    {
1487       log_error(LOG_LEVEL_ERROR,
1488          "Error opening certificate file %s: %s", cert_path, strerror(errno));
1489       return NULL;
1490    }
1491
1492    if (!(cert = PEM_read_X509(cert_f, NULL, NULL, NULL)))
1493    {
1494       log_ssl_errors(LOG_LEVEL_ERROR,
1495          "Error reading certificate file %s", cert_path);
1496    }
1497
1498    close_file_stream(cert_f, cert_path);
1499    return cert;
1500 }
1501
1502
1503 /*********************************************************************
1504  *
1505  * Function    :  ssl_certificate_is_invalid
1506  *
1507  * Description :  Checks whether or not a certificate is valid.
1508  *                Currently only checks that the certificate can be
1509  *                parsed and that the "valid to" date is in the future.
1510  *
1511  * Parameters  :
1512  *          1  :  cert_file = The certificate to check
1513  *
1514  * Returns     :   0 => The certificate is valid.
1515  *                 1 => The certificate is invalid
1516  *
1517  *********************************************************************/
1518 static int ssl_certificate_is_invalid(const char *cert_file)
1519 {
1520    int ret;
1521
1522    X509 *cert = NULL;
1523
1524    if (!(cert = ssl_certificate_load(cert_file)))
1525    {
1526       log_ssl_errors(LOG_LEVEL_ERROR,
1527          "Error reading certificate file %s", cert_file);
1528       return 1;
1529    }
1530
1531    ret = X509_cmp_current_time(X509_get_notAfter(cert));
1532    if (ret == 0)
1533    {
1534       log_ssl_errors(LOG_LEVEL_ERROR,
1535          "Error checking certificate %s validity", cert_file);
1536    }
1537
1538    X509_free(cert);
1539
1540    return ret == -1 ? 1 : 0;
1541 }
1542
1543
1544 /*********************************************************************
1545  *
1546  * Function    :  set_x509_ext
1547  *
1548  * Description :  Sets the X509V3 extension data
1549  *
1550  * Parameters  :
1551  *          1  :  cert = The certificate to modify
1552  *          2  :  issuer = Issuer certificate
1553  *          3  :  nid = OpenSSL NID
1554  *          4  :  value = extension value
1555  *
1556  * Returns     :   0 => Error while setting extensuon data
1557  *                 1 => It worked
1558  *
1559  *********************************************************************/
1560 static int set_x509_ext(X509 *cert, X509 *issuer, int nid, char *value)
1561 {
1562    X509_EXTENSION *ext = NULL;
1563    X509V3_CTX ctx;
1564    int ret = 0;
1565
1566    X509V3_set_ctx(&ctx, issuer, cert, NULL, NULL, 0);
1567    ext = X509V3_EXT_conf_nid(NULL, &ctx, nid, value);
1568    if (!ext)
1569    {
1570       log_ssl_errors(LOG_LEVEL_ERROR, "X509V3_EXT_conf_nid failure");
1571       goto exit;
1572    }
1573
1574    if (!X509_add_ext(cert, ext, -1))
1575    {
1576       log_ssl_errors(LOG_LEVEL_ERROR, "X509_add_ext failure");
1577       goto exit;
1578    }
1579
1580    ret = 1;
1581 exit:
1582    if (ext)
1583    {
1584       X509_EXTENSION_free(ext);
1585    }
1586    return ret;
1587 }
1588
1589
1590 /*********************************************************************
1591  *
1592  * Function    :  set_subject_alternative_name
1593  *
1594  * Description :  Sets the Subject Alternative Name extension to a cert
1595  *
1596  * Parameters  :
1597  *          1  :  cert = The certificate to modify
1598  *          2  :  issuer = Issuer certificate
1599  *          3  :  hostname = The hostname to add
1600  *
1601  * Returns     :   0 => Error while creating certificate.
1602  *                 1 => It worked
1603  *
1604  *********************************************************************/
1605 static int set_subject_alternative_name(X509 *cert, X509 *issuer, const char *hostname)
1606 {
1607    size_t altname_len = strlen(hostname) + sizeof(CERTIFICATE_ALT_NAME_PREFIX);
1608    char alt_name_buf[altname_len];
1609
1610    snprintf(alt_name_buf, sizeof(alt_name_buf),
1611       CERTIFICATE_ALT_NAME_PREFIX"%s", hostname);
1612    return set_x509_ext(cert, issuer, NID_subject_alt_name, alt_name_buf);
1613 }
1614
1615
1616 /*********************************************************************
1617  *
1618  * Function    :  generate_webpage_certificate
1619  *
1620  * Description :  Creates certificate file in presetted directory.
1621  *                If certificate already exists, no other certificate
1622  *                will be created. Subject of certificate is named
1623  *                by csp->http->host from parameter. This function also
1624  *                triggers generating of private key for new certificate.
1625  *
1626  * Parameters  :
1627  *          1  :  csp = Current client state (buffers, headers, etc...)
1628  *
1629  * Returns     :  -1 => Error while creating certificate.
1630  *                 0 => Certificate already exists.
1631  *                 1 => Certificate created
1632  *
1633  *********************************************************************/
1634 static int generate_webpage_certificate(struct client_state *csp)
1635 {
1636    char *key_buf = NULL;    /* Buffer for created key */
1637    X509 *issuer_cert = NULL;
1638    X509 *cert = NULL;
1639    BIO *pk_bio = NULL;
1640    EVP_PKEY *loaded_subject_key = NULL;
1641    EVP_PKEY *loaded_issuer_key = NULL;
1642    X509_NAME *issuer_name;
1643    X509_NAME *subject_name = NULL;
1644    ASN1_TIME *asn_time = NULL;
1645    ASN1_INTEGER *serial = NULL;
1646    BIGNUM *serial_num = NULL;
1647
1648    int ret = 0;
1649    cert_options cert_opt;
1650    char cert_valid_from[VALID_DATETIME_BUFLEN];
1651    char cert_valid_to[VALID_DATETIME_BUFLEN];
1652
1653    /* Paths to keys and certificates needed to create certificate */
1654    cert_opt.issuer_key  = NULL;
1655    cert_opt.subject_key = NULL;
1656    cert_opt.issuer_crt  = NULL;
1657
1658    cert_opt.output_file = make_certs_path(csp->config->certificate_directory,
1659       (const char *)csp->http->hash_of_host_hex, CERT_FILE_TYPE);
1660    if (cert_opt.output_file == NULL)
1661    {
1662       return -1;
1663    }
1664
1665    cert_opt.subject_key = make_certs_path(csp->config->certificate_directory,
1666       (const char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
1667    if (cert_opt.subject_key == NULL)
1668    {
1669       freez(cert_opt.output_file);
1670       return -1;
1671    }
1672
1673    if (file_exists(cert_opt.output_file) == 1)
1674    {
1675       /* The file exists, but is it valid? */
1676       if (ssl_certificate_is_invalid(cert_opt.output_file))
1677       {
1678          log_error(LOG_LEVEL_CONNECT,
1679             "Certificate %s is no longer valid. Removing it.",
1680             cert_opt.output_file);
1681          if (unlink(cert_opt.output_file))
1682          {
1683             log_error(LOG_LEVEL_ERROR, "Failed to unlink %s: %E",
1684                cert_opt.output_file);
1685
1686             freez(cert_opt.output_file);
1687             freez(cert_opt.subject_key);
1688
1689             return -1;
1690          }
1691          if (unlink(cert_opt.subject_key))
1692          {
1693             log_error(LOG_LEVEL_ERROR, "Failed to unlink %s: %E",
1694                cert_opt.subject_key);
1695
1696             freez(cert_opt.output_file);
1697             freez(cert_opt.subject_key);
1698
1699             return -1;
1700          }
1701       }
1702       else
1703       {
1704          freez(cert_opt.output_file);
1705          freez(cert_opt.subject_key);
1706
1707          return 0;
1708       }
1709    }
1710
1711    /*
1712     * Create key for requested host
1713     */
1714    int subject_key_len = generate_key(csp, &key_buf);
1715    if (subject_key_len < 0)
1716    {
1717       freez(cert_opt.output_file);
1718       freez(cert_opt.subject_key);
1719       log_error(LOG_LEVEL_ERROR, "Key generating failed");
1720       return -1;
1721    }
1722
1723    /*
1724     * Converting unsigned long serial number to char * serial number.
1725     * We must compute length of serial number in string + terminating null.
1726     */
1727    unsigned long certificate_serial = get_certificate_serial(csp);
1728    unsigned long certificate_serial_time = (unsigned long)time(NULL);
1729    int serial_num_size = snprintf(NULL, 0, "%lu%lu",
1730       certificate_serial_time, certificate_serial) + 1;
1731    if (serial_num_size <= 0)
1732    {
1733       serial_num_size = 1;
1734    }
1735
1736    char serial_num_text[serial_num_size];  /* Buffer for serial number */
1737    ret = snprintf(serial_num_text, (size_t)serial_num_size, "%lu%lu",
1738       certificate_serial_time, certificate_serial);
1739    if (ret < 0 || ret >= serial_num_size)
1740    {
1741       log_error(LOG_LEVEL_ERROR,
1742          "Converting certificate serial number into string failed");
1743       ret = -1;
1744       goto exit;
1745    }
1746
1747    /*
1748     * Preparing parameters for certificate
1749     */
1750    subject_name = X509_NAME_new();
1751    if (!subject_name)
1752    {
1753       log_ssl_errors(LOG_LEVEL_ERROR, "RSA key memory allocation failure");
1754       ret = -1;
1755       goto exit;
1756    }
1757
1758    if (!X509_NAME_add_entry_by_txt(subject_name, CERT_PARAM_COMMON_NAME_FCODE,
1759          MBSTRING_ASC, (void *)csp->http->host, -1, -1, 0))
1760    {
1761       log_ssl_errors(LOG_LEVEL_ERROR,
1762          "X509 subject name (code: %s, val: %s) error",
1763          CERT_PARAM_COMMON_NAME_FCODE, csp->http->host);
1764       ret = -1;
1765       goto exit;
1766    }
1767    if (!X509_NAME_add_entry_by_txt(subject_name, CERT_PARAM_ORGANIZATION_FCODE,
1768          MBSTRING_ASC, (void *)csp->http->host, -1, -1, 0))
1769    {
1770       log_ssl_errors(LOG_LEVEL_ERROR,
1771          "X509 subject name (code: %s, val: %s) error",
1772          CERT_PARAM_COMMON_NAME_FCODE, csp->http->host);
1773       ret = -1;
1774       goto exit;
1775    }
1776    if (!X509_NAME_add_entry_by_txt(subject_name, CERT_PARAM_ORG_UNIT_FCODE,
1777          MBSTRING_ASC, (void *)csp->http->host, -1, -1, 0))
1778    {
1779       log_ssl_errors(LOG_LEVEL_ERROR,
1780          "X509 subject name (code: %s, val: %s) error",
1781          CERT_PARAM_COMMON_NAME_FCODE, csp->http->host);
1782       ret = -1;
1783       goto exit;
1784    }
1785    if (!X509_NAME_add_entry_by_txt(subject_name, CERT_PARAM_COUNTRY_FCODE,
1786          MBSTRING_ASC, (void *)CERT_PARAM_COUNTRY_CODE, -1, -1, 0))
1787    {
1788       log_ssl_errors(LOG_LEVEL_ERROR,
1789          "X509 subject name (code: %s, val: %s) error",
1790          CERT_PARAM_COMMON_NAME_FCODE, csp->http->host);
1791       ret = -1;
1792       goto exit;
1793    }
1794
1795    cert_opt.issuer_crt = csp->config->ca_cert_file;
1796    cert_opt.issuer_key = csp->config->ca_key_file;
1797
1798    if (get_certificate_valid_from_date(cert_valid_from,
1799          sizeof(cert_valid_from), VALID_DATETIME_FMT)
1800     || get_certificate_valid_to_date(cert_valid_to,
1801          sizeof(cert_valid_to), VALID_DATETIME_FMT))
1802    {
1803       log_error(LOG_LEVEL_ERROR, "Generating one of the validity dates failed");
1804       ret = -1;
1805       goto exit;
1806    }
1807
1808    cert_opt.subject_pwd = CERT_SUBJECT_PASSWORD;
1809    cert_opt.issuer_pwd  = csp->config->ca_password;
1810    cert_opt.not_before  = cert_valid_from;
1811    cert_opt.not_after   = cert_valid_to;
1812    cert_opt.serial      = serial_num_text;
1813    cert_opt.max_pathlen = -1;
1814
1815    /*
1816     * Test if the private key was already created.
1817     * XXX: Can this still happen?
1818     */
1819    if (subject_key_len == 0)
1820    {
1821       log_error(LOG_LEVEL_ERROR, "Subject key was already created");
1822       ret = 0;
1823       goto exit;
1824    }
1825
1826    /*
1827     * Parse serial to MPI
1828     */
1829    serial_num = BN_new();
1830    if (!serial_num)
1831    {
1832       log_error(LOG_LEVEL_ERROR, "generate_webpage_certificate: memory error");
1833       ret = -1;
1834       goto exit;
1835    }
1836    if (!BN_dec2bn(&serial_num, cert_opt.serial))
1837    {
1838       log_ssl_errors(LOG_LEVEL_ERROR, "Failed to parse serial %s", cert_opt.serial);
1839       ret = -1;
1840       goto exit;
1841    }
1842
1843    if (!(serial = BN_to_ASN1_INTEGER(serial_num, NULL)))
1844    {
1845       log_ssl_errors(LOG_LEVEL_ERROR, "Failed to generate serial ASN1 representation");
1846       ret = -1;
1847       goto exit;
1848    }
1849
1850    /*
1851     * Loading certificates
1852     */
1853    if (!(issuer_cert = ssl_certificate_load(cert_opt.issuer_crt)))
1854    {
1855       log_error(LOG_LEVEL_ERROR, "Loading issuer certificate %s failed",
1856          cert_opt.issuer_crt);
1857       ret = -1;
1858       goto exit;
1859    }
1860
1861    issuer_name = X509_get_issuer_name(issuer_cert);
1862
1863    /*
1864     * Loading keys from file or from buffer
1865     */
1866    if (key_buf != NULL && subject_key_len > 0)
1867    {
1868       pk_bio = BIO_new_mem_buf(key_buf, subject_key_len);
1869    }
1870    else if (!(pk_bio = BIO_new_file(cert_opt.subject_key, "r")))
1871    {
1872       log_ssl_errors(LOG_LEVEL_ERROR,
1873          "Failure opening subject key %s BIO", cert_opt.subject_key);
1874       ret = -1;
1875       goto exit;
1876    }
1877
1878    loaded_subject_key = PEM_read_bio_PrivateKey(pk_bio, NULL, NULL,
1879       (void *)cert_opt.subject_pwd);
1880    if (!loaded_subject_key)
1881    {
1882       log_ssl_errors(LOG_LEVEL_ERROR, "Parsing subject key %s failed",
1883          cert_opt.subject_key);
1884       ret = -1;
1885       goto exit;
1886    }
1887
1888    if (!BIO_free(pk_bio))
1889    {
1890       log_ssl_errors(LOG_LEVEL_ERROR, "Error closing subject key BIO");
1891    }
1892
1893    if (!(pk_bio = BIO_new_file(cert_opt.issuer_key, "r")))
1894    {
1895       log_ssl_errors(LOG_LEVEL_ERROR, "Failure opening issuer key %s BIO",
1896          cert_opt.issuer_key);
1897       ret = -1;
1898       goto exit;
1899    }
1900
1901    loaded_issuer_key = PEM_read_bio_PrivateKey(pk_bio, NULL, NULL,
1902       (void *)cert_opt.issuer_pwd);
1903    if (!loaded_issuer_key)
1904    {
1905       log_ssl_errors(LOG_LEVEL_ERROR, "Parsing issuer key %s failed",
1906          cert_opt.subject_key);
1907       ret = -1;
1908       goto exit;
1909    }
1910
1911    cert = X509_new();
1912    if (!cert)
1913    {
1914       log_ssl_errors(LOG_LEVEL_ERROR, "Certificate allocation error");
1915       ret = -1;
1916       goto exit;
1917    }
1918
1919    if (!X509_set_version(cert, CERTIFICATE_VERSION))
1920    {
1921       log_ssl_errors(LOG_LEVEL_ERROR, "X509_set_version failed");
1922       ret = -1;
1923       goto exit;
1924    }
1925
1926    /*
1927     * Setting parameters of signed certificate
1928     */
1929    if (!X509_set_pubkey(cert, loaded_subject_key))
1930    {
1931       log_ssl_errors(LOG_LEVEL_ERROR,
1932          "Setting issuer name in signed certificate failed");
1933       ret = -1;
1934       goto exit;
1935    }
1936
1937    if (!X509_set_subject_name(cert, subject_name))
1938    {
1939       log_ssl_errors(LOG_LEVEL_ERROR,
1940          "Setting issuer name in signed certificate failed");
1941       ret = -1;
1942       goto exit;
1943    }
1944
1945    if (!X509_set_issuer_name(cert, issuer_name))
1946    {
1947       log_ssl_errors(LOG_LEVEL_ERROR,
1948          "Setting issuer name in signed certificate failed");
1949       ret = -1;
1950       goto exit;
1951    }
1952
1953    if (!X509_set_serialNumber(cert, serial))
1954    {
1955       log_ssl_errors(LOG_LEVEL_ERROR,
1956          "Setting serial number in signed certificate failed");
1957       ret = -1;
1958       goto exit;
1959    }
1960
1961    asn_time = ASN1_TIME_new();
1962    if (!asn_time)
1963    {
1964       log_ssl_errors(LOG_LEVEL_ERROR, "ASN1 time memory allocation failure");
1965       ret = -1;
1966       goto exit;
1967    }
1968
1969    if (!ASN1_TIME_set_string(asn_time, cert_opt.not_after))
1970    {
1971       log_ssl_errors(LOG_LEVEL_ERROR, "ASN1 time [%s] encode error", cert_opt.not_after);
1972       ret = -1;
1973       goto exit;
1974    }
1975
1976    if (!X509_set1_notAfter(cert, asn_time))
1977    {
1978       log_ssl_errors(LOG_LEVEL_ERROR,
1979          "Setting valid not after in signed certificate failed");
1980       ret = -1;
1981       goto exit;
1982    }
1983
1984    if (!ASN1_TIME_set_string(asn_time, cert_opt.not_before))
1985    {
1986       log_ssl_errors(LOG_LEVEL_ERROR, "ASN1 time encode error");
1987       ret = -1;
1988       goto exit;
1989    }
1990
1991    if (!X509_set1_notBefore(cert, asn_time))
1992    {
1993       log_ssl_errors(LOG_LEVEL_ERROR,
1994          "Setting valid not befre in signed certificate failed");
1995       ret = -1;
1996       goto exit;
1997    }
1998
1999    if (!set_x509_ext(cert, issuer_cert, NID_basic_constraints, CERTIFICATE_BASIC_CONSTRAINTS))
2000    {
2001       log_ssl_errors(LOG_LEVEL_ERROR, "Setting the basicConstraints extension "
2002          "in signed certificate failed");
2003       ret = -1;
2004       goto exit;
2005    }
2006
2007    if (!set_x509_ext(cert, issuer_cert, NID_subject_key_identifier, CERTIFICATE_SUBJECT_KEY))
2008    {
2009       log_ssl_errors(LOG_LEVEL_ERROR,
2010          "Setting the Subject Key Identifie extension failed");
2011       ret = -1;
2012       goto exit;
2013    }
2014
2015    if (!set_x509_ext(cert, issuer_cert, NID_authority_key_identifier, CERTIFICATE_AUTHORITY_KEY))
2016    {
2017       log_ssl_errors(LOG_LEVEL_ERROR,
2018          "Setting the Authority Key Identifier extension failed");
2019       ret = -1;
2020       goto exit;
2021    }
2022
2023    if (!host_is_ip_address(csp->http->host) &&
2024        !set_subject_alternative_name(cert, issuer_cert, csp->http->host))
2025    {
2026       log_ssl_errors(LOG_LEVEL_ERROR, "Setting the Subject Alt Nameextension failed");
2027       ret = -1;
2028       goto exit;
2029    }
2030
2031    if (!X509_sign(cert, loaded_issuer_key, EVP_sha256()))
2032    {
2033       log_ssl_errors(LOG_LEVEL_ERROR, "Signing certificate failed");
2034       ret = -1;
2035       goto exit;
2036    }
2037
2038    /*
2039     * Writing certificate into file
2040     */
2041    if (write_certificate(cert, cert_opt.output_file) < 0)
2042    {
2043       log_error(LOG_LEVEL_ERROR, "Writing certificate into file failed");
2044       ret = -1;
2045       goto exit;
2046    }
2047
2048    ret = 1;
2049
2050 exit:
2051    /*
2052     * Freeing used structures
2053     */
2054    if (issuer_cert)
2055    {
2056       X509_free(issuer_cert);
2057    }
2058    if (cert)
2059    {
2060       X509_free(cert);
2061    }
2062    if (pk_bio && !BIO_free(pk_bio))
2063    {
2064       log_ssl_errors(LOG_LEVEL_ERROR, "Error closing pk BIO");
2065    }
2066    if (loaded_subject_key)
2067    {
2068       EVP_PKEY_free(loaded_subject_key);
2069    }
2070    if (loaded_issuer_key)
2071    {
2072       EVP_PKEY_free(loaded_issuer_key);
2073    }
2074    if (subject_name)
2075    {
2076       X509_NAME_free(subject_name);
2077    }
2078    if (asn_time)
2079    {
2080       ASN1_TIME_free(asn_time);
2081    }
2082    if (serial_num)
2083    {
2084       BN_free(serial_num);
2085    }
2086    if (serial)
2087    {
2088       ASN1_INTEGER_free(serial);
2089    }
2090    freez(cert_opt.subject_key);
2091    freez(cert_opt.output_file);
2092    freez(key_buf);
2093
2094    return ret;
2095 }
2096
2097
2098 /*********************************************************************
2099  *
2100  * Function    :  ssl_crt_verify_info
2101  *
2102  * Description :  Returns an informational string about the verification
2103  *                status of a certificate.
2104  *
2105  * Parameters  :
2106  *          1  :  buf = Buffer to write to
2107  *          2  :  size = Maximum size of buffer
2108  *          3  :  csp = client state
2109  *
2110  * Returns     :  N/A
2111  *
2112  *********************************************************************/
2113 extern void ssl_crt_verify_info(char *buf, size_t size, struct client_state *csp)
2114 {
2115    strncpy(buf, X509_verify_cert_error_string(csp->server_cert_verification_result), size);
2116    buf[size - 1] = 0;
2117 }
2118
2119
2120 /*********************************************************************
2121  *
2122  * Function    :  ssl_release
2123  *
2124  * Description :  Release all SSL resources
2125  *
2126  * Parameters  :
2127  *
2128  * Returns     :  N/A
2129  *
2130  *********************************************************************/
2131 extern void ssl_release(void)
2132 {
2133    if (ssl_inited == 1)
2134    {
2135       SSL_COMP_free_compression_methods();
2136
2137       CONF_modules_free();
2138       CONF_modules_unload(1);
2139
2140       COMP_zlib_cleanup();
2141
2142       ERR_free_strings();
2143       EVP_cleanup();
2144
2145       CRYPTO_cleanup_all_ex_data();
2146    }
2147 }
2148