Boot security in the MCU
Daniel (Director and Co-Founder · elttam), Zoltan Madarassy (Security Consultant · elttam)
BSides Canberra VII (2024) · Day 2 · Main Track
Overview
The talk "Boot security in the MCU" by Zoltan Madarassy and Daniel from elttam delves into the critical area of secure boot implementations in microcontrollers (MCUs), specifically focusing on the widely used ESP32 by Espressif and STM32 by STMicroelectronics. The speakers, experienced security consultants, share their collaborative research journey into auditing the second-stage bootloaders of these popular MCU families. This talk is highly relevant as MCUs are ubiquitous, powering everything from smartwatches to industrial control systems, making their foundational security paramount.

Key moments
- 4:10 How Secure Boot works: Root of Trust and Boot Chain
- 10:30 ESP32 one-time programmable eFuses for security
- 23:40 Demonstrating ESP32 firmware rollback (TOCTOU) vulnerability
- 30:50 Challenges with STM32 documentation and ecosystem
- 36:00 STM32 Readout Protection (RDP) levels and implications
- 51:00 STM32 ST-SAFE I2C memory corruption vulnerability
- 54:10 Open-source tooling and future research directions
Boot security in the MCU
Speakers: Daniel (Director and Co-Founder, elttam); Zoltan Madarassy (Security Consultant, elttam)
Conference: BSides Canberra
YouTube: https://www.youtube.com/watch?v=LXdSVcvhJuI
Overview
The talk "Boot security in the MCU" by Zoltan Madarassy and Daniel from elttam delves into the critical area of secure boot implementations in microcontrollers (MCUs), specifically focusing on the widely used ESP32 by Espressif and STM32 by STMicroelectronics. The speakers, experienced security consultants, share their collaborative research journey into auditing the second-stage bootloaders of these popular MCU families. This talk is highly relevant as MCUs are ubiquitous, powering everything from smartwatches to industrial control systems, making their foundational security paramount.
The core of the presentation explores the practical challenges and vulnerabilities discovered within the reference implementations of secure boot provided by these vendors. By examining both the documentation and the underlying source code, Madarassy and Daniel highlight how seemingly robust security features can be undermined by subtle implementation flaws, particularly Time-of-Check Time-of-Use (TOCTOU) race conditions and memory corruption issues. Their work not only identifies specific vulnerabilities but also provides practical methodologies and tooling for other researchers and developers to assess and harden their own MCU boot processes.
This research is significant because it moves beyond theoretical secure boot concepts to demonstrate real-world attack vectors against widely deployed hardware. By focusing on open-source bootloader components, the speakers provide actionable insights for developers building secure embedded systems, emphasizing the importance of thorough code review, understanding hardware-software interactions, and diligent configuration of security features like eFuses and Readout Protection (RDP). The collaborative nature of their research and the release of their auditing tools further contribute to raising the overall security posture of the embedded ecosystem.
Background
▶ Watch: How Secure Boot works: Root of Trust and Boot Chain (4:10)
Microcontrollers (MCUs) are compact, integrated computers comprising a processor, built-in memory, and peripherals, found in countless devices from consumer electronics to industrial systems. Their pervasive nature makes their security a critical concern, particularly at the earliest stages of operation. Secure boot is a fundamental security mechanism designed to ensure that an MCU only executes trusted, verified code. Its primary objectives are protection (preventing malicious code execution and data compromise), detection (identifying tampering), and recovery (restoring to a known secure state).
The secure boot process typically begins with a Root of Trust, an immutable secret often embedded in the Boot ROM. This Root of Trust verifies the integrity of the first-stage bootloader (usually the Boot ROM itself), which then verifies the second-stage bootloader. This chain of trust continues, with each verified component responsible for authenticating the next, ultimately leading to the secure execution of the application firmware. While the Boot ROM is often a black box for researchers due to its proprietary nature and immutability, the second-stage bootloader is frequently open-source or provided as a reference implementation by vendors. This makes it a prime target for security auditing, as developers often adapt these reference implementations for their production devices.
The speakers chose to focus their research on the second-stage bootloader for several reasons: its accessibility through open-source code, the potential for discovering practical vulnerabilities that could impact real-world devices, and the opportunity to provide tailored guidance to their clients. Their work aims to bridge the gap between theoretical secure boot principles and their practical, often flawed, implementations in commercial MCUs. Despite the existence of guidelines from bodies like NIST, there is no single universally adopted industry standard for secure boot, leading to diverse and sometimes inconsistent implementations across vendors. This variability underscores the importance of independent security research to identify and address weaknesses before they are exploited in the wild.
Key Findings
▶ Watch: Demonstrating ESP32 firmware rollback (TOCTOU) vulnerability (23:40)
The research by Daniel and Zoltan Madarassy yielded significant findings across both the ESP32 and STM32 platforms, highlighting common pitfalls in secure boot implementations.
For the ESP32, the primary discovery revolved around Time-of-Check Time-of-Use (TOCTOU) vulnerabilities, specifically within the anti-rollback mechanism. They demonstrated that by manipulating the external SPI flash memory, an attacker could present a valid, signed firmware version during the initial check, and then swap it with an older, vulnerable version before execution. This practical attack led to the discovery of a vulnerability (for which a CVE was obtained, though not explicitly numbered in the talk) allowing a downgrade to an insecure firmware version despite secure boot being enabled. Further auditing revealed another conceptual TOCTOU issue in the process_segment_data function, where data loaded into RAM for execution could differ from the data used for hash verification. While this specific instance was mitigated by the ESP32's caching behavior, it underscored the pervasive risk of TOCTOU flaws and the potential for exploitation on other architectures using the same codebase.
On the STM32 platform, the key finding was a memory corruption vulnerability within the HAL_I2C_MasterReceive_IT function, affecting devices that utilize an external STSAFE secure element communicating via the I2C bus. The flaw allowed an attacker performing a Man-in-the-Middle (MITM) attack on the I2C bus to control the length of data received by the main MCU, leading to a buffer overflow. This permitted writing beyond the bounds of the intended buffer, enabling arbitrary code execution. This finding emphasizes the critical security implications of external secure elements and the communication channels between them and the main MCU, especially when proper encryption or authentication is not enforced (as is often the case in development or non-production environments).
Across both platforms, the research highlighted the critical importance of correctly configuring hardware security features (e.g., ESP32 eFuses, STM32 RDP levels) and the dangers of relying solely on secure boot without a holistic approach to system lockdown. The speakers also demonstrated the effectiveness of their custom tooling, including an NBD kit for emulated flash manipulation and logic analyzer plugins for physical hardware analysis, in uncovering and validating these types of vulnerabilities.
Technical Deep Dive
▶ Watch: Challenges with STM32 documentation and ecosystem (30:50)
The talk provided a deep dive into the secure boot mechanisms of two prominent microcontroller families: the Espressif ESP32 and STMicroelectronics STM32. The research primarily focused on their second-stage bootloader reference implementations, which are often open-source or publicly available, making them suitable targets for code auditing.
Espressif ESP32
The ESP32 family, particularly the older versions based on the Xtensa LX6 architecture, was the first target. Espressif's ESP-IDF framework serves as the reference implementation, providing components and tools for developers. The speakers reviewed multiple major versions of ESP-IDF to understand the evolution of secure boot.
Documentation and eFuses:
Espressif provides extensive documentation, including datasheets, technical reference manuals, and community forums. This facilitated understanding the platform's security features, which are largely controlled by One-Time Programmable (OTP) eFuses. These eFuses are physical components that can be "burnt" (changing a 0 to a 1) by software, an irreversible operation. The ESP32 features 1 kilobyte of OTP memory divided into four blocks:
- Block 0 (System Parameter Block): Configures microcontroller features, such as enabling/disabling JTAG for debugging. Disabling JTAG in production is crucial to prevent memory inspection and code injection, which could bypass secure boot.
- Block 1: Reserved for the Flash Encryption Key. This block should be read-protected to prevent key exfiltration.
- Block 2: Stores Secure Boot Keys.
- Block 3: General application purposes.
eFuses can also be write-protected to prevent accidental or malicious burning. For instance, the factory-assigned MAC address (stored in eFuses) often lacks write protection by default, allowing modification. Understanding these fuse configurations is paramount for securing the device.
Code Auditing Approach:
The auditing process involved a line-by-line review of the bootloader and bootloader_support folders within the ESP-IDF codebase, starting from the call_start_cpu0 entry point. This led to an understanding of the boot flow, including:
- Partition Table: The external SPI flash memory is logically divided into partitions. The first few kilobytes hold the second-stage bootloader and its digest for Boot ROM verification. The rest contains application code, data, and other configurations. The
select_partition_numberfunction determines which partition to boot from. - Anti-Rollback Mechanism: The
load_boot_imagefunction includes a call tocheck_anti_rollback. This feature prevents downgrading firmware to older, potentially vulnerable versions, especially after Over-The-Air (OTA) updates. When a new firmware is downloaded to an inactive OTA partition (e.g.,ota_1), the active partition is switched. Upon successful boot, an eFuse representing thesecure_version(an incrementing counter in the application image header, specifically theESP_APP_DESCstructure) is blown, making it impossible to revert to an earlier version.
Time-of-Check Time-of-Use (TOCTOU) Vulnerability:
A critical flaw was identified in the interaction between the version check and the actual loading of the firmware. If an attacker controls the external SPI flash, they can present a valid, high secure_version during the check_anti_rollback phase. However, before the read_partition function loads and executes the application, the attacker can swap the flash contents to an older, vulnerable firmware with a lower secure_version. This TOCTOU race condition allows bypassing the anti-rollback protection.
Further auditing uncovered a similar conceptual TOCTOU in the process_segment_data function, responsible for loading application data into RAM and simultaneously computing its hash for secure boot verification. The data fetch for loading (SRC[i]) and the data fetch for hashing (SRC[i]) occurred at different times. Theoretically, an attacker could manipulate the flash between these two fetches, causing the loaded RAM content to differ from the verified hash. However, due to the ESP32's caching mechanism and the close locality of accesses, this particular instance was not practically exploitable. The speakers noted that this might still be exploitable on other Xtensa LX7 or RISC-V architectures that share the same codebase but might have different caching behaviors.
STMicroelectronics STM32
The STM32 family presents a more complex ecosystem, with thousands of different MCUs. The research focused on the STM32L4S5 Discovery Kit, a low-power, accessible MCU.
Documentation Challenges:
Unlike Espressif, STMicroelectronics' documentation was described as disparate and sometimes contradictory, making it challenging to navigate their ecosystem and find consistent technical information. Their source versioning also bundles different codebases, further complicating research.
x-CUBE-SBSFU Framework:
At the time of research, ST's primary secure boot and secure firmware update (SBSFU) framework was x-CUBE-SBSFU. This framework relies heavily on ARM architecture security features and has a strategy to:
- Ensure a single code of entry (the SBSFU binary).
- Utilize ARM's Readout Protection (RDP).
- Protect and isolate secrets in enclaves (either local Flash or an external STSAFE secure element).
- Limit attack surface and disable debug ports (e.g., JTAG, SWD).
- Monitor for tampering (e.g., temperature control, side-channel monitoring).
ARM Security Features and Readout Protection (RDP):
The STM32 MCUs leverage various ARM security features, primarily RDP, which has three levels:
- RDP Level 0 (No Protection): Full debugger access to Flash and RAM.
- RDP Level 1 (Memory Protection): Debugger attachment halts the device and triggers a reset. However, RAM contents might still be accessible before the reset, potentially exposing secrets. Level 1 can be programmatically downgraded to Level 0, which the SBSFU code will detect and trigger a chip reset, wiping stored data.
- RDP Level 2 (Immutable Protection): No debugger access to Flash or RAM is permitted. This is the recommended production setting, though irreversible and complicates debugging.
Other ARM security features include:
- Memory Protection Unit (MPU): Granular access controls (non-executable, read-only, read-write) for memory pages.
- Write Protection (WRP): Protects memory regions from erasing and reprogramming.
- Proprietary Code Readout Protection (PCROP): Marks memory pages as execute-only.
- Firewall: Ensures privileged code is only called from other privileged code, protecting against unprivileged access.
These features are configured via option bytes in Flash memory. For example, 0xCC in the RDP option byte indicates Level 2, while 0xAA indicates Level 0. Research exists on fault injection and UV light attacks to downgrade RDP levels, though practical reliability is a challenge.
SBSFU Boot Flow and STSAFE:
The SBSFU boot flow involves board initialization, followed by the initialization of the "secure engine" (referred to as STSAFE even in KMS versions not using the external chip). This is followed by applying and checking static protections (RDP, WRP, PCROP) and runtime checks (Firewall, anti-tampering). The SBSFU then enters a state machine to manage firmware updates and execution. A notable gap in the reference implementation is the initial loading of secrets: the STSAFE initialization step often leaves the secure loading of initial secrets to the developer, with rudimentary examples placing keys in constant Flash addresses, which is explicitly noted as insecure.
STSAFE Secure Element and I2C Vulnerability:
The STSAFE is an external secure element (a low-power chip) designed to store secrets in 6KB of configurable non-volatile memory with OTP fuses. It communicates with the main MCU via the I2C bus. This external communication channel proved to be a critical attack surface.
The speakers discovered a memory corruption vulnerability in the HAL_I2C_MasterReceive_IT function, used by the main MCU to read data from the I2C bus. While the initial read length is preset, the driver subsequently resets the buffer length based on a value received from the bus, which is attacker-controlled in a Man-in-the-Middle (MITM) scenario. If the attacker-controlled length exceeds the statically allocated buffer (e.g., 523 bytes in SBSFU), a second read operation will write past the buffer's bounds, leading to a buffer overflow and potential arbitrary code execution. This attack relies on being able to intercept and manipulate I2C communication.
Demo / Proof of Concept
▶ Watch: STM32 ST-SAFE I2C memory corruption vulnerability (51:00)
The talk effectively demonstrated practical exploitation techniques and provided tooling to aid in research, showcasing the vulnerabilities found on both the ESP32 and STM32 platforms.
ESP32 Anti-Rollback Bypass (TOCTOU)
For the ESP32, the primary proof of concept revolved around exploiting the Time-of-Check Time-of-Use (TOCTOU) vulnerability in the anti-rollback mechanism. The speakers leveraged QEMU emulation of the ESP32, which allows the external SPI flash memory to be mapped to a fake block device.
The demonstration utilized a custom NBD kit (Network Block Device kit) program. This NBD kit was configured to act as an intermediary for flash accesses. During the initial boot sequence, when the ESP32 bootloader checks the secure_version of the firmware in, for example, the ota_1 partition, the NBD kit would present a valid, high version number. Immediately after this check, but before the firmware was fully loaded and executed, the NBD kit would dynamically swap the contents of the ota_1 partition to an older, known vulnerable version of the firmware. This successfully bypassed the anti-rollback protection, allowing the execution of a downgraded, vulnerable firmware, even though the eFuses specified a higher minimum secure_version. The screenshot shown during the talk depicted the eFuse value requiring version 10, while the actually running firmware was version 0.
To further analyze and visualize such TOCTOU scenarios, the researchers developed custom tooling capable of logging flash sector accesses (read/write operations) over time. This allowed them to plot a timeline of flash interactions, visually identifying instances where the same memory region was accessed multiple times, creating potential windows for TOCTOU attacks. This tooling was also extended with logic analyzer plugins to enable similar analysis on physical hardware, moving beyond emulation.
While a conceptual TOCTOU in process_segment_data was identified, it was not practically exploitable on the ESP32 due to hardware caching. This highlights that while a vulnerability might exist in code, hardware-specific behaviors can sometimes mitigate or prevent its exploitation in practice.
STM32 STSAFE I2C Memory Corruption
For the STM32, the demonstration focused on the memory corruption vulnerability found in the HAL_I2C_MasterReceive_IT function when communicating with an external STSAFE secure element over the I2C bus.
The proof of concept involved a physical setup using the STM32L4S5 Discovery Kit combined with a Nucleo-based extension shield containing an STSAFE chip. This setup conveniently exposed the I2C bus headers, allowing easy interception without complex soldering. A logic analyzer was used to monitor the I2C communication.
The attack involved a "malicious shield" (presumably another microcontroller or device) acting as a Man-in-the-Middle (MITM) on the I2C bus between the main STM32 MCU and the STSAFE chip. When the main MCU initiated a read operation expecting a certain response length from the STSAFE, the malicious shield would intercept this and respond with an attacker-controlled length that was larger than the MCU's allocated buffer. This manipulated response length, passed back to the HAL_I2C_MasterReceive_IT function, caused a buffer overflow during a subsequent read operation, leading to memory corruption and ultimately arbitrary code execution. The visual demonstration showed LEDs blinking on the board, indicating successful execution of the malicious code injected via the overflow.
The researchers also developed a Saleae Logic 2 plugin specifically for analyzing I2C communication, which proved invaluable for understanding and debugging the bus interactions to craft this exploit. It's important to note that this attack is primarily effective in development or non-production environments where STSAFE's encrypted communication is not enabled, allowing the I2C traffic to be openly intercepted and manipulated.
In summary, both demonstrations provided concrete, practical examples of how subtle flaws in secure boot implementations and inter-chip communication can be exploited, reinforcing the need for thorough auditing and a deep understanding of hardware-software interactions.
Defensive Implications
▶ Watch: Open-source tooling and future research directions (54:10)
The research presented by Daniel and Zoltan Madarassy offers crucial insights for developers, security engineers, and product managers working with microcontrollers. Implementing robust secure boot is not just about enabling a feature but understanding its intricacies and potential weaknesses.
- Prioritize Hardware Security Features:
- ESP32: Developers must rigorously configure eFuses (OTP memory) to lock down critical settings. This includes permanently disabling JTAG in production via Block 0, read-protecting the Flash Encryption Key in Block 1, and ensuring secure boot keys are correctly burnt in Block 2. Failure to do so leaves open avenues for debugging-based bypasses or key exfiltration.
- STM32: Always aim for RDP Level 2 protection in production. While Level 1 might seem convenient for field debugging, its ability to be downgraded (even if it wipes data) and potential RAM access before reset poses unacceptable risks for sensitive applications. Ensure all relevant option bytes are correctly set and protected. Leverage other ARM features like MPU, WRP, and PCROP where appropriate for granular memory protection.
- Beware of Time-of-Check Time-of-Use (TOCTOU) Vulnerabilities: The ESP32 anti-rollback bypass vividly demonstrates this. Any scenario where a security-critical check (e.g., version, signature) is performed at one point, and the data is used or executed at a later point, creates a window for attack. Critical data should be read and hashed atomically or verified immediately before use. If data must be fetched from external memory, ensure the entire block is read into a secure, internal buffer and then verified before any part of it is used or executed.
- Secure External Communication Channels: The STM32 STSAFE I2C vulnerability highlights the risks associated with external secure elements. All communication between the main MCU and external secure elements (or any critical peripheral) must be encrypted and authenticated in production environments. Do not rely on "secure by obscurity" or assume physical access is impossible. Input validation, especially for lengths and sizes received from external sources, is paramount to prevent memory corruption vulnerabilities like buffer overflows.
- Thorough Code Auditing (Especially Reference Implementations): Vendors' reference implementations, while helpful, are not always production-ready secure. Conduct independent, deep code reviews of all bootloader components, paying close attention to hardware-software interactions, memory management, and error handling. The speakers' approach of tracing functions line-by-line and researching associated features (e.g., partitions, anti-rollback) is a valuable methodology.
- Understand the Full Ecosystem: A secure bootloader is only as strong as the weakest link in the entire system. Insecure configurations elsewhere (e.g., unprotected MAC addresses on ESP32, rudimentary key storage in STM32 SBSFU) can undermine the entire security posture. Go beyond the bootloader. Understand how secrets are loaded, stored, and managed throughout the device's lifecycle. Account for all peripherals, communication buses, and potential debug interfaces.
- Leverage and Contribute to Open-Source Tooling: Tools like the NBD kit, flash access loggers, and Saleae Logic 2 plugins are invaluable for identifying and reproducing vulnerabilities. Utilize available security tools and consider contributing to their development or creating new ones tailored to specific research needs. This collaborative approach enhances the broader security community's capabilities.
Key Takeaways
- Second-stage bootloaders are critical attack surfaces: While Boot ROMs are often black boxes, open-source second-stage bootloaders are accessible for auditing and often contain exploitable flaws, making them a prime focus for security research.
- Time-of-Check Time-of-Use (TOCTOU) is a pervasive risk: Vulnerabilities arising from a time gap between a security check and the actual use of data (e.g., ESP32 anti-rollback bypass) are common in complex hardware-software interactions and can lead to severe compromises like firmware downgrades.
- External secure elements introduce new attack surfaces: While intended to enhance security, external secure elements (like STSAFE) communicating via buses like I2C can introduce vulnerabilities (e.g., STM32 memory corruption via I2C MITM) if communication is not sufficiently encrypted and validated.
- Hardware security features must be correctly configured and understood: Relying on default or lower security settings (e.g., unprotected eFuses on ESP32, RDP Level 1 on STM32) significantly weakens the system. Full lockdown (e.g., RDP Level 2) is crucial for production.
- Documentation review and code auditing are inseparable: A holistic approach combining thorough documentation analysis (despite vendor inconsistencies) with line-by-line code review is essential to identify vulnerabilities that span both hardware configuration and software implementation.
- Specialized tooling is vital for MCU security research: Emulation (QEMU, NBD kit), flash access logging, and logic analyzer plugins greatly aid in identifying, reproducing, and demonstrating complex vulnerabilities in embedded systems.
About the Speaker(s)
Daniel, a Director and Co-Founder at elttam, also serves as a Principal Consultant. With over two decades of experience, he possesses a deep passion for auditing code, particularly in the systems and firmware space, constantly seeking to understand the intricacies of low-level operations.
Zoltan Madarassy, also a Principal Consultant at elttam, shares a strong drive to understand how gadgets and devices function, often leading him to explore their inner workings. His curiosity about the underlying mechanisms of technology fuels his security research and auditing efforts.
Together, their combined expertise in firmware, systems, and code auditing forms the foundation of their collaborative research into MCU boot security.
Reviews
- Dr. Zero (Offensive Security Researcher) — MUST SEE ★★★★★