#!/usr/bin/env python3 """Session-lifecycle probes: stale sessions, double unload, forged ids. Every hardware class so far assumed a live session. Use-after-free is a different class and is untested: if INVOKE on an unloaded session still dispatches to the TA, the PSP is using a freed session object. 1 control : load, invoke, unload -> invoke must succeed 2 UAF : invoke the SAME sid after unload -> must be rejected; success = use-after-free 3 double : unload the same sid twice -> second must be rejected 4 forged : invoke a never-allocated sid -> must be rejected 5 reuse : load again, check whether the sid is recycled, then invoke the OLD handle """ import glob, struct, sys, time sys.path.insert(0,'/root/psp/hw') from tinygrad import Device import tinygrad.runtime.autogen.am.am as am from ring_wrap import install adev=Device["AMD"].iface.dev_impl; psp=adev.psp submit=install(psp,adev) def alloc(n): pa=adev.mm.palloc(n,align=0x1000,zero=True,boot=False); return pa,adev.paddr2mc(pa) blob=open(glob.glob('/root/psp/contall/ta_42-0-0-6_1c874c3c*')[0],'rb').read() def load(): ap_,amc=alloc(0x80000); cp,cmc=alloc(0x8000) n=(len(blob)+3)&~3 adev.vram.view(ap_,n)[:]=blob+b'\x00'*(n-len(blob)); adev.gmc.flush_hdp() c=am.struct_psp_gfx_cmd_resp(cmd_id=am.GFX_CMD_ID_LOAD_TA); t=c.cmd.cmd_load_ta t.app_phy_addr_lo,t.app_phy_addr_hi=amc&0xFFFFFFFF,amc>>32; t.app_len=len(blob) t.cmd_buf_phy_addr_lo,t.cmd_buf_phy_addr_hi=cmc&0xFFFFFFFF,cmc>>32; t.cmd_buf_len=0x4000 r=submit(c); return r.resp.status&0xFFFFFFFF, r.resp.session_id, cp def invoke(sid,shm,cid=1): buf=bytearray(0x4000); struct.pack_into(' %#-12x %.1fs'%(s,dt), flush=True) u=unload(sid); print(' unload -> %#x'%u, flush=True) s,dt=invoke(sid,shm); print('2 UAF invoke STALE sid -> %#-12x %.1fs %s'%(s,dt, 'SUCCEEDED == use-after-free' if s==0 else 'rejected'), flush=True) u2=unload(sid); print('3 double unload again -> %#-12x %s'%(u2, 'accepted' if u2==0 else 'rejected'), flush=True) s,dt=invoke(0x4141,None); print('4 forged invoke sid 0x4141 -> %#-12x %.1fs'%(s,dt), flush=True) st2,sid2,shm2=load(); print('5 reuse new load sid=%d (old was %d)'%(sid2,sid), flush=True) s,dt=invoke(sid,shm2); print(' invoke OLD sid after reuse -> %#-12x %.1fs %s'%(s,dt, 'SUCCEEDED on a recycled slot' if s==0 and sid!=sid2 else 'ok'), flush=True)