Files
WoW-Hybrid-gateway/tests/engine_poll_host_test.py

235 lines
15 KiB
Python

#!/usr/bin/env python3
"""Exercise per-object binding/rollback on owned synthetic memory, not a game."""
import hashlib,json,struct,sys,tempfile
from pathlib import Path
from unittest.mock import patch
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'ops'))
import engine_poll_host as host
import engine_wire_host as wire
Q=lambda value:struct.pack('<Q',value)
class Memory:
owner=0x100000;queue=0x110000;table=host.BASE+0x4800010;module_base=0x180000000
data=module_base+0x6000;callback=module_base+0x1100
packet_data=module_base+0x8000;packet_callback=module_base+0x1300;receiver=module_base+0x1200
def __init__(self):
self.bytes={};self.writes=[];self.fail_publish=False
self.meta={'exports':{'gw_poll_host_data':0x6000,'gw_poll_host_callback':0x1100,'gw_packet_host_data':0x8000,'gw_packet_poll_callback':0x1300,'gw_packet_receive_callback':0x1200}}
self.put(0x145e7a098,Q(self.owner));self.put(self.owner,Q(self.table))
self.put(self.owner+0x98,struct.pack('<I',2));self.put(self.owner+0x1a0,bytes(32))
self.put(self.owner+0xa0,Q(self.queue));self.put(self.queue,Q(self.owner))
self.methods=[host.BASE+0x4000+i*0x100 for i in range(8)]
self.methods[6]=0x141e47960
self.put(self.table-8,Q(host.BASE+0x5000000))
self.put(self.table,b''.join(Q(x) for x in self.methods)+Q(0))
self.put(self.data,struct.pack('<II',1,host.SIZE)+bytes(host.SIZE-8))
self.put(self.packet_data,struct.pack('<II',1,16440)+bytes(16432))
def put(self,address,data):self.bytes.update({address+i:b for i,b in enumerate(data)})
def read(self,address,size):return bytes(self.bytes[address+i] for i in range(size))
def u64(self,address):return struct.unpack('<Q',self.read(address,8))[0]
def write(self,address,data):
assert (address==self.owner and len(data)==8) or self.data<=address and address+len(data)<=self.data+host.SIZE or self.packet_data<=address and address+len(data)<=self.packet_data+16440
if self.fail_publish and address==self.data+8:raise ValueError('synthetic publication failure')
self.writes.append((address,len(data)));self.put(address,data)
def allowed(self,address,size,permission):return permission=='x' and address in (self.callback,self.packet_callback,self.receiver,self.methods[5])
def module(self):return self.module_base,self.meta
def close(self):pass
class WireMemory(Memory):
wire_base=0x190000000;wire_data=wire_base+0x7000;wire_callback=wire_base+0x2000
account_data=wire_base+0x9000;realms=wire_base+0xa000
realm_data=wire_base+0xc000
def __init__(self):
super().__init__();self.put(self.wire_data,struct.pack('<II',1,1080)+bytes(1072))
self.put(self.account_data,struct.pack('<II',1,1732)+bytes(1724))
self.put(self.realm_data,struct.pack('<II',1,48)+bytes(40))
self.put(0x141e46020,bytes.fromhex('48895c2410488974241855'))
caller=0x1401dfad3;self.put(caller-5,b'\xe8'+struct.pack('<i',0x141e53d80-caller))
def allowed(self,address,size,permission):
return permission=='x' and address in (self.wire_callback,0x141e46020,0x1401dface) or super().allowed(address,size,permission)
def write(self,address,data):
if self.wire_data<=address and address+len(data)<=self.wire_data+1080 or self.account_data<=address and address+len(data)<=self.account_data+1732 or self.realm_data<=address and address+len(data)<=self.realm_data+48:
self.writes.append((address,len(data)));self.put(address,data)
else:super().write(address,data)
def check_prepare_publication():
# Reuse the original fixture; model a native consumer running immediately
# when the owner pointer is published, rather than after install returns.
for invalid in (False,True):
with tempfile.TemporaryDirectory() as directory:
root=Path(directory);(root/'runtime').mkdir();(root/'build').mkdir()
peer=root/'build/libgateway_wine_wire.so';core=root/'build/libgateway_native.so'
peer.write_bytes(b'peer');core.write_bytes(b'core')
metadata={'wire_unix_library':{'wire_unix_path':str(peer),'wire_unix_sha256':hashlib.sha256(peer.read_bytes()).hexdigest(),'core_path':str(core),'core_sha256':hashlib.sha256(core.read_bytes()).hexdigest()}}
info={'exports':{'gw_wire_frame_data':0x7000,'gw_wire_frame_callback':0x2000}}
memory=WireMemory();published=[];original_write=memory.write
if invalid:memory.put(memory.wire_data,struct.pack('<II',99,1080))
def consume_at_publication(address,data):
if address==memory.owner:
binding=json.loads((root/'runtime/engine-poll-binding.json').read_text())
assert binding['wire_frame_callback']==memory.wire_callback
assert binding['wire_frame_data']==memory.wire_data
assert memory.u64(memory.data+56+5*8)==memory.wire_callback
assert memory.u64(memory.data+56+6*8)==memory.receiver
assert memory.u64(memory.packet_data+48)==0x141e47960
values=struct.unpack('<9IiIIQ',memory.read(memory.wire_data,56))
assert values[:4]==(1,1080,1,0) and values[-1]==memory.data
assert struct.unpack('<I',memory.read(memory.data+8,4))[0]==2
published.append(address)
# First-use progress must not be overwritten by the host.
memory.put(memory.data+8,struct.pack('<I',3))
original_write(address,data)
memory.write=consume_at_publication
with patch.object(host,'ROOT',root),patch.object(wire,'ROOT',root),patch.object(host,'Access',return_value=memory),patch.object(wire,'module',return_value=(memory.wire_base,info,metadata)):
if invalid:
try:wire.install_ping(123,'0x1401dfad3')
except ValueError:pass
else:raise AssertionError('Invalid preparation was published')
assert not published and memory.u64(memory.owner)==memory.table
assert json.loads((root/'runtime/engine-poll-binding.json').read_text())['restored']
else:
wire.install_ping(123,'0x1401dfad3')
assert published==[memory.owner]
assert memory.u64(memory.owner)==memory.data+56
assert memory.read(memory.data+8,4)==struct.pack('<I',3)
assert memory.read(memory.owner+0x98,4)==struct.pack('<I',2)
memory=WireMemory()
with patch.object(host,'Access',return_value=memory):
try:wire.install_ping(123,'0x140000000')
except ValueError:pass
else:raise AssertionError('Unverified safepoint accepted')
assert not memory.writes
if sys.argv[1:]==['--prepare-publication-only']:
check_prepare_publication()
print('PASS: fully prepared first use, preparation refusal, safepoint refusal')
raise SystemExit(0)
with tempfile.TemporaryDirectory() as directory:
root=Path(directory);(root/'runtime').mkdir()
memory=Memory()
with patch.object(host,'ROOT',root),patch.object(host,'Access',return_value=memory):
host.install(123,'0x1401dfad3')
assert memory.u64(memory.owner)==memory.data+56
clone=struct.unpack('<129Q',memory.read(memory.data+48,129*8))
assert clone[0]==host.BASE+0x5000000
assert list(clone[1:6])==memory.methods[:5] and clone[6]==memory.callback
assert list(clone[7:9])==memory.methods[6:]
assert memory.read(memory.owner+0x98,4)==struct.pack('<I',2)
assert memory.u64(memory.queue)==memory.owner
host.restore(123,'0x1401dfad3')
assert memory.u64(memory.owner)==memory.table
assert json.loads((root/'runtime/engine-poll-binding.json').read_text())['restored']
memory=Memory()
with patch.object(host,'ROOT',root),patch.object(host,'Access',return_value=memory):
host.install_packet(123,'0x1401dfad3')
assert memory.u64(memory.data+56+5*8)==memory.packet_callback
assert memory.u64(memory.data+56+6*8)==memory.receiver
assert memory.u64(memory.packet_data+48)==0x141e47960
assert memory.read(memory.owner+0x98,4)==struct.pack('<I',2)
host.restore(123,'0x1401dfad3')
assert memory.u64(memory.owner)==memory.table
memory=Memory();memory.fail_publish=True
with patch.object(host,'ROOT',root),patch.object(host,'Access',return_value=memory):
try:host.install(123,'0x1401dfad3')
except ValueError:pass
else:raise AssertionError('Failed publication accepted')
assert memory.u64(memory.owner)==memory.table
memory=Memory();memory.put(memory.owner+0x98,struct.pack('<I',5))
with patch.object(host,'ROOT',root),patch.object(host,'Access',return_value=memory):
try:host.install(123,'0x1401dfad3')
except ValueError:pass
else:raise AssertionError('Connected object accepted')
assert not memory.writes
try:host.install(123,'0x140000000')
except ValueError:pass
else:raise AssertionError('Unverified safepoint accepted')
assert not memory.writes
# Optional wire callback uses the same clone and restores it on metadata failure.
with tempfile.TemporaryDirectory() as directory:
root=Path(directory);(root/'runtime').mkdir();(root/'build').mkdir()
peer=root/'build/libgateway_wine_wire.so';core=root/'build/libgateway_native.so';peer.write_bytes(b'peer');core.write_bytes(b'core')
metadata={'wire_unix_library':{'wire_unix_path':str(peer),'wire_unix_sha256':hashlib.sha256(peer.read_bytes()).hexdigest(),'core_path':str(core),'core_sha256':hashlib.sha256(core.read_bytes()).hexdigest()}}
info={'exports':{'gw_wire_frame_data':0x7000,'gw_wire_frame_callback':0x2000}}
for invalid in (False,True):
memory=WireMemory()
if invalid:memory.put(memory.wire_data,struct.pack('<II',99,1080))
with patch.object(host,'ROOT',root),patch.object(wire,'ROOT',root),patch.object(host,'Access',return_value=memory),patch.object(wire,'module',return_value=(memory.wire_base,info,metadata)):
if invalid:
try:wire.install_ping(123,'0x1401dfad3')
except ValueError:pass
else:raise AssertionError('Invalid own frame ABI accepted')
assert memory.u64(memory.owner)==memory.table
else:
wire.install_ping(123,'0x1401dfad3')
assert memory.u64(memory.data+56+5*8)==memory.wire_callback
assert memory.u64(memory.data+56+6*8)==memory.receiver
assert memory.read(memory.owner+0x98,4)==struct.pack('<I',2)
values=struct.unpack('<9IiIIQ',memory.read(memory.wire_data,56))
assert values[:4]==(1,1080,1,0) and values[-1]==memory.data
host.restore(123,'0x1401dfad3');assert memory.u64(memory.owner)==memory.table
# Configure only an already-verified owned frame. Inputs are paths, never
# password bytes. Restore publishes cancellation before the original vtable.
directory=root/'secrets/account';directory.mkdir(parents=True)
for name,value in (('account.json','{"username":"synthetic"}'),('password.txt','do-not-export'),('version-hash.bin','fixture'),('addon-tail.bin','fixture')):
path=directory/name;path.write_text(value);path.chmod(0o600)
(root/'secrets/native-local-bootstrap.json').write_text(json.dumps({'account_directory':str(directory)}))
memory=WireMemory();info['exports'].update(gw_wire_auth_data=0x9000,gw_wire_auth_realms=0xa000,gw_wire_realm_data=0xc000)
with patch.object(host,'ROOT',root),patch.object(wire,'ROOT',root),patch.object(host,'Access',return_value=memory),patch.object(wire,'module',return_value=(memory.wire_base,info,metadata)):
wire.install_ping(123,'0x1401dfad3')
# Installing the callback does not complete its scalar ABI round trip.
# Account publication reads the real frame, not the diagnostic inspector.
before=list(memory.writes)
try:wire.start_account(123,'0x1401dfad3')
except ValueError as error:assert 'scalar wire ABI' in str(error)
else:raise AssertionError('Incomplete scalar exchange admitted account publication')
assert memory.writes==before and memory.read(memory.account_data+8,60)==bytes(60)
memory.put(memory.wire_data,struct.pack('<IIi6IiIIQ',1,wire.SIZE,2,1,1,1,0,0,0,0,1,0,memory.data))
wire.start_account(123,'0x1401dfad3')
payload=memory.read(memory.account_data,1732)
assert b'do-not-export' not in payload and b'synthetic\0' in payload
assert struct.unpack('<I',memory.read(memory.wire_data+8,4))[0]==3
memory.put(memory.wire_data+8,struct.pack('<I',4))
with patch.object(wire,'inspect_account',return_value={'state':2}):wire.probe_channel(123,'0x1401dfad3')
assert memory.read(memory.wire_data+8,4)==struct.pack('<I',5)
memory.put(memory.wire_data+8,struct.pack('<I',6))
with patch.object(wire,'inspect_account',return_value={'state':2,'server_proof_verified':1,'transport_prepared':1}):
caller=0x1401dfad3;memory.put(caller-5,b'\xe8'+struct.pack('<i',0x141e53d90-caller))
try:wire.open_engine_realm(123,'0x1401dfad3')
except ValueError:pass
else:raise AssertionError('Unverified engine queue target accepted')
assert memory.read(memory.wire_data+8,4)==struct.pack('<I',6)
memory.put(caller-5,b'\xe8'+struct.pack('<i',0x141e53d80-caller))
wire.open_engine_realm(123,'0x1401dfad3')
assert memory.read(memory.wire_data+8,4)==struct.pack('<I',7)
assert memory.u64(memory.realm_data+40)==memory.owner
assert memory.read(memory.owner+0x98,4)==struct.pack('<I',2) and memory.read(memory.owner+0x1a0,32)==bytes(32)
try:wire.open_engine_realm(123,'0x1401dfad3')
except ValueError:pass
else:raise AssertionError('Repeated engine-open publication accepted')
assert not wire.inspect_engine_realm(123)['world_authentication_proven']
# Public inspector must not read the credential/path input region.
original_read=memory.read
def guarded_read(address,size):
assert not memory.account_data+68<=address<memory.account_data+1732
return original_read(address,size)
with patch.object(memory,'read',side_effect=guarded_read):
report=wire.inspect_account(123);assert report['state']==0 and report['realms']==[]
host.restore(123,'0x1401dfad3')
assert memory.read(memory.account_data+48,4)==struct.pack('<I',1)
assert memory.u64(memory.owner)==memory.table
print('Per-object binding preserves original methods/state, rejects unsafe contexts and rolls back publication failures.')
# A real PE BSS export may straddle two adjacent Wine maps. Read only the public
# row, preserving the original per-map checks; holes/unreadable pages still fail.
class SplitRealm:
def __init__(self,gap=False,unreadable=False):
self.maps=[(0x1000,0x1080,'r',0,''),(0x1081 if gap else 0x1080,0x1198,'' if unreadable else 'r',0,'')]
def read(self,address,size):
if not any(a<=address and address+size<=b and 'r' in p for a,b,p,_,_ in self.maps):raise ValueError('Cross-map read')
return bytes([address%256])*size
assert len(wire.read_public_realm(SplitRealm(),0x1000))==408
for memory in (SplitRealm(gap=True),SplitRealm(unreadable=True)):
try:wire.read_public_realm(memory,0x1000)
except ValueError:pass
else:raise AssertionError('Unreadable public realm bytes accepted')