VirtualBox

source: vbox/trunk/src/libs/curl-8.11.1/lib/vtls/openssl.c@ 108333

最後變更 在這個檔案從108333是 108048,由 vboxsync 提交於 7 週 前

curl-8.11.1: Applied and adjusted our curl changes to 8.7.1. jiraref:VBP-1535

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette