Files
WoW-Hybrid-gateway/ops/native_registration_trace.py
praxisandClaude Fable 5.2 8a24c445b0 Content pipeline and operator tools
367 files, from working commit b1a079a.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-19 01:32:48 +02:00

306 lines
20 KiB
Python

"""Observe real70334 UI registration/allocator calls on an owned Wine child.
No injected calls, code patches, Lua writes, credential reads or state changes.
Reads are limited to known API names, one return address and the main Lua-state
pointer used by the actual registration helper. All genuine signals are retained.
"""
import ctypes as C
import json
import os
from pathlib import Path
import signal
import struct
import time
from engine_main_thread_probe import Probe,Registers,ROOT
REGISTER=0x14075a440
CREATE=0x144596af0
READY=0x14242fd80
LUA_GLOBAL=0x14075a46b+0x729a24d
# One declared original global only. This is not an API inventory mode.
REGIONAL_NAME_RVA=0x4e1bf30
REGIONAL_REGISTER_RVA=0x75a440
REGIONAL_EXACT_NAME=bytes.fromhex("526567696f6e616c556e697175654e616d6573456e61626c656400")
REGIONAL_MAX_ROWS=4096
REGIONAL_TOTAL_ROWS=16384
REGIONAL_MAX_STOPS=256
TOOLTIP_NAME_RVA=0x4e0aba8
TOOLTIP_EXACT_NAME=b'GetSpellBookItem\0'
TOOLTIP_NAMESPACE=b'C_TooltipInfo\0'
def exact_global_callback(read,readable,table,count,name_pointer,image_bounds):
"""Inspect name-pointer cells only; read one callback only for one match."""
if type(count)is not int or not 1<=count<=REGIONAL_MAX_ROWS:
return {"status":"row-count-held","rows":0}
if type(table)is not int or table<=0 or table>0xffffffffffffffff-count*16 or not readable(table,count*16):
return {"status":"table-mapping-held","rows":0}
matches=[]
for index in range(count):
raw=read(table+index*16,8)
if len(raw)!=8:return {"status":"short-name-pointer-held","rows":index}
if struct.unpack("<Q",raw)[0]==name_pointer:matches.append(index)
if not matches:return {"status":"not-this-registration","rows":count}
if len(matches)!=1:return {"status":"ambiguous-target-held","rows":count}
index=matches[0];raw=read(table+index*16+8,8)
if len(raw)!=8:return {"status":"short-callback-held","rows":count}
callback=struct.unpack("<Q",raw)[0]
if not image_bounds[0]<=callback<image_bounds[1]:
return {"status":"non-image-callback-held","rows":count}
return {"status":"exact-global-binding-candidate","rows":count,"row_index":index,
"callback":callback,"callback_rva":callback-image_bounds[0],"callback_page":callback&~0xfff}
def exact_spellbook_callback(read,readable,table,count,namespace_pointer,name_pointer,image_bounds,lua_global):
"""Qualify the exact namespace before inspecting any registration rows."""
if type(count)is not int or not 1<=count<=REGIONAL_MAX_ROWS:
return {"status":"row-count-held","rows":0}
if (type(namespace_pointer)is not int or namespace_pointer<=0 or
not readable(namespace_pointer,len(TOOLTIP_NAMESPACE))):
return {"status":"namespace-mapping-held","rows":0}
if read(namespace_pointer,len(TOOLTIP_NAMESPACE))!=TOOLTIP_NAMESPACE:
return {"status":"not-this-namespace","rows":0}
if not image_bounds[0]<=lua_global<=image_bounds[1]-8 or not readable(lua_global,8):
return {"status":"registration-state-mapping-held","rows":0}
raw=read(lua_global,8)
if len(raw)!=8:return {"status":"registration-state-short-held","rows":0}
state=struct.unpack('<Q',raw)[0]
if not state or not readable(state,1):return {"status":"registration-state-held","rows":0}
result=exact_global_callback(read,readable,table,count,name_pointer,image_bounds)
if result['status']=='exact-global-binding-candidate':
result['status']='exact-namespace-binding-candidate'
result.update(lua_state=state,lua_global=lua_global)
return result
def exact_owned_image(maps_text,image_path):
"""Rebase only an explicitly owned file mapping; no image/name inventory."""
expected=os.path.realpath(image_path);mappings=[];bases=[]
for line in maps_text.splitlines():
columns=line.split(None,5)
if len(columns)<5:continue
try:start,end=(int(x,16)for x in columns[0].split("-"));offset=int(columns[2],16)
except ValueError:continue
path=columns[5]if len(columns)>5 else""
mappings.append((start,end,columns[1],path))
if path and not path.endswith(" (deleted)") and os.path.realpath(path)==expected and offset==0:
bases.append(start)
if len(set(bases))!=1:raise ValueError("owned image header mapping is not unique")
return bases[0],mappings
def registration_namespace_whitelist(value):
"""Bound an opt-in observation to public C_ namespace names only."""
if value is None:return None
if type(value)not in (tuple,list) or not 1<=len(value)<=8:raise ValueError('Require one to eight exact namespace names')
if any(not isinstance(name,str) or not name.startswith('C_') or not 3<=len(name)<=64 or any(not(c=='_'or'0'<=c<='9'or'A'<=c<='Z'or'a'<=c<='z')for c in name)for name in value):raise ValueError('Require bounded exact public namespace names')
if len(set(value))!=len(value):raise ValueError('Duplicate namespace observation target')
return frozenset(value)
def registration_namespace_selected(name,seen,whitelist=None):
if whitelist is None:return bool(name)and(seen<8 or name=='C_Login')
return seen<128 and name in whitelist
class RegistrationTrace(Probe):
def __init__(self,pid,abi_path=None,*,exact_regional_global=False,exact_spellbook_tooltip=False,owned_image_path=None,result_path=None,namespace_whitelist=None):
namespace_whitelist=registration_namespace_whitelist(namespace_whitelist)
if exact_regional_global and exact_spellbook_tooltip:raise ValueError('Choose one exact registration scope')
if namespace_whitelist is not None and(exact_regional_global or exact_spellbook_tooltip):raise ValueError('Namespace observation and exact callback observation are separate scopes')
if (exact_regional_global or exact_spellbook_tooltip) and (owned_image_path is None or result_path is None):
raise ValueError("Exact global observation needs owned image and private result paths")
super().__init__(pid,abi_path=abi_path)
self.stage='trace-start';self.deadline=time.monotonic()+90
self.events=[];self.pending=None;self.returns=0;self.login_seen=False;self.ready_seen=False
self.names=0;self.targets=(REGISTER,CREATE,READY,0)
self.exact_regional_global=exact_regional_global;self.exact_spellbook_tooltip=exact_spellbook_tooltip;self.owned_image_path=owned_image_path
self.registration_result_path=Path(result_path)if result_path else ROOT/'runtime/native-registration-trace.json'
self.namespace_whitelist=namespace_whitelist
self.exact_rows=0;self.exact_stops=0;self.exact_image_bounds=None;self.exact_name_pointer=None
def exact_mode(self):
return self.exact_regional_global or getattr(self,'exact_spellbook_tooltip',False)
def read_word(self,address):
fd=os.open(f'/proc/{self.pid}/mem',os.O_RDONLY)
try:return struct.unpack('<Q',os.pread(fd,8,address))[0]
finally:os.close(fd)
def namespace(self,address):
if not 0x144a00000<=address<0x148500000:return None
fd=os.open(f'/proc/{self.pid}/mem',os.O_RDONLY)
try:name=os.pread(fd,64,address).split(b'\0',1)[0]
finally:os.close(fd)
if not name.startswith(b'C_') or not name or any(not (c==95 or 48<=c<=57 or 65<=c<=90 or 97<=c<=122) for c in name):return None
return name.decode('ascii')
def record(self,status,**fields):
out={'pid':self.pid,'status':status,'observed_stops':self.stops,
'code_bytes_modified':False,'engine_calls_injected':False,'lua_memory_modified':False,
'engine_world_entry':False,'events':self.events,**fields}
if getattr(self,'owned_lifetime',None)is not None:out['owned_lifetime']=self.owned_lifetime
if getattr(self,'namespace_whitelist',None)is not None:out['namespace_scope']={'names':sorted(self.namespace_whitelist),'max_namespace_records':128,'method_rows_read':False,'existing_create_and_ready_observation_retained':True}
if self.exact_mode():
out['exact_scope']={'target':'C_TooltipInfo.GetSpellBookItem'if getattr(self,'exact_spellbook_tooltip',False)else'RegionalUniqueNamesEnabled','rows_examined':self.exact_rows,
'registration_stops':self.exact_stops,'other_names_or_callbacks_read':False,
'code_pages_read':False,'max_rows_per_table':REGIONAL_MAX_ROWS,
'max_total_rows':REGIONAL_TOTAL_ROWS,'max_registration_stops':REGIONAL_MAX_STOPS}
target=self.registration_result_path
temporary=target.with_suffix('.new');temporary.write_text(json.dumps(out,indent=2)+'\n');temporary.chmod(0o600);temporary.replace(target)
def arm(self):
for i,address in enumerate(self.targets):self.debug(i,address)
self.debug(6,0);self.debug(7,0x1 if self.exact_mode() else 0x15) # Exact mode uses one execution slot.
def exact_rebase(self):
tooltip=getattr(self,'exact_spellbook_tooltip',False)
name_rva=TOOLTIP_NAME_RVA if tooltip else REGIONAL_NAME_RVA
expected_name=TOOLTIP_EXACT_NAME if tooltip else REGIONAL_EXACT_NAME
base,mappings=exact_owned_image((Path('/proc')/str(self.pid)/'maps').read_text(),self.owned_image_path)
readable=lambda address,size:any(a<=address and address+size<=b and'r'in permissions for a,b,permissions,path in mappings)
fd=os.open(f'/proc/{self.pid}/mem',os.O_RDONLY)
try:
read=lambda address,size:os.pread(fd,size,address)
if not readable(base,64):raise ValueError("owned image header unreadable")
dos=read(base,64)
if len(dos)!=64 or dos[:2]!=b'MZ':raise ValueError("owned image header differs")
nt=base+struct.unpack_from('<I',dos,60)[0]
if not readable(nt,84):raise ValueError("owned image PE header unreadable")
header=read(nt,84)
if len(header)!=84 or header[:4]!=bytes.fromhex("50450000") or struct.unpack_from('<H',header,24)[0]!=0x20b:
raise ValueError("owned image PE64 header differs")
size=struct.unpack_from('<I',header,80)[0]
if size<=name_rva+len(expected_name) or size>0x40000000:
raise ValueError("owned image extent differs")
name=base+name_rva
if not readable(name,len(expected_name)) or read(name,len(expected_name))!=expected_name:
raise ValueError("exact original global name differs")
finally:os.close(fd)
self.exact_image_bounds=(base,base+size);self.exact_name_pointer=name
if tooltip:self.exact_lua_global=base+(LUA_GLOBAL-0x140000000)
self.targets=(base+REGIONAL_REGISTER_RVA,0,0,0)
def observe_exact_global(self,registers):
self.exact_stops+=1;count=registers.rdx&0xffffffff
if self.exact_stops>REGIONAL_MAX_STOPS or self.exact_rows+count>REGIONAL_TOTAL_ROWS:
self.finish('exact-global-bounded-search-finished');return
maps=(Path('/proc')/str(self.pid)/'maps').read_text()
_,mappings=exact_owned_image(maps,self.owned_image_path)
def readable(address,size):
return any(a<=address and address+size<=b and'r'in permissions for a,b,permissions,path in mappings)
fd=os.open(f'/proc/{self.pid}/mem',os.O_RDONLY)
try:
read=lambda address,size:os.pread(fd,size,address)
result=exact_global_callback(read,readable,registers.rcx,count,self.exact_name_pointer,self.exact_image_bounds)
self.exact_rows+=result['rows']
if result['status']!='exact-global-binding-candidate':return
# A global registration has no namespace or an empty namespace.
# Inspect only this one byte after the exact target-name match.
namespace=registers.r8
if namespace and(not readable(namespace,1)or read(namespace,1)!=bytes.fromhex("00")):return
finally:os.close(fd)
callback=result['callback'];page=result['callback_page']
mapping=next(((a,b,permissions)for a,b,permissions,path in mappings if a<=callback<b),None)
self.events.append({'kind':'exact-original-global-binding','name':'RegionalUniqueNamesEnabled',
'name_pointer':hex(self.exact_name_pointer),'callback':hex(callback),'callback_rva':hex(result['callback_rva']),
'callback_page':hex(page),'image_base':hex(self.exact_image_bounds[0]),'image_end':hex(self.exact_image_bounds[1]),
'module':str(self.owned_image_path),'row_index':result['row_index'],'namespace_empty':True,
'callback_mapping':{'start':hex(mapping[0]),'end':hex(mapping[1]),'permissions':mapping[2]}if mapping else None,
'code_page_read':False,'registration_rows_examined':self.exact_rows,'registration_stops':self.exact_stops})
self.finish('exact-regional-global-binding-observed')
def observe_exact_spellbook(self,registers):
self.exact_stops+=1;count=registers.rdx&0xffffffff
if self.exact_stops>REGIONAL_MAX_STOPS or self.exact_rows+count>REGIONAL_TOTAL_ROWS:
self.finish('exact-spellbook-bounded-search-finished');return
_,mappings=exact_owned_image((Path('/proc')/str(self.pid)/'maps').read_text(),self.owned_image_path)
def readable(address,size):
return any(a<=address and address+size<=b and'r'in permissions for a,b,permissions,path in mappings)
fd=os.open(f'/proc/{self.pid}/mem',os.O_RDONLY)
try:
result=exact_spellbook_callback(lambda address,size:os.pread(fd,size,address),readable,
registers.rcx,count,registers.r8,self.exact_name_pointer,self.exact_image_bounds,self.exact_lua_global)
finally:os.close(fd)
self.exact_rows+=result['rows']
if result['status']!='exact-namespace-binding-candidate':return
callback=result['callback']
mapping=next(((a,b,permissions)for a,b,permissions,path in mappings if a<=callback<b),None)
code_ready=mapping is not None and 'x'in mapping[2]
self.events.append({'kind':'exact-original-namespace-binding','namespace':'C_TooltipInfo','name':'GetSpellBookItem',
'name_pointer':hex(self.exact_name_pointer),'callback':hex(callback),'callback_rva':hex(result['callback_rva']),
'callback_page':hex(result['callback_page']),'image_base':hex(self.exact_image_bounds[0]),'image_end':hex(self.exact_image_bounds[1]),
'module':str(self.owned_image_path),'row_index':result['row_index'],
'lua_global':hex(result['lua_global']),'registration_lua_state':hex(result['lua_state']),
'lua_state_layout_dereferenced':False,'closure_layout_assumed':False,
'callback_mapping':{'start':hex(mapping[0]),'end':hex(mapping[1]),'permissions':mapping[2]}if mapping else None,
'callback_code_ready':code_ready,'native_call_admitted':False,
'code_page_read':False,'registration_rows_examined':self.exact_rows,'registration_stops':self.exact_stops})
self.finish('exact-spellbook-namespace-binding-observed'if code_ready else'exact-spellbook-binding-observed-code-held')
def finish(self,status,**diagnostics):
self.restore_debug();self.ptrace('detach',0,self.pending_signal)
self.attached=False;self.stopped=False;self.done=True
self.record(status,hardware_registers_restored=True,**diagnostics)
def poll(self):
if self.done:return
if not self.attached:
if (Path('/proc')/str(self.pid)/'comm').read_text().strip()!='WowB.exe':
if time.monotonic()>self.deadline:self.done=True;self.record('no-owned-WowB-before-timeout')
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.record('client-exited');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':
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
if self.exact_mode():
try:self.exact_rebase()
except (OSError,ValueError,struct.error) as exc:
self.finish('exact-owned-image-binding-held',binding_error={'type':type(exc).__name__,'errno':getattr(exc,'errno',None),'reason':str(exc)[:512]});return
self.arm();self.stage='tracing';self.record('observational-trace-armed')
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(hits&(1<<i) and address==registers.rip for i,address in enumerate(self.targets)))
if own:self.pending_signal=0
if self.stage=='cancel-stop':self.finish('bounded-trace-finished');return
if own:
self.debug(6,0)
if self.exact_mode():
try:
if getattr(self,'exact_spellbook_tooltip',False):self.observe_exact_spellbook(registers)
else:self.observe_exact_global(registers)
except (OSError,ValueError,struct.error):
self.finish('exact-global-read-held');return
if self.done:return
elif registers.rip==REGISTER:
name=self.namespace(registers.r8)
if registration_namespace_selected(name,self.names,getattr(self,'namespace_whitelist',None)):
lua=self.read_word(LUA_GLOBAL)
self.events.append({'kind':'namespace','name':name,'count':registers.rdx&0xffffffff,
'table':hex(registers.rcx),'lua_state':hex(lua),'thread_id':self.pid,
'windows_bridge_loaded':'GWNativeBridge.dll' in (Path('/proc')/str(self.pid)/'maps').read_text()})
self.names+=1
if name=='C_Login':self.login_seen=True
self.record('observing-native-registration')
elif registers.rip==CREATE and self.pending is None and self.returns<4:
caller=self.read_word(registers.rsp)
if 0x140001000<=caller<0x144a00000:
event={'kind':'native-table-create','lua_state':hex(registers.rcx),
'global_lua_matches':registers.rcx==self.read_word(LUA_GLOBAL),
'array_count':registers.rdx&0xffffffff,'hash_count':registers.r8&0xffffffff,
'caller_return':hex(caller),'entry_stack_alignment':registers.rsp%16,'thread_id':self.pid}
self.events.append(event);self.pending=(registers.rsp,event)
self.targets=(REGISTER,CREATE,READY,caller)
self.debug(3,caller);self.debug(7,0x51) # Disable nested create entries; enable exact return.
self.record('observing-native-table-return')
elif registers.rip==READY:
self.events.append({'kind':'native-login-ready','lua_state':hex(registers.rcx),
'global_lua_matches':registers.rcx==self.read_word(LUA_GLOBAL),'thread_id':self.pid})
self.ready_seen=True;self.debug(2,0);self.targets=(REGISTER,CREATE,0,self.targets[3]);self.debug(7,self.debug(7)&~0x10)
self.record('native-login-state-observed')
elif self.pending and registers.rip==self.targets[3] and registers.rsp==self.pending[0]+8:
self.pending[1]['returned_normally']=True;self.pending=None;self.returns+=1
self.debug(3,0);self.targets=(REGISTER,CREATE,self.targets[2],0)
self.debug(7,0x5 if self.targets[2]==0 else 0x15)
if self.returns>=4:self.debug(7,self.debug(7)&~4)
self.record('native-table-return-observed')
if self.login_seen and self.ready_seen and self.returns>=4:self.finish('native-registration-and-allocator-observed');return
self.ptrace('cont',0,self.pending_signal);self.stopped=False