OpenSSL ssl_store_cert(): Translate EVP_PKEY_EC to a string
[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-2020 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    memset(last->next->file_buf, 0, sizeof(last->next->file_buf));
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    if (len > (sizeof(last->file_buf) - 1))
320    {
321       log_error(LOG_LEVEL_ERROR,
322          "X509 PEM cert len %ld is larger than buffer len %lu",
323          len, sizeof(last->file_buf) - 1);
324       len = sizeof(last->file_buf) - 1;
325    }
326
327    strncpy(last->file_buf, bio_mem_data, (size_t)len);
328    BIO_free(bio);
329    bio = BIO_new(BIO_s_mem());
330    if (!bio)
331    {
332       log_ssl_errors(LOG_LEVEL_ERROR, "BIO_new() failed");
333       ret = -1;
334       goto exit;
335    }
336
337    /*
338     * Saving certificate information into buffer
339     */
340    l = X509_get_version(crt);
341    if (l >= 0 && l <= 2)
342    {
343       if (BIO_printf(bio, "cert. version     : %ld\n", l + 1) <= 0)
344       {
345          log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for version failed");
346          ret = -1;
347          goto exit;
348       }
349    }
350    else
351    {
352       if (BIO_printf(bio, "cert. version     : Unknown (%ld)\n", l) <= 0)
353       {
354          log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for version failed");
355          ret = -1;
356          goto exit;
357       }
358    }
359
360    if (BIO_puts(bio, "serial number     : ") <= 0)
361    {
362       log_ssl_errors(LOG_LEVEL_ERROR, "BIO_puts() for serial failed");
363       ret = -1;
364       goto exit;
365    }
366    bs = X509_get0_serialNumber(crt);
367    if (bs->length <= (int)sizeof(long))
368    {
369       ERR_set_mark();
370       l = ASN1_INTEGER_get(bs);
371       ERR_pop_to_mark();
372    }
373    else
374    {
375       l = -1;
376    }
377    if (l != -1)
378    {
379       unsigned long ul;
380       const char *neg;
381       if (bs->type == V_ASN1_NEG_INTEGER)
382       {
383          ul = 0 - (unsigned long)l;
384          neg = "-";
385       }
386       else
387       {
388          ul = (unsigned long)l;
389          neg = "";
390       }
391       if (BIO_printf(bio, "%s%lu (%s0x%lx)\n", neg, ul, neg, ul) <= 0)
392       {
393          log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for serial failed");
394          ret = -1;
395          goto exit;
396       }
397    }
398    else
399    {
400       int i;
401       if (bs->type == V_ASN1_NEG_INTEGER)
402       {
403          if (BIO_puts(bio, " (Negative)") < 0)
404          {
405             log_ssl_errors(LOG_LEVEL_ERROR, "BIO_puts() for serial failed");
406             ret = -1;
407             goto exit;
408          }
409       }
410       for (i = 0; i < bs->length; i++)
411       {
412          if (BIO_printf(bio, "%02x%c", bs->data[i],
413                ((i + 1 == bs->length) ? '\n' : ':')) <= 0)
414          {
415             log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for serial failed");
416             ret = -1;
417             goto exit;
418          }
419       }
420    }
421
422    if (BIO_puts(bio, "issuer name       : ") <= 0)
423    {
424       log_ssl_errors(LOG_LEVEL_ERROR, "BIO_puts() for issuer failed");
425       ret = -1;
426       goto exit;
427    }
428    if (X509_NAME_print_ex(bio, X509_get_issuer_name(crt), 0, 0) < 0)
429    {
430       log_ssl_errors(LOG_LEVEL_ERROR, "X509_NAME_print_ex() for issuer failed");
431       ret = -1;
432       goto exit;
433    }
434
435    if (BIO_puts(bio, "\nsubject name      : ") <= 0)
436    {
437       log_ssl_errors(LOG_LEVEL_ERROR, "BIO_puts() for subject failed");
438       ret = -1;
439       goto exit;
440    }
441    if (X509_NAME_print_ex(bio, X509_get_subject_name(crt), 0, 0) < 0) {
442       log_ssl_errors(LOG_LEVEL_ERROR, "X509_NAME_print_ex() for subject failed");
443       ret = -1;
444       goto exit;
445    }
446
447    if (BIO_puts(bio, "\nissued  on        : ") <= 0)
448    {
449       log_ssl_errors(LOG_LEVEL_ERROR, "BIO_puts() for issued on failed");
450       ret = -1;
451       goto exit;
452    }
453    if (!ASN1_TIME_print(bio, X509_get0_notBefore(crt)))
454    {
455       log_ssl_errors(LOG_LEVEL_ERROR, "ASN1_TIME_print() for issued on failed");
456       ret = -1;
457       goto exit;
458    }
459
460    if (BIO_puts(bio, "\nexpires on        : ") <= 0)
461    {
462       log_ssl_errors(LOG_LEVEL_ERROR, "BIO_puts() for expires on failed");
463       ret = -1;
464       goto exit;
465    }
466    if (!ASN1_TIME_print(bio, X509_get0_notAfter(crt)))
467    {
468       log_ssl_errors(LOG_LEVEL_ERROR, "ASN1_TIME_print() for expires on failed");
469       ret = -1;
470       goto exit;
471    }
472
473 #if OPENSSL_VERSION_NUMBER > 0x10100000L
474    if (BIO_puts(bio, "\nsigned using      : ") <= 0)
475    {
476       log_ssl_errors(LOG_LEVEL_ERROR, "BIO_puts() for signed using failed");
477       ret = -1;
478       goto exit;
479    }
480    tsig_alg = X509_get0_tbs_sigalg(crt);
481    if (!i2a_ASN1_OBJECT(bio, tsig_alg->algorithm))
482    {
483       log_ssl_errors(LOG_LEVEL_ERROR, "i2a_ASN1_OBJECT() for signed using failed");
484       ret = -1;
485       goto exit;
486    }
487 #endif
488    pkey = X509_get_pubkey(crt);
489    if (!pkey)
490    {
491       log_ssl_errors(LOG_LEVEL_ERROR, "X509_get_pubkey() failed");
492       ret = -1;
493       goto exit;
494    }
495 #define BC              "18"
496    switch (EVP_PKEY_base_id(pkey))
497    {
498       case EVP_PKEY_RSA:
499          ret = BIO_printf(bio, "\n%-" BC "s: %d bits", "RSA key size", EVP_PKEY_bits(pkey));
500          break;
501       case EVP_PKEY_DSA:
502          ret = BIO_printf(bio, "\n%-" BC "s: %d bits", "DSA key size", EVP_PKEY_bits(pkey));
503          break;
504       case EVP_PKEY_EC:
505          ret = BIO_printf(bio, "\n%-" BC "s: %d bits", "EC key size", EVP_PKEY_bits(pkey));
506          break;
507       default:
508          ret = BIO_printf(bio, "\n%-" BC "s: %d bits", "non-RSA/DSA/EC key size",
509             EVP_PKEY_bits(pkey));
510          break;
511    }
512    if (ret <= 0)
513    {
514       log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for key size failed");
515       ret = -1;
516       goto exit;
517    }
518
519    loc = X509_get_ext_by_NID(crt, NID_basic_constraints, -1);
520    if (loc != -1)
521    {
522       X509_EXTENSION *ex = X509_get_ext(crt, loc);
523       if (BIO_puts(bio, "\nbasic constraints : ") <= 0)
524       {
525          log_ssl_errors(LOG_LEVEL_ERROR,
526             "BIO_printf() for basic constraints failed");
527          ret = -1;
528          goto exit;
529       }
530       if (!X509V3_EXT_print(bio, ex, 0, 0))
531       {
532          if (!ASN1_STRING_print_ex(bio, X509_EXTENSION_get_data(ex), ASN1_STRFLGS_RFC2253))
533          {
534             log_ssl_errors(LOG_LEVEL_ERROR,
535                "ASN1_STRING_print_ex() for basic constraints failed");
536             ret = -1;
537             goto exit;
538          }
539       }
540    }
541
542    loc = X509_get_ext_by_NID(crt, NID_subject_alt_name, -1);
543    if (loc != -1)
544    {
545       X509_EXTENSION *ex = X509_get_ext(crt, loc);
546       if (BIO_puts(bio, "\nsubject alt name  : ") <= 0)
547       {
548          log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for alt name failed");
549          ret = -1;
550          goto exit;
551       }
552       if (!X509V3_EXT_print(bio, ex, 0, 0))
553       {
554          if (!ASN1_STRING_print_ex(bio, X509_EXTENSION_get_data(ex),
555                ASN1_STRFLGS_RFC2253))
556          {
557             log_ssl_errors(LOG_LEVEL_ERROR,
558                "ASN1_STRING_print_ex() for alt name failed");
559             ret = -1;
560             goto exit;
561          }
562       }
563    }
564
565    loc = X509_get_ext_by_NID(crt, NID_netscape_cert_type, -1);
566    if (loc != -1)
567    {
568       X509_EXTENSION *ex = X509_get_ext(crt, loc);
569       if (BIO_puts(bio, "\ncert. type        : ") <= 0)
570       {
571          log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for cert type failed");
572          ret = -1;
573          goto exit;
574       }
575       if (!X509V3_EXT_print(bio, ex, 0, 0))
576       {
577          if (!ASN1_STRING_print_ex(bio, X509_EXTENSION_get_data(ex),
578                ASN1_STRFLGS_RFC2253))
579          {
580             log_ssl_errors(LOG_LEVEL_ERROR,
581                "ASN1_STRING_print_ex() for cert type failed");
582             ret = -1;
583             goto exit;
584          }
585       }
586    }
587
588    loc = X509_get_ext_by_NID(crt, NID_key_usage, -1);
589    if (loc != -1)
590    {
591       X509_EXTENSION *ex = X509_get_ext(crt, loc);
592       if (BIO_puts(bio, "\nkey usage         : ") <= 0)
593       {
594          log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for key usage failed");
595          ret = -1;
596          goto exit;
597       }
598       if (!X509V3_EXT_print(bio, ex, 0, 0))
599       {
600          if (!ASN1_STRING_print_ex(bio, X509_EXTENSION_get_data(ex),
601                ASN1_STRFLGS_RFC2253))
602          {
603             log_ssl_errors(LOG_LEVEL_ERROR,
604                "ASN1_STRING_print_ex() for key usage failed");
605             ret = -1;
606             goto exit;
607          }
608       }
609    }
610
611    loc = X509_get_ext_by_NID(crt, NID_ext_key_usage, -1);
612    if (loc != -1) {
613       X509_EXTENSION *ex = X509_get_ext(crt, loc);
614       if (BIO_puts(bio, "\next key usage     : ") <= 0)
615       {
616          log_ssl_errors(LOG_LEVEL_ERROR,
617             "BIO_printf() for ext key usage failed");
618          ret = -1;
619          goto exit;
620       }
621       if (!X509V3_EXT_print(bio, ex, 0, 0))
622       {
623          if (!ASN1_STRING_print_ex(bio, X509_EXTENSION_get_data(ex),
624                ASN1_STRFLGS_RFC2253))
625          {
626             log_ssl_errors(LOG_LEVEL_ERROR,
627                "ASN1_STRING_print_ex() for ext key usage failed");
628             ret = -1;
629             goto exit;
630          }
631       }
632    }
633
634    loc = X509_get_ext_by_NID(crt, NID_certificate_policies, -1);
635    if (loc != -1)
636    {
637       X509_EXTENSION *ex = X509_get_ext(crt, loc);
638       if (BIO_puts(bio, "\ncertificate policies : ") <= 0)
639       {
640          log_ssl_errors(LOG_LEVEL_ERROR, "BIO_printf() for certificate policies failed");
641          ret = -1;
642          goto exit;
643       }
644       if (!X509V3_EXT_print(bio, ex, 0, 0))
645       {
646          if (!ASN1_STRING_print_ex(bio, X509_EXTENSION_get_data(ex),
647                ASN1_STRFLGS_RFC2253))
648          {
649             log_ssl_errors(LOG_LEVEL_ERROR,
650                "ASN1_STRING_print_ex() for certificate policies failed");
651             ret = -1;
652             goto exit;
653          }
654       }
655    }
656
657    /* make valgrind happy */
658    static const char zero = 0;
659    BIO_write(bio, &zero, 1);
660
661    len = BIO_get_mem_data(bio, &bio_mem_data);
662    if (len <= 0)
663    {
664       log_error(LOG_LEVEL_ERROR, "BIO_get_mem_data() returned %ld "
665          "while gathering certificate information", len);
666       ret = -1;
667       goto exit;
668    }
669    encoded_text = html_encode(bio_mem_data);
670    if (encoded_text == NULL)
671    {
672       log_error(LOG_LEVEL_ERROR,
673          "Failed to HTML-encode the certificate information");
674       ret = -1;
675       goto exit;
676    }
677
678    strlcpy(last->info_buf, encoded_text, sizeof(last->info_buf));
679    freez(encoded_text);
680    ret = 0;
681
682 exit:
683    if (bio)
684    {
685       BIO_free(bio);
686    }
687    if (pkey)
688    {
689       EVP_PKEY_free(pkey);
690    }
691    return ret;
692 }
693
694
695 /*********************************************************************
696  *
697  * Function    :  host_to_hash
698  *
699  * Description :  Creates MD5 hash from host name. Host name is loaded
700  *                from structure csp and saved again into it.
701  *
702  * Parameters  :
703  *          1  :  csp = Current client state (buffers, headers, etc...)
704  *
705  * Returns     : -1 => Error while creating hash
706  *                0 => Hash created successfully
707  *
708  *********************************************************************/
709 static int host_to_hash(struct client_state *csp)
710 {
711    int ret = 0;
712
713    memset(csp->http->hash_of_host, 0, sizeof(csp->http->hash_of_host));
714    MD5((unsigned char *)csp->http->host, strlen(csp->http->host),
715       csp->http->hash_of_host);
716
717    /* Converting hash into string with hex */
718    size_t i = 0;
719    for (; i < 16; i++)
720    {
721       if ((ret = sprintf((char *)csp->http->hash_of_host_hex + 2 * i, "%02x",
722          csp->http->hash_of_host[i])) < 0)
723       {
724          log_error(LOG_LEVEL_ERROR, "Sprintf return value: %d", ret);
725          return -1;
726       }
727    }
728
729    return 0;
730 }
731
732
733 /*********************************************************************
734  *
735  * Function    :  create_client_ssl_connection
736  *
737  * Description :  Creates TLS/SSL secured connection with client
738  *
739  * Parameters  :
740  *          1  :  csp = Current client state (buffers, headers, etc...)
741  *
742  * Returns     :  0 on success, negative value if connection wasn't created
743  *                successfully.
744  *
745  *********************************************************************/
746 extern int create_client_ssl_connection(struct client_state *csp)
747 {
748    struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
749    /* Paths to certificates file and key file */
750    char *key_file  = NULL;
751    char *cert_file = NULL;
752    int ret = 0;
753    SSL *ssl;
754
755    /*
756     * Initializing OpenSSL structures for TLS/SSL connection
757     */
758    openssl_init();
759
760    /*
761     * Preparing hash of host for creating certificates
762     */
763    ret = host_to_hash(csp);
764    if (ret != 0)
765    {
766       log_error(LOG_LEVEL_ERROR, "Generating hash of host failed: %d", ret);
767       ret = -1;
768       goto exit;
769    }
770
771    /*
772     * Preparing paths to certificates files and key file
773     */
774    cert_file = make_certs_path(csp->config->certificate_directory,
775       (const char *)csp->http->hash_of_host_hex, CERT_FILE_TYPE);
776    key_file  = make_certs_path(csp->config->certificate_directory,
777       (const char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
778
779    if (cert_file == NULL || key_file == NULL)
780    {
781       ret = -1;
782       goto exit;
783    }
784
785    /*
786     * Generating certificate for requested host. Mutex to prevent
787     * certificate and key inconsistence must be locked.
788     */
789    privoxy_mutex_lock(&certificate_mutex);
790
791    ret = generate_host_certificate(csp);
792    if (ret < 0)
793    {
794       log_error(LOG_LEVEL_ERROR,
795          "generate_host_certificate failed: %d", ret);
796       privoxy_mutex_unlock(&certificate_mutex);
797       ret = -1;
798       goto exit;
799    }
800    privoxy_mutex_unlock(&certificate_mutex);
801
802    if (!(ssl_attr->openssl_attr.ctx = SSL_CTX_new(SSLv23_server_method())))
803    {
804       log_ssl_errors(LOG_LEVEL_ERROR, "Unable to create SSL context");
805       ret = -1;
806       goto exit;
807    }
808
809    /* Set the key and cert */
810    if (SSL_CTX_use_certificate_file(ssl_attr->openssl_attr.ctx,
811          cert_file, SSL_FILETYPE_PEM) != 1)
812    {
813       log_ssl_errors(LOG_LEVEL_ERROR,
814          "Loading webpage certificate %s failed", cert_file);
815       ret = -1;
816       goto exit;
817    }
818
819    if (SSL_CTX_use_PrivateKey_file(ssl_attr->openssl_attr.ctx,
820          key_file, SSL_FILETYPE_PEM) != 1)
821    {
822       log_ssl_errors(LOG_LEVEL_ERROR,
823          "Loading webpage certificate private key %s failed", key_file);
824       ret = -1;
825       goto exit;
826    }
827
828    SSL_CTX_set_options(ssl_attr->openssl_attr.ctx, SSL_OP_NO_SSLv3);
829
830    if (!(ssl_attr->openssl_attr.bio = BIO_new_ssl(ssl_attr->openssl_attr.ctx, 0)))
831    {
832       log_ssl_errors(LOG_LEVEL_ERROR, "Unable to create BIO structure");
833       ret = -1;
834       goto exit;
835    }
836
837    if (BIO_get_ssl(ssl_attr->openssl_attr.bio, &ssl) != 1)
838    {
839       log_ssl_errors(LOG_LEVEL_ERROR, "BIO_get_ssl failed");
840       ret = -1;
841       goto exit;
842    }
843
844    if (!SSL_set_fd(ssl, csp->cfd))
845    {
846       log_ssl_errors(LOG_LEVEL_ERROR, "SSL_set_fd failed");
847       ret = -1;
848       goto exit;
849    }
850
851    if (csp->config->cipher_list != NULL)
852    {
853       if (!SSL_set_cipher_list(ssl, csp->config->cipher_list))
854       {
855          log_ssl_errors(LOG_LEVEL_ERROR,
856             "Setting the cipher list '%s' for the client connection failed",
857             csp->config->cipher_list);
858          ret = -1;
859          goto exit;
860       }
861    }
862
863    /*
864     *  Handshake with client
865     */
866    log_error(LOG_LEVEL_CONNECT,
867       "Performing the TLS/SSL handshake with client. Hash of host: %s",
868       csp->http->hash_of_host_hex);
869    if (BIO_do_handshake(ssl_attr->openssl_attr.bio) != 1)
870    {
871        log_ssl_errors(LOG_LEVEL_ERROR,
872           "The TLS/SSL handshake with the client failed");
873        ret = -1;
874        goto exit;
875    }
876
877    log_error(LOG_LEVEL_CONNECT, "Client successfully connected over %s (%s).",
878       SSL_get_version(ssl), SSL_get_cipher_name(ssl));
879
880    csp->ssl_with_client_is_opened = 1;
881    ret = 0;
882
883 exit:
884    /*
885     * Freeing allocated paths to files
886     */
887    freez(cert_file);
888    freez(key_file);
889
890    /* Freeing structures if connection wasn't created successfully */
891    if (ret < 0)
892    {
893       free_client_ssl_structures(csp);
894    }
895    return ret;
896 }
897
898
899 /*********************************************************************
900  *
901  * Function    :  close_client_ssl_connection
902  *
903  * Description :  Closes TLS/SSL connection with client. This function
904  *                checks if this connection is already created.
905  *
906  * Parameters  :
907  *          1  :  csp = Current client state (buffers, headers, etc...)
908  *
909  * Returns     :  N/A
910  *
911  *********************************************************************/
912 extern void close_client_ssl_connection(struct client_state *csp)
913 {
914    struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
915    SSL *ssl;
916
917    if (csp->ssl_with_client_is_opened == 0)
918    {
919       return;
920    }
921
922    /*
923     * Notifying the peer that the connection is being closed.
924     */
925    BIO_ssl_shutdown(ssl_attr->openssl_attr.bio);
926    if (BIO_get_ssl(ssl_attr->openssl_attr.bio, &ssl) != 1)
927    {
928       log_ssl_errors(LOG_LEVEL_ERROR,
929          "BIO_get_ssl() failed in close_client_ssl_connection()");
930    }
931    else
932    {
933       /*
934        * Pretend we received a shutdown alert so
935        * the BIO_free_all() call later on returns
936        * quickly.
937        */
938       SSL_set_shutdown(ssl, SSL_RECEIVED_SHUTDOWN);
939    }
940    free_client_ssl_structures(csp);
941    csp->ssl_with_client_is_opened = 0;
942 }
943
944
945 /*********************************************************************
946  *
947  * Function    :  free_client_ssl_structures
948  *
949  * Description :  Frees structures used for SSL communication with
950  *                client.
951  *
952  * Parameters  :
953  *          1  :  csp = Current client state (buffers, headers, etc...)
954  *
955  * Returns     :  N/A
956  *
957  *********************************************************************/
958 static void free_client_ssl_structures(struct client_state *csp)
959 {
960    struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
961
962    if (ssl_attr->openssl_attr.bio)
963    {
964       BIO_free_all(ssl_attr->openssl_attr.bio);
965    }
966    if (ssl_attr->openssl_attr.ctx)
967    {
968       SSL_CTX_free(ssl_attr->openssl_attr.ctx);
969    }
970 }
971
972
973 /*********************************************************************
974  *
975  * Function    :  close_server_ssl_connection
976  *
977  * Description :  Closes TLS/SSL connection with server. This function
978  *                checks if this connection is already opened.
979  *
980  * Parameters  :
981  *          1  :  csp = Current client state (buffers, headers, etc...)
982  *
983  * Returns     :  N/A
984  *
985  *********************************************************************/
986 extern void close_server_ssl_connection(struct client_state *csp)
987 {
988    struct ssl_attr *ssl_attr = &csp->ssl_server_attr;
989    SSL *ssl;
990
991    if (csp->ssl_with_server_is_opened == 0)
992    {
993       return;
994    }
995
996    /*
997    * Notifying the peer that the connection is being closed.
998    */
999    BIO_ssl_shutdown(ssl_attr->openssl_attr.bio);
1000    if (BIO_get_ssl(ssl_attr->openssl_attr.bio, &ssl) != 1)
1001    {
1002       log_ssl_errors(LOG_LEVEL_ERROR,
1003          "BIO_get_ssl() failed in close_server_ssl_connection()");
1004    }
1005    else
1006    {
1007       /*
1008        * Pretend we received a shutdown alert so
1009        * the BIO_free_all() call later on returns
1010        * quickly.
1011        */
1012       SSL_set_shutdown(ssl, SSL_RECEIVED_SHUTDOWN);
1013    }
1014    free_server_ssl_structures(csp);
1015    csp->ssl_with_server_is_opened = 0;
1016 }
1017
1018
1019 /*********************************************************************
1020  *
1021  * Function    :  create_server_ssl_connection
1022  *
1023  * Description :  Creates TLS/SSL secured connection with server.
1024  *
1025  * Parameters  :
1026  *          1  :  csp = Current client state (buffers, headers, etc...)
1027  *
1028  * Returns     :  0 on success, negative value if connection wasn't created
1029  *                successfully.
1030  *
1031  *********************************************************************/
1032 extern int create_server_ssl_connection(struct client_state *csp)
1033 {
1034    openssl_connection_attr *ssl_attrs = &csp->ssl_server_attr.openssl_attr;
1035    int ret = 0;
1036    char *trusted_cas_file = NULL;
1037    STACK_OF(X509) *chain;
1038    SSL *ssl;
1039
1040    csp->server_cert_verification_result = SSL_CERT_NOT_VERIFIED;
1041    csp->server_certs_chain.next = NULL;
1042
1043    /* Setting path to file with trusted CAs */
1044    trusted_cas_file = csp->config->trusted_cas_file;
1045
1046    ssl_attrs->ctx = SSL_CTX_new(SSLv23_method());
1047    if (!ssl_attrs->ctx)
1048    {
1049       log_ssl_errors(LOG_LEVEL_ERROR, "SSL context creation failed");
1050       ret = -1;
1051       goto exit;
1052    }
1053
1054    /*
1055     * Loading file with trusted CAs
1056     */
1057    if (!SSL_CTX_load_verify_locations(ssl_attrs->ctx, trusted_cas_file, NULL))
1058    {
1059       log_ssl_errors(LOG_LEVEL_ERROR, "Loading trusted CAs file %s failed",
1060          trusted_cas_file);
1061       ret = -1;
1062       goto exit;
1063    }
1064
1065    SSL_CTX_set_verify(ssl_attrs->ctx, SSL_VERIFY_NONE, NULL);
1066    SSL_CTX_set_options(ssl_attrs->ctx, SSL_OP_NO_SSLv3);
1067
1068    if (!(ssl_attrs->bio = BIO_new_ssl(ssl_attrs->ctx, 1)))
1069    {
1070       log_ssl_errors(LOG_LEVEL_ERROR, "Unable to create BIO structure");
1071       ret = -1;
1072       goto exit;
1073    }
1074
1075    if (BIO_get_ssl(ssl_attrs->bio, &ssl) != 1)
1076    {
1077       log_ssl_errors(LOG_LEVEL_ERROR, "BIO_get_ssl failed");
1078       ret = -1;
1079       goto exit;
1080    }
1081
1082    if (!SSL_set_fd(ssl, csp->server_connection.sfd))
1083    {
1084       log_ssl_errors(LOG_LEVEL_ERROR, "SSL_set_fd failed");
1085       ret = -1;
1086       goto exit;
1087    }
1088
1089    if (csp->config->cipher_list != NULL)
1090    {
1091       if (!SSL_set_cipher_list(ssl, csp->config->cipher_list))
1092       {
1093          log_ssl_errors(LOG_LEVEL_ERROR,
1094             "Setting the cipher list '%s' for the server connection failed",
1095             csp->config->cipher_list);
1096          ret = -1;
1097          goto exit;
1098       }
1099    }
1100
1101    /*
1102     * Set the hostname to check against the received server certificate
1103     */
1104 #if OPENSSL_VERSION_NUMBER > 0x10100000L
1105    if (!SSL_set1_host(ssl, csp->http->host))
1106    {
1107       log_ssl_errors(LOG_LEVEL_ERROR, "SSL_set1_host failed");
1108       ret = -1;
1109       goto exit;
1110    }
1111 #else
1112    if (host_is_ip_address(csp->http->host))
1113    {
1114       if (X509_VERIFY_PARAM_set1_ip_asc(ssl->param,  csp->http->host) != 1)
1115       {
1116          log_ssl_errors(LOG_LEVEL_ERROR,
1117             "X509_VERIFY_PARAM_set1_ip_asc() failed");
1118          ret = -1;
1119          goto exit;
1120       }
1121    }
1122    else
1123    {
1124       if (X509_VERIFY_PARAM_set1_host(ssl->param,  csp->http->host, 0) != 1)
1125       {
1126          log_ssl_errors(LOG_LEVEL_ERROR,
1127             "X509_VERIFY_PARAM_set1_host() failed");
1128          ret = -1;
1129          goto exit;
1130       }
1131    }
1132 #endif
1133    /* SNI extension */
1134    if (!SSL_set_tlsext_host_name(ssl, csp->http->host))
1135    {
1136       log_ssl_errors(LOG_LEVEL_ERROR, "SSL_set_tlsext_host_name failed");
1137       ret = -1;
1138       goto exit;
1139    }
1140
1141    /*
1142     * Handshake with server
1143     */
1144    log_error(LOG_LEVEL_CONNECT,
1145       "Performing the TLS/SSL handshake with the server");
1146
1147    if (BIO_do_handshake(ssl_attrs->bio) != 1)
1148    {
1149       log_ssl_errors(LOG_LEVEL_ERROR,
1150          "The TLS/SSL handshake with the server failed");
1151       ret = -1;
1152       goto exit;
1153    }
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    BIGNUM *exp;
1485    RSA *rsa;
1486    EVP_PKEY *key;
1487
1488    key_file_path = make_certs_path(csp->config->certificate_directory,
1489       (char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
1490    if (key_file_path == NULL)
1491    {
1492       return -1;
1493    }
1494
1495    /*
1496     * Test if key already exists. If so, we don't have to create it again.
1497     */
1498    if (file_exists(key_file_path) == 1)
1499    {
1500       freez(key_file_path);
1501       return 0;
1502    }
1503
1504    exp = BN_new();
1505    rsa = RSA_new();
1506    key = EVP_PKEY_new();
1507    if (exp == NULL || rsa == NULL || key == NULL)
1508    {
1509       log_ssl_errors(LOG_LEVEL_ERROR, "RSA key memory allocation failure");
1510       ret = -1;
1511       goto exit;
1512    }
1513
1514    if (BN_set_word(exp, RSA_KEY_PUBLIC_EXPONENT) != 1)
1515    {
1516       log_ssl_errors(LOG_LEVEL_ERROR, "Setting RSA key exponent failed");
1517       ret = -1;
1518       goto exit;
1519    }
1520
1521    ret = RSA_generate_key_ex(rsa, RSA_KEYSIZE, exp, NULL);
1522    if (ret == 0)
1523    {
1524       log_ssl_errors(LOG_LEVEL_ERROR, "RSA key generation failure");
1525       ret = -1;
1526       goto exit;
1527    }
1528
1529    if (!EVP_PKEY_set1_RSA(key, rsa))
1530    {
1531       log_ssl_errors(LOG_LEVEL_ERROR,
1532          "Error assigning RSA key pair to PKEY structure");
1533       ret = -1;
1534       goto exit;
1535    }
1536
1537    /*
1538     * Exporting private key into file
1539     */
1540    if ((ret = write_private_key(key, key_buf, key_file_path)) < 0)
1541    {
1542       log_error(LOG_LEVEL_ERROR,
1543          "Writing private key into file %s failed", key_file_path);
1544       ret = -1;
1545       goto exit;
1546    }
1547
1548 exit:
1549    /*
1550     * Freeing used variables
1551     */
1552    if (exp)
1553    {
1554       BN_free(exp);
1555    }
1556    if (rsa)
1557    {
1558       RSA_free(rsa);
1559    }
1560    if (key)
1561    {
1562       EVP_PKEY_free(key);
1563    }
1564    freez(key_file_path);
1565
1566    return ret;
1567 }
1568
1569
1570 /*********************************************************************
1571  *
1572  * Function    :  ssl_certificate_load
1573  *
1574  * Description :  Loads certificate from file.
1575  *
1576  * Parameters  :
1577  *          1  :  cert_path = The certificate path to load
1578  *
1579  * Returns     :   NULL => error loading certificate,
1580  *                   pointer to certificate instance otherwise
1581  *
1582  *********************************************************************/
1583 static X509 *ssl_certificate_load(const char *cert_path)
1584 {
1585    X509 *cert = NULL;
1586    FILE *cert_f = NULL;
1587
1588    if (!(cert_f = fopen(cert_path, "r")))
1589    {
1590       log_error(LOG_LEVEL_ERROR,
1591          "Error opening certificate file %s: %s", cert_path, strerror(errno));
1592       return NULL;
1593    }
1594
1595    if (!(cert = PEM_read_X509(cert_f, NULL, NULL, NULL)))
1596    {
1597       log_ssl_errors(LOG_LEVEL_ERROR,
1598          "Error reading certificate file %s", cert_path);
1599    }
1600
1601    close_file_stream(cert_f, cert_path);
1602    return cert;
1603 }
1604
1605
1606 /*********************************************************************
1607  *
1608  * Function    :  ssl_certificate_is_invalid
1609  *
1610  * Description :  Checks whether or not a certificate is valid.
1611  *                Currently only checks that the certificate can be
1612  *                parsed and that the "valid to" date is in the future.
1613  *
1614  * Parameters  :
1615  *          1  :  cert_file = The certificate to check
1616  *
1617  * Returns     :   0 => The certificate is valid.
1618  *                 1 => The certificate is invalid
1619  *
1620  *********************************************************************/
1621 static int ssl_certificate_is_invalid(const char *cert_file)
1622 {
1623    int ret;
1624
1625    X509 *cert = NULL;
1626
1627    if (!(cert = ssl_certificate_load(cert_file)))
1628    {
1629       return 1;
1630    }
1631
1632    ret = X509_cmp_current_time(X509_get_notAfter(cert));
1633    if (ret == 0)
1634    {
1635       log_ssl_errors(LOG_LEVEL_ERROR,
1636          "Error checking certificate %s validity", cert_file);
1637       ret = -1;
1638    }
1639
1640    X509_free(cert);
1641
1642    return ret == -1 ? 1 : 0;
1643 }
1644
1645
1646 /*********************************************************************
1647  *
1648  * Function    :  set_x509_ext
1649  *
1650  * Description :  Sets the X509V3 extension data
1651  *
1652  * Parameters  :
1653  *          1  :  cert = The certificate to modify
1654  *          2  :  issuer = Issuer certificate
1655  *          3  :  nid = OpenSSL NID
1656  *          4  :  value = extension value
1657  *
1658  * Returns     :   0 => Error while setting extension data
1659  *                 1 => It worked
1660  *
1661  *********************************************************************/
1662 static int set_x509_ext(X509 *cert, X509 *issuer, int nid, char *value)
1663 {
1664    X509_EXTENSION *ext = NULL;
1665    X509V3_CTX ctx;
1666    int ret = 0;
1667
1668    X509V3_set_ctx(&ctx, issuer, cert, NULL, NULL, 0);
1669    ext = X509V3_EXT_conf_nid(NULL, &ctx, nid, value);
1670    if (!ext)
1671    {
1672       log_ssl_errors(LOG_LEVEL_ERROR, "X509V3_EXT_conf_nid failure");
1673       goto exit;
1674    }
1675
1676    if (!X509_add_ext(cert, ext, -1))
1677    {
1678       log_ssl_errors(LOG_LEVEL_ERROR, "X509_add_ext failure");
1679       goto exit;
1680    }
1681
1682    ret = 1;
1683 exit:
1684    if (ext)
1685    {
1686       X509_EXTENSION_free(ext);
1687    }
1688    return ret;
1689 }
1690
1691
1692 /*********************************************************************
1693  *
1694  * Function    :  set_subject_alternative_name
1695  *
1696  * Description :  Sets the Subject Alternative Name extension to a cert
1697  *
1698  * Parameters  :
1699  *          1  :  cert = The certificate to modify
1700  *          2  :  issuer = Issuer certificate
1701  *          3  :  hostname = The hostname to add
1702  *
1703  * Returns     :   0 => Error while creating certificate.
1704  *                 1 => It worked
1705  *
1706  *********************************************************************/
1707 static int set_subject_alternative_name(X509 *cert, X509 *issuer, const char *hostname)
1708 {
1709    size_t altname_len = strlen(hostname) + sizeof(CERTIFICATE_ALT_NAME_PREFIX);
1710    char alt_name_buf[altname_len];
1711
1712    snprintf(alt_name_buf, sizeof(alt_name_buf),
1713       CERTIFICATE_ALT_NAME_PREFIX"%s", hostname);
1714    return set_x509_ext(cert, issuer, NID_subject_alt_name, alt_name_buf);
1715 }
1716
1717
1718 /*********************************************************************
1719  *
1720  * Function    :  generate_host_certificate
1721  *
1722  * Description :  Creates certificate file in presetted directory.
1723  *                If certificate already exists, no other certificate
1724  *                will be created. Subject of certificate is named
1725  *                by csp->http->host from parameter. This function also
1726  *                triggers generating of private key for new certificate.
1727  *
1728  * Parameters  :
1729  *          1  :  csp = Current client state (buffers, headers, etc...)
1730  *
1731  * Returns     :  -1 => Error while creating certificate.
1732  *                 0 => Certificate already exists.
1733  *                 1 => Certificate created
1734  *
1735  *********************************************************************/
1736 static int generate_host_certificate(struct client_state *csp)
1737 {
1738    char *key_buf = NULL;    /* Buffer for created key */
1739    X509 *issuer_cert = NULL;
1740    X509 *cert = NULL;
1741    BIO *pk_bio = NULL;
1742    EVP_PKEY *loaded_subject_key = NULL;
1743    EVP_PKEY *loaded_issuer_key = NULL;
1744    X509_NAME *issuer_name;
1745    X509_NAME *subject_name = NULL;
1746    ASN1_TIME *asn_time = NULL;
1747    ASN1_INTEGER *serial = NULL;
1748    BIGNUM *serial_num = NULL;
1749
1750    int ret = 0;
1751    cert_options cert_opt;
1752    char cert_valid_from[VALID_DATETIME_BUFLEN];
1753    char cert_valid_to[VALID_DATETIME_BUFLEN];
1754
1755    /* Paths to keys and certificates needed to create certificate */
1756    cert_opt.issuer_key  = NULL;
1757    cert_opt.subject_key = NULL;
1758    cert_opt.issuer_crt  = NULL;
1759
1760    cert_opt.output_file = make_certs_path(csp->config->certificate_directory,
1761       (const char *)csp->http->hash_of_host_hex, CERT_FILE_TYPE);
1762    if (cert_opt.output_file == NULL)
1763    {
1764       return -1;
1765    }
1766
1767    cert_opt.subject_key = make_certs_path(csp->config->certificate_directory,
1768       (const char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
1769    if (cert_opt.subject_key == NULL)
1770    {
1771       freez(cert_opt.output_file);
1772       return -1;
1773    }
1774
1775    if (enforce_sane_certificate_state(cert_opt.output_file,
1776          cert_opt.subject_key))
1777    {
1778       freez(cert_opt.output_file);
1779       freez(cert_opt.subject_key);
1780
1781       return -1;
1782    }
1783
1784    if (file_exists(cert_opt.output_file) == 1)
1785    {
1786       /* The file exists, but is it valid? */
1787       if (ssl_certificate_is_invalid(cert_opt.output_file))
1788       {
1789          log_error(LOG_LEVEL_CONNECT,
1790             "Certificate %s is no longer valid. Removing it.",
1791             cert_opt.output_file);
1792          if (unlink(cert_opt.output_file))
1793          {
1794             log_error(LOG_LEVEL_ERROR, "Failed to unlink %s: %E",
1795                cert_opt.output_file);
1796
1797             freez(cert_opt.output_file);
1798             freez(cert_opt.subject_key);
1799
1800             return -1;
1801          }
1802          if (unlink(cert_opt.subject_key))
1803          {
1804             log_error(LOG_LEVEL_ERROR, "Failed to unlink %s: %E",
1805                cert_opt.subject_key);
1806
1807             freez(cert_opt.output_file);
1808             freez(cert_opt.subject_key);
1809
1810             return -1;
1811          }
1812       }
1813       else
1814       {
1815          freez(cert_opt.output_file);
1816          freez(cert_opt.subject_key);
1817
1818          return 0;
1819       }
1820    }
1821
1822    /*
1823     * Create key for requested host
1824     */
1825    int subject_key_len = generate_key(csp, &key_buf);
1826    if (subject_key_len < 0)
1827    {
1828       freez(cert_opt.output_file);
1829       freez(cert_opt.subject_key);
1830       log_error(LOG_LEVEL_ERROR, "Key generating failed");
1831       return -1;
1832    }
1833
1834    /*
1835     * Converting unsigned long serial number to char * serial number.
1836     * We must compute length of serial number in string + terminating null.
1837     */
1838    unsigned long certificate_serial = get_certificate_serial(csp);
1839    unsigned long certificate_serial_time = (unsigned long)time(NULL);
1840    int serial_num_size = snprintf(NULL, 0, "%lu%lu",
1841       certificate_serial_time, certificate_serial) + 1;
1842    if (serial_num_size <= 0)
1843    {
1844       serial_num_size = 1;
1845    }
1846
1847    char serial_num_text[serial_num_size];  /* Buffer for serial number */
1848    ret = snprintf(serial_num_text, (size_t)serial_num_size, "%lu%lu",
1849       certificate_serial_time, certificate_serial);
1850    if (ret < 0 || ret >= serial_num_size)
1851    {
1852       log_error(LOG_LEVEL_ERROR,
1853          "Converting certificate serial number into string failed");
1854       ret = -1;
1855       goto exit;
1856    }
1857
1858    /*
1859     * Preparing parameters for certificate
1860     */
1861    subject_name = X509_NAME_new();
1862    if (!subject_name)
1863    {
1864       log_ssl_errors(LOG_LEVEL_ERROR, "RSA key memory allocation failure");
1865       ret = -1;
1866       goto exit;
1867    }
1868
1869    if (!X509_NAME_add_entry_by_txt(subject_name, CERT_PARAM_COMMON_NAME_FCODE,
1870          MBSTRING_ASC, (void *)csp->http->host, -1, -1, 0))
1871    {
1872       log_ssl_errors(LOG_LEVEL_ERROR,
1873          "X509 subject name (code: %s, val: %s) error",
1874          CERT_PARAM_COMMON_NAME_FCODE, csp->http->host);
1875       ret = -1;
1876       goto exit;
1877    }
1878    if (!X509_NAME_add_entry_by_txt(subject_name, CERT_PARAM_ORGANIZATION_FCODE,
1879          MBSTRING_ASC, (void *)csp->http->host, -1, -1, 0))
1880    {
1881       log_ssl_errors(LOG_LEVEL_ERROR,
1882          "X509 subject name (code: %s, val: %s) error",
1883          CERT_PARAM_ORGANIZATION_FCODE, csp->http->host);
1884       ret = -1;
1885       goto exit;
1886    }
1887    if (!X509_NAME_add_entry_by_txt(subject_name, CERT_PARAM_ORG_UNIT_FCODE,
1888          MBSTRING_ASC, (void *)csp->http->host, -1, -1, 0))
1889    {
1890       log_ssl_errors(LOG_LEVEL_ERROR,
1891          "X509 subject name (code: %s, val: %s) error",
1892          CERT_PARAM_ORG_UNIT_FCODE, csp->http->host);
1893       ret = -1;
1894       goto exit;
1895    }
1896    if (!X509_NAME_add_entry_by_txt(subject_name, CERT_PARAM_COUNTRY_FCODE,
1897          MBSTRING_ASC, (void *)CERT_PARAM_COUNTRY_CODE, -1, -1, 0))
1898    {
1899       log_ssl_errors(LOG_LEVEL_ERROR,
1900          "X509 subject name (code: %s, val: %s) error",
1901          CERT_PARAM_COUNTRY_FCODE, csp->http->host);
1902       ret = -1;
1903       goto exit;
1904    }
1905
1906    cert_opt.issuer_crt = csp->config->ca_cert_file;
1907    cert_opt.issuer_key = csp->config->ca_key_file;
1908
1909    if (get_certificate_valid_from_date(cert_valid_from,
1910          sizeof(cert_valid_from), VALID_DATETIME_FMT)
1911     || get_certificate_valid_to_date(cert_valid_to,
1912          sizeof(cert_valid_to), VALID_DATETIME_FMT))
1913    {
1914       log_error(LOG_LEVEL_ERROR, "Generating one of the validity dates failed");
1915       ret = -1;
1916       goto exit;
1917    }
1918
1919    cert_opt.subject_pwd = CERT_SUBJECT_PASSWORD;
1920    cert_opt.issuer_pwd  = csp->config->ca_password;
1921    cert_opt.not_before  = cert_valid_from;
1922    cert_opt.not_after   = cert_valid_to;
1923    cert_opt.serial      = serial_num_text;
1924    cert_opt.max_pathlen = -1;
1925
1926    /*
1927     * Test if the private key was already created.
1928     * XXX: Can this still happen?
1929     */
1930    if (subject_key_len == 0)
1931    {
1932       log_error(LOG_LEVEL_ERROR, "Subject key was already created");
1933       ret = 0;
1934       goto exit;
1935    }
1936
1937    /*
1938     * Parse serial to MPI
1939     */
1940    serial_num = BN_new();
1941    if (!serial_num)
1942    {
1943       log_error(LOG_LEVEL_ERROR, "generate_host_certificate: memory error");
1944       ret = -1;
1945       goto exit;
1946    }
1947    if (!BN_dec2bn(&serial_num, cert_opt.serial))
1948    {
1949       log_ssl_errors(LOG_LEVEL_ERROR, "Failed to parse serial %s", cert_opt.serial);
1950       ret = -1;
1951       goto exit;
1952    }
1953
1954    if (!(serial = BN_to_ASN1_INTEGER(serial_num, NULL)))
1955    {
1956       log_ssl_errors(LOG_LEVEL_ERROR, "Failed to generate serial ASN1 representation");
1957       ret = -1;
1958       goto exit;
1959    }
1960
1961    /*
1962     * Loading certificates
1963     */
1964    if (!(issuer_cert = ssl_certificate_load(cert_opt.issuer_crt)))
1965    {
1966       log_error(LOG_LEVEL_ERROR, "Loading issuer certificate %s failed",
1967          cert_opt.issuer_crt);
1968       ret = -1;
1969       goto exit;
1970    }
1971
1972    issuer_name = X509_get_issuer_name(issuer_cert);
1973
1974    /*
1975     * Loading keys from file or from buffer
1976     */
1977    if (key_buf != NULL && subject_key_len > 0)
1978    {
1979       pk_bio = BIO_new_mem_buf(key_buf, subject_key_len);
1980    }
1981    else if (!(pk_bio = BIO_new_file(cert_opt.subject_key, "r")))
1982    {
1983       log_ssl_errors(LOG_LEVEL_ERROR,
1984          "Failure opening subject key %s BIO", cert_opt.subject_key);
1985       ret = -1;
1986       goto exit;
1987    }
1988
1989    loaded_subject_key = PEM_read_bio_PrivateKey(pk_bio, NULL, NULL,
1990       (void *)cert_opt.subject_pwd);
1991    if (!loaded_subject_key)
1992    {
1993       log_ssl_errors(LOG_LEVEL_ERROR, "Parsing subject key %s failed",
1994          cert_opt.subject_key);
1995       ret = -1;
1996       goto exit;
1997    }
1998
1999    if (!BIO_free(pk_bio))
2000    {
2001       log_ssl_errors(LOG_LEVEL_ERROR, "Error closing subject key BIO");
2002    }
2003
2004    if (!(pk_bio = BIO_new_file(cert_opt.issuer_key, "r")))
2005    {
2006       log_ssl_errors(LOG_LEVEL_ERROR, "Failure opening issuer key %s BIO",
2007          cert_opt.issuer_key);
2008       ret = -1;
2009       goto exit;
2010    }
2011
2012    loaded_issuer_key = PEM_read_bio_PrivateKey(pk_bio, NULL, NULL,
2013       (void *)cert_opt.issuer_pwd);
2014    if (!loaded_issuer_key)
2015    {
2016       log_ssl_errors(LOG_LEVEL_ERROR, "Parsing issuer key %s failed",
2017          cert_opt.subject_key);
2018       ret = -1;
2019       goto exit;
2020    }
2021
2022    cert = X509_new();
2023    if (!cert)
2024    {
2025       log_ssl_errors(LOG_LEVEL_ERROR, "Certificate allocation error");
2026       ret = -1;
2027       goto exit;
2028    }
2029
2030    if (!X509_set_version(cert, CERTIFICATE_VERSION))
2031    {
2032       log_ssl_errors(LOG_LEVEL_ERROR, "X509_set_version failed");
2033       ret = -1;
2034       goto exit;
2035    }
2036
2037    /*
2038     * Setting parameters of signed certificate
2039     */
2040    if (!X509_set_pubkey(cert, loaded_subject_key))
2041    {
2042       log_ssl_errors(LOG_LEVEL_ERROR,
2043          "Setting public key in signed certificate failed");
2044       ret = -1;
2045       goto exit;
2046    }
2047
2048    if (!X509_set_subject_name(cert, subject_name))
2049    {
2050       log_ssl_errors(LOG_LEVEL_ERROR,
2051          "Setting subject name in signed certificate failed");
2052       ret = -1;
2053       goto exit;
2054    }
2055
2056    if (!X509_set_issuer_name(cert, issuer_name))
2057    {
2058       log_ssl_errors(LOG_LEVEL_ERROR,
2059          "Setting issuer name in signed certificate failed");
2060       ret = -1;
2061       goto exit;
2062    }
2063
2064    if (!X509_set_serialNumber(cert, serial))
2065    {
2066       log_ssl_errors(LOG_LEVEL_ERROR,
2067          "Setting serial number in signed certificate failed");
2068       ret = -1;
2069       goto exit;
2070    }
2071
2072    asn_time = ASN1_TIME_new();
2073    if (!asn_time)
2074    {
2075       log_ssl_errors(LOG_LEVEL_ERROR, "ASN1 time memory allocation failure");
2076       ret = -1;
2077       goto exit;
2078    }
2079
2080    if (!ASN1_TIME_set_string(asn_time, cert_opt.not_after))
2081    {
2082       log_ssl_errors(LOG_LEVEL_ERROR, "ASN1 time [%s] encode error", cert_opt.not_after);
2083       ret = -1;
2084       goto exit;
2085    }
2086
2087    if (!X509_set1_notAfter(cert, asn_time))
2088    {
2089       log_ssl_errors(LOG_LEVEL_ERROR,
2090          "Setting valid not after in signed certificate failed");
2091       ret = -1;
2092       goto exit;
2093    }
2094
2095    if (!ASN1_TIME_set_string(asn_time, cert_opt.not_before))
2096    {
2097       log_ssl_errors(LOG_LEVEL_ERROR, "ASN1 time encode error");
2098       ret = -1;
2099       goto exit;
2100    }
2101
2102    if (!X509_set1_notBefore(cert, asn_time))
2103    {
2104       log_ssl_errors(LOG_LEVEL_ERROR,
2105          "Setting valid not before in signed certificate failed");
2106       ret = -1;
2107       goto exit;
2108    }
2109
2110    if (!set_x509_ext(cert, issuer_cert, NID_basic_constraints, CERTIFICATE_BASIC_CONSTRAINTS))
2111    {
2112       log_ssl_errors(LOG_LEVEL_ERROR, "Setting the basicConstraints extension "
2113          "in signed certificate failed");
2114       ret = -1;
2115       goto exit;
2116    }
2117
2118    if (!set_x509_ext(cert, issuer_cert, NID_subject_key_identifier, CERTIFICATE_SUBJECT_KEY))
2119    {
2120       log_ssl_errors(LOG_LEVEL_ERROR,
2121          "Setting the Subject Key Identifier extension failed");
2122       ret = -1;
2123       goto exit;
2124    }
2125
2126    if (!set_x509_ext(cert, issuer_cert, NID_authority_key_identifier, CERTIFICATE_AUTHORITY_KEY))
2127    {
2128       log_ssl_errors(LOG_LEVEL_ERROR,
2129          "Setting the Authority Key Identifier extension failed");
2130       ret = -1;
2131       goto exit;
2132    }
2133
2134    if (!host_is_ip_address(csp->http->host) &&
2135        !set_subject_alternative_name(cert, issuer_cert, csp->http->host))
2136    {
2137       log_ssl_errors(LOG_LEVEL_ERROR,
2138          "Setting the Subject Alt Name extension failed");
2139       ret = -1;
2140       goto exit;
2141    }
2142
2143    if (!X509_sign(cert, loaded_issuer_key, EVP_sha256()))
2144    {
2145       log_ssl_errors(LOG_LEVEL_ERROR, "Signing certificate failed");
2146       ret = -1;
2147       goto exit;
2148    }
2149
2150    /*
2151     * Writing certificate into file
2152     */
2153    if (write_certificate(cert, cert_opt.output_file) < 0)
2154    {
2155       log_error(LOG_LEVEL_ERROR, "Writing certificate into file failed");
2156       ret = -1;
2157       goto exit;
2158    }
2159
2160    ret = 1;
2161
2162 exit:
2163    /*
2164     * Freeing used structures
2165     */
2166    if (issuer_cert)
2167    {
2168       X509_free(issuer_cert);
2169    }
2170    if (cert)
2171    {
2172       X509_free(cert);
2173    }
2174    if (pk_bio && !BIO_free(pk_bio))
2175    {
2176       log_ssl_errors(LOG_LEVEL_ERROR, "Error closing pk BIO");
2177    }
2178    if (loaded_subject_key)
2179    {
2180       EVP_PKEY_free(loaded_subject_key);
2181    }
2182    if (loaded_issuer_key)
2183    {
2184       EVP_PKEY_free(loaded_issuer_key);
2185    }
2186    if (subject_name)
2187    {
2188       X509_NAME_free(subject_name);
2189    }
2190    if (asn_time)
2191    {
2192       ASN1_TIME_free(asn_time);
2193    }
2194    if (serial_num)
2195    {
2196       BN_free(serial_num);
2197    }
2198    if (serial)
2199    {
2200       ASN1_INTEGER_free(serial);
2201    }
2202    freez(cert_opt.subject_key);
2203    freez(cert_opt.output_file);
2204    freez(key_buf);
2205
2206    return ret;
2207 }
2208
2209
2210 /*********************************************************************
2211  *
2212  * Function    :  ssl_crt_verify_info
2213  *
2214  * Description :  Returns an informational string about the verification
2215  *                status of a certificate.
2216  *
2217  * Parameters  :
2218  *          1  :  buf = Buffer to write to
2219  *          2  :  size = Maximum size of buffer
2220  *          3  :  csp = client state
2221  *
2222  * Returns     :  N/A
2223  *
2224  *********************************************************************/
2225 extern void ssl_crt_verify_info(char *buf, size_t size, struct client_state *csp)
2226 {
2227    strncpy(buf, X509_verify_cert_error_string(csp->server_cert_verification_result), size);
2228    buf[size - 1] = 0;
2229 }
2230
2231
2232 #ifdef FEATURE_GRACEFUL_TERMINATION
2233 /*********************************************************************
2234  *
2235  * Function    :  ssl_release
2236  *
2237  * Description :  Release all SSL resources
2238  *
2239  * Parameters  :
2240  *
2241  * Returns     :  N/A
2242  *
2243  *********************************************************************/
2244 extern void ssl_release(void)
2245 {
2246    if (ssl_inited == 1)
2247    {
2248 #if OPENSSL_VERSION_NUMBER >= 0x1000200fL
2249 #ifndef LIBRESSL_VERSION_NUMBER
2250 #ifndef OPENSSL_NO_COMP
2251       SSL_COMP_free_compression_methods();
2252 #endif
2253 #endif
2254 #endif
2255       CONF_modules_free();
2256       CONF_modules_unload(1);
2257 #ifndef OPENSSL_NO_COMP
2258       COMP_zlib_cleanup();
2259 #endif
2260
2261       ERR_free_strings();
2262       EVP_cleanup();
2263
2264       CRYPTO_cleanup_all_ex_data();
2265    }
2266 }
2267 #endif /* def FEATURE_GRACEFUL_TERMINATION */