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