Is this image safe to jump to?
Check a firmware image's header, bounds, CRC and vector table before a bootloader starts it. A hard embedded C problem (OTA updates and rollback), run and…
hard · OTA updates and rollback · bootloader · ota · crc · vector-table · robustness
Before a bootloader jumps into an application, it must be sure the image is complete, intact and built for this slot. Jumping into a half-written image is a brick. Write image_check(slot, slot_base, slot_size). slot points at the slot's bytes, which start at address slot_base on the chip.
Read the header from the start of the slot (use memcpy, since slot need not be aligned). Make these checks in this order and return the first that fails:
magicisIMG_MAGIC, orIMG_BAD_MAGIC.lengthis at least 8, a multiple of 4, and the header plus the image fit in the slot, orIMG_BAD_LENGTH. Check this before reading any image bytes, and beware ofHDR_SIZE + lengthoverflowing.load_addrisslot_base + HDR_SIZE, where the image actually sits, orIMG_BAD_ADDR.crc32of thelengthimage bytes equalsimg_crc, orIMG_BAD_CRC.- The image starts with its vector table. Word 0 is the initial stack pointer: it must be above
RAM_START, at mostRAM_END, and a multiple of 8, orIMG_BAD_SP. - Word 1 is the reset handler's address: bit 0 must be set (Thumb), and the address without bit 0 must be inside the image, after the two vector words (from
load_addr + 8up toload_addr + length, exclusive), orIMG_BAD_RESET.
Otherwise return IMG_OK.
Starter code
int image_check(const uint8_t *slot, uint32_t slot_base, uint32_t slot_size) {
img_hdr_t h;
memcpy(&h, slot, sizeof h);
if (h.magic != IMG_MAGIC) return IMG_BAD_MAGIC;
if (crc32(slot + HDR_SIZE, h.length) != h.img_crc) return IMG_BAD_CRC;
return IMG_OK;
}Example tests
A good image, then one flipped byte
build(64, RAM_END, BASE + HDR_SIZE + 0x21);
check("good");
slot[HDR_SIZE + 40] ^= 0x01;
check("flipped");Expected output:
good: ok
flipped: bad crcA bad vector table
build(64, RAM_END, BASE + HDR_SIZE + 0x20);
check("arm-mode reset");
build(64, 0x30000000u, BASE + HDR_SIZE + 0x21);
check("sp outside ram");Expected output:
arm-mode reset: bad reset
sp outside ram: bad spLearn it first
- OTA updates and rollback · A/B slots, delta updates, rollback and signing.
More OTA updates and rollback problems
- Pick the slot to boot · Boot a new update on trial, and roll back if it never confirms itself.
- Receive an update in chunks · Write update chunks to the spare slot in order, ignore resends, refuse gaps and overruns, and check the CRC at the end.
- Resume an update after a power cut · Keep download progress in an append-only flash journal, and find where to resume even after a torn write.
- Anti-rollback with one-time fuses · Refuse old, vulnerable firmware by its security version, counted in one-time-programmable fuses.
- Thermostat fleet: boot the update or roll back · Decide which firmware slot to boot, trying a new update a few times before rolling back.