Coverage Report

Created: 2025-07-23 06:58

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