1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
|
#!/usr/bin/env python3
"""Load the ASD driver and run it, through the path hardware actually uses.
ASD is NOT loaded by the boot-time staging sweep, and that is correct firmware
behaviour rather than an emulator gap. `bl_stage2_task` guards its staging slot
(`+0x6F8000`) with a runtime flag:
00204a32 ldr r0, [r4, #4]
00204a34 ldr.w r0, [r0, #0x3e8]
00204a38 cmp r0, #0
00204a3a bge 0x204a76 ; >= 0 -> skip the ASD load entirely
...
00204a46 mov.w r2, #0x30000 ; slot bound
00204a54 add.w r1, r1, #0x6f8000
00204a58 bl 0x203f24 ; bl_load_ta_image
The gate field (VA 0x20E3E8) is **never written** during boot -- measured with a
write hook over the whole boot, zero writes -- so it keeps its zeroed BSS value
and the branch is always taken. ASD is driver-class (`'DR'` = 0x5244 at
body+0x14), not a TA, and arrives at runtime through the host ring instead.
So: boot, initialise the ring, and hand ASD to the firmware's own loader the
same way a host driver does. The image is verified on the CCP model (1 RSA
operation) and then executes in its own address space at 0xD00000.
Controls, because "ASD ran" is only meaningful if it could have failed:
positive -- clean image executes ASD code;
negative -- one bit flipped in the signed body, and one in the signature,
must each yield ZERO executed ASD blocks.
Exits non-zero unless all three hold.
"""
import sys, os, struct, importlib.util
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
sys.path.insert(0, os.path.dirname(__file__))
import unicorn
from unicorn import UC_HOOK_BLOCK
_b = importlib.util.spec_from_file_location(
"bmmod", os.path.join(os.path.dirname(__file__), "boot_and_mailbox.py"))
BM = importlib.util.module_from_spec(_b); _b.loader.exec_module(BM)
M = BM.M
ASD_LO, ASD_HI = 0x00D00000, 0x00E00000 # ASD's own address space
TA_PA = 0x04400000 # host-side staging for the image
IMAGE = os.environ.get("ASD_IMAGE", "asd_full.bin")
def boot_with_ring():
"""Boot sOS, bring up the command ring. No TA loaded yet."""
c, ccp, irqs, exc = BM.build()
run, _ = M.make_det_runner(c, irqs)
BM.drain_until(
run,
lambda: int.from_bytes(c.uc.mem_read(M.RING_STATUS, 4), "little") == 0x80000000,
slices=12, blocks=500_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, _raw = box.submit(2, bytes(rp), timeout=12, runner=run)
if st != 0:
raise SystemExit("ring init failed: %s" % st)
ring = M.Ring(c, irqs, BM.RING_PA, BM.RING_SZ, BM.CMDBUF_PA, run)
return c, ccp, irqs, ring, run
def load_asd(img, verbose=False):
"""One observation on a FRESH emulator.
Fresh per observation on purpose: a rejected load leaves the ring/session
state disturbed, and reusing one instance makes every later observation
look dead for the wrong reason (the latch documented in
psp_out/FINDING-HOST-MAILBOX-AND-RING-IN-EMULATOR.md).
"""
c, ccp, irqs, ring, run = boot_with_ring()
blocks = set()
# Range-filtered in C so this costs nothing on the hot path.
c.uc.hook_add(UC_HOOK_BLOCK, lambda u, a, s, x: blocks.add(a),
begin=ASD_LO, end=ASD_HI - 1)
c.uc.ctl_flush_tb()
for base in (TA_PA, TA_PA + M.Ring.ALIAS):
c.uc.mem_write(base, img)
ld = bytearray(0x20)
ld[0:4] = struct.pack("<I", TA_PA) # cmd buffer +0x1C image PA lo
ld[8:12] = struct.pack("<I", len(img)) # cmd buffer +0x24 image length
rsa0 = dict(ccp.stats()).get("RSA", 0)
probe = []
ring.submit(1, bytes(ld), timeout=10, probe=probe)
# Stop as soon as ASD code runs; a rejected image still gets the full budget.
BM.drain_until(run, lambda: bool(blocks), slices=6, blocks=2_000_000)
rsa1 = dict(ccp.stats()).get("RSA", 0)
return dict(blocks=blocks, faults=len(c.faults), rsa=rsa1 - rsa0, comp=c)
def main():
path = os.path.join(BM.PSP_OUT, IMAGE)
img = open(path, "rb").read()
klass = int.from_bytes(img[0x114:0x116], "little")
print("image: %s %d bytes (%#x) class body+0x14 = %#06x (%s)"
% (IMAGE, len(img), len(img), klass,
{0x5244: "'DR' driver", 0x4154: "'AT' trusted application"}.get(klass, "?")))
print("\nloading ASD through the host ring (firmware's own loader):")
pos = load_asd(img)
print(" clean image ASD blocks=%-4d faults=%-3d RSA ops=%d"
% (len(pos["blocks"]), pos["faults"], pos["rsa"]))
if pos["blocks"]:
print(" first ASD code executed: %s"
% sorted(hex(x) for x in pos["blocks"])[:8])
print("\nnegative controls (each MUST execute zero ASD blocks):")
negs = []
for label, off in (("1 bit flipped in signed body", 0x400),
("1 bit flipped in signature", len(img) - 0x80)):
bad = bytearray(img)
bad[off] ^= 0x01
r = load_asd(bytes(bad))
negs.append((label, len(r["blocks"])))
print(" %-30s ASD blocks=%-4d faults=%-3d RSA ops=%d"
% (label, len(r["blocks"]), r["faults"], r["rsa"]))
ok_pos = bool(pos["blocks"])
ok_neg = all(n == 0 for _l, n in negs)
print("\n== summary ==")
print(" ASD verified and executing : %s" % ("yes, %d blocks" % len(pos["blocks"])
if ok_pos else "NO"))
print(" corrupted images rejected : %s" % ("yes (%d/%d)" % (
sum(1 for _l, n in negs if n == 0), len(negs)) if ok_neg else "NO"))
if not ok_pos:
print("\nPOSITIVE CONTROL FAILED: ASD did not execute; nothing was measured.")
return 2
if not ok_neg:
print("\nNEGATIVE CONTROL FAILED: a corrupted image still ran ASD code, so")
print("'ASD loaded' here does not imply the signature check gated it.")
return 2
print(" RESULT: ASD loads, verifies and runs")
return 0
if __name__ == "__main__":
sys.exit(main())
|