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

235 lines
14 KiB
Python

"""Owned data-only retirement requests, after a fresh observe-only Login intent.
Only expected-generation/state/frame-command inputs are published. Native
main-thread code owns cleanup and acknowledgment; no auth/outcome flag writes.
"""
import json,os,struct,time
from pathlib import Path
import native_runtime_paths
import engine_poll_host as host
import engine_wire_host as wire
import engine_channel_policy_host as policy
from launcher_account_generation import require_retirement_ack
ROOT=Path(__file__).resolve().parents[1]
FORMAT='<IIiIIIiiiiiiQ';SIZE=56
FIELDS=('abi','size','state','expected_credentials_generation','completed_credentials_generation',
'next_credentials_generation','previous_account_error','previous_pipe_error',
'previous_world_error','previous_policy_error','result','previous_frame_error','owner')
EXPORT='gw_wire_session_retirement_data'
def decode(raw):
if len(raw)!=SIZE:raise ValueError('Retirement metadata size differs')
result=dict(zip(FIELDS,struct.unpack(FORMAT,raw)))
if result['abi']!=1 or result['size']!=SIZE or result['state']not in (0,1,2,3):
raise ValueError('Retirement metadata ABI/state differs')
if any(result[k]>64 for k in ('expected_credentials_generation','completed_credentials_generation','next_credentials_generation')):
raise ValueError('Retirement generation exceeds immutable callback capacity')
return result
def account_snapshot(access,base,exports):
values=struct.unpack('<II13iII',access.read(base+exports['gw_wire_auth_data'],68))
if values[:2]!=(1,1732)or not 0<=values[3]<=5:raise ValueError('Owned account header ABI differs')
header=struct.unpack('<IIi5I',access.read(base+exports['gw_wire_auth_credentials_data'],32))
if header[:2]!=(1,132)or not -1<=header[2]<=3 or header[7]:raise ValueError('Owned mailbox header ABI differs')
return dict(state=values[3],error=values[4],auth_result=values[6],discovery_result=values[7],
transport_result=values[10],server_proof_verified=values[13],transport_prepared=values[14],
memory_credentials=dict(zip(('state','generation','username_bytes','password_bytes','consumed_generation'),header[2:7])))
def pipe_snapshot(access,base,exports):
raw=access.read(base+exports['gw_wire_pipe_data'],176)
abi,size,stage,error=struct.unpack_from('<4I',raw)
if(abi,size)!=(1,640):raise ValueError('Owned pipe header ABI differs')
counters=struct.unpack_from('<24I',raw,80)
world=struct.unpack('<12I',access.read(base+exports['gw_wire_world_data'],48))
if world[:2]!=(1,432):raise ValueError('Owned world header ABI differs')
return dict(stage=stage,error=error,closed=counters[21],world_auth=counters[6],
world=dict(login_sent=world[2],self_create=world[5]))
def inspect(pid):
identity=policy._request_process(pid);access=host.Access(pid)
try:
base,info,meta=wire.module(access)
row=decode(access.read(base+info['exports'][EXPORT],SIZE))
if policy._request_process(pid)!=identity:raise ValueError('Owned child identity changed')
return dict(row,pid=pid)
finally:access.close()
def observe_intent(pid,registers):
"""Fixed original code only: never inspect input descriptors or payloads."""
from engine_login_input_observation import ENTRY,PREFIX
identity=policy._request_process(pid)
if registers.rip!=ENTRY or registers.rsp%16:raise ValueError('Original Login entry/stack differs')
access=host.Access(pid)
try:
base,info,meta=wire.module(access);policy._request_libraries(access,meta)
if not access.allowed(ENTRY,len(PREFIX),'x')or access.read(ENTRY,len(PREFIX))!=PREFIX:
raise ValueError('Original Login instruction differs')
binding=json.loads((native_runtime_paths.state_file(ROOT,'engine-poll-binding.json')).read_text())
owner=access.u64(0x145e7a098)
if binding.get('pid')!=pid or binding.get('restored')or binding.get('owner')!=owner:
raise ValueError('Original Login owned generation differs')
account=account_snapshot(access,base,info['exports'])
pipe=pipe_snapshot(access,base,info['exports'])
generation=account.get('memory_credentials',{}).get('generation')
if (account.get('state')not in (3,4)or pipe.get('closed')!=1 or
type(generation)is not int or not 1<=generation<=63):
raise ValueError('Previous owned generation is not terminal')
if policy._request_process(pid)!=identity:raise ValueError('Owned child identity changed')
return dict(kind='fresh-observed-original-login-intent',pid=pid,
observed_entry=hex(ENTRY),observed_ns=time.monotonic_ns(),
process_start=identity,owner=owner,expected_credentials_generation=generation,
credential_bytes_read=False,credential_descriptors_read=False,
authentication_attempted=False,native_state_written=False)
finally:access.close()
def valid_intent(intent,pid,identity,*,now_ns=None):
from engine_login_input_observation import ENTRY
now_ns=time.monotonic_ns()if now_ns is None else now_ns
if (not isinstance(intent,dict)or intent.get('kind')!='fresh-observed-original-login-intent'or
intent.get('pid')!=pid or intent.get('process_start')!=identity or
intent.get('observed_entry')!=hex(ENTRY)or type(intent.get('observed_ns'))is not int or
not 0<=now_ns-intent['observed_ns']<=30_000_000_000 or
type(intent.get('expected_credentials_generation'))is not int or
not 1<=intent['expected_credentials_generation']<=63 or
type(intent.get('owner'))is not int or not intent['owner'] or
any(intent.get(k)is not False for k in ('credential_bytes_read','credential_descriptors_read','authentication_attempted','native_state_written'))):
raise ValueError('Fresh credential-free original Login intent required')
return intent['expected_credentials_generation']
def frame(access,pid,base,exports,owner):
binding=json.loads((native_runtime_paths.state_file(ROOT,'engine-poll-binding.json')).read_text())
address=base+exports['gw_wire_frame_data'];callback=base+exports['gw_wire_frame_callback']
values=struct.unpack('<9IiIIQ',access.read(address,56))
if (binding.get('pid')!=pid or binding.get('restored')or binding.get('wire_ping_only')or
binding.get('owner')!=owner or binding.get('wire_frame_data')!=address or
binding.get('wire_frame_callback')!=callback or access.u64(owner)!=binding.get('bound_vtable')or
access.u64(binding['bound_vtable']+40)!=callback or not access.allowed(callback,1,'x')or
values[:2]!=(1,wire.SIZE)or values[2]!=8 or values[3]!=1 or not values[4]or not values[5]or
any(values[6:10])or values[12]!=binding.get('data')):
raise ValueError('Owned completed old-generation frame differs')
return address,binding,values
def request(pid,intent):
identity=policy._request_process(pid);expected=valid_intent(intent,pid,identity)
access=host.Access(pid)
try:
base,info,meta=wire.module(access);policy._request_libraries(access,meta)
owner=access.u64(0x145e7a098)
if owner!=intent['owner']:raise ValueError('Original Login owner changed')
address,binding,first=frame(access,pid,base,info['exports'],owner)
data=base+info['exports'][EXPORT];row=decode(access.read(data,SIZE))
if row['state']not in (0,2):raise ValueError('Retirement request pending/refused; preserved')
account=account_snapshot(access,base,info['exports'])
pipe=pipe_snapshot(access,base,info['exports'])
if(account.get('state')not in (3,4)or pipe.get('closed')!=1 or
account.get('memory_credentials',{}).get('generation')!=expected):
raise ValueError('Previous generation changed before retirement')
deadline=time.monotonic()+1
while True:
_,_,fresh=frame(access,pid,base,info['exports'],owner)
if fresh[5]!=first[5]or fresh[4]<first[4]:raise ValueError('Owned frame identity changed')
if fresh[4]>first[4]:break
if time.monotonic()>=deadline:raise ValueError('Owned frame did not advance')
time.sleep(.02)
if policy._request_process(pid)!=identity:raise ValueError('Owned child identity changed')
valid_intent(intent,pid,identity)
# Native request inputs only; frame publication is last.
access.write(data+12,struct.pack('<I',expected))
access.write(data+8,struct.pack('<i',1))
access.write(address+8,struct.pack('<i',9))
return dict(pid=pid,owner=owner,expected_credentials_generation=expected,
frame_calls_before=first[4],frame_calls_after=fresh[4],requested=True,
native_outcome_written=False,authentication_attempted=False)
finally:access.close()
def finalize(pid,request_record):
"""Metadata rebind only after independently reading genuine native cleanup."""
identity=policy._request_process(pid);ack=inspect(pid)
generation=require_retirement_ack(request_record,ack)
access=host.Access(pid)
try:
base,info,meta=wire.module(access);policy._request_libraries(access,meta)
binding=json.loads((native_runtime_paths.state_file(ROOT,'engine-poll-binding.json')).read_text())
values=struct.unpack('<9IiIIQ',access.read(base+info['exports']['gw_wire_frame_data'],56))
account=account_snapshot(access,base,info['exports']);memory=account.get('memory_credentials',{})
if (binding.get('pid')!=pid or binding.get('restored')or binding.get('owner')!=ack['owner']or
access.u64(0x145e7a098)!=ack['owner']or access.u64(ack['owner'])!=binding.get('bound_vtable')or
values[:2]!=(1,wire.SIZE)or values[2]!=10 or values[3]!=1 or any(values[6:10])or
account.get('state')!=0 or account.get('server_proof_verified')!=0 or account.get('transport_prepared')!=0 or
any(memory.get(k)!=0 for k in ('state','generation','consumed_generation','username_bytes','password_bytes'))):
raise ValueError('Native cleanup is not pristine')
if policy._request_process(pid)!=identity:raise ValueError('Owned child identity changed')
binding.update(wire_ping_only=True,credentials_generation=generation,
retired_credentials_generation=request_record['expected_credentials_generation'])
path=native_runtime_paths.state_file(ROOT,'engine-poll-binding.json')
temporary=path.with_name('.engine-poll-binding-retirement-'+str(os.getpid()))
fd=os.open(temporary,os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW|os.O_WRONLY,0o600)
try:
with os.fdopen(fd,'w')as out:json.dump(binding,out,indent=2);out.write('\n');out.flush();os.fsync(out.fileno())
os.replace(temporary,path)
finally:
if temporary.exists():temporary.unlink()
return dict(ack,pid=pid,ready_for_fresh_original_login=True,native_readiness_claimed=False)
finally:access.close()
def capture_generation(access,pid,base,exports,binding):
"""Choose only a native-acknowledged fresh generation, before input reads."""
generation=binding.get('credentials_generation',1)
if type(generation)is not int or not 1<=generation<=64:raise ValueError('Fresh Login generation malformed')
if generation==1:
if 'credentials_generation'in binding:raise ValueError('First Login cannot impersonate retirement')
return 1
ack=decode(access.read(base+exports[EXPORT],SIZE))
previous=binding.get('retired_credentials_generation')
request_record=dict(expected_credentials_generation=previous,owner=binding.get('owner'))
if require_retirement_ack(request_record,ack)!=generation or binding.get('pid')!=pid:
raise ValueError('Fresh Login generation does not match native retirement')
return generation
def pipe_binding(access,pid,base,exports,binding):
"""Select fixed native callbacks and a virgin immutable vtable epoch row."""
names=(EXPORT,'gw_wire_session_pipe_callbacks','gw_wire_session_pipe_tables')
present=[name in exports for name in names]
if not any(present):
return [base+exports[k]for k in ('gw_wire_pipe_write','gw_wire_pipe_read')],None,1
if not all(present):raise ValueError('Incomplete native session generation ABI')
generation=capture_generation(access,pid,base,exports,binding)
table=base+exports[names[1]];tables=base+exports[names[2]]
if(struct.unpack('<4I',access.read(table,16))!=(1,1040,64,0)or
struct.unpack('<4I',access.read(tables,16))!=(1,5136,64,0)):
raise ValueError('Immutable callback/vtable table ABI differs')
row=16+(generation-1)*16
pointers=struct.unpack('<2Q',access.read(table+row,16))
# Validate only this already hash-pinned PE row against its relocation;
# do not scan the image or accept an unrelated executable function.
import pefile
path=wire.module_path()
image=pefile.PE(str(path),fast_load=True)
try:
original=struct.unpack('<2Q',image.get_data(exports[names[1]]+row,16))
expected=tuple(base+p-image.OPTIONAL_HEADER.ImageBase for p in original)
if pointers!=expected or any(not 0<p-image.OPTIONAL_HEADER.ImageBase<image.OPTIONAL_HEADER.SizeOfImage for p in original):
raise ValueError('Native callback relocation differs')
finally:image.close()
if not all(access.allowed(p,1,'x')for p in pointers):raise ValueError('Native epoch callback unavailable')
row_address=tables+16+(generation-1)*80
if any(access.read(row_address,80)):raise ValueError('Native pipe epoch vtable already consumed')
return list(pointers),row_address,generation
def require_fresh_receiver(access,base,exports,receiver,generation):
"""A recycled native receiver can alias late virtual calls; never rebind it."""
if EXPORT not in exports:return # Released legacy module: no generation API.
name='gw_wire_session_pipe_receivers'
if name not in exports:raise ValueError('Native receiver history ABI missing')
if(type(receiver)is not int or not 0<receiver<2**64 or receiver%8 or
type(generation)is not int or not 1<=generation<=64):
raise ValueError('Native receiver identity/generation malformed')
raw=access.read(base+exports[name],528)
abi,size,count,reserved,*retired=struct.unpack('<4I64Q',raw)
if(abi,size,count,reserved)!=(1,528,64,0):raise ValueError('Native receiver history ABI differs')
if retired[generation-1]:raise ValueError('Native receiver epoch already retired; restart required')
if receiver in retired:raise ValueError('Native receiver address reused; restart required')