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