openssl.c (174680B)
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 /* 26 * Source file for all OpenSSL-specific code for the TLS/SSL layer. No code 27 * but vtls.c should ever call or use these functions. 28 */ 29 30 #include "../curl_setup.h" 31 32 #if defined(USE_QUICHE) || defined(USE_OPENSSL) 33 34 #include <limits.h> 35 36 /* Wincrypt must be included before anything that could include OpenSSL. */ 37 #ifdef USE_WIN32_CRYPTO 38 #include <wincrypt.h> 39 /* Undefine wincrypt conflicting symbols for BoringSSL. */ 40 #undef X509_NAME 41 #undef X509_EXTENSIONS 42 #undef PKCS7_ISSUER_AND_SERIAL 43 #undef PKCS7_SIGNER_INFO 44 #undef OCSP_REQUEST 45 #undef OCSP_RESPONSE 46 #endif 47 48 #include "../urldata.h" 49 #include "../sendf.h" 50 #include "../formdata.h" /* for the boundary function */ 51 #include "../url.h" /* for the ssl config check function */ 52 #include "../curlx/inet_pton.h" 53 #include "openssl.h" 54 #include "../connect.h" 55 #include "../slist.h" 56 #include "../select.h" 57 #include "../curlx/wait.h" 58 #include "vtls.h" 59 #include "vtls_int.h" 60 #include "vtls_scache.h" 61 #include "../vauth/vauth.h" 62 #include "keylog.h" 63 #include "hostcheck.h" 64 #include "../multiif.h" 65 #include "../curlx/strparse.h" 66 #include "../strdup.h" 67 #include "../strerror.h" 68 #include "../curl_printf.h" 69 70 #include <openssl/ssl.h> 71 #include <openssl/rand.h> 72 #include <openssl/x509v3.h> 73 #ifndef OPENSSL_NO_DSA 74 #include <openssl/dsa.h> 75 #endif 76 #include <openssl/dh.h> 77 #include <openssl/err.h> 78 #include <openssl/md5.h> 79 #include <openssl/conf.h> 80 #include <openssl/bn.h> 81 #include <openssl/rsa.h> 82 #include <openssl/bio.h> 83 #include <openssl/buffer.h> 84 #include <openssl/pkcs12.h> 85 #include <openssl/tls1.h> 86 #include <openssl/evp.h> 87 88 #ifdef HAVE_SSL_SET1_ECH_CONFIG_LIST 89 #define USE_ECH_OPENSSL 90 #endif 91 92 #ifdef USE_ECH_OPENSSL 93 # if !defined(OPENSSL_IS_BORINGSSL) && !defined(OPENSSL_IS_AWSLC) 94 # include <openssl/ech.h> 95 # endif 96 #endif /* USE_ECH_OPENSSL */ 97 98 #ifndef OPENSSL_NO_OCSP 99 #include <openssl/ocsp.h> 100 #endif 101 102 #if !defined(OPENSSL_NO_ENGINE) && !defined(OPENSSL_NO_UI_CONSOLE) 103 #define USE_OPENSSL_ENGINE 104 #include <openssl/engine.h> 105 #endif 106 107 #ifdef LIBRESSL_VERSION_NUMBER 108 # /* As of LibreSSL 2.0.0-4.0.0: OPENSSL_VERSION_NUMBER == 0x20000000L */ 109 # if LIBRESSL_VERSION_NUMBER < 0x2090100fL /* 2019-04-13 */ 110 # error "LibreSSL 2.9.1 or later required" 111 # endif 112 #elif OPENSSL_VERSION_NUMBER < 0x1000201fL /* 2015-03-19 */ 113 # error "OpenSSL 1.0.2a or later required" 114 #endif 115 116 #if OPENSSL_VERSION_NUMBER >= 0x3000000fL && !defined(OPENSSL_NO_UI_CONSOLE) 117 #include <openssl/provider.h> 118 #include <openssl/store.h> 119 /* this is used in the following conditions to make them easier to read */ 120 #define OPENSSL_HAS_PROVIDERS 121 122 static void ossl_provider_cleanup(struct Curl_easy *data); 123 #endif 124 125 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L && \ 126 !defined(LIBRESSL_VERSION_NUMBER) && \ 127 !defined(OPENSSL_IS_BORINGSSL)) 128 #define HAVE_SSL_CTX_SET_DEFAULT_READ_BUFFER_LEN 1 129 #endif 130 131 #include "../curlx/warnless.h" 132 133 /* The last #include files should be: */ 134 #include "../curl_memory.h" 135 #include "../memdebug.h" 136 137 /* Uncomment the ALLOW_RENEG line to a real #define if you want to allow TLS 138 renegotiations when built with BoringSSL. Renegotiating is non-compliant 139 with HTTP/2 and "an extremely dangerous protocol feature". Beware. 140 141 #define ALLOW_RENEG 1 142 */ 143 144 #ifndef OPENSSL_VERSION_NUMBER 145 #error "OPENSSL_VERSION_NUMBER not defined" 146 #endif 147 148 #if defined(USE_OPENSSL_ENGINE) || defined(OPENSSL_HAS_PROVIDERS) 149 #include <openssl/ui.h> 150 #endif 151 152 #if OPENSSL_VERSION_NUMBER >= 0x10100000L 153 #define OSSL_UI_METHOD_CAST(x) (x) 154 #else 155 #define OSSL_UI_METHOD_CAST(x) CURL_UNCONST(x) 156 #endif 157 158 #if OPENSSL_VERSION_NUMBER >= 0x10100000L /* OpenSSL 1.1.0+ and LibreSSL */ 159 #define HAVE_X509_GET0_EXTENSIONS 1 /* added in 1.1.0 -pre1 */ 160 #define HAVE_OPAQUE_EVP_PKEY 1 /* since 1.1.0 -pre3 */ 161 #define HAVE_OPAQUE_RSA_DSA_DH 1 /* since 1.1.0 -pre5 */ 162 #define HAVE_ERR_REMOVE_THREAD_STATE_DEPRECATED 1 163 #else 164 /* For OpenSSL before 1.1.0 */ 165 #define ASN1_STRING_get0_data(x) ASN1_STRING_data(x) 166 #define X509_get0_notBefore(x) X509_get_notBefore(x) 167 #define X509_get0_notAfter(x) X509_get_notAfter(x) 168 #define OpenSSL_version_num() SSLeay() 169 #endif 170 171 #if OPENSSL_VERSION_NUMBER >= 0x10002003L && \ 172 OPENSSL_VERSION_NUMBER <= 0x10002FFFL && \ 173 !defined(OPENSSL_NO_COMP) 174 #define HAVE_SSL_COMP_FREE_COMPRESSION_METHODS 1 175 #endif 176 177 #if (OPENSSL_VERSION_NUMBER >= 0x30000000L) 178 #define HAVE_EVP_PKEY_GET_PARAMS 1 179 #endif 180 181 #ifdef HAVE_EVP_PKEY_GET_PARAMS 182 #include <openssl/core_names.h> 183 #define DECLARE_PKEY_PARAM_BIGNUM(name) BIGNUM *name = NULL 184 #define FREE_PKEY_PARAM_BIGNUM(name) BN_clear_free(name) 185 #else 186 #define DECLARE_PKEY_PARAM_BIGNUM(name) const BIGNUM *name 187 #define FREE_PKEY_PARAM_BIGNUM(name) 188 #endif 189 190 /* Whether SSL_CTX_set_ciphersuites is available. 191 * OpenSSL: supported since 1.1.1 (commit a53b5be6a05) 192 * BoringSSL: no 193 * LibreSSL: supported since 3.4.1 (released 2021-10-14) 194 */ 195 #if ((OPENSSL_VERSION_NUMBER >= 0x10101000L && \ 196 !defined(LIBRESSL_VERSION_NUMBER)) || \ 197 (defined(LIBRESSL_VERSION_NUMBER) && \ 198 LIBRESSL_VERSION_NUMBER >= 0x3040100fL)) && \ 199 !defined(OPENSSL_IS_BORINGSSL) 200 #define HAVE_SSL_CTX_SET_CIPHERSUITES 201 #ifndef OPENSSL_IS_AWSLC 202 #define HAVE_SSL_CTX_SET_POST_HANDSHAKE_AUTH 203 #endif 204 #endif 205 206 /* Whether SSL_CTX_set1_sigalgs_list is available 207 * OpenSSL: supported since 1.0.2 (commit 0b362de5f575) 208 * BoringSSL: supported since 0.20240913.0 (commit 826ce15) 209 * LibreSSL: no 210 */ 211 #if (OPENSSL_VERSION_NUMBER >= 0x10002000L && \ 212 !defined(LIBRESSL_VERSION_NUMBER)) 213 #define HAVE_SSL_CTX_SET1_SIGALGS 214 #endif 215 216 #ifdef LIBRESSL_VERSION_NUMBER 217 #define OSSL_PACKAGE "LibreSSL" 218 #elif defined(OPENSSL_IS_BORINGSSL) 219 #define OSSL_PACKAGE "BoringSSL" 220 #elif defined(OPENSSL_IS_AWSLC) 221 #define OSSL_PACKAGE "AWS-LC" 222 #elif (defined(USE_NGTCP2) && defined(USE_NGHTTP3) && \ 223 !defined(OPENSSL_QUIC_API2)) || defined(USE_MSH3) 224 #define OSSL_PACKAGE "quictls" 225 #else 226 #define OSSL_PACKAGE "OpenSSL" 227 #endif 228 229 #if defined(OPENSSL_IS_BORINGSSL) || defined(OPENSSL_IS_AWSLC) 230 typedef size_t numcert_t; 231 #else 232 typedef int numcert_t; 233 #endif 234 #define ossl_valsize_t numcert_t 235 236 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) 237 /* up2date versions of OpenSSL maintain reasonably secure defaults without 238 * breaking compatibility, so it is better not to override the defaults in curl 239 */ 240 #define DEFAULT_CIPHER_SELECTION NULL 241 #else 242 /* not the case with old versions of OpenSSL */ 243 #define DEFAULT_CIPHER_SELECTION \ 244 "ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH" 245 #endif 246 247 #ifdef HAVE_OPENSSL_SRP 248 /* the function exists */ 249 #ifdef USE_TLS_SRP 250 /* the functionality is not disabled */ 251 #define USE_OPENSSL_SRP 252 #endif 253 #endif 254 255 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) 256 #define HAVE_RANDOM_INIT_BY_DEFAULT 1 257 #endif 258 259 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && \ 260 !defined(OPENSSL_IS_BORINGSSL) && \ 261 !defined(OPENSSL_IS_AWSLC) 262 #define HAVE_OPENSSL_VERSION 263 #endif 264 265 #if defined(OPENSSL_IS_BORINGSSL) || defined(OPENSSL_IS_AWSLC) 266 typedef uint32_t sslerr_t; 267 #else 268 typedef unsigned long sslerr_t; 269 #endif 270 271 /* 272 * Whether the OpenSSL version has the API needed to support sharing an 273 * X509_STORE between connections. The API is: 274 * * `X509_STORE_up_ref` -- Introduced: OpenSSL 1.1.0. 275 */ 276 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) /* OpenSSL >= 1.1.0 */ 277 #define HAVE_SSL_X509_STORE_SHARE 278 #endif 279 280 static CURLcode ossl_certchain(struct Curl_easy *data, SSL *ssl); 281 282 static CURLcode push_certinfo(struct Curl_easy *data, 283 BIO *mem, const char *label, int num) 284 WARN_UNUSED_RESULT; 285 286 static CURLcode push_certinfo(struct Curl_easy *data, 287 BIO *mem, const char *label, int num) 288 { 289 char *ptr; 290 long len = BIO_get_mem_data(mem, &ptr); 291 CURLcode result = Curl_ssl_push_certinfo_len(data, num, label, ptr, len); 292 (void)BIO_reset(mem); 293 return result; 294 } 295 296 static CURLcode pubkey_show(struct Curl_easy *data, 297 BIO *mem, 298 int num, 299 const char *type, 300 const char *name, 301 const BIGNUM *bn) 302 { 303 char namebuf[32]; 304 305 msnprintf(namebuf, sizeof(namebuf), "%s(%s)", type, name); 306 307 if(bn) 308 BN_print(mem, bn); 309 return push_certinfo(data, mem, namebuf, num); 310 } 311 312 #ifdef HAVE_OPAQUE_RSA_DSA_DH 313 #define print_pubkey_BN(_type, _name, _num) \ 314 pubkey_show(data, mem, _num, #_type, #_name, _name) 315 316 #else 317 #define print_pubkey_BN(_type, _name, _num) \ 318 do { \ 319 if(_type->_name) { \ 320 pubkey_show(data, mem, _num, #_type, #_name, _type->_name); \ 321 } \ 322 } while(0) 323 #endif 324 325 static int asn1_object_dump(ASN1_OBJECT *a, char *buf, size_t len) 326 { 327 int i, ilen; 328 329 ilen = (int)len; 330 if(ilen < 0) 331 return 1; /* buffer too big */ 332 333 i = i2t_ASN1_OBJECT(buf, ilen, a); 334 335 if(i >= ilen) 336 return 1; /* buffer too small */ 337 338 return 0; 339 } 340 341 static CURLcode X509V3_ext(struct Curl_easy *data, 342 int certnum, 343 const STACK_OF(X509_EXTENSION) *extsarg) 344 { 345 int i; 346 CURLcode result = CURLE_OK; 347 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \ 348 !defined(LIBRESSL_VERSION_NUMBER) 349 const STACK_OF(X509_EXTENSION) *exts = extsarg; 350 #else 351 STACK_OF(X509_EXTENSION) *exts = CURL_UNCONST(extsarg); 352 #endif 353 354 if((int)sk_X509_EXTENSION_num(exts) <= 0) 355 /* no extensions, bail out */ 356 return result; 357 358 for(i = 0; i < (int)sk_X509_EXTENSION_num(exts); i++) { 359 ASN1_OBJECT *obj; 360 X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, (ossl_valsize_t)i); 361 BUF_MEM *biomem; 362 char namebuf[128]; 363 BIO *bio_out = BIO_new(BIO_s_mem()); 364 365 if(!bio_out) 366 return result; 367 368 obj = X509_EXTENSION_get_object(ext); 369 370 asn1_object_dump(obj, namebuf, sizeof(namebuf)); 371 372 if(!X509V3_EXT_print(bio_out, ext, 0, 0)) 373 ASN1_STRING_print(bio_out, (ASN1_STRING *)X509_EXTENSION_get_data(ext)); 374 375 BIO_get_mem_ptr(bio_out, &biomem); 376 result = Curl_ssl_push_certinfo_len(data, certnum, namebuf, biomem->data, 377 biomem->length); 378 BIO_free(bio_out); 379 if(result) 380 break; 381 } 382 return result; 383 } 384 385 static CURLcode ossl_certchain(struct Curl_easy *data, SSL *ssl) 386 { 387 CURLcode result; 388 STACK_OF(X509) *sk; 389 int i; 390 numcert_t numcerts; 391 BIO *mem; 392 393 DEBUGASSERT(ssl); 394 395 sk = SSL_get_peer_cert_chain(ssl); 396 if(!sk) { 397 return CURLE_OUT_OF_MEMORY; 398 } 399 400 numcerts = sk_X509_num(sk); 401 402 result = Curl_ssl_init_certinfo(data, (int)numcerts); 403 if(result) 404 return result; 405 406 mem = BIO_new(BIO_s_mem()); 407 if(!mem) 408 result = CURLE_OUT_OF_MEMORY; 409 410 for(i = 0; !result && (i < (int)numcerts); i++) { 411 ASN1_INTEGER *num; 412 X509 *x = sk_X509_value(sk, (ossl_valsize_t)i); 413 EVP_PKEY *pubkey = NULL; 414 int j; 415 const ASN1_BIT_STRING *psig = NULL; 416 417 X509_NAME_print_ex(mem, X509_get_subject_name(x), 0, XN_FLAG_ONELINE); 418 result = push_certinfo(data, mem, "Subject", i); 419 if(result) 420 break; 421 422 X509_NAME_print_ex(mem, X509_get_issuer_name(x), 0, XN_FLAG_ONELINE); 423 result = push_certinfo(data, mem, "Issuer", i); 424 if(result) 425 break; 426 427 BIO_printf(mem, "%lx", X509_get_version(x)); 428 result = push_certinfo(data, mem, "Version", i); 429 if(result) 430 break; 431 432 num = X509_get_serialNumber(x); 433 if(num->type == V_ASN1_NEG_INTEGER) 434 BIO_puts(mem, "-"); 435 for(j = 0; j < num->length; j++) 436 BIO_printf(mem, "%02x", num->data[j]); 437 result = push_certinfo(data, mem, "Serial Number", i); 438 if(result) 439 break; 440 441 #ifdef HAVE_X509_GET0_EXTENSIONS 442 { 443 const X509_ALGOR *sigalg = NULL; 444 X509_PUBKEY *xpubkey = NULL; 445 ASN1_OBJECT *pubkeyoid = NULL; 446 447 X509_get0_signature(&psig, &sigalg, x); 448 if(sigalg) { 449 const ASN1_OBJECT *sigalgoid = NULL; 450 X509_ALGOR_get0(&sigalgoid, NULL, NULL, sigalg); 451 i2a_ASN1_OBJECT(mem, sigalgoid); 452 result = push_certinfo(data, mem, "Signature Algorithm", i); 453 if(result) 454 break; 455 } 456 457 xpubkey = X509_get_X509_PUBKEY(x); 458 if(xpubkey) { 459 X509_PUBKEY_get0_param(&pubkeyoid, NULL, NULL, NULL, xpubkey); 460 if(pubkeyoid) { 461 i2a_ASN1_OBJECT(mem, pubkeyoid); 462 result = push_certinfo(data, mem, "Public Key Algorithm", i); 463 if(result) 464 break; 465 } 466 } 467 468 result = X509V3_ext(data, i, X509_get0_extensions(x)); 469 if(result) 470 break; 471 } 472 #else 473 { 474 /* before OpenSSL 1.0.2 */ 475 X509_CINF *cinf = x->cert_info; 476 477 i2a_ASN1_OBJECT(mem, cinf->signature->algorithm); 478 result = push_certinfo(data, mem, "Signature Algorithm", i); 479 480 if(!result) { 481 i2a_ASN1_OBJECT(mem, cinf->key->algor->algorithm); 482 result = push_certinfo(data, mem, "Public Key Algorithm", i); 483 } 484 485 if(!result) 486 result = X509V3_ext(data, i, cinf->extensions); 487 488 if(result) 489 break; 490 491 psig = x->signature; 492 } 493 #endif 494 495 ASN1_TIME_print(mem, X509_get0_notBefore(x)); 496 result = push_certinfo(data, mem, "Start date", i); 497 if(result) 498 break; 499 500 ASN1_TIME_print(mem, X509_get0_notAfter(x)); 501 result = push_certinfo(data, mem, "Expire date", i); 502 if(result) 503 break; 504 505 pubkey = X509_get_pubkey(x); 506 if(!pubkey) 507 infof(data, " Unable to load public key"); 508 else { 509 int pktype; 510 #ifdef HAVE_OPAQUE_EVP_PKEY 511 pktype = EVP_PKEY_id(pubkey); 512 #else 513 pktype = pubkey->type; 514 #endif 515 switch(pktype) { 516 case EVP_PKEY_RSA: { 517 #ifndef HAVE_EVP_PKEY_GET_PARAMS 518 RSA *rsa; 519 #ifdef HAVE_OPAQUE_EVP_PKEY 520 rsa = EVP_PKEY_get0_RSA(pubkey); 521 #else 522 rsa = pubkey->pkey.rsa; 523 #endif /* HAVE_OPAQUE_EVP_PKEY */ 524 #endif /* !HAVE_EVP_PKEY_GET_PARAMS */ 525 526 { 527 #ifdef HAVE_OPAQUE_RSA_DSA_DH 528 DECLARE_PKEY_PARAM_BIGNUM(n); 529 DECLARE_PKEY_PARAM_BIGNUM(e); 530 #ifdef HAVE_EVP_PKEY_GET_PARAMS 531 EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_RSA_N, &n); 532 EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_RSA_E, &e); 533 #else 534 RSA_get0_key(rsa, &n, &e, NULL); 535 #endif /* HAVE_EVP_PKEY_GET_PARAMS */ 536 BIO_printf(mem, "%d", n ? BN_num_bits(n) : 0); 537 #else 538 BIO_printf(mem, "%d", rsa->n ? BN_num_bits(rsa->n) : 0); 539 #endif /* HAVE_OPAQUE_RSA_DSA_DH */ 540 result = push_certinfo(data, mem, "RSA Public Key", i); 541 if(result) 542 break; 543 print_pubkey_BN(rsa, n, i); 544 print_pubkey_BN(rsa, e, i); 545 FREE_PKEY_PARAM_BIGNUM(n); 546 FREE_PKEY_PARAM_BIGNUM(e); 547 } 548 549 break; 550 } 551 case EVP_PKEY_DSA: 552 { 553 #ifndef OPENSSL_NO_DSA 554 #ifndef HAVE_EVP_PKEY_GET_PARAMS 555 DSA *dsa; 556 #ifdef HAVE_OPAQUE_EVP_PKEY 557 dsa = EVP_PKEY_get0_DSA(pubkey); 558 #else 559 dsa = pubkey->pkey.dsa; 560 #endif /* HAVE_OPAQUE_EVP_PKEY */ 561 #endif /* !HAVE_EVP_PKEY_GET_PARAMS */ 562 { 563 #ifdef HAVE_OPAQUE_RSA_DSA_DH 564 DECLARE_PKEY_PARAM_BIGNUM(p); 565 DECLARE_PKEY_PARAM_BIGNUM(q); 566 DECLARE_PKEY_PARAM_BIGNUM(g); 567 DECLARE_PKEY_PARAM_BIGNUM(pub_key); 568 #ifdef HAVE_EVP_PKEY_GET_PARAMS 569 EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_FFC_P, &p); 570 EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_FFC_Q, &q); 571 EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_FFC_G, &g); 572 EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_PUB_KEY, &pub_key); 573 #else 574 DSA_get0_pqg(dsa, &p, &q, &g); 575 DSA_get0_key(dsa, &pub_key, NULL); 576 #endif /* HAVE_EVP_PKEY_GET_PARAMS */ 577 #endif /* HAVE_OPAQUE_RSA_DSA_DH */ 578 print_pubkey_BN(dsa, p, i); 579 print_pubkey_BN(dsa, q, i); 580 print_pubkey_BN(dsa, g, i); 581 print_pubkey_BN(dsa, pub_key, i); 582 FREE_PKEY_PARAM_BIGNUM(p); 583 FREE_PKEY_PARAM_BIGNUM(q); 584 FREE_PKEY_PARAM_BIGNUM(g); 585 FREE_PKEY_PARAM_BIGNUM(pub_key); 586 } 587 #endif /* !OPENSSL_NO_DSA */ 588 break; 589 } 590 case EVP_PKEY_DH: { 591 #ifndef HAVE_EVP_PKEY_GET_PARAMS 592 DH *dh; 593 #ifdef HAVE_OPAQUE_EVP_PKEY 594 dh = EVP_PKEY_get0_DH(pubkey); 595 #else 596 dh = pubkey->pkey.dh; 597 #endif /* HAVE_OPAQUE_EVP_PKEY */ 598 #endif /* !HAVE_EVP_PKEY_GET_PARAMS */ 599 { 600 #ifdef HAVE_OPAQUE_RSA_DSA_DH 601 DECLARE_PKEY_PARAM_BIGNUM(p); 602 DECLARE_PKEY_PARAM_BIGNUM(q); 603 DECLARE_PKEY_PARAM_BIGNUM(g); 604 DECLARE_PKEY_PARAM_BIGNUM(pub_key); 605 #ifdef HAVE_EVP_PKEY_GET_PARAMS 606 EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_FFC_P, &p); 607 EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_FFC_Q, &q); 608 EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_FFC_G, &g); 609 EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_PUB_KEY, &pub_key); 610 #else 611 DH_get0_pqg(dh, &p, &q, &g); 612 DH_get0_key(dh, &pub_key, NULL); 613 #endif /* HAVE_EVP_PKEY_GET_PARAMS */ 614 print_pubkey_BN(dh, p, i); 615 print_pubkey_BN(dh, q, i); 616 print_pubkey_BN(dh, g, i); 617 #else 618 print_pubkey_BN(dh, p, i); 619 print_pubkey_BN(dh, g, i); 620 #endif /* HAVE_OPAQUE_RSA_DSA_DH */ 621 print_pubkey_BN(dh, pub_key, i); 622 FREE_PKEY_PARAM_BIGNUM(p); 623 FREE_PKEY_PARAM_BIGNUM(q); 624 FREE_PKEY_PARAM_BIGNUM(g); 625 FREE_PKEY_PARAM_BIGNUM(pub_key); 626 } 627 break; 628 } 629 } 630 EVP_PKEY_free(pubkey); 631 } 632 633 if(!result && psig) { 634 for(j = 0; j < psig->length; j++) 635 BIO_printf(mem, "%02x:", psig->data[j]); 636 result = push_certinfo(data, mem, "Signature", i); 637 } 638 639 if(!result) { 640 PEM_write_bio_X509(mem, x); 641 result = push_certinfo(data, mem, "Cert", i); 642 } 643 } 644 645 BIO_free(mem); 646 647 if(result) 648 /* cleanup all leftovers */ 649 Curl_ssl_free_certinfo(data); 650 651 return result; 652 } 653 654 #endif /* quiche or OpenSSL */ 655 656 #ifdef USE_OPENSSL 657 658 #if OPENSSL_VERSION_NUMBER < 0x10100000L 659 #define BIO_set_init(x,v) ((x)->init=(v)) 660 #define BIO_get_data(x) ((x)->ptr) 661 #define BIO_set_data(x,v) ((x)->ptr=(v)) 662 #define BIO_get_shutdown(x) ((x)->shutdown) 663 #define BIO_set_shutdown(x,v) ((x)->shutdown=(v)) 664 #endif /* HAVE_PRE_1_1_API */ 665 666 static int ossl_bio_cf_create(BIO *bio) 667 { 668 BIO_set_shutdown(bio, 1); 669 BIO_set_init(bio, 1); 670 #if OPENSSL_VERSION_NUMBER < 0x10100000L 671 bio->num = -1; 672 #endif 673 BIO_set_data(bio, NULL); 674 return 1; 675 } 676 677 static int ossl_bio_cf_destroy(BIO *bio) 678 { 679 if(!bio) 680 return 0; 681 return 1; 682 } 683 684 static long ossl_bio_cf_ctrl(BIO *bio, int cmd, long num, void *ptr) 685 { 686 struct Curl_cfilter *cf = BIO_get_data(bio); 687 long ret = 1; 688 689 (void)cf; 690 (void)ptr; 691 switch(cmd) { 692 case BIO_CTRL_GET_CLOSE: 693 ret = (long)BIO_get_shutdown(bio); 694 break; 695 case BIO_CTRL_SET_CLOSE: 696 BIO_set_shutdown(bio, (int)num); 697 break; 698 case BIO_CTRL_FLUSH: 699 /* we do no delayed writes, but if we ever would, this 700 * needs to trigger it. */ 701 ret = 1; 702 break; 703 case BIO_CTRL_DUP: 704 ret = 1; 705 break; 706 #ifdef BIO_CTRL_EOF 707 case BIO_CTRL_EOF: { 708 /* EOF has been reached on input? */ 709 struct ssl_connect_data *connssl = cf->ctx; 710 return connssl->peer_closed; 711 } 712 #endif 713 default: 714 ret = 0; 715 break; 716 } 717 return ret; 718 } 719 720 static int ossl_bio_cf_out_write(BIO *bio, const char *buf, int blen) 721 { 722 struct Curl_cfilter *cf = BIO_get_data(bio); 723 struct ssl_connect_data *connssl = cf->ctx; 724 struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend; 725 struct Curl_easy *data = CF_DATA_CURRENT(cf); 726 size_t nwritten; 727 CURLcode result; 728 729 DEBUGASSERT(data); 730 if(blen < 0) 731 return 0; 732 733 result = Curl_conn_cf_send(cf->next, data, buf, (size_t)blen, FALSE, 734 &nwritten); 735 CURL_TRC_CF(data, cf, "ossl_bio_cf_out_write(len=%d) -> %d, %zu", 736 blen, result, nwritten); 737 BIO_clear_retry_flags(bio); 738 octx->io_result = result; 739 if(result) { 740 if(CURLE_AGAIN == result) 741 BIO_set_retry_write(bio); 742 return -1; 743 } 744 return (int)nwritten; 745 } 746 747 static int ossl_bio_cf_in_read(BIO *bio, char *buf, int blen) 748 { 749 struct Curl_cfilter *cf = BIO_get_data(bio); 750 struct ssl_connect_data *connssl = cf->ctx; 751 struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend; 752 struct Curl_easy *data = CF_DATA_CURRENT(cf); 753 size_t nread; 754 CURLcode result, r2; 755 756 DEBUGASSERT(data); 757 /* OpenSSL catches this case, so should we. */ 758 if(!buf) 759 return 0; 760 if(blen < 0) 761 return 0; 762 763 result = Curl_conn_cf_recv(cf->next, data, buf, (size_t)blen, &nread); 764 CURL_TRC_CF(data, cf, "ossl_bio_cf_in_read(len=%d) -> %d, %zu", 765 blen, result, nread); 766 BIO_clear_retry_flags(bio); 767 octx->io_result = result; 768 if(result) { 769 if(CURLE_AGAIN == result) 770 BIO_set_retry_read(bio); 771 } 772 else { 773 /* feeding data to OpenSSL means SSL_read() might succeed */ 774 connssl->input_pending = TRUE; 775 if(nread == 0) 776 connssl->peer_closed = TRUE; 777 } 778 779 /* Before returning server replies to the SSL instance, we need 780 * to have setup the x509 store or verification will fail. */ 781 if(!octx->x509_store_setup) { 782 r2 = Curl_ssl_setup_x509_store(cf, data, octx->ssl_ctx); 783 if(r2) { 784 octx->io_result = r2; 785 return -1; 786 } 787 octx->x509_store_setup = TRUE; 788 } 789 return result ? -1 : (int)nread; 790 } 791 792 #if OPENSSL_VERSION_NUMBER < 0x10100000L 793 794 static BIO_METHOD ossl_bio_cf_meth_1_0 = { 795 BIO_TYPE_MEM, 796 "OpenSSL CF BIO", 797 ossl_bio_cf_out_write, 798 ossl_bio_cf_in_read, 799 NULL, /* puts is never called */ 800 NULL, /* gets is never called */ 801 ossl_bio_cf_ctrl, 802 ossl_bio_cf_create, 803 ossl_bio_cf_destroy, 804 NULL 805 }; 806 807 static BIO_METHOD *ossl_bio_cf_method_create(void) 808 { 809 return &ossl_bio_cf_meth_1_0; 810 } 811 812 #define ossl_bio_cf_method_free(m) Curl_nop_stmt 813 814 #else 815 816 static BIO_METHOD *ossl_bio_cf_method_create(void) 817 { 818 BIO_METHOD *m = BIO_meth_new(BIO_TYPE_MEM, "OpenSSL CF BIO"); 819 if(m) { 820 BIO_meth_set_write(m, &ossl_bio_cf_out_write); 821 BIO_meth_set_read(m, &ossl_bio_cf_in_read); 822 BIO_meth_set_ctrl(m, &ossl_bio_cf_ctrl); 823 BIO_meth_set_create(m, &ossl_bio_cf_create); 824 BIO_meth_set_destroy(m, &ossl_bio_cf_destroy); 825 } 826 return m; 827 } 828 829 static void ossl_bio_cf_method_free(BIO_METHOD *m) 830 { 831 if(m) 832 BIO_meth_free(m); 833 } 834 835 #endif 836 837 838 #ifdef HAVE_KEYLOG_CALLBACK 839 static void ossl_keylog_callback(const SSL *ssl, const char *line) 840 { 841 (void)ssl; 842 843 Curl_tls_keylog_write_line(line); 844 } 845 #else 846 /* 847 * ossl_log_tls12_secret is called by libcurl to make the CLIENT_RANDOMs if the 848 * OpenSSL being used does not have native support for doing that. 849 */ 850 static void 851 ossl_log_tls12_secret(const SSL *ssl, bool *keylog_done) 852 { 853 const SSL_SESSION *session = SSL_get_session(ssl); 854 unsigned char client_random[SSL3_RANDOM_SIZE]; 855 unsigned char master_key[SSL_MAX_MASTER_KEY_LENGTH]; 856 int master_key_length = 0; 857 858 if(!session || *keylog_done) 859 return; 860 861 #if OPENSSL_VERSION_NUMBER >= 0x10100000L 862 /* ssl->s3 is not checked in OpenSSL 1.1.0-pre6, but let's assume that 863 * we have a valid SSL context if we have a non-NULL session. */ 864 SSL_get_client_random(ssl, client_random, SSL3_RANDOM_SIZE); 865 master_key_length = (int) 866 SSL_SESSION_get_master_key(session, master_key, SSL_MAX_MASTER_KEY_LENGTH); 867 #else 868 if(ssl->s3 && session->master_key_length > 0) { 869 master_key_length = session->master_key_length; 870 memcpy(master_key, session->master_key, session->master_key_length); 871 memcpy(client_random, ssl->s3->client_random, SSL3_RANDOM_SIZE); 872 } 873 #endif 874 875 /* The handshake has not progressed sufficiently yet, or this is a TLS 1.3 876 * session (when curl was built with older OpenSSL headers and running with 877 * newer OpenSSL runtime libraries). */ 878 if(master_key_length <= 0) 879 return; 880 881 *keylog_done = TRUE; 882 Curl_tls_keylog_write("CLIENT_RANDOM", client_random, 883 master_key, master_key_length); 884 } 885 #endif /* !HAVE_KEYLOG_CALLBACK */ 886 887 static const char *SSL_ERROR_to_str(int err) 888 { 889 switch(err) { 890 case SSL_ERROR_NONE: 891 return "SSL_ERROR_NONE"; 892 case SSL_ERROR_SSL: 893 return "SSL_ERROR_SSL"; 894 case SSL_ERROR_WANT_READ: 895 return "SSL_ERROR_WANT_READ"; 896 case SSL_ERROR_WANT_WRITE: 897 return "SSL_ERROR_WANT_WRITE"; 898 case SSL_ERROR_WANT_X509_LOOKUP: 899 return "SSL_ERROR_WANT_X509_LOOKUP"; 900 case SSL_ERROR_SYSCALL: 901 return "SSL_ERROR_SYSCALL"; 902 case SSL_ERROR_ZERO_RETURN: 903 return "SSL_ERROR_ZERO_RETURN"; 904 case SSL_ERROR_WANT_CONNECT: 905 return "SSL_ERROR_WANT_CONNECT"; 906 case SSL_ERROR_WANT_ACCEPT: 907 return "SSL_ERROR_WANT_ACCEPT"; 908 #ifdef SSL_ERROR_WANT_ASYNC 909 case SSL_ERROR_WANT_ASYNC: 910 return "SSL_ERROR_WANT_ASYNC"; 911 #endif 912 #ifdef SSL_ERROR_WANT_ASYNC_JOB 913 case SSL_ERROR_WANT_ASYNC_JOB: 914 return "SSL_ERROR_WANT_ASYNC_JOB"; 915 #endif 916 #ifdef SSL_ERROR_WANT_EARLY 917 case SSL_ERROR_WANT_EARLY: 918 return "SSL_ERROR_WANT_EARLY"; 919 #endif 920 default: 921 return "SSL_ERROR unknown"; 922 } 923 } 924 925 /* Return error string for last OpenSSL error 926 */ 927 static char *ossl_strerror(unsigned long error, char *buf, size_t size) 928 { 929 size_t len; 930 DEBUGASSERT(size); 931 *buf = '\0'; 932 933 len = Curl_ossl_version(buf, size); 934 DEBUGASSERT(len < (size - 2)); 935 if(len < (size - 2)) { 936 buf += len; 937 size -= (len + 2); 938 *buf++ = ':'; 939 *buf++ = ' '; 940 *buf = '\0'; 941 } 942 943 #if defined(OPENSSL_IS_BORINGSSL) || defined(OPENSSL_IS_AWSLC) 944 ERR_error_string_n((uint32_t)error, buf, size); 945 #else 946 ERR_error_string_n(error, buf, size); 947 #endif 948 949 if(!*buf) { 950 const char *msg = error ? "Unknown error" : "No error"; 951 if(strlen(msg) < size) 952 strcpy(buf, msg); 953 } 954 955 return buf; 956 } 957 958 static int passwd_callback(char *buf, int num, int encrypting, 959 void *password) 960 { 961 DEBUGASSERT(0 == encrypting); 962 963 if(!encrypting && num >= 0 && password) { 964 int klen = curlx_uztosi(strlen((char *)password)); 965 if(num > klen) { 966 memcpy(buf, password, klen + 1); 967 return klen; 968 } 969 } 970 return 0; 971 } 972 973 /* 974 * rand_enough() returns TRUE if we have seeded the random engine properly. 975 */ 976 static bool rand_enough(void) 977 { 978 return 0 != RAND_status(); 979 } 980 981 static CURLcode ossl_seed(struct Curl_easy *data) 982 { 983 /* This might get called before it has been added to a multi handle */ 984 if(data->multi && data->multi->ssl_seeded) 985 return CURLE_OK; 986 987 if(rand_enough()) { 988 /* OpenSSL 1.1.0+ should return here */ 989 if(data->multi) 990 data->multi->ssl_seeded = TRUE; 991 return CURLE_OK; 992 } 993 #ifdef HAVE_RANDOM_INIT_BY_DEFAULT 994 /* with OpenSSL 1.1.0+, a failed RAND_status is a showstopper */ 995 failf(data, "Insufficient randomness"); 996 return CURLE_SSL_CONNECT_ERROR; 997 #else 998 999 /* fallback to a custom seeding of the PRNG using a hash based on a current 1000 time */ 1001 do { 1002 unsigned char randb[64]; 1003 size_t len = sizeof(randb); 1004 size_t i, i_max; 1005 for(i = 0, i_max = len / sizeof(struct curltime); i < i_max; ++i) { 1006 struct curltime tv = curlx_now(); 1007 curlx_wait_ms(1); 1008 tv.tv_sec *= (time_t)i + 1; 1009 tv.tv_usec *= (int)i + 2; 1010 tv.tv_sec ^= ((curlx_now().tv_sec + (time_t)curlx_now().tv_usec) * 1011 (time_t)(i + 3)) << 8; 1012 tv.tv_usec ^= (int) ((curlx_now().tv_sec + (time_t)curlx_now().tv_usec) * 1013 (time_t)(i + 4)) << 16; 1014 memcpy(&randb[i * sizeof(struct curltime)], &tv, 1015 sizeof(struct curltime)); 1016 } 1017 RAND_add(randb, (int)len, (double)len/2); 1018 } while(!rand_enough()); 1019 1020 /* 1021 * Number of bytes to read from the random number seed file. This must be 1022 * a finite value (because some entropy "files" like /dev/urandom have 1023 * an infinite length), but must be large enough to provide enough 1024 * entropy to properly seed OpenSSL's PRNG. 1025 */ 1026 # define RAND_LOAD_LENGTH 1024 1027 1028 { 1029 /* generates a default path for the random seed file */ 1030 char fname[256]; 1031 fname[0] = 0; /* blank it first */ 1032 RAND_file_name(fname, sizeof(fname)); 1033 if(fname[0]) { 1034 /* we got a filename to try */ 1035 RAND_load_file(fname, RAND_LOAD_LENGTH); 1036 if(rand_enough()) 1037 return CURLE_OK; 1038 } 1039 } 1040 1041 infof(data, "libcurl is now using a weak random seed"); 1042 return rand_enough() ? CURLE_OK : 1043 CURLE_SSL_CONNECT_ERROR; /* confusing error code */ 1044 #endif 1045 } 1046 1047 #ifndef SSL_FILETYPE_ENGINE 1048 #define SSL_FILETYPE_ENGINE 42 1049 #endif 1050 #ifndef SSL_FILETYPE_PKCS12 1051 #define SSL_FILETYPE_PKCS12 43 1052 #endif 1053 #ifndef SSL_FILETYPE_PROVIDER 1054 #define SSL_FILETYPE_PROVIDER 44 1055 #endif 1056 static int ossl_do_file_type(const char *type) 1057 { 1058 if(!type || !type[0]) 1059 return SSL_FILETYPE_PEM; 1060 if(curl_strequal(type, "PEM")) 1061 return SSL_FILETYPE_PEM; 1062 if(curl_strequal(type, "DER")) 1063 return SSL_FILETYPE_ASN1; 1064 if(curl_strequal(type, "PROV")) 1065 return SSL_FILETYPE_PROVIDER; 1066 if(curl_strequal(type, "ENG")) 1067 return SSL_FILETYPE_ENGINE; 1068 if(curl_strequal(type, "P12")) 1069 return SSL_FILETYPE_PKCS12; 1070 return -1; 1071 } 1072 1073 #if defined(USE_OPENSSL_ENGINE) || defined(OPENSSL_HAS_PROVIDERS) 1074 /* 1075 * Supply default password to the engine user interface conversation. 1076 * The password is passed by OpenSSL engine from ENGINE_load_private_key() 1077 * last argument to the ui and can be obtained by UI_get0_user_data(ui) here. 1078 */ 1079 static int ssl_ui_reader(UI *ui, UI_STRING *uis) 1080 { 1081 const char *password; 1082 switch(UI_get_string_type(uis)) { 1083 case UIT_PROMPT: 1084 case UIT_VERIFY: 1085 password = (const char *)UI_get0_user_data(ui); 1086 if(password && (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD)) { 1087 UI_set_result(ui, uis, password); 1088 return 1; 1089 } 1090 FALLTHROUGH(); 1091 default: 1092 break; 1093 } 1094 return (UI_method_get_reader(UI_OpenSSL()))(ui, uis); 1095 } 1096 1097 /* 1098 * Suppress interactive request for a default password if available. 1099 */ 1100 static int ssl_ui_writer(UI *ui, UI_STRING *uis) 1101 { 1102 switch(UI_get_string_type(uis)) { 1103 case UIT_PROMPT: 1104 case UIT_VERIFY: 1105 if(UI_get0_user_data(ui) && 1106 (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD)) { 1107 return 1; 1108 } 1109 FALLTHROUGH(); 1110 default: 1111 break; 1112 } 1113 return (UI_method_get_writer(UI_OpenSSL()))(ui, uis); 1114 } 1115 1116 /* 1117 * Check if a given string is a PKCS#11 URI 1118 */ 1119 static bool is_pkcs11_uri(const char *string) 1120 { 1121 return string && curl_strnequal(string, "pkcs11:", 7); 1122 } 1123 1124 #endif 1125 1126 static CURLcode ossl_set_engine(struct Curl_easy *data, const char *engine); 1127 #if defined(OPENSSL_HAS_PROVIDERS) 1128 static CURLcode ossl_set_provider(struct Curl_easy *data, 1129 const char *provider); 1130 #endif 1131 1132 static int use_certificate_blob(SSL_CTX *ctx, const struct curl_blob *blob, 1133 int type, const char *key_passwd) 1134 { 1135 int ret = 0; 1136 X509 *x = NULL; 1137 /* the typecast of blob->len is fine since it is guaranteed to never be 1138 larger than CURL_MAX_INPUT_LENGTH */ 1139 BIO *in = BIO_new_mem_buf(blob->data, (int)(blob->len)); 1140 if(!in) 1141 return CURLE_OUT_OF_MEMORY; 1142 1143 if(type == SSL_FILETYPE_ASN1) { 1144 /* j = ERR_R_ASN1_LIB; */ 1145 x = d2i_X509_bio(in, NULL); 1146 } 1147 else if(type == SSL_FILETYPE_PEM) { 1148 /* ERR_R_PEM_LIB; */ 1149 x = PEM_read_bio_X509(in, NULL, 1150 passwd_callback, CURL_UNCONST(key_passwd)); 1151 } 1152 else { 1153 ret = 0; 1154 goto end; 1155 } 1156 1157 if(!x) { 1158 ret = 0; 1159 goto end; 1160 } 1161 1162 ret = SSL_CTX_use_certificate(ctx, x); 1163 end: 1164 X509_free(x); 1165 BIO_free(in); 1166 return ret; 1167 } 1168 1169 static int use_privatekey_blob(SSL_CTX *ctx, const struct curl_blob *blob, 1170 int type, const char *key_passwd) 1171 { 1172 int ret = 0; 1173 EVP_PKEY *pkey = NULL; 1174 BIO *in = BIO_new_mem_buf(blob->data, (int)(blob->len)); 1175 if(!in) 1176 return CURLE_OUT_OF_MEMORY; 1177 1178 if(type == SSL_FILETYPE_PEM) 1179 pkey = PEM_read_bio_PrivateKey(in, NULL, passwd_callback, 1180 CURL_UNCONST(key_passwd)); 1181 else if(type == SSL_FILETYPE_ASN1) 1182 pkey = d2i_PrivateKey_bio(in, NULL); 1183 else 1184 goto end; 1185 1186 if(!pkey) 1187 goto end; 1188 1189 ret = SSL_CTX_use_PrivateKey(ctx, pkey); 1190 EVP_PKEY_free(pkey); 1191 end: 1192 BIO_free(in); 1193 return ret; 1194 } 1195 1196 static int 1197 use_certificate_chain_blob(SSL_CTX *ctx, const struct curl_blob *blob, 1198 const char *key_passwd) 1199 { 1200 int ret = 0; 1201 X509 *x = NULL; 1202 BIO *in = BIO_new_mem_buf(blob->data, (int)(blob->len)); 1203 if(!in) 1204 return CURLE_OUT_OF_MEMORY; 1205 1206 ERR_clear_error(); 1207 1208 x = PEM_read_bio_X509_AUX(in, NULL, 1209 passwd_callback, CURL_UNCONST(key_passwd)); 1210 if(!x) 1211 goto end; 1212 1213 ret = SSL_CTX_use_certificate(ctx, x); 1214 1215 if(ERR_peek_error() != 0) 1216 ret = 0; 1217 1218 if(ret) { 1219 X509 *ca; 1220 sslerr_t err; 1221 1222 if(!SSL_CTX_clear_chain_certs(ctx)) { 1223 ret = 0; 1224 goto end; 1225 } 1226 1227 while((ca = PEM_read_bio_X509(in, NULL, passwd_callback, 1228 CURL_UNCONST(key_passwd))) 1229 != NULL) { 1230 1231 if(!SSL_CTX_add0_chain_cert(ctx, ca)) { 1232 X509_free(ca); 1233 ret = 0; 1234 goto end; 1235 } 1236 } 1237 1238 err = ERR_peek_last_error(); 1239 if((ERR_GET_LIB(err) == ERR_LIB_PEM) && 1240 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) 1241 ERR_clear_error(); 1242 else 1243 ret = 0; 1244 } 1245 1246 end: 1247 X509_free(x); 1248 BIO_free(in); 1249 return ret; 1250 } 1251 1252 static 1253 int cert_stuff(struct Curl_easy *data, 1254 SSL_CTX* ctx, 1255 char *cert_file, 1256 const struct curl_blob *cert_blob, 1257 const char *cert_type, 1258 char *key_file, 1259 const struct curl_blob *key_blob, 1260 const char *key_type, 1261 char *key_passwd) 1262 { 1263 char error_buffer[256]; 1264 bool check_privkey = TRUE; 1265 1266 int file_type = ossl_do_file_type(cert_type); 1267 1268 if(cert_file || cert_blob || (file_type == SSL_FILETYPE_ENGINE) || 1269 (file_type == SSL_FILETYPE_PROVIDER)) { 1270 SSL *ssl; 1271 X509 *x509; 1272 int cert_done = 0; 1273 int cert_use_result; 1274 1275 if(key_passwd) { 1276 /* set the password in the callback userdata */ 1277 SSL_CTX_set_default_passwd_cb_userdata(ctx, key_passwd); 1278 /* Set passwd callback: */ 1279 SSL_CTX_set_default_passwd_cb(ctx, passwd_callback); 1280 } 1281 1282 1283 switch(file_type) { 1284 case SSL_FILETYPE_PEM: 1285 /* SSL_CTX_use_certificate_chain_file() only works on PEM files */ 1286 cert_use_result = cert_blob ? 1287 use_certificate_chain_blob(ctx, cert_blob, key_passwd) : 1288 SSL_CTX_use_certificate_chain_file(ctx, cert_file); 1289 if(cert_use_result != 1) { 1290 failf(data, 1291 "could not load PEM client certificate from %s, " OSSL_PACKAGE 1292 " error %s, " 1293 "(no key found, wrong pass phrase, or wrong file format?)", 1294 (cert_blob ? "CURLOPT_SSLCERT_BLOB" : cert_file), 1295 ossl_strerror(ERR_get_error(), error_buffer, 1296 sizeof(error_buffer)) ); 1297 return 0; 1298 } 1299 break; 1300 1301 case SSL_FILETYPE_ASN1: 1302 /* SSL_CTX_use_certificate_file() works with either PEM or ASN1, but 1303 we use the case above for PEM so this can only be performed with 1304 ASN1 files. */ 1305 1306 cert_use_result = cert_blob ? 1307 use_certificate_blob(ctx, cert_blob, file_type, key_passwd) : 1308 SSL_CTX_use_certificate_file(ctx, cert_file, file_type); 1309 if(cert_use_result != 1) { 1310 failf(data, 1311 "could not load ASN1 client certificate from %s, " OSSL_PACKAGE 1312 " error %s, " 1313 "(no key found, wrong pass phrase, or wrong file format?)", 1314 (cert_blob ? "CURLOPT_SSLCERT_BLOB" : cert_file), 1315 ossl_strerror(ERR_get_error(), error_buffer, 1316 sizeof(error_buffer)) ); 1317 return 0; 1318 } 1319 break; 1320 case SSL_FILETYPE_ENGINE: 1321 #if defined(USE_OPENSSL_ENGINE) && defined(ENGINE_CTRL_GET_CMD_FROM_NAME) 1322 { 1323 /* Implicitly use pkcs11 engine if none was provided and the 1324 * cert_file is a PKCS#11 URI */ 1325 if(!data->state.engine) { 1326 if(is_pkcs11_uri(cert_file)) { 1327 if(ossl_set_engine(data, "pkcs11") != CURLE_OK) { 1328 return 0; 1329 } 1330 } 1331 } 1332 1333 if(data->state.engine) { 1334 const char *cmd_name = "LOAD_CERT_CTRL"; 1335 struct { 1336 const char *cert_id; 1337 X509 *cert; 1338 } params; 1339 1340 params.cert_id = cert_file; 1341 params.cert = NULL; 1342 1343 /* Does the engine supports LOAD_CERT_CTRL ? */ 1344 if(!ENGINE_ctrl(data->state.engine, ENGINE_CTRL_GET_CMD_FROM_NAME, 1345 0, CURL_UNCONST(cmd_name), NULL)) { 1346 failf(data, "ssl engine does not support loading certificates"); 1347 return 0; 1348 } 1349 1350 /* Load the certificate from the engine */ 1351 if(!ENGINE_ctrl_cmd(data->state.engine, cmd_name, 1352 0, ¶ms, NULL, 1)) { 1353 failf(data, "ssl engine cannot load client cert with id" 1354 " '%s' [%s]", cert_file, 1355 ossl_strerror(ERR_get_error(), error_buffer, 1356 sizeof(error_buffer))); 1357 return 0; 1358 } 1359 1360 if(!params.cert) { 1361 failf(data, "ssl engine did not initialized the certificate " 1362 "properly."); 1363 return 0; 1364 } 1365 1366 if(SSL_CTX_use_certificate(ctx, params.cert) != 1) { 1367 failf(data, "unable to set client certificate [%s]", 1368 ossl_strerror(ERR_get_error(), error_buffer, 1369 sizeof(error_buffer))); 1370 return 0; 1371 } 1372 X509_free(params.cert); /* we do not need the handle any more... */ 1373 } 1374 else { 1375 failf(data, "crypto engine not set, cannot load certificate"); 1376 return 0; 1377 } 1378 } 1379 break; 1380 #endif 1381 #if defined(OPENSSL_HAS_PROVIDERS) 1382 /* fall through to compatible provider */ 1383 case SSL_FILETYPE_PROVIDER: 1384 { 1385 /* Implicitly use pkcs11 provider if none was provided and the 1386 * cert_file is a PKCS#11 URI */ 1387 if(!data->state.provider_loaded) { 1388 if(is_pkcs11_uri(cert_file)) { 1389 if(ossl_set_provider(data, "pkcs11") != CURLE_OK) { 1390 return 0; 1391 } 1392 } 1393 } 1394 1395 if(data->state.provider_loaded) { 1396 /* Load the certificate from the provider */ 1397 OSSL_STORE_INFO *info = NULL; 1398 X509 *cert = NULL; 1399 OSSL_STORE_CTX *store = 1400 OSSL_STORE_open_ex(cert_file, data->state.libctx, 1401 NULL, NULL, NULL, NULL, NULL, NULL); 1402 if(!store) { 1403 failf(data, "Failed to open OpenSSL store: %s", 1404 ossl_strerror(ERR_get_error(), error_buffer, 1405 sizeof(error_buffer))); 1406 return 0; 1407 } 1408 if(OSSL_STORE_expect(store, OSSL_STORE_INFO_CERT) != 1) { 1409 failf(data, "Failed to set store preference. Ignoring the error: %s", 1410 ossl_strerror(ERR_get_error(), error_buffer, 1411 sizeof(error_buffer))); 1412 } 1413 1414 info = OSSL_STORE_load(store); 1415 if(info) { 1416 int ossl_type = OSSL_STORE_INFO_get_type(info); 1417 1418 if(ossl_type == OSSL_STORE_INFO_CERT) 1419 cert = OSSL_STORE_INFO_get1_CERT(info); 1420 OSSL_STORE_INFO_free(info); 1421 } 1422 OSSL_STORE_close(store); 1423 if(!cert) { 1424 failf(data, "No cert found in the openssl store: %s", 1425 ossl_strerror(ERR_get_error(), error_buffer, 1426 sizeof(error_buffer))); 1427 return 0; 1428 } 1429 1430 if(SSL_CTX_use_certificate(ctx, cert) != 1) { 1431 failf(data, "unable to set client certificate [%s]", 1432 ossl_strerror(ERR_get_error(), error_buffer, 1433 sizeof(error_buffer))); 1434 return 0; 1435 } 1436 X509_free(cert); /* we do not need the handle any more... */ 1437 } 1438 else { 1439 failf(data, "crypto provider not set, cannot load certificate"); 1440 return 0; 1441 } 1442 } 1443 break; 1444 #endif 1445 1446 case SSL_FILETYPE_PKCS12: 1447 { 1448 BIO *cert_bio = NULL; 1449 PKCS12 *p12 = NULL; 1450 EVP_PKEY *pri; 1451 STACK_OF(X509) *ca = NULL; 1452 if(cert_blob) { 1453 cert_bio = BIO_new_mem_buf(cert_blob->data, (int)(cert_blob->len)); 1454 if(!cert_bio) { 1455 failf(data, 1456 "BIO_new_mem_buf NULL, " OSSL_PACKAGE 1457 " error %s", 1458 ossl_strerror(ERR_get_error(), error_buffer, 1459 sizeof(error_buffer)) ); 1460 return 0; 1461 } 1462 } 1463 else { 1464 cert_bio = BIO_new(BIO_s_file()); 1465 if(!cert_bio) { 1466 failf(data, 1467 "BIO_new return NULL, " OSSL_PACKAGE 1468 " error %s", 1469 ossl_strerror(ERR_get_error(), error_buffer, 1470 sizeof(error_buffer)) ); 1471 return 0; 1472 } 1473 1474 if(BIO_read_filename(cert_bio, cert_file) <= 0) { 1475 failf(data, "could not open PKCS12 file '%s'", cert_file); 1476 BIO_free(cert_bio); 1477 return 0; 1478 } 1479 } 1480 1481 p12 = d2i_PKCS12_bio(cert_bio, NULL); 1482 BIO_free(cert_bio); 1483 1484 if(!p12) { 1485 failf(data, "error reading PKCS12 file '%s'", 1486 cert_blob ? "(memory blob)" : cert_file); 1487 return 0; 1488 } 1489 1490 PKCS12_PBE_add(); 1491 1492 if(!PKCS12_parse(p12, key_passwd, &pri, &x509, &ca)) { 1493 failf(data, 1494 "could not parse PKCS12 file, check password, " OSSL_PACKAGE 1495 " error %s", 1496 ossl_strerror(ERR_get_error(), error_buffer, 1497 sizeof(error_buffer)) ); 1498 PKCS12_free(p12); 1499 return 0; 1500 } 1501 1502 PKCS12_free(p12); 1503 1504 if(SSL_CTX_use_certificate(ctx, x509) != 1) { 1505 failf(data, 1506 "could not load PKCS12 client certificate, " OSSL_PACKAGE 1507 " error %s", 1508 ossl_strerror(ERR_get_error(), error_buffer, 1509 sizeof(error_buffer)) ); 1510 goto fail; 1511 } 1512 1513 if(SSL_CTX_use_PrivateKey(ctx, pri) != 1) { 1514 failf(data, "unable to use private key from PKCS12 file '%s'", 1515 cert_file); 1516 goto fail; 1517 } 1518 1519 if(!SSL_CTX_check_private_key (ctx)) { 1520 failf(data, "private key from PKCS12 file '%s' " 1521 "does not match certificate in same file", cert_file); 1522 goto fail; 1523 } 1524 /* Set Certificate Verification chain */ 1525 if(ca) { 1526 while(sk_X509_num(ca)) { 1527 /* 1528 * Note that sk_X509_pop() is used below to make sure the cert is 1529 * removed from the stack properly before getting passed to 1530 * SSL_CTX_add_extra_chain_cert(), which takes ownership. Previously 1531 * we used sk_X509_value() instead, but then we would clean it in the 1532 * subsequent sk_X509_pop_free() call. 1533 */ 1534 X509 *x = sk_X509_pop(ca); 1535 if(!SSL_CTX_add_client_CA(ctx, x)) { 1536 X509_free(x); 1537 failf(data, "cannot add certificate to client CA list"); 1538 goto fail; 1539 } 1540 if(!SSL_CTX_add_extra_chain_cert(ctx, x)) { 1541 X509_free(x); 1542 failf(data, "cannot add certificate to certificate chain"); 1543 goto fail; 1544 } 1545 } 1546 } 1547 1548 cert_done = 1; 1549 fail: 1550 EVP_PKEY_free(pri); 1551 X509_free(x509); 1552 sk_X509_pop_free(ca, X509_free); 1553 if(!cert_done) 1554 return 0; /* failure! */ 1555 break; 1556 } 1557 default: 1558 failf(data, "not supported file type '%s' for certificate", cert_type); 1559 return 0; 1560 } 1561 1562 if((!key_file) && (!key_blob)) { 1563 key_file = cert_file; 1564 key_blob = cert_blob; 1565 } 1566 else 1567 file_type = ossl_do_file_type(key_type); 1568 1569 switch(file_type) { 1570 case SSL_FILETYPE_PEM: 1571 if(cert_done) 1572 break; 1573 FALLTHROUGH(); 1574 case SSL_FILETYPE_ASN1: 1575 cert_use_result = key_blob ? 1576 use_privatekey_blob(ctx, key_blob, file_type, key_passwd) : 1577 SSL_CTX_use_PrivateKey_file(ctx, key_file, file_type); 1578 if(cert_use_result != 1) { 1579 failf(data, "unable to set private key file: '%s' type %s", 1580 key_file ? key_file : "(memory blob)", 1581 key_type ? key_type : "PEM"); 1582 return 0; 1583 } 1584 break; 1585 case SSL_FILETYPE_ENGINE: 1586 #ifdef USE_OPENSSL_ENGINE 1587 { 1588 EVP_PKEY *priv_key = NULL; 1589 1590 /* Implicitly use pkcs11 engine if none was provided and the 1591 * key_file is a PKCS#11 URI */ 1592 if(!data->state.engine) { 1593 if(is_pkcs11_uri(key_file)) { 1594 if(ossl_set_engine(data, "pkcs11") != CURLE_OK) { 1595 return 0; 1596 } 1597 } 1598 } 1599 1600 if(data->state.engine) { 1601 UI_METHOD *ui_method = 1602 UI_create_method(OSSL_UI_METHOD_CAST("curl user interface")); 1603 if(!ui_method) { 1604 failf(data, "unable do create " OSSL_PACKAGE 1605 " user-interface method"); 1606 return 0; 1607 } 1608 UI_method_set_opener(ui_method, UI_method_get_opener(UI_OpenSSL())); 1609 UI_method_set_closer(ui_method, UI_method_get_closer(UI_OpenSSL())); 1610 UI_method_set_reader(ui_method, ssl_ui_reader); 1611 UI_method_set_writer(ui_method, ssl_ui_writer); 1612 priv_key = ENGINE_load_private_key(data->state.engine, key_file, 1613 ui_method, 1614 key_passwd); 1615 UI_destroy_method(ui_method); 1616 if(!priv_key) { 1617 failf(data, "failed to load private key from crypto engine"); 1618 return 0; 1619 } 1620 if(SSL_CTX_use_PrivateKey(ctx, priv_key) != 1) { 1621 failf(data, "unable to set private key"); 1622 EVP_PKEY_free(priv_key); 1623 return 0; 1624 } 1625 EVP_PKEY_free(priv_key); /* we do not need the handle any more... */ 1626 } 1627 else { 1628 failf(data, "crypto engine not set, cannot load private key"); 1629 return 0; 1630 } 1631 } 1632 break; 1633 #endif 1634 #if defined(OPENSSL_HAS_PROVIDERS) 1635 /* fall through to compatible provider */ 1636 case SSL_FILETYPE_PROVIDER: 1637 { 1638 /* Implicitly use pkcs11 provider if none was provided and the 1639 * key_file is a PKCS#11 URI */ 1640 if(!data->state.provider_loaded) { 1641 if(is_pkcs11_uri(key_file)) { 1642 if(ossl_set_provider(data, "pkcs11") != CURLE_OK) { 1643 return 0; 1644 } 1645 } 1646 } 1647 1648 if(data->state.provider_loaded) { 1649 /* Load the private key from the provider */ 1650 EVP_PKEY *priv_key = NULL; 1651 OSSL_STORE_CTX *store = NULL; 1652 OSSL_STORE_INFO *info = NULL; 1653 UI_METHOD *ui_method = 1654 UI_create_method(OSSL_UI_METHOD_CAST("curl user interface")); 1655 if(!ui_method) { 1656 failf(data, "unable do create " OSSL_PACKAGE 1657 " user-interface method"); 1658 return 0; 1659 } 1660 UI_method_set_opener(ui_method, UI_method_get_opener(UI_OpenSSL())); 1661 UI_method_set_closer(ui_method, UI_method_get_closer(UI_OpenSSL())); 1662 UI_method_set_reader(ui_method, ssl_ui_reader); 1663 UI_method_set_writer(ui_method, ssl_ui_writer); 1664 1665 store = OSSL_STORE_open_ex(key_file, data->state.libctx, 1666 data->state.propq, ui_method, NULL, NULL, 1667 NULL, NULL); 1668 if(!store) { 1669 failf(data, "Failed to open OpenSSL store: %s", 1670 ossl_strerror(ERR_get_error(), error_buffer, 1671 sizeof(error_buffer))); 1672 return 0; 1673 } 1674 if(OSSL_STORE_expect(store, OSSL_STORE_INFO_PKEY) != 1) { 1675 failf(data, "Failed to set store preference. Ignoring the error: %s", 1676 ossl_strerror(ERR_get_error(), error_buffer, 1677 sizeof(error_buffer))); 1678 } 1679 1680 info = OSSL_STORE_load(store); 1681 if(info) { 1682 int ossl_type = OSSL_STORE_INFO_get_type(info); 1683 1684 if(ossl_type == OSSL_STORE_INFO_PKEY) 1685 priv_key = OSSL_STORE_INFO_get1_PKEY(info); 1686 OSSL_STORE_INFO_free(info); 1687 } 1688 OSSL_STORE_close(store); 1689 UI_destroy_method(ui_method); 1690 if(!priv_key) { 1691 failf(data, "No private key found in the openssl store: %s", 1692 ossl_strerror(ERR_get_error(), error_buffer, 1693 sizeof(error_buffer))); 1694 return 0; 1695 } 1696 1697 if(SSL_CTX_use_PrivateKey(ctx, priv_key) != 1) { 1698 failf(data, "unable to set private key [%s]", 1699 ossl_strerror(ERR_get_error(), error_buffer, 1700 sizeof(error_buffer))); 1701 EVP_PKEY_free(priv_key); 1702 return 0; 1703 } 1704 EVP_PKEY_free(priv_key); /* we do not need the handle any more... */ 1705 } 1706 else { 1707 failf(data, "crypto provider not set, cannot load private key"); 1708 return 0; 1709 } 1710 } 1711 break; 1712 #endif 1713 1714 case SSL_FILETYPE_PKCS12: 1715 if(!cert_done) { 1716 failf(data, "file type P12 for private key not supported"); 1717 return 0; 1718 } 1719 break; 1720 default: 1721 failf(data, "not supported file type for private key"); 1722 return 0; 1723 } 1724 1725 ssl = SSL_new(ctx); 1726 if(!ssl) { 1727 failf(data, "unable to create an SSL structure"); 1728 return 0; 1729 } 1730 1731 x509 = SSL_get_certificate(ssl); 1732 1733 /* This version was provided by Evan Jordan and is supposed to not 1734 leak memory as the previous version: */ 1735 if(x509) { 1736 EVP_PKEY *pktmp = X509_get_pubkey(x509); 1737 EVP_PKEY_copy_parameters(pktmp, SSL_get_privatekey(ssl)); 1738 EVP_PKEY_free(pktmp); 1739 } 1740 1741 #if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_IS_BORINGSSL) && \ 1742 !defined(OPENSSL_NO_DEPRECATED_3_0) 1743 { 1744 /* If RSA is used, do not check the private key if its flags indicate 1745 * it does not support it. */ 1746 EVP_PKEY *priv_key = SSL_get_privatekey(ssl); 1747 int pktype; 1748 #ifdef HAVE_OPAQUE_EVP_PKEY 1749 pktype = EVP_PKEY_id(priv_key); 1750 #else 1751 pktype = priv_key->type; 1752 #endif 1753 if(pktype == EVP_PKEY_RSA) { 1754 RSA *rsa = EVP_PKEY_get1_RSA(priv_key); 1755 if(RSA_flags(rsa) & RSA_METHOD_FLAG_NO_CHECK) 1756 check_privkey = FALSE; 1757 RSA_free(rsa); /* Decrement reference count */ 1758 } 1759 } 1760 #endif 1761 1762 SSL_free(ssl); 1763 1764 /* If we are using DSA, we can copy the parameters from 1765 * the private key */ 1766 1767 if(check_privkey == TRUE) { 1768 /* Now we know that a key and cert have been set against 1769 * the SSL context */ 1770 if(!SSL_CTX_check_private_key(ctx)) { 1771 failf(data, "Private key does not match the certificate public key"); 1772 return 0; 1773 } 1774 } 1775 } 1776 return 1; 1777 } 1778 1779 /* returns non-zero on failure */ 1780 static CURLcode x509_name_oneline(X509_NAME *a, struct dynbuf *d) 1781 { 1782 BIO *bio_out = BIO_new(BIO_s_mem()); 1783 BUF_MEM *biomem; 1784 int rc; 1785 CURLcode result = CURLE_OUT_OF_MEMORY; 1786 1787 if(bio_out) { 1788 curlx_dyn_reset(d); 1789 rc = X509_NAME_print_ex(bio_out, a, 0, XN_FLAG_SEP_SPLUS_SPC); 1790 if(rc != -1) { 1791 BIO_get_mem_ptr(bio_out, &biomem); 1792 result = curlx_dyn_addn(d, biomem->data, biomem->length); 1793 BIO_free(bio_out); 1794 } 1795 } 1796 return result; 1797 } 1798 1799 /** 1800 * Global SSL init 1801 * 1802 * @retval 0 error initializing SSL 1803 * @retval 1 SSL initialized successfully 1804 */ 1805 static int ossl_init(void) 1806 { 1807 #if OPENSSL_VERSION_NUMBER >= 0x10100000L 1808 const uint64_t flags = 1809 #ifdef OPENSSL_INIT_ENGINE_ALL_BUILTIN 1810 /* not present in BoringSSL */ 1811 OPENSSL_INIT_ENGINE_ALL_BUILTIN | 1812 #endif 1813 #ifdef CURL_DISABLE_OPENSSL_AUTO_LOAD_CONFIG 1814 OPENSSL_INIT_NO_LOAD_CONFIG | 1815 #else 1816 OPENSSL_INIT_LOAD_CONFIG | 1817 #endif 1818 0; 1819 OPENSSL_init_ssl(flags, NULL); 1820 #else 1821 OPENSSL_load_builtin_modules(); 1822 1823 #ifdef USE_OPENSSL_ENGINE 1824 ENGINE_load_builtin_engines(); 1825 #endif 1826 1827 /* CONF_MFLAGS_DEFAULT_SECTION was introduced some time between 0.9.8b and 1828 0.9.8e */ 1829 #ifndef CONF_MFLAGS_DEFAULT_SECTION 1830 #define CONF_MFLAGS_DEFAULT_SECTION 0x0 1831 #endif 1832 1833 #ifndef CURL_DISABLE_OPENSSL_AUTO_LOAD_CONFIG 1834 CONF_modules_load_file(NULL, NULL, 1835 CONF_MFLAGS_DEFAULT_SECTION| 1836 CONF_MFLAGS_IGNORE_MISSING_FILE); 1837 #endif 1838 1839 /* Let's get nice error messages */ 1840 SSL_load_error_strings(); 1841 1842 /* Init the global ciphers and digests */ 1843 if(!SSLeay_add_ssl_algorithms()) 1844 return 0; 1845 1846 OpenSSL_add_all_algorithms(); 1847 #endif 1848 1849 Curl_tls_keylog_open(); 1850 1851 return 1; 1852 } 1853 1854 /* Global cleanup */ 1855 static void ossl_cleanup(void) 1856 { 1857 #if OPENSSL_VERSION_NUMBER >= 0x10100000L 1858 /* OpenSSL 1.1 deprecates all these cleanup functions and 1859 turns them into no-ops in OpenSSL 1.0 compatibility mode */ 1860 #else 1861 /* Free ciphers and digests lists */ 1862 EVP_cleanup(); 1863 1864 #ifdef USE_OPENSSL_ENGINE 1865 /* Free engine list */ 1866 ENGINE_cleanup(); 1867 #endif 1868 1869 /* Free OpenSSL error strings */ 1870 ERR_free_strings(); 1871 1872 /* Free thread local error state, destroying hash upon zero refcount */ 1873 ERR_remove_thread_state(NULL); 1874 1875 /* Free all memory allocated by all configuration modules */ 1876 CONF_modules_free(); 1877 1878 #ifdef HAVE_SSL_COMP_FREE_COMPRESSION_METHODS 1879 SSL_COMP_free_compression_methods(); 1880 #endif 1881 #endif 1882 1883 Curl_tls_keylog_close(); 1884 } 1885 1886 /* Selects an OpenSSL crypto engine or provider. 1887 */ 1888 static CURLcode ossl_set_engine(struct Curl_easy *data, const char *name) 1889 { 1890 #ifdef USE_OPENSSL_ENGINE 1891 CURLcode result = CURLE_SSL_ENGINE_NOTFOUND; 1892 ENGINE *e = ENGINE_by_id(name); 1893 1894 if(e) { 1895 1896 if(data->state.engine) { 1897 ENGINE_finish(data->state.engine); 1898 ENGINE_free(data->state.engine); 1899 data->state.engine = NULL; 1900 } 1901 if(!ENGINE_init(e)) { 1902 char buf[256]; 1903 1904 ENGINE_free(e); 1905 failf(data, "Failed to initialise SSL Engine '%s': %s", 1906 name, ossl_strerror(ERR_get_error(), buf, sizeof(buf))); 1907 result = CURLE_SSL_ENGINE_INITFAILED; 1908 e = NULL; 1909 } 1910 else { 1911 result = CURLE_OK; 1912 } 1913 data->state.engine = e; 1914 return result; 1915 } 1916 #endif 1917 #ifdef OPENSSL_HAS_PROVIDERS 1918 return ossl_set_provider(data, name); 1919 #else 1920 (void)name; 1921 failf(data, "OpenSSL engine not found"); 1922 return CURLE_SSL_ENGINE_NOTFOUND; 1923 #endif 1924 } 1925 1926 /* Sets engine as default for all SSL operations 1927 */ 1928 static CURLcode ossl_set_engine_default(struct Curl_easy *data) 1929 { 1930 #ifdef USE_OPENSSL_ENGINE 1931 if(data->state.engine) { 1932 if(ENGINE_set_default(data->state.engine, ENGINE_METHOD_ALL) > 0) { 1933 infof(data, "set default crypto engine '%s'", 1934 ENGINE_get_id(data->state.engine)); 1935 } 1936 else { 1937 failf(data, "set default crypto engine '%s' failed", 1938 ENGINE_get_id(data->state.engine)); 1939 return CURLE_SSL_ENGINE_SETFAILED; 1940 } 1941 } 1942 #else 1943 (void) data; 1944 #endif 1945 return CURLE_OK; 1946 } 1947 1948 /* Return list of OpenSSL crypto engine names. 1949 */ 1950 static struct curl_slist *ossl_engines_list(struct Curl_easy *data) 1951 { 1952 struct curl_slist *list = NULL; 1953 #ifdef USE_OPENSSL_ENGINE 1954 struct curl_slist *beg; 1955 ENGINE *e; 1956 1957 for(e = ENGINE_get_first(); e; e = ENGINE_get_next(e)) { 1958 beg = curl_slist_append(list, ENGINE_get_id(e)); 1959 if(!beg) { 1960 curl_slist_free_all(list); 1961 return NULL; 1962 } 1963 list = beg; 1964 } 1965 #endif 1966 (void) data; 1967 return list; 1968 } 1969 1970 #if defined(OPENSSL_HAS_PROVIDERS) 1971 1972 static void ossl_provider_cleanup(struct Curl_easy *data) 1973 { 1974 if(data->state.baseprov) { 1975 OSSL_PROVIDER_unload(data->state.baseprov); 1976 data->state.baseprov = NULL; 1977 } 1978 if(data->state.provider) { 1979 OSSL_PROVIDER_unload(data->state.provider); 1980 data->state.provider = NULL; 1981 } 1982 OSSL_LIB_CTX_free(data->state.libctx); 1983 data->state.libctx = NULL; 1984 Curl_safefree(data->state.propq); 1985 data->state.provider_loaded = FALSE; 1986 } 1987 1988 #define MAX_PROVIDER_LEN 128 /* reasonable */ 1989 1990 /* Selects an OpenSSL crypto provider. 1991 * 1992 * A provider might need an associated property, a string passed on to 1993 * OpenSSL. Specify this as [PROVIDER][:PROPERTY]: separate the name and the 1994 * property with a colon. No colon means no property is set. 1995 * 1996 * An example provider + property looks like "tpm2:?provider=tpm2". 1997 */ 1998 static CURLcode ossl_set_provider(struct Curl_easy *data, const char *iname) 1999 { 2000 char name[MAX_PROVIDER_LEN + 1]; 2001 struct Curl_str prov; 2002 const char *propq = NULL; 2003 2004 if(!iname) { 2005 /* clear and cleanup provider use */ 2006 ossl_provider_cleanup(data); 2007 return CURLE_OK; 2008 } 2009 if(curlx_str_until(&iname, &prov, MAX_PROVIDER_LEN, ':')) 2010 return CURLE_BAD_FUNCTION_ARGUMENT; 2011 2012 if(!curlx_str_single(&iname, ':')) 2013 /* there was a colon, get the propq until the end of string */ 2014 propq = iname; 2015 2016 /* we need the name in a buffer, null-terminated */ 2017 memcpy(name, curlx_str(&prov), curlx_strlen(&prov)); 2018 name[curlx_strlen(&prov)] = 0; 2019 2020 if(!data->state.libctx) { 2021 OSSL_LIB_CTX *libctx = OSSL_LIB_CTX_new(); 2022 if(!libctx) 2023 return CURLE_OUT_OF_MEMORY; 2024 if(propq) { 2025 data->state.propq = strdup(propq); 2026 if(!data->state.propq) { 2027 OSSL_LIB_CTX_free(libctx); 2028 return CURLE_OUT_OF_MEMORY; 2029 } 2030 } 2031 data->state.libctx = libctx; 2032 } 2033 2034 #ifndef CURL_DISABLE_OPENSSL_AUTO_LOAD_CONFIG 2035 /* load the configuration file into the library context before checking the 2036 * provider availability */ 2037 if(!OSSL_LIB_CTX_load_config(data->state.libctx, NULL)) { 2038 infof(data, "Failed to load default openssl config. Proceeding."); 2039 } 2040 #endif 2041 2042 if(OSSL_PROVIDER_available(data->state.libctx, name)) { 2043 /* already loaded through the configuration - no action needed */ 2044 data->state.provider_loaded = TRUE; 2045 return CURLE_OK; 2046 } 2047 2048 data->state.provider = 2049 OSSL_PROVIDER_try_load(data->state.libctx, name, 1); 2050 if(!data->state.provider) { 2051 char error_buffer[256]; 2052 failf(data, "Failed to initialize provider: %s", 2053 ossl_strerror(ERR_get_error(), error_buffer, 2054 sizeof(error_buffer))); 2055 ossl_provider_cleanup(data); 2056 return CURLE_SSL_ENGINE_NOTFOUND; 2057 } 2058 2059 /* load the base provider as well */ 2060 data->state.baseprov = 2061 OSSL_PROVIDER_try_load(data->state.libctx, "base", 1); 2062 if(!data->state.baseprov) { 2063 ossl_provider_cleanup(data); 2064 failf(data, "Failed to load base"); 2065 return CURLE_SSL_ENGINE_NOTFOUND; 2066 } 2067 else 2068 data->state.provider_loaded = TRUE; 2069 return CURLE_OK; 2070 } 2071 #endif 2072 2073 2074 static CURLcode ossl_shutdown(struct Curl_cfilter *cf, 2075 struct Curl_easy *data, 2076 bool send_shutdown, bool *done) 2077 { 2078 struct ssl_connect_data *connssl = cf->ctx; 2079 struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend; 2080 CURLcode result = CURLE_OK; 2081 char buf[1024]; 2082 int nread = -1, err; 2083 unsigned long sslerr; 2084 size_t i; 2085 2086 DEBUGASSERT(octx); 2087 if(!octx->ssl || cf->shutdown) { 2088 *done = TRUE; 2089 goto out; 2090 } 2091 2092 connssl->io_need = CURL_SSL_IO_NEED_NONE; 2093 *done = FALSE; 2094 if(!(SSL_get_shutdown(octx->ssl) & SSL_SENT_SHUTDOWN)) { 2095 /* We have not started the shutdown from our side yet. Check 2096 * if the server already sent us one. */ 2097 ERR_clear_error(); 2098 for(i = 0; i < 10; ++i) { 2099 nread = SSL_read(octx->ssl, buf, (int)sizeof(buf)); 2100 CURL_TRC_CF(data, cf, "SSL shutdown not sent, read -> %d", nread); 2101 if(nread <= 0) 2102 break; 2103 } 2104 err = SSL_get_error(octx->ssl, nread); 2105 if(!nread && err == SSL_ERROR_ZERO_RETURN) { 2106 bool input_pending; 2107 /* Yes, it did. */ 2108 if(!send_shutdown) { 2109 CURL_TRC_CF(data, cf, "SSL shutdown received, not sending"); 2110 *done = TRUE; 2111 goto out; 2112 } 2113 else if(!cf->next->cft->is_alive(cf->next, data, &input_pending)) { 2114 /* Server closed the connection after its closy notify. It 2115 * seems not interested to see our close notify, so do not 2116 * send it. We are done. */ 2117 connssl->peer_closed = TRUE; 2118 CURL_TRC_CF(data, cf, "peer closed connection"); 2119 *done = TRUE; 2120 goto out; 2121 } 2122 } 2123 } 2124 2125 /* SSL should now have started the shutdown from our side. Since it 2126 * was not complete, we are lacking the close notify from the server. */ 2127 if(send_shutdown && !(SSL_get_shutdown(octx->ssl) & SSL_SENT_SHUTDOWN)) { 2128 ERR_clear_error(); 2129 CURL_TRC_CF(data, cf, "send SSL close notify"); 2130 if(SSL_shutdown(octx->ssl) == 1) { 2131 CURL_TRC_CF(data, cf, "SSL shutdown finished"); 2132 *done = TRUE; 2133 goto out; 2134 } 2135 if(SSL_ERROR_WANT_WRITE == SSL_get_error(octx->ssl, nread)) { 2136 CURL_TRC_CF(data, cf, "SSL shutdown still wants to send"); 2137 connssl->io_need = CURL_SSL_IO_NEED_SEND; 2138 goto out; 2139 } 2140 /* Having sent the close notify, we use SSL_read() to get the 2141 * missing close notify from the server. */ 2142 } 2143 2144 for(i = 0; i < 10; ++i) { 2145 ERR_clear_error(); 2146 nread = SSL_read(octx->ssl, buf, (int)sizeof(buf)); 2147 CURL_TRC_CF(data, cf, "SSL shutdown read -> %d", nread); 2148 if(nread <= 0) 2149 break; 2150 } 2151 err = SSL_get_error(octx->ssl, nread); 2152 switch(err) { 2153 case SSL_ERROR_ZERO_RETURN: /* no more data */ 2154 if(SSL_shutdown(octx->ssl) == 1) 2155 CURL_TRC_CF(data, cf, "SSL shutdown finished"); 2156 else 2157 CURL_TRC_CF(data, cf, "SSL shutdown not received, but closed"); 2158 *done = TRUE; 2159 break; 2160 case SSL_ERROR_NONE: /* just did not get anything */ 2161 case SSL_ERROR_WANT_READ: 2162 /* SSL has send its notify and now wants to read the reply 2163 * from the server. We are not really interested in that. */ 2164 CURL_TRC_CF(data, cf, "SSL shutdown sent, want receive"); 2165 connssl->io_need = CURL_SSL_IO_NEED_RECV; 2166 break; 2167 case SSL_ERROR_WANT_WRITE: 2168 CURL_TRC_CF(data, cf, "SSL shutdown send blocked"); 2169 connssl->io_need = CURL_SSL_IO_NEED_SEND; 2170 break; 2171 default: 2172 /* Server seems to have closed the connection without sending us 2173 * a close notify. */ 2174 sslerr = ERR_get_error(); 2175 CURL_TRC_CF(data, cf, "SSL shutdown, ignore recv error: '%s', errno %d", 2176 (sslerr ? 2177 ossl_strerror(sslerr, buf, sizeof(buf)) : 2178 SSL_ERROR_to_str(err)), 2179 SOCKERRNO); 2180 *done = TRUE; 2181 result = CURLE_OK; 2182 break; 2183 } 2184 2185 out: 2186 cf->shutdown = (result || *done); 2187 if(cf->shutdown || (connssl->io_need != CURL_SSL_IO_NEED_NONE)) 2188 connssl->input_pending = FALSE; 2189 return result; 2190 } 2191 2192 static void ossl_close(struct Curl_cfilter *cf, struct Curl_easy *data) 2193 { 2194 struct ssl_connect_data *connssl = cf->ctx; 2195 struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend; 2196 2197 (void)data; 2198 DEBUGASSERT(octx); 2199 2200 connssl->input_pending = FALSE; 2201 if(octx->ssl) { 2202 SSL_free(octx->ssl); 2203 octx->ssl = NULL; 2204 } 2205 if(octx->ssl_ctx) { 2206 SSL_CTX_free(octx->ssl_ctx); 2207 octx->ssl_ctx = NULL; 2208 octx->x509_store_setup = FALSE; 2209 } 2210 if(octx->bio_method) { 2211 ossl_bio_cf_method_free(octx->bio_method); 2212 octx->bio_method = NULL; 2213 } 2214 } 2215 2216 /* 2217 * This function is called when the 'data' struct is going away. Close 2218 * down everything and free all resources! 2219 */ 2220 static void ossl_close_all(struct Curl_easy *data) 2221 { 2222 #ifdef USE_OPENSSL_ENGINE 2223 if(data->state.engine) { 2224 ENGINE_finish(data->state.engine); 2225 ENGINE_free(data->state.engine); 2226 data->state.engine = NULL; 2227 } 2228 #else 2229 (void)data; 2230 #endif 2231 #ifdef OPENSSL_HAS_PROVIDERS 2232 ossl_provider_cleanup(data); 2233 #endif 2234 #ifndef HAVE_ERR_REMOVE_THREAD_STATE_DEPRECATED 2235 /* OpenSSL 1.0.1 and 1.0.2 build an error queue that is stored per-thread 2236 so we need to clean it here in case the thread will be killed. All OpenSSL 2237 code should extract the error in association with the error so clearing 2238 this queue here should be harmless at worst. */ 2239 ERR_remove_thread_state(NULL); 2240 #endif 2241 } 2242 2243 /* ====================================================== */ 2244 2245 /* 2246 * Match subjectAltName against the hostname. 2247 */ 2248 static bool subj_alt_hostcheck(struct Curl_easy *data, 2249 const char *match_pattern, 2250 size_t matchlen, 2251 const char *hostname, 2252 size_t hostlen, 2253 const char *dispname) 2254 { 2255 #ifdef CURL_DISABLE_VERBOSE_STRINGS 2256 (void)dispname; 2257 (void)data; 2258 #endif 2259 if(Curl_cert_hostcheck(match_pattern, matchlen, hostname, hostlen)) { 2260 infof(data, " subjectAltName: host \"%s\" matched cert's \"%s\"", 2261 dispname, match_pattern); 2262 return TRUE; 2263 } 2264 return FALSE; 2265 } 2266 2267 /* Quote from RFC2818 section 3.1 "Server Identity" 2268 2269 If a subjectAltName extension of type dNSName is present, that MUST 2270 be used as the identity. Otherwise, the (most specific) Common Name 2271 field in the Subject field of the certificate MUST be used. Although 2272 the use of the Common Name is existing practice, it is deprecated and 2273 Certification Authorities are encouraged to use the dNSName instead. 2274 2275 Matching is performed using the matching rules specified by 2276 [RFC2459]. If more than one identity of a given type is present in 2277 the certificate (e.g., more than one dNSName name, a match in any one 2278 of the set is considered acceptable.) Names may contain the wildcard 2279 character * which is considered to match any single domain name 2280 component or component fragment. E.g., *.a.com matches foo.a.com but 2281 not bar.foo.a.com. f*.com matches foo.com but not bar.com. 2282 2283 In some cases, the URI is specified as an IP address rather than a 2284 hostname. In this case, the iPAddress subjectAltName must be present 2285 in the certificate and must exactly match the IP in the URI. 2286 2287 This function is now used from ngtcp2 (QUIC) as well. 2288 */ 2289 static CURLcode ossl_verifyhost(struct Curl_easy *data, 2290 struct connectdata *conn, 2291 struct ssl_peer *peer, X509 *server_cert) 2292 { 2293 bool matched = FALSE; 2294 int target; /* target type, GEN_DNS or GEN_IPADD */ 2295 size_t addrlen = 0; 2296 STACK_OF(GENERAL_NAME) *altnames; 2297 #ifdef USE_IPV6 2298 struct in6_addr addr; 2299 #else 2300 struct in_addr addr; 2301 #endif 2302 CURLcode result = CURLE_OK; 2303 bool dNSName = FALSE; /* if a dNSName field exists in the cert */ 2304 bool iPAddress = FALSE; /* if an iPAddress field exists in the cert */ 2305 size_t hostlen; 2306 2307 (void)conn; 2308 hostlen = strlen(peer->hostname); 2309 switch(peer->type) { 2310 case CURL_SSL_PEER_IPV4: 2311 if(!curlx_inet_pton(AF_INET, peer->hostname, &addr)) 2312 return CURLE_PEER_FAILED_VERIFICATION; 2313 target = GEN_IPADD; 2314 addrlen = sizeof(struct in_addr); 2315 break; 2316 #ifdef USE_IPV6 2317 case CURL_SSL_PEER_IPV6: 2318 if(!curlx_inet_pton(AF_INET6, peer->hostname, &addr)) 2319 return CURLE_PEER_FAILED_VERIFICATION; 2320 target = GEN_IPADD; 2321 addrlen = sizeof(struct in6_addr); 2322 break; 2323 #endif 2324 case CURL_SSL_PEER_DNS: 2325 target = GEN_DNS; 2326 break; 2327 default: 2328 DEBUGASSERT(0); 2329 failf(data, "unexpected ssl peer type: %d", peer->type); 2330 return CURLE_PEER_FAILED_VERIFICATION; 2331 } 2332 2333 /* get a "list" of alternative names */ 2334 altnames = X509_get_ext_d2i(server_cert, NID_subject_alt_name, NULL, NULL); 2335 2336 if(altnames) { 2337 #if defined(OPENSSL_IS_BORINGSSL) || defined(OPENSSL_IS_AWSLC) 2338 size_t numalts; 2339 size_t i; 2340 #else 2341 int numalts; 2342 int i; 2343 #endif 2344 bool dnsmatched = FALSE; 2345 bool ipmatched = FALSE; 2346 2347 /* get amount of alternatives, RFC2459 claims there MUST be at least 2348 one, but we do not depend on it... */ 2349 numalts = sk_GENERAL_NAME_num(altnames); 2350 2351 /* loop through all alternatives - until a dnsmatch */ 2352 for(i = 0; (i < numalts) && !dnsmatched; i++) { 2353 /* get a handle to alternative name number i */ 2354 const GENERAL_NAME *check = sk_GENERAL_NAME_value(altnames, i); 2355 2356 if(check->type == GEN_DNS) 2357 dNSName = TRUE; 2358 else if(check->type == GEN_IPADD) 2359 iPAddress = TRUE; 2360 2361 /* only check alternatives of the same type the target is */ 2362 if(check->type == target) { 2363 /* get data and length */ 2364 const char *altptr = (const char *)ASN1_STRING_get0_data(check->d.ia5); 2365 size_t altlen = (size_t) ASN1_STRING_length(check->d.ia5); 2366 2367 switch(target) { 2368 case GEN_DNS: /* name/pattern comparison */ 2369 /* The OpenSSL manpage explicitly says: "In general it cannot be 2370 assumed that the data returned by ASN1_STRING_data() is null 2371 terminated or does not contain embedded nulls." But also that 2372 "The actual format of the data will depend on the actual string 2373 type itself: for example for an IA5String the data will be ASCII" 2374 2375 It has been however verified that in 0.9.6 and 0.9.7, IA5String 2376 is always null-terminated. 2377 */ 2378 if((altlen == strlen(altptr)) && 2379 /* if this is not true, there was an embedded zero in the name 2380 string and we cannot match it. */ 2381 subj_alt_hostcheck(data, altptr, altlen, 2382 peer->hostname, hostlen, 2383 peer->dispname)) { 2384 dnsmatched = TRUE; 2385 } 2386 break; 2387 2388 case GEN_IPADD: /* IP address comparison */ 2389 /* compare alternative IP address if the data chunk is the same size 2390 our server IP address is */ 2391 if((altlen == addrlen) && !memcmp(altptr, &addr, altlen)) { 2392 ipmatched = TRUE; 2393 infof(data, 2394 " subjectAltName: host \"%s\" matched cert's IP address!", 2395 peer->dispname); 2396 } 2397 break; 2398 } 2399 } 2400 } 2401 GENERAL_NAMES_free(altnames); 2402 2403 if(dnsmatched || ipmatched) 2404 matched = TRUE; 2405 } 2406 2407 if(matched) 2408 /* an alternative name matched */ 2409 ; 2410 else if(dNSName || iPAddress) { 2411 const char *tname = (peer->type == CURL_SSL_PEER_DNS) ? "hostname" : 2412 (peer->type == CURL_SSL_PEER_IPV4) ? 2413 "ipv4 address" : "ipv6 address"; 2414 infof(data, " subjectAltName does not match %s %s", tname, peer->dispname); 2415 failf(data, "SSL: no alternative certificate subject name matches " 2416 "target %s '%s'", tname, peer->dispname); 2417 result = CURLE_PEER_FAILED_VERIFICATION; 2418 } 2419 else { 2420 /* we have to look to the last occurrence of a commonName in the 2421 distinguished one to get the most significant one. */ 2422 int i = -1; 2423 unsigned char *cn = NULL; 2424 int cnlen = 0; 2425 bool free_cn = FALSE; 2426 2427 /* The following is done because of a bug in 0.9.6b */ 2428 X509_NAME *name = X509_get_subject_name(server_cert); 2429 if(name) { 2430 int j; 2431 while((j = X509_NAME_get_index_by_NID(name, NID_commonName, i)) >= 0) 2432 i = j; 2433 } 2434 2435 /* we have the name entry and we will now convert this to a string 2436 that we can use for comparison. Doing this we support BMPstring, 2437 UTF8, etc. */ 2438 2439 if(i >= 0) { 2440 ASN1_STRING *tmp = 2441 X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name, i)); 2442 2443 /* In OpenSSL 0.9.7d and earlier, ASN1_STRING_to_UTF8 fails if the input 2444 is already UTF-8 encoded. We check for this case and copy the raw 2445 string manually to avoid the problem. This code can be made 2446 conditional in the future when OpenSSL has been fixed. */ 2447 if(tmp) { 2448 if(ASN1_STRING_type(tmp) == V_ASN1_UTF8STRING) { 2449 cnlen = ASN1_STRING_length(tmp); 2450 cn = (unsigned char *)CURL_UNCONST(ASN1_STRING_get0_data(tmp)); 2451 } 2452 else { /* not a UTF8 name */ 2453 cnlen = ASN1_STRING_to_UTF8(&cn, tmp); 2454 free_cn = TRUE; 2455 } 2456 2457 if((cnlen <= 0) || !cn) 2458 result = CURLE_OUT_OF_MEMORY; 2459 else if((size_t)cnlen != strlen((char *)cn)) { 2460 /* there was a terminating zero before the end of string, this 2461 cannot match and we return failure! */ 2462 failf(data, "SSL: illegal cert name field"); 2463 result = CURLE_PEER_FAILED_VERIFICATION; 2464 } 2465 } 2466 } 2467 2468 if(result) 2469 /* error already detected, pass through */ 2470 ; 2471 else if(!cn) { 2472 failf(data, 2473 "SSL: unable to obtain common name from peer certificate"); 2474 result = CURLE_PEER_FAILED_VERIFICATION; 2475 } 2476 else if(!Curl_cert_hostcheck((const char *)cn, cnlen, 2477 peer->hostname, hostlen)) { 2478 failf(data, "SSL: certificate subject name '%s' does not match " 2479 "target hostname '%s'", cn, peer->dispname); 2480 result = CURLE_PEER_FAILED_VERIFICATION; 2481 } 2482 else { 2483 infof(data, " common name: %s (matched)", cn); 2484 } 2485 if(free_cn) 2486 OPENSSL_free(cn); 2487 } 2488 2489 return result; 2490 } 2491 2492 #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_OCSP) 2493 static CURLcode verifystatus(struct Curl_cfilter *cf, 2494 struct Curl_easy *data, 2495 struct ossl_ctx *octx) 2496 { 2497 int i, ocsp_status; 2498 #ifdef OPENSSL_IS_AWSLC 2499 const uint8_t *status; 2500 #else 2501 unsigned char *status; 2502 #endif 2503 const unsigned char *p; 2504 CURLcode result = CURLE_OK; 2505 OCSP_RESPONSE *rsp = NULL; 2506 OCSP_BASICRESP *br = NULL; 2507 X509_STORE *st = NULL; 2508 STACK_OF(X509) *ch = NULL; 2509 X509 *cert; 2510 OCSP_CERTID *id = NULL; 2511 int cert_status, crl_reason; 2512 ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd; 2513 int ret; 2514 long len; 2515 2516 (void)cf; 2517 DEBUGASSERT(octx); 2518 2519 len = (long)SSL_get_tlsext_status_ocsp_resp(octx->ssl, &status); 2520 2521 if(!status) { 2522 failf(data, "No OCSP response received"); 2523 result = CURLE_SSL_INVALIDCERTSTATUS; 2524 goto end; 2525 } 2526 p = status; 2527 rsp = d2i_OCSP_RESPONSE(NULL, &p, len); 2528 if(!rsp) { 2529 failf(data, "Invalid OCSP response"); 2530 result = CURLE_SSL_INVALIDCERTSTATUS; 2531 goto end; 2532 } 2533 2534 ocsp_status = OCSP_response_status(rsp); 2535 if(ocsp_status != OCSP_RESPONSE_STATUS_SUCCESSFUL) { 2536 failf(data, "Invalid OCSP response status: %s (%d)", 2537 OCSP_response_status_str(ocsp_status), ocsp_status); 2538 result = CURLE_SSL_INVALIDCERTSTATUS; 2539 goto end; 2540 } 2541 2542 br = OCSP_response_get1_basic(rsp); 2543 if(!br) { 2544 failf(data, "Invalid OCSP response"); 2545 result = CURLE_SSL_INVALIDCERTSTATUS; 2546 goto end; 2547 } 2548 2549 ch = SSL_get_peer_cert_chain(octx->ssl); 2550 if(!ch) { 2551 failf(data, "Could not get peer certificate chain"); 2552 result = CURLE_SSL_INVALIDCERTSTATUS; 2553 goto end; 2554 } 2555 st = SSL_CTX_get_cert_store(octx->ssl_ctx); 2556 2557 if(OCSP_basic_verify(br, ch, st, 0) <= 0) { 2558 failf(data, "OCSP response verification failed"); 2559 result = CURLE_SSL_INVALIDCERTSTATUS; 2560 goto end; 2561 } 2562 2563 /* Compute the certificate's ID */ 2564 cert = SSL_get1_peer_certificate(octx->ssl); 2565 if(!cert) { 2566 failf(data, "Error getting peer certificate"); 2567 result = CURLE_SSL_INVALIDCERTSTATUS; 2568 goto end; 2569 } 2570 2571 for(i = 0; i < (int)sk_X509_num(ch); i++) { 2572 X509 *issuer = sk_X509_value(ch, (ossl_valsize_t)i); 2573 if(X509_check_issued(issuer, cert) == X509_V_OK) { 2574 id = OCSP_cert_to_id(EVP_sha1(), cert, issuer); 2575 break; 2576 } 2577 } 2578 X509_free(cert); 2579 2580 if(!id) { 2581 failf(data, "Error computing OCSP ID"); 2582 result = CURLE_SSL_INVALIDCERTSTATUS; 2583 goto end; 2584 } 2585 2586 /* Find the single OCSP response corresponding to the certificate ID */ 2587 ret = OCSP_resp_find_status(br, id, &cert_status, &crl_reason, &rev, 2588 &thisupd, &nextupd); 2589 OCSP_CERTID_free(id); 2590 if(ret != 1) { 2591 failf(data, "Could not find certificate ID in OCSP response"); 2592 result = CURLE_SSL_INVALIDCERTSTATUS; 2593 goto end; 2594 } 2595 2596 /* Validate the corresponding single OCSP response */ 2597 if(!OCSP_check_validity(thisupd, nextupd, 300L, -1L)) { 2598 failf(data, "OCSP response has expired"); 2599 result = CURLE_SSL_INVALIDCERTSTATUS; 2600 goto end; 2601 } 2602 2603 infof(data, "SSL certificate status: %s (%d)", 2604 OCSP_cert_status_str(cert_status), cert_status); 2605 2606 switch(cert_status) { 2607 case V_OCSP_CERTSTATUS_GOOD: 2608 break; 2609 2610 case V_OCSP_CERTSTATUS_REVOKED: 2611 result = CURLE_SSL_INVALIDCERTSTATUS; 2612 failf(data, "SSL certificate revocation reason: %s (%d)", 2613 OCSP_crl_reason_str(crl_reason), crl_reason); 2614 goto end; 2615 2616 case V_OCSP_CERTSTATUS_UNKNOWN: 2617 default: 2618 result = CURLE_SSL_INVALIDCERTSTATUS; 2619 goto end; 2620 } 2621 2622 end: 2623 if(br) 2624 OCSP_BASICRESP_free(br); 2625 OCSP_RESPONSE_free(rsp); 2626 2627 return result; 2628 } 2629 #endif 2630 2631 #endif /* USE_OPENSSL */ 2632 2633 /* The SSL_CTRL_SET_MSG_CALLBACK does not exist in ancient OpenSSL versions 2634 and thus this cannot be done there. */ 2635 #ifdef SSL_CTRL_SET_MSG_CALLBACK 2636 2637 static const char *ssl_msg_type(int ssl_ver, int msg) 2638 { 2639 #ifdef SSL2_VERSION_MAJOR 2640 if(ssl_ver == SSL2_VERSION_MAJOR) { 2641 switch(msg) { 2642 case SSL2_MT_ERROR: 2643 return "Error"; 2644 case SSL2_MT_CLIENT_HELLO: 2645 return "Client hello"; 2646 case SSL2_MT_CLIENT_MASTER_KEY: 2647 return "Client key"; 2648 case SSL2_MT_CLIENT_FINISHED: 2649 return "Client finished"; 2650 case SSL2_MT_SERVER_HELLO: 2651 return "Server hello"; 2652 case SSL2_MT_SERVER_VERIFY: 2653 return "Server verify"; 2654 case SSL2_MT_SERVER_FINISHED: 2655 return "Server finished"; 2656 case SSL2_MT_REQUEST_CERTIFICATE: 2657 return "Request CERT"; 2658 case SSL2_MT_CLIENT_CERTIFICATE: 2659 return "Client CERT"; 2660 } 2661 } 2662 else 2663 #endif 2664 if(ssl_ver == SSL3_VERSION_MAJOR) { 2665 switch(msg) { 2666 case SSL3_MT_HELLO_REQUEST: 2667 return "Hello request"; 2668 case SSL3_MT_CLIENT_HELLO: 2669 return "Client hello"; 2670 case SSL3_MT_SERVER_HELLO: 2671 return "Server hello"; 2672 #ifdef SSL3_MT_NEWSESSION_TICKET 2673 case SSL3_MT_NEWSESSION_TICKET: 2674 return "Newsession Ticket"; 2675 #endif 2676 case SSL3_MT_CERTIFICATE: 2677 return "Certificate"; 2678 case SSL3_MT_SERVER_KEY_EXCHANGE: 2679 return "Server key exchange"; 2680 case SSL3_MT_CLIENT_KEY_EXCHANGE: 2681 return "Client key exchange"; 2682 case SSL3_MT_CERTIFICATE_REQUEST: 2683 return "Request CERT"; 2684 case SSL3_MT_SERVER_DONE: 2685 return "Server finished"; 2686 case SSL3_MT_CERTIFICATE_VERIFY: 2687 return "CERT verify"; 2688 case SSL3_MT_FINISHED: 2689 return "Finished"; 2690 #ifdef SSL3_MT_CERTIFICATE_STATUS 2691 case SSL3_MT_CERTIFICATE_STATUS: 2692 return "Certificate Status"; 2693 #endif 2694 #ifdef SSL3_MT_ENCRYPTED_EXTENSIONS 2695 case SSL3_MT_ENCRYPTED_EXTENSIONS: 2696 return "Encrypted Extensions"; 2697 #endif 2698 #ifdef SSL3_MT_SUPPLEMENTAL_DATA 2699 case SSL3_MT_SUPPLEMENTAL_DATA: 2700 return "Supplemental data"; 2701 #endif 2702 #ifdef SSL3_MT_END_OF_EARLY_DATA 2703 case SSL3_MT_END_OF_EARLY_DATA: 2704 return "End of early data"; 2705 #endif 2706 #ifdef SSL3_MT_KEY_UPDATE 2707 case SSL3_MT_KEY_UPDATE: 2708 return "Key update"; 2709 #endif 2710 #ifdef SSL3_MT_NEXT_PROTO 2711 case SSL3_MT_NEXT_PROTO: 2712 return "Next protocol"; 2713 #endif 2714 #ifdef SSL3_MT_MESSAGE_HASH 2715 case SSL3_MT_MESSAGE_HASH: 2716 return "Message hash"; 2717 #endif 2718 } 2719 } 2720 return "Unknown"; 2721 } 2722 2723 static const char *tls_rt_type(int type) 2724 { 2725 switch(type) { 2726 #ifdef SSL3_RT_HEADER 2727 case SSL3_RT_HEADER: 2728 return "TLS header"; 2729 #endif 2730 case SSL3_RT_CHANGE_CIPHER_SPEC: 2731 return "TLS change cipher"; 2732 case SSL3_RT_ALERT: 2733 return "TLS alert"; 2734 case SSL3_RT_HANDSHAKE: 2735 return "TLS handshake"; 2736 case SSL3_RT_APPLICATION_DATA: 2737 return "TLS app data"; 2738 default: 2739 return "TLS Unknown"; 2740 } 2741 } 2742 2743 /* 2744 * Our callback from the SSL/TLS layers. 2745 */ 2746 static void ossl_trace(int direction, int ssl_ver, int content_type, 2747 const void *buf, size_t len, SSL *ssl, 2748 void *userp) 2749 { 2750 const char *verstr = "???"; 2751 struct Curl_cfilter *cf = userp; 2752 struct Curl_easy *data = NULL; 2753 char unknown[32]; 2754 2755 if(!cf) 2756 return; 2757 data = CF_DATA_CURRENT(cf); 2758 if(!data || !data->set.fdebug || (direction && direction != 1)) 2759 return; 2760 2761 switch(ssl_ver) { 2762 #ifdef SSL2_VERSION /* removed in recent versions */ 2763 case SSL2_VERSION: 2764 verstr = "SSLv2"; 2765 break; 2766 #endif 2767 #ifdef SSL3_VERSION 2768 case SSL3_VERSION: 2769 verstr = "SSLv3"; 2770 break; 2771 #endif 2772 case TLS1_VERSION: 2773 verstr = "TLSv1.0"; 2774 break; 2775 #ifdef TLS1_1_VERSION 2776 case TLS1_1_VERSION: 2777 verstr = "TLSv1.1"; 2778 break; 2779 #endif 2780 #ifdef TLS1_2_VERSION 2781 case TLS1_2_VERSION: 2782 verstr = "TLSv1.2"; 2783 break; 2784 #endif 2785 #ifdef TLS1_3_VERSION 2786 case TLS1_3_VERSION: 2787 verstr = "TLSv1.3"; 2788 break; 2789 #endif 2790 case 0: 2791 break; 2792 default: 2793 msnprintf(unknown, sizeof(unknown), "(%x)", ssl_ver); 2794 verstr = unknown; 2795 break; 2796 } 2797 2798 /* Log progress for interesting records only (like Handshake or Alert), skip 2799 * all raw record headers (content_type == SSL3_RT_HEADER or ssl_ver == 0). 2800 * For TLS 1.3, skip notification of the decrypted inner Content-Type. 2801 */ 2802 if(ssl_ver 2803 #ifdef SSL3_RT_HEADER 2804 && content_type != SSL3_RT_HEADER 2805 #endif 2806 #ifdef SSL3_RT_INNER_CONTENT_TYPE 2807 && content_type != SSL3_RT_INNER_CONTENT_TYPE 2808 #endif 2809 ) { 2810 const char *msg_name, *tls_rt_name; 2811 char ssl_buf[1024]; 2812 int msg_type, txt_len; 2813 2814 /* the info given when the version is zero is not that useful for us */ 2815 2816 ssl_ver >>= 8; /* check the upper 8 bits only below */ 2817 2818 /* SSLv2 does not seem to have TLS record-type headers, so OpenSSL 2819 * always pass-up content-type as 0. But the interesting message-type 2820 * is at 'buf[0]'. 2821 */ 2822 if(ssl_ver == SSL3_VERSION_MAJOR && content_type) 2823 tls_rt_name = tls_rt_type(content_type); 2824 else 2825 tls_rt_name = ""; 2826 2827 if(content_type == SSL3_RT_CHANGE_CIPHER_SPEC) { 2828 msg_type = *(const char *)buf; 2829 msg_name = "Change cipher spec"; 2830 } 2831 else if(content_type == SSL3_RT_ALERT) { 2832 msg_type = (((const char *)buf)[0] << 8) + ((const char *)buf)[1]; 2833 msg_name = SSL_alert_desc_string_long(msg_type); 2834 } 2835 else { 2836 msg_type = *(const char *)buf; 2837 msg_name = ssl_msg_type(ssl_ver, msg_type); 2838 } 2839 2840 txt_len = msnprintf(ssl_buf, sizeof(ssl_buf), 2841 "%s (%s), %s, %s (%d):\n", 2842 verstr, direction ? "OUT" : "IN", 2843 tls_rt_name, msg_name, msg_type); 2844 Curl_debug(data, CURLINFO_TEXT, ssl_buf, (size_t)txt_len); 2845 } 2846 2847 Curl_debug(data, (direction == 1) ? CURLINFO_SSL_DATA_OUT : 2848 CURLINFO_SSL_DATA_IN, (const char *)buf, len); 2849 (void) ssl; 2850 } 2851 #endif 2852 2853 #ifdef USE_OPENSSL 2854 /* ====================================================== */ 2855 2856 /* Check for ALPN support. */ 2857 #ifndef OPENSSL_NO_TLSEXT 2858 # define HAS_ALPN_OPENSSL 2859 #endif 2860 2861 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) /* 1.1.0 */ 2862 static CURLcode 2863 ossl_set_ssl_version_min_max(struct Curl_cfilter *cf, SSL_CTX *ctx) 2864 { 2865 struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); 2866 /* first, TLS min version... */ 2867 long curl_ssl_version_min = conn_config->version; 2868 long curl_ssl_version_max; 2869 2870 /* convert curl min SSL version option to OpenSSL constant */ 2871 #if (defined(OPENSSL_IS_BORINGSSL) || \ 2872 defined(OPENSSL_IS_AWSLC) || \ 2873 defined(LIBRESSL_VERSION_NUMBER)) 2874 uint16_t ossl_ssl_version_min = 0; 2875 uint16_t ossl_ssl_version_max = 0; 2876 #else 2877 long ossl_ssl_version_min = 0; 2878 long ossl_ssl_version_max = 0; 2879 #endif 2880 switch(curl_ssl_version_min) { 2881 case CURL_SSLVERSION_TLSv1: /* TLS 1.x */ 2882 case CURL_SSLVERSION_TLSv1_0: 2883 ossl_ssl_version_min = TLS1_VERSION; 2884 break; 2885 case CURL_SSLVERSION_TLSv1_1: 2886 ossl_ssl_version_min = TLS1_1_VERSION; 2887 break; 2888 case CURL_SSLVERSION_TLSv1_2: 2889 ossl_ssl_version_min = TLS1_2_VERSION; 2890 break; 2891 case CURL_SSLVERSION_TLSv1_3: 2892 #ifdef TLS1_3_VERSION 2893 ossl_ssl_version_min = TLS1_3_VERSION; 2894 break; 2895 #else 2896 return CURLE_NOT_BUILT_IN; 2897 #endif 2898 } 2899 2900 /* CURL_SSLVERSION_DEFAULT means that no option was selected. 2901 We do not want to pass 0 to SSL_CTX_set_min_proto_version as 2902 it would enable all versions down to the lowest supported by 2903 the library. 2904 So we skip this, and stay with the library default 2905 */ 2906 if(curl_ssl_version_min != CURL_SSLVERSION_DEFAULT) { 2907 if(!SSL_CTX_set_min_proto_version(ctx, ossl_ssl_version_min)) { 2908 return CURLE_SSL_CONNECT_ERROR; 2909 } 2910 } 2911 2912 /* ... then, TLS max version */ 2913 curl_ssl_version_max = (long)conn_config->version_max; 2914 2915 /* convert curl max SSL version option to OpenSSL constant */ 2916 switch(curl_ssl_version_max) { 2917 case CURL_SSLVERSION_MAX_TLSv1_0: 2918 ossl_ssl_version_max = TLS1_VERSION; 2919 break; 2920 case CURL_SSLVERSION_MAX_TLSv1_1: 2921 ossl_ssl_version_max = TLS1_1_VERSION; 2922 break; 2923 case CURL_SSLVERSION_MAX_TLSv1_2: 2924 ossl_ssl_version_max = TLS1_2_VERSION; 2925 break; 2926 #ifdef TLS1_3_VERSION 2927 case CURL_SSLVERSION_MAX_TLSv1_3: 2928 ossl_ssl_version_max = TLS1_3_VERSION; 2929 break; 2930 #endif 2931 case CURL_SSLVERSION_MAX_NONE: /* none selected */ 2932 case CURL_SSLVERSION_MAX_DEFAULT: /* max selected */ 2933 default: 2934 /* SSL_CTX_set_max_proto_version states that: 2935 setting the maximum to 0 will enable 2936 protocol versions up to the highest version 2937 supported by the library */ 2938 ossl_ssl_version_max = 0; 2939 break; 2940 } 2941 2942 if(!SSL_CTX_set_max_proto_version(ctx, ossl_ssl_version_max)) { 2943 return CURLE_SSL_CONNECT_ERROR; 2944 } 2945 2946 return CURLE_OK; 2947 } 2948 #endif 2949 2950 #if defined(OPENSSL_IS_BORINGSSL) || defined(OPENSSL_IS_AWSLC) 2951 typedef uint32_t ctx_option_t; 2952 #elif OPENSSL_VERSION_NUMBER >= 0x30000000L 2953 typedef uint64_t ctx_option_t; 2954 #elif OPENSSL_VERSION_NUMBER >= 0x10100000L && \ 2955 !defined(LIBRESSL_VERSION_NUMBER) 2956 typedef unsigned long ctx_option_t; 2957 #else 2958 typedef long ctx_option_t; 2959 #endif 2960 2961 #if (OPENSSL_VERSION_NUMBER < 0x10100000L) /* 1.1.0 */ 2962 static CURLcode 2963 ossl_set_ssl_version_min_max_legacy(ctx_option_t *ctx_options, 2964 struct Curl_cfilter *cf, 2965 struct Curl_easy *data) 2966 { 2967 struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); 2968 long ssl_version = conn_config->version; 2969 long ssl_version_max = conn_config->version_max; 2970 2971 (void) data; /* In case it is unused. */ 2972 2973 switch(ssl_version) { 2974 case CURL_SSLVERSION_TLSv1_3: 2975 #ifdef TLS1_3_VERSION 2976 { 2977 struct ssl_connect_data *connssl = cf->ctx; 2978 struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend; 2979 DEBUGASSERT(octx); 2980 SSL_CTX_set_max_proto_version(octx->ssl_ctx, TLS1_3_VERSION); 2981 *ctx_options |= SSL_OP_NO_TLSv1_2; 2982 } 2983 #else 2984 (void)ctx_options; 2985 failf(data, OSSL_PACKAGE " was built without TLS 1.3 support"); 2986 return CURLE_NOT_BUILT_IN; 2987 #endif 2988 FALLTHROUGH(); 2989 case CURL_SSLVERSION_TLSv1_2: 2990 *ctx_options |= SSL_OP_NO_TLSv1_1; 2991 FALLTHROUGH(); 2992 case CURL_SSLVERSION_TLSv1_1: 2993 *ctx_options |= SSL_OP_NO_TLSv1; 2994 FALLTHROUGH(); 2995 case CURL_SSLVERSION_TLSv1_0: 2996 case CURL_SSLVERSION_TLSv1: 2997 break; 2998 } 2999 3000 switch(ssl_version_max) { 3001 case CURL_SSLVERSION_MAX_TLSv1_0: 3002 *ctx_options |= SSL_OP_NO_TLSv1_1; 3003 FALLTHROUGH(); 3004 case CURL_SSLVERSION_MAX_TLSv1_1: 3005 *ctx_options |= SSL_OP_NO_TLSv1_2; 3006 FALLTHROUGH(); 3007 case CURL_SSLVERSION_MAX_TLSv1_2: 3008 #ifdef TLS1_3_VERSION 3009 *ctx_options |= SSL_OP_NO_TLSv1_3; 3010 #endif 3011 break; 3012 case CURL_SSLVERSION_MAX_TLSv1_3: 3013 #ifdef TLS1_3_VERSION 3014 break; 3015 #else 3016 failf(data, OSSL_PACKAGE " was built without TLS 1.3 support"); 3017 return CURLE_NOT_BUILT_IN; 3018 #endif 3019 } 3020 return CURLE_OK; 3021 } 3022 #endif 3023 3024 CURLcode Curl_ossl_add_session(struct Curl_cfilter *cf, 3025 struct Curl_easy *data, 3026 const char *ssl_peer_key, 3027 SSL_SESSION *session, 3028 int ietf_tls_id, 3029 const char *alpn, 3030 unsigned char *quic_tp, 3031 size_t quic_tp_len) 3032 { 3033 const struct ssl_config_data *config; 3034 unsigned char *der_session_buf = NULL; 3035 unsigned char *qtp_clone = NULL; 3036 CURLcode result = CURLE_OK; 3037 3038 if(!cf || !data) 3039 goto out; 3040 3041 config = Curl_ssl_cf_get_config(cf, data); 3042 if(config->primary.cache_session) { 3043 struct Curl_ssl_session *sc_session = NULL; 3044 size_t der_session_size; 3045 unsigned char *der_session_ptr; 3046 size_t earlydata_max = 0; 3047 3048 der_session_size = i2d_SSL_SESSION(session, NULL); 3049 if(der_session_size == 0) { 3050 result = CURLE_OUT_OF_MEMORY; 3051 goto out; 3052 } 3053 3054 der_session_buf = der_session_ptr = malloc(der_session_size); 3055 if(!der_session_buf) { 3056 result = CURLE_OUT_OF_MEMORY; 3057 goto out; 3058 } 3059 3060 der_session_size = i2d_SSL_SESSION(session, &der_session_ptr); 3061 if(der_session_size == 0) { 3062 result = CURLE_OUT_OF_MEMORY; 3063 goto out; 3064 } 3065 3066 #ifdef HAVE_OPENSSL_EARLYDATA 3067 earlydata_max = SSL_SESSION_get_max_early_data(session); 3068 #endif 3069 if(quic_tp && quic_tp_len) { 3070 qtp_clone = Curl_memdup0((char *)quic_tp, quic_tp_len); 3071 if(!qtp_clone) { 3072 result = CURLE_OUT_OF_MEMORY; 3073 goto out; 3074 } 3075 } 3076 3077 result = Curl_ssl_session_create2(der_session_buf, der_session_size, 3078 ietf_tls_id, alpn, 3079 (curl_off_t)time(NULL) + 3080 SSL_SESSION_get_timeout(session), 3081 earlydata_max, qtp_clone, quic_tp_len, 3082 &sc_session); 3083 der_session_buf = NULL; /* took ownership of sdata */ 3084 if(!result) { 3085 result = Curl_ssl_scache_put(cf, data, ssl_peer_key, sc_session); 3086 /* took ownership of `sc_session` */ 3087 } 3088 } 3089 3090 out: 3091 free(der_session_buf); 3092 return result; 3093 } 3094 3095 /* The "new session" callback must return zero if the session can be removed 3096 * or non-zero if the session has been put into the session cache. 3097 */ 3098 static int ossl_new_session_cb(SSL *ssl, SSL_SESSION *ssl_sessionid) 3099 { 3100 struct Curl_cfilter *cf = (struct Curl_cfilter*) SSL_get_app_data(ssl); 3101 if(cf) { 3102 struct Curl_easy *data = CF_DATA_CURRENT(cf); 3103 struct ssl_connect_data *connssl = cf->ctx; 3104 Curl_ossl_add_session(cf, data, connssl->peer.scache_key, ssl_sessionid, 3105 SSL_version(ssl), connssl->negotiated.alpn, 3106 NULL, 0); 3107 } 3108 return 0; 3109 } 3110 3111 static CURLcode load_cacert_from_memory(X509_STORE *store, 3112 const struct curl_blob *ca_info_blob) 3113 { 3114 /* these need to be freed at the end */ 3115 BIO *cbio = NULL; 3116 STACK_OF(X509_INFO) *inf = NULL; 3117 3118 /* everything else is just a reference */ 3119 int i, count = 0; 3120 X509_INFO *itmp = NULL; 3121 3122 if(ca_info_blob->len > (size_t)INT_MAX) 3123 return CURLE_SSL_CACERT_BADFILE; 3124 3125 cbio = BIO_new_mem_buf(ca_info_blob->data, (int)ca_info_blob->len); 3126 if(!cbio) 3127 return CURLE_OUT_OF_MEMORY; 3128 3129 inf = PEM_X509_INFO_read_bio(cbio, NULL, NULL, NULL); 3130 if(!inf) { 3131 BIO_free(cbio); 3132 return CURLE_SSL_CACERT_BADFILE; 3133 } 3134 3135 /* add each entry from PEM file to x509_store */ 3136 for(i = 0; i < (int)sk_X509_INFO_num(inf); ++i) { 3137 itmp = sk_X509_INFO_value(inf, (ossl_valsize_t)i); 3138 if(itmp->x509) { 3139 if(X509_STORE_add_cert(store, itmp->x509)) { 3140 ++count; 3141 } 3142 else { 3143 /* set count to 0 to return an error */ 3144 count = 0; 3145 break; 3146 } 3147 } 3148 if(itmp->crl) { 3149 if(X509_STORE_add_crl(store, itmp->crl)) { 3150 ++count; 3151 } 3152 else { 3153 /* set count to 0 to return an error */ 3154 count = 0; 3155 break; 3156 } 3157 } 3158 } 3159 3160 sk_X509_INFO_pop_free(inf, X509_INFO_free); 3161 BIO_free(cbio); 3162 3163 /* if we did not end up importing anything, treat that as an error */ 3164 return (count > 0) ? CURLE_OK : CURLE_SSL_CACERT_BADFILE; 3165 } 3166 3167 #ifdef USE_WIN32_CRYPTO 3168 static CURLcode import_windows_cert_store(struct Curl_easy *data, 3169 const char *name, 3170 X509_STORE *store, 3171 bool *imported) 3172 { 3173 CURLcode result = CURLE_OK; 3174 HCERTSTORE hStore; 3175 3176 *imported = FALSE; 3177 3178 hStore = CertOpenSystemStoreA(0, name); 3179 if(hStore) { 3180 PCCERT_CONTEXT pContext = NULL; 3181 /* The array of enhanced key usage OIDs will vary per certificate and 3182 is declared outside of the loop so that rather than malloc/free each 3183 iteration we can grow it with realloc, when necessary. */ 3184 CERT_ENHKEY_USAGE *enhkey_usage = NULL; 3185 DWORD enhkey_usage_size = 0; 3186 3187 /* This loop makes a best effort to import all valid certificates from 3188 the MS root store. If a certificate cannot be imported it is 3189 skipped. 'result' is used to store only hard-fail conditions (such 3190 as out of memory) that cause an early break. */ 3191 result = CURLE_OK; 3192 for(;;) { 3193 X509 *x509; 3194 FILETIME now; 3195 BYTE key_usage[2]; 3196 DWORD req_size; 3197 const unsigned char *encoded_cert; 3198 pContext = CertEnumCertificatesInStore(hStore, pContext); 3199 if(!pContext) 3200 break; 3201 3202 #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS) 3203 else { 3204 char cert_name[256]; 3205 if(!CertGetNameStringA(pContext, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, 3206 NULL, cert_name, sizeof(cert_name))) 3207 infof(data, "SSL: unknown cert name"); 3208 else 3209 infof(data, "SSL: Checking cert \"%s\"", cert_name); 3210 } 3211 #endif 3212 encoded_cert = (const unsigned char *)pContext->pbCertEncoded; 3213 if(!encoded_cert) 3214 continue; 3215 3216 GetSystemTimeAsFileTime(&now); 3217 if(CompareFileTime(&pContext->pCertInfo->NotBefore, &now) > 0 || 3218 CompareFileTime(&now, &pContext->pCertInfo->NotAfter) > 0) 3219 continue; 3220 3221 /* If key usage exists check for signing attribute */ 3222 if(CertGetIntendedKeyUsage(pContext->dwCertEncodingType, 3223 pContext->pCertInfo, 3224 key_usage, sizeof(key_usage))) { 3225 if(!(key_usage[0] & CERT_KEY_CERT_SIGN_KEY_USAGE)) 3226 continue; 3227 } 3228 else if(GetLastError()) 3229 continue; 3230 3231 /* If enhanced key usage exists check for server auth attribute. 3232 * 3233 * Note "In a Microsoft environment, a certificate might also have 3234 * EKU extended properties that specify valid uses for the 3235 * certificate." The call below checks both, and behavior varies 3236 * depending on what is found. For more details see 3237 * CertGetEnhancedKeyUsage doc. 3238 */ 3239 if(CertGetEnhancedKeyUsage(pContext, 0, NULL, &req_size)) { 3240 if(req_size && req_size > enhkey_usage_size) { 3241 void *tmp = realloc(enhkey_usage, req_size); 3242 3243 if(!tmp) { 3244 failf(data, "SSL: Out of memory allocating for OID list"); 3245 result = CURLE_OUT_OF_MEMORY; 3246 break; 3247 } 3248 3249 enhkey_usage = (CERT_ENHKEY_USAGE *)tmp; 3250 enhkey_usage_size = req_size; 3251 } 3252 3253 if(CertGetEnhancedKeyUsage(pContext, 0, enhkey_usage, &req_size)) { 3254 if(!enhkey_usage->cUsageIdentifier) { 3255 /* "If GetLastError returns CRYPT_E_NOT_FOUND, the certificate 3256 is good for all uses. If it returns zero, the certificate 3257 has no valid uses." */ 3258 if((HRESULT)GetLastError() != CRYPT_E_NOT_FOUND) 3259 continue; 3260 } 3261 else { 3262 DWORD i; 3263 bool found = FALSE; 3264 3265 for(i = 0; i < enhkey_usage->cUsageIdentifier; ++i) { 3266 if(!strcmp("1.3.6.1.5.5.7.3.1" /* OID server auth */, 3267 enhkey_usage->rgpszUsageIdentifier[i])) { 3268 found = TRUE; 3269 break; 3270 } 3271 } 3272 3273 if(!found) 3274 continue; 3275 } 3276 } 3277 else 3278 continue; 3279 } 3280 else 3281 continue; 3282 3283 x509 = d2i_X509(NULL, &encoded_cert, (long)pContext->cbCertEncoded); 3284 if(!x509) 3285 continue; 3286 3287 /* Try to import the certificate. This may fail for legitimate 3288 reasons such as duplicate certificate, which is allowed by MS but 3289 not OpenSSL. */ 3290 if(X509_STORE_add_cert(store, x509) == 1) { 3291 #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS) 3292 infof(data, "SSL: Imported cert"); 3293 #endif 3294 *imported = TRUE; 3295 } 3296 X509_free(x509); 3297 } 3298 3299 free(enhkey_usage); 3300 CertFreeCertificateContext(pContext); 3301 CertCloseStore(hStore, 0); 3302 3303 if(result) 3304 return result; 3305 } 3306 3307 return result; 3308 } 3309 #endif 3310 3311 static CURLcode ossl_populate_x509_store(struct Curl_cfilter *cf, 3312 struct Curl_easy *data, 3313 X509_STORE *store) 3314 { 3315 struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); 3316 struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); 3317 CURLcode result = CURLE_OK; 3318 X509_LOOKUP *lookup = NULL; 3319 const struct curl_blob *ca_info_blob = conn_config->ca_info_blob; 3320 const char * const ssl_cafile = 3321 /* CURLOPT_CAINFO_BLOB overrides CURLOPT_CAINFO */ 3322 (ca_info_blob ? NULL : conn_config->CAfile); 3323 const char * const ssl_capath = conn_config->CApath; 3324 const char * const ssl_crlfile = ssl_config->primary.CRLfile; 3325 const bool verifypeer = conn_config->verifypeer; 3326 bool imported_native_ca = FALSE; 3327 bool imported_ca_info_blob = FALSE; 3328 3329 CURL_TRC_CF(data, cf, "ossl_populate_x509_store, path=%s, blob=%d", 3330 ssl_cafile ? ssl_cafile : "none", !!ca_info_blob); 3331 if(!store) 3332 return CURLE_OUT_OF_MEMORY; 3333 3334 if(verifypeer) { 3335 #ifdef USE_WIN32_CRYPTO 3336 /* Import certificates from the Windows root certificate store if 3337 requested. 3338 https://stackoverflow.com/questions/9507184/ 3339 https://github.com/d3x0r/SACK/blob/master/src/netlib/ssl_layer.c#L1037 3340 https://datatracker.ietf.org/doc/html/rfc5280 */ 3341 if(ssl_config->native_ca_store) { 3342 const char *storeNames[] = { 3343 "ROOT", /* Trusted Root Certification Authorities */ 3344 "CA" /* Intermediate Certification Authorities */ 3345 }; 3346 size_t i; 3347 for(i = 0; i < CURL_ARRAYSIZE(storeNames); ++i) { 3348 bool imported = FALSE; 3349 result = import_windows_cert_store(data, storeNames[i], store, 3350 &imported); 3351 if(result) 3352 return result; 3353 if(imported) { 3354 infof(data, "successfully imported Windows %s store", storeNames[i]); 3355 imported_native_ca = TRUE; 3356 } 3357 else 3358 infof(data, "error importing Windows %s store, continuing anyway", 3359 storeNames[i]); 3360 } 3361 } 3362 #endif 3363 if(ca_info_blob) { 3364 result = load_cacert_from_memory(store, ca_info_blob); 3365 if(result) { 3366 failf(data, "error importing CA certificate blob"); 3367 return result; 3368 } 3369 else { 3370 imported_ca_info_blob = TRUE; 3371 infof(data, "successfully imported CA certificate blob"); 3372 } 3373 } 3374 3375 if(ssl_cafile || ssl_capath) { 3376 #if (OPENSSL_VERSION_NUMBER >= 0x30000000L) 3377 /* OpenSSL 3.0.0 has deprecated SSL_CTX_load_verify_locations */ 3378 if(ssl_cafile && !X509_STORE_load_file(store, ssl_cafile)) { 3379 if(!imported_native_ca && !imported_ca_info_blob) { 3380 /* Fail if we insist on successfully verifying the server. */ 3381 failf(data, "error setting certificate file: %s", ssl_cafile); 3382 return CURLE_SSL_CACERT_BADFILE; 3383 } 3384 else 3385 infof(data, "error setting certificate file, continuing anyway"); 3386 } 3387 if(ssl_capath && !X509_STORE_load_path(store, ssl_capath)) { 3388 if(!imported_native_ca && !imported_ca_info_blob) { 3389 /* Fail if we insist on successfully verifying the server. */ 3390 failf(data, "error setting certificate path: %s", ssl_capath); 3391 return CURLE_SSL_CACERT_BADFILE; 3392 } 3393 else 3394 infof(data, "error setting certificate path, continuing anyway"); 3395 } 3396 #else 3397 /* tell OpenSSL where to find CA certificates that are used to verify the 3398 server's certificate. */ 3399 if(!X509_STORE_load_locations(store, ssl_cafile, ssl_capath)) { 3400 if(!imported_native_ca && !imported_ca_info_blob) { 3401 /* Fail if we insist on successfully verifying the server. */ 3402 failf(data, "error setting certificate verify locations:" 3403 " CAfile: %s CApath: %s", 3404 ssl_cafile ? ssl_cafile : "none", 3405 ssl_capath ? ssl_capath : "none"); 3406 return CURLE_SSL_CACERT_BADFILE; 3407 } 3408 else { 3409 infof(data, "error setting certificate verify locations," 3410 " continuing anyway"); 3411 } 3412 } 3413 #endif 3414 infof(data, " CAfile: %s", ssl_cafile ? ssl_cafile : "none"); 3415 infof(data, " CApath: %s", ssl_capath ? ssl_capath : "none"); 3416 } 3417 3418 #ifdef CURL_CA_FALLBACK 3419 if(!ssl_cafile && !ssl_capath && 3420 !imported_native_ca && !imported_ca_info_blob) { 3421 /* verifying the peer without any CA certificates will not 3422 work so use OpenSSL's built-in default as fallback */ 3423 X509_STORE_set_default_paths(store); 3424 } 3425 #endif 3426 } 3427 3428 if(ssl_crlfile) { 3429 /* tell OpenSSL where to find CRL file that is used to check certificate 3430 * revocation */ 3431 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file()); 3432 if(!lookup || 3433 (!X509_load_crl_file(lookup, ssl_crlfile, X509_FILETYPE_PEM)) ) { 3434 failf(data, "error loading CRL file: %s", ssl_crlfile); 3435 return CURLE_SSL_CRL_BADFILE; 3436 } 3437 /* Everything is fine. */ 3438 infof(data, "successfully loaded CRL file:"); 3439 X509_STORE_set_flags(store, 3440 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL); 3441 3442 infof(data, " CRLfile: %s", ssl_crlfile); 3443 } 3444 3445 if(verifypeer) { 3446 /* Try building a chain using issuers in the trusted store first to avoid 3447 problems with server-sent legacy intermediates. Newer versions of 3448 OpenSSL do alternate chain checking by default but we do not know how to 3449 determine that in a reliable manner. 3450 https://web.archive.org/web/20190422050538/ 3451 rt.openssl.org/Ticket/Display.html?id=3621 3452 */ 3453 #ifdef X509_V_FLAG_TRUSTED_FIRST 3454 X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST); 3455 #endif 3456 #ifdef X509_V_FLAG_PARTIAL_CHAIN 3457 if(!ssl_config->no_partialchain && !ssl_crlfile) { 3458 /* Have intermediate certificates in the trust store be treated as 3459 trust-anchors, in the same way as self-signed root CA certificates 3460 are. This allows users to verify servers using the intermediate cert 3461 only, instead of needing the whole chain. 3462 3463 Due to OpenSSL bug https://github.com/openssl/openssl/issues/5081 we 3464 cannot do partial chains with a CRL check. 3465 */ 3466 X509_STORE_set_flags(store, X509_V_FLAG_PARTIAL_CHAIN); 3467 } 3468 #endif 3469 } 3470 3471 return result; 3472 } 3473 3474 #ifdef HAVE_SSL_X509_STORE_SHARE 3475 3476 /* key to use at `multi->proto_hash` */ 3477 #define MPROTO_OSSL_X509_KEY "tls:ossl:x509:share" 3478 3479 struct ossl_x509_share { 3480 char *CAfile; /* CAfile path used to generate X509 store */ 3481 X509_STORE *store; /* cached X509 store or NULL if none */ 3482 struct curltime time; /* when the cached store was created */ 3483 }; 3484 3485 static void oss_x509_share_free(void *key, size_t key_len, void *p) 3486 { 3487 struct ossl_x509_share *share = p; 3488 DEBUGASSERT(key_len == (sizeof(MPROTO_OSSL_X509_KEY)-1)); 3489 DEBUGASSERT(!memcmp(MPROTO_OSSL_X509_KEY, key, key_len)); 3490 (void)key; 3491 (void)key_len; 3492 if(share->store) { 3493 X509_STORE_free(share->store); 3494 } 3495 free(share->CAfile); 3496 free(share); 3497 } 3498 3499 static bool 3500 ossl_cached_x509_store_expired(const struct Curl_easy *data, 3501 const struct ossl_x509_share *mb) 3502 { 3503 const struct ssl_general_config *cfg = &data->set.general_ssl; 3504 if(cfg->ca_cache_timeout < 0) 3505 return FALSE; 3506 else { 3507 struct curltime now = curlx_now(); 3508 timediff_t elapsed_ms = curlx_timediff(now, mb->time); 3509 timediff_t timeout_ms = cfg->ca_cache_timeout * (timediff_t)1000; 3510 3511 return elapsed_ms >= timeout_ms; 3512 } 3513 } 3514 3515 static bool 3516 ossl_cached_x509_store_different(struct Curl_cfilter *cf, 3517 const struct ossl_x509_share *mb) 3518 { 3519 struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); 3520 if(!mb->CAfile || !conn_config->CAfile) 3521 return mb->CAfile != conn_config->CAfile; 3522 3523 return strcmp(mb->CAfile, conn_config->CAfile); 3524 } 3525 3526 static X509_STORE *ossl_get_cached_x509_store(struct Curl_cfilter *cf, 3527 const struct Curl_easy *data) 3528 { 3529 struct Curl_multi *multi = data->multi; 3530 struct ossl_x509_share *share; 3531 X509_STORE *store = NULL; 3532 3533 DEBUGASSERT(multi); 3534 share = multi ? Curl_hash_pick(&multi->proto_hash, 3535 CURL_UNCONST(MPROTO_OSSL_X509_KEY), 3536 sizeof(MPROTO_OSSL_X509_KEY)-1) : NULL; 3537 if(share && share->store && 3538 !ossl_cached_x509_store_expired(data, share) && 3539 !ossl_cached_x509_store_different(cf, share)) { 3540 store = share->store; 3541 } 3542 3543 return store; 3544 } 3545 3546 static void ossl_set_cached_x509_store(struct Curl_cfilter *cf, 3547 const struct Curl_easy *data, 3548 X509_STORE *store) 3549 { 3550 struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); 3551 struct Curl_multi *multi = data->multi; 3552 struct ossl_x509_share *share; 3553 3554 DEBUGASSERT(multi); 3555 if(!multi) 3556 return; 3557 share = Curl_hash_pick(&multi->proto_hash, 3558 CURL_UNCONST(MPROTO_OSSL_X509_KEY), 3559 sizeof(MPROTO_OSSL_X509_KEY)-1); 3560 3561 if(!share) { 3562 share = calloc(1, sizeof(*share)); 3563 if(!share) 3564 return; 3565 if(!Curl_hash_add2(&multi->proto_hash, 3566 CURL_UNCONST(MPROTO_OSSL_X509_KEY), 3567 sizeof(MPROTO_OSSL_X509_KEY)-1, 3568 share, oss_x509_share_free)) { 3569 free(share); 3570 return; 3571 } 3572 } 3573 3574 if(X509_STORE_up_ref(store)) { 3575 char *CAfile = NULL; 3576 3577 if(conn_config->CAfile) { 3578 CAfile = strdup(conn_config->CAfile); 3579 if(!CAfile) { 3580 X509_STORE_free(store); 3581 return; 3582 } 3583 } 3584 3585 if(share->store) { 3586 X509_STORE_free(share->store); 3587 free(share->CAfile); 3588 } 3589 3590 share->time = curlx_now(); 3591 share->store = store; 3592 share->CAfile = CAfile; 3593 } 3594 } 3595 3596 CURLcode Curl_ssl_setup_x509_store(struct Curl_cfilter *cf, 3597 struct Curl_easy *data, 3598 SSL_CTX *ssl_ctx) 3599 { 3600 struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); 3601 struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); 3602 CURLcode result = CURLE_OK; 3603 X509_STORE *cached_store; 3604 bool cache_criteria_met; 3605 3606 /* Consider the X509 store cacheable if it comes exclusively from a CAfile, 3607 or no source is provided and we are falling back to OpenSSL's built-in 3608 default. */ 3609 cache_criteria_met = (data->set.general_ssl.ca_cache_timeout != 0) && 3610 conn_config->verifypeer && 3611 !conn_config->CApath && 3612 !conn_config->ca_info_blob && 3613 !ssl_config->primary.CRLfile && 3614 !ssl_config->native_ca_store; 3615 3616 cached_store = ossl_get_cached_x509_store(cf, data); 3617 if(cached_store && cache_criteria_met && X509_STORE_up_ref(cached_store)) { 3618 SSL_CTX_set_cert_store(ssl_ctx, cached_store); 3619 } 3620 else { 3621 X509_STORE *store = SSL_CTX_get_cert_store(ssl_ctx); 3622 3623 result = ossl_populate_x509_store(cf, data, store); 3624 if(result == CURLE_OK && cache_criteria_met) { 3625 ossl_set_cached_x509_store(cf, data, store); 3626 } 3627 } 3628 3629 return result; 3630 } 3631 #else /* HAVE_SSL_X509_STORE_SHARE */ 3632 CURLcode Curl_ssl_setup_x509_store(struct Curl_cfilter *cf, 3633 struct Curl_easy *data, 3634 SSL_CTX *ssl_ctx) 3635 { 3636 X509_STORE *store = SSL_CTX_get_cert_store(ssl_ctx); 3637 3638 return ossl_populate_x509_store(cf, data, store); 3639 } 3640 #endif /* HAVE_SSL_X509_STORE_SHARE */ 3641 3642 3643 static CURLcode 3644 ossl_init_session_and_alpns(struct ossl_ctx *octx, 3645 struct Curl_cfilter *cf, 3646 struct Curl_easy *data, 3647 struct ssl_peer *peer, 3648 const struct alpn_spec *alpns_requested, 3649 Curl_ossl_init_session_reuse_cb *sess_reuse_cb) 3650 { 3651 struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); 3652 struct alpn_spec alpns; 3653 char error_buffer[256]; 3654 CURLcode result; 3655 3656 Curl_alpn_copy(&alpns, alpns_requested); 3657 3658 octx->reused_session = FALSE; 3659 if(ssl_config->primary.cache_session) { 3660 struct Curl_ssl_session *scs = NULL; 3661 3662 result = Curl_ssl_scache_take(cf, data, peer->scache_key, &scs); 3663 if(!result && scs && scs->sdata && scs->sdata_len) { 3664 const unsigned char *der_sessionid = scs->sdata; 3665 size_t der_sessionid_size = scs->sdata_len; 3666 SSL_SESSION *ssl_session = NULL; 3667 3668 /* If OpenSSL does not accept the session from the cache, this 3669 * is not an error. We just continue without it. */ 3670 ssl_session = d2i_SSL_SESSION(NULL, &der_sessionid, 3671 (long)der_sessionid_size); 3672 if(ssl_session) { 3673 if(!SSL_set_session(octx->ssl, ssl_session)) { 3674 infof(data, "SSL: SSL_set_session not accepted, " 3675 "continuing without: %s", 3676 ossl_strerror(ERR_get_error(), error_buffer, 3677 sizeof(error_buffer))); 3678 } 3679 else { 3680 infof(data, "SSL reusing session with ALPN '%s'", 3681 scs->alpn ? scs->alpn : "-"); 3682 octx->reused_session = TRUE; 3683 #ifdef HAVE_OPENSSL_EARLYDATA 3684 if(ssl_config->earlydata && scs->alpn && 3685 SSL_SESSION_get_max_early_data(ssl_session) && 3686 !cf->conn->connect_only && 3687 (SSL_version(octx->ssl) == TLS1_3_VERSION)) { 3688 bool do_early_data = FALSE; 3689 if(sess_reuse_cb) { 3690 result = sess_reuse_cb(cf, data, &alpns, scs, &do_early_data); 3691 if(result) 3692 return result; 3693 } 3694 if(do_early_data) { 3695 /* We only try the ALPN protocol the session used before, 3696 * otherwise we might send early data for the wrong protocol */ 3697 Curl_alpn_restrict_to(&alpns, scs->alpn); 3698 } 3699 } 3700 #else 3701 (void)sess_reuse_cb; 3702 #endif 3703 } 3704 SSL_SESSION_free(ssl_session); 3705 } 3706 else { 3707 infof(data, "SSL session not accepted by OpenSSL, continuing without"); 3708 } 3709 } 3710 Curl_ssl_scache_return(cf, data, peer->scache_key, scs); 3711 } 3712 3713 #ifdef HAS_ALPN_OPENSSL 3714 if(alpns.count) { 3715 struct alpn_proto_buf proto; 3716 memset(&proto, 0, sizeof(proto)); 3717 result = Curl_alpn_to_proto_buf(&proto, &alpns); 3718 if(result) { 3719 failf(data, "Error determining ALPN"); 3720 return CURLE_SSL_CONNECT_ERROR; 3721 } 3722 if(SSL_set_alpn_protos(octx->ssl, proto.data, (int)proto.len)) { 3723 failf(data, "Error setting ALPN"); 3724 return CURLE_SSL_CONNECT_ERROR; 3725 } 3726 } 3727 #endif 3728 3729 return CURLE_OK; 3730 } 3731 3732 #ifdef USE_ECH_OPENSSL 3733 static CURLcode ossl_init_ech(struct ossl_ctx *octx, 3734 struct Curl_cfilter *cf, 3735 struct Curl_easy *data, 3736 struct ssl_peer *peer) 3737 { 3738 unsigned char *ech_config = NULL; 3739 size_t ech_config_len = 0; 3740 char *outername = data->set.str[STRING_ECH_PUBLIC]; 3741 int trying_ech_now = 0; 3742 CURLcode result; 3743 3744 if(!ECH_ENABLED(data)) 3745 return CURLE_OK; 3746 3747 if(data->set.tls_ech & CURLECH_GREASE) { 3748 infof(data, "ECH: will GREASE ClientHello"); 3749 # if defined(OPENSSL_IS_BORINGSSL) || defined(OPENSSL_IS_AWSLC) 3750 SSL_set_enable_ech_grease(octx->ssl, 1); 3751 # else 3752 SSL_set_options(octx->ssl, SSL_OP_ECH_GREASE); 3753 # endif 3754 } 3755 else if(data->set.tls_ech & CURLECH_CLA_CFG) { 3756 # if defined(OPENSSL_IS_BORINGSSL) || defined(OPENSSL_IS_AWSLC) 3757 /* have to do base64 decode here for BoringSSL */ 3758 const char *b64 = data->set.str[STRING_ECH_CONFIG]; 3759 3760 if(!b64) { 3761 infof(data, "ECH: ECHConfig from command line empty"); 3762 return CURLE_SSL_CONNECT_ERROR; 3763 } 3764 ech_config_len = 2 * strlen(b64); 3765 result = curlx_base64_decode(b64, &ech_config, &ech_config_len); 3766 if(result || !ech_config) { 3767 infof(data, "ECH: cannot base64 decode ECHConfig from command line"); 3768 if(data->set.tls_ech & CURLECH_HARD) 3769 return result; 3770 } 3771 if(SSL_set1_ech_config_list(octx->ssl, ech_config, 3772 ech_config_len) != 1) { 3773 infof(data, "ECH: SSL_ECH_set1_ech_config_list failed"); 3774 if(data->set.tls_ech & CURLECH_HARD) { 3775 free(ech_config); 3776 return CURLE_SSL_CONNECT_ERROR; 3777 } 3778 } 3779 free(ech_config); 3780 trying_ech_now = 1; 3781 # else 3782 ech_config = (unsigned char *) data->set.str[STRING_ECH_CONFIG]; 3783 if(!ech_config) { 3784 infof(data, "ECH: ECHConfig from command line empty"); 3785 return CURLE_SSL_CONNECT_ERROR; 3786 } 3787 ech_config_len = strlen(data->set.str[STRING_ECH_CONFIG]); 3788 if(SSL_set1_ech_config_list(octx->ssl, ech_config, 3789 ech_config_len) != 1) { 3790 infof(data, "ECH: SSL_ECH_set1_ech_config_list failed"); 3791 if(data->set.tls_ech & CURLECH_HARD) 3792 return CURLE_SSL_CONNECT_ERROR; 3793 } 3794 else 3795 trying_ech_now = 1; 3796 # endif 3797 infof(data, "ECH: ECHConfig from command line"); 3798 } 3799 else { 3800 struct Curl_dns_entry *dns = NULL; 3801 3802 if(peer->hostname) 3803 dns = Curl_dnscache_get(data, peer->hostname, peer->port, 3804 cf->conn->ip_version); 3805 if(!dns) { 3806 infof(data, "ECH: requested but no DNS info available"); 3807 if(data->set.tls_ech & CURLECH_HARD) 3808 return CURLE_SSL_CONNECT_ERROR; 3809 } 3810 else { 3811 struct Curl_https_rrinfo *rinfo = NULL; 3812 3813 rinfo = dns->hinfo; 3814 if(rinfo && rinfo->echconfiglist) { 3815 unsigned char *ecl = rinfo->echconfiglist; 3816 size_t elen = rinfo->echconfiglist_len; 3817 3818 infof(data, "ECH: ECHConfig from DoH HTTPS RR"); 3819 if(SSL_set1_ech_config_list(octx->ssl, ecl, elen) != 1) { 3820 infof(data, "ECH: SSL_set1_ech_config_list failed"); 3821 if(data->set.tls_ech & CURLECH_HARD) 3822 return CURLE_SSL_CONNECT_ERROR; 3823 } 3824 else { 3825 trying_ech_now = 1; 3826 infof(data, "ECH: imported ECHConfigList of length %zu", elen); 3827 } 3828 } 3829 else { 3830 infof(data, "ECH: requested but no ECHConfig available"); 3831 if(data->set.tls_ech & CURLECH_HARD) 3832 return CURLE_SSL_CONNECT_ERROR; 3833 } 3834 Curl_resolv_unlink(data, &dns); 3835 } 3836 } 3837 # if defined(OPENSSL_IS_BORINGSSL) || defined(OPENSSL_IS_AWSLC) 3838 if(trying_ech_now && outername) { 3839 infof(data, "ECH: setting public_name not supported with BoringSSL"); 3840 return CURLE_SSL_CONNECT_ERROR; 3841 } 3842 # else 3843 if(trying_ech_now && outername) { 3844 infof(data, "ECH: inner: '%s', outer: '%s'", 3845 peer->hostname ? peer->hostname : "NULL", outername); 3846 result = SSL_ech_set1_server_names(octx->ssl, 3847 peer->hostname, outername, 3848 0 /* do send outer */); 3849 if(result != 1) { 3850 infof(data, "ECH: rv failed to set server name(s) %d [ERROR]", result); 3851 return CURLE_SSL_CONNECT_ERROR; 3852 } 3853 } 3854 # endif /* OPENSSL_IS_BORINGSSL || OPENSSL_IS_AWSLC */ 3855 if(trying_ech_now 3856 && SSL_set_min_proto_version(octx->ssl, TLS1_3_VERSION) != 1) { 3857 infof(data, "ECH: cannot force TLSv1.3 [ERROR]"); 3858 return CURLE_SSL_CONNECT_ERROR; 3859 } 3860 3861 return CURLE_OK; 3862 } 3863 #endif /* USE_ECH_OPENSSL */ 3864 3865 3866 static CURLcode ossl_init_ssl(struct ossl_ctx *octx, 3867 struct Curl_cfilter *cf, 3868 struct Curl_easy *data, 3869 struct ssl_peer *peer, 3870 const struct alpn_spec *alpns_requested, 3871 void *ssl_user_data, 3872 Curl_ossl_init_session_reuse_cb *sess_reuse_cb) 3873 { 3874 /* Let's make an SSL structure */ 3875 if(octx->ssl) 3876 SSL_free(octx->ssl); 3877 octx->ssl = SSL_new(octx->ssl_ctx); 3878 if(!octx->ssl) { 3879 failf(data, "SSL: could not create a context (handle)"); 3880 return CURLE_OUT_OF_MEMORY; 3881 } 3882 3883 SSL_set_app_data(octx->ssl, ssl_user_data); 3884 3885 #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_OCSP) 3886 if(Curl_ssl_cf_get_primary_config(cf)->verifystatus) 3887 SSL_set_tlsext_status_type(octx->ssl, TLSEXT_STATUSTYPE_ocsp); 3888 #endif 3889 3890 #if (defined(OPENSSL_IS_BORINGSSL) || defined(OPENSSL_IS_AWSLC)) && \ 3891 defined(ALLOW_RENEG) 3892 SSL_set_renegotiate_mode(octx->ssl, ssl_renegotiate_freely); 3893 #endif 3894 3895 SSL_set_connect_state(octx->ssl); 3896 3897 octx->server_cert = NULL; 3898 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME 3899 if(peer->sni) { 3900 if(!SSL_set_tlsext_host_name(octx->ssl, peer->sni)) { 3901 failf(data, "Failed set SNI"); 3902 return CURLE_SSL_CONNECT_ERROR; 3903 } 3904 } 3905 3906 #ifdef USE_ECH_OPENSSL 3907 { 3908 CURLcode result = ossl_init_ech(octx, cf, data, peer); 3909 if(result) 3910 return result; 3911 } 3912 #endif /* USE_ECH_OPENSSL */ 3913 3914 #endif 3915 3916 return ossl_init_session_and_alpns(octx, cf, data, peer, 3917 alpns_requested, sess_reuse_cb); 3918 } 3919 3920 3921 static CURLcode ossl_init_method(struct Curl_cfilter *cf, 3922 struct Curl_easy *data, 3923 struct ssl_peer *peer, 3924 const SSL_METHOD **pmethod, 3925 unsigned int *pssl_version_min) 3926 { 3927 struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); 3928 3929 *pmethod = NULL; 3930 *pssl_version_min = conn_config->version; 3931 switch(peer->transport) { 3932 case TRNSPRT_TCP: 3933 /* check to see if we have been told to use an explicit SSL/TLS version */ 3934 switch(*pssl_version_min) { 3935 case CURL_SSLVERSION_DEFAULT: 3936 case CURL_SSLVERSION_TLSv1: 3937 case CURL_SSLVERSION_TLSv1_0: 3938 case CURL_SSLVERSION_TLSv1_1: 3939 case CURL_SSLVERSION_TLSv1_2: 3940 case CURL_SSLVERSION_TLSv1_3: 3941 /* it will be handled later with the context options */ 3942 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) 3943 *pmethod = TLS_client_method(); 3944 #else 3945 *pmethod = SSLv23_client_method(); 3946 #endif 3947 break; 3948 case CURL_SSLVERSION_SSLv2: 3949 failf(data, "No SSLv2 support"); 3950 return CURLE_NOT_BUILT_IN; 3951 case CURL_SSLVERSION_SSLv3: 3952 failf(data, "No SSLv3 support"); 3953 return CURLE_NOT_BUILT_IN; 3954 default: 3955 failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION"); 3956 return CURLE_SSL_CONNECT_ERROR; 3957 } 3958 break; 3959 case TRNSPRT_QUIC: 3960 *pssl_version_min = CURL_SSLVERSION_TLSv1_3; 3961 if(conn_config->version_max && 3962 (conn_config->version_max != CURL_SSLVERSION_MAX_TLSv1_3)) { 3963 failf(data, "QUIC needs at least TLS version 1.3"); 3964 return CURLE_SSL_CONNECT_ERROR; 3965 } 3966 3967 #ifdef USE_OPENSSL_QUIC 3968 *pmethod = OSSL_QUIC_client_method(); 3969 #elif (OPENSSL_VERSION_NUMBER >= 0x10100000L) 3970 *pmethod = TLS_method(); 3971 #else 3972 *pmethod = SSLv23_client_method(); 3973 #endif 3974 break; 3975 default: 3976 failf(data, "unsupported transport %d in SSL init", peer->transport); 3977 return CURLE_SSL_CONNECT_ERROR; 3978 } 3979 3980 return *pmethod ? CURLE_OK : CURLE_SSL_CONNECT_ERROR; 3981 } 3982 3983 3984 CURLcode Curl_ossl_ctx_init(struct ossl_ctx *octx, 3985 struct Curl_cfilter *cf, 3986 struct Curl_easy *data, 3987 struct ssl_peer *peer, 3988 const struct alpn_spec *alpns_requested, 3989 Curl_ossl_ctx_setup_cb *cb_setup, 3990 void *cb_user_data, 3991 Curl_ossl_new_session_cb *cb_new_session, 3992 void *ssl_user_data, 3993 Curl_ossl_init_session_reuse_cb *sess_reuse_cb) 3994 { 3995 CURLcode result = CURLE_OK; 3996 const char *ciphers; 3997 const SSL_METHOD *req_method = NULL; 3998 ctx_option_t ctx_options = 0; 3999 struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); 4000 struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); 4001 char * const ssl_cert = ssl_config->primary.clientcert; 4002 const struct curl_blob *ssl_cert_blob = ssl_config->primary.cert_blob; 4003 const char * const ssl_cert_type = ssl_config->cert_type; 4004 const bool verifypeer = conn_config->verifypeer; 4005 unsigned int ssl_version_min; 4006 char error_buffer[256]; 4007 4008 /* Make funny stuff to get random input */ 4009 result = ossl_seed(data); 4010 if(result) 4011 return result; 4012 4013 ssl_config->certverifyresult = !X509_V_OK; 4014 4015 result = ossl_init_method(cf, data, peer, &req_method, &ssl_version_min); 4016 if(result) 4017 return result; 4018 DEBUGASSERT(req_method); 4019 4020 DEBUGASSERT(!octx->ssl_ctx); 4021 octx->ssl_ctx = 4022 #ifdef OPENSSL_HAS_PROVIDERS 4023 data->state.libctx ? 4024 SSL_CTX_new_ex(data->state.libctx, data->state.propq, req_method): 4025 #endif 4026 SSL_CTX_new(req_method); 4027 4028 if(!octx->ssl_ctx) { 4029 failf(data, "SSL: could not create a context: %s", 4030 ossl_strerror(ERR_peek_error(), error_buffer, sizeof(error_buffer))); 4031 return CURLE_OUT_OF_MEMORY; 4032 } 4033 4034 if(cb_setup) { 4035 result = cb_setup(cf, data, cb_user_data); 4036 if(result) 4037 return result; 4038 } 4039 4040 #ifdef SSL_CTRL_SET_MSG_CALLBACK 4041 if(data->set.fdebug && data->set.verbose) { 4042 /* the SSL trace callback is only used for verbose logging */ 4043 SSL_CTX_set_msg_callback(octx->ssl_ctx, ossl_trace); 4044 SSL_CTX_set_msg_callback_arg(octx->ssl_ctx, cf); 4045 } 4046 #endif 4047 4048 /* OpenSSL contains code to work around lots of bugs and flaws in various 4049 SSL-implementations. SSL_CTX_set_options() is used to enabled those 4050 work-arounds. The manpage for this option states that SSL_OP_ALL enables 4051 all the work-arounds and that "It is usually safe to use SSL_OP_ALL to 4052 enable the bug workaround options if compatibility with somewhat broken 4053 implementations is desired." 4054 4055 The "-no_ticket" option was introduced in OpenSSL 0.9.8j. it is a flag to 4056 disable "rfc4507bis session ticket support". rfc4507bis was later turned 4057 into the proper RFC5077: https://datatracker.ietf.org/doc/html/rfc5077 4058 4059 The enabled extension concerns the session management. I wonder how often 4060 libcurl stops a connection and then resumes a TLS session. Also, sending 4061 the session data is some overhead. I suggest that you just use your 4062 proposed patch (which explicitly disables TICKET). 4063 4064 If someone writes an application with libcurl and OpenSSL who wants to 4065 enable the feature, one can do this in the SSL callback. 4066 4067 SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG option enabling allowed proper 4068 interoperability with web server Netscape Enterprise Server 2.0.1 which 4069 was released back in 1996. 4070 4071 Due to CVE-2010-4180, option SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG has 4072 become ineffective as of OpenSSL 0.9.8q and 1.0.0c. In order to mitigate 4073 CVE-2010-4180 when using previous OpenSSL versions we no longer enable 4074 this option regardless of OpenSSL version and SSL_OP_ALL definition. 4075 4076 OpenSSL added a work-around for an SSL 3.0/TLS 1.0 CBC vulnerability: 4077 https://web.archive.org/web/20240114184648/openssl.org/~bodo/tls-cbc.txt. 4078 In 0.9.6e they added a bit to SSL_OP_ALL that _disables_ that work-around 4079 despite the fact that SSL_OP_ALL is documented to do "rather harmless" 4080 workarounds. In order to keep the secure work-around, the 4081 SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS bit must not be set. 4082 */ 4083 4084 ctx_options = SSL_OP_ALL; 4085 4086 #ifdef SSL_OP_NO_TICKET 4087 ctx_options |= SSL_OP_NO_TICKET; 4088 #endif 4089 4090 #ifdef SSL_OP_NO_COMPRESSION 4091 ctx_options |= SSL_OP_NO_COMPRESSION; 4092 #endif 4093 4094 #ifdef SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG 4095 /* mitigate CVE-2010-4180 */ 4096 ctx_options &= ~(ctx_option_t)SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG; 4097 #endif 4098 4099 #ifdef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS 4100 /* unless the user explicitly asks to allow the protocol vulnerability we 4101 use the work-around */ 4102 if(!ssl_config->enable_beast) 4103 ctx_options &= ~(ctx_option_t)SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS; 4104 #endif 4105 4106 switch(ssl_version_min) { 4107 case CURL_SSLVERSION_SSLv2: 4108 case CURL_SSLVERSION_SSLv3: 4109 return CURLE_NOT_BUILT_IN; 4110 4111 /* "--tlsv<x.y>" options mean TLS >= version <x.y> */ 4112 case CURL_SSLVERSION_DEFAULT: 4113 case CURL_SSLVERSION_TLSv1: /* TLS >= version 1.0 */ 4114 case CURL_SSLVERSION_TLSv1_0: /* TLS >= version 1.0 */ 4115 case CURL_SSLVERSION_TLSv1_1: /* TLS >= version 1.1 */ 4116 case CURL_SSLVERSION_TLSv1_2: /* TLS >= version 1.2 */ 4117 case CURL_SSLVERSION_TLSv1_3: /* TLS >= version 1.3 */ 4118 /* asking for any TLS version as the minimum, means no SSL versions 4119 allowed */ 4120 ctx_options |= SSL_OP_NO_SSLv2; 4121 ctx_options |= SSL_OP_NO_SSLv3; 4122 4123 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) /* 1.1.0 */ 4124 result = ossl_set_ssl_version_min_max(cf, octx->ssl_ctx); 4125 #else 4126 result = ossl_set_ssl_version_min_max_legacy(&ctx_options, cf, data); 4127 #endif 4128 if(result != CURLE_OK) 4129 return result; 4130 break; 4131 4132 default: 4133 failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION"); 4134 return CURLE_SSL_CONNECT_ERROR; 4135 } 4136 4137 SSL_CTX_set_options(octx->ssl_ctx, ctx_options); 4138 SSL_CTX_set_read_ahead(octx->ssl_ctx, 1); 4139 4140 /* Max TLS1.2 record size 0x4000 + 0x800. 4141 OpenSSL supports processing "jumbo TLS record" (8 TLS records) in one go 4142 for some algorithms, so match that here. 4143 Experimentation shows that a slightly larger buffer is needed 4144 to avoid short reads. 4145 4146 However using a large buffer (8 packets) actually decreases performance. 4147 4 packets is better. 4148 */ 4149 4150 #ifdef HAVE_SSL_CTX_SET_DEFAULT_READ_BUFFER_LEN 4151 SSL_CTX_set_default_read_buffer_len(octx->ssl_ctx, 0x401e * 4); 4152 #endif 4153 4154 #ifdef SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER 4155 /* We do retry writes sometimes from another buffer address */ 4156 SSL_CTX_set_mode(octx->ssl_ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); 4157 #endif 4158 4159 ciphers = conn_config->cipher_list; 4160 if(!ciphers && (peer->transport != TRNSPRT_QUIC)) 4161 ciphers = DEFAULT_CIPHER_SELECTION; 4162 if(ciphers && (ssl_version_min < CURL_SSLVERSION_TLSv1_3)) { 4163 if(!SSL_CTX_set_cipher_list(octx->ssl_ctx, ciphers)) { 4164 failf(data, "failed setting cipher list: %s", ciphers); 4165 return CURLE_SSL_CIPHER; 4166 } 4167 infof(data, "Cipher selection: %s", ciphers); 4168 } 4169 4170 #ifdef HAVE_SSL_CTX_SET_CIPHERSUITES 4171 { 4172 const char *ciphers13 = conn_config->cipher_list13; 4173 if(ciphers13 && 4174 (!conn_config->version_max || 4175 (conn_config->version_max >= CURL_SSLVERSION_MAX_TLSv1_3))) { 4176 if(!SSL_CTX_set_ciphersuites(octx->ssl_ctx, ciphers13)) { 4177 failf(data, "failed setting TLS 1.3 cipher suite: %s", ciphers13); 4178 return CURLE_SSL_CIPHER; 4179 } 4180 infof(data, "TLS 1.3 cipher selection: %s", ciphers13); 4181 } 4182 } 4183 #endif 4184 4185 if(ssl_cert || ssl_cert_blob || ssl_cert_type) { 4186 if(!result && 4187 !cert_stuff(data, octx->ssl_ctx, 4188 ssl_cert, ssl_cert_blob, ssl_cert_type, 4189 ssl_config->key, ssl_config->key_blob, 4190 ssl_config->key_type, ssl_config->key_passwd)) 4191 result = CURLE_SSL_CERTPROBLEM; 4192 if(result) 4193 /* failf() is already done in cert_stuff() */ 4194 return result; 4195 } 4196 4197 #ifdef HAVE_SSL_CTX_SET_POST_HANDSHAKE_AUTH 4198 /* OpenSSL 1.1.1 requires clients to opt-in for PHA */ 4199 SSL_CTX_set_post_handshake_auth(octx->ssl_ctx, 1); 4200 #endif 4201 4202 { 4203 const char *curves = conn_config->curves; 4204 if(curves) { 4205 #if defined(OPENSSL_IS_BORINGSSL) || defined(OPENSSL_IS_AWSLC) 4206 #define OSSL_CURVE_CAST(x) (x) 4207 #else 4208 #define OSSL_CURVE_CAST(x) (char *)CURL_UNCONST(x) 4209 #endif 4210 if(!SSL_CTX_set1_curves_list(octx->ssl_ctx, OSSL_CURVE_CAST(curves))) { 4211 failf(data, "failed setting curves list: '%s'", curves); 4212 return CURLE_SSL_CIPHER; 4213 } 4214 } 4215 } 4216 4217 #ifdef HAVE_SSL_CTX_SET1_SIGALGS 4218 #define OSSL_SIGALG_CAST(x) OSSL_CURVE_CAST(x) 4219 { 4220 const char *signature_algorithms = conn_config->signature_algorithms; 4221 if(signature_algorithms) { 4222 if(!SSL_CTX_set1_sigalgs_list(octx->ssl_ctx, 4223 OSSL_SIGALG_CAST(signature_algorithms))) { 4224 failf(data, "failed setting signature algorithms: '%s'", 4225 signature_algorithms); 4226 return CURLE_SSL_CIPHER; 4227 } 4228 } 4229 } 4230 #endif 4231 4232 #ifdef USE_OPENSSL_SRP 4233 if(ssl_config->primary.username && Curl_auth_allowed_to_host(data)) { 4234 char * const ssl_username = ssl_config->primary.username; 4235 char * const ssl_password = ssl_config->primary.password; 4236 infof(data, "Using TLS-SRP username: %s", ssl_username); 4237 4238 if(!SSL_CTX_set_srp_username(octx->ssl_ctx, ssl_username)) { 4239 failf(data, "Unable to set SRP username"); 4240 return CURLE_BAD_FUNCTION_ARGUMENT; 4241 } 4242 if(!SSL_CTX_set_srp_password(octx->ssl_ctx, ssl_password)) { 4243 failf(data, "failed setting SRP password"); 4244 return CURLE_BAD_FUNCTION_ARGUMENT; 4245 } 4246 if(!conn_config->cipher_list) { 4247 infof(data, "Setting cipher list SRP"); 4248 4249 if(!SSL_CTX_set_cipher_list(octx->ssl_ctx, "SRP")) { 4250 failf(data, "failed setting SRP cipher list"); 4251 return CURLE_SSL_CIPHER; 4252 } 4253 } 4254 } 4255 #endif 4256 4257 /* OpenSSL always tries to verify the peer, this only says whether it should 4258 * fail to connect if the verification fails, or if it should continue 4259 * anyway. In the latter case the result of the verification is checked with 4260 * SSL_get_verify_result() below. */ 4261 SSL_CTX_set_verify(octx->ssl_ctx, 4262 verifypeer ? SSL_VERIFY_PEER : SSL_VERIFY_NONE, NULL); 4263 4264 /* Enable logging of secrets to the file specified in env SSLKEYLOGFILE. */ 4265 #ifdef HAVE_KEYLOG_CALLBACK 4266 if(Curl_tls_keylog_enabled()) { 4267 SSL_CTX_set_keylog_callback(octx->ssl_ctx, ossl_keylog_callback); 4268 } 4269 #endif 4270 4271 if(cb_new_session) { 4272 /* Enable the session cache because it is a prerequisite for the 4273 * "new session" callback. Use the "external storage" mode to prevent 4274 * OpenSSL from creating an internal session cache. 4275 */ 4276 SSL_CTX_set_session_cache_mode(octx->ssl_ctx, 4277 SSL_SESS_CACHE_CLIENT | 4278 SSL_SESS_CACHE_NO_INTERNAL); 4279 SSL_CTX_sess_set_new_cb(octx->ssl_ctx, cb_new_session); 4280 } 4281 4282 /* give application a chance to interfere with SSL set up. */ 4283 if(data->set.ssl.fsslctx) { 4284 /* When a user callback is installed to modify the SSL_CTX, 4285 * we need to do the full initialization before calling it. 4286 * See: #11800 */ 4287 if(!octx->x509_store_setup) { 4288 result = Curl_ssl_setup_x509_store(cf, data, octx->ssl_ctx); 4289 if(result) 4290 return result; 4291 octx->x509_store_setup = TRUE; 4292 } 4293 Curl_set_in_callback(data, TRUE); 4294 result = (*data->set.ssl.fsslctx)(data, octx->ssl_ctx, 4295 data->set.ssl.fsslctxp); 4296 Curl_set_in_callback(data, FALSE); 4297 if(result) { 4298 failf(data, "error signaled by ssl ctx callback"); 4299 return result; 4300 } 4301 } 4302 4303 return ossl_init_ssl(octx, cf, data, peer, alpns_requested, 4304 ssl_user_data, sess_reuse_cb); 4305 } 4306 4307 static CURLcode ossl_on_session_reuse(struct Curl_cfilter *cf, 4308 struct Curl_easy *data, 4309 struct alpn_spec *alpns, 4310 struct Curl_ssl_session *scs, 4311 bool *do_early_data) 4312 { 4313 struct ssl_connect_data *connssl = cf->ctx; 4314 CURLcode result = CURLE_OK; 4315 4316 *do_early_data = FALSE; 4317 connssl->earlydata_max = scs->earlydata_max; 4318 if(!connssl->earlydata_max) { 4319 CURL_TRC_CF(data, cf, "SSL session does not allow earlydata"); 4320 } 4321 else if(!Curl_alpn_contains_proto(alpns, scs->alpn)) { 4322 CURL_TRC_CF(data, cf, "SSL session has different ALPN, no early data"); 4323 } 4324 else { 4325 infof(data, "SSL session allows %zu bytes of early data, " 4326 "reusing ALPN '%s'", connssl->earlydata_max, scs->alpn); 4327 connssl->earlydata_state = ssl_earlydata_await; 4328 connssl->state = ssl_connection_deferred; 4329 result = Curl_alpn_set_negotiated(cf, data, connssl, 4330 (const unsigned char *)scs->alpn, 4331 scs->alpn ? strlen(scs->alpn) : 0); 4332 *do_early_data = !result; 4333 } 4334 return result; 4335 } 4336 4337 void Curl_ossl_report_handshake(struct Curl_easy *data, 4338 struct ossl_ctx *octx) 4339 { 4340 #ifndef CURL_DISABLE_VERBOSE_STRINGS 4341 if(Curl_trc_is_verbose(data)) { 4342 int psigtype_nid = NID_undef; 4343 const char *negotiated_group_name = NULL; 4344 4345 #if (OPENSSL_VERSION_NUMBER >= 0x30000000L) 4346 SSL_get_peer_signature_type_nid(octx->ssl, &psigtype_nid); 4347 #if (OPENSSL_VERSION_NUMBER >= 0x30200000L) 4348 negotiated_group_name = SSL_get0_group_name(octx->ssl); 4349 #else 4350 negotiated_group_name = 4351 OBJ_nid2sn(SSL_get_negotiated_group(octx->ssl) & 0x0000FFFF); 4352 #endif 4353 #endif 4354 4355 /* Informational message */ 4356 infof(data, "SSL connection using %s / %s / %s / %s", 4357 SSL_get_version(octx->ssl), 4358 SSL_get_cipher(octx->ssl), 4359 negotiated_group_name ? negotiated_group_name : "[blank]", 4360 OBJ_nid2sn(psigtype_nid)); 4361 } 4362 #else 4363 (void)data; 4364 (void)octx; 4365 #endif /* CURL_DISABLE_VERBOSE_STRINGS */ 4366 4367 } 4368 4369 static CURLcode ossl_connect_step1(struct Curl_cfilter *cf, 4370 struct Curl_easy *data) 4371 { 4372 struct ssl_connect_data *connssl = cf->ctx; 4373 struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend; 4374 BIO *bio; 4375 CURLcode result; 4376 4377 DEBUGASSERT(ssl_connect_1 == connssl->connecting_state); 4378 DEBUGASSERT(octx); 4379 4380 result = Curl_ossl_ctx_init(octx, cf, data, &connssl->peer, 4381 connssl->alpn, NULL, NULL, 4382 ossl_new_session_cb, cf, 4383 ossl_on_session_reuse); 4384 if(result) 4385 return result; 4386 4387 octx->bio_method = ossl_bio_cf_method_create(); 4388 if(!octx->bio_method) 4389 return CURLE_OUT_OF_MEMORY; 4390 bio = BIO_new(octx->bio_method); 4391 if(!bio) 4392 return CURLE_OUT_OF_MEMORY; 4393 4394 BIO_set_data(bio, cf); 4395 #ifdef HAVE_SSL_SET0_WBIO 4396 /* with OpenSSL v1.1.1 we get an alternative to SSL_set_bio() that works 4397 * without backward compat quirks. Every call takes one reference, so we 4398 * up it and pass. SSL* then owns it and will free. 4399 * We check on the function in configure, since LibreSSL and friends 4400 * each have their own versions to add support for this. */ 4401 BIO_up_ref(bio); 4402 SSL_set0_rbio(octx->ssl, bio); 4403 SSL_set0_wbio(octx->ssl, bio); 4404 #else 4405 SSL_set_bio(octx->ssl, bio, bio); 4406 #endif 4407 4408 #ifdef HAS_ALPN_OPENSSL 4409 if(connssl->alpn && (connssl->state != ssl_connection_deferred)) { 4410 struct alpn_proto_buf proto; 4411 memset(&proto, 0, sizeof(proto)); 4412 Curl_alpn_to_proto_str(&proto, connssl->alpn); 4413 infof(data, VTLS_INFOF_ALPN_OFFER_1STR, proto.data); 4414 } 4415 #endif 4416 connssl->connecting_state = ssl_connect_2; 4417 return CURLE_OK; 4418 } 4419 4420 #ifdef USE_ECH_OPENSSL 4421 /* If we have retry configs, then trace those out */ 4422 static void ossl_trace_ech_retry_configs(struct Curl_easy *data, SSL* ssl, 4423 int reason) 4424 { 4425 CURLcode result = CURLE_OK; 4426 size_t rcl = 0; 4427 int rv = 1; 4428 # if !defined(OPENSSL_IS_BORINGSSL) && !defined(OPENSSL_IS_AWSLC) 4429 char *inner = NULL; 4430 unsigned char *rcs = NULL; 4431 char *outer = NULL; 4432 # else 4433 const char *inner = NULL; 4434 const uint8_t *rcs = NULL; 4435 const char *outer = NULL; 4436 size_t out_name_len = 0; 4437 int servername_type = 0; 4438 # endif 4439 4440 /* nothing to trace if not doing ECH */ 4441 if(!ECH_ENABLED(data)) 4442 return; 4443 # if !defined(OPENSSL_IS_BORINGSSL) && !defined(OPENSSL_IS_AWSLC) 4444 rv = SSL_ech_get1_retry_config(ssl, &rcs, &rcl); 4445 # else 4446 SSL_get0_ech_retry_configs(ssl, &rcs, &rcl); 4447 rv = (int)rcl; 4448 # endif 4449 4450 if(rv && rcs) { 4451 char *b64str = NULL; 4452 size_t blen = 0; 4453 4454 result = curlx_base64_encode((const char *)rcs, rcl, &b64str, &blen); 4455 if(!result && b64str) { 4456 infof(data, "ECH: retry_configs %s", b64str); 4457 free(b64str); 4458 #if !defined(OPENSSL_IS_BORINGSSL) && !defined(OPENSSL_IS_AWSLC) 4459 rv = SSL_ech_get1_status(ssl, &inner, &outer); 4460 infof(data, "ECH: retry_configs for %s from %s, %d %d", 4461 inner ? inner : "NULL", outer ? outer : "NULL", reason, rv); 4462 #else 4463 rv = SSL_ech_accepted(ssl); 4464 servername_type = SSL_get_servername_type(ssl); 4465 inner = SSL_get_servername(ssl, servername_type); 4466 SSL_get0_ech_name_override(ssl, &outer, &out_name_len); 4467 infof(data, "ECH: retry_configs for %s from %s, %d %d", 4468 inner ? inner : "NULL", outer ? outer : "NULL", reason, rv); 4469 #endif 4470 } 4471 } 4472 else 4473 infof(data, "ECH: no retry_configs (rv = %d)", rv); 4474 # if !defined(OPENSSL_IS_BORINGSSL) && !defined(OPENSSL_IS_AWSLC) 4475 OPENSSL_free((void *)rcs); 4476 # endif 4477 return; 4478 } 4479 4480 #endif 4481 4482 static CURLcode ossl_connect_step2(struct Curl_cfilter *cf, 4483 struct Curl_easy *data) 4484 { 4485 int err; 4486 struct ssl_connect_data *connssl = cf->ctx; 4487 struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend; 4488 struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); 4489 DEBUGASSERT(ssl_connect_2 == connssl->connecting_state); 4490 DEBUGASSERT(octx); 4491 4492 connssl->io_need = CURL_SSL_IO_NEED_NONE; 4493 ERR_clear_error(); 4494 4495 err = SSL_connect(octx->ssl); 4496 4497 if(!octx->x509_store_setup) { 4498 /* After having send off the ClientHello, we prepare the x509 4499 * store to verify the coming certificate from the server */ 4500 CURLcode result = Curl_ssl_setup_x509_store(cf, data, octx->ssl_ctx); 4501 if(result) 4502 return result; 4503 octx->x509_store_setup = TRUE; 4504 } 4505 4506 #ifndef HAVE_KEYLOG_CALLBACK 4507 /* If key logging is enabled, wait for the handshake to complete and then 4508 * proceed with logging secrets (for TLS 1.2 or older). 4509 */ 4510 if(Curl_tls_keylog_enabled() && !octx->keylog_done) 4511 ossl_log_tls12_secret(octx->ssl, &octx->keylog_done); 4512 #endif 4513 4514 /* 1 is fine 4515 0 is "not successful but was shut down controlled" 4516 <0 is "handshake was not successful, because a fatal error occurred" */ 4517 if(1 != err) { 4518 int detail = SSL_get_error(octx->ssl, err); 4519 CURL_TRC_CF(data, cf, "SSL_connect() -> err=%d, detail=%d", err, detail); 4520 4521 if(SSL_ERROR_WANT_READ == detail) { 4522 CURL_TRC_CF(data, cf, "SSL_connect() -> want recv"); 4523 connssl->io_need = CURL_SSL_IO_NEED_RECV; 4524 return CURLE_AGAIN; 4525 } 4526 if(SSL_ERROR_WANT_WRITE == detail) { 4527 CURL_TRC_CF(data, cf, "SSL_connect() -> want send"); 4528 connssl->io_need = CURL_SSL_IO_NEED_SEND; 4529 return CURLE_AGAIN; 4530 } 4531 #ifdef SSL_ERROR_WANT_ASYNC 4532 if(SSL_ERROR_WANT_ASYNC == detail) { 4533 CURL_TRC_CF(data, cf, "SSL_connect() -> want async"); 4534 connssl->io_need = CURL_SSL_IO_NEED_RECV; 4535 return CURLE_AGAIN; 4536 } 4537 #endif 4538 #ifdef SSL_ERROR_WANT_RETRY_VERIFY 4539 if(SSL_ERROR_WANT_RETRY_VERIFY == detail) { 4540 CURL_TRC_CF(data, cf, "SSL_connect() -> want retry_verify"); 4541 connssl->io_need = CURL_SSL_IO_NEED_RECV; 4542 return CURLE_AGAIN; 4543 } 4544 #endif 4545 else { 4546 /* untreated error */ 4547 sslerr_t errdetail; 4548 char error_buffer[256]=""; 4549 CURLcode result; 4550 long lerr; 4551 int lib; 4552 int reason; 4553 4554 /* the connection failed, we are not waiting for anything else. */ 4555 connssl->connecting_state = ssl_connect_2; 4556 4557 /* Get the earliest error code from the thread's error queue and remove 4558 the entry. */ 4559 errdetail = ERR_get_error(); 4560 4561 /* Extract which lib and reason */ 4562 lib = ERR_GET_LIB(errdetail); 4563 reason = ERR_GET_REASON(errdetail); 4564 4565 if((lib == ERR_LIB_SSL) && 4566 ((reason == SSL_R_CERTIFICATE_VERIFY_FAILED) || 4567 (reason == SSL_R_SSLV3_ALERT_CERTIFICATE_EXPIRED))) { 4568 result = CURLE_PEER_FAILED_VERIFICATION; 4569 4570 lerr = SSL_get_verify_result(octx->ssl); 4571 if(lerr != X509_V_OK) { 4572 ssl_config->certverifyresult = lerr; 4573 failf(data, "SSL certificate problem: %s", 4574 X509_verify_cert_error_string(lerr)); 4575 } 4576 else 4577 failf(data, "%s", "SSL certificate verification failed"); 4578 } 4579 #ifdef SSL_R_TLSV13_ALERT_CERTIFICATE_REQUIRED 4580 /* SSL_R_TLSV13_ALERT_CERTIFICATE_REQUIRED is only available on 4581 OpenSSL version above v1.1.1, not LibreSSL, BoringSSL, or AWS-LC */ 4582 else if((lib == ERR_LIB_SSL) && 4583 (reason == SSL_R_TLSV13_ALERT_CERTIFICATE_REQUIRED)) { 4584 /* If client certificate is required, communicate the 4585 error to client */ 4586 result = CURLE_SSL_CLIENTCERT; 4587 failf(data, "TLS cert problem: %s", 4588 ossl_strerror(errdetail, error_buffer, sizeof(error_buffer))); 4589 } 4590 #endif 4591 #ifdef USE_ECH_OPENSSL 4592 else if((lib == ERR_LIB_SSL) && 4593 # if !defined(OPENSSL_IS_BORINGSSL) && !defined(OPENSSL_IS_AWSLC) 4594 (reason == SSL_R_ECH_REQUIRED)) { 4595 # else 4596 (reason == SSL_R_ECH_REJECTED)) { 4597 # endif 4598 4599 /* trace retry_configs if we got some */ 4600 ossl_trace_ech_retry_configs(data, octx->ssl, reason); 4601 4602 result = CURLE_ECH_REQUIRED; 4603 failf(data, "ECH required: %s", 4604 ossl_strerror(errdetail, error_buffer, sizeof(error_buffer))); 4605 } 4606 #endif 4607 else { 4608 result = CURLE_SSL_CONNECT_ERROR; 4609 failf(data, "TLS connect error: %s", 4610 ossl_strerror(errdetail, error_buffer, sizeof(error_buffer))); 4611 } 4612 4613 /* detail is already set to the SSL error above */ 4614 4615 /* If we e.g. use SSLv2 request-method and the server does not like us 4616 * (RST connection, etc.), OpenSSL gives no explanation whatsoever and 4617 * the SO_ERROR is also lost. 4618 */ 4619 if(CURLE_SSL_CONNECT_ERROR == result && errdetail == 0) { 4620 char extramsg[80]=""; 4621 int sockerr = SOCKERRNO; 4622 4623 if(sockerr && detail == SSL_ERROR_SYSCALL) 4624 Curl_strerror(sockerr, extramsg, sizeof(extramsg)); 4625 failf(data, OSSL_PACKAGE " SSL_connect: %s in connection to %s:%d ", 4626 extramsg[0] ? extramsg : SSL_ERROR_to_str(detail), 4627 connssl->peer.hostname, connssl->peer.port); 4628 } 4629 4630 return result; 4631 } 4632 } 4633 else { 4634 /* we connected fine, we are not waiting for anything else. */ 4635 connssl->connecting_state = ssl_connect_3; 4636 Curl_ossl_report_handshake(data, octx); 4637 4638 #ifdef USE_ECH_OPENSSL 4639 # if !defined(OPENSSL_IS_BORINGSSL) && !defined(OPENSSL_IS_AWSLC) 4640 if(ECH_ENABLED(data)) { 4641 char *inner = NULL, *outer = NULL; 4642 const char *status = NULL; 4643 int rv; 4644 4645 rv = SSL_ech_get1_status(octx->ssl, &inner, &outer); 4646 switch(rv) { 4647 case SSL_ECH_STATUS_SUCCESS: 4648 status = "succeeded"; 4649 break; 4650 case SSL_ECH_STATUS_GREASE_ECH: 4651 status = "sent GREASE, got retry-configs"; 4652 break; 4653 case SSL_ECH_STATUS_GREASE: 4654 status = "sent GREASE"; 4655 break; 4656 case SSL_ECH_STATUS_NOT_TRIED: 4657 status = "not attempted"; 4658 break; 4659 case SSL_ECH_STATUS_NOT_CONFIGURED: 4660 status = "not configured"; 4661 break; 4662 case SSL_ECH_STATUS_BACKEND: 4663 status = "backend (unexpected)"; 4664 break; 4665 case SSL_ECH_STATUS_FAILED: 4666 status = "failed"; 4667 break; 4668 case SSL_ECH_STATUS_BAD_CALL: 4669 status = "bad call (unexpected)"; 4670 break; 4671 case SSL_ECH_STATUS_BAD_NAME: 4672 status = "bad name (unexpected)"; 4673 break; 4674 default: 4675 status = "unexpected status"; 4676 infof(data, "ECH: unexpected status %d",rv); 4677 } 4678 infof(data, "ECH: result: status is %s, inner is %s, outer is %s", 4679 (status ? status : "NULL"), 4680 (inner ? inner : "NULL"), 4681 (outer ? outer : "NULL")); 4682 OPENSSL_free(inner); 4683 OPENSSL_free(outer); 4684 if(rv == SSL_ECH_STATUS_GREASE_ECH) { 4685 /* trace retry_configs if we got some */ 4686 ossl_trace_ech_retry_configs(data, octx->ssl, 0); 4687 } 4688 if(rv != SSL_ECH_STATUS_SUCCESS 4689 && data->set.tls_ech & CURLECH_HARD) { 4690 infof(data, "ECH: ech-hard failed"); 4691 return CURLE_SSL_CONNECT_ERROR; 4692 } 4693 } 4694 else { 4695 infof(data, "ECH: result: status is not attempted"); 4696 } 4697 # endif /* !OPENSSL_IS_BORINGSSL && !OPENSSL_IS_AWSLC */ 4698 #endif /* USE_ECH_OPENSSL */ 4699 4700 #ifdef HAS_ALPN_OPENSSL 4701 /* Sets data and len to negotiated protocol, len is 0 if no protocol was 4702 * negotiated 4703 */ 4704 if(connssl->alpn) { 4705 const unsigned char *neg_protocol; 4706 unsigned int len; 4707 SSL_get0_alpn_selected(octx->ssl, &neg_protocol, &len); 4708 4709 return Curl_alpn_set_negotiated(cf, data, connssl, neg_protocol, len); 4710 } 4711 #endif 4712 4713 return CURLE_OK; 4714 } 4715 } 4716 4717 /* 4718 * Heavily modified from: 4719 * https://www.owasp.org/index.php/Certificate_and_Public_Key_Pinning#OpenSSL 4720 */ 4721 static CURLcode ossl_pkp_pin_peer_pubkey(struct Curl_easy *data, X509* cert, 4722 const char *pinnedpubkey) 4723 { 4724 /* Scratch */ 4725 int len1 = 0, len2 = 0; 4726 unsigned char *buff1 = NULL, *temp = NULL; 4727 4728 /* Result is returned to caller */ 4729 CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH; 4730 4731 /* if a path was not specified, do not pin */ 4732 if(!pinnedpubkey) 4733 return CURLE_OK; 4734 4735 if(!cert) 4736 return result; 4737 4738 do { 4739 /* Begin Gyrations to get the subjectPublicKeyInfo */ 4740 /* Thanks to Viktor Dukhovni on the OpenSSL mailing list */ 4741 4742 /* https://groups.google.com/group/mailing.openssl.users/browse_thread 4743 /thread/d61858dae102c6c7 */ 4744 len1 = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), NULL); 4745 if(len1 < 1) 4746 break; /* failed */ 4747 4748 buff1 = temp = malloc(len1); 4749 if(!buff1) 4750 break; /* failed */ 4751 4752 /* https://docs.openssl.org/master/man3/d2i_X509/ */ 4753 len2 = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), &temp); 4754 4755 /* 4756 * These checks are verifying we got back the same values as when we 4757 * sized the buffer. it is pretty weak since they should always be the 4758 * same. But it gives us something to test. 4759 */ 4760 if((len1 != len2) || !temp || ((temp - buff1) != len1)) 4761 break; /* failed */ 4762 4763 /* End Gyrations */ 4764 4765 /* The one good exit point */ 4766 result = Curl_pin_peer_pubkey(data, pinnedpubkey, buff1, len1); 4767 } while(0); 4768 4769 if(buff1) 4770 free(buff1); 4771 4772 return result; 4773 } 4774 4775 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && \ 4776 !(defined(LIBRESSL_VERSION_NUMBER) && \ 4777 LIBRESSL_VERSION_NUMBER < 0x3060000fL) && \ 4778 !defined(OPENSSL_IS_BORINGSSL) && \ 4779 !defined(OPENSSL_IS_AWSLC) && \ 4780 !defined(CURL_DISABLE_VERBOSE_STRINGS) 4781 static void infof_certstack(struct Curl_easy *data, const SSL *ssl) 4782 { 4783 STACK_OF(X509) *certstack; 4784 long verify_result; 4785 int num_cert_levels; 4786 int cert_level; 4787 4788 verify_result = SSL_get_verify_result(ssl); 4789 if(verify_result != X509_V_OK) 4790 certstack = SSL_get_peer_cert_chain(ssl); 4791 else 4792 certstack = SSL_get0_verified_chain(ssl); 4793 num_cert_levels = sk_X509_num(certstack); 4794 4795 for(cert_level = 0; cert_level < num_cert_levels; cert_level++) { 4796 char cert_algorithm[80] = ""; 4797 char group_name_final[80] = ""; 4798 const X509_ALGOR *palg_cert = NULL; 4799 const ASN1_OBJECT *paobj_cert = NULL; 4800 X509 *current_cert; 4801 EVP_PKEY *current_pkey; 4802 int key_bits; 4803 int key_sec_bits; 4804 int get_group_name; 4805 const char *type_name; 4806 4807 current_cert = sk_X509_value(certstack, cert_level); 4808 4809 X509_get0_signature(NULL, &palg_cert, current_cert); 4810 X509_ALGOR_get0(&paobj_cert, NULL, NULL, palg_cert); 4811 OBJ_obj2txt(cert_algorithm, sizeof(cert_algorithm), paobj_cert, 0); 4812 4813 current_pkey = X509_get0_pubkey(current_cert); 4814 key_bits = EVP_PKEY_bits(current_pkey); 4815 #if (OPENSSL_VERSION_NUMBER < 0x30000000L) 4816 #define EVP_PKEY_get_security_bits EVP_PKEY_security_bits 4817 #endif 4818 key_sec_bits = EVP_PKEY_get_security_bits(current_pkey); 4819 #if (OPENSSL_VERSION_NUMBER >= 0x30000000L) 4820 { 4821 char group_name[80] = ""; 4822 get_group_name = EVP_PKEY_get_group_name(current_pkey, group_name, 4823 sizeof(group_name), NULL); 4824 msnprintf(group_name_final, sizeof(group_name_final), "/%s", group_name); 4825 } 4826 type_name = current_pkey ? EVP_PKEY_get0_type_name(current_pkey) : NULL; 4827 #else 4828 get_group_name = 0; 4829 type_name = NULL; 4830 #endif 4831 4832 infof(data, 4833 " Certificate level %d: " 4834 "Public key type %s%s (%d/%d Bits/secBits), signed using %s", 4835 cert_level, type_name ? type_name : "?", 4836 get_group_name == 0 ? "" : group_name_final, 4837 key_bits, key_sec_bits, cert_algorithm); 4838 } 4839 } 4840 #else 4841 #define infof_certstack(data, ssl) 4842 #endif 4843 4844 #define MAX_CERT_NAME_LENGTH 2048 4845 4846 CURLcode Curl_oss_check_peer_cert(struct Curl_cfilter *cf, 4847 struct Curl_easy *data, 4848 struct ossl_ctx *octx, 4849 struct ssl_peer *peer) 4850 { 4851 struct connectdata *conn = cf->conn; 4852 struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data); 4853 struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf); 4854 CURLcode result = CURLE_OK; 4855 long lerr; 4856 X509 *issuer; 4857 BIO *fp = NULL; 4858 char error_buffer[256]=""; 4859 const char *ptr; 4860 BIO *mem = BIO_new(BIO_s_mem()); 4861 bool strict = (conn_config->verifypeer || conn_config->verifyhost); 4862 struct dynbuf dname; 4863 4864 DEBUGASSERT(octx); 4865 4866 curlx_dyn_init(&dname, MAX_CERT_NAME_LENGTH); 4867 4868 if(!mem) { 4869 failf(data, 4870 "BIO_new return NULL, " OSSL_PACKAGE 4871 " error %s", 4872 ossl_strerror(ERR_get_error(), error_buffer, 4873 sizeof(error_buffer)) ); 4874 return CURLE_OUT_OF_MEMORY; 4875 } 4876 4877 if(data->set.ssl.certinfo) 4878 /* asked to gather certificate info */ 4879 (void)ossl_certchain(data, octx->ssl); 4880 4881 octx->server_cert = SSL_get1_peer_certificate(octx->ssl); 4882 if(!octx->server_cert) { 4883 BIO_free(mem); 4884 if(!strict) 4885 return CURLE_OK; 4886 4887 failf(data, "SSL: could not get peer certificate"); 4888 return CURLE_PEER_FAILED_VERIFICATION; 4889 } 4890 4891 infof(data, "%s certificate:", 4892 Curl_ssl_cf_is_proxy(cf) ? "Proxy" : "Server"); 4893 4894 result = x509_name_oneline(X509_get_subject_name(octx->server_cert), 4895 &dname); 4896 infof(data, " subject: %s", result ? "[NONE]" : curlx_dyn_ptr(&dname)); 4897 4898 #ifndef CURL_DISABLE_VERBOSE_STRINGS 4899 { 4900 char *buf; 4901 long len; 4902 ASN1_TIME_print(mem, X509_get0_notBefore(octx->server_cert)); 4903 len = BIO_get_mem_data(mem, (char **) &buf); 4904 infof(data, " start date: %.*s", (int)len, buf); 4905 (void)BIO_reset(mem); 4906 4907 ASN1_TIME_print(mem, X509_get0_notAfter(octx->server_cert)); 4908 len = BIO_get_mem_data(mem, (char **) &buf); 4909 infof(data, " expire date: %.*s", (int)len, buf); 4910 (void)BIO_reset(mem); 4911 } 4912 #endif 4913 4914 BIO_free(mem); 4915 4916 if(conn_config->verifyhost) { 4917 result = ossl_verifyhost(data, conn, peer, octx->server_cert); 4918 if(result) { 4919 X509_free(octx->server_cert); 4920 octx->server_cert = NULL; 4921 curlx_dyn_free(&dname); 4922 return result; 4923 } 4924 } 4925 4926 result = x509_name_oneline(X509_get_issuer_name(octx->server_cert), 4927 &dname); 4928 if(result) { 4929 if(strict) 4930 failf(data, "SSL: could not get X509-issuer name"); 4931 result = CURLE_PEER_FAILED_VERIFICATION; 4932 } 4933 else { 4934 infof(data, " issuer: %s", curlx_dyn_ptr(&dname)); 4935 curlx_dyn_free(&dname); 4936 4937 /* We could do all sorts of certificate verification stuff here before 4938 deallocating the certificate. */ 4939 4940 /* e.g. match issuer name with provided issuer certificate */ 4941 if(conn_config->issuercert || conn_config->issuercert_blob) { 4942 if(conn_config->issuercert_blob) { 4943 fp = BIO_new_mem_buf(conn_config->issuercert_blob->data, 4944 (int)conn_config->issuercert_blob->len); 4945 if(!fp) { 4946 failf(data, 4947 "BIO_new_mem_buf NULL, " OSSL_PACKAGE 4948 " error %s", 4949 ossl_strerror(ERR_get_error(), error_buffer, 4950 sizeof(error_buffer)) ); 4951 X509_free(octx->server_cert); 4952 octx->server_cert = NULL; 4953 return CURLE_OUT_OF_MEMORY; 4954 } 4955 } 4956 else { 4957 fp = BIO_new(BIO_s_file()); 4958 if(!fp) { 4959 failf(data, 4960 "BIO_new return NULL, " OSSL_PACKAGE 4961 " error %s", 4962 ossl_strerror(ERR_get_error(), error_buffer, 4963 sizeof(error_buffer)) ); 4964 X509_free(octx->server_cert); 4965 octx->server_cert = NULL; 4966 return CURLE_OUT_OF_MEMORY; 4967 } 4968 4969 if(BIO_read_filename(fp, conn_config->issuercert) <= 0) { 4970 if(strict) 4971 failf(data, "SSL: Unable to open issuer cert (%s)", 4972 conn_config->issuercert); 4973 BIO_free(fp); 4974 X509_free(octx->server_cert); 4975 octx->server_cert = NULL; 4976 return CURLE_SSL_ISSUER_ERROR; 4977 } 4978 } 4979 4980 issuer = PEM_read_bio_X509(fp, NULL, ZERO_NULL, NULL); 4981 if(!issuer) { 4982 if(strict) 4983 failf(data, "SSL: Unable to read issuer cert (%s)", 4984 conn_config->issuercert); 4985 BIO_free(fp); 4986 X509_free(issuer); 4987 X509_free(octx->server_cert); 4988 octx->server_cert = NULL; 4989 return CURLE_SSL_ISSUER_ERROR; 4990 } 4991 4992 if(X509_check_issued(issuer, octx->server_cert) != X509_V_OK) { 4993 if(strict) 4994 failf(data, "SSL: Certificate issuer check failed (%s)", 4995 conn_config->issuercert); 4996 BIO_free(fp); 4997 X509_free(issuer); 4998 X509_free(octx->server_cert); 4999 octx->server_cert = NULL; 5000 return CURLE_SSL_ISSUER_ERROR; 5001 } 5002 5003 infof(data, " SSL certificate issuer check ok (%s)", 5004 conn_config->issuercert); 5005 BIO_free(fp); 5006 X509_free(issuer); 5007 } 5008 5009 lerr = SSL_get_verify_result(octx->ssl); 5010 ssl_config->certverifyresult = lerr; 5011 if(lerr != X509_V_OK) { 5012 if(conn_config->verifypeer) { 5013 /* We probably never reach this, because SSL_connect() will fail 5014 and we return earlier if verifypeer is set? */ 5015 if(strict) 5016 failf(data, "SSL certificate verify result: %s (%ld)", 5017 X509_verify_cert_error_string(lerr), lerr); 5018 result = CURLE_PEER_FAILED_VERIFICATION; 5019 } 5020 else 5021 infof(data, " SSL certificate verify result: %s (%ld)," 5022 " continuing anyway.", 5023 X509_verify_cert_error_string(lerr), lerr); 5024 } 5025 else 5026 infof(data, " SSL certificate verify ok."); 5027 } 5028 infof_certstack(data, octx->ssl); 5029 5030 #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_OCSP) 5031 if(conn_config->verifystatus && !octx->reused_session) { 5032 /* do not do this after Session ID reuse */ 5033 result = verifystatus(cf, data, octx); 5034 if(result) { 5035 X509_free(octx->server_cert); 5036 octx->server_cert = NULL; 5037 return result; 5038 } 5039 } 5040 #endif 5041 5042 if(!strict) 5043 /* when not strict, we do not bother about the verify cert problems */ 5044 result = CURLE_OK; 5045 5046 #ifndef CURL_DISABLE_PROXY 5047 ptr = Curl_ssl_cf_is_proxy(cf) ? 5048 data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY] : 5049 data->set.str[STRING_SSL_PINNEDPUBLICKEY]; 5050 #else 5051 ptr = data->set.str[STRING_SSL_PINNEDPUBLICKEY]; 5052 #endif 5053 if(!result && ptr) { 5054 result = ossl_pkp_pin_peer_pubkey(data, octx->server_cert, ptr); 5055 if(result) 5056 failf(data, "SSL: public key does not match pinned public key"); 5057 } 5058 5059 X509_free(octx->server_cert); 5060 octx->server_cert = NULL; 5061 5062 return result; 5063 } 5064 5065 static CURLcode ossl_connect_step3(struct Curl_cfilter *cf, 5066 struct Curl_easy *data) 5067 { 5068 CURLcode result = CURLE_OK; 5069 struct ssl_connect_data *connssl = cf->ctx; 5070 struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend; 5071 5072 DEBUGASSERT(ssl_connect_3 == connssl->connecting_state); 5073 5074 /* 5075 * We check certificates to authenticate the server; otherwise we risk 5076 * man-in-the-middle attack; NEVERTHELESS, if we are told explicitly not to 5077 * verify the peer, ignore faults and failures from the server cert 5078 * operations. 5079 */ 5080 5081 result = Curl_oss_check_peer_cert(cf, data, octx, &connssl->peer); 5082 if(result) 5083 /* on error, remove sessions we might have in the pool */ 5084 Curl_ssl_scache_remove_all(cf, data, connssl->peer.scache_key); 5085 5086 return result; 5087 } 5088 5089 #ifdef HAVE_OPENSSL_EARLYDATA 5090 static CURLcode ossl_send_earlydata(struct Curl_cfilter *cf, 5091 struct Curl_easy *data) 5092 { 5093 struct ssl_connect_data *connssl = cf->ctx; 5094 struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend; 5095 CURLcode result = CURLE_OK; 5096 const unsigned char *buf; 5097 size_t blen, nwritten; 5098 int rc; 5099 5100 DEBUGASSERT(connssl->earlydata_state == ssl_earlydata_sending); 5101 octx->io_result = CURLE_OK; 5102 while(Curl_bufq_peek(&connssl->earlydata, &buf, &blen)) { 5103 nwritten = 0; 5104 rc = SSL_write_early_data(octx->ssl, buf, blen, &nwritten); 5105 CURL_TRC_CF(data, cf, "SSL_write_early_data(len=%zu) -> %d, %zu", 5106 blen, rc, nwritten); 5107 if(rc <= 0) { 5108 long sslerror; 5109 char error_buffer[256]; 5110 int err = SSL_get_error(octx->ssl, rc); 5111 5112 switch(err) { 5113 case SSL_ERROR_WANT_READ: 5114 connssl->io_need = CURL_SSL_IO_NEED_RECV; 5115 result = CURLE_AGAIN; 5116 goto out; 5117 case SSL_ERROR_WANT_WRITE: 5118 connssl->io_need = CURL_SSL_IO_NEED_SEND; 5119 result = CURLE_AGAIN; 5120 goto out; 5121 case SSL_ERROR_SYSCALL: { 5122 int sockerr = SOCKERRNO; 5123 5124 if(octx->io_result == CURLE_AGAIN) { 5125 result = CURLE_AGAIN; 5126 goto out; 5127 } 5128 sslerror = ERR_get_error(); 5129 if(sslerror) 5130 ossl_strerror(sslerror, error_buffer, sizeof(error_buffer)); 5131 else if(sockerr) 5132 Curl_strerror(sockerr, error_buffer, sizeof(error_buffer)); 5133 else 5134 msnprintf(error_buffer, sizeof(error_buffer), "%s", 5135 SSL_ERROR_to_str(err)); 5136 5137 failf(data, OSSL_PACKAGE " SSL_write:early_data: %s, errno %d", 5138 error_buffer, sockerr); 5139 result = CURLE_SEND_ERROR; 5140 goto out; 5141 } 5142 case SSL_ERROR_SSL: { 5143 /* A failure in the SSL library occurred, usually a protocol error. 5144 The OpenSSL error queue contains more information on the error. */ 5145 sslerror = ERR_get_error(); 5146 failf(data, "SSL_write_early_data() error: %s", 5147 ossl_strerror(sslerror, error_buffer, sizeof(error_buffer))); 5148 result = CURLE_SEND_ERROR; 5149 goto out; 5150 } 5151 default: 5152 /* a true error */ 5153 failf(data, OSSL_PACKAGE " SSL_write_early_data: %s, errno %d", 5154 SSL_ERROR_to_str(err), SOCKERRNO); 5155 result = CURLE_SEND_ERROR; 5156 goto out; 5157 } 5158 } 5159 Curl_bufq_skip(&connssl->earlydata, nwritten); 5160 } 5161 /* sent everything there was */ 5162 infof(data, "SSL sending %zu bytes of early data", connssl->earlydata_skip); 5163 out: 5164 return result; 5165 } 5166 #endif /* HAVE_OPENSSL_EARLYDATA */ 5167 5168 static CURLcode ossl_connect(struct Curl_cfilter *cf, 5169 struct Curl_easy *data, 5170 bool *done) 5171 { 5172 CURLcode result = CURLE_OK; 5173 struct ssl_connect_data *connssl = cf->ctx; 5174 5175 /* check if the connection has already been established */ 5176 if(ssl_connection_complete == connssl->state) { 5177 *done = TRUE; 5178 return CURLE_OK; 5179 } 5180 5181 *done = FALSE; 5182 connssl->io_need = CURL_SSL_IO_NEED_NONE; 5183 5184 if(ssl_connect_1 == connssl->connecting_state) { 5185 CURL_TRC_CF(data, cf, "ossl_connect, step1"); 5186 result = ossl_connect_step1(cf, data); 5187 if(result) 5188 goto out; 5189 } 5190 5191 if(ssl_connect_2 == connssl->connecting_state) { 5192 CURL_TRC_CF(data, cf, "ossl_connect, step2"); 5193 #ifdef HAVE_OPENSSL_EARLYDATA 5194 if(connssl->earlydata_state == ssl_earlydata_await) { 5195 goto out; 5196 } 5197 else if(connssl->earlydata_state == ssl_earlydata_sending) { 5198 result = ossl_send_earlydata(cf, data); 5199 if(result) 5200 goto out; 5201 connssl->earlydata_state = ssl_earlydata_sent; 5202 } 5203 #endif 5204 DEBUGASSERT((connssl->earlydata_state == ssl_earlydata_none) || 5205 (connssl->earlydata_state == ssl_earlydata_sent)); 5206 5207 result = ossl_connect_step2(cf, data); 5208 if(result) 5209 goto out; 5210 } 5211 5212 if(ssl_connect_3 == connssl->connecting_state) { 5213 CURL_TRC_CF(data, cf, "ossl_connect, step3"); 5214 result = ossl_connect_step3(cf, data); 5215 if(result) 5216 goto out; 5217 connssl->connecting_state = ssl_connect_done; 5218 #ifdef HAVE_OPENSSL_EARLYDATA 5219 if(connssl->earlydata_state > ssl_earlydata_none) { 5220 struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend; 5221 /* We should be in this state by now */ 5222 DEBUGASSERT(connssl->earlydata_state == ssl_earlydata_sent); 5223 connssl->earlydata_state = 5224 (SSL_get_early_data_status(octx->ssl) == SSL_EARLY_DATA_ACCEPTED) ? 5225 ssl_earlydata_accepted : ssl_earlydata_rejected; 5226 } 5227 #endif 5228 } 5229 5230 if(ssl_connect_done == connssl->connecting_state) { 5231 CURL_TRC_CF(data, cf, "ossl_connect, done"); 5232 connssl->state = ssl_connection_complete; 5233 } 5234 5235 out: 5236 if(result == CURLE_AGAIN) { 5237 *done = FALSE; 5238 return CURLE_OK; 5239 } 5240 *done = ((connssl->state == ssl_connection_complete) || 5241 (connssl->state == ssl_connection_deferred)); 5242 return result; 5243 } 5244 5245 static bool ossl_data_pending(struct Curl_cfilter *cf, 5246 const struct Curl_easy *data) 5247 { 5248 struct ssl_connect_data *connssl = cf->ctx; 5249 (void)data; 5250 return connssl->input_pending; 5251 } 5252 5253 static CURLcode ossl_send(struct Curl_cfilter *cf, 5254 struct Curl_easy *data, 5255 const void *mem, 5256 size_t len, 5257 size_t *pnwritten) 5258 { 5259 /* SSL_write() is said to return 'int' while write() and send() returns 5260 'size_t' */ 5261 int err; 5262 char error_buffer[256]; 5263 sslerr_t sslerror; 5264 int memlen; 5265 struct ssl_connect_data *connssl = cf->ctx; 5266 struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend; 5267 CURLcode result = CURLE_OK; 5268 int nwritten; 5269 5270 (void)data; 5271 DEBUGASSERT(octx); 5272 *pnwritten = 0; 5273 ERR_clear_error(); 5274 5275 connssl->io_need = CURL_SSL_IO_NEED_NONE; 5276 memlen = (len > (size_t)INT_MAX) ? INT_MAX : (int)len; 5277 nwritten = SSL_write(octx->ssl, mem, memlen); 5278 5279 if(nwritten > 0) 5280 *pnwritten = (size_t)nwritten; 5281 else { 5282 err = SSL_get_error(octx->ssl, nwritten); 5283 5284 switch(err) { 5285 case SSL_ERROR_WANT_READ: 5286 connssl->io_need = CURL_SSL_IO_NEED_RECV; 5287 result = CURLE_AGAIN; 5288 goto out; 5289 case SSL_ERROR_WANT_WRITE: 5290 result = CURLE_AGAIN; 5291 goto out; 5292 case SSL_ERROR_SYSCALL: 5293 { 5294 int sockerr = SOCKERRNO; 5295 5296 if(octx->io_result == CURLE_AGAIN) { 5297 result = CURLE_AGAIN; 5298 goto out; 5299 } 5300 sslerror = ERR_get_error(); 5301 if(sslerror) 5302 ossl_strerror(sslerror, error_buffer, sizeof(error_buffer)); 5303 else if(sockerr) 5304 Curl_strerror(sockerr, error_buffer, sizeof(error_buffer)); 5305 else 5306 msnprintf(error_buffer, sizeof(error_buffer), "%s", 5307 SSL_ERROR_to_str(err)); 5308 5309 failf(data, OSSL_PACKAGE " SSL_write: %s, errno %d", 5310 error_buffer, sockerr); 5311 result = CURLE_SEND_ERROR; 5312 goto out; 5313 } 5314 case SSL_ERROR_SSL: { 5315 /* A failure in the SSL library occurred, usually a protocol error. 5316 The OpenSSL error queue contains more information on the error. */ 5317 sslerror = ERR_get_error(); 5318 failf(data, "SSL_write() error: %s", 5319 ossl_strerror(sslerror, error_buffer, sizeof(error_buffer))); 5320 result = CURLE_SEND_ERROR; 5321 goto out; 5322 } 5323 default: 5324 /* a true error */ 5325 failf(data, OSSL_PACKAGE " SSL_write: %s, errno %d", 5326 SSL_ERROR_to_str(err), SOCKERRNO); 5327 result = CURLE_SEND_ERROR; 5328 goto out; 5329 } 5330 } 5331 5332 out: 5333 return result; 5334 } 5335 5336 static CURLcode ossl_recv(struct Curl_cfilter *cf, 5337 struct Curl_easy *data, /* transfer */ 5338 char *buf, /* store read data here */ 5339 size_t buffersize, /* max amount to read */ 5340 size_t *pnread) 5341 { 5342 char error_buffer[256]; 5343 unsigned long sslerror; 5344 int buffsize; 5345 struct connectdata *conn = cf->conn; 5346 struct ssl_connect_data *connssl = cf->ctx; 5347 struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend; 5348 CURLcode result = CURLE_OK; 5349 int nread; 5350 5351 (void)data; 5352 DEBUGASSERT(octx); 5353 5354 *pnread = 0; 5355 ERR_clear_error(); 5356 5357 connssl->io_need = CURL_SSL_IO_NEED_NONE; 5358 buffsize = (buffersize > (size_t)INT_MAX) ? INT_MAX : (int)buffersize; 5359 nread = SSL_read(octx->ssl, buf, buffsize); 5360 5361 if(nread > 0) 5362 *pnread = (size_t)nread; 5363 else { 5364 /* failed SSL_read */ 5365 int err = SSL_get_error(octx->ssl, (int)nread); 5366 5367 switch(err) { 5368 case SSL_ERROR_NONE: /* this is not an error */ 5369 break; 5370 case SSL_ERROR_ZERO_RETURN: /* no more data */ 5371 /* close_notify alert */ 5372 if(cf->sockindex == FIRSTSOCKET) 5373 /* mark the connection for close if it is indeed the control 5374 connection */ 5375 connclose(conn, "TLS close_notify"); 5376 break; 5377 case SSL_ERROR_WANT_READ: 5378 result = CURLE_AGAIN; 5379 goto out; 5380 case SSL_ERROR_WANT_WRITE: 5381 connssl->io_need = CURL_SSL_IO_NEED_SEND; 5382 result = CURLE_AGAIN; 5383 goto out; 5384 default: 5385 /* openssl/ssl.h for SSL_ERROR_SYSCALL says "look at error stack/return 5386 value/errno" */ 5387 /* https://docs.openssl.org/master/man3/ERR_get_error/ */ 5388 if(octx->io_result == CURLE_AGAIN) { 5389 result = CURLE_AGAIN; 5390 goto out; 5391 } 5392 sslerror = ERR_get_error(); 5393 if((nread < 0) || sslerror) { 5394 /* If the return code was negative or there actually is an error in the 5395 queue */ 5396 int sockerr = SOCKERRNO; 5397 if(sslerror) 5398 ossl_strerror(sslerror, error_buffer, sizeof(error_buffer)); 5399 else if(sockerr && err == SSL_ERROR_SYSCALL) 5400 Curl_strerror(sockerr, error_buffer, sizeof(error_buffer)); 5401 else 5402 msnprintf(error_buffer, sizeof(error_buffer), "%s", 5403 SSL_ERROR_to_str(err)); 5404 failf(data, OSSL_PACKAGE " SSL_read: %s, errno %d", 5405 error_buffer, sockerr); 5406 result = CURLE_RECV_ERROR; 5407 goto out; 5408 } 5409 else if(err == SSL_ERROR_SYSCALL) { 5410 if(octx->io_result) { 5411 /* logging handling in underlying filter already */ 5412 result = octx->io_result; 5413 } 5414 else if(connssl->peer_closed) { 5415 failf(data, "Connection closed abruptly"); 5416 result = CURLE_RECV_ERROR; 5417 } 5418 else { 5419 /* We should no longer get here nowadays. But handle 5420 * the error in case of some weirdness in the OSSL stack */ 5421 int sockerr = SOCKERRNO; 5422 if(sockerr) 5423 Curl_strerror(sockerr, error_buffer, sizeof(error_buffer)); 5424 else { 5425 msnprintf(error_buffer, sizeof(error_buffer), 5426 "Connection closed abruptly"); 5427 } 5428 failf(data, OSSL_PACKAGE " SSL_read: %s, errno %d", 5429 error_buffer, sockerr); 5430 result = CURLE_RECV_ERROR; 5431 } 5432 goto out; 5433 } 5434 } 5435 } 5436 5437 out: 5438 if((!result && !*pnread) || (result == CURLE_AGAIN)) { 5439 /* This happens when: 5440 * - we read an EOF 5441 * - OpenSSLs buffers are empty, there is no more data 5442 * - OpenSSL read is blocked on writing something first 5443 * - an incomplete TLS packet is buffered that cannot be read 5444 * until more data arrives */ 5445 connssl->input_pending = FALSE; 5446 } 5447 CURL_TRC_CF(data, cf, "ossl_recv(len=%zu) -> %d, %zu (in_pending=%d)", 5448 buffersize, result, *pnread, connssl->input_pending); 5449 return result; 5450 } 5451 5452 static CURLcode ossl_get_channel_binding(struct Curl_easy *data, int sockindex, 5453 struct dynbuf *binding) 5454 { 5455 /* required for X509_get_signature_nid support */ 5456 #if OPENSSL_VERSION_NUMBER > 0x10100000L 5457 X509 *cert; 5458 int algo_nid; 5459 const EVP_MD *algo_type; 5460 const char *algo_name; 5461 unsigned int length; 5462 unsigned char buf[EVP_MAX_MD_SIZE]; 5463 5464 const char prefix[] = "tls-server-end-point:"; 5465 struct connectdata *conn = data->conn; 5466 struct Curl_cfilter *cf = conn->cfilter[sockindex]; 5467 struct ossl_ctx *octx = NULL; 5468 5469 do { 5470 const struct Curl_cftype *cft = cf->cft; 5471 struct ssl_connect_data *connssl = cf->ctx; 5472 5473 if(cft->name && !strcmp(cft->name, "SSL")) { 5474 octx = (struct ossl_ctx *)connssl->backend; 5475 break; 5476 } 5477 5478 if(cf->next) 5479 cf = cf->next; 5480 5481 } while(cf->next); 5482 5483 if(!octx) { 5484 failf(data, "Failed to find the SSL filter"); 5485 return CURLE_BAD_FUNCTION_ARGUMENT; 5486 } 5487 5488 cert = SSL_get1_peer_certificate(octx->ssl); 5489 if(!cert) { 5490 /* No server certificate, don't do channel binding */ 5491 return CURLE_OK; 5492 } 5493 5494 if(!OBJ_find_sigid_algs(X509_get_signature_nid(cert), &algo_nid, NULL)) { 5495 failf(data, 5496 "Unable to find digest NID for certificate signature algorithm"); 5497 return CURLE_SSL_INVALIDCERTSTATUS; 5498 } 5499 5500 /* https://datatracker.ietf.org/doc/html/rfc5929#section-4.1 */ 5501 if(algo_nid == NID_md5 || algo_nid == NID_sha1) { 5502 algo_type = EVP_sha256(); 5503 } 5504 else { 5505 algo_type = EVP_get_digestbynid(algo_nid); 5506 if(!algo_type) { 5507 algo_name = OBJ_nid2sn(algo_nid); 5508 failf(data, "Could not find digest algorithm %s (NID %d)", 5509 algo_name ? algo_name : "(null)", algo_nid); 5510 return CURLE_SSL_INVALIDCERTSTATUS; 5511 } 5512 } 5513 5514 if(!X509_digest(cert, algo_type, buf, &length)) { 5515 failf(data, "X509_digest() failed"); 5516 return CURLE_SSL_INVALIDCERTSTATUS; 5517 } 5518 5519 /* Append "tls-server-end-point:" */ 5520 if(curlx_dyn_addn(binding, prefix, sizeof(prefix) - 1) != CURLE_OK) 5521 return CURLE_OUT_OF_MEMORY; 5522 /* Append digest */ 5523 if(curlx_dyn_addn(binding, buf, length)) 5524 return CURLE_OUT_OF_MEMORY; 5525 5526 return CURLE_OK; 5527 #else 5528 /* No X509_get_signature_nid support */ 5529 (void)data; /* unused */ 5530 (void)sockindex; /* unused */ 5531 (void)binding; /* unused */ 5532 return CURLE_OK; 5533 #endif 5534 } 5535 5536 size_t Curl_ossl_version(char *buffer, size_t size) 5537 { 5538 #ifdef LIBRESSL_VERSION_NUMBER 5539 char *p; 5540 size_t count; 5541 const char *ver = OpenSSL_version(OPENSSL_VERSION); 5542 const char expected[] = OSSL_PACKAGE " "; /* ie "LibreSSL " */ 5543 if(curl_strnequal(ver, expected, sizeof(expected) - 1)) { 5544 ver += sizeof(expected) - 1; 5545 } 5546 count = msnprintf(buffer, size, "%s/%s", OSSL_PACKAGE, ver); 5547 for(p = buffer; *p; ++p) { 5548 if(ISBLANK(*p)) 5549 *p = '_'; 5550 } 5551 return count; 5552 #elif defined(OPENSSL_IS_BORINGSSL) 5553 #ifdef CURL_BORINGSSL_VERSION 5554 return msnprintf(buffer, size, "%s/%s", 5555 OSSL_PACKAGE, 5556 CURL_BORINGSSL_VERSION); 5557 #else 5558 return msnprintf(buffer, size, OSSL_PACKAGE); 5559 #endif 5560 #elif defined(OPENSSL_IS_AWSLC) 5561 return msnprintf(buffer, size, "%s/%s", 5562 OSSL_PACKAGE, 5563 AWSLC_VERSION_NUMBER_STRING); 5564 #elif defined(HAVE_OPENSSL_VERSION) && defined(OPENSSL_VERSION_STRING) 5565 return msnprintf(buffer, size, "%s/%s", 5566 OSSL_PACKAGE, OpenSSL_version(OPENSSL_VERSION_STRING)); 5567 #else 5568 /* not LibreSSL, BoringSSL and not using OpenSSL_version */ 5569 5570 char sub[3]; 5571 unsigned long ssleay_value; 5572 sub[2]='\0'; 5573 sub[1]='\0'; 5574 ssleay_value = OpenSSL_version_num(); 5575 if(ssleay_value&0xff0) { 5576 int minor_ver = (ssleay_value >> 4) & 0xff; 5577 if(minor_ver > 26) { 5578 /* handle extended version introduced for 0.9.8za */ 5579 sub[1] = (char) ((minor_ver - 1) % 26 + 'a' + 1); 5580 sub[0] = 'z'; 5581 } 5582 else { 5583 sub[0] = (char) (minor_ver + 'a' - 1); 5584 } 5585 } 5586 else 5587 sub[0]='\0'; 5588 5589 return msnprintf(buffer, size, "%s/%lx.%lx.%lx%s" 5590 #ifdef OPENSSL_FIPS 5591 "-fips" 5592 #endif 5593 , 5594 OSSL_PACKAGE, 5595 (ssleay_value >> 28) & 0xf, 5596 (ssleay_value >> 20) & 0xff, 5597 (ssleay_value >> 12) & 0xff, 5598 sub); 5599 #endif /* OPENSSL_IS_BORINGSSL */ 5600 } 5601 5602 /* can be called with data == NULL */ 5603 static CURLcode ossl_random(struct Curl_easy *data, 5604 unsigned char *entropy, size_t length) 5605 { 5606 int rc; 5607 if(data) { 5608 if(ossl_seed(data)) /* Initiate the seed if not already done */ 5609 return CURLE_FAILED_INIT; /* could not seed for some reason */ 5610 } 5611 else { 5612 if(!rand_enough()) 5613 return CURLE_FAILED_INIT; 5614 } 5615 /* RAND_bytes() returns 1 on success, 0 otherwise. */ 5616 rc = RAND_bytes(entropy, (ossl_valsize_t)curlx_uztosi(length)); 5617 return rc == 1 ? CURLE_OK : CURLE_FAILED_INIT; 5618 } 5619 5620 #ifndef OPENSSL_NO_SHA256 5621 static CURLcode ossl_sha256sum(const unsigned char *tmp, /* input */ 5622 size_t tmplen, 5623 unsigned char *sha256sum /* output */, 5624 size_t unused) 5625 { 5626 EVP_MD_CTX *mdctx; 5627 unsigned int len = 0; 5628 (void) unused; 5629 5630 mdctx = EVP_MD_CTX_create(); 5631 if(!mdctx) 5632 return CURLE_OUT_OF_MEMORY; 5633 if(!EVP_DigestInit(mdctx, EVP_sha256())) { 5634 EVP_MD_CTX_destroy(mdctx); 5635 return CURLE_FAILED_INIT; 5636 } 5637 EVP_DigestUpdate(mdctx, tmp, tmplen); 5638 EVP_DigestFinal_ex(mdctx, sha256sum, &len); 5639 EVP_MD_CTX_destroy(mdctx); 5640 return CURLE_OK; 5641 } 5642 #endif 5643 5644 static bool ossl_cert_status_request(void) 5645 { 5646 #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_OCSP) 5647 return TRUE; 5648 #else 5649 return FALSE; 5650 #endif 5651 } 5652 5653 static void *ossl_get_internals(struct ssl_connect_data *connssl, 5654 CURLINFO info) 5655 { 5656 /* Legacy: CURLINFO_TLS_SESSION must return an SSL_CTX pointer. */ 5657 struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend; 5658 DEBUGASSERT(octx); 5659 return info == CURLINFO_TLS_SESSION ? 5660 (void *)octx->ssl_ctx : (void *)octx->ssl; 5661 } 5662 5663 const struct Curl_ssl Curl_ssl_openssl = { 5664 { CURLSSLBACKEND_OPENSSL, "openssl" }, /* info */ 5665 5666 SSLSUPP_CA_PATH | 5667 SSLSUPP_CAINFO_BLOB | 5668 SSLSUPP_CERTINFO | 5669 SSLSUPP_PINNEDPUBKEY | 5670 SSLSUPP_SSL_CTX | 5671 #ifdef HAVE_SSL_CTX_SET_CIPHERSUITES 5672 SSLSUPP_TLS13_CIPHERSUITES | 5673 #endif 5674 #ifdef HAVE_SSL_CTX_SET1_SIGALGS 5675 SSLSUPP_SIGNATURE_ALGORITHMS | 5676 #endif 5677 #ifdef USE_ECH_OPENSSL 5678 SSLSUPP_ECH | 5679 #endif 5680 SSLSUPP_CA_CACHE | 5681 SSLSUPP_HTTPS_PROXY | 5682 SSLSUPP_CIPHER_LIST, 5683 5684 sizeof(struct ossl_ctx), 5685 5686 ossl_init, /* init */ 5687 ossl_cleanup, /* cleanup */ 5688 Curl_ossl_version, /* version */ 5689 ossl_shutdown, /* shutdown */ 5690 ossl_data_pending, /* data_pending */ 5691 ossl_random, /* random */ 5692 ossl_cert_status_request, /* cert_status_request */ 5693 ossl_connect, /* connect */ 5694 Curl_ssl_adjust_pollset, /* adjust_pollset */ 5695 ossl_get_internals, /* get_internals */ 5696 ossl_close, /* close_one */ 5697 ossl_close_all, /* close_all */ 5698 ossl_set_engine, /* set_engine or provider */ 5699 ossl_set_engine_default, /* set_engine_default */ 5700 ossl_engines_list, /* engines_list */ 5701 #ifndef OPENSSL_NO_SHA256 5702 ossl_sha256sum, /* sha256sum */ 5703 #else 5704 NULL, /* sha256sum */ 5705 #endif 5706 ossl_recv, /* recv decrypted data */ 5707 ossl_send, /* send data to encrypt */ 5708 ossl_get_channel_binding /* get_channel_binding */ 5709 }; 5710 5711 #endif /* USE_OPENSSL */