diff --git a/.github/workflows/test-build-aarch64.yml b/.github/workflows/test-build-aarch64.yml index 6605a098f2..43bed61304 100644 --- a/.github/workflows/test-build-aarch64.yml +++ b/.github/workflows/test-build-aarch64.yml @@ -132,6 +132,16 @@ jobs: unsigned long psu_ddr_qos_init_data(void) { return 1UL; } STUB + # Keep the archive across runs so wolfssl.com is fetched only on a cache + # miss. Both build workflows share the key, which must name the same + # version as WOLFSSL_FIPS_READY_VER below; the SHA-256 check still runs. + - name: Cache FIPS-ready wolfSSL + if: ${{ inputs.fips }} + uses: actions/cache@v4 + with: + path: .fips-ready-cache + key: wolfssl-5.9.2-gplv3-fips-ready + - name: Download FIPS-ready wolfSSL if: ${{ inputs.fips }} env: @@ -145,9 +155,12 @@ jobs: run: | set -euxo pipefail sudo apt-get install -y unzip - zip=/tmp/wolfssl-fips-ready.zip - curl -fsSL --retry 3 --retry-delay 5 -o "$zip" \ - "https://www.wolfssl.com/wolfssl-${WOLFSSL_FIPS_READY_VER}.zip" + zip=.fips-ready-cache/wolfssl-${WOLFSSL_FIPS_READY_VER}.zip + if [ ! -f "$zip" ]; then + mkdir -p .fips-ready-cache + curl -fsSL --retry 3 --retry-delay 5 -o "$zip" \ + "https://www.wolfssl.com/wolfssl-${WOLFSSL_FIPS_READY_VER}.zip" + fi got="$(sha256sum "$zip" | awk '{print $1}')" echo "wolfssl-${WOLFSSL_FIPS_READY_VER}.zip sha256=$got" if [ -n "${WOLFSSL_FIPS_READY_SHA256:-}" ]; then diff --git a/.github/workflows/test-build.yml b/.github/workflows/test-build.yml index 7e1adb9862..b4bc395c73 100644 --- a/.github/workflows/test-build.yml +++ b/.github/workflows/test-build.yml @@ -53,6 +53,16 @@ jobs: - name: Pre-build setup if: inputs.prep-run != '' run: ${{inputs.prep-run}} + # Keep the archive across runs so wolfssl.com is fetched only on a cache + # miss. Both build workflows share the key, which must name the same + # version as WOLFSSL_FIPS_READY_VER below; the SHA-256 check still runs. + - name: Cache FIPS-ready wolfSSL + if: ${{ inputs.fips }} + uses: actions/cache@v4 + with: + path: .fips-ready-cache + key: wolfssl-5.9.2-gplv3-fips-ready + - name: Download FIPS-ready wolfSSL if: ${{ inputs.fips }} env: @@ -65,9 +75,12 @@ jobs: WOLFSSL_FIPS_READY_SHA256: ${{ vars.WOLFSSL_FIPS_READY_SHA256 }} run: | set -euxo pipefail - zip=/tmp/wolfssl-fips-ready.zip - curl -fsSL --retry 3 --retry-delay 5 -o "$zip" \ - "https://www.wolfssl.com/wolfssl-${WOLFSSL_FIPS_READY_VER}.zip" + zip=.fips-ready-cache/wolfssl-${WOLFSSL_FIPS_READY_VER}.zip + if [ ! -f "$zip" ]; then + mkdir -p .fips-ready-cache + curl -fsSL --retry 3 --retry-delay 5 -o "$zip" \ + "https://www.wolfssl.com/wolfssl-${WOLFSSL_FIPS_READY_VER}.zip" + fi got="$(sha256sum "$zip" | awk '{print $1}')" echo "wolfssl-${WOLFSSL_FIPS_READY_VER}.zip sha256=$got" if [ -n "${WOLFSSL_FIPS_READY_SHA256:-}" ]; then diff --git a/.github/workflows/test-configs.yml b/.github/workflows/test-configs.yml index aef24ad2d9..6b0f355917 100644 --- a/.github/workflows/test-configs.yml +++ b/.github/workflows/test-configs.yml @@ -1100,6 +1100,15 @@ jobs: config-file: ./config/examples/sim-fips.config fips: true + # ARMv8 asm inside the FIPS boundary, with AES-256 image encryption. + zynqmp_fips_test: + uses: ./.github/workflows/test-build-aarch64.yml + with: + arch: aarch64 + config-file: ./config/examples/zynqmp_sdcard.config + make-args: wolfboot.bin FIPS=1 SIGN=ECC384 HASH=SHA384 ENCRYPT=1 ENCRYPT_WITH_AES256=1 WOLFBOOT_LIB_WOLFSSL=../wolfssl-5.9.2-gplv3-fips-ready + fips: true + tegra234_sdcard_fs_test: uses: ./.github/workflows/test-build.yml with: diff --git a/.github/workflows/test-key-revocation-simulator.yml b/.github/workflows/test-key-revocation-simulator.yml new file mode 100644 index 0000000000..95ecedb61a --- /dev/null +++ b/.github/workflows/test-key-revocation-simulator.yml @@ -0,0 +1,100 @@ +name: Key revocation and security version - test with simulator target + +on: + push: + branches: [ 'master', 'main', 'release/**' ] + pull_request: + branches: [ '*' ] + +jobs: + revocation_svn_simulator_tests: + strategy: + fail-fast: false + matrix: + include: + - name: key-revocation + options: KEY_REVOCATION=1 + scripts: sim-key-revocation.sh + - name: security-version + options: SECURITY_VERSION=1 + scripts: sim-security-version.sh + - name: both + options: KEY_REVOCATION=1 SECURITY_VERSION=1 + scripts: sim-security-version.sh sim-key-revocation.sh + - name: both-production + options: KEY_REVOCATION=1 SECURITY_VERSION=1 WOLFBOOT_PRODUCTION=1 + scripts: sim-security-version.sh sim-key-revocation.sh + name: ${{ matrix.name }} + runs-on: ubuntu-latest + container: + image: ghcr.io/wolfssl/wolfboot-ci-sim:v1.0 + timeout-minutes: 15 + + steps: + - uses: actions/checkout@v4 + with: + submodules: true + + - name: Trust workspace + run: git config --global --add safe.directory "$GITHUB_WORKSPACE" + + - name: Select config + run: | + make distclean + cp config/examples/sim.config .config + for opt in ${{ matrix.options }}; do echo "$opt" >> .config; done + + - name: Build tools + run: | + make -C tools/keytools && make -C tools/bin-assemble + + - name: Build wolfboot.elf and test-app/image.elf + run: | + make test-sim-internal-flash-with-update + + - name: Run simulator tests + run: | + for s in ${{ matrix.scripts }}; do tools/scripts/$s || exit 1; done + + revocation_svn_tpm_nv_tests: + name: tpm-nv + runs-on: ubuntu-latest + timeout-minutes: 15 + + steps: + - uses: actions/checkout@v4 + with: + repository: kgoldman/ibmswtpm2 + ref: ad169862f25060f6d83ef3018be7dbdc9bf4e266 + path: ibmswtpm2 + - name: ibmswtpm2 make + working-directory: ./ibmswtpm2/src + run: | + make + ./tpm_server & + + - uses: actions/checkout@v4 + with: + submodules: true + + - name: Select config + run: | + make distclean + cp config/examples/sim-tpm.config .config + for opt in KEY_REVOCATION=1 SECURITY_VERSION=1 WOLFBOOT_TPM_POLICY_NV=1; do echo "$opt" >> .config; done + + - name: Build tools + run: | + make -C tools/keytools && make -C tools/bin-assemble + + - name: Build wolfboot.elf and test-app/image.elf + run: | + make test-sim-internal-flash-with-update + + - name: Build TPM tools + run: | + make tpmtools + + - name: Run simulator tests + run: | + for s in sim-security-version.sh sim-key-revocation.sh; do tools/scripts/$s || exit 1; done diff --git a/.github/workflows/test-units.yml b/.github/workflows/test-units.yml index 9a958d8b54..1805127c96 100644 --- a/.github/workflows/test-units.yml +++ b/.github/workflows/test-units.yml @@ -11,7 +11,7 @@ jobs: runs-on: ubuntu-latest container: image: ghcr.io/wolfssl/wolfboot-ci-sim:v1.0 - timeout-minutes: 15 + timeout-minutes: 30 steps: - uses: actions/checkout@v4 diff --git a/.gitignore b/.gitignore index e58350d14b..306aff7e95 100644 --- a/.gitignore +++ b/.gitignore @@ -132,6 +132,7 @@ tools/tpm/pcr_reset tools/tpm/pcr_extend tools/tpm/policy_create tools/tpm/policy_sign +tools/tpm/policy_nv config/*.ld config/*.sct test-lib @@ -642,6 +643,7 @@ tools/unit-tests/imx8qm_flexspi_extract.h tools/unit-tests/unit-ct-compare tools/unit-tests/unit-zynqmp-bbram-crc tools/unit-tests/unit-zynqmp-efuse-guards +tools/unit-tests/unit-zynqmp-efuse-counter tools/unit-tests/unit-zynqmp-efuse-burn tools/unit-tests/unit-fit-gzip-small tools/unit-tests/unit-gzip-bits32 @@ -703,12 +705,15 @@ tools/unit-tests/unit-ti-hercules-erase tools/unit-tests/unit-update-disk-fsp tools/unit-tests/unit-update-ram-custom-trailer tools/unit-tests/unit-update-ram-rollback-unconfirmed +tools/unit-tests/unit-update-ram-confirm-hooks +tools/unit-tests/unit-update-disk-confirm-hooks tools/unit-tests/unit-update-ram-nofixed-noramboot tools/unit-tests/unit-update-trigger-scrub tools/unit-tests/unit-x86-uart # sources generated by the unit-test extraction rules tools/unit-tests/bbram_crc_extract.h tools/unit-tests/efuse_guards_extract.h +tools/unit-tests/efuse_counter_extract.h tools/unit-tests/stm32g0_write_extract.h tools/unit-tests/ct_compare_extract.h tools/unit-tests/puf_extract.h diff --git a/arch.mk b/arch.mk index 9b55016bc9..e827dd307a 100644 --- a/arch.mk +++ b/arch.mk @@ -86,6 +86,25 @@ ifeq ($(ARCH),AARCH64) ifeq ($(TARGET),zynq) ARCH_FLAGS=-march=armv8-a+crypto CFLAGS+=$(ARCH_FLAGS) -DCORTEX_A53 + # User eFuse rows (USER_0..USER_7 index) for the security version counter + # and the key revocation mask. No default: the allocation is a + # provisioning decision. + ifeq ($(SECURITY_VERSION),1) + ifeq ($(ZYNQMP_EFUSE_SVN_ROW),) + $(error SECURITY_VERSION=1 on zynq needs ZYNQMP_EFUSE_SVN_ROW) + endif + ifeq ($(ZYNQMP_EFUSE_SVN_NROWS),) + $(error SECURITY_VERSION=1 on zynq needs ZYNQMP_EFUSE_SVN_NROWS) + endif + CFLAGS+=-DZYNQMP_EFUSE_SVN_ROW=$(ZYNQMP_EFUSE_SVN_ROW) + CFLAGS+=-DZYNQMP_EFUSE_SVN_NROWS=$(ZYNQMP_EFUSE_SVN_NROWS) + endif + ifeq ($(KEY_REVOCATION),1) + ifeq ($(ZYNQMP_EFUSE_REVOKE_ROW),) + $(error KEY_REVOCATION=1 on zynq needs ZYNQMP_EFUSE_REVOKE_ROW) + endif + CFLAGS+=-DZYNQMP_EFUSE_REVOKE_ROW=$(ZYNQMP_EFUSE_REVOKE_ROW) + endif CFLAGS+=-DNO_QNX # Support detection and skip of U-Boot legacy header */ CFLAGS+=-DWOLFBOOT_UBOOT_LEGACY @@ -182,6 +201,29 @@ ifeq ($(ARCH),AARCH64) endif endif endif + # As BL33 the user eFuse writes go through the PMU firmware; the same + # opt-in arms them, otherwise they are report-only. + ifneq ($(ZYNQMP_FSBL),1) + ifeq ($(ZYNQMP_EFUSE_BURN),1) + CFLAGS+=-DZYNQMP_EFUSE_BURN + endif + endif + # eFuse security state (SEC_CTRL, PUF, PPK0 hash): read directly as the + # FSBL, through the PMU firmware as BL33. + ifeq ($(ZYNQMP_SEC),1) + CFLAGS+=-DWOLFBOOT_ZYNQMP_SEC_STATE + endif + # SEC_CTRL bits a deployed part must have. A WOLFBOOT_PRODUCTION build + # refuses a part without them; any other build boots it and reports it. + ifneq ($(ZYNQMP_SEC_POLICY),) + ifneq ($(ZYNQMP_SEC),1) + $(error ZYNQMP_SEC_POLICY needs ZYNQMP_SEC=1) + endif + ifneq ($(filter 0 0x0 0x00 0x00000000,$(ZYNQMP_SEC_POLICY)),) + $(error ZYNQMP_SEC_POLICY=0 would refuse every part; leave it unset for no policy) + endif + CFLAGS+=-DZYNQMP_SEC_POLICY=$(ZYNQMP_SEC_POLICY) + endif endif diff --git a/config/examples/nai_68int6.config b/config/examples/nai_68int6.config index 62a895fe79..fd70f7daa4 100644 --- a/config/examples/nai_68int6.config +++ b/config/examples/nai_68int6.config @@ -117,3 +117,11 @@ DISK_ERASE=0 # Anti-rollback: persistent version floor + audit counters in TPM NV # (trust-on-first-use; provision before first boot where that matters). ANTI_ROLLBACK=1 + +# Signing key revocation and a security version floor in TPM NV bit-field +# indices. They are committed only for a confirmed image, so the OS must +# confirm each boot (DISK_BOOT_CONFIRM). Not yet run on this board. +#DISK_BOOT_CONFIRM=1 +#KEY_REVOCATION=1 +#SECURITY_VERSION=1 +#WOLFBOOT_TPM_POLICY_NV=1 diff --git a/docs/API.md b/docs/API.md index cc863f8282..ec4991af1c 100644 --- a/docs/API.md +++ b/docs/API.md @@ -97,6 +97,24 @@ This feature is disabled by default. To enable it, set smaller than, the flash write granularity. Raise it on platforms whose flash write word is wider than 16 bytes (for example 32 for the 256-bit words on STM32H7). +- `WOLFBOOT_DIAGNOSTICS_DISK_PART`: on the disk boot path (`WOLFBOOT_UPDATE_DISK`), + keep the region in this partition of the boot disk instead of flash. The + partition is normally reserved for it (a few sectors of + `WOLFBOOT_SECTOR_SIZE`); `WOLFBOOT_DIAGNOSTICS_ADDRESS` becomes a byte offset + into it and defaults to 0, and an erase writes the erased pattern. On a card + with no partition to spare it can share a boot slot's partition, with + `WOLFBOOT_DIAGNOSTICS_ADDRESS` at or beyond `IMAGE_HEADER_SIZE + + WOLFBOOT_RAMBOOT_MAX_SIZE` so no image the slot accepts can reach it; the + build refuses a slot partition without that, and a slot that holds a + filesystem (`WOLFBOOT_DISK_FS`). At boot the region must also end inside + the partition, before the slot's boot state trailer with + `DISK_BOOT_CONFIRM`; otherwise wolfBoot prints a warning and records + nothing. + The drive is `BOOT_DISK`. It cannot be combined with + `WOLFBOOT_DIAGNOSTICS_EXT`. Where the board also has a SPI flash, the same + store can live there instead with `EXT_FLASH=1` and + `WOLFBOOT_DIAGNOSTICS_EXT=1`; `WOLFBOOT_SECTOR_SIZE` must then be the flash + erase block (for example `0x20000` for the dual-parallel QSPI on ZCU102). The region is managed as a circular store over its sectors. With two or more sectors, older records are retained until the log wraps all the way around, so @@ -117,11 +135,25 @@ The following events are recorded: - A rollback was caused by a new image that never confirmed via `wolfBoot_success()` (`WOLFBOOT_FAILURE_PHASE_ROLLBACK`). +On the disk boot path every slot that is refused is recorded with +`WOLFBOOT_FAILURE_PHASE_BOOT` (or `WOLFBOOT_FAILURE_PHASE_ROLLBACK` for a slot +that did not confirm its last boot), `partition` set to the slot (0 A, 1 B, +2 golden) and `fw_version` to the version its header declares. When no slot +boots, a final `WOLFBOOT_FAILURE_PHASE_RECOVERY` record repeats the last cause +and slot. The newest record is printed on the console at the next boot. A +failure detected before the disk is opened (a HAL policy check in `hal_init()`) +can only be recorded in a flash store, not in a disk partition. + For verification failures, the cause distinguishes a bad header (`WOLFBOOT_FAILURE_CAUSE_HEADER`), a failed integrity/hash check (`WOLFBOOT_FAILURE_CAUSE_HASH`) and a failed signature/authenticity check (`WOLFBOOT_FAILURE_CAUSE_SIGNATURE`). A rollback uses -`WOLFBOOT_FAILURE_CAUSE_NOT_CONFIRMED`. +`WOLFBOOT_FAILURE_CAUSE_NOT_CONFIRMED`. The disk boot path also reports an +image that could not be decrypted (`WOLFBOOT_FAILURE_CAUSE_DECRYPT`) and one +refused for its version (`WOLFBOOT_FAILURE_CAUSE_VERSION`) or that could not be read from the disk +(`WOLFBOOT_FAILURE_CAUSE_READ`), and a HAL that +refuses a device whose security state does not meet the build's policy uses +`WOLFBOOT_FAILURE_CAUSE_POLICY` (ZynqMP `ZYNQMP_SEC_POLICY`). The application can read the records, ordered newest-first, through this API: @@ -133,7 +165,14 @@ The application can read the records, ordered newest-first, through this API: The read functions only read the region and have no external dependency. `wolfBoot_clear_failures()`, however, erases flash, so an application that calls it must have the HAL flash driver (`hal_flash_unlock`, `hal_flash_erase`, -`hal_flash_lock`) similarly to `wolfBoot_success()`. +`hal_flash_lock`) similarly to `wolfBoot_success()`. With +`WOLFBOOT_DIAGNOSTICS_DISK_PART` the API is built into wolfBoot only; an OS +reads the partition directly, where the layout is the same as in flash: sectors +of `WOLFBOOT_SECTOR_SIZE` bytes, each starting with a header (magic +`0x47414944`, generation, format version, CRC32) in a slot of +`WOLFBOOT_DIAGNOSTICS_RECORD_SIZE` bytes, followed by records in +`struct wolfBoot_failure_record` layout at the same stride, in the target's +byte order. Each `struct wolfBoot_failure_record` reports `phase`, `cause`, `partition`, `fw_version` (the version of the offending image, when known) and a monotonic diff --git a/docs/FIPS.md b/docs/FIPS.md index 82768c601c..e0f618cc40 100644 --- a/docs/FIPS.md +++ b/docs/FIPS.md @@ -40,16 +40,22 @@ Production use requires the licensed, validated FIPS bundle. Unpack it and point The `FIPS=1` build option (`options.mk`) rebuilds the wolfcrypt object list as the validated module boundary in link order (`wolfcrypt_first.o` first, `wolfcrypt_last.o` last, with `fips.o`/`fips_test.o` and the boundary crypto between them - the in-core integrity hash on GCC/ELF is enforced by this link order). Point the build at the FIPS tree and select an approved algorithm pair: ``` -cp config/examples/sim-fips.config .config # or cm4.config / cm5.config +cp config/examples/sim-fips.config .config # or cm4.config / cm5.config / zynqmp_sdcard.config make FIPS=1 WOLFBOOT_LIB_WOLFSSL=/path/to/wolfssl-5.9.2-gplv3-fips-ready \ SIGN=ECC384 HASH=SHA384 SPMATH=1 ``` +On AArch64 the boundary also links the module's ARMv8 assembly (`cpuid.o`, `port/arm/armv8-aes-asm_c.o`, `armv8-sha256-asm_c.o`, `armv8-sha512-asm_c.o`, `armv8-sha3-asm_c.o` and `sp_arm64.o`) between `wolfcrypt_first.o` and `wolfcrypt_last.o`, unless the build sets `NO_ARM_ASM=1`. The assembly is part of the module, so it is covered by the in-core integrity hash like the rest of the boundary. The SP ECC code it enables carries precomputed point tables of about 570 KB; targets with a tight memory map (the CM4 defaults to `NO_ARM_ASM=1`) build the portable-C module instead. 32-bit ARM builds always use the portable-C module: `FIPS=1` forces `NO_ARM_ASM=1` there. + +Encrypted images (`ENCRYPT=1` with `ENCRYPT_WITH_AES128` or `ENCRYPT_WITH_AES256`) are supported with `FIPS=1`: the AES-CTR decryption uses the module's own AES object. ChaCha20 (`ENCRYPT_WITH_CHACHA`) is outside the module and `ENCRYPT_PKCS11` is not wired in, so `FIPS=1` refuses both. + +The module's ECDH self-test is fixed to P-256, so FIPS builds keep P-256 compiled in even when images are signed with P-384 or P-521. Without it that self-test fails and the module enters degraded mode. + `-DHAVE_FIPS` is added by the `FIPS=1` block. `FIPS=1` also defaults `FIPS_READY=1`, which defines `WOLFSSL_FIPS_READY` (`include/user_settings.h`); that macro forces the evaluation bundle's `HAVE_FIPS_VERSION` to 7 and selects the FIPS-186-4 gating in `settings.h`. `FIPS_READY=1` (the default) builds the evaluation FIPS-ready bundle. A production build with the licensed **validated** bundle (not a FIPS-ready drop) must pass both `FIPS_READY=0` and `FIPS_VERSION=` (for example `FIPS_VERSION=7` for a 140-3 module), which `options.mk` turns into `-DHAVE_FIPS_VERSION=` to pin the module version. This is required because under wolfBoot's `-DWOLFSSL_USER_SETTINGS` build `settings.h` includes only `user_settings.h` and never the configure-generated `wolfssl/options.h`, so the validated bundle does not self-declare `HAVE_FIPS_VERSION`; without it the module would silently build as FIPS v1 (140-2). `options.mk` therefore errors if `FIPS_READY=0` is passed without `FIPS_VERSION`. The `HAVE_FIPS` block in `include/user_settings.h` also enables the module's algorithm set, keeps the RNG/DRBG enabled, and wires the entropy seed (below). ## Entropy source (required) -The FIPS DRBG needs a seed. wolfBoot's lean configuration compiles out the OS seed paths, so a seed is provided via `CUSTOM_RAND_GENERATE_SEED` (the `HAVE_FIPS` block in `include/user_settings.h` keeps the RNG enabled by undoing wolfBoot's `WC_NO_RNG`/`WC_NO_HASHDRBG`). The example wiring points it at `wolfBoot_fips_seed()`, implemented per target: `/dev/urandom` on the simulator (`hal/sim.c`) and the BCM2711 RNG200 hardware TRNG on the CM4 (`hal/rpi_common.c`). Without a working seed, the ECDSA power-on self-test (which performs a sign) fails with `ECDSA_KAT_FIPS_E` because `wc_GenerateSeed()` returns `NOT_COMPILED_IN`. +The FIPS DRBG needs a seed. wolfBoot's lean configuration compiles out the OS seed paths, so a seed is provided via `CUSTOM_RAND_GENERATE_SEED` (the `HAVE_FIPS` block in `include/user_settings.h` keeps the RNG enabled by undoing wolfBoot's `WC_NO_RNG`/`WC_NO_HASHDRBG`). The example wiring points it at `wolfBoot_fips_seed()`, implemented per target: `/dev/urandom` on the simulator (`hal/sim.c`), the BCM2711 RNG200 hardware TRNG on the CM4 (`hal/rpi_common.c`), and on ZynqMP, which has no TRNG on the processing system, the module's own CPU-jitter entropy source (`wc_Entropy_Get()`, built with `HAVE_ENTROPY_MEMUSE`; `FIPS_ENTROPY_MEMUSE=1` is the default for `TARGET=zynq`) in `hal/zynq.c`. Each jitter seed takes a few hundred milliseconds on a Cortex-A53, and the module seeds its DRBG on first use (the ECDSA self-test), so the first signature verification includes it. Without a working seed, the ECDSA power-on self-test (which performs a sign) fails with `ECDSA_KAT_FIPS_E` because `wc_GenerateSeed()` returns `NOT_COMPILED_IN`. ## Sealing the in-core integrity hash @@ -74,7 +80,7 @@ The FIPS module targets a hosted environment; a few things must be provided on b - **POST entry.** The module registers its POST via a C constructor (`.init_array`), which a hosted runtime runs before `main()`. wolfBoot's bare-metal startup does not run `.init_array`, so build with `NO_ATTRIBUTE_CONSTRUCTOR` and call `fipsEntry()` explicitly (`src/loader.c`). - **Normal (cacheable) memory.** wolfBoot's simple startup runs with the MMU off, where all memory is Device-nGnRnE and unaligned / 128-bit SIMD accesses fault (the FIPS module and newlib `printf`/`snprintf` do both). The CM4 HAL enables a minimal identity MMU with DDR mapped Normal cacheable before the POST (`cm4_mmu_enable`), and tears it down (clean D-cache, disable MMU/caches) before the boot handoff (`cm4_mmu_disable`) so the loaded image is coherent and the application starts MMU-off. -- **libc.** The module uses malloc/printf; stub the newlib syscalls (`--specs=nosys.specs`) and provide a bounded `_sbrk` so the heap cannot grow into the unverified image (the CM4 HAL allocates from a fixed static buffer in `hal/rpi_common.c`). +- **libc.** The module uses malloc/printf; stub the newlib syscalls (`--specs=nosys.specs`, the default for `TARGET=cm4`, `TARGET=cm5` and `TARGET=zynq` through `FIPS_NOSYS_SPECS`) and provide a bounded `_sbrk` so the heap cannot grow into the unverified image (the CM4 HAL allocates from a fixed static buffer in `hal/rpi_common.c`; the ZynqMP HAL uses the linker script's `.heap` region in `hal/zynq.c`). Build with a bare-metal toolchain (`aarch64-none-elf-`): with a hosted glibc cross compiler the module's `printf`/`snprintf` resolve to shared-library symbols that are never loaded. Bring the module up on the simulator (`config/examples/sim-fips.config`) first - it exercises the whole flow (module boundary, POST, in-core seal, verify, A/B update) with no hardware. diff --git a/docs/TPM.md b/docs/TPM.md index 43f1550d16..c1c19264e6 100644 --- a/docs/TPM.md +++ b/docs/TPM.md @@ -18,6 +18,7 @@ In wolfBoot we support TPM based root of trust, sealing/unsealing, cryptographic | `WOLFBOOT_TPM_SEAL=1` | `WOLFBOOT_TPM_SEAL` | Enables support for sealing/unsealing based on PCR policy signed externally. | | `WOLFBOOT_TPM_SEAL_NV_BASE=0x01400300` | `WOLFBOOT_TPM_SEAL_NV_BASE` | To override the default sealed blob storage location in the platform hierarchy. | | `WOLFBOOT_TPM_SEAL_AUTH=secret` | `WOLFBOOT_TPM_SEAL_AUTH` | Password for sealing/unsealing secrets, if omitted the PCR policy will be used | +| `WOLFBOOT_TPM_POLICY_NV=1` | `WOLFBOOT_TPM_POLICY_NV` | Keeps the `KEY_REVOCATION` mask and the `SECURITY_VERSION` floor in TPM NV bit-field indices (`WOLFBOOT_TPM_REVOKE_NV_INDEX`, default 0x01400401, and `WOLFBOOT_TPM_SVN_NV_INDEX`, default 0x01400402). See [docs/keystore.md](/docs/keystore.md#key-revocation). | | `WOLFBOOT_TPM_MFG_AUTH_DERIVE=1` | `WOLFBOOT_TPM_MFG_AUTH_DERIVE` | MFG identity: opt into on-device derive-from-master. The default is a precomputed per-device authValue (no master secret on device). Requires `WOLFTPM_MFG_IDENTITY`. | | (header macro) | `WOLFBOOT_TPM_MFG_AIK_AUTH` / `WOLFBOOT_TPM_MFG_EH_AUTH` | Default (precomputed) mode: the 16-byte per-device AIK / EH authValues (placeholder `0xFF` default). | | (header macro) | `WOLFBOOT_TPM_MFG_EH_MASTER` | Derive mode: override the endorsement-hierarchy master value (16-byte initializer list, sample default). | diff --git a/docs/Targets.md b/docs/Targets.md index e0f51d7ba3..a7a4b6ddfb 100644 --- a/docs/Targets.md +++ b/docs/Targets.md @@ -3881,7 +3881,18 @@ the_ROM_image: ### eFuse security state and programming (optional) -With `ZYNQMP_SEC=1` wolfBoot reads the eFuse cache at EL3 and prints `SEC_CTRL` (decoding `RSA_EN`, `ENC_ONLY`, `JTAG_DIS`, PPK revocation and the lock bits), the PUF `CHASH`/`AUX`, and the 12-word PPK0 hash. `zynqmp_sec_policy_check()` turns that into a boot-time gate: it returns non-zero when `SEC_CTRL` does not have every bit a deployment requires, so a build can refuse to run on a part that is not locked down. `RSA_EN` is the exception, being the redundant field `SEC_CTRL[25:11]` whose used bits depend on the silicon version, so any bit set counts as authentication enforced. +With `ZYNQMP_SEC=1` wolfBoot reads the eFuse cache and prints `SEC_CTRL` (decoding `RSA_EN`, `ENC_ONLY`, `JTAG_DIS`, PPK revocation and the lock bits), the PUF `CHASH`/`AUX`, and the 12-word PPK0 hash. `zynqmp_sec_policy_check()` turns that into a boot-time gate: it returns non-zero when `SEC_CTRL` does not have every bit a deployment requires, so a build can refuse to run on a part that is not locked down. `RSA_EN` is the exception, being the redundant field `SEC_CTRL[25:11]` whose used bits depend on the silicon version, so any bit set counts as authentication enforced. + +As the FSBL (EL3) wolfBoot reads the cache directly. As BL33 the read goes through the PMU firmware (`PM_EFUSE_ACCESS`, PMU firmware built with `ENABLE_EFUSE_ACCESS=1`), which returns `SEC_CTRL` only to the extent its build grants: in full with both `XSK_ACCESS_SECURE_CRITICAL_EFUSE` and `XSK_ACCESS_KEY_MANAGE_EFUSE`, without bits 29 and 31 (PPK1 lock and revocation) with the first alone, and not at all otherwise. A read the firmware reports as done without writing the value is treated as a failure. A masked bit reads as not programmed, so a part can only appear less locked than it is. The PUF and PPK0 fields are printed when the firmware returns them. + +`ZYNQMP_SEC_POLICY=` (requires `ZYNQMP_SEC=1`) runs the check at boot with the `SEC_CTRL` bits a deployed part must have, for example `0x20` for `JTAG_DIS`: + +| Build | Policy met | Policy not met or state unreadable | +|---|---|---| +| `WOLFBOOT_PRODUCTION=1` | boots | refuses to boot (recorded as `WOLFBOOT_FAILURE_CAUSE_POLICY` when failure diagnostics are enabled) | +| otherwise | boots | boots as a development unit and says so on the console | + +Either way the OS can tell the two apart. wolfBoot adds `/chosen/wolfboot,sec-ctrl` (the `SEC_CTRL` value read whenever `ZYNQMP_SEC=1`, or 0 when it could not be read) and `/chosen/wolfboot,sec-policy` (1 met, 0 not met; present only with a policy) to the DTB it hands to Linux, readable at `/proc/device-tree/chosen/`. A development unit that reaches the field therefore reports `wolfboot,sec-policy = 0`, and a production build never boots one. eFuse *programming* is separate and off by default: @@ -3901,6 +3912,24 @@ The rejection covers `SEC_CTRL` (page 0, row 22) only. Other one-shot fuses, inc The controller timing is derived from `PS_REF_CLK` (`TPGM`, `TRD`, `TSU_H_PS`, `TSU_H_PS_CS`, `TSU_H_CS`) using integer arithmetic. The default assumes 33.333 MHz; override with `CFLAGS_EXTRA+=-DZYNQMP_PS_REF_CLK_HZ=` if your board differs, since two of the five values land on an integer boundary at that clock. +### Security version counter and key revocation in user eFuses (optional) + +`SECURITY_VERSION=1` (see [firmware_update.md](firmware_update.md#security-version-floor)) and `KEY_REVOCATION=1` (see [keystore.md](keystore.md#key-revocation)) keep their state in the user eFuses `USER_0`..`USER_7` (OTP page 0, rows 8-15). The build must name the rows, by `USER_n` index, because the allocation is a provisioning decision: + +``` +SECURITY_VERSION=1 +ZYNQMP_EFUSE_SVN_ROW=0 # first counter row +ZYNQMP_EFUSE_SVN_NROWS=6 # 6 rows = up to 192 security versions +KEY_REVOCATION=1 +ZYNQMP_EFUSE_REVOKE_ROW=6 # one bit per keystore slot +``` + +The security version is the number of set bits across the counter rows, and raising it programs the lowest clear bits, so it can only increase. The revocation row holds the revoked-slot mask directly. A row that cannot be read rejects every image (security version) or treats every key as revoked (revocation). + +As BL33, wolfBoot reads and programs these rows through the PMU firmware (`PM_EFUSE_ACCESS`), which must be built with `ENABLE_EFUSE_ACCESS` and XilSKey's `XSK_ACCESS_USER_EFUSE`. That interface is open to every PMU master, so Linux can also program user eFuses: it can raise the counter or revoke keys, never lower or restore them. As the FSBL (`ZYNQMP_FSBL=1`), reads come from the eFuse cache and programming uses `zynqmp_efuse_write_bit()` with `ZYNQMP_EFUSE_WRITE=1`. + +Programming is report-only unless `ZYNQMP_EFUSE_BURN=1` is set: wolfBoot prints `eFuse: would program USER_n (row r) bits 0x...` and the stored value does not change. Do not burn the per-row write-lock fuses (`MISC_USER_CTRL`, row 16) for these rows, as that would freeze the counter. + ### PUF state reporting With `ZYNQMP_SEC=1` the eFuse dump reports `PUF_MISC` (eFuse cache `0x1054`), which carries the 24-bit AUX field with the PUF control bits above it: `REG_DIS` (registration permanently disabled), `SYN_WRLK` (helper data locked against programming) and `SYN_INVLD` (eFuse helper data invalidated). All three are one-shot, so together they say whether a part can still be provisioned. diff --git a/docs/compile.md b/docs/compile.md index 86bb23bbb2..8abec78e56 100644 --- a/docs/compile.md +++ b/docs/compile.md @@ -525,6 +525,22 @@ A dual-boot target that loads the image to RAM (two fixed slots, no swap, `src/u `DUALBOOT_ROLLBACK_UNCONFIRMED=1` lets that fallback go to a lower version: the other slot boots, and the unconfirmed slot is erased once that image has passed verification. If the other slot fails verification, the unconfirmed image is kept and booted again. The version check for confirmed images is unchanged. The option is not available with the hardware-assisted swap loader. The trade-off is that someone able to reset the board during the probation window can keep it on the older image, which `ALLOW_DOWNGRADE=0` otherwise prevents once the newer one has been written. +### Production build guard + +`WOLFBOOT_PRODUCTION=1` turns the options that disable or weaken verification into build errors instead of warnings: `SIGN=NONE`, `WOLFBOOT_SKIP_BOOT_VERIFY=1`, `ALLOW_DOWNGRADE=1`, `DUALBOOT_ROLLBACK_UNCONFIRMED=1`, `WOLFBOOT_UDS_UID_FALLBACK_FORTEST=1`, and `-DDEBUG_CSU` in `CFLAGS_EXTRA` (which enables JTAG on ZynqMP). +It also defines `WOLFBOOT_PRODUCTION` for the code, which a HAL can use to refuse a device that is not locked down: on ZynqMP, `ZYNQMP_SEC_POLICY` refuses to boot a part whose eFuses lack the required bits only in a production build (see the ZynqMP section of [Targets](Targets.md)). +With `KEY_REVOCATION=1` or `SECURITY_VERSION=1`, a production build also stops when a confirmed image's revocation mask or security version cannot be stored, since the next boot would otherwise accept images that image meant to retire; other builds print the error and boot. The ZynqMP report-only eFuse mode (without `ZYNQMP_EFUSE_BURN`) counts as stored. + +### Boot stage timing + +`BOOT_BENCHMARK=1` prints the time of each step as it runs (image load, decryption, integrity and signature checks), and on the RAM and disk boot paths also records a timestamp per stage, in microseconds of `hal_get_timer_us()`: `entry` (when `wolfBoot_start()` begins, after `hal_init()`), and the end of `load`, `decrypt`, `hash`, `verify` and `handoff` (just before `hal_prepare_boot()` and the jump to the payload). At that point wolfBoot prints one summary line, with the `entry` time and the time each stage added: + +``` +Boot times (us): entry= load=
decrypt=
hash=
verify=
handoff=
total=
+``` + +A stage that did not run shows 0, and `load` includes any earlier slot that failed verification. On targets whose counter starts at reset (the AArch64 generic timer on ZynqMP, started by `psu_init`), `entry` is the time spent before wolfBoot. On the disk boot path of a target that hands the payload a device tree, the stamps also go to the OS as `/chosen/wolfboot,boot-times`, six big-endian 32-bit values in that stage order, so a deployed system can report its boot cost from `/proc/device-tree/chosen/wolfboot,boot-times`. + ### Linux kernel command line (bootargs) On the FIT Linux-boot targets whose DTB comes from the signed FIT (Versal, ZynqMP, PolarFire SoC), a DTB that already carries a non-empty `/chosen/bootargs` keeps it by default - the image boots with the arguments its kernel was validated with, and wolfBoot logs `FDT: using DTB bootargs: ...`. Three macros control this: diff --git a/docs/firmware_update.md b/docs/firmware_update.md index 47919548db..a301e7ba72 100644 --- a/docs/firmware_update.md +++ b/docs/firmware_update.md @@ -48,6 +48,23 @@ Failing to set the BOOT partition to `STATE_SUCCESS` before the next reboot trig Roll-back is initiated by the bootloader by triggering a new update, this time starting from the backup copy of the original (pre-update) firmware, which is now stored in the UPDATE partition due to the swap occurring earlier. +### Security version floor + +The version check above compares the update with the image already in the BOOT partition, so it cannot stop an older image that reaches the device by another path, such as a reflash or a failover to the other slot. With `SECURITY_VERSION=1`, every image is also checked against a security version floor that the HAL keeps in storage the device cannot decrement (eFuse, OTP, TPM NV counter): + +```c +int hal_get_security_version(uint32_t *svn); /* non-zero: unreadable, reject */ +int hal_set_security_version(uint32_t svn); /* may only raise */ +``` + +The security version is a separate number from the firmware version, carried in the signature-covered `HDR_SECURITY_VERSION` (0x37) TLV and raised only for releases that fix a vulnerability: + +``` +./tools/keytools/sign --ecc384 --sha384 --custom-tlv 0x37 4 3 image.bin key.der 12 +``` + +An image without the TLV has security version 0. Any image below the floor is rejected on every boot path, including the update candidate before it is installed, and so is an image above the highest floor the storage can hold (`WOLFBOOT_SECURITY_VERSION_MAX`: 64 with the TPM backend, 32 per eFuse row on ZynqMP). With `STAGE1_AUTH=1` the first-stage loader checks only the signature of stage 2; the floor and the revocation mask apply to the images stage 2 boots. The floor is raised to the image's security version only once that image is confirmed, so an unconfirmed update can still roll back. Only an application image (`HDR_IMG_TYPE_APP`) raises it, so a key the keystore limits to another partition id cannot. If an update is staged before the confirmed image has rebooted, wolfBoot verifies the confirmed image and raises the floor first, so the update is checked against it. The simulator stores the floor in `sim_security_version.dd`. With `WOLFBOOT_TPM_POLICY_NV=1` the floor is kept in a TPM NV bit-field index (default 0x01400402) as one bit per level, so it can reach 64 and the TPM itself prevents it from decreasing; see the Key revocation section of [keystore.md](keystore.md) for how the index is protected. + ### Building a new firmware image Firmware images are position-dependent, and can only boot from the origin of the **BOOT** partition in FLASH. diff --git a/docs/keystore.md b/docs/keystore.md index 858b3be8e4..f27fb5d371 100644 --- a/docs/keystore.md +++ b/docs/keystore.md @@ -226,6 +226,29 @@ To support this mode of operation, the `keygen` tool supports the `--nolocalkeys On Microchip PolarFire SoC the trust anchor can be served from the System Controller secure NVM (sNVM) instead of being compiled into the bootloader, using the `SNVM_KEYSTORE` backend. See [PolarFire.md](PolarFire.md#hardware-root-of-trust-puf-kek-snvm-keystore-wrapped-image-key). +## Key revocation + +With `KEY_REVOCATION=1`, wolfBoot rejects any image whose signing key occupies a revoked keystore slot. The set of revoked slots is a 32-bit mask (bit n = slot n) that the HAL keeps in storage the device cannot clear, such as OTP, eFuse, or a TPM NV index with a write-once policy. The HAL provides two functions: + +```c +uint32_t hal_get_revoked_keys(void); +int hal_set_revoked_keys(uint32_t revoked); /* may only add bits */ +``` + +A key is revoked by an update signed with a key that is still valid, carrying the mask in the signature-covered `HDR_KEY_REVOKE` (0x36) TLV: + +``` +./tools/keytools/sign --ecc384 --sha384 --custom-tlv 0x36 4 0x1 image.bin key1.der 2 +``` + +The mask is applied at boot only after that image is confirmed (`wolfBoot_success()`), and only from an application image (`HDR_IMG_TYPE_APP`), so a key the keystore limits to another partition id cannot revoke keys; and an unconfirmed update can still fall back to an image signed by the old key. If an update is staged before the confirmed image has rebooted, wolfBoot verifies the confirmed image and applies its mask first, so the update is checked against it. A request to revoke a slot that signed the carrying image (either key of a hybrid signature) is refused, and an `HDR_KEY_REVOKE` TLV outside the signed part of the header makes the image invalid. Rotation is therefore: provision a keystore with spare slots, sign the next release with a spare key and the revoke mask for the old one, and confirm it. + +The simulator stores the mask in `sim_revoked_keys.dd`. + +On a target with a TPM, `WOLFBOOT_TPM_POLICY_NV=1` keeps the mask in a TPM NV bit-field index (`TPM_NT_BITS`, default 0x01400401). wolfBoot creates it under the platform hierarchy on the first revocation and writes it only with `TPM2_NV_SetBits`, which the TPM never lets clear a bit. An index that wolfBoot did not create (other attributes or hierarchy), or one that cannot be read, makes every key count as revoked. Before handing off, wolfBoot disables the platform hierarchy so the OS cannot delete the index; a replaced TPM starts with no keys revoked. `tools/tpm/policy_nv` prints the stored values for testing. + +`KEY_REVOCATION` and `SECURITY_VERSION` need the verifying key to be a keystore slot, so the build refuses them with Renesas TSIP/RSIP, the wolfHSM client, and wolfHSM server certificate chain verification. They are also not supported with `DUALBANK_SWAP`. + ## Build System Integration By default, when running `make` to build the default target (`factory.bin`) for the first time, wolfBoot automatically generates a signing keypair and creates a single-key keystore as a "demonstration". This is distinct from using `keygen` directly with `-g` or `-i` options, which provides full control over keystore creation. diff --git a/hal/sim.c b/hal/sim.c index 469e1d3593..d2458f5e8d 100644 --- a/hal/sim.c +++ b/hal/sim.c @@ -559,6 +559,72 @@ int hal_flash_erase(uintptr_t address, int len) return 0; } +#if defined(WOLFBOOT_KEY_REVOCATION) && !defined(WOLFBOOT_TPM_POLICY_NV) +/* Emulates write-once storage: bits can be set, never cleared. */ +#define SIM_REVOKED_KEYS_FILE "./sim_revoked_keys.dd" + +uint32_t hal_get_revoked_keys(void) +{ + uint32_t value = 0; + int fd = open(SIM_REVOKED_KEYS_FILE, O_RDONLY); + if (fd == -1) + return 0; + if (pread(fd, &value, sizeof(value), 0) != (ssize_t)sizeof(value)) + value = 0; + close(fd); + return value; +} + +int hal_set_revoked_keys(uint32_t revoked) +{ + int ret = -1; + int fd; + revoked |= hal_get_revoked_keys(); + fd = open(SIM_REVOKED_KEYS_FILE, O_RDWR | O_CREAT, 0644); + if (fd == -1) + return -1; + if (pwrite(fd, &revoked, sizeof(revoked), 0) == (ssize_t)sizeof(revoked)) + ret = 0; + close(fd); + return ret; +} +#endif + +#if defined(WOLFBOOT_SECURITY_VERSION) && !defined(WOLFBOOT_TPM_POLICY_NV) +/* Emulates a monotonic counter: the stored floor never decreases. */ +#define SIM_SECURITY_VERSION_FILE "./sim_security_version.dd" + +int hal_get_security_version(uint32_t *svn) +{ + uint32_t value = 0; + int fd = open(SIM_SECURITY_VERSION_FILE, O_RDONLY); + if (fd != -1) { + if (pread(fd, &value, sizeof(value), 0) != (ssize_t)sizeof(value)) + value = 0; + close(fd); + } + *svn = value; + return 0; +} + +int hal_set_security_version(uint32_t svn) +{ + uint32_t cur = 0; + int ret = -1; + int fd; + (void)hal_get_security_version(&cur); + if (svn <= cur) + return 0; + fd = open(SIM_SECURITY_VERSION_FILE, O_RDWR | O_CREAT, 0644); + if (fd == -1) + return -1; + if (pwrite(fd, &svn, sizeof(svn), 0) == (ssize_t)sizeof(svn)) + ret = 0; + close(fd); + return ret; +} +#endif + void hal_init(void) { int ret; diff --git a/hal/zynq.c b/hal/zynq.c index 600a5f6ce8..03597ab922 100644 --- a/hal/zynq.c +++ b/hal/zynq.c @@ -36,6 +36,7 @@ #include #include "aarch64_arch.h" #include "image.h" +#include "loader.h" #include "printf.h" #include "hal_fpga.h" @@ -395,6 +396,258 @@ uint32_t pmu_efuse_read(uint32_t offset, uint32_t* data, uint32_t size) return ret_payload[0]; /* 0=Success, 30=No Access */ } +#if defined(WOLFBOOT_SECURITY_VERSION) || defined(WOLFBOOT_KEY_REVOCATION) || \ + defined(WOLFBOOT_ZYNQMP_SEC_STATE) +#if defined(WOLFBOOT_ZYNQMP_FSBL) +uint32_t pmu_mmio_read(uint32_t addr); +#endif + +/* Pre-fill for a PMU eFuse read: for some fields (SEC_CTRL, PUF_MISC) the + * PMU firmware reports success but writes the word only when it was built + * with the matching XSK_ACCESS_* option, so an untouched word must be told + * apart from a read of zero. */ +#define ZYNQMP_EFUSE_READ_UNSET 0xFFFFFFFFUL + +/* Read 'words' words of the eFuse cache at 'offset' from ZYNQMP_EFUSE_BASE: + * directly as the FSBL, through the PMU firmware as BL33. */ +static int zynqmp_efuse_cache_read(uint32_t offset, uint32_t *val, + uint32_t words) +{ + uint32_t i; +#if defined(WOLFBOOT_ZYNQMP_FSBL) + for (i = 0; i < words; i++) { + val[i] = pmu_mmio_read(ZYNQMP_EFUSE_BASE + offset + + (i * (uint32_t)sizeof(uint32_t))); + } + return 0; +#else + pmu_efuse* cmd = (pmu_efuse*)efuseBuf; + uint32_t* data = (uint32_t*)(efuseBuf + sizeof(pmu_efuse)); + uint32_t ret_payload[PM_ARGS_CNT]; + uint64_t cmd_ptr = (uint64_t)(uintptr_t)cmd; + + if ((words == 0U) || (words * sizeof(uint32_t) > + (sizeof(efuseBuf) - sizeof(pmu_efuse)))) { + return -1; + } + memset(ret_payload, 0, sizeof(ret_payload)); + memset(efuseBuf, 0, sizeof(efuseBuf)); + for (i = 0; i < words; i++) { + data[i] = ZYNQMP_EFUSE_READ_UNSET; + } + cmd->src = (uint64_t)(uintptr_t)data; + cmd->offset = offset & 0xFF; + cmd->size = words; + cmd->flag = 0; + flush_dcache_range((unsigned long)efuseBuf, + (unsigned long)efuseBuf + sizeof(efuseBuf)); + pmu_request(PM_EFUSE_ACCESS, (uint32_t)(cmd_ptr >> 32), + (uint32_t)(cmd_ptr & 0xFFFFFFFF), 0, 0, ret_payload); + flush_dcache_range((unsigned long)efuseBuf, + (unsigned long)efuseBuf + sizeof(efuseBuf)); + if (ret_payload[0] != 0U || ret_payload[1] != 0U) { + return -1; + } + for (i = 0; i < words; i++) { + val[i] = data[i]; + } + return 0; +#endif +} +#endif + +#if defined(WOLFBOOT_SECURITY_VERSION) || defined(WOLFBOOT_KEY_REVOCATION) +/* Device policy in the user eFuses USER_0..USER_7 (OTP page 0, rows 8-15, + * cache 0x1020-0x103C). Which rows hold the security version counter and the + * revocation mask is a provisioning decision, so the build must name them. */ +#define ZYNQMP_EFUSE_USER_ROWS 8 +#define ZYNQMP_EFUSE_USER_ROW0 8 +#define ZYNQMP_EFUSE_USER_OFFSET(i) (0x1020U + ((uint32_t)(i) * 4U)) + +/* Number of set bits across the counter rows: the security version floor. + * Fuses only ever go from 0 to 1, so the count can never decrease. */ +uint32_t zynqmp_efuse_counter_value(const uint32_t *rows, int nrows) +{ + uint32_t n = 0; + int i; + for (i = 0; i < nrows; i++) { + uint32_t w = rows[i]; + while (w != 0U) { + w &= (w - 1U); + n++; + } + } + return n; +} + +/* Bits to program so that the counter reaches 'target', taking the lowest + * clear bits first. Returns -1 if the rows cannot hold 'target'. */ +int zynqmp_efuse_counter_bits(const uint32_t *rows, uint32_t *add, int nrows, + uint32_t target) +{ + uint32_t have = zynqmp_efuse_counter_value(rows, nrows); + int i, b; + + for (i = 0; i < nrows; i++) + add[i] = 0; + if (target > (uint32_t)nrows * 32U) + return -1; + for (i = 0; (i < nrows) && (have < target); i++) { + for (b = 0; (b < 32) && (have < target); b++) { + if ((rows[i] & (1UL << b)) == 0U) { + add[i] |= (1UL << b); + have++; + } + } + } + return 0; +} + +static int zynqmp_user_efuse_read(int idx, uint32_t *val) +{ + if (zynqmp_efuse_cache_read(ZYNQMP_EFUSE_USER_OFFSET(idx), val, 1) != 0) { + wolfBoot_printf("eFuse: USER_%d read failed; PMUFW needs " + "ENABLE_EFUSE_ACCESS and XSK_ACCESS_USER_EFUSE\n", idx); + return -1; + } + return 0; +} + +/* Program the given 1-bits of a user eFuse row. Report-only unless + * ZYNQMP_EFUSE_BURN is set, as for every other eFuse write in this HAL. */ +static int zynqmp_user_efuse_program(int idx, uint32_t bits) +{ + if (bits == 0U) + return 0; +#ifndef ZYNQMP_EFUSE_BURN + wolfBoot_printf("eFuse: would program USER_%d (row %d) bits 0x%08x\n", + idx, ZYNQMP_EFUSE_USER_ROW0 + idx, bits); + return 0; +#elif defined(WOLFBOOT_ZYNQMP_FSBL) + { + #ifdef WOLFBOOT_ZYNQMP_EFUSE_WRITE + int b; + for (b = 0; b < 32; b++) { + if ((bits & (1UL << b)) != 0U) { + if (zynqmp_efuse_write_bit(0, ZYNQMP_EFUSE_USER_ROW0 + idx, + (uint32_t)b) != 0) + return -1; + } + } + return 0; + #else + (void)idx; + wolfBoot_printf("eFuse: FSBL build needs ZYNQMP_EFUSE_WRITE=1\n"); + return -1; + #endif + } +#else + { + pmu_efuse* cmd = (pmu_efuse*)efuseBuf; + uint32_t* data = (uint32_t*)(efuseBuf + sizeof(pmu_efuse)); + uint32_t ret_payload[PM_ARGS_CNT]; + uint64_t cmd_ptr = (uint64_t)(uintptr_t)cmd; + + memset(ret_payload, 0, sizeof(ret_payload)); + memset(efuseBuf, 0, sizeof(efuseBuf)); + *data = bits; + cmd->src = (uint64_t)(uintptr_t)data; + cmd->offset = ZYNQMP_EFUSE_USER_OFFSET(idx) & 0xFF; + cmd->size = 1; + cmd->flag = 1; + flush_dcache_range((unsigned long)efuseBuf, + (unsigned long)efuseBuf + sizeof(efuseBuf)); + pmu_request(PM_EFUSE_ACCESS, (uint32_t)(cmd_ptr >> 32), + (uint32_t)(cmd_ptr & 0xFFFFFFFF), 0, 0, ret_payload); + if (ret_payload[0] != 0U || ret_payload[1] != 0U) { + wolfBoot_printf("eFuse: USER_%d program failed (%u/%u)\n", idx, + ret_payload[0], ret_payload[1]); + return -1; + } + return 0; + } +#endif +} +#endif /* WOLFBOOT_SECURITY_VERSION || WOLFBOOT_KEY_REVOCATION */ + +#ifdef WOLFBOOT_SECURITY_VERSION +#if !defined(ZYNQMP_EFUSE_SVN_ROW) || !defined(ZYNQMP_EFUSE_SVN_NROWS) +#error "SECURITY_VERSION needs ZYNQMP_EFUSE_SVN_ROW and ZYNQMP_EFUSE_SVN_NROWS" +#endif +#if (ZYNQMP_EFUSE_SVN_ROW < 0) || (ZYNQMP_EFUSE_SVN_NROWS < 1) || \ + ((ZYNQMP_EFUSE_SVN_ROW + ZYNQMP_EFUSE_SVN_NROWS) > ZYNQMP_EFUSE_USER_ROWS) +#error "ZYNQMP_EFUSE_SVN_ROW/NROWS must stay within USER_0..USER_7" +#endif + +int hal_get_security_version(uint32_t *svn) +{ + uint32_t rows[ZYNQMP_EFUSE_SVN_NROWS]; + int i; + + for (i = 0; i < ZYNQMP_EFUSE_SVN_NROWS; i++) { + if (zynqmp_user_efuse_read(ZYNQMP_EFUSE_SVN_ROW + i, &rows[i]) != 0) + return -1; + } + *svn = zynqmp_efuse_counter_value(rows, ZYNQMP_EFUSE_SVN_NROWS); + return 0; +} + +int hal_set_security_version(uint32_t svn) +{ + uint32_t rows[ZYNQMP_EFUSE_SVN_NROWS]; + uint32_t add[ZYNQMP_EFUSE_SVN_NROWS]; + int i; + + for (i = 0; i < ZYNQMP_EFUSE_SVN_NROWS; i++) { + if (zynqmp_user_efuse_read(ZYNQMP_EFUSE_SVN_ROW + i, &rows[i]) != 0) + return -1; + } + if (zynqmp_efuse_counter_bits(rows, add, ZYNQMP_EFUSE_SVN_NROWS, + svn) != 0) { + wolfBoot_printf("eFuse: security version %u exceeds %d counter bits\n", + (unsigned)svn, ZYNQMP_EFUSE_SVN_NROWS * 32); + return -1; + } + for (i = 0; i < ZYNQMP_EFUSE_SVN_NROWS; i++) { + if (zynqmp_user_efuse_program(ZYNQMP_EFUSE_SVN_ROW + i, add[i]) != 0) + return -1; + } + return 0; +} +#endif /* WOLFBOOT_SECURITY_VERSION */ + +#ifdef WOLFBOOT_KEY_REVOCATION +#ifndef ZYNQMP_EFUSE_REVOKE_ROW +#error "KEY_REVOCATION needs ZYNQMP_EFUSE_REVOKE_ROW" +#endif +#if (ZYNQMP_EFUSE_REVOKE_ROW < 0) || \ + (ZYNQMP_EFUSE_REVOKE_ROW >= ZYNQMP_EFUSE_USER_ROWS) +#error "ZYNQMP_EFUSE_REVOKE_ROW must be a USER row index 0..7" +#endif +#if defined(WOLFBOOT_SECURITY_VERSION) && \ + (ZYNQMP_EFUSE_REVOKE_ROW >= ZYNQMP_EFUSE_SVN_ROW) && \ + (ZYNQMP_EFUSE_REVOKE_ROW < (ZYNQMP_EFUSE_SVN_ROW + ZYNQMP_EFUSE_SVN_NROWS)) +#error "ZYNQMP_EFUSE_REVOKE_ROW overlaps the security version rows" +#endif + +uint32_t hal_get_revoked_keys(void) +{ + uint32_t val = 0; + /* Unreadable store: treat every key as revoked rather than none. */ + if (zynqmp_user_efuse_read(ZYNQMP_EFUSE_REVOKE_ROW, &val) != 0) + return 0xFFFFFFFFU; + return val; +} + +int hal_set_revoked_keys(uint32_t revoked) +{ + uint32_t cur = 0; + if (zynqmp_user_efuse_read(ZYNQMP_EFUSE_REVOKE_ROW, &cur) != 0) + return -1; + return zynqmp_user_efuse_program(ZYNQMP_EFUSE_REVOKE_ROW, revoked & ~cur); +} +#endif /* WOLFBOOT_KEY_REVOCATION */ + /* PMU-mediated MMIO. As the FSBL wolfBoot runs at EL3 with no ATF beneath it, * so the SMC/PMU path is unavailable -- access the register directly (the CSU, * eFuse and clock/reset regs these are used for are EL3-accessible, matching @@ -440,7 +693,7 @@ int pmu_mmio_wait(uint32_t addr, uint32_t wait_mask, uint32_t wait_val, return (timeout < tries) ? 0 : -1; } -#ifdef WOLFBOOT_ZYNQMP_FSBL_SEC +#if defined(WOLFBOOT_ZYNQMP_FSBL_SEC) || defined(WOLFBOOT_ZYNQMP_SEC_STATE) /* Snapshot of the device security state, read from the eFuse cache that the * BootROM loads at power-on. */ typedef struct zynqmp_sec_state { @@ -463,6 +716,32 @@ static int zynqmp_sec_state_get(zynqmp_sec_state* state) } memset(state, 0, sizeof(*state)); +#ifndef WOLFBOOT_ZYNQMP_FSBL_SEC + /* As BL33 the BootROM loaded the cache long before, and STATUS is not + * reachable through the PMU firmware. The policy depends on SEC_CTRL + * alone, so only that read has to succeed. The firmware fills the PUF and + * PPK0 fields only when built with XSK_ACCESS_SECURE_CRITICAL_EFUSE and + * XSK_ACCESS_KEY_MANAGE_EFUSE, and masks SEC_CTRL to the bits those grant; + * a masked bit reads as not set, so a part can only look less locked. */ + if ((zynqmp_efuse_cache_read(ZYNQMP_EFUSE_SEC_CTRL - ZYNQMP_EFUSE_BASE, + &state->sec_ctrl, 1) != 0) || + (state->sec_ctrl == ZYNQMP_EFUSE_READ_UNSET)) { + state->sec_ctrl = 0; + return -1; + } + state->status = ZYNQMP_EFUSE_STATUS_CACHE_DONE; + (void)zynqmp_efuse_cache_read(ZYNQMP_EFUSE_PUF_CHASH - ZYNQMP_EFUSE_BASE, + &state->puf_chash, 1); + if ((zynqmp_efuse_cache_read(ZYNQMP_EFUSE_PUF_MISC - ZYNQMP_EFUSE_BASE, + &state->puf_misc, 1) != 0) || + (state->puf_misc == ZYNQMP_EFUSE_READ_UNSET)) { + state->puf_misc = 0; + } + (void)zynqmp_efuse_cache_read(ZYNQMP_EFUSE_PPK0_0 - ZYNQMP_EFUSE_BASE, + state->ppk0_hash, ZYNQMP_EFUSE_PPK0_WORDS); + (void)i; + return 0; +#else /* Require CACHE_LOAD clear as well as CACHE_DONE set: a reload still in * flight can leave a stale done flag, and reading it would hand back an * unfinished snapshot. Matches the wait in the programming path. */ @@ -481,6 +760,7 @@ static int zynqmp_sec_state_get(zynqmp_sec_state* state) (uint32_t)((uint32_t)i * sizeof(uint32_t))); } return 0; +#endif } void zynqmp_efuse_dump(void) @@ -490,10 +770,15 @@ void zynqmp_efuse_dump(void) int i; if (zynqmp_sec_state_get(&state) != 0) { +#ifdef WOLFBOOT_ZYNQMP_FSBL_SEC /* state.status holds the value the check acted on; re-reading could * print a different one. */ wolfBoot_printf("eFuse: cache not loaded (STATUS 0x%08x)\n", state.status); +#else + wolfBoot_printf("eFuse: SEC_CTRL not returned by the PMU firmware " + "(needs ENABLE_EFUSE_ACCESS, XSK_ACCESS_SECURE_CRITICAL_EFUSE)\n"); +#endif return; } sec = state.sec_ctrl; @@ -557,7 +842,37 @@ int zynqmp_sec_policy_check(uint32_t required) } return 0; } -#endif /* WOLFBOOT_ZYNQMP_FSBL_SEC */ + +#if defined(ZYNQMP_SEC_POLICY) && defined(__WOLFBOOT) +/* Outcome of the boot-time policy check, published to the OS in /chosen */ +static int zynqmp_sec_policy_met = 0; + +/* A WOLFBOOT_PRODUCTION build refuses a part whose SEC_CTRL lacks a bit of + * ZYNQMP_SEC_POLICY. Any other build boots it as a development unit, and the + * OS can tell it apart by /chosen/wolfboot,sec-policy = 0. */ +static void zynqmp_sec_policy_enforce(void) +{ + if (zynqmp_sec_policy_check((uint32_t)(ZYNQMP_SEC_POLICY)) == 0) { + zynqmp_sec_policy_met = 1; + wolfBoot_printf("eFuse policy 0x%08x met\n", + (uint32_t)(ZYNQMP_SEC_POLICY)); + return; + } +#ifdef WOLFBOOT_PRODUCTION + wolfBoot_printf("eFuse policy 0x%08x not met: refusing to boot\n", + (uint32_t)(ZYNQMP_SEC_POLICY)); +#ifdef WOLFBOOT_PERSIST_FAILURE_STATUS + (void)wolfBoot_record_failure(WOLFBOOT_FAILURE_PHASE_BOOT, + WOLFBOOT_FAILURE_CAUSE_POLICY, 0, 0); +#endif + wolfBoot_panic(); +#else + wolfBoot_printf("eFuse policy 0x%08x not met: booting as a development " + "unit\n", (uint32_t)(ZYNQMP_SEC_POLICY)); +#endif +} +#endif /* ZYNQMP_SEC_POLICY && __WOLFBOOT */ +#endif /* WOLFBOOT_ZYNQMP_FSBL_SEC || WOLFBOOT_ZYNQMP_SEC_STATE */ #ifdef WOLFBOOT_ZYNQMP_EFUSE_WRITE /* Raw SysMon reading for one PS channel. Supply channels read 0 until the @@ -2786,6 +3101,45 @@ static void zynq_phy_init(void) #endif /* WOLFBOOT_ZYNQMP_PHY_INIT */ /* public HAL functions */ +#if defined(HAVE_FIPS) && defined(HAVE_ENTROPY_MEMUSE) +#include +/* FIPS DRBG entropy seed. The ZynqMP PS has no TRNG, so the seed comes from + * the module's CPU-jitter entropy source (cntvct_el0 timing, with startup and + * continuous health tests). Registered via CUSTOM_RAND_GENERATE_SEED in + * include/user_settings.h. */ +int wolfBoot_fips_seed(unsigned char* output, unsigned int sz) +{ + return (wc_Entropy_Get(MAX_ENTROPY_BITS, output, sz) == 0) ? 0 : -1; +} +#endif + +#ifdef HAVE_FIPS +/* The FIPS module pulls in newlib malloc (FIPS_NOSYS_SPECS=1). Bound the heap + * to the .heap region in hal/zynq.ld so it cannot grow into the image load + * area. */ +extern unsigned char _heap_start[]; +extern unsigned char _heap_end[]; +void* _sbrk(int incr); +void* _sbrk(int incr) +{ + static unsigned char* brk = _heap_start; + unsigned char* prev = brk; + + if (incr < 0) { + if ((size_t)(-incr) > (size_t)(brk - _heap_start)) + brk = _heap_start; + else + brk += incr; + return (void*)prev; + } + if ((size_t)(brk - _heap_start) + (size_t)incr > + (size_t)(_heap_end - _heap_start)) + return (void*)-1; + brk += incr; + return (void*)prev; +} +#endif + void hal_init(void) { const char* bootMsg = "\nwolfBoot Secure Boot\n"; @@ -2866,6 +3220,13 @@ void hal_init(void) #endif #endif +#if defined(WOLFBOOT_ZYNQMP_SEC_STATE) && !defined(WOLFBOOT_ZYNQMP_FSBL) + zynqmp_efuse_dump(); +#endif +#if defined(ZYNQMP_SEC_POLICY) && defined(__WOLFBOOT) + zynqmp_sec_policy_enforce(); +#endif + #if defined(WOLFBOOT_ZYNQMP_BBRAM) && defined(WOLFBOOT_ZYNQMP_BBRAM_SELFTEST) (void)zynqmp_bbram_test(); #endif @@ -3241,6 +3602,9 @@ int hal_dts_fixup(void* dts_addr, uint32_t capacity) { fdt_ctx ctx; int ret; +#ifdef WOLFBOOT_ZYNQMP_SEC_STATE + zynqmp_sec_state state; +#endif /* Validate the blob against the window it actually occupies. Every * bound the parser applies below comes from `capacity`, not from the @@ -3270,6 +3634,27 @@ int hal_dts_fixup(void* dts_addr, uint32_t capacity) wolfBoot_printf("FDT: Failed to set bootargs (%d)\n", ret); return ret; } +#ifdef WOLFBOOT_ZYNQMP_SEC_STATE + /* Let the OS tell a part that is not locked down from one that is. An + * unreadable state is published as 0, never left to a value the DTB + * already carried. */ + if (zynqmp_sec_state_get(&state) != 0) { + state.sec_ctrl = 0; + } + ret = fdt_fixup_chosen_val(&ctx, "wolfboot,sec-ctrl", state.sec_ctrl); + if (ret != 0) { + wolfBoot_printf("FDT: Failed to set wolfboot,sec-ctrl (%d)\n", ret); + return ret; + } +#endif +#ifdef ZYNQMP_SEC_POLICY + ret = fdt_fixup_chosen_val(&ctx, "wolfboot,sec-policy", + (uint32_t)zynqmp_sec_policy_met); + if (ret != 0) { + wolfBoot_printf("FDT: Failed to set wolfboot,sec-policy (%d)\n", ret); + return ret; + } +#endif #ifdef WOLFBOOT_UPDATE_DISK (void)wolfBoot_disk_dts_fixup(&ctx); #endif diff --git a/hal/zynq.h b/hal/zynq.h index 6bc63f90c9..6a3a16628c 100644 --- a/hal/zynq.h +++ b/hal/zynq.h @@ -880,8 +880,9 @@ static inline int zynqmp_l2_block_range(uint64_t start, uint64_t end, } /* Device security state, and BBRAM AES key provisioning. Defined in hal/zynq.c - * under WOLFBOOT_ZYNQMP_FSBL_SEC and WOLFBOOT_ZYNQMP_BBRAM respectively. */ -#ifdef WOLFBOOT_ZYNQMP_FSBL_SEC + * under WOLFBOOT_ZYNQMP_FSBL_SEC or WOLFBOOT_ZYNQMP_SEC_STATE, and + * WOLFBOOT_ZYNQMP_BBRAM respectively. */ +#if defined(WOLFBOOT_ZYNQMP_FSBL_SEC) || defined(WOLFBOOT_ZYNQMP_SEC_STATE) void zynqmp_efuse_dump(void); /* 0 when every bit in "required" is set in SEC_CTRL */ int zynqmp_sec_policy_check(uint32_t required); diff --git a/include/hal.h b/include/hal.h index 813426ef2f..93650470cd 100644 --- a/include/hal.h +++ b/include/hal.h @@ -90,10 +90,33 @@ uint64_t hal_get_timer_us(void); wolfBoot_printf(msg " (%lu ms)\r\n", (unsigned long)_elapsed_ms); \ (void)_elapsed_ms; \ } while(0) + /* Per-stage boot timestamps in microseconds of hal_get_timer_us(): when + * wolfBoot_start() began (ENTRY) and when each later stage ended. 0 marks + * a stage that did not run. On targets whose counter starts at reset the + * ENTRY stamp is the time spent in the boot stages before wolfBoot. */ + #define BOOT_TIME_ENTRY 0 + #define BOOT_TIME_LOAD 1 + #define BOOT_TIME_DECRYPT 2 + #define BOOT_TIME_HASH 3 + #define BOOT_TIME_VERIFY 4 + #define BOOT_TIME_HANDOFF 5 + #define BOOT_TIME_STAGES 6 + extern uint32_t wolfBoot_boot_times[BOOT_TIME_STAGES]; + void wolfBoot_boot_times_print(void); + #define BOOT_TIME_MARK(stage) \ + (wolfBoot_boot_times[(stage)] = (uint32_t)hal_get_timer_us()) + /* A new load attempt replaces whatever an earlier slot recorded */ + #define BOOT_TIME_RESTART() do { \ + int _st; \ + for (_st = BOOT_TIME_LOAD; _st < BOOT_TIME_STAGES; _st++) \ + wolfBoot_boot_times[_st] = 0; \ + } while(0) #else #define BENCHMARK_DECLARE() do {} while(0) #define BENCHMARK_START() do {} while(0) #define BENCHMARK_END(msg) wolfBoot_printf(msg "\r\n") + #define BOOT_TIME_MARK(stage) do {} while(0) + #define BOOT_TIME_RESTART() do {} while(0) #endif #ifdef ARCH_64BIT @@ -142,6 +165,38 @@ int ext_flash_is_erased(uintptr_t address, int len); * Return 0 on success, or a negative value on failure. */ int hal_flash_protect(haladdr_t address, int len); + +#ifdef WOLFBOOT_KEY_REVOCATION +/* + * Revoked keystore slots, bit n = slot n, kept in storage the device cannot + * clear (OTP, eFuse, TPM NV with a write-once policy). Set may only add bits. + */ +uint32_t hal_get_revoked_keys(void); +int hal_set_revoked_keys(uint32_t revoked); +#endif + +#ifdef WOLFBOOT_SECURITY_VERSION +/* + * Security version floor, kept in storage the device cannot decrement. + * Get returns non-zero if the floor cannot be read (images are then + * rejected); set may only raise it. + */ +int hal_get_security_version(uint32_t *svn); +int hal_set_security_version(uint32_t svn); + +/* Highest floor the backend can store; an image above it is rejected rather + * than booted with no floor. */ +#ifndef WOLFBOOT_SECURITY_VERSION_MAX + #if defined(WOLFBOOT_TPM_POLICY_NV) + #define WOLFBOOT_SECURITY_VERSION_MAX 64U + #elif defined(ZYNQMP_EFUSE_SVN_NROWS) + #define WOLFBOOT_SECURITY_VERSION_MAX \ + ((uint32_t)ZYNQMP_EFUSE_SVN_NROWS * 32U) + #else + #define WOLFBOOT_SECURITY_VERSION_MAX 0xFFFFFFFFU + #endif +#endif +#endif void hal_prepare_boot(void); /* Re-attribute [start,end) non-cacheable, for memory shared with a diff --git a/include/image.h b/include/image.h index 4939305b7e..a2e09b6f5e 100644 --- a/include/image.h +++ b/include/image.h @@ -1768,6 +1768,34 @@ void RAMFUNCTION wolfBoot_invalidate_hdr_cache(void); /* Find the key slot ID based on the SHA hash of the key. */ int keyslot_id_by_sha(const uint8_t *hint); +#if defined(WOLFBOOT_KEY_REVOCATION) || defined(WOLFBOOT_SECURITY_VERSION) +#if defined(WOLFBOOT_NO_SIGN) || defined(WOLFBOOT_RENESAS_SCEPROTECT) || \ + defined(WOLFBOOT_NO_KEYSTORE) +#error "KEY_REVOCATION and SECURITY_VERSION need signature verification and the built-in keystore" +#endif +#if defined(WOLFBOOT_RENESAS_TSIP) || defined(WOLFBOOT_RENESAS_RSIP) || \ + defined(WOLFBOOT_ENABLE_WOLFHSM_CLIENT) || \ + (defined(WOLFBOOT_ENABLE_WOLFHSM_SERVER) && \ + defined(WOLFBOOT_CERT_CHAIN_VERIFY)) +#error "KEY_REVOCATION and SECURITY_VERSION need a keystore slot for the verifying key" +#endif +#ifdef DUALBANK_SWAP +#error "KEY_REVOCATION and SECURITY_VERSION are not supported with DUALBANK_SWAP" +#endif +#define WOLFBOOT_CONFIRMED_IMAGE_HOOKS +#endif + +#ifdef WOLFBOOT_CONFIRMED_IMAGE_HOOKS +/* Apply the device policy carried by a verified boot image (key revocation, + * security version floor). + * Nothing is applied unless the boot path reports the image as confirmed, + * i.e. its state was SUCCESS when it was selected. */ +void wolfBoot_apply_confirmed_image(struct wolfBoot_image *img, int confirmed); +/* Verify a confirmed image that a trial update is about to replace or bypass + * and apply its policy first, so the update is checked against it. */ +int wolfBoot_commit_confirmed_image(struct wolfBoot_image *img); +#endif + #ifdef EXT_FLASH # ifdef PART_BOOT_EXT # define BOOT_EXT 1 diff --git a/include/tpm.h b/include/tpm.h index 7b3a2f2e52..f4a1cb3805 100644 --- a/include/tpm.h +++ b/include/tpm.h @@ -43,6 +43,12 @@ extern WOLFTPM2_KEY wolftpm_srk; #ifndef WOLFBOOT_TPM_BOOT_STATE_NV_BASE #define WOLFBOOT_TPM_BOOT_STATE_NV_BASE 0x01400400 #endif +#ifndef WOLFBOOT_TPM_REVOKE_NV_INDEX + #define WOLFBOOT_TPM_REVOKE_NV_INDEX 0x01400401 +#endif +#ifndef WOLFBOOT_TPM_SVN_NV_INDEX + #define WOLFBOOT_TPM_SVN_NV_INDEX 0x01400402 +#endif /* The PCR bank algorithm and its digest size must always agree. They used to * be defined together under a single #ifndef on the algorithm, which meant * overriding only WOLFBOOT_TPM_PCR_ALG left WOLFBOOT_TPM_PCR_DIG_SZ undefined @@ -140,6 +146,11 @@ int CSME_NSE_API wolfBoot_tpm2_parse_attest(const TPM2B_ATTEST* in, TPMS_ATTEST* /* Internal wolfBoot TPM API's */ int wolfBoot_tpm2_init(void); void wolfBoot_tpm2_deinit(void); +#ifdef WOLFBOOT_TPM_POLICY_NV +/* Disables the platform hierarchy so the OS cannot undefine the policy NV + * indices (src/tpm_policy_nv.c). */ +int wolfBoot_tpm_policy_nv_lock(void); +#endif int wolfBoot_tpm2_clear(void); diff --git a/include/user_settings.h b/include/user_settings.h index e30f81bf70..81685ff835 100644 --- a/include/user_settings.h +++ b/include/user_settings.h @@ -72,8 +72,12 @@ #define HAVE_AESCCM #define HAVE_AES_ECB /* AES CAST uses wc_AesEcbEncrypt */ #define HAVE_AES_CBC /* AES-CBC CAST */ - #define WOLFSSL_AES_COUNTER - #define WOLFSSL_AES_DIRECT + #ifndef WOLFSSL_AES_COUNTER + #define WOLFSSL_AES_COUNTER + #endif + #ifndef WOLFSSL_AES_DIRECT + #define WOLFSSL_AES_DIRECT + #endif #define WOLFSSL_AES_CFB #define WOLFSSL_AES_OFB #define WOLFSSL_AES_XTS @@ -86,9 +90,12 @@ #define WOLFSSL_KEY_GEN #define WOLFSSL_PUBLIC_MP #define WOLFSSL_SP_MATH_ALL - /* Use native 64-bit SP digits on 64-bit targets (portable C via __uint128_t; - * NOT the ARM64 SP asm, which sits outside the validated FIPS boundary and - * is disabled by NO_ARM_ASM). Without this, WOLFSSL_SP_MATH_ALL leaves the + /* With ARMv8 asm in the module (options.mk), use the ARM64 SP ECC code. */ + #if defined(__aarch64__) && defined(WOLFSSL_ARMASM) + #define WOLFSSL_HAVE_SP_ECC + #endif + /* Use native 64-bit SP digits on 64-bit targets (portable C via __uint128_t + * when NO_ARM_ASM). Without this, WOLFSSL_SP_MATH_ALL leaves the * word-size gate further below - which keys off WOLFSSL_HAVE_SP_ECC/RSA, * neither set in the FIPS build - unselected, so ECDSA verify would regress * to 32-bit limbs (~4x the multiply work) on the boot-critical path. */ @@ -361,9 +368,10 @@ extern int tolower(int c); #define WOLFSSL_PUBLIC_MP - /* Curve */ + /* Curve. FIPS keeps P-256: the module's ECDHE self-test is fixed to it. */ # if defined(WOLFBOOT_ENABLE_PK_ECC256) || defined(WOLFCRYPT_SECURE_MODE) || \ - defined(WOLFCRYPT_TEST) || defined(WOLFCRYPT_BENCHMARK) + defined(WOLFCRYPT_TEST) || defined(WOLFCRYPT_BENCHMARK) || \ + defined(HAVE_FIPS) # define HAVE_ECC256 # endif # if defined(WOLFBOOT_ENABLE_PK_ECC384) || \ diff --git a/include/wolfboot/wolfboot.h b/include/wolfboot/wolfboot.h index 0d554bd88c..7724cf08b2 100644 --- a/include/wolfboot/wolfboot.h +++ b/include/wolfboot/wolfboot.h @@ -330,6 +330,12 @@ extern "C" { /* Signature-covered digest of a raw (non-FIT) device tree, binding it to this * image. Length = image hash size (WOLFBOOT_SHA_DIGEST_SIZE). */ #define HDR_DEVICE_TREE_DIGEST 0x35 +/* Signature-covered 32-bit mask of keystore slots to revoke on this device + * (bit n = slot n), applied once the carrying image is confirmed. */ +#define HDR_KEY_REVOKE 0x36 +/* Signature-covered 32-bit security version, checked against a monotonic + * device floor that is raised once the carrying image is confirmed. */ +#define HDR_SECURITY_VERSION 0x37 #define HDR_PADDING 0xFF /* HDR_IMG_COMPRESSION algorithm ids */ @@ -847,6 +853,14 @@ int wolfBoot_get_partition_state(uint8_t part, uint8_t *st); #define WOLFBOOT_FAILURE_CAUSE_SIGNATURE 3 /* signature/auth check failed */ #define WOLFBOOT_FAILURE_CAUSE_NOT_CONFIRMED 4 /* image never confirmed via * wolfBoot_success() */ +#define WOLFBOOT_FAILURE_CAUSE_DECRYPT 5 /* image could not be + * decrypted */ +#define WOLFBOOT_FAILURE_CAUSE_VERSION 6 /* below the version floor or + * a refused downgrade */ +#define WOLFBOOT_FAILURE_CAUSE_POLICY 7 /* device security state does + * not meet the build policy */ +#define WOLFBOOT_FAILURE_CAUSE_READ 8 /* image could not be read + * from storage */ /* Persisted failure record. */ struct wolfBoot_failure_record { diff --git a/options.mk b/options.mk index 46ae658032..41dcc533f3 100644 --- a/options.mk +++ b/options.mk @@ -376,6 +376,12 @@ ifeq ($(WOLFBOOT_PERSIST_FAILURE_STATUS),1) ifeq ($(WOLFBOOT_DIAGNOSTICS_EXT),1) CFLAGS+=-D"WOLFBOOT_DIAGNOSTICS_EXT" endif + ifneq ($(WOLFBOOT_DIAGNOSTICS_DISK_PART),) + ifeq ($(WOLFBOOT_DIAGNOSTICS_EXT),1) + $(error WOLFBOOT_DIAGNOSTICS_DISK_PART and WOLFBOOT_DIAGNOSTICS_EXT are exclusive) + endif + CFLAGS+=-D"WOLFBOOT_DIAGNOSTICS_DISK_PART=$(WOLFBOOT_DIAGNOSTICS_DISK_PART)" + endif endif # Support for TPM signature verification @@ -603,6 +609,9 @@ ifeq ($(SIGN),ECC384) else ifneq ($(SPMATH),1) STACK_USAGE=11248 + else ifeq ($(ARCH),AARCH64) + # sp_arm64.c sp_384_ecc_mulmod_win_add_sub_6 needs 11232 with GCC 13 + STACK_USAGE=11264 else STACK_USAGE=11216 endif @@ -1352,6 +1361,29 @@ else ifeq ($(WATCHDOG_HANDOFF),1) $(error WATCHDOG_HANDOFF requires WATCHDOG=1) endif +ifeq ($(KEY_REVOCATION),1) + CFLAGS+= -D"WOLFBOOT_KEY_REVOCATION" +endif + +ifeq ($(SECURITY_VERSION),1) + CFLAGS+= -D"WOLFBOOT_SECURITY_VERSION" +endif + +# Key revocation and security version storage in TPM NV bit-field indices +ifeq ($(WOLFBOOT_TPM_POLICY_NV),1) + ifeq ($(filter 1,$(KEY_REVOCATION) $(SECURITY_VERSION)),) + $(error WOLFBOOT_TPM_POLICY_NV=1 needs KEY_REVOCATION=1 or SECURITY_VERSION=1) + endif + ifneq ($(WOLFTPM),1) + $(error WOLFBOOT_TPM_POLICY_NV=1 needs WOLFTPM=1) + endif + ifeq ($(TARGET),zynq) + $(error WOLFBOOT_TPM_POLICY_NV=1 is not supported on zynq, which keeps the policy in user eFuses) + endif + CFLAGS+= -D"WOLFBOOT_TPM_POLICY_NV" + OBJS+=./src/tpm_policy_nv.o +endif + ifeq ($(ALLOW_DOWNGRADE),1) $(warning ALLOW_DOWNGRADE=1 disables anti-rollback enforcement; signed older firmware images can replace newer ones) CFLAGS+= -D"ALLOW_DOWNGRADE" @@ -2722,26 +2754,17 @@ ifeq ($(FIPS),1) # clean-style goals (which do not compile/link) so 'make clean' still works # with FIPS=1 in .config. ifeq ($(filter %clean,$(MAKECMDGOALS)),) - # NO_ARM_ASM is an ARM-only knob; the FIPS module is portable C on every - # arch, but only the ARM/AArch64 builds have an asm crypto path to disable - # (which would sit outside the validated module boundary). Force it on rather - # than erroring when unset, so this works regardless of include order - # (test-app/Makefile includes options.mk before arch.mk, so NO_ARM_ASM is - # still empty here). Only an explicit NO_ARM_ASM=0 is a hard error. - ifneq ($(filter ARM AARCH64,$(ARCH)),) + # AArch64 links the module's ARMv8 asm inside the boundary (FIPS_ASM_OBJS + # below). 32-bit ARM has no asm objects wired into the boundary, so it must + # build the portable-C module: force NO_ARM_ASM there, and fail closed if + # arch.mk (included first) already selected the asm path. + ifeq ($(ARCH),ARM) ifeq ($(NO_ARM_ASM),0) - $(error FIPS=1 on $(ARCH) requires NO_ARM_ASM=1 (the FIPS module uses portable-C crypto); NO_ARM_ASM=0 was set) + $(error FIPS=1 on ARM requires NO_ARM_ASM=1; NO_ARM_ASM=0 was set) endif NO_ARM_ASM=1 - # Fail closed on include order: the top-level Makefile includes arch.mk - # BEFORE options.mk, so if NO_ARM_ASM was unset when arch.mk ran (e.g. - # TARGET=zynq/versal/nxp_ls1028a) it has already pulled the ARM asm crypto - # path into CFLAGS/OBJS - which the WOLFCRYPT_OBJS := reset below does NOT - # remove. Force-setting NO_ARM_ASM above is too late to unwind that, so - # refuse rather than link asm inside the validated boundary. Set - # NO_ARM_ASM=1 in your .config / on the command line (arch.mk sees it first). ifneq ($(filter -DWOLFSSL_ARMASM,$(CFLAGS)),) - $(error FIPS=1 on $(ARCH): ARM asm crypto (-DWOLFSSL_ARMASM) was already selected before options.mk; set NO_ARM_ASM=1 explicitly so arch.mk sees it first (see docs/FIPS.md)) + $(error FIPS=1 on ARM: ARM asm crypto (-DWOLFSSL_ARMASM) was already selected before options.mk; set NO_ARM_ASM=1 explicitly so arch.mk sees it first (see docs/FIPS.md)) endif endif # Only the ECDSA object set is wired into the FIPS boundary below. RSA-PSS @@ -2759,8 +2782,15 @@ ifeq ($(FIPS),1) ifneq ($(strip $(AUX_PK_ALGOS)),) $(error FIPS=1 does not support auxiliary public-key algorithms (AUX_PK_ALGOS=$(AUX_PK_ALGOS)); see docs/FIPS.md) endif + # Image encryption uses the module's own AES-CTR (aes.o is inside the + # boundary below). ChaCha20 and the PKCS#11 cipher are not in the module. ifeq ($(ENCRYPT),1) - $(error FIPS=1 does not support the image ENCRYPT path (its ChaCha/AES objects sit outside the FIPS boundary); see docs/FIPS.md) + ifeq ($(ENCRYPT_PKCS11),1) + $(error FIPS=1 does not support ENCRYPT_PKCS11 (the cipher runs outside the FIPS module); see docs/FIPS.md) + endif + ifeq ($(filter 1,$(ENCRYPT_WITH_AES128) $(ENCRYPT_WITH_AES256)),) + $(error FIPS=1 with ENCRYPT=1 requires ENCRYPT_WITH_AES128=1 or ENCRYPT_WITH_AES256=1 (ChaCha20 is not in the FIPS module); see docs/FIPS.md) + endif endif ifeq ($(WOLFTPM),1) $(error FIPS=1 with WOLFTPM is not supported) @@ -2827,17 +2857,40 @@ ifeq ($(FIPS),1) endif # The FIPS module pulls in libc malloc/printf. On a bare-metal newlib target, # stub the syscalls with nosys.specs; the HAL provides a bounded _sbrk so the - # heap cannot grow into the unverified image (rpi_common.c). This is WRONG for + # heap cannot grow into the unverified image (rpi_common.c, zynq.c). This is WRONG for # a hosted / glibc-cross toolchain, so make it opt-in per target rather than # "every non-sim ARCH" - a new bare-metal FIPS target sets FIPS_NOSYS_SPECS=1. FIPS_NOSYS_SPECS ?= 0 - ifneq ($(filter cm4 cm5,$(TARGET)),) + # Seed the DRBG from the module's CPU-jitter entropy source (wolfentropy.c) + # on targets with no hardware TRNG; the HAL's wolfBoot_fips_seed() reads it. + FIPS_ENTROPY_MEMUSE ?= 0 + ifeq ($(TARGET),zynq) + FIPS_ENTROPY_MEMUSE = 1 + endif + ifeq ($(FIPS_ENTROPY_MEMUSE),1) + CFLAGS+=-DHAVE_ENTROPY_MEMUSE + endif + ifneq ($(filter cm4 cm5 zynq,$(TARGET)),) FIPS_NOSYS_SPECS = 1 endif ifeq ($(FIPS_NOSYS_SPECS),1) LDFLAGS += --specs=nosys.specs endif WCDIR=$(WOLFBOOT_LIB_WOLFSSL)/wolfcrypt/src + # ARMv8 assembly is part of the module (processor algorithm acceleration); + # keep it inside the boundary between wolfcrypt_first.o and wolfcrypt_last.o. + FIPS_ASM_OBJS := + ifeq ($(ARCH),AARCH64) + ifneq ($(NO_ARM_ASM),1) + FIPS_ASM_OBJS := \ + $(WCDIR)/cpuid.o \ + $(WCDIR)/port/arm/armv8-aes-asm_c.o \ + $(WCDIR)/port/arm/armv8-sha256-asm_c.o \ + $(WCDIR)/port/arm/armv8-sha512-asm_c.o \ + $(WCDIR)/port/arm/armv8-sha3-asm_c.o \ + $(WCDIR)/sp_arm64.o + endif + endif WOLFCRYPT_OBJS := \ $(WCDIR)/wolfcrypt_first.o \ $(WCDIR)/hash.o \ @@ -2845,6 +2898,7 @@ ifeq ($(FIPS),1) $(WCDIR)/kdf.o \ $(WCDIR)/pwdbased.o \ $(WCDIR)/random.o \ + $(if $(filter 1,$(FIPS_ENTROPY_MEMUSE)),$(WCDIR)/wolfentropy.o) \ $(WCDIR)/sha.o \ $(WCDIR)/sha256.o \ $(WCDIR)/sha512.o \ @@ -2853,6 +2907,7 @@ ifeq ($(FIPS),1) $(WCDIR)/cmac.o \ $(WCDIR)/ecc.o \ $(WCDIR)/sp_int.o \ + $(FIPS_ASM_OBJS) \ $(WCDIR)/wolfmath.o \ $(WCDIR)/memory.o \ $(WCDIR)/wc_port.o \ @@ -2865,3 +2920,32 @@ ifeq ($(FIPS),1) $(WCDIR)/fips_test.o \ $(WCDIR)/wolfcrypt_last.o endif + +# Production build guard: refuse options that disable or weaken verification +# instead of only warning about them. +ifeq ($(WOLFBOOT_PRODUCTION),1) + CFLAGS+=-DWOLFBOOT_PRODUCTION + ifeq ($(SIGN),NONE) + $(error WOLFBOOT_PRODUCTION=1 forbids SIGN=NONE) + endif + ifeq ($(WOLFBOOT_SKIP_BOOT_VERIFY),1) + $(error WOLFBOOT_PRODUCTION=1 forbids WOLFBOOT_SKIP_BOOT_VERIFY=1) + endif + ifeq ($(ALLOW_DOWNGRADE),1) + $(error WOLFBOOT_PRODUCTION=1 forbids ALLOW_DOWNGRADE=1) + endif + ifeq ($(DUALBOOT_ROLLBACK_UNCONFIRMED),1) + $(error WOLFBOOT_PRODUCTION=1 forbids DUALBOOT_ROLLBACK_UNCONFIRMED=1) + endif + ifeq ($(WOLFBOOT_UDS_UID_FALLBACK_FORTEST),1) + $(error WOLFBOOT_PRODUCTION=1 forbids WOLFBOOT_UDS_UID_FALLBACK_FORTEST=1) + endif + ifneq ($(filter -DDEBUG_CSU -DDEBUG_CSU=%,$(subst ",,$(CFLAGS_EXTRA))),) + $(error WOLFBOOT_PRODUCTION=1 forbids DEBUG_CSU, which enables JTAG) + endif + ifeq ($(TARGET),zynq) + ifeq ($(ZYNQMP_SEC_POLICY),) + $(warning WOLFBOOT_PRODUCTION=1 without ZYNQMP_SEC_POLICY: the eFuse security state is not enforced) + endif + endif +endif diff --git a/src/boot_state.c b/src/boot_state.c index 9c44dafbea..edc4463bae 100644 --- a/src/boot_state.c +++ b/src/boot_state.c @@ -224,7 +224,10 @@ void boot_state_lock(void) /* On every boot, even with nothing written or the state unreadable, so * the OS can never move the floor. */ if (boot_state_backend_lock() != 0) { -#if defined(WOLFBOOT_ANTI_ROLLBACK_HALT_ON_FAILURE) +#if defined(WOLFBOOT_ANTI_ROLLBACK_HALT_ON_FAILURE) || \ + defined(WOLFBOOT_TPM_POLICY_NV) + /* With the policy indices in the TPM, platform auth left enabled + * lets the OS undefine them */ boot_state_log("could not lock anti-rollback state, refusing to boot"); /* Never returns. */ wolfBoot_panic(); diff --git a/src/image.c b/src/image.c index d770b417c8..aef63daa55 100644 --- a/src/image.c +++ b/src/image.c @@ -2953,6 +2953,54 @@ int wolfBoot_verify_authenticity(struct wolfBoot_image *img) return 0; } #else +#ifdef WOLFBOOT_CONFIRMED_IMAGE_HOOKS +/* Policy TLVs count only if they end before the digest TLV, where the signed + * part of the header ends. Returns the length, 0 if absent, -1 otherwise. */ +static int get_signed_policy_header(struct wolfBoot_image *img, uint16_t type, + uint8_t **ptr) +{ + uint8_t *digest = NULL; + uint16_t len = get_header(img, type, ptr); + + if (len == 0) + return 0; + if ((*ptr == NULL) || + (get_header(img, WOLFBOOT_SHA_HDR, &digest) == 0) || + (digest == NULL) || + (*ptr + len > digest - 2 * sizeof(uint16_t))) { + return -1; + } + return (int)len; +} +#endif + +#ifdef WOLFBOOT_SECURITY_VERSION +/* An image without the TLV has security version 0. */ +static int image_security_version(struct wolfBoot_image *img, uint32_t *svn) +{ + uint8_t *tlv = NULL; + int len = get_signed_policy_header(img, HDR_SECURITY_VERSION, &tlv); + + *svn = 0; + if (len == 0) + return 0; + if (len != (int)sizeof(uint32_t)) + return -1; + *svn = (uint32_t)tlv[0] | ((uint32_t)tlv[1] << 8) | + ((uint32_t)tlv[2] << 16) | ((uint32_t)tlv[3] << 24); + return 0; +} +#endif + +#ifdef WOLFBOOT_KEY_REVOCATION +static int key_slot_revoked(int key_slot) +{ + if ((key_slot < 0) || (key_slot >= 32)) + return 1; + return (hal_get_revoked_keys() & (1U << key_slot)) != 0U; +} +#endif + int wolfBoot_verify_authenticity(struct wolfBoot_image *img) { uint8_t *stored_signature; @@ -3009,6 +3057,11 @@ int wolfBoot_verify_authenticity(struct wolfBoot_image *img) if (key_slot < 0) { return -1; /* Key was not found */ } + #ifdef WOLFBOOT_KEY_REVOCATION + if (key_slot_revoked(key_slot)) { + return -1; /* Key revoked on this device */ + } + #endif #ifdef WOLFBOOT_TPM_KEYSTORE if (wolfBoot_check_rot(key_slot, pubkey_hint) != 0) { @@ -3034,6 +3087,24 @@ int wolfBoot_verify_authenticity(struct wolfBoot_image *img) * way so that skipping the re-check above (or its result) cannot let an * image with an unverified digest reach signature verification. */ SHA_SANITY_CHECK(img); +#ifdef WOLFBOOT_SECURITY_VERSION + { + uint32_t svn, svn_floor; + if ((image_security_version(img, &svn) != 0) || + (hal_get_security_version(&svn_floor) != 0) || + (svn < svn_floor) || (svn > WOLFBOOT_SECURITY_VERSION_MAX)) { + /* Below the floor, or above what the device can store */ + return -1; + } + } +#endif +#ifdef WOLFBOOT_KEY_REVOCATION + { + uint8_t *revoke = NULL; + if (get_signed_policy_header(img, HDR_KEY_REVOKE, &revoke) < 0) + return -1; /* Revocation mask outside the signed header */ + } +#endif image_part = image_type & HDR_IMG_TYPE_PART_MASK; #ifdef WOLFBOOT_NO_KEYSTORE /* No local keystore is linked: there is no per-key partition permission @@ -3180,6 +3251,11 @@ int wolfBoot_verify_authenticity(struct wolfBoot_image *img) if (key_slot < 0) { return -1; /* Key was not found */ } + #ifdef WOLFBOOT_KEY_REVOCATION + if (key_slot_revoked(key_slot)) { + return -1; /* Key revoked on this device */ + } + #endif key_mask = keystore_get_mask(key_slot); if (((1U << image_part) & key_mask) != (1U << image_part)) { return -1; /* Key not allowed to verify this partition id */ @@ -3307,4 +3383,120 @@ int keyslot_id_by_sha(const uint8_t *hint) } return match_id; } + +#ifdef WOLFBOOT_KEY_REVOCATION +/** + * @brief Apply the key revocation mask carried by a confirmed boot image. + * + * The mask comes from the signature-covered HDR_KEY_REVOKE TLV, so only an + * image signed by a key that is still valid can revoke others. It is applied + * only once the image is confirmed, so a trial image cannot strand the + * fallback image, and never to the slot that signed the image. + * + * @param img The verified, confirmed boot image. + * @return 0 if nothing to do or applied, -1 on a rejected or failed request. + */ +static int wolfBoot_apply_key_revocation(struct wolfBoot_image *img) +{ + uint8_t *tlv = NULL; + uint8_t *hint = NULL; + uint32_t mask, revoked, valid, own_mask; + int own, nkeys, len; + + len = get_signed_policy_header(img, HDR_KEY_REVOKE, &tlv); + if (len == 0) + return 0; + if (len != (int)sizeof(uint32_t)) + return -1; + if (get_header(img, HDR_PUBKEY, &hint) != WOLFBOOT_SHA_DIGEST_SIZE) + return -1; + own = keyslot_id_by_sha(hint); + nkeys = keystore_num_pubkeys(); + if ((own < 0) || (own >= 32) || (nkeys <= 0)) + return -1; + own_mask = 1U << own; +#ifdef SIGN_HYBRID + if (get_header(img, HDR_SECONDARY_PUBKEY, &hint) != + WOLFBOOT_SHA_DIGEST_SIZE) + return -1; + own = keyslot_id_by_sha(hint); + if ((own < 0) || (own >= 32)) + return -1; + own_mask |= 1U << own; +#endif + mask = (uint32_t)tlv[0] | ((uint32_t)tlv[1] << 8) | + ((uint32_t)tlv[2] << 16) | ((uint32_t)tlv[3] << 24); + valid = (nkeys >= 32) ? 0xFFFFFFFFU : ((1U << nkeys) - 1U); + mask &= valid; + if ((mask & own_mask) != 0U) { + wolfBoot_printf("Key revocation refused: mask includes signing key\n"); + return -1; + } + revoked = hal_get_revoked_keys(); + if ((mask & ~revoked) == 0U) + return 0; + wolfBoot_printf("Revoking key slots 0x%x\n", (unsigned)(mask & ~revoked)); + return hal_set_revoked_keys(revoked | mask); +} +#endif /* WOLFBOOT_KEY_REVOCATION */ + +#ifdef WOLFBOOT_SECURITY_VERSION +static int wolfBoot_apply_security_version(struct wolfBoot_image *img) +{ + uint32_t svn, svn_floor; + + if ((image_security_version(img, &svn) != 0) || + (hal_get_security_version(&svn_floor) != 0)) + return -1; + if (svn <= svn_floor) + return 0; + wolfBoot_printf("Raising security version %u -> %u\n", + (unsigned)svn_floor, (unsigned)svn); + return hal_set_security_version(svn); +} +#endif + +#ifdef WOLFBOOT_CONFIRMED_IMAGE_HOOKS +void wolfBoot_apply_confirmed_image(struct wolfBoot_image *img, int confirmed) +{ + int failed = 0; + + /* Only the application image sets device policy: a key the keystore + * limits to another partition id must not revoke keys or raise the + * floor */ + if (!confirmed || (wolfBoot_image_part_matches(img) != 0)) + return; +#ifdef WOLFBOOT_KEY_REVOCATION + if (wolfBoot_apply_key_revocation(img) < 0) { + wolfBoot_printf("Key revocation not applied\n"); + failed = 1; + } +#endif +#ifdef WOLFBOOT_SECURITY_VERSION + if (wolfBoot_apply_security_version(img) < 0) { + wolfBoot_printf("Security version not raised\n"); + failed = 1; + } +#endif +#ifdef WOLFBOOT_PRODUCTION + /* The requested policy is not kept anywhere else: booting on would let + * the next boot accept images it should refuse */ + if (failed) + wolfBoot_panic(); +#else + (void)failed; +#endif +} + +int wolfBoot_commit_confirmed_image(struct wolfBoot_image *img) +{ + if ((wolfBoot_verify_integrity(img) != 0) || + (wolfBoot_verify_authenticity(img) != 0) || + (img->sha_ok != 1U) || (img->signature_ok != 1U)) { + return -1; + } + wolfBoot_apply_confirmed_image(img, 1); + return 0; +} +#endif #endif /* !WOLFBOOT_NO_SIGN && !WOLFBOOT_RENESAS_SCEPROTECT */ diff --git a/src/libwolfboot.c b/src/libwolfboot.c index 1e1b27f34f..b420375cec 100644 --- a/src/libwolfboot.c +++ b/src/libwolfboot.c @@ -31,6 +31,10 @@ #include "wolfboot/wolfboot.h" #include "image.h" #include "printf.h" +#if defined(WOLFBOOT_PERSIST_FAILURE_STATUS) && \ + defined(WOLFBOOT_DIAGNOSTICS_DISK_PART) +#include "disk.h" +#endif #ifdef WATCHDOG /* Weak no-op default; a port HAL overrides this to service the watchdog. @@ -1904,7 +1908,11 @@ void RAMFUNCTION wolfBoot_success(void) #endif #endif /* HAVE_PARTITION_TRAILERS */ -#ifdef WOLFBOOT_PERSIST_FAILURE_STATUS +/* A disk region is read by the OS from the partition itself, so the store is + * only built into wolfBoot there. */ +#if defined(WOLFBOOT_PERSIST_FAILURE_STATUS) && \ + (!defined(WOLFBOOT_DIAGNOSTICS_DISK_PART) || defined(__WOLFBOOT) || \ + defined(UNIT_TEST)) /* Persistent failure diagnostics. * * Failure records are stored in a dedicated region of WOLFBOOT_DIAGNOSTICS_SECTORS @@ -1922,6 +1930,25 @@ void RAMFUNCTION wolfBoot_success(void) * fills it is erased and restarted, discarding all previous records. */ +#ifdef WOLFBOOT_DIAGNOSTICS_DISK_PART +/* The region is a partition of the boot disk, addressed by byte offset */ +#if defined(WOLFBOOT_DIAGNOSTICS_EXT) +#error "WOLFBOOT_DIAGNOSTICS_DISK_PART and WOLFBOOT_DIAGNOSTICS_EXT are exclusive" +#endif +#ifndef WOLFBOOT_DIAGNOSTICS_ADDRESS +#define WOLFBOOT_DIAGNOSTICS_ADDRESS 0 +#endif +/* The drive update_disk.c opens */ +#ifdef BOOT_DISK +#define WOLFBOOT_DIAGNOSTICS_DISK_DRV BOOT_DISK +#else +#define WOLFBOOT_DIAGNOSTICS_DISK_DRV 0 +#endif +#define DIAG_IS_DISK 1 +#else +#define DIAG_IS_DISK 0 +#endif + #ifndef WOLFBOOT_DIAGNOSTICS_ADDRESS #error "WOLFBOOT_PERSIST_FAILURE_STATUS requires WOLFBOOT_DIAGNOSTICS_ADDRESS" #endif @@ -1972,9 +1999,21 @@ typedef char diag_header_size_check[ typedef char diag_record_min_check[(DIAG_RECORD_SIZE >= 16U) ? 1 : -1]; typedef char diag_slots_check[(DIAG_SLOTS_PER_SECTOR >= 1) ? 1 : -1]; +#if DIAG_IS_DISK +/* Erased-flash pattern for the disk region, written in place of an erase */ +static uint8_t diag_disk_erased[512]; +#endif + static int RAMFUNCTION diag_read(haladdr_t addr, void *buf, uint32_t len) { -#if DIAG_IS_EXT +#if DIAG_IS_DISK + if (disk_part_read(WOLFBOOT_DIAGNOSTICS_DISK_DRV, + WOLFBOOT_DIAGNOSTICS_DISK_PART, (uint64_t)addr, len, + (uint8_t *)buf) != (int)len) { + return -1; + } + return (int)len; +#elif DIAG_IS_EXT return ext_flash_read(addr, (uint8_t *)buf, len); #else #ifdef NVM_FLASH_ECC @@ -2070,7 +2109,8 @@ static int RAMFUNCTION diag_ordered(int *order, uint32_t *gen, int *count) static void RAMFUNCTION diag_unlock(void) { -#if DIAG_IS_EXT +#if DIAG_IS_DISK +#elif DIAG_IS_EXT ext_flash_unlock(); #else hal_flash_unlock(); @@ -2079,7 +2119,8 @@ static void RAMFUNCTION diag_unlock(void) static void RAMFUNCTION diag_lock(void) { -#if DIAG_IS_EXT +#if DIAG_IS_DISK +#elif DIAG_IS_EXT ext_flash_lock(); #else hal_flash_lock(); @@ -2089,7 +2130,23 @@ static void RAMFUNCTION diag_lock(void) static int RAMFUNCTION diag_erase(haladdr_t addr, uint32_t len) { int ret; -#if DIAG_IS_EXT +#if DIAG_IS_DISK + uint32_t done = 0, n; + + XMEMSET(diag_disk_erased, FLASH_BYTE_ERASED, sizeof(diag_disk_erased)); + ret = 0; + while ((done < len) && (ret >= 0)) { + n = len - done; + if (n > (uint32_t)sizeof(diag_disk_erased)) + n = (uint32_t)sizeof(diag_disk_erased); + if (disk_part_write(WOLFBOOT_DIAGNOSTICS_DISK_DRV, + WOLFBOOT_DIAGNOSTICS_DISK_PART, (uint64_t)(addr + done), n, + diag_disk_erased) != (int)n) { + ret = -1; + } + done += n; + } +#elif DIAG_IS_EXT ret = ext_flash_erase(addr, len); #else ret = hal_flash_erase(addr, len); @@ -2101,7 +2158,11 @@ static int RAMFUNCTION diag_erase(haladdr_t addr, uint32_t len) static int RAMFUNCTION diag_write(haladdr_t addr, const void *buf, uint32_t len) { int ret; -#if DIAG_IS_EXT +#if DIAG_IS_DISK + ret = (disk_part_write(WOLFBOOT_DIAGNOSTICS_DISK_DRV, + WOLFBOOT_DIAGNOSTICS_DISK_PART, (uint64_t)addr, len, + (const uint8_t *)buf) == (int)len) ? 0 : -1; +#elif DIAG_IS_EXT ret = ext_flash_write(addr, (const uint8_t *)buf, len); #else ret = hal_flash_write(addr, (const uint8_t *)buf, len); @@ -2143,7 +2204,18 @@ static int RAMFUNCTION diag_slot_is_erased(haladdr_t sector_addr, int slot) { haladdr_t addr = sector_addr + DIAG_HDR_SIZE + (haladdr_t)slot * DIAG_RECORD_SIZE; -#if DIAG_IS_EXT +#if DIAG_IS_DISK + uint8_t buf[DIAG_RECORD_SIZE]; + uint32_t i; + + if (diag_read(addr, buf, DIAG_RECORD_SIZE) != (int)DIAG_RECORD_SIZE) + return 0; + for (i = 0; i < DIAG_RECORD_SIZE; i++) { + if (buf[i] != FLASH_BYTE_ERASED) + return 0; + } + return 1; +#elif DIAG_IS_EXT return ext_flash_is_erased(addr, DIAG_RECORD_SIZE) == 1; #else return hal_flash_is_erased(addr, DIAG_RECORD_SIZE) == 1; @@ -3336,8 +3408,11 @@ int aes_init(void) XMEMSET(&aes_enc, 0, sizeof(aes_enc)); XMEMSET(&aes_dec, 0, sizeof(aes_dec)); - wc_AesInit(&aes_enc, NULL, WOLFBOOT_DEVID_CRYPT); - wc_AesInit(&aes_dec, NULL, WOLFBOOT_DEVID_CRYPT); + if ((wc_AesInit(&aes_enc, NULL, WOLFBOOT_DEVID_CRYPT) != 0) || + (wc_AesInit(&aes_dec, NULL, WOLFBOOT_DEVID_CRYPT) != 0)) { + ret = -1; + goto exit; + } if (!encrypt_key_is_valid(key, ENCRYPT_KEY_SIZE)) { ret = -1; @@ -3369,8 +3444,13 @@ int aes_init(void) /* AES_ENCRYPTION is used for both directions in CTR * IV is set later with "wc_AesSetIV" */ - wc_AesSetKeyDirect(&aes_enc, key, ENCRYPT_KEY_SIZE, NULL, AES_ENCRYPTION); - wc_AesSetKeyDirect(&aes_dec, key, ENCRYPT_KEY_SIZE, NULL, AES_ENCRYPTION); + if ((wc_AesSetKeyDirect(&aes_enc, key, ENCRYPT_KEY_SIZE, NULL, + AES_ENCRYPTION) != 0) || + (wc_AesSetKeyDirect(&aes_dec, key, ENCRYPT_KEY_SIZE, NULL, + AES_ENCRYPTION) != 0)) { + ret = -1; + goto exit; + } /* Set global IV nonce used in aes_set_iv */ XMEMCPY(encrypt_iv_nonce, stored_nonce, ENCRYPT_NONCE_SIZE); diff --git a/src/loader.c b/src/loader.c index 5984077f69..e6337445ec 100644 --- a/src/loader.c +++ b/src/loader.c @@ -77,6 +77,39 @@ static void wolfBoot_fipsCb(int ok, int err, const char* hash) } #endif +#ifdef BOOT_BENCHMARK +#include "printf.h" + +uint32_t wolfBoot_boot_times[BOOT_TIME_STAGES]; + +/* One parseable line: the ENTRY stamp, then the time each stage added since + * the previous one that ran, and the total from ENTRY to HANDOFF. */ +void wolfBoot_boot_times_print(void) +{ + static const char* const names[BOOT_TIME_STAGES] = { + "entry", "load", "decrypt", "hash", "verify", "handoff" + }; + uint32_t prev = wolfBoot_boot_times[BOOT_TIME_ENTRY]; + uint32_t t; + int i; + + wolfBoot_printf("Boot times (us): entry=%lu", + (unsigned long)wolfBoot_boot_times[BOOT_TIME_ENTRY]); + for (i = BOOT_TIME_LOAD; i < BOOT_TIME_STAGES; i++) { + t = wolfBoot_boot_times[i]; + wolfBoot_printf(" %s=%lu", names[i], + (unsigned long)((t != 0U) ? (t - prev) : 0U)); + if (t != 0U) { + prev = t; + } + } + wolfBoot_printf(" total=%lu\r\n", + (unsigned long)(prev - wolfBoot_boot_times[BOOT_TIME_ENTRY])); + (void)names; + (void)prev; +} +#endif + #ifdef TARGET_sim /** * @brief Command line arguments for the test-app in sim mode. diff --git a/src/tpm.c b/src/tpm.c index 3df6b66a9c..723d7468e9 100644 --- a/src/tpm.c +++ b/src/tpm.c @@ -28,6 +28,7 @@ #include #include "image.h" +#include "loader.h" #include "printf.h" #include "spi_drv.h" #include "tpm.h" @@ -1784,7 +1785,7 @@ void wolfBoot_tpm2_deinit(void) #ifdef WOLFBOOT_TPM_KEYSTORE /* Anti-rollback has already disabled the platform hierarchy. */ #if !defined(ARCH_SIM) && !defined(WOLFBOOT_TPM_NO_CHG_PLAT_AUTH) && \ - !defined(WOLFBOOT_ANTI_ROLLBACK) + !defined(WOLFBOOT_ANTI_ROLLBACK) && !defined(WOLFBOOT_TPM_POLICY_NV) /* Password (empty platform auth) in slot 0; ChangePlatformAuth puts the * parameter-encryption session in slot 1. */ int rc = wolfTPM2_SetAuthPassword(&wolftpm_dev, 0, NULL); @@ -1801,6 +1802,14 @@ void wolfBoot_tpm2_deinit(void) wolfTPM2_UnloadHandle(&wolftpm_dev, &wolftpm_session.handle); wolfTPM2_UnloadHandle(&wolftpm_dev, &wolftpm_srk.handle); #endif /* WOLFBOOT_TPM_KEYSTORE */ +#if defined(WOLFBOOT_TPM_POLICY_NV) && !defined(WOLFBOOT_ANTI_ROLLBACK) && \ + !defined(ARCH_SIM) + /* With platform auth the OS could undefine the policy indices */ + if (wolfBoot_tpm_policy_nv_lock() != 0) { + wolfBoot_printf("Error locking the TPM platform hierarchy\n"); + wolfBoot_panic(); + } +#endif wolfTPM2_Cleanup(&wolftpm_dev); diff --git a/src/tpm_policy_nv.c b/src/tpm_policy_nv.c new file mode 100644 index 0000000000..6d7f5fe4b2 --- /dev/null +++ b/src/tpm_policy_nv.c @@ -0,0 +1,207 @@ +/* tpm_policy_nv.c + * + * TPM NV backend for the key revocation mask and the security version floor. + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of wolfBoot. + * + * wolfBoot 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. + * + * wolfBoot 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 + */ + +/* Both values live in TPM_NT_BITS indices, written only with TPM2_NV_SetBits: + * the TPM never clears a bit, so neither value can go back, even with + * platform authorization. The security version is unary (bits 0..svn-1). */ + +#include "user_settings.h" + +#ifdef WOLFBOOT_TPM_POLICY_NV + +#include "hal.h" +#include "tpm.h" +#include +#include + +/* A TPM_NT_BITS index holds one UINT64 */ +#define POLICY_NV_SIZE 8 +#define POLICY_NV_ATTR_MASK (TPMA_NV_PLATFORMCREATE | TPMA_NV_PPWRITE | \ + TPMA_NV_OWNERWRITE | TPMA_NV_AUTHWRITE | TPMA_NV_POLICYWRITE | \ + TPMA_NV_TPM_NT | TPMA_NV_CLEAR_STCLEAR | TPMA_NV_ORDERLY) +#define POLICY_NV_ATTR (TPMA_NV_PLATFORMCREATE | TPMA_NV_PPWRITE | \ + ((word32)TPM_NT_BITS << 4)) + +/* Returns 0 with the index value (0 if the index is not defined or never + * written), or -1 if it cannot be read or was not created by this backend. */ +static int policy_nv_read(word32 index, uint64_t *val) +{ + WOLFTPM2_DEV *dev = &wolftpm_dev; + WOLFTPM2_NV nv; + byte buf[POLICY_NV_SIZE]; + word32 readSz = sizeof(buf); + int rc; + int i; + + *val = 0; + memset(&nv, 0, sizeof(nv)); + rc = wolfTPM2_NVOpen(dev, &nv, index, NULL, 0); + if (rc != 0) { + if ((rc & RC_FMT1) && ((rc & RC_MAX_FMT1) == TPM_RC_HANDLE)) { + return 0; + } + return -1; + } + if ((nv.attributes & POLICY_NV_ATTR_MASK) != POLICY_NV_ATTR) { + return -1; + } + /* Defined but not yet set (power lost between create and SetBits) */ + if ((nv.attributes & TPMA_NV_WRITTEN) == 0) { + return 0; + } + wolfTPM2_SetAuthHandle(dev, 0, &nv.handle); + rc = wolfTPM2_NVReadAuth(dev, &nv, index, buf, &readSz, 0); + wolfTPM2_UnsetAuth(dev, 0); + if ((rc != 0) || (readSz != sizeof(buf))) { + return -1; + } + /* NV data is big-endian */ + for (i = 0; i < (int)sizeof(buf); i++) { + *val = (*val << 8) | buf[i]; + } + return 0; +} + +static int policy_nv_set_bits(word32 index, uint64_t bits) +{ + WOLFTPM2_DEV *dev = &wolftpm_dev; + WOLFTPM2_HANDLE parent; + WOLFTPM2_NV nv; + NV_SetBits_In in; + word32 nvAttributes = 0; + int rc; + + if (bits == 0) { + return 0; + } + memset(&parent, 0, sizeof(parent)); + memset(&nv, 0, sizeof(nv)); + parent.hndl = TPM_RH_PLATFORM; + + wolfTPM2_GetNvAttributesTemplate(TPM_RH_PLATFORM, &nvAttributes); + nvAttributes &= ~(TPMA_NV_AUTHWRITE | TPMA_NV_TPM_NT); + nvAttributes |= ((word32)TPM_NT_BITS << 4); + + /* Created on first write (trust on first use) */ + rc = wolfTPM2_NVCreateAuth(dev, &parent, &nv, index, nvAttributes, + POLICY_NV_SIZE, NULL, 0); + if (rc == TPM_RC_NV_DEFINED) { + rc = 0; + } + wolfTPM2_UnsetAuth(dev, 1); + if (rc != 0) { + return -1; + } + + memset(&in, 0, sizeof(in)); + in.authHandle = TPM_RH_PLATFORM; + in.nvIndex = index; + in.bits = bits; + wolfTPM2_SetAuthPassword(dev, 0, NULL); + rc = TPM2_NV_SetBits(&in); + wolfTPM2_UnsetAuth(dev, 0); + if (rc != 0) { + return -1; + } + return 0; +} + +int wolfBoot_tpm_policy_nv_lock(void) +{ + static int locked = 0; + WOLFTPM2_DEV *dev = &wolftpm_dev; + HierarchyControl_In in; + int rc; + + /* Platform auth is gone after the first call */ + if (locked) { + return 0; + } + + /* Disable the platform hierarchy until the next Startup(CLEAR) (TCG PC + * Client Platform spec, section 10): the OS cannot undefine the indices. */ + memset(&in, 0, sizeof(in)); + in.authHandle = TPM_RH_PLATFORM; + in.enable = TPM_RH_PLATFORM; + in.state = 0; + wolfTPM2_SetAuthPassword(dev, 0, NULL); + rc = TPM2_HierarchyControl(&in); + wolfTPM2_UnsetAuth(dev, 0); + if (rc != 0) { + return -1; + } + locked = 1; + return 0; +} + +#ifdef WOLFBOOT_KEY_REVOCATION +uint32_t hal_get_revoked_keys(void) +{ + uint64_t val; + + /* Unreadable or foreign index: treat every key as revoked */ + if (policy_nv_read(WOLFBOOT_TPM_REVOKE_NV_INDEX, &val) != 0) { + return 0xFFFFFFFFU; + } + return (uint32_t)val; +} + +int hal_set_revoked_keys(uint32_t revoked) +{ + return policy_nv_set_bits(WOLFBOOT_TPM_REVOKE_NV_INDEX, revoked); +} +#endif /* WOLFBOOT_KEY_REVOCATION */ + +#ifdef WOLFBOOT_SECURITY_VERSION +int hal_get_security_version(uint32_t *svn) +{ + uint64_t val; + uint32_t n = 0; + + if (svn == NULL) { + return -1; + } + if (policy_nv_read(WOLFBOOT_TPM_SVN_NV_INDEX, &val) != 0) { + return -1; + } + while (val != 0) { + n++; + val >>= 1; + } + *svn = n; + return 0; +} + +int hal_set_security_version(uint32_t svn) +{ + uint64_t bits; + + if (svn > 64U) { + return -1; + } + bits = (svn == 64U) ? ~(uint64_t)0 : (((uint64_t)1 << svn) - 1U); + return policy_nv_set_bits(WOLFBOOT_TPM_SVN_NV_INDEX, bits); +} +#endif /* WOLFBOOT_SECURITY_VERSION */ + +#endif /* WOLFBOOT_TPM_POLICY_NV */ diff --git a/src/update_disk.c b/src/update_disk.c index 684f609271..92566d4567 100644 --- a/src/update_disk.c +++ b/src/update_disk.c @@ -51,6 +51,10 @@ #ifdef DISK_BOOT_CONFIRM #include "disk_trailer.h" #endif +#if defined(WOLFBOOT_CONFIRMED_IMAGE_HOOKS) && \ + !defined(WOLFBOOT_SKIP_BOOT_VERIFY) && defined(DISK_BOOT_CONFIRM) + #define DISK_COMMIT_CONFIRMED +#endif #ifdef WOLFBOOT_DISK_FS #include "disk_fs.h" #endif @@ -162,6 +166,26 @@ static uint8_t disk_encrypt_nonce[ENCRYPT_NONCE_SIZE]; #define GOLDEN_ATTEMPTS 0 #define SLOT_IS_GOLDEN(s) 0 #endif +/* The failure log overwrites its region. In a boot slot's partition it has to + * start past the largest image the slot may hold. */ +#if defined(WOLFBOOT_PERSIST_FAILURE_STATUS) && \ + defined(WOLFBOOT_DIAGNOSTICS_DISK_PART) +#if (WOLFBOOT_DIAGNOSTICS_DISK_PART == BOOT_PART_A) || \ + (WOLFBOOT_DIAGNOSTICS_DISK_PART == BOOT_PART_B) || \ + (defined(DISK_GOLDEN_SLOT) && \ + (WOLFBOOT_DIAGNOSTICS_DISK_PART == BOOT_PART_GOLDEN)) +#if !defined(WOLFBOOT_DIAGNOSTICS_ADDRESS) || \ + !defined(WOLFBOOT_RAMBOOT_MAX_SIZE) || \ + (WOLFBOOT_DIAGNOSTICS_ADDRESS < \ + (IMAGE_HEADER_SIZE + WOLFBOOT_RAMBOOT_MAX_SIZE)) +#error "WOLFBOOT_DIAGNOSTICS_DISK_PART is a boot slot: WOLFBOOT_DIAGNOSTICS_ADDRESS must be at least IMAGE_HEADER_SIZE + WOLFBOOT_RAMBOOT_MAX_SIZE" +#endif +#ifdef WOLFBOOT_DISK_FS +#error "WOLFBOOT_DIAGNOSTICS_DISK_PART cannot be a boot slot with WOLFBOOT_DISK_FS" +#endif +#define DISK_DIAG_IN_SLOT +#endif +#endif /* Under the failover zeroize the image key may already be gone and the golden * image is a plaintext one, so only the operational slots are encrypted. @@ -282,10 +306,11 @@ static uint32_t get_decrypted_blob_version(uint8_t *hdr) * * @param block_offset Block offset for IV counter (0 = start of image). */ -static void disk_crypto_set_iv(uint32_t block_offset) +static int disk_crypto_set_iv(uint32_t block_offset) { + int ret = 0; #if defined(ENCRYPT_WITH_CHACHA) - wc_Chacha_SetIV(&chacha, disk_encrypt_nonce, block_offset); + ret = wc_Chacha_SetIV(&chacha, disk_encrypt_nonce, block_offset); #elif defined(ENCRYPT_WITH_AES128) || defined(ENCRYPT_WITH_AES256) /* For AES CTR, we need to construct the IV with the counter. * The sign tool uses the IV directly without byte-reversal, @@ -307,11 +332,12 @@ static void disk_crypto_set_iv(uint32_t block_offset) iv[14] = (uint8_t)(ctr >> 8); iv[15] = (uint8_t)(ctr); - wc_AesSetIV(&aes_dec, iv); + ret = wc_AesSetIV(&aes_dec, iv); /* Scrub the stack copy: the counter bytes are derived from the * secret disk-encryption nonce (matches aes_set_iv in libwolfboot.c). */ wc_ForceZero(iv, sizeof(iv)); #endif + return ret; } /** @@ -330,10 +356,12 @@ static int decrypt_header(const uint8_t *src, uint8_t *dst) uint32_t magic; /* Reset IV to start of image (block 0) */ - disk_crypto_set_iv(0); + if (disk_crypto_set_iv(0) != 0) + return -1; /* Decrypt header - CTR mode handles counter increment internally */ - crypto_decrypt(dst, src, IMAGE_HEADER_SIZE); + if (crypto_decrypt(dst, src, IMAGE_HEADER_SIZE) != 0) + return -1; magic = *((uint32_t*)dst); if (magic != WOLFBOOT_MAGIC) @@ -347,6 +375,19 @@ static void disk_crypto_clear(void) wc_ForceZero(disk_encrypt_nonce, sizeof(disk_encrypt_nonce)); } +/* The cipher context holds the expanded key; wipe it before the handoff. */ +static void disk_crypto_clear_ctx(void) +{ +#if defined(ENCRYPT_WITH_CHACHA) + wc_ForceZero(&chacha, sizeof(chacha)); +#elif defined(ENCRYPT_WITH_AES128) || defined(ENCRYPT_WITH_AES256) + wc_AesFree(&aes_dec); + wc_AesFree(&aes_enc); + wc_ForceZero(&aes_dec, sizeof(aes_dec)); + wc_ForceZero(&aes_enc, sizeof(aes_enc)); +#endif +} + #ifdef DISK_GOLDEN_ENCRYPT_KEY /* Re-key the cipher and the IV nonce for the slot about to be read. Both are * keyed once up front, which is enough only while every slot shares a key. */ @@ -419,6 +460,85 @@ struct boot_slot { * WOLFBOOT_SMALL_STACK=1. */ static struct boot_slot boot_slots[DISK_SLOTS]; +#ifdef WOLFBOOT_PERSIST_FAILURE_STATUS +/* Cause and slot of the last refusal, reported again if no slot boots */ +static uint8_t disk_last_cause = 0; +static int disk_last_slot = 0; +/* Why the first header read of slot A or B failed, 0 if it did not */ +static uint8_t disk_probe_cause[2]; +/* Set once those are recorded: a retry of the same slot is not recorded */ +static int disk_probe_recorded = 0; +/* Set when the log region cannot be used without overwriting a slot */ +static int disk_diag_off = 0; + +/* Persist why a slot was refused. The partition field holds the slot (0 A, + * 1 B, 2 golden), the version the one its header declared. */ +static void disk_record_failure(uint8_t phase, uint8_t cause, int sel, + uint32_t ver) +{ + disk_last_cause = cause; + disk_last_slot = sel; + if (disk_diag_off) { + return; + } + if (disk_probe_recorded && (phase == WOLFBOOT_FAILURE_PHASE_BOOT) && + (sel < 2) && (disk_probe_cause[sel] != 0)) { + return; + } + if (wolfBoot_record_failure(phase, cause, (uint8_t)sel, ver) != 0) { + wolfBoot_printf("Could not record the failure reason\r\n"); + } +} +/* An all-0x00 or all-0xFF header is an empty slot, not a failure */ +static int disk_hdr_blank(const uint8_t *hdr) +{ + int i; + + if ((hdr[0] != 0x00U) && (hdr[0] != 0xFFU)) { + return 0; + } + for (i = 1; i < IMAGE_HEADER_SIZE; i++) { + if (hdr[i] != hdr[0]) { + return 0; + } + } + return 1; +} + +/* Note why the first read of a slot's header gave no version */ +static void disk_probe_note(int sel, uint8_t cause, uint32_t ver, + const uint8_t *hdr) +{ + if (disk_probe_cause[sel] != 0U) { + return; + } + if (cause == WOLFBOOT_FAILURE_CAUSE_READ) { + disk_probe_cause[sel] = cause; + } + else if ((ver == 0U) && !disk_hdr_blank(hdr)) { + disk_probe_cause[sel] = (cause != 0U) ? cause : + WOLFBOOT_FAILURE_CAUSE_HEADER; + } +} + +static void disk_record_probes(void) +{ + int i; + + for (i = 0; i < 2; i++) { + if (disk_probe_cause[i] != 0U) { + disk_record_failure(WOLFBOOT_FAILURE_PHASE_BOOT, + disk_probe_cause[i], i, 0U); + } + } + disk_probe_recorded = 1; +} +#define DISK_PROBE_NOTE(sel, cause, ver, hdr) \ + disk_probe_note((sel), (cause), (ver), (hdr)) +#else +#define DISK_PROBE_NOTE(sel, cause, ver, hdr) do {} while (0) +#endif + #ifdef DISK_BOOT_CONFIRM /* Boot confirmation for the disk path. include/disk_trailer.h owns the * format: the offset, the magic and the four state values are defined there @@ -566,6 +686,11 @@ static void disk_boot_state_reap(uint32_t *pA_ver, uint32_t *pB_ver) } wolfBoot_printf("Slot %c was not confirmed; skipping it\r\n", 'A' + i); +#ifdef WOLFBOOT_PERSIST_FAILURE_STATUS + disk_record_failure(WOLFBOOT_FAILURE_PHASE_ROLLBACK, + WOLFBOOT_FAILURE_CAUSE_NOT_CONFIRMED, i, + (i == 0) ? *pA_ver : *pB_ver); +#endif slot_reaped[i] = 1; SET_FAILOVER(DISK_FAILOVER_UNCONFIRMED); if (i == 0) { @@ -797,6 +922,28 @@ static const char *disk_boot_file = NULL; * writing the staged DTB here: a HAL may edit a copy of it, and may replace * bootargs wholesale, so a /chosen property set in that pass is what * survives. Nothing is written before a slot has been verified. */ +#ifdef BOOT_BENCHMARK +/* /chosen/wolfboot,boot-times: the BOOT_TIME_* stamps in stage order, in + * microseconds, so the OS can report what the boot chain cost. */ +static int disk_dts_boot_times(fdt_ctx* ctx) +{ + uint32_t be[BOOT_TIME_STAGES]; + int i, off; + + off = fdt_subnode_offset(ctx, 0, "chosen"); + if (off == -FDT_ERR_NOTFOUND) { + off = fdt_add_subnode(ctx, 0, "chosen"); + } + if (off < 0) { + return off; + } + for (i = 0; i < BOOT_TIME_STAGES; i++) { + be[i] = cpu_to_fdt32(wolfBoot_boot_times[i]); + } + return fdt_setprop(ctx, off, "wolfboot,boot-times", be, (int)sizeof(be)); +} +#endif + int wolfBoot_disk_dts_fixup(fdt_ctx* ctx) { int ret; @@ -807,6 +954,13 @@ int wolfBoot_disk_dts_fixup(fdt_ctx* ctx) if (disk_boot_part < 0) { return 0; } +#ifdef BOOT_BENCHMARK + ret = disk_dts_boot_times(ctx); + if (ret != 0) { + wolfBoot_printf("FDT: Failed to set wolfboot,boot-times (%d)\r\n", + ret); + } +#endif ret = fdt_fixup_chosen_val(ctx, "wolfboot,boot-part", (uint32_t)disk_boot_part); if (ret != 0) { @@ -876,6 +1030,90 @@ static const char *disk_signed_cmdline(const uint8_t *hdr) } #endif +#ifdef WOLFBOOT_PERSIST_FAILURE_STATUS +#ifdef WOLFBOOT_DIAGNOSTICS_DISK_PART +/* Same defaults as the store in libwolfboot.c */ +#ifdef WOLFBOOT_DIAGNOSTICS_ADDRESS +#define DISK_DIAG_ADDRESS WOLFBOOT_DIAGNOSTICS_ADDRESS +#else +#define DISK_DIAG_ADDRESS 0 +#endif +#ifdef WOLFBOOT_DIAGNOSTICS_SECTORS +#define DISK_DIAG_SECTORS WOLFBOOT_DIAGNOSTICS_SECTORS +#else +#define DISK_DIAG_SECTORS 2 +#endif +#endif + +static void disk_report_last_failure(void) +{ + struct wolfBoot_failure_record rec; +#ifdef WOLFBOOT_DIAGNOSTICS_DISK_PART + uint64_t sz = 0; + uint64_t end = (uint64_t)DISK_DIAG_ADDRESS + + (uint64_t)DISK_DIAG_SECTORS * (uint64_t)WOLFBOOT_SECTOR_SIZE; +#ifdef WOLFBOOT_DISK_FS +#ifdef DISK_GOLDEN_SLOT + const char *golden; +#endif + int golden_part = -1; +#endif + +#if defined(DISK_DIAG_IN_SLOT) && defined(DISK_BOOT_CONFIRM) + /* The slot's boot state trailer sits in the partition's last bytes */ + end += (uint64_t)DISK_TRAILER_SZ; +#endif + if ((disk_part_size(BOOT_DISK, WOLFBOOT_DIAGNOSTICS_DISK_PART, &sz) != 0) + || (end > sz)) { + wolfBoot_printf("Failure log does not fit partition %d, not " + "recording\r\n", WOLFBOOT_DIAGNOSTICS_DISK_PART); + disk_diag_off = 1; + return; + } +#ifdef WOLFBOOT_DISK_FS + /* A label can resolve a slot to the log's partition at run time */ +#ifdef DISK_GOLDEN_SLOT + golden = BOOT_LABEL_GOLDEN; + golden_part = (golden != NULL) ? slot_find_by_label(golden) : + BOOT_PART_GOLDEN; +#endif + if ((boot_slots[0].part == WOLFBOOT_DIAGNOSTICS_DISK_PART) || + (boot_slots[1].part == WOLFBOOT_DIAGNOSTICS_DISK_PART) || + (golden_part == WOLFBOOT_DIAGNOSTICS_DISK_PART)) { + wolfBoot_printf("Failure log partition %d holds a boot slot, not " + "recording\r\n", WOLFBOOT_DIAGNOSTICS_DISK_PART); + disk_diag_off = 1; + return; + } +#endif +#endif + + if (wolfBoot_get_failure(0, &rec) == 0) { + wolfBoot_printf("Last recorded failure: #%u phase %u cause %u " + "slot %u version %u\r\n", (unsigned int)rec.seq, + (unsigned int)rec.phase, (unsigned int)rec.cause, + (unsigned int)rec.partition, (unsigned int)rec.fw_version); + } +} +/* Neither A nor B has a usable header. Without a golden slot nothing can + * boot. */ +static void disk_record_no_image(void) +{ +#ifndef DISK_GOLDEN_SLOT + disk_record_failure(WOLFBOOT_FAILURE_PHASE_RECOVERY, + (disk_last_cause != 0) ? disk_last_cause : + WOLFBOOT_FAILURE_CAUSE_HEADER, + disk_last_slot, 0U); +#endif +} + +#define DISK_RECORD_FAILURE(phase, cause) \ + disk_record_failure((phase), (cause), selected, \ + (selected == 0) ? pA_ver_u : ((selected == 1) ? pB_ver_u : 0U)) +#else +#define DISK_RECORD_FAILURE(phase, cause) do {} while (0) +#endif + void RAMFUNCTION wolfBoot_start(void) { uint8_t p_hdr[IMAGE_HEADER_SIZE] XALIGNED_STACK(16); @@ -895,6 +1133,11 @@ void RAMFUNCTION wolfBoot_start(void) int selected; uint32_t *load_address; int failures = 0; +#ifdef DISK_COMMIT_CONFIRMED + /* Confirmed slot whose policy is applied before a fresh update in the + * other slot is verified, and that update slot. */ + int commit_slot = -1, trial_slot = -1; +#endif #ifdef DISK_FAILOVER_ZEROIZE int failover_done = 0; #endif @@ -935,6 +1178,7 @@ void RAMFUNCTION wolfBoot_start(void) #endif BENCHMARK_DECLARE(); + BOOT_TIME_MARK(BOOT_TIME_ENTRY); #ifdef DISK_ENCRYPT /* Initialize encryption - this sets up the cipher with key from storage */ if (wolfBoot_initialize_encryption() != 0) { @@ -990,7 +1234,6 @@ void RAMFUNCTION wolfBoot_start(void) wolfBoot_printf("Error opening disk %d\r\n", BOOT_DISK); wolfBoot_panic(); } - #ifdef WOLFBOOT_FSP stage2_params = stage2_get_parameters(); #endif @@ -1032,6 +1275,9 @@ void RAMFUNCTION wolfBoot_start(void) BOOT_FILE_A, slot_max); (void)slot_prepare(&boot_slots[1], BOOT_PART_B, BOOT_LABEL_B, BOOT_FILE_B, slot_max); +#ifdef WOLFBOOT_PERSIST_FAILURE_STATUS + disk_report_last_failure(); +#endif wolfBoot_printf("Checking primary OS image in %d,%d...\r\n", BOOT_DISK, boot_slots[0].part); @@ -1044,10 +1290,17 @@ void RAMFUNCTION wolfBoot_start(void) pA_ver = get_decrypted_blob_version(dec_hdr); slot_note_image(&boot_slots[0], dec_hdr); } + else { + DISK_PROBE_NOTE(0, WOLFBOOT_FAILURE_CAUSE_DECRYPT, 0U, p_hdr); + } #else pA_ver = wolfBoot_get_blob_version((uint8_t*)p_hdr); slot_note_image(&boot_slots[0], p_hdr); #endif + DISK_PROBE_NOTE(0, 0U, pA_ver, p_hdr); + } + else { + DISK_PROBE_NOTE(0, WOLFBOOT_FAILURE_CAUSE_READ, 0U, p_hdr); } wolfBoot_printf("Checking secondary OS image in %d,%d...\r\n", BOOT_DISK, @@ -1061,12 +1314,22 @@ void RAMFUNCTION wolfBoot_start(void) pB_ver = get_decrypted_blob_version(dec_hdr); slot_note_image(&boot_slots[1], dec_hdr); } + else { + DISK_PROBE_NOTE(1, WOLFBOOT_FAILURE_CAUSE_DECRYPT, 0U, p_hdr); + } #else pB_ver = wolfBoot_get_blob_version((uint8_t*)p_hdr); slot_note_image(&boot_slots[1], p_hdr); #endif + DISK_PROBE_NOTE(1, 0U, pB_ver, p_hdr); + } + else { + DISK_PROBE_NOTE(1, WOLFBOOT_FAILURE_CAUSE_READ, 0U, p_hdr); } +#ifdef WOLFBOOT_PERSIST_FAILURE_STATUS + disk_record_probes(); +#endif #ifdef DISK_BOOT_CONFIRM disk_boot_state_reap(&pA_ver, &pB_ver); #endif @@ -1074,6 +1337,9 @@ void RAMFUNCTION wolfBoot_start(void) if ((pB_ver == 0) && (pA_ver == 0)) { wolfBoot_printf("No valid OS image found in either partition %d or %d\r\n", boot_slots[0].part, boot_slots[1].part); +#ifdef WOLFBOOT_PERSIST_FAILURE_STATUS + disk_record_no_image(); +#endif #ifdef DISK_GOLDEN_SLOT /* Straight to the golden slot. A version-0 header is not a bootable * A/B image here any more than it was before this option existed. */ @@ -1109,9 +1375,24 @@ void RAMFUNCTION wolfBoot_start(void) /* Choose partition with higher version */ selected = (pB_ver_u > pA_ver_u) ? 1 : 0; +#ifdef DISK_COMMIT_CONFIRMED + if ((slot_state[selected] == DISK_STATE_UPDATING) && + (slot_state[selected ^ 1] == DISK_STATE_SUCCESS)) { + trial_slot = selected; + commit_slot = selected ^ 1; + selected = commit_slot; + } +#endif do { failures++; +#ifdef DISK_COMMIT_CONFIRMED + if ((commit_slot >= 0) && (selected != commit_slot)) { + /* The confirmed slot failed: boot as if it had not been tried */ + commit_slot = -1; + failures = 1; + } +#endif #ifdef DISK_GOLDEN_SLOT if (failures > MAX_FAILURES) { selected = SLOT_GOLDEN; @@ -1154,6 +1435,8 @@ void RAMFUNCTION wolfBoot_start(void) if (!SLOT_IS_GOLDEN(selected) && slot_reaped[selected]) { wolfBoot_printf("Slot %c was not confirmed; not booting it\r\n", 'A' + selected); + DISK_RECORD_FAILURE(WOLFBOOT_FAILURE_PHASE_ROLLBACK, + WOLFBOOT_FAILURE_CAUSE_NOT_CONFIRMED); SET_FAILOVER(DISK_FAILOVER_UNCONFIRMED); selected ^= 1; continue; @@ -1163,8 +1446,14 @@ void RAMFUNCTION wolfBoot_start(void) { uint32_t cur_ver = selected ? pB_ver_u : pA_ver_u; if (!SLOT_IS_GOLDEN(selected) && (max_ver > 0U) && - (cur_ver < max_ver)) { + (cur_ver < max_ver) +#ifdef DISK_COMMIT_CONFIRMED + && (selected != commit_slot) +#endif + ) { wolfBoot_printf("Rollback to lower version not allowed\r\n"); + DISK_RECORD_FAILURE(WOLFBOOT_FAILURE_PHASE_BOOT, + WOLFBOOT_FAILURE_CAUSE_VERSION); #ifdef DISK_GOLDEN_SLOT /* Nothing newer can boot: only the golden slot is left. */ SET_FAILOVER(DISK_FAILOVER_ROLLBACK); @@ -1197,6 +1486,8 @@ void RAMFUNCTION wolfBoot_start(void) != IMAGE_HEADER_SIZE) { wolfBoot_printf("Error reading image header from disk: p%d\r\n", cur_part); + DISK_RECORD_FAILURE(WOLFBOOT_FAILURE_PHASE_BOOT, + WOLFBOOT_FAILURE_CAUSE_READ); SET_FAILOVER(DISK_FAILOVER_NO_IMAGE); selected ^= 1; continue; @@ -1208,6 +1499,8 @@ void RAMFUNCTION wolfBoot_start(void) /* Each slot carries its own key, so re-key before reading one. */ if (disk_crypto_rekey(selected) != 0) { wolfBoot_printf("Error selecting the key for %s\r\n", part_name); + DISK_RECORD_FAILURE(WOLFBOOT_FAILURE_PHASE_BOOT, + WOLFBOOT_FAILURE_CAUSE_DECRYPT); SET_FAILOVER_IF_UNSET(DISK_FAILOVER_NO_KEY); selected ^= 1; continue; @@ -1221,6 +1514,8 @@ void RAMFUNCTION wolfBoot_start(void) } else if (decrypt_header(p_hdr, dec_hdr) != 0) { wolfBoot_printf("Error decrypting header for %s\r\n", part_name); + DISK_RECORD_FAILURE(WOLFBOOT_FAILURE_PHASE_BOOT, + WOLFBOOT_FAILURE_CAUSE_DECRYPT); SET_FAILOVER(DISK_FAILOVER_NO_IMAGE); selected ^= 1; continue; @@ -1233,6 +1528,8 @@ void RAMFUNCTION wolfBoot_start(void) ret = wolfBoot_open_image_address(&os_image, (void*)hdr_ptr); if (ret < 0) { wolfBoot_printf("Error parsing loaded image\r\n"); + DISK_RECORD_FAILURE(WOLFBOOT_FAILURE_PHASE_BOOT, + WOLFBOOT_FAILURE_CAUSE_HEADER); SET_FAILOVER(DISK_FAILOVER_NO_IMAGE); selected ^= 1; continue; @@ -1246,6 +1543,8 @@ void RAMFUNCTION wolfBoot_start(void) if (wolfBoot_image_part_matches(&os_image) < 0) { wolfBoot_printf("Image partition mismatch for %s\r\n", part_name); + DISK_RECORD_FAILURE(WOLFBOOT_FAILURE_PHASE_BOOT, + WOLFBOOT_FAILURE_CAUSE_HEADER); selected ^= 1; continue; } @@ -1264,6 +1563,8 @@ void RAMFUNCTION wolfBoot_start(void) (((uint64_t)os_image.fw_size + (uint64_t)IMAGE_HEADER_SIZE) > fs_size(&slot->f))) { wolfBoot_printf("Image larger than file for %s\r\n", part_name); + DISK_RECORD_FAILURE(WOLFBOOT_FAILURE_PHASE_BOOT, + WOLFBOOT_FAILURE_CAUSE_HEADER); SET_FAILOVER(DISK_FAILOVER_NO_IMAGE); selected ^= 1; continue; @@ -1274,6 +1575,8 @@ void RAMFUNCTION wolfBoot_start(void) if (os_image.fw_size > WOLFBOOT_RAMBOOT_MAX_SIZE) { wolfBoot_printf("Image size %u exceeds max RAM load size\r\n", os_image.fw_size); + DISK_RECORD_FAILURE(WOLFBOOT_FAILURE_PHASE_BOOT, + WOLFBOOT_FAILURE_CAUSE_HEADER); SET_FAILOVER(DISK_FAILOVER_NO_IMAGE); selected ^= 1; continue; @@ -1287,6 +1590,8 @@ void RAMFUNCTION wolfBoot_start(void) if (os_image.fw_size > slot_max) { wolfBoot_printf("Image size %u doesn't fit in low memory\r\n", os_image.fw_size); + DISK_RECORD_FAILURE(WOLFBOOT_FAILURE_PHASE_BOOT, + WOLFBOOT_FAILURE_CAUSE_HEADER); SET_FAILOVER(DISK_FAILOVER_NO_IMAGE); selected ^= 1; continue; @@ -1299,6 +1604,7 @@ void RAMFUNCTION wolfBoot_start(void) /* Read the payload into RAM (skip header) */ wolfBoot_printf("Loading image from disk..."); + BOOT_TIME_RESTART(); BENCHMARK_START(); load_off = 0; do { @@ -1322,11 +1628,14 @@ void RAMFUNCTION wolfBoot_start(void) wolfBoot_printf("Error reading image from disk: p%d " "(%u of %u bytes)\r\n", cur_part, (unsigned int)load_off, (unsigned int)os_image.fw_size); + DISK_RECORD_FAILURE(WOLFBOOT_FAILURE_PHASE_BOOT, + WOLFBOOT_FAILURE_CAUSE_READ); SET_FAILOVER(DISK_FAILOVER_NO_IMAGE); selected ^= 1; continue; } BENCHMARK_END("done"); + BOOT_TIME_MARK(BOOT_TIME_LOAD); #ifdef DISK_ENCRYPT /* Decrypt the payload in RAM */ @@ -1339,10 +1648,19 @@ void RAMFUNCTION wolfBoot_start(void) wolfBoot_printf("Encrypted disk images require aligned header size\r\n"); wolfBoot_panic(); } - disk_crypto_set_iv(IMAGE_HEADER_SIZE / ENCRYPT_BLOCK_SIZE); - crypto_decrypt((uint8_t*)load_address, (uint8_t*)load_address, - os_image.fw_size); + if ((disk_crypto_set_iv(IMAGE_HEADER_SIZE / ENCRYPT_BLOCK_SIZE) + != 0) || + (crypto_decrypt((uint8_t*)load_address, + (uint8_t*)load_address, os_image.fw_size) != 0)) { + wolfBoot_printf("Error decrypting %s\r\n", part_name); + DISK_RECORD_FAILURE(WOLFBOOT_FAILURE_PHASE_BOOT, + WOLFBOOT_FAILURE_CAUSE_DECRYPT); + SET_FAILOVER(DISK_FAILOVER_VERIFY); + selected ^= 1; + continue; + } BENCHMARK_END("done"); + BOOT_TIME_MARK(BOOT_TIME_DECRYPT); } #endif @@ -1350,6 +1668,8 @@ void RAMFUNCTION wolfBoot_start(void) ret = wolfBoot_open_image_address(&os_image, (void*)hdr_ptr); if (ret < 0) { wolfBoot_printf("Error parsing loaded image\r\n"); + DISK_RECORD_FAILURE(WOLFBOOT_FAILURE_PHASE_BOOT, + WOLFBOOT_FAILURE_CAUSE_HEADER); SET_FAILOVER(DISK_FAILOVER_NO_IMAGE); selected ^= 1; continue; @@ -1364,22 +1684,37 @@ void RAMFUNCTION wolfBoot_start(void) BENCHMARK_START(); if (wolfBoot_verify_integrity(&os_image) != 0) { wolfBoot_printf("Error validating integrity for %s\r\n", part_name); + DISK_RECORD_FAILURE(WOLFBOOT_FAILURE_PHASE_BOOT, + WOLFBOOT_FAILURE_CAUSE_HASH); SET_FAILOVER(DISK_FAILOVER_VERIFY); selected ^= 1; continue; } BENCHMARK_END("done"); + BOOT_TIME_MARK(BOOT_TIME_HASH); wolfBoot_printf("Verifying image signature..."); BENCHMARK_START(); if (wolfBoot_verify_authenticity(&os_image) != 0) { wolfBoot_printf("Error validating authenticity for %s\r\n", part_name); + DISK_RECORD_FAILURE(WOLFBOOT_FAILURE_PHASE_BOOT, + WOLFBOOT_FAILURE_CAUSE_SIGNATURE); SET_FAILOVER(DISK_FAILOVER_VERIFY); selected ^= 1; continue; } else { BENCHMARK_END("done"); + BOOT_TIME_MARK(BOOT_TIME_VERIFY); +#ifdef DISK_COMMIT_CONFIRMED + if ((commit_slot >= 0) && (selected == commit_slot)) { + wolfBoot_apply_confirmed_image(&os_image, 1); + commit_slot = -1; + selected = trial_slot; + failures = 0; + continue; + } +#endif failures = 0; break; /* Success case */ } @@ -1395,6 +1730,10 @@ void RAMFUNCTION wolfBoot_start(void) disk_crypto_clear(); #endif wolfBoot_printf("Unable to find a valid partition!\r\n"); +#ifdef WOLFBOOT_PERSIST_FAILURE_STATUS + disk_record_failure(WOLFBOOT_FAILURE_PHASE_RECOVERY, disk_last_cause, + disk_last_slot, 0U); +#endif #if defined(WOLFBOOT_ANTI_ROLLBACK) && defined(WOLFBOOT_FSP) boot_state_on_failure(BOOT_FAIL_VERIFY_BOTH); #endif @@ -1414,6 +1753,19 @@ void RAMFUNCTION wolfBoot_start(void) } #endif +#if defined(WOLFBOOT_CONFIRMED_IMAGE_HOOKS) && \ + !defined(WOLFBOOT_SKIP_BOOT_VERIFY) + { + int confirmed = 0; + #ifdef DISK_BOOT_CONFIRM + /* The golden slot is a recovery image and never changes policy. */ + confirmed = (selected < 2) && + (slot_state[selected] == DISK_STATE_SUCCESS); + #endif + wolfBoot_apply_confirmed_image(&os_image, confirmed); + } +#endif + #ifdef DISK_BOOT_CONFIRM /* Put the slot on probation, but only if an update was staged into it. * This mirrors update_ram.c, which promotes UPDATING to TESTING and @@ -1681,6 +2033,18 @@ void RAMFUNCTION wolfBoot_start(void) /* Before hal_prepare_boot(), so a hook still has the MMU and caches as * wolfBoot set them up. */ wolfBoot_hook_preboot(&os_image); +#endif +#ifdef DISK_ENCRYPT + disk_crypto_clear(); + disk_crypto_clear_ctx(); +#endif +#if defined(WOLFBOOT_TPM_POLICY_NV) && !defined(WOLFBOOT_FSP) + /* Locks the platform hierarchy; the x86 FSP do_boot() does it there */ + wolfBoot_tpm2_deinit(); +#endif + BOOT_TIME_MARK(BOOT_TIME_HANDOFF); +#ifdef BOOT_BENCHMARK + wolfBoot_boot_times_print(); #endif hal_prepare_boot(); diff --git a/src/update_flash.c b/src/update_flash.c index 1dcfcd60c2..7d92492381 100644 --- a/src/update_flash.c +++ b/src/update_flash.c @@ -2299,6 +2299,18 @@ void RAMFUNCTION wolfBoot_start(void) #endif #endif +#ifdef WOLFBOOT_CONFIRMED_IMAGE_HOOKS + if ((bootRet == 0) && (bootState == IMG_STATE_SUCCESS) && + (updateRet == 0) && (updateState == IMG_STATE_UPDATING)) { + memset(&boot, 0, sizeof(boot)); + if (wolfBoot_open_image(&boot, PART_BOOT) == 0) + (void)wolfBoot_commit_confirmed_image(&boot); + #ifdef EXT_FLASH + wolfBoot_invalidate_hdr_cache(); + #endif + } +#endif + #if !defined(DISABLE_BACKUP) && !defined(CUSTOM_PARTITION_TRAILER) /* resume the final erase in case the power failed before it finished */ resumedFinalErase = wolfBoot_swap_and_final_erase(1, 0); @@ -2417,6 +2429,14 @@ void RAMFUNCTION wolfBoot_start(void) wolfBoot_panic(); } PART_SANITY_CHECK(&boot); +#ifdef WOLFBOOT_CONFIRMED_IMAGE_HOOKS + { + uint8_t rst = 0; + wolfBoot_apply_confirmed_image(&boot, + (wolfBoot_get_partition_state(PART_BOOT, &rst) == 0) && + (rst == IMG_STATE_SUCCESS)); + } +#endif #else if (bootRet < 0) { wolfBoot_panic(); diff --git a/src/update_ram.c b/src/update_ram.c index 42fbc59be9..88eb1ce464 100644 --- a/src/update_ram.c +++ b/src/update_ram.c @@ -64,6 +64,13 @@ extern uint8_t _end[]; /* linker symbol: end of wolfBoot BSS */ #define WOLFBOOT_USE_RAMBOOT #endif +#if defined(WOLFBOOT_CONFIRMED_IMAGE_HOOKS) && \ + !defined(WOLFBOOT_SKIP_BOOT_VERIFY) && \ + defined(HAVE_PARTITION_TRAILERS) && defined(WOLFBOOT_DUALBOOT) && \ + defined(WOLFBOOT_FIXED_PARTITIONS) + #define RAM_COMMIT_CONFIRMED +#endif + #if defined(WOLFBOOT_DUALBOOT) && defined(WOLFBOOT_FIXED_PARTITIONS) /* Slot the verified image was taken from, for the booted image to confirm. */ static int ramboot_part = -1; @@ -159,6 +166,7 @@ int wolfBoot_ramboot(struct wolfBoot_image *img, uint8_t *src, uint8_t *dst) /* Read the entire image into RAM */ wolfBoot_printf("Loading image %d bytes from %p to %p...", img_size, src + IMAGE_HEADER_SIZE, dst + IMAGE_HEADER_SIZE); + BOOT_TIME_RESTART(); BENCHMARK_START(); #if defined(EXT_FLASH) && defined(NO_XIP) ret = ext_flash_read((uintptr_t)src + IMAGE_HEADER_SIZE, @@ -175,6 +183,7 @@ int wolfBoot_ramboot(struct wolfBoot_image *img, uint8_t *src, uint8_t *dst) memcpy(dst + IMAGE_HEADER_SIZE, src + IMAGE_HEADER_SIZE, img_size); #endif BENCHMARK_END("done"); + BOOT_TIME_MARK(BOOT_TIME_LOAD); /* mark image as no longer external */ img->not_ext = 1; @@ -287,6 +296,12 @@ void RAMFUNCTION wolfBoot_start(void) /* Candidates already tried this boot; a failed RAM image cannot be * erased to invalidate it like the flash path does. */ int tried_boot = 0, tried_update = 0; +#ifdef RAM_COMMIT_CONFIRMED + /* Confirmed partition whose policy is applied before a fresh update in + * the other partition is verified, and that update partition. */ + int commit_part = -1, trial_part = -1; + uint8_t trial_state = 0, other_state = 0; +#endif struct wolfBoot_image os_image; BENCHMARK_DECLARE(); #ifdef WOLFBOOT_UBOOT_LEGACY @@ -332,6 +347,19 @@ void RAMFUNCTION wolfBoot_start(void) * sub-image. If present, hand off to BL31 instead of jumping to the * kernel directly. */ uintptr_t bl31_entry = 0; +#endif + BOOT_TIME_MARK(BOOT_TIME_ENTRY); +#ifdef RAM_COMMIT_CONFIRMED + trial_part = wolfBoot_dualboot_candidate(); + active = trial_part; + if ((trial_part >= 0) && + (wolfBoot_get_partition_state(trial_part, &trial_state) == 0) && + (trial_state == IMG_STATE_UPDATING) && + (wolfBoot_get_partition_state(trial_part ^ 1, &other_state) == 0) && + (other_state == IMG_STATE_SUCCESS)) { + commit_part = trial_part ^ 1; + active = commit_part; + } #endif for (;;) { /* Each open needs fresh image state: wolfBoot_open_image_address() @@ -420,6 +448,7 @@ void RAMFUNCTION wolfBoot_start(void) goto backup_on_failure; } BENCHMARK_END("done"); + BOOT_TIME_MARK(BOOT_TIME_HASH); /* Verify image authenticity (signature check) */ wolfBoot_printf("Verifying signature..."); @@ -430,9 +459,19 @@ void RAMFUNCTION wolfBoot_start(void) goto backup_on_failure; } BENCHMARK_END("done"); + BOOT_TIME_MARK(BOOT_TIME_VERIFY); #endif +#ifdef RAM_COMMIT_CONFIRMED + if ((commit_part >= 0) && (active == commit_part)) { + if ((os_image.sha_ok == 1U) && (os_image.signature_ok == 1U)) + wolfBoot_apply_confirmed_image(&os_image, 1); + commit_part = -1; + active = trial_part; + continue; + } +#endif { /* Success - integrity and signature valid */ #if !defined(WOLFBOOT_NO_LOAD_ADDRESS) && defined(WOLFBOOT_LOAD_ADDRESS) @@ -449,6 +488,13 @@ void RAMFUNCTION wolfBoot_start(void) backup_on_failure: wolfBoot_printf("Failure %d: Part %d, Hdr %d, Hash %d, Sig %d\n", ret, active, os_image.hdr_ok, os_image.sha_ok, os_image.signature_ok); +#ifdef RAM_COMMIT_CONFIRMED + if ((commit_part >= 0) && (active == commit_part)) { + commit_part = -1; + active = trial_part; + continue; + } +#endif /* panic if authentication fails and no backup */ if (!wolfBoot_fallback_is_possible()) { wolfBoot_printf("Impossible recovery with fallback.\n"); @@ -485,6 +531,19 @@ void RAMFUNCTION wolfBoot_start(void) ramboot_part = active; #endif +#if defined(WOLFBOOT_CONFIRMED_IMAGE_HOOKS) && \ + !defined(WOLFBOOT_SKIP_BOOT_VERIFY) + { + int confirmed = 0; + #ifdef HAVE_PARTITION_TRAILERS + uint8_t rst = 0; + confirmed = (wolfBoot_get_partition_state(active, &rst) == 0) && + (rst == IMG_STATE_SUCCESS); + #endif + wolfBoot_apply_confirmed_image(&os_image, confirmed); + } +#endif + /* First time we boot this update, set to TESTING to await * confirmation from the system */ @@ -893,6 +952,13 @@ void RAMFUNCTION wolfBoot_start(void) /* Before hal_prepare_boot(), so a hook still has the MMU and caches as * wolfBoot set them up. */ wolfBoot_hook_preboot(&os_image); +#endif +#ifdef WOLFBOOT_TPM_POLICY_NV + wolfBoot_tpm2_deinit(); +#endif + BOOT_TIME_MARK(BOOT_TIME_HANDOFF); +#ifdef BOOT_BENCHMARK + wolfBoot_boot_times_print(); #endif hal_prepare_boot(); diff --git a/stage1/Makefile b/stage1/Makefile index 84c5f6d9d0..bd8e534463 100644 --- a/stage1/Makefile +++ b/stage1/Makefile @@ -57,6 +57,11 @@ endif ELF=0 MULTIBOOT2=0 LINUX_PAYLOAD=0 +# The security version floor and key revocation apply to the images stage 2 +# boots; stage 2 is signed without them and stage 1 only checks its signature. +override KEY_REVOCATION:=0 +override SECURITY_VERSION:=0 +override WOLFBOOT_TPM_POLICY_NV:=0 ## Architecture/CPU configuration diff --git a/tools/config.mk b/tools/config.mk index ee5fa9d734..0083d0af9e 100644 --- a/tools/config.mk +++ b/tools/config.mk @@ -146,6 +146,9 @@ CONFIG_VARS:= ARCH TARGET SIGN HASH MCUXSDK MCUXPRESSO MCUXPRESSO_CPU MCUXPRESSO WOLFBOOT_VERSION_SECTION \ DDR_HIGH_BASE DDR_HIGH_SIZE NO_DDR_LOW \ BOOT_EL1 BOOT_EL2 \ + KEY_REVOCATION SECURITY_VERSION WOLFBOOT_PRODUCTION WOLFBOOT_TPM_POLICY_NV \ + ZYNQMP_EFUSE_SVN_ROW ZYNQMP_EFUSE_SVN_NROWS ZYNQMP_EFUSE_REVOKE_ROW ZYNQMP_EFUSE_BURN \ + ZYNQMP_SEC ZYNQMP_SEC_POLICY WOLFBOOT_DIAGNOSTICS_DISK_PART \ WOLFBOOT_DTS_BOOT_ADDRESS WOLFBOOT_DTS_UPDATE_ADDRESS \ WOLFBOOT_SMALL_STACK DELTA_UPDATES DELTA_BLOCK_SIZE WOLFBOOT_IMG_HASH_ONESHOT \ WOLFBOOT_HUGE_STACK FORCE_32BIT\ diff --git a/tools/scripts/sim-common.sh b/tools/scripts/sim-common.sh new file mode 100755 index 0000000000..5453c82880 --- /dev/null +++ b/tools/scripts/sim-common.sh @@ -0,0 +1,130 @@ +#!/bin/bash +# Helpers shared by the simulator scripts that assemble their own flash +# images: partition layout from .config, signing options, image assembly, +# and boot outcome checks. Source it from the wolfBoot root after building +# test-sim-internal-flash-with-update. + +if [ ! -f .config ] || [ ! -x ./wolfboot.elf ] || [ ! -f test-app/image.elf ]; then + echo "Build the simulator first (make test-sim-internal-flash-with-update)." >&2 + exit 1 +fi + +cfg() { sed -n "s/^$1?*=//p" .config | tail -1; } + +SIM_SIGN=$(cfg SIGN) +SIM_HASH=$(cfg HASH) +SIM_SIGN=${SIM_SIGN:-ED25519} +SIM_HASH=${SIM_HASH:-SHA256} +SIGNOPT="--$(echo "$SIM_SIGN" | tr 'A-Z' 'a-z') --$(echo "$SIM_HASH" | tr 'A-Z' 'a-z')" +KEYGENOPT="--$(echo "$SIM_SIGN" | tr 'A-Z' 'a-z')" +BOOT_ADDR=$(($(cfg WOLFBOOT_PARTITION_BOOT_ADDRESS))) +UPDATE_ADDR=$(($(cfg WOLFBOOT_PARTITION_UPDATE_ADDRESS))) +SWAP_ADDR=$(($(cfg WOLFBOOT_PARTITION_SWAP_ADDRESS))) +SECTOR_SIZE=$(($(cfg WOLFBOOT_SECTOR_SIZE))) +SIM_HDR_SIZE=$(cfg IMAGE_HEADER_SIZE) +SIM_HDR_SIZE=${SIM_HDR_SIZE:-256} +SIM_FAILS=0 + +# With WOLFBOOT_TPM_POLICY_NV=1 the revocation mask and the security version +# live in the TPM, read and cleared with tools/tpm/policy_nv. +SIM_TPM_POLICY=0 +if grep -Eq '^WOLFBOOT_TPM_POLICY_NV\??=1' .config; then + SIM_TPM_POLICY=1 + [ -x tools/tpm/policy_nv ] || { + echo "Build tools/tpm/policy_nv first (make tpmtools)." >&2 + exit 1 + } +fi + +# sim_policy NAME: "revoked" mask (hex, or none) or "svn" floor from the TPM +sim_policy() { + ./tools/tpm/policy_nv 2>/dev/null | sed -n "s/^$1 //p" +} + +# sim_policy_reset: forget the stored revocation mask and security version +sim_policy_reset() { + rm -f sim_revoked_keys.dd sim_security_version.dd + if [ "$SIM_TPM_POLICY" = 1 ]; then + ./tools/tpm/policy_nv -clear >/dev/null 2>&1 || exit 1 + fi +} + +# sim_sign KEY VERSION OUT [sign options...]: sign test-app/image.elf to OUT +sim_sign() { + local key=$1 ver=$2 out=$3 tmp + shift 3 + tmp=$(mktemp -d) + cp test-app/image.elf "$tmp/image.elf" + ./tools/keytools/sign $SIGNOPT "$@" "$tmp/image.elf" "$key" "$ver" \ + >/dev/null || { echo "sign failed: $out" >&2; exit 1; } + mv "$tmp/image_v${ver}_signed.bin" "$out" + rm -rf "$tmp" +} + +# sim_append_tlv IN OUT TYPE VALUE32: copy IN to OUT with a 4-byte TLV +# written into the header padding after the signature, outside the signed part +sim_append_tlv() { + python3 - "$1" "$2" "$3" "$4" "${SIM_HDR_SIZE}" <<'PYEOF' || exit 1 +import struct, sys +src, dst = sys.argv[1], sys.argv[2] +typ, val, hdr = (int(a, 0) for a in sys.argv[3:6]) +img = bytearray(open(src, 'rb').read()) +p = end = 8 +while p + 4 <= hdr: + if img[p] == 0xFF: + p += 1 + continue + t, l = struct.unpack_from(' hdr: + sys.exit("no room for the TLV in the header") +img[end:end + 8] = struct.pack('/dev/null 2>&1 || exit 1 + truncate -s $((SWAP_ADDR + SECTOR_SIZE)) internal_flash.dd +} + +# sim_put_update IMAGE: replace the image in the UPDATE partition, keeping +# its trailer (and so its update state) +sim_put_update() { + dd if="$1" of=internal_flash.dd bs=4096 oflag=seek_bytes \ + seek="$UPDATE_ADDR" conv=notrunc status=none +} + +# sim_boot [args...]: prints "BOOT vN", "PANIC" or "RC n" +sim_boot() { + local v rc + v=$(timeout 10s ./wolfboot.elf "$@" get_version 2>/dev/null) + rc=$? + if [ $rc -eq 0 ] && [ -n "$v" ]; then + echo "BOOT v$v" + elif [ $rc -eq 80 ]; then + echo "PANIC" + else + echo "RC $rc" + fi +} + +# sim_expect NAME EXPECTED OBSERVED +sim_expect() { + if [ "$2" = "$3" ]; then + printf 'PASS %-58s %s\n' "$1" "$3" + else + printf 'FAIL %-58s expected "%s", got "%s"\n' "$1" "$2" "$3" + SIM_FAILS=$((SIM_FAILS + 1)) + fi +} diff --git a/tools/scripts/sim-key-revocation.sh b/tools/scripts/sim-key-revocation.sh new file mode 100755 index 0000000000..a0ceec5e53 --- /dev/null +++ b/tools/scripts/sim-key-revocation.sh @@ -0,0 +1,92 @@ +#!/bin/bash +# Signing key revocation (KEY_REVOCATION=1) on the simulator. +# +# Rebuilds the keystore with two keys (slot 0 and slot 1), then checks that a +# confirmed image signed by key 1 carrying HDR_KEY_REVOKE=0x1 revokes key 0, +# that images signed by key 0 are then refused, that an unconfirmed update +# does not revoke, and that an image cannot revoke the key that signed it. +# The revocation mask lives in sim_revoked_keys.dd. + +set -u +. "$(dirname "$0")/sim-common.sh" + +grep -Eq '^KEY_REVOCATION\??=1' .config || { + echo "KEY_REVOCATION=1 is required in .config." >&2 + exit 1 +} + +HDR_KEY_REVOKE=0x36 +W=$(mktemp -d) +trap 'rm -rf "$W"; sim_policy_reset' EXIT + +rm -f src/keystore.c +./tools/keytools/keygen $KEYGENOPT -g "$W/key0.der" -g "$W/key1.der" \ + >/dev/null || exit 1 +make -s wolfboot.elf wolfboot.bin >/dev/null || exit 1 + +revoked() { + if [ "$SIM_TPM_POLICY" = 1 ]; then + sim_policy revoked + elif [ -s sim_revoked_keys.dd ]; then + od -An -tx4 sim_revoked_keys.dd | tr -d ' ' + else + echo none + fi +} + +sim_sign "$W/key0.der" 1 "$W/k0v1.bin" +sim_sign "$W/key1.der" 2 "$W/k1v2rev.bin" --custom-tlv $HDR_KEY_REVOKE 4 0x1 +sim_sign "$W/key0.der" 3 "$W/k0v3.bin" +sim_sign "$W/key1.der" 2 "$W/k1v2self.bin" --custom-tlv $HDR_KEY_REVOKE 4 0x2 +sim_sign "$W/key1.der" 2 "$W/k1v2.bin" +sim_append_tlv "$W/k1v2.bin" "$W/k1v2tail.bin" $HDR_KEY_REVOKE 0x1 + +sim_policy_reset +sim_assemble "$W/k0v1.bin" "$W/k1v2rev.bin" +sim_expect "key 0 image boots before revocation" "BOOT v1" "$(sim_boot update_trigger)" +sim_boot success >/dev/null +sim_expect "unconfirmed update does not revoke" "none" "$(revoked)" +sim_boot >/dev/null +sim_expect "confirmed key 1 image revokes key 0" "00000001" "$(revoked)" + +sim_assemble "$W/k1v2rev.bin" "$W/k0v3.bin" +sim_boot update_trigger >/dev/null +sim_expect "newer update signed by revoked key is refused" "BOOT v2" "$(sim_boot)" +sim_assemble "$W/k0v1.bin" - +sim_expect "boot image signed by revoked key is refused" "PANIC" "$(sim_boot)" + +sim_policy_reset +sim_assemble "$W/k0v1.bin" "$W/k1v2rev.bin" +sim_boot update_trigger >/dev/null +sim_boot >/dev/null +sim_expect "unconfirmed revoking update falls back to key 0 image" "BOOT v1" "$(sim_boot)" +sim_expect "fallback leaves key 0 valid" "none" "$(revoked)" + +sim_policy_reset +sim_assemble "$W/k0v1.bin" "$W/k1v2self.bin" +sim_boot update_trigger >/dev/null +sim_boot success >/dev/null +sim_boot >/dev/null +sim_expect "image cannot revoke its own signing key" "none" "$(revoked)" + +sim_policy_reset +sim_assemble "$W/k1v2tail.bin" - +sim_expect "revocation mask outside the signed header is refused" "PANIC" "$(sim_boot)" +sim_expect "unsigned revocation mask revokes nothing" "none" "$(revoked)" + +if [ "$SIM_TPM_POLICY" = 1 ]; then + ./tools/tpm/policy_nv -foreign >/dev/null 2>&1 || exit 1 + sim_assemble "$W/k1v2.bin" - + sim_expect "revocation index not created by wolfBoot is refused" "PANIC" \ + "$(sim_boot)" +fi + +sim_policy_reset +sim_assemble "$W/k0v1.bin" "$W/k1v2rev.bin" +sim_boot update_trigger >/dev/null +sim_boot success update_trigger >/dev/null +sim_put_update "$W/k0v3.bin" +sim_expect "update staged with a confirm is checked against its mask" "BOOT v2" "$(sim_boot)" +sim_expect "confirmed image mask committed before the update" "00000001" "$(revoked)" + +exit $SIM_FAILS diff --git a/tools/scripts/sim-security-version.sh b/tools/scripts/sim-security-version.sh new file mode 100755 index 0000000000..7f4b22aa49 --- /dev/null +++ b/tools/scripts/sim-security-version.sh @@ -0,0 +1,125 @@ +#!/bin/bash +# Security version floor (SECURITY_VERSION=1) on the simulator. +# +# Images carry their security version in the signed HDR_SECURITY_VERSION TLV. +# A confirmed image raises the floor kept in sim_security_version.dd; images +# below the floor, without the TLV once a floor is set, or with a malformed +# TLV are refused, and an unconfirmed update does not raise the floor. + +set -u +. "$(dirname "$0")/sim-common.sh" + +grep -Eq '^SECURITY_VERSION\??=1' .config || { + echo "SECURITY_VERSION=1 is required in .config." >&2 + exit 1 +} + +HDR_SECURITY_VERSION=0x37 +KEY=wolfboot_signing_private_key.der +W=$(mktemp -d) +trap 'rm -rf "$W"; sim_policy_reset' EXIT + +floor() { + if [ "$SIM_TPM_POLICY" = 1 ]; then + sim_policy svn + elif [ -s sim_security_version.dd ]; then + od -An -tu4 sim_security_version.dd | tr -d ' ' + else + echo 0 + fi +} + +svn() { # VERSION SVN OUT [TLV length] + sim_sign "$KEY" "$1" "$3" --custom-tlv $HDR_SECURITY_VERSION "${4:-4}" "$2" +} + +svn 1 1 "$W/v1s1.bin" +svn 2 2 "$W/v2s2.bin" +svn 3 1 "$W/v3s1.bin" +svn 3 3 "$W/v3s3.bin" +sim_sign "$KEY" 4 "$W/v4nosvn.bin" +svn 4 5 "$W/v4bad.bin" 2 +sim_append_tlv "$W/v4nosvn.bin" "$W/v4tail.bin" $HDR_SECURITY_VERSION 5 + +sim_policy_reset +sim_assemble "$W/v1s1.bin" - +sim_boot success >/dev/null +sim_boot >/dev/null +sim_expect "confirmed SVN 1 image sets the floor" "1" "$(floor)" + +sim_assemble "$W/v1s1.bin" "$W/v2s2.bin" +sim_boot update_trigger >/dev/null +sim_boot success >/dev/null +sim_expect "SVN 2 update in TESTING leaves the floor" "1" "$(floor)" +sim_boot >/dev/null +sim_expect "confirmed SVN 2 update raises the floor" "2" "$(floor)" + +sim_assemble "$W/v2s2.bin" "$W/v3s1.bin" +sim_boot update_trigger >/dev/null +sim_expect "higher version with lower SVN is refused as update" "BOOT v2" "$(sim_boot)" + +sim_assemble "$W/v1s1.bin" - +sim_expect "boot image below the floor is refused" "PANIC" "$(sim_boot)" + +sim_assemble "$W/v2s2.bin" "$W/v3s3.bin" +sim_boot update_trigger >/dev/null +sim_boot >/dev/null +sim_expect "unconfirmed SVN 3 update falls back" "BOOT v2" "$(sim_boot)" +sim_expect "fallback leaves the floor" "2" "$(floor)" + +sim_assemble "$W/v4nosvn.bin" - +sim_expect "image without SVN TLV is refused once a floor is set" "PANIC" "$(sim_boot)" + +# An image for another partition id booted from BOOT never sets the floor +sim_sign "$KEY" 5 "$W/v5s5part2.bin" --id 2 --custom-tlv $HDR_SECURITY_VERSION 4 5 +sim_policy_reset +sim_assemble "$W/v5s5part2.bin" - +sim_boot success >/dev/null +sim_expect "non-application image in BOOT still boots" "BOOT v5" "$(sim_boot)" +sim_expect "non-application image does not set the floor" "0" "$(floor)" + +if [ "$SIM_TPM_POLICY" != 1 ]; then + # A floor that cannot be raised (reads as 0, writes fail even as root): + # production builds stop, others boot + sim_policy_reset + ln -s /dev/full sim_security_version.dd + sim_assemble "$W/v2s2.bin" - + sim_boot success >/dev/null + if grep -Eq '^WOLFBOOT_PRODUCTION\??=1' .config; then + sim_expect "production build stops when the floor cannot be raised" \ + "PANIC" "$(sim_boot)" + else + sim_expect "floor that cannot be raised is reported, boot continues" \ + "BOOT v2" "$(sim_boot)" + fi +fi + +sim_policy_reset +sim_assemble "$W/v4bad.bin" - +sim_expect "malformed SVN TLV is refused" "PANIC" "$(sim_boot)" + +sim_policy_reset +sim_assemble "$W/v4tail.bin" - +sim_expect "SVN TLV outside the signed header is refused" "PANIC" "$(sim_boot)" + +sim_policy_reset +sim_assemble "$W/v1s1.bin" "$W/v2s2.bin" +sim_boot update_trigger >/dev/null +sim_boot success update_trigger >/dev/null +sim_put_update "$W/v3s1.bin" +sim_expect "update staged with a confirm is checked against its floor" "BOOT v2" "$(sim_boot)" +sim_expect "confirmed image floor committed before the update" "2" "$(floor)" + +if [ "$SIM_TPM_POLICY" = 1 ]; then + svn 2 65 "$W/v2s65.bin" + sim_assemble "$W/v2s65.bin" - + sim_expect "security version above the TPM backend's 64 is refused" \ + "PANIC" "$(sim_boot)" + + ./tools/tpm/policy_nv -foreign >/dev/null 2>&1 || exit 1 + sim_assemble "$W/v2s2.bin" - + sim_expect "SVN index not created by wolfBoot is refused" "PANIC" \ + "$(sim_boot)" +fi + +exit $SIM_FAILS diff --git a/tools/tpm/Makefile b/tools/tpm/Makefile index 050554b460..1f09696afc 100644 --- a/tools/tpm/Makefile +++ b/tools/tpm/Makefile @@ -85,7 +85,7 @@ vpath %.c ./ .PHONY: clean all -all: rot policy_create pcr_extend pcr_read pcr_reset policy_sign +all: rot policy_create pcr_extend pcr_read pcr_reset policy_sign policy_nv debug: CFLAGS+=$(DEBUG_FLAGS) debug: all @@ -126,6 +126,10 @@ policy_sign: $(OBJS_VIRT) policy_sign.o @echo "Building Policy Sign Tool" $(Q)$(LD) -o $@ $@.o $(OBJS_VIRT) $(LDFLAGS) +policy_nv: $(OBJS_VIRT) policy_nv.o + @echo "Building Policy NV Tool" + $(Q)$(LD) -o $@ $@.o $(OBJS_VIRT) $(LDFLAGS) + pcr_extend: $(OBJS_VIRT) $(WOLFBOOT_LIB_WOLFTPM)/examples/pcr/extend.o @echo "Building PCR Extend Tool" $(Q)$(LD) -o $@ $(WOLFBOOT_LIB_WOLFTPM)/examples/pcr/extend.o $(OBJS_VIRT) $(LDFLAGS) @@ -139,4 +143,4 @@ pcr_reset: $(OBJS_VIRT) $(WOLFBOOT_LIB_WOLFTPM)/examples/pcr/reset.o $(Q)$(LD) -o $@ $(WOLFBOOT_LIB_WOLFTPM)/examples/pcr/reset.o $(OBJS_VIRT) $(LDFLAGS) clean: - rm -f rot policy_create pcr_extend pcr_read pcr_reset *.o + rm -f rot policy_create pcr_extend pcr_read pcr_reset policy_nv *.o diff --git a/tools/tpm/policy_nv.c b/tools/tpm/policy_nv.c new file mode 100644 index 0000000000..eeeb1f3d80 --- /dev/null +++ b/tools/tpm/policy_nv.c @@ -0,0 +1,176 @@ +/* policy_nv.c + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of wolfBoot. + * + * wolfBoot 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. + * + * wolfBoot 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 + */ + +/* Test tool for WOLFBOOT_TPM_POLICY_NV: prints the key revocation mask and the + * security version floor wolfBoot keeps in TPM NV, deletes them (-clear), or + * defines owner indices in their place (-foreign) to check that wolfBoot + * refuses an index it did not create. Needs platform auth, so it only works + * before wolfBoot has locked the platform hierarchy (or on the simulator). */ + +#include +#include +#include +#include "wolfboot/wolfboot.h" +#include "tpm.h" + +#include + +static void usage(void) +{ + printf("Expected usage:\n"); + printf("./tools/tpm/policy_nv [-clear] [-foreign]\n"); + printf("* (no option): print \"revoked |none\" and \"svn \"\n"); + printf("* -clear: delete both indices (platform auth)\n"); + printf("* -foreign: define owner indices with AUTHWRITE in their place\n"); +} + +/* Returns 1 and the value if the index holds data, 0 if it is undefined or + * never written, or a negative TPM error. */ +static int read_index(WOLFTPM2_DEV *dev, word32 index, word64 *val) +{ + WOLFTPM2_NV nv; + byte buf[8]; + word32 readSz = sizeof(buf); + int rc, i; + + *val = 0; + XMEMSET(&nv, 0, sizeof(nv)); + rc = wolfTPM2_NVOpen(dev, &nv, index, NULL, 0); + if (rc != 0) { + if ((rc & RC_FMT1) && ((rc & RC_MAX_FMT1) == TPM_RC_HANDLE)) + return 0; + return -rc; + } + if ((nv.attributes & TPMA_NV_WRITTEN) == 0) + return 0; + wolfTPM2_SetAuthHandle(dev, 0, &nv.handle); + rc = wolfTPM2_NVReadAuth(dev, &nv, index, buf, &readSz, 0); + wolfTPM2_UnsetAuth(dev, 0); + if (rc != 0) + return -rc; + for (i = 0; i < (int)readSz; i++) + *val = (*val << 8) | buf[i]; + return 1; +} + +static int delete_index(WOLFTPM2_DEV *dev, TPMI_RH_NV_AUTH auth, word32 index) +{ + WOLFTPM2_HANDLE parent; + int rc; + + XMEMSET(&parent, 0, sizeof(parent)); + parent.hndl = auth; + wolfTPM2_SetAuthPassword(dev, 0, NULL); + rc = wolfTPM2_NVDeleteAuth(dev, &parent, index); + wolfTPM2_UnsetAuth(dev, 0); + if ((rc & RC_FMT1) && ((rc & RC_MAX_FMT1) == TPM_RC_HANDLE)) + rc = 0; + return rc; +} + +static int define_foreign(WOLFTPM2_DEV *dev, word32 index) +{ + WOLFTPM2_HANDLE parent; + WOLFTPM2_NV nv; + word32 attr = 0; + int rc; + + XMEMSET(&parent, 0, sizeof(parent)); + XMEMSET(&nv, 0, sizeof(nv)); + parent.hndl = TPM_RH_OWNER; + wolfTPM2_GetNvAttributesTemplate(TPM_RH_OWNER, &attr); + attr &= ~TPMA_NV_TPM_NT; + attr |= ((word32)TPM_NT_BITS << 4); + wolfTPM2_SetAuthPassword(dev, 0, NULL); + rc = wolfTPM2_NVCreateAuth(dev, &parent, &nv, index, attr, 8, NULL, 0); + wolfTPM2_UnsetAuth(dev, 0); + wolfTPM2_UnsetAuth(dev, 1); + return rc; +} + +int main(int argc, char *argv[]) +{ + WOLFTPM2_DEV dev; + word64 val = 0; + word32 svn = 0; + int doClear = 0, doForeign = 0; + int rc; + + if (argc > 1) { + if (XSTRCMP(argv[1], "-clear") == 0) + doClear = 1; + else if (XSTRCMP(argv[1], "-foreign") == 0) + doForeign = 1; + else { + usage(); + return (XSTRCMP(argv[1], "-h") == 0) ? 0 : -1; + } + } + + XMEMSET(&dev, 0, sizeof(dev)); +#ifndef WOLFTPM_ADV_IO + rc = wolfTPM2_Init(&dev, TPM2_IoCb, NULL); +#else + rc = wolfTPM2_Init(&dev, NULL, NULL); +#endif + if (rc != 0) { + fprintf(stderr, "wolfTPM2_Init failed 0x%x\n", rc); + return 1; + } + + if (doClear || doForeign) { + rc = delete_index(&dev, TPM_RH_PLATFORM, WOLFBOOT_TPM_REVOKE_NV_INDEX); + if (rc == 0) + rc = delete_index(&dev, TPM_RH_PLATFORM, WOLFBOOT_TPM_SVN_NV_INDEX); + if (rc == 0) + rc = delete_index(&dev, TPM_RH_OWNER, WOLFBOOT_TPM_REVOKE_NV_INDEX); + if (rc == 0) + rc = delete_index(&dev, TPM_RH_OWNER, WOLFBOOT_TPM_SVN_NV_INDEX); + if ((rc == 0) && doForeign) { + rc = define_foreign(&dev, WOLFBOOT_TPM_REVOKE_NV_INDEX); + if (rc == 0) + rc = define_foreign(&dev, WOLFBOOT_TPM_SVN_NV_INDEX); + } + } + else { + rc = read_index(&dev, WOLFBOOT_TPM_REVOKE_NV_INDEX, &val); + if (rc == 1) + printf("revoked %08x\n", (unsigned int)(val & 0xFFFFFFFFU)); + else if (rc == 0) + printf("revoked none\n"); + if (rc >= 0) + rc = read_index(&dev, WOLFBOOT_TPM_SVN_NV_INDEX, &val); + if (rc >= 0) { + while (val != 0) { + svn++; + val >>= 1; + } + printf("svn %u\n", (unsigned int)svn); + rc = 0; + } + } + + if (rc != 0) + fprintf(stderr, "Failure 0x%x: %s\n", rc < 0 ? -rc : rc, + wolfTPM2_GetRCString(rc < 0 ? -rc : rc)); + wolfTPM2_Cleanup(&dev); + return (rc == 0) ? 0 : 1; +} diff --git a/tools/unit-tests/Makefile b/tools/unit-tests/Makefile index 81c6cf0e5d..a5dfd8314f 100644 --- a/tools/unit-tests/Makefile +++ b/tools/unit-tests/Makefile @@ -91,8 +91,8 @@ TESTS:=unit-parser unit-parser-large-header unit-fdt unit-extflash unit-string \ unit-update-flash-self-update-ecc \ unit-update-flash-self-update-monolithic \ unit-nsc-update \ - unit-update-flash-enc unit-update-flash-enc-cache unit-update-flash-enc-full unit-update-flash-enc-intswap unit-update-ram unit-update-ram-fit unit-update-ram-uboot unit-update-ram-enc unit-update-ram-enc-start unit-update-ram-enc-nopart unit-update-ram-nofixed unit-update-ram-nofixed-noramboot unit-update-ram-noramboot unit-update-ram-custom-trailer unit-update-ram-rollback-unconfirmed unit-compressed-tlv unit-custom-trailer-nopart unit-update-flash-hwswap unit-update-flash-custom-trailer unit-pkcs11_store unit-psa_store unit-wolfhsm_flash_hal unit-disk \ - unit-update-disk unit-update-disk-confirm unit-update-disk-golden unit-update-disk-failover unit-update-disk-golden-enckey unit-update-disk-fsp unit-update-disk-oob unit-update-disk-fit unit-update-disk-fit-ramdisk unit-multiboot unit-boot-x86-fsp unit-loader-tpm-init unit-qspi-flash unit-fwtpm-stub unit-tpm-rsa-exp \ + unit-update-flash-enc unit-update-flash-enc-cache unit-update-flash-enc-full unit-update-flash-enc-intswap unit-update-ram unit-update-ram-fit unit-update-ram-uboot unit-update-ram-enc unit-update-ram-enc-start unit-update-ram-enc-nopart unit-update-ram-nofixed unit-update-ram-nofixed-noramboot unit-update-ram-noramboot unit-update-ram-custom-trailer unit-update-ram-rollback-unconfirmed unit-update-ram-confirm-hooks unit-update-disk-confirm-hooks unit-compressed-tlv unit-custom-trailer-nopart unit-update-flash-hwswap unit-update-flash-custom-trailer unit-pkcs11_store unit-psa_store unit-wolfhsm_flash_hal unit-disk \ + unit-update-disk unit-update-disk-confirm unit-update-disk-confirm-diag unit-update-disk-golden unit-update-disk-failover unit-update-disk-golden-enckey unit-update-disk-decrypt-fail unit-update-disk-fsp unit-update-disk-oob unit-update-disk-fit unit-update-disk-fit-ramdisk unit-multiboot unit-boot-x86-fsp unit-loader-tpm-init unit-qspi-flash unit-fwtpm-stub unit-tpm-rsa-exp \ unit-image-nopart unit-image-sha384 unit-image-sha3-384 unit-image-dts \ unit-image-dts-sha384 unit-image-dts-sha3-384 unit-store-sbrk \ unit-tpm-blob unit-policy-create unit-policy-sign unit-rot-auth unit-sdhci-response-bits \ @@ -117,6 +117,8 @@ TESTS+=unit-psoc-c3-divider TESTS+=unit-psoc-e8-tz TESTS+=unit-psoc-e8-flash TESTS+=unit-diagnostics-256 +TESTS+=unit-diagnostics-disk +TESTS+=unit-update-disk-diag unit-update-disk-diag-plain TESTS+=unit-fit-gzip unit-fit-nogzip TESTS+=unit-gzip-small unit-gzip-bits32 unit-gzip-root7 unit-fit-gzip-small ifeq ($(HAVE_ZLIB),1) @@ -170,6 +172,8 @@ TESTS+=unit-ct-compare TESTS+=unit-zynqmp-bbram-crc TESTS+=unit-zynqmp-efuse-guards TESTS+=unit-zynqmp-efuse-burn +TESTS+=unit-zynqmp-efuse-counter +TESTS+=unit-zynqmp-sec-bl33 TESTS+=unit-zynqmp-puf TESTS+=unit-zynqmp-puf-nofsbl TESTS+=unit-versal-qspi-dma @@ -246,7 +250,7 @@ TESTS+=unit-p1021-qe-firmware TESTS+=unit-t10xx-dts-memac TESTS+=unit-fs-probe TESTS+=unit-fs-malicious -TESTS+=unit-update-disk-fs unit-update-disk-fs-enc unit-update-disk-fs-confirm \ +TESTS+=unit-update-disk-fs unit-update-disk-fs-diag unit-update-disk-fs-enc unit-update-disk-fs-confirm \ unit-update-disk-fs-confirm-fdt # The filesystem interop tests build their fixtures with the host's real @@ -423,6 +427,7 @@ unit-nvm-journal-dual-ecc:CFLAGS+=-DNVM_FLASH_JOURNAL -DNVM_FLASH_JOURNAL_DUAL \ -DEXT_FLASH -DPART_BOOT_EXT -DPART_UPDATE_EXT unit-diagnostics:CFLAGS+=-DMOCK_PARTITIONS unit-diagnostics-256:CFLAGS+=-DMOCK_PARTITIONS -DWOLFBOOT_DIAGNOSTICS_RECORD_SIZE=32 +unit-diagnostics-disk:CFLAGS+=-DMOCK_PARTITIONS unit-enc-nvm:CFLAGS+=-DNVM_FLASH_WRITEONCE -DMOCK_PARTITIONS -DEXT_ENCRYPTED \ -DENCRYPT_WITH_CHACHA -DEXT_FLASH -DHAVE_CHACHA unit-enc-nvm:WOLFCRYPT_SRC+=$(WOLFBOOT_LIB_WOLFSSL)/wolfcrypt/src/chacha.c @@ -588,6 +593,12 @@ unit-update-ram-rollback-unconfirmed:CFLAGS+=-DMOCK_PARTITIONS -DWOLFBOOT_NO_SIG -DPART_SWAP_EXT -DPART_BOOT_EXT -DWOLFBOOT_DUALBOOT -DNO_XIP \ -DWOLFBOOT_DUALBOOT_ROLLBACK_UNCONFIRMED \ -DWOLFBOOT_ORIGIN=MOCK_ADDRESS_BOOT -DBOOTLOADER_PARTITION_SIZE=WOLFBOOT_PARTITION_SIZE +# unit-update-ram with the confirmed-image policy hook mocked by the test. +unit-update-ram-confirm-hooks:CFLAGS+=-DMOCK_PARTITIONS -DWOLFBOOT_NO_SIGN -DUNIT_TEST_AUTH \ + -DWOLFBOOT_HASH_SHA256 -DPRINTF_ENABLED -DEXT_FLASH -DPART_UPDATE_EXT \ + -DPART_SWAP_EXT -DPART_BOOT_EXT -DWOLFBOOT_DUALBOOT -DNO_XIP \ + -DWOLFBOOT_CONFIRMED_IMAGE_HOOKS \ + -DWOLFBOOT_ORIGIN=MOCK_ADDRESS_BOOT -DBOOTLOADER_PARTITION_SIZE=WOLFBOOT_PARTITION_SIZE unit-update-ram-noramboot:CFLAGS+=-DMOCK_PARTITIONS -DWOLFBOOT_NO_SIGN -DUNIT_TEST_AUTH \ -DWOLFBOOT_HASH_SHA256 -DPRINTF_ENABLED -DEXT_FLASH -DPART_UPDATE_EXT \ -DPART_SWAP_EXT -DPART_BOOT_EXT -DWOLFBOOT_DUALBOOT -DNO_XIP -DWOLFBOOT_NO_RAMBOOT \ @@ -655,14 +666,29 @@ unit-custom-trailer-nopart:CFLAGS+=-DMOCK_PARTITIONS -DWOLFBOOT_NO_SIGN \ # the cap update_disk.c now requires; all images here are exactly that size. unit-update-disk:CFLAGS+=-DMOCK_PARTITIONS -DPRINTF_ENABLED -DWOLFBOOT_RAMBOOT_MAX_SIZE=0x40 \ -DWOLFBOOT_ORIGIN=MOCK_ADDRESS_BOOT -DBOOTLOADER_PARTITION_SIZE=WOLFBOOT_PARTITION_SIZE +unit-update-disk-diag:CFLAGS+=-DMOCK_PARTITIONS -DPRINTF_ENABLED -DWOLFBOOT_RAMBOOT_MAX_SIZE=0x40 \ + -DWOLFBOOT_ORIGIN=MOCK_ADDRESS_BOOT -DBOOTLOADER_PARTITION_SIZE=WOLFBOOT_PARTITION_SIZE \ + -DWOLFBOOT_PERSIST_FAILURE_STATUS +unit-update-disk-diag-plain:CFLAGS+=-DMOCK_PARTITIONS -DPRINTF_ENABLED -DWOLFBOOT_RAMBOOT_MAX_SIZE=0x40 \ + -DWOLFBOOT_ORIGIN=MOCK_ADDRESS_BOOT -DBOOTLOADER_PARTITION_SIZE=WOLFBOOT_PARTITION_SIZE \ + -DWOLFBOOT_PERSIST_FAILURE_STATUS -DUNIT_DISK_PLAIN unit-update-disk-confirm:CFLAGS+=-DMOCK_PARTITIONS -DPRINTF_ENABLED -DWOLFBOOT_RAMBOOT_MAX_SIZE=0x400 \ -DWOLFBOOT_ORIGIN=MOCK_ADDRESS_BOOT -DBOOTLOADER_PARTITION_SIZE=WOLFBOOT_PARTITION_SIZE +unit-update-disk-confirm-diag:CFLAGS+=-DMOCK_PARTITIONS -DPRINTF_ENABLED -DWOLFBOOT_RAMBOOT_MAX_SIZE=0x400 \ + -DWOLFBOOT_ORIGIN=MOCK_ADDRESS_BOOT -DBOOTLOADER_PARTITION_SIZE=WOLFBOOT_PARTITION_SIZE \ + -DWOLFBOOT_PERSIST_FAILURE_STATUS -DWOLFBOOT_DIAGNOSTICS_DISK_PART=1 \ + -DWOLFBOOT_DIAGNOSTICS_ADDRESS=0x500 -DWOLFBOOT_DIAGNOSTICS_SECTORS=1 +unit-update-disk-confirm-hooks:CFLAGS+=-DMOCK_PARTITIONS -DPRINTF_ENABLED -DWOLFBOOT_RAMBOOT_MAX_SIZE=0x400 \ + -DWOLFBOOT_ORIGIN=MOCK_ADDRESS_BOOT -DBOOTLOADER_PARTITION_SIZE=WOLFBOOT_PARTITION_SIZE \ + -DWOLFBOOT_CONFIRMED_IMAGE_HOOKS unit-update-disk-golden:CFLAGS+=-DMOCK_PARTITIONS -DPRINTF_ENABLED -DWOLFBOOT_RAMBOOT_MAX_SIZE=0x400 \ -DWOLFBOOT_ORIGIN=MOCK_ADDRESS_BOOT -DBOOTLOADER_PARTITION_SIZE=WOLFBOOT_PARTITION_SIZE unit-update-disk-failover:CFLAGS+=-DMOCK_PARTITIONS -DPRINTF_ENABLED -DWOLFBOOT_RAMBOOT_MAX_SIZE=0x400 \ -DWOLFBOOT_ORIGIN=MOCK_ADDRESS_BOOT -DBOOTLOADER_PARTITION_SIZE=WOLFBOOT_PARTITION_SIZE unit-update-disk-golden-enckey:CFLAGS+=-DMOCK_PARTITIONS -DPRINTF_ENABLED -DWOLFBOOT_RAMBOOT_MAX_SIZE=0x400 \ -DWOLFBOOT_ORIGIN=MOCK_ADDRESS_BOOT -DBOOTLOADER_PARTITION_SIZE=WOLFBOOT_PARTITION_SIZE +unit-update-disk-decrypt-fail:CFLAGS+=-DMOCK_PARTITIONS -DPRINTF_ENABLED -DWOLFBOOT_RAMBOOT_MAX_SIZE=0x400 \ + -DWOLFBOOT_ORIGIN=MOCK_ADDRESS_BOOT -DBOOTLOADER_PARTITION_SIZE=WOLFBOOT_PARTITION_SIZE # Non-FSP disk-boot OOB regression (CRIT-03). WOLFBOOT_RAMBOOT_MAX_SIZE is the # cap the loader applies to the unauthenticated header fw_size before loading to # RAM, the same bound update_disk.c and update_ram.c enforce. @@ -689,6 +715,12 @@ unit-update-disk-fs:CFLAGS+=-DMOCK_PARTITIONS -DPRINTF_ENABLED \ -DWOLFBOOT_DISK_FS -DWOLFBOOT_FAT32 -DWOLFBOOT_EXT4 \ -DWOLFBOOT_ORIGIN=MOCK_ADDRESS_BOOT \ -DBOOTLOADER_PARTITION_SIZE=WOLFBOOT_PARTITION_SIZE +unit-update-disk-fs-diag:CFLAGS+=-DMOCK_PARTITIONS -DPRINTF_ENABLED \ + -DWOLFBOOT_RAMBOOT_MAX_SIZE=0x1000 -DMAX_DISKS=1 \ + -DWOLFBOOT_DISK_FS -DWOLFBOOT_FAT32 -DWOLFBOOT_EXT4 \ + -DWOLFBOOT_ORIGIN=MOCK_ADDRESS_BOOT \ + -DBOOTLOADER_PARTITION_SIZE=WOLFBOOT_PARTITION_SIZE \ + -DWOLFBOOT_PERSIST_FAILURE_STATUS -DWOLFBOOT_DIAGNOSTICS_DISK_PART=2 unit-update-disk-oob:CFLAGS+=-DMOCK_PARTITIONS -DPRINTF_ENABLED \ -DWOLFBOOT_RAMBOOT_MAX_SIZE=0x1000 \ -DWOLFBOOT_ORIGIN=MOCK_ADDRESS_BOOT -DBOOTLOADER_PARTITION_SIZE=WOLFBOOT_PARTITION_SIZE @@ -1307,6 +1339,9 @@ unit-diagnostics: ../../include/target.h unit-diagnostics.c unit-diagnostics-256: ../../include/target.h unit-diagnostics.c gcc -o $@ unit-diagnostics.c $(CFLAGS) $(LDFLAGS) +unit-diagnostics-disk: ../../include/target.h unit-diagnostics-disk.c + gcc -o $@ unit-diagnostics-disk.c $(CFLAGS) $(LDFLAGS) + unit-enc-nvm: ../../include/target.h unit-enc-nvm.c gcc -o $@ $(WOLFCRYPT_SRC) unit-enc-nvm.c $(CFLAGS) $(WOLFCRYPT_CFLAGS) $(LDFLAGS) @@ -1580,6 +1615,9 @@ unit-update-ram-nofixed-noramboot: ../../include/target.h unit-update-ram-nofixe unit-update-ram-rollback-unconfirmed: ../../include/target.h unit-update-ram.c gcc -o $@ unit-update-ram.c ../../src/image.c $(WOLFBOOT_LIB_WOLFSSL)/wolfcrypt/src/sha256.c $(CFLAGS) $(LDFLAGS) +unit-update-ram-confirm-hooks: ../../include/target.h unit-update-ram.c + gcc -o $@ unit-update-ram.c ../../src/image.c $(WOLFBOOT_LIB_WOLFSSL)/wolfcrypt/src/sha256.c $(CFLAGS) $(LDFLAGS) + unit-update-ram-noramboot: ../../include/target.h unit-update-ram-noramboot.c gcc -o $@ unit-update-ram-noramboot.c ../../src/image.c $(WOLFBOOT_LIB_WOLFSSL)/wolfcrypt/src/sha256.c $(CFLAGS) $(LDFLAGS) @@ -1595,9 +1633,22 @@ unit-update-flash-hwswap: ../../include/target.h unit-update-flash-hwswap.c unit-update-disk: ../../include/target.h unit-update-disk.c gcc -o $@ unit-update-disk.c $(CFLAGS) $(LDFLAGS) +# unit-update-disk with failure diagnostics: which refusals are recorded +unit-update-disk-diag: ../../include/target.h unit-update-disk.c + gcc -o $@ unit-update-disk.c $(CFLAGS) $(LDFLAGS) + +unit-update-disk-diag-plain: ../../include/target.h unit-update-disk.c + gcc -o $@ unit-update-disk.c $(CFLAGS) $(LDFLAGS) + unit-update-disk-confirm: ../../include/target.h unit-update-disk-confirm.c gcc -o $@ unit-update-disk-confirm.c $(CFLAGS) $(LDFLAGS) +unit-update-disk-confirm-diag: ../../include/target.h unit-update-disk-confirm.c + gcc -o $@ unit-update-disk-confirm.c $(CFLAGS) $(LDFLAGS) + +unit-update-disk-confirm-hooks: ../../include/target.h unit-update-disk-confirm.c + gcc -o $@ unit-update-disk-confirm.c $(CFLAGS) $(LDFLAGS) + unit-update-disk-golden: ../../include/target.h unit-update-disk-golden.c gcc -o $@ unit-update-disk-golden.c $(CFLAGS) $(LDFLAGS) @@ -1607,6 +1658,9 @@ unit-update-disk-failover: ../../include/target.h unit-update-disk-failover.c unit-update-disk-golden-enckey: ../../include/target.h unit-update-disk-golden-enckey.c gcc -o $@ unit-update-disk-golden-enckey.c $(CFLAGS) $(LDFLAGS) +unit-update-disk-decrypt-fail: ../../include/target.h unit-update-disk-decrypt-fail.c + gcc -o $@ unit-update-disk-decrypt-fail.c $(CFLAGS) $(LDFLAGS) + # WOLFBOOT_FSP (x86) boot path of update_disk.c: the low-memory (tolum) # size check must reject a slot and fall back to the other one, like every # other per-slot rejection in the retry loop. @@ -1625,6 +1679,9 @@ unit-update-disk-oob: ../../include/target.h unit-update-disk-oob.c unit-update-disk-fs: ../../include/target.h unit-update-disk-fs.c gcc -o $@ unit-update-disk-fs.c $(CFLAGS) $(LDFLAGS) +unit-update-disk-fs-diag: ../../include/target.h unit-update-disk-fs.c + gcc -o $@ unit-update-disk-fs.c $(CFLAGS) $(LDFLAGS) + # Same source with disk encryption compiled in. The mock cipher's keystream # depends on the byte's position in the image, so this pins the fact that a # file's byte stream lines up with the CTR counter exactly as a raw @@ -1863,6 +1920,28 @@ efuse_guards_extract.h: ../../hal/zynq.c ../../hal/zynq.h unit-zynqmp-efuse-guards: unit-zynqmp-efuse-guards.c efuse_guards_extract.h ../../hal/zynq.h gcc -o $@ unit-zynqmp-efuse-guards.c $(CFLAGS) -I../.. $(LDFLAGS) +# unit-zynqmp-efuse-counter covers the user-eFuse security version counter +# encoding (set-bit count, lowest-clear-bits-first raise), extracted verbatim. +efuse_counter_extract.h: ../../hal/zynq.c + sed -n '/^uint32_t zynqmp_efuse_counter_value(/,/^}/p' $< > $@ + sed -n '/^int zynqmp_efuse_counter_bits(/,/^}/p' $< >> $@ + +unit-zynqmp-efuse-counter: unit-zynqmp-efuse-counter.c efuse_counter_extract.h + gcc -o $@ unit-zynqmp-efuse-counter.c $(CFLAGS) $(LDFLAGS) + +# unit-zynqmp-sec-bl33 covers the eFuse security state read through the PMU +# firmware (BL33), including a read the firmware reports as done without +# writing the word. The functions under test are extracted verbatim. +sec_bl33_extract.h: ../../hal/zynq.c + sed -n '/^#define ZYNQMP_EFUSE_READ_UNSET /p' $< > $@ + sed -n '/^static int zynqmp_efuse_cache_read(/,/^}/p' $< >> $@ + sed -n '/^typedef struct zynqmp_sec_state {/,/^} zynqmp_sec_state;/p' $< >> $@ + sed -n '/^static int zynqmp_sec_state_get(/,/^}/p' $< >> $@ + sed -n '/^int zynqmp_sec_policy_check(/,/^}/p' $< >> $@ + +unit-zynqmp-sec-bl33: unit-zynqmp-sec-bl33.c sec_bl33_extract.h ../../hal/zynq.h + gcc -o $@ unit-zynqmp-sec-bl33.c $(CFLAGS) -I../.. $(LDFLAGS) + # Same source, compiled with the program strobe enabled, so the burn-only # error paths (T-bit refusal, program timeout, cache-reload timeout) and the # PGM_EN/WR_LOCK cleanup are covered as well as report-only behaviour. @@ -3037,7 +3116,8 @@ GENERATED_SRC:=aurix_erased_extract.h elf_store_extract.h \ versal_wdt_extract.h \ versal_host.h versal_qspidev_extract.h versal_uart_rx_extract.h \ raspi3_uart_rx_extract.h zynq_erase_extract.h \ - bbram_crc_extract.h efuse_guards_extract.h \ + bbram_crc_extract.h efuse_guards_extract.h efuse_counter_extract.h \ + sec_bl33_extract.h \ puf_extract.h \ zynq_write_extract.h \ fat32-test.img fat32-test.img.tmp fat32-payload.bin fat32-nested.bin \ diff --git a/tools/unit-tests/unit-diagnostics-disk.c b/tools/unit-tests/unit-diagnostics-disk.c new file mode 100644 index 0000000000..dd525dda16 --- /dev/null +++ b/tools/unit-tests/unit-diagnostics-disk.c @@ -0,0 +1,215 @@ +/* unit-diagnostics-disk.c + * + * Failure diagnostics store kept in a partition of the boot disk + * (WOLFBOOT_DIAGNOSTICS_DISK_PART): the same circular log as the flash store, + * over disk_part_read()/disk_part_write(), with erase emulated by writing the + * erased pattern. + * + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of wolfBoot. + * + * wolfBoot 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. + * + * wolfBoot 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 + */ +#define WOLFBOOT_HASH_SHA256 +#define IMAGE_HEADER_SIZE 256 +#define WOLFBOOT_PERSIST_FAILURE_STATUS +#define WOLFBOOT_DIAGNOSTICS_DISK_PART 3 +#define WOLFBOOT_DIAGNOSTICS_SECTORS 2 +#define WC_RSA_BLINDING +#define ECC_TIMING_RESISTANT +#include +#include "libwolfboot.c" +#include +#include +#include +#include + +#include "unit-mock-flash.c" + +Suite *wolfboot_suite(void); + +#define DIAG_REGION_SIZE (WOLFBOOT_DIAGNOSTICS_SECTORS * WOLFBOOT_SECTOR_SIZE) + +/* The diagnostics partition, as the disk layer would present it */ +static uint8_t diag_part[DIAG_REGION_SIZE]; +static int disk_is_open; +static int disk_write_fail; +static int disk_writes; + +int disk_part_read(int drv, int part, uint64_t off, uint64_t sz, uint8_t *buf) +{ + ck_assert_int_eq(drv, 0); + ck_assert_int_eq(part, WOLFBOOT_DIAGNOSTICS_DISK_PART); + if (!disk_is_open || off >= sizeof(diag_part)) + return -1; + if (sz > sizeof(diag_part) - off) + sz = sizeof(diag_part) - off; + memcpy(buf, diag_part + off, (size_t)sz); + return (int)sz; +} + +int disk_part_write(int drv, int part, uint64_t off, uint64_t sz, + const uint8_t *buf) +{ + ck_assert_int_eq(drv, 0); + ck_assert_int_eq(part, WOLFBOOT_DIAGNOSTICS_DISK_PART); + if (!disk_is_open || disk_write_fail || off >= sizeof(diag_part)) + return -1; + if (sz > sizeof(diag_part) - off) + sz = sizeof(diag_part) - off; + memcpy(diag_part + off, buf, (size_t)sz); + disk_writes++; + return (int)sz; +} + +static void disk_reset(uint8_t fill) +{ + memset(diag_part, fill, sizeof(diag_part)); + disk_is_open = 1; + disk_write_fail = 0; + disk_writes = 0; +} + +static void record_one(uint8_t cause, uint8_t slot, uint32_t ver) +{ + ck_assert_int_eq(wolfBoot_record_failure(WOLFBOOT_FAILURE_PHASE_BOOT, + cause, slot, ver), 0); +} + +START_TEST(test_disk_record_and_read) +{ + struct wolfBoot_failure_record rec; + + /* A new partition holds zeros, not the erased pattern */ + disk_reset(0x00); + ck_assert_int_eq(wolfBoot_get_failure_count(), 0); + + record_one(WOLFBOOT_FAILURE_CAUSE_SIGNATURE, 0, 7); + record_one(WOLFBOOT_FAILURE_CAUSE_DECRYPT, 1, 8); + record_one(WOLFBOOT_FAILURE_CAUSE_VERSION, 2, 0); + ck_assert_int_eq(wolfBoot_get_failure_count(), 3); + + ck_assert_int_eq(wolfBoot_get_failure(0, &rec), 0); + ck_assert_uint_eq(rec.cause, WOLFBOOT_FAILURE_CAUSE_VERSION); + ck_assert_uint_eq(rec.partition, 2); + ck_assert_int_eq(wolfBoot_get_failure(2, &rec), 0); + ck_assert_uint_eq(rec.cause, WOLFBOOT_FAILURE_CAUSE_SIGNATURE); + ck_assert_uint_eq(rec.partition, 0); + ck_assert_uint_eq(rec.fw_version, 7); + + /* The bytes on the partition decode the same way */ + ck_assert_uint_eq(((struct wolfBoot_diag_header *)diag_part)->magic, + DIAG_HDR_MAGIC); +} +END_TEST + +START_TEST(test_disk_ring_wrap) +{ + struct wolfBoot_failure_record rec; + int slots = (int)DIAG_SLOTS_PER_SECTOR; + int total = 2 * slots + 1; + int count, i; + + disk_reset(0x00); + for (i = 1; i <= total; i++) + record_one(WOLFBOOT_FAILURE_CAUSE_HASH, 0, (uint32_t)i); + count = wolfBoot_get_failure_count(); + ck_assert_int_eq(count, slots + 1); + for (i = 0; i < count; i++) { + ck_assert_int_eq(wolfBoot_get_failure(i, &rec), 0); + ck_assert_uint_eq(rec.fw_version, (uint32_t)(total - i)); + } +} +END_TEST + +START_TEST(test_disk_torn_slot_rotates) +{ + struct wolfBoot_failure_record rec; + + disk_reset(0x00); + record_one(WOLFBOOT_FAILURE_CAUSE_HASH, 0, 1); + /* Garbage where the next record would go: not erased, not valid */ + diag_part[DIAG_HDR_SIZE + DIAG_RECORD_SIZE] = 0x5A; + record_one(WOLFBOOT_FAILURE_CAUSE_HASH, 0, 2); + ck_assert_int_eq(wolfBoot_get_failure(0, &rec), 0); + ck_assert_uint_eq(rec.fw_version, 2); + ck_assert_int_eq(wolfBoot_get_failure(1, &rec), 0); + ck_assert_uint_eq(rec.fw_version, 1); +} +END_TEST + +START_TEST(test_disk_not_open) +{ + disk_reset(0x00); + disk_is_open = 0; + ck_assert_int_eq(wolfBoot_record_failure(WOLFBOOT_FAILURE_PHASE_BOOT, + WOLFBOOT_FAILURE_CAUSE_POLICY, 0, 0), -1); + ck_assert_int_eq(disk_writes, 0); + ck_assert_int_eq(wolfBoot_get_failure_count(), 0); +} +END_TEST + +START_TEST(test_disk_write_error) +{ + disk_reset(0x00); + disk_write_fail = 1; + ck_assert_int_eq(wolfBoot_record_failure(WOLFBOOT_FAILURE_PHASE_BOOT, + WOLFBOOT_FAILURE_CAUSE_HASH, 0, 0), -1); + disk_write_fail = 0; + ck_assert_int_eq(wolfBoot_get_failure_count(), 0); +} +END_TEST + +START_TEST(test_disk_clear) +{ + size_t i; + + disk_reset(0x00); + record_one(WOLFBOOT_FAILURE_CAUSE_HASH, 0, 1); + ck_assert_int_eq(wolfBoot_clear_failures(), 0); + ck_assert_int_eq(wolfBoot_get_failure_count(), 0); + for (i = 0; i < sizeof(diag_part); i++) + ck_assert_uint_eq(diag_part[i], FLASH_BYTE_ERASED); +} +END_TEST + +Suite *wolfboot_suite(void) +{ + Suite *s = suite_create("wolfboot-diagnostics-disk"); + TCase *tc = tcase_create("disk"); + + tcase_add_test(tc, test_disk_record_and_read); + tcase_add_test(tc, test_disk_ring_wrap); + tcase_add_test(tc, test_disk_torn_slot_rotates); + tcase_add_test(tc, test_disk_not_open); + tcase_add_test(tc, test_disk_write_error); + tcase_add_test(tc, test_disk_clear); + suite_add_tcase(s, tc); + return s; +} + +int main(void) +{ + int fails; + Suite *s = wolfboot_suite(); + SRunner *sr = srunner_create(s); + + srunner_run_all(sr, CK_NORMAL); + fails = srunner_ntests_failed(sr); + srunner_free(sr); + return fails; +} diff --git a/tools/unit-tests/unit-update-disk-confirm.c b/tools/unit-tests/unit-update-disk-confirm.c index ab71446099..a6da396e97 100644 --- a/tools/unit-tests/unit-update-disk-confirm.c +++ b/tools/unit-tests/unit-update-disk-confirm.c @@ -33,7 +33,12 @@ static uint8_t load_buffer[IMAGE_HEADER_SIZE + TEST_PAYLOAD_SIZE + 1024]; /* A real partition is far larger than its image; the boot-state record lives * in its last 512-byte sector. Size the mock so image and record cannot * overlap, which is the layout the loader requires. */ +#ifdef WOLFBOOT_PERSIST_FAILURE_STATUS +/* Room for the failure log after WOLFBOOT_RAMBOOT_MAX_SIZE */ +#define TEST_PART_SIZE 0x1000 +#else #define TEST_PART_SIZE (IMAGE_HEADER_SIZE + TEST_PAYLOAD_SIZE + 1024) +#endif #define TEST_STATE_OFF (TEST_PART_SIZE - 512) static uint8_t part_a_image[TEST_PART_SIZE]; @@ -288,6 +293,48 @@ int hal_flash_protect(haladdr_t address, int len) return 0; } +#ifdef WOLFBOOT_CONFIRMED_IMAGE_HOOKS +/* Order of confirmed-image policy calls made by wolfBoot_start() */ +#define MAX_POLICY_CALLS 4 +static int policy_calls; +static uint32_t policy_version[MAX_POLICY_CALLS]; +static int policy_confirmed[MAX_POLICY_CALLS]; + +void wolfBoot_apply_confirmed_image(struct wolfBoot_image *img, int confirmed) +{ + if (policy_calls < MAX_POLICY_CALLS) { + /* build_image() puts the version TLV first */ + memcpy(&policy_version[policy_calls], + img->hdr + IMAGE_HEADER_OFFSET + 2 * sizeof(uint16_t), + sizeof(uint32_t)); + policy_confirmed[policy_calls] = confirmed; + } + policy_calls++; +} +#endif + +#ifdef WOLFBOOT_PERSIST_FAILURE_STATUS +static int mock_records; + +int wolfBoot_record_failure(uint8_t phase, uint8_t cause, uint8_t partition, + uint32_t fw_version) +{ + (void)phase; + (void)cause; + (void)partition; + (void)fw_version; + mock_records++; + return 0; +} + +int wolfBoot_get_failure(int index, struct wolfBoot_failure_record *out) +{ + (void)index; + (void)out; + return -1; +} +#endif + #include "update_disk.c" @@ -592,6 +639,133 @@ START_TEST(test_failover_does_not_land_on_a_testing_slot) } END_TEST +#ifdef WOLFBOOT_CONFIRMED_IMAGE_HOOKS +/* A confirmed slot's policy is applied before a fresh update in the other + * slot is verified, so the update is checked against it. */ +START_TEST(test_confirmed_policy_before_trial) +{ + reset_mocks(); + policy_calls = 0; + build_image(part_a_image, 4, 0xA1); + build_image(part_b_image, 5, 0xB2); + set_state(part_a_image, ST_SUCCESS); + set_state(part_b_image, ST_UPDATING); + + wolfBoot_start(); + + ck_assert_int_eq(wolfBoot_panicked, 0); + ck_assert_int_eq(mock_do_boot_called, 1); + ck_assert_int_eq(memcmp(load_buffer, part_b_image + IMAGE_HEADER_SIZE, + TEST_PAYLOAD_SIZE), 0); + ck_assert_int_eq(policy_calls, 2); + ck_assert_uint_eq(policy_version[0], 4U); + ck_assert_int_eq(policy_confirmed[0], 1); + ck_assert_uint_eq(policy_version[1], 5U); + ck_assert_int_eq(policy_confirmed[1], 0); +} +END_TEST + +/* A confirmed slot that cannot be read is skipped: the update still boots + * and nothing is applied from the unread slot. */ +START_TEST(test_unreadable_confirmed_slot_still_boots_trial) +{ + reset_mocks(); + policy_calls = 0; + build_image(part_a_image, 4, 0xA1); + build_image(part_b_image, 5, 0xB2); + set_state(part_a_image, ST_SUCCESS); + set_state(part_b_image, ST_UPDATING); + mock_fail_payload_part = BOOT_PART_A; + + wolfBoot_start(); + + ck_assert_int_eq(wolfBoot_panicked, 0); + ck_assert_int_eq(mock_do_boot_called, 1); + ck_assert_int_eq(memcmp(load_buffer, part_b_image + IMAGE_HEADER_SIZE, + TEST_PAYLOAD_SIZE), 0); + ck_assert_int_eq(policy_calls, 1); + ck_assert_uint_eq(policy_version[0], 5U); + ck_assert_int_eq(policy_confirmed[0], 0); +} +END_TEST +#endif + +#ifdef WOLFBOOT_PERSIST_FAILURE_STATUS +/* The failure log shares slot B's partition. Its region plus the boot state + * trailer, the partition's last DISK_TRAILER_SZ bytes. */ +#define DIAG_LOG_END (WOLFBOOT_DIAGNOSTICS_ADDRESS + \ + WOLFBOOT_DIAGNOSTICS_SECTORS * WOLFBOOT_SECTOR_SIZE) + +START_TEST(test_diag_log_clear_of_the_trailer_records) +{ + reset_mocks(); + mock_records = 0; + build_image(part_a_image, 4, 0xA1); + build_image(part_b_image, 5, 0xB2); + mock_part_size = DIAG_LOG_END + DISK_TRAILER_SZ; + mock_verify_authenticity_ret = -1; + + wolfBoot_start(); + + ck_assert_int_eq(wolfBoot_panicked, 1); + ck_assert_int_gt(mock_records, 0); +} +END_TEST + +START_TEST(test_diag_log_reap_records_when_clear) +{ + reset_mocks(); + mock_records = 0; + build_image(part_a_image, 5, 0xA1); + build_image(part_b_image, 4, 0xB2); + mock_part_size = DIAG_LOG_END + DISK_TRAILER_SZ; + set_state_at(part_a_image, (size_t)mock_part_size, ST_TESTING); + set_state_at(part_b_image, (size_t)mock_part_size, ST_SUCCESS); + + wolfBoot_start(); + + ck_assert_int_eq(mock_do_boot_called, 1); + ck_assert_int_eq(mock_records, 1); +} +END_TEST + +/* An unconfirmed slot is dropped without writing the log over the trailer */ +START_TEST(test_diag_log_reap_over_the_trailer_is_not_written) +{ + reset_mocks(); + mock_records = 0; + build_image(part_a_image, 5, 0xA1); + build_image(part_b_image, 4, 0xB2); + mock_part_size = DIAG_LOG_END + DISK_TRAILER_SZ - 1; + set_state_at(part_a_image, (size_t)mock_part_size, ST_TESTING); + set_state_at(part_b_image, (size_t)mock_part_size, ST_SUCCESS); + + wolfBoot_start(); + + ck_assert_int_eq(mock_do_boot_called, 1); + ck_assert_int_eq(mock_records, 0); + ck_assert_uint_eq(get_state_at(part_a_image, (size_t)mock_part_size), + ST_TESTING); +} +END_TEST + +START_TEST(test_diag_log_over_the_trailer_is_not_written) +{ + reset_mocks(); + mock_records = 0; + build_image(part_a_image, 4, 0xA1); + build_image(part_b_image, 5, 0xB2); + mock_part_size = DIAG_LOG_END + DISK_TRAILER_SZ - 1; + mock_verify_authenticity_ret = -1; + + wolfBoot_start(); + + ck_assert_int_eq(wolfBoot_panicked, 1); + ck_assert_int_eq(mock_records, 0); +} +END_TEST +#endif + Suite *wolfboot_suite(void) { Suite *s = suite_create("wolfBoot"); @@ -608,6 +782,16 @@ Suite *wolfboot_suite(void) tcase_add_test(tc, test_partition_too_small_for_a_trailer_still_boots); tcase_add_test(tc, test_two_unconfirmed_slots_boot_neither); tcase_add_test(tc, test_failover_does_not_land_on_a_testing_slot); +#ifdef WOLFBOOT_CONFIRMED_IMAGE_HOOKS + tcase_add_test(tc, test_confirmed_policy_before_trial); + tcase_add_test(tc, test_unreadable_confirmed_slot_still_boots_trial); +#endif +#ifdef WOLFBOOT_PERSIST_FAILURE_STATUS + tcase_add_test(tc, test_diag_log_clear_of_the_trailer_records); + tcase_add_test(tc, test_diag_log_over_the_trailer_is_not_written); + tcase_add_test(tc, test_diag_log_reap_records_when_clear); + tcase_add_test(tc, test_diag_log_reap_over_the_trailer_is_not_written); +#endif suite_add_tcase(s, tc); return s; diff --git a/tools/unit-tests/unit-update-disk-decrypt-fail.c b/tools/unit-tests/unit-update-disk-decrypt-fail.c new file mode 100644 index 0000000000..65d41d42f5 --- /dev/null +++ b/tools/unit-tests/unit-update-disk-decrypt-fail.c @@ -0,0 +1,376 @@ +/* unit-update-disk-decrypt-fail.c + * + * Unit test for cipher failures while booting an encrypted disk image: a + * failed IV set or decrypt must skip the slot rather than boot it, and the + * cipher context and nonce must be wiped before the handoff. + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of wolfBoot. + * + * wolfBoot 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. + * + * wolfBoot 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-1301, USA + */ + +#define WOLFBOOT_UPDATE_DISK +#define WOLFBOOT_SELF_UPDATE_MONOLITHIC +#define RAM_CODE +#define WOLFBOOT_SELF_HEADER +#define EXT_ENCRYPTED +#define ENCRYPT_WITH_CHACHA +#define HAVE_CHACHA +#define IMAGE_HEADER_SIZE 256 +#define BOOT_PART_A 0 +#define BOOT_PART_B 1 +#define MOCK_ADDRESS_BOOT 0xCD000000 + +#include +#include +#include +#include + +#include "hal.h" +#include "target.h" +#include "wolfboot/wolfboot.h" +#include "image.h" +#include "loader.h" +#include + +#define TEST_PAYLOAD_SIZE 64 +#define TEST_PART_SIZE (IMAGE_HEADER_SIZE + TEST_PAYLOAD_SIZE + 1024) +#define FILL_A 0xA1 +#define FILL_B 0xB2 +#define N_PARTS 2 +#define KEY_BYTE 0x5A +#define ENC_LEN (IMAGE_HEADER_SIZE + TEST_PAYLOAD_SIZE) + +static uint8_t load_buffer[TEST_PART_SIZE]; +#define WOLFBOOT_LOAD_ADDRESS ((uintptr_t)load_buffer) + +static uint8_t part_image[N_PARTS][TEST_PART_SIZE]; +static int mock_do_boot_called; +static int mock_booted_fill; +/* Number of upcoming header (counter 0) or payload (counter != 0) IV sets, + * and payload decrypts, that fail. */ +static int fail_header_iv; +static int fail_payload_iv; +static int fail_payload_decrypt; +static int ctx_wiped_at_boot; +static int nonce_wiped_at_boot; +ChaCha chacha; + +static void set_u16_le(uint8_t *dst, uint16_t value) +{ + dst[0] = (uint8_t)(value & 0xFF); + dst[1] = (uint8_t)(value >> 8); +} + +static void set_u32_le(uint8_t *dst, uint32_t value) +{ + dst[0] = (uint8_t)(value & 0xFF); + dst[1] = (uint8_t)((value >> 8) & 0xFF); + dst[2] = (uint8_t)((value >> 16) & 0xFF); + dst[3] = (uint8_t)(value >> 24); +} + +static void build_image(uint8_t *image, uint32_t version, uint8_t fill) +{ + int i; + + memset(image, 0, TEST_PART_SIZE); + set_u32_le(image, WOLFBOOT_MAGIC); + set_u32_le(image + sizeof(uint32_t), TEST_PAYLOAD_SIZE); + set_u16_le(image + IMAGE_HEADER_OFFSET, HDR_VERSION); + set_u16_le(image + IMAGE_HEADER_OFFSET + sizeof(uint16_t), 4); + set_u32_le(image + IMAGE_HEADER_OFFSET + 2 * sizeof(uint16_t), version); + memset(image + IMAGE_HEADER_SIZE, fill, TEST_PAYLOAD_SIZE); + for (i = 0; i < ENC_LEN; i++) { + image[i] ^= KEY_BYTE; + } +} + +static int all_zero(const void *p, size_t len) +{ + const uint8_t *b = (const uint8_t *)p; + size_t i; + for (i = 0; i < len; i++) { + if (b[i] != 0) + return 0; + } + return 1; +} + +static void reset_mocks(void) +{ + memset(load_buffer, 0, sizeof(load_buffer)); + build_image(part_image[BOOT_PART_A], 3, FILL_A); + build_image(part_image[BOOT_PART_B], 2, FILL_B); + mock_do_boot_called = 0; + mock_booted_fill = -1; + fail_header_iv = 0; + fail_payload_iv = 0; + fail_payload_decrypt = 0; + ctx_wiped_at_boot = 0; + nonce_wiped_at_boot = 0; + wolfBoot_panicked = 0; +} + +int chacha_init(void) +{ + /* Stand-in for the expanded key held in the context. */ + memset(&chacha, KEY_BYTE, sizeof(chacha)); + return 0; +} + +int wc_Chacha_SetIV(ChaCha* ctx, const byte* inIv, word32 counter) +{ + (void)ctx; (void)inIv; + if (counter == 0 && fail_header_iv > 0) { + fail_header_iv--; + return -1; + } + if (counter != 0 && fail_payload_iv > 0) { + fail_payload_iv--; + return -1; + } + return 0; +} + +int wc_Chacha_Process(ChaCha* ctx, byte* output, const byte* input, + word32 msglen) +{ + word32 i; + (void)ctx; + if (msglen == TEST_PAYLOAD_SIZE && fail_payload_decrypt > 0) { + fail_payload_decrypt--; + return -1; + } + for (i = 0; i < msglen; i++) { + output[i] = (byte)(input[i] ^ KEY_BYTE); + } + return 0; +} + +void wc_ForceZero(void* mem, size_t len) +{ + volatile uint8_t *p = (volatile uint8_t *)mem; + while (len-- > 0) + *p++ = 0; +} + +int wolfBoot_initialize_encryption(void) +{ + return chacha_init(); +} + +int wolfBoot_get_encrypt_key(uint8_t *key, uint8_t *nonce) +{ + memset(key, KEY_BYTE, ENCRYPT_KEY_SIZE); + memset(nonce, 0xC3, ENCRYPT_NONCE_SIZE); + return 0; +} + +int disk_init(int drv) +{ + (void)drv; + return 0; +} + +int disk_open(int drv) +{ + (void)drv; + return 0; +} + +void disk_close(int drv) +{ + (void)drv; +} + +int disk_part_read(int drv, int part, uint64_t off, uint64_t sz, uint8_t *buf) +{ + (void)drv; + if (part < 0 || part >= N_PARTS) + return -1; + if ((off > TEST_PART_SIZE) || (sz > (TEST_PART_SIZE - off))) + return -1; + memcpy(buf, part_image[part] + off, (size_t)sz); + return (int)sz; +} + +int disk_part_write(int drv, int part, uint64_t off, uint64_t sz, + const uint8_t *buf) +{ + (void)drv; + if (part < 0 || part >= N_PARTS) + return -1; + if ((off > TEST_PART_SIZE) || (sz > (TEST_PART_SIZE - off))) + return -1; + memcpy(part_image[part] + off, buf, (size_t)sz); + return (int)sz; +} + +int disk_part_size(int drv, int part, uint64_t *size) +{ + (void)drv; + if (part < 0 || part >= N_PARTS) + return -1; + *size = TEST_PART_SIZE; + return 0; +} + +int wolfBoot_open_image_address(struct wolfBoot_image* img, uint8_t* image) +{ + uint32_t magic; + uint32_t fw_size; + + memcpy(&magic, image, sizeof(magic)); + if (magic != WOLFBOOT_MAGIC) + return -1; + memset(img, 0, sizeof(*img)); + img->hdr = image; + memcpy(&fw_size, image + sizeof(uint32_t), sizeof(fw_size)); + img->fw_size = fw_size; + img->fw_base = image + IMAGE_HEADER_SIZE; + img->hdr_ok = 1; + return 0; +} + +int wolfBoot_verify_integrity(struct wolfBoot_image* img) +{ + img->sha_ok = 1; + return 0; +} + +int wolfBoot_verify_authenticity(struct wolfBoot_image* img) +{ + img->signature_ok = 1; + return 0; +} + +int wolfBoot_image_part_matches(struct wolfBoot_image* img) +{ + (void)img; + return 0; +} + +int wolfBoot_get_dts_size(void *dts_addr, uint32_t capacity) +{ + (void)capacity; (void)dts_addr; + return -1; +} + +void hal_prepare_boot(void) +{ +} + +int hal_flash_protect(haladdr_t address, int len) +{ + (void)address; (void)len; + return 0; +} + +#include "update_disk.c" + +void do_boot(const uint32_t *address) +{ + mock_do_boot_called++; + mock_booted_fill = ((const uint8_t*)address)[0]; + ctx_wiped_at_boot = all_zero(&chacha, sizeof(chacha)); + nonce_wiped_at_boot = all_zero(disk_encrypt_nonce, + sizeof(disk_encrypt_nonce)); +} + +START_TEST(test_decrypted_image_boots_with_cipher_state_wiped) +{ + reset_mocks(); + wolfBoot_start(); + ck_assert_int_eq(wolfBoot_panicked, 0); + ck_assert_int_eq(mock_booted_fill, FILL_A); + ck_assert_int_eq(ctx_wiped_at_boot, 1); + ck_assert_int_eq(nonce_wiped_at_boot, 1); +} +END_TEST + +/* B is built at A's version for the failover cases: falling back to a lower + * version is a downgrade, which the loader refuses on its own. */ +START_TEST(test_payload_iv_failure_skips_the_slot) +{ + reset_mocks(); + build_image(part_image[BOOT_PART_B], 3, FILL_B); + fail_payload_iv = 1; + wolfBoot_start(); + ck_assert_int_eq(wolfBoot_panicked, 0); + ck_assert_int_eq(mock_booted_fill, FILL_B); +} +END_TEST + +START_TEST(test_payload_decrypt_failure_skips_the_slot) +{ + reset_mocks(); + build_image(part_image[BOOT_PART_B], 3, FILL_B); + fail_payload_decrypt = 1; + wolfBoot_start(); + ck_assert_int_eq(wolfBoot_panicked, 0); + ck_assert_int_eq(mock_booted_fill, FILL_B); +} +END_TEST + +START_TEST(test_payload_decrypt_failure_on_both_slots_fails_closed) +{ + reset_mocks(); + build_image(part_image[BOOT_PART_B], 3, FILL_B); + fail_payload_decrypt = 1000; + wolfBoot_start(); + ck_assert_int_eq(mock_do_boot_called, 0); + ck_assert_int_ne(wolfBoot_panicked, 0); +} +END_TEST + +START_TEST(test_header_iv_failure_on_both_slots_fails_closed) +{ + reset_mocks(); + fail_header_iv = 1000; + wolfBoot_start(); + ck_assert_int_eq(mock_do_boot_called, 0); + ck_assert_int_ne(wolfBoot_panicked, 0); +} +END_TEST + +Suite *wolfboot_suite(void) +{ + Suite *s = suite_create("wolfBoot"); + TCase *tc = tcase_create("update-disk-decrypt-fail"); + + tcase_add_test(tc, test_decrypted_image_boots_with_cipher_state_wiped); + tcase_add_test(tc, test_payload_iv_failure_skips_the_slot); + tcase_add_test(tc, test_payload_decrypt_failure_skips_the_slot); + tcase_add_test(tc, test_payload_decrypt_failure_on_both_slots_fails_closed); + tcase_add_test(tc, test_header_iv_failure_on_both_slots_fails_closed); + + suite_add_tcase(s, tc); + return s; +} + +int main(void) +{ + int fails; + Suite *s = wolfboot_suite(); + SRunner *sr = srunner_create(s); + + srunner_run_all(sr, CK_NORMAL); + fails = srunner_ntests_failed(sr); + srunner_free(sr); + return fails; +} diff --git a/tools/unit-tests/unit-update-disk-fs.c b/tools/unit-tests/unit-update-disk-fs.c index 55bba3483e..5c01411326 100644 --- a/tools/unit-tests/unit-update-disk-fs.c +++ b/tools/unit-tests/unit-update-disk-fs.c @@ -738,6 +738,28 @@ int hal_flash_protect(haladdr_t address, int len) #ifdef WOLFBOOT_FDT #include "fdt.c" #endif +#ifdef WOLFBOOT_PERSIST_FAILURE_STATUS +static int mock_records; + +int wolfBoot_record_failure(uint8_t phase, uint8_t cause, uint8_t partition, + uint32_t fw_version) +{ + (void)phase; + (void)cause; + (void)partition; + (void)fw_version; + mock_records++; + return 0; +} + +int wolfBoot_get_failure(int index, struct wolfBoot_failure_record *out) +{ + (void)index; + (void)out; + return -1; +} +#endif + #include "update_disk.c" /* --- tests --- */ @@ -1432,6 +1454,38 @@ END_TEST #endif /* WOLFBOOT_FDT */ #endif /* DISK_BOOT_CONFIRM */ +#ifdef WOLFBOOT_PERSIST_FAILURE_STATUS +/* The log partition is free: recording stays on */ +START_TEST(test_fs_diag_partition_clear_of_slots_records) +{ + reset_mocks(); + open_disk(); + disk_diag_off = 0; + boot_slots[0].part = 0; + boot_slots[1].part = 1; + + disk_report_last_failure(); + + ck_assert_int_eq(disk_diag_off, 0); +} +END_TEST + +/* A slot resolved (by label) to the log partition turns recording off */ +START_TEST(test_fs_diag_partition_holding_a_slot_is_not_written) +{ + reset_mocks(); + open_disk(); + disk_diag_off = 0; + boot_slots[0].part = 0; + boot_slots[1].part = WOLFBOOT_DIAGNOSTICS_DISK_PART; + + disk_report_last_failure(); + + ck_assert_int_eq(disk_diag_off, 1); +} +END_TEST +#endif + static Suite *wolfboot_suite(void) { Suite *s = suite_create("wolfboot-update-disk-fs"); @@ -1442,6 +1496,10 @@ static Suite *wolfboot_suite(void) tcase_set_timeout(tc, 60); tcase_add_test(tc, test_fs_boots_higher_version_across_filesystems); +#ifdef WOLFBOOT_PERSIST_FAILURE_STATUS + tcase_add_test(tc, test_fs_diag_partition_clear_of_slots_records); + tcase_add_test(tc, test_fs_diag_partition_holding_a_slot_is_not_written); +#endif tcase_add_test(tc, test_fs_boots_from_fat32_when_it_is_newer); tcase_add_test(tc, test_fs_falls_back_when_file_is_missing); tcase_add_test(tc, test_fs_rejects_truncated_file); diff --git a/tools/unit-tests/unit-update-disk.c b/tools/unit-tests/unit-update-disk.c index 8bc993cf33..aed551c3f5 100644 --- a/tools/unit-tests/unit-update-disk.c +++ b/tools/unit-tests/unit-update-disk.c @@ -2,9 +2,11 @@ #define WOLFBOOT_SELF_UPDATE_MONOLITHIC #define RAM_CODE #define WOLFBOOT_SELF_HEADER +#ifndef UNIT_DISK_PLAIN #define EXT_ENCRYPTED #define ENCRYPT_WITH_CHACHA #define HAVE_CHACHA +#endif #define IMAGE_HEADER_SIZE 256 #define BOOT_PART_A 0 #define BOOT_PART_B 1 @@ -20,7 +22,9 @@ #include "wolfboot/wolfboot.h" #include "image.h" #include "loader.h" +#ifndef UNIT_DISK_PLAIN #include +#endif #define TEST_PAYLOAD_SIZE 64 @@ -34,6 +38,8 @@ static int mock_disk_close_called; static int mock_do_boot_called; static const uint32_t *mock_boot_address; static int mock_fail_payload_part; +static int mock_fail_all_reads; +static int mock_fail_header_part; static int mock_verify_integrity_ret; /* not_ext as the verify calls saw it: the staged image lives in RAM, so an * EXT_FLASH build must not route these reads back through external flash. */ @@ -43,7 +49,9 @@ static int mock_verify_authenticity_ret; static int mock_part_mismatch_part; static int mock_last_read_part; +#ifndef UNIT_DISK_PLAIN ChaCha chacha; +#endif static void set_u16_le(uint8_t *dst, uint16_t value) { @@ -86,6 +94,8 @@ static void reset_mocks(void) mock_do_boot_called = 0; mock_boot_address = NULL; mock_fail_payload_part = -1; + mock_fail_all_reads = 0; + mock_fail_header_part = -1; mock_verify_integrity_ret = 0; mock_verify_authenticity_ret = 0; mock_part_mismatch_part = -2; @@ -98,6 +108,7 @@ static void reset_mocks(void) wolfBoot_panicked = 0; } +#ifndef UNIT_DISK_PLAIN int chacha_init(void) { return 0; @@ -117,6 +128,7 @@ int wc_Chacha_Process(ChaCha* ctx, byte* output, const byte* input, word32 msgle memmove(output, input, msglen); return 0; } +#endif void wc_ForceZero(void* mem, size_t len) { @@ -126,6 +138,7 @@ void wc_ForceZero(void* mem, size_t len) } } +#ifndef UNIT_DISK_PLAIN int wolfBoot_initialize_encryption(void) { return 0; @@ -137,6 +150,22 @@ int wolfBoot_get_encrypt_key(uint8_t *key, uint8_t *nonce) memset(nonce, 0xC3, ENCRYPT_NONCE_SIZE); return 0; } +#endif + +#ifdef UNIT_DISK_PLAIN +/* The layout build_image() writes: magic, then the version TLV first */ +uint32_t wolfBoot_get_blob_version(uint8_t *blob) +{ + uint32_t magic, ver; + + memcpy(&magic, blob, sizeof(magic)); + if (magic != WOLFBOOT_MAGIC) + return 0; + memcpy(&ver, blob + IMAGE_HEADER_OFFSET + 2 * sizeof(uint16_t), + sizeof(ver)); + return ver; +} +#endif int disk_init(int drv) { @@ -163,6 +192,8 @@ int disk_part_read(int drv, int part, uint64_t off, uint64_t sz, uint8_t *buf) (void)drv; mock_last_read_part = part; + if (mock_fail_all_reads || ((mock_fail_header_part == part) && (off == 0))) + return -1; image = (part == BOOT_PART_B) ? part_b_image : part_a_image; if ((mock_fail_payload_part == part) && (off >= IMAGE_HEADER_SIZE)) return -1; @@ -241,8 +272,42 @@ int hal_flash_protect(haladdr_t address, int len) return 0; } +#ifdef WOLFBOOT_PERSIST_FAILURE_STATUS +/* Failure records as update_disk.c reported them, oldest first */ +#define MOCK_MAX_RECORDS 16 +static struct wolfBoot_failure_record mock_records[MOCK_MAX_RECORDS]; +static int mock_record_count; + +int wolfBoot_record_failure(uint8_t phase, uint8_t cause, uint8_t partition, + uint32_t fw_version) +{ + if (mock_record_count < MOCK_MAX_RECORDS) { + mock_records[mock_record_count].phase = phase; + mock_records[mock_record_count].cause = cause; + mock_records[mock_record_count].partition = partition; + mock_records[mock_record_count].fw_version = fw_version; + } + mock_record_count++; + return 0; +} + +int wolfBoot_get_failure(int index, struct wolfBoot_failure_record *out) +{ + (void)index; + (void)out; + return -1; +} + +static void reset_records(void) +{ + memset(mock_records, 0, sizeof(mock_records)); + mock_record_count = 0; +} +#endif + #include "update_disk.c" +#ifndef UNIT_DISK_PLAIN START_TEST(test_update_disk_zeroizes_key_material_on_panic) { size_t i; @@ -288,6 +353,7 @@ START_TEST(test_update_disk_zeroizes_key_material_before_boot) } } END_TEST +#endif START_TEST(test_update_disk_prefers_primary_partition_when_versions_equal) { @@ -357,6 +423,7 @@ START_TEST(test_update_disk_marks_staged_image_not_external) } END_TEST +#ifndef UNIT_DISK_PLAIN START_TEST(test_get_decrypted_blob_version_rejects_truncated_version_tlv) { uint8_t hdr[IMAGE_HEADER_SIZE + 2]; @@ -385,6 +452,7 @@ START_TEST(test_get_decrypted_blob_version_rejects_truncated_version_tlv) ck_assert_uint_eq(get_decrypted_blob_version(hdr), 0); } END_TEST +#endif START_TEST(test_update_disk_highbit_version_selects_higher_partition) { @@ -403,7 +471,9 @@ END_TEST START_TEST(test_update_disk_rejects_rollback_after_higher_image_failure) { +#ifndef UNIT_DISK_PLAIN size_t i; +#endif reset_mocks(); build_image(part_a_image, 7, 0xA1); @@ -414,12 +484,14 @@ START_TEST(test_update_disk_rejects_rollback_after_higher_image_failure) ck_assert_int_gt(wolfBoot_panicked, 0); ck_assert_int_eq(mock_do_boot_called, 0); +#ifndef UNIT_DISK_PLAIN for (i = 0; i < ENCRYPT_KEY_SIZE; i++) { ck_assert_uint_eq(disk_encrypt_key[i], 0); } for (i = 0; i < ENCRYPT_NONCE_SIZE; i++) { ck_assert_uint_eq(disk_encrypt_nonce[i], 0); } +#endif } END_TEST @@ -481,24 +553,245 @@ START_TEST(test_update_disk_rejects_partition_mismatch) } END_TEST +#ifdef WOLFBOOT_PERSIST_FAILURE_STATUS +START_TEST(test_update_disk_records_unreadable_headers) +{ + reset_mocks(); + reset_records(); + build_image(part_a_image, 7, 0xA1); + build_image(part_b_image, 7, 0xB2); + mock_fail_all_reads = 1; + + wolfBoot_start(); + + ck_assert_int_gt(wolfBoot_panicked, 0); + /* The mock panic returns, so the retry loop adds records after these */ + ck_assert_int_ge(mock_record_count, 3); + ck_assert_uint_eq(mock_records[0].cause, WOLFBOOT_FAILURE_CAUSE_READ); + ck_assert_uint_eq(mock_records[0].partition, 0); + ck_assert_uint_eq(mock_records[1].cause, WOLFBOOT_FAILURE_CAUSE_READ); + ck_assert_uint_eq(mock_records[1].partition, 1); + ck_assert_uint_eq(mock_records[2].phase, WOLFBOOT_FAILURE_PHASE_RECOVERY); + ck_assert_uint_eq(mock_records[2].cause, WOLFBOOT_FAILURE_CAUSE_READ); +} +END_TEST + +START_TEST(test_update_disk_records_blank_headers) +{ + reset_mocks(); + reset_records(); + memset(part_a_image, 0, sizeof(part_a_image)); + memset(part_b_image, 0, sizeof(part_b_image)); + + wolfBoot_start(); + + ck_assert_int_gt(wolfBoot_panicked, 0); + /* Empty slots are not failures; only the final record is written */ + ck_assert_int_ge(mock_record_count, 1); + ck_assert_uint_eq(mock_records[0].phase, WOLFBOOT_FAILURE_PHASE_RECOVERY); + ck_assert_uint_eq(mock_records[0].cause, WOLFBOOT_FAILURE_CAUSE_HEADER); +} +END_TEST + +START_TEST(test_update_disk_records_unreadable_slot_when_other_boots) +{ + reset_mocks(); + reset_records(); + build_image(part_a_image, 7, 0xA1); + build_image(part_b_image, 5, 0xB2); + mock_fail_header_part = BOOT_PART_A; + + wolfBoot_start(); + + ck_assert_int_eq(mock_do_boot_called, 1); + ck_assert_int_eq(mock_record_count, 1); + ck_assert_uint_eq(mock_records[0].phase, WOLFBOOT_FAILURE_PHASE_BOOT); + ck_assert_uint_eq(mock_records[0].cause, WOLFBOOT_FAILURE_CAUSE_READ); + ck_assert_uint_eq(mock_records[0].partition, 0); +} +END_TEST + +START_TEST(test_update_disk_records_corrupt_header_when_other_boots) +{ + reset_mocks(); + reset_records(); + memset(part_a_image, 0x5A, IMAGE_HEADER_SIZE); + build_image(part_b_image, 5, 0xB2); + + wolfBoot_start(); + + ck_assert_int_eq(mock_do_boot_called, 1); + ck_assert_int_eq(mock_record_count, 1); + ck_assert_uint_eq(mock_records[0].partition, 0); +#ifdef DISK_ENCRYPT + ck_assert_uint_eq(mock_records[0].cause, WOLFBOOT_FAILURE_CAUSE_DECRYPT); +#else + ck_assert_uint_eq(mock_records[0].cause, WOLFBOOT_FAILURE_CAUSE_HEADER); +#endif +} +END_TEST + +START_TEST(test_update_disk_records_blank_slot_nothing) +{ + reset_mocks(); + reset_records(); + memset(part_a_image, 0xFF, IMAGE_HEADER_SIZE); + build_image(part_b_image, 5, 0xB2); + + wolfBoot_start(); + + ck_assert_int_eq(mock_do_boot_called, 1); + ck_assert_int_eq(mock_record_count, 0); +} +END_TEST + +/* A slot already recorded by the first header read is not recorded again + * when the retry loop falls back to it */ +START_TEST(test_update_disk_records_probe_failure_once) +{ + int i, a_boot = 0; + + reset_mocks(); + reset_records(); + build_image(part_a_image, 7, 0xA1); + build_image(part_b_image, 5, 0xB2); + mock_fail_header_part = BOOT_PART_A; + mock_verify_authenticity_ret = -1; + + wolfBoot_start(); + + for (i = 0; (i < mock_record_count) && (i < MOCK_MAX_RECORDS); i++) { + if ((mock_records[i].phase == WOLFBOOT_FAILURE_PHASE_BOOT) && + (mock_records[i].partition == 0)) + a_boot++; + } + ck_assert_int_eq(a_boot, 1); +} +END_TEST + +START_TEST(test_update_disk_records_refused_slot) +{ + reset_mocks(); + reset_records(); + build_image(part_a_image, 7, 0xA1); + build_image(part_b_image, 7, 0xB2); + mock_part_mismatch_part = BOOT_PART_A; + + wolfBoot_start(); + + ck_assert_int_eq(mock_do_boot_called, 1); + ck_assert_int_eq(mock_record_count, 1); + ck_assert_uint_eq(mock_records[0].phase, WOLFBOOT_FAILURE_PHASE_BOOT); + ck_assert_uint_eq(mock_records[0].cause, WOLFBOOT_FAILURE_CAUSE_HEADER); + ck_assert_uint_eq(mock_records[0].partition, 0); + ck_assert_uint_eq(mock_records[0].fw_version, 7); +} +END_TEST + +START_TEST(test_update_disk_records_signature_and_recovery) +{ + int last; + + reset_mocks(); + reset_records(); + build_image(part_a_image, 7, 0xA1); + build_image(part_b_image, 7, 0xB2); + mock_verify_authenticity_ret = -1; + + wolfBoot_start(); + + ck_assert_int_gt(wolfBoot_panicked, 0); + ck_assert_int_ge(mock_record_count, 3); + ck_assert_int_le(mock_record_count, MOCK_MAX_RECORDS); + ck_assert_uint_eq(mock_records[0].cause, WOLFBOOT_FAILURE_CAUSE_SIGNATURE); + ck_assert_uint_eq(mock_records[0].partition, 0); + ck_assert_uint_eq(mock_records[1].cause, WOLFBOOT_FAILURE_CAUSE_SIGNATURE); + ck_assert_uint_eq(mock_records[1].partition, 1); + last = mock_record_count - 1; + ck_assert_uint_eq(mock_records[last].phase, + WOLFBOOT_FAILURE_PHASE_RECOVERY); + ck_assert_uint_eq(mock_records[last].cause, + WOLFBOOT_FAILURE_CAUSE_SIGNATURE); + /* The slot whose refusal is repeated, not the one tried next */ + ck_assert_uint_eq(mock_records[last].partition, + mock_records[last - 1].partition); +} +END_TEST + +START_TEST(test_update_disk_records_hash_failure) +{ + reset_mocks(); + reset_records(); + build_image(part_a_image, 7, 0xA1); + build_image(part_b_image, 7, 0xB2); + mock_verify_integrity_ret = -1; + + wolfBoot_start(); + + ck_assert_int_gt(wolfBoot_panicked, 0); + ck_assert_int_ge(mock_record_count, 1); + ck_assert_uint_eq(mock_records[0].cause, WOLFBOOT_FAILURE_CAUSE_HASH); +} +END_TEST + +START_TEST(test_update_disk_records_refused_rollback) +{ + reset_mocks(); + reset_records(); + build_image(part_a_image, 7, 0xA1); + build_image(part_b_image, 5, 0xB2); + mock_fail_payload_part = BOOT_PART_A; + + wolfBoot_start(); + + ck_assert_int_gt(wolfBoot_panicked, 0); + ck_assert_int_eq(mock_record_count, 2); + ck_assert_uint_eq(mock_records[0].cause, WOLFBOOT_FAILURE_CAUSE_READ); + ck_assert_uint_eq(mock_records[0].partition, 0); + ck_assert_uint_eq(mock_records[0].fw_version, 7); + ck_assert_uint_eq(mock_records[1].cause, WOLFBOOT_FAILURE_CAUSE_VERSION); + ck_assert_uint_eq(mock_records[1].partition, 1); + ck_assert_uint_eq(mock_records[1].fw_version, 5); +} +END_TEST +#endif + Suite *wolfboot_suite(void) { Suite *s = suite_create("wolfBoot"); TCase *tc = tcase_create("update-disk"); +#ifndef UNIT_DISK_PLAIN tcase_add_test(tc, test_update_disk_zeroizes_key_material_on_panic); +#endif +#ifndef UNIT_DISK_PLAIN tcase_add_test(tc, test_update_disk_zeroizes_key_material_before_boot); +#endif tcase_add_test(tc, test_update_disk_prefers_primary_partition_when_versions_equal); tcase_add_test(tc, test_update_disk_boots_from_A_when_B_is_blank); tcase_add_test(tc, test_update_disk_boots_from_B_when_A_is_blank); tcase_add_test(tc, test_update_disk_marks_staged_image_not_external); +#ifndef UNIT_DISK_PLAIN tcase_add_test(tc, test_get_decrypted_blob_version_rejects_truncated_version_tlv); +#endif tcase_add_test(tc, test_update_disk_highbit_version_selects_higher_partition); tcase_add_test(tc, test_update_disk_rejects_rollback_after_higher_image_failure); tcase_add_test(tc, test_update_disk_rejects_invalid_integrity); tcase_add_test(tc, test_update_disk_rejects_invalid_signature); tcase_add_test(tc, test_update_disk_skips_partition_mismatch); tcase_add_test(tc, test_update_disk_rejects_partition_mismatch); +#ifdef WOLFBOOT_PERSIST_FAILURE_STATUS + tcase_add_test(tc, test_update_disk_records_refused_slot); + tcase_add_test(tc, test_update_disk_records_signature_and_recovery); + tcase_add_test(tc, test_update_disk_records_hash_failure); + tcase_add_test(tc, test_update_disk_records_refused_rollback); + tcase_add_test(tc, test_update_disk_records_unreadable_headers); + tcase_add_test(tc, test_update_disk_records_blank_headers); + tcase_add_test(tc, test_update_disk_records_unreadable_slot_when_other_boots); + tcase_add_test(tc, test_update_disk_records_corrupt_header_when_other_boots); + tcase_add_test(tc, test_update_disk_records_blank_slot_nothing); + tcase_add_test(tc, test_update_disk_records_probe_failure_once); +#endif suite_add_tcase(s, tc); return s; diff --git a/tools/unit-tests/unit-update-ram.c b/tools/unit-tests/unit-update-ram.c index 55dfac96bc..e8cab9cd7c 100644 --- a/tools/unit-tests/unit-update-ram.c +++ b/tools/unit-tests/unit-update-ram.c @@ -78,6 +78,23 @@ void do_boot(const uint32_t *address) } +#ifdef WOLFBOOT_CONFIRMED_IMAGE_HOOKS +/* Order of confirmed-image policy calls made by wolfBoot_start() */ +#define MAX_POLICY_CALLS 4 +static int policy_calls = 0; +static uint32_t policy_version[MAX_POLICY_CALLS]; +static int policy_confirmed[MAX_POLICY_CALLS]; + +void wolfBoot_apply_confirmed_image(struct wolfBoot_image *img, int confirmed) +{ + if (policy_calls < MAX_POLICY_CALLS) { + policy_version[policy_calls] = wolfBoot_get_blob_version(img->hdr); + policy_confirmed[policy_calls] = confirmed; + } + policy_calls++; +} +#endif + static int mock_flash_protect_called = 0; static haladdr_t mock_flash_protect_addr = 0; static int mock_flash_protect_len = 0; @@ -671,6 +688,34 @@ END_TEST /* An application running from the update partition arms an image it wrote * to the boot partition. */ +#ifdef WOLFBOOT_CONFIRMED_IMAGE_HOOKS +START_TEST (test_confirmed_policy_before_trial) { + reset_mock_stats(); + policy_calls = 0; + prepare_flash(); + add_payload(PART_BOOT, 2, TEST_SIZE_SMALL); + wolfBoot_success_part(PART_BOOT); + add_payload(PART_UPDATE, 3, TEST_SIZE_SMALL); + wolfBoot_update_trigger_part(PART_UPDATE); + wolfBoot_start(); + ck_assert_uint_eq(get_version_ramloaded(), 3U); + /* The confirmed v2 policy is applied before v3 is verified */ + ck_assert_int_eq(policy_calls, 2); + ck_assert_uint_eq(policy_version[0], 2U); + ck_assert_int_eq(policy_confirmed[0], 1); + ck_assert_uint_eq(policy_version[1], 3U); + ck_assert_int_eq(policy_confirmed[1], 0); + + /* A later boot of the trial image does not repeat the commit pass */ + policy_calls = 0; + wolfBoot_start(); + ck_assert_uint_eq(get_version_ramloaded(), 3U); + ck_assert_int_eq(policy_calls, 1); + cleanup_flash(); +} +END_TEST +#endif + START_TEST (test_update_trigger_part_boot) { reset_mock_stats(); prepare_flash(); @@ -822,6 +867,9 @@ Suite *wolfboot_suite(void) #endif tcase_add_test(emergency_rollback, test_success_part_update); tcase_add_test(emergency_rollback, test_update_trigger_part_boot); +#ifdef WOLFBOOT_CONFIRMED_IMAGE_HOOKS + tcase_add_test(emergency_rollback, test_confirmed_policy_before_trial); +#endif tcase_add_test(empty_boot_partition_update, test_empty_boot_partition_update); tcase_add_test(empty_boot_but_update_sha_corrupted_denied, test_empty_boot_but_update_sha_corrupted_denied); tcase_add_test(both_images_corrupted, test_both_images_corrupted_panics); diff --git a/tools/unit-tests/unit-zynqmp-efuse-counter.c b/tools/unit-tests/unit-zynqmp-efuse-counter.c new file mode 100644 index 0000000000..5dea63b37a --- /dev/null +++ b/tools/unit-tests/unit-zynqmp-efuse-counter.c @@ -0,0 +1,137 @@ +/* unit-zynqmp-efuse-counter.c + * + * Coverage for the ZynqMP user-eFuse security version counter encoding: the + * value is the number of set bits across the counter rows, and raising it + * programs the lowest clear bits. The functions under test are extracted + * verbatim from hal/zynq.c by the Makefile. + * + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of wolfBoot. + * + * wolfBoot 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. + * + * wolfBoot 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 + */ + +#include +#include +#include + +#include "efuse_counter_extract.h" + +START_TEST(test_counter_value) +{ + uint32_t rows[3] = { 0, 0, 0 }; + + ck_assert_uint_eq(zynqmp_efuse_counter_value(rows, 3), 0); + rows[0] = 0x7; + ck_assert_uint_eq(zynqmp_efuse_counter_value(rows, 3), 3); + rows[0] = 0xFFFFFFFFU; + rows[1] = 0x1; + ck_assert_uint_eq(zynqmp_efuse_counter_value(rows, 3), 33); + /* A stray bit anywhere still counts: fuses only add, never subtract. */ + rows[2] = 0x80000000U; + ck_assert_uint_eq(zynqmp_efuse_counter_value(rows, 3), 34); +} +END_TEST + +START_TEST(test_counter_bits_from_zero) +{ + uint32_t rows[2] = { 0, 0 }; + uint32_t add[2]; + + ck_assert_int_eq(zynqmp_efuse_counter_bits(rows, add, 2, 3), 0); + ck_assert_uint_eq(add[0], 0x7); + ck_assert_uint_eq(add[1], 0); +} +END_TEST + +START_TEST(test_counter_bits_crosses_row) +{ + uint32_t rows[2] = { 0x3FFFFFFFU, 0 }; + uint32_t add[2]; + + ck_assert_int_eq(zynqmp_efuse_counter_bits(rows, add, 2, 33), 0); + ck_assert_uint_eq(add[0], 0xC0000000U); + ck_assert_uint_eq(add[1], 0x1); +} +END_TEST + +START_TEST(test_counter_bits_fills_gaps) +{ + /* A failed earlier program can leave a hole; the hole is filled first. */ + uint32_t rows[1] = { 0x5 }; + uint32_t add[1]; + + ck_assert_int_eq(zynqmp_efuse_counter_bits(rows, add, 1, 3), 0); + ck_assert_uint_eq(add[0], 0x2); + rows[0] |= add[0]; + ck_assert_uint_eq(zynqmp_efuse_counter_value(rows, 1), 3); +} +END_TEST + +START_TEST(test_counter_bits_never_lowers) +{ + uint32_t rows[1] = { 0xFF }; + uint32_t add[1]; + + ck_assert_int_eq(zynqmp_efuse_counter_bits(rows, add, 1, 2), 0); + ck_assert_uint_eq(add[0], 0); + ck_assert_int_eq(zynqmp_efuse_counter_bits(rows, add, 1, 8), 0); + ck_assert_uint_eq(add[0], 0); +} +END_TEST + +START_TEST(test_counter_bits_capacity) +{ + uint32_t rows[2] = { 0, 0 }; + uint32_t add[2]; + + ck_assert_int_eq(zynqmp_efuse_counter_bits(rows, add, 2, 64), 0); + ck_assert_uint_eq(add[0], 0xFFFFFFFFU); + ck_assert_uint_eq(add[1], 0xFFFFFFFFU); + ck_assert_int_eq(zynqmp_efuse_counter_bits(rows, add, 2, 65), -1); + ck_assert_uint_eq(add[0], 0); + ck_assert_uint_eq(add[1], 0); +} +END_TEST + +static Suite *wolfboot_suite(void) +{ + Suite *s = suite_create("wolfBoot"); + TCase *tc = tcase_create("zynqmp-efuse-counter"); + + tcase_add_test(tc, test_counter_value); + tcase_add_test(tc, test_counter_bits_from_zero); + tcase_add_test(tc, test_counter_bits_crosses_row); + tcase_add_test(tc, test_counter_bits_fills_gaps); + tcase_add_test(tc, test_counter_bits_never_lowers); + tcase_add_test(tc, test_counter_bits_capacity); + suite_add_tcase(s, tc); + return s; +} + +int main(void) +{ + int failed; + Suite *s = wolfboot_suite(); + SRunner *sr = srunner_create(s); + + srunner_run_all(sr, CK_NORMAL); + failed = srunner_ntests_failed(sr); + srunner_free(sr); + + return (failed == 0) ? 0 : 1; +} diff --git a/tools/unit-tests/unit-zynqmp-sec-bl33.c b/tools/unit-tests/unit-zynqmp-sec-bl33.c new file mode 100644 index 0000000000..6562b7f221 --- /dev/null +++ b/tools/unit-tests/unit-zynqmp-sec-bl33.c @@ -0,0 +1,204 @@ +/* unit-zynqmp-sec-bl33.c + * + * Coverage for the ZynqMP eFuse security state read as BL33, where the eFuse + * cache comes through the PMU firmware (PM_EFUSE_ACCESS). The firmware + * reports success for SEC_CTRL whether or not its build grants the field, + * writing the word only when it does, so an unwritten word must fail the + * read rather than pass as "no fuses set". The functions under test are + * extracted verbatim from hal/zynq.c by the Makefile. + * + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of wolfBoot. + * + * wolfBoot 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. + * + * wolfBoot 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 + */ + +#include +#include +#include +#include + +#define WOLFBOOT_ZYNQMP_SEC_STATE + +#include "hal/zynq.h" + +#define wolfBoot_printf(...) do {} while (0) + +#define PM_ARGS_CNT 8 +#define PM_EFUSE_ACCESS 0x35 +typedef struct pmu_efuse { + uint64_t src; + uint32_t size; + uint32_t offset; + uint32_t flag; + uint32_t pufUserFuse; +} pmu_efuse; + +static uint8_t efuseBuf[sizeof(pmu_efuse) + 48]; + +/* What the fake PMU firmware does for a SEC_CTRL read */ +enum { FW_FULL, FW_MASKED, FW_UNGRANTED, FW_DENIED }; +static int fw_mode; +static uint32_t fuse_sec_ctrl; +static int sec_ctrl_reads; + +static void flush_dcache_range(unsigned long start, unsigned long end) +{ + (void)start; + (void)end; +} + +static int pmu_request(uint32_t api_id, uint32_t arg0, uint32_t arg1, + uint32_t arg2, uint32_t arg3, uint32_t *ret_payload) +{ + pmu_efuse *cmd = (pmu_efuse *)(uintptr_t)(((uint64_t)arg0 << 32) | arg1); + uint32_t *data = (uint32_t *)(uintptr_t)cmd->src; + + (void)arg2; + (void)arg3; + ck_assert_uint_eq(api_id, PM_EFUSE_ACCESS); + ck_assert_uint_eq(cmd->flag, 0); + ret_payload[0] = 0; + ret_payload[1] = 0; + if (cmd->offset == ((ZYNQMP_EFUSE_SEC_CTRL - ZYNQMP_EFUSE_BASE) & 0xFF)) { + sec_ctrl_reads++; + ck_assert_uint_eq(cmd->size, 1); + if (fw_mode == FW_FULL) { + data[0] = fuse_sec_ctrl; + } + else if (fw_mode == FW_MASKED) { + /* XSK_ACCESS_SECURE_CRITICAL_EFUSE alone */ + data[0] = fuse_sec_ctrl & 0x5FFFFFFFU; + } + else if (fw_mode == FW_DENIED) { + ret_payload[0] = 30; + } + /* FW_UNGRANTED: success, word left as it was */ + return 0; + } + /* PUF and PPK0 fields are not granted by the fake firmware */ + ret_payload[0] = 30; + return 0; +} + +#include "sec_bl33_extract.h" + +static void fw_reset(int mode, uint32_t sec_ctrl) +{ + fw_mode = mode; + fuse_sec_ctrl = sec_ctrl; + sec_ctrl_reads = 0; +} + +START_TEST(test_full_read) +{ + zynqmp_sec_state state; + + fw_reset(FW_FULL, ZYNQMP_EFUSE_SEC_CTRL_JTAG_DIS); + ck_assert_int_eq(zynqmp_sec_state_get(&state), 0); + ck_assert_uint_eq(state.sec_ctrl, ZYNQMP_EFUSE_SEC_CTRL_JTAG_DIS); + ck_assert_uint_eq(state.puf_chash, 0); + ck_assert_uint_eq(state.puf_misc, 0); + ck_assert_int_eq(sec_ctrl_reads, 1); + ck_assert_int_eq(zynqmp_sec_policy_check(ZYNQMP_EFUSE_SEC_CTRL_JTAG_DIS), + 0); + ck_assert_int_eq(zynqmp_sec_policy_check(ZYNQMP_EFUSE_SEC_CTRL_JTAG_DIS | + ZYNQMP_EFUSE_SEC_CTRL_ENC_ONLY), -1); +} +END_TEST + +START_TEST(test_virgin_part) +{ + fw_reset(FW_FULL, 0); + ck_assert_int_eq(zynqmp_sec_policy_check(ZYNQMP_EFUSE_SEC_CTRL_RSA_EN), -1); +} +END_TEST + +START_TEST(test_ungranted_fails) +{ + zynqmp_sec_state state; + + /* The firmware says success but never wrote SEC_CTRL. */ + fw_reset(FW_UNGRANTED, ZYNQMP_EFUSE_SEC_CTRL_JTAG_DIS); + ck_assert_int_eq(zynqmp_sec_state_get(&state), -1); + ck_assert_uint_eq(state.sec_ctrl, 0); + ck_assert_int_eq(zynqmp_sec_policy_check(ZYNQMP_EFUSE_SEC_CTRL_JTAG_DIS), + -1); +} +END_TEST + +START_TEST(test_denied_fails) +{ + zynqmp_sec_state state; + + fw_reset(FW_DENIED, ZYNQMP_EFUSE_SEC_CTRL_JTAG_DIS); + ck_assert_int_eq(zynqmp_sec_state_get(&state), -1); + ck_assert_int_eq(zynqmp_sec_policy_check(ZYNQMP_EFUSE_SEC_CTRL_JTAG_DIS), + -1); +} +END_TEST + +START_TEST(test_masked_only_clears) +{ + /* A masked read hides PPK1_WRLK: the policy fails, it never passes a + * part that lacks a required bit. */ + fw_reset(FW_MASKED, ZYNQMP_EFUSE_SEC_CTRL_PPK1_WRLK | + ZYNQMP_EFUSE_SEC_CTRL_JTAG_DIS); + ck_assert_int_eq(zynqmp_sec_policy_check(ZYNQMP_EFUSE_SEC_CTRL_JTAG_DIS), + 0); + ck_assert_int_eq(zynqmp_sec_policy_check(ZYNQMP_EFUSE_SEC_CTRL_PPK1_WRLK), + -1); +} +END_TEST + +START_TEST(test_cache_read_bounds) +{ + uint32_t v[13]; + + fw_reset(FW_FULL, 0); + ck_assert_int_eq(zynqmp_efuse_cache_read(0x58, v, 0), -1); + ck_assert_int_eq(zynqmp_efuse_cache_read(0x58, v, 13), -1); + ck_assert_int_eq(sec_ctrl_reads, 0); +} +END_TEST + +static Suite *sec_bl33_suite(void) +{ + Suite *s = suite_create("zynqmp-sec-bl33"); + TCase *tc = tcase_create("sec_state"); + + tcase_add_test(tc, test_full_read); + tcase_add_test(tc, test_virgin_part); + tcase_add_test(tc, test_ungranted_fails); + tcase_add_test(tc, test_denied_fails); + tcase_add_test(tc, test_masked_only_clears); + tcase_add_test(tc, test_cache_read_bounds); + suite_add_tcase(s, tc); + return s; +} + +int main(void) +{ + int fails; + Suite *s = sec_bl33_suite(); + SRunner *sr = srunner_create(s); + + srunner_run_all(sr, CK_NORMAL); + fails = srunner_ntests_failed(sr); + srunner_free(sr); + return fails; +}