Files
WoW-Hybrid-gateway/tests/windows_native_bootstrap_test.py
praxisandClaude Fable 5.2 7f2139d8d0 Offline test fixtures
883 files, from working commit b1a079a.

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

249 lines
19 KiB
Python

import ctypes as C,json,struct,tempfile,unittest
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import patch
import windows_native_bootstrap as b
class OwnedFiles(unittest.TestCase):
def test_exact_regular_pin_and_path_boundaries(self):
with tempfile.TemporaryDirectory() as d:
root=Path(d);p=root/'owned.dll';p.write_bytes(b'owned');entry={'path':'owned.dll','sha256':b.digest(p)}
self.assertEqual(b.owned_file(root,entry),p)
for name in ['../owned.dll',str(p)]:
with self.assertRaises(ValueError):b.owned_file(root,{**entry,'path':name})
with self.assertRaises(ValueError):b.owned_file(root,{**entry,'sha256':'0'*64})
def test_symlink_not_owned(self):
with tempfile.TemporaryDirectory() as d:
root=Path(d);p=root/'one.dll';p.write_bytes(b'owned');(root/'link.dll').symlink_to(p)
with self.assertRaises(ValueError):b.owned_file(root,{'path':'link.dll','sha256':b.digest(p)})
def test_actual_export_reader_and_corrupt_architecture(self):
source=Path(__file__).resolve().parents[1]/'build/windows-native-bridge-20261022/GWNativeWire.dll'
if not source.exists():self.skipTest('Built PE fixture absent')
self.assertIn('gw_wire_frame_data',b.pe_exports(source))
with tempfile.TemporaryDirectory() as d:
raw=bytearray(source.read_bytes());pe=struct.unpack_from('<I',raw,60)[0];raw[pe+4:pe+6]=b'\x4c\x01';p=Path(d)/'bad.dll';p.write_bytes(raw)
with self.assertRaises(ValueError):b.pe_exports(p)
class ForwardedLoader(unittest.TestCase):
def test_rebases_actual_forwarder_owner_not_kernel32_or_local_address(self):
api=b.Kernel.__new__(b.Kernel);local=0x7ff000000000;remote=0x180000000;path=str(Path('/system/KernelBase.dll').resolve())
def owner(flags,address,out):
self.assertEqual(address,local+0x1234);out._obj.value=local;return 1
def filename(module,buffer,size):buffer.value=path;return len(path)
api.k=SimpleNamespace(GetModuleHandleW=lambda name:0x700000,GetProcAddress=lambda m,n:local+0x1234,GetModuleHandleExW=owner,GetModuleFileNameW=filename)
api.modules=lambda pid:[{'base':remote,'size':0x10000,'path':path}]
self.assertEqual(api.loader(123),remote+0x1234)
def test_same_basename_foreign_path_and_duplicate_module_refused(self):
path=str(Path('/system/KernelBase.dll').resolve());row={'base':1,'size':2,'path':path}
for modules in [[{**row,'path':str(Path('/foreign/KernelBase.dll').resolve())}],[row,row]]:
with self.assertRaises(ValueError):b.matching_module(modules,path)
class InjectionLifetime(unittest.TestCase):
def fake(self,wait=0,modules=True):
calls=[];path=Path('/owned/one.dll').resolve()
api=SimpleNamespace(k=SimpleNamespace(VirtualAllocEx=lambda *a:0x1000,CreateRemoteThread=lambda *a:99,WaitForSingleObject=lambda *a:wait,CloseHandle=lambda h:calls.append(('close',h)),VirtualFreeEx=lambda *a:calls.append(('free',a[1])) or 1),write=lambda *a:None,loader=lambda pid:0x180012340,modules=lambda pid:[{'base':0x180020000,'size':100,'path':str(path)}] if modules else [])
def checked(x):
if not x:raise RuntimeError('fixture API refused')
api.checked=checked;return api,path,calls
def test_success_returns_enumerated_64bit_base_and_frees_path_buffer(self):
api,path,calls=self.fake();pending=[];result=b.inject(api,501,888,path,pending)
self.assertEqual(result['base'],0x180020000);self.assertEqual(pending,[]);self.assertEqual(calls,[('close',99),('free',0x1000)])
def test_pending_loader_buffer_not_freed_while_thread_could_use_it(self):
api,path,calls=self.fake(wait=258);pending=[]
with self.assertRaises(TimeoutError):b.inject(api,501,888,path,pending)
self.assertEqual(calls,[('close',99)]);self.assertEqual(pending,[0x1000])
def test_completed_loader_without_exact_module_is_failure_and_buffer_freed(self):
api,path,calls=self.fake(modules=False);pending=[]
with self.assertRaises(ValueError):b.inject(api,501,888,path,pending)
self.assertEqual(pending,[]);self.assertIn(('free',0x1000),calls)
class LaunchLifecycle(unittest.TestCase):
def test_owned_child_cleanup_and_no_authentication_or_external_pid_input(self):
source=Path(__file__).resolve().parents[1]/'build/windows-native-bridge-20261022/GWNativeWire.dll'
if not source.exists():self.skipTest('Built PE fixture absent')
with tempfile.TemporaryDirectory() as d:
root=Path(d);(root/'compat').mkdir();(root/'compat/native-engine-template.json').write_text('{}')
profile={'schema':1}
for name in ['client','bridge','wire','backend','codec']:
p=root/(name+'.dll');p.write_bytes(source.read_bytes());profile[name]={'path':p.name,'sha256':b.digest(p)}
calls=[]
def create(*args):
out=args[-1]._obj;out.hProcess=501;out.hThread=502;out.dwProcessId=888;return 1
def wait(handle,ms):return 258 if ms==0 else 0
fake=SimpleNamespace(k=SimpleNamespace(CreateProcessW=create,TerminateProcess=lambda h,c:calls.append(('terminate',h)) or 1,WaitForSingleObject=wait,CloseHandle=lambda h:calls.append(('close',h))),identity=lambda h:(123,str(root/'client.dll')),checked=lambda x:None)
with patch.object(b,'os',SimpleNamespace(name='nt')),patch.object(b,'Kernel',return_value=fake),patch.object(b,'inject',side_effect=RuntimeError('load failed')):
with self.assertRaisesRegex(RuntimeError,'load failed'):b.launch_owned(root,profile)
self.assertEqual(calls,[('terminate',501),('close',502),('close',501)])
self.assertFalse((root/'runtime/native-engine-pe.json').exists())
class FreshFrameHandoff(unittest.TestCase):
def run_handoff(self,bad=False):
source=Path(__file__).resolve().parents[1]/'build/windows-native-bridge-20261022/GWNativeWire.dll'
if not source.exists():self.skipTest('Built PE fixture absent')
with tempfile.TemporaryDirectory() as d:
root=Path(d);(root/'compat').mkdir();(root/'compat/native-engine-template.json').write_text(json.dumps({'retained':'original metadata','auxiliary_dependencies':[{'file':'GWNativeWire.dll','sha256':'old','kept':'oldwiremetadata'},{'file':'Original.dll','sha256':'retained'}]}))
profile={'schema':1}
for name in ['client','bridge','wire','backend','codec']:
p=root/(name+'.dll');p.write_bytes(source.read_bytes());profile[name]={'path':p.name,'sha256':b.digest(p)}
calls=[];writes=[]
def create(*args):
out=args[-1]._obj;out.hProcess=501;out.hThread=502;out.dwProcessId=888;return 1
def checked(value):
if not value:raise RuntimeError('cleanup refused')
fake=SimpleNamespace(k=SimpleNamespace(CreateProcessW=create,TerminateProcess=lambda h,c:calls.append(('terminate',h)) or 1,WaitForSingleObject=lambda h,ms:258 if ms==0 else 0,CloseHandle=lambda h:calls.append(('close',h))),identity=lambda h:(123,str(root/'client.dll')),checked=checked,read=lambda *a:struct.pack('<II',1,1080)+bytes([1 if bad else 0])+bytes(47),write=lambda h,a,raw:writes.append((a,raw)))
with patch.object(b,'os',SimpleNamespace(name='nt')),patch.object(b,'Kernel',return_value=fake),patch.object(b,'inject',side_effect=[{'base':0x180000000,'path':str(root/'bridge.dll'),'size':1000000},{'base':0x190000000,'path':str(root/'wire.dll'),'size':1000000}]):
if bad:
with self.assertRaisesRegex(ValueError,'not pristine'):b.launch_owned(root,profile)
self.assertEqual(writes,[]);self.assertIn(('terminate',501),calls)
else:
result=b.launch_owned(root,profile);self.assertFalse(result['authentication_attempted']);self.assertEqual(result['pid'],888)
self.assertEqual(writes,[]);self.assertTrue(result['frame_filename_deferred_to_install_ping'])
journal=json.loads((root/'runtime/native-engine-pe.json').read_text());self.assertEqual(journal['retained'],'original metadata');self.assertTrue(journal['windows_native_bootstrap']);self.assertEqual(journal['auxiliary_dependencies'][0]['kept'],'oldwiremetadata');self.assertEqual(journal['auxiliary_dependencies'][0]['sha256'],profile['wire']['sha256']);self.assertEqual(journal['auxiliary_dependencies'][1],{'file':'Original.dll','sha256':'retained'});self.assertEqual(calls,[('close',502),('close',501)])
def test_handoff_defers_filename_and_preserves_template(self):self.run_handoff()
def test_nonpristine_frame_abstains_before_write_and_cleans_owned_child(self):self.run_handoff(True)
class SameThreadLoaderDiagnostic(unittest.TestCase):
"""Execute the exact thunk against x64 ms_abi local fixture functions."""
@classmethod
def setUpClass(cls):
import subprocess,platform
if platform.machine().lower()not in ('x86_64','amd64'):raise unittest.SkipTest('x64 ABI fixture required')
cls.temp=tempfile.TemporaryDirectory(prefix='loader-error-abi-')
folder=Path(cls.temp.name);source=folder/'loader_error_abi.c';library=folder/'loader_error_abi.so'
source.write_text(r"""
#include <stdint.h>
#include <pthread.h>
static uint64_t module_value;
static uint32_t error_value,steps[4],count;
static uintptr_t observed_thread,calling_thread;
static int same_thread,canary_ok;
__attribute__((noinline)) static void record_step(uint32_t value) {
uintptr_t current=(uintptr_t)pthread_self();
if (!count) observed_thread=current;
else if (current!=observed_thread) same_thread=0;
if (current!=calling_thread) same_thread=0;
if (count<4) steps[count++]=value;
}
__attribute__((ms_abi,noinline)) uint64_t fixture_load(const uint16_t *path) {
record_step(1);
if (!path || path[0]!=47) return 0;
return module_value;
}
__attribute__((ms_abi,noinline)) uint32_t fixture_error(void) {
record_step(2);return error_value;
}
void reset_fixture(uint64_t module,uint32_t error) {
module_value=module;error_value=error;count=0;same_thread=1;canary_ok=0;
observed_thread=0;calling_thread=(uintptr_t)pthread_self();
}
uint64_t run_thunk(void *entry,void *parameter) {
typedef uint64_t (__attribute__((ms_abi)) *thread_entry)(void*);
register uint64_t preserved __asm__("rbx")=0x1234432112344321ULL;
__asm__ volatile("" : "+r"(preserved));
uint64_t result=((thread_entry)entry)(parameter);
__asm__ volatile("" : "+r"(preserved));
canary_ok=preserved==0x1234432112344321ULL;return result;
}
uint32_t observed_count(void) { return count; }
uint32_t observed_step(uint32_t index) { return steps[index]; }
int observed_same_thread(void) { return same_thread; }
int observed_canary(void) { return canary_ok; }
""")
completed=subprocess.run(['gcc','-shared','-fPIC','-O2','-Wall','-Wextra','-Werror','-pthread',str(source),'-o',str(library)],capture_output=True,text=True)
if completed.returncode:raise RuntimeError('ABI fixture compile failed: '+completed.stderr)
cls.lib=C.CDLL(str(library));cls.lib.reset_fixture.argtypes=[C.c_uint64,C.c_uint32]
cls.lib.run_thunk.argtypes=[C.c_void_p,C.c_void_p];cls.lib.run_thunk.restype=C.c_uint64
cls.lib.observed_step.argtypes=[C.c_uint32];cls.lib.observed_step.restype=C.c_uint32
@classmethod
def tearDownClass(cls):cls.temp.cleanup()
def fake(self,module=0,error=126,wait=0,bad_marker=False):
import mmap
lib=self.lib;lib.reset_fixture(module,error);allocations={};events=[];state=dict(exit=0,error_exports=0)
def allocate(process,address,size,kind,protect):
self.assertEqual(protect,4)
memory=mmap.mmap(-1,size,prot=mmap.PROT_READ|mmap.PROT_WRITE)
pointer=C.addressof(C.c_char.from_buffer(memory));allocations[pointer]=memory;events.append(('alloc',pointer,size));return pointer
libc=C.CDLL(None);libc.mprotect.argtypes=[C.c_void_p,C.c_size_t,C.c_int];libc.mprotect.restype=C.c_int
def protect(process,address,size,mode,old):
self.assertEqual(mode,0x20);self.assertIn(address,allocations)
old._obj.value=4;events.append(('RX-only-new-code',address,size));return libc.mprotect(address,size,5)==0
def create(process,security,stack,entry,parameter,flags,tid):
tid._obj.value=77;events.append(('thread',entry,parameter))
if wait==0:
state['exit']=lib.run_thunk(entry,parameter)&0xffffffff
if bad_marker:C.c_uint32.from_address(parameter+36).value=0
return 99
def exit_code(thread,output):output._obj.value=state['exit'];return 1
def free(process,address,size,kind):events.append(('free',address));allocations.pop(address).close();return 1
def exports(pid):
state['error_exports']+=1
return C.cast(lib.fixture_load,C.c_void_p).value,C.cast(lib.fixture_error,C.c_void_p).value
def checked(value):
if not value:raise RuntimeError('fixture API refusal')
path=Path('/owned/Bridge.dll')
api=SimpleNamespace(k=SimpleNamespace(VirtualAllocEx=allocate,VirtualProtectEx=protect,FlushInstructionCache=lambda *a:1,CreateRemoteThread=create,WaitForSingleObject=lambda *a:wait,GetExitCodeThread=exit_code,CloseHandle=lambda h:events.append(('close',h)),VirtualFreeEx=free),checked=checked,write=lambda process,address,data:C.memmove(address,data,len(data)),read=lambda process,address,size:C.string_at(address,size),loader_error_exports=exports,loader=lambda pid:C.cast(lib.fixture_load,C.c_void_p).value,modules=lambda pid:[dict(base=module,size=4096,path=str(path))]if module else [])
return api,path,events,allocations,state
def test_actual_x64_assembly_success_and_same_thread_error_cases(self):
from capstone import Cs,CS_ARCH_X86,CS_MODE_64
instructions=list(Cs(CS_ARCH_X86,CS_MODE_64).disasm(b.LOAD_ERROR_THUNK,0))
self.assertEqual(sum(x.size for x in instructions),len(b.LOAD_ERROR_THUNK))
self.assertEqual([(x.mnemonic,x.op_str)for x in instructions if x.mnemonic=='call'],[('call','qword ptr [rbx + 8]'),('call','qword ptr [rbx + 0x10]')])
self.assertEqual(instructions[0].mnemonic,'push');self.assertEqual(instructions[0].op_str,'rbx')
self.assertEqual(instructions[1].op_str,'rsp, 0x20')
for module,error in [(0x1234567812340000,1114),(0,126),(0,193),(0,1114),(0,5)]:
with self.subTest(module=module,error=error):
api,path,events,allocations,state=self.fake(module,error);pending=[]
if module:self.assertEqual(b.inject(api,501,1440,path,pending,diagnostic_last_error=True)['base'],module)
else:
with self.assertRaises(OSError)as failure:b.inject(api,501,1440,path,pending,diagnostic_last_error=True)
self.assertEqual(failure.exception.errno,error)
observation=api._last_load_attempt
self.assertTrue(observation['thread_completed']);self.assertTrue(observation['thunk_completion_observed'])
self.assertEqual(observation['module_handle'],module)
self.assertEqual(observation['remote_last_error'],None if module else error)
self.assertEqual(self.lib.observed_count(),1 if module else 2)
self.assertEqual(self.lib.observed_step(0),1)
if not module:self.assertEqual(self.lib.observed_step(1),2)
self.assertEqual(self.lib.observed_same_thread(),1);self.assertEqual(self.lib.observed_canary(),1)
self.assertEqual(pending,[]);self.assertFalse(allocations);self.assertEqual(state['error_exports'],1)
self.assertEqual(len([x for x in events if x[0]=='RX-only-new-code']),1)
def test_default_has_no_thunk_and_pending_or_incomplete_diagnostic_is_not_error_proof(self):
api,path,events,allocations,state=self.fake(0x1234567812340000);pending=[]
b.inject(api,501,1440,path,pending)
self.assertEqual(state['error_exports'],0);self.assertEqual(len([x for x in events if x[0]=='alloc']),1)
self.assertFalse(api._last_load_attempt['remote_last_error_observed'])
for wait,bad_marker in [(258,False),(0,True)]:
api,path,events,allocations,state=self.fake(0,193,wait,bad_marker);pending=[]
try:
with self.assertRaises((TimeoutError,ValueError)):b.inject(api,501,1440,path,pending,diagnostic_last_error=True)
self.assertFalse(api._last_load_attempt['remote_last_error_observed'])
self.assertFalse(api._last_load_attempt['thunk_completion_observed'])
if wait:self.assertEqual(len(pending),2);self.assertFalse(any(x[0]=='free'for x in events))
else:self.assertFalse(pending);self.assertFalse(allocations)
finally:
for memory in allocations.values():memory.close()
def test_incomplete_result_preserves_untrusted_fields_without_result_authority(self):
for module,error in [(0,193),(0x1234567812340000,1114)]:
with self.subTest(module=module):
api,path,events,allocations,state=self.fake(module,error,bad_marker=True);pending=[]
with self.assertRaises(ValueError):b.inject(api,501,1440,path,pending,diagnostic_last_error=True)
observation=api._last_load_attempt;candidates=observation['untrusted_result_candidates']
self.assertEqual(candidates['module_handle'],module)
self.assertEqual(candidates['last_error'],193 if module==0 else 0)
self.assertEqual(candidates['completion_marker'],0)
self.assertGreater(candidates['path_pointer'],0)
self.assertEqual(candidates['load_library_pointer'],C.cast(self.lib.fixture_load,C.c_void_p).value)
self.assertEqual(candidates['get_last_error_pointer'],C.cast(self.lib.fixture_error,C.c_void_p).value)
self.assertEqual(candidates['authority'],'UNTRUSTED_RAW_ONLY_NO_LOAD_OR_LAST_ERROR_CLAIM')
self.assertTrue(observation['thread_completed'])
self.assertFalse(observation['thunk_completion_observed'])
self.assertFalse(observation['full_width_module_handle_observed'])
self.assertFalse(observation['remote_last_error_observed'])
self.assertNotIn('module_handle',observation);self.assertNotIn('remote_last_error',observation)
self.assertFalse(pending);self.assertFalse(allocations)
def test_two_exports_resolve_their_actual_remote_owner_once(self):
api=b.Kernel.__new__(b.Kernel);path=str(Path('/system/KernelBase.dll').resolve());local=0x7ff000000000;remote=0x180000000;snapshots=[]
def proc(module,name):return local+(0x1234 if name==b'LoadLibraryW'else 0x5678)
def owner(flags,address,out):out._obj.value=local;return 1
def filename(module,buffer,size):buffer.value=path;return len(path)
api.k=SimpleNamespace(GetModuleHandleW=lambda name:1,GetProcAddress=proc,GetModuleHandleExW=owner,GetModuleFileNameW=filename)
api.modules=lambda pid:snapshots.append(pid)or[dict(base=remote,size=0x10000,path=path)]
self.assertEqual(api.loader_error_exports(1440),(remote+0x1234,remote+0x5678));self.assertEqual(snapshots,[1440])
if __name__=='__main__':unittest.main()