diff --git a/.github/workflows/mbedtls-compat.yml b/.github/workflows/mbedtls-compat.yml index 903c9e1..0006f54 100644 --- a/.github/workflows/mbedtls-compat.yml +++ b/.github/workflows/mbedtls-compat.yml @@ -6,28 +6,48 @@ on: jobs: # make MBEDTLS_COMPAT=1 mbedtls-compat-test: the Mbed TLS 4.x API on - # wolfCrypt, tested with Mbed TLS's test data. See the README. + # wolfSSL, tested with Mbed TLS's sample programs and test data. See the + # README. mbedtls-compat: runs-on: ubuntu-latest timeout-minutes: 15 strategy: fail-fast: false matrix: - wolfssl-ref: [ master, v5.9.4-stable ] + # The compatibility layer needs wolfSSL master, not a release + wolfssl-ref: [ master ] options: [ "", "MBEDTLS_THREADING_C=1 ASAN=1" ] steps: - name: Check out wolfPSA uses: actions/checkout@v4 + - name: Install build dependencies + run: | + 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 - # The tests need only framework/data_files + # The tests need framework's data files, and tf-psa-crypto's headers for + # the test certificates - name: Clone sibling Mbed TLS run: | git clone --depth 1 --branch mbedtls-4.2.0 https://github.com/Mbed-TLS/mbedtls ../mbedtls - git -C ../mbedtls submodule update --init --depth 1 framework + git -C ../mbedtls submodule update --init --depth 1 framework tf-psa-crypto - name: Build and run the compatibility tests run: make MBEDTLS_COMPAT=1 ${{ matrix.options }} mbedtls-compat-test + + # -z defs fails on undefined symbols + - name: Build client-only and server-only + if: matrix.options == '' + env: + LDFLAGS: -Wl,-z,defs + run: | + for side in CLIENT SERVER; do + make -j"$(nproc)" MBEDTLS_COMPAT=1 BUILD_DIR=build-no-$side \ + WOLFSSL_CPPFLAGS="-DWOLFSSL_USER_SETTINGS -DNO_WOLFSSL_$side" \ + want-surface-test + done diff --git a/.github/workflows/test-psa-api.yml b/.github/workflows/test-psa-api.yml index a8f070f..49a9220 100644 --- a/.github/workflows/test-psa-api.yml +++ b/.github/workflows/test-psa-api.yml @@ -75,6 +75,10 @@ jobs: # master tracks upstream; the -stable tag is the release wolfPSA is # validated against. Bump it together with the wolfPSA version. wolfssl-ref: [ master, v5.9.4-stable ] + # MBEDTLS_COMPAT=1 needs wolfSSL master + include: + - wolfssl-ref: v5.9.4-stable + make-args: MBEDTLS_COMPAT=0 steps: - name: Check out wolfPSA @@ -92,7 +96,7 @@ jobs: - name: Build and run the PSA API tests env: LD_LIBRARY_PATH: ${{ github.workspace }}:${{ github.workspace }}/../wolfssl/src/.libs - run: make unit-run + run: make unit-run ${{ matrix.make-args }} # The crypto callback reads the HMAC key out of Hmac.keyRaw, which # wolfCrypt borrows rather than copies. Only a sanitizer notices when diff --git a/Makefile b/Makefile index 207ea0d..3ae2e24 100644 --- a/Makefile +++ b/Makefile @@ -79,10 +79,18 @@ WOLFCRYPT_SRC := \ WOLFCRYPT_OBJ := $(patsubst $(WOLFSSL_PATH)/wolfcrypt/src/%.c,$(OBJDIR)/wolfcrypt_%.o,$(WOLFCRYPT_SRC)) WOLFCRYPT_OBJ_PIC := $(patsubst $(WOLFSSL_PATH)/wolfcrypt/src/%.c,$(OBJDIR_PIC)/wolfcrypt_%.o,$(WOLFCRYPT_SRC)) -# MBEDTLS_COMPAT=1 adds the Mbed TLS 4.x X.509 API. See src/mbedtls/. +# MBEDTLS_COMPAT=1 adds the Mbed TLS 4.x TLS, X.509 and network API, on +# wolfSSL's TLS compiled from WOLFSSL_PATH like wolfCrypt. See src/mbedtls/. +WOLFSSL_TLS_SRC := ifeq ($(MBEDTLS_COMPAT),1) CPPFLAGS += -DWOLFPSA_MBEDTLS_COMPAT -I$(CURDIR)/wolfpsa/mbedtls_compat +WOLFSSL_TLS_SRC := $(addprefix $(WOLFSSL_PATH)/src/,internal.c keys.c ssl.c \ + tls.c tls13.c wolfio.c) endif +WOLFSSL_TLS_OBJ := $(patsubst $(WOLFSSL_PATH)/src/%.c,$(OBJDIR)/wolfssl_%.o, \ + $(WOLFSSL_TLS_SRC)) +WOLFSSL_TLS_OBJ_PIC := $(patsubst $(WOLFSSL_PATH)/src/%.c, \ + $(OBJDIR_PIC)/wolfssl_%.o,$(WOLFSSL_TLS_SRC)) # MBEDTLS_THREADING_C=1 builds a thread safe library, as in Mbed TLS. See # user_settings.h. Applications define MBEDTLS_THREADING_C too. @@ -141,7 +149,7 @@ LDFLAGS += --coverage endif .PHONY: all clean psa-objects unit-run run-tests cov covclean \ - want-surface-test mbedtls-compat-test + want-surface-test all: $(LIBNAME) $(SHLIBNAME) @@ -151,11 +159,14 @@ all: $(LIBNAME) $(SHLIBNAME) # bundled wolfCrypt sources are out of scope. psa-objects: $(OBJ) -$(LIBNAME): $(OBJ) $(WOLFCRYPT_OBJ) +# Made again, so that objects of another MBEDTLS_COMPAT build are not kept +$(LIBNAME): $(OBJ) $(WOLFCRYPT_OBJ) $(WOLFSSL_TLS_OBJ) + rm -f $@ $(AR) rcs $@ $^ $(RANLIB) $@ -$(SHLIBNAME): $(OBJ_PIC) $(WOLFCRYPT_OBJ_PIC) $(EXPORT_MAP) +$(SHLIBNAME): $(OBJ_PIC) $(WOLFCRYPT_OBJ_PIC) $(WOLFSSL_TLS_OBJ_PIC) \ + $(EXPORT_MAP) $(CC) -shared -Wl,--version-script,$(EXPORT_MAP) -Wl,-Bsymbolic-functions -o $@ $(filter-out $(EXPORT_MAP),$^) $(LDFLAGS) # Build the PSA_WANT_* macros based on what the wolfCrypt build supports. @@ -168,7 +179,8 @@ $(PSA_CONFIG): FORCE $(PYTHON) tools/gen-crypto-config.py $@ "$(CC)" \ tools/psa_want_probe.c $(CPPFLAGS) $(CFLAGS) -$(OBJ) $(OBJ_PIC) $(WOLFCRYPT_OBJ) $(WOLFCRYPT_OBJ_PIC): $(PSA_CONFIG) +$(OBJ) $(OBJ_PIC) $(WOLFCRYPT_OBJ) $(WOLFCRYPT_OBJ_PIC) $(WOLFSSL_TLS_OBJ) \ + $(WOLFSSL_TLS_OBJ_PIC): $(PSA_CONFIG) FORCE: @@ -178,7 +190,8 @@ want-surface-test: $(LIBNAME) $(SHLIBNAME) -lpthread -lm $(BUILD_DIR)/psa_want_surface_test -$(OBJ) $(WOLFCRYPT_OBJ) $(OBJ_PIC) $(WOLFCRYPT_OBJ_PIC): $(OPTIONS_STAMP) +$(OBJ) $(WOLFCRYPT_OBJ) $(WOLFSSL_TLS_OBJ) $(OBJ_PIC) $(WOLFCRYPT_OBJ_PIC) \ + $(WOLFSSL_TLS_OBJ_PIC): $(OPTIONS_STAMP) $(OPTIONS_STAMP): @mkdir -p $(@D) @@ -201,6 +214,14 @@ $(OBJDIR_PIC)/wolfcrypt_%.o: $(WOLFSSL_PATH)/wolfcrypt/src/%.c @mkdir -p $(OBJDIR_PIC) $(CC) $(CPPFLAGS) $(DEPFLAGS) $(CFLAGS) -fPIC -c $< -o $@ +$(OBJDIR)/wolfssl_%.o: $(WOLFSSL_PATH)/src/%.c + @mkdir -p $(OBJDIR) + $(CC) $(CPPFLAGS) $(DEPFLAGS) $(CFLAGS) -c $< -o $@ + +$(OBJDIR_PIC)/wolfssl_%.o: $(WOLFSSL_PATH)/src/%.c + @mkdir -p $(OBJDIR_PIC) + $(CC) $(CPPFLAGS) $(DEPFLAGS) $(CFLAGS) -fPIC -c $< -o $@ + # The unit tests. The servers (psa_tls_client, psa_tls_server) and the # benchmark are not unit tests and are not listed. UNIT_TESTS := psa_api_test \ @@ -284,21 +305,27 @@ unit-run: all @$(MAKE) -C test $(UNIT_TESTS) @$(MAKE) run-tests -# Mbed TLS repo, for its test data +# Mbed TLS repo, for its test data and sample programs MBEDTLS_PATH ?= ../mbedtls +# mbedtls-compat-test runs mbedtls-compat-unit, our own tests of the API, and +# mbedtls-compat-programs, Mbed TLS's sample programs with wolfSSL peers. Each +# runs the target of the same name in test/mbedtls_compat. +MBEDTLS_COMPAT_TESTS := $(addprefix mbedtls-compat-,test unit programs) +.PHONY: $(MBEDTLS_COMPAT_TESTS) ifeq ($(MBEDTLS_COMPAT),1) -mbedtls-compat-test: $(LIBNAME) +$(MBEDTLS_COMPAT_TESTS): mbedtls-compat-%: $(LIBNAME) $(MAKE) -C test/mbedtls_compat WOLFPSA_PATH=$(CURDIR) \ + WOLFSSL_PATH=$(abspath $(WOLFSSL_PATH)) \ MBEDTLS_PATH=$(abspath $(MBEDTLS_PATH)) \ BUILD_DIR=$(abspath $(BUILD_DIR))/mbedtls_compat \ PSA_CONFIG_DIR=$(abspath $(dir $(PSA_CONFIG))) \ WOLFSSL_FLAGS="-I$(abspath $(WOLFSSL_PATH)) \ -I$(abspath $(USER_SETTINGS_PATH)) $(WOLFSSL_CPPFLAGS)" \ - SANITIZE_FLAGS="$(SANITIZE_FLAGS)" WOLFPSA_LDFLAGS="$(LDFLAGS)" check + SANITIZE_FLAGS="$(SANITIZE_FLAGS)" WOLFPSA_LDFLAGS="$(LDFLAGS)" $* else -mbedtls-compat-test: - @echo "Run make MBEDTLS_COMPAT=1 mbedtls-compat-test"; exit 1 +$(MBEDTLS_COMPAT_TESTS): + @echo "Run make MBEDTLS_COMPAT=1 $@"; exit 1 endif # Build everything with gcov instrumentation, run the unit tests, and emit an @@ -349,5 +376,6 @@ covclean: clean: rm -rf $(BUILD_DIR) $(LIBNAME) $(SHLIBNAME) --include $(OBJ:.o=.d) $(WOLFCRYPT_OBJ:.o=.d) --include $(OBJ_PIC:.o=.d) $(WOLFCRYPT_OBJ_PIC:.o=.d) +-include $(OBJ:.o=.d) $(WOLFCRYPT_OBJ:.o=.d) $(WOLFSSL_TLS_OBJ:.o=.d) +-include $(OBJ_PIC:.o=.d) $(WOLFCRYPT_OBJ_PIC:.o=.d) \ + $(WOLFSSL_TLS_OBJ_PIC:.o=.d) diff --git a/README.md b/README.md index ae31f75..7ef43ed 100644 --- a/README.md +++ b/README.md @@ -90,21 +90,31 @@ includes `` needs that directory on its include path next to ## Mbed TLS compatibility -`MBEDTLS_COMPAT=1` adds the Mbed TLS 4.x X.509 API on top of wolfCrypt, so -that applications written for Mbed TLS 4.x build against wolfPSA without -source changes. wolfPSA already provides the TF-PSA-Crypto side (`psa_*`, -`mbedtls_pk_*`, `mbedtls_psa_crypto_free`, `mbedtls/platform.h`). +`MBEDTLS_COMPAT=1` adds the Mbed TLS 4.x TLS, X.509 and network API on top of +wolfSSL, so that applications written for Mbed TLS 4.x build against wolfPSA +without source changes. wolfPSA already provides the TF-PSA-Crypto side +(`psa_*`, `mbedtls_pk_*`, `mbedtls_psa_crypto_free`, `mbedtls/platform.h`). ``` make MBEDTLS_COMPAT=1 ``` +- wolfSSL's TLS sources are compiled from `WOLFSSL_PATH` into + `libwolfpsa.a`, like wolfCrypt, with the TLS settings in `user_settings.h`. + Changing the option rebuilds everything. +- Needs a current wolfSSL built from its master branch. wolfSSL releases, + such as v5.9.4-stable, are not supported. - Applications use `-I/wolfpsa`, `-I/wolfpsa/mbedtls_compat` and `-I/build/include`, and link `libwolfpsa.a`, in place of Mbed TLS's libraries. The headers include no wolfSSL header. +- The feature macros, such as `MBEDTLS_SSL_TLS_C`, `MBEDTLS_NET_C` and + `MBEDTLS_PEM_PARSE_C`, are in the generated config in `build/include`, so + a build without the option does not define them. - The functions have the Mbed TLS names, so code that finds them by symbol name (`dlsym`, language bindings) works too. +- With `MBEDTLS_THREADING_C=1`, TLS is thread safe too. +- TLS uses wolfPSA's constant-time AES. `AES_FAST=1` applies to TLS too. - As in Mbed TLS, certificates may have NULL parameters after an ECDSA signature OID. This needs `WOLFSSL_ECC_SIGALG_PARAMS_NULL_ALLOWED`, which wolfPSA's `user_settings.h` defines. A build with its own @@ -112,14 +122,93 @@ make MBEDTLS_COMPAT=1 example Mbed TLS's `test-ca2.crt`. - The X.509 API needs wolfCrypt's certificate parsing: without it (`NO_ASN` or `NO_CERTS`), `MBEDTLS_X509_CRT_PARSE_C` is not defined. +- TLS needs the X.509 API and wolfSSL's TLS with `HAVE_SNI`: without them, + 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`). Mapped so far: +- net: init, connect, bind, accept, close, free, recv, send, usleep +- 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, + 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 +- 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. +- 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 + overlap wolfCrypt codes. +- A config needs `mbedtls_ssl_config_defaults`. `mbedtls_ssl_conf_endpoint` + and `mbedtls_ssl_conf_transport` cannot change the endpoint and transport + it set: `mbedtls_ssl_setup` and the handshake then return + `MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE`. wolfSSL makes its config for one + endpoint and transport. +- `mbedtls_ssl_conf_ca_chain` refuses a CRL: `mbedtls_ssl_setup` and the + handshake then return `MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE` until a CA + list without one is set. +- A server's config needs its `mbedtls_ssl_conf_own_cert` before + `mbedtls_ssl_setup`, which fails without it with + `MBEDTLS_ERR_SSL_BAD_CONFIG`: wolfSSL makes a server connection only with + a certificate and key. +- A second `mbedtls_ssl_conf_own_cert` replaces the first. Mbed TLS keeps + both and picks one for each handshake. After a failed one, + `mbedtls_ssl_setup` and the handshake return its error until one + succeeds, where Mbed TLS keeps the certificates set before. +- `mbedtls_net_accept` is TCP only. +- RSA keys are limited to 3072 bits, so a certificate chain with an RSA-4096 + CA does not verify. +- `mbedtls_ssl_conf_ca_chain` leaves out a CA that wolfSSL does not load, + such as an expired one. A peer certificate from that CA then fails as + `NOT_TRUSTED`, where Mbed TLS reports `EXPIRED`. +- A certificate's issuer name must match its CA's subject name exactly, as + encoded. Mbed TLS also takes names that differ only in letter case or in + string type (PrintableString or UTF8String). Such a certificate fails as + `NOT_TRUSTED`. For example, Mbed TLS's test certificate `cli2.crt` has + issuer `PolarSSL Test EC CA`, and its CA `test-ca2.crt` has subject + `Polarssl Test EC CA`. +- An IP address host name is matched against the certificate's IP address + SANs only. Mbed TLS also matches a DNS SAN with the same text, or the CN + of a certificate without SANs. It is not sent as the server name, which + RFC 6066 does not allow and Mbed TLS does. +- A host name without a dot, such as `router`, fails with + `MBEDTLS_ERR_SSL_BAD_INPUT_DATA` from `mbedtls_ssl_set_hostname`, or from + `mbedtls_ssl_setup` when set before it. wolfSSL takes only a fully + qualified name, an IP address or `localhost`. +- `mbedtls_ssl_set_hostname` during a handshake applies from the next + `mbedtls_ssl_session_reset`. Mbed TLS uses the new name for the rest of + that handshake. +- A server resumes sessions from wolfSSL's session cache, where Mbed TLS + needs `mbedtls_ssl_conf_session_cache`. A server that verifies client + certificates reports `MBEDTLS_X509_BADCERT_MISSING` for a resumed session. +- wolfSSL keeps the intermediate CAs of a chain that verifies, for the + config's later handshakes. A peer that then leaves them out still + verifies, where Mbed TLS reports `NOT_TRUSTED`. +- `mbedtls_ssl_conf_dbg` and `mbedtls_ssl_conf_cert_profile` are accepted + and ignored. +- `mbedtls_pem_read_buffer` returns `MBEDTLS_ERR_PEM_FEATURE_UNAVAILABLE` + for encrypted PEM. No `mbedtls_pem_write_buffer`. - `mbedtls_x509_crt` has one node per certificate, with no parsed fields apart from `raw`. Parse errors are `MBEDTLS_ERR_X509_INVALID_FORMAT` or `MBEDTLS_ERR_X509_ALLOC_FAILED`. @@ -131,17 +220,42 @@ Known differences from Mbed TLS: - wolfSSL parses some certificates differently. For example, it rejects serial number 0 and a pathlen above `WOLFSSL_MAX_PATH_LEN`, and accepts spaces in PEM. +- No global mutexes such as `mbedtls_threading_gmtime_mutex`. -`test/mbedtls_compat/x509_crt_test.c` and `pk_test.c` parse Mbed TLS's test -certificates and keys. To run them: +### Mbed TLS compatibility tests ``` make MBEDTLS_COMPAT=1 mbedtls-compat-test ``` +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. +- `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. + +Notes: + - `MBEDTLS_PATH` (default `../mbedtls`) is an Mbed TLS 4.x checkout with - its `framework` submodule. Only its test data files are used. -- `WRAP` prefixes each test program, for example `WRAP=valgrind`. + its `framework` and `tf-psa-crypto` submodules, for its test data and + sample programs. +- The example server and client come from a wolfSSL configured out of tree + from `WOLFSSL_PATH`, which must not be configured in place. The tests use + the certificates in its `certs/`. This needs autoconf, automake and + libtool. +- Also needs python3 with jinja2. Without faketime, the case that needs it + is skipped. +- `WRAP` prefixes each test program, for example `WRAP=valgrind`. Server + programs are stopped by the script, so their exit codes are not checked. +- `libwolfpsa.a` has no Mbed TLS code. The tests link Mbed TLS's test + certificate data. ## Testing (PSA Architecture Test Suite) diff --git a/src/mbedtls/mbedtls_compat_internal.h b/src/mbedtls/mbedtls_compat_internal.h new file mode 100644 index 0000000..379d5cd --- /dev/null +++ b/src/mbedtls/mbedtls_compat_internal.h @@ -0,0 +1,40 @@ +/* mbedtls_compat_internal.h + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of wolfPSA. + * + * wolfPSA is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * wolfPSA is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * 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. */ + +#ifndef MBEDTLS_COMPAT_INTERNAL_H +#define MBEDTLS_COMPAT_INTERNAL_H + +#include +#include + +enum { + MBED_IO_RECV = 0, + MBED_IO_SEND = 1 +}; + +/* I/O error code in one direction, toWolf from Mbed TLS to wolfSSL */ +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); + +#endif /* MBEDTLS_COMPAT_INTERNAL_H */ diff --git a/src/mbedtls/net.c b/src/mbedtls/net.c new file mode 100644 index 0000000..c1feccd --- /dev/null +++ b/src/mbedtls/net.c @@ -0,0 +1,309 @@ +/* net.c + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of wolfPSA. + * + * wolfPSA is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * wolfPSA is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +/* Mbed TLS 4.x network API on wolfSSL's sockets (MBEDTLS_COMPAT=1). */ + +/* getaddrinfo() with -std=c99 */ +#if defined(WOLFPSA_MBEDTLS_COMPAT) && !defined(_POSIX_C_SOURCE) + #define _POSIX_C_SOURCE 200112L +#endif /* WOLFPSA_MBEDTLS_COMPAT && !_POSIX_C_SOURCE */ + +#ifdef HAVE_CONFIG_H + #include +#endif /* HAVE_CONFIG_H */ + +#include "psa_config.h" + +#if defined(WOLFSSL_PSA_ENGINE) && defined(WOLFPSA_MBEDTLS_COMPAT) + +#include +#if defined(MBEDTLS_SSL_TLS_C) + #include + #include +#endif /* MBEDTLS_SSL_TLS_C */ + +/* The generated config has MBEDTLS_NET_C with TLS and wolfSSL's sockets */ +#if defined(MBEDTLS_NET_C) != \ + (defined(MBEDTLS_SSL_TLS_C) && defined(USE_WOLFSSL_IO)) + #error "MBEDTLS_NET_C does not match MBEDTLS_SSL_TLS_C and USE_WOLFSSL_IO" +#endif /* MBEDTLS_NET_C != (MBEDTLS_SSL_TLS_C && USE_WOLFSSL_IO) */ + +#if defined(MBEDTLS_NET_C) + +#include +#include "mbedtls_compat_internal.h" +#ifndef USE_WINDOWS_API + #include + #include + #include +#endif /* !USE_WINDOWS_API */ + +void mbedtls_net_init(mbedtls_net_context* ctx) +{ + WOLFSSL_ENTER("mbedtls_net_init"); + + if (ctx != NULL) { + ctx->fd = -1; + } +} + +/* As in Mbed TLS: Winsock starts on first use and is not stopped, and a send + * to a closed peer fails instead of ending the process. Returns 1 when + * sockets can be used. */ +static int MbedNetPrepare(void) +{ +#ifdef USE_WINDOWS_API + static int started = 0; + WSADATA data; + + if (!started) { + started = (WSAStartup(MAKEWORD(2, 2), &data) == 0); + } + return started; +#else + (void)signal(SIGPIPE, SIG_IGN); + return 1; +#endif /* USE_WINDOWS_API */ +} + +static int MbedNetBind(int fd, const struct addrinfo* ai, int proto) +{ + int on = 1; + + if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, + (XSOCKLENT)sizeof(on)) != 0) { + return MBEDTLS_ERR_NET_SOCKET_FAILED; + } + if (bind(fd, ai->ai_addr, (XSOCKLENT)ai->ai_addrlen) != 0) { + return MBEDTLS_ERR_NET_BIND_FAILED; + } + if (proto == MBEDTLS_NET_PROTO_TCP && + listen(fd, MBEDTLS_NET_LISTEN_BACKLOG) != 0) { + return MBEDTLS_ERR_NET_LISTEN_FAILED; + } + return 0; +} + +/* Connects to host, or binds to it when server is set. A server with no + * host binds to every address. */ +static int MbedNetOpen(mbedtls_net_context* ctx, const char* host, + const char* port, int proto, int server) +{ + struct addrinfo hints; + struct addrinfo* list = NULL; + struct addrinfo* ai; + int ret = MBEDTLS_ERR_NET_UNKNOWN_HOST; + + if (ctx == NULL || (host == NULL && !server) || port == NULL) { + return MBEDTLS_ERR_NET_INVALID_CONTEXT; + } + XMEMSET(&hints, 0, sizeof(hints)); + hints.ai_family = AF_UNSPEC; + if (proto == MBEDTLS_NET_PROTO_UDP) { + hints.ai_socktype = SOCK_DGRAM; + hints.ai_protocol = IPPROTO_UDP; + } + else { + hints.ai_socktype = SOCK_STREAM; + hints.ai_protocol = IPPROTO_TCP; + } + if (host == NULL) { + hints.ai_flags = AI_PASSIVE; + } + + if (!MbedNetPrepare()) { + return MBEDTLS_ERR_NET_SOCKET_FAILED; + } + if (getaddrinfo(host, port, &hints, &list) != 0) { + return MBEDTLS_ERR_NET_UNKNOWN_HOST; + } + + for (ai = list; ai != NULL; ai = ai->ai_next) { + ctx->fd = (int)socket(ai->ai_family, ai->ai_socktype, + ai->ai_protocol); + if (ctx->fd < 0) { + ret = MBEDTLS_ERR_NET_SOCKET_FAILED; + continue; + } + if (server) { + ret = MbedNetBind(ctx->fd, ai, proto); + } + else if (connect(ctx->fd, ai->ai_addr, + (XSOCKLENT)ai->ai_addrlen) == 0) { + ret = 0; + } + else { + ret = MBEDTLS_ERR_NET_CONNECT_FAILED; + } + if (ret == 0) { + break; + } + CloseSocket(ctx->fd); + ctx->fd = -1; + } + + freeaddrinfo(list); + return ret; +} + +int mbedtls_net_connect(mbedtls_net_context* ctx, const char* host, + const char* port, int proto) +{ + WOLFSSL_ENTER("mbedtls_net_connect"); + + return MbedNetOpen(ctx, host, port, proto, 0); +} + +int mbedtls_net_bind(mbedtls_net_context* ctx, const char* bind_ip, + const char* port, int proto) +{ + WOLFSSL_ENTER("mbedtls_net_bind"); + + return MbedNetOpen(ctx, bind_ip, port, proto, 1); +} + +/* The last socket call failed only because it would block */ +static int MbedNetWouldBlock(void) +{ +#ifdef USE_WINDOWS_API + int err = WSAGetLastError(); +#else + int err = errno; +#endif /* USE_WINDOWS_API */ + + return err == SOCKET_EWOULDBLOCK || err == SOCKET_EAGAIN; +} + +/* TCP only. client_ip gets the 4 or 16 bytes of the client's address. */ +int mbedtls_net_accept(mbedtls_net_context* bind_ctx, + mbedtls_net_context* client_ctx, void* client_ip, size_t buf_size, + size_t* cip_len) +{ + struct sockaddr_storage addr; + XSOCKLENT addrLen = (XSOCKLENT)sizeof(addr); + const void* ip; + size_t ipLen; + + WOLFSSL_ENTER("mbedtls_net_accept"); + + if (bind_ctx == NULL || client_ctx == NULL || bind_ctx->fd < 0) { + return MBEDTLS_ERR_NET_INVALID_CONTEXT; + } + client_ctx->fd = (int)accept(bind_ctx->fd, (struct sockaddr*)&addr, + &addrLen); + if (client_ctx->fd < 0) { + return MbedNetWouldBlock() ? MBEDTLS_ERR_SSL_WANT_READ : + MBEDTLS_ERR_NET_ACCEPT_FAILED; + } + if (client_ip == NULL) { + return 0; + } + + if (addr.ss_family == AF_INET) { + ip = &((struct sockaddr_in*)&addr)->sin_addr; + ipLen = sizeof(struct in_addr); + } + else { + ip = &((struct sockaddr_in6*)&addr)->sin6_addr; + ipLen = sizeof(struct in6_addr); + } + *cip_len = ipLen; + if (buf_size < ipLen) { + return MBEDTLS_ERR_NET_BUFFER_TOO_SMALL; + } + XMEMCPY(client_ip, ip, ipLen); + return 0; +} + +void mbedtls_net_usleep(unsigned long usec) +{ + WOLFSSL_ENTER("mbedtls_net_usleep"); + +#ifdef USE_WINDOWS_API + Sleep((DWORD)((usec + 999) / 1000)); +#else + struct timeval tv; + + tv.tv_sec = (time_t)(usec / 1000000); + tv.tv_usec = (suseconds_t)(usec % 1000000); + (void)select(0, NULL, NULL, NULL, &tv); +#endif /* USE_WINDOWS_API */ +} + +void mbedtls_net_close(mbedtls_net_context* ctx) +{ + WOLFSSL_ENTER("mbedtls_net_close"); + + if (ctx != NULL && ctx->fd >= 0) { + CloseSocket(ctx->fd); + ctx->fd = -1; + } +} + +/* Also ends the connection for a forked process that shares the socket */ +void mbedtls_net_free(mbedtls_net_context* ctx) +{ + WOLFSSL_ENTER("mbedtls_net_free"); + + if (ctx != NULL && ctx->fd >= 0) { + (void)shutdown(ctx->fd, 2); + } + mbedtls_net_close(ctx); +} + +int mbedtls_net_recv(void* ctx, unsigned char* buf, size_t len) +{ + mbedtls_net_context* net = (mbedtls_net_context*)ctx; + int ret; + + WOLFSSL_ENTER("mbedtls_net_recv"); + + if (net == NULL || net->fd < 0) { + return MBEDTLS_ERR_NET_INVALID_CONTEXT; + } + ret = wolfIO_Recv(net->fd, (char*)buf, MbedIoLen(len, INT_MAX), 0); + if (ret >= 0) { + return ret; + } + return MbedIoErr(ret, MBED_IO_RECV, 0); +} + +int mbedtls_net_send(void* ctx, const unsigned char* buf, size_t len) +{ + mbedtls_net_context* net = (mbedtls_net_context*)ctx; + int ret; + + WOLFSSL_ENTER("mbedtls_net_send"); + + if (net == NULL || net->fd < 0) { + return MBEDTLS_ERR_NET_INVALID_CONTEXT; + } + ret = wolfIO_Send(net->fd, (char*)(wc_ptr_t)buf, MbedIoLen(len, INT_MAX), + 0); + if (ret >= 0) { + return ret; + } + return MbedIoErr(ret, MBED_IO_SEND, 0); +} + +#endif /* MBEDTLS_NET_C */ + +#endif /* WOLFSSL_PSA_ENGINE && WOLFPSA_MBEDTLS_COMPAT */ diff --git a/src/mbedtls/pem.c b/src/mbedtls/pem.c new file mode 100644 index 0000000..3a16428 --- /dev/null +++ b/src/mbedtls/pem.c @@ -0,0 +1,160 @@ +/* pem.c + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of wolfPSA. + * + * wolfPSA is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * wolfPSA is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +/* Mbed TLS 4.x PEM decoding on wolfCrypt's Base64 (MBEDTLS_COMPAT=1). */ + +#ifdef HAVE_CONFIG_H + #include +#endif /* HAVE_CONFIG_H */ + +#include "psa_config.h" + +#if defined(WOLFSSL_PSA_ENGINE) && defined(WOLFPSA_MBEDTLS_COMPAT) + +#include +#include +#include +#include +#include + +/* The generated config has MBEDTLS_PEM_PARSE_C with wolfCrypt's Base64 + * decoding */ +#if defined(MBEDTLS_PEM_PARSE_C) != \ + (!defined(NO_CODING) && defined(WOLFSSL_BASE64_DECODE)) + #error "MBEDTLS_PEM_PARSE_C does not match wolfCrypt's Base64 decoding" +#endif /* MBEDTLS_PEM_PARSE_C != (!NO_CODING && WOLFSSL_BASE64_DECODE) */ + +#if defined(MBEDTLS_PEM_PARSE_C) + +/* Mbed TLS adds MBEDTLS_ERR_BASE64_INVALID_CHARACTER to the PEM error */ +#define MBED_PEM_BAD_BASE64 (MBEDTLS_ERR_PEM_INVALID_DATA - 0x002C) + +void mbedtls_pem_init(mbedtls_pem_context* ctx) +{ + WOLFSSL_ENTER("mbedtls_pem_init"); + + if (ctx != NULL) { + XMEMSET(ctx, 0, sizeof(*ctx)); + } +} + +/* Skips a space and the end of the line after it. Returns NULL when the line + * does not end there and the end is required. */ +static const char* MbedPemEol(const char* s, int required) +{ + if (*s == ' ') { + s++; + } + if (*s == '\r') { + s++; + } + if (*s == '\n') { + return s + 1; + } + return required ? NULL : s; +} + +/* As in Mbed TLS, *use_len is set once the header and footer are found */ +int mbedtls_pem_read_buffer(mbedtls_pem_context* ctx, const char* header, + const char* footer, const unsigned char* data, const unsigned char* pwd, + size_t pwdlen, size_t* use_len) +{ + const char* s1; + const char* s2; + unsigned char* buf; + word32 inLen; + word32 size; + word32 len; + int ret = 0; + + WOLFSSL_ENTER("mbedtls_pem_read_buffer"); + + (void)pwd; + (void)pwdlen; + if (ctx == NULL || header == NULL || footer == NULL || data == NULL || + use_len == NULL) { + return MBEDTLS_ERR_PEM_BAD_INPUT_DATA; + } + + s1 = XSTRSTR((const char*)data, header); + s2 = XSTRSTR((const char*)data, footer); + if (s1 == NULL || s2 == NULL || s2 <= s1) { + return MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT; + } + s1 = MbedPemEol(s1 + XSTRLEN(header), 1); + if (s1 == NULL) { + return MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT; + } + *use_len = (size_t)(MbedPemEol(s2 + XSTRLEN(footer), 0) - + (const char*)data); + + if (s2 - s1 >= 22 && XMEMCMP(s1, "Proc-Type: 4,ENCRYPTED", 22) == 0) { + return MBEDTLS_ERR_PEM_FEATURE_UNAVAILABLE; + } + if (s1 >= s2) { + return MBEDTLS_ERR_PEM_INVALID_DATA; + } + if ((size_t)(s2 - s1) > (size_t)WOLFSSL_MAX_32BIT) { + return MBEDTLS_ERR_PEM_BAD_INPUT_DATA; + } + if (!wolfPSA_CryptoReady()) { + return PSA_ERROR_BAD_STATE; + } + + inLen = (word32)(s2 - s1); + size = (inLen / 4 + 1) * 3; + buf = (unsigned char*)XMALLOC(size, NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (buf == NULL) { + return MBEDTLS_ERR_PEM_ALLOC_FAILED; + } + len = size; + if (Base64_Decode((const byte*)s1, inLen, buf, &len) != 0) { + ret = MBED_PEM_BAD_BASE64; + } + else if (len == 0) { + ret = MBEDTLS_ERR_PEM_BAD_INPUT_DATA; + } + if (ret != 0) { + wc_ForceZero(buf, size); + XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER); + return ret; + } + + mbedtls_pem_free(ctx); + ctx->buf = buf; + ctx->buflen = len; + return 0; +} + +void mbedtls_pem_free(mbedtls_pem_context* ctx) +{ + WOLFSSL_ENTER("mbedtls_pem_free"); + + if (ctx != NULL && ctx->buf != NULL) { + wc_ForceZero(ctx->buf, ctx->buflen); + XFREE(ctx->buf, NULL, DYNAMIC_TYPE_TMP_BUFFER); + } + mbedtls_pem_init(ctx); +} + +#endif /* MBEDTLS_PEM_PARSE_C */ + +#endif /* WOLFSSL_PSA_ENGINE && WOLFPSA_MBEDTLS_COMPAT */ diff --git a/src/mbedtls/ssl.c b/src/mbedtls/ssl.c new file mode 100644 index 0000000..25ee76d --- /dev/null +++ b/src/mbedtls/ssl.c @@ -0,0 +1,1217 @@ +/* ssl.c + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of wolfPSA. + * + * wolfPSA is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * wolfPSA is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +/* Mbed TLS 4.x TLS API on wolfSSL (MBEDTLS_COMPAT=1). */ + +#ifdef HAVE_CONFIG_H + #include +#endif /* HAVE_CONFIG_H */ + +#include "psa_config.h" + +#if defined(WOLFSSL_PSA_ENGINE) && defined(WOLFPSA_MBEDTLS_COMPAT) + +#include + +/* The generated config has MBEDTLS_SSL_TLS_C with wolfSSL's TLS and SNI, and + * MBEDTLS_X509_CRT_PARSE_C */ +#if defined(MBEDTLS_SSL_TLS_C) != (defined(MBEDTLS_X509_CRT_PARSE_C) && \ + !defined(WOLFCRYPT_ONLY) && defined(HAVE_SNI)) + #error "MBEDTLS_SSL_TLS_C does not match WOLFCRYPT_ONLY and HAVE_SNI" +#endif /* MBEDTLS_SSL_TLS_C != (X509_CRT_PARSE_C && TLS && SNI) */ + +#if defined(MBEDTLS_SSL_TLS_C) + +#include +#include +#include +#include +#include +#include +#include +#include "mbedtls_compat_internal.h" +#include "psa_tf_psa_internal.h" + +/* Unknown codes map to the last entry */ +int MbedIoErr(int code, int dir, int toWolf) +{ + static const struct { + int wolf; + int mbed[2]; + } map[] = { + { WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_WANT_READ), + { MBEDTLS_ERR_SSL_WANT_READ, MBEDTLS_ERR_SSL_WANT_WRITE } }, + { WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_CONN_RST), + { MBEDTLS_ERR_NET_CONN_RESET, MBEDTLS_ERR_NET_CONN_RESET } }, + /* A receive of 0 bytes is EOF */ + { WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_CONN_CLOSE), + { 0, MBEDTLS_ERR_NET_CONN_RESET } }, + { WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_TIMEOUT), + { MBEDTLS_ERR_SSL_TIMEOUT, MBEDTLS_ERR_SSL_TIMEOUT } }, + { WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_ISR), + { MBEDTLS_ERR_SSL_WANT_READ, MBEDTLS_ERR_SSL_WANT_WRITE } }, + { WC_NO_ERR_TRACE(WOLFSSL_CBIO_ERR_GENERAL), + { MBEDTLS_ERR_NET_RECV_FAILED, MBEDTLS_ERR_NET_SEND_FAILED } } + }; + const size_t last = XELEM_CNT(map) - 1; + size_t i; + + if (toWolf) { + for (i = 0; i < last; i++) { + if (map[i].mbed[dir] == code) { + break; + } + } + return map[i].wolf; + } + + for (i = 0; i < last; i++) { + if (map[i].wolf == code) { + break; + } + } + return map[i].mbed[dir]; +} + +int MbedIoLen(size_t len, int max) +{ + return (len > (size_t)max) ? max : (int)len; +} + +/* Mbed TLS checks these apart from the chain and fails with + * MBEDTLS_ERR_SSL_BAD_CERTIFICATE */ +#define MBED_USAGE_FLAGS \ + (MBEDTLS_X509_BADCERT_KEY_USAGE | MBEDTLS_X509_BADCERT_EXT_KEY_USAGE) + +/* Map the wolfSSL error behind a failed call to an Mbed TLS return code */ +static int MbedSslErr(const mbedtls_ssl_context* ssl, int ret) +{ + static const struct { + int wolf; + int mbed; + } map[] = { + /* A zero-length read or write */ + { WOLFSSL_ERROR_NONE, 0 }, + { WOLFSSL_ERROR_WANT_READ, MBEDTLS_ERR_SSL_WANT_READ }, + { WOLFSSL_ERROR_WANT_WRITE, MBEDTLS_ERR_SSL_WANT_WRITE }, + { WOLFSSL_ERROR_ZERO_RETURN, MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY }, + { WC_NO_ERR_TRACE(SOCKET_PEER_CLOSED_E), MBEDTLS_ERR_SSL_CONN_EOF }, + { WC_NO_ERR_TRACE(NO_PEER_CERT), MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE } + }; + int err = wolfSSL_get_error(ssl->ssl, ret); + size_t i; + + /* A failed verify is what ended the handshake */ + if (ssl->verify_flags != 0) { + return ((ssl->verify_flags & ~MBED_USAGE_FLAGS) != 0) ? + MBEDTLS_ERR_X509_CERT_VERIFY_FAILED : + MBEDTLS_ERR_SSL_BAD_CERTIFICATE; + } + /* wolfSSL's error for any failed BIO call */ + if (err == WC_NO_ERR_TRACE(SOCKET_ERROR_E) && ssl->io_err != 0) { + return ssl->io_err; + } + for (i = 0; i < XELEM_CNT(map); i++) { + if (map[i].wolf == err) { + return map[i].mbed; + } + } + /* wolfSSL codes overlap Mbed TLS and PSA codes */ + return MBEDTLS_ERR_SSL_INTERNAL_ERROR; +} + +/* WOLFSSL_SUCCESS becomes 0. WOLFSSL_FAILURE is 0, a success for + * wolfPSA_MbedRet(). */ +static int MbedRet(int ret, int fallback) +{ + if (ret == WOLFSSL_SUCCESS) { + return 0; + } + return (ret == WOLFSSL_FAILURE) ? fallback : + wolfPSA_MbedRet(ret, fallback); +} + +/* conf->err index of each kind of conf call. Each call sets its own, 0 on + * success, apart from a method change, which only config_defaults clears. */ +enum { + MBED_CONF_ERR_METHOD, + MBED_CONF_ERR_AUTHMODE, + MBED_CONF_ERR_CA, + MBED_CONF_ERR_OWN_CERT, + MBED_CONF_ERR_KINDS +}; +wc_static_assert(MBED_CONF_ERR_KINDS == + XELEM_CNT(((mbedtls_ssl_config*)0)->err)); + +static int MbedConfErr(const mbedtls_ssl_config* conf) +{ + size_t i; + + for (i = 0; i < XELEM_CNT(conf->err); i++) { + if (conf->err[i] != 0) { + return conf->err[i]; + } + } + return 0; +} + +/* The BIO call's result for wolfSSL. Keeps an error for MbedSslErr(). */ +static int MbedIoRet(mbedtls_ssl_context* s, int ret, int dir) +{ + s->io_err = (ret < 0) ? ret : 0; + return (ret > 0) ? ret : MbedIoErr(ret, dir, 1); +} + +static int MbedRecvCb(WOLFSSL* ssl, char* buf, int sz, void* ctx) +{ + mbedtls_ssl_context* s = (mbedtls_ssl_context*)ctx; + int ret = MBEDTLS_ERR_SSL_BAD_INPUT_DATA; + + (void)ssl; + if (s->f_recv_timeout != NULL) { + ret = s->f_recv_timeout(s->p_bio, (unsigned char*)buf, (size_t)sz, 0); + } + else if (s->f_recv != NULL) { + ret = s->f_recv(s->p_bio, (unsigned char*)buf, (size_t)sz); + } + return MbedIoRet(s, ret, MBED_IO_RECV); +} + +static int MbedSendCb(WOLFSSL* ssl, char* buf, int sz, void* ctx) +{ + mbedtls_ssl_context* s = (mbedtls_ssl_context*)ctx; + int ret = MBEDTLS_ERR_SSL_BAD_INPUT_DATA; + + (void)ssl; + if (s->f_send != NULL) { + ret = s->f_send(s->p_bio, (const unsigned char*)buf, (size_t)sz); + } + return MbedIoRet(s, ret, MBED_IO_SEND); +} + +/* Unknown codes map to the last entry */ +static uint32_t MbedVerifyFlag(int err) +{ + static const struct { + int wolf; + uint32_t mbed; + } map[] = { + { 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_SIG_CONFIRM_E), + MBEDTLS_X509_BADCERT_NOT_TRUSTED }, + { WC_NO_ERR_TRACE(DOMAIN_NAME_MISMATCH), + MBEDTLS_X509_BADCERT_CN_MISMATCH }, + { WC_NO_ERR_TRACE(IPADDR_MISMATCH), MBEDTLS_X509_BADCERT_CN_MISMATCH }, + { WC_NO_ERR_TRACE(CRL_CERT_REVOKED), MBEDTLS_X509_BADCERT_REVOKED }, + { WC_NO_ERR_TRACE(OCSP_CERT_REVOKED), MBEDTLS_X509_BADCERT_REVOKED }, + { WC_NO_ERR_TRACE(CRL_CERT_DATE_ERR), MBEDTLS_X509_BADCRL_EXPIRED }, + { WC_NO_ERR_TRACE(KEYUSE_SIGNATURE_E), + MBEDTLS_X509_BADCERT_KEY_USAGE }, + { WC_NO_ERR_TRACE(KEYUSE_ENCIPHER_E), MBEDTLS_X509_BADCERT_KEY_USAGE }, + { WC_NO_ERR_TRACE(EXTKEYUSE_AUTH_E), + MBEDTLS_X509_BADCERT_EXT_KEY_USAGE }, + { WC_NO_ERR_TRACE(RSA_KEY_SIZE_E), MBEDTLS_X509_BADCERT_BAD_KEY }, + { WC_NO_ERR_TRACE(ECC_KEY_SIZE_E), MBEDTLS_X509_BADCERT_BAD_KEY }, + { 0, MBEDTLS_X509_BADCERT_OTHER } + }; + const size_t last = XELEM_CNT(map) - 1; + size_t i; + + for (i = 0; i < last; i++) { + if (map[i].wolf == err) { + break; + } + } + 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 MbedVerifyCb(int preverify, WOLFSSL_X509_STORE_CTX* store) +{ + mbedtls_ssl_context* s = (mbedtls_ssl_context*)store->userCtx; + + if (!preverify) { + s->verify_flags |= MbedVerifyFlag(store->error); + } + return preverify; +} + +void mbedtls_ssl_config_init(mbedtls_ssl_config* conf) +{ + WOLFSSL_ENTER("mbedtls_ssl_config_init"); + + if (conf != NULL) { + XMEMSET(conf, 0, sizeof(*conf)); + } +} + +void mbedtls_ssl_config_free(mbedtls_ssl_config* conf) +{ + WOLFSSL_ENTER("mbedtls_ssl_config_free"); + + if (conf != NULL) { + wolfSSL_CTX_free(conf->ctx); + XMEMSET(conf, 0, sizeof(*conf)); + } +} + +void mbedtls_ssl_conf_authmode(mbedtls_ssl_config* conf, int authmode) +{ + WOLFSSL_ENTER("mbedtls_ssl_conf_authmode"); + + if (conf == NULL) { + return; + } + conf->changes++; + if (authmode != MBEDTLS_SSL_VERIFY_NONE && + authmode != MBEDTLS_SSL_VERIFY_REQUIRED) { + 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); + } +} + +/* 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. */ +static void MbedConfCAs(mbedtls_ssl_config* conf) +{ + const mbedtls_x509_crt* crt; + int ret = (conf->ca_crl == NULL) ? 0 : MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; + + if (ret == 0) { + ret = MbedRet(wolfSSL_CTX_UnloadCAs(conf->ctx), + MBEDTLS_ERR_SSL_BAD_INPUT_DATA); + } + 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)) { + ret = MBEDTLS_ERR_SSL_ALLOC_FAILED; + } + } + conf->err[MBED_CONF_ERR_CA] = ret; +} + +int mbedtls_ssl_config_defaults(mbedtls_ssl_config* conf, + int endpoint, int transport, int preset) +{ + static const struct { + int endpoint; + int transport; + WOLFSSL_METHOD* (*method)(void); + } methods[] = { + #ifndef NO_WOLFSSL_CLIENT + { MBEDTLS_SSL_IS_CLIENT, MBEDTLS_SSL_TRANSPORT_STREAM, + wolfTLS_client_method }, + #endif /* !NO_WOLFSSL_CLIENT */ + #ifndef NO_WOLFSSL_SERVER + { MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_TRANSPORT_STREAM, + wolfTLS_server_method }, + #endif /* !NO_WOLFSSL_SERVER */ + #if defined(WOLFSSL_DTLS) && !defined(NO_WOLFSSL_CLIENT) + { MBEDTLS_SSL_IS_CLIENT, MBEDTLS_SSL_TRANSPORT_DATAGRAM, + wolfDTLS_client_method }, + #endif /* WOLFSSL_DTLS && !NO_WOLFSSL_CLIENT */ + #if defined(WOLFSSL_DTLS) && !defined(NO_WOLFSSL_SERVER) + { MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_TRANSPORT_DATAGRAM, + wolfDTLS_server_method }, + #endif /* WOLFSSL_DTLS && !NO_WOLFSSL_SERVER */ + }; + size_t i; + + WOLFSSL_ENTER("mbedtls_ssl_config_defaults"); + + if (conf == NULL) { + return MBEDTLS_ERR_SSL_BAD_INPUT_DATA; + } + for (i = 0; i < XELEM_CNT(methods); i++) { + if (methods[i].endpoint == endpoint && + methods[i].transport == transport) { + break; + } + } + if (i == XELEM_CNT(methods) || preset != MBEDTLS_SSL_PRESET_DEFAULT) { + return MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; + } + if (!wolfPSA_CryptoReady()) { + return PSA_ERROR_BAD_STATE; + } + + wolfSSL_CTX_free(conf->ctx); + conf->changes++; + XMEMSET(conf->err, 0, sizeof(conf->err)); + /* wolfSSL_new() fails for a server without a certificate and key */ + if (endpoint == MBEDTLS_SSL_IS_SERVER) { + conf->err[MBED_CONF_ERR_OWN_CERT] = MBEDTLS_ERR_SSL_BAD_CONFIG; + } + conf->endpoint = endpoint; + conf->transport = transport; +#ifdef MBEDTLS_SSL_PROTO_TLS1_2 + conf->min_tls_version = MBEDTLS_SSL_VERSION_TLS1_2; +#else + conf->min_tls_version = MBEDTLS_SSL_VERSION_TLS1_3; +#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ +#ifdef MBEDTLS_SSL_PROTO_TLS1_3 + conf->max_tls_version = MBEDTLS_SSL_VERSION_TLS1_3; +#else + conf->max_tls_version = MBEDTLS_SSL_VERSION_TLS1_2; +#endif /* MBEDTLS_SSL_PROTO_TLS1_3 */ + conf->ciphersuites = NULL; + conf->ctx = wolfSSL_CTX_new(methods[i].method()); + if (conf->ctx == NULL) { + return MBEDTLS_ERR_SSL_ALLOC_FAILED; + } + mbedtls_ssl_conf_authmode(conf, + (endpoint == MBEDTLS_SSL_IS_CLIENT) ? MBEDTLS_SSL_VERIFY_REQUIRED : + MBEDTLS_SSL_VERIFY_NONE); + /* As in Mbed TLS, the CAs set before are kept */ + MbedConfCAs(conf); + return 0; +} + +/* The WOLFSSL_CTX keeps the endpoint and transport of config_defaults */ +static void MbedConfMethod(mbedtls_ssl_config* conf, int* field, int value) +{ + if (conf->ctx != NULL && *field != value) { + conf->err[MBED_CONF_ERR_METHOD] = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; + } + *field = value; + conf->changes++; +} + +void mbedtls_ssl_conf_endpoint(mbedtls_ssl_config* conf, int endpoint) +{ + WOLFSSL_ENTER("mbedtls_ssl_conf_endpoint"); + + if (conf != NULL) { + MbedConfMethod(conf, &conf->endpoint, endpoint); + } +} + +void mbedtls_ssl_conf_transport(mbedtls_ssl_config* conf, int transport) +{ + WOLFSSL_ENTER("mbedtls_ssl_conf_transport"); + + if (conf != NULL) { + MbedConfMethod(conf, &conf->transport, transport); + } +} + +int mbedtls_ssl_conf_get_endpoint(const mbedtls_ssl_config* conf) +{ + WOLFSSL_ENTER("mbedtls_ssl_conf_get_endpoint"); + + return (conf != NULL) ? conf->endpoint : MBEDTLS_ERR_SSL_BAD_INPUT_DATA; +} + +void mbedtls_ssl_conf_ca_chain(mbedtls_ssl_config* conf, + mbedtls_x509_crt* ca_chain, mbedtls_x509_crl* ca_crl) +{ + WOLFSSL_ENTER("mbedtls_ssl_conf_ca_chain"); + + if (conf == NULL) { + return; + } + conf->changes++; + conf->ca_chain = ca_chain; + conf->ca_crl = ca_crl; + if (conf->ctx != NULL) { + MbedConfCAs(conf); + } +} + +/* Mbed TLS sends every certificate in own_cert. A second call replaces the + * first, where Mbed TLS keeps both and picks one per handshake. wolfSSL + * replaces each before checking it, so setup returns a failed load's error. */ +int mbedtls_ssl_conf_own_cert(mbedtls_ssl_config* conf, + mbedtls_x509_crt* own_cert, mbedtls_pk_context* pk_key) +{ + const mbedtls_x509_crt* crt; + unsigned char* chain; + size_t len = 0; + int ret; + + WOLFSSL_ENTER("mbedtls_ssl_conf_own_cert"); + + if (conf == NULL || conf->ctx == NULL || own_cert == NULL || + own_cert->raw.p == NULL || pk_key == NULL || pk_key->der == NULL) { + return MBEDTLS_ERR_SSL_BAD_INPUT_DATA; + } + conf->changes++; + + for (crt = own_cert; crt != NULL; crt = crt->next) { + len += crt->raw.len; + } + chain = (unsigned char*)XMALLOC(len, NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (chain == NULL) { + return MBEDTLS_ERR_SSL_ALLOC_FAILED; + } + len = 0; + for (crt = own_cert; crt != NULL; crt = crt->next) { + XMEMCPY(chain + len, crt->raw.p, crt->raw.len); + len += crt->raw.len; + } + + ret = MbedRet(wolfSSL_CTX_use_certificate_chain_buffer_format(conf->ctx, + chain, (long)len, WOLFSSL_FILETYPE_ASN1), + MBEDTLS_ERR_SSL_BAD_INPUT_DATA); + XFREE(chain, NULL, DYNAMIC_TYPE_TMP_BUFFER); + if (ret == 0) { + ret = MbedRet(wolfSSL_CTX_use_PrivateKey_buffer(conf->ctx, + pk_key->der, (long)pk_key->der_len, WOLFSSL_FILETYPE_ASN1), + MBEDTLS_ERR_SSL_BAD_INPUT_DATA); + } + conf->err[MBED_CONF_ERR_OWN_CERT] = ret; + return ret; +} + +/* Without MBEDTLS_DEBUG_C, Mbed TLS never calls f_dbg either */ +void mbedtls_ssl_conf_dbg(mbedtls_ssl_config* conf, + void (*f_dbg)(void*, int, const char*, int, const char*), void* p_dbg) +{ + WOLFSSL_ENTER("mbedtls_ssl_conf_dbg"); + + (void)conf; + (void)f_dbg; + (void)p_dbg; +} + +void mbedtls_ssl_conf_min_tls_version(mbedtls_ssl_config* conf, + mbedtls_ssl_protocol_version tls_version) +{ + WOLFSSL_ENTER("mbedtls_ssl_conf_min_tls_version"); + + if (conf != NULL) { + conf->min_tls_version = tls_version; + conf->changes++; + } +} + +void mbedtls_ssl_conf_max_tls_version(mbedtls_ssl_config* conf, + mbedtls_ssl_protocol_version tls_version) +{ + WOLFSSL_ENTER("mbedtls_ssl_conf_max_tls_version"); + + if (conf != NULL) { + conf->max_tls_version = tls_version; + conf->changes++; + } +} + +/* Not copied: the list must stay valid while conf is in use */ +void mbedtls_ssl_conf_ciphersuites(mbedtls_ssl_config* conf, + const int* ciphersuites) +{ + WOLFSSL_ENTER("mbedtls_ssl_conf_ciphersuites"); + + if (conf != NULL) { + conf->ciphersuites = ciphersuites; + conf->changes++; + } +} + +void mbedtls_ssl_conf_cert_profile(mbedtls_ssl_config* conf, + const mbedtls_x509_crt_profile* profile) +{ + WOLFSSL_ENTER("mbedtls_ssl_conf_cert_profile"); + + (void)conf; + (void)profile; +} + +#define MBED_SUITES_MAX (WOLFSSL_MAX_SUITE_SZ / 2) +#define MBED_SUITE_NAME_SZ 64 + +static int mbedSuiteIds[MBED_SUITES_MAX + 1]; +static char mbedSuiteNames[MBED_SUITES_MAX][MBED_SUITE_NAME_SZ]; +static int mbedSuitesSet = 0; + +/* MBEDTLS_THREADING_C is on pthreads, which have a static initializer */ +#ifdef MBEDTLS_THREADING_C +static wolfSSL_Mutex mbedSuitesMutex = + WOLFSSL_MUTEX_INITIALIZER(mbedSuitesMutex); +#define MBED_SUITES_LOCK() (void)wc_LockMutex(&mbedSuitesMutex) +#define MBED_SUITES_UNLOCK() (void)wc_UnLockMutex(&mbedSuitesMutex) +#else +#define MBED_SUITES_LOCK() WC_DO_NOTHING +#define MBED_SUITES_UNLOCK() WC_DO_NOTHING +#endif /* MBEDTLS_THREADING_C */ + +/* TLS1-3-AES-128-GCM-SHA256 for TLS_AES_128_GCM_SHA256, else the IANA name + * with dashes */ +static void MbedSuiteName(byte cs0, byte cs, char* name, size_t sz) +{ + const char* iana = wolfSSL_get_cipher_name_iana_from_suite(cs0, cs); + size_t i = 0; + + if (iana == NULL) { + iana = "unknown"; + } + if (cs0 == TLS13_BYTE && XSTRNCMP(iana, "TLS_", 4) == 0) { + XMEMCPY(name, "TLS1-3", 6); + i = 6; + iana += 3; + } + for (; i + 1 < sz && *iana != '\0'; i++, iana++) { + name[i] = (*iana == '_') ? '-' : *iana; + } + name[i] = '\0'; +} + +/* wolfSSL's default client suites, most preferred first. No WOLFSSL_CTX, so + * it works for either side and before psa_crypto_init(). */ +static void MbedSuitesFill(void) +{ + Suites suites; +#ifdef WOLFSSL_TLS13 + const ProtocolVersion pv = MakeTLSv1_3(); +#else + const ProtocolVersion pv = MakeTLSv1_2(); +#endif /* WOLFSSL_TLS13 */ + size_t n = 0; + word16 i; + byte cs0; + byte cs; + + XMEMSET(&suites, 0, sizeof(suites)); + /* Every key type, without PSK and anonymous suites */ + InitSuites(&suites, pv, 0, TRUE, FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, + FALSE, TRUE, TRUE, TRUE, TRUE, WOLFSSL_CLIENT_END); + for (i = 0; i + 1 < suites.suiteSz && n < MBED_SUITES_MAX; i += 2) { + cs0 = suites.suites[i]; + cs = suites.suites[i + 1]; + if (cs0 == CIPHER_BYTE && cs == TLS_EMPTY_RENEGOTIATION_INFO_SCSV) { + continue; + } + mbedSuiteIds[n] = (cs0 << 8) | cs; + MbedSuiteName(cs0, cs, mbedSuiteNames[n], sizeof(mbedSuiteNames[n])); + n++; + } + mbedSuiteIds[n] = 0; +} + +/* Filled on first use, as Mbed TLS does */ +const int* mbedtls_ssl_list_ciphersuites(void) +{ + WOLFSSL_ENTER("mbedtls_ssl_list_ciphersuites"); + + MBED_SUITES_LOCK(); + if (!mbedSuitesSet) { + MbedSuitesFill(); + mbedSuitesSet = 1; + } + MBED_SUITES_UNLOCK(); + return mbedSuiteIds; +} + +const char* mbedtls_ssl_get_ciphersuite_name(const int ciphersuite_id) +{ + const int* ids = mbedtls_ssl_list_ciphersuites(); + size_t i; + + WOLFSSL_ENTER("mbedtls_ssl_get_ciphersuite_name"); + + for (i = 0; ids[i] != 0; i++) { + if (ids[i] == ciphersuite_id) { + return mbedSuiteNames[i]; + } + } + return "unknown"; +} + +int mbedtls_ssl_get_ciphersuite_id(const char* ciphersuite_name) +{ + const int* ids = mbedtls_ssl_list_ciphersuites(); + size_t i; + + WOLFSSL_ENTER("mbedtls_ssl_get_ciphersuite_id"); + + for (i = 0; ciphersuite_name != NULL && ids[i] != 0; i++) { + if (XSTRCMP(mbedSuiteNames[i], ciphersuite_name) == 0) { + return ids[i]; + } + } + return 0; +} + +void mbedtls_ssl_init(mbedtls_ssl_context* ssl) +{ + WOLFSSL_ENTER("mbedtls_ssl_init"); + + if (ssl != NULL) { + XMEMSET(ssl, 0, sizeof(*ssl)); + } +} + +void mbedtls_ssl_free(mbedtls_ssl_context* ssl) +{ + WOLFSSL_ENTER("mbedtls_ssl_free"); + + if (ssl != NULL) { + wolfSSL_free(ssl->ssl); + XFREE(ssl->hostname, NULL, DYNAMIC_TYPE_DOMAIN); + XMEMSET(ssl, 0, sizeof(*ssl)); + } +} + +/* Eight groups of four hex digits, seven colons and the NUL */ +#define MBED_IP_TEXT_SZ 40 + +/* The IP address in host as wolfSSL prints a certificate's IP addresses for + * its name check: dotted decimal, or eight groups of four hex digits. + * Returns 0 when host is not an IP address. */ +static int MbedIpText(const char* host, char* text, size_t sz) +{ + byte ip[16]; + int len = 0; + + (void)host; + (void)text; + (void)sz; + (void)ip; +#ifdef AF_INET + if (XINET_PTON(AF_INET, host, ip) == 1) { + len = XSNPRINTF(text, sz, "%u.%u.%u.%u", (unsigned)ip[0], + (unsigned)ip[1], (unsigned)ip[2], (unsigned)ip[3]); + } +#endif /* AF_INET */ +#ifdef AF_INET6 + if (len == 0 && XINET_PTON(AF_INET6, host, ip) == 1) { + int i; + + for (i = 0; i < 8; i++) { + len += XSNPRINTF(text + len, sz - (size_t)len, "%02X%02X%s", + (unsigned)ip[2 * i], (unsigned)ip[2 * i + 1], + (i < 7) ? ":" : ""); + } + } +#endif /* AF_INET6 */ + return len; +} + +/* RFC 6066 has no IP addresses in server_name, which Mbed TLS sends anyway */ +static int MbedSetHostname(WOLFSSL* ssl, const char* hostname) +{ + char ip[MBED_IP_TEXT_SZ]; + int ret; + + if (hostname == NULL) { + return 0; + } + if (MbedIpText(hostname, ip, sizeof(ip)) > 0) { + return MbedRet(wolfSSL_check_ip_address(ssl, ip), + MBEDTLS_ERR_SSL_BAD_INPUT_DATA); + } + ret = MbedRet(wolfSSL_UseSNI(ssl, WOLFSSL_SNI_HOST_NAME, hostname, + (word16)XSTRLEN(hostname)), MBEDTLS_ERR_SSL_BAD_INPUT_DATA); + if (ret == 0) { + ret = MbedRet(wolfSSL_check_domain_name(ssl, hostname), + MBEDTLS_ERR_SSL_BAD_INPUT_DATA); + } + return ret; +} + +/* TLS 1.2, TLS 1.3, or both. With a minimum set, wolfSSL_SetVersion() sets + * the top of the range. */ +static int MbedSetVersion(WOLFSSL* ssl, const mbedtls_ssl_config* conf) +{ + static const struct { + mbedtls_ssl_protocol_version mbed; + int wolf; + } map[] = { + { MBEDTLS_SSL_VERSION_TLS1_2, WOLFSSL_TLSV1_2 }, + { MBEDTLS_SSL_VERSION_TLS1_3, WOLFSSL_TLSV1_3 } + }; + int minVer = -1; + int maxVer = -1; + int ret = MBEDTLS_ERR_SSL_BAD_INPUT_DATA; + size_t i; + + for (i = 0; i < XELEM_CNT(map); i++) { + if (map[i].mbed == conf->min_tls_version) { + minVer = map[i].wolf; + } + if (map[i].mbed == conf->max_tls_version) { + maxVer = map[i].wolf; + } + } + if (minVer >= 0 && minVer <= maxVer) { + ret = MbedRet(wolfSSL_SetMinVersion(ssl, minVer), + MBEDTLS_ERR_SSL_BAD_INPUT_DATA); + } + if (ret == 0) { + ret = MbedRet(wolfSSL_SetVersion(ssl, maxVer), + MBEDTLS_ERR_SSL_BAD_INPUT_DATA); + } + return ret; +} + +/* After MbedSetVersion, which resets the suites */ +static int MbedSetSuites(WOLFSSL* ssl, const int* ids) +{ + byte suites[WOLFSSL_MAX_SUITE_SZ]; + int len = 0; + + if (ids == NULL) { + return 0; + } + for (; *ids != 0 && len + 2 <= (int)sizeof(suites); ids++) { + suites[len++] = (byte)(*ids >> 8); + suites[len++] = (byte)*ids; + } + return MbedRet(wolfSSL_set_cipher_list_bytes(ssl, suites, len), + MBEDTLS_ERR_SSL_BAD_INPUT_DATA); +} + +/* Replaces the WOLFSSL with a new one from the config, with this context's + * callbacks, host name and session. Leaves none on failure. */ +static int MbedSslNew(mbedtls_ssl_context* ssl) +{ + WOLFSSL_SESSION* session = NULL; + int ret = MbedConfErr(ssl->conf); + + if (ret == 0 && ssl->conf->ctx == NULL) { + ret = MBEDTLS_ERR_SSL_BAD_INPUT_DATA; + } + if (ret == 0 && ssl->session_set) { + session = wolfSSL_get1_session(ssl->ssl); + } + wolfSSL_free(ssl->ssl); + ssl->ssl = NULL; + if (ret == 0) { + ssl->ssl = wolfSSL_new(ssl->conf->ctx); + if (ssl->ssl == NULL) { + ret = MBEDTLS_ERR_SSL_ALLOC_FAILED; + } + } + if (ret == 0) { + ssl->started = 0; + ssl->authmode = ssl->conf->authmode; + ssl->verify_flags = 0; + ssl->io_err = 0; + wolfSSL_SSLSetIORecv(ssl->ssl, MbedRecvCb); + wolfSSL_SSLSetIOSend(ssl->ssl, MbedSendCb); + wolfSSL_SetIOReadCtx(ssl->ssl, ssl); + wolfSSL_SetIOWriteCtx(ssl->ssl, ssl); + wolfSSL_SetCertCbCtx(ssl->ssl, ssl); + ret = MbedSetVersion(ssl->ssl, ssl->conf); + } + if (ret == 0) { + ret = MbedSetSuites(ssl->ssl, ssl->conf->ciphersuites); + } + if (ret == 0) { + ret = MbedSetHostname(ssl->ssl, ssl->hostname); + } + if (ret == 0 && session != NULL) { + /* One that expired since gets a full handshake, as in Mbed TLS */ + (void)wolfSSL_set_session(ssl->ssl, session); + } + wolfSSL_SESSION_free(session); + if (ret == 0) { + ssl->conf_changes = ssl->conf->changes; + ssl->hostname_changed = 0; + } + else { + wolfSSL_free(ssl->ssl); + ssl->ssl = NULL; + } + return ret; +} + +int mbedtls_ssl_setup(mbedtls_ssl_context* ssl, const mbedtls_ssl_config* conf) +{ + WOLFSSL_ENTER("mbedtls_ssl_setup"); + + if (ssl == NULL || conf == NULL) { + return MBEDTLS_ERR_SSL_BAD_INPUT_DATA; + } + ssl->conf = conf; + return MbedSslNew(ssl); +} + +const mbedtls_ssl_config* mbedtls_ssl_context_get_config( + const mbedtls_ssl_context* ssl) +{ + WOLFSSL_ENTER("mbedtls_ssl_context_get_config"); + + return (ssl != NULL) ? ssl->conf : NULL; +} + +int mbedtls_ssl_session_reset(mbedtls_ssl_context* ssl) +{ + WOLFSSL_ENTER("mbedtls_ssl_session_reset"); + + if (ssl == NULL || ssl->conf == NULL) { + return MBEDTLS_ERR_SSL_BAD_INPUT_DATA; + } + /* As in Mbed TLS, the session set before is not used again */ + ssl->session_set = 0; + return MbedSslNew(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) +{ + WOLFSSL_ENTER("mbedtls_ssl_set_bio"); + + if (ssl != NULL) { + ssl->p_bio = p_bio; + ssl->f_send = f_send; + ssl->f_recv = f_recv; + ssl->f_recv_timeout = f_recv_timeout; + } +} + +/* 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) +{ + char* copy = NULL; + size_t len; + int ret = 0; + + WOLFSSL_ENTER("mbedtls_ssl_set_hostname"); + + if (ssl == NULL) { + return MBEDTLS_ERR_SSL_BAD_INPUT_DATA; + } + if (hostname != NULL) { + len = XSTRLEN(hostname); + if (len > MBEDTLS_SSL_MAX_HOST_NAME_LEN) { + return MBEDTLS_ERR_SSL_BAD_INPUT_DATA; + } + if (!wolfPSA_CryptoReady()) { + return PSA_ERROR_BAD_STATE; + } + copy = (char*)XMALLOC(len + 1, NULL, DYNAMIC_TYPE_DOMAIN); + if (copy == NULL) { + return MBEDTLS_ERR_SSL_ALLOC_FAILED; + } + XMEMCPY(copy, hostname, len + 1); + } + + /* Once the handshake starts, the name applies from the next reset */ + if (ssl->ssl != NULL && !ssl->started) { + ret = MbedSetHostname(ssl->ssl, hostname); + /* wolfSSL cannot remove a name: MbedSslStart() makes a new WOLFSSL */ + if (ret != 0 || ssl->hostname != NULL) { + ssl->hostname_changed = 1; + } + } + if (ret == 0) { + XFREE(ssl->hostname, NULL, DYNAMIC_TYPE_DOMAIN); + ssl->hostname = copy; + ssl->hostname_set = 1; + } + else { + XFREE(copy, NULL, DYNAMIC_TYPE_DOMAIN); + } + return ret; +} + +/* Mbed TLS reads the config during the handshake, so conf_* calls and a host + * name set before it starts apply to it. As in Mbed TLS 4.x, a client that + * verifies the server needs mbedtls_ssl_set_hostname() first. */ +static int MbedSslStart(mbedtls_ssl_context* ssl) +{ + int ret = 0; + + if (ssl == NULL || ssl->conf == NULL || ssl->ssl == NULL) { + return MBEDTLS_ERR_SSL_BAD_INPUT_DATA; + } + if (!ssl->started && (ssl->conf_changes != ssl->conf->changes || + ssl->hostname_changed)) { + ret = MbedSslNew(ssl); + } + if (ret == 0 && ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT && + ssl->authmode == MBEDTLS_SSL_VERIFY_REQUIRED && + !ssl->hostname_set) { + ret = MBEDTLS_ERR_SSL_CERTIFICATE_VERIFICATION_WITHOUT_HOSTNAME; + } + if (ret == 0) { + ssl->started = 1; + } + return ret; +} + +int mbedtls_ssl_handshake(mbedtls_ssl_context* ssl) +{ + int ret; + + WOLFSSL_ENTER("mbedtls_ssl_handshake"); + + ret = MbedSslStart(ssl); + if (ret != 0) { + return ret; + } + ret = wolfSSL_negotiate(ssl->ssl); + return (ret == WOLFSSL_SUCCESS) ? 0 : MbedSslErr(ssl, ret); +} + +int mbedtls_ssl_is_handshake_over(mbedtls_ssl_context* ssl) +{ + WOLFSSL_ENTER("mbedtls_ssl_is_handshake_over"); + + return ssl != NULL && ssl->ssl != NULL && + wolfSSL_is_init_finished(ssl->ssl); +} + +/* All ones while no result is available, as in Mbed TLS */ +uint32_t mbedtls_ssl_get_verify_result(const mbedtls_ssl_context* ssl) +{ + WOLFSSL_ENTER("mbedtls_ssl_get_verify_result"); + + if (ssl == NULL || ssl->ssl == NULL) { + return 0xFFFFFFFF; + } + if (ssl->verify_flags != 0) { + return ssl->verify_flags; + } + if (!wolfSSL_is_init_finished(ssl->ssl)) { + return 0xFFFFFFFF; + } + if (ssl->session_set && wolfSSL_session_reused(ssl->ssl)) { + return ssl->session_verify; + } + if (ssl->authmode == MBEDTLS_SSL_VERIFY_NONE) { + return MBEDTLS_X509_BADCERT_SKIP_VERIFY; + } + /* A server keeps no verify result with a session it resumes */ + return wolfSSL_session_reused(ssl->ssl) ? MBEDTLS_X509_BADCERT_MISSING : + 0; +} + +const char* mbedtls_ssl_get_ciphersuite(const mbedtls_ssl_context* ssl) +{ + WOLFSSL_ENTER("mbedtls_ssl_get_ciphersuite"); + + if (ssl == NULL || ssl->ssl == NULL) { + return NULL; + } + return mbedtls_ssl_get_ciphersuite_name( + mbedtls_ssl_get_ciphersuite_id_from_ssl(ssl)); +} + +int mbedtls_ssl_get_ciphersuite_id_from_ssl(const mbedtls_ssl_context* ssl) +{ + WOLFSSL_ENTER("mbedtls_ssl_get_ciphersuite_id_from_ssl"); + + if (ssl == NULL || ssl->ssl == NULL) { + return 0; + } + return wolfSSL_get_current_cipher_suite(ssl->ssl); +} + +const char* mbedtls_ssl_get_version(const mbedtls_ssl_context* ssl) +{ + WOLFSSL_ENTER("mbedtls_ssl_get_version"); + + if (ssl == NULL || ssl->ssl == NULL) { + return "unknown"; + } + return wolfSSL_get_version(ssl->ssl); +} + +/* wolfSSL_version() returns the same IETF values */ +mbedtls_ssl_protocol_version mbedtls_ssl_get_version_number( + const mbedtls_ssl_context* ssl) +{ + int version; + + WOLFSSL_ENTER("mbedtls_ssl_get_version_number"); + + if (ssl == NULL || ssl->ssl == NULL) { + return MBEDTLS_SSL_VERSION_UNKNOWN; + } + version = wolfSSL_version(ssl->ssl); + if (version != MBEDTLS_SSL_VERSION_TLS1_2 && + version != MBEDTLS_SSL_VERSION_TLS1_3) { + return MBEDTLS_SSL_VERSION_UNKNOWN; + } + return (mbedtls_ssl_protocol_version)version; +} + +size_t mbedtls_ssl_get_bytes_avail(const mbedtls_ssl_context* ssl) +{ + int ret; + + WOLFSSL_ENTER("mbedtls_ssl_get_bytes_avail"); + + if (ssl == NULL || ssl->ssl == NULL) { + return 0; + } + ret = wolfSSL_pending(ssl->ssl); + return (ret > 0) ? (size_t)ret : 0; +} + +int mbedtls_ssl_read(mbedtls_ssl_context* ssl, unsigned char* buf, size_t len) +{ + int ret; + + WOLFSSL_ENTER("mbedtls_ssl_read"); + + ret = MbedSslStart(ssl); + if (ret != 0) { + return ret; + } + ret = wolfSSL_read(ssl->ssl, buf, MbedIoLen(len, INT_MAX)); + if (ret > 0) { + return ret; + } + ret = MbedSslErr(ssl, ret); + /* As in Mbed TLS, EOF without close_notify reads 0 */ + return (ret == MBEDTLS_ERR_SSL_CONN_EOF) ? 0 : ret; +} + +int mbedtls_ssl_write(mbedtls_ssl_context* ssl, + const unsigned char* buf, size_t len) +{ + int ret; + + WOLFSSL_ENTER("mbedtls_ssl_write"); + + ret = MbedSslStart(ssl); + if (ret != 0) { + return ret; + } + /* As in Mbed TLS, at most one record */ + ret = wolfSSL_write(ssl->ssl, buf, MbedIoLen(len, MAX_RECORD_SIZE)); + return (ret > 0) ? ret : MbedSslErr(ssl, ret); +} + +/* Mbed TLS sends close_notify without waiting for the peer's reply */ +int mbedtls_ssl_close_notify(mbedtls_ssl_context* ssl) +{ + int ret; + + WOLFSSL_ENTER("mbedtls_ssl_close_notify"); + + if (ssl == NULL || ssl->ssl == NULL) { + return MBEDTLS_ERR_SSL_BAD_INPUT_DATA; + } + ret = wolfSSL_shutdown(ssl->ssl); + if (ret == WOLFSSL_SUCCESS || + ret == WC_NO_ERR_TRACE(WOLFSSL_SHUTDOWN_NOT_DONE)) { + return 0; + } + return MbedSslErr(ssl, ret); +} + +void mbedtls_ssl_session_init(mbedtls_ssl_session* session) +{ + WOLFSSL_ENTER("mbedtls_ssl_session_init"); + + if (session != NULL) { + XMEMSET(session, 0, sizeof(*session)); + } +} + +void mbedtls_ssl_session_free(mbedtls_ssl_session* session) +{ + WOLFSSL_ENTER("mbedtls_ssl_session_free"); + + if (session != NULL) { + wolfSSL_SESSION_free(session->session); + XMEMSET(session, 0, sizeof(*session)); + } +} + +int mbedtls_ssl_get_session(const mbedtls_ssl_context* ssl, + mbedtls_ssl_session* session) +{ + WOLFSSL_ENTER("mbedtls_ssl_get_session"); + + if (ssl == NULL || ssl->ssl == NULL || session == NULL || + session->session != NULL) { + return MBEDTLS_ERR_SSL_BAD_INPUT_DATA; + } + 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; +} + +int mbedtls_ssl_set_session(mbedtls_ssl_context* ssl, + const mbedtls_ssl_session* session) +{ + int ret; + + WOLFSSL_ENTER("mbedtls_ssl_set_session"); + + if (ssl == NULL || ssl->ssl == NULL || session == NULL || + session->session == NULL) { + return MBEDTLS_ERR_SSL_BAD_INPUT_DATA; + } + ret = MbedRet(wolfSSL_set_session(ssl->ssl, session->session), + MBEDTLS_ERR_SSL_BAD_INPUT_DATA); + if (ret == 0) { + ssl->session_set = 1; + ssl->session_verify = session->verify_result; + } + return ret; +} + +/* Serializing a session needs HAVE_EXT_CACHE */ +int mbedtls_ssl_session_save(const mbedtls_ssl_session* session, + unsigned char* buf, size_t buf_len, size_t* olen) +{ + WOLFSSL_ENTER("mbedtls_ssl_session_save"); + + (void)session; + (void)buf; + (void)buf_len; + if (olen != NULL) { + *olen = 0; + } + return MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; +} + +int mbedtls_ssl_session_load(mbedtls_ssl_session* session, + const unsigned char* buf, size_t len) +{ + WOLFSSL_ENTER("mbedtls_ssl_session_load"); + + (void)session; + (void)buf; + (void)len; + return MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; +} + +#endif /* MBEDTLS_SSL_TLS_C */ + +#endif /* WOLFSSL_PSA_ENGINE && WOLFPSA_MBEDTLS_COMPAT */ diff --git a/src/psa_crypto.c b/src/psa_crypto.c index 580834b..4e8f9ef 100644 --- a/src/psa_crypto.c +++ b/src/psa_crypto.c @@ -34,6 +34,23 @@ #include #include +#ifdef MBEDTLS_SSL_TLS_C +#include + +/* Takes wolfSSL's reference, which includes wolfCrypt's. Without it, + * wolfSSL_CTX_new() takes one that is never released. */ +static int wolfPSA_LibInit(void) +{ + int ret = wolfSSL_Init(); + + return (ret == WOLFSSL_SUCCESS) ? 0 : ret; +} +#define wolfPSA_LibCleanup() wolfSSL_Cleanup() +#else +#define wolfPSA_LibInit() wolfCrypt_Init() +#define wolfPSA_LibCleanup() wolfCrypt_Cleanup() +#endif /* MBEDTLS_SSL_TLS_C */ + /* Init latch. psa_crypto_init() must complete single-threaded (per the PSA * contract) before any concurrent PSA use: the mutex-creation bootstrap in * wolfpsa_lock_ensure_init() is a plain, non-atomic flag guard. Once the lock @@ -84,7 +101,7 @@ psa_status_t psa_crypto_init(void) WOLFPSA_LOCK(); if (!g_psa_crypto_initialized) { - ret = wolfCrypt_Init(); + ret = wolfPSA_LibInit(); if (ret != 0) { status = wc_error_to_psa_status(ret); } @@ -116,7 +133,7 @@ void wolfPSA_CryptoCleanup(void) psa_key_storage_cleanup(); if (initialized) { - (void)wolfCrypt_Cleanup(); + (void)wolfPSA_LibCleanup(); } } diff --git a/test/Makefile b/test/Makefile index 060fecf..3d59690 100644 --- a/test/Makefile +++ b/test/Makefile @@ -341,16 +341,20 @@ psa_tf_psa_threading_test: psa_server/psa_tf_psa_threading_test.c \ $(SANITIZE_FLAGS) -pthread -lm # The memory tracker is installed by the real wolfCrypt_Init(), so its test -# has a library built with it, and with the X.509 API, which allocates too +# has a library built with it. Here MBEDTLS_COMPAT=1 is the default and adds +# the Mbed TLS API, which allocates too. It needs wolfSSL master: use +# MBEDTLS_COMPAT=0 with a wolfSSL release. +MBEDTLS_COMPAT ?= 1 TRACK_BUILD_DIR := $(abspath .)/build-track$(if $(SANITIZE_FLAGS),-asan) TRACK_LIB := $(TRACK_BUILD_DIR)/libwolfpsa-track.a TRACK_CPPFLAGS := -DWOLFSSL_USER_SETTINGS -DWOLFSSL_TRACK_MEMORY \ - -DWOLFPSA_MBEDTLS_COMPAT $(VARIANT_INC) \ - -I$(WOLFPSA_ABS)/wolfpsa/mbedtls_compat -I$(TRACK_BUILD_DIR)/include + $(if $(filter 1,$(MBEDTLS_COMPAT)),-DWOLFPSA_MBEDTLS_COMPAT) \ + $(VARIANT_INC) -I$(WOLFPSA_ABS)/wolfpsa/mbedtls_compat \ + -I$(TRACK_BUILD_DIR)/include $(TRACK_LIB): FORCE $(call variant_lib,$(TRACK_BUILD_DIR),-DWOLFSSL_TRACK_MEMORY, \ - MBEDTLS_COMPAT=1) + MBEDTLS_COMPAT=$(MBEDTLS_COMPAT)) psa_track_memory_test: psa_server/psa_track_memory_test.c \ $(TRACK_LIB) FORCE diff --git a/test/mbedtls_compat/Makefile b/test/mbedtls_compat/Makefile index 79e739e..124f638 100644 --- a/test/mbedtls_compat/Makefile +++ b/test/mbedtls_compat/Makefile @@ -1,12 +1,13 @@ -# Build and run the Mbed TLS compatibility tests. Run by -# make MBEDTLS_COMPAT=1 mbedtls-compat-test in the wolfPSA root, which sets -# the paths, all absolute. +# Build and run the Mbed TLS compatibility tests. Run by the +# mbedtls-compat-test, mbedtls-compat-unit and mbedtls-compat-programs +# targets in the wolfPSA root, which set the paths, all absolute. ifndef WOLFPSA_PATH $(error Run make MBEDTLS_COMPAT=1 mbedtls-compat-test in the wolfPSA root) endif CFLAGS ?= -O2 +# Sources from other repositories build without -Werror WARNFLAGS ?= -Wall # Tests use the layer in libwolfpsa.a. WOLFPSA_LDFLAGS has what its build @@ -22,29 +23,124 @@ LAYER_FLAGS += -DMBEDTLS_THREADING_C LAYER_LIBS += -pthread endif -# Certificate and key parsing, on Mbed TLS's test data +# Mbed TLS's test data DATA := $(MBEDTLS_PATH)/framework/data_files -TESTS := $(addprefix $(BUILD_DIR)/,x509_crt_test pk_test) +# Certificate, key and PEM parsing, and TLS return codes and verify results +# with a client and a server in one process +UNIT := $(addprefix $(BUILD_DIR)/,x509_crt_test pk_test pem_test ssl_test) -# 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) +# The peers are the wolfSSL example server and client, from a wolfSSL +# configured out of tree from WOLFSSL_PATH, so they do not depend on wolfPSA's +# settings +WOLFSSL_BUILD := $(BUILD_DIR)/wolfssl +# Mbed TLS's test CA test-ca2.crt has NULL ECDSA parameters, which +# ssl_server sends in its chain +WOLFSSL_CONFIG := --enable-static --disable-shared \ + CPPFLAGS=-DWOLFSSL_ECC_SIGALG_PARAMS_NULL_ALLOWED +WOLFSSL_SERVER := $(WOLFSSL_BUILD)/examples/server/server +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) +# Threads, with MBEDTLS_THREADING_C=1 +ifeq ($(MBEDTLS_THREADING_C),1) +PROGRAMS += $(BUILD_DIR)/programs/ssl/ssl_pthread_server +endif +# Mbed TLS test certificates, data only. certs.c and the generated +# test_certs.h build against the Mbed TLS checkout's own headers. +CERTS := $(BUILD_DIR)/certs.o +CERTS_H := $(BUILD_DIR)/include/test/test_certs.h +MBEDTLS_FLAGS := -I$(BUILD_DIR)/include -I$(MBEDTLS_PATH)/include \ + -I$(MBEDTLS_PATH)/tests/include \ + $(addprefix -I$(MBEDTLS_PATH)/tf-psa-crypto/,include core \ + drivers/builtin/include) + +# $(call link,flags,libraries) links the C source and objects among the +# prerequisites +link = $(CC) $(1) $(CPPFLAGS) $(CFLAGS) $(SANITIZE_FLAGS) $(WARNFLAGS) \ + -o $@ $(filter %.c %.o,$^) $(LDFLAGS) $(2) + +# Used by programs.sh +export BUILD_DIR WOLFSSL_PATH WOLFSSL_SERVER WOLFSSL_CLIENT MBEDTLS_PATH \ + MBEDTLS_THREADING_C +# With ASAN=1: let a preloaded library, such as faketime's, come first +ASAN_LINK_ORDER := verify_asan_link_order=0 +export ASAN_OPTIONS := $(if $(ASAN_OPTIONS),$(ASAN_OPTIONS):)$(ASAN_LINK_ORDER) -.PHONY: check +.PHONY: test unit programs data-check wolfssl-check FORCE -check: $(TESTS) +test: unit programs + +unit: $(UNIT) | data-check + @fails=0; for t in $(UNIT); do \ + (cd $(DATA) && $(WRAP) $$t) || fails=$$((fails + 1)); \ + done; \ + [ $$fails -eq 0 ] || { echo "$$fails of $(words $(UNIT)) failed"; exit 1; } + +programs: $(CLIENT) $(PROGRAMS) $(WOLFSSL_SERVER) $(WOLFSSL_CLIENT) | \ + data-check + ./programs.sh + +data-check: @if [ ! -f $(DATA)/server5.crt ]; then \ echo "$(DATA) not found, run git submodule update --init" \ "in $(MBEDTLS_PATH)"; \ exit 1; \ fi - @fails=0; for t in $(TESTS); do \ - (cd $(DATA) && $(WRAP) $$t) || fails=$$((fails + 1)); \ - done; \ - [ $$fails -eq 0 ] -$(BUILD_DIR)/%: %.c $(WOLFPSA_LIB) +# 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) + +$(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) +$(CLIENT) $(UNIT) $(PROGRAMS): $(WOLFPSA_LIB) + @mkdir -p $(@D) + $(call link,$(LAYER_FLAGS),$(LAYER_LIBS)) + +$(CERTS_H): + @mkdir -p $(@D) + PYTHONPATH=$(MBEDTLS_PATH)/framework/scripts python3 \ + $(MBEDTLS_PATH)/framework/scripts/generate_test_cert_macros.py \ + --output $@ + +$(CERTS): $(MBEDTLS_PATH)/tests/src/certs.c $(CERTS_H) + $(CC) $(MBEDTLS_FLAGS) $(CPPFLAGS) $(CFLAGS) $(SANITIZE_FLAGS) \ + $(WARNFLAGS) -c -o $@ $< + +# configure refuses a clone that is configured in place. autogen.sh only adds +# files git ignores. +wolfssl-check: + @if [ -f $(WOLFSSL_PATH)/config.status ]; then \ + echo "Run make distclean in $(WOLFSSL_PATH)"; exit 1; \ + fi + +$(WOLFSSL_PATH)/configure: + cd $(@D) && ./autogen.sh + +# Contains WOLFSSL_PATH. Another path starts the build again. +WOLFSSL_STAMP := $(WOLFSSL_BUILD).path +$(WOLFSSL_STAMP): FORCE + @mkdir -p $(@D) + @if [ "$$(cat $@ 2>/dev/null)" != "$(WOLFSSL_PATH)" ]; then \ + rm -rf $(WOLFSSL_BUILD); echo "$(WOLFSSL_PATH)" > $@; \ + fi + +$(WOLFSSL_BUILD)/Makefile: Makefile $(WOLFSSL_STAMP) \ + $(WOLFSSL_PATH)/configure | wolfssl-check @mkdir -p $(@D) - $(CC) $(LAYER_FLAGS) $(CPPFLAGS) $(CFLAGS) $(SANITIZE_FLAGS) \ - $(WARNFLAGS) -o $@ $< \ - $(LDFLAGS) $(LAYER_LIBS) + cd $(@D) && $(WOLFSSL_PATH)/configure CC="$(CC)" $(WOLFSSL_CONFIG) + +# One make builds both, so the library is not built twice at once +$(WOLFSSL_CLIENT): $(WOLFSSL_SERVER) +$(WOLFSSL_SERVER): $(WOLFSSL_BUILD)/Makefile FORCE + $(MAKE) -C $(WOLFSSL_BUILD) examples/server/server examples/client/client + +FORCE: diff --git a/test/mbedtls_compat/client-tls-mbedtls.c b/test/mbedtls_compat/client-tls-mbedtls.c new file mode 100644 index 0000000..45ce4af --- /dev/null +++ b/test/mbedtls_compat/client-tls-mbedtls.c @@ -0,0 +1,185 @@ +/* client-tls-mbedtls.c + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of wolfPSA. + * + * wolfPSA is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * wolfPSA is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +/* Mbed TLS 4.x client built on wolfSSL through the Mbed TLS compatibility + * headers. tls_get() is the code from the Mbed TLS migration guide. Run + * from the wolfSSL root, for its certs. */ + +/* the usual suspects */ +#include +#include +#include + +/* socket includes */ +#include +#include +#include +#include +#include + +/* Mbed TLS, provided by wolfPSA */ +#include +#include +#include +#include + +#define DEFAULT_PORT 11111 + +#define CA_FILE "certs/ca-cert.pem" +/* DNS name in the subjectAltName of certs/server-cert.pem */ +#define HOST_NAME "example.com" + +/* Non-blocking I/O: call again with the same arguments */ +static int tls_want(int ret) +{ + return ret == MBEDTLS_ERR_SSL_WANT_READ || + ret == MBEDTLS_ERR_SSL_WANT_WRITE; +} + +int tls_get(int fd, const char* host, const char* caFile) +{ + int ret; + mbedtls_net_context net; + mbedtls_ssl_context ssl; + mbedtls_ssl_config conf; + mbedtls_x509_crt ca; + unsigned char buf[256]; + const char req[] = "GET / HTTP/1.0\r\n\r\n"; + size_t sent = 0; + + mbedtls_net_init(&net); + net.fd = fd; + mbedtls_ssl_init(&ssl); + mbedtls_ssl_config_init(&conf); + mbedtls_x509_crt_init(&ca); + + ret = (int)psa_crypto_init(); /* 4.x: before any parsing */ + if (ret != PSA_SUCCESS) { + goto out; + } + if ((ret = mbedtls_x509_crt_parse_file(&ca, caFile)) != 0) { + goto out; + } + if ((ret = mbedtls_ssl_config_defaults(&conf, MBEDTLS_SSL_IS_CLIENT, + MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT)) != 0) { + goto out; + } + mbedtls_ssl_conf_ca_chain(&conf, &ca, NULL); + /* 3.6 only: mbedtls_ssl_conf_rng(&conf, mbedtls_ctr_drbg_random, &drbg); */ + + if ((ret = mbedtls_ssl_setup(&ssl, &conf)) != 0 || + (ret = mbedtls_ssl_set_hostname(&ssl, host)) != 0) { + goto out; + } + mbedtls_ssl_set_bio(&ssl, &net, mbedtls_net_send, mbedtls_net_recv, NULL); + + while ((ret = mbedtls_ssl_handshake(&ssl)) != 0) { + if (!tls_want(ret)) { + goto out; + } + } + while (sent < sizeof(req) - 1) { + ret = mbedtls_ssl_write(&ssl, (const unsigned char*)req + sent, + sizeof(req) - 1 - sent); + if (ret > 0) { + sent += (size_t)ret; + } + else if (!tls_want(ret)) { + goto out; + } + } + do { + ret = mbedtls_ssl_read(&ssl, buf, sizeof(buf) - 1); + } while (tls_want(ret) || + ret == MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET); + if (ret > 0) { + ret = 0; + } + mbedtls_ssl_close_notify(&ssl); + +out: + mbedtls_ssl_free(&ssl); + mbedtls_ssl_config_free(&conf); + mbedtls_x509_crt_free(&ca); + return ret; +} + +int main(int argc, char** argv) +{ + int sockfd; + struct sockaddr_in servAddr; + const char* caFile = CA_FILE; + const char* host = HOST_NAME; + int nonBlock = 0; + int opt; + int ret; + + while ((opt = getopt(argc, argv, "A:S:N")) != -1) { + if (opt == 'A') { + caFile = optarg; + } + else if (opt == 'S') { + host = optarg; + } + else if (opt == 'N') { + nonBlock = 1; + } + else { + break; + } + } + if (opt != -1 || optind != argc - 1) { + printf("usage: %s [-A ] [-S ] [-N] " + "\n", argv[0]); + return 1; + } + + memset(&servAddr, 0, sizeof(servAddr)); + servAddr.sin_family = AF_INET; + servAddr.sin_port = htons(DEFAULT_PORT); + if (inet_pton(AF_INET, argv[optind], &servAddr.sin_addr) != 1) { + fprintf(stderr, "ERROR: invalid address\n"); + return 1; + } + + if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { + fprintf(stderr, "ERROR: failed to create the socket\n"); + return 1; + } + if (connect(sockfd, (struct sockaddr*)&servAddr, sizeof(servAddr)) == -1) { + fprintf(stderr, "ERROR: failed to connect\n"); + close(sockfd); + return 1; + } + /* tls_get() retries on MBEDTLS_ERR_SSL_WANT_READ/WANT_WRITE */ + if (nonBlock && + fcntl(sockfd, F_SETFL, fcntl(sockfd, F_GETFL) | O_NONBLOCK) != 0) { + fprintf(stderr, "ERROR: failed to set non-blocking\n"); + close(sockfd); + return 1; + } + + ret = tls_get(sockfd, host, caFile); + printf("tls_get() returned %d\n", ret); + + close(sockfd); + return (ret == 0) ? 0 : 1; +} diff --git a/test/mbedtls_compat/pem_test.c b/test/mbedtls_compat/pem_test.c new file mode 100644 index 0000000..824868a --- /dev/null +++ b/test/mbedtls_compat/pem_test.c @@ -0,0 +1,184 @@ +/* pem_test.c + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of wolfPSA. + * + * wolfPSA is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * wolfPSA is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +/* PEM decoding through the TF-PSA-Crypto 1.x API. The unencrypted cases come + * from TF-PSA-Crypto's tests/suites/test_suite_pem.data. Run from + * framework/data_files in an Mbed TLS checkout. */ + +#include +#include + +#include +#include + +#define CERT_BEGIN "-----BEGIN CERTIFICATE-----" +#define CERT_END "-----END CERTIFICATE-----" +/* Mbed TLS adds MBEDTLS_ERR_BASE64_INVALID_CHARACTER, -0x002C */ +#define BAD_BASE64 (MBEDTLS_ERR_PEM_INVALID_DATA - 0x002C) +/* Larger than the test files */ +#define FILE_SZ 8192 + +static const struct { + const char* name; + const char* data; + int ret; + const char* out; +} cases[] = { + { "valid", "^\nTWJlZCBUTFM=\n$", 0, "Mbed TLS" }, + { "empty content", "^\n\n$", MBEDTLS_ERR_PEM_BAD_INPUT_DATA, NULL }, + { "encrypted", + "^\nProc-Type: 4,ENCRYPTED\nDEK-Info: AES-128-CBC,00\n\nTWJl\n$", + MBEDTLS_ERR_PEM_FEATURE_UNAVAILABLE, NULL }, + { "bad Base64", "^\nTW!lZCBUTFM=\n$", BAD_BASE64, NULL }, + { "no header", "TWJlZCBUTFM=\n$", MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT, + NULL }, + { "no footer", "^\nTWJlZCBUTFM=\n", + MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT, NULL }, + { "footer first", "$\n^\nTWJlZCBUTFM=\n", + MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT, NULL }, + { "data on the header line", "^TWJlZCBUTFM=\n$", + MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT, NULL }, + { "CRLF and a space", "^ \r\nTWJlZCBU\r\nTFM=\r\n$", 0, "Mbed TLS" } +}; + +static long ReadFile(const char* path, unsigned char* buf, size_t sz) +{ + FILE* f = fopen(path, "rb"); + size_t len = 0; + + if (f != NULL) { + len = fread(buf, 1, sz, f); + fclose(f); + } + return (f == NULL || len == sz) ? -1 : (long)len; +} + +/* Two certificates in one buffer: use_len is where the second starts */ +static int TwoCerts(void) +{ + static unsigned char pem[2 * FILE_SZ + 1]; + static unsigned char der[FILE_SZ]; + mbedtls_pem_context ctx; + const unsigned char* out; + size_t outLen = 0; + size_t used = 0; + long pemLen = ReadFile("server5.crt", pem, FILE_SZ); + long derLen = ReadFile("server5.crt.der", der, sizeof(der)); + int ok = pemLen > 0 && derLen > 0; + + mbedtls_pem_init(&ctx); + if (ok) { + memcpy(pem + pemLen, pem, (size_t)pemLen); + pem[2 * pemLen] = '\0'; + ok = mbedtls_pem_read_buffer(&ctx, CERT_BEGIN, CERT_END, pem, NULL, 0, + &used) == 0 && used == (size_t)pemLen; + } + if (ok) { + out = mbedtls_pem_get_buffer(&ctx, &outLen); + ok = outLen == (size_t)derLen && memcmp(out, der, outLen) == 0; + } + /* A second read into the context replaces the first */ + if (ok) { + ok = mbedtls_pem_read_buffer(&ctx, CERT_BEGIN, CERT_END, pem + used, + NULL, 0, &used) == 0 && used == (size_t)pemLen; + } + if (ok) { + out = mbedtls_pem_get_buffer(&ctx, &outLen); + ok = outLen == (size_t)derLen && memcmp(out, der, outLen) == 0; + } + mbedtls_pem_free(&ctx); + return ok; +} + +static int BadInput(void) +{ + mbedtls_pem_context ctx; + size_t used = 0; + + mbedtls_pem_init(&ctx); + return mbedtls_pem_read_buffer(NULL, "^", "$", + (const unsigned char*)"^\nTWJl\n$", NULL, 0, &used) == + MBEDTLS_ERR_PEM_BAD_INPUT_DATA && + mbedtls_pem_read_buffer(&ctx, "^", "$", NULL, NULL, 0, &used) == + MBEDTLS_ERR_PEM_BAD_INPUT_DATA; +} + +static int Case(size_t i) +{ + mbedtls_pem_context ctx; + const unsigned char* out; + size_t outLen = 0; + size_t used = 0; + int ret; + int ok; + + mbedtls_pem_init(&ctx); + ret = mbedtls_pem_read_buffer(&ctx, "^", "$", + (const unsigned char*)cases[i].data, NULL, 0, &used); + ok = ret == cases[i].ret; + if (ok && ret == 0) { + out = mbedtls_pem_get_buffer(&ctx, &outLen); + ok = used == strlen(cases[i].data) && + outLen == strlen(cases[i].out) && + memcmp(out, cases[i].out, outLen) == 0; + } + if (!ok) { + printf("FAIL: %s: returned %d, expected %d\n", cases[i].name, ret, + cases[i].ret); + } + mbedtls_pem_free(&ctx); + return ok; +} + +int main(void) +{ + size_t i; + int fails = 0; + + if (psa_crypto_init() != PSA_SUCCESS) { + printf("FAIL: psa_crypto_init\n"); + return 1; + } + for (i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) { + if (Case(i)) { + printf("PASS: %s\n", cases[i].name); + } + else { + fails++; + } + } + if (TwoCerts()) { + printf("PASS: two certificates\n"); + } + else { + printf("FAIL: two certificates\n"); + fails++; + } + if (BadInput()) { + printf("PASS: bad input\n"); + } + else { + printf("FAIL: bad input\n"); + fails++; + } + mbedtls_psa_crypto_free(); + return (fails == 0) ? 0 : 1; +} diff --git a/test/mbedtls_compat/programs.sh b/test/mbedtls_compat/programs.sh new file mode 100755 index 0000000..dbeb9cc --- /dev/null +++ b/test/mbedtls_compat/programs.sh @@ -0,0 +1,202 @@ +#!/bin/sh + +# Run the Mbed TLS migration guide client, client-tls-mbedtls.c, and Mbed +# TLS's sample programs, built unchanged from MBEDTLS_PATH, against the +# wolfSSL example server, one server per case. A program missing a feature +# 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. + +: "${BUILD_DIR:?}" "${WOLFSSL_PATH:?}" "${WOLFSSL_SERVER:?}" \ + "${WOLFSSL_CLIENT:?}" "${MBEDTLS_PATH:?}" + +DATA=$MBEDTLS_PATH/framework/data_files +READY=$BUILD_DIR/server-ready +FAILS=0 +SKIPS=0 + +if [ ! -f "$DATA/server5.crt" ]; then + echo "$DATA not found, run git submodule update --init in $MBEDTLS_PATH" + exit 1 +fi + +if [ "$MBEDTLS_THREADING_C" != 1 ]; then + echo "SKIP: ssl_pthread_server: MBEDTLS_THREADING_C=1 not set" + SKIPS=$((SKIPS + 1)) +fi + +# The example server and the programs run from the wolfSSL root, for its certs +start_server() { + rm -f "$READY" + (cd "$WOLFSSL_PATH" && exec "$WOLFSSL_SERVER" -R "$READY" $1) \ + >/dev/null 2>&1 & + srv=$! + i=0 + while [ ! -f "$READY" ] && [ $i -lt 50 ]; do + i=$((i + 1)) + sleep 0.1 + done +} + +# The migration guide client, on its port, with certs/server-cert.pem +C=client-tls-mbedtls +LO=127.0.0.1 +TLS13="-p 11111 -d -v 4" +TLS12="-p 11111 -d -v 3" +GOT="tls_get() returned" +P=programs/ssl +# mini_client's built-in CA, test-ca2 from 2013, encodes its name as only the +# older server5 certs do, and wolfSSL compares encoded names +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" +# 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" \ + "$WOLFSSL_PATH/certs/ca-cert.pem" > "$BUNDLE" + +# name|program|arguments|server options|wrapper|expected exit code| +# expected output +while IFS='|' read -r name prog args sopts wrap expect want; do + [ -z "$name" ] && continue + if [ -n "$wrap" ] && ! command -v "${wrap%% *}" >/dev/null; then + echo "SKIP: $name: ${wrap%% *} not found" + SKIPS=$((SKIPS + 1)) + continue + fi + start_server "$sopts" + out=$(cd "$WOLFSSL_PATH" && $wrap $WRAP "$BUILD_DIR/$prog" $args 2>&1) + rc=$? + if [ $rc -eq "$expect" ] && ! echo "$out" | grep -q "not defined" && + echo "$out" | grep -qF -- "$want"; then + echo "PASS: $name" + else + echo "FAIL: $name: exit $rc: $out" + FAILS=$((FAILS + 1)) + fi + kill $srv 2>/dev/null + wait $srv 2>/dev/null +done <"$LOG" 2>&1 & + srv=$! + i=0 + while ! grep -q "Waiting for a remote connection" "$LOG" 2>/dev/null && + [ $i -lt 100 ]; do + i=$((i + 1)) + sleep 0.1 + done +} + +# Options for the wolfSSL example client +run_client() { + "$WOLFSSL_CLIENT" -p 4433 -g -A "$CAS" "$@" +} + +LOG=$BUILD_DIR/server.log +# The server's response contains mbedtls_ssl_get_ciphersuite() +RESPONSE="Successful connection using: TLS" +# The server programs send their certificate and the CAs of certs.c's +# mbedtls_test_cas_pem, and the wolfSSL client checks each of them +CAS=$BUILD_DIR/test-cas.pem +cat "$DATA/test-ca-sha256.crt" "$DATA/test-ca-sha1.crt" \ + "$DATA/test-ca2.crt" > "$CAS" +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" + THREADED="ssl_pthread_server, 5 clients at once|$P/ssl_pthread_server|$FIVE" +fi + +# Prints the output of a client that does not get the expected result. A +# client after ! must fail. +check_client() { + want=0 + c=$1 + case "$c" in + !*) want=1; c=${c#!} ;; + esac + cout=$(cd "$WOLFSSL_PATH" && run_client $c 2>&1) + rc=$? + got=1 + if [ $rc -eq 0 ] && echo "$cout" | grep -qF -- "$RESPONSE"; then + got=0 + fi + if [ $got -ne $want ]; then + printf '\nclient %s: exit %d: %s' "$c" $rc "$cout" + fi +} + +# name|program|clients, separated by ; and run one after another. Clients +# joined by & run at the same time. +while IFS='|' read -r name prog clients; do + [ -z "$name" ] && continue + start_program "$prog" + out= + IFS=';' + for step in $clients; do + IFS='&' + pids= + n=0 + for c in $step; do + unset IFS + check_client "$c" >"$LOG.$n" & + pids="$pids $!" + n=$((n + 1)) + done + wait $pids + for f in "$LOG".*; do + out="$out$(cat "$f")" + done + rm -f "$LOG".* + done + unset IFS + kill $srv 2>/dev/null + wait $srv 2>/dev/null + if [ -z "$out" ]; then + echo "PASS: $name" + else + echo "FAIL: $name:$out +server: $(cat "$LOG")" + FAILS=$((FAILS + 1)) + fi +done < +#include +#include +#include +#include +#ifdef MBEDTLS_THREADING_C + #include +#endif /* MBEDTLS_THREADING_C */ + +#include +#include +#include +#include +#include +#ifdef MBEDTLS_SSL_CACHE_C + #include +#endif /* MBEDTLS_SSL_CACHE_C */ + +#define CA_FILE "test-ca2.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_KEY_FILE "server10.key" +#define ROOT_FILE "test-ca.crt" +/* Self-signed with server5.key, IP address SANs 97.98.99.100 and + * 6162:6364:2E65:7861:6D70:6C65:2E63:6F6D, the bytes of abcd.example.com */ +#define IP_SAN_FILE "server5-tricky-ip-san.crt.der" +/* The CN of server5.crt and server10.crt */ +#define HOST_NAME "localhost" +/* Handshake steps for each side */ +#define MAX_STEPS 20 +/* 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" +/* The most data in one TLS record */ +#define RECORD_SZ 16384 +/* Threads that look up the cipher suites at once */ +#define SUITE_THREADS 8 + +/* Data in one direction. closed is set by the writer. */ +typedef struct { + unsigned char buf[32768]; + size_t len; + int closed; +} Pipe; + +typedef struct { + mbedtls_ssl_config conf; + mbedtls_ssl_context ssl; + Pipe* rx; + Pipe* tx; + /* Returned by each send or receive when set */ + int sendErr; + int recvErr; +} Peer; + +/* The CAs a peer trusts, and the certificates and key a server sends */ +typedef struct { + mbedtls_x509_crt* ca; + mbedtls_x509_crt* own; + mbedtls_pk_context* key; +} Certs; + +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_pk_context leafKey; +static mbedtls_x509_crt ekuSrv; +static mbedtls_x509_crt ipSan; +static const Certs defaultCerts = { &ca, &cert, &key }; +static const Certs ipSanCerts = { &ipSan, &ipSan, &key }; +/* The client trusts the root of the chain the server sends */ +static const Certs chainCerts = { &root, &chain, &leafKey }; +/* The client does not trust it */ +static const Certs untrustedCerts = { &ca, &chain, &leafKey }; +static Pipe toClient; +static Pipe toServer; +static Peer cli; +static Peer srv; + +static int PipeSend(void* ctx, const unsigned char* buf, size_t len) +{ + Pipe* p = ((Peer*)ctx)->tx; + + if (((Peer*)ctx)->sendErr != 0) { + return ((Peer*)ctx)->sendErr; + } + if (len > sizeof(p->buf) - p->len) { + len = sizeof(p->buf) - p->len; + } + if (len == 0) { + return MBEDTLS_ERR_SSL_WANT_WRITE; + } + memcpy(p->buf + p->len, buf, len); + p->len += len; + return (int)len; +} + +static int PipeRecv(void* ctx, unsigned char* buf, size_t len) +{ + Pipe* p = ((Peer*)ctx)->rx; + + if (((Peer*)ctx)->recvErr != 0) { + return ((Peer*)ctx)->recvErr; + } + if (p->len == 0) { + return p->closed ? 0 : MBEDTLS_ERR_SSL_WANT_READ; + } + if (len > p->len) { + len = p->len; + } + memcpy(buf, p->buf, len); + memmove(p->buf, p->buf + len, p->len - len); + p->len -= len; + return (int)len; +} + +static void PeerInit(Peer* p, int endpoint) +{ + 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->sendErr = 0; + p->recvErr = 0; + memset(p->tx, 0, sizeof(*p->tx)); + mbedtls_ssl_set_bio(&p->ssl, p, PipeSend, PipeRecv, NULL); +} + +/* A client sets host, NULL included, unless setHost is 0 */ +static int PeerNewCerts(Peer* p, int endpoint, int authmode, + const Certs* certs, int setHost, const char* host) +{ + int ret; + + PeerInit(p, endpoint); + ret = mbedtls_ssl_config_defaults(&p->conf, endpoint, + MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT); + if (ret == 0) { + mbedtls_ssl_conf_authmode(&p->conf, authmode); + mbedtls_ssl_conf_ca_chain(&p->conf, certs->ca, NULL); + if (endpoint == MBEDTLS_SSL_IS_SERVER) { + ret = mbedtls_ssl_conf_own_cert(&p->conf, certs->own, certs->key); + } + } + if (ret == 0) { + ret = mbedtls_ssl_setup(&p->ssl, &p->conf); + } + if (ret == 0 && setHost) { + ret = mbedtls_ssl_set_hostname(&p->ssl, host); + } + return ret; +} + +static int PeerNew(Peer* p, int endpoint, int authmode, int setHost, + const char* host) +{ + return PeerNewCerts(p, endpoint, authmode, &defaultCerts, setHost, host); +} + +static void PeerFree(Peer* p) +{ + mbedtls_ssl_free(&p->ssl); + mbedtls_ssl_config_free(&p->conf); +} + +static int Waiting(int ret) +{ + return ret == MBEDTLS_ERR_SSL_WANT_READ || + ret == MBEDTLS_ERR_SSL_WANT_WRITE; +} + +/* The client's result. *srvRet gets the server's. */ +static int Handshake(int* srvRet) +{ + int c = MBEDTLS_ERR_SSL_WANT_READ; + int s = MBEDTLS_ERR_SSL_WANT_READ; + int i; + + for (i = 0; i < MAX_STEPS && (Waiting(c) || Waiting(s)); i++) { + if (Waiting(c)) { + c = mbedtls_ssl_handshake(&cli.ssl); + } + if (Waiting(s)) { + s = mbedtls_ssl_handshake(&srv.ssl); + } + } + *srvRet = s; + return c; +} + +/* Connects a client with VERIFY_REQUIRED and HOST_NAME */ +static int Connect(int srvAuthmode) +{ + int s; + + if (PeerNew(&cli, MBEDTLS_SSL_IS_CLIENT, MBEDTLS_SSL_VERIFY_REQUIRED, 1, + HOST_NAME) != 0 || + PeerNew(&srv, MBEDTLS_SSL_IS_SERVER, srvAuthmode, 0, NULL) != 0) { + return -1; + } + return (Handshake(&s) == 0 && s == 0) ? 0 : -1; +} + +static int NoClientCertRequired(void) +{ + int s = 0; + int ok = PeerNew(&cli, MBEDTLS_SSL_IS_CLIENT, MBEDTLS_SSL_VERIFY_REQUIRED, + 1, HOST_NAME) == 0 && + PeerNew(&srv, MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_VERIFY_REQUIRED, 0, + NULL) == 0; + + if (ok) { + (void)Handshake(&s); + ok = s == MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE; + } + PeerFree(&cli); + PeerFree(&srv); + return ok; +} + +/* setHost 0 leaves the host name unset. flags is the client's verify + * result. */ +static int ClientHost(const Certs* certs, int setHost, const char* first, + const char* host, int want, uint32_t flags) +{ + int s; + int ok = PeerNewCerts(&cli, MBEDTLS_SSL_IS_CLIENT, + MBEDTLS_SSL_VERIFY_REQUIRED, certs, setHost, first) == 0 && + PeerNewCerts(&srv, MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_VERIFY_NONE, + certs, 0, NULL) == 0; + + if (ok && setHost) { + ok = mbedtls_ssl_set_hostname(&cli.ssl, host) == 0; + } + if (ok) { + ok = Handshake(&s) == want && + mbedtls_ssl_get_verify_result(&cli.ssl) == flags; + } + PeerFree(&cli); + PeerFree(&srv); + return ok; +} + +static int HostNotSet(void) +{ + return ClientHost(&defaultCerts, 0, NULL, NULL, + MBEDTLS_ERR_SSL_CERTIFICATE_VERIFICATION_WITHOUT_HOSTNAME, + 0xFFFFFFFF); +} + +static int HostCleared(void) +{ + return ClientHost(&defaultCerts, 1, "wrong.example.org", NULL, 0, 0); +} + +static int HostReplaced(void) +{ + return ClientHost(&defaultCerts, 1, "wrong.example.org", HOST_NAME, 0, 0); +} + +/* An IP address replaced by a DNS name, then the other way */ +static int HostKindReplaced(void) +{ + return ClientHost(&defaultCerts, 1, "127.0.0.1", HOST_NAME, 0, 0) && + ClientHost(&ipSanCerts, 1, "wrong.example.org", "97.98.99.100", 0, 0); +} + +static int HostWrong(void) +{ + return ClientHost(&defaultCerts, 1, HOST_NAME, "wrong.example.org", + MBEDTLS_ERR_X509_CERT_VERIFY_FAILED, MBEDTLS_X509_BADCERT_CN_MISMATCH); +} + +/* A name wolfSSL refuses leaves the client without one */ +static int HostRefused(void) +{ + int s; + int ok = PeerNew(&cli, MBEDTLS_SSL_IS_CLIENT, MBEDTLS_SSL_VERIFY_REQUIRED, + 0, NULL) == 0 && + PeerNew(&srv, MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_VERIFY_NONE, 0, + NULL) == 0 && + mbedtls_ssl_set_hostname(&cli.ssl, "router") == + MBEDTLS_ERR_SSL_BAD_INPUT_DATA && + Handshake(&s) == + MBEDTLS_ERR_SSL_CERTIFICATE_VERIFICATION_WITHOUT_HOSTNAME; + + PeerFree(&cli); + PeerFree(&srv); + return ok; +} + +static int PipeHas(const Pipe* p, const char* s) +{ + size_t len = strlen(s); + size_t i; + + for (i = 0; i + len <= p->len; i++) { + if (memcmp(p->buf + i, s, len) == 0) { + return 1; + } + } + return 0; +} + +/* RFC 6066 has no IP addresses in server_name */ +static int ServerNameSent(void) +{ + static const struct { + const char* host; + int sent; + } hosts[] = { + { HOST_NAME, 1 }, + { "97.98.99.100", 0 }, + { "6162:6364:2e65:7861:6d70:6c65:2e63:6f6d", 0 } + }; + size_t i; + int ok = 1; + + for (i = 0; ok && i < sizeof(hosts) / sizeof(hosts[0]); i++) { + ok = PeerNew(&cli, MBEDTLS_SSL_IS_CLIENT, MBEDTLS_SSL_VERIFY_REQUIRED, + 1, hosts[i].host) == 0 && + mbedtls_ssl_handshake(&cli.ssl) == MBEDTLS_ERR_SSL_WANT_READ && + PipeHas(&toServer, hosts[i].host) == hosts[i].sent; + PeerFree(&cli); + } + return ok; +} + +/* The connection is kept, and the name applies from the next session reset */ +static int HostAfterHandshake(void) +{ + unsigned char buf[16]; + int s; + int ok = Connect(MBEDTLS_SSL_VERIFY_NONE) == 0 && + mbedtls_ssl_set_hostname(&cli.ssl, "wrong.example.org") == 0 && + mbedtls_ssl_write(&cli.ssl, (const unsigned char*)"hello", 5) == 5 && + mbedtls_ssl_read(&srv.ssl, buf, sizeof(buf)) == 5 && + mbedtls_ssl_session_reset(&cli.ssl) == 0 && + mbedtls_ssl_session_reset(&srv.ssl) == 0 && + Handshake(&s) == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED; + + PeerFree(&cli); + PeerFree(&srv); + return ok; +} + +/* A client that verifies with the CAs of certs, and a server that sends the + * certificates of certs. flags is the client's verify result. */ +static int ClientVerify(const Certs* certs, const char* host, int want, + uint32_t flags) +{ + int s; + int ok = PeerNewCerts(&cli, MBEDTLS_SSL_IS_CLIENT, + MBEDTLS_SSL_VERIFY_REQUIRED, certs, 1, host) == 0 && + PeerNewCerts(&srv, MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_VERIFY_NONE, + certs, 0, NULL) == 0 && + Handshake(&s) == want && + mbedtls_ssl_get_verify_result(&cli.ssl) == flags; + + PeerFree(&cli); + PeerFree(&srv); + return ok; +} + +static int VerifyChain(void) +{ + return ClientVerify(&chainCerts, HOST_NAME, 0, 0); +} + +/* The handshake ends at the first failed check, the one flag reported */ +static int VerifyUntrusted(void) +{ + return ClientVerify(&untrustedCerts, HOST_NAME, + MBEDTLS_ERR_X509_CERT_VERIFY_FAILED, MBEDTLS_X509_BADCERT_NOT_TRUSTED); +} + +/* IP address host names, matched against the IP address SANs */ +static int IpSan(void) +{ + static const char* const hosts[] = { + "97.98.99.100", + "6162:6364:2e65:7861:6d70:6c65:2e63:6f6d", + "6162:6364:2E65:7861:6D70:6C65:2E63:6F6D" + }; + size_t i; + int ok = 1; + + for (i = 0; ok && i < sizeof(hosts) / sizeof(hosts[0]); i++) { + ok = ClientVerify(&ipSanCerts, hosts[i], 0, 0); + } + return ok; +} + +static int IpSanWrong(void) +{ + static const char* const hosts[] = { + "97.98.99.101", + "::1", + /* An IP address SAN is not a DNS name */ + "abcd.example.com" + }; + size_t i; + int ok = 1; + + for (i = 0; ok && i < sizeof(hosts) / sizeof(hosts[0]); i++) { + ok = ClientVerify(&ipSanCerts, hosts[i], + MBEDTLS_ERR_X509_CERT_VERIFY_FAILED, + MBEDTLS_X509_BADCERT_CN_MISMATCH); + } + return ok; +} + +/* The server's extended key usage only: the server reports the flag */ +static int ClientCertUsage(void) +{ + int s = 0; + int 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) { + (void)Handshake(&s); + ok = s == MBEDTLS_ERR_SSL_BAD_CERTIFICATE && + mbedtls_ssl_get_verify_result(&srv.ssl) == + MBEDTLS_X509_BADCERT_EXT_KEY_USAGE; + } + PeerFree(&cli); + PeerFree(&srv); + return ok; +} + +/* A client that does not verify accepts an untrusted server */ +static int VerifyNone(void) +{ + int s = 0; + int ok = PeerNewCerts(&cli, MBEDTLS_SSL_IS_CLIENT, + MBEDTLS_SSL_VERIFY_NONE, &untrustedCerts, 0, NULL) == 0 && + PeerNewCerts(&srv, MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_VERIFY_NONE, + &untrustedCerts, 0, NULL) == 0 && + Handshake(&s) == 0 && s == 0 && + mbedtls_ssl_get_verify_result(&cli.ssl) == + MBEDTLS_X509_BADCERT_SKIP_VERIFY && + mbedtls_ssl_get_verify_result(&srv.ssl) == + MBEDTLS_X509_BADCERT_SKIP_VERIFY; + + PeerFree(&cli); + PeerFree(&srv); + return ok; +} + +/* As in Mbed TLS, the CAs set before mbedtls_ssl_config_defaults are kept */ +static int CaChainBeforeDefaults(void) +{ + int s = 0; + int ok; + + PeerInit(&cli, MBEDTLS_SSL_IS_CLIENT); + mbedtls_ssl_conf_ca_chain(&cli.conf, &ca, NULL); + ok = mbedtls_ssl_config_defaults(&cli.conf, MBEDTLS_SSL_IS_CLIENT, + MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT) == 0 && + mbedtls_ssl_setup(&cli.ssl, &cli.conf) == 0 && + mbedtls_ssl_set_hostname(&cli.ssl, HOST_NAME) == 0 && + PeerNew(&srv, MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_VERIFY_NONE, 0, + NULL) == 0 && + Handshake(&s) == 0 && s == 0 && + mbedtls_ssl_get_verify_result(&cli.ssl) == 0; + + PeerFree(&cli); + PeerFree(&srv); + return ok; +} + +static int ReadWrite(void) +{ + unsigned char buf[16]; + int ok = Connect(MBEDTLS_SSL_VERIFY_NONE) == 0 && + mbedtls_ssl_write(&cli.ssl, (const unsigned char*)"hello", 5) == 5 && + mbedtls_ssl_read(&srv.ssl, buf, sizeof(buf)) == 5 && + memcmp(buf, "hello", 5) == 0; + + PeerFree(&cli); + PeerFree(&srv); + return ok; +} + +static int WriteZero(void) +{ + int ok = Connect(MBEDTLS_SSL_VERIFY_NONE) == 0 && + mbedtls_ssl_write(&cli.ssl, (const unsigned char*)"", 0) == 0; + + PeerFree(&cli); + PeerFree(&srv); + return ok; +} + +/* The transport ends without close_notify */ +static int ReadEof(void) +{ + unsigned char buf[16]; + int ok = Connect(MBEDTLS_SSL_VERIFY_NONE) == 0; + + if (ok) { + toClient.closed = 1; + ok = mbedtls_ssl_read(&cli.ssl, buf, sizeof(buf)) == 0; + } + PeerFree(&cli); + PeerFree(&srv); + return ok; +} + +static int ReadCloseNotify(void) +{ + unsigned char buf[16]; + int ok = Connect(MBEDTLS_SSL_VERIFY_NONE) == 0 && + mbedtls_ssl_close_notify(&srv.ssl) == 0 && + mbedtls_ssl_read(&cli.ssl, buf, sizeof(buf)) == + MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY; + + PeerFree(&cli); + PeerFree(&srv); + return ok; +} + +/* The client's send or receive fails with err during the handshake. It sends + * before it receives. */ +static int BioErrorHandshake(int send, int err) +{ + int s; + int 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) { + *(send ? &cli.sendErr : &cli.recvErr) = err; + ok = Handshake(&s) == err; + } + PeerFree(&cli); + PeerFree(&srv); + return ok; +} + +/* The BIO's error is returned by the call it fails */ +static int BioErrors(void) +{ + static const struct { + int send; + int err; + } errs[] = { + { 0, MBEDTLS_ERR_SSL_TIMEOUT }, + { 0, MBEDTLS_ERR_NET_CONN_RESET }, + { 0, MBEDTLS_ERR_NET_RECV_FAILED }, + { 1, MBEDTLS_ERR_NET_CONN_RESET }, + { 1, MBEDTLS_ERR_NET_SEND_FAILED } + }; + unsigned char buf[16]; + size_t i; + int ok = 1; + + for (i = 0; ok && i < sizeof(errs) / sizeof(errs[0]); i++) { + ok = BioErrorHandshake(errs[i].send, errs[i].err); + } + if (ok) { + ok = Connect(MBEDTLS_SSL_VERIFY_NONE) == 0; + cli.sendErr = MBEDTLS_ERR_NET_SEND_FAILED; + srv.recvErr = MBEDTLS_ERR_SSL_TIMEOUT; + ok = ok && mbedtls_ssl_write(&cli.ssl, (const unsigned char*)"hello", + 5) == MBEDTLS_ERR_NET_SEND_FAILED && + mbedtls_ssl_read(&srv.ssl, buf, sizeof(buf)) == + MBEDTLS_ERR_SSL_TIMEOUT; + PeerFree(&cli); + PeerFree(&srv); + } + return ok; +} + +/* A length that does not fit in an int. As in Mbed TLS, a write sends at + * most one record, so each write and read uses only RECORD_SZ bytes of buf. + * A sanitizer report here means a write sent more than one record. */ +static int LargeLength(void) +{ + static const size_t lens[] = { + (size_t)INT_MAX + 1, + #if SIZE_MAX > UINT_MAX + (size_t)UINT_MAX + 1, + (size_t)UINT_MAX + 6 + #endif /* SIZE_MAX > UINT_MAX */ + }; + static unsigned char buf[RECORD_SZ]; + size_t i; + int ok = Connect(MBEDTLS_SSL_VERIFY_NONE) == 0; + + for (i = 0; ok && i < sizeof(lens) / sizeof(lens[0]); i++) { + ok = mbedtls_ssl_write(&cli.ssl, buf, lens[i]) == RECORD_SZ && + mbedtls_ssl_read(&srv.ssl, buf, lens[i]) == RECORD_SZ; + } + PeerFree(&cli); + PeerFree(&srv); + return ok; +} + +/* The tests below change the config between mbedtls_ssl_setup and the + * handshake, which Mbed TLS reads the config in */ + +static int ClientCertAfterSetup(void) +{ + int s = 0; + int ok = PeerNew(&cli, MBEDTLS_SSL_IS_CLIENT, MBEDTLS_SSL_VERIFY_REQUIRED, + 1, HOST_NAME) == 0 && + PeerNew(&srv, MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_VERIFY_REQUIRED, 0, + NULL) == 0 && + mbedtls_ssl_conf_own_cert(&cli.conf, &cert, &key) == 0; + + if (ok) { + ok = Handshake(&s) == 0 && s == 0 && + mbedtls_ssl_get_verify_result(&srv.ssl) == 0; + } + PeerFree(&cli); + PeerFree(&srv); + return ok; +} + +/* The client trusts either certificate */ +static int ServerCertReplaced(void) +{ + mbedtls_x509_crt cas; + Certs both = { &cas, NULL, NULL }; + int s = 0; + int ok; + + mbedtls_x509_crt_init(&cas); + ok = mbedtls_x509_crt_parse_file(&cas, CA_FILE) == 0 && + mbedtls_x509_crt_parse_file(&cas, ROOT_FILE) == 0 && + PeerNewCerts(&cli, MBEDTLS_SSL_IS_CLIENT, MBEDTLS_SSL_VERIFY_REQUIRED, + &both, 1, HOST_NAME) == 0 && + PeerNew(&srv, MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_VERIFY_NONE, 0, + NULL) == 0 && + mbedtls_ssl_conf_own_cert(&srv.conf, &chain, &leafKey) == 0; + + if (ok) { + ok = Handshake(&s) == 0 && s == 0; + } + PeerFree(&cli); + PeerFree(&srv); + mbedtls_x509_crt_free(&cas); + return ok; +} + +static int SuitesAfterSetup(void) +{ + static const int suites[] = { SUITE_ID, 0 }; + int s = 0; + int 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_ciphersuites(&cli.conf, suites); + ok = Handshake(&s) == 0 && s == 0 && + mbedtls_ssl_get_ciphersuite_id_from_ssl(&cli.ssl) == SUITE_ID && + strcmp(mbedtls_ssl_get_ciphersuite(&cli.ssl), SUITE_NAME) == 0; + } + PeerFree(&cli); + PeerFree(&srv); + return ok; +} + +static int AuthmodeAfterSetup(void) +{ + int s = 0; + int 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_authmode(&srv.conf, MBEDTLS_SSL_VERIFY_REQUIRED); + (void)Handshake(&s); + ok = s == MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE; + } + PeerFree(&cli); + PeerFree(&srv); + return ok; +} + +/* Ranges other than TLS 1.2, TLS 1.3 or both fail the handshake */ +static int VersionsAfterSetup(void) +{ + static const mbedtls_ssl_protocol_version ranges[][2] = { + { MBEDTLS_SSL_VERSION_TLS1_3, MBEDTLS_SSL_VERSION_TLS1_2 }, + { MBEDTLS_SSL_VERSION_UNKNOWN, MBEDTLS_SSL_VERSION_TLS1_2 }, + { MBEDTLS_SSL_VERSION_UNKNOWN, MBEDTLS_SSL_VERSION_TLS1_3 } + }; + size_t i; + int ok = 1; + + for (i = 0; ok && i < sizeof(ranges) / sizeof(ranges[0]); i++) { + ok = PeerNew(&cli, MBEDTLS_SSL_IS_CLIENT, MBEDTLS_SSL_VERIFY_REQUIRED, + 1, HOST_NAME) == 0; + if (ok) { + mbedtls_ssl_conf_min_tls_version(&cli.conf, ranges[i][0]); + mbedtls_ssl_conf_max_tls_version(&cli.conf, ranges[i][1]); + /* No connection is left to use */ + ok = mbedtls_ssl_handshake(&cli.ssl) == + MBEDTLS_ERR_SSL_BAD_INPUT_DATA && + mbedtls_ssl_close_notify(&cli.ssl) == + MBEDTLS_ERR_SSL_BAD_INPUT_DATA; + } + PeerFree(&cli); + } + return ok; +} + +#define V12 MBEDTLS_SSL_VERSION_TLS1_2 +#define V13 MBEDTLS_SSL_VERSION_TLS1_3 +/* The version negotiated by the client and server ranges, UNKNOWN for none */ +static int VersionRanges(void) +{ + static const struct { + mbedtls_ssl_protocol_version cli[2]; + mbedtls_ssl_protocol_version srv[2]; + mbedtls_ssl_protocol_version want; + } ranges[] = { + { { V12, V13 }, { V12, V13 }, V13 }, + { { V12, V13 }, { V12, V12 }, V12 }, + { { V12, V12 }, { V12, V13 }, V12 }, + { { V13, V13 }, { V12, V13 }, V13 }, + { { V12, V13 }, { V13, V13 }, V13 }, + { { V13, V13 }, { V12, V12 }, MBEDTLS_SSL_VERSION_UNKNOWN }, + { { V12, V12 }, { V13, V13 }, MBEDTLS_SSL_VERSION_UNKNOWN } + }; + size_t i; + int s; + int c; + int ok = 1; + + for (i = 0; ok && i < sizeof(ranges) / sizeof(ranges[0]); i++) { + 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_min_tls_version(&cli.conf, ranges[i].cli[0]); + mbedtls_ssl_conf_max_tls_version(&cli.conf, ranges[i].cli[1]); + mbedtls_ssl_conf_min_tls_version(&srv.conf, ranges[i].srv[0]); + mbedtls_ssl_conf_max_tls_version(&srv.conf, ranges[i].srv[1]); + c = Handshake(&s); + ok = (ranges[i].want == MBEDTLS_SSL_VERSION_UNKNOWN) ? + c != 0 : c == 0 && s == 0 && + mbedtls_ssl_get_version_number(&cli.ssl) == ranges[i].want; + } + PeerFree(&cli); + PeerFree(&srv); + } + return ok; +} +#undef V12 +#undef V13 + +/* VERIFY_NONE needs no host name */ +static int AuthmodeNoneAfterSetup(void) +{ + int s = 0; + int ok = PeerNew(&cli, MBEDTLS_SSL_IS_CLIENT, MBEDTLS_SSL_VERIFY_REQUIRED, + 0, NULL) == 0 && + PeerNew(&srv, MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_VERIFY_NONE, 0, + NULL) == 0; + + if (ok) { + mbedtls_ssl_conf_authmode(&cli.conf, MBEDTLS_SSL_VERIFY_NONE); + ok = Handshake(&s) == 0 && s == 0; + } + PeerFree(&cli); + PeerFree(&srv); + return ok; +} + +/* 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) +{ +#ifdef MBEDTLS_SSL_CACHE_C + mbedtls_ssl_cache_context cache; +#endif /* MBEDTLS_SSL_CACHE_C */ + mbedtls_ssl_session session; + int s = 0; + int ok; + +#ifdef MBEDTLS_SSL_CACHE_C + 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, + 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); +#ifdef MBEDTLS_SSL_CACHE_C + mbedtls_ssl_conf_session_cache(&srv.conf, &cache, + mbedtls_ssl_cache_get, mbedtls_ssl_cache_set); +#endif /* MBEDTLS_SSL_CACHE_C */ + ok = mbedtls_ssl_session_reset(&cli.ssl) == 0 && + mbedtls_ssl_session_reset(&srv.ssl) == 0 && + Handshake(&s) == 0 && s == 0 && + mbedtls_ssl_get_session(&cli.ssl, &session) == 0; + } + if (ok) { + memset(&toClient, 0, sizeof(toClient)); + memset(&toServer, 0, sizeof(toServer)); + ok = mbedtls_ssl_session_reset(&cli.ssl) == 0 && + mbedtls_ssl_session_reset(&srv.ssl) == 0 && + mbedtls_ssl_set_session(&cli.ssl, &session) == 0; + } + if (ok) { + mbedtls_ssl_conf_ca_chain(&cli.conf, &root, NULL); + mbedtls_ssl_conf_authmode(&srv.conf, srvAuthmode); + ok = Handshake(&s) == want && (want != 0 || s == 0) && + mbedtls_ssl_get_verify_result(&cli.ssl) == flags; + } + mbedtls_ssl_session_free(&session); + PeerFree(&cli); + PeerFree(&srv); +#ifdef MBEDTLS_SSL_CACHE_C + mbedtls_ssl_cache_free(&cache); +#endif /* MBEDTLS_SSL_CACHE_C */ + return ok; +} + +static int ResumeRequired(void) +{ + return Resume(MBEDTLS_SSL_VERIFY_NONE, 0, 0); +} + +/* 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); +} + +/* The same endpoint and transport again keep the config */ +static int EndpointSame(void) +{ + int s = 0; + int 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_endpoint(&srv.conf, MBEDTLS_SSL_IS_SERVER); + mbedtls_ssl_conf_transport(&srv.conf, MBEDTLS_SSL_TRANSPORT_STREAM); + ok = mbedtls_ssl_context_get_config(&srv.ssl) == &srv.conf && + mbedtls_ssl_conf_get_endpoint(&srv.conf) == + MBEDTLS_SSL_IS_SERVER && + mbedtls_ssl_conf_get_endpoint(&cli.conf) == + MBEDTLS_SSL_IS_CLIENT && + Handshake(&s) == 0 && s == 0; + } + PeerFree(&cli); + PeerFree(&srv); + return ok; +} + +/* Not read: any CRL is refused */ +static void ConfCrl(mbedtls_ssl_config* conf) +{ + mbedtls_ssl_conf_ca_chain(conf, &ca, (mbedtls_x509_crl*)&ca); +} + +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_conf_authmode(conf, 1); +} + +static void ConfAuthmodeNone(mbedtls_ssl_config* conf) +{ + mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_NONE); +} + +static void ConfEndpoint(mbedtls_ssl_config* conf) +{ + mbedtls_ssl_conf_endpoint(conf, MBEDTLS_SSL_IS_CLIENT); +} + +static void ConfTransport(mbedtls_ssl_config* conf) +{ + mbedtls_ssl_conf_transport(conf, MBEDTLS_SSL_TRANSPORT_DATAGRAM); +} + +/* A conf_* failure after a server's mbedtls_ssl_setup, returned by next as + * err. Then fix, when set, clears it. */ +static int ConfError(void (*fail)(mbedtls_ssl_config*), int err, + int (*next)(mbedtls_ssl_context*), void (*fix)(mbedtls_ssl_config*)) +{ + int ok = PeerNew(&srv, MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_VERIFY_NONE, 0, + NULL) == 0; + + if (ok) { + fail(&srv.conf); + ok = next(&srv.ssl) == err; + } + if (ok && fix != NULL) { + fix(&srv.conf); + ok = next(&srv.ssl) == 0; + } + PeerFree(&srv); + return ok; +} + +/* A CRL set before mbedtls_ssl_config_defaults is refused too */ +static int CrlBeforeDefaults(void) +{ + int ok; + + PeerInit(&srv, MBEDTLS_SSL_IS_SERVER); + ConfCrl(&srv.conf); + ok = mbedtls_ssl_config_defaults(&srv.conf, MBEDTLS_SSL_IS_SERVER, + MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT) == 0 && + mbedtls_ssl_conf_own_cert(&srv.conf, &cert, &key) == 0 && + mbedtls_ssl_setup(&srv.ssl, &srv.conf) == + MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; + PeerFree(&srv); + return ok; +} + +static int ResetConfError(void) +{ + return ConfError(ConfCrl, MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE, + mbedtls_ssl_session_reset, NULL); +} + +static int HandshakeConfError(void) +{ + return ConfError(ConfCrl, MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE, + mbedtls_ssl_handshake, NULL); +} + +static int CrlCleared(void) +{ + return ConfError(ConfCrl, MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE, + mbedtls_ssl_session_reset, ConfCa); +} + +static int AuthmodeCleared(void) +{ + return ConfError(ConfAuthmodeOptional, MBEDTLS_ERR_SSL_BAD_INPUT_DATA, + mbedtls_ssl_session_reset, ConfAuthmodeNone); +} + +static int EndpointChanged(void) +{ + return ConfError(ConfEndpoint, MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE, + mbedtls_ssl_handshake, NULL); +} + +static int TransportChanged(void) +{ + return ConfError(ConfTransport, MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE, + mbedtls_ssl_handshake, NULL); +} + +/* wolfSSL makes no server connection without a certificate and key */ +static int ServerNoCert(void) +{ + int ok; + + PeerInit(&srv, MBEDTLS_SSL_IS_SERVER); + ok = mbedtls_ssl_close_notify(&srv.ssl) == + MBEDTLS_ERR_SSL_BAD_INPUT_DATA && + mbedtls_ssl_config_defaults(&srv.conf, MBEDTLS_SSL_IS_SERVER, + MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT) == 0 && + mbedtls_ssl_setup(&srv.ssl, &srv.conf) == MBEDTLS_ERR_SSL_BAD_CONFIG && + mbedtls_ssl_close_notify(&srv.ssl) == MBEDTLS_ERR_SSL_BAD_INPUT_DATA; + PeerFree(&srv); + return ok; +} + +/* wolfSSL's own code for a key it refuses is not returned. Setup fails until + * a certificate and key load. */ +static int OwnKeyTooSmall(void) +{ + mbedtls_pk_context small; + int ok; + + mbedtls_pk_init(&small); + PeerInit(&srv, MBEDTLS_SSL_IS_SERVER); + ok = mbedtls_pk_parse_keyfile(&small, "rsa_pkcs1_768_clear.der", + NULL) == 0 && + mbedtls_ssl_config_defaults(&srv.conf, MBEDTLS_SSL_IS_SERVER, + MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT) == 0 && + mbedtls_ssl_conf_own_cert(&srv.conf, &cert, &small) == + MBEDTLS_ERR_SSL_BAD_INPUT_DATA && + mbedtls_ssl_setup(&srv.ssl, &srv.conf) == + MBEDTLS_ERR_SSL_BAD_INPUT_DATA && + mbedtls_ssl_conf_own_cert(&srv.conf, &cert, &key) == 0 && + mbedtls_ssl_setup(&srv.ssl, &srv.conf) == 0; + PeerFree(&srv); + mbedtls_pk_free(&small); + return ok; +} + +#ifdef MBEDTLS_THREADING_C +typedef struct { + int nameFirst; + size_t count; + const char* name; +} SuiteLookup; + +static void* SuiteThread(void* arg) +{ + SuiteLookup* l = (SuiteLookup*)arg; + const int* ids; + + if (l->nameFirst) { + l->name = mbedtls_ssl_get_ciphersuite_name(SUITE_ID); + } + ids = mbedtls_ssl_list_ciphersuites(); + if (!l->nameFirst) { + l->name = mbedtls_ssl_get_ciphersuite_name(SUITE_ID); + } + while (ids[l->count] != 0) { + l->count++; + } + return NULL; +} + +/* Threads that make the first lookups at once each see the whole list */ +static int SuitesThreads(void) +{ + pthread_t threads[SUITE_THREADS]; + SuiteLookup l[SUITE_THREADS]; + int started; + int i; + int ok = 1; + + memset(l, 0, sizeof(l)); + for (started = 0; started < SUITE_THREADS; started++) { + l[started].nameFirst = started % 2; + if (pthread_create(&threads[started], NULL, SuiteThread, + &l[started]) != 0) { + ok = 0; + break; + } + } + for (i = 0; i < started; i++) { + (void)pthread_join(threads[i], NULL); + } + for (i = 0; ok && i < SUITE_THREADS; i++) { + ok = l[i].count > 0 && l[i].count == l[0].count && + strcmp(l[i].name, SUITE_NAME) == 0; + } + return ok; +} +#endif /* MBEDTLS_THREADING_C */ + +static int AcceptWouldBlock(void) +{ + mbedtls_net_context bound; + mbedtls_net_context client; + int ok; + + mbedtls_net_init(&bound); + mbedtls_net_init(&client); + ok = mbedtls_net_bind(&bound, "127.0.0.1", "0", + MBEDTLS_NET_PROTO_TCP) == 0 && + fcntl(bound.fd, F_SETFL, fcntl(bound.fd, F_GETFL) | O_NONBLOCK) == + 0 && + mbedtls_net_accept(&bound, &client, NULL, 0, NULL) == + MBEDTLS_ERR_SSL_WANT_READ; + mbedtls_net_free(&client); + mbedtls_net_free(&bound); + return ok; +} + +/* Each listed suite's name gives back its ID */ +static int SuiteIdFromName(void) +{ + const int* ids = mbedtls_ssl_list_ciphersuites(); + int ok = ids[0] != 0 && + mbedtls_ssl_get_ciphersuite_id(SUITE_NAME) == SUITE_ID && + mbedtls_ssl_get_ciphersuite_id("TLS-NO-SUCH-SUITE") == 0 && + mbedtls_ssl_get_ciphersuite_id(NULL) == 0; + size_t i; + + for (i = 0; ok && ids[i] != 0; i++) { + ok = mbedtls_ssl_get_ciphersuite_id( + mbedtls_ssl_get_ciphersuite_name(ids[i])) == ids[i]; + } + return ok; +} + +static int HandshakeOver(void) +{ + int s = 0; + int ok = !mbedtls_ssl_is_handshake_over(NULL) && + 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 && + !mbedtls_ssl_is_handshake_over(&cli.ssl) && + !mbedtls_ssl_is_handshake_over(&srv.ssl) && + Handshake(&s) == 0 && s == 0 && + mbedtls_ssl_is_handshake_over(&cli.ssl) && + mbedtls_ssl_is_handshake_over(&srv.ssl); + + PeerFree(&cli); + PeerFree(&srv); + return ok; +} + +/* Zero after init, kept through a session reset */ +static int UserData(void) +{ + int x = 0; + int ok = PeerNew(&cli, MBEDTLS_SSL_IS_CLIENT, MBEDTLS_SSL_VERIFY_REQUIRED, + 1, HOST_NAME) == 0 && + mbedtls_ssl_conf_get_user_data_p(&cli.conf) == NULL && + mbedtls_ssl_get_user_data_n(&cli.ssl) == 0; + + if (ok) { + mbedtls_ssl_conf_set_user_data_n(&cli.conf, 42); + mbedtls_ssl_set_user_data_p(&cli.ssl, &x); + ok = mbedtls_ssl_session_reset(&cli.ssl) == 0 && + mbedtls_ssl_conf_get_user_data_n(&cli.conf) == 42 && + mbedtls_ssl_get_user_data_p(&cli.ssl) == &x; + } + if (ok) { + mbedtls_ssl_conf_set_user_data_p(&cli.conf, &x); + mbedtls_ssl_set_user_data_n(&cli.ssl, 7); + ok = mbedtls_ssl_conf_get_user_data_p(&cli.conf) == &x && + mbedtls_ssl_get_user_data_n(&cli.ssl) == 7; + } + PeerFree(&cli); + return ok; +} + +static const struct { + const char* name; + int (*test)(void); +} cases[] = { +#ifdef MBEDTLS_THREADING_C + /* First: the list is made on the first lookup */ + { "cipher suite lookups, threads at once", SuitesThreads }, +#endif /* MBEDTLS_THREADING_C */ + { "no client certificate, REQUIRED", NoClientCertRequired }, + { "host name not set", HostNotSet }, + { "host name cleared", HostCleared }, + { "host name replaced", HostReplaced }, + { "IP address and DNS name replaced", HostKindReplaced }, + { "wrong host name", HostWrong }, + { "host name refused", HostRefused }, + { "server name, not an IP address", ServerNameSent }, + { "host name set after the handshake", HostAfterHandshake }, + { "chain with intermediate CAs", VerifyChain }, + { "untrusted chain", VerifyUntrusted }, + { "IP address SANs", IpSan }, + { "wrong IP address or DNS name", IpSanWrong }, + { "client certificate for servers only", ClientCertUsage }, + { "VERIFY_NONE", VerifyNone }, + { "CA list set before config_defaults", CaChainBeforeDefaults }, + { "write and read", ReadWrite }, + { "zero-length write", WriteZero }, + { "EOF without close_notify", ReadEof }, + { "close_notify", ReadCloseNotify }, + { "BIO errors", BioErrors }, + { "length over INT_MAX", LargeLength }, + { "client certificate set after setup", ClientCertAfterSetup }, + { "server certificate replaced after setup", ServerCertReplaced }, + { "cipher suites set after setup", SuitesAfterSetup }, + { "authmode set after setup", AuthmodeAfterSetup }, + { "bad version range set after setup", VersionsAfterSetup }, + { "version ranges", VersionRanges }, + { "VERIFY_NONE set after setup, no host name", AuthmodeNoneAfterSetup }, + { "session resumed, REQUIRED", ResumeRequired }, + { "session without a client certificate, server REQUIRED", + ResumeServerRequired }, + { "same endpoint and transport set again", EndpointSame }, + { "session reset after a conf error", ResetConfError }, + { "handshake after a conf error", HandshakeConfError }, + { "CRL error cleared by a new CA list", CrlCleared }, + { "authmode error cleared by a new authmode", AuthmodeCleared }, + { "server without a certificate", ServerNoCert }, + { "CRL set before config_defaults", CrlBeforeDefaults }, + { "endpoint changed after config_defaults", EndpointChanged }, + { "transport changed after config_defaults", TransportChanged }, + { "own key too small", OwnKeyTooSmall }, + { "accept would block", AcceptWouldBlock }, + { "cipher suite ID from its name", SuiteIdFromName }, + { "handshake over", HandshakeOver }, + { "user data kept through session reset", UserData } +}; + +int main(void) +{ + size_t i; + int fails = 0; + + mbedtls_x509_crt_init(&ca); + mbedtls_x509_crt_init(&cert); + mbedtls_pk_init(&key); + mbedtls_x509_crt_init(&root); + mbedtls_x509_crt_init(&chain); + mbedtls_pk_init(&leafKey); + mbedtls_x509_crt_init(&ekuSrv); + mbedtls_x509_crt_init(&ipSan); + if (psa_crypto_init() != PSA_SUCCESS || + mbedtls_x509_crt_parse_file(&ca, CA_FILE) != 0 || + mbedtls_x509_crt_parse_file(&cert, CERT_FILE) != 0 || + 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_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) { + printf("FAIL: loading the certificates and keys\n"); + return 1; + } + for (i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) { + if (cases[i].test()) { + printf("PASS: %s\n", cases[i].name); + } + else { + printf("FAIL: %s\n", cases[i].name); + fails++; + } + } + mbedtls_x509_crt_free(&ipSan); + mbedtls_x509_crt_free(&ekuSrv); + mbedtls_pk_free(&leafKey); + mbedtls_x509_crt_free(&chain); + mbedtls_x509_crt_free(&root); + mbedtls_pk_free(&key); + mbedtls_x509_crt_free(&cert); + mbedtls_x509_crt_free(&ca); + mbedtls_psa_crypto_free(); + return (fails == 0) ? 0 : 1; +} diff --git a/test/psa_server/psa_track_memory_test.c b/test/psa_server/psa_track_memory_test.c index f040fc5..1d603fe 100644 --- a/test/psa_server/psa_track_memory_test.c +++ b/test/psa_server/psa_track_memory_test.c @@ -28,6 +28,12 @@ #include #include #include +#ifdef MBEDTLS_PEM_PARSE_C + #include +#endif /* MBEDTLS_PEM_PARSE_C */ +#ifdef MBEDTLS_SSL_TLS_C + #include +#endif /* MBEDTLS_SSL_TLS_C */ #include #include @@ -37,6 +43,9 @@ static int failures; static const uint8_t msg[] = "abc"; +#ifdef MBEDTLS_PEM_PARSE_C +static const unsigned char pem_abc[] = "^\nYWJj\n$"; +#endif /* MBEDTLS_PEM_PARSE_C */ static const uint8_t sha256_abc[] = { 0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea, 0x41, 0x41, 0x40, 0xde, 0x5d, 0xae, 0x22, 0x23, @@ -74,6 +83,45 @@ static void check_bytes(const char *what, const uint8_t *got, size_t got_len, } } +#ifdef MBEDTLS_PEM_PARSE_C +static void test_pem(int want, const char *what) +{ + mbedtls_pem_context pem; + size_t used = 0; + + mbedtls_pem_init(&pem); + check(what, mbedtls_pem_read_buffer(&pem, "^", "$", pem_abc, NULL, 0, + &used), want); + mbedtls_pem_free(&pem); +} +#endif /* MBEDTLS_PEM_PARSE_C */ + +#ifdef MBEDTLS_SSL_TLS_C +/* The calls that allocate what the config or context keeps */ +static void test_ssl(int want, const char *when) +{ + mbedtls_ssl_config conf; + mbedtls_ssl_context ssl; + const int *ids = mbedtls_ssl_list_ciphersuites(); + char what[64]; + + mbedtls_ssl_config_init(&conf); + mbedtls_ssl_init(&ssl); + snprintf(what, sizeof(what), "mbedtls_ssl_config_defaults %s", when); + check(what, mbedtls_ssl_config_defaults(&conf, MBEDTLS_SSL_IS_CLIENT, + MBEDTLS_SSL_TRANSPORT_STREAM, + MBEDTLS_SSL_PRESET_DEFAULT), want); + snprintf(what, sizeof(what), "mbedtls_ssl_set_hostname %s", when); + check(what, mbedtls_ssl_set_hostname(&ssl, "localhost"), want); + /* Allocates nothing, so works before init too, as in Mbed TLS */ + snprintf(what, sizeof(what), "mbedtls_ssl_list_ciphersuites %s", when); + check(what, ids[0] != 0 && mbedtls_ssl_get_ciphersuite_id( + mbedtls_ssl_get_ciphersuite_name(ids[0])) == ids[0], 1); + mbedtls_ssl_free(&ssl); + mbedtls_ssl_config_free(&conf); +} +#endif /* MBEDTLS_SSL_TLS_C */ + static void test_before_init(void) { psa_hash_operation_t op = PSA_HASH_OPERATION_INIT; @@ -127,6 +175,12 @@ static void test_before_init(void) #endif /* MBEDTLS_FS_IO */ mbedtls_x509_crt_free(&crt); #endif /* MBEDTLS_X509_CRT_PARSE_C */ +#ifdef MBEDTLS_PEM_PARSE_C + test_pem(PSA_ERROR_BAD_STATE, "mbedtls_pem_read_buffer before init"); +#endif /* MBEDTLS_PEM_PARSE_C */ +#ifdef MBEDTLS_SSL_TLS_C + test_ssl(PSA_ERROR_BAD_STATE, "before init"); +#endif /* MBEDTLS_SSL_TLS_C */ (void)psa_hash_abort(&op); (void)psa_xof_abort(&xof); @@ -208,6 +262,12 @@ static void test_after_init(void) PSA_SUCCESS); mbedtls_x509_crt_free(&crt); #endif /* MBEDTLS_X509_CRT_PARSE_C */ +#ifdef MBEDTLS_PEM_PARSE_C + test_pem(0, "mbedtls_pem_read_buffer after init"); +#endif /* MBEDTLS_PEM_PARSE_C */ +#ifdef MBEDTLS_SSL_TLS_C + test_ssl(0, "after init"); +#endif /* MBEDTLS_SSL_TLS_C */ } /* Leaks, and frees of memory the tracker did not allocate, unbalance it */ @@ -225,6 +285,25 @@ static void check_tracker(const memoryStats *stats) } } +/* wolfCrypt_Init() restarts the tracker only when nothing kept a reference + * after mbedtls_psa_crypto_free() */ +static void check_released(const memoryStats *stats) +{ + long allocs; + + if (stats == NULL) { + return; + } + allocs = stats->totalAllocs; + check("psa_crypto_init again", psa_crypto_init(), PSA_SUCCESS); + if (stats->totalAllocs >= allocs) { + printf("FAIL: wolfCrypt not released by mbedtls_psa_crypto_free\n"); + failures++; + } + mbedtls_psa_crypto_free(); + check_tracker(stats); +} + int main(void) { const memoryStats *stats; @@ -236,6 +315,7 @@ int main(void) test_after_init(); mbedtls_psa_crypto_free(); check_tracker(stats); + check_released(stats); if (failures != 0) { printf("PSA track memory test: %d failure(s)\n", failures); diff --git a/tools/psa_want_probe.c b/tools/psa_want_probe.c index 7f8bf1e..a1abfbe 100644 --- a/tools/psa_want_probe.c +++ b/tools/psa_want_probe.c @@ -269,6 +269,30 @@ __WPSA_EMIT__MBEDTLS_CTR_DRBG_C #endif /* ----- Mbed TLS options, MBEDTLS_COMPAT=1 ----- */ +#if defined(WOLFPSA_MBEDTLS_COMPAT) && !defined(NO_CODING) && \ + defined(WOLFSSL_BASE64_DECODE) +__WPSA_EMIT__MBEDTLS_PEM_PARSE_C +#endif #if defined(WOLFPSA_MBEDTLS_COMPAT) && !defined(NO_ASN) && !defined(NO_CERTS) __WPSA_EMIT__MBEDTLS_X509_CRT_PARSE_C +#if !defined(WOLFCRYPT_ONLY) && defined(HAVE_SNI) +/* USE_WOLFSSL_IO, when wolfSSL has socket I/O */ +#include +#if defined(USE_WOLFSSL_IO) +__WPSA_EMIT__MBEDTLS_NET_C +#endif +__WPSA_EMIT__MBEDTLS_SSL_TLS_C +#if !defined(NO_WOLFSSL_CLIENT) +__WPSA_EMIT__MBEDTLS_SSL_CLI_C +#endif +#if !defined(NO_WOLFSSL_SERVER) +__WPSA_EMIT__MBEDTLS_SSL_SRV_C +#endif +#if !defined(WOLFSSL_NO_TLS12) +__WPSA_EMIT__MBEDTLS_SSL_PROTO_TLS1_2 +#endif +#if defined(WOLFSSL_TLS13) +__WPSA_EMIT__MBEDTLS_SSL_PROTO_TLS1_3 +#endif +#endif #endif diff --git a/user_settings.h b/user_settings.h index a7e5226..a6c89d7 100644 --- a/user_settings.h +++ b/user_settings.h @@ -34,7 +34,9 @@ #include_next "user_settings.h" #else +#ifndef WOLFPSA_MBEDTLS_COMPAT #define WOLFCRYPT_ONLY +#endif /* !WOLFPSA_MBEDTLS_COMPAT */ /* MBEDTLS_THREADING_C: thread safe, see src/psa_lock.h */ #if defined(MBEDTLS_THREADING_C) && !defined(WOLFPSA_THREAD_SAFE) #define WOLFPSA_THREAD_SAFE @@ -140,6 +142,23 @@ #ifdef WOLFPSA_MBEDTLS_COMPAT /* Mbed TLS accepts NULL parameters after an ECDSA signature OID */ #define WOLFSSL_ECC_SIGALG_PARAMS_NULL_ALLOWED +/* wolfSSL TLS, with configure's TLS defaults. NO_DH: wolfPSA builds no + * dh.c. */ +#define HAVE_TLS_EXTENSIONS +#define HAVE_SNI +#define HAVE_SUPPORTED_CURVES +#define HAVE_EXTENDED_MASTER +#define HAVE_ENCRYPT_THEN_MAC +#define HAVE_SERVER_RENEGOTIATION_INFO +#define WOLFSSL_TLS13 +#define NO_OLD_TLS +#define NO_DES3_TLS_SUITES +#define NO_PSK +#define NO_DH +/* mbedtls_ssl_conf_ciphersuites() takes cipher suite IDs */ +#define WOLFSSL_SET_CIPHER_BYTES +/* An IP address host name is checked against the certificate's IP SANs */ +#define WOLFSSL_IP_ALT_NAME #endif /* WOLFPSA_MBEDTLS_COMPAT */ #endif /* __ZEPHYR__ */ diff --git a/wolfpsa.map b/wolfpsa.map index 2b840c4..1922648 100644 --- a/wolfpsa.map +++ b/wolfpsa.map @@ -140,6 +140,9 @@ WOLFPSA_1.0 { wolfPSA_SetDefaultDevID; wolfPSA_GetDefaultDevID; /* Mbed TLS compatibility layer, MBEDTLS_COMPAT=1 */ + mbedtls_net_*; + mbedtls_pem_*; + mbedtls_ssl_*; mbedtls_x509_*; /* The wolfCrypt objects a devId selects live inside this library, * so a shared-library user has to register the device against this diff --git a/wolfpsa/mbedtls_compat/mbedtls/debug.h b/wolfpsa/mbedtls_compat/mbedtls/debug.h new file mode 100644 index 0000000..eaa0c28 --- /dev/null +++ b/wolfpsa/mbedtls_compat/mbedtls/debug.h @@ -0,0 +1,29 @@ +/* debug.h + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of wolfPSA. + * + * wolfPSA is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * wolfPSA is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +/* MBEDTLS_DEBUG_C is not defined; mbedtls_ssl_conf_dbg is in ssl.h. */ + +#ifndef MBEDTLS_DEBUG_H +#define MBEDTLS_DEBUG_H + +#include "mbedtls/ssl.h" + +#endif /* MBEDTLS_DEBUG_H */ diff --git a/wolfpsa/mbedtls_compat/mbedtls/error.h b/wolfpsa/mbedtls_compat/mbedtls/error.h new file mode 100644 index 0000000..b1f33ba --- /dev/null +++ b/wolfpsa/mbedtls_compat/mbedtls/error.h @@ -0,0 +1,29 @@ +/* error.h + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of wolfPSA. + * + * wolfPSA is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * wolfPSA is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +/* No mbedtls_strerror() yet. */ + +#ifndef MBEDTLS_ERROR_H +#define MBEDTLS_ERROR_H + +#include "mbedtls/build_info.h" + +#endif /* MBEDTLS_ERROR_H */ diff --git a/wolfpsa/mbedtls_compat/mbedtls/net_sockets.h b/wolfpsa/mbedtls_compat/mbedtls/net_sockets.h new file mode 100644 index 0000000..b4131ea --- /dev/null +++ b/wolfpsa/mbedtls_compat/mbedtls/net_sockets.h @@ -0,0 +1,72 @@ +/* net_sockets.h + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of wolfPSA. + * + * wolfPSA is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * wolfPSA is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +#ifndef MBEDTLS_NET_SOCKETS_H +#define MBEDTLS_NET_SOCKETS_H + +#include "mbedtls/ssl.h" + +#include + +#ifdef __cplusplus + extern "C" { +#endif /* __cplusplus */ + +#define MBEDTLS_NET_PROTO_TCP 0 +#define MBEDTLS_NET_PROTO_UDP 1 + +#define MBEDTLS_ERR_NET_SOCKET_FAILED -0x0042 +#define MBEDTLS_ERR_NET_CONNECT_FAILED -0x0044 +#define MBEDTLS_ERR_NET_INVALID_CONTEXT -0x0045 +#define MBEDTLS_ERR_NET_BIND_FAILED -0x0046 +#define MBEDTLS_ERR_NET_LISTEN_FAILED -0x0048 +#define MBEDTLS_ERR_NET_ACCEPT_FAILED -0x004A +#define MBEDTLS_ERR_NET_RECV_FAILED -0x004C +#define MBEDTLS_ERR_NET_SEND_FAILED -0x004E +#define MBEDTLS_ERR_NET_CONN_RESET -0x0050 +#define MBEDTLS_ERR_NET_UNKNOWN_HOST -0x0052 +#define MBEDTLS_ERR_NET_BUFFER_TOO_SMALL PSA_ERROR_BUFFER_TOO_SMALL + +#define MBEDTLS_NET_LISTEN_BACKLOG 10 + +typedef struct mbedtls_net_context { + int fd; +} mbedtls_net_context; + +void mbedtls_net_init(mbedtls_net_context* ctx); +int mbedtls_net_connect(mbedtls_net_context* ctx, const char* host, + const char* port, int proto); +int mbedtls_net_bind(mbedtls_net_context* ctx, const char* bind_ip, + const char* port, int proto); +int mbedtls_net_accept(mbedtls_net_context* bind_ctx, + mbedtls_net_context* client_ctx, void* client_ip, size_t buf_size, + size_t* cip_len); +void mbedtls_net_usleep(unsigned long usec); +void mbedtls_net_close(mbedtls_net_context* ctx); +void mbedtls_net_free(mbedtls_net_context* ctx); +int mbedtls_net_recv(void* ctx, unsigned char* buf, size_t len); +int mbedtls_net_send(void* ctx, const unsigned char* buf, size_t len); + +#ifdef __cplusplus + } /* extern "C" */ +#endif /* __cplusplus */ + +#endif /* MBEDTLS_NET_SOCKETS_H */ diff --git a/wolfpsa/mbedtls_compat/mbedtls/pem.h b/wolfpsa/mbedtls_compat/mbedtls/pem.h new file mode 100644 index 0000000..8c787d8 --- /dev/null +++ b/wolfpsa/mbedtls_compat/mbedtls/pem.h @@ -0,0 +1,70 @@ +/* pem.h + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of wolfPSA. + * + * wolfPSA is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * wolfPSA is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +/* PEM decoding, without encrypted PEM. No MBEDTLS_PEM_WRITE_C yet. */ + +#ifndef MBEDTLS_PEM_H +#define MBEDTLS_PEM_H + +#include "tf-psa-crypto/build_info.h" +#include "psa/crypto.h" + +#include + +#ifdef __cplusplus + extern "C" { +#endif /* __cplusplus */ + +#define MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT -0x1080 +#define MBEDTLS_ERR_PEM_INVALID_DATA -0x1100 +#define MBEDTLS_ERR_PEM_INVALID_ENC_IV -0x1200 +#define MBEDTLS_ERR_PEM_UNKNOWN_ENC_ALG -0x1280 +#define MBEDTLS_ERR_PEM_PASSWORD_REQUIRED -0x1300 +#define MBEDTLS_ERR_PEM_PASSWORD_MISMATCH -0x1380 +#define MBEDTLS_ERR_PEM_FEATURE_UNAVAILABLE -0x1400 +#define MBEDTLS_ERR_PEM_BAD_INPUT_DATA PSA_ERROR_INVALID_ARGUMENT +#define MBEDTLS_ERR_PEM_ALLOC_FAILED PSA_ERROR_INSUFFICIENT_MEMORY + +#if defined(MBEDTLS_PEM_PARSE_C) +typedef struct mbedtls_pem_context { + unsigned char* buf; /* the decoded data */ + size_t buflen; +} mbedtls_pem_context; + +void mbedtls_pem_init(mbedtls_pem_context* ctx); +int mbedtls_pem_read_buffer(mbedtls_pem_context* ctx, const char* header, + const char* footer, const unsigned char* data, const unsigned char* pwd, + size_t pwdlen, size_t* use_len); +void mbedtls_pem_free(mbedtls_pem_context* ctx); + +static inline const unsigned char* mbedtls_pem_get_buffer( + mbedtls_pem_context* ctx, size_t* buflen) +{ + *buflen = ctx->buflen; + return ctx->buf; +} +#endif /* MBEDTLS_PEM_PARSE_C */ + +#ifdef __cplusplus + } /* extern "C" */ +#endif /* __cplusplus */ + +#endif /* MBEDTLS_PEM_H */ diff --git a/wolfpsa/mbedtls_compat/mbedtls/psa_util.h b/wolfpsa/mbedtls_compat/mbedtls/psa_util.h new file mode 100644 index 0000000..f30228a --- /dev/null +++ b/wolfpsa/mbedtls_compat/mbedtls/psa_util.h @@ -0,0 +1,30 @@ +/* psa_util.h + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of wolfPSA. + * + * wolfPSA is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * wolfPSA is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +/* No mbedtls_psa_get_random() or ECDSA signature conversion yet. */ + +#ifndef MBEDTLS_PSA_UTIL_H +#define MBEDTLS_PSA_UTIL_H + +#include "tf-psa-crypto/build_info.h" +#include "psa/crypto.h" + +#endif /* MBEDTLS_PSA_UTIL_H */ diff --git a/wolfpsa/mbedtls_compat/mbedtls/ssl.h b/wolfpsa/mbedtls_compat/mbedtls/ssl.h new file mode 100644 index 0000000..102ca38 --- /dev/null +++ b/wolfpsa/mbedtls_compat/mbedtls/ssl.h @@ -0,0 +1,239 @@ +/* ssl.h + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of wolfPSA. + * + * wolfPSA is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * wolfPSA is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +#ifndef MBEDTLS_SSL_H +#define MBEDTLS_SSL_H + +#include "mbedtls/build_info.h" +#include "mbedtls/ssl_ciphersuites.h" +#include "mbedtls/x509_crt.h" +/* From wolfPSA, as Mbed TLS takes it from TF-PSA-Crypto */ +#include "psa/crypto.h" +/* Mbed TLS includes it through ssl_cache.h, on by default there */ +#include "mbedtls/threading.h" + +#include +#include + +#ifdef __cplusplus + extern "C" { +#endif /* __cplusplus */ + +#define MBEDTLS_SSL_IS_CLIENT 0 +#define MBEDTLS_SSL_IS_SERVER 1 +#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_REQUIRED 2 +#define MBEDTLS_SSL_MAX_HOST_NAME_LEN 255 + +#define MBEDTLS_ERR_SSL_CERTIFICATE_VERIFICATION_WITHOUT_HOSTNAME -0x5D80 +#define MBEDTLS_ERR_SSL_BAD_CONFIG -0x5E80 +#define MBEDTLS_ERR_SSL_TIMEOUT -0x6800 +#define MBEDTLS_ERR_SSL_WANT_WRITE -0x6880 +#define MBEDTLS_ERR_SSL_WANT_READ -0x6900 +#define MBEDTLS_ERR_SSL_INTERNAL_ERROR -0x6C00 +#define MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE -0x7080 +#define MBEDTLS_ERR_SSL_CONN_EOF -0x7280 +#define MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE -0x7480 +#define MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY -0x7880 +#define MBEDTLS_ERR_SSL_BAD_CERTIFICATE -0x7A00 +#define MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET -0x7B00 +#define MBEDTLS_ERR_SSL_HW_ACCEL_FAILED -0x7F80 +#define MBEDTLS_ERR_SSL_BAD_INPUT_DATA PSA_ERROR_INVALID_ARGUMENT +#define MBEDTLS_ERR_SSL_ALLOC_FAILED PSA_ERROR_INSUFFICIENT_MEMORY + +typedef enum { + MBEDTLS_SSL_VERSION_UNKNOWN, + MBEDTLS_SSL_VERSION_TLS1_2 = 0x0303, + MBEDTLS_SSL_VERSION_TLS1_3 = 0x0304 +} mbedtls_ssl_protocol_version; + +/* wolfSSL objects, opaque to the application */ +struct WOLFSSL_CTX; +struct WOLFSSL; +struct WOLFSSL_SESSION; + +typedef int mbedtls_ssl_send_t(void* ctx, const unsigned char* buf, + size_t len); +typedef int mbedtls_ssl_recv_t(void* ctx, unsigned char* buf, size_t len); +typedef int mbedtls_ssl_recv_timeout_t(void* ctx, unsigned char* buf, + size_t len, uint32_t timeout); + +typedef union { + uintptr_t n; + void* p; +} mbedtls_ssl_user_data_t; + +typedef struct mbedtls_ssl_config { + struct WOLFSSL_CTX* ctx; + int err[4]; /* by kind of conf call, returned at setup and reset */ + unsigned int changes; /* counts conf calls, see MbedSslStart() */ + int authmode; + int endpoint; + int transport; + mbedtls_ssl_protocol_version min_tls_version; + 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 */ + mbedtls_x509_crl* ca_crl; /* not supported, an error when set */ + mbedtls_ssl_user_data_t user_data; +} mbedtls_ssl_config; + +typedef struct mbedtls_ssl_session { + struct WOLFSSL_SESSION* session; + uint32_t verify_result; /* of the handshake the session is from */ +} mbedtls_ssl_session; + +typedef struct mbedtls_ssl_context { + const mbedtls_ssl_config* conf; + struct WOLFSSL* ssl; + unsigned int conf_changes; /* conf->changes when ssl was made */ + int started; /* the handshake started on ssl */ + char* hostname; /* applied again by mbedtls_ssl_session_reset() */ + int hostname_set; /* mbedtls_ssl_set_hostname() succeeded */ + int hostname_changed; /* ssl needs a new WOLFSSL for the host name */ + int session_set; /* mbedtls_ssl_set_session() was called */ + uint32_t session_verify; /* verify_result of the session set */ + void* p_bio; + mbedtls_ssl_send_t* f_send; + mbedtls_ssl_recv_t* f_recv; + 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 */ + mbedtls_ssl_user_data_t user_data; +} mbedtls_ssl_context; + +void mbedtls_ssl_config_init(mbedtls_ssl_config* conf); +void mbedtls_ssl_config_free(mbedtls_ssl_config* conf); +int mbedtls_ssl_config_defaults(mbedtls_ssl_config* conf, + int endpoint, int transport, int preset); +void mbedtls_ssl_conf_endpoint(mbedtls_ssl_config* conf, int endpoint); +void mbedtls_ssl_conf_transport(mbedtls_ssl_config* conf, int transport); +int mbedtls_ssl_conf_get_endpoint(const mbedtls_ssl_config* conf); +void mbedtls_ssl_conf_authmode(mbedtls_ssl_config* conf, int authmode); +void mbedtls_ssl_conf_ca_chain(mbedtls_ssl_config* conf, + mbedtls_x509_crt* ca_chain, mbedtls_x509_crl* ca_crl); +int mbedtls_ssl_conf_own_cert(mbedtls_ssl_config* conf, + mbedtls_x509_crt* own_cert, mbedtls_pk_context* pk_key); +void mbedtls_ssl_conf_dbg(mbedtls_ssl_config* conf, + void (*f_dbg)(void*, int, const char*, int, const char*), void* p_dbg); +void mbedtls_ssl_conf_min_tls_version(mbedtls_ssl_config* conf, + mbedtls_ssl_protocol_version tls_version); +void mbedtls_ssl_conf_max_tls_version(mbedtls_ssl_config* conf, + mbedtls_ssl_protocol_version tls_version); +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); + +static inline void mbedtls_ssl_conf_set_user_data_p(mbedtls_ssl_config* conf, + void* p) +{ + conf->user_data.p = p; +} + +static inline void mbedtls_ssl_conf_set_user_data_n(mbedtls_ssl_config* conf, + uintptr_t n) +{ + conf->user_data.n = n; +} + +static inline void* mbedtls_ssl_conf_get_user_data_p(mbedtls_ssl_config* conf) +{ + return conf->user_data.p; +} + +static inline uintptr_t mbedtls_ssl_conf_get_user_data_n( + mbedtls_ssl_config* conf) +{ + return conf->user_data.n; +} + +const int* mbedtls_ssl_list_ciphersuites(void); +const char* mbedtls_ssl_get_ciphersuite_name(const int ciphersuite_id); +int mbedtls_ssl_get_ciphersuite_id(const char* ciphersuite_name); + +void mbedtls_ssl_init(mbedtls_ssl_context* ssl); +void mbedtls_ssl_free(mbedtls_ssl_context* ssl); +int mbedtls_ssl_setup(mbedtls_ssl_context* ssl, const mbedtls_ssl_config* conf); +const mbedtls_ssl_config* mbedtls_ssl_context_get_config( + const mbedtls_ssl_context* ssl); +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); +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); +uint32_t mbedtls_ssl_get_verify_result(const mbedtls_ssl_context* ssl); +const char* mbedtls_ssl_get_ciphersuite(const mbedtls_ssl_context* ssl); +int mbedtls_ssl_get_ciphersuite_id_from_ssl(const mbedtls_ssl_context* ssl); +const char* mbedtls_ssl_get_version(const mbedtls_ssl_context* ssl); +mbedtls_ssl_protocol_version mbedtls_ssl_get_version_number( + const mbedtls_ssl_context* ssl); +size_t mbedtls_ssl_get_bytes_avail(const mbedtls_ssl_context* ssl); +int mbedtls_ssl_read(mbedtls_ssl_context* ssl, unsigned char* buf, size_t len); +int mbedtls_ssl_write(mbedtls_ssl_context* ssl, + const unsigned char* buf, size_t len); +int mbedtls_ssl_close_notify(mbedtls_ssl_context* ssl); + +static inline void mbedtls_ssl_set_user_data_p(mbedtls_ssl_context* ssl, + void* p) +{ + ssl->user_data.p = p; +} + +static inline void mbedtls_ssl_set_user_data_n(mbedtls_ssl_context* ssl, + uintptr_t n) +{ + ssl->user_data.n = n; +} + +static inline void* mbedtls_ssl_get_user_data_p(mbedtls_ssl_context* ssl) +{ + return ssl->user_data.p; +} + +static inline uintptr_t mbedtls_ssl_get_user_data_n(mbedtls_ssl_context* ssl) +{ + return ssl->user_data.n; +} + +void mbedtls_ssl_session_init(mbedtls_ssl_session* session); +void mbedtls_ssl_session_free(mbedtls_ssl_session* session); +int mbedtls_ssl_get_session(const mbedtls_ssl_context* ssl, + mbedtls_ssl_session* session); +int mbedtls_ssl_set_session(mbedtls_ssl_context* ssl, + const mbedtls_ssl_session* session); +int mbedtls_ssl_session_save(const mbedtls_ssl_session* session, + unsigned char* buf, size_t buf_len, size_t* olen); +int mbedtls_ssl_session_load(mbedtls_ssl_session* session, + const unsigned char* buf, size_t len); + +#ifdef __cplusplus + } /* extern "C" */ +#endif /* __cplusplus */ + +#endif /* MBEDTLS_SSL_H */ diff --git a/wolfpsa/mbedtls_compat/mbedtls/ssl_ciphersuites.h b/wolfpsa/mbedtls_compat/mbedtls/ssl_ciphersuites.h new file mode 100644 index 0000000..c0fd067 --- /dev/null +++ b/wolfpsa/mbedtls_compat/mbedtls/ssl_ciphersuites.h @@ -0,0 +1,53 @@ +/* ssl_ciphersuites.h + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of wolfPSA. + * + * wolfPSA is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * wolfPSA is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +#ifndef MBEDTLS_SSL_CIPHERSUITES_H +#define MBEDTLS_SSL_CIPHERSUITES_H + +#include "mbedtls/build_info.h" + +/* Not all are offered, see mbedtls_ssl_list_ciphersuites() */ +#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA 0xC009 +#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA 0xC00A +#define MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA 0xC013 +#define MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA 0xC014 +#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 0xC023 +#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 0xC024 +#define MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 0xC027 +#define MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 0xC028 +#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 0xC02B +#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 0xC02C +#define MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 0xC02F +#define MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 0xC030 +#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM 0xC0AC +#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CCM 0xC0AD +#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 0xC0AE +#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8 0xC0AF +#define MBEDTLS_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 0xCCA8 +#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 0xCCA9 + +#define MBEDTLS_TLS1_3_AES_128_GCM_SHA256 0x1301 +#define MBEDTLS_TLS1_3_AES_256_GCM_SHA384 0x1302 +#define MBEDTLS_TLS1_3_CHACHA20_POLY1305_SHA256 0x1303 +#define MBEDTLS_TLS1_3_AES_128_CCM_SHA256 0x1304 +#define MBEDTLS_TLS1_3_AES_128_CCM_8_SHA256 0x1305 + +#endif /* MBEDTLS_SSL_CIPHERSUITES_H */ diff --git a/wolfpsa/mbedtls_compat/mbedtls/timing.h b/wolfpsa/mbedtls_compat/mbedtls/timing.h new file mode 100644 index 0000000..5c21245 --- /dev/null +++ b/wolfpsa/mbedtls_compat/mbedtls/timing.h @@ -0,0 +1,29 @@ +/* timing.h + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of wolfPSA. + * + * wolfPSA is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * wolfPSA is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +/* No mbedtls_timing_* yet; DTLS needs them. */ + +#ifndef MBEDTLS_TIMING_H +#define MBEDTLS_TIMING_H + +#include "mbedtls/build_info.h" + +#endif /* MBEDTLS_TIMING_H */ diff --git a/wolfpsa/mbedtls_compat/mbedtls/version.h b/wolfpsa/mbedtls_compat/mbedtls/version.h new file mode 100644 index 0000000..d60952e --- /dev/null +++ b/wolfpsa/mbedtls_compat/mbedtls/version.h @@ -0,0 +1,30 @@ +/* version.h + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of wolfPSA. + * + * wolfPSA is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * wolfPSA is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +/* The version macros are in build_info.h. MBEDTLS_VERSION_C is not defined, + * so there is no mbedtls_version_get_number() and friends. */ + +#ifndef MBEDTLS_VERSION_H +#define MBEDTLS_VERSION_H + +#include "mbedtls/build_info.h" + +#endif /* MBEDTLS_VERSION_H */