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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
|
"""Fuzz the host-reachable HDCP TA entry point inside the emulator.
Entry: hdcp_invoke_entry(a1, a2, a3, a4)
a3 & 0xF == 7, a4 = &{buf_ptr, buf_len}, buf_len > 0x2817
buf+0 = command id
buf+12 = request body
buf+5136 = response body
Why emulate: a canary smash on hardware costs a PCIe retrain + reboot (~40 s per
case). Here it is sub-millisecond, deterministic, and we get the exact faulting
PC/address instead of a crash record that cannot even name which of the 16
__stack_chk_fail callers fired.
Detection (all hook-free -- UC_HOOK_MEM_WRITE corrupts Thumb ITSTATE, see
pspemu/trace.py):
* unicorn fault -> kind/addr/pc (incl. the __stack_chk_fail DEADBEEF trap)
* redzone sentinels -> OOB writes past the session table and past the request
buffer, detected by reading memory after the run
* instruction budget -> hangs / runaway loops
"""
import os
import random
import sys
from collections import Counter
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
from pspemu import Component, CryptoService, AsdRpcService, consts # noqa: E402
TABLE_PTR = consts.HDCP["session_table_ptr"]
SESS_SZ = consts.SESS_SIZE
NSESS = 8
RED = b"\xDE\xAD\xBE\xEF" * 4 # 16-byte redzone sentinel
STACK_TRAP_PC = 0x40433C # __stack_chk_fail's deliberate load
CMDS = [1, 2, 3, 4, 5, 6, 7, 9, 0xB, 0xC, 0xE, 0xF, 0x10, 0x11, 0x12, 0x13]
# TA entry points, from the entry trampoline's literal pool at 0x4042a0.
TA_CREATE = 0x40139C
TA_INVOKE = 0x4013B4
CMD_OPEN_SESSION = 0x0E
class Fuzzer:
def __init__(self, seed=0, persist=None):
# PERSISTENCE. Hardware keeps TA globals for a whole boot, and the
# cmd 0x0F err_state latch is precisely a cross-command state effect:
# the first failing subcommand bricks a session for later cmd 0x0F.
# Wiping the session table every iteration makes that unreachable, so
# this harness could never find any bug needing accumulated state.
#
# persist=True models "one boot, many commands" (a real host session)
# persist=False models "fresh slot per observation", which is the
# protocol the HARDWARE measurements used -- also valid,
# but it is a different experiment, not a neutral default.
#
# Measured, 1500 iterations seed 1, distinct HDCP blocks / CANARY_SMASH:
# wipe 767 / 26 persist+reboot/50 800 / 6
# persist+reboot/200 837 / 4 persist (no reboot) 839 / 3
# Persistence gains ~9% coverage; the drop in CANARY_SMASH is the LATCH
# being modelled (subcmd12 stops being reached), not lost bug-finding.
self.persist = (os.environ.get("HDCP_PERSIST", "1") != "0") if persist is None else persist
self.rng = random.Random(seed)
self.c = Component("hdcp")
self.c.set_rpc_services({
consts.SERVICE_CRYPTO: CryptoService(overrun_uninitialised=False),
consts.SERVICE_ASD: AsdRpcService(stub_status=0),
})
c = self.c
# Run the TA's own init and use the TA's own session table, rather than
# allocating one and patching `dword_40237C` to point at it. The real
# table is at the image default 0x407000 (zeroed BSS); 8 slots end at
# 0x408460, still inside the mapped image region, so the redzone oracle
# below survives the move.
c.run_function(TA_CREATE, (0, 0, 0, 0))
self.table = c.rd32(TABLE_PTR)
# NO session-table redzone. It used to sit at table + NSESS*SESS_SZ,
# which was safe only while the table was a private c.alloc() with
# slack behind it. Against the TA's REAL table at 0x407000 that address
# is not spare memory: the firmware keeps a 60-byte record array there,
# starting exactly at 0x408460 and walked with `adds r4,#0x3c`
# (destinations 0x408460, 0x40849c, 0x4084d8, ... from the serialisation
# loop at 0x4032f0-0x403325). A sentinel there overlays live TA data and
# every command that touches the array reports an overrun.
#
# That is what the REDZONE_session_table hit in 5/5 seeds actually was:
# an artefact of this harness's own placement, not a firmware overrun.
# See psp_out/OBSERVATION-SESSION-TABLE-REDZONE-UNDER-REAL-INIT.md.
#
# The oracle is not re-sited, because "writes past the last session
# slot" is not expressible when a real object begins at that address.
# Overruns are still caught by the canary check, the argbuf redzones and
# fault classification.
# request/response buffer + redzone
self.buf = c.alloc(0x4000 + 64)
self.buf_red = self.buf + 0x4000
# scratch for the real cmd 0x0E open path
self.openbuf = c.alloc(0x4000)
self.openparams = c.alloc(0x40)
# the {ptr,len} descriptor a4 points at
self.desc = c.alloc(8)
c.wr32(self.desc + 0, self.buf)
c.wr32(self.desc + 4, 0x4000)
self.stats = Counter()
self.findings = []
def reset(self):
c = self.c
# I/O scratch is always reset; the SESSION TABLE is TA state and is only
# wiped in non-persistent mode.
if not self.persist:
c.write(self.table, b"\x00" * (NSESS * SESS_SZ))
c.write(self.buf, b"\x00" * 0x4000)
c.write(self.buf_red, RED)
c.wr32(self.desc + 0, self.buf)
c.wr32(self.desc + 4, 0x4000)
def _invoke_open(self):
"""One real cmd 0x0E open. hdcp_invoke_entry requires paramTypes&0xF==7
and params[0].size > 0x2817, with the command id in *buffer."""
c = self.c
c.wr32(self.openbuf, CMD_OPEN_SESSION)
c.wr32(self.openparams + 0, self.openbuf)
c.wr32(self.openparams + 4, 0x3000)
try:
c.run_function(TA_INVOKE, (0, 0, 7, self.openparams))
except Exception:
pass
def open_sessions(self):
"""Put a few sessions in the post-cmd0E state the host can reach.
`state`/`active` used to be written straight into the table. They are
now set by the firmware: each real cmd 0x0E invoke opens the next free
slot. `topology_type`//`mode` are still fuzzed inputs, not bookkeeping.
"""
for i in range(NSESS):
if self.rng.random() < 0.75:
self._invoke_open()
for i in range(NSESS):
s = self.table + SESS_SZ * i
if self.c.rd32(s + 0x008) == 1: # opened by the TA
self.c.wr32(s + 0x010, self.rng.choice([6, 6, 6, 0, 1]))
self.c.wr32(s + 0x024, self.rng.choice([20, 21, 22, 0]))
# subcommand id -> (length formula given N, max N)
SUBCMDS = {3: (lambda n: 524, 0), 6: (lambda n: 1 + 16, 0), 7: (lambda n: 1 + 32, 0),
8: (lambda n: 1 + 16, 0), 10: (lambda n: 1 + 8, 0),
12: (lambda n: 5 * n + 26, 103), 13: (lambda n: 2, 0),
17: (lambda n: 1 + 32, 0), 18: (lambda n: 1 + 4, 0), 20: (lambda n: 1 + 4, 0)}
def mutate(self, cmd):
"""Structure-aware: build a VALID skeleton, then fuzz the contents.
Random bytes essentially never satisfy cmd 0x0F's `payload[0]==desc.id`
check or the per-subcommand length formulas, so a naive mutator never
gets past the dispatcher (measured: 9/28 function entries, no subcommand
ever reached). This builds the skeleton and fuzzes inside it.
"""
c, rng = self.c, self.rng
c.wr32(self.buf, cmd)
req = bytearray(0x244)
req[0x00] = rng.randrange(NSESS) # slot
if cmd == 0xF:
off = 0x1C # payload cursor
for d in range(rng.randint(1, 3)): # up to 3 descriptors
sid = rng.choice([12,12,3,7,17,6,8,10,13,18,20]) if d==0 else rng.choice(list(self.SUBCMDS))
fml, maxn = self.SUBCMDS[sid]
n = rng.randint(0, maxn) if maxn else 0
ln = fml(n)
if rng.random() < 0.25: # length edge cases
ln += rng.choice([-2, -1, 1, 2, 5])
# NB: pack into `req` -- writing to memory here would be
# clobbered by the single c.write() of `req` at the end.
req[0x04 + 8 * d:0x08 + 8 * d] = int(sid & 0xFFFFFFFF).to_bytes(4, "little")
req[0x08 + 8 * d:0x0C + 8 * d] = int(ln & 0xFFFFFFFF).to_bytes(4, "little")
if off < 0x244:
req[off] = sid # payload[0] == desc.id
body = bytes(rng.getrandbits(8) for _ in range(min(max(ln - 1, 0), 0x244 - off - 1)))
if sid == 12 and len(body) > 9:
b = bytearray(body)
b[0] = 0; b[1] = 0; b[2] = n # msg[0],msg[1],msg[2]=rx_count
if rng.random() < 0.5:
b[6] = b[7] = b[8] = 0 # seq=0 -> reach the v58 copy
body = bytes(b)
req[off + 1:off + 1 + len(body)] = body
off += max(ln, 1)
# the builder selectors live at request +0x23C / +0x240
req[0x23C] = rng.choice([2, 4, 5, 9, 11, 14, 15, 16, 19, 129, rng.getrandbits(8)])
req[0x240] = rng.choice([2, 4, 5, 9, 11, 14, 15, 16, 19, 129, rng.getrandbits(8)])
else:
n = rng.choice([16, 64, 256, 0x244])
req[4:4 + n] = bytes(rng.getrandbits(8) for _ in range(min(n, 0x244 - 4)))
c.write(self.buf + 12, bytes(req))
def run_one(self):
self.reset()
self.open_sessions()
# cmd 0x0F carries the entire subcommand+builder surface; bias hard toward it
cmd = 0xF if self.rng.random() < 0.75 else self.rng.choice(CMDS)
self.mutate(cmd)
c = self.c
try:
c.run_function(consts.HDCP["invoke_entry"], (0, 0, 7, self.desc),
count=2_000_000)
fault = None
except Exception as e:
fault = e
# hook-free post-run checks
red_buf = c.read(self.buf_red, 16) != RED
if fault is not None:
f = c.faults[-1] if c.faults else {}
pc = f.get("pc", 0)
if pc == STACK_TRAP_PC:
kind = "CANARY_SMASH"
else:
kind = f.get("kind", "FAULT")
self.stats[kind] += 1
if kind != "CANARY_SMASH":
self.findings.append((kind, cmd, hex(pc), hex(f.get("addr", 0))))
else:
self.stats["ok"] += 1
if red_buf:
self.stats["REDZONE_request_buf"] += 1
self.findings.append(("REDZONE_request_buf", cmd, "-", "-"))
return cmd
def main(iters=3000, seed=1):
f = Fuzzer(seed)
for i in range(iters):
f.run_one()
print("iterations:", iters, " seed:", seed,
" state:", "PERSISTENT (one boot)" if f.persist else "wiped per iteration")
# Show the latch, so the state regime is visible rather than implied.
act = [k for k in range(NSESS) if f.c.rd32(f.table + k * SESS_SZ + 8) == 1]
errs = Counter(f.c.rd32(f.table + k * SESS_SZ + 0x18) for k in act)
print(" sessions active at end: %d err_state distribution: %s"
% (len(act), dict(errs)))
for k, v in f.stats.most_common():
print(" %-26s %d" % (k, v))
if f.findings:
print("\nnon-canary findings (first 25):")
seen = set()
for t in f.findings[:200]:
key = (t[0], t[2])
if key in seen:
continue
seen.add(key)
print(" kind=%-22s cmd=%#04x pc=%-12s addr=%s" % t)
if len(seen) >= 25:
break
else:
print("\nno faults or redzone violations")
if __name__ == "__main__":
main(int(sys.argv[1]) if len(sys.argv) > 1 else 3000,
int(sys.argv[2]) if len(sys.argv) > 2 else 1)
|