diff --git a/.github/workflows/test-configs.yml b/.github/workflows/test-configs.yml index fe28089fd5..20834005e8 100644 --- a/.github/workflows/test-configs.yml +++ b/.github/workflows/test-configs.yml @@ -1149,6 +1149,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 f1a7bb4295..a1ec33e0ca 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 @@ -649,6 +650,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 @@ -710,12 +712,17 @@ 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-policy +tools/unit-tests/unit-update-disk-confirm-policy 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/sec_bl33_extract.h +tools/unit-tests/sec_bl33_burn_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 f20e910bf3..d5c92c3b39 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..610c88e853 100644 --- a/docs/API.md +++ b/docs/API.md @@ -121,7 +121,8 @@ 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 ZynqMP `ZYNQMP_SEC_POLICY` check +uses `WOLFBOOT_FAILURE_CAUSE_POLICY`. The application can read the records, ordered newest-first, through this API: diff --git a/docs/FIPS.md b/docs/FIPS.md index 82768c601c..95f9910f86 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 module's ARMv8 assembly (`cpuid.o`, `port/arm/armv8-*-asm_c.o`, `sp_arm64.o`) is linked inside the boundary unless `NO_ARM_ASM=1`. Its SP ECC tables add about 570 KB, so the CM4 builds the portable-C module. 32-bit ARM always does. + +`ENCRYPT=1` works with `ENCRYPT_WITH_AES128` or `ENCRYPT_WITH_AES256`, using the module's AES. ChaCha20 and `ENCRYPT_PKCS11` are refused. + +FIPS builds keep P-256 compiled in for the module's ECDH self-test, whatever curve signs the images. + `-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 the module's CPU-jitter entropy source on ZynqMP, which has no TRNG (`hal/zynq.c`, `FIPS_ENTROPY_MEMUSE=1` by default for `TARGET=zynq`). A jitter seed takes a few hundred milliseconds on a Cortex-A53, paid in the first signature verification. 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,9 @@ 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 on cm4, cm5 and zynq via `FIPS_NOSYS_SPECS`) and give the module a bounded `_sbrk` so the heap cannot grow into the unverified image. wolfBoot provides one on cm4/cm5 (`hal/rpi_common.c`) and zynq (`hal/zynq.c`); a new bare-metal FIPS target needs its own. Use a bare-metal toolchain (`aarch64-none-elf-`); with a glibc cross compiler the module's `printf` does not link to anything at run time. + +`WOLFBOOT_SELF_HEADER=1` is not supported with `FIPS=1` on AArch64. 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/Signing.md b/docs/Signing.md index 2a86f9ddd2..171d8fe458 100644 --- a/docs/Signing.md +++ b/docs/Signing.md @@ -363,6 +363,16 @@ Provides a value to be set with a custom tag altered without breaking the image signature. Example: `--cmdline "root=/dev/mmcblk0p2 rw rootwait console=ttyTCU0,115200"`. + * `--security-version n`: Sets the image security version, the 4-byte signed TLV + `HDR_SECURITY_VERSION` (0x37) checked against the floor with `SECURITY_VERSION=1` + (see [firmware_update.md](firmware_update.md#security-version-floor)). + + * `--revoke-keys mask`: Sets the key revocation mask, the 4-byte signed TLV + `HDR_KEY_REVOKE` (0x36), one bit per keystore slot, applied with `KEY_REVOCATION=1` + (see [keystore.md](keystore.md#key-revocation)). + + Both take a decimal or `0x` hex value up to 32 bits and may each be given once per image. + * `--dts filename`: Binds a raw (non-FIT) device tree blob to the firmware image. The sign tool hashes exactly the first `totalsize` bytes of the `.dtb`, per that header field (validating the FDT magic and version the same way the bootloader does) with the image hash algorithm and stores the 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 761efa2b67..c56fb42210 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 wolfBoot reads the cache directly; as BL33 it asks the PMU firmware (`PM_EFUSE_ACCESS`, built with `ENABLE_EFUSE_ACCESS=1`). The firmware returns all of `SEC_CTRL` only when built with `XSK_ACCESS_SECURE_CRITICAL_EFUSE` and `XSK_ACCESS_KEY_MANAGE_EFUSE`; a bit it masks reads as not set, so a part can only look less locked than it is. + +`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 | + +wolfBoot adds `/chosen/wolfboot,sec-ctrl` (`SEC_CTRL`, 0 if unreadable) and, with a policy, `/chosen/wolfboot,sec-policy` (1 met, 0 not met) to the DTB it passes to Linux. eFuse *programming* is separate and off by default: @@ -3901,6 +3912,25 @@ 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 names the rows by `USER_n` index; there is no default: + +``` +DISK_BOOT_CONFIRM=1 # SD/eMMC boot: only a confirmed image commits +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 count of set bits across the counter rows; the revocation row holds the mask. An unreadable row rejects every image (security version) or revokes every key (revocation). + +As BL33 the rows go through the PMU firmware (`ENABLE_EFUSE_ACCESS`, `XSK_ACCESS_USER_EFUSE`). Linux can use the same interface, so it can raise the counter or revoke keys, but never undo either. As the FSBL, programming uses `zynqmp_efuse_write_bit()` with `ZYNQMP_EFUSE_WRITE=1`. + +Programming is report-only (`eFuse: would program ...`) unless `ZYNQMP_EFUSE_BURN=1`. Do not burn the row write-lock fuses (`MISC_USER_CTRL`, row 16) for these rows; that freezes 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..e8f0daa1d5 100644 --- a/docs/compile.md +++ b/docs/compile.md @@ -525,6 +525,21 @@ 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` makes the following options build errors, whether set as the make variable or passed as the `-D` define: + +| Make variable | Define | +|---|---| +| `SIGN=NONE` | `WOLFBOOT_NO_SIGN` | +| `WOLFBOOT_SKIP_BOOT_VERIFY=1` | `WOLFBOOT_SKIP_BOOT_VERIFY` | +| `ALLOW_DOWNGRADE=1` | `ALLOW_DOWNGRADE` | +| `DUALBOOT_ROLLBACK_UNCONFIRMED=1` | `WOLFBOOT_DUALBOOT_ROLLBACK_UNCONFIRMED` | +| `WOLFBOOT_UDS_UID_FALLBACK_FORTEST=1` | `WOLFBOOT_UDS_UID_FALLBACK_FORTEST` | +| - | `DEBUG_CSU` (JTAG on ZynqMP) | + +It also defines `WOLFBOOT_PRODUCTION`: the ZynqMP `ZYNQMP_SEC_POLICY` check then refuses to boot (see [Targets](Targets.md)), and with `KEY_REVOCATION=1` or `SECURITY_VERSION=1` wolfBoot halts when a confirmed image's revocation mask or security version cannot be stored. The ZynqMP report-only eFuse mode counts as stored. + ### 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..3580051c94 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 + +With `SECURITY_VERSION=1` every image is also checked against a security version floor the HAL keeps in storage that cannot be decremented (eFuse, OTP, TPM NV), which also stops an older image that arrives by reflash or failover: + +```c +int hal_get_security_version(uint32_t *svn); /* non-zero: unreadable, reject */ +int hal_raise_security_version(uint32_t svn); /* may only raise */ +``` + +The security version is separate from the firmware version and is carried in the signed `HDR_SECURITY_VERSION` (0x37) TLV: + +``` +./tools/keytools/sign --ecc384 --sha384 --security-version 3 image.bin key.der 12 +``` + +An image without the TLV has security version 0. On every boot path wolfBoot rejects an image below the floor or above `WOLFBOOT_SECURITY_VERSION_MAX` (64 with the TPM backend, 32 per eFuse row on ZynqMP). The floor is raised only by a confirmed application image (`HDR_IMG_TYPE_APP`); if a newer image is waiting, staged or not, the confirmed image raises it before the newer one is verified. On the RAM and disk boot paths a newer image written without staging stays unconfirmed, so every boot verifies both images until it is confirmed. A build in which no image can be confirmed is refused: disk boot needs `DISK_BOOT_CONFIRM=1`, RAM boot needs partition trailers and, with `DUALBOOT`, fixed partitions. With `STAGE1_AUTH=1` stage 1 checks only the signature of stage 2. The simulator keeps the floor in `sim_security_version.dd`; `WOLFBOOT_TPM_POLICY_NV=1` keeps it in a TPM NV bit-field index (default 0x01400402, see [keystore.md](keystore.md#key-revocation)). + ### 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..f1dd110416 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 an image signed by a key in a revoked keystore slot. The revoked slots are a 32-bit mask (bit n = slot n) the HAL keeps in storage that cannot be cleared: + +```c +uint32_t hal_get_revoked_keys(void); +int hal_revoke_keys(uint32_t revoked); /* may only add bits */ +``` + +An image signed by a valid key revokes others with the signed `HDR_KEY_REVOKE` (0x36) TLV: + +``` +./tools/keytools/sign --ecc384 --sha384 --revoke-keys 0x1 image.bin key1.der 2 +``` + +The mask is applied only from a confirmed application image (`HDR_IMG_TYPE_APP`); if a newer image is waiting, staged or not, the confirmed image applies it before the newer one is verified. As for the security version, disk boot needs `DISK_BOOT_CONFIRM=1` and RAM boot needs partition trailers and, with `DUALBOOT`, fixed partitions. A mask that revokes a key that signed its own image is refused, and the TLV outside the signed header makes the image invalid. To rotate keys, provision spare slots, sign the next release with a spare key and the mask for the old one, and confirm it. + +The simulator stores the mask in `sim_revoked_keys.dd`. + +`WOLFBOOT_TPM_POLICY_NV=1` keeps the mask in a TPM NV bit-field index (`TPM_NT_BITS`, default 0x01400401) that wolfBoot creates under the platform hierarchy on first use and writes only with `TPM2_NV_SetBits`. An index it did not create, or cannot read, revokes every key. wolfBoot disables the platform hierarchy before handoff, also in TrustZone builds that keep the TPM for secure services, so the OS cannot delete the index; a replaced TPM starts with nothing revoked. `tools/tpm/policy_nv` prints the stored values. + +`KEY_REVOCATION` and `SECURITY_VERSION` need the verifying key in a keystore slot, so the build refuses them with Renesas TSIP/RSIP, the wolfHSM client, wolfHSM server certificate chains and `DUALBANK_SWAP`. They are also refused with `SELF_UPDATE_MONOLITHIC`, which replaces the application without committing its policy first. + ## 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..1c7558b4fe 100644 --- a/hal/sim.c +++ b/hal/sim.c @@ -559,6 +559,81 @@ int hal_flash_erase(uintptr_t address, int len) return 0; } +#if (defined(WOLFBOOT_KEY_REVOCATION) || defined(WOLFBOOT_SECURITY_VERSION)) && \ + !defined(WOLFBOOT_TPM_POLICY_NV) +/* Policy state is kept in a file; only a missing file reads as 0 */ +static int sim_policy_read(const char *path, uint32_t *value) +{ + int ret = -1; + int fd = open(path, O_RDONLY); + + *value = 0; + if (fd == -1) + return (errno == ENOENT) ? 0 : -1; + if (pread(fd, value, sizeof(*value), 0) == (ssize_t)sizeof(*value)) + ret = 0; + close(fd); + return ret; +} + +static int sim_policy_write(const char *path, uint32_t value) +{ + int ret = -1; + int fd = open(path, O_RDWR | O_CREAT, 0644); + if (fd == -1) + return -1; + if (pwrite(fd, &value, sizeof(value), 0) == (ssize_t)sizeof(value)) + ret = 0; + close(fd); + return ret; +} +#endif + +#if defined(WOLFBOOT_KEY_REVOCATION) && !defined(WOLFBOOT_TPM_POLICY_NV) +#define SIM_REVOKED_KEYS_FILE "./sim_revoked_keys.dd" + +/* Write-once: bits can be set, never cleared */ +uint32_t hal_get_revoked_keys(void) +{ + uint32_t revoked; + + /* Unreadable store: treat every key as revoked */ + if (sim_policy_read(SIM_REVOKED_KEYS_FILE, &revoked) != 0) + return 0xFFFFFFFFU; + return revoked; +} + +int hal_revoke_keys(uint32_t revoked) +{ + uint32_t cur; + + if (sim_policy_read(SIM_REVOKED_KEYS_FILE, &cur) != 0) + return -1; + return sim_policy_write(SIM_REVOKED_KEYS_FILE, revoked | cur); +} +#endif + +#if defined(WOLFBOOT_SECURITY_VERSION) && !defined(WOLFBOOT_TPM_POLICY_NV) +#define SIM_SECURITY_VERSION_FILE "./sim_security_version.dd" + +/* Monotonic: the stored floor never decreases */ +int hal_get_security_version(uint32_t *svn) +{ + return sim_policy_read(SIM_SECURITY_VERSION_FILE, svn); +} + +int hal_raise_security_version(uint32_t svn) +{ + uint32_t cur; + + if (sim_policy_read(SIM_SECURITY_VERSION_FILE, &cur) != 0) + return -1; + if (svn <= cur) + return 0; + return sim_policy_write(SIM_SECURITY_VERSION_FILE, svn); +} +#endif + void hal_init(void) { int ret; diff --git a/hal/zynq.c b/hal/zynq.c index 600a5f6ce8..a5d6207878 100644 --- a/hal/zynq.c +++ b/hal/zynq.c @@ -35,7 +35,12 @@ #include #include "aarch64_arch.h" + +#if defined(WOLFBOOT_PRODUCTION) && defined(DEBUG_CSU) +#error "WOLFBOOT_PRODUCTION forbids DEBUG_CSU, which enables JTAG" +#endif #include "image.h" +#include "loader.h" #include "printf.h" #include "hal_fpga.h" @@ -395,6 +400,275 @@ 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 + +/* The PMU firmware reports success without writing fields its XSK_ACCESS_* + * build options exclude; this tells such a word apart from a zero read. */ +#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, where each word is + * pre-filled with 'fill'. */ +static int zynqmp_efuse_cache_read_fill(uint32_t offset, uint32_t *val, + uint32_t words, uint32_t fill) +{ + uint32_t i; +#if defined(WOLFBOOT_ZYNQMP_FSBL) + (void)fill; + 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] = fill; + } + 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 +} + +static int zynqmp_efuse_cache_read(uint32_t offset, uint32_t *val, + uint32_t words) +{ + return zynqmp_efuse_cache_read_fill(offset, val, words, + ZYNQMP_EFUSE_READ_UNSET); +} +#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) +{ + uint32_t zero_fill = 0; + + /* A word the PMU firmware did not write keeps its fill, so two reads + * with different fills only agree on a real value */ + if ((zynqmp_efuse_cache_read(ZYNQMP_EFUSE_USER_OFFSET(idx), val, 1) != 0) +#ifndef WOLFBOOT_ZYNQMP_FSBL + || (zynqmp_efuse_cache_read_fill(ZYNQMP_EFUSE_USER_OFFSET(idx), + &zero_fill, 1, 0) != 0) || (zero_fill != *val) +#endif + ) { + (void)zero_fill; + 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_raise_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_revoke_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 +714,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 +737,29 @@ static int zynqmp_sec_state_get(zynqmp_sec_state* state) } memset(state, 0, sizeof(*state)); +#ifndef WOLFBOOT_ZYNQMP_FSBL_SEC + /* STATUS is not reachable through the PMU firmware, and the policy needs + * only SEC_CTRL. Bits the firmware masks read as clear, 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 +778,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 +788,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 +860,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 +3119,41 @@ 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 seed from the module's CPU-jitter entropy source: the ZynqMP PS + * has no TRNG. */ +int wolfBoot_fips_seed(unsigned char* output, unsigned int sz) +{ + return (wc_Entropy_Get(MAX_ENTROPY_BITS, output, sz) == 0) ? 0 : -1; +} +#endif + +#if defined(HAVE_FIPS) && defined(__WOLFBOOT) +/* Keep the FIPS module's newlib malloc inside .heap (hal/zynq.ld) */ +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 +3234,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 +3616,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 +3648,25 @@ 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 + /* An unreadable state is published as 0, not left as the DTB had it */ + 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..ded226c9e4 100644 --- a/include/hal.h +++ b/include/hal.h @@ -142,6 +142,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_revoke_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_raise_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..68000d717b 100644 --- a/include/image.h +++ b/include/image.h @@ -1768,6 +1768,41 @@ 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_POLICY +#endif + +/* Same list as the options.mk production guard, for any -D spelling */ +#if defined(WOLFBOOT_PRODUCTION) && (defined(WOLFBOOT_NO_SIGN) || \ + defined(WOLFBOOT_SKIP_BOOT_VERIFY) || defined(ALLOW_DOWNGRADE) || \ + defined(WOLFBOOT_DUALBOOT_ROLLBACK_UNCONFIRMED) || \ + defined(WOLFBOOT_UDS_UID_FALLBACK_FORTEST)) +#error "WOLFBOOT_PRODUCTION forbids options that disable or weaken verification" +#endif + +#ifdef WOLFBOOT_CONFIRMED_IMAGE_POLICY +/* Apply the key revocation and security version of a verified image, only if + * it is confirmed. Non-zero means a production build failed to store the + * policy and the caller must halt. */ +int 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 797b7442c8..3ecc8060cf 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,12 +90,13 @@ #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 - * 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. */ + /* 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 + /* 64-bit SP digits: the word-size gate below keys off + * WOLFSSL_HAVE_SP_ECC/RSA, which the FIPS build does not set, so ECDSA + * verify would otherwise use 32-bit limbs. */ /* Key the 64-bit limb selection off the compiler macro __x86_64__ as well * as ARCH_x86_64: ARCH=sim emits only ARCH_SIM, so sim-fips on an x86_64 * host would otherwise fall back to 32-bit SP limbs. */ @@ -361,9 +366,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..cca033dd64 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,8 @@ 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_POLICY 7 /* device security state does + * not meet the build policy */ /* Persisted failure record. */ struct wolfBoot_failure_record { diff --git a/options.mk b/options.mk index 181492fb43..a00a84556d 100644 --- a/options.mk +++ b/options.mk @@ -603,6 +603,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 +1355,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" @@ -2724,28 +2750,24 @@ 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 + # The test-app links the module for WOLFBOOT_SELF_HEADER, but includes + # options.mk before arch.mk, which appends the ARMv8 asm again + ifeq ($(ARCH)$(WOLFBOOT_SELF_HEADER),AARCH641) + $(error FIPS=1 with WOLFBOOT_SELF_HEADER=1 is not supported on AArch64) + endif # Only the ECDSA object set is wired into the FIPS boundary below. RSA-PSS # would additionally need rsa.o inside the boundary and its own CI job. ifeq ($(filter $(SIGN),ECC256 ECC384 ECC521),) @@ -2761,8 +2783,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) @@ -2829,17 +2858,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 \ @@ -2847,6 +2899,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 \ @@ -2855,6 +2908,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 \ @@ -2867,3 +2921,29 @@ 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 + 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..821ba6202f 100644 --- a/src/image.c +++ b/src/image.c @@ -2011,11 +2011,12 @@ int wolfBoot_image_part_matches(struct wolfBoot_image *img) uint8_t *type_field = NULL; uint16_t image_type; - if (img == NULL || img->hdr == NULL) { + /* An external partition's header is a device offset, which may be 0 */ + if (img == NULL || (!(PART_IS_EXT(img)) && (img->hdr == NULL))) { return -1; } - if (wolfBoot_find_header(img->hdr + IMAGE_HEADER_OFFSET, HDR_IMG_TYPE, - &type_field) != WOLFBOOT_HDR_U16_SZ) { + if (wolfBoot_get_header(img, HDR_IMG_TYPE, &type_field) != + WOLFBOOT_HDR_U16_SZ) { return -1; } image_type = (uint16_t)(type_field[0] + (type_field[1] << 8)); @@ -2953,6 +2954,96 @@ int wolfBoot_verify_authenticity(struct wolfBoot_image *img) return 0; } #else +#ifdef WOLFBOOT_CONFIRMED_IMAGE_POLICY +/* 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 if empty or + * unsigned. */ +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 (*ptr == NULL) ? 0 : -1; + 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; +} + +/* The signed HDR_KEY_REVOKE mask, limited to keystore slots. Returns 0 with + * the mask (0 if absent), -1 if malformed or it names a signing key. */ +static int signed_revoke_mask(struct wolfBoot_image *img, uint32_t *mask) +{ + uint8_t *tlv = NULL; + uint8_t *hint = NULL; + uint32_t valid, own_mask; + int own, nkeys, len; + + *mask = 0; + 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 + valid = (nkeys >= 32) ? 0xFFFFFFFFU : ((1U << nkeys) - 1U); + *mask = ((uint32_t)tlv[0] | ((uint32_t)tlv[1] << 8) | + ((uint32_t)tlv[2] << 16) | ((uint32_t)tlv[3] << 24)) & valid; + if ((*mask & own_mask) != 0U) { + wolfBoot_printf("Key revocation refused: mask includes signing key\n"); + return -1; + } + return 0; +} +#endif + int wolfBoot_verify_authenticity(struct wolfBoot_image *img) { uint8_t *stored_signature; @@ -3009,6 +3100,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 +3130,25 @@ 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 + { + uint32_t revoke; + /* Refused here, not after the image is confirmed */ + if (signed_revoke_mask(img, &revoke) != 0) + return -1; + } +#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 +3295,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 +3427,87 @@ int keyslot_id_by_sha(const uint8_t *hint) } return match_id; } + +#ifdef WOLFBOOT_KEY_REVOCATION +/** + * @brief Apply the signed HDR_KEY_REVOKE mask of a confirmed image. The slot + * that signed the image is never revoked. + * + * @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) +{ + uint32_t mask, revoked; + + if (signed_revoke_mask(img, &mask) != 0) + return -1; + revoked = hal_get_revoked_keys(); + /* All ones is the backends' unreadable value: the verified image's own + * key would be revoked otherwise */ + if (revoked == 0xFFFFFFFFU) + return -1; + if ((mask & ~revoked) == 0U) + return 0; + wolfBoot_printf("Revoking key slots 0x%x\n", (unsigned)(mask & ~revoked)); + return hal_revoke_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_raise_security_version(svn); +} +#endif + +#ifdef WOLFBOOT_CONFIRMED_IMAGE_POLICY +int wolfBoot_apply_confirmed_image(struct wolfBoot_image *img, int confirmed) +{ + int failed = 0; + + /* Only the application image sets device policy */ + if (!confirmed || (wolfBoot_image_part_matches(img) != 0)) + return 0; +#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 + /* Booting on would let the next boot accept images it should refuse */ + return failed ? -1 : 0; +#else + (void)failed; + return 0; +#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; + } + if (wolfBoot_apply_confirmed_image(img, 1) != 0) + wolfBoot_panic(); + return 0; +} +#endif #endif /* !WOLFBOOT_NO_SIGN && !WOLFBOOT_RENESAS_SCEPROTECT */ 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..5aa93219f5 --- /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_revoke_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_raise_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..6577be55f3 100644 --- a/src/update_disk.c +++ b/src/update_disk.c @@ -51,6 +51,16 @@ #ifdef DISK_BOOT_CONFIRM #include "disk_trailer.h" #endif +#if defined(WOLFBOOT_CONFIRMED_IMAGE_POLICY) && \ + !defined(WOLFBOOT_SKIP_BOOT_VERIFY) && defined(DISK_BOOT_CONFIRM) + #define DISK_COMMIT_CONFIRMED +#endif +/* Without it no disk image is ever confirmed, so the floor and the mask + * would be checked but never written */ +#if defined(WOLFBOOT_CONFIRMED_IMAGE_POLICY) && \ + !defined(WOLFBOOT_SKIP_BOOT_VERIFY) && !defined(DISK_BOOT_CONFIRM) +#error "KEY_REVOCATION and SECURITY_VERSION on disk boot need DISK_BOOT_CONFIRM=1" +#endif #ifdef WOLFBOOT_DISK_FS #include "disk_fs.h" #endif @@ -895,6 +905,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 @@ -1109,9 +1124,26 @@ void RAMFUNCTION wolfBoot_start(void) /* Choose partition with higher version */ selected = (pB_ver_u > pA_ver_u) ? 1 : 0; +#ifdef DISK_COMMIT_CONFIRMED + /* Any candidate not yet booted, staged or not */ + if ((slot_state[selected] != DISK_STATE_SUCCESS) && + (slot_state[selected] != DISK_STATE_TESTING) && + (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; @@ -1163,7 +1195,11 @@ 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"); #ifdef DISK_GOLDEN_SLOT /* Nothing newer can boot: only the golden slot is left. */ @@ -1237,6 +1273,8 @@ void RAMFUNCTION wolfBoot_start(void) selected ^= 1; continue; } + /* The header was read from disk into RAM, not external flash */ + os_image.not_ext = 1; /* The image must target this core's partition: the key mask only * restricts which partition ids the signing key may claim, not @@ -1380,6 +1418,22 @@ void RAMFUNCTION wolfBoot_start(void) continue; } else { BENCHMARK_END("done"); +#ifdef DISK_COMMIT_CONFIRMED + if ((commit_slot >= 0) && (selected == commit_slot)) { + if (wolfBoot_apply_confirmed_image(&os_image, 1) != 0) { +#ifdef DISK_ENCRYPT + disk_decrypted_header_clear(dec_hdr); + disk_crypto_clear(); +#endif + wolfBoot_panic(); + return; + } + commit_slot = -1; + selected = trial_slot; + failures = 0; + continue; + } +#endif failures = 0; break; /* Success case */ } @@ -1414,6 +1468,26 @@ void RAMFUNCTION wolfBoot_start(void) } #endif +#if defined(WOLFBOOT_CONFIRMED_IMAGE_POLICY) && \ + !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 + if (wolfBoot_apply_confirmed_image(&os_image, confirmed) != 0) { +#ifdef DISK_ENCRYPT + disk_decrypted_header_clear(dec_hdr); + disk_crypto_clear(); +#endif + wolfBoot_panic(); + return; + } + } +#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 +1755,23 @@ 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 +#if defined(WOLFBOOT_TPM_POLICY_NV) && !defined(WOLFBOOT_FSP) +#ifdef DISK_ENCRYPT + /* Nothing after this needs the key; the boot hook still reads the header */ + disk_crypto_clear(); +#endif +#if !defined(WOLFBOOT_ANTI_ROLLBACK) && !defined(ARCH_SIM) + if (wolfBoot_tpm_policy_nv_lock() != 0) { + wolfBoot_printf("Error locking the TPM platform hierarchy\n"); +#ifdef DISK_ENCRYPT + disk_decrypted_header_clear(dec_hdr); +#endif + wolfBoot_panic(); + } +#endif + /* The x86 FSP do_boot() does this there */ + wolfBoot_tpm2_deinit(); #endif hal_prepare_boot(); diff --git a/src/update_flash.c b/src/update_flash.c index 1dcfcd60c2..a7b9f87047 100644 --- a/src/update_flash.c +++ b/src/update_flash.c @@ -40,6 +40,13 @@ #endif #include "printf.h" +/* A monolithic self-update replaces the application without committing its + * pending policy, and keeps BOOT's SUCCESS state for the new one */ +#if defined(WOLFBOOT_SELF_UPDATE_MONOLITHIC) && \ + defined(WOLFBOOT_CONFIRMED_IMAGE_POLICY) +#error "KEY_REVOCATION and SECURITY_VERSION are not supported with SELF_UPDATE_MONOLITHIC" +#endif + /* Bytes at the end of each partition that hold the trailer */ #define TRAILER_LEN (WOLFBOOT_TRAILER_SECTORS * WOLFBOOT_SECTOR_SIZE) @@ -126,6 +133,42 @@ int WP11_Library_Init(void); #pragma section FRAM #endif +#if defined(WOLFBOOT_CONFIRMED_IMAGE_POLICY) && \ + !defined(WOLFBOOT_SELF_UPDATE_MONOLITHIC) +/* Commit the policy of a confirmed boot image before a staged update, of the + * application or of wolfBoot itself, is verified against it */ +static void RAMFUNCTION wolfBoot_commit_pending_policy(void) +{ + struct wolfBoot_image boot; + uint8_t bootState = 0, updateState = 0; + int bootRet, updateRet; + +#ifdef NVM_FLASH_WRITEONCE + hal_flash_unlock(); +#ifdef EXT_FLASH + ext_flash_unlock(); +#endif +#endif + bootRet = wolfBoot_get_partition_state(PART_BOOT, &bootState); + updateRet = wolfBoot_get_partition_state(PART_UPDATE, &updateState); +#ifdef NVM_FLASH_WRITEONCE + hal_flash_lock(); +#ifdef EXT_FLASH + ext_flash_lock(); +#endif +#endif + 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 + #ifdef RAM_CODE #ifndef TARGET_rp2350 extern unsigned int _start_text; @@ -2271,6 +2314,10 @@ void RAMFUNCTION wolfBoot_start(void) #endif #ifdef RAM_CODE +#if defined(WOLFBOOT_CONFIRMED_IMAGE_POLICY) && \ + !defined(WOLFBOOT_SELF_UPDATE_MONOLITHIC) + wolfBoot_commit_pending_policy(); +#endif wolfBoot_check_self_update(); #endif @@ -2299,6 +2346,10 @@ void RAMFUNCTION wolfBoot_start(void) #endif #endif +#if defined(WOLFBOOT_CONFIRMED_IMAGE_POLICY) && !defined(RAM_CODE) + wolfBoot_commit_pending_policy(); +#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 +2468,16 @@ void RAMFUNCTION wolfBoot_start(void) wolfBoot_panic(); } PART_SANITY_CHECK(&boot); +#ifdef WOLFBOOT_CONFIRMED_IMAGE_POLICY + { + uint8_t rst = 0; + if (wolfBoot_apply_confirmed_image(&boot, + (wolfBoot_get_partition_state(PART_BOOT, &rst) == 0) && + (rst == IMG_STATE_SUCCESS)) != 0) { + wolfBoot_panic(); + } + } +#endif #else if (bootRet < 0) { wolfBoot_panic(); @@ -2453,6 +2514,14 @@ void RAMFUNCTION wolfBoot_start(void) #if defined(WOLFBOOT_TPM) && !defined(WOLFCRYPT_SECURE_MODE) /* leave TPM2 available to be called from non-secure callable */ wolfBoot_tpm2_deinit(); +#elif defined(WOLFBOOT_TPM_POLICY_NV) && !defined(WOLFBOOT_ANTI_ROLLBACK) && \ + !defined(ARCH_SIM) + /* The TPM stays up for the secure services, but the application must + * not be able to undefine the policy indices */ + if (wolfBoot_tpm_policy_nv_lock() != 0) { + wolfBoot_printf("Error locking the TPM platform hierarchy\n"); + wolfBoot_panic(); + } #endif #ifdef ENCRYPT_PKCS11 diff --git a/src/update_ram.c b/src/update_ram.c index 42fbc59be9..d628ff042a 100644 --- a/src/update_ram.c +++ b/src/update_ram.c @@ -64,6 +64,26 @@ extern uint8_t _end[]; /* linker symbol: end of wolfBoot BSS */ #define WOLFBOOT_USE_RAMBOOT #endif +#if defined(WOLFBOOT_CONFIRMED_IMAGE_POLICY) && \ + !defined(WOLFBOOT_SKIP_BOOT_VERIFY) && \ + defined(HAVE_PARTITION_TRAILERS) && defined(WOLFBOOT_DUALBOOT) && \ + defined(WOLFBOOT_FIXED_PARTITIONS) + #define RAM_COMMIT_CONFIRMED +#endif +/* Without a partition state no RAM-booted image is ever confirmed, so the + * floor and the mask would be checked but never written */ +#if defined(WOLFBOOT_CONFIRMED_IMAGE_POLICY) && \ + !defined(WOLFBOOT_SKIP_BOOT_VERIFY) && !defined(HAVE_PARTITION_TRAILERS) +#error "KEY_REVOCATION and SECURITY_VERSION on RAM boot need partition trailers (WOLFBOOT_FIXED_PARTITIONS or CUSTOM_PARTITION_TRAILER)" +#endif +/* The pass that commits the confirmed image's policy before a newer + * candidate is verified addresses fixed partitions */ +#if defined(WOLFBOOT_CONFIRMED_IMAGE_POLICY) && \ + !defined(WOLFBOOT_SKIP_BOOT_VERIFY) && defined(WOLFBOOT_DUALBOOT) && \ + !defined(WOLFBOOT_FIXED_PARTITIONS) +#error "KEY_REVOCATION and SECURITY_VERSION with RAM dual boot need WOLFBOOT_FIXED_PARTITIONS" +#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; @@ -287,6 +307,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 +358,21 @@ 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 +#ifdef RAM_COMMIT_CONFIRMED + trial_part = wolfBoot_dualboot_candidate(); + active = trial_part; + /* Any candidate not yet booted, staged or not: an unreadable trailer + * counts as such. A TESTING one had its commit pass when it was staged. */ + if ((trial_part >= 0) && + ((wolfBoot_get_partition_state(trial_part, &trial_state) != 0) || + ((trial_state != IMG_STATE_SUCCESS) && + (trial_state != IMG_STATE_TESTING))) && + (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() @@ -433,6 +474,17 @@ void RAMFUNCTION wolfBoot_start(void) #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) != 0)) { + wolfBoot_panic(); + } + 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 +501,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 +544,20 @@ void RAMFUNCTION wolfBoot_start(void) ramboot_part = active; #endif +#if defined(WOLFBOOT_CONFIRMED_IMAGE_POLICY) && \ + !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 + if (wolfBoot_apply_confirmed_image(&os_image, confirmed) != 0) + wolfBoot_panic(); + } +#endif + /* First time we boot this update, set to TESTING to await * confirmation from the system */ @@ -893,6 +966,9 @@ 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 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 c4ad451bc3..e55ddbdb88 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_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/keytools/sign.c b/tools/keytools/sign.c index d83a4eff89..94feb76dc0 100644 --- a/tools/keytools/sign.c +++ b/tools/keytools/sign.c @@ -1975,6 +1975,22 @@ static int make_header_ex(int is_diff, uint8_t *pubkey, uint32_t pubkey_sz, goto failure; } } + /* The loader reads the first of each; a second would only mislead */ + for (i = 0; i < CMD.custom_tlvs; i++) { + uint32_t j; + if ((CMD.custom_tlv[i].tag != HDR_SECURITY_VERSION) && + (CMD.custom_tlv[i].tag != HDR_KEY_REVOKE)) { + continue; + } + for (j = i + 1; j < CMD.custom_tlvs; j++) { + if (CMD.custom_tlv[j].tag == CMD.custom_tlv[i].tag) { + fprintf(stderr, + "Error: TLV tag 0x%04x given more than once\n", + (unsigned)CMD.custom_tlv[i].tag); + goto failure; + } + } + } for (i = 0; i < CMD.custom_tlvs; i++) { /* require 8-byte alignment */ /* The offset '4' takes into account 2B Tag + 2B Len, so that the @@ -4086,6 +4102,42 @@ int main(int argc, char** argv) CMD.custom_tlvs++; i += 2; } + else if ((strcmp(argv[i], "--security-version") == 0) || + (strcmp(argv[i], "--revoke-keys") == 0)) { + /* The 4-byte HDR_SECURITY_VERSION / HDR_KEY_REVOKE TLVs read + * by SECURITY_VERSION=1 and KEY_REVOCATION=1 */ + int p = CMD.custom_tlvs; + const char *s; + char *end = NULL; + unsigned long long v; + if (p >= MAX_CUSTOM_TLVS) { + fprintf(stderr, "Too many custom TLVs.\n"); + exit(16); + } + if (argc < (i + 2)) { + fprintf(stderr, "Missing %s argument.\n", argv[i]); + exit(16); + } + s = argv[i + 1]; + errno = 0; + if (strncmp(s, "0x", 2) == 0) + v = strtoull(s, &end, 16); + else + v = strtoull(s, &end, 10); + if ((errno != 0) || (s[0] == '-') || (end == s) || + (*end != '\0') || (v > 0xFFFFFFFFULL)) { + fprintf(stderr, "Invalid %s value: %s\n", argv[i], s); + exit(16); + } + CMD.custom_tlv[p].tag = + (strcmp(argv[i], "--security-version") == 0) ? + HDR_SECURITY_VERSION : HDR_KEY_REVOKE; + CMD.custom_tlv[p].len = 4; + CMD.custom_tlv[p].val = (uint64_t)v; + CMD.custom_tlv[p].buffer = NULL; + CMD.custom_tlvs++; + i += 1; + } else if (strcmp(argv[i], "--cmdline") == 0) { /* Shorthand for --custom-tlv-string HDR_CMDLINE "": stores the * OS command line as a signature-covered TLV in the manifest. */ diff --git a/tools/scripts/sim-common.sh b/tools/scripts/sim-common.sh new file mode 100755 index 0000000000..16cabc6cce --- /dev/null +++ b/tools/scripts/sim-common.sh @@ -0,0 +1,131 @@ +#!/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}" "${5:-4}" <<'PYEOF' || exit 1 +import struct, sys +src, dst = sys.argv[1], sys.argv[2] +typ, val, hdr, ln = (int(a, 0) for a in sys.argv[3:7]) +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") +tlv = 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..1085af5b73 --- /dev/null +++ b/tools/scripts/sim-key-revocation.sh @@ -0,0 +1,103 @@ +#!/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" --revoke-keys 0x1 +sim_sign "$W/key0.der" 3 "$W/k0v3.bin" +sim_sign "$W/key1.der" 2 "$W/k1v2self.bin" --revoke-keys 0x2 +sim_sign "$W/key1.der" 2 "$W/k1v2.bin" +sim_sign "$W/key1.der" 2 "$W/k1v2short.bin" --custom-tlv $HDR_KEY_REVOKE 2 0x1 +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_expect "update revoking its own signing key is refused" "BOOT v1" "$(sim_boot)" +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/k1v2short.bin" - +sim_expect "revocation mask that is not 4 bytes is refused" "PANIC" "$(sim_boot)" + +if [ "$SIM_TPM_POLICY" = 0 ]; then + sim_policy_reset + sim_assemble "$W/k0v1.bin" - + printf 'xx' > sim_revoked_keys.dd + sim_expect "unreadable revocation mask refuses every key" "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..42f12896cb --- /dev/null +++ b/tools/scripts/sim-security-version.sh @@ -0,0 +1,143 @@ +#!/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, only for a malformed TLV] + if [ -n "${4:-}" ]; then + sim_sign "$KEY" "$1" "$3" --custom-tlv $HDR_SECURITY_VERSION "$4" "$2" + else + sim_sign "$KEY" "$1" "$3" --security-version "$2" + fi +} + +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_append_tlv "$W/v4nosvn.bin" "$W/v4empty.bin" $HDR_SECURITY_VERSION 0 0 + +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 --security-version 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/v4empty.bin" - +sim_expect "empty SVN TLV is refused" "PANIC" "$(sim_boot)" + +if [ "$SIM_TPM_POLICY" = 0 ]; then + sim_policy_reset + sim_assemble "$W/v1s1.bin" - + sim_boot success >/dev/null + sim_boot >/dev/null + truncate -s 2 sim_security_version.dd + sim_expect "unreadable floor refuses every image" "PANIC" "$(sim_boot)" +fi + +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..d7c6d66d6d --- /dev/null +++ b/tools/tpm/policy_nv.c @@ -0,0 +1,175 @@ +/* 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: print the policy indices, delete them + * (-clear) or replace them with owner indices (-foreign). Needs platform auth, + * so only before wolfBoot locks the platform hierarchy. */ + +#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 > 0) && (rc & RC_FMT1) && + ((rc & RC_MAX_FMT1) == TPM_RC_HANDLE)) + return 0; + return (rc < 0) ? rc : -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 < 0) ? rc : -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 2b443e2754..dd97a1aa82 100644 --- a/tools/unit-tests/Makefile +++ b/tools/unit-tests/Makefile @@ -92,8 +92,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-policy unit-update-disk-confirm-policy 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-tpm-lock 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-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 \ @@ -105,6 +105,7 @@ TESTS:=unit-parser unit-parser-large-header unit-fdt unit-extflash unit-string \ unit-sign-header-failure \ unit-keygen-xmss-params TESTS+=unit-tpm-check-rot-auth +TESTS+=unit-tpm-policy-nv TESTS+=unit-tpm-api-names TESTS+=unit-tpm-nsc-cert TESTS+=unit-tpm-advio-zeroize @@ -171,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 unit-zynqmp-sec-bl33-burn TESTS+=unit-zynqmp-puf TESTS+=unit-zynqmp-puf-nofsbl TESTS+=unit-versal-qspi-dma @@ -385,6 +388,7 @@ run: $(TESTS) python3 unit-update-flash-diag-build.py || exit 1 python3 unit-x86-fsp-stage1auth-build.py || exit 1 python3 unit-sign-custom-tlv-le.py || exit 1 + python3 unit-sign-policy-tlv.py || exit 1 python3 unit-sign-custom-tlv-large.py || exit 1 python3 unit-sign-custom-tlv-pubkey-der.py || exit 1 python3 unit-sign-dts.py || exit 1 @@ -592,6 +596,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-policy: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_POLICY \ + -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 \ @@ -659,8 +669,15 @@ 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 +# The same with the TPM policy hierarchy lock before handoff and the boot hook +unit-update-disk-tpm-lock:CFLAGS+=-DMOCK_PARTITIONS -DPRINTF_ENABLED -DWOLFBOOT_RAMBOOT_MAX_SIZE=0x40 \ + -DWOLFBOOT_ORIGIN=MOCK_ADDRESS_BOOT -DBOOTLOADER_PARTITION_SIZE=WOLFBOOT_PARTITION_SIZE \ + -DWOLFBOOT_TPM_POLICY_NV -DWOLFBOOT_HOOK_BOOT -DWOLFBOOT_HOOK_PANIC 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-policy:CFLAGS+=-DMOCK_PARTITIONS -DPRINTF_ENABLED -DWOLFBOOT_RAMBOOT_MAX_SIZE=0x400 \ + -DWOLFBOOT_ORIGIN=MOCK_ADDRESS_BOOT -DBOOTLOADER_PARTITION_SIZE=WOLFBOOT_PARTITION_SIZE \ + -DWOLFBOOT_CONFIRMED_IMAGE_POLICY 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 \ @@ -764,6 +781,11 @@ unit-tpm-check-rot-auth: ../../include/target.h unit-tpm-check-rot-auth.c ../../ -DWOLFBOOT_HASH_SHA256 \ -ffunction-sections -fdata-sections $(LDFLAGS) -Wl,--gc-sections +unit-tpm-policy-nv: ../../include/target.h unit-tpm-policy-nv.c ../../src/tpm_policy_nv.c + gcc -o $@ unit-tpm-policy-nv.c $(CFLAGS) -I$(WOLFBOOT_LIB_WOLFTPM) -DWOLFBOOT_TPM \ + -DWOLFTPM_USER_SETTINGS -DWOLFBOOT_SIGN_ECC256 -DWOLFBOOT_HASH_SHA256 \ + -ffunction-sections -fdata-sections $(LDFLAGS) -Wl,--gc-sections + unit-tpm-api-names: ../../include/target.h unit-tpm-api-names.c ../../src/string.c gcc -o $@ $^ $(CFLAGS) -I$(WOLFBOOT_LIB_WOLFTPM) -DWOLFBOOT_TPM \ -DWOLFTPM_USER_SETTINGS -DWOLFBOOT_SIGN_RSA2048 \ @@ -1610,6 +1632,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-policy: ../../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) @@ -1625,9 +1650,15 @@ 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-tpm-lock: ../../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-policy: ../../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) @@ -1893,6 +1924,47 @@ 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_fill(/,/^}/p' $< >> $@ + sed -n '/^static int zynqmp_efuse_cache_read(/,/^}/p' $< >> $@ + sed -n '/^#define ZYNQMP_EFUSE_USER_OFFSET/p' $< >> $@ + sed -n '/^static int zynqmp_user_efuse_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) + +# The same, with the BL33 write path for the policy rows (ZYNQMP_EFUSE_BURN) +sec_bl33_burn_extract.h: ../../hal/zynq.c + sed -n '/^#define ZYNQMP_EFUSE_USER_ROW0 /p' $< > $@ + sed -n '/^uint32_t zynqmp_efuse_counter_value(/,/^}/p' $< >> $@ + sed -n '/^int zynqmp_efuse_counter_bits(/,/^}/p' $< >> $@ + sed -n '/^static int zynqmp_user_efuse_program(/,/^}/p' $< >> $@ + sed -n '/^int hal_get_security_version(/,/^}/p' $< >> $@ + sed -n '/^int hal_raise_security_version(/,/^}/p' $< >> $@ + sed -n '/^uint32_t hal_get_revoked_keys(/,/^}/p' $< >> $@ + sed -n '/^int hal_revoke_keys(/,/^}/p' $< >> $@ + +unit-zynqmp-sec-bl33-burn: unit-zynqmp-sec-bl33.c sec_bl33_extract.h sec_bl33_burn_extract.h ../../hal/zynq.h + gcc -o $@ unit-zynqmp-sec-bl33.c $(CFLAGS) -I../.. -DZYNQMP_EFUSE_BURN \ + -DZYNQMP_EFUSE_SVN_ROW=0 -DZYNQMP_EFUSE_SVN_NROWS=2 \ + -DZYNQMP_EFUSE_REVOKE_ROW=3 $(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. @@ -3057,6 +3129,7 @@ GENERATED_SRC:=aurix_erased_extract.h elf_store_extract.h \ nrf5340_protect_fn_extract.h \ keystore_api_extract.h keystore_emitted.c keystore_gen \ rp2350_flash_write_extract.h \ + sec_bl33_extract.h sec_bl33_burn_extract.h \ sdhci_host.c \ stm32c0_write_extract.h stm32g0_write_extract.h stm32g4_write_extract.h stm32l4_write_extract.h \ stm32h7s_write_extract.h stm32h7_trailer_extract.h \ @@ -3067,7 +3140,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-image.c b/tools/unit-tests/unit-image.c index da337203c3..e868f59a49 100644 --- a/tools/unit-tests/unit-image.c +++ b/tools/unit-tests/unit-image.c @@ -1080,6 +1080,44 @@ START_TEST(test_image_part_matches_rejects_wolfboot) } END_TEST +/* The header of a non-mapped external partition is a device offset */ +START_TEST(test_image_part_matches_ext) +{ + struct wolfBoot_image test_img; + uint8_t buf[sizeof(test_img_v200000000_signed_bin)]; + int ret; + + memcpy(buf, test_img_v200000000_signed_bin, sizeof(buf)); + find_header_mocked = 0; + hdr_cpy_done = 0; + ext_flash_erase(0, 2 * WOLFBOOT_SECTOR_SIZE); + ext_flash_write(0, buf, sizeof(buf)); + memset(&test_img, 0, sizeof(test_img)); + test_img.part = PART_UPDATE; + ret = wolfBoot_image_part_matches(&test_img); + ck_assert_int_eq(ret, 0); + + patch_image_type_part(buf, sizeof(buf), 2); + hdr_cpy_done = 0; + ext_flash_erase(0, 2 * WOLFBOOT_SECTOR_SIZE); + ext_flash_write(0, buf, sizeof(buf)); + ret = wolfBoot_image_part_matches(&test_img); + ck_assert_int_eq(ret, -1); + + /* A header already in RAM (disk loader) is read in place even though + * the partition is external: external flash is erased here */ + memcpy(buf, test_img_v200000000_signed_bin, sizeof(buf)); + hdr_cpy_done = 0; + ext_flash_erase(0, 2 * WOLFBOOT_SECTOR_SIZE); + memset(&test_img, 0, sizeof(test_img)); + test_img.part = PART_UPDATE; + test_img.not_ext = 1; + test_img.hdr = buf; + ret = wolfBoot_image_part_matches(&test_img); + ck_assert_int_eq(ret, 0); +} +END_TEST + START_TEST(test_image_part_matches_null) { struct wolfBoot_image test_img; @@ -1467,6 +1505,7 @@ Suite *wolfboot_suite(void) tcase_add_test(tcase_verify_authenticity, test_image_part_matches_rejects_wolfboot); tcase_add_test(tcase_verify_authenticity, test_image_part_matches_null); + tcase_add_test(tcase_verify_authenticity, test_image_part_matches_ext); #endif /* WOLFBOOT_HASH_SHA256 */ suite_add_tcase(s, tcase_verify_authenticity); #endif diff --git a/tools/unit-tests/unit-sign-policy-tlv.py b/tools/unit-tests/unit-sign-policy-tlv.py new file mode 100644 index 0000000000..2c07b63b2f --- /dev/null +++ b/tools/unit-tests/unit-sign-policy-tlv.py @@ -0,0 +1,163 @@ +#!/usr/bin/env python3 +# unit-sign-policy-tlv.py +# +# The sign tool's --security-version and --revoke-keys options write the +# 4-byte little-endian HDR_SECURITY_VERSION (0x37) and HDR_KEY_REVOKE (0x36) +# TLVs, refuse a value that does not fit 32 bits, and refuse a second TLV +# with either tag (the option twice, or alongside --custom-tlv). +# +# 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. + +import os +import subprocess +import sys +import tempfile + +HDR_PADDING = 0xFF +HDR_KEY_REVOKE = 0x36 +HDR_SECURITY_VERSION = 0x37 + +THIS_DIR = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.abspath(os.path.join(THIS_DIR, "..", "..")) +SIGN = os.path.join(ROOT, "tools", "keytools", "sign") +NAME = "unit-sign-policy-tlv" + + +def skip(msg): + print("SKIP %s: %s" % (NAME, msg)) + sys.exit(0) + +def find_tlv_bytes(data, want_type, scan_end): + """Return raw value bytes for a TLV entry (mirrors wolfBoot_find_header).""" + p = 8 # skip 4-byte magic + 4-byte image size + while p + 4 <= scan_end: + htype = data[p] | (data[p + 1] << 8) + if htype == 0: + break + if data[p] == HDR_PADDING or (p & 1) != 0: + p += 1 + continue + length = data[p + 2] | (data[p + 3] << 8) + if htype == want_type: + if p + 4 + length > scan_end: + return None + return bytes(data[p + 4:p + 4 + length]) + p += 4 + length + return None + + +def ensure_sign(): + if os.path.exists(SIGN): + return True + try: + subprocess.run(["make", "sign"], + cwd=os.path.join(ROOT, "tools", "keytools"), + check=True, capture_output=True, text=True) + except (subprocess.CalledProcessError, OSError): + return False + return os.path.exists(SIGN) + + +def make_ed25519_key(path): + """Write a 64-byte raw ed25519 key (seed + public) as expected by sign.""" + try: + from cryptography.hazmat.primitives.asymmetric.ed25519 import \ + Ed25519PrivateKey + from cryptography.hazmat.primitives import serialization + except Exception: + return False + seed = b"\x42" * 32 + sk = Ed25519PrivateKey.from_private_bytes(seed) + pub = sk.public_key().public_bytes(serialization.Encoding.Raw, + serialization.PublicFormat.Raw) + with open(path, "wb") as f: + f.write(seed + pub) + return True + + +def sign(work, image, key, opts): + signed = image.replace(".bin", "_v1_signed.bin") + if os.path.exists(signed): + os.remove(signed) + cmd = [SIGN, "--ed25519", "--sha256"] + opts + [image, key, "1"] + r = subprocess.run(cmd, cwd=work, capture_output=True, text=True) + if r.returncode != 0 or not os.path.exists(signed): + return None + with open(signed, "rb") as f: + return f.read(512) + + +def le32(v): + return bytes([v & 0xFF, (v >> 8) & 0xFF, (v >> 16) & 0xFF, + (v >> 24) & 0xFF]) + + +GOOD = [ + (["--security-version", "3"], {HDR_SECURITY_VERSION: le32(3)}), + (["--revoke-keys", "0x80000001"], {HDR_KEY_REVOKE: le32(0x80000001)}), + (["--security-version", "4294967295", "--revoke-keys", "0x6"], + {HDR_SECURITY_VERSION: le32(0xFFFFFFFF), HDR_KEY_REVOKE: le32(0x6)}), +] + +BAD = [ + ["--security-version", "0x100000000"], + ["--security-version", "0x"], + ["--revoke-keys", "0x"], + ["--security-version", "-1"], + ["--revoke-keys", "abc"], + ["--revoke-keys", "0x1z"], + ["--security-version", "1", "--security-version", "2"], + ["--revoke-keys", "0x1", "--custom-tlv", "0x36", "4", "0x2"], +] + + +def main(): + if not ensure_sign(): + skip("could not build tools/keytools/sign") + + failures = [] + with tempfile.TemporaryDirectory() as work: + key = os.path.join(work, "priv.der") + if not make_ed25519_key(key): + skip("python cryptography module not available") + image = os.path.join(work, "image.bin") + with open(image, "wb") as f: + f.write(bytes(range(256)) * 8) + + for opts, want in GOOD: + data = sign(work, image, key, opts) + if data is None: + failures.append("%s: sign failed" % " ".join(opts)) + continue + for tag, expected in want.items(): + got = find_tlv_bytes(data, tag, len(data)) + if got != expected: + failures.append("%s: tag 0x%02x got %s, want %s" % ( + " ".join(opts), tag, + None if got is None else got.hex(), expected.hex())) + for opts in BAD: + if sign(work, image, key, opts) is not None: + failures.append("%s: accepted" % " ".join(opts)) + + if failures: + for msg in failures: + print("FAIL %s: %s" % (NAME, msg)) + sys.exit(1) + print("%s: OK" % NAME) + sys.exit(0) + + +if __name__ == "__main__": + main() diff --git a/tools/unit-tests/unit-tpm-policy-nv.c b/tools/unit-tests/unit-tpm-policy-nv.c new file mode 100644 index 0000000000..a58c82cf9f --- /dev/null +++ b/tools/unit-tests/unit-tpm-policy-nv.c @@ -0,0 +1,186 @@ +/* unit-tpm-policy-nv.c + * + * Unit tests for the TPM policy NV platform hierarchy lock. + * + * 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_TPM_POLICY_NV +#define WOLFBOOT_KEY_REVOCATION + +#include "wolfboot/wolfboot.h" +#include "tpm.h" + +WOLFTPM2_DEV wolftpm_dev; + +static int hc_calls; +static TPM_RC hc_ret; +static HierarchyControl_In hc_last; +static int auth_set; + +TPM_RC TPM2_HierarchyControl(HierarchyControl_In* in) +{ + hc_calls++; + hc_last = *in; + /* The empty platform password must be in slot 0 for the call */ + ck_assert_int_eq(auth_set, 1); + return hc_ret; +} + +int wolfTPM2_SetAuthPassword(WOLFTPM2_DEV* dev, int index, + const TPM2B_AUTH* auth) +{ + (void)dev; + (void)auth; + if (index == 0) + auth_set = 1; + return 0; +} + +int wolfTPM2_UnsetAuth(WOLFTPM2_DEV* dev, int index) +{ + (void)dev; + if (index == 0) + auth_set = 0; + return 0; +} + +/* The NV value paths are covered by the TPM simulator job */ +int wolfTPM2_NVOpen(WOLFTPM2_DEV* dev, WOLFTPM2_NV* nv, word32 nvIndex, + const byte* auth, word32 authSz) +{ + (void)dev; (void)nv; (void)nvIndex; (void)auth; (void)authSz; + return TPM_RC_FAILURE; +} + +int wolfTPM2_SetAuthHandle(WOLFTPM2_DEV* dev, int index, + const WOLFTPM2_HANDLE* handle) +{ + (void)dev; (void)index; (void)handle; + return 0; +} + +int wolfTPM2_NVReadAuth(WOLFTPM2_DEV* dev, WOLFTPM2_NV* nv, word32 nvIndex, + byte* dataBuf, word32* pDataSz, word32 offset) +{ + (void)dev; (void)nv; (void)nvIndex; (void)dataBuf; (void)pDataSz; + (void)offset; + return TPM_RC_FAILURE; +} + +int wolfTPM2_GetNvAttributesTemplate(TPM_HANDLE auth, word32* nvAttributes) +{ + (void)auth; + *nvAttributes = 0; + return 0; +} + +int wolfTPM2_NVCreateAuth(WOLFTPM2_DEV* dev, WOLFTPM2_HANDLE* parent, + WOLFTPM2_NV* nv, word32 nvIndex, word32 nvAttributes, word32 maxSize, + const byte* auth, int authSz) +{ + (void)dev; (void)parent; (void)nv; (void)nvIndex; (void)nvAttributes; + (void)maxSize; (void)auth; (void)authSz; + return TPM_RC_FAILURE; +} + +TPM_RC TPM2_NV_SetBits(NV_SetBits_In* in) +{ + (void)in; + return TPM_RC_FAILURE; +} + +#include "../../src/tpm_policy_nv.c" + +/* Runs in a forked process per test, so the cached lock state starts clear */ +static void reset(void) +{ + hc_calls = 0; + hc_ret = TPM_RC_SUCCESS; + auth_set = 0; + memset(&hc_last, 0xA5, sizeof(hc_last)); +} + +START_TEST(test_lock_disables_platform_hierarchy) +{ + reset(); + ck_assert_int_eq(wolfBoot_tpm_policy_nv_lock(), 0); + ck_assert_int_eq(hc_calls, 1); + ck_assert_uint_eq(hc_last.authHandle, TPM_RH_PLATFORM); + ck_assert_uint_eq(hc_last.enable, TPM_RH_PLATFORM); + ck_assert_uint_eq(hc_last.state, 0); + ck_assert_int_eq(auth_set, 0); + + /* Platform auth is gone after the first call: no second request */ + ck_assert_int_eq(wolfBoot_tpm_policy_nv_lock(), 0); + ck_assert_int_eq(hc_calls, 1); +} +END_TEST + +START_TEST(test_lock_failure_is_not_cached) +{ + reset(); + hc_ret = TPM_RC_FAILURE; + ck_assert_int_eq(wolfBoot_tpm_policy_nv_lock(), -1); + ck_assert_int_eq(auth_set, 0); + ck_assert_int_eq(wolfBoot_tpm_policy_nv_lock(), -1); + ck_assert_int_eq(hc_calls, 2); + + hc_ret = TPM_RC_SUCCESS; + ck_assert_int_eq(wolfBoot_tpm_policy_nv_lock(), 0); + ck_assert_int_eq(hc_calls, 3); +} +END_TEST + +/* An unreadable revocation index revokes every key */ +START_TEST(test_unreadable_index_revokes_all) +{ + reset(); + ck_assert_uint_eq(hal_get_revoked_keys(), 0xFFFFFFFFU); +} +END_TEST + +static Suite *policy_nv_suite(void) +{ + Suite *s = suite_create("tpm-policy-nv"); + TCase *tc = tcase_create("lock"); + + tcase_add_test(tc, test_lock_disables_platform_hierarchy); + tcase_add_test(tc, test_lock_failure_is_not_cached); + tcase_add_test(tc, test_unreadable_index_revokes_all); + suite_add_tcase(s, tc); + return s; +} + +int main(void) +{ + int fails; + Suite *s = policy_nv_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..f50b44c7aa 100644 --- a/tools/unit-tests/unit-update-disk-confirm.c +++ b/tools/unit-tests/unit-update-disk-confirm.c @@ -288,6 +288,28 @@ int hal_flash_protect(haladdr_t address, int len) return 0; } +#ifdef WOLFBOOT_CONFIRMED_IMAGE_POLICY +/* 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]; + +int 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++; + return 0; +} +#endif + + #include "update_disk.c" @@ -592,6 +614,81 @@ START_TEST(test_failover_does_not_land_on_a_testing_slot) } END_TEST +#ifdef WOLFBOOT_CONFIRMED_IMAGE_POLICY +/* 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 newer slot written without staging (NEW trailer) gets the same pass */ +START_TEST(test_confirmed_policy_before_unstaged_slot) +{ + 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); + + 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 + + Suite *wolfboot_suite(void) { Suite *s = suite_create("wolfBoot"); @@ -608,6 +705,11 @@ 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_POLICY + tcase_add_test(tc, test_confirmed_policy_before_trial); + tcase_add_test(tc, test_confirmed_policy_before_unstaged_slot); + tcase_add_test(tc, test_unreadable_confirmed_slot_still_boots_trial); +#endif suite_add_tcase(s, tc); return s; diff --git a/tools/unit-tests/unit-update-disk.c b/tools/unit-tests/unit-update-disk.c index 8bc993cf33..3a742d2b21 100644 --- a/tools/unit-tests/unit-update-disk.c +++ b/tools/unit-tests/unit-update-disk.c @@ -39,6 +39,17 @@ static int mock_verify_integrity_ret; * EXT_FLASH build must not route these reads back through external flash. */ static int mock_integrity_saw_not_ext; static int mock_authenticity_saw_not_ext; +static int mock_part_matches_saw_not_ext; +#ifdef WOLFBOOT_TPM_POLICY_NV +/* The loader's image, so the panic hook can look at its header */ +static struct wolfBoot_image *mock_os_image; +static int mock_policy_lock_ret; +static int mock_policy_lock_called; +static int mock_tpm_deinit_called; +static uint32_t mock_hook_boot_magic; +static int mock_hook_boot_called; +static int mock_panic_hdr_wiped; +#endif static int mock_verify_authenticity_ret; static int mock_part_mismatch_part; static int mock_last_read_part; @@ -92,10 +103,20 @@ static void reset_mocks(void) mock_last_read_part = -1; mock_integrity_saw_not_ext = -1; mock_authenticity_saw_not_ext = -1; + mock_part_matches_saw_not_ext = -1; mock_flash_protect_called = 0; mock_flash_protect_addr = 0; mock_flash_protect_len = 0; wolfBoot_panicked = 0; +#ifdef WOLFBOOT_TPM_POLICY_NV + mock_os_image = NULL; + mock_policy_lock_ret = 0; + mock_policy_lock_called = 0; + mock_tpm_deinit_called = 0; + mock_hook_boot_magic = 0; + mock_hook_boot_called = 0; + mock_panic_hdr_wiped = -1; +#endif } int chacha_init(void) @@ -206,9 +227,50 @@ int wolfBoot_verify_authenticity(struct wolfBoot_image* img) return mock_verify_authenticity_ret; } +#ifdef WOLFBOOT_TPM_POLICY_NV +int wolfBoot_tpm_policy_nv_lock(void); +void wolfBoot_tpm2_deinit(void); + +int wolfBoot_tpm_policy_nv_lock(void) +{ + mock_policy_lock_called++; + return mock_policy_lock_ret; +} + +/* As the real one: locks the hierarchy and halts if that fails */ +void wolfBoot_tpm2_deinit(void) +{ + mock_tpm_deinit_called++; + if (wolfBoot_tpm_policy_nv_lock() != 0) + wolfBoot_panic(); +} + +void wolfBoot_hook_boot(struct wolfBoot_image *boot_img) +{ + mock_hook_boot_called++; + memcpy(&mock_hook_boot_magic, boot_img->hdr, sizeof(uint32_t)); +} + +void wolfBoot_hook_panic(void) +{ + int i; + + if (mock_os_image == NULL) + return; + mock_panic_hdr_wiped = 1; + for (i = 0; i < IMAGE_HEADER_SIZE; i++) { + if (mock_os_image->hdr[i] != 0) + mock_panic_hdr_wiped = 0; + } +} +#endif + int wolfBoot_image_part_matches(struct wolfBoot_image* img) { - (void)img; +#ifdef WOLFBOOT_TPM_POLICY_NV + mock_os_image = img; +#endif + mock_part_matches_saw_not_ext = img->not_ext; /* The header of the slot under test is the last one read. */ if ((mock_part_mismatch_part == -1) || (mock_last_read_part == mock_part_mismatch_part)) @@ -354,6 +416,8 @@ START_TEST(test_update_disk_marks_staged_image_not_external) * just staged, so a good image fails integrity. */ ck_assert_int_eq(mock_integrity_saw_not_ext, 1); ck_assert_int_eq(mock_authenticity_saw_not_ext, 1); + /* So must the partition check, which reads the header from disk in RAM */ + ck_assert_int_eq(mock_part_matches_saw_not_ext, 1); } END_TEST @@ -481,6 +545,38 @@ START_TEST(test_update_disk_rejects_partition_mismatch) } END_TEST +#ifdef WOLFBOOT_TPM_POLICY_NV +/* The hierarchy is locked before handoff, and the boot hook still gets the + * decrypted header */ +START_TEST(test_update_disk_policy_lock_keeps_header_for_hook) +{ + reset_mocks(); + + wolfBoot_start(); + + ck_assert_int_eq(wolfBoot_panicked, 0); + ck_assert_int_ge(mock_policy_lock_called, 1); + ck_assert_int_eq(mock_tpm_deinit_called, 1); + ck_assert_int_eq(mock_hook_boot_called, 1); + ck_assert_uint_eq(mock_hook_boot_magic, WOLFBOOT_MAGIC); + ck_assert_int_eq(mock_do_boot_called, 1); +} +END_TEST + +/* A failed lock halts with the decrypted header already wiped */ +START_TEST(test_update_disk_policy_lock_failure_halts) +{ + reset_mocks(); + mock_policy_lock_ret = -1; + + wolfBoot_start(); + + ck_assert_int_ge(wolfBoot_panicked, 1); + ck_assert_int_eq(mock_panic_hdr_wiped, 1); +} +END_TEST +#endif + Suite *wolfboot_suite(void) { Suite *s = suite_create("wolfBoot"); @@ -499,6 +595,10 @@ Suite *wolfboot_suite(void) 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_TPM_POLICY_NV + tcase_add_test(tc, test_update_disk_policy_lock_keeps_header_for_hook); + tcase_add_test(tc, test_update_disk_policy_lock_failure_halts); +#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..5c00fce8af 100644 --- a/tools/unit-tests/unit-update-ram.c +++ b/tools/unit-tests/unit-update-ram.c @@ -78,6 +78,24 @@ void do_boot(const uint32_t *address) } +#ifdef WOLFBOOT_CONFIRMED_IMAGE_POLICY +/* 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]; + +int 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++; + return 0; +} +#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 +689,55 @@ END_TEST /* An application running from the update partition arms an image it wrote * to the boot partition. */ +#ifdef WOLFBOOT_CONFIRMED_IMAGE_POLICY +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 + +#ifdef WOLFBOOT_CONFIRMED_IMAGE_POLICY +/* A newer image written without the update trigger gets the same pass */ +START_TEST (test_confirmed_policy_before_unstaged_image) { + 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_start(); + ck_assert_uint_eq(get_version_ramloaded(), 3U); + 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); + cleanup_flash(); +} +END_TEST +#endif + START_TEST (test_update_trigger_part_boot) { reset_mock_stats(); prepare_flash(); @@ -822,6 +889,10 @@ 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_POLICY + tcase_add_test(emergency_rollback, test_confirmed_policy_before_trial); + tcase_add_test(emergency_rollback, test_confirmed_policy_before_unstaged_image); +#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..77ea494120 --- /dev/null +++ b/tools/unit-tests/unit-zynqmp-sec-bl33.c @@ -0,0 +1,334 @@ +/* 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, FW_WRITE_STATUS }; +static int fw_mode; +static uint32_t fuse_sec_ctrl; +static int sec_ctrl_reads; +/* USER_0..USER_7 as the fake firmware returns them, in the same modes; a + * write ORs bits in, as programming a fuse does */ +static uint32_t fuse_user[8]; +static int user_writes; +static int last_write_row; +static uint32_t last_write_bits; + +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); +#ifdef ZYNQMP_EFUSE_BURN + ck_assert_uint_le(cmd->flag, 1); +#else + ck_assert_uint_eq(cmd->flag, 0); +#endif + 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; + } + if ((cmd->offset >= 0x20U) && (cmd->offset < 0x40U)) { + int row = (int)(cmd->offset - 0x20U) / 4; + ck_assert_uint_eq(cmd->size, 1); + if (fw_mode == FW_DENIED) { + ret_payload[0] = 30; + } + else if (cmd->flag == 1U) { + user_writes++; + last_write_row = row; + last_write_bits = data[0]; + if (fw_mode == FW_WRITE_STATUS) + ret_payload[1] = 5; + else + fuse_user[row] |= data[0]; + } + else if ((fw_mode == FW_FULL) || (fw_mode == FW_WRITE_STATUS)) { + data[0] = fuse_user[row]; + } + return 0; + } + /* PUF and PPK0 fields are not granted by the fake firmware */ + ret_payload[0] = 30; + return 0; +} + +#include "sec_bl33_extract.h" +#ifdef ZYNQMP_EFUSE_BURN +#include "sec_bl33_burn_extract.h" +#endif + +static void fw_reset(int mode, uint32_t sec_ctrl) +{ + fw_mode = mode; + fuse_sec_ctrl = sec_ctrl; + sec_ctrl_reads = 0; + memset(fuse_user, 0, sizeof(fuse_user)); + user_writes = 0; + last_write_row = -1; + last_write_bits = 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_user_row_read) +{ + uint32_t v = 0; + + /* A fully programmed row is a real value, not an unwritten one */ + fw_reset(FW_FULL, 0); + fuse_user[0] = 0xFFFFFFFFU; + ck_assert_int_eq(zynqmp_user_efuse_read(0, &v), 0); + ck_assert_uint_eq(v, 0xFFFFFFFFU); + fuse_user[0] = 0x00000005U; + ck_assert_int_eq(zynqmp_user_efuse_read(0, &v), 0); + ck_assert_uint_eq(v, 0x00000005U); + + /* Success without a write must not read as a fully set row */ + fw_reset(FW_UNGRANTED, 0); + ck_assert_int_eq(zynqmp_user_efuse_read(0, &v), -1); + fw_reset(FW_DENIED, 0); + ck_assert_int_eq(zynqmp_user_efuse_read(0, &v), -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 + +#ifdef ZYNQMP_EFUSE_BURN +/* Only the bits not yet set go to the PMU, and only to the policy row */ +START_TEST(test_burn_revocation_row) +{ + fw_reset(FW_FULL, 0); + fuse_user[ZYNQMP_EFUSE_REVOKE_ROW] = 0x1U; + ck_assert_int_eq(hal_revoke_keys(0x5U), 0); + ck_assert_int_eq(user_writes, 1); + ck_assert_int_eq(last_write_row, ZYNQMP_EFUSE_REVOKE_ROW); + ck_assert_uint_eq(last_write_bits, 0x4U); + ck_assert_uint_eq(hal_get_revoked_keys(), 0x5U); + + /* Nothing new: no PMU write at all */ + ck_assert_int_eq(hal_revoke_keys(0x5U), 0); + ck_assert_int_eq(user_writes, 1); +} +END_TEST + +START_TEST(test_burn_security_version_rows) +{ + uint32_t svn = 0; + + fw_reset(FW_FULL, 0); + ck_assert_int_eq(hal_raise_security_version(3), 0); + ck_assert_int_eq(user_writes, 1); + ck_assert_int_eq(last_write_row, ZYNQMP_EFUSE_SVN_ROW); + ck_assert_uint_eq(last_write_bits, 0x7U); + ck_assert_int_eq(hal_get_security_version(&svn), 0); + ck_assert_uint_eq(svn, 3U); + + /* Crossing into the second counter row writes only that row's bits */ + user_writes = 0; + ck_assert_int_eq(hal_raise_security_version(34), 0); + ck_assert_int_eq(user_writes, 2); + ck_assert_int_eq(last_write_row, ZYNQMP_EFUSE_SVN_ROW + 1); + ck_assert_uint_eq(last_write_bits, 0x3U); + ck_assert_int_eq(hal_get_security_version(&svn), 0); + ck_assert_uint_eq(svn, 34U); + + /* A floor the rows cannot hold is refused without a write */ + user_writes = 0; + ck_assert_int_eq( + hal_raise_security_version(ZYNQMP_EFUSE_SVN_NROWS * 32 + 1), -1); + ck_assert_int_eq(user_writes, 0); +} +END_TEST + +/* Either PMU status word failing the write fails the setter */ +START_TEST(test_burn_pmu_errors) +{ + fw_reset(FW_WRITE_STATUS, 0); + ck_assert_int_eq(hal_revoke_keys(0x2U), -1); + ck_assert_int_eq(hal_raise_security_version(1), -1); + ck_assert_int_eq(user_writes, 2); + + fw_reset(FW_DENIED, 0); + ck_assert_int_eq(hal_revoke_keys(0x2U), -1); + ck_assert_int_eq(user_writes, 0); + ck_assert_int_eq(zynqmp_user_efuse_program(ZYNQMP_EFUSE_REVOKE_ROW, 0x2U), + -1); + ck_assert_int_eq(zynqmp_user_efuse_program(ZYNQMP_EFUSE_REVOKE_ROW, 0U), + 0); +} +END_TEST +#endif + +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); + tcase_add_test(tc, test_user_row_read); +#ifdef ZYNQMP_EFUSE_BURN + tcase_add_test(tc, test_burn_revocation_row); + tcase_add_test(tc, test_burn_security_version_rows); + tcase_add_test(tc, test_burn_pmu_errors); +#endif + 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; +}