From 939dd57881dbabb3a2a2f730de30084d642898f0 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 | 2 + docs/API.md | 6 ++ 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 | 7 +- options.mk | 9 +- src/libwolfboot.c | 123 ++++++++++++++++++---- src/update_flash_hwswap.c | 4 + src/update_ram.c | 19 ++++ tools/unit-tests/Makefile | 29 +++++- tools/unit-tests/unit-update-flash.c | 6 ++ tools/unit-tests/unit-update-ram-enc.c | 130 ++++++++++++++++++++++++ tools/unit-tests/unit-update-ram.c | 82 +++++++++++++++ tools/unit-tests/unit-versal-qspi-dma.c | 73 +++++++++++++ 19 files changed, 564 insertions(+), 28 deletions(-) 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..be2bc564d2 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 @@ -682,6 +683,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..78331ec93d 100644 --- a/docs/API.md +++ b/docs/API.md @@ -27,12 +27,16 @@ Basic interaction from the application is provided via the following high-level `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()` @@ -53,6 +57,8 @@ single-block SWAP space. ### 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..2cb84a0329 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()` and write an update to the other one. 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..17bb35366e 100644 --- a/include/wolfboot/wolfboot.h +++ b/include/wolfboot/wolfboot.h @@ -790,6 +790,7 @@ extern "C" { void wolfBoot_update_trigger(void); 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 +823,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 +909,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/libwolfboot.c b/src/libwolfboot.c index 23c3ce03dd..262a438101 100644 --- a/src/libwolfboot.c +++ b/src/libwolfboot.c @@ -1811,29 +1811,47 @@ void RAMFUNCTION wolfBoot_update_trigger(void) #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. + * + * @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 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 +2404,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 +2463,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 +2474,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 +2496,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 +2507,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 +2533,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 +2545,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 +2728,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 +2776,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 +2786,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 +2879,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 +3721,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 +3966,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 +3996,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 +4022,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 +4094,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 +4113,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..f32fe90dfa 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,12 @@ void RAMFUNCTION wolfBoot_start(void) #endif wolfBoot_printf("Firmware Valid\n"); +#if defined(WOLFBOOT_DUALBOOT) && defined(WOLFBOOT_FIXED_PARTITIONS) + ramboot_part = active; +#ifdef WOLFBOOT_DUALBOOT_ROLLBACK_UNCONFIRMED + wolfBoot_dualboot_erase_rejected(active); +#endif +#endif /* First time we boot this update, set to TESTING to await * confirmation from the system diff --git a/tools/unit-tests/Makefile b/tools/unit-tests/Makefile index 9a2ee29cd2..0c8493a937 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-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 \ @@ -1409,6 +1416,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. @@ -1502,6 +1523,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 +1853,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 +1895,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.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..e2867657bb 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,75 @@ 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 START_TEST (test_emergency_rollback_failure_due_to_bad_update) { uint8_t testing_flags[5] = { IMG_STATE_TESTING, 'B', 'O', 'O', 'T' }; @@ -700,6 +777,11 @@ 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(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;