Side channels and glitches
Timing and power side channels, constant-time code, glitching single decisions, and lockouts that hold.
The attacker with the device in hand
Network attackers see only the bytes a device sends. An attacker who holds the device sees much more: how long each answer takes, how much current the chip draws at each instant, what it radiates, and what it does when its supply or clock is disturbed. These are physical attacks, and they defeat code that is logically correct. They need no bug in the usual sense; they need code that was not written with them in mind.
This lesson covers the two families embedded engineers must design against: side channels (the device leaks information) and fault injection (the attacker makes it compute wrongly).
Timing side channels
The textbook example is the one almost everyone writes first:
int check_pin(const char *guess) {
for (int i = 0; i < 4; i++)
if (guess[i] != pin[i]) return 0; /* stops at the first wrong digit */
return 1;
}
It answers sooner when the first digit is wrong than when only the last one is. An attacker who measures the time to the answer (a scope on the UART's TX line resolves a single instruction) tries 0xxx to 9xxx, keeps the digit that took longest, and moves on: at most 40 guesses instead of 10 000. The same leak hides in memcmp, strcmp, early-exit loops over MACs and passwords, and any branch on a secret.
The fix is to make the time independent of the secret: examine every byte, combine the differences without branching, decide once.
#include <stdio.h>
#include <stdint.h>
/* The time does not depend on where the inputs differ: every byte is looked at, and the decision is made once. */
static int equal_ct(const uint8_t *a, const uint8_t *b, unsigned n) {
uint8_t diff = 0;
for (unsigned i = 0; i < n; i++) diff |= (uint8_t)(a[i] ^ b[i]);
return diff == 0;
}
/* Counts the loop's steps, as a stand-in for its time. */
static unsigned steps_naive(const uint8_t *a, const uint8_t *b, unsigned n) {
unsigned s = 0;
for (unsigned i = 0; i < n; i++) { s++; if (a[i] != b[i]) break; }
return s;
}
int main(void) {
const uint8_t pin[4] = { 4, 7, 1, 1 };
const uint8_t guesses[3][4] = { { 0, 0, 0, 0 }, { 4, 7, 0, 0 }, { 4, 7, 1, 0 } };
for (int g = 0; g < 3; g++)
printf("guess %d: naive steps %u, constant-time result %d\n", g, steps_naive(guesses[g], pin, 4), equal_ct(guesses[g], pin, 4));
return 0;
}
Constant time is a property of the compiled code, not the C. Compilers can turn a branch-free loop back into an early exit, especially at high optimisation; check the disassembly of security-critical comparisons, and use the platform's audited functions (mbedtls_ct_memcmp, libsodium's sodium_memcmp) where they exist.
Power and electromagnetic side channels
A CMOS chip's current depends on the data it processes: writing 0xFF to a register draws more than writing 0x00, because more bits switch. With a small resistor in the supply and an oscilloscope, an attacker records the current while the device encrypts, and:
- Simple power analysis (SPA) reads secrets from one trace when the code's sequence depends on them: an RSA or ECC implementation that does a multiply only for 1 bits of the key shows the key in the trace's pattern.
- Differential power analysis (DPA) and correlation power analysis use thousands of traces with known inputs and statistics to recover an AES key from the tiny data-dependent differences, typically in minutes to hours with a few hundred dollars of equipment (ChipWhisperer).
Countermeasures are mostly a matter of choosing implementations: constant-time, constant-sequence cryptography; masking (computing on the secret XORed with a fresh random value); random delays and shuffling; and above all hardware AES and PKA engines built with countermeasures, or a secure element that holds the key. General-purpose firmware should not implement cryptography itself.
Fault injection: glitches
A glitch is a brief disturbance outside the chip's specification: the supply pulled down for 50 ns, one clock cycle shortened, an electromagnetic pulse over the die, a laser on a transistor. Timed well, it makes the core skip an instruction, read a wrong value from flash, or take a branch the wrong way, without crashing. Famous results include bypassing readout protection on several MCU families and extracting firmware from hardware wallets.
The most common target is a single decision:
if (signature_ok(image)) boot(image); /* one branch: skip it, and the check never happened */
else lock_up();
One instruction skipped at the right moment (the compare, or the branch after it) and an unsigned image boots. The defences assume the attacker gets one fault per attempt:
- Decide twice, differently. Check the condition again later, from a recomputed value, so a single skip cannot pass both.
- Use values a single fault cannot produce. Instead of 0 and 1, return
0x3CA5for success and0xC35Afor failure; a skipped instruction or a zeroed register gives neither, and anything else is treated as an attack. - Count the steps. A counter incremented at each step of a critical sequence, checked at the end, shows a skipped step.
- Default to failure. Initialise the result to "denied" so a skipped assignment leaves it denied.
- Random delays before critical checks make the moment to glitch hard to find.
- Detect and react: hardware glitch detectors, brown-out detectors set tight, and a lockout or key erasure when a check finds an inconsistency.
#include <stdio.h>
#include <stdint.h>
#define GRANTED 0x3CA5u
#define DENIED 0xC35Au
static volatile uint32_t steps;
/* A decision a single skipped instruction cannot turn into GRANTED: the result starts DENIED, the comparison is
constant time, its outcome is turned into an unusual value, and the caller checks it twice and the step count. */
static uint32_t check(const uint8_t *guess, const uint8_t *secret, unsigned n) {
uint32_t result = DENIED;
uint8_t diff = 0;
for (unsigned i = 0; i < n; i++) { diff |= (uint8_t)(guess[i] ^ secret[i]); steps++; }
if (diff == 0) result = GRANTED;
return result;
}
int main(void) {
const uint8_t secret[4] = { 4, 7, 1, 1 }, guess[4] = { 4, 7, 1, 1 };
steps = 0;
uint32_t r = check(guess, secret, 4);
if (r == GRANTED && steps == 4) {
if (r == GRANTED) printf("unlocked\n"); /* the second, separate check */
} else if (r != DENIED) {
printf("fault detected: lock out\n"); /* neither value: something was skipped */
} else {
printf("denied\n");
}
return 0;
}
The simulator can glitch a board: a test's glitch input skips the instruction the chip is about to run, at the moment the test chooses. Sweep it across your check on your own build and see whether any one skip unlocks it.
Lockouts that hold
The last defence against guessing, electronic or physical, is a limit on attempts. It only works if the attacker cannot reset it:
- Count failures before acting on the result (or before answering), so cutting the power the moment a wrong answer is detected does not give a free attempt.
- Keep the count where a reset cannot clear it: a checked RAM record survives a reset but not a power cycle; flash or EEPROM survives both but wears, so write it with wear levelling or a few bits at a time.
- At boot, if the count says locked, start the delay again.
- An inconsistent counter (a bad CRC) means locked, never "start from zero".
Going deeper
Interview question: What is a timing side channel, and how do you write a comparison that does not have one?
Answer: It is information about a secret leaked through how long an operation takes. A comparison that returns at the first differing byte runs longer the more leading bytes are right, so an attacker measuring response times can find a PIN, password or MAC byte by byte with a few guesses per position instead of trying every combination. A constant-time comparison examines every byte regardless, accumulating the differences with XOR and OR into one value without branching on it, and makes one decision at the end. The compiled code must be checked too, since compilers can reintroduce early exits, and the same rule applies to any code that branches or indexes memory on secret data.
Interview question: How can firmware be hardened against voltage or clock glitching attacks?
Answer: Assume the attacker can cause one fault per attempt, typically a skipped or corrupted instruction, and make sure no single fault changes a security decision. Default results to failure, encode success and failure as values with large Hamming distance rather than 0 and 1, check critical conditions twice in different ways and compare, count steps through a critical sequence and verify the count, add random delays before checks to make timing them hard, and treat any inconsistency as an attack that triggers a lockout or key erasure. Combine that with hardware: glitch and brown-out detectors, the chip's readout protection, and secure elements for keys.
Interview question: What is differential power analysis, and why should most firmware not implement its own cryptography?
Answer: It recovers keys by recording the chip's power consumption over many operations with known inputs and correlating the tiny data-dependent variations with a model of the algorithm's intermediate values, for example the AES S-box output for each key byte guess; with enough traces the correct key guess stands out. Defending against it needs careful implementation: constant-time and constant-sequence code, masking with fresh randomness, shuffling, and noise. Getting that right is specialist work, so firmware should use the MCU's hardware crypto accelerators, audited libraries with side-channel countermeasures, or a secure element that keeps the key off the main chip entirely.
Explain it: In your own words, explain why a single if (signature_ok) boot(); is weak against glitching, and what makes a check robust.
Answer: The whole security decision rests on one branch, and a glitch timed to skip or corrupt that one instruction makes the code take the success path whatever the check found. A robust check makes one fault insufficient: the result starts as failure, success is an unusual value that a skipped write or zeroed register cannot produce, the condition is checked again separately before acting, and a count of completed steps proves nothing was skipped. Any disagreement between the checks is treated as an attack, so the attacker would need two precisely placed faults in one attempt, which is far harder.