Section 5.36

Constant-time cryptographic implementation

Definition

A constant-time cryptographic implementation is code for a cryptographic algorithm §14.1 whose observable behavior does not depend on secret values such as keys. For the same public inputs, it runs the same instructions, reads and writes the same memory addresses, and gives the same operand values to every instruction whose duration depends on its operands, whatever the secret is. Its running time may still depend on public values, such as the length of a message: the name means constant with respect to secrets, not a fixed duration.

The idea

A mathematically strong algorithm can still leak its key through the time its code takes. A device that compares a received tag (the short value that a message authentication code §5.7 computes from a key and a message) with the correct tag byte by byte, stopping at the first difference, rejects a guess sooner the fewer of its leading bytes are right. An attacker who times the rejections can therefore find the correct tag one byte at a time. Paul Kocher showed in 1996 that the running time of public-key operations can reveal the private key [337], and Daniel Bernstein showed in 2005 that the timing effects of table lookups were enough to recover the full key of AES (Advanced Encryption Standard) from a test server that used the OpenSSL cryptographic library [336].

A side channel §1.29, meaning any route by which information leaks other than the intended output, needs a difference in behavior to carry the information. Constant-time code removes the difference: the processor does the same things, in the same order, at the same addresses, for every key. The difficulty is that this must hold for the instructions the processor actually runs. The compiler chooses those instructions, and the processor’s microarchitecture §4.39 (its internal design: caches, pipelines and branch predictors) decides how long each one takes.

How it works

Timing reveals a secret through three kinds of dependence, and constant-time code follows one rule for each.

  1. No secret-dependent control flow. No branch, loop exit or early return may depend on a secret. A comparison that stops at the first differing byte breaks this rule. The repair compares every byte and decides once, at the end: it combines each pair of bytes with XOR (exclusive OR, which gives 0 in every bit position where the two bytes agree), merges the results with bitwise OR (a result bit is 1 when that bit is 1 in either input), and tests the merged value after the loop. The constant-time comparison §4.33 entry works through this loop.

  2. No secret-dependent memory addresses. A processor cache is a small, fast memory that holds recently used data in blocks called cache lines, often 64 bytes long. A read is faster when its line is already in the cache, so which lines a program used shows in its own timing and in the timing of other programs that share the cache. A table lookup whose index is computed from a key therefore reveals part of the index. The repair reads every entry of the table and keeps the wanted one with a mask, a value whose bits keep or clear the bits of another value, as shown below; or it computes the value without a table.

  3. No secret operands to variable-time instructions. Some instructions take a number of clock cycles that depends on their operand values: the hardware divide instructions of the Arm Cortex-M3 and Cortex-M4 §6.3 processors take between 2 and 12 cycles, depending on the values divided. Processor manuals rarely promise anything about timing. Some recent processors offer a mode that does promise data-independent timing for a listed set of instructions; Arm calls its version DIT (Data Independent Timing).

A branch on a secret bit bb is replaced by arithmetic with a mask. Let m=0−bm = 0 - b in unsigned arithmetic, where 0−10 - 1 wraps around to the largest value, whose bits are all 1: so every bit of mm is 1 when b=1b = 1, and m=0m = 0 when b=0b = 0. Then (x&m)|(y&¬m)(x \mathbin{\&} m) \mathbin{|} (y \mathbin{\&} \lnot m), where &\&, || and ¬\lnot are bitwise AND, OR and NOT, equals xx when b=1b = 1 and yy when b=0b = 0, with the same instructions in both cases. A constant-time table lookup reads every entry TiT_i of the table, computes for each a mask mim_i whose bits are all 1 only when ii is the wanted index, using a comparison that itself has no branch, and combines all the values Ti&miT_i \mathbin{\&} m_i with OR; only the wanted entry survives.

Source code is only half the job. Programming-language standards say nothing about timing, so compiler optimization §3.39 (the changes a compiler makes to speed up code without changing its result as the language defines it) may turn branch-free source back into a branch. Constant-time code is therefore checked on the compiled code: by reading the machine instructions; with tools such as ctgrind, which mark the secret bytes and report every branch or address that depends on them; or with tools such as dudect, which time many runs on two classes of secret inputs and apply a hypothesis test §11.22 to decide whether the two timing distributions differ.

Worked example

An early-exit comparison. A receiver checks a 16-byte tag with a loop that stops at the first differing byte. The attacker keeps one message fixed, so the correct tag stays the same. A blind search would have to cover 2128≈3.4×10382^{128} \approx 3.4 \times 10^{38} possible tags, since 16 bytes are 16×8=12816 \times 8 = 128 bits. Instead, the attacker sends the 256 tags that differ only in the first byte, 0x00 to 0xff. The one with the correct first byte is rejected slightly later, because the loop goes on to compare the second byte. Repeating this for each byte takes at most 16×256=409616 \times 256 = 4096 candidate tags, each sent many times so that averaging removes the noise.

A key-indexed table. A table-based AES implementation reads 4-byte entries from tables of 256 entries, so each table occupies 256×4=1024256 \times 4 = 1024 bytes, or 1024/64=161024 / 64 = 16 cache lines of 64 bytes. In the first round, the index is a plaintext byte XOR a key byte. Take the plaintext byte 0x3A, which the attacker knows, and the key byte 0x7C: the index is 0x3A XOR 0x7C = 0x46, which is 70. Entry 70 starts at byte 70×4=28070 \times 4 = 280 of the table, which lies in line ⌊280/64⌋=4\lfloor 280 / 64 \rfloor = 4, where ⌊x⌋\lfloor x \rfloor means xx rounded down; line 4 holds entries 64 to 79. An attacker who learns from timing that line 4 was used knows that the index lies between 64 and 79, so its upper 4 bits are 0100, the number 4. The upper 4 bits of the plaintext byte are 0011, the number 3, and XOR acts bit by bit, so the upper 4 bits of the key byte are 4 XOR 3 = 7. That is correct: 0x7C begins with the hexadecimal digit 7. Repeated for all 16 key bytes, this gives 64 of the 128 key bits; published attacks on the second round recover the rest.

The constant-time versions. Comparing A1 B2 C3 D4 with A1 B2 00 D4, the byte-wise XOR results are 00, 00, C3 and 00, and their OR is C3, which is not zero: the values differ, and all 4 positions were visited, as for any pair of values. The constant-time table lookup reads all 256 entries and keeps entry 70 with masks, so all 16 cache lines are used on every lookup, at the price of 256 reads instead of 1.

Stated precisely

Let pp be the public inputs of one run, such as the message and its length, and ss its secret inputs, such as the key. Define the leakage trace T(p,s)T(p, s) as the sequence of the following events, in the order they happen: the address of each instruction executed, which records every branch taken; the address of each memory read and write; and the operand values of each instruction that the target processor executes in operand-dependent time. The implementation is constant-time when T(p,s)=T(p,s′)for every public input p and all secret inputs s and s′.T(p, s) = T(p, s') \quad \text{for every public input } p \text{ and all secret inputs } s \text{ and } s'.

The guarantee rests on one assumption, the leakage model: the running time, and the effect of the run on hardware shared with other programs, such as the cache, are determined by TT and by the processor’s state when the run starts, and by nothing else. If it holds, an observer who knows pp and sees the running time or the cache afterwards learns nothing about ss. This is a noninterference §1.42 property: changing the secret inputs leaves a stated set of observations unchanged.

Limits and common mistakes

Constant-time code does not stop power analysis or electromagnetic analysis. The power a chip draws, and the field it radiates, depend on the data values it processes, so an attacker with a probe near the chip can recover keys from perfectly constant-time code. Countermeasures such as masking, which splits every secret value into random shares, are a separate subject.

Speculative execution can break the guarantee. A modern processor guesses the outcome of a branch and runs ahead; on a wrong guess it discards the results, but its memory reads can leave traces in the cache. The Spectre attacks, published in 2018 [252], use this. The definition above covers only instructions that complete.

Source code is not evidence. A new compiler version, a different optimization level, or a link-time optimization §12.10 that sees across files can reintroduce a branch, so the check is repeated for every build that ships.

Dependence on public data is allowed, but someone must decide what is public. If the length of a password or a message is secret, a loop over that length leaks it.

A timing test that finds no difference is not a proof: noise can hide a small leak, and an attacker can average many more runs than the test did.

Small microcontrollers §6.1 are not automatically safe. Many have no data cache, so a table lookup takes the same time for every index, but a flash memory §6.6 prefetch buffer or a cache added by the chip maker can change that. The argument must be made for the actual chip.

Questions answered

Does table lookup or variable-time comparison depend on key material?

Yes: when the table index or the compared bytes are computed from the key, the time these operations take depends on the key, and an attacker who measures that time recovers key material. A lookup whose index is computed from a key byte, as in table-based AES (Advanced Encryption Standard), reads a cache line (one of the fixed-size blocks in which the processor cache holds memory) chosen by the key; learning from timing which line was used reveals part of the index and so part of the key. A comparison that stops at the first differing byte runs longer the more leading bytes match. When it compares a received tag with the correct tag, the short value that a message authentication code computes from the key and the message, an attacker recovers the correct tag byte by byte, with at most 256 candidates per byte.

The repair is constant-time code: read every table entry and keep the wanted one with a mask, or avoid secret-indexed tables; compare all bytes and decide once at the end. Then check the compiled code, because a compiler may turn branch-free source code back into a branch.

Related entries: Constant-time comparison (§4.33), Side channel (§1.29), Compiler optimization (§3.39), Noninterference (§1.42), Microarchitecture (§4.39). Further reading: [252, 336, 337].