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