Coverage Report

Created: 2026-09-14 06:43

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/CMake/Utilities/cmcurl/lib/vtls/vtls.c
Line
Count
Source
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
/* This file is for implementing all "generic" SSL functions that all libcurl
26
   internals should use. It is then responsible for calling the proper
27
   "backend" function.
28
29
   SSL-functions in libcurl should call functions in this source file, and not
30
   to any specific SSL-layer.
31
32
   Curl_ssl_ - prefix for generic ones
33
34
   Note that this source code uses the functions of the configured SSL
35
   backend via the global Curl_ssl instance.
36
37
   "SSL/TLS Strong Encryption: An Introduction"
38
   https://httpd.apache.org/docs/2.0/ssl/ssl_intro.html
39
 */
40
41
#include "curl_setup.h"
42
43
#include "urldata.h"
44
#include "cfilters.h"
45
46
#include "vtls/vtls.h" /* generic SSL protos etc */
47
#include "vtls/vtls_int.h"
48
#include "vtls/vtls_scache.h"
49
#include "vtls/keylog.h"
50
51
#include "vtls/openssl.h"        /* OpenSSL versions */
52
#include "vtls/gtls.h"           /* GnuTLS versions */
53
#include "vtls/wolfssl.h"        /* wolfSSL versions */
54
#include "vtls/schannel.h"       /* Schannel SSPI version */
55
#include "vtls/mbedtls.h"        /* mbedTLS versions */
56
#include "vtls/rustls.h"         /* Rustls versions */
57
58
#include "slist.h"
59
#include "curl_trc.h"
60
#include "strcase.h"
61
#include "url.h"
62
#include "progress.h"
63
#include "curlx/fopen.h"
64
#include "curl_sha256.h"
65
#include "curlx/base64.h"
66
#include "curlx/inet_pton.h"
67
#include "connect.h"
68
#include "select.h"
69
#include "setopt.h"
70
#include "vdns/cf-dns.h"
71
#include "curlx/strdup.h"
72
#include "curlx/strcopy.h"
73
74
#ifdef USE_APPLE_SECTRUST
75
#include <Security/Security.h>
76
#endif
77
78
#ifdef USE_SSL
79
#if !defined(CURL_DISABLE_HTTP) || !defined(CURL_DISABLE_PROXY)
80
static const struct alpn_spec ALPN_SPEC_H11 = {
81
  { ALPN_HTTP_1_1 }, 1
82
};
83
static const struct alpn_spec ALPN_SPEC_H10_H11 = {
84
  { ALPN_HTTP_1_0, ALPN_HTTP_1_1 }, 2
85
};
86
#ifdef USE_HTTP2
87
static const struct alpn_spec ALPN_SPEC_H2 = {
88
  { ALPN_H2 }, 1
89
};
90
static const struct alpn_spec ALPN_SPEC_H2_H11 = {
91
  { ALPN_H2, ALPN_HTTP_1_1 }, 2
92
};
93
static const struct alpn_spec ALPN_SPEC_H11_H2 = {
94
  { ALPN_HTTP_1_1, ALPN_H2 }, 2
95
};
96
#endif /* USE_HTTP2 */
97
98
static const struct alpn_spec *alpn_get_spec(http_majors wanted,
99
                                             http_majors preferred,
100
                                             bool only_http_10,
101
                                             bool use_alpn)
102
{
103
  if(!use_alpn)
104
    return NULL;
105
  /* If HTTP/1.0 is the wanted protocol then use ALPN http/1.0 and http/1.1.
106
     This is for compatibility reasons since some HTTP/1.0 servers with old
107
     ALPN implementations understand ALPN http/1.1 but not http/1.0. */
108
  if(only_http_10 && (wanted & CURL_HTTP_V1x))
109
    return &ALPN_SPEC_H10_H11;
110
#ifdef USE_HTTP2
111
  if(wanted & CURL_HTTP_V2x) {
112
    if(wanted & CURL_HTTP_V1x)
113
      return (preferred == CURL_HTTP_V1x) ?
114
        &ALPN_SPEC_H11_H2 : &ALPN_SPEC_H2_H11;
115
    return &ALPN_SPEC_H2;
116
  }
117
#else
118
  (void)wanted;
119
  (void)preferred;
120
#endif
121
  return &ALPN_SPEC_H11;
122
}
123
#endif /* !CURL_DISABLE_HTTP || !CURL_DISABLE_PROXY */
124
#endif /* USE_SSL */
125
126
#ifdef USE_SSL
127
static int multissl_setup(const struct Curl_ssl *backend);
128
#endif
129
130
curl_sslbackend Curl_ssl_backend(void)
131
0
{
132
#ifdef USE_SSL
133
  multissl_setup(NULL);
134
  return Curl_ssl->info.id;
135
#else
136
0
  return CURLSSLBACKEND_NONE;
137
0
#endif
138
0
}
139
140
#ifdef USE_SSL
141
142
/* "global" init done? */
143
static bool init_ssl = FALSE;
144
145
/**
146
 * Global SSL init
147
 *
148
 * @retval 0 error initializing SSL
149
 * @retval 1 SSL initialized successfully
150
 */
151
int Curl_ssl_init(void)
152
{
153
  /* make sure this is only done once */
154
  if(init_ssl)
155
    return 1;
156
  init_ssl = TRUE; /* never again */
157
158
  if(Curl_ssl->init)
159
    return Curl_ssl->init();
160
  return 1;
161
}
162
163
static bool ssl_prefs_check(struct Curl_easy *data)
164
{
165
  /* check for CURLOPT_SSLVERSION invalid parameter value */
166
  const unsigned char sslver = data->set.ssl.primary.version;
167
  if(sslver >= CURL_SSLVERSION_LAST) {
168
    failf(data, "Unrecognized parameter value passed via CURLOPT_SSLVERSION");
169
    return FALSE;
170
  }
171
172
  switch(data->set.ssl.primary.version_max) {
173
  case CURL_SSLVERSION_MAX_NONE:
174
  case CURL_SSLVERSION_MAX_DEFAULT:
175
    break;
176
177
  default:
178
    if((data->set.ssl.primary.version_max >> 16) < sslver) {
179
      failf(data, "CURL_SSLVERSION_MAX incompatible with CURL_SSLVERSION");
180
      return FALSE;
181
    }
182
  }
183
184
  return TRUE;
185
}
186
187
static struct ssl_connect_data *cf_ctx_new(struct Curl_easy *data,
188
                                           const struct alpn_spec *alpn)
189
{
190
  struct ssl_connect_data *ctx;
191
192
  (void)data;
193
  ctx = curlx_calloc(1, sizeof(*ctx));
194
  if(!ctx)
195
    return NULL;
196
197
  ctx->ssl_impl = Curl_ssl;
198
  ctx->alpn = alpn;
199
  Curl_bufq_init2(&ctx->earlydata, CURL_SSL_EARLY_MAX, 1, BUFQ_OPT_NO_SPARES);
200
  ctx->backend = curlx_calloc(1, ctx->ssl_impl->sizeof_ssl_backend_data);
201
  if(!ctx->backend) {
202
    curlx_free(ctx);
203
    return NULL;
204
  }
205
  return ctx;
206
}
207
208
static void cf_ctx_free(struct ssl_connect_data *ctx)
209
{
210
  if(ctx) {
211
    curlx_safefree(ctx->negotiated.alpn);
212
    Curl_bufq_free(&ctx->earlydata);
213
    curlx_free(ctx->backend);
214
    curlx_free(ctx);
215
  }
216
}
217
218
CURLcode Curl_ssl_get_channel_binding(struct Curl_easy *data, int8_t sockindex,
219
                                      struct dynbuf *binding)
220
{
221
  if(Curl_ssl->get_channel_binding)
222
    return Curl_ssl->get_channel_binding(data, sockindex, binding);
223
  return CURLE_OK;
224
}
225
226
void Curl_ssl_close_all(struct Curl_easy *data)
227
{
228
  if(Curl_ssl->close_all)
229
    Curl_ssl->close_all(data);
230
}
231
232
CURLcode Curl_ssl_adjust_pollset(struct Curl_cfilter *cf,
233
                                 struct Curl_easy *data,
234
                                 struct easy_pollset *ps)
235
{
236
  struct ssl_connect_data *connssl = cf->ctx;
237
238
  if(connssl->io_need) {
239
    curl_socket_t sock = Curl_conn_cf_get_socket(cf->next, data);
240
    CURLcode result = CURLE_OK;
241
    if(sock != CURL_SOCKET_BAD) {
242
      if(connssl->io_need & CURL_SSL_IO_NEED_SEND) {
243
        result = Curl_pollset_set_out_only(data, ps, sock);
244
        CURL_TRC_CF(data, cf, "adjust_pollset, POLLOUT fd=%" FMT_SOCKET_T,
245
                    sock);
246
      }
247
      else {
248
        result = Curl_pollset_set_in_only(data, ps, sock);
249
        CURL_TRC_CF(data, cf, "adjust_pollset, POLLIN fd=%" FMT_SOCKET_T,
250
                    sock);
251
      }
252
    }
253
    return result;
254
  }
255
  return CURLE_OK;
256
}
257
258
/* Selects an SSL crypto engine
259
 */
260
CURLcode Curl_ssl_set_engine(struct Curl_easy *data, const char *engine)
261
{
262
  if(Curl_ssl->set_engine)
263
    return Curl_ssl->set_engine(data, engine);
264
  return CURLE_NOT_BUILT_IN;
265
}
266
267
/* Selects the default SSL crypto engine
268
 */
269
CURLcode Curl_ssl_set_engine_default(struct Curl_easy *data)
270
{
271
  if(Curl_ssl->set_engine_default)
272
    return Curl_ssl->set_engine_default(data);
273
  return CURLE_NOT_BUILT_IN;
274
}
275
276
/* Return list of OpenSSL crypto engine names. */
277
struct curl_slist *Curl_ssl_engines_list(struct Curl_easy *data)
278
{
279
  if(Curl_ssl->engines_list)
280
    return Curl_ssl->engines_list(data);
281
  return NULL;
282
}
283
284
static size_t multissl_version(char *buffer, size_t size);
285
286
void Curl_ssl_version(char *buffer, size_t size)
287
{
288
#ifdef CURL_WITH_MULTI_SSL
289
  (void)multissl_version(buffer, size);
290
#else
291
  (void)Curl_ssl->version(buffer, size);
292
#endif
293
}
294
295
void Curl_ssl_free_certinfo(struct Curl_easy *data)
296
{
297
  struct curl_certinfo *ci = &data->info.certs;
298
299
  if(ci->num_of_certs) {
300
    /* free all individual lists used */
301
    int i;
302
    for(i = 0; i < ci->num_of_certs; i++) {
303
      curl_slist_free_all(ci->certinfo[i]);
304
      ci->certinfo[i] = NULL;
305
    }
306
307
    curlx_safefree(ci->certinfo); /* free the actual array too */
308
    ci->num_of_certs = 0;
309
  }
310
}
311
312
CURLcode Curl_ssl_init_certinfo(struct Curl_easy *data, int num)
313
{
314
  struct curl_certinfo *ci = &data->info.certs;
315
  struct curl_slist **table;
316
317
  /* Free any previous certificate information structures */
318
  Curl_ssl_free_certinfo(data);
319
320
  /* Allocate the required certificate information structures */
321
  table = curlx_calloc((size_t)num, sizeof(struct curl_slist *));
322
  if(!table)
323
    return CURLE_OUT_OF_MEMORY;
324
325
  ci->num_of_certs = num;
326
  ci->certinfo = table;
327
328
  return CURLE_OK;
329
}
330
331
/*
332
 * 'value' is NOT a null-terminated string
333
 */
334
CURLcode Curl_ssl_push_certinfo_len(struct Curl_easy *data,
335
                                    int certnum,
336
                                    const char *label,
337
                                    const char *value,
338
                                    size_t valuelen)
339
{
340
  struct curl_certinfo *ci = &data->info.certs;
341
  struct curl_slist *nl;
342
  CURLcode result = CURLE_OK;
343
  struct dynbuf build;
344
345
  DEBUGASSERT(certnum < ci->num_of_certs);
346
347
  curlx_dyn_init(&build, CURL_X509_STR_MAX);
348
349
  if(curlx_dyn_add(&build, label) ||
350
     curlx_dyn_addn(&build, ":", 1) ||
351
     curlx_dyn_addn(&build, value, valuelen))
352
    return CURLE_OUT_OF_MEMORY;
353
354
  nl = Curl_slist_append_nodup(ci->certinfo[certnum], curlx_dyn_ptr(&build));
355
  if(!nl) {
356
    curlx_dyn_free(&build);
357
    curl_slist_free_all(ci->certinfo[certnum]);
358
    result = CURLE_OUT_OF_MEMORY;
359
  }
360
361
  ci->certinfo[certnum] = nl;
362
  return result;
363
}
364
365
/* get length bytes of randomness */
366
CURLcode Curl_ssl_random(struct Curl_easy *data,
367
                         unsigned char *buffer, size_t length)
368
{
369
  DEBUGASSERT(length == sizeof(int));
370
  if(Curl_ssl->random)
371
    return Curl_ssl->random(data, buffer, length);
372
  else
373
    return CURLE_NOT_BUILT_IN;
374
}
375
376
/*
377
 * Public key pem to der conversion
378
 */
379
380
static CURLcode pubkey_pem_to_der(const char *pem,
381
                                  unsigned char **der, size_t *der_len)
382
{
383
  const char *begin_pos, *end_pos;
384
  size_t pem_count, pem_len;
385
  CURLcode result;
386
  struct dynbuf pbuf;
387
388
  /* if no pem, exit. */
389
  if(!pem)
390
    return CURLE_BAD_CONTENT_ENCODING;
391
392
  curlx_dyn_init(&pbuf, MAX_PINNED_PUBKEY_SIZE);
393
394
  begin_pos = strstr(pem, "-----BEGIN PUBLIC KEY-----");
395
  if(!begin_pos)
396
    return CURLE_BAD_CONTENT_ENCODING;
397
398
  pem_count = begin_pos - pem;
399
  /* Invalid if not at beginning AND not directly following \n */
400
  if(pem_count && '\n' != pem[pem_count - 1])
401
    return CURLE_BAD_CONTENT_ENCODING;
402
403
  /* 26 is length of "-----BEGIN PUBLIC KEY-----" */
404
  pem_count += 26;
405
406
  /* Invalid if not directly following \n */
407
  end_pos = strstr(pem + pem_count, "\n-----END PUBLIC KEY-----");
408
  if(!end_pos)
409
    return CURLE_BAD_CONTENT_ENCODING;
410
411
  pem_len = end_pos - pem;
412
413
  /*
414
   * Here we loop through the pem array one character at a time between the
415
   * correct indices, and place each character that is not '\n' or '\r'
416
   * into the stripped_pem array, which should represent the raw base64 string
417
   */
418
  while(pem_count < pem_len) {
419
    if('\n' != pem[pem_count] && '\r' != pem[pem_count]) {
420
      result = curlx_dyn_addn(&pbuf, &pem[pem_count], 1);
421
      if(result)
422
        return result;
423
    }
424
    ++pem_count;
425
  }
426
427
  if(curlx_dyn_len(&pbuf)) {
428
    result = curlx_base64_decode(curlx_dyn_ptr(&pbuf), der, der_len);
429
    curlx_dyn_free(&pbuf);
430
  }
431
  else
432
    result = CURLE_BAD_CONTENT_ENCODING;
433
434
  return result;
435
}
436
437
/*
438
 * Generic pinned public key check.
439
 */
440
441
CURLcode Curl_pin_peer_pubkey(struct Curl_easy *data,
442
                              const char *pinnedpubkey,
443
                              const unsigned char *pubkey, size_t pubkeylen)
444
{
445
  CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH;
446
447
  /* if a path was not specified, do not pin */
448
  if(!pinnedpubkey)
449
    return CURLE_OK;
450
  if(!pubkey || !pubkeylen)
451
    return result;
452
453
  /* only do this if pinnedpubkey starts with "sha256//", length 8 */
454
  if(!strncmp(pinnedpubkey, "sha256//", 8)) {
455
    CURLcode encode;
456
    char *cert_hash = NULL;
457
    const char *pinned_hash, *end_pos;
458
    size_t cert_hash_len = 0, pinned_hash_len;
459
    unsigned char *sha256sumdigest;
460
461
    if(!Curl_ssl->sha256sum) {
462
      /* without sha256 support, this cannot match */
463
      return result;
464
    }
465
466
    /* compute sha256sum of public key */
467
    sha256sumdigest = curlx_malloc(CURL_SHA256_DIGEST_LENGTH);
468
    if(!sha256sumdigest)
469
      return CURLE_OUT_OF_MEMORY;
470
    encode = Curl_ssl->sha256sum(pubkey, pubkeylen,
471
                                 sha256sumdigest, CURL_SHA256_DIGEST_LENGTH);
472
473
    if(!encode)
474
      encode = curlx_base64_encode(sha256sumdigest,
475
                                   CURL_SHA256_DIGEST_LENGTH,
476
                                   &cert_hash, &cert_hash_len);
477
    curlx_safefree(sha256sumdigest);
478
479
    if(encode)
480
      return encode;
481
482
    infof(data, " public key hash: sha256//%s", cert_hash);
483
484
    pinned_hash = pinnedpubkey;
485
    while(pinned_hash &&
486
          !strncmp(pinned_hash, "sha256//", CURL_CSTRLEN("sha256//"))) {
487
      pinned_hash = pinned_hash + CURL_CSTRLEN("sha256//");
488
      end_pos = strchr(pinned_hash, ';');
489
      pinned_hash_len = end_pos ?
490
                        (size_t)(end_pos - pinned_hash) : strlen(pinned_hash);
491
492
      /* compare base64 sha256 digests */
493
      if(cert_hash_len == pinned_hash_len &&
494
         !memcmp(cert_hash, pinned_hash, cert_hash_len)) {
495
        DEBUGF(infof(data, "public key hash matches pinned value"));
496
        result = CURLE_OK;
497
        break;
498
      }
499
500
      DEBUGF(infof(data, "public key hash does not match 'sha256//%.*s'",
501
                   (int)pinned_hash_len, pinned_hash));
502
      /* next one or we are at the end */
503
      pinned_hash = end_pos ? (end_pos + 1) : NULL;
504
    }
505
    curlx_safefree(cert_hash);
506
  }
507
  else {
508
    long filesize;
509
    size_t size, pem_len;
510
    CURLcode pem_read;
511
    struct dynbuf buf;
512
    unsigned char *pem_ptr = NULL;
513
    size_t left;
514
    FILE *fp = curlx_fopen(pinnedpubkey, "rb");
515
    if(!fp)
516
      return result;
517
518
    curlx_dyn_init(&buf, MAX_PINNED_PUBKEY_SIZE);
519
520
    /* Determine the file's size */
521
    if(fseek(fp, 0, SEEK_END))
522
      goto end;
523
    filesize = ftell(fp);
524
    if(fseek(fp, 0, SEEK_SET))
525
      goto end;
526
    if(filesize < 0 || filesize > MAX_PINNED_PUBKEY_SIZE)
527
      goto end;
528
529
    /*
530
     * if the size of our certificate is bigger than the file
531
     * size then it cannot match
532
     */
533
    size = curlx_sotouz((curl_off_t)filesize);
534
    if(pubkeylen > size)
535
      goto end;
536
537
    /*
538
     * Read the file into the dynbuf
539
     */
540
    left = size;
541
    do {
542
      char buffer[1024];
543
      size_t want = left > sizeof(buffer) ? sizeof(buffer) : left;
544
      if(fread(buffer, 1, want, fp) != want)
545
        goto end;
546
      if(curlx_dyn_addn(&buf, buffer, want))
547
        goto end;
548
      left -= want;
549
    } while(left);
550
551
    /* If the sizes are the same, it cannot be base64 encoded, must be der */
552
    if(pubkeylen == size) {
553
      if(!memcmp(pubkey, curlx_dyn_ptr(&buf), pubkeylen))
554
        result = CURLE_OK;
555
      goto end;
556
    }
557
558
    /*
559
     * Otherwise we assume it is PEM and try to decode it after placing
560
     * null-terminator
561
     */
562
    pem_read = pubkey_pem_to_der(curlx_dyn_ptr(&buf), &pem_ptr, &pem_len);
563
    /* if it was not read successfully, exit */
564
    if(pem_read)
565
      goto end;
566
567
    /*
568
     * if the size of our certificate does not match the size of
569
     * the decoded file, they cannot be the same, otherwise compare
570
     */
571
    if(pubkeylen == pem_len && !memcmp(pubkey, pem_ptr, pubkeylen))
572
      result = CURLE_OK;
573
end:
574
    curlx_dyn_free(&buf);
575
    curlx_safefree(pem_ptr);
576
    curlx_fclose(fp);
577
  }
578
579
  return result;
580
}
581
582
/*
583
 * Check whether the SSL backend supports the status_request extension.
584
 */
585
bool Curl_ssl_cert_status_request(void)
586
{
587
  if(Curl_ssl->cert_status_request)
588
    return Curl_ssl->cert_status_request();
589
  return FALSE;
590
}
591
592
static int multissl_init(void)
593
{
594
  if(multissl_setup(NULL))
595
    return 1;
596
  if(Curl_ssl->init)
597
    return Curl_ssl->init();
598
  return 1;
599
}
600
601
static CURLcode multissl_random(struct Curl_easy *data,
602
                                unsigned char *entropy, size_t length)
603
{
604
  if(multissl_setup(NULL))
605
    return CURLE_FAILED_INIT;
606
  return Curl_ssl->random(data, entropy, length);
607
}
608
609
static CURLcode multissl_connect(struct Curl_cfilter *cf,
610
                                 struct Curl_easy *data, bool *done)
611
{
612
  if(multissl_setup(NULL))
613
    return CURLE_FAILED_INIT;
614
  return Curl_ssl->do_connect(cf, data, done);
615
}
616
617
static CURLcode multissl_adjust_pollset(struct Curl_cfilter *cf,
618
                                        struct Curl_easy *data,
619
                                        struct easy_pollset *ps)
620
{
621
  if(multissl_setup(NULL))
622
    return CURLE_OK;
623
  return Curl_ssl->adjust_pollset(cf, data, ps);
624
}
625
626
static void *multissl_get_internals(struct ssl_connect_data *connssl,
627
                                    CURLINFO info)
628
{
629
  if(multissl_setup(NULL))
630
    return NULL;
631
  return Curl_ssl->get_internals(connssl, info);
632
}
633
634
static void multissl_close(struct Curl_cfilter *cf, struct Curl_easy *data)
635
{
636
  if(multissl_setup(NULL))
637
    return;
638
  Curl_ssl->close(cf, data);
639
}
640
641
static CURLcode multissl_recv_plain(struct Curl_cfilter *cf,
642
                                    struct Curl_easy *data,
643
                                    char *buf, size_t len, size_t *pnread)
644
{
645
  if(multissl_setup(NULL))
646
    return CURLE_FAILED_INIT;
647
  return Curl_ssl->recv_plain(cf, data, buf, len, pnread);
648
}
649
650
static CURLcode multissl_send_plain(struct Curl_cfilter *cf,
651
                                    struct Curl_easy *data,
652
                                    const void *mem, size_t len,
653
                                    size_t *pnwritten)
654
{
655
  if(multissl_setup(NULL))
656
    return CURLE_FAILED_INIT;
657
  return Curl_ssl->send_plain(cf, data, mem, len, pnwritten);
658
}
659
660
static const struct Curl_ssl Curl_ssl_multi = {
661
  { CURLSSLBACKEND_NONE, "multi" },  /* info */
662
  0, /* supports nothing */
663
  (size_t)-1, /* something insanely large to be on the safe side */
664
665
  multissl_init,                     /* init */
666
  NULL,                              /* cleanup */
667
  multissl_version,                  /* version */
668
  NULL,                              /* shutdown */
669
  NULL,                              /* data_pending */
670
  multissl_random,                   /* random */
671
  NULL,                              /* cert_status_request */
672
  multissl_connect,                  /* connect */
673
  multissl_adjust_pollset,           /* adjust_pollset */
674
  multissl_get_internals,            /* get_internals */
675
  multissl_close,                    /* close_one */
676
  NULL,                              /* close_all */
677
  NULL,                              /* set_engine */
678
  NULL,                              /* set_engine_default */
679
  NULL,                              /* engines_list */
680
  NULL,                              /* sha256sum */
681
  multissl_recv_plain,               /* recv decrypted data */
682
  multissl_send_plain,               /* send data to encrypt */
683
  NULL,                              /* get_channel_binding */
684
};
685
686
const struct Curl_ssl *Curl_ssl =
687
#ifdef CURL_WITH_MULTI_SSL
688
  &Curl_ssl_multi;
689
#elif defined(USE_WOLFSSL)
690
  &Curl_ssl_wolfssl;
691
#elif defined(USE_GNUTLS)
692
  &Curl_ssl_gnutls;
693
#elif defined(USE_MBEDTLS)
694
  &Curl_ssl_mbedtls;
695
#elif defined(USE_RUSTLS)
696
  &Curl_ssl_rustls;
697
#elif defined(USE_OPENSSL)
698
  &Curl_ssl_openssl;
699
#elif defined(USE_SCHANNEL)
700
  &Curl_ssl_schannel;
701
#else
702
#error "Missing struct Curl_ssl for selected SSL backend"
703
#endif
704
705
static const struct Curl_ssl *available_backends[] = {
706
#ifdef USE_WOLFSSL
707
  &Curl_ssl_wolfssl,
708
#endif
709
#ifdef USE_GNUTLS
710
  &Curl_ssl_gnutls,
711
#endif
712
#ifdef USE_MBEDTLS
713
  &Curl_ssl_mbedtls,
714
#endif
715
#ifdef USE_OPENSSL
716
  &Curl_ssl_openssl,
717
#endif
718
#ifdef USE_SCHANNEL
719
  &Curl_ssl_schannel,
720
#endif
721
#ifdef USE_RUSTLS
722
  &Curl_ssl_rustls,
723
#endif
724
  NULL
725
};
726
727
/* Global cleanup */
728
void Curl_ssl_cleanup(void)
729
{
730
  if(init_ssl) {
731
    /* only cleanup if we did a previous init */
732
    if(Curl_ssl->cleanup)
733
      Curl_ssl->cleanup();
734
#ifdef CURL_WITH_MULTI_SSL
735
    Curl_ssl = &Curl_ssl_multi;
736
#endif
737
    init_ssl = FALSE;
738
  }
739
}
740
741
static size_t multissl_version(char *buffer, size_t size)
742
{
743
  static const struct Curl_ssl *selected;
744
  static char backends[200];
745
  static size_t backends_len;
746
  const struct Curl_ssl *current;
747
748
  current = Curl_ssl == &Curl_ssl_multi ? available_backends[0] : Curl_ssl;
749
750
  if(current != selected) {
751
    char *p = backends;
752
    const char *end = backends + sizeof(backends);
753
    int i;
754
755
    selected = current;
756
757
    backends[0] = '\0';
758
759
    for(i = 0; available_backends[i]; ++i) {
760
      char vb[200];
761
      bool paren = (selected != available_backends[i]);
762
763
      if(available_backends[i]->version(vb, sizeof(vb))) {
764
        p += curl_msnprintf(p, end - p, "%s%s%s%s", (p != backends ? " " : ""),
765
                            (paren ? "(" : ""), vb, (paren ? ")" : ""));
766
      }
767
    }
768
769
    backends_len = p - backends;
770
  }
771
772
  if(size) {
773
    curlx_strcopy(buffer, size, backends, backends_len);
774
  }
775
  return 0;
776
}
777
778
static int multissl_setup(const struct Curl_ssl *backend)
779
{
780
  int i;
781
  char *env;
782
783
  if(Curl_ssl != &Curl_ssl_multi)
784
    return 1;
785
786
  if(backend) {
787
    Curl_ssl = backend;
788
    return 0;
789
  }
790
791
  if(!available_backends[0])
792
    return 1;
793
794
  env = curl_getenv("CURL_SSL_BACKEND");
795
  if(env) {
796
    for(i = 0; available_backends[i]; i++) {
797
      if(curl_strequal(env, available_backends[i]->info.name)) {
798
        Curl_ssl = available_backends[i];
799
        curlx_free(env);
800
        return 0;
801
      }
802
    }
803
  }
804
805
#ifdef CURL_DEFAULT_SSL_BACKEND
806
  for(i = 0; available_backends[i]; i++) {
807
    if(curl_strequal(CURL_DEFAULT_SSL_BACKEND,
808
                     available_backends[i]->info.name)) {
809
      Curl_ssl = available_backends[i];
810
      curlx_free(env);
811
      return 0;
812
    }
813
  }
814
#endif
815
816
  /* Fall back to first available backend */
817
  Curl_ssl = available_backends[0];
818
  curlx_free(env);
819
  return 0;
820
}
821
822
/* This function is used to select the SSL backend to use. It is called by
823
   curl_global_sslset (easy.c) which uses the global init lock. */
824
CURLsslset Curl_init_sslset_nolock(curl_sslbackend id, const char *name,
825
                                   const curl_ssl_backend ***avail)
826
{
827
  int i;
828
829
  if(avail)
830
    *avail = (const curl_ssl_backend **)&available_backends;
831
832
  if(Curl_ssl != &Curl_ssl_multi)
833
    return id == Curl_ssl->info.id ||
834
           (name && curl_strequal(name, Curl_ssl->info.name)) ?
835
           CURLSSLSET_OK :
836
#ifdef CURL_WITH_MULTI_SSL
837
           CURLSSLSET_TOO_LATE;
838
#else
839
           CURLSSLSET_UNKNOWN_BACKEND;
840
#endif
841
842
  for(i = 0; available_backends[i]; i++) {
843
    if(available_backends[i]->info.id == id ||
844
       (name && curl_strequal(available_backends[i]->info.name, name))) {
845
      multissl_setup(available_backends[i]);
846
      return CURLSSLSET_OK;
847
    }
848
  }
849
850
  return CURLSSLSET_UNKNOWN_BACKEND;
851
}
852
853
#else /* USE_SSL */
854
CURLsslset Curl_init_sslset_nolock(curl_sslbackend id, const char *name,
855
                                   const curl_ssl_backend ***avail)
856
0
{
857
0
  (void)id;
858
0
  (void)name;
859
0
  (void)avail;
860
0
  return CURLSSLSET_NO_BACKENDS;
861
0
}
862
863
#endif /* !USE_SSL */
864
865
#ifdef USE_SSL
866
867
void Curl_ssl_peer_cleanup(struct ssl_peer *peer)
868
{
869
  Curl_peer_unlink(&peer->origin);
870
  Curl_peer_unlink(&peer->peer);
871
  curlx_safefree(peer->sni);
872
  curlx_safefree(peer->scache_key);
873
  peer->transport = TRNSPRT_NONE;
874
  peer->type = CURL_SSL_PEER_DNS;
875
}
876
877
static ssl_peer_type get_peer_type(const char *hostname)
878
{
879
  if(hostname && hostname[0]) {
880
#ifdef USE_IPV6
881
    struct in6_addr addr;
882
#else
883
    struct in_addr addr;
884
#endif
885
    if(curlx_inet_pton(AF_INET, hostname, &addr))
886
      return CURL_SSL_PEER_IPV4;
887
#ifdef USE_IPV6
888
    else if(curlx_inet_pton(AF_INET6, hostname, &addr)) {
889
      return CURL_SSL_PEER_IPV6;
890
    }
891
#endif
892
  }
893
  return CURL_SSL_PEER_DNS;
894
}
895
896
CURLcode Curl_ssl_peer_init(struct ssl_peer *ssl_peer,
897
                            struct Curl_peer *origin,
898
                            struct Curl_peer *peer,
899
                            struct ssl_primary_config *sslc,
900
                            const char *tls_id,
901
                            uint8_t transport)
902
{
903
  CURLcode result = CURLE_OUT_OF_MEMORY;
904
905
  /* We expect a clean struct, e.g. called only ONCE */
906
  if(!ssl_peer || !origin) {
907
    DEBUGASSERT(0);
908
    return CURLE_FAILED_INIT;
909
  }
910
  DEBUGASSERT(!ssl_peer->origin);
911
  DEBUGASSERT(!ssl_peer->peer);
912
  DEBUGASSERT(!ssl_peer->sni);
913
  ssl_peer->transport = transport;
914
915
  Curl_peer_link(&ssl_peer->origin, origin);
916
  Curl_peer_link(&ssl_peer->peer, peer);
917
  ssl_peer->type = get_peer_type(origin->hostname);
918
  if(ssl_peer->type == CURL_SSL_PEER_DNS) {
919
    /* not an IP address, normalize according to RCC 6066 ch. 3,
920
     * max len of SNI is 2^16-1, no trailing dot */
921
    size_t len = strlen(origin->hostname);
922
    if(len && (origin->hostname[len - 1] == '.'))
923
      len--;
924
    if(len < USHRT_MAX) {
925
      ssl_peer->sni = curlx_calloc(1, len + 1);
926
      if(!ssl_peer->sni)
927
        goto out;
928
      Curl_strntolower(ssl_peer->sni, origin->hostname, len);
929
      ssl_peer->sni[len] = 0;
930
    }
931
  }
932
933
  result = Curl_ssl_peer_key_make(ssl_peer, sslc, tls_id,
934
                                  &ssl_peer->scache_key);
935
936
out:
937
  if(result)
938
    Curl_ssl_peer_cleanup(ssl_peer);
939
  return result;
940
}
941
942
static void ssl_cf_destroy(struct Curl_cfilter *cf, struct Curl_easy *data)
943
{
944
  struct ssl_connect_data *connssl = cf->ctx;
945
  if(connssl) {
946
    connssl->ssl_impl->close(cf, data);
947
    connssl->state = ssl_connection_none;
948
    connssl->connecting_state = ssl_connect_1;
949
    connssl->prefs_checked = FALSE;
950
    Curl_ssl_peer_cleanup(&connssl->peer);
951
    Curl_ssl_session_destroy(connssl->session);
952
    cf_ctx_free(connssl);
953
    cf->ctx = NULL;
954
  }
955
  cf->connected = FALSE;
956
}
957
958
static CURLcode ssl_cf_connect(struct Curl_cfilter *cf,
959
                               struct Curl_easy *data,
960
                               bool *done)
961
{
962
  struct ssl_connect_data *connssl = cf->ctx;
963
  struct cf_call_data save;
964
  CURLcode result;
965
966
  if(cf->connected && (connssl->state != ssl_connection_deferred)) {
967
    *done = TRUE;
968
    return CURLE_OK;
969
  }
970
971
  if(!cf->next || !connssl->peer.origin) {
972
    *done = FALSE;
973
    return CURLE_FAILED_INIT;
974
  }
975
976
  if(!cf->next->connected) {
977
    result = cf->next->cft->do_connect(cf->next, data, done);
978
    if(result || !*done)
979
      return result;
980
  }
981
982
  CF_DATA_SAVE(save, cf, data);
983
  CURL_TRC_CF(data, cf, "cf_connect()");
984
  DEBUGASSERT(connssl);
985
986
  *done = FALSE;
987
988
  if(!connssl->prefs_checked) {
989
    if(!ssl_prefs_check(data)) {
990
      result = CURLE_SSL_CONNECT_ERROR;
991
      goto out;
992
    }
993
    connssl->prefs_checked = TRUE;
994
  }
995
996
  result = connssl->ssl_impl->do_connect(cf, data, done);
997
998
  if(!result && *done) {
999
    cf->connected = TRUE;
1000
    if(connssl->state == ssl_connection_complete) {
1001
      connssl->handshake_done = *Curl_pgrs_now(data);
1002
    }
1003
    if(Curl_tls_keylog_enabled()) {
1004
      infof(data, "SSLKEYLOGFILE set, all TLS secrets are logged to '%s'",
1005
            Curl_tls_keylog_file_name());
1006
#ifdef LIBRESSL_VERSION_NUMBER
1007
      infof(data, "Note LibreSSL only supports SSLKEYLOGFILE for TLS <= 1.2");
1008
#endif
1009
    }
1010
    /* Connection can be deferred when sending early data */
1011
    DEBUGASSERT(connssl->state == ssl_connection_complete ||
1012
                connssl->state == ssl_connection_deferred);
1013
    DEBUGASSERT(connssl->state != ssl_connection_deferred ||
1014
                connssl->earlydata_state > ssl_earlydata_none);
1015
  }
1016
out:
1017
  CURL_TRC_CF(data, cf, "cf_connect() -> %d, done=%d", (int)result, *done);
1018
  CF_DATA_RESTORE(cf, save);
1019
  return result;
1020
}
1021
1022
static CURLcode ssl_cf_set_earlydata(struct Curl_cfilter *cf,
1023
                                     struct Curl_easy *data,
1024
                                     const void *buf, size_t blen)
1025
{
1026
  struct ssl_connect_data *connssl = cf->ctx;
1027
  size_t nwritten = 0;
1028
  CURLcode result = CURLE_OK;
1029
1030
  DEBUGASSERT(connssl->earlydata_state == ssl_earlydata_await);
1031
  DEBUGASSERT(Curl_bufq_is_empty(&connssl->earlydata));
1032
  if(blen) {
1033
    if(blen > connssl->earlydata_max)
1034
      blen = connssl->earlydata_max;
1035
    result = Curl_bufq_write(&connssl->earlydata, buf, blen, &nwritten);
1036
    CURL_TRC_CF(data, cf, "ssl_cf_set_earlydata(len=%zu) -> %zu",
1037
                blen, nwritten);
1038
    if(result)
1039
      return result;
1040
  }
1041
  return CURLE_OK;
1042
}
1043
1044
static CURLcode ssl_cf_connect_deferred(struct Curl_cfilter *cf,
1045
                                        struct Curl_easy *data,
1046
                                        const void *buf, size_t blen,
1047
                                        bool *done)
1048
{
1049
  struct ssl_connect_data *connssl = cf->ctx;
1050
  CURLcode result = CURLE_OK;
1051
1052
  DEBUGASSERT(connssl->state == ssl_connection_deferred);
1053
  *done = FALSE;
1054
  if(connssl->earlydata_state == ssl_earlydata_await) {
1055
    result = ssl_cf_set_earlydata(cf, data, buf, blen);
1056
    if(result)
1057
      return result;
1058
    /* we buffered any early data we would like to send. Actually
1059
     * do the connect now which sends it and performs the handshake. */
1060
    connssl->earlydata_state = ssl_earlydata_sending;
1061
    connssl->earlydata_skip = Curl_bufq_len(&connssl->earlydata);
1062
  }
1063
1064
  result = ssl_cf_connect(cf, data, done);
1065
1066
  if(!result && *done) {
1067
    if(!connssl->stats_reported && (cf->cft == &Curl_cft_ssl)) {
1068
      Curl_pgrsTimeWas(data, TIMER_APPCONNECT, connssl->handshake_done);
1069
      connssl->stats_reported = TRUE;
1070
    }
1071
    switch(connssl->earlydata_state) {
1072
    case ssl_earlydata_none:
1073
      break;
1074
    case ssl_earlydata_accepted:
1075
      if(!Curl_ssl_cf_is_proxy(cf))
1076
        Curl_pgrsEarlyData(data, (curl_off_t)connssl->earlydata_skip);
1077
      infof(data, "Server accepted %zu bytes of TLS early data.",
1078
            connssl->earlydata_skip);
1079
      break;
1080
    case ssl_earlydata_rejected:
1081
      if(!Curl_ssl_cf_is_proxy(cf))
1082
        Curl_pgrsEarlyData(data, -(curl_off_t)connssl->earlydata_skip);
1083
      infof(data, "Server rejected TLS early data.");
1084
      connssl->earlydata_skip = 0;
1085
      break;
1086
    default:
1087
      /* This should not happen. Either we do not use early data or we
1088
       * should know if it was accepted or not. */
1089
      DEBUGASSERT(NULL);
1090
      break;
1091
    }
1092
  }
1093
  return result;
1094
}
1095
1096
static bool ssl_cf_data_pending(struct Curl_cfilter *cf,
1097
                                const struct Curl_easy *data)
1098
{
1099
  struct ssl_connect_data *connssl = cf->ctx;
1100
  struct cf_call_data save;
1101
  bool pending;
1102
1103
  CF_DATA_SAVE(save, cf, data);
1104
  if(connssl->ssl_impl->data_pending &&
1105
     connssl->ssl_impl->data_pending(cf, data))
1106
    pending = TRUE;
1107
  else
1108
    pending = cf->next->cft->has_data_pending(cf->next, data);
1109
  CF_DATA_RESTORE(cf, save);
1110
  return pending;
1111
}
1112
1113
static CURLcode ssl_cf_send(struct Curl_cfilter *cf,
1114
                            struct Curl_easy *data,
1115
                            const uint8_t *buf, size_t blen,
1116
                            bool eos, size_t *pnwritten)
1117
{
1118
  struct ssl_connect_data *connssl = cf->ctx;
1119
  struct cf_call_data save;
1120
  CURLcode result = CURLE_OK;
1121
1122
  (void)eos;
1123
  *pnwritten = 0;
1124
  CF_DATA_SAVE(save, cf, data);
1125
1126
  if(connssl->state == ssl_connection_deferred) {
1127
    bool done = FALSE;
1128
    result = ssl_cf_connect_deferred(cf, data, buf, blen, &done);
1129
    if(result)
1130
      goto out;
1131
    else if(!done) {
1132
      result = CURLE_AGAIN;
1133
      goto out;
1134
    }
1135
    DEBUGASSERT(connssl->state == ssl_connection_complete);
1136
  }
1137
1138
  if(connssl->earlydata_skip) {
1139
    if(connssl->earlydata_skip >= blen) {
1140
      connssl->earlydata_skip -= blen;
1141
      result = CURLE_OK;
1142
      *pnwritten = blen;
1143
      goto out;
1144
    }
1145
    else {
1146
      *pnwritten = connssl->earlydata_skip;
1147
      buf = buf + connssl->earlydata_skip;
1148
      blen -= connssl->earlydata_skip;
1149
      connssl->earlydata_skip = 0;
1150
    }
1151
  }
1152
1153
  /* OpenSSL and maybe other TLS libs do not like 0-length writes. Skip. */
1154
  if(blen > 0) {
1155
    size_t nwritten;
1156
    result = connssl->ssl_impl->send_plain(cf, data, buf, blen, &nwritten);
1157
    if(!result)
1158
      *pnwritten += nwritten;
1159
  }
1160
1161
out:
1162
  CF_DATA_RESTORE(cf, save);
1163
  return result;
1164
}
1165
1166
static CURLcode ssl_cf_recv(struct Curl_cfilter *cf,
1167
                            struct Curl_easy *data, char *buf, size_t len,
1168
                            size_t *pnread)
1169
{
1170
  struct ssl_connect_data *connssl = cf->ctx;
1171
  struct cf_call_data save;
1172
  CURLcode result = CURLE_OK;
1173
1174
  CF_DATA_SAVE(save, cf, data);
1175
  *pnread = 0;
1176
  if(connssl->state == ssl_connection_deferred) {
1177
    bool done = FALSE;
1178
    result = ssl_cf_connect_deferred(cf, data, NULL, 0, &done);
1179
    if(result)
1180
      goto out;
1181
    else if(!done) {
1182
      result = CURLE_AGAIN;
1183
      goto out;
1184
    }
1185
    DEBUGASSERT(connssl->state == ssl_connection_complete);
1186
  }
1187
1188
  result = connssl->ssl_impl->recv_plain(cf, data, buf, len, pnread);
1189
1190
out:
1191
  CF_DATA_RESTORE(cf, save);
1192
  return result;
1193
}
1194
1195
static CURLcode ssl_cf_shutdown(struct Curl_cfilter *cf,
1196
                                struct Curl_easy *data,
1197
                                bool *done)
1198
{
1199
  struct ssl_connect_data *connssl = cf->ctx;
1200
  CURLcode result = CURLE_OK;
1201
1202
  *done = TRUE;
1203
  /* If we have done the SSL handshake, shut down the connection cleanly */
1204
  if(cf->connected && (connssl->state == ssl_connection_complete) &&
1205
     !cf->shutdown && Curl_ssl->shut_down) {
1206
    struct cf_call_data save;
1207
1208
    CF_DATA_SAVE(save, cf, data);
1209
    result = connssl->ssl_impl->shut_down(cf, data, TRUE, done);
1210
    CURL_TRC_CF(data, cf, "cf_shutdown -> %d, done=%d", (int)result, *done);
1211
    CF_DATA_RESTORE(cf, save);
1212
    cf->shutdown = (result || *done);
1213
  }
1214
  return result;
1215
}
1216
1217
static CURLcode ssl_cf_adjust_pollset(struct Curl_cfilter *cf,
1218
                                      struct Curl_easy *data,
1219
                                      struct easy_pollset *ps)
1220
{
1221
  struct ssl_connect_data *connssl = cf->ctx;
1222
  struct cf_call_data save;
1223
  CURLcode result;
1224
1225
  CF_DATA_SAVE(save, cf, data);
1226
  result = connssl->ssl_impl->adjust_pollset(cf, data, ps);
1227
  CF_DATA_RESTORE(cf, save);
1228
  return result;
1229
}
1230
1231
static CURLcode ssl_cf_query(struct Curl_cfilter *cf,
1232
                             struct Curl_easy *data,
1233
                             int query, int *pres1, void *pres2)
1234
{
1235
  struct ssl_connect_data *connssl = cf->ctx;
1236
1237
  switch(query) {
1238
  case CF_QUERY_SSL_INFO:
1239
  case CF_QUERY_SSL_CTX_INFO:
1240
    if(!Curl_ssl_cf_is_proxy(cf)) {
1241
      struct curl_tlssessioninfo *info = pres2;
1242
      struct cf_call_data save;
1243
      CF_DATA_SAVE(save, cf, data);
1244
      info->backend = Curl_ssl_backend();
1245
      info->internals = connssl->ssl_impl->get_internals(
1246
        cf->ctx, (query == CF_QUERY_SSL_INFO) ?
1247
        CURLINFO_TLS_SSL_PTR : CURLINFO_TLS_SESSION);
1248
      CF_DATA_RESTORE(cf, save);
1249
      return CURLE_OK;
1250
    }
1251
    break;
1252
  case CF_QUERY_ALPN_NEGOTIATED: {
1253
    const char **palpn = pres2;
1254
    DEBUGASSERT(palpn);
1255
    *palpn = connssl->negotiated.alpn;
1256
    CURL_TRC_CF(data, cf, "query ALPN: returning '%s'", *palpn);
1257
    return CURLE_OK;
1258
  }
1259
  default:
1260
    break;
1261
  }
1262
  return cf->next ?
1263
    cf->next->cft->query(cf->next, data, query, pres1, pres2) :
1264
    CURLE_UNKNOWN_OPTION;
1265
}
1266
1267
static CURLcode ssl_cf_cntrl(struct Curl_cfilter *cf,
1268
                             struct Curl_easy *data,
1269
                             int event, int arg1, void *arg2)
1270
{
1271
  struct ssl_connect_data *connssl = cf->ctx;
1272
1273
  (void)arg1;
1274
  (void)arg2;
1275
  (void)data;
1276
  switch(event) {
1277
  case CF_CTRL_CONN_INFO_UPDATE:
1278
    if(connssl->negotiated.alpn && !cf->sockindex) {
1279
      if(!strcmp("http/1.1", connssl->negotiated.alpn))
1280
        cf->conn->httpversion_seen = 11;
1281
      else if(!strcmp("h2", connssl->negotiated.alpn))
1282
        cf->conn->httpversion_seen = 20;
1283
      else if(!strcmp("h3", connssl->negotiated.alpn))
1284
        cf->conn->httpversion_seen = 30;
1285
    }
1286
    break;
1287
  case CF_CTRL_REPORT_STATS:
1288
    if(cf->connected && !connssl->stats_reported &&
1289
       (cf->cft == &Curl_cft_ssl) &&
1290
       (connssl->handshake_done.tv_sec || connssl->handshake_done.tv_usec)) {
1291
      Curl_pgrsTimeWas(data, TIMER_APPCONNECT, connssl->handshake_done);
1292
      connssl->stats_reported = TRUE;
1293
    }
1294
    break;
1295
  }
1296
  return CURLE_OK;
1297
}
1298
1299
static bool cf_ssl_is_alive(struct Curl_cfilter *cf, struct Curl_easy *data,
1300
                            bool *input_pending)
1301
{
1302
  /*
1303
   * This function tries to determine connection status.
1304
   */
1305
  return cf->next ?
1306
    cf->next->cft->is_alive(cf->next, data, input_pending) :
1307
    FALSE; /* pessimistic in absence of data */
1308
}
1309
1310
struct Curl_cftype Curl_cft_ssl = {
1311
  "SSL",
1312
  CF_TYPE_SSL,
1313
  CURL_LOG_LVL_NONE,
1314
  ssl_cf_destroy,
1315
  ssl_cf_connect,
1316
  ssl_cf_shutdown,
1317
  ssl_cf_adjust_pollset,
1318
  ssl_cf_data_pending,
1319
  ssl_cf_send,
1320
  ssl_cf_recv,
1321
  ssl_cf_cntrl,
1322
  cf_ssl_is_alive,
1323
  Curl_cf_def_conn_keep_alive,
1324
  ssl_cf_query,
1325
};
1326
1327
#ifndef CURL_DISABLE_PROXY
1328
1329
struct Curl_cftype Curl_cft_ssl_proxy = {
1330
  "SSL-PROXY",
1331
  CF_TYPE_SSL | CF_TYPE_PROXY,
1332
  CURL_LOG_LVL_NONE,
1333
  ssl_cf_destroy,
1334
  ssl_cf_connect,
1335
  ssl_cf_shutdown,
1336
  ssl_cf_adjust_pollset,
1337
  ssl_cf_data_pending,
1338
  ssl_cf_send,
1339
  ssl_cf_recv,
1340
  Curl_cf_def_cntrl,
1341
  cf_ssl_is_alive,
1342
  Curl_cf_def_conn_keep_alive,
1343
  ssl_cf_query,
1344
};
1345
1346
#endif /* !CURL_DISABLE_PROXY */
1347
1348
static CURLcode cf_ssl_create(struct Curl_cfilter **pcf,
1349
                              struct Curl_easy *data,
1350
                              struct connectdata *conn)
1351
{
1352
  struct Curl_cfilter *cf = NULL;
1353
  struct ssl_connect_data *ctx;
1354
  CURLcode result;
1355
1356
  DEBUGASSERT(data->conn);
1357
1358
#ifdef CURL_DISABLE_HTTP
1359
  (void)conn;
1360
  /* We only support ALPN for HTTP so far. */
1361
  DEBUGASSERT(!conn->bits.tls_enable_alpn);
1362
  ctx = cf_ctx_new(data, NULL);
1363
#else
1364
  ctx = cf_ctx_new(data, alpn_get_spec(data->state.http_neg.wanted,
1365
                                       data->state.http_neg.preferred,
1366
                                       (bool)data->state.http_neg.only_10,
1367
                                       (bool)conn->bits.tls_enable_alpn));
1368
#endif
1369
  if(!ctx) {
1370
    result = CURLE_OUT_OF_MEMORY;
1371
    goto out;
1372
  }
1373
1374
  result = Curl_cf_create(&cf, &Curl_cft_ssl, ctx);
1375
1376
out:
1377
  if(result)
1378
    cf_ctx_free(ctx);
1379
  *pcf = result ? NULL : cf;
1380
  return result;
1381
}
1382
1383
static CURLcode cf_ssl_peer_init(struct Curl_cfilter *cf,
1384
                                 struct Curl_peer *origin,
1385
                                 struct Curl_peer *peer,
1386
                                 struct ssl_primary_config *sslc)
1387
{
1388
  struct ssl_connect_data *connssl = cf->ctx;
1389
  char tls_id[80];
1390
  connssl->ssl_impl->version(tls_id, sizeof(tls_id) - 1);
1391
  return Curl_ssl_peer_init(&connssl->peer, origin, peer, sslc,
1392
                            tls_id, TRNSPRT_TCP);
1393
}
1394
1395
CURLcode Curl_ssl_cfilter_add(struct Curl_easy *data,
1396
                              struct Curl_peer *origin,
1397
                              struct connectdata *conn,
1398
                              int8_t sockindex)
1399
{
1400
  struct Curl_cfilter *cf;
1401
  struct Curl_peer *peer = (sockindex == SECONDARYSOCKET) ?
1402
    conn->via_peer2 : conn->via_peer;
1403
  CURLcode result;
1404
1405
  result = cf_ssl_create(&cf, data, conn);
1406
  if(!result)
1407
    result = cf_ssl_peer_init(cf, origin, peer, &conn->ssl_config);
1408
  if(!result)
1409
    Curl_conn_cf_add(data, conn, sockindex, cf);
1410
  else if(cf)
1411
    Curl_conn_cf_discard_chain(&cf, data);
1412
  return result;
1413
}
1414
1415
CURLcode Curl_cf_ssl_insert_after(struct Curl_cfilter *cf_at,
1416
                                  struct Curl_easy *data,
1417
                                  struct Curl_peer *origin,
1418
                                  struct Curl_peer *peer)
1419
{
1420
  struct Curl_cfilter *cf;
1421
  CURLcode result;
1422
1423
  result = cf_ssl_create(&cf, data, cf_at->conn);
1424
  if(!result)
1425
    result = cf_ssl_peer_init(cf, origin, peer, &cf_at->conn->ssl_config);
1426
  if(!result) {
1427
    Curl_conn_cf_insert_after(cf_at, cf);
1428
#if defined(USE_HTTPSRR) && defined(USE_ECH)
1429
    /* When using ECH, kick off the HTTPS-RR resolve */
1430
    if((origin->scheme->family == CURLPROTO_HTTP) &&
1431
       CURLECH_ENABLED(data) &&
1432
       Curl_ssl_supports(data, SSLSUPP_ECH) &&
1433
       (data->set.tls_ech != CURLECH_GREASE) &&
1434
       !CURL_EASY_STR(data, STRING_ECH_CONFIG)) {
1435
      result = Curl_conn_dns_add_https_resolve(data, cf->conn, cf->sockindex,
1436
                                               origin);
1437
    }
1438
#endif /* USE_HTTPSRR && USE_ECH */
1439
  }
1440
  else if(cf)
1441
    Curl_conn_cf_discard_chain(&cf, data);
1442
  return result;
1443
}
1444
1445
#ifndef CURL_DISABLE_PROXY
1446
1447
static CURLcode cf_ssl_proxy_create(struct Curl_cfilter **pcf,
1448
                                    struct Curl_easy *data,
1449
                                    struct connectdata *conn)
1450
{
1451
  struct Curl_cfilter *cf = NULL;
1452
  struct ssl_connect_data *ctx;
1453
  CURLcode result;
1454
  /* ALPN is default, but if user explicitly disables it, obey */
1455
  bool use_alpn = (bool)data->set.ssl_enable_alpn;
1456
  http_majors wanted = CURL_HTTP_V1x;
1457
1458
  (void)conn;
1459
#ifdef USE_HTTP2
1460
  if(conn->http_proxy.proxytype == CURLPROXY_HTTPS2) {
1461
    use_alpn = TRUE;
1462
    wanted = (CURL_HTTP_V1x | CURL_HTTP_V2x);
1463
  }
1464
#endif
1465
1466
  ctx = cf_ctx_new(data, alpn_get_spec(wanted, 0, FALSE, use_alpn));
1467
  if(!ctx) {
1468
    result = CURLE_OUT_OF_MEMORY;
1469
    goto out;
1470
  }
1471
  result = Curl_cf_create(&cf, &Curl_cft_ssl_proxy, ctx);
1472
1473
out:
1474
  if(result)
1475
    cf_ctx_free(ctx);
1476
  *pcf = result ? NULL : cf;
1477
  return result;
1478
}
1479
1480
CURLcode Curl_cf_ssl_proxy_insert_after(struct Curl_cfilter *cf_at,
1481
                                        struct Curl_easy *data,
1482
                                        struct Curl_peer *peer)
1483
{
1484
  struct Curl_cfilter *cf;
1485
  CURLcode result;
1486
1487
  result = cf_ssl_proxy_create(&cf, data, cf_at->conn);
1488
  if(!result)
1489
    result = cf_ssl_peer_init(cf, peer, NULL, &cf_at->conn->proxy_ssl_config);
1490
  if(!result)
1491
    Curl_conn_cf_insert_after(cf_at, cf);
1492
  else if(cf)
1493
    Curl_conn_cf_discard_chain(&cf, data);
1494
  return result;
1495
}
1496
1497
#endif /* !CURL_DISABLE_PROXY */
1498
1499
bool Curl_ssl_supports(struct Curl_easy *data, unsigned int ssl_option)
1500
{
1501
  (void)data;
1502
  return (Curl_ssl->supports & ssl_option);
1503
}
1504
1505
static CURLcode vtls_shutdown_blocking(struct Curl_cfilter *cf,
1506
                                       struct Curl_easy *data,
1507
                                       bool send_shutdown, bool *done)
1508
{
1509
  struct ssl_connect_data *connssl = cf->ctx;
1510
  struct cf_call_data save;
1511
  CURLcode result = CURLE_OK;
1512
  timediff_t timeout_ms;
1513
  int what, loop = 10;
1514
1515
  if(cf->shutdown) {
1516
    *done = TRUE;
1517
    return CURLE_OK;
1518
  }
1519
  CF_DATA_SAVE(save, cf, data);
1520
1521
  *done = FALSE;
1522
  while(!result && !*done && loop--) {
1523
    timeout_ms = Curl_shutdown_timeleft(data, cf->conn, cf->sockindex);
1524
1525
    if(timeout_ms < 0) {
1526
      /* no need to continue if time is already up */
1527
      failf(data, "SSL shutdown timeout");
1528
      result = CURLE_OPERATION_TIMEDOUT;
1529
      goto out;
1530
    }
1531
1532
    result = connssl->ssl_impl->shut_down(cf, data, send_shutdown, done);
1533
    if(result || *done)
1534
      goto out;
1535
1536
    if(connssl->io_need) {
1537
      what = Curl_conn_cf_poll(cf, data, timeout_ms);
1538
      if(what < 0) {
1539
        /* fatal error */
1540
        failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
1541
        result = CURLE_RECV_ERROR;
1542
        goto out;
1543
      }
1544
      else if(what == 0) {
1545
        /* timeout */
1546
        failf(data, "SSL shutdown timeout");
1547
        result = CURLE_OPERATION_TIMEDOUT;
1548
        goto out;
1549
      }
1550
      /* socket is readable or writable */
1551
    }
1552
  }
1553
out:
1554
  CF_DATA_RESTORE(cf, save);
1555
  cf->shutdown = (result || *done);
1556
  return result;
1557
}
1558
1559
CURLcode Curl_ssl_cfilter_remove(struct Curl_easy *data,
1560
                                 int8_t sockindex, bool send_shutdown)
1561
{
1562
  struct Curl_cfilter *cf, *head;
1563
  CURLcode result = CURLE_OK;
1564
1565
  head = data->conn ? data->conn->cfilter[sockindex] : NULL;
1566
  for(cf = head; cf; cf = cf->next) {
1567
    if(cf->cft == &Curl_cft_ssl) {
1568
      bool done;
1569
      CURL_TRC_CF(data, cf, "shutdown and remove SSL, start");
1570
      Curl_shutdown_start(data, sockindex, 0);
1571
      result = vtls_shutdown_blocking(cf, data, send_shutdown, &done);
1572
      Curl_shutdown_clear(data, sockindex);
1573
      if(!result && !done) /* blocking failed? */
1574
        result = CURLE_SSL_SHUTDOWN_FAILED;
1575
      Curl_conn_cf_discard(&cf, data);
1576
      CURL_TRC_CF(data, cf, "shutdown and remove SSL, done -> %d",
1577
                  (int)result);
1578
      break;
1579
    }
1580
  }
1581
  return result;
1582
}
1583
1584
bool Curl_ssl_cf_is_proxy(struct Curl_cfilter *cf)
1585
{
1586
  return (cf->cft->flags & CF_TYPE_SSL) && (cf->cft->flags & CF_TYPE_PROXY);
1587
}
1588
1589
struct ssl_config_data *Curl_ssl_cf_get_config(struct Curl_cfilter *cf,
1590
                                               struct Curl_easy *data)
1591
{
1592
#ifdef CURL_DISABLE_PROXY
1593
  (void)cf;
1594
  return &data->set.ssl;
1595
#else
1596
  return Curl_ssl_cf_is_proxy(cf) ? &data->set.proxy_ssl : &data->set.ssl;
1597
#endif
1598
}
1599
1600
struct ssl_primary_config *Curl_ssl_cf_get_primary_config(
1601
  struct Curl_cfilter *cf)
1602
{
1603
#ifdef CURL_DISABLE_PROXY
1604
  return &cf->conn->ssl_config;
1605
#else
1606
  return Curl_ssl_cf_is_proxy(cf) ?
1607
    &cf->conn->proxy_ssl_config : &cf->conn->ssl_config;
1608
#endif
1609
}
1610
1611
CURLcode Curl_alpn_to_proto_buf(struct alpn_proto_buf *buf,
1612
                                const struct alpn_spec *spec)
1613
{
1614
  size_t i, len;
1615
  int off = 0;
1616
  unsigned char blen;
1617
1618
  memset(buf, 0, sizeof(*buf));
1619
  for(i = 0; spec && i < spec->count; ++i) {
1620
    len = strlen(spec->entries[i]);
1621
    if(len >= ALPN_NAME_MAX)
1622
      return CURLE_FAILED_INIT;
1623
    blen = (unsigned char)len;
1624
    if(off + blen + 1 >= (int)sizeof(buf->data))
1625
      return CURLE_FAILED_INIT;
1626
    buf->data[off++] = blen;
1627
    memcpy(buf->data + off, spec->entries[i], blen);
1628
    off += blen;
1629
  }
1630
  buf->len = off;
1631
  return CURLE_OK;
1632
}
1633
1634
CURLcode Curl_alpn_to_proto_str(struct alpn_proto_buf *buf,
1635
                                const struct alpn_spec *spec)
1636
{
1637
  size_t i, len;
1638
  size_t off = 0;
1639
1640
  memset(buf, 0, sizeof(*buf));
1641
  for(i = 0; spec && i < spec->count; ++i) {
1642
    len = strlen(spec->entries[i]);
1643
    if(len >= ALPN_NAME_MAX)
1644
      return CURLE_FAILED_INIT;
1645
    if(off + len + 2 >= sizeof(buf->data))
1646
      return CURLE_FAILED_INIT;
1647
    if(off)
1648
      buf->data[off++] = ',';
1649
    memcpy(buf->data + off, spec->entries[i], len);
1650
    off += len;
1651
  }
1652
  buf->data[off] = '\0';
1653
  buf->len = (int)off;
1654
  return CURLE_OK;
1655
}
1656
1657
bool Curl_alpn_contains_proto(const struct alpn_spec *spec,
1658
                              const char *proto)
1659
{
1660
  size_t i, plen = proto ? strlen(proto) : 0;
1661
  for(i = 0; spec && plen && i < spec->count; ++i) {
1662
    size_t slen = strlen(spec->entries[i]);
1663
    if((slen == plen) && !memcmp(proto, spec->entries[i], plen))
1664
      return TRUE;
1665
  }
1666
  return FALSE;
1667
}
1668
1669
void Curl_alpn_restrict_to(struct alpn_spec *spec, const char *proto)
1670
{
1671
  size_t plen = strlen(proto);
1672
  DEBUGASSERT(plen < sizeof(spec->entries[0]));
1673
  if(plen < sizeof(spec->entries[0])) {
1674
    memcpy(spec->entries[0], proto, plen + 1);
1675
    spec->count = 1;
1676
  }
1677
}
1678
1679
void Curl_alpn_copy(struct alpn_spec *dest, const struct alpn_spec *src)
1680
{
1681
  if(src)
1682
    memcpy(dest, src, sizeof(*dest));
1683
  else
1684
    memset(dest, 0, sizeof(*dest));
1685
}
1686
1687
CURLcode Curl_alpn_set_negotiated(struct Curl_cfilter *cf,
1688
                                  struct Curl_easy *data,
1689
                                  struct ssl_connect_data *connssl,
1690
                                  const unsigned char *proto,
1691
                                  size_t proto_len)
1692
{
1693
  CURLcode result = CURLE_OK;
1694
  (void)cf;
1695
1696
  if(connssl->negotiated.alpn) {
1697
    /* When we ask for a specific ALPN protocol, we need the confirmation
1698
     * of it by the server, as we have installed protocol handler and
1699
     * connection filter chain for exactly this protocol. */
1700
    if(!proto_len) {
1701
      failf(data, "ALPN: asked for '%s' from previous session, "
1702
            "but server did not confirm it. Refusing to continue.",
1703
            connssl->negotiated.alpn);
1704
      result = CURLE_SSL_CONNECT_ERROR;
1705
      goto out;
1706
    }
1707
    else if(!proto) {
1708
      DEBUGASSERT(0); /* with length, we need a pointer */
1709
      result = CURLE_SSL_CONNECT_ERROR;
1710
      goto out;
1711
    }
1712
    else if((strlen(connssl->negotiated.alpn) != proto_len) ||
1713
            memcmp(connssl->negotiated.alpn, proto, proto_len)) {
1714
      failf(data, "ALPN: asked for '%s' from previous session, but server "
1715
            "selected '%.*s'. Refusing to continue.",
1716
            connssl->negotiated.alpn, (int)proto_len, proto);
1717
      result = CURLE_SSL_CONNECT_ERROR;
1718
      goto out;
1719
    }
1720
    /* ALPN is exactly what we asked for, done. */
1721
    infof(data, "ALPN: server confirmed to use '%s'",
1722
          connssl->negotiated.alpn);
1723
    goto out;
1724
  }
1725
1726
  if(proto && proto_len) {
1727
    if(memchr(proto, '\0', proto_len)) {
1728
      failf(data, "ALPN: server selected protocol contains NUL. "
1729
                  "Refusing to continue.");
1730
      result = CURLE_SSL_CONNECT_ERROR;
1731
      goto out;
1732
    }
1733
    connssl->negotiated.alpn = curlx_memdup0((const char *)proto, proto_len);
1734
    if(!connssl->negotiated.alpn)
1735
      return CURLE_OUT_OF_MEMORY;
1736
  }
1737
1738
  if(proto && proto_len) {
1739
    if(connssl->state == ssl_connection_deferred)
1740
      infof(data, VTLS_INFOF_ALPN_DEFERRED, (int)proto_len, proto);
1741
    else
1742
      infof(data, VTLS_INFOF_ALPN_ACCEPTED, (int)proto_len, proto);
1743
  }
1744
  else {
1745
    if(connssl->state == ssl_connection_deferred)
1746
      infof(data, VTLS_INFOF_NO_ALPN_DEFERRED);
1747
    else
1748
      infof(data, VTLS_INFOF_NO_ALPN);
1749
  }
1750
1751
out:
1752
  return result;
1753
}
1754
1755
CURLcode Curl_on_session_reuse(struct Curl_cfilter *cf,
1756
                               struct Curl_easy *data,
1757
                               struct alpn_spec *alpns,
1758
                               struct Curl_ssl_session *scs,
1759
                               bool *do_early_data, bool early_data_allowed)
1760
{
1761
  struct ssl_connect_data *connssl = cf->ctx;
1762
  CURLcode result = CURLE_OK;
1763
1764
  *do_early_data = FALSE;
1765
1766
  if(!early_data_allowed) {
1767
    CURL_TRC_CF(data, cf, "SSL session does not allow earlydata");
1768
  }
1769
  else if(!Curl_alpn_contains_proto(alpns, scs->alpn)) {
1770
    CURL_TRC_CF(data, cf, "SSL session has different ALPN, no early data");
1771
  }
1772
  else {
1773
    infof(data, "SSL session allows %zu bytes of early data, "
1774
          "reusing ALPN '%s'", connssl->earlydata_max, scs->alpn);
1775
    connssl->earlydata_state = ssl_earlydata_await;
1776
    connssl->state = ssl_connection_deferred;
1777
    result = Curl_alpn_set_negotiated(cf, data, connssl,
1778
                                      (const unsigned char *)scs->alpn,
1779
                                      scs->alpn ? strlen(scs->alpn) : 0);
1780
    *do_early_data = !result;
1781
  }
1782
  return result;
1783
}
1784
1785
struct Curl_ssl_session *Curl_ssl_get_cf_session(struct Curl_easy *data,
1786
                                                 const struct Curl_cftype *cft,
1787
                                                 int8_t sockindex)
1788
{
1789
  if(data->conn &&
1790
#ifndef CURL_DISABLE_PROXY
1791
     ((cft == &Curl_cft_ssl) || (cft == &Curl_cft_ssl_proxy))) {
1792
#else
1793
     (cft == &Curl_cft_ssl)) {
1794
#endif
1795
    struct Curl_cfilter *cf1 = data->conn->cfilter[sockindex];
1796
    for(; cf1; cf1 = cf1->next) {
1797
      /* A tunneling proxy does not offer end2end encryption, even if
1798
       * it does SSL itself (e.g. QUIC H3 proxy) */
1799
      if(cf1->cft == cft)
1800
        break;
1801
    }
1802
    if(cf1) {
1803
      struct ssl_connect_data *connssl = cf1->ctx;
1804
      if(connssl)
1805
        return connssl->session;
1806
    }
1807
  }
1808
  return NULL;
1809
}
1810
1811
#endif /* USE_SSL */