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

568 lines
28 KiB
Python

"""Owned Linux, process-wide hardware witness for the pinned loader writer.
This is an opt-in diagnostic provider, not a game launch path. The owner must
launch the child and supply its PID/start time. It stops that one thread group,
admits every existing task, follows clone stops before new tasks run, and
restores each task's debug registers before detach. It never changes client
code, argument registers, or loader status fields.
"""
from __future__ import annotations
import ctypes as C
from dataclasses import dataclass
import errno
import hashlib
import os
from pathlib import Path
import signal
import subprocess
import threading
import time
from engine_main_thread_probe import Registers
ROOT = Path(__file__).resolve().parents[1]
LOADER_SHA256 = 'ce09256540963a1920fe375af5b6fb37817f65ba0756b7c859c23288990f98dd'
LOADER_ENTRY_RVA = 0xA27CA0
LOADER_ENTRY_PREFIX = bytes.fromhex('4157415641554154565755534881ec88')
LOADER_IMAGE_SIZE = 0x29A0000
LOADER_IDENTITY_BITS = 31
PTRACE_GETEVENTMSG = 0x4201
PTRACE_O_TRACECLONE = 1 << 3
PTRACE_EVENT_CLONE = 3
PTRACE_EVENT_STOP = 128
WALL = 0x40000000
DEBUG_OFFSET = 848 # Asserted against the existing native-ptrace-abi utility.
SAVED_DR = (0, 1, 2, 3, 6, 7)
TARGET_STATUSES = frozenset((0x302, 0x303))
_SAFE_FAILURE_CODES = {
'Owned loader process identity changed': 'owned_identity_changed',
'Pinned loader header mapping unavailable or ambiguous': 'loader_header_unavailable',
'Owned child identity changed': 'owned_identity_changed',
'Owned child is already stopped by another action': 'child_already_stopped',
'Pinned loader image differs': 'loader_disk_hash_mismatch',
'Pinned loader mapping ambiguous': 'loader_header_ambiguous',
'Pinned loader writer RVA differs': 'loader_base_changed',
'Pinned loader PE header differs': 'loader_pe_header_mismatch',
'Pinned loader image size differs': 'loader_image_size_invalid',
'Pinned loader writer page not executable': 'writer_page_not_rx',
'Pinned loader writer prefix differs': 'writer_prefix_mismatch',
'Trusted loader metadata incomplete': 'trusted_metadata_incomplete',
'Trusted loader metadata differs': 'trusted_metadata_mismatch',
'Pinned loader live PE header differs': 'loader_live_pe_mismatch',
'Thread inventory changed during frozen admission': 'thread_inventory_changed',
'Existing hardware debug slot occupied': 'debug_slot_occupied',
'Clone did not inherit expected owned debug slot': 'clone_debug_state_mismatch',
}
def sanitized_failure(error: BaseException, witness: WriterEntryObserver | None = None) -> dict:
"""Fixed metadata only; callers may continue if rollback is fully clean."""
reason = _SAFE_FAILURE_CODES.get(str(error), 'unclassified')
return {
'error_type': type(error).__name__,
'error_phase': getattr(witness, 'phase', 'loader-discovery'),
'error_predicate': reason,
'clean_unarmed': witness is None or (
not witness.threads and not witness.group_stop_owned and not witness.armed),
}
def process_identity(pid: int) -> tuple[int, int]:
"""Return (parent PID, proc start ticks) without parsing the comm field."""
raw = (Path('/proc') / str(pid) / 'stat').read_text()
fields = raw[raw.rfind(')') + 2:].split()
return int(fields[1]), int(fields[19])
def task_ids(pid: int) -> set[int]:
return {int(path.name) for path in (Path('/proc') / str(pid) / 'task').iterdir()}
def stopped_task(tid: int) -> bool:
status = (Path('/proc') / str(tid) / 'status').read_text()
state = next((line for line in status.splitlines() if line.startswith('State:')), '')
return state.split()[1:2] in (['T'], ['t'])
def pe_identity(read_at) -> tuple[int, int, int, int, int, int]:
"""Bounded immutable PE fields: offset, machine, sections, time, magic, size."""
dos = read_at(0, 64)
if len(dos) != 64 or dos[:2] != b'MZ':
raise ValueError('Pinned loader PE header differs')
offset = int.from_bytes(dos[0x3c:0x40], 'little')
if not 0x40 <= offset <= 0x1000:
raise ValueError('Pinned loader PE header differs')
nt = read_at(offset, 84)
if len(nt) != 84 or nt[:4] != b'PE\0\0':
raise ValueError('Pinned loader PE header differs')
return (offset, int.from_bytes(nt[4:6], 'little'),
int.from_bytes(nt[6:8], 'little'),
int.from_bytes(nt[8:12], 'little'),
int.from_bytes(nt[24:26], 'little'),
int.from_bytes(nt[80:84], 'little'))
@dataclass
class ThreadState:
saved: dict[int, int] | None = None
stopped: bool = False
armed: bool = False
pending_signal: int = 0
class WriterEntryObserver:
def __init__(self, pid: int, starttime: int, entry: int, prefix: bytes,
*, module_path: Path | None = None, module_sha256: str | None = None,
trusted_loader_base: int | None = None,
trusted_loader_size: int | None = None,
trusted_identity_bits: int | None = None,
timeout: float = 120, max_nonmatching: int = 256,
abi_path: Path | None = None):
if (os.name != 'posix' or type(pid) is not int or pid <= 0 or
type(starttime) is not int or starttime <= 0):
raise ValueError('Owned Linux process identity required')
if type(entry) is not int or entry <= 0 or not isinstance(prefix, bytes) or not 1 <= len(prefix) <= 32:
raise ValueError('Fixed executable entry and prefix required')
if not 0 < timeout <= 120 or not 0 < max_nonmatching <= 256:
raise ValueError('Bounded writer observation required')
self.pid, self.starttime, self.entry, self.prefix = pid, starttime, entry, prefix
self.module_path = module_path.resolve(strict=True) if module_path is not None else None
self.module_sha256 = module_sha256
trusted = (trusted_loader_base, trusted_loader_size, trusted_identity_bits)
if any(value is not None for value in trusted):
if self.module_path is None or any(type(value) is not int for value in trusted):
raise ValueError('Trusted loader metadata incomplete')
if (trusted_loader_base <= 0 or trusted_loader_size != LOADER_IMAGE_SIZE or
trusted_identity_bits != LOADER_IDENTITY_BITS or
trusted_loader_base + trusted_loader_size >= 0x0000800000000000 or
entry != trusted_loader_base + LOADER_ENTRY_RVA):
raise ValueError('Trusted loader metadata differs')
self.trusted_loader_base = trusted_loader_base
self.trusted_loader_size = trusted_loader_size
self.timeout, self.max_nonmatching = timeout, max_nonmatching
self.threads: dict[int, ThreadState] = {}
self.nonmatching = 0
self.initial_threads: set[int] = set()
self.clone_threads: set[int] = set()
self.group_stop_owned = False
self.armed = False
self.phase = 'constructed'
self.libc = C.CDLL(None, use_errno=True)
self.libc.ptrace.argtypes = [C.c_ulong, C.c_ulong, C.c_void_p, C.c_void_p]
self.libc.ptrace.restype = C.c_long
utility = Path(abi_path or ROOT / 'build/native-ptrace-abi')
import json
self.abi = json.loads(subprocess.check_output([str(utility)]))
if self.abi['debug_offset'] != DEBUG_OFFSET or self.abi['register_bytes'] != C.sizeof(Registers) or self.abi['wall'] != WALL:
raise RuntimeError('Host ptrace register ABI differs')
def _ptrace(self, request: int, tid: int, address: int = 0, data: int = 0) -> int:
C.set_errno(0)
result = self.libc.ptrace(request, tid, C.c_void_p(address), C.c_void_p(data))
error = C.get_errno()
if result == -1 and error:
raise OSError(error, 'Owned-child ptrace operation failed')
return result
def _dr(self, tid: int, index: int, value: int | None = None) -> int:
address = DEBUG_OFFSET + 8 * index
if value is None:
return self._ptrace(self.abi['peekuser'], tid, address) & 0xffffffffffffffff
self._ptrace(self.abi['pokeuser'], tid, address, value)
return value
def _regs(self, tid: int) -> Registers:
registers = Registers()
self._ptrace(self.abi['getregs'], tid, 0, C.addressof(registers))
return registers
def _verify_owner(self) -> None:
parent, start = process_identity(self.pid)
if parent != os.getpid() or start != self.starttime:
raise ValueError('Owned child identity changed')
def _freeze_group(self) -> set[int]:
self._verify_owner()
existing = task_ids(self.pid)
if not existing or any(stopped_task(tid) for tid in existing):
raise ValueError('Owned child is already stopped by another action')
os.kill(self.pid, signal.SIGSTOP)
self.group_stop_owned = True
deadline = time.monotonic() + 3
previous: set[int] = set()
while time.monotonic() < deadline:
current = task_ids(self.pid)
if current and current == previous and all(stopped_task(tid) for tid in current):
return current
previous = current
time.sleep(.005)
raise TimeoutError('Owned thread group did not freeze')
def _verify_entry(self) -> None:
maps = (Path('/proc') / str(self.pid) / 'maps').read_text().splitlines()
if self.module_path is not None:
if self.module_sha256 is None or hashlib.sha256(self.module_path.read_bytes()).hexdigest() != self.module_sha256:
raise ValueError('Pinned loader image differs')
with self.module_path.open('rb') as module:
def disk_read(offset, size):
module.seek(offset)
return module.read(size)
disk_pe = pe_identity(disk_read)
if disk_pe[1] != 0x8664 or disk_pe[4] != 0x20b:
raise ValueError('Pinned loader PE header differs')
self.module_size = disk_pe[5]
if self.module_size != LOADER_IMAGE_SIZE:
raise ValueError('Pinned loader image size differs')
if self.trusted_loader_base is None:
headers = [int(parts[0].split('-')[0], 16) for line in maps
if (parts := line.split(maxsplit=5))[2] == '00000000' and
len(parts) == 6 and Path(parts[5]).resolve() == self.module_path]
if len(headers) != 1:
raise ValueError('Pinned loader mapping ambiguous')
self.module_base = headers[0]
else:
self.module_base = self.trusted_loader_base
if not any(int(parts[0].split('-')[0], 16) <= self.module_base and
self.module_base + 0x1000 <= int(parts[0].split('-')[1], 16) and
'r' in parts[1]
for line in maps if (parts := line.split())):
raise ValueError('Pinned loader live PE header differs')
fd = os.open(f'/proc/{self.pid}/mem', os.O_RDONLY)
try:
try:
live_pe = pe_identity(lambda offset, size: os.pread(
fd, size, self.module_base + offset))
except ValueError:
raise ValueError('Pinned loader live PE header differs') from None
finally:
os.close(fd)
if live_pe != disk_pe or live_pe[5] != self.trusted_loader_size:
raise ValueError('Pinned loader live PE header differs')
if self.entry != self.module_base + LOADER_ENTRY_RVA or \
self.entry + len(self.prefix) > self.module_base + self.module_size:
raise ValueError('Pinned loader writer RVA differs')
if not any(int(parts[0].split('-')[0], 16) <= self.entry and
self.entry + len(self.prefix) <= int(parts[0].split('-')[1], 16) and
'r' in parts[1] and 'x' in parts[1]
for line in maps if (parts := line.split())):
raise ValueError('Pinned loader writer page not executable')
fd = os.open(f'/proc/{self.pid}/mem', os.O_RDONLY)
try:
actual = os.pread(fd, len(self.prefix), self.entry)
finally:
os.close(fd)
if actual != self.prefix:
raise ValueError('Pinned loader writer prefix differs')
def _wait_tid(self, tid: int, deadline: float) -> int:
while time.monotonic() < deadline:
try:
got, status = os.waitpid(tid, WALL | os.WNOHANG)
except ChildProcessError:
raise RuntimeError('Owned tracee disappeared before admission') from None
if got == tid:
return status
time.sleep(.001)
raise TimeoutError('Owned tracee stop timed out')
def _save_arm(self, tid: int, inherited_from: int | None = None) -> None:
state = self.threads[tid]
if not state.stopped:
raise RuntimeError('Tracee not stopped for debug admission')
observed = {index: self._dr(tid, index) for index in SAVED_DR}
if inherited_from is None:
saved = observed
state.saved = saved # Claim rollback before the first register write.
if saved[7] & 0xff:
raise RuntimeError('Existing hardware debug slot occupied')
else:
parent = self.threads[inherited_from]
if parent.saved is None or not parent.armed:
raise RuntimeError('Clone parent debug state not admitted')
# Linux clone inherits the parent's *armed* DRs. The child's
# uninstrumented state would have inherited the saved originals.
saved = dict(parent.saved)
state.saved = saved # Also owns rollback if validation rejects.
expected_dr7 = (saved[7] & ~(3 | (0xf << 16))) | 1
# This kernel copies the enabled DR7 bit but clears DR0 on clone.
# Both the copied and cleared forms are safe while the child holds
# its automatic clone stop; install the exact target before resume.
if (observed[0] not in (self.entry, saved[0]) or
observed[7] not in (expected_dr7, saved[7]) or
any(observed[i] != saved[i] for i in (1, 2, 3))):
raise RuntimeError('Clone did not inherit expected owned debug slot')
self._dr(tid, 0, self.entry)
self._dr(tid, 6, 0)
self._dr(tid, 7, (saved[7] & ~(3 | (0xf << 16))) | 1)
state.armed = True
def arm(self) -> dict:
"""Stop the owned group, admit every task, then resume it fully armed."""
try:
self.phase = 'owner-freeze'
initial = self._freeze_group()
self.initial_threads = set(initial)
self.phase = 'loader-code-admission'
self._verify_entry()
self.phase = 'thread-seize'
for tid in sorted(initial):
self._ptrace(self.abi['seize'], tid, 0, PTRACE_O_TRACECLONE)
self.threads[tid] = ThreadState()
self.phase = 'thread-stop'
for tid in sorted(initial):
self._ptrace(self.abi['interrupt'], tid)
deadline = time.monotonic() + 3
self.phase = 'debug-arm'
for tid in sorted(initial):
status = self._wait_tid(tid, deadline)
if not os.WIFSTOPPED(status):
raise RuntimeError('Existing tracee did not stop')
self.threads[tid].stopped = True
self._save_arm(tid)
if task_ids(self.pid) != initial:
raise RuntimeError('Thread inventory changed during frozen admission')
# All tasks still hold ptrace stops. SIGCONT only lifts our group
# stop; none may execute before its own PTRACE_CONT below.
self.phase = 'release'
os.kill(self.pid, signal.SIGCONT)
self.group_stop_owned = False
for tid in sorted(initial):
self._ptrace(self.abi['cont'], tid)
self.threads[tid].stopped = False
self.armed = True
self.phase = 'observing'
return {'initial_thread_count': len(initial), 'all_initial_armed': True}
except BaseException:
self.close()
raise
def _clone(self, parent: int) -> None:
message = C.c_ulonglong()
self._ptrace(PTRACE_GETEVENTMSG, parent, 0, C.addressof(message))
tid = int(message.value)
if tid <= 0 or tid in self.threads:
raise RuntimeError('Clone event TID differs')
self.threads[tid] = ThreadState()
self.clone_threads.add(tid)
status = self._wait_tid(tid, time.monotonic() + 3)
if not os.WIFSTOPPED(status):
raise RuntimeError('New tracee did not stop before execution')
self.threads[tid].stopped = True
self._save_arm(tid, inherited_from=parent)
self._ptrace(self.abi['cont'], tid)
self.threads[tid].stopped = False
self._ptrace(self.abi['cont'], parent)
self.threads[parent].stopped = False
def _caller(self, rsp: int) -> tuple[str | None, str | None]:
if rsp % 8:
return None, None
fd = os.open(f'/proc/{self.pid}/mem', os.O_RDONLY)
try:
raw = os.pread(fd, 8, rsp)
finally:
os.close(fd)
if len(raw) != 8:
return None, None
address = int.from_bytes(raw, 'little')
if (self.module_path is not None and
self.module_base <= address < self.module_base + self.module_size):
return hex(address), f'{self.module_path.name}+0x{address-self.module_base:x}'
for line in (Path('/proc') / str(self.pid) / 'maps').read_text().splitlines():
parts = line.split(maxsplit=5)
lo, hi = (int(x, 16) for x in parts[0].split('-'))
if lo <= address < hi and 'x' in parts[1]:
return hex(address), f'{parts[5] if len(parts) == 6 else "[anonymous mapping]"}+0x{address-lo:x}'
return None, None
def observe(self, cancel: threading.Event | None = None) -> dict:
if not self.armed:
raise RuntimeError('All-thread admission required')
deadline = time.monotonic() + self.timeout
result = {'status': 'timeout'}
try:
while time.monotonic() < deadline:
if cancel is not None and cancel.is_set():
result = {'status': 'cancelled'}
break
progressed = False
for tid in list(self.threads):
try:
got, status = os.waitpid(tid, WALL | os.WNOHANG)
except ChildProcessError:
self.threads.pop(tid, None)
continue
if not got:
continue
progressed = True
if os.WIFEXITED(status) or os.WIFSIGNALED(status):
self.threads.pop(tid, None)
continue
if not os.WIFSTOPPED(status):
raise RuntimeError('Unexpected owned tracee wait status')
state = self.threads[tid]
state.stopped = True
event = status >> 16
stopped_signal = os.WSTOPSIG(status)
if event == PTRACE_EVENT_CLONE:
self._clone(tid)
continue
if event == PTRACE_EVENT_STOP:
self._ptrace(self.abi['cont'], tid)
state.stopped = False
continue
if stopped_signal == signal.SIGTRAP:
registers = self._regs(tid)
if self._dr(tid, 6) & 1 and registers.rip == self.entry:
value = int(registers.r9) & 0xffffffff
hit_unix_ns = time.time_ns()
hit_monotonic_ns = time.monotonic_ns()
self._dr(tid, 6, 0)
if value in TARGET_STATUSES:
caller, module = self._caller(int(registers.rsp))
result = {'status': 'matched', 'writer_input': value,
'tid': tid, 'caller_return': caller,
'caller_module_rva': module,
'entry_rsp_mod16': int(registers.rsp) % 16,
'hit_unix_ns': hit_unix_ns,
'hit_monotonic_ns': hit_monotonic_ns,
'loader_base': hex(self.module_base),
'loader_image_size': self.module_size,
'loader_sha256': self.module_sha256,
'writer_rva': hex(LOADER_ENTRY_RVA)}
return result
self.nonmatching += 1
if self.nonmatching >= self.max_nonmatching:
result = {'status': 'nonmatching-limit'}
return result
self._ptrace(self.abi['cont'], tid)
state.stopped = False
continue
# Preserve non-owned signals, including a genuine SIGTRAP.
self._ptrace(self.abi['cont'], tid, 0, stopped_signal)
state.stopped = False
if not self.threads:
result = {'status': 'client-exited'}
break
if not progressed:
time.sleep(.002)
return result
finally:
restored = self.close()
result.update({'initial_thread_count': len(self.initial_threads),
'clone_thread_count': len(self.clone_threads),
'nonmatching_hits': self.nonmatching,
'restored_thread_count': restored,
'debug_registers_restored': not self.threads})
def close(self) -> int:
"""Stop, restore and detach each live tracee; fail closed on errors."""
restored = 0
if not self.threads:
if self.group_stop_owned:
os.kill(self.pid, signal.SIGCONT)
self.group_stop_owned = False
self.armed = False
return 0
deadline = time.monotonic() + 3
# A clone can be pending when a different thread hits the writer.
# Admit its automatic stop to rollback ownership before detaching any
# parent; keep iterating until the whole traced group is stopped.
while any(not state.stopped for state in self.threads.values()):
for tid, state in list(self.threads.items()):
if state.stopped:
continue
try:
self._ptrace(self.abi['interrupt'], tid)
except OSError as error:
if error.errno == errno.ESRCH:
self.threads.pop(tid, None)
elif error.errno != errno.EIO: # Already in a ptrace stop.
raise
for tid, state in list(self.threads.items()):
if state.stopped:
continue
try:
status = self._wait_tid(tid, deadline)
except RuntimeError:
self.threads.pop(tid, None)
continue
if not os.WIFSTOPPED(status):
self.threads.pop(tid, None)
continue
state.stopped = True
event = status >> 16
sig = os.WSTOPSIG(status)
if event == PTRACE_EVENT_CLONE:
message = C.c_ulonglong()
self._ptrace(PTRACE_GETEVENTMSG, tid, 0, C.addressof(message))
child = int(message.value)
if child <= 0 or child in self.threads or state.saved is None:
raise RuntimeError('Unowned clone during rollback')
self.threads[child] = ThreadState(saved=dict(state.saved))
self.clone_threads.add(child)
child_status = self._wait_tid(child, deadline)
if not os.WIFSTOPPED(child_status):
raise RuntimeError('Clone did not stop during rollback')
self.threads[child].stopped = True
elif event != PTRACE_EVENT_STOP and sig == signal.SIGTRAP and state.armed:
registers = self._regs(tid)
if self._dr(tid, 6) & 1 and registers.rip == self.entry:
self._dr(tid, 6, 0) # Our breakpoint, never deliver it.
else:
state.pending_signal = sig
elif event != PTRACE_EVENT_STOP:
state.pending_signal = sig
if time.monotonic() >= deadline and any(not x.stopped for x in self.threads.values()):
raise TimeoutError('All-thread rollback stop timed out')
for tid, state in list(self.threads.items()):
if state.saved is not None:
for index, value in state.saved.items():
self._dr(tid, index, value)
if any(self._dr(tid, index) != value for index, value in state.saved.items()):
raise RuntimeError('Debug register restoration differs')
restored += 1
self._ptrace(self.abi['detach'], tid, 0, state.pending_signal)
self.threads.pop(tid, None)
if self.group_stop_owned:
os.kill(self.pid, signal.SIGCONT)
self.group_stop_owned = False
self.armed = False
return restored
def discover_loader_base(pid: int, starttime: int, loader_path: Path) -> int:
"""Resolve one exact mapped loader header; arm() rechecks it while stopped."""
parent, start = process_identity(pid)
if parent != os.getpid() or start != starttime:
raise ValueError('Owned loader process identity changed')
wanted = loader_path.resolve(strict=True)
headers = []
for line in (Path('/proc') / str(pid) / 'maps').read_text().splitlines():
parts = line.split(maxsplit=5)
if len(parts) == 6 and parts[2] == '00000000' and Path(parts[5]).resolve() == wanted:
headers.append(int(parts[0].split('-')[0], 16))
if len(headers) != 1:
raise ValueError('Pinned loader header mapping unavailable or ambiguous')
return headers[0]
def pinned_loader_observer(pid: int, starttime: int, loader_path: Path,
*, loader_base: int | None = None,
loader_size: int | None = None,
identity_bits: int | None = None,
**options) -> WriterEntryObserver:
if loader_base is None:
if loader_size is not None or identity_bits is not None:
raise ValueError('Trusted loader metadata incomplete')
loader_base = discover_loader_base(pid, starttime, loader_path)
elif loader_size is None or identity_bits is None:
raise ValueError('Trusted loader metadata incomplete')
return WriterEntryObserver(pid, starttime, loader_base + LOADER_ENTRY_RVA,
LOADER_ENTRY_PREFIX, module_path=loader_path,
module_sha256=LOADER_SHA256,
trusted_loader_base=loader_base if loader_size is not None else None,
trusted_loader_size=loader_size,
trusted_identity_bits=identity_bits, **options)