From 0fd0df64a301f3b20c55fbc12d265c29ba7fe81b Mon Sep 17 00:00:00 2001 From: David Garske Date: Mon, 16 Nov 2026 13:20:47 -0800 Subject: [PATCH] Add ML-DSA signed, AES-256 encrypted image boot from QSPI and SD for Versal VMK180 --- .github/workflows/test-configs.yml | 15 + .gitignore | 3 + docs/API.md | 10 + docs/Targets.md | 25 ++ docs/compile.md | 6 + hal/versal.c | 40 +- hal/versal.ld | 2 +- include/fdt.h | 3 + include/image.h | 11 +- include/wolfboot/wolfboot.h | 8 +- options.mk | 9 +- src/boot_aarch64.c | 5 + src/libwolfboot.c | 172 ++++++-- src/update_flash_hwswap.c | 4 + src/update_ram.c | 22 + tools/config.mk | 2 +- tools/unit-tests/Makefile | 42 +- tools/unit-tests/unit-update-flash.c | 6 + tools/unit-tests/unit-update-ram-enc-start.c | 397 +++++++++++++++++++ tools/unit-tests/unit-update-ram-enc.c | 130 ++++++ tools/unit-tests/unit-update-ram.c | 122 ++++++ tools/unit-tests/unit-versal-qspi-dma.c | 73 ++++ 22 files changed, 1077 insertions(+), 30 deletions(-) create mode 100644 tools/unit-tests/unit-update-ram-enc-start.c diff --git a/.github/workflows/test-configs.yml b/.github/workflows/test-configs.yml index ae8d2395e8..5bc9f30fff 100644 --- a/.github/workflows/test-configs.yml +++ b/.github/workflows/test-configs.yml @@ -1667,6 +1667,21 @@ jobs: arch: aarch64 config-file: ./config/examples/versal_vmk180_sdcard.config + # ML-DSA-87 signed, AES-256 encrypted images in two fixed QSPI slots. + versal_vmk180_pq_enc_test: + uses: ./.github/workflows/test-build-aarch64.yml + with: + arch: aarch64 + config-file: ./config/examples/versal_vmk180.config + make-args: SIGN=ML_DSA ML_DSA_LEVEL=5 IMAGE_SIGNATURE_SIZE=4627 IMAGE_HEADER_SIZE=12288 ENCRYPT=1 ENCRYPT_WITH_AES256=1 CUSTOM_ENCRYPT_KEY=1 ENCRYPT_CACHE=0x08200000 DUALBOOT_ROLLBACK_UNCONFIRMED=1 WOLFBOOT_PARTITION_SIZE=0x400000 WOLFBOOT_PARTITION_UPDATE_ADDRESS=0xC00000 WOLFBOOT_PARTITION_SWAP_ADDRESS=0x1000000 + + versal_vmk180_sdcard_pq_enc_test: + uses: ./.github/workflows/test-build-aarch64.yml + with: + arch: aarch64 + config-file: ./config/examples/versal_vmk180_sdcard.config + make-args: SIGN=ML_DSA ML_DSA_LEVEL=5 IMAGE_SIGNATURE_SIZE=4627 IMAGE_HEADER_SIZE=12288 ENCRYPT=1 ENCRYPT_WITH_AES256=1 CUSTOM_ENCRYPT_KEY=1 DISK_BOOT_CONFIRM=1 WOLFBOOT_SECTOR_SIZE=0x4000 + # FIT read from a filesystem with no kernel load/entry and no fdt # sub-image, so the staging addresses come from the build. versal_vmk180_sdcard_fit_file_test: diff --git a/.gitignore b/.gitignore index d8ce12d80e..716e334b4e 100644 --- a/.gitignore +++ b/.gitignore @@ -183,6 +183,7 @@ tools/unit-tests/unit-spi-flash tools/unit-tests/unit-string tools/unit-tests/unit-update-flash tools/unit-tests/unit-update-flash-enc +tools/unit-tests/unit-update-flash-enc-cache tools/unit-tests/unit-update-flash-db tools/unit-tests/unit-update-flash-flagshome tools/unit-tests/unit-update-flash-invert @@ -276,6 +277,7 @@ tools/unit-tests/unit-imx-rt-cache-align tools/unit-tests/unit-update-disk-fit tools/unit-tests/unit-update-disk-oob tools/unit-tests/unit-update-ram-enc +tools/unit-tests/unit-update-ram-enc-start tools/unit-tests/unit-update-ram-enc-nopart tools/unit-tests/unit-va416x0-fram tools/unit-tests/unit-wolfhsm_flash_hal @@ -682,6 +684,7 @@ tools/unit-tests/unit-t10xx-flash-status 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-nofixed-noramboot tools/unit-tests/unit-update-trigger-scrub tools/unit-tests/unit-x86-uart diff --git a/docs/API.md b/docs/API.md index 1776f1c64c..cc863f8282 100644 --- a/docs/API.md +++ b/docs/API.md @@ -25,14 +25,20 @@ Basic interaction from the application is provided via the following high-level `void wolfBoot_update_trigger(void)` +`void wolfBoot_update_trigger_part(uint8_t part)` + `void wolfBoot_success(void)` +`void wolfBoot_success_part(uint8_t part)` + ### Firmware version Current (boot) firmware and update firmware versions can be retrieved from the application using: `uint32_t wolfBoot_get_image_version(uint8_t part)` +On an MMU target that keeps its images encrypted in flash (`EXT_ENCRYPTED` with `MMU`), only the bootloader holds the key, so this call returns 0 from the application for an encrypted partition. + Or via the shortcut macros: `wolfBoot_current_firmware_version()` @@ -51,8 +57,12 @@ to `STATE_UPDATING`, instructing the bootloader to perform the update upon the n wolfBoot update process swaps the contents of the UPDATE and the BOOT partitions, using a temporary single-block SWAP space. + - `wolfBoot_update_trigger_part(part)` does the same for the given partition. `PART_UPDATE` is identical to `wolfBoot_update_trigger()`. A fixed-slot dual-boot application running from the update partition, which stored the new image in the BOOT partition, passes `PART_BOOT`. `PART_BOOT` is ignored with `NVM_FLASH_WRITEONCE`, `NVM_FLASH_JOURNAL`, `FLAGS_HOME`, or an encryption key kept in flash; any other value is ignored. + ### Confirm current image +- `wolfBoot_success_part(part)` marks `PART_BOOT` or `PART_UPDATE` as successful and ignores any other value. A fixed-slot dual-boot application that may run from either partition passes the one it was booted from, which the bootloader reports to it (on Versal, the `/chosen/wolfboot,boot-part` device tree property). `wolfBoot_success()` is the same call for `PART_BOOT`. + - `wolfBoot_success()` indicates a successful boot of a new firmware. This can be called by the application at any time, but it will only be effective to mark the current firmware (in the BOOT partition) with the state `STATE_SUCCESS`, indicating that no roll-back is required. An application should typically call `wolfBoot_success()` diff --git a/docs/Targets.md b/docs/Targets.md index e21b0a6741..ee7adebfb8 100644 --- a/docs/Targets.md +++ b/docs/Targets.md @@ -4949,6 +4949,31 @@ Typical boot timing with ECC384/SHA384 signing: --- +### Post-quantum signed and encrypted images + +The Versal configurations also build with ML-DSA-87 signatures and AES-256 encrypted images by adding make arguments: + +```sh +# QSPI, two fixed slots at 0x800000 and 0xC00000 +cp config/examples/versal_vmk180.config .config +make SIGN=ML_DSA ML_DSA_LEVEL=5 IMAGE_SIGNATURE_SIZE=4627 IMAGE_HEADER_SIZE=12288 \ + ENCRYPT=1 ENCRYPT_WITH_AES256=1 CUSTOM_ENCRYPT_KEY=1 ENCRYPT_CACHE=0x08200000 \ + DUALBOOT_ROLLBACK_UNCONFIRMED=1 WOLFBOOT_PARTITION_SIZE=0x400000 \ + WOLFBOOT_PARTITION_UPDATE_ADDRESS=0xC00000 WOLFBOOT_PARTITION_SWAP_ADDRESS=0x1000000 + +# SD card A/B slots +cp config/examples/versal_vmk180_sdcard.config .config +make SIGN=ML_DSA ML_DSA_LEVEL=5 IMAGE_SIGNATURE_SIZE=4627 IMAGE_HEADER_SIZE=12288 \ + ENCRYPT=1 ENCRYPT_WITH_AES256=1 CUSTOM_ENCRYPT_KEY=1 DISK_BOOT_CONFIRM=1 \ + WOLFBOOT_SECTOR_SIZE=0x4000 +``` + +The QSPI flash is not memory mapped, so wolfBoot reads the ciphertext of the selected slot into DDR at `WOLFBOOT_LOAD_ADDRESS`, decrypts it in place and verifies it there. + +The platform supplies the image key through the `CUSTOM_ENCRYPT_KEY` hooks. `hal/versal.c` has weak defaults that fail, so an encrypted image does not boot until `wolfBoot_get_encrypt_key()` is provided, for example from eFuse, BBRAM or a PUF-wrapped store; link it with `OBJS_EXTRA=.o`. + +With `DUALBOOT_ROLLBACK_UNCONFIRMED=1` (see [compile.md](compile.md#roll-back-an-unconfirmed-image-in-dual-boot-mode)) wolfBoot reports the slot it booted to the application in the device tree as `/chosen/wolfboot,boot-part` (0 = boot slot, 1 = update slot), so a bare-metal application can confirm its own slot with `wolfBoot_success_part()`, write an update to the other one and arm it with `wolfBoot_update_trigger_part()`. ML-DSA-87 verification needs a deep stack; the EL2 stack in `hal/versal.ld` is sized for it. + ### SD Card Boot (MBR + A/B) Use `config/examples/versal_vmk180_sdcard.config`. This uses the Arasan SDHCI controller and an **MBR** partitioned SD card. diff --git a/docs/compile.md b/docs/compile.md index 965d1a0025..44a9872dac 100644 --- a/docs/compile.md +++ b/docs/compile.md @@ -506,6 +506,12 @@ downgrades, compile with `ALLOW_DOWNGRADE=1`. Warning: this option will disable version checking before the updates, thus exposing the system to potential forced downgrade attacks. +### Roll back an unconfirmed image in dual-boot mode + +A dual-boot target that loads the image to RAM (two fixed slots, no swap, `src/update_ram.c`) boots the slot with the higher version and marks it `TESTING` until the application confirms it with `wolfBoot_success_part()`. If the board resets while the slot is still `TESTING`, wolfBoot falls back to the other slot only when that does not lower the version, so an update that boots but never confirms keeps being retried. + +`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. + ### 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/hal/versal.c b/hal/versal.c index 2694e6344a..9ef4e190fe 100644 --- a/hal/versal.c +++ b/hal/versal.c @@ -821,7 +821,10 @@ static int qspi_transfer(QspiDev_t *dev, const uint8_t *txData, uint32_t txLen, chunkLen = writeLen; while (chunkLen > 0 && ret == 0) { - uint32_t chunk = (chunkLen > 255) ? 255 : chunkLen; + /* Dual parallel stripes bytes across the two devices, so a chunk + * boundary must fall on an even byte count. */ + uint32_t chunkMax = dev->stripe ? 254 : 255; + uint32_t chunk = (chunkLen > chunkMax) ? chunkMax : chunkLen; chunkEntry = txEntry | GQSPI_GEN_FIFO_IMM(chunk); ret = qspi_gen_fifo_push(chunkEntry); @@ -1457,6 +1460,31 @@ void* hal_get_dts_update_address(void) #endif } +#if defined(EXT_ENCRYPTED) && defined(CUSTOM_ENCRYPT_KEY) +/* No key store is implemented for this target: these defaults fail, so an + * encrypted image does not boot until the platform supplies the key (eFuse, + * BBRAM or a PUF-wrapped store) by overriding wolfBoot_get_encrypt_key(). */ +int WEAKFUNCTION wolfBoot_get_encrypt_key(uint8_t *key, uint8_t *nonce) +{ + (void)key; + (void)nonce; + return -1; +} + +int WEAKFUNCTION wolfBoot_set_encrypt_key(const uint8_t *key, + const uint8_t *nonce) +{ + (void)key; + (void)nonce; + return -1; +} + +int WEAKFUNCTION wolfBoot_erase_encrypt_key(void) +{ + return -1; +} +#endif + #ifdef __WOLFBOOT /** * Fixup Device Tree before booting Linux @@ -1499,6 +1527,16 @@ int hal_dts_fixup(void* dts_addr, uint32_t capacity) } #ifdef WOLFBOOT_UPDATE_DISK (void)wolfBoot_disk_dts_fixup(&ctx); +#elif defined(WOLFBOOT_DUALBOOT) && defined(WOLFBOOT_FIXED_PARTITIONS) + if (wolfBoot_ramboot_part() >= 0) { + ret = fdt_fixup_chosen_val(&ctx, "wolfboot,boot-part", + (uint32_t)wolfBoot_ramboot_part()); + if (ret != 0) { + wolfBoot_printf("FDT: Failed to set wolfboot,boot-part (%d)\n", + ret); + return ret; + } + } #endif return 0; diff --git a/hal/versal.ld b/hal/versal.ld index a09b1c97ba..b19aadd286 100644 --- a/hal/versal.ld +++ b/hal/versal.ld @@ -30,7 +30,7 @@ _HEAP_SIZE = DEFINED(_HEAP_SIZE) ? _HEAP_SIZE : 0x20000; /* 128KB heap */ _EL0_STACK_SIZE = DEFINED(_EL0_STACK_SIZE) ? _EL0_STACK_SIZE : 0x1000; _EL1_STACK_SIZE = DEFINED(_EL1_STACK_SIZE) ? _EL1_STACK_SIZE : 0x2000; -_EL2_STACK_SIZE = DEFINED(_EL2_STACK_SIZE) ? _EL2_STACK_SIZE : 0x8000; /* Primary stack at EL2 */ +_EL2_STACK_SIZE = DEFINED(_EL2_STACK_SIZE) ? _EL2_STACK_SIZE : 0x40000; /* Primary stack at EL2, sized for ML-DSA-87 verify */ /* Memory regions * wolfBoot at 0x8000000 with 2MB allocated diff --git a/include/fdt.h b/include/fdt.h index 5b03854e25..c5a6c0558b 100644 --- a/include/fdt.h +++ b/include/fdt.h @@ -375,6 +375,9 @@ int fdt_fixup_chosen_val(fdt_ctx* ctx, const char* name, uint32_t val); int wolfBoot_disk_dts_fixup(fdt_ctx* ctx); #endif +/* Slot (PART_BOOT / PART_UPDATE) the RAM-boot loader verified, or -1. */ +int wolfBoot_ramboot_part(void); + /* Write /chosen/linux,initrd-{start,end} as 64-bit big-endian values, * creating /chosen if needed. Returns 0 or a negative FDT_ERR_*. */ int fdt_fixup_initrd(fdt_ctx* ctx, uint64_t start, uint64_t size); diff --git a/include/image.h b/include/image.h index 9306ee2ff1..4939305b7e 100644 --- a/include/image.h +++ b/include/image.h @@ -1797,7 +1797,16 @@ int keyslot_id_by_sha(const uint8_t *hint); # define PART_IS_EXT(x) (!(x)->not_ext) && PARTN_IS_EXT(((x)->part)) -#if defined(EXT_ENCRYPTED) && (defined(__WOLFBOOT) || defined(UNIT_TEST)) +/* An MMU target that loads the image from external flash to RAM keeps the + * ciphertext in flash as written and decrypts it in RAM + * (wolfBoot_ram_decrypt), so flash access for headers and trailers is raw. */ +#if defined(EXT_ENCRYPTED) && defined(MMU) && defined(EXT_FLASH) && \ + defined(NO_XIP) + #define WOLFBOOT_RAM_DECRYPT_EXT +#endif + +#if defined(EXT_ENCRYPTED) && !defined(WOLFBOOT_RAM_DECRYPT_EXT) && \ + (defined(__WOLFBOOT) || defined(UNIT_TEST)) #define ext_flash_check_write ext_flash_encrypt_write #define ext_flash_check_read ext_flash_decrypt_read #else diff --git a/include/wolfboot/wolfboot.h b/include/wolfboot/wolfboot.h index 0c78ce54cb..0d554bd88c 100644 --- a/include/wolfboot/wolfboot.h +++ b/include/wolfboot/wolfboot.h @@ -789,7 +789,9 @@ extern "C" { #endif void wolfBoot_update_trigger(void); +void wolfBoot_update_trigger_part(uint8_t part); void wolfBoot_success(void); +void wolfBoot_success_part(uint8_t part); uint32_t wolfBoot_image_size(uint8_t *image); uint32_t wolfBoot_get_blob_version(uint8_t *blob); uint16_t wolfBoot_get_blob_type(uint8_t *blob); @@ -822,6 +824,9 @@ int wolfBoot_clear_trailer(uint8_t part); int wolfBoot_fallback_is_possible(void); int wolfBoot_dualboot_candidate(void); +#ifdef WOLFBOOT_DUALBOOT_ROLLBACK_UNCONFIRMED +void wolfBoot_dualboot_erase_rejected(int active); +#endif int wolfBoot_dualboot_candidate_addr(void**); int wolfBoot_get_partition_state(uint8_t part, uint8_t *st); @@ -905,7 +910,8 @@ int wolfBoot_record_failure(uint8_t phase, uint8_t cause, uint8_t partition, #endif /* EXT_ENCRYPTED */ -#if defined(EXT_ENCRYPTED) && defined(MMU) +#if defined(EXT_ENCRYPTED) && defined(MMU) && \ + (defined(__WOLFBOOT) || defined(UNIT_TEST)) int wolfBoot_ram_decrypt(uint8_t *src, uint8_t *dst); #endif diff --git a/options.mk b/options.mk index 6bb2b4c064..ea305bf395 100644 --- a/options.mk +++ b/options.mk @@ -1126,6 +1126,13 @@ ifneq ($(filter 1,$(DISK_SDCARD) $(DISK_EMMC)),) endif endif +# Dual-boot (two fixed slots, no swap): an image that was booted on probation +# and never confirmed is dropped in favour of the other slot even when that +# slot holds a lower version. Anti-rollback still applies to confirmed images. +ifeq ($(DUALBOOT_ROLLBACK_UNCONFIRMED),1) + CFLAGS+=-D"WOLFBOOT_DUALBOOT_ROLLBACK_UNCONFIRMED" +endif + # Optional boot confirmation and rollback for disk boot (src/update_disk.c). # wolfBoot marks the slot it boots as TESTING in the last sector of that raw # partition; the OS clears it to SUCCESS once it is up. A slot still marked @@ -2027,7 +2034,7 @@ endif # Support external encryption cache # ifeq ($(ENCRYPT),1) - ifeq ($(ENCRYPT_CACHE),1) + ifneq ($(ENCRYPT_CACHE),) CFLAGS+=-D"WOLFBOOT_ENCRYPT_CACHE=$(ENCRYPT_CACHE)" endif endif diff --git a/src/boot_aarch64.c b/src/boot_aarch64.c index 3407776ab8..65f9b68944 100644 --- a/src/boot_aarch64.c +++ b/src/boot_aarch64.c @@ -179,6 +179,11 @@ void RAMFUNCTION do_boot(const uint32_t *app_offset) if ((dts_offset != NULL) && (wolfBoot_disk_boot_part() >= 0)) { wolfBoot_panic(); } +#elif defined(WOLFBOOT_DUALBOOT) && defined(WOLFBOOT_FIXED_PARTITIONS) + /* Same for the fixed-slot RAM loader. */ + if ((dts_offset != NULL) && (wolfBoot_ramboot_part() >= 0)) { + wolfBoot_panic(); + } #endif } #endif diff --git a/src/libwolfboot.c b/src/libwolfboot.c index 23c3ce03dd..1e1b27f34f 100644 --- a/src/libwolfboot.c +++ b/src/libwolfboot.c @@ -1808,32 +1808,97 @@ void RAMFUNCTION wolfBoot_update_trigger(void) } } +/** + * @brief Trigger an update of the given partition. + * + * PART_UPDATE is the same as wolfBoot_update_trigger. A fixed-slot dual-boot + * application running from the update partition, which wrote the new image + * to the BOOT partition, passes PART_BOOT to set that partition to + * "IMG_STATE_UPDATING". PART_BOOT is not supported where the BOOT partition + * trailer holds other state (NVM_FLASH_WRITEONCE, NVM_FLASH_JOURNAL, + * FLAGS_HOME, or an encryption key kept in flash). + * + * @param part PART_BOOT or PART_UPDATE. + */ +void RAMFUNCTION wolfBoot_update_trigger_part(uint8_t part) +{ + if (part == PART_UPDATE) { + wolfBoot_update_trigger(); + } +#if !defined(NVM_FLASH_WRITEONCE) && !defined(NVM_FLASH_JOURNAL) && \ + !defined(FLAGS_HOME) && (!defined(EXT_ENCRYPTED) || defined(MMU)) + else if (part == PART_BOOT) { + uint8_t st = IMG_STATE_UPDATING; +#ifndef CUSTOM_PARTITION_TRAILER + uintptr_t lastSector = ((PART_BOOT_ENDFLAGS - 1) / + WOLFBOOT_SECTOR_SIZE) * WOLFBOOT_SECTOR_SIZE; +#endif + + if (FLAGS_BOOT_EXT()) { + ext_flash_unlock(); +#ifndef CUSTOM_PARTITION_TRAILER + ext_flash_erase(lastSector, WOLFBOOT_SECTOR_SIZE); +#endif + wolfBoot_set_partition_state(PART_BOOT, st); + ext_flash_lock(); + } else { + hal_flash_unlock(); +#ifndef CUSTOM_PARTITION_TRAILER + hal_flash_erase(lastSector, WOLFBOOT_SECTOR_SIZE); +#endif + wolfBoot_set_partition_state(PART_BOOT, st); + hal_flash_lock(); + } + } +#endif +} + #endif /* WOLFBOOT_FIXED_PARTITIONS */ /** - * @brief Success function. + * @brief Success function for a given partition. * - * This function updates the boot partition state to "IMG_STATE_SUCCESS". - * If the FLAGS_BOOT_EXT macro is defined, it calls the appropriate flash unlock - * and lock functions before updating the partition state. If the EXT_ENCRYPTED - * macro is defined, it calls wolfBoot_erase_encrypt_key function. + * This function updates the state of the BOOT or UPDATE partition to + * "IMG_STATE_SUCCESS", using the flash unlock and lock functions that match + * where that partition lives. A dual-boot image running from the update + * partition confirms itself with PART_UPDATE. If the EXT_ENCRYPTED macro is + * defined, it calls wolfBoot_erase_encrypt_key function, unless the + * partitions stay encrypted in flash (WOLFBOOT_RAM_DECRYPT_EXT) and the key + * is needed on every boot. + * + * @param part PART_BOOT or PART_UPDATE. */ -void RAMFUNCTION wolfBoot_success(void) +void RAMFUNCTION wolfBoot_success_part(uint8_t part) { uint8_t st = IMG_STATE_SUCCESS; - if (FLAGS_BOOT_EXT()) { + + if ((part != PART_BOOT) && (part != PART_UPDATE)) + return; + if (((part == PART_BOOT) && FLAGS_BOOT_EXT()) || + ((part == PART_UPDATE) && FLAGS_UPDATE_EXT())) { ext_flash_unlock(); - wolfBoot_set_partition_state(PART_BOOT, st); + wolfBoot_set_partition_state(part, st); ext_flash_lock(); } else { hal_flash_unlock(); - wolfBoot_set_partition_state(PART_BOOT, st); + wolfBoot_set_partition_state(part, st); hal_flash_lock(); } -#ifdef EXT_ENCRYPTED +#if defined(EXT_ENCRYPTED) && !defined(WOLFBOOT_RAM_DECRYPT_EXT) wolfBoot_erase_encrypt_key(); #endif } + +/** + * @brief Success function. + * + * This function updates the boot partition state to "IMG_STATE_SUCCESS". + * See wolfBoot_success_part. + */ +void RAMFUNCTION wolfBoot_success(void) +{ + wolfBoot_success_part(PART_BOOT); +} #ifdef __CCRX__ #pragma section #endif @@ -2386,7 +2451,15 @@ int wolfBoot_get_delta_info(uint8_t part, int inverse, uint32_t **img_offset, #endif -#if defined(EXT_ENCRYPTED) && defined(MMU) +/* Reading a field of an encrypted header means decrypting it first, which + * only the bootloader can do: an application linking this file has neither + * the cipher state nor the key. */ +#if defined(EXT_ENCRYPTED) && defined(MMU) && \ + (defined(__WOLFBOOT) || defined(UNIT_TEST)) +#define WOLFBOOT_DECRYPT_HDR +#endif + +#ifdef WOLFBOOT_DECRYPT_HDR #if defined(__WOLFBOOT) && defined(WOLFBOOT_LOAD_ADDRESS) extern uint8_t _end[]; /* linker symbol: end of wolfBoot BSS */ #endif @@ -2437,7 +2510,7 @@ uint32_t wolfBoot_get_blob_version(uint8_t *blob) uint32_t version = 0; if (blob == NULL) return 0; -#if defined(EXT_ENCRYPTED) && defined(MMU) +#ifdef WOLFBOOT_DECRYPT_HDR if (wolfBoot_initialize_encryption() < 0) return 0; decrypt_header(blob); @@ -2448,7 +2521,7 @@ uint32_t wolfBoot_get_blob_version(uint8_t *blob) if (wolfBoot_find_header(img_bin + IMAGE_HEADER_OFFSET, HDR_VERSION, (void *)&version_field) == WOLFBOOT_HDR_U32_SZ && version_field) version = im2n(WOLFBOOT_HDR_GET_U32(version_field)); -#if defined(EXT_ENCRYPTED) && defined(MMU) +#ifdef WOLFBOOT_DECRYPT_HDR dec_hdr_clear(); #endif return version; @@ -2470,7 +2543,7 @@ uint16_t wolfBoot_get_blob_type(uint8_t *blob) uint16_t *volatile type_field = NULL; uint8_t *img_bin = blob; uint16_t type = 0; -#if defined(EXT_ENCRYPTED) && defined(MMU) +#ifdef WOLFBOOT_DECRYPT_HDR if (wolfBoot_initialize_encryption() < 0) return 0; decrypt_header(blob); @@ -2481,7 +2554,7 @@ uint16_t wolfBoot_get_blob_type(uint8_t *blob) if (wolfBoot_find_header(img_bin + IMAGE_HEADER_OFFSET, HDR_IMG_TYPE, (void *)&type_field) == WOLFBOOT_HDR_U16_SZ && type_field) type = im2ns(WOLFBOOT_HDR_GET_U16(type_field)); -#if defined(EXT_ENCRYPTED) && defined(MMU) +#ifdef WOLFBOOT_DECRYPT_HDR dec_hdr_clear(); #endif return type; @@ -2507,7 +2580,7 @@ uint32_t wolfBoot_get_blob_diffbase_version(uint8_t *blob) uint32_t *magic = NULL; uint8_t *img_bin = blob; uint32_t delta_base_ver = 0; -#if defined(EXT_ENCRYPTED) && defined(MMU) +#ifdef WOLFBOOT_DECRYPT_HDR if (wolfBoot_initialize_encryption() < 0) return 0; decrypt_header(blob); @@ -2519,7 +2592,7 @@ uint32_t wolfBoot_get_blob_diffbase_version(uint8_t *blob) if (wolfBoot_find_header(img_bin + IMAGE_HEADER_OFFSET, HDR_IMG_DELTA_BASE, (void *)&delta_base) == sizeof(uint32_t) && delta_base) delta_base_ver = im2n(*delta_base); -#if defined(EXT_ENCRYPTED) && defined(MMU) +#ifdef WOLFBOOT_DECRYPT_HDR dec_hdr_clear(); #endif return delta_base_ver; @@ -2702,12 +2775,30 @@ uint16_t wolfBoot_get_image_type(uint8_t part) * Returns -1 if no valid candidate is found. * */ +#ifdef WOLFBOOT_DUALBOOT_ROLLBACK_UNCONFIRMED +/* Unconfirmed slot passed over by wolfBoot_dualboot_candidate(), or -1. */ +static int dualboot_rejected = -1; + +/* Erase the passed-over slot. The loader calls this once the image it boots + * instead has been verified, so a bad fallback never costs the only other + * image. */ +void wolfBoot_dualboot_erase_rejected(int active) +{ + if ((dualboot_rejected >= 0) && (dualboot_rejected != active)) + wolfBoot_erase_partition((uint8_t)dualboot_rejected); + dualboot_rejected = -1; +} +#endif + int wolfBoot_dualboot_candidate(void) { int candidate = PART_BOOT; int fallback_possible = 0; uint32_t boot_v, update_v; uint8_t p_state; +#ifdef WOLFBOOT_DUALBOOT_ROLLBACK_UNCONFIRMED + dualboot_rejected = -1; +#endif /* Find the candidate */ boot_v = wolfBoot_current_firmware_version(); update_v = wolfBoot_update_firmware_version(); @@ -2732,7 +2823,8 @@ int wolfBoot_dualboot_candidate(void) (wolfBoot_get_partition_state(candidate, &p_state) == 0) && (p_state == IMG_STATE_TESTING)) { -#ifndef ALLOW_DOWNGRADE +#if !defined(ALLOW_DOWNGRADE) && \ + !defined(WOLFBOOT_DUALBOOT_ROLLBACK_UNCONFIRMED) uint32_t candidate_v = (candidate == PART_BOOT) ? boot_v : update_v; uint32_t fallback_v = (candidate == PART_BOOT) ? update_v : boot_v; @@ -2741,7 +2833,11 @@ int wolfBoot_dualboot_candidate(void) return candidate; } #endif +#ifdef WOLFBOOT_DUALBOOT_ROLLBACK_UNCONFIRMED + dualboot_rejected = candidate; +#else wolfBoot_erase_partition(candidate); +#endif candidate ^= 1; /* switch to other partition if available */ } return candidate; @@ -2830,7 +2926,7 @@ int wolfBoot_fallback_is_possible(void) #endif #endif #else - #define ENCRYPT_CACHE (WOLFBOOT_ENCRYPT_CACHE) + #define ENCRYPT_CACHE ((uint8_t *)(uintptr_t)(WOLFBOOT_ENCRYPT_CACHE)) #endif #if defined(EXT_ENCRYPTED) && defined(MMU) && !defined(CUSTOM_ENCRYPT_KEY) @@ -3672,7 +3768,7 @@ int RAMFUNCTION ext_flash_encrypt_write(uintptr_t address, const uint8_t *data, * or they would re-anchor the stream at the standard-IV position. */ uint32_t iv_offset_at_entry = 0; #if defined(EXT_ENCRYPTED) && !defined(WOLFBOOT_SMALL_STACK) && \ - !defined(NVM_FLASH_WRITEONCE) + !defined(NVM_FLASH_WRITEONCE) && !defined(WOLFBOOT_ENCRYPT_CACHE) uint8_t ENCRYPT_CACHE[NVM_CACHE_SIZE] XALIGNED_STACK(32); #endif @@ -3917,7 +4013,7 @@ int RAMFUNCTION ext_flash_decrypt_read(uintptr_t address, uint8_t *data, int len #endif /* EXT_FLASH */ #endif /* __WOLFBOOT */ -#if defined(MMU) +#ifdef WOLFBOOT_DECRYPT_HDR /* The decrypt loop in wolfBoot_ram_decrypt() copies in ENCRYPT_BLOCK_SIZE * granules, rounding the final write up to a block boundary. The size bound is * only safe if the RAM load region is itself block-aligned; assert that where @@ -3947,6 +4043,9 @@ int wolfBoot_ram_decrypt(uint8_t *src, uint8_t *dst) uint8_t *row_address = src; uint32_t dst_offset = 0, iv_counter = 0; uint32_t len; +#ifdef WOLFBOOT_RAM_DECRYPT_EXT + uint32_t stage_len; +#endif #if defined(__WOLFBOOT) && defined(WOLFBOOT_LOAD_ADDRESS) uintptr_t wb_hi = (uintptr_t)_end; uintptr_t img_lo = (uintptr_t)dst; @@ -3970,8 +4069,27 @@ int wolfBoot_ram_decrypt(uint8_t *src, uint8_t *dst) } } +#ifdef WOLFBOOT_RAM_DECRYPT_EXT + /* The flash is not memory mapped: stage the ciphertext at the load + * address and decrypt it in place. */ +#if defined(__WOLFBOOT) && defined(WOLFBOOT_LOAD_ADDRESS) + if (ramboot_region_overlap(img_lo, img_lo + IMAGE_HEADER_SIZE, wb_lo, + wb_hi)) { + wolfBoot_printf("Error: image header at %p overlaps wolfBoot\n", + (void*)img_lo); + return -1; + } +#endif + if (ext_flash_read((uintptr_t)src, dst, IMAGE_HEADER_SIZE) != + IMAGE_HEADER_SIZE) { + wolfBoot_printf("Error reading header at %p!\n", src); + return -1; + } + row_address = dst; +#endif + /* Attempt to decrypt firmware header */ - if (decrypt_header(src) != 0) { + if (decrypt_header(row_address) != 0) { wolfBoot_printf("Error decrypting header at %p!\n", src); return -1; } @@ -4023,6 +4141,14 @@ int wolfBoot_ram_decrypt(uint8_t *src, uint8_t *dst) (void*)img_lo, (void*)img_hi, (void*)wb_lo, (void*)wb_hi); return -1; } +#endif +#ifdef WOLFBOOT_RAM_DECRYPT_EXT + stage_len = (len + ENCRYPT_BLOCK_SIZE - 1) & ~(ENCRYPT_BLOCK_SIZE - 1); + if (ext_flash_read((uintptr_t)src + IMAGE_HEADER_SIZE, + dst + IMAGE_HEADER_SIZE, (int)stage_len) != (int)stage_len) { + wolfBoot_printf("Error reading image at %p!\n", src); + return -1; + } #endif while (dst_offset < (len + IMAGE_HEADER_SIZE)) { wolfBoot_crypto_set_iv(encrypt_iv_nonce, iv_counter); @@ -4034,7 +4160,7 @@ int wolfBoot_ram_decrypt(uint8_t *src, uint8_t *dst) } return 0; } -#endif /* MMU */ +#endif /* WOLFBOOT_DECRYPT_HDR */ #endif /* EXT_ENCRYPTED */ /* A secure application without wolfCrypt TZ is entered Secure and exports no diff --git a/src/update_flash_hwswap.c b/src/update_flash_hwswap.c index c10216d28e..42962216c5 100644 --- a/src/update_flash_hwswap.c +++ b/src/update_flash_hwswap.c @@ -34,6 +34,10 @@ int WP11_Library_Init(void); #endif +#ifdef WOLFBOOT_DUALBOOT_ROLLBACK_UNCONFIRMED +#error DUALBOOT_ROLLBACK_UNCONFIRMED is only supported by the RAM loader +#endif + extern void hal_flash_dualbank_swap(void); static inline void boot_panic(void) diff --git a/src/update_ram.c b/src/update_ram.c index 81dad3fb20..42fbc59be9 100644 --- a/src/update_ram.c +++ b/src/update_ram.c @@ -64,6 +64,16 @@ extern uint8_t _end[]; /* linker symbol: end of wolfBoot BSS */ #define WOLFBOOT_USE_RAMBOOT #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; + +int wolfBoot_ramboot_part(void) +{ + return ramboot_part; +} +#endif + #ifdef WOLFBOOT_USE_RAMBOOT /* Function to load image from flash to ram */ @@ -366,6 +376,9 @@ void RAMFUNCTION wolfBoot_start(void) #if defined(EXT_ENCRYPTED) && defined(MMU) ret = wolfBoot_ram_decrypt((uint8_t*)source_address, (uint8_t*)load_address); + #ifdef WOLFBOOT_RAM_DECRYPT_EXT + os_image.not_ext = 1; + #endif #else ret = wolfBoot_ramboot(&os_image, (uint8_t*)source_address, (uint8_t*)load_address); @@ -468,6 +481,9 @@ void RAMFUNCTION wolfBoot_start(void) #endif wolfBoot_printf("Firmware Valid\n"); +#if defined(WOLFBOOT_DUALBOOT) && defined(WOLFBOOT_FIXED_PARTITIONS) + ramboot_part = active; +#endif /* First time we boot this update, set to TESTING to await * confirmation from the system @@ -867,6 +883,12 @@ void RAMFUNCTION wolfBoot_start(void) * an unvalidated blob. */ wolfboot_dts_addr = (void*)dts_addr; #endif +#if defined(WOLFBOOT_DUALBOOT) && defined(WOLFBOOT_FIXED_PARTITIONS) && \ + defined(WOLFBOOT_DUALBOOT_ROLLBACK_UNCONFIRMED) + /* The fallback is verified and loaded. */ + wolfBoot_dualboot_erase_rejected(active); +#endif + #ifdef WOLFBOOT_HOOK_PREBOOT /* Before hal_prepare_boot(), so a hook still has the MMU and caches as * wolfBoot set them up. */ diff --git a/tools/config.mk b/tools/config.mk index da55c94d7e..ee5fa9d734 100644 --- a/tools/config.mk +++ b/tools/config.mk @@ -121,7 +121,7 @@ WATCHDOG_HANDOFF?=0 CONFIG_VARS:= ARCH TARGET SIGN HASH MCUXSDK MCUXPRESSO MCUXPRESSO_CPU MCUXPRESSO_DRIVERS \ MCUXPRESSO_CMSIS FREEDOM_E_SDK STM32CUBE CYPRESS_PDL CYPRESS_CORE_LIB CYPRESS_CMSIS CYPRESS_TEMPLATE_LIB DEBUG VTOR \ - CORTEX_M0 CORTEX_M7 CORTEX_M23 CORTEX_M33 CORTEX_M55 NO_ASM EXT_FLASH SPI_FLASH NO_XIP UART_FLASH ALLOW_DOWNGRADE NVM_FLASH_WRITEONCE CUSTOM_PARTITION_TRAILER \ + CORTEX_M0 CORTEX_M7 CORTEX_M23 CORTEX_M33 CORTEX_M55 NO_ASM EXT_FLASH SPI_FLASH NO_XIP UART_FLASH ALLOW_DOWNGRADE DUALBOOT_ROLLBACK_UNCONFIRMED NVM_FLASH_WRITEONCE CUSTOM_PARTITION_TRAILER \ NVM_FLASH_JOURNAL NVM_FLASH_JOURNAL_DUAL NVM_FLASH_ECC \ FLASH_WRITE_UNIT FLASH_ERASE_UNIT \ DISABLE_BACKUP WOLFBOOT_VERSION V NO_MPU ENCRYPT FLAGS_HOME FLAGS_INVERT NO_SWAP_EXT \ diff --git a/tools/unit-tests/Makefile b/tools/unit-tests/Makefile index 9a2ee29cd2..1c42cefc1c 100644 --- a/tools/unit-tests/Makefile +++ b/tools/unit-tests/Makefile @@ -86,7 +86,7 @@ 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-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-nopart unit-update-ram-nofixed unit-update-ram-nofixed-noramboot unit-update-ram-noramboot unit-update-ram-custom-trailer 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-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-image-nopart unit-image-sha384 unit-image-sha3-384 unit-image-dts \ unit-image-dts-sha384 unit-image-dts-sha3-384 unit-store-sbrk \ @@ -563,6 +563,13 @@ unit-update-flash-hwswap:CFLAGS+=-DMOCK_PARTITIONS -DWOLFBOOT_NO_SIGN -DUNIT_TES -DWOLFBOOT_HASH_SHA256 -DPRINTF_ENABLED -DEXT_FLASH -DPART_UPDATE_EXT \ -DPART_SWAP_EXT -DPART_BOOT_EXT -DWOLFBOOT_DUALBOOT -DNO_XIP \ -DWOLFBOOT_ORIGIN=MOCK_ADDRESS_BOOT -DBOOTLOADER_PARTITION_SIZE=WOLFBOOT_PARTITION_SIZE +# unit-update-ram with an unconfirmed (TESTING) image allowed to fall back to a +# lower version. +unit-update-ram-rollback-unconfirmed: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_DUALBOOT_ROLLBACK_UNCONFIRMED \ + -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 \ @@ -572,6 +579,13 @@ unit-update-ram-enc:CFLAGS+=-DMOCK_PARTITIONS -DWOLFBOOT_NO_SIGN -DUNIT_TEST_AUT -DPART_SWAP_EXT -DPART_BOOT_EXT -DWOLFBOOT_DUALBOOT -DNO_XIP -DMMU \ -DEXT_ENCRYPTED -DENCRYPT_WITH_CHACHA -DHAVE_CHACHA \ -DWOLFBOOT_ORIGIN=MOCK_ADDRESS_BOOT -DBOOTLOADER_PARTITION_SIZE=WOLFBOOT_PARTITION_SIZE +unit-update-ram-enc-start: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 -DMMU \ + -DEXT_ENCRYPTED -DENCRYPT_WITH_CHACHA -DHAVE_CHACHA \ + -DWOLFBOOT_DTS_BOOT_ADDRESS=0xCF000000 \ + -DWOLFBOOT_DTS_UPDATE_ADDRESS=0xCF100000 \ + -DWOLFBOOT_ORIGIN=MOCK_ADDRESS_BOOT -DBOOTLOADER_PARTITION_SIZE=WOLFBOOT_PARTITION_SIZE # Same source as unit-update-ram-enc, but with a WOLFBOOT_RAMBOOT_MAX_SIZE that # is tighter than the partition cap (NO_PARTITIONS / RAM-load-region flavour), # so the bound check is exercised through its RAMBOOT_MAX_SIZE branch. @@ -1409,6 +1423,20 @@ unit-update-flash-enc: ../../include/target.h unit-update-flash.c $(WOLFBOOT_LIB_WOLFSSL)/wolfcrypt/src/chacha.c \ $(CFLAGS) $(LDFLAGS) +# unit-update-flash-enc with the encrypt staging buffer supplied by +# WOLFBOOT_ENCRYPT_CACHE instead of the stack. +unit-update-flash-enc-cache:CFLAGS+=-DMOCK_PARTITIONS -DWOLFBOOT_NO_SIGN -DUNIT_TEST_AUTH \ + -DWOLFBOOT_HASH_SHA256 -DPRINTF_ENABLED -DEXT_FLASH -DPART_UPDATE_EXT \ + -DPART_SWAP_EXT -DEXT_ENCRYPTED -DENCRYPT_WITH_CHACHA -DHAVE_CHACHA \ + -DCUSTOM_ENCRYPT_KEY -DUNIT_TEST_FALLBACK_ONLY \ + -DWOLFBOOT_ENCRYPT_CACHE=unit_encrypt_cache \ + -DWOLFBOOT_ORIGIN=MOCK_ADDRESS_BOOT -DBOOTLOADER_PARTITION_SIZE=WOLFBOOT_PARTITION_SIZE +unit-update-flash-enc-cache: ../../include/target.h unit-update-flash.c + gcc -o $@ unit-update-flash.c ../../src/image.c \ + $(WOLFBOOT_LIB_WOLFSSL)/wolfcrypt/src/sha256.c \ + $(WOLFBOOT_LIB_WOLFSSL)/wolfcrypt/src/chacha.c \ + $(CFLAGS) $(LDFLAGS) + # Same encrypted target without UNIT_TEST_FALLBACK_ONLY, so the full # end-to-end suite (forward updates, rollback, ...) runs against the # encrypted swap and its IV derivation. @@ -1490,6 +1518,12 @@ unit-update-ram-enc: ../../include/target.h unit-update-ram-enc.c $(WOLFBOOT_LIB_WOLFSSL)/wolfcrypt/src/chacha.c \ $(CFLAGS) $(LDFLAGS) +unit-update-ram-enc-start: ../../include/target.h unit-update-ram-enc-start.c + gcc -o $@ unit-update-ram-enc-start.c ../../src/image.c \ + $(WOLFBOOT_LIB_WOLFSSL)/wolfcrypt/src/sha256.c \ + $(WOLFBOOT_LIB_WOLFSSL)/wolfcrypt/src/chacha.c \ + $(CFLAGS) $(LDFLAGS) + unit-update-ram-enc-nopart: ../../include/target.h unit-update-ram-enc.c gcc -o $@ unit-update-ram-enc.c \ $(WOLFBOOT_LIB_WOLFSSL)/wolfcrypt/src/sha256.c \ @@ -1502,6 +1536,9 @@ unit-update-ram-nofixed: ../../include/target.h unit-update-ram-nofixed.c unit-update-ram-nofixed-noramboot: ../../include/target.h unit-update-ram-nofixed-noramboot.c gcc -o $@ unit-update-ram-nofixed-noramboot.c ../../src/image.c $(WOLFBOOT_LIB_WOLFSSL)/wolfcrypt/src/sha256.c $(CFLAGS) $(LDFLAGS) +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-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) @@ -1829,6 +1866,8 @@ unit-sama5d3-ext-read: unit-sama5d3-ext-read.c sama5d3_read_extract.h # - VERSAL_QSPI_BASE rebased onto host memory (register offsets kept); # - the real qspi_dma_wait() renamed to qspi_dma_wait_hw() so the test # can provide a qspi_dma_wait() that performs the DMA move; +# - the real qspi_fifo_tx() renamed to qspi_fifo_tx_hw() so the test can +# record each write chunk with the GenFIFO entry that carries it; # The test is built with -DTARGET_versal -DEXT_FLASH -DARCH_AARCH64 # -DARCH_64BIT (the file is guarded by TARGET_versal, the QSPI section by # EXT_FLASH, and the architecture check / hal.h prototypes by the ARCH @@ -1869,6 +1908,7 @@ versal_host.c: ../../hal/versal.c versal_host.h aarch64_arch_host.h -e 's/__asm__ volatile\("mrs %0, cntpct_el0" : "=r" \(cntpct\)\);/cntpct = ++versal_host_ticks;/' \ -e 's/__asm__ volatile\("mrs %0, cntfrq_el0" : "=r" \(cntfrq\)\);/cntfrq = 1000000ULL;/' \ -e 's/^static int qspi_dma_wait\(void\)$$/static int qspi_dma_wait_hw(void)/' \ + -e 's/^static int qspi_fifo_tx\(const uint8_t \*data, uint32_t len\)$$/static int qspi_fifo_tx_hw(const uint8_t *data, uint32_t len)/' \ -e 's/^[[:space:]]*__asm__[[:space:]]+(__)?(volatile__|volatile)\("[^"]*"\);[[:space:]]*//' \ -e 's/^[[:space:]]*__asm__[[:space:]]+(__)?(volatile__|volatile)\("[^"]*"[[:space:]]*:[[:space:]]*:[^;]*\);[[:space:]]*//' $< > $@ test -s $@ diff --git a/tools/unit-tests/unit-update-flash.c b/tools/unit-tests/unit-update-flash.c index 7411abe05a..fcf5f2c6b3 100644 --- a/tools/unit-tests/unit-update-flash.c +++ b/tools/unit-tests/unit-update-flash.c @@ -37,7 +37,13 @@ #include #include "user_settings.h" #include "wolfboot/wolfboot.h" +#ifdef WOLFBOOT_ENCRYPT_CACHE +extern uint8_t unit_encrypt_cache[]; +#endif #include "libwolfboot.c" +#ifdef WOLFBOOT_ENCRYPT_CACHE +uint8_t unit_encrypt_cache[NVM_CACHE_SIZE]; +#endif #ifdef DELTA_UPDATES #define wb_patch_init unit_test_wb_patch_init #define wb_patch unit_test_wb_patch diff --git a/tools/unit-tests/unit-update-ram-enc-start.c b/tools/unit-tests/unit-update-ram-enc-start.c new file mode 100644 index 0000000000..0ec16f0f24 --- /dev/null +++ b/tools/unit-tests/unit-update-ram-enc-start.c @@ -0,0 +1,397 @@ +/* unit-update-ram-enc-start.c + * + * Unit tests for wolfBoot_start() loading an encrypted image from external + * flash that is not memory mapped (WOLFBOOT_RAM_DECRYPT_EXT). + * + * 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 + */ +#ifndef WOLFBOOT_HASH_SHA256 + #define WOLFBOOT_HASH_SHA256 +#endif +#define IMAGE_HEADER_SIZE 256 +#define MOCK_ADDRESS_UPDATE 0xCC000000 +#define MOCK_ADDRESS_BOOT 0xCD000000 +#define MOCK_ADDRESS_SWAP 0xCE000000 +#include "target.h" +static unsigned char wolfboot_ram[2 * WOLFBOOT_PARTITION_SIZE + IMAGE_HEADER_SIZE]; + +#define WOLFBOOT_LOAD_ADDRESS (((uintptr_t)wolfboot_ram + IMAGE_HEADER_SIZE)) + +/* Not a multiple of ENCRYPT_BLOCK_SIZE, so the staged read is rounded up */ +#define TEST_SIZE 5300 +#define TEST_SIZE_PADDED 5312 +#define TEST_TOTAL (IMAGE_HEADER_SIZE + TEST_SIZE_PADDED) + +#include +#include +#include "user_settings.h" +#include "wolfboot/wolfboot.h" +#include "libwolfboot.c" +#include "fdt.h" +static uint8_t dts_stage[WOLFBOOT_DTS_MAX_SIZE]; +#define WOLFBOOT_LOAD_DTS_ADDRESS ((uintptr_t)dts_stage) + +void* hal_get_dts_address(void) +{ + return NULL; +} + +int hal_dts_fixup(void *dts_addr, uint32_t capacity) +{ + (void)dts_addr; + (void)capacity; + return 0; +} + +/* The test images are raw binaries, not FIT */ +int fdt_open(fdt_ctx* ctx, void* blob, uint32_t capacity) +{ + (void)ctx; + (void)blob; + (void)capacity; + return -1; +} + +uint32_t fdt_size(const fdt_ctx* ctx) +{ + (void)ctx; + return 0; +} + +int fdt_peek_size(const void* hdr, uint32_t hdr_len, uint32_t* totalsize) +{ + (void)hdr; + (void)hdr_len; + (void)totalsize; + return -1; +} + +void fdt_set_dtb_authenticated(int authenticated) +{ + (void)authenticated; +} + +const char* fit_find_images(fdt_ctx* ctx, const char** pkernel, + const char** pflat_dt, const char** pramdisk, const char** pfpga) +{ + (void)ctx; + (void)pkernel; + (void)pflat_dt; + (void)pramdisk; + (void)pfpga; + return NULL; +} + +void* fit_load_image(fdt_ctx* ctx, const char* image, int* lenp) +{ + (void)ctx; + (void)image; + (void)lenp; + return NULL; +} + +void* fit_load_kernel(fdt_ctx* ctx, const char* kernel_node, int* lenp) +{ + (void)ctx; + (void)kernel_node; + (void)lenp; + return NULL; +} + +/* image.c needs the device tree partitions; the loader under test has none */ +#undef WOLFBOOT_DTS_BOOT_ADDRESS +#undef WOLFBOOT_DTS_UPDATE_ADDRESS +#include "update_ram.c" +#include +#include +#include +#include +#define ext_flash_read mock_ext_flash_read +#include "unit-mock-flash.c" +#undef ext_flash_read +#include +#include + +const char *argv0; + +Suite *wolfboot_suite(void); + +/* Reads outside the two partitions are refused and counted: the flash is not + * memory mapped, so a RAM address is never a valid flash offset. */ +static int mock_bad_reads = 0; + +int ext_flash_read(uintptr_t address, uint8_t *data, int len) +{ + if (!((address >= WOLFBOOT_PARTITION_BOOT_ADDRESS && + address < WOLFBOOT_PARTITION_BOOT_ADDRESS + + WOLFBOOT_PARTITION_SIZE) || + (address >= WOLFBOOT_PARTITION_UPDATE_ADDRESS && + address < WOLFBOOT_PARTITION_UPDATE_ADDRESS + + WOLFBOOT_PARTITION_SIZE))) { + mock_bad_reads++; + return -1; + } + return mock_ext_flash_read(address, data, len); +} + +static uint8_t plain_img[2][TEST_TOTAL]; +static uint8_t enc_img[2][TEST_TOTAL]; +static int wolfBoot_staged_ok = 0; +static int staged_part = -1; + +void do_boot(const uint32_t *address, const uint32_t *dts) +{ + (void)dts; + if (wolfBoot_panicked) + return; + wolfBoot_staged_ok++; + staged_part = wolfBoot_ramboot_part(); + ck_assert_uint_eq((uintptr_t)address, WOLFBOOT_LOAD_ADDRESS); +} + +int hal_flash_protect(haladdr_t address, int len) +{ + (void)address; + (void)len; + return 0; +} + +static void prepare_flash(void) +{ + uint8_t key[ENCRYPT_KEY_SIZE]; + uint8_t nonce[ENCRYPT_NONCE_SIZE]; + unsigned int i; + int ret; + + ret = mmap_file("/tmp/wolfboot-unit-ext-file.bin", + (void *)(uintptr_t)MOCK_ADDRESS_UPDATE, + WOLFBOOT_PARTITION_SIZE + IMAGE_HEADER_SIZE, NULL); + ck_assert(ret >= 0); + ret = mmap_file("/tmp/wolfboot-unit-int-file.bin", + (void *)(uintptr_t)MOCK_ADDRESS_BOOT, + WOLFBOOT_PARTITION_SIZE + IMAGE_HEADER_SIZE, NULL); + ck_assert(ret >= 0); + ext_flash_unlock(); + ext_flash_erase(WOLFBOOT_PARTITION_BOOT_ADDRESS, + WOLFBOOT_PARTITION_SIZE + IMAGE_HEADER_SIZE); + ext_flash_erase(WOLFBOOT_PARTITION_UPDATE_ADDRESS, + WOLFBOOT_PARTITION_SIZE + IMAGE_HEADER_SIZE); + ext_flash_lock(); + + for (i = 0; i < ENCRYPT_KEY_SIZE; i++) + key[i] = (uint8_t)(i + 1); + for (i = 0; i < ENCRYPT_NONCE_SIZE; i++) + nonce[i] = (uint8_t)(0xA0 + i); + encrypt_initialized = 0; + ck_assert_int_eq(wolfBoot_set_encrypt_key(key, nonce), 0); + ck_assert_int_eq(crypto_init(), 0); + + wolfBoot_panicked = 0; + wolfBoot_staged_ok = 0; + staged_part = -1; + mock_bad_reads = 0; + memset(wolfboot_ram, 0, sizeof(wolfboot_ram)); +} + +static void cleanup_flash(void) +{ + munmap((void *)WOLFBOOT_PARTITION_BOOT_ADDRESS, + WOLFBOOT_PARTITION_SIZE + IMAGE_HEADER_SIZE); + munmap((void *)WOLFBOOT_PARTITION_UPDATE_ADDRESS, + WOLFBOOT_PARTITION_SIZE + IMAGE_HEADER_SIZE); +} + +#define DIGEST_TLV_OFF_IN_HDR 28 +/* Build a hashed image, encrypt it the way the sign tool does and write the + * ciphertext to the partition. */ +static void add_enc_payload(uint8_t part, uint32_t version) +{ + uint8_t *plain = plain_img[part]; + uint8_t *enc = enc_img[part]; + uintptr_t base = WOLFBOOT_PARTITION_BOOT_ADDRESS; + uint32_t word; + uint16_t word16; + uint32_t size = TEST_SIZE; + uint32_t off; + wc_Sha256 sha; + int i; + + if (part == PART_UPDATE) + base = WOLFBOOT_PARTITION_UPDATE_ADDRESS; + + memset(plain, 0xFF, TEST_TOTAL); + memcpy(plain, "WOLF", 4); + memcpy(plain + 4, &size, 4); + word = 4 << 16 | HDR_VERSION; + memcpy(plain + 8, &word, 4); + memcpy(plain + 12, &version, 4); + word = 2 << 16 | HDR_IMG_TYPE; + memcpy(plain + 16, &word, 4); + word16 = HDR_IMG_TYPE_AUTH_NONE | HDR_IMG_TYPE_APP; + memcpy(plain + 20, &word16, 2); + for (i = 0; i < TEST_SIZE; i++) + plain[IMAGE_HEADER_SIZE + i] = (uint8_t)(i * 7 + 3 + part); + + ck_assert_int_eq(wc_InitSha256_ex(&sha, NULL, INVALID_DEVID), 0); + ck_assert_int_eq(wc_Sha256Update(&sha, plain, DIGEST_TLV_OFF_IN_HDR), 0); + ck_assert_int_eq(wc_Sha256Update(&sha, plain + IMAGE_HEADER_SIZE, + TEST_SIZE), 0); + word = SHA256_DIGEST_SIZE << 16 | HDR_SHA256; + memcpy(plain + DIGEST_TLV_OFF_IN_HDR, &word, 4); + ck_assert_int_eq(wc_Sha256Final(&sha, + plain + DIGEST_TLV_OFF_IN_HDR + 4), 0); + wc_Sha256Free(&sha); + + for (off = 0; off < TEST_TOTAL; off += ENCRYPT_BLOCK_SIZE) { + wolfBoot_crypto_set_iv(encrypt_iv_nonce, off / ENCRYPT_BLOCK_SIZE); + crypto_encrypt(enc + off, plain + off, ENCRYPT_BLOCK_SIZE); + } + + ext_flash_unlock(); + ext_flash_write(base, enc, TEST_TOTAL); + ext_flash_lock(); +} + +static void tamper_flash(uint8_t part, uint32_t off) +{ + uint8_t *base = (uint8_t *)WOLFBOOT_PARTITION_BOOT_ADDRESS; + uint8_t b; + + if (part == PART_UPDATE) + base = (uint8_t *)WOLFBOOT_PARTITION_UPDATE_ADDRESS; + b = base[off] ^ 0x01; + ext_flash_unlock(); + ext_flash_write((uintptr_t)base + off, &b, 1); + ext_flash_lock(); +} + +START_TEST(test_enc_ext_start_valid) +{ + prepare_flash(); + add_enc_payload(PART_BOOT, 1); + + wolfBoot_start(); + + ck_assert_int_eq(wolfBoot_panicked, 0); + ck_assert_int_eq(wolfBoot_staged_ok, 1); + ck_assert_int_eq(staged_part, PART_BOOT); + ck_assert_int_eq(mock_bad_reads, 0); + ck_assert_mem_eq(wolfboot_ram, plain_img[PART_BOOT], + IMAGE_HEADER_SIZE + TEST_SIZE); + /* The ciphertext in flash is left as written */ + ck_assert_mem_eq((uint8_t *)WOLFBOOT_PARTITION_BOOT_ADDRESS, + enc_img[PART_BOOT], TEST_TOTAL); + cleanup_flash(); +} +END_TEST + +START_TEST(test_enc_ext_start_tampered_rejected) +{ + prepare_flash(); + add_enc_payload(PART_BOOT, 1); + tamper_flash(PART_BOOT, IMAGE_HEADER_SIZE + 100); + + wolfBoot_start(); + + ck_assert_int_eq(wolfBoot_staged_ok, 0); + ck_assert_int_ne(wolfBoot_panicked, 0); + ck_assert_int_eq(mock_bad_reads, 0); + cleanup_flash(); +} +END_TEST + +START_TEST(test_enc_ext_start_tampered_update_falls_back) +{ + prepare_flash(); + add_enc_payload(PART_BOOT, 1); + add_enc_payload(PART_UPDATE, 2); + tamper_flash(PART_UPDATE, IMAGE_HEADER_SIZE + 100); + + wolfBoot_start(); + + ck_assert_int_eq(wolfBoot_panicked, 0); + ck_assert_int_eq(wolfBoot_staged_ok, 1); + ck_assert_int_eq(staged_part, PART_BOOT); + ck_assert_int_eq(mock_bad_reads, 0); + ck_assert_mem_eq(wolfboot_ram, plain_img[PART_BOOT], + IMAGE_HEADER_SIZE + TEST_SIZE); + cleanup_flash(); +} +END_TEST + +/* The slots stay encrypted, so confirming an image must leave the key in + * place for the next boot. */ +START_TEST(test_enc_ext_start_boots_again_after_confirm) +{ + uint8_t st = 0; + + prepare_flash(); + add_enc_payload(PART_BOOT, 1); + + wolfBoot_start(); + ck_assert_int_eq(wolfBoot_staged_ok, 1); + + wolfBoot_success_part(PART_BOOT); + ck_assert_int_eq(wolfBoot_get_partition_state(PART_BOOT, &st), 0); + ck_assert_uint_eq(st, IMG_STATE_SUCCESS); + + /* Next boot: the cipher is set up again from the stored key */ + encrypt_initialized = 0; + memset(wolfboot_ram, 0, sizeof(wolfboot_ram)); + wolfBoot_start(); + + ck_assert_int_eq(wolfBoot_panicked, 0); + ck_assert_int_eq(wolfBoot_staged_ok, 2); + ck_assert_int_eq(mock_bad_reads, 0); + ck_assert_mem_eq(wolfboot_ram, plain_img[PART_BOOT], + IMAGE_HEADER_SIZE + TEST_SIZE); + cleanup_flash(); +} +END_TEST + +Suite *wolfboot_suite(void) +{ + Suite *s = suite_create("wolfboot-ram-decrypt-start"); + TCase *tc = tcase_create("encrypted ext flash RAM loader"); + + tcase_add_test(tc, test_enc_ext_start_valid); + tcase_add_test(tc, test_enc_ext_start_tampered_rejected); + tcase_add_test(tc, test_enc_ext_start_tampered_update_falls_back); + tcase_add_test(tc, test_enc_ext_start_boots_again_after_confirm); + tcase_set_timeout(tc, 5); + suite_add_tcase(s, tc); + return s; +} + +int main(int argc, char *argv[]) +{ + int fails; + Suite *s; + SRunner *sr; + + (void)argc; + argv0 = strdup(argv[0]); + s = wolfboot_suite(); + sr = srunner_create(s); + srunner_set_fork_status(sr, CK_NOFORK); + srunner_run_all(sr, CK_NORMAL); + fails = srunner_ntests_failed(sr); + srunner_free(sr); + return fails; +} diff --git a/tools/unit-tests/unit-update-ram-enc.c b/tools/unit-tests/unit-update-ram-enc.c index 3ed885f4a3..28e863b58c 100644 --- a/tools/unit-tests/unit-update-ram-enc.c +++ b/tools/unit-tests/unit-update-ram-enc.c @@ -359,6 +359,122 @@ START_TEST(test_ram_decrypt_one_over_rejected) } END_TEST +#ifdef WOLFBOOT_RAM_DECRYPT_EXT +/* The ciphertext is staged from external flash: a short read of the header + * must be rejected before anything is decrypted. */ +START_TEST(test_ram_decrypt_ext_header_short_read_rejected) +{ + const uint32_t len = 1024; + uint8_t *enc = malloc(IMAGE_HEADER_SIZE + len); + uint8_t *dst = malloc(WOLFBOOT_PARTITION_SIZE); + int ret; + + ck_assert_ptr_nonnull(enc); + ck_assert_ptr_nonnull(dst); + memset(enc, 0, IMAGE_HEADER_SIZE + len); + + setup_crypto_key(); + make_encrypted_header(enc, len); + + mock_ext_flash_short_len = IMAGE_HEADER_SIZE; + mock_ext_flash_short_bytes = 1; + ret = wolfBoot_ram_decrypt(enc, dst); + /* Clear the mock before asserting: the suite runs CK_NOFORK. */ + mock_ext_flash_short_len = 0; + mock_ext_flash_short_bytes = 0; + ck_assert_int_eq(ret, -1); + + free(enc); + free(dst); +} +END_TEST + +/* A short read of the image body must be rejected, and the ciphertext in + * flash is left as written. */ +START_TEST(test_ram_decrypt_ext_body_short_read_rejected) +{ + const uint32_t len = 1024; + const uint32_t total = IMAGE_HEADER_SIZE + len; + uint8_t *enc = malloc(total); + uint8_t *ref = malloc(total); + uint8_t *dst = malloc(WOLFBOOT_PARTITION_SIZE); + int ret; + + ck_assert_ptr_nonnull(enc); + ck_assert_ptr_nonnull(ref); + ck_assert_ptr_nonnull(dst); + ck_assert_uint_ne(len, IMAGE_HEADER_SIZE); + memset(enc, 0, total); + + setup_crypto_key(); + make_encrypted_header(enc, len); + memcpy(ref, enc, total); + + mock_ext_flash_short_len = (int)len; + mock_ext_flash_short_bytes = 1; + ret = wolfBoot_ram_decrypt(enc, dst); + mock_ext_flash_short_len = 0; + mock_ext_flash_short_bytes = 0; + ck_assert_int_eq(ret, -1); + ck_assert_mem_eq(enc, ref, total); + + /* The same image reads in full once the flash behaves. */ + ret = wolfBoot_ram_decrypt(enc, dst); + ck_assert_int_eq(ret, 0); + ck_assert_mem_eq(enc, ref, total); + + free(enc); + free(ref); + free(dst); +} +END_TEST + +/* A payload that is not a multiple of the cipher block: the staging read + * rounds up to a whole block and nothing past that block is written. */ +START_TEST(test_ram_decrypt_ext_unaligned_len) +{ + const uint32_t len = 1025; + const uint32_t padded = (len + ENCRYPT_BLOCK_SIZE - 1) & + ~(uint32_t)(ENCRYPT_BLOCK_SIZE - 1); + const uint32_t total = IMAGE_HEADER_SIZE + padded; + uint8_t *plain = malloc(total); + uint8_t *enc = malloc(total); + uint8_t *dst = malloc(WOLFBOOT_PARTITION_SIZE); + uint32_t magic = WOLFBOOT_MAGIC; + uint32_t touched_past = 0; + uint32_t i; + int ret; + + ck_assert_ptr_nonnull(plain); + ck_assert_ptr_nonnull(enc); + ck_assert_ptr_nonnull(dst); + ck_assert_uint_ne(len % ENCRYPT_BLOCK_SIZE, 0); + + for (i = 0; i < total; i++) + plain[i] = (uint8_t)(i * 7 + 3); + memcpy(plain, &magic, sizeof(magic)); + memcpy(plain + sizeof(uint32_t), &len, sizeof(len)); + + setup_crypto_key(); + encrypt_blob(enc, plain, total); + memset(dst, DST_CANARY, WOLFBOOT_PARTITION_SIZE); + + ret = wolfBoot_ram_decrypt(enc, dst); + ck_assert_int_eq(ret, 0); + ck_assert_mem_eq(dst, plain, IMAGE_HEADER_SIZE + len); + for (i = total; i < WOLFBOOT_PARTITION_SIZE; i++) { + if (dst[i] != DST_CANARY) + touched_past++; + } + ck_assert_uint_eq(touched_past, 0); + + free(plain); + free(enc); + free(dst); +} +END_TEST +#endif /* WOLFBOOT_RAM_DECRYPT_EXT */ + Suite *wolfboot_suite(void) { Suite *s = suite_create("wolfboot-ram-decrypt"); @@ -368,6 +484,9 @@ Suite *wolfboot_suite(void) TCase *bitflip = tcase_create("ram_decrypt length bit-flip rejected"); TCase *maxvalid = tcase_create("ram_decrypt exact-max valid"); TCase *oneover = tcase_create("ram_decrypt one block over rejected"); +#ifdef WOLFBOOT_RAM_DECRYPT_EXT + TCase *extshort = tcase_create("ram_decrypt ext flash short read rejected"); +#endif tcase_add_test(valid, test_ram_decrypt_valid); tcase_add_test(oversize, test_ram_decrypt_oversize_rejected); @@ -375,6 +494,11 @@ Suite *wolfboot_suite(void) tcase_add_test(bitflip, test_ram_decrypt_len_bitflip_rejected); tcase_add_test(maxvalid, test_ram_decrypt_max_valid); tcase_add_test(oneover, test_ram_decrypt_one_over_rejected); +#ifdef WOLFBOOT_RAM_DECRYPT_EXT + tcase_add_test(extshort, test_ram_decrypt_ext_header_short_read_rejected); + tcase_add_test(extshort, test_ram_decrypt_ext_body_short_read_rejected); + tcase_add_test(valid, test_ram_decrypt_ext_unaligned_len); +#endif suite_add_tcase(s, valid); suite_add_tcase(s, oversize); @@ -382,6 +506,9 @@ Suite *wolfboot_suite(void) suite_add_tcase(s, bitflip); suite_add_tcase(s, maxvalid); suite_add_tcase(s, oneover); +#ifdef WOLFBOOT_RAM_DECRYPT_EXT + suite_add_tcase(s, extshort); +#endif tcase_set_timeout(bitflip, 5); tcase_set_timeout(valid, 5); @@ -389,6 +516,9 @@ Suite *wolfboot_suite(void) tcase_set_timeout(overflow, 5); tcase_set_timeout(maxvalid, 5); tcase_set_timeout(oneover, 5); +#ifdef WOLFBOOT_RAM_DECRYPT_EXT + tcase_set_timeout(extshort, 5); +#endif return s; } diff --git a/tools/unit-tests/unit-update-ram.c b/tools/unit-tests/unit-update-ram.c index 65df44cb09..55dfac96bc 100644 --- a/tools/unit-tests/unit-update-ram.c +++ b/tools/unit-tests/unit-update-ram.c @@ -375,6 +375,9 @@ START_TEST (test_sunnyday_noupdate) wolfBoot_start(); ck_assert(wolfBoot_staged_ok); ck_assert(get_version_ramloaded() == 1); +#if defined(WOLFBOOT_DUALBOOT) && defined(WOLFBOOT_FIXED_PARTITIONS) + ck_assert_int_eq(wolfBoot_ramboot_part(), PART_BOOT); +#endif ck_assert_int_eq(wolfBoot_get_partition_state(PART_BOOT, &st), -1); #ifndef TZEN ck_assert_int_eq(mock_flash_protect_called, 1); @@ -408,6 +411,9 @@ START_TEST (test_forward_update_samesize) { wolfBoot_start(); ck_assert(wolfBoot_staged_ok); ck_assert(get_version_ramloaded() == 2); +#if defined(WOLFBOOT_DUALBOOT) && defined(WOLFBOOT_FIXED_PARTITIONS) + ck_assert_int_eq(wolfBoot_ramboot_part(), PART_UPDATE); +#endif assert_part_state(PART_UPDATE, IMG_STATE_TESTING); cleanup_flash(); } @@ -567,7 +573,13 @@ START_TEST (test_emergency_rollback_to_older_version_denied) { wolfBoot_start(); ck_assert(wolfBoot_staged_ok); +#ifdef WOLFBOOT_DUALBOOT_ROLLBACK_UNCONFIRMED + /* The unconfirmed image is dropped for the older confirmed one. */ + ck_assert_int_eq(get_version_ramloaded(), 1); + ck_assert_uint_eq(wolfBoot_current_firmware_version(), 0U); +#else ck_assert_int_eq(get_version_ramloaded(), 2); +#endif ck_assert_int_eq(wolfBoot_panicked, 0); cleanup_flash(); } @@ -587,10 +599,114 @@ START_TEST (test_dualboot_candidate_rejects_testing_rollback_to_lower_version) { ext_flash_lock(); candidate = wolfBoot_dualboot_candidate(); +#ifdef WOLFBOOT_DUALBOOT_ROLLBACK_UNCONFIRMED + /* Falls back to the lower version. The unconfirmed slot is kept until + * the loader has verified the fallback. */ + ck_assert_int_eq(candidate, PART_UPDATE); + ck_assert_uint_eq(wolfBoot_current_firmware_version(), 2U); + ck_assert_uint_eq(wolfBoot_update_firmware_version(), 1U); + wolfBoot_dualboot_erase_rejected(candidate); + ck_assert_uint_eq(wolfBoot_current_firmware_version(), 0U); + ck_assert_uint_eq(wolfBoot_update_firmware_version(), 1U); +#else ck_assert_int_eq(candidate, PART_BOOT); ck_assert_uint_eq(wolfBoot_current_firmware_version(), 2U); +#endif + cleanup_flash(); +} + +#ifdef WOLFBOOT_DUALBOOT_ROLLBACK_UNCONFIRMED +/* The fallback of an unconfirmed image fails verification: the unconfirmed + * image must still be there to boot. */ +START_TEST (test_rollback_unconfirmed_bad_fallback_keeps_image) { + uint8_t testing_flags[5] = { IMG_STATE_TESTING, 'B', 'O', 'O', 'T' }; + uint8_t bad_digest[SHA256_DIGEST_SIZE]; + reset_mock_stats(); + prepare_flash(); + add_payload(PART_BOOT, 2, TEST_SIZE_SMALL); + add_payload(PART_UPDATE, 1, TEST_SIZE_SMALL); + memset(bad_digest, 0xBA, SHA256_DIGEST_SIZE); + ext_flash_unlock(); + ext_flash_write(WOLFBOOT_PARTITION_BOOT_ADDRESS + WOLFBOOT_PARTITION_SIZE - 5, + testing_flags, 5); + ext_flash_write(WOLFBOOT_PARTITION_UPDATE_ADDRESS + DIGEST_TLV_OFF_IN_HDR + 4, + bad_digest, SHA256_DIGEST_SIZE); + ext_flash_lock(); + + wolfBoot_start(); + ck_assert(wolfBoot_staged_ok); + ck_assert_int_eq(wolfBoot_panicked, 0); + ck_assert_int_eq(get_version_ramloaded(), 2); + ck_assert_uint_eq(wolfBoot_current_firmware_version(), 2U); + cleanup_flash(); +} +END_TEST +#endif + +/* An image booted from the update partition confirms that partition. */ +START_TEST (test_success_part_update) { + reset_mock_stats(); + prepare_flash(); + add_payload(PART_BOOT, 1, TEST_SIZE_SMALL); + add_payload(PART_UPDATE, 2, TEST_SIZE_SMALL); + wolfBoot_update_trigger(); + wolfBoot_start(); + ck_assert(wolfBoot_staged_ok); + assert_part_state(PART_UPDATE, IMG_STATE_TESTING); + + wolfBoot_success_part(PART_UPDATE); + assert_part_state(PART_UPDATE, IMG_STATE_SUCCESS); + + /* Still selected, and kept, on the next boot. */ + ck_assert_int_eq(wolfBoot_dualboot_candidate(), PART_UPDATE); + ck_assert_uint_eq(wolfBoot_update_firmware_version(), 2U); + + /* Any other partition id is ignored. */ + wolfBoot_success_part(PART_SWAP); + wolfBoot_success_part(0xFF); + assert_part_state(PART_UPDATE, IMG_STATE_SUCCESS); cleanup_flash(); } +END_TEST + +/* An application running from the update partition arms an image it wrote + * to the boot partition. */ +START_TEST (test_update_trigger_part_boot) { + reset_mock_stats(); + prepare_flash(); + add_payload(PART_BOOT, 1, TEST_SIZE_SMALL); + add_payload(PART_UPDATE, 2, TEST_SIZE_SMALL); + wolfBoot_update_trigger_part(PART_UPDATE); + assert_part_state(PART_UPDATE, IMG_STATE_UPDATING); + wolfBoot_start(); + ck_assert_uint_eq(get_version_ramloaded(), 2U); + wolfBoot_success_part(PART_UPDATE); + + add_payload(PART_BOOT, 3, TEST_SIZE_SMALL); + /* Any other partition id is ignored. */ + wolfBoot_update_trigger_part(PART_SWAP); + wolfBoot_update_trigger_part(0xFF); + assert_part_state(PART_UPDATE, IMG_STATE_SUCCESS); + wolfBoot_update_trigger_part(PART_BOOT); + assert_part_state(PART_BOOT, IMG_STATE_UPDATING); + assert_part_state(PART_UPDATE, IMG_STATE_SUCCESS); + + wolfBoot_start(); + ck_assert_uint_eq(get_version_ramloaded(), 3U); + ck_assert_int_eq(wolfBoot_ramboot_part(), PART_BOOT); + assert_part_state(PART_BOOT, IMG_STATE_TESTING); + assert_part_state(PART_UPDATE, IMG_STATE_SUCCESS); + +#ifdef WOLFBOOT_DUALBOOT_ROLLBACK_UNCONFIRMED + /* Reset without confirming: back to the confirmed update partition. */ + wolfBoot_start(); + ck_assert_uint_eq(get_version_ramloaded(), 2U); + ck_assert_int_eq(wolfBoot_ramboot_part(), PART_UPDATE); + ck_assert_uint_eq(wolfBoot_current_firmware_version(), 0U); +#endif + cleanup_flash(); +} +END_TEST START_TEST (test_emergency_rollback_failure_due_to_bad_update) { uint8_t testing_flags[5] = { IMG_STATE_TESTING, 'B', 'O', 'O', 'T' }; @@ -700,6 +816,12 @@ Suite *wolfboot_suite(void) tcase_add_test(dualboot_candidate_rollback_denied, test_dualboot_candidate_rejects_testing_rollback_to_lower_version); tcase_add_test(emergency_rollback_failure_due_to_bad_update, test_emergency_rollback_failure_due_to_bad_update); +#ifdef WOLFBOOT_DUALBOOT_ROLLBACK_UNCONFIRMED + tcase_add_test(emergency_rollback_failure_due_to_bad_update, + test_rollback_unconfirmed_bad_fallback_keeps_image); +#endif + tcase_add_test(emergency_rollback, test_success_part_update); + tcase_add_test(emergency_rollback, test_update_trigger_part_boot); 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-versal-qspi-dma.c b/tools/unit-tests/unit-versal-qspi-dma.c index 29015fb4eb..18e9ce4b04 100644 --- a/tools/unit-tests/unit-versal-qspi-dma.c +++ b/tools/unit-tests/unit-versal-qspi-dma.c @@ -77,6 +77,26 @@ static int qspi_dma_wait(void) /* The real HAL (identical to hal/versal.c apart from the transforms * documented above). */ +#define MAX_TX 8 +struct tx_chunk { + uint32_t entry; + uint32_t len; + const uint8_t *data; +}; +static struct tx_chunk g_tx[MAX_TX]; +static int g_tx_n; + +static int qspi_fifo_tx(const uint8_t *data, uint32_t len) +{ + if (g_tx_n < MAX_TX) { + g_tx[g_tx_n].entry = GQSPI_GEN_FIFO; + g_tx[g_tx_n].len = len; + g_tx[g_tx_n].data = data; + g_tx_n++; + } + return 0; +} + #include "versal_host.c" static QspiDev_t g_dev; @@ -95,6 +115,8 @@ static void setup(void) memset(g_moves, 0, sizeof(g_moves)); g_moves_n = 0; + memset(g_tx, 0, sizeof(g_tx)); + g_tx_n = 0; memset(&g_dev, 0, sizeof(g_dev)); g_dev.bus = GQSPI_GEN_FIFO_BUS_LOW; @@ -172,6 +194,55 @@ START_TEST(test_dma_unaligned_oversized) } END_TEST +/* Single device: write data goes out in chunks of up to 255 bytes, the + * GenFIFO immediate length limit. */ +START_TEST(test_write_chunks_single) +{ + static uint8_t data[600]; + static const uint8_t tx[4] = { 0x02, 0x00, 0x00, 0x00 }; + + ck_assert_int_eq(qspi_transfer(&g_dev, tx, sizeof(tx), NULL, 0, 0, + data, sizeof(data)), 0); + + ck_assert_int_eq(g_tx_n, 3); + ck_assert_uint_eq(g_tx[0].len, 255); + ck_assert_uint_eq(g_tx[1].len, 255); + ck_assert_uint_eq(g_tx[2].len, 90); +} +END_TEST + +/* Dual parallel: bytes alternate between the two devices, so every chunk + * but the last must hold an even number of bytes or the next chunk resumes + * on the wrong device. */ +START_TEST(test_write_chunks_striped) +{ + static uint8_t data[600]; + static const uint8_t tx[4] = { 0x02, 0x00, 0x00, 0x00 }; + uint32_t total = 0; + int i; + + g_dev.bus = GQSPI_GEN_FIFO_BUS_BOTH; + g_dev.cs = GQSPI_GEN_FIFO_CS_BOTH; + g_dev.stripe = GQSPI_GEN_FIFO_STRIPE; + + ck_assert_int_eq(qspi_transfer(&g_dev, tx, sizeof(tx), NULL, 0, 0, + data, sizeof(data)), 0); + + ck_assert_int_eq(g_tx_n, 3); + for (i = 0; i < g_tx_n; i++) { + ck_assert_ptr_eq(g_tx[i].data, data + total); + ck_assert_uint_eq(g_tx[i].entry & GQSPI_GEN_FIFO_IMM_MASK, + g_tx[i].len); + ck_assert(g_tx[i].entry & GQSPI_GEN_FIFO_STRIPE); + if (i < g_tx_n - 1) + ck_assert_uint_eq(g_tx[i].len % 2, 0); + total += g_tx[i].len; + } + ck_assert_uint_eq(g_tx[0].len, 254); + ck_assert_uint_eq(total, sizeof(data)); +} +END_TEST + Suite *versal_qspi_dma_suite(void) { Suite *s = suite_create("versal-qspi-dma"); @@ -181,6 +252,8 @@ Suite *versal_qspi_dma_suite(void) tcase_add_test(tc, test_dma_aligned_large); tcase_add_test(tc, test_dma_unaligned_small); tcase_add_test(tc, test_dma_unaligned_oversized); + tcase_add_test(tc, test_write_chunks_single); + tcase_add_test(tc, test_write_chunks_striped); suite_add_tcase(s, tc); return s;