Coverage Report

Created: 2025-08-03 06:36

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