Check the chain of trust
Verify each boot stage's hash and version before trusting the next. A medium embedded C problem (Secure boot and cryptography), run and graded in the browser.
medium · Secure boot and cryptography · secure-boot · hashing · rollback
Secure boot runs only code it has verified. Starting from ROM, each stage checks the next before jumping to it, forming a chain of trust. Two checks per stage:
- the image's hash equals its expected hash (it has not been modified),
- its version is not below that stage's minimum version, kept in one-time-programmable memory (anti-rollback: old, vulnerable firmware cannot be reinstalled). Each stage has its own counter:
min_versions[i].
Write verify_chain(stages, n, min_versions): check the stages in order and return the index of the first stage that fails either check, or -1 if all pass. When the whole chain passes, raise each stage's minimum to its version where that is higher (the device burns the new minimums). If any stage fails, change no minimum.
Starter code
int verify_chain(stage_t *stages, int n, uint32_t *min_versions) {
for (int i = 0; i < n; i++) {
if (hash32(stages[i].image, stages[i].size) != stages[i].expected_hash) return i;
}
(void)min_versions;
return -1;
}Example tests
A good chain raises the minimums
stage_t s[2];
chain(3, 7, s);
uint32_t min[2] = { 2, 5 };
show(s, min);Expected output:
boot OK; minimums now 3 and 7A modified application
stage_t s[2];
chain(3, 7, s);
app[0] ^= 1; /* one bit changed */
uint32_t min[2] = { 1, 1 };
show(s, min);
app[0] ^= 1;Expected output:
stage 1 rejected; minimums stay 1 and 1Learn it first
- Secure boot and cryptography · Chains of trust, key storage, crypto accelerators and attacks.