Week 12 · Hardware security · Lesson 24 of 24

FPGA hardware security: TRNGs, PUFs and bitstreams

Threats to FPGA designs, ring-oscillator TRNGs with NIST SP 800-90B health tests in RTL, PUFs, power analysis and bitstream encryption and authentication.

advanced1 hUpdated Fact-checked Free

What you will learn

  • Write a threat model for an FPGA product: assets, attackers and the main attack classes
  • Explain how a ring-oscillator TRNG works and why simulation cannot show its entropy
  • Implement the SP 800-90B Repetition Count and Adaptive Proportion tests in RTL and verify them against a Python model
  • Describe ring-oscillator and SRAM PUFs, their reliability problem and the role of helper data
  • Choose bitstream protection features (readback disable, encryption, authentication) from vendor documentation

Before you start

  • Clock domain crossing (lesson 12)
  • Verification with cocotb (lesson 10)
  • DDS, LFSRs and CRCs (lesson 16)

After this lesson you can write a threat model for an FPGA product and pick the device features that answer it. You will also have two pieces of security hardware: a ring-oscillator noise source skeleton, and the NIST SP 800-90B health tests that watch it, verified in cocotb against a Python model of the standard.

Attacks are described only as far as needed to explain the countermeasures.

Threat model

List the assets first: usually the design itself (the bitstream is the product’s IP), keys held in the device, and the data it processes. Then list the attackers and their access, from network access only, through an owner who can open the product, to a lab with probes and oscilloscopes.

ThreatWhat happensMain countermeasures
CloningThe bitstream is copied from the configuration flash and loaded into another device of the same typeBitstream encryption with a key held in the device; device authentication
Reverse engineeringA captured bitstream or a readback image is analysed to recover the designEncryption; readback disable
TamperingA modified bitstream is loaded, or the board is changedBitstream authentication; secure boot; tamper sensors
Side channelsPower, electromagnetic emission or timing reveals a key while it is usedDesigns with data-independent timing and power; vendor blocks with power-analysis countermeasures
Fault injectionThe device is disturbed so that it computes wrongly, and the faulty output is exploitedChecks on results; tamper and environment sensors
Supply chainCounterfeit, recycled or modified parts reach productionTrusted suppliers; device authenticity checks offered by the vendor

Kocher et al. note that a correct implementation of a strong protocol is not necessarily secure: defective computations and leaked information can break it. The hardware layer needs its own threat model.

True random numbers

Keys, nonces and initialisation vectors must be unpredictable. An LFSR (lesson 16) is not: its whole future follows from its state. A true random number generator (TRNG) uses a physical noise process instead.

The entropy source model

NIST SP 800-90B splits an entropy source into three parts:

  • the noise source, the non-deterministic process that all security rests on;
  • optional conditioning, a deterministic function that reduces bias or raises the entropy per output bit;
  • health tests, which check that the noise source still works.

If the noise source fails, no other component can compensate. Health tests run on the raw noise samples, before conditioning. The vetted conditioning functions include HMAC, CMAC and CBC-MAC with AES (keyed), and approved hash functions, Hash_df and Block_Cipher_df (unkeyed).

SP 800-90B measures randomness as min-entropy: H=−log⁡2max⁡ipiH = -\log_2 \max_i p_i, where pip_i is the probability of the most likely sample value. A fair bit has H=1H = 1. A bit that is 1 with probability 0.75 has H=−log⁡20.75≈0.415H = -\log_2 0.75 \approx 0.415.

Block diagram. Three rings made of a NAND gate and inverters each feed a pair of flip-flops on the system clock. The three sampled bits go into an XOR gate and then into a block that takes one bit every DIV clocks, all inside a dashed box labelled noise source, ro_trng.sv, hardware only. The raw bits go to a conditioning block (vetted hash or MAC) and then to a DRBG or key generator. The raw bits also go to a health-tests block with RCT and APT, health_tests.sv, whose fail output blocks the output and tells the consumer.
Ring-oscillator entropy source with continuous health tests on the raw bits and conditioning before use.

Ring oscillators and jitter

A ring of an odd number of inverters has no stable state, so it oscillates. Its edges do not arrive at exactly the same time each period. Wold and Tan describe this jitter as a timing deviation caused by electronic or thermal noise, typically Gaussian. Sample a free-running ring with an unrelated clock, and the jitter accumulated since the last sample makes the sampled bit hard to predict.

The design in ro_trng.sv follows the structure that Wold and Tan proposed, building on Sunar et al.: several rings, each sampled by its own flip-flops, with the sampled bits XORed together. In the earlier design, the rings were XORed first and the result sampled by a single flip-flop. Wold and Tan measured a bias in that design and attributed it to the many transitions that the XOR tree and the flip-flop see per clock period when there are many fast rings. A second flip-flop per ring gives a metastable first stage time to settle (lesson 12).

Wold and Tan also measured that rings of equal length run at different frequencies, because place and route puts their inverters in different places. Their MATLAB model of the ring TRNG, run without any jitter at all, produced sequences that passed the NIST SP 800-22 statistical tests once it had 50 or more rings. A deterministic sequence can pass statistical tests. Passing a test suite does not prove entropy.

This is also why ro_trng.sv is never simulated for randomness. A logic simulator uses fixed gate delays or none, so the rings either stay at X or toggle in a pattern that repeats exactly on every run. Only measurements on the device, assessed with the SP 800-90B estimation procedures, can tell you how much entropy the raw bits carry.

Building the rings in RTL

Each ring is a NAND gate (for the enable) followed by inverters:

/* verilator lint_off UNOPTFLAT */
(* keep = "true", dont_touch = "true" *) logic [STAGES-1:0] node;
/* verilator lint_on UNOPTFLAT */

assign node[0] = ~(enable & node[STAGES-1]);
for (genvar s = 1; s < STAGES; s++) begin : g_inv
    assign node[s] = ~node[s-1];
end

Three tool issues follow from the deliberate loop:

  • Lint. Verilator reports the loop as UNOPTFLAT (circular combinational logic). The waiver covers only the ring declaration, and without it the file fails verilator --lint-only -Wall. No other file in the course needs a waiver for a combinational loop.
  • Optimisation. Synthesis would collapse a chain of inverters into one LUT. In Vivado, the KEEP and DONT_TOUCH attributes preserve the nets. AMD’s property guide (UG912) recommends setting DONT_TOUCH in the RTL, because signals can be optimised away before the constraints file is read. Other tools have their own attributes; look them up before you build.
  • Timing. Vivado reports a combinational loop (methodology check TIMING-23) and disables a timing arc to break it. Check that each reported loop is one you intended.

The file is labelled as a hardware-only skeleton: lint-clean, never run on a board, not a certified entropy source.

Download ro_trng.sv

SP 800-90B continuous health tests

SP 800-90B approves two continuous tests. Both need only a comparator and counters.

Repetition Count Test

The Repetition Count Test (RCT) catches a source stuck on one value. Following section 4.4.1:

  1. A = first sample, B = 1.
  2. For each next sample X: if X = A, then B = B + 1, and if B ≥ C signal a failure. Otherwise A = X and B = 1.

The cutoff comes from the assessed min-entropy HH and the accepted false-positive probability α\alpha:

C=1+⌈−log⁡2αH⌉C = 1 + \left\lceil \frac{-\log_2 \alpha}{H} \right\rceil

With α=2−20\alpha = 2^{-20} and H=2H = 2 the standard’s own example gives C=11C = 11. The standard recommends α\alpha between 2−202^{-20} and 2−402^{-40}. It also warns that the RCT only detects total failures: a source assessed at 8 bits per sample that degrades to 4 bits would take about a million samples to trip it.

Adaptive Proportion Test

The Adaptive Proportion Test (APT) catches a value that becomes too common. Following section 4.4.2:

  1. A = first sample of a window, B = 1.
  2. For the next W - 1 samples: if a sample equals A, then B = B + 1, and if B ≥ C signal a failure.
  3. Start a new window with the next sample.

W is 1024 for binary sources and 512 otherwise. C is the smallest count that a healthy source reaches with probability at most α\alpha. The standard gives the spreadsheet form C=1+CRITBINOM(W,2−H,1−α)C = 1 + \text{CRITBINOM}(W, 2^{-H}, 1 - \alpha). In Python that is 1 + scipy.stats.binom.ppf(1 - alpha, W, 2**-H), and test_sp80090b_health.py checks that it reproduces all ten entries of the standard’s Table 2, for example C=589C = 589 for a binary source with H=1H = 1.

health_tests.sv

The RTL follows the two procedures line by line. The RCT part:

end else if (sample_valid) begin
    if (!rct_started || sample != rct_a) begin
        rct_started <= 1'b1;
        rct_a       <= sample;
        rct_b       <= RCT_BW'(1);
    end else begin
        if (rct_b < RCT_BW'(RCT_C)) rct_b <= rct_b + 1'b1;
        if (rct_b + 1'b1 >= RCT_BW'(RCT_C)) rct_fail <= 1'b1;
    end
end

The parameters are the sample width SW, RCT_C, APT_W, APT_C and STARTUP. Failures are sticky until reset, because SP 800-90B requires the entropy source to notify the consuming application and, after a persistent failure, to stop producing output. The ready output rises after STARTUP samples without a failure: the standard’s start-up tests run the continuous tests over at least 1024 consecutive samples before the output is used. For a binary source with these cutoffs the module needs two 1-bit reference registers, a 5-bit RCT counter, an 11-bit APT counter, a 10-bit window index and an 11-bit start-up counter.

Download health_tests.sv

Testing against the standard

sp80090b_health.py implements both tests as written in the standard, plus seeded test sources. Running it on 65536 samples of each source, with H=1H = 1:

fair, p = 0.50     RCT fails      0 (first at     -)   APT fails      0 (first at     -)
biased, p = 0.60   RCT fails      0 (first at     -)   APT fails    910 (first at   990)
biased, p = 0.75   RCT fails    133 (first at   627)   APT fails   8352 (first at   757)
stuck at 1         RCT fails  65516 (first at    20)   APT fails  27904 (first at   588)
alternating 0101   RCT fails      0 (first at     -)   APT fails      0 (first at     -)
Two scatter plots over 64 blocks of 1024 bits. Left, Adaptive Proportion Test: the count for a fair source stays near 512, well below the cutoff line at 589; for a source with P(1) = 0.6 the count is near 410 when the window starts with 0 and near 615 when it starts with 1, often above the cutoff; for P(1) = 0.75 it is near 770 when the window starts with 1, always above, and near 260 when it starts with 0. Right, Repetition Count Test: the longest run per block is 7 to 17 for the fair source, up to 17 for P(1) = 0.6, and often 21 to 37 for P(1) = 0.75, crossing the cutoff line at 21.
Health-test statistics for three seeded binary sources assessed at H = 1. The APT catches a 0.6 bias only in windows whose first sample is the common value; the RCT catches only the strongest bias.

The APT detects moderate bias that the RCT misses, but only in windows that start with the common value. The alternating pattern passes both tests, although it has no entropy at all. SP 800-90B anticipates this: it asks developers to document known failure modes, naming periodic output like 101…01 as an example, and to add their own tests for them.

cocotb_health.py feeds each source into health_tests.sv and checks that rct_fail and apt_fail first rise on exactly the sample where the Python model first fails. Extra cases cover a source that turns biased after two windows (it checks the window boundaries), random idle cycles and reset. The wrapper runs it twice: a binary build (H=1H = 1, W = 1024, C = 21 and 589) and a 4-bit build (H=2H = 2, W = 512, C = 11 and 177).

cd public/code/fpga-design/hardware-security
/Volumes/M2-Dev/conda/envs/toptech/bin/python -m pytest -q
# 20 passed
Download sp80090b_health.py Download test_sp80090b_health.py Download cocotb_health.py Download test_cocotb_health.py

Physical unclonable functions

A physical unclonable function (PUF) should give the same answer every time on one chip and a different answer on every other chip. It turns manufacturing variation into an identity or a key that is never stored in memory.

Ring-oscillator PUF

Suh and Devadas build a PUF from many identically laid-out ring oscillators. Manufacturing variation gives each ring a slightly different frequency. Two counters compare a pair of rings, and the faster one decides the bit. With N rings there are N(N - 1)/2 pairs, but the bits are correlated; the number of independent bits is at most log⁡2(N!)\log_2(N!), for example 133 bits from 35 rings.

Temperature and voltage change the frequencies, and two rings with close frequencies can swap order. Their fixes for this reliability problem:

  • Masking: for each group of k pairs, use only the pair with the largest frequency difference (they used 1-out-of-8) and store which pair was chosen.
  • Error correction: at enrolment, compute the syndrome of an error-correcting code (their example is BCH(127, 64, 21), which corrects 10 errors in 127 bits). Later, the syndrome corrects the bit flips in the new response. The syndrome and the mask are public helper data; a b-bit syndrome reveals at most b bits of the response.
  • Key derivation: hash the corrected response to get a key.

On 15 Xilinx Virtex-4 FPGAs with 1024 rings each, two chips differed in 46.15 % of 128 output bits on average (ideal: 50 %). Moving one chip from 20 °C to 120 °C and from 1.2 V to 1.08 V core supply changed only 0.48 % of its bits.

SRAM PUF

An SRAM PUF uses the start-up contents of an SRAM block, read before anything writes to it, as the chip-specific pattern. Microchip’s PolarFire security documentation describes the property that matters: keys derived from the SRAM-PUF are not stored on the chip but extracted from it, and while the SRAM is unpowered no key is present.

Side channels

Kocher, Jaffe and Jun showed in 1999 that a device’s power consumption reveals the data it processes. Simple power analysis reads a single trace: a conditional branch on a key bit, or a comparison that exits at the first mismatch, shows up as a visible difference. Differential power analysis (DPA) needs no visible difference. It splits many traces into two groups according to a bit that depends on a guessed part of the key, and averages each group. For a wrong guess the difference of the averages tends to zero as more traces are added; for the right guess a peak remains.

Their countermeasures fall into three groups:

  • Reduce the signal: constant execution paths, balanced Hamming weights and transitions, shielding. This cannot reach zero, so it only raises the number of traces needed.
  • Add noise: random noise and randomised timing or order. Randomised timing needs care, because many such techniques can be bypassed or compensated for.
  • Design for leakage: assume the hardware leaks, and limit what an attacker can gather, for example with key updates that cannot be correlated across operations, or key-use counters.

In RTL the first rule is cheap: make timing independent of secrets, with a fixed number of cycles per operation and no early exit on secret data. For DPA resistance in cryptographic cores, use vendor blocks designed for it. Microchip’s PolarFire SoC devices with the suffix S include a DPA-resistant crypto coprocessor, and AMD lists DPA countermeasures for Spartan UltraScale+.

Protecting the bitstream

What 7-series devices provide

AMD’s 7-series configuration guide (UG470) documents three basic protections:

  • Readback disable: the bitstream security setting Level1 disables readback; Level2 disables readback and reconfiguration.
  • Encryption: AES-256 in CBC mode. The key is stored in battery-backed RAM or in eFUSEs and can only be programmed through JTAG. After an encrypted configuration, the configuration memory cannot be read through JTAG or SelectMAP, whatever the security setting. The decryptor serves only the bitstream; user logic cannot use it. The Spartan-7 7S6 and 7S15 do not support AES encryption.
  • Authentication: an HMAC with SHA-256 and a key separate from the AES key. The MAC is embedded in the encrypted bitstream and checked after decryption; any change, including a single bit flip, is detected. On a mismatch the device loads a fallback image or blocks the configuration interface.

Newer families

Newer families add more. Features vary within a family, so check the documentation for your exact device:

  • AMD’s Spartan UltraScale+ product page lists NIST-approved post-quantum cryptography, a PUF for device identification, a permanent tamper penalty, DPA countermeasures and AES-GCM decryption.
  • Microchip’s PolarFire Family FPGA Security User Guide documents for PolarFire and PolarFire SoC: SRAM-PUF master keys, bitstream encryption and authentication, DPA countermeasures, an anti-tamper mesh and sensors, and secure boot on the SoC devices. For the supply chain it describes a signed device certificate and factory-set device integrity bits that let you check that a device is genuine and unused.

Secure boot applies the same idea to software: each boot stage checks the next one before running it.

A minimal product checklist: encrypt and authenticate the bitstream, disable readback, protect key programming in production, run the TRNG health tests continuously, and write down which threats you chose not to cover.

Exercise

Cutoffs and counter widths

A binary noise source is assessed at H=0.5H = 0.5 bits per sample. With α=2−20\alpha = 2^{-20}, compute the RCT and APT cutoffs and the parameters for health_tests.sv. How wide are the RCT counter, the APT counter and the window index?

Show solution

RCT: C=1+⌈20/0.5⌉=41C = 1 + \lceil 20 / 0.5 \rceil = 41.

APT, binary, so W=1024W = 1024: sp80090b_health.apt_cutoff(0.5, 1024) gives C=793C = 793. It is not in Table 2, but the same function reproduces every Table 2 entry.

Instantiate health_tests #(.SW(1), .RCT_C(41), .APT_W(1024), .APT_C(793)). The widths come from $clog2: the RCT counter needs ⌈log⁡242⌉=6\lceil \log_2 42 \rceil = 6 bits, the APT counter ⌈log⁡21025⌉=11\lceil \log_2 1025 \rceil = 11 bits and the window index log⁡21024=10\log_2 1024 = 10 bits.

Exercise

Find the timing leak

A colleague’s access-code checker compares a 16-byte code with a stored secret, one byte per clock. The state machine moves to FAIL at the first byte that differs and to OK after 16 matching bytes. What does an observer learn from the time until the result appears, and how do you fix it?

Show solution

The time to FAIL tells the observer how many leading bytes were correct. They can then guess one byte at a time: at most 256 tries per byte, 4096 in total, instead of 21282^{128}. Kocher et al. name exactly this kind of early-exit comparison as a leak.

Fix: always take 16 cycles. Accumulate the differences and decide once at the end:

always_ff @(posedge clk) begin
    if (start) begin
        idx  <= '0;
        diff <= 1'b0;
        busy <= 1'b1;
    end else if (busy) begin
        diff <= diff | (code[idx] != secret[idx]);
        idx  <= idx + 1'b1;
        if (idx == 4'd15) busy <= 1'b0;   // result = !diff, always after 16 cycles
    end
end

Also limit the number of attempts, so that an attacker cannot gather many trials. The same paper uses key-use counters for the same purpose: to stop an attacker gathering many samples.

Summary

  • Start with a threat model: assets, attackers, access. Cloning, reverse engineering, tampering, side channels, fault injection and the supply chain each need their own answer.
  • A ring-oscillator TRNG takes its randomness from jitter. Simulation cannot show entropy, and passing statistical tests does not prove it; deterministic models pass them too.
  • The SP 800-90B Repetition Count and Adaptive Proportion tests are cheap counters in RTL. Their cutoffs follow from H and alpha, and a Python model of the standard verifies the RTL sample for sample.
  • PUFs derive per-chip secrets from manufacturing variation. Masking, error-correction helper data and hashing make them reliable enough for keys.
  • Power analysis recovers keys from statistics over many traces. Keep secret-dependent timing out of RTL and use vendor DPA-resistant blocks for cryptography.
  • Turn on readback protection, bitstream encryption and authentication, using the features your vendor documents for your exact device.

Check your understanding

Pick an answer for each question, then check. Answers stay hidden until you submit.

1. A binary noise source is assessed at H = 0.5 bits per sample, with alpha = 2^-20. What is the Repetition Count Test cutoff?
2. Which failure do both approved SP 800-90B continuous tests miss?
3. Why does a cocotb simulation of ro_trng.sv say nothing about its entropy?
4. In the ring-oscillator PUF of Suh and Devadas, what is stored as public helper data?
5. According to UG470, what happens when a 7-series FPGA loads an encrypted bitstream whose HMAC does not match and fallback is disabled?

Further reading

Found a mistake or something unclear?Report a correction.