aboutsummaryrefslogtreecommitdiffstats
path: root/psp_emu/pspemu/component.py
blob: 82398184ef634c85b41286a9d2e57d650880d6f5 (plain) (blame)
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
"""A single emulated PSP component (one TA / one address space)."""
import unicorn
from unicorn import Uc, UC_ARCH_ARM, UC_MODE_THUMB, UC_MODE_LITTLE_ENDIAN, UC_PROT_ALL
from unicorn import UC_HOOK_INTR, UC_HOOK_MEM_WRITE, UC_HOOK_BLOCK, UC_HOOK_MEM_INVALID
from unicorn.arm_const import (UC_ARM_REG_R0, UC_ARM_REG_R1, UC_ARM_REG_R2,
                               UC_ARM_REG_R3, UC_ARM_REG_SP, UC_ARM_REG_LR,
                               UC_ARM_REG_PC, UC_ARM_REG_CPSR)

from . import loader, memmap, svc as svcmod, isa
from .memmap import MAGIC_RET

ARGREGS = (UC_ARM_REG_R0, UC_ARM_REG_R1, UC_ARM_REG_R2, UC_ARM_REG_R3)


class Fault(Exception):
    def __init__(self, kind, addr, pc, detail=""):
        super().__init__(f"{kind} at {addr:#010x} (pc={pc:#010x}) {detail}")
        self.kind, self.addr, self.pc = kind, addr, pc


class Component:
    """Wraps a Unicorn instance with the PSP TA environment."""

    def __init__(self, name, image_path=None, config=None, root=None):
        self.name = name
        self.config = dict(config or {})
        self.cmap = memmap.MAPS[name]()
        self.uc = Uc(UC_ARCH_ARM, UC_MODE_THUMB | UC_MODE_LITTLE_ENDIAN)
        for r in self.cmap.regions:
            self.uc.mem_map(r.addr, r.size, UC_PROT_ALL)
        path = image_path or loader.resolve(name, root)
        self.image_path = path
        self.entry, self.placed = loader.load_image(self.uc, path, base=self.cmap.image_base)
        self._zero_signature_tail()

        # TRNG source (SVC 0xA2). Seedable so canary-dependent tests reproduce.
        import random as _random
        self._trng = _random.Random(self.config.get("trng_seed", 0xA5D_1DEA))
        self.canary = None
        self.canary_addr = None
        if self.config.get("randomize_canary", True):
            self._randomize_canary()

        # Real hardware does NOT zero the stack/scratch between calls, so
        # uninitialised reads return stale data (that is exactly how the ASD
        # 0x202 canary leak and the bl_derive_key kernel-stack leak disclose
        # secrets). Unicorn zero-fills mapped memory, hiding those. Opt in to a
        # non-zero fill so uninitialised-read disclosures show up instead of
        # silently reading 0. Default None = zero (unchanged behaviour/tests).
        fill = self.config.get("stale_fill", None)
        if fill is not None:
            self._prefill_scratch_stack(fill)

        self._scratch_ptr = self.cmap.scratch
        self.faults = []
        self.rpc_log = []
        # Gate bookkeeping: requests the modelled sOS region check rejected, and
        # calls to a destination we do not model. Both used to be silent.
        self.gate_rejects = []
        self.gate_unknown_dest = []

        self.svc = svcmod.SvcDispatcher(self)
        svcmod.install_defaults(self.svc)
        self.uc.hook_add(UC_HOOK_INTR, self.svc.hook)
        self.uc.hook_add(UC_HOOK_MEM_INVALID, self._on_invalid)

        self.tracer = None
        self._trace_handle = None
        self.mode_overrides = dict(self.config.get("mode_overrides", {}))
        self._mode_cache = {}
        self._mode_map = None

    def _zero_signature_tail(self):
        """Zero everything from the TA header's BSS base to the end of the image.

        The *_code.bin blobs end with the 256-byte RSA signature (body is
        $PS1.size, file is size+0x100), and the TA header field +0x1c is the BSS
        base, which lands exactly on that tail. Loading it verbatim maps
        high-entropy signature bytes where zeroed BSS belongs -- they then
        masquerade as initialised data. Found by fuzzing: ASD sub_D02794 loads a
        "function pointer" from 0xD330C8 (inside ASD's signature tail), passes
        its `CBZ` null guard, and BLXes to 0x6de4a430.
        """
        base, size = self.placed[0]
        try:
            bss = self.rd32(base + 0x1C)
        except Exception:
            return
        end = base + size
        if base < bss < end:
            self.uc.mem_write(bss, b"\x00" * (end - bss))
            self.sig_tail = (bss, end)
        else:
            self.sig_tail = None

    def trng_word(self):
        """One CCP TRNG word (SVC 0xA2). Fresh each call, seedable for repro."""
        return self._trng.getrandbits(32)

    def _prefill_scratch_stack(self, fill):
        """Fill stack + scratch with a recognisable byte so uninitialised reads
        are visible (models hardware not zeroing DRAM between calls)."""
        b = bytes([fill & 0xFF]) if isinstance(fill, int) else bytes(fill)
        for r in self.cmap.regions:
            if r.name in ("stack", "scratch"):
                self.uc.mem_write(r.addr, (b * (r.size // len(b) + 1))[:r.size])

    def _randomize_canary(self):
        """Model bl_load_ta_image: write a per-load TRNG word to __stack_chk_guard.

        The TA header field at image_base+0x20 holds the VA of __stack_chk_guard
        (0 => the image has no stack protector). On real hardware the loader reads
        one SVC 0xA2 word and stores it there; the shipped image only carries a
        build-time placeholder (0x33333333). Without this, emulated canary
        overflows pass with the placeholder and canary-leak PoCs read a constant
        instead of the runtime-random guard -- the exact emulator/hardware gap
        noted in VULN-ASD-202-CANARY-LEAK.md.
        """
        base = self.cmap.image_base
        try:
            guard_va = self.rd32(base + 0x20)
        except Exception:
            return
        # plausibility: a VA inside this image's mapped space
        img_lo = self.placed[0][0]
        img_hi = img_lo + self.placed[0][1]
        if not (img_lo <= guard_va < img_hi):
            return
        self.canary = self.trng_word()
        self.canary_addr = guard_va
        self.wr32(guard_va, self.canary)

    # ------------------------------------------------------------- memory I/O
    def rd32(self, a): return int.from_bytes(self.uc.mem_read(a, 4), "little")
    def wr32(self, a, v): self.uc.mem_write(a, int(v & 0xFFFFFFFF).to_bytes(4, "little"))
    def rd8(self, a): return self.uc.mem_read(a, 1)[0]
    def wr8(self, a, v): self.uc.mem_write(a, bytes([v & 0xFF]))
    def read(self, a, n): return bytes(self.uc.mem_read(a, n))
    def write(self, a, b): self.uc.mem_write(a, bytes(b))

    def alloc(self, size, align=16, fill=b"\x00"):
        p = (self._scratch_ptr + align - 1) & ~(align - 1)
        end = p + size
        limit = self.cmap.scratch + self.cmap.scratch_size
        if end > limit:
            raise MemoryError("scratch exhausted")
        self._scratch_ptr = end
        if fill:
            self.uc.mem_write(p, (fill * ((size // len(fill)) + 1))[:size])
        return p

    # ---------------------------------------------------------------- tracing
    def trace_writes(self, ranges=None, limit=200000):
        from .trace import WriteTracer
        self.tracer = WriteTracer(ranges, limit)
        self._trace_handle = self.uc.hook_add(UC_HOOK_MEM_WRITE, self.tracer.hook)
        return self.tracer

    def stop_trace(self):
        if self._trace_handle is not None:
            self.uc.hook_del(self._trace_handle)
            self._trace_handle = None

    def add_watch(self, wp):
        return self.uc.hook_add(UC_HOOK_MEM_WRITE, wp.hook)

    # ------------------------------------------------------------- exec hooks
    def _on_invalid(self, uc, access, address, size, value, user):
        pc = uc.reg_read(UC_ARM_REG_PC)
        kind = {unicorn.UC_MEM_READ_UNMAPPED: "READ_UNMAPPED",
                unicorn.UC_MEM_WRITE_UNMAPPED: "WRITE_UNMAPPED",
                unicorn.UC_MEM_FETCH_UNMAPPED: "FETCH_UNMAPPED"}.get(access, str(access))
        self.faults.append(dict(kind=kind, addr=address, size=size, pc=pc))
        return False        # stop emulation

    # ------------------------------------------------------------ calling ABI
    @property
    def mode_map(self):
        """Call-site-derived {addr: (is_thumb, thumb_votes, arm_votes)}."""
        if self._mode_map is None:
            base, size = self.placed[0]
            self._mode_map = isa.build_mode_map(self.read(base, size), base)
        return self._mode_map

    def mode_of(self, addr):
        """True = Thumb, False = ARM.

        Priority: explicit override > call-site votes (BL/BLX, authoritative)
        > byte heuristic. IDA's `T` segment register is NOT used: it is wrong
        on these images (e.g. HDCP ta_memcpy @0x401058 is ARM but marked T=1).
        """
        a = addr & ~1
        if a in self.mode_overrides:
            return self.mode_overrides[a]
        if a in self._mode_cache:
            return self._mode_cache[a]
        voted = self.mode_map.get(a)
        if voted is not None and (voted[1] or voted[2]):
            thumb = voted[0]
        else:
            thumb, _ = isa.guess_mode(self.read(a, 32), a)
        self._mode_cache[a] = thumb
        return thumb

    def run_function(self, addr, args=(), stack_args=(), timeout=0, count=0,
                     sp=None, clear_faults=True, thumb=None):
        """Call a function with AAPCS args; returns R0.

        `thumb` defaults to byte-based detection (see mode_of).
        Raises Fault if emulation stopped on an invalid access.
        """
        uc = self.uc
        if clear_faults:
            self.faults = []
        if thumb is None:
            thumb = self.mode_of(addr)
        sp = sp if sp is not None else (self.cmap.stack_top - 0x400)
        sp &= ~7
        if stack_args:
            sp -= 4 * len(stack_args)
            sp &= ~7
            for i, v in enumerate(stack_args):
                self.wr32(sp + 4 * i, v)
        uc.reg_write(UC_ARM_REG_SP, sp)
        for i, v in enumerate(args[:4]):
            uc.reg_write(ARGREGS[i], v & 0xFFFFFFFF)
        uc.reg_write(UC_ARM_REG_LR, MAGIC_RET | 1)
        cpsr = uc.reg_read(UC_ARM_REG_CPSR)
        uc.reg_write(UC_ARM_REG_CPSR, (cpsr | (1 << 5)) if thumb else (cpsr & ~(1 << 5)))
        begin = (addr | 1) if thumb else (addr & ~1)
        try:
            uc.emu_start(begin, MAGIC_RET, timeout=timeout, count=count)
        except unicorn.UcError as e:
            if self.faults:
                f = self.faults[-1]
                raise Fault(f["kind"], f["addr"], f["pc"], str(e))
            raise
        if self.faults:
            f = self.faults[-1]
            raise Fault(f["kind"], f["addr"], f["pc"])
        return uc.reg_read(UC_ARM_REG_R0)

    # -------------------------------------------------------------- utilities
    def set_rpc_services(self, services):
        from .services import make_rpc_gate
        from . import consts
        self.svc.register(consts.SVC_RPC_GATE, make_rpc_gate(services))

    def disasm(self, addr, n=16):
        import capstone
        md = capstone.Cs(capstone.CS_ARCH_ARM, capstone.CS_MODE_THUMB)
        out = []
        for ins in md.disasm(self.read(addr, n * 4), addr, n):
            out.append(f"{ins.address:#010x}  {ins.mnemonic:<8} {ins.op_str}")
        return "\n".join(out)

    def __repr__(self):
        return f"<Component {self.name} image={self.image_path} entry={self.entry:#x}>"