723820bf0d0c6579933fa3ae4eb91d8c1197c2df
[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    if (encoded_text == NULL)
642    {
643       log_error(LOG_LEVEL_ERROR,
644          "Failed to HTML-encode the certificate information");
645       ret = -1;
646       goto exit;
647    }
648
649    strlcpy(last->info_buf, encoded_text, sizeof(last->info_buf));
650    freez(encoded_text);
651    ret = 0;
652
653 exit:
654    if (bio)
655    {
656       BIO_free(bio);
657    }
658    if (pkey)
659    {
660       EVP_PKEY_free(pkey);
661    }
662    return ret;
663 }
664
665
666 /*********************************************************************
667  *
668  * Function    :  host_to_hash
669  *
670  * Description :  Creates MD5 hash from host name. Host name is loaded
671  *                from structure csp and saved again into it.
672  *
673  * Parameters  :
674  *          1  :  csp = Current client state (buffers, headers, etc...)
675  *
676  * Returns     :  1 => Error while creating hash
677  *                0 => Hash created successfully
678  *
679  *********************************************************************/
680 static int host_to_hash(struct client_state *csp)
681 {
682    int ret = 0;
683
684    memset(csp->http->hash_of_host, 0, sizeof(csp->http->hash_of_host));
685    MD5((unsigned char *)csp->http->host, strlen(csp->http->host),
686       csp->http->hash_of_host);
687
688    /* Converting hash into string with hex */
689    size_t i = 0;
690    for (; i < 16; i++)
691    {
692       if ((ret = sprintf((char *)csp->http->hash_of_host_hex + 2 * i, "%02x",
693          csp->http->hash_of_host[i])) < 0)
694       {
695          log_error(LOG_LEVEL_ERROR, "Sprintf return value: %d", ret);
696          return -1;
697       }
698    }
699
700    return 0;
701 }
702
703
704 /*********************************************************************
705  *
706  * Function    :  create_client_ssl_connection
707  *
708  * Description :  Creates TLS/SSL secured connection with client
709  *
710  * Parameters  :
711  *          1  :  csp = Current client state (buffers, headers, etc...)
712  *
713  * Returns     :  0 on success, negative value if connection wasn't created
714  *                successfully.
715  *
716  *********************************************************************/
717 extern int create_client_ssl_connection(struct client_state *csp)
718 {
719    struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
720    /* Paths to certificates file and key file */
721    char *key_file  = NULL;
722    char *ca_file   = NULL;
723    char *cert_file = NULL;
724    int ret = 0;
725    SSL* ssl;
726
727    /*
728     * Initializing OpenSSL structures for TLS/SSL connection
729     */
730    openssl_init();
731
732    /*
733     * Preparing hash of host for creating certificates
734     */
735    ret = host_to_hash(csp);
736    if (ret != 0)
737    {
738       log_error(LOG_LEVEL_ERROR, "Generating hash of host failed: %d", ret);
739       ret = -1;
740       goto exit;
741    }
742
743    /*
744     * Preparing paths to certificates files and key file
745     */
746    ca_file   = csp->config->ca_cert_file;
747    cert_file = make_certs_path(csp->config->certificate_directory,
748       (const char *)csp->http->hash_of_host_hex, CERT_FILE_TYPE);
749    key_file  = make_certs_path(csp->config->certificate_directory,
750       (const char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
751
752    if (cert_file == NULL || key_file == NULL)
753    {
754       ret = -1;
755       goto exit;
756    }
757
758    /*
759     * Generating certificate for requested host. Mutex to prevent
760     * certificate and key inconsistence must be locked.
761     */
762    privoxy_mutex_lock(&certificate_mutex);
763
764    ret = generate_webpage_certificate(csp);
765    if (ret < 0)
766    {
767       log_error(LOG_LEVEL_ERROR,
768          "Generate_webpage_certificate failed: %d", ret);
769       privoxy_mutex_unlock(&certificate_mutex);
770       ret = -1;
771       goto exit;
772    }
773    privoxy_mutex_unlock(&certificate_mutex);
774
775    if (!(ssl_attr->openssl_attr.ctx = SSL_CTX_new(SSLv23_server_method())))
776    {
777       log_ssl_errors(LOG_LEVEL_ERROR, "Unable to create SSL context");
778       ret = -1;
779       goto exit;
780    }
781
782    /* Set the key and cert */
783    if (SSL_CTX_use_certificate_file(ssl_attr->openssl_attr.ctx,
784          cert_file, SSL_FILETYPE_PEM) != 1)
785    {
786       log_ssl_errors(LOG_LEVEL_ERROR,
787          "Loading webpage certificate %s failed", cert_file);
788       ret = -1;
789       goto exit;
790    }
791
792    if (SSL_CTX_use_PrivateKey_file(ssl_attr->openssl_attr.ctx,
793          key_file, SSL_FILETYPE_PEM) != 1)
794    {
795       log_ssl_errors(LOG_LEVEL_ERROR,
796          "Loading webpage certificate private key %s failed", key_file);
797       ret = -1;
798       goto exit;
799    }
800
801    SSL_CTX_set_options(ssl_attr->openssl_attr.ctx, SSL_OP_NO_SSLv3);
802
803    if (!(ssl_attr->openssl_attr.bio = BIO_new_ssl(ssl_attr->openssl_attr.ctx, 0)))
804    {
805       log_ssl_errors(LOG_LEVEL_ERROR, "Unable to create BIO structure");
806       ret = -1;
807       goto exit;
808    }
809
810    if (BIO_get_ssl(ssl_attr->openssl_attr.bio, &ssl) != 1)
811    {
812       log_ssl_errors(LOG_LEVEL_ERROR, "BIO_get_ssl failed");
813       ret = -1;
814       goto exit;
815    }
816
817    if (!SSL_set_fd(ssl, csp->cfd))
818    {
819       log_ssl_errors(LOG_LEVEL_ERROR, "SSL_set_fd failed");
820       ret = -1;
821       goto exit;
822    }
823
824    /*
825     *  Handshake with client
826     */
827    log_error(LOG_LEVEL_CONNECT,
828       "Performing the TLS/SSL handshake with client. Hash of host: %s",
829       csp->http->hash_of_host_hex);
830    if (BIO_do_handshake(ssl_attr->openssl_attr.bio) != 1)
831    {
832        log_ssl_errors(LOG_LEVEL_ERROR,
833           "The TLS/SSL handshake with the client failed");
834        ret = -1;
835        goto exit;
836    }
837
838    log_error(LOG_LEVEL_CONNECT, "Client successfully connected over TLS/SSL");
839    csp->ssl_with_client_is_opened = 1;
840    ret = 0;
841
842 exit:
843    /*
844     * Freeing allocated paths to files
845     */
846    freez(cert_file);
847    freez(key_file);
848
849    /* Freeing structures if connection wasn't created successfully */
850    if (ret < 0)
851    {
852       free_client_ssl_structures(csp);
853    }
854    return ret;
855 }
856
857
858 /*********************************************************************
859  *
860  * Function    :  close_client_ssl_connection
861  *
862  * Description :  Closes TLS/SSL connection with client. This function
863  *                checks if this connection is already created.
864  *
865  * Parameters  :
866  *          1  :  csp = Current client state (buffers, headers, etc...)
867  *
868  * Returns     :  N/A
869  *
870  *********************************************************************/
871 extern void close_client_ssl_connection(struct client_state *csp)
872 {
873    struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
874
875    if (csp->ssl_with_client_is_opened == 0)
876    {
877       return;
878    }
879
880    /*
881     * Notifying the peer that the connection is being closed.
882     */
883    BIO_ssl_shutdown(ssl_attr->openssl_attr.bio);
884    free_client_ssl_structures(csp);
885    csp->ssl_with_client_is_opened = 0;
886 }
887
888
889 /*********************************************************************
890  *
891  * Function    :  free_client_ssl_structures
892  *
893  * Description :  Frees structures used for SSL communication with
894  *                client.
895  *
896  * Parameters  :
897  *          1  :  csp = Current client state (buffers, headers, etc...)
898  *
899  * Returns     :  N/A
900  *
901  *********************************************************************/
902 static void free_client_ssl_structures(struct client_state *csp)
903 {
904    struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
905
906    if (ssl_attr->openssl_attr.bio)
907    {
908       BIO_free_all(ssl_attr->openssl_attr.bio);
909    }
910    if (ssl_attr->openssl_attr.ctx)
911    {
912       SSL_CTX_free(ssl_attr->openssl_attr.ctx);
913    }
914 }
915
916
917 /*********************************************************************
918  *
919  * Function    :  close_server_ssl_connection
920  *
921  * Description :  Closes TLS/SSL connection with server. This function
922  *                checks if this connection is already opened.
923  *
924  * Parameters  :
925  *          1  :  csp = Current client state (buffers, headers, etc...)
926  *
927  * Returns     :  N/A
928  *
929  *********************************************************************/
930 extern void close_server_ssl_connection(struct client_state *csp)
931 {
932    struct ssl_attr *ssl_attr = &csp->ssl_server_attr;
933
934    if (csp->ssl_with_server_is_opened == 0)
935    {
936       return;
937    }
938
939    /*
940    * Notifying the peer that the connection is being closed.
941    */
942    BIO_ssl_shutdown(ssl_attr->openssl_attr.bio);
943    free_server_ssl_structures(csp);
944    csp->ssl_with_server_is_opened = 0;
945 }
946
947
948 /*********************************************************************
949  *
950  * Function    :  create_server_ssl_connection
951  *
952  * Description :  Creates TLS/SSL secured connection with server.
953  *
954  * Parameters  :
955  *          1  :  csp = Current client state (buffers, headers, etc...)
956  *
957  * Returns     :  0 on success, negative value if connection wasn't created
958  *                successfully.
959  *
960  *********************************************************************/
961 extern int create_server_ssl_connection(struct client_state *csp)
962 {
963    openssl_connection_attr *ssl_attrs = &csp->ssl_server_attr.openssl_attr;
964    int ret = 0;
965    char *trusted_cas_file = NULL;
966    STACK_OF(X509) *chain;
967    SSL *ssl;
968
969    csp->server_cert_verification_result = SSL_CERT_NOT_VERIFIED;
970    csp->server_certs_chain.next = NULL;
971
972    /* Setting path to file with trusted CAs */
973    trusted_cas_file = csp->config->trusted_cas_file;
974
975    ssl_attrs->ctx = SSL_CTX_new(SSLv23_method());
976    if (!ssl_attrs->ctx)
977    {
978       log_ssl_errors(LOG_LEVEL_ERROR, "SSL context creation failed");
979       ret = -1;
980       goto exit;
981    }
982
983    /*
984     * Loading file with trusted CAs
985     */
986    if (!SSL_CTX_load_verify_locations(ssl_attrs->ctx, trusted_cas_file, NULL))
987    {
988       log_ssl_errors(LOG_LEVEL_ERROR, "Loading trusted CAs file %s failed",
989          trusted_cas_file);
990       ret = -1;
991       goto exit;
992    }
993
994    SSL_CTX_set_verify(ssl_attrs->ctx, SSL_VERIFY_NONE, NULL);
995    SSL_CTX_set_options(ssl_attrs->ctx, SSL_OP_NO_SSLv3);
996
997    if (!(ssl_attrs->bio = BIO_new_ssl(ssl_attrs->ctx, 1)))
998    {
999       log_ssl_errors(LOG_LEVEL_ERROR, "Unable to create BIO structure");
1000       ret = -1;
1001       goto exit;
1002    }
1003
1004    if (BIO_get_ssl(ssl_attrs->bio, &ssl) != 1)
1005    {
1006       log_ssl_errors(LOG_LEVEL_ERROR, "BIO_get_ssl failed");
1007       ret = -1;
1008       goto exit;
1009    }
1010
1011    if (!SSL_set_fd(ssl, csp->server_connection.sfd))
1012    {
1013       log_ssl_errors(LOG_LEVEL_ERROR, "SSL_set_fd failed");
1014       ret = -1;
1015       goto exit;
1016    }
1017
1018    /*
1019     * Set the hostname to check against the received server certificate
1020     */
1021 #if OPENSSL_VERSION_NUMBER > 0x10100000L
1022    if (!SSL_set1_host(ssl, csp->http->host))
1023    {
1024       log_ssl_errors(LOG_LEVEL_ERROR, "SSL_set1_host failed");
1025       ret = -1;
1026       goto exit;
1027    }
1028 #else
1029    if (host_is_ip_address(csp->http->host))
1030    {
1031       if (X509_VERIFY_PARAM_set1_ip_asc(ssl->param,  csp->http->host) != 1)
1032       {
1033          log_ssl_errors(LOG_LEVEL_ERROR,
1034             "X509_VERIFY_PARAM_set1_ip_asc() failed");
1035          ret = -1;
1036          goto exit;
1037       }
1038    }
1039    else
1040    {
1041       if (X509_VERIFY_PARAM_set1_host(ssl->param,  csp->http->host, 0) != 1)
1042       {
1043          log_ssl_errors(LOG_LEVEL_ERROR,
1044             "X509_VERIFY_PARAM_set1_host() failed");
1045          ret = -1;
1046          goto exit;
1047       }
1048    }
1049 #endif
1050    /* SNI extension */
1051    if (!SSL_set_tlsext_host_name(ssl, csp->http->host))
1052    {
1053       log_ssl_errors(LOG_LEVEL_ERROR, "SSL_set_tlsext_host_name failed");
1054       ret = -1;
1055       goto exit;
1056    }
1057
1058    /*
1059     * Handshake with server
1060     */
1061    log_error(LOG_LEVEL_CONNECT,
1062       "Performing the TLS/SSL handshake with the server");
1063
1064    if (BIO_do_handshake(ssl_attrs->bio) != 1)
1065    {
1066       log_ssl_errors(LOG_LEVEL_ERROR,
1067          "The TLS/SSL handshake with the server failed");
1068       ret = -1;
1069       goto exit;
1070    }
1071
1072    chain = SSL_get_peer_cert_chain(ssl);
1073    if (chain)
1074    {
1075       for (int i = 0; i < sk_X509_num(chain); i++)
1076       {
1077          if (ssl_store_cert(csp, sk_X509_value(chain, i)) != 0)
1078          {
1079             log_error(LOG_LEVEL_ERROR, "ssl_store_cert failed");
1080             ret = -1;
1081             goto exit;
1082          }
1083       }
1084    }
1085
1086    if (!csp->dont_verify_certificate)
1087    {
1088       long verify_result = SSL_get_verify_result(ssl);
1089       if (verify_result == X509_V_OK)
1090       {
1091          ret = 0;
1092          csp->server_cert_verification_result = SSL_CERT_VALID;
1093       }
1094       else
1095       {
1096          csp->server_cert_verification_result = verify_result;
1097          log_error(LOG_LEVEL_ERROR, "SSL_get_verify_result failed: %s",
1098             X509_verify_cert_error_string(verify_result));
1099          ret = -1;
1100          goto exit;
1101       }
1102    }
1103
1104    log_error(LOG_LEVEL_CONNECT, "Server successfully connected over TLS/SSL");
1105
1106    /*
1107     * Server certificate chain is valid, so we can clean
1108     * chain, because we will not send it to client.
1109     */
1110    free_certificate_chain(csp);
1111
1112    csp->ssl_with_server_is_opened = 1;
1113 exit:
1114    /* Freeing structures if connection wasn't created successfully */
1115    if (ret < 0)
1116    {
1117       free_server_ssl_structures(csp);
1118    }
1119
1120    return ret;
1121 }
1122
1123
1124 /*********************************************************************
1125  *
1126  * Function    :  free_server_ssl_structures
1127  *
1128  * Description :  Frees structures used for SSL communication with server
1129  *
1130  * Parameters  :
1131  *          1  :  csp = Current client state (buffers, headers, etc...)
1132  *
1133  * Returns     :  N/A
1134  *
1135  *********************************************************************/
1136 static void free_server_ssl_structures(struct client_state *csp)
1137 {
1138    struct ssl_attr *ssl_attr = &csp->ssl_server_attr;
1139
1140    if (ssl_attr->openssl_attr.bio)
1141    {
1142       BIO_free_all(ssl_attr->openssl_attr.bio);
1143    }
1144    if (ssl_attr->openssl_attr.ctx)
1145    {
1146       SSL_CTX_free(ssl_attr->openssl_attr.ctx);
1147    }
1148 }
1149
1150
1151 /*********************************************************************
1152  *
1153  * Function    :  log_ssl_errors
1154  *
1155  * Description :  Log SSL errors
1156  *
1157  * Parameters  :
1158  *          1  :  debuglevel = Debug level
1159  *          2  :  desc = Error description
1160  *
1161  * Returns     :  N/A
1162  *
1163  *********************************************************************/
1164 static void log_ssl_errors(int debuglevel, const char* fmt, ...)
1165 {
1166    unsigned long err_code;
1167    char prefix[ERROR_BUF_SIZE];
1168    va_list args;
1169    va_start(args, fmt);
1170    vsnprintf(prefix, sizeof(prefix), fmt, args);
1171    int reported = 0;
1172
1173    while ((err_code = ERR_get_error()))
1174    {
1175       char err_buf[ERROR_BUF_SIZE];
1176       reported = 1;
1177       ERR_error_string_n(err_code, err_buf, sizeof(err_buf));
1178       log_error(debuglevel, "%s: %s", prefix, err_buf);
1179    }
1180    va_end(args);
1181    /*
1182     * In case if called by mistake and there were
1183     * no TLS/SSL errors let's report it to the log.
1184     */
1185    if (!reported)
1186    {
1187       log_error(debuglevel, "%s: no TLS/SSL errors detected", prefix);
1188    }
1189 }
1190
1191
1192 /*********************************************************************
1193  *
1194  * Function    :  ssl_base64_encode
1195  *
1196  * Description :  Encode a buffer into base64 format.
1197  *
1198  * Parameters  :
1199  *          1  :  dst = Destination buffer
1200  *          2  :  dlen = Destination buffer length
1201  *          3  :  olen = Number of bytes written
1202  *          4  :  src = Source buffer
1203  *          5  :  slen = Amount of data to be encoded
1204  *
1205  * Returns     :  0 on success, error code othervise
1206  *
1207  *********************************************************************/
1208 extern int ssl_base64_encode(unsigned char *dst, size_t dlen, size_t *olen,
1209                              const unsigned char *src, size_t slen)
1210 {
1211    *olen = 4 * ((slen/3)  + ((slen%3) ? 1 : 0)) + 1;
1212    if (*olen < dlen)
1213    {
1214       return ENOBUFS;
1215    }
1216    *olen = (size_t)EVP_EncodeBlock(dst, src, (int)slen) + 1;
1217    return 0;
1218 }
1219
1220
1221 /*********************************************************************
1222  *
1223  * Function    :  close_file_stream
1224  *
1225  * Description :  Close file stream, report error on close error
1226  *
1227  * Parameters  :
1228  *          1  :  f = file stream to close
1229  *          2  :  path = path for error report
1230  *
1231  * Returns     :  N/A
1232  *
1233  *********************************************************************/
1234 static void close_file_stream(FILE *f, const char *path)
1235 {
1236    if (fclose(f) != 0)
1237    {
1238       log_error(LOG_LEVEL_ERROR,
1239          "Error closing file %s: %s", path, strerror(errno));
1240    }
1241 }
1242
1243
1244 /*********************************************************************
1245  *
1246  * Function    :  write_certificate
1247  *
1248  * Description :  Writes certificate into file.
1249  *
1250  * Parameters  :
1251  *          1  :  crt = certificate to write into file
1252  *          2  :  output_file = path to save certificate file
1253  *
1254  *                on error
1255  * Returns     :  1 on success success or negative value
1256  *
1257  *********************************************************************/
1258 static int write_certificate(X509 *crt, const char *output_file)
1259 {
1260    FILE *f = NULL;
1261    int ret = -1;
1262
1263    /*
1264     * Saving certificate into file
1265     */
1266    if ((f = fopen(output_file, "w")) == NULL)
1267    {
1268       log_error(LOG_LEVEL_ERROR, "Opening file %s to save certificate failed",
1269          output_file);
1270       return ret;
1271    }
1272
1273    ret = PEM_write_X509(f, crt);
1274    if (!ret)
1275    {
1276       log_ssl_errors(LOG_LEVEL_ERROR,
1277          "Writing certificate into file %s failed", output_file);
1278       ret = -1;
1279    }
1280
1281    close_file_stream(f, output_file);
1282
1283    return ret;
1284 }
1285
1286 /*********************************************************************
1287  *
1288  * Function    :  write_private_key
1289  *
1290  * Description :  Writes private key into file and copies saved
1291  *                content into given pointer to string. If function
1292  *                returns 0 for success, this copy must be freed by
1293  *                caller.
1294  *
1295  * Parameters  :
1296  *          1  :  key = key to write into file
1297  *          2  :  ret_buf = pointer to string with created key file content
1298  *          3  :  key_file_path = path where to save key file
1299  *
1300  * Returns     :  Length of written private key on success or negative value
1301  *                on error
1302  *
1303  *********************************************************************/
1304 static int write_private_key(EVP_PKEY *key, char **ret_buf,
1305                              const char *key_file_path)
1306 {
1307    size_t len = 0;                /* Length of created key    */
1308    FILE *f = NULL;                /* File to save certificate */
1309    int ret = 0;
1310    BIO *bio_mem = BIO_new(BIO_s_mem());
1311    char *bio_mem_data = 0;
1312
1313    if (bio_mem == NULL)
1314    {
1315       log_ssl_errors(LOG_LEVEL_ERROR, "write_private_key memory allocation failure");
1316       return -1;
1317    }
1318
1319    /*
1320     * Writing private key into PEM string
1321     */
1322    if (!PEM_write_bio_PrivateKey(bio_mem, key, NULL, NULL, 0, NULL, NULL))
1323    {
1324       log_ssl_errors(LOG_LEVEL_ERROR,
1325          "Writing private key into PEM string failed");
1326       ret = -1;
1327       goto exit;
1328    }
1329
1330    len = (size_t)BIO_get_mem_data(bio_mem, &bio_mem_data);
1331
1332    /* Initializing buffer for key file content */
1333    *ret_buf = zalloc_or_die(len + 1);
1334    (*ret_buf)[len] = 0;
1335
1336    strncpy(*ret_buf, bio_mem_data, len);
1337
1338    /*
1339     * Saving key into file
1340     */
1341    if ((f = fopen(key_file_path, "wb")) == NULL)
1342    {
1343       log_error(LOG_LEVEL_ERROR,
1344          "Opening file %s to save private key failed: %E",
1345          key_file_path);
1346       ret = -1;
1347       goto exit;
1348    }
1349
1350    if (fwrite(*ret_buf, 1, len, f) != len)
1351    {
1352       log_error(LOG_LEVEL_ERROR,
1353          "Writing private key into file %s failed",
1354          key_file_path);
1355       close_file_stream(f, key_file_path);
1356       ret = -1;
1357       goto exit;
1358    }
1359
1360    close_file_stream(f, key_file_path);
1361
1362 exit:
1363    BIO_free(bio_mem);
1364    if (ret < 0)
1365    {
1366       freez(*ret_buf);
1367       *ret_buf = NULL;
1368       return ret;
1369    }
1370    return (int)len;
1371 }
1372
1373
1374 /*********************************************************************
1375  *
1376  * Function    :  generate_key
1377  *
1378  * Description : Tests if private key for host saved in csp already
1379  *               exists.  If this file doesn't exists, a new key is
1380  *               generated and saved in a file. The generated key is also
1381  *               copied into given parameter key_buf, which must be then
1382  *               freed by caller. If file with key exists, key_buf
1383  *               contain NULL and no private key is generated.
1384  *
1385  * Parameters  :
1386  *          1  :  csp = Current client state (buffers, headers, etc...)
1387  *          2  :  key_buf = buffer to save new generated key
1388  *
1389  * Returns     :  -1 => Error while generating private key
1390  *                 0 => Key already exists
1391  *                >0 => Length of generated private key
1392  *
1393  *********************************************************************/
1394 static int generate_key(struct client_state *csp, char **key_buf)
1395 {
1396    int ret = 0;
1397    char* key_file_path = NULL;
1398    BIGNUM *exp = BN_new();
1399    RSA *rsa = RSA_new();
1400    EVP_PKEY *key = EVP_PKEY_new();
1401
1402    if (exp == NULL || rsa == NULL || key == NULL)
1403    {
1404       log_ssl_errors(LOG_LEVEL_ERROR, "RSA key memory allocation failure");
1405       ret = -1;
1406       goto exit;
1407    }
1408
1409    BN_set_word(exp, RSA_KEY_PUBLIC_EXPONENT);
1410
1411    key_file_path = make_certs_path(csp->config->certificate_directory,
1412       (char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
1413    if (key_file_path == NULL)
1414    {
1415       ret = -1;
1416       goto exit;
1417    }
1418
1419    /*
1420     * Test if key already exists. If so, we don't have to create it again.
1421     */
1422    if (file_exists(key_file_path) == 1)
1423    {
1424       ret = 0;
1425       goto exit;
1426    }
1427
1428    ret = RSA_generate_key_ex(rsa, RSA_KEYSIZE, exp, NULL);
1429    if (ret == 0)
1430    {
1431       log_ssl_errors(LOG_LEVEL_ERROR, "RSA key generation failure");
1432       ret = -1;
1433       goto exit;
1434    }
1435
1436    if (!EVP_PKEY_set1_RSA(key, rsa))
1437    {
1438       log_ssl_errors(LOG_LEVEL_ERROR,
1439          "Error assigning RSA key pair to PKEY structure");
1440       ret = -1;
1441       goto exit;
1442    }
1443
1444    /*
1445     * Exporting private key into file
1446     */
1447    if ((ret = write_private_key(key, key_buf, key_file_path)) < 0)
1448    {
1449       log_error(LOG_LEVEL_ERROR,
1450          "Writing private key into file %s failed", key_file_path);
1451       ret = -1;
1452       goto exit;
1453    }
1454
1455 exit:
1456    /*
1457     * Freeing used variables
1458     */
1459    if (exp)
1460    {
1461       BN_free(exp);
1462    }
1463    if (rsa)
1464    {
1465       RSA_free(rsa);
1466    }
1467    if (key)
1468    {
1469       EVP_PKEY_free(key);
1470    }
1471    freez(key_file_path);
1472
1473    return ret;
1474 }
1475
1476
1477 /*********************************************************************
1478  *
1479  * Function    :  ssl_certificate_load
1480  *
1481  * Description :  Loads certificate from file.
1482  *
1483  * Parameters  :
1484  *          1  :  cert_path = The certificate path to load
1485  *
1486  * Returns     :   NULL => error loading certificate,
1487  *                   pointer to certificate instance otherwise
1488  *
1489  *********************************************************************/
1490 static X509* ssl_certificate_load(const char *cert_path)
1491 {
1492    X509 *cert = NULL;
1493    FILE *cert_f = NULL;
1494
1495    if (!(cert_f = fopen(cert_path, "r")))
1496    {
1497       log_error(LOG_LEVEL_ERROR,
1498          "Error opening certificate file %s: %s", cert_path, strerror(errno));
1499       return NULL;
1500    }
1501
1502    if (!(cert = PEM_read_X509(cert_f, NULL, NULL, NULL)))
1503    {
1504       log_ssl_errors(LOG_LEVEL_ERROR,
1505          "Error reading certificate file %s", cert_path);
1506    }
1507
1508    close_file_stream(cert_f, cert_path);
1509    return cert;
1510 }
1511
1512
1513 /*********************************************************************
1514  *
1515  * Function    :  ssl_certificate_is_invalid
1516  *
1517  * Description :  Checks whether or not a certificate is valid.
1518  *                Currently only checks that the certificate can be
1519  *                parsed and that the "valid to" date is in the future.
1520  *
1521  * Parameters  :
1522  *          1  :  cert_file = The certificate to check
1523  *
1524  * Returns     :   0 => The certificate is valid.
1525  *                 1 => The certificate is invalid
1526  *
1527  *********************************************************************/
1528 static int ssl_certificate_is_invalid(const char *cert_file)
1529 {
1530    int ret;
1531
1532    X509 *cert = NULL;
1533
1534    if (!(cert = ssl_certificate_load(cert_file)))
1535    {
1536       log_ssl_errors(LOG_LEVEL_ERROR,
1537          "Error reading certificate file %s", cert_file);
1538       return 1;
1539    }
1540
1541    ret = X509_cmp_current_time(X509_get_notAfter(cert));
1542    if (ret == 0)
1543    {
1544       log_ssl_errors(LOG_LEVEL_ERROR,
1545          "Error checking certificate %s validity", cert_file);
1546    }
1547
1548    X509_free(cert);
1549
1550    return ret == -1 ? 1 : 0;
1551 }
1552
1553
1554 /*********************************************************************
1555  *
1556  * Function    :  set_x509_ext
1557  *
1558  * Description :  Sets the X509V3 extension data
1559  *
1560  * Parameters  :
1561  *          1  :  cert = The certificate to modify
1562  *          2  :  issuer = Issuer certificate
1563  *          3  :  nid = OpenSSL NID
1564  *          4  :  value = extension value
1565  *
1566  * Returns     :   0 => Error while setting extensuon data
1567  *                 1 => It worked
1568  *
1569  *********************************************************************/
1570 static int set_x509_ext(X509 *cert, X509 *issuer, int nid, char *value)
1571 {
1572    X509_EXTENSION *ext = NULL;
1573    X509V3_CTX ctx;
1574    int ret = 0;
1575
1576    X509V3_set_ctx(&ctx, issuer, cert, NULL, NULL, 0);
1577    ext = X509V3_EXT_conf_nid(NULL, &ctx, nid, value);
1578    if (!ext)
1579    {
1580       log_ssl_errors(LOG_LEVEL_ERROR, "X509V3_EXT_conf_nid failure");
1581       goto exit;
1582    }
1583
1584    if (!X509_add_ext(cert, ext, -1))
1585    {
1586       log_ssl_errors(LOG_LEVEL_ERROR, "X509_add_ext failure");
1587       goto exit;
1588    }
1589
1590    ret = 1;
1591 exit:
1592    if (ext)
1593    {
1594       X509_EXTENSION_free(ext);
1595    }
1596    return ret;
1597 }
1598
1599
1600 /*********************************************************************
1601  *
1602  * Function    :  set_subject_alternative_name
1603  *
1604  * Description :  Sets the Subject Alternative Name extension to a cert
1605  *
1606  * Parameters  :
1607  *          1  :  cert = The certificate to modify
1608  *          2  :  issuer = Issuer certificate
1609  *          3  :  hostname = The hostname to add
1610  *
1611  * Returns     :   0 => Error while creating certificate.
1612  *                 1 => It worked
1613  *
1614  *********************************************************************/
1615 static int set_subject_alternative_name(X509 *cert, X509 *issuer, const char *hostname)
1616 {
1617    size_t altname_len = strlen(hostname) + sizeof(CERTIFICATE_ALT_NAME_PREFIX);
1618    char alt_name_buf[altname_len];
1619
1620    snprintf(alt_name_buf, sizeof(alt_name_buf),
1621       CERTIFICATE_ALT_NAME_PREFIX"%s", hostname);
1622    return set_x509_ext(cert, issuer, NID_subject_alt_name, alt_name_buf);
1623 }
1624
1625
1626 /*********************************************************************
1627  *
1628  * Function    :  generate_webpage_certificate
1629  *
1630  * Description :  Creates certificate file in presetted directory.
1631  *                If certificate already exists, no other certificate
1632  *                will be created. Subject of certificate is named
1633  *                by csp->http->host from parameter. This function also
1634  *                triggers generating of private key for new certificate.
1635  *
1636  * Parameters  :
1637  *          1  :  csp = Current client state (buffers, headers, etc...)
1638  *
1639  * Returns     :  -1 => Error while creating certificate.
1640  *                 0 => Certificate already exists.
1641  *                 1 => Certificate created
1642  *
1643  *********************************************************************/
1644 static int generate_webpage_certificate(struct client_state *csp)
1645 {
1646    char *key_buf = NULL;    /* Buffer for created key */
1647    X509 *issuer_cert = NULL;
1648    X509 *cert = NULL;
1649    BIO *pk_bio = NULL;
1650    EVP_PKEY *loaded_subject_key = NULL;
1651    EVP_PKEY *loaded_issuer_key = NULL;
1652    X509_NAME *issuer_name;
1653    X509_NAME *subject_name = NULL;
1654    ASN1_TIME *asn_time = NULL;
1655    ASN1_INTEGER *serial = NULL;
1656    BIGNUM *serial_num = NULL;
1657
1658    int ret = 0;
1659    cert_options cert_opt;
1660    char cert_valid_from[VALID_DATETIME_BUFLEN];
1661    char cert_valid_to[VALID_DATETIME_BUFLEN];
1662
1663    /* Paths to keys and certificates needed to create certificate */
1664    cert_opt.issuer_key  = NULL;
1665    cert_opt.subject_key = NULL;
1666    cert_opt.issuer_crt  = NULL;
1667
1668    cert_opt.output_file = make_certs_path(csp->config->certificate_directory,
1669       (const char *)csp->http->hash_of_host_hex, CERT_FILE_TYPE);
1670    if (cert_opt.output_file == NULL)
1671    {
1672       return -1;
1673    }
1674
1675    cert_opt.subject_key = make_certs_path(csp->config->certificate_directory,
1676       (const char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
1677    if (cert_opt.subject_key == NULL)
1678    {
1679       freez(cert_opt.output_file);
1680       return -1;
1681    }
1682
1683    if (file_exists(cert_opt.output_file) == 1)
1684    {
1685       /* The file exists, but is it valid? */
1686       if (ssl_certificate_is_invalid(cert_opt.output_file))
1687       {
1688          log_error(LOG_LEVEL_CONNECT,
1689             "Certificate %s is no longer valid. Removing it.",
1690             cert_opt.output_file);
1691          if (unlink(cert_opt.output_file))
1692          {
1693             log_error(LOG_LEVEL_ERROR, "Failed to unlink %s: %E",
1694                cert_opt.output_file);
1695
1696             freez(cert_opt.output_file);
1697             freez(cert_opt.subject_key);
1698
1699             return -1;
1700          }
1701          if (unlink(cert_opt.subject_key))
1702          {
1703             log_error(LOG_LEVEL_ERROR, "Failed to unlink %s: %E",
1704                cert_opt.subject_key);
1705
1706             freez(cert_opt.output_file);
1707             freez(cert_opt.subject_key);
1708
1709             return -1;
1710          }
1711       }
1712       else
1713       {
1714          freez(cert_opt.output_file);
1715          freez(cert_opt.subject_key);
1716
1717          return 0;
1718       }
1719    }
1720
1721    /*
1722     * Create key for requested host
1723     */
1724    int subject_key_len = generate_key(csp, &key_buf);
1725    if (subject_key_len < 0)
1726    {
1727       freez(cert_opt.output_file);
1728       freez(cert_opt.subject_key);
1729       log_error(LOG_LEVEL_ERROR, "Key generating failed");
1730       return -1;
1731    }
1732
1733    /*
1734     * Converting unsigned long serial number to char * serial number.
1735     * We must compute length of serial number in string + terminating null.
1736     */
1737    unsigned long certificate_serial = get_certificate_serial(csp);
1738    unsigned long certificate_serial_time = (unsigned long)time(NULL);
1739    int serial_num_size = snprintf(NULL, 0, "%lu%lu",
1740       certificate_serial_time, certificate_serial) + 1;
1741    if (serial_num_size <= 0)
1742    {
1743       serial_num_size = 1;
1744    }
1745
1746    char serial_num_text[serial_num_size];  /* Buffer for serial number */
1747    ret = snprintf(serial_num_text, (size_t)serial_num_size, "%lu%lu",
1748       certificate_serial_time, certificate_serial);
1749    if (ret < 0 || ret >= serial_num_size)
1750    {
1751       log_error(LOG_LEVEL_ERROR,
1752          "Converting certificate serial number into string failed");
1753       ret = -1;
1754       goto exit;
1755    }
1756
1757    /*
1758     * Preparing parameters for certificate
1759     */
1760    subject_name = X509_NAME_new();
1761    if (!subject_name)
1762    {
1763       log_ssl_errors(LOG_LEVEL_ERROR, "RSA key memory allocation failure");
1764       ret = -1;
1765       goto exit;
1766    }
1767
1768    if (!X509_NAME_add_entry_by_txt(subject_name, CERT_PARAM_COMMON_NAME_FCODE,
1769          MBSTRING_ASC, (void *)csp->http->host, -1, -1, 0))
1770    {
1771       log_ssl_errors(LOG_LEVEL_ERROR,
1772          "X509 subject name (code: %s, val: %s) error",
1773          CERT_PARAM_COMMON_NAME_FCODE, csp->http->host);
1774       ret = -1;
1775       goto exit;
1776    }
1777    if (!X509_NAME_add_entry_by_txt(subject_name, CERT_PARAM_ORGANIZATION_FCODE,
1778          MBSTRING_ASC, (void *)csp->http->host, -1, -1, 0))
1779    {
1780       log_ssl_errors(LOG_LEVEL_ERROR,
1781          "X509 subject name (code: %s, val: %s) error",
1782          CERT_PARAM_COMMON_NAME_FCODE, csp->http->host);
1783       ret = -1;
1784       goto exit;
1785    }
1786    if (!X509_NAME_add_entry_by_txt(subject_name, CERT_PARAM_ORG_UNIT_FCODE,
1787          MBSTRING_ASC, (void *)csp->http->host, -1, -1, 0))
1788    {
1789       log_ssl_errors(LOG_LEVEL_ERROR,
1790          "X509 subject name (code: %s, val: %s) error",
1791          CERT_PARAM_COMMON_NAME_FCODE, csp->http->host);
1792       ret = -1;
1793       goto exit;
1794    }
1795    if (!X509_NAME_add_entry_by_txt(subject_name, CERT_PARAM_COUNTRY_FCODE,
1796          MBSTRING_ASC, (void *)CERT_PARAM_COUNTRY_CODE, -1, -1, 0))
1797    {
1798       log_ssl_errors(LOG_LEVEL_ERROR,
1799          "X509 subject name (code: %s, val: %s) error",
1800          CERT_PARAM_COMMON_NAME_FCODE, csp->http->host);
1801       ret = -1;
1802       goto exit;
1803    }
1804
1805    cert_opt.issuer_crt = csp->config->ca_cert_file;
1806    cert_opt.issuer_key = csp->config->ca_key_file;
1807
1808    if (get_certificate_valid_from_date(cert_valid_from,
1809          sizeof(cert_valid_from), VALID_DATETIME_FMT)
1810     || get_certificate_valid_to_date(cert_valid_to,
1811          sizeof(cert_valid_to), VALID_DATETIME_FMT))
1812    {
1813       log_error(LOG_LEVEL_ERROR, "Generating one of the validity dates failed");
1814       ret = -1;
1815       goto exit;
1816    }
1817
1818    cert_opt.subject_pwd = CERT_SUBJECT_PASSWORD;
1819    cert_opt.issuer_pwd  = csp->config->ca_password;
1820    cert_opt.not_before  = cert_valid_from;
1821    cert_opt.not_after   = cert_valid_to;
1822    cert_opt.serial      = serial_num_text;
1823    cert_opt.max_pathlen = -1;
1824
1825    /*
1826     * Test if the private key was already created.
1827     * XXX: Can this still happen?
1828     */
1829    if (subject_key_len == 0)
1830    {
1831       log_error(LOG_LEVEL_ERROR, "Subject key was already created");
1832       ret = 0;
1833       goto exit;
1834    }
1835
1836    /*
1837     * Parse serial to MPI
1838     */
1839    serial_num = BN_new();
1840    if (!serial_num)
1841    {
1842       log_error(LOG_LEVEL_ERROR, "generate_webpage_certificate: memory error");
1843       ret = -1;
1844       goto exit;
1845    }
1846    if (!BN_dec2bn(&serial_num, cert_opt.serial))
1847    {
1848       log_ssl_errors(LOG_LEVEL_ERROR, "Failed to parse serial %s", cert_opt.serial);
1849       ret = -1;
1850       goto exit;
1851    }
1852
1853    if (!(serial = BN_to_ASN1_INTEGER(serial_num, NULL)))
1854    {
1855       log_ssl_errors(LOG_LEVEL_ERROR, "Failed to generate serial ASN1 representation");
1856       ret = -1;
1857       goto exit;
1858    }
1859
1860    /*
1861     * Loading certificates
1862     */
1863    if (!(issuer_cert = ssl_certificate_load(cert_opt.issuer_crt)))
1864    {
1865       log_error(LOG_LEVEL_ERROR, "Loading issuer certificate %s failed",
1866          cert_opt.issuer_crt);
1867       ret = -1;
1868       goto exit;
1869    }
1870
1871    issuer_name = X509_get_issuer_name(issuer_cert);
1872
1873    /*
1874     * Loading keys from file or from buffer
1875     */
1876    if (key_buf != NULL && subject_key_len > 0)
1877    {
1878       pk_bio = BIO_new_mem_buf(key_buf, subject_key_len);
1879    }
1880    else if (!(pk_bio = BIO_new_file(cert_opt.subject_key, "r")))
1881    {
1882       log_ssl_errors(LOG_LEVEL_ERROR,
1883          "Failure opening subject key %s BIO", cert_opt.subject_key);
1884       ret = -1;
1885       goto exit;
1886    }
1887
1888    loaded_subject_key = PEM_read_bio_PrivateKey(pk_bio, NULL, NULL,
1889       (void *)cert_opt.subject_pwd);
1890    if (!loaded_subject_key)
1891    {
1892       log_ssl_errors(LOG_LEVEL_ERROR, "Parsing subject key %s failed",
1893          cert_opt.subject_key);
1894       ret = -1;
1895       goto exit;
1896    }
1897
1898    if (!BIO_free(pk_bio))
1899    {
1900       log_ssl_errors(LOG_LEVEL_ERROR, "Error closing subject key BIO");
1901    }
1902
1903    if (!(pk_bio = BIO_new_file(cert_opt.issuer_key, "r")))
1904    {
1905       log_ssl_errors(LOG_LEVEL_ERROR, "Failure opening issuer key %s BIO",
1906          cert_opt.issuer_key);
1907       ret = -1;
1908       goto exit;
1909    }
1910
1911    loaded_issuer_key = PEM_read_bio_PrivateKey(pk_bio, NULL, NULL,
1912       (void *)cert_opt.issuer_pwd);
1913    if (!loaded_issuer_key)
1914    {
1915       log_ssl_errors(LOG_LEVEL_ERROR, "Parsing issuer key %s failed",
1916          cert_opt.subject_key);
1917       ret = -1;
1918       goto exit;
1919    }
1920
1921    cert = X509_new();
1922    if (!cert)
1923    {
1924       log_ssl_errors(LOG_LEVEL_ERROR, "Certificate allocation error");
1925       ret = -1;
1926       goto exit;
1927    }
1928
1929    if (!X509_set_version(cert, CERTIFICATE_VERSION))
1930    {
1931       log_ssl_errors(LOG_LEVEL_ERROR, "X509_set_version failed");
1932       ret = -1;
1933       goto exit;
1934    }
1935
1936    /*
1937     * Setting parameters of signed certificate
1938     */
1939    if (!X509_set_pubkey(cert, loaded_subject_key))
1940    {
1941       log_ssl_errors(LOG_LEVEL_ERROR,
1942          "Setting issuer name in signed certificate failed");
1943       ret = -1;
1944       goto exit;
1945    }
1946
1947    if (!X509_set_subject_name(cert, subject_name))
1948    {
1949       log_ssl_errors(LOG_LEVEL_ERROR,
1950          "Setting issuer name in signed certificate failed");
1951       ret = -1;
1952       goto exit;
1953    }
1954
1955    if (!X509_set_issuer_name(cert, issuer_name))
1956    {
1957       log_ssl_errors(LOG_LEVEL_ERROR,
1958          "Setting issuer name in signed certificate failed");
1959       ret = -1;
1960       goto exit;
1961    }
1962
1963    if (!X509_set_serialNumber(cert, serial))
1964    {
1965       log_ssl_errors(LOG_LEVEL_ERROR,
1966          "Setting serial number in signed certificate failed");
1967       ret = -1;
1968       goto exit;
1969    }
1970
1971    asn_time = ASN1_TIME_new();
1972    if (!asn_time)
1973    {
1974       log_ssl_errors(LOG_LEVEL_ERROR, "ASN1 time memory allocation failure");
1975       ret = -1;
1976       goto exit;
1977    }
1978
1979    if (!ASN1_TIME_set_string(asn_time, cert_opt.not_after))
1980    {
1981       log_ssl_errors(LOG_LEVEL_ERROR, "ASN1 time [%s] encode error", cert_opt.not_after);
1982       ret = -1;
1983       goto exit;
1984    }
1985
1986    if (!X509_set1_notAfter(cert, asn_time))
1987    {
1988       log_ssl_errors(LOG_LEVEL_ERROR,
1989          "Setting valid not after in signed certificate failed");
1990       ret = -1;
1991       goto exit;
1992    }
1993
1994    if (!ASN1_TIME_set_string(asn_time, cert_opt.not_before))
1995    {
1996       log_ssl_errors(LOG_LEVEL_ERROR, "ASN1 time encode error");
1997       ret = -1;
1998       goto exit;
1999    }
2000
2001    if (!X509_set1_notBefore(cert, asn_time))
2002    {
2003       log_ssl_errors(LOG_LEVEL_ERROR,
2004          "Setting valid not befre in signed certificate failed");
2005       ret = -1;
2006       goto exit;
2007    }
2008
2009    if (!set_x509_ext(cert, issuer_cert, NID_basic_constraints, CERTIFICATE_BASIC_CONSTRAINTS))
2010    {
2011       log_ssl_errors(LOG_LEVEL_ERROR, "Setting the basicConstraints extension "
2012          "in signed certificate failed");
2013       ret = -1;
2014       goto exit;
2015    }
2016
2017    if (!set_x509_ext(cert, issuer_cert, NID_subject_key_identifier, CERTIFICATE_SUBJECT_KEY))
2018    {
2019       log_ssl_errors(LOG_LEVEL_ERROR,
2020          "Setting the Subject Key Identifie extension failed");
2021       ret = -1;
2022       goto exit;
2023    }
2024
2025    if (!set_x509_ext(cert, issuer_cert, NID_authority_key_identifier, CERTIFICATE_AUTHORITY_KEY))
2026    {
2027       log_ssl_errors(LOG_LEVEL_ERROR,
2028          "Setting the Authority Key Identifier extension failed");
2029       ret = -1;
2030       goto exit;
2031    }
2032
2033    if (!host_is_ip_address(csp->http->host) &&
2034        !set_subject_alternative_name(cert, issuer_cert, csp->http->host))
2035    {
2036       log_ssl_errors(LOG_LEVEL_ERROR, "Setting the Subject Alt Nameextension failed");
2037       ret = -1;
2038       goto exit;
2039    }
2040
2041    if (!X509_sign(cert, loaded_issuer_key, EVP_sha256()))
2042    {
2043       log_ssl_errors(LOG_LEVEL_ERROR, "Signing certificate failed");
2044       ret = -1;
2045       goto exit;
2046    }
2047
2048    /*
2049     * Writing certificate into file
2050     */
2051    if (write_certificate(cert, cert_opt.output_file) < 0)
2052    {
2053       log_error(LOG_LEVEL_ERROR, "Writing certificate into file failed");
2054       ret = -1;
2055       goto exit;
2056    }
2057
2058    ret = 1;
2059
2060 exit:
2061    /*
2062     * Freeing used structures
2063     */
2064    if (issuer_cert)
2065    {
2066       X509_free(issuer_cert);
2067    }
2068    if (cert)
2069    {
2070       X509_free(cert);
2071    }
2072    if (pk_bio && !BIO_free(pk_bio))
2073    {
2074       log_ssl_errors(LOG_LEVEL_ERROR, "Error closing pk BIO");
2075    }
2076    if (loaded_subject_key)
2077    {
2078       EVP_PKEY_free(loaded_subject_key);
2079    }
2080    if (loaded_issuer_key)
2081    {
2082       EVP_PKEY_free(loaded_issuer_key);
2083    }
2084    if (subject_name)
2085    {
2086       X509_NAME_free(subject_name);
2087    }
2088    if (asn_time)
2089    {
2090       ASN1_TIME_free(asn_time);
2091    }
2092    if (serial_num)
2093    {
2094       BN_free(serial_num);
2095    }
2096    if (serial)
2097    {
2098       ASN1_INTEGER_free(serial);
2099    }
2100    freez(cert_opt.subject_key);
2101    freez(cert_opt.output_file);
2102    freez(key_buf);
2103
2104    return ret;
2105 }
2106
2107
2108 /*********************************************************************
2109  *
2110  * Function    :  ssl_crt_verify_info
2111  *
2112  * Description :  Returns an informational string about the verification
2113  *                status of a certificate.
2114  *
2115  * Parameters  :
2116  *          1  :  buf = Buffer to write to
2117  *          2  :  size = Maximum size of buffer
2118  *          3  :  csp = client state
2119  *
2120  * Returns     :  N/A
2121  *
2122  *********************************************************************/
2123 extern void ssl_crt_verify_info(char *buf, size_t size, struct client_state *csp)
2124 {
2125    strncpy(buf, X509_verify_cert_error_string(csp->server_cert_verification_result), size);
2126    buf[size - 1] = 0;
2127 }
2128
2129
2130 /*********************************************************************
2131  *
2132  * Function    :  ssl_release
2133  *
2134  * Description :  Release all SSL resources
2135  *
2136  * Parameters  :
2137  *
2138  * Returns     :  N/A
2139  *
2140  *********************************************************************/
2141 extern void ssl_release(void)
2142 {
2143    if (ssl_inited == 1)
2144    {
2145       SSL_COMP_free_compression_methods();
2146
2147       CONF_modules_free();
2148       CONF_modules_unload(1);
2149
2150       COMP_zlib_cleanup();
2151
2152       ERR_free_strings();
2153       EVP_cleanup();
2154
2155       CRYPTO_cleanup_all_ex_data();
2156    }
2157 }
2158