Simvik

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:

OffsetSizeField
04magic 0x31474D49 ("IMG1")
42hardware id
62version
84payload length in bytes
124CRC-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:

CodeFailure
1fewer than 16 bytes, or the wrong magic
2the payload length does not fit in what arrived (16 + length > size)
3the hardware id is not hw_id
4the version is below min_version
5the 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
5

Another 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
4

Learn it first