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