Coverage Report

Created: 2026-10-28 06:38

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