367 files, from working commit b1a079a. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
762 lines
55 KiB
Python
762 lines
55 KiB
Python
#!/usr/bin/env python3
|
|
"""Observe one allowlisted DBC in an owned, isolated PE32 Wine child.
|
|
|
|
Only execution debug registers are changed, then restored. No callbacks, code
|
|
patches, injected engine calls, credential/UI input, or opaque MPQ dereferences.
|
|
The initial implementation rejects seeks, async reads and unknown read branches.
|
|
"""
|
|
import argparse
|
|
import ctypes as C
|
|
from contextlib import contextmanager
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import signal
|
|
import struct
|
|
import subprocess
|
|
import time
|
|
|
|
from engine_main_thread_probe import Probe, Registers, ROOT
|
|
from octo_client_data import canonical_sha256
|
|
from turtle_reference import _check_network
|
|
from turtle_data import INVENTORY_SCHEMAS
|
|
import octo_transmog_contract as transmog_contract
|
|
|
|
CLIENT_SHA='5014ca1cfedf860f10e93fe7d955c56c28eb11a2bb503030dbb9b1c777f00470'
|
|
LOADER_SHA='228d7bb5e3b5b0c2062d6c5f40c38c2a173e4c80d8a5d9e4077be800431b48a3'
|
|
LOADER_COMPANION=('VfPatcher.dll','f283b6b5ad8042e7995eff9768c150042dd47de6e5f00ffe530d2e67743df81d')
|
|
LOADER_COPY_MANIFEST=ROOT/'runtime/octo-private-official-loader-copy.json'
|
|
OPEN=0x6477a0
|
|
READ=0x648460
|
|
SEEK=0x648a60
|
|
CLOSE=0x648730
|
|
MPQ_COUNT=0x648540
|
|
LOOSE_COUNT=0x6484dd
|
|
BLOCK_FILL=0x65702d
|
|
BLOCK_MODE='mpq-block-fills-v1'
|
|
BLOCK_ANALYSIS=ROOT/'docs/evidence/data/octo-file-block-static.json'
|
|
TRANSMOG_ANALYSIS=ROOT/'docs/evidence/data/octo-transmog-read-contract.json'
|
|
MAX_BYTES=64*1024*1024
|
|
TABLE_FIELDS={name:INVENTORY_SCHEMAS[name] for name in ('Talent','TalentTab','Spell','ItemDisplayInfo','SpellIcon','SpellVisualKit')}
|
|
BLOCK_ONLY={'Spell','ItemDisplayInfo'}
|
|
TABLE_NAME=b'DBFilesClient\\Talent.dbc' # Backward-compatible default fixture name.
|
|
|
|
|
|
def table_name(table):
|
|
if table not in TABLE_FIELDS:raise ValueError('Only reviewed allowlisted DBC tables are supported')
|
|
return ('DBFilesClient\\'+table+'.dbc').encode('ascii')
|
|
|
|
|
|
def validate_capture_mode(table,mode):
|
|
if mode not in ('per-read','block-fill') or table in BLOCK_ONLY and mode!='block-fill':raise ValueError('Large table capture requires explicit block-fill mode')
|
|
|
|
|
|
def completion_status(table):
|
|
table_name(table)
|
|
return 'complete-natural-'+table.lower()+'-content'
|
|
FULL_FUNCTIONS={READ:(373,'cbfceae78aa0fc594940bc0267aba96fe2efbc7c6f7e064a1db1605e99afb4f3'),
|
|
SEEK:(359,'873f2d5a411931d88d5b3821a1fa08f1c9a0cbdeea58585168a71938f48e132a'),
|
|
CLOSE:(126,'dccbf1063dd1c30935effec2c0f73881a815e27312e72ad5866302344b920eb4')}
|
|
|
|
|
|
BLOCK_CONTRACT={'entry_va': '0x65702d', 'runtime_entry_sha256': '141355574503375215310ad8a76e63490f2f566cc55021745837fda8bb0d3429', 'verified': True, 'buffer_register': 'esi', 'actual_register': 'ebx', 'owner_frame_offset': -52, 'offset_frame_offset': -12, 'lower_request_frame_offset': -8, 'async_frame_offset': 24, 'return_frame_offset': 4, 'source_read_return': 6587707, 'outer_inner_offset': 60, 'inner_function_va': '0x656b40', 'runtime_inner_sha256': '411c1b71bdcfc173c4a1c77c2e535e4a28a07942f8d9268468a0085281bda05e', 'outer_function_va': '0x648460', 'runtime_outer_sha256': 'cbfceae78aa0fc594940bc0267aba96fe2efbc7c6f7e064a1db1605e99afb4f3', 'outer_frame_offset': 0, 'outer_return_frame_offset': 4, 'outer_entry_sp_delta': 4, 'outer_argument_bytes': 24}
|
|
BLOCK_FUNCTIONS={BLOCK_FILL:(16,'141355574503375215310ad8a76e63490f2f566cc55021745837fda8bb0d3429'),0x656b40:(1524,'411c1b71bdcfc173c4a1c77c2e535e4a28a07942f8d9268468a0085281bda05e'),READ:FULL_FUNCTIONS[READ]}
|
|
|
|
def sha(raw):return hashlib.sha256(raw).hexdigest()
|
|
|
|
|
|
def code_difference(va,expected,actual,expected_sha,phase):
|
|
"""Bounded public-code evidence, never a replacement runtime contract."""
|
|
changed=[i for i,(a,b)in enumerate(zip(expected,actual))if a!=b]if expected is not None else []
|
|
event=dict(kind='code-contract-rejected',phase=phase,entry_va=hex(va),contract_bytes=len(actual),expected_sha256=expected_sha,actual_sha256=sha(actual),
|
|
sample_bytes=min(32,len(actual)),actual_prefix_hex=actual[:32].hex(),expected_prefix_hex=expected[:32].hex()if expected is not None else None,
|
|
prefix_sample_truncated=len(actual)>32,changed_offsets=changed[:16],changed_offsets_truncated=len(changed)>16,changed_byte_count=len(changed)if expected is not None else None,expected_body_available=expected is not None)
|
|
if len(actual)>=5 and actual[0]==0xe9:event['direct_jump']=dict(encoding='E9-rel32',target_va=hex((va+5+struct.unpack_from('<i',actual,1)[0])&0xffffffff))
|
|
return event
|
|
|
|
|
|
def stack32(raw, arguments):
|
|
if len(raw)!=4*(arguments+1):raise ValueError('Incomplete PE32 stack')
|
|
return struct.unpack('<'+'I'*(arguments+1),raw)
|
|
|
|
|
|
def validate_return(call, sp, thread, arguments):
|
|
if thread!=call['thread_id'] or sp!=call['entry_sp']+4+arguments:raise ValueError('Natural return stack/thread differs')
|
|
|
|
|
|
def actual_boundary(file_type, async_pointer, requested):
|
|
if async_pointer:raise ValueError('Tracked async read is not supported')
|
|
if not 0<requested<=MAX_BYTES:raise ValueError('Tracked zero or oversized read is not content proof')
|
|
if file_type==0:return LOOSE_COUNT,'esi'
|
|
if file_type in (2,3):return MPQ_COUNT,'ecx'
|
|
raise ValueError('Tracked read branch is not reviewed')
|
|
|
|
|
|
class Content:
|
|
def __init__(self,expected_fields=None):self.raw=bytearray();self.reads=[];self.blocks=[];self.expected=None;self.expected_fields=expected_fields
|
|
def add(self, call, raw):
|
|
actual=call['actual'];requested=call['requested']
|
|
if not 0<actual<=requested<=MAX_BYTES or len(raw)!=actual or call['result']!=1:raise ValueError('Invalid actual read result')
|
|
return self._append(call,raw,self.reads)
|
|
def add_block(self,block,raw):
|
|
actual=block['actual']
|
|
if not 0<actual<=block['lower_requested']<=MAX_BYTES or len(raw)!=actual or block['offset']!=len(self.raw):raise ValueError('Block extent, offset or actual count differs')
|
|
return self._append(block,raw,self.blocks)
|
|
def _append(self,call,raw,segments):
|
|
actual=call['actual']
|
|
if len(segments)>=100000 or len(self.raw)+actual>MAX_BYTES:raise ValueError('Capture bound exceeded')
|
|
row=dict(call,offset=len(self.raw),sha256=sha(raw));self.raw.extend(raw);segments.append(row)
|
|
if self.expected is None and len(self.raw)>=20:
|
|
magic,count,fields,size,strings=struct.unpack_from('<4s4I',self.raw)
|
|
expected=20+count*size+strings
|
|
if magic!=b'WDBC' or count>100000 or not 1<=fields<=512 or size!=fields*4 or not 1<=strings or not 20<=expected<=MAX_BYTES:raise ValueError('Natural bytes are not bounded WDBC')
|
|
if self.expected_fields is not None and fields!=self.expected_fields:raise ValueError('Selected table schema differs from reviewed source')
|
|
self.expected=expected
|
|
if self.expected is not None and len(self.raw)>self.expected:raise ValueError('Reads exceed WDBC file extent')
|
|
return self.expected is not None and len(self.raw)==self.expected
|
|
|
|
|
|
def _private(path, directory=False):
|
|
path=Path(path).absolute()
|
|
if path.is_symlink() or not path.is_relative_to(ROOT/'runtime') or path.resolve()!=path or not (path.is_dir() if directory else path.is_file()):raise ValueError('Require regular workspace runtime path')
|
|
return path
|
|
|
|
|
|
def launch_guard(executable,prefix):
|
|
exe=_private(executable);prefix=_private(prefix,True);game=exe.parent
|
|
if exe.name!='WoW.exe' or exe.stat().st_size!=7024640 or sha(exe.read_bytes())!=CLIENT_SHA:raise ValueError('Private executable is not pinned Octo PE32')
|
|
if prefix.stat().st_mode&0o077:raise ValueError('Wine prefix must be private')
|
|
for relative in ('WTF/Account','Imports/logins.txt'):
|
|
candidate=game/relative
|
|
if candidate.exists() or candidate.is_symlink():raise ValueError('Private reference copy contains account state')
|
|
_check_network(game/'realmlist.wtf',require_realm=True)
|
|
config=game/'WTF/Config.wtf'
|
|
if config.exists():
|
|
_check_network(config)
|
|
import re
|
|
# Only declaration names are inspected; values are never exposed.
|
|
if re.search(r'^\s*(?:set\s+)?(?:accountName|accountList|lastAccountName|password|accountLogin)\b',config.read_text(),re.I|re.M):raise ValueError('Private configuration contains remembered credential declarations')
|
|
if (game/'WTF').is_symlink():raise ValueError('Private WTF directory must not be linked')
|
|
return exe,prefix
|
|
|
|
|
|
def dll_manifest_names(raw):
|
|
if not isinstance(raw,bytes) or not 0<len(raw)<=8192:raise ValueError('Private DLL manifest bound')
|
|
names=[line.strip()for line in raw.decode('utf-8').splitlines()if line.strip()and not line.strip().startswith('#')]
|
|
import re
|
|
if not 1<=len(names)<=32 or len({name.casefold()for name in names})!=len(names) or any(not re.fullmatch(r'[A-Za-z0-9_.-]{1,96}\.dll',name,re.I)or name.startswith('.')for name in names):raise ValueError('Private DLL manifest must contain distinct basenames only')
|
|
return names
|
|
|
|
|
|
def official_cache_bytes(game,prefix,names):
|
|
game=Path(game);drive_c=Path(prefix)/'drive_c'
|
|
relative=''if game==drive_c else str(game.relative_to(drive_c)).replace('/','\\')if game.is_relative_to(drive_c)else None
|
|
base='C:\\'+relative if relative is not None else 'Z:'+str(game).replace('/','\\')
|
|
return '\r\n'.join(base.rstrip('\\')+'\\'+name for name in names).encode('utf-8')
|
|
|
|
|
|
def pe32_loader(raw,expected_sha=LOADER_SHA,expected_bytes=88576):
|
|
if not isinstance(raw,bytes)or len(raw)!=expected_bytes or sha(raw)!=expected_sha or len(raw)<64 or raw[:2]!=b'MZ':raise ValueError('Official loader identity differs')
|
|
offset=struct.unpack_from('<I',raw,0x3c)[0]
|
|
if offset+26>len(raw)or raw[offset:offset+4]!=b'PE\0\0'or struct.unpack_from('<H',raw,offset+4)[0]!=0x14c or struct.unpack_from('<H',raw,offset+24)[0]!=0x10b:raise ValueError('Official loader is not reviewed PE32')
|
|
|
|
|
|
def official_loader_guard(loader,exe,prefix,manifest_path):
|
|
loader=_private(loader);exe=Path(exe);prefix=Path(prefix)
|
|
if loader.name!='VanillaFixes.exe'or loader.parent!=exe.parent:raise ValueError('Official loader must be beside the private target')
|
|
if loader.stat().st_size!=88576:raise ValueError('Official loader size differs')
|
|
raw=loader.read_bytes();pe32_loader(raw,LOADER_SHA,88576)
|
|
manifest_path=_private(manifest_path)
|
|
if not 0<manifest_path.stat().st_size<=32768:raise ValueError('Public loader copy manifest bound')
|
|
manifest_raw=manifest_path.read_bytes();report=json.loads(manifest_raw)
|
|
record=report.get('loader',{})
|
|
if record.get('sha256')!=LOADER_SHA or record.get('bytes')!=88576 or ROOT/str(record.get('copy'))!=loader:raise ValueError('Official loader copy manifest differs')
|
|
if report.get('saved_accounts_copied')is not False or report.get('original_modified')is not False:raise ValueError('Require credential-free original-preserving loader copy')
|
|
public=exe.parent/'dlls.txt'
|
|
if public.is_symlink()or not public.is_file()or not 0<public.stat().st_size<=8192:raise ValueError('Private DLL manifest is unavailable')
|
|
public_raw=public.read_bytes();names=dll_manifest_names(public_raw)
|
|
if sha(public_raw)!=report.get('dll_manifest_sha256'):raise ValueError('Private DLL manifest differs from source copy pin')
|
|
rows=report.get('modules')
|
|
if not isinstance(rows,list)or len(rows)!=len(names)or [row.get('basename')for row in rows]!=names:raise ValueError('Private DLL order differs from copied source manifest')
|
|
modules=[]
|
|
for name,row in zip(names,rows):
|
|
path=_private(exe.parent/name)
|
|
if not 0<path.stat().st_size<=MAX_BYTES:raise ValueError('Private requested module size bound')
|
|
actual=sha(path.read_bytes())
|
|
if actual!=row.get('sha256'):raise ValueError('Private requested module differs from source copy pin')
|
|
modules.append(dict(basename=name,sha256=actual,bytes=path.stat().st_size))
|
|
companion=_private(exe.parent/LOADER_COMPANION[0])
|
|
if not 0<companion.stat().st_size<=MAX_BYTES:raise ValueError('Official loader companion size bound')
|
|
companion_sha=sha(companion.read_bytes())
|
|
if companion_sha!=LOADER_COMPANION[1]:raise ValueError('Official loader companion differs')
|
|
cache_raw=official_cache_bytes(exe.parent,prefix,names);cache=exe.parent/'dlls.txt.cache'
|
|
if cache.is_symlink()or cache.exists()and (not cache.is_file()or cache.stat().st_size>32768 or cache.read_bytes()!=cache_raw):raise ValueError('Existing private loader cache conflicts; preserve it')
|
|
return dict(method='unmodified-pinned-official-loader',file=str(loader),bytes=len(raw),sha256=LOADER_SHA,pe_machine='0x14c',pe_optional_magic='0x10b',publisher_signature_verified=False,
|
|
arguments=[exe.name],working_directory=str(exe.parent),copy_manifest=str(manifest_path),copy_manifest_sha256=sha(manifest_raw),dll_manifest_sha256=sha(public_raw),
|
|
requested_modules=modules,companion=dict(basename=companion.name,sha256=companion_sha,bytes=companion.stat().st_size),cache_file=str(cache),cache_sha256=sha(cache_raw),cache_created=False)
|
|
|
|
|
|
def launch_command(exe,loader_info=None):
|
|
return ['/usr/bin/wine',loader_info['file'],exe.name]if loader_info is not None else ['/usr/bin/wine',str(exe),'-windowed']
|
|
|
|
|
|
def ensure_official_cache(info,exe,prefix):
|
|
names=[row['basename']for row in info['requested_modules']];expected=official_cache_bytes(exe.parent,prefix,names);path=Path(info['cache_file'])
|
|
if path.is_symlink():raise ValueError('Private loader cache became a symlink')
|
|
if path.exists():
|
|
if not path.is_file()or path.stat().st_size>32768 or path.read_bytes()!=expected:raise ValueError('Private loader cache changed')
|
|
else:
|
|
fd=os.open(path,os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,0o600)
|
|
with os.fdopen(fd,'wb')as stream:stream.write(expected)
|
|
info['cache_created']=True
|
|
if sha(path.read_bytes())!=info['cache_sha256']:raise ValueError('Private loader cache identity differs')
|
|
|
|
|
|
def process_info(pid,proc_root=Path('/proc')):
|
|
raw=(proc_root/str(pid)/'stat').read_text()
|
|
end=raw.rfind(')');start=raw.find('(')
|
|
if start<0 or end<start:raise ValueError('Malformed owned process identity')
|
|
fields=raw[end+1:].split()
|
|
return dict(pid=int(raw[:start].strip()),name=raw[start+1:end],ppid=int(fields[1]),start_time=int(fields[19]))
|
|
|
|
|
|
def prefix_matches(pid,prefix,proc_root=Path('/proc')):
|
|
return b'WINEPREFIX='+str(prefix).encode() in (proc_root/str(pid)/'environ').read_bytes().split(b'\0')
|
|
|
|
|
|
def prefix_processes(prefix,proc_root=Path('/proc')):
|
|
found=[]
|
|
for entry in proc_root.iterdir():
|
|
if not entry.name.isdigit():continue
|
|
try:
|
|
info=process_info(int(entry.name),proc_root);name=info['name'].lower()
|
|
# Inspect only Wine/Windows process environments, never expose them.
|
|
if ('wine' in name or name.endswith('.exe')) and prefix_matches(info['pid'],prefix,proc_root):found.append(info)
|
|
except (FileNotFoundError,ProcessLookupError,PermissionError):continue
|
|
return found
|
|
|
|
|
|
class OwnedWineChildren:
|
|
"""Discover only new matching descendants, including subreaper adoptees."""
|
|
def __init__(self,observer_pid,prefix,executable,proc_root=Path('/proc')):
|
|
self.observer=process_info(observer_pid,proc_root);self.prefix=Path(prefix);self.executable=Path(executable)
|
|
self.proc_root=proc_root;self.selected=None;self.ancestry=None
|
|
def no_existing_prefix(self):
|
|
if prefix_processes(self.prefix,self.proc_root):raise ValueError('Private prefix already has a Wine process')
|
|
def chain(self,pid):
|
|
rows=[];seen=set();current=pid
|
|
while current and current not in seen and len(rows)<128:
|
|
seen.add(current);info=process_info(current,self.proc_root);rows.append(info)
|
|
if current==self.observer['pid']:
|
|
if info['start_time']!=self.observer['start_time']:raise ValueError('Observer process identity changed')
|
|
# A parent/adopter cannot have started after its descendant.
|
|
if any(parent['start_time']>child['start_time'] for child,parent in zip(rows,rows[1:])):raise ValueError('Process ancestry identity changed')
|
|
return rows
|
|
current=info['ppid']
|
|
raise ValueError('Matching game is not an owned descendant')
|
|
def discover(self):
|
|
candidates=[]
|
|
for info in prefix_processes(self.prefix,self.proc_root):
|
|
if info['name']!='WoW.exe':continue
|
|
try:
|
|
lines=(self.proc_root/str(info['pid'])/'maps').read_text().splitlines()
|
|
ready=any(len(row.split())>=6 and row.split()[0].split('-')[0]=='00400000' and row.split()[2]=='00000000' and row.split()[-1]==str(self.executable) for row in lines)
|
|
if not ready:continue
|
|
ancestry=self.chain(info['pid'])
|
|
if process_info(info['pid'],self.proc_root)['start_time']!=info['start_time']:raise ValueError('Matching game PID was reused')
|
|
candidates.append((info,ancestry))
|
|
except (FileNotFoundError,ProcessLookupError):continue
|
|
if len(candidates)>1:raise ValueError('Multiple matching owned games require manual recovery')
|
|
if not candidates:return None
|
|
info,ancestry=candidates[0]
|
|
if self.selected is not None and (info['pid'],info['start_time'])!=(self.selected['pid'],self.selected['start_time']):raise ValueError('Selected game identity changed')
|
|
self.selected=info;self.ancestry=ancestry
|
|
return info['pid']
|
|
def verify_selected(self,pid):
|
|
info=process_info(pid,self.proc_root)
|
|
if self.selected is None or (info['pid'],info['start_time'])!=(self.selected['pid'],self.selected['start_time']):raise ValueError('Selected game PID was reused')
|
|
self.chain(pid)
|
|
if not prefix_matches(pid,self.prefix,self.proc_root):raise ValueError('Owned child prefix changed')
|
|
|
|
|
|
class ChildSubreaper:
|
|
"""Process-local child supervision only; no ptrace/security policy change."""
|
|
def __init__(self,libc=None):
|
|
self.libc=libc or C.CDLL(None,use_errno=True);self.previous=None;self.restored=False
|
|
if libc is None:
|
|
self.libc.prctl.argtypes=[C.c_int,C.c_ulong,C.c_ulong,C.c_ulong,C.c_ulong];self.libc.prctl.restype=C.c_int
|
|
def __enter__(self):
|
|
value=C.c_int()
|
|
if self.libc.prctl(37,C.addressof(value),0,0,0)!=0:raise OSError(C.get_errno(),'Cannot inspect process-local child supervision')
|
|
self.previous=value.value
|
|
if self.libc.prctl(36,1,0,0,0)!=0:raise OSError(C.get_errno(),'Cannot enable process-local child supervision')
|
|
return self
|
|
def __exit__(self,*unused):
|
|
if self.previous is not None:
|
|
if self.libc.prctl(36,self.previous,0,0,0)!=0:raise OSError(C.get_errno(),'Cannot restore process-local child supervision')
|
|
self.restored=True
|
|
|
|
|
|
class DbcReadTrace(Probe):
|
|
def __init__(self,pid,executable,prefix,output,scan,loader,timeout=90,abi_path=None,table='Talent',capture_mode='per-read',block_analysis=None,read_contract='original',transmog=None,transmog_analysis_path=None):
|
|
self.source_path=Path(__file__).resolve();self.source_sha256=sha(self.source_path.read_bytes())
|
|
super().__init__(pid,observe_only=True,abi_path=abi_path)
|
|
self.executable=Path(executable);self.prefix=Path(prefix);self.output=Path(output)
|
|
validate_capture_mode(table,capture_mode)
|
|
self.capture_mode=capture_mode;self.block_analysis=block_analysis;self.block_binding=None;self.block_inner=None;self.block_complete=False;self.final_read=None
|
|
self.table=table;self.table_name=table_name(table);self.complete_status=completion_status(table)
|
|
self.scan=scan;self.loader=loader;self.content=Content(TABLE_FIELDS[table]);self.open_call=None;self.pending=None;self.handle=None
|
|
self.targets=[OPEN,0,0,0];self.events=[];self.verified=False;self.restored=False;self.status='waiting-owned-image'
|
|
self.deadline=time.monotonic()+timeout;self.contracts={};self.error=None;self.seek_seen=False;self.stage='waiting-image'
|
|
self.module_inventory_initial=None;self.module_inventory_final=None;self.code_verifications=0
|
|
self.ownership=None;self.launch_pid=None;self.subreaper_state=None;self.launch_method=None
|
|
self.read_contract=read_contract;self.transmog=transmog;self.hook_runtime=None;self.hook_module_base=None
|
|
self.implementation_pins={}
|
|
if read_contract==transmog_contract.VARIANT:
|
|
for path in (Path(transmog_contract.__file__).resolve(),Path(transmog_analysis_path).resolve()):self.implementation_pins[path]=sha(path.read_bytes())
|
|
def memory(self,address,count):
|
|
if not 0<address<2**32 or not 0<=count<=MAX_BYTES or address+count>2**32:raise ValueError('Bounded PE32 memory range required')
|
|
fd=os.open(f'/proc/{self.pid}/mem',os.O_RDONLY)
|
|
try:raw=os.pread(fd,count,address)
|
|
finally:os.close(fd)
|
|
if len(raw)!=count:raise ValueError('Incomplete owned process read')
|
|
return raw
|
|
def word(self,address):return struct.unpack('<I',self.memory(address,4))[0]
|
|
def image_ready(self):
|
|
if self.ownership is not None:
|
|
if not self.pid:
|
|
selected=self.ownership.discover()
|
|
if selected is None:return False
|
|
self.pid=selected;self.events.append(dict(kind='owned-game-discovered',launch_pid=self.launch_pid,selected_pid=self.pid,ancestry=self.ownership.ancestry))
|
|
self.ownership.verify_selected(self.pid)
|
|
proc=Path('/proc')/str(self.pid)
|
|
if not proc.exists():return False
|
|
if (proc/'comm').read_text().strip()!='WoW.exe':return False
|
|
if b'WINEPREFIX='+str(self.prefix).encode() not in (proc/'environ').read_bytes().split(b'\0'):raise ValueError('Owned child prefix changed')
|
|
rows=(proc/'maps').read_text().splitlines()
|
|
return any(len(row.split())>=6 and row.split()[0].split('-')[0]=='00400000' and row.split()[2]=='00000000' and row.split()[-1]==str(self.executable) for row in rows)
|
|
def expected_code(self,va,size):
|
|
raw=self.executable.read_bytes()
|
|
if sha(raw)!=CLIENT_SHA:raise ValueError('Pinned private executable changed')
|
|
rva=va-0x400000
|
|
for section in self.loader['executable']['sections']:
|
|
start=int(section['rva'],16);offset=int(section['raw_offset'],16)
|
|
if start<=rva and rva+size<=start+section['raw_bytes']:return raw[offset+rva-start:offset+rva-start+size]
|
|
raise ValueError('Known code outside reviewed file sections')
|
|
def jump_module(self,address):
|
|
"""Correlate only approved private mapped DLLs; do not read target code."""
|
|
method=self.launch_method or {};pins={r['basename'].casefold():r['sha256']for r in method.get('requested_modules',[])}
|
|
if method.get('companion'):pins[method['companion']['basename'].casefold()]=method['companion']['sha256']
|
|
rows=Path(f'/proc/{self.pid}/maps').read_text().splitlines();mappings=[]
|
|
for row in rows:
|
|
fields=row.split(maxsplit=5)
|
|
if len(fields)<5:continue
|
|
start,end=(int(value,16)for value in fields[0].split('-'))
|
|
mappings.append((start,end,fields))
|
|
if not any(start<=address<end and 'r'in fields[1]and 'x'in fields[1]for start,end,fields in mappings):return dict(status='target-not-in-readable-executable-map')
|
|
matches=[]
|
|
for base,end,fields in mappings:
|
|
if len(fields)!=6 or int(fields[2],16)!=0:continue
|
|
path=Path(fields[5]);name=path.name.casefold()
|
|
if path.parent!=self.executable.parent or path.suffix.lower()!='.dll'or name not in pins or path.is_symlink()or not path.is_file()or not 0<path.stat().st_size<=MAX_BYTES:continue
|
|
raw=path.read_bytes();actual=sha(raw)
|
|
if actual!=pins[name]or len(raw)<64 or raw[:2]!=b'MZ':continue
|
|
pe=struct.unpack_from('<I',raw,0x3c)[0]
|
|
if pe+84>len(raw)or raw[pe:pe+4]!=b'PE\0\0'or struct.unpack_from('<H',raw,pe+4)[0]!=0x14c or struct.unpack_from('<H',raw,pe+24)[0]!=0x10b:continue
|
|
image_size=struct.unpack_from('<I',raw,pe+80)[0]
|
|
if 0<image_size<=MAX_BYTES and base<=address<base+image_size:matches.append(dict(status='pinned-private-mapped-module-range',basename=path.name,sha256=actual,module_base=base,module_image_size=image_size,relative_offset=hex(address-base),correlation='mapped-PE-header-plus-file-image-extent',function_contract_verified=False))
|
|
return matches[0]if len(matches)==1 else dict(status='ambiguous-private-module-range'if matches else 'target-not-correlated-to-pinned-private-module')
|
|
def reject_code(self,va,actual,expected_sha,phase,expected=None):
|
|
if expected is None:
|
|
try:expected=self.expected_code(va,len(actual))
|
|
except (OSError,ValueError,KeyError,TypeError):expected=None
|
|
if expected is not None and (len(expected)!=len(actual)or sha(expected)!=expected_sha):expected=None
|
|
event=code_difference(va,expected,actual,expected_sha,phase)
|
|
if 'direct_jump'in event:
|
|
try:event['direct_jump']['module']=self.jump_module(int(event['direct_jump']['target_va'],16))
|
|
except (OSError,ValueError,KeyError,TypeError,struct.error):event['direct_jump']['module']=dict(status='public-module-correlation-unavailable')
|
|
self.events.append(event)
|
|
def verify_source(self):
|
|
if sha(self.source_path.read_bytes())!=self.source_sha256:raise ValueError('Observer source changed during trace')
|
|
for path,expected in getattr(self,'implementation_pins',{}).items():
|
|
if sha(path.read_bytes())!=expected:raise ValueError('Observer helper/static analysis changed during trace')
|
|
def verify_transmog(self,evidence):
|
|
raw=self.memory(READ,6)
|
|
if len(raw)!=6 or raw[0]!=0xe9 or raw[5]!=0x90:raise ValueError('Reviewed transmog read entry is absent')
|
|
target=(READ+5+struct.unpack_from('<i',raw,1)[0])&0xffffffff
|
|
module=self.jump_module(target)
|
|
if module.get('status')!='pinned-private-mapped-module-range' or module.get('basename')!='transmogfix.dll' or module.get('sha256')!=transmog_contract.MODULE_SHA or module.get('relative_offset')!='0x18dd' or module.get('module_image_size')!=0x11000:raise ValueError('Read hook is not the reviewed mapped transmog module')
|
|
base=module['module_base']
|
|
if self.hook_module_base is not None and base!=self.hook_module_base:raise ValueError('Reviewed transmog module ownership changed')
|
|
proofs=self.transmog.verify(self.memory,base,self.expected_code(READ,373),self.expected_code(CLOSE,126),evidence[READ]['bytes'])
|
|
self.hook_module_base=base;self.hook_runtime=proofs;self.contracts.update(proofs)
|
|
def verify_code(self):
|
|
self.verify_source()
|
|
evidence={int(row['va'],16):row for row in self.loader['byte_evidence']}
|
|
hooked=False
|
|
if getattr(self,'read_contract','original')==transmog_contract.VARIANT:
|
|
hooked=self.memory(READ,6)!=bytes.fromhex(evidence[READ]['hex'])[:6]
|
|
if hooked:self.verify_transmog(evidence)
|
|
elif self.handle is not None or self.hook_runtime is not None:raise ValueError('Reviewed transmog hook is required before selected reads')
|
|
for name,va,args in [('open',OPEN,8),('read',READ,24),('seek',SEEK,16),('close',CLOSE,4)]:
|
|
row=evidence[va];raw=self.memory(va,row['bytes'])
|
|
if not(hooked and name in ('read','close'))and (sha(raw)!=row['sha256'] or raw.hex()!=row['hex']):
|
|
self.reject_code(va,raw,row['sha256'],'instruction-prefix',bytes.fromhex(row['hex']))
|
|
raise ValueError('Runtime instruction prefix differs')
|
|
if name in ('open','read'):self.contracts[name]=dict(entry_va=hex(va),argument_bytes=args,runtime_entry_sha256=sha(raw),verified=True)
|
|
self.contracts['actual_counts']=[]
|
|
for va,reg in [(MPQ_COUNT,'ecx'),(LOOSE_COUNT,'esi')]:
|
|
row=evidence[va];raw=self.memory(va,row['bytes'])
|
|
if sha(raw)!=row['sha256'] or raw.hex()!=row['hex']:
|
|
self.reject_code(va,raw,row['sha256'],'actual-count-prefix',bytes.fromhex(row['hex']))
|
|
raise ValueError('Runtime actual-count prefix differs')
|
|
self.contracts['actual_counts'].append(dict(entry_va=hex(va),register=reg,runtime_entry_sha256=sha(raw),verified=True))
|
|
for va,(length,expected) in FULL_FUNCTIONS.items():
|
|
if hooked and va in (READ,CLOSE):continue
|
|
actual=self.memory(va,length)
|
|
if sha(actual)!=expected:
|
|
self.reject_code(va,actual,expected,'full-function')
|
|
raise ValueError('Runtime full read/seek function differs')
|
|
if self.capture_mode=='block-fill':
|
|
if self.block_analysis is None or self.block_analysis['executable']['sha256']!=CLIENT_SHA or self.block_analysis['source_installation']!=self.scan['source_installation'] or self.block_analysis['block_fill_contract']!=BLOCK_CONTRACT:raise ValueError('Block analysis identity differs')
|
|
rows={int(row['va'],16):row for row in self.block_analysis['byte_evidence']}
|
|
if set(rows)!=set(BLOCK_FUNCTIONS):raise ValueError('Incomplete reviewed block function set')
|
|
for va,(size,expected) in BLOCK_FUNCTIONS.items():
|
|
row=rows[va]
|
|
if row['bytes']!=size or row['sha256']!=expected or sha(bytes.fromhex(row['hex']))!=expected:raise ValueError('Reviewed block-fill instructions differ')
|
|
actual=self.memory(va,size)
|
|
if sha(actual)!=expected:
|
|
self.reject_code(va,actual,expected,'block-fill-function',bytes.fromhex(row['hex']))
|
|
raise ValueError('Runtime block-fill instructions differ')
|
|
self.contracts['block_fill']=dict(BLOCK_CONTRACT)
|
|
self.verified=True;self.code_verifications+=1
|
|
def module_inventory(self,phase):
|
|
result=dict(phase=phase,scope='mapped-private-game-executable-files-only',file_hashes_only=True,modules_may_still_be_loading=True,complete_loader_inventory=False,modules=[])
|
|
try:lines=Path(f'/proc/{self.pid}/maps').read_text().splitlines()
|
|
except OSError:
|
|
result['available']=False;return result
|
|
seen=set();root=self.executable.parent
|
|
for line in lines:
|
|
columns=line.split(maxsplit=5)
|
|
if len(columns)!=6:continue
|
|
path=Path(columns[5])
|
|
if not path.is_absolute() or not path.is_relative_to(root) or path.suffix.lower() not in ('.exe','.dll'):continue
|
|
if path in seen:continue
|
|
if len(seen)>=128:raise ValueError('Private module inventory bound exceeded')
|
|
seen.add(path)
|
|
if path.is_symlink() or path.resolve()!=path or not path.is_file() or not 0<path.stat().st_size<=MAX_BYTES:raise ValueError('Mapped private game module identity unavailable')
|
|
result['modules'].append(dict(basename=path.name,relative_file=str(path.relative_to(root)),bytes=path.stat().st_size,sha256=sha(path.read_bytes())))
|
|
result['modules'].sort(key=lambda row:row['relative_file']);result['available']=True
|
|
return result
|
|
def arm(self):
|
|
control=0
|
|
for i,address in enumerate(self.targets):
|
|
self.debug(i,address)
|
|
if address:control|=1<<(2*i)
|
|
self.debug(6,0);self.debug(7,control)
|
|
def metadata(self,status):
|
|
captures=[]
|
|
if self.handle is not None:
|
|
captures=[dict(table=self.table,name=self.table_name.decode(),file='capture/'+self.table+'.dbc',handle_generation=1,
|
|
finished=status==self.complete_status,seek_status='observed-rejected' if self.seek_seen else 'none-observed',
|
|
open=self.open_call,bytes=len(self.content.raw),sha256=sha(self.content.raw))]
|
|
if self.capture_mode=='block-fill':captures[0].update(capture_method=BLOCK_MODE,block_binding=self.block_binding,final_read=self.final_read,blocks=self.content.blocks,engine_consumed_full_table=False)
|
|
else:captures[0]['reads']=self.content.reads
|
|
return dict(schema_version=1,kind='octo-observed-dbc-content',status=status,pid=self.pid,launch_pid=self.launch_pid,process_local_child_supervision=self.subreaper_state,launch_method=self.launch_method,
|
|
source_installation=self.scan['source_installation'],working_executable=str(self.executable),private_prefix=str(self.prefix),
|
|
scan_sha256=canonical_sha256(self.scan),loader_analysis_sha256=canonical_sha256(self.loader),
|
|
client_identity=dict(client_sha256=CLIENT_SHA,client_build=self.scan.get('client_build'),locale=self.loader['observations'].get('declared_config_locale')),
|
|
observer=dict(code_sha256=self.source_sha256,pointer_bits=32,thread_scope='owned-main-thread-natural-calls',other_threads_observed=False,
|
|
**(dict(implementation_files={path.name:expected for path,expected in self.implementation_pins.items()})if getattr(self,'read_contract','original')==transmog_contract.VARIANT else {})),
|
|
contracts=self.contracts,captures=captures,events=self.events,observed_stops=self.stops,
|
|
launcher_equivalence_status='blocked-runtime-code-contract-changed'if any(row.get('kind')=='code-contract-rejected'for row in self.events)else 'not-established',
|
|
**(dict(capture_mode=BLOCK_MODE,block_analysis_sha256=canonical_sha256(self.block_analysis),all_parser_read_results_verified=False,all_inner_crc_paths_verified=False)if self.capture_mode=='block-fill' else {}),
|
|
**(dict(read_contract=transmog_contract.VARIANT,transmog_analysis_sha256=canonical_sha256(self.transmog.analysis))if getattr(self,'read_contract','original')==transmog_contract.VARIANT else {}),
|
|
fixed_code_verification_count=self.code_verifications,module_inventory_initial=self.module_inventory_initial,module_inventory_final=self.module_inventory_final,
|
|
hardware_registers_restored=self.restored,code_bytes_modified=False,engine_calls_injected=False,instruction_pointer_changed=False,
|
|
credentials_read=False,ui_input_sent=False,postload_semantics_verified=False,gameplay_verified=False,error=self.error,
|
|
limits=['No backing archive or global precedence is inferred.','Only the owned PE32 main thread is observed; external hooks and post-load transformations remain unverified.'])
|
|
def publish(self):
|
|
target=self.output/'observation.json';temporary=self.output/'observation.json.new'
|
|
fd=os.open(temporary,os.O_WRONLY|os.O_CREAT|os.O_TRUNC|os.O_NOFOLLOW,0o600)
|
|
with os.fdopen(fd,'w') as output:json.dump(self.metadata(self.status),output,indent=2);output.write('\n')
|
|
temporary.replace(target)
|
|
def finish(self,status):
|
|
if status==self.complete_status:
|
|
try:self.verify_source()
|
|
except (OSError,ValueError):
|
|
self.error=dict(type='ValueError',reason='Observer source changed during trace');status='observer-source-changed'
|
|
self.status=status
|
|
try:self.module_inventory_final=self.module_inventory('trace-finish')
|
|
except (OSError,ValueError):self.module_inventory_final=dict(phase='trace-finish',available=False,complete_loader_inventory=False,reason='private-module-inventory-unavailable')
|
|
if status==self.complete_status and self.module_inventory_final.get('available') is not True:
|
|
status=self.status='module-inventory-unavailable'
|
|
if self.attached:
|
|
if not self.stopped:raise ValueError('Cannot detach running child without stop')
|
|
self.restore_debug();self.restored=True
|
|
self.ptrace('detach',0,self.pending_signal);self.attached=False;self.stopped=False
|
|
self.done=True
|
|
if status==self.complete_status:
|
|
folder=self.output/'capture';folder.mkdir(mode=0o700)
|
|
fd=os.open(folder/(self.table+'.dbc'),os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,0o600)
|
|
with os.fdopen(fd,'wb') as output:output.write(self.content.raw)
|
|
self.publish()
|
|
def require_image_caller(self,call,entry):
|
|
if not 0x401000<=call['return_address']<0x800000:
|
|
self.events.append(dict(kind='selected-return-rejected',entry_va=hex(entry),return_va=hex(call['return_address'])))
|
|
raise ValueError('Natural return is outside pinned image')
|
|
def call(self,registers,arguments,require_image_return=True):
|
|
if registers.cs!=0x23 or not 0<registers.rsp<2**32 or registers.rsp%4:raise ValueError('Natural PE32 register ABI differs')
|
|
values=stack32(self.memory(registers.rsp,4*(arguments+1)),arguments)
|
|
call=dict(entry_sp=registers.rsp,return_address=values[0],thread_id=self.pid,handle_generation=1)
|
|
if require_image_return:self.require_image_caller(call,registers.rip)
|
|
return call,values[1:]
|
|
def observed(self,r):
|
|
pc=r.rip
|
|
if r.cs!=0x23:raise ValueError('Natural PE32 code segment differs')
|
|
if pc==OPEN and self.handle is None:
|
|
call,args=self.call(r,2,require_image_return=False);name,out=args
|
|
if not name:return # A NULL name cannot select the allowlisted table.
|
|
# Filename only, never file contents. Stop at first terminator.
|
|
public=self.memory(name,64).split(b'\0',1)[0]
|
|
if public.lower()!=self.table_name.lower():return
|
|
self.require_image_caller(call,pc)
|
|
if self.open_call is not None:raise ValueError('Selected open reentered')
|
|
if not out:raise ValueError('Selected named-open output absent')
|
|
self.open_call=call;self.open_out=out;self.targets[3]=call['return_address'];self.arm()
|
|
self.events.append(dict(kind='selected-natural-open',thread_id=self.pid))
|
|
elif self.open_call is not None and self.handle is None and pc==self.targets[3]:
|
|
validate_return(self.open_call,r.rsp,self.pid,8)
|
|
if not r.rax&0xffffffff:raise ValueError('Selected named-open failed')
|
|
self.handle=self.word(self.open_out)
|
|
if not self.handle:raise ValueError('Selected named-open returned empty handle')
|
|
self.open_call.update(return_sp=r.rsp,return_thread_id=self.pid,wrapper_handle=self.handle)
|
|
self.verify_code()
|
|
self.targets=[SEEK,READ,CLOSE,0];self.arm();self.events.append(dict(kind='selected-handle-correlated',handle_generation=1))
|
|
elif pc==SEEK:
|
|
call,args=self.call(r,4,require_image_return=False)
|
|
if args[0]==self.handle:
|
|
self.require_image_caller(call,pc)
|
|
self.seek_seen=True;self.events.append(dict(kind='selected-seek-rejected',origin=args[3]))
|
|
self.finish('selected-seek-not-supported')
|
|
elif pc==CLOSE:
|
|
call,args=self.call(r,1,require_image_return=False)
|
|
if args[0]==self.handle:
|
|
self.require_image_caller(call,pc)
|
|
self.events.append(dict(kind='selected-close-before-complete',handle_generation=1))
|
|
self.finish('selected-handle-closed-before-complete')
|
|
elif pc==READ:
|
|
call,args=self.call(r,6,require_image_return=False)
|
|
handle,dest,count,actual_pointer,async_pointer,unused=args
|
|
if handle!=self.handle:return
|
|
self.require_image_caller(call,pc)
|
|
if self.pending is not None:raise ValueError('Selected read reentered')
|
|
file_type=self.word(handle);boundary,reg=actual_boundary(file_type,async_pointer,count)
|
|
if getattr(self,'read_contract','original')==transmog_contract.VARIANT:
|
|
if self.hook_runtime is None or file_type not in (2,3):raise ValueError('Reviewed transmog requires verified ordinary MPQ read')
|
|
# Nonzero MPQ type makes the reviewed special-wrapper predicate false.
|
|
call['read_contract']=transmog_contract.VARIANT
|
|
call.update(requested=count,actual_count_pointer=actual_pointer,file_type=file_type)
|
|
if self.capture_mode=='block-fill':
|
|
if file_type not in (2,3):raise ValueError('Block fill requires reviewed MPQ branch')
|
|
inner=self.word(handle+60)
|
|
if not inner or inner%4:raise ValueError('Natural MPQ inner owner is invalid')
|
|
self.block_inner=inner;call.update(wrapper_handle=handle,inner_handle=inner,asynchronous_pointer=0)
|
|
self.block_binding=call;self.pending=dict(kind='block-binding',call=call)
|
|
self.targets=[SEEK,BLOCK_FILL,CLOSE,call['return_address']];self.arm();return
|
|
self.pending=dict(call=call,args=args,dest=dest,boundary=boundary,register=reg,actual=None)
|
|
self.targets[2]=boundary;self.targets[3]=call['return_address'];self.arm()
|
|
elif pc==BLOCK_FILL and self.capture_mode=='block-fill':
|
|
frame=r.rbp
|
|
if not 0x40<=frame<2**32 or frame%4:raise ValueError('Block-fill frame is not PE32')
|
|
owner=self.word(frame-52)
|
|
if owner!=self.block_inner:return
|
|
source_return=self.word(frame+4);asynchronous=self.word(frame+24)
|
|
if source_return!=0x64853b or asynchronous:raise ValueError('Block fill is not reviewed synchronous outer call')
|
|
block=dict(offset=self.word(frame-12),actual=r.rbx&0xffffffff,buffer_address=r.rsi&0xffffffff,
|
|
thread_id=self.pid,handle_generation=1,observation_pc=hex(BLOCK_FILL),frame_pointer=frame,
|
|
source_read_return=source_return,inner_owner=owner,asynchronous_pointer=asynchronous,lower_requested=self.word(frame-8))
|
|
if not 0<block['actual']<=block['lower_requested']<=MAX_BYTES or block['offset']!=len(self.content.raw) or block['offset']+block['actual']>MAX_BYTES:raise ValueError('Block fill extent, offset or actual count differs')
|
|
self.block_complete=self.content.add_block(block,self.memory(block['buffer_address'],block['actual']))
|
|
if self.block_complete:
|
|
outer=self.word(frame)
|
|
if not frame<outer<2**32-32 or outer%4 or self.word(outer+8)!=self.handle:raise ValueError('Final block outer owner/frame differs')
|
|
caller=self.word(outer+4)
|
|
self.require_image_caller(dict(return_address=caller),BLOCK_FILL)
|
|
self.final_read=dict(entry_sp=outer+4,return_address=caller,thread_id=self.pid,handle_generation=1,wrapper_handle=self.handle,inner_handle=owner,source_frame_pointer=frame,outer_frame_pointer=outer,entry_sp_proof='inner-saved-outer-frame')
|
|
if self.pending is not None and (self.pending['call']['entry_sp'],self.pending['call']['return_address'])!=(outer+4,caller):raise ValueError('Final block disagrees with observed first read')
|
|
self.targets[3]=caller;self.arm()
|
|
elif self.pending is not None and self.pending.get('kind')=='block-binding' and pc==self.targets[3]:
|
|
call=self.pending['call'];validate_return(call,r.rsp,self.pid,24)
|
|
if r.rax&0xffffffff!=1 or not self.content.blocks:raise ValueError('First natural read bypassed reviewed block fill')
|
|
call.update(return_sp=r.rsp,return_thread_id=self.pid,result=1)
|
|
self.pending=None;self.targets[3]=0;self.arm()
|
|
if self.block_complete:
|
|
validate_return(self.final_read,r.rsp,self.pid,24)
|
|
self.final_read.update(return_sp=r.rsp,return_thread_id=self.pid,result=1)
|
|
self.verify_code();self.finish(self.complete_status)
|
|
elif self.capture_mode=='block-fill' and self.final_read is not None and pc==self.targets[3]:
|
|
validate_return(self.final_read,r.rsp,self.pid,24)
|
|
if r.rax&0xffffffff!=1:raise ValueError('Final natural outer read failed')
|
|
self.final_read.update(return_sp=r.rsp,return_thread_id=self.pid,result=1)
|
|
self.verify_code();self.finish(self.complete_status)
|
|
elif self.pending is not None and self.pending.get('call',{}).get('read_contract')==transmog_contract.VARIANT and pc==self.hook_module_base+0x1941:
|
|
pending=self.pending;call=pending['call'];frame=call.get('hook_frame')
|
|
if frame is None or frame.get('original_result') is not None:raise ValueError('Transmog original return lacks unique actual-count proof')
|
|
validate_return(dict(entry_sp=frame['original_entry_sp'],thread_id=call['thread_id']),r.rsp,self.pid,24)
|
|
if r.rbp!=frame['hook_frame_pointer'] or r.rax&0xffffffff!=1:raise ValueError('Transmog original natural return failed')
|
|
frame.update(original_return_sp=r.rsp,original_return_thread_id=self.pid,original_result=1)
|
|
self.targets[2]=CLOSE;self.arm()
|
|
elif self.pending is not None and pc==self.targets[2]:
|
|
pending=self.pending;call=pending['call']
|
|
actual=(r.rcx if pending['register']=='ecx' else r.rsi)&0xffffffff
|
|
if not 0<actual<=pending['call']['requested']:raise ValueError('Actual count is zero or exceeds request')
|
|
if call.get('read_contract')==transmog_contract.VARIANT:
|
|
call['hook_frame']=transmog_contract.ordinary_frame(self.memory,call['entry_sp'],r.rbp,pending['args'],self.hook_module_base,call['return_address'],actual)
|
|
elif r.rbp+4!=call['entry_sp']:raise ValueError('Actual-count frame differs')
|
|
if pending['actual'] is not None:raise ValueError('Actual-count boundary repeated')
|
|
pending['actual']=actual;pending['call']['actual_count_proof']=dict(method='verified-count-pc',pc=hex(pc),value=actual,thread_id=self.pid,handle_generation=1)
|
|
if call.get('read_contract')==transmog_contract.VARIANT:
|
|
self.targets[2]=self.hook_module_base+0x1941;self.arm()
|
|
elif self.pending is not None and pc==self.targets[3]:
|
|
pending=self.pending;call=pending['call'];validate_return(call,r.rsp,self.pid,24)
|
|
if pending['actual'] is None:raise ValueError('Selected read skipped actual-count boundary')
|
|
if call.get('read_contract')==transmog_contract.VARIANT and call.get('hook_frame',{}).get('original_result')!=1:raise ValueError('Transmog final return skipped original return proof')
|
|
if call['actual_count_pointer'] and self.word(call['actual_count_pointer'])!=pending['actual']:raise ValueError('Caller actual-count pointer differs')
|
|
call.update(return_sp=r.rsp,return_thread_id=self.pid,actual=pending['actual'],result=r.rax&0xffffffff)
|
|
done=self.content.add(call,self.memory(pending['dest'],pending['actual']))
|
|
self.pending=None;self.targets[2:]=[CLOSE,0];self.arm()
|
|
if done:
|
|
self.verify_code()
|
|
self.finish(self.complete_status)
|
|
def poll(self):
|
|
if self.done:return
|
|
if not self.attached:
|
|
if time.monotonic()>self.deadline:self.finish('owned-image-timeout');return
|
|
if not self.image_ready():return
|
|
self.ptrace('seize');self.attached=True;self.stage='initial-stop';self.ptrace('interrupt');return
|
|
if time.monotonic()>self.deadline and self.stage!='cancel-stop':self.stage='cancel-stop';self.ptrace('interrupt')
|
|
got,status=os.waitpid(self.pid,os.WNOHANG|self.abi['wall'])
|
|
if not got:return
|
|
if os.WIFEXITED(status) or os.WIFSIGNALED(status):
|
|
self.attached=False;self.done=True;self.status='owned-client-exited';self.publish();return
|
|
if not os.WIFSTOPPED(status):return
|
|
self.stopped=True;self.stops+=1;stop=os.WSTOPSIG(status)
|
|
self.pending_signal=0 if status>>16==128 else stop
|
|
if self.stage=='initial-stop':
|
|
if self.ownership is not None:self.ownership.verify_selected(self.pid)
|
|
self.saved={i:self.debug(i) for i in (0,1,2,3,6,7)}
|
|
if self.saved[7]&0xff:self.finish('existing-debug-registers-preserved');return
|
|
self.verify_code();self.module_inventory_initial=self.module_inventory('initial-arm');self.arm();self.stage='tracing';self.status='observing-natural-'+self.table.lower()+'-open';self.publish()
|
|
else:
|
|
registers=Registers();self.ptrace('getregs',0,C.addressof(registers))
|
|
hits=self.debug(6)&15 if stop==signal.SIGTRAP else 0
|
|
own=bool(hits and any(address and registers.rip==address and hits&(1<<i) for i,address in enumerate(self.targets)))
|
|
if own:self.pending_signal=0;self.debug(6,0)
|
|
if self.stage=='cancel-stop':self.finish('bounded-observer-finished');return
|
|
if own:self.observed(registers)
|
|
if self.done:return
|
|
self.ptrace('cont',0,self.pending_signal);self.stopped=False
|
|
def cancel(self):
|
|
if not self.attached:
|
|
if not self.done:self.finish('observer-cancelled')
|
|
return
|
|
if self.stopped:self.finish('observer-rejected' if self.error else 'observer-cancelled');return
|
|
self.stage='cancel-stop';self.ptrace('interrupt');end=time.monotonic()+3
|
|
while self.attached and time.monotonic()<end:self.poll();time.sleep(.001)
|
|
if self.attached:raise RuntimeError('Owned debug-register cleanup did not complete')
|
|
|
|
|
|
@contextmanager
|
|
def termination_guard():
|
|
def stop(signum,frame):raise KeyboardInterrupt('Observer termination requested')
|
|
saved={sig:signal.getsignal(sig) for sig in (signal.SIGTERM,signal.SIGHUP)}
|
|
try:
|
|
for sig in saved:signal.signal(sig,stop)
|
|
yield
|
|
finally:
|
|
for sig,handler in saved.items():signal.signal(sig,handler)
|
|
|
|
|
|
def run(executable,prefix,output,scan_path,loader_path,timeout=90,abi_path=None,table='Talent',capture_mode='per-read',block_analysis_path=BLOCK_ANALYSIS,official_loader=None,loader_copy_manifest=LOADER_COPY_MANIFEST,read_contract='original',transmog_analysis_path=TRANSMOG_ANALYSIS):
|
|
table_name(table)
|
|
validate_capture_mode(table,capture_mode)
|
|
if read_contract not in ('original',transmog_contract.VARIANT):raise ValueError('Unknown read contract')
|
|
if read_contract==transmog_contract.VARIANT:transmog_contract.require_variant(table,capture_mode,official_loader is not None)
|
|
block_analysis=json.loads(Path(block_analysis_path).read_text())if capture_mode=='block-fill' else None
|
|
exe,prefix=launch_guard(executable,prefix)
|
|
launch_method=official_loader_guard(official_loader,exe,prefix,loader_copy_manifest)if official_loader is not None else dict(method='direct-private-executable',arguments=['-windowed'])
|
|
transmog=None
|
|
if read_contract==transmog_contract.VARIANT:
|
|
module=_private(exe.parent/'transmogfix.dll');analysis=Path(transmog_analysis_path)
|
|
if module.stat().st_size!=12800 or analysis.is_symlink()or not analysis.is_file()or not 0<analysis.stat().st_size<=32768:raise ValueError('Reviewed transmog bounded inputs differ')
|
|
transmog=transmog_contract.ReviewedTransmog(module.read_bytes(),analysis.read_bytes())
|
|
if not any(row['basename']=='transmogfix.dll' and row['sha256']==transmog_contract.MODULE_SHA and row['bytes']==12800 for row in launch_method['requested_modules']):raise ValueError('Official loader does not request reviewed transmog module')
|
|
if not 1<=timeout<=180:raise ValueError('Observer timeout must be1..180 seconds')
|
|
output=Path(output).absolute()
|
|
if not output.is_relative_to(ROOT/'runtime') or output.exists() or output.is_symlink() or output.parent.resolve()!=output.parent:raise ValueError('Require a new runtime observation directory')
|
|
scan=json.loads(Path(scan_path).read_text());loader=json.loads(Path(loader_path).read_text())
|
|
if loader['executable']['sha256']!=CLIENT_SHA or loader['source_installation']!=scan['source_installation']:raise ValueError('Scan/static identities differ')
|
|
if not any(row.get('table')==table and row.get('fields')==TABLE_FIELDS[table] for row in scan.get('candidates',[])):raise ValueError('Selected table lacks reviewed schema candidates')
|
|
output.mkdir(mode=0o700)
|
|
env=dict(os.environ,WINEPREFIX=str(prefix),WINEDEBUG='-all')
|
|
child=None;trace=None;supervision=ChildSubreaper()
|
|
try:
|
|
with termination_guard(),supervision,(output/'wine-startup.log').open('xb') as log:
|
|
os.chmod(log.name,0o600)
|
|
try:
|
|
# Validate the ptrace helper ABI before launching any client.
|
|
trace=DbcReadTrace(0,exe,prefix,output,scan,loader,timeout,abi_path,table,capture_mode,block_analysis,read_contract,transmog,transmog_analysis_path)
|
|
trace.ownership=OwnedWineChildren(os.getpid(),prefix,exe)
|
|
trace.ownership.no_existing_prefix()
|
|
trace.launch_method=launch_method
|
|
if official_loader is not None:
|
|
ensure_official_cache(launch_method,exe,prefix)
|
|
# Revalidate every public loader input immediately before launch.
|
|
latest=official_loader_guard(official_loader,exe,prefix,loader_copy_manifest)
|
|
if any(latest[key]!=launch_method[key]for key in latest if key!='cache_created'):raise ValueError('Official loader inputs changed before launch')
|
|
trace.subreaper_state=dict(enabled=True,original=supervision.previous,restored=False,ptrace_policy_changed=False)
|
|
command=launch_command(exe,launch_method if official_loader is not None else None)
|
|
child=subprocess.Popen(command,cwd=exe.parent,env=env,stdout=log,stderr=log,start_new_session=True)
|
|
trace.launch_pid=child.pid
|
|
while not trace.done:trace.poll();time.sleep(.001)
|
|
except BaseException as error:
|
|
if trace is not None:
|
|
trace.error=dict(type=type(error).__name__,reason=str(error) if isinstance(error,ValueError) else 'owned-observer-operation-failed')
|
|
raise
|
|
finally:
|
|
if trace is not None:trace.cancel()
|
|
finally:
|
|
if trace is not None:
|
|
trace.subreaper_state=dict(enabled=supervision.previous is not None,original=supervision.previous,restored=supervision.restored,ptrace_policy_changed=False)
|
|
trace.publish()
|
|
return trace.metadata(trace.status)
|
|
|
|
|
|
def main():
|
|
parser=argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('--executable',type=Path,required=True);parser.add_argument('--prefix',type=Path,required=True)
|
|
parser.add_argument('--output',type=Path,required=True);parser.add_argument('--scan',type=Path,required=True)
|
|
parser.add_argument('--loader-analysis',type=Path,default=ROOT/'docs/evidence/data/octo-loader-static.json')
|
|
parser.add_argument('--timeout',type=int,default=90)
|
|
parser.add_argument('--loader',type=Path,help='Explicit pinned official VanillaFixes.exe in the private game directory')
|
|
parser.add_argument('--loader-copy-manifest',type=Path,default=LOADER_COPY_MANIFEST)
|
|
parser.add_argument('--table',choices=tuple(TABLE_FIELDS),default='Talent')
|
|
parser.add_argument('--capture-mode',choices=('per-read','block-fill'),default='per-read')
|
|
parser.add_argument('--block-analysis',type=Path,default=BLOCK_ANALYSIS)
|
|
parser.add_argument('--read-contract',choices=('original',transmog_contract.VARIANT),default='original')
|
|
parser.add_argument('--transmog-analysis',type=Path,default=TRANSMOG_ANALYSIS)
|
|
args=parser.parse_args()
|
|
try:
|
|
result=run(args.executable,args.prefix,args.output,args.scan,args.loader_analysis,args.timeout,table=args.table,capture_mode=args.capture_mode,block_analysis_path=args.block_analysis,official_loader=args.loader,loader_copy_manifest=args.loader_copy_manifest,read_contract=args.read_contract,transmog_analysis_path=args.transmog_analysis)
|
|
print(json.dumps({key:result[key] for key in ('status','pid','observed_stops','hardware_registers_restored')},indent=2))
|
|
return 0 if result['status']==completion_status(args.table) else 1
|
|
except KeyboardInterrupt:
|
|
print(json.dumps(dict(status='observer-cancelled'),indent=2));return 130
|
|
except (OSError,ValueError,RuntimeError) as error:
|
|
print(json.dumps(dict(status='observer-not-completed',error_type=type(error).__name__),indent=2));return 1
|
|
|
|
|
|
if __name__=='__main__':raise SystemExit(main())
|