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