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