VirtualBox

source: vbox/trunk/src/libs/curl-7.87.0/lib/vtls/openssl.c@ 98326

最後變更 在這個檔案從98326是 98326,由 vboxsync 提交於 2 年 前

curl-7.87.0: Applied and adjusted our curl changes to 7.83.1. bugref:10356

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette