Algorithmresearch
Constant-time verification
Also called ct-verif.
Proves that a program is constant time by reducing the two-run property to a safety check on a product program.
- Time
- O(n^2 + m t) worst
- Space
- O(n^2) extra
- Where
- m = the number of start pairs with equal public inputs; n = the size of the program; t = the number of steps of one run of the product
- Model
- Word RAM
- Properties
- deterministic
- Evidence
- Proof sketchCode in 1 languages
- Origin
- José Bacelar Almeida, Manuel Barbosa, Gilles Barthe, François Dupressoir, Michael Emmi, 2016
Constant-time verification proves that a program is constant time: for any two runs with the same public inputs, the program takes the same branches, accesses the same memory addresses and gives the same operands to variable-time instructions. This is a property of two runs, a hyperproperty of the 2-safety class. The algorithm of Almeida et al. (2016) builds one product program that runs two copies of the input program in lockstep and asserts before each statement that the two copies leak the same thing. The input program is constant time exactly when the product can never fail an assert, which is an ordinary safety question for a standard verifier.
In plain words
A program that handles a key must not let the key change what an observer can see from outside. The observer cannot read the data, but can see which way each branch goes and which memory cells the program touches, for example through the cache. To check this, think of two copies of the program. Both get the same public data, but each gets a different key. Run them side by side, one step at a time. Before each step, check that the two copies are about to show the same thing to the observer. If this holds for every possible pair of keys, the key never shows. The product program is this side-by-side run, written as one program, so a normal program checker can prove it safe.
The problem
The input is a program , a set of public inputs and a leakage model. The leakage model says what one step of a run shows to the observer. The output is "constant time", or a pair of start states that agree on and give two different leakage traces.
The observer of this page sees, for each run, the trace of leakage events and nothing else. In the toy language of the code these events are: the decision of each branch, the count of each loop, the array and the index of each memory access, and the two operands of each division. The values that the program computes are not in the trace. This is the constant-time policy of Almeida et al.: the sequence of branch decisions and memory addresses does not depend on secret inputs. Formally, is constant time when
for all start states , where is the leakage trace and means equal on the public inputs. This is noninterference with the trace as the output.
The algorithm
Each variable and array gets a fresh shadow copy , and is the expression with every name replaced by its shadow. The leak terms of an expression are the subexpressions whose values its evaluation shows: the index of each load and both operands of each division. The joined state holds the first run in the plain names and the second run in the shadow names.
CT-VERIF(P, X, D) ▷ X: the public inputs, D: the finite domain of the inputs- 1
Q ← PRODUCT(P) - 2
for each pair (σ, σ̂) of start states over D with σ(x) = σ̂(x) for each x in X do - 3
run Q from the joined state σ ⊕ σ̂' - 4
if an assert of Q fails then - 5
return (false, σ, σ̂) - 6
return true PRODUCT(B) ▷ B is a block of statements- 7
for x ← e: emit assert G(e); x ← e; x' ← e' - 8
for a[i] ← e: emit assert G(i) ∧ G(e) ∧ i = i'; a[i] ← e; a'[i'] ← e' - 9
for if c then B1 else B2: - 10
emit assert G(c) ∧ (c ≠ 0) = (c' ≠ 0); if c then PRODUCT(B1) else PRODUCT(B2) - 11
for repeat e times B1: emit assert G(e) ∧ e = e'; repeat e times PRODUCT(B1) - 12
do this for each statement of B in order, and return the emitted block G(e) ▷ the leakage of e is the same in both copies- 13
return the conjunction of l = l' over the leak terms l of e
The asserts of lines L10 and L11 make the two copies take the same branch and the same number of iterations. So the product needs only one copy of the control structure, and it has as many paths as . A plain self-composition has the product of the two path counts.
Lines L2 to L5 are the safety check. The code of this page does it by brute force over a small domain , which is enough for a toy program and for the test. The ct-verif tool proves the same product safe for every input with a deductive verifier: it gives each loop of the product the invariant that each variable equals its shadow where the copies must agree, and it sends the verification conditions to an SMT solver.
Example
Take values mod 4, one public input , one secret input and a public table . The product of the one-line program is
The pair , with fails the assert, and the two traces are the accesses to and to . The verifier finds the five verdicts below.
| program | verdict | first witness |
|---|---|---|
| not constant time | and , with | |
| if then else | not constant time | and |
| not constant time | and | |
| , then for : | constant time | none |
| if then else | constant time | none |
The fourth program reads every cell of and keeps the right one with a mask that is all ones or all zeros, so it computes with the same four accesses for every . This is the full-scan lookup of constant-time programming. The last program is constant time because for every , so the branch is always the same. A security type system rejects it, because the guard has a secret type. The product accepts it, because it reasons about values.
The trace also fixes the cost in an abstract cache. With 4 sets, 1 way, lines of 1 cell and costs of 1 for a hit and 10 for a miss, the program costs 11 units when and 20 units otherwise. The verifier rejects it. The masked lookup has the same cost for every .
Correctness
The proof is a lockstep simulation. Run PRODUCT from the joined state of and . By structural induction on , either the product ends with no failed assert, the two runs of have the same trace and the product ends in the joined state of the two final states, or an assert fails and the two traces differ. The key step is that the events a statement emits before it enters a sub-block have a length fixed by the program text, and the assert before the statement holds exactly when these events are equal in the two copies. A failure therefore comes after two equal prefixes of equal length, so the traces differ. Line L2 enumerates every pair with equal public inputs, so CT-VERIF returns true if and only if is constant time on , and every witness it returns is a real pair of distinguishable runs. This is the toy form of Theorem 1 of Almeida et al., which they proved in Coq. The full proof is below.
Proof: The product check accepts a program exactly when the program is constant timefull
The setting. This is the toy language of the page. Values are the integers mod , every array has cells, a division by 0 gives 0, and a loop repeats its body times. So every expression has a value in every state, and every run of a program stops (by induction on the program text, with an inner induction on the loop count). A state maps variables and arrays to values. A run of a block from gives a final state and a trace of events. No name in ends with a prime, so the shadow names are fresh. For two states and , the joined state maps to and to .
Definition. is constant time when for all start states and that agree on the public inputs and on the tables, and that give the value 0 to every other variable.
Lemma 1 (renaming). For each expression and states , the value of in is the value of in , and the value of in is the value of in . A statement of writes only names without a prime, and its shadow copy writes only names with a prime.
Proof. By induction on . The shadow copy replaces each variable by and each array by and keeps the operators, and the joined state gives the value . The second claim holds because reads no primed name. The claim on writes is clear from the form of the copy.
Lemma 2 (the events of an expression). The evaluation of emits one event for each load node and one for each division node of , in a fixed order that depends on the text of only. The event of a load is , where is the value of the term . The event of a division is , with the values of the terms and . These terms are exactly the leak terms of that line L13 collects. So the events of in and in are equal if and only if each leak term has the same value in and in .
Proof. By induction on , from the definition of the evaluation. The two event lists have the same length and the same array names at each position, so they are equal exactly when the values at each position are equal.
Corollary 3 (the guard). evaluates to 1 in if and only if the events of in equal the events of in .
Proof. is the conjunction of over the leak terms . By Lemma 1 the two sides have the values of in and in . Apply Lemma 2.
The head of a statement. Call the events that a statement emits before it runs a sub-block the head . For it is the events of . For it is the events of , then of , then . For a branch on it is the events of , then . For a loop on it is the events of , then . By Lemma 2 the length of the head depends on the text of only, and by Corollary 3 and the form of lines L7 to L11, the assert that PRODUCT puts before holds in if and only if . For the branch, the extra conjunct compares the branch events. For the store and the loop, the conjuncts and compare the address and the count.
Lemma 4 (lockstep). For each block and states , the run of PRODUCT from does one of two things.
- It ends with no failed assert. Then , and the final state is .
- It stops at a failed assert. Then .
Proof. By induction on the text of and, inside a loop, on the number of iterations. The empty block gives case 1 with two empty traces.
Let . The product is the assert , then the product of without that assert, then PRODUCT (line L12). Write , where is the trace of the sub-blocks that runs, and do the same for .
If fails, then by the head property. The two heads have the same length, so the two traces differ at a position inside the heads, and case 2 holds.
If holds, the heads are equal. Look at the form of .
- or . The product runs and then its shadow copy. By Lemma 1 the first writes 's value into the name without a prime and the second writes 's value into the primed name. So the state becomes , and is empty on both sides.
- A branch on . The assert gives in exactly when in , so the product takes the same arm that both runs take. Apply the induction hypothesis to PRODUCT, a shorter text.
- A loop on . The assert gives the same count in both runs, and the product repeats PRODUCT times. Apply the induction hypothesis to each iteration in turn. If an iteration fails, the traces of that iteration differ, after equal traces of the earlier iterations; since a failure in case 2 comes with traces that differ at some position, and the earlier parts have equal length, the full traces differ.
In each form, either a failure inside gives traces that differ after an equal prefix, which is case 2, or ends in the joined state of the two runs with equal traces. Then apply the induction hypothesis to from that joined state. A failure in comes after equal prefixes of the same length, so the full traces differ. Success in gives equal full traces and the joined final state.
Theorem. CT-VERIF returns true if and only if is constant time over the domain . When it returns false, the pair that it returns agrees on the public inputs and gives two different traces.
Proof. Line L2 lists every pair of start states that agree on the public inputs and on the tables, with 0 for every other variable. This is the assumption step of the product. Line L3 runs PRODUCT from the joined state of the pair. By Lemma 4, an assert fails on a pair if and only if the two traces of on that pair differ. So line L5 returns a pair only when it is a true witness, and line L6 is reached only when no pair gives two traces, which is the definition of constant time. Each run stops, so the check stops.
Corollary (the abstract cache). If is constant time, then for each cache geometry, the cost of CACHE-COST is the same for all start states with the same public inputs.
Proof. The cache starts empty, and its cost is a function of the sequence of addresses over the address events of the trace. Equal traces give equal sequences, and so equal costs. The converse is false: two different traces can have the same cache cost, for example when two secret indices fall in the same line. So the cost in one cache model is a weaker observation than the trace, and the constant-time policy is the stronger guarantee.
Complexity
PRODUCT visits each statement once. The guard repeats each leak term, and a leak term can contain other leak terms, so the product has size in the worst case and when the nesting depth of the expressions is bounded. Each run of the product takes steps. The brute-force check runs the product on start pairs, for public and secret inputs, so the total time is and the extra space is the size of the product.
The number grows exponentially with the number of inputs, so the brute-force check is only a model. With a deductive verifier the cost is the cost of the safety proof of one program of the size of . For programs with unbounded loops and memory, the safety of a program is undecidable in general, so no checker is complete and fast on every input.
Properties
- Sound and complete for programs without public outputs (theorem). Theorem 1 of Almeida et al. states that a safe program without public outputs is constant time if and only if its output-insensitive product is safe. The guarantee holds against an observer who sees the leakage trace of the model in each run.
- Sound only when outputs are public (theorem). If a program declares some outputs public, for example the length of a decrypted message, the output-insensitive product rejects some correct programs. The output-sensitive product of their Theorem 2 accepts more programs, and it is sound but not complete.
- The paths of , not the square. The product keeps the control flow of , so a path-based verifier sees no more paths in than in .
- The model decides the meaning. "Constant time" is relative to the leakage model. A model with branches and addresses only says nothing about a multiplication or a division that takes a data-dependent time on a given processor. Add their operands to the model to cover them, as the code does for division.
- No speculation. The model describes the paths that the program really takes. A processor that runs a wrong path for a short time, as in a Spectre attack, can leak secrets that no real path touches. A proof of this page does not cover that observer.
Variants and improvements
- Output-sensitive product. Some branches may depend on values that are public outputs. The output-sensitive product lets the copies take different paths there, and records the public outputs in history variables.
- Type systems. A security type system for constant time gives each variable a level and rejects a secret guard or a secret index. It is fast and modular but rejects programs such as the example.
- Symbolic execution and model checking. A symbolic execution or bounded model checking of the product finds witnesses on bounded runs.
- Quantitative checks. A cache-aware abstract interpretation can bound how many different cache states a program can reach, which gives a bound on the leak in bits instead of a yes or no answer.
- Statistical tests. dudect (Reparaz et al. 2017) runs the binary on two classes of inputs and applies a Welch t-test to the measured times, in the style of TVLA. It is a measurement on one machine, not a proof, and it can miss a leak that its inputs do not trigger.
- Speculative constant time. Later work extends the observer with mispredicted paths, so that a verified program also resists the Spectre class of attacks.
When to use it
Use it on the core routines of cryptographic code, such as field arithmetic, table lookups, comparisons of tags and padding checks, where the code is small, the secret inputs are clear and a leak is a key. Check the lowest level that you can, such as LLVM code or the binary, because a compiler can turn a masked select back into a branch. For a whole application, a type system or a taint check is cheaper; for code that you cannot change, a statistical test gives a measurement.
Pitfalls
- Checking the source only. A proof on C source says nothing about the machine code if the compiler adds a branch or a table. ct-verif works on optimized LLVM code for this reason.
- A leakage model that is too weak. If the model leaves out variable-time instructions, the proof holds for a machine that does not exist.
- Forgetting public outputs. A program that reveals a public output, such as a message length, fails the output-insensitive check. Declare the output and use the output-sensitive product; do not weaken the leakage model.
- Confusing this with a timing test. The verifier proves a property of a model. A timing attack is a measurement on real hardware. The two meet only if the model covers every source of time variation on that hardware.
- Exhaustive checks on a tiny domain. The brute-force check of the code is complete only for the domain that it enumerates. A larger word size needs a symbolic proof.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/constant-time-verification/. The authors are listed in prov/B355TH.jsonl.
"""Constant-time verification by a product program, on a toy language.
The toy language works on the integers mod w. It has no real memory, no
real cache and no clock. A run gives a leakage trace of abstract events:
("br", b) the decision b of a branch
("loop", n) the iteration count n of a loop
("addr", a, i) an access to cell i of the array a
("div", x, y) the two operands of a division
Expressions are tuples:
("c", n) the constant n mod w
("v", x) the variable x (a variable that was not set is 0)
("ld", a, e) the cell e of the array a
("div", e1, e2) e1 div e2, and 0 when e2 is 0
(op, e1, e2) op is one of + - * & | ^ < ==
Statements are tuples, and a block is a list of statements:
("set", x, e) x <- e
("st", a, i, e) a[i] <- e
("if", c, b1, b2) if c != 0 then b1 else b2
("rep", e, b) repeat the block b e times
("assert", e) only in product programs: e must not be 0
Every array has w cells, so every index is a valid cell, every program is
total and every run stops. The shadow copy of a variable or array x is
named x + "'".
"""
from collections.abc import Mapping, Sequence
from itertools import product as cartesian
Expr = tuple
Stmt = tuple
Block = list
Event = tuple
OPS = ("+", "-", "*", "&", "|", "^", "<", "==")
class AssertFailed(Exception):
"""An assert of a product program is false."""
def _binop(op: str, a: int, b: int, w: int) -> int:
if op == "+":
return (a + b) % w
if op == "-":
return (a - b) % w
if op == "*":
return (a * b) % w
if op == "&":
return (a & b) % w
if op == "|":
return (a | b) % w
if op == "^":
return (a ^ b) % w
if op == "<":
return 1 if a < b else 0
if op == "==":
return 1 if a == b else 0
raise ValueError(f"unknown operator {op!r}")
def _eval(e: Expr, env: dict[str, int], arrs: dict[str, list[int]], w: int, trace: list[Event] | None) -> int:
tag = e[0]
if tag == "c":
return e[1] % w
if tag == "v":
return env.get(e[1], 0)
if tag == "ld":
i = _eval(e[2], env, arrs, w, trace)
if trace is not None:
trace.append(("addr", e[1], i))
return arrs[e[1]][i]
a = _eval(e[1], env, arrs, w, trace)
b = _eval(e[2], env, arrs, w, trace)
if tag == "div":
if trace is not None:
trace.append(("div", a, b))
return a // b if b else 0
return _binop(tag, a, b, w)
def _exec(block: Block, env: dict[str, int], arrs: dict[str, list[int]], w: int, trace: list[Event] | None) -> None:
for s in block:
tag = s[0]
if tag == "set":
env[s[1]] = _eval(s[2], env, arrs, w, trace)
elif tag == "st":
i = _eval(s[2], env, arrs, w, trace)
v = _eval(s[3], env, arrs, w, trace)
if trace is not None:
trace.append(("addr", s[1], i))
arrs[s[1]][i] = v
elif tag == "if":
c = _eval(s[1], env, arrs, w, trace) != 0
if trace is not None:
trace.append(("br", c))
_exec(s[2] if c else s[3], env, arrs, w, trace)
elif tag == "rep":
n = _eval(s[1], env, arrs, w, trace)
if trace is not None:
trace.append(("loop", n))
for _ in range(n):
_exec(s[2], env, arrs, w, trace)
elif tag == "assert":
if _eval(s[1], env, arrs, w, None) == 0:
raise AssertFailed
else:
raise ValueError(f"unknown statement {tag!r}")
def run(prog: Block, inputs: Mapping[str, int], tables: Mapping[str, Sequence[int]], w: int = 4) -> tuple[dict[str, int], list[Event]]:
"""Run prog once and return the final variables and the leakage trace.
Precondition: w >= 2, each input is in range(w), and each table has w
cells with values in range(w). Cost: O(t) for a run of t steps.
"""
env = dict(inputs)
arrs = {a: list(t) for a, t in tables.items()}
trace: list[Event] = []
_exec(prog, env, arrs, w, trace)
return env, trace
def _sh(e: Expr) -> Expr:
"""The shadow copy e' of the expression e."""
tag = e[0]
if tag == "c":
return e
if tag == "v":
return ("v", e[1] + "'")
if tag == "ld":
return ("ld", e[1] + "'", _sh(e[2]))
return (tag, _sh(e[1]), _sh(e[2]))
def _leak_terms(e: Expr) -> list[Expr]:
"""The subexpressions of e whose values the evaluation of e leaks."""
tag = e[0]
if tag in ("c", "v"):
return []
if tag == "ld":
return _leak_terms(e[2]) + [e[2]]
terms = _leak_terms(e[1]) + _leak_terms(e[2])
if tag == "div":
terms += [e[1], e[2]]
return terms
def _guard(terms: list[Expr]) -> Expr:
"""The conjunction of l == l' over the terms l."""
g: Expr = ("c", 1)
for t in terms: # @line L13
g = ("&", g, ("==", t, _sh(t)))
return g
def product(prog: Block) -> Block:
"""The output-insensitive product of prog with its shadow copy.
Each statement is preceded by an assert that its leakage is the same in
both copies. The product keeps the control structure of prog: it has one
branch for each branch of prog and one loop for each loop of prog.
Cost: O(n^2) time and size for a program of size n, and O(n) when the
nesting depth of the expressions is bounded.
"""
out: Block = []
for s in prog: # @line L12
tag = s[0]
if tag == "set": # @line L7
g = _guard(_leak_terms(s[2]))
out += [("assert", g), s, ("set", s[1] + "'", _sh(s[2]))]
elif tag == "st": # @line L8
g = _guard(_leak_terms(s[2]) + _leak_terms(s[3]) + [s[2]])
out += [("assert", g), s, ("st", s[1] + "'", _sh(s[2]), _sh(s[3]))]
elif tag == "if": # @line L9
c = s[1]
same = ("==", ("==", c, ("c", 0)), ("==", _sh(c), ("c", 0)))
g = ("&", _guard(_leak_terms(c)), same) # @line L10
out += [("assert", g), ("if", c, product(s[2]), product(s[3]))]
elif tag == "rep": # @line L11
g = _guard(_leak_terms(s[1]) + [s[1]])
out += [("assert", g), ("rep", s[1], product(s[2]))]
else:
raise ValueError(f"unknown statement {tag!r}")
return out
def ct_verif(prog: Block, public: Sequence[str], secret: Sequence[str], tables: Mapping[str, Sequence[int]], w: int = 4) -> tuple[bool, tuple[dict[str, int], dict[str, int]] | None]:
"""Decide whether prog is constant time, with a witness pair if it is not.
prog is constant time when any two runs whose public inputs are equal give
the same leakage trace. The tables are public and equal in both runs.
The check runs the product once for each start pair over range(w).
Precondition: w >= 2, the names in public and secret are distinct, each
table has w cells with values in range(w), and no name ends with "'".
Cost: O(n^2) to build the product, then O(t) for each of the
m = w^(p + 2s) start pairs, for p public and s secret inputs, where t is
the number of steps of one run of the product.
"""
if w < 2:
raise ValueError("w must be at least 2")
for t in tables.values():
if len(t) != w:
raise ValueError("each table must have w cells")
q = product(prog) # @line L1
space = list(cartesian(range(w), repeat=len(secret)))
for pv in cartesian(range(w), repeat=len(public)): # @line L2
for sv in space:
for sv2 in space:
a = dict(zip(public, pv)) | dict(zip(secret, sv))
b = dict(zip(public, pv)) | dict(zip(secret, sv2))
env = a | {x + "'": v for x, v in b.items()}
arrs = {n: list(t) for n, t in tables.items()}
arrs |= {n + "'": list(t) for n, t in tables.items()}
try:
_exec(q, env, arrs, w, None) # @line L3
except AssertFailed: # @line L4
return False, (a, b) # @line L5
return True, None # @line L6
def cache_cost(trace: Sequence[Event], base: Mapping[str, int], sets: int = 2, ways: int = 1, line: int = 2, hit: int = 1, miss: int = 10) -> int:
"""The cost of the array accesses of a trace in an abstract LRU cache.
The cache starts empty. It has the given number of sets and ways, and
lines of line cells. Cell i of array a has the address base[a] + i, which
goes to the set (address div line) mod sets. A hit costs hit units and a
miss costs miss units. Other events cost nothing. The cost is a function
of the sequence of addresses alone. Precondition: sets, ways and line are
at least 1. Cost: O(k * ways) for k events.
"""
content: list[list[int]] = [[] for _ in range(sets)]
total = 0
for ev in trace:
if ev[0] != "addr":
continue
tag = (base[ev[1]] + ev[2]) // line
lines = content[tag % sets]
if tag in lines:
total += hit
lines.remove(tag)
else:
total += miss
if len(lines) == ways:
lines.pop(0)
lines.append(tag)
return total
test_constant_time_verification.py 245 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/constant-time-verification/. The authors are listed in prov/B355TH.jsonl.
import random
from itertools import product as cartesian
from constant_time_verification import cache_cost, ct_verif, product, run
W = 4
T = {"T": [3, 1, 0, 2]}
def v(x):
return ("v", x)
def c(n):
return ("c", n)
# An independent interpreter for the oracle. It returns the final variables
# and the trace of leakage events of one run.
def oracle_run(prog, inputs, tables, w=W):
env = dict(inputs)
mem = {a: list(t) for a, t in tables.items()}
events = []
def ev(e):
k = e[0]
if k == "c":
return e[1] % w
if k == "v":
return env.get(e[1], 0)
if k == "ld":
i = ev(e[2])
events.append(("addr", e[1], i))
return mem[e[1]][i]
x, y = ev(e[1]), ev(e[2])
if k == "div":
events.append(("div", x, y))
return 0 if y == 0 else x // y
table = {
"+": lambda: (x + y) % w,
"-": lambda: (x - y) % w,
"*": lambda: (x * y) % w,
"&": lambda: (x & y) % w,
"|": lambda: (x | y) % w,
"^": lambda: (x ^ y) % w,
"<": lambda: int(x < y),
"==": lambda: int(x == y),
}
return table[k]()
def ex(block):
for s in block:
if s[0] == "set":
env[s[1]] = ev(s[2])
elif s[0] == "st":
i = ev(s[2])
val = ev(s[3])
events.append(("addr", s[1], i))
mem[s[1]][i] = val
elif s[0] == "if":
b = ev(s[1]) != 0
events.append(("br", b))
ex(s[2] if b else s[3])
else:
n = ev(s[1])
events.append(("loop", n))
for _ in range(n):
ex(s[2])
ex(prog)
return env, events
def oracle_ct(prog, public, secret, tables, w=W):
"""Run every pair of start states with equal public inputs twice."""
space = list(cartesian(range(w), repeat=len(secret)))
for pv in cartesian(range(w), repeat=len(public)):
traces = set()
for sv in space:
inputs = dict(zip(public, pv)) | dict(zip(secret, sv))
traces.add(tuple(oracle_run(prog, inputs, tables, w)[1]))
if len(traces) > 1:
return False
return True
def check(prog, expected, public=("p",), secret=("s",)):
ok, pair = ct_verif(prog, public, secret, T, W)
assert ok == expected
assert oracle_ct(prog, public, secret, T) == expected
if not ok:
a, b = pair
assert all(a[x] == b[x] for x in public)
assert oracle_run(prog, a, T)[1] != oracle_run(prog, b, T)[1]
else:
assert pair is None
def masked_lookup():
# y = T[0] & m0 | T[1] & m1 | ..., with mj = 0 - (j == s), all ones or 0.
prog = [("set", "y", c(0))]
for j in range(W):
mask = ("-", c(0), ("==", c(j), v("s")))
prog.append(("set", "y", ("|", v("y"), ("&", ("ld", "T", c(j)), mask))))
return prog
def test_secret_index_lookup_is_not_constant_time():
check([("set", "y", ("ld", "T", v("s")))], False)
def test_public_index_lookup_is_constant_time():
check([("set", "y", ("ld", "T", v("p")))], True)
def test_masked_lookup_is_constant_time_and_correct():
prog = masked_lookup()
assert len(prog) <= 10
check(prog, True)
for s in range(W):
env, _ = run(prog, {"p": 0, "s": s}, T, W)
assert env["y"] == T["T"][s]
def test_secret_branch_is_not_constant_time():
check([("if", v("s"), [("set", "y", c(1))], [("set", "y", c(2))])], False)
def test_branch_on_s_xor_s_is_constant_time():
# A security type system rejects this program; the product accepts it.
check([("if", ("^", v("s"), v("s")), [("set", "y", ("ld", "T", v("s")))], [("set", "y", c(2))])], True)
def test_division_leaks_its_operands():
check([("set", "y", ("div", v("p"), v("s")))], False)
check([("set", "y", ("div", v("p"), c(1)))], True)
def test_loop_count():
check([("rep", v("s"), [("set", "y", ("+", v("y"), c(1)))])], False)
check([("rep", v("p"), [("set", "y", ("+", v("y"), v("s")))])], True)
def test_flow_through_a_variable():
check([("set", "x", v("s")), ("set", "y", ("ld", "T", v("x")))], False)
check([("set", "x", ("^", v("s"), v("s"))), ("set", "y", ("ld", "T", v("x")))], True)
def test_store_to_secret_index():
check([("st", "T", v("s"), c(0))], False)
check([("st", "T", v("p"), v("s")), ("set", "y", ("ld", "T", v("p")))], True)
# The stored secret later becomes an index.
check([("st", "T", c(0), v("s")), ("set", "y", ("ld", "T", ("ld", "T", c(0))))], False)
def test_product_keeps_the_control_structure():
prog = [
("if", v("p"), [("rep", v("p"), [("set", "y", c(1))])], []),
("set", "x", ("ld", "T", v("p"))),
]
q = product(prog)
def shape(block):
return [(s[0], [shape(b) for b in s[2:] if isinstance(b, list)]) for s in block if s[0] in ("if", "rep")]
assert shape(q) == shape(prog)
assert sum(1 for s in q if s[0] == "assert") == len(prog)
def test_two_secrets():
prog = [("set", "y", ("ld", "T", ("&", v("s"), v("k"))))]
for s in (prog, [("set", "y", ("&", ("ld", "T", v("p")), ("^", v("s"), v("k"))))]):
ok, _ = ct_verif(s, ("p",), ("s", "k"), T, W)
assert ok == oracle_ct(s, ("p",), ("s", "k"), T)
assert not ct_verif(prog, ("p",), ("s", "k"), T, W)[0]
def test_cache_cost_example():
prog = [("set", "x", ("ld", "T", c(0))), ("set", "y", ("ld", "T", v("s")))]
base = {"T": 0}
costs = {cache_cost(run(prog, {"p": 0, "s": s}, T, W)[1], base, sets=4, ways=1, line=1) for s in range(W)}
assert costs == {11, 20}
costs = {cache_cost(run(masked_lookup(), {"p": 0, "s": s}, T, W)[1], base, sets=4, ways=1, line=1) for s in range(W)}
assert len(costs) == 1
def test_lru_order():
trace = [("addr", "T", 0), ("addr", "T", 2), ("addr", "T", 0), ("addr", "T", 1)]
# One set, two ways, lines of one cell: miss, miss, hit, miss.
assert cache_cost(trace, {"T": 0}, sets=1, ways=2, line=1) == 31
trace = [("addr", "T", 0), ("addr", "T", 2), ("addr", "T", 1), ("addr", "T", 0)]
# Cell 0 was evicted by cell 1 as the least recently used line.
assert cache_cost(trace, {"T": 0}, sets=1, ways=2, line=1) == 40
def random_expr(rng, depth):
r = rng.random()
if depth == 0 or r < 0.3:
return v(rng.choice("psxy")) if rng.random() < 0.7 else c(rng.randrange(W))
if r < 0.5:
return ("ld", "T", random_expr(rng, depth - 1))
if r < 0.58:
return ("div", random_expr(rng, depth - 1), random_expr(rng, depth - 1))
op = rng.choice(["+", "-", "*", "&", "|", "^", "<", "=="])
return (op, random_expr(rng, depth - 1), random_expr(rng, depth - 1))
def random_block(rng, size, depth):
block = []
for _ in range(size):
r = rng.random()
if depth > 0 and r < 0.2:
block.append(("if", random_expr(rng, 1), random_block(rng, 1, depth - 1), random_block(rng, 1, depth - 1)))
elif depth > 0 and r < 0.3:
block.append(("rep", random_expr(rng, 1), random_block(rng, 1, depth - 1)))
elif r < 0.4:
block.append(("st", "T", random_expr(rng, 1), random_expr(rng, 1)))
else:
block.append(("set", rng.choice("xy"), random_expr(rng, 2)))
return block
def test_random_programs_against_the_two_run_oracle():
rng = random.Random(20160810)
seen = {True: 0, False: 0}
cache_checked = 0
for _ in range(600):
prog = random_block(rng, rng.randrange(1, 5), 1)
ok, pair = ct_verif(prog, ("p",), ("s",), T, W)
assert ok == oracle_ct(prog, ("p",), ("s",), T), prog
seen[ok] += 1
if not ok:
a, b = pair
assert a["p"] == b["p"]
assert oracle_run(prog, a, T)[1] != oracle_run(prog, b, T)[1]
elif cache_checked < 100:
# A constant-time program has one cache cost for each public input.
cache_checked += 1
for p in range(W):
costs = {cache_cost(run(prog, {"p": p, "s": s}, T, W)[1], {"T": 0}, sets=2, ways=1, line=1) for s in range(W)}
assert len(costs) == 1
assert seen[True] >= 100 and seen[False] >= 100
History
Barthe, D'Argenio and Rezk (2004) reduced noninterference to a property of one program by self-composition. Terauchi and Aiken (2005) named the class of 2-safety properties and showed that a smarter composition makes them easier to check. Barthe, Crespo and Kunz (2011) defined product programs that run the two copies in lockstep where their control flow agrees. Almeida, Barbosa, Barthe, Dupressoir and Emmi (2016) used this for the constant-time policy. Their product needs no lockstep search, because the policy forces the two copies to take the same branches. They proved the reduction in Coq and verified code from NaCl, OpenSSL, FourQlib and curve25519-donna with ct-verif. Reparaz, Balasch and Verbauwhede (2017) gave dudect, a statistical test of the same policy on real timings.
References
- José Bacelar Almeida, Manuel Barbosa, Gilles Barthe, François Dupressoir and Michael Emmi, Verifying constant-time implementations, 25th USENIX Security Symposium, 2016, pages 53-70, Section 3 (the leakage models and Definition 1), Section 4 (the output-insensitive product of Figures 7 and 8 with Theorem 1, and the output-sensitive product with Theorem 2) and Section 5 (the ct-verif tool on LLVM through SMACK and Boogie)
- Gilles Barthe, Pedro R. D'Argenio and Tamara Rezk, Secure information flow by self-composition, 17th IEEE Computer Security Foundations Workshop, 2004, the reduction of noninterference to a property of one program that runs two copies of the original
- Tachio Terauchi and Alex Aiken, Secure information flow as a safety problem, SAS 2005, LNCS 3672, the notion of a 2-safety property and its check as a safety property of a composed program
- Gilles Barthe, Juan Manuel Crespo and César Kunz, Relational verification using product programs, FM 2011, LNCS 6664, the definition of product programs, which run two copies in lockstep where their control flow agrees
- Oscar Reparaz, Josep Balasch and Ingrid Verbauwhede, Dude, is my code constant time?, DATE 2017, pages 1697-1702, the dudect method, a Welch t-test on measured run times for two classes of inputs (a test, not a proof)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag B355TH Edit this page History Report an error Markdown