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.8 Exercises: auditing for missing mitigations

These exercises practise the review questions from 14.1 on code you are likely to meet in EL3 and Secure-world firmware. For each one, decide what the attacker controls, which variant applies, what the fix is, and how you would show that the fix matters. Answers are collapsed. Try each before opening it.

Use this checklist for all of them:

QuestionVariantWhere the fix lives
Is there an indirect branch reachable from a lower-EL entry before any prediction mitigation?v2, BHB14.4
Is an attacker-supplied value bounds-checked by a branch and then used to form an address?v114.3
Is a sanitised value written over an attacker value in memory and then reloaded?v414.5
Can code fall through an ERET, RET or BR into bytes that load?SLS14.2
Is a context identity (ASID, VMID, image slot) reused for a new owner?Prediction residue14.7
Does secret-dependent work rely on a PSTATE bit (SSBS, DIT) that someone else could have left in the wrong state?v4 / timing14.5, 14.6

Exercise 1: an EL3 vector

The platform’s core reports CSV2 = 1, CSV3 = 1, SSBS = 0 (not implemented), ECBHB = 0 and CLRBHB = 0. Its security bulletin lists it as affected by Spectre-BHB, with a branch-loop count k given in the TRM, and by Spectre v4, with an IMPLEMENTATION DEFINED “disable load pass store” bit that the platform uses dynamically. Audit this lower-EL AArch64 synchronous vector and the exit path:

    .balign 0x80
lower_el_sync_a64:                         // VBAR_EL3 + 0x400
    stp     x29, x30, [sp, #CTX_X29]
    mrs     x30, esr_el3
    ubfx    x30, x30, #26, #6              // EC
    cmp     x30, #0x17                     // SMC from AArch64?
    b.ne    1f
    ldr     x30, =smc_dispatch
    br      x30
1:  b       handle_other_sync

    // ...

el3_exit:
    bl      restore_gp_regs                // x0-x30 from context
    eret
    .ltorg                                 // literal pool follows

And in the reset code:

    mov_imm x0, (SCTLR_EL3_RES1 | SCTLR_I_BIT | SCTLR_SA_BIT | SCTLR_DSSBS_BIT)
    msr     sctlr_el3, x0
Answer

There are four problems, plus one non-problem.

  1. Indirect branch before BHB mitigation (Spectre-BHB). br x30 is the first indirect branch after entry from Non-secure EL1. On an affected core without ECBHB, the branch history built up by the Non-secure world selects its predicted target. CSV2 = 1 does not help, because CSV2 covers branch targets trained in another context, while BHB attacks steer selection by history. That is why CSV2_3 exists. Fixes: put the k-iteration branch loop (or CLRBHB where implemented, or rely on ECBHB) at the very top of every lower-EL vector entry, before any indirect branch. Better still, remove the indirect branch: b smc_dispatch reaches the same place, because the target is a link-time constant. The ldr =/br pair exists only for range, and a direct B covers ±128 MB.
  2. No v4 mitigation on entry. With dynamic WORKAROUND_2, the “disable load pass store” bit must be set on every lower-EL entry and restored to the caller’s requested state on exit (14.5). This vector does neither. EL3 runs with whatever the Non-secure kernel last asked for, and its context save (spill and reload of attacker-chosen x0–x7) is the shape of a v4 gadget.
  3. SLS after ERET. The literal pool follows the ERET directly. If the front end speculates straight past the ERET, it decodes pool constants as instructions, possibly including loads. Add sb (FEAT_SB) or dsb nsh; isb straight after the ERET, as TF-A’s exception_return macro does.
  4. No BHB mitigation on the path used by SMCCC_ARCH_WORKAROUND_3 discovery. If firmware answers SMCCC_ARCH_FEATURES(WORKAROUND_3) with 0 but the vectors do not actually run the loop, Linux trusts the answer and drops its own mitigation for calls into EL3. Check that the discovery answer and the vector code come from the same build flag (TF-A: WORKAROUND_CVE_2022_23960).

Non-problem: SCTLR_DSSBS_BIT in the SCTLR_EL3 value. On a core without FEAT_SSBS, SCTLR_EL3.DSSBS is RES0, so the bit does nothing. It is still a latent bug: the same code on a later core with SSBS would make EL3 run with SSBS=1, mitigation off. Clear it, as TF-A does.

How to show the fixes matter: on silicon, train the BHB from Non-secure EL1 with a branch pattern that ends in a call to a chosen gadget address, issue SMC, and look for a probe-array fill. Repeat with the loop enabled. PMU events BR_MIS_PRED and L1D_CACHE_REFILL counted around the SMC make the before/after difference visible without fine-grained timing.

Exercise 2: an SMC handler in C

typedef uint64_t (*svc_fn)(uint64_t, uint64_t);
static const svc_fn svc_table[NUM_SVCS];        /* NUM_SVCS = 11 */
static const uint8_t key[32];                   /* Secure */
static const uint8_t sbox[256];

uint64_t smc_handler(uint32_t fid, uint64_t x1, uint64_t x2)
{
    uint32_t idx = fid & 0xffff;
    if (idx >= NUM_SVCS)
        return SMC_UNK;
    return svc_table[idx](x1, x2);
}

static uint64_t svc_key_check(uint64_t i, uint64_t guess)
{
    if (i >= sizeof(key))
        return SMC_INVALID_PARAM;
    return sbox[key[i] ^ (uint8_t)guess] == 0;
}
Answer
  1. svc_table[idx] is v1 feeding an indirect call. The Non-secure caller trains idx >= NUM_SVCS as not taken with valid FIDs, then passes idx = 1000. The CPU speculatively loads a “function pointer” from svc_table + 8000, which is whatever EL3 data sits there, and branches to it speculatively with attacker-chosen x1/x2. This is worse than a plain v1 leak, because it gives the attacker a speculative jump to a location determined by EL3 memory contents. Fix: clamp the index without a branch the CPU can predict.
static inline uint64_t index_nospec(uint64_t idx, uint64_t size)
{
    uint64_t safe;
    asm volatile("cmp   %1, %2\n"
                 "csel  %0, %1, xzr, lo\n"
                 "csdb\n"
                 : "=r"(safe) : "r"(idx), "r"(size) : "cc");
    return safe;
}
    ...
    idx = index_nospec(idx, NUM_SVCS);

An alternative is to make the table size a power of two (16, padding the extra entries with an “unknown” handler) and use idx & 15. Then there is no bounds check to bypass, and TF-A’s runtime-service lookup uses the same idea (14.3).

  1. svc_key_check has the same v1 shape, key[i] followed by sbox[...], so it needs the same clamp on i. But it also leaks without any speculation. sbox[key[i] ^ guess] is an architecturally executed, secret-indexed load. Its cache footprint reveals key[i] ^ guess, so an attacker who can run Prime+Probe on a shared cache recovers the key byte by byte. Neither CSDB nor PSTATE.DIT fixes this. DIT makes the data timing of individual instructions constant; it does not make an address constant (14.6). The fix is algorithmic: compare in constant time without a table, or touch every table entry.

  2. Not a problem: fid & 0xffff is not a mitigation, but it is not a bug either. It just narrows the range before the check.

Exercise 3: spot the gadget

For each snippet, say whether there is an exploitable speculation or timing issue. If there is, name it and give the minimal fix. Assume Secure EL1 or EL3 code, with x0–x3 controlled by the Non-secure caller unless stated otherwise.

Snippet A

    cmp     x1, #64
    b.hs    out
    ldrb    w2, [x10, x1]          // x10: Secure buffer
    ldrb    w3, [x11, x2, lsl #6]  // x11: any buffer

Snippet B

    cmp     x1, #64
    csel    x1, x1, xzr, lo
    ldrb    w2, [x10, x1]
    ldrb    w3, [x11, x2, lsl #6]

Snippet C

    ubfx    x1, x0, #24, #4        // 4-bit field
    adr     x9, handlers           // 16 entries, all valid
    ldr     x9, [x9, x1, lsl #3]
    blr     x9

Snippet D

/* Secure partition manager, per-call */
ctx->arg_len = regs->x2;                    /* raw, saved for tracing   */
ctx->arg_len = MIN(regs->x2, MAX_LEN);      /* sanitised, same field    */
memcpy_from_ns(buf, regs->x1, ctx->arg_len);
val = lookup[buf[ctx->arg_len - 1]];        /* reload of arg_len        */

Snippet E

/* SPMC: restart a crashed partition */
void sp_restart(struct sp *sp)
{
    load_image(sp);                 /* same memory, same VMID */
    tlbi_vmalls12e1_for(sp->vmid);  /* TLBI VMALLS12E1IS; DSB ISH */
    sp_enter(sp);
}

Snippet F

el3_cold_boot:
    mov     x0, #DIT_BIT
    msr     dit, x0                // "constant-time crypto from here on"
    ...
lower_el_sync_a64:
    // ... save context, no DIT write ...
    bl      ecdsa_sign_with_hw_key
Answer

A: Spectre v1. This is the textbook shape: a predicted-not-taken b.hs, then a load indexed by x1 followed by a load indexed by the result. Fix: csel x1, x1, xzr, lo followed by csdb before the first load, or an SB after the branch where its cost is acceptable.

B: still v1, because the CSDB is missing. The CSEL looks like a mask, but without CSDB the architecture lets the PE use a predicted NZCV value (or a predicted data value) for the CSEL result. Speculatively, x1 can still be 1000. The guarantee comes from CSDB: later instructions, other than branches, cannot use unresolved NZCV or data-value predictions from before it. Add csdb after the CSEL. On a core that does not predict flags it costs nothing, and on one that does it is the fix.

C: no gadget. The index is bounded by construction (ubfx gives 0–15), every entry is a valid handler, and no conditional branch exists to mispredict. The blr is an indirect branch, so v2 and BHB still apply at the vector level (Exercise 1), but there is no v1 here. The lesson is to recognise this pattern as safe rather than adding CSDB everywhere.

D: Spectre v4. The raw x2 is stored, then overwritten with the clamped value at the same address, then reloaded. If the sanitising store’s address resolves late (for example ctx came from a cache-missing load), the reload can bypass it and transiently see the raw length. buf[len - 1] then indexes far outside buf, and lookup[...] turns the byte into a cache fill. Fixes, best first: keep the sanitised value in a register and do not reload it, or store the raw value in a different field. If the reload must stay, put ssbb between store and reload, or run the partition manager with PSTATE.SSBS = 0 (or the static chicken bit on pre-SSBS cores). The memcpy_from_ns also needs the clamp itself to be CSDB-safe if MIN compiles to a branch.

E: prediction residue on identity reuse. The new instance has the same Security state, EL and VMID as the old one, so CSV2 sees one context, and predictions the crashed (possibly compromised) instance trained remain usable. TLB maintenance has no effect on predictors. Fix: on each PE that ran the old instance, CFP/DVP/CPP RCTX (and COSP with SPECRES2) with the VMID, EL = EL1 and EL0, NS = 0, then DSB and ISB. Alternatively, give the restarted instance a fresh VMID and retire the old one until the next roll-over cleanup (14.7).

F: not speculation, but a real timing bug. PSTATE.DIT is a PSTATE bit. It is saved to SPSR_EL3 and restored by every ERET, and exception entry does not change it. After the first return to the Non-secure world, each SMC enters EL3 with the caller’s DIT value, typically 0, so the signing code runs without the data-independent-timing guarantee. Fix: msr dit, #1 on every EL3 entry, before any secret-dependent work, as TF-A’s ENABLE_FEAT_DIT entry code does (14.6).

Validation note: An audit finding becomes a validated finding only when you can show the signal with the mitigation removed. For each fix above, keep a directed test with a build switch that disables it. The test must give a probe-array signal (or, for D, a replay-count increase) with the switch off, and none with the switch on. Count INST_SPEC against INST_RETIRED to show the transient window opened, BR_MIS_PRED to show the training took effect, and L1D_CACHE_REFILL on the probe array (16.5). Run on silicon or cycle-accurate RTL, because FVP and QEMU model none of this. For E and F, an architectural test is enough to prove the precondition. For F, read MRS x0, DIT in the EL3 handler after entry from an EL1 that cleared DIT. For E, check that the restart path executes the RCTX instructions on every PE (a Tarmac trace on FVP shows them).

Checkpoint

Q14.8.1 A reviewer proposes adding CSDB after every indirect branch in EL3 “to stop Spectre”. Which statement best explains why this is the wrong fix?

  • A. CSDB is a NOP on all cores and has no effect anywhere
  • B. CSDB restricts the use of predicted NZCV and data values by later non-branch instructions. It does not constrain where an indirect branch is predicted to go, which is the v2/BHB problem
  • C. CSDB only works at EL0
  • D. CSDB must be placed before the branch, not after
Answer

B. Each variant has its own fix. Branch-target and history injection are handled by CSV2/CSV2_3, by vector-entry BHB sequences and WORKAROUND_1/3, or by removing the indirect branch. CSDB is a v1 tool used with CSEL masks. A is the tempting answer, because CSDB is a HINT that older cores treat as a NOP, but on cores with flag or data-value prediction it has defined semantics.

Read more: Arm ARM (DDI0487), CSDB; Restrictions on the effects of speculation

Q14.8.2 Firmware answers SMCCC_ARCH_FEATURES(SMCCC_ARCH_WORKAROUND_3) with 0, but a build-flag mismatch left the BHB loop out of the EL3 vectors. What is the consequence for a Linux kernel on an affected core?

  • A. None. Linux always runs its own BHB loop before an SMC
  • B. Linux detects the mismatch through ID_AA64MMFR1_EL1.ECBHB and falls back
  • C. Linux treats firmware as mitigated and may rely on the WORKAROUND_3 call for its own entry. EL3 entries are then unprotected, and Linux’s mitigation may also be incomplete
  • D. The SMC is rejected with NOT_SUPPORTED at run time
Answer

C. Discovery is a promise that the lower EL takes at face value. Nothing in the architecture checks it. ECBHB describes the hardware, not the firmware, so it cannot detect the gap. That is why the audit must tie the discovery answer and the vector code to one build flag, and why validation must test with the mitigation compiled out.

Read more: Arm, Firmware interfaces for mitigating cache speculation vulnerabilities (SMCCC_ARCH_WORKAROUND_3)

Q14.8.3 Of the following EL3 sequences, which one needs no additional speculation mitigation for v1, given that x0 is attacker-controlled?

  • A. and x1, x0, #7 then ldr x2, [x9, x1, lsl #3] into an 8-entry table, then ldrb w3, [x10, x2]
  • B. cmp x0, #8; b.hs 1f; ldr x2, [x9, x0, lsl #3]; ldrb w3, [x10, x2]
  • C. cmp x0, #8; csel x1, x0, xzr, lo; ldr x2, [x9, x1, lsl #3]; ldrb w3, [x10, x2]
  • D. cmp x0, #8; b.hs 1f; dmb ish; ldr x2, [x9, x0, lsl #3]; ldrb w3, [x10, x2]
Answer

A. The AND bounds the index by data dependency, with no prediction involved, so every speculative value is in range. B is the plain gadget. C is the tempting answer, but it lacks the CSDB that stops a predicted NZCV from feeding the CSEL. In D, a DMB orders observation and has no speculation semantics.

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