aboutsummaryrefslogtreecommitdiffstats
path: root/fw/ta_capacity_audit.py
blob: f8b0f0dc8bd6218456468ee5de297012c32508a5 (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
259
260
261
262
263
264
265
266
267
268
#!/usr/bin/env python3
"""Compare a copy's MAXIMUM POSSIBLE length against the destination's capacity.

Twelve passes established that "is the length compared?" is the wrong question here. Most
lengths come from byte or halfword fields, so they are type-bounded (255 / 65535) whether or
not anyone compares them, and what decides safety is:

        max_possible_length x scaling   vs   destination capacity

Both sides are recoverable for stack destinations:

  * max length: trace the length register back; `ldrb` -> 255, `ldrh` -> 65535,
    an explicit `cmp rX,#C` -> C, and accumulate scaling from `lsl #n` and the
    `add rD, rA, rA, lsl #n` idiom (which is x(1+2^n), e.g. x5)
  * capacity: destination is `sp` or `sp+k` and the frame is `sub sp,#F`, so capacity = F - k

This is exactly the arithmetic that makes the two known cases differ, which is why they serve
as controls in opposite directions:

  POSITIVE  hdcp `0x402cde`  byte(255) x5 = 1275 into a 232-byte stack buffer  -> MUST fire
  NEGATIVE  xgmi `0x402d4c`  count(<=64) x16 = 1024 into a 1024-byte buffer    -> MUST NOT fire

Usage:
  ./ta_capacity_audit.py --selftest
  ./ta_capacity_audit.py --all
"""
from __future__ import annotations

import argparse
import json
import re
from pathlib import Path

import capstone as cs

HERE = Path(__file__).resolve().parent
REPO = HERE.parent
THUMB = cs.Cs(cs.CS_ARCH_ARM, cs.CS_MODE_THUMB)
ARM = cs.Cs(cs.CS_ARCH_ARM, cs.CS_MODE_ARM)
CACHE = HERE / "audits" / "fnbounds.json"
MODULES = {"hdcp": ("psp_out/hdcp_code.bin", 0x400100),
           "sys_drv": ("psp_out/sys_drv_code.bin", 0xE00100),
           "asd": ("psp_out/asd_code.bin", 0xD00100)}
TAS = ["gcp", "opm", "xgmi", "merit", "fp", "auc", "powerplay", "wspe", "rap", "oc",
       "csu", "tmz"]


def load(name):
    if name in MODULES:
        bp, base = MODULES[name]
        return (REPO / bp).read_bytes(), base, json.loads(CACHE.read_text())[name]
    meta = json.loads((HERE / "syms" / ("%s.meta.json" % name)).read_text())
    p = Path(meta["path"])
    b = (p if p.is_absolute() else REPO / p).read_bytes()
    fns = [[f["ea"], f.get("size", 0)]
           for f in json.loads((HERE / "libdumps" / ("%s.json" % name)).read_text())
           if f.get("size", 0) > 0]
    return b, 0x400100, fns


def helpers(b, base, fns):
    tg = set()
    for ea, sz in fns:
        o = ea - base
        if o < 0 or o + sz > len(b):
            continue
        for i in THUMB.disasm(b[o:o + sz], ea):
            if i.mnemonic == "blx" and (i.op_str or "").startswith("#"):
                tg.add(int(i.op_str[1:], 16))
    out = set()
    for t in tg:
        o = t - base
        if not (0 <= o < len(b) - 16):
            continue
        a = list(ARM.disasm(b[o:o + 0x60], t))
        if any(x.mnemonic.startswith(("cdp", "mcr", "mrc", "stc", "ldc")) for x in a):
            continue
        if any(x.mnemonic.startswith(("ldr", "ldm")) for x in a) and \
           any(x.mnemonic.startswith(("str", "stm")) for x in a):
            out.add(t)
    return out


def max_len(ins, lo, at, reg):
    """(max value, description) for reg at index `at`, following scaling."""
    cur, scale, desc = reg, 1, []
    for _ in range(8):
        # A compare is only a BOUND if it constrains the magnitude: `cmp reg,#0` is a null
        # test, and taking it as a bound returned max=0 and silently suppressed HDCP's
        # overflow. So look for the definition first and use a compare only to tighten.
        cap_from_cmp = None
        for k in range(at - 1, lo - 1, -1):
            i = ins[k]
            if i.mnemonic.startswith("cmp"):
                m = re.match(r"(%s),\s*#(0x[0-9a-f]+|\d+)$" % re.escape(cur), i.op_str or "")
                if m and int(m.group(2), 0) > 0:
                    cap_from_cmp = int(m.group(2), 0)
                    break
        for k in range(at - 1, lo - 1, -1):
            i = ins[k]
            m = re.match(r"(%s),\s*(.+)$" % re.escape(cur), i.op_str or "")
            if not m or i.mnemonic.startswith(("cmp", "str", "push", "tst", "b")):
                continue
            rhs = m.group(2).strip()
            if i.mnemonic.startswith("ldrb"):
                v = min(0xFF, cap_from_cmp) if cap_from_cmp else 0xFF
                return v * scale, "byte(max %d) x%d" % (v, scale)
            if i.mnemonic.startswith("ldrh"):
                v = min(0xFFFF, cap_from_cmp) if cap_from_cmp else 0xFFFF
                return v * scale, "half(max %d) x%d" % (v, scale)
            if i.mnemonic.startswith("ldr"):
                return None, "word x%d" % scale      # unknown width: not decidable here
            mi = re.fullmatch(r"#(0x[0-9a-f]+|\d+)", rhs)
            if mi:
                v = int(mi.group(1), 0)
                # a literal that looks like a code/data address is not a length: the SYS_DRV
                # false positive reported "max 14779680" (= 0xE1A0E0, an address)
                if v >= 0x100000:
                    return None, "address-like literal"
                return v * scale, "imm x%d" % scale
            # x(1+2^n): add rD, rA, rA, lsl #n
            m5 = re.match(r"(r\d+|sb|sl|ip),\s*(r\d+|sb|sl|ip),\s*lsl\s*#(\d+)$", rhs)
            if m5 and i.mnemonic.startswith("add") and m5.group(1) == m5.group(2):
                scale *= (1 + (1 << int(m5.group(3))))
                cur, at = m5.group(1), k
                break
            msh = re.match(r"(r\d+|sb|sl|ip),\s*#(\d+)$", rhs)
            if msh and i.mnemonic.startswith("lsl"):
                scale *= (1 << int(msh.group(2)))
                cur, at = msh.group(1), k
                break
            mmv = re.fullmatch(r"(r\d+|sb|sl|fp|ip)", rhs)
            if mmv:
                cur, at = mmv.group(1), k
                break
            return None, "expr x%d" % scale
        else:
            return None, "unresolved"
    return None, "deep"


def capacity(ins, lo, at, frame):
    """If the destination (r0) is sp or sp+k, capacity = frame - k."""
    cur = "r0"
    for _ in range(6):
        for k in range(at - 1, lo - 1, -1):
            i = ins[k]
            m = re.match(r"(%s),\s*(.+)$" % re.escape(cur), i.op_str or "")
            if not m or i.mnemonic.startswith(("cmp", "str", "push", "tst", "b")):
                continue
            rhs = m.group(2).strip()
            if rhs == "sp":
                return frame, 0
            ms = re.match(r"sp,\s*#(0x[0-9a-f]+|\d+)$", rhs)
            if ms and i.mnemonic.startswith("add"):
                k2 = int(ms.group(1), 0)
                return frame - k2, k2
            mm = re.fullmatch(r"(r\d+|sb|sl|fp|ip)", rhs)
            if mm:
                cur, at = mm.group(1), k
                break
            return None, None
        else:
            return None, None
    return None, None


def split_merged(b, base, fns):
    """Split IDA-merged extents at interior prologues.

    IDA merged OPM's cmd-8 handler (0x401320) into 0x4012c0, so a copy in the second function
    was measured against the FIRST function's frame. That produced a false positive here, but
    the same error in the other direction -- picking a larger frame than the real one -- would
    MASK a genuine overflow. So subdivide: an interior `push {...,lr}` followed within a few
    instructions by `sub sp` is a real function entry.
    """
    out = []
    for ea, sz in fns:
        o = ea - base
        if o < 0 or sz <= 0 or o + sz > len(b):
            continue
        ins = list(THUMB.disasm(b[o:o + sz], ea))
        cuts = [ea]
        for n, i in enumerate(ins):
            if i.address == ea or not i.mnemonic.startswith("push"):
                continue
            nxt = ins[n + 1:n + 4]
            if any(x.mnemonic in ("sub", "subw", "sub.w")
                   and re.match(r"sp,\s*(?:sp,\s*)?#", x.op_str or "") for x in nxt):
                cuts.append(i.address)
        cuts.append(ea + sz)
        for k in range(len(cuts) - 1):
            out.append([cuts[k], cuts[k + 1] - cuts[k]])
    return out


def analyse(name):
    b, base, fns = load(name)
    hp = helpers(b, base, fns)
    fns = split_merged(b, base, fns)
    out = []
    for ea, sz in fns:
        o = ea - base
        if o < 0 or sz <= 0 or o + sz > len(b):
            continue
        ins = list(THUMB.disasm(b[o:o + sz], ea))
        frame = None
        for i in ins[:8]:
            # `sub sp,#imm` AND `sub.w sp,sp,#imm` -- missing the second form left frame=None
            # for HDCP's `sub.w sp, sp, #0x214`, so the positive control never fired.
            m = re.match(r"sp,\s*(?:sp,\s*)?#(0x[0-9a-f]+|\d+)$", i.op_str or "")
            if m and i.mnemonic in ("sub", "subw", "sub.w"):
                frame = int(m.group(1), 0)
                break
        if frame is None:
            continue
        for n, i in enumerate(ins):
            if not (i.mnemonic in ("blx", "bl") and (i.op_str or "").startswith("#")):
                continue
            if int(i.op_str[1:], 16) not in hp:
                continue
            cap, koff = capacity(ins, 0, n, frame)
            if cap is None or cap <= 0:
                continue
            mx, how = max_len(ins, 0, n, "r2")
            if mx is None:
                continue
            if mx > cap:
                out.append((i.address, ea, mx, how, cap, koff))
    return out


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--selftest", action="store_true")
    ap.add_argument("--all", action="store_true")
    ap.add_argument("--module")
    a = ap.parse_args()

    if a.selftest:
        hd = analyse("hdcp")
        pos = [f for f in hd if f[0] == 0x402CDE]
        xg = analyse("xgmi")
        neg = [f for f in xg if f[0] == 0x402D4C]
        print("SELFTEST (max length vs destination capacity)")
        print("   POSITIVE hdcp 0x402cde fires:        %s" % ("yes" if pos else "NO"))
        if pos:
            print("      max %d (%s) into capacity %d" % (pos[0][2], pos[0][3], pos[0][4]))
        print("   NEGATIVE xgmi 0x402d4c does not fire: %s" % ("yes" if not neg else "NO"))
        ok = bool(pos) and not neg
        print("\nverdict: %s" % ("TRUSTWORTHY" if ok else "NOT trustworthy"))
        return 0 if ok else 1

    for m in (TAS + ["asd", "sys_drv"] if a.all else [a.module]):
        try:
            res = analyse(m)
        except Exception as exc:  # noqa: BLE001
            print("%-10s SKIP (%s)" % (m, str(exc)[:50]))
            continue
        print("%-10s %d site(s)%s" % (m, len(res), ":" if res else ""))
        for site, fn, mx, how, cap, koff in res:
            print("     copy @%#x (fn %#x) max %d (%s) > capacity %d (sp+%#x)"
                  % (site, fn, mx, how, cap, koff))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())