Files
WoW-Hybrid-gateway/ops/windows_frame_probe.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

335 lines
23 KiB
Python

"""Owned Win64 hardware observation at pinned original70334 witnesses.
The callback runs only while a matching main-thread DEBUG_EVENT holds the
process. No code bytes, instruction/stack pointers, or credential bytes are
written/exported by this observer. Windows-native acceptance remains separate.
"""
from __future__ import annotations
import ctypes as C
import hashlib
import json
import math
import os
from pathlib import Path
import native_runtime_paths
import re
from types import SimpleNamespace
import time
ROOT=Path(__file__).resolve().parents[1]
BASE=0x140000000
FRAME=0x1401DFAD3
LOGIN=0x14242E199
PIPE=0x141E46101
REALM=0x141E46020
ORIGINAL_SHA256='c49ce22c3e0aaeb7a7007a5c5cb792e4c3e6cdecc55a1145a5933fc113e3e57f'
PIPE_PREFIX=bytes.fromhex("33d2488bcfe895480000")
_ALLOWED=frozenset((FRAME,LOGIN,PIPE,REALM))
EXCEPTION=1;CREATE_THREAD=2;CREATE_PROCESS=3;EXIT_THREAD=4;EXIT_PROCESS=5;LOAD_DLL=6
SINGLE_STEP=0x80000004;BREAKPOINT=0x80000003
CONTINUE=0x00010002;NOT_HANDLED=0x80010001
CONTEXT_FLAGS=0x00100013;DEBUG_FLAGS=0x00100010
_DEBUG_FIELDS=('Dr0','Dr1','Dr2','Dr3','Dr6','Dr7')
_REGISTERS=('Rax','Rcx','Rdx','Rbx','Rsp','Rbp','Rsi','Rdi','R8','R9','R10','R11','R12','R13','R14','R15','Rip')
D=C.c_uint32;Q=C.c_uint64;H=C.c_void_p
class CONTEXT64(C.Structure):
_fields_=([(f'P{i}Home',Q) for i in range(1,7)]+
[('ContextFlags',D),('MxCsr',D)]+[(n,C.c_uint16) for n in ('SegCs','SegDs','SegEs','SegFs','SegGs','SegSs')]+
[('EFlags',D)]+[(n,Q) for n in _DEBUG_FIELDS]+[(n,Q) for n in _REGISTERS]+
[('FltSave',C.c_ubyte*512),('VectorRegister',C.c_ubyte*416)]+
[(n,Q) for n in ('VectorControl','DebugControl','LastBranchToRip','LastBranchFromRip','LastExceptionToRip','LastExceptionFromRip')])
class EXCEPTION_RECORD64(C.Structure):
_fields_=[('code',D),('flags',D),('record',H),('address',H),('parameters',D),('information',Q*15)]
class EXCEPTION_INFO(C.Structure):
_fields_=[('record',EXCEPTION_RECORD64),('first_chance',D)]
class CREATE_PROCESS_INFO(C.Structure):
_fields_=[('file',H),('process',H),('thread',H),('base',H),('debug_offset',D),('debug_size',D),('tls',H),('start',H),('image_name',H),('unicode',C.c_uint16)]
class CREATE_THREAD_INFO(C.Structure):
_fields_=[('thread',H),('tls',H),('start',H)]
class LOAD_DLL_INFO(C.Structure):
_fields_=[('file',H),('base',H),('debug_offset',D),('debug_size',D),('image_name',H),('unicode',C.c_uint16)]
class EVENT_UNION(C.Union):
_fields_=[('exception',EXCEPTION_INFO),('process',CREATE_PROCESS_INFO),('thread',CREATE_THREAD_INFO),('dll',LOAD_DLL_INFO),('exit_code',D),('padding',C.c_ubyte*160)]
class DEBUG_EVENT(C.Structure):
_fields_=[('code',D),('pid',D),('tid',D),('data',EVENT_UNION)]
class FILETIME(C.Structure):
_fields_=[('low',D),('high',D)]
def _aligned_context(value=None):
storage=C.create_string_buffer(C.sizeof(CONTEXT64)+15)
pointer=C.cast((C.addressof(storage)+15)&~15,C.POINTER(CONTEXT64))
if value is not None:C.memmove(pointer,C.byref(value),C.sizeof(value))
return storage,pointer
class ProbeError(RuntimeError):
def __init__(self,message,proof):super().__init__(message);self.proof=proof
class _WindowsAPI:
def __init__(self,pid,expected_image,expected_sha256):
if os.name!='nt' or C.sizeof(H)!=8:raise RuntimeError('Native64 Windows observer required')
from windows_process_access import Access
self.access=Access(pid);self.pid=pid;self.pending=None;self.events={};self.thread_handles=[]
self.k=C.WinDLL('kernel32',use_last_error=True)
declarations={
'DebugActiveProcess':([D],C.c_int32),'DebugActiveProcessStop':([D],C.c_int32),
'DebugSetProcessKillOnExit':([C.c_int32],C.c_int32),
'WaitForDebugEventEx':([C.POINTER(DEBUG_EVENT),D],C.c_int32),
'ContinueDebugEvent':([D,D,D],C.c_int32),
'OpenThread':([D,C.c_int32,D],H),'GetProcessIdOfThread':([H],D),
'GetThreadContext':([H,C.POINTER(CONTEXT64)],C.c_int32),
'SetThreadContext':([H,C.POINTER(CONTEXT64)],C.c_int32),
'SuspendThread':([H],D),'ResumeThread':([H],D),'CloseHandle':([H],C.c_int32),
'GetProcessTimes':([H,C.POINTER(FILETIME),C.POINTER(FILETIME),C.POINTER(FILETIME),C.POINTER(FILETIME)],C.c_int32),
'QueryFullProcessImageNameW':([H,D,C.c_wchar_p,C.POINTER(D)],C.c_int32),
'IsWow64Process2':([H,C.POINTER(C.c_uint16),C.POINTER(C.c_uint16)],C.c_int32),
'GetModuleHandleW':([C.c_wchar_p],H),'GetProcAddress':([H,C.c_char_p],H)}
for name,(args,result) in declarations.items():f=getattr(self.k,name);f.argtypes=args;f.restype=result
try:
expected=Path(expected_image or ROOT/'runtime/native-client/_classic_beta_/WowB.exe').resolve(strict=True)
buffer=C.create_unicode_buffer(32768);length=D(len(buffer))
self._ok(self.k.QueryFullProcessImageNameW(self.access.handle,0,buffer,C.byref(length)))
if Path(buffer.value).resolve(strict=True)!=expected:raise ValueError('Owned image path differs')
digest=hashlib.sha256(expected.read_bytes()).hexdigest()
if expected_sha256 is None:
metadata=json.loads((native_runtime_paths.engine_journal(ROOT)).read_text())
allowed={metadata.get('original_sha256'),metadata.get('patched_sha256')}
else:allowed={expected_sha256}
if digest not in {x for x in allowed if isinstance(x,str) and re.fullmatch('[0-9a-f]{64}',x)}:raise ValueError('Owned image digest differs')
process_machine=C.c_uint16();native_machine=C.c_uint16()
self._ok(self.k.IsWow64Process2(self.access.handle,C.byref(process_machine),C.byref(native_machine)))
if process_machine.value!=0 or native_machine.value!=0x8664:raise ValueError('Owned process is not native AMD64')
self.created,self.exited=self.process_times(self.access.handle)
if self.exited:raise ValueError('Owned process already exited')
header=self.access.read(BASE,64)
if header[:2]!=b'MZ':raise ValueError('Pinned main image base differs')
self.image_sha256=digest
self.attach_breakpoints=self._attach_breakpoints()
except BaseException:self.access.close();raise
def _ok(self,value):
if not value:raise C.WinError(C.get_last_error())
return value
def process_times(self,handle):
values=[FILETIME() for _ in range(4)];self._ok(self.k.GetProcessTimes(handle,*(C.byref(x) for x in values)))
return values[0].low|(values[0].high<<32),values[1].low|(values[1].high<<32)
def is_alive(self):return self.process_times(self.access.handle)[1]==0
def _attach_breakpoints(self):
module=self.k.GetModuleHandleW('ntdll.dll');function=self.k.GetProcAddress(module,b'DbgBreakPoint')
if not module or not function or C.string_at(function,2)!=b'\xcc\xc3':raise ValueError('Known OS attach breakpoint unavailable')
bases={lo for lo,hi,perm,offset,name in self.access.maps if offset=='00000000' and Path(name).name.casefold()=='ntdll.dll'}
if len(bases)!=1:raise ValueError('Owned OS attach module differs')
address=next(iter(bases))+function-module
if not self.access.allowed(address,2,'x') or self.access.read(address,2)!=b'\xcc\xc3':raise ValueError('Known remote OS attach breakpoint differs')
return frozenset((address,address+1))
def validate_entry(self,entry,executing=False):
if executing:self.access.refresh_maps()
# Original Login/constructor-return pages may still be naturally cold
# when armed. Execution must be RX and retain the pinned bytes at hit.
valid=self.access.allowed(entry,1,'x') if executing or entry==FRAME else any(lo<=entry<hi for lo,hi,*_ in self.access.maps)
if not valid:raise ValueError('Original witness mapping differs')
def verify_prefix(self,entry,prefix):
if self.access.read(entry,len(prefix))!=prefix:raise ValueError('Original executed prefix differs')
def query_page(self,address):return self.access.query_page(address)
def verify_readable_prefix(self,address,prefix,region):return self.access.read_pinned_prefix(address,prefix,region)
def attach(self):self._ok(self.k.DebugActiveProcess(self.pid))
def no_kill(self):self._ok(self.k.DebugSetProcessKillOnExit(False))
def wait(self,milliseconds):
raw=DEBUG_EVENT()
if not self.k.WaitForDebugEventEx(C.byref(raw),milliseconds):
if C.get_last_error()==121:return None
raise C.WinError(C.get_last_error())
event=SimpleNamespace(kind=int(raw.code),pid=int(raw.pid),tid=int(raw.tid),exception=0,address=0,first_chance=0,base=0,process_handle=0)
self.pending=event
if event.kind==EXCEPTION:event.exception=int(raw.data.exception.record.code);event.address=int(raw.data.exception.record.address or 0);event.first_chance=int(raw.data.exception.first_chance)
if event.kind==CREATE_PROCESS:
event.base=int(raw.data.process.base or 0);event.process_handle=raw.data.process.process
self.events[(event.pid,0)]=raw.data.process.process;self.events[(event.pid,event.tid)]=raw.data.process.thread
if raw.data.process.file:self.k.CloseHandle(raw.data.process.file)
if event.kind==CREATE_THREAD:self.events[(event.pid,event.tid)]=raw.data.thread.thread
if event.kind==LOAD_DLL and raw.data.dll.file:self.k.CloseHandle(raw.data.dll.file)
return event
def primary(self,event,expected_tid):
if event.pid!=self.pid or event.base!=BASE or not event.process_handle:raise ValueError('Debug process identity differs')
if self.process_times(event.process_handle)[0]!=self.created:raise ValueError('Debug process creation identity differs')
if expected_tid is not None and event.tid!=expected_tid:raise ValueError('Owned primary thread differs')
handle=self.k.OpenThread(0x0008|0x0010|0x0002|0x0040,False,event.tid)
self._ok(handle)
if self.k.GetProcessIdOfThread(handle)!=self.pid:self.k.CloseHandle(handle);raise ValueError('Primary thread owner differs')
self.thread_handles.append(handle);return handle
def get_context(self,thread):
backing,pointer=_aligned_context();pointer.contents.ContextFlags=CONTEXT_FLAGS
self._ok(self.k.GetThreadContext(thread,pointer));return CONTEXT64.from_buffer_copy(bytes(pointer.contents))
def set_context(self,thread,context):
backing,pointer=_aligned_context(context);pointer.contents.ContextFlags=DEBUG_FLAGS;self._ok(self.k.SetThreadContext(thread,pointer))
def suspend(self,thread):
if self.k.SuspendThread(thread)==0xffffffff:raise C.WinError(C.get_last_error())
def resume(self,thread):
if self.k.ResumeThread(thread)==0xffffffff:raise C.WinError(C.get_last_error())
def continue_event(self,event,status):
self._ok(self.k.ContinueDebugEvent(event.pid,event.tid,status));self.pending=None
# Windows closes these event handles when their EXIT event continues.
if event.kind==EXIT_THREAD:self.events.pop((event.pid,event.tid),None)
if event.kind==EXIT_PROCESS:
self.events={k:v for k,v in self.events.items() if k[0]!=event.pid}
def detach(self):self._ok(self.k.DebugActiveProcessStop(self.pid))
def close(self):
for handle in set(self.events.values())|set(self.thread_handles):
if handle:self.k.CloseHandle(handle)
self.events.clear();self.thread_handles.clear();self.access.close()
# A failed restoration never produces a false successful detach. Retain handles
# so the owner can keep the failed startup observable instead of killing it.
_HELD={}
def observe(pid,callback,timeout=30,expected_image=None,*,entry=FRAME,on_registers=None,followup=None,on_armed=None,on_resumed_armed=None,expected_thread_id=None,expected_sha256=None,_api=None,_clock=time.monotonic):
if type(pid) is not int or pid<=0 or type(entry) is not int or entry not in _ALLOWED:raise ValueError('Exact owned PID and pinned witness required')
manual_login_wait=timeout is None and entry==LOGIN
if timeout is None:
if not manual_login_wait or callback is not None or followup is not None:
raise ValueError('Only original manual Login may wait for its owned lifetime')
elif type(timeout) not in (int,float) or not math.isfinite(timeout) or not 0<timeout<=120:
raise ValueError('Bounded observer timeout required')
if entry==FRAME and (not callable(callback) or on_registers is not None):raise ValueError('Frame caller callback required')
if entry==LOGIN and (not callable(on_registers) or callback is not None):raise ValueError('Original Login register callback required')
if entry==PIPE and (not callable(callback) or on_registers is not None):raise ValueError('Original constructor callback required')
realm_pages=entry==REALM
if realm_pages and (callback is not None or on_registers is not None or followup is not None or on_armed is not None or not callable(on_resumed_armed) or expected_thread_id is None or expected_sha256!=ORIGINAL_SHA256):
raise ValueError('Fixed read-only realm profile and resumed-arm callback required')
if followup is not None:
if (entry!=FRAME or type(followup) not in (tuple,list) or len(followup)!=3 or
followup[0]!=PIPE or followup[1]!=PIPE_PREFIX or not callable(followup[2])):
raise ValueError('Only the pinned constructor-return followup is admitted')
if on_armed is not None and not callable(on_armed):raise ValueError('Armed notification callback required')
if on_resumed_armed is not None and not callable(on_resumed_armed):raise ValueError('Resumed-arm callback required')
if on_resumed_armed is not None and not realm_pages:raise ValueError('Resumed-arm callback belongs to fixed realm profile')
if expected_thread_id is not None and (type(expected_thread_id) is not int or expected_thread_id<=0):raise ValueError('Exact primary thread ID required')
if pid in _HELD:raise ValueError('Previous failed observer cleanup remains owned')
api=_api or _WindowsAPI(pid,expected_image,expected_sha256)
proof={'pid':pid,'entry':hex(entry),'status':'pending','main_thread_observed':False,'callback_invoked':False,'code_bytes_modified':False,'instruction_pointer_modified':False,'credential_bytes_exported':False,'debug_registers_restored':False,'detached':False,'observed_events':0,'manual_login_lifetime_wait':manual_login_wait}
attached=False;thread=None;saved=None;armed=False;pending=None;pending_status=CONTINUE;result=None;result_valid=False;stage='first';client_exited=False
try:
api.validate_entry(entry)
if followup is not None or realm_pages:api.validate_entry(PIPE)
api.attach();attached=True;api.no_kill();deadline=None if manual_login_wait else _clock()+timeout
initial_breakpoint=False
while deadline is None or _clock()<deadline:
pending=api.wait(100 if deadline is None else min(100,max(1,int((deadline-_clock())*1000))))
if pending is None:
if manual_login_wait and not api.is_alive():
client_exited=True;armed=False;proof['status']='client-exited';proof['client_exited']=True
proof['debug_registers_retired_with_process']=saved is not None
break
continue
pending_status=NOT_HANDLED if pending.kind==EXCEPTION else CONTINUE
proof['observed_events']+=1
if proof['observed_events']>8192:raise RuntimeError('Bounded event count exhausted')
if pending.pid!=pid:raise RuntimeError('Unexpected debug process event')
if pending.kind==CREATE_PROCESS:
if thread is not None:raise RuntimeError('Duplicate primary process event')
thread=api.primary(pending,expected_thread_id);proof['thread_id']=pending.tid
context=api.get_context(thread);saved={name:int(getattr(context,name)) for name in _DEBUG_FIELDS}
if saved['Dr7']&0xff:raise RuntimeError('Existing hardware debug registers preserved')
context.Dr0=entry;context.Dr6=0;context.Dr7=(saved['Dr7']&~(0xf<<16)&~3)|1
if followup is not None or realm_pages:context.Dr1=PIPE;context.Dr7=(context.Dr7&~(0xf<<20)&~(3<<2))|(1<<2)
# A failing SetThreadContext can have partially changed DRs;
# retain cleanup ownership before attempting the write.
armed=True;api.set_context(thread,context)
if on_armed is not None:on_armed()
elif pending.kind==EXIT_PROCESS:
client_exited=True;armed=False;proof['status']='client-exited';proof['client_exited']=True
proof['debug_registers_retired_with_process']=saved is not None
api.continue_event(pending,CONTINUE);pending=None;attached=False;proof['detached']=True
proof['detach_basis']='continued original EXIT_PROCESS event';break
elif pending.kind==EXCEPTION:
if (not initial_breakpoint and pending.exception==BREAKPOINT and pending.first_chance and pending.address in api.attach_breakpoints):
initial_breakpoint=True;pending_status=CONTINUE
elif pending.exception==SINGLE_STEP and armed and pending.tid==proof.get('thread_id'):
context=api.get_context(thread);slot=1 if stage=='followup' else 0;target=PIPE if slot else entry
if (followup is not None or realm_pages) and stage=='first' and context.Dr6&2:
# Dr1 belongs to us even before a frame intent. Never
# deliver our premature observer exception to the game.
pending_status=CONTINUE
raise RuntimeError('Constructor witness preceded frame intent')
if context.Dr6&(1<<slot):
pending_status=CONTINUE
if context.Rip!=target or getattr(context,'Dr'+str(slot))!=target:raise RuntimeError('Hardware stop differs from original witness')
if not realm_pages:
api.validate_entry(target,executing=True)
if target==PIPE:api.verify_prefix(PIPE,PIPE_PREFIX)
proof['main_thread_observed']=True
if realm_pages:
region=api.query_page(PIPE)
sample={'sequence':len(proof.setdefault('page_samples',[]))+1,'site':'return' if stage=='followup' else 'entry','pid':pid,'tid':pending.tid,**region}
if stage=='followup':sample['return_prefix_verified']=api.verify_readable_prefix(PIPE,PIPE_PREFIX,region)
proof['page_samples'].append(sample)
if stage=='followup':proof['status']='observed';break
context.Dr0=saved['Dr0'];context.Dr6=0;context.Dr7=(context.Dr7&~3)|(saved['Dr7']&3)
api.set_context(thread,context);stage='followup';proof['entry_observed']=True
api.continue_event(pending,pending_status);pending=None
continue
if stage=='followup':
followup_result=followup[2](None)
if len(json.dumps(followup_result,allow_nan=False).encode())>4096:raise RuntimeError('Bounded followup result exceeded')
proof['followup_observed']=True;proof['followup_entry']=hex(PIPE);proof['followup_result']=followup_result
proof['status']='observed';break
proof['callback_invoked']=True
if entry==FRAME:result=callback(hex(FRAME))
elif entry==PIPE:result=callback(None)
else:
registers=SimpleNamespace(**{name.lower():int(getattr(context,name)) for name in _REGISTERS},main_thread=True,thread_id=pending.tid)
result=on_registers(registers)
if len(json.dumps(result,allow_nan=False).encode())>4096:raise RuntimeError('Bounded callback result exceeded')
result_valid=True
if followup is None:proof['status']='observed';break
# Dr1 was armed before the first callback wrote the real
# open intent. Disable only first-stage Dr0; no gap.
context.Dr0=saved['Dr0'];context.Dr6=0;context.Dr7=(context.Dr7&~3)|(saved['Dr7']&3)
api.set_context(thread,context);stage='followup';proof['frame_callback_completed']=True
was_create=pending.kind==CREATE_PROCESS
api.continue_event(pending,pending_status);pending=None
if realm_pages and was_create:
# The initial CREATE_PROCESS event has been continued; the
# child can execute with both slots installed before host command7.
proof['resumed_armed']=True
on_resumed_armed({'pid':pid,'tid':proof['thread_id'],'image_sha256':api.image_sha256,'created':api.created})
else:proof['status']='followup-timeout' if stage=='followup' else 'timeout'
except BaseException as exc:
proof['status']='failed';proof['error_type']=type(exc).__name__
finally:
pending=pending or getattr(api,'pending',None)
cleanup_error=None
try:
alive=api.is_alive() if attached else not client_exited
if armed and thread is not None and alive:
suspended=False
try:
if pending is None:api.suspend(thread);suspended=True
context=api.get_context(thread)
for name,value in saved.items():setattr(context,name,value)
api.set_context(thread,context);armed=False;proof['debug_registers_restored']=True
finally:
if suspended and not armed:api.resume(thread)
elif armed and not alive:
armed=False;proof['client_exited']=True;proof['debug_registers_retired_with_process']=True
elif saved is not None and not client_exited:proof['debug_registers_preserved']=True
if pending is not None:api.continue_event(pending,pending_status);pending=None
if attached:
try:api.detach();proof['detached']=True;attached=False
except BaseException:
if api.is_alive():raise
attached=False;proof['client_exited']=True;proof['detach_basis']='owned process exit confirmed; debug target no longer alive'
except BaseException as exc:
cleanup_error=exc;proof['cleanup_error_type']=type(exc).__name__;proof['status']='cleanup-failed'
if cleanup_error is not None:_HELD[pid]=api
else:api.close()
if proof['callback_invoked'] and result_valid:proof['operation_result']=result
elif proof['callback_invoked']:proof['callback_result_withheld']=True
if proof['status'] in ('failed','cleanup-failed'):raise ProbeError('Owned Windows observation failed; inspect bounded proof',proof) from None
return proof
def observe_realm_pages(pid,timeout=30,expected_image=None,*,on_resumed_armed,expected_thread_id,expected_sha256,_api=None,_clock=time.monotonic):
"""One fixed original OpenRealm entry/constructor-return page observation."""
return observe(pid,None,timeout,expected_image,entry=REALM,on_resumed_armed=on_resumed_armed,
expected_thread_id=expected_thread_id,expected_sha256=expected_sha256,_api=_api,_clock=_clock)