0357efa1ce72eced6783e2a7ce98bacdf9c20d58
[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-2021 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 = 2 };
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       if (WOLFSSL_SUCCESS != ret)
977       {
978          shutdown_attempts++;
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 }
995
996
997 /*********************************************************************
998  *
999  * Function    :  close_client_ssl_connection
1000  *
1001  * Description :  Closes TLS connection with client. This function
1002  *                checks if this connection is already created.
1003  *
1004  * Parameters  :
1005  *          1  :  csp = Current client state (buffers, headers, etc...)
1006  *
1007  * Returns     :  N/A
1008  *
1009  *********************************************************************/
1010 extern void close_client_ssl_connection(struct client_state *csp)
1011 {
1012    struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
1013
1014    if (csp->ssl_with_client_is_opened == 0)
1015    {
1016       return;
1017    }
1018
1019    /*
1020     * Notify the peer that the connection is being closed.
1021     */
1022    shutdown_connection(ssl_attr->wolfssl_attr.ssl, "client");
1023
1024    free_client_ssl_structures(csp);
1025    csp->ssl_with_client_is_opened = 0;
1026 }
1027
1028
1029 /*********************************************************************
1030  *
1031  * Function    :  free_client_ssl_structures
1032  *
1033  * Description :  Frees structures used for SSL communication with
1034  *                client.
1035  *
1036  * Parameters  :
1037  *          1  :  csp = Current client state (buffers, headers, etc...)
1038  *
1039  * Returns     :  N/A
1040  *
1041  *********************************************************************/
1042 static void free_client_ssl_structures(struct client_state *csp)
1043 {
1044    struct ssl_attr *ssl_attr = &csp->ssl_client_attr;
1045
1046    if (ssl_attr->wolfssl_attr.ssl)
1047    {
1048       wolfSSL_free(ssl_attr->wolfssl_attr.ssl);
1049    }
1050    if (ssl_attr->wolfssl_attr.ctx)
1051    {
1052       wolfSSL_CTX_free(ssl_attr->wolfssl_attr.ctx);
1053    }
1054 }
1055
1056
1057 /*********************************************************************
1058  *
1059  * Function    :  close_server_ssl_connection
1060  *
1061  * Description :  Closes TLS connection with server. This function
1062  *                checks if this connection is already opened.
1063  *
1064  * Parameters  :
1065  *          1  :  csp = Current client state (buffers, headers, etc...)
1066  *
1067  * Returns     :  N/A
1068  *
1069  *********************************************************************/
1070 extern void close_server_ssl_connection(struct client_state *csp)
1071 {
1072    struct ssl_attr *ssl_attr = &csp->ssl_server_attr;
1073
1074    if (csp->ssl_with_server_is_opened == 0)
1075    {
1076       return;
1077    }
1078
1079    /*
1080    * Notify the peer that the connection is being closed.
1081    */
1082    shutdown_connection(ssl_attr->wolfssl_attr.ssl, "server");
1083
1084    free_server_ssl_structures(csp);
1085    csp->ssl_with_server_is_opened = 0;
1086 }
1087
1088
1089 /*********************************************************************
1090  *
1091  * Function    :  create_server_ssl_connection
1092  *
1093  * Description :  Creates TLS-secured connection with the server.
1094  *
1095  * Parameters  :
1096  *          1  :  csp = Current client state (buffers, headers, etc...)
1097  *
1098  * Returns     :  0 on success, negative value if connection wasn't created
1099  *                successfully.
1100  *
1101  *********************************************************************/
1102 extern int create_server_ssl_connection(struct client_state *csp)
1103 {
1104    wolfssl_connection_attr *ssl_attrs = &csp->ssl_server_attr.wolfssl_attr;
1105    int ret = 0;
1106    WOLFSSL *ssl;
1107    int connect_ret = 0;
1108
1109    csp->server_cert_verification_result = SSL_CERT_NOT_VERIFIED;
1110    csp->server_certs_chain.next = NULL;
1111
1112    ssl_attrs->ctx = wolfSSL_CTX_new(wolfSSLv23_method());
1113    if (ssl_attrs->ctx == NULL)
1114    {
1115       log_ssl_errors(LOG_LEVEL_ERROR, "TLS context creation failed");
1116       ret = -1;
1117       goto exit;
1118    }
1119
1120    if (csp->dont_verify_certificate)
1121    {
1122       wolfSSL_CTX_set_verify(ssl_attrs->ctx, WOLFSSL_VERIFY_NONE, NULL);
1123    }
1124    else if (wolfSSL_CTX_load_verify_locations(ssl_attrs->ctx,
1125       csp->config->trusted_cas_file, NULL) != WOLFSSL_SUCCESS)
1126    {
1127       log_ssl_errors(LOG_LEVEL_ERROR, "Loading trusted CAs file %s failed",
1128          csp->config->trusted_cas_file);
1129       ret = -1;
1130       goto exit;
1131    }
1132
1133    wolfSSL_CTX_set_options(ssl_attrs->ctx, WOLFSSL_OP_NO_SSLv3);
1134
1135    ssl = ssl_attrs->ssl = wolfSSL_new(ssl_attrs->ctx);
1136
1137    if (wolfSSL_set_fd(ssl, csp->server_connection.sfd) != WOLFSSL_SUCCESS)
1138    {
1139       log_ssl_errors(LOG_LEVEL_ERROR,
1140          "wolfSSL_set_fd() failed to set the server socket");
1141       ret = -1;
1142       goto exit;
1143    }
1144
1145    if (csp->config->cipher_list != NULL)
1146    {
1147       if (wolfSSL_set_cipher_list(ssl, csp->config->cipher_list) != WOLFSSL_SUCCESS)
1148       {
1149          log_ssl_errors(LOG_LEVEL_ERROR,
1150             "Setting the cipher list '%s' for the server connection failed",
1151             csp->config->cipher_list);
1152          ret = -1;
1153          goto exit;
1154       }
1155    }
1156
1157    ret = wolfSSL_UseSNI(ssl, WOLFSSL_SNI_HOST_NAME,
1158       csp->http->host, (unsigned short)strlen(csp->http->host));
1159    if (ret != WOLFSSL_SUCCESS)
1160    {
1161       log_ssl_errors(LOG_LEVEL_ERROR, "Failed to set use of SNI");
1162       ret = -1;
1163       goto exit;
1164    }
1165
1166    ret = wolfSSL_check_domain_name(ssl, csp->http->host);
1167    if (ret != WOLFSSL_SUCCESS)
1168    {
1169       char buffer[80];
1170       int error = wolfSSL_get_error(ssl, ret);
1171       log_error(LOG_LEVEL_FATAL,
1172          "Failed to set check domain name. error = %d, %s",
1173          error, wolfSSL_ERR_error_string((unsigned long)error, buffer));
1174       ret = -1;
1175       goto exit;
1176    }
1177
1178 #ifdef HAVE_SECURE_RENEGOTIATION
1179 #warning wolfssl has been compiled with HAVE_SECURE_RENEGOTIATION while you probably want HAVE_RENEGOTIATION_INDICATION
1180    if(wolfSSL_UseSecureRenegotiation(ssl) != WOLFSSL_SUCCESS)
1181    {
1182       log_ssl_errors(LOG_LEVEL_ERROR,
1183          "Failed to enable 'Secure' Renegotiation. Continuing anyway.");
1184    }
1185 #endif
1186 #ifndef HAVE_RENEGOTIATION_INDICATION
1187 #warning Looks like wolfssl has been compiled without HAVE_RENEGOTIATION_INDICATION
1188 #endif
1189
1190    log_error(LOG_LEVEL_CONNECT,
1191       "Performing the TLS/SSL handshake with the server");
1192
1193    /* wolfSSL_Debugging_ON(); */
1194    connect_ret = wolfSSL_connect(ssl);
1195    /* wolfSSL_Debugging_OFF(); */
1196
1197    /*
1198    wolfSSL_Debugging_ON();
1199    */
1200    if (!csp->dont_verify_certificate)
1201    {
1202       long verify_result = wolfSSL_get_error(ssl, connect_ret);
1203
1204       if (verify_result == WOLFSSL_X509_V_OK)
1205       {
1206          ret = 0;
1207          csp->server_cert_verification_result = SSL_CERT_VALID;
1208       }
1209       else
1210       {
1211          WOLF_STACK_OF(WOLFSSL_X509) *chain;
1212
1213          csp->server_cert_verification_result = verify_result;
1214          log_error(LOG_LEVEL_ERROR,
1215             "X509 certificate verification for %s failed with error %ld: %s",
1216             csp->http->hostport, verify_result,
1217             wolfSSL_X509_verify_cert_error_string(verify_result));
1218
1219          chain = wolfSSL_get_peer_cert_chain(ssl);
1220          if (chain != NULL)
1221          {
1222             int i;
1223             for (i = 0; i < wolfSSL_sk_X509_num(chain); i++)
1224             {
1225                if (ssl_store_cert(csp, wolfSSL_sk_X509_value(chain, i)) != 0)
1226                {
1227                   log_error(LOG_LEVEL_ERROR,
1228                      "ssl_store_cert() failed for cert %d", i);
1229                   /*
1230                    * ssl_send_certificate_error() wil not be able to show
1231                    * the certificate but the user will stil get the error
1232                    * description.
1233                    */
1234                }
1235             }
1236          }
1237
1238          ret = -1;
1239          goto exit;
1240       }
1241    }
1242    /*
1243    wolfSSL_Debugging_OFF();
1244    */
1245    if (connect_ret == WOLFSSL_SUCCESS)
1246    {
1247       log_error(LOG_LEVEL_CONNECT,
1248          "Server successfully connected over %s (%s).",
1249          wolfSSL_get_version(ssl), wolfSSL_get_cipher_name(ssl));
1250       csp->ssl_with_server_is_opened = 1;
1251       ret = 0;
1252    }
1253    else
1254    {
1255       char buffer[80];
1256       int error = wolfSSL_get_error(ssl, ret);
1257       log_error(LOG_LEVEL_ERROR,
1258          "The TLS handshake with the server %s failed. error = %d, %s",
1259          csp->http->hostport,
1260          error, wolfSSL_ERR_error_string((unsigned long)error, buffer));
1261       ret = -1;
1262    }
1263
1264 exit:
1265    /* Freeing structures if connection wasn't created successfully */
1266    if (ret < 0)
1267    {
1268       free_server_ssl_structures(csp);
1269    }
1270
1271    return ret;
1272 }
1273
1274
1275 /*********************************************************************
1276  *
1277  * Function    :  free_server_ssl_structures
1278  *
1279  * Description :  Frees structures used for SSL communication with server
1280  *
1281  * Parameters  :
1282  *          1  :  csp = Current client state (buffers, headers, etc...)
1283  *
1284  * Returns     :  N/A
1285  *
1286  *********************************************************************/
1287 static void free_server_ssl_structures(struct client_state *csp)
1288 {
1289    struct ssl_attr *ssl_attr = &csp->ssl_server_attr;
1290
1291    if (ssl_attr->wolfssl_attr.ssl)
1292    {
1293       wolfSSL_free(ssl_attr->wolfssl_attr.ssl);
1294    }
1295    if (ssl_attr->wolfssl_attr.ctx)
1296    {
1297       wolfSSL_CTX_free(ssl_attr->wolfssl_attr.ctx);
1298    }
1299 }
1300
1301
1302 /*********************************************************************
1303  *
1304  * Function    :  log_ssl_errors
1305  *
1306  * Description :  Log SSL errors
1307  *
1308  * Parameters  :
1309  *          1  :  debuglevel = Debug level
1310  *          2  :  desc = Error description
1311  *
1312  * Returns     :  N/A
1313  *
1314  *********************************************************************/
1315 static void log_ssl_errors(int debuglevel, const char* fmt, ...)
1316 {
1317    unsigned long err_code;
1318    char prefix[ERROR_BUF_SIZE];
1319    va_list args;
1320    va_start(args, fmt);
1321    vsnprintf(prefix, sizeof(prefix), fmt, args);
1322    int reported = 0;
1323
1324    while ((err_code = wolfSSL_ERR_get_error()))
1325    {
1326       char err_buf[ERROR_BUF_SIZE];
1327       reported = 1;
1328       wolfSSL_ERR_error_string_n(err_code, err_buf, sizeof(err_buf));
1329       log_error(debuglevel, "%s: %s", prefix, err_buf);
1330    }
1331    va_end(args);
1332    /*
1333     * In case if called by mistake and there were
1334     * no TLS errors let's report it to the log.
1335     */
1336    if (!reported)
1337    {
1338       log_error(debuglevel, "%s: no TLS errors detected", prefix);
1339    }
1340 }
1341
1342
1343 /*********************************************************************
1344  *
1345  * Function    :  ssl_base64_encode
1346  *
1347  * Description :  Encode a buffer into base64 format.
1348  *
1349  * Parameters  :
1350  *          1  :  dst = Destination buffer
1351  *          2  :  dlen = Destination buffer length
1352  *          3  :  olen = Number of bytes written
1353  *          4  :  src = Source buffer
1354  *          5  :  slen = Amount of data to be encoded
1355  *
1356  * Returns     :  0 on success, error code othervise
1357  *
1358  *********************************************************************/
1359 extern int ssl_base64_encode(unsigned char *dst, size_t dlen, size_t *olen,
1360                              const unsigned char *src, size_t slen)
1361 {
1362    word32 output_length;
1363    int ret;
1364
1365    *olen = 4 * ((slen/3) + ((slen%3) ? 1 : 0)) + 1;
1366    if (*olen > dlen)
1367    {
1368       return ENOBUFS;
1369    }
1370
1371    output_length = (word32)dlen;
1372    ret = Base64_Encode_NoNl(src, (word32)slen, dst, &output_length);
1373    if (ret != 0)
1374    {
1375       log_error(LOG_LEVEL_ERROR, "base64 encoding failed with %d", ret);
1376       return ret;
1377    }
1378    *olen = output_length;
1379
1380    return 0;
1381
1382 }
1383
1384
1385 /*********************************************************************
1386  *
1387  * Function    :  close_file_stream
1388  *
1389  * Description :  Close file stream, report error on close error
1390  *
1391  * Parameters  :
1392  *          1  :  f = file stream to close
1393  *          2  :  path = path for error report
1394  *
1395  * Returns     :  N/A
1396  *
1397  *********************************************************************/
1398 static void close_file_stream(FILE *f, const char *path)
1399 {
1400    if (fclose(f) != 0)
1401    {
1402       log_error(LOG_LEVEL_ERROR,
1403          "Error closing file %s: %s", path, strerror(errno));
1404    }
1405 }
1406
1407
1408 /*********************************************************************
1409  *
1410  * Function    :  write_certificate
1411  *
1412  * Description :  Writes a PEM-encoded certificate to a file.
1413  *
1414  * Parameters  :
1415  *          1  :  certificate_path = Path to the file to create
1416  *          2  :  certificate = PEM-encoded certificate to write.
1417  *
1418  * Returns     :  NULL => Error. Otherwise a key;
1419  *
1420  *********************************************************************/
1421 static int write_certificate(const char *certificate_path, const char *certificate)
1422 {
1423    FILE *fp;
1424
1425    assert(certificate_path != NULL);
1426    assert(certificate != NULL);
1427
1428    fp = fopen(certificate_path, "wb");
1429    if (NULL == fp)
1430    {
1431       log_error(LOG_LEVEL_ERROR,
1432          "Failed to open %s to write the certificate: %E",
1433          certificate_path);
1434       return -1;
1435    }
1436    if (fputs(certificate, fp) < 0)
1437    {
1438       log_error(LOG_LEVEL_ERROR, "Failed to write certificate to %s: %E",
1439          certificate_path);
1440       fclose(fp);
1441       return -1;
1442    }
1443    fclose(fp);
1444
1445    return 0;
1446
1447 }
1448
1449
1450 /*********************************************************************
1451  *
1452  * Function    :  generate_rsa_key
1453  *
1454  * Description : Generates a new RSA key and saves it in a file.
1455  *
1456  * Parameters  :
1457  *          1  :  rsa_key_path = Path to the key that should be written.
1458  *
1459  * Returns     :  -1 => Error while generating private key
1460  *                 0 => Success.
1461  *
1462  *********************************************************************/
1463 static int generate_rsa_key(const char *rsa_key_path)
1464 {
1465    RsaKey rsa_key;
1466    byte rsa_key_der[4096];
1467    int ret;
1468    byte key_pem[4096];
1469    int der_key_size;
1470    int pem_key_size;
1471    FILE *f = NULL;
1472
1473    assert(file_exists(rsa_key_path) != 1);
1474
1475    wc_InitRsaKey(&rsa_key, NULL);
1476
1477    log_error(LOG_LEVEL_CONNECT, "Making RSA key %s ...", rsa_key_path);
1478    ret = wc_MakeRsaKey(&rsa_key, RSA_KEYSIZE, RSA_KEY_PUBLIC_EXPONENT,
1479       &wolfssl_rng);
1480    if (ret != 0)
1481    {
1482       log_error(LOG_LEVEL_ERROR, "RSA key generation failed");
1483       ret = -1;
1484       goto exit;
1485    }
1486    log_error(LOG_LEVEL_CONNECT, "Done making RSA key %s", rsa_key_path);
1487
1488    der_key_size = wc_RsaKeyToDer(&rsa_key, rsa_key_der, sizeof(rsa_key_der));
1489    wc_FreeRsaKey(&rsa_key);
1490    if (der_key_size < 0)
1491    {
1492       log_error(LOG_LEVEL_ERROR, "RSA key conversion to DER format failed");
1493       ret = -1;
1494       goto exit;
1495    }
1496    pem_key_size = wc_DerToPem(rsa_key_der, (word32)der_key_size,
1497       key_pem, sizeof(key_pem), PRIVATEKEY_TYPE);
1498    if (pem_key_size < 0)
1499    {
1500       log_error(LOG_LEVEL_ERROR, "RSA key conversion to PEM format failed");
1501       ret = -1;
1502       goto exit;
1503    }
1504
1505    /*
1506     * Saving key into file
1507     */
1508    if ((f = fopen(rsa_key_path, "wb")) == NULL)
1509    {
1510       log_error(LOG_LEVEL_ERROR,
1511          "Opening file %s to save private key failed: %E",
1512          rsa_key_path);
1513       ret = -1;
1514       goto exit;
1515    }
1516
1517    if (fwrite(key_pem, 1, (size_t)pem_key_size, f) != pem_key_size)
1518    {
1519       log_error(LOG_LEVEL_ERROR,
1520          "Writing private key into file %s failed",
1521          rsa_key_path);
1522       close_file_stream(f, rsa_key_path);
1523       ret = -1;
1524       goto exit;
1525    }
1526
1527    close_file_stream(f, rsa_key_path);
1528
1529 exit:
1530
1531    return ret;
1532
1533 }
1534
1535
1536 /*********************************************************************
1537  *
1538  * Function    :  ssl_certificate_load
1539  *
1540  * Description :  Loads certificate from file.
1541  *
1542  * Parameters  :
1543  *          1  :  cert_path = The certificate path to load
1544  *
1545  * Returns     :   NULL => error loading certificate,
1546  *                   pointer to certificate instance otherwise
1547  *
1548  *********************************************************************/
1549 static X509 *ssl_certificate_load(const char *cert_path)
1550 {
1551    X509 *cert = NULL;
1552    FILE *cert_f = NULL;
1553
1554    if (!(cert_f = fopen(cert_path, "r")))
1555    {
1556       log_error(LOG_LEVEL_ERROR,
1557          "Error opening certificate file %s: %s", cert_path, strerror(errno));
1558       return NULL;
1559    }
1560
1561    if (!(cert = PEM_read_X509(cert_f, NULL, NULL, NULL)))
1562    {
1563       log_ssl_errors(LOG_LEVEL_ERROR,
1564          "Error reading certificate file %s", cert_path);
1565    }
1566
1567    close_file_stream(cert_f, cert_path);
1568    return cert;
1569 }
1570
1571
1572 /*********************************************************************
1573  *
1574  * Function    :  ssl_certificate_is_invalid
1575  *
1576  * Description :  Checks whether or not a certificate is valid.
1577  *                Currently only checks that the certificate can be
1578  *                parsed and that the "valid to" date is in the future.
1579  *
1580  * Parameters  :
1581  *          1  :  cert_file = The certificate to check
1582  *
1583  * Returns     :   0 => The certificate is valid.
1584  *                 1 => The certificate is invalid
1585  *
1586  *********************************************************************/
1587 static int ssl_certificate_is_invalid(const char *cert_file)
1588 {
1589    int ret;
1590
1591    X509 *cert = NULL;
1592
1593    if (!(cert = ssl_certificate_load(cert_file)))
1594    {
1595       return 1;
1596    }
1597
1598    ret = wolfSSL_X509_cmp_current_time(wolfSSL_X509_get_notAfter(cert));
1599    if (ret == 0)
1600    {
1601       log_ssl_errors(LOG_LEVEL_ERROR,
1602          "Error checking certificate %s validity", cert_file);
1603       ret = -1;
1604    }
1605
1606    wolfSSL_X509_free(cert);
1607
1608    return ret == -1 ? 1 : 0;
1609 }
1610
1611
1612 /*********************************************************************
1613  *
1614  * Function    :  load_rsa_key
1615  *
1616  * Description :  Load a PEM-encoded RSA file into memory.
1617  *
1618  * Parameters  :
1619  *          1  :  rsa_key_path = Path to the file that holds the key.
1620  *          2  :  password = Password to unlock the key. NULL if no
1621  *                           password is required.
1622  *          3  :  rsa_key = Initialized RSA key storage.
1623  *
1624  * Returns     :   0 => Error while creating the key.
1625  *                 1 => It worked
1626  *
1627  *********************************************************************/
1628 static int load_rsa_key(const char *rsa_key_path, const char *password, RsaKey *rsa_key)
1629 {
1630    FILE *fp;
1631    size_t length;
1632    long ret;
1633    unsigned char *key_pem;
1634    DerBuffer *der_buffer;
1635    word32 der_index = 0;
1636    DerBuffer decrypted_der_buffer;
1637    unsigned char der_data[4096];
1638
1639    fp = fopen(rsa_key_path, "rb");
1640    if (NULL == fp)
1641    {
1642       log_error(LOG_LEVEL_ERROR, "Failed to open %s: %E", rsa_key_path);
1643       return 0;
1644    }
1645
1646    /* Get file length */
1647    if (fseek(fp, 0, SEEK_END))
1648    {
1649       log_error(LOG_LEVEL_ERROR,
1650          "Unexpected error while fseek()ing to the end of %s: %E",
1651          rsa_key_path);
1652       fclose(fp);
1653       return 0;
1654    }
1655    ret = ftell(fp);
1656    if (-1 == ret)
1657    {
1658       log_error(LOG_LEVEL_ERROR,
1659          "Unexpected ftell() error while loading %s: %E",
1660          rsa_key_path);
1661       fclose(fp);
1662       return 0;
1663    }
1664    length = (size_t)ret;
1665
1666    /* Go back to the beginning. */
1667    if (fseek(fp, 0, SEEK_SET))
1668    {
1669       log_error(LOG_LEVEL_ERROR,
1670          "Unexpected error while fseek()ing to the beginning of %s: %E",
1671          rsa_key_path);
1672       fclose(fp);
1673       return 0;
1674    }
1675
1676    key_pem = malloc_or_die(length);
1677
1678    if (1 != fread(key_pem, length, 1, fp))
1679    {
1680       log_error(LOG_LEVEL_ERROR,
1681          "Couldn't completely read file %s.", rsa_key_path);
1682       fclose(fp);
1683       freez(key_pem);
1684       return 0;
1685    }
1686
1687    fclose(fp);
1688
1689    if (password == NULL)
1690    {
1691       ret = wc_PemToDer(key_pem, (long)length, PRIVATEKEY_TYPE,
1692          &der_buffer, NULL, NULL, NULL);
1693    }
1694    else
1695    {
1696       der_buffer = &decrypted_der_buffer;
1697       der_buffer->buffer = der_data;
1698       ret = wc_KeyPemToDer(key_pem, (int)length, der_buffer->buffer,
1699          sizeof(der_data), password);
1700       if (ret < 0)
1701       {
1702          log_error(LOG_LEVEL_ERROR,
1703             "Failed to convert PEM key %s into DER format. Error: %ld",
1704             rsa_key_path, ret);
1705          freez(key_pem);
1706          return 0;
1707       }
1708       der_buffer->length = (word32)ret;
1709    }
1710
1711    freez(key_pem);
1712
1713    if (ret < 0)
1714    {
1715       log_error(LOG_LEVEL_ERROR,
1716          "Failed to convert buffer into DER format for file %s. Error = %ld",
1717          rsa_key_path, ret);
1718       return 0;
1719    }
1720
1721    ret = wc_RsaPrivateKeyDecode(der_buffer->buffer, &der_index, rsa_key,
1722       der_buffer->length);
1723    if (password == NULL)
1724    {
1725       freez(der_buffer);
1726    }
1727    if (ret < 0)
1728    {
1729       log_error(LOG_LEVEL_ERROR,
1730          "Failed to decode DER buffer into RSA key structure for %s",
1731          rsa_key_path);
1732       return 0;
1733    }
1734
1735    return 1;
1736 }
1737
1738 #ifndef WOLFSSL_ALT_NAMES
1739 #error wolfSSL lacks Subject Alternative Name support (WOLFSSL_ALT_NAMES) which is mandatory
1740 #endif
1741 /*********************************************************************
1742  *
1743  * Function    :  set_subject_alternative_name
1744  *
1745  * Description :  Sets the Subject Alternative Name extension to
1746  *                a cert using the awesome "API" provided by wolfSSL.
1747  *
1748  * Parameters  :
1749  *          1  :  cert = The certificate to modify
1750  *          2  :  hostname = The hostname to add
1751  *
1752  * Returns     :  <0 => Error.
1753  *                 0 => It worked
1754  *
1755  *********************************************************************/
1756 static int set_subject_alternative_name(struct Cert *certificate, const char *hostname)
1757 {
1758    const size_t hostname_length = strlen(hostname);
1759
1760    if (hostname_length >= 253)
1761    {
1762       /*
1763        * We apparently only have a byte to represent the length
1764        * of the sequence.
1765        */
1766       log_error(LOG_LEVEL_ERROR,
1767          "Hostname '%s' is too long to set Subject Alternative Name",
1768          hostname);
1769       return -1;
1770    }
1771    certificate->altNames[0] = 0x30; /* Sequence */
1772    certificate->altNames[1] = (unsigned char)hostname_length + 2;
1773
1774    certificate->altNames[2] = 0x82; /* DNS name */
1775    certificate->altNames[3] = (unsigned char)hostname_length;
1776    memcpy(&certificate->altNames[4], hostname, hostname_length);
1777
1778    certificate->altNamesSz = (int)hostname_length + 4;
1779
1780    return 0;
1781 }
1782
1783
1784 /*********************************************************************
1785  *
1786  * Function    :  generate_host_certificate
1787  *
1788  * Description :  Creates certificate file in presetted directory.
1789  *                If certificate already exists, no other certificate
1790  *                will be created. Subject of certificate is named
1791  *                by csp->http->host from parameter. This function also
1792  *                triggers generating of private key for new certificate.
1793  *
1794  * Parameters  :
1795  *          1  :  csp = Current client state (buffers, headers, etc...)
1796  *          2  :  certificate_path = Path to the certficate to generate.
1797  *          3  :  rsa_key_path = Path to the key to generate for the
1798  *                               certificate.
1799  *
1800  * Returns     :  -1 => Error while creating certificate.
1801  *                 0 => Certificate already exists.
1802  *                 1 => Certificate created
1803  *
1804  *********************************************************************/
1805 static int generate_host_certificate(struct client_state *csp,
1806    const char *certificate_path, const char *rsa_key_path)
1807 {
1808    struct Cert certificate;
1809    RsaKey ca_key;
1810    RsaKey rsa_key;
1811    int ret;
1812    byte certificate_der[4096];
1813    int der_certificate_length;
1814    byte certificate_pem[4096];
1815    int pem_certificate_length;
1816
1817    if (file_exists(certificate_path) == 1)
1818    {
1819       /* The file exists, but is it valid? */
1820       if (ssl_certificate_is_invalid(certificate_path))
1821       {
1822          log_error(LOG_LEVEL_CONNECT,
1823             "Certificate %s is no longer valid. Removing it.",
1824             certificate_path);
1825          if (unlink(certificate_path))
1826          {
1827             log_error(LOG_LEVEL_ERROR, "Failed to unlink %s: %E",
1828                certificate_path);
1829             return -1;
1830          }
1831          if (unlink(rsa_key_path))
1832          {
1833             log_error(LOG_LEVEL_ERROR, "Failed to unlink %s: %E",
1834                rsa_key_path);
1835             return -1;
1836          }
1837       }
1838       else
1839       {
1840          return 0;
1841       }
1842    }
1843    else
1844    {
1845       log_error(LOG_LEVEL_CONNECT, "Creating new certificate %s",
1846          certificate_path);
1847    }
1848    if (enforce_sane_certificate_state(certificate_path, rsa_key_path))
1849    {
1850       return -1;
1851    }
1852
1853    wc_InitRsaKey(&rsa_key, NULL);
1854    wc_InitRsaKey(&ca_key, NULL);
1855
1856    if (generate_rsa_key(rsa_key_path) == -1)
1857    {
1858       return -1;
1859    }
1860
1861    wc_InitCert(&certificate);
1862
1863    strncpy(certificate.subject.country, CERT_PARAM_COUNTRY_CODE, CTC_NAME_SIZE);
1864    strncpy(certificate.subject.org, "Privoxy", CTC_NAME_SIZE);
1865    strncpy(certificate.subject.unit, "Development", CTC_NAME_SIZE);
1866    strncpy(certificate.subject.commonName, csp->http->host, CTC_NAME_SIZE);
1867    certificate.daysValid = 90;
1868    certificate.selfSigned = 0;
1869    certificate.sigType = CTC_SHA256wRSA;
1870    if (!host_is_ip_address(csp->http->host) &&
1871        set_subject_alternative_name(&certificate, csp->http->host))
1872    {
1873       ret = -1;
1874       goto exit;
1875    }
1876
1877    ret = wc_SetIssuer(&certificate, csp->config->ca_cert_file);
1878    if (ret < 0)
1879    {
1880       log_error(LOG_LEVEL_ERROR,
1881          "Failed to set Issuer file %s", csp->config->ca_cert_file);
1882       ret = -1;
1883       goto exit;
1884    }
1885
1886    if (load_rsa_key(rsa_key_path, NULL, &rsa_key) != 1)
1887    {
1888       log_error(LOG_LEVEL_ERROR,
1889          "Failed to load RSA key %s", rsa_key_path);
1890       ret = -1;
1891       goto exit;
1892    }
1893
1894    /* wolfSSL_Debugging_ON(); */
1895    der_certificate_length = wc_MakeCert(&certificate, certificate_der,
1896       sizeof(certificate_der), &rsa_key, NULL, &wolfssl_rng);
1897    /* wolfSSL_Debugging_OFF(); */
1898
1899    if (der_certificate_length < 0)
1900    {
1901       log_error(LOG_LEVEL_ERROR, "Failed to make certificate");
1902       ret = -1;
1903       goto exit;
1904    }
1905
1906    if (load_rsa_key(csp->config->ca_key_file, csp->config->ca_password,
1907       &ca_key) != 1)
1908    {
1909       log_error(LOG_LEVEL_ERROR,
1910          "Failed to load CA key %s", csp->config->ca_key_file);
1911       ret = -1;
1912       goto exit;
1913    }
1914
1915    der_certificate_length = wc_SignCert(certificate.bodySz, certificate.sigType,
1916       certificate_der, sizeof(certificate_der), &ca_key, NULL, &wolfssl_rng);
1917    wc_FreeRsaKey(&ca_key);
1918    if (der_certificate_length < 0)
1919    {
1920       log_error(LOG_LEVEL_ERROR, "Failed to sign certificate");
1921       ret = -1;
1922       goto exit;
1923    }
1924
1925    pem_certificate_length = wc_DerToPem(certificate_der,
1926       (word32)der_certificate_length, certificate_pem,
1927       sizeof(certificate_pem), CERT_TYPE);
1928    if (pem_certificate_length < 0)
1929    {
1930       log_error(LOG_LEVEL_ERROR,
1931          "Failed to convert certificate from DER to PEM");
1932       ret = -1;
1933       goto exit;
1934    }
1935    certificate_pem[pem_certificate_length] = '\0';
1936
1937    if (write_certificate(certificate_path, (const char*)certificate_pem))
1938    {
1939       ret = -1;
1940       goto exit;
1941    }
1942
1943    ret = 1;
1944
1945 exit:
1946    wc_FreeRsaKey(&rsa_key);
1947    wc_FreeRsaKey(&ca_key);
1948
1949    return 1;
1950
1951 }
1952
1953
1954 /*********************************************************************
1955  *
1956  * Function    :  ssl_crt_verify_info
1957  *
1958  * Description :  Returns an informational string about the verification
1959  *                status of a certificate.
1960  *
1961  * Parameters  :
1962  *          1  :  buf = Buffer to write to
1963  *          2  :  size = Maximum size of buffer
1964  *          3  :  csp = client state
1965  *
1966  * Returns     :  N/A
1967  *
1968  *********************************************************************/
1969 extern void ssl_crt_verify_info(char *buf, size_t size, struct client_state *csp)
1970 {
1971    strncpy(buf, wolfSSL_X509_verify_cert_error_string(
1972       csp->server_cert_verification_result), size);
1973    buf[size - 1] = 0;
1974 }
1975
1976
1977 #ifdef FEATURE_GRACEFUL_TERMINATION
1978 /*********************************************************************
1979  *
1980  * Function    :  ssl_release
1981  *
1982  * Description :  Release all SSL resources
1983  *
1984  * Parameters  :
1985  *
1986  * Returns     :  N/A
1987  *
1988  *********************************************************************/
1989 extern void ssl_release(void)
1990 {
1991    if (wolfssl_initialized == 1)
1992    {
1993       wc_FreeRng(&wolfssl_rng);
1994       wolfSSL_Cleanup();
1995    }
1996 }
1997 #endif /* def FEATURE_GRACEFUL_TERMINATION */