Check an image header
Validate an update image's header field by field, in the right order, without reading past what was received. A medium embedded C problem (Signed firmware…
medium · Signed firmware and the chain of trust · bootloader · security · parsing
An update image starts with a 16-byte header, little-endian:
| Offset | Size | Field |
|---|---|---|
| 0 | 4 | magic 0x31474D49 ("IMG1") |
| 4 | 2 | hardware id |
| 6 | 2 | version |
| 8 | 4 | payload length in bytes |
| 12 | 4 | CRC-32 of the payload |
and the payload follows. Write image_check(img, size, hw_id, min_version), where size is how many bytes arrived. Check, in this order, and return the first failure's code:
| Code | Failure |
|---|---|
| 1 | fewer than 16 bytes, or the wrong magic |
| 2 | the payload length does not fit in what arrived (16 + length > size) |
| 3 | the hardware id is not hw_id |
| 4 | the version is below min_version |
| 5 | the payload's CRC-32 is wrong (crc32() is written for you) |
Return 0 when every check passes. Read the fields byte by byte: the header may not be aligned. In a real bootloader a signature over the image is checked too: the CRC only proves the bytes arrived intact.
Starter code
int image_check(const uint8_t *img, uint32_t size, uint16_t hw_id, uint16_t min_version) {
uint32_t magic = img[0] | img[1] << 8 | img[2] << 16 | (uint32_t)img[3] << 24;
if (magic != 0x31474D49u) return 1;
uint32_t length = img[8] | img[9] << 8 | img[10] << 16 | (uint32_t)img[11] << 24;
uint32_t crc = img[12] | img[13] << 8 | img[14] << 16 | (uint32_t)img[15] << 24;
if (crc32(img + 16, length) != crc) return 5;
(void)size; (void)hw_id; (void)min_version;
return 0;
}Example tests
A good image, and one with a flipped payload byte
make();
printf("%d\n", image_check(img, 24, 0x0102, 1));
img[20] ^= 0x10;
printf("%d\n", image_check(img, 24, 0x0102, 1));Expected output:
0
5Another board's image, and an old one
make();
printf("%d\n", image_check(img, 24, 0x0201, 1));
printf("%d\n", image_check(img, 24, 0x0102, 4));Expected output:
3
4Learn it first
- Signed firmware and the chain of trust · Hashes, HMACs and signatures, a root of trust, key management, encryption and anti-rollback versions.