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