From 4be00fd94b24c7ff2af4d608c499c529f99c1936 Mon Sep 17 00:00:00 2001 From: Paul Adelsbach Date: Thu, 12 Nov 2026 20:32:15 -0800 Subject: [PATCH 1/4] Add Mbed TLS 4.x verify callbacks and VERIFY_OPTIONAL --- .github/workflows/mbedtls-compat.yml | 13 +- README.md | 47 ++- src/mbedtls/mbedtls_compat_internal.h | 10 +- src/mbedtls/ssl.c | 274 +++++++++++-- src/mbedtls/x509.c | 5 +- test/mbedtls_compat/Makefile | 15 +- test/mbedtls_compat/programs.sh | 22 +- test/mbedtls_compat/ssl_test.c | 551 +++++++++++++++++++++++++- user_settings.h | 2 + wolfpsa/mbedtls_compat/mbedtls/ssl.h | 19 +- 10 files changed, 868 insertions(+), 90 deletions(-) diff --git a/.github/workflows/mbedtls-compat.yml b/.github/workflows/mbedtls-compat.yml index 0006f54..1934b59 100644 --- a/.github/workflows/mbedtls-compat.yml +++ b/.github/workflows/mbedtls-compat.yml @@ -14,8 +14,9 @@ jobs: strategy: fail-fast: false matrix: - # The compatibility layer needs wolfSSL master, not a release - wolfssl-ref: [ master ] + # The compatibility layer needs wolfSSL master, not a release. The + # verify callbacks need this pull request until it merges. + wolfssl-ref: [ pull/11110/head ] options: [ "", "MBEDTLS_THREADING_C=1 ASAN=1" ] steps: @@ -27,8 +28,12 @@ jobs: sudo apt-get update sudo apt-get install -y build-essential autoconf automake libtool libtool-bin pkg-config python3-jinja2 faketime - - name: Clone sibling wolfSSL - run: git clone --depth 1 --branch ${{ matrix.wolfssl-ref }} https://github.com/wolfSSL/wolfssl ../wolfssl + # Fetched by ref, which may be a pull request's + - name: Fetch sibling wolfSSL + run: | + git init -q ../wolfssl + git -C ../wolfssl fetch -q --depth 1 https://github.com/wolfSSL/wolfssl ${{ matrix.wolfssl-ref }} + git -C ../wolfssl checkout -q FETCH_HEAD # The tests need framework's data files, and tf-psa-crypto's headers for # the test certificates diff --git a/README.md b/README.md index 7ef43ed..352a636 100644 --- a/README.md +++ b/README.md @@ -126,6 +126,9 @@ make MBEDTLS_COMPAT=1 for example with `WOLFCRYPT_ONLY`, `MBEDTLS_SSL_TLS_C` is not defined. `MBEDTLS_NET_C` needs TLS and wolfSSL's socket I/O (no `WOLFSSL_USER_IO`). `MBEDTLS_PEM_PARSE_C` needs wolfCrypt's Base64 decoding (no `NO_CODING`). +- The verify callbacks need `WOLFSSL_ALWAYS_VERIFY_CB`, which wolfPSA's + `user_settings.h` defines. A build with its own `USER_SETTINGS_PATH` + defines it too. Mapped so far: @@ -133,29 +136,31 @@ Mapped so far: - pem: init, read_buffer, get_buffer, free - x509_crt: init, free, parse, parse_der, parse_file, parse_path; the default, next and suiteb profiles, as names only -- ssl_config: init, free, defaults; ssl_conf: authmode, ca_chain, own_cert, - min_tls_version, max_tls_version, ciphersuites, cert_profile, dbg, - endpoint, transport, get_endpoint, set_user_data_p, set_user_data_n, +- ssl_config: init, free, defaults; ssl_conf: authmode, verify, ca_chain, + own_cert, min_tls_version, max_tls_version, ciphersuites, cert_profile, + dbg, endpoint, transport, get_endpoint, set_user_data_p, set_user_data_n, get_user_data_p, get_user_data_n - ssl: init, free, setup, context_get_config, session_reset, set_bio, - set_hostname, set_session, get_session, handshake, is_handshake_over, - get_verify_result, get_ciphersuite, get_ciphersuite_id_from_ssl, - get_version, get_version_number, get_bytes_avail, read, write, - close_notify, set_user_data_p, set_user_data_n, get_user_data_p, - get_user_data_n; list_ciphersuites, get_ciphersuite_name, - get_ciphersuite_id + set_verify, set_hostname, set_session, get_session, handshake, + is_handshake_over, get_verify_result, get_ciphersuite, + get_ciphersuite_id_from_ssl, get_version, get_version_number, + get_bytes_avail, read, write, close_notify, set_user_data_p, + set_user_data_n, get_user_data_p, get_user_data_n; list_ciphersuites, + get_ciphersuite_name, get_ciphersuite_id - ssl_session: init, free; save and load return `MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE` Known differences from Mbed TLS: -- `MBEDTLS_SSL_VERIFY_OPTIONAL`, `mbedtls_ssl_conf_verify` and - `mbedtls_ssl_set_verify` are not available yet, so an application that - uses them does not build. -- With `MBEDTLS_SSL_VERIFY_REQUIRED`, the handshake stops at the first check - of the peer's chain that fails, and `mbedtls_ssl_get_verify_result` has - only its flag. Mbed TLS checks the whole chain first and reports the flag - of each failure. +- The verify flags come from wolfSSL, which reports one failure from each + certificate's signature and date checks, and one from the later checks of + the peer's own, such as the host name. So the verify callback and + `mbedtls_ssl_get_verify_result` can report fewer flags than Mbed TLS: an + untrusted certificate that has also expired is only `NOT_TRUSTED`. +- The verify callback gets the certificates the peer sent, in that order, + then above them the CA from the CA list that issued the last one. Mbed TLS + builds the chain itself, and leaves out a certificate the peer sent once + it reaches a CA from the list. - A wolfSSL error with no Mbed TLS match returns a general code for the call, such as `MBEDTLS_ERR_SSL_INTERNAL_ERROR`. wolfSSL's own codes are not returned: some Mbed TLS 4.x codes are PSA values (-128 to -160), which @@ -232,14 +237,14 @@ runs these against `libwolfpsa.a`. Each is also a target of its own. - `mbedtls-compat-unit`: `test/mbedtls_compat/x509_crt_test.c`, `pk_test.c` and `pem_test.c` parse Mbed TLS's test certificates and keys. - `ssl_test.c` checks return codes and verify results, client and server in - one process. + `ssl_test.c` checks return codes, verify results and the verify + callbacks, client and server in one process. - `mbedtls-compat-programs`: the Mbed TLS migration guide client (`test/mbedtls_compat/client-tls-mbedtls.c`) and Mbed TLS's sample programs, built unchanged, run against the wolfSSL example server. Mbed - TLS's server programs run against the wolfSSL example client. With - `MBEDTLS_THREADING_C=1`, `ssl_pthread_server` serves clients at the same - time. + TLS's server programs run against the wolfSSL example client and + `ssl_client1`. With `MBEDTLS_THREADING_C=1`, `ssl_pthread_server` serves + clients at the same time. Notes: diff --git a/src/mbedtls/mbedtls_compat_internal.h b/src/mbedtls/mbedtls_compat_internal.h index 379d5cd..9e5ec5d 100644 --- a/src/mbedtls/mbedtls_compat_internal.h +++ b/src/mbedtls/mbedtls_compat_internal.h @@ -19,13 +19,13 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ -/* Shared by ssl.c and net.c. Not part of the public API. */ +/* Shared by ssl.c, net.c and x509.c. Not part of the public API. */ #ifndef MBEDTLS_COMPAT_INTERNAL_H #define MBEDTLS_COMPAT_INTERNAL_H #include -#include +#include enum { MBED_IO_RECV = 0, @@ -37,4 +37,10 @@ WOLFSSL_LOCAL int MbedIoErr(int code, int dir, int toWolf); /* An I/O length as an int, at most max */ WOLFSSL_LOCAL int MbedIoLen(size_t len, int max); +struct DecodedCert; +/* Decodes der without verifying it. Free cert with wc_FreeDecodedCert() + * regardless of result. */ +WOLFSSL_LOCAL int MbedCertDecode(struct DecodedCert* cert, const byte* der, + word32 len); + #endif /* MBEDTLS_COMPAT_INTERNAL_H */ diff --git a/src/mbedtls/ssl.c b/src/mbedtls/ssl.c index 25ee76d..143ee38 100644 --- a/src/mbedtls/ssl.c +++ b/src/mbedtls/ssl.c @@ -45,11 +45,17 @@ #include #include #include +#include #include #include #include "mbedtls_compat_internal.h" #include "psa_tf_psa_internal.h" +/* MbedVerifyCb() needs the call for the peer's certificate when it passes */ +#ifndef WOLFSSL_ALWAYS_VERIFY_CB + #error "wolfPSA: MBEDTLS_COMPAT needs WOLFSSL_ALWAYS_VERIFY_CB" +#endif /* !WOLFSSL_ALWAYS_VERIFY_CB */ + /* Unknown codes map to the last entry */ int MbedIoErr(int code, int dir, int toWolf) { @@ -119,8 +125,12 @@ static int MbedSslErr(const mbedtls_ssl_context* ssl, int ret) int err = wolfSSL_get_error(ssl->ssl, ret); size_t i; - /* A failed verify is what ended the handshake */ - if (ssl->verify_flags != 0) { + if (ssl->verify_ret != 0) { + return ssl->verify_ret; + } + /* A failed verify with VERIFY_REQUIRED is what ended the handshake */ + if (ssl->verify_flags != 0 && + ssl->authmode == MBEDTLS_SSL_VERIFY_REQUIRED) { return ((ssl->verify_flags & ~MBED_USAGE_FLAGS) != 0) ? MBEDTLS_ERR_X509_CERT_VERIFY_FAILED : MBEDTLS_ERR_SSL_BAD_CERTIFICATE; @@ -245,17 +255,175 @@ static uint32_t MbedVerifyFlag(int err) return map[i].mbed; } -/* wolfSSL calls this for a failed check of the peer's chain. Keeps the - * check's flag for mbedtls_ssl_get_verify_result() and lets the handshake - * fail. */ +static int MbedChainNew(mbedtls_ssl_context* ssl, int len) +{ + const size_t sz = (size_t)len * sizeof(*ssl->chain_flags); + + ssl->chain_flags = (uint32_t*)XMALLOC(sz, NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (ssl->chain_flags == NULL) { + return MBEDTLS_ERR_X509_ALLOC_FAILED; + } + XMEMSET(ssl->chain_flags, 0, sz); + ssl->chain_len = len; + return 0; +} + +static void MbedChainFree(mbedtls_ssl_context* ssl) +{ + XFREE(ssl->chain_flags, NULL, DYNAMIC_TYPE_TMP_BUFFER); + ssl->chain_flags = NULL; + ssl->chain_len = 0; +} + +/* Sets *ca to the CA, of those wolfSSL loaded from conf's CA list, that + * issued top, the last certificate the peer sent, matched as wolfSSL finds a + * signer. NULL when top is one of them. */ +static int MbedChainCA(const mbedtls_ssl_config* conf, + const WOLFSSL_BUFFER_INFO* top, mbedtls_x509_crt** ca) +{ + DecodedCert* cert; + DecodedCert* issuer; + mbedtls_x509_crt* crt; + size_t i; + int ret = 0; + + *ca = NULL; + for (crt = conf->ca_chain, i = 0; crt != NULL && i < conf->ca_count; + crt = crt->next, i++) { + if (conf->ca_loaded[i] && crt->raw.len == top->length && + XMEMCMP(crt->raw.p, top->buffer, top->length) == 0) { + return 0; + } + } + + cert = (DecodedCert*)XMALLOC(sizeof(*cert), NULL, DYNAMIC_TYPE_DCERT); + issuer = (DecodedCert*)XMALLOC(sizeof(*issuer), NULL, DYNAMIC_TYPE_DCERT); + if (cert == NULL || issuer == NULL) { + ret = MBEDTLS_ERR_X509_ALLOC_FAILED; + } + if (ret == 0) { + ret = MbedCertDecode(cert, top->buffer, top->length); + for (crt = conf->ca_chain, i = 0; ret == 0 && *ca == NULL && + crt != NULL && i < conf->ca_count; crt = crt->next, i++) { + if (!conf->ca_loaded[i]) { + continue; + } + ret = MbedCertDecode(issuer, crt->raw.p, (word32)crt->raw.len); + if (ret == 0 && + XMEMCMP(issuer->subjectHash, cert->issuerHash, + KEYID_SIZE) == 0 && + (!cert->extAuthKeyIdSet || + XMEMCMP(issuer->extSubjKeyId, cert->extAuthKeyId, + KEYID_SIZE) == 0)) { + *ca = crt; + } + wc_FreeDecodedCert(issuer); + } + wc_FreeDecodedCert(cert); + ret = wolfPSA_MbedRet(ret, MBEDTLS_ERR_X509_FATAL_ERROR); + } + XFREE(issuer, NULL, DYNAMIC_TYPE_DCERT); + XFREE(cert, NULL, DYNAMIC_TYPE_DCERT); + return ret; +} + +/* As Mbed TLS does once it has checked the chain: calls the verify callback + * for each certificate from the top down, with its flags and the certificates + * the peer sent after it, the CA from the CA list first */ +static int MbedVerifyChain(mbedtls_ssl_context* ssl, + const WOLFSSL_X509_STORE_CTX* store) +{ + int (*f_vrfy)(void*, mbedtls_x509_crt*, int, uint32_t*) = ssl->f_vrfy; + void* p_vrfy = ssl->p_vrfy; + const uint32_t* chain = ssl->chain_flags; + const int top = ssl->chain_len - 1; + mbedtls_x509_crt peer; + mbedtls_x509_crt* ca = NULL; + mbedtls_x509_crt* crt; + uint32_t flags = 0; + uint32_t usage; + int depth; + int i; + int ret = 0; + + if (f_vrfy == NULL) { + f_vrfy = ssl->conf->f_vrfy; + p_vrfy = ssl->conf->p_vrfy; + } + mbedtls_x509_crt_init(&peer); + for (i = 0; f_vrfy != NULL && ret == 0 && i <= top; i++) { + ret = mbedtls_x509_crt_parse_der(&peer, store->certs[i].buffer, + store->certs[i].length); + } + if (f_vrfy != NULL && ret == 0 && + (chain[top] & MBEDTLS_X509_BADCERT_NOT_TRUSTED) == 0) { + ret = MbedChainCA(ssl->conf, &store->certs[top], &ca); + } + if (ret == 0 && ca != NULL) { + ret = f_vrfy(p_vrfy, ca, top + 1, &flags); + } + ssl->verify_flags = flags; + + for (depth = top; ret == 0 && depth >= 0; depth--) { + usage = (depth == 0) ? (chain[0] & MBED_USAGE_FLAGS) : 0; + flags = chain[depth] & ~usage; + if (f_vrfy != NULL) { + for (crt = &peer, i = 0; i < depth; i++) { + crt = crt->next; + } + ret = f_vrfy(p_vrfy, crt, depth, &flags); + } + ssl->verify_flags |= flags | usage; + } + mbedtls_x509_crt_free(&peer); + + /* As in Mbed TLS, so it does not read as a failed verify */ + return (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) ? + MBEDTLS_ERR_X509_FATAL_ERROR : ret; +} + +/* wolfSSL calls this for each failed check in the peer's chain, top down, + * then last for the peer's certificate. Until then it records the flag and + * accepts, so the app's callback and the result see the whole chain, as in + * Mbed TLS. A chain CA accepted here is trusted only by this connection. */ static int MbedVerifyCb(int preverify, WOLFSSL_X509_STORE_CTX* store) { mbedtls_ssl_context* s = (mbedtls_ssl_context*)store->userCtx; + const int depth = store->error_depth; + int ret = 0; + + if (store->totalCerts <= 0) { + if (!preverify) { + s->verify_flags |= MbedVerifyFlag(store->error); + } + return preverify || s->authmode == MBEDTLS_SSL_VERIFY_OPTIONAL; + } + s->peer_cert = 1; + if (s->chain_flags == NULL) { + ret = MbedChainNew(s, store->totalCerts); + } + if (ret == 0 && (s->chain_len != store->totalCerts || depth < 0 || + depth >= s->chain_len)) { + ret = MBEDTLS_ERR_X509_FATAL_ERROR; + } + if (ret == 0 && !preverify) { + s->chain_flags[depth] |= MbedVerifyFlag(store->error); + } + if (ret == 0 && (depth > 0 || + s->ssl->options.asyncState != TLS_ASYNC_FINALIZE)) { + return 1; + } - if (!preverify) { - s->verify_flags |= MbedVerifyFlag(store->error); + if (ret == 0) { + ret = MbedVerifyChain(s, store); + } + MbedChainFree(s); + if (ret != 0) { + s->verify_ret = ret; + s->verify_flags = 0xFFFFFFFF; } - return preverify; + return ret == 0 && (s->verify_flags == 0 || + s->authmode == MBEDTLS_SSL_VERIFY_OPTIONAL); } void mbedtls_ssl_config_init(mbedtls_ssl_config* conf) @@ -273,57 +441,82 @@ void mbedtls_ssl_config_free(mbedtls_ssl_config* conf) if (conf != NULL) { wolfSSL_CTX_free(conf->ctx); + XFREE(conf->ca_loaded, NULL, DYNAMIC_TYPE_TMP_BUFFER); XMEMSET(conf, 0, sizeof(*conf)); } } void mbedtls_ssl_conf_authmode(mbedtls_ssl_config* conf, int authmode) { + static const struct { + int mbed; + int wolf; + } modes[] = { + { MBEDTLS_SSL_VERIFY_NONE, WOLFSSL_VERIFY_NONE }, + { MBEDTLS_SSL_VERIFY_OPTIONAL, WOLFSSL_VERIFY_PEER }, + { MBEDTLS_SSL_VERIFY_REQUIRED, + WOLFSSL_VERIFY_PEER | WOLFSSL_VERIFY_FAIL_IF_NO_PEER_CERT } + }; + size_t i; + WOLFSSL_ENTER("mbedtls_ssl_conf_authmode"); if (conf == NULL) { return; } conf->changes++; - if (authmode != MBEDTLS_SSL_VERIFY_NONE && - authmode != MBEDTLS_SSL_VERIFY_REQUIRED) { + for (i = 0; i < XELEM_CNT(modes); i++) { + if (modes[i].mbed == authmode) { + break; + } + } + if (i == XELEM_CNT(modes)) { conf->err[MBED_CONF_ERR_AUTHMODE] = MBEDTLS_ERR_SSL_BAD_INPUT_DATA; return; } conf->err[MBED_CONF_ERR_AUTHMODE] = 0; conf->authmode = authmode; - if (conf->ctx == NULL) { - return; - } - if (authmode == MBEDTLS_SSL_VERIFY_NONE) { - wolfSSL_CTX_set_verify(conf->ctx, WOLFSSL_VERIFY_NONE, NULL); - } - else { - wolfSSL_CTX_set_verify(conf->ctx, - WOLFSSL_VERIFY_PEER | WOLFSSL_VERIFY_FAIL_IF_NO_PEER_CERT, - MbedVerifyCb); + if (conf->ctx != NULL) { + wolfSSL_CTX_set_verify(conf->ctx, modes[i].wolf, + (authmode == MBEDTLS_SSL_VERIFY_NONE) ? NULL : MbedVerifyCb); } } /* Loads conf->ca_chain into the WOLFSSL_CTX. Mbed TLS checks a CA only when * it is used, so a CA that wolfSSL rejects on load, such as an expired one, - * is left out. */ + * is left out. ca_loaded records which were loaded. */ static void MbedConfCAs(mbedtls_ssl_config* conf) { const mbedtls_x509_crt* crt; + size_t n = 0; int ret = (conf->ca_crl == NULL) ? 0 : MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; + int loaded; + XFREE(conf->ca_loaded, NULL, DYNAMIC_TYPE_TMP_BUFFER); + conf->ca_loaded = NULL; + conf->ca_count = 0; + for (crt = conf->ca_chain; crt != NULL; crt = crt->next) { + n++; + } if (ret == 0) { ret = MbedRet(wolfSSL_CTX_UnloadCAs(conf->ctx), MBEDTLS_ERR_SSL_BAD_INPUT_DATA); } + if (ret == 0 && n > 0) { + conf->ca_loaded = (unsigned char*)XMALLOC(n, NULL, + DYNAMIC_TYPE_TMP_BUFFER); + if (conf->ca_loaded == NULL) { + ret = MBEDTLS_ERR_SSL_ALLOC_FAILED; + } + } for (crt = conf->ca_chain; ret == 0 && crt != NULL; crt = crt->next) { - if (crt->raw.p != NULL && - wolfSSL_CTX_load_verify_buffer(conf->ctx, crt->raw.p, - (long)crt->raw.len, WOLFSSL_FILETYPE_ASN1) == - WC_NO_ERR_TRACE(MEMORY_E)) { + loaded = (crt->raw.p == NULL) ? WOLFSSL_FAILURE : + wolfSSL_CTX_load_verify_buffer(conf->ctx, crt->raw.p, + (long)crt->raw.len, WOLFSSL_FILETYPE_ASN1); + if (loaded == WC_NO_ERR_TRACE(MEMORY_E)) { ret = MBEDTLS_ERR_SSL_ALLOC_FAILED; } + conf->ca_loaded[conf->ca_count++] = (loaded == WOLFSSL_SUCCESS); } conf->err[MBED_CONF_ERR_CA] = ret; } @@ -555,6 +748,18 @@ void mbedtls_ssl_conf_cert_profile(mbedtls_ssl_config* conf, (void)profile; } +void mbedtls_ssl_conf_verify(mbedtls_ssl_config* conf, + int (*f_vrfy)(void*, mbedtls_x509_crt*, int, uint32_t*), void* p_vrfy) +{ + WOLFSSL_ENTER("mbedtls_ssl_conf_verify"); + + if (conf != NULL) { + conf->f_vrfy = f_vrfy; + conf->p_vrfy = p_vrfy; + conf->changes++; + } +} + #define MBED_SUITES_MAX (WOLFSSL_MAX_SUITE_SZ / 2) #define MBED_SUITE_NAME_SZ 64 @@ -684,6 +889,7 @@ void mbedtls_ssl_free(mbedtls_ssl_context* ssl) WOLFSSL_ENTER("mbedtls_ssl_free"); if (ssl != NULL) { + MbedChainFree(ssl); wolfSSL_free(ssl->ssl); XFREE(ssl->hostname, NULL, DYNAMIC_TYPE_DOMAIN); XMEMSET(ssl, 0, sizeof(*ssl)); @@ -824,6 +1030,9 @@ static int MbedSslNew(mbedtls_ssl_context* ssl) ssl->started = 0; ssl->authmode = ssl->conf->authmode; ssl->verify_flags = 0; + MbedChainFree(ssl); + ssl->verify_ret = 0; + ssl->peer_cert = 0; ssl->io_err = 0; wolfSSL_SSLSetIORecv(ssl->ssl, MbedRecvCb); wolfSSL_SSLSetIOSend(ssl->ssl, MbedSendCb); @@ -899,6 +1108,17 @@ void mbedtls_ssl_set_bio(mbedtls_ssl_context* ssl, void* p_bio, } } +void mbedtls_ssl_set_verify(mbedtls_ssl_context* ssl, + int (*f_vrfy)(void*, mbedtls_x509_crt*, int, uint32_t*), void* p_vrfy) +{ + WOLFSSL_ENTER("mbedtls_ssl_set_verify"); + + if (ssl != NULL) { + ssl->f_vrfy = f_vrfy; + ssl->p_vrfy = p_vrfy; + } +} + /* Before mbedtls_ssl_setup too, as in Mbed TLS. NULL skips the name check. */ int mbedtls_ssl_set_hostname(mbedtls_ssl_context* ssl, const char* hostname) { @@ -1012,6 +1232,10 @@ uint32_t mbedtls_ssl_get_verify_result(const mbedtls_ssl_context* ssl) if (ssl->authmode == MBEDTLS_SSL_VERIFY_NONE) { return MBEDTLS_X509_BADCERT_SKIP_VERIFY; } + /* With VERIFY_OPTIONAL, a client may send no certificate */ + if (!ssl->peer_cert) { + return MBEDTLS_X509_BADCERT_MISSING; + } /* A server keeps no verify result with a session it resumes */ return wolfSSL_session_reused(ssl->ssl) ? MBEDTLS_X509_BADCERT_MISSING : 0; diff --git a/src/mbedtls/x509.c b/src/mbedtls/x509.c index 89dd61f..614d920 100644 --- a/src/mbedtls/x509.c +++ b/src/mbedtls/x509.c @@ -35,6 +35,7 @@ #include #include #include "psa_tf_psa_internal.h" +#include "mbedtls_compat_internal.h" /* The generated config has MBEDTLS_X509_CRT_PARSE_C when wolfCrypt parses * certificates */ @@ -52,9 +53,7 @@ #include #endif /* MBEDTLS_FS_IO && !NO_WOLFSSL_DIR && !_WIN32 */ -/* Decodes der without verifying it. Free cert with wc_FreeDecodedCert() - * whatever the result. */ -static int MbedCertDecode(DecodedCert* cert, const byte* der, word32 len) +int MbedCertDecode(DecodedCert* cert, const byte* der, word32 len) { wc_InitDecodedCert(cert, der, len, NULL); return wc_ParseCert(cert, CERT_TYPE, NO_VERIFY, NULL); diff --git a/test/mbedtls_compat/Makefile b/test/mbedtls_compat/Makefile index 124f638..9af2b50 100644 --- a/test/mbedtls_compat/Makefile +++ b/test/mbedtls_compat/Makefile @@ -43,8 +43,8 @@ WOLFSSL_CLIENT := $(WOLFSSL_BUILD)/examples/client/client # Mbed TLS migration guide client CLIENT := $(BUILD_DIR)/client-tls-mbedtls # Mbed TLS sample programs, built unchanged from MBEDTLS_PATH -PROGRAMS := $(addprefix $(BUILD_DIR)/programs/ssl/,mini_client ssl_server \ - ssl_fork_server) +PROGRAMS := $(addprefix $(BUILD_DIR)/programs/ssl/,mini_client ssl_client1 \ + ssl_server ssl_fork_server) # Threads, with MBEDTLS_THREADING_C=1 ifeq ($(MBEDTLS_THREADING_C),1) PROGRAMS += $(BUILD_DIR)/programs/ssl/ssl_pthread_server @@ -91,16 +91,17 @@ data-check: exit 1; \ fi -# x509_crt_test sets wolfSSL's allocators. WOLFSSL_FLAGS configures the -# wolfSSL headers as for libwolfpsa.a. -$(BUILD_DIR)/x509_crt_test: LAYER_FLAGS += $(WOLFSSL_FLAGS) -I$(WOLFPSA_PATH) +# x509_crt_test and ssl_test set wolfSSL's allocators. WOLFSSL_FLAGS +# configures the wolfSSL headers as for libwolfpsa.a. +$(addprefix $(BUILD_DIR)/,x509_crt_test ssl_test): \ + LAYER_FLAGS += $(WOLFSSL_FLAGS) -I$(WOLFPSA_PATH) $(CLIENT): client-tls-mbedtls.c $(UNIT): $(BUILD_DIR)/%: %.c $(PROGRAMS): $(BUILD_DIR)/programs/%: $(MBEDTLS_PATH)/programs/%.c $(PROGRAMS): override CPPFLAGS += -I$(MBEDTLS_PATH)/tests/include -$(addprefix $(BUILD_DIR)/programs/ssl/,ssl_server ssl_fork_server \ - ssl_pthread_server): $(CERTS) +$(addprefix $(BUILD_DIR)/programs/ssl/,ssl_client1 ssl_server \ + ssl_fork_server ssl_pthread_server): $(CERTS) $(CLIENT) $(UNIT) $(PROGRAMS): $(WOLFPSA_LIB) @mkdir -p $(@D) $(call link,$(LAYER_FLAGS),$(LAYER_LIBS)) diff --git a/test/mbedtls_compat/programs.sh b/test/mbedtls_compat/programs.sh index dbeb9cc..fa92396 100755 --- a/test/mbedtls_compat/programs.sh +++ b/test/mbedtls_compat/programs.sh @@ -6,8 +6,8 @@ # macro prints "... not defined" and exits 0, so that output fails the case, # and a case can require a line of output. A case whose wrapper, such as # faketime, is not installed is skipped. Then Mbed TLS's server programs, -# against the wolfSSL example client. WRAP prefixes the programs. Run by the -# Makefile in this directory, which sets the paths. +# against the wolfSSL example client and ssl_client1. WRAP prefixes the +# programs. Run by the Makefile in this directory, which sets the paths. : "${BUILD_DIR:?}" "${WOLFSSL_PATH:?}" "${WOLFSSL_SERVER:?}" \ "${WOLFSSL_CLIENT:?}" "${MBEDTLS_PATH:?}" @@ -52,6 +52,11 @@ P=programs/ssl SERVER5="-p 4433 -d -c $DATA/server5-expired.crt -k $DATA/server5.key" # Inside both validity periods: the CA ends 2023-09-22, the server 2014-03-08 CA2_DATE="faketime 2014-01-01" +# Signed by test-ca-sha256.crt, in certs.c's mbedtls_test_cas_pem +SERVER2="-p 4433 -d -c $DATA/server2-sha256.crt -k $DATA/server2.key" +# The wolfSSL example server's own certificate, from another CA +SERVER_WOLF="-p 4433 -d" +VERIFY="Verifying peer X.509 certificate..." # A CA that wolfSSL refuses to load, then the server's CA BUNDLE=$BUILD_DIR/ca-bundle.pem cat "$WOLFSSL_PATH/certs/test/expired/expired-ca.pem" \ @@ -94,6 +99,8 @@ wrong IP address host, VERIFY_FAILED|$C|-S 127.0.0.2 $LO|$TLS13||1|$GOT -9984 IPv6 address host, VERIFY_FAILED|$C|-S ::1 $LO|$TLS13||1|$GOT -9984 mini_client|$P/mini_client||$SERVER5|$CA2_DATE|0| mini_client, expired CA, ssl_handshake_failed|$P/mini_client||$SERVER5||7| +ssl_client1|$P/ssl_client1||$SERVER2||0|$VERIFY ok +ssl_client1, untrusted, OPTIONAL|$P/ssl_client1||$SERVER_WOLF||0|$VERIFY failed CASES rm -f "$READY" @@ -111,9 +118,12 @@ start_program() { done } -# Options for the wolfSSL example client +# Options for the wolfSSL example client, or a program run_client() { - "$WOLFSSL_CLIENT" -p 4433 -g -A "$CAS" "$@" + case "$1" in + -*) "$WOLFSSL_CLIENT" -p 4433 -g -A "$CAS" "$@" ;; + *) $WRAP "$BUILD_DIR/$1" ;; + esac } LOG=$BUILD_DIR/server.log @@ -127,7 +137,7 @@ cat "$DATA/test-ca-sha256.crt" "$DATA/test-ca-sha1.crt" \ THREADED= if [ "$MBEDTLS_THREADING_C" = 1 ]; then # ssl_pthread_server's limit, MAX_NUM_THREADS - FIVE="-v 4&-v 3&-v 4&-v 3&-v 4" + FIVE="-v 4&-v 3&-v 4&-v 3&$P/ssl_client1" THREADED="ssl_pthread_server, 5 clients at once|$P/ssl_pthread_server|$FIVE" fi @@ -184,7 +194,7 @@ server: $(cat "$LOG")" FAILS=$((FAILS + 1)) fi done < +#include #include #include #include @@ -40,14 +41,19 @@ #ifdef MBEDTLS_SSL_CACHE_C #include #endif /* MBEDTLS_SSL_CACHE_C */ +#include +#include #define CA_FILE "test-ca2.crt" +/* A CA_FILE that is not valid until 2029, then CA_FILE */ +#define FUTURE_CA_FILE "test-ca2_cat-future-present.crt" #define CERT_FILE "server5.crt" #define KEY_FILE "server5.key" /* server5.crt with server authentication as its only extended key usage */ #define EKU_SRV_FILE "server5.eku-srv.crt" /* localhost, two intermediate CAs, then test-ca.crt */ #define CHAIN_FILE "server10_int3_int-ca2.crt" +#define LEAF_FILE "server10.crt" #define LEAF_KEY_FILE "server10.key" #define ROOT_FILE "test-ca.crt" /* Self-signed with server5.key, IP address SANs 97.98.99.100 and @@ -57,6 +63,12 @@ #define HOST_NAME "localhost" /* Handshake steps for each side */ #define MAX_STEPS 20 +/* Verify callback calls recorded */ +#define MAX_CALLS 8 +/* A verify callback's own return code */ +#define VERIFY_CB_ERR -0x1234 +/* Allocations before the CA's verify callback that VerifyNoMemory fails */ +#define NO_MEMORY_TRIES 32 /* TLS_AES_128_GCM_SHA256, which wolfSSL does not pick by default */ #define SUITE_ID 0x1301 #define SUITE_NAME "TLS1-3-AES-128-GCM-SHA256" @@ -89,11 +101,27 @@ typedef struct { mbedtls_pk_context* key; } Certs; +/* What a verify callback saw and what it does. want is the certificate + * list expected at each depth. */ +typedef struct { + const mbedtls_x509_crt* want[MAX_CALLS]; + int depth[MAX_CALLS]; + uint32_t flags[MAX_CALLS]; + int calls; + int same; /* each certificate and the list after it was as expected */ + uint32_t clear; + uint32_t set; /* at depth 0 */ + int ret; + int ret2; /* the client's result in a second handshake */ + uint32_t flags2; /* and its verify result */ +} Verify; + static mbedtls_x509_crt ca; static mbedtls_x509_crt cert; static mbedtls_pk_context key; static mbedtls_x509_crt root; static mbedtls_x509_crt chain; +static mbedtls_x509_crt leaf; static mbedtls_pk_context leafKey; static mbedtls_x509_crt ekuSrv; static mbedtls_x509_crt ipSan; @@ -107,6 +135,11 @@ static Pipe toClient; static Pipe toServer; static Peer cli; static Peer srv; +/* A second client and server, with pipes of their own */ +static Pipe toClient2; +static Pipe toServer2; +static Peer cli2; +static Peer srv2; static int PipeSend(void* ctx, const unsigned char* buf, size_t len) { @@ -147,10 +180,14 @@ static int PipeRecv(void* ctx, unsigned char* buf, size_t len) static void PeerInit(Peer* p, int endpoint) { + const int second = (p == &cli2 || p == &srv2); + Pipe* toCli = second ? &toClient2 : &toClient; + Pipe* toSrv = second ? &toServer2 : &toServer; + mbedtls_ssl_config_init(&p->conf); mbedtls_ssl_init(&p->ssl); - p->rx = (endpoint == MBEDTLS_SSL_IS_CLIENT) ? &toClient : &toServer; - p->tx = (endpoint == MBEDTLS_SSL_IS_CLIENT) ? &toServer : &toClient; + p->rx = (endpoint == MBEDTLS_SSL_IS_CLIENT) ? toCli : toSrv; + p->tx = (endpoint == MBEDTLS_SSL_IS_CLIENT) ? toSrv : toCli; p->sendErr = 0; p->recvErr = 0; memset(p->tx, 0, sizeof(*p->tx)); @@ -200,8 +237,8 @@ static int Waiting(int ret) ret == MBEDTLS_ERR_SSL_WANT_WRITE; } -/* The client's result. *srvRet gets the server's. */ -static int Handshake(int* srvRet) +/* The result of client. *srvRet gets server's. */ +static int HandshakeOf(Peer* client, Peer* server, int* srvRet) { int c = MBEDTLS_ERR_SSL_WANT_READ; int s = MBEDTLS_ERR_SSL_WANT_READ; @@ -209,16 +246,21 @@ static int Handshake(int* srvRet) for (i = 0; i < MAX_STEPS && (Waiting(c) || Waiting(s)); i++) { if (Waiting(c)) { - c = mbedtls_ssl_handshake(&cli.ssl); + c = mbedtls_ssl_handshake(&client->ssl); } if (Waiting(s)) { - s = mbedtls_ssl_handshake(&srv.ssl); + s = mbedtls_ssl_handshake(&server->ssl); } } *srvRet = s; return c; } +static int Handshake(int* srvRet) +{ + return HandshakeOf(&cli, &srv, srvRet); +} + /* Connects a client with VERIFY_REQUIRED and HOST_NAME */ static int Connect(int srvAuthmode) { @@ -504,6 +546,440 @@ static int CaChainBeforeDefaults(void) return ok; } +static int NoClientCertOptional(void) +{ + int ok = Connect(MBEDTLS_SSL_VERIFY_OPTIONAL) == 0 && + mbedtls_ssl_get_verify_result(&cli.ssl) == 0 && + mbedtls_ssl_get_verify_result(&srv.ssl) == + MBEDTLS_X509_BADCERT_MISSING; + + PeerFree(&cli); + PeerFree(&srv); + return ok; +} + +/* Compares crt and the certificates after it with want */ +static int SameList(const mbedtls_x509_crt* crt, const mbedtls_x509_crt* want) +{ + for (; crt != NULL && want != NULL; crt = crt->next, want = want->next) { + if (crt->raw.len != want->raw.len || + memcmp(crt->raw.p, want->raw.p, crt->raw.len) != 0) { + return 0; + } + } + return crt == NULL && want == NULL; +} + +static int VerifyCb(void* ctx, mbedtls_x509_crt* crt, int depth, + uint32_t* flags) +{ + Verify* v = (Verify*)ctx; + + if (v->calls < MAX_CALLS) { + v->depth[v->calls] = depth; + v->flags[v->calls] = *flags; + } + if (depth >= 0 && depth < MAX_CALLS && v->want[depth] != NULL) { + v->same &= SameList(crt, v->want[depth]); + } + v->calls++; + *flags &= ~v->clear; + if (depth == 0) { + *flags |= v->set; + } + return v->ret; +} + +static void VerifyInit(Verify* v) +{ + memset(v, 0, sizeof(*v)); + v->same = 1; +} + +/* The callback ran n times, from depth n - 1 down to 0 */ +static int TopDown(const Verify* v, int n) +{ + int i; + + for (i = 0; i < n && i < MAX_CALLS; i++) { + if (v->depth[i] != n - 1 - i) { + return 0; + } + } + return v->calls == n; +} + +/* Client trusts certs->ca and verifies with VerifyCb(v); server sends + * certs->own */ +static int VerifyPeers(int authmode, const Certs* certs, const char* host, + Verify* v) +{ + int ok = PeerNewCerts(&cli, MBEDTLS_SSL_IS_CLIENT, authmode, certs, 1, + host) == 0 && + PeerNewCerts(&srv, MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_VERIFY_NONE, + certs, 0, NULL) == 0; + + if (ok) { + mbedtls_ssl_conf_verify(&cli.conf, VerifyCb, v); + } + return ok; +} + +/* From the root in the client's CA list down to the server's certificate, + * each with the certificates the server sent after it */ +static int VerifyTopDown(void) +{ + Verify v; + int s; + int ok; + + VerifyInit(&v); + v.want[0] = &chain; + v.want[1] = chain.next; + v.want[2] = chain.next->next; + v.want[3] = &root; + ok = VerifyPeers(MBEDTLS_SSL_VERIFY_REQUIRED, &chainCerts, HOST_NAME, + &v) && + Handshake(&s) == 0 && s == 0 && TopDown(&v, 4) && v.same && + (v.flags[0] | v.flags[1] | v.flags[2] | v.flags[3]) == 0 && + mbedtls_ssl_get_verify_result(&cli.ssl) == 0; + PeerFree(&cli); + PeerFree(&srv); + return ok; +} + +/* The flags of the untrusted top of the chain, cleared */ +static int VerifyClear(void) +{ + Verify v; + int s; + int ok; + + VerifyInit(&v); + v.clear = MBEDTLS_X509_BADCERT_NOT_TRUSTED; + v.want[0] = &chain; + v.want[1] = chain.next; + v.want[2] = chain.next->next; + ok = VerifyPeers(MBEDTLS_SSL_VERIFY_REQUIRED, &untrustedCerts, HOST_NAME, + &v) && + Handshake(&s) == 0 && s == 0 && TopDown(&v, 3) && v.same && + v.flags[0] == MBEDTLS_X509_BADCERT_NOT_TRUSTED && + (v.flags[1] | v.flags[2]) == 0 && + mbedtls_ssl_get_verify_result(&cli.ssl) == 0; + PeerFree(&cli); + PeerFree(&srv); + return ok; +} + +/* A name mismatch only, cleared, as for curl --no-verifyhost */ +static int VerifyClearHost(void) +{ + Verify v; + int s; + int ok; + + VerifyInit(&v); + v.clear = MBEDTLS_X509_BADCERT_CN_MISMATCH; + v.want[0] = &cert; + v.want[1] = &ca; + ok = VerifyPeers(MBEDTLS_SSL_VERIFY_REQUIRED, &defaultCerts, + "wrong.example.org", &v) && + Handshake(&s) == 0 && s == 0 && TopDown(&v, 2) && v.same && + v.flags[0] == 0 && v.flags[1] == MBEDTLS_X509_BADCERT_CN_MISMATCH && + mbedtls_ssl_get_verify_result(&cli.ssl) == 0; + PeerFree(&cli); + PeerFree(&srv); + return ok; +} + +/* The CA list has a CA that is not valid yet, then the same CA that is. The + * callback gets the second, the one wolfSSL loaded. */ +static int VerifyCaLoaded(void) +{ + mbedtls_x509_crt cas; + const Certs certs = { &cas, &cert, &key }; + Verify v; + int s; + int ok; + + VerifyInit(&v); + v.want[0] = &cert; + v.want[1] = &ca; + mbedtls_x509_crt_init(&cas); + ok = mbedtls_x509_crt_parse_file(&cas, FUTURE_CA_FILE) == 0 && + VerifyPeers(MBEDTLS_SSL_VERIFY_REQUIRED, &certs, HOST_NAME, &v) && + Handshake(&s) == 0 && s == 0 && TopDown(&v, 2) && v.same && + mbedtls_ssl_get_verify_result(&cli.ssl) == 0; + PeerFree(&cli); + PeerFree(&srv); + mbedtls_x509_crt_free(&cas); + return ok; +} + +static wolfSSL_Malloc_cb realMalloc; +/* Allocations since the count was reset, and the one that fails, 0 for + * none */ +static int allocs; +static int failAt; + +static void* FailMalloc(size_t size) +{ + if (++allocs == failAt) { + return NULL; + } + /* wolfSSL uses malloc() when no allocator is set */ + return (realMalloc != NULL) ? realMalloc(size) : malloc(size); +} + +/* Sets *ctx to the allocations before the CA's call */ +static int AllocsCb(void* ctx, mbedtls_x509_crt* crt, int depth, + uint32_t* flags) +{ + (void)crt; + (void)flags; + if (depth == 1) { + *(int*)ctx = allocs; + } + return 0; +} + +/* Fails each of the last allocations before the CA's verify callback. The + * handshake fails, or passes after the callback for the CA. */ +static int VerifyNoMemory(void) +{ + wolfSSL_Free_cb ff; + wolfSSL_Realloc_cb rf; + int caAllocs = 0; + int at; + int ret; + int s; + int i; + int ok = 1; + + (void)wolfSSL_GetAllocators(&realMalloc, &ff, &rf); + (void)wolfSSL_SetAllocators(FailMalloc, ff, rf); + for (i = 0; ok && i <= NO_MEMORY_TRIES && i <= caAllocs; i++) { + at = -1; + ok = PeerNew(&cli, MBEDTLS_SSL_IS_CLIENT, MBEDTLS_SSL_VERIFY_REQUIRED, + 1, HOST_NAME) == 0 && + PeerNew(&srv, MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_VERIFY_NONE, 0, + NULL) == 0; + if (ok) { + mbedtls_ssl_conf_verify(&cli.conf, AllocsCb, &at); + allocs = 0; + failAt = (i == 0) ? 0 : caAllocs + 1 - i; + ret = Handshake(&s); + failAt = 0; + ok = (i == 0) ? (ret == 0 && at > 0) : (ret != 0 || at >= 0); + } + if (i == 0) { + caAllocs = at; + } + PeerFree(&cli); + PeerFree(&srv); + } + (void)wolfSSL_SetAllocators(realMalloc, ff, rf); + return ok; +} + +/* The extended key usage of a client certificate is checked after the + * server's callback, which does not see it */ +static int VerifyUsage(void) +{ + Verify v; + int s = 0; + int ok; + + VerifyInit(&v); + v.clear = 0xFFFFFFFF; + ok = PeerNew(&cli, MBEDTLS_SSL_IS_CLIENT, MBEDTLS_SSL_VERIFY_REQUIRED, 1, + HOST_NAME) == 0 && + mbedtls_ssl_conf_own_cert(&cli.conf, &ekuSrv, &key) == 0 && + mbedtls_ssl_session_reset(&cli.ssl) == 0 && + PeerNew(&srv, MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_VERIFY_REQUIRED, 0, + NULL) == 0; + if (ok) { + mbedtls_ssl_conf_verify(&srv.conf, VerifyCb, &v); + (void)Handshake(&s); + ok = s == MBEDTLS_ERR_SSL_BAD_CERTIFICATE && TopDown(&v, 2) && + (v.flags[0] | v.flags[1]) == 0 && + mbedtls_ssl_get_verify_result(&srv.ssl) == + MBEDTLS_X509_BADCERT_EXT_KEY_USAGE; + } + PeerFree(&cli); + PeerFree(&srv); + return ok; +} + +/* A flag set on a good chain fails the handshake */ +static int VerifySet(void) +{ + Verify v; + int s; + int ok; + + VerifyInit(&v); + v.set = MBEDTLS_X509_BADCERT_OTHER; + ok = VerifyPeers(MBEDTLS_SSL_VERIFY_REQUIRED, &chainCerts, HOST_NAME, + &v) && + Handshake(&s) == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED && + TopDown(&v, 4) && + mbedtls_ssl_get_verify_result(&cli.ssl) == MBEDTLS_X509_BADCERT_OTHER; + PeerFree(&cli); + PeerFree(&srv); + return ok; +} + +/* A callback that fails stops the handshake, also with VERIFY_OPTIONAL */ +static int VerifyFails(int cbRet, int want) +{ + Verify v; + int s; + int ok; + + VerifyInit(&v); + v.ret = cbRet; + ok = VerifyPeers(MBEDTLS_SSL_VERIFY_OPTIONAL, &chainCerts, HOST_NAME, + &v) && + Handshake(&s) == want && v.calls == 1 && + mbedtls_ssl_get_verify_result(&cli.ssl) == 0xFFFFFFFF; + PeerFree(&cli); + PeerFree(&srv); + return ok; +} + +static int VerifyError(void) +{ + return VerifyFails(VERIFY_CB_ERR, VERIFY_CB_ERR); +} + +static int VerifyErrorVerifyFailed(void) +{ + return VerifyFails(MBEDTLS_ERR_X509_CERT_VERIFY_FAILED, + MBEDTLS_ERR_X509_FATAL_ERROR); +} + +/* The callback set on the context is used in place of the config's */ +static int VerifyContext(void) +{ + Verify vConf; + Verify v; + int s; + int ok; + + VerifyInit(&vConf); + VerifyInit(&v); + ok = VerifyPeers(MBEDTLS_SSL_VERIFY_REQUIRED, &chainCerts, HOST_NAME, + &vConf); + if (ok) { + mbedtls_ssl_set_verify(&cli.ssl, VerifyCb, &v); + ok = Handshake(&s) == 0 && vConf.calls == 0 && TopDown(&v, 4); + } + PeerFree(&cli); + PeerFree(&srv); + return ok; +} + +/* After a handshake that accepted the untrusted CAs of the chain, or + * rejected them, the next handshake on the config does not trust them */ +static int VerifyNoCaCache(int authmode, uint32_t clear, int want) +{ + const Certs leafCerts = { &ca, &leaf, &leafKey }; + Verify v; + int s; + int ok; + + VerifyInit(&v); + v.clear = clear; + ok = VerifyPeers(authmode, &untrustedCerts, HOST_NAME, &v) && + Handshake(&s) == want; + PeerFree(&srv); + if (ok) { + VerifyInit(&v); + memset(cli.tx, 0, sizeof(*cli.tx)); + ok = mbedtls_ssl_session_reset(&cli.ssl) == 0 && + PeerNewCerts(&srv, MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_VERIFY_NONE, + &leafCerts, 0, NULL) == 0; + } + if (ok) { + (void)Handshake(&s); + ok = (mbedtls_ssl_get_verify_result(&cli.ssl) & + MBEDTLS_X509_BADCERT_NOT_TRUSTED) != 0; + } + PeerFree(&cli); + PeerFree(&srv); + return ok; +} + +static int NoCaCacheOptional(void) +{ + return VerifyNoCaCache(MBEDTLS_SSL_VERIFY_OPTIONAL, 0, 0); +} + +static int NoCaCacheCleared(void) +{ + return VerifyNoCaCache(MBEDTLS_SSL_VERIFY_REQUIRED, + MBEDTLS_X509_BADCERT_NOT_TRUSTED, 0); +} + +static int NoCaCacheRejected(void) +{ + return VerifyNoCaCache(MBEDTLS_SSL_VERIFY_REQUIRED, 0, + MBEDTLS_ERR_X509_CERT_VERIFY_FAILED); +} + +/* Clears every flag. The first call runs a handshake of cli2, on the config + * of cli, with srv2, which sends only the chain's leaf. */ +static int VerifySecondCb(void* ctx, mbedtls_x509_crt* crt, int depth, + uint32_t* flags) +{ + const Certs leafCerts = { &ca, &leaf, &leafKey }; + Verify* v = (Verify*)ctx; + int s; + + (void)crt; + (void)depth; + *flags = 0; + if (v->calls++ > 0) { + return 0; + } + PeerInit(&cli2, MBEDTLS_SSL_IS_CLIENT); + if (mbedtls_ssl_setup(&cli2.ssl, &cli.conf) == 0 && + mbedtls_ssl_set_hostname(&cli2.ssl, HOST_NAME) == 0 && + PeerNewCerts(&srv2, MBEDTLS_SSL_IS_SERVER, + MBEDTLS_SSL_VERIFY_NONE, &leafCerts, 0, NULL) == 0) { + v->ret2 = HandshakeOf(&cli2, &srv2, &s); + v->flags2 = mbedtls_ssl_get_verify_result(&cli2.ssl); + } + PeerFree(&cli2); + PeerFree(&srv2); + return 0; +} + +/* While the verify callback of a handshake runs, after wolfSSL accepted the + * untrusted CAs of its chain, a handshake on the same config does not trust + * them */ +static int NoCaCacheDuringVerify(void) +{ + Verify v; + int s; + int ok = PeerNewCerts(&cli, MBEDTLS_SSL_IS_CLIENT, + MBEDTLS_SSL_VERIFY_REQUIRED, &untrustedCerts, 1, HOST_NAME) == 0 && + PeerNewCerts(&srv, MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_VERIFY_NONE, + &untrustedCerts, 0, NULL) == 0; + + VerifyInit(&v); + if (ok) { + mbedtls_ssl_set_verify(&cli.ssl, VerifySecondCb, &v); + ok = Handshake(&s) == 0 && s == 0 && v.calls == 3 && + v.ret2 == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED && + v.flags2 == MBEDTLS_X509_BADCERT_NOT_TRUSTED; + } + PeerFree(&cli); + PeerFree(&srv); + return ok; +} + static int ReadWrite(void) { unsigned char buf[16]; @@ -811,14 +1287,18 @@ static int AuthmodeNoneAfterSetup(void) } /* A TLS 1.2 handshake, then one with its session, set before conf_* calls as - * curl does. The new CA list does not trust the server, so only a resumed - * session passes, with the first result. want and flags are the client's. */ -static int Resume(int srvAuthmode, int want, uint32_t flags) + * curl does. The client verifies with authmode and the CAs of certs, then + * trusts only root, which changes the result of a full handshake. A resumed + * session keeps the first result and calls no verify callback. want and flags + * are the client's. */ +static int Resume(int authmode, const Certs* certs, int srvAuthmode, + int want, uint32_t flags) { #ifdef MBEDTLS_SSL_CACHE_C mbedtls_ssl_cache_context cache; #endif /* MBEDTLS_SSL_CACHE_C */ mbedtls_ssl_session session; + Verify v; int s = 0; int ok; @@ -826,10 +1306,11 @@ static int Resume(int srvAuthmode, int want, uint32_t flags) mbedtls_ssl_cache_init(&cache); #endif /* MBEDTLS_SSL_CACHE_C */ mbedtls_ssl_session_init(&session); - ok = PeerNew(&cli, MBEDTLS_SSL_IS_CLIENT, MBEDTLS_SSL_VERIFY_REQUIRED, 1, + VerifyInit(&v); + ok = PeerNewCerts(&cli, MBEDTLS_SSL_IS_CLIENT, authmode, certs, 1, HOST_NAME) == 0 && - PeerNew(&srv, MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_VERIFY_NONE, 0, - NULL) == 0; + PeerNewCerts(&srv, MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_VERIFY_NONE, + certs, 0, NULL) == 0; if (ok) { mbedtls_ssl_conf_max_tls_version(&cli.conf, MBEDTLS_SSL_VERSION_TLS1_2); #ifdef MBEDTLS_SSL_CACHE_C @@ -849,9 +1330,11 @@ static int Resume(int srvAuthmode, int want, uint32_t flags) mbedtls_ssl_set_session(&cli.ssl, &session) == 0; } if (ok) { + mbedtls_ssl_set_verify(&cli.ssl, VerifyCb, &v); mbedtls_ssl_conf_ca_chain(&cli.conf, &root, NULL); mbedtls_ssl_conf_authmode(&srv.conf, srvAuthmode); - ok = Handshake(&s) == want && (want != 0 || s == 0) && + ok = Handshake(&s) == want && + (want != 0 || (s == 0 && v.calls == 0)) && mbedtls_ssl_get_verify_result(&cli.ssl) == flags; } mbedtls_ssl_session_free(&session); @@ -865,14 +1348,22 @@ static int Resume(int srvAuthmode, int want, uint32_t flags) static int ResumeRequired(void) { - return Resume(MBEDTLS_SSL_VERIFY_NONE, 0, 0); + return Resume(MBEDTLS_SSL_VERIFY_REQUIRED, &defaultCerts, + MBEDTLS_SSL_VERIFY_NONE, 0, 0); +} + +static int ResumeOptional(void) +{ + return Resume(MBEDTLS_SSL_VERIFY_OPTIONAL, &untrustedCerts, + MBEDTLS_SSL_VERIFY_NONE, 0, MBEDTLS_X509_BADCERT_NOT_TRUSTED); } /* The session has no client certificate, so a full handshake */ static int ResumeServerRequired(void) { - return Resume(MBEDTLS_SSL_VERIFY_REQUIRED, - MBEDTLS_ERR_X509_CERT_VERIFY_FAILED, MBEDTLS_X509_BADCERT_NOT_TRUSTED); + return Resume(MBEDTLS_SSL_VERIFY_REQUIRED, &defaultCerts, + MBEDTLS_SSL_VERIFY_REQUIRED, MBEDTLS_ERR_X509_CERT_VERIFY_FAILED, + MBEDTLS_X509_BADCERT_NOT_TRUSTED); } /* The same endpoint and transport again keep the config */ @@ -910,10 +1401,10 @@ static void ConfCa(mbedtls_ssl_config* conf) mbedtls_ssl_conf_ca_chain(conf, &ca, NULL); } -/* MBEDTLS_SSL_VERIFY_OPTIONAL in Mbed TLS */ -static void ConfAuthmodeOptional(mbedtls_ssl_config* conf) +/* MBEDTLS_SSL_VERIFY_UNSET in Mbed TLS, only for SNI */ +static void ConfAuthmodeUnset(mbedtls_ssl_config* conf) { - mbedtls_ssl_conf_authmode(conf, 1); + mbedtls_ssl_conf_authmode(conf, 3); } static void ConfAuthmodeNone(mbedtls_ssl_config* conf) @@ -987,7 +1478,7 @@ static int CrlCleared(void) static int AuthmodeCleared(void) { - return ConfError(ConfAuthmodeOptional, MBEDTLS_ERR_SSL_BAD_INPUT_DATA, + return ConfError(ConfAuthmodeUnset, MBEDTLS_ERR_SSL_BAD_INPUT_DATA, mbedtls_ssl_session_reset, ConfAuthmodeNone); } @@ -1186,6 +1677,7 @@ static const struct { /* First: the list is made on the first lookup */ { "cipher suite lookups, threads at once", SuitesThreads }, #endif /* MBEDTLS_THREADING_C */ + { "no client certificate, OPTIONAL", NoClientCertOptional }, { "no client certificate, REQUIRED", NoClientCertRequired }, { "host name not set", HostNotSet }, { "host name cleared", HostCleared }, @@ -1202,6 +1694,21 @@ static const struct { { "client certificate for servers only", ClientCertUsage }, { "VERIFY_NONE", VerifyNone }, { "CA list set before config_defaults", CaChainBeforeDefaults }, + { "verify callback, top down", VerifyTopDown }, + { "verify callback clears NOT_TRUSTED", VerifyClear }, + { "verify callback clears CN_MISMATCH", VerifyClearHost }, + { "verify callback gets the CA wolfSSL loaded", VerifyCaLoaded }, + { "allocation failures before the CA's verify callback", VerifyNoMemory }, + { "verify callback cannot clear EXT_KEY_USAGE", VerifyUsage }, + { "verify callback sets a flag", VerifySet }, + { "verify callback error", VerifyError }, + { "verify callback returns CERT_VERIFY_FAILED", VerifyErrorVerifyFailed }, + { "verify callback on the context", VerifyContext }, + { "untrusted chain CA not kept, OPTIONAL", NoCaCacheOptional }, + { "untrusted chain CA not kept, cleared", NoCaCacheCleared }, + { "untrusted chain CA not kept, rejected", NoCaCacheRejected }, + { "untrusted chain CA not used during the verify callback", + NoCaCacheDuringVerify }, { "write and read", ReadWrite }, { "zero-length write", WriteZero }, { "EOF without close_notify", ReadEof }, @@ -1216,6 +1723,7 @@ static const struct { { "version ranges", VersionRanges }, { "VERIFY_NONE set after setup, no host name", AuthmodeNoneAfterSetup }, { "session resumed, REQUIRED", ResumeRequired }, + { "session resumed, OPTIONAL", ResumeOptional }, { "session without a client certificate, server REQUIRED", ResumeServerRequired }, { "same endpoint and transport set again", EndpointSame }, @@ -1244,6 +1752,7 @@ int main(void) mbedtls_pk_init(&key); mbedtls_x509_crt_init(&root); mbedtls_x509_crt_init(&chain); + mbedtls_x509_crt_init(&leaf); mbedtls_pk_init(&leafKey); mbedtls_x509_crt_init(&ekuSrv); mbedtls_x509_crt_init(&ipSan); @@ -1253,6 +1762,7 @@ int main(void) mbedtls_pk_parse_keyfile(&key, KEY_FILE, NULL) != 0 || mbedtls_x509_crt_parse_file(&root, ROOT_FILE) != 0 || mbedtls_x509_crt_parse_file(&chain, CHAIN_FILE) != 0 || + mbedtls_x509_crt_parse_file(&leaf, LEAF_FILE) != 0 || mbedtls_pk_parse_keyfile(&leafKey, LEAF_KEY_FILE, NULL) != 0 || mbedtls_x509_crt_parse_file(&ekuSrv, EKU_SRV_FILE) != 0 || mbedtls_x509_crt_parse_file(&ipSan, IP_SAN_FILE) != 0) { @@ -1271,6 +1781,7 @@ int main(void) mbedtls_x509_crt_free(&ipSan); mbedtls_x509_crt_free(&ekuSrv); mbedtls_pk_free(&leafKey); + mbedtls_x509_crt_free(&leaf); mbedtls_x509_crt_free(&chain); mbedtls_x509_crt_free(&root); mbedtls_pk_free(&key); diff --git a/user_settings.h b/user_settings.h index a6c89d7..b41c39f 100644 --- a/user_settings.h +++ b/user_settings.h @@ -159,6 +159,8 @@ #define WOLFSSL_SET_CIPHER_BYTES /* An IP address host name is checked against the certificate's IP SANs */ #define WOLFSSL_IP_ALT_NAME +/* The verify callbacks need the call for a peer certificate that passes */ +#define WOLFSSL_ALWAYS_VERIFY_CB #endif /* WOLFPSA_MBEDTLS_COMPAT */ #endif /* __ZEPHYR__ */ diff --git a/wolfpsa/mbedtls_compat/mbedtls/ssl.h b/wolfpsa/mbedtls_compat/mbedtls/ssl.h index 102ca38..67159c2 100644 --- a/wolfpsa/mbedtls_compat/mbedtls/ssl.h +++ b/wolfpsa/mbedtls_compat/mbedtls/ssl.h @@ -42,8 +42,8 @@ #define MBEDTLS_SSL_TRANSPORT_STREAM 0 #define MBEDTLS_SSL_TRANSPORT_DATAGRAM 1 #define MBEDTLS_SSL_PRESET_DEFAULT 0 -/* No MBEDTLS_SSL_VERIFY_OPTIONAL yet */ #define MBEDTLS_SSL_VERIFY_NONE 0 +#define MBEDTLS_SSL_VERIFY_OPTIONAL 1 #define MBEDTLS_SSL_VERIFY_REQUIRED 2 #define MBEDTLS_SSL_MAX_HOST_NAME_LEN 255 @@ -96,7 +96,11 @@ typedef struct mbedtls_ssl_config { mbedtls_ssl_protocol_version max_tls_version; const int* ciphersuites; /* the application's, NULL for the default */ mbedtls_x509_crt* ca_chain; /* the application's */ + unsigned char* ca_loaded; /* per CA of ca_chain, 1 if wolfSSL loaded it */ + size_t ca_count; /* of ca_loaded */ mbedtls_x509_crl* ca_crl; /* not supported, an error when set */ + int (*f_vrfy)(void*, mbedtls_x509_crt*, int, uint32_t*); + void* p_vrfy; mbedtls_ssl_user_data_t user_data; } mbedtls_ssl_config; @@ -121,7 +125,14 @@ typedef struct mbedtls_ssl_context { mbedtls_ssl_recv_timeout_t* f_recv_timeout; int io_err; /* the last BIO call's error, 0 after data */ int authmode; - uint32_t verify_flags; /* MBEDTLS_X509_BADCERT_* of the failed check */ + uint32_t verify_flags; /* MBEDTLS_X509_BADCERT_* from the handshake */ + /* Used in place of the config's when set */ + int (*f_vrfy)(void*, mbedtls_x509_crt*, int, uint32_t*); + void* p_vrfy; + int verify_ret; /* the verify callback's error */ + int peer_cert; /* the peer sent a certificate */ + uint32_t* chain_flags; /* of each certificate, while the chain is checked */ + int chain_len; mbedtls_ssl_user_data_t user_data; } mbedtls_ssl_context; @@ -147,6 +158,8 @@ void mbedtls_ssl_conf_ciphersuites(mbedtls_ssl_config* conf, const int* ciphersuites); void mbedtls_ssl_conf_cert_profile(mbedtls_ssl_config* conf, const mbedtls_x509_crt_profile* profile); +void mbedtls_ssl_conf_verify(mbedtls_ssl_config* conf, + int (*f_vrfy)(void*, mbedtls_x509_crt*, int, uint32_t*), void* p_vrfy); static inline void mbedtls_ssl_conf_set_user_data_p(mbedtls_ssl_config* conf, void* p) @@ -184,6 +197,8 @@ int mbedtls_ssl_session_reset(mbedtls_ssl_context* ssl); void mbedtls_ssl_set_bio(mbedtls_ssl_context* ssl, void* p_bio, mbedtls_ssl_send_t* f_send, mbedtls_ssl_recv_t* f_recv, mbedtls_ssl_recv_timeout_t* f_recv_timeout); +void mbedtls_ssl_set_verify(mbedtls_ssl_context* ssl, + int (*f_vrfy)(void*, mbedtls_x509_crt*, int, uint32_t*), void* p_vrfy); int mbedtls_ssl_set_hostname(mbedtls_ssl_context* ssl, const char* hostname); int mbedtls_ssl_handshake(mbedtls_ssl_context* ssl); int mbedtls_ssl_is_handshake_over(mbedtls_ssl_context* ssl); From 944c3be5b5b426a5be523f01d7270d3c295e0c2a Mon Sep 17 00:00:00 2001 From: Paul Adelsbach Date: Mon, 16 Nov 2026 15:36:50 -0800 Subject: [PATCH 2/4] Address verify review: OPENSSL_EXTRA CA call, self-signed, CA ids --- src/mbedtls/ssl.c | 88 ++++++++++++++++++---------- test/mbedtls_compat/ssl_test.c | 77 +++++++++++++++++++++++- wolfpsa/mbedtls_compat/mbedtls/ssl.h | 5 +- 3 files changed, 137 insertions(+), 33 deletions(-) diff --git a/src/mbedtls/ssl.c b/src/mbedtls/ssl.c index 143ee38..183b227 100644 --- a/src/mbedtls/ssl.c +++ b/src/mbedtls/ssl.c @@ -227,6 +227,8 @@ static uint32_t MbedVerifyFlag(int err) { WC_NO_ERR_TRACE(ASN_AFTER_DATE_E), MBEDTLS_X509_BADCERT_EXPIRED }, { WC_NO_ERR_TRACE(ASN_BEFORE_DATE_E), MBEDTLS_X509_BADCERT_FUTURE }, { WC_NO_ERR_TRACE(ASN_NO_SIGNER_E), MBEDTLS_X509_BADCERT_NOT_TRUSTED }, + { WC_NO_ERR_TRACE(ASN_SELF_SIGNED_E), + MBEDTLS_X509_BADCERT_NOT_TRUSTED }, { WC_NO_ERR_TRACE(ASN_SIG_CONFIRM_E), MBEDTLS_X509_BADCERT_NOT_TRUSTED }, { WC_NO_ERR_TRACE(DOMAIN_NAME_MISMATCH), @@ -275,14 +277,21 @@ static void MbedChainFree(mbedtls_ssl_context* ssl) ssl->chain_len = 0; } +/* How wolfSSL finds a CA of the config's list as a signer */ +typedef struct wolfPSA_MbedCaId { + byte loaded; + byte subjectHash[KEYID_SIZE]; + byte skid[KEYID_SIZE]; +} MbedCaId; + /* Sets *ca to the CA, of those wolfSSL loaded from conf's CA list, that * issued top, the last certificate the peer sent, matched as wolfSSL finds a * signer. NULL when top is one of them. */ static int MbedChainCA(const mbedtls_ssl_config* conf, const WOLFSSL_BUFFER_INFO* top, mbedtls_x509_crt** ca) { + const MbedCaId* id; DecodedCert* cert; - DecodedCert* issuer; mbedtls_x509_crt* crt; size_t i; int ret = 0; @@ -290,39 +299,33 @@ static int MbedChainCA(const mbedtls_ssl_config* conf, *ca = NULL; for (crt = conf->ca_chain, i = 0; crt != NULL && i < conf->ca_count; crt = crt->next, i++) { - if (conf->ca_loaded[i] && crt->raw.len == top->length && + if (conf->ca_ids[i].loaded && crt->raw.len == top->length && XMEMCMP(crt->raw.p, top->buffer, top->length) == 0) { return 0; } } cert = (DecodedCert*)XMALLOC(sizeof(*cert), NULL, DYNAMIC_TYPE_DCERT); - issuer = (DecodedCert*)XMALLOC(sizeof(*issuer), NULL, DYNAMIC_TYPE_DCERT); - if (cert == NULL || issuer == NULL) { + if (cert == NULL) { ret = MBEDTLS_ERR_X509_ALLOC_FAILED; } if (ret == 0) { ret = MbedCertDecode(cert, top->buffer, top->length); for (crt = conf->ca_chain, i = 0; ret == 0 && *ca == NULL && crt != NULL && i < conf->ca_count; crt = crt->next, i++) { - if (!conf->ca_loaded[i]) { - continue; - } - ret = MbedCertDecode(issuer, crt->raw.p, (word32)crt->raw.len); - if (ret == 0 && - XMEMCMP(issuer->subjectHash, cert->issuerHash, - KEYID_SIZE) == 0 && + id = &conf->ca_ids[i]; + if (id->loaded && + XMEMCMP(id->subjectHash, cert->issuerHash, + sizeof(id->subjectHash)) == 0 && (!cert->extAuthKeyIdSet || - XMEMCMP(issuer->extSubjKeyId, cert->extAuthKeyId, - KEYID_SIZE) == 0)) { + XMEMCMP(id->skid, cert->extAuthKeyId, + sizeof(id->skid)) == 0)) { *ca = crt; } - wc_FreeDecodedCert(issuer); } wc_FreeDecodedCert(cert); ret = wolfPSA_MbedRet(ret, MBEDTLS_ERR_X509_FATAL_ERROR); } - XFREE(issuer, NULL, DYNAMIC_TYPE_DCERT); XFREE(cert, NULL, DYNAMIC_TYPE_DCERT); return ret; } @@ -398,6 +401,11 @@ static int MbedVerifyCb(int preverify, WOLFSSL_X509_STORE_CTX* store) } return preverify || s->authmode == MBEDTLS_SSL_VERIFY_OPTIONAL; } + /* With OPENSSL_EXTRA, an extra verify callback is called for the CA at + * the top of the chain, already in the store. Proceed past it. */ + if (depth == store->totalCerts) { + return 1; + } s->peer_cert = 1; if (s->chain_flags == NULL) { ret = MbedChainNew(s, store->totalCerts); @@ -441,7 +449,7 @@ void mbedtls_ssl_config_free(mbedtls_ssl_config* conf) if (conf != NULL) { wolfSSL_CTX_free(conf->ctx); - XFREE(conf->ca_loaded, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(conf->ca_ids, NULL, DYNAMIC_TYPE_TMP_BUFFER); XMEMSET(conf, 0, sizeof(*conf)); } } @@ -482,18 +490,42 @@ void mbedtls_ssl_conf_authmode(mbedtls_ssl_config* conf, int authmode) } } +/* Loads crt into ctx and sets id, all zero when crt is not loaded. cert is + * for decoding crt. */ +static int MbedCaLoad(WOLFSSL_CTX* ctx, const mbedtls_x509_crt* crt, + DecodedCert* cert, MbedCaId* id) +{ + int ret = (crt->raw.p == NULL) ? WOLFSSL_FAILURE : + wolfSSL_CTX_load_verify_buffer(ctx, crt->raw.p, (long)crt->raw.len, + WOLFSSL_FILETYPE_ASN1); + + XMEMSET(id, 0, sizeof(*id)); + if (ret == WOLFSSL_SUCCESS) { + ret = MbedCertDecode(cert, crt->raw.p, (word32)crt->raw.len); + if (ret == 0) { + id->loaded = 1; + XMEMCPY(id->subjectHash, cert->subjectHash, + sizeof(id->subjectHash)); + XMEMCPY(id->skid, cert->extSubjKeyId, sizeof(id->skid)); + } + wc_FreeDecodedCert(cert); + } + return (ret == WC_NO_ERR_TRACE(MEMORY_E)) ? + MBEDTLS_ERR_SSL_ALLOC_FAILED : 0; +} + /* Loads conf->ca_chain into the WOLFSSL_CTX. Mbed TLS checks a CA only when * it is used, so a CA that wolfSSL rejects on load, such as an expired one, - * is left out. ca_loaded records which were loaded. */ + * is left out. ca_ids keeps the ones loaded, for MbedChainCA(). */ static void MbedConfCAs(mbedtls_ssl_config* conf) { const mbedtls_x509_crt* crt; + DecodedCert* cert = NULL; size_t n = 0; int ret = (conf->ca_crl == NULL) ? 0 : MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; - int loaded; - XFREE(conf->ca_loaded, NULL, DYNAMIC_TYPE_TMP_BUFFER); - conf->ca_loaded = NULL; + XFREE(conf->ca_ids, NULL, DYNAMIC_TYPE_TMP_BUFFER); + conf->ca_ids = NULL; conf->ca_count = 0; for (crt = conf->ca_chain; crt != NULL; crt = crt->next) { n++; @@ -503,21 +535,18 @@ static void MbedConfCAs(mbedtls_ssl_config* conf) MBEDTLS_ERR_SSL_BAD_INPUT_DATA); } if (ret == 0 && n > 0) { - conf->ca_loaded = (unsigned char*)XMALLOC(n, NULL, + conf->ca_ids = (MbedCaId*)XMALLOC(n * sizeof(*conf->ca_ids), NULL, DYNAMIC_TYPE_TMP_BUFFER); - if (conf->ca_loaded == NULL) { + cert = (DecodedCert*)XMALLOC(sizeof(*cert), NULL, DYNAMIC_TYPE_DCERT); + if (conf->ca_ids == NULL || cert == NULL) { ret = MBEDTLS_ERR_SSL_ALLOC_FAILED; } } for (crt = conf->ca_chain; ret == 0 && crt != NULL; crt = crt->next) { - loaded = (crt->raw.p == NULL) ? WOLFSSL_FAILURE : - wolfSSL_CTX_load_verify_buffer(conf->ctx, crt->raw.p, - (long)crt->raw.len, WOLFSSL_FILETYPE_ASN1); - if (loaded == WC_NO_ERR_TRACE(MEMORY_E)) { - ret = MBEDTLS_ERR_SSL_ALLOC_FAILED; - } - conf->ca_loaded[conf->ca_count++] = (loaded == WOLFSSL_SUCCESS); + ret = MbedCaLoad(conf->ctx, crt, cert, + &conf->ca_ids[conf->ca_count++]); } + XFREE(cert, NULL, DYNAMIC_TYPE_DCERT); conf->err[MBED_CONF_ERR_CA] = ret; } @@ -756,7 +785,6 @@ void mbedtls_ssl_conf_verify(mbedtls_ssl_config* conf, if (conf != NULL) { conf->f_vrfy = f_vrfy; conf->p_vrfy = p_vrfy; - conf->changes++; } } diff --git a/test/mbedtls_compat/ssl_test.c b/test/mbedtls_compat/ssl_test.c index f2cb461..fa4bed4 100644 --- a/test/mbedtls_compat/ssl_test.c +++ b/test/mbedtls_compat/ssl_test.c @@ -440,7 +440,7 @@ static int VerifyChain(void) return ClientVerify(&chainCerts, HOST_NAME, 0, 0); } -/* The handshake ends at the first failed check, the one flag reported */ +/* The whole chain is checked, then the handshake fails */ static int VerifyUntrusted(void) { return ClientVerify(&untrustedCerts, HOST_NAME, @@ -558,6 +558,57 @@ static int NoClientCertOptional(void) return ok; } +/* Replaces the Certificate record of a TLS 1.2 server's flight in p with an + * empty one */ +static int EmptyCertRecord(Pipe* p) +{ + static const unsigned char empty[] = { + 0x16, 0x03, 0x03, 0x00, 0x07, 0x0b, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00 + }; + size_t i; + size_t len; + + for (i = 0; i + 6 <= p->len; i += len) { + len = 5 + ((size_t)p->buf[i + 3] << 8 | p->buf[i + 4]); + if (i + len > p->len) { + break; + } + if (p->buf[i] == 0x16 && p->buf[i + 5] == 0x0b) { + memmove(p->buf + i + sizeof(empty), p->buf + i + len, + p->len - i - len); + memcpy(p->buf + i, empty, sizeof(empty)); + p->len -= len - sizeof(empty); + return 1; + } + } + return 0; +} + +/* Unlike a server, a client with VERIFY_OPTIONAL fails on no certificate */ +static int NoServerCertOptional(void) +{ + int s = 0; + int c; + int ok = PeerNew(&cli, MBEDTLS_SSL_IS_CLIENT, MBEDTLS_SSL_VERIFY_OPTIONAL, + 1, HOST_NAME) == 0 && + PeerNew(&srv, MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_VERIFY_NONE, 0, + NULL) == 0; + + if (ok) { + mbedtls_ssl_conf_max_tls_version(&cli.conf, MBEDTLS_SSL_VERSION_TLS1_2); + ok = mbedtls_ssl_handshake(&cli.ssl) == MBEDTLS_ERR_SSL_WANT_READ && + mbedtls_ssl_handshake(&srv.ssl) == MBEDTLS_ERR_SSL_WANT_READ && + EmptyCertRecord(&toClient); + } + if (ok) { + c = Handshake(&s); + ok = c != 0 && !Waiting(c); + } + PeerFree(&cli); + PeerFree(&srv); + return ok; +} + /* Compares crt and the certificates after it with want */ static int SameList(const mbedtls_x509_crt* crt, const mbedtls_x509_crt* want) { @@ -671,6 +722,27 @@ static int VerifyClear(void) return ok; } +/* The flags of an untrusted self-signed certificate, cleared */ +static int VerifyClearSelfSigned(void) +{ + const Certs certs = { &ca, &ipSan, &key }; + Verify v; + int s; + int ok; + + VerifyInit(&v); + v.clear = MBEDTLS_X509_BADCERT_NOT_TRUSTED; + v.want[0] = &ipSan; + ok = VerifyPeers(MBEDTLS_SSL_VERIFY_REQUIRED, &certs, "97.98.99.100", + &v) && + Handshake(&s) == 0 && s == 0 && TopDown(&v, 1) && v.same && + v.flags[0] == MBEDTLS_X509_BADCERT_NOT_TRUSTED && + mbedtls_ssl_get_verify_result(&cli.ssl) == 0; + PeerFree(&cli); + PeerFree(&srv); + return ok; +} + /* A name mismatch only, cleared, as for curl --no-verifyhost */ static int VerifyClearHost(void) { @@ -1679,6 +1751,7 @@ static const struct { #endif /* MBEDTLS_THREADING_C */ { "no client certificate, OPTIONAL", NoClientCertOptional }, { "no client certificate, REQUIRED", NoClientCertRequired }, + { "no server certificate, OPTIONAL", NoServerCertOptional }, { "host name not set", HostNotSet }, { "host name cleared", HostCleared }, { "host name replaced", HostReplaced }, @@ -1696,6 +1769,8 @@ static const struct { { "CA list set before config_defaults", CaChainBeforeDefaults }, { "verify callback, top down", VerifyTopDown }, { "verify callback clears NOT_TRUSTED", VerifyClear }, + { "verify callback clears NOT_TRUSTED, self-signed", + VerifyClearSelfSigned }, { "verify callback clears CN_MISMATCH", VerifyClearHost }, { "verify callback gets the CA wolfSSL loaded", VerifyCaLoaded }, { "allocation failures before the CA's verify callback", VerifyNoMemory }, diff --git a/wolfpsa/mbedtls_compat/mbedtls/ssl.h b/wolfpsa/mbedtls_compat/mbedtls/ssl.h index 67159c2..f1d6067 100644 --- a/wolfpsa/mbedtls_compat/mbedtls/ssl.h +++ b/wolfpsa/mbedtls_compat/mbedtls/ssl.h @@ -73,6 +73,7 @@ typedef enum { struct WOLFSSL_CTX; struct WOLFSSL; struct WOLFSSL_SESSION; +struct wolfPSA_MbedCaId; typedef int mbedtls_ssl_send_t(void* ctx, const unsigned char* buf, size_t len); @@ -96,8 +97,8 @@ typedef struct mbedtls_ssl_config { mbedtls_ssl_protocol_version max_tls_version; const int* ciphersuites; /* the application's, NULL for the default */ mbedtls_x509_crt* ca_chain; /* the application's */ - unsigned char* ca_loaded; /* per CA of ca_chain, 1 if wolfSSL loaded it */ - size_t ca_count; /* of ca_loaded */ + struct wolfPSA_MbedCaId* ca_ids; /* per CA of ca_chain */ + size_t ca_count; /* of ca_ids */ mbedtls_x509_crl* ca_crl; /* not supported, an error when set */ int (*f_vrfy)(void*, mbedtls_x509_crt*, int, uint32_t*); void* p_vrfy; From a38febd001ed551b8f58098f20e3a09aca76c31d Mon Sep 17 00:00:00 2001 From: Paul Adelsbach Date: Mon, 16 Nov 2026 15:53:09 -0800 Subject: [PATCH 3/4] Replace the session in get_session, test accept's client address --- src/mbedtls/ssl.c | 4 +-- test/mbedtls_compat/ssl_test.c | 64 ++++++++++++++++++++++++++++++++-- 2 files changed, 63 insertions(+), 5 deletions(-) diff --git a/src/mbedtls/ssl.c b/src/mbedtls/ssl.c index 183b227..803af7c 100644 --- a/src/mbedtls/ssl.c +++ b/src/mbedtls/ssl.c @@ -1409,10 +1409,10 @@ int mbedtls_ssl_get_session(const mbedtls_ssl_context* ssl, { WOLFSSL_ENTER("mbedtls_ssl_get_session"); - if (ssl == NULL || ssl->ssl == NULL || session == NULL || - session->session != NULL) { + if (ssl == NULL || ssl->ssl == NULL || session == NULL) { return MBEDTLS_ERR_SSL_BAD_INPUT_DATA; } + mbedtls_ssl_session_free(session); session->session = wolfSSL_get1_session(ssl->ssl); session->verify_result = mbedtls_ssl_get_verify_result(ssl); return (session->session != NULL) ? 0 : MBEDTLS_ERR_SSL_BAD_INPUT_DATA; diff --git a/test/mbedtls_compat/ssl_test.c b/test/mbedtls_compat/ssl_test.c index fa4bed4..2548aa1 100644 --- a/test/mbedtls_compat/ssl_test.c +++ b/test/mbedtls_compat/ssl_test.c @@ -29,6 +29,8 @@ #include #include #include +#include +#include #ifdef MBEDTLS_THREADING_C #include #endif /* MBEDTLS_THREADING_C */ @@ -1361,8 +1363,8 @@ static int AuthmodeNoneAfterSetup(void) /* A TLS 1.2 handshake, then one with its session, set before conf_* calls as * curl does. The client verifies with authmode and the CAs of certs, then * trusts only root, which changes the result of a full handshake. A resumed - * session keeps the first result and calls no verify callback. want and flags - * are the client's. */ + * session keeps the first result, calls no verify callback and is exported + * into the same session. want and flags are the client's. */ static int Resume(int authmode, const Certs* certs, int srvAuthmode, int want, uint32_t flags) { @@ -1406,7 +1408,8 @@ static int Resume(int authmode, const Certs* certs, int srvAuthmode, mbedtls_ssl_conf_ca_chain(&cli.conf, &root, NULL); mbedtls_ssl_conf_authmode(&srv.conf, srvAuthmode); ok = Handshake(&s) == want && - (want != 0 || (s == 0 && v.calls == 0)) && + (want != 0 || (s == 0 && v.calls == 0 && + mbedtls_ssl_get_session(&cli.ssl, &session) == 0)) && mbedtls_ssl_get_verify_result(&cli.ssl) == flags; } mbedtls_ssl_session_free(&session); @@ -1679,6 +1682,59 @@ static int AcceptWouldBlock(void) return ok; } +/* Accepts two clients of host, with client_ip one byte short of ip's size, + * then of its size */ +static int AcceptIp(const char* host, const unsigned char* ip, size_t ipLen) +{ + mbedtls_net_context bound; + mbedtls_net_context conn; + mbedtls_net_context client; + struct sockaddr_storage addr; + socklen_t addrLen = (socklen_t)sizeof(addr); + unsigned char buf[16]; + char port[8]; + size_t bufSz; + size_t len; + int ok; + + mbedtls_net_init(&bound); + ok = mbedtls_net_bind(&bound, host, "0", MBEDTLS_NET_PROTO_TCP) == 0 && + getsockname(bound.fd, (struct sockaddr*)&addr, &addrLen) == 0 && + getnameinfo((struct sockaddr*)&addr, addrLen, NULL, 0, port, + sizeof(port), NI_NUMERICSERV) == 0; + for (bufSz = ipLen - 1; ok && bufSz <= ipLen; bufSz++) { + mbedtls_net_init(&conn); + mbedtls_net_init(&client); + memset(buf, 0, sizeof(buf)); + len = 0; + ok = mbedtls_net_connect(&conn, host, port, MBEDTLS_NET_PROTO_TCP) == + 0 && + mbedtls_net_accept(&bound, &client, buf, bufSz, &len) == + ((bufSz < ipLen) ? MBEDTLS_ERR_NET_BUFFER_TOO_SMALL : 0) && + len == ipLen && (bufSz < ipLen || memcmp(buf, ip, ipLen) == 0); + mbedtls_net_free(&client); + mbedtls_net_free(&conn); + } + mbedtls_net_free(&bound); + return ok; +} + +static int AcceptIpv4(void) +{ + static const unsigned char ip[] = { 127, 0, 0, 1 }; + + return AcceptIp("127.0.0.1", ip, sizeof(ip)); +} + +static int AcceptIpv6(void) +{ + static const unsigned char ip[] = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 + }; + + return AcceptIp("::1", ip, sizeof(ip)); +} + /* Each listed suite's name gives back its ID */ static int SuiteIdFromName(void) { @@ -1812,6 +1868,8 @@ static const struct { { "transport changed after config_defaults", TransportChanged }, { "own key too small", OwnKeyTooSmall }, { "accept would block", AcceptWouldBlock }, + { "accept, IPv4 client address", AcceptIpv4 }, + { "accept, IPv6 client address", AcceptIpv6 }, { "cipher suite ID from its name", SuiteIdFromName }, { "handshake over", HandshakeOver }, { "user data kept through session reset", UserData } From 9bca3f711f14e3300a0e812c8c9d544c3854cf1a Mon Sep 17 00:00:00 2001 From: Paul Adelsbach Date: Mon, 16 Nov 2026 20:27:25 -0800 Subject: [PATCH 4/4] README: keep the API list and programs paragraph from conflicting --- README.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 352a636..35292c4 100644 --- a/README.md +++ b/README.md @@ -136,9 +136,9 @@ Mapped so far: - pem: init, read_buffer, get_buffer, free - x509_crt: init, free, parse, parse_der, parse_file, parse_path; the default, next and suiteb profiles, as names only -- ssl_config: init, free, defaults; ssl_conf: authmode, verify, ca_chain, - own_cert, min_tls_version, max_tls_version, ciphersuites, cert_profile, - dbg, endpoint, transport, get_endpoint, set_user_data_p, set_user_data_n, +- ssl_config: init, free, defaults; ssl_conf: authmode, ca_chain, own_cert, + min_tls_version, max_tls_version, ciphersuites, cert_profile, dbg, verify, + endpoint, transport, get_endpoint, set_user_data_p, set_user_data_n, get_user_data_p, get_user_data_n - ssl: init, free, setup, context_get_config, session_reset, set_bio, set_verify, set_hostname, set_session, get_session, handshake, @@ -243,8 +243,9 @@ runs these against `libwolfpsa.a`. Each is also a target of its own. (`test/mbedtls_compat/client-tls-mbedtls.c`) and Mbed TLS's sample programs, built unchanged, run against the wolfSSL example server. Mbed TLS's server programs run against the wolfSSL example client and - `ssl_client1`. With `MBEDTLS_THREADING_C=1`, `ssl_pthread_server` serves - clients at the same time. + `ssl_client1`. With + `MBEDTLS_THREADING_C=1`, `ssl_pthread_server` serves clients at the same + time. Notes: