Debian Codegraph @

extra/curl/curl-8.14.1/lib/vtls/wolfssl.c

raw
1 /***************************************************************************
2 * _ _ ____ _
3 * Project ___| | | | _ \| |
4 * / __| | | | |_) | |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
7 *
8 * Copyright (C) Daniel Stenberg, <[email protected]>, et al.
9 *
10 * This software is licensed as described in the file COPYING, which
11 * you should have received as part of this distribution. The terms
12 * are also available at https://curl.se/docs/copyright.html.
13 *
14 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15 * copies of the Software, and permit persons to whom the Software is
16 * furnished to do so, under the terms of the COPYING file.
17 *
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
20 *
21 * SPDX-License-Identifier: curl
22 *
23 ***************************************************************************/
24
25 /*
26 * Source file for all wolfSSL specific code for the TLS/SSL layer. No code
27 * but vtls.c should ever call or use these functions.
28 *
29 */
30
31 #include "../curl_setup.h"
32
33 #ifdef USE_WOLFSSL
34
35 #define WOLFSSL_OPTIONS_IGNORE_SYS
36 #include <wolfssl/options.h>
37 #include <wolfssl/version.h>
38
39
40 #if LIBWOLFSSL_VERSION_HEX < 0x03004006 /* wolfSSL 3.4.6 (2015) */
41 #error "wolfSSL version should be at least 3.4.6"
42 #endif
43
44 /* To determine what functions are available we rely on one or both of:
45 - the user's options.h generated by wolfSSL
46 - the symbols detected by curl's configure
47 Since they are markedly different from one another, and one or the other may
48 not be available, we do some checking below to bring things in sync. */
49
50 /* HAVE_ALPN is wolfSSL's build time symbol for enabling ALPN in options.h. */
51 #ifndef HAVE_ALPN
52 #ifdef HAVE_WOLFSSL_USEALPN
53 #define HAVE_ALPN
54 #endif
55 #endif
56
57 #include <limits.h>
58
59 #include "../urldata.h"
60 #include "../sendf.h"
61 #include "../curlx/inet_pton.h"
62 #include "vtls.h"
63 #include "vtls_int.h"
64 #include "vtls_scache.h"
65 #include "keylog.h"
66 #include "../parsedate.h"
67 #include "../connect.h" /* for the connect timeout */
68 #include "../progress.h"
69 #include "../select.h"
70 #include "../strcase.h"
71 #include "../strdup.h"
72 #include "x509asn1.h"
73 #include "../curl_printf.h"
74 #include "../multiif.h"
75
76 #include <wolfssl/ssl.h>
77 #include <wolfssl/error-ssl.h>
78 #include "wolfssl.h"
79
80 /* The last #include files should be: */
81 #include "../curl_memory.h"
82 #include "../memdebug.h"
83
84 #ifdef HAVE_WOLFSSL_CTX_GENERATEECHCONFIG
85 #define USE_ECH_WOLFSSL
86 #endif
87
88 /* KEEP_PEER_CERT is a product of the presence of build time symbol
89 OPENSSL_EXTRA without NO_CERTS, depending on the version. KEEP_PEER_CERT is
90 in wolfSSL's settings.h, and the latter two are build time symbols in
91 options.h. */
92 #ifndef KEEP_PEER_CERT
93 #if defined(HAVE_WOLFSSL_GET_PEER_CERTIFICATE) || \
94 (defined(OPENSSL_EXTRA) && !defined(NO_CERTS))
95 #define KEEP_PEER_CERT
96 #endif
97 #endif
98
99 #ifdef HAVE_WOLFSSL_BIO_NEW
100 #define USE_BIO_CHAIN
101 #ifdef HAVE_WOLFSSL_BIO_SET_SHUTDOWN
102 #define USE_FULL_BIO
103 #else /* HAVE_WOLFSSL_BIO_SET_SHUTDOWN */
104 #undef USE_FULL_BIO
105 #endif
106 /* wolfSSL 5.7.4 and older do not have these symbols, but only the
107 * OpenSSL ones. */
108 #ifndef WOLFSSL_BIO_CTRL_GET_CLOSE
109 #define WOLFSSL_BIO_CTRL_GET_CLOSE BIO_CTRL_GET_CLOSE
110 #define WOLFSSL_BIO_CTRL_SET_CLOSE BIO_CTRL_SET_CLOSE
111 #define WOLFSSL_BIO_CTRL_FLUSH BIO_CTRL_FLUSH
112 #define WOLFSSL_BIO_CTRL_DUP BIO_CTRL_DUP
113 #define wolfSSL_BIO_set_retry_write BIO_set_retry_write
114 #define wolfSSL_BIO_set_retry_read BIO_set_retry_read
115 #endif /* !WOLFSSL_BIO_CTRL_GET_CLOSE */
116
117 #else /* HAVE_WOLFSSL_BIO_NEW */
118 #undef USE_BIO_CHAIN
119 #endif
120
121 static CURLcode wssl_connect(struct Curl_cfilter *cf,
122 struct Curl_easy *data,
123 bool *done);
124
125 #ifdef OPENSSL_EXTRA
126 /*
127 * Availability note:
128 * The TLS 1.3 secret callback (wolfSSL_set_tls13_secret_cb) was added in
129 * wolfSSL 4.4.0, but requires the -DHAVE_SECRET_CALLBACK build option. If that
130 * option is not set, then TLS 1.3 will not be logged.
131 * For TLS 1.2 and before, we use wolfSSL_get_keys().
132 * wolfSSL_get_client_random and wolfSSL_get_keys require OPENSSL_EXTRA
133 * (--enable-opensslextra or --enable-all).
134 */
135 #if defined(HAVE_SECRET_CALLBACK) && defined(WOLFSSL_TLS13)
136 static int
137 wssl_tls13_secret_callback(SSL *ssl, int id, const unsigned char *secret,
138 int secretSz, void *ctx)
139 {
140 const char *label;
141 unsigned char client_random[SSL3_RANDOM_SIZE];
142 (void)ctx;
143
144 if(!ssl || !Curl_tls_keylog_enabled()) {
145 return 0;
146 }
147
148 switch(id) {
149 case CLIENT_EARLY_TRAFFIC_SECRET:
150 label = "CLIENT_EARLY_TRAFFIC_SECRET";
151 break;
152 case CLIENT_HANDSHAKE_TRAFFIC_SECRET:
153 label = "CLIENT_HANDSHAKE_TRAFFIC_SECRET";
154 break;
155 case SERVER_HANDSHAKE_TRAFFIC_SECRET:
156 label = "SERVER_HANDSHAKE_TRAFFIC_SECRET";
157 break;
158 case CLIENT_TRAFFIC_SECRET:
159 label = "CLIENT_TRAFFIC_SECRET_0";
160 break;
161 case SERVER_TRAFFIC_SECRET:
162 label = "SERVER_TRAFFIC_SECRET_0";
163 break;
164 case EARLY_EXPORTER_SECRET:
165 label = "EARLY_EXPORTER_SECRET";
166 break;
167 case EXPORTER_SECRET:
168 label = "EXPORTER_SECRET";
169 break;
170 default:
171 return 0;
172 }
173
174 if(wolfSSL_get_client_random(ssl, client_random, SSL3_RANDOM_SIZE) == 0) {
175 /* Should never happen as wolfSSL_KeepArrays() was called before. */
176 return 0;
177 }
178
179 Curl_tls_keylog_write(label, client_random, secret, secretSz);
180 return 0;
181 }
182 #endif /* defined(HAVE_SECRET_CALLBACK) && defined(WOLFSSL_TLS13) */
183
184 static void wssl_log_tls12_secret(WOLFSSL *ssl)
185 {
186 unsigned char *ms, *sr, *cr;
187 unsigned int msLen, srLen, crLen, i, x = 0;
188
189 #if LIBWOLFSSL_VERSION_HEX >= 0x0300d000 /* >= 3.13.0 */
190 /* wolfSSL_GetVersion is available since 3.13, we use it instead of
191 * SSL_version since the latter relies on OPENSSL_ALL (--enable-opensslall or
192 * --enable-all). Failing to perform this check could result in an unusable
193 * key log line when TLS 1.3 is actually negotiated. */
194 switch(wolfSSL_GetVersion(ssl)) {
195 case WOLFSSL_SSLV3:
196 case WOLFSSL_TLSV1:
197 case WOLFSSL_TLSV1_1:
198 case WOLFSSL_TLSV1_2:
199 break;
200 default:
201 /* TLS 1.3 does not use this mechanism, the "master secret" returned below
202 * is not directly usable. */
203 return;
204 }
205 #endif
206
207 if(wolfSSL_get_keys(ssl, &ms, &msLen, &sr, &srLen, &cr, &crLen) !=
208 WOLFSSL_SUCCESS) {
209 return;
210 }
211
212 /* Check for a missing master secret and skip logging. That can happen if
213 * curl rejects the server certificate and aborts the handshake.
214 */
215 for(i = 0; i < msLen; i++) {
216 x |= ms[i];
217 }
218 if(x == 0) {
219 return;
220 }
221
222 Curl_tls_keylog_write("CLIENT_RANDOM", cr, ms, msLen);
223 }
224 #endif /* OPENSSL_EXTRA */
225
226 static int wssl_do_file_type(const char *type)
227 {
228 if(!type || !type[0])
229 return WOLFSSL_FILETYPE_PEM;
230 if(strcasecompare(type, "PEM"))
231 return WOLFSSL_FILETYPE_PEM;
232 if(strcasecompare(type, "DER"))
233 return WOLFSSL_FILETYPE_ASN1;
234 return -1;
235 }
236
237 #ifdef WOLFSSL_HAVE_KYBER
238 struct group_name_map {
239 const word16 group;
240 const char *name;
241 };
242
243 static const struct group_name_map gnm[] = {
244 { WOLFSSL_ML_KEM_512, "ML_KEM_512" },
245 { WOLFSSL_ML_KEM_768, "ML_KEM_768" },
246 { WOLFSSL_ML_KEM_1024, "ML_KEM_1024" },
247 { WOLFSSL_P256_ML_KEM_512, "P256_ML_KEM_512" },
248 { WOLFSSL_P384_ML_KEM_768, "P384_ML_KEM_768" },
249 { WOLFSSL_P521_ML_KEM_1024, "P521_ML_KEM_1024" },
250 { 0, NULL }
251 };
252 #endif
253
254 #ifdef USE_BIO_CHAIN
255
256 static int wssl_bio_cf_create(WOLFSSL_BIO *bio)
257 {
258 #ifdef USE_FULL_BIO
259 wolfSSL_BIO_set_shutdown(bio, 1);
260 #endif
261 wolfSSL_BIO_set_data(bio, NULL);
262 return 1;
263 }
264
265 static int wssl_bio_cf_destroy(WOLFSSL_BIO *bio)
266 {
267 if(!bio)
268 return 0;
269 return 1;
270 }
271
272 static long wssl_bio_cf_ctrl(WOLFSSL_BIO *bio, int cmd, long num, void *ptr)
273 {
274 struct Curl_cfilter *cf = wolfSSL_BIO_get_data(bio);
275 long ret = 1;
276
277 (void)cf;
278 (void)ptr;
279 (void)num;
280 switch(cmd) {
281 case WOLFSSL_BIO_CTRL_GET_CLOSE:
282 #ifdef USE_FULL_BIO
283 ret = (long)wolfSSL_BIO_get_shutdown(bio);
284 #else
285 ret = 0;
286 #endif
287 break;
288 case WOLFSSL_BIO_CTRL_SET_CLOSE:
289 #ifdef USE_FULL_BIO
290 wolfSSL_BIO_set_shutdown(bio, (int)num);
291 #endif
292 break;
293 case WOLFSSL_BIO_CTRL_FLUSH:
294 /* we do no delayed writes, but if we ever would, this
295 * needs to trigger it. */
296 ret = 1;
297 break;
298 case WOLFSSL_BIO_CTRL_DUP:
299 ret = 1;
300 break;
301 #ifdef WOLFSSL_BIO_CTRL_EOF
302 case WOLFSSL_BIO_CTRL_EOF: {
303 /* EOF has been reached on input? */
304 struct ssl_connect_data *connssl = cf->ctx;
305 return connssl->peer_closed;
306 }
307 #endif
308 default:
309 ret = 0;
310 break;
311 }
312 return ret;
313 }
314
315 static int wssl_bio_cf_out_write(WOLFSSL_BIO *bio,
316 const char *buf, int blen)
317 {
318 struct Curl_cfilter *cf = wolfSSL_BIO_get_data(bio);
319 struct ssl_connect_data *connssl = cf->ctx;
320 struct wssl_ctx *wssl = (struct wssl_ctx *)connssl->backend;
321 struct Curl_easy *data = CF_DATA_CURRENT(cf);
322 ssize_t nwritten, skiplen = 0;
323 CURLcode result = CURLE_OK;
324
325 DEBUGASSERT(data);
326 if(wssl->shutting_down && wssl->io_send_blocked_len &&
327 (wssl->io_send_blocked_len < blen)) {
328 /* bug in wolfSSL: <https://github.com/wolfSSL/wolfssl/issues/7784>
329 * It adds the close notify message again every time we retry
330 * sending during shutdown. */
331 CURL_TRC_CF(data, cf, "bio_write, shutdown restrict send of %d"
332 " to %d bytes", blen, wssl->io_send_blocked_len);
333 skiplen = (ssize_t)(blen - wssl->io_send_blocked_len);
334 blen = wssl->io_send_blocked_len;
335 }
336 nwritten = Curl_conn_cf_send(cf->next, data, buf, blen, FALSE, &result);
337 wssl->io_result = result;
338 CURL_TRC_CF(data, cf, "bio_write(len=%d) -> %zd, %d",
339 blen, nwritten, result);
340 #ifdef USE_FULL_BIO
341 wolfSSL_BIO_clear_retry_flags(bio);
342 #endif
343 if(nwritten < 0 && CURLE_AGAIN == result) {
344 wolfSSL_BIO_set_retry_write(bio);
345 if(wssl->shutting_down && !wssl->io_send_blocked_len)
346 wssl->io_send_blocked_len = blen;
347 }
348 else if(!result && skiplen)
349 nwritten += skiplen;
350 return (int)nwritten;
351 }
352
353 static int wssl_bio_cf_in_read(WOLFSSL_BIO *bio, char *buf, int blen)
354 {
355 struct Curl_cfilter *cf = wolfSSL_BIO_get_data(bio);
356 struct ssl_connect_data *connssl = cf->ctx;
357 struct wssl_ctx *wssl = (struct wssl_ctx *)connssl->backend;
358 struct Curl_easy *data = CF_DATA_CURRENT(cf);
359 ssize_t nread;
360 CURLcode result = CURLE_OK;
361
362 DEBUGASSERT(data);
363 /* OpenSSL catches this case, so should we. */
364 if(!buf)
365 return 0;
366
367 if((connssl->connecting_state == ssl_connect_2) &&
368 !wssl->x509_store_setup) {
369 /* During handshake, init the x509 store before receiving the
370 * server response. This allows sending of ClientHello without delay. */
371 result = Curl_wssl_setup_x509_store(cf, data, wssl);
372 if(result) {
373 CURL_TRC_CF(data, cf, "Curl_wssl_setup_x509_store() -> %d", result);
374 wssl->io_result = result;
375 return -1;
376 }
377 }
378
379 nread = Curl_conn_cf_recv(cf->next, data, buf, blen, &result);
380 wssl->io_result = result;
381 CURL_TRC_CF(data, cf, "bio_read(len=%d) -> %zd, %d", blen, nread, result);
382 #ifdef USE_FULL_BIO
383 wolfSSL_BIO_clear_retry_flags(bio);
384 #endif
385 if(nread < 0 && CURLE_AGAIN == result)
386 wolfSSL_BIO_set_retry_read(bio);
387 else if(nread == 0)
388 connssl->peer_closed = TRUE;
389 return (int)nread;
390 }
391
392 static WOLFSSL_BIO_METHOD *wssl_bio_cf_method = NULL;
393
394 static void wssl_bio_cf_init_methods(void)
395 {
396 wssl_bio_cf_method = wolfSSL_BIO_meth_new(WOLFSSL_BIO_MEMORY,
397 "wolfSSL CF BIO");
398 wolfSSL_BIO_meth_set_write(wssl_bio_cf_method, &wssl_bio_cf_out_write);
399 wolfSSL_BIO_meth_set_read(wssl_bio_cf_method, &wssl_bio_cf_in_read);
400 wolfSSL_BIO_meth_set_ctrl(wssl_bio_cf_method, &wssl_bio_cf_ctrl);
401 wolfSSL_BIO_meth_set_create(wssl_bio_cf_method, &wssl_bio_cf_create);
402 wolfSSL_BIO_meth_set_destroy(wssl_bio_cf_method, &wssl_bio_cf_destroy);
403 }
404
405 static void wssl_bio_cf_free_methods(void)
406 {
407 wolfSSL_BIO_meth_free(wssl_bio_cf_method);
408 }
409
410 #else /* USE_BIO_CHAIN */
411
412 #define wssl_bio_cf_init_methods() Curl_nop_stmt
413 #define wssl_bio_cf_free_methods() Curl_nop_stmt
414
415 #endif /* !USE_BIO_CHAIN */
416
417 CURLcode Curl_wssl_cache_session(struct Curl_cfilter *cf,
418 struct Curl_easy *data,
419 const char *ssl_peer_key,
420 WOLFSSL_SESSION *session,
421 int ietf_tls_id,
422 const char *alpn,
423 unsigned char *quic_tp,
424 size_t quic_tp_len)
425 {
426 CURLcode result = CURLE_OK;
427 struct Curl_ssl_session *sc_session = NULL;
428 unsigned char *sdata = NULL, *qtp_clone = NULL;
429 unsigned int sdata_len;
430 unsigned int earlydata_max = 0;
431
432 if(!session)
433 goto out;
434
435 sdata_len = wolfSSL_i2d_SSL_SESSION(session, NULL);
436 if(sdata_len <= 0) {
437 CURL_TRC_CF(data, cf, "fail to assess session length: %u", sdata_len);
438 result = CURLE_FAILED_INIT;
439 goto out;
440 }
441 sdata = calloc(1, sdata_len);
442 if(!sdata) {
443 failf(data, "unable to allocate session buffer of %u bytes", sdata_len);
444 result = CURLE_OUT_OF_MEMORY;
445 goto out;
446 }
447 sdata_len = wolfSSL_i2d_SSL_SESSION(session, &sdata);
448 if(sdata_len <= 0) {
449 CURL_TRC_CF(data, cf, "fail to serialize session: %u", sdata_len);
450 result = CURLE_FAILED_INIT;
451 goto out;
452 }
453 if(quic_tp && quic_tp_len) {
454 qtp_clone = Curl_memdup0((char *)quic_tp, quic_tp_len);
455 if(!qtp_clone) {
456 free(sdata);
457 return CURLE_OUT_OF_MEMORY;
458 }
459 }
460 #ifdef WOLFSSL_EARLY_DATA
461 earlydata_max = wolfSSL_SESSION_get_max_early_data(session);
462 #endif
463
464 result = Curl_ssl_session_create2(sdata, sdata_len,
465 ietf_tls_id, alpn,
466 (curl_off_t)time(NULL) +
467 wolfSSL_SESSION_get_timeout(session),
468 earlydata_max, qtp_clone, quic_tp_len,
469 &sc_session);
470 sdata = NULL; /* took ownership of sdata */
471 if(!result) {
472 result = Curl_ssl_scache_put(cf, data, ssl_peer_key, sc_session);
473 /* took ownership of `sc_session` */
474 }
475
476 out:
477 free(sdata);
478 return result;
479 }
480
481 static int wssl_vtls_new_session_cb(WOLFSSL *ssl, WOLFSSL_SESSION *session)
482 {
483 struct Curl_cfilter *cf;
484
485 cf = (struct Curl_cfilter*)wolfSSL_get_app_data(ssl);
486 DEBUGASSERT(cf != NULL);
487 if(cf && session) {
488 struct ssl_connect_data *connssl = cf->ctx;
489 struct Curl_easy *data = CF_DATA_CURRENT(cf);
490 DEBUGASSERT(connssl);
491 DEBUGASSERT(data);
492 if(connssl && data) {
493 (void)Curl_wssl_cache_session(cf, data, connssl->peer.scache_key,
494 session, wolfSSL_version(ssl),
495 connssl->negotiated.alpn, NULL, 0);
496 }
497 }
498 return 0;
499 }
500
501 static CURLcode wssl_on_session_reuse(struct Curl_cfilter *cf,
502 struct Curl_easy *data,
503 struct alpn_spec *alpns,
504 struct Curl_ssl_session *scs,
505 bool *do_early_data)
506 {
507 struct ssl_connect_data *connssl = cf->ctx;
508 struct wssl_ctx *wssl = (struct wssl_ctx *)connssl->backend;
509 CURLcode result = CURLE_OK;
510
511 *do_early_data = FALSE;
512 #ifdef WOLFSSL_EARLY_DATA
513 connssl->earlydata_max = wolfSSL_SESSION_get_max_early_data(
514 wolfSSL_get_session(wssl->ssl));
515 #else
516 (void)wssl;
517 connssl->earlydata_max = 0;
518 #endif
519
520 if(!connssl->earlydata_max) {
521 /* Seems to be GnuTLS way to signal no EarlyData in session */
522 CURL_TRC_CF(data, cf, "SSL session does not allow earlydata");
523 }
524 else if(!Curl_alpn_contains_proto(alpns, scs->alpn)) {
525 CURL_TRC_CF(data, cf, "SSL session has different ALPN, no early data");
526 }
527 else {
528 infof(data, "SSL session allows %zu bytes of early data, "
529 "reusing ALPN '%s'", connssl->earlydata_max, scs->alpn);
530 connssl->earlydata_state = ssl_earlydata_await;
531 connssl->state = ssl_connection_deferred;
532 result = Curl_alpn_set_negotiated(cf, data, connssl,
533 (const unsigned char *)scs->alpn,
534 scs->alpn ? strlen(scs->alpn) : 0);
535 *do_early_data = !result;
536 }
537 return result;
538 }
539
540 static CURLcode
541 wssl_setup_session(struct Curl_cfilter *cf,
542 struct Curl_easy *data,
543 struct wssl_ctx *wss,
544 struct alpn_spec *alpns,
545 const char *ssl_peer_key,
546 Curl_wssl_init_session_reuse_cb *sess_reuse_cb)
547 {
548 struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
549 struct Curl_ssl_session *scs = NULL;
550 CURLcode result;
551
552 result = Curl_ssl_scache_take(cf, data, ssl_peer_key, &scs);
553 if(!result && scs && scs->sdata && scs->sdata_len &&
554 (!scs->alpn || Curl_alpn_contains_proto(alpns, scs->alpn))) {
555 WOLFSSL_SESSION *session;
556 /* wolfSSL changes the passed pointer for whatever reasons, yikes */
557 const unsigned char *sdata = scs->sdata;
558 session = wolfSSL_d2i_SSL_SESSION(NULL, &sdata, (long)scs->sdata_len);
559 if(session) {
560 int ret = wolfSSL_set_session(wss->ssl, session);
561 if(ret != WOLFSSL_SUCCESS) {
562 Curl_ssl_session_destroy(scs);
563 scs = NULL;
564 infof(data, "cached session not accepted (%d), "
565 "removing from cache", ret);
566 }
567 else {
568 infof(data, "SSL reusing session with ALPN '%s'",
569 scs->alpn ? scs->alpn : "-");
570 if(ssl_config->earlydata &&
571 !cf->conn->connect_only &&
572 !strcmp("TLSv1.3", wolfSSL_get_version(wss->ssl))) {
573 bool do_early_data = FALSE;
574 if(sess_reuse_cb) {
575 result = sess_reuse_cb(cf, data, alpns, scs, &do_early_data);
576 if(result)
577 goto out;
578 }
579 #ifdef WOLFSSL_EARLY_DATA
580 if(do_early_data) {
581 unsigned int edmax = (scs->earlydata_max < UINT_MAX) ?
582 (unsigned int)scs->earlydata_max : UINT_MAX;
583 /* We only try the ALPN protocol the session used before,
584 * otherwise we might send early data for the wrong protocol */
585 Curl_alpn_restrict_to(alpns, scs->alpn);
586 wolfSSL_set_max_early_data(wss->ssl, edmax);
587 }
588 #else
589 /* Should never enable when not supported */
590 DEBUGASSERT(!do_early_data);
591 #endif
592 }
593 }
594 wolfSSL_SESSION_free(session);
595 }
596 else {
597 failf(data, "could not decode previous session");
598 }
599 }
600 out:
601 Curl_ssl_scache_return(cf, data, ssl_peer_key, scs);
602 return result;
603 }
604
605 static CURLcode wssl_populate_x509_store(struct Curl_cfilter *cf,
606 struct Curl_easy *data,
607 WOLFSSL_X509_STORE *store,
608 struct wssl_ctx *wssl)
609 {
610 struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
611 const struct curl_blob *ca_info_blob = conn_config->ca_info_blob;
612 const char * const ssl_cafile =
613 /* CURLOPT_CAINFO_BLOB overrides CURLOPT_CAINFO */
614 (ca_info_blob ? NULL : conn_config->CAfile);
615 const char * const ssl_capath = conn_config->CApath;
616 struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
617 bool imported_native_ca = FALSE;
618 bool imported_ca_info_blob = FALSE;
619
620 /* We do not want to do this again, no matter the outcome */
621 wssl->x509_store_setup = TRUE;
622
623 #ifndef NO_FILESYSTEM
624 /* load native CA certificates */
625 if(ssl_config->native_ca_store) {
626 #ifdef WOLFSSL_SYS_CA_CERTS
627 if(wolfSSL_CTX_load_system_CA_certs(wssl->ssl_ctx) != WOLFSSL_SUCCESS) {
628 infof(data, "error importing native CA store, continuing anyway");
629 }
630 else {
631 imported_native_ca = TRUE;
632 infof(data, "successfully imported native CA store");
633 }
634 #else
635 infof(data, "ignoring native CA option because wolfSSL was built without "
636 "native CA support");
637 #endif
638 }
639 #endif /* !NO_FILESYSTEM */
640
641 /* load certificate blob */
642 if(ca_info_blob) {
643 if(wolfSSL_CTX_load_verify_buffer(wssl->ssl_ctx, ca_info_blob->data,
644 (long)ca_info_blob->len,
645 WOLFSSL_FILETYPE_PEM) !=
646 WOLFSSL_SUCCESS) {
647 failf(data, "error importing CA certificate blob");
648 return CURLE_SSL_CACERT_BADFILE;
649 }
650 else {
651 imported_ca_info_blob = TRUE;
652 infof(data, "successfully imported CA certificate blob");
653 }
654 }
655
656 #ifndef NO_FILESYSTEM
657 /* load trusted cacert from file if not blob */
658
659 CURL_TRC_CF(data, cf, "wssl_populate_x509_store, path=%s, blob=%d",
660 ssl_cafile ? ssl_cafile : "none", !!ca_info_blob);
661 if(!store)
662 return CURLE_OUT_OF_MEMORY;
663
664 if(ssl_cafile || ssl_capath) {
665 int rc =
666 wolfSSL_CTX_load_verify_locations_ex(wssl->ssl_ctx,
667 ssl_cafile,
668 ssl_capath,
669 WOLFSSL_LOAD_FLAG_IGNORE_ERR);
670 if(WOLFSSL_SUCCESS != rc) {
671 if(conn_config->verifypeer &&
672 !imported_native_ca && !imported_ca_info_blob) {
673 /* Fail if we insist on successfully verifying the server. */
674 failf(data, "error setting certificate verify locations:"
675 " CAfile: %s CApath: %s",
676 ssl_cafile ? ssl_cafile : "none",
677 ssl_capath ? ssl_capath : "none");
678 return CURLE_SSL_CACERT_BADFILE;
679 }
680 else {
681 /* Just continue with a warning if no strict certificate
682 verification is required. */
683 infof(data, "error setting certificate verify locations,"
684 " continuing anyway:");
685 }
686 }
687 else {
688 /* Everything is fine. */
689 infof(data, "successfully set certificate verify locations:");
690 }
691 infof(data, " CAfile: %s", ssl_cafile ? ssl_cafile : "none");
692 infof(data, " CApath: %s", ssl_capath ? ssl_capath : "none");
693 }
694 #endif
695 (void)store;
696 return CURLE_OK;
697 }
698
699 /* key to use at `multi->proto_hash` */
700 #define MPROTO_WSSL_X509_KEY "tls:wssl:x509:share"
701
702 struct wssl_x509_share {
703 char *CAfile; /* CAfile path used to generate X509 store */
704 WOLFSSL_X509_STORE *store; /* cached X509 store or NULL if none */
705 struct curltime time; /* when the cached store was created */
706 };
707
708 static void wssl_x509_share_free(void *key, size_t key_len, void *p)
709 {
710 struct wssl_x509_share *share = p;
711 DEBUGASSERT(key_len == (sizeof(MPROTO_WSSL_X509_KEY)-1));
712 DEBUGASSERT(!memcmp(MPROTO_WSSL_X509_KEY, key, key_len));
713 (void)key;
714 (void)key_len;
715 if(share->store) {
716 wolfSSL_X509_STORE_free(share->store);
717 }
718 free(share->CAfile);
719 free(share);
720 }
721
722 static bool
723 wssl_cached_x509_store_expired(const struct Curl_easy *data,
724 const struct wssl_x509_share *mb)
725 {
726 const struct ssl_general_config *cfg = &data->set.general_ssl;
727 struct curltime now = curlx_now();
728 timediff_t elapsed_ms = curlx_timediff(now, mb->time);
729 timediff_t timeout_ms = cfg->ca_cache_timeout * (timediff_t)1000;
730
731 if(timeout_ms < 0)
732 return FALSE;
733
734 return elapsed_ms >= timeout_ms;
735 }
736
737 static bool
738 wssl_cached_x509_store_different(struct Curl_cfilter *cf,
739 const struct wssl_x509_share *mb)
740 {
741 struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
742 if(!mb->CAfile || !conn_config->CAfile)
743 return mb->CAfile != conn_config->CAfile;
744
745 return strcmp(mb->CAfile, conn_config->CAfile);
746 }
747
748 static WOLFSSL_X509_STORE *wssl_get_cached_x509_store(struct Curl_cfilter *cf,
749 const struct Curl_easy *data)
750 {
751 struct Curl_multi *multi = data->multi;
752 struct wssl_x509_share *share;
753 WOLFSSL_X509_STORE *store = NULL;
754
755 DEBUGASSERT(multi);
756 share = multi ? Curl_hash_pick(&multi->proto_hash,
757 CURL_UNCONST(MPROTO_WSSL_X509_KEY),
758 sizeof(MPROTO_WSSL_X509_KEY)-1) : NULL;
759 if(share && share->store &&
760 !wssl_cached_x509_store_expired(data, share) &&
761 !wssl_cached_x509_store_different(cf, share)) {
762 store = share->store;
763 }
764
765 return store;
766 }
767
768 static void wssl_set_cached_x509_store(struct Curl_cfilter *cf,
769 const struct Curl_easy *data,
770 WOLFSSL_X509_STORE *store)
771 {
772 struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
773 struct Curl_multi *multi = data->multi;
774 struct wssl_x509_share *share;
775
776 DEBUGASSERT(multi);
777 if(!multi)
778 return;
779 share = Curl_hash_pick(&multi->proto_hash,
780 CURL_UNCONST(MPROTO_WSSL_X509_KEY),
781 sizeof(MPROTO_WSSL_X509_KEY)-1);
782
783 if(!share) {
784 share = calloc(1, sizeof(*share));
785 if(!share)
786 return;
787 if(!Curl_hash_add2(&multi->proto_hash,
788 CURL_UNCONST(MPROTO_WSSL_X509_KEY),
789 sizeof(MPROTO_WSSL_X509_KEY)-1,
790 share, wssl_x509_share_free)) {
791 free(share);
792 return;
793 }
794 }
795
796 if(wolfSSL_X509_STORE_up_ref(store)) {
797 char *CAfile = NULL;
798
799 if(conn_config->CAfile) {
800 CAfile = strdup(conn_config->CAfile);
801 if(!CAfile) {
802 wolfSSL_X509_STORE_free(store);
803 return;
804 }
805 }
806
807 if(share->store) {
808 wolfSSL_X509_STORE_free(share->store);
809 free(share->CAfile);
810 }
811
812 share->time = curlx_now();
813 share->store = store;
814 share->CAfile = CAfile;
815 }
816 }
817
818 CURLcode Curl_wssl_setup_x509_store(struct Curl_cfilter *cf,
819 struct Curl_easy *data,
820 struct wssl_ctx *wssl)
821 {
822 struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
823 struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
824 CURLcode result = CURLE_OK;
825 WOLFSSL_X509_STORE *cached_store;
826 bool cache_criteria_met;
827
828 /* Consider the X509 store cacheable if it comes exclusively from a CAfile,
829 or no source is provided and we are falling back to wolfSSL's built-in
830 default. */
831 cache_criteria_met = (data->set.general_ssl.ca_cache_timeout != 0) &&
832 conn_config->verifypeer &&
833 !conn_config->CApath &&
834 !conn_config->ca_info_blob &&
835 !ssl_config->primary.CRLfile &&
836 !ssl_config->native_ca_store;
837
838 cached_store = cache_criteria_met ? wssl_get_cached_x509_store(cf, data)
839 : NULL;
840 if(cached_store &&
841 wolfSSL_CTX_get_cert_store(wssl->ssl_ctx) == cached_store) {
842 /* The cached store is already in use, do nothing. */
843 }
844 else if(cached_store && wolfSSL_X509_STORE_up_ref(cached_store)) {
845 wolfSSL_CTX_set_cert_store(wssl->ssl_ctx, cached_store);
846 }
847 else if(cache_criteria_met) {
848 /* wolfSSL's initial store in CTX is not shareable by default.
849 * Make a new one, suitable for adding to the cache. See #14278 */
850 WOLFSSL_X509_STORE *store = wolfSSL_X509_STORE_new();
851 if(!store) {
852 failf(data, "SSL: could not create a X509 store");
853 return CURLE_OUT_OF_MEMORY;
854 }
855 wolfSSL_CTX_set_cert_store(wssl->ssl_ctx, store);
856
857 result = wssl_populate_x509_store(cf, data, store, wssl);
858 if(!result) {
859 wssl_set_cached_x509_store(cf, data, store);
860 }
861 }
862 else {
863 /* We never share the CTX's store, use it. */
864 WOLFSSL_X509_STORE *store = wolfSSL_CTX_get_cert_store(wssl->ssl_ctx);
865 result = wssl_populate_x509_store(cf, data, store, wssl);
866 }
867
868 return result;
869 }
870
871 #ifdef WOLFSSL_TLS13
872 static CURLcode
873 wssl_add_default_ciphers(bool tls13, struct dynbuf *buf)
874 {
875 int i;
876 char *str;
877
878 for(i = 0; (str = wolfSSL_get_cipher_list(i)) != NULL; i++) {
879 size_t n;
880 if((strncmp(str, "TLS13", 5) == 0) != tls13)
881 continue;
882
883 /* if there already is data in the string, add colon separator */
884 if(curlx_dyn_len(buf)) {
885 CURLcode result = curlx_dyn_addn(buf, ":", 1);
886 if(result)
887 return result;
888 }
889
890 n = strlen(str);
891 if(curlx_dyn_addn(buf, str, n))
892 return CURLE_OUT_OF_MEMORY;
893 }
894
895 return CURLE_OK;
896 }
897 #endif
898
899 /* 4.2.0 (2019) */
900 #if LIBWOLFSSL_VERSION_HEX < 0x04002000 || !defined(OPENSSL_EXTRA)
901 static int
902 wssl_legacy_CTX_set_min_proto_version(WOLFSSL_CTX* ctx, int version)
903 {
904 int res;
905 switch(version) {
906 default:
907 case TLS1_VERSION:
908 res = wolfSSL_CTX_SetMinVersion(ctx, WOLFSSL_TLSV1);
909 if(res == WOLFSSL_SUCCESS)
910 return res;
911 FALLTHROUGH();
912 case TLS1_1_VERSION:
913 res = wolfSSL_CTX_SetMinVersion(ctx, WOLFSSL_TLSV1_1);
914 if(res == WOLFSSL_SUCCESS)
915 return res;
916 FALLTHROUGH();
917 case TLS1_2_VERSION:
918 res = wolfSSL_CTX_SetMinVersion(ctx, WOLFSSL_TLSV1_2);
919 #ifdef WOLFSSL_TLS13
920 if(res == WOLFSSL_SUCCESS)
921 return res;
922 FALLTHROUGH();
923 case TLS1_3_VERSION:
924 res = wolfSSL_CTX_SetMinVersion(ctx, WOLFSSL_TLSV1_3);
925 #endif
926 }
927 return res;
928 }
929 static int
930 wssl_legacy_CTX_set_max_proto_version(WOLFSSL_CTX* ctx, int version)
931 {
932 (void) ctx, (void) version;
933 return WOLFSSL_NOT_IMPLEMENTED;
934 }
935 #define wolfSSL_CTX_set_min_proto_version wssl_legacy_CTX_set_min_proto_version
936 #define wolfSSL_CTX_set_max_proto_version wssl_legacy_CTX_set_max_proto_version
937 #endif
938
939 #define QUIC_CIPHERS \
940 "TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:TLS_CHACHA20_" \
941 "POLY1305_SHA256:TLS_AES_128_CCM_SHA256"
942 #define QUIC_GROUPS "P-256:P-384:P-521"
943
944 CURLcode Curl_wssl_ctx_init(struct wssl_ctx *wctx,
945 struct Curl_cfilter *cf,
946 struct Curl_easy *data,
947 struct ssl_peer *peer,
948 const struct alpn_spec *alpns_requested,
949 Curl_wssl_ctx_setup_cb *cb_setup,
950 void *cb_user_data,
951 void *ssl_user_data,
952 Curl_wssl_init_session_reuse_cb *sess_reuse_cb)
953 {
954 struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
955 struct ssl_primary_config *conn_config;
956 WOLFSSL_METHOD* req_method = NULL;
957 struct alpn_spec alpns;
958 int res;
959 char *curves;
960 #ifdef WOLFSSL_HAVE_KYBER
961 word16 pqkem = 0;
962 size_t idx = 0;
963 #endif
964 CURLcode result = CURLE_FAILED_INIT;
965
966 DEBUGASSERT(!wctx->ssl_ctx);
967 DEBUGASSERT(!wctx->ssl);
968 conn_config = Curl_ssl_cf_get_primary_config(cf);
969 if(!conn_config) {
970 result = CURLE_FAILED_INIT;
971 goto out;
972 }
973 Curl_alpn_copy(&alpns, alpns_requested);
974
975 #if LIBWOLFSSL_VERSION_HEX < 0x04002000 /* 4.2.0 (2019) */
976 req_method = wolfSSLv23_client_method();
977 #else
978 req_method = wolfTLS_client_method();
979 #endif
980 if(!req_method) {
981 failf(data, "wolfSSL: could not create a client method");
982 result = CURLE_OUT_OF_MEMORY;
983 goto out;
984 }
985
986 if(wctx->ssl_ctx)
987 wolfSSL_CTX_free(wctx->ssl_ctx);
988
989 wctx->ssl_ctx = wolfSSL_CTX_new(req_method);
990 if(!wctx->ssl_ctx) {
991 failf(data, "wolfSSL: could not create a context");
992 result = CURLE_OUT_OF_MEMORY;
993 goto out;
994 }
995
996 switch(conn_config->version) {
997 case CURL_SSLVERSION_DEFAULT:
998 case CURL_SSLVERSION_TLSv1:
999 case CURL_SSLVERSION_TLSv1_0:
1000 res = wolfSSL_CTX_set_min_proto_version(wctx->ssl_ctx, TLS1_VERSION);
1001 break;
1002 case CURL_SSLVERSION_TLSv1_1:
1003 res = wolfSSL_CTX_set_min_proto_version(wctx->ssl_ctx, TLS1_1_VERSION);
1004 break;
1005 case CURL_SSLVERSION_TLSv1_2:
1006 res = wolfSSL_CTX_set_min_proto_version(wctx->ssl_ctx, TLS1_2_VERSION);
1007 break;
1008 #ifdef WOLFSSL_TLS13
1009 case CURL_SSLVERSION_TLSv1_3:
1010 res = wolfSSL_CTX_set_min_proto_version(wctx->ssl_ctx, TLS1_3_VERSION);
1011 break;
1012 #endif
1013 default:
1014 failf(data, "wolfSSL: unsupported minimum TLS version value");
1015 result = CURLE_SSL_CONNECT_ERROR;
1016 goto out;
1017 }
1018 if(res != WOLFSSL_SUCCESS) {
1019 failf(data, "wolfSSL: failed set the minimum TLS version");
1020 result = CURLE_SSL_CONNECT_ERROR;
1021 goto out;
1022 }
1023
1024 switch(conn_config->version_max) {
1025 #ifdef WOLFSSL_TLS13
1026 case CURL_SSLVERSION_MAX_TLSv1_3:
1027 res = wolfSSL_CTX_set_max_proto_version(wctx->ssl_ctx, TLS1_3_VERSION);
1028 break;
1029 #endif
1030 case CURL_SSLVERSION_MAX_TLSv1_2:
1031 res = wolfSSL_CTX_set_max_proto_version(wctx->ssl_ctx, TLS1_2_VERSION);
1032 break;
1033 case CURL_SSLVERSION_MAX_TLSv1_1:
1034 res = wolfSSL_CTX_set_max_proto_version(wctx->ssl_ctx, TLS1_1_VERSION);
1035 break;
1036 case CURL_SSLVERSION_MAX_TLSv1_0:
1037 res = wolfSSL_CTX_set_max_proto_version(wctx->ssl_ctx, TLS1_VERSION);
1038 break;
1039 case CURL_SSLVERSION_MAX_DEFAULT:
1040 case CURL_SSLVERSION_MAX_NONE:
1041 res = WOLFSSL_SUCCESS;
1042 break;
1043 default:
1044 failf(data, "wolfSSL: unsupported maximum TLS version value");
1045 result = CURLE_SSL_CONNECT_ERROR;
1046 goto out;
1047 }
1048 if(res != WOLFSSL_SUCCESS) {
1049 failf(data, "wolfSSL: failed set the maximum TLS version");
1050 result = CURLE_SSL_CONNECT_ERROR;
1051 goto out;
1052 }
1053
1054 #ifndef WOLFSSL_TLS13
1055 {
1056 char *ciphers = conn_config->cipher_list;
1057 if(ciphers) {
1058 if(!SSL_CTX_set_cipher_list(wctx->ssl_ctx, ciphers)) {
1059 failf(data, "failed setting cipher list: %s", ciphers);
1060 result = CURLE_SSL_CIPHER;
1061 goto out;
1062 }
1063 infof(data, "Cipher selection: %s", ciphers);
1064 }
1065 }
1066 #else
1067 #define MAX_CIPHER_LEN 4096
1068 if(conn_config->cipher_list || conn_config->cipher_list13) {
1069 const char *ciphers12 = conn_config->cipher_list;
1070 const char *ciphers13 = conn_config->cipher_list13;
1071 struct dynbuf c;
1072 curlx_dyn_init(&c, MAX_CIPHER_LEN);
1073
1074 if(ciphers13)
1075 result = curlx_dyn_add(&c, ciphers13);
1076 else
1077 result = wssl_add_default_ciphers(TRUE, &c);
1078
1079 if(!result) {
1080 if(ciphers12) {
1081 if(curlx_dyn_len(&c))
1082 result = curlx_dyn_addn(&c, ":", 1);
1083 if(!result)
1084 result = curlx_dyn_add(&c, ciphers12);
1085 }
1086 else
1087 result = wssl_add_default_ciphers(FALSE, &c);
1088 }
1089 if(result)
1090 goto out;
1091
1092 if(!wolfSSL_CTX_set_cipher_list(wctx->ssl_ctx, curlx_dyn_ptr(&c))) {
1093 failf(data, "failed setting cipher list: %s", curlx_dyn_ptr(&c));
1094 curlx_dyn_free(&c);
1095 result = CURLE_SSL_CIPHER;
1096 goto out;
1097 }
1098 infof(data, "Cipher selection: %s", curlx_dyn_ptr(&c));
1099 curlx_dyn_free(&c);
1100 }
1101 #endif
1102
1103 curves = conn_config->curves;
1104 if(!curves && cf->conn->transport == TRNSPRT_QUIC)
1105 curves = (char *)CURL_UNCONST(QUIC_GROUPS);
1106
1107 if(curves) {
1108 #ifdef WOLFSSL_HAVE_KYBER
1109 for(idx = 0; gnm[idx].name != NULL; idx++) {
1110 if(strncmp(curves, gnm[idx].name, strlen(gnm[idx].name)) == 0) {
1111 pqkem = gnm[idx].group;
1112 break;
1113 }
1114 }
1115
1116 if(pqkem == 0)
1117 #endif
1118 {
1119 if(!wolfSSL_CTX_set1_curves_list(wctx->ssl_ctx, curves)) {
1120 failf(data, "failed setting curves list: '%s'", curves);
1121 result = CURLE_SSL_CIPHER;
1122 goto out;
1123 }
1124 }
1125 }
1126
1127 /* Load the client certificate, and private key */
1128 #ifndef NO_FILESYSTEM
1129 if(ssl_config->primary.cert_blob || ssl_config->primary.clientcert) {
1130 const char *cert_file = ssl_config->primary.clientcert;
1131 const char *key_file = ssl_config->key;
1132 const struct curl_blob *cert_blob = ssl_config->primary.cert_blob;
1133 const struct curl_blob *key_blob = ssl_config->key_blob;
1134 int file_type = wssl_do_file_type(ssl_config->cert_type);
1135 int rc;
1136
1137 switch(file_type) {
1138 case WOLFSSL_FILETYPE_PEM:
1139 rc = cert_blob ?
1140 wolfSSL_CTX_use_certificate_chain_buffer(wctx->ssl_ctx,
1141 cert_blob->data,
1142 (long)cert_blob->len) :
1143 wolfSSL_CTX_use_certificate_chain_file(wctx->ssl_ctx, cert_file);
1144 break;
1145 case WOLFSSL_FILETYPE_ASN1:
1146 rc = cert_blob ?
1147 wolfSSL_CTX_use_certificate_buffer(wctx->ssl_ctx, cert_blob->data,
1148 (long)cert_blob->len, file_type) :
1149 wolfSSL_CTX_use_certificate_file(wctx->ssl_ctx, cert_file, file_type);
1150 break;
1151 default:
1152 failf(data, "unknown cert type");
1153 result = CURLE_BAD_FUNCTION_ARGUMENT;
1154 goto out;
1155 }
1156 if(rc != 1) {
1157 failf(data, "unable to use client certificate");
1158 result = CURLE_SSL_CONNECT_ERROR;
1159 goto out;
1160 }
1161
1162 if(!key_blob && !key_file) {
1163 key_blob = cert_blob;
1164 key_file = cert_file;
1165 }
1166 else
1167 file_type = wssl_do_file_type(ssl_config->key_type);
1168
1169 rc = key_blob ?
1170 wolfSSL_CTX_use_PrivateKey_buffer(wctx->ssl_ctx, key_blob->data,
1171 (long)key_blob->len, file_type) :
1172 wolfSSL_CTX_use_PrivateKey_file(wctx->ssl_ctx, key_file, file_type);
1173 if(rc != 1) {
1174 failf(data, "unable to set private key");
1175 result = CURLE_SSL_CONNECT_ERROR;
1176 goto out;
1177 }
1178 }
1179 #else /* NO_FILESYSTEM */
1180 if(ssl_config->primary.cert_blob) {
1181 const struct curl_blob *cert_blob = ssl_config->primary.cert_blob;
1182 const struct curl_blob *key_blob = ssl_config->key_blob;
1183 int file_type = wssl_do_file_type(ssl_config->cert_type);
1184 int rc;
1185
1186 switch(file_type) {
1187 case WOLFSSL_FILETYPE_PEM:
1188 rc = wolfSSL_CTX_use_certificate_chain_buffer(wctx->ssl_ctx,
1189 cert_blob->data,
1190 (long)cert_blob->len);
1191 break;
1192 case WOLFSSL_FILETYPE_ASN1:
1193 rc = wolfSSL_CTX_use_certificate_buffer(wctx->ssl_ctx, cert_blob->data,
1194 (long)cert_blob->len, file_type);
1195 break;
1196 default:
1197 failf(data, "unknown cert type");
1198 result = CURLE_BAD_FUNCTION_ARGUMENT;
1199 goto out;
1200 }
1201 if(rc != 1) {
1202 failf(data, "unable to use client certificate");
1203 result = CURLE_SSL_CONNECT_ERROR;
1204 goto out;
1205 }
1206
1207 if(!key_blob)
1208 key_blob = cert_blob;
1209 else
1210 file_type = wssl_do_file_type(ssl_config->key_type);
1211
1212 if(wolfSSL_CTX_use_PrivateKey_buffer(wctx->ssl_ctx, key_blob->data,
1213 (long)key_blob->len,
1214 file_type) != 1) {
1215 failf(data, "unable to set private key");
1216 result = CURLE_SSL_CONNECT_ERROR;
1217 goto out;
1218 }
1219 }
1220 #endif /* !NO_FILESYSTEM */
1221
1222 /* SSL always tries to verify the peer, this only says whether it should
1223 * fail to connect if the verification fails, or if it should continue
1224 * anyway. In the latter case the result of the verification is checked with
1225 * SSL_get_verify_result() below. */
1226 wolfSSL_CTX_set_verify(wctx->ssl_ctx,
1227 conn_config->verifypeer ? WOLFSSL_VERIFY_PEER :
1228 WOLFSSL_VERIFY_NONE, NULL);
1229
1230 #ifdef HAVE_SNI
1231 if(peer->sni) {
1232 size_t sni_len = strlen(peer->sni);
1233 if((sni_len < USHRT_MAX)) {
1234 if(wolfSSL_CTX_UseSNI(wctx->ssl_ctx, WOLFSSL_SNI_HOST_NAME,
1235 peer->sni, (unsigned short)sni_len) != 1) {
1236 failf(data, "Failed to set SNI");
1237 result = CURLE_SSL_CONNECT_ERROR;
1238 goto out;
1239 }
1240 CURL_TRC_CF(data, cf, "set SNI '%s'", peer->sni);
1241 }
1242 }
1243 #endif
1244
1245 if(ssl_config->primary.cache_session &&
1246 cf->conn->transport != TRNSPRT_QUIC) {
1247 /* Register to get notified when a new session is received */
1248 wolfSSL_CTX_sess_set_new_cb(wctx->ssl_ctx, wssl_vtls_new_session_cb);
1249 }
1250
1251 if(cb_setup) {
1252 result = cb_setup(cf, data, cb_user_data);
1253 if(result)
1254 goto out;
1255 }
1256
1257 /* give application a chance to interfere with SSL set up. */
1258 if(data->set.ssl.fsslctx) {
1259 if(!wctx->x509_store_setup) {
1260 result = Curl_wssl_setup_x509_store(cf, data, wctx);
1261 if(result)
1262 goto out;
1263 }
1264 result = (*data->set.ssl.fsslctx)(data, wctx->ssl_ctx,
1265 data->set.ssl.fsslctxp);
1266 if(result) {
1267 failf(data, "error signaled by ssl ctx callback");
1268 goto out;
1269 }
1270 }
1271 #ifdef NO_FILESYSTEM
1272 else if(conn_config->verifypeer) {
1273 failf(data, "SSL: Certificates cannot be loaded because wolfSSL was built"
1274 " with \"no filesystem\". Either disable peer verification"
1275 " (insecure) or if you are building an application with libcurl you"
1276 " can load certificates via CURLOPT_SSL_CTX_FUNCTION.");
1277 result = CURLE_SSL_CONNECT_ERROR;
1278 goto out;
1279 }
1280 #endif
1281
1282 /* Let's make an SSL structure */
1283 wctx->ssl = wolfSSL_new(wctx->ssl_ctx);
1284 if(!wctx->ssl) {
1285 failf(data, "SSL: could not create a handle");
1286 result = CURLE_OUT_OF_MEMORY;
1287 goto out;
1288 }
1289
1290 wolfSSL_set_app_data(wctx->ssl, ssl_user_data);
1291 #ifdef WOLFSSL_QUIC
1292 if(cf->conn->transport == TRNSPRT_QUIC)
1293 wolfSSL_set_quic_use_legacy_codepoint(wctx->ssl, 0);
1294 #endif
1295
1296 #ifdef WOLFSSL_HAVE_KYBER
1297 if(pqkem) {
1298 if(wolfSSL_UseKeyShare(wctx->ssl, pqkem) != WOLFSSL_SUCCESS) {
1299 failf(data, "unable to use PQ KEM");
1300 }
1301 }
1302 #endif
1303
1304 /* Check if there is a cached ID we can/should use here! */
1305 if(ssl_config->primary.cache_session) {
1306 /* Set session from cache if there is one */
1307 (void)wssl_setup_session(cf, data, wctx, &alpns,
1308 peer->scache_key, sess_reuse_cb);
1309 }
1310
1311 #ifdef HAVE_ALPN
1312 if(alpns.count) {
1313 struct alpn_proto_buf proto;
1314 memset(&proto, 0, sizeof(proto));
1315 Curl_alpn_to_proto_str(&proto, &alpns);
1316
1317 if(wolfSSL_UseALPN(wctx->ssl, (char *)proto.data,
1318 (unsigned int)proto.len,
1319 WOLFSSL_ALPN_CONTINUE_ON_MISMATCH) != WOLFSSL_SUCCESS) {
1320 failf(data, "SSL: failed setting ALPN protocols");
1321 result = CURLE_SSL_CONNECT_ERROR;
1322 goto out;
1323 }
1324 CURL_TRC_CF(data, cf, "set ALPN: %s", proto.data);
1325 }
1326 #endif /* HAVE_ALPN */
1327
1328 #ifdef OPENSSL_EXTRA
1329 if(Curl_tls_keylog_enabled()) {
1330 /* Ensure the Client Random is preserved. */
1331 wolfSSL_KeepArrays(wctx->ssl);
1332 #if defined(HAVE_SECRET_CALLBACK) && defined(WOLFSSL_TLS13)
1333 wolfSSL_set_tls13_secret_cb(wctx->ssl,
1334 wssl_tls13_secret_callback, NULL);
1335 #endif
1336 }
1337 #endif /* OPENSSL_EXTRA */
1338
1339 #ifdef HAVE_SECURE_RENEGOTIATION
1340 if(wolfSSL_UseSecureRenegotiation(wctx->ssl) != SSL_SUCCESS) {
1341 failf(data, "SSL: failed setting secure renegotiation");
1342 result = CURLE_SSL_CONNECT_ERROR;
1343 goto out;
1344 }
1345 #endif /* HAVE_SECURE_RENEGOTIATION */
1346
1347 #ifdef USE_ECH_WOLFSSL
1348 if(ECH_ENABLED(data)) {
1349 int trying_ech_now = 0;
1350
1351 if(data->set.str[STRING_ECH_PUBLIC]) {
1352 infof(data, "ECH: outername not (yet) supported with wolfSSL");
1353 result = CURLE_SSL_CONNECT_ERROR;
1354 goto out;
1355 }
1356 if(data->set.tls_ech == CURLECH_GREASE) {
1357 infof(data, "ECH: GREASE is done by default by wolfSSL: no need to ask");
1358 }
1359 if(data->set.tls_ech & CURLECH_CLA_CFG
1360 && data->set.str[STRING_ECH_CONFIG]) {
1361 char *b64val = data->set.str[STRING_ECH_CONFIG];
1362 word32 b64len = 0;
1363
1364 b64len = (word32) strlen(b64val);
1365 if(b64len
1366 && wolfSSL_SetEchConfigsBase64(wctx->ssl, b64val, b64len)
1367 != WOLFSSL_SUCCESS) {
1368 if(data->set.tls_ech & CURLECH_HARD) {
1369 result = CURLE_SSL_CONNECT_ERROR;
1370 goto out;
1371 }
1372 }
1373 else {
1374 trying_ech_now = 1;
1375 infof(data, "ECH: ECHConfig from command line");
1376 }
1377 }
1378 else {
1379 struct ssl_connect_data *connssl = cf->ctx;
1380 struct Curl_dns_entry *dns = NULL;
1381
1382 dns = Curl_dnscache_get(data, connssl->peer.hostname, connssl->peer.port,
1383 cf->conn->ip_version);
1384 if(!dns) {
1385 infof(data, "ECH: requested but no DNS info available");
1386 if(data->set.tls_ech & CURLECH_HARD) {
1387 result = CURLE_SSL_CONNECT_ERROR;
1388 goto out;
1389 }
1390 }
1391 else {
1392 struct Curl_https_rrinfo *rinfo = NULL;
1393
1394 rinfo = dns->hinfo;
1395 if(rinfo && rinfo->echconfiglist) {
1396 unsigned char *ecl = rinfo->echconfiglist;
1397 size_t elen = rinfo->echconfiglist_len;
1398
1399 infof(data, "ECH: ECHConfig from DoH HTTPS RR");
1400 if(wolfSSL_SetEchConfigs(wctx->ssl, ecl, (word32) elen) !=
1401 WOLFSSL_SUCCESS) {
1402 infof(data, "ECH: wolfSSL_SetEchConfigs failed");
1403 if(data->set.tls_ech & CURLECH_HARD) {
1404 result = CURLE_SSL_CONNECT_ERROR;
1405 goto out;
1406 }
1407 }
1408 else {
1409 trying_ech_now = 1;
1410 infof(data, "ECH: imported ECHConfigList of length %ld", elen);
1411 }
1412 }
1413 else {
1414 infof(data, "ECH: requested but no ECHConfig available");
1415 if(data->set.tls_ech & CURLECH_HARD) {
1416 result = CURLE_SSL_CONNECT_ERROR;
1417 goto out;
1418 }
1419 }
1420 Curl_resolv_unlink(data, &dns);
1421 }
1422 }
1423
1424 if(trying_ech_now && wolfSSL_set_min_proto_version(wctx->ssl,
1425 TLS1_3_VERSION) != 1) {
1426 infof(data, "ECH: cannot force TLSv1.3 [ERROR]");
1427 result = CURLE_SSL_CONNECT_ERROR;
1428 goto out;
1429 }
1430
1431 }
1432 #endif /* USE_ECH_WOLFSSL */
1433
1434 result = CURLE_OK;
1435
1436 out:
1437 if(result && wctx->ssl) {
1438 wolfSSL_free(wctx->ssl);
1439 wctx->ssl = NULL;
1440 }
1441 if(result && wctx->ssl_ctx) {
1442 wolfSSL_CTX_free(wctx->ssl_ctx);
1443 wctx->ssl_ctx = NULL;
1444 }
1445 return result;
1446 }
1447
1448 /*
1449 * This function loads all the client/CA certificates and CRLs. Setup the TLS
1450 * layer and do all necessary magic.
1451 */
1452 static CURLcode
1453 wssl_connect_step1(struct Curl_cfilter *cf, struct Curl_easy *data)
1454 {
1455 struct ssl_connect_data *connssl = cf->ctx;
1456 struct wssl_ctx *wssl = (struct wssl_ctx *)connssl->backend;
1457 struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
1458 CURLcode result;
1459
1460 DEBUGASSERT(wssl);
1461
1462 if(connssl->state == ssl_connection_complete)
1463 return CURLE_OK;
1464
1465 result = Curl_wssl_ctx_init(wssl, cf, data, &connssl->peer,
1466 connssl->alpn, NULL, NULL, cf,
1467 wssl_on_session_reuse);
1468 if(result)
1469 return result;
1470
1471 #ifdef HAVE_ALPN
1472 if(connssl->alpn && (connssl->state != ssl_connection_deferred)) {
1473 struct alpn_proto_buf proto;
1474 memset(&proto, 0, sizeof(proto));
1475 Curl_alpn_to_proto_str(&proto, connssl->alpn);
1476 infof(data, VTLS_INFOF_ALPN_OFFER_1STR, proto.data);
1477 }
1478 #endif
1479
1480 /* Enable RFC2818 checks */
1481 if(conn_config->verifyhost) {
1482 char *snihost = connssl->peer.sni ?
1483 connssl->peer.sni : connssl->peer.hostname;
1484 if(wolfSSL_check_domain_name(wssl->ssl, snihost) !=
1485 WOLFSSL_SUCCESS) {
1486 return CURLE_SSL_CONNECT_ERROR;
1487 }
1488 }
1489
1490 #ifdef USE_BIO_CHAIN
1491 {
1492 WOLFSSL_BIO *bio;
1493
1494 bio = wolfSSL_BIO_new(wssl_bio_cf_method);
1495 if(!bio)
1496 return CURLE_OUT_OF_MEMORY;
1497
1498 wolfSSL_BIO_set_data(bio, cf);
1499 wolfSSL_set_bio(wssl->ssl, bio, bio);
1500 }
1501 #else /* USE_BIO_CHAIN */
1502 /* pass the raw socket into the SSL layer */
1503 if(!wolfSSL_set_fd(wssl->ssl,
1504 (int)Curl_conn_cf_get_socket(cf, data))) {
1505 failf(data, "SSL: wolfSSL_set_fd failed");
1506 return CURLE_SSL_CONNECT_ERROR;
1507 }
1508 #endif /* !USE_BIO_CHAIN */
1509
1510 return CURLE_OK;
1511 }
1512
1513
1514 static char *wssl_strerror(unsigned long error, char *buf,
1515 unsigned long size)
1516 {
1517 DEBUGASSERT(size > 40);
1518 *buf = '\0';
1519
1520 wolfSSL_ERR_error_string_n(error, buf, size);
1521
1522 if(!*buf) {
1523 const char *msg = error ? "Unknown error" : "No error";
1524 /* the string fits because the assert above assures this */
1525 strcpy(buf, msg);
1526 }
1527
1528 return buf;
1529 }
1530
1531 CURLcode Curl_wssl_verify_pinned(struct Curl_cfilter *cf,
1532 struct Curl_easy *data,
1533 struct wssl_ctx *wssl)
1534 {
1535 #ifndef CURL_DISABLE_PROXY
1536 const char * const pinnedpubkey = Curl_ssl_cf_is_proxy(cf) ?
1537 data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY] :
1538 data->set.str[STRING_SSL_PINNEDPUBLICKEY];
1539 #else
1540 const char * const pinnedpubkey = data->set.str[STRING_SSL_PINNEDPUBLICKEY];
1541 #endif
1542
1543 if(pinnedpubkey) {
1544 #ifdef KEEP_PEER_CERT
1545 WOLFSSL_X509 *x509;
1546 const char *x509_der;
1547 int x509_der_len;
1548 struct Curl_X509certificate x509_parsed;
1549 struct Curl_asn1Element *pubkey;
1550 CURLcode result;
1551
1552 x509 = wolfSSL_get_peer_certificate(wssl->ssl);
1553 if(!x509) {
1554 failf(data, "SSL: failed retrieving server certificate");
1555 return CURLE_SSL_PINNEDPUBKEYNOTMATCH;
1556 }
1557
1558 x509_der = (const char *)wolfSSL_X509_get_der(x509, &x509_der_len);
1559 if(!x509_der) {
1560 failf(data, "SSL: failed retrieving ASN.1 server certificate");
1561 return CURLE_SSL_PINNEDPUBKEYNOTMATCH;
1562 }
1563
1564 memset(&x509_parsed, 0, sizeof(x509_parsed));
1565 if(Curl_parseX509(&x509_parsed, x509_der, x509_der + x509_der_len))
1566 return CURLE_SSL_PINNEDPUBKEYNOTMATCH;
1567
1568 pubkey = &x509_parsed.subjectPublicKeyInfo;
1569 if(!pubkey->header || pubkey->end <= pubkey->header) {
1570 failf(data, "SSL: failed retrieving public key from server certificate");
1571 return CURLE_SSL_PINNEDPUBKEYNOTMATCH;
1572 }
1573
1574 result = Curl_pin_peer_pubkey(data,
1575 pinnedpubkey,
1576 (const unsigned char *)pubkey->header,
1577 (size_t)(pubkey->end - pubkey->header));
1578 wolfSSL_FreeX509(x509);
1579 if(result) {
1580 failf(data, "SSL: public key does not match pinned public key");
1581 return result;
1582 }
1583 #else
1584 failf(data, "Library lacks pinning support built-in");
1585 return CURLE_NOT_BUILT_IN;
1586 #endif
1587 }
1588 return CURLE_OK;
1589 }
1590
1591 #ifdef WOLFSSL_EARLY_DATA
1592 static CURLcode wssl_send_earlydata(struct Curl_cfilter *cf,
1593 struct Curl_easy *data)
1594 {
1595 struct ssl_connect_data *connssl = cf->ctx;
1596 struct wssl_ctx *wssl = (struct wssl_ctx *)connssl->backend;
1597 CURLcode result = CURLE_OK;
1598 const unsigned char *buf;
1599 size_t blen;
1600
1601 DEBUGASSERT(connssl->earlydata_state == ssl_earlydata_sending);
1602 wssl->io_result = CURLE_OK;
1603 while(Curl_bufq_peek(&connssl->earlydata, &buf, &blen)) {
1604 int nwritten = 0, rc;
1605
1606 wolfSSL_ERR_clear_error();
1607 rc = wolfSSL_write_early_data(wssl->ssl, buf, (int)blen, &nwritten);
1608 CURL_TRC_CF(data, cf, "wolfSSL_write_early_data(len=%zu) -> %d, %d",
1609 blen, rc, nwritten);
1610 if(rc < 0) {
1611 int err = wolfSSL_get_error(wssl->ssl, rc);
1612 switch(err) {
1613 case WOLFSSL_ERROR_NONE: /* just did not get anything */
1614 case WOLFSSL_ERROR_WANT_READ:
1615 case WOLFSSL_ERROR_WANT_WRITE:
1616 result = CURLE_AGAIN;
1617 break;
1618 default: {
1619 char error_buffer[256];
1620 int detail = wolfSSL_get_error(wssl->ssl, err);
1621 CURL_TRC_CF(data, cf, "SSL send early data, error: '%s'(%d)",
1622 wssl_strerror((unsigned long)err, error_buffer,
1623 sizeof(error_buffer)),
1624 detail);
1625 result = CURLE_SEND_ERROR;
1626 break;
1627 }
1628 }
1629 goto out;
1630 }
1631
1632 Curl_bufq_skip(&connssl->earlydata, (size_t)nwritten);
1633 }
1634 /* sent everything there was */
1635 connssl->earlydata_state = ssl_earlydata_sent;
1636 if(!Curl_ssl_cf_is_proxy(cf))
1637 Curl_pgrsEarlyData(data, (curl_off_t)connssl->earlydata_skip);
1638 infof(data, "SSL sending %zu bytes of early data", connssl->earlydata_skip);
1639 out:
1640 return result;
1641 }
1642 #endif /* WOLFSSL_EARLY_DATA */
1643
1644 static CURLcode wssl_handshake(struct Curl_cfilter *cf,
1645 struct Curl_easy *data)
1646 {
1647 struct ssl_connect_data *connssl = cf->ctx;
1648 struct wssl_ctx *wssl = (struct wssl_ctx *)connssl->backend;
1649 struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
1650 int ret = -1, detail;
1651 CURLcode result;
1652
1653 DEBUGASSERT(wssl);
1654 connssl->io_need = CURL_SSL_IO_NEED_NONE;
1655
1656 #ifdef WOLFSSL_EARLY_DATA
1657 if(connssl->earlydata_state == ssl_earlydata_sending) {
1658 result = wssl_send_earlydata(cf, data);
1659 if(result)
1660 return result;
1661 }
1662 DEBUGASSERT((connssl->earlydata_state == ssl_earlydata_none) ||
1663 (connssl->earlydata_state == ssl_earlydata_sent));
1664 #else
1665 DEBUGASSERT(connssl->earlydata_state == ssl_earlydata_none);
1666 #endif /* WOLFSSL_EARLY_DATA */
1667
1668 wolfSSL_ERR_clear_error();
1669 ret = wolfSSL_connect(wssl->ssl);
1670
1671 if(!wssl->x509_store_setup) {
1672 /* After having send off the ClientHello, we prepare the x509
1673 * store to verify the coming certificate from the server */
1674 result = Curl_wssl_setup_x509_store(cf, data, wssl);
1675 if(result) {
1676 CURL_TRC_CF(data, cf, "Curl_wssl_setup_x509_store() -> %d", result);
1677 return result;
1678 }
1679 }
1680
1681 #ifdef OPENSSL_EXTRA
1682 if(Curl_tls_keylog_enabled()) {
1683 /* If key logging is enabled, wait for the handshake to complete and then
1684 * proceed with logging secrets (for TLS 1.2 or older).
1685 *
1686 * During the handshake (ret==-1), wolfSSL_want_read() is true as it waits
1687 * for the server response. At that point the master secret is not yet
1688 * available, so we must not try to read it.
1689 * To log the secret on completion with a handshake failure, detect
1690 * completion via the observation that there is nothing to read or write.
1691 * Note that OpenSSL SSL_want_read() is always true here. If wolfSSL ever
1692 * changes, the worst case is that no key is logged on error.
1693 */
1694 if(ret == WOLFSSL_SUCCESS ||
1695 (!wolfSSL_want_read(wssl->ssl) &&
1696 !wolfSSL_want_write(wssl->ssl))) {
1697 wssl_log_tls12_secret(wssl->ssl);
1698 /* Client Random and master secrets are no longer needed, erase these.
1699 * Ignored while the handshake is still in progress. */
1700 wolfSSL_FreeArrays(wssl->ssl);
1701 }
1702 }
1703 #endif /* OPENSSL_EXTRA */
1704
1705 detail = wolfSSL_get_error(wssl->ssl, ret);
1706 CURL_TRC_CF(data, cf, "wolfSSL_connect() -> %d, detail=%d", ret, detail);
1707
1708 if(ret == WOLFSSL_SUCCESS) {
1709 return CURLE_OK;
1710 }
1711 else {
1712 if(WOLFSSL_ERROR_WANT_READ == detail) {
1713 connssl->io_need = CURL_SSL_IO_NEED_RECV;
1714 return CURLE_AGAIN;
1715 }
1716 else if(WOLFSSL_ERROR_WANT_WRITE == detail) {
1717 connssl->io_need = CURL_SSL_IO_NEED_SEND;
1718 return CURLE_AGAIN;
1719 }
1720 else if(DOMAIN_NAME_MISMATCH == detail) {
1721 /* There is no easy way to override only the CN matching.
1722 * This will enable the override of both mismatching SubjectAltNames
1723 * as also mismatching CN fields */
1724 failf(data, " subject alt name(s) or common name do not match \"%s\"",
1725 connssl->peer.dispname);
1726 return CURLE_PEER_FAILED_VERIFICATION;
1727 }
1728 else if(ASN_NO_SIGNER_E == detail) {
1729 if(conn_config->verifypeer) {
1730 failf(data, " CA signer not available for verification");
1731 return CURLE_SSL_CACERT_BADFILE;
1732 }
1733 /* Just continue with a warning if no strict certificate
1734 verification is required. */
1735 infof(data, "CA signer not available for verification, "
1736 "continuing anyway");
1737 return CURLE_OK;
1738 }
1739 else if(ASN_AFTER_DATE_E == detail) {
1740 failf(data, "server verification failed: certificate has expired.");
1741 return CURLE_PEER_FAILED_VERIFICATION;
1742 }
1743 else if(ASN_BEFORE_DATE_E == detail) {
1744 failf(data, "server verification failed: certificate not valid yet.");
1745 return CURLE_PEER_FAILED_VERIFICATION;
1746 }
1747 else if(wssl->io_result) {
1748 switch(wssl->io_result) {
1749 case CURLE_SEND_ERROR:
1750 case CURLE_RECV_ERROR:
1751 return CURLE_SSL_CONNECT_ERROR;
1752 default:
1753 return wssl->io_result;
1754 }
1755 }
1756 #ifdef USE_ECH_WOLFSSL
1757 else if(-1 == detail) {
1758 /* try access a retry_config ECHConfigList for tracing */
1759 byte echConfigs[1000];
1760 word32 echConfigsLen = 1000;
1761 int rv = 0;
1762
1763 /* this currently does not produce the retry_configs */
1764 rv = wolfSSL_GetEchConfigs(wssl->ssl, echConfigs,
1765 &echConfigsLen);
1766 if(rv != WOLFSSL_SUCCESS) {
1767 infof(data, "Failed to get ECHConfigs");
1768 }
1769 else {
1770 char *b64str = NULL;
1771 size_t blen = 0;
1772
1773 result = curlx_base64_encode((const char *)echConfigs, echConfigsLen,
1774 &b64str, &blen);
1775 if(!result && b64str)
1776 infof(data, "ECH: (not yet) retry_configs %s", b64str);
1777 free(b64str);
1778 }
1779 return CURLE_SSL_CONNECT_ERROR;
1780 }
1781 #endif
1782 else {
1783 char error_buffer[256];
1784 failf(data, "SSL_connect failed with error %d: %s", detail,
1785 wssl_strerror((unsigned long)detail, error_buffer,
1786 sizeof(error_buffer)));
1787 return CURLE_SSL_CONNECT_ERROR;
1788 }
1789 }
1790 }
1791
1792 static ssize_t wssl_send(struct Curl_cfilter *cf,
1793 struct Curl_easy *data,
1794 const void *buf, size_t blen,
1795 CURLcode *curlcode)
1796 {
1797 struct ssl_connect_data *connssl = cf->ctx;
1798 struct wssl_ctx *wssl = (struct wssl_ctx *)connssl->backend;
1799 size_t total_written = 0;
1800 ssize_t nwritten = -1;
1801 DEBUGASSERT(wssl);
1802
1803 wolfSSL_ERR_clear_error();
1804
1805 if(blen) {
1806 int memlen = (blen > (size_t)INT_MAX) ? INT_MAX : (int)blen;
1807 int rc;
1808
1809 rc = wolfSSL_write(wssl->ssl, buf, memlen);
1810 if(rc <= 0) {
1811 int err = wolfSSL_get_error(wssl->ssl, rc);
1812
1813 switch(err) {
1814 case WOLFSSL_ERROR_WANT_READ:
1815 case WOLFSSL_ERROR_WANT_WRITE:
1816 /* there is data pending, re-invoke wolfSSL_write() */
1817 if(total_written) {
1818 *curlcode = CURLE_OK;
1819 nwritten = total_written;
1820 goto out;
1821 }
1822 *curlcode = CURLE_AGAIN;
1823 nwritten = -1;
1824 goto out;
1825
1826 default:
1827 if(wssl->io_result == CURLE_AGAIN) {
1828 if(total_written) {
1829 *curlcode = CURLE_OK;
1830 nwritten = total_written;
1831 goto out;
1832 }
1833 *curlcode = CURLE_AGAIN;
1834 nwritten = -1;
1835 goto out;
1836 }
1837 {
1838 char error_buffer[256];
1839 failf(data, "SSL write: %s, errno %d",
1840 wssl_strerror((unsigned long)err, error_buffer,
1841 sizeof(error_buffer)),
1842 SOCKERRNO);
1843 }
1844 *curlcode = CURLE_SEND_ERROR;
1845 nwritten = -1;
1846 goto out;
1847 }
1848 }
1849 else
1850 total_written += rc;
1851 }
1852
1853 *curlcode = CURLE_OK;
1854 nwritten = total_written;
1855 out:
1856 CURL_TRC_CF(data, cf, "wssl_send(len=%zu) -> %" FMT_OFF_T ", %d",
1857 blen, nwritten, *curlcode);
1858 return nwritten;
1859 }
1860
1861 static CURLcode wssl_shutdown(struct Curl_cfilter *cf,
1862 struct Curl_easy *data,
1863 bool send_shutdown, bool *done)
1864 {
1865 struct ssl_connect_data *connssl = cf->ctx;
1866 struct wssl_ctx *wctx = (struct wssl_ctx *)connssl->backend;
1867 CURLcode result = CURLE_OK;
1868 char buf[1024];
1869 char error_buffer[256];
1870 int nread = -1, err;
1871 size_t i;
1872 int detail;
1873
1874 DEBUGASSERT(wctx);
1875 if(!wctx->ssl || cf->shutdown) {
1876 *done = TRUE;
1877 goto out;
1878 }
1879
1880 wctx->shutting_down = TRUE;
1881 connssl->io_need = CURL_SSL_IO_NEED_NONE;
1882 *done = FALSE;
1883 if(!(wolfSSL_get_shutdown(wctx->ssl) & WOLFSSL_SENT_SHUTDOWN)) {
1884 /* We have not started the shutdown from our side yet. Check
1885 * if the server already sent us one. */
1886 wolfSSL_ERR_clear_error();
1887 nread = wolfSSL_read(wctx->ssl, buf, (int)sizeof(buf));
1888 err = wolfSSL_get_error(wctx->ssl, nread);
1889 CURL_TRC_CF(data, cf, "wolfSSL_read, nread=%d, err=%d", nread, err);
1890 if(!nread && err == WOLFSSL_ERROR_ZERO_RETURN) {
1891 bool input_pending;
1892 /* Yes, it did. */
1893 if(!send_shutdown) {
1894 CURL_TRC_CF(data, cf, "SSL shutdown received, not sending");
1895 *done = TRUE;
1896 goto out;
1897 }
1898 else if(!cf->next->cft->is_alive(cf->next, data, &input_pending)) {
1899 /* Server closed the connection after its closy notify. It
1900 * seems not interested to see our close notify, so do not
1901 * send it. We are done. */
1902 CURL_TRC_CF(data, cf, "peer closed connection");
1903 connssl->peer_closed = TRUE;
1904 *done = TRUE;
1905 goto out;
1906 }
1907 }
1908 }
1909
1910 /* wolfSSL should now have started the shutdown from our side. Since it
1911 * was not complete, we are lacking the close notify from the server. */
1912 if(send_shutdown) {
1913 wolfSSL_ERR_clear_error();
1914 if(wolfSSL_shutdown(wctx->ssl) == 1) {
1915 CURL_TRC_CF(data, cf, "SSL shutdown finished");
1916 *done = TRUE;
1917 goto out;
1918 }
1919 if(WOLFSSL_ERROR_WANT_WRITE == wolfSSL_get_error(wctx->ssl, nread)) {
1920 CURL_TRC_CF(data, cf, "SSL shutdown still wants to send");
1921 connssl->io_need = CURL_SSL_IO_NEED_SEND;
1922 goto out;
1923 }
1924 /* Having sent the close notify, we use wolfSSL_read() to get the
1925 * missing close notify from the server. */
1926 }
1927
1928 for(i = 0; i < 10; ++i) {
1929 wolfSSL_ERR_clear_error();
1930 nread = wolfSSL_read(wctx->ssl, buf, (int)sizeof(buf));
1931 if(nread <= 0)
1932 break;
1933 }
1934 err = wolfSSL_get_error(wctx->ssl, nread);
1935 switch(err) {
1936 case WOLFSSL_ERROR_ZERO_RETURN: /* no more data */
1937 CURL_TRC_CF(data, cf, "SSL shutdown received");
1938 *done = TRUE;
1939 break;
1940 case WOLFSSL_ERROR_NONE: /* just did not get anything */
1941 case WOLFSSL_ERROR_WANT_READ:
1942 /* wolfSSL has send its notify and now wants to read the reply
1943 * from the server. We are not really interested in that. */
1944 CURL_TRC_CF(data, cf, "SSL shutdown sent, want receive");
1945 connssl->io_need = CURL_SSL_IO_NEED_RECV;
1946 break;
1947 case WOLFSSL_ERROR_WANT_WRITE:
1948 CURL_TRC_CF(data, cf, "SSL shutdown send blocked");
1949 connssl->io_need = CURL_SSL_IO_NEED_SEND;
1950 break;
1951 default:
1952 detail = wolfSSL_get_error(wctx->ssl, err);
1953 CURL_TRC_CF(data, cf, "SSL shutdown, error: '%s'(%d)",
1954 wssl_strerror((unsigned long)err, error_buffer,
1955 sizeof(error_buffer)),
1956 detail);
1957 result = CURLE_RECV_ERROR;
1958 break;
1959 }
1960
1961 out:
1962 cf->shutdown = (result || *done);
1963 return result;
1964 }
1965
1966 static void wssl_close(struct Curl_cfilter *cf, struct Curl_easy *data)
1967 {
1968 struct ssl_connect_data *connssl = cf->ctx;
1969 struct wssl_ctx *wssl = (struct wssl_ctx *)connssl->backend;
1970
1971 (void) data;
1972
1973 DEBUGASSERT(wssl);
1974
1975 if(wssl->ssl) {
1976 wolfSSL_free(wssl->ssl);
1977 wssl->ssl = NULL;
1978 }
1979 if(wssl->ssl_ctx) {
1980 wolfSSL_CTX_free(wssl->ssl_ctx);
1981 wssl->ssl_ctx = NULL;
1982 }
1983 }
1984
1985 static ssize_t wssl_recv(struct Curl_cfilter *cf,
1986 struct Curl_easy *data,
1987 char *buf, size_t blen,
1988 CURLcode *curlcode)
1989 {
1990 struct ssl_connect_data *connssl = cf->ctx;
1991 struct wssl_ctx *wssl = (struct wssl_ctx *)connssl->backend;
1992 int buffsize = (blen > (size_t)INT_MAX) ? INT_MAX : (int)blen;
1993 int nread;
1994
1995 DEBUGASSERT(wssl);
1996
1997 wolfSSL_ERR_clear_error();
1998 *curlcode = CURLE_OK;
1999
2000 nread = wolfSSL_read(wssl->ssl, buf, buffsize);
2001
2002 if(nread <= 0) {
2003 int err = wolfSSL_get_error(wssl->ssl, nread);
2004
2005 switch(err) {
2006 case WOLFSSL_ERROR_ZERO_RETURN: /* no more data */
2007 CURL_TRC_CF(data, cf, "wssl_recv(len=%zu) -> CLOSED", blen);
2008 *curlcode = CURLE_OK;
2009 return 0;
2010 case WOLFSSL_ERROR_NONE:
2011 case WOLFSSL_ERROR_WANT_READ:
2012 case WOLFSSL_ERROR_WANT_WRITE:
2013 if(!wssl->io_result && connssl->peer_closed) {
2014 CURL_TRC_CF(data, cf, "wssl_recv(len=%zu) -> CLOSED", blen);
2015 *curlcode = CURLE_OK;
2016 return 0;
2017 }
2018 /* there is data pending, re-invoke wolfSSL_read() */
2019 CURL_TRC_CF(data, cf, "wssl_recv(len=%zu) -> AGAIN", blen);
2020 *curlcode = CURLE_AGAIN;
2021 return -1;
2022 default:
2023 if(wssl->io_result == CURLE_AGAIN) {
2024 CURL_TRC_CF(data, cf, "wssl_recv(len=%zu) -> AGAIN", blen);
2025 *curlcode = CURLE_AGAIN;
2026 return -1;
2027 }
2028 else if(!wssl->io_result && connssl->peer_closed) {
2029 CURL_TRC_CF(data, cf, "wssl_recv(len=%zu) -> CLOSED", blen);
2030 *curlcode = CURLE_OK;
2031 return 0;
2032 }
2033 else {
2034 char error_buffer[256];
2035 failf(data, "SSL read: %s, errno %d",
2036 wssl_strerror((unsigned long)err, error_buffer,
2037 sizeof(error_buffer)),
2038 SOCKERRNO);
2039 }
2040 *curlcode = CURLE_RECV_ERROR;
2041 return -1;
2042 }
2043 }
2044
2045 CURL_TRC_CF(data, cf, "wssl_recv(len=%zu) -> %d", blen, nread);
2046 return nread;
2047 }
2048
2049 size_t Curl_wssl_version(char *buffer, size_t size)
2050 {
2051 #if LIBWOLFSSL_VERSION_HEX >= 0x03006000
2052 return msnprintf(buffer, size, "wolfSSL/%s", wolfSSL_lib_version());
2053 #elif defined(WOLFSSL_VERSION)
2054 return msnprintf(buffer, size, "wolfSSL/%s", WOLFSSL_VERSION);
2055 #endif
2056 }
2057
2058
2059 static int wssl_init(void)
2060 {
2061 int ret;
2062
2063 #ifdef OPENSSL_EXTRA
2064 Curl_tls_keylog_open();
2065 #endif
2066 ret = (wolfSSL_Init() == WOLFSSL_SUCCESS);
2067 wssl_bio_cf_init_methods();
2068 return ret;
2069 }
2070
2071
2072 static void wssl_cleanup(void)
2073 {
2074 wssl_bio_cf_free_methods();
2075 wolfSSL_Cleanup();
2076 #ifdef OPENSSL_EXTRA
2077 Curl_tls_keylog_close();
2078 #endif
2079 }
2080
2081
2082 static bool wssl_data_pending(struct Curl_cfilter *cf,
2083 const struct Curl_easy *data)
2084 {
2085 struct ssl_connect_data *ctx = cf->ctx;
2086 struct wssl_ctx *wssl;
2087
2088 (void)data;
2089 DEBUGASSERT(ctx && ctx->backend);
2090
2091 wssl = (struct wssl_ctx *)ctx->backend;
2092 if(wssl->ssl) /* wolfSSL is in use */
2093 return wolfSSL_pending(wssl->ssl);
2094 else
2095 return FALSE;
2096 }
2097
2098 static CURLcode wssl_connect(struct Curl_cfilter *cf,
2099 struct Curl_easy *data,
2100 bool *done)
2101 {
2102 struct ssl_connect_data *connssl = cf->ctx;
2103 struct wssl_ctx *wssl = (struct wssl_ctx *)connssl->backend;
2104 CURLcode result = CURLE_OK;
2105
2106 /* check if the connection has already been established */
2107 if(ssl_connection_complete == connssl->state) {
2108 *done = TRUE;
2109 return CURLE_OK;
2110 }
2111
2112 *done = FALSE;
2113 connssl->io_need = CURL_SSL_IO_NEED_NONE;
2114
2115 if(ssl_connect_1 == connssl->connecting_state) {
2116 result = wssl_connect_step1(cf, data);
2117 if(result)
2118 return result;
2119 connssl->connecting_state = ssl_connect_2;
2120 }
2121
2122 if(ssl_connect_2 == connssl->connecting_state) {
2123 if(connssl->earlydata_state == ssl_earlydata_await) {
2124 /* We defer the handshake until request data arrives. */
2125 DEBUGASSERT(connssl->state == ssl_connection_deferred);
2126 goto out;
2127 }
2128 result = wssl_handshake(cf, data);
2129 if(result == CURLE_AGAIN)
2130 goto out;
2131 wssl->hs_result = result;
2132 connssl->connecting_state = ssl_connect_3;
2133 }
2134
2135 if(ssl_connect_3 == connssl->connecting_state) {
2136 /* Once the handshake has errored, it stays in that state and will
2137 * error again on every call. */
2138 if(wssl->hs_result) {
2139 result = wssl->hs_result;
2140 goto out;
2141 }
2142 result = Curl_wssl_verify_pinned(cf, data, wssl);
2143 if(result) {
2144 wssl->hs_result = result;
2145 goto out;
2146 }
2147 /* handhshake was done without errors */
2148 #ifdef HAVE_ALPN
2149 if(connssl->alpn) {
2150 int rc;
2151 char *protocol = NULL;
2152 unsigned short protocol_len = 0;
2153
2154 rc = wolfSSL_ALPN_GetProtocol(wssl->ssl, &protocol, &protocol_len);
2155
2156 if(rc == WOLFSSL_SUCCESS) {
2157 Curl_alpn_set_negotiated(cf, data, connssl,
2158 (const unsigned char *)protocol,
2159 protocol_len);
2160 }
2161 else if(rc == WOLFSSL_ALPN_NOT_FOUND)
2162 Curl_alpn_set_negotiated(cf, data, connssl, NULL, 0);
2163 else {
2164 failf(data, "ALPN, failure getting protocol, error %d", rc);
2165 wssl->hs_result = result = CURLE_SSL_CONNECT_ERROR;
2166 goto out;
2167 }
2168 }
2169 #endif /* HAVE_ALPN */
2170
2171 #if (LIBWOLFSSL_VERSION_HEX >= 0x03009010)
2172 infof(data, "SSL connection using %s / %s",
2173 wolfSSL_get_version(wssl->ssl),
2174 wolfSSL_get_cipher_name(wssl->ssl));
2175 #else
2176 infof(data, "SSL connected");
2177 #endif
2178
2179 connssl->connecting_state = ssl_connect_done;
2180 connssl->state = ssl_connection_complete;
2181
2182 #ifdef WOLFSSL_EARLY_DATA
2183 if(connssl->earlydata_state > ssl_earlydata_none) {
2184 /* We should be in this state by now */
2185 DEBUGASSERT(connssl->earlydata_state == ssl_earlydata_sent);
2186 connssl->earlydata_state =
2187 (wolfSSL_get_early_data_status(wssl->ssl) ==
2188 WOLFSSL_EARLY_DATA_REJECTED) ?
2189 ssl_earlydata_rejected : ssl_earlydata_accepted;
2190 }
2191 #endif /* WOLFSSL_EARLY_DATA */
2192 }
2193
2194 if((connssl->connecting_state == ssl_connect_done) ||
2195 (connssl->state == ssl_connection_deferred)) {
2196 *done = TRUE;
2197 }
2198
2199 out:
2200 if(result) {
2201 *done = FALSE;
2202 if(result == CURLE_AGAIN)
2203 return CURLE_OK;
2204 }
2205 else if((connssl->connecting_state == ssl_connect_done) ||
2206 (connssl->state == ssl_connection_deferred)) {
2207 *done = TRUE;
2208 }
2209 return result;
2210 }
2211
2212 static CURLcode wssl_random(struct Curl_easy *data,
2213 unsigned char *entropy, size_t length)
2214 {
2215 WC_RNG rng;
2216 (void)data;
2217 if(wc_InitRng(&rng))
2218 return CURLE_FAILED_INIT;
2219 if(length > UINT_MAX)
2220 return CURLE_FAILED_INIT;
2221 if(wc_RNG_GenerateBlock(&rng, entropy, (unsigned)length))
2222 return CURLE_FAILED_INIT;
2223 if(wc_FreeRng(&rng))
2224 return CURLE_FAILED_INIT;
2225 return CURLE_OK;
2226 }
2227
2228 static CURLcode wssl_sha256sum(const unsigned char *tmp, /* input */
2229 size_t tmplen,
2230 unsigned char *sha256sum /* output */,
2231 size_t unused)
2232 {
2233 wc_Sha256 SHA256pw;
2234 (void)unused;
2235 if(wc_InitSha256(&SHA256pw))
2236 return CURLE_FAILED_INIT;
2237 wc_Sha256Update(&SHA256pw, tmp, (word32)tmplen);
2238 wc_Sha256Final(&SHA256pw, sha256sum);
2239 return CURLE_OK;
2240 }
2241
2242 static void *wssl_get_internals(struct ssl_connect_data *connssl,
2243 CURLINFO info UNUSED_PARAM)
2244 {
2245 struct wssl_ctx *wssl = (struct wssl_ctx *)connssl->backend;
2246 (void)info;
2247 DEBUGASSERT(wssl);
2248 return wssl->ssl;
2249 }
2250
2251 const struct Curl_ssl Curl_ssl_wolfssl = {
2252 { CURLSSLBACKEND_WOLFSSL, "wolfssl" }, /* info */
2253
2254 #ifdef KEEP_PEER_CERT
2255 SSLSUPP_PINNEDPUBKEY |
2256 #endif
2257 #ifdef USE_BIO_CHAIN
2258 SSLSUPP_HTTPS_PROXY |
2259 #endif
2260 SSLSUPP_CA_PATH |
2261 SSLSUPP_CAINFO_BLOB |
2262 #ifdef USE_ECH_WOLFSSL
2263 SSLSUPP_ECH |
2264 #endif
2265 SSLSUPP_SSL_CTX |
2266 #ifdef WOLFSSL_TLS13
2267 SSLSUPP_TLS13_CIPHERSUITES |
2268 #endif
2269 SSLSUPP_CA_CACHE |
2270 SSLSUPP_CIPHER_LIST,
2271
2272 sizeof(struct wssl_ctx),
2273
2274 wssl_init, /* init */
2275 wssl_cleanup, /* cleanup */
2276 Curl_wssl_version, /* version */
2277 wssl_shutdown, /* shutdown */
2278 wssl_data_pending, /* data_pending */
2279 wssl_random, /* random */
2280 NULL, /* cert_status_request */
2281 wssl_connect, /* connect */
2282 Curl_ssl_adjust_pollset, /* adjust_pollset */
2283 wssl_get_internals, /* get_internals */
2284 wssl_close, /* close_one */
2285 NULL, /* close_all */
2286 NULL, /* set_engine */
2287 NULL, /* set_engine_default */
2288 NULL, /* engines_list */
2289 NULL, /* false_start */
2290 wssl_sha256sum, /* sha256sum */
2291 wssl_recv, /* recv decrypted data */
2292 wssl_send, /* send data to encrypt */
2293 NULL, /* get_channel_binding */
2294 };
2295
2296 #endif