From 116390eac59bbe3be692ca108f00d0e4ee6c2e2f Mon Sep 17 00:00:00 2001 From: Andrew Hutchings Date: Wed, 25 Nov 2026 15:30:50 +0000 Subject: [PATCH 1/4] STM32Sim: add STM32F417/F407 targets with RNG fault injection Adds the F4 crypto block to STM32Sim so wolfSSL's F4 hardware crypto and STM32 RNG seed code can be tested in CI, prompted by a wolfSSL wc_GenerateSeed() that hung forever when the F4 RNG raised an error mid-request (reproduced on an STM32F4DISCOVERY first). Simulator: - stm32f417 chip (CRYP, HASH, RNG, USART1/2/3, RCC) and stm32f407 (no CRYP/HASH), with the RM0090 memory map. - CRYP v1: DES/TDES ECB/CBC; an F4 variant that drops the GCM/CCM mode bits as F405/F415/F417 silicon does; the IV registers track the chaining value, as wolfSSL's HAL_V2 DES path reads them back. - HASH v1: an F4 layout with SHA-1/MD5 only (ALGO bit 18 reserved, no extended HR window). - USART: the F1/F2/F4 register layout. RCC: F4 ready bits. - RNG: --rng-fault seed|clock:[:sticky] injects a seed or clock error after a number of RNG_DR reads, with the RM0090 recovery rules (seed error clears on SEIS clear + RNGEN cycle; clock error clears after a short glitch; sticky never clears). Works on every chip. - A run that hits --timeout logs the PC it stopped at. Firmware and CI: - firmware/rng-fault-f4: wc_GenerateSeed() fault test for the StdPeriph and WOLFSSL_STM32_RNG_NOLIB arms. Builds for stm32-sim or for a real STM32F4DISCOVERY, where it stops the RNG kernel clock from SysTick (board-run.sh flashes and reads it back over OpenOCD). ST's StdPeriph library is not vendored; a small shim stands in. - firmware/wolfcrypt-test-f417: the wolfCrypt test through the STM32CubeF4 HAL (CRYP for DES/TDES and AES ECB/CBC/CTR, HASH for SHA-1/MD5, RNG), including the software GCM fallback and DES ECB. - scripts/run-wolfcrypt-f417.sh, scripts/run-rng-fault-f417.sh, the Docker image gains cmsis-device-f4 and stm32f4xx-hal-driver, and a new stm32-wolfcrypt-test-f417 workflow runs both. The workflow tests wolfSSL master, so it needs the wolfSSL fixes for the StdPeriph RNG hang, the NOLIB clock-error handling and the STM32 DES ECB build merged first. --- .../workflows/stm32-wolfcrypt-test-f417.yml | 48 +++ README.md | 3 + STM32Sim/Dockerfile.wolfcrypt | 37 +- STM32Sim/README.md | 60 +++- STM32Sim/firmware/rng-fault-f4/Makefile | 89 +++++ STM32Sim/firmware/rng-fault-f4/README.md | 70 ++++ STM32Sim/firmware/rng-fault-f4/board-run.sh | 33 ++ STM32Sim/firmware/rng-fault-f4/main.c | 309 ++++++++++++++++ .../firmware/rng-fault-f4/startup_stm32f4.c | 93 +++++ .../rng-fault-f4/stdperiph/stdperiph_shim.h | 49 +++ .../rng-fault-f4/stdperiph/stm32f4xx.h | 35 ++ .../firmware/rng-fault-f4/stdperiph_shim.c | 75 ++++ STM32Sim/firmware/rng-fault-f4/stm32f4.ld | 83 +++++ .../firmware/rng-fault-f4/user_settings.h | 71 ++++ .../wolfcrypt-test-f417/CMakeLists.txt | 108 ++++++ STM32Sim/firmware/wolfcrypt-test-f417/main.c | 164 +++++++++ .../wolfcrypt-test-f417/startup_stm32f417.c | 104 ++++++ .../firmware/wolfcrypt-test-f417/stm32f417.ld | 106 ++++++ .../wolfcrypt-test-f417/stm32f4xx_hal_conf.h | 121 +++++++ .../toolchain-arm-none-eabi.cmake | 35 ++ .../wolfcrypt-test-f417/user_settings.h | 86 +++++ STM32Sim/scripts/run-rng-fault-f417.sh | 105 ++++++ STM32Sim/scripts/run-wolfcrypt-f417.sh | 86 +++++ STM32Sim/stm32-sim/Cargo.toml | 1 + STM32Sim/stm32-sim/chips/src/lib.rs | 57 ++- STM32Sim/stm32-sim/chips/src/stm32f417.rs | 119 +++++++ STM32Sim/stm32-sim/chips/src/stm32h753.rs | 6 +- STM32Sim/stm32-sim/chips/src/stm32mp135.rs | 6 +- STM32Sim/stm32-sim/chips/src/stm32u575.rs | 10 +- STM32Sim/stm32-sim/core/src/runner.rs | 4 + STM32Sim/stm32-sim/peripherals/Cargo.toml | 1 + .../stm32-sim/peripherals/src/cryp/mod.rs | 98 +++++- STM32Sim/stm32-sim/peripherals/src/cryp/v1.rs | 190 +++++++++- STM32Sim/stm32-sim/peripherals/src/hash/v1.rs | 45 ++- STM32Sim/stm32-sim/peripherals/src/lib.rs | 4 +- STM32Sim/stm32-sim/peripherals/src/rcc.rs | 12 + STM32Sim/stm32-sim/peripherals/src/rng.rs | 330 +++++++++++++++++- STM32Sim/stm32-sim/peripherals/src/usart.rs | 106 ++++-- STM32Sim/stm32-sim/runner-bin/src/main.rs | 18 +- 39 files changed, 2883 insertions(+), 94 deletions(-) create mode 100644 .github/workflows/stm32-wolfcrypt-test-f417.yml create mode 100644 STM32Sim/firmware/rng-fault-f4/Makefile create mode 100644 STM32Sim/firmware/rng-fault-f4/README.md create mode 100755 STM32Sim/firmware/rng-fault-f4/board-run.sh create mode 100644 STM32Sim/firmware/rng-fault-f4/main.c create mode 100644 STM32Sim/firmware/rng-fault-f4/startup_stm32f4.c create mode 100644 STM32Sim/firmware/rng-fault-f4/stdperiph/stdperiph_shim.h create mode 100644 STM32Sim/firmware/rng-fault-f4/stdperiph/stm32f4xx.h create mode 100644 STM32Sim/firmware/rng-fault-f4/stdperiph_shim.c create mode 100644 STM32Sim/firmware/rng-fault-f4/stm32f4.ld create mode 100644 STM32Sim/firmware/rng-fault-f4/user_settings.h create mode 100644 STM32Sim/firmware/wolfcrypt-test-f417/CMakeLists.txt create mode 100644 STM32Sim/firmware/wolfcrypt-test-f417/main.c create mode 100644 STM32Sim/firmware/wolfcrypt-test-f417/startup_stm32f417.c create mode 100644 STM32Sim/firmware/wolfcrypt-test-f417/stm32f417.ld create mode 100644 STM32Sim/firmware/wolfcrypt-test-f417/stm32f4xx_hal_conf.h create mode 100644 STM32Sim/firmware/wolfcrypt-test-f417/toolchain-arm-none-eabi.cmake create mode 100644 STM32Sim/firmware/wolfcrypt-test-f417/user_settings.h create mode 100755 STM32Sim/scripts/run-rng-fault-f417.sh create mode 100755 STM32Sim/scripts/run-wolfcrypt-f417.sh create mode 100644 STM32Sim/stm32-sim/chips/src/stm32f417.rs diff --git a/.github/workflows/stm32-wolfcrypt-test-f417.yml b/.github/workflows/stm32-wolfcrypt-test-f417.yml new file mode 100644 index 0000000..71140e0 --- /dev/null +++ b/.github/workflows/stm32-wolfcrypt-test-f417.yml @@ -0,0 +1,48 @@ +name: STM32Sim wolfCrypt test (F417) + +on: + push: + branches: [main] + pull_request: + branches: ['**'] + workflow_dispatch: + +jobs: + wolfcrypt-test: + name: wolfCrypt + RNG fault tests on STM32Sim F417 + runs-on: ubuntu-24.04 + steps: + - name: Checkout simulator-stm32 + uses: actions/checkout@v4 + with: + path: simulator-stm32 + + - name: Checkout wolfSSL + uses: actions/checkout@v4 + with: + repository: wolfSSL/wolfssl + ref: master + path: wolfssl + + - name: Build stm32sim-wolfcrypt image + run: | + docker build \ + -t stm32sim-wolfcrypt:ci \ + -f simulator-stm32/STM32Sim/Dockerfile.wolfcrypt \ + simulator-stm32/STM32Sim + + # CRYP (DES/TDES, AES ECB/CBC/CTR), HASH (SHA-1/MD5) and RNG through + # the STM32CubeF4 HAL. + - name: Run wolfCrypt test on stm32-sim (F417) + run: | + docker run --rm \ + -v "${{ github.workspace }}/wolfssl:/opt/wolfssl:ro" \ + stm32sim-wolfcrypt:ci run-wolfcrypt-f417.sh + + # wc_GenerateSeed() must return, not hang, when the RNG raises a + # seed or clock error mid-request (StdPeriph and NOLIB arms). + - name: Run RNG fault test on stm32-sim (F417) + run: | + docker run --rm \ + -v "${{ github.workspace }}/wolfssl:/opt/wolfssl:ro" \ + stm32sim-wolfcrypt:ci run-rng-fault-f417.sh diff --git a/README.md b/README.md index 6f9ca94..af1fbdd 100644 --- a/README.md +++ b/README.md @@ -50,6 +50,9 @@ supported targets: - **STM32MP135** (Cortex-A7 with MMU, runs out of DDR with no internal flash; CRYP1/HASH1/RNG1/PKA modelled, including SHA3 and SHAKE on HASH1) +- **STM32F417 / F407** (Cortex-M4; F417 CRYP with DES/TDES and AES + ECB/CBC/CTR, HASH with SHA-1/MD5, RNG with seed/clock fault + injection) ## PIC32MZSim diff --git a/STM32Sim/Dockerfile.wolfcrypt b/STM32Sim/Dockerfile.wolfcrypt index 931a53b..e3e046b 100644 --- a/STM32Sim/Dockerfile.wolfcrypt +++ b/STM32Sim/Dockerfile.wolfcrypt @@ -9,20 +9,21 @@ # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. -# Builds the wolfCrypt-on-STM32 firmwares (H753, U585, MP135) that -# today run under Renode CI, then runs them through stm32-sim -# instead. The wolfSSL source tree is expected to be mounted at -# /opt/wolfssl at runtime (the GitHub workflow does +# Builds the wolfCrypt-on-STM32 firmwares (H753, U585, MP135, F417) and +# runs them through stm32-sim. The wolfSSL source tree is expected to be +# mounted at /opt/wolfssl at runtime (the GitHub workflow does # `docker run -v $(pwd):/opt/wolfssl ...`). Default CMD runs the H7 -# firmware; override with `run-wolfcrypt-u5.sh` or -# `run-wolfcrypt-mp135.sh` for the other targets. +# firmware; override with `run-wolfcrypt-u5.sh`, `run-wolfcrypt-mp135.sh`, +# `run-wolfcrypt-f417.sh` or `run-rng-fault-f417.sh` for the others. # Image contents: # - arm-none-eabi-gcc cross toolchain # - CMSIS_5, cmsis-device-h7, STM32CubeH7 v1.11.2 (vendored under /opt) # - cmsis-device-u5, STM32CubeU5 (vendored under /opt) # - STM32CubeMP13 (vendored under /opt for the MP135 build) +# - cmsis-device-f4, stm32f4xx-hal-driver (vendored under /opt for F417) # - stm32-sim runner binary (built from this same repo) -# - run-wolfcrypt-{h7,u5,mp135}.sh entrypoints +# - run-wolfcrypt-{h7,u5,mp135,f417}.sh and run-rng-fault-f417.sh +# entrypoints # ============================================================================= # Stage 1: build stm32-sim (Rust) @@ -59,6 +60,12 @@ RUN git clone --depth 1 \ && git clone --depth 1 \ https://github.com/STMicroelectronics/cmsis-device-u5.git \ /opt/cmsis-device-u5 \ + && git clone --depth 1 \ + https://github.com/STMicroelectronics/cmsis-device-f4.git \ + /opt/cmsis-device-f4 \ + && git clone --depth 1 \ + https://github.com/STMicroelectronics/stm32f4xx-hal-driver.git \ + /opt/stm32f4xx-hal-driver \ && git clone --depth 1 \ https://github.com/ARM-software/CMSIS_5.git \ /opt/CMSIS_5 \ @@ -87,7 +94,8 @@ RUN git clone --depth 1 \ && cd /opt/STM32CubeMP13 \ && git submodule update --init --recursive --depth 1)) \ && find /opt/STM32CubeH7 /opt/STM32CubeU5 /opt/STM32CubeMP13 -name '.git' -prune -exec rm -rf {} + \ - && rm -rf /opt/cmsis-device-h7/.git /opt/cmsis-device-u5/.git /opt/CMSIS_5/.git + && rm -rf /opt/cmsis-device-h7/.git /opt/cmsis-device-u5/.git /opt/CMSIS_5/.git \ + /opt/cmsis-device-f4/.git /opt/stm32f4xx-hal-driver/.git COPY --from=sim-builder /app/stm32-sim/target/release/stm32-sim /usr/local/bin/stm32-sim @@ -99,17 +107,24 @@ COPY --from=sim-builder /app/stm32-sim/target/release/stm32-sim /usr/local/bin/s COPY firmware/wolfcrypt-test-h7/ /opt/firmware-h7/ COPY firmware/wolfcrypt-test-u5/ /opt/firmware-u5/ COPY firmware/wolfcrypt-test-mp135/ /opt/firmware-mp135/ +COPY firmware/wolfcrypt-test-f417/ /opt/firmware-f417/ +COPY firmware/rng-fault-f4/ /opt/firmware-rng-fault-f4/ COPY scripts/run-wolfcrypt-h7.sh /usr/local/bin/run-wolfcrypt-h7.sh COPY scripts/run-wolfcrypt-u5.sh /usr/local/bin/run-wolfcrypt-u5.sh COPY scripts/run-wolfcrypt-mp135.sh /usr/local/bin/run-wolfcrypt-mp135.sh +COPY scripts/run-wolfcrypt-f417.sh /usr/local/bin/run-wolfcrypt-f417.sh +COPY scripts/run-rng-fault-f417.sh /usr/local/bin/run-rng-fault-f417.sh RUN chmod +x /usr/local/bin/run-wolfcrypt-h7.sh \ /usr/local/bin/run-wolfcrypt-u5.sh \ - /usr/local/bin/run-wolfcrypt-mp135.sh + /usr/local/bin/run-wolfcrypt-mp135.sh \ + /usr/local/bin/run-wolfcrypt-f417.sh \ + /usr/local/bin/run-rng-fault-f417.sh ENV WOLFSSL_ROOT=/opt/wolfssl # Default entrypoint runs the H7 wolfCrypt test. Override by passing -# `run-wolfcrypt-u5.sh` (U585) or `run-wolfcrypt-mp135.sh` (MP135) as -# the command for the other targets. +# `run-wolfcrypt-u5.sh` (U585), `run-wolfcrypt-mp135.sh` (MP135), +# `run-wolfcrypt-f417.sh` (F417) or `run-rng-fault-f417.sh` (F4 RNG fault +# regression) as the command for the other targets. CMD ["run-wolfcrypt-h7.sh"] diff --git a/STM32Sim/README.md b/STM32Sim/README.md index 7d22653..01f6fd2 100644 --- a/STM32Sim/README.md +++ b/STM32Sim/README.md @@ -35,8 +35,9 @@ Cargo workspace under [`stm32-sim/`](stm32-sim): stm32-sim/ core/ CPU + MMIO bus + ELF loader + Runner peripherals/ USART, RCC, RNG, CRYP, HASH, PKA - chips/ STM32H753 / STM32U575 / STM32U585 / STM32MP135 chip - configurations (memory map + peripheral wiring) + chips/ STM32F407 / STM32F417 / STM32H753 / STM32U575 / + STM32U585 / STM32MP135 chip configurations (memory + map + peripheral wiring) runner-bin/ `stm32-sim` CLI binary ``` @@ -52,19 +53,25 @@ even though three chips might present three different DIN/HR layouts. ## Status **STM32H753** (Cortex-M7, HAL v1, no PKA), **STM32U575/U585** -(Cortex-M33, HAL v2, PKA v2), and **STM32MP135** (Cortex-A7, -HAL v2 with the H7-style CRYP block, PKA v2) chip targets all boot, -run firmware, and drive their on-chip cryptographic peripherals end- -to-end: - -| Peripheral | H7 (v1) | U5 (v2) | MP135 | -|------------|----------------------------------|--------------------|---------------------------------------| -| USART | OK | OK | OK (UART4) | -| RCC | stub | stub | stub | -| RNG | OK | OK | OK (RNG1) | -| CRYP/AES | ECB/CBC/CTR/GCM (HAL-driven) | ECB/CBC/CTR/GCM | ECB/CBC/CTR/GCM (CRYP1, aliased CRYP) | -| HASH | SHA-1/224/256, MD5 | SHA-1/224/256, MD5 | SHA-1/224/256, MD5, SHA-384/512, SHA3-224/256/384/512, SHAKE-128/256 (HASH1) | -| PKA | n/a | ECC mul (P-256/P-384), RSA modexp, mod arithmetic | same as U5 | +(Cortex-M33, HAL v2, PKA v2), **STM32MP135** (Cortex-A7, HAL v2 with +the H7-style CRYP block, PKA v2) and **STM32F417** (Cortex-M4, the F4 +CRYP/HASH/RNG block) chip targets all boot, run firmware, and drive +their on-chip cryptographic peripherals end-to-end. **STM32F407** is +the F417 without CRYP and HASH (the STM32F4DISCOVERY part). + +| Peripheral | H7 (v1) | U5 (v2) | MP135 | F417 | +|------------|----------------------------------|--------------------|---------------------------------------|-------------------------------| +| USART | OK | OK | OK (UART4) | OK (USART1/2/3, F4 layout) | +| RCC | stub | stub | stub | stub | +| RNG | OK | OK | OK (RNG1) | OK | +| CRYP/AES | ECB/CBC/CTR/GCM (HAL-driven) | ECB/CBC/CTR/GCM | ECB/CBC/CTR/GCM (CRYP1, aliased CRYP) | DES/TDES ECB/CBC, AES ECB/CBC/CTR (no GCM/CCM on this part) | +| HASH | SHA-1/224/256, MD5 | SHA-1/224/256, MD5 | SHA-1/224/256, MD5, SHA-384/512, SHA3-224/256/384/512, SHAKE-128/256 (HASH1) | SHA-1, MD5 | +| PKA | n/a | ECC mul (P-256/P-384), RSA modexp, mod arithmetic | same as U5 | n/a | + +The F417 CRYP and HASH reject what the silicon lacks the same way the +silicon does: the GCM/CCM mode bits and the HASH SHA-224/256 ALGO bit +are reserved and dropped, so firmware that tries to use them gets the +wrong answer rather than a silently working model. The MP135 is bare-metal Cortex-A7 with no internal flash. The firmware links at the DDR base (0xC0000000); the simulator maps DDR as plain @@ -115,6 +122,29 @@ make -C firmware/smoke-test-mp135 Expected output ends with `=== smoke test passed ===` and the binary exits 0 when the firmware sets `test_result = 0` and `test_complete = 1`. +A run that hits `--timeout` exits 3 and logs the PC the core was at, so +a hung firmware says where it hung. + +### RNG fault injection + +`--rng-fault :[:sticky]` makes the chip's RNG raise +an error after `` RNG_DR reads, following the F2/F4 reference +manual error management (RM0033 / RM0090): + +- `seed`: SECS and SEIS latch and DRDY stays low until the firmware + clears SEIS and cycles RNGEN. +- `clock`: CECS and CEIS latch and DRDY stays low until the kernel clock + "recovers" a few dozen RNG_SR polls later; CEIS stays set until + cleared. +- `:sticky`: the error never clears (a dead entropy source, a clock + that never comes back). + +[`firmware/rng-fault-f4/`](firmware/rng-fault-f4) uses this to check +that wolfSSL's `wc_GenerateSeed()` returns rather than hangs when the +F4 RNG fails mid-request, for both the Standard Peripheral Library and +`WOLFSSL_STM32_RNG_NOLIB` arms (`scripts/run-rng-fault-f417.sh`). The +same firmware also builds for a real STM32F4DISCOVERY, where it stops +the RNG kernel clock itself; see that directory's README. ## Tests diff --git a/STM32Sim/firmware/rng-fault-f4/Makefile b/STM32Sim/firmware/rng-fault-f4/Makefile new file mode 100644 index 0000000..4c3839a --- /dev/null +++ b/STM32Sim/firmware/rng-fault-f4/Makefile @@ -0,0 +1,89 @@ +# STM32F4 RNG fault test for wolfSSL's wc_GenerateSeed(). +# +# make [TARGET=sim|board] [ARM=stdperiph|nolib] +# +# TARGET=sim (default) STM32F417 under stm32-sim; the RNG fault comes from +# the simulator's --rng-fault option. +# TARGET=board STM32F407 (STM32F4DISCOVERY) silicon; the firmware stops the +# RNG kernel clock itself mid-fill. `make TARGET=board flash` +# programs it with OpenOCD. +# ARM=stdperiph (default) selects the Standard Peripheral Library arm of +# wc_GenerateSeed(); ARM=nolib selects WOLFSSL_STM32_RNG_NOLIB. + +WOLFSSL_ROOT ?= /opt/wolfssl +CMSIS_CORE ?= /opt/CMSIS_5/CMSIS/Core/Include +CMSIS_DEVICE ?= /opt/cmsis-device-f4/Include +TARGET ?= sim +ARM ?= stdperiph + +CC = arm-none-eabi-gcc + +ifeq ($(TARGET),board) +DEVICE ?= STM32F407xx +DEFS += -DRNG_FAULT_BOARD +else ifeq ($(TARGET),sim) +DEVICE ?= STM32F417xx +else +$(error TARGET must be sim or board) +endif + +ifeq ($(ARM),nolib) +DEFS += -DRNG_ARM_NOLIB +else ifneq ($(ARM),stdperiph) +$(error ARM must be stdperiph or nolib) +endif + +# TARGET=board only: GLITCH_MS= restores the RNG clock n ms after +# removing it (a transient clock glitch rather than a dead clock). +ifneq ($(GLITCH_MS),) +DEFS += -DRNG_FAULT_GLITCH_MS=$(GLITCH_MS) +SUFFIX = -glitch$(GLITCH_MS) +endif + +BUILD = build/$(ARM)-$(TARGET)$(SUFFIX) +ELF = rng-fault-$(ARM)-$(TARGET)$(SUFFIX).elf + +WOLFCRYPT_SRCS = \ + $(WOLFSSL_ROOT)/wolfcrypt/src/random.c \ + $(WOLFSSL_ROOT)/wolfcrypt/src/sha256.c \ + $(WOLFSSL_ROOT)/wolfcrypt/src/memory.c \ + $(WOLFSSL_ROOT)/wolfcrypt/src/wc_port.c \ + $(WOLFSSL_ROOT)/wolfcrypt/src/logging.c \ + $(WOLFSSL_ROOT)/wolfcrypt/src/error.c + +LOCAL_SRCS = main.c startup_stm32f4.c stdperiph_shim.c +HEADERS = user_settings.h stdperiph/stm32f4xx.h stdperiph/stdperiph_shim.h + +OBJS = $(addprefix $(BUILD)/,$(LOCAL_SRCS:.c=.o)) \ + $(addprefix $(BUILD)/wolfcrypt/,$(notdir $(WOLFCRYPT_SRCS:.c=.o))) + +ARCH = -mcpu=cortex-m4 -mthumb -mfloat-abi=soft +# stdperiph/ comes before the CMSIS device directory so its StdPeriph-style +# stm32f4xx.h wrapper shadows the CMSIS one (and #include_next's it). +CPPFLAGS = -DWOLFSSL_USER_SETTINGS -D$(DEVICE) $(DEFS) \ + -I. -Istdperiph -I$(CMSIS_DEVICE) -I$(CMSIS_CORE) -I$(WOLFSSL_ROOT) +CFLAGS = $(ARCH) -Os -g -ffunction-sections -fdata-sections -Wall +LDFLAGS = $(ARCH) -Tstm32f4.ld -nostartfiles -Wl,--gc-sections \ + -specs=nano.specs -specs=nosys.specs -Wl,-Map=$(BUILD)/rng-fault.map + +all: $(ELF) + +$(ELF): $(OBJS) + $(CC) $(LDFLAGS) -o $@ $^ + +$(BUILD)/%.o: %.c $(HEADERS) + @mkdir -p $(dir $@) + $(CC) $(CPPFLAGS) $(CFLAGS) -c -o $@ $< + +$(BUILD)/wolfcrypt/%.o: $(WOLFSSL_ROOT)/wolfcrypt/src/%.c $(HEADERS) + @mkdir -p $(dir $@) + $(CC) $(CPPFLAGS) $(CFLAGS) -c -o $@ $< + +flash: $(ELF) + openocd -f interface/stlink.cfg -f target/stm32f4x.cfg \ + -c "program $(ELF) verify reset exit" + +clean: + rm -rf build rng-fault-*.elf + +.PHONY: all flash clean diff --git a/STM32Sim/firmware/rng-fault-f4/README.md b/STM32Sim/firmware/rng-fault-f4/README.md new file mode 100644 index 0000000..7ab9071 --- /dev/null +++ b/STM32Sim/firmware/rng-fault-f4/README.md @@ -0,0 +1,70 @@ +# rng-fault-f4 + +STM32F4 hardware-RNG fault test for wolfSSL's `wc_GenerateSeed()`. + +The firmware pulls a short seed with the RNG healthy, then a long one while +the RNG fails part way through. A correct `wc_GenerateSeed()` returns from +the second call, with `0` if the RNG recovered or `RNG_FAILURE_E` (-199) if +it did not. The regression it guards against is the call never returning: +before the fix, the Standard Peripheral Library arm of the `STM32_RNG` seed +code polled DRDY with no bound, so a seed or clock error mid-request hung +it forever with the crypto hardware mutex held. + +Two `wc_GenerateSeed()` arms can be built: + +| `ARM=` | wolfSSL configuration | +|-------------|-----------------------| +| `stdperiph` | `WOLFSSL_STM32F4`, neither `WOLFSSL_STM32_CUBEMX` nor `WOLFSSL_STM32_BARE` (the Standard Peripheral Library arm) | +| `nolib` | `WOLFSSL_STM32_RNG_NOLIB` (direct register access) | + +ST's Standard Peripheral Library is not vendored. `stdperiph/` holds a +StdPeriph-style `stm32f4xx.h` wrapper and `stdperiph_shim.c` implements the +handful of RNG/RCC calls the seed code makes, with the same register-level +behaviour as the library's functions of the same names. + +## On stm32-sim (CI) + +```sh +make TARGET=sim ARM=stdperiph WOLFSSL_ROOT=/path/to/wolfssl +stm32-sim --chip stm32f417 --timeout 20 --rng-fault seed:200 \ + rng-fault-stdperiph-sim.elf +``` + +The simulator's `--rng-fault` option supplies the fault. +`scripts/run-rng-fault-f417.sh` builds both arms and runs every fault +scenario with its expected result; a hang fails with the PC it hung at. + +## On an STM32F4DISCOVERY (STM32F407) + +```sh +make TARGET=board ARM=stdperiph WOLFSSL_ROOT=/path/to/wolfssl +./board-run.sh rng-fault-stdperiph-board.elf 8 +``` + +`board-run.sh` programs the board with OpenOCD over the on-board ST-LINK, +lets it run, halts it and prints the test's state, the RNG and RCC +registers, and the function the PC is in. + +The board build stops the RNG kernel clock itself: SYSCLK stays on the +16 MHz HSI and the main PLL runs only to feed the 48 MHz PLL48CLK, so a +SysTick interrupt can switch the PLL off 3 ms into the long seed request +without stopping the core. The silicon reports a genuine clock error +(RNG_SR = 0x22, CECS | CEIS) and DRDY stops. `GLITCH_MS=` switches +the PLL back on n ms later instead, for a transient glitch. + +What to look for: + +| Variable | Meaning | +|-----------------|---------| +| `g_stage` | 2 = still inside the faulted `wc_GenerateSeed()`, 3 = it returned | +| `g_fault_ret` | its return value (stays 1 if it never returned) | +| `g_hung` | set by SysTick if it has not returned 5 s after the fault | +| `g_rng_sr_after_fault` | RNG_SR 100 ms after the fault | +| `g_return_tick` | SysTick ms at which it returned (fault at `g_fault_fired_tick`) | + +LEDs: green = sanity seed passed, orange = faulted call returned, +red = faulted call hung, blue = heartbeat. + +Make variables `CMSIS_CORE` and `CMSIS_DEVICE` point at the ARM CMSIS +core headers and ST's `cmsis-device-f4` headers (default: the `/opt` +layout of the Docker image). diff --git a/STM32Sim/firmware/rng-fault-f4/board-run.sh b/STM32Sim/firmware/rng-fault-f4/board-run.sh new file mode 100755 index 0000000..f7d7659 --- /dev/null +++ b/STM32Sim/firmware/rng-fault-f4/board-run.sh @@ -0,0 +1,33 @@ +#!/bin/sh +# Program an STM32F4DISCOVERY with a TARGET=board build of this firmware, +# let it run, then halt it and print the test's diagnostic variables, the +# PC (with the function it is in) and the RNG / RCC registers. +# +# ./board-run.sh rng-fault-stdperiph-board.elf [seconds] +set -eu + +ELF=${1:?usage: board-run.sh [seconds]} +SECS=${2:-8} + +sym() { + arm-none-eabi-nm "$ELF" | awk -v s="$1" '$3 == s { print "0x" $1 }' +} + +CMDS="program $ELF verify; reset run; sleep $((SECS * 1000)); halt;" +for v in g_stage g_sanity_ret g_fault_ret g_tick g_fault_tick \ + g_fault_fired_tick g_rng_sr_after_fault g_return_tick g_hung \ + test_complete test_result; do + a=$(sym "$v") + CMDS="$CMDS echo \"$v [read_memory $a 32 1]\";" +done +CMDS="$CMDS echo \"RNG_CR_SR [read_memory 0x50060800 32 2]\";" +CMDS="$CMDS echo \"RCC_CR [read_memory 0x40023800 32 1]\";" +CMDS="$CMDS echo \"PC [lindex [reg pc] 2]\"; shutdown" + +OUT=$(openocd -f interface/stlink.cfg -f target/stm32f4x.cfg -c "$CMDS" 2>&1) +echo "$OUT" | grep -v -E '^(Info|Open On-Chip|Licensed|For bug|\s+http|Warn : Unable to match)' || true + +PC=$(echo "$OUT" | awk '$1 == "PC" { print $2 }') +if [ -n "$PC" ]; then + echo "PC $PC is in: $(arm-none-eabi-addr2line -f -e "$ELF" "$PC" | head -1)" +fi diff --git a/STM32Sim/firmware/rng-fault-f4/main.c b/STM32Sim/firmware/rng-fault-f4/main.c new file mode 100644 index 0000000..caa95f3 --- /dev/null +++ b/STM32Sim/firmware/rng-fault-f4/main.c @@ -0,0 +1,309 @@ +/* main.c + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of STM32Sim. + * + * STM32Sim 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. + * + * STM32Sim 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 + */ + +/* STM32F4 hardware-RNG fault test for wolfSSL's wc_GenerateSeed(). + * + * 1. Sanity: pull a short seed with the RNG healthy; must return 0. + * 2. Fault: pull a long seed while the RNG fails part way through. + * + * A correct wc_GenerateSeed() returns from step 2, either with 0 (the + * RNG recovered) or RNG_FAILURE_E (it did not). The bug this guards + * against is the call never returning. + * + * How the RNG is made to fail depends on the build: + * + * RNG_FAULT_BOARD (real STM32F407/F417 silicon): SYSCLK stays on HSI + * and the main PLL runs only to feed PLL48CLK, the RNG kernel clock. + * A SysTick interrupt switches the PLL off a few milliseconds into + * step 2, so the RNG loses its clock mid-fill (a genuine clock error: + * DRDY stops, CECS/CEIS latch). Built with RNG_FAULT_GLITCH_MS= + * the PLL is switched back on n ms later instead, i.e. a transient + * clock glitch. The debugger reads the g_* variables back; the LEDs on + * PD12-PD15 show the same thing. + * + * Default (stm32-sim): the simulator's --rng-fault option latches the + * SECS or CECS condition after a set number of DR reads. + * + * test_result is 0 when step 1 passed and step 2 returned; the console + * line "RNG_FAULT ... fault=" carries the step 2 return code. */ + +#include +#include + +#include +#include +#include + +#include "stm32f4xx.h" + +#ifdef RNG_FAULT_BOARD + /* Long enough (tens of ms at 16 MHz) that the SysTick fault lands + * well inside the fill. */ + #define FAULT_BUF_SZ 32768 + #define FAULT_DELAY_MS 3 + #define HANG_MS 5000 +#else + #define FAULT_BUF_SZ 1024 +#endif +#define SANITY_SZ 64 + +#define STAGE_INIT 0 +#define STAGE_SANITY 1 +#define STAGE_FAULT 2 +#define STAGE_DONE 3 + +/* Polled by stm32-sim through the ELF symbol table. */ +volatile int test_result __attribute__((section(".data"))) = -1; +volatile int test_complete __attribute__((section(".data"))) = 0; + +/* Diagnostics, read back with the debugger on hardware. */ +volatile uint32_t g_stage = STAGE_INIT; +volatile int32_t g_sanity_ret = 1; +volatile int32_t g_fault_ret = 1; +volatile uint32_t g_tick; +volatile uint32_t g_fault_tick; +volatile uint32_t g_fault_fired_tick; +volatile uint32_t g_rng_sr_after_fault; +volatile uint32_t g_return_tick; +volatile uint32_t g_hung; + +static byte sanity_buf[SANITY_SZ]; +static byte fault_buf[FAULT_BUF_SZ]; + +/* ---- console (USART2, F4 register layout) ------------------------------ */ + +static void uart_init(void) +{ + RCC->APB1ENR |= RCC_APB1ENR_USART2EN; + USART2->BRR = 16000000U / 115200U; + USART2->CR1 = USART_CR1_UE | USART_CR1_TE; +} + +static void uart_putc(char c) +{ + while ((USART2->SR & USART_SR_TXE) == 0U) { + } + USART2->DR = (uint32_t)(unsigned char)c; +} + +static void uart_puts(const char* s) +{ + while (*s != '\0') { + if (*s == '\n') { + uart_putc('\r'); + } + uart_putc(*s++); + } +} + +static void uart_putd(int32_t v) +{ + char buf[12]; + int i = 0; + uint32_t u; + + if (v < 0) { + uart_putc('-'); + u = (uint32_t)0 - (uint32_t)v; + } + else { + u = (uint32_t)v; + } + do { + buf[i++] = (char)('0' + (u % 10U)); + u /= 10U; + } while (u != 0U); + while (i > 0) { + uart_putc(buf[--i]); + } +} + +/* ---- newlib hooks ------------------------------------------------------ */ + +extern char __heap_start__; +extern char __heap_end__; + +void* _sbrk(ptrdiff_t incr) +{ + static char* heap_ptr = NULL; + char* prev; + + if (heap_ptr == NULL) { + heap_ptr = &__heap_start__; + } + prev = heap_ptr; + if (heap_ptr + incr > &__heap_end__) { + return (void*)-1; + } + heap_ptr += incr; + return prev; +} + +/* ---- RNG kernel clock --------------------------------------------------- */ + +/* SYSCLK stays on HSI (16 MHz). Run the main PLL from HSI purely for the + * 48 MHz PLL48CLK: 16 MHz / M(16) * N(336) = 336 MHz VCO, / Q(7) = 48 MHz. + * PLLP is unused because SYSCLK does not come from the PLL, which is what + * lets the fault below stop the PLL without stopping the core. */ +static void pll48_start(void) +{ + uint32_t cfg = RCC->PLLCFGR; + + cfg &= ~(RCC_PLLCFGR_PLLM_Msk | RCC_PLLCFGR_PLLN_Msk | + RCC_PLLCFGR_PLLP_Msk | RCC_PLLCFGR_PLLSRC_Msk | + RCC_PLLCFGR_PLLQ_Msk); + cfg |= (16U << RCC_PLLCFGR_PLLM_Pos) | (336U << RCC_PLLCFGR_PLLN_Pos) | + (7U << RCC_PLLCFGR_PLLQ_Pos); + RCC->PLLCFGR = cfg; + RCC->CR |= RCC_CR_PLLON; + while ((RCC->CR & RCC_CR_PLLRDY) == 0U) { + } +} + +#ifdef RNG_FAULT_BOARD + +/* ---- STM32F4DISCOVERY LEDs ----------------------------------------------- */ + +#define LED_GREEN 12 /* sanity seed passed */ +#define LED_ORANGE 13 /* faulted seed call returned */ +#define LED_RED 14 /* faulted seed call hung */ +#define LED_BLUE 15 /* heartbeat */ + +static void leds_init(void) +{ + RCC->AHB1ENR |= RCC_AHB1ENR_GPIODEN; + (void)RCC->AHB1ENR; + GPIOD->MODER |= (1U << (LED_GREEN * 2)) | (1U << (LED_ORANGE * 2)) | + (1U << (LED_RED * 2)) | (1U << (LED_BLUE * 2)); +} + +static void led_on(int pin) +{ + GPIOD->BSRR = 1U << pin; +} + +static void led_toggle(int pin) +{ + GPIOD->ODR ^= 1U << pin; +} + +void SysTick_Handler(void) +{ + uint32_t t = ++g_tick; + + if (g_fault_tick != 0U && t == g_fault_tick) { + /* Take the RNG kernel clock away mid-fill. */ + RCC->CR &= ~RCC_CR_PLLON; + g_fault_fired_tick = t; + } +#ifdef RNG_FAULT_GLITCH_MS + if (g_fault_fired_tick != 0U && + t == g_fault_fired_tick + RNG_FAULT_GLITCH_MS) { + RCC->CR |= RCC_CR_PLLON; /* the clock comes back */ + } +#endif + if (g_fault_fired_tick != 0U && t == g_fault_fired_tick + 100U) { + g_rng_sr_after_fault = RNG->SR; + } + if (g_stage == STAGE_FAULT && g_fault_fired_tick != 0U && + (t - g_fault_fired_tick) > HANG_MS) { + g_hung = 1; + led_on(LED_RED); + } + if ((t % 250U) == 0U) { + led_toggle(LED_BLUE); + } +} + +#endif /* RNG_FAULT_BOARD */ + +int main(void) +{ + OS_Seed os; + int i; + int nonzero = 0; + + XMEMSET(&os, 0, sizeof(os)); + uart_init(); + pll48_start(); +#ifdef RNG_FAULT_BOARD + leds_init(); + (void)SysTick_Config(16000U); /* 1 kHz from the 16 MHz HSI */ +#endif + +#ifdef WOLFSSL_STM32_RNG_NOLIB + uart_puts("\n=== RNG fault test: WOLFSSL_STM32_RNG_NOLIB arm ===\n"); +#else + uart_puts("\n=== RNG fault test: StdPeriph arm ===\n"); +#endif + + g_stage = STAGE_SANITY; + g_sanity_ret = wc_GenerateSeed(&os, sanity_buf, sizeof(sanity_buf)); + for (i = 0; i < (int)sizeof(sanity_buf); i++) { + nonzero |= sanity_buf[i]; + } + if (g_sanity_ret == 0 && nonzero == 0) { + g_sanity_ret = -1; /* all-zero "seed": RNG not actually running */ + } +#ifdef RNG_FAULT_BOARD + if (g_sanity_ret == 0) { + led_on(LED_GREEN); + } +#endif + uart_puts("sanity seed ret="); + uart_putd(g_sanity_ret); + uart_puts("\n"); + + uart_puts("faulted seed: calling wc_GenerateSeed()\n"); + g_stage = STAGE_FAULT; +#ifdef RNG_FAULT_BOARD + g_fault_tick = g_tick + FAULT_DELAY_MS; +#endif + g_fault_ret = wc_GenerateSeed(&os, fault_buf, sizeof(fault_buf)); + g_stage = STAGE_DONE; +#ifdef RNG_FAULT_BOARD + g_return_tick = g_tick; + led_on(LED_ORANGE); +#endif + + uart_puts("RNG_FAULT sanity="); + uart_putd(g_sanity_ret); + uart_puts(" fault="); + uart_putd(g_fault_ret); + uart_puts("\n"); + + if (g_sanity_ret == 0 && + (g_fault_ret == 0 || g_fault_ret == RNG_FAILURE_E)) { + test_result = 0; + uart_puts("=== RNG fault test returned ===\n"); + } + else { + test_result = 1; + uart_puts("=== RNG fault test FAILED ===\n"); + } + /* Last: stm32-sim exits as soon as this goes nonzero. */ + test_complete = 1; + + for (;;) { + __asm__ volatile ("wfi"); + } + return 0; +} diff --git a/STM32Sim/firmware/rng-fault-f4/startup_stm32f4.c b/STM32Sim/firmware/rng-fault-f4/startup_stm32f4.c new file mode 100644 index 0000000..44ad94a --- /dev/null +++ b/STM32Sim/firmware/rng-fault-f4/startup_stm32f4.c @@ -0,0 +1,93 @@ +/* startup_stm32f4.c + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of STM32Sim. + * + * STM32Sim 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. + * + * STM32Sim 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 + */ + +/* Minimal Cortex-M4 startup for STM32F405/407/415/417: copies .data, + * zeroes .bss and calls main(). Only the core exception vectors are + * populated; nothing here enables a peripheral interrupt. */ + +#include + +extern int main(void); + +extern unsigned long _estack; +extern unsigned long __data_start__; +extern unsigned long __data_end__; +extern unsigned long __bss_start__; +extern unsigned long __bss_end__; +extern unsigned long _sidata; + +void Reset_Handler(void); +void Default_Handler(void); + +void Reset_Handler(void) +{ + unsigned long* src = &_sidata; + unsigned long* dst; + + for (dst = &__data_start__; dst < &__data_end__;) { + *dst++ = *src++; + } + for (dst = &__bss_start__; dst < &__bss_end__;) { + *dst++ = 0; + } + + (void)main(); + + for (;;) { + __asm__ volatile ("wfi"); + } +} + +void Default_Handler(void) +{ + for (;;) { + } +} + +void NMI_Handler(void) __attribute__((weak, alias("Default_Handler"))); +void HardFault_Handler(void) __attribute__((weak, alias("Default_Handler"))); +void MemManage_Handler(void) __attribute__((weak, alias("Default_Handler"))); +void BusFault_Handler(void) __attribute__((weak, alias("Default_Handler"))); +void UsageFault_Handler(void) __attribute__((weak, alias("Default_Handler"))); +void SVC_Handler(void) __attribute__((weak, alias("Default_Handler"))); +void DebugMon_Handler(void) __attribute__((weak, alias("Default_Handler"))); +void PendSV_Handler(void) __attribute__((weak, alias("Default_Handler"))); +void SysTick_Handler(void) __attribute__((weak, alias("Default_Handler"))); + +__attribute__((section(".isr_vector"), used)) +void (* const g_pfnVectors[])(void) = { + (void (*)(void))(&_estack), + Reset_Handler, + NMI_Handler, + HardFault_Handler, + MemManage_Handler, + BusFault_Handler, + UsageFault_Handler, + 0, + 0, + 0, + 0, + SVC_Handler, + DebugMon_Handler, + 0, + PendSV_Handler, + SysTick_Handler +}; diff --git a/STM32Sim/firmware/rng-fault-f4/stdperiph/stdperiph_shim.h b/STM32Sim/firmware/rng-fault-f4/stdperiph/stdperiph_shim.h new file mode 100644 index 0000000..debb933 --- /dev/null +++ b/STM32Sim/firmware/rng-fault-f4/stdperiph/stdperiph_shim.h @@ -0,0 +1,49 @@ +/* stdperiph_shim.h + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of STM32Sim. + * + * STM32Sim 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. + * + * STM32Sim 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 + */ + +/* Minimal stand-in for the STM32F4xx Standard Peripheral Library RNG and + * RCC calls that wolfSSL's STM32_RNG StdPeriph wc_GenerateSeed() arm uses. + * ST's StdPeriph library is not vendored here, so these mirror the + * register-level behaviour of its stm32f4xx_rng.c / stm32f4xx_rcc.c + * functions of the same names. */ + +#ifndef STDPERIPH_SHIM_H +#define STDPERIPH_SHIM_H + +#include + +#define RCC_AHB2Periph_RNG ((uint32_t)0x00000040) + +#define RNG_FLAG_DRDY ((uint8_t)0x0001) +#define RNG_FLAG_CECS ((uint8_t)0x0002) +#define RNG_FLAG_SECS ((uint8_t)0x0004) + +void RCC_AHB2PeriphClockCmd(uint32_t RCC_AHB2Periph, + FunctionalState NewState); +void RCC_AHB2PeriphResetCmd(uint32_t RCC_AHB2Periph, + FunctionalState NewState); +void RNG_DeInit(void); +void RNG_Cmd(FunctionalState NewState); +uint32_t RNG_GetRandomNumber(void); +FlagStatus RNG_GetFlagStatus(uint8_t RNG_FLAG); +void RNG_ClearFlag(uint8_t RNG_FLAG); + +#endif /* STDPERIPH_SHIM_H */ diff --git a/STM32Sim/firmware/rng-fault-f4/stdperiph/stm32f4xx.h b/STM32Sim/firmware/rng-fault-f4/stdperiph/stm32f4xx.h new file mode 100644 index 0000000..7bfbdf4 --- /dev/null +++ b/STM32Sim/firmware/rng-fault-f4/stdperiph/stm32f4xx.h @@ -0,0 +1,35 @@ +/* stm32f4xx.h + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of STM32Sim. + * + * STM32Sim 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. + * + * STM32Sim 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 + */ + +/* StdPeriph-style umbrella header. wolfSSL's settings.h includes + * "stm32f4xx.h" for a WOLFSSL_STM32F4 build with neither + * WOLFSSL_STM32_CUBEMX nor WOLFSSL_STM32_BARE, expecting the StdPeriph + * library's device header (which pulls in the peripheral driver headers). + * This wrapper sits ahead of ST's CMSIS device include directory, pulls in + * the real CMSIS header and then the StdPeriph shim prototypes. */ + +#ifndef RNG_FAULT_STM32F4XX_H +#define RNG_FAULT_STM32F4XX_H + +#include_next +#include "stdperiph_shim.h" + +#endif /* RNG_FAULT_STM32F4XX_H */ diff --git a/STM32Sim/firmware/rng-fault-f4/stdperiph_shim.c b/STM32Sim/firmware/rng-fault-f4/stdperiph_shim.c new file mode 100644 index 0000000..6241a7f --- /dev/null +++ b/STM32Sim/firmware/rng-fault-f4/stdperiph_shim.c @@ -0,0 +1,75 @@ +/* stdperiph_shim.c + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of STM32Sim. + * + * STM32Sim 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. + * + * STM32Sim is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + +#include "stm32f4xx.h" + +void RCC_AHB2PeriphClockCmd(uint32_t RCC_AHB2Periph, FunctionalState NewState) +{ + if (NewState != DISABLE) { + RCC->AHB2ENR |= RCC_AHB2Periph; + } + else { + RCC->AHB2ENR &= ~RCC_AHB2Periph; + } +} + +void RCC_AHB2PeriphResetCmd(uint32_t RCC_AHB2Periph, FunctionalState NewState) +{ + if (NewState != DISABLE) { + RCC->AHB2RSTR |= RCC_AHB2Periph; + } + else { + RCC->AHB2RSTR &= ~RCC_AHB2Periph; + } +} + +void RNG_DeInit(void) +{ + RCC_AHB2PeriphResetCmd(RCC_AHB2Periph_RNG, ENABLE); + RCC_AHB2PeriphResetCmd(RCC_AHB2Periph_RNG, DISABLE); +} + +void RNG_Cmd(FunctionalState NewState) +{ + if (NewState != DISABLE) { + RNG->CR |= RNG_CR_RNGEN; + } + else { + RNG->CR &= ~RNG_CR_RNGEN; + } +} + +uint32_t RNG_GetRandomNumber(void) +{ + return RNG->DR; +} + +FlagStatus RNG_GetFlagStatus(uint8_t RNG_FLAG) +{ + return ((RNG->SR & RNG_FLAG) != 0U) ? SET : RESET; +} + +/* SEIS/CEIS sit four bits above SECS/CECS and are cleared by writing 0; + * the status bits below them are read-only. */ +void RNG_ClearFlag(uint8_t RNG_FLAG) +{ + RNG->SR = ~(uint32_t)(((uint32_t)RNG_FLAG) << 4); +} diff --git a/STM32Sim/firmware/rng-fault-f4/stm32f4.ld b/STM32Sim/firmware/rng-fault-f4/stm32f4.ld new file mode 100644 index 0000000..ff921f9 --- /dev/null +++ b/STM32Sim/firmware/rng-fault-f4/stm32f4.ld @@ -0,0 +1,83 @@ +/* STM32F405/407/415/417 memory map: 1 MiB flash, 128 KiB contiguous + * SRAM1+SRAM2 at 0x20000000. Matches stm32-sim-chips/src/stm32f417.rs. + * The 64 KiB CCM RAM at 0x10000000 is not used. */ +MEMORY +{ + FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 1024K + RAM (xrw) : ORIGIN = 0x20000000, LENGTH = 128K +} + +_estack = ORIGIN(RAM) + LENGTH(RAM); +_Min_Heap_Size = 16K; +_Min_Stack_Size = 8K; + +ENTRY(Reset_Handler) + +SECTIONS +{ + .isr_vector : + { + . = ALIGN(4); + KEEP(*(.isr_vector)) + . = ALIGN(4); + } > FLASH + + .text : + { + . = ALIGN(4); + *(.text*) + *(.rodata*) + *(.glue_7) + *(.glue_7t) + *(.eh_frame) + . = ALIGN(4); + _etext = .; + } > FLASH + + .ARM.extab : + { + *(.ARM.extab* .gnu.linkonce.armextab.*) + } > FLASH + + .ARM.exidx : + { + __exidx_start = .; + *(.ARM.exidx*) + __exidx_end = .; + } > FLASH + + _sidata = LOADADDR(.data); + + .data : + { + . = ALIGN(4); + __data_start__ = .; + *(.data*) + . = ALIGN(4); + __data_end__ = .; + } > RAM AT> FLASH + + .bss : + { + . = ALIGN(4); + __bss_start__ = .; + *(.bss*) + *(COMMON) + . = ALIGN(4); + __bss_end__ = .; + } > RAM + + .heap_stack (NOLOAD): + { + . = ALIGN(8); + PROVIDE(__heap_start__ = .); + . = . + _Min_Heap_Size; + PROVIDE(__heap_end__ = .); + PROVIDE(end = __heap_end__); + . = ALIGN(8); + . = . + _Min_Stack_Size; + } > RAM +} + +PROVIDE(_init = 0); +PROVIDE(_fini = 0); diff --git a/STM32Sim/firmware/rng-fault-f4/user_settings.h b/STM32Sim/firmware/rng-fault-f4/user_settings.h new file mode 100644 index 0000000..7c8b12d --- /dev/null +++ b/STM32Sim/firmware/rng-fault-f4/user_settings.h @@ -0,0 +1,71 @@ +/* user_settings.h + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of STM32Sim. + * + * STM32Sim 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. + * + * STM32Sim 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 + */ + +/* Minimal wolfCrypt configuration for the STM32F4 RNG fault test. + * + * Default: WOLFSSL_STM32F4 with neither WOLFSSL_STM32_CUBEMX nor + * WOLFSSL_STM32_BARE, which selects the Standard Peripheral Library arm of + * wc_GenerateSeed() in wolfcrypt/src/random.c. + * + * Build with -DRNG_ARM_NOLIB to select the direct-register + * WOLFSSL_STM32_RNG_NOLIB arm instead (the comparison case). */ + +#ifndef USER_SETTINGS_RNG_FAULT_F4_H +#define USER_SETTINGS_RNG_FAULT_F4_H + +#define WOLFSSL_STM32F4 +#define WOLFSSL_ARM_CORTEX_M + +#ifdef RNG_ARM_NOLIB + #define WOLFSSL_STM32_RNG_NOLIB +#endif + +/* This firmware only exercises the RNG. */ +#define NO_STM32_HASH +#define NO_STM32_CRYPTO + +#define WOLFCRYPT_ONLY +#define SINGLE_THREADED +#define NO_FILESYSTEM +#define NO_WRITEV +#define WOLFSSL_NO_SOCK +#define NO_MAIN_DRIVER + +#define HAVE_HASHDRBG +#define NO_RSA +#define NO_DH +#define NO_DSA +#define NO_DES3 +#define NO_MD5 +#define NO_SHA +#define NO_AES +#define NO_HMAC +#define NO_PWDBASED +#define NO_ASN +#define NO_CERTS +#define NO_CODING +#define NO_SIG_WRAPPER +#define NO_OLD_TLS +#define NO_PSK +#define NO_BIG_INT +#define WOLFSSL_NO_ASM + +#endif /* USER_SETTINGS_RNG_FAULT_F4_H */ diff --git a/STM32Sim/firmware/wolfcrypt-test-f417/CMakeLists.txt b/STM32Sim/firmware/wolfcrypt-test-f417/CMakeLists.txt new file mode 100644 index 0000000..040ff43 --- /dev/null +++ b/STM32Sim/firmware/wolfcrypt-test-f417/CMakeLists.txt @@ -0,0 +1,108 @@ +cmake_minimum_required(VERSION 3.18) +project(wolfcrypt_stm32f417 LANGUAGES C ASM) + +# WOLFSSL_ROOT is the path to a wolfSSL source tree. The Docker entrypoint +# mounts the user's wolfSSL into /opt/wolfssl by default. +set(WOLFSSL_ROOT "/opt/wolfssl" CACHE PATH "wolfSSL source") + +# ST/ARM vendor trees; see toolchain-arm-none-eabi.cmake. +if(NOT DEFINED STM32SIM_VENDOR_DIR) + if(DEFINED ENV{STM32SIM_VENDOR_DIR}) + set(STM32SIM_VENDOR_DIR "$ENV{STM32SIM_VENDOR_DIR}") + else() + set(STM32SIM_VENDOR_DIR "/opt") + endif() +endif() +set(CMSIS_CORE_INC ${STM32SIM_VENDOR_DIR}/CMSIS_5/CMSIS/Core/Include) +set(CMSIS_DEVICE_INC ${STM32SIM_VENDOR_DIR}/cmsis-device-f4/Include) +set(HAL_DIR ${STM32SIM_VENDOR_DIR}/stm32f4xx-hal-driver) + +set(CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY) +enable_language(ASM) + +# Order matters: this directory first (user_settings.h and +# stm32f4xx_hal_conf.h), then CMSIS core, device CMSIS, and the HAL. +include_directories(BEFORE + ${CMAKE_SOURCE_DIR} + ${CMSIS_CORE_INC} + ${CMSIS_DEVICE_INC} + ${HAL_DIR}/Inc/Legacy + ${HAL_DIR}/Inc +) + +set(HAL_SRC_DIR ${HAL_DIR}/Src) +if(EXISTS ${HAL_SRC_DIR}) + set(HAL_SOURCES + ${HAL_SRC_DIR}/stm32f4xx_hal.c + ${HAL_SRC_DIR}/stm32f4xx_hal_rcc.c + ${HAL_SRC_DIR}/stm32f4xx_hal_rcc_ex.c + ${HAL_SRC_DIR}/stm32f4xx_hal_cortex.c + ${HAL_SRC_DIR}/stm32f4xx_hal_dma.c + ${HAL_SRC_DIR}/stm32f4xx_hal_dma_ex.c + ${HAL_SRC_DIR}/stm32f4xx_hal_rng.c + ${HAL_SRC_DIR}/stm32f4xx_hal_cryp.c + ${HAL_SRC_DIR}/stm32f4xx_hal_cryp_ex.c + ${HAL_SRC_DIR}/stm32f4xx_hal_hash.c + ${HAL_SRC_DIR}/stm32f4xx_hal_hash_ex.c + ) +else() + message(FATAL_ERROR "STM32F4 HAL source directory not found: ${HAL_SRC_DIR}") +endif() + +# wolfSSL build options +set(WOLFSSL_USER_SETTINGS ON CACHE BOOL "Use user_settings.h") +set(WOLFSSL_CRYPT_TESTS OFF CACHE BOOL "") +set(WOLFSSL_EXAMPLES OFF CACHE BOOL "") +set(BUILD_SHARED_LIBS OFF CACHE BOOL "") + +add_subdirectory(${WOLFSSL_ROOT} ${CMAKE_BINARY_DIR}/wolfssl-build EXCLUDE_FROM_ALL) +target_include_directories(wolfssl PRIVATE + ${CMSIS_CORE_INC} + ${CMSIS_DEVICE_INC} + ${HAL_DIR}/Inc/Legacy + ${HAL_DIR}/Inc + ${CMAKE_SOURCE_DIR} +) +target_compile_definitions(wolfssl PRIVATE STM32F417xx USE_HAL_DRIVER) +target_compile_options(wolfssl PRIVATE -Wno-cpp) + +# wolfSSL STM32 port driving the CRYP (through the HAL) and HASH. +set(WOLFSSL_STM32_PORT_SRC ${WOLFSSL_ROOT}/wolfcrypt/src/port/st/stm32.c) + +add_executable(wolfcrypt_test.elf + startup_stm32f417.c + main.c + ${WOLFSSL_ROOT}/wolfcrypt/test/test.c + ${HAL_SOURCES} + ${WOLFSSL_STM32_PORT_SRC} +) + +target_include_directories(wolfcrypt_test.elf PRIVATE + ${CMAKE_SOURCE_DIR} + ${WOLFSSL_ROOT} +) + +target_compile_definitions(wolfcrypt_test.elf PRIVATE + WOLFSSL_USER_SETTINGS + STM32F417xx + USE_HAL_DRIVER +) + +set_source_files_properties(${HAL_SOURCES} PROPERTIES + COMPILE_FLAGS "-mcpu=cortex-m4 -mthumb -mfpu=fpv4-sp-d16 -mfloat-abi=hard -ffunction-sections -fdata-sections -Os -include stdint.h -w" +) + +target_compile_options(wolfcrypt_test.elf PRIVATE + -mcpu=cortex-m4 -mthumb -mfpu=fpv4-sp-d16 -mfloat-abi=hard + -ffunction-sections -fdata-sections -Os +) + +target_link_options(wolfcrypt_test.elf PRIVATE + -T${CMAKE_SOURCE_DIR}/stm32f417.ld + -Wl,--gc-sections + -nostartfiles + -specs=nano.specs + -specs=nosys.specs +) + +target_link_libraries(wolfcrypt_test.elf PRIVATE wolfssl m c gcc nosys) diff --git a/STM32Sim/firmware/wolfcrypt-test-f417/main.c b/STM32Sim/firmware/wolfcrypt-test-f417/main.c new file mode 100644 index 0000000..b682400 --- /dev/null +++ b/STM32Sim/firmware/wolfcrypt-test-f417/main.c @@ -0,0 +1,164 @@ +/* main.c - Entry point for wolfCrypt test on STM32F417 under stm32-sim. + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of STM32Sim. + * + * STM32Sim 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. + * + * STM32Sim 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 + */ + +/* Runs the wolfCrypt test suite with output via USART2. wolfSSL's + * `wolfcrypt_test()` returns 0 on success; this firmware also prints + * the canonical pass/fail strings the simulator's run script greps + * for, and writes test_result/test_complete in .data so the + * simulator can poll completion via ELF symbol lookup. + */ + +#include +#include +#include + +/* wolfCrypt test entry point */ +extern int wolfcrypt_test(void *args); + +/* USART2 (STM32F4 register layout: SR 0x00, DR 0x04, BRR 0x08, CR1 0x0C) */ +#define USART2_BASE 0x40004400UL +#define USART2_SR (*(volatile uint32_t *)(USART2_BASE + 0x00)) +#define USART2_DR (*(volatile uint32_t *)(USART2_BASE + 0x04)) +#define USART2_BRR (*(volatile uint32_t *)(USART2_BASE + 0x08)) +#define USART2_CR1 (*(volatile uint32_t *)(USART2_BASE + 0x0C)) + +#define USART_CR1_UE (1 << 13) +#define USART_CR1_TE (1 << 3) +#define USART_SR_TXE (1 << 7) + +/* RCC register for enabling the USART2 clock */ +#define RCC_BASE 0x40023800UL +#define RCC_APB1ENR (*(volatile uint32_t *)(RCC_BASE + 0x40)) +#define RCC_APB1ENR_USART2EN (1 << 17) + +static void uart_init(void) +{ + /* Enable USART2 clock */ + RCC_APB1ENR |= RCC_APB1ENR_USART2EN; + + /* Configure USART2: 115200 baud at the 16 MHz HSI */ + USART2_BRR = 16000000 / 115200; + USART2_CR1 = USART_CR1_UE | USART_CR1_TE; +} + +static void uart_putc(char c) +{ + while (!(USART2_SR & USART_SR_TXE)) + ; + USART2_DR = c; +} + +static void uart_puts(const char *s) +{ + while (*s) { + if (*s == '\n') + uart_putc('\r'); + uart_putc(*s++); + } +} + +/* newlib _write syscall - redirects printf to UART */ +int _write(int fd, const char *buf, int len) +{ + (void)fd; + for (int i = 0; i < len; i++) { + if (buf[i] == '\n') + uart_putc('\r'); + uart_putc(buf[i]); + } + return len; +} + +/* Heap management for malloc - required by printf with format strings */ +extern char __heap_start__; +extern char __heap_end__; + +void *_sbrk(ptrdiff_t incr) +{ + static char *heap_ptr = NULL; + char *prev_heap_ptr; + + if (heap_ptr == NULL) { + heap_ptr = &__heap_start__; + } + + prev_heap_ptr = heap_ptr; + + if (heap_ptr + incr > &__heap_end__) { + /* Out of heap memory */ + return (void *)-1; + } + + heap_ptr += incr; + return prev_heap_ptr; +} + +/* Simple counter for time - used by GENSEED_FORTEST */ +static volatile uint32_t tick_counter = 0; + +/* time() stub for wolfSSL GENSEED_FORTEST */ +#include +time_t time(time_t *t) +{ + tick_counter += 12345; /* Simple pseudo-random increment */ + time_t val = (time_t)tick_counter; + if (t) + *t = val; + return val; +} + +/* Result variables - the simulator polls these by ELF symbol address. */ +volatile int test_result __attribute__((section(".data"))) = -1; +volatile int test_complete __attribute__((section(".data"))) = 0; + + +int main(int argc, char **argv) +{ + (void)argc; + (void)argv; + + setvbuf(stdin, NULL, _IONBF, 0); + setvbuf(stdout, NULL, _IONBF, 0); + setvbuf(stderr, NULL, _IONBF, 0); + uart_init(); + uart_puts("\n\n=== Starting wolfCrypt test ===\n\n"); + + test_result = wolfcrypt_test(NULL); + + if (test_result == 0) { + uart_puts("\n\n=== wolfCrypt test passed! ===\n"); + } else { + uart_puts("\n\n=== wolfCrypt test FAILED ===\n"); + } + + /* Set test_complete last: the simulator polls this between + * instruction slices and exits as soon as it goes nonzero, + * which would race with any output emitted afterwards. */ + test_complete = 1; + + /* Spin forever after the test completes */ + while (1) { + __asm__ volatile ("wfi"); + } + + return test_result; +} + diff --git a/STM32Sim/firmware/wolfcrypt-test-f417/startup_stm32f417.c b/STM32Sim/firmware/wolfcrypt-test-f417/startup_stm32f417.c new file mode 100644 index 0000000..7439d97 --- /dev/null +++ b/STM32Sim/firmware/wolfcrypt-test-f417/startup_stm32f417.c @@ -0,0 +1,104 @@ +/* Minimal startup code for STM32F417 running under stm32-sim. + * Cortex-M4 vector table + reset handler that copies .data from + * flash to RAM, zeroes .bss, runs static constructors, then jumps + * to main(). */ + +#include +#include + +extern int main(int argc, char** argv); + +void Default_Handler(void); +void Reset_Handler(void); + +/* Symbols provided by the linker script */ +extern unsigned long _estack; +extern unsigned long __data_start__; +extern unsigned long __data_end__; +extern unsigned long __bss_start__; +extern unsigned long __bss_end__; +extern unsigned long _sidata; /* start of .data in flash */ + +/* Minimal init_array support */ +extern void (*__preinit_array_start[])(void); +extern void (*__preinit_array_end[])(void); +extern void (*__init_array_start[])(void); +extern void (*__init_array_end[])(void); + +static void call_init_array(void) +{ + size_t count, i; + + count = __preinit_array_end - __preinit_array_start; + for (i = 0; i < count; i++) + __preinit_array_start[i](); + + count = __init_array_end - __init_array_start; + for (i = 0; i < count; i++) + __init_array_start[i](); +} + +void Reset_Handler(void) +{ + unsigned long *src, *dst; + + /* Copy .data from flash to RAM */ + src = &_sidata; + for (dst = &__data_start__; dst < &__data_end__;) + *dst++ = *src++; + + /* Zero .bss */ + for (dst = &__bss_start__; dst < &__bss_end__;) + *dst++ = 0; + + /* Call static constructors */ + call_init_array(); + + /* Call main */ + (void)main(0, (char**)0); + + /* Infinite loop after main returns */ + while (1) { + __asm__ volatile ("wfi"); + } +} + +void Default_Handler(void) +{ + while (1) { + __asm__ volatile ("wfi"); + } +} + +/* Exception handlers - all weak aliases to Default_Handler */ +void NMI_Handler(void) __attribute__((weak, alias("Default_Handler"))); +void HardFault_Handler(void) __attribute__((weak, alias("Default_Handler"))); +void MemManage_Handler(void) __attribute__((weak, alias("Default_Handler"))); +void BusFault_Handler(void) __attribute__((weak, alias("Default_Handler"))); +void UsageFault_Handler(void) __attribute__((weak, alias("Default_Handler"))); +void SVC_Handler(void) __attribute__((weak, alias("Default_Handler"))); +void DebugMon_Handler(void) __attribute__((weak, alias("Default_Handler"))); +void PendSV_Handler(void) __attribute__((weak, alias("Default_Handler"))); +void SysTick_Handler(void) __attribute__((weak, alias("Default_Handler"))); + +/* Vector table */ +__attribute__ ((section(".isr_vector"), used)) +void (* const g_pfnVectors[])(void) = { + (void (*)(void))(&_estack), /* Initial stack pointer */ + Reset_Handler, /* Reset Handler */ + NMI_Handler, /* NMI Handler */ + HardFault_Handler, /* Hard Fault Handler */ + MemManage_Handler, /* MPU Fault Handler */ + BusFault_Handler, /* Bus Fault Handler */ + UsageFault_Handler, /* Usage Fault Handler */ + 0, /* Reserved */ + 0, /* Reserved */ + 0, /* Reserved */ + 0, /* Reserved */ + SVC_Handler, /* SVCall Handler */ + DebugMon_Handler, /* Debug Monitor Handler */ + 0, /* Reserved */ + PendSV_Handler, /* PendSV Handler */ + SysTick_Handler /* SysTick Handler */ + /* IRQ vectors would continue here */ +}; diff --git a/STM32Sim/firmware/wolfcrypt-test-f417/stm32f417.ld b/STM32Sim/firmware/wolfcrypt-test-f417/stm32f417.ld new file mode 100644 index 0000000..14ed61c --- /dev/null +++ b/STM32Sim/firmware/wolfcrypt-test-f417/stm32f417.ld @@ -0,0 +1,106 @@ +/* STM32F417 memory map for stm32-sim. Matches the chip configuration in + * stm32-sim-chips/src/stm32f417.rs: 1 MiB flash at 0x08000000, 128 KiB + * SRAM at 0x20000000 (.data, .bss and the heap) and 64 KiB CCM RAM at + * 0x10000000 (the stack; the CRYP/HASH are driven by the CPU, not DMA, + * so nothing needs a DMA-reachable stack). */ +MEMORY +{ + FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 1024K + CCMRAM (xrw) : ORIGIN = 0x10000000, LENGTH = 64K + RAM (xrw) : ORIGIN = 0x20000000, LENGTH = 128K +} + +_estack = ORIGIN(CCMRAM) + LENGTH(CCMRAM); + +ENTRY(Reset_Handler) + +SECTIONS +{ + .isr_vector : + { + . = ALIGN(4); + KEEP(*(.isr_vector)) + . = ALIGN(4); + } > FLASH + + .text : + { + . = ALIGN(4); + *(.text*) + *(.rodata*) + *(.glue_7) + *(.glue_7t) + *(.eh_frame) + . = ALIGN(4); + _etext = .; + } > FLASH + + .ARM.extab : + { + *(.ARM.extab* .gnu.linkonce.armextab.*) + } > FLASH + + .ARM.exidx : + { + __exidx_start = .; + *(.ARM.exidx*) + __exidx_end = .; + } > FLASH + + .preinit_array : + { + PROVIDE_HIDDEN(__preinit_array_start = .); + KEEP(*(.preinit_array*)) + PROVIDE_HIDDEN(__preinit_array_end = .); + } > FLASH + + .init_array : + { + PROVIDE_HIDDEN(__init_array_start = .); + KEEP(*(SORT(.init_array.*))) + KEEP(*(.init_array*)) + PROVIDE_HIDDEN(__init_array_end = .); + } > FLASH + + .fini_array : + { + PROVIDE_HIDDEN(__fini_array_start = .); + KEEP(*(SORT(.fini_array.*))) + KEEP(*(.fini_array*)) + PROVIDE_HIDDEN(__fini_array_end = .); + } > FLASH + + _sidata = LOADADDR(.data); + + .data : + { + . = ALIGN(4); + __data_start__ = .; + *(.data*) + . = ALIGN(4); + __data_end__ = .; + } > RAM AT> FLASH + + .bss : + { + . = ALIGN(4); + __bss_start__ = .; + *(.bss*) + *(COMMON) + . = ALIGN(4); + __bss_end__ = .; + } > RAM + + /* Everything left in SRAM is heap. */ + .heap (NOLOAD): + { + . = ALIGN(8); + PROVIDE(__heap_start__ = .); + . = ORIGIN(RAM) + LENGTH(RAM); + PROVIDE(__heap_end__ = .); + PROVIDE(end = __heap_start__); + } > RAM +} + +PROVIDE(_init = 0); +PROVIDE(_fini = 0); diff --git a/STM32Sim/firmware/wolfcrypt-test-f417/stm32f4xx_hal_conf.h b/STM32Sim/firmware/wolfcrypt-test-f417/stm32f4xx_hal_conf.h new file mode 100644 index 0000000..b18cd80 --- /dev/null +++ b/STM32Sim/firmware/wolfcrypt-test-f417/stm32f4xx_hal_conf.h @@ -0,0 +1,121 @@ +/* stm32f4xx_hal_conf.h - HAL configuration for the STM32F417 wolfCrypt + * build under stm32-sim. + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of STM32Sim. + * + * STM32Sim 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. + * + * STM32Sim 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 STM32F4xx_HAL_CONF_H +#define STM32F4xx_HAL_CONF_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* ------------------------- Module Selection ----------------------------- */ +#define HAL_MODULE_ENABLED +#define HAL_CORTEX_MODULE_ENABLED +#define HAL_RCC_MODULE_ENABLED +#define HAL_GPIO_MODULE_ENABLED +#define HAL_EXTI_MODULE_ENABLED +#define HAL_DMA_MODULE_ENABLED +#define HAL_FLASH_MODULE_ENABLED +#define HAL_PWR_MODULE_ENABLED +#define HAL_RNG_MODULE_ENABLED +#define HAL_CRYP_MODULE_ENABLED +#define HAL_HASH_MODULE_ENABLED + +/* ------------------------- Oscillator Values ---------------------------- */ +#if !defined(HSE_VALUE) +#define HSE_VALUE 8000000U +#endif +#if !defined(HSE_STARTUP_TIMEOUT) +#define HSE_STARTUP_TIMEOUT 100U +#endif +#if !defined(HSI_VALUE) +#define HSI_VALUE 16000000U +#endif +#if !defined(LSI_VALUE) +#define LSI_VALUE 32000U +#endif +#if !defined(LSE_VALUE) +#define LSE_VALUE 32768U +#endif +#if !defined(LSE_STARTUP_TIMEOUT) +#define LSE_STARTUP_TIMEOUT 5000U +#endif +#if !defined(EXTERNAL_CLOCK_VALUE) +#define EXTERNAL_CLOCK_VALUE 12288000U +#endif + +/* ------------------------- System Configuration ------------------------- */ +#define VDD_VALUE 3300U +#define TICK_INT_PRIORITY 0x0FU +#define USE_RTOS 0U +#define PREFETCH_ENABLE 1U +#define INSTRUCTION_CACHE_ENABLE 1U +#define DATA_CACHE_ENABLE 1U + +#define USE_HAL_CRYP_REGISTER_CALLBACKS 0U +#define USE_HAL_HASH_REGISTER_CALLBACKS 0U +#define USE_HAL_RNG_REGISTER_CALLBACKS 0U + +/* ------------------------- Includes ------------------------------------- */ +#ifdef HAL_RCC_MODULE_ENABLED +#include "stm32f4xx_hal_rcc.h" +#endif +#ifdef HAL_GPIO_MODULE_ENABLED +#include "stm32f4xx_hal_gpio.h" +#endif +#ifdef HAL_EXTI_MODULE_ENABLED +#include "stm32f4xx_hal_exti.h" +#endif +#ifdef HAL_DMA_MODULE_ENABLED +#include "stm32f4xx_hal_dma.h" +#endif +#ifdef HAL_CORTEX_MODULE_ENABLED +#include "stm32f4xx_hal_cortex.h" +#endif +#ifdef HAL_FLASH_MODULE_ENABLED +#include "stm32f4xx_hal_flash.h" +#endif +#ifdef HAL_PWR_MODULE_ENABLED +#include "stm32f4xx_hal_pwr.h" +#endif +#ifdef HAL_RNG_MODULE_ENABLED +#include "stm32f4xx_hal_rng.h" +#endif +#ifdef HAL_CRYP_MODULE_ENABLED +#include "stm32f4xx_hal_cryp.h" +#endif +#ifdef HAL_HASH_MODULE_ENABLED +#include "stm32f4xx_hal_hash.h" +#endif + +#ifdef USE_FULL_ASSERT +#define assert_param(expr) ((expr) ? (void)0U : assert_failed((uint8_t *)__FILE__, __LINE__)) +void assert_failed(uint8_t *file, uint32_t line); +#else +#define assert_param(expr) ((void)0U) +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* STM32F4xx_HAL_CONF_H */ diff --git a/STM32Sim/firmware/wolfcrypt-test-f417/toolchain-arm-none-eabi.cmake b/STM32Sim/firmware/wolfcrypt-test-f417/toolchain-arm-none-eabi.cmake new file mode 100644 index 0000000..371a746 --- /dev/null +++ b/STM32Sim/firmware/wolfcrypt-test-f417/toolchain-arm-none-eabi.cmake @@ -0,0 +1,35 @@ +# arm-none-eabi toolchain for the STM32F417 wolfCrypt firmware. +# +# ST/ARM vendor trees (cmsis-device-f4, stm32f4xx-hal-driver, CMSIS_5) are +# expected under /opt, as the Docker image lays them out. Set the +# STM32SIM_VENDOR_DIR environment variable to build against another root. + +set(CMAKE_SYSTEM_NAME Generic) +set(CMAKE_SYSTEM_PROCESSOR arm) + +set(CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY) + +set(CMAKE_C_COMPILER arm-none-eabi-gcc) +set(CMAKE_CXX_COMPILER arm-none-eabi-g++) +set(CMAKE_ASM_COMPILER arm-none-eabi-gcc) + +set(CMAKE_AR arm-none-eabi-ar) +set(CMAKE_RANLIB arm-none-eabi-ranlib) + +set(CMAKE_C_STANDARD 11) + +if(DEFINED ENV{STM32SIM_VENDOR_DIR}) + set(STM32SIM_VENDOR_DIR "$ENV{STM32SIM_VENDOR_DIR}") +else() + set(STM32SIM_VENDOR_DIR "/opt") +endif() + +set(CPU_FLAGS "-mcpu=cortex-m4 -mthumb -mfpu=fpv4-sp-d16 -mfloat-abi=hard") +set(OPT_FLAGS "-Os -ffunction-sections -fdata-sections") +set(CMSIS_INCLUDES "-I${STM32SIM_VENDOR_DIR}/cmsis-device-f4/Include -I${STM32SIM_VENDOR_DIR}/CMSIS_5/CMSIS/Core/Include -I${CMAKE_CURRENT_LIST_DIR}") + +set(CMAKE_C_FLAGS_INIT "${CPU_FLAGS} ${OPT_FLAGS} ${CMSIS_INCLUDES} -DSTM32F417xx") +set(CMAKE_CXX_FLAGS_INIT "${CPU_FLAGS} ${OPT_FLAGS} ${CMSIS_INCLUDES} -DSTM32F417xx") +set(CMAKE_ASM_FLAGS_INIT "${CPU_FLAGS}") + +set(CMAKE_EXE_LINKER_FLAGS_INIT "-Wl,--gc-sections -static") diff --git a/STM32Sim/firmware/wolfcrypt-test-f417/user_settings.h b/STM32Sim/firmware/wolfcrypt-test-f417/user_settings.h new file mode 100644 index 0000000..d6bdd9a --- /dev/null +++ b/STM32Sim/firmware/wolfcrypt-test-f417/user_settings.h @@ -0,0 +1,86 @@ +/* user_settings.h - wolfSSL/wolfCrypt configuration for STM32F417 + * running under stm32-sim. + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of STM32Sim. + * + * STM32Sim 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. + * + * STM32Sim 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 + */ + +/* The F417 crypto block: DES/TDES and AES ECB/CBC/CTR on the CRYP (no + * GCM/CCM on this part), SHA-1 and MD5 on the HASH, and the RNG. SHA-2, + * RSA and ECC run in software. */ + +#ifndef USER_SETTINGS_STM32SIM_F417_H +#define USER_SETTINGS_STM32SIM_F417_H + +/* ------------------------- Platform ------------------------------------- */ +#define WOLFSSL_ARM_CORTEX_M +#define WOLFSSL_STM32F4 +#define WOLFSSL_STM32_CUBEMX +/* Current STM32CubeF4 CRYP HAL only offers HAL_CRYP_Encrypt/Decrypt. */ +#define STM32_HAL_V2 + +/* Required for consistent math library settings (CTC_SETTINGS) */ +#define SIZEOF_LONG 4 +#define SIZEOF_LONG_LONG 8 + +/* ------------------------- Threading / OS ------------------------------- */ +#define SINGLE_THREADED + +/* ------------------------- Filesystem / I/O ----------------------------- */ +#define WOLFSSL_NO_CURRDIR +#define NO_FILESYSTEM +#define NO_WRITEV + +/* ------------------------- wolfCrypt Only ------------------------------- */ +#define WOLFCRYPT_ONLY +#define NO_DH +#define NO_DSA + +/* ------------------------- Symmetric ------------------------------------ */ +#define WOLFSSL_AES_COUNTER +#define WOLFSSL_AES_DIRECT +#define HAVE_AES_ECB +/* No GCM on the F417 CRYP: this covers wolfSSL's software GHASH fallback + * (the model drops the GCM mode bits as the silicon does). */ +#define HAVE_AESGCM +#define WOLFSSL_DES_ECB + +/* ------------------------- RNG Configuration ---------------------------- */ +#define NO_DEV_RANDOM +#define HAVE_HASHDRBG + +/* ------------------------- Math Library --------------------------------- */ +#define WOLFSSL_SP_MATH_ALL +#define WOLFSSL_HAVE_SP_RSA +#define WOLFSSL_HAVE_SP_ECC +#define WOLFSSL_SP_ARM_CORTEX_M_ASM +#define SP_WORD_SIZE 32 +#define HAVE_ECC + +/* ------------------------- Crypto Hardening ----------------------------- */ +#define WC_RSA_BLINDING +#define ECC_TIMING_RESISTANT + +/* ------------------------- Size Optimization ---------------------------- */ +#define WOLFSSL_SMALL_STACK + +/* ------------------------- Test Configuration --------------------------- */ +#define BENCH_EMBEDDED +#define NO_MAIN_DRIVER + +#endif /* USER_SETTINGS_STM32SIM_F417_H */ diff --git a/STM32Sim/scripts/run-rng-fault-f417.sh b/STM32Sim/scripts/run-rng-fault-f417.sh new file mode 100755 index 0000000..2bc3096 --- /dev/null +++ b/STM32Sim/scripts/run-rng-fault-f417.sh @@ -0,0 +1,105 @@ +#!/usr/bin/env bash +# +# Copyright (C) 2026 wolfSSL Inc. +# +# This file is part of STM32Sim. +# +# STM32Sim 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. +# +# STM32Sim 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 +# +# STM32F4 RNG fault regression test for wolfSSL's wc_GenerateSeed(). +# +# Builds firmware/rng-fault-f4 for both STM32_RNG arms that drive the F4 +# RNG directly (the Standard Peripheral Library arm and +# WOLFSSL_STM32_RNG_NOLIB) and runs each on stm32-sim --chip stm32f417 +# with RNG seed / clock errors injected part way through a seed request. +# Every scenario must return the expected code; a hung wc_GenerateSeed() +# shows up as a simulator timeout and fails the test with the hung PC. + +set -euo pipefail + +WOLFSSL_ROOT="${WOLFSSL_ROOT:-/opt/wolfssl}" +FIRMWARE_DIR="${FIRMWARE_DIR:-/opt/firmware-rng-fault-f4}" +TIMEOUT="${TIMEOUT:-20}" + +if [[ ! -d "${WOLFSSL_ROOT}" ]]; then + echo "ERROR: wolfSSL source not mounted at ${WOLFSSL_ROOT}" >&2 + exit 2 +fi + +BUILD_DIR="$(mktemp -d)" +cp -r "${FIRMWARE_DIR}/." "${BUILD_DIR}/" + +# The sanity seed reads 64 RNG words, so a fault after 200 reads lands +# inside the second, faulted, seed request. RNG_FAILURE_E is -199. +# +# arm fault expected fault= value(s) +SCENARIOS=" +stdperiph none 0 +stdperiph seed:200 0 +stdperiph seed:200:sticky -199 +stdperiph clock:200 0 +stdperiph clock:200:sticky -199 +nolib none 0 +nolib seed:200 0 +nolib seed:200:sticky -199 +nolib clock:200 0 +nolib clock:200:sticky -199 +" + +for arm in stdperiph nolib; do + echo ">> Building rng-fault firmware (${arm} arm) against ${WOLFSSL_ROOT} ..." + make -s -C "${BUILD_DIR}" TARGET=sim ARM="${arm}" WOLFSSL_ROOT="${WOLFSSL_ROOT}" +done + +FAILED=0 +while read -r arm fault expect; do + [[ -z "${arm}" ]] && continue + elf="${BUILD_DIR}/rng-fault-${arm}-sim.elf" + args=(--chip stm32f417 --timeout "${TIMEOUT}") + [[ "${fault}" != "none" ]] && args+=(--rng-fault "${fault}") + + set +e + out="$(stm32-sim "${args[@]}" "${elf}" 2>&1)" + rc=$? + set -e + + got="$(sed -n 's/.*RNG_FAULT sanity=[-0-9]* fault=\([-0-9]*\).*/\1/p' <<<"${out}")" + sanity="$(sed -n 's/.*RNG_FAULT sanity=\([-0-9]*\).*/\1/p' <<<"${out}")" + label="$(printf '%-9s %-17s' "${arm}" "${fault}")" + if [[ ${rc} -eq 3 ]]; then + pc="$(sed -n 's/.*TIMEOUT.*PC=\(0x[0-9a-f]*\).*/\1/p' <<<"${out}")" + where="$(arm-none-eabi-addr2line -f -e "${elf}" "${pc}" 2>/dev/null | head -1)" + echo "FAIL ${label} hung: no return after ${TIMEOUT}s, PC ${pc} in ${where}" + FAILED=1 + elif [[ "${sanity}" != "0" ]]; then + echo "FAIL ${label} sanity seed returned '${sanity}' (sim exit ${rc})" + echo "${out}" | tail -5 + FAILED=1 + elif [[ "|${expect}|" == *"|${got}|"* ]]; then + echo "ok ${label} fault=${got}" + else + echo "FAIL ${label} fault=${got}, expected ${expect} (sim exit ${rc})" + FAILED=1 + fi +done <<<"${SCENARIOS}" + +rm -rf "${BUILD_DIR}" +if [[ ${FAILED} -ne 0 ]]; then + echo + echo "RNG fault tests FAILED." + exit 1 +fi +echo +echo "RNG fault tests completed successfully." diff --git a/STM32Sim/scripts/run-wolfcrypt-f417.sh b/STM32Sim/scripts/run-wolfcrypt-f417.sh new file mode 100755 index 0000000..8303132 --- /dev/null +++ b/STM32Sim/scripts/run-wolfcrypt-f417.sh @@ -0,0 +1,86 @@ +#!/usr/bin/env bash +# +# Copyright (C) 2026 wolfSSL Inc. +# +# This file is part of STM32Sim. +# +# STM32Sim 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. +# +# STM32Sim 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 +# +# Build the wolfCrypt test for STM32F417 (CubeMX HAL: CRYP for DES/TDES and +# AES ECB/CBC/CTR, HASH for SHA-1/MD5, RNG) and run it on stm32-sim. + +set -euo pipefail + +WOLFSSL_ROOT="${WOLFSSL_ROOT:-/opt/wolfssl}" +FIRMWARE_DIR="${FIRMWARE_DIR:-/opt/firmware-f417}" +TIMEOUT="${TIMEOUT:-300}" + +if [[ ! -d "${WOLFSSL_ROOT}" ]]; then + echo "ERROR: wolfSSL source not mounted at ${WOLFSSL_ROOT}" >&2 + exit 2 +fi + +WOLFSSL_BUILD_TREE=/opt/wolfssl-build-tree-f417 +rm -rf "${WOLFSSL_BUILD_TREE}" +cp -r "${WOLFSSL_ROOT}" "${WOLFSSL_BUILD_TREE}" +rm -f "${WOLFSSL_BUILD_TREE}/config.h" + +echo ">> Building wolfCrypt firmware against wolfSSL at ${WOLFSSL_ROOT} ..." +# WOLFSSL_SINGLE_THREADED keeps wolfSSL's CMake from linking a host +# threads library into the bare-metal image. +cmake -G Ninja \ + -DWOLFSSL_USER_SETTINGS=ON \ + -DWOLFSSL_SINGLE_THREADED=yes \ + -DCMAKE_TOOLCHAIN_FILE="${FIRMWARE_DIR}/toolchain-arm-none-eabi.cmake" \ + -DCMAKE_BUILD_TYPE=Release \ + -DWOLFSSL_CRYPT_TESTS=OFF \ + -DWOLFSSL_EXAMPLES=OFF \ + -DWOLFSSL_ROOT="${WOLFSSL_BUILD_TREE}" \ + -B "${FIRMWARE_DIR}/build" \ + -S "${FIRMWARE_DIR}" +cmake --build "${FIRMWARE_DIR}/build" + +ELF="${FIRMWARE_DIR}/build/wolfcrypt_test.elf" +if [[ ! -f "${ELF}" ]]; then + echo "ERROR: firmware build produced no ELF at ${ELF}" >&2 + exit 1 +fi + +echo ">> Running ${ELF} on stm32-sim --chip stm32f417 (timeout ${TIMEOUT}s) ..." +LOG="$(mktemp)" +set +e +stm32-sim \ + --chip stm32f417 \ + --timeout "${TIMEOUT}" \ + --exit-on test_complete \ + --result-symbol test_result \ + "${ELF}" 2>&1 | tee "${LOG}" +SIM_EXIT=${PIPESTATUS[0]} +set -e + +if grep -q "=== wolfCrypt test passed! ===" "${LOG}"; then + echo + echo "wolfCrypt tests completed successfully." + exit 0 +fi +if grep -q "=== wolfCrypt test FAILED ===" "${LOG}"; then + echo + echo "wolfCrypt tests FAILED." + exit 1 +fi + +echo +echo "wolfCrypt tests did not report a result string. Simulator exit=${SIM_EXIT}" +exit "${SIM_EXIT}" diff --git a/STM32Sim/stm32-sim/Cargo.toml b/STM32Sim/stm32-sim/Cargo.toml index 1dd9600..dfd2373 100644 --- a/STM32Sim/stm32-sim/Cargo.toml +++ b/STM32Sim/stm32-sim/Cargo.toml @@ -32,6 +32,7 @@ hex = "0.4" aes = "0.8" cipher = "0.4" +des = "0.8" ctr = "0.9" cfb-mode = "0.8" ofb = "0.6" diff --git a/STM32Sim/stm32-sim/chips/src/lib.rs b/STM32Sim/stm32-sim/chips/src/lib.rs index 51e097b..d918467 100644 --- a/STM32Sim/stm32-sim/chips/src/lib.rs +++ b/STM32Sim/stm32-sim/chips/src/lib.rs @@ -19,12 +19,21 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ +pub mod stm32f417; pub mod stm32h753; pub mod stm32mp135; pub mod stm32u575; use anyhow::Result; use stm32_sim_core::{Bus, CpuKind, MemoryRegion}; +use stm32_sim_peripherals::RngFault; + +/// Run-time knobs that apply to every chip. +#[derive(Debug, Clone, Default)] +pub struct ChipOptions { + /// Fault to inject into the chip's RNG (`stm32-sim --rng-fault`). + pub rng_fault: Option, +} pub struct Chip { pub name: &'static str, @@ -34,19 +43,55 @@ pub struct Chip { } pub trait ChipBuilder { - fn build() -> Result; + fn build_with(opts: &ChipOptions) -> Result; + + fn build() -> Result { + Self::build_with(&ChipOptions::default()) + } } pub fn build(name: &str) -> Result { + build_with(name, &ChipOptions::default()) +} + +pub fn build_with(name: &str, opts: &ChipOptions) -> Result { match name { - "stm32h753" => stm32h753::Stm32H753::build(), - "stm32u575" => stm32u575::Stm32U575::build(), - "stm32u585" => stm32u575::Stm32U585::build(), - "stm32mp135" => stm32mp135::Stm32Mp135::build(), + "stm32f407" => stm32f417::Stm32F407::build_with(opts), + "stm32f417" => stm32f417::Stm32F417::build_with(opts), + "stm32h753" => stm32h753::Stm32H753::build_with(opts), + "stm32u575" => stm32u575::Stm32U575::build_with(opts), + "stm32u585" => stm32u575::Stm32U585::build_with(opts), + "stm32mp135" => stm32mp135::Stm32Mp135::build_with(opts), other => anyhow::bail!("unknown chip: {other}"), } } pub fn list() -> &'static [&'static str] { - &["stm32h753", "stm32u575", "stm32u585", "stm32mp135"] + &["stm32f407", "stm32f417", "stm32h753", "stm32u575", "stm32u585", "stm32mp135"] +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_listed_chip_builds() { + for name in list() { + let chip = build(name).unwrap_or_else(|e| panic!("{name}: {e}")); + assert_eq!(chip.name, *name); + } + assert!(build("stm32f999").is_err()); + } + + #[test] + fn f417_has_crypto_and_f407_does_not() { + let has = |chip: &Chip, name: &str| chip.bus.regions.iter().any(|r| r.name == name); + let f417 = build("stm32f417").unwrap(); + let f407 = build("stm32f407").unwrap(); + for p in ["cryp", "hash", "rng", "rcc", "usart2"] { + assert!(has(&f417, p), "F417 missing {p}"); + } + assert!(!has(&f407, "cryp") && !has(&f407, "hash")); + assert!(has(&f407, "rng")); + } } diff --git a/STM32Sim/stm32-sim/chips/src/stm32f417.rs b/STM32Sim/stm32-sim/chips/src/stm32f417.rs new file mode 100644 index 0000000..38064f8 --- /dev/null +++ b/STM32Sim/stm32-sim/chips/src/stm32f417.rs @@ -0,0 +1,119 @@ +/* stm32f417.rs + * + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of STM32Sim. + * + * STM32Sim 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. + * + * STM32Sim 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 + */ + +use anyhow::Result; +use stm32_sim_core::peripheral::wrap; +use stm32_sim_core::{Bus, CpuKind, MemoryRegion}; +use stm32_sim_peripherals::{ + cryp::v1::CrypV1, hash::v1::HashV1, usart::StdoutSink, Rcc, Rng, Usart, +}; + +use crate::{Chip, ChipOptions}; + +/// STM32F417 - Cortex-M4F, 1 MiB flash, 192 KiB SRAM, with the F4 +/// crypto block: CRYP (DES/TDES, AES ECB/CBC/CTR; the GCM/CCM modes only +/// arrived with F437/F439), HASH (SHA-1/MD5) and RNG. +/// +/// Memory map (RM0090 section 2.3): +/// FLASH 0x0800_0000 1 MiB +/// CCMRAM 0x1000_0000 64 KiB +/// SRAM 0x2000_0000 128 KiB (SRAM1 112 KiB + SRAM2 16 KiB) +/// +/// Peripherals: +/// USART2 0x4000_4400 USART3 0x4000_4800 USART1 0x4001_1000 +/// (F1/F2/F4 register layout, transmit to stdout) +/// RCC 0x4002_3800 +/// FLASH 0x4002_3C00 (interface registers, scratch: ACR latency) +/// CRYP 0x5006_0000 +/// HASH 0x5006_0400 +/// RNG 0x5006_0800 +pub struct Stm32F417; + +impl crate::ChipBuilder for Stm32F417 { + fn build_with(opts: &ChipOptions) -> Result { + build_f4("stm32f417", true, opts) + } +} + +/// STM32F407 - the F417 without CRYP and HASH (the STM32F4DISCOVERY +/// part). Same memory map and RNG. +pub struct Stm32F407; + +impl crate::ChipBuilder for Stm32F407 { + fn build_with(opts: &ChipOptions) -> Result { + build_f4("stm32f407", false, opts) + } +} + +fn build_f4(name: &'static str, crypto: bool, opts: &ChipOptions) -> Result { + let memory = vec![ + MemoryRegion { + base: 0x0800_0000, + size: 0x0010_0000, + name: "FLASH", + }, + MemoryRegion { + base: 0x1000_0000, + size: 0x0001_0000, + name: "CCMRAM", + }, + MemoryRegion { + base: 0x2000_0000, + size: 0x0002_0000, + name: "SRAM", + }, + ]; + + let mut bus = Bus::new(); + + for (base, uname) in [ + (0x4000_4400, "usart2"), + (0x4000_4800, "usart3"), + (0x4001_1000, "usart1"), + ] { + let u = wrap(Usart::new_legacy(uname, Box::new(StdoutSink))); + bus.map(base, 0x0400, uname, u); + } + + let rcc = wrap(Rcc::f4()); + bus.map(0x4002_3800, 0x0400, "rcc", rcc); + + let flash_if = wrap(Rcc::raw("flash-if")); + bus.map(0x4002_3C00, 0x0400, "flash-if", flash_if); + + if crypto { + let cryp = wrap(CrypV1::new_f4()); + bus.map(0x5006_0000, 0x0400, "cryp", cryp); + + let hash = wrap(HashV1::new_f4()); + bus.map(0x5006_0400, 0x0400, "hash", hash); + } + + let rng = wrap(Rng::new().with_fault(opts.rng_fault)); + bus.map(0x5006_0800, 0x0400, "rng", rng); + + Ok(Chip { + name, + cpu_kind: CpuKind::CortexM, + memory_regions: memory, + bus, + }) +} diff --git a/STM32Sim/stm32-sim/chips/src/stm32h753.rs b/STM32Sim/stm32-sim/chips/src/stm32h753.rs index e742b66..0c3aa25 100644 --- a/STM32Sim/stm32-sim/chips/src/stm32h753.rs +++ b/STM32Sim/stm32-sim/chips/src/stm32h753.rs @@ -26,7 +26,7 @@ use stm32_sim_peripherals::{ cryp::v1::CrypV1, hash::v1::HashV1, usart::StdoutSink, Dbgmcu, Rcc, Rng, Usart, }; -use crate::Chip; +use crate::{Chip, ChipOptions}; /// STM32H753 - Cortex-M7, 2 MiB flash, 1 MiB SRAM (split DTCM/AXI/SRAM). /// @@ -43,7 +43,7 @@ use crate::Chip; pub struct Stm32H753; impl crate::ChipBuilder for Stm32H753 { - fn build() -> Result { + fn build_with(opts: &ChipOptions) -> Result { let memory = vec![ MemoryRegion { base: 0x0800_0000, @@ -81,7 +81,7 @@ impl crate::ChipBuilder for Stm32H753 { let hash = wrap(HashV1::new()); bus.map(0x4802_1400, 0x0400, "hash", hash); - let rng = wrap(Rng::new()); + let rng = wrap(Rng::new().with_fault(opts.rng_fault)); bus.map(0x4802_1800, 0x0400, "rng", rng); // DBGMCU @ 0x5C00_1000 - HAL reads IDCODE for revision-gated diff --git a/STM32Sim/stm32-sim/chips/src/stm32mp135.rs b/STM32Sim/stm32-sim/chips/src/stm32mp135.rs index 9037357..f3a4457 100644 --- a/STM32Sim/stm32-sim/chips/src/stm32mp135.rs +++ b/STM32Sim/stm32-sim/chips/src/stm32mp135.rs @@ -57,12 +57,12 @@ use stm32_sim_peripherals::{ cryp::v1::CrypV1, hash::v1::HashV1, pka::v2::PkaV2, usart::StdoutSink, Dbgmcu, Rcc, Rng, Usart, }; -use crate::Chip; +use crate::{Chip, ChipOptions}; pub struct Stm32Mp135; impl crate::ChipBuilder for Stm32Mp135 { - fn build() -> Result { + fn build_with(opts: &ChipOptions) -> Result { let memory = vec![ MemoryRegion { base: 0x2FFE_0000, @@ -114,7 +114,7 @@ impl crate::ChipBuilder for Stm32Mp135 { let hash1 = wrap(HashV1::new_mp13()); bus.map(0x5400_3000, 0x0400, "hash1", hash1); - let rng1 = wrap(Rng::new()); + let rng1 = wrap(Rng::new().with_fault(opts.rng_fault)); bus.map(0x5400_4000, 0x0400, "rng1", rng1); // PKA spans 0x2000 like on the U5, since the SRAM-style diff --git a/STM32Sim/stm32-sim/chips/src/stm32u575.rs b/STM32Sim/stm32-sim/chips/src/stm32u575.rs index aa07c1c..0439130 100644 --- a/STM32Sim/stm32-sim/chips/src/stm32u575.rs +++ b/STM32Sim/stm32-sim/chips/src/stm32u575.rs @@ -38,12 +38,12 @@ use stm32_sim_peripherals::{ cryp::v2::CrypV2, hash::v1::HashV1, pka::v2::PkaV2, usart::StdoutSink, Dbgmcu, Rcc, Rng, Usart, }; -use crate::Chip; +use crate::{Chip, ChipOptions}; pub struct Stm32U575; impl crate::ChipBuilder for Stm32U575 { - fn build() -> Result { + fn build_with(opts: &ChipOptions) -> Result { let memory = vec![ MemoryRegion { base: 0x0800_0000, @@ -91,7 +91,7 @@ impl crate::ChipBuilder for Stm32U575 { let hash = wrap(HashV1::new_u5()); bus.map(0x420C_0400, 0x0400, "hash", hash); - let rng = wrap(Rng::new()); + let rng = wrap(Rng::new().with_fault(opts.rng_fault)); bus.map(0x420C_0800, 0x0400, "rng", rng); let pka = wrap(PkaV2::new()); @@ -119,8 +119,8 @@ impl crate::ChipBuilder for Stm32U575 { pub struct Stm32U585; impl crate::ChipBuilder for Stm32U585 { - fn build() -> Result { - let mut chip = Stm32U575::build()?; + fn build_with(opts: &ChipOptions) -> Result { + let mut chip = Stm32U575::build_with(opts)?; chip.name = "stm32u585"; Ok(chip) } diff --git a/STM32Sim/stm32-sim/core/src/runner.rs b/STM32Sim/stm32-sim/core/src/runner.rs index c6b2e43..833a2de 100644 --- a/STM32Sim/stm32-sim/core/src/runner.rs +++ b/STM32Sim/stm32-sim/core/src/runner.rs @@ -59,6 +59,9 @@ pub enum RunOutcome { elapsed: Duration, }, Timeout { + /// Where the core was when the deadline passed: for a hung + /// firmware, the loop it is stuck in. + pc: u64, elapsed: Duration, }, Fault { @@ -107,6 +110,7 @@ impl Runner { if start.elapsed() > self.exit.timeout { return Ok(RunOutcome::Timeout { + pc: self.cpu.read_pc().unwrap_or(0), elapsed: start.elapsed(), }); } diff --git a/STM32Sim/stm32-sim/peripherals/Cargo.toml b/STM32Sim/stm32-sim/peripherals/Cargo.toml index 4a06e80..e08ff41 100644 --- a/STM32Sim/stm32-sim/peripherals/Cargo.toml +++ b/STM32Sim/stm32-sim/peripherals/Cargo.toml @@ -16,6 +16,7 @@ hex.workspace = true aes.workspace = true cipher.workspace = true +des.workspace = true sha-1.workspace = true sha2.workspace = true sha3.workspace = true diff --git a/STM32Sim/stm32-sim/peripherals/src/cryp/mod.rs b/STM32Sim/stm32-sim/peripherals/src/cryp/mod.rs index 82574e4..ff05e15 100644 --- a/STM32Sim/stm32-sim/peripherals/src/cryp/mod.rs +++ b/STM32Sim/stm32-sim/peripherals/src/cryp/mod.rs @@ -19,11 +19,13 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ -//! Shared AES engine for the STM32 CRYP peripheral. +//! Shared cipher engine for the STM32 CRYP peripheral. //! -//! The register-shape adapter (v1 = H7 HAL v1, v2 = U5 HAL v2) is in +//! The register-shape adapter (v1 = F4/H7 HAL v1, v2 = U5 HAL v2) is in //! per-revision modules. This module owns the actual cryptographic -//! state (key, IV, FIFOs) and the per-block transform. +//! state (key, IV, FIFOs) and the per-block transform: AES (16-byte +//! blocks) on every revision, plus DES / TDES (8-byte blocks) on the v1 +//! CRYP found in F2/F4/F7/H7. pub mod gcm; pub mod v1; @@ -32,6 +34,7 @@ pub mod v2; use aes::cipher::generic_array::GenericArray; use aes::cipher::{BlockDecrypt, BlockEncrypt, KeyInit}; use aes::{Aes128, Aes192, Aes256}; +use des::{Des, TdesEde3}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum KeySize { @@ -54,6 +57,24 @@ pub enum AesMode { /// `aes::Aes*::decrypt_block`, so we just need to absorb (and /// silently discard) any DIN that arrives during this phase. KeyDerivation, + /// DES-ECB (v1 ALGOMODE 0b0010). Key K1. + DesEcb, + /// DES-CBC (v1 ALGOMODE 0b0011). Key K1, IV IV0. + DesCbc, + /// TDES-ECB (v1 ALGOMODE 0b0000). Keys K1/K2/K3, EDE. + TdesEcb, + /// TDES-CBC (v1 ALGOMODE 0b0001). Keys K1/K2/K3, IV IV0. + TdesCbc, +} + +impl AesMode { + /// Cipher block length in bytes: 8 for DES/TDES, 16 for AES. + pub fn block_len(self) -> usize { + match self { + AesMode::DesEcb | AesMode::DesCbc | AesMode::TdesEcb | AesMode::TdesCbc => 8, + _ => 16, + } + } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -106,10 +127,13 @@ impl DataType { } } -/// Stateful CRYP engine: a 16-byte input FIFO that triggers a block -/// transform once full, a 16-byte output FIFO drained by DOUT reads. +/// Stateful CRYP engine: an input FIFO that triggers a block transform +/// once it holds one cipher block (16 bytes AES, 8 bytes DES/TDES) and an +/// output FIFO drained by DOUT reads. pub struct CrypEngine { pub key: [u8; 32], + /// DES / TDES key material K1 || K2 || K3 (DES uses K1 only). + pub des_key: [u8; 24], pub iv: [u8; 16], pub key_size: KeySize, pub mode: AesMode, @@ -127,6 +151,7 @@ impl Default for CrypEngine { fn default() -> Self { Self { key: [0; 32], + des_key: [0; 24], iv: [0; 16], key_size: KeySize::K128, mode: AesMode::Ecb, @@ -152,7 +177,7 @@ impl CrypEngine { } pub fn input_full(&self) -> bool { - self.in_len == 16 + self.in_len >= self.mode.block_len() } pub fn input_empty(&self) -> bool { self.in_len == 0 @@ -161,13 +186,14 @@ impl CrypEngine { self.out_avail == 0 } pub fn output_full(&self) -> bool { - self.out_avail == 16 + self.out_avail == self.mode.block_len() } /// Push one DIN word. Triggers a block transform when the FIFO - /// hits 16 bytes. + /// holds one cipher block. pub fn write_din(&mut self, value: u32) { - if !self.enabled || self.in_len >= 16 { + let block_len = self.mode.block_len(); + if !self.enabled || self.in_len >= block_len { return; } let swapped = self.datatype.swap(value); @@ -176,7 +202,7 @@ impl CrypEngine { self.in_buf[self.in_len] = b; self.in_len += 1; } - if self.in_len == 16 { + if self.in_len == block_len { self.process_block(); } } @@ -238,11 +264,40 @@ impl CrypEngine { // the input block on the floor. emit = false; } + AesMode::DesEcb | AesMode::TdesEcb => { + let mut b8 = [0u8; 8]; + b8.copy_from_slice(&block[..8]); + self.des_block(&mut b8); + block[..8].copy_from_slice(&b8); + } + AesMode::DesCbc | AesMode::TdesCbc => { + let mut b8 = [0u8; 8]; + b8.copy_from_slice(&block[..8]); + match self.direction { + Direction::Encrypt => { + for i in 0..8 { + b8[i] ^= self.iv[i]; + } + self.des_block(&mut b8); + self.iv[..8].copy_from_slice(&b8); + } + Direction::Decrypt => { + let mut prev_iv = [0u8; 8]; + prev_iv.copy_from_slice(&self.iv[..8]); + self.iv[..8].copy_from_slice(&b8); + self.des_block(&mut b8); + for i in 0..8 { + b8[i] ^= prev_iv[i]; + } + } + } + block[..8].copy_from_slice(&b8); + } } if emit { self.out_buf = block; self.out_pos = 0; - self.out_avail = 16; + self.out_avail = self.mode.block_len(); } self.in_buf = [0; 16]; self.in_len = 0; @@ -261,6 +316,27 @@ impl CrypEngine { self.out_avail = 16; } + /// DES or TDES (EDE with K1/K2/K3) on one 8-byte block, in the + /// selected direction. + fn des_block(&self, block: &mut [u8; 8]) { + let arr = GenericArray::from_mut_slice(block); + let tdes = matches!(self.mode, AesMode::TdesEcb | AesMode::TdesCbc); + match (tdes, self.direction) { + (false, Direction::Encrypt) => { + Des::new(GenericArray::from_slice(&self.des_key[..8])).encrypt_block(arr) + } + (false, Direction::Decrypt) => { + Des::new(GenericArray::from_slice(&self.des_key[..8])).decrypt_block(arr) + } + (true, Direction::Encrypt) => { + TdesEde3::new(GenericArray::from_slice(&self.des_key)).encrypt_block(arr) + } + (true, Direction::Decrypt) => { + TdesEde3::new(GenericArray::from_slice(&self.des_key)).decrypt_block(arr) + } + } + } + /// Apply the AES round selected by `direction` to `block` in place. fn aes_block(&self, block: &mut [u8; 16]) { match self.direction { diff --git a/STM32Sim/stm32-sim/peripherals/src/cryp/v1.rs b/STM32Sim/stm32-sim/peripherals/src/cryp/v1.rs index a9c282d..b3975f6 100644 --- a/STM32Sim/stm32-sim/peripherals/src/cryp/v1.rs +++ b/STM32Sim/stm32-sim/peripherals/src/cryp/v1.rs @@ -19,7 +19,8 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ -//! STM32H7-style CRYP register file (HAL v1). See RM0433 ยง35. +//! STM32F2/F4/F7/H7-style CRYP register file (HAL v1). See RM0090 section 23 +//! (F4) and RM0433 section 35 (H7). //! //! Register map (1 KiB peripheral, 4 KiB page on the bus): //! 0x00 CR Control @@ -30,8 +31,15 @@ //! 0x14 IMSCR Interrupt mask //! 0x18 RISR Raw interrupt status //! 0x1C MISR Masked interrupt status -//! 0x20..0x3C K0LR..K3RR (8 words = 256-bit key) -//! 0x40..0x4C IV0LR..IV1RR (4 words = 128-bit IV) +//! 0x20..0x3C K0LR..K3RR (8 words = 256-bit key; DES uses K1, +//! TDES uses K1/K2/K3) +//! 0x40..0x4C IV0LR..IV1RR (4 words = 128-bit IV; DES/TDES use IV0) +//! +//! ALGOMODE: 0b0000 TDES-ECB, 0b0001 TDES-CBC, 0b0010 DES-ECB, +//! 0b0011 DES-CBC, 0b0100 AES-ECB, 0b0101 AES-CBC, 0b0110 AES-CTR, +//! 0b0111 AES key preparation, 0b1000 AES-GCM. The F405/F415/F417 CRYP +//! predates GCM/CCM: ALGOMODE[3] (bit 19) and GCM_CCMPH (bits 17:16) are +//! reserved there, see [`CrypV1::new_f4`]. use stm32_sim_core::peripheral::Peripheral; @@ -69,6 +77,8 @@ const CR_GCMPH_SHIFT: u32 = 16; const CR_GCMPH_MASK: u32 = 0x3 << CR_GCMPH_SHIFT; pub struct CrypV1 { + /// False on the F405/F415/F417 CRYP, which has no GCM/CCM. + gcm_capable: bool, cr: u32, key_regs: [u32; 8], iv_regs: [u32; 4], @@ -89,8 +99,21 @@ impl Default for CrypV1 { } impl CrypV1 { + /// F7/H7-style CRYP: DES/TDES/AES including GCM. pub fn new() -> Self { + Self::with_gcm(true) + } + + /// F405/F415/F417-style CRYP: DES/TDES and AES ECB/CBC/CTR only. + /// The GCM/CCM control bits are reserved, so writes to them are + /// dropped as silicon drops them. + pub fn new_f4() -> Self { + Self::with_gcm(false) + } + + fn with_gcm(gcm_capable: bool) -> Self { Self { + gcm_capable, cr: 0, key_regs: [0; 8], iv_regs: [0; 4], @@ -144,6 +167,11 @@ impl CrypV1 { fn write_cr(&mut self, value: u32) { let was_enabled = self.cr & CR_CRYPEN != 0; let prev_cr = self.cr; + let value = if self.gcm_capable { + value + } else { + value & !(CR_ALGOMODE_HI | CR_GCMPH_MASK) + }; self.cr = value & !CR_FFLUSH; // FFLUSH self-clears if value & CR_FFLUSH != 0 { @@ -209,6 +237,10 @@ impl CrypV1 { let algomode = algomode_low | if self.cr & CR_ALGOMODE_HI != 0 { 0x8 } else { 0 }; self.engine.mode = match algomode { + 0b0000 => AesMode::TdesEcb, + 0b0001 => AesMode::TdesCbc, + 0b0010 => AesMode::DesEcb, + 0b0011 => AesMode::DesCbc, 0b0100 => AesMode::Ecb, 0b0101 => AesMode::Cbc, 0b0110 => AesMode::Ctr, @@ -216,7 +248,7 @@ impl CrypV1 { 0b1000 => AesMode::Gcm, other => { log::warn!( - "CRYP v1: unsupported ALGOMODE 0x{:x} (modelled: AES ECB/CBC/CTR/GCM)", + "CRYP v1: unsupported ALGOMODE 0x{:x} (modelled: DES/TDES ECB/CBC, AES ECB/CBC/CTR/GCM)", other ); AesMode::Ecb @@ -224,6 +256,7 @@ impl CrypV1 { }; self.engine.key = expand_key(&self.key_regs, self.engine.key_size); + self.engine.des_key = expand_des_key(&self.key_regs); self.engine.iv = expand_iv(&self.iv_regs); self.engine.reset_fifos(); self.gcm_in_buf = [0; 16]; @@ -239,6 +272,21 @@ impl CrypV1 { } } + /// The IV registers track the chaining value as blocks are processed + /// (CBC: the last ciphertext block, CTR: the counter); RM0090's + /// context-swap procedure saves them for exactly that reason, and + /// wolfSSL's HAL_V2 DES path reads IV0LR/IV0RR back as the next call's + /// IV. + fn sync_iv_regs(&mut self) { + if !self.engine.enabled { + return; + } + for (i, reg) in self.iv_regs.iter_mut().enumerate() { + let b = &self.engine.iv[i * 4..i * 4 + 4]; + *reg = u32::from_be_bytes([b[0], b[1], b[2], b[3]]); + } + } + fn compute_sr(&self) -> u32 { // STM32H7 CRYP_SR: bit 0 IFEM (input FIFO empty), bit 1 IFNF // (input FIFO not full), bit 2 OFNE (output not empty), bit 3 @@ -291,6 +339,16 @@ fn expand_key(regs: &[u32; 8], size: KeySize) -> [u8; 32] { out } +/// DES / TDES key material: K1LR..K3RR (registers 2..8) in order. DES +/// only uses the first 8 bytes (K1). +fn expand_des_key(regs: &[u32; 8]) -> [u8; 24] { + let mut out = [0u8; 24]; + for (i, w) in regs[2..].iter().enumerate() { + out[i * 4..i * 4 + 4].copy_from_slice(&w.to_be_bytes()); + } + out +} + fn expand_iv(regs: &[u32; 4]) -> [u8; 16] { let mut out = [0u8; 16]; for (i, w) in regs.iter().enumerate() { @@ -333,6 +391,7 @@ impl Peripheral for CrypV1 { self.gcm_din(value); } else { self.engine.write_din(value); + self.sync_iv_regs(); } } DMACR => self.dmacr = value, @@ -347,6 +406,7 @@ impl Peripheral for CrypV1 { // write so the next block sees the latest bytes. if self.engine.enabled { self.engine.key = expand_key(&self.key_regs, self.engine.key_size); + self.engine.des_key = expand_des_key(&self.key_regs); } } o if (IV_BASE..=IV_END).contains(&o) => { @@ -590,4 +650,126 @@ mod tests { assert_eq!(read_word(&mut p, 0x0C), 0xeafc4990); assert_eq!(read_word(&mut p, 0x0C), 0x4b496089); } + + fn write_words(p: &mut CrypV1, off: u32, words: &[u32]) { + for w in words { + write_word(p, off, *w); + } + } + + fn read_words(p: &mut CrypV1, n: usize) -> Vec { + (0..n).map(|_| read_word(p, 0x0C)).collect() + } + + /// Classic single-DES worked example: + /// K = 133457799bbcdff1, PT = 0123456789abcdef, CT = 85e813540f0ab405. + #[test] + fn des_ecb_kat() { + let mut p = CrypV1::new_f4(); + write_word(&mut p, 0x28, 0x13345779); // K1LR + write_word(&mut p, 0x2C, 0x9bbcdff1); // K1RR + write_word(&mut p, 0x00, (0b010 << 3) | CR_CRYPEN); + write_words(&mut p, 0x08, &[0x01234567, 0x89abcdef]); + assert_eq!(read_words(&mut p, 2), [0x85e81354, 0x0f0ab405]); + + let mut p = CrypV1::new_f4(); + write_word(&mut p, 0x28, 0x13345779); + write_word(&mut p, 0x2C, 0x9bbcdff1); + write_word(&mut p, 0x00, (0b010 << 3) | CR_ALGODIR | CR_CRYPEN); + write_words(&mut p, 0x08, &[0x85e81354, 0x0f0ab405]); + assert_eq!(read_words(&mut p, 2), [0x01234567, 0x89abcdef]); + } + + /// wolfCrypt des_cbc_test vector, driven with DATATYPE=byte the way + /// wolfSSL's STM32 port feeds the CRYP. + #[test] + fn des_cbc_wolfcrypt_vector() { + let pt = b"now is the time for all "; + let ct: [u8; 24] = [ + 0x8b, 0x7c, 0x52, 0xb0, 0x01, 0x2b, 0x6c, 0xb8, 0x4f, 0x0f, 0xeb, 0xf3, 0xfb, 0x5f, + 0x86, 0x73, 0x15, 0x85, 0xb3, 0x22, 0x4b, 0x86, 0x2b, 0x4b, + ]; + let le = |b: &[u8]| u32::from_le_bytes([b[0], b[1], b[2], b[3]]); + + for (dir, input, expect) in [(0, &pt[..], &ct[..]), (CR_ALGODIR, &ct[..], &pt[..])] { + let mut p = CrypV1::new_f4(); + write_word(&mut p, 0x28, 0x01234567); + write_word(&mut p, 0x2C, 0x89abcdef); + write_word(&mut p, 0x40, 0x12345678); + write_word(&mut p, 0x44, 0x90abcdef); + write_word(&mut p, 0x00, (0b011 << 3) | (0b10 << CR_DATATYPE_SHIFT) | dir | CR_CRYPEN); + let mut out = Vec::new(); + for blk in input.chunks(8) { + write_word(&mut p, 0x08, le(&blk[0..4])); + write_word(&mut p, 0x08, le(&blk[4..8])); + for w in read_words(&mut p, 2) { + out.extend_from_slice(&w.to_le_bytes()); + } + } + assert_eq!(out.as_slice(), expect); + } + } + + /// NIST SP 800-67 TDES example (K1 0123456789abcdef, K2 + /// 23456789abcdef01, K3 456789abcdef0123, PT "The qufck brown fox + /// jump"), ECB, plus the same input in CBC with IV 1234567890abcdef + /// (expected values cross-checked with OpenSSL des-ede3 / + /// des-ede3-cbc). + #[test] + fn tdes_ecb_and_cbc_kats() { + let keys = [0x01234567, 0x89abcdef, 0x23456789, 0xabcdef01, 0x456789ab, 0xcdef0123]; + let pt = [0x54686520, 0x71756663, 0x6b206272, 0x6f776e20, 0x666f7820, 0x6a756d70]; + let ecb = [0xa826fd8c, 0xe53b855f, 0xcce21c81, 0x12256fe6, 0x68d5c05d, 0xd9b6b900]; + let cbc = [0x38413d4b, 0xa2325cf1, 0x141f7074, 0x71ac2ced, 0x57db530f, 0x0123b5ac]; + + for (algo, expect) in [(0b000u32, ecb), (0b001u32, cbc)] { + for (dir, input, output) in [(0, pt, expect), (CR_ALGODIR, expect, pt)] { + let mut p = CrypV1::new_f4(); + for (i, k) in keys.iter().enumerate() { + write_word(&mut p, 0x28 + 4 * i as u32, *k); + } + write_word(&mut p, 0x40, 0x12345678); + write_word(&mut p, 0x44, 0x90abcdef); + write_word(&mut p, 0x00, (algo << 3) | dir | CR_CRYPEN); + let mut out = Vec::new(); + for blk in input.chunks(2) { + write_words(&mut p, 0x08, blk); + out.extend(read_words(&mut p, 2)); + } + assert_eq!(out.as_slice(), &output, "algo {algo:#b} dir {dir:#x}"); + } + } + } + + /// On the F417 CRYP, ALGOMODE[3] is reserved: asking for GCM + /// (ALGOMODE 0b1000) leaves ALGOMODE 0b000, i.e. TDES-ECB, and the + /// GCM_CCMPH bits read back as zero. + #[test] + fn f4_cryp_has_no_gcm() { + let mut p = CrypV1::new_f4(); + write_word(&mut p, 0x00, CR_ALGOMODE_HI | (1 << 16) | CR_CRYPEN); + assert_eq!(read_word(&mut p, 0x00), CR_CRYPEN); + assert_eq!(p.engine.mode, AesMode::TdesEcb); + + let mut p = CrypV1::new(); + write_word(&mut p, 0x00, CR_ALGOMODE_HI | CR_CRYPEN); + assert_eq!(p.engine.mode, AesMode::Gcm); + } + + /// After a CBC block the IV registers hold the last ciphertext block, + /// so firmware can read them back as the IV for the next call. + #[test] + fn cbc_iv_registers_track_chaining_value() { + let mut p = CrypV1::new_f4(); + write_word(&mut p, 0x28, 0x01234567); + write_word(&mut p, 0x2C, 0x89abcdef); + write_word(&mut p, 0x40, 0x12345678); + write_word(&mut p, 0x44, 0x90abcdef); + write_word(&mut p, 0x00, (0b011 << 3) | CR_CRYPEN); + write_words(&mut p, 0x08, &[0x6e6f7720, 0x69732074]); + let ct = read_words(&mut p, 2); + assert_eq!(ct, [0x8b7c52b0, 0x012b6cb8]); + assert_eq!(read_word(&mut p, 0x40), ct[0]); + assert_eq!(read_word(&mut p, 0x44), ct[1]); + } } diff --git a/STM32Sim/stm32-sim/peripherals/src/hash/v1.rs b/STM32Sim/stm32-sim/peripherals/src/hash/v1.rs index fa30fbc..942909f 100644 --- a/STM32Sim/stm32-sim/peripherals/src/hash/v1.rs +++ b/STM32Sim/stm32-sim/peripherals/src/hash/v1.rs @@ -103,6 +103,12 @@ pub enum AlgoLayout { /// 12..15). The SHA3CFGR register at offset 0x28 supplies extra /// padding / round metadata that we model as a write-back store. Mp13, + /// F405/F415/F417 (and F2) HASH: 1-bit ALGO at CR bit 7, SHA-1 or + /// MD5 only. Bit 18 is reserved on these parts (the SHA-224/256 + /// ALGO[1] bit arrived with F437/F439), so it is ignored exactly as + /// silicon ignores it, and the extended HR window at 0x310 does not + /// exist. + F4, } impl AlgoLayout { @@ -186,6 +192,11 @@ impl HashV1 { Self::with_layout(AlgoLayout::Mp13) } + /// F405/F415/F417 layout: SHA-1 and MD5 only. + pub fn new_f4() -> Self { + Self::with_layout(AlgoLayout::F4) + } + fn with_layout(layout: AlgoLayout) -> Self { Self { layout, @@ -242,7 +253,8 @@ impl HashV1 { } } else { let lo_bit = 1u32 << self.layout_lo_bit(); - let hi_bit = 1u32 << 18; + // F4 (F405/F415/F417) has no ALGO[1]: bit 18 is reserved. + let hi_bit = if self.layout == AlgoLayout::F4 { 0 } else { 1u32 << 18 }; let lo = if self.cr & lo_bit != 0 { 1u32 } else { 0 }; let hi = if self.cr & hi_bit != 0 { 1u32 } else { 0 }; match (hi, lo) { @@ -257,7 +269,7 @@ impl HashV1 { fn layout_lo_bit(&self) -> u32 { match self.layout { - AlgoLayout::H7 => 7, + AlgoLayout::H7 | AlgoLayout::F4 => 7, AlgoLayout::U5 => 17, // Unused on MP13 - that path takes the 4-bit branch in // parse_algo. We still need a value to type-check. @@ -360,7 +372,7 @@ impl Peripheral for HashV1 { let idx = ((o - HR_LEGACY_BASE) / 4) as usize; self.read_hr(idx) } - o if (HR_EXT_BASE..=HR_EXT_END).contains(&o) => { + o if (HR_EXT_BASE..=HR_EXT_END).contains(&o) && self.layout != AlgoLayout::F4 => { let idx = ((o - HR_EXT_BASE) / 4) as usize; self.read_hr(idx) } @@ -670,4 +682,31 @@ mod tests { let expected = [0xd41d8cd9, 0x8f00b204, 0xe9800998, 0xecf8427e]; assert_eq!(hr.as_slice(), &expected); } + + /// F405/F415/F417 HASH has no ALGO[1] (bit 18), so a SHA-256 request + /// (bits 18 and 7) runs MD5 and a SHA-224 request (bit 18) runs SHA-1, + /// exactly as the silicon does; the SHA-256 result window is absent. + #[test] + fn f4_layout_ignores_algo_bit_18() { + let mut p = HashV1::new_f4(); + write_word(&mut p, CR, CR_ALGO_HI | CR_ALGO_LO | CR_INIT); + write_word(&mut p, STR, STR_DCAL); + let hr: Vec = (0..4) + .map(|i| read_word(&mut p, HR_LEGACY_BASE + i * 4)) + .collect(); + assert_eq!(hr.as_slice(), &[0xd41d8cd9, 0x8f00b204, 0xe9800998, 0xecf8427e]); + assert_eq!(read_word(&mut p, HR_EXT_BASE), 0); + + let mut p = HashV1::new_f4(); + write_word(&mut p, CR, CR_ALGO_HI | CR_INIT); + write_word(&mut p, DIN, 0x6162_6300); + write_word(&mut p, STR, STR_DCAL | 24); + let hr: Vec = (0..5) + .map(|i| read_word(&mut p, HR_LEGACY_BASE + i * 4)) + .collect(); + assert_eq!( + hr.as_slice(), + &[0xa9993e36, 0x4706816a, 0xba3e2571, 0x7850c26c, 0x9cd0d89d] + ); + } } diff --git a/STM32Sim/stm32-sim/peripherals/src/lib.rs b/STM32Sim/stm32-sim/peripherals/src/lib.rs index d1850e6..c45a416 100644 --- a/STM32Sim/stm32-sim/peripherals/src/lib.rs +++ b/STM32Sim/stm32-sim/peripherals/src/lib.rs @@ -33,5 +33,5 @@ pub use dbgmcu::Dbgmcu; pub use hash::v1::HashV1; pub use pka::v2::PkaV2; pub use rcc::Rcc; -pub use rng::Rng; -pub use usart::{Usart, UsartSink}; +pub use rng::{Rng, RngFault, RngFaultKind}; +pub use usart::{Usart, UsartLayout, UsartSink}; diff --git a/STM32Sim/stm32-sim/peripherals/src/rcc.rs b/STM32Sim/stm32-sim/peripherals/src/rcc.rs index a9a0390..99d7cef 100644 --- a/STM32Sim/stm32-sim/peripherals/src/rcc.rs +++ b/STM32Sim/stm32-sim/peripherals/src/rcc.rs @@ -77,6 +77,18 @@ impl Rcc { )); me } + + /// STM32F2/F4 RCC ready bits. CR @ 0x00: HSIRDY(1), HSERDY(17), + /// PLLRDY(25), PLLI2SRDY(27). BDCR @ 0x70: LSERDY(1). CSR @ 0x74: + /// LSIRDY(1). + pub fn f4() -> Self { + let mut me = Self::raw("rcc-f4"); + me.ready_offsets + .push((0x00, (1 << 1) | (1 << 17) | (1 << 25) | (1 << 27))); + me.ready_offsets.push((0x70, 1 << 1)); + me.ready_offsets.push((0x74, 1 << 1)); + me + } } impl Peripheral for Rcc { diff --git a/STM32Sim/stm32-sim/peripherals/src/rng.rs b/STM32Sim/stm32-sim/peripherals/src/rng.rs index 8dd198e..28b3b0b 100644 --- a/STM32Sim/stm32-sim/peripherals/src/rng.rs +++ b/STM32Sim/stm32-sim/peripherals/src/rng.rs @@ -19,18 +19,125 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ +use std::fmt; +use std::str::FromStr; + use rand::{RngCore, SeedableRng}; use rand_chacha::ChaCha20Rng; use stm32_sim_core::peripheral::Peripheral; -/// STM32 RNG peripheral. Register layout is identical across H7/U5/L4: +const CR: u32 = 0x00; +const SR: u32 = 0x04; +const DR: u32 = 0x08; + +const CR_RNGEN: u32 = 1 << 2; + +const SR_DRDY: u32 = 1 << 0; +const SR_CECS: u32 = 1 << 1; +const SR_SECS: u32 = 1 << 2; +const SR_CEIS: u32 = 1 << 5; +const SR_SEIS: u32 = 1 << 6; + +/// Number of SR reads a non-sticky clock error stays asserted for before +/// the (modelled) kernel clock comes back. +const CLOCK_GLITCH_SR_READS: u32 = 64; + +/// Which RNG error condition to inject. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RngFaultKind { + /// Seed error: the entropy source failed its health checks. SECS and + /// SEIS latch and generation stops until software runs the recovery + /// sequence (clear SEIS, then cycle RNGEN). + Seed, + /// Clock error: the RNG kernel clock is too slow (or gone). CECS and + /// CEIS latch and DRDY stops until the clock comes back. + Clock, +} + +/// An RNG fault to inject after a set number of DR reads. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct RngFault { + pub kind: RngFaultKind, + /// DR reads served normally before the fault latches. + pub after_reads: u64, + /// A sticky fault never clears: a dead entropy source or a kernel + /// clock that never returns. Otherwise a seed error clears once + /// software runs the recovery sequence and a clock error clears on + /// its own after a short glitch. + pub sticky: bool, +} + +impl FromStr for RngFault { + type Err = String; + + /// Parses `:[:sticky]`. + fn from_str(s: &str) -> Result { + let parts: Vec<&str> = s.split(':').collect(); + if parts.len() < 2 || parts.len() > 3 { + return Err(format!( + "expected :[:sticky], got `{s}`" + )); + } + let kind = match parts[0] { + "seed" => RngFaultKind::Seed, + "clock" => RngFaultKind::Clock, + other => return Err(format!("unknown RNG fault kind `{other}`")), + }; + let after_reads = parts[1] + .parse::() + .map_err(|e| format!("bad DR read count `{}`: {e}", parts[1]))?; + let sticky = match parts.get(2) { + None => false, + Some(&"sticky") => true, + Some(other) => return Err(format!("unknown RNG fault flag `{other}`")), + }; + Ok(Self { + kind, + after_reads, + sticky, + }) + } +} + +impl fmt::Display for RngFault { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let kind = match self.kind { + RngFaultKind::Seed => "seed", + RngFaultKind::Clock => "clock", + }; + write!(f, "{kind}:{}", self.after_reads)?; + if self.sticky { + write!(f, ":sticky")?; + } + Ok(()) + } +} + +/// STM32 RNG peripheral. Register layout is identical across F2/F4/H7/U5/L4: /// 0x00 CR 0x04 SR 0x08 DR -/// On read of DR we always have data ready (DRDY=1) and never report -/// SECS/CECS errors. Optional fixed seeding makes tests deterministic. +/// +/// A healthy RNG always has data ready (DRDY=1) and never reports +/// SECS/CECS. An optional injected fault (see [`RngFault`]) models the +/// error management described in the F2/F4 reference manuals (RM0033 / +/// RM0090 "Error management"): while a seed or clock error is current, +/// DRDY stays low and DR holds no fresh data. Optional fixed seeding makes +/// tests deterministic. pub struct Rng { rng: ChaCha20Rng, cr: u32, + /// Software-visible SR bits other than DRDY / CECS / SECS, i.e. the + /// CEIS / SEIS interrupt flags (write 0 to clear). sr: u32, + fault: Option, + dr_reads: u64, + /// The fault has latched (it only latches once per run). + fault_fired: bool, + /// A seed or clock error is current (SECS / CECS set, DRDY held low). + error_current: bool, + /// Seed-error recovery progress: RNGEN observed low after the fault. + rngen_dropped: bool, + /// Clock-error recovery progress: SR reads since the fault latched. + glitch_reads: u32, } impl Rng { @@ -41,12 +148,103 @@ impl Rng { rng: ChaCha20Rng::seed_from_u64(seed), cr: 0, sr: 0, + fault: None, + dr_reads: 0, + fault_fired: false, + error_current: false, + rngen_dropped: false, + glitch_reads: 0, } } pub fn new() -> Self { Self::with_seed(0xDEAD_BEEF_CAFE_BABE) } + + /// Arm a fault that latches after `fault.after_reads` DR reads. + pub fn with_fault(mut self, fault: Option) -> Self { + self.fault = fault; + self + } + + fn maybe_latch_fault(&mut self) { + let Some(fault) = self.fault else { return }; + if self.fault_fired || self.dr_reads < fault.after_reads { + return; + } + self.fault_fired = true; + self.error_current = true; + self.rngen_dropped = false; + self.glitch_reads = 0; + self.sr |= match fault.kind { + RngFaultKind::Seed => SR_SEIS, + RngFaultKind::Clock => SR_CEIS, + }; + log::info!("rng: injected {fault} fault after {} DR reads", self.dr_reads); + } + + fn current_error_bits(&self) -> u32 { + match (self.error_current, self.fault.map(|f| f.kind)) { + (true, Some(RngFaultKind::Seed)) => SR_SECS, + (true, Some(RngFaultKind::Clock)) => SR_CECS, + _ => 0, + } + } + + fn clear_error(&mut self) { + if self.error_current { + self.error_current = false; + log::info!("rng: injected fault cleared"); + } + } + + fn read_sr(&mut self) -> u32 { + if self.error_current { + if let Some(f) = self.fault { + if f.kind == RngFaultKind::Clock && !f.sticky { + self.glitch_reads += 1; + if self.glitch_reads >= CLOCK_GLITCH_SR_READS { + self.clear_error(); + } + } + } + } + let drdy = if self.error_current { 0 } else { SR_DRDY }; + self.sr | self.current_error_bits() | drdy + } + + fn read_dr(&mut self) -> u32 { + if self.error_current { + return 0; + } + let v = self.rng.next_u32(); + self.dr_reads += 1; + self.maybe_latch_fault(); + v + } + + fn write_cr(&mut self, value: u32) { + let was_enabled = self.cr & CR_RNGEN != 0; + let now_enabled = value & CR_RNGEN != 0; + self.cr = value; + + let Some(f) = self.fault else { return }; + if !self.error_current || f.kind != RngFaultKind::Seed || f.sticky { + return; + } + if was_enabled && !now_enabled { + self.rngen_dropped = true; + } else if !was_enabled && now_enabled && self.rngen_dropped && self.sr & SR_SEIS == 0 { + // RM0090 seed-error recovery: SEIS cleared, then RNGEN cycled. + self.clear_error(); + } + } + + fn write_sr(&mut self, value: u32) { + // Only CEIS / SEIS are writable, and only to 0 (rc_w0). + let clear = !value & (SR_CEIS | SR_SEIS); + self.sr &= !clear; + } } impl Default for Rng { @@ -62,18 +260,134 @@ impl Peripheral for Rng { fn read(&mut self, offset: u32, _size: u8) -> u32 { match offset { - 0x00 => self.cr, - 0x04 => self.sr | 0x1, // SR.DRDY - 0x08 => self.rng.next_u32(), + CR => self.cr, + SR => self.read_sr(), + DR => self.read_dr(), _ => 0, } } fn write(&mut self, offset: u32, _size: u8, value: u32) { match offset { - 0x00 => self.cr = value, - 0x04 => self.sr = value & !0x1, // DRDY is RO + CR => self.write_cr(value), + SR => self.write_sr(value), _ => {} } } } + +#[cfg(test)] +mod tests { + use super::*; + + fn fault(s: &str) -> Option { + Some(s.parse().unwrap()) + } + + fn drain(r: &mut Rng, n: u64) { + for _ in 0..n { + assert_ne!(r.read(SR, 4) & SR_DRDY, 0); + r.read(DR, 4); + } + } + + #[test] + fn parses_fault_specs() { + assert_eq!( + "seed:10".parse::().unwrap(), + RngFault { + kind: RngFaultKind::Seed, + after_reads: 10, + sticky: false + } + ); + assert_eq!( + "clock:0:sticky".parse::().unwrap(), + RngFault { + kind: RngFaultKind::Clock, + after_reads: 0, + sticky: true + } + ); + assert!("seed".parse::().is_err()); + assert!("noise:1".parse::().is_err()); + assert!("seed:x".parse::().is_err()); + assert!("seed:1:forever".parse::().is_err()); + assert_eq!( + "clock:7:sticky".parse::().unwrap().to_string(), + "clock:7:sticky" + ); + } + + #[test] + fn healthy_rng_always_ready() { + let mut r = Rng::new(); + r.write(CR, 4, CR_RNGEN); + drain(&mut r, 1000); + assert_eq!(r.read(SR, 4), SR_DRDY); + } + + #[test] + fn seed_error_latches_and_recovers_per_rm() { + let mut r = Rng::new().with_fault(fault("seed:4")); + r.write(CR, 4, CR_RNGEN); + drain(&mut r, 4); + + assert_eq!(r.read(SR, 4), SR_SECS | SR_SEIS); + assert_eq!(r.read(DR, 4), 0); + + // Cycling RNGEN without clearing SEIS first does not recover. + r.write(CR, 4, 0); + r.write(CR, 4, CR_RNGEN); + assert_eq!(r.read(SR, 4) & SR_DRDY, 0); + + // Clear SEIS, then cycle RNGEN. + r.write(SR, 4, 0); + assert_eq!(r.read(SR, 4), SR_SECS); + r.write(CR, 4, 0); + r.write(CR, 4, CR_RNGEN); + assert_eq!(r.read(SR, 4), SR_DRDY); + // The fault only fires once. + drain(&mut r, 100); + } + + #[test] + fn sticky_seed_error_never_recovers() { + let mut r = Rng::new().with_fault(fault("seed:0:sticky")); + r.write(CR, 4, CR_RNGEN); + r.read(DR, 4); + for _ in 0..4 { + r.write(SR, 4, 0); + r.write(CR, 4, 0); + r.write(CR, 4, CR_RNGEN); + assert_eq!(r.read(SR, 4), SR_SECS); + } + } + + #[test] + fn clock_glitch_clears_by_itself() { + let mut r = Rng::new().with_fault(fault("clock:2")); + r.write(CR, 4, CR_RNGEN); + drain(&mut r, 2); + assert_eq!(r.read(SR, 4), SR_CECS | SR_CEIS); + let mut polls = 1; + while r.read(SR, 4) & SR_DRDY == 0 { + polls += 1; + assert!(polls <= CLOCK_GLITCH_SR_READS, "clock glitch never cleared"); + } + // CEIS stays latched until software clears it. + assert_eq!(r.read(SR, 4), SR_DRDY | SR_CEIS); + r.write(SR, 4, !SR_CEIS); + assert_eq!(r.read(SR, 4), SR_DRDY); + } + + #[test] + fn sticky_clock_error_holds_drdy_low() { + let mut r = Rng::new().with_fault(fault("clock:1:sticky")); + r.write(CR, 4, CR_RNGEN); + drain(&mut r, 1); + for _ in 0..(CLOCK_GLITCH_SR_READS * 4) { + assert_eq!(r.read(SR, 4), SR_CECS | SR_CEIS); + } + } +} diff --git a/STM32Sim/stm32-sim/peripherals/src/usart.rs b/STM32Sim/stm32-sim/peripherals/src/usart.rs index 2f98cf0..7aa4551 100644 --- a/STM32Sim/stm32-sim/peripherals/src/usart.rs +++ b/STM32Sim/stm32-sim/peripherals/src/usart.rs @@ -66,28 +66,56 @@ impl UsartSink for CapturingSink { } } -/// STM32 H7/U5 USART register layout (the F4/F7 layout differs and is -/// not modelled here yet). Offsets: -/// 0x00 CR1 0x04 CR2 0x08 CR3 0x0C BRR -/// 0x1C ISR 0x20 ICR 0x24 RDR 0x28 TDR +/// USART register layout generation. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum UsartLayout { + /// H7/U5/MP13 (and F7/L4) layout: + /// 0x00 CR1 0x04 CR2 0x08 CR3 0x0C BRR + /// 0x1C ISR 0x20 ICR 0x24 RDR 0x28 TDR + Modern, + /// F1/F2/F4 layout: + /// 0x00 SR 0x04 DR 0x08 BRR 0x0C CR1 + /// 0x10 CR2 0x14 CR3 0x18 GTPR + Legacy, +} + +/// STM32 USART, transmit side only. TXE and TC always read as set so +/// firmware never blocks waiting for the transmitter. pub struct Usart { name: &'static str, + layout: UsartLayout, sink: Box, cr1: u32, cr2: u32, cr3: u32, brr: u32, + gtpr: u32, } +/// ISR / SR bits 7 (TXE) and 6 (TC); the same positions in both layouts. +const TX_READY: u32 = 0x0000_00C0; + impl Usart { + /// H7/U5-style USART. pub fn new(name: &'static str, sink: Box) -> Self { + Self::with_layout(name, UsartLayout::Modern, sink) + } + + /// F1/F2/F4-style USART. + pub fn new_legacy(name: &'static str, sink: Box) -> Self { + Self::with_layout(name, UsartLayout::Legacy, sink) + } + + pub fn with_layout(name: &'static str, layout: UsartLayout, sink: Box) -> Self { Self { name, + layout, sink, cr1: 0, cr2: 0, cr3: 0, brr: 0, + gtpr: 0, } } } @@ -98,27 +126,65 @@ impl Peripheral for Usart { } fn read(&mut self, offset: u32, _size: u8) -> u32 { - match offset { - 0x00 => self.cr1, - 0x04 => self.cr2, - 0x08 => self.cr3, - 0x0C => self.brr, - // ISR: TXE_TXFNF (bit 7) and TC (bit 6) always set so firmware - // never blocks waiting for the TX FIFO to drain. - 0x1C => 0x0000_00C0, + match (self.layout, offset) { + (UsartLayout::Modern, 0x00) => self.cr1, + (UsartLayout::Modern, 0x04) => self.cr2, + (UsartLayout::Modern, 0x08) => self.cr3, + (UsartLayout::Modern, 0x0C) => self.brr, + (UsartLayout::Modern, 0x1C) => TX_READY, // ISR + (UsartLayout::Legacy, 0x00) => TX_READY, // SR + (UsartLayout::Legacy, 0x08) => self.brr, + (UsartLayout::Legacy, 0x0C) => self.cr1, + (UsartLayout::Legacy, 0x10) => self.cr2, + (UsartLayout::Legacy, 0x14) => self.cr3, + (UsartLayout::Legacy, 0x18) => self.gtpr, _ => 0, } } fn write(&mut self, offset: u32, _size: u8, value: u32) { - match offset { - 0x00 => self.cr1 = value, - 0x04 => self.cr2 = value, - 0x08 => self.cr3 = value, - 0x0C => self.brr = value, - 0x20 => {} // ICR write-1-to-clear, no-op for stub - 0x28 => self.sink.write_byte((value & 0xFF) as u8), // TDR - _ => {} + match (self.layout, offset) { + (UsartLayout::Modern, 0x00) => self.cr1 = value, + (UsartLayout::Modern, 0x04) => self.cr2 = value, + (UsartLayout::Modern, 0x08) => self.cr3 = value, + (UsartLayout::Modern, 0x0C) => self.brr = value, + (UsartLayout::Modern, 0x28) => self.sink.write_byte((value & 0xFF) as u8), // TDR + (UsartLayout::Legacy, 0x04) => self.sink.write_byte((value & 0xFF) as u8), // DR + (UsartLayout::Legacy, 0x08) => self.brr = value, + (UsartLayout::Legacy, 0x0C) => self.cr1 = value, + (UsartLayout::Legacy, 0x10) => self.cr2 = value, + (UsartLayout::Legacy, 0x14) => self.cr3 = value, + (UsartLayout::Legacy, 0x18) => self.gtpr = value, + _ => {} // ICR (modern) / SR clears (legacy): no-op for the stub } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn legacy_layout_transmits_on_dr() { + let sink = CapturingSink::new(); + let mut u = Usart::new_legacy("usart2", Box::new(sink.clone())); + u.write(0x0C, 4, 0x200C); // CR1: UE | TE | RE + assert_eq!(u.read(0x0C, 4), 0x200C); + assert_eq!(u.read(0x00, 4) & TX_READY, TX_READY); + for b in b"ok" { + u.write(0x04, 4, *b as u32); + } + u.write(0x28, 4, b'x' as u32); // TDR offset means nothing here + assert_eq!(sink.snapshot(), b"ok"); + } + + #[test] + fn modern_layout_transmits_on_tdr() { + let sink = CapturingSink::new(); + let mut u = Usart::new("usart3", Box::new(sink.clone())); + u.write(0x04, 4, b'x' as u32); // CR2, not data + u.write(0x28, 4, b'h' as u32); + assert_eq!(u.read(0x1C, 4), TX_READY); + assert_eq!(sink.snapshot(), b"h"); + } +} diff --git a/STM32Sim/stm32-sim/runner-bin/src/main.rs b/STM32Sim/stm32-sim/runner-bin/src/main.rs index 26b87d7..a5bd5d9 100644 --- a/STM32Sim/stm32-sim/runner-bin/src/main.rs +++ b/STM32Sim/stm32-sim/runner-bin/src/main.rs @@ -25,7 +25,9 @@ use std::path::PathBuf; use std::process::ExitCode; use std::time::Duration; +use stm32_sim_chips::ChipOptions; use stm32_sim_core::{Cpu, ElfImage, ExitCondition, RunOutcome, Runner}; +use stm32_sim_peripherals::RngFault; #[derive(Parser, Debug)] #[command(version, about = "wolfSSL STM32 simulator runner")] @@ -51,6 +53,13 @@ struct Args { #[arg(long)] list_chips: bool, + /// Inject an RNG fault after a number of RNG_DR reads: + /// `seed:` (seed error; clears once firmware clears SEIS and + /// cycles RNGEN), `clock:` (clock error; clears by itself after + /// a short glitch). Append `:sticky` for a fault that never clears. + #[arg(long, value_name = "KIND:READS[:sticky]")] + rng_fault: Option, + /// ELF file to load. elf: Option, } @@ -81,7 +90,10 @@ fn run(args: Args) -> Result { .clone() .ok_or_else(|| anyhow!("ELF path required (or pass --list-chips)"))?; - let chip = stm32_sim_chips::build(&args.chip)?; + let opts = ChipOptions { + rng_fault: args.rng_fault, + }; + let chip = stm32_sim_chips::build_with(&args.chip, &opts)?; let image = ElfImage::from_path_with_kind(&elf_path, chip.cpu_kind) .with_context(|| format!("loading {}", elf_path.display()))?; @@ -122,8 +134,8 @@ fn run(args: Args) -> Result { log::error!("FAIL (result={result}, elapsed={:?})", elapsed); Ok(ExitCode::FAILURE) } - RunOutcome::Timeout { elapsed } => { - log::error!("TIMEOUT after {:?}", elapsed); + RunOutcome::Timeout { pc, elapsed } => { + log::error!("TIMEOUT after {:?} at PC=0x{pc:08x}", elapsed); Ok(ExitCode::from(3)) } RunOutcome::Fault { pc, elapsed } => { From 02351c8ca4d11fa19b52c5c8b14a7b9901d4b250 Mon Sep 17 00:00:00 2001 From: Andrew Hutchings Date: Wed, 25 Nov 2026 15:42:37 +0000 Subject: [PATCH 2/4] STM32Sim: check the crypto mutex is released in the F4 RNG fault test wc_GenerateSeed() must release the crypto hardware mutex on every return path, including when it gives up with RNG_FAILURE_E. In a SINGLE_THREADED build the mutex itself is a no-op, so a leak would go unnoticed. The rng-fault-f4 firmware now links with ld --wrap for wolfSSL_CryptHwMutexLock/UnLock, tracks the lock depth, and reports "mutex=ok" or "mutex=bad" after each call (also g_hw_mutex_errors for board runs). run-rng-fault-f417.sh fails a scenario whose mutex is not released. With a wolfSSL copy whose StdPeriph retry-exhaustion path skips the unlock, the seed:200:sticky and clock:200:sticky scenarios now fail with "mutex='bad'"; the fixed tree passes all ten. The runner also cleans the copied firmware directory before building, so build output left in a local checkout can't stand in for a fresh build against WOLFSSL_ROOT. --- STM32Sim/firmware/rng-fault-f4/Makefile | 3 + STM32Sim/firmware/rng-fault-f4/README.md | 5 +- STM32Sim/firmware/rng-fault-f4/board-run.sh | 1 + STM32Sim/firmware/rng-fault-f4/main.c | 63 +++++++++++++++++++-- STM32Sim/scripts/run-rng-fault-f417.sh | 14 ++++- 5 files changed, 77 insertions(+), 9 deletions(-) diff --git a/STM32Sim/firmware/rng-fault-f4/Makefile b/STM32Sim/firmware/rng-fault-f4/Makefile index 4c3839a..75cc4e2 100644 --- a/STM32Sim/firmware/rng-fault-f4/Makefile +++ b/STM32Sim/firmware/rng-fault-f4/Makefile @@ -63,7 +63,10 @@ ARCH = -mcpu=cortex-m4 -mthumb -mfloat-abi=soft CPPFLAGS = -DWOLFSSL_USER_SETTINGS -D$(DEVICE) $(DEFS) \ -I. -Istdperiph -I$(CMSIS_DEVICE) -I$(CMSIS_CORE) -I$(WOLFSSL_ROOT) CFLAGS = $(ARCH) -Os -g -ffunction-sections -fdata-sections -Wall +# --wrap lets main.c account for every crypto hardware mutex lock/unlock. LDFLAGS = $(ARCH) -Tstm32f4.ld -nostartfiles -Wl,--gc-sections \ + -Wl,--wrap=wolfSSL_CryptHwMutexLock \ + -Wl,--wrap=wolfSSL_CryptHwMutexUnLock \ -specs=nano.specs -specs=nosys.specs -Wl,-Map=$(BUILD)/rng-fault.map all: $(ELF) diff --git a/STM32Sim/firmware/rng-fault-f4/README.md b/STM32Sim/firmware/rng-fault-f4/README.md index 7ab9071..949b799 100644 --- a/STM32Sim/firmware/rng-fault-f4/README.md +++ b/STM32Sim/firmware/rng-fault-f4/README.md @@ -5,7 +5,9 @@ STM32F4 hardware-RNG fault test for wolfSSL's `wc_GenerateSeed()`. The firmware pulls a short seed with the RNG healthy, then a long one while the RNG fails part way through. A correct `wc_GenerateSeed()` returns from the second call, with `0` if the RNG recovered or `RNG_FAILURE_E` (-199) if -it did not. The regression it guards against is the call never returning: +it did not, and must leave the crypto hardware mutex released either way +(the firmware wraps `wolfSSL_CryptHwMutexLock`/`UnLock` with `ld --wrap` +and tracks the lock depth). The regression it guards against is the call never returning: before the fix, the Standard Peripheral Library arm of the `STM32_RNG` seed code polled DRDY with no bound, so a seed or clock error mid-request hung it forever with the crypto hardware mutex held. @@ -61,6 +63,7 @@ What to look for: | `g_hung` | set by SysTick if it has not returned 5 s after the fault | | `g_rng_sr_after_fault` | RNG_SR 100 ms after the fault | | `g_return_tick` | SysTick ms at which it returned (fault at `g_fault_fired_tick`) | +| `g_hw_mutex_errors` | crypto hardware mutex misuse: locked while held, unlocked while free, or still held after a call (must be 0) | LEDs: green = sanity seed passed, orange = faulted call returned, red = faulted call hung, blue = heartbeat. diff --git a/STM32Sim/firmware/rng-fault-f4/board-run.sh b/STM32Sim/firmware/rng-fault-f4/board-run.sh index f7d7659..097c7fb 100755 --- a/STM32Sim/firmware/rng-fault-f4/board-run.sh +++ b/STM32Sim/firmware/rng-fault-f4/board-run.sh @@ -16,6 +16,7 @@ sym() { CMDS="program $ELF verify; reset run; sleep $((SECS * 1000)); halt;" for v in g_stage g_sanity_ret g_fault_ret g_tick g_fault_tick \ g_fault_fired_tick g_rng_sr_after_fault g_return_tick g_hung \ + g_hw_mutex_depth g_hw_mutex_errors \ test_complete test_result; do a=$(sym "$v") CMDS="$CMDS echo \"$v [read_memory $a 32 1]\";" diff --git a/STM32Sim/firmware/rng-fault-f4/main.c b/STM32Sim/firmware/rng-fault-f4/main.c index caa95f3..5bd6f11 100644 --- a/STM32Sim/firmware/rng-fault-f4/main.c +++ b/STM32Sim/firmware/rng-fault-f4/main.c @@ -26,7 +26,10 @@ * * A correct wc_GenerateSeed() returns from step 2, either with 0 (the * RNG recovered) or RNG_FAILURE_E (it did not). The bug this guards - * against is the call never returning. + * against is the call never returning. Every call must also leave the + * crypto hardware mutex released, whatever it returns: the Makefile links + * with ld --wrap for wolfSSL_CryptHwMutexLock/UnLock, so the firmware sees + * every lock and unlock and can track the lock depth. * * How the RNG is made to fail depends on the build: * @@ -42,8 +45,9 @@ * Default (stm32-sim): the simulator's --rng-fault option latches the * SECS or CECS condition after a set number of DR reads. * - * test_result is 0 when step 1 passed and step 2 returned; the console - * line "RNG_FAULT ... fault=" carries the step 2 return code. */ + * test_result is 0 when step 1 passed, step 2 returned and the mutex was + * always released; the console line "RNG_FAULT ... fault= + * mutex=" carries the step 2 return code and the mutex result. */ #include #include @@ -84,6 +88,9 @@ volatile uint32_t g_fault_fired_tick; volatile uint32_t g_rng_sr_after_fault; volatile uint32_t g_return_tick; volatile uint32_t g_hung; +/* Crypto hardware mutex accounting (see the wrappers below). */ +volatile int32_t g_hw_mutex_depth; +volatile uint32_t g_hw_mutex_errors; static byte sanity_buf[SANITY_SZ]; static byte fault_buf[FAULT_BUF_SZ]; @@ -136,6 +143,50 @@ static void uart_putd(int32_t v) } } +/* ---- crypto hardware mutex accounting ----------------------------------- */ + +/* The Makefile links with --wrap=wolfSSL_CryptHwMutexLock and + * --wrap=wolfSSL_CryptHwMutexUnLock, so wolfSSL's calls land here and the + * real functions are reachable as __real_*. Locking while already held, + * unlocking while free, or still holding the mutex once a + * wc_GenerateSeed() call has returned all count as errors. */ +int __real_wolfSSL_CryptHwMutexLock(void); +int __real_wolfSSL_CryptHwMutexUnLock(void); +int __wrap_wolfSSL_CryptHwMutexLock(void); +int __wrap_wolfSSL_CryptHwMutexUnLock(void); + +int __wrap_wolfSSL_CryptHwMutexLock(void) +{ + int ret = __real_wolfSSL_CryptHwMutexLock(); + + if (ret == 0) { + if (g_hw_mutex_depth != 0) { + g_hw_mutex_errors++; + } + g_hw_mutex_depth++; + } + return ret; +} + +int __wrap_wolfSSL_CryptHwMutexUnLock(void) +{ + if (g_hw_mutex_depth <= 0) { + g_hw_mutex_errors++; + } + else { + g_hw_mutex_depth--; + } + return __real_wolfSSL_CryptHwMutexUnLock(); +} + +static void check_mutex_released(void) +{ + if (g_hw_mutex_depth != 0) { + g_hw_mutex_errors++; + g_hw_mutex_depth = 0; + } +} + /* ---- newlib hooks ------------------------------------------------------ */ extern char __heap_start__; @@ -257,6 +308,7 @@ int main(void) g_stage = STAGE_SANITY; g_sanity_ret = wc_GenerateSeed(&os, sanity_buf, sizeof(sanity_buf)); + check_mutex_released(); for (i = 0; i < (int)sizeof(sanity_buf); i++) { nonzero |= sanity_buf[i]; } @@ -278,6 +330,7 @@ int main(void) g_fault_tick = g_tick + FAULT_DELAY_MS; #endif g_fault_ret = wc_GenerateSeed(&os, fault_buf, sizeof(fault_buf)); + check_mutex_released(); g_stage = STAGE_DONE; #ifdef RNG_FAULT_BOARD g_return_tick = g_tick; @@ -288,9 +341,9 @@ int main(void) uart_putd(g_sanity_ret); uart_puts(" fault="); uart_putd(g_fault_ret); - uart_puts("\n"); + uart_puts(g_hw_mutex_errors == 0U ? " mutex=ok\n" : " mutex=bad\n"); - if (g_sanity_ret == 0 && + if (g_sanity_ret == 0 && g_hw_mutex_errors == 0U && (g_fault_ret == 0 || g_fault_ret == RNG_FAILURE_E)) { test_result = 0; uart_puts("=== RNG fault test returned ===\n"); diff --git a/STM32Sim/scripts/run-rng-fault-f417.sh b/STM32Sim/scripts/run-rng-fault-f417.sh index 2bc3096..7b305a2 100755 --- a/STM32Sim/scripts/run-rng-fault-f417.sh +++ b/STM32Sim/scripts/run-rng-fault-f417.sh @@ -24,8 +24,9 @@ # RNG directly (the Standard Peripheral Library arm and # WOLFSSL_STM32_RNG_NOLIB) and runs each on stm32-sim --chip stm32f417 # with RNG seed / clock errors injected part way through a seed request. -# Every scenario must return the expected code; a hung wc_GenerateSeed() -# shows up as a simulator timeout and fails the test with the hung PC. +# Every scenario must return the expected code and leave the crypto +# hardware mutex released; a hung wc_GenerateSeed() shows up as a simulator +# timeout and fails the test with the hung PC. set -euo pipefail @@ -58,6 +59,9 @@ nolib clock:200 0 nolib clock:200:sticky -199 " +# Drop any build output copied along with the sources, so every run builds +# against WOLFSSL_ROOT afresh. +make -s -C "${BUILD_DIR}" clean for arm in stdperiph nolib; do echo ">> Building rng-fault firmware (${arm} arm) against ${WOLFSSL_ROOT} ..." make -s -C "${BUILD_DIR}" TARGET=sim ARM="${arm}" WOLFSSL_ROOT="${WOLFSSL_ROOT}" @@ -77,18 +81,22 @@ while read -r arm fault expect; do got="$(sed -n 's/.*RNG_FAULT sanity=[-0-9]* fault=\([-0-9]*\).*/\1/p' <<<"${out}")" sanity="$(sed -n 's/.*RNG_FAULT sanity=\([-0-9]*\).*/\1/p' <<<"${out}")" + mutex="$(sed -n 's/.*RNG_FAULT .* mutex=\([a-z]*\).*/\1/p' <<<"${out}")" label="$(printf '%-9s %-17s' "${arm}" "${fault}")" if [[ ${rc} -eq 3 ]]; then pc="$(sed -n 's/.*TIMEOUT.*PC=\(0x[0-9a-f]*\).*/\1/p' <<<"${out}")" where="$(arm-none-eabi-addr2line -f -e "${elf}" "${pc}" 2>/dev/null | head -1)" echo "FAIL ${label} hung: no return after ${TIMEOUT}s, PC ${pc} in ${where}" FAILED=1 + elif [[ "${mutex}" != "ok" ]]; then + echo "FAIL ${label} crypto hardware mutex not released (fault=${got}, mutex='${mutex}')" + FAILED=1 elif [[ "${sanity}" != "0" ]]; then echo "FAIL ${label} sanity seed returned '${sanity}' (sim exit ${rc})" echo "${out}" | tail -5 FAILED=1 elif [[ "|${expect}|" == *"|${got}|"* ]]; then - echo "ok ${label} fault=${got}" + echo "ok ${label} fault=${got} mutex=ok" else echo "FAIL ${label} fault=${got}, expected ${expect} (sim exit ${rc})" FAILED=1 From 2bb0193ff557a1038bcbebabe96c2bb21f72a458 Mon Sep 17 00:00:00 2001 From: Andrew Hutchings Date: Wed, 25 Nov 2026 15:48:27 +0000 Subject: [PATCH 3/4] STM32Sim: tighten F417 CI pass checks and latch zero-read RNG faults - run-wolfcrypt-f417.sh: the firmware prints its pass line before it sets test_complete, so a simulator timeout or fault after that line still exited 0. Pass now needs the marker and a zero simulator exit status, and a run with neither exits non-zero. - run-rng-fault-f417.sh: likewise, a scenario whose RNG_FAULT line matches now also needs the simulator to exit cleanly. - rng: a fault armed with zero reads latched only after the first RNG_DR read had returned fresh data, so seed:0 behaved like seed:1 and the firmware's first status check saw a healthy RNG. It now latches when armed, so the error is there from the start. --- STM32Sim/README.md | 5 ++-- STM32Sim/scripts/run-rng-fault-f417.sh | 7 ++++++ STM32Sim/scripts/run-wolfcrypt-f417.sh | 9 ++++++-- STM32Sim/stm32-sim/peripherals/src/rng.rs | 28 +++++++++++++++++++++-- STM32Sim/stm32-sim/runner-bin/src/main.rs | 3 ++- 5 files changed, 45 insertions(+), 7 deletions(-) diff --git a/STM32Sim/README.md b/STM32Sim/README.md index 01f6fd2..7aef066 100644 --- a/STM32Sim/README.md +++ b/STM32Sim/README.md @@ -128,8 +128,9 @@ a hung firmware says where it hung. ### RNG fault injection `--rng-fault :[:sticky]` makes the chip's RNG raise -an error after `` RNG_DR reads, following the F2/F4 reference -manual error management (RM0033 / RM0090): +an error after `` RNG_DR reads (with `0`, the error is there +before the first status check), following the F2/F4 reference manual +error management (RM0033 / RM0090): - `seed`: SECS and SEIS latch and DRDY stays low until the firmware clears SEIS and cycles RNGEN. diff --git a/STM32Sim/scripts/run-rng-fault-f417.sh b/STM32Sim/scripts/run-rng-fault-f417.sh index 7b305a2..c6cd227 100755 --- a/STM32Sim/scripts/run-rng-fault-f417.sh +++ b/STM32Sim/scripts/run-rng-fault-f417.sh @@ -95,6 +95,13 @@ while read -r arm fault expect; do echo "FAIL ${label} sanity seed returned '${sanity}' (sim exit ${rc})" echo "${out}" | tail -5 FAILED=1 + elif [[ ${rc} -ne 0 ]]; then + # The firmware prints RNG_FAULT before it sets test_complete, so + # a matching line alone is not a pass: the run must also end + # cleanly. + echo "FAIL ${label} fault=${got} but the simulator exited ${rc}" + echo "${out}" | tail -5 + FAILED=1 elif [[ "|${expect}|" == *"|${got}|"* ]]; then echo "ok ${label} fault=${got} mutex=ok" else diff --git a/STM32Sim/scripts/run-wolfcrypt-f417.sh b/STM32Sim/scripts/run-wolfcrypt-f417.sh index 8303132..cd841da 100755 --- a/STM32Sim/scripts/run-wolfcrypt-f417.sh +++ b/STM32Sim/scripts/run-wolfcrypt-f417.sh @@ -70,7 +70,9 @@ stm32-sim \ SIM_EXIT=${PIPESTATUS[0]} set -e -if grep -q "=== wolfCrypt test passed! ===" "${LOG}"; then +# The firmware prints its result line before it sets test_complete, so +# the pass marker only counts if the simulator also exited cleanly. +if [[ ${SIM_EXIT} -eq 0 ]] && grep -q "=== wolfCrypt test passed! ===" "${LOG}"; then echo echo "wolfCrypt tests completed successfully." exit 0 @@ -82,5 +84,8 @@ if grep -q "=== wolfCrypt test FAILED ===" "${LOG}"; then fi echo -echo "wolfCrypt tests did not report a result string. Simulator exit=${SIM_EXIT}" +echo "wolfCrypt tests did not finish cleanly. Simulator exit=${SIM_EXIT}" +if [[ ${SIM_EXIT} -eq 0 ]]; then + exit 1 +fi exit "${SIM_EXIT}" diff --git a/STM32Sim/stm32-sim/peripherals/src/rng.rs b/STM32Sim/stm32-sim/peripherals/src/rng.rs index 28b3b0b..90f7e2c 100644 --- a/STM32Sim/stm32-sim/peripherals/src/rng.rs +++ b/STM32Sim/stm32-sim/peripherals/src/rng.rs @@ -58,7 +58,9 @@ pub enum RngFaultKind { #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct RngFault { pub kind: RngFaultKind, - /// DR reads served normally before the fault latches. + /// DR reads served normally before the fault latches. With 0 the + /// error is already present when the fault is armed, before the + /// firmware's first status check. pub after_reads: u64, /// A sticky fault never clears: a dead entropy source or a kernel /// clock that never returns. Otherwise a seed error clears once @@ -161,9 +163,11 @@ impl Rng { Self::with_seed(0xDEAD_BEEF_CAFE_BABE) } - /// Arm a fault that latches after `fault.after_reads` DR reads. + /// Arm a fault that latches after `fault.after_reads` DR reads (at + /// once for 0). pub fn with_fault(mut self, fault: Option) -> Self { self.fault = fault; + self.maybe_latch_fault(); self } @@ -351,6 +355,26 @@ mod tests { drain(&mut r, 100); } + /// A zero-read fault is there from the start: the first SR read already + /// shows it and no fresh data is served. + #[test] + fn zero_read_fault_is_present_before_first_read() { + let mut r = Rng::new().with_fault(fault("seed:0")); + assert_eq!(r.read(SR, 4), SR_SECS | SR_SEIS); + assert_eq!(r.read(DR, 4), 0); + + let mut r = Rng::new().with_fault(fault("clock:0:sticky")); + r.write(CR, 4, CR_RNGEN); + assert_eq!(r.read(SR, 4), SR_CECS | SR_CEIS); + + // One read later is a different fault from zero reads. + let mut r = Rng::new().with_fault(fault("seed:1:sticky")); + r.write(CR, 4, CR_RNGEN); + assert_eq!(r.read(SR, 4), SR_DRDY); + r.read(DR, 4); + assert_eq!(r.read(SR, 4), SR_SECS | SR_SEIS); + } + #[test] fn sticky_seed_error_never_recovers() { let mut r = Rng::new().with_fault(fault("seed:0:sticky")); diff --git a/STM32Sim/stm32-sim/runner-bin/src/main.rs b/STM32Sim/stm32-sim/runner-bin/src/main.rs index a5bd5d9..19ae514 100644 --- a/STM32Sim/stm32-sim/runner-bin/src/main.rs +++ b/STM32Sim/stm32-sim/runner-bin/src/main.rs @@ -53,7 +53,8 @@ struct Args { #[arg(long)] list_chips: bool, - /// Inject an RNG fault after a number of RNG_DR reads: + /// Inject an RNG fault after a number of RNG_DR reads (0: present + /// from the start): /// `seed:` (seed error; clears once firmware clears SEIS and /// cycles RNGEN), `clock:` (clock error; clears by itself after /// a short glitch). Append `:sticky` for a fault that never clears. From 86a80d6ca623f322fa122044779921d09f1f8a73 Mon Sep 17 00:00:00 2001 From: Andrew Hutchings Date: Wed, 25 Nov 2026 16:20:25 +0000 Subject: [PATCH 4/4] PIC32MZSim: seed from the RNG block under Harmony, accept EC weak entropy wolfSSL master (76aed2f9d4, "Use available entropy sources in embedded configurations") turned weak PIC32 seed sources into #errors, which broke three of the four PIC32MZ wolfCrypt tiers: - EC direct: the EC has no TRNG, so wolfSSL seeds the PIC32MZ RNG block from the core timer and now requires WOLFSSL_ACCEPT_WEAK_ENTROPY. - EC and EF Harmony: the Harmony build never defined WOLFSSL_PIC32MZ_RNG (the direct port gets it with WOLFSSL_MICROCHIP_PIC32MZ), so wolfSSL fell back to rand() seeded from the core timer, which is now an #error too, even on the EF with its TRNG. Define WOLFSSL_PIC32MZ_RNG for the Harmony tier, so it seeds from the RNG block like the direct port (the EF from its TRNG), and define WOLFSSL_ACCEPT_WEAK_ENTROPY on EC parts only, keyed on __PIC32_FEATURE_SET1 as wolfSSL's own check is. All four tiers pass against wolfSSL master. --- PIC32MZSim/firmware/common/user_settings.h | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/PIC32MZSim/firmware/common/user_settings.h b/PIC32MZSim/firmware/common/user_settings.h index f027a6d..898fa11 100644 --- a/PIC32MZSim/firmware/common/user_settings.h +++ b/PIC32MZSim/firmware/common/user_settings.h @@ -29,6 +29,17 @@ #define MICROCHIP_MPLAB_HARMONY #define MICROCHIP_PIC32 #define WOLFSSL_HAVE_MCHP_HW_CRYPTO_HARMONY +/* Seed from the PIC32MZ RNG block, as the direct port does (there it comes + * with WOLFSSL_MICROCHIP_PIC32MZ). Without it wolfSSL falls back to rand() + * seeded from the core timer, which it rejects as weak entropy. */ +#define WOLFSSL_PIC32MZ_RNG +#endif + +/* The PIC32MZ EC has no TRNG: wolfSSL seeds its RNG block from the core + * timer, which it only accepts as a test configuration. This is a + * simulator, so accept it on EC; EF seeds from its TRNG. */ +#if defined(__PIC32_FEATURE_SET1) && (__PIC32_FEATURE_SET1 == 'C') +#define WOLFSSL_ACCEPT_WEAK_ENTROPY #endif /* ---- No OS dependencies ---- */