Coverage Report

Created: 2026-06-15 07:03

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