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