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

200 lines
9.4 KiB
Python

#!/usr/bin/env python3
"""Read only the public Wire realm-admission state of a direct child client.
The caller must launch the exact owned process and call ``prepare`` before
credentials. ``sample`` reads three fixed public headers once at the realm
transition. Original page protection comes from the existing in-process
startup log, never from a guessed Linux mapping or a protection change.
"""
import argparse
from collections import Counter
import hashlib
import os
from pathlib import Path
import re
import struct
import pefile
ROOT = Path(__file__).resolve().parents[1]
WIRE_SHA = "d2fcc0457f9a3347e0089f85876e934786e1953c6603aa535b63360ded0e5f2f"
EXPORT_SPANS = {"gw_wire_auth_data": 68, "gw_wire_realm_data": 48,
"gw_wire_frame_data": 28}
GOOD_LOG = ROOT / "runtime/continuation-20261106/e9-v44-qualified-compat-package-private/candidate/runtime/native-wine-prefix/drive_c/gw-native-startup-e9-v44-dxvk-package-once.log"
HELD_LOG = ROOT / "runtime/continuation-20261106/e9-v44-qualified-compat-package-private/candidate/runtime/native-wine-prefix/drive_c/gw-native-startup-e9-v44-dxvk-world180-once.log"
def file_sha(path):
digest = hashlib.sha256()
with path.open("rb") as source:
for block in iter(lambda: source.read(1048576), b""):
digest.update(block)
return digest.hexdigest()
def wire_artifact(package):
package = Path(package).resolve()
if package.parent != ROOT / "runtime" or not package.name.startswith("nohelper-compat-"):
raise ValueError("Require isolated nohelper compatibility package")
manifest = package / "nohelper-compat-package.private.json"
if manifest.is_symlink() or not manifest.is_file():
raise ValueError("Package manifest missing")
import json
metadata = json.loads(manifest.read_text())
if (metadata.get("kind") != "private-nohelper-e9-v44-direct-entry-compatibility-v1"
or metadata.get("inherited_siblings", {}).get("GWNativeWire.dll") != WIRE_SHA):
raise ValueError("Pinned package Wire identity differs")
path = package / "runtime/native-wine-prefix/drive_c/windows/system32/GWNativeWire.dll"
if path.is_symlink() or not path.is_file() or file_sha(path) != WIRE_SHA:
raise ValueError("Pinned Wire image differs")
image = pefile.PE(str(path), fast_load=True)
image.parse_data_directories(
directories=[pefile.DIRECTORY_ENTRY["IMAGE_DIRECTORY_ENTRY_EXPORT"]])
if image.FILE_HEADER.Machine != 0x8664 or image.OPTIONAL_HEADER.Magic != 0x20B:
raise ValueError("Wire PE architecture differs")
exports = {symbol.name.decode("ascii"): symbol.address
for symbol in image.DIRECTORY_ENTRY_EXPORT.symbols if symbol.name}
size = image.OPTIONAL_HEADER.SizeOfImage
if any(name not in exports or exports[name] <= 0 or
exports[name] + span > size for name, span in EXPORT_SPANS.items()):
raise ValueError("Public Wire export missing or out of bounds")
return path, size, {name: exports[name] for name in EXPORT_SPANS}
def process_identity(pid):
fields = (Path("/proc") / str(pid) / "stat").read_text().rsplit(")", 1)[1].split()
return int(fields[1]), int(fields[19])
def prepare(pid, package):
"""Attest an exact child and mapped Wire image before client input."""
parent, starttime = process_identity(pid)
if parent != os.getpid():
raise ValueError("Wire reader requires direct child ownership")
wire, image_size, exports = wire_artifact(package)
mapped = str(wire.resolve())
ranges, bases = [], []
for line in (Path("/proc") / str(pid) / "maps").read_text().splitlines():
parts = line.split(maxsplit=5)
if len(parts) < 5:
continue
low, high = (int(value, 16) for value in parts[0].split("-", 1))
ranges.append((low, high, parts[1]))
if (len(parts) == 6 and parts[2] == "00000000" and
parts[5] == mapped and "r" in parts[1]):
bases.append(low)
if len(bases) != 1:
raise ValueError("Exact mapped Wire base not unique")
base = bases[0]
if any(not any(low <= base + rva and base + rva + EXPORT_SPANS[name] <= high
and "r" in permission for low, high, permission in ranges)
for name, rva in exports.items()):
raise ValueError("Public Wire header is not mapped readable")
fd = os.open(f"/proc/{pid}/mem", os.O_RDONLY | os.O_CLOEXEC)
try:
dos = os.pread(fd, 64, base)
if len(dos) != 64 or dos[:2] != b"MZ":
raise ValueError("Mapped Wire DOS header differs")
nt_offset = struct.unpack_from("<I", dos, 0x3C)[0]
nt = os.pread(fd, 84, base + nt_offset) if nt_offset < 4096 else b""
if (len(nt) != 84 or nt[:4] != b"PE\0\0" or
struct.unpack_from("<H", nt, 4)[0] != 0x8664 or
struct.unpack_from("<H", nt, 24)[0] != 0x20B or
struct.unpack_from("<I", nt, 24 + 56)[0] != image_size):
raise ValueError("Mapped Wire PE header differs")
finally:
os.close(fd)
return {"pid": pid, "starttime": starttime, "wire_base": base,
"export_rvas": exports, "image_size": image_size,
"credential_payload_read": False}
def sample(pid, proof):
"""Read public headers once; never read the adjacent private credential fields."""
parent, starttime = process_identity(pid)
if (parent != os.getpid() or pid != proof["pid"] or
starttime != proof["starttime"]):
raise ValueError("Exact child lifetime changed")
base, exports = proof["wire_base"], proof["export_rvas"]
fd = os.open(f"/proc/{pid}/mem", os.O_RDONLY | os.O_CLOEXEC)
try:
raw = {name: os.pread(fd, span, base + exports[name])
for name, span in EXPORT_SPANS.items()}
finally:
os.close(fd)
if any(len(raw[name]) != span for name, span in EXPORT_SPANS.items()):
raise ValueError("Public Wire header short read")
account = struct.unpack("<II13iII", raw["gw_wire_auth_data"])
realm = struct.unpack("<II6iIIQ", raw["gw_wire_realm_data"])
frame = struct.unpack("<II5i", raw["gw_wire_frame_data"])
if account[:2] != (1, 1732) or realm[:2] != (1, 48) or frame[:2] != (1, 1080):
raise ValueError("Public Wire ABI changed")
if not 0 <= account[8] <= 64 or account[9] < -1 or account[9] >= 64:
raise ValueError("Public realm count/index out of bound")
return {
"status": "PASS_PARENT_PUBLIC_REALM_ADMISSION_SNAPSHOT",
"account": dict(zip(("state", "error", "auth_result", "discovery_result",
"realm_count", "selected_index", "transport_result",
"server_proof_verified", "transport_prepared"),
(account[3], account[4], account[6], account[7],
account[8], account[9], account[10], account[13],
account[14]))),
"realm": dict(zip(("stage", "error", "result", "state_before",
"state_after", "realm_index"),
(realm[2], realm[3], realm[5], realm[6], realm[7], realm[9]))),
"frame": {"command": frame[2], "error": frame[6]},
"credential_payload_read": False,
}
def admission_events(path):
"""Decode only existing numeric realm admission events from one run's log."""
path = Path(path)
if path.is_symlink() or not path.is_file() or path.stat().st_size > 1048576:
raise ValueError("Bounded owned startup log required")
counts = Counter()
page = None
retry = None
for line in path.read_text(errors="replace").splitlines():
if not line.startswith("GW_LOGIN_SITE event="):
continue
parts = dict((key, value) for key, value in re.findall(r"([a-z_]+)=([0-9]+)", line))
event = int(parts.get("event", "-1"))
if event in (10, 33, 36, 37, 100):
counts[event] += 1
if event in (36, 37) and "module=" in line:
page = page or {}
if event == 36:
page.update(state=int(parts["query"]), protection=int(parts["error"]))
else:
page.update(mapping_type=int(parts["query"]), identity_bits=int(parts["error"]))
if event == 36 and "module=" not in line:
retry = {"attempts": int(parts["query"]), "frame_command": int(parts["state"]),
"error": int(parts["error"])}
return {"events": dict(sorted(counts.items())), "constructor_page": page,
"retry_expiry": retry}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--check", action="store_true")
args = parser.parse_args()
if not args.check:
parser.error("Import prepare/sample into the exact child owner; --check is offline only")
wire_artifact(ROOT / "runtime/nohelper-compat-20261106")
good, held = admission_events(GOOD_LOG), admission_events(HELD_LOG)
if (good["events"].get(10) != 1 or good["events"].get(33) != 1 or
held["events"].get(10) or held["events"].get(33) or
held["constructor_page"] != {"state": 4096, "protection": 1,
"mapping_type": 262144, "identity_bits": 7} or
held["retry_expiry"] != {"attempts": 100, "frame_command": 7,
"error": 16}):
raise ValueError("Saved realm admission control/delta changed")
print("PASS_PINNED_PARENT_REALM_READER_AND_SAVED_ADMISSION_DELTA")
if __name__ == "__main__":
main()