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