Algorithm Search⌘K

Algorithmadvanced

Template attack

Also called profiled side-channel attack.

Builds multivariate Gaussian templates of the leakage of each intermediate value on a copy of the device, then ranks the key guesses of the target by maximum likelihood.

Time
Θ(n T² + V T³ + g m T²) worst · average · best
Space
Θ(V T² + g) extra
Where
T = the number of samples in each trace; V = the number of template classes; g = the number of key guesses; m = the number of attack traces; n = the number of profiling traces
Origin
Suresh Chari, Josyula R. Rao, Pankaj Rohatgi, 2002

A template attack is a side-channel attack in two phases. In the profiling phase the attacker uses a copy of the device with a known key and learns, for each value of a key-dependent intermediate, the mean trace and the covariance matrix of the noise: a multivariate Gaussian "template". In the attack phase it scores each key guess by the likelihood of the target's traces under the templates that the guess selects, and keeps the guess with the largest likelihood. With exact templates this maximum likelihood rule has the highest success probability of all rules on the same traces, which makes the template attack the reference for the strongest attacker in a stated model. Chari, Rao and Rohatgi (2002) introduced it.

In plain words

First, the attacker gets a copy of the chip and sets the key itself. It records the power many times and sorts the recordings by the value the chip was handling, which it knows. For each value it writes down what a typical recording looks like and how the noise usually moves, for example that two moments in a recording tend to go up together. That is the template. Then it records the real chip a few times. For each key guess, it asks how well the new recordings fit the templates that this guess says should apply. A right guess explains the recordings well, and a wrong guess explains them badly. The guess with the best fit wins, often after very few recordings.

The problem

The attacker is a profiling adversary. It has a copy of the device on which it can choose the key and the inputs, and it sees the target device on mm known inputs. In the model of this page, for the value v=S(p⊕k)v = S(p \oplus k), where SS is the 4-bit S-box of PRESENT, a trace has T=2T = 2 samples:

ℓ=μv+N,μv=(HW(v), ∑b=03wbvb),N∼N(0,Σ),Σ=σ2(1ρρ1),\ell = \mu_v + N, \qquad \mu_v = \Big(\mathrm{HW}(v),\ \sum_{b=0}^{3} w_b v_b\Big), \qquad N \sim \mathcal{N}(0, \Sigma), \quad \Sigma = \sigma^2 \begin{pmatrix} 1 & \rho \\ \rho & 1 \end{pmatrix},

where vbv_b is bit bb of vv, the weights are w=(1,0.5,0.25,2)w = (1, 0.5, 0.25, 2), and the noise of the two samples has correlation ρ\rho. The 16 values give 16 different means. The profiling phase sees nn pairs (vi,ℓi)(v_i, \ell_i) with known viv_i. The attack phase sees mm pairs (pi,ℓi)(p_i, \ell_i) from the target, with the key kk unknown. The goal is to output kk. The cost model is the real RAM.

The algorithm

The algorithm estimates one mean for each of the V=16V = 16 classes and one pooled covariance for all of them, factors the covariance once by Cholesky decomposition, and sums log densities.

  1. TEMPLATE-ATTACK(profiling pairs (v_i, l_i), attack pairs (p_i, l_i), S-box S)
  2. 1for each class v do μ_v ← mean of the profiling traces l_i with v_i = v
  3. 2Σ ← pooled covariance of the residuals l_i - μ_{v_i} ▷ divide by n - V
  4. 3C ← the Cholesky factor of Σ, so that C Cᵀ = Σ
  5. 4best ← none, top ← -∞
  6. 5for each key guess g = 0 .. |S| - 1 do
  7. 6score(g) ← 0
  8. 7for each attack pair (p, l) do
  9. 8score(g) ← score(g) - ½ ((l - μ_{S(p ⊕ g)})ᵀ Σ⁻¹ (l - μ_{S(p ⊕ g)}) + ln det Σ)
  10. 9if score(g) > top then
  11. 10best ← g, top ← score(g)
  12. 11return best and the list of scores

Line L8 is the log of the Gaussian density without the constant −T2ln⁡2π-\tfrac{T}{2}\ln 2\pi, which is the same for every guess. The quadratic form is computed as ∥C−1d∥2\lVert C^{-1} d \rVert^2 by one forward substitution with the triangular factor, never by an explicit inverse. With a pooled covariance the term ln⁡det⁡Σ\ln\det\Sigma is also the same for every guess; it matters only for the variant with one covariance for each class. The sum of logs in line L8 is the log of the product of the densities of independent traces.

Example

Take σ=0.5\sigma = 0.5, ρ=0.8\rho = 0.8, the exact templates, and the key k=Bk = \texttt{B}. Three attack traces arrive:

input p trace l value S(p ⊕ B) template mean μ
0 (1.47, 1.96) 8 (1, 2)
5 (0.66, 0.84) 1 (1, 1)
9 (1.49, 0.32) 6 (2, 0.75)

The scores below omit the term ln⁡det⁡Σ\ln\det\Sigma, which is the same for every guess.

traces used best guess and score next guesses rank of B
1 6: -0.64 0: -0.66, B: -1.40 3
2 B: -1.70 0: -2.07, E: -6.95 1
3 B: -2.23 5: -13.02, 4: -13.53 1

After one trace the guesses 6 and 0 fit a little better than B, because their classes A\texttt{A} and C\texttt{C} have means (2,2.5)(2, 2.5) and (2,2.25)(2, 2.25), and the noise correlation of 0.8 makes a move along the diagonal cheap. After three traces the right key leads by 10.810.8 in log likelihood, a likelihood ratio of about 5×1045 \times 10^4.

Correctness

The loop of line L5 keeps the loop invariant that top is the largest score so far and best is the first guess with it. With exact templates, the score of gg is the log likelihood of the attack traces under gg, up to a constant. The central fact is a theorem: if the key is uniform and the traces are independent given the key, the rule that returns the guess of largest likelihood has the largest success probability of all decision rules on the same traces. It is the maximum a posteriori rule, by Bayes' theorem, and the maximum of the posterior is the best possible guess at each point. With estimated templates the estimates converge to the exact ones as nn grows, and so do the scores. The proof gives the computation of line L8, the optimality theorem and the convergence.

Proof: The template attack computes the log likelihood of each guess, and the maximum likelihood rule is optimalfull

Write φ(x;μ,Σ)=(2π)−T/2(det⁡Σ)−1/2exp⁡(−12(x−μ)⊤Σ−1(x−μ))\varphi(x; \mu, \Sigma) = (2\pi)^{-T/2} (\det\Sigma)^{-1/2} \exp\big(-\tfrac12 (x - \mu)^\top \Sigma^{-1} (x - \mu)\big) for the density of N(μ,Σ)\mathcal{N}(\mu, \Sigma) in dimension TT, with Σ\Sigma symmetric positive definite.

Lemma 1 (line L8). Let CC be lower triangular with positive diagonal and CC⊤=ΣCC^\top = \Sigma. Let yy solve Cy=dCy = d by forward substitution. Then d⊤Σ−1d=∥y∥2d^\top \Sigma^{-1} d = \lVert y \rVert^2 and ln⁡det⁡Σ=2∑iln⁡Cii\ln\det\Sigma = 2\sum_i \ln C_{ii}.

Proof. Σ−1=(C⊤)−1C−1\Sigma^{-1} = (C^\top)^{-1} C^{-1}, so d⊤Σ−1d=(C−1d)⊤(C−1d)=y⊤yd^\top \Sigma^{-1} d = (C^{-1}d)^\top (C^{-1}d) = y^\top y. Forward substitution finds yi=(di−∑q<iCiqyq)/Ciiy_i = (d_i - \sum_{q < i} C_{iq} y_q)/C_{ii} in order i=1,…,Ti = 1, \ldots, T, which is the unique solution because CC is triangular with a nonzero diagonal. The determinant of a triangular matrix is the product of its diagonal, so det⁡Σ=(det⁡C)2=∏iCii2\det\Sigma = (\det C)^2 = \prod_i C_{ii}^2. □\square

So after the loop of line L7, score(g)=∑iln⁡φ(ℓi;μS(pi⊕g),Σ)+mT2ln⁡2π\mathrm{score}(g) = \sum_i \ln \varphi(\ell_i; \mu_{S(p_i \oplus g)}, \Sigma) + \tfrac{mT}{2}\ln 2\pi. The added constant is the same for every guess.

Lemma 2 (the loop of line L5). Line L11 returns the first guess with the largest score.

Proof. Each score is finite, so the first guess passes line L9, and later guesses replace best only with a strictly larger score. By induction, top is the largest score so far and best is the first guess that reaches it. □\square

The model. The key KK is uniform on {0,…,15}\{0, \ldots, 15\}. Given K=kK = k and the inputs p1,…,pmp_1, \ldots, p_m, the traces are independent and ℓi\ell_i has density fk(ℓi∣pi)=φ(ℓi;μS(pi⊕k),Σ)f_k(\ell_i \mid p_i) = \varphi(\ell_i; \mu_{S(p_i \oplus k)}, \Sigma). The inputs are known and independent of KK. Write Lk(x)=∏ifk(ℓi∣pi)L_k(x) = \prod_i f_k(\ell_i \mid p_i) for the likelihood of the observation x=(pi,ℓi)i≤mx = (p_i, \ell_i)_{i \le m} under the key kk.

Theorem (optimality). Let dd be any decision rule that maps an observation xx to a guess d(x)d(x). Then Pr⁡[d(x)=K]≤Pr⁡[d∗(x)=K]\Pr[d(x) = K] \le \Pr[d^\ast(x) = K], where d∗(x)d^\ast(x) is a guess with the largest likelihood Lk(x)L_k(x). With exact templates (μv\mu_v and Σ\Sigma of the model), the template attack is such a rule d∗d^\ast.

Proof. Fix the inputs; the argument is the same for each choice of them, and so it holds after averaging over the inputs. The traces have the density q(x)=116∑kLk(x)q(x) = \tfrac{1}{16}\sum_k L_k(x), and by Bayes' theorem the posterior of the key is Pr⁡[K=k∣x]=Lk(x)/∑k′Lk′(x)\Pr[K = k \mid x] = L_k(x) / \sum_{k'} L_{k'}(x). So

Pr⁡[d(x)=K]=∫116Ld(x)(x) dx≤∫116max⁡kLk(x) dx=Pr⁡[d∗(x)=K].\Pr[d(x) = K] = \int \tfrac{1}{16} L_{d(x)}(x)\, dx \le \int \tfrac{1}{16} \max_k L_k(x)\, dx = \Pr[d^\ast(x) = K].

The inequality holds point by point, because Ld(x)(x)≤max⁡kLk(x)L_{d(x)}(x) \le \max_k L_k(x). With the uniform prior, the largest posterior and the largest likelihood are reached at the same key. By Lemma 1, with exact templates the score of guess gg is ln⁡Lg(x)\ln L_g(x) plus a constant that does not depend on gg, and the logarithm is increasing, so the guess of line L11 has the largest likelihood. ■\blacksquare

The theorem is about the stated model: it assumes that the templates are the true distribution of the target's traces. It gives no bound when the profiling device and the target differ.

Proposition (estimated templates converge). Fix the model and let the number nn of profiling traces grow, with each value drawn uniformly. Then with probability 1, the means of line L1 converge to μv\mu_v, the pooled covariance of line L2 converges to Σ\Sigma, and for fixed attack traces each score converges to its value under the exact templates.

Proof. Each class receives a number of traces that grows without bound, with probability 1. By the strong law of large numbers the class means converge to μv\mu_v. The pooled covariance is 1n−V∑i(ℓi−μ^vi)(ℓi−μ^vi)⊤\frac{1}{n - V}\sum_i (\ell_i - \hat\mu_{v_i})(\ell_i - \hat\mu_{v_i})^\top. Write ℓi−μ^vi=(ℓi−μvi)−(μ^vi−μvi)\ell_i - \hat\mu_{v_i} = (\ell_i - \mu_{v_i}) - (\hat\mu_{v_i} - \mu_{v_i}). The average of (ℓi−μvi)(ℓi−μvi)⊤(\ell_i - \mu_{v_i})(\ell_i - \mu_{v_i})^\top converges to Σ\Sigma by the law of large numbers, and the terms with μ^v−μv\hat\mu_v - \mu_v tend to 0 because that difference tends to 0 while the averages that multiply it stay bounded. The factor n/(n−V)n/(n - V) tends to 1. The Cholesky factor is a continuous function of a positive definite matrix, and the score of Lemma 1 is a continuous function of the means and the factor. So the scores converge. □\square

If, in addition, the exact scores have a unique maximum, the estimated rule picks the same guess as the exact rule for all large nn, and so its success probability tends to that of the optimal rule.

Complexity

Line L1 costs Θ(nT)\Theta(nT), and line L2 costs Θ(nT2)\Theta(nT^2) for the outer products of the residuals. Line L3 costs Θ(T3)\Theta(T^3) once; the variant with one covariance for each class costs Θ(VT3)\Theta(V T^3). In the attack phase, each of the gg guesses and mm traces needs one forward substitution in Θ(T2)\Theta(T^2). So the time is Θ(nT2+VT3+gmT2)\Theta(nT^2 + VT^3 + gmT^2) in every case. The extra space is Θ(VT)\Theta(VT) for the means, Θ(VT2)\Theta(VT^2) for the factors in the per-class variant, and Θ(g)\Theta(g) for the scores.

A measurement in the model, with σ=1\sigma = 1, ρ=0.8\rho = 0.8 and a random key in each run: the success rate for mm attack traces with the exact templates (300 runs), with pooled templates estimated from n=1600n = 1600 profiling traces (100 runs), and with the rule that ignores the noise correlation (300 runs):

attack traces m 1 2 3 5 8 12
exact templates 0.31 0.44 0.59 0.85 0.96 1.00
estimated, pooled 0.26 0.40 0.55 0.78 0.93 0.99
covariance ignored 0.30 0.32 0.54 0.69 0.87 0.94

Properties

  • Optimal with exact templates. No attack on the same traces has a higher success probability (a theorem, under a uniform key and independent traces). This is why evaluation labs use template attacks to bound what any attacker can do in a given leakage model.
  • Profiled. It needs a device with a known or chosen key, and the profiling and the target device must leak in the same way. The theorem says nothing about the mismatch between two real devices.
  • Uses the noise structure. The covariance lets the attack cancel noise that two samples share. In the measurement, the rule that ignores it needs about 50 percent more traces for a success rate of 0.9.
  • Few attack traces. Because it uses the full distribution, it often needs far fewer attack traces than CPA, down to one trace when the noise is small.
  • Full ranking. The scores are log likelihoods, so they can be turned into probabilities for each key part and combined by key rank estimation.

Variants and improvements

  • Pooled or per-class covariance. The original form estimates one covariance for each class, which makes the classifier a quadratic discriminant analysis. Pooling one covariance for all classes, as above, makes it a linear discriminant analysis and needs far fewer profiling traces.
  • Points of interest. Real traces have thousands of samples, and the covariance of all of them cannot be estimated. Chari, Rao and Rohatgi keep the few samples where the class means differ most; principal component analysis and linear discriminant analysis are later ways to reduce the dimension.
  • Templates on the Hamming weight. Building 5 classes for the weights instead of 16 for the values needs fewer profiling traces, at the cost of losing what the weight does not show.
  • Linear regression on the bits. Fit the mean of each sample as a linear function of the bits of the value. For a 4-bit value this needs 5 parameters per sample (one for each bit and a constant) rather than 16 class means.
  • Machine learning. A naive Bayes classifier, a support vector machine or a neural network can replace the Gaussian model. They need no Gaussian assumption, but they lose the optimality theorem.

When to use it

Use a template attack in an evaluation that must bound the strongest attacker, or when the attacker in the threat model can buy or build a copy of the device. Use CPA or MIA when there is no profiling device. To show only that a device leaks, without a key, a leakage test is cheaper.

Pitfalls

  • Ignoring the covariance. If line L2 sets Σ\Sigma to σ2I\sigma^2 I, line L8 measures a Euclidean distance and cannot cancel the noise that the samples share. In the measurement, the success rate at m=5m = 5 falls from 0.85 to 0.69. Estimate the full covariance in line L2.
  • One covariance for each class with few traces. With TT samples a class needs at least T+1T + 1 traces for its covariance to be invertible, and many more for it to be accurate; with too few, the Cholesky step of line L3 fails or gives a factor with tiny diagonal entries, and line L8 then trusts noise. Pool the covariance, as line L2 does, unless the profiling set is large.
  • Multiplying densities. If line L8 multiplies the densities of the traces instead of adding their logs, the product becomes smaller than the smallest floating point number once there are enough traces or samples, and all guesses tie at 0. Add logs.
  • An explicit inverse. Computing Σ−1\Sigma^{-1} and then the quadratic form loses accuracy when Σ\Sigma is close to singular, which happens with strongly correlated samples. Use the Cholesky factor and a triangular solve, as in line L8.

Implementations

The code of this page is an abstract model on synthetic data. Its profiling and attack traces come from the two-sample model of "The problem", drawn with a seeded random.Random by the functions profiling_set and attack_set; the code never reads a device, a file or a clock. The tests check the Cholesky factor and the quadratic form against a cofactor inverse, the scores against a direct formula on 500 random inputs, the pooled covariance against a direct computation, the example above, the loss from ignoring the covariance, and the success rate with estimated templates.

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.

template_attack.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/template-attack/. The authors are listed in prov/9Z5T63.jsonl.
"""Template attack (Gaussian templates) on a synthetic two-sample leakage model.

The traces come from a stated statistical model, never from a device. For
the value v = S(p xor k), with S the 4-bit S-box of PRESENT (Bogdanov et
al., CHES 2007), sample 0 is HW(v) and sample 1 is a weighted sum of the
bits of v, and the noise of the two samples is Gaussian with correlation
``rho``, drawn with a seeded ``random.Random``. This is a study model for
defenders and students.
"""

import math
import random

PRESENT_SBOX: tuple[int, ...] = (
    0xC, 0x5, 0x6, 0xB, 0x9, 0x0, 0xA, 0xD,
    0x3, 0xE, 0xF, 0x8, 0x4, 0x7, 0x1, 0x2,
)
BIT_WEIGHTS: tuple[float, ...] = (1.0, 0.5, 0.25, 2.0)

Vector = list[float]
Matrix = list[list[float]]


def hamming_weight(v: int) -> int:
    """Return the number of 1 bits of a non-negative integer."""
    return bin(v).count("1")


def leakage_mean(v: int) -> Vector:
    """The noiseless two-sample leakage of the value v in the model."""
    return [
        float(hamming_weight(v)),
        sum(w for b, w in enumerate(BIT_WEIGHTS) if (v >> b) & 1),
    ]


def noisy_leakage(rng: random.Random, v: int, sigma: float, rho: float) -> Vector:
    """Leakage of v plus Gaussian noise with variance sigma^2 and correlation rho."""
    z0 = rng.gauss(0.0, 1.0)
    z1 = rng.gauss(0.0, 1.0)
    mu = leakage_mean(v)
    return [mu[0] + sigma * z0, mu[1] + sigma * (rho * z0 + math.sqrt(1.0 - rho * rho) * z1)]


def profiling_set(rng: random.Random, n: int, sigma: float, rho: float) -> list[tuple[int, Vector]]:
    """n profiling pairs (value, trace) with a known, uniform value. Cost: O(n)."""
    out = []
    for _ in range(n):
        v = rng.randrange(16)
        out.append((v, noisy_leakage(rng, v, sigma, rho)))
    return out


def attack_set(
    rng: random.Random, key: int, m: int, sigma: float, rho: float
) -> list[tuple[int, Vector]]:
    """m attack pairs (input, trace) for the key. Cost: O(m)."""
    out = []
    for _ in range(m):
        p = rng.randrange(16)
        out.append((p, noisy_leakage(rng, PRESENT_SBOX[p ^ key], sigma, rho)))
    return out


def cholesky(a: Matrix) -> Matrix:
    """Lower triangular L with L L^T = a, for a symmetric positive definite a.

    Raises ValueError if a is not positive definite. Cost: O(T^3).
    """
    t = len(a)
    low = [[0.0] * t for _ in range(t)]
    for i in range(t):
        for j in range(i + 1):
            s = a[i][j] - sum(low[i][q] * low[j][q] for q in range(j))
            if i == j:
                if s <= 0.0:
                    raise ValueError("matrix is not positive definite")
                low[i][i] = math.sqrt(s)
            else:
                low[i][j] = s / low[j][j]
    return low


def quadratic_form(low: Matrix, x: Vector) -> float:
    """Return x^T (L L^T)^{-1} x by one forward substitution. Cost: O(T^2)."""
    y: Vector = []
    for i in range(len(x)):
        y.append((x[i] - sum(low[i][q] * y[q] for q in range(i))) / low[i][i])
    return sum(v * v for v in y)


def build_templates(
    profile: list[tuple[int, Vector]], classes: int = 16, pooled: bool = True
) -> tuple[list[Vector], list[Matrix], list[float]]:
    """Return (means, Cholesky factors, log determinants) for each class.

    With ``pooled`` the covariance is the pooled covariance of the residuals
    of all classes (one matrix for every class); otherwise each class has its
    own sample covariance. Precondition: each class has at least two traces
    (T + 1 without pooling) and the covariances are positive definite.
    Cost: Theta(n * T^2 + V * T^3) for n traces and V classes.
    """
    t = len(profile[0][1])
    groups: list[list[Vector]] = [[] for _ in range(classes)]
    for v, tr in profile:
        groups[v].append(tr)
    if any(not g for g in groups):
        raise ValueError("every class needs profiling traces")
    means = [[sum(tr[j] for tr in g) / len(g) for j in range(t)] for g in groups]  # @line L1

    def scatter(vs: list[int]) -> tuple[Matrix, int]:
        s = [[0.0] * t for _ in range(t)]
        count = 0
        for v in vs:
            for tr in groups[v]:
                d = [tr[j] - means[v][j] for j in range(t)]
                for a in range(t):
                    for b in range(t):
                        s[a][b] += d[a] * d[b]
            count += len(groups[v]) - 1
        return [[x / count for x in row] for row in s], count

    if pooled:
        cov, _ = scatter(list(range(classes)))  # @line L2
        low = cholesky(cov)  # @line L3
        lows = [low] * classes
    else:
        lows = [cholesky(scatter([v])[0]) for v in range(classes)]
    logdets = [2.0 * sum(math.log(low[i][i]) for i in range(t)) for low in lows]
    return means, lows, logdets


def template_attack(
    attack: list[tuple[int, Vector]],
    templates: tuple[list[Vector], list[Matrix], list[float]],
    sbox: tuple[int, ...] = PRESENT_SBOX,
) -> tuple[int, list[float]]:
    """Return (best guess, log-likelihood of each guess) by Chari et al.

    The score of g is the sum over the attack traces (p, l) of the Gaussian
    log density of l under the template of the class sbox[p ^ g], without
    the constant -T/2 log(2 pi). The first guess with the top score wins.

    Precondition: at least one attack trace; templates from
    build_templates. Cost: Theta(g * m * T^2) for g guesses and m traces,
    and Theta(g + T) extra space.
    """
    if not attack:
        raise ValueError("need at least one attack trace")
    means, lows, logdets = templates
    best, top = -1, -math.inf  # @line L4
    scores: list[float] = []
    for g in range(len(sbox)):  # @line L5
        score = 0.0  # @line L6
        for p, tr in attack:  # @line L7
            v = sbox[p ^ g]
            d = [tr[j] - means[v][j] for j in range(len(tr))]
            score -= 0.5 * (quadratic_form(lows[v], d) + logdets[v])  # @line L8
        scores.append(score)
        if score > top:  # @line L9
            best, top = g, score  # @line L10
    return best, scores  # @line L11
test_template_attack.py 176 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/template-attack/. The authors are listed in prov/9Z5T63.jsonl.

import math
import random
import statistics

import pytest
from template_attack import (
    PRESENT_SBOX,
    attack_set,
    build_templates,
    cholesky,
    leakage_mean,
    profiling_set,
    quadratic_form,
    template_attack,
)


def det(a):
    if len(a) == 1:
        return a[0][0]
    return sum(
        (-1) ** c * a[0][c] * det([row[:c] + row[c + 1:] for row in a[1:]])
        for c in range(len(a))
    )


def inverse(a):
    """Inverse by cofactors, independent of the Cholesky code."""
    t = len(a)
    if t == 1:
        return [[1.0 / a[0][0]]]
    d = det(a)
    return [
        [
            (-1) ** (i + j) * det([row[:i] + row[i + 1:] for k, row in enumerate(a) if k != j]) / d
            for j in range(t)
        ]
        for i in range(t)
    ]


def random_spd(rng, t):
    b = [[rng.uniform(-1, 1) for _ in range(t)] for _ in range(t)]
    return [[sum(b[i][q] * b[j][q] for q in range(t)) + (0.5 if i == j else 0.0) for j in range(t)] for i in range(t)]


def oracle_scores(attack, means, covs):
    invs = [inverse(c) for c in covs]
    logdets = [math.log(det(c)) for c in covs]
    out = []
    for g in range(16):
        s = 0.0
        for p, tr in attack:
            v = PRESENT_SBOX[p ^ g]
            inv = invs[v]
            d = [tr[j] - means[v][j] for j in range(len(tr))]
            q = sum(d[i] * inv[i][j] * d[j] for i in range(len(d)) for j in range(len(d)))
            s += -0.5 * (q + logdets[v])
        out.append(s)
    return out


def exact_templates(sigma, rho):
    cov = [[sigma * sigma, rho * sigma * sigma], [rho * sigma * sigma, sigma * sigma]]
    low = cholesky(cov)
    logdet = math.log(det(cov))
    return [leakage_mean(v) for v in range(16)], [low] * 16, [logdet] * 16


def test_cholesky_and_quadratic_form() -> None:
    rng = random.Random(1)
    for _ in range(200):
        t = rng.randrange(1, 4)
        a = random_spd(rng, t)
        low = cholesky(a)
        for i in range(t):
            for j in range(t):
                assert sum(low[i][q] * low[j][q] for q in range(t)) == pytest.approx(a[i][j], abs=1e-9)
        x = [rng.uniform(-2, 2) for _ in range(t)]
        inv = inverse(a)
        want = sum(x[i] * inv[i][j] * x[j] for i in range(t) for j in range(t))
        assert quadratic_form(low, x) == pytest.approx(want, rel=1e-9, abs=1e-9)
    with pytest.raises(ValueError):
        cholesky([[1.0, 2.0], [2.0, 1.0]])


def test_worked_example() -> None:
    means, lows, _ = exact_templates(0.5, 0.8)
    tpl = (means, lows, [0.0] * 16)
    attack = [(0, [1.47, 1.96]), (5, [0.66, 0.84]), (9, [1.49, 0.32])]
    best, scores = template_attack(attack[:1], tpl)
    assert best == 0x6 and 1 + sum(s > scores[0xB] for s in scores) == 3
    best, scores = template_attack(attack, tpl)
    assert best == 0xB
    assert scores[0xB] == pytest.approx(-2.23, abs=0.005)
    assert sorted(scores, reverse=True)[1] == pytest.approx(-13.02, abs=0.005)


def test_against_oracle_random() -> None:
    rng = random.Random(20240504)
    for _ in range(500):
        t = rng.randrange(1, 4)
        means = [[rng.uniform(-2, 2) for _ in range(t)] for _ in range(16)]
        covs = [random_spd(rng, t) for _ in range(16)]
        lows = [cholesky(c) for c in covs]
        logdets = [2.0 * sum(math.log(low[i][i]) for i in range(t)) for low in lows]
        attack = [(rng.randrange(16), [rng.uniform(-3, 3) for _ in range(t)]) for _ in range(rng.randrange(1, 5))]
        best, scores = template_attack(attack, (means, lows, logdets))
        want = oracle_scores(attack, means, covs)
        assert scores == pytest.approx(want, rel=1e-9, abs=1e-9)
        assert want[best] == pytest.approx(max(want), abs=1e-9)


def test_build_templates_against_statistics() -> None:
    rng = random.Random(2)
    prof = profiling_set(rng, 400, 1.0, 0.8)
    means, lows, logdets = build_templates(prof)
    for v in range(16):
        rows = [tr for u, tr in prof if u == v]
        assert means[v] == pytest.approx([statistics.mean(r[j] for r in rows) for j in range(2)])
    resid = [[tr[j] - means[u][j] for j in range(2)] for u, tr in prof]
    dof = len(prof) - 16
    pooled = [[sum(r[a] * r[b] for r in resid) / dof for b in range(2)] for a in range(2)]
    low = lows[0]
    for a in range(2):
        for b in range(2):
            assert sum(low[a][q] * low[b][q] for q in range(2)) == pytest.approx(pooled[a][b])
    assert logdets[0] == pytest.approx(math.log(det(pooled)))
    with pytest.raises(ValueError):
        build_templates([(0, [1.0, 2.0]), (0, [1.5, 2.5])])


def test_low_noise_recovers_every_key() -> None:
    tpl = exact_templates(0.05, 0.8)
    rng = random.Random(3)
    for key in range(16):
        attack = attack_set(rng, key, 4, 0.05, 0.8)
        assert template_attack(attack, tpl)[0] == key


def test_ignoring_the_covariance_costs_success() -> None:
    # The maximum likelihood rule beats the rule that assumes independent noise.
    rng = random.Random(4)
    exact = exact_templates(1.0, 0.8)
    ident = ([leakage_mean(v) for v in range(16)], [cholesky([[1.0, 0.0], [0.0, 1.0]])] * 16, [0.0] * 16)
    runs = 300
    he = hi = 0
    for _ in range(runs):
        key = rng.randrange(16)
        attack = attack_set(rng, key, 5, 1.0, 0.8)
        he += template_attack(attack, exact)[0] == key
        hi += template_attack(attack, ident)[0] == key
    assert he / runs > 0.75
    assert he - hi >= 0.05 * runs


def test_estimated_templates() -> None:
    rng = random.Random(5)
    hits_pooled = hits_class = 0
    runs = 20
    for _ in range(runs):
        prof = profiling_set(rng, 1600, 1.0, 0.8)
        key = rng.randrange(16)
        attack = attack_set(rng, key, 12, 1.0, 0.8)
        hits_pooled += template_attack(attack, build_templates(prof))[0] == key
        hits_class += template_attack(attack, build_templates(prof, pooled=False))[0] == key
    assert hits_pooled >= runs - 2
    assert hits_class >= runs - 3


def test_edges() -> None:
    with pytest.raises(ValueError):
        template_attack([], exact_templates(1.0, 0.0))

History

Chari, Rao and Rohatgi introduced template attacks at CHES 2002, and showed that a well profiled device can leak a key from very few traces. Their model of the noise as a multivariate Gaussian, with a mean for each value and a covariance learned on a copy of the device, is the model of this page. Standaert, Malkin and Yung (2009) gave the framework of success rate and guessing entropy in which profiled and non-profiled attacks are compared. Later work replaced the Gaussian classifier by general machine learning, with the template attack as the baseline.

References

  1. Suresh Chari, Josyula R. Rao and Pankaj Rohatgi, Template attacks, CHES 2002, LNCS 2523, pages 13 to 28, the profiling step (a mean and a noise covariance for each value), the choice of points of interest, and the maximum likelihood classification
  2. Stefan Mangard, Elisabeth Oswald and Thomas Popp, Power Analysis Attacks, Springer, 2007, ISBN 978-0-387-30857-9, Chapter 4 (the multivariate Gaussian model of power traces) and Chapter 5, pages 101 to 118 (template attacks on a single trace)
  3. François-Xavier Standaert, Tal G. Malkin and Moti Yung, A unified framework for the analysis of side-channel key recovery attacks, EUROCRYPT 2009, LNCS 5479, pages 443 to 461, the definitions of the success rate and the guessing entropy, and the profiled adversary
  4. Andrey Bogdanov and others, PRESENT, an ultra-lightweight block cipher, CHES 2007, LNCS 4727, the description of the substitution layer (the table of the 4-bit S-box used in the examples of this page)

Where this leads

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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example