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