Try Embedded

OTA updates and rollback

A/B slots, delta updates, rollback and signing.

Every connected device needs updates

Bugs ship. Security vulnerabilities are found after release. Regulations increasingly require security updates for a product's supported life. Over-the-air (OTA) updates are how firmware reaches devices in the field, and a bad update mechanism can brick a whole fleet at once. The design goals are simple to state and hard to get right:

  1. Never brick the device, even if power fails at any moment during the update.
  2. Only accept authentic firmware from the manufacturer.
  3. Recover automatically if the new firmware does not work.
  4. Use as little bandwidth, energy and flash as practical.

A/B (dual-bank) updates

The safest scheme keeps two complete firmware slots:

flash:  [ bootloader ][ slot A: running v1.4 ][ slot B: downloading v1.5 ][ config ]
  1. The running firmware downloads the new image into the inactive slot in the background, while continuing to work.
  2. It verifies the image (signature, hash) and marks slot B as "try once".
  3. It reboots. The bootloader boots slot B in trial mode.
  4. The new firmware runs self-tests (can it reach the server? are the sensors working?) and, if satisfied, confirms itself as good.
  5. If it crashes, hangs (watchdog reset) or fails to confirm within a set number of boots, the bootloader rolls back to slot A.

Power loss at any point leaves at least one valid slot. The cost is twice the flash for firmware. Some MCUs support bank swapping in hardware, remapping the two banks so both slots are linked at the same address.

On embedded Linux the same idea applies to root filesystem partitions (rootfs A and B), with tools such as RAUC, SWUpdate, Mender or OSTree and U-Boot's boot counter.

Single slot with a recovery image or staging area

When flash is too small for two full slots:

  • Overwrite with swap: download to a staging area, then the bootloader copies or swaps it into the primary slot, recording progress in flash so a power failure mid-copy resumes rather than corrupts. MCUboot's swap modes do this, and can swap back to roll back.
  • Recovery image: a small, rarely-updated recovery firmware that can download a full image if the main one is broken.
  • External flash as the staging area for MCUs with small internal flash.

Making updates smaller: delta updates

A full image over NB-IoT or LoRaWAN can take hours and drain the battery. A delta (patch) contains only the differences between the old and new versions; the device reconstructs the new image from its current one plus the patch. Typical tools: bsdiff-style algorithms, detools, Mender's delta, vendor solutions. Deltas are often 5 to 20% of a full image.

Requirements: the server must know exactly which version each device runs, and the device must verify the reconstructed image's signature, not just the patch.

#include <stdio.h>
#include <stdint.h>
#include <string.h>

/* A toy delta format: copy runs from the old image and insert new bytes. */
typedef struct { uint8_t op; uint16_t a, b; } patch_op_t;   /* op 0: copy old[a..a+b), op 1: insert b bytes from extra[a] */

int main(void) {
  const char *old_img = "FIRMWARE v1.4 BUILD 0331 CRC";
  const char *extra   = "5 BUILD 0412";
  patch_op_t patch[] = { { 0, 0, 12 }, { 1, 0, 12 }, { 0, 24, 4 } };

  char new_img[64] = { 0 };
  size_t n = 0;
  for (unsigned i = 0; i < sizeof patch / sizeof patch[0]; i++) {
    const char *src = patch[i].op == 0 ? old_img + patch[i].a : extra + patch[i].a;
    memcpy(new_img + n, src, patch[i].b);
    n += patch[i].b;
  }
  printf("old: %s\nnew: %s\n", old_img, new_img);
  printf("patch carried %u new bytes instead of %u\n", (unsigned)strlen(extra), (unsigned)n);
  return 0;
}

Security of updates

An update mechanism is the most powerful attack surface on a device: whoever controls it controls the device.

  • Sign every image with a private key kept offline or in an HSM; the device verifies with the public key (ECDSA P-256 or Ed25519) before installing and the bootloader verifies before booting (secure boot).
  • Encrypt images if the firmware contains secrets or IP worth protecting; signing alone does not hide contents.
  • Anti-rollback: a version counter (often in OTP fuses or protected storage) stops an attacker installing an older, vulnerable but validly signed version. Rollback to the previous slot after a failed update is allowed only within the protected minimum.
  • Transport security (TLS) protects the download, but the signature is what matters: it holds even if the server or CDN is compromised.
  • Frameworks such as Uptane (automotive) and TUF handle key compromise, role separation and metadata freshness for large fleets.

Running an update campaign

Fleet management matters as much as the device code:

  • Staged rollouts: 1% of devices, then 10%, then everyone, watching crash rates and confirmation rates at each stage, with the ability to halt.
  • Device reporting: each device reports its version, update result and failure reason.
  • Compatibility checks: hardware revision, bootloader version, current firmware version before offering an update.
  • Update windows and conditions: battery above a threshold, not in active use, good signal.
  • Long-term keys and certificates: plan for key rotation and for devices that come online after years in a warehouse.

Pitfall: Confirming the new firmware as good immediately at boot, before it has proven anything, makes rollback useless: a version that boots but cannot connect to the server would be confirmed, and the device is stranded. Confirm only after the critical functions, especially the ability to receive another update, have been verified.

Interview question: Design a robust OTA update for a microcontroller with external flash.

Answer: Use a small, rarely changed bootloader (for example MCUboot) that verifies image signatures with a public key in protected flash. The application downloads the new image into a staging slot in external flash over TLS, checks its hash and signature, and marks it pending. On reboot the bootloader verifies it again and swaps it into the internal primary slot using a power-fail-safe swap that records progress, booting it in trial mode. The new firmware runs self-tests including connecting to the update server, then confirms; a watchdog reset or failure to confirm makes the bootloader swap back. Add anti-rollback version counters and report results for staged rollouts.

Interview question: What is anti-rollback protection and why is it needed if images are signed?

Answer: Signing proves an image came from the manufacturer, but old images were also validly signed, including ones with known vulnerabilities. Without anti-rollback, an attacker could install an old signed version and exploit it. Anti-rollback keeps a monotonic security version counter in tamper-resistant storage such as OTP fuses or a secure element; the bootloader refuses images with a lower security version. It is raised when a release fixes a security issue, while normal rollback to the previous slot after a failed update stays allowed if it meets the minimum.

Build it: take an update over the car's network

This is step 4, the last of the module project. The electronic parking brake is updated in the workshop, or over the air through the car's gateway, using the diagnostic protocol every ECU speaks: UDS. The tester sends RequestDownload with the image size, the image in numbered TransferData blocks, then RequestTransferExit. CAN frames get lost and retried, so the same block can arrive twice, and the ECU must also refuse to start at all while the car is moving.

Lab: RequestDownload, TransferData and TransferExit

Each function returns 0 for a positive response, or a UDS negative response code (NRC).

  • uds_request_download(d, size, speed_kmh): refuse with NRC_CONDITIONS (0x22) unless the car is stationary, and with NRC_OUT_OF_RANGE (0x31) for a size of 0 or more than SLOT_SIZE. Otherwise start a download: nothing received yet, and the first block expected is number 1.
  • uds_transfer_data(d, seq, data, len): NRC_SEQUENCE (0x24) if no download is active.
  • If seq is the expected number, write the data to the update slot at the next offset with slot_write(offset, data, len), and expect seq + 1 next. Block numbers are 8 bits and wrap from 0xFF to 0x00.
  • If seq is the block just accepted (the tester did not get the response and sent it again), answer 0 without writing it again.
  • Any other number: NRC_WRONG_BLOCK (0x73), changing nothing.
  • A block that would take the total past the announced size: NRC_SUSPENDED (0x71).
  • uds_transfer_exit(d, crc): NRC_SEQUENCE if no download is active or fewer bytes than announced arrived. Otherwise end the download (it is no longer active, whatever the result) and compare crc with slot_crc(size), the CRC-32 of what is in the slot: if they differ, NRC_PROGRAMMING (0x72); if they match, call mark_pending() so the bootloader checks and installs it at the next start.

Going deeper

Interview question: How would you update the firmware of 50,000 thermostats safely?

Answer: Signed images, two slots with a bootloader that tries the new image and rolls back unless the application confirms it after a health check, anti-rollback version counters, and a staged rollout (1 %, then more) watching telemetry for crashes. The update must survive a power cut at any point, and the old image stays until the new one is proven.

Interview question: What is a delta update and what does it require?

Answer: Instead of downloading the whole new image, the device downloads a patch describing differences from the version it runs and reconstructs the new image from its current one. It can cut download size by 80 to 95 percent. It requires the server to know each device's exact version, enough space to build the new image, a robust reconstruction that survives power loss, and verification of the signature of the reconstructed image, not just the patch.

Interview question: How do staged rollouts reduce the risk of an update?

Answer: The update is first released to a small percentage of devices while their crash rates, update success, reconnection and key metrics are monitored, then widened in steps. A defect that slipped through testing affects a few devices that can be rolled back, and the rollout can be halted before the whole fleet is hit.

Explain it: In your own words, explain how an A/B update scheme avoids bricking a device.

Answer: The device has two slots for firmware. While running from slot A, it downloads the new version into slot B, verifies its signature and marks it for one trial boot, and the old version in slot A stays untouched. If power fails during the download, slot A still boots. After rebooting into B, the new firmware runs self-tests and confirms itself only if everything works, including reaching the update server. If it crashes, hangs or never confirms, the bootloader returns to slot A, so at every moment there is a known good image to fall back on.