Coverage Report

Created: 2025-08-26 07:08

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