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