Перейти до основного вмісту

OTFDEC MCAL Module

This module provides an abstraction layer for the on-the-fly decryption engine (OTFDEC) of STM32 MCUs: the hardware decryption of the firmware and the data that are stored encrypted in an external Octo-SPI flash and read through the memory-mapped window. The engine decrypts every read of the protected regions with AES in the counter mode, without any CPU time and with no plain copy in the memory, so that the code can be executed in place from an encrypted external flash. It offers the definition of up to four regions with their keys, nonces and versions, the enhanced (execute-only) mode, the locking and the key check information. It is a low-level MCAL module: it owns the OTFDEC hardware, the application and the other modules never touch the registers.

The public interface (OtfDec_Port.h, OtfDec_Types.h) is identical for all supported families. The implementation for a family lives in its own branch (Dev/<Family> for development, Releases/<Family> for the released versions), so a module or an application written against the interface does not change when the MCU family changes.

This README is the landing page and the specification of the interface (master). The family branches contain their own README with everything that is specific to the family: the instances of the device, their settings and the status of the implementation.

Status: design. No implementation exists yet, the interface below is a proposal. Stories and branches follow.


Intent and purpose​

  • An external flash is the weak spot of a product: anybody can read it with a clip and copy the firmware. The OTFDEC keeps the flash content encrypted and decrypts it inside the chip on the path between the Octo-SPI interface and the CPU: the key is held in write-only registers, the data on the external bus are never in plain text, and the execute-in-place speed is kept because the AES-CTR keystream is generated in parallel with the read.
  • Up to four independent regions (the granularity of 4 KB) can be protected, each with its own 128-bit key, the 8-byte nonce and the 2-byte firmware version. The CTR counter is built from the nonce, the version and the physical address of the read, so a region is bound to its address and its version: at least one of the three must change every time the image is encrypted again (the rule for the CTR mode - never reuse the keystream). The module takes the region description and writes it to the hardware in the right order.
  • The encryption of the image is done offline by the production or the update tool with the same key, nonce, version and the address of the region; the module's documentation gives the exact counter format so that the tool matches the hardware.
  • The module hides the differences between the families: the number of the regions, the number of the engines (one per Octo-SPI instance), the enhanced mode and the security rules differ, the interface stays the same.

What the module is not: it does not encrypt the image (an offline tool does), it does not store or derive the key (the key comes from the secure key management - the SAes and Ccb modules), and it does not authenticate the image (the signature check of the secure boot, with the Hash and Pka modules).


Concept​

An engine is identified by otfDec_PeriphId_t (OTFDEC_PERIPH_1 ...), one per external memory interface. A region (otfDec_RegionId_t, OTFDEC_REGION_1 ... _4) is configured by:

ItemMeaning
Address rangeThe start and the end address inside the memory-mapped window of the interface, in the granularity of 4096 bytes.
Key128-bit AES key, written once to write-only registers (the CRC of the key can be read back as the public key information to check that it was loaded correctly).
Nonce and versionThe 8-byte application nonce and the 2-byte firmware version that are a part of the counter.
ModeOTFDEC_MODE_DEFAULT (decryption), OTFDEC_MODE_ENHANCED (a proprietary layer on top of the AES stream cipher, execute only: a data read of the region does not give the plain text).
LockThe region configuration is locked until the reset (the key lock; the key cannot be changed).

Rules:

  1. OtfDec_Init enables the engine; the regions are set with OtfDec_Set_RegionConfig and activated with OtfDec_Set_RegionActive. A region is configured while it is disabled; the module rejects the overlap of the regions and the ranges that violate the granularity or leave the window.
  2. The module writes the key, the nonce and the version, then the range, and reads the key CRC back: a mismatch (OTFDEC_REQUEST_ERROR) means a wrong key was loaded, and the region stays disabled. The key is not kept by the module after the call and the caller clears its copy.
  3. The engine must be configured before the code in the region is executed or the data are read; reading an encrypted region with the engine disabled returns the cipher text.
  4. The Octo-SPI interface must be in the memory-mapped mode (the Ospi module) for the regions to be effective; the Ospi pre-fetching is compatible with the engine.
  5. In a TrustZone device the registers are programmable from the secure world only (the Gtzc module assigns the peripheral); the module reports a non-secure call as an error.
  6. The error callback reports the security error (a violation of the enhanced-mode rules: a data read of an execute-only region), the key error and the CRC mismatch.
  7. All parameters are checked before a register is written.

Supported families​

Every family gets its own story, its own tasks and its own branches Dev/<Family> and Releases/<Family> cut from this master.

FamilyBranchEngineStatus
STM32H5Dev/STM32H5OTFDEC1 on STM32H533, H553, H573 and H5F (OTFDEC2 on the H5F lines with the second Octo-SPI): AES-CTR 128-bit, four regions of the 4 KB granularity each with the key, nonce and version, the key CRC, the enhanced execute-only mode, the Octo-SPI pre-fetch support, secure-only programmingplanned (first)
STM32U5Dev/STM32U5OTFDEC1, OTFDEC2 on the lines that have themplanned
STM32H7Dev/STM32H7OTFDEC1, OTFDEC2 on the lines that have themplanned
STM32U3Dev/STM32U3device dependentplanned
STM32F4, STM32F7, STM32G4, STM32L4Dev/STM32F4 ...no on-the-fly decryption on the device - the module is a stub that returns OTFDEC_REQUEST_ERRORplanned

A function without a meaning in a family stays in the interface, returns OTFDEC_REQUEST_ERROR and suppresses the unused parameters (for example the enhanced mode on an engine without it, a fourth region on an engine with fewer).


Public interface in short (proposal)​

GroupFunctions
Module managementOtfDec_Get_ModuleVersion, OtfDec_Init, OtfDec_Deinit, OtfDec_Task, OtfDec_Get_DefaultConfig
RegionsOtfDec_Set_RegionConfig, OtfDec_Set_RegionActive, OtfDec_Set_RegionInactive, OtfDec_Get_RegionState, OtfDec_Get_KeyCrc
ProtectionOtfDec_Set_RegionLock, OtfDec_Get_LockState
InterruptsOtfDec_Set_IrqPriority / Get, the callbacks are a part of the configuration
otfDec_ModuleVersion_t OtfDec_Get_ModuleVersion ( void );

otfDec_RequestState_t OtfDec_Init ( const otfDec_Config_t * const otfDecConfig );
otfDec_RequestState_t OtfDec_Deinit ( otfDec_PeriphId_t periphId );
void OtfDec_Task ( void );
otfDec_RequestState_t OtfDec_Get_DefaultConfig ( otfDec_Config_t * const otfDecConfig );

otfDec_RequestState_t OtfDec_Set_RegionConfig ( otfDec_PeriphId_t periphId, otfDec_RegionId_t regionId, const otfDec_RegionConfig_t * const regionConfig );
otfDec_RequestState_t OtfDec_Set_RegionActive ( otfDec_PeriphId_t periphId, otfDec_RegionId_t regionId );
otfDec_RequestState_t OtfDec_Set_RegionInactive ( otfDec_PeriphId_t periphId, otfDec_RegionId_t regionId );
otfDec_RequestState_t OtfDec_Get_KeyCrc ( otfDec_PeriphId_t periphId, otfDec_RegionId_t regionId, otfDec_Crc_t * const keyCrc );
otfDec_RequestState_t OtfDec_Set_RegionLock ( otfDec_PeriphId_t periphId, otfDec_RegionId_t regionId );

Every function returns OTFDEC_REQUEST_OK / OTFDEC_REQUEST_ERROR and checks its parameters and the state of the module before it touches a register.

TypeMeaning
otfDec_Config_tInterrupt priority, callbacks
otfDec_RegionConfig_tStart and end address, key (16 bytes), nonce (8 bytes), version (2 bytes), mode, the expected key CRC
otfDec_RegionState_tOTFDEC_REGION_DISABLED, OTFDEC_REGION_ACTIVE, OTFDEC_REGION_LOCKED
CallbacksErrorCallback( regionId, errorMask ) (security error, key error)

Usage​

Encrypted firmware in an external flash​

#include "OtfDec_Port.h"

otfDec_Config_t otfDecConfig;
otfDec_RegionConfig_t firmware =
{
.StartAddress = EXTERNAL_FLASH_FIRMWARE_START, .EndAddress = EXTERNAL_FLASH_FIRMWARE_END,
.Mode = OTFDEC_MODE_DEFAULT, .Version = firmwareVersion,
};

(void)OtfDec_Get_DefaultConfig( &otfDecConfig );
(void)OtfDec_Init( &otfDecConfig );

(void)memcpy( firmware.Key, keyFromSecureStore, sizeof( firmware.Key ) );
(void)memcpy( firmware.Nonce, firmwareNonce, sizeof( firmware.Nonce ) );

(void)OtfDec_Set_RegionConfig( OTFDEC_PERIPH_1, OTFDEC_REGION_1, &firmware ); /* the key CRC is verified */
(void)OtfDec_Set_RegionActive( OTFDEC_PERIPH_1, OTFDEC_REGION_1 );
(void)OtfDec_Set_RegionLock( OTFDEC_PERIPH_1, OTFDEC_REGION_1 ); /* until the reset */
/* the Ospi module has started the memory-mapped mode: the code is executed in place from the encrypted flash */

Behaviour and limits​

  • Never reuse the keystream. The CTR counter is composed of the nonce, the version and the address; encrypting two different images with the same key, nonce, version and addresses leaks their XOR. Change the version (or the nonce) at every new image.
  • Address bound. The ciphertext is bound to its physical address: an image encrypted for one address cannot be moved without a re-encryption.
  • Granularity. The regions start and end at a 4 KB boundary; the image is padded to it.
  • Reads before the activation. A read of the region before the engine is active returns the ciphertext (a failure of the application sequence, not an error of the module).
  • Execute only. In the enhanced mode a data read (not an instruction fetch) of the region is refused by the hardware and reported as the security error.
  • Not part of the first version: the encryption of the image (offline tool), the authentication of the image, the key derivation, the multiple firmware slots with the version switching.

Dependencies​

  • Rcc - peripheral clock and reset
  • Nvic - interrupt (the security error)
  • Ospi - the memory-mapped window whose reads are decrypted
  • Gtzc - the assignment of the engine to the secure world
  • RAL (Register Abstraction Layer) - used internally to access the registers

All mandatory RCC and NVIC configurations are handled internally.


Testing​

  • Unit tests (host, Unity + CMock + RegMem): the region validation (granularity, overlap, window), the register write order, the key CRC check and the failed-key path, the lock, the enhanced-mode rules, the error callback, the rejected calls from the non-secure state.
  • Integration tests (target, probe-rs): an image encrypted offline with a known key, read back in plain text through the memory-mapped window, code executed in place from the encrypted region, the execute-only refusal of a data read, the failure with a wrong version.

Interface conventions​

The module follows the common rules of the MCAL layer, so that it behaves like the other modules:

  • Lists instead of free members. Everything that the hardware restricts (the pins, the kernel clock sources, the DMA channels, the triggers and the other selectable sources) is a typedef enum list with exactly the items that are valid for the device line; a pin is an item OTFDEC_<SIGNAL>_PIN_<INSTANCE>_P<port><pin> and there is an *_UNUSED item. A choice that is not in the list cannot be written.
  • Own peripheral only. The module calls only the registers / LL functions of its own peripheral. The clocks, the interrupts, the pins, the DMA and the EXTI lines go through the API of the Rcc, Nvic, Gpio, Gpdma and Exti modules; a missing function is added to that module, it is not bypassed.
  • Init verifies itself. OtfDec_Init checks the result at the end; when it is not as required, the module is deinitialized and an error is returned. The waiting for the hardware is a loop on the register state with a timeout, never a blind delay.
  • Transfer modes. Where the module moves data, the POLL (served by OtfDec_Task), ISR and DMA modes have the same configuration structure, the same request and the same callbacks (error, half transfer, transfer complete).
  • Flags and states are enums of the module (otfDec_FunctionState_t, otfDec_FlagState_t), the limits and the constants are named, there are no magic numbers in the interface.
  • Unsupported functions stay. A function without a meaning in a family keeps its signature, suppresses the unused parameters and returns OTFDEC_REQUEST_ERROR.
  • Documentation. Every function and type has a Doxygen description, the main header has the \defgroup.

Repository layout and branches​

The master holds this README and the license. The family branches (Dev/<Family>, Releases/<Family>) hold:

PathContent
README.mdREADME of the family: the instances of the device, specifics, errata, status
OtfDec_Port.h, OtfDec_Types.hPublic interface (identical in all families)
OtfDec*.c, OtfDec.hImplementation of the family
CMakeLists.txtLibrary OtfDec_Lib of the EmBi platform
Tests/UnitTestsUnit tests (Unity + CMock + RegMem)
Tests/IntegrationTestsIntegration tests on the target (probe-rs)

A change of the public interface is made in all families.


CMake integration​

target_link_libraries( User_Lib PRIVATE OtfDec_Lib )
  1. Link OtfDec_Lib to your CMake library.
  2. Include OtfDec_Port.h in your project.
  3. Configure the module as needed for your hardware.

License​

This project is licensed under the Creative Commons Attribution-NonCommercial 4.0 International (CC BY-NC 4.0).

You are free to use, modify, and share this work for non-commercial purposes, provided appropriate credit is given.

See LICENSE.md for full terms or visit creativecommons.org/licenses/by-nc/4.0.


Authors​

Contributions are welcome! Please open a pull request.