Coverage Report

Created: 2026-12-01 06:33

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