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