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