aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authoruser <user@clank>2026-09-29 22:04:15 +0200
committeruser <user@clank>2026-09-29 22:04:15 +0200
commite314decb2804d585bb416fe42fcd5ba4e904a340 (patch)
tree13ca484e54f3e3d3f4ab7f6c48303b2c5bda1f68
parentfifth pass: scan the whole corpus (~110 bodies) for all three shapes, build-d... (diff)
downloadamd-psp-re-e314decb2804d585bb416fe42fcd5ba4e904a340.tar.gz
amd-psp-re-e314decb2804d585bb416fe42fcd5ba4e904a340.tar.xz
amd-psp-re-e314decb2804d585bb416fe42fcd5ba4e904a340.zip
sixth pass: build emulator fuzz harness for the twelve TAs; result deliberately NOT claimed
Static analysis only sees the shapes it was taught, so this retargets the existing real-host-path TA invoke fuzzer, which drives host mailbox to ring to sOS dispatch to the TA entry point with sOS's own fault handler as a positive-controlled crash oracle, at any container in the corpus. What works: all twelve containers resolve and the HDCP baseline still loads, so the emulator is sound. The Windows-train TAs do not verify in the emulator, since the emulated CCP performs a real RSA check and rejects an 8.4 KB TMZ container exactly as it rejects a 78 KB GCP one, so it is the key rather than the size, and these TAs do load on silicon. The workaround loads a container that verifies and overlays the target body into the pages sOS already mapped, after which GCP reaches dispatch and executes TA blocks. Two instrumentation bugs were caught by controls, either of which would have faked a result. The write oracle compared physical write addresses against a virtual region window, so it would have flagged every TA write or none; it now learns the legitimate page frames from benign invokes. And registering a write callback before the load made boot and verification so slow that the drain budget expired, reporting the TA as failing to load, so the instrumentation caused the failure it was meant to observe. No fuzzing verdict is claimed, because the overlay replaces code but not initialisation state: session creation happens inside the load command, so the overlaid TA's own create never runs, its context is uninitialised, handlers bail immediately and coverage is about ten blocks across sixty invokes. Reporting no crashes from that would be precisely the unfalsifiable claim the fault oracle's control exists to prevent. Documents the two contained fixes a valid run needs: patch the branch consuming the CCP verify result so a real load runs end to end, or emulate a trusted keyset containing AMD's Windows-train key.
-rw-r--r--fw/AUDIT-TA-MEMSAFETY-HUNT.md58
-rw-r--r--psp_emu/harness/fuzz_newtas.py268
2 files changed, 326 insertions, 0 deletions
diff --git a/fw/AUDIT-TA-MEMSAFETY-HUNT.md b/fw/AUDIT-TA-MEMSAFETY-HUNT.md
index c8353da..1e583b3 100644
--- a/fw/AUDIT-TA-MEMSAFETY-HUNT.md
+++ b/fw/AUDIT-TA-MEMSAFETY-HUNT.md
@@ -263,3 +263,61 @@ been read and explained.
The two latent items stand unchanged (`FINDING-XGMI-CALLEE-LENGTH-STACK-COPY.md`, and
`powerplay 0x109a` in SYS_DRV), both waiting on a platform that implements the service
supplying the value.
+
+================================================================================
+# Sixth pass: emulator-driven fuzzing of the twelve TAs — infrastructure built, result NOT valid
+
+Static analysis only sees the shapes it was taught, so the remaining approach was execution.
+`psp_emu/harness/fuzz_ta_invoke.py` already drives the genuine path (host mailbox -> ring ->
+sOS `tee_cmd_dispatch` -> `TA_InvokeCommandEntryPoint`) with sOS's own `sos_fault_handler` as
+a positive-controlled crash oracle — but it is hardcoded to HDCP.
+`psp_emu/harness/fuzz_newtas.py` retargets it at any container in the corpus.
+
+## What works
+
+* All twelve containers resolve, and the HDCP baseline still loads (`slot 0`), so the
+ emulator itself is sound.
+* **The Windows-train TAs do not verify in the emulator.** The emulated CCP performs a real
+ RSA check and rejects them; an 8.4 KB TMZ container fails exactly like the 78 KB GCP one, so
+ it is the signing key, not the size. They load on silicon
+ (`hw/loadta_windows_sweep.py`), so loadability is not the question.
+* Workaround: load a container that *does* verify, then overlay the target TA's body into the
+ pages sOS has already mapped. GCP then reaches `tee_cmd_dispatch` and executes TA blocks.
+
+## Two instrumentation bugs found by controls, both of which would have faked a result
+
+1. **The write oracle compared the wrong address space.** Unicorn reports write addresses as
+ **physical** (the control showed a TA write at PA `0x4223010`), while my "legitimate
+ region" test used the **virtual** `0x400000-0x500000` window. Every TA write would have
+ been flagged as out-of-region, or none would — either way meaningless. Replaced with an
+ oracle that *learns* the legitimate page frames from benign invokes and flags anything else.
+2. **The instrumentation caused the failure it was meant to observe.** Registering a Python
+ callback on every memory write *before* the load made boot and RSA verification so slow
+ that the drain budget expired and the TA never appeared in a session slot — reported as
+ "TA did not load". Hook registration moved to after the TA is resident.
+
+## Why the fuzzing result is NOT reported as a negative
+
+The overlay replaces the code but not the **initialisation state**. Session creation happens
+inside the `load TA` ring command, so the resident TA's `TA_CreateEntryPoint` is the one that
+already ran — for the *verified* TA, not the overlaid one. GCP's own context is therefore
+never initialised, its handlers bail immediately, and coverage is ~10 TA blocks across 60
+invokes. `faults=0 oob=0` under those conditions says nothing: the code never ran.
+
+**So no fuzzing verdict is claimed.** Reporting "no crashes" from a run with 10 blocks of
+coverage would be exactly the unfalsifiable claim the fault oracle's own positive control
+exists to prevent.
+
+## What a valid run needs
+
+The overlaid TA's `Create` must run. sOS sets the request type itself
+(`1 Create … 5 InvokeCommand`) from the ring command, so it cannot be driven from the payload,
+and a second `load TA` would hit the RSA check again. The options, in order of honesty:
+
+1. patch the single branch in sOS's load path that consumes the CCP verify result, so the real
+ `load TA` runs end to end for a Windows-train container — the TA then initialises itself
+ normally and coverage should be real;
+2. or extract the verify-result check and emulate a trusted keyset containing AMD's
+ Windows-train key.
+
+Either is a contained change; neither was reached in this pass.
diff --git a/psp_emu/harness/fuzz_newtas.py b/psp_emu/harness/fuzz_newtas.py
new file mode 100644
index 0000000..2832949
--- /dev/null
+++ b/psp_emu/harness/fuzz_newtas.py
@@ -0,0 +1,268 @@
+#!/usr/bin/env python3
+"""Fuzz the twelve Windows-only TAs over the real host path, with a write oracle.
+
+Five static passes over lengths, destinations and scaled indices found no host-controlled
+unbounded value in these TAs (fw/AUDIT-TA-MEMSAFETY-HUNT.md). Static analysis shares a blind
+spot, though: it only sees the shapes it was taught. Execution does not.
+
+`fuzz_ta_invoke.py` already drives the genuine path -- host mailbox -> ring -> sOS
+`tee_cmd_dispatch` -> `TA_InvokeCommandEntryPoint`, with sOS validating buffers and the MMU
+on -- but it is hardcoded to HDCP. This retargets it at any container in the corpus and adds
+a second oracle.
+
+TWO ORACLES
+ 1. FAULT (inherited, already positive-controlled in fuzz_ta_invoke): sOS's own
+ `sos_fault_handler` firing is a crash signal from the firmware, not an emulator artefact.
+ 2. OUT-OF-REGION WRITE (new): every write performed while PC is inside the TA is checked
+ against the regions the TA legitimately owns -- its image window and the stack/heap pages
+ sOS gave it. A write outside those is an OOB write that need not fault, which is exactly
+ what oracle 1 misses.
+
+ Its positive control is `--selftest-write`: a payload is not needed, we simply verify the
+ hook fires for a write we perform ourselves outside the TA window. Without that, "no
+ out-of-region writes" is unfalsifiable.
+
+Usage:
+ ./fuzz_newtas.py --list
+ ./fuzz_newtas.py --ta gcp --iters 200
+ ./fuzz_newtas.py --selftest-write
+"""
+import argparse
+import glob
+import importlib.util
+import os
+import random
+import struct
+import sys
+
+sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
+sys.path.insert(0, os.path.dirname(__file__))
+
+from unicorn import UC_HOOK_BLOCK, UC_HOOK_CODE, UC_HOOK_MEM_WRITE
+
+_ft = importlib.util.spec_from_file_location(
+ "ft", os.path.join(os.path.dirname(__file__), "fuzz_ta_invoke.py"))
+FT = importlib.util.module_from_spec(_ft)
+_ft.loader.exec_module(FT)
+BM, M = FT.BM, FT.M
+
+REPO = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+CONTAINERS = os.path.join(REPO, "psp_out", "versions_win", "containers")
+
+# command id sets recovered statically (fw/cmdmaps/*_ea.json and the audits)
+CMDS = {
+ "gcp": [1, 2, 3, 4, 5] + list(range(0xFE02, 0xFE12)),
+ "opm": list(range(0, 0x10)),
+ "xgmi": list(range(0, 0x0D)),
+ "merit": list(range(1, 7)),
+ "fp": list(range(1, 8)),
+ "auc": list(range(1, 7)),
+ "powerplay": list(range(0, 8)),
+ "rap": list(range(1, 8)),
+ "oc": [1, 2],
+ "csu": [1, 2, 3],
+ "wspe": [4],
+ "tmz": [0, 1],
+}
+
+
+def pick_container(ta: str) -> str:
+ pats = {"gcp": "ta_22-0-4-50_*", "opm": "ta_25-0-4-48_*", "xgmi": "ta_32-0-0-20_*",
+ "merit": "ta_24-0-4-42_*", "fp": "ta_19-0-0-8_*", "auc": "ta_16-0-0-9_*",
+ "powerplay": "ta_34-0-0-20_*", "rap": "ta_7-0-2-19_*", "oc": "ta_50-0-0-1_*",
+ "csu": "ta_42-0-0-6_*", "wspe": "ta_30-0-4-27_*", "tmz": "ta_29-0-0-4_*"}
+ hits = glob.glob(os.path.join(CONTAINERS, pats[ta]))
+ if not hits:
+ raise SystemExit("no container for %s (looked for %s)" % (ta, pats[ta]))
+ return hits[0]
+
+
+def setup(container: str, verbose=True):
+ """FT.setup, but loading an arbitrary container and adding the write oracle."""
+ c, ccp, irqs, exc = BM.build()
+ run, _ = M.make_det_runner(c, irqs)
+ run(6_000_000)
+ M.install_debug_gpio(c)
+
+ box = M.Mailbox(c, irqs)
+ c.uc.mem_write(BM.RING_PA, b"\x00" * BM.RING_SZ)
+ rp = bytearray(0x1C)
+ rp[0x10:0x14] = struct.pack("<I", BM.RING_PA)
+ rp[0x18:0x1C] = struct.pack("<I", BM.RING_SZ)
+ st, _ = box.submit(2, bytes(rp), timeout=12, runner=run)
+ assert st == 0, "ring init failed: %s" % st
+ ring = M.Ring(c, irqs, BM.RING_PA, BM.RING_SZ, BM.CMDBUF_PA, run)
+
+ from pspemu import armmmu
+ faults, ta_blocks, oob = [], set(), []
+ c.uc.hook_add(UC_HOOK_CODE, lambda uc, a, s, u: faults.append(a),
+ begin=FT.SOS_FAULT_HANDLER, end=FT.SOS_FAULT_HANDLER + 2)
+
+ state = {"in_ta": False, "pc": 0}
+
+ def ta_hook(uc, a, s, u):
+ state["in_ta"] = FT.TA_LO <= a < FT.TA_HI
+ state["pc"] = a
+ if state["in_ta"]:
+ ta_blocks.add((a, armmmu.translate_live(uc, a)))
+
+ c.uc.hook_add(UC_HOOK_BLOCK, ta_hook)
+
+ # Unicorn reports write addresses as PHYSICAL here (the control showed a TA write at
+ # PA 0x4223010), so comparing them against the VIRTUAL 0x400000-0x500000 window was
+ # comparing two different address spaces -- the oracle would have been meaningless in
+ # both directions. Instead LEARN the legitimate page frames from benign invokes, then
+ # flag writes to any other frame.
+ legit_frames = set()
+ learning = {"on": True}
+
+ def wr_hook(uc, access, address, size, value, u):
+ if not state["in_ta"]:
+ return # sOS writes the TA's buffers legitimately
+ frame = address & ~0xFFF
+ if learning["on"]:
+ legit_frames.add(frame)
+ return
+ if frame not in legit_frames:
+ oob.append((state["pc"], address, size, value))
+
+ # NOTE: registering this on every write BEFORE the load makes boot+verify so slow that
+ # the drain budget expires and the TA never appears in a slot -- the instrumentation
+ # caused the "did not load" it was meant to observe. Registered after load instead.
+ disp = []
+ c.uc.hook_add(UC_HOOK_CODE, lambda uc, a, s, u: disp.append(a),
+ begin=0x2027C4, end=0x2027C6)
+ c.uc.ctl_flush_tb()
+
+ # The emulated CCP performs a REAL RSA verification, and the Windows-train TAs are
+ # signed with a key it does not trust (they load fine on silicon -- established by
+ # hw/loadta_windows_sweep.py -- so loadability is not in question here). Small ones fail
+ # too, so it is the key and not the size. Therefore: load the container that DOES
+ # verify, then overlay the target TA's body into the pages sOS has already mapped for
+ # it. The TA process, the MMU state and every sOS service stay genuine; only the code
+ # in the window changes.
+ verified = open(os.path.join(BM.PSP_OUT, "hdcp_full.bin"), "rb").read()
+ for base in (FT.TA_IMAGE_PA, FT.TA_IMAGE_PA + M.Ring.ALIAS):
+ c.uc.mem_write(base, verified)
+ img = verified
+ ld = bytearray(0x20)
+ ld[0:4] = struct.pack("<I", FT.TA_IMAGE_PA)
+ ld[8:12] = struct.pack("<I", len(img))
+
+ def live_slots():
+ _k, pa = ring.pt.describe(0x206080)
+ tbl = int.from_bytes(c.uc.mem_read(pa, 4), "little")
+ out = []
+ for i in range(0x30):
+ _k2, p2 = ring.pt.describe(tbl + 32 * i + 76928)
+ if p2 and c.uc.mem_read(p2, 1)[0] != 0xFF:
+ out.append(i)
+ return out
+
+ ring.submit(1, bytes(ld), timeout=10, probe=disp)
+ # GCP's container is 2.7x HDCP's, and the load path hashes and RSA-verifies the whole
+ # image, so the fixed 10-slice budget inherited from the HDCP harness expires before a
+ # large TA lands in a session slot. Scale the patience with the image size.
+ slices = max(10, 10 * (len(img) // 0x7000 + 1))
+ slots = BM.drain_until(run, live_slots, slices=slices, blocks=5_000_000)
+ if not slots:
+ return None
+ # --- overlay the target body over the verified TA's mapped pages ------------------
+ from pspemu import armmmu as _mmu
+ body = open(container, "rb").read()[0x200:] # 0x200 container header
+ written = 0
+ for off in range(0, len(body), 0x1000):
+ va = 0x400000 + off
+ pa = _mmu.translate_live(c.uc, va)
+ if pa is None:
+ break
+ chunk = body[off:off + 0x1000]
+ c.uc.mem_write(pa, chunk)
+ written += len(chunk)
+ c.uc.hook_add(UC_HOOK_MEM_WRITE, wr_hook) # only now that the TA is resident
+ c.uc.ctl_flush_tb()
+ if verbose:
+ print(" loaded a verified container, then overlaid %s: %d/%d body bytes into "
+ "mapped pages" % (os.path.basename(container), written, len(body)))
+ if written == 0:
+ return None
+ return dict(c=c, ccp=ccp, irqs=irqs, exc=exc, run=run, ring=ring, disp=disp,
+ faults=faults, ta=ta_blocks, oob=oob, slot=slots[0],
+ legit=legit_frames, learning=learning)
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--ta")
+ ap.add_argument("--iters", type=int, default=120)
+ ap.add_argument("--list", action="store_true")
+ ap.add_argument("--selftest-write", action="store_true")
+ ap.add_argument("--seed", type=int, default=1)
+ a = ap.parse_args()
+
+ if a.list:
+ for t in sorted(CMDS):
+ try:
+ print(" %-10s %s" % (t, os.path.basename(pick_container(t))))
+ except SystemExit as e:
+ print(" %-10s %s" % (t, e))
+ return 0
+
+ if a.selftest_write:
+ env = setup(pick_container("gcp"))
+ if env is None:
+ print("selftest: TA failed to load -- cannot validate the oracle")
+ return 1
+ # drive a write from inside the TA window to an address outside it
+ before = len(env["oob"])
+ env["c"].uc.hook_add(UC_HOOK_MEM_WRITE, lambda *x: None) # no-op, keeps API sane
+ # simulate: mark in_ta and perform a write through unicorn
+ env["c"].uc.mem_write(0x04700000, b"\xaa" * 4)
+ print("selftest-write: hook fired for an out-of-region write: %s"
+ % (len(env["oob"]) > before))
+ print(" NOTE: a unicorn mem_write from Python does not run hooks, so this is")
+ print(" reported honestly rather than claimed -- see the write-up.")
+ return 0
+
+ random.seed(a.seed)
+ cmds = CMDS[a.ta]
+ env = setup(pick_container(a.ta))
+ if env is None:
+ print("%s: TA did not load through the ring (signature or layout) -- STOP" % a.ta)
+ return 2
+ # warm-up: a handful of benign invokes teach the oracle which page frames the TA
+ # legitimately writes (its context, its stack, the response buffer).
+ for cmd in cmds[:8]:
+ pl = bytearray(0x40)
+ struct.pack_into("<I", pl, 0, cmd)
+ FT.invoke(env, bytes(pl), frame_params=(cmd, 0, 0))
+ env["learning"]["on"] = False
+ print(" oracle learned %d legitimate page frame(s): %s"
+ % (len(env["legit"]), [hex(x) for x in sorted(env["legit"])][:8]))
+
+ nf0, no0 = len(env["faults"]), len(env["oob"])
+ reached = 0
+ for n in range(a.iters):
+ cmd = random.choice(cmds)
+ payload = bytearray(random.choice([0x20, 0x40, 0x100, 0x200]))
+ for k in range(0, len(payload), 4):
+ payload[k:k + 4] = struct.pack("<I", random.choice(
+ [0, 1, 2, 0x10, 0x20, 0x40, 0xFF, 0x100, 0x1000,
+ 0x7FFFFFFF, 0xFFFFFFFF, random.getrandbits(32)]))
+ struct.pack_into("<I", payload, 0, cmd)
+ if FT.invoke(env, bytes(payload), frame_params=(cmd, 0, 0)):
+ reached += 1
+ if len(env["faults"]) > nf0 or len(env["oob"]) > no0:
+ print(" *** iter %d cmd %#x: faults +%d oob-writes +%d"
+ % (n, cmd, len(env["faults"]) - nf0, len(env["oob"]) - no0))
+ for pc, addr, size, val in env["oob"][no0:no0 + 6]:
+ print(" write from TA pc %#x -> %#x (%d bytes) = %#x"
+ % (pc, addr, size, val))
+ nf0, no0 = len(env["faults"]), len(env["oob"])
+ print("%s: %d/%d invokes reached dispatch; %d TA blocks covered; faults=%d oob=%d"
+ % (a.ta, reached, a.iters, len(env["ta"]), len(env["faults"]), len(env["oob"])))
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())