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