Artifactspublic-v0

curl

master
ply4 git calls32 ms301 KiB3 cachedprotocol v2
1721 lines53 KiBRaw
1/***************************************************************************
2 * _ _ ____ _
3 * Project ___| | | | _ \| |
4 * / __| | | | |_) | |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
7 *
8 * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
9 * Copyright (C) Hoi-Ho Chan, <hoiho.chan@gmail.com>
10 *
11 * This software is licensed as described in the file COPYING, which
12 * you should have received as part of this distribution. The terms
13 * are also available at https://curl.se/docs/copyright.html.
14 *
15 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
16 * copies of the Software, and permit persons to whom the Software is
17 * furnished to do so, under the terms of the COPYING file.
18 *
19 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
20 * KIND, either express or implied.
21 *
22 * SPDX-License-Identifier: curl
23 *
24 ***************************************************************************/
25/*
26 * Source file for all mbedTLS-specific code for the TLS/SSL layer. No code
27 * but vtls.c should ever call or use these functions.
28 *
29 */
30#include "curl_setup.h"
32#ifdef USE_MBEDTLS
34/* Define this to enable lots of debugging for mbedTLS */
35/* #define MBEDTLS_DEBUG */
37#include <mbedtls/version.h>
38#if MBEDTLS_VERSION_NUMBER < 0x03020000
39#error "mbedTLS 3.2.0 or greater required"
40#endif
41#include <psa/crypto_config.h>
42#include <mbedtls/net_sockets.h>
43#include <mbedtls/ssl.h>
44#include <mbedtls/x509.h>
45#include <mbedtls/psa_util.h>
47#if MBEDTLS_VERSION_NUMBER < 0x04000000 && !defined(MBEDTLS_CTR_DRBG_C)
48#error "MBEDTLS_CTR_DRBG_C is required for mbedTLS 3.x."
49#endif
51#include <mbedtls/error.h>
52#if MBEDTLS_VERSION_NUMBER < 0x04000000
53#include <mbedtls/entropy.h>
54#include <mbedtls/ctr_drbg.h>
55#endif
56#ifdef MBEDTLS_DEBUG
57#include <mbedtls/debug.h>
58#endif
60#include "vtls/cipher_suite.h"
61#include "urldata.h"
62#include "curl_trc.h"
63#include "vtls/mbedtls.h"
64#include "vtls/vtls.h"
65#include "vtls/vtls_int.h"
66#include "vtls/vtls_scache.h"
67#include "vtls/x509asn1.h"
68#include "connect.h" /* for the connect timeout */
69#include "curlx/strdup.h"
70#include "curl_sha256.h"
72/* ALPN for http2 */
73#if defined(USE_HTTP2) && defined(MBEDTLS_SSL_ALPN)
74#define HAS_ALPN_MBEDTLS
75#endif
77struct mbed_ssl_backend_data {
78 mbedtls_ssl_context ssl;
79 mbedtls_x509_crt cacert;
80 mbedtls_x509_crt clicert;
81#ifdef MBEDTLS_X509_CRL_PARSE_C
82 mbedtls_x509_crl crl;
83#endif
84 mbedtls_pk_context pk;
85 mbedtls_ssl_config config;
86#ifdef HAS_ALPN_MBEDTLS
87 const char *protocols[3];
88#endif
89 int *ciphersuites;
90 size_t send_blocked_len;
91 BIT(initialized); /* mbedtls_ssl_context is initialized */
92 BIT(sent_shutdown);
93 BIT(send_blocked);
94};
96/** A context for random number generation (RNG).
97 */
98#if MBEDTLS_VERSION_NUMBER < 0x04000000
99struct rng_context_t {
100 mbedtls_entropy_context entropy;
101 mbedtls_ctr_drbg_context drbg;
102};
104static struct rng_context_t rng;
105#endif
107#ifndef MBEDTLS_ERROR_C
108#define mbedtls_strerror(a, b, c) b[0] = 0
109#endif
111#ifdef MBEDTLS_DEBUG
112static void mbed_debug(void *context, int level, const char *f_name,
113 int line_nb, const char *line)
115 struct Curl_easy *data = (struct Curl_easy *)context;
116 (void)level;
117 (void)line_nb;
118 (void)f_name;
120 if(data) {
121 size_t len = strlen(line);
122 if(len && (line[len - 1] == '\n'))
123 /* discount any trailing newline */
124 len--;
125 infof(data, "%.*s", (int)len, line);
126 }
128#endif
130static int mbedtls_bio_cf_write(void *bio,
131 const unsigned char *buf, size_t blen)
133 struct Curl_cfilter *cf = bio;
134 struct Curl_easy *data = CF_DATA_CURRENT(cf);
135 size_t nwritten;
136 CURLcode result;
138 DEBUGASSERT(data);
139 if(!data)
140 return 0;
142 result = Curl_conn_cf_send(cf->next, data, buf, blen, FALSE, &nwritten);
143 CURL_TRC_CF(data, cf, "mbedtls_bio_cf_out_write(len=%zu) -> %d, %zu",
144 blen, (int)result, nwritten);
145 if(result == CURLE_AGAIN)
146 return MBEDTLS_ERR_SSL_WANT_WRITE;
147 return result ? -1 : (int)nwritten;
150static int mbedtls_bio_cf_read(void *bio, unsigned char *buf, size_t blen)
152 struct Curl_cfilter *cf = bio;
153 struct Curl_easy *data = CF_DATA_CURRENT(cf);
154 size_t nread = 0;
155 CURLcode result;
157 DEBUGASSERT(data);
158 if(!data)
159 return 0;
160 /* OpenSSL catches this case, so should we. */
161 if(!buf)
162 return 0;
164 result = Curl_conn_cf_recv(cf->next, data, (char *)buf, blen, &nread);
165 CURL_TRC_CF(data, cf, "mbedtls_bio_cf_in_read(len=%zu) -> %d, %zu",
166 blen, (int)result, nread);
167 if(result == CURLE_AGAIN)
168 return MBEDTLS_ERR_SSL_WANT_READ;
169 /* nread is never larger than int here */
170 return result ? -1 : (int)nread;
173/* See:
174 * https://web.archive.org/web/20200921194007/tls.mbed.org/discussions/generic/howto-determine-exact-buffer-len-for-mbedtls_pk_write_pubkey_der
175 */
176#define RSA_PUB_DER_MAX_BYTES (38 + (2 * MBEDTLS_MPI_MAX_SIZE))
177#define ECP_PUB_DER_MAX_BYTES (30 + (2 * MBEDTLS_ECP_MAX_BYTES))
179#define PUB_DER_MAX_BYTES (RSA_PUB_DER_MAX_BYTES > ECP_PUB_DER_MAX_BYTES ? \
180 RSA_PUB_DER_MAX_BYTES : ECP_PUB_DER_MAX_BYTES)
182static CURLcode mbed_set_ssl_version_min_max(
183 struct Curl_easy *data,
184 struct mbed_ssl_backend_data *backend,
185 struct ssl_filter_config *conn_config)
187 mbedtls_ssl_protocol_version ver_min =
188#ifdef MBEDTLS_SSL_PROTO_TLS1_2
189 MBEDTLS_SSL_VERSION_TLS1_2
190#else
191 MBEDTLS_SSL_VERSION_TLS1_3
192#endif
193 ;
194 mbedtls_ssl_protocol_version ver_max =
195#ifdef MBEDTLS_SSL_PROTO_TLS1_3
196 MBEDTLS_SSL_VERSION_TLS1_3
197#else
198 MBEDTLS_SSL_VERSION_TLS1_2
199#endif
200 ;
202 DEBUGASSERT(conn_config->version != CURL_SSLVERSION_DEFAULT);
203 switch(conn_config->version) {
204 case CURL_SSLVERSION_TLSv1:
205 case CURL_SSLVERSION_TLSv1_0:
206 case CURL_SSLVERSION_TLSv1_1:
207 case CURL_SSLVERSION_TLSv1_2:
208#ifdef MBEDTLS_SSL_PROTO_TLS1_2
209 ver_min = MBEDTLS_SSL_VERSION_TLS1_2;
210 break;
211#endif
212 case CURL_SSLVERSION_TLSv1_3:
213#ifdef MBEDTLS_SSL_PROTO_TLS1_3
214 ver_min = MBEDTLS_SSL_VERSION_TLS1_3;
215 break;
216#endif
217 default:
218 failf(data, "mbedTLS: unsupported minimum TLS version value: %x",
219 conn_config->version);
220 return CURLE_SSL_CONNECT_ERROR;
221 }
223 switch(conn_config->version_max) {
224 case CURL_SSLVERSION_MAX_DEFAULT:
225 case CURL_SSLVERSION_MAX_NONE:
226 case CURL_SSLVERSION_MAX_TLSv1_3:
227#ifdef MBEDTLS_SSL_PROTO_TLS1_3
228 ver_max = MBEDTLS_SSL_VERSION_TLS1_3;
229 break;
230#endif
231#ifdef MBEDTLS_SSL_PROTO_TLS1_2
232 case CURL_SSLVERSION_MAX_TLSv1_2:
233 ver_max = MBEDTLS_SSL_VERSION_TLS1_2;
234 break;
235#endif
236 case CURL_SSLVERSION_MAX_TLSv1_1:
237 case CURL_SSLVERSION_MAX_TLSv1_0:
238 default:
239 failf(data, "mbedTLS: unsupported maximum TLS version value");
240 return CURLE_SSL_CONNECT_ERROR;
241 }
243 mbedtls_ssl_conf_min_tls_version(&backend->config, ver_min);
244 mbedtls_ssl_conf_max_tls_version(&backend->config, ver_max);
246 return CURLE_OK;
249/* TLS_ECJPAKE_WITH_AES_128_CCM_8 (0xC0FF) is marked experimental in mbedTLS.
250 The number is not reserved by IANA nor is the cipher suite present in other
251 SSL implementations. Provide provisional support for specifying the cipher
252 suite here. */
253#ifdef MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8
254static int mbed_cipher_suite_get_str(uint16_t id, char *buf, size_t buf_size,
255 bool prefer_rfc)
257 if(id == MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8)
258 curl_msnprintf(buf, buf_size, "%s", "TLS_ECJPAKE_WITH_AES_128_CCM_8");
259 else
260 return Curl_cipher_suite_get_str(id, buf, buf_size, prefer_rfc);
261 return 0;
264static uint16_t mbed_cipher_suite_walk_str(const char **str, const char **end)
266 uint16_t id = Curl_cipher_suite_walk_str(str, end);
267 size_t len = *end - *str;
268 static const char ecjpake_suite[] = "TLS_ECJPAKE_WITH_AES_128_CCM_8";
270 if(!id) {
271 if((len == CURL_CSTRLEN(ecjpake_suite)) &&
272 curl_strnequal(ecjpake_suite, *str, len))
273 id = MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8;
274 }
275 return id;
277#else
278#define mbed_cipher_suite_get_str Curl_cipher_suite_get_str
279#define mbed_cipher_suite_walk_str Curl_cipher_suite_walk_str
280#endif
282static CURLcode mbed_set_selected_ciphers(
283 struct Curl_easy *data,
284 struct mbed_ssl_backend_data *backend,
285 const char *ciphers12,
286 const char *ciphers13)
288 const char *ciphers = ciphers12;
289 const int *supported;
290 int *selected;
291 size_t supported_len, count = 0, default13_count = 0, i, j;
292 const char *ptr, *end;
294 supported = mbedtls_ssl_list_ciphersuites();
295 for(i = 0; supported[i] != 0; i++)
296 ;
297 supported_len = i;
299 selected = curlx_malloc(sizeof(int) * (supported_len + 1));
300 if(!selected)
301 return CURLE_OUT_OF_MEMORY;
303#ifndef MBEDTLS_SSL_PROTO_TLS1_3
304 (void)ciphers13, (void)j;
305#else
306 if(!ciphers13) {
307 /* Add default TLSv1.3 ciphers to selection */
308 for(j = 0; j < supported_len; j++) {
309 uint16_t id = (uint16_t)supported[j];
310 if(strncmp(mbedtls_ssl_get_ciphersuite_name(id), "TLS1-3", 6))
311 continue;
313 selected[count++] = id;
314 }
316 default13_count = count;
317 }
318 else
319 ciphers = ciphers13;
321add_ciphers:
322#endif
323 for(ptr = ciphers; ptr[0] != '\0' && count < supported_len; ptr = end) {
324 uint16_t id = mbed_cipher_suite_walk_str(&ptr, &end);
326 /* Check if cipher is supported */
327 if(id) {
328 for(i = 0; i < supported_len && supported[i] != id; i++)
329 ;
330 if(i == supported_len)
331 id = 0;
332 }
333 if(!id) {
334 if(ptr[0] != '\0')
335 infof(data, "mbedTLS: unknown cipher in list: \"%.*s\"",
336 (int)(end - ptr), ptr);
337 continue;
338 }
340 /* No duplicates allowed (so selected cannot overflow) */
341 for(i = 0; i < count && selected[i] != id; i++)
342 ;
343 if(i < count) {
344 if(i >= default13_count)
345 infof(data, "mbedTLS: duplicate cipher in list: \"%.*s\"",
346 (int)(end - ptr), ptr);
347 continue;
348 }
350 selected[count++] = id;
351 }
353#ifdef MBEDTLS_SSL_PROTO_TLS1_3
354 if(ciphers == ciphers13 && ciphers12) {
355 ciphers = ciphers12;
356 goto add_ciphers;
357 }
359 if(!ciphers12) {
360 /* Add default TLSv1.2 ciphers to selection */
361 for(j = 0; j < supported_len; j++) {
362 uint16_t id = (uint16_t)supported[j];
363 if(!strncmp(mbedtls_ssl_get_ciphersuite_name(id), "TLS1-3", 6))
364 continue;
366 /* No duplicates allowed (so selected cannot overflow) */
367 for(i = 0; i < count && selected[i] != id; i++)
368 ;
369 if(i < count)
370 continue;
372 selected[count++] = id;
373 }
374 }
375#endif
377 selected[count] = 0;
379 if(count == 0) {
380 curlx_free(selected);
381 failf(data, "mbedTLS: no supported cipher in list");
382 return CURLE_SSL_CIPHER;
383 }
385 /* mbedtls_ssl_conf_ciphersuites(): The ciphersuites array is not copied.
386 It must remain valid for the lifetime of the SSL configuration */
387 backend->ciphersuites = selected;
388 mbedtls_ssl_conf_ciphersuites(&backend->config, backend->ciphersuites);
389 return CURLE_OK;
392static void mbed_dump_cert_info(struct Curl_easy *data,
393 const mbedtls_x509_crt *crt)
395#if !defined(CURLVERBOSE) || defined(MBEDTLS_X509_REMOVE_INFO)
396 (void)data, (void)crt;
397#else
398 const size_t bufsize = 16384;
399 char *p, *buffer = curlx_malloc(bufsize);
401 if(buffer && mbedtls_x509_crt_info(buffer, bufsize, " ", crt) > 0) {
402 infof(data, "Server certificate:");
403 for(p = buffer; *p; p += *p != '\0') {
404 size_t s = strcspn(p, "\n");
405 infof(data, "%.*s", (int)s, p);
406 p += s;
407 }
408 }
409 else
410 infof(data, "Unable to dump certificate information");
412 curlx_free(buffer);
413#endif
416static void mbed_extract_certinfo(struct Curl_easy *data,
417 const mbedtls_x509_crt *crt)
419 CURLcode result;
420 const mbedtls_x509_crt *cur;
421 int cert_count = 0;
422 int i;
424 for(cur = crt; cur && cert_count <= MAX_ALLOWED_CERT_AMOUNT; cur = cur->next)
425 cert_count++;
427 if(cert_count > MAX_ALLOWED_CERT_AMOUNT) {
428 infof(data, "More certificates than allowed (%d), skipping certinfo",
429 MAX_ALLOWED_CERT_AMOUNT);
430 return;
431 }
433 result = Curl_ssl_init_certinfo(data, cert_count);
435 for(i = 0, cur = crt; result == CURLE_OK && cur; ++i, cur = cur->next) {
436 result = Curl_extract_certinfo(data, i, cur->raw.p,
437 cur->raw.p + cur->raw.len);
438 }
441static int mbed_verify_cb(void *ptr, mbedtls_x509_crt *crt,
442 int depth, uint32_t *flags)
444 struct Curl_cfilter *cf = (struct Curl_cfilter *)ptr;
445 struct ssl_filter_config *conn_config = Curl_ssl_cf_get_filter_config(cf);
446 struct Curl_easy *data = CF_DATA_CURRENT(cf);
448 if(depth == 0) {
449 if(data->set.verbose)
450 mbed_dump_cert_info(data, crt);
451 if(data->set.ssl.certinfo)
452 mbed_extract_certinfo(data, crt);
453 }
455 /* `verifypeer` and `verifyhost` are independent, so clear the flags of a
456 disabled check only. The name mismatch belongs to `verifyhost`. */
457 if(!conn_config->verifypeer)
458 *flags &= MBEDTLS_X509_BADCERT_CN_MISMATCH;
459 if(!conn_config->verifyhost)
460 *flags &= ~MBEDTLS_X509_BADCERT_CN_MISMATCH;
462 if(*flags) {
463#ifndef MBEDTLS_X509_REMOVE_INFO
464 char buf[128];
465 mbedtls_x509_crt_verify_info(buf, sizeof(buf), "", *flags);
466 failf(data, "mbedTLS: %s", buf);
467#else
468 failf(data, "mbedTLS: certificate verification error 0x%08x",
469 (unsigned int)*flags);
470#endif
471 }
473 return 0;
476static CURLcode mbed_load_cacert(struct Curl_cfilter *cf,
477 struct Curl_easy *data)
479 struct ssl_connect_data *connssl = cf->ctx;
480 struct mbed_ssl_backend_data *backend =
481 (struct mbed_ssl_backend_data *)connssl->backend;
482 struct ssl_filter_config *conn_config = Curl_ssl_cf_get_filter_config(cf);
483 const struct curl_blob *ca_info_blob = conn_config->ca_info_blob;
484 const char * const ssl_cafile =
485 /* CURLOPT_CAINFO_BLOB overrides CURLOPT_CAINFO */
486 (ca_info_blob ? NULL : conn_config->CAfile);
487 const bool verifypeer = conn_config->verifypeer;
488 const char * const ssl_capath = conn_config->CApath;
489#ifdef MBEDTLS_PEM_PARSE_C
490 const char * const ssl_cert_type = conn_config->cert_type;
491#endif
492 int ret = -1;
493 char errorbuf[128];
495 mbedtls_x509_crt_init(&backend->cacert);
497 if(ca_info_blob && verifypeer) {
498#ifdef MBEDTLS_PEM_PARSE_C
499 /* if DER or a null-terminated PEM process using
500 mbedtls_x509_crt_parse(). */
501 if((ssl_cert_type && curl_strequal(ssl_cert_type, "DER")) ||
502 ((char *)(ca_info_blob->data))[ca_info_blob->len - 1] == '\0') {
503 ret = mbedtls_x509_crt_parse(&backend->cacert, ca_info_blob->data,
504 ca_info_blob->len);
505 }
506 else { /* they say it is PEM and it is not null-terminated */
508 /* Unfortunately, mbedtls_x509_crt_parse() requires the data to be
509 null-terminated if the data is PEM encoded (even when provided the
510 exact length). The function accepts PEM or DER formats, but we cannot
511 assume if the user passed in a PEM format cert that it is
512 null-terminated. */
513 unsigned char *newblob = curlx_memdup0(ca_info_blob->data,
514 ca_info_blob->len);
515 if(!newblob)
516 return CURLE_OUT_OF_MEMORY;
518 ret = mbedtls_x509_crt_parse(&backend->cacert, newblob,
519 ca_info_blob->len + 1);
520 curlx_free(newblob);
521 }
522#else
523 /* DER encoded certs do not need to be null-terminated because it is a
524 binary format. Thus, if we are not compiling with PEM_PARSE we can avoid
525 the extra memory copies altogether. */
526 ret = mbedtls_x509_crt_parse_der(&backend->cacert, ca_info_blob->data,
527 ca_info_blob->len);
528#endif
530 if(ret < 0) {
531 mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
532 failf(data, "mbedTLS: error importing CA cert blob: (-0x%04X) %s",
533 (unsigned int)-ret, errorbuf);
534 return CURLE_SSL_CERTPROBLEM;
535 }
536 }
538 if(ssl_cafile && verifypeer) {
539#ifdef MBEDTLS_FS_IO
540 ret = mbedtls_x509_crt_parse_file(&backend->cacert, ssl_cafile);
542 if(ret < 0) {
543 mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
544 failf(data, "mbedTLS: error reading CA cert file %s: (-0x%04X) %s",
545 ssl_cafile, (unsigned int)-ret, errorbuf);
546 return CURLE_SSL_CACERT_BADFILE;
547 }
548#else
549 failf(data, "mbedTLS: functions that use the file system not built in");
550 return CURLE_NOT_BUILT_IN;
551#endif
552 }
554 if(ssl_capath) {
555#ifdef MBEDTLS_FS_IO
556 ret = mbedtls_x509_crt_parse_path(&backend->cacert, ssl_capath);
558 if(ret < 0) {
559 mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
560 failf(data, "mbedTLS: error reading CA cert path %s: (-0x%04X) %s",
561 ssl_capath, (unsigned int)-ret, errorbuf);
563 if(verifypeer)
564 return CURLE_SSL_CACERT_BADFILE;
565 }
566#else
567 failf(data, "mbedTLS: functions that use the file system not built in");
568 return CURLE_NOT_BUILT_IN;
569#endif
570 }
572 return CURLE_OK;
575static CURLcode mbed_load_clicert(struct Curl_cfilter *cf,
576 struct Curl_easy *data)
578 struct ssl_connect_data *connssl = cf->ctx;
579 struct mbed_ssl_backend_data *backend =
580 (struct mbed_ssl_backend_data *)connssl->backend;
581 struct ssl_filter_config *conn_config = Curl_ssl_cf_get_filter_config(cf);
582 char * const ssl_cert = conn_config->clientcert;
583 const struct curl_blob *ssl_cert_blob = conn_config->cert_blob;
584#ifdef MBEDTLS_PEM_PARSE_C
585 const char * const ssl_cert_type = conn_config->cert_type;
586#endif
587 int ret = -1;
588 char errorbuf[128];
590 mbedtls_x509_crt_init(&backend->clicert);
592 if(ssl_cert) {
593#ifdef MBEDTLS_FS_IO
594 ret = mbedtls_x509_crt_parse_file(&backend->clicert, ssl_cert);
596 if(ret) {
597 mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
598 failf(data, "mbedTLS: error reading client cert file %s: (-0x%04X) %s",
599 ssl_cert, (unsigned int)-ret, errorbuf);
601 return CURLE_SSL_CERTPROBLEM;
602 }
603#else
604 failf(data, "mbedTLS: functions that use the file system not built in");
605 return CURLE_NOT_BUILT_IN;
606#endif
607 }
609 if(ssl_cert_blob) {
610#ifdef MBEDTLS_PEM_PARSE_C
611 /* if DER or a null-terminated PEM process using
612 mbedtls_x509_crt_parse(). */
613 if((ssl_cert_type && curl_strequal(ssl_cert_type, "DER")) ||
614 ((char *)(ssl_cert_blob->data))[ssl_cert_blob->len - 1] == '\0') {
616 ret = mbedtls_x509_crt_parse(&backend->clicert,
617 ssl_cert_blob->data,
618 ssl_cert_blob->len);
619 }
620 else { /* they say it is PEM and it is not null-terminated */
622 /* Unfortunately, mbedtls_x509_crt_parse() requires the data to be
623 null-terminated if the data is PEM encoded (even when provided the
624 exact length). The function accepts PEM or DER formats, but we cannot
625 assume if the user passed in a PEM format cert that it is
626 null-terminated. */
627 unsigned char *newblob = curlx_memdup0(ssl_cert_blob->data,
628 ssl_cert_blob->len);
629 if(!newblob)
630 return CURLE_OUT_OF_MEMORY;
631 ret = mbedtls_x509_crt_parse(&backend->clicert, newblob,
632 ssl_cert_blob->len + 1);
633 curlx_free(newblob);
634 }
635#else
636 /* DER encoded certs do not need to be null-terminated because it is a
637 binary format. Thus, if we are not compiling with PEM_PARSE we can avoid
638 the extra memory copies altogether. */
639 ret = mbedtls_x509_crt_parse_der(&backend->clicert, ssl_cert_blob->data,
640 ssl_cert_blob->len);
641#endif
643 if(ret) {
644 mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
645 failf(data, "mbedTLS: error reading client cert blob: (-0x%04X) %s",
646 (unsigned int)-ret, errorbuf);
647 return CURLE_SSL_CERTPROBLEM;
648 }
649 }
651 return CURLE_OK;
654static CURLcode mbed_load_privkey(struct Curl_cfilter *cf,
655 struct Curl_easy *data)
657 struct ssl_connect_data *connssl = cf->ctx;
658 struct mbed_ssl_backend_data *backend =
659 (struct mbed_ssl_backend_data *)connssl->backend;
660 struct ssl_filter_config *conn_config = Curl_ssl_cf_get_filter_config(cf);
661 int ret = -1;
662 char errorbuf[128];
664 mbedtls_pk_init(&backend->pk);
666 if(conn_config->key || conn_config->key_blob) {
667 if(conn_config->key) {
668#ifdef MBEDTLS_FS_IO
669#if MBEDTLS_VERSION_NUMBER >= 0x04000000
670 ret = mbedtls_pk_parse_keyfile(&backend->pk, conn_config->key,
671 conn_config->key_passwd);
672 if(ret == 0 &&
673 !(mbedtls_pk_can_do_psa(&backend->pk,
674 PSA_ALG_RSA_PKCS1V15_SIGN(PSA_ALG_ANY_HASH),
675 PSA_KEY_USAGE_SIGN_HASH) ||
676 mbedtls_pk_can_do_psa(&backend->pk,
677 MBEDTLS_PK_ALG_ECDSA(PSA_ALG_ANY_HASH),
678 PSA_KEY_USAGE_SIGN_HASH)))
679 ret = MBEDTLS_ERR_PK_TYPE_MISMATCH;
680#else
681 ret = mbedtls_pk_parse_keyfile(&backend->pk, conn_config->key,
682 conn_config->key_passwd,
683 mbedtls_ctr_drbg_random,
684 &rng.drbg);
685 if(ret == 0 && !(mbedtls_pk_can_do(&backend->pk, MBEDTLS_PK_RSA) ||
686 mbedtls_pk_can_do(&backend->pk, MBEDTLS_PK_ECKEY)))
687 ret = MBEDTLS_ERR_PK_TYPE_MISMATCH;
688#endif
690 if(ret) {
691 mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
692 failf(data, "mbedTLS: error reading private key %s: (-0x%04X) %s",
693 conn_config->key, (unsigned int)-ret, errorbuf);
694 return CURLE_SSL_CERTPROBLEM;
695 }
696#else
697 failf(data, "mbedTLS: functions that use the file system not built in");
698 return CURLE_NOT_BUILT_IN;
699#endif
700 }
701 else {
702 const struct curl_blob *ssl_key_blob = conn_config->key_blob;
703 const char *passwd = conn_config->key_passwd;
704 const bool is_der = conn_config->key_type &&
705 curl_strequal(conn_config->key_type, "DER");
706 /* Unfortunately, mbedtls_pk_parse_key() requires the data to be
707 null-terminated if the data is PEM encoded (even when provided the
708 exact length). */
709 unsigned char *newblob = curlx_memdup0(ssl_key_blob->data,
710 ssl_key_blob->len);
711 /* mbedtls_pk_parse_key() requires the terminator to be counted in the
712 length for PEM input, while the DER parsers require the exact
713 length: a DER key with the terminator counted in is rejected with
714 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH. */
715 size_t keylen = is_der ? ssl_key_blob->len : ssl_key_blob->len + 1;
716 if(!newblob)
717 return CURLE_OUT_OF_MEMORY;
719#if MBEDTLS_VERSION_NUMBER >= 0x04000000
720 ret = mbedtls_pk_parse_key(&backend->pk, newblob, keylen,
721 (const unsigned char *)passwd,
722 passwd ? strlen(passwd) : 0);
723 if(ret == 0 &&
724 !(mbedtls_pk_can_do_psa(&backend->pk,
725 PSA_ALG_RSA_PKCS1V15_SIGN(PSA_ALG_ANY_HASH),
726 PSA_KEY_USAGE_SIGN_HASH) ||
727 mbedtls_pk_can_do_psa(&backend->pk,
728 MBEDTLS_PK_ALG_ECDSA(PSA_ALG_ANY_HASH),
729 PSA_KEY_USAGE_SIGN_HASH)))
730 ret = MBEDTLS_ERR_PK_TYPE_MISMATCH;
731#else
732 ret = mbedtls_pk_parse_key(&backend->pk, newblob, keylen,
733 (const unsigned char *)passwd,
734 passwd ? strlen(passwd) : 0,
735 mbedtls_ctr_drbg_random,
736 &rng.drbg);
737 if(ret == 0 && !(mbedtls_pk_can_do(&backend->pk, MBEDTLS_PK_RSA) ||
738 mbedtls_pk_can_do(&backend->pk, MBEDTLS_PK_ECKEY)))
739 ret = MBEDTLS_ERR_PK_TYPE_MISMATCH;
740#endif
741 curlx_free(newblob);
743 if(ret) {
744 mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
745 failf(data, "mbedTLS: error parsing private key: (-0x%04X) %s",
746 (unsigned int)-ret, errorbuf);
747 return CURLE_SSL_CERTPROBLEM;
748 }
749 }
750 }
752 return CURLE_OK;
755static CURLcode mbed_load_crl(struct Curl_cfilter *cf,
756 struct Curl_easy *data)
758 struct ssl_connect_data *connssl = cf->ctx;
759 struct mbed_ssl_backend_data *backend =
760 (struct mbed_ssl_backend_data *)connssl->backend;
761 struct ssl_filter_config *conn_config = Curl_ssl_cf_get_filter_config(cf);
762 const char * const ssl_crlfile = conn_config->CRLfile;
764#ifdef MBEDTLS_X509_CRL_PARSE_C
765 mbedtls_x509_crl_init(&backend->crl);
767 if(ssl_crlfile) {
768 char errorbuf[128];
769#ifdef MBEDTLS_FS_IO
770 int ret = mbedtls_x509_crl_parse_file(&backend->crl, ssl_crlfile);
772 if(ret) {
773 mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
774 failf(data, "mbedTLS: error reading CRL file %s: (-0x%04X) %s",
775 ssl_crlfile, (unsigned int)-ret, errorbuf);
777 return CURLE_SSL_CRL_BADFILE;
778 }
779#else
780 (void)errorbuf;
781 failf(data, "mbedTLS: functions that use the file system not built in");
782 return CURLE_NOT_BUILT_IN;
783#endif
784 }
785#else
786 (void)backend;
787 if(ssl_crlfile) {
788 failf(data, "mbedTLS: CRL support not built in");
789 return CURLE_NOT_BUILT_IN;
790 }
791#endif
793 return CURLE_OK;
796static bool mbed_apply_session(struct Curl_cfilter *cf,
797 struct Curl_easy *data,
798 struct Curl_ssl_session *sc_session)
800 struct ssl_connect_data *connssl = cf->ctx;
801 struct mbed_ssl_backend_data *backend =
802 (struct mbed_ssl_backend_data *)connssl->backend;
804 if(sc_session && sc_session->sdata && sc_session->sdata_len) {
805 mbedtls_ssl_session session;
806 int ret;
808 mbedtls_ssl_session_init(&session);
809 ret = mbedtls_ssl_session_load(&session, sc_session->sdata,
810 sc_session->sdata_len);
811 if(ret) {
812 failf(data, "SSL session error loading: -0x%x", (unsigned int)-ret);
813 }
814 else {
815 ret = mbedtls_ssl_set_session(&backend->ssl, &session);
816 if(ret)
817 failf(data, "SSL session error setting: -0x%x", (unsigned int)-ret);
818 }
819 mbedtls_ssl_session_free(&session);
820 if(!ret) {
821 infof(data, "SSL reusing session ID");
822 return TRUE;
823 }
824 }
825 return FALSE;
828static CURLcode mbed_configure_ssl(struct Curl_cfilter *cf,
829 struct Curl_easy *data)
831 struct ssl_connect_data *connssl = cf->ctx;
832 struct mbed_ssl_backend_data *backend =
833 (struct mbed_ssl_backend_data *)connssl->backend;
834 struct ssl_filter_config *conn_config = Curl_ssl_cf_get_filter_config(cf);
835 int ret;
836 bool session_applied = FALSE;
837 CURLcode result;
838 char errorbuf[128];
840 infof(data, "mbedTLS: Connecting to %s:%d",
841 connssl->peer.origin->hostname, connssl->peer.origin->port);
843 mbedtls_ssl_config_init(&backend->config);
844 ret = mbedtls_ssl_config_defaults(&backend->config,
845 MBEDTLS_SSL_IS_CLIENT,
846 MBEDTLS_SSL_TRANSPORT_STREAM,
847 MBEDTLS_SSL_PRESET_DEFAULT);
848 if(ret) {
849 failf(data, "mbedTLS: ssl_config failed");
850 return CURLE_SSL_CONNECT_ERROR;
851 }
853#ifdef MBEDTLS_DEBUG
854 /* In order to make that work in mbedtls MBEDTLS_DEBUG_C must be defined. */
855 mbedtls_ssl_conf_dbg(&backend->config, mbed_debug, data);
856 /* - 0 No debug
857 * - 1 Error
858 * - 2 State change
859 * - 3 Informational
860 * - 4 Verbose
861 */
862 mbedtls_debug_set_threshold(4);
863#endif
865#if defined(MBEDTLS_SSL_SESSION_TICKETS) && \
866 defined(MBEDTLS_SSL_PROTO_TLS1_3) && \
867 MBEDTLS_VERSION_NUMBER >= 0x03060100 && \
868 MBEDTLS_VERSION_NUMBER < 0x04000000
869 /* New in mbedTLS 3.6.1, need to enable, default is now disabled. 4.0.0
870 enabled it by default for TLSv1.3. */
871 mbedtls_ssl_conf_tls13_enable_signal_new_session_tickets(
872 &backend->config, MBEDTLS_SSL_TLS1_3_SIGNAL_NEW_SESSION_TICKETS_ENABLED);
873#endif
875 /* Always let mbedTLS verify certificates, if verifypeer or verifyhost are
876 * disabled we clear the corresponding error flags in the verify callback
877 * function. That is also where we log verification errors. */
878 mbedtls_ssl_conf_verify(&backend->config, mbed_verify_cb, cf);
879 mbedtls_ssl_conf_authmode(&backend->config, MBEDTLS_SSL_VERIFY_REQUIRED);
881 mbedtls_ssl_init(&backend->ssl);
882 backend->initialized = TRUE;
884 /* use the default secure profile baked into mbedTLS */
885 mbedtls_ssl_conf_cert_profile(&backend->config,
886 &mbedtls_x509_crt_profile_next);
888 result = mbed_set_ssl_version_min_max(data, backend, conn_config);
889 if(result)
890 return result;
892#if MBEDTLS_VERSION_NUMBER < 0x04000000
893 mbedtls_ssl_conf_rng(&backend->config, mbedtls_ctr_drbg_random,
894 &rng.drbg);
895#endif
897 ret = mbedtls_ssl_setup(&backend->ssl,
898 &backend->config);
899 if(ret) {
900 mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
901 failf(data, "mbedTLS: ssl_setup failed: "
902 "(-0x%04X) %s", (unsigned int)-ret, errorbuf);
903 return CURLE_SSL_CONNECT_ERROR;
904 }
906 mbedtls_ssl_set_bio(&backend->ssl, cf,
907 mbedtls_bio_cf_write,
908 mbedtls_bio_cf_read,
909 NULL /* rev_timeout() */);
911#ifndef MBEDTLS_SSL_PROTO_TLS1_3
912 if(conn_config->cipher_list) {
913 result = mbed_set_selected_ciphers(data, backend,
914 conn_config->cipher_list, NULL);
915#else
916 if(conn_config->cipher_list || conn_config->cipher_list13) {
917 result = mbed_set_selected_ciphers(data, backend,
918 conn_config->cipher_list,
919 conn_config->cipher_list13);
920#endif
921 if(result) {
922 failf(data, "mbedTLS: failed to set cipher suites");
923 return result;
924 }
925 }
926 else {
927 mbedtls_ssl_conf_ciphersuites(&backend->config,
928 mbedtls_ssl_list_ciphersuites());
929 }
931#ifdef MBEDTLS_SSL_RENEGOTIATION
932 mbedtls_ssl_conf_renegotiation(&backend->config,
933 MBEDTLS_SSL_RENEGOTIATION_ENABLED);
934#endif
936#ifdef MBEDTLS_SSL_SESSION_TICKETS
937 mbedtls_ssl_conf_session_tickets(&backend->config,
938 MBEDTLS_SSL_SESSION_TICKETS_DISABLED);
939#endif
941 if((cf->sockindex == SECONDARYSOCKET) && !(cf->cft->flags & CF_TYPE_PROXY)) {
942 /* FTP is a bitch. On TLS secured transfers, it is a common server
943 * option to require the client to use the SAME TLS session as on
944 * the control connection or it fails the request. See #22225. */
945 struct Curl_ssl_session *scs =
946 Curl_ssl_get_cf_session(data, cf->cft, FIRSTSOCKET);
947 if(scs) {
948 if(mbed_apply_session(cf, data, scs)) {
949 CURL_TRC_CF(data, cf, "applied SSL session from control connection");
950 session_applied = TRUE;
951 }
952 }
953 }
955 /* Check if there is a cached ID we can/should use here! */
956 if(!session_applied && Curl_ssl_scache_use(cf, data)) {
957 struct Curl_ssl_session *sc_session = NULL;
958 CURLcode sresult = Curl_ssl_scache_take(cf, data, connssl->peer.scache_key,
959 &sc_session);
960 if(!sresult && sc_session && sc_session->sdata && sc_session->sdata_len) {
961 mbedtls_ssl_session session;
963 mbedtls_ssl_session_init(&session);
964 ret = mbedtls_ssl_session_load(&session, sc_session->sdata,
965 sc_session->sdata_len);
966 if(ret) {
967 failf(data, "SSL session error loading: -0x%x", (unsigned int)-ret);
968 }
969 else {
970 ret = mbedtls_ssl_set_session(&backend->ssl, &session);
971 if(ret)
972 failf(data, "SSL session error setting: -0x%x", (unsigned int)-ret);
973 else
974 infof(data, "SSL reusing session ID");
975 }
976 mbedtls_ssl_session_free(&session);
977 }
978 Curl_ssl_scache_return(cf, data, connssl->peer.scache_key,
979 sc_session);
980 }
982 mbedtls_ssl_conf_ca_chain(&backend->config, &backend->cacert,
983#ifdef MBEDTLS_X509_CRL_PARSE_C
984 &backend->crl
985#else
986 NULL
987#endif
988 );
990 if(conn_config->key || conn_config->key_blob) {
991 mbedtls_ssl_conf_own_cert(&backend->config, &backend->clicert,
992 &backend->pk);
993 }
995 if(mbedtls_ssl_set_hostname(&backend->ssl, connssl->peer.sni ?
996 connssl->peer.sni :
997 connssl->peer.origin->hostname)) {
998 /* mbedtls_ssl_set_hostname() sets the name to use in CN/SAN checks and
999 the name to set in the SNI extension. Thus even if curl connects to
1000 a host specified as an IP address, this function must be used. */
1001 failf(data, "Failed to set SNI");
1002 return CURLE_SSL_CONNECT_ERROR;
1005#ifdef HAS_ALPN_MBEDTLS
1006 if(connssl->alpn) {
1007 struct alpn_proto_buf proto;
1008 size_t i;
1010 for(i = 0; i < connssl->alpn->count; ++i) {
1011 backend->protocols[i] = connssl->alpn->entries[i];
1013 /* this function does not clone the protocols array, which is why we need
1014 to keep it around */
1015 if(mbedtls_ssl_conf_alpn_protocols(&backend->config,
1016 &backend->protocols[0])) {
1017 failf(data, "Failed setting ALPN protocols");
1018 return CURLE_SSL_CONNECT_ERROR;
1020 Curl_alpn_to_proto_str(&proto, connssl->alpn);
1021 infof(data, VTLS_INFOF_ALPN_OFFER_1STR, proto.data);
1023#endif
1025 /* give application a chance to interfere with mbedTLS set up. */
1026 if(data->set.ssl_fsslctx) {
1027 result = (*data->set.ssl_fsslctx)(data, &backend->config,
1028 data->set.ssl_fsslctxp);
1029 if(result)
1030 failf(data, "error signaled by SSL ctx callback");
1033 return result;
1036static CURLcode mbed_connect_step1(struct Curl_cfilter *cf,
1037 struct Curl_easy *data)
1039 struct ssl_connect_data *connssl = cf->ctx;
1040 struct ssl_filter_config *conn_config = Curl_ssl_cf_get_filter_config(cf);
1041 CURLcode result;
1043 if((conn_config->version == CURL_SSLVERSION_SSLv2) ||
1044 (conn_config->version == CURL_SSLVERSION_SSLv3)) {
1045 failf(data, "Not supported SSL version");
1046 return CURLE_NOT_BUILT_IN;
1049 result = mbed_load_cacert(cf, data);
1050 if(!result)
1051 result = mbed_load_clicert(cf, data);
1052 if(!result)
1053 result = mbed_load_privkey(cf, data);
1054 if(!result)
1055 result = mbed_load_crl(cf, data);
1056 if(!result)
1057 result = mbed_configure_ssl(cf, data);
1058 if(result)
1059 return result;
1061 connssl->connecting_state = ssl_connect_2;
1062 return CURLE_OK;
1065#if defined(MBEDTLS_PK_WRITE_C) && defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
1066#define HAVE_PINNED_PUBKEY
1067#endif
1069static CURLcode mbed_connect_step2(struct Curl_cfilter *cf,
1070 struct Curl_easy *data)
1072#if defined(HAVE_PINNED_PUBKEY) || defined(HAS_ALPN_MBEDTLS)
1073 CURLcode result;
1074#endif
1075 int ret;
1076 struct ssl_connect_data *connssl = cf->ctx;
1077 struct mbed_ssl_backend_data *backend =
1078 (struct mbed_ssl_backend_data *)connssl->backend;
1079#ifdef HAVE_PINNED_PUBKEY
1080#ifndef CURL_DISABLE_PROXY
1081 const char * const pinnedpubkey = Curl_ssl_cf_is_proxy(cf) ?
1082 CURL_EASY_STR(data, STRING_SSL_PINNEDPUBLICKEY_PROXY) :
1083 CURL_EASY_STR(data, STRING_SSL_PINNEDPUBLICKEY);
1084#else
1085 const char * const pinnedpubkey =
1086 CURL_EASY_STR(data, STRING_SSL_PINNEDPUBLICKEY);
1087#endif
1088#endif
1090 DEBUGASSERT(backend);
1092 ret = mbedtls_ssl_handshake(&backend->ssl);
1094 if(ret == MBEDTLS_ERR_SSL_WANT_READ) {
1095 connssl->io_need = CURL_SSL_IO_NEED_RECV;
1096 return CURLE_OK;
1098 else if(ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
1099 connssl->io_need = CURL_SSL_IO_NEED_SEND;
1100 return CURLE_OK;
1102 else if(ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) {
1103 failf(data, "peer certificate could not be verified");
1104 return CURLE_PEER_FAILED_VERIFICATION;
1106 else if(ret) {
1107 char errorbuf[128];
1108 CURL_TRC_CF(data, cf, "TLS version %04X",
1109 mbedtls_ssl_get_version_number(&backend->ssl));
1110 mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
1111 failf(data, "ssl_handshake returned: (-0x%04X) %s",
1112 (unsigned int)-ret, errorbuf);
1113 return CURLE_SSL_CONNECT_ERROR;
1117 char cipher_str[64];
1118 uint16_t cipher_id;
1119 cipher_id =
1120 (uint16_t)mbedtls_ssl_get_ciphersuite_id_from_ssl(&backend->ssl);
1121 mbed_cipher_suite_get_str(cipher_id, cipher_str, sizeof(cipher_str), TRUE);
1122 infof(data, "mbedTLS: %s Handshake complete, cipher is %s",
1123 mbedtls_ssl_get_version(&backend->ssl), cipher_str);
1126#ifdef HAVE_PINNED_PUBKEY
1127 if(pinnedpubkey) {
1128 int size;
1129 const mbedtls_x509_crt *peercert;
1130 mbedtls_x509_crt *p = NULL;
1131 unsigned char *pubkey = NULL;
1133 peercert = mbedtls_ssl_get_peer_cert(&backend->ssl);
1134 if(!peercert || !peercert->raw.p || !peercert->raw.len) {
1135 failf(data, "Failed due to missing peer certificate");
1136 return CURLE_SSL_PINNEDPUBKEYNOTMATCH;
1139 p = curlx_calloc(1, sizeof(*p));
1141 if(!p)
1142 return CURLE_OUT_OF_MEMORY;
1144 pubkey = curlx_malloc(PUB_DER_MAX_BYTES);
1146 if(!pubkey) {
1147 result = CURLE_OUT_OF_MEMORY;
1148 goto pinnedpubkey_error;
1151 mbedtls_x509_crt_init(p);
1153 /* Make a copy of our const peercert because mbedtls_pk_write_pubkey_der
1154 needs a non-const key, for now.
1155 https://github.com/Mbed-TLS/mbedtls/issues/396 */
1156 if(mbedtls_x509_crt_parse_der(p, peercert->raw.p, peercert->raw.len)) {
1157 failf(data, "Failed copying peer certificate");
1158 result = CURLE_SSL_PINNEDPUBKEYNOTMATCH;
1159 goto pinnedpubkey_error;
1162 size = mbedtls_pk_write_pubkey_der(&p->pk, pubkey, PUB_DER_MAX_BYTES);
1164 if(size <= 0) {
1165 failf(data, "Failed copying public key from peer certificate");
1166 result = CURLE_SSL_PINNEDPUBKEYNOTMATCH;
1167 goto pinnedpubkey_error;
1170 /* mbedtls_pk_write_pubkey_der writes data at the end of the buffer. */
1171 result = Curl_pin_peer_pubkey(data,
1172 pinnedpubkey,
1173 &pubkey[PUB_DER_MAX_BYTES - size], size);
1174pinnedpubkey_error:
1175 mbedtls_x509_crt_free(p);
1176 curlx_free(p);
1177 curlx_free(pubkey);
1178 if(result)
1179 return result;
1181#endif
1183#ifdef HAS_ALPN_MBEDTLS
1184 if(connssl->alpn) {
1185 const char *proto = mbedtls_ssl_get_alpn_protocol(&backend->ssl);
1187 result = Curl_alpn_set_negotiated(cf, data, connssl,
1188 (const unsigned char *)proto,
1189 proto ? strlen(proto) : 0);
1190 if(result)
1191 return result;
1193#endif
1195 connssl->connecting_state = ssl_connect_3;
1196 infof(data, "SSL connected");
1198 return CURLE_OK;
1201static CURLcode mbed_new_session(struct Curl_cfilter *cf,
1202 struct Curl_easy *data)
1204 struct ssl_connect_data *connssl = cf->ctx;
1205 struct mbed_ssl_backend_data *backend =
1206 (struct mbed_ssl_backend_data *)connssl->backend;
1207 mbedtls_ssl_session session;
1208 bool msession_alloced = FALSE;
1209 struct Curl_ssl_session *sc_session = NULL;
1210 unsigned char *sdata = NULL;
1211 size_t slen = 0;
1212 int ietf_tls_id;
1213 CURLcode result = CURLE_OK;
1214 int ret;
1216 DEBUGASSERT(backend);
1217 if(!Curl_ssl_scache_use(cf, data))
1218 return CURLE_OK;
1220 mbedtls_ssl_session_init(&session);
1221 ret = mbedtls_ssl_get_session(&backend->ssl, &session);
1222 msession_alloced = (ret != MBEDTLS_ERR_SSL_ALLOC_FAILED);
1223 if(ret) {
1224 failf(data, "mbedtls_ssl_get_session returned -0x%x", (unsigned int)-ret);
1225 result = CURLE_SSL_CONNECT_ERROR;
1226 goto out;
1229 mbedtls_ssl_session_save(&session, NULL, 0, &slen);
1230 if(!slen) {
1231 failf(data, "failed to serialize session: length is 0");
1232 goto out;
1235 sdata = curlx_malloc(slen);
1236 if(!sdata) {
1237 result = CURLE_OUT_OF_MEMORY;
1238 goto out;
1241 ret = mbedtls_ssl_session_save(&session, sdata, slen, &slen);
1242 if(ret) {
1243 failf(data, "failed to serialize session: -0x%x", (unsigned int)-ret);
1244 goto out;
1247 ietf_tls_id = mbedtls_ssl_get_version_number(&backend->ssl);
1248 result = Curl_ssl_session_create(sdata, slen,
1249 ietf_tls_id,
1250 connssl->negotiated.alpn, 0, 0,
1251 &sc_session);
1252 sdata = NULL; /* call took ownership */
1253 if(!result && /* return a duplicate if asked for and FTP */
1254 (cf->conn->scheme->family == CURLPROTO_FTP)) {
1255 Curl_ssl_session_destroy(connssl->session);
1256 result = Curl_ssl_session_dup(sc_session, &connssl->session);
1259 if(!result) {
1260 result = Curl_ssl_scache_put(cf, data, connssl->peer.scache_key,
1261 sc_session);
1262 sc_session = NULL;
1265out:
1266 if(msession_alloced)
1267 mbedtls_ssl_session_free(&session);
1268 Curl_ssl_session_destroy(sc_session);
1269 curlx_free(sdata);
1270 return result;
1273static CURLcode mbed_send(struct Curl_cfilter *cf, struct Curl_easy *data,
1274 const void *mem, size_t len, size_t *pnwritten)
1276 struct ssl_connect_data *connssl = cf->ctx;
1277 struct mbed_ssl_backend_data *backend =
1278 (struct mbed_ssl_backend_data *)connssl->backend;
1279 CURLcode result = CURLE_OK;
1280 int nwritten;
1282 DEBUGASSERT(backend);
1283#ifdef MBEDTLS_SSL_PROTO_TLS1_3
1284do_send:
1285#endif
1286 *pnwritten = 0;
1287 connssl->io_need = CURL_SSL_IO_NEED_NONE;
1288 /* mbedTLS is picky when a mbedtls_ssl_write() was previously blocked.
1289 * It requires to be called with the same amount of bytes again, or it
1290 * loses bytes, e.g. reporting all was sent but they were not.
1291 * Remember the blocked length and use that when set. */
1292 if(backend->send_blocked) {
1293 if(backend->send_blocked_len > len) {
1294 DEBUGASSERT(0);
1295 failf(data, "re-send data shorter than previously");
1296 result = CURLE_BAD_FUNCTION_ARGUMENT;
1297 goto out;
1299 CURL_TRC_CF(data, cf, "mbedtls_ssl_write(len=%zu) -> previously blocked "
1300 "on %zu bytes", len, backend->send_blocked_len);
1301 len = backend->send_blocked_len;
1304 nwritten = mbedtls_ssl_write(&backend->ssl, (const unsigned char *)mem, len);
1306 if(nwritten >= 0) {
1307 *pnwritten = (size_t)nwritten;
1308 backend->send_blocked = FALSE;
1310 else {
1311 CURL_TRC_CF(data, cf, "mbedtls_ssl_write(len=%zu) -> -0x%04X",
1312 len, (unsigned int)-nwritten);
1313 switch(nwritten) {
1314#ifdef MBEDTLS_SSL_PROTO_TLS1_3
1315 case MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET:
1316 result = mbed_new_session(cf, data);
1317 /* This return code is not blocking. Having treated the new
1318 * ticket, resume sending until we get a "real" result. */
1319 if(!result)
1320 goto do_send;
1321 break;
1322#endif
1323 case MBEDTLS_ERR_SSL_WANT_READ:
1324 connssl->io_need = CURL_SSL_IO_NEED_RECV;
1325 result = CURLE_AGAIN;
1326 break;
1327 case MBEDTLS_ERR_SSL_WANT_WRITE:
1328 connssl->io_need = CURL_SSL_IO_NEED_SEND;
1329 result = CURLE_AGAIN;
1330 break;
1331 default:
1332 result = CURLE_SEND_ERROR;
1333 break;
1335 if((result == CURLE_AGAIN) && !backend->send_blocked) {
1336 backend->send_blocked = TRUE;
1337 backend->send_blocked_len = len;
1341out:
1342 CURL_TRC_CF(data, cf, "mbedtls_ssl_write(len=%zu) -> %d, %zu",
1343 len, (int)result, *pnwritten);
1344 return result;
1347static CURLcode mbedtls_shutdown(struct Curl_cfilter *cf,
1348 struct Curl_easy *data,
1349 bool send_shutdown, bool *done)
1351 struct ssl_connect_data *connssl = cf->ctx;
1352 struct mbed_ssl_backend_data *backend =
1353 (struct mbed_ssl_backend_data *)connssl->backend;
1354 unsigned char buf[1024];
1355 CURLcode result = CURLE_OK;
1356 int ret = 0;
1357 size_t i;
1359 DEBUGASSERT(backend);
1361 if(!backend->initialized || cf->shutdown) {
1362 *done = TRUE;
1363 return CURLE_OK;
1366 connssl->io_need = CURL_SSL_IO_NEED_NONE;
1367 *done = FALSE;
1369 if(!backend->sent_shutdown) {
1370 /* do this only once */
1371 backend->sent_shutdown = TRUE;
1372 if(send_shutdown) {
1373 ret = mbedtls_ssl_close_notify(&backend->ssl);
1374 switch(ret) {
1375 case 0: /* we sent it, receive from the server */
1376 break;
1377 case MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY: /* server also closed */
1378 *done = TRUE;
1379 goto out;
1380 case MBEDTLS_ERR_SSL_WANT_READ:
1381 connssl->io_need = CURL_SSL_IO_NEED_RECV;
1382 goto out;
1383 case MBEDTLS_ERR_SSL_WANT_WRITE:
1384 connssl->io_need = CURL_SSL_IO_NEED_SEND;
1385 goto out;
1386 default:
1387 CURL_TRC_CF(data, cf, "mbedtls_shutdown error -0x%04X",
1388 (unsigned int)-ret);
1389 result = CURLE_RECV_ERROR;
1390 goto out;
1395 /* SSL should now have started the shutdown from our side. Since it
1396 * was not complete, we are lacking the close notify from the server. */
1397 for(i = 0; i < 10; ++i) {
1398 ret = mbedtls_ssl_read(&backend->ssl, buf, sizeof(buf));
1399 /* This seems to be a bug in mbedTLS TLSv1.3 where it reports
1400 * WANT_READ, but has not encountered an EAGAIN. */
1401 if(ret == MBEDTLS_ERR_SSL_WANT_READ)
1402 ret = mbedtls_ssl_read(&backend->ssl, buf, sizeof(buf));
1403#ifdef MBEDTLS_SSL_PROTO_TLS1_3
1404 if(ret == MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET)
1405 continue;
1406#endif
1407 if(ret <= 0)
1408 break;
1411 if(ret > 0) {
1412 /* still data coming in? */
1413 CURL_TRC_CF(data, cf, "mbedtls_shutdown, still getting data");
1415 else if(ret == 0 || (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY)) {
1416 /* We got the close notify alert and are done. */
1417 CURL_TRC_CF(data, cf, "mbedtls_shutdown done");
1418 *done = TRUE;
1420 else if(ret == MBEDTLS_ERR_SSL_WANT_READ) {
1421 CURL_TRC_CF(data, cf, "mbedtls_shutdown, need RECV");
1422 connssl->io_need = CURL_SSL_IO_NEED_RECV;
1424 else if(ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
1425 CURL_TRC_CF(data, cf, "mbedtls_shutdown, need SEND");
1426 connssl->io_need = CURL_SSL_IO_NEED_SEND;
1428 else {
1429 CURL_TRC_CF(data, cf, "mbedtls_shutdown error -0x%04X",
1430 (unsigned int)-ret);
1431 result = CURLE_RECV_ERROR;
1434out:
1435 cf->shutdown = (result || *done);
1436 return result;
1439static void mbedtls_close(struct Curl_cfilter *cf, struct Curl_easy *data)
1441 struct ssl_connect_data *connssl = cf->ctx;
1442 struct mbed_ssl_backend_data *backend =
1443 (struct mbed_ssl_backend_data *)connssl->backend;
1445 (void)data;
1446 DEBUGASSERT(backend);
1447 mbedtls_pk_free(&backend->pk);
1448 mbedtls_x509_crt_free(&backend->clicert);
1449 mbedtls_x509_crt_free(&backend->cacert);
1450#ifdef MBEDTLS_X509_CRL_PARSE_C
1451 mbedtls_x509_crl_free(&backend->crl);
1452#endif
1453 curlx_safefree(backend->ciphersuites);
1454 mbedtls_ssl_config_free(&backend->config);
1455 if(backend->initialized) {
1456 mbedtls_ssl_free(&backend->ssl);
1457 backend->initialized = FALSE;
1461static CURLcode mbed_recv(struct Curl_cfilter *cf, struct Curl_easy *data,
1462 char *buf, size_t buffersize, size_t *pnread)
1464 struct ssl_connect_data *connssl = cf->ctx;
1465 struct mbed_ssl_backend_data *backend =
1466 (struct mbed_ssl_backend_data *)connssl->backend;
1467 CURLcode result = CURLE_OK;
1468 int nread;
1470 DEBUGASSERT(backend);
1471#ifdef MBEDTLS_SSL_SESSION_TICKETS
1472do_read:
1473#endif
1474 *pnread = 0;
1475 connssl->io_need = CURL_SSL_IO_NEED_NONE;
1477 nread = mbedtls_ssl_read(&backend->ssl, (unsigned char *)buf, buffersize);
1478 if(nread > 0)
1479 *pnread = (size_t)nread;
1480 else {
1481 char errorbuf[128];
1482 CURL_TRC_CF(data, cf, "mbedtls_ssl_read(len=%zu) -> -0x%04X",
1483 buffersize, (unsigned int)-nread);
1484 switch(nread) {
1485#ifdef MBEDTLS_SSL_SESSION_TICKETS
1486 case MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET:
1487 result = mbed_new_session(cf, data);
1488 /* This is not blocking anything. We can try again until a
1489 * "real" result comes. */
1490 if(!result)
1491 goto do_read;
1492 break;
1493#endif
1494 case MBEDTLS_ERR_SSL_WANT_READ:
1495 connssl->io_need = CURL_SSL_IO_NEED_RECV;
1496 result = CURLE_AGAIN;
1497 break;
1498 case MBEDTLS_ERR_SSL_WANT_WRITE:
1499 connssl->io_need = CURL_SSL_IO_NEED_SEND;
1500 result = CURLE_AGAIN;
1501 break;
1502 case MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY:
1503 result = CURLE_OK;
1504 break;
1505 default:
1506 mbedtls_strerror(nread, errorbuf, sizeof(errorbuf));
1507 failf(data, "ssl_read returned: (-0x%04X) %s", (unsigned int)-nread,
1508 errorbuf);
1509 result = CURLE_RECV_ERROR;
1510 break;
1513 return result;
1516static size_t mbedtls_version(char *buffer, size_t size)
1518#ifdef MBEDTLS_VERSION_C
1519 /* if mbedtls_version_get_number() is available it is better */
1520 unsigned int version = mbedtls_version_get_number();
1521 return curl_msnprintf(buffer, size, "mbedTLS/%u.%u.%u", version >> 24,
1522 (version >> 16) & 0xff, (version >> 8) & 0xff);
1523#else
1524 return curl_msnprintf(buffer, size, "mbedTLS/%s", MBEDTLS_VERSION_STRING);
1525#endif
1528/* 'data' might be NULL */
1529static CURLcode mbedtls_random(struct Curl_easy *data,
1530 unsigned char *entropy, size_t length)
1532 psa_status_t status;
1533 (void)data;
1535 status = psa_generate_random(entropy, length);
1537 return status == PSA_SUCCESS ? CURLE_OK : CURLE_FAILED_INIT;
1540static CURLcode mbedtls_connect(struct Curl_cfilter *cf,
1541 struct Curl_easy *data,
1542 bool *done)
1544 CURLcode result;
1545 struct ssl_connect_data *connssl = cf->ctx;
1547 /* check if the connection has already been established */
1548 if(ssl_connection_complete == connssl->state) {
1549 *done = TRUE;
1550 return CURLE_OK;
1553 *done = FALSE;
1554 connssl->io_need = CURL_SSL_IO_NEED_NONE;
1556 if(connssl->connecting_state == ssl_connect_1) {
1557 result = mbed_connect_step1(cf, data);
1558 if(result)
1559 return result;
1562 if(connssl->connecting_state == ssl_connect_2) {
1563 result = mbed_connect_step2(cf, data);
1564 if(result)
1565 return result;
1568 if(connssl->connecting_state == ssl_connect_3) {
1569 /* For tls1.3 we get notified about new sessions */
1570 struct ssl_connect_data *ctx = cf->ctx;
1571 struct mbed_ssl_backend_data *backend =
1572 (struct mbed_ssl_backend_data *)ctx->backend;
1574 if(mbedtls_ssl_get_version_number(&backend->ssl) <=
1575 MBEDTLS_SSL_VERSION_TLS1_2) {
1576 result = mbed_new_session(cf, data);
1577 if(result)
1578 return result;
1580 connssl->connecting_state = ssl_connect_done;
1583 if(connssl->connecting_state == ssl_connect_done) {
1584 connssl->state = ssl_connection_complete;
1585 *done = TRUE;
1588 return CURLE_OK;
1592 * return 0 error initializing SSL
1593 * return 1 SSL initialized successfully
1594 */
1595static int mbedtls_init(void)
1597#if MBEDTLS_VERSION_NUMBER < 0x04000000
1598 int ret = 0;
1599#endif
1600 psa_status_t status;
1601 status = psa_crypto_init();
1603 if(status != PSA_SUCCESS)
1604 return 0;
1606#if MBEDTLS_VERSION_NUMBER < 0x04000000
1607 mbedtls_ctr_drbg_init(&rng.drbg);
1608 mbedtls_entropy_init(&rng.entropy);
1610 ret = mbedtls_ctr_drbg_seed(&rng.drbg, mbedtls_entropy_func, &rng.entropy,
1611 NULL, 0);
1613 if(ret)
1614 /* mbedtls_ctr_drbg_seed returned error */
1615 return 0;
1617 /* To prevent an adversary from reading your random data,
1618 you can enable prediction resistance.
1620 Entropy is gathered before each mbedtls_ctr_drbg_random() call.
1621 Only use this if you have ample supply of good entropy.*/
1622 mbedtls_ctr_drbg_set_prediction_resistance(&rng.drbg,
1623 MBEDTLS_CTR_DRBG_PR_ON);
1624#endif
1625 return 1;
1628static void mbedtls_cleanup(void)
1630 mbedtls_psa_crypto_free();
1632#if MBEDTLS_VERSION_NUMBER < 0x04000000
1633 mbedtls_ctr_drbg_free(&rng.drbg);
1634 mbedtls_entropy_free(&rng.entropy);
1635#endif
1638static bool mbedtls_data_pending(struct Curl_cfilter *cf,
1639 const struct Curl_easy *data)
1641 struct ssl_connect_data *ctx = cf->ctx;
1642 struct mbed_ssl_backend_data *backend;
1644 (void)data;
1645 DEBUGASSERT(ctx && ctx->backend);
1646 backend = (struct mbed_ssl_backend_data *)ctx->backend;
1647 return mbedtls_ssl_get_bytes_avail(&backend->ssl) != 0;
1650static CURLcode mbedtls_sha256sum(const unsigned char *input,
1651 size_t inputlen,
1652 unsigned char *sha256sum,
1653 size_t sha256len)
1655#if defined(PSA_WANT_ALG_SHA_256) && PSA_WANT_ALG_SHA_256
1656 psa_status_t status;
1657 size_t sha256len_actual;
1658 status = psa_hash_compute(PSA_ALG_SHA_256, input, inputlen,
1659 sha256sum, sha256len,
1660 &sha256len_actual);
1661 if(status != PSA_SUCCESS)
1662 return CURLE_BAD_FUNCTION_ARGUMENT;
1663 return CURLE_OK;
1664#else
1665 (void)sha256len;
1666 return Curl_sha256it(sha256sum, input, inputlen);
1667#endif
1670static void *mbedtls_get_internals(struct ssl_connect_data *connssl,
1671 CURLINFO info)
1673 struct mbed_ssl_backend_data *backend =
1674 (struct mbed_ssl_backend_data *)connssl->backend;
1675 (void)info;
1676 DEBUGASSERT(backend);
1677 return &backend->ssl;
1680const struct Curl_ssl Curl_ssl_mbedtls = {
1681 { CURLSSLBACKEND_MBEDTLS, "mbedtls" }, /* info */
1683 SSLSUPP_CA_PATH |
1684 SSLSUPP_CAINFO_BLOB |
1685 SSLSUPP_CERTINFO |
1686#ifdef HAVE_PINNED_PUBKEY
1687 SSLSUPP_PINNEDPUBKEY |
1688#endif
1689 SSLSUPP_SSL_CTX |
1690#ifdef MBEDTLS_SSL_PROTO_TLS1_3 /* requires mbedTLS 3.6.0+ */
1691 SSLSUPP_TLS13_CIPHERSUITES |
1692#endif
1693 SSLSUPP_HTTPS_PROXY |
1694 SSLSUPP_CIPHER_LIST |
1695#ifdef MBEDTLS_X509_CRL_PARSE_C
1696 SSLSUPP_CRLFILE |
1697#endif
1698 0,
1700 sizeof(struct mbed_ssl_backend_data),
1702 mbedtls_init, /* init */
1703 mbedtls_cleanup, /* cleanup */
1704 mbedtls_version, /* version */
1705 mbedtls_shutdown, /* shutdown */
1706 mbedtls_data_pending, /* data_pending */
1707 mbedtls_random, /* random */
1708 NULL, /* cert_status_request */
1709 mbedtls_connect, /* connect */
1710 Curl_ssl_adjust_pollset, /* adjust_pollset */
1711 mbedtls_get_internals, /* get_internals */
1712 mbedtls_close, /* close_one */
1713 NULL, /* close_all */
1714 NULL, /* engines_list */
1715 mbedtls_sha256sum, /* sha256sum */
1716 mbed_recv, /* recv decrypted data */
1717 mbed_send, /* send data to encrypt */
1718 NULL, /* get_channel_binding */
1721#endif /* USE_MBEDTLS */
Diagnostics4 git calls · 32 ms
CallStatusSizeTime032 ms
discover200152 B3 ms
git.upload-pack discover
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=3
git.response.bytes=152
git.server.agent=gitty/1.0
git.server.object_format=sha1
git.server.caps=agent ls-refs fetch object-format
git.server.fetch=shallow filter sideband-all
git.protocol.version=2
git.pkt.frames=8
git.pkt.data=6
git.pkt.flush=2
git.pkt.delim=0
git.pkt.bytes=152
git.pkt.payload.max=34
ls-refs200149 B · hit3 ms
git.upload-pack ls-refs
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=3
git.response.bytes=149
git.response.cache=HIT
git.response.duration_ms=3
git.protocol.version=2
git.pkt.frames=3
git.pkt.data=2
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=149
git.pkt.payload.max=78
git.ls_refs.count=2
git.ls_refs.head=refs/heads/master
fetchblob:none · deepen 10200287 KiB · hit2 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=2
git.response.bytes=293470
git.response.cache=HIT
git.response.duration_ms=2
git.fetch.filter=blob:none
git.fetch.filter.requested=tree:0
git.fetch.filter.fallback=blob:none
git.fetch.filter.learned=false
git.fetch.wants=31c911efe5652725e930f4d2e60c9060e5f6646d
git.fetch.haves.count=0
git.fetch.deepen=10
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=10
git.pkt.data=8
git.pkt.flush=1
git.pkt.delim=1
git.pkt.bytes=293470
git.pkt.payload.max=65516
git.sideband.band1.bytes=293354
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=87
git.pack.bytes=293354
git.pack.ofs_delta=0
git.pack.ref_delta=1
git.pack.chain.max=1
git.pack.trailer=6a646bcda6740bab42e321b51998b52ea15146c0
git.pack.full=86
Open pack map
fetch20014 KiB · hit27 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=27
git.response.bytes=14088
git.response.cache=HIT
git.response.duration_ms=27
git.fetch.wants=428c3f3d55fbb6bdf8dc1f7a3995dd524e69fc0f
git.fetch.haves.count=0
git.fetch.deepen=0
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=3
git.pkt.data=2
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=14088
git.pkt.payload.max=14067
git.sideband.band1.bytes=14066
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0

Each row is one HTTP round trip ply made to the git server for this page, on one timeline. discover asks what the server speaks, ls-refs lists branch tips, fetch brings objects by id. A hit was served by Workers Cache. Tap a row for its wire details.

Remote
https://5ad2236b39de4c8bd8f6270ea63f3ea9.artifacts.cloudflare.net/git/public-v0/curl.git
Ref
refs/heads/master
Commit
31c911efe5652725e930f4d2e60c9060e5f6646d
cf-ray
a5e346755ab1f4d4
Request
092dbe79…
Protocol
v2 · sha1
Agent
gitty/1.0
Filter
advertised
Fetch
shallow filter sideband-all
Capabilities
agent ls-refs fetch object-format