Disable fast-redirect for archive.softwareheritage.org/
[privoxy.git] / wolfssl.c
1 /*********************************************************************
2  *
3  * File        :  $Source: /cvsroot/ijbswa/current/wolfssl.c,v $
4  *
5  * Purpose     :  File with TLS/SSL extension. Contains methods for
6  *                creating, using and closing TLS/SSL connections
7  *                using wolfSSL.
8  *
9  * Copyright   :  Copyright (C) 2018-2024 by Fabian Keil <fk@fabiankeil.de>
10  *                Copyright (C) 2020 Maxim Antonov <mantonov@gmail.com>
11  *                Copyright (C) 2017 Vaclav Svec. FIT CVUT.
12  *
13  *                This program is free software; you can redistribute it
14  *                and/or modify it under the terms of the GNU General
15  *                Public License as published by the Free Software
16  *                Foundation; either version 2 of the License, or (at
17  *                your option) any later version.
18  *
19  *                This program is distributed in the hope that it will
20  *                be useful, but WITHOUT ANY WARRANTY; without even the
21  *                implied warranty of MERCHANTABILITY or FITNESS FOR A
22  *                PARTICULAR PURPOSE.  See the GNU General Public
23  *                License for more details.
24  *
25  *                The GNU General Public License should be included with
26  *                this file.  If not, you can view it at
27  *                http://www.gnu.org/copyleft/gpl.html
28  *                or write to the Free Software Foundation, Inc., 59
29  *                Temple Place - Suite 330, Boston, MA  02111-1307, USA.
30  *
31  *********************************************************************/
32
33 #include <string.h>
34 #include <unistd.h>
35 #include <assert.h>
36 #include "config.h"
37
38 #include <wolfssl/options.h>
39 #include <wolfssl/openssl/x509v3.h>
40 #include <wolfssl/openssl/pem.h>
41 #include <wolfssl/ssl.h>
42 #include <wolfssl/wolfcrypt/coding.h>
43 #include <wolfssl/wolfcrypt/rsa.h>
44
45 #include "project.h"
46 #include "miscutil.h"
47 #include "errlog.h"
48 #include "encode.h"
49 #include "jcc.h"
50 #include "jbsockets.h"
51 #include "ssl.h"
52 #include "ssl_common.h"
53
54 static int ssl_certificate_is_invalid(const char *cert_file);
55 static int generate_host_certificate(struct client_state *csp,
56    const char *certificate_path, const char *key_path);
57 static void free_client_ssl_structures(struct client_state *csp);
58 static void free_server_ssl_structures(struct client_state *csp);
59 static int ssl_store_cert(struct client_state *csp, X509 *crt);
60 static void log_ssl_errors(int debuglevel, const char* fmt, ...) __attribute__((format(printf, 2, 3)));
61
62 static int wolfssl_initialized = 0;
63
64 /*
65  * Whether or not sharing the RNG is thread-safe
66  * doesn't matter because we only use it with
67  * the certificate_mutex locked.
68  */
69 static WC_RNG wolfssl_rng;
70
71 #ifndef WOLFSSL_ALT_CERT_CHAINS
72 /*
73  * Without WOLFSSL_ALT_CERT_CHAINS wolfSSL will reject valid
74  * certificates if the certificate chain contains CA certificates
75  * that are "only" signed by trusted CA certificates but aren't
76  * trusted CAs themselves.
77  */
78 #warning wolfSSL has been compiled without WOLFSSL_ALT_CERT_CHAINS
79 #endif
80
81 /*********************************************************************
82  *
83  * Function    :  wolfssl_init
84  *
85  * Description :  Initializes wolfSSL library once
86  *
87  * Parameters  :  N/A
88  *
89  * Returns     :  N/A
90  *
91  *********************************************************************/
92 static void wolfssl_init(void)
93 {
94    if (wolfssl_initialized == 0)
95    {
96       privoxy_mutex_lock(&ssl_init_mutex);
97       if (wolfssl_initialized == 0)
98       {
99          if (wolfSSL_Init() != WOLFSSL_SUCCESS)
100          {
101             log_error(LOG_LEVEL_FATAL, "Failed to initialize wolfSSL");
102          }
103          wc_InitRng(&wolfssl_rng);
104          wolfssl_initialized = 1;
105       }
106       privoxy_mutex_unlock(&ssl_init_mutex);
107    }
108 }
109
110
111 /*********************************************************************
112  *
113  * Function    :  is_ssl_pending
114  *
115  * Description :  Tests if there are some waiting data on ssl connection.
116  *                Only considers data that has actually been received
117  *                locally and ignores data that is still on the fly
118  *                or has not yet been sent by the remote end.
119  *
120  * Parameters  :
121  *          1  :  ssl_attr = SSL context to test
122  *
123  * Returns     :   0 => No data are pending
124  *                >0 => Pending data length. XXX: really?
125  *
126  *********************************************************************/
127 extern size_t is_ssl_pending(struct ssl_attr *ssl_attr)
128 {
129    return (size_t)wolfSSL_pending(ssl_attr->wolfssl_attr.ssl);
130 }
131
132
133 /*********************************************************************
134  *
135  * Function    :  ssl_send_data
136  *
137  * Description :  Sends the content of buf (for n bytes) to given SSL
138  *                connection context.
139  *
140  * Parameters  :
141  *          1  :  ssl_attr = SSL context to send data to
142  *          2  :  buf = Pointer to data to be sent
143  *          3  :  len = Length of data to be sent to the SSL context
144  *
145  * Returns     :  Length of sent data or negative value on error.
146  *
147  *********************************************************************/
148 extern int ssl_send_data(struct ssl_attr *ssl_attr, const unsigned char *buf, size_t len)
149 {
150    WOLFSSL *ssl;
151    int ret = 0;
152    int pos = 0; /* Position of unsent part in buffer */
153    int fd = -1;
154
155    if (len == 0)
156    {
157       return 0;
158    }
159
160    ssl = ssl_attr->wolfssl_attr.ssl;
161    fd = wolfSSL_get_fd(ssl);
162
163    while (pos < len)
164    {
165       int send_len = (int)len - pos;
166
167       log_error(LOG_LEVEL_WRITING, "TLS on socket %d: %N",
168          fd, send_len, buf+pos);
169
170       ret = wolfSSL_write(ssl, buf+pos, send_len);
171       if (ret <= 0)
172       {
173          log_ssl_errors(LOG_LEVEL_ERROR,
174             "Sending data on socket %d over TLS failed", fd);
175          return -1;
176       }
177
178       /* Adding count of sent bytes to position in buffer */
179       pos = pos + ret;
180    }
181
182    return (int)len;
183 }
184
185
186 /*********************************************************************
187  *
188  * Function    :  ssl_recv_data
189  *
190  * Description :  Receives data from given SSL context and puts
191  *                it into buffer.
192  *
193  * Parameters  :
194  *          1  :  ssl_attr = SSL context to receive data from
195  *          2  :  buf = Pointer to buffer where data will be written
196  *          3  :  max_length = Maximum number of bytes to read
197  *
198  * Returns     :  Number of bytes read, 0 for EOF, or -1
199  *                on error.
200  *
201  *********************************************************************/
202 extern int ssl_recv_data(struct ssl_attr *ssl_attr, unsigned char *buf, size_t max_length)
203 {
204    WOLFSSL *ssl;
205    int ret = 0;
206    int fd = -1;
207
208    memset(buf, 0, max_length);
209
210    /*
211     * Receiving data from SSL context into buffer
212     */
213    ssl = ssl_attr->wolfssl_attr.ssl;
214    ret = wolfSSL_read(ssl, buf, (int)max_length);
215    fd = wolfSSL_get_fd(ssl);
216
217    if (ret < 0)
218    {
219       log_ssl_errors(LOG_LEVEL_ERROR,
220          "Receiving data on socket %d over TLS failed", fd);
221
222       return -1;
223    }
224
225    log_error(LOG_LEVEL_RECEIVED, "TLS from socket %d: %N",
226       fd, ret, buf);
227
228    return ret;
229 }
230
231
232 /*********************************************************************
233  *
234  * Function    :  get_public_key_size_string
235  *
236  * Description : Translates a public key type to a string.
237  *
238  * Parameters  :
239  *          1  :  key_type = The public key type.
240  *
241  * Returns     :  String containing the translated key size.
242  *
243  *********************************************************************/
244 static const char *get_public_key_size_string(int key_type)
245 {
246    switch (key_type)
247    {
248       case EVP_PKEY_RSA:
249          return "RSA key size";
250       case EVP_PKEY_DSA:
251          return "DSA key size";
252       case EVP_PKEY_EC:
253          return "EC key size";
254       default:
255          return "non-RSA/DSA/EC key size";
256    }
257 }
258
259
260 /*********************************************************************
261  *
262  * Function    :  ssl_store_cert
263  *
264  * Description : This function is called once for each certificate in the
265  *               server's certificate trusted chain and prepares
266  *               information about the certificate. The information can
267  *               be used to inform the user about invalid certificates.
268  *
269  * Parameters  :
270  *          1  :  csp = Current client state (buffers, headers, etc...)
271  *          2  :  cert = certificate from trusted chain
272  *
273  * Returns     :  0 on success and negative value on error
274  *
275  *********************************************************************/
276 static int ssl_store_cert(struct client_state *csp, X509 *cert)
277 {
278    long len;
279    struct certs_chain *last = &(csp->server_certs_chain);
280    int ret = 0;
281    WOLFSSL_BIO *bio = BIO_new(BIO_s_mem());
282    WOLFSSL_EVP_PKEY *pkey = NULL;
283    char *bio_mem_data = NULL;
284    char *encoded_text;
285    long l;
286    unsigned char serial_number[32];
287    int  serial_number_size = sizeof(serial_number);
288    WOLFSSL_X509_NAME *issuer_name;
289    WOLFSSL_X509_NAME *subject_name;
290    char *subject_alternative_name;
291    int loc;
292    int san_prefix_printed = 0;
293
294    if (!bio)
295    {
296       log_ssl_errors(LOG_LEVEL_ERROR, "BIO_new() failed");
297       return -1;
298    }
299
300    /*
301     * Searching for last item in certificates linked list
302     */
303    while (last->next != NULL)
304    {
305       last = last->next;
306    }
307
308    /*
309     * Preparing next item in linked list for next certificate
310     */
311    last->next = zalloc_or_die(sizeof(struct certs_chain));
312
313    /*
314     * Saving certificate file into buffer
315     */
316    if (wolfSSL_PEM_write_bio_X509(bio, cert) != WOLFSSL_SUCCESS)
317    {
318       log_ssl_errors(LOG_LEVEL_ERROR, "wolfSSL_PEM_write_bio_X509() failed");
319       ret = -1;
320       goto exit;
321    }
322
323    len = wolfSSL_BIO_get_mem_data(bio, &bio_mem_data);
324    last->file_buf = malloc((size_t)len + 1);
325    if (last->file_buf == NULL)
326    {
327       log_error(LOG_LEVEL_ERROR,
328          "Failed to allocate %lu bytes to store the X509 PEM certificate",
329          len + 1);
330       ret = -1;
331       goto exit;
332    }
333
334    strncpy(last->file_buf, bio_mem_data, (size_t)len);
335    last->file_buf[len] = '\0';
336    wolfSSL_BIO_free(bio);
337    bio = wolfSSL_BIO_new(wolfSSL_BIO_s_mem());
338    if (!bio)
339    {
340       log_ssl_errors(LOG_LEVEL_ERROR, "wolfSSL_BIO_new() failed");
341       ret = -1;
342       goto exit;
343    }
344
345    /*
346     * Saving certificate information into buffer
347     */
348    l = wolfSSL_X509_get_version(cert);
349    if (l >= 0 && l <= 2)
350    {
351       if (wolfSSL_BIO_printf(bio, "cert. version     : %ld\n", l + 1) <= 0)
352       {
353          log_ssl_errors(LOG_LEVEL_ERROR,
354             "wolfSSL_BIO_printf() for version failed");
355          ret = -1;
356          goto exit;
357       }
358    }
359    else
360    {
361       if (wolfSSL_BIO_printf(bio, "cert. version     : Unknown (%ld)\n", l) <= 0)
362       {
363          log_ssl_errors(LOG_LEVEL_ERROR,
364             "wolfSSL_BIO_printf() for version failed");
365          ret = -1;
366          goto exit;
367       }
368    }
369
370    if (wolfSSL_BIO_puts(bio, "serial number     : ") <= 0)
371    {
372       log_ssl_errors(LOG_LEVEL_ERROR,
373          "wolfSSL_BIO_puts() for serial number failed");
374       ret = -1;
375       goto exit;
376    }
377    if (wolfSSL_X509_get_serial_number(cert, serial_number, &serial_number_size)
378       != WOLFSSL_SUCCESS)
379    {
380       log_error(LOG_LEVEL_ERROR, "wolfSSL_X509_get_serial_number() failed");
381       ret = -1;
382       goto exit;
383    }
384
385    if (serial_number_size <= (int)sizeof(char))
386    {
387       if (wolfSSL_BIO_printf(bio, "%lu (0x%lx)\n", serial_number[0],
388             serial_number[0]) <= 0)
389       {
390          log_ssl_errors(LOG_LEVEL_ERROR,
391             "wolfSSL_BIO_printf() for serial number as single byte failed");
392          ret = -1;
393          goto exit;
394       }
395    }
396    else
397    {
398       int i;
399       for (i = 0; i < serial_number_size; i++)
400       {
401          if (wolfSSL_BIO_printf(bio, "%02x%c", serial_number[i],
402                ((i + 1 == serial_number_size) ? '\n' : ':')) <= 0)
403          {
404             log_ssl_errors(LOG_LEVEL_ERROR,
405                "wolfSSL_BIO_printf() for serial number bytes failed");
406             ret = -1;
407             goto exit;
408          }
409       }
410    }
411
412    if (wolfSSL_BIO_puts(bio, "issuer name       : ") <= 0)
413    {
414       log_ssl_errors(LOG_LEVEL_ERROR, "wolfSSL_BIO_puts() for issuer failed");
415       ret = -1;
416       goto exit;
417    }
418    issuer_name = wolfSSL_X509_get_issuer_name(cert);
419    if (wolfSSL_X509_NAME_get_sz(issuer_name) <= 0)
420    {
421       if (wolfSSL_BIO_puts(bio, "none") <= 0)
422       {
423          log_ssl_errors(LOG_LEVEL_ERROR,
424             "wolfSSL_BIO_puts() for issuer name failed");
425          ret = -1;
426          goto exit;
427       }
428    }
429    else if (wolfSSL_X509_NAME_print_ex(bio, issuer_name, 0, 0) < 0)
430    {
431       log_ssl_errors(LOG_LEVEL_ERROR,
432          "wolfSSL_X509_NAME_print_ex() for issuer failed");
433       ret = -1;
434       goto exit;
435    }
436
437    if (wolfSSL_BIO_puts(bio, "\nsubject name      : ") <= 0)
438    {
439       log_ssl_errors(LOG_LEVEL_ERROR,
440          "wolfSSL_BIO_puts() for subject name failed");
441       ret = -1;
442       goto exit;
443    }
444    subject_name = wolfSSL_X509_get_subject_name(cert);
445    if (wolfSSL_X509_NAME_get_sz(subject_name) <= 0)
446    {
447       if (wolfSSL_BIO_puts(bio, "none") <= 0)
448       {
449          log_ssl_errors(LOG_LEVEL_ERROR,
450             "wolfSSL_BIO_puts() for subject name failed");
451          ret = -1;
452          goto exit;
453       }
454    }
455    else if (wolfSSL_X509_NAME_print_ex(bio, subject_name, 0, 0) < 0)
456    {
457       log_ssl_errors(LOG_LEVEL_ERROR,
458          "wolfSSL_X509_NAME_print_ex() for subject name failed");
459       ret = -1;
460       goto exit;
461    }
462
463    if (wolfSSL_BIO_puts(bio, "\nissued  on        : ") <= 0)
464    {
465       log_ssl_errors(LOG_LEVEL_ERROR,
466          "wolfSSL_BIO_puts() for issued on failed");
467       ret = -1;
468       goto exit;
469    }
470    if (!wolfSSL_ASN1_TIME_print(bio, wolfSSL_X509_get_notBefore(cert)))
471    {
472       log_ssl_errors(LOG_LEVEL_ERROR,
473          "wolfSSL_ASN1_TIME_print() for issued on failed");
474       ret = -1;
475       goto exit;
476    }
477
478    if (wolfSSL_BIO_puts(bio, "\nexpires on        : ") <= 0)
479    {
480       log_ssl_errors(LOG_LEVEL_ERROR,
481          "wolfSSL_BIO_puts() for expires on failed");
482       ret = -1;
483       goto exit;
484    }
485    if (!wolfSSL_ASN1_TIME_print(bio, wolfSSL_X509_get_notAfter(cert)))
486    {
487       log_ssl_errors(LOG_LEVEL_ERROR,
488          "wolfSSL_ASN1_TIME_print() for expires on failed");
489       ret = -1;
490       goto exit;
491    }
492
493    /* XXX: Show signature algorithm */
494
495    pkey = wolfSSL_X509_get_pubkey(cert);
496    if (!pkey)
497    {
498       log_ssl_errors(LOG_LEVEL_ERROR, "wolfSSL_X509_get_pubkey() failed");
499       ret = -1;
500       goto exit;
501    }
502    ret = wolfSSL_BIO_printf(bio, "\n%-18s: %d bits",
503       get_public_key_size_string(wolfSSL_EVP_PKEY_base_id(pkey)),
504       wolfSSL_EVP_PKEY_bits(pkey));
505    if (ret <= 0)
506    {
507       log_ssl_errors(LOG_LEVEL_ERROR,
508          "wolfSSL_BIO_printf() for key size failed");
509       ret = -1;
510       goto exit;
511    }
512
513    /*
514     * XXX: Show cert usage, etc.
515     */
516    loc = wolfSSL_X509_get_ext_by_NID(cert, NID_basic_constraints, -1);
517    if (loc != -1)
518    {
519       WOLFSSL_X509_EXTENSION *ex = wolfSSL_X509_get_ext(cert, loc);
520       if (BIO_puts(bio, "\nbasic constraints : ") <= 0)
521       {
522          log_ssl_errors(LOG_LEVEL_ERROR,
523             "BIO_printf() for basic constraints failed");
524          ret = -1;
525          goto exit;
526       }
527       if (!wolfSSL_X509V3_EXT_print(bio, ex, 0, 0))
528       {
529          if (!wolfSSL_ASN1_STRING_print_ex(bio,
530                wolfSSL_X509_EXTENSION_get_data(ex),
531                ASN1_STRFLGS_RFC2253))
532          {
533             log_ssl_errors(LOG_LEVEL_ERROR,
534                "wolfSSL_ASN1_STRING_print_ex() for basic constraints failed");
535             ret = -1;
536             goto exit;
537          }
538       }
539    }
540
541    while ((subject_alternative_name = wolfSSL_X509_get_next_altname(cert))
542       != NULL)
543    {
544       if (san_prefix_printed == 0)
545       {
546          ret = wolfSSL_BIO_printf(bio, "\nsubject alt name  : ");
547          san_prefix_printed = 1;
548       }
549       if (ret > 0)
550       {
551          ret = wolfSSL_BIO_printf(bio, "%s ", subject_alternative_name);
552       }
553       if (ret <= 0)
554       {
555          log_ssl_errors(LOG_LEVEL_ERROR,
556             "wolfSSL_BIO_printf() for Subject Alternative Name failed");
557          ret = -1;
558          goto exit;
559       }
560    }
561
562 #if 0
563    /*
564     * This code compiles but does not work because wolfSSL
565     * sets NID_netscape_cert_type to NID_undef.
566     */
567    loc = wolfSSL_X509_get_ext_by_NID(cert, NID_netscape_cert_type, -1);
568    if (loc != -1)
569    {
570       WOLFSSL_X509_EXTENSION *ex = wolfSSL_X509_get_ext(cert, loc);
571       if (wolfSSL_BIO_puts(bio, "\ncert. type        : ") <= 0)
572       {
573          log_ssl_errors(LOG_LEVEL_ERROR,
574             "wolfSSL_BIO_printf() for cert type failed");
575          ret = -1;
576          goto exit;
577       }
578       if (!wolfSSL_X509V3_EXT_print(bio, ex, 0, 0))
579       {
580          if (!wolfSSL_ASN1_STRING_print_ex(bio,
581                wolfSSL_X509_EXTENSION_get_data(ex),
582                ASN1_STRFLGS_RFC2253))
583          {
584             log_ssl_errors(LOG_LEVEL_ERROR,
585                "wolfSSL_ASN1_STRING_print_ex() for cert type failed");
586             ret = -1;
587             goto exit;
588          }
589       }
590    }
591 #endif
592
593 #if 0
594    /*
595     * This code compiles but does not work. wolfSSL_OBJ_obj2nid()
596     * triggers a 'X509V3_EXT_print not yet implemented for ext type' message.
597      */
598    loc = wolfSSL_X509_get_ext_by_NID(cert, NID_key_usage, -1);
599    if (loc != -1)
600    {
601       WOLFSSL_X509_EXTENSION *extension = wolfSSL_X509_get_ext(cert, loc);
602       if (BIO_puts(bio, "\nkey usage         : ") <= 0)
603       {
604          log_ssl_errors(LOG_LEVEL_ERROR,
605             "wolfSSL_BIO_printf() for key usage failed");
606          ret = -1;
607          goto exit;
608       }
609       if (!wolfSSL_X509V3_EXT_print(bio, extension, 0, 0))
610       {
611          if (!wolfSSL_ASN1_STRING_print_ex(bio,
612                wolfSSL_X509_EXTENSION_get_data(extension),
613                ASN1_STRFLGS_RFC2253))
614          {
615             log_ssl_errors(LOG_LEVEL_ERROR,
616                "wolfSSL_ASN1_STRING_print_ex() for key usage failed");
617             ret = -1;
618             goto exit;
619          }
620       }
621    }
622 #endif
623
624 #if 0
625    /*
626     * This compiles but doesn't work. wolfSSL_X509_ext_isSet_by_NID()
627     * complains about "NID not in table".
628     */
629    loc = wolfSSL_X509_get_ext_by_NID(cert, NID_ext_key_usage, -1);
630    if (loc != -1) {
631       WOLFSSL_X509_EXTENSION *ex = wolfSSL_X509_get_ext(cert, loc);
632       if (wolfSSL_BIO_puts(bio, "\next key usage     : ") <= 0)
633       {
634          log_ssl_errors(LOG_LEVEL_ERROR,
635             "wolfSSL_BIO_printf() for ext key usage failed");
636          ret = -1;
637          goto exit;
638       }
639       if (!wolfSSL_X509V3_EXT_print(bio, ex, 0, 0))
640       {
641          if (!wolfSSL_ASN1_STRING_print_ex(bio,
642                wolfSSL_X509_EXTENSION_get_data(ex),
643                ASN1_STRFLGS_RFC2253))
644          {
645             log_ssl_errors(LOG_LEVEL_ERROR,
646                "wolfSSL_ASN1_STRING_print_ex() for ext key usage failed");
647             ret = -1;
648             goto exit;
649          }
650       }
651    }
652 #endif
653
654 #if 0
655    /*
656     * This compiles but doesn't work. wolfSSL_X509_ext_isSet_by_NID()
657     * complains about "NID not in table". XXX: again?
658     */
659    loc = wolfSSL_X509_get_ext_by_NID(cert, NID_certificate_policies, -1);
660    if (loc != -1)
661    {
662       WOLFSSL_X509_EXTENSION *ex = wolfSSL_X509_get_ext(cert, loc);
663       if (wolfSSL_BIO_puts(bio, "\ncertificate policies : ") <= 0)
664       {
665          log_ssl_errors(LOG_LEVEL_ERROR,
666             "wolfSSL_BIO_printf() for certificate policies failed");
667          ret = -1;
668          goto exit;
669       }
670       if (!wolfSSL_X509V3_EXT_print(bio, ex, 0, 0))
671       {
672          if (!wolfSSL_ASN1_STRING_print_ex(bio,
673                wolfSSL_X509_EXTENSION_get_data(ex),
674                ASN1_STRFLGS_RFC2253))
675          {
676             log_ssl_errors(LOG_LEVEL_ERROR,
677                "wolfSSL_ASN1_STRING_print_ex() for certificate policies failed");
678             ret = -1;
679             goto exit;
680          }
681       }
682    }
683 #endif
684
685    /* make valgrind happy */
686    static const char zero = 0;
687    wolfSSL_BIO_write(bio, &zero, 1);
688
689    len = wolfSSL_BIO_get_mem_data(bio, &bio_mem_data);
690    if (len <= 0)
691    {
692       log_error(LOG_LEVEL_ERROR, "BIO_get_mem_data() returned %ld "
693          "while gathering certificate information", len);
694       ret = -1;
695       goto exit;
696    }
697    encoded_text = html_encode(bio_mem_data);
698    if (encoded_text == NULL)
699    {
700       log_error(LOG_LEVEL_ERROR,
701          "Failed to HTML-encode the certificate information");
702       ret = -1;
703       goto exit;
704    }
705
706    strlcpy(last->info_buf, encoded_text, sizeof(last->info_buf));
707    freez(encoded_text);
708    ret = 0;
709
710 exit:
711    if (bio)
712    {
713       wolfSSL_BIO_free(bio);
714    }
715    if (pkey)
716    {
717       wolfSSL_EVP_PKEY_free(pkey);
718    }
719    return ret;
720 }
721
722
723 /*********************************************************************
724  *
725  * Function    :  host_to_hash
726  *
727  * Description :  Creates MD5 hash from host name. Host name is loaded
728  *                from structure csp and saved again into it.
729  *
730  * Parameters  :
731  *          1  :  csp = Current client state (buffers, headers, etc...)
732  *
733  * Returns     : -1 => Error while creating hash
734  *                0 => Hash created successfully
735  *
736  *********************************************************************/
737 static int host_to_hash(struct client_state *csp)
738 {
739    wc_Md5 md5;
740    int ret;
741    size_t i;
742
743    ret = wc_InitMd5(&md5);
744    if (ret != 0)
745    {
746       return -1;
747    }
748
749    ret = wc_Md5Update(&md5, (const byte *)csp->http->host,
750       (word32)strlen(csp->http->host));
751    if (ret != 0)
752    {
753       return -1;
754    }
755
756    ret = wc_Md5Final(&md5, csp->http->hash_of_host);
757    if (ret != 0)
758    {
759       return -1;
760    }
761
762    wc_Md5Free(&md5);
763
764    /* Converting hash into string with hex */
765    for (i = 0; i < 16; i++)
766    {
767       ret = snprintf((char *)csp->http->hash_of_host_hex + 2 * i,
768          sizeof(csp->http->hash_of_host_hex) - 2 * i,
769          "%02x", csp->http->hash_of_host[i]);
770       if (ret < 0)
771       {
772          log_error(LOG_LEVEL_ERROR, "sprintf() failed. Return value: %d", ret);
773          return -1;
774       }
775    }
776
777    return 0;
778 }
779
780
781 /*********************************************************************
782  *
783  * Function    :  create_client_ssl_connection
784  *
785  * Description :  Creates a TLS-secured connection with the client.
786  *
787  * Parameters  :
788  *          1  :  csp = Current client state (buffers, headers, etc...)
789  *
790  * Returns     :  0 on success, negative value if connection wasn't created
791  *                successfully.
792  *
793  *********************************************************************/
794 extern int create_client_ssl_connection(struct client_state *csp)
795 {
796    struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
797    /* Paths to certificates file and key file */
798    char *key_file  = NULL;
799    char *cert_file = NULL;
800    int ret = 0;
801    WOLFSSL *ssl;
802
803    /* Should probably be called from somewhere else. */
804    wolfssl_init();
805
806    /*
807     * Preparing hash of host for creating certificates
808     */
809    ret = host_to_hash(csp);
810    if (ret != 0)
811    {
812       log_error(LOG_LEVEL_ERROR, "Generating hash of host failed: %d", ret);
813       ret = -1;
814       goto exit;
815    }
816
817    /*
818     * Preparing paths to certificates files and key file
819     */
820    cert_file = make_certs_path(csp->config->certificate_directory,
821       (const char *)csp->http->hash_of_host_hex, CERT_FILE_TYPE);
822    key_file  = make_certs_path(csp->config->certificate_directory,
823       (const char *)csp->http->hash_of_host_hex, KEY_FILE_TYPE);
824
825    if (cert_file == NULL || key_file == NULL)
826    {
827       ret = -1;
828       goto exit;
829    }
830
831    /* Do we need to generate a new host certificate and key? */
832    if (!file_exists(cert_file) || !file_exists(key_file) ||
833        ssl_certificate_is_invalid(cert_file))
834    {
835       /*
836        * Yes we do. Lock mutex to prevent certificate and
837        * key inconsistencies.
838        */
839       privoxy_mutex_lock(&certificate_mutex);
840       ret = generate_host_certificate(csp, cert_file, key_file);
841       privoxy_mutex_unlock(&certificate_mutex);
842       if (ret < 0)
843       {
844          /*
845           * No need to log something, generate_host_certificate()
846           * took care of it.
847           */
848          ret = -1;
849          goto exit;
850       }
851    }
852    ssl_attr->wolfssl_attr.ctx = wolfSSL_CTX_new(wolfSSLv23_method());
853    if (ssl_attr->wolfssl_attr.ctx == NULL)
854    {
855       log_ssl_errors(LOG_LEVEL_ERROR, "Unable to create TLS context");
856       ret = -1;
857       goto exit;
858    }
859
860    /* Set the key and cert */
861    if (wolfSSL_CTX_use_certificate_file(ssl_attr->wolfssl_attr.ctx,
862          cert_file, SSL_FILETYPE_PEM) != WOLFSSL_SUCCESS)
863    {
864       log_ssl_errors(LOG_LEVEL_ERROR,
865          "Loading host certificate %s failed", cert_file);
866       ret = -1;
867       goto exit;
868    }
869
870    if (wolfSSL_CTX_use_PrivateKey_file(ssl_attr->wolfssl_attr.ctx,
871          key_file, SSL_FILETYPE_PEM) != WOLFSSL_SUCCESS)
872    {
873       log_ssl_errors(LOG_LEVEL_ERROR,
874          "Loading host certificate private key %s failed", key_file);
875       ret = -1;
876       goto exit;
877    }
878
879    wolfSSL_CTX_set_options(ssl_attr->wolfssl_attr.ctx, WOLFSSL_OP_NO_SSLv3);
880
881    ssl = ssl_attr->wolfssl_attr.ssl = wolfSSL_new(ssl_attr->wolfssl_attr.ctx);
882
883    if (wolfSSL_set_fd(ssl, csp->cfd) != WOLFSSL_SUCCESS)
884    {
885       log_ssl_errors(LOG_LEVEL_ERROR,
886          "wolfSSL_set_fd() failed to set the client socket");
887       ret = -1;
888       goto exit;
889    }
890
891    if (csp->config->cipher_list != NULL)
892    {
893       if (!wolfSSL_set_cipher_list(ssl, csp->config->cipher_list))
894       {
895          log_ssl_errors(LOG_LEVEL_ERROR,
896             "Setting the cipher list '%s' for the client connection failed",
897             csp->config->cipher_list);
898          ret = -1;
899          goto exit;
900       }
901    }
902
903    /*
904     *  Handshake with client
905     */
906    log_error(LOG_LEVEL_CONNECT,
907       "Performing the TLS/SSL handshake with client. Hash of host: %s",
908       csp->http->hash_of_host_hex);
909
910    ret = wolfSSL_accept(ssl);
911    if (ret == WOLFSSL_SUCCESS)
912    {
913       log_error(LOG_LEVEL_CONNECT,
914          "Client successfully connected over %s (%s).",
915          wolfSSL_get_version(ssl), wolfSSL_get_cipher_name(ssl));
916       csp->ssl_with_client_is_opened = 1;
917       ret = 0;
918    }
919    else
920    {
921       char buffer[80];
922       int error = wolfSSL_get_error(ssl, ret);
923       log_error(LOG_LEVEL_ERROR,
924          "The TLS handshake with the client failed. error = %d, %s",
925          error, wolfSSL_ERR_error_string((unsigned long)error, buffer));
926       ret = -1;
927    }
928
929 exit:
930    /*
931     * Freeing allocated paths to files
932     */
933    freez(cert_file);
934    freez(key_file);
935
936    /* Freeing structures if connection wasn't created successfully */
937    if (ret < 0)
938    {
939       free_client_ssl_structures(csp);
940    }
941    return ret;
942 }
943
944
945 /*********************************************************************
946  *
947  * Function    :  shutdown_connection
948  *
949  * Description :  Shuts down a TLS connection if the socket is still
950  *                alive.
951  *
952  * Parameters  :
953  *          1  :  csp = Current client state (buffers, headers, etc...)
954  *
955  * Returns     :  N/A
956  *
957  *********************************************************************/
958 static void shutdown_connection(WOLFSSL *ssl, const char *type)
959 {
960    int shutdown_attempts = 0;
961    int ret;
962    int fd;
963    enum { MAX_SHUTDOWN_ATTEMPTS = 5 };
964
965    fd = wolfSSL_get_fd(ssl);
966
967    do
968    {
969       if (!socket_is_still_alive(fd))
970       {
971          log_error(LOG_LEVEL_CONNECT, "Not shutting down %s connection "
972             "on socket %d. The socket is no longer alive.", type, fd);
973          return;
974       }
975       ret = wolfSSL_shutdown(ssl);
976       shutdown_attempts++;
977       if (WOLFSSL_SUCCESS != ret)
978       {
979          log_error(LOG_LEVEL_CONNECT, "Failed to shutdown %s connection "
980             "on socket %d. Attempts so far: %d, ret: %d", type, fd,
981             shutdown_attempts, ret);
982       }
983    } while (ret == WOLFSSL_SHUTDOWN_NOT_DONE &&
984       shutdown_attempts < MAX_SHUTDOWN_ATTEMPTS);
985    if (WOLFSSL_SUCCESS != ret)
986    {
987       char buffer[80];
988       int error = wolfSSL_get_error(ssl, ret);
989       log_error(LOG_LEVEL_ERROR, "Failed to shutdown %s connection "
990          "on socket %d after %d attempts. ret: %d, error: %d, %s",
991          type, fd, shutdown_attempts, ret, error,
992          wolfSSL_ERR_error_string((unsigned long)error, buffer));
993    }
994    else if (shutdown_attempts > 1)
995    {
996       log_error(LOG_LEVEL_CONNECT, "Succeeded to shutdown %s connection "
997          "on socket %d after %d attempts.", type, fd, shutdown_attempts);
998    }
999 }
1000
1001
1002 /*********************************************************************
1003  *
1004  * Function    :  close_client_ssl_connection
1005  *
1006  * Description :  Closes TLS connection with client. This function
1007  *                checks if this connection is already created.
1008  *
1009  * Parameters  :
1010  *          1  :  csp = Current client state (buffers, headers, etc...)
1011  *
1012  * Returns     :  N/A
1013  *
1014  *********************************************************************/
1015 extern void close_client_ssl_connection(struct client_state *csp)
1016 {
1017    struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
1018
1019    if (csp->ssl_with_client_is_opened == 0)
1020    {
1021       return;
1022    }
1023
1024    /*
1025     * Notify the peer that the connection is being closed.
1026     */
1027    shutdown_connection(ssl_attr->wolfssl_attr.ssl, "client");
1028
1029    free_client_ssl_structures(csp);
1030    csp->ssl_with_client_is_opened = 0;
1031 }
1032
1033
1034 /*********************************************************************
1035  *
1036  * Function    :  free_client_ssl_structures
1037  *
1038  * Description :  Frees structures used for SSL communication with
1039  *                client.
1040  *
1041  * Parameters  :
1042  *          1  :  csp = Current client state (buffers, headers, etc...)
1043  *
1044  * Returns     :  N/A
1045  *
1046  *********************************************************************/
1047 static void free_client_ssl_structures(struct client_state *csp)
1048 {
1049    struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
1050
1051    if (ssl_attr->wolfssl_attr.ssl)
1052    {
1053       wolfSSL_free(ssl_attr->wolfssl_attr.ssl);
1054    }
1055    if (ssl_attr->wolfssl_attr.ctx)
1056    {
1057       wolfSSL_CTX_free(ssl_attr->wolfssl_attr.ctx);
1058    }
1059 }
1060
1061
1062 /*********************************************************************
1063  *
1064  * Function    :  close_server_ssl_connection
1065  *
1066  * Description :  Closes TLS connection with server. This function
1067  *                checks if this connection is already opened.
1068  *
1069  * Parameters  :
1070  *          1  :  csp = Current client state (buffers, headers, etc...)
1071  *
1072  * Returns     :  N/A
1073  *
1074  *********************************************************************/
1075 extern void close_server_ssl_connection(struct client_state *csp)
1076 {
1077    struct ssl_attr *ssl_attr = &csp->ssl_server_attr;
1078
1079    if (csp->ssl_with_server_is_opened == 0)
1080    {
1081       return;
1082    }
1083
1084    /*
1085    * Notify the peer that the connection is being closed.
1086    */
1087    shutdown_connection(ssl_attr->wolfssl_attr.ssl, "server");
1088
1089    free_server_ssl_structures(csp);
1090    csp->ssl_with_server_is_opened = 0;
1091 }
1092
1093
1094 /*********************************************************************
1095  *
1096  * Function    :  create_server_ssl_connection
1097  *
1098  * Description :  Creates TLS-secured connection with the server.
1099  *
1100  * Parameters  :
1101  *          1  :  csp = Current client state (buffers, headers, etc...)
1102  *
1103  * Returns     :  0 on success, negative value if connection wasn't created
1104  *                successfully.
1105  *
1106  *********************************************************************/
1107 extern int create_server_ssl_connection(struct client_state *csp)
1108 {
1109    wolfssl_connection_attr *ssl_attrs = &csp->ssl_server_attr.wolfssl_attr;
1110    int ret = 0;
1111    WOLFSSL *ssl;
1112    int connect_ret = 0;
1113
1114    csp->server_cert_verification_result = SSL_CERT_NOT_VERIFIED;
1115    csp->server_certs_chain.next = NULL;
1116
1117    ssl_attrs->ctx = wolfSSL_CTX_new(wolfSSLv23_method());
1118    if (ssl_attrs->ctx == NULL)
1119    {
1120       log_ssl_errors(LOG_LEVEL_ERROR, "TLS context creation failed");
1121       ret = -1;
1122       goto exit;
1123    }
1124
1125    if (csp->dont_verify_certificate)
1126    {
1127       wolfSSL_CTX_set_verify(ssl_attrs->ctx, WOLFSSL_VERIFY_NONE, NULL);
1128    }
1129    else if (wolfSSL_CTX_load_verify_locations(ssl_attrs->ctx,
1130       csp->config->trusted_cas_file, NULL) != WOLFSSL_SUCCESS)
1131    {
1132       log_ssl_errors(LOG_LEVEL_ERROR, "Loading trusted CAs file %s failed",
1133          csp->config->trusted_cas_file);
1134       ret = -1;
1135       goto exit;
1136    }
1137
1138    wolfSSL_CTX_set_options(ssl_attrs->ctx, WOLFSSL_OP_NO_SSLv3);
1139
1140    ssl = ssl_attrs->ssl = wolfSSL_new(ssl_attrs->ctx);
1141
1142    if (wolfSSL_set_fd(ssl, csp->server_connection.sfd) != WOLFSSL_SUCCESS)
1143    {
1144       log_ssl_errors(LOG_LEVEL_ERROR,
1145          "wolfSSL_set_fd() failed to set the server socket");
1146       ret = -1;
1147       goto exit;
1148    }
1149
1150    if (csp->config->cipher_list != NULL)
1151    {
1152       if (wolfSSL_set_cipher_list(ssl, csp->config->cipher_list) != WOLFSSL_SUCCESS)
1153       {
1154          log_ssl_errors(LOG_LEVEL_ERROR,
1155             "Setting the cipher list '%s' for the server connection failed",
1156             csp->config->cipher_list);
1157          ret = -1;
1158          goto exit;
1159       }
1160    }
1161
1162    ret = wolfSSL_UseSNI(ssl, WOLFSSL_SNI_HOST_NAME,
1163       csp->http->host, (unsigned short)strlen(csp->http->host));
1164    if (ret != WOLFSSL_SUCCESS)
1165    {
1166       log_ssl_errors(LOG_LEVEL_ERROR, "Failed to set use of SNI");
1167       ret = -1;
1168       goto exit;
1169    }
1170
1171    ret = wolfSSL_check_domain_name(ssl, csp->http->host);
1172    if (ret != WOLFSSL_SUCCESS)
1173    {
1174       char buffer[80];
1175       int error = wolfSSL_get_error(ssl, ret);
1176       log_error(LOG_LEVEL_FATAL,
1177          "Failed to set check domain name. error = %d, %s",
1178          error, wolfSSL_ERR_error_string((unsigned long)error, buffer));
1179       ret = -1;
1180       goto exit;
1181    }
1182
1183 #ifdef HAVE_SECURE_RENEGOTIATION
1184 #warning wolfssl has been compiled with HAVE_SECURE_RENEGOTIATION while you probably want HAVE_RENEGOTIATION_INDICATION
1185    if(wolfSSL_UseSecureRenegotiation(ssl) != WOLFSSL_SUCCESS)
1186    {
1187       log_ssl_errors(LOG_LEVEL_ERROR,
1188          "Failed to enable 'Secure' Renegotiation. Continuing anyway.");
1189    }
1190 #endif
1191 #ifndef HAVE_RENEGOTIATION_INDICATION
1192 #warning Looks like wolfssl has been compiled without HAVE_RENEGOTIATION_INDICATION
1193 #endif
1194
1195    log_error(LOG_LEVEL_CONNECT,
1196       "Performing the TLS/SSL handshake with the server");
1197
1198    /* wolfSSL_Debugging_ON(); */
1199    connect_ret = wolfSSL_connect(ssl);
1200    /* wolfSSL_Debugging_OFF(); */
1201
1202    /*
1203    wolfSSL_Debugging_ON();
1204    */
1205    if (!csp->dont_verify_certificate)
1206    {
1207       long verify_result = wolfSSL_get_error(ssl, connect_ret);
1208
1209 #if LIBWOLFSSL_VERSION_HEX > 0x05005004
1210       if (verify_result == WOLFSSL_X509_V_OK)
1211 #else
1212       if (verify_result == X509_V_OK)
1213 #endif
1214       {
1215          ret = 0;
1216          csp->server_cert_verification_result = SSL_CERT_VALID;
1217       }
1218       else
1219       {
1220          WOLF_STACK_OF(WOLFSSL_X509) *chain;
1221
1222          csp->server_cert_verification_result = verify_result;
1223          log_error(LOG_LEVEL_ERROR,
1224             "X509 certificate verification for %s failed with error %ld: %s",
1225             csp->http->hostport, verify_result,
1226             wolfSSL_X509_verify_cert_error_string(verify_result));
1227
1228          chain = wolfSSL_get_peer_cert_chain(ssl);
1229          if (chain != NULL)
1230          {
1231             int i;
1232             for (i = 0; i < wolfSSL_sk_X509_num(chain); i++)
1233             {
1234                if (ssl_store_cert(csp, wolfSSL_sk_X509_value(chain, i)) != 0)
1235                {
1236                   log_error(LOG_LEVEL_ERROR,
1237                      "ssl_store_cert() failed for cert %d", i);
1238                   /*
1239                    * ssl_send_certificate_error() wil not be able to show
1240                    * the certificate but the user will stil get the error
1241                    * description.
1242                    */
1243                }
1244             }
1245          }
1246
1247          ret = -1;
1248          goto exit;
1249       }
1250    }
1251    /*
1252    wolfSSL_Debugging_OFF();
1253    */
1254    if (connect_ret == WOLFSSL_SUCCESS)
1255    {
1256       log_error(LOG_LEVEL_CONNECT,
1257          "Server successfully connected over %s (%s).",
1258          wolfSSL_get_version(ssl), wolfSSL_get_cipher_name(ssl));
1259       csp->ssl_with_server_is_opened = 1;
1260       ret = 0;
1261    }
1262    else
1263    {
1264       char buffer[80];
1265       int error = wolfSSL_get_error(ssl, ret);
1266       log_error(LOG_LEVEL_ERROR,
1267          "The TLS handshake with the server %s failed. error = %d, %s",
1268          csp->http->hostport,
1269          error, wolfSSL_ERR_error_string((unsigned long)error, buffer));
1270       ret = -1;
1271    }
1272
1273 exit:
1274    /* Freeing structures if connection wasn't created successfully */
1275    if (ret < 0)
1276    {
1277       free_server_ssl_structures(csp);
1278    }
1279
1280    return ret;
1281 }
1282
1283
1284 /*********************************************************************
1285  *
1286  * Function    :  free_server_ssl_structures
1287  *
1288  * Description :  Frees structures used for SSL communication with server
1289  *
1290  * Parameters  :
1291  *          1  :  csp = Current client state (buffers, headers, etc...)
1292  *
1293  * Returns     :  N/A
1294  *
1295  *********************************************************************/
1296 static void free_server_ssl_structures(struct client_state *csp)
1297 {
1298    struct ssl_attr *ssl_attr = &csp->ssl_server_attr;
1299
1300    if (ssl_attr->wolfssl_attr.ssl)
1301    {
1302       wolfSSL_free(ssl_attr->wolfssl_attr.ssl);
1303    }
1304    if (ssl_attr->wolfssl_attr.ctx)
1305    {
1306       wolfSSL_CTX_free(ssl_attr->wolfssl_attr.ctx);
1307    }
1308 }
1309
1310
1311 /*********************************************************************
1312  *
1313  * Function    :  log_ssl_errors
1314  *
1315  * Description :  Log SSL errors
1316  *
1317  * Parameters  :
1318  *          1  :  debuglevel = Debug level
1319  *          2  :  desc = Error description
1320  *
1321  * Returns     :  N/A
1322  *
1323  *********************************************************************/
1324 static void log_ssl_errors(int debuglevel, const char* fmt, ...)
1325 {
1326    unsigned long err_code;
1327    char prefix[ERROR_BUF_SIZE];
1328    va_list args;
1329    va_start(args, fmt);
1330    vsnprintf(prefix, sizeof(prefix), fmt, args);
1331    int reported = 0;
1332
1333    while ((err_code = wolfSSL_ERR_get_error()))
1334    {
1335       char err_buf[ERROR_BUF_SIZE];
1336       reported = 1;
1337       wolfSSL_ERR_error_string_n(err_code, err_buf, sizeof(err_buf));
1338       log_error(debuglevel, "%s: %s", prefix, err_buf);
1339    }
1340    va_end(args);
1341    /*
1342     * In case if called by mistake and there were
1343     * no TLS errors let's report it to the log.
1344     */
1345    if (!reported)
1346    {
1347       log_error(debuglevel, "%s: no TLS errors detected", prefix);
1348    }
1349 }
1350
1351
1352 /*********************************************************************
1353  *
1354  * Function    :  ssl_base64_encode
1355  *
1356  * Description :  Encode a buffer into base64 format.
1357  *
1358  * Parameters  :
1359  *          1  :  dst = Destination buffer
1360  *          2  :  dlen = Destination buffer length
1361  *          3  :  olen = Number of bytes written
1362  *          4  :  src = Source buffer
1363  *          5  :  slen = Amount of data to be encoded
1364  *
1365  * Returns     :  0 on success, error code othervise
1366  *
1367  *********************************************************************/
1368 extern int ssl_base64_encode(unsigned char *dst, size_t dlen, size_t *olen,
1369                              const unsigned char *src, size_t slen)
1370 {
1371    word32 output_length;
1372    int ret;
1373
1374    *olen = 4 * ((slen/3) + ((slen%3) ? 1 : 0)) + 1;
1375    if (*olen > dlen)
1376    {
1377       return ENOBUFS;
1378    }
1379
1380    output_length = (word32)dlen;
1381    ret = Base64_Encode_NoNl(src, (word32)slen, dst, &output_length);
1382    if (ret != 0)
1383    {
1384       log_error(LOG_LEVEL_ERROR, "base64 encoding failed with %d", ret);
1385       return ret;
1386    }
1387    *olen = output_length;
1388
1389    return 0;
1390
1391 }
1392
1393
1394 /*********************************************************************
1395  *
1396  * Function    :  close_file_stream
1397  *
1398  * Description :  Close file stream, report error on close error
1399  *
1400  * Parameters  :
1401  *          1  :  f = file stream to close
1402  *          2  :  path = path for error report
1403  *
1404  * Returns     :  N/A
1405  *
1406  *********************************************************************/
1407 static void close_file_stream(FILE *f, const char *path)
1408 {
1409    if (fclose(f) != 0)
1410    {
1411       log_error(LOG_LEVEL_ERROR,
1412          "Error closing file %s: %s", path, strerror(errno));
1413    }
1414 }
1415
1416
1417 /*********************************************************************
1418  *
1419  * Function    :  write_certificate
1420  *
1421  * Description :  Writes a PEM-encoded certificate to a file.
1422  *
1423  * Parameters  :
1424  *          1  :  certificate_path = Path to the file to create
1425  *          2  :  certificate = PEM-encoded certificate to write.
1426  *
1427  * Returns     :  NULL => Error. Otherwise a key;
1428  *
1429  *********************************************************************/
1430 static int write_certificate(const char *certificate_path, const char *certificate)
1431 {
1432    FILE *fp;
1433
1434    assert(certificate_path != NULL);
1435    assert(certificate != NULL);
1436
1437    fp = fopen(certificate_path, "wb");
1438    if (NULL == fp)
1439    {
1440       log_error(LOG_LEVEL_ERROR,
1441          "Failed to open %s to write the certificate: %E",
1442          certificate_path);
1443       return -1;
1444    }
1445    if (fputs(certificate, fp) < 0)
1446    {
1447       log_error(LOG_LEVEL_ERROR, "Failed to write certificate to %s: %E",
1448          certificate_path);
1449       fclose(fp);
1450       return -1;
1451    }
1452    fclose(fp);
1453
1454    return 0;
1455
1456 }
1457
1458
1459 /*********************************************************************
1460  *
1461  * Function    :  generate_rsa_key
1462  *
1463  * Description : Generates a new RSA key and saves it in a file.
1464  *
1465  * Parameters  :
1466  *          1  :  rsa_key_path = Path to the key that should be written.
1467  *
1468  * Returns     :  -1 => Error while generating private key
1469  *                 0 => Success.
1470  *
1471  *********************************************************************/
1472 static int generate_rsa_key(const char *rsa_key_path)
1473 {
1474    RsaKey rsa_key;
1475    byte rsa_key_der[4096];
1476    int ret;
1477    byte key_pem[4096];
1478    int der_key_size;
1479    int pem_key_size;
1480    FILE *f = NULL;
1481
1482    assert(file_exists(rsa_key_path) != 1);
1483
1484    wc_InitRsaKey(&rsa_key, NULL);
1485
1486    log_error(LOG_LEVEL_CONNECT, "Making RSA key %s ...", rsa_key_path);
1487    ret = wc_MakeRsaKey(&rsa_key, RSA_KEYSIZE, RSA_KEY_PUBLIC_EXPONENT,
1488       &wolfssl_rng);
1489    if (ret != 0)
1490    {
1491       log_error(LOG_LEVEL_ERROR, "RSA key generation failed");
1492       ret = -1;
1493       goto exit;
1494    }
1495    log_error(LOG_LEVEL_CONNECT, "Done making RSA key %s", rsa_key_path);
1496
1497    der_key_size = wc_RsaKeyToDer(&rsa_key, rsa_key_der, sizeof(rsa_key_der));
1498    wc_FreeRsaKey(&rsa_key);
1499    if (der_key_size < 0)
1500    {
1501       log_error(LOG_LEVEL_ERROR, "RSA key conversion to DER format failed");
1502       ret = -1;
1503       goto exit;
1504    }
1505    pem_key_size = wc_DerToPem(rsa_key_der, (word32)der_key_size,
1506       key_pem, sizeof(key_pem), PRIVATEKEY_TYPE);
1507    if (pem_key_size < 0)
1508    {
1509       log_error(LOG_LEVEL_ERROR, "RSA key conversion to PEM format failed");
1510       ret = -1;
1511       goto exit;
1512    }
1513
1514    /*
1515     * Saving key into file
1516     */
1517    if ((f = fopen(rsa_key_path, "wb")) == NULL)
1518    {
1519       log_error(LOG_LEVEL_ERROR,
1520          "Opening file %s to save private key failed: %E",
1521          rsa_key_path);
1522       ret = -1;
1523       goto exit;
1524    }
1525
1526    if (fwrite(key_pem, 1, (size_t)pem_key_size, f) != pem_key_size)
1527    {
1528       log_error(LOG_LEVEL_ERROR,
1529          "Writing private key into file %s failed",
1530          rsa_key_path);
1531       close_file_stream(f, rsa_key_path);
1532       ret = -1;
1533       goto exit;
1534    }
1535
1536    close_file_stream(f, rsa_key_path);
1537
1538 exit:
1539
1540    return ret;
1541
1542 }
1543
1544
1545 /*********************************************************************
1546  *
1547  * Function    :  ssl_certificate_load
1548  *
1549  * Description :  Loads certificate from file.
1550  *
1551  * Parameters  :
1552  *          1  :  cert_path = The certificate path to load
1553  *
1554  * Returns     :   NULL => error loading certificate,
1555  *                   pointer to certificate instance otherwise
1556  *
1557  *********************************************************************/
1558 static X509 *ssl_certificate_load(const char *cert_path)
1559 {
1560    X509 *cert = NULL;
1561    FILE *cert_f = NULL;
1562
1563    if (!(cert_f = fopen(cert_path, "r")))
1564    {
1565       log_error(LOG_LEVEL_ERROR,
1566          "Error opening certificate file %s: %s", cert_path, strerror(errno));
1567       return NULL;
1568    }
1569
1570    if (!(cert = PEM_read_X509(cert_f, NULL, NULL, NULL)))
1571    {
1572       log_ssl_errors(LOG_LEVEL_ERROR,
1573          "Error reading certificate file %s", cert_path);
1574    }
1575
1576    close_file_stream(cert_f, cert_path);
1577    return cert;
1578 }
1579
1580
1581 /*********************************************************************
1582  *
1583  * Function    :  ssl_certificate_is_invalid
1584  *
1585  * Description :  Checks whether or not a certificate is valid.
1586  *                Currently only checks that the certificate can be
1587  *                parsed and that the "valid to" date is in the future.
1588  *
1589  * Parameters  :
1590  *          1  :  cert_file = The certificate to check
1591  *
1592  * Returns     :   0 => The certificate is valid.
1593  *                 1 => The certificate is invalid
1594  *
1595  *********************************************************************/
1596 static int ssl_certificate_is_invalid(const char *cert_file)
1597 {
1598    int ret;
1599
1600    X509 *cert = NULL;
1601
1602    if (!(cert = ssl_certificate_load(cert_file)))
1603    {
1604       return 1;
1605    }
1606
1607    ret = wolfSSL_X509_cmp_current_time(wolfSSL_X509_get_notAfter(cert));
1608    if (ret == 0)
1609    {
1610       log_ssl_errors(LOG_LEVEL_ERROR,
1611          "Error checking certificate %s validity", cert_file);
1612       ret = -1;
1613    }
1614
1615    wolfSSL_X509_free(cert);
1616
1617    return ret == -1 ? 1 : 0;
1618 }
1619
1620
1621 /*********************************************************************
1622  *
1623  * Function    :  load_rsa_key
1624  *
1625  * Description :  Load a PEM-encoded RSA file into memory.
1626  *
1627  * Parameters  :
1628  *          1  :  rsa_key_path = Path to the file that holds the key.
1629  *          2  :  password = Password to unlock the key. NULL if no
1630  *                           password is required.
1631  *          3  :  rsa_key = Initialized RSA key storage.
1632  *
1633  * Returns     :   0 => Error while creating the key.
1634  *                 1 => It worked
1635  *
1636  *********************************************************************/
1637 static int load_rsa_key(const char *rsa_key_path, const char *password, RsaKey *rsa_key)
1638 {
1639    FILE *fp;
1640    size_t length;
1641    long ret;
1642    unsigned char *key_pem;
1643    DerBuffer *der_buffer;
1644    word32 der_index = 0;
1645    DerBuffer decrypted_der_buffer;
1646    unsigned char der_data[4096];
1647
1648    fp = fopen(rsa_key_path, "rb");
1649    if (NULL == fp)
1650    {
1651       log_error(LOG_LEVEL_ERROR, "Failed to open %s: %E", rsa_key_path);
1652       return 0;
1653    }
1654
1655    /* Get file length */
1656    if (fseek(fp, 0, SEEK_END))
1657    {
1658       log_error(LOG_LEVEL_ERROR,
1659          "Unexpected error while fseek()ing to the end of %s: %E",
1660          rsa_key_path);
1661       fclose(fp);
1662       return 0;
1663    }
1664    ret = ftell(fp);
1665    if (-1 == ret)
1666    {
1667       log_error(LOG_LEVEL_ERROR,
1668          "Unexpected ftell() error while loading %s: %E",
1669          rsa_key_path);
1670       fclose(fp);
1671       return 0;
1672    }
1673    length = (size_t)ret;
1674
1675    /* Go back to the beginning. */
1676    if (fseek(fp, 0, SEEK_SET))
1677    {
1678       log_error(LOG_LEVEL_ERROR,
1679          "Unexpected error while fseek()ing to the beginning of %s: %E",
1680          rsa_key_path);
1681       fclose(fp);
1682       return 0;
1683    }
1684
1685    key_pem = malloc_or_die(length);
1686
1687    if (1 != fread(key_pem, length, 1, fp))
1688    {
1689       log_error(LOG_LEVEL_ERROR,
1690          "Couldn't completely read file %s.", rsa_key_path);
1691       fclose(fp);
1692       freez(key_pem);
1693       return 0;
1694    }
1695
1696    fclose(fp);
1697
1698    if (password == NULL)
1699    {
1700       ret = wc_PemToDer(key_pem, (long)length, PRIVATEKEY_TYPE,
1701          &der_buffer, NULL, NULL, NULL);
1702    }
1703    else
1704    {
1705       der_buffer = &decrypted_der_buffer;
1706       der_buffer->buffer = der_data;
1707       ret = wc_KeyPemToDer(key_pem, (int)length, der_buffer->buffer,
1708          sizeof(der_data), password);
1709       if (ret < 0)
1710       {
1711          log_error(LOG_LEVEL_ERROR,
1712             "Failed to convert PEM key %s into DER format. Error: %ld",
1713             rsa_key_path, ret);
1714          freez(key_pem);
1715          return 0;
1716       }
1717       der_buffer->length = (word32)ret;
1718    }
1719
1720    freez(key_pem);
1721
1722    if (ret < 0)
1723    {
1724       log_error(LOG_LEVEL_ERROR,
1725          "Failed to convert buffer into DER format for file %s. Error = %ld",
1726          rsa_key_path, ret);
1727       return 0;
1728    }
1729
1730    ret = wc_RsaPrivateKeyDecode(der_buffer->buffer, &der_index, rsa_key,
1731       der_buffer->length);
1732    if (password == NULL)
1733    {
1734       freez(der_buffer);
1735    }
1736    if (ret < 0)
1737    {
1738       log_error(LOG_LEVEL_ERROR,
1739          "Failed to decode DER buffer into RSA key structure for %s",
1740          rsa_key_path);
1741       return 0;
1742    }
1743
1744    return 1;
1745 }
1746
1747 #ifndef WOLFSSL_ALT_NAMES
1748 #error wolfSSL lacks Subject Alternative Name support (WOLFSSL_ALT_NAMES) which is mandatory
1749 #endif
1750 /*********************************************************************
1751  *
1752  * Function    :  set_subject_alternative_name
1753  *
1754  * Description :  Sets the Subject Alternative Name extension to
1755  *                a cert using the awesome "API" provided by wolfSSL.
1756  *
1757  * Parameters  :
1758  *          1  :  cert = The certificate to modify
1759  *          2  :  hostname = The hostname to add
1760  *
1761  * Returns     :  <0 => Error.
1762  *                 0 => It worked
1763  *
1764  *********************************************************************/
1765 static int set_subject_alternative_name(struct Cert *certificate, const char *hostname)
1766 {
1767    const size_t hostname_length = strlen(hostname);
1768
1769    if (hostname_length >= 253)
1770    {
1771       /*
1772        * We apparently only have a byte to represent the length
1773        * of the sequence.
1774        */
1775       log_error(LOG_LEVEL_ERROR,
1776          "Hostname '%s' is too long to set Subject Alternative Name",
1777          hostname);
1778       return -1;
1779    }
1780    certificate->altNames[0] = 0x30; /* Sequence */
1781    certificate->altNames[1] = (unsigned char)hostname_length + 2;
1782
1783    certificate->altNames[2] = 0x82; /* DNS name */
1784    certificate->altNames[3] = (unsigned char)hostname_length;
1785    memcpy(&certificate->altNames[4], hostname, hostname_length);
1786
1787    certificate->altNamesSz = (int)hostname_length + 4;
1788
1789    return 0;
1790 }
1791
1792
1793 /*********************************************************************
1794  *
1795  * Function    :  generate_host_certificate
1796  *
1797  * Description :  Creates certificate file in presetted directory.
1798  *                If certificate already exists, no other certificate
1799  *                will be created. Subject of certificate is named
1800  *                by csp->http->host from parameter. This function also
1801  *                triggers generating of private key for new certificate.
1802  *
1803  * Parameters  :
1804  *          1  :  csp = Current client state (buffers, headers, etc...)
1805  *          2  :  certificate_path = Path to the certficate to generate.
1806  *          3  :  rsa_key_path = Path to the key to generate for the
1807  *                               certificate.
1808  *
1809  * Returns     :  -1 => Error while creating certificate.
1810  *                 0 => Certificate already exists.
1811  *                 1 => Certificate created
1812  *
1813  *********************************************************************/
1814 static int generate_host_certificate(struct client_state *csp,
1815    const char *certificate_path, const char *rsa_key_path)
1816 {
1817    struct Cert certificate;
1818    RsaKey ca_key;
1819    RsaKey rsa_key;
1820    int ret;
1821    byte certificate_der[4096];
1822    int der_certificate_length;
1823    byte certificate_pem[4096];
1824    int pem_certificate_length;
1825
1826    if (file_exists(certificate_path) == 1)
1827    {
1828       /* The file exists, but is it valid? */
1829       if (ssl_certificate_is_invalid(certificate_path))
1830       {
1831          log_error(LOG_LEVEL_CONNECT,
1832             "Certificate %s is no longer valid. Removing it.",
1833             certificate_path);
1834          if (unlink(certificate_path))
1835          {
1836             log_error(LOG_LEVEL_ERROR, "Failed to unlink %s: %E",
1837                certificate_path);
1838             return -1;
1839          }
1840          if (unlink(rsa_key_path))
1841          {
1842             log_error(LOG_LEVEL_ERROR, "Failed to unlink %s: %E",
1843                rsa_key_path);
1844             return -1;
1845          }
1846       }
1847       else
1848       {
1849          return 0;
1850       }
1851    }
1852    else
1853    {
1854       log_error(LOG_LEVEL_CONNECT, "Creating new certificate %s",
1855          certificate_path);
1856    }
1857    if (enforce_sane_certificate_state(certificate_path, rsa_key_path))
1858    {
1859       return -1;
1860    }
1861
1862    wc_InitRsaKey(&rsa_key, NULL);
1863    wc_InitRsaKey(&ca_key, NULL);
1864
1865    if (generate_rsa_key(rsa_key_path) == -1)
1866    {
1867       return -1;
1868    }
1869
1870    wc_InitCert(&certificate);
1871
1872    strncpy(certificate.subject.country, CERT_PARAM_COUNTRY_CODE, CTC_NAME_SIZE);
1873    strncpy(certificate.subject.org, "Privoxy", CTC_NAME_SIZE);
1874    strncpy(certificate.subject.unit, "Development", CTC_NAME_SIZE);
1875    strncpy(certificate.subject.commonName, csp->http->host, CTC_NAME_SIZE);
1876    certificate.daysValid = 90;
1877    certificate.selfSigned = 0;
1878    certificate.sigType = CTC_SHA256wRSA;
1879    if (!host_is_ip_address(csp->http->host) &&
1880        set_subject_alternative_name(&certificate, csp->http->host))
1881    {
1882       ret = -1;
1883       goto exit;
1884    }
1885
1886    ret = wc_SetIssuer(&certificate, csp->config->ca_cert_file);
1887    if (ret < 0)
1888    {
1889       log_error(LOG_LEVEL_ERROR,
1890          "Failed to set Issuer file %s", csp->config->ca_cert_file);
1891       ret = -1;
1892       goto exit;
1893    }
1894
1895    if (load_rsa_key(rsa_key_path, NULL, &rsa_key) != 1)
1896    {
1897       log_error(LOG_LEVEL_ERROR,
1898          "Failed to load RSA key %s", rsa_key_path);
1899       ret = -1;
1900       goto exit;
1901    }
1902
1903    /* wolfSSL_Debugging_ON(); */
1904    der_certificate_length = wc_MakeCert(&certificate, certificate_der,
1905       sizeof(certificate_der), &rsa_key, NULL, &wolfssl_rng);
1906    /* wolfSSL_Debugging_OFF(); */
1907
1908    if (der_certificate_length < 0)
1909    {
1910       log_error(LOG_LEVEL_ERROR, "Failed to make certificate");
1911       ret = -1;
1912       goto exit;
1913    }
1914
1915    if (load_rsa_key(csp->config->ca_key_file, csp->config->ca_password,
1916       &ca_key) != 1)
1917    {
1918       log_error(LOG_LEVEL_ERROR,
1919          "Failed to load CA key %s", csp->config->ca_key_file);
1920       ret = -1;
1921       goto exit;
1922    }
1923
1924    der_certificate_length = wc_SignCert(certificate.bodySz, certificate.sigType,
1925       certificate_der, sizeof(certificate_der), &ca_key, NULL, &wolfssl_rng);
1926    wc_FreeRsaKey(&ca_key);
1927    if (der_certificate_length < 0)
1928    {
1929       log_error(LOG_LEVEL_ERROR, "Failed to sign certificate");
1930       ret = -1;
1931       goto exit;
1932    }
1933
1934    pem_certificate_length = wc_DerToPem(certificate_der,
1935       (word32)der_certificate_length, certificate_pem,
1936       sizeof(certificate_pem), CERT_TYPE);
1937    if (pem_certificate_length < 0)
1938    {
1939       log_error(LOG_LEVEL_ERROR,
1940          "Failed to convert certificate from DER to PEM");
1941       ret = -1;
1942       goto exit;
1943    }
1944    certificate_pem[pem_certificate_length] = '\0';
1945
1946    if (write_certificate(certificate_path, (const char*)certificate_pem))
1947    {
1948       ret = -1;
1949       goto exit;
1950    }
1951
1952    ret = 1;
1953
1954 exit:
1955    wc_FreeRsaKey(&rsa_key);
1956    wc_FreeRsaKey(&ca_key);
1957
1958    return 1;
1959
1960 }
1961
1962
1963 /*********************************************************************
1964  *
1965  * Function    :  ssl_crt_verify_info
1966  *
1967  * Description :  Returns an informational string about the verification
1968  *                status of a certificate.
1969  *
1970  * Parameters  :
1971  *          1  :  buf = Buffer to write to
1972  *          2  :  size = Maximum size of buffer
1973  *          3  :  csp = client state
1974  *
1975  * Returns     :  N/A
1976  *
1977  *********************************************************************/
1978 extern void ssl_crt_verify_info(char *buf, size_t size, struct client_state *csp)
1979 {
1980    strncpy(buf, wolfSSL_X509_verify_cert_error_string(
1981       csp->server_cert_verification_result), size);
1982    buf[size - 1] = 0;
1983 }
1984
1985
1986 #ifdef FEATURE_GRACEFUL_TERMINATION
1987 /*********************************************************************
1988  *
1989  * Function    :  ssl_release
1990  *
1991  * Description :  Release all SSL resources
1992  *
1993  * Parameters  :
1994  *
1995  * Returns     :  N/A
1996  *
1997  *********************************************************************/
1998 extern void ssl_release(void)
1999 {
2000    if (wolfssl_initialized == 1)
2001    {
2002       wc_FreeRng(&wolfssl_rng);
2003       wolfSSL_Cleanup();
2004    }
2005 }
2006 #endif /* def FEATURE_GRACEFUL_TERMINATION */