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