367 files, from working commit b1a079a. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
537 lines
40 KiB
Python
537 lines
40 KiB
Python
#!/usr/bin/env python3
|
|
"""Launch one owned native Windows client and load its pinned PE bridges.
|
|
|
|
Only a created child or explicit continuation of its preserved bootstrap may be owned.
|
|
No arbitrary PID attachment, credential handling or automatic authentication.
|
|
The original client image remains unchanged. Only the newly created child can
|
|
be terminated during failed bootstrap cleanup, before ownership is handed off.
|
|
"""
|
|
import argparse, ctypes as C, hashlib, json, os, struct, time
|
|
from ctypes import wintypes as W
|
|
from pathlib import Path
|
|
import native_runtime_paths
|
|
|
|
def digest(path):return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
|
def atomic_json(path,value):
|
|
temporary=path.with_name(path.name+'.new');temporary.write_text(json.dumps(value,indent=2)+'\n');temporary.replace(path)
|
|
def owned_file(root,entry):
|
|
name=entry['path'];p=Path(name)
|
|
if p.is_absolute() or '..' in p.parts:raise ValueError('Bundle-relative file required')
|
|
original=root/p;path=original.resolve()
|
|
if not path.is_relative_to(root) or original.is_symlink() or not path.is_file():raise ValueError('Owned regular bundle file required')
|
|
expected=entry['sha256']
|
|
if not isinstance(expected,str) or len(expected)!=64 or any(c not in '0123456789abcdef' for c in expected) or digest(path)!=expected:raise ValueError('Pinned bundle file changed')
|
|
return path
|
|
|
|
def engine_template(root,profile):
|
|
"""Use an explicitly pinned Windows template for a shared client folder."""
|
|
entry=profile.get('engine_template')
|
|
path=owned_file(root,entry) if entry is not None else root/'compat/native-engine-template.json'
|
|
return json.loads(path.read_text())
|
|
|
|
def pe_exports(path):
|
|
data=Path(path).read_bytes()
|
|
def u16(p):return struct.unpack_from('<H',data,p)[0]
|
|
def u32(p):return struct.unpack_from('<I',data,p)[0]
|
|
if len(data)<64 or data[:2]!=b'MZ':raise ValueError('PE image required')
|
|
pe=u32(60)
|
|
if pe+264>len(data) or data[pe:pe+4]!=b'PE\0\0' or u16(pe+4)!=0x8664:raise ValueError('AMD64 PE required')
|
|
sections=u16(pe+6);opt=pe+24;opt_size=u16(pe+20)
|
|
if u16(opt)!=0x20b or opt_size<120 or not 1<=sections<=96:raise ValueError('PE32+ header required')
|
|
image_size=u32(opt+56);table=opt+opt_size
|
|
if table+sections*40>len(data):raise ValueError('Truncated PE sections')
|
|
def offset(rva,size):
|
|
for i in range(sections):
|
|
s=table+i*40;va=u32(s+12);raw_size=u32(s+16);raw=u32(s+20)
|
|
if va<=rva and rva+size<=va+raw_size and raw+rva-va+size<=len(data):return raw+rva-va
|
|
raise ValueError('Export RVA outside raw sections')
|
|
export_rva=u32(opt+112);export_size=u32(opt+116)
|
|
if not export_rva:return {}
|
|
e=offset(export_rva,40);count=u32(e+20);names=u32(e+24)
|
|
if not 0<count<=4096 or names>count:raise ValueError('Export count bound')
|
|
functions=offset(u32(e+28),count*4);name_table=offset(u32(e+32),names*4);ordinals=offset(u32(e+36),names*2)
|
|
result={}
|
|
for i in range(names):
|
|
p=offset(u32(name_table+i*4),1);end=data.find(b'\0',p,p+129)
|
|
if end<0:raise ValueError('Export name bound')
|
|
name=data[p:end].decode('ascii');ordinal=u16(ordinals+i*2)
|
|
if ordinal>=count or name in result:raise ValueError('Export ordinal/name invalid')
|
|
rva=u32(functions+ordinal*4)
|
|
if not 0<rva<image_size or export_rva<=rva<export_rva+export_size:raise ValueError('Forwarded/outside own export rejected')
|
|
result[name]=rva
|
|
return result
|
|
|
|
class STARTUPINFO(C.Structure):
|
|
_fields_=[('cb',W.DWORD),('lpReserved',W.LPWSTR),('lpDesktop',W.LPWSTR),('lpTitle',W.LPWSTR),('dwX',W.DWORD),('dwY',W.DWORD),('dwXSize',W.DWORD),('dwYSize',W.DWORD),('dwXCountChars',W.DWORD),('dwYCountChars',W.DWORD),('dwFillAttribute',W.DWORD),('dwFlags',W.DWORD),('wShowWindow',W.WORD),('cbReserved2',W.WORD),('lpReserved2',C.c_void_p),('hStdInput',W.HANDLE),('hStdOutput',W.HANDLE),('hStdError',W.HANDLE)]
|
|
class PROCESS_INFORMATION(C.Structure):
|
|
_fields_=[('hProcess',W.HANDLE),('hThread',W.HANDLE),('dwProcessId',W.DWORD),('dwThreadId',W.DWORD)]
|
|
class MODULEENTRY32(C.Structure):
|
|
_fields_=[('dwSize',W.DWORD),('th32ModuleID',W.DWORD),('th32ProcessID',W.DWORD),('GlblcntUsage',W.DWORD),('ProccntUsage',W.DWORD),('modBaseAddr',C.c_void_p),('modBaseSize',W.DWORD),('hModule',W.HMODULE),('szModule',W.WCHAR*256),('szExePath',W.WCHAR*260)]
|
|
class Kernel:
|
|
def __init__(self):
|
|
if (C.sizeof(STARTUPINFO),C.sizeof(PROCESS_INFORMATION),C.sizeof(MODULEENTRY32))!=(104,24,1080):raise RuntimeError('Win64 process/module structure ABI mismatch')
|
|
self.k=C.WinDLL('kernel32',use_last_error=True)
|
|
sig={
|
|
'CreateProcessW':([W.LPCWSTR,W.LPWSTR,C.c_void_p,C.c_void_p,W.BOOL,W.DWORD,C.c_void_p,W.LPCWSTR,C.POINTER(STARTUPINFO),C.POINTER(PROCESS_INFORMATION)],W.BOOL),
|
|
'OpenProcess':([W.DWORD,W.BOOL,W.DWORD],W.HANDLE),'CloseHandle':([W.HANDLE],W.BOOL),'WaitForSingleObject':([W.HANDLE,W.DWORD],W.DWORD),'GetExitCodeThread':([W.HANDLE,C.POINTER(W.DWORD)],W.BOOL),'TerminateProcess':([W.HANDLE,W.UINT],W.BOOL),
|
|
'GetProcessTimes':([W.HANDLE,C.POINTER(W.FILETIME),C.POINTER(W.FILETIME),C.POINTER(W.FILETIME),C.POINTER(W.FILETIME)],W.BOOL),
|
|
'QueryFullProcessImageNameW':([W.HANDLE,W.DWORD,W.LPWSTR,C.POINTER(W.DWORD)],W.BOOL),
|
|
'CreateToolhelp32Snapshot':([W.DWORD,W.DWORD],W.HANDLE),'Module32FirstW':([W.HANDLE,C.POINTER(MODULEENTRY32)],W.BOOL),'Module32NextW':([W.HANDLE,C.POINTER(MODULEENTRY32)],W.BOOL),
|
|
'GetModuleHandleW':([W.LPCWSTR],W.HMODULE),'GetModuleHandleExW':([W.DWORD,C.c_void_p,C.POINTER(W.HMODULE)],W.BOOL),'GetProcAddress':([W.HMODULE,C.c_char_p],C.c_void_p),'GetModuleFileNameW':([W.HMODULE,W.LPWSTR,W.DWORD],W.DWORD),
|
|
'VirtualAllocEx':([W.HANDLE,C.c_void_p,C.c_size_t,W.DWORD,W.DWORD],C.c_void_p),'VirtualFreeEx':([W.HANDLE,C.c_void_p,C.c_size_t,W.DWORD],W.BOOL),
|
|
'VirtualProtectEx':([W.HANDLE,C.c_void_p,C.c_size_t,W.DWORD,C.POINTER(W.DWORD)],W.BOOL),'FlushInstructionCache':([W.HANDLE,C.c_void_p,C.c_size_t],W.BOOL),
|
|
'WriteProcessMemory':([W.HANDLE,C.c_void_p,C.c_void_p,C.c_size_t,C.POINTER(C.c_size_t)],W.BOOL),'ReadProcessMemory':([W.HANDLE,C.c_void_p,C.c_void_p,C.c_size_t,C.POINTER(C.c_size_t)],W.BOOL),
|
|
'CreateRemoteThread':([W.HANDLE,C.c_void_p,C.c_size_t,C.c_void_p,C.c_void_p,W.DWORD,C.POINTER(W.DWORD)],W.HANDLE)}
|
|
for name,(args,result) in sig.items():
|
|
f=getattr(self.k,name);f.argtypes=args;f.restype=result
|
|
def checked(self,success):
|
|
if not success:raise C.WinError(C.get_last_error())
|
|
def identity(self,process):
|
|
creation=W.FILETIME();exit=W.FILETIME();kernel=W.FILETIME();user=W.FILETIME()
|
|
self.checked(self.k.GetProcessTimes(process,C.byref(creation),C.byref(exit),C.byref(kernel),C.byref(user)))
|
|
name=C.create_unicode_buffer(32768);size=W.DWORD(len(name));self.checked(self.k.QueryFullProcessImageNameW(process,0,name,C.byref(size)))
|
|
return (creation.dwHighDateTime<<32)|creation.dwLowDateTime,str(Path(name.value).resolve())
|
|
def _module_snapshot(self,pid):
|
|
for attempt in range(3):
|
|
snapshot=self.k.CreateToolhelp32Snapshot(0x18,pid)
|
|
if snapshot!=C.c_void_p(-1).value:break
|
|
if C.get_last_error()!=24 or attempt==2:raise C.WinError(C.get_last_error())
|
|
time.sleep(0.01)
|
|
try:
|
|
row=MODULEENTRY32();row.dwSize=C.sizeof(row);ok=self.k.Module32FirstW(snapshot,C.byref(row));result=[]
|
|
if not ok:raise C.WinError(C.get_last_error())
|
|
while ok:
|
|
result.append({'base':int(row.modBaseAddr),'size':int(row.modBaseSize),'path':str(Path(row.szExePath).resolve())})
|
|
if len(result)>4096:raise ValueError('Module enumeration bound')
|
|
ok=self.k.Module32NextW(snapshot,C.byref(row))
|
|
if C.get_last_error()!=18:raise C.WinError(C.get_last_error())
|
|
return result
|
|
finally:self.k.CloseHandle(snapshot)
|
|
def modules(self,pid):
|
|
# Only initial bootstrap has this120s owned readiness context. Later
|
|
# readers keep the existing immediate snapshot behavior.
|
|
owner=getattr(self,'_startup_owner',None)
|
|
while True:
|
|
try:
|
|
result=self._module_snapshot(pid);self._last_modules=result;return result
|
|
except OSError as exc:
|
|
if (not owner or owner['pid']!=pid or getattr(exc,'winerror',None)not in(24,299)):
|
|
raise
|
|
if self.k.WaitForSingleObject(owner['process'],0)==0:
|
|
raise RuntimeError('Owned client exited before initial modules became ready')from None
|
|
if self.identity(owner['process'])!=owner['identity']:
|
|
raise ValueError('Owned startup identity changed')from None
|
|
if time.monotonic()>=owner['deadline']:
|
|
raise TimeoutError('Owned initial module readiness deadline expired')from None
|
|
time.sleep(0.1)
|
|
|
|
def read(self,process,address,size):
|
|
data=C.create_string_buffer(size);got=C.c_size_t();self.checked(self.k.ReadProcessMemory(process,address,data,size,C.byref(got)))
|
|
if got.value!=size:raise ValueError('Partial remote read')
|
|
return data.raw
|
|
def write(self,process,address,data):
|
|
source=C.create_string_buffer(data);written=C.c_size_t();self.checked(self.k.WriteProcessMemory(process,address,source,len(data),C.byref(written)))
|
|
if written.value!=len(data):raise ValueError('Partial remote write')
|
|
def _loader_export(self,pid,symbol,modules=None):
|
|
if symbol not in (b'LoadLibraryW',b'GetLastError'):raise ValueError('Unreviewed loader export')
|
|
# GetProcAddress can be forwarded. Rebase the actual owner and its RVA
|
|
# in this child, never reuse a local absolute function address.
|
|
local=self.k.GetProcAddress(self.k.GetModuleHandleW('kernel32.dll'),symbol);self.checked(local)
|
|
owner=W.HMODULE();self.checked(self.k.GetModuleHandleExW(0x6,local,C.byref(owner)))
|
|
name=C.create_unicode_buffer(32768);n=self.k.GetModuleFileNameW(owner,name,len(name));self.checked(n and n<len(name))
|
|
rva=int(local)-int(owner.value)
|
|
if modules is None:
|
|
modules=getattr(self,'_startup_modules',None);self._startup_modules=None
|
|
if modules is None:modules=self.modules(pid)
|
|
remote=matching_module(modules,name.value)
|
|
if not 0<=rva<remote['size']:raise ValueError('Loader export owner RVA invalid')
|
|
return remote['base']+rva
|
|
def loader(self,pid):
|
|
return self._loader_export(pid,b'LoadLibraryW')
|
|
def loader_error_exports(self,pid):
|
|
modules=getattr(self,'_startup_modules',None);self._startup_modules=None
|
|
if modules is None:modules=self.modules(pid)
|
|
return (self._loader_export(pid,b'LoadLibraryW',modules),
|
|
self._loader_export(pid,b'GetLastError',modules))
|
|
|
|
def matching_module(modules,path):
|
|
path=str(Path(path).resolve()).casefold();found=[m for m in modules if m['path'].casefold()==path]
|
|
if len(found)!=1:raise ValueError('Exact remote module identity unavailable')
|
|
return found[0]
|
|
# Private opt-in diagnostic only. Windows x64 entry RSP is 8 mod16: preserve
|
|
# RBX, reserve32 shadow bytes, retain alignment across both calls, then restore.
|
|
# Parameter: path Q0, LoadLibraryW Q8, GetLastError Q16, HMODULE Q24,
|
|
# DWORD error32, DWORD completion36. Only the completed result is authoritative.
|
|
LOAD_ERROR_COMPLETION=0x31454c4c
|
|
LOAD_ERROR_THUNK=(bytes.fromhex('53 4883ec20 4889cb 488b0b ff5308 48894318 4885c0 7506 ff5310 894320 c74324')
|
|
+struct.pack('<I',LOAD_ERROR_COMPLETION)+bytes.fromhex('31c0 4883c420 5b c3'))
|
|
def _inject_with_last_error(api,process,pid,path,pending):
|
|
load,last_error=api.loader_error_exports(pid)
|
|
raw_path=(str(path)+'\0').encode('utf-16-le');owned=[];thread=None;started=False;completed=False
|
|
observation=dict(requested_path=str(path),diagnostic_kind='same-thread-LoadLibraryW-GetLastError-v1',
|
|
new_executable_thunk=True,thread_completed=False,thunk_completion_observed=False,
|
|
full_width_module_handle_observed=False,remote_last_error_observed=False,exact_module_present=None)
|
|
api._last_load_attempt=observation
|
|
try:
|
|
data=api.k.VirtualAllocEx(process,None,40+len(raw_path),0x3000,4);api.checked(data);owned.append(data);pending.append(data)
|
|
code=api.k.VirtualAllocEx(process,None,len(LOAD_ERROR_THUNK),0x3000,4);api.checked(code);owned.append(code);pending.append(code)
|
|
observation['owned_allocations']=list(owned)
|
|
api.write(process,data,struct.pack('<QQQQII',data+40,load,last_error,0,0,0)+raw_path)
|
|
api.write(process,code,LOAD_ERROR_THUNK)
|
|
# Only this newly allocated private code page changes RW->RX. No
|
|
# existing image/data page or process mitigation is modified.
|
|
old=W.DWORD();api.checked(api.k.VirtualProtectEx(process,code,len(LOAD_ERROR_THUNK),0x20,C.byref(old)))
|
|
if old.value!=4:raise ValueError('New diagnostic code allocation protection differs')
|
|
api.checked(api.k.FlushInstructionCache(process,code,len(LOAD_ERROR_THUNK)))
|
|
tid=W.DWORD();thread=api.k.CreateRemoteThread(process,None,0,code,data,0,C.byref(tid));api.checked(thread);started=True
|
|
observation['thread_id']=int(tid.value)
|
|
if api.k.WaitForSingleObject(thread,15000)!=0:raise TimeoutError('Owned diagnostic DLL load did not complete; preserve allocations')
|
|
completed=True;observation['thread_completed']=True
|
|
exit_code=W.DWORD();api.checked(api.k.GetExitCodeThread(thread,C.byref(exit_code)))
|
|
observation.update(exit_dword=int(exit_code.value),exit_dword_hex=f'0x{exit_code.value:08x}')
|
|
raw=api.read(process,data,40)
|
|
if len(raw)!=40:raise ValueError('Partial diagnostic loader result')
|
|
path_pointer,observed_load,observed_error,module,error,marker=struct.unpack('<QQQQII',raw)
|
|
# Preserve partial diagnostic evidence before any completion/header
|
|
# refusal. These raw fields have NO loader/last-error authority; trusted
|
|
# result fields below are populated only after all completion checks.
|
|
observation['untrusted_result_candidates']=dict(
|
|
path_pointer=path_pointer,load_library_pointer=observed_load,
|
|
get_last_error_pointer=observed_error,module_handle=module,
|
|
last_error=error,completion_marker=marker,
|
|
authority='UNTRUSTED_RAW_ONLY_NO_LOAD_OR_LAST_ERROR_CLAIM')
|
|
observation['completion_marker']=marker
|
|
if (path_pointer,observed_load,observed_error)!=(data+40,load,last_error):raise ValueError('Diagnostic loader parameter identity changed')
|
|
if marker!=LOAD_ERROR_COMPLETION or exit_code.value!=0:raise ValueError('Diagnostic thunk completion/result not established')
|
|
observation.update(thunk_completion_observed=True,full_width_module_handle_observed=True,
|
|
module_handle=module,module_handle_hex=f'0x{module:016x}',
|
|
remote_last_error_observed=module==0,remote_last_error=error if module==0 else None)
|
|
modules=api.modules(pid)
|
|
try:loaded=matching_module(modules,path)
|
|
except ValueError:
|
|
observation['exact_module_present']=False
|
|
if module==0:raise OSError(error,'Same-thread LoadLibraryW returned NULL')from None
|
|
raise
|
|
observation['exact_module_present']=True
|
|
if module==0 or loaded['base']!=module:raise ValueError('Full-width loader result differs from exact module')
|
|
return loaded
|
|
finally:
|
|
if thread:api.k.CloseHandle(thread)
|
|
# No execution can still use these allocations after joined completion
|
|
# or before thread creation. Pending threads retain both under custody.
|
|
if completed or not started:
|
|
for address in reversed(owned):
|
|
api.checked(api.k.VirtualFreeEx(process,address,0,0x8000));pending.remove(address)
|
|
|
|
def inject(api,process,pid,path,pending,*,diagnostic_last_error=False):
|
|
if type(diagnostic_last_error)is not bool:raise ValueError('Invalid loader diagnostic option')
|
|
if diagnostic_last_error:return _inject_with_last_error(api,process,pid,path,pending)
|
|
raw=(str(path)+'\0').encode('utf-16-le');remote=api.k.VirtualAllocEx(process,None,len(raw),0x3000,4);api.checked(remote)
|
|
pending.append(remote);thread=None;completed=False
|
|
try:
|
|
api.write(process,remote,raw);tid=W.DWORD();thread=api.k.CreateRemoteThread(process,None,0,api.loader(pid),remote,0,C.byref(tid));api.checked(thread)
|
|
if api.k.WaitForSingleObject(thread,15000)!=0:raise TimeoutError('Owned DLL load did not complete')
|
|
completed=True
|
|
code=W.DWORD();api.checked(api.k.GetExitCodeThread(thread,C.byref(code)))
|
|
# A thread exit DWORD is not a full-width HMODULE or remote GetLastError.
|
|
# Preserve it before CloseHandle, including when module enumeration fails.
|
|
observation=dict(requested_path=str(path),thread_id=int(tid.value),thread_completed=True,
|
|
exit_dword=int(code.value),exit_dword_hex=f'0x{code.value:08x}',
|
|
full_width_module_handle_observed=False,remote_last_error_observed=False,
|
|
exact_module_present=None)
|
|
api._last_load_attempt=observation
|
|
modules=api.modules(pid)
|
|
try:loaded=matching_module(modules,path)
|
|
except ValueError:
|
|
observation['exact_module_present']=False
|
|
raise
|
|
observation['exact_module_present']=True
|
|
return loaded
|
|
finally:
|
|
if thread:api.k.CloseHandle(thread)
|
|
if completed:
|
|
api.checked(api.k.VirtualFreeEx(process,remote,0,0x8000));pending.remove(remote)
|
|
|
|
def validate_previous_ownership(meta,profile,paths):
|
|
if (meta.get('windows_native_bootstrap')is not True or type(meta.get('pid'))is not int or meta['pid']<=0
|
|
or type(meta.get('starttime'))is not int or meta['starttime']<=0
|
|
or str(meta.get('image_path','')).casefold()!=str(paths['client']).casefold()
|
|
or meta.get('dll_sha256')!=profile['bridge']['sha256']):raise ValueError('Previous Windows ownership journal differs')
|
|
pins=meta.get('wire_unix_library',{})
|
|
for key,name in [('core','backend'),('wire_unix','backend'),('source_codec','codec')]:
|
|
if pins.get(key+'_sha256')!=profile[name]['sha256'] or str(pins.get(key+'_path','')).casefold()!=str(paths[name]).casefold():raise ValueError('Previous Windows library pins differ')
|
|
|
|
def require_previous_closed(meta,profile,paths,api):
|
|
validate_previous_ownership(meta,profile,paths)
|
|
handle=api.k.OpenProcess(0x1000|0x100000,False,meta['pid'])
|
|
if not handle:
|
|
if C.get_last_error()!=87:raise C.WinError(C.get_last_error())
|
|
return
|
|
try:
|
|
if api.k.WaitForSingleObject(handle,0)!=0:raise ValueError('Close the preserved client before another launch')
|
|
finally:api.k.CloseHandle(handle)
|
|
|
|
def reviewed_preauth_stage(profile):
|
|
stage=profile.get('reviewed_preauth_stage')
|
|
if stage not in (None,'modules-loaded-v1','bridge-loaded-v1','before-modules-v1'):
|
|
raise ValueError('Unreviewed Windows preauth stage')
|
|
role=profile.get('reviewed_preauth_role')
|
|
if stage=='bridge-loaded-v1':
|
|
if role!='bridge-only-load-isolation-v1' or profile.get('backend_transport')!='owned-stdio-ipc-v1':
|
|
raise ValueError('Private IPC Bridge-only diagnostic role required')
|
|
elif stage=='before-modules-v1':
|
|
if role!='system-loader-isolation-v1' or profile.get('backend_transport')!='owned-stdio-ipc-v1':
|
|
raise ValueError('Private IPC system-loader diagnostic role required')
|
|
elif role is not None:
|
|
raise ValueError('Bridge-only diagnostic role requires its exact stage')
|
|
return stage
|
|
|
|
def launch_owned(bundle_root,profile=None,*,_resume=None,_api=None):
|
|
if os.name!='nt' or C.sizeof(C.c_void_p)!=8:raise RuntimeError('Native64-bit Windows owner required')
|
|
root=Path(bundle_root).resolve()
|
|
profile=json.loads((root/'compat/windows-native.json').read_text()) if profile is None else profile
|
|
if profile.get('schema')!=1:raise ValueError('Windows bootstrap profile required')
|
|
stage=reviewed_preauth_stage(profile)
|
|
bridge_only=stage=='bridge-loaded-v1'
|
|
before_modules=stage=='before-modules-v1'
|
|
system_control=bool(_resume and _resume.get('system_loader_control')is True)
|
|
late_bridge=bool(_resume and _resume.get('late_bridge_only')is True)
|
|
if system_control and late_bridge:raise ValueError('Only one fixed diagnostic continuation is allowed')
|
|
if bridge_only and _resume is not None:raise ValueError('Bridge-only stage requires a new closed-generation action')
|
|
if system_control and not before_modules:raise ValueError('System-loader control requires its private before-modules role')
|
|
if late_bridge and not before_modules:raise ValueError('Late Bridge requires the private before-modules role')
|
|
if before_modules and _resume is not None and not(system_control or late_bridge):raise ValueError('Explicit fixed diagnostic continuation required')
|
|
paths={name:owned_file(root,profile[name]) for name in ['client','bridge','wire','backend','codec']}
|
|
# The existing frontend may delegate its own43-operation ABI to an owned
|
|
# worker. Validate the real executable before the original game is started;
|
|
# this is not permission to load backend/codec inside that process.
|
|
if profile.get('backend_transport')=='owned-stdio-ipc-v1':
|
|
worker=owned_file(root,profile.get('backend_host',{}))
|
|
if worker!=paths['backend'].parent/'windows-backend-host.exe':
|
|
raise ValueError('Owned backend worker must be the pinned backend sibling')
|
|
paths['backend_host']=worker
|
|
elif profile.get('backend_transport')not in(None,'native-Windows'):
|
|
raise ValueError('Unknown Windows backend transport profile')
|
|
exports={name:pe_exports(paths[name]) for name in ['bridge','wire']}
|
|
pe_exports(paths['client'])
|
|
for name in exports:
|
|
if profile[name].get('exports',exports[name])!=exports[name]:raise ValueError('Pinned export RVAs changed')
|
|
if 'gw_wire_frame_data' not in exports['wire']:raise ValueError('Wire frame ABI export missing')
|
|
backend_bytes=(str(paths['backend'])+'\0').encode('utf-16-le')
|
|
if len(backend_bytes)>1024:raise ValueError('Backend frame filename bound')
|
|
runtime=root/'runtime';runtime.mkdir(exist_ok=True);state=native_runtime_paths.prepare_state_directory(root);journal=native_runtime_paths.engine_journal(root)
|
|
if (profile.get('runtime_journal_scope')=='windows-isolated-v1') != (journal==runtime/'windows-native-engine-pe.json'):
|
|
raise ValueError('Windows journal requires the matching on-disk profile')
|
|
template=engine_template(root,profile);api=_api or Kernel()
|
|
failure_journal=state/'windows-bootstrap-failure.json'
|
|
resume_meta=None
|
|
if _resume is not None:
|
|
if profile.get('backend_transport')!='owned-stdio-ipc-v1':raise ValueError('Only preserved IPC preauth bootstrap can resume')
|
|
if not failure_journal.exists():raise ValueError('Preserved owned bootstrap receipt required')
|
|
resume_meta=json.loads(failure_journal.read_text());validate_previous_ownership(resume_meta,profile,paths)
|
|
if (type(_resume.get('pid'))is not int or type(_resume.get('starttime'))is not int
|
|
or _resume['pid']!=resume_meta['pid']or _resume['starttime']!=resume_meta['starttime']
|
|
or resume_meta.get('bootstrap_handoff')is not False
|
|
or resume_meta.get('credentials_submitted')is not False):
|
|
raise ValueError('Explicit exact unhanded preauth continuation required')
|
|
if system_control and (resume_meta.get('preserved_stage')!='before-modules-v1'
|
|
or resume_meta.get('system_loader_control_attempted')is not False):
|
|
raise ValueError('Only an unconsumed before-modules owner can run the system-loader control')
|
|
if late_bridge and (resume_meta.get('preserved_stage')!='system-loader-completed-v1'
|
|
or resume_meta.get('system_loader_control_attempted')is not True
|
|
or resume_meta.get('system_loader_control_completed')is not True
|
|
or resume_meta.get('loaded_modules')!={}
|
|
or resume_meta.get('late_bridge_load_attempted')is True):
|
|
raise ValueError('Late Bridge requires an unconsumed completed system-loader owner')
|
|
elif failure_journal.exists():
|
|
require_previous_closed(json.loads(failure_journal.read_text()),profile,paths,api)
|
|
if journal.exists():
|
|
if resume_meta and json.loads(journal.read_text()).get('pid')==resume_meta['pid']:
|
|
raise ValueError('Existing successful owner handoff must not be repeated')
|
|
previous=digest(journal)
|
|
if profile.get('previous_journal_sha256')!=previous:
|
|
if journal.stat().st_size>131072:raise ValueError('Previous runtime journal exceeds bound')
|
|
require_previous_closed(json.loads(journal.read_text()),profile,paths,api)
|
|
backup=state/'windows-bootstrap-backups';backup.mkdir(exist_ok=True)
|
|
target=backup/('native-engine-pe.'+previous+'.json')
|
|
if target.exists() and digest(target)!=previous:raise ValueError('Journal recovery collision')
|
|
if not target.exists():target.write_bytes(journal.read_bytes())
|
|
startup=STARTUPINFO();startup.cb=C.sizeof(startup);info=PROCESS_INFORMATION();pending=[];handed=False
|
|
command=C.create_unicode_buffer('"'+str(paths['client'])+'" -d3d11')
|
|
environment={k:v for k,v in os.environ.items()if k.casefold()!='path'}
|
|
environment['PATH']=str(paths['wire'].parent)+';'+str(root/'build')+';'+os.environ.get('PATH','')
|
|
environment=C.create_unicode_buffer('\0'.join(k+'='+v for k,v in sorted(environment.items(),key=lambda row:row[0].casefold()))+'\0\0')
|
|
if resume_meta is None:
|
|
api.checked(api.k.CreateProcessW(str(paths['client']),command,None,None,False,0x400,C.cast(environment,C.c_void_p),str(paths['client'].parent),C.byref(startup),C.byref(info)))
|
|
else:
|
|
info.dwProcessId=resume_meta['pid']
|
|
info.hProcess=api.k.OpenProcess(0x100000|0x1000|0x0400|0x0010|0x0020|0x0008|0x0002,False,info.dwProcessId)
|
|
api.checked(info.hProcess)
|
|
|
|
identity=None;loaded={};system_attempted=False;system_completed=False;partial_completed=False
|
|
late_attempted=False;late_completed=False
|
|
system_before=None;system_after=None
|
|
try:
|
|
identity=api.identity(info.hProcess)
|
|
if identity[1].casefold()!=str(paths['client']).casefold():raise ValueError('Created image identity mismatch')
|
|
if resume_meta and identity[0]!=resume_meta['starttime']:raise ValueError('Preserved owned creation identity changed')
|
|
if api.k.WaitForSingleObject(info.hProcess,0)==0:raise ValueError('Owned initial process already exited')
|
|
api._startup_owner=dict(pid=int(info.dwProcessId),process=info.hProcess,identity=identity,deadline=time.monotonic()+120)
|
|
if _resume is not None and _resume.get('module_snapshot')is not None:
|
|
snap=_resume['module_snapshot']
|
|
if (snap.get('status')!='CURRENT_OWNED_MODULE_SNAPSHOT_PASS' or snap.get('pid')!=info.dwProcessId
|
|
or snap.get('starttime')!=identity[0]or type(snap.get('modules'))is not list or not 1<=len(snap['modules'])<=4096):
|
|
raise ValueError('Exact owned module-read receipt required')
|
|
api._startup_modules=snap['modules']
|
|
|
|
loaded={}
|
|
modules=getattr(api,'_startup_modules',None)
|
|
if modules is None:modules=api.modules(info.dwProcessId)
|
|
if late_bridge:
|
|
if any(Path(row['path']).name.casefold()in('gwnativebridge.dll','gwnativewire.dll')for row in modules):
|
|
raise ValueError('Hybrid module already present before late Bridge')
|
|
late_attempted=True
|
|
atomic_json(failure_journal,{**resume_meta,'preserved_stage':'late-bridge-submitting-v1',
|
|
'late_bridge_load_attempted':True,'late_bridge_load_completed':False})
|
|
if before_modules and not late_bridge:
|
|
if any(Path(row['path']).name.casefold()in('gwnativebridge.dll','gwnativewire.dll')for row in modules):
|
|
raise ValueError('Hybrid module present before system-loader control')
|
|
if system_control:
|
|
# Fixed OS module only: its exact full path must already match
|
|
# the same local 64-bit Windows module. No caller path or new
|
|
# third-party image is accepted by this diagnostic operation.
|
|
local=api.k.GetModuleHandleW('kernel32.dll');api.checked(local)
|
|
name=C.create_unicode_buffer(32768)
|
|
api.checked(api.k.GetModuleFileNameW(local,name,len(name)))
|
|
if Path(name.value).name.casefold()!='kernel32.dll':raise ValueError('Canonical system module differs')
|
|
system_before=matching_module(modules,Path(name.value))
|
|
system_attempted=True
|
|
atomic_json(failure_journal,{**resume_meta,'preserved_stage':'system-loader-submitting-v1',
|
|
'system_loader_control_attempted':True,'system_module_before':system_before})
|
|
# Call the unchanged loader even though this system module is
|
|
# already present. This is the single operation under test.
|
|
system_after=inject(api,info.hProcess,info.dwProcessId,Path(name.value),pending)
|
|
if any(system_before[key]!=system_after[key]for key in('base','size','path')):
|
|
raise ValueError('System module identity changed during loader control')
|
|
if any(Path(row['path']).name.casefold()in('gwnativebridge.dll','gwnativewire.dll')
|
|
for row in getattr(api,'_last_modules',None)or[]):
|
|
raise ValueError('Hybrid module appeared during system-loader control')
|
|
system_completed=True
|
|
partial_completed=True
|
|
return dict(pid=int(info.dwProcessId),starttime=identity[0],imagepath=identity[1],
|
|
reviewed_preauth_stage='before-modules-v1',bootstrap_handoff=False,
|
|
custody_path=str(failure_journal),hybrid_modules_loaded=False,wire_load_attempted=False,
|
|
system_loader_control_attempted=system_attempted,system_loader_control_completed=system_completed,
|
|
system_module_before=system_before,system_module_after=system_after,
|
|
debug_observation_started=False,native_callbacks_installed=False,
|
|
authentication_attempted=False,full_startup_verified=False)
|
|
# LoadLibraryW does not imply DLL_LOAD_DIR dependency search. Load the
|
|
# declared canonical bridge first, using the same pinned-path loader.
|
|
for name in ['bridge','wire']:
|
|
if api.identity(info.hProcess)!=identity:raise ValueError('Owned child identity changed')
|
|
exact=[m for m in modules if m['path'].casefold()==str(paths[name]).casefold()]
|
|
foreign=[m for m in modules if Path(m['path']).name.casefold()==paths[name].name.casefold() and m not in exact]
|
|
if foreign:raise ValueError('Foreign canonical module already loaded')
|
|
if exact:loaded[name]=matching_module(modules,paths[name])
|
|
else:
|
|
api._startup_modules=modules
|
|
loaded[name]=inject(api,info.hProcess,info.dwProcessId,paths[name],pending)
|
|
modules=getattr(api,'_last_modules',None)or api.modules(info.dwProcessId)
|
|
if (bridge_only or late_bridge)and name=='bridge':
|
|
# Deliberately retain unhanded custody through the existing
|
|
# failure/partial-owner journal. No Wire frame or full owner
|
|
# journal exists at this diagnostic boundary.
|
|
result=dict(pid=int(info.dwProcessId),starttime=identity[0],imagepath=identity[1],
|
|
bridge={**loaded['bridge'],'exports':exports['bridge']},
|
|
reviewed_preauth_stage='late-bridge-loaded-v1'if late_bridge else'bridge-loaded-v1',bootstrap_handoff=False,
|
|
custody_path=str(failure_journal),wire_load_attempted=False,
|
|
debug_observation_started=False,native_callbacks_installed=False,
|
|
authentication_attempted=False,full_startup_verified=False)
|
|
if late_bridge:
|
|
late_completed=True
|
|
result.update(late_bridge_load_attempted=True,late_bridge_load_completed=True,
|
|
system_loader_control_attempted=True,system_loader_control_completed=True)
|
|
return result
|
|
frame=loaded['wire']['base']+exports['wire']['gw_wire_frame_data'];header=api.read(info.hProcess,frame,56)
|
|
if struct.unpack_from('<II',header)!=(1,1080) or any(header[8:]):raise ValueError('Fresh wire frame is not pristine')
|
|
# install_ping owns the frame publication; leave filename and command
|
|
# pristine here so its original guarded transaction can initialize them.
|
|
data=dict(template);data.update(windows_native_bootstrap=True,host='windows_owned_loadlibrary',wine_prefix=str(runtime/'native-wine-prefix'),pid=int(info.dwProcessId),starttime=identity[0],image_path=identity[1],dll_sha256=profile['bridge']['sha256'],exports=exports['bridge'],restored=False)
|
|
if resume_meta:data['resumed_owned_bootstrap']={'pid':resume_meta['pid'],'starttime':resume_meta['starttime'],'previous_held_loader_allocations':resume_meta.get('loader_allocations_held_until_process_exit',0),'new_process_created':False,'credentials_submitted':False}
|
|
data['wire_unix_library']={'backend_transport':profile.get('backend_transport','native-Windows'),'core_path':str(paths['backend']),'core_sha256':profile['backend']['sha256'],'wire_unix_path':str(paths['backend']),'wire_unix_sha256':profile['backend']['sha256'],'source_codec_path':str(paths['codec']),'source_codec_sha256':profile['codec']['sha256'],'platform':'native-Windows'}
|
|
if 'backend_host'in paths:data['owned_backend_worker']={'path':str(paths['backend_host']),'sha256':profile['backend_host']['sha256'],'loaded_in_original_process':False}
|
|
auxiliary=template.get('auxiliary_dependencies',[])
|
|
if not isinstance(auxiliary,list) or any(not isinstance(row,dict) for row in auxiliary):raise ValueError('Original auxiliary manifest list required')
|
|
auxiliary=[dict(row) for row in auxiliary];matches=[i for i,row in enumerate(auxiliary) if row.get('file')=='GWNativeWire.dll']
|
|
if len(matches)>1:raise ValueError('Duplicate wire dependency metadata')
|
|
wire_metadata={'file':'GWNativeWire.dll','path':str(paths['wire']),'sha256':profile['wire']['sha256'],'exports':exports['wire']}
|
|
if matches:auxiliary[matches[0]].update(wire_metadata)
|
|
else:auxiliary.append(wire_metadata)
|
|
data['auxiliary_dependencies']=auxiliary
|
|
data['windows_modules']={name:{**loaded[name],'exports':exports[name],'sha256':profile[name]['sha256']} for name in loaded}
|
|
atomic_json(journal,data);handed=True
|
|
return {'pid':int(info.dwProcessId),'starttime':identity[0],'imagepath':identity[1],'bridge':{**loaded['bridge'],'exports':exports['bridge']},'wire':{**loaded['wire'],'exports':exports['wire']},'backend_path':str(paths['backend']),'journal_path':str(journal),'authentication_attempted':False,'frame_filename_deferred_to_install_ping':True}
|
|
finally:
|
|
try:
|
|
if not handed:
|
|
# These HANDLEs come only from our CreateProcess, never from a PID
|
|
# supplied by callers. Kill only this unhanded child on failure;
|
|
# process exit releases any allocation still used by a loader thread.
|
|
if profile.get('backend_transport')=='owned-stdio-ipc-v1':
|
|
# Keep a new original guard dialog/report and any still-used
|
|
# loader allocation intact. The caller must stop this path;
|
|
# never launch another process over this owned failure.
|
|
pins={'core_path':str(paths['backend']),'core_sha256':profile['backend']['sha256'],
|
|
'wire_unix_path':str(paths['backend']),'wire_unix_sha256':profile['backend']['sha256'],
|
|
'source_codec_path':str(paths['codec']),'source_codec_sha256':profile['codec']['sha256']}
|
|
partial_details={}
|
|
if late_bridge:
|
|
partial_details=dict(preserved_stage='late-bridge-loaded-v1'if late_completed else'late-bridge-failed-v1',
|
|
preservation_reason='reviewed-late-bridge-only-stage',bootstrap_failure=not late_completed,
|
|
late_bridge_load_attempted=late_attempted,late_bridge_load_completed=late_completed,
|
|
system_loader_control_attempted=resume_meta['system_loader_control_attempted'],
|
|
system_loader_control_completed=resume_meta['system_loader_control_completed'],
|
|
system_module_before=resume_meta.get('system_module_before'),system_module_after=resume_meta.get('system_module_after'))
|
|
elif bridge_only and 'bridge'in loaded:
|
|
partial_details=dict(preserved_stage='bridge-loaded-v1',preservation_reason='reviewed-partial-module-stage',bootstrap_failure=False)
|
|
elif before_modules:
|
|
preserved=('system-loader-completed-v1'if system_completed else'system-loader-failed-v1')if system_attempted else('before-modules-v1'if partial_completed else'before-modules-failed-v1')
|
|
partial_details=dict(preserved_stage=preserved,preservation_reason='reviewed-partial-system-loader-stage',
|
|
bootstrap_failure=not partial_completed,system_loader_control_attempted=system_attempted,
|
|
system_loader_control_completed=system_completed,system_module_before=system_before,system_module_after=system_after)
|
|
atomic_json(failure_journal,dict(windows_native_bootstrap=True,pid=int(info.dwProcessId),
|
|
starttime=identity[0]if identity else 0,image_path=str(paths['client']),
|
|
dll_sha256=profile['bridge']['sha256'],wire_unix_library=pins,
|
|
backend_transport='owned-stdio-ipc-v1',bootstrap_handoff=False,
|
|
**partial_details,
|
|
loader_allocations_held_until_process_exit=len(pending)+(resume_meta.get('loader_allocations_held_until_process_exit',0)if resume_meta else 0),loaded_modules=loaded,
|
|
original_client_preserved=api.k.WaitForSingleObject(info.hProcess,0)!=0,
|
|
credentials_submitted=False,automatic_retry_allowed=False,
|
|
last_load_attempt=getattr(api,'_last_load_attempt',None),
|
|
observed_module_snapshot=(dict(status='CURRENT_OWNED_MODULE_SNAPSHOT_PASS',pid=int(info.dwProcessId),starttime=identity[0],modules=api._last_modules)if identity and getattr(api,'_last_modules',None)else None)))
|
|
elif api.k.WaitForSingleObject(info.hProcess,0)!=0:
|
|
api.checked(api.k.TerminateProcess(info.hProcess,0x47574253))
|
|
if api.k.WaitForSingleObject(info.hProcess,5000)!=0:raise RuntimeError('Owned bootstrap child cleanup incomplete')
|
|
finally:
|
|
api._startup_owner=None;api._startup_modules=None
|
|
if info.hThread:api.k.CloseHandle(info.hThread)
|
|
api.k.CloseHandle(info.hProcess)
|
|
|
|
def resume_owned(bundle_root,expected_pid,expected_starttime,*,module_snapshot=None,system_loader_control=False,late_bridge_only=False,_api=None):
|
|
"""Explicit continuation of our unhanded preauth child; never CreateProcess.
|
|
|
|
The caller supplies the saved exact lifetime, not an arbitrary target PID.
|
|
A successful existing module receipt can be consumed once; post-load module
|
|
verification is still performed by the unchanged injector.
|
|
"""
|
|
if type(system_loader_control)is not bool:raise ValueError('Fixed system-loader control selector must be boolean')
|
|
if type(late_bridge_only)is not bool or(system_loader_control and late_bridge_only):raise ValueError('One fixed late-Bridge selector must be boolean')
|
|
return launch_owned(bundle_root,_resume=dict(pid=expected_pid,starttime=expected_starttime,module_snapshot=module_snapshot,
|
|
system_loader_control=system_loader_control,late_bridge_only=late_bridge_only),_api=_api)
|
|
|
|
|
|
def main():
|
|
p=argparse.ArgumentParser(description=__doc__);p.add_argument('--bundle-root',required=True,type=Path);p.add_argument('--receipt',required=True,type=Path);a=p.parse_args()
|
|
result=launch_owned(a.bundle_root);atomic_json(a.receipt,result);print('Owned native Windows client bootstrapped; no authentication attempted.')
|
|
if __name__=='__main__':main()
|