Coverage Report

Created: 2025-07-11 06:33

/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
/*
2246
 * Match subjectAltName against the hostname.
2247
 */
2248
static bool subj_alt_hostcheck(struct Curl_easy *data,
2249
                               const char *match_pattern,
2250
                               size_t matchlen,
2251
                               const char *hostname,
2252
                               size_t hostlen,
2253
                               const char *dispname)
2254
0
{
2255
#ifdef CURL_DISABLE_VERBOSE_STRINGS
2256
  (void)dispname;
2257
  (void)data;
2258
#endif
2259
0
  if(Curl_cert_hostcheck(match_pattern, matchlen, hostname, hostlen)) {
2260
0
    infof(data, " subjectAltName: host \"%s\" matched cert's \"%s\"",
2261
0
          dispname, match_pattern);
2262
0
    return TRUE;
2263
0
  }
2264
0
  return FALSE;
2265
0
}
2266
2267
/* Quote from RFC2818 section 3.1 "Server Identity"
2268
2269
   If a subjectAltName extension of type dNSName is present, that MUST
2270
   be used as the identity. Otherwise, the (most specific) Common Name
2271
   field in the Subject field of the certificate MUST be used. Although
2272
   the use of the Common Name is existing practice, it is deprecated and
2273
   Certification Authorities are encouraged to use the dNSName instead.
2274
2275
   Matching is performed using the matching rules specified by
2276
   [RFC2459]. If more than one identity of a given type is present in
2277
   the certificate (e.g., more than one dNSName name, a match in any one
2278
   of the set is considered acceptable.) Names may contain the wildcard
2279
   character * which is considered to match any single domain name
2280
   component or component fragment. E.g., *.a.com matches foo.a.com but
2281
   not bar.foo.a.com. f*.com matches foo.com but not bar.com.
2282
2283
   In some cases, the URI is specified as an IP address rather than a
2284
   hostname. In this case, the iPAddress subjectAltName must be present
2285
   in the certificate and must exactly match the IP in the URI.
2286
2287
   This function is now used from ngtcp2 (QUIC) as well.
2288
*/
2289
static CURLcode ossl_verifyhost(struct Curl_easy *data,
2290
                                struct connectdata *conn,
2291
                                struct ssl_peer *peer, X509 *server_cert)
2292
0
{
2293
0
  bool matched = FALSE;
2294
0
  int target; /* target type, GEN_DNS or GEN_IPADD */
2295
0
  size_t addrlen = 0;
2296
0
  STACK_OF(GENERAL_NAME) *altnames;
2297
0
#ifdef USE_IPV6
2298
0
  struct in6_addr addr;
2299
#else
2300
  struct in_addr addr;
2301
#endif
2302
0
  CURLcode result = CURLE_OK;
2303
0
  bool dNSName = FALSE; /* if a dNSName field exists in the cert */
2304
0
  bool iPAddress = FALSE; /* if an iPAddress field exists in the cert */
2305
0
  size_t hostlen;
2306
2307
0
  (void)conn;
2308
0
  hostlen = strlen(peer->hostname);
2309
0
  switch(peer->type) {
2310
0
  case CURL_SSL_PEER_IPV4:
2311
0
    if(!curlx_inet_pton(AF_INET, peer->hostname, &addr))
2312
0
      return CURLE_PEER_FAILED_VERIFICATION;
2313
0
    target = GEN_IPADD;
2314
0
    addrlen = sizeof(struct in_addr);
2315
0
    break;
2316
0
#ifdef USE_IPV6
2317
0
  case CURL_SSL_PEER_IPV6:
2318
0
    if(!curlx_inet_pton(AF_INET6, peer->hostname, &addr))
2319
0
      return CURLE_PEER_FAILED_VERIFICATION;
2320
0
    target = GEN_IPADD;
2321
0
    addrlen = sizeof(struct in6_addr);
2322
0
    break;
2323
0
#endif
2324
0
  case CURL_SSL_PEER_DNS:
2325
0
    target = GEN_DNS;
2326
0
    break;
2327
0
  default:
2328
0
    DEBUGASSERT(0);
2329
0
    failf(data, "unexpected ssl peer type: %d", peer->type);
2330
0
    return CURLE_PEER_FAILED_VERIFICATION;
2331
0
  }
2332
2333
  /* get a "list" of alternative names */
2334
0
  altnames = X509_get_ext_d2i(server_cert, NID_subject_alt_name, NULL, NULL);
2335
2336
0
  if(altnames) {
2337
#if defined(OPENSSL_IS_BORINGSSL) || defined(OPENSSL_IS_AWSLC)
2338
    size_t numalts;
2339
    size_t i;
2340
#else
2341
0
    int numalts;
2342
0
    int i;
2343
0
#endif
2344
0
    bool dnsmatched = FALSE;
2345
0
    bool ipmatched = FALSE;
2346
2347
    /* get amount of alternatives, RFC2459 claims there MUST be at least
2348
       one, but we do not depend on it... */
2349
0
    numalts = sk_GENERAL_NAME_num(altnames);
2350
2351
    /* loop through all alternatives - until a dnsmatch */
2352
0
    for(i = 0; (i < numalts) && !dnsmatched; i++) {
2353
      /* get a handle to alternative name number i */
2354
0
      const GENERAL_NAME *check = sk_GENERAL_NAME_value(altnames, i);
2355
2356
0
      if(check->type == GEN_DNS)
2357
0
        dNSName = TRUE;
2358
0
      else if(check->type == GEN_IPADD)
2359
0
        iPAddress = TRUE;
2360
2361
      /* only check alternatives of the same type the target is */
2362
0
      if(check->type == target) {
2363
        /* get data and length */
2364
0
        const char *altptr = (const char *)ASN1_STRING_get0_data(check->d.ia5);
2365
0
        size_t altlen = (size_t) ASN1_STRING_length(check->d.ia5);
2366
2367
0
        switch(target) {
2368
0
        case GEN_DNS: /* name/pattern comparison */
2369
          /* The OpenSSL manpage explicitly says: "In general it cannot be
2370
             assumed that the data returned by ASN1_STRING_data() is null
2371
             terminated or does not contain embedded nulls." But also that
2372
             "The actual format of the data will depend on the actual string
2373
             type itself: for example for an IA5String the data will be ASCII"
2374
2375
             It has been however verified that in 0.9.6 and 0.9.7, IA5String
2376
             is always null-terminated.
2377
          */
2378
0
          if((altlen == strlen(altptr)) &&
2379
             /* if this is not true, there was an embedded zero in the name
2380
                string and we cannot match it. */
2381
0
             subj_alt_hostcheck(data, altptr, altlen,
2382
0
                                peer->hostname, hostlen,
2383
0
                                peer->dispname)) {
2384
0
            dnsmatched = TRUE;
2385
0
          }
2386
0
          break;
2387
2388
0
        case GEN_IPADD: /* IP address comparison */
2389
          /* compare alternative IP address if the data chunk is the same size
2390
             our server IP address is */
2391
0
          if((altlen == addrlen) && !memcmp(altptr, &addr, altlen)) {
2392
0
            ipmatched = TRUE;
2393
0
            infof(data,
2394
0
                  " subjectAltName: host \"%s\" matched cert's IP address!",
2395
0
                  peer->dispname);
2396
0
          }
2397
0
          break;
2398
0
        }
2399
0
      }
2400
0
    }
2401
0
    GENERAL_NAMES_free(altnames);
2402
2403
0
    if(dnsmatched || ipmatched)
2404
0
      matched = TRUE;
2405
0
  }
2406
2407
0
  if(matched)
2408
    /* an alternative name matched */
2409
0
    ;
2410
0
  else if(dNSName || iPAddress) {
2411
0
    const char *tname = (peer->type == CURL_SSL_PEER_DNS) ? "hostname" :
2412
0
                        (peer->type == CURL_SSL_PEER_IPV4) ?
2413
0
                        "ipv4 address" : "ipv6 address";
2414
0
    infof(data, " subjectAltName does not match %s %s", tname, peer->dispname);
2415
0
    failf(data, "SSL: no alternative certificate subject name matches "
2416
0
          "target %s '%s'", tname, peer->dispname);
2417
0
    result = CURLE_PEER_FAILED_VERIFICATION;
2418
0
  }
2419
0
  else {
2420
    /* we have to look to the last occurrence of a commonName in the
2421
       distinguished one to get the most significant one. */
2422
0
    int i = -1;
2423
0
    unsigned char *cn = NULL;
2424
0
    int cnlen = 0;
2425
0
    bool free_cn = FALSE;
2426
2427
    /* The following is done because of a bug in 0.9.6b */
2428
0
    X509_NAME *name = X509_get_subject_name(server_cert);
2429
0
    if(name) {
2430
0
      int j;
2431
0
      while((j = X509_NAME_get_index_by_NID(name, NID_commonName, i)) >= 0)
2432
0
        i = j;
2433
0
    }
2434
2435
    /* we have the name entry and we will now convert this to a string
2436
       that we can use for comparison. Doing this we support BMPstring,
2437
       UTF8, etc. */
2438
2439
0
    if(i >= 0) {
2440
0
      ASN1_STRING *tmp =
2441
0
        X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name, i));
2442
2443
      /* In OpenSSL 0.9.7d and earlier, ASN1_STRING_to_UTF8 fails if the input
2444
         is already UTF-8 encoded. We check for this case and copy the raw
2445
         string manually to avoid the problem. This code can be made
2446
         conditional in the future when OpenSSL has been fixed. */
2447
0
      if(tmp) {
2448
0
        if(ASN1_STRING_type(tmp) == V_ASN1_UTF8STRING) {
2449
0
          cnlen = ASN1_STRING_length(tmp);
2450
0
          cn = (unsigned char *)CURL_UNCONST(ASN1_STRING_get0_data(tmp));
2451
0
        }
2452
0
        else { /* not a UTF8 name */
2453
0
          cnlen = ASN1_STRING_to_UTF8(&cn, tmp);
2454
0
          free_cn = TRUE;
2455
0
        }
2456
2457
0
        if((cnlen <= 0) || !cn)
2458
0
          result = CURLE_OUT_OF_MEMORY;
2459
0
        else if((size_t)cnlen != strlen((char *)cn)) {
2460
          /* there was a terminating zero before the end of string, this
2461
             cannot match and we return failure! */
2462
0
          failf(data, "SSL: illegal cert name field");
2463
0
          result = CURLE_PEER_FAILED_VERIFICATION;
2464
0
        }
2465
0
      }
2466
0
    }
2467
2468
0
    if(result)
2469
      /* error already detected, pass through */
2470
0
      ;
2471
0
    else if(!cn) {
2472
0
      failf(data,
2473
0
            "SSL: unable to obtain common name from peer certificate");
2474
0
      result = CURLE_PEER_FAILED_VERIFICATION;
2475
0
    }
2476
0
    else if(!Curl_cert_hostcheck((const char *)cn, cnlen,
2477
0
                                 peer->hostname, hostlen)) {
2478
0
      failf(data, "SSL: certificate subject name '%s' does not match "
2479
0
            "target hostname '%s'", cn, peer->dispname);
2480
0
      result = CURLE_PEER_FAILED_VERIFICATION;
2481
0
    }
2482
0
    else {
2483
0
      infof(data, " common name: %s (matched)", cn);
2484
0
    }
2485
0
    if(free_cn)
2486
0
      OPENSSL_free(cn);
2487
0
  }
2488
2489
0
  return result;
2490
0
}
2491
2492
#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_OCSP)
2493
static CURLcode verifystatus(struct Curl_cfilter *cf,
2494
                             struct Curl_easy *data,
2495
                             struct ossl_ctx *octx)
2496
0
{
2497
0
  int i, ocsp_status;
2498
#ifdef OPENSSL_IS_AWSLC
2499
  const uint8_t *status;
2500
#else
2501
0
  unsigned char *status;
2502
0
#endif
2503
0
  const unsigned char *p;
2504
0
  CURLcode result = CURLE_OK;
2505
0
  OCSP_RESPONSE *rsp = NULL;
2506
0
  OCSP_BASICRESP *br = NULL;
2507
0
  X509_STORE     *st = NULL;
2508
0
  STACK_OF(X509) *ch = NULL;
2509
0
  X509 *cert;
2510
0
  OCSP_CERTID *id = NULL;
2511
0
  int cert_status, crl_reason;
2512
0
  ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
2513
0
  int ret;
2514
0
  long len;
2515
2516
0
  (void)cf;
2517
0
  DEBUGASSERT(octx);
2518
2519
0
  len = (long)SSL_get_tlsext_status_ocsp_resp(octx->ssl, &status);
2520
2521
0
  if(!status) {
2522
0
    failf(data, "No OCSP response received");
2523
0
    result = CURLE_SSL_INVALIDCERTSTATUS;
2524
0
    goto end;
2525
0
  }
2526
0
  p = status;
2527
0
  rsp = d2i_OCSP_RESPONSE(NULL, &p, len);
2528
0
  if(!rsp) {
2529
0
    failf(data, "Invalid OCSP response");
2530
0
    result = CURLE_SSL_INVALIDCERTSTATUS;
2531
0
    goto end;
2532
0
  }
2533
2534
0
  ocsp_status = OCSP_response_status(rsp);
2535
0
  if(ocsp_status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
2536
0
    failf(data, "Invalid OCSP response status: %s (%d)",
2537
0
          OCSP_response_status_str(ocsp_status), ocsp_status);
2538
0
    result = CURLE_SSL_INVALIDCERTSTATUS;
2539
0
    goto end;
2540
0
  }
2541
2542
0
  br = OCSP_response_get1_basic(rsp);
2543
0
  if(!br) {
2544
0
    failf(data, "Invalid OCSP response");
2545
0
    result = CURLE_SSL_INVALIDCERTSTATUS;
2546
0
    goto end;
2547
0
  }
2548
2549
0
  ch = SSL_get_peer_cert_chain(octx->ssl);
2550
0
  if(!ch) {
2551
0
    failf(data, "Could not get peer certificate chain");
2552
0
    result = CURLE_SSL_INVALIDCERTSTATUS;
2553
0
    goto end;
2554
0
  }
2555
0
  st = SSL_CTX_get_cert_store(octx->ssl_ctx);
2556
2557
0
  if(OCSP_basic_verify(br, ch, st, 0) <= 0) {
2558
0
    failf(data, "OCSP response verification failed");
2559
0
    result = CURLE_SSL_INVALIDCERTSTATUS;
2560
0
    goto end;
2561
0
  }
2562
2563
  /* Compute the certificate's ID */
2564
0
  cert = SSL_get1_peer_certificate(octx->ssl);
2565
0
  if(!cert) {
2566
0
    failf(data, "Error getting peer certificate");
2567
0
    result = CURLE_SSL_INVALIDCERTSTATUS;
2568
0
    goto end;
2569
0
  }
2570
2571
0
  for(i = 0; i < (int)sk_X509_num(ch); i++) {
2572
0
    X509 *issuer = sk_X509_value(ch, (ossl_valsize_t)i);
2573
0
    if(X509_check_issued(issuer, cert) == X509_V_OK) {
2574
0
      id = OCSP_cert_to_id(EVP_sha1(), cert, issuer);
2575
0
      break;
2576
0
    }
2577
0
  }
2578
0
  X509_free(cert);
2579
2580
0
  if(!id) {
2581
0
    failf(data, "Error computing OCSP ID");
2582
0
    result = CURLE_SSL_INVALIDCERTSTATUS;
2583
0
    goto end;
2584
0
  }
2585
2586
  /* Find the single OCSP response corresponding to the certificate ID */
2587
0
  ret = OCSP_resp_find_status(br, id, &cert_status, &crl_reason, &rev,
2588
0
                              &thisupd, &nextupd);
2589
0
  OCSP_CERTID_free(id);
2590
0
  if(ret != 1) {
2591
0
    failf(data, "Could not find certificate ID in OCSP response");
2592
0
    result = CURLE_SSL_INVALIDCERTSTATUS;
2593
0
    goto end;
2594
0
  }
2595
2596
  /* Validate the corresponding single OCSP response */
2597
0
  if(!OCSP_check_validity(thisupd, nextupd, 300L, -1L)) {
2598
0
    failf(data, "OCSP response has expired");
2599
0
    result = CURLE_SSL_INVALIDCERTSTATUS;
2600
0
    goto end;
2601
0
  }
2602
2603
0
  infof(data, "SSL certificate status: %s (%d)",
2604
0
        OCSP_cert_status_str(cert_status), cert_status);
2605
2606
0
  switch(cert_status) {
2607
0
  case V_OCSP_CERTSTATUS_GOOD:
2608
0
    break;
2609
2610
0
  case V_OCSP_CERTSTATUS_REVOKED:
2611
0
    result = CURLE_SSL_INVALIDCERTSTATUS;
2612
0
    failf(data, "SSL certificate revocation reason: %s (%d)",
2613
0
          OCSP_crl_reason_str(crl_reason), crl_reason);
2614
0
    goto end;
2615
2616
0
  case V_OCSP_CERTSTATUS_UNKNOWN:
2617
0
  default:
2618
0
    result = CURLE_SSL_INVALIDCERTSTATUS;
2619
0
    goto end;
2620
0
  }
2621
2622
0
end:
2623
0
  if(br)
2624
0
    OCSP_BASICRESP_free(br);
2625
0
  OCSP_RESPONSE_free(rsp);
2626
2627
0
  return result;
2628
0
}
2629
#endif
2630
2631
#endif /* USE_OPENSSL */
2632
2633
/* The SSL_CTRL_SET_MSG_CALLBACK does not exist in ancient OpenSSL versions
2634
   and thus this cannot be done there. */
2635
#ifdef SSL_CTRL_SET_MSG_CALLBACK
2636
2637
static const char *ssl_msg_type(int ssl_ver, int msg)
2638
0
{
2639
#ifdef SSL2_VERSION_MAJOR
2640
  if(ssl_ver == SSL2_VERSION_MAJOR) {
2641
    switch(msg) {
2642
    case SSL2_MT_ERROR:
2643
      return "Error";
2644
    case SSL2_MT_CLIENT_HELLO:
2645
      return "Client hello";
2646
    case SSL2_MT_CLIENT_MASTER_KEY:
2647
      return "Client key";
2648
    case SSL2_MT_CLIENT_FINISHED:
2649
      return "Client finished";
2650
    case SSL2_MT_SERVER_HELLO:
2651
      return "Server hello";
2652
    case SSL2_MT_SERVER_VERIFY:
2653
      return "Server verify";
2654
    case SSL2_MT_SERVER_FINISHED:
2655
      return "Server finished";
2656
    case SSL2_MT_REQUEST_CERTIFICATE:
2657
      return "Request CERT";
2658
    case SSL2_MT_CLIENT_CERTIFICATE:
2659
      return "Client CERT";
2660
    }
2661
  }
2662
  else
2663
#endif
2664
0
  if(ssl_ver == SSL3_VERSION_MAJOR) {
2665
0
    switch(msg) {
2666
0
    case SSL3_MT_HELLO_REQUEST:
2667
0
      return "Hello request";
2668
0
    case SSL3_MT_CLIENT_HELLO:
2669
0
      return "Client hello";
2670
0
    case SSL3_MT_SERVER_HELLO:
2671
0
      return "Server hello";
2672
0
#ifdef SSL3_MT_NEWSESSION_TICKET
2673
0
    case SSL3_MT_NEWSESSION_TICKET:
2674
0
      return "Newsession Ticket";
2675
0
#endif
2676
0
    case SSL3_MT_CERTIFICATE:
2677
0
      return "Certificate";
2678
0
    case SSL3_MT_SERVER_KEY_EXCHANGE:
2679
0
      return "Server key exchange";
2680
0
    case SSL3_MT_CLIENT_KEY_EXCHANGE:
2681
0
      return "Client key exchange";
2682
0
    case SSL3_MT_CERTIFICATE_REQUEST:
2683
0
      return "Request CERT";
2684
0
    case SSL3_MT_SERVER_DONE:
2685
0
      return "Server finished";
2686
0
    case SSL3_MT_CERTIFICATE_VERIFY:
2687
0
      return "CERT verify";
2688
0
    case SSL3_MT_FINISHED:
2689
0
      return "Finished";
2690
0
#ifdef SSL3_MT_CERTIFICATE_STATUS
2691
0
    case SSL3_MT_CERTIFICATE_STATUS:
2692
0
      return "Certificate Status";
2693
0
#endif
2694
0
#ifdef SSL3_MT_ENCRYPTED_EXTENSIONS
2695
0
    case SSL3_MT_ENCRYPTED_EXTENSIONS:
2696
0
      return "Encrypted Extensions";
2697
0
#endif
2698
0
#ifdef SSL3_MT_SUPPLEMENTAL_DATA
2699
0
    case SSL3_MT_SUPPLEMENTAL_DATA:
2700
0
      return "Supplemental data";
2701
0
#endif
2702
0
#ifdef SSL3_MT_END_OF_EARLY_DATA
2703
0
    case SSL3_MT_END_OF_EARLY_DATA:
2704
0
      return "End of early data";
2705
0
#endif
2706
0
#ifdef SSL3_MT_KEY_UPDATE
2707
0
    case SSL3_MT_KEY_UPDATE:
2708
0
      return "Key update";
2709
0
#endif
2710
0
#ifdef SSL3_MT_NEXT_PROTO
2711
0
    case SSL3_MT_NEXT_PROTO:
2712
0
      return "Next protocol";
2713
0
#endif
2714
0
#ifdef SSL3_MT_MESSAGE_HASH
2715
0
    case SSL3_MT_MESSAGE_HASH:
2716
0
      return "Message hash";
2717
0
#endif
2718
0
    }
2719
0
  }
2720
0
  return "Unknown";
2721
0
}
2722
2723
static const char *tls_rt_type(int type)
2724
0
{
2725
0
  switch(type) {
2726
0
#ifdef SSL3_RT_HEADER
2727
0
  case SSL3_RT_HEADER:
2728
0
    return "TLS header";
2729
0
#endif
2730
0
  case SSL3_RT_CHANGE_CIPHER_SPEC:
2731
0
    return "TLS change cipher";
2732
0
  case SSL3_RT_ALERT:
2733
0
    return "TLS alert";
2734
0
  case SSL3_RT_HANDSHAKE:
2735
0
    return "TLS handshake";
2736
0
  case SSL3_RT_APPLICATION_DATA:
2737
0
    return "TLS app data";
2738
0
  default:
2739
0
    return "TLS Unknown";
2740
0
  }
2741
0
}
2742
2743
/*
2744
 * Our callback from the SSL/TLS layers.
2745
 */
2746
static void ossl_trace(int direction, int ssl_ver, int content_type,
2747
                       const void *buf, size_t len, SSL *ssl,
2748
                       void *userp)
2749
0
{
2750
0
  const char *verstr = "???";
2751
0
  struct Curl_cfilter *cf = userp;
2752
0
  struct Curl_easy *data = NULL;
2753
0
  char unknown[32];
2754
2755
0
  if(!cf)
2756
0
    return;
2757
0
  data = CF_DATA_CURRENT(cf);
2758
0
  if(!data || !data->set.fdebug || (direction && direction != 1))
2759
0
    return;
2760
2761
0
  switch(ssl_ver) {
2762
0
#ifdef SSL2_VERSION /* removed in recent versions */
2763
0
  case SSL2_VERSION:
2764
0
    verstr = "SSLv2";
2765
0
    break;
2766
0
#endif
2767
0
#ifdef SSL3_VERSION
2768
0
  case SSL3_VERSION:
2769
0
    verstr = "SSLv3";
2770
0
    break;
2771
0
#endif
2772
0
  case TLS1_VERSION:
2773
0
    verstr = "TLSv1.0";
2774
0
    break;
2775
0
#ifdef TLS1_1_VERSION
2776
0
  case TLS1_1_VERSION:
2777
0
    verstr = "TLSv1.1";
2778
0
    break;
2779
0
#endif
2780
0
#ifdef TLS1_2_VERSION
2781
0
  case TLS1_2_VERSION:
2782
0
    verstr = "TLSv1.2";
2783
0
    break;
2784
0
#endif
2785
0
#ifdef TLS1_3_VERSION
2786
0
  case TLS1_3_VERSION:
2787
0
    verstr = "TLSv1.3";
2788
0
    break;
2789
0
#endif
2790
0
  case 0:
2791
0
    break;
2792
0
  default:
2793
0
    msnprintf(unknown, sizeof(unknown), "(%x)", ssl_ver);
2794
0
    verstr = unknown;
2795
0
    break;
2796
0
  }
2797
2798
  /* Log progress for interesting records only (like Handshake or Alert), skip
2799
   * all raw record headers (content_type == SSL3_RT_HEADER or ssl_ver == 0).
2800
   * For TLS 1.3, skip notification of the decrypted inner Content-Type.
2801
   */
2802
0
  if(ssl_ver
2803
0
#ifdef SSL3_RT_HEADER
2804
0
     && content_type != SSL3_RT_HEADER
2805
0
#endif
2806
0
#ifdef SSL3_RT_INNER_CONTENT_TYPE
2807
0
     && content_type != SSL3_RT_INNER_CONTENT_TYPE
2808
0
#endif
2809
0
    ) {
2810
0
    const char *msg_name, *tls_rt_name;
2811
0
    char ssl_buf[1024];
2812
0
    int msg_type, txt_len;
2813
2814
    /* the info given when the version is zero is not that useful for us */
2815
2816
0
    ssl_ver >>= 8; /* check the upper 8 bits only below */
2817
2818
    /* SSLv2 does not seem to have TLS record-type headers, so OpenSSL
2819
     * always pass-up content-type as 0. But the interesting message-type
2820
     * is at 'buf[0]'.
2821
     */
2822
0
    if(ssl_ver == SSL3_VERSION_MAJOR && content_type)
2823
0
      tls_rt_name = tls_rt_type(content_type);
2824
0
    else
2825
0
      tls_rt_name = "";
2826
2827
0
    if(content_type == SSL3_RT_CHANGE_CIPHER_SPEC) {
2828
0
      msg_type = *(const char *)buf;
2829
0
      msg_name = "Change cipher spec";
2830
0
    }
2831
0
    else if(content_type == SSL3_RT_ALERT) {
2832
0
      msg_type = (((const char *)buf)[0] << 8) + ((const char *)buf)[1];
2833
0
      msg_name = SSL_alert_desc_string_long(msg_type);
2834
0
    }
2835
0
    else {
2836
0
      msg_type = *(const char *)buf;
2837
0
      msg_name = ssl_msg_type(ssl_ver, msg_type);
2838
0
    }
2839
2840
0
    txt_len = msnprintf(ssl_buf, sizeof(ssl_buf),
2841
0
                        "%s (%s), %s, %s (%d):\n",
2842
0
                        verstr, direction ? "OUT" : "IN",
2843
0
                        tls_rt_name, msg_name, msg_type);
2844
0
    Curl_debug(data, CURLINFO_TEXT, ssl_buf, (size_t)txt_len);
2845
0
  }
2846
2847
0
  Curl_debug(data, (direction == 1) ? CURLINFO_SSL_DATA_OUT :
2848
0
             CURLINFO_SSL_DATA_IN, (const char *)buf, len);
2849
0
  (void) ssl;
2850
0
}
2851
#endif
2852
2853
#ifdef USE_OPENSSL
2854
/* ====================================================== */
2855
2856
/* Check for ALPN support. */
2857
#ifndef OPENSSL_NO_TLSEXT
2858
#  define HAS_ALPN_OPENSSL
2859
#endif
2860
2861
#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) /* 1.1.0 */
2862
static CURLcode
2863
ossl_set_ssl_version_min_max(struct Curl_cfilter *cf, SSL_CTX *ctx)
2864
0
{
2865
0
  struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
2866
  /* first, TLS min version... */
2867
0
  long curl_ssl_version_min = conn_config->version;
2868
0
  long curl_ssl_version_max;
2869
2870
  /* convert curl min SSL version option to OpenSSL constant */
2871
#if (defined(OPENSSL_IS_BORINGSSL)  || \
2872
     defined(OPENSSL_IS_AWSLC)      || \
2873
     defined(LIBRESSL_VERSION_NUMBER))
2874
  uint16_t ossl_ssl_version_min = 0;
2875
  uint16_t ossl_ssl_version_max = 0;
2876
#else
2877
0
  long ossl_ssl_version_min = 0;
2878
0
  long ossl_ssl_version_max = 0;
2879
0
#endif
2880
0
  switch(curl_ssl_version_min) {
2881
0
  case CURL_SSLVERSION_TLSv1: /* TLS 1.x */
2882
0
  case CURL_SSLVERSION_TLSv1_0:
2883
0
    ossl_ssl_version_min = TLS1_VERSION;
2884
0
    break;
2885
0
  case CURL_SSLVERSION_TLSv1_1:
2886
0
    ossl_ssl_version_min = TLS1_1_VERSION;
2887
0
    break;
2888
0
  case CURL_SSLVERSION_TLSv1_2:
2889
0
    ossl_ssl_version_min = TLS1_2_VERSION;
2890
0
    break;
2891
0
  case CURL_SSLVERSION_TLSv1_3:
2892
0
#ifdef TLS1_3_VERSION
2893
0
    ossl_ssl_version_min = TLS1_3_VERSION;
2894
0
    break;
2895
#else
2896
    return CURLE_NOT_BUILT_IN;
2897
#endif
2898
0
  }
2899
2900
  /* CURL_SSLVERSION_DEFAULT means that no option was selected.
2901
     We do not want to pass 0 to SSL_CTX_set_min_proto_version as
2902
     it would enable all versions down to the lowest supported by
2903
     the library.
2904
     So we skip this, and stay with the library default
2905
  */
2906
0
  if(curl_ssl_version_min != CURL_SSLVERSION_DEFAULT) {
2907
0
    if(!SSL_CTX_set_min_proto_version(ctx, ossl_ssl_version_min)) {
2908
0
      return CURLE_SSL_CONNECT_ERROR;
2909
0
    }
2910
0
  }
2911
2912
  /* ... then, TLS max version */
2913
0
  curl_ssl_version_max = (long)conn_config->version_max;
2914
2915
  /* convert curl max SSL version option to OpenSSL constant */
2916
0
  switch(curl_ssl_version_max) {
2917
0
  case CURL_SSLVERSION_MAX_TLSv1_0:
2918
0
    ossl_ssl_version_max = TLS1_VERSION;
2919
0
    break;
2920
0
  case CURL_SSLVERSION_MAX_TLSv1_1:
2921
0
    ossl_ssl_version_max = TLS1_1_VERSION;
2922
0
    break;
2923
0
  case CURL_SSLVERSION_MAX_TLSv1_2:
2924
0
    ossl_ssl_version_max = TLS1_2_VERSION;
2925
0
    break;
2926
0
#ifdef TLS1_3_VERSION
2927
0
  case CURL_SSLVERSION_MAX_TLSv1_3:
2928
0
    ossl_ssl_version_max = TLS1_3_VERSION;
2929
0
    break;
2930
0
#endif
2931
0
  case CURL_SSLVERSION_MAX_NONE:  /* none selected */
2932
0
  case CURL_SSLVERSION_MAX_DEFAULT:  /* max selected */
2933
0
  default:
2934
    /* SSL_CTX_set_max_proto_version states that:
2935
       setting the maximum to 0 will enable
2936
       protocol versions up to the highest version
2937
       supported by the library */
2938
0
    ossl_ssl_version_max = 0;
2939
0
    break;
2940
0
  }
2941
2942
0
  if(!SSL_CTX_set_max_proto_version(ctx, ossl_ssl_version_max)) {
2943
0
    return CURLE_SSL_CONNECT_ERROR;
2944
0
  }
2945
2946
0
  return CURLE_OK;
2947
0
}
2948
#endif
2949
2950
#if defined(OPENSSL_IS_BORINGSSL) || defined(OPENSSL_IS_AWSLC)
2951
typedef uint32_t ctx_option_t;
2952
#elif OPENSSL_VERSION_NUMBER >= 0x30000000L
2953
typedef uint64_t ctx_option_t;
2954
#elif OPENSSL_VERSION_NUMBER >= 0x10100000L && \
2955
  !defined(LIBRESSL_VERSION_NUMBER)
2956
typedef unsigned long ctx_option_t;
2957
#else
2958
typedef long ctx_option_t;
2959
#endif
2960
2961
#if (OPENSSL_VERSION_NUMBER < 0x10100000L) /* 1.1.0 */
2962
static CURLcode
2963
ossl_set_ssl_version_min_max_legacy(ctx_option_t *ctx_options,
2964
                                    struct Curl_cfilter *cf,
2965
                                    struct Curl_easy *data)
2966
{
2967
  struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
2968
  long ssl_version = conn_config->version;
2969
  long ssl_version_max = conn_config->version_max;
2970
2971
  (void) data; /* In case it is unused. */
2972
2973
  switch(ssl_version) {
2974
  case CURL_SSLVERSION_TLSv1_3:
2975
#ifdef TLS1_3_VERSION
2976
  {
2977
    struct ssl_connect_data *connssl = cf->ctx;
2978
    struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend;
2979
    DEBUGASSERT(octx);
2980
    SSL_CTX_set_max_proto_version(octx->ssl_ctx, TLS1_3_VERSION);
2981
    *ctx_options |= SSL_OP_NO_TLSv1_2;
2982
  }
2983
#else
2984
  (void)ctx_options;
2985
  failf(data, OSSL_PACKAGE " was built without TLS 1.3 support");
2986
  return CURLE_NOT_BUILT_IN;
2987
#endif
2988
  FALLTHROUGH();
2989
  case CURL_SSLVERSION_TLSv1_2:
2990
    *ctx_options |= SSL_OP_NO_TLSv1_1;
2991
    FALLTHROUGH();
2992
  case CURL_SSLVERSION_TLSv1_1:
2993
    *ctx_options |= SSL_OP_NO_TLSv1;
2994
    FALLTHROUGH();
2995
  case CURL_SSLVERSION_TLSv1_0:
2996
  case CURL_SSLVERSION_TLSv1:
2997
    break;
2998
  }
2999
3000
  switch(ssl_version_max) {
3001
  case CURL_SSLVERSION_MAX_TLSv1_0:
3002
    *ctx_options |= SSL_OP_NO_TLSv1_1;
3003
    FALLTHROUGH();
3004
  case CURL_SSLVERSION_MAX_TLSv1_1:
3005
    *ctx_options |= SSL_OP_NO_TLSv1_2;
3006
    FALLTHROUGH();
3007
  case CURL_SSLVERSION_MAX_TLSv1_2:
3008
#ifdef TLS1_3_VERSION
3009
    *ctx_options |= SSL_OP_NO_TLSv1_3;
3010
#endif
3011
    break;
3012
  case CURL_SSLVERSION_MAX_TLSv1_3:
3013
#ifdef TLS1_3_VERSION
3014
    break;
3015
#else
3016
    failf(data, OSSL_PACKAGE " was built without TLS 1.3 support");
3017
    return CURLE_NOT_BUILT_IN;
3018
#endif
3019
  }
3020
  return CURLE_OK;
3021
}
3022
#endif
3023
3024
CURLcode Curl_ossl_add_session(struct Curl_cfilter *cf,
3025
                               struct Curl_easy *data,
3026
                               const char *ssl_peer_key,
3027
                               SSL_SESSION *session,
3028
                               int ietf_tls_id,
3029
                               const char *alpn,
3030
                               unsigned char *quic_tp,
3031
                               size_t quic_tp_len)
3032
0
{
3033
0
  const struct ssl_config_data *config;
3034
0
  unsigned char *der_session_buf = NULL;
3035
0
  unsigned char *qtp_clone = NULL;
3036
0
  CURLcode result = CURLE_OK;
3037
3038
0
  if(!cf || !data)
3039
0
    goto out;
3040
3041
0
  config = Curl_ssl_cf_get_config(cf, data);
3042
0
  if(config->primary.cache_session) {
3043
0
    struct Curl_ssl_session *sc_session = NULL;
3044
0
    size_t der_session_size;
3045
0
    unsigned char *der_session_ptr;
3046
0
    size_t earlydata_max = 0;
3047
3048
0
    der_session_size = i2d_SSL_SESSION(session, NULL);
3049
0
    if(der_session_size == 0) {
3050
0
      result = CURLE_OUT_OF_MEMORY;
3051
0
      goto out;
3052
0
    }
3053
3054
0
    der_session_buf = der_session_ptr = malloc(der_session_size);
3055
0
    if(!der_session_buf) {
3056
0
      result = CURLE_OUT_OF_MEMORY;
3057
0
      goto out;
3058
0
    }
3059
3060
0
    der_session_size = i2d_SSL_SESSION(session, &der_session_ptr);
3061
0
    if(der_session_size == 0) {
3062
0
      result = CURLE_OUT_OF_MEMORY;
3063
0
      goto out;
3064
0
    }
3065
3066
0
#ifdef HAVE_OPENSSL_EARLYDATA
3067
0
    earlydata_max = SSL_SESSION_get_max_early_data(session);
3068
0
#endif
3069
0
    if(quic_tp && quic_tp_len) {
3070
0
      qtp_clone = Curl_memdup0((char *)quic_tp, quic_tp_len);
3071
0
      if(!qtp_clone) {
3072
0
        result = CURLE_OUT_OF_MEMORY;
3073
0
        goto out;
3074
0
      }
3075
0
    }
3076
3077
0
    result = Curl_ssl_session_create2(der_session_buf, der_session_size,
3078
0
                                      ietf_tls_id, alpn,
3079
0
                                      (curl_off_t)time(NULL) +
3080
0
                                      SSL_SESSION_get_timeout(session),
3081
0
                                      earlydata_max, qtp_clone, quic_tp_len,
3082
0
                                      &sc_session);
3083
0
    der_session_buf = NULL;  /* took ownership of sdata */
3084
0
    if(!result) {
3085
0
      result = Curl_ssl_scache_put(cf, data, ssl_peer_key, sc_session);
3086
      /* took ownership of `sc_session` */
3087
0
    }
3088
0
  }
3089
3090
0
out:
3091
0
  free(der_session_buf);
3092
0
  return result;
3093
0
}
3094
3095
/* The "new session" callback must return zero if the session can be removed
3096
 * or non-zero if the session has been put into the session cache.
3097
 */
3098
static int ossl_new_session_cb(SSL *ssl, SSL_SESSION *ssl_sessionid)
3099
0
{
3100
0
  struct Curl_cfilter *cf = (struct Curl_cfilter*) SSL_get_app_data(ssl);
3101
0
  if(cf) {
3102
0
    struct Curl_easy *data = CF_DATA_CURRENT(cf);
3103
0
    struct ssl_connect_data *connssl = cf->ctx;
3104
0
    Curl_ossl_add_session(cf, data, connssl->peer.scache_key, ssl_sessionid,
3105
0
                          SSL_version(ssl), connssl->negotiated.alpn,
3106
0
                          NULL, 0);
3107
0
  }
3108
0
  return 0;
3109
0
}
3110
3111
static CURLcode load_cacert_from_memory(X509_STORE *store,
3112
                                        const struct curl_blob *ca_info_blob)
3113
0
{
3114
  /* these need to be freed at the end */
3115
0
  BIO *cbio = NULL;
3116
0
  STACK_OF(X509_INFO) *inf = NULL;
3117
3118
  /* everything else is just a reference */
3119
0
  int i, count = 0;
3120
0
  X509_INFO *itmp = NULL;
3121
3122
0
  if(ca_info_blob->len > (size_t)INT_MAX)
3123
0
    return CURLE_SSL_CACERT_BADFILE;
3124
3125
0
  cbio = BIO_new_mem_buf(ca_info_blob->data, (int)ca_info_blob->len);
3126
0
  if(!cbio)
3127
0
    return CURLE_OUT_OF_MEMORY;
3128
3129
0
  inf = PEM_X509_INFO_read_bio(cbio, NULL, NULL, NULL);
3130
0
  if(!inf) {
3131
0
    BIO_free(cbio);
3132
0
    return CURLE_SSL_CACERT_BADFILE;
3133
0
  }
3134
3135
  /* add each entry from PEM file to x509_store */
3136
0
  for(i = 0; i < (int)sk_X509_INFO_num(inf); ++i) {
3137
0
    itmp = sk_X509_INFO_value(inf, (ossl_valsize_t)i);
3138
0
    if(itmp->x509) {
3139
0
      if(X509_STORE_add_cert(store, itmp->x509)) {
3140
0
        ++count;
3141
0
      }
3142
0
      else {
3143
        /* set count to 0 to return an error */
3144
0
        count = 0;
3145
0
        break;
3146
0
      }
3147
0
    }
3148
0
    if(itmp->crl) {
3149
0
      if(X509_STORE_add_crl(store, itmp->crl)) {
3150
0
        ++count;
3151
0
      }
3152
0
      else {
3153
        /* set count to 0 to return an error */
3154
0
        count = 0;
3155
0
        break;
3156
0
      }
3157
0
    }
3158
0
  }
3159
3160
0
  sk_X509_INFO_pop_free(inf, X509_INFO_free);
3161
0
  BIO_free(cbio);
3162
3163
  /* if we did not end up importing anything, treat that as an error */
3164
0
  return (count > 0) ? CURLE_OK : CURLE_SSL_CACERT_BADFILE;
3165
0
}
3166
3167
#ifdef USE_WIN32_CRYPTO
3168
static CURLcode import_windows_cert_store(struct Curl_easy *data,
3169
                                          const char *name,
3170
                                          X509_STORE *store,
3171
                                          bool *imported)
3172
{
3173
  CURLcode result = CURLE_OK;
3174
  HCERTSTORE hStore;
3175
3176
  *imported = FALSE;
3177
3178
  hStore = CertOpenSystemStoreA(0, name);
3179
  if(hStore) {
3180
    PCCERT_CONTEXT pContext = NULL;
3181
    /* The array of enhanced key usage OIDs will vary per certificate and
3182
       is declared outside of the loop so that rather than malloc/free each
3183
       iteration we can grow it with realloc, when necessary. */
3184
    CERT_ENHKEY_USAGE *enhkey_usage = NULL;
3185
    DWORD enhkey_usage_size = 0;
3186
3187
    /* This loop makes a best effort to import all valid certificates from
3188
       the MS root store. If a certificate cannot be imported it is
3189
       skipped. 'result' is used to store only hard-fail conditions (such
3190
       as out of memory) that cause an early break. */
3191
    result = CURLE_OK;
3192
    for(;;) {
3193
      X509 *x509;
3194
      FILETIME now;
3195
      BYTE key_usage[2];
3196
      DWORD req_size;
3197
      const unsigned char *encoded_cert;
3198
      pContext = CertEnumCertificatesInStore(hStore, pContext);
3199
      if(!pContext)
3200
        break;
3201
3202
#if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
3203
      else {
3204
        char cert_name[256];
3205
        if(!CertGetNameStringA(pContext, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0,
3206
                               NULL, cert_name, sizeof(cert_name)))
3207
          infof(data, "SSL: unknown cert name");
3208
        else
3209
          infof(data, "SSL: Checking cert \"%s\"", cert_name);
3210
      }
3211
#endif
3212
      encoded_cert = (const unsigned char *)pContext->pbCertEncoded;
3213
      if(!encoded_cert)
3214
        continue;
3215
3216
      GetSystemTimeAsFileTime(&now);
3217
      if(CompareFileTime(&pContext->pCertInfo->NotBefore, &now) > 0 ||
3218
         CompareFileTime(&now, &pContext->pCertInfo->NotAfter) > 0)
3219
        continue;
3220
3221
      /* If key usage exists check for signing attribute */
3222
      if(CertGetIntendedKeyUsage(pContext->dwCertEncodingType,
3223
                                 pContext->pCertInfo,
3224
                                 key_usage, sizeof(key_usage))) {
3225
        if(!(key_usage[0] & CERT_KEY_CERT_SIGN_KEY_USAGE))
3226
          continue;
3227
      }
3228
      else if(GetLastError())
3229
        continue;
3230
3231
      /* If enhanced key usage exists check for server auth attribute.
3232
       *
3233
       * Note "In a Microsoft environment, a certificate might also have
3234
       * EKU extended properties that specify valid uses for the
3235
       * certificate."  The call below checks both, and behavior varies
3236
       * depending on what is found. For more details see
3237
       * CertGetEnhancedKeyUsage doc.
3238
       */
3239
      if(CertGetEnhancedKeyUsage(pContext, 0, NULL, &req_size)) {
3240
        if(req_size && req_size > enhkey_usage_size) {
3241
          void *tmp = realloc(enhkey_usage, req_size);
3242
3243
          if(!tmp) {
3244
            failf(data, "SSL: Out of memory allocating for OID list");
3245
            result = CURLE_OUT_OF_MEMORY;
3246
            break;
3247
          }
3248
3249
          enhkey_usage = (CERT_ENHKEY_USAGE *)tmp;
3250
          enhkey_usage_size = req_size;
3251
        }
3252
3253
        if(CertGetEnhancedKeyUsage(pContext, 0, enhkey_usage, &req_size)) {
3254
          if(!enhkey_usage->cUsageIdentifier) {
3255
            /* "If GetLastError returns CRYPT_E_NOT_FOUND, the certificate
3256
               is good for all uses. If it returns zero, the certificate
3257
               has no valid uses." */
3258
            if((HRESULT)GetLastError() != CRYPT_E_NOT_FOUND)
3259
              continue;
3260
          }
3261
          else {
3262
            DWORD i;
3263
            bool found = FALSE;
3264
3265
            for(i = 0; i < enhkey_usage->cUsageIdentifier; ++i) {
3266
              if(!strcmp("1.3.6.1.5.5.7.3.1" /* OID server auth */,
3267
                         enhkey_usage->rgpszUsageIdentifier[i])) {
3268
                found = TRUE;
3269
                break;
3270
              }
3271
            }
3272
3273
            if(!found)
3274
              continue;
3275
          }
3276
        }
3277
        else
3278
          continue;
3279
      }
3280
      else
3281
        continue;
3282
3283
      x509 = d2i_X509(NULL, &encoded_cert, (long)pContext->cbCertEncoded);
3284
      if(!x509)
3285
        continue;
3286
3287
      /* Try to import the certificate. This may fail for legitimate
3288
         reasons such as duplicate certificate, which is allowed by MS but
3289
         not OpenSSL. */
3290
      if(X509_STORE_add_cert(store, x509) == 1) {
3291
#if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
3292
        infof(data, "SSL: Imported cert");
3293
#endif
3294
        *imported = TRUE;
3295
      }
3296
      X509_free(x509);
3297
    }
3298
3299
    free(enhkey_usage);
3300
    CertFreeCertificateContext(pContext);
3301
    CertCloseStore(hStore, 0);
3302
3303
    if(result)
3304
      return result;
3305
  }
3306
3307
  return result;
3308
}
3309
#endif
3310
3311
static CURLcode ossl_populate_x509_store(struct Curl_cfilter *cf,
3312
                                         struct Curl_easy *data,
3313
                                         X509_STORE *store)
3314
0
{
3315
0
  struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
3316
0
  struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
3317
0
  CURLcode result = CURLE_OK;
3318
0
  X509_LOOKUP *lookup = NULL;
3319
0
  const struct curl_blob *ca_info_blob = conn_config->ca_info_blob;
3320
0
  const char * const ssl_cafile =
3321
    /* CURLOPT_CAINFO_BLOB overrides CURLOPT_CAINFO */
3322
0
    (ca_info_blob ? NULL : conn_config->CAfile);
3323
0
  const char * const ssl_capath = conn_config->CApath;
3324
0
  const char * const ssl_crlfile = ssl_config->primary.CRLfile;
3325
0
  const bool verifypeer = conn_config->verifypeer;
3326
0
  bool imported_native_ca = FALSE;
3327
0
  bool imported_ca_info_blob = FALSE;
3328
3329
0
  CURL_TRC_CF(data, cf, "ossl_populate_x509_store, path=%s, blob=%d",
3330
0
              ssl_cafile ? ssl_cafile : "none", !!ca_info_blob);
3331
0
  if(!store)
3332
0
    return CURLE_OUT_OF_MEMORY;
3333
3334
0
  if(verifypeer) {
3335
#ifdef USE_WIN32_CRYPTO
3336
    /* Import certificates from the Windows root certificate store if
3337
       requested.
3338
       https://stackoverflow.com/questions/9507184/
3339
       https://github.com/d3x0r/SACK/blob/master/src/netlib/ssl_layer.c#L1037
3340
       https://datatracker.ietf.org/doc/html/rfc5280 */
3341
    if(ssl_config->native_ca_store) {
3342
      const char *storeNames[] = {
3343
        "ROOT",   /* Trusted Root Certification Authorities */
3344
        "CA"      /* Intermediate Certification Authorities */
3345
      };
3346
      size_t i;
3347
      for(i = 0; i < CURL_ARRAYSIZE(storeNames); ++i) {
3348
        bool imported = FALSE;
3349
        result = import_windows_cert_store(data, storeNames[i], store,
3350
                                           &imported);
3351
        if(result)
3352
          return result;
3353
        if(imported) {
3354
          infof(data, "successfully imported Windows %s store", storeNames[i]);
3355
          imported_native_ca = TRUE;
3356
        }
3357
        else
3358
          infof(data, "error importing Windows %s store, continuing anyway",
3359
                storeNames[i]);
3360
      }
3361
    }
3362
#endif
3363
0
    if(ca_info_blob) {
3364
0
      result = load_cacert_from_memory(store, ca_info_blob);
3365
0
      if(result) {
3366
0
        failf(data, "error importing CA certificate blob");
3367
0
        return result;
3368
0
      }
3369
0
      else {
3370
0
        imported_ca_info_blob = TRUE;
3371
0
        infof(data, "successfully imported CA certificate blob");
3372
0
      }
3373
0
    }
3374
3375
0
    if(ssl_cafile || ssl_capath) {
3376
#if (OPENSSL_VERSION_NUMBER >= 0x30000000L)
3377
      /* OpenSSL 3.0.0 has deprecated SSL_CTX_load_verify_locations */
3378
      if(ssl_cafile && !X509_STORE_load_file(store, ssl_cafile)) {
3379
        if(!imported_native_ca && !imported_ca_info_blob) {
3380
          /* Fail if we insist on successfully verifying the server. */
3381
          failf(data, "error setting certificate file: %s", ssl_cafile);
3382
          return CURLE_SSL_CACERT_BADFILE;
3383
        }
3384
        else
3385
          infof(data, "error setting certificate file, continuing anyway");
3386
      }
3387
      if(ssl_capath && !X509_STORE_load_path(store, ssl_capath)) {
3388
        if(!imported_native_ca && !imported_ca_info_blob) {
3389
          /* Fail if we insist on successfully verifying the server. */
3390
          failf(data, "error setting certificate path: %s", ssl_capath);
3391
          return CURLE_SSL_CACERT_BADFILE;
3392
        }
3393
        else
3394
          infof(data, "error setting certificate path, continuing anyway");
3395
      }
3396
#else
3397
      /* tell OpenSSL where to find CA certificates that are used to verify the
3398
         server's certificate. */
3399
0
      if(!X509_STORE_load_locations(store, ssl_cafile, ssl_capath)) {
3400
0
        if(!imported_native_ca && !imported_ca_info_blob) {
3401
          /* Fail if we insist on successfully verifying the server. */
3402
0
          failf(data, "error setting certificate verify locations:"
3403
0
                "  CAfile: %s CApath: %s",
3404
0
                ssl_cafile ? ssl_cafile : "none",
3405
0
                ssl_capath ? ssl_capath : "none");
3406
0
          return CURLE_SSL_CACERT_BADFILE;
3407
0
        }
3408
0
        else {
3409
0
          infof(data, "error setting certificate verify locations,"
3410
0
                " continuing anyway");
3411
0
        }
3412
0
      }
3413
0
#endif
3414
0
      infof(data, " CAfile: %s", ssl_cafile ? ssl_cafile : "none");
3415
0
      infof(data, " CApath: %s", ssl_capath ? ssl_capath : "none");
3416
0
    }
3417
3418
#ifdef CURL_CA_FALLBACK
3419
    if(!ssl_cafile && !ssl_capath &&
3420
       !imported_native_ca && !imported_ca_info_blob) {
3421
      /* verifying the peer without any CA certificates will not
3422
         work so use OpenSSL's built-in default as fallback */
3423
      X509_STORE_set_default_paths(store);
3424
    }
3425
#endif
3426
0
  }
3427
3428
0
  if(ssl_crlfile) {
3429
    /* tell OpenSSL where to find CRL file that is used to check certificate
3430
     * revocation */
3431
0
    lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
3432
0
    if(!lookup ||
3433
0
       (!X509_load_crl_file(lookup, ssl_crlfile, X509_FILETYPE_PEM)) ) {
3434
0
      failf(data, "error loading CRL file: %s", ssl_crlfile);
3435
0
      return CURLE_SSL_CRL_BADFILE;
3436
0
    }
3437
    /* Everything is fine. */
3438
0
    infof(data, "successfully loaded CRL file:");
3439
0
    X509_STORE_set_flags(store,
3440
0
                         X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
3441
3442
0
    infof(data, "  CRLfile: %s", ssl_crlfile);
3443
0
  }
3444
3445
0
  if(verifypeer) {
3446
    /* Try building a chain using issuers in the trusted store first to avoid
3447
       problems with server-sent legacy intermediates. Newer versions of
3448
       OpenSSL do alternate chain checking by default but we do not know how to
3449
       determine that in a reliable manner.
3450
       https://web.archive.org/web/20190422050538/
3451
       rt.openssl.org/Ticket/Display.html?id=3621
3452
    */
3453
0
#ifdef X509_V_FLAG_TRUSTED_FIRST
3454
0
    X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
3455
0
#endif
3456
0
#ifdef X509_V_FLAG_PARTIAL_CHAIN
3457
0
    if(!ssl_config->no_partialchain && !ssl_crlfile) {
3458
      /* Have intermediate certificates in the trust store be treated as
3459
         trust-anchors, in the same way as self-signed root CA certificates
3460
         are. This allows users to verify servers using the intermediate cert
3461
         only, instead of needing the whole chain.
3462
3463
         Due to OpenSSL bug https://github.com/openssl/openssl/issues/5081 we
3464
         cannot do partial chains with a CRL check.
3465
      */
3466
0
      X509_STORE_set_flags(store, X509_V_FLAG_PARTIAL_CHAIN);
3467
0
    }
3468
0
#endif
3469
0
  }
3470
3471
0
  return result;
3472
0
}
3473
3474
#ifdef HAVE_SSL_X509_STORE_SHARE
3475
3476
/* key to use at `multi->proto_hash` */
3477
0
#define MPROTO_OSSL_X509_KEY   "tls:ossl:x509:share"
3478
3479
struct ossl_x509_share {
3480
  char *CAfile;         /* CAfile path used to generate X509 store */
3481
  X509_STORE *store;    /* cached X509 store or NULL if none */
3482
  struct curltime time; /* when the cached store was created */
3483
};
3484
3485
static void oss_x509_share_free(void *key, size_t key_len, void *p)
3486
0
{
3487
0
  struct ossl_x509_share *share = p;
3488
0
  DEBUGASSERT(key_len == (sizeof(MPROTO_OSSL_X509_KEY)-1));
3489
0
  DEBUGASSERT(!memcmp(MPROTO_OSSL_X509_KEY, key, key_len));
3490
0
  (void)key;
3491
0
  (void)key_len;
3492
0
  if(share->store) {
3493
0
    X509_STORE_free(share->store);
3494
0
  }
3495
0
  free(share->CAfile);
3496
0
  free(share);
3497
0
}
3498
3499
static bool
3500
ossl_cached_x509_store_expired(const struct Curl_easy *data,
3501
                               const struct ossl_x509_share *mb)
3502
0
{
3503
0
  const struct ssl_general_config *cfg = &data->set.general_ssl;
3504
0
  if(cfg->ca_cache_timeout < 0)
3505
0
    return FALSE;
3506
0
  else {
3507
0
    struct curltime now = curlx_now();
3508
0
    timediff_t elapsed_ms = curlx_timediff(now, mb->time);
3509
0
    timediff_t timeout_ms = cfg->ca_cache_timeout * (timediff_t)1000;
3510
3511
0
    return elapsed_ms >= timeout_ms;
3512
0
  }
3513
0
}
3514
3515
static bool
3516
ossl_cached_x509_store_different(struct Curl_cfilter *cf,
3517
                                 const struct ossl_x509_share *mb)
3518
0
{
3519
0
  struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
3520
0
  if(!mb->CAfile || !conn_config->CAfile)
3521
0
    return mb->CAfile != conn_config->CAfile;
3522
3523
0
  return strcmp(mb->CAfile, conn_config->CAfile);
3524
0
}
3525
3526
static X509_STORE *ossl_get_cached_x509_store(struct Curl_cfilter *cf,
3527
                                              const struct Curl_easy *data)
3528
0
{
3529
0
  struct Curl_multi *multi = data->multi;
3530
0
  struct ossl_x509_share *share;
3531
0
  X509_STORE *store = NULL;
3532
3533
0
  DEBUGASSERT(multi);
3534
0
  share = multi ? Curl_hash_pick(&multi->proto_hash,
3535
0
                                 CURL_UNCONST(MPROTO_OSSL_X509_KEY),
3536
0
                                 sizeof(MPROTO_OSSL_X509_KEY)-1) : NULL;
3537
0
  if(share && share->store &&
3538
0
     !ossl_cached_x509_store_expired(data, share) &&
3539
0
     !ossl_cached_x509_store_different(cf, share)) {
3540
0
    store = share->store;
3541
0
  }
3542
3543
0
  return store;
3544
0
}
3545
3546
static void ossl_set_cached_x509_store(struct Curl_cfilter *cf,
3547
                                       const struct Curl_easy *data,
3548
                                       X509_STORE *store)
3549
0
{
3550
0
  struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
3551
0
  struct Curl_multi *multi = data->multi;
3552
0
  struct ossl_x509_share *share;
3553
3554
0
  DEBUGASSERT(multi);
3555
0
  if(!multi)
3556
0
    return;
3557
0
  share = Curl_hash_pick(&multi->proto_hash,
3558
0
                         CURL_UNCONST(MPROTO_OSSL_X509_KEY),
3559
0
                         sizeof(MPROTO_OSSL_X509_KEY)-1);
3560
3561
0
  if(!share) {
3562
0
    share = calloc(1, sizeof(*share));
3563
0
    if(!share)
3564
0
      return;
3565
0
    if(!Curl_hash_add2(&multi->proto_hash,
3566
0
                       CURL_UNCONST(MPROTO_OSSL_X509_KEY),
3567
0
                       sizeof(MPROTO_OSSL_X509_KEY)-1,
3568
0
                       share, oss_x509_share_free)) {
3569
0
      free(share);
3570
0
      return;
3571
0
    }
3572
0
  }
3573
3574
0
  if(X509_STORE_up_ref(store)) {
3575
0
    char *CAfile = NULL;
3576
3577
0
    if(conn_config->CAfile) {
3578
0
      CAfile = strdup(conn_config->CAfile);
3579
0
      if(!CAfile) {
3580
0
        X509_STORE_free(store);
3581
0
        return;
3582
0
      }
3583
0
    }
3584
3585
0
    if(share->store) {
3586
0
      X509_STORE_free(share->store);
3587
0
      free(share->CAfile);
3588
0
    }
3589
3590
0
    share->time = curlx_now();
3591
0
    share->store = store;
3592
0
    share->CAfile = CAfile;
3593
0
  }
3594
0
}
3595
3596
CURLcode Curl_ssl_setup_x509_store(struct Curl_cfilter *cf,
3597
                                   struct Curl_easy *data,
3598
                                   SSL_CTX *ssl_ctx)
3599
0
{
3600
0
  struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
3601
0
  struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
3602
0
  CURLcode result = CURLE_OK;
3603
0
  X509_STORE *cached_store;
3604
0
  bool cache_criteria_met;
3605
3606
  /* Consider the X509 store cacheable if it comes exclusively from a CAfile,
3607
     or no source is provided and we are falling back to OpenSSL's built-in
3608
     default. */
3609
0
  cache_criteria_met = (data->set.general_ssl.ca_cache_timeout != 0) &&
3610
0
    conn_config->verifypeer &&
3611
0
    !conn_config->CApath &&
3612
0
    !conn_config->ca_info_blob &&
3613
0
    !ssl_config->primary.CRLfile &&
3614
0
    !ssl_config->native_ca_store;
3615
3616
0
  cached_store = ossl_get_cached_x509_store(cf, data);
3617
0
  if(cached_store && cache_criteria_met && X509_STORE_up_ref(cached_store)) {
3618
0
    SSL_CTX_set_cert_store(ssl_ctx, cached_store);
3619
0
  }
3620
0
  else {
3621
0
    X509_STORE *store = SSL_CTX_get_cert_store(ssl_ctx);
3622
3623
0
    result = ossl_populate_x509_store(cf, data, store);
3624
0
    if(result == CURLE_OK && cache_criteria_met) {
3625
0
      ossl_set_cached_x509_store(cf, data, store);
3626
0
    }
3627
0
  }
3628
3629
0
  return result;
3630
0
}
3631
#else /* HAVE_SSL_X509_STORE_SHARE */
3632
CURLcode Curl_ssl_setup_x509_store(struct Curl_cfilter *cf,
3633
                                   struct Curl_easy *data,
3634
                                   SSL_CTX *ssl_ctx)
3635
{
3636
  X509_STORE *store = SSL_CTX_get_cert_store(ssl_ctx);
3637
3638
  return ossl_populate_x509_store(cf, data, store);
3639
}
3640
#endif /* HAVE_SSL_X509_STORE_SHARE */
3641
3642
3643
static CURLcode
3644
ossl_init_session_and_alpns(struct ossl_ctx *octx,
3645
                            struct Curl_cfilter *cf,
3646
                            struct Curl_easy *data,
3647
                            struct ssl_peer *peer,
3648
                            const struct alpn_spec *alpns_requested,
3649
                            Curl_ossl_init_session_reuse_cb *sess_reuse_cb)
3650
0
{
3651
0
  struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
3652
0
  struct alpn_spec alpns;
3653
0
  char error_buffer[256];
3654
0
  CURLcode result;
3655
3656
0
  Curl_alpn_copy(&alpns, alpns_requested);
3657
3658
0
  octx->reused_session = FALSE;
3659
0
  if(ssl_config->primary.cache_session) {
3660
0
    struct Curl_ssl_session *scs = NULL;
3661
3662
0
    result = Curl_ssl_scache_take(cf, data, peer->scache_key, &scs);
3663
0
    if(!result && scs && scs->sdata && scs->sdata_len) {
3664
0
      const unsigned char *der_sessionid = scs->sdata;
3665
0
      size_t der_sessionid_size = scs->sdata_len;
3666
0
      SSL_SESSION *ssl_session = NULL;
3667
3668
      /* If OpenSSL does not accept the session from the cache, this
3669
       * is not an error. We just continue without it. */
3670
0
      ssl_session = d2i_SSL_SESSION(NULL, &der_sessionid,
3671
0
                                    (long)der_sessionid_size);
3672
0
      if(ssl_session) {
3673
0
        if(!SSL_set_session(octx->ssl, ssl_session)) {
3674
0
          infof(data, "SSL: SSL_set_session not accepted, "
3675
0
                "continuing without: %s",
3676
0
                ossl_strerror(ERR_get_error(), error_buffer,
3677
0
                              sizeof(error_buffer)));
3678
0
        }
3679
0
        else {
3680
0
          infof(data, "SSL reusing session with ALPN '%s'",
3681
0
                scs->alpn ? scs->alpn : "-");
3682
0
          octx->reused_session = TRUE;
3683
0
#ifdef HAVE_OPENSSL_EARLYDATA
3684
0
          if(ssl_config->earlydata && scs->alpn &&
3685
0
             SSL_SESSION_get_max_early_data(ssl_session) &&
3686
0
             !cf->conn->connect_only &&
3687
0
             (SSL_version(octx->ssl) == TLS1_3_VERSION)) {
3688
0
            bool do_early_data = FALSE;
3689
0
            if(sess_reuse_cb) {
3690
0
              result = sess_reuse_cb(cf, data, &alpns, scs, &do_early_data);
3691
0
              if(result)
3692
0
                return result;
3693
0
            }
3694
0
            if(do_early_data) {
3695
              /* We only try the ALPN protocol the session used before,
3696
               * otherwise we might send early data for the wrong protocol */
3697
0
              Curl_alpn_restrict_to(&alpns, scs->alpn);
3698
0
            }
3699
0
          }
3700
#else
3701
          (void)sess_reuse_cb;
3702
#endif
3703
0
        }
3704
0
        SSL_SESSION_free(ssl_session);
3705
0
      }
3706
0
      else {
3707
0
        infof(data, "SSL session not accepted by OpenSSL, continuing without");
3708
0
      }
3709
0
    }
3710
0
    Curl_ssl_scache_return(cf, data, peer->scache_key, scs);
3711
0
  }
3712
3713
0
#ifdef HAS_ALPN_OPENSSL
3714
0
  if(alpns.count) {
3715
0
    struct alpn_proto_buf proto;
3716
0
    memset(&proto, 0, sizeof(proto));
3717
0
    result = Curl_alpn_to_proto_buf(&proto, &alpns);
3718
0
    if(result) {
3719
0
      failf(data, "Error determining ALPN");
3720
0
      return CURLE_SSL_CONNECT_ERROR;
3721
0
    }
3722
0
    if(SSL_set_alpn_protos(octx->ssl, proto.data, (int)proto.len)) {
3723
0
      failf(data, "Error setting ALPN");
3724
0
      return CURLE_SSL_CONNECT_ERROR;
3725
0
    }
3726
0
  }
3727
0
#endif
3728
3729
0
  return CURLE_OK;
3730
0
}
3731
3732
#ifdef USE_ECH_OPENSSL
3733
static CURLcode ossl_init_ech(struct ossl_ctx *octx,
3734
                              struct Curl_cfilter *cf,
3735
                              struct Curl_easy *data,
3736
                              struct ssl_peer *peer)
3737
{
3738
  unsigned char *ech_config = NULL;
3739
  size_t ech_config_len = 0;
3740
  char *outername = data->set.str[STRING_ECH_PUBLIC];
3741
  int trying_ech_now = 0;
3742
  CURLcode result;
3743
3744
  if(!ECH_ENABLED(data))
3745
    return CURLE_OK;
3746
3747
  if(data->set.tls_ech & CURLECH_GREASE) {
3748
    infof(data, "ECH: will GREASE ClientHello");
3749
# if defined(OPENSSL_IS_BORINGSSL) || defined(OPENSSL_IS_AWSLC)
3750
    SSL_set_enable_ech_grease(octx->ssl, 1);
3751
# else
3752
    SSL_set_options(octx->ssl, SSL_OP_ECH_GREASE);
3753
# endif
3754
  }
3755
  else if(data->set.tls_ech & CURLECH_CLA_CFG) {
3756
# if defined(OPENSSL_IS_BORINGSSL) || defined(OPENSSL_IS_AWSLC)
3757
    /* have to do base64 decode here for BoringSSL */
3758
    const char *b64 = data->set.str[STRING_ECH_CONFIG];
3759
3760
    if(!b64) {
3761
      infof(data, "ECH: ECHConfig from command line empty");
3762
      return CURLE_SSL_CONNECT_ERROR;
3763
    }
3764
    ech_config_len = 2 * strlen(b64);
3765
    result = curlx_base64_decode(b64, &ech_config, &ech_config_len);
3766
    if(result || !ech_config) {
3767
      infof(data, "ECH: cannot base64 decode ECHConfig from command line");
3768
      if(data->set.tls_ech & CURLECH_HARD)
3769
        return result;
3770
    }
3771
    if(SSL_set1_ech_config_list(octx->ssl, ech_config,
3772
                                ech_config_len) != 1) {
3773
      infof(data, "ECH: SSL_ECH_set1_ech_config_list failed");
3774
      if(data->set.tls_ech & CURLECH_HARD) {
3775
        free(ech_config);
3776
        return CURLE_SSL_CONNECT_ERROR;
3777
      }
3778
    }
3779
    free(ech_config);
3780
    trying_ech_now = 1;
3781
# else
3782
    ech_config = (unsigned char *) data->set.str[STRING_ECH_CONFIG];
3783
    if(!ech_config) {
3784
      infof(data, "ECH: ECHConfig from command line empty");
3785
      return CURLE_SSL_CONNECT_ERROR;
3786
    }
3787
    ech_config_len = strlen(data->set.str[STRING_ECH_CONFIG]);
3788
    if(SSL_set1_ech_config_list(octx->ssl, ech_config,
3789
                                ech_config_len) != 1) {
3790
      infof(data, "ECH: SSL_ECH_set1_ech_config_list failed");
3791
      if(data->set.tls_ech & CURLECH_HARD)
3792
        return CURLE_SSL_CONNECT_ERROR;
3793
    }
3794
    else
3795
      trying_ech_now = 1;
3796
# endif
3797
    infof(data, "ECH: ECHConfig from command line");
3798
  }
3799
  else {
3800
    struct Curl_dns_entry *dns = NULL;
3801
3802
    if(peer->hostname)
3803
      dns = Curl_dnscache_get(data, peer->hostname, peer->port,
3804
                              cf->conn->ip_version);
3805
    if(!dns) {
3806
      infof(data, "ECH: requested but no DNS info available");
3807
      if(data->set.tls_ech & CURLECH_HARD)
3808
        return CURLE_SSL_CONNECT_ERROR;
3809
    }
3810
    else {
3811
      struct Curl_https_rrinfo *rinfo = NULL;
3812
3813
      rinfo = dns->hinfo;
3814
      if(rinfo && rinfo->echconfiglist) {
3815
        unsigned char *ecl = rinfo->echconfiglist;
3816
        size_t elen = rinfo->echconfiglist_len;
3817
3818
        infof(data, "ECH: ECHConfig from DoH HTTPS RR");
3819
        if(SSL_set1_ech_config_list(octx->ssl, ecl, elen) != 1) {
3820
          infof(data, "ECH: SSL_set1_ech_config_list failed");
3821
          if(data->set.tls_ech & CURLECH_HARD)
3822
            return CURLE_SSL_CONNECT_ERROR;
3823
        }
3824
        else {
3825
          trying_ech_now = 1;
3826
          infof(data, "ECH: imported ECHConfigList of length %zu", elen);
3827
        }
3828
      }
3829
      else {
3830
        infof(data, "ECH: requested but no ECHConfig available");
3831
        if(data->set.tls_ech & CURLECH_HARD)
3832
          return CURLE_SSL_CONNECT_ERROR;
3833
      }
3834
      Curl_resolv_unlink(data, &dns);
3835
    }
3836
  }
3837
# if defined(OPENSSL_IS_BORINGSSL) || defined(OPENSSL_IS_AWSLC)
3838
  if(trying_ech_now && outername) {
3839
    infof(data, "ECH: setting public_name not supported with BoringSSL");
3840
    return CURLE_SSL_CONNECT_ERROR;
3841
  }
3842
# else
3843
  if(trying_ech_now && outername) {
3844
    infof(data, "ECH: inner: '%s', outer: '%s'",
3845
          peer->hostname ? peer->hostname : "NULL", outername);
3846
    result = SSL_ech_set1_server_names(octx->ssl,
3847
                                      peer->hostname, outername,
3848
                                      0 /* do send outer */);
3849
    if(result != 1) {
3850
      infof(data, "ECH: rv failed to set server name(s) %d [ERROR]", result);
3851
      return CURLE_SSL_CONNECT_ERROR;
3852
    }
3853
  }
3854
# endif  /* OPENSSL_IS_BORINGSSL || OPENSSL_IS_AWSLC */
3855
  if(trying_ech_now
3856
     && SSL_set_min_proto_version(octx->ssl, TLS1_3_VERSION) != 1) {
3857
    infof(data, "ECH: cannot force TLSv1.3 [ERROR]");
3858
    return CURLE_SSL_CONNECT_ERROR;
3859
  }
3860
3861
  return CURLE_OK;
3862
}
3863
#endif /* USE_ECH_OPENSSL */
3864
3865
3866
static CURLcode ossl_init_ssl(struct ossl_ctx *octx,
3867
                              struct Curl_cfilter *cf,
3868
                              struct Curl_easy *data,
3869
                              struct ssl_peer *peer,
3870
                              const struct alpn_spec *alpns_requested,
3871
                              void *ssl_user_data,
3872
                              Curl_ossl_init_session_reuse_cb *sess_reuse_cb)
3873
0
{
3874
  /* Let's make an SSL structure */
3875
0
  if(octx->ssl)
3876
0
    SSL_free(octx->ssl);
3877
0
  octx->ssl = SSL_new(octx->ssl_ctx);
3878
0
  if(!octx->ssl) {
3879
0
    failf(data, "SSL: could not create a context (handle)");
3880
0
    return CURLE_OUT_OF_MEMORY;
3881
0
  }
3882
3883
0
  SSL_set_app_data(octx->ssl, ssl_user_data);
3884
3885
0
#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_OCSP)
3886
0
  if(Curl_ssl_cf_get_primary_config(cf)->verifystatus)
3887
0
    SSL_set_tlsext_status_type(octx->ssl, TLSEXT_STATUSTYPE_ocsp);
3888
0
#endif
3889
3890
#if (defined(OPENSSL_IS_BORINGSSL) || defined(OPENSSL_IS_AWSLC)) && \
3891
    defined(ALLOW_RENEG)
3892
  SSL_set_renegotiate_mode(octx->ssl, ssl_renegotiate_freely);
3893
#endif
3894
3895
0
  SSL_set_connect_state(octx->ssl);
3896
3897
0
  octx->server_cert = NULL;
3898
0
#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
3899
0
  if(peer->sni) {
3900
0
    if(!SSL_set_tlsext_host_name(octx->ssl, peer->sni)) {
3901
0
      failf(data, "Failed set SNI");
3902
0
      return CURLE_SSL_CONNECT_ERROR;
3903
0
    }
3904
0
  }
3905
3906
#ifdef USE_ECH_OPENSSL
3907
  {
3908
    CURLcode result = ossl_init_ech(octx, cf, data, peer);
3909
    if(result)
3910
      return result;
3911
  }
3912
#endif  /* USE_ECH_OPENSSL */
3913
3914
0
#endif
3915
3916
0
  return ossl_init_session_and_alpns(octx, cf, data, peer,
3917
0
                                     alpns_requested, sess_reuse_cb);
3918
0
}
3919
3920
3921
static CURLcode ossl_init_method(struct Curl_cfilter *cf,
3922
                                 struct Curl_easy *data,
3923
                                 struct ssl_peer *peer,
3924
                                 const SSL_METHOD **pmethod,
3925
                                 unsigned int *pssl_version_min)
3926
0
{
3927
0
  struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
3928
3929
0
  *pmethod = NULL;
3930
0
  *pssl_version_min = conn_config->version;
3931
0
  switch(peer->transport) {
3932
0
  case TRNSPRT_TCP:
3933
    /* check to see if we have been told to use an explicit SSL/TLS version */
3934
0
    switch(*pssl_version_min) {
3935
0
    case CURL_SSLVERSION_DEFAULT:
3936
0
    case CURL_SSLVERSION_TLSv1:
3937
0
    case CURL_SSLVERSION_TLSv1_0:
3938
0
    case CURL_SSLVERSION_TLSv1_1:
3939
0
    case CURL_SSLVERSION_TLSv1_2:
3940
0
    case CURL_SSLVERSION_TLSv1_3:
3941
      /* it will be handled later with the context options */
3942
0
  #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
3943
0
      *pmethod = TLS_client_method();
3944
  #else
3945
      *pmethod = SSLv23_client_method();
3946
  #endif
3947
0
      break;
3948
0
    case CURL_SSLVERSION_SSLv2:
3949
0
      failf(data, "No SSLv2 support");
3950
0
      return CURLE_NOT_BUILT_IN;
3951
0
    case CURL_SSLVERSION_SSLv3:
3952
0
      failf(data, "No SSLv3 support");
3953
0
      return CURLE_NOT_BUILT_IN;
3954
0
    default:
3955
0
      failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION");
3956
0
      return CURLE_SSL_CONNECT_ERROR;
3957
0
    }
3958
0
    break;
3959
0
  case TRNSPRT_QUIC:
3960
0
    *pssl_version_min = CURL_SSLVERSION_TLSv1_3;
3961
0
    if(conn_config->version_max &&
3962
0
       (conn_config->version_max != CURL_SSLVERSION_MAX_TLSv1_3)) {
3963
0
      failf(data, "QUIC needs at least TLS version 1.3");
3964
0
      return CURLE_SSL_CONNECT_ERROR;
3965
0
    }
3966
3967
#ifdef USE_OPENSSL_QUIC
3968
    *pmethod = OSSL_QUIC_client_method();
3969
#elif (OPENSSL_VERSION_NUMBER >= 0x10100000L)
3970
0
    *pmethod = TLS_method();
3971
#else
3972
    *pmethod = SSLv23_client_method();
3973
#endif
3974
0
    break;
3975
0
  default:
3976
0
    failf(data, "unsupported transport %d in SSL init", peer->transport);
3977
0
    return CURLE_SSL_CONNECT_ERROR;
3978
0
  }
3979
3980
0
  return *pmethod ? CURLE_OK : CURLE_SSL_CONNECT_ERROR;
3981
0
}
3982
3983
3984
CURLcode Curl_ossl_ctx_init(struct ossl_ctx *octx,
3985
                            struct Curl_cfilter *cf,
3986
                            struct Curl_easy *data,
3987
                            struct ssl_peer *peer,
3988
                            const struct alpn_spec *alpns_requested,
3989
                            Curl_ossl_ctx_setup_cb *cb_setup,
3990
                            void *cb_user_data,
3991
                            Curl_ossl_new_session_cb *cb_new_session,
3992
                            void *ssl_user_data,
3993
                            Curl_ossl_init_session_reuse_cb *sess_reuse_cb)
3994
0
{
3995
0
  CURLcode result = CURLE_OK;
3996
0
  const char *ciphers;
3997
0
  const SSL_METHOD *req_method = NULL;
3998
0
  ctx_option_t ctx_options = 0;
3999
0
  struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
4000
0
  struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
4001
0
  char * const ssl_cert = ssl_config->primary.clientcert;
4002
0
  const struct curl_blob *ssl_cert_blob = ssl_config->primary.cert_blob;
4003
0
  const char * const ssl_cert_type = ssl_config->cert_type;
4004
0
  const bool verifypeer = conn_config->verifypeer;
4005
0
  unsigned int ssl_version_min;
4006
0
  char error_buffer[256];
4007
4008
  /* Make funny stuff to get random input */
4009
0
  result = ossl_seed(data);
4010
0
  if(result)
4011
0
    return result;
4012
4013
0
  ssl_config->certverifyresult = !X509_V_OK;
4014
4015
0
  result = ossl_init_method(cf, data, peer, &req_method, &ssl_version_min);
4016
0
  if(result)
4017
0
    return result;
4018
0
  DEBUGASSERT(req_method);
4019
4020
0
  DEBUGASSERT(!octx->ssl_ctx);
4021
0
  octx->ssl_ctx =
4022
#ifdef OPENSSL_HAS_PROVIDERS
4023
    data->state.libctx ?
4024
    SSL_CTX_new_ex(data->state.libctx, data->state.propq, req_method):
4025
#endif
4026
0
    SSL_CTX_new(req_method);
4027
4028
0
  if(!octx->ssl_ctx) {
4029
0
    failf(data, "SSL: could not create a context: %s",
4030
0
          ossl_strerror(ERR_peek_error(), error_buffer, sizeof(error_buffer)));
4031
0
    return CURLE_OUT_OF_MEMORY;
4032
0
  }
4033
4034
0
  if(cb_setup) {
4035
0
    result = cb_setup(cf, data, cb_user_data);
4036
0
    if(result)
4037
0
      return result;
4038
0
  }
4039
4040
0
#ifdef SSL_CTRL_SET_MSG_CALLBACK
4041
0
  if(data->set.fdebug && data->set.verbose) {
4042
    /* the SSL trace callback is only used for verbose logging */
4043
0
    SSL_CTX_set_msg_callback(octx->ssl_ctx, ossl_trace);
4044
0
    SSL_CTX_set_msg_callback_arg(octx->ssl_ctx, cf);
4045
0
  }
4046
0
#endif
4047
4048
  /* OpenSSL contains code to work around lots of bugs and flaws in various
4049
     SSL-implementations. SSL_CTX_set_options() is used to enabled those
4050
     work-arounds. The manpage for this option states that SSL_OP_ALL enables
4051
     all the work-arounds and that "It is usually safe to use SSL_OP_ALL to
4052
     enable the bug workaround options if compatibility with somewhat broken
4053
     implementations is desired."
4054
4055
     The "-no_ticket" option was introduced in OpenSSL 0.9.8j. it is a flag to
4056
     disable "rfc4507bis session ticket support". rfc4507bis was later turned
4057
     into the proper RFC5077: https://datatracker.ietf.org/doc/html/rfc5077
4058
4059
     The enabled extension concerns the session management. I wonder how often
4060
     libcurl stops a connection and then resumes a TLS session. Also, sending
4061
     the session data is some overhead. I suggest that you just use your
4062
     proposed patch (which explicitly disables TICKET).
4063
4064
     If someone writes an application with libcurl and OpenSSL who wants to
4065
     enable the feature, one can do this in the SSL callback.
4066
4067
     SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG option enabling allowed proper
4068
     interoperability with web server Netscape Enterprise Server 2.0.1 which
4069
     was released back in 1996.
4070
4071
     Due to CVE-2010-4180, option SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG has
4072
     become ineffective as of OpenSSL 0.9.8q and 1.0.0c. In order to mitigate
4073
     CVE-2010-4180 when using previous OpenSSL versions we no longer enable
4074
     this option regardless of OpenSSL version and SSL_OP_ALL definition.
4075
4076
     OpenSSL added a work-around for an SSL 3.0/TLS 1.0 CBC vulnerability:
4077
     https://web.archive.org/web/20240114184648/openssl.org/~bodo/tls-cbc.txt.
4078
     In 0.9.6e they added a bit to SSL_OP_ALL that _disables_ that work-around
4079
     despite the fact that SSL_OP_ALL is documented to do "rather harmless"
4080
     workarounds. In order to keep the secure work-around, the
4081
     SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS bit must not be set.
4082
  */
4083
4084
0
  ctx_options = SSL_OP_ALL;
4085
4086
0
#ifdef SSL_OP_NO_TICKET
4087
0
  ctx_options |= SSL_OP_NO_TICKET;
4088
0
#endif
4089
4090
0
#ifdef SSL_OP_NO_COMPRESSION
4091
0
  ctx_options |= SSL_OP_NO_COMPRESSION;
4092
0
#endif
4093
4094
0
#ifdef SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
4095
  /* mitigate CVE-2010-4180 */
4096
0
  ctx_options &= ~(ctx_option_t)SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG;
4097
0
#endif
4098
4099
0
#ifdef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
4100
  /* unless the user explicitly asks to allow the protocol vulnerability we
4101
     use the work-around */
4102
0
  if(!ssl_config->enable_beast)
4103
0
    ctx_options &= ~(ctx_option_t)SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
4104
0
#endif
4105
4106
0
  switch(ssl_version_min) {
4107
0
  case CURL_SSLVERSION_SSLv2:
4108
0
  case CURL_SSLVERSION_SSLv3:
4109
0
    return CURLE_NOT_BUILT_IN;
4110
4111
    /* "--tlsv<x.y>" options mean TLS >= version <x.y> */
4112
0
  case CURL_SSLVERSION_DEFAULT:
4113
0
  case CURL_SSLVERSION_TLSv1: /* TLS >= version 1.0 */
4114
0
  case CURL_SSLVERSION_TLSv1_0: /* TLS >= version 1.0 */
4115
0
  case CURL_SSLVERSION_TLSv1_1: /* TLS >= version 1.1 */
4116
0
  case CURL_SSLVERSION_TLSv1_2: /* TLS >= version 1.2 */
4117
0
  case CURL_SSLVERSION_TLSv1_3: /* TLS >= version 1.3 */
4118
    /* asking for any TLS version as the minimum, means no SSL versions
4119
       allowed */
4120
0
    ctx_options |= SSL_OP_NO_SSLv2;
4121
0
    ctx_options |= SSL_OP_NO_SSLv3;
4122
4123
0
#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) /* 1.1.0 */
4124
0
    result = ossl_set_ssl_version_min_max(cf, octx->ssl_ctx);
4125
#else
4126
    result = ossl_set_ssl_version_min_max_legacy(&ctx_options, cf, data);
4127
#endif
4128
0
    if(result != CURLE_OK)
4129
0
      return result;
4130
0
    break;
4131
4132
0
  default:
4133
0
    failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION");
4134
0
    return CURLE_SSL_CONNECT_ERROR;
4135
0
  }
4136
4137
0
  SSL_CTX_set_options(octx->ssl_ctx, ctx_options);
4138
0
  SSL_CTX_set_read_ahead(octx->ssl_ctx, 1);
4139
4140
  /* Max TLS1.2 record size 0x4000 + 0x800.
4141
     OpenSSL supports processing "jumbo TLS record" (8 TLS records) in one go
4142
     for some algorithms, so match that here.
4143
     Experimentation shows that a slightly larger buffer is needed
4144
      to avoid short reads.
4145
4146
     However using a large buffer (8 packets) actually decreases performance.
4147
     4 packets is better.
4148
   */
4149
4150
0
#ifdef HAVE_SSL_CTX_SET_DEFAULT_READ_BUFFER_LEN
4151
0
  SSL_CTX_set_default_read_buffer_len(octx->ssl_ctx, 0x401e * 4);
4152
0
#endif
4153
4154
0
#ifdef SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER
4155
  /* We do retry writes sometimes from another buffer address */
4156
0
  SSL_CTX_set_mode(octx->ssl_ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
4157
0
#endif
4158
4159
0
  ciphers = conn_config->cipher_list;
4160
0
  if(!ciphers && (peer->transport != TRNSPRT_QUIC))
4161
0
    ciphers = DEFAULT_CIPHER_SELECTION;
4162
0
  if(ciphers && (ssl_version_min < CURL_SSLVERSION_TLSv1_3)) {
4163
0
    if(!SSL_CTX_set_cipher_list(octx->ssl_ctx, ciphers)) {
4164
0
      failf(data, "failed setting cipher list: %s", ciphers);
4165
0
      return CURLE_SSL_CIPHER;
4166
0
    }
4167
0
    infof(data, "Cipher selection: %s", ciphers);
4168
0
  }
4169
4170
0
#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
4171
0
  {
4172
0
    const char *ciphers13 = conn_config->cipher_list13;
4173
0
    if(ciphers13 &&
4174
0
       (!conn_config->version_max ||
4175
0
        (conn_config->version_max >= CURL_SSLVERSION_MAX_TLSv1_3))) {
4176
0
      if(!SSL_CTX_set_ciphersuites(octx->ssl_ctx, ciphers13)) {
4177
0
        failf(data, "failed setting TLS 1.3 cipher suite: %s", ciphers13);
4178
0
        return CURLE_SSL_CIPHER;
4179
0
      }
4180
0
      infof(data, "TLS 1.3 cipher selection: %s", ciphers13);
4181
0
    }
4182
0
  }
4183
0
#endif
4184
4185
0
  if(ssl_cert || ssl_cert_blob || ssl_cert_type) {
4186
0
    if(!result &&
4187
0
       !cert_stuff(data, octx->ssl_ctx,
4188
0
                   ssl_cert, ssl_cert_blob, ssl_cert_type,
4189
0
                   ssl_config->key, ssl_config->key_blob,
4190
0
                   ssl_config->key_type, ssl_config->key_passwd))
4191
0
      result = CURLE_SSL_CERTPROBLEM;
4192
0
    if(result)
4193
      /* failf() is already done in cert_stuff() */
4194
0
      return result;
4195
0
  }
4196
4197
0
#ifdef HAVE_SSL_CTX_SET_POST_HANDSHAKE_AUTH
4198
  /* OpenSSL 1.1.1 requires clients to opt-in for PHA */
4199
0
  SSL_CTX_set_post_handshake_auth(octx->ssl_ctx, 1);
4200
0
#endif
4201
4202
0
  {
4203
0
    const char *curves = conn_config->curves;
4204
0
    if(curves) {
4205
#if defined(OPENSSL_IS_BORINGSSL) || defined(OPENSSL_IS_AWSLC)
4206
#define OSSL_CURVE_CAST(x) (x)
4207
#else
4208
0
#define OSSL_CURVE_CAST(x) (char *)CURL_UNCONST(x)
4209
0
#endif
4210
0
      if(!SSL_CTX_set1_curves_list(octx->ssl_ctx, OSSL_CURVE_CAST(curves))) {
4211
0
        failf(data, "failed setting curves list: '%s'", curves);
4212
0
        return CURLE_SSL_CIPHER;
4213
0
      }
4214
0
    }
4215
0
  }
4216
4217
0
#ifdef HAVE_SSL_CTX_SET1_SIGALGS
4218
0
#define OSSL_SIGALG_CAST(x) OSSL_CURVE_CAST(x)
4219
0
  {
4220
0
    const char *signature_algorithms = conn_config->signature_algorithms;
4221
0
    if(signature_algorithms) {
4222
0
      if(!SSL_CTX_set1_sigalgs_list(octx->ssl_ctx,
4223
0
                                    OSSL_SIGALG_CAST(signature_algorithms))) {
4224
0
        failf(data, "failed setting signature algorithms: '%s'",
4225
0
              signature_algorithms);
4226
0
        return CURLE_SSL_CIPHER;
4227
0
      }
4228
0
    }
4229
0
  }
4230
0
#endif
4231
4232
0
#ifdef USE_OPENSSL_SRP
4233
0
  if(ssl_config->primary.username && Curl_auth_allowed_to_host(data)) {
4234
0
    char * const ssl_username = ssl_config->primary.username;
4235
0
    char * const ssl_password = ssl_config->primary.password;
4236
0
    infof(data, "Using TLS-SRP username: %s", ssl_username);
4237
4238
0
    if(!SSL_CTX_set_srp_username(octx->ssl_ctx, ssl_username)) {
4239
0
      failf(data, "Unable to set SRP username");
4240
0
      return CURLE_BAD_FUNCTION_ARGUMENT;
4241
0
    }
4242
0
    if(!SSL_CTX_set_srp_password(octx->ssl_ctx, ssl_password)) {
4243
0
      failf(data, "failed setting SRP password");
4244
0
      return CURLE_BAD_FUNCTION_ARGUMENT;
4245
0
    }
4246
0
    if(!conn_config->cipher_list) {
4247
0
      infof(data, "Setting cipher list SRP");
4248
4249
0
      if(!SSL_CTX_set_cipher_list(octx->ssl_ctx, "SRP")) {
4250
0
        failf(data, "failed setting SRP cipher list");
4251
0
        return CURLE_SSL_CIPHER;
4252
0
      }
4253
0
    }
4254
0
  }
4255
0
#endif
4256
4257
  /* OpenSSL always tries to verify the peer, this only says whether it should
4258
   * fail to connect if the verification fails, or if it should continue
4259
   * anyway. In the latter case the result of the verification is checked with
4260
   * SSL_get_verify_result() below. */
4261
0
  SSL_CTX_set_verify(octx->ssl_ctx,
4262
0
                     verifypeer ? SSL_VERIFY_PEER : SSL_VERIFY_NONE, NULL);
4263
4264
  /* Enable logging of secrets to the file specified in env SSLKEYLOGFILE. */
4265
0
#ifdef HAVE_KEYLOG_CALLBACK
4266
0
  if(Curl_tls_keylog_enabled()) {
4267
0
    SSL_CTX_set_keylog_callback(octx->ssl_ctx, ossl_keylog_callback);
4268
0
  }
4269
0
#endif
4270
4271
0
  if(cb_new_session) {
4272
    /* Enable the session cache because it is a prerequisite for the
4273
     * "new session" callback. Use the "external storage" mode to prevent
4274
     * OpenSSL from creating an internal session cache.
4275
     */
4276
0
    SSL_CTX_set_session_cache_mode(octx->ssl_ctx,
4277
0
                                   SSL_SESS_CACHE_CLIENT |
4278
0
                                   SSL_SESS_CACHE_NO_INTERNAL);
4279
0
    SSL_CTX_sess_set_new_cb(octx->ssl_ctx, cb_new_session);
4280
0
  }
4281
4282
  /* give application a chance to interfere with SSL set up. */
4283
0
  if(data->set.ssl.fsslctx) {
4284
    /* When a user callback is installed to modify the SSL_CTX,
4285
     * we need to do the full initialization before calling it.
4286
     * See: #11800 */
4287
0
    if(!octx->x509_store_setup) {
4288
0
      result = Curl_ssl_setup_x509_store(cf, data, octx->ssl_ctx);
4289
0
      if(result)
4290
0
        return result;
4291
0
      octx->x509_store_setup = TRUE;
4292
0
    }
4293
0
    Curl_set_in_callback(data, TRUE);
4294
0
    result = (*data->set.ssl.fsslctx)(data, octx->ssl_ctx,
4295
0
                                      data->set.ssl.fsslctxp);
4296
0
    Curl_set_in_callback(data, FALSE);
4297
0
    if(result) {
4298
0
      failf(data, "error signaled by ssl ctx callback");
4299
0
      return result;
4300
0
    }
4301
0
  }
4302
4303
0
  return ossl_init_ssl(octx, cf, data, peer, alpns_requested,
4304
0
                       ssl_user_data, sess_reuse_cb);
4305
0
}
4306
4307
static CURLcode ossl_on_session_reuse(struct Curl_cfilter *cf,
4308
                                      struct Curl_easy *data,
4309
                                      struct alpn_spec *alpns,
4310
                                      struct Curl_ssl_session *scs,
4311
                                      bool *do_early_data)
4312
0
{
4313
0
  struct ssl_connect_data *connssl = cf->ctx;
4314
0
  CURLcode result = CURLE_OK;
4315
4316
0
  *do_early_data = FALSE;
4317
0
  connssl->earlydata_max = scs->earlydata_max;
4318
0
  if(!connssl->earlydata_max) {
4319
0
    CURL_TRC_CF(data, cf, "SSL session does not allow earlydata");
4320
0
  }
4321
0
  else if(!Curl_alpn_contains_proto(alpns, scs->alpn)) {
4322
0
    CURL_TRC_CF(data, cf, "SSL session has different ALPN, no early data");
4323
0
  }
4324
0
  else {
4325
0
    infof(data, "SSL session allows %zu bytes of early data, "
4326
0
          "reusing ALPN '%s'", connssl->earlydata_max, scs->alpn);
4327
0
    connssl->earlydata_state = ssl_earlydata_await;
4328
0
    connssl->state = ssl_connection_deferred;
4329
0
    result = Curl_alpn_set_negotiated(cf, data, connssl,
4330
0
                    (const unsigned char *)scs->alpn,
4331
0
                    scs->alpn ? strlen(scs->alpn) : 0);
4332
0
    *do_early_data = !result;
4333
0
  }
4334
0
  return result;
4335
0
}
4336
4337
static CURLcode ossl_connect_step1(struct Curl_cfilter *cf,
4338
                                   struct Curl_easy *data)
4339
0
{
4340
0
  struct ssl_connect_data *connssl = cf->ctx;
4341
0
  struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend;
4342
0
  BIO *bio;
4343
0
  CURLcode result;
4344
4345
0
  DEBUGASSERT(ssl_connect_1 == connssl->connecting_state);
4346
0
  DEBUGASSERT(octx);
4347
4348
0
  result = Curl_ossl_ctx_init(octx, cf, data, &connssl->peer,
4349
0
                              connssl->alpn, NULL, NULL,
4350
0
                              ossl_new_session_cb, cf,
4351
0
                              ossl_on_session_reuse);
4352
0
  if(result)
4353
0
    return result;
4354
4355
0
  octx->bio_method = ossl_bio_cf_method_create();
4356
0
  if(!octx->bio_method)
4357
0
    return CURLE_OUT_OF_MEMORY;
4358
0
  bio = BIO_new(octx->bio_method);
4359
0
  if(!bio)
4360
0
    return CURLE_OUT_OF_MEMORY;
4361
4362
0
  BIO_set_data(bio, cf);
4363
0
#ifdef HAVE_SSL_SET0_WBIO
4364
  /* with OpenSSL v1.1.1 we get an alternative to SSL_set_bio() that works
4365
   * without backward compat quirks. Every call takes one reference, so we
4366
   * up it and pass. SSL* then owns it and will free.
4367
   * We check on the function in configure, since LibreSSL and friends
4368
   * each have their own versions to add support for this. */
4369
0
  BIO_up_ref(bio);
4370
0
  SSL_set0_rbio(octx->ssl, bio);
4371
0
  SSL_set0_wbio(octx->ssl, bio);
4372
#else
4373
  SSL_set_bio(octx->ssl, bio, bio);
4374
#endif
4375
4376
0
#ifdef HAS_ALPN_OPENSSL
4377
0
  if(connssl->alpn && (connssl->state != ssl_connection_deferred)) {
4378
0
    struct alpn_proto_buf proto;
4379
0
    memset(&proto, 0, sizeof(proto));
4380
0
    Curl_alpn_to_proto_str(&proto, connssl->alpn);
4381
0
    infof(data, VTLS_INFOF_ALPN_OFFER_1STR, proto.data);
4382
0
  }
4383
0
#endif
4384
0
  connssl->connecting_state = ssl_connect_2;
4385
0
  return CURLE_OK;
4386
0
}
4387
4388
#ifdef USE_ECH_OPENSSL
4389
/* If we have retry configs, then trace those out */
4390
static void ossl_trace_ech_retry_configs(struct Curl_easy *data, SSL* ssl,
4391
                                         int reason)
4392
{
4393
  CURLcode result = CURLE_OK;
4394
  size_t rcl = 0;
4395
  int rv = 1;
4396
# if !defined(OPENSSL_IS_BORINGSSL) && !defined(OPENSSL_IS_AWSLC)
4397
  char *inner = NULL;
4398
  unsigned char *rcs = NULL;
4399
  char *outer = NULL;
4400
# else
4401
  const char *inner = NULL;
4402
  const uint8_t *rcs = NULL;
4403
  const char *outer = NULL;
4404
  size_t out_name_len = 0;
4405
  int servername_type = 0;
4406
# endif
4407
4408
  /* nothing to trace if not doing ECH */
4409
  if(!ECH_ENABLED(data))
4410
    return;
4411
# if !defined(OPENSSL_IS_BORINGSSL) && !defined(OPENSSL_IS_AWSLC)
4412
  rv = SSL_ech_get1_retry_config(ssl, &rcs, &rcl);
4413
# else
4414
  SSL_get0_ech_retry_configs(ssl, &rcs, &rcl);
4415
  rv = (int)rcl;
4416
# endif
4417
4418
  if(rv && rcs) {
4419
    char *b64str = NULL;
4420
    size_t blen = 0;
4421
4422
    result = curlx_base64_encode((const char *)rcs, rcl, &b64str, &blen);
4423
    if(!result && b64str) {
4424
      infof(data, "ECH: retry_configs %s", b64str);
4425
      free(b64str);
4426
#if !defined(OPENSSL_IS_BORINGSSL) && !defined(OPENSSL_IS_AWSLC)
4427
      rv = SSL_ech_get1_status(ssl, &inner, &outer);
4428
      infof(data, "ECH: retry_configs for %s from %s, %d %d",
4429
            inner ? inner : "NULL", outer ? outer : "NULL", reason, rv);
4430
#else
4431
      rv = SSL_ech_accepted(ssl);
4432
      servername_type = SSL_get_servername_type(ssl);
4433
      inner = SSL_get_servername(ssl, servername_type);
4434
      SSL_get0_ech_name_override(ssl, &outer, &out_name_len);
4435
      infof(data, "ECH: retry_configs for %s from %s, %d %d",
4436
            inner ? inner : "NULL", outer ? outer : "NULL", reason, rv);
4437
#endif
4438
    }
4439
  }
4440
  else
4441
    infof(data, "ECH: no retry_configs (rv = %d)", rv);
4442
# if !defined(OPENSSL_IS_BORINGSSL) && !defined(OPENSSL_IS_AWSLC)
4443
  OPENSSL_free((void *)rcs);
4444
# endif
4445
  return;
4446
}
4447
4448
#endif
4449
4450
static CURLcode ossl_connect_step2(struct Curl_cfilter *cf,
4451
                                   struct Curl_easy *data)
4452
0
{
4453
0
  int err;
4454
0
  struct ssl_connect_data *connssl = cf->ctx;
4455
0
  struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend;
4456
0
  struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
4457
0
  DEBUGASSERT(ssl_connect_2 == connssl->connecting_state);
4458
0
  DEBUGASSERT(octx);
4459
4460
0
  connssl->io_need = CURL_SSL_IO_NEED_NONE;
4461
0
  ERR_clear_error();
4462
4463
0
  err = SSL_connect(octx->ssl);
4464
4465
0
  if(!octx->x509_store_setup) {
4466
    /* After having send off the ClientHello, we prepare the x509
4467
     * store to verify the coming certificate from the server */
4468
0
    CURLcode result = Curl_ssl_setup_x509_store(cf, data, octx->ssl_ctx);
4469
0
    if(result)
4470
0
      return result;
4471
0
    octx->x509_store_setup = TRUE;
4472
0
  }
4473
4474
#ifndef HAVE_KEYLOG_CALLBACK
4475
  /* If key logging is enabled, wait for the handshake to complete and then
4476
   * proceed with logging secrets (for TLS 1.2 or older).
4477
   */
4478
  if(Curl_tls_keylog_enabled() && !octx->keylog_done)
4479
    ossl_log_tls12_secret(octx->ssl, &octx->keylog_done);
4480
#endif
4481
4482
  /* 1  is fine
4483
     0  is "not successful but was shut down controlled"
4484
     <0 is "handshake was not successful, because a fatal error occurred" */
4485
0
  if(1 != err) {
4486
0
    int detail = SSL_get_error(octx->ssl, err);
4487
0
    CURL_TRC_CF(data, cf, "SSL_connect() -> err=%d, detail=%d", err, detail);
4488
4489
0
    if(SSL_ERROR_WANT_READ == detail) {
4490
0
      CURL_TRC_CF(data, cf, "SSL_connect() -> want recv");
4491
0
      connssl->io_need = CURL_SSL_IO_NEED_RECV;
4492
0
      return CURLE_AGAIN;
4493
0
    }
4494
0
    if(SSL_ERROR_WANT_WRITE == detail) {
4495
0
      CURL_TRC_CF(data, cf, "SSL_connect() -> want send");
4496
0
      connssl->io_need = CURL_SSL_IO_NEED_SEND;
4497
0
      return CURLE_AGAIN;
4498
0
    }
4499
0
#ifdef SSL_ERROR_WANT_ASYNC
4500
0
    if(SSL_ERROR_WANT_ASYNC == detail) {
4501
0
      CURL_TRC_CF(data, cf, "SSL_connect() -> want async");
4502
0
      connssl->io_need = CURL_SSL_IO_NEED_RECV;
4503
0
      return CURLE_AGAIN;
4504
0
    }
4505
0
#endif
4506
#ifdef SSL_ERROR_WANT_RETRY_VERIFY
4507
    if(SSL_ERROR_WANT_RETRY_VERIFY == detail) {
4508
      CURL_TRC_CF(data, cf, "SSL_connect() -> want retry_verify");
4509
      connssl->io_need = CURL_SSL_IO_NEED_RECV;
4510
      return CURLE_AGAIN;
4511
    }
4512
#endif
4513
0
    else {
4514
      /* untreated error */
4515
0
      sslerr_t errdetail;
4516
0
      char error_buffer[256]="";
4517
0
      CURLcode result;
4518
0
      long lerr;
4519
0
      int lib;
4520
0
      int reason;
4521
4522
      /* the connection failed, we are not waiting for anything else. */
4523
0
      connssl->connecting_state = ssl_connect_2;
4524
4525
      /* Get the earliest error code from the thread's error queue and remove
4526
         the entry. */
4527
0
      errdetail = ERR_get_error();
4528
4529
      /* Extract which lib and reason */
4530
0
      lib = ERR_GET_LIB(errdetail);
4531
0
      reason = ERR_GET_REASON(errdetail);
4532
4533
0
      if((lib == ERR_LIB_SSL) &&
4534
0
         ((reason == SSL_R_CERTIFICATE_VERIFY_FAILED) ||
4535
0
          (reason == SSL_R_SSLV3_ALERT_CERTIFICATE_EXPIRED))) {
4536
0
        result = CURLE_PEER_FAILED_VERIFICATION;
4537
4538
0
        lerr = SSL_get_verify_result(octx->ssl);
4539
0
        if(lerr != X509_V_OK) {
4540
0
          ssl_config->certverifyresult = lerr;
4541
0
          failf(data, "SSL certificate problem: %s",
4542
0
                X509_verify_cert_error_string(lerr));
4543
0
        }
4544
0
        else
4545
0
          failf(data, "%s", "SSL certificate verification failed");
4546
0
      }
4547
0
#ifdef SSL_R_TLSV13_ALERT_CERTIFICATE_REQUIRED
4548
      /* SSL_R_TLSV13_ALERT_CERTIFICATE_REQUIRED is only available on
4549
         OpenSSL version above v1.1.1, not LibreSSL, BoringSSL, or AWS-LC */
4550
0
      else if((lib == ERR_LIB_SSL) &&
4551
0
              (reason == SSL_R_TLSV13_ALERT_CERTIFICATE_REQUIRED)) {
4552
        /* If client certificate is required, communicate the
4553
           error to client */
4554
0
        result = CURLE_SSL_CLIENTCERT;
4555
0
        failf(data, "TLS cert problem: %s",
4556
0
              ossl_strerror(errdetail, error_buffer, sizeof(error_buffer)));
4557
0
      }
4558
0
#endif
4559
#ifdef USE_ECH_OPENSSL
4560
      else if((lib == ERR_LIB_SSL) &&
4561
# if !defined(OPENSSL_IS_BORINGSSL) && !defined(OPENSSL_IS_AWSLC)
4562
              (reason == SSL_R_ECH_REQUIRED)) {
4563
# else
4564
              (reason == SSL_R_ECH_REJECTED)) {
4565
# endif
4566
4567
        /* trace retry_configs if we got some */
4568
        ossl_trace_ech_retry_configs(data, octx->ssl, reason);
4569
4570
        result = CURLE_ECH_REQUIRED;
4571
        failf(data, "ECH required: %s",
4572
              ossl_strerror(errdetail, error_buffer, sizeof(error_buffer)));
4573
      }
4574
#endif
4575
0
      else {
4576
0
        result = CURLE_SSL_CONNECT_ERROR;
4577
0
        failf(data, "TLS connect error: %s",
4578
0
              ossl_strerror(errdetail, error_buffer, sizeof(error_buffer)));
4579
0
      }
4580
4581
      /* detail is already set to the SSL error above */
4582
4583
      /* If we e.g. use SSLv2 request-method and the server does not like us
4584
       * (RST connection, etc.), OpenSSL gives no explanation whatsoever and
4585
       * the SO_ERROR is also lost.
4586
       */
4587
0
      if(CURLE_SSL_CONNECT_ERROR == result && errdetail == 0) {
4588
0
        char extramsg[80]="";
4589
0
        int sockerr = SOCKERRNO;
4590
4591
0
        if(sockerr && detail == SSL_ERROR_SYSCALL)
4592
0
          Curl_strerror(sockerr, extramsg, sizeof(extramsg));
4593
0
        failf(data, OSSL_PACKAGE " SSL_connect: %s in connection to %s:%d ",
4594
0
              extramsg[0] ? extramsg : SSL_ERROR_to_str(detail),
4595
0
              connssl->peer.hostname, connssl->peer.port);
4596
0
      }
4597
4598
0
      return result;
4599
0
    }
4600
0
  }
4601
0
  else {
4602
0
    int psigtype_nid = NID_undef;
4603
0
    const char *negotiated_group_name = NULL;
4604
4605
    /* we connected fine, we are not waiting for anything else. */
4606
0
    connssl->connecting_state = ssl_connect_3;
4607
4608
#if (OPENSSL_VERSION_NUMBER >= 0x30000000L)
4609
    SSL_get_peer_signature_type_nid(octx->ssl, &psigtype_nid);
4610
#if (OPENSSL_VERSION_NUMBER >= 0x30200000L)
4611
    negotiated_group_name = SSL_get0_group_name(octx->ssl);
4612
#else
4613
    negotiated_group_name =
4614
      OBJ_nid2sn(SSL_get_negotiated_group(octx->ssl) & 0x0000FFFF);
4615
#endif
4616
#endif
4617
4618
    /* Informational message */
4619
0
    infof(data, "SSL connection using %s / %s / %s / %s",
4620
0
          SSL_get_version(octx->ssl),
4621
0
          SSL_get_cipher(octx->ssl),
4622
0
          negotiated_group_name ? negotiated_group_name : "[blank]",
4623
0
          OBJ_nid2sn(psigtype_nid));
4624
4625
#ifdef USE_ECH_OPENSSL
4626
# if !defined(OPENSSL_IS_BORINGSSL) && !defined(OPENSSL_IS_AWSLC)
4627
    if(ECH_ENABLED(data)) {
4628
      char *inner = NULL, *outer = NULL;
4629
      const char *status = NULL;
4630
      int rv;
4631
4632
      rv = SSL_ech_get1_status(octx->ssl, &inner, &outer);
4633
      switch(rv) {
4634
      case SSL_ECH_STATUS_SUCCESS:
4635
        status = "succeeded";
4636
        break;
4637
      case SSL_ECH_STATUS_GREASE_ECH:
4638
        status = "sent GREASE, got retry-configs";
4639
        break;
4640
      case SSL_ECH_STATUS_GREASE:
4641
        status = "sent GREASE";
4642
        break;
4643
      case SSL_ECH_STATUS_NOT_TRIED:
4644
        status = "not attempted";
4645
        break;
4646
      case SSL_ECH_STATUS_NOT_CONFIGURED:
4647
        status = "not configured";
4648
        break;
4649
      case SSL_ECH_STATUS_BACKEND:
4650
        status = "backend (unexpected)";
4651
        break;
4652
      case SSL_ECH_STATUS_FAILED:
4653
        status = "failed";
4654
        break;
4655
      case SSL_ECH_STATUS_BAD_CALL:
4656
        status = "bad call (unexpected)";
4657
        break;
4658
      case SSL_ECH_STATUS_BAD_NAME:
4659
        status = "bad name (unexpected)";
4660
        break;
4661
      default:
4662
        status = "unexpected status";
4663
        infof(data, "ECH: unexpected status %d",rv);
4664
      }
4665
      infof(data, "ECH: result: status is %s, inner is %s, outer is %s",
4666
            (status ? status : "NULL"),
4667
            (inner ? inner : "NULL"),
4668
            (outer ? outer : "NULL"));
4669
      OPENSSL_free(inner);
4670
      OPENSSL_free(outer);
4671
      if(rv == SSL_ECH_STATUS_GREASE_ECH) {
4672
        /* trace retry_configs if we got some */
4673
        ossl_trace_ech_retry_configs(data, octx->ssl, 0);
4674
      }
4675
      if(rv != SSL_ECH_STATUS_SUCCESS
4676
         && data->set.tls_ech & CURLECH_HARD) {
4677
        infof(data, "ECH: ech-hard failed");
4678
        return CURLE_SSL_CONNECT_ERROR;
4679
      }
4680
   }
4681
   else {
4682
      infof(data, "ECH: result: status is not attempted");
4683
   }
4684
# endif  /* !OPENSSL_IS_BORINGSSL && !OPENSSL_IS_AWSLC */
4685
#endif  /* USE_ECH_OPENSSL */
4686
4687
0
#ifdef HAS_ALPN_OPENSSL
4688
    /* Sets data and len to negotiated protocol, len is 0 if no protocol was
4689
     * negotiated
4690
     */
4691
0
    if(connssl->alpn) {
4692
0
      const unsigned char *neg_protocol;
4693
0
      unsigned int len;
4694
0
      SSL_get0_alpn_selected(octx->ssl, &neg_protocol, &len);
4695
4696
0
      return Curl_alpn_set_negotiated(cf, data, connssl, neg_protocol, len);
4697
0
    }
4698
0
#endif
4699
4700
0
    return CURLE_OK;
4701
0
  }
4702
0
}
4703
4704
/*
4705
 * Heavily modified from:
4706
 * https://www.owasp.org/index.php/Certificate_and_Public_Key_Pinning#OpenSSL
4707
 */
4708
static CURLcode ossl_pkp_pin_peer_pubkey(struct Curl_easy *data, X509* cert,
4709
                                         const char *pinnedpubkey)
4710
0
{
4711
  /* Scratch */
4712
0
  int len1 = 0, len2 = 0;
4713
0
  unsigned char *buff1 = NULL, *temp = NULL;
4714
4715
  /* Result is returned to caller */
4716
0
  CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH;
4717
4718
  /* if a path was not specified, do not pin */
4719
0
  if(!pinnedpubkey)
4720
0
    return CURLE_OK;
4721
4722
0
  if(!cert)
4723
0
    return result;
4724
4725
0
  do {
4726
    /* Begin Gyrations to get the subjectPublicKeyInfo     */
4727
    /* Thanks to Viktor Dukhovni on the OpenSSL mailing list */
4728
4729
    /* https://groups.google.com/group/mailing.openssl.users/browse_thread
4730
       /thread/d61858dae102c6c7 */
4731
0
    len1 = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), NULL);
4732
0
    if(len1 < 1)
4733
0
      break; /* failed */
4734
4735
0
    buff1 = temp = malloc(len1);
4736
0
    if(!buff1)
4737
0
      break; /* failed */
4738
4739
    /* https://docs.openssl.org/master/man3/d2i_X509/ */
4740
0
    len2 = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), &temp);
4741
4742
    /*
4743
     * These checks are verifying we got back the same values as when we
4744
     * sized the buffer. it is pretty weak since they should always be the
4745
     * same. But it gives us something to test.
4746
     */
4747
0
    if((len1 != len2) || !temp || ((temp - buff1) != len1))
4748
0
      break; /* failed */
4749
4750
    /* End Gyrations */
4751
4752
    /* The one good exit point */
4753
0
    result = Curl_pin_peer_pubkey(data, pinnedpubkey, buff1, len1);
4754
0
  } while(0);
4755
4756
0
  if(buff1)
4757
0
    free(buff1);
4758
4759
0
  return result;
4760
0
}
4761
4762
#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) &&  \
4763
  !(defined(LIBRESSL_VERSION_NUMBER) && \
4764
    LIBRESSL_VERSION_NUMBER < 0x3060000fL) && \
4765
  !defined(OPENSSL_IS_BORINGSSL) && \
4766
  !defined(OPENSSL_IS_AWSLC) && \
4767
  !defined(CURL_DISABLE_VERBOSE_STRINGS)
4768
static void infof_certstack(struct Curl_easy *data, const SSL *ssl)
4769
0
{
4770
0
  STACK_OF(X509) *certstack;
4771
0
  long verify_result;
4772
0
  int num_cert_levels;
4773
0
  int cert_level;
4774
4775
0
  verify_result = SSL_get_verify_result(ssl);
4776
0
  if(verify_result != X509_V_OK)
4777
0
    certstack = SSL_get_peer_cert_chain(ssl);
4778
0
  else
4779
0
    certstack = SSL_get0_verified_chain(ssl);
4780
0
  num_cert_levels = sk_X509_num(certstack);
4781
4782
0
  for(cert_level = 0; cert_level < num_cert_levels; cert_level++) {
4783
0
    char cert_algorithm[80] = "";
4784
0
    char group_name_final[80] = "";
4785
0
    const X509_ALGOR *palg_cert = NULL;
4786
0
    const ASN1_OBJECT *paobj_cert = NULL;
4787
0
    X509 *current_cert;
4788
0
    EVP_PKEY *current_pkey;
4789
0
    int key_bits;
4790
0
    int key_sec_bits;
4791
0
    int get_group_name;
4792
0
    const char *type_name;
4793
4794
0
    current_cert = sk_X509_value(certstack, cert_level);
4795
4796
0
    X509_get0_signature(NULL, &palg_cert, current_cert);
4797
0
    X509_ALGOR_get0(&paobj_cert, NULL, NULL, palg_cert);
4798
0
    OBJ_obj2txt(cert_algorithm, sizeof(cert_algorithm), paobj_cert, 0);
4799
4800
0
    current_pkey = X509_get0_pubkey(current_cert);
4801
0
    key_bits = EVP_PKEY_bits(current_pkey);
4802
0
#if (OPENSSL_VERSION_NUMBER < 0x30000000L)
4803
0
#define EVP_PKEY_get_security_bits EVP_PKEY_security_bits
4804
0
#endif
4805
0
    key_sec_bits = EVP_PKEY_get_security_bits(current_pkey);
4806
#if (OPENSSL_VERSION_NUMBER >= 0x30000000L)
4807
    {
4808
      char group_name[80] = "";
4809
      get_group_name = EVP_PKEY_get_group_name(current_pkey, group_name,
4810
                                               sizeof(group_name), NULL);
4811
      msnprintf(group_name_final, sizeof(group_name_final), "/%s", group_name);
4812
    }
4813
    type_name = current_pkey ? EVP_PKEY_get0_type_name(current_pkey) : NULL;
4814
#else
4815
0
    get_group_name = 0;
4816
0
    type_name = NULL;
4817
0
#endif
4818
4819
0
    infof(data,
4820
0
          "  Certificate level %d: "
4821
0
          "Public key type %s%s (%d/%d Bits/secBits), signed using %s",
4822
0
          cert_level, type_name ? type_name : "?",
4823
0
          get_group_name == 0 ? "" : group_name_final,
4824
0
          key_bits, key_sec_bits, cert_algorithm);
4825
0
  }
4826
0
}
4827
#else
4828
#define infof_certstack(data, ssl)
4829
#endif
4830
4831
0
#define MAX_CERT_NAME_LENGTH 2048
4832
4833
CURLcode Curl_oss_check_peer_cert(struct Curl_cfilter *cf,
4834
                                  struct Curl_easy *data,
4835
                                  struct ossl_ctx *octx,
4836
                                  struct ssl_peer *peer)
4837
0
{
4838
0
  struct connectdata *conn = cf->conn;
4839
0
  struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
4840
0
  struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
4841
0
  CURLcode result = CURLE_OK;
4842
0
  long lerr;
4843
0
  X509 *issuer;
4844
0
  BIO *fp = NULL;
4845
0
  char error_buffer[256]="";
4846
0
  const char *ptr;
4847
0
  BIO *mem = BIO_new(BIO_s_mem());
4848
0
  bool strict = (conn_config->verifypeer || conn_config->verifyhost);
4849
0
  struct dynbuf dname;
4850
4851
0
  DEBUGASSERT(octx);
4852
4853
0
  curlx_dyn_init(&dname, MAX_CERT_NAME_LENGTH);
4854
4855
0
  if(!mem) {
4856
0
    failf(data,
4857
0
          "BIO_new return NULL, " OSSL_PACKAGE
4858
0
          " error %s",
4859
0
          ossl_strerror(ERR_get_error(), error_buffer,
4860
0
                        sizeof(error_buffer)) );
4861
0
    return CURLE_OUT_OF_MEMORY;
4862
0
  }
4863
4864
0
  if(data->set.ssl.certinfo)
4865
    /* asked to gather certificate info */
4866
0
    (void)ossl_certchain(data, octx->ssl);
4867
4868
0
  octx->server_cert = SSL_get1_peer_certificate(octx->ssl);
4869
0
  if(!octx->server_cert) {
4870
0
    BIO_free(mem);
4871
0
    if(!strict)
4872
0
      return CURLE_OK;
4873
4874
0
    failf(data, "SSL: could not get peer certificate");
4875
0
    return CURLE_PEER_FAILED_VERIFICATION;
4876
0
  }
4877
4878
0
  infof(data, "%s certificate:",
4879
0
        Curl_ssl_cf_is_proxy(cf) ? "Proxy" : "Server");
4880
4881
0
  result = x509_name_oneline(X509_get_subject_name(octx->server_cert),
4882
0
                             &dname);
4883
0
  infof(data, " subject: %s", result ? "[NONE]" : curlx_dyn_ptr(&dname));
4884
4885
0
#ifndef CURL_DISABLE_VERBOSE_STRINGS
4886
0
  {
4887
0
    char *buf;
4888
0
    long len;
4889
0
    ASN1_TIME_print(mem, X509_get0_notBefore(octx->server_cert));
4890
0
    len = BIO_get_mem_data(mem, (char **) &buf);
4891
0
    infof(data, " start date: %.*s", (int)len, buf);
4892
0
    (void)BIO_reset(mem);
4893
4894
0
    ASN1_TIME_print(mem, X509_get0_notAfter(octx->server_cert));
4895
0
    len = BIO_get_mem_data(mem, (char **) &buf);
4896
0
    infof(data, " expire date: %.*s", (int)len, buf);
4897
0
    (void)BIO_reset(mem);
4898
0
  }
4899
0
#endif
4900
4901
0
  BIO_free(mem);
4902
4903
0
  if(conn_config->verifyhost) {
4904
0
    result = ossl_verifyhost(data, conn, peer, octx->server_cert);
4905
0
    if(result) {
4906
0
      X509_free(octx->server_cert);
4907
0
      octx->server_cert = NULL;
4908
0
      curlx_dyn_free(&dname);
4909
0
      return result;
4910
0
    }
4911
0
  }
4912
4913
0
  result = x509_name_oneline(X509_get_issuer_name(octx->server_cert),
4914
0
                             &dname);
4915
0
  if(result) {
4916
0
    if(strict)
4917
0
      failf(data, "SSL: could not get X509-issuer name");
4918
0
    result = CURLE_PEER_FAILED_VERIFICATION;
4919
0
  }
4920
0
  else {
4921
0
    infof(data, " issuer: %s", curlx_dyn_ptr(&dname));
4922
0
    curlx_dyn_free(&dname);
4923
4924
    /* We could do all sorts of certificate verification stuff here before
4925
       deallocating the certificate. */
4926
4927
    /* e.g. match issuer name with provided issuer certificate */
4928
0
    if(conn_config->issuercert || conn_config->issuercert_blob) {
4929
0
      if(conn_config->issuercert_blob) {
4930
0
        fp = BIO_new_mem_buf(conn_config->issuercert_blob->data,
4931
0
                             (int)conn_config->issuercert_blob->len);
4932
0
        if(!fp) {
4933
0
          failf(data,
4934
0
                "BIO_new_mem_buf NULL, " OSSL_PACKAGE
4935
0
                " error %s",
4936
0
                ossl_strerror(ERR_get_error(), error_buffer,
4937
0
                              sizeof(error_buffer)) );
4938
0
          X509_free(octx->server_cert);
4939
0
          octx->server_cert = NULL;
4940
0
          return CURLE_OUT_OF_MEMORY;
4941
0
        }
4942
0
      }
4943
0
      else {
4944
0
        fp = BIO_new(BIO_s_file());
4945
0
        if(!fp) {
4946
0
          failf(data,
4947
0
                "BIO_new return NULL, " OSSL_PACKAGE
4948
0
                " error %s",
4949
0
                ossl_strerror(ERR_get_error(), error_buffer,
4950
0
                              sizeof(error_buffer)) );
4951
0
          X509_free(octx->server_cert);
4952
0
          octx->server_cert = NULL;
4953
0
          return CURLE_OUT_OF_MEMORY;
4954
0
        }
4955
4956
0
        if(BIO_read_filename(fp, conn_config->issuercert) <= 0) {
4957
0
          if(strict)
4958
0
            failf(data, "SSL: Unable to open issuer cert (%s)",
4959
0
                  conn_config->issuercert);
4960
0
          BIO_free(fp);
4961
0
          X509_free(octx->server_cert);
4962
0
          octx->server_cert = NULL;
4963
0
          return CURLE_SSL_ISSUER_ERROR;
4964
0
        }
4965
0
      }
4966
4967
0
      issuer = PEM_read_bio_X509(fp, NULL, ZERO_NULL, NULL);
4968
0
      if(!issuer) {
4969
0
        if(strict)
4970
0
          failf(data, "SSL: Unable to read issuer cert (%s)",
4971
0
                conn_config->issuercert);
4972
0
        BIO_free(fp);
4973
0
        X509_free(issuer);
4974
0
        X509_free(octx->server_cert);
4975
0
        octx->server_cert = NULL;
4976
0
        return CURLE_SSL_ISSUER_ERROR;
4977
0
      }
4978
4979
0
      if(X509_check_issued(issuer, octx->server_cert) != X509_V_OK) {
4980
0
        if(strict)
4981
0
          failf(data, "SSL: Certificate issuer check failed (%s)",
4982
0
                conn_config->issuercert);
4983
0
        BIO_free(fp);
4984
0
        X509_free(issuer);
4985
0
        X509_free(octx->server_cert);
4986
0
        octx->server_cert = NULL;
4987
0
        return CURLE_SSL_ISSUER_ERROR;
4988
0
      }
4989
4990
0
      infof(data, " SSL certificate issuer check ok (%s)",
4991
0
            conn_config->issuercert);
4992
0
      BIO_free(fp);
4993
0
      X509_free(issuer);
4994
0
    }
4995
4996
0
    lerr = SSL_get_verify_result(octx->ssl);
4997
0
    ssl_config->certverifyresult = lerr;
4998
0
    if(lerr != X509_V_OK) {
4999
0
      if(conn_config->verifypeer) {
5000
        /* We probably never reach this, because SSL_connect() will fail
5001
           and we return earlier if verifypeer is set? */
5002
0
        if(strict)
5003
0
          failf(data, "SSL certificate verify result: %s (%ld)",
5004
0
                X509_verify_cert_error_string(lerr), lerr);
5005
0
        result = CURLE_PEER_FAILED_VERIFICATION;
5006
0
      }
5007
0
      else
5008
0
        infof(data, " SSL certificate verify result: %s (%ld),"
5009
0
              " continuing anyway.",
5010
0
              X509_verify_cert_error_string(lerr), lerr);
5011
0
    }
5012
0
    else
5013
0
      infof(data, " SSL certificate verify ok.");
5014
0
  }
5015
0
  infof_certstack(data, octx->ssl);
5016
5017
0
#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_OCSP)
5018
0
  if(conn_config->verifystatus && !octx->reused_session) {
5019
    /* do not do this after Session ID reuse */
5020
0
    result = verifystatus(cf, data, octx);
5021
0
    if(result) {
5022
0
      X509_free(octx->server_cert);
5023
0
      octx->server_cert = NULL;
5024
0
      return result;
5025
0
    }
5026
0
  }
5027
0
#endif
5028
5029
0
  if(!strict)
5030
    /* when not strict, we do not bother about the verify cert problems */
5031
0
    result = CURLE_OK;
5032
5033
0
#ifndef CURL_DISABLE_PROXY
5034
0
  ptr = Curl_ssl_cf_is_proxy(cf) ?
5035
0
    data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY] :
5036
0
    data->set.str[STRING_SSL_PINNEDPUBLICKEY];
5037
#else
5038
  ptr = data->set.str[STRING_SSL_PINNEDPUBLICKEY];
5039
#endif
5040
0
  if(!result && ptr) {
5041
0
    result = ossl_pkp_pin_peer_pubkey(data, octx->server_cert, ptr);
5042
0
    if(result)
5043
0
      failf(data, "SSL: public key does not match pinned public key");
5044
0
  }
5045
5046
0
  X509_free(octx->server_cert);
5047
0
  octx->server_cert = NULL;
5048
5049
0
  return result;
5050
0
}
5051
5052
static CURLcode ossl_connect_step3(struct Curl_cfilter *cf,
5053
                                   struct Curl_easy *data)
5054
0
{
5055
0
  CURLcode result = CURLE_OK;
5056
0
  struct ssl_connect_data *connssl = cf->ctx;
5057
0
  struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend;
5058
5059
0
  DEBUGASSERT(ssl_connect_3 == connssl->connecting_state);
5060
5061
  /*
5062
   * We check certificates to authenticate the server; otherwise we risk
5063
   * man-in-the-middle attack; NEVERTHELESS, if we are told explicitly not to
5064
   * verify the peer, ignore faults and failures from the server cert
5065
   * operations.
5066
   */
5067
5068
0
  result = Curl_oss_check_peer_cert(cf, data, octx, &connssl->peer);
5069
0
  if(result)
5070
    /* on error, remove sessions we might have in the pool */
5071
0
    Curl_ssl_scache_remove_all(cf, data, connssl->peer.scache_key);
5072
5073
0
  return result;
5074
0
}
5075
5076
#ifdef HAVE_OPENSSL_EARLYDATA
5077
static CURLcode ossl_send_earlydata(struct Curl_cfilter *cf,
5078
                                    struct Curl_easy *data)
5079
0
{
5080
0
  struct ssl_connect_data *connssl = cf->ctx;
5081
0
  struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend;
5082
0
  CURLcode result = CURLE_OK;
5083
0
  const unsigned char *buf;
5084
0
  size_t blen, nwritten;
5085
0
  int rc;
5086
5087
0
  DEBUGASSERT(connssl->earlydata_state == ssl_earlydata_sending);
5088
0
  octx->io_result = CURLE_OK;
5089
0
  while(Curl_bufq_peek(&connssl->earlydata, &buf, &blen)) {
5090
0
    nwritten = 0;
5091
0
    rc = SSL_write_early_data(octx->ssl, buf, blen, &nwritten);
5092
0
    CURL_TRC_CF(data, cf, "SSL_write_early_data(len=%zu) -> %d, %zu",
5093
0
                blen, rc, nwritten);
5094
0
    if(rc <= 0) {
5095
0
      long sslerror;
5096
0
      char error_buffer[256];
5097
0
      int err = SSL_get_error(octx->ssl, rc);
5098
5099
0
      switch(err) {
5100
0
      case SSL_ERROR_WANT_READ:
5101
0
        connssl->io_need = CURL_SSL_IO_NEED_RECV;
5102
0
        result = CURLE_AGAIN;
5103
0
        goto out;
5104
0
      case SSL_ERROR_WANT_WRITE:
5105
0
        connssl->io_need = CURL_SSL_IO_NEED_SEND;
5106
0
        result = CURLE_AGAIN;
5107
0
        goto out;
5108
0
      case SSL_ERROR_SYSCALL: {
5109
0
        int sockerr = SOCKERRNO;
5110
5111
0
        if(octx->io_result == CURLE_AGAIN) {
5112
0
          result = CURLE_AGAIN;
5113
0
          goto out;
5114
0
        }
5115
0
        sslerror = ERR_get_error();
5116
0
        if(sslerror)
5117
0
          ossl_strerror(sslerror, error_buffer, sizeof(error_buffer));
5118
0
        else if(sockerr)
5119
0
          Curl_strerror(sockerr, error_buffer, sizeof(error_buffer));
5120
0
        else
5121
0
          msnprintf(error_buffer, sizeof(error_buffer), "%s",
5122
0
                    SSL_ERROR_to_str(err));
5123
5124
0
        failf(data, OSSL_PACKAGE " SSL_write:early_data: %s, errno %d",
5125
0
              error_buffer, sockerr);
5126
0
        result = CURLE_SEND_ERROR;
5127
0
        goto out;
5128
0
      }
5129
0
      case SSL_ERROR_SSL: {
5130
        /*  A failure in the SSL library occurred, usually a protocol error.
5131
            The OpenSSL error queue contains more information on the error. */
5132
0
        sslerror = ERR_get_error();
5133
0
        failf(data, "SSL_write_early_data() error: %s",
5134
0
              ossl_strerror(sslerror, error_buffer, sizeof(error_buffer)));
5135
0
        result = CURLE_SEND_ERROR;
5136
0
        goto out;
5137
0
      }
5138
0
      default:
5139
        /* a true error */
5140
0
        failf(data, OSSL_PACKAGE " SSL_write_early_data: %s, errno %d",
5141
0
              SSL_ERROR_to_str(err), SOCKERRNO);
5142
0
        result = CURLE_SEND_ERROR;
5143
0
        goto out;
5144
0
      }
5145
0
    }
5146
0
    Curl_bufq_skip(&connssl->earlydata, nwritten);
5147
0
  }
5148
  /* sent everything there was */
5149
0
  infof(data, "SSL sending %zu bytes of early data", connssl->earlydata_skip);
5150
0
out:
5151
0
  return result;
5152
0
}
5153
#endif /* HAVE_OPENSSL_EARLYDATA */
5154
5155
static CURLcode ossl_connect(struct Curl_cfilter *cf,
5156
                             struct Curl_easy *data,
5157
                             bool *done)
5158
0
{
5159
0
  CURLcode result = CURLE_OK;
5160
0
  struct ssl_connect_data *connssl = cf->ctx;
5161
5162
  /* check if the connection has already been established */
5163
0
  if(ssl_connection_complete == connssl->state) {
5164
0
    *done = TRUE;
5165
0
    return CURLE_OK;
5166
0
  }
5167
5168
0
  *done = FALSE;
5169
0
  connssl->io_need = CURL_SSL_IO_NEED_NONE;
5170
5171
0
  if(ssl_connect_1 == connssl->connecting_state) {
5172
0
    CURL_TRC_CF(data, cf, "ossl_connect, step1");
5173
0
    result = ossl_connect_step1(cf, data);
5174
0
    if(result)
5175
0
      goto out;
5176
0
  }
5177
5178
0
  if(ssl_connect_2 == connssl->connecting_state) {
5179
0
    CURL_TRC_CF(data, cf, "ossl_connect, step2");
5180
0
#ifdef HAVE_OPENSSL_EARLYDATA
5181
0
    if(connssl->earlydata_state == ssl_earlydata_await) {
5182
0
      goto out;
5183
0
    }
5184
0
    else if(connssl->earlydata_state == ssl_earlydata_sending) {
5185
0
      result = ossl_send_earlydata(cf, data);
5186
0
      if(result)
5187
0
        goto out;
5188
0
      connssl->earlydata_state = ssl_earlydata_sent;
5189
0
    }
5190
0
#endif
5191
0
    DEBUGASSERT((connssl->earlydata_state == ssl_earlydata_none) ||
5192
0
                (connssl->earlydata_state == ssl_earlydata_sent));
5193
5194
0
    result = ossl_connect_step2(cf, data);
5195
0
    if(result)
5196
0
      goto out;
5197
0
  }
5198
5199
0
  if(ssl_connect_3 == connssl->connecting_state) {
5200
0
    CURL_TRC_CF(data, cf, "ossl_connect, step3");
5201
0
    result = ossl_connect_step3(cf, data);
5202
0
    if(result)
5203
0
      goto out;
5204
0
    connssl->connecting_state = ssl_connect_done;
5205
0
#ifdef HAVE_OPENSSL_EARLYDATA
5206
0
    if(connssl->earlydata_state > ssl_earlydata_none) {
5207
0
      struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend;
5208
      /* We should be in this state by now */
5209
0
      DEBUGASSERT(connssl->earlydata_state == ssl_earlydata_sent);
5210
0
      connssl->earlydata_state =
5211
0
        (SSL_get_early_data_status(octx->ssl) == SSL_EARLY_DATA_ACCEPTED) ?
5212
0
        ssl_earlydata_accepted : ssl_earlydata_rejected;
5213
0
    }
5214
0
#endif
5215
0
  }
5216
5217
0
  if(ssl_connect_done == connssl->connecting_state) {
5218
0
    CURL_TRC_CF(data, cf, "ossl_connect, done");
5219
0
    connssl->state = ssl_connection_complete;
5220
0
  }
5221
5222
0
out:
5223
0
  if(result == CURLE_AGAIN) {
5224
0
    *done = FALSE;
5225
0
    return CURLE_OK;
5226
0
  }
5227
0
  *done = ((connssl->state == ssl_connection_complete) ||
5228
0
           (connssl->state == ssl_connection_deferred));
5229
0
  return result;
5230
0
}
5231
5232
static bool ossl_data_pending(struct Curl_cfilter *cf,
5233
                              const struct Curl_easy *data)
5234
0
{
5235
0
  struct ssl_connect_data *connssl = cf->ctx;
5236
0
  (void)data;
5237
0
  return connssl->input_pending;
5238
0
}
5239
5240
static CURLcode ossl_send(struct Curl_cfilter *cf,
5241
                          struct Curl_easy *data,
5242
                          const void *mem,
5243
                          size_t len,
5244
                          size_t *pnwritten)
5245
0
{
5246
  /* SSL_write() is said to return 'int' while write() and send() returns
5247
     'size_t' */
5248
0
  int err;
5249
0
  char error_buffer[256];
5250
0
  sslerr_t sslerror;
5251
0
  int memlen;
5252
0
  struct ssl_connect_data *connssl = cf->ctx;
5253
0
  struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend;
5254
0
  CURLcode result = CURLE_OK;
5255
0
  int nwritten;
5256
5257
0
  (void)data;
5258
0
  DEBUGASSERT(octx);
5259
0
  *pnwritten = 0;
5260
0
  ERR_clear_error();
5261
5262
0
  connssl->io_need = CURL_SSL_IO_NEED_NONE;
5263
0
  memlen = (len > (size_t)INT_MAX) ? INT_MAX : (int)len;
5264
0
  nwritten = SSL_write(octx->ssl, mem, memlen);
5265
5266
0
  if(nwritten > 0)
5267
0
    *pnwritten = (size_t)nwritten;
5268
0
  else {
5269
0
    err = SSL_get_error(octx->ssl, nwritten);
5270
5271
0
    switch(err) {
5272
0
    case SSL_ERROR_WANT_READ:
5273
0
      connssl->io_need = CURL_SSL_IO_NEED_RECV;
5274
0
      result = CURLE_AGAIN;
5275
0
      goto out;
5276
0
    case SSL_ERROR_WANT_WRITE:
5277
0
      result = CURLE_AGAIN;
5278
0
      goto out;
5279
0
    case SSL_ERROR_SYSCALL:
5280
0
    {
5281
0
      int sockerr = SOCKERRNO;
5282
5283
0
      if(octx->io_result == CURLE_AGAIN) {
5284
0
        result = CURLE_AGAIN;
5285
0
        goto out;
5286
0
      }
5287
0
      sslerror = ERR_get_error();
5288
0
      if(sslerror)
5289
0
        ossl_strerror(sslerror, error_buffer, sizeof(error_buffer));
5290
0
      else if(sockerr)
5291
0
        Curl_strerror(sockerr, error_buffer, sizeof(error_buffer));
5292
0
      else
5293
0
        msnprintf(error_buffer, sizeof(error_buffer), "%s",
5294
0
                  SSL_ERROR_to_str(err));
5295
5296
0
      failf(data, OSSL_PACKAGE " SSL_write: %s, errno %d",
5297
0
            error_buffer, sockerr);
5298
0
      result = CURLE_SEND_ERROR;
5299
0
      goto out;
5300
0
    }
5301
0
    case SSL_ERROR_SSL: {
5302
      /*  A failure in the SSL library occurred, usually a protocol error.
5303
          The OpenSSL error queue contains more information on the error. */
5304
0
      sslerror = ERR_get_error();
5305
0
      failf(data, "SSL_write() error: %s",
5306
0
            ossl_strerror(sslerror, error_buffer, sizeof(error_buffer)));
5307
0
      result = CURLE_SEND_ERROR;
5308
0
      goto out;
5309
0
    }
5310
0
    default:
5311
      /* a true error */
5312
0
      failf(data, OSSL_PACKAGE " SSL_write: %s, errno %d",
5313
0
            SSL_ERROR_to_str(err), SOCKERRNO);
5314
0
      result = CURLE_SEND_ERROR;
5315
0
      goto out;
5316
0
    }
5317
0
  }
5318
5319
0
out:
5320
0
  return result;
5321
0
}
5322
5323
static CURLcode ossl_recv(struct Curl_cfilter *cf,
5324
                          struct Curl_easy *data,   /* transfer */
5325
                          char *buf,                /* store read data here */
5326
                          size_t buffersize,        /* max amount to read */
5327
                          size_t *pnread)
5328
0
{
5329
0
  char error_buffer[256];
5330
0
  unsigned long sslerror;
5331
0
  int buffsize;
5332
0
  struct connectdata *conn = cf->conn;
5333
0
  struct ssl_connect_data *connssl = cf->ctx;
5334
0
  struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend;
5335
0
  CURLcode result = CURLE_OK;
5336
0
  int nread;
5337
5338
0
  (void)data;
5339
0
  DEBUGASSERT(octx);
5340
5341
0
  *pnread = 0;
5342
0
  ERR_clear_error();
5343
5344
0
  connssl->io_need = CURL_SSL_IO_NEED_NONE;
5345
0
  buffsize = (buffersize > (size_t)INT_MAX) ? INT_MAX : (int)buffersize;
5346
0
  nread = SSL_read(octx->ssl, buf, buffsize);
5347
5348
0
  if(nread > 0)
5349
0
    *pnread = (size_t)nread;
5350
0
  else {
5351
    /* failed SSL_read */
5352
0
    int err = SSL_get_error(octx->ssl, (int)nread);
5353
5354
0
    switch(err) {
5355
0
    case SSL_ERROR_NONE: /* this is not an error */
5356
0
      break;
5357
0
    case SSL_ERROR_ZERO_RETURN: /* no more data */
5358
      /* close_notify alert */
5359
0
      if(cf->sockindex == FIRSTSOCKET)
5360
        /* mark the connection for close if it is indeed the control
5361
           connection */
5362
0
        connclose(conn, "TLS close_notify");
5363
0
      break;
5364
0
    case SSL_ERROR_WANT_READ:
5365
0
      result = CURLE_AGAIN;
5366
0
      goto out;
5367
0
    case SSL_ERROR_WANT_WRITE:
5368
0
      connssl->io_need = CURL_SSL_IO_NEED_SEND;
5369
0
      result = CURLE_AGAIN;
5370
0
      goto out;
5371
0
    default:
5372
      /* openssl/ssl.h for SSL_ERROR_SYSCALL says "look at error stack/return
5373
         value/errno" */
5374
      /* https://docs.openssl.org/master/man3/ERR_get_error/ */
5375
0
      if(octx->io_result == CURLE_AGAIN) {
5376
0
        result = CURLE_AGAIN;
5377
0
        goto out;
5378
0
      }
5379
0
      sslerror = ERR_get_error();
5380
0
      if((nread < 0) || sslerror) {
5381
        /* If the return code was negative or there actually is an error in the
5382
           queue */
5383
0
        int sockerr = SOCKERRNO;
5384
0
        if(sslerror)
5385
0
          ossl_strerror(sslerror, error_buffer, sizeof(error_buffer));
5386
0
        else if(sockerr && err == SSL_ERROR_SYSCALL)
5387
0
          Curl_strerror(sockerr, error_buffer, sizeof(error_buffer));
5388
0
        else
5389
0
          msnprintf(error_buffer, sizeof(error_buffer), "%s",
5390
0
                    SSL_ERROR_to_str(err));
5391
0
        failf(data, OSSL_PACKAGE " SSL_read: %s, errno %d",
5392
0
              error_buffer, sockerr);
5393
0
        result = CURLE_RECV_ERROR;
5394
0
        goto out;
5395
0
      }
5396
0
      else if(err == SSL_ERROR_SYSCALL) {
5397
0
        if(octx->io_result) {
5398
          /* logging handling in underlying filter already */
5399
0
          result = octx->io_result;
5400
0
        }
5401
0
        else if(connssl->peer_closed) {
5402
0
          failf(data, "Connection closed abruptly");
5403
0
          result = CURLE_RECV_ERROR;
5404
0
        }
5405
0
        else {
5406
          /* We should no longer get here nowadays. But handle
5407
           * the error in case of some weirdness in the OSSL stack */
5408
0
          int sockerr = SOCKERRNO;
5409
0
          if(sockerr)
5410
0
            Curl_strerror(sockerr, error_buffer, sizeof(error_buffer));
5411
0
          else {
5412
0
            msnprintf(error_buffer, sizeof(error_buffer),
5413
0
                      "Connection closed abruptly");
5414
0
          }
5415
0
          failf(data, OSSL_PACKAGE " SSL_read: %s, errno %d",
5416
0
                error_buffer, sockerr);
5417
0
          result = CURLE_RECV_ERROR;
5418
0
        }
5419
0
        goto out;
5420
0
      }
5421
0
    }
5422
0
  }
5423
5424
0
out:
5425
0
  if((!result && !*pnread) || (result == CURLE_AGAIN)) {
5426
    /* This happens when:
5427
     * - we read an EOF
5428
     * - OpenSSLs buffers are empty, there is no more data
5429
     * - OpenSSL read is blocked on writing something first
5430
     * - an incomplete TLS packet is buffered that cannot be read
5431
     *   until more data arrives */
5432
0
    connssl->input_pending = FALSE;
5433
0
  }
5434
0
  CURL_TRC_CF(data, cf, "ossl_recv(len=%zu) -> %d, %zu (in_pending=%d)",
5435
0
              buffersize, result, *pnread, connssl->input_pending);
5436
0
  return result;
5437
0
}
5438
5439
static CURLcode ossl_get_channel_binding(struct Curl_easy *data, int sockindex,
5440
                                         struct dynbuf *binding)
5441
0
{
5442
  /* required for X509_get_signature_nid support */
5443
0
#if OPENSSL_VERSION_NUMBER > 0x10100000L
5444
0
  X509 *cert;
5445
0
  int algo_nid;
5446
0
  const EVP_MD *algo_type;
5447
0
  const char *algo_name;
5448
0
  unsigned int length;
5449
0
  unsigned char buf[EVP_MAX_MD_SIZE];
5450
5451
0
  const char prefix[] = "tls-server-end-point:";
5452
0
  struct connectdata *conn = data->conn;
5453
0
  struct Curl_cfilter *cf = conn->cfilter[sockindex];
5454
0
  struct ossl_ctx *octx = NULL;
5455
5456
0
  do {
5457
0
    const struct Curl_cftype *cft = cf->cft;
5458
0
    struct ssl_connect_data *connssl = cf->ctx;
5459
5460
0
    if(cft->name && !strcmp(cft->name, "SSL")) {
5461
0
      octx = (struct ossl_ctx *)connssl->backend;
5462
0
      break;
5463
0
    }
5464
5465
0
    if(cf->next)
5466
0
      cf = cf->next;
5467
5468
0
  } while(cf->next);
5469
5470
0
  if(!octx) {
5471
0
    failf(data, "Failed to find the SSL filter");
5472
0
    return CURLE_BAD_FUNCTION_ARGUMENT;
5473
0
  }
5474
5475
0
  cert = SSL_get1_peer_certificate(octx->ssl);
5476
0
  if(!cert) {
5477
    /* No server certificate, don't do channel binding */
5478
0
    return CURLE_OK;
5479
0
  }
5480
5481
0
  if(!OBJ_find_sigid_algs(X509_get_signature_nid(cert), &algo_nid, NULL)) {
5482
0
    failf(data,
5483
0
          "Unable to find digest NID for certificate signature algorithm");
5484
0
    return CURLE_SSL_INVALIDCERTSTATUS;
5485
0
  }
5486
5487
  /* https://datatracker.ietf.org/doc/html/rfc5929#section-4.1 */
5488
0
  if(algo_nid == NID_md5 || algo_nid == NID_sha1) {
5489
0
    algo_type = EVP_sha256();
5490
0
  }
5491
0
  else {
5492
0
    algo_type = EVP_get_digestbynid(algo_nid);
5493
0
    if(!algo_type) {
5494
0
      algo_name = OBJ_nid2sn(algo_nid);
5495
0
      failf(data, "Could not find digest algorithm %s (NID %d)",
5496
0
            algo_name ? algo_name : "(null)", algo_nid);
5497
0
      return CURLE_SSL_INVALIDCERTSTATUS;
5498
0
    }
5499
0
  }
5500
5501
0
  if(!X509_digest(cert, algo_type, buf, &length)) {
5502
0
    failf(data, "X509_digest() failed");
5503
0
    return CURLE_SSL_INVALIDCERTSTATUS;
5504
0
  }
5505
5506
  /* Append "tls-server-end-point:" */
5507
0
  if(curlx_dyn_addn(binding, prefix, sizeof(prefix) - 1) != CURLE_OK)
5508
0
    return CURLE_OUT_OF_MEMORY;
5509
  /* Append digest */
5510
0
  if(curlx_dyn_addn(binding, buf, length))
5511
0
    return CURLE_OUT_OF_MEMORY;
5512
5513
0
  return CURLE_OK;
5514
#else
5515
  /* No X509_get_signature_nid support */
5516
  (void)data; /* unused */
5517
  (void)sockindex; /* unused */
5518
  (void)binding; /* unused */
5519
  return CURLE_OK;
5520
#endif
5521
0
}
5522
5523
size_t Curl_ossl_version(char *buffer, size_t size)
5524
0
{
5525
#ifdef LIBRESSL_VERSION_NUMBER
5526
  char *p;
5527
  size_t count;
5528
  const char *ver = OpenSSL_version(OPENSSL_VERSION);
5529
  const char expected[] = OSSL_PACKAGE " "; /* ie "LibreSSL " */
5530
  if(curl_strnequal(ver, expected, sizeof(expected) - 1)) {
5531
    ver += sizeof(expected) - 1;
5532
  }
5533
  count = msnprintf(buffer, size, "%s/%s", OSSL_PACKAGE, ver);
5534
  for(p = buffer; *p; ++p) {
5535
    if(ISBLANK(*p))
5536
      *p = '_';
5537
  }
5538
  return count;
5539
#elif defined(OPENSSL_IS_BORINGSSL)
5540
#ifdef CURL_BORINGSSL_VERSION
5541
  return msnprintf(buffer, size, "%s/%s",
5542
                   OSSL_PACKAGE,
5543
                   CURL_BORINGSSL_VERSION);
5544
#else
5545
  return msnprintf(buffer, size, OSSL_PACKAGE);
5546
#endif
5547
#elif defined(OPENSSL_IS_AWSLC)
5548
  return msnprintf(buffer, size, "%s/%s",
5549
                   OSSL_PACKAGE,
5550
                   AWSLC_VERSION_NUMBER_STRING);
5551
#elif defined(HAVE_OPENSSL_VERSION) && defined(OPENSSL_VERSION_STRING)
5552
  return msnprintf(buffer, size, "%s/%s",
5553
                   OSSL_PACKAGE, OpenSSL_version(OPENSSL_VERSION_STRING));
5554
#else
5555
  /* not LibreSSL, BoringSSL and not using OpenSSL_version */
5556
5557
0
  char sub[3];
5558
0
  unsigned long ssleay_value;
5559
0
  sub[2]='\0';
5560
0
  sub[1]='\0';
5561
0
  ssleay_value = OpenSSL_version_num();
5562
0
  if(ssleay_value&0xff0) {
5563
0
    int minor_ver = (ssleay_value >> 4) & 0xff;
5564
0
    if(minor_ver > 26) {
5565
      /* handle extended version introduced for 0.9.8za */
5566
0
      sub[1] = (char) ((minor_ver - 1) % 26 + 'a' + 1);
5567
0
      sub[0] = 'z';
5568
0
    }
5569
0
    else {
5570
0
      sub[0] = (char) (minor_ver + 'a' - 1);
5571
0
    }
5572
0
  }
5573
0
  else
5574
0
    sub[0]='\0';
5575
5576
0
  return msnprintf(buffer, size, "%s/%lx.%lx.%lx%s"
5577
#ifdef OPENSSL_FIPS
5578
                   "-fips"
5579
#endif
5580
0
                   ,
5581
0
                   OSSL_PACKAGE,
5582
0
                   (ssleay_value >> 28) & 0xf,
5583
0
                   (ssleay_value >> 20) & 0xff,
5584
0
                   (ssleay_value >> 12) & 0xff,
5585
0
                   sub);
5586
0
#endif /* OPENSSL_IS_BORINGSSL */
5587
0
}
5588
5589
/* can be called with data == NULL */
5590
static CURLcode ossl_random(struct Curl_easy *data,
5591
                            unsigned char *entropy, size_t length)
5592
0
{
5593
0
  int rc;
5594
0
  if(data) {
5595
0
    if(ossl_seed(data)) /* Initiate the seed if not already done */
5596
0
      return CURLE_FAILED_INIT; /* could not seed for some reason */
5597
0
  }
5598
0
  else {
5599
0
    if(!rand_enough())
5600
0
      return CURLE_FAILED_INIT;
5601
0
  }
5602
  /* RAND_bytes() returns 1 on success, 0 otherwise.  */
5603
0
  rc = RAND_bytes(entropy, (ossl_valsize_t)curlx_uztosi(length));
5604
0
  return rc == 1 ? CURLE_OK : CURLE_FAILED_INIT;
5605
0
}
5606
5607
#ifndef OPENSSL_NO_SHA256
5608
static CURLcode ossl_sha256sum(const unsigned char *tmp, /* input */
5609
                               size_t tmplen,
5610
                               unsigned char *sha256sum /* output */,
5611
                               size_t unused)
5612
0
{
5613
0
  EVP_MD_CTX *mdctx;
5614
0
  unsigned int len = 0;
5615
0
  (void) unused;
5616
5617
0
  mdctx = EVP_MD_CTX_create();
5618
0
  if(!mdctx)
5619
0
    return CURLE_OUT_OF_MEMORY;
5620
0
  if(!EVP_DigestInit(mdctx, EVP_sha256())) {
5621
0
    EVP_MD_CTX_destroy(mdctx);
5622
0
    return CURLE_FAILED_INIT;
5623
0
  }
5624
0
  EVP_DigestUpdate(mdctx, tmp, tmplen);
5625
0
  EVP_DigestFinal_ex(mdctx, sha256sum, &len);
5626
0
  EVP_MD_CTX_destroy(mdctx);
5627
0
  return CURLE_OK;
5628
0
}
5629
#endif
5630
5631
static bool ossl_cert_status_request(void)
5632
0
{
5633
0
#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_OCSP)
5634
0
  return TRUE;
5635
#else
5636
  return FALSE;
5637
#endif
5638
0
}
5639
5640
static void *ossl_get_internals(struct ssl_connect_data *connssl,
5641
                                CURLINFO info)
5642
0
{
5643
  /* Legacy: CURLINFO_TLS_SESSION must return an SSL_CTX pointer. */
5644
0
  struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend;
5645
0
  DEBUGASSERT(octx);
5646
0
  return info == CURLINFO_TLS_SESSION ?
5647
0
    (void *)octx->ssl_ctx : (void *)octx->ssl;
5648
0
}
5649
5650
const struct Curl_ssl Curl_ssl_openssl = {
5651
  { CURLSSLBACKEND_OPENSSL, "openssl" }, /* info */
5652
5653
  SSLSUPP_CA_PATH |
5654
  SSLSUPP_CAINFO_BLOB |
5655
  SSLSUPP_CERTINFO |
5656
  SSLSUPP_PINNEDPUBKEY |
5657
  SSLSUPP_SSL_CTX |
5658
#ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
5659
  SSLSUPP_TLS13_CIPHERSUITES |
5660
#endif
5661
#ifdef HAVE_SSL_CTX_SET1_SIGALGS
5662
  SSLSUPP_SIGNATURE_ALGORITHMS |
5663
#endif
5664
#ifdef USE_ECH_OPENSSL
5665
  SSLSUPP_ECH |
5666
#endif
5667
  SSLSUPP_CA_CACHE |
5668
  SSLSUPP_HTTPS_PROXY |
5669
  SSLSUPP_CIPHER_LIST,
5670
5671
  sizeof(struct ossl_ctx),
5672
5673
  ossl_init,                /* init */
5674
  ossl_cleanup,             /* cleanup */
5675
  Curl_ossl_version,        /* version */
5676
  ossl_shutdown,            /* shutdown */
5677
  ossl_data_pending,        /* data_pending */
5678
  ossl_random,              /* random */
5679
  ossl_cert_status_request, /* cert_status_request */
5680
  ossl_connect,             /* connect */
5681
  Curl_ssl_adjust_pollset,  /* adjust_pollset */
5682
  ossl_get_internals,       /* get_internals */
5683
  ossl_close,               /* close_one */
5684
  ossl_close_all,           /* close_all */
5685
  ossl_set_engine,          /* set_engine or provider */
5686
  ossl_set_engine_default,  /* set_engine_default */
5687
  ossl_engines_list,        /* engines_list */
5688
#ifndef OPENSSL_NO_SHA256
5689
  ossl_sha256sum,           /* sha256sum */
5690
#else
5691
  NULL,                     /* sha256sum */
5692
#endif
5693
  ossl_recv,                /* recv decrypted data */
5694
  ossl_send,                /* send data to encrypt */
5695
  ossl_get_channel_binding  /* get_channel_binding */
5696
};
5697
5698
#endif /* USE_OPENSSL */