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