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