367 files, from working commit b1a079a. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
247 lines
12 KiB
Python
Executable File
247 lines
12 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Exercise opt-in Source profile 4 in Wine, independently of the game.
|
|
|
|
Offline is the default. A real local account submission requires --real-once,
|
|
a matching artifact receipt, local-only listeners and a durable no-replay
|
|
state. This does not establish original client registration or World entry.
|
|
"""
|
|
import argparse
|
|
import fcntl
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import stat
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
RUNTIME = ROOT / 'runtime'
|
|
LEGACY = RUNTIME / 'continuation-20261031/source-local-profile-private/real-wine-boundary'
|
|
STATE = RUNTIME / 'source-local-account-fixture.state'
|
|
|
|
|
|
def digest(path):
|
|
h = hashlib.sha256()
|
|
with path.open('rb') as stream:
|
|
for chunk in iter(lambda: stream.read(1024 * 1024), b''):
|
|
h.update(chunk)
|
|
return h.hexdigest()
|
|
|
|
|
|
def project_file(value):
|
|
path = Path(value).resolve(strict=True)
|
|
if not path.is_relative_to(ROOT) or not path.is_file():
|
|
raise ValueError('Fixture artifact is not an owned project file')
|
|
return path
|
|
|
|
|
|
def private_fd(path):
|
|
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_CLOEXEC)
|
|
s = os.fstat(fd)
|
|
if not stat.S_ISREG(s.st_mode) or s.st_uid != os.getuid() or s.st_mode & 0o077:
|
|
os.close(fd)
|
|
raise ValueError('Local fixture file permissions differ')
|
|
return fd, s
|
|
|
|
|
|
def local_ready():
|
|
seen = set()
|
|
for name in ('tcp', 'tcp6'):
|
|
for line in Path('/proc/net', name).read_text().splitlines()[1:]:
|
|
fields = line.split()
|
|
ip, port = fields[1].split(':')
|
|
port = int(port, 16)
|
|
if fields[3] != '0A':
|
|
continue
|
|
if port == 19085:
|
|
raise ValueError('The external gateway is running')
|
|
if name == 'tcp' and ip.upper() in ('00000000', '0100007F') and port in (3724, 8090):
|
|
seen.add(port)
|
|
if seen != {3724, 8090}:
|
|
raise ValueError('The authorized local IPv4 listeners are unavailable')
|
|
|
|
|
|
def account_inputs():
|
|
cfg = json.loads((ROOT / 'secrets/native-local-bootstrap.json').read_text())
|
|
directory = Path(cfg['account_directory']).resolve(strict=True)
|
|
if not directory.is_relative_to((ROOT / 'secrets').resolve()):
|
|
raise ValueError('Local fixture account is outside the owned secret directory')
|
|
fd, before = private_fd(directory / 'account.json')
|
|
try:
|
|
raw = os.read(fd, min(before.st_size + 1, 65537))
|
|
after = os.fstat(fd)
|
|
if before.st_size > 65536 or len(raw) != before.st_size or (before.st_ino, before.st_size, before.st_mtime_ns) != (after.st_ino, after.st_size, after.st_mtime_ns):
|
|
raise ValueError('Local fixture account metadata changed')
|
|
info = json.loads(raw)
|
|
finally:
|
|
os.close(fd)
|
|
if info.get('auth_port') != 3724 or info.get('world_port') != 8090:
|
|
raise ValueError('Local fixture endpoint differs')
|
|
username = bytearray(info['username'].encode('ascii'))
|
|
if not 1 <= len(username) <= 32 or any(not 32 <= c <= 126 for c in username):
|
|
raise ValueError('Local fixture account format differs')
|
|
for name in ('version-hash.bin', 'addon-tail.bin'):
|
|
fd, s = private_fd(directory / name)
|
|
os.close(fd)
|
|
if (name == 'version-hash.bin' and s.st_size != 20) or (name == 'addon-tail.bin' and not 4 <= s.st_size <= 10000):
|
|
raise ValueError('Local fixture protocol input differs')
|
|
return directory, username
|
|
|
|
|
|
def legacy_result_safe():
|
|
if not (LEGACY / 'local-account-real-once.lock').exists():
|
|
return True
|
|
try:
|
|
result = json.loads((LEGACY / 'local-account-once-result.private.json').read_text())
|
|
output = (LEGACY / 'local-account-once.stdout.private').read_bytes()
|
|
return isinstance(result, dict) and result.get('exit_code') == 0 and result.get('attempts') == 1 and b'GW_LOCAL_PROFILE genuine-realm-prepared\n' in output
|
|
except (OSError, ValueError, TypeError):
|
|
return False
|
|
|
|
|
|
def save_state(fd, value):
|
|
content = (json.dumps(value, sort_keys=True) + '\n').encode()
|
|
os.lseek(fd, 0, os.SEEK_SET)
|
|
os.ftruncate(fd, 0)
|
|
os.write(fd, content)
|
|
os.fsync(fd)
|
|
|
|
|
|
def claim_once_state(path):
|
|
fd = os.open(path, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW | os.O_CLOEXEC, 0o600)
|
|
try:
|
|
metadata = os.fstat(fd)
|
|
if not stat.S_ISREG(metadata.st_mode) or metadata.st_uid != os.getuid() or metadata.st_mode & 0o077:
|
|
raise ValueError('One-shot state permissions differ')
|
|
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
previous = os.read(fd, 4097)
|
|
if previous:
|
|
try:
|
|
prior = json.loads(previous)
|
|
except (ValueError, TypeError):
|
|
raise ValueError('A previous local account attempt requires review') from None
|
|
if not isinstance(prior, dict) or prior.get('status') != 'success':
|
|
raise ValueError('A previous local account attempt requires review')
|
|
save_state(fd, {'status': 'reserved'})
|
|
return fd
|
|
except BaseException:
|
|
os.close(fd)
|
|
raise
|
|
|
|
|
|
def compile_fixture(folder, pe, wire):
|
|
from build_wine_wire import FLAGS, LIBS
|
|
slash = chr(92)
|
|
dos = 'Z:' + str(pe).replace('/', slash)
|
|
nt = slash + '??' + slash + 'Z:' + str(wire).replace('/', slash)
|
|
obj, exe = folder / 'fixture.obj', folder / 'fixture.exe'
|
|
subprocess.run(['clang', *FLAGS, '-DGW_WIRE_DLL=' + json.dumps(dos), '-DGW_WIRE_UNIX=L' + json.dumps(nt), '-c', str(ROOT / 'tests/source_local_account_fixture.c'), '-o', str(obj)], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
|
|
subprocess.run(['lld-link', '/entry:fixture_start', '/subsystem:console', '/nodefaultlib', '/timestamp:0', '/out:' + str(exe), str(obj), str(LIBS[2]), str(LIBS[3])], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
|
|
return exe
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('--pe', required=True, help='Owned profile-4 PE wire DLL')
|
|
parser.add_argument('--unix-wire', required=True, help='Owned Wine Unix wire shared library')
|
|
parser.add_argument('--work-dir', required=True, help='Dedicated fixture directory within runtime')
|
|
parser.add_argument('--real-once', action='store_true', help='Submit the owned local account once; never retry a failed or interrupted attempt')
|
|
parser.add_argument('--pin-receipt', help='Existing PE/Unix/core hash receipt; required for a real submission')
|
|
parser.add_argument('--realm-index', type=int, help='Explicit advertised local realm index for --real-once')
|
|
args = parser.parse_args()
|
|
pe, wire = project_file(args.pe), project_file(args.unix_wire)
|
|
core = project_file(wire.parent / 'libgateway_native.so')
|
|
work = Path(args.work_dir).resolve()
|
|
if not work.is_relative_to(RUNTIME.resolve()) or work == RUNTIME.resolve():
|
|
raise ValueError('Fixture work directory must be below runtime')
|
|
work.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
if args.real_once and args.realm_index is None:
|
|
raise ValueError('An explicit local realm index is required')
|
|
if args.realm_index is not None and not 0 <= args.realm_index < 64:
|
|
raise ValueError('Realm index is outside the bounded range')
|
|
if args.real_once:
|
|
if not args.pin_receipt:
|
|
raise ValueError('A matching PE/Unix/core receipt is required for a real submission')
|
|
pins = json.loads(project_file(args.pin_receipt).read_text())['files_sha256']
|
|
if any(pins.get(k) != digest(p) for k, p in (('pe_wire', pe), ('source59_unix_wire', wire), ('combined_native_core', core))):
|
|
raise ValueError('Fixture artifacts differ from their accepted receipt')
|
|
if not legacy_result_safe():
|
|
raise ValueError('A previous local account attempt requires review')
|
|
run = Path(tempfile.mkdtemp(prefix='source-profile-', dir=work))
|
|
sys.path.insert(0, str(ROOT / 'ops'))
|
|
exe = compile_fixture(run, pe, wire)
|
|
env = dict(os.environ, WINEPREFIX=str(work / 'disposable-prefix'), WINEDEBUG='-all', WINEDLLOVERRIDES='mscoree,mshtml=')
|
|
for key in ('LD_PRELOAD', 'LD_LIBRARY_PATH', 'GW_NATIVE_BOOTSTRAP', 'GW_NATIVE_EXPECTED_EXE', 'GW_NATIVE_REGISTER', 'GW_LOCAL_FIXTURE_MODE', 'GW_LOCAL_REALM_INDEX', 'GW_LOCAL_VERSION_PATH', 'GW_LOCAL_ADDON_PATH'):
|
|
env.pop(key, None)
|
|
state_fd = None
|
|
username, password, payload = bytearray(), bytearray(), bytearray()
|
|
try:
|
|
if args.real_once:
|
|
local_ready()
|
|
directory, username = account_inputs()
|
|
state_fd = claim_once_state(STATE)
|
|
fd, before = private_fd(directory / 'password.txt')
|
|
try:
|
|
password = bytearray(128)
|
|
n = os.readv(fd, [password])
|
|
after = os.fstat(fd)
|
|
if n != before.st_size or (before.st_ino, before.st_size, before.st_mtime_ns) != (after.st_ino, after.st_size, after.st_mtime_ns):
|
|
raise ValueError('Local fixture password file changed')
|
|
del password[n:]
|
|
finally:
|
|
os.close(fd)
|
|
while password and password[-1] in (10, 13):
|
|
password.pop()
|
|
if not 1 <= len(password) <= 64 or any(not 32 <= c <= 126 for c in password):
|
|
raise ValueError('Local fixture password format differs')
|
|
payload = bytearray((len(username), len(password)))
|
|
payload.extend(username)
|
|
payload.extend(password)
|
|
env.update(GW_LOCAL_FIXTURE_MODE='real-once', GW_LOCAL_REALM_INDEX=str(args.realm_index), GW_LOCAL_VERSION_PATH=str(directory / 'version-hash.bin'), GW_LOCAL_ADDON_PATH=str(directory / 'addon-tail.bin'))
|
|
with tempfile.TemporaryFile() as stdout, tempfile.TemporaryFile() as stderr:
|
|
proc = subprocess.Popen(['wine', str(exe)], stdin=subprocess.PIPE if args.real_once else subprocess.DEVNULL, stdout=stdout, stderr=stderr, env=env)
|
|
try:
|
|
if args.real_once:
|
|
proc.stdin.write(payload)
|
|
proc.stdin.close()
|
|
for buf in (payload, password):
|
|
for i in range(len(buf)):
|
|
buf[i] = 0
|
|
rc = proc.wait(timeout=75 if args.real_once else 30)
|
|
except subprocess.TimeoutExpired:
|
|
proc.kill()
|
|
proc.wait()
|
|
rc = 124
|
|
output = os.pread(stdout.fileno(), 8193, 0)
|
|
errors = os.pread(stderr.fileno(), 8193, 0)
|
|
if len(output) > 8192 or len(errors) > 8192:
|
|
raise RuntimeError('Fixture output exceeded its bound')
|
|
(run / 'stdout.private').write_bytes(output)
|
|
(run / 'stderr.private').write_bytes(errors)
|
|
offline = b'GW_LOCAL_PROFILE offline-preflight-pass\n' in output
|
|
real = b'GW_LOCAL_PROFILE submitted-once\n' in output and b'GW_LOCAL_PROFILE one-proposal-sent\n' in output and b'GW_LOCAL_PROFILE genuine-realm-prepared\n' in output
|
|
passed = rc == 0 and offline and (real if args.real_once else not real)
|
|
if state_fd is not None:
|
|
save_state(state_fd, {'status': 'success' if passed else 'failed', 'exit_code': rc})
|
|
(run / 'result.json').write_text(json.dumps({'mode': 'real-once' if args.real_once else 'offline', 'exit_code': rc, 'passed': passed, 'game_client_used': False, 'native_client_acceptance': False}) + '\n')
|
|
if not passed:
|
|
raise RuntimeError('Local Source fixture did not complete; no automatic retry')
|
|
print('Local Source fixture passed:', 'one local realm proposal' if args.real_once else 'offline preflight')
|
|
finally:
|
|
for buf in (username, password, payload):
|
|
for i in range(len(buf)):
|
|
buf[i] = 0
|
|
if state_fd is not None:
|
|
os.close(state_fd)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
os.umask(0o077)
|
|
try:
|
|
main()
|
|
except (OSError, ValueError, KeyError, UnicodeError, RuntimeError, subprocess.SubprocessError) as error:
|
|
print('Local Source fixture stopped:', type(error).__name__, file=sys.stderr)
|
|
sys.exit(1)
|