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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
|
#!/usr/bin/env python3
"""Differential test: pspemu.gate vs the firmware's own region validators.
`pspemu/gate.py` reimplements sos_check_user_ptr (FA 0x178C) and
sos_check_user_range (FA 0x191C) from reading them. Reading is not evidence, so
this runs both against the real routines in a booted sOS over a spread of inputs
chosen to sit on every boundary the decode implies, and requires exact
agreement on the returned status.
It also carries its own positive control: a deliberately wrong model must be
caught. A differential that cannot fail is not a differential.
python3 harness/sos_gate.py -> rc 0 iff the model matches
"""
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from pspemu import Component, gate
CHECK_PTR = 0x178C
CHECK_RANGE = 0x191C
PROC_TABLE = 0x0000CA24 # the literal both routines load
# mcr p15,0,rX,c3,c0,0 sites in sOS's exception entry/exit paths
DACR_SITES = (0x1B4, 0x264, 0x294)
def proc_ids_by_type(c):
"""Provide one type-4 process and one that is not.
In a fresh image the process table at 0xCA24 is all zero, so every id reads
as type 0 and the type-4 branch of both validators would never execute --
the differential would silently cover only half the rule.
The type nibble is an INPUT to the routine under test, so writing it is
setting up the input, not faking a result: the routine's own logic still
decides the verdict, and the model is compared against that verdict. The
write is verified below by requiring the firmware to actually change its
answer for a SYS_DRV-window pointer.
"""
c.write(PROC_TABLE + 1 * 8, b"\x04") # pid 1 -> type 4
c.write(PROC_TABLE + 0 * 8, b"\x00") # pid 0 -> type 0
probe = 0x00E08000 # inside SYS_DRV's window
if c.run_function(CHECK_PTR, (1, probe, 0, 0)) != gate.GATE_BAD_PTR:
return None, None # type-4 branch not actually live
if c.run_function(CHECK_PTR, (0, probe, 0, 0)) != gate.GATE_OK:
return None, None # type-0 path not behaving either
return 1, 0
def ptr_vectors():
v = []
for edge in (0x0, 0x1000, 0x1FFFFF, 0x200000, 0x200001, 0x2FFFFF, 0x300000,
0x400000, 0xDFFFFF, 0xE00000, 0xE08000, 0xEFFFFF, 0xF00000,
0xFFFFFFF, 0x10000000, 0x10000001, 0x20000000, 0xFFFFFFFF):
v += [edge]
v += [0x400000 + i * 0x10101 for i in range(24)]
return v
def range_vectors():
out = []
bases = (0x0, 0x1FFFFF, 0x200000, 0x2FFFF0, 0x300000, 0x400000, 0xDFFFF0,
0xE00000, 0xEFFFF0, 0xF00000, 0xFFFFFF0, 0x10000000, 0xFFFFFFF0)
lens = (0, 1, 0x10, 0x1000, 0x100000, 0x1000000, 0x80000000, 0xFFFFFFFF)
for b in bases:
for l in lens:
out.append((b, l))
return out
def svc_gate_live():
"""The permission model must be enforced in SvcDispatcher, not just correct.
Two earlier versions of this check were wrong, both recorded because each
would have passed a gate that did nothing:
* driving TA_CreateEntryPoint, which issues no SVCs at all;
* driving an HDCP invoke, which issues 11 SVCs but all of them 0xF2 --
and 0xF2 > 0xEF, a range the firmware exempts from the permission
check entirely, so zero denials is the CORRECT answer there.
ASD is used instead: it issues 0x5D / 0x5E / 0x8D and friends, all <= 0xDF,
which a type-5 process is refused.
"""
import importlib.util
here = os.path.dirname(os.path.abspath(__file__))
spec = importlib.util.spec_from_file_location("fal", os.path.join(here, "fuzz_asd.py"))
FA = importlib.util.module_from_spec(spec); spec.loader.exec_module(FA)
counts = {}
for label, pb in (("ordinary", 0x00), ("type-5", 0x05)):
f = FA.AsdFuzzer(1)
f.c.config["proc_byte"] = pb
for _ in range(40):
try:
f.run_one()
except Exception:
pass
counts[label] = (len(f.c.svc.denied), len(f.c.svc.log))
print("\n SVC gate live in the dispatcher:")
for label in ("ordinary", "type-5"):
d, t = counts[label]
print(" %-9s process : %d of %d SVCs denied" % (label, d, t))
if counts["ordinary"][1] == 0:
return False # no SVC traffic: the check is vacuous
return counts["ordinary"][0] == 0 and counts["type-5"][0] > 0
def svc_permission_differential(c):
"""Compare gate.check_svc against the real sos_svc_dispatch.
The dispatcher reads the calling process from the current-task pointer at
0x80D8, so a task object is built and pointed at a chosen process entry --
those are the routine's INPUTS. Handler bodies are never executed: hooks at
the three body entry points stop emulation the moment one is reached, so the
comparison is purely 'denied with 0xE' vs 'reached a handler', with no side
effects to confuse it.
"""
from unicorn import UC_HOOK_CODE
from unicorn.arm_const import UC_ARM_REG_R0
CUR_TASK = 0x80D8
task = c.alloc(0x100)
c.write(task, b"\x00" * 0x100)
c.wr32(CUR_TASK, task)
c.wr32(task + 0x70, 0) # take the [r4+0x4C] path
pid = 2
c.write(task + 0x4C, bytes([pid])) # proc id, not 0xFF
reached = {"body": False}
def stop(u, a, s, x):
reached["body"] = True
u.emu_stop()
for site in (gate.SVC_BODY_LOW, gate.SVC_BODY_MID, gate.SVC_BODY_HIGH):
c.uc.hook_add(UC_HOOK_CODE, stop, begin=site, end=site)
c.uc.ctl_flush_tb()
svcs = [0x00, 0x51, 0x57, 0x5D, 0x75, 0x8D, 0xB4, 0xDF,
0xE0, 0xE5, 0xEF, 0xF0, 0xF2, 0xFF]
proc_bytes = [0x00, 0x01, 0x04, 0x05, 0x06, 0x07, 0x20, 0x25, 0x26, 0x2F]
mismatches, compared = [], 0
for pb in proc_bytes:
c.write(PROC_TABLE + pid * 8, bytes([pb]))
for s in svcs:
reached["body"] = False
try:
rv = c.run_function(0x587C, (s, 0, 0, 0))
except Exception:
rv = None
fw_denied = (not reached["body"]) and rv == gate.SVC_DENIED
me_denied = gate.check_svc(s, pb) == gate.SVC_DENIED
compared += 1
if fw_denied != me_denied:
mismatches.append((s, pb, fw_denied, me_denied, rv))
print("\n SVC permission gate (sos_svc_dispatch):")
print(" cases compared : %d" % compared)
print(" mismatches : %d" % len(mismatches))
for s, pb, fw, me, rv in mismatches[:8]:
print(" svc %#04x proc_byte %#04x firmware_denied=%s model_denied=%s rv=%s"
% (s, pb, fw, me, rv))
denied_n = sum(1 for pb in proc_bytes for s in svcs
if gate.check_svc(s, pb) == gate.SVC_DENIED)
print(" cases the gate actually denies: %d (if 0, the test proves nothing)"
% denied_n)
return len(mismatches), compared, denied_n
def dacr_enforced_by_emulator():
"""Does the emulator enforce ARM domain permissions at all?
Unicorn exposes no DACR register to Python, so this is settled by behaviour:
map one section into domain 1 and read it under different DACR settings.
The manager case is the positive control -- if it does not read cleanly the
test cannot discriminate and no conclusion may be drawn from the others.
"""
import struct
from unicorn import Uc, UC_ARCH_ARM, UC_MODE_ARM, UcError, UC_PROT_ALL
from unicorn.arm_const import UC_ARM_REG_R0
def movw(rd, imm): return 0xE3000000 | ((imm >> 12) << 16) | (rd << 12) | (imm & 0xFFF)
def movt(rd, imm): return 0xE3400000 | ((imm >> 12) << 16) | (rd << 12) | (imm & 0xFFF)
def trial(dom1, ap=3):
uc = Uc(UC_ARCH_ARM, UC_MODE_ARM)
CODE, PT, DATA = 0x0, 0x00100000, 0x00200000
for b, sz in ((CODE, 0x1000), (PT, 0x8000), (DATA, 0x1000)):
uc.mem_map(b, sz, UC_PROT_ALL)
tbl = bytearray(0x4000)
for i in range(16):
dom = 1 if i == 2 else 0 # 0x200000 >> 20 == 2
struct.pack_into("<I", tbl, i * 4, (i << 20) | (dom << 5) | (ap << 10) | 0x2)
uc.mem_write(PT, bytes(tbl))
uc.mem_write(DATA, b"\xEF\xBE\xAD\xDE")
dacr = (3 << 0) | (dom1 << 2)
asm = ([movw(0, PT & 0xFFFF), movt(0, PT >> 16), 0xEE020F10] +
[movw(0, dacr & 0xFFFF), movt(0, dacr >> 16), 0xEE030F10] +
[0xEE110F10, 0xE3800001, 0xEE010F10] +
[movw(1, DATA & 0xFFFF), movt(1, DATA >> 16), 0xE5910000, 0xEAFFFFFE])
blob = b"".join(struct.pack("<I", w) for w in asm)
uc.mem_write(CODE, blob)
try:
uc.emu_start(CODE, CODE + len(blob) - 4, count=60)
return uc.reg_read(UC_ARM_REG_R0) == 0xDEADBEEF
except UcError:
return False
control = trial(3) # manager: must read
noaccess = trial(0) # no access: must fault
client_ok = trial(1, ap=3) # client + AP allow: must read
client_deny = trial(1, ap=0) # client + AP deny: must fault
print("\n DACR enforcement by the emulator:")
print(" domain1=manager -> %s (positive control)" % ("read" if control else "FAULT"))
print(" domain1=no-access -> %s" % ("read" if noaccess else "fault"))
print(" domain1=client AP=3 -> %s" % ("read" if client_ok else "fault"))
print(" domain1=client AP=0 -> %s" % ("read" if client_deny else "fault"))
if not control:
return None # cannot discriminate
return (not noaccess) and client_ok and (not client_deny)
def dacr_live_in_boot():
"""Do sOS's own DACR writes actually execute in a booted system?"""
import collections
import importlib.util
from unicorn import UC_HOOK_CODE
here = os.path.dirname(os.path.abspath(__file__))
spec = importlib.util.spec_from_file_location("bmg", os.path.join(here, "boot_and_mailbox.py"))
BM = importlib.util.module_from_spec(spec); spec.loader.exec_module(BM)
c, _ccp, irqs, _exc = BM.build()
run, _ = BM.M.make_det_runner(c, irqs)
hits = collections.Counter()
for s in DACR_SITES:
c.uc.hook_add(UC_HOOK_CODE,
(lambda a_: (lambda u, a, sz, x: hits.update([a_])))(s), begin=s, end=s)
c.uc.ctl_flush_tb()
for _ in range(8):
run(200_000)
if sum(hits.values()) > 2000:
break
print("\n sOS DACR writes executed during boot:")
for s in DACR_SITES:
print(" %#08x : %d" % (s, hits[s]))
return sum(hits.values())
def scheduler_live_in_boot():
"""Is dispatch actually asynchronous, or does everything run on one stack?
Component-level harnesses are synchronous by construction -- there is no sOS.
The full-system harnesses run sOS's own scheduler, so rather than assume
either way, count task creation, reschedules, and the number of distinct
stacks in play. Several busy stacks means real context switching.
"""
import collections
import importlib.util
from unicorn import UC_HOOK_CODE, UC_HOOK_BLOCK
from unicorn.arm_const import UC_ARM_REG_SP
here = os.path.dirname(os.path.abspath(__file__))
spec = importlib.util.spec_from_file_location("bms", os.path.join(here, "boot_and_mailbox.py"))
BM = importlib.util.module_from_spec(spec); spec.loader.exec_module(BM)
c, _ccp, irqs, _exc = BM.build()
run, _ = BM.M.make_det_runner(c, irqs)
sites = {0x186C: "sos_sched_age_tasks", 0x1DEC: "sos_task_create",
0x4DC4: "svc_60_reschedule", 0x587C: "sos_svc_dispatch"}
hits = collections.Counter(); sps = collections.Counter()
for a, n in sites.items():
c.uc.hook_add(UC_HOOK_CODE,
(lambda n_: (lambda u, ad, sz, x: hits.update([n_])))(n), begin=a, end=a)
c.uc.hook_add(UC_HOOK_BLOCK, lambda u, a, s, x: sps.update([u.reg_read(UC_ARM_REG_SP) >> 12]))
c.uc.ctl_flush_tb()
for _ in range(10):
run(300_000)
busy = [p for p, n in sps.items() if n > 1000]
print("\n sOS scheduler during boot:")
for n in sites.values():
print(" %-22s %d" % (n, hits[n]))
print(" distinct stacks (SP>>12) : %d (%d with >1000 blocks)"
% (len(sps), len(busy)))
return hits["sos_task_create"], hits["svc_60_reschedule"], len(busy)
def live_gate_check():
"""The model is worthless if it is not actually enforced. Drive a real TA's
RPC gate with in- and out-of-window request pointers and require that the
service runs only for the valid one."""
import importlib.util
from unicorn.arm_const import UC_ARM_REG_R0, UC_ARM_REG_R1
from pspemu import services
here = os.path.dirname(os.path.abspath(__file__))
spec = importlib.util.spec_from_file_location("h0", os.path.join(here, "hdcp_cmd0f.py"))
H0 = importlib.util.module_from_spec(spec); spec.loader.exec_module(H0)
c, table = H0.setup()
slot, _s = H0.open_slot(c, table)
H0.invoke(c, H0.build_req(c, slot, 40))
real_rejects = len(c.gate_rejects)
hits = []
g = services.make_rpc_gate({1: lambda comp, r: (hits.append(r), 0)[1]})
outcomes = []
for probe in (0x1000, 0x1FFFFF, 0x10000001, 0x400000):
c.uc.reg_write(UC_ARM_REG_R0, 1)
c.uc.reg_write(UC_ARM_REG_R1, probe)
outcomes.append((probe, g(c, 0xF2)))
print("\n gate live in the RPC path:")
print(" real HDCP invoke rejected %d of its own requests (expect 0)" % real_rejects)
for p, rv in outcomes:
print(" req ptr %#010x -> %#x %s" % (p, rv, "rejected" if rv == gate.GATE_BAD_PTR else "dispatched"))
bad_rejected = all(rv == gate.GATE_BAD_PTR for p, rv in outcomes[:3])
good_ran = outcomes[3][1] == 0 and 0x400000 in hits
return real_rejects == 0 and bad_rejected and good_ran
def main():
c = Component("sos")
type4, other = proc_ids_by_type(c)
print("sOS gate differential -- model vs firmware")
print(" proc id with type==4 : %s" % (hex(type4) if type4 is not None else "none found"))
print(" proc id with type!=4 : %s" % (hex(other) if other is not None else "none found"))
if type4 is None or other is None:
print("\n Could not find both process classes; the type-4 branch would go")
print(" untested and the differential would be vacuous.")
print("RESULT NOT REPORTABLE")
return 2
cases = []
for pid, ptype in ((type4, 4), (other, 0)):
for p in ptr_vectors():
cases.append(("ptr", pid, ptype, p, 0))
for b, l in range_vectors():
cases.append(("range", pid, ptype, b, l))
mismatches = []
for kind, pid, ptype, a, b in cases:
if kind == "ptr":
fw = c.run_function(CHECK_PTR, (pid, a, 0, 0))
me = gate.check_ptr(a, ptype)
else:
fw = c.run_function(CHECK_RANGE, (pid, a, b, 0))
me = gate.check_range(a, b, ptype)
if fw != me:
mismatches.append((kind, ptype, a, b, fw, me))
print(" cases compared : %d (%d ptr, %d range)"
% (len(cases), sum(1 for x in cases if x[0] == "ptr"),
sum(1 for x in cases if x[0] == "range")))
print(" mismatches : %d" % len(mismatches))
for kind, ptype, a, b, fw, me in mismatches[:10]:
print(" %-5s type=%d a=%#010x b=%#010x firmware=%#x model=%#x"
% (kind, ptype, a, b, fw, me))
# positive control: a model that is wrong on purpose must be caught
caught = 0
for kind, pid, ptype, a, b in cases:
if kind != "ptr":
continue
fw = c.run_function(CHECK_PTR, (pid, a, 0, 0))
wrong = gate.GATE_OK # "everything is a valid pointer" -- the old behaviour
if fw != wrong:
caught += 1
print(" control (always-OK model, i.e. the old silent R0=0): %d/%d cases caught"
% (caught, sum(1 for x in cases if x[0] == "ptr")))
live = live_gate_check()
dacr_enf = dacr_enforced_by_emulator()
dacr_n = dacr_live_in_boot()
tasks, resched, busy_stacks = scheduler_live_in_boot()
svc_bad, svc_n, svc_denied = svc_permission_differential(Component("sos"))
svc_live = svc_gate_live()
print("\n summary")
print(" region validation : modelled, %d/%d cases match firmware"
% (len(cases) - len(mismatches), len(cases)))
print(" gate enforced : %s" % ("yes" if live else "NO"))
print(" DACR enforced by emulator : %s"
% {True: "yes", False: "no", None: "undetermined (control failed)"}[dacr_enf])
print(" DACR switches per boot : %d" % dacr_n)
print(" SVC permission : %d/%d match firmware, %d denials exercised"
% (svc_n - svc_bad, svc_n, svc_denied))
print(" SVC gate live : %s" % ("yes" if svc_live else "NO"))
print(" async dispatch : %d tasks, %d reschedules, %d busy stacks"
% (tasks, resched, busy_stacks))
print(" (full-system only; component-level harnesses are synchronous)")
if svc_bad or svc_denied == 0 or not svc_live:
print("\n The SVC permission gate does not match the firmware, denies")
print(" nothing, or is not enforced in the dispatcher.")
print("RESULT NOT REPORTABLE")
return 2
if not mismatches and caught > 0 and live and dacr_enf and dacr_n > 0 \
and tasks > 1 and busy_stacks > 1:
print("\n Model matches the firmware on every case, the differential")
print(" demonstrably rejects a wrong model, the gate is live in the RPC")
print(" path, the domain switch is enforced and actually exercised, and")
print(" dispatch is genuinely concurrent under sOS's own scheduler.")
return 0
if tasks <= 1 or busy_stacks <= 1:
print("\n Dispatch is running on a single stack: not concurrent.")
print("RESULT NOT REPORTABLE")
return 2
if dacr_enf is not True or dacr_n == 0:
print("\n Domain switching is not demonstrably in effect.")
print("RESULT NOT REPORTABLE")
return 2
if not live:
print("\n The gate is not actually enforced in the RPC path -- validated")
print(" but inert code proves nothing.")
print("RESULT NOT REPORTABLE")
return 2
if caught == 0:
print("\n The control was not caught: this differential cannot fail.")
print("RESULT NOT REPORTABLE")
return 2
print("\n Model disagrees with the firmware. Fix pspemu/gate.py.")
return 1
if __name__ == "__main__":
sys.exit(main())
|