Coverage Report

Created: 2026-07-14 07:09

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