aboutsummaryrefslogtreecommitdiffstats
path: root/dmcub/dmcub_emu_dpaux.py
blob: ad3c4e975035a83e382d23739e7aed2d8d1d5b61 (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
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
#!/usr/bin/env python3
"""Emulate the DPIA `DP_AUX_ACCESS` (type 70) handler to confirm FINDING-11.

This is step 1 of `AUDIT-DMCUB-07-DPAUX.md` "Next": the static claim is that
`0x6001e62c` computes `base + 0x%x + instance` with stride 1 and stores a
host-controlled byte there, before the only bounds check on the path. That is
cheap to *execute* rather than argue about -- the function is 128 bytes, the
memory model is flat, and the base pointer comes out of the image itself.

Scope, deliberately small: a tiny Xtensa windowed-ABI interpreter covering only
the 30 opcodes these three functions use. Anything else raises `Unsupported`
rather than being skipped, because an interpreter that silently ignores an
instruction would manufacture exactly the result we are trying to test.

Emulated for real: 0x6001e770 (entry), 0x6001e62c (the writer), 0x6001e970 (the
bounds-checked sibling). Every other call is stubbed, returns 0, and is logged.

    /home/user/.venvs/cs6/bin/python dmcub_emu_dpaux.py --selftest
    /home/user/.venvs/cs6/bin/python dmcub_emu_dpaux.py --image fw/dcn_3_5_dmcub.bin
"""
import argparse
import os
import sys

import dmcub_dis as dis

HERE = os.path.dirname(os.path.abspath(__file__))

# Per-image: entry handler, writer, bounded sibling, and the expected array.
TARGETS = {
    # gate/slot: the sibling's feature flag and its per-instance word. Both are
    # zero in a cold model, so the sibling bails *before* its `instance < 4`
    # bound; seeding them is the only way to exercise that bound.
    'dcn_3_5': dict(entry=0x6001e770, writer=0x6001e62c, sibling=0x6001e970,
                    array=0xa7b0, neighbour=0xa7b8, gate=0xa56c, slot=0xa57c),
    'dcn_3_6': dict(entry=0x6001e7a0, writer=0x6001e65c, sibling=0x6001e9a0,
                    array=0xb0a0, neighbour=0xb0a8, gate=0xae5c, slot=0xae6c),
}

FRAME = 0x66100000          # where we place the 64-byte command frame
STACK = 0x67000000          # separate region so stack traffic is distinguishable
DATA_LO, DATA_HI = 0x66000000, 0x66020000


class Unsupported(Exception):
    pass


def ops(x):
    return [p.strip() for p in x.op_str.split(',')]


def reg(tok):
    if not tok.startswith('a'):
        raise Unsupported('not a register: %r' % tok)
    return int(tok[1:])


def imm(tok):
    return int(tok, 0)


class Mem:
    """Flat memory: firmware image read-only, plus tracked overlay regions."""

    def __init__(self, analysis):
        self.a = analysis
        self.img_lo = analysis.img.base
        self.img_hi = self.img_lo + len(analysis.img.payload)
        self.over = {}
        self.writes = []        # (addr, size, value, region, clock)
        self.wild = []
        self.clock = lambda: 0   # set to len(cpu.trace) so writes can be ordered

    def region(self, addr):
        if self.img_lo <= addr < self.img_hi:
            return 'image'
        if DATA_LO <= addr < DATA_HI:
            return 'data'
        if FRAME <= addr < FRAME + 0x40:
            return 'frame'
        if STACK - 0x4000 <= addr < STACK + 0x1000:
            return 'stack'
        return None

    def load(self, addr, size):
        r = self.region(addr)
        if r is None:
            self.wild.append(('read', addr, size))
            return 0
        if r == 'image' and addr not in self.over:
            v = 0
            for i in range(size):
                b = self.a.img.byte(addr + i) if hasattr(self.a.img, 'byte') else None
                if b is None:
                    off = addr + i - self.img_lo
                    b = self.a.img.payload[off] if 0 <= off < len(self.a.img.payload) else 0
                v |= b << (8 * i)
            return v
        v = 0
        for i in range(size):
            v |= self.over.get(addr + i, 0) << (8 * i)
        return v

    def store(self, addr, size, val):
        r = self.region(addr)
        if r is None:
            self.wild.append(('write', addr, size))
            return
        for i in range(size):
            self.over[addr + i] = (val >> (8 * i)) & 0xFF
        self.writes.append((addr, size, val & ((1 << (8 * size)) - 1), r, self.clock()))


class Cpu:
    def __init__(self, analysis, mem, emulate):
        self.a = analysis
        self.m = mem
        self.emulate = set(emulate)
        self.phys = [0] * 64
        self.wb = 0
        self.frames = []
        self.pending = None
        self.stubs = []
        self.trace = []
        self.ins = {}
        for f in self.emulate:
            for x in analysis.dis(f):
                self.ins[x.address] = x

    # windowed register file
    def get(self, i):
        return self.phys[(self.wb * 4 + i) % 64]

    def set(self, i, v):
        self.phys[(self.wb * 4 + i) % 64] = v & 0xFFFFFFFF

    def run(self, pc, max_steps=4000):
        steps = 0
        while True:
            steps += 1
            if steps > max_steps:
                raise Unsupported('step limit -- probable infinite loop at 0x%08x' % pc)
            x = self.ins.get(pc)
            if x is None:
                raise Unsupported('no instruction decoded at 0x%08x' % pc)
            self.trace.append(pc)
            nxt = self.step(x)
            if nxt == 'done':
                return
            pc = nxt

    def step(self, x):
        m, o = x.mnemonic, ops(x)
        nxt = x.address + x.size
        g, s = self.get, self.set

        def tgt():
            t = self.a.target(x)
            if t is None:
                raise Unsupported('unresolved target at 0x%08x (%s %s)'
                                  % (x.address, m, x.op_str))
            return t

        if m == 'entry':
            old_a1 = g(1)
            ret, inc = self.pending if self.pending else (None, 0)
            self.wb += inc
            self.frames.append(inc)
            s(1, old_a1 - imm(o[1]))
            if ret is not None:
                s(0, ret)
            self.pending = None
        elif m == 'l32r':
            s(reg(o[0]), self.a.lit(x))
        elif m in ('l32i', 'l32i.n'):
            s(reg(o[0]), self.m.load(g(reg(o[1])) + imm(o[2]), 4))
        elif m == 'l8ui':
            s(reg(o[0]), self.m.load(g(reg(o[1])) + imm(o[2]), 1))
        elif m == 's8i':
            self.m.store(g(reg(o[1])) + imm(o[2]), 1, g(reg(o[0])))
        elif m in ('s32i', 's32i.n'):
            self.m.store(g(reg(o[1])) + imm(o[2]), 4, g(reg(o[0])))
        elif m == 'add.n':
            s(reg(o[0]), g(reg(o[1])) + g(reg(o[2])))
        elif m in ('addi', 'addi.n', 'addmi'):
            v = imm(o[2])
            if v > 0x7FFFFFFF:
                v -= 1 << 32
            s(reg(o[0]), g(reg(o[1])) + v)
        elif m == 'addx4':
            s(reg(o[0]), (g(reg(o[1])) << 2) + g(reg(o[2])))
        elif m in ('movi', 'movi.n'):
            v = imm(o[1])
            s(reg(o[0]), v & 0xFFFFFFFF)
        elif m == 'mov.n':
            s(reg(o[0]), g(reg(o[1])))
        elif m == 'or':
            s(reg(o[0]), g(reg(o[1])) | g(reg(o[2])))
        elif m == 'and':
            s(reg(o[0]), g(reg(o[1])) & g(reg(o[2])))
        elif m == 'xor':
            s(reg(o[0]), g(reg(o[1])) ^ g(reg(o[2])))
        elif m == 'slli':
            s(reg(o[0]), (g(reg(o[1])) << imm(o[2])) & 0xFFFFFFFF)
        elif m == 'extui':
            s(reg(o[0]), (g(reg(o[1])) >> imm(o[2])) & ((1 << imm(o[3])) - 1))
        elif m == 'mul16s':
            def sx16(v):
                v &= 0xFFFF
                return v - 0x10000 if v & 0x8000 else v
            s(reg(o[0]), sx16(g(reg(o[1]))) * sx16(g(reg(o[2]))))
        elif m == 'moveqz':
            if g(reg(o[2])) == 0:
                s(reg(o[0]), g(reg(o[1])))
        elif m == 'movnez':
            if g(reg(o[2])) != 0:
                s(reg(o[0]), g(reg(o[1])))
        elif m in ('beqz', 'beqz.n'):
            return tgt() if g(reg(o[0])) == 0 else nxt
        elif m in ('bnez', 'bnez.n'):
            return tgt() if g(reg(o[0])) != 0 else nxt
        elif m == 'beqi':
            return tgt() if g(reg(o[0])) == imm(o[1]) else nxt
        elif m == 'bnei':
            return tgt() if g(reg(o[0])) != imm(o[1]) else nxt
        elif m == 'bgeui':
            return tgt() if g(reg(o[0])) >= imm(o[1]) else nxt
        elif m == 'bltui':
            return tgt() if g(reg(o[0])) < imm(o[1]) else nxt
        elif m == 'beq':
            return tgt() if g(reg(o[0])) == g(reg(o[1])) else nxt
        elif m == 'bne':
            return tgt() if g(reg(o[0])) != g(reg(o[1])) else nxt
        elif m == 'bgeu':
            return tgt() if g(reg(o[0])) >= g(reg(o[1])) else nxt
        elif m == 'bltu':
            return tgt() if g(reg(o[0])) < g(reg(o[1])) else nxt
        elif m == 'j':
            return tgt()
        elif m == 'call8':
            t = tgt()
            if t in self.emulate:
                self.pending = (nxt, 2)
                return t
            self.stubs.append((x.address, t))
            s(10, 0)
            return nxt
        elif m == 'callx8':
            self.stubs.append((x.address, g(reg(o[0]))))
            s(10, 0)
            return nxt
        elif m in ('retw', 'retw.n'):
            ret = g(0)
            inc = self.frames.pop() if self.frames else 0
            self.wb -= inc
            if not self.frames:
                return 'done'
            return ret
        elif m == 'nop':
            pass
        else:
            raise Unsupported('unimplemented opcode %r (%s) at 0x%08x'
                              % (m, x.op_str, x.address))
        return nxt


def run_case(path, t, instance, value, channel=1, seed=None):
    """`seed`: {offset_from_base: (size, value)} applied before the run, used to
    satisfy the sibling's feature gate so its `instance < 4` bound is reachable."""
    a = dis.Analysis(path)
    mem = Mem(a)
    cpu = Cpu(a, mem, [t['entry'], t['writer'], t['sibling']])
    mem.clock = lambda: len(cpu.trace)

    frame = bytearray(0x40)
    frame[0] = 70
    frame[4] = instance & 0xFF
    frame[5] = value & 0xFF
    frame[0x0c:0x10] = channel.to_bytes(4, 'little')   # aux_channel_type
    frame[0x12] = 0x10                                 # dpaux.length
    for i, b in enumerate(frame):
        mem.over[FRAME + i] = b
    # only the frame is pre-seeded; the data region starts as zeros

    base = mem.load(0x60013d70 if 'dcn_3_5' in path else 0x60013d80, 4)
    for off, (sz, val) in (seed or {}).items():
        for i in range(sz):
            mem.over[base + off + i] = (val >> (8 * i)) & 0xFF
    pre = len(mem.writes)

    cpu.set(1, STACK)
    cpu.set(10, FRAME)
    cpu.pending = (None, 2)
    cpu.run(t['entry'])

    del mem.writes[:pre]
    return mem, cpu, base


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--image', default=os.path.join(HERE, 'fw', 'dcn_3_5_dmcub.bin'))
    ap.add_argument('--selftest', action='store_true')
    args = ap.parse_args()

    if args.selftest:
        # Both affected images must reproduce independently -- 3.6 has different
        # offsets, so agreement there is the check that the interpreter is not
        # simply echoing the numbers the static audit expected.
        rc = 0
        for name in ('dcn_3_5', 'dcn_3_6'):
            img = os.path.join(HERE, 'fw', '%s_dmcub.bin' % name)
            print('=' * 70)
            sys.argv = [sys.argv[0], '--image', img]
            rc |= main()
        print('=' * 70)
        print('SELFTEST %s' % ('PASS' if rc == 0 else 'FAIL'))
        return rc

    key = 'dcn_3_6' if 'dcn_3_6' in args.image else 'dcn_3_5'
    t = TARGETS[key]
    print('image %s  entry 0x%08x writer 0x%08x sibling 0x%08x'
          % (os.path.basename(args.image), t['entry'], t['writer'], t['sibling']))

    VAL = 0xA5
    failures = []

    # ---- the sweep -----------------------------------------------------
    print('\ninstance  write addr   val  offset-from-base  verdict')
    got = {}
    for inst in (0, 1, 2, 3, 4, 8, 0x15, 0x7F, 0xFF):
        mem, cpu, base = run_case(args.image, t, inst, VAL)
        arr = [w for w in mem.writes if w[3] == 'data' and w[2] == VAL and w[1] == 1]
        if not arr:
            print('  0x%02x     %-12s %-4s %-17s NO BYTE WRITTEN' % (inst, '-', '-', '-'))
            got[inst] = None
            continue
        addr = arr[-1][0]
        got[inst] = addr
        exp = base + t['array'] + inst
        ok = addr == exp
        print('  0x%02x     0x%08x  0x%02x  base+0x%04x%s      %s'
              % (inst, addr, arr[-1][2], addr - base,
                 '', 'matches static' if ok else 'MISMATCH exp 0x%08x' % exp))
        if not ok:
            failures.append('instance 0x%02x wrote 0x%08x, static says 0x%08x'
                            % (inst, addr, exp))

    mem0, _, base = run_case(args.image, t, 0, VAL)

    # ---- controls -------------------------------------------------------
    print('\ncontrols')

    # 1. in-range writes land inside the 4-entry array
    inrange = all(got[i] == base + t['array'] + i for i in (0, 1, 2, 3))
    print('  [%s] instance 0..3 land in the 4-entry array at base+0x%x'
          % ('PASS' if inrange else 'FAIL', t['array']))
    if not inrange:
        failures.append('in-range writes did not land in the array')

    # 2. the value is the host byte, not a constant
    m2, _, _ = run_case(args.image, t, 8, 0x3C)
    v2 = [w for w in m2.writes if w[3] == 'data' and w[1] == 1
          and w[0] == base + t['array'] + 8]
    hostbyte = bool(v2) and v2[-1][2] == 0x3C
    print('  [%s] stored byte follows frame[5] (0x3C in, 0x%02X out) -- attacker-controlled'
          % ('PASS' if hostbyte else 'FAIL', v2[-1][2] if v2 else 0))
    if not hostbyte:
        failures.append('stored value did not track frame[5]')

    # 3. instance=8 reaches the multiply-referenced neighbour
    hit = got[8] == base + t['neighbour']
    print('  [%s] instance 8 writes base+0x%x, the neighbouring struct (OOB)'
          % ('PASS' if hit else 'FAIL', t['neighbour']))
    if not hit:
        failures.append('instance 8 did not reach base+0x%x' % t['neighbour'])

    # 4. NEGATIVE control: non-DPIA channel must not touch the array
    mneg, cneg, _ = run_case(args.image, t, 0xFF, VAL, channel=0)
    neg = [w for w in mneg.writes if w[3] == 'data']
    print('  [%s] negative control: channel!=DPIA writes nothing to the array (%d data writes)'
          % ('PASS' if not neg else 'FAIL', len(neg)))
    if neg:
        failures.append('legacy path wrote to the data region')

    # 5. ORDERING: the OOB store retires before the sibling is even entered.
    m5, c5, _ = run_case(args.image, t, 0xFF, VAL)
    sib_first = next((i for i, p in enumerate(c5.trace)
                      if t['sibling'] <= p < t['sibling'] + 0x120), None)
    # Use the FIRST such store: the writer stores a3 again at the same address
    # *after* the sibling returns (0x6001e663), so the last store is naturally
    # later than the call and says nothing about ordering.
    st = [w for w in m5.writes if w[3] == 'data' and w[1] == 1 and w[2] == VAL]
    ordered = bool(st) and sib_first is not None and st[0][4] < sib_first
    print('  [%s] ordering: first OOB store at trace step %s, sibling entered at step %s'
          ' (store repeats post-return at step %s)'
          % ('PASS' if ordered else 'FAIL',
             st[0][4] if st else '-', sib_first,
             st[-1][4] if len(st) > 1 else 'n/a'))
    if not ordered:
        failures.append('OOB store did not precede the sibling call')

    # 6. The sibling's `instance < 4` bound is real -- but only reachable once its
    #    feature gate is satisfied. Unseeded it bails early on a zeroed flag at
    #    base+0x%x, which is why this needs seeding to mean anything.
    gate, slot = t['gate'], t['slot']
    deep = {}
    for inst in (0, 3, 4, 8, 0xFF):
        sd = {gate: (4, 1), slot + 4 * inst: (4, 1)}
        mm, cc, _ = run_case(args.image, t, inst, VAL, seed=sd)
        sib = [p for p in cc.trace if t['sibling'] <= p < t['sibling'] + 0x120]
        deep[inst] = len(sib)
    lo = {deep[0], deep[3]}
    hi = {deep[4], deep[8], deep[0xFF]}
    bound_real = len(lo) == 1 and len(hi) == 1 and lo != hi
    print('  [%s] sibling bound exercised: instance 0/3 run %s insns (deep path), '
          '4/8/0xFF run %s (bail at bgeui)'
          % ('PASS' if bound_real else 'FAIL', lo.pop() if len(lo) == 1 else lo,
             hi.pop() if len(hi) == 1 else hi))
    if not bound_real:
        failures.append('could not exercise the sibling bound')

    # 6. no wild accesses -- the model stayed inside its regions
    print('  [%s] no unmapped accesses during the sweep (%d)'
          % ('PASS' if not mem0.wild else 'FAIL', len(mem0.wild)))

    span = [got[i] for i in got if got[i]]
    if span:
        print('\nprimitive: %d distinct byte offsets, base+0x%x .. base+0x%x (%d bytes past '
              'the 4-entry array)' % (len(set(span)), min(span) - base, max(span) - base,
                                      (max(span) - base) - (t['array'] + 3)))
    print('stubbed calls: %s' % ', '.join('0x%08x' % s[1] for s in c5.stubs) or 'none')

    if failures:
        print('\nFAILURES:')
        for f in failures:
            print('  - %s' % f)
        return 1
    print('\nALL CONTROLS PASS -- FINDING-11 reproduced in emulation')
    return 0


if __name__ == '__main__':
    sys.exit(main())