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