Coverage Report

Created: 2026-04-29 07:01

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