Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

14.3 Spectre v1 (bounds check bypass)

Spectre v1 (CVE-2017-5753) abuses the conditional branch predictor. The attacker calls the victim many times with an in-bounds index, which trains the bounds check to predict “in range”. Then it passes an out-of-bounds index. The PE predicts the check, runs the protected loads in the transient window, and leaves a cache footprint that encodes data from outside the array. Nothing at the architectural level goes wrong: the branch resolves, the loads are squashed, and the handler returns an error.

/* SMC handler at EL3. x1 (idx) comes from Non-secure EL1. */
if (idx < table_len) {              /* B.HS predicted not taken          */
    uint8_t v = table[idx];         /* transient: reads beyond the table */
    ret = lut[v * 64];              /* transient: fill encodes v          */
}

The architecture does not order these loads behind the branch. A control dependency orders a later store behind the branch’s operands, but it does not order loads (7.4). Even if it did, the memory model only constrains architecturally executed accesses. A fix has to force the protected loads to use a value that is safe even when the branch is mispredicted. There are three tools for this: CSDB with a conditional select, SB, and masking that is safe by construction.

CSDB: Consumption of Speculative Data Barrier

CSDB is HINT #20. It is part of the base architecture from v8.0. Arm defined it retroactively in 2018 and placed it in the hint space so that older cores execute it as a NOP. That is correct for them, because Arm’s guidance is that a conditional select followed by CSDB is enough on every Arm implementation. The guarantee, paraphrasing DDI0487:

No instruction other than a branch, appearing in program order after the CSDB, can be speculatively executed using the results of any data value prediction, or of any PSTATE.{N,Z,C,V} prediction of an instruction other than a conditional branch, where that instruction appears in program order before the CSDB and has not been architecturally resolved.

Three points in that definition are easy to miss.

  1. It is about predicted data and flags, not predicted control flow. CSDB does not stop the PE from speculating down the wrong side of the B.HS. It only stops later instructions from consuming a value that was computed from a predicted flag. A bare CSDB after the branch, with no conditional select, does nothing useful.
  2. The conditional select is what makes it work. CSEL x1, x1, xzr, LO produces a result from the flags. If those flags were predicted instead of computed, the result is the “result of a PSTATE prediction”, and CSDB stops any later instruction from using it until the flags resolve. Once the flags resolve, the CSEL result is correct (zero for an out-of-bounds index) even on the mispredicted path.
  3. Branches are excluded on the consumer side. Later conditional branches can still be predicted. Only data consumption is constrained.

The canonical sequence:

// x0 = table, x1 = idx (untrusted), x2 = table_len
    cmp     x1, x2
    b.hs    1f                    // architectural bounds check
    csel    x1, x1, xzr, lo       // idx if in bounds, else 0: depends on real flags
    csdb                          // nothing after this uses a predicted-flags result
    ldrb    w3, [x0, x1]          // safe: x1 is in bounds or 0 on every path
    ldr     x4, [x5, x3, lsl #6]
1:

Linux uses a branchless mask form, array_index_mask_nospec() in arch/arm64/include/asm/barrier.h:

    cmp     x1, x2                // idx - sz: C = 1 when idx >= sz
    sbc     x6, xzr, xzr          // x6 = 0 - 0 - !C = ~0 if idx < sz, else 0
    csdb
    and     x1, x1, x6            // array_index_nospec(): idx or 0

SBC consumes the carry flag in the same way CSEL does, so the CSDB rule covers it. OP-TEE provides the same pattern as confine_array_index() in lib/libutils/ext/include/confine_array_index.h, using CMP; CSEL ..., LO; HINT #20, and uses it in its SCMI server and drivers on IDs that come from the Normal world.

Clamping to 0 is a convention. Any index that is in bounds works. What matters is that the clamped value is architecturally correct on the good path and harmless on the bad one. Index 0 must not itself be secret, which is normally true for a dispatch table.

SB: Speculation Barrier

SB (FEAT_SB, ID_AA64ISAR1_EL1.SB, bits [39:36]) is permitted from v8.0 and mandatory from v8.5. It is a full stop for speculation. Paraphrasing DDI0487: until the SB completes, no instruction after it in program order can be executed speculatively to the extent that the speculation can be observed through side channels as a result of control-flow or data-value speculation. An SB cannot itself be executed speculatively as a result of control-flow or data-value speculation. It can be executed speculatively on the prediction that an earlier instruction does not take an exception, so it does not replace the fault-deferral defences of 14.6.

CSDBSB
EncodingHINT #20 (NOP if not understood)Dedicated system encoding; UNDEFINED without FEAT_SB
AvailabilityEvery v8.0+ coreFEAT_SB; mandatory from v8.5
StopsUse of predicted data values and predicted flags by later non-branch instructionsAll speculative execution past the barrier
Needs a select or mask in frontYesNo
CostUsually a few cyclesA pipeline drain, but no wait for memory completion
Fallback when absent—DSB SY; ISB (TF-A) or DSB NSH; ISB (Linux). Documented by Arm as working, but not architecturally defined as a speculation barrier

Use SB where masking is impractical:

  • after an ERET or a RET (straight-line speculation, 14.2);
  • after a bounds check that guards a long block with many uses of the index;
  • after an untrusted pointer that is dereferenced in many places;
  • at the end of the BHB loop (14.4).

Use CSEL+CSDB on hot paths, because it costs a few cycles instead of a drain. Code that must run on both v8.0 and v8.5 parts needs to detect the feature at runtime or through build configuration. TF-A’s speculation_barrier macro uses ENABLE_FEAT_SB, and Linux patches the barrier at boot with alternatives.

Masking patterns that need no barrier

Some code is safe by construction. The rule is: if the index or pointer is forced into range by unconditional arithmetic, with no flag involved, no prediction can produce an out-of-range value.

PatternExampleWhy it is safe
Power-of-two table indexed by a bit fieldTF-A’s SMC dispatcher: two ubfx and an orr combine the 6-bit OEN with the call-type bit, giving a 7-bit index into rt_svc_descs_indices[128] (MAX_RT_SVCS)Every value the ubfx can produce is inside the array
AND with size−1table[idx & (N - 1)] for N a power of twoRange forced without flags
Address-space bit clearingLinux __uaccess_mask_ptr(): BIC ptr, ptr, #(1 << 55)A user pointer can never select the TTBR1 (kernel) half, even speculatively
Branchless minCMP + CSEL to the boundNeeds CSDB, because CSEL reads flags

Watch the second stage in the TF-A example. The byte read from rt_svc_descs_indices is checked with tbnz w15, #7, smc_unknown before it scales into the descriptor array, and that check is a branch. Whether a mispredicted tbnz is a gadget depends on what an out-of-range descriptor load can reach and on the fact that the result is used as an indirect branch target. This is exactly the kind of judgement an audit has to make (14.8).

Compiler support

  • Builtins. GCC provides __builtin_speculation_safe_value(val, failval). On AArch64 it lowers to a conditional select plus CSDB when speculation tracking is available, and to a heavier barrier otherwise. Linux and OP-TEE use their own inline assembly, which makes the instruction sequence explicit.
  • Whole-program hardening. Clang’s speculative load hardening (-mspeculative-load-hardening) supports AArch64. It tracks misprediction in a register using CSEL and CSDB, and masks loaded values or addresses. Its cost is high, so firmware rarely uses it.
  • The compiler can undo you. A C-level if (i < n) i &= mask; can be turned back into a branch, or have the mask hoisted. Write the mask in asm volatile, as Linux and OP-TEE do, or use the builtin.

Variant 1.1 and other relatives

Bounds check bypass store (v1.1, CVE-2018-3693) uses the same mispredicted bounds check to guard a store. Speculative stores never leave the core, but the transient store can be forwarded to younger transient loads. A transient store that overwrites a saved return address on the stack gives a transient RET to an attacker-chosen target. The fixes are the same: mask the index before the store, or put an SB after the check.

v1 gadgets in a TEE are found wherever Normal-world input selects memory. Look for:

  • SMC arguments x1–x7;
  • FF-A partition IDs and memory-handle indices;
  • SCMI domain and clock IDs;
  • OP-TEE syscall and pseudo-TA command IDs;
  • lengths that bound a loop over a Secure buffer.

The two-load shape (an index into table A, whose value indexes table B) is the classic gadget. An index into a table of function pointers is just as bad, because it combines v1 with an indirect branch.

Security note: The bounds check and the mask must use the same, already-copied value. If an SMC handler reads idx from shared Normal-world memory, checks it, and then reads it again to use it, the result is a TOCTOU bug whether or not speculation is involved. A speculative-only fix such as CSDB on the second read does not address it. Copy untrusted values into registers or Secure memory once, then check and mask the copy.

Checkpoint

Q14.3.1 A developer hardens a bounds check by adding CSDB directly after b.hs 1f, with no CSEL, and leaves ldrb w3, [x0, x1] using the unmodified x1. Is the gadget closed?

  • A. Yes. CSDB prevents speculative execution past it until the preceding branch resolves.
  • B. Yes, on v8.5 cores, where CSDB is upgraded to SB semantics.
  • C. No. CSDB only stops later instructions from consuming results derived from predicted flags or predicted data values. x1 was never derived from the flags, so the load can still use the out-of-range value on the mispredicted path.
  • D. No, because CSDB must come before the CMP to take effect.
Answer

C. CSDB is not a control-flow barrier. It is effective only together with an instruction such as CSEL or SBC that turns the real flags into a data value. Then, on the wrong path, the value used after the CSDB is the clamped one. A describes SB, not CSDB. B is false: CSDB’s semantics do not change with the architecture version.

Read more: Arm ARM (DDI0487), CSDB; Arm whitepaper “Cache Speculation Side-channels”, Software mitigation

Q14.3.2 Which of these index sanitisations is safe against Spectre v1 without any speculation barrier?

  • A. cmp x1, x2; csel x1, x1, xzr, lo
  • B. and x1, x1, #0x3f for a 64-entry table
  • C. cmp x1, x2; b.hs fail with the load placed after the branch
  • D. cmp x1, x2; sbc x6, xzr, xzr; and x1, x1, x6
Answer

B. The AND forces the index into 0–63 without reading any flag, so no prediction can produce an out-of-range value. A and D both derive the mask from flags, which may be predicted, so they need a CSDB after the flag-consuming instruction. That is exactly why Linux’s array_index_mask_nospec() ends with csdb(). C is the unmitigated gadget.

Read more: Arm ARM (DDI0487), CSDB; Linux arch/arm64/include/asm/barrier.h, array_index_mask_nospec()

Q14.3.3 TF-A is built with ENABLE_FEAT_SB=1 by mistake for a v8.2 core that lacks FEAT_SB and uses the BHB loop mitigation on its lower-EL vectors. FEATURE_DETECTION is left at its default of 0. What happens?

  • A. Every ERET from EL3 is followed by an Undefined Instruction exception, because the SB in exception_return is UNDEFINED.
  • B. Nothing. SB is in the hint space and executes as a NOP on cores that lack it.
  • C. ERET paths work, because the SB after an ERET is never architecturally executed. The first exception from a lower EL runs the BHB loop’s speculation_barrier architecturally, and that SB takes an Undefined Instruction exception (EC 0x00) at EL3.
  • D. The core silently falls back to DSB NSH; ISB for every SB.
Answer

C. Unlike CSDB, SB has a dedicated encoding outside the hint space, and it is UNDEFINED without FEAT_SB. An SB placed after ERET is only ever reached speculatively, so it never faults, and on this core it also gives no protection. The barrier at the end of the BHB loop is in the normal flow of the vector entry, so it is executed and faults. A misses that difference. B confuses SB with CSDB. D describes a build-time choice in TF-A’s macros, not a hardware fallback.

Read more: Arm ARM (DDI0487), SB; ID_AA64ISAR1_EL1.SB; TF-A docs, build options, ENABLE_FEAT_SB