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