Posts Tagged ‘prevent cpld attack’

PostHeaderIcon Preventing Timing Attacks in Code: Constant Time, Not Slower Time

The first instinct when a timing leak is discovered is to add a delay. It is the wrong instinct, and understanding why takes about thirty seconds of arithmetic. If a comparison takes 100 ns when the first byte is wrong and 140 ns when the first two bytes are right, the difference is 40 ns. Adding a random delay of 0 to 1 µs makes each individual measurement useless. Averaging a thousand measurements reduces the noise by a factor of about thirty, and the 40 ns signal reappears, because the signal is constant and the noise is not.

Delays hide leaks. They do not remove them. The only code-level defence that survives averaging is code whose execution time is independent of the secret, which is a property of the code’s structure rather than of its speed.

The leak is in the control flow

Timing leaks on a microcontroller come from four sources, and three of them are the compiler’s doing rather than the programmer’s.

Source Mechanism Typical magnitude
Early return in a comparison Loop exits at first mismatch Tens of ns to µs
Branch on a secret bit Two paths, different lengths A few cycles
Table lookup with secret index Cache or flash wait states Tens of ns
Data-dependent arithmetic Multiply/divide by secret Cycles to tens of cycles

The first is the classic. A function that compares a supplied MAC against a computed one, byte by byte, and returns as soon as a byte differs, leaks the length of the matching prefix. An attacker who can measure that length recovers the MAC one byte at a time: 256 guesses per byte, times the length, instead of 256 to the length. A sixteen-byte tag drops from 2^128 to 4096.

The second is subtler because it looks harmless. A branch that tests a bit of the key and does one extra operation is a one-cycle difference on a fast core, and one cycle out of twenty is a two percent difference that averaging can resolve given enough samples. On a part with a cache, or with flash wait states that depend on the access pattern, the difference becomes much larger.

The pattern that replaces it

A constant-time comparison replaces the early return with an accumulator that runs to completion regardless of where the first mismatch is.

“ diff = 0 for i in range(n): diff |= a[i] ^ b[i] return diff == 0 “

Every iteration executes. There is no branch on the data, no early exit, and the loop count is public — it is the length of the tag, which is not a secret. The result is a boolean that depends on all bytes equally.

The same shape applies to other operations. A conditional selection becomes a mask: instead of if (bit) r = x; else r = y;, compute mask = -(bit & 1) and then r = (x & mask) | (y & ~mask). A conditional swap becomes an XOR swap gated by the mask. A table lookup with a secret index becomes a linear scan over the whole table with a mask per entry, which is slower by the table size and constant in time.

Dangerous pattern Constant-time replacement Cost
if (a[i] != b[i]) return 0; OR-accumulate XOR Same
if (secret) x++ ; Masked add A few cycles
table[secret] Full scan with mask O(n) instead of O(1)
while (secret) {...} Fixed iteration count Bounded by worst case

The last row is the one that hurts, because a loop whose trip count depends on the secret cannot be made constant without running the maximum number of iterations every time. Where that cost is unacceptable, the design has to change so that the trip count is public.

The compiler will undo your work

This is the failure mode that wastes the most time, and it is invisible in source review. A modern optimiser recognises the mask-and-select pattern as a conditional move and may convert it back into a branch, or may vectorise the OR-accumulator into a reduction whose length depends on the data. Either transformation restores the leak.

The defence is to check the generated code rather than the source. Compiling the function, disassembling it, and looking for conditional branches inside the loop is a two-minute check that catches most of these. Where the compiler insists on transforming, the options are to compile that translation unit at a lower optimisation level, to insert an optimisation barrier that the compiler cannot see through, or to write the loop in assembly.

The same applies to the loop bound. for (i = 0; i < n; i++) where n is a variable is fine if n is public, and is a leak if n is secret, regardless of what the body does. Making the bound a compile-time constant is often the simplest fix.

Where the leak moves next

Fixing the comparison moves the leak rather than removing it, and the new location is predictable. There are four places it typically goes.

The first is the error path. A function that now compares in constant time but returns a different error code for “wrong length” than for “wrong content” has told the attacker which of the two failed, and the length is often the more useful fact. Making both paths return the same code, after the same amount of work, is part of the same fix.

The second is the format check. A parser that validates a checksum before comparing the payload spends time proportional to how far the payload got before the checksum failed. If the checksum is over the secret, the parser leaks it. The fix is to validate in an order that does not depend on secret data, or to validate everything and combine the results at the end.

The third is the response transmission. A device that replies with a fixed-length frame is fine; a device that replies with a variable-length frame, or that pads to a block boundary derived from the secret, leaks the length. Length is a weak secret but it is often enough to narrow a search.

The fourth is the log. A device that writes a log entry on failure and a different one on success has a timing difference in the flash write, and flash writes are slow enough to be visible without any equipment beyond a current probe.

New leak location What it reveals Fix
Distinct error codes Which check failed Single code, equal work
Early format rejection Prefix validity Validate all, combine at end
Variable response length Secret length Fixed frame, public padding
Different log writes Outcome Same write path, dummy record

The general principle is that constant time is a property of the whole observable path, from the first input byte to the last output byte, and not of any single function. Auditing one function and declaring the device safe is the most common way this work is done badly.

Measuring whether it worked

A constant-time implementation is a claim, and claims about timing are testable. The test is straightforward: run the function many times with inputs that differ in the position of the first mismatch, collect the execution time distribution for each class, and compare the means.

With ten thousand samples per class, a difference of one clock cycle is usually detectable on a microcontroller with a cycle counter, because the measurement noise on a deterministic loop is small. If the distributions overlap completely across all mismatch positions, the implementation is constant in the dimension tested.

Test What it catches Sample count
Mismatch position sweep Early return 10k per position
Secret bit flip Branch on secret 10k per bit
Input length variation Length-dependent loop 1k per length
Power or EM correlation Data-dependent arithmetic 100k traces

The fourth row is beyond a timing test and belongs to the power side channel, but it is worth knowing that a function can pass the timing test and still leak through its current draw. Constant time is necessary and not sufficient.

What constant time cannot fix

Two limits are worth stating because customers sometimes expect more.

A constant-time implementation cannot fix a leak that comes from the platform rather than the code. If the flash controller’s wait states depend on the address, and the address depends on the secret, the leak is in the memory system. The fix is to make the access pattern public, which may mean copying the table into RAM, which may be impossible on a small part.

Nor can it fix a leak in a library that the code calls. A vendor crypto library that returns early inside its own comparison is a leak no amount of careful code around it will remove. Checking the library is part of the job, and a surprising number of production libraries fail this.

Where this fits with the rest

Code-level constant time is one of three defences, and it is the only one that removes the leak rather than masking it. The system-level defences, including why random delays fail against averaging, are covered in preventing timing attacks at system level. What the attacker is measuring in the first place, and the four shapes a leak can take, is in where timing leaks.

On the offensive side, the same knowledge drives assessment work: we build a timing profile of a protected routine, identify which of the four shapes it exhibits, and report whether the measurement budget on the actual board is sufficient to exploit it. That assessment is described in before a timing attack. Where the leak is real and the counter-measure is absent, the recovery of a credential from a device is covered in where the secret key lives. The service here is the audit and the measurement, and it is honest about the difference between a leak that exists and a leak that is reachable with the equipment the customer’s board allows.