Coverage Report

Created: 2024-09-08 06:32

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