4G remote monitoring for compactors & critical equipment
Free 1-month trial
Technical & AI

IoT firmware security: secure boot, flash encryption and secure OTA

27 juillet 202613 min readIOTINNOV Team

Why IoT firmware security is a critical issue

In industrial IoT, each connected node is a potential entry point to the factory network. Sensors, remote management modules, edge gateways, actuators: these devices, often deployed in unmonitored locations, are prime targets. Classic entry points are well identified: unsigned firmware, private keys extracted by reading the flash, unauthenticated OTA updates.

For an industrial SME or an IoT integrator, the consequences of unsecured firmware are severe: production stoppage, theft of intellectual property (embedded business algorithms), remote takeover of critical equipment, or even a pivot attack toward the information system. The associated costs (loss of revenue, ransom, reputational damage) can be considerable.

This article is aimed at embedded architects, R&D project managers and technical decision-makers. It details the fundamental security mechanisms of industrial IoT firmware — secure boot, flash memory encryption, secure OTA updates, key lifecycle management — with code examples and pitfalls to avoid.

Secure boot: the chain of trust from reset

Secure boot is the foundation of all firmware security. It is the first link in the chain of trust (chain of trust): it guarantees that only signed and intact firmware is executed by the microcontroller, from the boot ROM to the application.

Operating principle

The process unfolds in several locked steps:

  1. Boot ROM (burned into silicon, immutable): at reset, the processor executes code that verifies the signature of the first-stage bootloader (FSBL) using a public key, or its hash, stored in OTP fuses (one-time programmable). If the signature is invalid, boot stops.
  2. FSBL: loads and verifies the second-stage bootloader (SSBL) or directly the RTOS kernel or the application.
  3. Application: can in turn verify the integrity of data in flash (configuration, certificates) before starting its tasks.

Each link verifies the next before handing over control. If a link is compromised, the chain is broken and the system refuses to boot.

Implementation on ESP32-S3

Recent Espressif chips offer a second-generation secure boot (Secure Boot V2). Depending on the chip, signing relies on RSA-PSS 3072-bit (as on the ESP32-S3) or on ECDSA with the P-256 curve (secp256r1), offered on other chips in the range. The example below uses the ECDSA scheme; on ESP32-S3, generate an RSA key (--scheme rsa3072). The steps remain the same:

# Step 1: Generate the private key (on a dedicated workstation, never shared)
espsecure.py generate_signing_key --scheme ecdsa256 secure_boot_signing_key.pem

# Step 2: Burn the public key into efuses (IRREVERSIBLE)
# This operation locks the efuses — impossible to change the key afterward
espefuse.py burn_key DIGEST secure_boot_signing_key.pem --sha-digest
espefuse.py burn_efuse SECURE_BOOT_EN

# Step 3: Sign the firmware at each build
espsecure.py sign_data --keyfile secure_boot_signing_key.pem   --version 2 --output build/app-signed.bin build/app.bin

# Step 4: Verification by the bootloader at startup
# The SHA-256 hash of the signed firmware is compared to the efuse public key
# If mismatch => boot immediately stopped

These commands are schematic: efuse names and exact syntax vary by chip and ESP-IDF version. In practice, the efuse contains the SHA-256 hash of the public key; the bootloader compares this hash to the key provided with the image, then verifies the firmware signature. Consult the Espressif documentation before any burning.

Critical pitfall: once the SECURE_BOOT_EN efuse is programmed, secure boot can no longer be disabled and any unsigned firmware is rejected. If the private key is lost, no more updates can be installed on the product. Key management must be integrated into the build process, with secure backup (HSM or software vault).

Implementation on STM32 with TrustZone

The STM32U5 and STM32H5 integrate a hardware secure boot based on TrustZone (ARMv8-M) and OEMiRoT (OEM immutable Root of Trust):

/* OEMiRoT activation via STM32CubeProgrammer */
# 1. Burn the OEMiRoT bootloader in the secure zone
# 2. Configure RDP (Read Protection) at level 2 — irreversible
# 3. Boot verifies the SHA-256 hash of the user firmware before execution

/* Header structure for signed STM32 firmware */
typedef struct __attribute__((packed)) {
    uint32_t magic;              // 0x45535552 ('USER')
    uint32_t image_length;       // Total firmware size
    uint32_t image_version;      // Version incremented at each release
    uint8_t  sha256_hash[32];    // SHA-256 of the firmware
    uint8_t  signature[64];      // ECDSA P-256 signature
    uint32_t crc32;              // CRC32 of the header
} stm32_firmware_header_t;

The immutable bootloader verifies the image signature using a trust anchor stored in a protected zone. If it is valid, the firmware is decrypted (if encryption is enabled) then executed. The header structure above is a simplified example: the actual format is defined by ST's tooling.

Flash encryption: protecting data at rest

Flash memory encryption prevents extracting firmware and sensitive data (keys, certificates, configuration) by physically reading the component: bus snooping, microprobing or desoldering the SPI flash. This is an essential barrier when the product is installed at an unmonitored site.

ESP32: AES-XTS encryption

The ESP32-S3 encrypts flash with AES-XTS transparently: the flash controller integrates a hardware encryption and decryption engine, and the CPU reads data in clear without software intervention. The key is stored in efuses and becomes inaccessible to software once read-protected.

# Flash encryption activation (ESP32-S3)
# Development mode: the key can be regenerated (debug)
# Release mode: the key is locked — irreversible
espefuse.py --port /dev/ttyUSB0 burn_efuse FLASH_CRYPT_CNT 1
espefuse.py --port /dev/ttyUSB0 burn_efuse FLASH_CRYPT_CONFIG 0xF

# To activate Release mode (production):
espefuse.py --port /dev/ttyUSB0 burn_efuse FLASH_CRYPT_CNT 127
# The encryption key is then permanently inaccessible

# Secure data storage in flash (NVS):
# Use nvs_flash with the NVS_ENCRYPT_FLAG parameter
#include "nvs_flash.h"
esp_err_t ret = nvs_flash_secure_init(nvs_default_partition,
                                       nvs_encryption_keys);

As with secure boot, efuse names differ by chip (the commands above use those of the original ESP32). In practice, encryption is most often activated through the ESP-IDF project configuration rather than by manually burning efuses.

Pitfall: in Release mode, flash encryption is irreversible. Corrupted firmware or a failed update can render the product unusable. Imperatively test the OTA update mechanism before switching to Release mode: we recommend validating at least 100 successful OTA cycles in Development mode.

STM32: OTFDEC and RDP

STMicroelectronics combines on-the-fly decryption of external flash (OTFDEC, on-the-fly decryption) with read protection levels (RDP):

/* RDP configuration on STM32U5 */
// RDP Level 0: no protection (debug open)
// RDP Level 1: debug protection by password
// RDP Level 2: total protection, debug permanently closed (IRREVERSIBLE)

/* Activation via option bytes */
HAL_OB_ConfigRDP(OB_RDP_LEVEL_2); // Irreversible level

/* OTFDEC: automatic decryption of external flash */
/* The AES-256 key is stored in OTP (One-Time Programmable) */
OTFDEC_Config config = {
    .key = aes256_key,           // AES-256 key loaded from OTP
    .key_size = 32,
    .region = OTFDEC_REGION_1,
    .start_addr = EXT_FLASH_ADDR,
    .size = EXT_FLASH_SIZE
};
HAL_OTFDEC_Init(&otfdec_handle, &config);

RDP level 2 is the maximum protection: the SWD/JTAG port is permanently disabled and internal memory can no longer be read from the outside. Combined with OTFDEC for external flash, it effectively protects the product against common physical attacks. This code is illustrative: refer to the HAL API of your STM32 series for the exact syntax.

Remote updates (OTA, over-the-air) are both a functional necessity and the most exposed attack surface of an IoT product. An unsecured OTA channel allows an attacker to deploy their own firmware across an entire fleet.

Secure OTA architecture in three layers

  1. Secure transport: the firmware is downloaded over HTTPS (TLS 1.3) from an authenticated server. No unencrypted channel (HTTP, FTP).
  2. Firmware signature: the binary is signed with a private key distinct from the transport key. The device verifies the signature before applying the update.
  3. Dual partition with rollback: two firmware slots (A and B) allow reverting to the previous version in case of failure.

Implementation with ESP-IDF (esp_ota)

#include "esp_ota_ops.h"
#include "esp_https_ota.h"
#include "esp_image_format.h"

static const char *TAG = "ota";

/* Structure describing the update */
typedef struct {
    char url[256];              // HTTPS URL of the firmware
    uint8_t expected_sha[32];   // Expected SHA-256 (verified before flash)
    uint32_t version;           // Version number (for rollback decision)
} ota_update_info_t;

esp_err_t perform_secure_ota(const ota_update_info_t *update) {
    esp_http_client_config_t http_cfg = {
        .url = update->url,
        .cert_pem = server_cert_pem_start,  // Server certificate (SSL pinning)
        .timeout_ms = 30000,
        .keep_alive_enable = false,
    };

    esp_https_ota_config_t ota_cfg = {
        .http_config = &http_cfg,
        .partial_http_download = true,
        .max_http_request_size = 32768,
    };

    /* Download and automatic verification */
    esp_err_t ret = esp_https_ota(&ota_cfg);
    if (ret == ESP_OK) {
        /* Additional verification: compare version */
        const esp_partition_t *running = esp_ota_get_running_partition();
        esp_app_desc_t running_app_info;
        esp_ota_get_partition_description(running, &running_app_info);

        const esp_partition_t *update_part = esp_ota_get_next_update_partition(NULL);
        esp_app_desc_t update_app_info;
        esp_ota_get_partition_description(update_part, &update_app_info);

        if (update_app_info.version <= running_app_info.version) {
            ESP_LOGE(TAG, "Version downgrade detected — rollback");
            esp_ota_mark_app_invalid_rollback_and_reboot();
            return ESP_FAIL;
        }

        /* Validate the update */
        esp_ota_set_boot_partition(update_part);
        esp_ota_mark_app_valid_cancel_rollback();
        esp_restart();
    }
    return ret;
}

/* Bootloader: active slot selection */
void check_ota_rollback(void) {
    const esp_partition_t *boot_partition = esp_ota_get_boot_partition();
    esp_ota_img_states_t ota_state;
    if (esp_ota_get_state_partition(boot_partition, &ota_state) == ESP_OK) {
        if (ota_state == ESP_OTA_IMG_PENDING_VERIFY) {
            /* The firmware has not yet confirmed it works properly */
            if (app_self_test() == ESP_OK) {
                esp_ota_mark_app_valid_cancel_rollback();
                ESP_LOGI(TAG, "OTA validated — slot marked valid");
            } else {
                ESP_LOGE(TAG, "Self-test failed — rolling back");
                esp_ota_mark_app_invalid_rollback_and_reboot();
            }
        }
    }
}

Key points:

  • The server certificate is pinned (certificate pinning) in the firmware to prevent man-in-the-middle (MitM) attacks, even if a certificate authority is compromised.
  • The automatic rollback after self-test ensures that a defective firmware does not permanently block the product.
  • The downgrade detection (downgrade) prevents reinstalling an old vulnerable version.

Signing and server-side deployment

#!/usr/bin/env python3
"""OTA signing and deployment script — example pipeline"""
import hashlib, json, requests
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec, utils

def sign_firmware(firmware_path: str, key_path: str) -> dict:
    # Load the ECDSA P-256 private key
    with open(key_path, "rb") as f:
        private_key = serialization.load_pem_private_key(f.read(), password=None)

    # Compute the SHA-256 hash of the firmware
    with open(firmware_path, "rb") as f:
        fw_data = f.read()
    fw_hash = hashlib.sha256(fw_data).digest()

    # Sign the hash with ECDSA
    signature = private_key.sign(
        fw_hash,
        ec.ECDSA(hashes.SHA256())
    )

    # Package for deployment
    manifest = {
        "version": extract_version(firmware_path),
        "fw_hash": fw_hash.hex(),
        "signature": signature.hex(),
        "fw_size": len(fw_data),
        "algorithm": "ECDSA-P256",
    }
    return manifest

def deploy_ota(device_id: str, firmware_path: str, manifest: dict):
    """OTA deployment to a specific device"""
    with open(firmware_path, "rb") as f:
        files = {"firmware": f}
        payload = {"manifest": json.dumps(manifest)}
        resp = requests.post(
            f"https://ota.example.com/api/v1/devices/{device_id}/update",
            files=files, data=payload,
            headers={"Authorization": "Bearer <server_api_key>"},
            timeout=120
        )
    return resp.status_code == 200

Cryptographic key lifecycle management

The security of an embedded system ultimately rests on its keys. A compromised key renders all other mechanisms useless. Their management is therefore a strategic topic, often neglected at the prototype stage.

Typology of keys in an IoT system

Key typeUsageStorageRotation
Firmware signing keySign OTA binariesHSM or isolated workstation (offline)Rare and planned (provide several revocable keys)
Secure boot public keyVerify bootEfuse OTP (burned hash)Never (irreversible)
Flash encryption keyDecrypt firmware on the flyEfuse OTPNever (irreversible)
Device identity (DeviceID)MQTT/TLS authenticationEncrypted NVS or secure elementAt each factory reset
TLS client certificateMutual TLS with serverEncrypted flash and NVS slotPer policy (30 to 365 days)
Session keysApplication data encryptionRAM (volatile)At each session

Secure provisioning in production

Production is the most vulnerable phase of an IoT device's lifecycle: this is where the unique identity (identifier, certificate, private key) is injected into each unit. Three approaches exist:

  1. Factory provisioning: keys are generated by the production server and injected via the test port (JTAG/SWD) into a secure element (SE05x, ATECC608), then the flash is locked. This is the safest method, but it requires a controlled production infrastructure.
  2. On-site provisioning: the device generates its own key pair at first boot and sends the public key to the server via a pre-established TLS channel. This approach avoids handling private keys on the production line, but requires initial proof of identity (signed factory certificate).
  3. Dedicated PKI provisioning: a certificate authority (EJBCA, Smallstep CA, etc.) issues an individual certificate to each device upon first contact. The private key, generated locally, stays in the device.

Approach no. 3 offers a good compromise: a factory certificate burned in OTP allows the device to authenticate to an internal PKI, which issues its operational certificate. The corresponding private key is generated by the device and never leaves its secure element.

Secure storage with ATECC608 and SE05x

Secure elements (secure elements) are dedicated chips that keep keys in attack-resistant hardware and perform cryptographic operations without exposing the key to the main processor:

#include "cryptoauthlib.h"

/* Example: signing with ATECC608A (Microchip) */
ATCAIfaceCfg cfg = {
    .iface_type = ATCA_I2C_IFACE,
    .devtype = ATECC608A,
    .atcai2c.bus = 1,
    .atcai2c.address = 0x6C,
    .wake_delay = 1500,
};

ATCA_STATUS status = atcab_init(&cfg);
if (status != ATCA_SUCCESS) {
    ESP_LOGE(TAG, "ATECC init failed: %d", status);
    return ESP_FAIL;
}

/* Hashing the message to sign */
uint8_t message[] = "{"device":"node-42","timestamp":1728304921}";
uint8_t hash[32];
atcab_hw_sha2_256(message, sizeof(message), hash);

/* ECDSA signature with the key stored in slot 0 of the ATECC */
uint8_t signature[64];
uint8_t verified = 0;
status = atcab_sign(0, hash, signature);  // Slot 0 = private key
if (status == ATCA_SUCCESS) {
    /* Verification with the public key stored in slot 1 */
    status = atcab_verify(1, hash, signature, &verified);
}

/* Result: signature without the private key ever crossing the I2C bus
   in clear (the slot is configured as Never Export) */

Pitfall: ATECC608 configuration (slots, access rights, locking) is a one-time and irreversible operation. It must be planned in the production process (pre-provisioning by the manufacturer or configuration on a test bench), not improvised after assembly.

Protection against physical attacks

An IoT product installed in a public space (measurement station, remote management terminal, meter) is physically accessible. Several techniques can extract information from a device that is nevertheless secure on the software side.

Side-channel attacks

Analysis of power consumption (SPA/DPA), electromagnetic emissions or execution time can reveal information about keys. Countermeasures include:

  • Masking and randomization: masking intermediate values and randomizing the sequence of cryptographic operations.
  • Electromagnetic shielding: a metal enclosure connected to ground complicates electromagnetic eavesdropping.
  • Dummy operations (dummy cycles): inserting useless operations to blur the consumption profile.
  • Fault injection detectors: on high-end microcontrollers, integrated sensors detect laser or perturbation attacks and trigger an immediate reset.

Anti-intrusion and tamper detection

For critical products (remote management station, access controller), the following are added:

  • A tamper switch: a switch detects enclosure opening and erases volatile keys.
  • Battery-backed RAM: keys are kept in SRAM powered by a battery; if power is cut (desoldering), they disappear.
  • A protection mesh: a network of fine traces on the printed circuit board, monitored by a circuit that detects any break.

For the vast majority of industrial IoT use cases (sensors, actuators, gateways), the combination of secure boot, flash encryption, signed OTA and secure element offers a sufficient level of protection. Advanced physical countermeasures are reserved for highly critical applications (defense, sensitive infrastructure).

Complete security stack: overview

Here is how these mechanisms fit together in a typical industrial IoT product:

PhaseMechanismProtects against
ManufacturingKey burning in OTP, efuse locking, identity provisioningFactory tampering, identical keys from one unit to another
BootSecure boot (signature verification), hardware flash decryptionExecution of unauthorized firmware, flash extraction
OperationMutual TLS 1.3, application encryption, secure elementNetwork eavesdropping, MitM, device spoofing
UpdateHTTPS and ECDSA signature, dual partition, automatic rollbackMalicious firmware, downgrade, OTA corruption
MaintenanceLocked debug port (RDP level 2), signed logs, attestationReverse engineering, log replay, cloning
End of lifeRemote wipe, certificate revocation, key destructionIdentity reuse on a counterfeit device

Every link matters: a single weak point, for example an unsigned OTA, cancels the protection provided by all the others.

Security testing and certification

A secure firmware is not configured once and for all: new vulnerabilities appear and algorithms age. A continuous testing program is essential.

Recommended test plan

  1. Cryptographic unit tests: verify that each primitive (signing, verification, encryption) produces expected results on known test vectors.
  2. Boot integrity test: flash an unsigned firmware and verify that secure boot rejects it.
  3. OTA rollback test: simulate an update failure (network cut, corrupted firmware) and verify that the device reverts to the previous version.
  4. Flash extraction test: attempt to read the external flash with an SPI programmer and verify that data is encrypted.
  5. Network intrusion test: analyze TLS traffic, attempt a MitM attack with a fake certificate and verify that certificate pinning blocks the connection.
  6. Endurance test (30 days): simulate 10,000 OTA cycles to detect flash wear or a memory leak in the OTA manager.

Certification frameworks

Depending on the target market, certain certifications are required or strongly recommended:

  • PSA Certified (Arm): levels 1 to 3 for IoT devices; evaluates the chain of trust and key management in particular.
  • SESIP (GlobalPlatform): IoT component security evaluation methodology, recognized in Europe.
  • IEC 62443: series of standards for industrial automation system cybersecurity. The SL2 level (Security Level 2) is often considered a minimum for an industrial IoT product.
  • Common Criteria (ISO/IEC 15408): formal evaluation for regulated markets (defense, energy, healthcare).

Practical note: for an SME launching its first IoT product, certification is not an end in itself. However, the security architecture must be designed from the start so it can be certified later without a rewrite.

Conclusion: an investment rather than a cost

Firmware security is a prerequisite for any industrial IoT product deployed in real-world conditions. A poorly secured product exposes its manufacturer to legal risks (GDPR, product liability), financial risks (ransom, production loss) and reputational risks.

The mechanisms presented here — secure boot, flash encryption, signed OTA, secure element — are mature and available on both common microcontrollers (ESP32-S3, STM32U5, RP2350) and high-end platforms. Their implementation must be planned from the design phase; the development overhead is largely offset by risk reduction.

To go further, consult our articles on FreeRTOS in industrial environments, on industrial IoT network security and on embedded debugging with JTAG, OpenOCD and GDB.

An embedded IoT project?

Our team designs the box, its firmware and the platform. Let's discuss your needs.