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
|
"""Emulated PSP services reachable over the SVC 0xF2 RPC gate.
These stand in for code that lives in sOS / secure SRAM and is therefore not
present in any image we can disassemble. Each service is deliberately
*configurable* so a harness can model both the correct behaviour and the
buggy behaviour observed on hardware (e.g. the crypto MAC writing more than
32 bytes into its destination on an uninitialised context).
"""
import hashlib
import struct
from . import consts
class CryptoService:
"""Service id 1.
Opcodes seen from HDCP:
0x30 init (a=req[0x38], b=req[0x3C]) -> ctx handle in req[0x40]
0x31 free (handle=req[0x38])
0x33 setkey (req[0x08]=key, req[0x0C]=12*n, handle=req[0x38])
0x10 mac (req[0x08]=buf, req[0x0C]=len, req[0x10]=dst, handle=req[0x38])
``overrun_uninitialised`` models the hardware bug: on the first MAC call
for a context that never saw a setkey, the service writes ``len`` bytes to
``dst`` instead of 32, smashing the caller's stack canary.
"""
def __init__(self, overrun_uninitialised=True, mac_len=32):
self.overrun_uninitialised = overrun_uninitialised
self.mac_len = mac_len
self.contexts = {}
self.next_handle = 0x1000
self.calls = []
# ---------------------------------------------------------------- helpers
def _mac(self, data, key=b""):
return hashlib.sha256(key + data).digest()
# --------------------------------------------------------------- dispatch
def __call__(self, comp, req_ptr):
op = comp.rd32(req_ptr + consts.CRYPTO_REQ_OPCODE)
handle = comp.rd32(req_ptr + consts.CRYPTO_REQ_HANDLE)
self.calls.append((op, handle))
if op == consts.CRYPTO_OP_INIT:
h = self.next_handle
self.next_handle += 1
self.contexts[h] = dict(keyed=False, key=b"")
comp.wr32(req_ptr + consts.CRYPTO_REQ_OUTH, h)
return 0
if op == consts.CRYPTO_OP_FREE:
self.contexts.pop(handle, None)
return 0
if op == consts.CRYPTO_OP_SETKEY:
key_ptr = comp.rd32(req_ptr + consts.CRYPTO_REQ_ARG0)
key_len = comp.rd32(req_ptr + consts.CRYPTO_REQ_ARG1)
ctx = self.contexts.setdefault(handle, dict(keyed=False, key=b""))
try:
ctx["key"] = bytes(comp.uc.mem_read(key_ptr, min(key_len, 0x200))) if key_ptr else b""
except Exception:
ctx["key"] = b""
ctx["keyed"] = True
return 0
if op == consts.CRYPTO_OP_MAC:
buf = comp.rd32(req_ptr + consts.CRYPTO_REQ_ARG0)
ln = comp.rd32(req_ptr + consts.CRYPTO_REQ_ARG1)
dst = comp.rd32(req_ptr + consts.CRYPTO_REQ_ARG2)
ctx = self.contexts.get(handle, dict(keyed=False, key=b""))
data = bytes(comp.uc.mem_read(buf, min(ln, 0x4000))) if buf and ln else b""
digest = self._mac(data, ctx.get("key", b""))
if dst:
if self.overrun_uninitialised and not ctx.get("keyed"):
# hardware-observed bug: writes len bytes, not 32
blob = (digest * ((ln // 32) + 2))[:max(ln, self.mac_len)]
comp.uc.mem_write(dst, blob)
else:
comp.uc.mem_write(dst, digest[: self.mac_len])
return 0
return 0
class AsdRpcService:
"""Service id 2: forwards a request tuple to the ASD component.
Request struct built by the HDCP thunks (STM {R0,R4-R7}):
req[0]=asd_cmd, req[4]=a1, req[8]=a2, req[0xC]=a3, req[0x10]=a4
In "stub" mode every verb simply succeeds, which is what a freshly
provisioned card does for the verbs subcmd12 touches.
"""
def __init__(self, bus=None, stub_status=0, per_cmd=None):
self.bus = bus
self.stub_status = stub_status
self.per_cmd = dict(per_cmd or {})
self.calls = []
def __call__(self, comp, req_ptr):
cmd = comp.rd32(req_ptr + 0)
args = [comp.rd32(req_ptr + 4 * (i + 1)) for i in range(4)]
self.calls.append((cmd, args))
if cmd in self.per_cmd:
return self.per_cmd[cmd]
if self.bus is not None:
return self.bus.route_asd(cmd, args, caller=comp)
return self.stub_status
def make_rpc_gate(services):
"""Build the SVC 0xF2 handler. ``services`` maps dest-id -> callable.
The real gate validates the caller's request pointer before touching it
(`sos_check_user_ptr`, FA 0x178C). That check is modelled in `pspemu.gate`
and validated against the firmware by `harness/sos_gate.py`; it is applied
here so a request pointer outside the user window is rejected with the
firmware's own 0xA instead of being dereferenced as if valid.
Set config['gate'] = False to restore the old unvalidated behaviour, and
config['proc_type'] = 4 to model a privileged caller (for which sOS's and
SYS_DRV's own windows are additionally off-limits).
"""
def handler(comp, num):
from unicorn.arm_const import UC_ARM_REG_R0, UC_ARM_REG_R1
from . import gate as _gate
dest = comp.uc.reg_read(UC_ARM_REG_R0)
req = comp.uc.reg_read(UC_ARM_REG_R1)
# Validate BEFORE dereferencing. The logging below reads the request
# word, which is itself a dereference of a caller-supplied pointer, so
# it has to sit after the check -- the real gate does not touch the
# request until sos_check_user_ptr has passed it either.
if comp.config.get("gate", True):
st = _gate.check_ptr(req, comp.config.get("proc_type", 0))
if st != _gate.GATE_OK:
comp.gate_rejects.append((dest, req))
comp.rpc_log.append((dest, req, None))
return st
# The gate validates the address RANGE, not whether the page is mapped;
# a gate-valid but unmapped pointer is an MMU fault on hardware. This is
# harness bookkeeping, so it must not turn that into a crash -- the
# service's own dereference below still faults and gets recorded.
word = None
if req:
try:
word = comp.rd32(req)
except Exception:
word = None
comp.rpc_log.append((dest, req, word))
svc = services.get(dest)
if svc is None:
# Not modelled as an error because the real status for an unknown
# destination has not been measured. Counted rather than silently
# returning 0, so it cannot pass for a successful call.
comp.gate_unknown_dest.append((dest, req))
return 0
return svc(comp, req)
return handler
# ---------------------------------------------- sOS SVCs measured from a boot
#
# These four SVCs used to fall through SvcDispatcher's silent R0=0 default, and
# psp_out/FINDING-ASD-SVC-STUBS-LOAD-BEARING.md showed three of them are
# load-bearing: driving any one to a failure moves ASD coverage by up to 48%.
#
# Rather than guess, the real values were measured by watching sos_svc_dispatch
# in harness/full_system.py, where ASD's SVCs are serviced by the actual sOS:
#
# svc 0x51 -> 1, 2, 3, 4, ... strictly increasing, 18 calls, no reuse
# svc 0x5D -> 0, 1, 2, 3, ... strictly increasing, 39 calls, no reuse
# svc 0x57 -> 0 (3 calls)
# svc 0xB4 -> 0 (1 call)
#
# So 0x51 and 0x5D are sequential handle allocators and the old 0 was wrong for
# both: it handed every caller the same handle, and for 0x51 a handle the real
# kernel never returns. 0x57 and 0xB4 really do return 0 -- now on evidence
# rather than by default.
#
# The observed call counts are small, so this is the behaviour over one boot,
# not proof of the allocator's policy at exhaustion or after a free.
SOS_SVC_MEASURED_ZERO = (0x57, 0xB4)
SOS_SVC_ALLOCATOR_START = {0x51: 1, 0x5D: 0}
def make_seq_allocator(start):
"""Model a sequential sOS handle allocator, as measured from a real boot."""
state = {"next": start}
def handler(comp, num):
h = state["next"]
state["next"] = h + 1
return h
return handler
def register_measured_sos_svcs(comp):
"""Install the measured models for the four SVCs ASD issues unmodelled."""
for svc, start in SOS_SVC_ALLOCATOR_START.items():
comp.svc.register(svc, make_seq_allocator(start))
for svc in SOS_SVC_MEASURED_ZERO:
comp.svc.register(svc, lambda c, n: 0)
|