diff --git a/.github/workflows/README.md b/.github/workflows/README.md index f06ff2d72..5aaa88221 100644 --- a/.github/workflows/README.md +++ b/.github/workflows/README.md @@ -23,7 +23,7 @@ An accepted upload queues analysis; results appear after Coverity processes it. |------|---------|---------| | **Fast (per-PR)** | every PR; push to main | host unit suites, ISO C99, house style, bare-scope scan, Arm PSA-FF conformance, cross-compile, compiler matrix, sanitizers, valgrind, integrations, core/port split guard | | **M33MU smoke** | every PR | each port not marked label only, on both crypto engines (its smoke tier in `port.json`) | -| **M33MU full** | PR labels `ci:all`, `ci:m33mu` or a port's own label; push to main; `cron: 0 8 * * *`; `workflow_dispatch` (port input) | every scenario of that port on both engines (see below) | +| **M33MU all** | PR labels `ci:all`, `ci:m33mu` or a port's own label; push to main; `cron: 0 8 * * *`; `workflow_dispatch` (port input) | every scenario of that port on both engines (see below) | The M33MU workflow (`m33mu.yml`) is label-selected the way wolfProvider's `pr-osp-select.yml` is: a `select` job checks the routing table @@ -50,8 +50,8 @@ rendered wolfBoot-style as `M33MU / __` (for example `M33MU / stm32h563_confboot_native`). The scenario groups per port and tier live in `tests/target/lib/scenario_matrix.py`, which `make test-target` also reads. Every group also runs on a build profile: jobs on -the lean `default` image carry `_default` before the engine (for example -`stm32h563_positive_default_native`), jobs without it build the `full` +the `default` profile carry `_default` before the engine (for example +`stm32h563_positive_default_native`), jobs without it build the `extended` profile. The table below is a representative slice: | Check name | Scenario key | What it proves | diff --git a/.github/workflows/cross-compile.yml b/.github/workflows/cross-compile.yml index cf1003c7b..a45d269a0 100644 --- a/.github/workflows/cross-compile.yml +++ b/.github/workflows/cross-compile.yml @@ -175,10 +175,10 @@ jobs: python3 tools/secure_ram.py --base-max 45728 \ build_budget_$target/wolftrust.map done - - name: Build every port's full-profile secure image (every engine) + - name: Build every port's extended-profile secure image (every engine) if: matrix.leg != 'common' run: | - flags="$(. tests/target/lib/profile.sh; scenario_profile_flags full)" + flags="$(. tests/target/lib/profile.sh; scenario_profile_flags extended)" for target in $WT_CI_PORT; do for engine in $(python3 tests/target/lib/scenario_matrix.py --port $target --get build.engines); do # shellcheck disable=SC2086 @@ -217,12 +217,21 @@ jobs: if: matrix.leg != 'common' run: | for target in $WT_CI_PORT; do - for profile in compat standard lean symmetric; do + for profile in extended default small tiny; do dir=build_spsa_${target}_$profile make TARGET=$target WT_SECURE_PSA=1 WT_SECURE_PSA_PROFILE=$profile \ secure-image TOOLPREFIX=arm-none-eabi- BUILD_DIR=$dir grep -qx 'WT_SECURE_PSA=1' $dir/secure_build_mode.stamp grep -qx "WT_SECURE_PSA_PROFILE=$profile" $dir/secure_build_mode.stamp + cfg=$dir/wolfpsa_cfg/crypto_config_generated.h + if [ "$profile" = extended ]; then + grep -qE '^#define PSA_WANT_ALG_SP800_108_COUNTER_HMAC\b' $cfg + grep -qE '^#define PSA_WANT_ALG_CCM_STAR_NO_TAG\b' $cfg + elif grep -qE '^#define PSA_WANT_ALG_(SP800_108_COUNTER_(HMAC|CMAC)|CCM_STAR_NO_TAG)\b' $cfg || + arm-none-eabi-nm $dir/wolftrust.elf | grep -qi sp800_108; then + echo "FAIL: $profile still carries SP 800-108 or CCM*" >&2 + exit 1 + fi done done - name: Verify bad Secure PSA settings stop the build @@ -240,6 +249,50 @@ jobs: WT_PSA_KEY_SLOTS=8 WT_PSA_OP_SLOTS=4 secure-image \ TOOLPREFIX=arm-none-eabi- BUILD_DIR=build_spsa_sizes grep -qx 'WT_PSA_SIZES=8192/8/4/' build_spsa_sizes/secure_build_mode.stamp + # small and tiny offer one PSA AEAD: CCM unless WT_AEAD=gcm + for aead in "" gcm ccm; do + dir=build_aead_small_${aead:-default} + used=${aead:-ccm} + make WT_SECURE_PSA=1 WT_SECURE_PSA_PROFILE=small WT_AEAD=$aead \ + secure-image TOOLPREFIX=arm-none-eabi- BUILD_DIR=$dir + grep -qx "WT_AEAD=$used" $dir/secure_build_mode.stamp + if [ "$used" = ccm ]; then want=CCM; drop=GCM; else want=GCM; drop=CCM; fi + cfg=$dir/wolfpsa_cfg/crypto_config_generated.h + arm-none-eabi-nm $dir/wolftrust.elf > $dir/syms.txt + grep -qE "^#define PSA_WANT_ALG_$want\b" $cfg + grep -qi " wc_Aes$want" $dir/syms.txt + if grep -qE "^#define PSA_WANT_ALG_$drop\b" $cfg || grep -qi " wc_Aes$drop" $dir/syms.txt; then + echo "FAIL: small with WT_AEAD=$used still carries $drop" >&2 + exit 1 + fi + done + # With no Secure PSA AEAD to share, the vault keeps GCM + for profile in small tiny; do + make WT_SECURE_PSA=0 WT_PROFILE=$profile secure-image \ + TOOLPREFIX=arm-none-eabi- BUILD_DIR=build_aead_nopsa_$profile + grep -qx 'WT_AEAD=gcm' build_aead_nopsa_$profile/secure_build_mode.stamp + done + make WT_SECURE_PSA=1 WT_AEAD=ccm secure-image TOOLPREFIX=arm-none-eabi- \ + BUILD_DIR=build_aead_compat_ccm + grep -qx 'WT_AEAD=ccm' build_aead_compat_ccm/secure_build_mode.stamp + for want in GCM CCM; do + grep -qE "^#define PSA_WANT_ALG_$want\b" \ + build_aead_compat_ccm/wolfpsa_cfg/crypto_config_generated.h + done + for mode in "WT_ENGINE=hsm" "WT_SECURE_PSA=0"; do + # shellcheck disable=SC2086 + make $mode WT_AEAD=ccm secure-image TOOLPREFIX=arm-none-eabi- \ + BUILD_DIR=build_aead_mode + grep -qx 'WT_AEAD=ccm' build_aead_mode/secure_build_mode.stamp + arm-none-eabi-nm build_aead_mode/wolftrust.elf | grep -q ' wc_AesCcm' + rm -rf build_aead_mode + done + if make WT_AEAD=chacha BUILD_DIR=build_spsa_bad secure-image \ + TOOLPREFIX=arm-none-eabi- 2> spsa.err; then + echo "FAIL: WT_AEAD=chacha built" >&2 + exit 1 + fi + grep -q 'WT_AEAD' spsa.err for bad in "WT_PSA_OP_SLOTS=1x" "WT_PSA_OP_SLOTS=300" "WT_PSA_POOL_BYTES=1024"; do # shellcheck disable=SC2086 if make WT_SECURE_PSA=1 $bad BUILD_DIR=build_spsa_bad \ @@ -249,6 +302,70 @@ jobs: fi grep -qE 'WT_PSA_(OP_SLOTS|POOL_BYTES)' spsa.err done + - name: Build every port's tiny profile with no ECC in the image + if: matrix.leg != 'common' + run: | + ecc='[0-9a-f]+ . (sp_256_|sp_ecc_|wc_ecc_|wolfPSA_P256_|wc_CoseSign1)' + for target in $WT_CI_PORT; do + dir=build_tiny_$target + make TARGET=$target WT_PROFILE=tiny secure-image \ + TOOLPREFIX=arm-none-eabi- BUILD_DIR=$dir + grep -qx 'WT_ATTEST_KEY=hmac/1' $dir/secure_build_mode.stamp + grep -qx 'WT_VAULT_ECC=0' $dir/secure_build_mode.stamp + arm-none-eabi-nm $dir/wolftrust.elf > $dir/syms.txt + grep -q ' wc_CoseEatPsaToken_CreateMac0' $dir/syms.txt + if grep -qE "$ecc" $dir/syms.txt; then + echo "FAIL: $target tiny still links ECC" >&2 + exit 1 + fi + done + - name: Verify each ECC feature flag (WT_ATTEST_KEY, WT_VAULT_ECC) and what tiny saves + if: matrix.leg == 'common' + run: | + ecc='[0-9a-f]+ . (sp_256_|sp_ecc_|wc_ecc_|wolfPSA_P256_|wc_CoseSign1)' + flash() { arm-none-eabi-size "$1" | awk 'NR == 2 { print $1 + $2 }'; } + # Either flag alone brings ECC back, and each works on any profile. + for args in "WT_PROFILE=tiny WT_ATTEST_KEY=ecc" "WT_PROFILE=tiny WT_VAULT_ECC=1" \ + "WT_ATTEST_KEY=hmac" "WT_VAULT_ECC=0" "WT_ATTEST_KEY=hmac WT_VAULT_ECC=0"; do + dir=build_eccflag + # shellcheck disable=SC2086 + make $args secure-image TOOLPREFIX=arm-none-eabi- BUILD_DIR=$dir + for flag in $args; do + case $flag in + WT_ATTEST_KEY=*) grep -qx "$flag/1" $dir/secure_build_mode.stamp ;; + WT_VAULT_ECC=*) grep -qx "$flag" $dir/secure_build_mode.stamp ;; + esac + done + arm-none-eabi-nm $dir/wolftrust.elf | grep -qE "$ecc" + case $args in + "WT_PROFILE=tiny WT_ATTEST_KEY=ecc") with_ecc=$(flash $dir/wolftrust.elf) ;; + esac + rm -rf $dir + done + # The cut is the point of the profile: it must stay worth 8 KiB. + make WT_PROFILE=tiny secure-image TOOLPREFIX=arm-none-eabi- BUILD_DIR=build_eccflag + tiny=$(flash build_eccflag/wolftrust.elf) + rm -rf build_eccflag + echo "tiny $tiny bytes, with an ECC attestation key $with_ecc bytes" + test $((tiny + 8192)) -le "$with_ecc" || \ + { echo "FAIL: tiny without ECC saves less than 8 KiB" >&2; exit 1; } + # A product build has no development key until its port supplies one. + if make WT_PROFILE=tiny WT_ATTEST_DEV_KEY=0 secure-image \ + TOOLPREFIX=arm-none-eabi- BUILD_DIR=build_eccflag 2> eccflag.err; then + echo "FAIL: tiny linked with no attestation key source" >&2 + exit 1 + fi + grep -q 'wt_port_attest_hmac_key' eccflag.err + for bad in "WT_ATTEST_KEY=rsa" "WT_VAULT_ECC=2" "WT_ATTEST_DEV_KEY=2" \ + "WT_ENGINE=hsm WT_ATTEST_KEY=hmac" "WT_ENGINE=hsm WT_VAULT_ECC=0"; do + # shellcheck disable=SC2086 + if make $bad BUILD_DIR=build_eccflag secure-image \ + TOOLPREFIX=arm-none-eabi- 2> eccflag.err; then + echo "FAIL: $bad built" >&2 + exit 1 + fi + grep -qE 'WT_(ATTEST_KEY|VAULT_ECC|ATTEST_DEV_KEY)' eccflag.err + done - name: Verify the Secure PSA guest links the client and no wolfPSA if: matrix.leg != 'common' run: | diff --git a/AGENTS.md b/AGENTS.md index f134486e8..ded9b4815 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -55,7 +55,7 @@ and [docs/Building.md](docs/Building.md). | `make test` | host suites, registry and scenario self-tests, the assertion mutation test, the scaffold self-test, the guards, the provisioning gates, the hardware runner self-tests | the `wolftrust-ci` image the workflows pin (`docker/wolftrust-ci/`), which carries `expect` for the typed provisioning cases | | `make c99-check CC=gcc`, `sh scripts/check_house_style.sh`, `python3 scripts/check-empty-brace-scopes.py` | the coding-standard gates | any host | | `make test-compilers`, `make test-sanitize`, `make test-valgrind` | the host suites under each compiler and checker | any host | -| `make test-target TARGET=` (`WT_TIER=full`, `WT_ENGINE=hsm`) | M33MU emulator scenarios; `tests/target/run_target.sh ` runs one | the port's `wolfboot-ci-m33mu` image from docs/Ports.md; NXP ports also need the MCUXpresso SDK (see the guide) | +| `make test-target TARGET=` (`WT_TIER=all`, `WT_ENGINE=hsm`) | M33MU emulator scenarios; `tests/target/run_target.sh ` runs one | the port's `wolfboot-ci-m33mu` image from docs/Ports.md; NXP ports also need the MCUXpresso SDK (see the guide) | | `make test-hardware TARGET=` | the board scenarios; writes flash and resets the board | the host that owns the probe | `make test` stops at its first failing step. The emulator and hardware diff --git a/Makefile b/Makefile index 6213c1c1e..1d34ccdf9 100644 --- a/Makefile +++ b/Makefile @@ -17,6 +17,9 @@ endif ifeq ($(wildcard mk/arch-$(ARCH).mk),) $(error unsupported secure build architecture ARCH=$(ARCH)) endif +# make test-target runs the profile asked for, or default then extended. +WT_TEST_PROFILES ?= $(if $(filter command line environment,$(origin WT_PROFILE)),$(WT_PROFILE),default extended) +include mk/profile.mk include mk/target-$(TARGET).mk include mk/layout.mk include mk/arch-$(ARCH).mk @@ -85,24 +88,21 @@ c99-check: EXTRA_CFLAGS="$(C99_CFLAGS)" # M33MU scenarios for one registered port (TARGET): WT_TIER=smoke (default) or -# full, from its port.json. WT_PROFILE picks the build profile: default (the -# lean image make builds with no options), full (every add-on) or both, the -# default here, which runs default then full. Skips, never passes, without an -# emulator; runs in the wolfboot-ci-m33mu container, never bare-metal. +# all, from its port.json, on each of WT_TEST_PROFILES. Skips, never passes, +# without an emulator; runs in the wolfboot-ci-m33mu container, never bare-metal. WT_TIER ?= smoke -WT_PROFILE ?= both WT_SCENARIOS = $(shell python3 tests/target/lib/scenario_matrix.py \ --port $(TARGET) --tier $(WT_TIER) --engine $(WT_ENGINE) \ --profile $(1) --flat) test-target: - @case "$(WT_PROFILE)" in default|full|both) ;; *) \ - echo "unsupported WT_PROFILE='$(WT_PROFILE)' (want default, full or both)" >&2; \ - exit 2 ;; esac + @for p in $(WT_TEST_PROFILES); do case "$$p" in default|extended) ;; *) \ + echo "unsupported test profile '$$p' (want default or extended)" >&2; \ + exit 2 ;; esac; done @if ! tests/target/detect_m33mu.sh $(TARGET) >/dev/null 2>&1; then \ echo "SKIP: FF-M target scenarios ($$(tests/target/detect_m33mu.sh $(TARGET) 2>&1))"; \ else \ - $(foreach p,$(if $(filter both,$(WT_PROFILE)),default full,$(WT_PROFILE)),\ - WT_PROFILE=$(p) WT_SUITE_LOG_DIR=$(if $(filter both,$(WT_PROFILE)),logs/$(p),logs) \ + $(foreach p,$(WT_TEST_PROFILES),\ + WT_PROFILE=$(p) WT_SUITE_LOG_DIR=$(if $(word 2,$(WT_TEST_PROFILES)),logs/$(p),logs) \ tests/target/run_suite.sh $(TARGET) \ $(call WT_SCENARIOS,$(p)) || exit 1;) \ fi diff --git a/README.md b/README.md index afd1f727a..fa549e203 100644 --- a/README.md +++ b/README.md @@ -119,7 +119,7 @@ make test The Secure build produces `build/wolftrust.elf`, `build/wolftrust.bin`, and `build/secure_cmse_implib.o`. `make` builds the -lean default image: isolation level 3, one Non-secure guest, and the Crypto, +`default` profile: isolation level 3, one Non-secure guest, and the Crypto, ITS, Protected Storage and attestation services. Add-ons such as a second guest (`WT_MAX_GUESTS=2`) or firmware update (`WT_FWU=1`) are one Make variable each; see [Build profiles](docs/Macros.md#build-profiles). @@ -148,7 +148,7 @@ make test-hardware TARGET=stm32h563 make test-hardware TARGET=mcxn947 ``` -`make test-target` runs the port's smoke tier under M33MU (`WT_TIER=full` for +`make test-target` runs the port's smoke tier under M33MU (`WT_TIER=all` for every scenario): the STM32H563 default skips explicitly when M33MU is unavailable, and `TARGET=mimxrt700` or `TARGET=mcxn947` builds its pinned emulator and wolfBoot first stage itself. diff --git a/docs/Architecture.md b/docs/Architecture.md index 387c3a181..3aa5139df 100644 --- a/docs/Architecture.md +++ b/docs/Architecture.md @@ -10,7 +10,7 @@ enforce that policy. The only currently supported and validated reference implementation combines the Armv8-M adapter with the STM32H563 port. Its default configuration runs one Non-secure guest on one Cortex-M33 (two with `WT_MAX_GUESTS=2`, as the -`full` build profile does) and exposes Secure services only through FF-M IPC. These are current reference-port choices. The common policy and +`extended` build profile does) and exposes Secure services only through FF-M IPC. These are current reference-port choices. The common policy and service design is intended for reuse, but current internal contracts still contain Armv8-M-specific types and assumptions. diff --git a/docs/Building.md b/docs/Building.md index e37b5b94c..ff12c4214 100644 --- a/docs/Building.md +++ b/docs/Building.md @@ -36,7 +36,7 @@ reference is the mutable `main` branch, not a pinned workspace. make ``` -This builds the lean default image: isolation level 3, one Non-secure image, +This builds the `default` profile: isolation level 3, one Non-secure image, Crypto, Internal Trusted Storage, Protected Storage and Initial Attestation, with the manifest checked at build time. Turn an add-on back on with its Make variable, alone or together: @@ -47,7 +47,9 @@ make WT_FWU=1 secure-image # PSA Firmware Update make WT_MANIFEST_RUNTIME_CHECK=1 secure-image # boot-time manifest check make WT_SHA256_FAST=1 secure-image # unrolled SHA-256 transform make WT_ENGINE=hsm secure-image # the wolfHSM engine -make WT_MAX_GUESTS=2 WT_MANIFEST_RUNTIME_CHECK=1 WT_FWU=1 WT_SHA256_FAST=1 secure-image # full profile +make WT_PROFILE=extended secure-image # every add-on, extended PSA set +make WT_PROFILE=small secure-image # one AEAD, no AES decryption +make WT_PROFILE=tiny secure-image # no ECC: HMAC attestation key, no vault P-256 ``` [Macros](Macros.md#build-profiles) lists what each add-on brings back and its @@ -153,7 +155,7 @@ Record the LTO setting with published size results. [Footprint](Footprint.md) lists the measured sizes and the options that change them. The default image runs one guest; `WT_MAX_GUESTS=2` adds the second guest the -reference two-guest demos use (the target runners pass it through the `full` +reference two-guest demos use (the target runners pass it through the `extended` profile). Changing guest addresses or sizes also requires matching manifest, guest linker, emulator-load, flash, and measurement-record settings. See diff --git a/docs/Crypto-Engines.md b/docs/Crypto-Engines.md index ba084eaa8..19e215bcf 100644 --- a/docs/Crypto-Engines.md +++ b/docs/Crypto-Engines.md @@ -23,7 +23,7 @@ independent TF-M Level 3 code and data isolation. | Secure key service | Native request format dispatches wolfCrypt directly; explicitly vault-backed keys are NVM objects | wolfHSM request format dispatches the wolfHSM server and its keystore | | Guest volatile PSA keys | Held in the Secure image, or in the guest's Non-secure memory with `WT_SECURE_PSA=0` | Keys for supported offloaded operations are held by the Secure wolfHSM server | | Persistent Secure keys | Native vault objects marked `SENSITIVE` and `NONEXPORTABLE` | wolfHSM server-keystore objects with wolfHSM key policy | -| Attestation IAK | Vault-backed P-256 key used directly by wolfCrypt | Committed wolfHSM server-keystore key | +| Attestation IAK | Vault-backed P-256 key used directly by wolfCrypt; with `WT_ATTEST_KEY=hmac`, the port's HMAC key held by the attestation partition | Committed wolfHSM server-keystore key | | External HSM path | Not provided by this engine | Available through the wolfHSM server model when a deployment configures a backend; the reference build uses software wolfCrypt | | Secure-image footprint | Lower | Adds the wolfHSM protocol, server, per-guest contexts, and per-guest server stacks | @@ -91,7 +91,7 @@ NVM reads reject non-exportable objects, and the native request format has no private-key export operation. Private-key computations run in the Secure key-vault domain and temporary plaintext key buffers are zeroized after use. The attestation IAK is a separate fixed vault object used only by the -attestation path. +attestation path; a `WT_ATTEST_KEY=hmac` image stores no IAK in the vault. The native engine builds wolfCrypt with `NO_ASN` and does not compile `asn.c`. Its key operations use only raw forms (P-256 scalars, X9.63 public @@ -121,8 +121,13 @@ The defined operations are key generate, import, public export, sign, verify, encrypt, decrypt, and destroy, plus random generation and SHA-256 hashing. Random responses are limited to 256 bytes per request. P-256 signatures use a fixed 64-byte `r || s` form and public keys use the 65-byte uncompressed X9.63 -form. AES-256 encrypt and decrypt use AES-GCM and return or consume -`nonce || ciphertext || tag`. +form. `WT_VAULT_ECC=0`, which the `tiny` profile sets, builds no P-256 key +operations: generating or importing a P-256 key, public export, sign and +verify return `PSA_ERROR_NOT_SUPPORTED`. AES-256 encrypt and decrypt use AES-GCM, or AES-CCM when `WT_AEAD` is +`ccm` (the default of the `tiny` and `small` Secure PSA profiles), and return or consume +`nonce || ciphertext || tag`. With `WT_SECURE_PSA=1`, both run on wolfPSA's +streaming code (`wolfpsa/psa_gcm.h`, `wolfpsa/psa_ccm.h`), so wolfCrypt's +one-shot GCM and CCM are not linked as well. The structures are copied directly between the reference Cortex-M client and Secure image. This is a target-local ABI, not a versioned network protocol. @@ -188,27 +193,35 @@ Transport and memory: message, the additional data or the derivation into the pool. `WT_SECURE_PSA_PROFILE` picks the algorithm set compiled into the Secure -image. The wolfCrypt side lives in +image; it follows the [build profile](Macros.md#build-profiles) `WT_PROFILE` +unless set. The wolfCrypt side lives in `src/services/wolfhsm/runner/secure_psa_profile.h`, which the host suite includes too: | Profile | Algorithms | STM32H563 Secure flash / RAM | | --- | --- | ---: | -| `compat` (default) | The reference guest's set: P-256 ECDSA (deterministic) and ECDH, AES-GCM, CCM, CTR, CBC and ECB, SHA-256, HMAC, HKDF, PBKDF2, TLS 1.2 PRF | 110,005 / 48,880 | -| `standard` | `compat` without PBKDF2, TLS 1.2 PRF, CBC, ECB and deterministic ECDSA (ECDSA uses a random nonce) | 103,223 / 48,880 | -| `lean` | `standard` without CCM and AES decryption | 101,559 / 48,880 | -| `symmetric` | `lean` without ECC in the PSA surface; ECC key imports and generation return `PSA_ERROR_NOT_SUPPORTED` | 96,823 / 48,880 | - -RAM is the Secure RAM the image reserves. It is the same for every profile: -the crypto partition's stack grows from 5 to 6 KiB for wolfPSA's ECDSA, and its -data band from 1.5 KiB to `WT_PSA_POOL_BYTES` plus 2 KiB. The opt-out, -`WT_SECURE_PSA=0`, is 70,940 / 45,296 bytes. The PSA +| `tiny` | `small` without ECC in the PSA surface; ECC key imports and generation return `PSA_ERROR_NOT_SUPPORTED` | 87,551 / 47,344 | +| `small` | `default` with one AEAD, CCM (`WT_AEAD=gcm` swaps it for GCM), and no AES decryption | 91,207 / 47,344 | +| `default` (default) | P-256 ECDSA (random nonce) and ECDH, AES-GCM, CCM and CTR, SHA-256, HMAC, HKDF | 94,343 / 47,344 | +| `extended` | The reference guest's set: `default` plus deterministic ECDSA, CBC and ECB, PBKDF2, SP 800-108 counter KDF, TLS 1.2 PRF, CCM* without a tag | 106,069 / 48,368 | + +Every profile but `extended` signs, verifies and agrees keys on wolfPSA's direct +P-256 path over wolfCrypt's SP code, so `ecc.c` and the multi-precision math +leave the image; `extended` keeps them for deterministic ECDSA. With +`WT_AEAD=gcm`, `small` is 92,647 bytes and `tiny` 88,991. + +The `tiny` row is the algorithm set alone, `WT_SECURE_PSA_PROFILE=tiny`: the +attestation key and the vault's keys still use P-256 there. +`make WT_PROFILE=tiny` also sets `WT_ATTEST_KEY=hmac` and `WT_VAULT_ECC=0`, +and with no feature left that uses ECC the image links no curve or +big-number code at all ([ECC options](Macros.md#ecc-options)). + +RAM is the Secure RAM the image reserves. The crypto partition's stack is 6 KiB +in `extended` for `ecc.c`'s ECDSA and 5 KiB in the other profiles, as with +`WT_SECURE_PSA=0`; its data band grows from 1.5 KiB to `WT_PSA_POOL_BYTES` plus +1.5 KiB. The opt-out, `WT_SECURE_PSA=0`, is 70,780 / 45,296 bytes. The PSA guest drops from 65,384 to 34,600 bytes of flash; it keeps wolfCrypt only for -the attestation token verifier. For comparison, TF-M v2.3.1 at isolation -level 3 on the STM32L562 with its Medium crypto set is 79,680 bytes of flash -and 45,728 bytes of RAM; of that flash, its Crypto partition and Mbed TLS -are 40,478 bytes, against 55,021 for wolfCrypt, wolfPSA, the service and the -key glue in `standard`. +the attestation token verifier. wolfPSA refuses AES or GHASH whose timing depends on the key or the data, so the Secure image runs AES on wolfCrypt's touch-lines C core and GHASH on its @@ -252,7 +265,9 @@ are dropped in native. The store's on-flash format is identical in both engines, so persistent storage objects survive a switch between engines. The Initial Attestation Key is the exception. The hsm engine keeps the IAK in -the wolfHSM server keystore; the native engine keeps it as a vault key object. +the wolfHSM server keystore; the native engine keeps it as a vault key object, +or with `WT_ATTEST_KEY=hmac` takes the device's HMAC key from the port at each +boot and stores none. Neither engine migrates the other's, so switching engines on an already-provisioned device does not carry the attestation identity: a provisioning lifecycle mints a fresh IAK, and a SECURED device with no IAK for @@ -366,21 +381,23 @@ arm-none-eabi-size build_size_native/wolftrust.elf \ Flash is `text + data`. Secure RAM is everything the image reserves: `data + bss` plus the SPM main stack and every partition stack and band ([Footprint](Footprint.md#how-sizes-are-measured)). The images use the -STM32H563 reference manifest at isolation level 3. The default profile has +STM32H563 reference manifest at isolation level 3. The `default` profile has one guest, ITS, Protected Storage, vault services and COSE attestation. The -`full` profile adds `WT_MAX_GUESTS=2 WT_MANIFEST_RUNTIME_CHECK=1 WT_FWU=1 WT_SHA256_FAST=1`. +`extended` profile adds `WT_MAX_GUESTS=2 WT_MANIFEST_RUNTIME_CHECK=1 WT_FWU=1 WT_SHA256_FAST=1` +and the `extended` PSA algorithm set. wolfBoot and Non-secure guest images are not included. | Engine and profile | `text` | `data` | `bss` | Flash | Secure RAM | | --- | ---: | ---: | ---: | ---: | ---: | -| Native, default (`WT_SECURE_PSA=1`, `compat`) | 109,609 bytes | 396 bytes | 20,768 bytes | 110,005 bytes | 48,880 bytes | -| Native, `WT_SECURE_PSA=1` `standard` | 102,831 bytes | 392 bytes | 20,768 bytes | 103,223 bytes | 48,880 bytes | -| Native, `WT_SECURE_PSA=0` | 70,556 bytes | 384 bytes | 18,376 bytes | 70,940 bytes | 45,296 bytes | -| wolfHSM, default | 98,776 bytes | 392 bytes | 40,716 bytes | 99,168 bytes | 83,968 bytes | -| wolfHSM over native `WT_SECURE_PSA=0` | 28,220 bytes | 8 bytes | 22,340 bytes | 28,228 bytes | 38,672 bytes | -| Native, `full` | 118,680 bytes | 732 bytes | 31,872 bytes | 119,412 bytes | 64,420 bytes | -| Native, `full`, `WT_SECURE_PSA=0` | 79,596 bytes | 720 bytes | 27,432 bytes | 80,316 bytes | 58,788 bytes | -| wolfHSM, `full` | 108,292 bytes | 728 bytes | 66,576 bytes | 109,020 bytes | 107,956 bytes | +| Native, `default` | 93,951 bytes | 392 bytes | 20,768 bytes | 94,343 bytes | 47,344 bytes | +| Native, `small` | 90,815 bytes | 392 bytes | 20,768 bytes | 91,207 bytes | 47,344 bytes | +| Native, `default`, `WT_SECURE_PSA_PROFILE=extended` | 105,673 bytes | 396 bytes | 20,768 bytes | 106,069 bytes | 48,368 bytes | +| Native, `WT_SECURE_PSA=0` | 70,396 bytes | 384 bytes | 18,376 bytes | 70,780 bytes | 45,296 bytes | +| wolfHSM, default | 98,776 bytes | 392 bytes | 40,684 bytes | 99,168 bytes | 83,968 bytes | +| wolfHSM over native `WT_SECURE_PSA=0` | 28,380 bytes | 8 bytes | 22,308 bytes | 28,388 bytes | 38,672 bytes | +| Native, `extended` | 115,096 bytes | 732 bytes | 31,872 bytes | 115,828 bytes | 63,908 bytes | +| Native, `extended`, `WT_SECURE_PSA=0` | 79,468 bytes | 720 bytes | 27,432 bytes | 80,188 bytes | 58,788 bytes | +| wolfHSM, `extended` | 108,260 bytes | 728 bytes | 66,544 bytes | 108,988 bytes | 107,956 bytes | ### Stack contribution @@ -390,7 +407,7 @@ image has one guest and one 10,496-byte slot (10,240-byte stack plus a is the crypto partition's larger stack (10 KiB instead of 5 KiB, since the wolfHSM server peaks at 7,608 bytes on it) and its larger data band (24 KiB instead of 1.5 KiB), which holds the server, protocol and per-guest state. With -`WT_MAX_GUESTS=2` (the `full` profile): +`WT_MAX_GUESTS=2` (the `extended` profile): ```text 2 * (10,240-byte stack + 256-byte underflow guard) = 20,992 bytes diff --git a/docs/Footprint.md b/docs/Footprint.md index 07e94885c..95104bab3 100644 --- a/docs/Footprint.md +++ b/docs/Footprint.md @@ -1,10 +1,13 @@ # Footprint This page records the measured size of the Secure image and lists every build -option that changes it. The lean default is the smallest image that keeps -every PSA service; `WT_ATTEST_COSE=0` builds a smaller one without Initial -Attestation. Each option below adds a feature back, and the table gives its -cost. +option that changes it. The native image with PSA Crypto in the guest +(`WT_SECURE_PSA=0`) is the smallest that keeps every PSA service; +`WT_ATTEST_COSE=0` builds a smaller one without Initial Attestation. Each +option below adds a feature back, and the table gives its cost. +[Crypto Engines](Crypto-Engines.md#psa-crypto-in-the-secure-image-wt_secure_psa1) +has the sizes of the `tiny`, `small`, `default` and `extended` profiles with +PSA Crypto in the Secure image. [Macros](Macros.md#build-profiles) has the full description of each option. ## How sizes are measured @@ -34,26 +37,28 @@ make TARGET=stm32h563 size-report `size-report` prints the reserved Secure RAM with its breakdown, and the largest sections and `.bss` objects. Use a separate `BUILD_DIR` for each -configuration you compare. The cross-compile workflow fails if the lean native -default image on any port grows past 79,680 bytes of flash or 45,728 bytes of +configuration you compare. The cross-compile workflow fails if the native +`WT_SECURE_PSA=0` image on any port grows past 79,680 bytes of flash or 45,728 bytes of reserved Secure RAM, TF-M level 3's figures on the STM32L562E-DK. A port that runs code from a RAM band (`WT_RAMFUNC_SIZE`, 4 KiB on the MIMXRT700) is allowed that band on top. ## Measured sizes -Measured 2026-11-24, with wolfCrypt built as portable C (the default). The `full` profile turns on all four add-ons +Measured 2026-11-30 on the `WT_SECURE_PSA=0` image, with wolfCrypt built as +portable C (the default). The `extended` columns turn on the four add-ons the +`extended` profile sets (`WT_MAX_GUESTS=2 WT_FWU=1 WT_MANIFEST_RUNTIME_CHECK=1 WT_SHA256_FAST=1`). -| Port | Engine | Default flash | Default RAM | `full` flash | `full` RAM | +| Port | Engine | Default flash | Default RAM | `extended` flash | `extended` RAM | | --- | --- | ---: | ---: | ---: | ---: | -| STM32H563 | native | 70,940 | 45,296 | 80,316 | 58,788 | -| STM32H563 | hsm | 99,168 | 83,968 | 109,020 | 107,956 | -| MIMXRT700 | native | 71,212 | 49,692 | 80,640 | 63,180 | +| STM32H563 | native | 70,780 | 45,296 | 80,188 | 58,788 | +| STM32H563 | hsm | 99,168 | 83,968 | 108,988 | 107,956 | +| MIMXRT700 | native | 71,052 | 49,692 | 80,512 | 63,180 | | MIMXRT700 | hsm | 99,436 | 88,360 | 109,348 | 112,348 | -| MCX N947 | native | 69,716 | 45,492 | 79,152 | 58,980 | -| MCX N947 | hsm | 97,940 | 84,160 | 107,828 | 108,148 | -| STM32L562 | native | 70,432 | 45,280 | 79,836 | 58,764 | +| MCX N947 | native | 69,556 | 45,492 | 79,024 | 58,980 | +| MCX N947 | hsm | 97,908 | 84,160 | 107,828 | 108,148 | +| STM32L562 | native | 70,304 | 45,280 | 79,708 | 58,764 | The MIMXRT700 RAM includes its 4 KiB RAM code band (the NSC gateway and the NOR program code). The STM32L562 port builds the native engine only. @@ -66,16 +71,16 @@ the default. | Option | Adds | Flash / RAM | Speed | | --- | --- | ---: | --- | -| `WT_MAX_GUESTS=2` | A second Non-secure guest, the scheduling between two, and an IPC message pool of 8 instead of 4 | +2,328 / +9,368 | Adds SAU, MPU and IRQ reprogramming on every guest switch | -| `WT_FWU=1` | PSA Firmware Update and its 4 KiB stack | +3,348 / +4,120 | None | -| `WT_MANIFEST_RUNTIME_CHECK=1` | The boot-time manifest and port-binding validator | +3,316 / 0 | Adds the validator run at boot | -| `WT_SHA256_FAST=1` | The unrolled SHA-256 transform | +384 / 0 | Faster guest verification at boot, attestation and the PSA hash service | -| `WT_WOLFCRYPT_SP_ASM=1 WT_WOLFCRYPT_ARMASM=1` | wolfCrypt's Cortex-M assembly for ECC, AES and SHA-256, and the 9 KiB native crypto stack its P-256 verify needs | +8,636 / +4,096 | Faster ECC, AES and SHA-256; the AES uses lookup tables and is not constant time | -| `WT_ENGINE=hsm` | The wolfHSM server as the crypto engine, with its 10 KiB crypto stack and 24 KiB data band | +28,228 / +38,672 | Adds the wolfHSM request layer to each crypto call | -| `full` profile | The first four together | +9,376 / +13,492 | As above | +| `WT_MAX_GUESTS=2` | A second Non-secure guest, the scheduling between two, and an IPC message pool of 8 instead of 4 | +2,360 / +9,372 | Adds SAU, MPU and IRQ reprogramming on every guest switch | +| `WT_FWU=1` | PSA Firmware Update and its 4 KiB stack | +3,476 / +4,120 | None | +| `WT_MANIFEST_RUNTIME_CHECK=1` | The boot-time manifest and port-binding validator | +3,188 / 0 | Adds the validator run at boot | +| `WT_SHA256_FAST=1` | The unrolled SHA-256 transform | +416 / 0 | Faster guest verification at boot, attestation and the PSA hash service | +| `WT_WOLFCRYPT_SP_ASM=1 WT_WOLFCRYPT_ARMASM=1` | wolfCrypt's Cortex-M assembly for ECC, AES and SHA-256, and the 9 KiB native crypto stack its P-256 verify needs | +8,604 / +4,096 | Faster ECC, AES and SHA-256; the AES uses lookup tables and is not constant time | +| `WT_ENGINE=hsm` | The wolfHSM server as the crypto engine, with its 10 KiB crypto stack and 24 KiB data band | +28,388 / +38,672 | Adds the wolfHSM request layer to each crypto call | +| `extended` profile add-ons | The first four together | +9,408 / +13,492 | As above | -With the wolfHSM engine, `WT_MAX_GUESTS=2` costs +2,648 bytes of flash and -+19,864 bytes of RAM, because each guest gets its own server stack. +With the wolfHSM engine, `WT_MAX_GUESTS=2` costs +2,776 bytes of flash and ++19,868 bytes of RAM, because each guest gets its own server stack. Each partition stack is sized from the high-water mark measured on M33MU across the positive, restart, recovery, update and Arm conformance scenarios @@ -89,9 +94,9 @@ Stack high-water marks on the STM32H563, read from M33MU RAM dumps filled with `0xA5` (2026-11-17). The native column is the `nativewire` scenario, which runs the positive lifecycle and every native wire key op from the guest; the wolfHSM column is `positive` on the default profile and `bothpsa` -on `full`. +on `extended`. -| Stack | Size | Native, default | wolfHSM, default | wolfHSM, `full` | +| Stack | Size | Native, default | wolfHSM, default | wolfHSM, `extended` | | --- | ---: | ---: | ---: | ---: | | SPM main | 4,096 | 2,200 | 1,124 | 1,244 | | Crypto | 5,120 native, 10,240 wolfHSM | 4,416 | 7,608 | 7,676 | @@ -115,16 +120,19 @@ These options also add code but are not part of a production size budget: ## Smallest image -Build with no options: +Build with PSA Crypto in the guest: ```sh -make TARGET= secure-image +make TARGET= WT_SECURE_PSA=0 secure-image ``` -That is the native engine, one guest, LTO on, and every add-on off. Keep +That is the native engine, one guest, LTO on, every add-on off, and PSA +Crypto running in the guest's wolfPSA. A build with no options puts PSA Crypto +in the Secure image instead (the STM32L562 already defaults to +`WT_SECURE_PSA=0`). Keep `WT_LTO=1`; `WT_LTO=0` is for toolchain diagnostics and builds a larger image. `-Oz` was measured against the default `-Os` and gave no smaller -image. The default keeps Crypto, Internal Trusted Storage, Protected Storage +image. It keeps Crypto, Internal Trusted Storage, Protected Storage and Initial Attestation at isolation level 3. `WT_ATTEST_COSE=0` removes Initial Attestation and wolfCOSE for a smaller image without that service; CI compile-checks it in the MIMXRT700 and MCX N947 builds, while every M33MU @@ -152,30 +160,31 @@ Leave these at their defaults, which already favor speed: so the comparison covers both images: the Secure image and the application that calls it. `tools/measure_interface_footprint.sh` builds each port, engine and API with `WT_INTERFACE_PROFILE=default` and checks that every pair is present; -the cross-compile workflow publishes its CSV. Measured 2026-11-24. +the cross-compile workflow publishes its CSV. Measured 2026-11-30. Flash is Secure plus application, in bytes; RAM is reserved Secure RAM. | Port | Engine | PSA flash | TPM 2.0 flash | PKCS#11 flash | PSA RAM | TPM 2.0 RAM | PKCS#11 RAM | | --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | -| STM32H563 | native | 145,661 | 133,688 (-8.2%) | 116,404 (-20.1%) | 48,880 | 83,184 | 98,544 | -| STM32H563 | hsm | 177,440 | 173,644 (-2.1%) | 153,548 (-13.5%) | 83,968 | 123,904 | 139,264 | -| MIMXRT700 | native | 145,897 | 133,860 (-8.3%) | 116,644 (-20.1%) | 53,276 | 87,580 | 102,940 | -| MIMXRT700 | hsm | 177,708 | 173,884 (-2.2%) | 153,820 (-13.4%) | 88,360 | 128,296 | 143,656 | -| MCX N947 | native | 144,433 | 132,396 (-8.3%) | 115,164 (-20.3%) | 49,076 | 83,380 | 98,740 | -| MCX N947 | hsm | 176,212 | 172,420 (-2.2%) | 152,308 (-13.6%) | 84,160 | 124,096 | 139,456 | -| STM32L562 | native | 135,816 | 133,144 (-2.0%) | 115,904 (-14.7%) | 45,280 | 83,168 | 98,528 | - -The application shrinks because it no longer links a PSA Crypto client: the -PKCS#11 proxy is under 8 KB. The Secure image grows by the provider (fwTPM or -wolfPKCS11) and its private wolfCrypt copy. The wolfTPM client keeps its own +| STM32H563 | native | 130,063 | 140,044 (+7.7%) | 116,276 (-10.6%) | 47,344 | 83,184 | 98,544 | +| STM32H563 | hsm | 177,152 | 180,164 (+1.7%) | 153,516 (-13.3%) | 83,968 | 123,904 | 139,264 | +| MIMXRT700 | native | 130,303 | 140,284 (+7.7%) | 116,484 (-10.6%) | 51,740 | 87,580 | 102,940 | +| MIMXRT700 | hsm | 177,324 | 180,400 (+1.7%) | 153,788 (-13.3%) | 88,360 | 128,296 | 143,656 | +| MCX N947 | native | 128,807 | 138,788 (+7.7%) | 115,004 (-10.7%) | 47,540 | 83,380 | 98,740 | +| MCX N947 | hsm | 175,796 | 178,904 (+1.8%) | 152,308 (-13.4%) | 84,160 | 124,096 | 139,456 | +| STM32L562 | native | 135,368 | 139,536 (+3.1%) | 115,744 (-14.5%) | 45,280 | 83,168 | 98,528 | + +The PKCS#11 application is under 8 KB because its proxy links no PSA Crypto +client. Both interfaces grow the Secure image by the provider (fwTPM or +wolfPKCS11) and its private wolfCrypt copy, so TPM 2.0 is larger than PSA +overall. The wolfTPM client keeps its own wolfCrypt for sessions and takes its entropy from `TPM2_GetRandom`, so it links no crypto engine client and is the same size under both engines. TPM 2.0 includes fwTPM dictionary-attack lockout; `WT_TPM_DA=0` saves about 2.3 KB of Secure flash. -The extra RAM is the interface band above SPM RAM, sized from the `full` +The extra RAM is the interface band above SPM RAM, sized from the `extended` profile on the STM32H563 with the stack method above: | Band | Data used / reserved | Stack peak / reserved | diff --git a/docs/Interface-Profiles.md b/docs/Interface-Profiles.md index a32e52426..a8564855e 100644 --- a/docs/Interface-Profiles.md +++ b/docs/Interface-Profiles.md @@ -1,14 +1,14 @@ # Crypto operation profiles `WT_ENGINE=native|hsm` selects the crypto engine independently of the application -API. `WT_INTERFACE_PROFILE=default|full` selects the exported operations. Native is +API. `WT_INTERFACE_PROFILE=default|extended` selects the exported operations. Native is the default engine. Neither TPM nor PKCS#11 requires wolfHSM. The default profile covers RNG, SHA-256 and P-256 key generation, signing and verification. It also includes the key, session and token management needed to use those operations. PKCS#11 retains PIN setup, login, attempt limits and recovery. `config/crypto-profiles.json` is the explicit default operation list. -The full profile retains the broader operations supported by the pinned +The extended profile retains the broader operations supported by the pinned libraries and this platform's algorithm and memory configuration. ## Select operations @@ -17,7 +17,7 @@ Use the same settings for the application and Secure image: ```sh make secure-image CONFIG_PKCS11=y WT_ENGINE=native WT_INTERFACE_PROFILE=default -make secure-image CONFIG_TPM=y WT_ENGINE=hsm WT_INTERFACE_PROFILE=full +make secure-image CONFIG_TPM=y WT_ENGINE=hsm WT_INTERFACE_PROFILE=extended WT_INTERFACE_ENABLE='pkcs11:C_GetObjectSize tpm:PCR_Read' \ WT_INTERFACE_DISABLE='pkcs11:C_GenerateRandom' \ @@ -60,7 +60,7 @@ python3 tools/crypto_profile.py --output build/crypto-profile \ The command catalog includes dependency commands whose algorithm or feature family can be disabled by platform settings. Selection does not override those settings or provide missing NV storage. A default-derived TPM selection checks -that every requested command survived those guards. The full profile retains +that every requested command survived those guards. The extended profile retains the dependency guards; `TPM_CAP_COMMANDS` reports the commands actually built. ## What is removed @@ -86,7 +86,7 @@ TPM and PKCS#11 images link no wolfPSA Crypto implementation. Their `psa_call` functions are the FF-M IPC boundary. The basic selection also omits unused AES-CTR, CCM and deterministic-ECDSA -extensions from the Secure image. Full profiles and broader custom command or +extensions from the Secure image. Extended profiles and broader custom command or mechanism selections restore those extensions. Required CFB and PIN primitives remain enabled. The basic TPM image uses wolfCrypt's original ASN codec; broader TPM profiles and PKCS#11 retain the template codec. Host tests cover @@ -94,7 +94,7 @@ both codecs, malformed keys and signatures, and cross-codec key decoding. HSM callback dispatch for basic TPM/PKCS#11 selections retains RNG, SHA-256 and P-256. It omits unrequested AES and HKDF dispatch after loading the complete -shared type definitions. Full and broader custom selections retain the original +shared type definitions. Extended and broader custom selections retain the original callback. No dependency files or structure layouts are changed. ## Reference builds and verification @@ -119,7 +119,7 @@ the bare-metal TPM 2.0 and PKCS#11 applications and their partition-isolation scenarios. Run `make test` for the host regressions. The target runner builds the -interface profile named by `WT_PROFILE` (`default` or `full`) unless +interface profile named by `WT_PROFILE` (`default` or `extended`) unless `WT_INTERFACE_PROFILE` is set; product builds default to `default`. Applications must match the selected operation list. diff --git a/docs/MCXN947-Guide.md b/docs/MCXN947-Guide.md index 84bd53ce8..b2d36ab6e 100644 --- a/docs/MCXN947-Guide.md +++ b/docs/MCXN947-Guide.md @@ -260,7 +260,7 @@ tests/target/run_hardware.sh mcxn947 positive WT_ENGINE=hsm tests/target/run_hardware.sh mcxn947 positive ``` -The hardware runner builds the `full` profile, so its scenarios launch two +The hardware runner builds the `extended` profile, so its scenarios launch two guests and include Firmware Update; it refuses any other `WT_PROFILE`. `tests/target/run_hardware.sh mcxn947 ` runs on the host that owns diff --git a/docs/MIMXRT700-Guide.md b/docs/MIMXRT700-Guide.md index a8eedf400..9aaf5c74b 100644 --- a/docs/MIMXRT700-Guide.md +++ b/docs/MIMXRT700-Guide.md @@ -247,7 +247,7 @@ Running `discover` again clears both it and any earlier `regress` stamp. ## Build, flash, and verify -The hardware runner builds the `full` profile, so its scenarios launch two +The hardware runner builds the `extended` profile, so its scenarios launch two guests and include Firmware Update; it refuses any other `WT_PROFILE`. The hardware runner (`tests/target/run_hardware.sh mimxrt700 `) diff --git a/docs/Macros.md b/docs/Macros.md index 4d94cdb22..deb6ce2cf 100644 --- a/docs/Macros.md +++ b/docs/Macros.md @@ -7,40 +7,59 @@ selected values into C preprocessor defines. Defaults below come from ## Build profiles -`make` with no options builds the lean default image. It runs at isolation -level 3 with one Non-secure image and the PSA services a TF-M level 3 build -ships: Crypto, Internal Trusted Storage, Protected Storage, and Initial -Attestation. The manifest is checked at build time. Each add-on below turns one feature back on with one Make variable. -None of them changes the isolation level. +`WT_PROFILE` picks one of four build profiles, smallest first: `tiny`, `small`, +`default` and `extended`. `make` with no options builds `default`: isolation +level 3, one Non-secure image and four PSA services (Crypto, Internal Trusted +Storage, Protected Storage and Initial Attestation), with the manifest checked +at build time. A profile sets the defaults of the +add-ons below and of [`WT_SECURE_PSA_PROFILE`](Crypto-Engines.md#psa-crypto-in-the-secure-image-wt_secure_psa1); +a variable set explicitly still wins. No profile changes the isolation level. + +| `WT_PROFILE` | Secure PSA algorithm set | Flags it sets | +| --- | --- | --- | +| `tiny` | `tiny`: CCM, AES-CTR, SHA-256, HMAC and HKDF, no ECC in the PSA surface | `WT_ATTEST_KEY=hmac WT_VAULT_ECC=0` (native engine), so the image links no ECC | +| `small` | `small`: one AEAD (CCM), AES-CTR, P-256 ECDSA and ECDH, SHA-256, HMAC and HKDF | none | +| `default` | `default`: GCM and CCM, CTR, P-256 ECDSA and ECDH, SHA-256, HMAC and HKDF | none | +| `extended` | `extended`: `default` plus CBC, ECB, PBKDF2, TLS 1.2 PRF, SP 800-108, CCM* and deterministic ECDSA | `WT_MAX_GUESTS=2 WT_MANIFEST_RUNTIME_CHECK=1 WT_FWU=1 WT_SHA256_FAST=1` | + +`mk/profile.mk` holds this table for the build and +`tests/target/lib/profile.sh` the same one for the target runners. + +A profile is only a preset. Each flag it sets is an option of its own and works +on every profile: `make WT_PROFILE=tiny WT_ATTEST_KEY=ecc WT_VAULT_ECC=1` is +`tiny` with the P-256 attestation key and vault keys back, and +`make WT_ATTEST_KEY=hmac` is `default` with an HMAC attestation key. See +[ECC options](#ecc-options). Costs are over the default image, built with Arm GNU 15.2.1 in `ghcr.io/wolfssl/wolfboot-ci-m33mu:v1.25` with LTO and read with `make size-report`: flash is `text + data`, and RAM is the Secure RAM the image reserves, partition stacks and bands included ([Footprint](Footprint.md#how-sizes-are-measured)). The default native image serves PSA Crypto from the Secure image and is -110,005 bytes of flash and 48,880 bytes of RAM on the STM32H563, with wolfCrypt +94,343 bytes of flash and 47,344 bytes of RAM on the STM32H563, with wolfCrypt built as portable C. The other rows are measured over the `WT_SECURE_PSA=0` -image, 70,940 and 45,296 bytes on the STM32H563, and 70,432 and 45,280 bytes +image, 70,780 and 45,296 bytes on the STM32H563, and 70,304 and 45,280 bytes on the STM32L562. [Footprint](Footprint.md) logs the sizes of every port and engine. | Option | Brings back | STM32H563 flash / RAM | STM32L562 flash / RAM | Enable | | --- | --- | ---: | ---: | --- | -| [`WT_MAX_GUESTS=2`](#wt_max_guests-a-second-guest) | A second Non-secure image, the scheduling that shares the core between two, and an IPC message pool of 8 instead of 4 | +2,328 / +9,368 | +2,328 / +9,364 | `make WT_MAX_GUESTS=2 secure-image` | -| [`WT_FWU=1`](#wt_fwu-psa-firmware-update) | The PSA Firmware Update service and its 4 KiB stack | +3,348 / +4,120 | +3,372 / +4,136 | `make WT_FWU=1 secure-image` | -| [`WT_MANIFEST_RUNTIME_CHECK=1`](#wt_manifest_runtime_check-boot-time-manifest-check) | The boot-time manifest and port-binding validator | +3,316 / 0 | +3,284 / 0 | `make WT_MANIFEST_RUNTIME_CHECK=1 secure-image` | -| [`WT_SHA256_FAST=1`](#wt_sha256_fast-unrolled-sha-256) | The unrolled SHA-256 transform, faster hashing for boot and guest measurement | +384 / 0 | +416 / 0 | `make WT_SHA256_FAST=1 secure-image` | -| [`WT_ENGINE=hsm`](#wt_enginehsm-the-wolfhsm-engine) | The wolfHSM server as the crypto engine | +28,228 / +38,672 | not supported | `make WT_ENGINE=hsm secure-image` | -| [`WT_SECURE_PSA=0`](Crypto-Engines.md#psa-crypto-in-the-secure-image-wt_secure_psa1) | Removes PSA Crypto from the Secure image and runs wolfPSA in the guest again; saves 39,065 / 3,584 against the `compat` default (`standard` is +32,283 / +3,584 over it) | -39,065 / -3,584 | not measured | `make WT_SECURE_PSA=0 secure-image` | -| `full` profile | `WT_MAX_GUESTS=2 WT_MANIFEST_RUNTIME_CHECK=1 WT_FWU=1 WT_SHA256_FAST=1` together | +9,376 / +13,492 | +9,404 / +13,484 | `make WT_MAX_GUESTS=2 WT_MANIFEST_RUNTIME_CHECK=1 WT_FWU=1 WT_SHA256_FAST=1 secure-image` | +| [`WT_MAX_GUESTS=2`](#wt_max_guests-a-second-guest) | A second Non-secure image, the scheduling that shares the core between two, and an IPC message pool of 8 instead of 4 | +2,360 / +9,372 | +2,328 / +9,364 | `make WT_MAX_GUESTS=2 secure-image` | +| [`WT_FWU=1`](#wt_fwu-psa-firmware-update) | The PSA Firmware Update service and its 4 KiB stack | +3,476 / +4,120 | +3,440 / +4,120 | `make WT_FWU=1 secure-image` | +| [`WT_MANIFEST_RUNTIME_CHECK=1`](#wt_manifest_runtime_check-boot-time-manifest-check) | The boot-time manifest and port-binding validator | +3,188 / 0 | +3,124 / 0 | `make WT_MANIFEST_RUNTIME_CHECK=1 secure-image` | +| [`WT_SHA256_FAST=1`](#wt_sha256_fast-unrolled-sha-256) | The unrolled SHA-256 transform, faster hashing for boot and guest measurement | +416 / 0 | +384 / 0 | `make WT_SHA256_FAST=1 secure-image` | +| [`WT_ENGINE=hsm`](#wt_enginehsm-the-wolfhsm-engine) | The wolfHSM server as the crypto engine | +28,388 / +38,672 | not supported | `make WT_ENGINE=hsm secure-image` | +| [`WT_SECURE_PSA=0`](Crypto-Engines.md#psa-crypto-in-the-secure-image-wt_secure_psa1) | Removes PSA Crypto from the Secure image and runs wolfPSA in the guest again; saves 23,563 / 2,048 against the `default` algorithm set (35,289 / 3,072 against `extended`) | -23,563 / -2,048 | not measured | `make WT_SECURE_PSA=0 secure-image` | +| `extended` add-ons | `WT_MAX_GUESTS=2 WT_MANIFEST_RUNTIME_CHECK=1 WT_FWU=1 WT_SHA256_FAST=1` together | +9,408 / +13,492 | +9,404 / +13,484 | `make WT_MAX_GUESTS=2 WT_MANIFEST_RUNTIME_CHECK=1 WT_FWU=1 WT_SHA256_FAST=1 secure-image` | The RAM figures include every stack and band an option adds, the 4 KiB FWU stack for `WT_FWU=1` among them. The engine is a separate axis: -CI runs both engines on both profiles where the port supports them. +CI runs both engines on the `default` and `extended` profiles where the port +supports them. -`tests/target/lib/profile.sh` holds the profile flags. `make test-target` runs -both profiles; `WT_PROFILE=default` or `WT_PROFILE=full` picks one. Hardware runners -build `full` only, because their checks assert both guests. +`make test-target` runs `default` then `extended` (`WT_TEST_PROFILES`); +`WT_PROFILE=default` or `WT_PROFILE=extended` picks one. Hardware runners +build `extended` only, because their checks assert both guests. ## Add-on options @@ -56,13 +75,13 @@ build `full` only, because their checks assert both guests. also adds a second server tasklet and its 10 KiB stack. One guest keeps the restart policy, launch verification, the Secure tick and the Secure Partition scheduler. -- Cost: STM32H563 native +2,328 bytes flash and +9,368 bytes RAM, wolfHSM - +2,648 and +19,864; STM32L562 native +2,328 and +9,364. Most of the RAM is +- Cost: STM32H563 native +2,360 bytes flash and +9,372 bytes RAM, wolfHSM + +2,776 and +19,868; STM32L562 native +2,328 and +9,364. Most of the RAM is the IPC message pool, which holds 8 messages with two guests and 4 with one (`WT_FFM_MAX_MESSAGES`). - Enable: `make WT_MAX_GUESTS=2 secure-image` -- CI: the cross-compile job builds it alone and in the `full` profile for - every port and engine, and checks that `WT_MAX_GUESTS=3` stops the build. The M33MU `full` +- CI: the cross-compile job builds it alone and in the `extended` profile for + every port and engine, and checks that `WT_MAX_GUESTS=3` stops the build. The M33MU `extended` profile runs the two-guest scenarios (`bothpsa`, `bothiso`, `guestisoneg`, `restart` and the rest). `tests/host/monitor` builds both guest counts. @@ -80,15 +99,15 @@ build `full` only, because their checks assert both guests. exist and a connect to SID `0x1005` is refused like any unknown service. Anti-rollback enforcement at boot stays in every image. `WT_BOOTUPDATE_PROBE=1` needs `WT_FWU=1`. -- Cost: STM32H563 native +3,348 bytes flash and +4,120 bytes RAM; STM32L562 - native +3,372 and +4,136. The RAM is almost all the update partition's +- Cost: STM32H563 native +3,476 bytes flash and +4,120 bytes RAM; STM32L562 + native +3,440 and +4,120. The RAM is almost all the update partition's stack. - Enable: `make WT_FWU=1 secure-image` -- CI: the cross-compile job builds it alone and in the `full` profile for - every port and engine. The M33MU `full` profile runs `fwustage` and +- CI: the cross-compile job builds it alone and in the `extended` profile for + every port and engine. The M33MU `extended` profile runs `fwustage` and `bootupdate`. `tests/host/sp_layout`, `tests/host/rt700_xspi`, `tests/host/fwu_service` and - `tests/host/manifest_ports` (default and full manifests) cover the layout, + `tests/host/manifest_ports` (`default` and `extended` manifests) cover the layout, the NOR window, the service and the excluded manifest. ### `WT_MANIFEST_RUNTIME_CHECK`: boot-time manifest check @@ -103,13 +122,13 @@ build `full` only, because their checks assert both guests. `wt_manifest_validate()`, `wt_partitions_bind_manifest()` runs `wt_partition_validate_port_binding()`, and the monitor runs `wt_partition_validate_profile()` for each guest. -- Cost: flash only, RAM does not change. STM32H563 native +3,316 bytes and - STM32L562 native +3,284 bytes. +- Cost: flash only, RAM does not change. STM32H563 native +3,188 bytes and + STM32L562 native +3,124 bytes. - Enable: `make WT_MANIFEST_RUNTIME_CHECK=1 secure-image` - CI: the cross-compile job builds every port and engine with it and checks that only the opt-in image links `wt_manifest_validate`. The `manifestneg` and `manifestneg2` scenarios corrupt the manifest at boot, so they force it - on, and the M33MU `full` profile runs every scenario with it. + on, and the M33MU `extended` profile runs every scenario with it. `tests/host/manifest_ports` runs the validator over every port manifest. ### `WT_SHA256_FAST`: unrolled SHA-256 @@ -122,12 +141,12 @@ build `full` only, because their checks assert both guests. - SHA-256 runs at boot over each guest image (launch verification), in every attestation token and in the PSA hash service, so `1` shortens those paths; nothing else changes. -- Cost: flash only, +384 bytes on the STM32H563 and +416 on the STM32L562 +- Cost: flash only, +416 bytes on the STM32H563 and +384 on the STM32L562 with the default portable C build, or +1,472 bytes with `WT_WOLFCRYPT_ARMASM=1`. - Enable: `make WT_SHA256_FAST=1 secure-image` -- CI: the cross-compile job builds it alone and in the `full` profile for - every port and engine, the M33MU `full` profile runs every scenario on the +- CI: the cross-compile job builds it alone and in the `extended` profile for + every port and engine, the M33MU `extended` profile runs every scenario on the unrolled transform, and the `default` profile runs them on the looped one. ### `WT_ENGINE=hsm`: the wolfHSM engine @@ -135,7 +154,7 @@ build `full` only, because their checks assert both guests. - Default `native`, which runs wolfCrypt directly behind `SERVICE_HSM`. `hsm` links the wolfHSM server instead, with server-keystore semantics and an external-HSM offload path. The FF-M surface does not change. -- Cost: STM32H563 +28,228 bytes flash and +38,672 bytes RAM over the native +- Cost: STM32H563 +28,388 bytes flash and +38,672 bytes RAM over the native `WT_SECURE_PSA=0` image, including the wolfHSM server's 10 KiB crypto partition stack and 24 KiB data band. Part of it is AES block decryption, which the wolfHSM server serves to clients and the native engine leaves out. The STM32L562 builds the native engine only; its 256 KiB of SRAM @@ -145,6 +164,74 @@ build `full` only, because their checks assert both guests. - CI: every cross-compile and M33MU tier runs both engines on the ports that support them. See [Crypto Engines](Crypto-Engines.md). +## ECC options + +The Secure image links P-256 for three features: the PSA algorithm set, the +attestation key and the vault's key operations. Each has its own flag. When +none of them asks for ECC, the build drops the curve and the big-number code +with it (`sp_c32.c`, `sp_int.c`, `ecc.c`); there is no separate switch. The +`tiny` profile sets all three that way. `make print-profile` prints the +resolved flags and `WT_NO_ECC`. + +| What uses ECC | Flag | Without ECC | +| --- | --- | --- | +| PSA Crypto algorithm set | `WT_SECURE_PSA_PROFILE` | `tiny`, or `WT_SECURE_PSA=0` | +| Initial Attestation key | `WT_ATTEST_KEY` | `hmac` | +| Vault key operations | `WT_VAULT_ECC` | `0` | +| wolfHSM engine, TPM 2.0, PKCS#11 | `WT_ENGINE`, `CONFIG_TPM`, `CONFIG_PKCS11` | native engine, both off | + +### `WT_ATTEST_KEY`: the attestation key type + +- Default `ecc`: a P-256 key the crypto partition generates at first boot and + keeps; tokens are COSE_Sign1 with ES256. `hmac` uses a 32-byte HMAC-SHA256 + key instead; tokens are COSE_Mac0 with HMAC 256/256 + ([RFC 9783](https://www.rfc-editor.org/rfc/rfc9783.html), section 5.1.1), + and the Instance ID is `0x01 || SHA-256(SHA-256(key))`. The `tiny` profile + sets `hmac`. Any other value stops the build. +- A verifier checks an HMAC token with the same key, so the key is the + device's, not random: the port returns it from + `wt_port_attest_hmac_key()` (see [Porting](Porting.md#attestation-key)). + The attestation partition holds it; no call exports it and there is no + public-key query. +- Saves: the signing door between the attestation and crypto partitions, the + stored P-256 key and COSE_Sign1. With `WT_VAULT_ECC=0` on the `tiny` + algorithm set, the whole of ECC: at least 8 KiB of flash on the STM32H563, + which CI enforces. +- Enable: `make WT_ATTEST_KEY=hmac secure-image`. Requires the native engine; + the wolfHSM engine keeps the attestation key in its keystore. +- CI: the cross-compile job builds `tiny` for every port and fails if a curve, + big-number or COSE_Sign1 symbol is linked, builds each flag alone, and + checks the saving. `tests/host/attestation_hmac` issues tokens with the + `tiny` wolfCOSE configuration and verifies them independently, starting + from the RFC 9783 Appendix A.2 token. + +### `WT_ATTEST_DEV_KEY`: the development attestation key + +- Default `1`: with `WT_ATTEST_KEY=hmac`, link `port/common/attest_dev_key.c`, + a fixed public key, so the reference boards build and test with no + provisioning. The build prints a warning. A token under this key proves + nothing about a device. +- `0` links no key source: the port supplies `wt_port_attest_hmac_key()`, and + the image does not link without it. A product sets `0`. +- CI: the cross-compile job checks that `0` does not link on a reference port. + +### `WT_VAULT_ECC`: the vault's P-256 key operations + +- Default `1`: the vault generates, imports, signs with and verifies P-256 + keys for its clients. `0` leaves those out: the requests return + `PSA_ERROR_NOT_SUPPORTED`, and AES-256 keys, sealed storage and random + bytes are unchanged. The `tiny` profile sets `0`. Any other value stops the + build. +- With `WT_ATTEST_KEY=ecc` the vault still holds P-256 for the attestation + key, so `0` alone saves only the request handling; the saving comes with + `WT_ATTEST_KEY=hmac`. +- A P-256 key a client stored under `1` stays in the store and is unusable + under `0`. +- Enable: `make WT_VAULT_ECC=0 secure-image`. Requires the native engine. +- CI: the cross-compile job builds it alone and in `tiny`; + `tests/host/native_wire` runs the vault without P-256, with and without an + ECC attestation key. + ## Build selection | Define | Description | Requirement | @@ -176,10 +263,15 @@ build `full` only, because their checks assert both guests. | `WT_ENGINE_HSM` | Legacy engine selector; unset by default. `0` maps to `WT_ENGINE=native` and `1` maps to `WT_ENGINE=hsm` when the public selector is not supplied. The build also derives this internal value from `WT_ENGINE`. | Prefer `WT_ENGINE` for new builds and do not supply conflicting selectors. The guest and Secure image must select the same engine. | | `WT_ATTEST_COSE` | Build the COSE attestation token service; default `1`. CI compile-checks `0`, and builds each port with its `port.json` `attest_cose` value. | `1` requires the wolfCOSE submodule and the configured attestation key backend. | | `WT_SECURE_PSA` | When `1`, serve PSA Crypto from the Secure image: wolfPSA runs in the crypto partition and the guest links the PSA client instead of wolfPSA. Default `1` with the native engine and `0` with wolfHSM; a port may default it to `0` in its `mk/target-.mk`. See [Crypto Engines](Crypto-Engines.md#psa-crypto-in-the-secure-image-wt_secure_psa1). | `1` requires `WT_ENGINE=native`; build every guest with the Secure image's value. | -| `WT_SECURE_PSA_PROFILE` | Algorithm set of a `WT_SECURE_PSA=1` image: `compat` (default), `standard`, `lean` or `symmetric`. | Any other value stops the build. | +| `WT_PROFILE` | Build profile: `tiny`, `small`, `default` (default) or `extended`. Sets the add-on defaults, `WT_SECURE_PSA_PROFILE` and `WT_INTERFACE_PROFILE`; see [Build profiles](#build-profiles). | Any other value stops the build. | +| `WT_SECURE_PSA_PROFILE` | Algorithm set of a `WT_SECURE_PSA=1` image: `tiny`, `small`, `default` or `extended`; follows `WT_PROFILE` unless set. | Any other value stops the build. | +| `WT_ATTEST_KEY` | Attestation key type: `ecc` (P-256, COSE_Sign1) or `hmac` (HMAC-SHA256, COSE_Mac0). Default `ecc`; `tiny` sets `hmac`. See [ECC options](#ecc-options). | `hmac` requires the native engine and a key from the port. Any other value stops the build. | +| `WT_ATTEST_DEV_KEY` | With `WT_ATTEST_KEY=hmac`, link the public development key of the reference boards; default `1`, with a build warning. | A product sets `0` and supplies `wt_port_attest_hmac_key()`. | +| `WT_VAULT_ECC` | Vault P-256 key operations; default `1`, `tiny` sets `0`. `0` returns `PSA_ERROR_NOT_SUPPORTED` for them. | `0` requires the native engine. Any other value stops the build. | | `WT_PSA_POOL_BYTES` | Make variable: size of the crypto partition's private wolfPSA pool, split evenly into one arena per guest; empty keeps 2,048 bytes per guest. | A smaller arena fails calls that hold more with `PSA_ERROR_INSUFFICIENT_MEMORY`; below 1,536 bytes per guest stops the build. A pool past the crypto partition's band fails the link. | | `WT_PSA_KEY_SLOTS`, `WT_PSA_OP_SLOTS` | Make variables: volatile keys and live operations the Secure PSA service tracks, split evenly across the guests; empty keeps `16` and `8`. | Fewer slots than guests, more than 256 operation slots, or a non-number stops the build. Each slot's state is allocated from `WT_PSA_POOL_BYTES`. | -| `WT_WOLFCRYPT_SP_ASM` | Enable wolfCrypt SP Cortex-M assembly; default `0`, the portable C `sp_c32.c`, which is smaller. `1` trades flash for faster ECC and, on the native engine, raises the crypto partition stack from 5 KiB to 9 KiB for its deeper P-256 verify. | `1` requires compatible Armv8-M assembly sources and toolchain. | +| `WT_WOLFCRYPT_SP_ASM` | Enable wolfCrypt SP Cortex-M assembly; default `0`, the portable C `sp_c32.c`, which is smaller. `1` trades flash for faster ECC and, on the native engine, raises the crypto partition stack to 9 KiB in every profile (from 5 KiB, or 6 KiB in `extended`) for its deeper P-256 verify. | `1` requires compatible Armv8-M assembly sources and toolchain. | +| `WT_AEAD` | AES-256 AEAD of the vault encrypt service and sealed storage, and the one PSA AEAD of the `tiny` and `small` Secure PSA profiles: `gcm` or `ccm`, both with a 12-byte nonce and 16-byte tag. Empty picks `ccm` for the `tiny` and `small` Secure PSA profiles, where the vault shares the one PSA AEAD, and `gcm` for every other build, `WT_SECURE_PSA=0` included. `default` and `extended` offer both through PSA either way. CCM carries no GHASH, so `small` is 1,440 bytes smaller with `ccm` than with `gcm` on the STM32H563. | Data sealed or encrypted under one setting does not open under the other, so changing it on a deployed device means re-provisioning its sealed store and re-encrypting vault data. Any other value stops the build. | | `WT_WOLFCRYPT_ARMASM` | Enable additional wolfCrypt Thumb-2 assembly; default `0`, portable C AES with small tables that touches every table line on each lookup. `1` trades flash for faster AES and SHA-256. | `1` requires a compatible GNU Arm toolchain and `WT_SECURE_PSA=0`: the Thumb-2 AES uses lookup tables and is not constant time, which wolfPSA refuses, and the vault seal key runs on it. [`WT_SHA256_FAST`](#wt_sha256_fast-unrolled-sha-256) picks the SHA-256 transform either way. | | `WT_WOLFCRYPT_STM32_HASH` | STM32 HASH acceleration selector; default `0`. | Must remain `0`: the Makefile rejects other values because wolfHSM SHA state is not compatible with the peripheral representation. | | `WT_CONFORMANCE` | When `1`, select the manifest and sources used by Arm PSA API validation. | Use only for conformance builds; the default production manifest is selected at `0`. | @@ -233,7 +325,7 @@ PSA is the default application API. These select TPM 2.0 or PKCS#11 instead; | --- | --- | --- | | `CONFIG_TPM` | `y` adds `SERVICE_TPM` and its manifest overlay, running wolfTPM's firmware TPM in its own partition; default `n`. | Excludes `CONFIG_PKCS11`, `CONFIG_VNET` and `WT_CONFORMANCE`. The port must list `tpm` in its `port.json` `build.variants`. `WT_SECURE_PSA` defaults to `0`, and `1` stops the build. | | `CONFIG_PKCS11` | `y` adds `SERVICE_PKCS11` and its manifest overlay, running wolfPKCS11 in its own partition; default `n`. | Excludes `CONFIG_TPM`, `CONFIG_VNET` and `WT_CONFORMANCE`. The port must list `pkcs11` in `build.variants`. `WT_SECURE_PSA` as for `CONFIG_TPM`. | -| `WT_INTERFACE_PROFILE` | Operation set the TPM 2.0 or PKCS#11 service exports: `default` (RNG, SHA-256, P-256) or `full`. `WT_INTERFACE_CONFIG`, `WT_INTERFACE_ENABLE` and `WT_INTERFACE_DISABLE` edit it. See [Interface Profiles](Interface-Profiles.md). | Read only when `CONFIG_TPM` or `CONFIG_PKCS11` is `y`. Applications must be built with the same profile. | +| `WT_INTERFACE_PROFILE` | Operation set the TPM 2.0 or PKCS#11 service exports: `default` (RNG, SHA-256, P-256) or `extended`, following `WT_PROFILE` (`extended` for `extended`, `default` otherwise). `WT_INTERFACE_CONFIG`, `WT_INTERFACE_ENABLE` and `WT_INTERFACE_DISABLE` edit it. See [Interface Profiles](Interface-Profiles.md). | Read only when `CONFIG_TPM` or `CONFIG_PKCS11` is `y`. Applications must be built with the same profile. | | `WT_INTERFACE_LOCAL_PROVIDER` | Internal: `1` builds the provider's wolfCrypt into the interface partition with its symbols renamed apart from the crypto partition's copy. `mk/arch-armv8m.mk` sets it. | Not a user setting. | | `WT_PKCS11_PIN_MAX_FAILURES` | Consecutive wrong user or SO PINs before that PIN locks; empty keeps `3`. | Must be a positive integer. | | `WT_PKCS11_TEST_PBKDF2_ITERATIONS` | Emulator only: lowers the PIN PBKDF2 count from 600,000. | Never set it for a product image; the footprint script refuses it. | @@ -251,10 +343,10 @@ command-line option. | `WOLFCRYPT_ONLY` | Builds only wolfCrypt functionality. | Fixed for the Secure image. | | `NO_WOLFSSL_MEMORY` | Removes the wolfSSL allocator layer. | Fixed for the Secure image. | | `WOLFSSL_NO_MALLOC` | Rejects accidental dynamic allocation paths. | Fixed for the Secure image; Secure code must use static or stack storage. | -| `HAVE_ECC` | Enables the configured ECC implementation. | The reference image uses P-256 operations. | -| `HAVE_AESGCM` | Enables AES-GCM. | Required by Protected Storage sealing. | +| `HAVE_ECC` | Enables the configured ECC implementation. | P-256 only. Undefined, with `NO_BIG_INT` set in its place, when no feature of the build uses ECC ([ECC options](#ecc-options)), as in the `tiny` profile. | +| `HAVE_AESGCM` | Enables AES-GCM. | Required by Protected Storage sealing unless `WT_AEAD=ccm`, which needs `HAVE_AESCCM` instead. | | `NO_ASN` | Native engine only: drops wolfCrypt ASN.1. | The native engine signs, verifies and imports keys in raw form; the wolfHSM server keeps ASN for its DER keystore. | -| `NO_AES_DECRYPT`, `HAVE_AESGCM_DECRYPT` | Native engine only: drop the AES inverse key schedule and decrypt tables but keep `wc_AesGcmDecrypt`. | Native AES is GCM only, which runs the block cipher forward for both seal and unseal. | +| `NO_AES_DECRYPT`, `HAVE_AESGCM_DECRYPT` | Native engine only: drop the AES inverse key schedule and decrypt tables but keep `wc_AesGcmDecrypt`. | GCM runs the block cipher forward for both seal and unseal. `WT_AEAD=ccm` undefines `NO_AES_DECRYPT`, which wolfCrypt's CCM decrypt is compiled under, though it also runs forward. | | `HAVE_HKDF` | Enables HKDF. | Required by linked wolfHSM/wolfCrypt code paths. | | `HAVE_HASHDRBG` | Enables the HashDRBG. | Requires the target `CUSTOM_RAND_GENERATE_BLOCK` entropy callback. | | `NO_RSA` | Excludes RSA from the Secure profile. | Fixed for the reference image. | diff --git a/docs/PKCS11.md b/docs/PKCS11.md index d76834630..8a3a8a2ca 100644 --- a/docs/PKCS11.md +++ b/docs/PKCS11.md @@ -44,7 +44,7 @@ PKCS#11 uses the same `WT_ENGINE=native` (default) or `WT_ENGINE=hsm` selector as PSA. Native needs no wolfHSM crypto. The application may run bare metal or under an RTOS; the Secure service uses wolfTrust's existing runtime. `WT_INTERFACE_PROFILE=default` selects the RNG/SHA-256/P-256 default operation -set; `full` retains the broader set. Individual operations and mechanisms are +set; `extended` retains the broader set. Individual operations and mechanisms are configurable through [operation profiles](Interface-Profiles.md). [Footprint](Footprint.md#tpm-20-and-pkcs11) has the measured Secure image and @@ -61,10 +61,10 @@ Run the application suite and the isolation scenario under M33MU: ```sh WT_ENGINE=hsm tests/target/run_suite.sh mimxrt700 pkcs11 pkcs11neg -WT_ENGINE=native WT_PROFILE=full tests/target/run_suite.sh mcxn947 pkcs11 +WT_ENGINE=native WT_PROFILE=extended tests/target/run_suite.sh mcxn947 pkcs11 ``` -The default profile runs the `profile` suite; `full` runs all four groups in +The default profile runs the `profile` suite; `extended` runs all four groups in one authenticated boot. `WT_PKCS11_SUITE=core|objects|crypto|negative` builds one group for focused debugging. @@ -113,7 +113,7 @@ The embedded application suite covers: - invalid arguments, handles, state transitions, and signatures; - user PIN lockout after repeated wrong PINs, and SO recovery. -The full profile requires all 40 cases through the real proxy, service, and +The extended profile requires all 40 cases through the real proxy, service, and selected engine. The default profile runs nine cases for its selected operations. This is API-level runtime evidence, not a cross-compile-only check. ## PIN attempt limit @@ -197,6 +197,6 @@ wiping, handler failures, reconnection, and prevention of duplicate execution. The M33MU workflow runs `pkcs11` and `pkcs11neg` on every port, each engine the port builds, and each profile the port registers, from the port registry's -`m33mu.groups`: nine default-profile cases and 40 full-profile cases. The +`m33mu.groups`: nine default-profile cases and 40 extended-profile cases. The STM32L562 runs the default profile only. The cross-compile workflow builds the `CONFIG_PKCS11=y` Secure image on every port and engine. diff --git a/docs/Porting.md b/docs/Porting.md index cb5f3a5d4..1e6bbd1f0 100644 --- a/docs/Porting.md +++ b/docs/Porting.md @@ -156,7 +156,7 @@ firmware, the linker script, the layout check, the guest builds and the host fixtures cannot disagree (`tests/host/layout_config` proves it for every registered port). -Level 3 is claimed for a port only when its full M33MU tier runs every +Level 3 is claimed for a port only when its M33MU `all` tier runs every scenario in `L3_REQUIRED` (`tests/target/lib/scenario_matrix.py`). A scenario a port cannot run yet goes in that port's `l3_exempt` map with the open issue that tracks it; `scenario_matrix.py --selftest`, run in CI, fails on a @@ -303,6 +303,30 @@ never in reused memory). A fill never serves a word an earlier request saw. `tests/host/h5_rng`, `rt700_trng` and `mcxn947_rng` prove this on each driver over a model of its device. +### Attestation key + +A `WT_ATTEST_KEY=hmac` image (the `tiny` profile) authenticates its +attestation tokens with a 32-byte HMAC-SHA256 key the verifier also holds, +so the port supplies it: + +```c +int wt_port_attest_hmac_key(uint8_t* key, size_t keySize); +``` + +It runs with a privileged thread at boot and again when the attestation +partition restarts, copies the key into `key` and returns `0`; any other +return leaves the device with no key, and every token request then fails +closed. Read the key from one-time-programmable storage or derive it from a +hardware unique key, and keep it stable for the life of the device: the +token's Instance ID is derived from it. + +The reference ports link `port/common/attest_dev_key.c`, a fixed public key, +under `WT_ATTEST_DEV_KEY=1` (the default, with a build warning). A product +port builds with `WT_ATTEST_DEV_KEY=0`, adds its own source with this +function to `TARGET_EXTRA_SRCS`, and gives that object an owner line. +`WT_ATTEST_KEY=ecc` images need none of this: the key is generated on the +device and its public half is exported. + ### Platform hooks `port/common/armv8m/platform_armv8m.c` owns `wt_platform_init` and every @@ -414,7 +438,7 @@ never a pass. | G2 host | `make test`, which runs `tests/host/port_flash` over the port's model and its own suites | every suite passes and `docs/Ports.md is current` | | G3 layout | `TOOLPREFIX=arm-none-eabi- tools/check-layout-rebuild.sh ` | `PASS: layout rebuild ()` | | G4 emulator smoke | `make test-target TARGET=` inside the port's CI image | `PASS: target/all` | -| G5 emulator full | `WT_TIER=full make test-target TARGET=` on both engines | `PASS: target/all` twice | +| G5 emulator all | `WT_TIER=all make test-target TARGET=` on both engines | `PASS: target/all` twice | | G6 hardware minimum | `make test-hardware TARGET=` on the probe host | `PASS: hardware/all`, evidence under `logs/-hw/` | | G7 provisioning | `TARGET= tests/target/provisioning/provisioning_ctrl.sh status`, then `discover` | both exit 0 and nothing is written | diff --git a/docs/Ports.md b/docs/Ports.md index ecc89b65d..7a9ee3a31 100644 --- a/docs/Ports.md +++ b/docs/Ports.md @@ -13,7 +13,7 @@ regenerate this page instead of editing it. ## Emulator scenarios -Every port's full tier is in `port.json` (`m33mu.groups`). The smoke tier +Every port's all tier is in `port.json` (`m33mu.groups`). The smoke tier runs on every pull request for a port whose CI label is optional; a port marked label only above runs only under its label. Capabilities a port declares absent exempt the scenarios that need them and mark their diff --git a/docs/STM32H5-Guide.md b/docs/STM32H5-Guide.md index 547f23ce9..4808b3ba4 100644 --- a/docs/STM32H5-Guide.md +++ b/docs/STM32H5-Guide.md @@ -142,7 +142,7 @@ make test-hardware TARGET=stm32h563 WT_HW_TIER=qualification tests/target/run_hardware.sh stm32h563 positive ``` -The hardware runner builds the `full` profile, so its scenarios launch two +The hardware runner builds the `extended` profile, so its scenarios launch two guests and include Firmware Update; it refuses any other `WT_PROFILE`. When the host that owns the board has no cross toolchain, build in the diff --git a/docs/STM32L562-Guide.md b/docs/STM32L562-Guide.md index bbfb17e25..6c5abb598 100644 --- a/docs/STM32L562-Guide.md +++ b/docs/STM32L562-Guide.md @@ -26,7 +26,7 @@ RDP. The only RDP write is a typed regression back to level 0. wolfBoot's `hal/stm32l5_lifecycle.h`, and the emulator profile checks the copy matches the pinned wolfBoot before every boot. - **Emulator:** on this layout, under m33mu 268fbef3 with the carried patch, the - smoke tier passes 6 of 6. Across two full-tier runs every one of the 46 + smoke tier passes 6 of 6. Across two `all`-tier runs every one of the 46 scenarios has passed. The patch's FLASH TrustZone model also has its own unit test, which the profile runs before each boot. - **Board:** none for this layout. An earlier layout ran on a DK, with the diff --git a/docs/Security-Model.md b/docs/Security-Model.md index 54e8b0e82..4755aeb30 100644 --- a/docs/Security-Model.md +++ b/docs/Security-Model.md @@ -319,7 +319,7 @@ ITS supports the core set/get/get-info/remove interface and the write-once flag. Protected Storage always adds sealing even when a caller supplies `NO_CONFIDENTIALITY` or `NO_REPLAY_PROTECTION` hints. `psa_ps_get_info()` reports the protection applied to the object. -Sealing uses AES-256-GCM with: +Sealing uses AES-256-GCM, or AES-256-CCM when `WT_AEAD` is `ccm`, with: - a device-local non-exportable key stored in the shared Secure NVM store; - the object label as authenticated data; diff --git a/docs/Services.md b/docs/Services.md index cecd23804..ce1e3cc83 100644 --- a/docs/Services.md +++ b/docs/Services.md @@ -15,7 +15,7 @@ PKCS#11 service, an application API offered instead of PSA Crypto. | `SERVICE_ITS` | `0x1003` | Yes | PSA Internal Trusted Storage | | `SERVICE_PS` | `0x1004` | Yes | PSA Protected Storage | | `SERVICE_FWU` | `0x1005` | Yes, `WT_FWU=1` | PSA Firmware Update staging for wolfBoot | -| `SERVICE_HSM` | `0x0106` | Yes | Copied request relay for the selected native or wolfHSM crypto engine, plus the attestation partition's signing door; with `WT_SECURE_PSA=1` it also serves the PSA Crypto API | +| `SERVICE_HSM` | `0x0106` | Yes | Copied request relay for the selected native or wolfHSM crypto engine, plus the attestation partition's signing door (not built with `WT_ATTEST_KEY=hmac`); with `WT_SECURE_PSA=1` it also serves the PSA Crypto API | | `SERVICE_VNET` | `0x0107` | Yes, optional | Secure virtual Ethernet switch implemented by wolfTrust for optional Non-secure wolfIP guests | | `SERVICE_TPM` | `0x0108` | Yes, `CONFIG_TPM=y` | wolfTPM firmware TPM 2.0 serving one TPM 2.0 command frame per call | | `SERVICE_PKCS11` | `0x0109` | Yes, `CONFIG_PKCS11=y` | wolfPKCS11 token serving the PKCS#11 `C_*` API through the client proxy | @@ -123,7 +123,8 @@ Every Protected Storage object created through the public shim is likewise limited to 512 bytes. The underlying Secure vault still uses a 1024-byte object buffer and caps one copied vault response at 1000 bytes. -Every stored object is AES-256-GCM sealed in the vault under a device-local +Every stored object is AES-256-GCM sealed (AES-256-CCM when `WT_AEAD` is +`ccm`, the default of the `tiny` and `small` Secure PSA profiles) in the vault under a device-local non-exportable key in the shared NVM store. A persisted write counter supplies the nonce and the object label is authenticated data. Confidentiality and replay-protection hint flags do not weaken storage: Protected Storage still @@ -135,9 +136,10 @@ object's write-once flag. `SERVICE_ATTEST` implements the token and exact-size API operations from PSA Initial Attestation 1.0. It accepts a 32-, 48-, or 64-byte challenge and returns -a tagged COSE_Sign1 token signed with ES256 through an external signer backed -by the selected engine's protected attestation key. wolfCOSE performs the COSE -encoding. +a token wolfCOSE encodes. With the default P-256 attestation key +(`WT_ATTEST_KEY=ecc`) that is a tagged COSE_Sign1 signed with ES256 through an +external signer backed by the selected engine's protected attestation key; +with an HMAC key it is a COSE_Mac0, described at the end of this section. The token uses the `tag:psacertified.org,2023:psa#tfm` identifier from RFC 9783. The SPM generates a public 32-byte boot seed from the platform RNG at @@ -159,7 +161,8 @@ The EAT/PSA claim set binds: - one software component for each guest that passed launch verification. The service also supports internal call types for exact token-size and -uncompressed P-256 public-key queries. The attestation partition holds no key +uncompressed P-256 public-key queries. With a P-256 key the attestation +partition holds no key material: every signature and the public key come from `SERVICE_HSM`'s attestation door (`WT_HSM_OP_ATTEST_SIGN`, `WT_HSM_OP_ATTEST_PUBLIC_KEY`), which serves the attestation partition alone and refuses every other client. @@ -167,6 +170,17 @@ which serves the attestation partition alone and refuses every other client. only, so the attestation partition cannot use it. The private attestation key is never exported. +With `WT_ATTEST_KEY=hmac`, which the `tiny` profile sets, the token is a +tagged COSE_Mac0 authenticated with HMAC 256/256 instead. The key is the +device's 32-byte key from the port +([Porting](Porting.md#attestation-key)); the privileged boot path copies it +into the attestation partition's own data band, which no guest and no other +partition can read at isolation level 3. The Instance ID is +`0x01 || SHA-256(SHA-256(key))`, the public-key query returns +`PSA_ERROR_NOT_SUPPORTED`, the attestation door is not built, and no call +exports the key. A verifier needs the same key, so an HMAC token +authenticates the device only to parties that hold it. + ## Firmware Update `SERVICE_FWU` is an add-on: it exists only in images built with `WT_FWU=1` diff --git a/docs/TF-M-Compatibility.md b/docs/TF-M-Compatibility.md index 984165b68..af8178c20 100644 --- a/docs/TF-M-Compatibility.md +++ b/docs/TF-M-Compatibility.md @@ -17,18 +17,18 @@ options. These are local builds, not published reference figures. | Image | Flash | Secure RAM | | --- | ---: | ---: | -| wolfTrust Secure runtime, native default | 70,432 bytes | 45,280 bytes | +| wolfTrust Secure runtime, native default | 70,304 bytes | 45,280 bytes | | TF-M v2.3.1 `tfm_s`, level 3 | 79,680 bytes | 45,728 bytes | | wolfBoot, STM32L5 secure application handoff | 27,216 bytes | 2,104 bytes | | TF-M BL2 (MCUboot, EC-P256) | 38,744 bytes | 27,408 bytes | -| Chain: wolfBoot + wolfTrust | 97,648 bytes | | +| Chain: wolfBoot + wolfTrust | 97,520 bytes | | | Chain: BL2 + TF-M | 118,424 bytes | | -The wolfTrust runtime is 9,248 bytes smaller in flash and 448 bytes smaller -in Secure RAM; the boot chain is 20,776 bytes smaller in flash. Both RAM +The wolfTrust runtime is 9,376 bytes smaller in flash and 448 bytes smaller +in Secure RAM; the boot chain is 20,904 bytes smaller in flash. Both RAM figures include every partition stack (see Methodology). The bootloader's RAM is reused by the runtime, so the RAM figures are not summed. The -cross-compile workflow fails if any port's lean native default image grows +cross-compile workflow fails if any port's native `WT_SECURE_PSA=0` image grows past TF-M's 79,680 bytes of flash or 45,728 bytes of Secure RAM, plus the RAM code band (`WT_RAMFUNC_SIZE`) of a port that runs code from RAM. @@ -44,12 +44,13 @@ feature the default leaves out comes back with one Make variable; see The crypto split matches TF-M's: both serve PSA Crypto from a Secure crypto partition, which wolfTrust's native default does with `WT_SECURE_PSA=1` (see [Crypto Engines](Crypto-Engines.md#psa-crypto-in-the-secure-image-wt_secure_psa1)). -That default is larger than TF-M. On the STM32H563 the `standard` profile, the -closest to TF-M's Medium set, is -103,223 bytes of flash and 48,880 bytes of Secure RAM: 23,543 bytes more flash -and 3,152 bytes more RAM than the TF-M image above. 12,007 bytes of the flash -gap are the crypto stack (52,485 against 40,478 for TF-M's Crypto partition -and Mbed TLS); the rest is the storage and SPM code outside it. The +That default is larger than TF-M. On the STM32H563 the `default` profile is +94,343 bytes of flash and 47,344 bytes of Secure RAM: 14,663 bytes more flash +and 1,616 bytes more RAM than the TF-M image above. The `small` profile (CCM +as the one AEAD) is the closest to TF-M's Medium set: its crypto stack is +40,443 bytes against 40,478 for TF-M's Crypto partition and Mbed TLS, where +`default`'s is 43,567. The rest of the gap is the storage and SPM code +outside the crypto stack. The `WT_SECURE_PSA=0` opt-out, which runs wolfPSA in the Non-secure guest instead, stays below TF-M, and CI holds it to TF-M's flash and RAM. @@ -72,12 +73,12 @@ Secure RAM = all RAM the Secure image reserves, partition stacks included length. - Neither figure counts Secure RAM a port leaves free. -- wolfTrust: the STM32L562 port built with its defaults (native engine, - LTO, one guest): `make TARGET=stm32l562 secure-image` in +- wolfTrust: the STM32L562 port, built with its defaults (native engine, LTO, + one guest): `make TARGET=stm32l562 secure-image` in `ghcr.io/wolfssl/wolfboot-ci-m33mu:v1.25`. With `WT_SECURE_PSA=0`, the same - defaults give 70,940 bytes of flash and 45,296 bytes of Secure RAM for - `TARGET=stm32h563` in this tree; the `WT_SECURE_PSA=1` default gives 110,005 - and 48,880. + defaults give 70,780 bytes of flash and 45,296 bytes of Secure RAM for + `TARGET=stm32h563` in this tree; the `WT_SECURE_PSA=1` default gives 94,343 + and 47,344. - wolfBoot: `config/examples/stm32l5-tz-wolftrust.config` (ECC256, SHA256, `WOLFBOOT_SECURE_APP=1`). - TF-M: v2.3.1, platform `stm/stm32l562e_dk`, `TFM_ISOLATION_LEVEL=3`, diff --git a/docs/TPM.md b/docs/TPM.md index d2f6c712a..12dcf93eb 100644 --- a/docs/TPM.md +++ b/docs/TPM.md @@ -30,7 +30,7 @@ refused). The application reaches the SPM through the CMSE gateway. All three application interfaces use `WT_ENGINE=native` (default) or `WT_ENGINE=hsm`. For TPM 2.0 the engine changes only the Secure image. `WT_INTERFACE_PROFILE=default` exports RNG, SHA-256, P-256 key generation, -signing, verification, and their required lifecycle commands. `full` retains +signing, verification, and their required lifecycle commands. `extended` retains the broader supported command set, including PCR operations. Individual commands can be added or removed with [operation profiles](Interface-Profiles.md). @@ -39,7 +39,7 @@ make TARGET=mimxrt700 CONFIG_TPM=y WT_ENGINE=native secure-image make -C tests/firmware/interface-guest TARGET=mimxrt700 WT_INTERFACE=tpm WT_ENGINE=native tests/target/run_suite.sh mimxrt700 tpm tpmneg -WT_ENGINE=hsm WT_PROFILE=full tests/target/run_suite.sh stm32h563 tpm tpmneg +WT_ENGINE=hsm WT_PROFILE=extended tests/target/run_suite.sh stm32h563 tpm tpmneg ``` Every Cortex-M33 port registers the `tpm` build variant in its `port.json`; @@ -133,6 +133,6 @@ FF-M runtime and checks bounds, caller identity, wiping, and no replay. The M33MU workflow runs `tpm` and `tpmneg` on every port, each engine the port builds, and each profile the port registers, from the port registry's `m33mu.groups`. The STM32L562 runs the default profile only: its interface -layout has no update partition for the full profile's `WT_FWU=1`. The +layout has no update partition for the extended profile's `WT_FWU=1`. The cross-compile workflow builds the `CONFIG_TPM=y` Secure image on every port and engine, and the host manifest suite validates its rendered manifest. diff --git a/docs/Testing.md b/docs/Testing.md index a085fbc4d..99ea8e3a8 100644 --- a/docs/Testing.md +++ b/docs/Testing.md @@ -37,8 +37,8 @@ isolation, vault and storage services, attestation and COSE integration, firmware update, runtime remeasurement, linked Secure layout, VNET, public PSA headers, boot-handoff record consumption, and negative paths. The manifest_ports suite generates every `port/*/manifest*.json` with that -port's build arguments, for the default profile (update partition left out) -and the `full` profile, and runs each through the boot-time validator, the +port's build arguments, for the `default` profile (update partition left out) +and the `extended` profile, and runs each through the boot-time validator, the port binding, and FF-M activation, since default images validate the manifest only at build time. `tests/host/manifest/test_generator.py` checks that each manifest the boot-time checks reject also fails generation. @@ -47,12 +47,26 @@ lifecycle decisions against the production scheduler with simulated architecture operations. The attestation IAK suite runs wolfHSM NVM with both the default 8-byte and STM32H5 16-byte flash programming units. +The attestation_hmac suite issues tokens through the production encoder with +an HMAC key (`WT_ATTEST_KEY=hmac`), built with the `tiny` profile's own +wolfCOSE defines and a wolfCrypt with no ECC or big-number code. It checks +each COSE_Mac0 with an HMAC computed in the test, which it first proves on +the RFC 9783 Appendix A.2 token, and checks the Instance ID, the nonce, the +predicted size, a wrong key, a changed byte and a port that has no key. The +attestation_service suite runs its FF-M dispatch a second time built for an +HMAC key and checks that the public-key query is not served. The +attest_restore suite takes the attestation partition's restart hook from the +production partition table, wipes the partition's state as a restart does, +and checks that the hook loads the key again and tokens verify, and that a +restart with no key or no retained handoff issues none. On a target, +`tinyattest` runs the same restart for real. The psa_secure_crypto suite runs the PSA client against the Secure PSA service in a separate process: cross-client key and operation isolation, stale handles after a service restart, persistent keys, quotas, per-guest pool arenas, one-shots split over several messages and AEAD tag failures. `run` builds and runs it once per `WT_SECURE_PSA_PROFILE`, checking what each profile keeps and what it refuses with -`PSA_ERROR_NOT_SUPPORTED`; `run-one PROFILE=` runs one. Its `sanitize` +`PSA_ERROR_NOT_SUPPORTED`, and once more for `tiny` with no ECC in wolfCrypt +(`NO_ECC=1`), as `WT_PROFILE=tiny` links it; `run-one PROFILE=` runs one. Its `sanitize` and `valgrind` targets rerun it under ASan/UBSan and Valgrind. Additional host checks: @@ -125,20 +139,20 @@ WT_ENGINE=hsm make test-target ``` It runs the port's smoke tier from its `port.json` (listed in -[Ports](Ports.md)); `WT_TIER=full` runs every scenario. Detection accepts `m33mu` on +[Ports](Ports.md)); `WT_TIER=all` runs every scenario. Detection accepts `m33mu` on `PATH` or a path in `M33MU`; a port whose emulator carries a model patch (`M33MU_PATCH` in its profile) builds its pinned emulator instead. If the emulator is unavailable, the target reports a skip rather than a pass. -Each tier runs on both build profiles, the lean default first, then `full`, -with their logs under `logs/default` and `logs/full`; `WT_PROFILE=default` or -`WT_PROFILE=full` runs one. The default profile runs +Each tier runs on the `default` build profile first, then `extended`, with +their logs under `logs/default` and `logs/extended`; `WT_PROFILE=default` or +`WT_PROFILE=extended` runs one. The `default` profile runs the image an unqualified `make` builds: its one-guest `positive`, the level 3 scenarios, the native wire key ops, and the SP fault, panic, attestation, launch, rollback, re-measurement, manifest, SP budget and peripheral negatives, plus the silicon-revision negative on the STM32H563 (see [Build profiles](Macros.md#build-profiles)). Each port's -`port.json` lists its lean set under `m33mu.default`; the two-guest, VNET, -conformance and update scenarios run only on `full`. +`port.json` lists its `default` set under `m33mu.default`; the two-guest, VNET, +conformance and update scenarios run only on `extended`. Additional focused runs use: @@ -162,7 +176,7 @@ firmware update, manifest rejection, GTZC behavior, and VNET paths. `restartidle` runs the recovery check on the one-guest default image. It requires every allowed relaunch and the final terminal verdict (BKPT 0x7d, -no guest left). The full tier runs it with both crypto engines on every port. +no guest left). The `all` tier runs it with both crypto engines on every port. It also runs `tests/target/test_systick_idle.sh`, which executes the production Armv8-M timer code with modeled Non-secure timer registers and real Secure SysTick interrupts. The check covers timer configuration and pending-tick @@ -275,10 +289,12 @@ requires both isolation faults and recovery. The full CI scenario list adds `engine: [native, hsm]` as a matrix dimension. Every scenario runs with both engines except the engine-specific ones listed in `ENGINE_ONLY` in `tests/target/lib/scenario_matrix.py`: the wolfHSM-only -scenarios run under hsm only, and `nativewire` and `nativewireasm`, which -drive the native wire, under native only. +scenarios run under hsm only, and `nativewire`, `nativewireasm` and +`nativewiresmall` (the `small` PSA profile's smaller crypto stack), which drive the +native wire, and `tinyattest` (an HMAC attestation key, which the wolfHSM +engine refuses), under native only. The generator is the source of truth for the exact list: -`python3 tests/target/lib/scenario_matrix.py --port stm32h563 --tier full --json`. +`python3 tests/target/lib/scenario_matrix.py --port stm32h563 --tier all --json`. `hsmattackneg` drives the raw wolfHSM protocol from a compromised-guest probe. It checks that a forged wolfHSM client ID cannot select the attestation key and @@ -337,8 +353,12 @@ runs and exempts the rest with a reason. Beyond the families above: with a cross-key refusal, RNG, AES-CTR, and an attestation token verified against the IAK and wolfBoot's measurement), `bothiso` (a forged handle, an oversized vector, a vector in the peer window and an unknown SID refused), - `attestneg`, and `fwustage` (a candidate staged through SERVICE_FWU, armed, - and restored READY). + `attestneg`, `fwustage` (a candidate staged through SERVICE_FWU, armed, + and restored READY), and `tinyattest`. `tinyattest` builds `WT_PROFILE=tiny WT_SECURE_PSA=1`, + faults the attestation partition once so it restarts on a reset band, and + has the guest verify the COSE_Mac0 under the development key (Instance ID + included), reject a tampered token, and see P-256 refused; the judge also + checks that no P-256 symbol is linked. - The remaining level 3 negatives (`deputyneg`, `hsmpinneg`, `hsmfaultneg`, `periphspneg`) run the PSA guest in both windows, and guest 0 ends the run on its breakpoint once its lifecycle is done; `manifestneg2`, @@ -477,9 +497,9 @@ engines for each port whose CI label is optional; a port marked label only in on manual dispatch (with a `port` input), and on a pull request that carries the port's label, `ci:all`, or `ci:m33mu`. The scenario groups per port and tier are in its `port.json`; `make test-target TARGET=` runs the same -smoke tier locally and `WT_TIER=full` every scenario. Every tier runs on both -build profiles, and the level 3 bar (`l3_gaps()` in the matrix selftest) -must hold on `default` and on `full`. +smoke tier locally and `WT_TIER=all` every scenario. Every tier runs on the +`default` and `extended` build profiles, and the level 3 bar (`l3_gaps()` in +the matrix selftest) must hold on both. ### Running M33MU off a pull request diff --git a/docs/Threat-Model.md b/docs/Threat-Model.md index 00539db1d..baf1e1dce 100644 --- a/docs/Threat-Model.md +++ b/docs/Threat-Model.md @@ -83,7 +83,7 @@ images. | Cross-guest key use | The SPM-stamped identity selects the native vault sub-owner; the hsm relay maps guest `N` to forced wolfHSM client ID `N + 1`; with `WT_SECURE_PSA=1` every PSA key and operation is owned by the SPM-stamped client ID and another guest's handle is rejected. | | Direct NVM access through a crypto protocol | The native format exposes no general NVM operation; the hsm relay rejects wolfHSM NVM message groups. | | Storage object confusion | The vault namespaces objects by front-end partition, stamped client, and UID, and storage requests cannot use its reserved key-object type. | -| Protected Storage disclosure or edit | AES-256-GCM sealing, a non-exportable device key, authenticated labels, and checked NVM operations. | +| Protected Storage disclosure or edit | AES-256-GCM sealing (CCM when `WT_AEAD` is `ccm`), a non-exportable device key, authenticated labels, and checked NVM operations. | | Stale sealed-object replay | Each sealed write advances a persisted counter used in its nonce; the current slot counter authenticates reads. | | Firmware downgrade | Outside assembly-and-test and provisioning, boot checks the Secure-image and recorded-guest floors before first guest execution. Firmware Update separately checks the candidate Secure-image version against its boot-loaded floor before arming wolfBoot. | | Malformed update | Bounded aligned writes, staged-image header verification, version binding, and wolfBoot authentication before commit. | diff --git a/include/psa/protected_storage.h b/include/psa/protected_storage.h index 1b06e0ab6..48d51e351 100644 --- a/include/psa/protected_storage.h +++ b/include/psa/protected_storage.h @@ -19,7 +19,7 @@ */ /* PSA Protected Storage API (SRC-PSA-STORAGE). Served by SERVICE_PS: every - * object is AES-GCM sealed under a device-unique wolfHSM key with default-on + * object is AES-256 AEAD sealed under a device-unique wolfHSM key with default-on * rollback protection (WT-FFM-0048) — confidentiality and replay protection * are not optional features in wolfTrust. Definitions arrive with the NSPE * client shim (P4-S6); Secure-side dispatch is storage_service.c. */ diff --git a/include/wolftrust/services/hsm.h b/include/wolftrust/services/hsm.h index 4c8b70887..5a118e3ca 100644 --- a/include/wolftrust/services/hsm.h +++ b/include/wolftrust/services/hsm.h @@ -148,6 +148,7 @@ int wt_hsm_reset_guest(wt_guest_id_t guest_id); * the vault's store memory. Privileged bootstrap only. */ int wt_hsm_bind_nvm(struct whNvmContext_t* nvm); +#ifndef WT_ATTEST_KEY_hmac /* Provision or reopen the Initial Attestation Key in the wolfHSM keystore. * The private key is non-exportable and restricted to signing. */ int wt_hsm_attest_init(void); @@ -170,6 +171,7 @@ int wt_hsm_attest_sign(const uint8_t* digest, size_t digestSize, /* Return the IAK public point in X9.63 form, 0x04 followed by X and Y. */ int wt_hsm_attest_public_key(uint8_t* publicKey, size_t publicKeyCapacity, size_t* publicKeySize); +#endif /* !WT_ATTEST_KEY_hmac */ /* Gated vault backing (WT-FFM-0047): bind the shared NVM context, then * install wt_hsm_vault_backend into SERVICE_VAULT. wt_hsm_init does both; @@ -180,15 +182,30 @@ int wt_hsm_vault_init(struct whNvmContext_t* nvm); struct wt_vault_backend; extern const struct wt_vault_backend wt_hsm_vault_backend; -/* Vault sealer (WT-FFM-0048): AES-GCM confidentiality and rollback binding +/* Vault sealer (WT-FFM-0048): AEAD confidentiality and rollback binding * for WT_VAULT_FLAG_SEALED objects. Operations run in the confined vault SP, * with the device-unique key kept in the shared keystore trust band. seal * writes pt_len + WT_VAULT_SEAL_TAG_LEN bytes ([ciphertext][tag]); unseal * takes ct_len >= tag length and writes ct_len - tag plaintext bytes. The - * monotonic rollback counter is the GCM nonce, so a replayed (rolled-back) + * monotonic rollback counter is the AEAD nonce, so a replayed (rolled-back) * ciphertext fails tag authentication. */ #define WT_VAULT_SEAL_TAG_LEN 16U +/* AES-256 AEAD shared by the vault encrypt service and the sealer: GCM, or + * CCM under WT_AEAD_CCM. 12-byte nonce, 16-byte tag. decrypt clears out + * on failure and reports a bad tag as PSA_ERROR_INVALID_SIGNATURE. */ +#define WT_HSM_AEAD_KEY_LEN 32U +#define WT_HSM_AEAD_NONCE_LEN 12U +#define WT_HSM_AEAD_TAG_LEN 16U +psa_status_t wt_hsm_aead_encrypt(const uint8_t* key, const uint8_t* nonce, + const uint8_t* aad, size_t aad_len, + const uint8_t* in, size_t len, uint8_t* out, + uint8_t* tag); +psa_status_t wt_hsm_aead_decrypt(const uint8_t* key, const uint8_t* nonce, + const uint8_t* aad, size_t aad_len, + const uint8_t* in, size_t len, + const uint8_t* tag, uint8_t* out); + /* Device-unique seal key + rollback counter table ids: directly above the * vault object window (0x0100..0x011F), never matched by vault lookups. */ #define WT_HSM_SEAL_KEY_ID 0x0120U @@ -207,7 +224,7 @@ typedef struct wt_vault_sealer { * are refused with PSA_ERROR_NOT_SUPPORTED. */ void wt_hsm_vault_set_sealer(const wt_vault_sealer_t* sealer); -/* wolfCrypt AES-256-GCM sealer over the device-unique key at +/* wolfCrypt AES-256 AEAD sealer over the device-unique key at * WT_HSM_SEAL_KEY_ID (generated on first boot, NONEXPORTABLE and immutable). * Only linked into builds that carry wolfCrypt. */ int wt_hsm_seal_init(struct whNvmContext_t* nvm); diff --git a/include/wolftrust/services/hsm_relay.h b/include/wolftrust/services/hsm_relay.h index 9affc509e..1c46e05a3 100644 --- a/include/wolftrust/services/hsm_relay.h +++ b/include/wolftrust/services/hsm_relay.h @@ -86,9 +86,11 @@ typedef int (*wt_hsm_attest_sign_fn)(const uint8_t* digest, size_t digest_len, typedef int (*wt_hsm_attest_public_key_fn)(uint8_t* public_key, size_t public_key_capacity, size_t* public_key_len); +#ifndef WT_ATTEST_KEY_hmac void wt_hsm_relay_set_attest_ops(int32_t attest_partition_id, wt_hsm_attest_sign_fn sign, wt_hsm_attest_public_key_fn public_key); +#endif /* Transport seam, mirroring the other services: direct gate calls on the * host, the SVC transport when scheduled on target. NULL restores default. */ diff --git a/include/wolftrust/services/initial_attestation.h b/include/wolftrust/services/initial_attestation.h index e07af5c4f..46dc5122a 100644 --- a/include/wolftrust/services/initial_attestation.h +++ b/include/wolftrust/services/initial_attestation.h @@ -39,6 +39,7 @@ #define WT_ATTEST_CHALLENGE_SIZE_64 64u #define WT_ATTEST_BOOT_SEED_SIZE 32u #define WT_ATTEST_IAK_PUBLIC_KEY_SIZE 65u +#define WT_ATTEST_HMAC_KEY_SIZE 32u #define WT_ATTEST_MAX_TOKEN_SIZE 640u /* The SPM supplies the public random value retained for the current boot. */ @@ -52,6 +53,12 @@ int wt_initial_attest_get_token(wt_guest_id_t guestId, const uint8_t* challenge, size_t challengeSize, uint8_t* token, size_t tokenCapacity, size_t* tokenSize); +#ifdef WT_ATTEST_KEY_hmac +/* WT_ATTEST_KEY=hmac: the port supplies the device's HMAC-SHA256 attestation + * key, the one its verifier holds. Called with a privileged thread at boot + * and on a partition restart; 0 fills key, anything else leaves no key. */ +int wt_port_attest_hmac_key(uint8_t* key, size_t keySize); +#else int wt_initial_attest_get_iak_public_key(uint8_t* publicKey, size_t publicKeyCapacity, size_t* publicKeySize); @@ -69,5 +76,6 @@ int wt_initial_attest_bind_hsm(wt_spm_transport_fn transport, * public-key request closes it and reconnects instead of calling a dead * handle, a PROGRAMMER ERROR the SPM would panic this partition for. */ void wt_initial_attest_hsm_restarted(void); +#endif /* WT_ATTEST_KEY_hmac */ #endif /* WOLFTRUST_SERVICES_INITIAL_ATTESTATION_H */ diff --git a/include/wolftrust/services/storage_service.h b/include/wolftrust/services/storage_service.h index 687b3f8b9..e974a67c9 100644 --- a/include/wolftrust/services/storage_service.h +++ b/include/wolftrust/services/storage_service.h @@ -32,7 +32,7 @@ * (WT-FFM-0047). Each end client's objects are namespaced by the vault under * (partition, client id, uid) via the delegated sub_owner (WT-FFM-0044). * The PS instance additionally ORs WT_VAULT_FLAG_SEALED into every request: - * AES-GCM under the device-unique wolfHSM key plus rollback binding, applied + * AES-256 AEAD under the device-unique wolfHSM key plus rollback binding, applied * inside the confined vault partition (WT-FFM-0048). */ /* psa_call request types (client face). Ops 1-4 are the shared ITS/PS core; diff --git a/include/wolftrust/services/vault_service.h b/include/wolftrust/services/vault_service.h index 1639af9a9..95deec28e 100644 --- a/include/wolftrust/services/vault_service.h +++ b/include/wolftrust/services/vault_service.h @@ -104,7 +104,7 @@ typedef struct wt_vault_nvm_avail { #define WT_VAULT_FLAG_NO_REPLAY 0x4U /* Internal flag a storage frontend ORs in (never a PSA create flag): the - * object is AES-GCM sealed under the device-unique wolfHSM key with the + * object is AES-256 AEAD sealed under the device-unique wolfHSM key with the * monotonic rollback counter as nonce (WT-FFM-0048). Sealing runs inside the * confined vault partition. */ #define WT_VAULT_FLAG_SEALED 0x10000U @@ -132,7 +132,7 @@ typedef struct wt_vault_nvm_avail { /* Fixed sizes on the key wire: P-256 private scalar / AES-256 key material * (import payload), X9.63 public point (export_public), SHA-256 digest and * raw r||s signature (sign/verify: invec[1] = [digest][sig] on verify), and - * the AES-GCM ciphertext framing [nonce][ct][tag] (encrypt/decrypt). */ + * the AES-256 AEAD ciphertext framing [nonce][ct][tag] (encrypt/decrypt). */ #define WT_VAULT_KEY_MATERIAL_LEN 32U #define WT_VAULT_KEY_PUB_LEN 65U #define WT_VAULT_KEY_DIGEST_LEN 32U diff --git a/lib/wolfPSA b/lib/wolfPSA index 9b3cf50ca..58f926975 160000 --- a/lib/wolfPSA +++ b/lib/wolfPSA @@ -1 +1 @@ -Subproject commit 9b3cf50ca68cbd18e4e38c1b5e065855e7d8bf59 +Subproject commit 58f92697503a69932cc651b33733a1bfbf829197 diff --git a/mk/common.mk b/mk/common.mk index 7ea9a2c83..21ced8844 100644 --- a/mk/common.mk +++ b/mk/common.mk @@ -161,16 +161,19 @@ endif ifeq ($(WT_ATTEST_COSE),1) SECURE_CFLAGS_COSE := -I$(WOLFCOSE_DIR)/include \ - -DWT_ATTEST_COSE=1 \ - -DWOLFCOSE_LEAN -DWOLFCOSE_ENABLE_EXT_SIGN -DWOLFCOSE_NO_LOCAL_SIGN \ - -DWOLFCOSE_ENABLE_DEPRECATED_ALGS \ - -DWOLFCOSE_NO_SIGN1_VERIFY -DWOLFCOSE_NO_ENCRYPT0 \ - -DWOLFCOSE_NO_MAC0 -DWOLFCOSE_NO_KEY_ENCODE \ - -DWOLFCOSE_NO_KEY_DECODE \ + -DWT_ATTEST_COSE=1 -DWOLFCOSE_LEAN \ + -DWOLFCOSE_NO_ENCRYPT0 -DWOLFCOSE_NO_KEY_ENCODE -DWOLFCOSE_NO_KEY_DECODE \ -DWOLFCOSE_ENABLE_EAT_PSA \ -DWOLFCOSE_ENABLE_EAT_PSA_CURRENT \ - -DWOLFCOSE_ENABLE_EAT_PSA_ISSUE \ - -DWOLFCOSE_ENABLE_EAT_PSA_SIGN1_ISSUE + -DWOLFCOSE_ENABLE_EAT_PSA_ISSUE +ifeq ($(WT_ATTEST_KEY),hmac) +SECURE_CFLAGS_COSE += -DWOLFCOSE_NO_SIGN1 -DWOLFCOSE_NO_MAC0_VERIFY \ + -DWOLFCOSE_ENABLE_EAT_PSA_MAC0_ISSUE +else +SECURE_CFLAGS_COSE += -DWOLFCOSE_ENABLE_EXT_SIGN -DWOLFCOSE_NO_LOCAL_SIGN \ + -DWOLFCOSE_ENABLE_DEPRECATED_ALGS -DWOLFCOSE_NO_SIGN1_VERIFY \ + -DWOLFCOSE_NO_MAC0 -DWOLFCOSE_ENABLE_EAT_PSA_SIGN1_ISSUE +endif endif WOLFPKCS11_COMMON_DEFS := -DWOLFPKCS11_USER_SETTINGS \ @@ -253,6 +256,43 @@ endif ifeq ($(WT_DEPUTY_NEG_PROBE),1) SECURE_CFLAGS += -DWT_DEPUTY_NEG_PROBE=1 endif +# The vault's AES AEAD, and the one PSA AEAD of small and tiny (ccm there) +WT_AEAD ?= +ifneq ($(filter-out gcm ccm,$(WT_AEAD))$(word 2,$(WT_AEAD)),) +$(error unsupported WT_AEAD='$(WT_AEAD)' (want gcm or ccm)) +endif +WT_AEAD_ONE := $(if $(filter 1,$(WT_SECURE_PSA)),$(filter small tiny,$(WT_SECURE_PSA_PROFILE))) +WT_AEAD_USED := $(or $(WT_AEAD),$(if $(WT_AEAD_ONE),ccm,gcm)) +SECURE_CFLAGS += -DWT_AEAD_$(if $(filter ccm,$(WT_AEAD_USED)),CCM,GCM) +ifneq ($(filter-out ecc hmac,$(WT_ATTEST_KEY))$(words $(WT_ATTEST_KEY)),1) +$(error unsupported WT_ATTEST_KEY='$(WT_ATTEST_KEY)' (want ecc or hmac)) +endif +ifneq ($(filter-out 0 1,$(WT_VAULT_ECC))$(words $(WT_VAULT_ECC)),1) +$(error unsupported WT_VAULT_ECC='$(WT_VAULT_ECC)' (want 0 or 1)) +endif +WT_ATTEST_DEV_KEY ?= 1 +ifneq ($(filter-out 0 1,$(WT_ATTEST_DEV_KEY))$(words $(WT_ATTEST_DEV_KEY)),1) +$(error unsupported WT_ATTEST_DEV_KEY='$(WT_ATTEST_DEV_KEY)' (want 0 or 1)) +endif +ifeq ($(WT_ENGINE),hsm) +ifeq ($(WT_ATTEST_KEY),hmac) +$(error WT_ATTEST_KEY=hmac requires WT_ENGINE=native; the wolfHSM engine keeps the attestation key in its keystore) +endif +ifeq ($(WT_VAULT_ECC),0) +$(error WT_VAULT_ECC=0 requires WT_ENGINE=native; the wolfHSM engine serves the vault from its server) +endif +endif +# ECC leaves the Secure image when no feature asks for it. +WT_ECC_USERS := $(filter hsm,$(WT_ENGINE)) $(filter 1,$(WT_VAULT_ECC)) \ + $(if $(filter 1,$(WT_ATTEST_COSE)),$(filter ecc,$(WT_ATTEST_KEY))) \ + $(if $(filter 1,$(WT_SECURE_PSA)),$(filter-out tiny,$(WT_SECURE_PSA_PROFILE))) \ + $(filter y,$(CONFIG_TPM) $(CONFIG_PKCS11)) +WT_NO_ECC := $(if $(strip $(WT_ECC_USERS)),0,1) +# An ECC attestation key signs through the vault's P-256 backend. +WT_KEYVAULT_P256 := $(if $(filter 1,$(WT_VAULT_ECC))$(if $(filter 1,$(WT_ATTEST_COSE)),$(filter ecc,$(WT_ATTEST_KEY))),1,0) +WT_ECC_CFLAGS := -DWT_ATTEST_KEY_$(WT_ATTEST_KEY)=1 -DWT_VAULT_ECC=$(WT_VAULT_ECC) \ + -DWT_KEYVAULT_P256=$(WT_KEYVAULT_P256) $(if $(filter 1,$(WT_NO_ECC)),-DWT_NO_ECC=1) +SECURE_CFLAGS += $(WT_ECC_CFLAGS) ifeq ($(WT_HSM_PIN_NEG_PROBE),1) # Probe lives in the hsm-only wt_hsm.c; defining it for a native build would # leave the spm_partitions.c call undefined at link. Native has no tasklet, so @@ -328,6 +368,10 @@ else # The conformance manifest never carries the update partition. MANIFEST_EXCLUDE := $(if $(filter 1,$(WT_CONFORMANCE)),,--exclude-partition PARTITION_FWU) endif +# An HMAC attestation key is held in the attestation partition, never the crypto service. +ifeq ($(WT_ATTEST_KEY),hmac) +MANIFEST_EXCLUDE += --drop-dependency PARTITION_ATTEST=SERVICE_HSM +endif # Hardware guest-flash write protection: refuse to launch a guest whose image # sectors are not WRP-protected, so a peer Non-secure guest cannot reprogram a # suspended guest's flash. Silicon only (the M33MU model has no flash WRP). @@ -440,6 +484,10 @@ WOLFCRYPT_SECURE_SRCS += $(ARCH_WOLFCRYPT_ASM_SRCS) ifeq ($(WT_ENGINE)/$(filter y,$(CONFIG_TPM) $(CONFIG_PKCS11)),native/) WOLFCRYPT_SECURE_SRCS := $(filter-out %/asn.c,$(WOLFCRYPT_SECURE_SRCS)) endif +ifeq ($(WT_NO_ECC),1) +WOLFCRYPT_SECURE_SRCS := $(filter-out %/ecc.c %/sp_int.c %/wolfmath.c \ + $(ARCH_WOLFCRYPT_SP_SRCS),$(WOLFCRYPT_SECURE_SRCS)) +endif # TPM 2.0 and PKCS#11 build one provider the same way; only one is ever linked. WT_IF := $(if $(filter y,$(CONFIG_TPM)),tpm,$(if $(filter y,$(CONFIG_PKCS11)),p11)) @@ -521,7 +569,6 @@ WT_SECURE_EXTRA_SRCS += \ $(ROOT)/src/services/native/keyvault.c endif -WT_SECURE_PSA_PROFILE ?= compat WT_PSA_SIZE_VARS := WT_PSA_POOL_BYTES WT_PSA_KEY_SLOTS WT_PSA_OP_SLOTS $(foreach v,$(WT_PSA_SIZE_VARS),$(if $(filter-out 0 1 2 3 4 5 6 7 8 9,$(subst 0,0 ,$(subst 1,1 ,$(subst 2,2 ,$(subst 3,3 ,$(subst 4,4 ,$(subst 5,5 ,$(subst 6,6 ,$(subst 7,7 ,$(subst 8,8 ,$(subst 9,9 ,$($(v)))))))))))))$(word 2,$($(v))),$(error unsupported $(v)='$($(v))' (want a decimal count)))) WOLFPSA_DIR := $(ROOT)/lib/wolfPSA @@ -533,8 +580,8 @@ ifeq ($(WT_SECURE_PSA),1) ifneq ($(WT_ENGINE),native) $(error WT_SECURE_PSA=1 requires WT_ENGINE=native) endif -ifneq ($(filter-out compat standard lean symmetric,$(WT_SECURE_PSA_PROFILE))$(words $(WT_SECURE_PSA_PROFILE)),1) -$(error unsupported WT_SECURE_PSA_PROFILE='$(WT_SECURE_PSA_PROFILE)' (want compat, standard, lean or symmetric)) +ifneq ($(filter-out extended default small tiny,$(WT_SECURE_PSA_PROFILE))$(words $(WT_SECURE_PSA_PROFILE)),1) +$(error unsupported WT_SECURE_PSA_PROFILE='$(WT_SECURE_PSA_PROFILE)' (want extended, default, small or tiny)) endif ifeq ($(WT_WOLFCRYPT_ARMASM),1) $(error WT_SECURE_PSA=1 needs constant-time AES, and WT_WOLFCRYPT_ARMASM=1 builds the T-table Thumb-2 AES) @@ -549,14 +596,28 @@ SECURE_CFLAGS += $(WT_SECURE_PSA_CFLAGS) HSM_LIB_CFLAGS += $(WT_SECURE_PSA_CFLAGS) HSM_WOLFHSM_CFLAGS += $(WT_SECURE_PSA_CFLAGS) WOLFPSA_SECURE_SRCS := $(filter-out %/psa_store_posix.c %/psa_attestation.c \ - %/psa_ffm.c %/psa_its.c %/misc_impl.c %/psa_store_zephyr.c %/psa_tf_psa.c,$(wildcard $(WOLFPSA_DIR)/src/*.c)) + %/psa_ffm.c %/psa_its.c %/psa_store_zephyr.c %/psa_tf_psa.c,$(wildcard $(WOLFPSA_DIR)/src/*.c)) WT_SECURE_EXTRA_SRCS += $(ROOT)/src/services/native/psa_crypto_service.c -ifeq ($(WT_SECURE_PSA_PROFILE),compat) +ifeq ($(WT_SECURE_PSA_PROFILE),extended) WOLFCRYPT_SECURE_SRCS += $(WOLFSSL_DIR)/wolfcrypt/src/kdf.c \ $(WOLFSSL_DIR)/wolfcrypt/src/pwdbased.c endif +ifneq ($(WT_AEAD_ONE),) +ifeq ($(WT_AEAD_USED),ccm) +WT_PSA_WANT_WITHOUT := --without PSA_WANT_ALG_GCM +endif +endif +ifneq ($(WT_SECURE_PSA_PROFILE),extended) +WT_PSA_WANT_WITHOUT += --without PSA_WANT_ALG_SP800_108_COUNTER_HMAC \ + --without PSA_WANT_ALG_SP800_108_COUNTER_CMAC \ + --without PSA_WANT_ALG_CCM_STAR_NO_TAG +endif endif +ifeq ($(WT_ATTEST_COSE)/$(WT_ATTEST_KEY)/$(WT_ATTEST_DEV_KEY),1/hmac/1) +$(warning WT_ATTEST_DEV_KEY=1 builds the public development attestation key; a product sets it to 0 and supplies wt_port_attest_hmac_key()) +WT_SECURE_EXTRA_SRCS += $(PORT_NEUTRAL_DIR)/attest_dev_key.c +endif ifeq ($(WT_ATTEST_COSE),1) WT_SECURE_EXTRA_SRCS += \ $(ROOT)/src/services/attestation_service.c \ @@ -1826,6 +1887,8 @@ BUILD_MODE_LINES = \ 'WT_PROVIDER_ECC_FALLBACK=$(WT_PROVIDER_ECC_FALLBACK)' \ 'WT_TPM_DA=$(WT_TPM_DA)' \ 'WT_ATTEST_COSE=$(WT_ATTEST_COSE)' \ + 'WT_ATTEST_KEY=$(WT_ATTEST_KEY)/$(WT_ATTEST_DEV_KEY)' \ + 'WT_VAULT_ECC=$(WT_VAULT_ECC)' \ 'WT_SECURE_PSA=$(WT_SECURE_PSA)' \ 'WT_SECURE_PSA_PROFILE=$(if $(filter 1,$(WT_SECURE_PSA)),$(WT_SECURE_PSA_PROFILE))' \ 'WT_PSA_SIZES=$(if $(filter 1,$(WT_SECURE_PSA)),$(subst / ,/,$(foreach v,$(WT_PSA_SIZE_VARS),$($(v))/)))' \ @@ -1867,6 +1930,7 @@ BUILD_MODE_LINES = \ 'WT_CO_STACK_SIZE=$(WT_CO_STACK_SIZE)' \ 'WT_SPM_STACK_SIZE=$(WT_SPM_STACK_SIZE)' \ 'WT_WOLFCRYPT_SP_ASM=$(WT_WOLFCRYPT_SP_ASM)' \ + 'WT_AEAD=$(WT_AEAD_USED)' \ 'WT_WOLFCRYPT_ARMASM=$(WT_WOLFCRYPT_ARMASM)' \ 'WT_SHA256_FAST=$(WT_SHA256_FAST)' \ 'WT_WOLFCRYPT_STM32_HASH=$(WT_WOLFCRYPT_STM32_HASH)' \ @@ -1887,7 +1951,14 @@ $(BUILD_MODE_STAMP): FORCE | $(BUILD_DIR) fi # The resolved configuration for tools and tests outside this directory. -.PHONY: print-layout-cflags print-build-mode +.PHONY: print-layout-cflags print-build-mode print-profile print-attest-defs +# The attestation defines of this build, for the host suite that issues tokens. +print-attest-defs: + @echo $(filter -D%,$(SECURE_CFLAGS_COSE)) -DWT_ATTEST_KEY_$(WT_ATTEST_KEY)=1 +print-profile: + @echo $(foreach v,WT_PROFILE WT_SECURE_PSA_PROFILE WT_INTERFACE_PROFILE \ + WT_MAX_GUESTS WT_MANIFEST_RUNTIME_CHECK WT_FWU WT_SHA256_FAST \ + WT_ATTEST_KEY WT_VAULT_ECC WT_NO_ECC,$(v)=$($(v))) print-layout-cflags: @echo '$(WT_LAYOUT_CFLAGS_ABS)' print-build-mode: @@ -1907,7 +1978,7 @@ ifeq ($(WT_SECURE_PSA),1) # FORCE: the generator rewrites the header only when the surface changes. $(WT_PSA_CONFIG_H): $(WOLFHSM_CFG_H) $(BUILD_MODE_STAMP) FORCE | $(BUILD_DIR) @mkdir -p $(dir $@) - python3 $(WOLFPSA_DIR)/tools/gen-crypto-config.py $@ "$(CC)" \ + python3 $(WOLFPSA_DIR)/tools/gen-crypto-config.py $(WT_PSA_WANT_WITHOUT) $@ "$(CC)" \ $(WOLFPSA_DIR)/tools/psa_want_probe.c $(HSM_LIB_CFLAGS) -I$(WOLFPSA_DIR)/src \ -DWT_PSA_WANT_PROBE $(BUILD_DIR)/wt_sec_psa_crypto_service.o: $(WT_PSA_CONFIG_H) diff --git a/mk/crypto-profile.mk b/mk/crypto-profile.mk index 4359bdfce..88a60d724 100644 --- a/mk/crypto-profile.mk +++ b/mk/crypto-profile.mk @@ -18,7 +18,7 @@ # along with this program; if not, see . # Generate one operation selection shared by the provider and its clients. -WT_INTERFACE_PROFILE ?= default +WT_INTERFACE_PROFILE ?= $(if $(filter extended,$(WT_PROFILE)),extended,default) WT_INTERFACE_PROFILE_DIR := $(abspath $(BUILD_DIR)/crypto-profile) WT_INTERFACE_PROFILE_HEADER := $(WT_INTERFACE_PROFILE_DIR)/selected_profile.h WT_INTERFACE_PROFILE_FLAGS := -include $(WT_INTERFACE_PROFILE_HEADER) diff --git a/mk/layout.mk b/mk/layout.mk index 7359113bd..325bedaf0 100644 --- a/mk/layout.mk +++ b/mk/layout.mk @@ -3,6 +3,10 @@ # and the host fixtures) takes WT_LAYOUT_CFLAGS: defines and include paths # only, no ISA flags, so a host compiler accepts it. Included right after # mk/target-.mk, which gives every input its default. +# Target fragments test profile-owned flags, so the profile resolves first. +ifeq ($(WT_PROFILE_RESOLVED),) +$(error include mk/profile.mk before mk/target-$(TARGET).mk) +endif ARCH ?= armv8m PORT_NEUTRAL_DIR := $(ROOT)/port/common PORT_COMMON_DIR := $(ROOT)/port/common/$(ARCH) @@ -66,12 +70,14 @@ WT_LAYOUT_DEFS := \ # PKCS#11 guests use their own API, so those builds default it off. WT_SECURE_PSA ?= $(if $(or $(filter hsm,$(WT_ENGINE)),$(filter 1,$(WT_ENGINE_HSM)),\ $(filter y,$(CONFIG_TPM) $(CONFIG_PKCS11))),0,1) -# A Secure PSA crypto band holds the wolfPSA pool (2 KB per guest) plus about -# 1.4 KB of slot tables and service state; its crypto stack peaks at 4,836 B (7,240 B asm). +# A Secure PSA crypto band holds the wolfPSA pool (2 KB per guest) plus 1,376 B of +# slot tables and service state. Crypto stack peaks: extended 4,804 B (ecc.c), default +# and small 4,028 B, tiny 3,664 B (direct P-256 for the vault's native wire keys). ifeq ($(WT_SECURE_PSA),1) WT_SP_HSM_DATA_SIZE ?= $(shell echo $$(( ($(or $(WT_PSA_POOL_BYTES),\ - $(or $(WT_MAX_GUESTS),1) * 2048) + 2048 + 31) / 32 * 32 )) 2>/dev/null) -WT_SP_CRYPTO_STACK_SIZE ?= 0x00001800u + $(or $(WT_MAX_GUESTS),1) * 2048) + 1536 + 31) / 32 * 32 )) 2>/dev/null) +WT_SP_CRYPTO_STACK_SIZE ?= $(strip $(if $(filter extended,$(or $(WT_SECURE_PSA_PROFILE),default)),\ + 0x00001800u,0x00001400u)) endif WT_LAYOUT_DEFS += $(foreach v,$(WT_LAYOUT_OPTIONAL_INPUTS),\ $(if $(strip $($(v))),-D$(v)=$($(v)))) diff --git a/mk/profile.mk b/mk/profile.mk new file mode 100644 index 000000000..6cb3acdc8 --- /dev/null +++ b/mk/profile.mk @@ -0,0 +1,22 @@ +# Build profile: tiny, small, default or extended. It picks the add-on +# defaults and the Secure PSA algorithm set; a flag set explicitly still wins. +WT_PROFILE ?= default +ifneq ($(filter-out tiny small default extended,$(WT_PROFILE))$(words $(WT_PROFILE)),1) +$(error unsupported WT_PROFILE='$(WT_PROFILE)' (want tiny, small, default or extended)) +endif +ifeq ($(WT_PROFILE),extended) +WT_MAX_GUESTS ?= 2 +WT_MANIFEST_RUNTIME_CHECK ?= 1 +WT_FWU ?= 1 +WT_SHA256_FAST ?= 1 +endif +# tiny carries no ECC: an HMAC attestation key and no vault P-256 key +# operations. The wolfHSM engine keeps both, its server signs with ECC. +ifeq ($(WT_PROFILE)/$(filter hsm,$(WT_ENGINE))$(filter 1,$(WT_ENGINE_HSM)),tiny/) +WT_ATTEST_KEY ?= hmac +WT_VAULT_ECC ?= 0 +endif +WT_ATTEST_KEY ?= ecc +WT_VAULT_ECC ?= 1 +WT_SECURE_PSA_PROFILE ?= $(WT_PROFILE) +WT_PROFILE_RESOLVED := $(WT_PROFILE) diff --git a/port/common/attest_dev_key.c b/port/common/attest_dev_key.c new file mode 100644 index 000000000..9b271d72e --- /dev/null +++ b/port/common/attest_dev_key.c @@ -0,0 +1,47 @@ +/* attest_dev_key.c + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of wolfTrust. + * + * wolfTrust 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. + * + * wolfTrust 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, see . + */ + +/* The WT_ATTEST_DEV_KEY=1 attestation key of the reference boards. It is + * public, so a token it authenticates proves nothing about a device. */ + +#include +#include +#include + +#include "wolftrust/services/initial_attestation.h" + +/* "wolfTrust-DEV-attestation-key-00" */ +static const uint8_t g_attest_dev_key[WT_ATTEST_HMAC_KEY_SIZE] = { + 0x77, 0x6f, 0x6c, 0x66, 0x54, 0x72, 0x75, 0x73, + 0x74, 0x2d, 0x44, 0x45, 0x56, 0x2d, 0x61, 0x74, + 0x74, 0x65, 0x73, 0x74, 0x61, 0x74, 0x69, 0x6f, + 0x6e, 0x2d, 0x6b, 0x65, 0x79, 0x2d, 0x30, 0x30 +}; + +int wt_port_attest_hmac_key(uint8_t* key, size_t keySize) +{ + int ret = -1; + + if ((key != NULL) && (keySize == sizeof(g_attest_dev_key))) { + (void)memcpy(key, g_attest_dev_key, sizeof(g_attest_dev_key)); + ret = 0; + } + return ret; +} diff --git a/port/mcxn947/port.json b/port/mcxn947/port.json index 91324415a..20c402f25 100644 --- a/port/mcxn947/port.json +++ b/port/mcxn947/port.json @@ -55,6 +55,7 @@ ["authneg rollbackneg remeasureneg manifestneg spbudgetneg", "MCXN947 launch, rollback, re-measure, manifest and SP budget verdicts, one guest"], ["spfaultneg panicneg", "MCXN947 SP fault recovery and panic, one guest"], ["attestneg", "MCXN947 attestation negatives, one guest"], + ["tinyattest", "MCXN947 tiny with no ECC, the COSE_Mac0 token across an attestation partition restart, one guest (L3)"], ["hsmattackneg", "MCXN947 wolfHSM cross-namespace + NVM relay negatives, one guest"], ["periphneg", "MCXN947 NS read of the SPM's ELS refused by the SAU, one guest"], ["nativewire nativewireasm", "MCXN947 every native wire key op from the guest, portable C and assembly, one guest"], @@ -67,7 +68,7 @@ ["tpm tpmneg tpmreset", "MCXN947 TPM 2.0 interface, isolation and client reset, one guest (L3)"], ["pkcs11 pkcs11neg pkcs11reset", "MCXN947 PKCS#11 interface, isolation and client reset, one guest (L3)"] ], - "l3_exempt": {"hsmfaultneg": "the tasklet fault scenario ends on the second guest's breakpoint, so it runs on the full profile only"} + "l3_exempt": {"hsmfaultneg": "the tasklet fault scenario ends on the second guest's breakpoint, so it runs on the extended profile only"} }, "guests": {"hwpsa": ["psa", "psa"], "lifecycle": ["baremetal", "baremetal"], "psa": ["psa", "psa"], "conformance": ["psa", "baremetal"], "vnet": ["vnet", "vnet"], "tpm": ["interface", "baremetal"], "pkcs11": ["interface", "baremetal"]}, "guest_end": {}, @@ -78,7 +79,8 @@ "caps_absent": {"dma_probe": "the M33MU MCXN947 model has no DMA; the NS eDMA copies out of Secure memory are the FRDM run's to show", "idcode": "no silicon revision gate on this port", "bootupdate": "the MCXN947 emulator chain does not stage a wolfBoot update candidate yet", "vnet": "no wolfIP network guests for this port", "idle_scheduler": "the single-guest idle backoff scenario is not wired for this port", "busfault": "M33MU at the pinned ref does not vector a precise data BusFault", "guest_fence": "the MCXN947 first stage arms no guest flash fence (wrpoff proves the refusal)", "handler_overrun": "the Non-secure handler overrun scenario is not wired for this port"}, "faults_by_design": {"periphneg": "the bare-metal probe's NS read of the ELS faults on every launch and the monitor contains it", "crossdomain": "the storage SP's probe faults on its first wake while both guests finish; the trace boot names the fault", "keystoreneg": "the storage SP's probe faults on its first wake while both guests finish; the trace boot names the fault", "periphspneg": "the storage SP's probe faults on its first wake while the PSA guest finishes"}, "exempt": { - "hsmrestartneg": "the probe lives in the Zephyr guest; this port's PSA role runs the bare-metal PSA guest" + "hsmrestartneg": "the probe lives in the Zephyr guest; this port's PSA role runs the bare-metal PSA guest", + "nativewiresmall": "the Secure PSA crypto stack sizes are one shared layout over portable C on every port; the STM32H563 runs it" } }, "hardware": { diff --git a/port/mimxrt700/port.json b/port/mimxrt700/port.json index 103078e42..b8e6eb0f3 100644 --- a/port/mimxrt700/port.json +++ b/port/mimxrt700/port.json @@ -55,6 +55,7 @@ ["authneg rollbackneg remeasureneg manifestneg spbudgetneg", "RT700 launch, rollback, re-measure, manifest and SP budget verdicts, one guest"], ["spfaultneg panicneg", "RT700 SP fault recovery and panic, one guest"], ["attestneg", "RT700 attestation negatives, one guest"], + ["tinyattest", "RT700 tiny with no ECC, the COSE_Mac0 token across an attestation partition restart, one guest (L3)"], ["hsmattackneg", "RT700 wolfHSM cross-namespace + NVM relay negatives, one guest"], ["periphneg", "RT700 NS read of the SPM's TRNG refused by the SAU, one guest"], ["nativewire nativewireasm", "RT700 every native wire key op from the guest, portable C and assembly, one guest"], @@ -67,7 +68,7 @@ ["tpm tpmneg tpmreset", "RT700 TPM 2.0 interface, isolation and client reset, one guest (L3)"], ["pkcs11 pkcs11neg pkcs11reset", "RT700 PKCS#11 interface, isolation and client reset, one guest (L3)"] ], - "l3_exempt": {"hsmfaultneg": "the tasklet fault scenario ends on the second guest's breakpoint, so it runs on the full profile only"} + "l3_exempt": {"hsmfaultneg": "the tasklet fault scenario ends on the second guest's breakpoint, so it runs on the extended profile only"} }, "guests": {"hwpsa": ["psa", "psa"], "lifecycle": ["baremetal", "baremetal"], "psa": ["psa", "psa"], "conformance": ["psa", "baremetal"], "vnet": ["vnet", "vnet"], "tpm": ["interface", "baremetal"], "pkcs11": ["interface", "baremetal"]}, "guest_end": {}, @@ -78,7 +79,8 @@ "caps_absent": {"dma_probe": "the M33MU RT700 model has no DMA; the NS eDMA copies out of Secure memory are the EVK run's to show", "idcode": "no silicon revision gate on this port", "bootupdate": "the RT700 emulator chain does not stage a wolfBoot update candidate yet", "vnet": "no wolfIP network guests for this port", "idle_scheduler": "the single-guest idle backoff scenario is not wired for this port", "busfault": "M33MU at the pinned ref does not vector a precise data BusFault"}, "faults_by_design": {"periphneg": "the bare-metal probe's NS read of the TRNG faults on every launch and the monitor contains it", "crossdomain": "the storage SP's probe faults on its first wake while both guests finish; the trace boot names the fault", "keystoreneg": "the storage SP's probe faults on its first wake while both guests finish; the trace boot names the fault", "periphspneg": "the storage SP's probe faults on its first wake while the PSA guest finishes"}, "exempt": { - "hsmrestartneg": "the probe lives in the Zephyr guest; this port's PSA role runs the bare-metal PSA guest" + "hsmrestartneg": "the probe lives in the Zephyr guest; this port's PSA role runs the bare-metal PSA guest", + "nativewiresmall": "the Secure PSA crypto stack sizes are one shared layout over portable C on every port; the STM32H563 runs it" } }, "hardware": { diff --git a/port/stm32h563/port.json b/port/stm32h563/port.json index 9f4b2cf39..f772ce433 100644 --- a/port/stm32h563/port.json +++ b/port/stm32h563/port.json @@ -85,14 +85,15 @@ ["fpneg sealneg sealhaltneg sealpivotneg xnneg svcneg", "FP, seal, execute-never and SVC misuse, one guest (L3)"], ["spfaultneg panicneg", "SP fault recovery and panic, one guest"], ["attestneg", "Attestation negatives, one guest"], + ["tinyattest", "tiny with no ECC, the COSE_Mac0 token across an attestation partition restart, one guest (L3)"], ["hsmattackneg", "wolfHSM cross-namespace + NVM relay negatives, one guest"], ["authneg rollbackneg remeasureneg manifestneg spbudgetneg", "Launch, rollback, re-measure, manifest and SP budget verdicts, one guest"], ["periphneg revneg", "NS peripheral access and engineering-sample refusal, one guest"], - ["nativewire nativewireasm", "Every native wire key op from the guest, portable C and assembly, one guest"], + ["nativewire nativewireasm nativewiresmall", "Every native wire key op from the guest, portable C, assembly and the small profile's 5 KiB crypto stack, one guest"], ["tpm tpmneg tpmreset", "TPM 2.0 interface, isolation and client reset, one guest (L3)"], ["pkcs11 pkcs11neg pkcs11reset", "PKCS#11 interface, isolation and client reset, one guest (L3)"] ], - "l3_exempt": {"hsmfaultneg": "the tasklet fault scenario ends on the second guest's breakpoint, so it runs on the full profile only"} + "l3_exempt": {"hsmfaultneg": "the tasklet fault scenario ends on the second guest's breakpoint, so it runs on the extended profile only"} }, "guests": {"hwpsa": ["psa", "psa"], "lifecycle": ["zephyr", "freertos"], "psa": ["zephyr", "freertos"], "conformance": ["zephyr", "freertos"], "vnet": ["vnet", "vnet"], "tpm": ["interface", "baremetal"], "pkcs11": ["interface", "baremetal"]}, "guest_end": {"zephyr": "bkpt", "vnet": "bkpt"}, diff --git a/port/stm32l562/port.json b/port/stm32l562/port.json index 7348acc5c..b843d769a 100644 --- a/port/stm32l562/port.json +++ b/port/stm32l562/port.json @@ -126,6 +126,7 @@ ["authneg rollbackneg remeasureneg manifestneg spbudgetneg", "STM32L562 launch, rollback, re-measure, manifest and SP budget verdicts, one guest"], ["spfaultneg panicneg", "STM32L562 SP fault recovery and panic, one guest"], ["attestneg", "STM32L562 attestation negatives, one guest"], + ["tinyattest", "STM32L562 tiny with no ECC, the COSE_Mac0 token across an attestation partition restart, one guest (L3)"], ["periphneg", "STM32L562 NS read of the SPM's RNG refused by the SAU, one guest"], ["nativewire nativewireasm", "STM32L562 every native wire key op from the guest, portable C and assembly, one guest"], ["crossdomain keystoreneg periphspneg deputyneg", "STM32L562 SP domain, SPM peripheral and deputy, one guest (L3)"], @@ -202,6 +203,7 @@ "exempt": { "hsmrestartneg": "wolfHSM engine only; the STM32L562 builds the native engine", "devcryptolocal": "the STM32L562 defaults to WT_SECURE_PSA=0, so devcrypto already runs the guest-local PSA it checks", + "nativewiresmall": "the Secure PSA crypto stack sizes are one shared layout over portable C on every port; the STM32H563 runs it", "hsmattackneg": "wolfHSM engine only; the STM32L562 builds the native engine (the wolfHSM bands do not fit 256 KiB of SRAM)", "hsmpinneg": "wolfHSM engine only; the STM32L562 builds the native engine (the wolfHSM bands do not fit 256 KiB of SRAM)", "hsmfaultneg": "wolfHSM engine only; the STM32L562 builds the native engine (the wolfHSM bands do not fit 256 KiB of SRAM)" diff --git a/src/arch/common/spm_gate_core.c b/src/arch/common/spm_gate_core.c index 0bd45ea69..a1c9f600a 100644 --- a/src/arch/common/spm_gate_core.c +++ b/src/arch/common/spm_gate_core.c @@ -205,7 +205,8 @@ static void wt_spm_fault_release(void* ctx) * crypto partition's cached keystore door must close and reconnect. */ wt_nvm_client_partition_vault_restarted(); } -#if defined(WT_ATTEST_COSE) && (WT_ATTEST_COSE == 1) +#if defined(WT_ATTEST_COSE) && (WT_ATTEST_COSE == 1) && \ + !defined(WT_ATTEST_KEY_hmac) if (c->slot->partition_id == g_spm_hsm_partition_id) { wt_initial_attest_hsm_restarted(); } diff --git a/src/boot.c b/src/boot.c index fc95e1550..1f6b2c55b 100644 --- a/src/boot.c +++ b/src/boot.c @@ -109,7 +109,8 @@ void wt_boot_run(void) } } #endif -#if defined(WT_ATTEST_COSE) && (WT_ATTEST_COSE == 1) +#if defined(WT_ATTEST_COSE) && (WT_ATTEST_COSE == 1) && \ + !defined(WT_ATTEST_KEY_hmac) if (wt_hsm_attest_bootstrap() != WH_ERROR_OK) { /* The vault could not be provisioned and auto-reformat was not * permitted (a foreign or corrupt pool on a SECURED device). Boot diff --git a/src/services/attestation_service.c b/src/services/attestation_service.c index 85158a287..fc1b51596 100644 --- a/src/services/attestation_service.c +++ b/src/services/attestation_service.c @@ -195,6 +195,7 @@ static psa_status_t wt_attestation_service_token_size( return PSA_SUCCESS; } +#ifndef WT_ATTEST_KEY_hmac /* IAK public-key query (WT_ATTEST_OP_PUBLIC_KEY): the uncompressed P-256 * public point out. Public data only — the private IAK never leaves the * secure side. */ @@ -220,6 +221,7 @@ static psa_status_t wt_attestation_service_public_key( } return PSA_SUCCESS; } +#endif int wt_attestation_service_dispatch(void* context, wt_ffm_runtime_t* runtime, int32_t partition_id) @@ -257,8 +259,13 @@ int wt_attestation_service_dispatch(void* context, wt_ffm_runtime_t* runtime, reply_status = wt_attestation_service_token_size(runtime, partition_id, &msg); } else if (msg.type == WT_ATTEST_OP_PUBLIC_KEY) { +#ifdef WT_ATTEST_KEY_hmac + /* A known operation an HMAC key cannot serve, not a client error */ + reply_status = PSA_ERROR_NOT_SUPPORTED; +#else reply_status = wt_attestation_service_public_key(runtime, partition_id, &msg); +#endif } else { reply_status = PSA_ERROR_PROGRAMMER_ERROR; } diff --git a/src/services/hsm_relay_service.c b/src/services/hsm_relay_service.c index 78869c11d..96d923298 100644 --- a/src/services/hsm_relay_service.c +++ b/src/services/hsm_relay_service.c @@ -40,9 +40,11 @@ static wt_spm_transport_fn g_relay_transport = wt_spm_transport_direct; defined(WT_INTERFACE_LOCAL_PROVIDER) static int32_t g_relay_secure_client = 0; #endif +#ifndef WT_ATTEST_KEY_hmac static int32_t g_relay_attest_client = 0; static wt_hsm_attest_sign_fn g_relay_attest_sign = NULL; static wt_hsm_attest_public_key_fn g_relay_attest_public_key = NULL; +#endif /* P-256 verify needs roughly 4 KiB below the relay frames. Keep the copied * packets in Secure KEYSTORE instead of the HSM partition's 8 KiB stack. */ @@ -75,6 +77,7 @@ void wt_hsm_relay_set_transport(wt_spm_transport_fn fn) g_relay_transport = (fn != NULL) ? fn : wt_spm_transport_direct; } +#ifndef WT_ATTEST_KEY_hmac void wt_hsm_relay_set_attest_ops(int32_t attest_partition_id, wt_hsm_attest_sign_fn sign, wt_hsm_attest_public_key_fn public_key) @@ -84,6 +87,7 @@ void wt_hsm_relay_set_attest_ops(int32_t attest_partition_id, g_relay_attest_sign = sign; g_relay_attest_public_key = public_key; } +#endif /* Drain invec[0] into a bounded private buffer (WT-FFM-0041 copied * transfers). */ @@ -197,6 +201,7 @@ static psa_status_t wt_hsm_relay_call(wt_ffm_runtime_t* runtime, return status; } +#ifndef WT_ATTEST_KEY_hmac /* Map the engine signer's wolfHSM-style result onto a PSA status; NOTREADY * (no IAK yet) surfaces as BAD_STATE so the attestation partition reports * not-ready rather than a generic failure. */ @@ -271,6 +276,7 @@ static psa_status_t wt_hsm_relay_attest_call(wt_ffm_runtime_t* runtime, wt_forceZero(out, sizeof(out)); return status; } +#endif /* !WT_ATTEST_KEY_hmac */ int wt_hsm_relay_dispatch(void* context, wt_ffm_runtime_t* runtime, int32_t partition_id) @@ -318,9 +324,11 @@ int wt_hsm_relay_dispatch(void* context, wt_ffm_runtime_t* runtime, else { reply_status = PSA_ERROR_NOT_PERMITTED; } +#ifndef WT_ATTEST_KEY_hmac } else if (msg.type == WT_HSM_OP_ATTEST_SIGN || msg.type == WT_HSM_OP_ATTEST_PUBLIC_KEY) { reply_status = wt_hsm_relay_attest_call(runtime, partition_id, &msg); +#endif } else { reply_status = PSA_ERROR_PROGRAMMER_ERROR; } diff --git a/src/services/initial_attestation.c b/src/services/initial_attestation.c index 2651575f2..45d1315f0 100644 --- a/src/services/initial_attestation.c +++ b/src/services/initial_attestation.c @@ -69,6 +69,10 @@ static uint8_t g_signer_id[WC_SHA256_DIGEST_SIZE]; static bool g_handoff_ready; static bool g_attest_ready; +#ifdef WT_ATTEST_KEY_hmac +/* The HMAC attestation key, loaded by the privileged boot and restart paths. */ +static uint8_t g_attest_hmac_key[WT_ATTEST_HMAC_KEY_SIZE]; +#else /* SERVICE_HSM signer binding: transport, the attestation partition's own id * (stamped by the SVC on target), the crypto service's SID, and the cached * connection. A NULL transport selects the engine's local signer. */ @@ -78,6 +82,7 @@ static int32_t g_attest_hsm_partition; static uint32_t g_attest_hsm_sid; static psa_handle_t g_attest_hsm_handle; static uint8_t g_attest_hsm_restarted; +#endif static void wt_attest_force_zero(void* memory, size_t size) { @@ -89,6 +94,7 @@ static void wt_attest_force_zero(void* memory, size_t size) } } +#ifndef WT_ATTEST_KEY_hmac int wt_initial_attest_bind_hsm(wt_spm_transport_fn transport, wt_ffm_runtime_t* runtime, int32_t partition_id, uint32_t hsm_sid) @@ -252,12 +258,35 @@ static int wt_attest_signer_public_key(uint8_t* publicKey, } return ret; } +#endif /* !WT_ATTEST_KEY_hmac */ + +#ifdef WT_ATTEST_KEY_hmac +/* The IAK identifier of an HMAC key is the hash of its hash, never a + * direct digest of the key (RFC 9783 A.2). */ +static int wt_attest_hmac_key_id(uint8_t* id) +{ + uint8_t keyHash[WC_SHA256_DIGEST_SIZE]; + int ret; + + ret = wc_Sha256Hash(g_attest_hmac_key, (word32)sizeof(g_attest_hmac_key), + keyHash); + if (ret == 0) { + ret = wc_Sha256Hash(keyHash, (word32)sizeof(keyHash), id); + } + wt_attest_force_zero(keyHash, sizeof(keyHash)); + return (ret == 0) ? WT_ATTEST_SUCCESS : WT_ATTEST_ERROR_CRYPTO; +} +#endif static int wt_attest_prepare(void) { +#ifndef WT_ATTEST_KEY_hmac uint8_t publicKey[WT_ATTEST_IAK_PUBLIC_KEY_SIZE]; +#endif uint8_t digest[WC_SHA256_DIGEST_SIZE]; +#ifndef WT_ATTEST_KEY_hmac size_t publicKeySize = sizeof(publicKey); +#endif int ret; if (g_attest_ready) { @@ -267,6 +296,9 @@ static int wt_attest_prepare(void) return WT_ATTEST_ERROR_NOT_READY; } +#ifdef WT_ATTEST_KEY_hmac + ret = wt_attest_hmac_key_id(digest); +#else ret = wt_attest_signer_public_key(publicKey, sizeof(publicKey), &publicKeySize); if (ret == WH_ERROR_NOTREADY) { @@ -284,13 +316,16 @@ static int wt_attest_prepare(void) ret = WT_ATTEST_ERROR_CRYPTO; } } +#endif if (ret == 0) { g_ueid[0] = WT_UEID_TYPE_RANDOM; (void)memcpy(&g_ueid[1], digest, sizeof(digest)); g_attest_ready = true; } +#ifndef WT_ATTEST_KEY_hmac wt_attest_force_zero(publicKey, sizeof(publicKey)); +#endif wt_attest_force_zero(digest, sizeof(digest)); return ret; } @@ -332,6 +367,23 @@ static int wt_attest_measurement_get(size_t index, return 0; } +#ifdef WT_ATTEST_KEY_hmac +/* Size of a tagged COSE_Mac0 with an inline payload: tag, array head, + * protected {1: 5}, empty unprotected map, payload bstr and a 32-byte tag. */ +static size_t wt_attest_mac0_size(size_t payloadSize) +{ + size_t head = 3u; + + if (payloadSize < 24u) { + head = 1u; + } + else if (payloadSize < 256u) { + head = 2u; + } + return 1u + 1u + 4u + 1u + head + payloadSize + 2u + + (size_t)WC_SHA256_DIGEST_SIZE; +} +#else /* COSE external-signer callback: wolfCOSE hands us the digest of the * Sig_structure; forward it to the IAK held in the secure HSM. */ static int wt_attest_eat_sign(void* context, int32_t algorithm, @@ -345,6 +397,7 @@ static int wt_attest_eat_sign(void* context, int32_t algorithm, return wt_attest_signer_sign(digest, digestSize, signature, signatureSize, signatureLength); } +#endif static int wt_attest_build_claims(wt_guest_id_t guestId, const uint8_t* challenge, size_t challengeSize, @@ -472,6 +525,16 @@ int wt_initial_attest_init(const wt_boot_handoff_t* handoff, ret = wc_Sha256Hash(g_signer_name, (word32)(sizeof(g_signer_name) - 1u), g_signer_id); } +#ifdef WT_ATTEST_KEY_hmac + if ((ret == 0) && (wt_port_attest_hmac_key(g_attest_hmac_key, + sizeof(g_attest_hmac_key)) != 0)) { + /* No key, no tokens: every request fails closed until a later init. */ + wt_attest_force_zero(g_attest_hmac_key, sizeof(g_attest_hmac_key)); + g_handoff_ready = false; + g_attest_ready = false; + ret = -1; + } +#endif if (ret == 0) { (void)memcpy(&g_boot_handoff, handoff, sizeof(g_boot_handoff)); (void)memcpy(g_boot_seed, bootSeed, sizeof(g_boot_seed)); @@ -522,11 +585,15 @@ int wt_initial_attest_get_token_size(size_t challengeSize, } } if (ret == WT_ATTEST_SUCCESS) { +#ifdef WT_ATTEST_KEY_hmac + *tokenSize = wt_attest_mac0_size(payloadSize); +#else if (wc_CoseSign1_SignSize_ex(NULL, WOLFCOSE_ALG_ES256, 0u, payloadSize, 0u, 0u, tokenSize) != WOLFCOSE_SUCCESS) { *tokenSize = 0u; ret = WT_ATTEST_ERROR_CRYPTO; } +#endif } wt_attest_force_zero(challenge, sizeof(challenge)); @@ -573,6 +640,12 @@ int wt_initial_attest_get_token(wt_guest_id_t guestId, } else { keyReady = 1; +#ifdef WT_ATTEST_KEY_hmac + if (wc_CoseKey_SetSymmetric(&key, g_attest_hmac_key, + sizeof(g_attest_hmac_key)) != WOLFCOSE_SUCCESS) { + ret = WT_ATTEST_ERROR_CRYPTO; + } +#else key.kty = WOLFCOSE_KTY_EC2; key.crv = WOLFCOSE_CRV_P256; key.alg = WOLFCOSE_ALG_ES256; @@ -580,12 +653,19 @@ int wt_initial_attest_get_token(wt_guest_id_t guestId, WOLFCOSE_SUCCESS) { ret = WT_ATTEST_ERROR_CRYPTO; } +#endif } } if (ret == WT_ATTEST_SUCCESS) { +#ifdef WT_ATTEST_KEY_hmac + ret = wc_CoseEatPsaToken_CreateMac0(&key, WOLFCOSE_ALG_HMAC256, + &claims, claimsBuf, sizeof(claimsBuf), scratch, sizeof(scratch), + token, tokenCapacity, tokenSize); +#else ret = wc_CoseEatPsaToken_CreateSign1(&key, WOLFCOSE_ALG_ES256, &claims, claimsBuf, sizeof(claimsBuf), scratch, sizeof(scratch), token, tokenCapacity, tokenSize, NULL); +#endif if (ret == WOLFCOSE_E_BUFFER_TOO_SMALL) { ret = WT_ATTEST_ERROR_BUFFER_TOO_SMALL; } @@ -602,6 +682,7 @@ int wt_initial_attest_get_token(wt_guest_id_t guestId, return ret; } +#ifndef WT_ATTEST_KEY_hmac int wt_initial_attest_get_iak_public_key(uint8_t* publicKey, size_t publicKeyCapacity, size_t* publicKeySize) { @@ -620,3 +701,4 @@ int wt_initial_attest_get_iak_public_key(uint8_t* publicKey, } return ret; } +#endif /* !WT_ATTEST_KEY_hmac */ diff --git a/src/services/native/crypto_native.c b/src/services/native/crypto_native.c index e9791354f..af686cc9c 100644 --- a/src/services/native/crypto_native.c +++ b/src/services/native/crypto_native.c @@ -58,8 +58,6 @@ WT_STATIC_ASSERT(WT_HSM_ATTEST_NOT_READY == WH_ERROR_NOTREADY, #define WT_NATIVE_IAK_SUB 0 #define WT_NATIVE_IAK_UID 0xF0u -static bool g_native_attest_ready; - int wt_native_init(void) { int rc; @@ -98,6 +96,10 @@ int wt_native_bind_nvm(whNvmContext* nvm) * as the hsm engine: 64-byte * r||s signatures, 65-byte X9.63 public point. * ====================================================================== */ +/* An HMAC attestation key stays with the attestation partition: no IAK here. */ +#ifndef WT_ATTEST_KEY_hmac +static bool g_native_attest_ready; + static psa_status_t wt_native_iak_generate(void) { return wt_hsm_key_backend.generate(WT_NATIVE_IAK_OWNER, @@ -239,3 +241,4 @@ int wt_hsm_attest_public_key(uint8_t* publicKey, size_t publicKeyCapacity, publicKeySize); return (status == PSA_SUCCESS) ? WH_ERROR_OK : WH_ERROR_ABORTED; } +#endif /* !WT_ATTEST_KEY_hmac */ diff --git a/src/services/native/keyvault.c b/src/services/native/keyvault.c index 6c219d49a..39f7e3cdf 100644 --- a/src/services/native/keyvault.c +++ b/src/services/native/keyvault.c @@ -33,7 +33,12 @@ /* wolfCrypt settings must come first. */ #include "wolfssl/wolfcrypt/settings.h" #include "wolfssl/wolfcrypt/types.h" +#ifndef WT_KEYVAULT_P256 +#define WT_KEYVAULT_P256 1 +#endif +#if WT_KEYVAULT_P256 #include "wolfssl/wolfcrypt/ecc.h" +#endif #include "wolfssl/wolfcrypt/aes.h" #include "wolfssl/wolfcrypt/random.h" #include "wolfssl/wolfcrypt/error-crypt.h" @@ -49,10 +54,21 @@ #include +#if WT_VAULT_KEY_MATERIAL_LEN != WT_HSM_AEAD_KEY_LEN || \ + WT_VAULT_KEY_NONCE_LEN != WT_HSM_AEAD_NONCE_LEN || \ + WT_VAULT_KEY_TAG_LEN != WT_HSM_AEAD_TAG_LEN +#error "vault key encryption must match the vault AEAD sizes" +#endif + +#if WT_KEYVAULT_P256 && defined(WOLFPSA_ECC_SP_DIRECT) +#include "wolfpsa/psa_p256.h" +#endif + #define WT_HSM_KEY_P256_OBJ_LEN \ (WT_VAULT_KEY_MATERIAL_LEN + WT_VAULT_KEY_PUB_LEN) #define WT_HSM_KEY_AES_OBJ_LEN WT_VAULT_KEY_MATERIAL_LEN +#if WT_KEYVAULT_P256 /* NO_ASN makes wc_ecc_sign_hash/verify_hash use the fixed-width r||s form; * TPM 2.0 and PKCS#11 builds link ASN.1, so they convert through DER. */ #if !defined(NO_ASN) && !defined(CONFIG_TPM) && !defined(CONFIG_PKCS11) @@ -61,6 +77,7 @@ #ifndef NO_ASN #define WT_HSM_KEY_DER_SIG_MAX 80U #endif +#endif #define WT_HSM_KEY_LABEL(usage, type) \ (WT_VAULT_FLAG_KEY | ((usage) & WT_VAULT_KEY_USAGE_MASK) | \ @@ -210,9 +227,15 @@ static psa_status_t wt_hsm_kv_load(int32_t owner, int32_t sub, uint64_t uid, return PSA_SUCCESS; } +#if WT_KEYVAULT_P256 /* Derive [d][X9.63 public] from a P-256 private scalar. */ static psa_status_t wt_hsm_kv_p256_object(const uint8_t* d, uint8_t* obj) { +#ifdef WOLFPSA_ECC_SP_DIRECT + (void)memcpy(obj, d, WT_VAULT_KEY_MATERIAL_LEN); + return (wolfPSA_P256_Public(d, obj + WT_VAULT_KEY_MATERIAL_LEN) == 0) ? + PSA_SUCCESS : PSA_ERROR_GENERIC_ERROR; +#else ecc_key key; word32 len; int rc; @@ -236,19 +259,27 @@ static psa_status_t wt_hsm_kv_p256_object(const uint8_t* d, uint8_t* obj) } wc_ecc_free(&key); return (rc == 0) ? PSA_SUCCESS : PSA_ERROR_GENERIC_ERROR; +#endif } +#endif /* WT_KEYVAULT_P256 */ static psa_status_t wt_hsm_kv_generate(int32_t owner, int32_t sub, uint64_t uid, uint32_t type, uint32_t usage) { +#if WT_KEYVAULT_P256 uint8_t obj[WT_HSM_KEY_P256_OBJ_LEN]; +#endif uint8_t d[WT_VAULT_KEY_MATERIAL_LEN]; +#if WT_KEYVAULT_P256 && !defined(WOLFPSA_ECC_SP_DIRECT) ecc_key key; - WC_RNG* rng; word32 len; +#endif + WC_RNG* rng; psa_status_t status; +#if WT_KEYVAULT_P256 int rc; +#endif if (g_kv_nvm == NULL) { return PSA_ERROR_NOT_SUPPORTED; @@ -260,7 +291,11 @@ static psa_status_t wt_hsm_kv_generate(int32_t owner, int32_t sub, if (status != PSA_SUCCESS) { return status; } +#if WT_KEYVAULT_P256 if (type == WT_VAULT_KEY_P256) { +#ifdef WOLFPSA_ECC_SP_DIRECT + rc = wolfPSA_P256_Generate(rng, obj, obj + WT_VAULT_KEY_MATERIAL_LEN); +#else rc = wc_ecc_init_ex(&key, NULL, INVALID_DEVID); if (rc != 0) { return PSA_ERROR_GENERIC_ERROR; @@ -276,6 +311,7 @@ static psa_status_t wt_hsm_kv_generate(int32_t owner, int32_t sub, &len); } wc_ecc_free(&key); +#endif if (rc != 0) { wt_hsm_kv_zeroize(obj, sizeof(obj)); return PSA_ERROR_GENERIC_ERROR; @@ -285,6 +321,7 @@ static psa_status_t wt_hsm_kv_generate(int32_t owner, int32_t sub, wt_hsm_kv_zeroize(obj, sizeof(obj)); return status; } +#endif if (type == WT_VAULT_KEY_AES256) { if (wc_RNG_GenerateBlock(rng, d, WT_VAULT_KEY_MATERIAL_LEN) == 0) { status = wt_hsm_kv_store(owner, sub, uid, type, usage, d, @@ -303,8 +340,10 @@ static psa_status_t wt_hsm_kv_import(int32_t owner, int32_t sub, uint64_t uid, uint32_t type, uint32_t usage, const uint8_t* data, size_t len) { +#if WT_KEYVAULT_P256 uint8_t obj[WT_HSM_KEY_P256_OBJ_LEN]; psa_status_t status; +#endif if (g_kv_nvm == NULL) { return PSA_ERROR_NOT_SUPPORTED; @@ -313,6 +352,7 @@ static psa_status_t wt_hsm_kv_import(int32_t owner, int32_t sub, uint64_t uid, len != WT_VAULT_KEY_MATERIAL_LEN) { return PSA_ERROR_INVALID_ARGUMENT; } +#if WT_KEYVAULT_P256 if (type == WT_VAULT_KEY_P256) { status = wt_hsm_kv_p256_object(data, obj); if (status == PSA_SUCCESS) { @@ -322,6 +362,7 @@ static psa_status_t wt_hsm_kv_import(int32_t owner, int32_t sub, uint64_t uid, wt_hsm_kv_zeroize(obj, sizeof(obj)); return status; } +#endif if (type == WT_VAULT_KEY_AES256) { return wt_hsm_kv_store(owner, sub, uid, type, usage, data, WT_HSM_KEY_AES_OBJ_LEN); @@ -329,6 +370,7 @@ static psa_status_t wt_hsm_kv_import(int32_t owner, int32_t sub, uint64_t uid, return PSA_ERROR_NOT_SUPPORTED; } +#if WT_KEYVAULT_P256 /* Public halves are exportable by design; usage bits do not gate this. */ static psa_status_t wt_hsm_kv_export_public(int32_t owner, int32_t sub, uint64_t uid, uint8_t* out, @@ -351,7 +393,7 @@ static psa_status_t wt_hsm_kv_export_public(int32_t owner, int32_t sub, return PSA_SUCCESS; } -#ifndef NO_ASN +#if !defined(NO_ASN) && !defined(WOLFPSA_ECC_SP_DIRECT) /* Sign into DER, then return the fixed-width raw r||s the vault wire uses. */ static int wt_hsm_kv_sign_raw(const uint8_t* digest, word32 digest_len, uint8_t* sig, word32* sig_len, WC_RNG* rng, @@ -401,7 +443,9 @@ static psa_status_t wt_hsm_kv_sign(int32_t owner, int32_t sub, uint64_t uid, uint8_t* sig, size_t cap, size_t* out_len) { uint8_t obj[WT_HSM_KEY_P256_OBJ_LEN]; +#ifndef WOLFPSA_ECC_SP_DIRECT ecc_key key; +#endif WC_RNG* rng; word32 sig_len = WT_VAULT_KEY_SIG_LEN; psa_status_t status; @@ -425,6 +469,9 @@ static psa_status_t wt_hsm_kv_sign(int32_t owner, int32_t sub, uint64_t uid, wt_hsm_kv_zeroize(obj, sizeof(obj)); return status; } +#ifdef WOLFPSA_ECC_SP_DIRECT + rc = wolfPSA_P256_Sign(obj, digest, (word32)digest_len, rng, sig); +#else rc = wc_ecc_init_ex(&key, NULL, INVALID_DEVID); if (rc == 0) { rc = wc_ecc_import_private_key_ex(obj, WT_VAULT_KEY_MATERIAL_LEN, @@ -440,6 +487,7 @@ static psa_status_t wt_hsm_kv_sign(int32_t owner, int32_t sub, uint64_t uid, } wc_ecc_free(&key); } +#endif wt_hsm_kv_zeroize(obj, sizeof(obj)); if (rc != 0 || sig_len != WT_VAULT_KEY_SIG_LEN) { (void)memset(sig, 0, WT_VAULT_KEY_SIG_LEN); @@ -454,7 +502,9 @@ static psa_status_t wt_hsm_kv_verify(int32_t owner, int32_t sub, uint64_t uid, const uint8_t* sig, size_t sig_len) { uint8_t obj[WT_HSM_KEY_P256_OBJ_LEN]; +#ifndef WOLFPSA_ECC_SP_DIRECT ecc_key key; +#endif int res = 0; psa_status_t status; int rc; @@ -469,6 +519,10 @@ static psa_status_t wt_hsm_kv_verify(int32_t owner, int32_t sub, uint64_t uid, if (status != PSA_SUCCESS) { return status; } +#ifdef WOLFPSA_ECC_SP_DIRECT + rc = wolfPSA_P256_Verify(obj + WT_VAULT_KEY_MATERIAL_LEN, digest, + (word32)digest_len, sig, &res); +#else rc = wc_ecc_init_ex(&key, NULL, INVALID_DEVID); if (rc == 0) { rc = wc_ecc_import_x963_ex(obj + WT_VAULT_KEY_MATERIAL_LEN, @@ -484,12 +538,57 @@ static psa_status_t wt_hsm_kv_verify(int32_t owner, int32_t sub, uint64_t uid, } wc_ecc_free(&key); } +#endif wt_hsm_kv_zeroize(obj, sizeof(obj)); if (rc != 0) { return PSA_ERROR_GENERIC_ERROR; } return (res == 1) ? PSA_SUCCESS : PSA_ERROR_INVALID_SIGNATURE; } +#else +/* No P-256 key type in this build: the three P-256 entries refuse. */ +static psa_status_t wt_hsm_kv_export_public(int32_t owner, int32_t sub, + uint64_t uid, uint8_t* out, + size_t cap, size_t* out_len) +{ + (void)owner; + (void)sub; + (void)uid; + (void)out; + (void)cap; + (void)out_len; + return PSA_ERROR_NOT_SUPPORTED; +} + +static psa_status_t wt_hsm_kv_sign(int32_t owner, int32_t sub, uint64_t uid, + const uint8_t* digest, size_t digest_len, + uint8_t* sig, size_t cap, size_t* out_len) +{ + (void)owner; + (void)sub; + (void)uid; + (void)digest; + (void)digest_len; + (void)sig; + (void)cap; + (void)out_len; + return PSA_ERROR_NOT_SUPPORTED; +} + +static psa_status_t wt_hsm_kv_verify(int32_t owner, int32_t sub, uint64_t uid, + const uint8_t* digest, size_t digest_len, + const uint8_t* sig, size_t sig_len) +{ + (void)owner; + (void)sub; + (void)uid; + (void)digest; + (void)digest_len; + (void)sig; + (void)sig_len; + return PSA_ERROR_NOT_SUPPORTED; +} +#endif /* WT_KEYVAULT_P256 */ static psa_status_t wt_hsm_kv_encrypt(int32_t owner, int32_t sub, uint64_t uid, const uint8_t* input, @@ -497,7 +596,6 @@ static psa_status_t wt_hsm_kv_encrypt(int32_t owner, int32_t sub, size_t cap, size_t* out_len) { uint8_t obj[WT_HSM_KEY_AES_OBJ_LEN]; - Aes aes; WC_RNG* rng; psa_status_t status; int rc; @@ -520,24 +618,15 @@ static psa_status_t wt_hsm_kv_encrypt(int32_t owner, int32_t sub, return status; } rc = wc_RNG_GenerateBlock(rng, out, WT_VAULT_KEY_NONCE_LEN); - if (rc == 0) { - rc = wc_AesInit(&aes, NULL, INVALID_DEVID); - if (rc == 0) { - rc = wc_AesGcmSetKey(&aes, obj, WT_VAULT_KEY_MATERIAL_LEN); - if (rc == 0) { - rc = wc_AesGcmEncrypt(&aes, out + WT_VAULT_KEY_NONCE_LEN, - input, (word32)input_len, out, - WT_VAULT_KEY_NONCE_LEN, - out + WT_VAULT_KEY_NONCE_LEN + - input_len, - WT_VAULT_KEY_TAG_LEN, NULL, 0U); - } - wc_AesFree(&aes); - } + status = (rc == 0) ? PSA_SUCCESS : PSA_ERROR_GENERIC_ERROR; + if (status == PSA_SUCCESS) { + status = wt_hsm_aead_encrypt(obj, out, NULL, 0U, input, input_len, + out + WT_VAULT_KEY_NONCE_LEN, + out + WT_VAULT_KEY_NONCE_LEN + input_len); } wt_hsm_kv_zeroize(obj, sizeof(obj)); - if (rc != 0) { - return PSA_ERROR_GENERIC_ERROR; + if (status != PSA_SUCCESS) { + return status; } *out_len = input_len + WT_VAULT_KEY_NONCE_LEN + WT_VAULT_KEY_TAG_LEN; return PSA_SUCCESS; @@ -549,10 +638,8 @@ static psa_status_t wt_hsm_kv_decrypt(int32_t owner, int32_t sub, size_t cap, size_t* out_len) { uint8_t obj[WT_HSM_KEY_AES_OBJ_LEN]; - Aes aes; size_t pt_len; psa_status_t status; - int rc; if (input_len < WT_VAULT_KEY_NONCE_LEN + WT_VAULT_KEY_TAG_LEN) { return PSA_ERROR_INVALID_ARGUMENT; @@ -567,27 +654,13 @@ static psa_status_t wt_hsm_kv_decrypt(int32_t owner, int32_t sub, if (status != PSA_SUCCESS) { return status; } - rc = wc_AesInit(&aes, NULL, INVALID_DEVID); - if (rc == 0) { - rc = wc_AesGcmSetKey(&aes, obj, WT_VAULT_KEY_MATERIAL_LEN); - if (rc == 0) { - rc = wc_AesGcmDecrypt(&aes, out, - input + WT_VAULT_KEY_NONCE_LEN, - (word32)pt_len, input, - WT_VAULT_KEY_NONCE_LEN, - input + input_len - WT_VAULT_KEY_TAG_LEN, - WT_VAULT_KEY_TAG_LEN, NULL, 0U); - } - wc_AesFree(&aes); - } + status = wt_hsm_aead_decrypt(obj, input, NULL, 0U, + input + WT_VAULT_KEY_NONCE_LEN, pt_len, + input + input_len - WT_VAULT_KEY_TAG_LEN, + out); wt_hsm_kv_zeroize(obj, sizeof(obj)); - if (rc != 0) { - /* wolfSSL leaves out[] undefined after a non-zero AES-GCM decrypt; - * clear the plaintext region so no unauthenticated bytes survive in - * the shared response band. */ - wt_hsm_kv_zeroize(out, pt_len); - return (rc == AES_GCM_AUTH_E) ? PSA_ERROR_INVALID_SIGNATURE : - PSA_ERROR_GENERIC_ERROR; + if (status != PSA_SUCCESS) { + return status; } *out_len = pt_len; return PSA_SUCCESS; diff --git a/src/services/native/native_wire.c b/src/services/native/native_wire.c index a325d0d79..cede62861 100644 --- a/src/services/native/native_wire.c +++ b/src/services/native/native_wire.c @@ -42,6 +42,10 @@ #include "wolftrust/services/psa_crypto_service.h" #endif +#ifndef WT_VAULT_ECC +#define WT_VAULT_ECC 1 +#endif + /* ========================================================================= * wt_native_submit — SERVICE_HSM's native wire backend. * @@ -110,6 +114,14 @@ int wt_native_submit(void* submit_ctx, int32_t client_id, const uint8_t* req, else if (hdr.op != WT_CRYPTO_OP_PSA && WT_PSA_UID_RESERVED(hdr.uid)) { status = PSA_ERROR_NOT_PERMITTED; } +#if !WT_VAULT_ECC + /* The backend may still hold P-256 for an ECC attestation key. */ + else if ((hdr.op == WT_CRYPTO_OP_KEY_GENERATE || + hdr.op == WT_CRYPTO_OP_KEY_IMPORT) && + hdr.key_type == WT_VAULT_KEY_P256) { + status = PSA_ERROR_NOT_SUPPORTED; + } +#endif else switch (hdr.op) { #ifdef WT_SECURE_PSA case WT_CRYPTO_OP_PSA: @@ -126,6 +138,7 @@ int wt_native_submit(void* submit_ctx, int32_t client_id, const uint8_t* req, hdr.key_type, hdr.usage, payload, payload_len); break; +#if WT_VAULT_ECC case WT_CRYPTO_OP_KEY_EXPORT_PUBLIC: status = wt_hsm_key_backend.export_public(owner, client_id, hdr.uid, out, out_cap, &out_len); @@ -149,6 +162,7 @@ int wt_native_submit(void* submit_ctx, int32_t client_id, const uint8_t* req, WT_VAULT_KEY_SIG_LEN); } break; +#endif case WT_CRYPTO_OP_KEY_ENCRYPT: status = wt_hsm_key_backend.encrypt(owner, client_id, hdr.uid, payload, payload_len, out, diff --git a/src/services/native/psa_crypto_service.c b/src/services/native/psa_crypto_service.c index 90ec9cdb0..a98cec3d9 100644 --- a/src/services/native/psa_crypto_service.c +++ b/src/services/native/psa_crypto_service.c @@ -644,7 +644,7 @@ static psa_status_t wt_psa_attr_get(const uint8_t* p, size_t len, attr->policy.alg = (psa_algorithm_t)wt_psa_rd32(p + 12); attr->policy.alg2 = (psa_algorithm_t)wt_psa_rd32(p + 16); attr->id = (psa_key_id_t)wt_psa_rd32(p + 20); -#ifdef WT_SECURE_PSA_symmetric +#ifdef WT_SECURE_PSA_tiny /* wolfCrypt keeps ECC for the native engine; the profile serves none. */ if (PSA_KEY_TYPE_IS_ECC(attr->type)) { return PSA_ERROR_NOT_SUPPORTED; @@ -745,10 +745,7 @@ static psa_status_t wt_psa_keys_fn(uint32_t fn, wt_psa_call_t* c) break; case WT_PSA_FN_GET_KEY_ATTRIBUTES: attr = psa_key_attributes_init(); - status = wt_psa_key_ok(A(0)); - if (status == PSA_SUCCESS) { - status = psa_get_key_attributes(A(0), &attr); - } + status = psa_get_key_attributes(A(0), &attr); if (status == PSA_SUCCESS) { status = wt_psa_attr_put(&attr, OUT(0), CAP(0), OL(0)); } @@ -771,10 +768,7 @@ static psa_status_t wt_psa_keys_fn(uint32_t fn, wt_psa_call_t* c) c->val = (status == PSA_SUCCESS) ? id : 0U; break; case WT_PSA_FN_COPY_KEY: - status = wt_psa_key_ok(A(0)); - if (status == PSA_SUCCESS) { - status = wt_psa_attr_get(IN(0), INL(0), &attr); - } + status = wt_psa_attr_get(IN(0), INL(0), &attr); if (status == PSA_SUCCESS) { status = psa_copy_key(A(0), &attr, &id); status = wt_psa_key_add(status, id); @@ -782,31 +776,19 @@ static psa_status_t wt_psa_keys_fn(uint32_t fn, wt_psa_call_t* c) c->val = (status == PSA_SUCCESS) ? id : 0U; break; case WT_PSA_FN_EXPORT_KEY: - status = wt_psa_key_ok(A(0)); - if (status == PSA_SUCCESS) { - status = psa_export_key(A(0), OUT(0), CAP(0), OL(0)); - } + status = psa_export_key(A(0), OUT(0), CAP(0), OL(0)); break; case WT_PSA_FN_EXPORT_PUBLIC_KEY: - status = wt_psa_key_ok(A(0)); - if (status == PSA_SUCCESS) { - status = psa_export_public_key(A(0), OUT(0), CAP(0), OL(0)); - } + status = psa_export_public_key(A(0), OUT(0), CAP(0), OL(0)); break; case WT_PSA_FN_DESTROY_KEY: - status = wt_psa_key_ok(A(0)); - if (status == PSA_SUCCESS) { - status = psa_destroy_key(A(0)); - } + status = psa_destroy_key(A(0)); if (status == PSA_SUCCESS) { wt_psa_key_drop(A(0)); } break; case WT_PSA_FN_PURGE_KEY: - status = wt_psa_key_ok(A(0)); - if (status == PSA_SUCCESS) { - status = psa_purge_key(A(0)); - } + status = psa_purge_key(A(0)); break; default: status = PSA_ERROR_NOT_SUPPORTED; @@ -854,26 +836,17 @@ static psa_status_t wt_psa_hash_mac_fn(uint32_t fn, wt_psa_call_t* c) c->op = tgt; break; case WT_PSA_FN_MAC_COMPUTE: - status = wt_psa_key_ok(A(0)); - if (status == PSA_SUCCESS) { - status = psa_mac_compute(A(0), A(1), IN(0), INL(0), OUT(0), CAP(0), - OL(0)); - } + status = psa_mac_compute(A(0), A(1), IN(0), INL(0), OUT(0), CAP(0), + OL(0)); break; case WT_PSA_FN_MAC_VERIFY: - status = wt_psa_key_ok(A(0)); - if (status == PSA_SUCCESS) { - status = psa_mac_verify(A(0), A(1), IN(0), INL(0), IN(1), INL(1)); - } + status = psa_mac_verify(A(0), A(1), IN(0), INL(0), IN(1), INL(1)); break; case WT_PSA_FN_MAC_SIGN_SETUP: case WT_PSA_FN_MAC_VERIFY_SETUP: - status = wt_psa_key_ok(A(1)); - if (status == PSA_SUCCESS) { - status = (fn == WT_PSA_FN_MAC_SIGN_SETUP) ? - psa_mac_sign_setup(m, A(1), A(2)) : - psa_mac_verify_setup(m, A(1), A(2)); - } + status = (fn == WT_PSA_FN_MAC_SIGN_SETUP) ? + psa_mac_sign_setup(m, A(1), A(2)) : + psa_mac_verify_setup(m, A(1), A(2)); break; case WT_PSA_FN_MAC_UPDATE: status = psa_mac_update(m, IN(0), INL(0)); @@ -899,23 +872,17 @@ static psa_status_t wt_psa_cipher_fn(uint32_t fn, wt_psa_call_t* c) switch (fn) { case WT_PSA_FN_CIPHER_ENCRYPT: case WT_PSA_FN_CIPHER_DECRYPT: - status = wt_psa_key_ok(A(0)); - if (status == PSA_SUCCESS) { - status = (fn == WT_PSA_FN_CIPHER_ENCRYPT) ? - psa_cipher_encrypt(A(0), A(1), IN(0), INL(0), OUT(0), - CAP(0), OL(0)) : - psa_cipher_decrypt(A(0), A(1), IN(0), INL(0), OUT(0), - CAP(0), OL(0)); - } + status = (fn == WT_PSA_FN_CIPHER_ENCRYPT) ? + psa_cipher_encrypt(A(0), A(1), IN(0), INL(0), OUT(0), + CAP(0), OL(0)) : + psa_cipher_decrypt(A(0), A(1), IN(0), INL(0), OUT(0), + CAP(0), OL(0)); break; case WT_PSA_FN_CIPHER_ENCRYPT_SETUP: case WT_PSA_FN_CIPHER_DECRYPT_SETUP: - status = wt_psa_key_ok(A(1)); - if (status == PSA_SUCCESS) { - status = (fn == WT_PSA_FN_CIPHER_ENCRYPT_SETUP) ? - psa_cipher_encrypt_setup(o, A(1), A(2)) : - psa_cipher_decrypt_setup(o, A(1), A(2)); - } + status = (fn == WT_PSA_FN_CIPHER_ENCRYPT_SETUP) ? + psa_cipher_encrypt_setup(o, A(1), A(2)) : + psa_cipher_decrypt_setup(o, A(1), A(2)); break; case WT_PSA_FN_CIPHER_GENERATE_IV: status = psa_cipher_generate_iv(o, OUT(0), CAP(0), OL(0)); @@ -944,23 +911,17 @@ static psa_status_t wt_psa_aead_fn(uint32_t fn, wt_psa_call_t* c) switch (fn) { case WT_PSA_FN_AEAD_ENCRYPT: case WT_PSA_FN_AEAD_DECRYPT: - status = wt_psa_key_ok(A(0)); - if (status == PSA_SUCCESS) { - status = (fn == WT_PSA_FN_AEAD_ENCRYPT) ? - psa_aead_encrypt(A(0), A(1), IN(0), INL(0), IN(1), INL(1), - IN(2), INL(2), OUT(0), CAP(0), OL(0)) : - psa_aead_decrypt(A(0), A(1), IN(0), INL(0), IN(1), INL(1), - IN(2), INL(2), OUT(0), CAP(0), OL(0)); - } + status = (fn == WT_PSA_FN_AEAD_ENCRYPT) ? + psa_aead_encrypt(A(0), A(1), IN(0), INL(0), IN(1), INL(1), + IN(2), INL(2), OUT(0), CAP(0), OL(0)) : + psa_aead_decrypt(A(0), A(1), IN(0), INL(0), IN(1), INL(1), + IN(2), INL(2), OUT(0), CAP(0), OL(0)); break; case WT_PSA_FN_AEAD_ENCRYPT_SETUP: case WT_PSA_FN_AEAD_DECRYPT_SETUP: - status = wt_psa_key_ok(A(1)); - if (status == PSA_SUCCESS) { - status = (fn == WT_PSA_FN_AEAD_ENCRYPT_SETUP) ? - psa_aead_encrypt_setup(o, A(1), A(2)) : - psa_aead_decrypt_setup(o, A(1), A(2)); - } + status = (fn == WT_PSA_FN_AEAD_ENCRYPT_SETUP) ? + psa_aead_encrypt_setup(o, A(1), A(2)) : + psa_aead_decrypt_setup(o, A(1), A(2)); break; case WT_PSA_FN_AEAD_GENERATE_NONCE: status = psa_aead_generate_nonce(o, OUT(0), CAP(0), OL(0)); @@ -1015,18 +976,12 @@ static psa_status_t wt_psa_kdf_fn(uint32_t fn, wt_psa_call_t* c) status = psa_key_derivation_input_bytes(o, A(1), IN(0), INL(0)); break; case WT_PSA_FN_KDF_INPUT_KEY: - status = wt_psa_key_ok(A(2)); - if (status == PSA_SUCCESS) { - status = psa_key_derivation_input_key(o, A(1), A(2)); - } + status = psa_key_derivation_input_key(o, A(1), A(2)); break; -#ifndef WT_SECURE_PSA_symmetric +#ifndef WT_SECURE_PSA_tiny case WT_PSA_FN_KDF_KEY_AGREEMENT: - status = wt_psa_key_ok(A(2)); - if (status == PSA_SUCCESS) { - status = psa_key_derivation_key_agreement(o, A(1), A(2), IN(0), - INL(0)); - } + status = psa_key_derivation_key_agreement(o, A(1), A(2), IN(0), + INL(0)); break; #endif case WT_PSA_FN_KDF_OUTPUT_BYTES: @@ -1052,10 +1007,7 @@ static psa_status_t wt_psa_kdf_fn(uint32_t fn, wt_psa_call_t* c) status = psa_key_derivation_verify_bytes(o, IN(0), INL(0)); break; case WT_PSA_FN_KDF_VERIFY_KEY: - status = wt_psa_key_ok(A(1)); - if (status == PSA_SUCCESS) { - status = psa_key_derivation_verify_key(o, A(1)); - } + status = psa_key_derivation_verify_key(o, A(1)); break; case WT_PSA_FN_KDF_ABORT: status = psa_key_derivation_abort(o); @@ -1067,18 +1019,13 @@ static psa_status_t wt_psa_kdf_fn(uint32_t fn, wt_psa_call_t* c) return status; } -#ifndef WT_SECURE_PSA_symmetric +#ifndef WT_SECURE_PSA_tiny static psa_status_t wt_psa_asym_fn(uint32_t fn, wt_psa_call_t* c) { psa_key_attributes_t attr; psa_key_id_t id = PSA_KEY_ID_NULL; psa_status_t status; - status = wt_psa_key_ok((fn == WT_PSA_FN_RAW_KEY_AGREEMENT || - fn == WT_PSA_FN_KEY_AGREEMENT) ? A(1) : A(0)); - if (status != PSA_SUCCESS) { - return status; - } switch (fn) { case WT_PSA_FN_KEY_AGREEMENT: status = wt_psa_attr_get(IN(1), INL(1), &attr); @@ -1089,6 +1036,7 @@ static psa_status_t wt_psa_asym_fn(uint32_t fn, wt_psa_call_t* c) } c->val = (status == PSA_SUCCESS) ? id : 0U; break; +#if defined(PSA_WANT_ALG_RSA_PKCS1V15_CRYPT) || defined(PSA_WANT_ALG_RSA_OAEP) case WT_PSA_FN_ASYMMETRIC_ENCRYPT: status = psa_asymmetric_encrypt(A(0), A(1), IN(0), INL(0), IN(1), INL(1), OUT(0), CAP(0), OL(0)); @@ -1097,6 +1045,7 @@ static psa_status_t wt_psa_asym_fn(uint32_t fn, wt_psa_call_t* c) status = psa_asymmetric_decrypt(A(0), A(1), IN(0), INL(0), IN(1), INL(1), OUT(0), CAP(0), OL(0)); break; +#endif case WT_PSA_FN_SIGN_HASH: status = psa_sign_hash(A(0), A(1), IN(0), INL(0), OUT(0), CAP(0), OL(0)); @@ -1123,10 +1072,70 @@ static psa_status_t wt_psa_asym_fn(uint32_t fn, wt_psa_call_t* c) } #endif +/* Wire argument holding the caller's key id, plus one; 0 when there is none */ +static uint32_t wt_psa_key_arg(uint32_t fn) +{ + uint32_t arg = 0U; + + switch (fn) { + case WT_PSA_FN_GET_KEY_ATTRIBUTES: + case WT_PSA_FN_EXPORT_KEY: + case WT_PSA_FN_EXPORT_PUBLIC_KEY: + case WT_PSA_FN_DESTROY_KEY: + case WT_PSA_FN_PURGE_KEY: + case WT_PSA_FN_COPY_KEY: + case WT_PSA_FN_MAC_COMPUTE: + case WT_PSA_FN_MAC_VERIFY: + case WT_PSA_FN_CIPHER_ENCRYPT: + case WT_PSA_FN_CIPHER_DECRYPT: + case WT_PSA_FN_AEAD_ENCRYPT: + case WT_PSA_FN_AEAD_DECRYPT: +#ifndef WT_SECURE_PSA_tiny + case WT_PSA_FN_SIGN_HASH: + case WT_PSA_FN_VERIFY_HASH: + case WT_PSA_FN_SIGN_MESSAGE: + case WT_PSA_FN_VERIFY_MESSAGE: + case WT_PSA_FN_ASYMMETRIC_ENCRYPT: + case WT_PSA_FN_ASYMMETRIC_DECRYPT: +#endif + arg = 1U; + break; + case WT_PSA_FN_MAC_SIGN_SETUP: + case WT_PSA_FN_MAC_VERIFY_SETUP: + case WT_PSA_FN_CIPHER_ENCRYPT_SETUP: + case WT_PSA_FN_CIPHER_DECRYPT_SETUP: + case WT_PSA_FN_AEAD_ENCRYPT_SETUP: + case WT_PSA_FN_AEAD_DECRYPT_SETUP: + case WT_PSA_FN_KDF_VERIFY_KEY: +#ifndef WT_SECURE_PSA_tiny + case WT_PSA_FN_RAW_KEY_AGREEMENT: + case WT_PSA_FN_KEY_AGREEMENT: +#endif + arg = 2U; + break; + case WT_PSA_FN_KDF_INPUT_KEY: +#ifndef WT_SECURE_PSA_tiny + case WT_PSA_FN_KDF_KEY_AGREEMENT: +#endif + arg = 3U; + break; + default: + break; + } + return arg; +} + static psa_status_t wt_psa_fn(uint32_t fn, wt_psa_call_t* c) { - psa_status_t status; + psa_status_t status = PSA_SUCCESS; + uint32_t key_arg = wt_psa_key_arg(fn); + if (key_arg != 0U) { + status = wt_psa_key_ok(A(key_arg - 1U)); + } + if (status != PSA_SUCCESS) { + return status; + } if (fn == WT_PSA_FN_CRYPTO_INIT) { wt_psa_client_reset(g_psa_client); status = PSA_SUCCESS; @@ -1147,7 +1156,7 @@ static psa_status_t wt_psa_fn(uint32_t fn, wt_psa_call_t* c) else if (fn >= WT_PSA_FN_KDF_SETUP && fn <= WT_PSA_FN_KDF_ABORT) { status = wt_psa_kdf_fn(fn, c); } -#ifndef WT_SECURE_PSA_symmetric +#ifndef WT_SECURE_PSA_tiny else if (fn >= WT_PSA_FN_SIGN_HASH && fn <= WT_PSA_FN_ASYMMETRIC_DECRYPT) { status = wt_psa_asym_fn(fn, c); diff --git a/src/services/wolfhsm/runner/secure_psa_profile.h b/src/services/wolfhsm/runner/secure_psa_profile.h index 0a2493e4c..3a2f090dc 100644 --- a/src/services/wolfhsm/runner/secure_psa_profile.h +++ b/src/services/wolfhsm/runner/secure_psa_profile.h @@ -24,28 +24,49 @@ #ifndef WOLFTRUST_SECURE_PSA_PROFILE_H #define WOLFTRUST_SECURE_PSA_PROFILE_H +/* The vault's AES AEAD, and the one PSA AEAD of small and tiny */ +#if defined(WT_AEAD_GCM) && defined(WT_AEAD_CCM) +#error "WT_AEAD_GCM and WT_AEAD_CCM are exclusive" +#endif +#if defined(WT_SECURE_PSA_small) || defined(WT_SECURE_PSA_tiny) +#define WT_PSA_ONE_AEAD +#if !defined(WT_AEAD_GCM) && !defined(WT_AEAD_CCM) +#define WT_AEAD_CCM +#endif +#endif + #ifdef WT_SECURE_PSA -#if defined(WT_PSA_WANT_PROBE) && defined(WT_SECURE_PSA_symmetric) +#if defined(WT_PSA_WANT_PROBE) && defined(WT_SECURE_PSA_tiny) /* The vault keeps ECC; the PSA_WANT_* surface of this profile does not. */ #undef HAVE_ECC #endif #define WC_ALLOW_ECC_ZERO_HASH +/* One copy of wolfCrypt's misc.c helpers, built by wolfPSA's misc_impl.c */ +#define NO_INLINE /* wolfPSA refuses T-table AES and a GHASH that branches on the hash key. */ #define WOLFSSL_AES_TOUCH_LINES #undef GCM_SMALL #define WOLFSSL_AES_COUNTER -/* wolfPSA's multipart GCM runs on the wolfCrypt GCM streaming calls. */ +#if !defined(WT_PSA_ONE_AEAD) || !defined(WT_AEAD_CCM) +/* wolfPSA's multipart and one-shot GCM run on the wolfCrypt GCM streaming + * calls, so the one-shot calls are not linked. */ #define WOLFSSL_AESGCM_STREAM -#if !defined(WT_SECURE_PSA_lean) && !defined(WT_SECURE_PSA_symmetric) +#define WOLFPSA_GCM_ONESHOT_STREAM +#endif +#if !defined(WT_PSA_ONE_AEAD) || defined(WT_AEAD_CCM) #define HAVE_AESCCM /* wolfPSA's multipart CCM runs on the direct AES block calls. */ #define WOLFSSL_AES_DIRECT #endif #define HAVE_ECC_DHE -#if defined(WT_SECURE_PSA_compat) || defined(WT_SECURE_PSA_standard) +/* wolfPSA's direct P-256 path is randomized ECDSA only, so extended keeps ecc.c */ +#ifndef WT_SECURE_PSA_extended +#define WOLFPSA_ECC_SP_DIRECT +#endif +#if defined(WT_SECURE_PSA_extended) || defined(WT_SECURE_PSA_default) #undef NO_AES_DECRYPT #endif -#ifdef WT_SECURE_PSA_compat +#ifdef WT_SECURE_PSA_extended #define HAVE_AES_ECB #define WOLFSSL_ECDSA_DETERMINISTIC_K #undef NO_PWDBASED @@ -56,10 +77,6 @@ #define NO_PBKDF2 #define NO_KDF #endif -#if defined(WT_PSA_POOL_TU) && defined(NO_AES_CBC) -#define wc_AesCbcEncrypt(a, o, i, s) ((void)(a), (void)(o), (void)(i), (void)(s), -174) -#define wc_AesCbcDecrypt(a, o, i, s) ((void)(a), (void)(o), (void)(i), (void)(s), -174) -#endif #ifdef WT_PSA_POOL_TU #define XMALLOC_OVERRIDE void* wt_psa_pool_alloc(unsigned int sz); @@ -71,4 +88,23 @@ void* wt_psa_pool_realloc(void* p, unsigned int sz); #endif #endif +#ifdef WT_NO_ECC +/* No feature of this build uses ECC: no curve and no big-number code. */ +#undef HAVE_ECC +#undef HAVE_ECC_DHE +#undef WOLFSSL_HAVE_SP_ECC +#undef WOLFSSL_SP_MATH +#undef WOLFSSL_SP_MATH_ALL +#undef WOLFPSA_ECC_SP_DIRECT +#define NO_BIG_INT +#endif + +#if defined(WT_AEAD_CCM) && !defined(HAVE_AESCCM) +#define HAVE_AESCCM +#endif +#ifdef WT_AEAD_CCM +/* wolfCrypt builds CCM decrypt only with HAVE_AES_DECRYPT; it runs AES forward */ +#undef NO_AES_DECRYPT +#endif + #endif /* WOLFTRUST_SECURE_PSA_PROFILE_H */ diff --git a/src/services/wolfhsm/wt_hsm_aead.c b/src/services/wolfhsm/wt_hsm_aead.c new file mode 100644 index 000000000..6e8b13ef3 --- /dev/null +++ b/src/services/wolfhsm/wt_hsm_aead.c @@ -0,0 +1,161 @@ +/* wt_hsm_aead.c + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of wolfTrust. + * + * wolfTrust 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. + * + * wolfTrust 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, see . + */ + +/* AES-256 AEAD for the vault sealer and native vault key encryption: GCM, + * or CCM under WT_AEAD_CCM. Callers own the key and a unique nonce. */ + +#include "wolfssl/wolfcrypt/settings.h" +#include "wolfssl/wolfcrypt/types.h" +#include "wolfssl/wolfcrypt/aes.h" +#include "wolfssl/wolfcrypt/error-crypt.h" + +#include "wolftrust/services/hsm.h" +#include "wolftrust/zeroize.h" + +#if defined(WT_AEAD_CCM) && !defined(HAVE_AESCCM) +#error "WT_AEAD_CCM needs HAVE_AESCCM" +#endif +#if !defined(WT_AEAD_CCM) && !defined(HAVE_AESGCM) +#error "the vault AEAD needs HAVE_AESGCM, or WT_AEAD_CCM" +#endif +/* With wolfPSA in the image, the AEAD runs on its streaming code, so + * wolfCrypt's one-shot GCM or CCM is not linked twice over. */ +#if defined(WT_SECURE_PSA) && defined(WT_AEAD_CCM) +#define WT_AEAD_WOLFPSA +#include "wolfpsa/psa_ccm.h" +#define WT_AEAD_SEAL wolfPSA_AesCcmEncrypt +#define WT_AEAD_OPEN wolfPSA_AesCcmDecrypt +#define WT_AEAD_AUTH_E AES_CCM_AUTH_E +#elif defined(WT_SECURE_PSA) && defined(WOLFPSA_GCM_ONESHOT_STREAM) +#define WT_AEAD_WOLFPSA +#include "wolfpsa/psa_gcm.h" +#define WT_AEAD_SEAL wolfPSA_AesGcmEncrypt +#define WT_AEAD_OPEN wolfPSA_AesGcmDecrypt +#define WT_AEAD_AUTH_E AES_GCM_AUTH_E +#endif + +#ifdef WT_AEAD_WOLFPSA +psa_status_t wt_hsm_aead_encrypt(const uint8_t* key, const uint8_t* nonce, + const uint8_t* aad, size_t aad_len, + const uint8_t* in, size_t len, uint8_t* out, + uint8_t* tag) +{ + int rc; + + rc = WT_AEAD_SEAL(key, WT_HSM_AEAD_KEY_LEN, nonce, WT_HSM_AEAD_NONCE_LEN, + aad, (word32)aad_len, in, (word32)len, out, tag, + WT_HSM_AEAD_TAG_LEN); + return (rc == 0) ? PSA_SUCCESS : PSA_ERROR_GENERIC_ERROR; +} + +psa_status_t wt_hsm_aead_decrypt(const uint8_t* key, const uint8_t* nonce, + const uint8_t* aad, size_t aad_len, + const uint8_t* in, size_t len, + const uint8_t* tag, uint8_t* out) +{ + int rc; + + rc = WT_AEAD_OPEN(key, WT_HSM_AEAD_KEY_LEN, nonce, WT_HSM_AEAD_NONCE_LEN, + aad, (word32)aad_len, in, (word32)len, tag, + WT_HSM_AEAD_TAG_LEN, out); + if (rc == 0) { + return PSA_SUCCESS; + } + /* No unauthenticated plaintext may survive a failed decrypt */ + wt_forceZero(out, len); + return (rc == WT_AEAD_AUTH_E) ? PSA_ERROR_INVALID_SIGNATURE : + PSA_ERROR_GENERIC_ERROR; +} +#else + +psa_status_t wt_hsm_aead_encrypt(const uint8_t* key, const uint8_t* nonce, + const uint8_t* aad, size_t aad_len, + const uint8_t* in, size_t len, uint8_t* out, + uint8_t* tag) +{ + Aes aes; + int rc; + + rc = wc_AesInit(&aes, NULL, INVALID_DEVID); + if (rc == 0) { +#ifdef WT_AEAD_CCM + rc = wc_AesCcmSetKey(&aes, key, WT_HSM_AEAD_KEY_LEN); + if (rc == 0) { + rc = wc_AesCcmEncrypt(&aes, out, in, (word32)len, nonce, + WT_HSM_AEAD_NONCE_LEN, tag, + WT_HSM_AEAD_TAG_LEN, aad, (word32)aad_len); + } +#else + rc = wc_AesGcmSetKey(&aes, key, WT_HSM_AEAD_KEY_LEN); + if (rc == 0) { + rc = wc_AesGcmEncrypt(&aes, out, in, (word32)len, nonce, + WT_HSM_AEAD_NONCE_LEN, tag, + WT_HSM_AEAD_TAG_LEN, aad, (word32)aad_len); + } +#endif + wc_AesFree(&aes); + } + return (rc == 0) ? PSA_SUCCESS : PSA_ERROR_GENERIC_ERROR; +} + +psa_status_t wt_hsm_aead_decrypt(const uint8_t* key, const uint8_t* nonce, + const uint8_t* aad, size_t aad_len, + const uint8_t* in, size_t len, + const uint8_t* tag, uint8_t* out) +{ + Aes aes; + psa_status_t status = PSA_SUCCESS; + int rc; + + rc = wc_AesInit(&aes, NULL, INVALID_DEVID); + if (rc == 0) { +#ifdef WT_AEAD_CCM + rc = wc_AesCcmSetKey(&aes, key, WT_HSM_AEAD_KEY_LEN); + if (rc == 0) { + rc = wc_AesCcmDecrypt(&aes, out, in, (word32)len, nonce, + WT_HSM_AEAD_NONCE_LEN, tag, + WT_HSM_AEAD_TAG_LEN, aad, (word32)aad_len); + } + if (rc == AES_CCM_AUTH_E) { + status = PSA_ERROR_INVALID_SIGNATURE; + } +#else + rc = wc_AesGcmSetKey(&aes, key, WT_HSM_AEAD_KEY_LEN); + if (rc == 0) { + rc = wc_AesGcmDecrypt(&aes, out, in, (word32)len, nonce, + WT_HSM_AEAD_NONCE_LEN, tag, + WT_HSM_AEAD_TAG_LEN, aad, (word32)aad_len); + } + if (rc == AES_GCM_AUTH_E) { + status = PSA_ERROR_INVALID_SIGNATURE; + } +#endif + wc_AesFree(&aes); + } + if (rc != 0) { + /* No unauthenticated plaintext may survive a failed decrypt */ + wt_forceZero(out, len); + if (status == PSA_SUCCESS) { + status = PSA_ERROR_GENERIC_ERROR; + } + } + return status; +} +#endif /* WT_AEAD_WOLFPSA */ diff --git a/src/services/wolfhsm/wt_hsm_seal.c b/src/services/wolfhsm/wt_hsm_seal.c index 620c8e665..7bd2fbcc8 100644 --- a/src/services/wolfhsm/wt_hsm_seal.c +++ b/src/services/wolfhsm/wt_hsm_seal.c @@ -18,10 +18,11 @@ * along with this program; if not, see . */ -/* wolfCrypt AES-256-GCM vault sealer (WT-FFM-0048). The device-unique key is - * generated on first boot, stored at WT_HSM_SEAL_KEY_ID as NONEXPORTABLE and - * immutable, and cached in the shared keystore trust band granted only to the - * confined keystore partitions. The GCM nonce is the caller-supplied +/* wolfCrypt AES-256 AEAD vault sealer (WT-FFM-0048), GCM or WT_AEAD=ccm. + * The device-unique key is generated on first boot, stored at + * WT_HSM_SEAL_KEY_ID as NONEXPORTABLE and immutable, and cached in the shared + * keystore trust band granted only to the confined keystore partitions. The + * AEAD nonce is the caller-supplied * monotonic rollback counter, unique per sealed write by construction, so a * rolled-back ciphertext fails tag authentication on unseal. */ @@ -43,6 +44,11 @@ #define WT_HSM_SEAL_KEY_LEN 32U #define WT_HSM_SEAL_NONCE_LEN 12U +#if WT_HSM_SEAL_KEY_LEN != WT_HSM_AEAD_KEY_LEN || \ + WT_HSM_SEAL_NONCE_LEN != WT_HSM_AEAD_NONCE_LEN || \ + WT_VAULT_SEAL_TAG_LEN != WT_HSM_AEAD_TAG_LEN +#error "the seal format must match the vault AEAD sizes" +#endif #define WT_HSM_SEAL_LABEL_MAGIC 0x4B535457UL /* "WTSK" little-endian */ @@ -159,35 +165,22 @@ static psa_status_t wt_hsm_seal_seal(const uint8_t* aad, size_t aad_len, uint64_t counter, const uint8_t* pt, size_t pt_len, uint8_t* ct) { - Aes aes; uint8_t nonce[WT_HSM_SEAL_NONCE_LEN]; - int rc; if (g_seal_ready == 0) { return PSA_ERROR_NOT_SUPPORTED; } wt_hsm_seal_nonce(nonce, counter); - rc = wc_AesInit(&aes, NULL, INVALID_DEVID); - if (rc == 0) { - rc = wc_AesGcmSetKey(&aes, g_seal_key, WT_HSM_SEAL_KEY_LEN); - } - if (rc == 0) { - rc = wc_AesGcmEncrypt(&aes, ct, pt, (word32)pt_len, nonce, - WT_HSM_SEAL_NONCE_LEN, ct + pt_len, - WT_VAULT_SEAL_TAG_LEN, aad, (word32)aad_len); - } - wc_AesFree(&aes); - return (rc == 0) ? PSA_SUCCESS : PSA_ERROR_GENERIC_ERROR; + return wt_hsm_aead_encrypt(g_seal_key, nonce, aad, aad_len, pt, pt_len, ct, + ct + pt_len); } static psa_status_t wt_hsm_seal_unseal(const uint8_t* aad, size_t aad_len, uint64_t counter, const uint8_t* ct, size_t ct_len, uint8_t* pt) { - Aes aes; uint8_t nonce[WT_HSM_SEAL_NONCE_LEN]; size_t pt_len; - int rc; if (g_seal_ready == 0) { return PSA_ERROR_NOT_SUPPORTED; @@ -197,20 +190,8 @@ static psa_status_t wt_hsm_seal_unseal(const uint8_t* aad, size_t aad_len, } pt_len = ct_len - WT_VAULT_SEAL_TAG_LEN; wt_hsm_seal_nonce(nonce, counter); - rc = wc_AesInit(&aes, NULL, INVALID_DEVID); - if (rc == 0) { - rc = wc_AesGcmSetKey(&aes, g_seal_key, WT_HSM_SEAL_KEY_LEN); - } - if (rc == 0) { - rc = wc_AesGcmDecrypt(&aes, pt, ct, (word32)pt_len, nonce, - WT_HSM_SEAL_NONCE_LEN, ct + pt_len, - WT_VAULT_SEAL_TAG_LEN, aad, (word32)aad_len); - } - wc_AesFree(&aes); - if (rc == AES_GCM_AUTH_E) { - return PSA_ERROR_INVALID_SIGNATURE; - } - return (rc == 0) ? PSA_SUCCESS : PSA_ERROR_GENERIC_ERROR; + return wt_hsm_aead_decrypt(g_seal_key, nonce, aad, aad_len, ct, pt_len, + ct + pt_len, pt); } const wt_vault_sealer_t wt_hsm_sealer = { diff --git a/src/spm_partitions.c b/src/spm_partitions.c index a83261aa1..c266639e4 100644 --- a/src/spm_partitions.c +++ b/src/spm_partitions.c @@ -260,7 +260,8 @@ static void wt_spm_hsm_entry(void* arg) } } -#if defined(WT_ATTEST_COSE) && (WT_ATTEST_COSE == 1) +#if defined(WT_ATTEST_COSE) && (WT_ATTEST_COSE == 1) && \ + !defined(WT_ATTEST_KEY_hmac) /* What boot established about the attestation signer, kept in SPM RAM: a * restarted crypto partition is rebuilt from this, never from its own band. */ static uint8_t g_spm_iak_public[WT_HSM_ATTEST_PUBLIC_KEY_LEN]; @@ -318,7 +319,8 @@ static int wt_spm_hsm_bind(int32_t partition_id) #endif wt_hsm_relay_set_submit(wt_native_submit, (void*)(intptr_t)partition_id); #endif -#if defined(WT_ATTEST_COSE) && (WT_ATTEST_COSE == 1) +#if defined(WT_ATTEST_COSE) && (WT_ATTEST_COSE == 1) && \ + !defined(WT_ATTEST_KEY_hmac) wt_hsm_relay_set_attest_ops(PARTITION_ATTEST_ID, wt_hsm_attest_sign, wt_hsm_attest_public_key); #endif @@ -346,7 +348,8 @@ static int wt_spm_hsm_restore(int32_t partition_id) } #endif #endif -#if defined(WT_ATTEST_COSE) && (WT_ATTEST_COSE == 1) +#if defined(WT_ATTEST_COSE) && (WT_ATTEST_COSE == 1) && \ + !defined(WT_ATTEST_KEY_hmac) if (wt_hsm_attest_restore((g_spm_iak_public_len != 0u) ? g_spm_iak_public : NULL, g_spm_iak_public_len) != 0) { @@ -367,7 +370,8 @@ int wt_spm_hsm_start(wt_ffm_runtime_t* runtime, int32_t partition_id) return ret; } #endif -#if defined(WT_ATTEST_COSE) && (WT_ATTEST_COSE == 1) +#if defined(WT_ATTEST_COSE) && (WT_ATTEST_COSE == 1) && \ + !defined(WT_ATTEST_KEY_hmac) /* Taken before the store is rebound to the door view, which the boot * context cannot call through. */ g_spm_iak_public_len = 0u; @@ -390,10 +394,9 @@ int wt_spm_hsm_start(wt_ffm_runtime_t* runtime, int32_t partition_id) } #if defined(WT_ATTEST_COSE) && (WT_ATTEST_COSE == 1) -/* SERVICE_ATTEST's dispatch loop: a confined scheduled SP. The token state - * lives in the partition's own data band; the IAK stays with the crypto - * partition, reached through SERVICE_HSM's attestation door, and the boot - * measurements come from the SVC gate's read-only snapshot. */ +/* SERVICE_ATTEST's dispatch loop: a confined SP with its token state, and an + * HMAC key, in its own data band. A P-256 IAK stays with the crypto partition + * behind SERVICE_HSM's door; measurements come from the SVC gate's snapshot. */ static void wt_spm_attest_entry(void* arg) { int32_t partition_id = (int32_t)(intptr_t)arg; @@ -425,10 +428,14 @@ static void wt_spm_attest_entry(void* arg) static int wt_spm_attest_bind(int32_t partition_id) { wt_attestation_service_set_transport(wt_spm_svc_transport); +#ifdef WT_ATTEST_KEY_hmac + (void)partition_id; +#else if (wt_initial_attest_bind_hsm(wt_spm_svc_transport, NULL, partition_id, SERVICE_HSM_SID) != WT_ATTEST_SUCCESS) { return WT_FFM_ERROR_STATE; } +#endif return WT_FFM_SUCCESS; } diff --git a/tests/firmware/baremetal-guest/Makefile b/tests/firmware/baremetal-guest/Makefile index 2d5d7ac8c..483800add 100644 --- a/tests/firmware/baremetal-guest/Makefile +++ b/tests/firmware/baremetal-guest/Makefile @@ -25,6 +25,7 @@ BOARD_DIR := $(ROOT)/tests/firmware/boards/$(TARGET) # The same guest links into both Non-secure windows, read from the port's # memory map under the Secure image's layout configuration; the monitor # refuses to start unless every configured guest has an image. +include $(ROOT)/mk/profile.mk include $(ROOT)/mk/target-$(TARGET).mk include $(ROOT)/mk/layout.mk $(foreach kv,$(WT_LAYOUT_GUEST_WINDOWS),$(eval $(kv))) diff --git a/tests/firmware/interface-guest/Makefile b/tests/firmware/interface-guest/Makefile index fdb2f976d..351cd6724 100644 --- a/tests/firmware/interface-guest/Makefile +++ b/tests/firmware/interface-guest/Makefile @@ -49,6 +49,7 @@ ifneq ($(CONFIG_TPM)/$(CONFIG_PKCS11),$(WT_IF_WANT)) $(error WT_INTERFACE=$(WT_INTERFACE) conflicts with CONFIG_TPM=$(CONFIG_TPM) CONFIG_PKCS11=$(CONFIG_PKCS11)) endif +include $(ROOT)/mk/profile.mk include $(ROOT)/mk/target-$(TARGET).mk include $(ROOT)/mk/layout.mk $(foreach kv,$(WT_LAYOUT_GUEST_WINDOWS),$(eval $(kv))) diff --git a/tests/firmware/interface-guest/tpm_tests.c b/tests/firmware/interface-guest/tpm_tests.c index 462328dbc..816bec9fb 100644 --- a/tests/firmware/interface-guest/tpm_tests.c +++ b/tests/firmware/interface-guest/tpm_tests.c @@ -94,7 +94,7 @@ static int tpm_property_matches(UINT32 property, UINT32 expected) return 0; } -#if defined(WT_PROFILE_FULL) && !WT_PROFILE_FULL +#if defined(WT_PROFILE_EXTENDED) && !WT_PROFILE_EXTENDED static int tpm_command_capabilities(void) { GetCapability_In in; @@ -420,7 +420,7 @@ int wt_tpm_run(void) return -1; } app_line("tpm frame caps ok"); -#if defined(WT_PROFILE_FULL) && !WT_PROFILE_FULL +#if defined(WT_PROFILE_EXTENDED) && !WT_PROFILE_EXTENDED if (tpm_command_capabilities() != 0) { app_line("tpm command capabilities FAILED"); return -1; diff --git a/tests/firmware/psa-guest/Makefile b/tests/firmware/psa-guest/Makefile index 078ae30ce..480e3104e 100644 --- a/tests/firmware/psa-guest/Makefile +++ b/tests/firmware/psa-guest/Makefile @@ -19,6 +19,7 @@ BUILD ?= build # The guest windows come from the port's memory map under the same layout # configuration the Secure image is built with. +include $(ROOT)/mk/profile.mk include $(ROOT)/mk/target-$(TARGET).mk include $(ROOT)/mk/layout.mk $(foreach kv,$(WT_LAYOUT_GUEST_WINDOWS),$(eval $(kv))) @@ -243,6 +244,8 @@ ifeq ($(WT_SECURE_PSA),1) PSA_CFG_H := $(ROOT)/build/wolfpsa_cfg/crypto_config_generated.h endif +# An HMAC attestation key needs COSE_Mac0 verify in the guest. +GUEST_COSE_MAC0 := $(if $(filter hmac,$(WT_ATTEST_KEY)),-DWOLFCOSE_NO_MAC0_CREATE,-DWOLFCOSE_NO_MAC0) CFLAGS := -mcpu=cortex-m33 -mthumb -mgeneral-regs-only \ -ffreestanding -fno-builtin -nostdlib -Os -g \ -Wall -Wextra -Wno-unused-function -Wno-unused-variable \ @@ -271,7 +274,7 @@ CFLAGS := -mcpu=cortex-m33 -mthumb -mgeneral-regs-only \ -DNO_ERROR_STRINGS -DWOLFSSL_PUBLIC_MP -DWC_RSA_DIRECT \ -DWC_RESEED_INTERVAL=1000000 \ -DWOLFCOSE_LEAN -DWOLFCOSE_ENABLE_DEPRECATED_ALGS -DWOLFCOSE_NO_SIGN1_SIGN \ - -DWOLFCOSE_NO_ENCRYPT0 -DWOLFCOSE_NO_MAC0 -DWOLFCOSE_NO_KEY_ENCODE \ + -DWOLFCOSE_NO_ENCRYPT0 $(GUEST_COSE_MAC0) -DWOLFCOSE_NO_KEY_ENCODE \ -DWOLFCOSE_NO_KEY_DECODE \ -DWT_EXPECTED_LIFECYCLE=$(WT_EXPECTED_LIFECYCLE) \ $(ENGINE_DEFS) \ @@ -280,6 +283,13 @@ CFLAGS := -mcpu=cortex-m33 -mthumb -mgeneral-regs-only \ ifneq ($(WT_EXPECTED_MEASUREMENT_HEX),) CFLAGS += -DWT_EXPECTED_MEASUREMENT_HEX=\"$(WT_EXPECTED_MEASUREMENT_HEX)\" endif +# Both guests check the attestation key, and P-256 when PSA runs Secure. +ifeq ($(WT_ATTEST_KEY),hmac) +CFLAGS += -DWT_GUEST_ATTEST_HMAC +endif +ifeq ($(WT_SECURE_PSA)/$(WT_SECURE_PSA_PROFILE),1/tiny) +CFLAGS += -DWT_GUEST_NO_P256 +endif PROBE_CFLAGS := GUEST1_BKPT_CFLAGS := diff --git a/tests/firmware/psa-guest/main.c b/tests/firmware/psa-guest/main.c index bf665d31c..240206a19 100644 --- a/tests/firmware/psa-guest/main.c +++ b/tests/firmware/psa-guest/main.c @@ -347,6 +347,27 @@ static void guest_p256_attributes(psa_key_attributes_t* attr) psa_set_key_bits(attr, 256); } +#if defined(WT_GUEST_NO_P256) +/* The tiny Secure PSA profile must refuse P-256 outright. */ +static void exercise_no_p256(void) +{ + psa_key_attributes_t attr = PSA_KEY_ATTRIBUTES_INIT; + psa_key_id_t key = PSA_KEY_ID_NULL; + psa_status_t st; + + guest_p256_attributes(&attr); + st = psa_generate_key(&attr, &key); + if (st == PSA_ERROR_NOT_SUPPORTED) { + guest_line("wolfTrust key-ops P-256 refused (no ECC)"); + } + else { + guest_line_i32("key-ops P-256 not refused st=", (int32_t)st); + if (st == PSA_SUCCESS) { + (void)psa_destroy_key(key); + } + } +} +#else static void exercise_keys(void) { static const uint8_t digest[32] = { @@ -457,6 +478,7 @@ static void exercise_key_negatives(void) (void)psa_destroy_key(key_a); (void)psa_destroy_key(key_b); } +#endif /* ---- FF-M IPC negatives ------------------------------------------------- */ @@ -607,6 +629,17 @@ static void exercise_psa_cipher(void) /* ---- initial attestation ------------------------------------------------ */ +#if defined(WT_GUEST_ATTEST_HMAC) +/* The reference ports' public development key (port/common/attest_dev_key.c), + * kept separate so a drift between the two fails the token check. */ +static const uint8_t g_guest_attest_dev_key[32] = { + 0x77, 0x6f, 0x6c, 0x66, 0x54, 0x72, 0x75, 0x73, + 0x74, 0x2d, 0x44, 0x45, 0x56, 0x2d, 0x61, 0x74, + 0x74, 0x65, 0x73, 0x74, 0x61, 0x74, 0x69, 0x6f, + 0x6e, 0x2d, 0x6b, 0x65, 0x79, 0x2d, 0x30, 0x30 +}; +#endif + static void exercise_attestation(void) { uint8_t challenge[PSA_INITIAL_ATTEST_CHALLENGE_SIZE_32]; @@ -650,6 +683,43 @@ static void exercise_attestation(void) st = wolftrust_attestation_get_iak_public_key(public_key, sizeof(public_key), &public_key_size); +#if defined(WT_GUEST_ATTEST_HMAC) + if (st != PSA_ERROR_NOT_SUPPORTED) { + guest_line_i32("wolfTrust attestation: IAK public key not refused st=", + (int32_t)st); + return; + } + guest_line("wolfTrust attestation: IAK public key refused"); + verify = wt_attestation_verify_mac0_ex(token, token_size, + g_guest_attest_dev_key, + sizeof(g_guest_attest_dev_key), + challenge, sizeof(challenge), + WT_EXPECTED_MEASUREMENT_HEX, + WT_EXPECTED_LIFECYCLE, + &verified_lifecycle, measurement); + if (verify != 0) { + guest_line_i32("wolfTrust attestation: COSE_Mac0 verification failed rc=", + (int32_t)verify); + guest_line_i32("wolfTrust attestation: received lifecycle=", + (int32_t)verified_lifecycle); + return; + } + guest_line("wolfTrust attestation: COSE_Mac0 verified"); + token[token_size - 1u] ^= 0x01u; + verify = wt_attestation_verify_mac0_ex(token, token_size, + g_guest_attest_dev_key, + sizeof(g_guest_attest_dev_key), + challenge, sizeof(challenge), + WT_EXPECTED_MEASUREMENT_HEX, + WT_EXPECTED_LIFECYCLE, + &verified_lifecycle, NULL); + token[token_size - 1u] ^= 0x01u; + if (verify == 0) { + guest_line("wolfTrust attestation: tampered COSE_Mac0 accepted"); + return; + } + guest_line("wolfTrust attestation: tampered COSE_Mac0 rejected"); +#else if (st != PSA_SUCCESS) { guest_line_i32("psa_initial_attestation public_key_st=", (int32_t)st); return; @@ -668,12 +738,18 @@ static void exercise_attestation(void) return; } guest_line("wolfTrust attestation: COSE_Sign1 verified"); +#endif g_guest_mailbox.lifecycle |= GUEST_LC_COSE; guest_puts(GUEST_NAME ": wolfTrust attestation: token measurement="); guest_put_hex(measurement, sizeof(measurement)); guest_puts("\r\n"); +#if defined(WT_GUEST_ATTEST_HMAC) + guest_line("attestation verify=0 challenge=ok identity=ok measurement=ok " + "cose=HMAC256"); +#else guest_line("attestation verify=0 challenge=ok identity=ok measurement=ok " "cose=ES256"); +#endif } #if defined(WT_ATTEST_NEG_PROBE) @@ -1418,8 +1494,12 @@ void Reset_Handler(void) } exercise_its(); exercise_ps(); +#if defined(WT_GUEST_NO_P256) + exercise_no_p256(); +#else exercise_keys(); exercise_key_negatives(); +#endif exercise_ffm_negatives(); #if defined(WT_HSM_ATTACK_PROBE) exercise_hsm_attack_probe(); diff --git a/tests/firmware/stm32h563/Makefile b/tests/firmware/stm32h563/Makefile index eec13d2a3..c44f52dec 100644 --- a/tests/firmware/stm32h563/Makefile +++ b/tests/firmware/stm32h563/Makefile @@ -16,6 +16,7 @@ WT_GUEST0_FLASH_BASE ?= $(WT_GUEST0_FLASH_ORIGIN) WT_GUEST1_FLASH_BASE ?= $(WT_GUEST1_FLASH_ORIGIN) WT_GUEST0_FLASH_SIZE ?= $(WT_GUEST_FLASH_SIZE) WT_GUEST1_FLASH_SIZE ?= $(WT_GUEST_FLASH_SIZE) +include $(ROOT)/mk/profile.mk include $(ROOT)/mk/target-$(TARGET).mk include $(ROOT)/mk/layout.mk diff --git a/tests/firmware/zephyr-stm32h5/apps/guest0_psa/src/attestation_verify.c b/tests/firmware/zephyr-stm32h5/apps/guest0_psa/src/attestation_verify.c index d07ec04f7..b04341e21 100644 --- a/tests/firmware/zephyr-stm32h5/apps/guest0_psa/src/attestation_verify.c +++ b/tests/firmware/zephyr-stm32h5/apps/guest0_psa/src/attestation_verify.c @@ -22,6 +22,9 @@ #include #include +#if defined(WT_GUEST_ATTEST_HMAC) +#include +#endif #include @@ -197,8 +200,9 @@ static int wt_verify_software_component(WOLFCOSE_CBOR_CTX* cbor, static int wt_verify_claims(const uint8_t* payload, size_t payloadSize, const uint8_t* challenge, size_t challengeSize, - const uint8_t* expectedMeasurement, uint32_t expectedLifecycle, - uint32_t* verifiedLifecycle, uint8_t* tokenMeasurement) + const uint8_t* expectedMeasurement, const uint8_t* expectedUeid, + uint32_t expectedLifecycle, uint32_t* verifiedLifecycle, + uint8_t* tokenMeasurement) { WOLFCOSE_CBOR_CTX cbor; const uint8_t* data; @@ -229,7 +233,9 @@ static int wt_verify_claims(const uint8_t* payload, size_t payloadSize, } else if ((ret == 0) && (label == WT_EAT_CLAIM_UEID)) { ret = wc_CBOR_DecodeBstr(&cbor, &data, &dataSize); - if ((ret == 0) && (dataSize == 33u) && (data[0] == 0x01u)) { + if ((ret == 0) && (dataSize == 33u) && (data[0] == 0x01u) && + ((expectedUeid == NULL) || + (memcmp(data, expectedUeid, dataSize) == 0))) { claims |= 2u; } else { @@ -365,7 +371,7 @@ int wt_attestation_verify_ex(const uint8_t* token, size_t tokenSize, } if (ret == 0) { ret = wt_verify_claims(payload, payloadSize, challenge, challengeSize, - expected, expectedLifecycle, + expected, NULL, expectedLifecycle, verifiedLifecycle, tokenMeasurement); } @@ -380,6 +386,85 @@ int wt_attestation_verify_ex(const uint8_t* token, size_t tokenSize, return ret; } +#if defined(WT_GUEST_ATTEST_HMAC) +/* RFC 9783 Appendix A.2: the Instance ID is 0x01 || SHA-256(SHA-256(key)). */ +static int wt_mac0_instance_id(const uint8_t* key, size_t keySize, + uint8_t* ueid) +{ + uint8_t first[WC_SHA256_DIGEST_SIZE]; + int ret; + + ueid[0] = 0x01u; + ret = wc_Sha256Hash(key, (word32)keySize, first); + if (ret == 0) { + ret = wc_Sha256Hash(first, (word32)sizeof(first), &ueid[1]); + } + (void)memset(first, 0, sizeof(first)); + return (ret == 0) ? 0 : -1; +} + +int wt_attestation_verify_mac0_ex(const uint8_t* token, size_t tokenSize, + const uint8_t* key, size_t keySize, + const uint8_t* challenge, size_t challengeSize, + const char* expectedMeasurementHex, uint32_t expectedLifecycle, + uint32_t* verifiedLifecycle, uint8_t* tokenMeasurement) +{ + uint8_t expectedMeasurement[32]; + uint8_t ueid[1 + WC_SHA256_DIGEST_SIZE]; + const uint8_t* expected = NULL; + uint8_t scratch[640]; + const uint8_t* payload = NULL; + size_t payloadSize = 0u; + WOLFCOSE_HDR header; + WOLFCOSE_KEY coseKey; + int coseKeyInited = 0; + int ret = 0; + + if ((token == NULL) || (key == NULL) || (keySize != 32u) || + (challenge == NULL) || (verifiedLifecycle == NULL)) { + return -1; + } + *verifiedLifecycle = 0u; + if ((expectedMeasurementHex != NULL) && + (expectedMeasurementHex[0] != '\0')) { + ret = wt_decode_measurement(expectedMeasurementHex, + expectedMeasurement); + expected = expectedMeasurement; + } + if (ret == 0) { + ret = wt_mac0_instance_id(key, keySize, ueid); + } + if (ret == 0) { + ret = wc_CoseKey_Init(&coseKey); + if (ret == 0) { + coseKeyInited = 1; + ret = wc_CoseKey_SetSymmetric(&coseKey, key, keySize); + } + } + if (ret == 0) { + (void)memset(&header, 0, sizeof(header)); + ret = wc_CoseMac0_Verify(&coseKey, token, tokenSize, NULL, 0u, + NULL, 0u, scratch, sizeof(scratch), &header, &payload, + &payloadSize); + } + if ((ret == 0) && (header.alg != WOLFCOSE_ALG_HMAC_256_256)) { + ret = -1; + } + if (ret == 0) { + ret = wt_verify_claims(payload, payloadSize, challenge, challengeSize, + expected, ueid, expectedLifecycle, + verifiedLifecycle, tokenMeasurement); + } + + if (coseKeyInited != 0) { + wc_CoseKey_Free(&coseKey); + } + (void)memset(expectedMeasurement, 0, sizeof(expectedMeasurement)); + (void)memset(scratch, 0, sizeof(scratch)); + return ret; +} +#endif + int wt_attestation_verify(const uint8_t* token, size_t tokenSize, const uint8_t* publicKey, size_t publicKeySize, const uint8_t* challenge, size_t challengeSize, diff --git a/tests/firmware/zephyr-stm32h5/apps/guest0_psa/src/attestation_verify.h b/tests/firmware/zephyr-stm32h5/apps/guest0_psa/src/attestation_verify.h index e22817d2f..6e6211589 100644 --- a/tests/firmware/zephyr-stm32h5/apps/guest0_psa/src/attestation_verify.h +++ b/tests/firmware/zephyr-stm32h5/apps/guest0_psa/src/attestation_verify.h @@ -40,4 +40,14 @@ int wt_attestation_verify_ex(const uint8_t* token, size_t tokenSize, const char* expectedMeasurementHex, uint32_t expectedLifecycle, uint32_t* verifiedLifecycle, uint8_t* tokenMeasurement); +#if defined(WT_GUEST_ATTEST_HMAC) +/* As wt_attestation_verify_ex for a COSE_Mac0 HMAC 256/256 token under a + * 32-byte key, which must also derive the token's Instance ID. */ +int wt_attestation_verify_mac0_ex(const uint8_t* token, size_t tokenSize, + const uint8_t* key, size_t keySize, + const uint8_t* challenge, size_t challengeSize, + const char* expectedMeasurementHex, uint32_t expectedLifecycle, + uint32_t* verifiedLifecycle, uint8_t* tokenMeasurement); +#endif + #endif /* WOLFTRUST_ATTESTATION_VERIFY_H */ diff --git a/tests/host/Makefile b/tests/host/Makefile index 99f108fc0..746a81ec4 100644 --- a/tests/host/Makefile +++ b/tests/host/Makefile @@ -42,7 +42,7 @@ UNIT_SUITES := domain manifest manifest_ports lifecycle monitor guest_verify rol keystore_isolation \ attestation_service attestation attestation_token \ attestation_golden attestation_negatives attestation_replay \ - attestation_iak ffm_domain sp_layout tasklet_priv port_binding silicon_rev boot_handoff \ + attestation_iak attestation_hmac attest_restore ffm_domain sp_layout tasklet_priv port_binding silicon_rev boot_handoff \ spm_gate \ flash_nvm ffm_veneer secure_layout \ vault_service storage_service ps_service keystore_ipc negatives qcbor_shim \ @@ -53,7 +53,12 @@ UNIT_SUITES := domain manifest manifest_ports lifecycle monitor guest_verify rol UNIT_SUITES += $(filter-out $(UNIT_SUITES),$(patsubst %/Makefile,%,$(wildcard \ $(addsuffix _*/Makefile,$(notdir $(patsubst %/port.json,%,$(wildcard ../../port/*/port.json))))))) -.PHONY: all test test-compilers test-sanitize test-valgrind print-suites clean +.PHONY: all test test-vault-ccm test-compilers test-sanitize test-valgrind \ + print-suites clean + +# The vault and seal callers rerun with WT_AEAD=ccm after the main pass +VAULT_CCM_SUITES := native_wire ps_service keystore_ipc negatives nvm_boot \ + psa_storage_client psa_secure_crypto all: test @@ -93,6 +98,17 @@ test: echo "PASS: $(TEST_KIND)/$$suite"; \ done @echo "PASS: $(TEST_KIND)/all"; echo "LOG: $(LOG_FILE)" +ifneq ($(TEST_KIND),vault-ccm) + @$(MAKE) --no-print-directory test-vault-ccm CC="$(CC)" \ + BUILD_ROOT="$(BUILD_ROOT)" EXTRA_CFLAGS="$(EXTRA_CFLAGS)" +endif + +test-vault-ccm: + @$(MAKE) --no-print-directory test TEST_KIND=vault-ccm CC="$(CC)" \ + UNIT_SUITES="$(VAULT_CCM_SUITES)" \ + BUILD_ROOT="$(BUILD_ROOT)/vault-ccm" \ + LOG_FILE="$(BUILD_ROOT)/vault-ccm/logs/vault-ccm.log" \ + EXTRA_CFLAGS="$(EXTRA_CFLAGS) -DWT_AEAD_CCM" test-compilers: $(MAKE) test TEST_KIND=compiler CC="$(CC)" \ diff --git a/tests/host/attest_restore/Makefile b/tests/host/attest_restore/Makefile new file mode 100644 index 000000000..1080986f0 --- /dev/null +++ b/tests/host/attest_restore/Makefile @@ -0,0 +1,96 @@ +# Makefile +# +# Copyright (C) 2026 wolfSSL Inc. +# +# This file is part of wolfTrust. +# +# wolfTrust 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. +# +# wolfTrust 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, see . + +ROOT := ../../.. +TARGET := stm32h563 +WOLFSSL := $(ROOT)/lib/wolfSSL +WOLFCOSE := $(ROOT)/lib/wolfCOSE +CC ?= cc +BUILD_DIR ?= build +include $(ROOT)/tests/host/layout.mk + +# The tiny profile's own attestation defines, as tests/host/attestation_hmac. +ATTEST_DEFS := $(shell $(MAKE) -s --no-print-directory -C $(ROOT) \ + WT_PROFILE=tiny print-attest-defs 2>/dev/null) +ifeq ($(filter -DWT_ATTEST_KEY_hmac=1,$(ATTEST_DEFS)),) +$(error the tiny profile no longer builds an HMAC attestation key) +endif + +CFLAGS := -std=c99 -O0 -g -Wall -Wextra -Werror -pedantic \ + -Wno-unused-function -Wno-unused-parameter \ + -ffunction-sections -fdata-sections \ + -DWOLFSSL_USER_SETTINGS -UHAVE_CONFIG_H $(ATTEST_DEFS) \ + -DWOLFHSM_CFG_NO_CRYPTO -DWOLFHSM_CFG_NO_SYS_TIME \ + -I../attestation_hmac -I$(ROOT)/include -I$(ROOT)/lib/wolfHSM \ + -I$(WOLFSSL) -I$(WOLFCOSE)/include -I$(BUILD_DIR) $(EXTRA_CFLAGS) +include ../vendor_c99.mk +LIB_CFLAGS := $(filter-out -Werror -pedantic,$(CFLAGS)) + +ifeq ($(shell uname -s),Darwin) +GC_FLAGS := -Wl,-dead_strip +else +GC_FLAGS := -Wl,--gc-sections +endif + +_WC := hmac sha256 hash memory error logging wc_port misc +_CO := cbor util alg ecc hdr key struct recipient sign1 sign countersign \ + encrypt0 mac0 encrypt mac eat_psa +LIB_OBJS := $(addprefix $(BUILD_DIR)/wc_,$(addsuffix .o,$(_WC))) \ + $(addprefix $(BUILD_DIR)/co_,$(addsuffix .o,$(_CO))) + +TEST := $(BUILD_DIR)/test_attest_restore +GENERATOR := $(ROOT)/tools/manifest/generate.py +FIXTURE := $(BUILD_DIR)/manifest.json +GENERATED := $(BUILD_DIR)/wolftrust_manifest_generated.h + +.PHONY: all run sanitize valgrind clean + +all: $(TEST) + +$(FIXTURE): $(WT_MANIFEST_RENDER_DEPS) + mkdir -p $(BUILD_DIR) + $(WT_MANIFEST_RENDER) --output $@ $(WT_MANIFEST_TEMPLATE) + +$(GENERATED): $(GENERATOR) $(FIXTURE) + python3 $(GENERATOR) $(FIXTURE) $(BUILD_DIR) \ + --supported-features 0x1 --address-bits 32 --unchecked + +$(BUILD_DIR)/wc_%.o: $(WOLFSSL)/wolfcrypt/src/%.c | $(GENERATED) + $(CC) $(LIB_CFLAGS) -c -o $@ $< + +$(BUILD_DIR)/co_%.o: $(WOLFCOSE)/src/wolfcose_%.c | $(GENERATED) + $(CC) $(LIB_CFLAGS) -c -o $@ $< + +$(TEST): main.c $(ROOT)/src/spm_partitions.c \ + $(ROOT)/src/services/initial_attestation.c $(LIB_OBJS) $(GENERATED) + $(CC) $(CFLAGS) $(GC_FLAGS) $(EXTRA_LDFLAGS) -o $@ main.c $(LIB_OBJS) + +run: $(TEST) + $(TEST) + +sanitize: + $(MAKE) run CC=clang BUILD_DIR=$(BUILD_DIR)/sanitize \ + EXTRA_CFLAGS="-fsanitize=address,undefined -fno-omit-frame-pointer" \ + EXTRA_LDFLAGS="-fsanitize=address,undefined" + +valgrind: $(TEST) + valgrind --error-exitcode=1 --leak-check=full $(TEST) + +clean: + rm -rf $(BUILD_DIR) diff --git a/tests/host/attest_restore/main.c b/tests/host/attest_restore/main.c new file mode 100644 index 000000000..37a96d49d --- /dev/null +++ b/tests/host/attest_restore/main.c @@ -0,0 +1,209 @@ +/* main.c + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of wolfTrust. + * + * wolfTrust 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. + * + * wolfTrust 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, see . + */ + +/* The attestation partition's registered restart hook with an HMAC key + * (WT_ATTEST_KEY=hmac): a restart wipes the partition's data band, key + * included, and the hook must load the key again before tokens resume. */ + +#include +#include + +/* The partition table and the token encoder are production; the scheduler + * and the attestation dispatch loop are simulated. */ +#include "../../../src/spm_partitions.c" +#include "../../../src/services/initial_attestation.c" + +#include "mac0_check.h" + +static wt_spm_sp_restore_fn g_restore; +static int32_t g_restore_id; +static int g_added; +static int g_failures; +static wt_boot_handoff_t g_handoff; +static int g_handoff_kept = 1; +static uint8_t g_port_key[WT_ATTEST_HMAC_KEY_SIZE]; +static int g_port_key_fail; +static int g_port_key_calls; + +int wt_port_attest_hmac_key(uint8_t* key, size_t keySize) +{ + g_port_key_calls++; + if ((g_port_key_fail != 0) || (keySize != sizeof(g_port_key))) { + return -1; + } + (void)memcpy(key, g_port_key, sizeof(g_port_key)); + return 0; +} + +static const uint8_t g_seed[WT_ATTEST_BOOT_SEED_SIZE] = { 0x5Au }; + +/* The boot path's restore: it re-initializes from what boot retained. */ +int wt_boot_restore_attestation(void) +{ + if (g_handoff_kept == 0) { + return WT_ATTEST_ERROR_NOT_READY; + } + return wt_initial_attest_init(&g_handoff, g_seed); +} + +int wt_spm_sched_add(wt_ffm_runtime_t* runtime, int32_t partition_id, + wt_spm_sp_entry_fn entry, void* arg) +{ + (void)runtime; + (void)partition_id; + (void)entry; + (void)arg; + g_added++; + return WT_FFM_SUCCESS; +} + +int wt_spm_sched_set_restore(int32_t partition_id, + wt_spm_sp_restore_fn restore) +{ + g_restore_id = partition_id; + g_restore = restore; + return WT_FFM_SUCCESS; +} + +int wt_spm_svc_transport(wt_ffm_runtime_t* runtime, struct wt_spm_call* call) +{ + (void)runtime; + (void)call; + return WT_FFM_ERROR_STATE; +} + +void wt_attestation_service_set_transport(wt_spm_transport_fn transport) +{ + (void)transport; +} + +int wt_attestation_service_dispatch(void* context, wt_ffm_runtime_t* runtime, + int32_t partition_id) +{ + (void)context; + (void)runtime; + (void)partition_id; + return WT_FFM_ERROR_STATE; +} + +size_t wt_guest_measurement_count(void) +{ + return 0u; +} + +const wt_guest_measurement_t* wt_guest_measurement_get(size_t index, + const char** name) +{ + (void)index; + (void)name; + return NULL; +} + +static void check(int ok, const char* what) +{ + (void)printf("%s: %s\n", ok ? "PASS" : "FAIL", what); + if (!ok) { + g_failures++; + } +} + +/* What the SPM does to the partition's data band before its restart hook. */ +static void band_reset(void) +{ + (void)memset(&g_boot_handoff, 0, sizeof(g_boot_handoff)); + (void)memset(g_ueid, 0, sizeof(g_ueid)); + (void)memset(g_boot_seed, 0, sizeof(g_boot_seed)); + (void)memset(g_implementation_id, 0, sizeof(g_implementation_id)); + (void)memset(g_signer_id, 0, sizeof(g_signer_id)); + (void)memset(g_attest_hmac_key, 0, sizeof(g_attest_hmac_key)); + g_handoff_ready = false; + g_attest_ready = false; +} + +/* 0 when a token is issued and verifies under key; the status otherwise. */ +static int token_under(const uint8_t* key) +{ + uint8_t challenge[WT_ATTEST_CHALLENGE_SIZE_32]; + uint8_t token[WT_ATTEST_MAX_TOKEN_SIZE]; + size_t tokenSize = 0u; + int ret; + + (void)memset(challenge, 0x2a, sizeof(challenge)); + ret = wt_initial_attest_get_token(0u, challenge, sizeof(challenge), token, + sizeof(token), &tokenSize); + if (ret == WT_ATTEST_SUCCESS) { + ret = mac0_verify(key, WT_ATTEST_HMAC_KEY_SIZE, token, tokenSize); + } + return ret; +} + +int main(void) +{ + uint8_t first[WT_ATTEST_HMAC_KEY_SIZE]; + + (void)memset(&g_handoff, 0, sizeof(g_handoff)); + g_handoff.magic = WT_BOOT_HANDOFF_MAGIC; + g_handoff.version = WT_BOOT_HANDOFF_VERSION; + g_handoff.lifecycle = 0x3000u; + g_handoff.hash_algorithm = WT_BOOT_HANDOFF_HASH_SHA256; + g_handoff.measurement_size = WT_BOOT_HANDOFF_DIGEST_SIZE; + (void)memset(g_handoff.measurement, 0xAB, WT_BOOT_HANDOFF_DIGEST_SIZE); + (void)memset(g_port_key, 0x61, sizeof(g_port_key)); + (void)memcpy(first, g_port_key, sizeof(first)); + + /* Boot: the privileged path takes the handoff, then starts the partition. */ + check(wt_initial_attest_init(&g_handoff, g_seed) == WT_ATTEST_SUCCESS && + g_port_key_calls == 1, "boot loads the key through the port hook"); + check(wt_spm_attest_start(NULL, PARTITION_ATTEST_ID) == WT_FFM_SUCCESS && + g_added == 1 && g_restore != NULL && + g_restore_id == PARTITION_ATTEST_ID, + "the attestation partition registers a restart hook"); + check(token_under(first) == 0, "a token verifies under the device key"); + + band_reset(); + check(token_under(first) == WT_ATTEST_ERROR_NOT_READY, + "a wiped band issues no token"); + check(g_restore != NULL && + g_restore(PARTITION_ATTEST_ID) == WT_FFM_SUCCESS && + g_port_key_calls == 2, "the restart hook loads the key again"); + check(token_under(first) == 0, + "a token verifies again after the restart"); + + /* A restart the port cannot serve leaves attestation closed, not stale. */ + band_reset(); + g_port_key_fail = 1; + check(g_restore != NULL && + g_restore(PARTITION_ATTEST_ID) == WT_FFM_SUCCESS && + token_under(first) == WT_ATTEST_ERROR_NOT_READY, + "a restart with no key restarts the partition and issues no token"); + g_port_key_fail = 0; + band_reset(); + g_handoff_kept = 0; + check(g_restore != NULL && + g_restore(PARTITION_ATTEST_ID) == WT_FFM_SUCCESS && + token_under(first) == WT_ATTEST_ERROR_NOT_READY, + "a restart with no retained handoff issues no token"); + + if (g_failures != 0) { + return 1; + } + (void)printf("PASS: attestation partition restart hook (HMAC key)\n"); + return 0; +} diff --git a/tests/host/attestation_hmac/Makefile b/tests/host/attestation_hmac/Makefile new file mode 100644 index 000000000..2504049eb --- /dev/null +++ b/tests/host/attestation_hmac/Makefile @@ -0,0 +1,141 @@ +# Makefile +# +# Copyright (C) 2026 wolfSSL Inc. +# +# This file is part of wolfTrust. +# +# wolfTrust 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. +# +# wolfTrust 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 + +ROOT := ../../.. +WOLFSSL := $(ROOT)/lib/wolfSSL +WOLFCOSE := $(ROOT)/lib/wolfCOSE +WOLFHSM := $(ROOT)/lib/wolfHSM + +CC ?= cc +BUILD_DIR ?= build + +# The tiny profile's own attestation defines, so this suite issues tokens +# with the wolfCOSE configuration the Secure image links. +ATTEST_DEFS := $(shell $(MAKE) -s --no-print-directory -C $(ROOT) \ + WT_PROFILE=tiny print-attest-defs 2>/dev/null) +ifeq ($(filter -DWT_ATTEST_KEY_hmac=1,$(ATTEST_DEFS)),) +$(error the tiny profile no longer builds an HMAC attestation key) +endif + +CFLAGS := \ + -DWOLFSSL_USER_SETTINGS \ + -UHAVE_CONFIG_H \ + $(ATTEST_DEFS) \ + -DWOLFHSM_CFG_NO_CRYPTO \ + -DWOLFHSM_CFG_NO_SYS_TIME \ + -I. \ + -I$(ROOT)/include \ + -I$(WOLFSSL) \ + -I$(WOLFHSM) \ + -I$(WOLFCOSE)/include \ + -std=c99 -O0 -g -Wall -Wextra -Werror -pedantic \ + -Wno-unused-function -Wno-unused-parameter +CFLAGS += $(EXTRA_CFLAGS) +include ../vendor_c99.mk + +# wolfCOSE sources are not -pedantic/-Werror clean under this profile; build +# them with the warnings relaxed while keeping wolfTrust + test code strict. +COSE_CFLAGS := $(filter-out -Werror -pedantic,$(CFLAGS)) + +_WT_SRCS := \ + $(ROOT)/src/services/initial_attestation.c \ + $(ROOT)/src/guest_verify.c + +_WC_SRCS := \ + $(WOLFSSL)/wolfcrypt/src/hmac.c \ + $(WOLFSSL)/wolfcrypt/src/sha256.c \ + $(WOLFSSL)/wolfcrypt/src/hash.c \ + $(WOLFSSL)/wolfcrypt/src/memory.c \ + $(WOLFSSL)/wolfcrypt/src/error.c \ + $(WOLFSSL)/wolfcrypt/src/logging.c \ + $(WOLFSSL)/wolfcrypt/src/wc_port.c \ + $(WOLFSSL)/wolfcrypt/src/misc.c + +_CO_SRCS := \ + $(WOLFCOSE)/src/wolfcose_cbor.c \ + $(WOLFCOSE)/src/wolfcose_util.c \ + $(WOLFCOSE)/src/wolfcose_alg.c \ + $(WOLFCOSE)/src/wolfcose_ecc.c \ + $(WOLFCOSE)/src/wolfcose_hdr.c \ + $(WOLFCOSE)/src/wolfcose_key.c \ + $(WOLFCOSE)/src/wolfcose_struct.c \ + $(WOLFCOSE)/src/wolfcose_recipient.c \ + $(WOLFCOSE)/src/wolfcose_sign1.c \ + $(WOLFCOSE)/src/wolfcose_sign.c \ + $(WOLFCOSE)/src/wolfcose_countersign.c \ + $(WOLFCOSE)/src/wolfcose_encrypt0.c \ + $(WOLFCOSE)/src/wolfcose_mac0.c \ + $(WOLFCOSE)/src/wolfcose_encrypt.c \ + $(WOLFCOSE)/src/wolfcose_mac.c \ + $(WOLFCOSE)/src/wolfcose_eat_psa.c + +_TEST_SRCS := main.c + +_WT_OBJS := $(patsubst %.c,wt_%.o,$(notdir $(_WT_SRCS))) +_WC_OBJS := $(patsubst %.c,wc_%.o,$(notdir $(_WC_SRCS))) +_CO_OBJS := $(patsubst %.c,co_%.o,$(notdir $(_CO_SRCS))) +_TEST_OBJS := $(patsubst %.c,%.o,$(notdir $(_TEST_SRCS))) + +ALL_OBJS := $(addprefix $(BUILD_DIR)/,$(_WT_OBJS) $(_WC_OBJS) $(_CO_OBJS) $(_TEST_OBJS)) +TEST_BIN := $(BUILD_DIR)/test_attestation_hmac + +.PHONY: all run compilers sanitize valgrind clean + +all: $(TEST_BIN) + +$(BUILD_DIR): + mkdir -p $@ + +$(BUILD_DIR)/wt_%.o: $(ROOT)/src/services/%.c | $(BUILD_DIR) + $(CC) $(CFLAGS) -c -o $@ $< + +$(BUILD_DIR)/wt_%.o: $(ROOT)/src/%.c | $(BUILD_DIR) + $(CC) $(CFLAGS) -c -o $@ $< + +$(BUILD_DIR)/wc_%.o: $(WOLFSSL)/wolfcrypt/src/%.c | $(BUILD_DIR) + $(CC) $(CFLAGS) -c -o $@ $< + +$(BUILD_DIR)/co_%.o: $(WOLFCOSE)/src/%.c | $(BUILD_DIR) + $(CC) $(COSE_CFLAGS) -c -o $@ $< + +$(BUILD_DIR)/%.o: %.c | $(BUILD_DIR) + $(CC) $(CFLAGS) -c -o $@ $< + +$(TEST_BIN): $(ALL_OBJS) | $(BUILD_DIR) + $(CC) $(CFLAGS) $(EXTRA_LDFLAGS) -o $@ $(ALL_OBJS) + +run: $(TEST_BIN) + $(TEST_BIN) + +compilers: + $(MAKE) clean run CC=gcc BUILD_DIR=$(BUILD_DIR)/gcc + $(MAKE) clean run CC=clang BUILD_DIR=$(BUILD_DIR)/clang + +sanitize: + $(MAKE) clean run CC=clang \ + BUILD_DIR=$(BUILD_DIR)/sanitize \ + EXTRA_CFLAGS="-fsanitize=address,undefined -fno-omit-frame-pointer" \ + EXTRA_LDFLAGS="-fsanitize=address,undefined" + +valgrind: $(TEST_BIN) + valgrind --error-exitcode=1 --leak-check=full $(TEST_BIN) + +clean: + rm -rf $(BUILD_DIR) diff --git a/tests/host/attestation_hmac/mac0_check.h b/tests/host/attestation_hmac/mac0_check.h new file mode 100644 index 000000000..48a98df82 --- /dev/null +++ b/tests/host/attestation_hmac/mac0_check.h @@ -0,0 +1,169 @@ +/* mac0_check.h + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of wolfTrust. + * + * wolfTrust 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. + * + * wolfTrust 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, see . + */ + +/* An HMAC-SHA256 COSE_Mac0 check that shares no code with the encoder under + * test, for the host suites that issue HMAC attestation tokens. */ + +#ifndef WT_TEST_MAC0_CHECK_H +#define WT_TEST_MAC0_CHECK_H + +#include +#include +#include +#include + +#include +#include + +#define MAC0_TAG_SIZE 32u +#define UEID_SIZE 33u + +static size_t bstr_head(size_t len, uint8_t* head) +{ + size_t n; + + if (len < 24u) { + head[0] = (uint8_t)(0x40u + len); + n = 1u; + } + else if (len < 256u) { + head[0] = 0x58u; + head[1] = (uint8_t)len; + n = 2u; + } + else { + head[0] = 0x59u; + head[1] = (uint8_t)(len >> 8); + head[2] = (uint8_t)len; + n = 3u; + } + return n; +} + +/* Split a tagged COSE_Mac0 whose protected header is {1: 5} (HMAC 256/256) + * and whose unprotected map is empty into its payload and tag. */ +static int mac0_split(const uint8_t* token, size_t tokenSize, + const uint8_t** payload, size_t* payloadSize, const uint8_t** tag) +{ + static const uint8_t head[] = { 0xD1, 0x84, 0x43, 0xA1, 0x01, 0x05, 0xA0 }; + size_t off = sizeof(head); + size_t len; + + if ((tokenSize < (sizeof(head) + 3u)) || + (memcmp(token, head, sizeof(head)) != 0)) { + return -1; + } + if ((token[off] >= 0x40u) && (token[off] <= 0x57u)) { + len = (size_t)token[off] - 0x40u; + off += 1u; + } + else if (token[off] == 0x58u) { + len = token[off + 1u]; + off += 2u; + } + else if (token[off] == 0x59u) { + len = ((size_t)token[off + 1u] << 8) | token[off + 2u]; + off += 3u; + } + else { + return -1; + } + if ((tokenSize != (off + len + 2u + MAC0_TAG_SIZE)) || + (token[off + len] != 0x58u) || (token[off + len + 1u] != 0x20u)) { + return -1; + } + *payload = token + off; + *payloadSize = len; + *tag = token + off + len + 2u; + return 0; +} + +/* 0 when the tag is HMAC-SHA256 over MAC_structure + * ["MAC0", h'A10105', h'', payload]; 1 when it is not. */ +static int mac0_verify(const uint8_t* key, size_t keySize, + const uint8_t* token, size_t tokenSize) +{ + static const uint8_t context[] = { 0x84, 0x64, 'M', 'A', 'C', '0', + 0x43, 0xA1, 0x01, 0x05, 0x40 }; + const uint8_t* payload = NULL; + const uint8_t* tag = NULL; + uint8_t head[3]; + uint8_t mac[MAC0_TAG_SIZE]; + size_t payloadSize = 0u; + size_t headSize; + Hmac hmac; + int ret; + + if (mac0_split(token, tokenSize, &payload, &payloadSize, &tag) != 0) { + return -1; + } + headSize = bstr_head(payloadSize, head); + ret = wc_HmacInit(&hmac, NULL, INVALID_DEVID); + if (ret != 0) { + return -1; + } + ret = wc_HmacSetKey(&hmac, WC_SHA256, key, (word32)keySize); + if (ret == 0) { + ret = wc_HmacUpdate(&hmac, context, (word32)sizeof(context)); + } + if (ret == 0) { + ret = wc_HmacUpdate(&hmac, head, (word32)headSize); + } + if (ret == 0) { + ret = wc_HmacUpdate(&hmac, payload, (word32)payloadSize); + } + if (ret == 0) { + ret = wc_HmacFinal(&hmac, mac); + } + wc_HmacFree(&hmac); + if (ret != 0) { + return -1; + } + return (memcmp(mac, tag, sizeof(mac)) == 0) ? 0 : 1; +} + +static int contains(const uint8_t* hay, size_t haySize, const uint8_t* needle, + size_t needleSize) +{ + size_t i; + + for (i = 0u; (i + needleSize) <= haySize; i++) { + if (memcmp(hay + i, needle, needleSize) == 0) { + return 1; + } + } + return 0; +} + +/* The Instance ID of an HMAC key: 0x01 || SHA-256(SHA-256(key)). */ +static int instance_id(const uint8_t* key, size_t keySize, uint8_t* ueid) +{ + uint8_t first[WC_SHA256_DIGEST_SIZE]; + int ret; + + ueid[0] = 0x01u; + ret = wc_Sha256Hash(key, (word32)keySize, first); + if (ret == 0) { + ret = wc_Sha256Hash(first, (word32)sizeof(first), &ueid[1]); + } + return ret; +} + +#endif /* WT_TEST_MAC0_CHECK_H */ diff --git a/tests/host/attestation_hmac/main.c b/tests/host/attestation_hmac/main.c new file mode 100644 index 000000000..898abd693 --- /dev/null +++ b/tests/host/attestation_hmac/main.c @@ -0,0 +1,273 @@ +/* main.c + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of wolfTrust. + * + * wolfTrust 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. + * + * wolfTrust 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, see . + */ + +/* HMAC attestation key (WT_ATTEST_KEY=hmac): drive the production token + * encoder with the tiny profile's wolfCOSE configuration and check each + * COSE_Mac0 with an HMAC computed here, first proven on the RFC 9783 example. */ + +#include "wolftrust/services/initial_attestation.h" + +#include "mac0_check.h" + +#include +#include +#include + +/* RFC 9783 Appendix A.2: the COSE_Mac0 token and its 64-byte HS256 key. */ +static const char g_rfc_token_hex[] = + "d18443a10105a0590100a8190100582101c557bd4fadc83f756fca2cd5ea2dcc" + "8b82159bb4e7453d6a744d4eecd6d0ac6019095c582000000000000000000000" + "000000000000000000000000000000000000000000000a582001010101010101" + "0101010101010101010101010101010101010101010101010119095a1a7fffff" + "ff19095b19300019010978217461673a7073616365727469666965642e6f7267" + "2c323032333a7073612374666d19010c48000000000000000019095f81a30558" + "2004040404040404040404040404040404040404040404040404040404040404" + "0402582003030303030303030303030303030303030303030303030303030303" + "03030303016450526f545820cf88d330e7a5366a95cf744a4dbf0d50304d405e" + "dd8b2530e243eddbd3177820"; +static const char g_rfc_key_hex[] = + "de038b34aca125768c5e3357ab8d06b367b9ab0d7e8be124edca47fe033a5bb7" + "a93d307ff229aa36ff246c1295964facf71ab7aa6ec4fd6102b7b3983255ad92"; + +static int g_checks; +static int g_failures; +static uint8_t g_key[WT_ATTEST_HMAC_KEY_SIZE]; +static int g_key_fail; +static int g_key_calls; + +static void check(int cond, const char* name) +{ + g_checks++; + if (cond != 0) { + printf(" [check] PASS %s\n", name); + } + else { + g_failures++; + printf(" [check] FAIL %s\n", name); + } +} + +/* The port hook the Secure image calls for the device key. */ +int wt_port_attest_hmac_key(uint8_t* key, size_t keySize) +{ + g_key_calls++; + if ((g_key_fail != 0) || (key == NULL) || (keySize != sizeof(g_key))) { + return -1; + } + (void)memcpy(key, g_key, sizeof(g_key)); + return 0; +} + +static size_t unhex(const char* hex, uint8_t* out, size_t cap) +{ + size_t n = 0u; + unsigned int byte; + + while ((hex[0] != '\0') && (hex[1] != '\0') && (n < cap)) { + if (sscanf(hex, "%2x", &byte) != 1) { + return 0u; + } + out[n++] = (uint8_t)byte; + hex += 2; + } + return (hex[0] == '\0') ? n : 0u; +} + +static void test_rfc_vector(void) +{ + uint8_t token[320]; + uint8_t key[64]; + uint8_t ueid[UEID_SIZE]; + const uint8_t* payload = NULL; + const uint8_t* tag = NULL; + size_t payloadSize = 0u; + size_t tokenSize = unhex(g_rfc_token_hex, token, sizeof(token)); + size_t keySize = unhex(g_rfc_key_hex, key, sizeof(key)); + + check((tokenSize == 300u) && (keySize == 64u), + "RFC 9783 A.2 token and key decode"); + check(mac0_verify(key, keySize, token, tokenSize) == 0, + "RFC 9783 A.2 token verifies with its key"); + check((mac0_split(token, tokenSize, &payload, &payloadSize, &tag) == 0) && + (instance_id(key, keySize, ueid) == 0) && + (contains(payload, payloadSize, ueid, sizeof(ueid)) != 0), + "RFC 9783 A.2 Instance ID is 0x01 || SHA-256(SHA-256(key))"); + key[0] ^= 0x01u; + check(mac0_verify(key, keySize, token, tokenSize) == 1, + "RFC 9783 A.2 token fails under another key"); + key[0] ^= 0x01u; + token[40] ^= 0x01u; + check(mac0_verify(key, keySize, token, tokenSize) == 1, + "RFC 9783 A.2 token fails with a changed payload"); +} + +static void run_challenge(size_t challengeSize, const uint8_t* otherKey) +{ + uint8_t challenge[WT_ATTEST_CHALLENGE_SIZE_64]; + uint8_t token[WT_ATTEST_MAX_TOKEN_SIZE]; + uint8_t nonce[3u + WT_ATTEST_CHALLENGE_SIZE_64]; + uint8_t ueidClaim[5u + UEID_SIZE] = { 0x19, 0x01, 0x00, 0x58, 0x21 }; + uint8_t keyHash[WC_SHA256_DIGEST_SIZE]; + const uint8_t* payload = NULL; + const uint8_t* tag = NULL; + size_t payloadSize = 0u; + size_t predicted = 0u; + size_t tokenSize = 0u; + char name[96]; + int ret; + + (void)memset(challenge, 0x2a, sizeof(challenge)); + (void)memset(token, 0, sizeof(token)); + + ret = wt_initial_attest_get_token_size(challengeSize, &predicted); + (void)snprintf(name, sizeof(name), "get_token_size(%u) succeeds", + (unsigned)challengeSize); + check(ret == WT_ATTEST_SUCCESS, name); + + ret = wt_initial_attest_get_token(0u, challenge, challengeSize, token, + sizeof(token), &tokenSize); + (void)snprintf(name, sizeof(name), "get_token(%u) succeeds", + (unsigned)challengeSize); + check(ret == WT_ATTEST_SUCCESS, name); + + (void)snprintf(name, sizeof(name), + "token(%u) size matches get_token_size", + (unsigned)challengeSize); + check((tokenSize > 0u) && (tokenSize == predicted), name); + + (void)snprintf(name, sizeof(name), + "token(%u) is a tagged COSE_Mac0 with HMAC 256/256", + (unsigned)challengeSize); + check(mac0_split(token, tokenSize, &payload, &payloadSize, &tag) == 0, + name); + + (void)snprintf(name, sizeof(name), "token(%u) verifies with the device key", + (unsigned)challengeSize); + check(mac0_verify(g_key, sizeof(g_key), token, tokenSize) == 0, name); + + (void)snprintf(name, sizeof(name), "token(%u) fails under another key", + (unsigned)challengeSize); + check(mac0_verify(otherKey, sizeof(g_key), token, tokenSize) == 1, name); + + if (payload != NULL) { + (void)snprintf(name, sizeof(name), + "token(%u) carries the Instance ID of the key", + (unsigned)challengeSize); + check((instance_id(g_key, sizeof(g_key), &ueidClaim[5]) == 0) && + (contains(payload, payloadSize, ueidClaim, + sizeof(ueidClaim)) != 0), name); + + nonce[0] = 0x0a; + nonce[1] = 0x58; + nonce[2] = (uint8_t)challengeSize; + (void)memcpy(&nonce[3], challenge, challengeSize); + (void)snprintf(name, sizeof(name), + "token(%u) carries the challenge as its nonce", + (unsigned)challengeSize); + check(contains(payload, payloadSize, nonce, 3u + challengeSize) != 0, + name); + } + + (void)snprintf(name, sizeof(name), + "token(%u) holds neither the key nor its plain hash", + (unsigned)challengeSize); + check((wc_Sha256Hash(g_key, (word32)sizeof(g_key), keyHash) == 0) && + (contains(token, tokenSize, g_key, sizeof(g_key)) == 0) && + (contains(token, tokenSize, keyHash, sizeof(keyHash)) == 0), name); + + token[tokenSize / 2u] ^= 0x01u; + (void)snprintf(name, sizeof(name), "token(%u) fails once a byte changes", + (unsigned)challengeSize); + check(mac0_verify(g_key, sizeof(g_key), token, tokenSize) != 0, name); +} + +int main(void) +{ + static const size_t sizes[] = { WT_ATTEST_CHALLENGE_SIZE_32, + WT_ATTEST_CHALLENGE_SIZE_48, + WT_ATTEST_CHALLENGE_SIZE_64 }; + static const uint8_t bootSeed[WT_ATTEST_BOOT_SEED_SIZE] = { 0xA5u }; + wt_boot_handoff_t handoff; + uint8_t challenge[WT_ATTEST_CHALLENGE_SIZE_32]; + uint8_t token[WT_ATTEST_MAX_TOKEN_SIZE]; + uint8_t firstKey[WT_ATTEST_HMAC_KEY_SIZE]; + size_t tokenSize = 7u; + size_t i; + int ret; + + test_rfc_vector(); + + (void)memset(&handoff, 0, sizeof(handoff)); + handoff.magic = WT_BOOT_HANDOFF_MAGIC; + handoff.version = WT_BOOT_HANDOFF_VERSION; + handoff.lifecycle = 0x3000u; + handoff.hash_algorithm = WT_BOOT_HANDOFF_HASH_SHA256; + handoff.measurement_size = WT_BOOT_HANDOFF_DIGEST_SIZE; + (void)memset(handoff.measurement, 0xAB, WT_BOOT_HANDOFF_DIGEST_SIZE); + (void)memset(challenge, 0x2a, sizeof(challenge)); + + /* No key: the handoff is refused and every request fails closed. */ + g_key_fail = 1; + ret = wt_initial_attest_init(&handoff, bootSeed); + check((ret == WT_ATTEST_ERROR_CRYPTO) && (g_key_calls == 1), + "init fails when the port has no key"); + ret = wt_initial_attest_get_token(0u, challenge, sizeof(challenge), token, + sizeof(token), &tokenSize); + check((ret == WT_ATTEST_ERROR_NOT_READY) && (tokenSize == 0u), + "get_token is not ready without a key"); + ret = wt_initial_attest_get_token_size(sizeof(challenge), &tokenSize); + check((ret == WT_ATTEST_ERROR_NOT_READY) && (tokenSize == 0u), + "get_token_size is not ready without a key"); + + g_key_fail = 0; + for (i = 0u; i < sizeof(g_key); i++) { + g_key[i] = (uint8_t)(0x10u + i); + firstKey[i] = g_key[i]; + } + ret = wt_initial_attest_init(&handoff, bootSeed); + check((ret == WT_ATTEST_SUCCESS) && (g_key_calls == 2), + "init loads the key through the port hook"); + (void)memset(token, 0x5a, sizeof(token)); + for (i = 0u; i < (sizeof(sizes) / sizeof(sizes[0])); i++) { + run_challenge(sizes[i], token); + } + + /* A later init takes the port's current key, and a failed one drops it. */ + (void)memset(g_key, 0xC3, sizeof(g_key)); + ret = wt_initial_attest_init(&handoff, bootSeed); + check(ret == WT_ATTEST_SUCCESS, "a second init reloads the key"); + run_challenge(WT_ATTEST_CHALLENGE_SIZE_32, firstKey); + g_key_fail = 1; + ret = wt_initial_attest_init(&handoff, bootSeed); + tokenSize = 7u; + check((ret == WT_ATTEST_ERROR_CRYPTO) && + (wt_initial_attest_get_token(0u, challenge, sizeof(challenge), token, + sizeof(token), &tokenSize) == WT_ATTEST_ERROR_NOT_READY) && + (tokenSize == 0u), "a failed init leaves no usable key"); + + printf("attestation HMAC tests: %d checks, %d failures\n", g_checks, + g_failures); + if (g_failures != 0) { + printf("FAIL: attestation_hmac\n"); + return 1; + } + printf("PASS: attestation_hmac\n"); + return 0; +} diff --git a/tests/host/attestation_hmac/user_settings.h b/tests/host/attestation_hmac/user_settings.h new file mode 100644 index 000000000..e8b28ad60 --- /dev/null +++ b/tests/host/attestation_hmac/user_settings.h @@ -0,0 +1,61 @@ +/* user_settings.h + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of wolfTrust. + * + * wolfTrust 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. + * + * wolfTrust 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, see . + */ + +/* wolfCrypt for the HMAC attestation host test: SHA-256 and HMAC only, with + * no curve and no big-number code, as the tiny Secure image links it. */ + +#ifndef USER_SETTINGS_H +#define USER_SETTINGS_H + +#define HAVE_ANONYMOUS_INLINE_AGGREGATES 1 + +#define WOLFCRYPT_ONLY +#define WOLFSSL_USER_IO +#define NO_TLS + +#define NO_BIG_INT +#define WC_NO_RNG +#define NO_ASN +#define NO_CODING +#define NO_AES + +#define NO_SHA +#define NO_RSA +#define NO_DH +#define NO_DSA +#define NO_DES3 +#define NO_RC4 +#define NO_MD4 +#define NO_MD5 +#define NO_PWDBASED +#define NO_PKCS7 + +#define WOLFSSL_USE_ALIGN +#define WOLFSSL_IGNORE_FILE_WARN +#define NO_MAIN_DRIVER +#define NO_OLD_RNGNAME +#define NO_OLD_WC_NAMES +#define NO_OLD_SSL_NAMES +#define NO_OLD_SHA_NAMES +#define NO_OLD_MD5_NAME +#define NO_ERROR_QUEUE +#define NO_INLINE + +#endif /* USER_SETTINGS_H */ diff --git a/tests/host/attestation_service/Makefile b/tests/host/attestation_service/Makefile index b0738f1a6..8d7f74bc7 100644 --- a/tests/host/attestation_service/Makefile +++ b/tests/host/attestation_service/Makefile @@ -71,6 +71,10 @@ $(TEST_BIN): $(ALL_OBJS) | $(BUILD_DIR) run: $(TEST_BIN) $(TEST_BIN) +ifeq ($(findstring WT_ATTEST_KEY_hmac,$(EXTRA_CFLAGS)),) + $(MAKE) --no-print-directory run BUILD_DIR=$(BUILD_DIR)/hmac \ + EXTRA_CFLAGS="$(EXTRA_CFLAGS) -DWT_ATTEST_KEY_hmac=1" +endif compilers: $(MAKE) clean run CC=gcc BUILD_DIR=$(BUILD_DIR)/gcc diff --git a/tests/host/attestation_service/main.c b/tests/host/attestation_service/main.c index 612e010bc..d943ec5b2 100644 --- a/tests/host/attestation_service/main.c +++ b/tests/host/attestation_service/main.c @@ -257,6 +257,15 @@ int main(void) (void)memset(public_key, 0, sizeof(public_key)); status = wt_ffm_call(&runtime, TEST_NS_CLIENT, handle, WT_ATTEST_OP_PUBLIC_KEY, NULL, 0U, &key_out, 1U); +#ifdef WT_ATTEST_KEY_hmac + /* An HMAC key has no public half: the query is not served. */ + if (status != PSA_ERROR_NOT_SUPPORTED || public_key[0] != 0u) { + (void)fprintf(stderr, "public-key query not refused st=%d\n", + (int)status); + return 1; + } + (void)printf("PASS: an HMAC key serves no public-key query\n"); +#else if (status != PSA_SUCCESS || key_out.len != WT_ATTEST_IAK_PUBLIC_KEY_SIZE || public_key[0] != 0x04u) { @@ -265,6 +274,7 @@ int main(void) return 1; } (void)printf("PASS: mediated IAK public-key query\n"); +#endif /* A token CALL whose output vector is shorter than the token must report * BUFFER_TOO_SMALL, not fault the partition into its panic trap: a short diff --git a/tests/host/crypto_profile/test_generator.py b/tests/host/crypto_profile/test_generator.py index da49c357f..21c75c8a4 100644 --- a/tests/host/crypto_profile/test_generator.py +++ b/tests/host/crypto_profile/test_generator.py @@ -71,9 +71,9 @@ def test_footprint_requires_matched_pairs_per_port(self): rows[-1] = dict(rows[-1], flash="8303") self.assertTrue(footprint.compare(rows, 8192)[1]) - def test_full_means_implemented_proxy_operations(self): + def test_extended_means_implemented_proxy_operations(self): selected, mechanisms = profile.select(self.catalog, self.defaults, - "full", {}, [], []) + "extended", {}, [], []) self.assertIn("C_DeriveKey", selected["pkcs11"]) self.assertNotIn("C_WrapKey", selected["pkcs11"]) self.assertIsNone(mechanisms) @@ -157,7 +157,7 @@ def test_multipart_actions_and_mechanism_aliases(self): def test_secure_auxiliary_modes_follow_selected_dependencies(self): cases = (("default", {}, [], False), - ("full", {}, [], True), + ("extended", {}, [], True), ("default", {"mechanisms": ["CKM_AES_CTR"]}, [], True), ("default", {}, ["tpm:PCR_Read"], True)) for kind, custom, enabled, extra in cases: diff --git a/tests/host/keystore_ipc/Makefile b/tests/host/keystore_ipc/Makefile index 9e45aaec2..6a73ace2f 100644 --- a/tests/host/keystore_ipc/Makefile +++ b/tests/host/keystore_ipc/Makefile @@ -68,7 +68,8 @@ _WT_SRCS := \ $(ROOT)/src/services/initial_attestation.c \ $(ROOT)/src/services/attestation_cose.c \ $(ROOT)/src/services/wolfhsm/wt_hsm_vault.c \ - $(ROOT)/src/services/wolfhsm/wt_hsm_seal.c + $(ROOT)/src/services/wolfhsm/wt_hsm_seal.c \ + $(ROOT)/src/services/wolfhsm/wt_hsm_aead.c _WH_SRCS := \ $(WOLFHSM)/src/wh_nvm.c \ diff --git a/tests/host/keystore_ipc/user_settings.h b/tests/host/keystore_ipc/user_settings.h index b2eacb152..4e89a6347 100644 --- a/tests/host/keystore_ipc/user_settings.h +++ b/tests/host/keystore_ipc/user_settings.h @@ -54,6 +54,9 @@ #define WOLFSSL_SHA256 #define HAVE_HASHDRBG #define HAVE_AESGCM +#ifdef WT_AEAD_CCM +#define HAVE_AESCCM +#endif #define NO_SHA #define NO_RSA diff --git a/tests/host/layout.mk b/tests/host/layout.mk index 8fa4599d1..b9440015f 100644 --- a/tests/host/layout.mk +++ b/tests/host/layout.mk @@ -6,6 +6,7 @@ WT_LAYOUT_CPP ?= $(CC) # A fixture renders the whole template, update partition included, so its # layout reserves the update stack (WT_FWU=1). WT_FWU ?= 1 +include $(ROOT)/mk/profile.mk include $(ROOT)/mk/target-$(TARGET).mk include $(ROOT)/mk/layout.mk # The renderer runs on every make and writes only on change, as the diff --git a/tests/host/manifest/test_generator.py b/tests/host/manifest/test_generator.py index fc56884a3..244cfd42a 100644 --- a/tests/host/manifest/test_generator.py +++ b/tests/host/manifest/test_generator.py @@ -291,18 +291,18 @@ def test_excluded_partition_leaves_no_symbols(self): manifest = json.loads(FIXTURE.read_text(encoding="utf-8")) manifest["partitions"][0]["dependencies"] = [] source.write_text(json.dumps(manifest), encoding="utf-8") - full = root / "full" - lean = root / "lean" - self.assertEqual(self.run_generator(source, full).returncode, 0) + whole = root / "whole" + trimmed = root / "trimmed" + self.assertEqual(self.run_generator(source, whole).returncode, 0) result = self.run_generator( - source, lean, extra=("--exclude-partition", "PARTITION_BETA")) + source, trimmed, extra=("--exclude-partition", "PARTITION_BETA")) self.assertEqual(result.returncode, 0, result.stderr) - pid = (lean / "psa_manifest" / "pid.h").read_text(encoding="utf-8") - sid = (lean / "psa_manifest" / "sid.h").read_text(encoding="utf-8") + pid = (trimmed / "psa_manifest" / "pid.h").read_text(encoding="utf-8") + sid = (trimmed / "psa_manifest" / "sid.h").read_text(encoding="utf-8") self.assertIn("#define PARTITION_ALPHA_ID 1", pid) self.assertNotIn("PARTITION_BETA", pid) self.assertNotIn("SERVICE_BETA", sid) - self.assertFalse((lean / "psa_manifest" / + self.assertFalse((trimmed / "psa_manifest" / "partition_beta.h").exists()) reused = root / "reused" self.assertEqual(self.run_generator(source, reused).returncode, 0) @@ -323,9 +323,9 @@ def test_excluded_partition_leaves_no_symbols(self): digest = hashlib.sha256(json.dumps( manifest, sort_keys=True, separators=(",", ":")).encode("utf-8")).hexdigest() - lean_c = (lean / "wolftrust_manifest_generated.c").read_text( + lean_c = (trimmed / "wolftrust_manifest_generated.c").read_text( encoding="utf-8") - full_c = (full / "wolftrust_manifest_generated.c").read_text( + full_c = (whole / "wolftrust_manifest_generated.c").read_text( encoding="utf-8") self.assertIn("SHA-256: " + digest, lean_c) self.assertNotIn("SHA-256: " + digest, full_c) @@ -346,6 +346,106 @@ def test_excluding_a_dependency_or_unknown_partition_is_rejected(self): self.assertIn(message, result.stderr) self.assertFalse(output.exists()) + def test_dropped_dependency_leaves_the_partition_and_its_digest(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + whole = root / "whole" + dropped = root / "dropped" + self.assertEqual(self.run_generator(FIXTURE, whole).returncode, 0) + result = self.run_generator( + FIXTURE, dropped, + extra=("--drop-dependency", "PARTITION_ALPHA=SERVICE_BETA")) + self.assertEqual(result.returncode, 0, result.stderr) + full_c = (whole / "wolftrust_manifest_generated.c").read_text( + encoding="utf-8") + lean_c = (dropped / "wolftrust_manifest_generated.c").read_text( + encoding="utf-8") + self.assertIn("wt_generated_dependencies_0[1]", full_c) + self.assertNotIn("wt_generated_dependencies_0", lean_c) + self.assertEqual(lean_c.count(".dependency_count = 0U,"), 2) + manifest = json.loads(FIXTURE.read_text(encoding="utf-8")) + manifest["partitions"][0]["dependencies"] = [] + digest = hashlib.sha256(json.dumps( + manifest, sort_keys=True, + separators=(",", ":")).encode("utf-8")).hexdigest() + self.assertIn("SHA-256: " + digest, lean_c) + self.assertIn("SERVICE_BETA", (dropped / "psa_manifest" / + "sid.h").read_text(encoding="utf-8")) + print("PASS: WT-FFM-0004 a dropped dependency keeps the service " + "and the digest covers the trimmed manifest") + + def test_dropped_dependency_lets_its_service_be_excluded(self): + drop = ("--drop-dependency", "PARTITION_ALPHA=SERVICE_BETA") + exclude = ("--exclude-partition", "PARTITION_BETA") + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + for index, extra in enumerate((drop + exclude, exclude + drop)): + output = root / ("both%d" % index) + result = self.run_generator(FIXTURE, output, extra=extra) + self.assertEqual(result.returncode, 0, result.stderr) + pid = (output / "psa_manifest" / "pid.h").read_text( + encoding="utf-8") + self.assertNotIn("PARTITION_BETA", pid) + print("PASS: WT-FFM-0004 a dropped dependency lets the partition it " + "named be excluded, in either flag order") + + def test_dropping_an_unknown_or_absent_dependency_is_rejected(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + for value, message in ( + ("PARTITION_BETA=SERVICE_ALPHA", + "PARTITION_BETA does not depend on SERVICE_ALPHA"), + ("PARTITION_ALPHA=SERVICE_ALPHA", + "PARTITION_ALPHA does not depend on SERVICE_ALPHA"), + ("PARTITION_GAMMA=SERVICE_BETA", "does not name a partition"), + ("PARTITION_ALPHA=SERVICE_GAMMA", "does not name a partition"), + ("PARTITION_ALPHA", "does not name a partition")): + output = root / value.replace("=", "_") + result = self.run_generator( + FIXTURE, output, extra=("--drop-dependency", value)) + self.assertNotEqual(result.returncode, 0, value) + self.assertIn(message, result.stderr) + self.assertFalse(output.exists()) + twice = root / "twice.json" + manifest = json.loads(FIXTURE.read_text(encoding="utf-8")) + manifest["partitions"][0]["dependencies"] *= 2 + twice.write_text(json.dumps(manifest), encoding="utf-8") + output = root / "twice" + result = self.run_generator( + twice, output, + extra=("--drop-dependency", "PARTITION_ALPHA=SERVICE_BETA")) + self.assertNotEqual(result.returncode, 0) + self.assertIn("exactly once", result.stderr) + self.assertFalse(output.exists()) + print("PASS: WT-FFM-0004 a dependency the manifest lacks or " + "repeats is refused") + + def test_hmac_attestation_key_drops_the_crypto_dependency(self): + drop = "--drop-dependency PARTITION_ATTEST=SERVICE_HSM" + for flags, dropped in ((("WT_PROFILE=tiny",), True), + (("WT_ATTEST_KEY=hmac",), True), + (("WT_PROFILE=default",), False)): + args = subprocess.run( + ["make", "-s", "--no-print-directory", "-C", str(ROOT), + "TARGET=stm32h563", + "WT_LAYOUT_CPP=" + os.environ.get("CC", "cc")] + list(flags) + + ["print-manifest-gen-args"], + check=True, capture_output=True, text=True).stdout + self.assertEqual(drop in " ".join(args.split()), dropped, flags) + with tempfile.TemporaryDirectory() as temporary: + output = Path(temporary) / "hmac" + result = self.run_generator( + H5_MANIFEST, output, supported_features="0x7", + extra=tuple(drop.split())) + self.assertEqual(result.returncode, 0, result.stderr) + source = (output / "wolftrust_manifest_generated.c").read_text( + encoding="utf-8") + attest = source[source.index('.name = "PARTITION_ATTEST"'):] + attest = attest[:attest.index("},")] + self.assertIn(".dependency_count = 0U,", attest) + print("PASS: WT-FFM-0004 an HMAC attestation key leaves the " + "attestation partition no crypto service dependency") + def test_excluding_a_partition_outside_an_sp_domain_is_rejected(self): with tempfile.TemporaryDirectory() as temporary: root = Path(temporary) diff --git a/tests/host/manifest/test_probe_stamp.sh b/tests/host/manifest/test_probe_stamp.sh index b8d96c9dd..8713630c2 100644 --- a/tests/host/manifest/test_probe_stamp.sh +++ b/tests/host/manifest/test_probe_stamp.sh @@ -126,13 +126,13 @@ esac check $st "WT_CONFORMANCE=1 in the 256 KiB slot links" plan=$(cd "$root" && make -n -s TARGET=stm32h563 test-target 2>/dev/null | tr '\n' ' ') case "$plan" in -*"WT_PROFILE=default WT_SUITE_LOG_DIR=logs/default"*"WT_PROFILE=full WT_SUITE_LOG_DIR=logs/full"*) st=0 ;; +*"WT_PROFILE=default WT_SUITE_LOG_DIR=logs/default"*"WT_PROFILE=extended WT_SUITE_LOG_DIR=logs/extended"*) st=0 ;; *) st=1 ;; esac -check $st "make test-target runs default then full, each with its own logs" +check $st "make test-target runs default then extended, each with its own logs" plan=$(cd "$root" && make -n -s TARGET=stm32h563 WT_PROFILE=default test-target 2>/dev/null | tr '\n' ' ') case "$plan" in -*"WT_PROFILE=full"*) st=1 ;; +*"WT_PROFILE=extended"*) st=1 ;; *"WT_PROFILE=default WT_SUITE_LOG_DIR=logs "*) st=0 ;; *) st=1 ;; esac @@ -159,13 +159,85 @@ for value in 2 "0 1"; do else st=1; fi check $st "WT_MANIFEST_RUNTIME_CHECK='$value' stops the build" done -for value in lean "default full"; do +for value in lean full compat "default extended"; do if (cd "$root" && WT_TARGET_SCENARIOS=1 make -s WT_PROFILE="$value" \ test-target >/dev/null 2>"$build/profile.err"); then st=1; elif grep -q 'unsupported WT_PROFILE' "$build/profile.err"; then st=0; else st=1; fi check $st "make test-target WT_PROFILE='$value' fails" done +if (cd "$root" && WT_TARGET_SCENARIOS=1 make -s WT_PROFILE=tiny \ + test-target >/dev/null 2>"$build/profile.err"); then st=1; +elif grep -q "unsupported test profile 'tiny'" "$build/profile.err"; then st=0; +else st=1; fi +check $st "make test-target WT_PROFILE=tiny fails, no scenario set registers it" +# shellcheck source=../../target/lib/profile.sh disable=SC1091 +. "$root/tests/target/lib/profile.sh" +for value in tiny small default extended; do + want=$(cd "$root" && make -s --no-print-directory TARGET=stm32h563 \ + WT_PROFILE="$value" print-profile) + # shellcheck disable=SC2046 + got=$(cd "$root" && make -s --no-print-directory TARGET=stm32h563 \ + $(scenario_profile_flags "$value") print-profile) + case "$want" in + *"WT_SECURE_PSA_PROFILE=$value "*) st=0 ;; + *) st=1 ;; + esac + [ "$want" = "$got" ] || st=1 + check $st "profile.sh and mk/profile.mk agree on $value" +done +for cfg in CONFIG_TPM=y CONFIG_PKCS11=y; do + if (cd "$root" && make -s --no-print-directory TARGET=stm32l562 "$cfg" \ + WT_PROFILE=extended print-profile >/dev/null 2>"$build/profile.err"); then + st=1 + elif grep -q 'no update partition' "$build/profile.err"; then st=0; + else st=1; fi + check $st "stm32l562 $cfg refuses the extended profile's update partition" + got=$(cd "$root" && make -s --no-print-directory TARGET=stm32l562 "$cfg" \ + WT_PROFILE=extended WT_FWU=0 print-profile 2>/dev/null) + case "$got" in + *"WT_SECURE_PSA_PROFILE=extended "*"WT_FWU=0 "*) st=0 ;; + *) st=1 ;; + esac + check $st "stm32l562 $cfg builds extended with WT_FWU=0" +done +# ECC leaves a build only when no feature asks for it; each row is +# "|". +while IFS='|' read -r args want; do + # shellcheck disable=SC2086 + got=$(cd "$root" && make -s --no-print-directory TARGET=stm32h563 $args \ + print-profile 2>/dev/null) + case "$got" in + *" $want") st=0 ;; + *) st=1 ;; + esac + check $st "'$args' resolves $want" +done <<'EOF' +WT_PROFILE=tiny|WT_ATTEST_KEY=hmac WT_VAULT_ECC=0 WT_NO_ECC=1 +WT_PROFILE=small|WT_ATTEST_KEY=ecc WT_VAULT_ECC=1 WT_NO_ECC=0 +WT_PROFILE=default|WT_ATTEST_KEY=ecc WT_VAULT_ECC=1 WT_NO_ECC=0 +WT_PROFILE=extended|WT_ATTEST_KEY=ecc WT_VAULT_ECC=1 WT_NO_ECC=0 +WT_PROFILE=tiny WT_ATTEST_KEY=ecc|WT_ATTEST_KEY=ecc WT_VAULT_ECC=0 WT_NO_ECC=0 +WT_PROFILE=tiny WT_VAULT_ECC=1|WT_ATTEST_KEY=hmac WT_VAULT_ECC=1 WT_NO_ECC=0 +WT_PROFILE=tiny CONFIG_TPM=y|WT_ATTEST_KEY=hmac WT_VAULT_ECC=0 WT_NO_ECC=0 +WT_PROFILE=tiny WT_SECURE_PSA=0|WT_ATTEST_KEY=hmac WT_VAULT_ECC=0 WT_NO_ECC=1 +WT_PROFILE=tiny WT_ENGINE=hsm|WT_ATTEST_KEY=ecc WT_VAULT_ECC=1 WT_NO_ECC=0 +WT_PROFILE=small WT_ATTEST_KEY=hmac WT_VAULT_ECC=0|WT_ATTEST_KEY=hmac WT_VAULT_ECC=0 WT_NO_ECC=0 +EOF +while IFS='|' read -r args want; do + # shellcheck disable=SC2086 + if (cd "$root" && make -s --no-print-directory TARGET=stm32h563 $args \ + print-profile >/dev/null 2>"$build/profile.err"); then st=1; + elif grep -q "$want" "$build/profile.err"; then st=0; + else st=1; fi + check $st "'$args' stops the build" +done <<'EOF' +WT_ATTEST_KEY=rsa|unsupported WT_ATTEST_KEY +WT_VAULT_ECC=2|unsupported WT_VAULT_ECC +WT_ATTEST_KEY=hmac WT_ATTEST_DEV_KEY=2|unsupported WT_ATTEST_DEV_KEY +WT_ENGINE=hsm WT_ATTEST_KEY=hmac|WT_ATTEST_KEY=hmac requires WT_ENGINE=native +WT_ENGINE=hsm WT_VAULT_ECC=0|WT_VAULT_ECC=0 requires WT_ENGINE=native +EOF gen for target in stm32h563 mimxrt700 mcxn947; do diff --git a/tests/host/manifest_ports/run.sh b/tests/host/manifest_ports/run.sh index 6ac619769..cd0199c9c 100755 --- a/tests/host/manifest_ports/run.sh +++ b/tests/host/manifest_ports/run.sh @@ -35,10 +35,10 @@ for port in $(python3 "$matrix" --list-ports); do for variant in base $(python3 "$matrix" --port "$port" --get build.variants); do case "$variant" in conformance) profiles="conformance" ;; - vnet) profiles="full" ;; + vnet) profiles="extended" ;; *) profiles=$(python3 "$matrix" --port "$port" \ --get "build.variant_profiles.$variant" 2>/dev/null) || - profiles="default full" ;; + profiles="default extended" ;; esac for profile in $profiles; do out="$build/$port-$variant-$profile" diff --git a/tests/host/manifest_render/test_manifest_render.py b/tests/host/manifest_render/test_manifest_render.py index ffb9e5abe..259b537fb 100644 --- a/tests/host/manifest_render/test_manifest_render.py +++ b/tests/host/manifest_render/test_manifest_render.py @@ -40,19 +40,19 @@ # pinned so a layout or template change is a reviewed change. COMMITTED = { ("mimxrt700", "base", ()): - "2a8f67cd013b5f534c3c48e0195cc2c5854525ee47a36954c0b675b12a01847a", + "e63895e06a379aad3bcc0c4b29953f77526675089cc9729f3980f8de27c8c644", ("mimxrt700", "conformance", ()): - "748bf73294540693073ccb9aa5a83bb55085b92e30003380ef01d336efbfbe5a", + "4cfda447a1f99b01d81c35c98ccd3981f22e346ac42aebfcd5d6d129a660b9dc", ("mcxn947", "base", ()): - "28c46fc03171158475db9153502bdb22e583bc14fcb60299bc3c3345bc2bb445", + "221d9fc37deeaf28f3bf04623e064adb3dda39bfc1c31e1a4573ffb0e6174fd6", ("mcxn947", "conformance", ()): - "cf0602f422b3d53eb62c18ed9580f091af0003e9159e6c7325e161018d56bee8", + "462e1613c838077827e9a9bc4923e9fe61ca1dc226fa00cf126b1229c99ee1ac", ("stm32h563", "base", H5_COMMITTED): - "77f09d6487ea655ece1f7dba193c292ac3ed436a9c02721bf84629a5a0b6f6f8", + "40b10e0c917069a5b703545d01047a5a7caf6aa508c89d74dba646d8a4ff9e11", ("stm32h563", "conformance", H5_COMMITTED): - "c9115da7e2dc8cb9bb2edb6c53f5d7ea46c16abd2db8c62fb1a4c53110cb294b", + "b0ce6923988b108cc713414953189e700622de0b85cc0fd5a5d8976d12d467c9", ("stm32h563", "vnet", H5_COMMITTED): - "e49f32094532d8007ea671fa8ade84300ef0e17239ace7f71c06155f39c97a37", + "c167af67004d5c7e04c57a557f6a275e1ef06db5685569177bccf4858b6cf710", } WINDOW_MACROS = ( "WT_SECURE_FLASH_BASE", "WT_RAM_S_BASE", "WT_SP_CODE_BASE", @@ -182,7 +182,7 @@ def mode(target, variant): """A variant a port limits to the default profile builds without FWU.""" result = run([sys.executable, str(ROOT / "tests/target/lib/scenario_matrix.py"), "--port", target, "--get", "build.variant_profiles." + variant]) - if result.returncode == 0 and "full" not in result.stdout.split(): + if result.returncode == 0 and "extended" not in result.stdout.split(): return tuple(f for f in MODE[variant] if f != "WT_FWU=1"), True return MODE[variant], False diff --git a/tests/host/native_wire/Makefile b/tests/host/native_wire/Makefile index 437c6d4fc..6c623cab4 100644 --- a/tests/host/native_wire/Makefile +++ b/tests/host/native_wire/Makefile @@ -21,9 +21,12 @@ ROOT := ../../.. WOLFHSM := $(ROOT)/lib/wolfHSM WOLFSSL := $(ROOT)/lib/wolfSSL +WOLFPSA := $(ROOT)/lib/wolfPSA CC ?= cc BUILD_DIR ?= build +# SP_DIRECT=1 builds the direct P-256 keyvault path of the profiles below extended +SP_DIRECT ?= 0 CFLAGS := \ -DWOLFSSL_USER_SETTINGS \ @@ -36,6 +39,18 @@ CFLAGS := \ -I$(WOLFSSL) \ -std=c11 -O0 -g -Wall -Wextra -Werror -pedantic \ -Wno-unused-function -Wno-unused-parameter +ifeq ($(SP_DIRECT),1) +CFLAGS += -DWOLFPSA_ECC_SP_DIRECT -I$(WOLFPSA) +endif +# VAULT_ECC=0 builds the vault without P-256 key operations, as tiny does; +# KEYVAULT_P256=1 keeps the backend's P-256 for an ECC attestation key. +VAULT_ECC ?= 1 +KEYVAULT_P256 ?= $(VAULT_ECC) +NO_ECC := $(if $(filter 00,$(VAULT_ECC)$(KEYVAULT_P256)),1,0) +CFLAGS += -DWT_VAULT_ECC=$(VAULT_ECC) -DWT_KEYVAULT_P256=$(KEYVAULT_P256) +ifeq ($(NO_ECC),1) +CFLAGS += -DWT_NO_ECC=1 +endif CFLAGS += $(EXTRA_CFLAGS) # wolfCrypt's ECC sources need GNU libc declarations that strict C11 @@ -48,6 +63,7 @@ WC_CFLAGS := $(filter-out -std=c11 -Werror -pedantic -Wextra,$(CFLAGS)) _WT_SRCS := \ $(ROOT)/src/services/native/native_wire.c \ $(ROOT)/src/services/native/keyvault.c \ + $(ROOT)/src/services/wolfhsm/wt_hsm_aead.c \ $(ROOT)/src/services/wolfhsm/wt_hsm_vault.c _WH_SRCS := \ @@ -71,6 +87,13 @@ _WC_SRCS := \ $(WOLFSSL)/wolfcrypt/src/hash.c \ $(WOLFSSL)/wolfcrypt/src/wc_port.c \ $(WOLFSSL)/wolfcrypt/src/misc.c +ifeq ($(SP_DIRECT),1) +_WC_SRCS += $(WOLFSSL)/wolfcrypt/src/sp_c32.c $(WOLFSSL)/wolfcrypt/src/sp_c64.c +_WP_SRCS := $(WOLFPSA)/src/psa_p256.c +endif +ifeq ($(NO_ECC),1) +_WC_SRCS := $(filter-out %/ecc.c %/sp_int.c %/wolfmath.c,$(_WC_SRCS)) +endif _TEST_SRCS := main.c @@ -85,9 +108,11 @@ endif _WT_OBJS := $(patsubst %.c,wt_%.o,$(notdir $(_WT_SRCS))) _WH_OBJS := $(patsubst %.c,wh_%.o,$(notdir $(_WH_SRCS))) _WC_OBJS := $(patsubst %.c,wc_%.o,$(notdir $(_WC_SRCS))) +_WP_OBJS := $(patsubst %.c,wp_%.o,$(notdir $(_WP_SRCS))) _TEST_OBJS := $(patsubst %.c,%.o,$(notdir $(_TEST_SRCS))) -ALL_OBJS := $(addprefix $(BUILD_DIR)/,$(_WT_OBJS) $(_WH_OBJS) $(_WC_OBJS) $(_TEST_OBJS)) +ALL_OBJS := $(addprefix $(BUILD_DIR)/,$(_WT_OBJS) $(_WH_OBJS) $(_WC_OBJS) \ + $(_WP_OBJS) $(_TEST_OBJS)) TEST_BIN := $(BUILD_DIR)/test_native_wire .PHONY: all run compilers sanitize valgrind clean @@ -117,6 +142,9 @@ $(BUILD_DIR)/wh_%.o: $(WOLFHSM)/src/%.c | $(BUILD_DIR) $(BUILD_DIR)/wc_%.o: $(WOLFSSL)/wolfcrypt/src/%.c | $(BUILD_DIR) $(CC) $(WC_CFLAGS) -c -o $@ $< +$(BUILD_DIR)/wp_%.o: $(WOLFPSA)/src/%.c | $(BUILD_DIR) + $(CC) $(WC_CFLAGS) -c -o $@ $< + $(BUILD_DIR)/%.o: %.c | $(BUILD_DIR) $(CC) $(CFLAGS) -c -o $@ $< @@ -130,12 +158,27 @@ run: $(TEST_BIN) if [ "$$result" -ne 1 ]; then \ cat $(BUILD_DIR)/aes_setup_failure.log; exit 1; \ fi; \ - if ! grep -q '^PASS: AES-GCM setup failure returns safely$$' $(BUILD_DIR)/aes_setup_failure.log; then \ + if ! grep -q '^PASS: AEAD setup failure returns safely$$' $(BUILD_DIR)/aes_setup_failure.log; then \ cat $(BUILD_DIR)/aes_setup_failure.log; exit 1; \ fi; \ - printf '%s\n' 'PASS: AES-GCM setup failure remains a failed test' + printf '%s\n' 'PASS: AEAD setup failure remains a failed test' $(MAKE) --no-print-directory all BUILD_DIR=$(BUILD_DIR)/asn ASN=1 $(BUILD_DIR)/asn/test_native_wire +ifneq ($(SP_DIRECT),1) + $(MAKE) --no-print-directory SP_DIRECT=1 BUILD_DIR=$(BUILD_DIR)/direct \ + $(BUILD_DIR)/direct/test_native_wire + $(BUILD_DIR)/direct/test_native_wire + @printf '%s\n' 'PASS: native wire on the direct P-256 path' +endif +ifeq ($(VAULT_ECC)$(SP_DIRECT),10) + $(MAKE) --no-print-directory VAULT_ECC=0 BUILD_DIR=$(BUILD_DIR)/noecc \ + $(BUILD_DIR)/noecc/test_native_wire + $(BUILD_DIR)/noecc/test_native_wire + $(MAKE) --no-print-directory VAULT_ECC=0 KEYVAULT_P256=1 \ + BUILD_DIR=$(BUILD_DIR)/iakecc $(BUILD_DIR)/iakecc/test_native_wire + $(BUILD_DIR)/iakecc/test_native_wire + @printf '%s\n' 'PASS: native wire without vault P-256' +endif compilers: $(MAKE) clean run CC=gcc BUILD_DIR=$(BUILD_DIR)/gcc diff --git a/tests/host/native_wire/main.c b/tests/host/native_wire/main.c index 73cc334ed..c76f295fc 100644 --- a/tests/host/native_wire/main.c +++ b/tests/host/native_wire/main.c @@ -21,7 +21,7 @@ /* Native crypto wire suite: drives wt_native_submit with real request * packets over a RAM-backed NVM store, exactly as SERVICE_HSM's relay hands * them over on target — every operation, the per-client key namespace, usage - * and type enforcement, malformed packets, and AES-GCM tamper rejection. */ + * and type enforcement, malformed packets, and AEAD tamper rejection. */ #include "wolfssl/wolfcrypt/settings.h" #include "wolfssl/wolfcrypt/types.h" @@ -424,7 +424,7 @@ static void test_aes_rng_failure(void) static void test_aes_gcm(void) { - static const uint8_t plaintext[] = "native wire AES-GCM round trip"; + static const uint8_t plaintext[] = "native wire AEAD round trip"; uint8_t ct[WT_HSM_RELAY_MSG_MAX]; uint8_t pt[WT_HSM_RELAY_MSG_MAX]; size_t ct_len = 0U; @@ -494,6 +494,74 @@ static void test_import(void) "import refuses a short scalar"); } +/* WT_VAULT_ECC=0: no client reaches a P-256 key, and the backend keeps the + * key type only for an ECC attestation key (WT_KEYVAULT_P256). */ +static void test_no_p256(void) +{ + static const uint8_t digest[WT_VAULT_KEY_DIGEST_LEN] = { 0x5a }; + uint8_t in[WT_VAULT_KEY_DIGEST_LEN + WT_VAULT_KEY_SIG_LEN]; + uint8_t out[WT_HSM_RELAY_MSG_MAX]; + size_t got = 0U; + psa_status_t status = PSA_SUCCESS; + int rc; + + (void)memset(in, 0x11, sizeof(in)); + rc = wire(TEST_NS_GUEST0, WT_CRYPTO_OP_KEY_GENERATE, 0x60U, + WT_VAULT_KEY_USAGE_SIGN, WT_VAULT_KEY_P256, NULL, 0U, NULL, 0U, + &got, &status); + check(rc == 0 && status == PSA_ERROR_NOT_SUPPORTED && got == 0U, + "GENERATE refuses a P-256 key"); + rc = wire(TEST_NS_GUEST0, WT_CRYPTO_OP_KEY_IMPORT, 0x61U, + WT_VAULT_KEY_USAGE_SIGN, WT_VAULT_KEY_P256, in, + WT_VAULT_KEY_MATERIAL_LEN, NULL, 0U, &got, &status); + check(rc == 0 && status == PSA_ERROR_NOT_SUPPORTED && got == 0U, + "IMPORT refuses a P-256 key"); + rc = wire(TEST_NS_GUEST0, WT_CRYPTO_OP_KEY_EXPORT_PUBLIC, 0x60U, 0U, 0U, + NULL, 0U, out, sizeof(out), &got, &status); + check(rc == 0 && status == PSA_ERROR_NOT_SUPPORTED && got == 0U, + "EXPORT_PUBLIC is not served"); + rc = wire(TEST_NS_GUEST0, WT_CRYPTO_OP_KEY_SIGN, 0x60U, 0U, 0U, digest, + sizeof(digest), out, sizeof(out), &got, &status); + check(rc == 0 && status == PSA_ERROR_NOT_SUPPORTED && got == 0U, + "SIGN is not served"); + rc = wire(TEST_NS_GUEST0, WT_CRYPTO_OP_KEY_VERIFY, 0x60U, 0U, 0U, in, + sizeof(in), NULL, 0U, &got, &status); + check(rc == 0 && status == PSA_ERROR_NOT_SUPPORTED && got == 0U, + "VERIFY is not served"); + rc = wire(TEST_NS_GUEST0, WT_CRYPTO_OP_KEY_GENERATE, 0x2004ULL, + WT_VAULT_KEY_USAGE_ENCRYPT | WT_VAULT_KEY_USAGE_DECRYPT, + WT_VAULT_KEY_AES256, NULL, 0U, NULL, 0U, &got, &status); + check(rc == 0 && status == PSA_SUCCESS, + "GENERATE still makes an AES-256 key"); + + status = wt_hsm_key_backend.generate(0, 0, 0xF0U, WT_VAULT_KEY_P256, + WT_VAULT_KEY_USAGE_SIGN); +#if WT_KEYVAULT_P256 + check(status == PSA_SUCCESS, "the backend makes the attestation key"); + status = wt_hsm_key_backend.sign(0, 0, 0xF0U, digest, sizeof(digest), + out, sizeof(out), &got); + check(status == PSA_SUCCESS && got == WT_VAULT_KEY_SIG_LEN, + "the backend signs with the attestation key"); + rc = wire(0, WT_CRYPTO_OP_KEY_SIGN, 0xF0U, 0U, 0U, digest, + sizeof(digest), out, sizeof(out), &got, &status); + check(rc == 0 && status == PSA_ERROR_NOT_SUPPORTED && got == 0U, + "the wire does not sign with the attestation key"); +#else + check(status == PSA_ERROR_NOT_SUPPORTED, "the backend has no P-256 key"); + got = 7U; + status = wt_hsm_key_backend.sign(0, 0, 0xF0U, digest, sizeof(digest), + out, sizeof(out), &got); + check(status == PSA_ERROR_NOT_SUPPORTED, "the backend does not sign"); + status = wt_hsm_key_backend.verify(0, 0, 0xF0U, digest, sizeof(digest), + in, WT_VAULT_KEY_SIG_LEN); + check(status == PSA_ERROR_NOT_SUPPORTED, "the backend does not verify"); + status = wt_hsm_key_backend.export_public(0, 0, 0xF0U, out, sizeof(out), + &got); + check(status == PSA_ERROR_NOT_SUPPORTED, + "the backend exports no public key"); +#endif +} + static void test_psa_uid_reserved(void) { static const uint32_t ops[] = { @@ -590,17 +658,22 @@ int main(int argc, char* argv[]) if (g_failures != 1) { return 2; } - (void)printf("PASS: AES-GCM setup failure returns safely\n"); + (void)printf("PASS: AEAD setup failure returns safely\n"); return 1; } test_random_and_hash(); +#if WT_VAULT_ECC test_p256_lifecycle(); test_usage_and_type(); test_aes_rng_failure(); test_aes_gcm(); test_import(); test_malformed(); +#else + test_no_p256(); + test_aes_gcm(); +#endif test_psa_uid_reserved(); if (g_failures != 0) { diff --git a/tests/host/native_wire/user_settings.h b/tests/host/native_wire/user_settings.h index a6271dacf..d7aa329c2 100644 --- a/tests/host/native_wire/user_settings.h +++ b/tests/host/native_wire/user_settings.h @@ -29,6 +29,9 @@ #define WOLFSSL_USER_IO #define NO_TLS +#ifdef WT_NO_ECC +#define NO_BIG_INT +#else #define HAVE_ECC #define ECC_USER_CURVES #define ECC_TIMING_RESISTANT @@ -36,9 +39,17 @@ /* ISO C99 gate: pin fixed-size SP-math stacks (no VLAs) and pull in * so ecc.c's strcasecmp curve lookup is declared. */ #define WOLFSSL_SP_NO_DYN_STACK +#ifdef WOLFPSA_ECC_SP_DIRECT +#define WOLFSSL_HAVE_SP_ECC +#define WOLFSSL_SP_SMALL +#endif #define HAVE_STRINGS_H +#endif #define HAVE_AESGCM +#ifdef WT_AEAD_CCM +#define HAVE_AESCCM +#endif #define WOLFSSL_SHA256 #define HAVE_HASHDRBG diff --git a/tests/host/negatives/Makefile b/tests/host/negatives/Makefile index 50733446f..22904490d 100644 --- a/tests/host/negatives/Makefile +++ b/tests/host/negatives/Makefile @@ -47,6 +47,7 @@ _WT_SRCS := \ $(ROOT)/src/services/vault_service.c \ $(ROOT)/src/services/wolfhsm/wt_hsm_vault.c \ $(ROOT)/src/services/wolfhsm/wt_hsm_seal.c \ + $(ROOT)/src/services/wolfhsm/wt_hsm_aead.c \ $(ROOT)/src/services/storage_service.c _WH_SRCS := \ diff --git a/tests/host/negatives/user_settings.h b/tests/host/negatives/user_settings.h index 0aa5c1f3f..c27327412 100644 --- a/tests/host/negatives/user_settings.h +++ b/tests/host/negatives/user_settings.h @@ -93,6 +93,9 @@ #define NO_DH #define NO_DSA #define HAVE_AESGCM +#ifdef WT_AEAD_CCM +#define HAVE_AESCCM +#endif #define NO_DES3 #define NO_RC4 #define NO_MD4 diff --git a/tests/host/nvm_boot/Makefile b/tests/host/nvm_boot/Makefile index 9177664b8..e5f192b4b 100644 --- a/tests/host/nvm_boot/Makefile +++ b/tests/host/nvm_boot/Makefile @@ -43,7 +43,8 @@ _WT_SRCS := \ $(ROOT)/src/services/nvm_boot.c \ $(ROOT)/src/services/vault_service.c \ $(ROOT)/src/services/wolfhsm/wt_hsm_vault.c \ - $(ROOT)/src/services/wolfhsm/wt_hsm_seal.c + $(ROOT)/src/services/wolfhsm/wt_hsm_seal.c \ + $(ROOT)/src/services/wolfhsm/wt_hsm_aead.c _WH_SRCS := \ $(WOLFHSM)/src/wh_nvm.c \ diff --git a/tests/host/ps_service/Makefile b/tests/host/ps_service/Makefile index 524a69630..3b55bd862 100644 --- a/tests/host/ps_service/Makefile +++ b/tests/host/ps_service/Makefile @@ -46,7 +46,8 @@ _WT_SRCS := \ $(ROOT)/src/services/storage_service.c \ $(ROOT)/src/services/vault_service.c \ $(ROOT)/src/services/wolfhsm/wt_hsm_vault.c \ - $(ROOT)/src/services/wolfhsm/wt_hsm_seal.c + $(ROOT)/src/services/wolfhsm/wt_hsm_seal.c \ + $(ROOT)/src/services/wolfhsm/wt_hsm_aead.c _WH_SRCS := \ $(WOLFHSM)/src/wh_nvm.c \ diff --git a/tests/host/ps_service/main.c b/tests/host/ps_service/main.c index 15afa8606..8e0cefab6 100644 --- a/tests/host/ps_service/main.c +++ b/tests/host/ps_service/main.c @@ -21,7 +21,7 @@ /* Host proof of the PS partition (P4-S3, WT-FFM-0048): the full sealed * storage chain — a Non-secure client calling SERVICE_PS, the PS dispatch * forcing WT_VAULT_FLAG_SEALED and forwarding over SP-to-SP FF-M IPC to - * SERVICE_VAULT, the real wt_hsm_vault backend AES-GCM-sealing every object + * SERVICE_VAULT, the real wt_hsm_vault backend AEAD-sealing every object * under the device-unique wolfHSM key with the persisted rollback counter as * nonce, over the real wolfHSM NVM stack on the RAM flash simulator. * Negative evidence: plaintext never at rest, a rolled-back ciphertext fails @@ -949,7 +949,7 @@ int main(void) return 1; } - /* The sealed chain: NS -> PS -> gate -> vault -> AES-GCM -> NVM. */ + /* The sealed chain: NS -> PS -> gate -> vault -> AEAD -> NVM. */ status = ps_set(&runtime, TEST_NS_GUEST0, handle_g0, 0x5001ULL, 0U, secret_v1, sizeof(secret_v1)); check(status == PSA_SUCCESS, @@ -964,7 +964,7 @@ int main(void) /* WT-FFM-0048: plaintext is never at rest — the stored NVM object is * ciphertext + tag, and the secret bytes appear nowhere in flash. */ check(test_find_stored(sizeof(secret_v1), &stored_id, &meta) == 0, - "stored object is plain length + GCM tag"); + "stored object is plain length + AEAD tag"); if (stored_id != 0U) { check(test_flash_contains(secret_v1, sizeof(secret_v1)) == 0, "WT-FFM-0048 secret plaintext absent from flash at rest"); diff --git a/tests/host/ps_service/user_settings.h b/tests/host/ps_service/user_settings.h index f93c277b8..4363ac4fe 100644 --- a/tests/host/ps_service/user_settings.h +++ b/tests/host/ps_service/user_settings.h @@ -31,6 +31,9 @@ #define NO_TLS #define HAVE_AESGCM +#ifdef WT_AEAD_CCM +#define HAVE_AESCCM +#endif #define WOLFSSL_SHA256 #define HAVE_HASHDRBG diff --git a/tests/host/psa_secure_crypto/Makefile b/tests/host/psa_secure_crypto/Makefile index a915ee1ee..19646f5e8 100644 --- a/tests/host/psa_secure_crypto/Makefile +++ b/tests/host/psa_secure_crypto/Makefile @@ -24,9 +24,22 @@ WOLFPSA := $(ROOT)/lib/wolfPSA CC ?= cc BUILD_DIR ?= build -# run builds and runs every WT_SECURE_PSA_PROFILE; run-one takes PROFILE. -PROFILE ?= compat -PROFILES := compat standard lean symmetric +# run builds and runs every WT_SECURE_PSA_PROFILE, small on GCM and tiny with +# no ECC in wolfCrypt; run-one takes PROFILE, AEAD (WT_AEAD) and NO_ECC. +PROFILE ?= default +AEAD ?= +NO_ECC ?= +PROFILES := extended default small tiny +# A pass whose EXTRA_CFLAGS already picks the AEAD skips the small-gcm run +RUNS := $(PROFILES) tiny-noecc $(if $(findstring WT_AEAD_,$(EXTRA_CFLAGS)),,small-gcm) +NO_ECC_CFLAGS := $(if $(NO_ECC),-DWT_NO_ECC=1 -DWT_VAULT_ECC=0 -DWT_KEYVAULT_P256=0) +AEAD_CFLAGS := $(if $(filter gcm,$(AEAD)),-DWT_AEAD_GCM)$(if $(filter ccm,$(AEAD)),-DWT_AEAD_CCM) +# small and tiny offer one PSA AEAD, CCM unless GCM is asked for +ONE_AEAD_GCM := $(or $(filter gcm,$(AEAD)),$(findstring WT_AEAD_GCM,$(EXTRA_CFLAGS))) +WANT_WITHOUT := $(if $(filter small tiny,$(PROFILE)),$(if $(ONE_AEAD_GCM),,--without PSA_WANT_ALG_GCM)) \ + $(if $(filter-out extended,$(PROFILE)),--without PSA_WANT_ALG_SP800_108_COUNTER_HMAC \ + --without PSA_WANT_ALG_SP800_108_COUNTER_CMAC \ + --without PSA_WANT_ALG_CCM_STAR_NO_TAG) WARN := -std=c11 -O0 -g -Wall -Wextra -Werror -pedantic \ -Wno-unused-function -Wno-unused-parameter @@ -40,23 +53,28 @@ SRV_CFLAGS := \ -DWOLFSSL_PSA_ENGINE -DWOLFPSA_CUSTOM_STORE -DWOLFPSA_NO_TRACE -DWOLFPSA_AEAD_BORROW \ -DWOLFPSA_AEAD_STREAM_AAD \ -I. -I$(ROOT)/include -I$(WOLFHSM) -I$(WOLFSSL) -I$(WOLFPSA) \ - -I$(WOLFPSA)/wolfpsa -I$(BUILD_DIR)/wolfpsa_cfg $(EXTRA_CFLAGS) + -I$(WOLFPSA)/wolfpsa -I$(BUILD_DIR)/wolfpsa_cfg $(AEAD_CFLAGS) \ + $(NO_ECC_CFLAGS) $(EXTRA_CFLAGS) LIB_CFLAGS := $(SRV_CFLAGS) -O0 -g -w # The Non-secure side: the client library only, no crypto. CLI_CFLAGS := -I. -I$(ROOT)/include -I$(WOLFPSA)/wolfpsa -I$(BUILD_DIR)/wolfpsa_cfg $(WARN) \ - -DWT_SECURE_PSA_$(PROFILE)=1 \ + -DWT_SECURE_PSA_$(PROFILE)=1 $(AEAD_CFLAGS) \ $(EXTRA_CFLAGS) _SRV_WT := \ $(ROOT)/src/services/native/psa_crypto_service.c \ $(ROOT)/src/services/native/native_wire.c \ $(ROOT)/src/services/native/keyvault.c \ + $(ROOT)/src/services/wolfhsm/wt_hsm_aead.c \ $(ROOT)/src/services/wolfhsm/wt_hsm_vault.c _SRV_WH := wh_nvm wh_nvm_flash wh_flash_ramsim wh_flash_unit wh_utils _SRV_WC := aes coding ecc sp_int wolfmath sha256 random memory error logging \ - hash wc_port misc hmac kdf pwdbased + hash wc_port misc hmac kdf pwdbased sp_c32 sp_c64 +ifneq ($(NO_ECC),) +_SRV_WC := $(filter-out ecc sp_int wolfmath sp_c32 sp_c64,$(_SRV_WC)) +endif _SRV_WP := $(notdir $(basename $(filter-out %/psa_store_posix.c \ %/psa_store_zephyr.c %/psa_attestation.c %/psa_ffm.c %/psa_its.c \ %/misc_impl.c %/psa_tf_psa.c,$(wildcard $(WOLFPSA)/src/*.c)))) @@ -76,7 +94,7 @@ CLI_OBJS := $(BUILD_DIR)/psa_crypto_client.o \ SRV_BIN := $(BUILD_DIR)/psa_server TEST_BIN := $(BUILD_DIR)/test_psa_secure_crypto -.PHONY: all run run-one compilers sanitize valgrind clean +.PHONY: all run run-one compilers sanitize valgrind valgrind-one clean FORCE all: $(SRV_BIN) $(TEST_BIN) @@ -84,11 +102,12 @@ $(BUILD_DIR): mkdir -p $@ # Both sides see the PSA_WANT_* surface of the service's wolfCrypt set. +# FORCE: the generator rewrites the header only when the surface changes. PSA_CFG_H := $(BUILD_DIR)/wolfpsa_cfg/crypto_config_generated.h $(PSA_CFG_H): $(WOLFPSA)/tools/gen-crypto-config.py \ - $(WOLFPSA)/tools/psa_want_probe.c user_settings.h | $(BUILD_DIR) + $(WOLFPSA)/tools/psa_want_probe.c user_settings.h FORCE | $(BUILD_DIR) mkdir -p $(dir $@) - python3 $(WOLFPSA)/tools/gen-crypto-config.py $@ "$(CC)" \ + python3 $(WOLFPSA)/tools/gen-crypto-config.py $(WANT_WITHOUT) $@ "$(CC)" \ $(WOLFPSA)/tools/psa_want_probe.c $(SRV_CFLAGS) -DWT_PSA_WANT_PROBE $(SRV_OBJS) $(CLI_OBJS) $(BUILD_DIR)/main.o: $(PSA_CFG_H) @@ -130,11 +149,13 @@ $(SRV_BIN): $(SRV_OBJS) $(TEST_BIN): $(CLI_OBJS) $(BUILD_DIR)/main.o $(CC) $(EXTRA_LDFLAGS) -o $@ $^ -run: - @for p in $(PROFILES); do \ - echo "== profile $$p"; \ - $(MAKE) --no-print-directory run-one PROFILE=$$p \ - BUILD_DIR=$(BUILD_DIR)/$$p || exit 1; \ +run valgrind: + @for r in $(RUNS); do \ + p=$${r%-gcm}; a=; [ "$$p" = "$$r" ] || a=gcm; \ + n=; case $$r in *-noecc) p=$${r%-noecc}; n=1 ;; esac; \ + echo "== profile $$r"; \ + $(MAKE) --no-print-directory $@-one PROFILE=$$p AEAD=$$a NO_ECC=$$n \ + BUILD_DIR=$(BUILD_DIR)/$$r || exit 1; \ done run-one: all @@ -151,10 +172,12 @@ sanitize: EXTRA_CFLAGS="-fsanitize=address,undefined -fno-omit-frame-pointer" \ EXTRA_LDFLAGS="-fsanitize=address,undefined" -valgrind: all +valgrind-one: all rm -f $(BUILD_DIR)/flash.bin valgrind --error-exitcode=1 --leak-check=full \ --trace-children=yes $(TEST_BIN) clean: rm -rf $(BUILD_DIR) + +FORCE: diff --git a/tests/host/psa_secure_crypto/main.c b/tests/host/psa_secure_crypto/main.c index 795268d11..ca2251151 100644 --- a/tests/host/psa_secure_crypto/main.c +++ b/tests/host/psa_secure_crypto/main.c @@ -31,6 +31,7 @@ #include "wolftrust/crypto_native_client.h" #include "wolftrust/services/crypto_native.h" #include "wolftrust/services/psa_crypto_wire.h" +#include "wolftrust/services/vault_service.h" #include "transport.h" #define GUEST0 (-1) @@ -39,6 +40,13 @@ /* Past what the old 2,048-byte staging buffer could carry. */ #define HUGE 5000U +/* small and tiny offer one AEAD, CCM unless built with WT_AEAD=gcm */ +#ifdef PSA_WANT_ALG_GCM +#define WT_TEST_AEAD PSA_ALG_GCM +#else +#define WT_TEST_AEAD PSA_ALG_CCM +#endif + static int g_failures; static void check(int ok, const char* what) @@ -60,7 +68,7 @@ static psa_key_id_t aes_key(psa_key_id_t id, uint8_t fill, psa_status_t* st) psa_set_key_bits(&attr, 128); psa_set_key_usage_flags(&attr, PSA_KEY_USAGE_ENCRYPT | PSA_KEY_USAGE_DECRYPT | PSA_KEY_USAGE_EXPORT); - psa_set_key_algorithm(&attr, PSA_ALG_GCM); + psa_set_key_algorithm(&attr, WT_TEST_AEAD); if (id != PSA_KEY_ID_NULL) { psa_set_key_id(&attr, id); } @@ -119,12 +127,12 @@ static psa_status_t aes_oneshot(psa_algorithm_t alg, int decrypt) return st; } -static psa_status_t pbkdf2_setup(void) +static psa_status_t kdf_setup(psa_algorithm_t alg) { psa_key_derivation_operation_t op = PSA_KEY_DERIVATION_OPERATION_INIT; psa_status_t st; - st = psa_key_derivation_setup(&op, PSA_ALG_PBKDF2_HMAC(PSA_ALG_SHA_256)); + st = psa_key_derivation_setup(&op, alg); (void)psa_key_derivation_abort(&op); return st; } @@ -137,34 +145,58 @@ static void test_profile(void) check(psa_generate_random(NULL, 1U) == PSA_ERROR_INVALID_ARGUMENT, "generate_random refuses a NULL buffer"); - check(aes_oneshot(PSA_ALG_GCM, 0) == PSA_SUCCESS, "GCM in every profile"); +#if defined(WT_SECURE_PSA_small) || defined(WT_SECURE_PSA_tiny) +#ifdef PSA_WANT_ALG_GCM + check(aes_oneshot(PSA_ALG_GCM, 0) == PSA_SUCCESS && + aes_oneshot(PSA_ALG_CCM, 0) == PSA_ERROR_NOT_SUPPORTED, + "WT_AEAD=gcm offers GCM and not CCM"); +#else + check(aes_oneshot(PSA_ALG_CCM, 0) == PSA_SUCCESS && + aes_oneshot(PSA_ALG_GCM, 0) == PSA_ERROR_NOT_SUPPORTED, + "the one-AEAD profiles offer CCM and not GCM"); +#endif +#else + check(aes_oneshot(PSA_ALG_GCM, 0) == PSA_SUCCESS && + aes_oneshot(PSA_ALG_CCM, 0) == PSA_SUCCESS, + "extended and default offer GCM and CCM"); +#endif k = ecc_key(&ecc); if (k != PSA_KEY_ID_NULL) { (void)psa_destroy_key(k); } -#if defined(WT_SECURE_PSA_compat) - check(aes_oneshot(PSA_ALG_CCM, 0) == PSA_SUCCESS, "compat keeps CCM"); + check(kdf_setup(PSA_ALG_HKDF(PSA_ALG_SHA_256)) == PSA_SUCCESS, + "every profile keeps HKDF"); + check(aes_oneshot(PSA_ALG_CTR, 0) == PSA_SUCCESS, + "every profile keeps AES-CTR"); +#if defined(WT_SECURE_PSA_extended) + check(kdf_setup(PSA_ALG_SP800_108_COUNTER_HMAC(PSA_ALG_SHA_256)) == + PSA_SUCCESS, "extended keeps SP 800-108 HMAC"); + check(aes_oneshot(PSA_ALG_CCM_STAR_NO_TAG, 0) == PSA_SUCCESS, + "extended keeps CCM* without a tag"); +#else + check(kdf_setup(PSA_ALG_SP800_108_COUNTER_HMAC(PSA_ALG_SHA_256)) == + PSA_ERROR_NOT_SUPPORTED, "only extended offers SP 800-108"); + check(aes_oneshot(PSA_ALG_CCM_STAR_NO_TAG, 0) == PSA_ERROR_NOT_SUPPORTED, + "only extended offers CCM* without a tag"); +#endif +#if defined(WT_SECURE_PSA_extended) check(aes_oneshot(PSA_ALG_CBC_NO_PADDING, 1) == PSA_SUCCESS, - "compat keeps CBC decryption"); - check(pbkdf2_setup() == PSA_SUCCESS, "compat keeps PBKDF2"); - check(ecc == PSA_SUCCESS, "compat keeps ECC"); -#elif defined(WT_SECURE_PSA_standard) - check(aes_oneshot(PSA_ALG_CCM, 0) == PSA_SUCCESS, "standard keeps CCM"); + "extended keeps CBC decryption"); + check(kdf_setup(PSA_ALG_PBKDF2_HMAC(PSA_ALG_SHA_256)) == PSA_SUCCESS, + "extended keeps PBKDF2"); + check(ecc == PSA_SUCCESS, "extended keeps ECC"); +#elif defined(WT_SECURE_PSA_default) check(aes_oneshot(PSA_ALG_CBC_NO_PADDING, 0) == PSA_ERROR_NOT_SUPPORTED, - "standard compiles out CBC"); - check(pbkdf2_setup() == PSA_ERROR_NOT_SUPPORTED, - "standard compiles out PBKDF2"); - check(ecc == PSA_SUCCESS, "standard keeps ECC"); -#elif defined(WT_SECURE_PSA_lean) - check(aes_oneshot(PSA_ALG_CCM, 0) == PSA_ERROR_NOT_SUPPORTED, - "lean compiles out CCM"); + "default compiles out CBC"); + check(kdf_setup(PSA_ALG_PBKDF2_HMAC(PSA_ALG_SHA_256)) == + PSA_ERROR_NOT_SUPPORTED, "default compiles out PBKDF2"); + check(ecc == PSA_SUCCESS, "default keeps ECC"); +#elif defined(WT_SECURE_PSA_small) check(aes_oneshot(PSA_ALG_ECB_NO_PADDING, 1) == PSA_ERROR_NOT_SUPPORTED, - "lean compiles out AES decryption"); - check(ecc == PSA_SUCCESS, "lean keeps ECC"); -#elif defined(WT_SECURE_PSA_symmetric) - check(aes_oneshot(PSA_ALG_CCM, 0) == PSA_ERROR_NOT_SUPPORTED, - "symmetric compiles out CCM"); - check(ecc == PSA_ERROR_NOT_SUPPORTED, "symmetric compiles out ECC"); + "small compiles out AES decryption"); + check(ecc == PSA_SUCCESS, "small keeps ECC"); +#elif defined(WT_SECURE_PSA_tiny) + check(ecc == PSA_ERROR_NOT_SUPPORTED, "tiny compiles out ECC"); #endif } @@ -224,16 +256,16 @@ static void test_lost_message(void) "a long hash works again after the lost piece"); k = aes_key(PSA_KEY_ID_NULL, 0x77, &st); check(st == PSA_SUCCESS && - psa_aead_encrypt(k, PSA_ALG_GCM, nonce, sizeof(nonce), NULL, 0U, + psa_aead_encrypt(k, WT_TEST_AEAD, nonce, sizeof(nonce), NULL, 0U, big, sizeof(big), ct, sizeof(ct), &len) == - PSA_SUCCESS, "GCM encrypt for the lost-message decrypt"); + PSA_SUCCESS, "AEAD encrypt for the lost-message decrypt"); (void)memset(pt, 0xAA, sizeof(pt)); wt_test_fail_call(7); - check(psa_aead_decrypt(k, PSA_ALG_GCM, nonce, sizeof(nonce), NULL, 0U, + check(psa_aead_decrypt(k, WT_TEST_AEAD, nonce, sizeof(nonce), NULL, 0U, ct, len, pt, sizeof(pt), &len2) == PSA_ERROR_COMMUNICATION_FAILURE && len2 == 0U && pt[0] == 0U && pt[100] == 0U, "a lost piece of a long decrypt leaves no plaintext"); - check(psa_aead_decrypt(k, PSA_ALG_GCM, nonce, sizeof(nonce), NULL, 0U, + check(psa_aead_decrypt(k, WT_TEST_AEAD, nonce, sizeof(nonce), NULL, 0U, ct, len, pt, sizeof(pt), &len2) == PSA_SUCCESS && len2 == sizeof(big) && memcmp(pt, big, sizeof(big)) == 0, "the decrypt works again after the lost piece"); @@ -278,24 +310,24 @@ static void test_large_oneshots(psa_key_id_t k, const uint8_t* nonce) for (i = 0U; i < sizeof(msg); i++) { msg[i] = (uint8_t)(i * 7U); } - check(psa_aead_encrypt(k, PSA_ALG_GCM, nonce, 12U, msg, 700U, msg, + check(psa_aead_encrypt(k, WT_TEST_AEAD, nonce, 12U, msg, 700U, msg, sizeof(msg), ct, sizeof(ct), &len) == PSA_SUCCESS && len == sizeof(msg) + 16U && - psa_aead_decrypt(k, PSA_ALG_GCM, nonce, 12U, msg, 700U, ct, len, pt, + psa_aead_decrypt(k, WT_TEST_AEAD, nonce, 12U, msg, 700U, ct, len, pt, sizeof(pt), &len2) == PSA_SUCCESS && len2 == sizeof(msg) && memcmp(pt, msg, sizeof(msg)) == 0, - "5,000-byte GCM round trip with a 700-byte AD"); - check(psa_aead_encrypt(k, PSA_ALG_GCM, nonce, 12U, msg, 700U, msg, + "5,000-byte AEAD round trip with a 700-byte AD"); + check(psa_aead_encrypt(k, WT_TEST_AEAD, nonce, 12U, msg, 700U, msg, sizeof(msg), ct, sizeof(msg), &len) == PSA_ERROR_BUFFER_TOO_SMALL && len == 0U, - "a long GCM encrypt with no room for the tag fails"); + "a long AEAD encrypt with no room for the tag fails"); ct[sizeof(msg) - 1U] ^= 1U; (void)memset(pt, 0xAA, sizeof(pt)); - check(psa_aead_decrypt(k, PSA_ALG_GCM, nonce, 12U, msg, 700U, ct, + check(psa_aead_decrypt(k, WT_TEST_AEAD, nonce, 12U, msg, 700U, ct, sizeof(msg) + 16U, pt, sizeof(pt), &len2) == PSA_ERROR_INVALID_SIGNATURE && len2 == 0U && pt[0] == 0U && pt[sizeof(pt) - 1U] == 0U, - "a long GCM decrypt with a bad tag leaves no plaintext"); + "a long AEAD decrypt with a bad tag leaves no plaintext"); check(psa_hash_compute(PSA_ALG_SHA_256, msg, sizeof(msg), hash, sizeof(hash), &len) == PSA_SUCCESS && psa_hash_setup(&op, PSA_ALG_SHA_256) == PSA_SUCCESS && @@ -335,7 +367,7 @@ static void test_arena_isolation(void) k = aes_key(PSA_KEY_ID_NULL, 0x24, &st); for (nops = 0U; st == PSA_SUCCESS && nops < 8U; nops++) { ops[nops] = psa_aead_operation_init(); - st = psa_aead_encrypt_setup(&ops[nops], k, PSA_ALG_GCM); + st = psa_aead_encrypt_setup(&ops[nops], k, WT_TEST_AEAD); if (st == PSA_SUCCESS) { st = psa_aead_set_nonce(&ops[nops], nonce, sizeof(nonce)); } @@ -352,10 +384,10 @@ static void test_arena_isolation(void) wt_test_set_client(GUEST1); k = aes_key(PSA_KEY_ID_NULL, 0x26, &st); check(st == PSA_SUCCESS && - psa_aead_encrypt(k, PSA_ALG_GCM, nonce, sizeof(nonce), msg, 300U, + psa_aead_encrypt(k, WT_TEST_AEAD, nonce, sizeof(nonce), msg, 300U, msg, sizeof(msg), ct, sizeof(ct), &len) == PSA_SUCCESS && len == sizeof(msg) + 16U, - "guest1 runs a long GCM while guest0 holds everything it can"); + "guest1 runs a long AEAD while guest0 holds everything it can"); (void)psa_destroy_key(k); wt_test_set_client(GUEST0); @@ -365,7 +397,7 @@ static void test_arena_isolation(void) check(raw_init() == PSA_SUCCESS, "guest0 restarts and drops its state"); k = aes_key(PSA_KEY_ID_NULL, 0x27, &st); check(st == PSA_SUCCESS && - psa_aead_encrypt(k, PSA_ALG_GCM, nonce, sizeof(nonce), NULL, 0U, + psa_aead_encrypt(k, WT_TEST_AEAD, nonce, sizeof(nonce), NULL, 0U, msg, sizeof(msg), ct, sizeof(ct), &len) == PSA_SUCCESS, "guest0's arena is whole again after its restart"); (void)psa_destroy_key(k); @@ -423,25 +455,25 @@ static void test_basic(void) check(psa_get_key_attributes(k, &attr) == PSA_SUCCESS && psa_get_key_type(&attr) == PSA_KEY_TYPE_AES && psa_get_key_bits(&attr) == 128U, "get_key_attributes of the new key"); - st = psa_aead_encrypt(k, PSA_ALG_GCM, nonce, sizeof(nonce), big, 20U, big, + st = psa_aead_encrypt(k, WT_TEST_AEAD, nonce, sizeof(nonce), big, 20U, big, sizeof(big), ct, sizeof(ct), &len); check(st == PSA_SUCCESS && len == sizeof(big) + 16U, - "GCM encrypt of 1500 bytes"); - st = psa_aead_decrypt(k, PSA_ALG_GCM, nonce, sizeof(nonce), big, 20U, ct, + "AEAD encrypt of 1500 bytes"); + st = psa_aead_decrypt(k, WT_TEST_AEAD, nonce, sizeof(nonce), big, 20U, ct, len, pt, sizeof(pt), &len2); check(st == PSA_SUCCESS && len2 == sizeof(big) && - memcmp(pt, big, sizeof(big)) == 0, "GCM decrypt round trip"); + memcmp(pt, big, sizeof(big)) == 0, "AEAD decrypt round trip"); ct[5] ^= 1U; (void)memset(pt, 0xAA, sizeof(pt)); - st = psa_aead_decrypt(k, PSA_ALG_GCM, nonce, sizeof(nonce), big, 20U, ct, + st = psa_aead_decrypt(k, WT_TEST_AEAD, nonce, sizeof(nonce), big, 20U, ct, len, pt, sizeof(pt), &len2); check(st == PSA_ERROR_INVALID_SIGNATURE && len2 == 0U && pt[0] == 0U && pt[100] == 0U && pt[sizeof(pt) - 1U] == 0U, - "GCM bad tag fails and releases no plaintext"); + "AEAD bad tag fails and releases no plaintext"); test_large_oneshots(k, nonce); check(psa_destroy_key(k) == PSA_SUCCESS, "destroy volatile key"); -#ifndef WT_SECURE_PSA_symmetric +#ifndef WT_SECURE_PSA_tiny k = ecc_key(&st); check(st == PSA_SUCCESS, "generate P-256 key in Secure"); st = psa_sign_hash(k, PSA_ALG_ECDSA(PSA_ALG_SHA_256), hash, sizeof(hash), @@ -544,6 +576,109 @@ static void test_isolation(void) "the native key wire cannot create in the PSA uid range"); } +static void refused(psa_status_t st, const char* what) +{ + check(st == PSA_ERROR_INVALID_HANDLE, what); +} + +/* Every wire call that names a key, from the client that does not own it */ +static void test_foreign_key(void) +{ + psa_key_attributes_t attr = psa_key_attributes_init(); + psa_mac_operation_t mop = PSA_MAC_OPERATION_INIT; + psa_cipher_operation_t cop = PSA_CIPHER_OPERATION_INIT; + psa_aead_operation_t aop = PSA_AEAD_OPERATION_INIT; + psa_key_derivation_operation_t kop = PSA_KEY_DERIVATION_OPERATION_INIT; + const psa_algorithm_t hmac = PSA_ALG_HMAC(PSA_ALG_SHA_256); + uint8_t in[32]; + uint8_t out[80]; + uint8_t nonce[13]; + psa_key_id_t k; + psa_key_id_t id = PSA_KEY_ID_NULL; + psa_status_t st; + size_t len = 0U; + + (void)memset(in, 0x3C, sizeof(in)); + (void)memset(out, 0x5A, sizeof(out)); + (void)memset(nonce, 0x11, sizeof(nonce)); + wt_test_set_client(GUEST0); + k = aes_key(PSA_KEY_ID_NULL, 0x44, &st); + check(st == PSA_SUCCESS, "guest0 imports the key guest1 will name"); + + wt_test_set_client(GUEST1); + refused(psa_get_key_attributes(k, &attr), "foreign key: get attributes"); + refused(psa_export_public_key(k, out, sizeof(out), &len), + "foreign key: export public key"); + refused(psa_purge_key(k), "foreign key: purge"); + psa_set_key_usage_flags(&attr, PSA_KEY_USAGE_EXPORT); + refused(psa_copy_key(k, &attr, &id), "foreign key: copy"); + refused(psa_mac_compute(k, hmac, in, 16U, out, sizeof(out), &len), + "foreign key: MAC compute"); + refused(psa_mac_verify(k, hmac, in, 16U, in, 32U), + "foreign key: MAC verify"); + refused(psa_mac_sign_setup(&mop, k, hmac), "foreign key: MAC sign setup"); + (void)psa_mac_abort(&mop); + refused(psa_mac_verify_setup(&mop, k, hmac), + "foreign key: MAC verify setup"); + (void)psa_mac_abort(&mop); + refused(psa_cipher_encrypt(k, PSA_ALG_ECB_NO_PADDING, in, 16U, out, + sizeof(out), &len), "foreign key: cipher encrypt"); + refused(psa_cipher_decrypt(k, PSA_ALG_ECB_NO_PADDING, in, 16U, out, + sizeof(out), &len), "foreign key: cipher decrypt"); + refused(psa_cipher_encrypt_setup(&cop, k, PSA_ALG_ECB_NO_PADDING), + "foreign key: cipher encrypt setup"); + (void)psa_cipher_abort(&cop); + refused(psa_cipher_decrypt_setup(&cop, k, PSA_ALG_ECB_NO_PADDING), + "foreign key: cipher decrypt setup"); + (void)psa_cipher_abort(&cop); + refused(psa_aead_encrypt(k, WT_TEST_AEAD, nonce, 12U, in, 8U, in, 16U, out, + sizeof(out), &len), "foreign key: AEAD encrypt"); + refused(psa_aead_decrypt(k, WT_TEST_AEAD, nonce, 12U, in, 8U, in, 32U, out, + sizeof(out), &len), "foreign key: AEAD decrypt"); + refused(psa_aead_encrypt_setup(&aop, k, WT_TEST_AEAD), + "foreign key: AEAD encrypt setup"); + (void)psa_aead_abort(&aop); + refused(psa_aead_decrypt_setup(&aop, k, WT_TEST_AEAD), + "foreign key: AEAD decrypt setup"); + (void)psa_aead_abort(&aop); + if (psa_key_derivation_setup(&kop, PSA_ALG_HKDF(PSA_ALG_SHA_256)) == + PSA_SUCCESS) { + refused(psa_key_derivation_input_key(&kop, + PSA_KEY_DERIVATION_INPUT_SECRET, k), "foreign key: KDF input"); + refused(psa_key_derivation_verify_key(&kop, k), + "foreign key: KDF verify key"); +#ifndef WT_SECURE_PSA_tiny + refused(psa_key_derivation_key_agreement(&kop, + PSA_KEY_DERIVATION_INPUT_SECRET, k, out, 65U), + "foreign key: KDF key agreement"); +#endif + (void)psa_key_derivation_abort(&kop); + } +#ifndef WT_SECURE_PSA_tiny + refused(psa_sign_hash(k, PSA_ALG_ECDSA(PSA_ALG_SHA_256), in, 32U, out, + sizeof(out), &len), "foreign key: sign hash"); + refused(psa_verify_hash(k, PSA_ALG_ECDSA(PSA_ALG_SHA_256), in, 32U, out, + 64U), "foreign key: verify hash"); + refused(psa_sign_message(k, PSA_ALG_ECDSA(PSA_ALG_SHA_256), in, 16U, out, + sizeof(out), &len), "foreign key: sign message"); + refused(psa_verify_message(k, PSA_ALG_ECDSA(PSA_ALG_SHA_256), in, 16U, out, + 64U), "foreign key: verify message"); + refused(psa_asymmetric_encrypt(k, PSA_ALG_RSA_PKCS1V15_CRYPT, in, 16U, + NULL, 0U, out, sizeof(out), &len), + "foreign key: asymmetric encrypt"); + refused(psa_asymmetric_decrypt(k, PSA_ALG_RSA_PKCS1V15_CRYPT, in, 16U, + NULL, 0U, out, sizeof(out), &len), + "foreign key: asymmetric decrypt"); + refused(psa_raw_key_agreement(PSA_ALG_ECDH, k, out, 65U, in, sizeof(in), + &len), "foreign key: raw key agreement"); + refused(psa_key_agreement(k, out, 65U, PSA_ALG_ECDH, &attr, &id), + "foreign key: key agreement"); +#endif + + wt_test_set_client(GUEST0); + check(psa_destroy_key(k) == PSA_SUCCESS, "guest0 still owns the key"); +} + static void test_quota_and_reset(void) { psa_key_id_t keys[10]; @@ -650,18 +785,68 @@ static void test_token_exhaustion(void) "a service restart gives guest0 fresh slots"); } +/* The vault's AES-256 key ops run its AEAD, which is wolfPSA's streaming CCM + * when WT_AEAD_CCM builds with WT_SECURE_PSA. */ +static void test_vault_aead(void) +{ + static const uint8_t msg[] = "vault AEAD in the Secure PSA image"; + wt_crypto_wire_req_t hdr; + uint8_t ct[sizeof(msg) + WT_VAULT_KEY_NONCE_LEN + WT_VAULT_KEY_TAG_LEN]; + uint8_t pt[sizeof(msg)]; + size_t ct_len = 0U; + size_t pt_len = 0U; + psa_status_t st; + int ok; + + (void)memset(&hdr, 0, sizeof(hdr)); + hdr.uid = 0x3001ULL; + hdr.op = WT_CRYPTO_OP_KEY_GENERATE; + hdr.usage = WT_VAULT_KEY_USAGE_ENCRYPT | WT_VAULT_KEY_USAGE_DECRYPT; + hdr.key_type = WT_VAULT_KEY_AES256; + st = wt_crypto_native_call(&hdr, NULL, 0U, NULL, 0U, &pt_len); + check(st == PSA_SUCCESS, "vault AES-256 key generates"); + + hdr.usage = 0U; + hdr.key_type = 0U; + hdr.op = WT_CRYPTO_OP_KEY_ENCRYPT; + st = wt_crypto_native_call(&hdr, msg, sizeof(msg), ct, sizeof(ct), + &ct_len); + ok = (st == PSA_SUCCESS && ct_len == sizeof(ct)); + check(ok, "vault encrypt frames nonce || ciphertext || tag"); + hdr.op = WT_CRYPTO_OP_KEY_DECRYPT; + if (!ok) { + hdr.op = WT_CRYPTO_OP_KEY_DESTROY; + (void)wt_crypto_native_call(&hdr, NULL, 0U, NULL, 0U, &pt_len); + return; + } + st = wt_crypto_native_call(&hdr, ct, ct_len, pt, sizeof(pt), &pt_len); + check(st == PSA_SUCCESS && pt_len == sizeof(msg) && + memcmp(pt, msg, sizeof(msg)) == 0, + "vault decrypt recovers the plaintext"); + ct[ct_len - 1U] ^= 0x01U; + pt_len = 1U; + st = wt_crypto_native_call(&hdr, ct, ct_len, pt, sizeof(pt), &pt_len); + check(st == PSA_ERROR_INVALID_SIGNATURE && pt_len == 0U, + "vault decrypt rejects a tampered tag and returns no plaintext"); + hdr.op = WT_CRYPTO_OP_KEY_DESTROY; + check(wt_crypto_native_call(&hdr, NULL, 0U, NULL, 0U, &pt_len) == + PSA_SUCCESS, "vault AES-256 key destroys"); +} + int main(void) { wt_test_set_client(GUEST0); test_basic(); test_profile(); test_isolation(); + test_foreign_key(); test_quota_and_reset(); test_service_restart(); test_token_exhaustion(); test_lost_message(); test_malformed_reply(); test_arena_isolation(); + test_vault_aead(); (void)printf("%s: %d failure(s)\n", g_failures ? "FAIL" : "PASS", g_failures); return g_failures ? 1 : 0; diff --git a/tests/host/psa_secure_crypto/user_settings.h b/tests/host/psa_secure_crypto/user_settings.h index e9c7ef6b5..c1ae3ed1b 100644 --- a/tests/host/psa_secure_crypto/user_settings.h +++ b/tests/host/psa_secure_crypto/user_settings.h @@ -57,6 +57,11 @@ #define NO_MAIN_DRIVER #define NO_ERROR_STRINGS +/* Profiles other than extended run P-256 on wolfPSA's direct path over small SP */ +#ifndef WT_SECURE_PSA_extended +#define WOLFSSL_HAVE_SP_ECC +#define WOLFSSL_SP_SMALL +#endif #include "../../../src/services/wolfhsm/runner/secure_psa_profile.h" #endif /* USER_SETTINGS_H */ diff --git a/tests/host/psa_secure_crypto/want_check.c b/tests/host/psa_secure_crypto/want_check.c index 7ed876754..b504f128a 100644 --- a/tests/host/psa_secure_crypto/want_check.c +++ b/tests/host/psa_secure_crypto/want_check.c @@ -22,41 +22,50 @@ * PSA_WANT_* surface its service implements. */ #include "psa/crypto.h" -#if !defined(PSA_WANT_ALG_GCM) || !defined(PSA_WANT_ALG_HKDF) || \ - !defined(PSA_WANT_ALG_HMAC) || !defined(PSA_WANT_ALG_SHA_256) -#error "every profile advertises GCM, HKDF, HMAC and SHA-256" +#if !defined(PSA_WANT_ALG_HKDF) || !defined(PSA_WANT_ALG_HMAC) || \ + !defined(PSA_WANT_ALG_SHA_256) +#error "every profile advertises HKDF, HMAC and SHA-256" #endif -#ifdef WT_SECURE_PSA_symmetric +#ifdef WT_SECURE_PSA_tiny #if defined(PSA_WANT_ALG_ECDSA) || defined(PSA_WANT_ALG_ECDH) || \ defined(PSA_WANT_ALG_DETERMINISTIC_ECDSA) || \ defined(PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY) || \ defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_BASIC) || \ defined(PSA_WANT_ECC_SECP_R1_256) -#error "symmetric advertises ECC" +#error "tiny advertises ECC" #endif #elif !defined(PSA_WANT_ALG_ECDSA) || !defined(PSA_WANT_ALG_ECDH) || \ !defined(PSA_WANT_ECC_SECP_R1_256) #error "the ECC profiles advertise P-256 ECDSA and ECDH" #endif -#if defined(WT_SECURE_PSA_lean) || defined(WT_SECURE_PSA_symmetric) -#ifdef PSA_WANT_ALG_CCM -#error "lean and symmetric advertise CCM" +#if defined(WT_SECURE_PSA_small) || defined(WT_SECURE_PSA_tiny) +#ifdef WT_AEAD_GCM +#if !defined(PSA_WANT_ALG_GCM) || defined(PSA_WANT_ALG_CCM) +#error "small and tiny with WT_AEAD=gcm advertise GCM and not CCM" #endif -#elif !defined(PSA_WANT_ALG_CCM) -#error "compat and standard advertise CCM" +#elif !defined(PSA_WANT_ALG_CCM) || defined(PSA_WANT_ALG_GCM) +#error "small and tiny advertise CCM and not GCM" +#endif +#elif !defined(PSA_WANT_ALG_GCM) || !defined(PSA_WANT_ALG_CCM) +#error "extended and default advertise GCM and CCM" #endif -#ifdef WT_SECURE_PSA_compat +#ifdef WT_SECURE_PSA_extended #if !defined(PSA_WANT_ALG_PBKDF2_HMAC) || !defined(PSA_WANT_ALG_CBC_NO_PADDING) || \ !defined(PSA_WANT_ALG_TLS12_PRF) || \ + !defined(PSA_WANT_ALG_SP800_108_COUNTER_HMAC) || \ + !defined(PSA_WANT_ALG_CCM_STAR_NO_TAG) || \ !defined(PSA_WANT_ALG_DETERMINISTIC_ECDSA) -#error "compat advertises PBKDF2, CBC, TLS 1.2 PRF and deterministic ECDSA" +#error "extended advertises PBKDF2, CBC, TLS 1.2 PRF, SP 800-108, CCM* and deterministic ECDSA" #endif #elif defined(PSA_WANT_ALG_PBKDF2_HMAC) || defined(PSA_WANT_ALG_CBC_NO_PADDING) || \ - defined(PSA_WANT_ALG_TLS12_PRF) -#error "only compat advertises PBKDF2, CBC and TLS 1.2 PRF" + defined(PSA_WANT_ALG_TLS12_PRF) || \ + defined(PSA_WANT_ALG_SP800_108_COUNTER_HMAC) || \ + defined(PSA_WANT_ALG_SP800_108_COUNTER_CMAC) || \ + defined(PSA_WANT_ALG_CCM_STAR_NO_TAG) +#error "only extended advertises PBKDF2, CBC, TLS 1.2 PRF, SP 800-108 and CCM*" #endif typedef int wt_want_check_t; diff --git a/tests/host/psa_storage_client/Makefile b/tests/host/psa_storage_client/Makefile index 8442e4dca..d4edd8cad 100644 --- a/tests/host/psa_storage_client/Makefile +++ b/tests/host/psa_storage_client/Makefile @@ -46,7 +46,8 @@ _WT_SRCS := \ $(ROOT)/src/services/storage_service.c \ $(ROOT)/src/services/vault_service.c \ $(ROOT)/src/services/wolfhsm/wt_hsm_vault.c \ - $(ROOT)/src/services/wolfhsm/wt_hsm_seal.c + $(ROOT)/src/services/wolfhsm/wt_hsm_seal.c \ + $(ROOT)/src/services/wolfhsm/wt_hsm_aead.c _CLIENT_SRCS := \ $(ROOT)/src/client/psa_ffm_client.c \ diff --git a/tests/host/psa_storage_client/main.c b/tests/host/psa_storage_client/main.c index 5a4b401ff..7401272ab 100644 --- a/tests/host/psa_storage_client/main.c +++ b/tests/host/psa_storage_client/main.c @@ -280,7 +280,7 @@ int main(void) return 1; } wt_vault_service_set_backend(&wt_hsm_vault_backend); - /* PS seals every object; bind the AES-GCM sealer over the same NVM. */ + /* PS seals every object; bind the AEAD sealer over the same NVM. */ if (wt_hsm_seal_init(&nvm_ctx) != 0) { (void)fprintf(stderr, "wt_hsm_seal_init failed\n"); return 1; diff --git a/tests/host/psa_storage_client/user_settings.h b/tests/host/psa_storage_client/user_settings.h index f93c277b8..4363ac4fe 100644 --- a/tests/host/psa_storage_client/user_settings.h +++ b/tests/host/psa_storage_client/user_settings.h @@ -31,6 +31,9 @@ #define NO_TLS #define HAVE_AESGCM +#ifdef WT_AEAD_CCM +#define HAVE_AESCCM +#endif #define WOLFSSL_SHA256 #define HAVE_HASHDRBG diff --git a/tests/scripts/test_scenario_asserts.py b/tests/scripts/test_scenario_asserts.py index d25f121bf..2fb93a961 100644 --- a/tests/scripts/test_scenario_asserts.py +++ b/tests/scripts/test_scenario_asserts.py @@ -452,7 +452,7 @@ def main(): display = scenario_matrix.PORTS[port]["def"]["display"] tiers = scenarios.hardware_tiers(port) hardware = sorted(set(tiers["qualification"]) | set(tiers["optin"])) - runs = [(s, "emulator") for s in scenario_matrix.flat(port, "full", None)] + runs = [(s, "emulator") for s in scenario_matrix.flat(port, "all", None)] runs += [(s, "hardware") for s in hardware] for scenario, env in runs: row = scenarios.SCENARIOS[scenario] diff --git a/tests/target/lib/profile.sh b/tests/target/lib/profile.sh index 90bbd8d0e..7a411a32b 100644 --- a/tests/target/lib/profile.sh +++ b/tests/target/lib/profile.sh @@ -18,20 +18,22 @@ # You should have received a copy of the GNU General Public License # along with this program; if not, see . -# Build profiles every target runner puts ahead of its scenario's probe flags. -# "default" is the lean image `make` builds with no options; "full" turns -# every add-on back on. POSIX sh; source it, do not execute it. +# Build profiles every target runner puts ahead of its scenario's probe flags: +# tiny, small, default (the image `make` builds with no options) or extended +# (every add-on). mk/profile.mk holds the same table for the build itself. +# POSIX sh; source it, do not execute it. -# The add-on variables a profile owns, cleared before a profile is applied so -# the caller's environment never leaks into a run. -SCENARIO_PROFILE_VARS="WT_MAX_GUESTS WT_MANIFEST_RUNTIME_CHECK WT_FWU WT_SHA256_FAST" +# The variables a profile owns, cleared before a profile is applied so the +# caller's environment never leaks into a run. +SCENARIO_PROFILE_VARS="WT_PROFILE WT_SECURE_PSA_PROFILE WT_MAX_GUESTS \ +WT_MANIFEST_RUNTIME_CHECK WT_FWU WT_SHA256_FAST WT_ATTEST_KEY WT_VAULT_ECC" scenario_profile_flags() { case "$1" in - default) echo "" ;; - full) echo "WT_MAX_GUESTS=2 WT_MANIFEST_RUNTIME_CHECK=1 WT_FWU=1 WT_SHA256_FAST=1" ;; + tiny|small|default) echo "WT_PROFILE=$1" ;; + extended) echo "WT_PROFILE=extended WT_MAX_GUESTS=2 WT_MANIFEST_RUNTIME_CHECK=1 WT_FWU=1 WT_SHA256_FAST=1" ;; *) - echo "unknown build profile '$1' (want default or full)" >&2 + echo "unknown build profile '$1' (want tiny, small, default or extended)" >&2 return 1 ;; esac @@ -40,8 +42,8 @@ scenario_profile_flags() { # Guests the profile's Secure image schedules. scenario_profile_guests() { case "$1" in - full) echo 2 ;; - *) echo 1 ;; + extended) echo 2 ;; + *) echo 1 ;; esac } diff --git a/tests/target/lib/scenario.sh b/tests/target/lib/scenario.sh index 53e243cab..88a67f1ad 100644 --- a/tests/target/lib/scenario.sh +++ b/tests/target/lib/scenario.sh @@ -23,7 +23,7 @@ expect_n_re() { local n; n="$(count_re "$3")"; \ . "$(dirname "${BASH_SOURCE[0]}")/profile.sh" # The profile scenario $2 of port $1 builds with: WT_PROFILE when the matrix -# registers it there, otherwise full when it runs there, otherwise its only +# registers it there, otherwise extended when it runs there, otherwise its only # profile. scenario_profile() { python3 "$(dirname "${BASH_SOURCE[0]}")/scenario_matrix.py" \ diff --git a/tests/target/lib/scenario_matrix.py b/tests/target/lib/scenario_matrix.py index e2f412633..f44b20f8d 100755 --- a/tests/target/lib/scenario_matrix.py +++ b/tests/target/lib/scenario_matrix.py @@ -29,17 +29,17 @@ GITHUB_EVENT_NAME=pull_request PR_LABELS="ci:" scenario_matrix.py --ci-plan scenario_matrix.py --port --tier smoke --json - scenario_matrix.py --port --tier full --engine native --flat + scenario_matrix.py --port --tier all --engine native --flat scenario_matrix.py --port --get ci.mcuxsdk_board scenario_matrix.py --build-plan WT_PROFILE=default scenario_matrix.py --port --profile-of positive -Every group also names the build profile its Secure image is built with: -"full" turns every add-on on (tests/target/lib/profile.sh holds the flags), -"default" is the lean image the Makefile builds with no options. A port's -m33mu "smoke" and "groups" are its full profile; m33mu "default" holds the -same two lists for the lean image. A runner asks --profile-of which profile a -scenario runs on. +Every group also names the build profile (WT_PROFILE) its Secure image is +built with: "extended" turns every add-on on (tests/target/lib/profile.sh and +mk/profile.mk hold the flags), "default" is the image the Makefile builds with +no options. A port's m33mu "smoke" and "groups" are its extended profile; +m33mu "default" holds the same two lists for the default image. A runner asks +--profile-of which profile a scenario runs on. """ import argparse @@ -48,11 +48,11 @@ import sys ENGINES = ("native", "hsm") -PROFILES = ("default", "full") +PROFILES = ("default", "extended") -# Scenarios that need a second guest or an add-on the lean default leaves -# out; they never run on the default profile. -NEEDS_FULL = frozenset(( +# Scenarios that need a second guest or an add-on the default profile leaves +# out; they never run on it. +NEEDS_EXTENDED = frozenset(( "restart", "sauneg", "ahbscneg", "gtzcneg", "guestisoneg", "bothpsa", "bothiso", "fwustage", "bootupdate", "confboot", "devstorage", "devcrypto", "devattest", "devattestqcbor", "vaultrecover", @@ -63,10 +63,11 @@ # engine: the native engine does not link it, so the behaviour under test does # not exist there. HSM_ONLY = frozenset(("hsmattackneg", "hsmpinneg", "hsmfaultneg", "hsmrestartneg")) -NATIVE_ONLY = frozenset(("nativewire", "nativewireasm", "devcryptolocal")) +NATIVE_ONLY = frozenset(("nativewire", "nativewireasm", "nativewiresmall", "devcryptolocal", + "tinyattest")) ENGINE_ONLY = {"hsm": HSM_ONLY, "native": NATIVE_ONLY} -# The isolation level 3 bar: every port's full tier runs each of these, or +# The isolation level 3 bar: every port's all tier runs each of these, or # names it in its "l3_exempt" map with the reason (an open issue) it cannot. L3_REQUIRED = frozenset(( "crossdomain", "keystoreneg", "deputyneg", "hsmpinneg", "hsmfaultneg", @@ -87,7 +88,7 @@ def load_ports(root=PORT_ROOT): """Every port//port.json, keyed by port name; a port directory with no registry entry is an error, so nothing exists unregistered. - smoke: the per-PR set (one job per scenario and engine). groups: the full + smoke: the per-PR set (one job per scenario and engine). groups: the all tier, packed so each job builds the emulator and wolfBoot once. label_only: an unlabeled pull request runs none of this port.""" ports = {} @@ -104,20 +105,20 @@ def load_ports(root=PORT_ROOT): raise SystemExit("port/%s/port.json: name mismatch or missing %s" % (name, " ".join(missing))) m33mu = data["m33mu"] - lean = m33mu.get("default", {}) + base = m33mu.get("default", {}) ports[name] = { "label": data["ci"]["label"], "label_only": bool(data["ci"].get("label_only", False)), "image": data["ci"]["image"], "arm": m33mu["arm"], - "smoke": {"full": tuple(m33mu["smoke"]), - "default": tuple(lean.get("smoke", []))}, - "groups": {"full": tuple((key, text) + "smoke": {"extended": tuple(m33mu["smoke"]), + "default": tuple(base.get("smoke", []))}, + "groups": {"extended": tuple((key, text) for key, text in m33mu["groups"]), "default": tuple((key, text) for key, text in - lean.get("groups", []))}, - "l3_exempt": {"full": dict(m33mu.get("l3_exempt", {})), - "default": dict(lean.get("l3_exempt", {}))}, + base.get("groups", []))}, + "l3_exempt": {"extended": dict(m33mu.get("l3_exempt", {})), + "default": dict(base.get("l3_exempt", {}))}, "def": data, } return ports @@ -144,8 +145,8 @@ def engines_for(scenarios, engine, port_engines=ENGINES): def entry(port, tier, engine, profile, key, name): port_def = PORTS[port] - # Check names follow wolfBoot's _ slugs; the lean profile's - # jobs carry "default" so a scenario's two runs never share a name. + # Check names follow wolfBoot's _ slugs; the default + # profile's jobs carry "default" so a scenario's two runs never share a name. words = [port] + key.split() if profile == "default": words.append("default") @@ -177,9 +178,9 @@ def entries(port, tier, engine, profile=None): def ci_plan(event, labels, port_input): """Every job of one workflow run: a pull request gets each port's smoke - tier unless its label (or ci:all) asks for the full one, and a label_only + tier unless its label (or ci:all) asks for the all tier, and a label_only port runs only when labelled; a push, the schedule, or a dispatch gets the - full tier of the selected ports. Each tier runs on both profiles.""" + all tier of the selected ports. Each tier runs on both profiles.""" out = [] if (event == "workflow_dispatch" and port_input not in ("", "all") and port_input not in PORTS): @@ -188,17 +189,17 @@ def ci_plan(event, labels, port_input): for port in sorted(PORTS): label = PORTS[port]["label"] if event == "pull_request": - full = ("ci:all" in labels or "ci:m33mu" in labels or - label in labels) - if not full and PORTS[port].get("label_only"): + whole = ("ci:all" in labels or "ci:m33mu" in labels or + label in labels) + if not whole and PORTS[port].get("label_only"): continue elif event == "workflow_dispatch": - full = port_input in ("", "all", port) - if not full: + whole = port_input in ("", "all", port) + if not whole: continue else: - full = True - out.extend(entries(port, "full" if full else "smoke", None)) + whole = True + out.extend(entries(port, "all" if whole else "smoke", None)) return out @@ -244,21 +245,21 @@ def plan_tiers(event, labels, port_input): def routing_gaps(): """The routing rule as properties over the registry: an unlabeled pull request runs every always-on port at smoke; a port's label runs that port - full and the rest as unlabeled; ci:all, ci:m33mu, a push, the schedule and - a dispatch with no port run every port full; a dispatch names one port; + at all and the rest as unlabeled; ci:all, ci:m33mu, a push, the schedule + and a dispatch with no port run every port at all; a dispatch names one port; an unknown dispatch port is refused.""" ports = sorted(PORTS) always = dict((p, "smoke") for p in ports if not PORTS[p]["label_only"]) - everything = dict((p, "full") for p in ports) + everything = dict((p, "all") for p in ports) checks = [("pull_request", [], "", always)] for port in ports: want = dict(always) - want[port] = "full" + want[port] = "all" checks.append(("pull_request", [PORTS[port]["label"]], "", want)) if len(ports) > 1: want = dict(always) - want[ports[0]] = "full" - want[ports[1]] = "full" + want[ports[0]] = "all" + want[ports[1]] = "all" checks.append(("pull_request", [PORTS[ports[0]]["label"], PORTS[ports[1]]["label"]], "", want)) @@ -269,7 +270,7 @@ def routing_gaps(): for port_input in ("", "all"): checks.append(("workflow_dispatch", [], port_input, everything)) for port in ports: - checks.append(("workflow_dispatch", [], port, {port: "full"})) + checks.append(("workflow_dispatch", [], port, {port: "all"})) gaps = [] for event, labels, port_input, want in checks: got = plan_tiers(event, labels, port_input) @@ -295,7 +296,7 @@ def registry_gaps(): """A registered port has its build fragment, its guide and its shared architecture layer, no copy of a shared source, a unique CI label and runner arm, a usable image, known engines, and a smoke set drawn from its - full tier.""" + all tier.""" gaps = [] labels = {} arms = {} @@ -324,15 +325,15 @@ def registry_gaps(): if not PORTS[port]["image"]: gaps.append("%s: empty image" % port) for prof in PROFILES: - full = set(flat(port, "full", None, prof)) + whole = set(flat(port, "all", None, prof)) for scenario in PORTS[port]["smoke"][prof]: - if scenario not in full: + if scenario not in whole: gaps.append("%s: %s smoke scenario %s is not in its " - "full tier" % (port, prof, scenario)) + "all tier" % (port, prof, scenario)) if not PORTS[port]["groups"][prof]: gaps.append("%s: no %s profile scenarios" % (port, prof)) - for scenario in flat(port, "full", None, "default"): - if scenario in NEEDS_FULL: + for scenario in flat(port, "all", None, "default"): + if scenario in NEEDS_EXTENDED: gaps.append("%s runs %s on the default profile" % (port, scenario)) engines = data["build"].get("engines", []) @@ -342,21 +343,21 @@ def registry_gaps(): def profiles_of(port, scenario): - """The profiles whose full tier registers scenario.""" + """The profiles whose all tier registers scenario.""" return [prof for prof in PROFILES - if scenario in flat(port, "full", None, prof)] + if scenario in flat(port, "all", None, prof)] def profile_of(port, scenario, requested): """The profile a runner builds scenario with: the requested one when the - scenario is registered there, else full when it runs there, else its only + scenario is registered there, else extended when it runs there, else its only profile. None when the scenario cannot run as asked.""" found = profiles_of(port, scenario) if requested: return requested if requested in found else None if not found: return None - return "full" if "full" in found else found[0] + return "extended" if "extended" in found else found[0] def l3_gaps(port): @@ -367,7 +368,7 @@ def l3_gaps(port): gaps = [] for prof in PROFILES: exempt = port_def["l3_exempt"][prof] - run = set(flat(port, "full", None, prof)) + run = set(flat(port, "all", None, prof)) for scenario in sorted(L3_REQUIRED): if scenario not in run and not exempt.get(scenario, "").strip(): gaps.append("%s does not run level 3 scenario %s on %s" % @@ -397,11 +398,11 @@ def profile_gaps(): gaps.append("ci_plan(%s) runs %s on %s only" % (event, port, " ".join(got))) for port in sorted(PORTS): - for scenario in flat(port, "full", None, "default"): + for scenario in flat(port, "all", None, "default"): if profile_of(port, scenario, "default") != "default": gaps.append("%s: %s does not resolve to default" % (port, scenario)) - for scenario in NEEDS_FULL: + for scenario in NEEDS_EXTENDED: if profile_of(port, scenario, "default") is not None: gaps.append("%s: %s resolves to the default profile" % (port, scenario)) @@ -415,7 +416,7 @@ def selftest(): bar, run by the select job and by make test.""" gaps = registry_gaps() + routing_gaps() + profile_gaps() for port in sorted(PORTS): - for tier in ("smoke", "full"): + for tier in ("smoke", "all"): for e in entries(port, tier, None): names = e["key"].split() for only, restricted in ENGINE_ONLY.items(): @@ -443,7 +444,7 @@ def flat(port, tier, engine, profile=None): def main(): parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) parser.add_argument("--port", choices=sorted(PORTS)) - parser.add_argument("--tier", choices=("smoke", "full"), default="smoke") + parser.add_argument("--tier", choices=("smoke", "all"), default="smoke") parser.add_argument("--engine", choices=ENGINES) parser.add_argument("--profile", choices=PROFILES, help="only this build profile's scenarios") diff --git a/tests/target/lib/scenarios.py b/tests/target/lib/scenarios.py index 67640a3de..7e27e603c 100644 --- a/tests/target/lib/scenarios.py +++ b/tests/target/lib/scenarios.py @@ -204,6 +204,12 @@ def S(secure="", role="lifecycle", guest_flags="", end="guest", timeout=None, hw_blocks=("hw_no_escalation", "hw_devattest"), hw_secure="WT_CONF_DIAG_TRAP=0"), "attestneg": S(role="psa", guest_flags="WT_ATTEST_NEG_PROBE=1", blocks=("psa_lifecycle", "attestneg")), + # tiny with no ECC: the attestation partition restarts on a reset band, + # reloads its HMAC key, and the guest verifies the COSE_Mac0 it issues. + "tinyattest": S(secure="WT_PROFILE=tiny WT_SECURE_PSA=1 WT_RESTART_NEG_PROBE=2", role="hwpsa", + guest_flags=SP_PROBE_FLAGS, end="bkpt:0x7f", quit_on_faults=False, + engines=("native",), level3=True, + blocks=("psa_probe_lifecycle", "l3", "tinyattest")), "nativewire": S(role="hwpsa", guest_flags="WT_NATIVE_WIRE_PROBE=1 " + SP_PROBE_FLAGS, end="bkpt:0x7f", engines=("native",), blocks=("no_faults", "psa_lifecycle", "nativewire")), @@ -211,6 +217,10 @@ def S(secure="", role="lifecycle", guest_flags="", end="guest", timeout=None, role="hwpsa", guest_flags="WT_NATIVE_WIRE_PROBE=1 " + SP_PROBE_FLAGS, end="bkpt:0x7f", engines=("native",), blocks=("no_faults", "psa_lifecycle", "nativewire")), + "nativewiresmall": S(secure="WT_SECURE_PSA=1 WT_SECURE_PSA_PROFILE=small", + role="hwpsa", guest_flags="WT_NATIVE_WIRE_PROBE=1 " + SP_PROBE_FLAGS, + end="bkpt:0x7f", engines=("native",), + blocks=("no_faults", "psa_lifecycle", "nativewire")), "hsmattackneg": S(role="psa", guest_flags="WT_HSM_ATTACK_PROBE=1", blocks=("no_faults", "psa_lifecycle", "hsmattackneg"), engines=("hsm",), @@ -809,7 +819,7 @@ def _l3(ctx): v.get(stack + "_LO"), v.get(stack + "_HI")), refute_re("no access ran past its fault, no keystore pin was open", r'^\[USGFLT\]'), refute_re("faults were contained, not escalated", r'^(\[HARDFLT\]|HardFault|SecureFault)')] - if fam == "restartneg": + if fam == "restartneg" or name == "tinyattest": return [expect_n_re("partition faulted once and restarted on a reset band", 1, r'^\[USGFLT\] CFSR=0x00010000'), refute_re("the fault was the planted one", r'^\[USGFLT\] mem16\[[^]]*\]=0xde02'), @@ -1049,6 +1059,21 @@ def block_checks(ctx, block, end): expect("tampered token fails the guest verify", pre + "attestneg tampered token rejected"), expect("misattributed lifecycle fails the guest verify", pre + "attestneg lifecycle mismatch rejected"), expect("attestation negatives verified", pre + "wolfTrust attestation negatives verified")] + if block == "tinyattest": + return [symbol("the Secure image links the COSE_Mac0 issuer", "wc_CoseEatPsaToken_CreateMac0"), + refute_re("the Secure image links no P-256 code", + r"^[0-9a-f]+ \S (sp_256_|sp_ecc_|wc_ecc_|wolfPSA_P256_|wc_CoseSign1)", where="syms"), + expect("the restarted attestation partition issued a token", "guest0: psa_initial_attestation st=0"), + expect("the IAK public key query is refused under an HMAC key", + "guest0: wolfTrust attestation: IAK public key refused"), + expect("the COSE_Mac0 verifies under the development key, Instance ID included", + "guest0: wolfTrust attestation: COSE_Mac0 verified"), + expect("token measurement equals wolfBoot's measurement of the signed image", + "guest0: wolfTrust attestation: token measurement={expected_measurement}"), + expect("a tampered COSE_Mac0 fails the guest verify", + "guest0: wolfTrust attestation: tampered COSE_Mac0 rejected"), + expect("P-256 is refused by the Secure PSA service", + "guest0: wolfTrust key-ops P-256 refused (no ECC)")] if block == "nativewire": return [expect("every native wire key op served by the crypto partition", "guest0: nativewire every key op verified"), @@ -1849,11 +1874,11 @@ def profile_gaps(): def one_guest_gaps(): - """No assertion a lean (one-guest) run applies can only be met by the + """No assertion a one-guest run applies can only be met by the guest that image never schedules.""" gaps = [] for port in sorted(PORTS): - for name in scenario_matrix.flat(port, "full", None, "default"): + for name in scenario_matrix.flat(port, "all", None, "default"): p = plan(port, name, "native", "emulator") ctx = Ctx(port, p["scenario"], "emulator", one_guest(p["guests"], 1), {"board": "X"}) @@ -1903,7 +1928,7 @@ def selftest(): for name, end in m33mu.get("ends", {}).items(): if name not in SCENARIOS or not (end in ("fault", "idle", "timeout") or re.match(r"^bkpt:0x[0-9a-f]+$", str(end))): gaps.append("%s: ends.%s is unknown or not an end mode" % (port, name)) - run = set(scenario_matrix.flat(port, "full", None)) + run = set(scenario_matrix.flat(port, "all", None)) # A run that should hit the wall clock passes on exit 0 only where # guest0 ends it on its own clean breakpoint. for name in sorted(n for n in run if n in SCENARIOS): @@ -2000,7 +2025,7 @@ def main(): parser.add_argument("--engine", choices=("native", "hsm"), default="native") parser.add_argument("--env", choices=("emulator", "hardware"), default="emulator") parser.add_argument("--guests", type=int, choices=(1, 2), default=2, - help="guests the Secure image schedules (1: the lean default)") + help="guests the Secure image schedules (1: the default profile)") mode = parser.add_mutually_exclusive_group() mode.add_argument("--shell", action="store_true", help="the resolved plan as SC_* assignments") mode.add_argument("--asserts", action="store_true", help="the applicable blocks and their checks") diff --git a/tests/target/run_hardware.sh b/tests/target/run_hardware.sh index a992c3e36..e9b044de3 100755 --- a/tests/target/run_hardware.sh +++ b/tests/target/run_hardware.sh @@ -40,15 +40,15 @@ lib="$here/lib" # shellcheck source=lib/engine.sh disable=SC1091 . "$lib/engine.sh" -# The hardware suites build, flash and assert both guests, so only the full -# profile runs on silicon; its flags go ahead of every scenario's own. -case "${WT_PROFILE:-full}" in - full) ;; - *) echo "WT_PROFILE=$WT_PROFILE is not supported on hardware (the suite asserts both guests; use WT_PROFILE=full)" >&2; exit 2 ;; +# The hardware suites build, flash and assert both guests, so only the +# extended profile runs on silicon; its flags go ahead of every scenario's own. +case "${WT_PROFILE:-extended}" in + extended) ;; + *) echo "WT_PROFILE=$WT_PROFILE is not supported on hardware (the suite asserts both guests; use WT_PROFILE=extended)" >&2; exit 2 ;; esac scenario_profile_reset # shellcheck disable=SC2046 -export $(scenario_profile_flags full) +export $(scenario_profile_flags extended) ports="$(python3 "$lib/scenario_matrix.py" --list-ports)" case " $ports " in diff --git a/tests/target/run_target.sh b/tests/target/run_target.sh index b78e10d09..b1f3d257f 100755 --- a/tests/target/run_target.sh +++ b/tests/target/run_target.sh @@ -11,8 +11,8 @@ # # Environment (all optional): # WT_ENGINE native (default) or hsm: the crypto engine under test -# WT_PROFILE default or full: the build profile (unset: the one the -# scenario is registered on, full when both) +# WT_PROFILE default or extended: the build profile (unset: the one +# the scenario is registered on, extended when both) # M33MU a prebuilt emulator at the port's pin; otherwise the # pin is built under /tmp # _WOLFBOOT_DIR a wolfBoot tree built by lib/wolfboot_stage.sh with @@ -61,7 +61,7 @@ if [ -n "$SC_MISSING" ]; then echo "$scenario needs a capability port/$port declares absent: $SC_MISSING" >&2 exit 2 fi -known="$(python3 "$lib/scenario_matrix.py" --port "$port" --tier full --flat)" +known="$(python3 "$lib/scenario_matrix.py" --port "$port" --tier all --flat)" case " $known " in *" $scenario "*) ;; *) echo "$port does not run $scenario (port/$port/port.json m33mu.groups)" >&2; exit 2 ;; diff --git a/tools/crypto_profile.py b/tools/crypto_profile.py index 60ec3da96..79871b0bc 100644 --- a/tools/crypto_profile.py +++ b/tools/crypto_profile.py @@ -105,9 +105,9 @@ def select(catalog, defaults, profile, custom, enable, disable, require_tpm=True for kind, names in custom.items(): if not isinstance(names, list) or any(not isinstance(n, str) for n in names): raise ValueError("profile field %s must be a list of names" % kind) - selected = {kind: set(catalog[kind] if profile == "full" else + selected = {kind: set(catalog[kind] if profile == "extended" else defaults[kind]) for kind in KINDS} - mechanisms = None if profile == "full" else defaults["mechanisms"] + mechanisms = None if profile == "extended" else defaults["mechanisms"] for kind, names in custom.items(): if kind == "mechanisms": mechanisms = names @@ -318,7 +318,7 @@ def generate(root, output, profile, custom, enable, disable, interface="tpm"): raise ValueError("TPM 2.0 and PKCS#11 builds link no PSA Crypto; remove psa selections") basic_mechanisms = {"CKM_SHA256", "CKM_EC_KEY_PAIR_GEN", "CKM_ECDSA", "CKM_ECDSA_KEY_PAIR_GEN"} - extra_crypto = (profile == "full" or mechanisms is None or + extra_crypto = (profile == "extended" or mechanisms is None or not set(mechanisms) <= basic_mechanisms or not selected["tpm"] <= set(defaults["tpm"])) output.mkdir(parents=True, exist_ok=True) @@ -326,7 +326,7 @@ def generate(root, output, profile, custom, enable, disable, interface="tpm"): pkcs11_header(signatures, selected["pkcs11"], mechanisms)) write_file(output / "pkcs11_crypto.c", pkcs11_mechanism_source(root, mechanisms)) write_file(output / "hsm_callback.c", hsm_callback_source(root, extra_crypto)) - write_file(output / "fwtpm_command.c", selected_tpm(commands, selected["tpm"], profile == "full")) + write_file(output / "fwtpm_command.c", selected_tpm(commands, selected["tpm"], profile == "extended")) psa_wrappers(root, output, sources, selected["psa"], catalog["psa"]) # Consumers depend only on this header, so it must change with any output. digest = hashlib.sha256() @@ -339,7 +339,7 @@ def generate(root, output, profile, custom, enable, disable, interface="tpm"): "#ifndef WT_SELECTED_CRYPTO_PROFILE_H", "#define WT_SELECTED_CRYPTO_PROFILE_H", "#define WT_PROFILE_OUTPUTS_SHA256 \"%s\"" % digest.hexdigest(), - "#define WT_PROFILE_FULL %d" % (profile == "full"), + "#define WT_PROFILE_EXTENDED %d" % (profile == "extended"), "#define WT_PROFILE_PROVIDER_EXTRA_CRYPTO %d" % extra_crypto, "#define WT_PROFILE_TPM_COMMAND_COUNT %dU" % len(selected["tpm"]), "#define WT_PKCS11_PROFILE_HEADER %s" % @@ -368,7 +368,7 @@ def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parent.parent) parser.add_argument("--output", type=Path) - parser.add_argument("--profile", choices=("default", "full"), default="default") + parser.add_argument("--profile", choices=("default", "extended"), default="default") parser.add_argument("--config", type=Path) parser.add_argument("--enable", action="append", default=[]) parser.add_argument("--disable", action="append", default=[]) diff --git a/tools/gen-port-docs.py b/tools/gen-port-docs.py index 7f66e45c5..fa04da3c7 100755 --- a/tools/gen-port-docs.py +++ b/tools/gen-port-docs.py @@ -63,7 +63,7 @@ def render(): ", ".join(d["build"]["engines"]), ", ".join(d["build"].get("variants", [])) or "none", d["ci"]["image"])) lines += ["", "## Emulator scenarios", "", - "Every port's full tier is in `port.json` (`m33mu.groups`). The smoke tier", + "Every port's all tier is in `port.json` (`m33mu.groups`). The smoke tier", "runs on every pull request for a port whose CI label is optional; a port", "marked label only above runs only under its label. Capabilities a port", "declares absent exempt the scenarios that need them and mark their", diff --git a/tools/manifest/generate.py b/tools/manifest/generate.py index 4df539a63..ef6e204d4 100644 --- a/tools/manifest/generate.py +++ b/tools/manifest/generate.py @@ -1123,6 +1123,24 @@ def exclude_partitions(manifest, names): if domain["id"] not in removed] +def drop_dependencies(manifest, items): + """Each PARTITION=SERVICE removes a dependency this build never uses, so + the partition loses the right to connect to that service.""" + for item in items: + name, equals, service = item.partition("=") + parts = [part for part in manifest["partitions"] + if part["name"] == name] + sids = [entry["sid"] for part in manifest["partitions"] + for entry in part["services"] if entry["name"] == service] + if not equals or len(parts) != 1 or len(sids) != 1: + policy_error("--drop-dependency {!r} does not name a partition " + "and a service in the manifest".format(item)) + if parts[0]["dependencies"].count(sids[0]) != 1: + policy_error("{} does not depend on {} exactly once".format( + name, service)) + parts[0]["dependencies"].remove(sids[0]) + + def check_stacks(manifest, stacks): """Each NAME=BASE:SIZE names where the linked layout put that partition's stack; a manifest that disagrees would confine it to the wrong RAM. With @@ -1190,6 +1208,9 @@ def main(): parser.add_argument("--exclude-partition", action="append", default=[], metavar="NAME", help="leave this partition and its domain out") + parser.add_argument("--drop-dependency", action="append", default=[], + metavar="PARTITION=SERVICE", + help="remove a dependency this build never uses") parser.add_argument("--stack", action="append", default=[], metavar="NAME=BASE:SIZE", help="the layout's stack for partition NAME") @@ -1243,8 +1264,10 @@ def main(): object_pairs_hook=reject_duplicate_keys) word_max = (1 << int(args.address_bits)) - 1 validate(manifest, MANIFEST_SCHEMA, "manifest", word_max) + drop_dependencies(manifest, args.drop_dependency) if args.exclude_partition: exclude_partitions(manifest, args.exclude_partition) + if args.exclude_partition or args.drop_dependency: # The digest covers the manifest the image is built from. input_bytes = json.dumps(manifest, sort_keys=True, separators=(",", ":")).encode("utf-8") diff --git a/tools/secure_owners.txt b/tools/secure_owners.txt index e2706a498..db1bbb06b 100644 --- a/tools/secure_owners.txt +++ b/tools/secure_owners.txt @@ -57,6 +57,7 @@ wt_sec_mutex.o spm wt_sec_nvm_boot.o spm wt_sec_reg.o spm wt_sec_rng_entropy.o spm +wt_sec_attest_dev_key.o spm wt_sec_sau_armv8m.o spm wt_sec_sp_fault_armv8m.o spm wt_sec_spm_gate_core.o spm @@ -73,6 +74,7 @@ wh_sec_wh_nvm_flash.o vault wt_sec_hsm_flash_ctx.o vault wt_sec_nvm_store.o vault wt_sec_vault_service.o vault +wt_sec_wt_hsm_aead.o shared wt_sec_wt_hsm_seal.o vault wt_sec_wt_hsm_vault.o vault @@ -116,6 +118,7 @@ wt_sec_hsm_relay_service.o hsm wt_sec_keyvault.o hsm wt_sec_native_wire.o hsm wt_sec_psa_crypto_service.o hsm +wp_sec_psa_aead.o shared wp_sec_* hsm wc_sec_kdf.o hsm wc_sec_pwdbased.o hsm