master
Showing 4000 of 5665 lines.
1/***************************************************************************
2 * _ _ ____ _
3 * Project ___| | | | _ \| |
4 * / __| | | | |_) | |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
7 *
8 * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, 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 * Source file for all OpenSSL-specific code for the TLS/SSL layer. No code
26 * but vtls.c should ever call or use these functions.
27 */
28#include "curl_setup.h"
30#ifdef USE_OPENSSL
32#include "urldata.h"
33#include "curl_trc.h"
34#include "formdata.h" /* for the boundary function */
35#include "url.h" /* for the SSL config check function */
36#include "curlx/inet_pton.h"
37#include "vtls/openssl.h"
38#include "connect.h"
39#include "progress.h"
40#include "vtls/vtls.h"
41#include "vtls/vtls_int.h"
42#include "vtls/vtls_scache.h"
43#include "vauth/vauth.h"
44#include "vtls/keylog.h"
45#include "vtls/hostcheck.h"
46#include "transfer.h"
47#include "multiif.h"
48#include "curlx/strerr.h"
49#include "curlx/strparse.h"
50#include "curlx/strcopy.h"
51#include "curlx/strdup.h"
52#include "vdns/cf-dns.h"
53#include "vdns/httpsrr.h"
54#include "vtls/apple.h"
55#ifdef USE_ECH
56#include "curlx/base64.h"
57#endif
59#include <openssl/rand.h>
60#include <openssl/x509v3.h>
61#ifndef OPENSSL_NO_DSA
62#include <openssl/dsa.h>
63#endif
64#include <openssl/dh.h>
65#include <openssl/err.h>
66#include <openssl/conf.h>
67#include <openssl/bn.h>
68#include <openssl/rsa.h>
69#include <openssl/bio.h>
70#include <openssl/pkcs12.h>
71#include <openssl/tls1.h>
72#include <openssl/evp.h>
74#if defined(HAVE_SSL_SET1_ECH_CONFIG_LIST) && !defined(HAVE_BORINGSSL_LIKE)
75#include <openssl/ech.h>
76#endif
78#ifndef OPENSSL_NO_OCSP
79#include <openssl/ocsp.h>
80#endif
82#if !defined(OPENSSL_NO_ENGINE) && !defined(OPENSSL_NO_UI_CONSOLE)
83#define USE_OPENSSL_ENGINE
84#include <openssl/engine.h>
85#endif
87#ifdef LIBRESSL_VERSION_NUMBER
88/* As of LibreSSL 2.0.0-4.0.0: OPENSSL_VERSION_NUMBER == 0x20000000L */
89# if LIBRESSL_VERSION_NUMBER < 0x3040100fL /* 2021-10-14 */
90# error "LibreSSL 3.4.1 or greater required"
91# endif
92#elif !defined(HAVE_BORINGSSL_LIKE)
93# ifndef HAVE_OPENSSL3 /* 2021-09-07 */
94# error "OpenSSL 3.0.0 or greater required"
95# endif
96#endif
98#if defined(HAVE_OPENSSL3) && !defined(OPENSSL_NO_UI_CONSOLE)
99#include <openssl/provider.h>
100#include <openssl/store.h>
101/* this is used in the following conditions to make them easier to read */
102#define OPENSSL_HAS_PROVIDERS
103#endif
105/* AWS-LC fixed a bug with large buffers in v1.61.0 which also introduced
106 * X509_V_ERR_EC_KEY_EXPLICIT_PARAMS. */
107#if !defined(LIBRESSL_VERSION_NUMBER) && !defined(OPENSSL_IS_BORINGSSL) && \
108 (!defined(OPENSSL_IS_AWSLC) || defined(X509_V_ERR_EC_KEY_EXPLICIT_PARAMS))
109#define HAVE_SSL_CTX_SET_DEFAULT_READ_BUFFER_LEN 1
110#endif
112#if defined(USE_OPENSSL_ENGINE) || defined(OPENSSL_HAS_PROVIDERS)
113#include <openssl/ui.h>
114#endif
116#ifdef HAVE_OPENSSL3
117#define HAVE_EVP_PKEY_GET_PARAMS 1
118#endif
120#ifdef HAVE_EVP_PKEY_GET_PARAMS
121#include <openssl/core_names.h>
122#define DECLARE_PKEY_PARAM_BIGNUM(name) BIGNUM *name = NULL
123#define FREE_PKEY_PARAM_BIGNUM(name) BN_clear_free(name)
124#else
125#define DECLARE_PKEY_PARAM_BIGNUM(name) const BIGNUM *name
126#define FREE_PKEY_PARAM_BIGNUM(name)
127#endif
129/* Whether SSL_CTX_set_ciphersuites is available.
130 * BoringSSL: no
131 * LibreSSL: supported since 3.4.1 (released 2021-10-14)
132 * OpenSSL: supported since 1.1.1 (commit a53b5be6a05)
133 */
134#ifndef OPENSSL_IS_BORINGSSL
135# define HAVE_SSL_CTX_SET_CIPHERSUITES
136# ifndef OPENSSL_IS_AWSLC
137# define HAVE_SSL_CTX_SET_POST_HANDSHAKE_AUTH
138# endif
139#endif
141/* Whether SSL_CTX_set1_sigalgs_list is available
142 * BoringSSL: supported since 0.20240913.0 (commit 826ce15)
143 * LibreSSL: no
144 * OpenSSL: supported since 1.0.2 (commit 0b362de5f575)
145 */
146#ifndef LIBRESSL_VERSION_NUMBER
147#define HAVE_SSL_CTX_SET1_SIGALGS
148#endif
150#ifdef LIBRESSL_VERSION_NUMBER
151#define OSSL_PACKAGE "LibreSSL"
152#elif defined(OPENSSL_IS_AWSLC)
153#define OSSL_PACKAGE "AWS-LC"
154#elif defined(OPENSSL_IS_BORINGSSL)
155#define OSSL_PACKAGE "BoringSSL"
156#elif defined(USE_NGTCP2) && defined(USE_NGHTTP3) && \
157 !defined(OPENSSL_QUIC_API2)
158#define OSSL_PACKAGE "quictls"
159#else
160#define OSSL_PACKAGE "OpenSSL"
161#endif
163#ifdef HAVE_BORINGSSL_LIKE
164typedef size_t numcert_t;
165typedef uint32_t sslerr_t;
166#else
167typedef int numcert_t;
168typedef unsigned long sslerr_t;
169#endif
170#define ossl_valsize_t numcert_t
172#if OPENSSL_VERSION_NUMBER >= 0x40100000L
173#define ossl_ASN1_STRING_get_length ASN1_STRING_get_length
174#else
175static size_t ossl_ASN1_STRING_get_length(const ASN1_STRING *str)
176{
177 const int length = ASN1_STRING_length(str);
178 return length >= 0 ? (size_t)length : 0;
179}
180#endif
182static CURLcode push_certinfo(struct Curl_easy *data,
183 BIO *mem, const char *label, int num)
184 WARN_UNUSED_RESULT;
186static CURLcode push_certinfo(struct Curl_easy *data,
187 BIO *mem, const char *label, int num)
188{
189 char *ptr;
190 long len = BIO_get_mem_data(mem, &ptr);
191 CURLcode result = Curl_ssl_push_certinfo_len(data, num, label, ptr, len);
192 (void)BIO_reset(mem);
193 return result;
194}
196static CURLcode pubkey_show(struct Curl_easy *data,
197 BIO *mem,
198 int num,
199 const char *type,
200 const char *name,
201 const BIGNUM *bn) WARN_UNUSED_RESULT;
203static CURLcode pubkey_show(struct Curl_easy *data,
204 BIO *mem,
205 int num,
206 const char *type,
207 const char *name,
208 const BIGNUM *bn)
209{
210 char namebuf[32];
212 curl_msnprintf(namebuf, sizeof(namebuf), "%s(%s)", type, name);
214 if(bn)
215 BN_print(mem, bn);
216 return push_certinfo(data, mem, namebuf, num);
217}
219#define print_pubkey_BN(_type, _name, _num) \
220 pubkey_show(data, mem, _num, #_type, #_name, _name)
222static int asn1_object_dump(const ASN1_OBJECT *a, char *buf, size_t len)
223{
224 int i = i2t_ASN1_OBJECT(buf, (int)len, a);
225 return (i >= (int)len); /* buffer too small */
226}
228static CURLcode X509V3_ext(struct Curl_easy *data,
229 int certnum,
230 const STACK_OF(X509_EXTENSION) *extsarg)
231{
232 int i;
233 CURLcode result = CURLE_OK;
234#ifdef LIBRESSL_VERSION_NUMBER
235 STACK_OF(X509_EXTENSION) *exts = CURL_UNCONST(extsarg);
236#else
237 const STACK_OF(X509_EXTENSION) *exts = extsarg;
238#endif
240 if((int)sk_X509_EXTENSION_num(exts) <= 0)
241 /* no extensions, bail out */
242 return result;
244 for(i = 0; i < (int)sk_X509_EXTENSION_num(exts); i++) {
245 const ASN1_OBJECT *obj;
246 X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, (ossl_valsize_t)i);
247 BUF_MEM *biomem;
248 char namebuf[128];
249 BIO *bio_out = BIO_new(BIO_s_mem());
251 if(!bio_out)
252 return result;
254 obj = X509_EXTENSION_get_object(ext);
256 if(asn1_object_dump(obj, namebuf, sizeof(namebuf)))
257 /* make sure the name is null-terminated */
258 namebuf[CURL_CSTRLEN(namebuf)] = 0;
260 if(!X509V3_EXT_print(bio_out, ext, 0, 0))
261 ASN1_STRING_print(bio_out,
262 (const ASN1_STRING *)X509_EXTENSION_get_data(ext));
264 BIO_get_mem_ptr(bio_out, &biomem);
265 result = Curl_ssl_push_certinfo_len(data, certnum, namebuf, biomem->data,
266 biomem->length);
267 BIO_free(bio_out);
268 if(result)
269 break;
270 }
271 return result;
272}
274static CURLcode get_pkey_rsa(struct Curl_easy *data,
275 EVP_PKEY *pubkey, BIO *mem, int i)
276{
277 CURLcode result = CURLE_OK;
278#ifndef HAVE_EVP_PKEY_GET_PARAMS
279 RSA *rsa = EVP_PKEY_get0_RSA(pubkey);
280#endif /* !HAVE_EVP_PKEY_GET_PARAMS */
281 DECLARE_PKEY_PARAM_BIGNUM(n);
282 DECLARE_PKEY_PARAM_BIGNUM(e);
283#ifdef HAVE_EVP_PKEY_GET_PARAMS
284 EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_RSA_N, &n);
285 EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_RSA_E, &e);
286#else
287 RSA_get0_key(rsa, &n, &e, NULL);
288#endif /* HAVE_EVP_PKEY_GET_PARAMS */
289 BIO_printf(mem, "%d", (int)(n ? BN_num_bits(n) : 0));
290 result = push_certinfo(data, mem, "RSA Public Key", i);
291 if(!result) {
292 result = print_pubkey_BN(rsa, n, i);
293 if(!result)
294 result = print_pubkey_BN(rsa, e, i);
295 }
296 FREE_PKEY_PARAM_BIGNUM(n);
297 FREE_PKEY_PARAM_BIGNUM(e);
298 return result;
299}
301#ifndef OPENSSL_NO_DSA
302static CURLcode get_pkey_dsa(struct Curl_easy *data,
303 EVP_PKEY *pubkey, BIO *mem, int i)
304{
305 CURLcode result = CURLE_OK;
306#ifndef HAVE_EVP_PKEY_GET_PARAMS
307 DSA *dsa = EVP_PKEY_get0_DSA(pubkey);
308#endif /* !HAVE_EVP_PKEY_GET_PARAMS */
309 DECLARE_PKEY_PARAM_BIGNUM(p);
310 DECLARE_PKEY_PARAM_BIGNUM(q);
311 DECLARE_PKEY_PARAM_BIGNUM(g);
312 DECLARE_PKEY_PARAM_BIGNUM(pub_key);
313#ifdef HAVE_EVP_PKEY_GET_PARAMS
314 EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_FFC_P, &p);
315 EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_FFC_Q, &q);
316 EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_FFC_G, &g);
317 EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_PUB_KEY, &pub_key);
318#else
319 DSA_get0_pqg(dsa, &p, &q, &g);
320 DSA_get0_key(dsa, &pub_key, NULL);
321#endif /* HAVE_EVP_PKEY_GET_PARAMS */
322 result = print_pubkey_BN(dsa, p, i);
323 if(!result)
324 result = print_pubkey_BN(dsa, q, i);
325 if(!result)
326 result = print_pubkey_BN(dsa, g, i);
327 if(!result)
328 result = print_pubkey_BN(dsa, pub_key, i);
329 FREE_PKEY_PARAM_BIGNUM(p);
330 FREE_PKEY_PARAM_BIGNUM(q);
331 FREE_PKEY_PARAM_BIGNUM(g);
332 FREE_PKEY_PARAM_BIGNUM(pub_key);
333 return result;
334}
335#endif /* !OPENSSL_NO_DSA */
337static CURLcode get_pkey_dh(struct Curl_easy *data,
338 EVP_PKEY *pubkey, BIO *mem, int i)
339{
340 CURLcode result;
341#ifndef HAVE_EVP_PKEY_GET_PARAMS
342 DH *dh = EVP_PKEY_get0_DH(pubkey);
343#endif /* !HAVE_EVP_PKEY_GET_PARAMS */
344 DECLARE_PKEY_PARAM_BIGNUM(p);
345 DECLARE_PKEY_PARAM_BIGNUM(q);
346 DECLARE_PKEY_PARAM_BIGNUM(g);
347 DECLARE_PKEY_PARAM_BIGNUM(pub_key);
348#ifdef HAVE_EVP_PKEY_GET_PARAMS
349 EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_FFC_P, &p);
350 EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_FFC_Q, &q);
351 EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_FFC_G, &g);
352 EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_PUB_KEY, &pub_key);
353#else
354 DH_get0_pqg(dh, &p, &q, &g);
355 DH_get0_key(dh, &pub_key, NULL);
356#endif /* HAVE_EVP_PKEY_GET_PARAMS */
357 result = print_pubkey_BN(dh, p, i);
358 if(!result)
359 result = print_pubkey_BN(dh, q, i);
360 if(!result)
361 result = print_pubkey_BN(dh, g, i);
362 if(!result)
363 result = print_pubkey_BN(dh, pub_key, i);
364 FREE_PKEY_PARAM_BIGNUM(p);
365 FREE_PKEY_PARAM_BIGNUM(q);
366 FREE_PKEY_PARAM_BIGNUM(g);
367 FREE_PKEY_PARAM_BIGNUM(pub_key);
368 return result;
369}
371#ifdef HAVE_OPENSSL3
372/* from OpenSSL commit fc756e594ed5a27af378 */
373typedef const X509_PUBKEY pubkeytype_t;
374#else
375typedef X509_PUBKEY pubkeytype_t;
376#endif
378static CURLcode ossl_certchain(struct Curl_easy *data, SSL *ssl)
379{
380 CURLcode result;
381 STACK_OF(X509) *sk;
382 int i;
383 numcert_t numcerts;
384 BIO *mem;
386 DEBUGASSERT(ssl);
388 sk = SSL_get_peer_cert_chain(ssl);
389 if(!sk)
390 return CURLE_SSL_CONNECT_ERROR;
392 numcerts = sk_X509_num(sk);
393 if(numcerts > MAX_ALLOWED_CERT_AMOUNT) {
394 failf(data, "%d certificates is more than allowed (%d)", (int)numcerts,
395 MAX_ALLOWED_CERT_AMOUNT);
396 return CURLE_SSL_CONNECT_ERROR;
397 }
399 result = Curl_ssl_init_certinfo(data, (int)numcerts);
400 if(result)
401 return result;
403 mem = BIO_new(BIO_s_mem());
404 if(!mem)
405 result = CURLE_OUT_OF_MEMORY;
407 for(i = 0; !result && (i < (int)numcerts); i++) {
408 X509 *x = sk_X509_value(sk, (ossl_valsize_t)i);
409 EVP_PKEY *pubkey = NULL;
410 size_t j;
411 const ASN1_BIT_STRING *psig = NULL;
413 X509_NAME_print_ex(mem, X509_get_subject_name(x), 0, XN_FLAG_ONELINE);
414 result = push_certinfo(data, mem, "Subject", i);
415 if(result)
416 break;
418 X509_NAME_print_ex(mem, X509_get_issuer_name(x), 0, XN_FLAG_ONELINE);
419 result = push_certinfo(data, mem, "Issuer", i);
420 if(result)
421 break;
423 BIO_printf(mem, "%lx", (unsigned long)X509_get_version(x));
424 result = push_certinfo(data, mem, "Version", i);
425 if(result)
426 break;
428 {
429 ASN1_INTEGER *num = X509_get_serialNumber(x);
430 const unsigned char *numdata = ASN1_STRING_get0_data(num);
431 const size_t numlen = ossl_ASN1_STRING_get_length(num);
432 if(ASN1_STRING_type(num) == V_ASN1_NEG_INTEGER)
433 BIO_puts(mem, "-");
434 for(j = 0; j < numlen; j++)
435 BIO_printf(mem, "%02x", numdata[j]);
436 }
437 result = push_certinfo(data, mem, "Serial Number", i);
438 if(result)
439 break;
441 {
442 const X509_ALGOR *sigalg = NULL;
443 pubkeytype_t *xpubkey = NULL;
444 ASN1_OBJECT *pubkeyoid = NULL;
446 X509_get0_signature(&psig, &sigalg, x);
447 if(sigalg) {
448 const ASN1_OBJECT *sigalgoid = NULL;
449 X509_ALGOR_get0(&sigalgoid, NULL, NULL, sigalg);
450 i2a_ASN1_OBJECT(mem, sigalgoid);
451 result = push_certinfo(data, mem, "Signature Algorithm", i);
452 if(result)
453 break;
454 }
456 xpubkey = X509_get_X509_PUBKEY(x);
457 if(xpubkey) {
458 X509_PUBKEY_get0_param(&pubkeyoid, NULL, NULL, NULL, xpubkey);
459 if(pubkeyoid) {
460 i2a_ASN1_OBJECT(mem, pubkeyoid);
461 result = push_certinfo(data, mem, "Public Key Algorithm", i);
462 if(result)
463 break;
464 }
465 }
467 result = X509V3_ext(data, i, X509_get0_extensions(x));
468 if(result)
469 break;
470 }
472 ASN1_TIME_print(mem, X509_get0_notBefore(x));
473 result = push_certinfo(data, mem, "Start date", i);
474 if(result)
475 break;
477 ASN1_TIME_print(mem, X509_get0_notAfter(x));
478 result = push_certinfo(data, mem, "Expire date", i);
479 if(result)
480 break;
482 pubkey = X509_get_pubkey(x);
483 if(!pubkey)
484 infof(data, " Unable to load public key");
485 else {
486 switch(EVP_PKEY_id(pubkey)) {
487 case EVP_PKEY_RSA:
488 result = get_pkey_rsa(data, pubkey, mem, i);
489 break;
491#ifndef OPENSSL_NO_DSA
492 case EVP_PKEY_DSA:
493 result = get_pkey_dsa(data, pubkey, mem, i);
494 break;
495#endif
497 case EVP_PKEY_DH:
498 result = get_pkey_dh(data, pubkey, mem, i);
499 break;
500 }
501 EVP_PKEY_free(pubkey);
502 }
504 if(!result && psig) {
505 const unsigned char *psigdata = ASN1_STRING_get0_data(psig);
506 const size_t psiglen = ossl_ASN1_STRING_get_length(psig);
507 for(j = 0; j < psiglen; j++)
508 BIO_printf(mem, "%02x:", psigdata[j]);
509 result = push_certinfo(data, mem, "Signature", i);
510 }
512 if(!result) {
513 PEM_write_bio_X509(mem, x);
514 result = push_certinfo(data, mem, "Cert", i);
515 }
516 }
518 BIO_free(mem);
520 if(result)
521 /* cleanup all leftovers */
522 Curl_ssl_free_certinfo(data);
524 return result;
525}
527static int ossl_bio_cf_create(BIO *bio)
528{
529 BIO_set_shutdown(bio, 1);
530 BIO_set_init(bio, 1);
531 BIO_set_data(bio, NULL);
532 return 1;
533}
535static int ossl_bio_cf_destroy(BIO *bio)
536{
537 if(!bio)
538 return 0;
539 return 1;
540}
542static long ossl_bio_cf_ctrl(BIO *bio, int cmd, long num, void *ptr)
543{
544 struct Curl_cfilter *cf = BIO_get_data(bio);
545 long ret = 1;
547 (void)cf;
548 (void)ptr;
549 switch(cmd) {
550 case BIO_CTRL_GET_CLOSE:
551 ret = (long)BIO_get_shutdown(bio);
552 break;
553 case BIO_CTRL_SET_CLOSE:
554 BIO_set_shutdown(bio, (int)num);
555 break;
556 case BIO_CTRL_FLUSH:
557 /* we do no delayed writes, but if we ever would, this
558 * needs to trigger it. */
559 ret = 1;
560 break;
561 case BIO_CTRL_DUP:
562 ret = 1;
563 break;
564 case BIO_CTRL_EOF: {
565 /* EOF has been reached on input? */
566 struct ssl_connect_data *connssl = cf->ctx;
567 return connssl->peer_closed;
568 }
569 default:
570 ret = 0;
571 break;
572 }
573 return ret;
574}
576static int ossl_bio_cf_out_write(BIO *bio, const char *buf, int blen)
577{
578 struct Curl_cfilter *cf = BIO_get_data(bio);
579 struct ssl_connect_data *connssl = cf->ctx;
580 struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend;
581 struct Curl_easy *data = CF_DATA_CURRENT(cf);
582 size_t nwritten;
583 CURLcode result;
585 DEBUGASSERT(data);
586 if(blen < 0)
587 return 0;
589 result = Curl_conn_cf_send(cf->next, data,
590 (const uint8_t *)buf, (size_t)blen, FALSE,
591 &nwritten);
592 CURL_TRC_CF(data, cf, "ossl_bio_cf_out_write(len=%d) -> %d, %zu",
593 blen, (int)result, nwritten);
594 BIO_clear_retry_flags(bio);
595 octx->io_result = result;
596 if(result) {
597 if(result == CURLE_AGAIN)
598 BIO_set_retry_write(bio);
599 return -1;
600 }
601 return (int)nwritten;
602}
604static int ossl_bio_cf_in_read(BIO *bio, char *buf, int blen)
605{
606 struct Curl_cfilter *cf = BIO_get_data(bio);
607 struct ssl_connect_data *connssl = cf->ctx;
608 struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend;
609 struct Curl_easy *data = CF_DATA_CURRENT(cf);
610 size_t nread;
611 CURLcode result, r2;
613 DEBUGASSERT(data);
614 /* OpenSSL catches this case, so should we. */
615 if(!buf)
616 return 0;
617 if(blen < 0)
618 return 0;
620 result = Curl_conn_cf_recv(cf->next, data, buf, (size_t)blen, &nread);
621 CURL_TRC_CF(data, cf, "ossl_bio_cf_in_read(len=%d) -> %d, %zu",
622 blen, (int)result, nread);
623 BIO_clear_retry_flags(bio);
624 octx->io_result = result;
625 if(result) {
626 if(result == CURLE_AGAIN)
627 BIO_set_retry_read(bio);
628 }
629 else {
630 /* feeding data to OpenSSL means SSL_read() might succeed */
631 connssl->input_pending = TRUE;
632 if(nread == 0)
633 connssl->peer_closed = TRUE;
634 }
636 /* Before returning server replies to the SSL instance, we need
637 * to have setup the x509 store or verification fails. */
638 if(!octx->x509_store_setup) {
639 r2 = Curl_ssl_setup_x509_store(cf, data, octx);
640 if(r2) {
641 BIO_clear_retry_flags(bio);
642 octx->io_result = r2;
643 return -1;
644 }
645 octx->x509_store_setup = TRUE;
646 }
647 return result ? -1 : (int)nread;
648}
650static BIO_METHOD *ossl_bio_cf_method_create(void)
651{
652 BIO_METHOD *m = BIO_meth_new(BIO_TYPE_MEM, "OpenSSL CF BIO");
653 if(m) {
654 BIO_meth_set_write(m, &ossl_bio_cf_out_write);
655 BIO_meth_set_read(m, &ossl_bio_cf_in_read);
656 BIO_meth_set_ctrl(m, &ossl_bio_cf_ctrl);
657 BIO_meth_set_create(m, &ossl_bio_cf_create);
658 BIO_meth_set_destroy(m, &ossl_bio_cf_destroy);
659 }
660 return m;
661}
663static void ossl_bio_cf_method_free(BIO_METHOD *m)
664{
665 if(m)
666 BIO_meth_free(m);
667}
669#ifndef HAVE_KEYLOG_UPSTREAM
670#ifdef HAVE_KEYLOG_CALLBACK
671static void ossl_keylog_callback(const SSL *ssl, const char *line)
672{
673 (void)ssl;
675 Curl_tls_keylog_write_line(line);
676}
677#else
678/*
679 * ossl_log_tls12_secret is called by libcurl to make the CLIENT_RANDOMs if the
680 * OpenSSL being used does not have native support for doing that.
681 */
682static void ossl_log_tls12_secret(const SSL *ssl, bool *keylog_done)
683{
684 const SSL_SESSION *session;
685 unsigned char client_random[SSL3_RANDOM_SIZE];
686 unsigned char master_key[SSL_MAX_MASTER_KEY_LENGTH];
687 int master_key_length = 0;
689 ERR_set_mark();
691 session = SSL_get_session(ssl);
693 if(!session || *keylog_done) {
694 ERR_pop_to_mark();
695 return;
696 }
698 SSL_get_client_random(ssl, client_random, SSL3_RANDOM_SIZE);
699 master_key_length = (int)
700 SSL_SESSION_get_master_key(session, master_key, SSL_MAX_MASTER_KEY_LENGTH);
702 ERR_pop_to_mark();
704 /* The handshake has not progressed sufficiently yet, or this is a TLS 1.3
705 * session (when curl was built with older OpenSSL headers and running with
706 * newer OpenSSL runtime libraries). */
707 if(master_key_length <= 0)
708 return;
710 *keylog_done = TRUE;
711 Curl_tls_keylog_write("CLIENT_RANDOM", client_random,
712 sizeof(client_random),
713 master_key, master_key_length);
714}
715#endif /* !HAVE_KEYLOG_CALLBACK */
716#endif /* HAVE_KEYLOG_UPSTREAM */
718static const char *SSL_ERROR_to_str(int err)
719{
720 switch(err) {
721 case SSL_ERROR_NONE:
722 return "SSL_ERROR_NONE";
723 case SSL_ERROR_SSL:
724 return "SSL_ERROR_SSL";
725 case SSL_ERROR_WANT_READ:
726 return "SSL_ERROR_WANT_READ";
727 case SSL_ERROR_WANT_WRITE:
728 return "SSL_ERROR_WANT_WRITE";
729 case SSL_ERROR_WANT_X509_LOOKUP:
730 return "SSL_ERROR_WANT_X509_LOOKUP";
731 case SSL_ERROR_SYSCALL:
732 return "SSL_ERROR_SYSCALL";
733 case SSL_ERROR_ZERO_RETURN:
734 return "SSL_ERROR_ZERO_RETURN";
735 case SSL_ERROR_WANT_CONNECT:
736 return "SSL_ERROR_WANT_CONNECT";
737 case SSL_ERROR_WANT_ACCEPT:
738 return "SSL_ERROR_WANT_ACCEPT";
739#ifdef SSL_ERROR_WANT_ASYNC /* OpenSSL 1.1.0+, LibreSSL 3.6.0+ */
740 case SSL_ERROR_WANT_ASYNC:
741 return "SSL_ERROR_WANT_ASYNC";
742#endif
743#ifdef SSL_ERROR_WANT_ASYNC_JOB /* OpenSSL 1.1.0+, LibreSSL 3.6.0+ */
744 case SSL_ERROR_WANT_ASYNC_JOB:
745 return "SSL_ERROR_WANT_ASYNC_JOB";
746#endif
747#ifdef SSL_ERROR_WANT_CLIENT_HELLO_CB /* OpenSSL 1.1.1, LibreSSL 3.6.0+ */
748 case SSL_ERROR_WANT_CLIENT_HELLO_CB:
749 return "SSL_ERROR_WANT_CLIENT_HELLO_CB";
750#endif
751 default:
752 return "SSL_ERROR unknown";
753 }
754}
756/* Return error string for last OpenSSL error
757 */
758static char *ossl_strerror(unsigned long error, char *buf, size_t size)
759{
760 size_t len;
761 DEBUGASSERT(size);
762 *buf = '\0';
764 len = Curl_ossl_version(buf, size);
765 DEBUGASSERT(len < (size - 2));
766 if(len < (size - 2)) {
767 buf += len;
768 size -= (len + 2);
769 *buf++ = ':';
770 *buf++ = ' ';
771 *buf = '\0';
772 }
774#ifdef HAVE_BORINGSSL_LIKE
775 ERR_error_string_n((uint32_t)error, buf, size);
776#else
777 ERR_error_string_n(error, buf, size);
778#endif
780 if(!*buf) {
781 const char *msg = error ? "Unknown error" : "No error";
782 curlx_strcopy(buf, size, msg, strlen(msg));
783 }
785 return buf;
786}
788static int passwd_callback(char *buf, int num, int encrypting, void *password)
789{
790 DEBUGASSERT(encrypting == 0);
792 if(!encrypting && num >= 0 && password) {
793 int klen = curlx_uztosi(strlen((char *)password));
794 if(num > klen) {
795 memcpy(buf, password, klen + 1);
796 return klen;
797 }
798 }
799 return 0;
800}
802/*
803 * rand_enough() returns TRUE if we have seeded the random engine properly.
804 */
805static bool rand_enough(void)
806{
807 return RAND_status() != 0;
808}
810static CURLcode ossl_seed(struct Curl_easy *data)
811{
812 /* This might get called before it has been added to a multi handle */
813 if(data->multi && data->multi->ssl_seeded)
814 return CURLE_OK;
816 if(rand_enough()) {
817 /* OpenSSL 1.1.0+ should return here */
818 if(data->multi)
819 data->multi->ssl_seeded = TRUE;
820 return CURLE_OK;
821 }
822 failf(data, "Insufficient randomness");
823 return CURLE_SSL_CONNECT_ERROR;
824}
826#ifndef SSL_FILETYPE_ENGINE
827#define SSL_FILETYPE_ENGINE 42
828#endif
829#ifndef SSL_FILETYPE_PKCS12
830#define SSL_FILETYPE_PKCS12 43
831#endif
832#ifndef SSL_FILETYPE_PROVIDER
833#define SSL_FILETYPE_PROVIDER 44
834#endif
835static int ossl_do_file_type(const char *type)
836{
837 if(!type || !type[0])
838 return SSL_FILETYPE_PEM;
839 if(curl_strequal(type, "PEM"))
840 return SSL_FILETYPE_PEM;
841 if(curl_strequal(type, "DER"))
842 return SSL_FILETYPE_ASN1;
843 if(curl_strequal(type, "PROV"))
844 return SSL_FILETYPE_PROVIDER;
845 if(curl_strequal(type, "ENG"))
846 return SSL_FILETYPE_ENGINE;
847 if(curl_strequal(type, "P12"))
848 return SSL_FILETYPE_PKCS12;
849 return -1;
850}
852#if defined(USE_OPENSSL_ENGINE) || defined(OPENSSL_HAS_PROVIDERS)
853/*
854 * Supply default password to the engine user interface conversation.
855 * The password is passed by OpenSSL engine from ENGINE_load_private_key()
856 * last argument to the ui and can be obtained by UI_get0_user_data(ui) here.
857 */
858static int ssl_ui_reader(UI *ui, UI_STRING *uis)
859{
860 const char *password;
861 switch(UI_get_string_type(uis)) {
862 case UIT_PROMPT:
863 case UIT_VERIFY:
864 password = (const char *)UI_get0_user_data(ui);
865 if(password && (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD)) {
866 UI_set_result(ui, uis, password);
867 return 1;
868 }
869 FALLTHROUGH();
870 default:
871 break;
872 }
873 return UI_method_get_reader(UI_OpenSSL())(ui, uis);
874}
876/*
877 * Suppress interactive request for a default password if available.
878 */
879static int ssl_ui_writer(UI *ui, UI_STRING *uis)
880{
881 switch(UI_get_string_type(uis)) {
882 case UIT_PROMPT:
883 case UIT_VERIFY:
884 if(UI_get0_user_data(ui) &&
885 (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD)) {
886 return 1;
887 }
888 FALLTHROUGH();
889 default:
890 break;
891 }
892 return UI_method_get_writer(UI_OpenSSL())(ui, uis);
893}
895/*
896 * Check if a given string is a PKCS#11 URI
897 */
898static bool is_pkcs11_uri(const char *string)
899{
900 return string && curl_strnequal(string, "pkcs11:", 7);
901}
903#endif
905static CURLcode ossl_set_engine(struct Curl_easy *data, struct ossl_ctx *octx,
906 const char *name);
907#ifdef OPENSSL_HAS_PROVIDERS
908static CURLcode ossl_set_provider(struct Curl_easy *data,
909 struct ossl_ctx *octx,
910 const char *iname);
911#endif
913static int use_certificate_blob(SSL_CTX *ctx, const struct curl_blob *blob,
914 int type, const char *key_passwd)
915{
916 int ret = 0;
917 X509 *x = NULL;
918 /* the typecast of blob->len is fine since it is guaranteed to never be
919 larger than CURL_MAX_INPUT_LENGTH */
920 BIO *in = BIO_new_mem_buf(blob->data, (int)blob->len);
921 if(!in)
922 return CURLE_OUT_OF_MEMORY;
924 if(type == SSL_FILETYPE_ASN1) {
925 /* j = ERR_R_ASN1_LIB; */
926 x = d2i_X509_bio(in, NULL);
927 }
928 else if(type == SSL_FILETYPE_PEM) {
929 /* ERR_R_PEM_LIB; */
930 x = PEM_read_bio_X509(in, NULL, passwd_callback, CURL_UNCONST(key_passwd));
931 }
932 else {
933 ret = 0;
934 goto end;
935 }
937 if(!x) {
938 ret = 0;
939 goto end;
940 }
942 ret = SSL_CTX_use_certificate(ctx, x);
943end:
944 X509_free(x);
945 BIO_free(in);
946 return ret;
947}
949static int use_privatekey_blob(SSL_CTX *ctx, const struct curl_blob *blob,
950 int type, const char *key_passwd)
951{
952 int ret = 0;
953 EVP_PKEY *pkey = NULL;
954 BIO *in = BIO_new_mem_buf(blob->data, (int)blob->len);
955 if(!in)
956 return CURLE_OUT_OF_MEMORY;
958 if(type == SSL_FILETYPE_PEM)
959 pkey = PEM_read_bio_PrivateKey(in, NULL, passwd_callback,
960 CURL_UNCONST(key_passwd));
961 else if(type == SSL_FILETYPE_ASN1)
962 pkey = d2i_PrivateKey_bio(in, NULL);
963 else
964 goto end;
966 if(!pkey)
967 goto end;
969 ret = SSL_CTX_use_PrivateKey(ctx, pkey);
970 EVP_PKEY_free(pkey);
971end:
972 BIO_free(in);
973 return ret;
974}
976static int use_certificate_chain_blob(SSL_CTX *ctx,
977 const struct curl_blob *blob,
978 const char *key_passwd)
979{
980 int ret = 0;
981 X509 *x = NULL;
982 BIO *in = BIO_new_mem_buf(blob->data, (int)blob->len);
983 if(!in)
984 return CURLE_OUT_OF_MEMORY;
986 ERR_clear_error();
988 x = PEM_read_bio_X509_AUX(in, NULL,
989 passwd_callback, CURL_UNCONST(key_passwd));
990 if(!x)
991 goto end;
993 ret = SSL_CTX_use_certificate(ctx, x);
995 if(ERR_peek_error() != 0)
996 ret = 0;
998 if(ret) {
999 X509 *ca;
1000 sslerr_t err;
1002 if(!SSL_CTX_clear_chain_certs(ctx)) {
1003 ret = 0;
1004 goto end;
1005 }
1007 while((ca = PEM_read_bio_X509(in, NULL, passwd_callback,
1008 CURL_UNCONST(key_passwd))) != NULL) {
1010 if(!SSL_CTX_add0_chain_cert(ctx, ca)) {
1011 X509_free(ca);
1012 ret = 0;
1013 goto end;
1014 }
1015 }
1017 err = ERR_peek_last_error();
1018 if((ERR_GET_LIB(err) == ERR_LIB_PEM) &&
1019 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE))
1020 ERR_clear_error();
1021 else
1022 ret = 0;
1023 }
1025end:
1026 X509_free(x);
1027 BIO_free(in);
1028 return ret;
1029}
1031static int enginecheck(struct Curl_easy *data,
1032 struct ossl_ctx *octx,
1033 const char *key_file,
1034 const char *key_passwd)
1035{
1036#ifdef USE_OPENSSL_ENGINE
1037 EVP_PKEY *priv_key = NULL;
1038 SSL_CTX *ctx = octx->ssl_ctx;
1040 /* Implicitly use pkcs11 engine if none was provided and the
1041 * key_file is a PKCS#11 URI */
1042 if(!octx->p.engine && is_pkcs11_uri(key_file) &&
1043 ossl_set_engine(data, octx, "pkcs11") != CURLE_OK)
1044 return 0;
1046 if(octx->p.engine) {
1047 UI_METHOD *ui_method = UI_create_method("curl user interface");
1048 if(!ui_method) {
1049 failf(data, "unable to create " OSSL_PACKAGE " user-interface method");
1050 return 0;
1051 }
1052 UI_method_set_opener(ui_method, UI_method_get_opener(UI_OpenSSL()));
1053 UI_method_set_closer(ui_method, UI_method_get_closer(UI_OpenSSL()));
1054 UI_method_set_reader(ui_method, ssl_ui_reader);
1055 UI_method_set_writer(ui_method, ssl_ui_writer);
1056 priv_key = ENGINE_load_private_key(octx->p.engine, key_file,
1057 ui_method,
1058 CURL_UNCONST(key_passwd));
1059 UI_destroy_method(ui_method);
1060 if(!priv_key) {
1061 failf(data, "failed to load private key from crypto engine");
1062 return 0;
1063 }
1064 if(SSL_CTX_use_PrivateKey(ctx, priv_key) != 1) {
1065 failf(data, "unable to set private key");
1066 EVP_PKEY_free(priv_key);
1067 return 0;
1068 }
1069 EVP_PKEY_free(priv_key); /* we do not need the handle any more... */
1070 }
1071 else {
1072 failf(data, "crypto engine not set, cannot load private key");
1073 return 0;
1074 }
1075 return 1;
1076#else
1077 (void)octx;
1078 (void)key_file;
1079 (void)key_passwd;
1080 failf(data, "SSL_FILETYPE_ENGINE not supported for private key");
1081 return 0;
1082#endif
1083}
1085static int providercheck(struct Curl_easy *data,
1086 struct ossl_ctx *octx,
1087 const char *key_file)
1088{
1089#ifdef OPENSSL_HAS_PROVIDERS
1090 char error_buffer[256];
1091 SSL_CTX *ctx = octx->ssl_ctx;
1093 /* Implicitly use pkcs11 provider if none was provided and the
1094 * key_file is a PKCS#11 URI */
1095 if(!octx->p.provider_loaded && is_pkcs11_uri(key_file) &&
1096 ossl_set_provider(data, octx, "pkcs11") != CURLE_OK) {
1097 return 0;
1098 }
1100 if(octx->p.provider_loaded) {
1101 /* Load the private key from the provider */
1102 EVP_PKEY *priv_key = NULL;
1103 OSSL_STORE_CTX *store = NULL;
1104 OSSL_STORE_INFO *info = NULL;
1105 UI_METHOD *ui_method = UI_create_method("curl user interface");
1106 if(!ui_method) {
1107 failf(data, "unable to create " OSSL_PACKAGE " user-interface method");
1108 return 0;
1109 }
1110 UI_method_set_opener(ui_method, UI_method_get_opener(UI_OpenSSL()));
1111 UI_method_set_closer(ui_method, UI_method_get_closer(UI_OpenSSL()));
1112 UI_method_set_reader(ui_method, ssl_ui_reader);
1113 UI_method_set_writer(ui_method, ssl_ui_writer);
1115 store = OSSL_STORE_open_ex(key_file, octx->p.libctx,
1116 octx->p.propq, ui_method, NULL, NULL,
1117 NULL, NULL);
1118 if(!store) {
1119 failf(data, "Failed to open OpenSSL store: %s",
1120 ossl_strerror(ERR_get_error(), error_buffer,
1121 sizeof(error_buffer)));
1122 UI_destroy_method(ui_method);
1123 return 0;
1124 }
1125 if(OSSL_STORE_expect(store, OSSL_STORE_INFO_PKEY) != 1) {
1126 failf(data, "Failed to set store preference. Ignoring the error: %s",
1127 ossl_strerror(ERR_get_error(), error_buffer,
1128 sizeof(error_buffer)));
1129 }
1131 info = OSSL_STORE_load(store);
1132 if(info) {
1133 int ossl_type = OSSL_STORE_INFO_get_type(info);
1135 if(ossl_type == OSSL_STORE_INFO_PKEY)
1136 priv_key = OSSL_STORE_INFO_get1_PKEY(info);
1137 OSSL_STORE_INFO_free(info);
1138 }
1139 OSSL_STORE_close(store);
1140 UI_destroy_method(ui_method);
1141 if(!priv_key) {
1142 failf(data, "No private key found in the openssl store: %s",
1143 ossl_strerror(ERR_get_error(), error_buffer,
1144 sizeof(error_buffer)));
1145 return 0;
1146 }
1148 if(SSL_CTX_use_PrivateKey(ctx, priv_key) != 1) {
1149 failf(data, "unable to set private key [%s]",
1150 ossl_strerror(ERR_get_error(), error_buffer,
1151 sizeof(error_buffer)));
1152 EVP_PKEY_free(priv_key);
1153 return 0;
1154 }
1155 EVP_PKEY_free(priv_key); /* we do not need the handle any more... */
1156 }
1157 else {
1158 failf(data, "crypto provider not set, cannot load private key");
1159 return 0;
1160 }
1161 return 1;
1162#else
1163 (void)octx;
1164 (void)key_file;
1165 failf(data, "SSL_FILETYPE_PROVIDER not supported for private key");
1166 return 0;
1167#endif
1168}
1170static int engineload(struct Curl_easy *data,
1171 struct ossl_ctx *octx,
1172 const char *cert_file)
1173{
1174/* ENGINE_CTRL_GET_CMD_FROM_NAME supported by OpenSSL, LibreSSL <=3.8.3 */
1175#if defined(USE_OPENSSL_ENGINE) && defined(ENGINE_CTRL_GET_CMD_FROM_NAME)
1176 char error_buffer[256];
1177 SSL_CTX *ctx = octx->ssl_ctx;
1179 /* Implicitly use pkcs11 engine if none was provided and the cert_file is a
1180 * PKCS#11 URI */
1181 if(!octx->p.engine && is_pkcs11_uri(cert_file) &&
1182 ossl_set_engine(data, octx, "pkcs11") != CURLE_OK)
1183 return 0;
1185 if(octx->p.engine) {
1186 static const char cmd_name[] = "LOAD_CERT_CTRL";
1187 struct {
1188 const char *cert_id;
1189 X509 *cert;
1190 } params;
1192 params.cert_id = cert_file;
1193 params.cert = NULL;
1195 /* Does the engine supports LOAD_CERT_CTRL ? */
1196 if(!ENGINE_ctrl(octx->p.engine, ENGINE_CTRL_GET_CMD_FROM_NAME,
1197 0, CURL_UNCONST(cmd_name), NULL)) {
1198 failf(data, "SSL engine does not support loading certificates");
1199 return 0;
1200 }
1202 /* Load the certificate from the engine */
1203 if(!ENGINE_ctrl_cmd(octx->p.engine, cmd_name, 0, ¶ms, NULL, 1)) {
1204 failf(data, "SSL engine cannot load client cert with id '%s' [%s]",
1205 cert_file,
1206 ossl_strerror(ERR_get_error(), error_buffer,
1207 sizeof(error_buffer)));
1208 return 0;
1209 }
1211 if(!params.cert) {
1212 failf(data, "SSL engine did not initialize the certificate properly.");
1213 return 0;
1214 }
1216 if(SSL_CTX_use_certificate(ctx, params.cert) != 1) {
1217 failf(data, "unable to set client certificate [%s]",
1218 ossl_strerror(ERR_get_error(), error_buffer,
1219 sizeof(error_buffer)));
1220 X509_free(params.cert);
1221 return 0;
1222 }
1223 X509_free(params.cert); /* we do not need the handle any more... */
1224 }
1225 else {
1226 failf(data, "crypto engine not set, cannot load certificate");
1227 return 0;
1228 }
1229 return 1;
1230#else
1231 (void)octx;
1232 (void)cert_file;
1233 failf(data, "SSL_FILETYPE_ENGINE not supported for certificate");
1234 return 0;
1235#endif
1236}
1238static int providerload(struct Curl_easy *data,
1239 struct ossl_ctx *octx,
1240 const char *cert_file)
1241{
1242#ifdef OPENSSL_HAS_PROVIDERS
1243 char error_buffer[256];
1244 SSL_CTX *ctx = octx->ssl_ctx;
1246 /* Implicitly use pkcs11 provider if none was provided and the cert_file is
1247 * a PKCS#11 URI */
1248 if(!octx->p.provider_loaded && is_pkcs11_uri(cert_file) &&
1249 ossl_set_provider(data, octx, "pkcs11") != CURLE_OK)
1250 return 0;
1252 if(octx->p.provider_loaded) {
1253 /* Load the certificate from the provider */
1254 OSSL_STORE_INFO *info = NULL;
1255 X509 *cert = NULL;
1256 OSSL_STORE_CTX *store =
1257 OSSL_STORE_open_ex(cert_file, octx->p.libctx,
1258 NULL, NULL, NULL, NULL, NULL, NULL);
1259 int rc;
1261 if(!store) {
1262 failf(data, "Failed to open OpenSSL store: %s",
1263 ossl_strerror(ERR_get_error(), error_buffer,
1264 sizeof(error_buffer)));
1265 return 0;
1266 }
1267 if(OSSL_STORE_expect(store, OSSL_STORE_INFO_CERT) != 1) {
1268 failf(data, "Failed to set store preference. Ignoring the error: %s",
1269 ossl_strerror(ERR_get_error(), error_buffer,
1270 sizeof(error_buffer)));
1271 }
1273 info = OSSL_STORE_load(store);
1274 if(info) {
1275 int ossl_type = OSSL_STORE_INFO_get_type(info);
1277 if(ossl_type == OSSL_STORE_INFO_CERT)
1278 cert = OSSL_STORE_INFO_get1_CERT(info);
1279 OSSL_STORE_INFO_free(info);
1280 }
1281 OSSL_STORE_close(store);
1282 if(!cert) {
1283 failf(data, "No cert found in the openssl store: %s",
1284 ossl_strerror(ERR_get_error(), error_buffer,
1285 sizeof(error_buffer)));
1286 return 0;
1287 }
1289 rc = SSL_CTX_use_certificate(ctx, cert);
1290 X509_free(cert); /* we do not need the handle any more... */
1292 if(rc != 1) {
1293 failf(data, "unable to set client certificate [%s]",
1294 ossl_strerror(ERR_get_error(), error_buffer,
1295 sizeof(error_buffer)));
1296 return 0;
1297 }
1298 }
1299 else {
1300 failf(data, "crypto provider not set, cannot load certificate");
1301 return 0;
1302 }
1303 return 1;
1304#else
1305 (void)octx;
1306 (void)cert_file;
1307 failf(data, "SSL_FILETYPE_PROVIDER not supported for certificate");
1308 return 0;
1309#endif
1310}
1312static int pkcs12load(struct Curl_easy *data,
1313 SSL_CTX* ctx,
1314 const struct curl_blob *cert_blob,
1315 const char *cert_file,
1316 const char *key_passwd)
1317{
1318 char error_buffer[256];
1319 BIO *cert_bio = NULL;
1320 PKCS12 *p12 = NULL;
1321 EVP_PKEY *pri;
1322 X509 *x509;
1323 int cert_done = 0;
1324 STACK_OF(X509) *ca = NULL;
1325 if(cert_blob) {
1326 cert_bio = BIO_new_mem_buf(cert_blob->data, (int)cert_blob->len);
1327 if(!cert_bio) {
1328 failf(data, "BIO_new_mem_buf NULL, " OSSL_PACKAGE " error %s",
1329 ossl_strerror(ERR_get_error(), error_buffer,
1330 sizeof(error_buffer)));
1331 return 0;
1332 }
1333 }
1334 else {
1335 cert_bio = BIO_new(BIO_s_file());
1336 if(!cert_bio) {
1337 failf(data, "BIO_new return NULL, " OSSL_PACKAGE " error %s",
1338 ossl_strerror(ERR_get_error(), error_buffer,
1339 sizeof(error_buffer)));
1340 return 0;
1341 }
1343 if(BIO_read_filename(cert_bio, CURL_UNCONST(cert_file)) <= 0) {
1344 failf(data, "could not open PKCS12 file '%s'", cert_file);
1345 BIO_free(cert_bio);
1346 return 0;
1347 }
1348 }
1350 p12 = d2i_PKCS12_bio(cert_bio, NULL);
1351 BIO_free(cert_bio);
1353 if(!p12) {
1354 failf(data, "error reading PKCS12 file '%s'",
1355 cert_blob ? "(memory blob)" : cert_file);
1356 return 0;
1357 }
1359 if(!PKCS12_parse(p12, key_passwd, &pri, &x509, &ca)) {
1360 failf(data, "could not parse PKCS12 file, check password, " OSSL_PACKAGE
1361 " error %s",
1362 ossl_strerror(ERR_get_error(), error_buffer, sizeof(error_buffer)));
1363 PKCS12_free(p12);
1364 return 0;
1365 }
1367 PKCS12_free(p12);
1369 if(SSL_CTX_use_certificate(ctx, x509) != 1) {
1370 failf(data, "could not load PKCS12 client certificate, " OSSL_PACKAGE
1371 " error %s",
1372 ossl_strerror(ERR_get_error(), error_buffer, sizeof(error_buffer)));
1373 goto fail;
1374 }
1376 if(SSL_CTX_use_PrivateKey(ctx, pri) != 1) {
1377 failf(data, "unable to use private key from PKCS12 file '%s'", cert_file);
1378 goto fail;
1379 }
1381 if(!SSL_CTX_check_private_key(ctx)) {
1382 failf(data, "private key from PKCS12 file '%s' "
1383 "does not match certificate in same file", cert_file);
1384 goto fail;
1385 }
1386 /* Set Certificate Verification chain */
1387 if(ca) {
1388 while(sk_X509_num(ca)) {
1389 /*
1390 * Note that sk_X509_pop() is used below to make sure the cert is
1391 * removed from the stack properly before getting passed to
1392 * SSL_CTX_add_extra_chain_cert(), which takes ownership. Previously
1393 * we used sk_X509_value() instead, but then we would clean it in the
1394 * subsequent sk_X509_pop_free() call.
1395 */
1396 X509 *x = sk_X509_pop(ca);
1397 if(!SSL_CTX_add_client_CA(ctx, x)) {
1398 X509_free(x);
1399 failf(data, "cannot add certificate to client CA list");
1400 goto fail;
1401 }
1402 if(!SSL_CTX_add_extra_chain_cert(ctx, x)) {
1403 X509_free(x);
1404 failf(data, "cannot add certificate to certificate chain");
1405 goto fail;
1406 }
1407 }
1408 }
1410 cert_done = 1;
1411fail:
1412 EVP_PKEY_free(pri);
1413 X509_free(x509);
1414#if defined(__clang__) && __clang_major__ >= 16
1415#pragma clang diagnostic push
1416#pragma clang diagnostic ignored "-Wcast-function-type-strict"
1417#endif
1418 sk_X509_pop_free(ca, X509_free);
1419#if defined(__clang__) && __clang_major__ >= 16
1420#pragma clang diagnostic pop
1421#endif
1422 if(!cert_done)
1423 return 0; /* failure! */
1424 return 1;
1425}
1427static CURLcode client_cert(struct Curl_easy *data,
1428 struct ossl_ctx *octx,
1429 char *cert_file,
1430 const struct curl_blob *cert_blob,
1431 const char *cert_type,
1432 char *key_file,
1433 const struct curl_blob *key_blob,
1434 const char *key_type,
1435 char *key_passwd)
1436{
1437 char error_buffer[256];
1438 bool check_privkey = TRUE;
1439 int file_type = ossl_do_file_type(cert_type);
1440 SSL_CTX *ctx = octx->ssl_ctx;
1442 if(cert_file || cert_blob || (file_type == SSL_FILETYPE_ENGINE) ||
1443 (file_type == SSL_FILETYPE_PROVIDER)) {
1444 SSL *ssl;
1445 X509 *x509;
1446 bool pcks12_done = FALSE;
1447 int cert_use_result;
1449 if(key_passwd) {
1450 /* set the password in the callback userdata */
1451 SSL_CTX_set_default_passwd_cb_userdata(ctx, key_passwd);
1452 /* Set passwd callback: */
1453 SSL_CTX_set_default_passwd_cb(ctx, passwd_callback);
1454 }
1456 switch(file_type) {
1457 case SSL_FILETYPE_PEM:
1458 /* SSL_CTX_use_certificate_chain_file() only works on PEM files */
1459 cert_use_result = cert_blob ?
1460 use_certificate_chain_blob(ctx, cert_blob, key_passwd) :
1461 SSL_CTX_use_certificate_chain_file(ctx, cert_file);
1462 if(cert_use_result != 1) {
1463 failf(data,
1464 "could not load PEM client certificate from %s, " OSSL_PACKAGE
1465 " error %s, "
1466 "(no key found, wrong passphrase, or wrong file format?)",
1467 (cert_blob ? "CURLOPT_SSLCERT_BLOB" : cert_file),
1468 ossl_strerror(ERR_get_error(), error_buffer,
1469 sizeof(error_buffer)));
1470 return CURLE_SSL_CERTPROBLEM;
1471 }
1472 break;
1474 case SSL_FILETYPE_ASN1:
1475 /* SSL_CTX_use_certificate_file() works with either PEM or ASN1, but
1476 we use the case above for PEM so this can only be performed with
1477 ASN1 files. */
1479 cert_use_result = cert_blob ?
1480 use_certificate_blob(ctx, cert_blob, file_type, key_passwd) :
1481 SSL_CTX_use_certificate_file(ctx, cert_file, file_type);
1482 if(cert_use_result != 1) {
1483 failf(data,
1484 "could not load ASN1 client certificate from %s, " OSSL_PACKAGE
1485 " error %s, "
1486 "(no key found, wrong passphrase, or wrong file format?)",
1487 (cert_blob ? "CURLOPT_SSLCERT_BLOB" : cert_file),
1488 ossl_strerror(ERR_get_error(), error_buffer,
1489 sizeof(error_buffer)));
1490 return CURLE_SSL_CERTPROBLEM;
1491 }
1492 break;
1494 case SSL_FILETYPE_ENGINE:
1495 if(!cert_file || !engineload(data, octx, cert_file))
1496 return CURLE_SSL_CERTPROBLEM;
1497 break;
1499 case SSL_FILETYPE_PROVIDER:
1500 if(!cert_file || !providerload(data, octx, cert_file))
1501 return CURLE_SSL_CERTPROBLEM;
1502 break;
1504 case SSL_FILETYPE_PKCS12:
1505 if(!pkcs12load(data, ctx, cert_blob, cert_file, key_passwd))
1506 return CURLE_SSL_CERTPROBLEM;
1507 pcks12_done = TRUE;
1508 break;
1510 default:
1511 failf(data, "not supported file type '%s' for certificate", cert_type);
1512 return CURLE_BAD_FUNCTION_ARGUMENT;
1513 }
1515 if(!key_file && !key_blob) {
1516 key_file = cert_file;
1517 key_blob = cert_blob;
1518 }
1519 else
1520 file_type = ossl_do_file_type(key_type);
1522 switch(file_type) {
1523 case SSL_FILETYPE_PEM:
1524 case SSL_FILETYPE_ASN1:
1525 cert_use_result = key_blob ?
1526 use_privatekey_blob(ctx, key_blob, file_type, key_passwd) :
1527 SSL_CTX_use_PrivateKey_file(ctx, key_file, file_type);
1528 if(cert_use_result != 1) {
1529 failf(data, "unable to set private key file: '%s' type %s",
1530 key_file ? key_file : "(memory blob)",
1531 key_type ? key_type : "PEM");
1532 return CURLE_BAD_FUNCTION_ARGUMENT;
1533 }
1534 break;
1535 case SSL_FILETYPE_ENGINE:
1536 if(!enginecheck(data, octx, key_file, key_passwd))
1537 return CURLE_SSL_CERTPROBLEM;
1538 break;
1540 case SSL_FILETYPE_PROVIDER:
1541 if(!providercheck(data, octx, key_file))
1542 return CURLE_SSL_CERTPROBLEM;
1543 break;
1545 case SSL_FILETYPE_PKCS12:
1546 if(!pcks12_done) {
1547 failf(data, "file type P12 for private key not supported");
1548 return CURLE_SSL_CERTPROBLEM;
1549 }
1550 break;
1551 default:
1552 failf(data, "not supported file type for private key");
1553 return CURLE_BAD_FUNCTION_ARGUMENT;
1554 }
1556 ssl = SSL_new(ctx);
1557 if(!ssl) {
1558 failf(data, "unable to create an SSL structure");
1559 return CURLE_OUT_OF_MEMORY;
1560 }
1562 x509 = SSL_get_certificate(ssl);
1564 if(x509) {
1565 EVP_PKEY *pktmp = X509_get_pubkey(x509);
1566 EVP_PKEY_copy_parameters(pktmp, SSL_get_privatekey(ssl));
1567 EVP_PKEY_free(pktmp);
1568 }
1570#if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_NO_DEPRECATED_3_0)
1571 {
1572 /* If RSA is used, do not check the private key if its flags indicate
1573 * it does not support it. */
1574 EVP_PKEY *priv_key = SSL_get_privatekey(ssl);
1575 if(EVP_PKEY_id(priv_key) == EVP_PKEY_RSA) {
1576 RSA *rsa = EVP_PKEY_get1_RSA(priv_key);
1577 if(RSA_flags(rsa) & RSA_METHOD_FLAG_NO_CHECK)
1578 check_privkey = FALSE;
1579 RSA_free(rsa); /* Decrement reference count */
1580 }
1581 }
1582#endif
1584 SSL_free(ssl);
1586 /* If we are using DSA, we can copy the parameters from
1587 * the private key */
1589 if(check_privkey == TRUE) {
1590 /* Now we know that a key and cert have been set against
1591 * the SSL context */
1592 if(!SSL_CTX_check_private_key(ctx)) {
1593 failf(data, "Private key does not match the certificate public key");
1594 return CURLE_SSL_CERTPROBLEM;
1595 }
1596 }
1597 }
1598 return CURLE_OK;
1599}
1601#ifdef CURLVERBOSE
1602/* returns non-zero on failure */
1603static CURLcode x509_name_oneline(const X509_NAME *a, struct dynbuf *d)
1604{
1605 BIO *bio_out = BIO_new(BIO_s_mem());
1606 BUF_MEM *biomem;
1607 int rc;
1608 CURLcode result = CURLE_OUT_OF_MEMORY;
1610 if(bio_out) {
1611 unsigned long flags = XN_FLAG_SEP_SPLUS_SPC |
1612 (XN_FLAG_ONELINE & ~ASN1_STRFLGS_ESC_MSB & ~XN_FLAG_SPC_EQ);
1613 curlx_dyn_reset(d);
1614 rc = X509_NAME_print_ex(bio_out, a, 0, flags);
1615 if(rc != -1) {
1616 BIO_get_mem_ptr(bio_out, &biomem);
1617 result = curlx_dyn_addn(d, biomem->data, biomem->length);
1618 }
1619 BIO_free(bio_out);
1620 }
1621 return result;
1622}
1623#endif
1625/**
1626 * Global SSL init
1627 *
1628 * @retval 0 error initializing SSL
1629 * @retval 1 SSL initialized successfully
1630 */
1631static int ossl_init(void)
1632{
1633 const uint64_t flags =
1634#ifdef OPENSSL_INIT_ENGINE_ALL_BUILTIN
1635 /* not present in BoringSSL */
1636 OPENSSL_INIT_ENGINE_ALL_BUILTIN |
1637#endif
1638#ifdef CURL_DISABLE_OPENSSL_AUTO_LOAD_CONFIG
1639 OPENSSL_INIT_NO_LOAD_CONFIG |
1640#else
1641 OPENSSL_INIT_LOAD_CONFIG |
1642#endif
1643 0;
1644 OPENSSL_init_ssl(flags, NULL);
1646#ifndef HAVE_KEYLOG_UPSTREAM
1647 Curl_tls_keylog_open();
1648#endif
1650 return 1;
1651}
1653/* Global cleanup */
1654static void ossl_cleanup(void)
1655{
1656#ifndef HAVE_KEYLOG_UPSTREAM
1657 Curl_tls_keylog_close();
1658#endif
1659}
1661/* Selects an OpenSSL crypto engine or provider.
1662 */
1663static CURLcode ossl_set_engine(struct Curl_easy *data, struct ossl_ctx *octx,
1664 const char *name)
1665{
1666#ifdef USE_OPENSSL_ENGINE
1667 CURLcode result = CURLE_SSL_ENGINE_NOTFOUND;
1668 ENGINE *e = ENGINE_by_id(name);
1670 if(e) {
1672 if(octx->p.engine) {
1673 ENGINE_finish(octx->p.engine);
1674 ENGINE_free(octx->p.engine);
1675 octx->p.engine = NULL;
1676 }
1677 if(!ENGINE_init(e)) {
1678 char buf[256];
1680 ENGINE_free(e);
1681 failf(data, "Failed to initialize SSL Engine '%s': %s",
1682 name, ossl_strerror(ERR_get_error(), buf, sizeof(buf)));
1683 result = CURLE_SSL_ENGINE_INITFAILED;
1684 e = NULL;
1685 }
1686 else {
1687 result = CURLE_OK;
1688 }
1689 octx->p.engine = e;
1690 return result;
1691 }
1692#endif
1693#ifdef OPENSSL_HAS_PROVIDERS
1694 return ossl_set_provider(data, octx, name);
1695#else
1696 (void)octx;
1697 (void)name;
1698 failf(data, "OpenSSL engine not found");
1699 return CURLE_SSL_ENGINE_NOTFOUND;
1700#endif
1701}
1703/* Sets engine as default for all SSL operations
1704 */
1705static CURLcode ossl_set_engine_default(struct Curl_easy *data,
1706 struct ossl_ctx *octx)
1707{
1708#ifdef USE_OPENSSL_ENGINE
1709 if(octx->p.engine) {
1710 if(ENGINE_set_default(octx->p.engine, ENGINE_METHOD_ALL) > 0) {
1711 infof(data, "set default crypto engine '%s'",
1712 ENGINE_get_id(octx->p.engine));
1713 }
1714 else {
1715 failf(data, "set default crypto engine '%s' failed",
1716 ENGINE_get_id(octx->p.engine));
1717 return CURLE_SSL_ENGINE_SETFAILED;
1718 }
1719 }
1720#else
1721 (void)data;
1722 (void)octx;
1723#endif
1724 return CURLE_OK;
1725}
1727/* Return list of OpenSSL crypto engine names.
1728 */
1729static struct curl_slist *ossl_engines_list(struct Curl_easy *data)
1730{
1731 struct curl_slist *list = NULL;
1732#ifdef USE_OPENSSL_ENGINE
1733 struct curl_slist *beg;
1734 ENGINE *e;
1736 for(e = ENGINE_get_first(); e; e = ENGINE_get_next(e)) {
1737 beg = curl_slist_append(list, ENGINE_get_id(e));
1738 if(!beg) {
1739 curl_slist_free_all(list);
1740 return NULL;
1741 }
1742 list = beg;
1743 }
1744#endif
1745 (void)data;
1746 return list;
1747}
1749#ifdef OPENSSL_HAS_PROVIDERS
1751static void ossl_provider_cleanup(struct ossl_ctx *octx)
1752{
1753 if(!octx)
1754 return;
1755 if(octx->p.baseprov) {
1756 OSSL_PROVIDER_unload(octx->p.baseprov);
1757 octx->p.baseprov = NULL;
1758 }
1759 if(octx->p.provider) {
1760 OSSL_PROVIDER_unload(octx->p.provider);
1761 octx->p.provider = NULL;
1762 }
1763 OSSL_LIB_CTX_free(octx->p.libctx);
1764 octx->p.libctx = NULL;
1765 curlx_safefree(octx->p.propq);
1766 octx->p.provider_loaded = FALSE;
1767}
1769#define MAX_PROVIDER_LEN 128 /* reasonable */
1771/* Selects an OpenSSL crypto provider.
1772 *
1773 * A provider might need an associated property, a string passed on to
1774 * OpenSSL. Specify this as [PROVIDER][:PROPERTY]: separate the name and the
1775 * property with a colon. No colon means no property is set.
1776 *
1777 * An example provider + property looks like "tpm2:?provider=tpm2".
1778 */
1779static CURLcode ossl_set_provider(struct Curl_easy *data,
1780 struct ossl_ctx *octx,
1781 const char *iname)
1782{
1783 char name[MAX_PROVIDER_LEN + 1];
1784 struct Curl_str prov;
1785 const char *propq = NULL;
1787 if(!iname) {
1788 /* clear and cleanup provider use */
1789 ossl_provider_cleanup(octx);
1790 return CURLE_OK;
1791 }
1792 if(curlx_str_until(&iname, &prov, MAX_PROVIDER_LEN, ':'))
1793 return CURLE_BAD_FUNCTION_ARGUMENT;
1795 if(!curlx_str_single(&iname, ':'))
1796 /* there was a colon, get the propq until the end of string */
1797 propq = iname;
1799 /* we need the name in a buffer, null-terminated */
1800 memcpy(name, curlx_str(&prov), curlx_strlen(&prov));
1801 name[curlx_strlen(&prov)] = 0;
1803 if(!octx->p.libctx) {
1804 OSSL_LIB_CTX *libctx = OSSL_LIB_CTX_new();
1805 if(!libctx)
1806 return CURLE_OUT_OF_MEMORY;
1807 if(propq) {
1808 octx->p.propq = curlx_strdup(propq);
1809 if(!octx->p.propq) {
1810 OSSL_LIB_CTX_free(libctx);
1811 return CURLE_OUT_OF_MEMORY;
1812 }
1813 }
1814 octx->p.libctx = libctx;
1815 }
1817#ifndef CURL_DISABLE_OPENSSL_AUTO_LOAD_CONFIG
1818 /* load the configuration file into the library context before checking the
1819 * provider availability */
1820 if(!OSSL_LIB_CTX_load_config(octx->p.libctx, NULL)) {
1821 infof(data, "Failed to load default openssl config. Proceeding.");
1822 }
1823#endif
1825 if(OSSL_PROVIDER_available(octx->p.libctx, name)) {
1826 /* already loaded through the configuration - no action needed */
1827 octx->p.provider_loaded = TRUE;
1828 return CURLE_OK;
1829 }
1831 octx->p.provider = OSSL_PROVIDER_try_load(octx->p.libctx, name, 1);
1832 if(!octx->p.provider) {
1833 char error_buffer[256];
1834 failf(data, "Failed to initialize provider: %s",
1835 ossl_strerror(ERR_get_error(), error_buffer, sizeof(error_buffer)));
1836 ossl_provider_cleanup(octx);
1837 return CURLE_SSL_ENGINE_NOTFOUND;
1838 }
1840 /* load the base provider as well */
1841 octx->p.baseprov = OSSL_PROVIDER_try_load(octx->p.libctx, "base", 1);
1842 if(!octx->p.baseprov) {
1843 ossl_provider_cleanup(octx);
1844 failf(data, "Failed to load base");
1845 return CURLE_SSL_ENGINE_NOTFOUND;
1846 }
1847 else
1848 octx->p.provider_loaded = TRUE;
1849 return CURLE_OK;
1850}
1851#else /* OPENSSL_HAS_PROVIDERS */
1852#define ossl_provider_cleanup(x)
1853#endif
1855static CURLcode ossl_shutdown(struct Curl_cfilter *cf,
1856 struct Curl_easy *data,
1857 bool send_shutdown, bool *done)
1858{
1859 struct ssl_connect_data *connssl = cf->ctx;
1860 struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend;
1861 CURLcode result = CURLE_OK;
1862 char buf[1024];
1863 int nread = -1, err;
1864 size_t i;
1866 DEBUGASSERT(octx);
1867 if(!octx->ssl || cf->shutdown) {
1868 *done = TRUE;
1869 goto out;
1870 }
1872 connssl->io_need = CURL_SSL_IO_NEED_NONE;
1873 *done = FALSE;
1874 if(!(SSL_get_shutdown(octx->ssl) & SSL_SENT_SHUTDOWN)) {
1875 /* We have not started the shutdown from our side yet. Check
1876 * if the server already sent us one. */
1877 ERR_clear_error();
1878 for(i = 0; i < 10; ++i) {
1879 nread = SSL_read(octx->ssl, buf, (int)sizeof(buf));
1880 CURL_TRC_CF(data, cf, "SSL shutdown not sent, read -> %d", nread);
1881 if(nread <= 0)
1882 break;
1883 }
1884 err = SSL_get_error(octx->ssl, nread);
1885 if(!nread && err == SSL_ERROR_ZERO_RETURN) {
1886 bool input_pending;
1887 /* Yes, it did. */
1888 if(!send_shutdown) {
1889 CURL_TRC_CF(data, cf, "SSL shutdown received, not sending");
1890 *done = TRUE;
1891 goto out;
1892 }
1893 else if(!cf->next->cft->is_alive(cf->next, data, &input_pending)) {
1894 /* Server closed the connection after its closy notify. It
1895 * seems not interested to see our close notify, so do not
1896 * send it. We are done. */
1897 connssl->peer_closed = TRUE;
1898 CURL_TRC_CF(data, cf, "peer closed connection");
1899 *done = TRUE;
1900 goto out;
1901 }
1902 }
1903 }
1905 /* SSL should now have started the shutdown from our side. Since it
1906 * was not complete, we are lacking the close notify from the server. */
1907 if(send_shutdown && !(SSL_get_shutdown(octx->ssl) & SSL_SENT_SHUTDOWN)) {
1908 int rc;
1909 ERR_clear_error();
1910 CURL_TRC_CF(data, cf, "send SSL close notify");
1911 rc = SSL_shutdown(octx->ssl);
1912 if(rc == 1) {
1913 CURL_TRC_CF(data, cf, "SSL shutdown finished");
1914 *done = TRUE;
1915 goto out;
1916 }
1917 if(rc < 0) {
1918 err = SSL_get_error(octx->ssl, rc);
1919 if(err == SSL_ERROR_WANT_WRITE) {
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 if(err != SSL_ERROR_WANT_READ) {
1925 VERBOSE(unsigned long sslerr = ERR_get_error());
1926 CURL_TRC_CF(data, cf,
1927 "SSL shutdown, ignore send error: %s (%s), errno %d",
1928 SSL_ERROR_to_str(err),
1929 (sslerr ? ossl_strerror(sslerr, buf, sizeof(buf)) :
1930 "no OpenSSL error"),
1931 SOCKERRNO);
1932 *done = TRUE;
1933 goto out;
1934 }
1935 }
1936 /* Having sent the close notify, we use SSL_read() to get the
1937 * missing close notify from the server. */
1938 }
1940 for(i = 0; i < 10; ++i) {
1941 ERR_clear_error();
1942 nread = SSL_read(octx->ssl, buf, (int)sizeof(buf));
1943 CURL_TRC_CF(data, cf, "SSL shutdown read -> %d", nread);
1944 if(nread <= 0)
1945 break;
1946 }
1947 err = SSL_get_error(octx->ssl, nread);
1948 switch(err) {
1949 case SSL_ERROR_ZERO_RETURN: /* no more data */
1950 if(SSL_shutdown(octx->ssl) == 1)
1951 CURL_TRC_CF(data, cf, "SSL shutdown finished");
1952 else
1953 CURL_TRC_CF(data, cf, "SSL shutdown not received, but closed");
1954 *done = TRUE;
1955 break;
1956 case SSL_ERROR_NONE: /* did not get anything */
1957 case SSL_ERROR_WANT_READ:
1958 /* SSL has sent its notify and now wants to read the reply
1959 * from the server. We are not really interested in that. */
1960 CURL_TRC_CF(data, cf, "SSL shutdown sent, want receive");
1961 connssl->io_need = CURL_SSL_IO_NEED_RECV;
1962 break;
1963 case SSL_ERROR_WANT_WRITE:
1964 CURL_TRC_CF(data, cf, "SSL shutdown send blocked");
1965 connssl->io_need = CURL_SSL_IO_NEED_SEND;
1966 break;
1967 default:
1968 /* Server seems to have closed the connection without sending us
1969 * a close notify. */
1970 {
1971 VERBOSE(unsigned long sslerr = ERR_get_error());
1972 CURL_TRC_CF(data, cf, "SSL shutdown, ignore recv error: '%s', errno %d",
1973 (sslerr ?
1974 ossl_strerror(sslerr, buf, sizeof(buf)) :
1975 SSL_ERROR_to_str(err)),
1976 SOCKERRNO);
1977 }
1978 *done = TRUE;
1979 result = CURLE_OK;
1980 break;
1981 }
1983out:
1984 cf->shutdown = (result || *done);
1985 if(cf->shutdown || (connssl->io_need != CURL_SSL_IO_NEED_NONE))
1986 connssl->input_pending = FALSE;
1987 return result;
1988}
1990/* also used by quic-tls */
1991void Curl_osslctx_cleanup(struct ossl_ctx *octx)
1992{
1993 DEBUGASSERT(octx);
1994 if(octx->ssl) {
1995 SSL_free(octx->ssl);
1996 octx->ssl = NULL;
1997 }
1998 if(octx->ssl_ctx) {
1999 SSL_CTX_free(octx->ssl_ctx);
2000 octx->ssl_ctx = NULL;
2001 octx->x509_store_setup = FALSE;
2002 }
2003 if(octx->bio_method) {
2004 ossl_bio_cf_method_free(octx->bio_method);
2005 octx->bio_method = NULL;
2006 }
2007#ifdef USE_OPENSSL_ENGINE
2008 if(octx->p.engine) {
2009 ENGINE_finish(octx->p.engine);
2010 ENGINE_free(octx->p.engine);
2011 octx->p.engine = NULL;
2012 }
2013#endif
2014 ossl_provider_cleanup(octx);
2015}
2017static void ossl_close(struct Curl_cfilter *cf, struct Curl_easy *data)
2018{
2019 struct ssl_connect_data *connssl = cf->ctx;
2020 struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend;
2021 (void)data;
2022 Curl_osslctx_cleanup(octx);
2023}
2025/*
2026 * This function is called when the 'data' struct is going away. Close
2027 * down everything and free all resources!
2028 */
2029static void ossl_close_all(struct Curl_easy *data)
2030{
2031 (void)data;
2032}
2034/* ====================================================== */
2036/* Quote from RFC2818 section 3.1 "Server Identity"
2038 If a subjectAltName extension of type dNSName is present, that MUST
2039 be used as the identity. Otherwise, the (most specific) Common Name
2040 field in the Subject field of the certificate MUST be used. Although
2041 the use of the Common Name is existing practice, it is deprecated and
2042 Certification Authorities are encouraged to use the dNSName instead.
2044 Matching is performed using the matching rules specified by
2045 [RFC2459]. If more than one identity of a given type is present in
2046 the certificate (e.g., more than one dNSName name, a match in any one
2047 of the set is considered acceptable.) Names may contain the wildcard
2048 character * which is considered to match any single domain name
2049 component or component fragment. E.g., *.a.com matches foo.a.com but
2050 not bar.foo.a.com. f*.com matches foo.com but not bar.com.
2052 In some cases, the URI is specified as an IP address rather than a
2053 hostname. In this case, the iPAddress subjectAltName must be present
2054 in the certificate and must exactly match the IP in the URI.
2056 This function is now used from ngtcp2 (QUIC) as well.
2057 */
2058static CURLcode ossl_verifyhost(struct Curl_easy *data,
2059 struct connectdata *conn,
2060 struct ssl_peer *peer,
2061 X509 *server_cert)
2062{
2063 bool matched = FALSE;
2064 int target; /* target type, GEN_DNS or GEN_IPADD */
2065 size_t addrlen = 0;
2066 STACK_OF(GENERAL_NAME) *altnames;
2067#ifdef USE_IPV6
2068 struct in6_addr addr;
2069#else
2070 struct in_addr addr;
2071#endif
2072 CURLcode result = CURLE_OK;
2073 bool dNSName = FALSE; /* if a dNSName field exists in the cert */
2074 bool iPAddress = FALSE; /* if an iPAddress field exists in the cert */
2075 size_t hostlen = strlen(peer->origin->hostname);
2077 (void)conn;
2078 switch(peer->type) {
2079 case CURL_SSL_PEER_IPV4:
2080 if(!curlx_inet_pton(AF_INET, peer->origin->hostname, &addr))
2081 return CURLE_PEER_FAILED_VERIFICATION;
2082 target = GEN_IPADD;
2083 addrlen = sizeof(struct in_addr);
2084 break;
2085#ifdef USE_IPV6
2086 case CURL_SSL_PEER_IPV6:
2087 if(!curlx_inet_pton(AF_INET6, peer->origin->hostname, &addr))
2088 return CURLE_PEER_FAILED_VERIFICATION;
2089 target = GEN_IPADD;
2090 addrlen = sizeof(struct in6_addr);
2091 break;
2092#endif
2093 case CURL_SSL_PEER_DNS:
2094 target = GEN_DNS;
2095 break;
2096 default:
2097 DEBUGASSERT(0);
2098 failf(data, "unexpected SSL peer type: %d", (int)peer->type);
2099 return CURLE_PEER_FAILED_VERIFICATION;
2100 }
2102 /* get a "list" of alternative names */
2103 altnames = X509_get_ext_d2i(server_cert, NID_subject_alt_name, NULL, NULL);
2105 if(altnames) {
2106#ifdef HAVE_BORINGSSL_LIKE
2107 size_t numalts;
2108 size_t i;
2109#else
2110 int numalts;
2111 int i;
2112#endif
2114 /* get amount of alternatives, RFC2459 claims there MUST be at least
2115 one, but we do not depend on it... */
2116 numalts = sk_GENERAL_NAME_num(altnames);
2118 /* loop through all alternatives - until a dnsmatch */
2119 for(i = 0; (i < numalts) && !matched; i++) {
2120 /* get a handle to alternative name number i */
2121 const GENERAL_NAME *check = sk_GENERAL_NAME_value(altnames, i);
2123 if(check->type == GEN_DNS)
2124 dNSName = TRUE;
2125 else if(check->type == GEN_IPADD)
2126 iPAddress = TRUE;
2128 /* only check alternatives of the same type the target is */
2129 if(check->type == target) {
2130 /* get data and length */
2131 const char *altptr = (const char *)ASN1_STRING_get0_data(check->d.ia5);
2132 size_t altlen = ossl_ASN1_STRING_get_length(check->d.ia5);
2134 switch(target) {
2135 case GEN_DNS: /* name/pattern comparison */
2136 if(!memchr(altptr, '\0', altlen) &&
2137 Curl_cert_hostcheck(altptr, altlen,
2138 peer->origin->hostname, hostlen)) {
2139 matched = TRUE;
2140 infof(data, " subjectAltName: \"%s\" matches cert's \"%.*s\"",
2141 peer->origin->user_hostname, (int)altlen, altptr);
2142 }
2143 break;
2145 case GEN_IPADD: /* IP address comparison */
2146 /* compare alternative IP address if the data chunk is the same size
2147 our server IP address is */
2148 if((altlen == addrlen) && !memcmp(altptr, &addr, altlen)) {
2149 matched = TRUE;
2150 infof(data, " subjectAltName: \"%s\" matches cert's IP address!",
2151 peer->origin->user_hostname);
2152 }
2153 break;
2154 }
2155 }
2156 }
2157 GENERAL_NAMES_free(altnames);
2158 }
2160 if(matched)
2161 /* an alternative name matched */
2162 ;
2163 else if(dNSName || iPAddress) {
2164 const char *tname = (peer->type == CURL_SSL_PEER_DNS) ? "hostname" :
2165 (peer->type == CURL_SSL_PEER_IPV4) ?
2166 "IPv4 address" : "IPv6 address";
2167 infof(data, " subjectAltName does not match %s %s", tname,
2168 peer->origin->user_hostname);
2169 failf(data, "SSL: no alternative certificate subject name matches "
2170 "target %s '%s'", tname, peer->origin->user_hostname);
2171 result = CURLE_PEER_FAILED_VERIFICATION;
2172 }
2173 else {
2174 /* we have to look to the last occurrence of a commonName in the
2175 distinguished one to get the most significant one. */
2176 int i = -1;
2177 unsigned char *cn = NULL;
2178 size_t cnlen = 0;
2179 bool free_cn = FALSE;
2181 /* The following is done because of a bug in 0.9.6b */
2182 const X509_NAME *name = X509_get_subject_name(server_cert);
2183 if(name) {
2184 int j;
2185 while((j = X509_NAME_get_index_by_NID(name, NID_commonName, i)) >= 0)
2186 i = j;
2187 }
2189 /* we have the name entry and we now convert this to a string
2190 that we can use for comparison. Doing this we support BMPstring,
2191 UTF8, etc. */
2193 if(i >= 0) {
2194 const ASN1_STRING *tmp =
2195 X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name, i));
2197 /* In OpenSSL 0.9.7d and earlier, ASN1_STRING_to_UTF8 fails if the input
2198 is already UTF-8 encoded. We check for this case and copy the raw
2199 string manually to avoid the problem. This code can be made
2200 conditional in the future when OpenSSL has been fixed. */
2201 if(tmp) {
2202 if(ASN1_STRING_type(tmp) == V_ASN1_UTF8STRING) {
2203 cnlen = ossl_ASN1_STRING_get_length(tmp);
2204 cn = (unsigned char *)CURL_UNCONST(ASN1_STRING_get0_data(tmp));
2205 }
2206 else { /* not a UTF8 name */
2207 const int utf8len = ASN1_STRING_to_UTF8(&cn, tmp);
2208 if(utf8len < 0)
2209 cnlen = 0;
2210 else
2211 cnlen = (size_t)utf8len;
2212 free_cn = TRUE;
2213 }
2215 if((cnlen == 0) || !cn)
2216 result = CURLE_OUT_OF_MEMORY;
2217 else if(memchr(cn, '\0', cnlen)) {
2218 /* there was a null-terminator before the end of string, this
2219 cannot match and we return failure! */
2220 failf(data, "SSL: illegal cert name field");
2221 result = CURLE_PEER_FAILED_VERIFICATION;
2222 }
2223 }
2224 }
2226 if(result)
2227 /* error already detected, pass through */
2228 ;
2229 else if(!cn) {
2230 failf(data, "SSL: unable to obtain common name from peer certificate");
2231 result = CURLE_PEER_FAILED_VERIFICATION;
2232 }
2233 else if(!Curl_cert_hostcheck((const char *)cn, cnlen,
2234 peer->origin->hostname, hostlen)) {
2235 failf(data, "SSL: certificate subject name '%.*s' does not match "
2236 "target hostname '%s'", (int)cnlen, cn,
2237 peer->origin->user_hostname);
2238 result = CURLE_PEER_FAILED_VERIFICATION;
2239 }
2240 else {
2241 infof(data, " common name: %.*s (matched)", (int)cnlen, cn);
2242 }
2243 if(free_cn)
2244 OPENSSL_free(cn);
2245 }
2247 return result;
2248}
2250#ifndef OPENSSL_NO_OCSP
2251static CURLcode verifystatus(struct Curl_cfilter *cf,
2252 struct Curl_easy *data,
2253 struct ossl_ctx *octx)
2254{
2255 int i, ocsp_status;
2256#ifdef HAVE_BORINGSSL_LIKE
2257 const uint8_t *status;
2258#else
2259 unsigned char *status;
2260#endif
2261 const unsigned char *p;
2262 CURLcode result = CURLE_OK;
2263 OCSP_RESPONSE *rsp = NULL;
2264 OCSP_BASICRESP *br = NULL;
2265 X509_STORE *st = NULL;
2266 STACK_OF(X509) *ch = NULL;
2267 X509 *cert;
2268 OCSP_CERTID *id = NULL;
2269 int cert_status, crl_reason;
2270 ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
2271 int ret;
2272 long len;
2274 (void)cf;
2275 DEBUGASSERT(octx);
2277 len = (long)SSL_get_tlsext_status_ocsp_resp(octx->ssl, &status);
2279 if(!status) {
2280 failf(data, "No OCSP response received");
2281 result = CURLE_SSL_INVALIDCERTSTATUS;
2282 goto end;
2283 }
2284 p = status;
2285 rsp = d2i_OCSP_RESPONSE(NULL, &p, len);
2286 if(!rsp) {
2287 failf(data, "Invalid OCSP response");
2288 result = CURLE_SSL_INVALIDCERTSTATUS;
2289 goto end;
2290 }
2292 ocsp_status = OCSP_response_status(rsp);
2293 if(ocsp_status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
2294 failf(data, "Invalid OCSP response status: %s (%d)",
2295 OCSP_response_status_str(ocsp_status), ocsp_status);
2296 result = CURLE_SSL_INVALIDCERTSTATUS;
2297 goto end;
2298 }
2300 br = OCSP_response_get1_basic(rsp);
2301 if(!br) {
2302 failf(data, "Invalid OCSP response");
2303 result = CURLE_SSL_INVALIDCERTSTATUS;
2304 goto end;
2305 }
2307#if !defined(HAVE_BORINGSSL_LIKE) && \
2308 !(defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x3060000fL)
2309 ch = SSL_get0_verified_chain(octx->ssl);
2310#else
2311 ch = SSL_get_peer_cert_chain(octx->ssl);
2312#endif
2313 if(!ch) {
2314 failf(data, "Could not get peer certificate chain");
2315 result = CURLE_SSL_INVALIDCERTSTATUS;
2316 goto end;
2317 }
2318 st = SSL_CTX_get_cert_store(octx->ssl_ctx);
2320 if(OCSP_basic_verify(br, ch, st, 0) <= 0) {
2321 failf(data, "OCSP response verification failed");
2322 result = CURLE_SSL_INVALIDCERTSTATUS;
2323 goto end;
2324 }
2326 /* Compute the certificate's ID */
2327 cert = SSL_get1_peer_certificate(octx->ssl);
2328 if(!cert) {
2329 failf(data, "Error getting peer certificate");
2330 result = CURLE_SSL_INVALIDCERTSTATUS;
2331 goto end;
2332 }
2334 for(i = 0; i < (int)sk_X509_num(ch); i++) {
2335 X509 *issuer = sk_X509_value(ch, (ossl_valsize_t)i);
2336 if(X509_check_issued(issuer, cert) == X509_V_OK) {
2337 /* Note to analysis tools: using SHA1 here is fine. The `id`
2338 * generated is used as a hash lookup key, not as a verifier
2339 * of the OCSP data itself. This all according to RFC 5019. */
2340 id = OCSP_cert_to_id(EVP_sha1(), cert, issuer);
2341 break;
2342 }
2343 }
2344 X509_free(cert);
2346 if(!id) {
2347 failf(data, "Error computing OCSP ID");
2348 result = CURLE_SSL_INVALIDCERTSTATUS;
2349 goto end;
2350 }
2352 /* Find the single OCSP response corresponding to the certificate ID */
2353 ret = OCSP_resp_find_status(br, id, &cert_status, &crl_reason, &rev,
2354 &thisupd, &nextupd);
2355 OCSP_CERTID_free(id);
2356 if(ret != 1) {
2357 failf(data, "Could not find certificate ID in OCSP response");
2358 result = CURLE_SSL_INVALIDCERTSTATUS;
2359 goto end;
2360 }
2362 /* Validate the OCSP response issuing and update times.
2363 * - `thisupd` is the time the OCSP response was issued
2364 * - `nextupd` is the time the OCSP response should be updated
2365 * (valid life time assigned by the OCSP responder)
2366 * - 3rd param: how many seconds of clock skew we allow between
2367 * our clock and the instance that issued the OCSP response
2368 * - 4th param: how many seconds in the past `thisupd` may be, with
2369 * -1 meaning there is no limit. */
2370 if(!OCSP_check_validity(thisupd, nextupd, 300L, -1L)) {
2371 failf(data, "OCSP response has expired");
2372 result = CURLE_SSL_INVALIDCERTSTATUS;
2373 goto end;
2374 }
2376 infof(data, "SSL certificate status: %s (%d)",
2377 OCSP_cert_status_str(cert_status), cert_status);
2379 switch(cert_status) {
2380 case V_OCSP_CERTSTATUS_GOOD:
2381 break;
2383 case V_OCSP_CERTSTATUS_REVOKED:
2384 result = CURLE_SSL_INVALIDCERTSTATUS;
2385 failf(data, "SSL certificate revocation reason: %s (%d)",
2386 OCSP_crl_reason_str(crl_reason), crl_reason);
2387 goto end;
2389 case V_OCSP_CERTSTATUS_UNKNOWN:
2390 default:
2391 result = CURLE_SSL_INVALIDCERTSTATUS;
2392 goto end;
2393 }
2395end:
2396 if(br)
2397 OCSP_BASICRESP_free(br);
2398 OCSP_RESPONSE_free(rsp);
2400 return result;
2401}
2402#endif
2404static const char *ssl_msg_type(int ssl_ver, int msg)
2405{
2406 if(ssl_ver == SSL3_VERSION_MAJOR) {
2407 switch(msg) {
2408 case SSL3_MT_HELLO_REQUEST:
2409 return "Hello request";
2410 case SSL3_MT_CLIENT_HELLO:
2411 return "Client hello";
2412 case SSL3_MT_SERVER_HELLO:
2413 return "Server hello";
2414#ifdef SSL3_MT_NEWSESSION_TICKET
2415 case SSL3_MT_NEWSESSION_TICKET:
2416 return "Newsession Ticket";
2417#endif
2418 case SSL3_MT_CERTIFICATE:
2419 return "Certificate";
2420 case SSL3_MT_SERVER_KEY_EXCHANGE:
2421 return "Server key exchange";
2422 case SSL3_MT_CLIENT_KEY_EXCHANGE:
2423 return "Client key exchange";
2424 case SSL3_MT_CERTIFICATE_REQUEST:
2425 return "Request CERT";
2426 case SSL3_MT_SERVER_DONE:
2427 return "Server finished";
2428 case SSL3_MT_CERTIFICATE_VERIFY:
2429 return "CERT verify";
2430 case SSL3_MT_FINISHED:
2431 return "Finished";
2432#ifdef SSL3_MT_CERTIFICATE_STATUS
2433 case SSL3_MT_CERTIFICATE_STATUS:
2434 return "Certificate Status";
2435#endif
2436#ifdef SSL3_MT_ENCRYPTED_EXTENSIONS
2437 case SSL3_MT_ENCRYPTED_EXTENSIONS:
2438 return "Encrypted Extensions";
2439#endif
2440#ifdef SSL3_MT_SUPPLEMENTAL_DATA
2441 case SSL3_MT_SUPPLEMENTAL_DATA:
2442 return "Supplemental data";
2443#endif
2444#ifdef SSL3_MT_END_OF_EARLY_DATA
2445 case SSL3_MT_END_OF_EARLY_DATA:
2446 return "End of early data";
2447#endif
2448#ifdef SSL3_MT_KEY_UPDATE
2449 case SSL3_MT_KEY_UPDATE:
2450 return "Key update";
2451#endif
2452#ifdef SSL3_MT_NEXT_PROTO
2453 case SSL3_MT_NEXT_PROTO:
2454 return "Next protocol";
2455#endif
2456#ifdef SSL3_MT_MESSAGE_HASH
2457 case SSL3_MT_MESSAGE_HASH:
2458 return "Message hash";
2459#endif
2460 }
2461 }
2462 return "Unknown";
2463}
2465static const char *tls_rt_type(int type)
2466{
2467 switch(type) {
2468#ifdef SSL3_RT_HEADER
2469 case SSL3_RT_HEADER:
2470 return "TLS header";
2471#endif
2472 case SSL3_RT_CHANGE_CIPHER_SPEC:
2473 return "TLS change cipher";
2474 case SSL3_RT_ALERT:
2475 return "TLS alert";
2476 case SSL3_RT_HANDSHAKE:
2477 return "TLS handshake";
2478 case SSL3_RT_APPLICATION_DATA:
2479 return "TLS app data";
2480 default:
2481 return "TLS Unknown";
2482 }
2483}
2485/*
2486 * Our callback from the SSL/TLS layers.
2487 */
2488static void ossl_trace(int direction, int ssl_ver, int content_type,
2489 const void *buf, size_t len, SSL *ssl,
2490 void *userp)
2491{
2492 const char *verstr;
2493 struct Curl_cfilter *cf = userp;
2494 struct Curl_easy *data = NULL;
2495 char unknown[32];
2497 if(!cf)
2498 return;
2499 data = CF_DATA_CURRENT(cf);
2500 if(!data || !data->set.fdebug || (direction && direction != 1))
2501 return;
2503 switch(ssl_ver) {
2504#ifdef SSL3_VERSION
2505 case SSL3_VERSION:
2506 verstr = "SSLv3";
2507 break;
2508#endif
2509 case TLS1_VERSION:
2510 verstr = "TLSv1.0";
2511 break;
2512#ifdef TLS1_1_VERSION
2513 case TLS1_1_VERSION:
2514 verstr = "TLSv1.1";
2515 break;
2516#endif
2517#ifdef TLS1_2_VERSION
2518 case TLS1_2_VERSION:
2519 verstr = "TLSv1.2";
2520 break;
2521#endif
2522 case TLS1_3_VERSION:
2523 verstr = "TLSv1.3";
2524 break;
2525 default:
2526 curl_msnprintf(unknown, sizeof(unknown), "(%x)", (unsigned int)ssl_ver);
2527 verstr = unknown;
2528 break;
2529 }
2531 /* Log progress for interesting records only (like Handshake or Alert), skip
2532 * all raw record headers (content_type == SSL3_RT_HEADER or ssl_ver == 0).
2533 * For TLS 1.3, skip notification of the decrypted inner Content-Type.
2534 */
2535 if(ssl_ver
2536#ifdef SSL3_RT_HEADER
2537 && content_type != SSL3_RT_HEADER
2538#endif
2539#ifdef SSL3_RT_INNER_CONTENT_TYPE
2540 && content_type != SSL3_RT_INNER_CONTENT_TYPE
2541#endif
2542 ) {
2543 const char *msg_name = "Truncated message";
2544 const char *tls_rt_name;
2545 char ssl_buf[1024];
2546 int msg_type = 0;
2547 int txt_len;
2549 /* the info given when the version is zero is not that useful for us */
2551 ssl_ver >>= 8; /* check the upper 8 bits only below */
2553 /* SSLv2 does not seem to have TLS record-type headers, so OpenSSL
2554 * always pass-up content-type as 0, but the interesting message-type
2555 * is at 'buf[0]'.
2556 */
2557 if(ssl_ver == SSL3_VERSION_MAJOR && content_type)
2558 tls_rt_name = tls_rt_type(content_type);
2559 else
2560 tls_rt_name = "";
2562 if(content_type == SSL3_RT_CHANGE_CIPHER_SPEC) {
2563 if(len) {
2564 msg_type = *(const unsigned char *)buf;
2565 msg_name = "Change cipher spec";
2566 }
2567 }
2568 else if(content_type == SSL3_RT_ALERT) {
2569 if(len >= 2) {
2570 msg_type =
2571 (((const unsigned char *)buf)[0] << 8) +
2572 ((const unsigned char *)buf)[1];
2573 msg_name = SSL_alert_desc_string_long(msg_type);
2574 }
2575 }
2576 else if(len) {
2577 msg_type = *(const unsigned char *)buf;
2578 msg_name = ssl_msg_type(ssl_ver, msg_type);
2579 }
2581 txt_len = curl_msnprintf(ssl_buf, sizeof(ssl_buf),
2582 "%s (%s), %s, %s (%d):\n",
2583 verstr, direction ? "OUT" : "IN",
2584 tls_rt_name, msg_name, msg_type);
2585 Curl_debug(data, CURLINFO_TEXT, ssl_buf, (size_t)txt_len);
2586 }
2588 Curl_debug(data, (direction == 1) ? CURLINFO_SSL_DATA_OUT :
2589 CURLINFO_SSL_DATA_IN, (const char *)buf, len);
2590 (void)ssl;
2591}
2593static CURLcode ossl_set_ssl_version_min_max(struct Curl_cfilter *cf,
2594 SSL_CTX *ctx,
2595 unsigned int ssl_version_min)
2596{
2597 struct ssl_filter_config *conn_config = Curl_ssl_cf_get_filter_config(cf);
2598 /* first, TLS min version... */
2599 long curl_ssl_version_min = (long)ssl_version_min;
2600 long curl_ssl_version_max;
2602 /* convert curl min SSL version option to OpenSSL constant */
2603#if defined(HAVE_BORINGSSL_LIKE) || defined(LIBRESSL_VERSION_NUMBER)
2604 uint16_t ossl_ssl_version_min = 0;
2605 uint16_t ossl_ssl_version_max = 0;
2606#else
2607 long ossl_ssl_version_min = 0;
2608 long ossl_ssl_version_max = 0;
2609#endif
2610 /* it cannot be default here */
2611 DEBUGASSERT(curl_ssl_version_min != CURL_SSLVERSION_DEFAULT);
2612 switch(curl_ssl_version_min) {
2613 case CURL_SSLVERSION_TLSv1: /* TLS 1.x */
2614 case CURL_SSLVERSION_TLSv1_0:
2615 ossl_ssl_version_min = TLS1_VERSION;
2616 break;
2617 case CURL_SSLVERSION_TLSv1_1:
2618 ossl_ssl_version_min = TLS1_1_VERSION;
2619 break;
2620 case CURL_SSLVERSION_TLSv1_2:
2621 ossl_ssl_version_min = TLS1_2_VERSION;
2622 break;
2623 case CURL_SSLVERSION_TLSv1_3:
2624 ossl_ssl_version_min = TLS1_3_VERSION;
2625 break;
2626 }
2628 /* ... then, TLS max version */
2629 curl_ssl_version_max = (long)conn_config->version_max;
2631 /* convert curl max SSL version option to OpenSSL constant */
2632 switch(curl_ssl_version_max) {
2633 case CURL_SSLVERSION_MAX_TLSv1_0:
2634 ossl_ssl_version_max = TLS1_VERSION;
2635 break;
2636 case CURL_SSLVERSION_MAX_TLSv1_1:
2637 ossl_ssl_version_max = TLS1_1_VERSION;
2638 break;
2639 case CURL_SSLVERSION_MAX_TLSv1_2:
2640 ossl_ssl_version_max = TLS1_2_VERSION;
2641 break;
2642 case CURL_SSLVERSION_MAX_TLSv1_3:
2643 ossl_ssl_version_max = TLS1_3_VERSION;
2644 break;
2645 case CURL_SSLVERSION_MAX_NONE: /* none selected */
2646 case CURL_SSLVERSION_MAX_DEFAULT: /* max selected */
2647 default:
2648 /* SSL_CTX_set_max_proto_version states that: setting the maximum to 0
2649 enables protocol versions up to the highest version supported by
2650 the library */
2651 ossl_ssl_version_max = 0;
2652 break;
2653 }
2655 if(!SSL_CTX_set_min_proto_version(ctx, ossl_ssl_version_min) ||
2656 !SSL_CTX_set_max_proto_version(ctx, ossl_ssl_version_max))
2657 return CURLE_SSL_CONNECT_ERROR;
2659 return CURLE_OK;
2660}
2662CURLcode Curl_ossl_add_session(struct Curl_cfilter *cf,
2663 struct Curl_easy *data,
2664 struct ossl_ctx *octx,
2665 const char *ssl_peer_key,
2666 SSL_SESSION *session,
2667 const char *alpn,
2668 unsigned char *quic_tp,
2669 size_t quic_tp_len,
2670 struct Curl_ssl_session **psession)
2671{
2672 struct Curl_ssl_session *sc_session = NULL, *sc_dup = NULL;
2673 unsigned char *der_session_buf = NULL;
2674 unsigned char *qtp_clone = NULL;
2675 CURLcode result = CURLE_OK;
2677 if(psession)
2678 *psession = NULL;
2679 if(!cf || !data)
2680 goto out;
2682 if(Curl_ssl_scache_use(cf, data)) {
2683 size_t der_session_size;
2684 unsigned char *der_session_ptr;
2685 size_t earlydata_max = 0;
2686 int ietf_tls_id = SSL_version(octx->ssl);
2688 der_session_size = i2d_SSL_SESSION(session, NULL);
2689 if(der_session_size == 0) {
2690 result = CURLE_OUT_OF_MEMORY;
2691 goto out;
2692 }
2694 der_session_buf = der_session_ptr = curlx_malloc(der_session_size);
2695 if(!der_session_buf) {
2696 result = CURLE_OUT_OF_MEMORY;
2697 goto out;
2698 }
2700 der_session_size = i2d_SSL_SESSION(session, &der_session_ptr);
2701 if(der_session_size == 0) {
2702 result = CURLE_OUT_OF_MEMORY;
2703 goto out;
2704 }
2706#ifdef HAVE_OPENSSL_EARLYDATA
2707 earlydata_max = SSL_SESSION_get_max_early_data(session);
2708#endif
2709 if(quic_tp && quic_tp_len) {
2710 qtp_clone = curlx_memdup0((const char *)quic_tp, quic_tp_len);
2711 if(!qtp_clone) {
2712 result = CURLE_OUT_OF_MEMORY;
2713 goto out;
2714 }
2715 }
2717 result = Curl_ssl_session_create2(der_session_buf, der_session_size,
2718 ietf_tls_id, alpn,
2719 (curl_off_t)time(NULL) +
2720 SSL_SESSION_get_timeout(session),
2721 earlydata_max, qtp_clone, quic_tp_len,
2722 &sc_session);
2723 der_session_buf = NULL; /* took ownership of sdata */
2724#ifdef USE_APPLE_SECTRUST
2725 if(!result)
2726 sc_session->sectrust_verified = octx->sectrust_verified;
2727#endif
2728 if(!result && psession && /* return a duplicate if asked for and FTP */
2729 (cf->conn->scheme->family == CURLPROTO_FTP)) {
2730 result = Curl_ssl_session_dup(sc_session, &sc_dup);
2731 }
2732 if(!result) {
2733 result = Curl_ssl_scache_put(cf, data, ssl_peer_key, sc_session);
2734 /* took ownership of `sc_session` */
2735 sc_session = NULL;
2736 }
2737 }
2739out:
2740 curlx_free(der_session_buf);
2741 if(!result && psession) {
2742 *psession = sc_dup;
2743 sc_dup = NULL;
2744 }
2745 Curl_ssl_session_destroy(sc_session);
2746 Curl_ssl_session_destroy(sc_dup);
2747 return result;
2748}
2750/* The "new session" callback must return zero if the session can be removed
2751 * or non-zero if the session has been put into the session cache.
2752 */
2753static int ossl_new_session_cb(SSL *ssl, SSL_SESSION *ssl_sessionid)
2754{
2755 struct Curl_cfilter *cf = (struct Curl_cfilter *)SSL_get_app_data(ssl);
2756 if(cf) {
2757 struct Curl_easy *data = CF_DATA_CURRENT(cf);
2758 struct ssl_connect_data *connssl = cf->ctx;
2759 struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend;
2760 struct Curl_ssl_session *session = NULL;
2761 Curl_ossl_add_session(cf, data, octx, connssl->peer.scache_key,
2762 ssl_sessionid, connssl->negotiated.alpn, NULL,
2763 0, &session);
2764 if(session) { /* remember current TLS session */
2765 Curl_ssl_session_destroy(connssl->session);
2766 connssl->session = session;
2767 }
2768 }
2769 return 0;
2770}
2772static CURLcode load_cacert_from_memory(X509_STORE *store,
2773 const struct curl_blob *ca_info_blob)
2774{
2775 /* these need to be freed at the end */
2776 BIO *cbio = NULL;
2777 STACK_OF(X509_INFO) *inf = NULL;
2779 /* everything else is a reference */
2780 int i, count = 0;
2781 X509_INFO *itmp = NULL;
2783 if(ca_info_blob->len > (size_t)INT_MAX)
2784 return CURLE_SSL_CACERT_BADFILE;
2786 cbio = BIO_new_mem_buf(ca_info_blob->data, (int)ca_info_blob->len);
2787 if(!cbio)
2788 return CURLE_OUT_OF_MEMORY;
2790 inf = PEM_X509_INFO_read_bio(cbio, NULL, NULL, NULL);
2791 if(!inf) {
2792 BIO_free(cbio);
2793 return CURLE_SSL_CACERT_BADFILE;
2794 }
2796 /* add each entry from PEM file to x509_store */
2797 for(i = 0; i < (int)sk_X509_INFO_num(inf); ++i) {
2798 itmp = sk_X509_INFO_value(inf, (ossl_valsize_t)i);
2799 if(itmp->x509) {
2800 if(X509_STORE_add_cert(store, itmp->x509)) {
2801 ++count;
2802 }
2803 else {
2804 /* set count to 0 to return an error */
2805 count = 0;
2806 break;
2807 }
2808 }
2809 if(itmp->crl) {
2810 if(X509_STORE_add_crl(store, itmp->crl)) {
2811 ++count;
2812 }
2813 else {
2814 /* set count to 0 to return an error */
2815 count = 0;
2816 break;
2817 }
2818 }
2819 }
2821#if defined(__clang__) && __clang_major__ >= 16
2822#pragma clang diagnostic push
2823#pragma clang diagnostic ignored "-Wcast-function-type-strict"
2824#endif
2825 sk_X509_INFO_pop_free(inf, X509_INFO_free);
2826#if defined(__clang__) && __clang_major__ >= 16
2827#pragma clang diagnostic pop
2828#endif
2829 BIO_free(cbio);
2831 /* if we did not end up importing anything, treat that as an error */
2832 return (count > 0) ? CURLE_OK : CURLE_SSL_CACERT_BADFILE;
2833}
2835#ifdef USE_WIN32_CRYPTO
2836static CURLcode ossl_win_load_store(struct Curl_easy *data,
2837 struct Curl_cfilter *cf,
2838 const char *win_store,
2839 X509_STORE *store,
2840 bool *padded)
2841{
2842 CURLcode result = CURLE_OK;
2843 HCERTSTORE hStore;
2845 *padded = FALSE;
2847 hStore = CertOpenSystemStoreA(0, win_store);
2848 if(hStore) {
2849 PCCERT_CONTEXT pContext = NULL;
2850 /* The array of enhanced key usage OIDs varies per certificate and
2851 is declared outside of the loop so that rather than malloc/free each
2852 iteration we can grow it with realloc, when necessary. */
2853 CERT_ENHKEY_USAGE *enhkey_usage = NULL;
2854 DWORD enhkey_usage_size = 0;
2855 VERBOSE(size_t total = 0);
2856 VERBOSE(size_t imported = 0);
2858 /* This loop makes a best effort to import all valid certificates from
2859 the MS root store. If a certificate cannot be imported it is
2860 skipped. 'result' is used to store only hard-fail conditions (such
2861 as out of memory) that cause an early break. */
2862 result = CURLE_OK;
2863 for(;;) {
2864 X509 *x509;
2865 FILETIME now;
2866 BYTE key_usage[2];
2867 DWORD req_size;
2868 const unsigned char *encoded_cert;
2869 pContext = CertEnumCertificatesInStore(hStore, pContext);
2870 if(!pContext)
2871 break;
2873 VERBOSE(++total);
2875#if defined(DEBUGBUILD) && defined(CURLVERBOSE)
2876 {
2877 char cert_name[256];
2878 if(!CertGetNameStringA(pContext, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0,
2879 NULL, cert_name, sizeof(cert_name)))
2880 infof(data, "SSL: unknown cert name");
2881 else
2882 infof(data, "SSL: Checking cert \"%s\"", cert_name);
2883 }
2884#endif
2885 encoded_cert = (const unsigned char *)pContext->pbCertEncoded;
2886 if(!encoded_cert)
2887 continue;
2889 GetSystemTimeAsFileTime(&now);
2890 if(CompareFileTime(&pContext->pCertInfo->NotBefore, &now) > 0 ||
2891 CompareFileTime(&now, &pContext->pCertInfo->NotAfter) > 0)
2892 continue;
2894 /* If key usage exists check for signing attribute */
2895 if(CertGetIntendedKeyUsage(pContext->dwCertEncodingType,
2896 pContext->pCertInfo,
2897 key_usage, sizeof(key_usage))) {
2898 if(!(key_usage[0] & CERT_KEY_CERT_SIGN_KEY_USAGE))
2899 continue;
2900 }
2901 else if(GetLastError())
2902 continue;
2904 /* If enhanced key usage exists check for server auth attribute.
2905 *
2906 * Note "In a Microsoft environment, a certificate might also have
2907 * EKU extended properties that specify valid uses for the
2908 * certificate." The call below checks both, and behavior varies
2909 * depending on what is found. For more details see
2910 * CertGetEnhancedKeyUsage doc.
2911 */
2912 if(CertGetEnhancedKeyUsage(pContext, 0, NULL, &req_size) && req_size) {
2913 if(req_size > enhkey_usage_size) {
2914 void *tmp = curlx_realloc(enhkey_usage, req_size);
2916 if(!tmp) {
2917 failf(data, "SSL: Out of memory allocating for OID list");
2918 result = CURLE_OUT_OF_MEMORY;
2919 break;
2920 }
2922 enhkey_usage = (CERT_ENHKEY_USAGE *)tmp;
2923 enhkey_usage_size = req_size;
2924 }
2926 if(CertGetEnhancedKeyUsage(pContext, 0, enhkey_usage, &req_size)) {
2927 if(!enhkey_usage->cUsageIdentifier) {
2928 /* "If GetLastError returns CRYPT_E_NOT_FOUND, the certificate
2929 is good for all uses. If it returns zero, the certificate
2930 has no valid uses." */
2931 if((HRESULT)GetLastError() != CRYPT_E_NOT_FOUND)
2932 continue;
2933 }
2934 else {
2935 DWORD i;
2936 bool found = FALSE;
2938 for(i = 0; i < enhkey_usage->cUsageIdentifier; ++i) {
2939 if(!strcmp("1.3.6.1.5.5.7.3.1" /* OID server auth */,
2940 enhkey_usage->rgpszUsageIdentifier[i])) {
2941 found = TRUE;
2942 break;
2943 }
2944 }
2946 if(!found)
2947 continue;
2948 }
2949 }
2950 else
2951 continue;
2952 }
2953 else
2954 continue;
2956 {
2957 /* Blacklisted roots and intermediates.
2958 * https://emudhra.we-have-a-problem.com/
2959 *
2960 * Microsoft blocked the bad eMudhra intermediate certificates in
2961 * supported versions of Windows that receive updates, but may still
2962 * trust the issuer root certificates which other vendors have removed.
2963 *
2964 * Regardless we skip importing these certificates. OpenSSL does not
2965 * check Microsoft's blacklist and assuming the user did not provide a
2966 * CRL file it would otherwise be possible for verification to succeed.
2967 */
2968 static const char * const blacklist[] = {
2969 "emSign Root TLS CA - G3",
2970 "emSign Root CS CA - G3",
2971 "AAA Certificate Services",
2972 "emSign ECC Root CA - G3",
2973 "EM DV TLS CA - G3B",
2974 "EM OV TLS CA - G3B",
2975 "EM EV TLS CA - G3B",
2976 "EM DV TLS CA - G3C",
2977 "EM OV TLS CA - G3C",
2978 "EM EV TLS CA - G3C",
2979 "EM OV CS CA - G3B",
2980 "EM OV CS CA - G3C",
2981 NULL
2982 };
2983 char cert_name[256];
2984 if(CertGetNameStringA(pContext, CERT_NAME_ATTR_TYPE, 0,
2985 CURL_UNCONST(szOID_COMMON_NAME),
2986 cert_name, sizeof(cert_name)) > 1) {
2987 const char * const *b;
2988 for(b = blacklist; *b && strcmp(cert_name, *b); ++b)
2989 ;
2990 if(*b)
2991 continue;
2992 }
2993 }
2995 x509 = d2i_X509(NULL, &encoded_cert, (long)pContext->cbCertEncoded);
2996 if(!x509)
2997 continue;
2999 /* Try to import the certificate. This may fail for legitimate reasons
3000 such as duplicate certificate, which is allowed by MS but not
3001 OpenSSL. */
3002 if(X509_STORE_add_cert(store, x509) == 1) {
3003 VERBOSE(++imported);
3004#ifdef DEBUGBUILD
3005 infof(data, "SSL: Imported cert");
3006#endif
3007 *padded = TRUE;
3008 }
3009 X509_free(x509);
3010 }
3012 curlx_free(enhkey_usage);
3013 CertFreeCertificateContext(pContext);
3014 CertCloseStore(hStore, 0);
3016 CURL_TRC_CF(data, cf,
3017 "ossl_win_load_store() found: %zu imported: %zu certs in %s.",
3018 total, imported, win_store);
3020 if(result)
3021 return result;
3022 }
3024 return result;
3025}
3027static CURLcode ossl_windows_load_anchors(struct Curl_cfilter *cf,
3028 struct Curl_easy *data,
3029 X509_STORE *store,
3030 bool *padded)
3031{
3032 /* Import certificates from the Windows root certificate store if
3033 requested.
3034 https://stackoverflow.com/questions/9507184/
3035 https://github.com/d3x0r/SACK/blob/ff15424d3c581b86d40f818532e5a400c516d39d/src/netlib/ssl_layer.c#L1410
3036 https://datatracker.ietf.org/doc/html/rfc5280 */
3037 static const char * const win_stores[] = {
3038 "ROOT", /* Trusted Root Certification Authorities */
3039 "CA" /* Intermediate Certification Authorities */
3040 };
3041 size_t i;
3042 CURLcode result = CURLE_OK;
3044 *padded = FALSE;
3045 for(i = 0; i < CURL_ARRAYSIZE(win_stores); ++i) {
3046 bool store_added = FALSE;
3047 result = ossl_win_load_store(data, cf, win_stores[i], store, &store_added);
3048 if(result)
3049 return result;
3050 if(store_added) {
3051 CURL_TRC_CF(data, cf, "added trust anchors from Windows %s store",
3052 win_stores[i]);
3053 *padded = TRUE;
3054 }
3055 else
3056 infof(data, "error importing Windows %s store, continuing anyway",
3057 win_stores[i]);
3058 }
3059 return result;
3060}
3062#endif /* USE_WIN32_CRYPTO */
3064static CURLcode ossl_load_trust_anchors(struct Curl_cfilter *cf,
3065 struct Curl_easy *data,
3066 struct ossl_ctx *octx,
3067 X509_STORE *store)
3068{
3069 struct ssl_filter_config *conn_config = Curl_ssl_cf_get_filter_config(cf);
3070 CURLcode result = CURLE_OK;
3071 const char * const ssl_cafile =
3072 /* CURLOPT_CAINFO_BLOB overrides CURLOPT_CAINFO */
3073 (conn_config->ca_info_blob ? NULL : conn_config->CAfile);
3074 const char * const ssl_capath = conn_config->CApath;
3075 bool have_native_check = FALSE;
3077 octx->store_is_empty = TRUE;
3078 if(conn_config->native_ca_store) {
3079#ifdef USE_WIN32_CRYPTO
3080 bool added = FALSE;
3081 result = ossl_windows_load_anchors(cf, data, store, &added);
3082 if(result)
3083 return result;
3084 if(added) {
3085 infof(data, " Native: Windows System Stores ROOT+CA");
3086 octx->store_is_empty = FALSE;
3087 }
3088#elif defined(USE_APPLE_SECTRUST)
3089 infof(data, " Native: Apple SecTrust");
3090 have_native_check = TRUE;
3091#endif
3092 }
3094 if(conn_config->ca_info_blob) {
3095 result = load_cacert_from_memory(store, conn_config->ca_info_blob);
3096 if(result) {
3097 failf(data, "error adding trust anchors from certificate blob: %d",
3098 (int)result);
3099 return result;
3100 }
3101 infof(data, " CA Blob from configuration");
3102 octx->store_is_empty = FALSE;
3103 }
3105 if(ssl_cafile || ssl_capath) {
3106#ifdef HAVE_OPENSSL3
3107 /* OpenSSL 3.0.0 has deprecated SSL_CTX_load_verify_locations */
3108 if(ssl_cafile) {
3109 if(!X509_STORE_load_file(store, ssl_cafile)) {
3110 if(octx->store_is_empty && !have_native_check) {
3111 /* Fail if we insist on successfully verifying the server. */
3112 failf(data, "error adding trust anchors from file: %s", ssl_cafile);
3113 return CURLE_SSL_CACERT_BADFILE;
3114 }
3115 else
3116 infof(data, "error setting certificate file, continuing anyway");
3117 }
3118 infof(data, " CAfile: %s", ssl_cafile);
3119 octx->store_is_empty = FALSE;
3120 }
3121 if(ssl_capath) {
3122 if(!X509_STORE_load_path(store, ssl_capath)) {
3123 if(octx->store_is_empty && !have_native_check) {
3124 /* Fail if we insist on successfully verifying the server. */
3125 failf(data, "error adding trust anchors from path: %s", ssl_capath);
3126 return CURLE_SSL_CACERT_BADFILE;
3127 }
3128 else
3129 infof(data, "error setting certificate path, continuing anyway");
3130 }
3131 infof(data, " CApath: %s", ssl_capath);
3132 octx->store_is_empty = FALSE;
3133 }
3134#else
3135 /* tell OpenSSL where to find CA certificates that are used to verify the
3136 server's certificate. */
3137 if(!X509_STORE_load_locations(store, ssl_cafile, ssl_capath)) {
3138 if(octx->store_is_empty && !have_native_check) {
3139 /* Fail if we insist on successfully verifying the server. */
3140 failf(data, "error adding trust anchors from locations:"
3141 " CAfile: %s CApath: %s",
3142 ssl_cafile ? ssl_cafile : "none",
3143 ssl_capath ? ssl_capath : "none");
3144 return CURLE_SSL_CACERT_BADFILE;
3145 }
3146 else {
3147 infof(data, "error setting certificate verify locations,"
3148 " continuing anyway");
3149 }
3150 }
3151 if(ssl_cafile)
3152 infof(data, " CAfile: %s", ssl_cafile);
3153 if(ssl_capath)
3154 infof(data, " CApath: %s", ssl_capath);
3155 octx->store_is_empty = FALSE;
3156#endif
3157 }
3159#ifdef CURL_CA_FALLBACK
3160 if(octx->store_is_empty) {
3161 /* verifying the peer without any CA certificates does not
3162 work so use OpenSSL's built-in default as fallback */
3163 X509_STORE_set_default_paths(store);
3164 infof(data, " OpenSSL default paths (fallback)");
3165 octx->store_is_empty = FALSE;
3166 }
3167#endif
3168 if(octx->store_is_empty && !have_native_check)
3169 infof(data, " no trust anchors configured");
3171 return result;
3172}
3174static CURLcode ossl_populate_x509_store(struct Curl_cfilter *cf,
3175 struct Curl_easy *data,
3176 struct ossl_ctx *octx,
3177 X509_STORE *store)
3178{
3179 struct ssl_filter_config *conn_config = Curl_ssl_cf_get_filter_config(cf);
3180 CURLcode result = CURLE_OK;
3181 X509_LOOKUP *lookup = NULL;
3182 const char * const ssl_crlfile = conn_config->CRLfile;
3183 unsigned long x509flags = 0;
3185 CURL_TRC_CF(data, cf, "configuring OpenSSL's x509 trust store");
3186 if(!store)
3187 return CURLE_OUT_OF_MEMORY;
3189 if(!conn_config->verifypeer) {
3190 infof(data, "SSL Trust: peer verification disabled");
3191 return CURLE_OK;
3192 }
3194 infof(data, "SSL Trust Anchors:");
3195 result = ossl_load_trust_anchors(cf, data, octx, store);
3196 if(result)
3197 return result;
3199 /* Does not make sense to load a CRL file without peer verification */
3200#ifdef USE_APPLE_SECTRUST
3201 if(ssl_crlfile && conn_config->native_ca_store) {
3202 failf(data, "openssl: CRL file not supported with native CA store; "
3203 "the platform verifier has no CRL attachment API");
3204 return CURLE_NOT_BUILT_IN;
3205 }
3206#endif
3207 if(ssl_crlfile) {
3208 /* tell OpenSSL where to find CRL file that is used to check certificate
3209 * revocation */
3210 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
3211 if(!lookup ||
3212 (!X509_load_crl_file(lookup, ssl_crlfile, X509_FILETYPE_PEM))) {
3213 failf(data, "error loading CRL file: %s", ssl_crlfile);
3214 return CURLE_SSL_CRL_BADFILE;
3215 }
3216 x509flags = X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL;
3217 infof(data, " CRLfile: %s", ssl_crlfile);
3218 }
3220 /* Try building a chain using issuers in the trusted store first to avoid
3221 problems with server-sent legacy intermediates. Newer versions of
3222 OpenSSL do alternate chain checking by default but we do not know how to
3223 determine that in a reliable manner.
3224 https://web.archive.org/web/20190422050538/rt.openssl.org/Ticket/Display.html?id=3621
3225 */
3226 x509flags |= X509_V_FLAG_TRUSTED_FIRST;
3228 if(!conn_config->no_partialchain && !ssl_crlfile) {
3229 /* Have intermediate certificates in the trust store be treated as
3230 trust-anchors, in the same way as self-signed root CA certificates are.
3231 This allows users to verify servers using the intermediate cert only,
3232 instead of needing the whole chain.
3234 Due to OpenSSL bug https://github.com/openssl/openssl/issues/5081 we
3235 cannot do partial chains with a CRL check. */
3236 x509flags |= X509_V_FLAG_PARTIAL_CHAIN;
3237 }
3238 (void)X509_STORE_set_flags(store, x509flags);
3240 return result;
3241}
3243/* key to use at `multi->proto_hash` */
3244#define MPROTO_OSSL_X509_KEY "tls:ossl:x509:share"
3246struct ossl_x509_share {
3247 char *CAfile; /* CAfile path used to generate X509 store */
3248 char *CApath; /* CApath path used to generate X509 store */
3249 X509_STORE *store; /* cached X509 store or NULL if none */
3250 struct curltime time; /* when the cached store was created */
3251 BIT(store_is_empty); /* no certs/paths/blobs are in the store */
3252 BIT(no_partialchain); /* keep partial chain state */
3253};
3255static void oss_x509_share_free(const void *key, size_t key_len, void *p)
3256{
3257 struct ossl_x509_share *share = p;
3258 DEBUGASSERT(key_len == CURL_CSTRLEN(MPROTO_OSSL_X509_KEY));
3259 DEBUGASSERT(!memcmp(MPROTO_OSSL_X509_KEY, key, key_len));
3260 (void)key;
3261 (void)key_len;
3262 if(share->store) {
3263 X509_STORE_free(share->store);
3264 }
3265 curlx_free(share->CAfile);
3266 curlx_free(share->CApath);
3267 curlx_free(share);
3268}
3270static bool ossl_cached_x509_store_expired(struct Curl_easy *data,
3271 const struct ossl_x509_share *mb)
3272{
3273 if(data->set.ssl_ca_cache_timeout < 0)
3274 return FALSE;
3275 else {
3276 timediff_t elapsed_ms = curlx_ptimediff_ms(Curl_pgrs_now(data), &mb->time);
3277 timediff_t timeout_ms = data->set.ssl_ca_cache_timeout * (timediff_t)1000;
3279 return elapsed_ms >= timeout_ms;
3280 }
3281}
3283static bool ossl_cached_x509_store_different(struct Curl_cfilter *cf,
3284 const struct Curl_easy *data,
3285 const struct ossl_x509_share *mb)
3286{
3287 struct ssl_filter_config *conn_config = Curl_ssl_cf_get_filter_config(cf);
3288 (void)data;
3289 if(mb->no_partialchain != conn_config->no_partialchain)
3290 return TRUE;
3291 if(!mb->CAfile || !conn_config->CAfile) {
3292 if(mb->CAfile != conn_config->CAfile)
3293 return TRUE;
3294 }
3295 else if(strcmp(mb->CAfile, conn_config->CAfile))
3296 return TRUE;
3298 if(!mb->CApath || !conn_config->CApath) {
3299 if(mb->CApath != conn_config->CApath)
3300 return TRUE;
3301 }
3302 else if(strcmp(mb->CApath, conn_config->CApath))
3303 return TRUE;
3305 return FALSE;
3306}
3308static X509_STORE *ossl_get_cached_x509_store(struct Curl_cfilter *cf,
3309 struct Curl_easy *data,
3310 bool *pempty)
3311{
3312 struct Curl_multi *multi = data->multi;
3313 struct ossl_x509_share *share;
3314 X509_STORE *store = NULL;
3316 DEBUGASSERT(multi);
3317 *pempty = TRUE;
3318 share = multi ? Curl_hash_pick(&multi->proto_hash,
3319 MPROTO_OSSL_X509_KEY,
3320 CURL_CSTRLEN(MPROTO_OSSL_X509_KEY)) : NULL;
3321 if(share && share->store &&
3322 !ossl_cached_x509_store_expired(data, share) &&
3323 !ossl_cached_x509_store_different(cf, data, share)) {
3324 store = share->store;
3325 *pempty = (bool)share->store_is_empty;
3326 }
3328 return store;
3329}
3331static void ossl_set_cached_x509_store(struct Curl_cfilter *cf,
3332 struct Curl_easy *data,
3333 X509_STORE *store,
3334 bool is_empty)
3335{
3336 struct ssl_filter_config *conn_config = Curl_ssl_cf_get_filter_config(cf);
3337 struct Curl_multi *multi = data->multi;
3338 struct ossl_x509_share *share;
3340 DEBUGASSERT(multi);
3341 if(!multi)
3342 return;
3343 share = Curl_hash_pick(&multi->proto_hash,
3344 MPROTO_OSSL_X509_KEY,
3345 CURL_CSTRLEN(MPROTO_OSSL_X509_KEY));
3347 if(!share) {
3348 share = curlx_calloc(1, sizeof(*share));
3349 if(!share)
3350 return;
3351 if(!Curl_hash_add2(&multi->proto_hash,
3352 MPROTO_OSSL_X509_KEY,
3353 CURL_CSTRLEN(MPROTO_OSSL_X509_KEY),
3354 share, oss_x509_share_free)) {
3355 curlx_free(share);
3356 return;
3357 }
3358 }
3360 if(X509_STORE_up_ref(store)) {
3361 char *CAfile = NULL;
3362 char *CApath = NULL;
3364 if(conn_config->CAfile) {
3365 CAfile = curlx_strdup(conn_config->CAfile);
3366 if(!CAfile) {
3367 X509_STORE_free(store);
3368 return;
3369 }
3370 }
3372 if(conn_config->CApath) {
3373 CApath = curlx_strdup(conn_config->CApath);
3374 if(!CApath) {
3375 curlx_free(CAfile);
3376 X509_STORE_free(store);
3377 return;
3378 }
3379 }
3381 if(share->store) {
3382 X509_STORE_free(share->store);
3383 curlx_free(share->CAfile);
3384 curlx_free(share->CApath);
3385 }
3387 share->time = *Curl_pgrs_now(data);
3388 share->store = store;
3389 share->store_is_empty = is_empty;
3390 share->CAfile = CAfile;
3391 share->CApath = CApath;
3392 share->no_partialchain = conn_config->no_partialchain;
3393 }
3394}
3396#ifdef OPENSSL_HAS_PROVIDERS
3397/* CApath certificates loaded under a provider libctx can outlive that libctx
3398 when the store is shared with the multi handle. */
3399#define USING_PROVIDER(octx) octx->p.libctx
3400#else
3401#define USING_PROVIDER(x) 0
3402#endif
3404CURLcode Curl_ssl_setup_x509_store(struct Curl_cfilter *cf,
3405 struct Curl_easy *data,
3406 struct ossl_ctx *octx)
3407{
3408 struct ssl_filter_config *conn_config = Curl_ssl_cf_get_filter_config(cf);
3409 CURLcode result = CURLE_OK;
3410 X509_STORE *cached_store;
3411 bool cache_criteria_met, is_empty;
3413 /* Consider the X509 store cacheable if it comes from CAfile/CApath,
3414 or no source is provided and we are falling back to OpenSSL's built-in
3415 default. */
3416 cache_criteria_met = (data->set.ssl_ca_cache_timeout != 0) &&
3417 conn_config->verifypeer &&
3418 !conn_config->ca_info_blob &&
3419 !conn_config->CRLfile &&
3420 !conn_config->native_ca_store &&
3421 !USING_PROVIDER(octx);
3423 ERR_set_mark();
3425 cached_store = ossl_get_cached_x509_store(cf, data, &is_empty);
3426 if(cached_store && cache_criteria_met && X509_STORE_up_ref(cached_store)) {
3427 SSL_CTX_set_cert_store(octx->ssl_ctx, cached_store);
3428 octx->store_is_empty = is_empty;
3429 }
3430 else {
3431 X509_STORE *store = SSL_CTX_get_cert_store(octx->ssl_ctx);
3433 result = ossl_populate_x509_store(cf, data, octx, store);
3434 if(result == CURLE_OK && cache_criteria_met) {
3435 ossl_set_cached_x509_store(cf, data, store, (bool)octx->store_is_empty);
3436 }
3437 }
3439 ERR_pop_to_mark();
3441 return result;
3442}
3444static bool ossl_apply_session(
3445 struct ossl_ctx *octx,
3446 struct Curl_cfilter *cf,
3447 struct Curl_easy *data,
3448 struct alpn_spec *alpns,
3449 Curl_ossl_init_session_reuse_cb *sess_reuse_cb,
3450 struct Curl_ssl_session *scs)
3451{
3452 struct ssl_filter_config *conn_cfg = Curl_ssl_cf_get_filter_config(cf);
3453 const unsigned char *der_sessionid = scs->sdata;
3454 size_t der_sessionid_size = scs->sdata_len;
3455 SSL_SESSION *ssl_session = NULL;
3457 /* If OpenSSL does not accept the session from the cache, this
3458 * is not an error. We continue without it. */
3459 ssl_session = d2i_SSL_SESSION(NULL, &der_sessionid,
3460 (long)der_sessionid_size);
3461 if(ssl_session) {
3462 if(!SSL_set_session(octx->ssl, ssl_session)) {
3463 VERBOSE(char error_buffer[256]);
3464 infof(data, "SSL: SSL_set_session not accepted, "
3465 "continuing without: %s",
3466 ossl_strerror(ERR_get_error(), error_buffer,
3467 sizeof(error_buffer)));
3468 }
3469 else {
3470 if(conn_cfg->verifypeer &&
3471 (SSL_get_verify_result(octx->ssl) != X509_V_OK)
3472#ifdef USE_APPLE_SECTRUST
3473 /* if sectrust is used and verified the session before */
3474 && (!conn_cfg->native_ca_store || !scs->sectrust_verified)
3475#endif
3476 ) {
3477 /* Session was from unverified connection, cannot reuse here */
3478 SSL_set_session(octx->ssl, NULL);
3479 infof(data, "SSL session not peer verified, not reusing");
3480 }
3481 else {
3482 infof(data, "SSL reusing session with ALPN '%s'",
3483 scs->alpn ? scs->alpn : "-");
3484 octx->reused_session = TRUE;
3485#ifdef USE_APPLE_SECTRUST
3486 octx->sectrust_session = scs->sectrust_verified;
3487#endif
3488 infof(data, "SSL verify result: %lx",
3489 (unsigned long)SSL_get_verify_result(octx->ssl));
3490#ifdef HAVE_OPENSSL_EARLYDATA
3491 if(conn_cfg->earlydata && scs->alpn &&
3492 SSL_SESSION_get_max_early_data(ssl_session) &&
3493 !cf->conn->bits.connect_only &&
3494 (SSL_version(octx->ssl) == TLS1_3_VERSION)) {
3495 bool do_early_data = FALSE;
3496 if(sess_reuse_cb)
3497 (void)sess_reuse_cb(cf, data, alpns, scs, &do_early_data);
3498 if(do_early_data) {
3499 /* We only try the ALPN protocol the session used before,
3500 * otherwise we might send early data for the wrong protocol */
3501 Curl_alpn_restrict_to(alpns, scs->alpn);
3502 }
3503 }
3504#else
3505 (void)alpns;
3506 (void)conn_cfg;
3507 (void)sess_reuse_cb;
3508#endif
3509 }
3510 }
3511 SSL_SESSION_free(ssl_session);
3512 }
3513 else {
3514 infof(data, "SSL session not accepted by OpenSSL, continuing without");
3515 }
3516 return (bool)octx->reused_session;
3517}
3519static CURLcode ossl_init_session_and_alpns(
3520 struct ossl_ctx *octx,
3521 struct Curl_cfilter *cf,
3522 struct Curl_easy *data,
3523 struct ssl_peer *peer,
3524 const struct alpn_spec *alpns_requested,
3525 Curl_ossl_init_session_reuse_cb *sess_reuse_cb)
3526{
3527 struct ssl_filter_config *conn_cfg = Curl_ssl_cf_get_filter_config(cf);
3528 struct alpn_spec alpns;
3529 CURLcode result;
3531 Curl_alpn_copy(&alpns, alpns_requested);
3533 octx->reused_session = FALSE;
3535 if((cf->sockindex == SECONDARYSOCKET) && !(cf->cft->flags & CF_TYPE_PROXY)) {
3536 /* FTP is a bitch. On TLS secured transfers, it is a common server
3537 * option to require the client to use the SAME TLS session as on
3538 * the control connection or it fails the request. See #22225. */
3539 struct Curl_ssl_session *scs =
3540 Curl_ssl_get_cf_session(data, cf->cft, FIRSTSOCKET);
3541 if(scs) {
3542 if(ossl_apply_session(octx, cf, data, &alpns, sess_reuse_cb, scs))
3543 CURL_TRC_CF(data, cf, "applied SSL session from control connection");
3544 }
3545 }
3547 if(!octx->reused_session &&
3548 Curl_ssl_scache_use(cf, data) && !conn_cfg->verifystatus) {
3549 struct Curl_ssl_session *scs = NULL;
3551 result = Curl_ssl_scache_take(cf, data, peer->scache_key, &scs);
3552 if(!result && scs && scs->sdata && scs->sdata_len) {
3553 (void)ossl_apply_session(octx, cf, data, &alpns, sess_reuse_cb, scs);
3554 }
3555 Curl_ssl_scache_return(cf, data, peer->scache_key, scs);
3556 }
3558 if(alpns.count) {
3559 struct alpn_proto_buf proto;
3560 memset(&proto, 0, sizeof(proto));
3561 result = Curl_alpn_to_proto_buf(&proto, &alpns);
3562 if(result) {
3563 failf(data, "Error determining ALPN");
3564 return CURLE_SSL_CONNECT_ERROR;
3565 }
3566 if(SSL_set_alpn_protos(octx->ssl, proto.data, proto.len)) {
3567 failf(data, "Error setting ALPN");
3568 return CURLE_SSL_CONNECT_ERROR;
3569 }
3570 }
3572 return CURLE_OK;
3573}
3575#ifdef HAVE_SSL_SET1_ECH_CONFIG_LIST
3576static CURLcode ossl_init_ech(struct ossl_ctx *octx,
3577 struct Curl_cfilter *cf,
3578 struct Curl_easy *data,
3579 struct ssl_peer *peer)
3580{
3581 struct ssl_filter_config *conn_config = Curl_ssl_cf_get_filter_config(cf);
3582 int trying_ech_now = 0;
3584 if(!Curl_ssl_ech_enabled(cf))
3585 return CURLE_OK;
3587 if(conn_config->ech == CURLECH_GREASE) {
3588 infof(data, "ECH: will GREASE ClientHello");
3589#ifdef HAVE_BORINGSSL_LIKE
3590 SSL_set_enable_ech_grease(octx->ssl, 1);
3591#else
3592 SSL_set_options(octx->ssl, SSL_OP_ECH_GREASE);
3593#endif
3594 }
3595 else if(conn_config->ech && conn_config->ech_config) {
3596#ifdef HAVE_BORINGSSL_LIKE
3597 uint8_t *ech_config;
3598 size_t ech_config_len = 0;
3599 CURLcode result;
3601 if(!conn_config->ech_config[0]) {
3602 infof(data, "ECH: ECHConfig from command line empty");
3603 return CURLE_SSL_CONNECT_ERROR;
3604 }
3605 ech_config_len = 2 * strlen(conn_config->ech_config);
3606 result = curlx_base64_decode(conn_config->ech_config,
3607 &ech_config, &ech_config_len);
3608 if(result || !ech_config) {
3609 infof(data, "ECH: cannot base64 decode ECHConfig from command line");
3610 if(conn_config->ech == CURLECH_HARD)
3611 return result;
3612 }
3613 if(SSL_set1_ech_config_list(octx->ssl, ech_config, ech_config_len) != 1) {
3614 infof(data, "ECH: SSL_ECH_set1_ech_config_list failed");
3615 if(conn_config->ech == CURLECH_HARD) {
3616 curlx_free(ech_config);
3617 return CURLE_SSL_CONNECT_ERROR;
3618 }
3619 }
3620 curlx_free(ech_config);
3621 trying_ech_now = 1;
3622#else
3623 size_t ech_config_len = 0;
3624 if(!conn_config->ech_config[0]) {
3625 infof(data, "ECH: ECHConfig from command line empty");
3626 return CURLE_SSL_CONNECT_ERROR;
3627 }
3628 ech_config_len = strlen(conn_config->ech_config);
3629 if(SSL_set1_ech_config_list(octx->ssl,
3630 (const uint8_t *)conn_config->ech_config,
3631 ech_config_len) != 1) {
3632 infof(data, "ECH: SSL_ECH_set1_ech_config_list failed");
3633 if(conn_config->ech == CURLECH_HARD)
3634 return CURLE_SSL_CONNECT_ERROR;
3635 }
3636 else
3637 trying_ech_now = 1;
3638#endif /* HAVE_BORINGSSL_LIKE */
3639 infof(data, "ECH: ECHConfig from command line");
3640 }
3641 else {
3642 const struct Curl_https_rrinfo *rinfo =
3643 Curl_conn_dns_get_https(data, cf->sockindex, peer->origin);
3645 if(Curl_httpsrr_is_for_peer(peer->origin, rinfo) && rinfo->echconfiglist) {
3646 const unsigned char *ecl = rinfo->echconfiglist;
3647 size_t elen = rinfo->echconfiglist_len;
3649 infof(data, "ECH: ECHConfig from HTTPS RR");
3650 if(SSL_set1_ech_config_list(octx->ssl, ecl, elen) != 1) {
3651 infof(data, "ECH: SSL_set1_ech_config_list failed");
3652 if(conn_config->ech == CURLECH_HARD)
3653 return CURLE_SSL_CONNECT_ERROR;
3654 }
3655 else {
3656 trying_ech_now = 1;
3657 infof(data, "ECH: imported ECHConfigList of length %zu", elen);
3658 }
3659 }
3660 else {
3661 infof(data, "ECH: requested but no ECHConfig available");
3662 if(conn_config->ech == CURLECH_HARD)
3663 return CURLE_SSL_CONNECT_ERROR;
3664 }
3665 }
3666#ifdef HAVE_BORINGSSL_LIKE
3667 (void)peer;
3668 if(trying_ech_now && conn_config->ech_public) {
3669 infof(data, "ECH: setting public_name not supported with BoringSSL");
3670 return CURLE_SSL_CONNECT_ERROR;
3671 }
3672#else
3673 if(trying_ech_now && conn_config->ech_public) {
3674 int ret;
3675 infof(data, "ECH: inner: '%s', outer: '%s'",
3676 peer->origin->hostname ? peer->origin->hostname : "NULL",
3677 conn_config->ech_public);
3678 ret = SSL_ech_set1_server_names(octx->ssl,
3679 peer->origin->hostname,
3680 conn_config->ech_public,
3681 0 /* do send outer */);
3682 if(ret != 1) {
3683 infof(data, "ECH: rv failed to set server name(s) %d [ERROR]", ret);
3684 return CURLE_SSL_CONNECT_ERROR;
3685 }
3686 }
3687#endif /* HAVE_BORINGSSL_LIKE */
3688 if(trying_ech_now &&
3689 SSL_set_min_proto_version(octx->ssl, TLS1_3_VERSION) != 1) {
3690 infof(data, "ECH: cannot force TLSv1.3 [ERROR]");
3691 return CURLE_SSL_CONNECT_ERROR;
3692 }
3694 return CURLE_OK;
3695}
3696#endif /* else HAVE_SSL_SET1_ECH_CONFIG_LIST */
3698static CURLcode ossl_init_ssl(struct ossl_ctx *octx,
3699 struct Curl_cfilter *cf,
3700 struct Curl_easy *data,
3701 struct ssl_peer *peer,
3702 const struct alpn_spec *alpns_requested,
3703 void *ssl_user_data,
3704 Curl_ossl_init_session_reuse_cb *sess_reuse_cb)
3705{
3706 /* Let's make an SSL structure */
3707 if(octx->ssl)
3708 SSL_free(octx->ssl);
3709 octx->ssl = SSL_new(octx->ssl_ctx);
3710 if(!octx->ssl) {
3711 failf(data, "SSL: could not create a context (handle)");
3712 return CURLE_OUT_OF_MEMORY;
3713 }
3715 SSL_set_app_data(octx->ssl, ssl_user_data);
3717#ifndef OPENSSL_NO_OCSP
3718 if(Curl_ssl_cf_get_filter_config(cf)->verifystatus)
3719 SSL_set_tlsext_status_type(octx->ssl, TLSEXT_STATUSTYPE_ocsp);
3720#endif
3722 SSL_set_connect_state(octx->ssl);
3724 if(peer->sni) {
3725 if(!SSL_set_tlsext_host_name(octx->ssl, peer->sni)) {
3726 failf(data, "Failed set SNI");
3727 return CURLE_SSL_CONNECT_ERROR;
3728 }
3729 }
3731#ifdef HAVE_SSL_SET1_ECH_CONFIG_LIST
3732 {
3733 CURLcode result = ossl_init_ech(octx, cf, data, peer);
3734 if(result)
3735 return result;
3736 }
3737#endif /* HAVE_SSL_SET1_ECH_CONFIG_LIST */
3739 return ossl_init_session_and_alpns(octx, cf, data, peer,
3740 alpns_requested, sess_reuse_cb);
3741}
3743static CURLcode ossl_init_method(struct Curl_cfilter *cf,
3744 struct Curl_easy *data,
3745 struct ssl_peer *peer,
3746 const SSL_METHOD **pmethod,
3747 unsigned int *pssl_version_min)
3748{
3749 struct ssl_filter_config *conn_config = Curl_ssl_cf_get_filter_config(cf);
3751 *pmethod = NULL;
3752 *pssl_version_min = conn_config->version;
3753 DEBUGASSERT(conn_config->version != CURL_SSLVERSION_DEFAULT);
3754 switch(peer->transport) {
3755 case TRNSPRT_TCP:
3756 /* check to see if we have been told to use an explicit SSL/TLS version */
3757 switch(*pssl_version_min) {
3758 case CURL_SSLVERSION_TLSv1:
3759 case CURL_SSLVERSION_TLSv1_0:
3760 case CURL_SSLVERSION_TLSv1_1:
3761 case CURL_SSLVERSION_TLSv1_2:
3762 case CURL_SSLVERSION_TLSv1_3:
3763 /* it is handled later with the context options */
3764 *pmethod = TLS_client_method();
3765 break;
3766 case CURL_SSLVERSION_SSLv2:
3767 failf(data, "No SSLv2 support");
3768 return CURLE_NOT_BUILT_IN;
3769 case CURL_SSLVERSION_SSLv3:
3770 failf(data, "No SSLv3 support");
3771 return CURLE_NOT_BUILT_IN;
3772 default:
3773 failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION");
3774 return CURLE_SSL_CONNECT_ERROR;
3775 }
3776 break;
3777 case TRNSPRT_QUIC:
3778 *pssl_version_min = CURL_SSLVERSION_TLSv1_3;
3779 if(conn_config->version_max &&
3780 (conn_config->version_max != CURL_SSLVERSION_MAX_DEFAULT) &&
3781 (conn_config->version_max != CURL_SSLVERSION_MAX_TLSv1_3)) {
3782 failf(data, "QUIC needs at least TLS version 1.3");
3783 return CURLE_SSL_CONNECT_ERROR;
3784 }
3786 *pmethod = TLS_method();
3787 break;
3788 default:
3789 failf(data, "unsupported transport %d in SSL init", peer->transport);
3790 return CURLE_SSL_CONNECT_ERROR;
3791 }
3793 return *pmethod ? CURLE_OK : CURLE_SSL_CONNECT_ERROR;
3794}
3796CURLcode Curl_ossl_ctx_init(struct ossl_ctx *octx,
3797 struct Curl_cfilter *cf,
3798 struct Curl_easy *data,
3799 struct ssl_peer *peer,
3800 const struct alpn_spec *alpns_requested,
3801 Curl_ossl_ctx_setup_cb *cb_setup,
3802 void *cb_user_data,
3803 Curl_ossl_new_session_cb *cb_new_session,
3804 void *ssl_user_data,
3805 Curl_ossl_init_session_reuse_cb *sess_reuse_cb)
3806{
3807 CURLcode result = CURLE_OK;
3808 const char *ciphers;
3809 const SSL_METHOD *req_method = NULL;
3810 ctx_option_t ctx_options = 0;
3811 struct ssl_filter_config *conn_config = Curl_ssl_cf_get_filter_config(cf);
3812 struct ssl_easy_config *ssl_config = Curl_ssl_cf_get_easy_config(cf, data);
3813 char * const ssl_cert = conn_config->clientcert;
3814 const struct curl_blob *ssl_cert_blob = conn_config->cert_blob;
3815 const char * const ssl_cert_type = conn_config->cert_type;
3816 unsigned int ssl_version_min = CURL_SSLVERSION_DEFAULT;
3817 char error_buffer[256];
3819 /* Make funny stuff to get random input */
3820 result = ossl_seed(data);
3821 if(!result) {
3822 if(CURL_EASY_STR(data, STRING_SSL_ENGINE))
3823 result = ossl_set_engine(data, octx,
3824 CURL_EASY_STR(data, STRING_SSL_ENGINE));
3825 if(!result && data->set.engine_default)
3826 result = ossl_set_engine_default(data, octx);
3827 }
3829 if(!result) {
3830 ssl_config->certverifyresult = !X509_V_OK;
3831 result = ossl_init_method(cf, data, peer, &req_method, &ssl_version_min);
3832 }
3833 if(result)
3834 return result;
3835 DEBUGASSERT(req_method);
3837 DEBUGASSERT(!octx->ssl_ctx);
3838 octx->ssl_ctx =
3839#ifdef OPENSSL_HAS_PROVIDERS
3840 octx->p.libctx ?
3841 SSL_CTX_new_ex(octx->p.libctx, octx->p.propq, req_method):
3842#endif
3843 SSL_CTX_new(req_method);
3845 if(!octx->ssl_ctx) {
3846 failf(data, "SSL: could not create a context: %s",
3847 ossl_strerror(ERR_peek_error(), error_buffer, sizeof(error_buffer)));
3848 return CURLE_OUT_OF_MEMORY;
3849 }
3851 if(cb_setup) {
3852 result = cb_setup(cf, data, cb_user_data);
3853 if(result)
3854 return result;
3855 }
3857 if(data->set.fdebug && data->set.verbose &&
3858 (peer->transport != TRNSPRT_QUIC)) {
3859 /* the SSL trace callback is only used for verbose logging;
3860 * QUIC connections use a different TLS record format that
3861 * ossl_trace cannot handle */
3862 SSL_CTX_set_msg_callback(octx->ssl_ctx, ossl_trace);
3863 SSL_CTX_set_msg_callback_arg(octx->ssl_ctx, cf);
3864 }
3866 /* OpenSSL contains code to work around lots of bugs and flaws in various
3867 SSL-implementations. SSL_CTX_set_options() is used to enable those
3868 workarounds. The man page for this option states that SSL_OP_ALL enables
3869 all the workarounds and that "It is usually safe to use SSL_OP_ALL to
3870 enable the bug workaround options if compatibility with somewhat broken
3871 implementations is desired."
3873 The "-no_ticket" option was introduced in OpenSSL 0.9.8j. it is a flag to
3874 disable "rfc4507bis session ticket support". rfc4507bis was later turned
3875 into the proper RFC5077: https://datatracker.ietf.org/doc/html/rfc5077
3877 The enabled extension concerns the session management. I wonder how often
3878 libcurl stops a connection and then resumes a TLS session. Also, sending
3879 the session data is some overhead. I suggest that you use your proposed
3880 patch (which explicitly disables TICKET).
3882 If someone writes an application with libcurl and OpenSSL who wants to
3883 enable the feature, one can do this in the SSL callback.
3885 SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG option enabling allowed proper
3886 interoperability with web server Netscape Enterprise Server 2.0.1 which
3887 was released back in 1996.
3889 Due to CVE-2010-4180, option SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG has
3890 become ineffective as of OpenSSL 0.9.8q and 1.0.0c. In order to mitigate
3891 CVE-2010-4180 when using previous OpenSSL versions we no longer enable
3892 this option regardless of OpenSSL version and SSL_OP_ALL definition.
3894 OpenSSL added a workaround for an SSL 3.0/TLS 1.0 CBC vulnerability:
3895 https://web.archive.org/web/20240114184648/openssl.org/~bodo/tls-cbc.txt.
3896 In 0.9.6e they added a bit to SSL_OP_ALL that _disables_ that workaround
3897 despite the fact that SSL_OP_ALL is documented to do "rather harmless"
3898 workarounds. In order to keep the secure workaround, the
3899 SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS bit must not be set. */
3901 ctx_options = SSL_OP_ALL | SSL_OP_NO_TICKET | SSL_OP_NO_COMPRESSION;
3903 /* mitigate CVE-2010-4180 */
3904 ctx_options &= ~(ctx_option_t)SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG;
3906 /* unless the user explicitly asks to allow the protocol vulnerability we
3907 use the workaround */
3908 if(!conn_config->enable_beast)
3909 ctx_options &= ~(ctx_option_t)SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
3911 DEBUGASSERT(ssl_version_min != CURL_SSLVERSION_DEFAULT);
3912 switch(ssl_version_min) {
3913 case CURL_SSLVERSION_SSLv2:
3914 case CURL_SSLVERSION_SSLv3:
3915 return CURLE_NOT_BUILT_IN;
3917 /* "--tlsv<x.y>" options mean TLS >= version <x.y> */
3918 case CURL_SSLVERSION_TLSv1: /* TLS >= version 1.0 */
3919 case CURL_SSLVERSION_TLSv1_0: /* TLS >= version 1.0 */
3920 case CURL_SSLVERSION_TLSv1_1: /* TLS >= version 1.1 */
3921 case CURL_SSLVERSION_TLSv1_2: /* TLS >= version 1.2 */
3922 case CURL_SSLVERSION_TLSv1_3: /* TLS >= version 1.3 */
3923 /* asking for any TLS version as the minimum, means no SSL versions
3924 allowed */
3925 ctx_options |= SSL_OP_NO_SSLv2;
3926 ctx_options |= SSL_OP_NO_SSLv3;
3928 result = ossl_set_ssl_version_min_max(cf, octx->ssl_ctx, ssl_version_min);
3929 if(result)
3930 return result;
3931 break;
3933 default:
3934 failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION");
3935 return CURLE_SSL_CONNECT_ERROR;
3936 }
3938 SSL_CTX_set_options(octx->ssl_ctx, ctx_options);
3939 SSL_CTX_set_read_ahead(octx->ssl_ctx, 1);
3941 /* Max TLS1.2 record size 0x4000 + 0x800.
3942 OpenSSL supports processing "jumbo TLS record" (8 TLS records) in one go
3943 for some algorithms, so match that here.
3944 Experimentation shows that a slightly larger buffer is needed
3945 to avoid short reads.
3947 However using a large buffer (8 packets) actually decreases performance.
3948 4 packets is better.
3949 */
3950#ifdef HAVE_SSL_CTX_SET_DEFAULT_READ_BUFFER_LEN
3951 SSL_CTX_set_default_read_buffer_len(octx->ssl_ctx, 0x401e * 4);
3952#endif
3954 /* We do retry writes sometimes from another buffer address */
3955 SSL_CTX_set_mode(octx->ssl_ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
3957 ciphers = conn_config->cipher_list;
3958 if(!ciphers && (peer->transport != TRNSPRT_QUIC))
3959 ciphers = NULL;
3960 if(ciphers && (ssl_version_min < CURL_SSLVERSION_TLSv1_3)) {
3961 if(!SSL_CTX_set_cipher_list(octx->ssl_ctx, ciphers)) {
3962 failf(data, "failed setting cipher list: %s", ciphers);
3963 return CURLE_SSL_CIPHER;
3964 }
3965 infof(data, "Cipher selection: %s", ciphers);
3966 }
3968#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
3969 {
3970 const char *ciphers13 = conn_config->cipher_list13;
3971 if(ciphers13 &&
3972 (!conn_config->version_max ||
3973 (conn_config->version_max == CURL_SSLVERSION_MAX_DEFAULT) ||
3974 (conn_config->version_max >= CURL_SSLVERSION_MAX_TLSv1_3))) {
3975 if(!SSL_CTX_set_ciphersuites(octx->ssl_ctx, ciphers13)) {
3976 failf(data, "failed setting TLS 1.3 cipher suite: %s", ciphers13);
3977 return CURLE_SSL_CIPHER;
3978 }
3979 infof(data, "TLS 1.3 cipher selection: %s", ciphers13);
3980 }
3981 }
3982#endif
3984 if(ssl_cert || ssl_cert_blob || ssl_cert_type) {
3985 result = client_cert(data, octx,
3986 ssl_cert, ssl_cert_blob, ssl_cert_type,
3987 conn_config->key, conn_config->key_blob,
3988 conn_config->key_type,
3989 conn_config->key_passwd);
3990 if(result)
3991 /* failf() is already done in client_cert() */
3992 return result;
3993 }
3995#ifdef HAVE_SSL_CTX_SET_POST_HANDSHAKE_AUTH
3996 /* OpenSSL 1.1.1 requires clients to opt-in for PHA */
3997 SSL_CTX_set_post_handshake_auth(octx->ssl_ctx, 1);
3998#endif
4000 {
Diagnostics4 git calls · 161 ms
CallStatusSizeTime0161 ms
discover200152 B3 ms
git.upload-pack discover http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=3 git.response.bytes=152 git.server.agent=gitty/1.0 git.server.object_format=sha1 git.server.caps=agent ls-refs fetch object-format git.server.fetch=shallow filter sideband-all git.protocol.version=2 git.pkt.frames=8 git.pkt.data=6 git.pkt.flush=2 git.pkt.delim=0 git.pkt.bytes=152 git.pkt.payload.max=34
ls-refs200149 B · hit3 ms
git.upload-pack ls-refs http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=3 git.response.bytes=149 git.response.cache=HIT git.response.duration_ms=3 git.protocol.version=2 git.pkt.frames=3 git.pkt.data=2 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=149 git.pkt.payload.max=78 git.ls_refs.count=2 git.ls_refs.head=refs/heads/master
fetchblob:none · deepen 10200287 KiB · hit2 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=2 git.response.bytes=293470 git.response.cache=HIT git.response.duration_ms=2 git.fetch.filter=blob:none git.fetch.filter.requested=tree:0 git.fetch.filter.fallback=blob:none git.fetch.filter.learned=false git.fetch.wants=31c911efe5652725e930f4d2e60c9060e5f6646d git.fetch.haves.count=0 git.fetch.deepen=10 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=10 git.pkt.data=8 git.pkt.flush=1 git.pkt.delim=1 git.pkt.bytes=293470 git.pkt.payload.max=65516 git.sideband.band1.bytes=293354 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=87 git.pack.bytes=293354 git.pack.ofs_delta=0 git.pack.ref_delta=1 git.pack.chain.max=1 git.pack.trailer=6a646bcda6740bab42e321b51998b52ea15146c0 git.pack.full=86Open pack map
fetch20049 KiB156 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=156 git.response.bytes=49760 git.response.cache=MISS git.response.duration_ms=156 git.fetch.wants=517f9c258ebbce6a9b218324bd6234b9512cae46 git.fetch.haves.count=0 git.fetch.deepen=0 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=3 git.pkt.data=2 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=49760 git.pkt.payload.max=49739 git.sideband.band1.bytes=49738 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0
Each row is one HTTP round trip ply made to the git server for this page, on one timeline. discover asks what the server speaks, ls-refs lists branch tips, fetch brings objects by id. A hit was served by Workers Cache. Tap a row for its wire details.
- Remote
- https://5ad2236b39de4c8bd8f6270ea63f3ea9.artifacts.cloudflare.net/git/public-v0/curl.git
- Ref
- refs/heads/master
- Commit
- 31c911efe5652725e930f4d2e60c9060e5f6646d
- cf-ray
- a5e2ffe8ba1af3c9
- Request
- 28a29076…
- Protocol
- v2 · sha1
- Agent
- gitty/1.0
- Filter
- advertised
- Fetch
- shallow filter sideband-all
- Capabilities
- agent ls-refs fetch object-format