Debian Codegraph @

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

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