#!/usr/bin/env python3 """Local-only preparation of a new preserving passive Windows code-pair controller. No SSH, staging or target action is exposed here. The generated controller's enter phase remains closed until a separate reviewed source generation binds actual server source/broker/public-time-key/mTLS-route qualification. Original 14fb evidence and Main indices are read-only; no time pins or calibration exist in this package. Source review and native PS AST/C# compile remain separate. """ import argparse import base64 import hashlib import json import os from pathlib import Path import uuid import system_pipe_upgrade as prior ROOT = Path(__file__).resolve().parents[2] MAIN = ROOT.parent / 'rust-discovery' STATE = ROOT / 'devstate/windows-signed-clock/passive-pair-upgrade' PRIOR_SOURCE = 'e466576673a0e5c332cfc1613ae88a62f5b526015ced76b1d22473e292a995e0' OLD_CASE = '14fb176a-f653-4573-a8d7-6f9fe47a3020' OLD_AGENT = 'f10c78dd738e7fb277e0c4d24fadf0f61ae3269458399b9224570ba5e66abc2c' OLD_HELPER = '5f8c62fab6bc8ea1bbb009166b3d0e741c034c36690a4e32ea4e3cb2d7729a79' OLD_POLICY = 'a3024467c460e80d9151a47d49729f444d98eefa8cfb7ee98c624f873e2c7b2b' OLD_PIN = 'af518db88a6d4a856c32ca9d89d88405689aa2d89163ab0cb638c1abdd8fa118' RUNTIME_INDEX = 'e49231e72aff7b001189b8507200c6c701f73e47f77c29194116cf1da41ca0c2' COMPONENT_INDEX = '005317e652f50de3e1277be3bc42717318226208015e7c8011e1b73469cc7562' ORIGINAL_RESULT = 'd5c4996821911a5bdac5014e9f985c56bbb592b803f2e33411dd28bb986b8eed' ORIGINAL_INTENT = '374adc97bec41bd798409f7c4f8c7716b085e20d2b6fb64b33f7ab675e6483e2' CANDIDATE = ROOT / 'devstate/windows-signed-clock/trusted-os-candidate-link-542cbf43-afb2-4994-b141-06e003e5e2e8' CANDIDATE_RECEIPT = '04ed34e6e850aca77c1fd4677ddb271f7ccd9492a97f5d4e00ead4c1f032f29d' QUALIFICATION = '96b05fe13f4d459b4b3ef78292beea33827b1ea47293ffb5921c685940e82a4d' NEW_AGENT = '26dc9d2f6928c5a41050ac9324e041c065e7a9ae52324416f3bb6222c002ae6b' NEW_HELPER = '59675a3cbb3a5d213fc764f38379d6b81baaf9d47a7124470cc2767d4985763e' PROBE = '727732fb4b38ac5431a330527bd52a3ab80af8f189ae75a7b48eceb1d4b69cac' SYSTEM_PROBE = '77a344912c61b7ac4a92152ae1b534ca7c36fe6f7dc4675783f20558c3a7f434' require = prior.require sha, raw_sha, canonical = prior.sha, prior.raw_sha, prior.canonical def replace_once(text, old, new): require(text.count(old) == 1, 'exact reviewed controller delta') return text.replace(old, new, 1) def controller(): require(sha(prior.__file__) == PRIOR_SOURCE, 'immutable original controller source') prior.guards() prefix = prior.PREFIX for old, new in ((prior.OLD_AGENT, OLD_AGENT), (prior.OLD_HELPER, OLD_HELPER), (prior.OLD_POLICY, OLD_POLICY), (prior.OLD_PIN, OLD_PIN)): prefix = replace_once(prefix, old, new) prefix = replace_once(prefix, "$p.action-notin@('baseline','enter','finish','readback')", "$p.action-isnot[string]-or$p.action-cnotin@('baseline','enter','finish','readback')") prefix = replace_once(prefix, 'RmmPipeUpgradePayload', 'RmmSignedClockPairPayload') prefix = replace_once(prefix, "('system-pipe-'+$p.id)", "('signed-clock-pair-'+$p.id)") prefix = replace_once(prefix, "'system-pipe-active-intent.json'", "'signed-clock-pair-active-intent.json'") marker = "foreach($field in @('old_agent'" index = prefix.index(marker) prefix = prefix[:index] + ("# No caller flag or staged file can replace missing server qualification.\n" "if($p.action-ceq'enter'){throw 'SERVER_TIME_QUALIFICATION_NOT_BOUND'}\n" "if($p.new_agent-cne'"+NEW_AGENT+"'-or$p.new_helper-cne'"+NEW_HELPER+ "'){throw 'Fixed signed-clock freshness candidate pair'}\n") + prefix[index:] # Require explicit absence; this bootstrap never creates or adopts a # calibration/public-time-pin file or changes the six-field passive config. marker = 'function State([bool]$new){\n' prefix = replace_once(prefix, marker, marker + " if(Test-Path -LiteralPath (Join-Path $helperRoot 'time-attestation.json')){throw 'Separate time-pin provisioning required; passive bootstrap does not adopt it'}\n") native = prior.NATIVE.replace('RmmPipeNative', 'RmmSignedClockPairNative') phases = prior.PHASES.replace('SystemPipeUpgrade.ps1', 'SignedClockPairUpgrade.ps1').replace('RmmPipeNative', 'RmmSignedClockPairNative') # No implicit fallthrough may become an effect, even if a future caller # bypasses an earlier read branch or the outer whitelist is changed. boundary = "if((Test-Path -LiteralPath $folder)-or(Test-Path -LiteralPath $active)){throw 'Existing pipe intent: readback only'}" phases = replace_once(phases, boundary, "if($p.action-cne'enter'){throw 'EXACT_ENTER_ACTION_REQUIRED'}\n" "throw 'SERVER_TIME_QUALIFICATION_NOT_BOUND'\n" + boundary) # Only the existing fixed passive journal witnesses and authenticated Probe # are used. No helper Snapshot/Apply/Execute or time control operation. return prefix+'\n'+native+prior.READBACK_SERVICE+'\n'+phases def source_guards(script): require("if($p.action-ceq'enter'){throw 'SERVER_TIME_QUALIFICATION_NOT_BOUND'}" in script, 'target effects closed pending actual independently reviewed server evidence') require("$p.action-isnot[string]-or$p.action-cnotin@('baseline','enter','finish','readback')" in script and "$p.action-notin@" not in script, 'strict string and case-sensitive action whitelist') boundary = ("if($p.action-cne'enter'){throw 'EXACT_ENTER_ACTION_REQUIRED'}\n" "throw 'SERVER_TIME_QUALIFICATION_NOT_BOUND'\n" "if((Test-Path -LiteralPath $folder)-or(Test-Path -LiteralPath $active))") require(script.count(boundary) == 1 and script.index(boundary) < script.index(" StopHeld 'agent'"), 'explicit exact enter and unconditional qualification gate before all effect flow') require('RmmPipeNative' not in script and 'RmmPipeUpgradePayload' not in script, 'only the new controller class and payload identifiers') require(script.count('Start-Service -Name $name') == script.count('Stop-Service -Name $name') == 1, 'one fixed-role service-control primitive only') positions = [script.index(x) for x in (" StopHeld 'agent'", " Backup 'agent'", "Backup 'pin'", " Swap 'agent'", "Swap 'pin'", '$swapped=ActualState $true', " StartOnce 'helper'", "StartOnce 'agent'")] require(positions == sorted(positions), 'backups then all four CAS replacements then helper/agent starts') require('[IO.File]::Replace($candidate,$destination,$nativeBackup)' in script, 'explicit native original backup, no null backup') require(all(x not in script for x in ('Restart-Service', 'Restart-Computer', 'Stop-Computer', 'Set-Service', 'New-Service', 'Remove-Item', 'Invoke-Expression', 'Bypass', 'TimeBegin', 'TimeComplete', 'TimeClose', 'ExecutionPolicy Bypass')), 'no extra effect or time-control scope') require('function Snapshot' not in script and 'function Apply' not in script, 'no clock-dependent helper synchronization in passive witness') def protected(path, expected): prior.cb.contract.protected_json(path) require(sha(path) == expected, 'exact protected original public evidence') return prior.cb.contract.protected_json(path) def original(): evidence = MAIN/'devstate/windows-client' runtime = protected(evidence/'current-runtime.json', RUNTIME_INDEX) components = protected(evidence/'current-components.json', COMPONENT_INDEX) folder = evidence/'system-pipe-upgrade'/OLD_CASE result = protected(folder/'result.json', ORIGINAL_RESULT) intent = protected(folder/'intent.json', ORIGINAL_INTENT) require(result['verified'] is True and result['completed'] is True and result['no_jobs'] is True and result['windows_jobs_enabled'] is False and result['helper_effects_enabled'] is False and result['clock_adapter_qualified'] is False, 'accepted original closed passive pair') require(runtime['case_id'] == components['case_id'] == OLD_CASE and runtime['binary_sha256'] == components['agent_sha256'] == OLD_AGENT and components['helper_sha256'] == OLD_HELPER and components['policy_sha256'] == OLD_POLICY and components['pin_sha256'] == OLD_PIN and runtime['windows_jobs_enabled'] is False and components['helper_effects_enabled'] is False, 'same original Main indices') old = base64.b64decode(intent['payload']['settings_base64'], validate=True) require(raw_sha(old) == OLD_POLICY and raw_sha(base64.b64decode(intent['payload']['pin_base64'], validate=True)) == OLD_PIN, 'original public reciprocal settings, never key material') value = json.loads(old, object_pairs_hook=prior.cb.contract.strict_object) require(set(value) == {'schema_version','binding','agent','helper','allowed_services', 'max_runtime_seconds','enable_effects','allow_reboot'} and value['schema_version'] == 1 and value['agent']['binary_sha256'] == OLD_AGENT and value['helper']['binary_sha256'] == OLD_HELPER and value['allowed_services'] == [] and value['max_runtime_seconds'] == 30 and value['enable_effects'] is False and value['allow_reboot'] is False, 'exact original closed public profile') value['agent']['binary_sha256'] = NEW_AGENT; value['helper']['binary_sha256'] = NEW_HELPER settings = canonical(value); policy = raw_sha(settings) pin = canonical(dict(schema_version=1,binding=value['binding'],policy_sha256=policy, agent=value['agent'],helper=value['helper'])) require(intent['payload']['probe_sha256'] == PROBE and intent['payload']['system_probe_sha256'] == SYSTEM_PROBE, 'same previously qualified fixed read-only journal witnesses') return result, intent, settings, pin, policy def write(path, raw): fd = os.open(path,os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,0o600) with os.fdopen(fd,'wb') as stream: stream.write(raw);stream.flush();os.fsync(stream.fileno()) def prepare(script): result, old_intent, settings, pin, policy = original() receipt = protected(CANDIDATE/'receipt.json', CANDIDATE_RECEIPT) require(receipt['source_receipt_sha256'] == QUALIFICATION and receipt['input_count'] == 202 and receipt['link_exit'] == 0 and receipt['target_called'] is False and receipt['artifacts']['rmm-agent-windows.exe']['sha256'] == NEW_AGENT and receipt['artifacts']['rmm-helper-windows.exe']['sha256'] == NEW_HELPER, 'actual new offline-linked freshness pair, no native qualification inferred') ident = str(uuid.uuid4()); folder = STATE/ident; folder.mkdir(mode=0o700,parents=True) script_sha = raw_sha(script.encode()) draft = dict(id=ident,old_agent=OLD_AGENT,old_helper=OLD_HELPER,old_policy=OLD_POLICY,old_pin=OLD_PIN, new_agent=NEW_AGENT,new_helper=NEW_HELPER,new_policy=policy,new_pin=raw_sha(pin), config_sha256=result['native']['config_sha256'],probe_sha256=PROBE,system_probe_sha256=SYSTEM_PROBE, manifest_sha256=CANDIDATE_RECEIPT,qualification_sha256=QUALIFICATION,script_sha256=script_sha, settings_base64=base64.b64encode(settings).decode(),pin_base64=base64.b64encode(pin).decode(), intent_leaves=old_intent['payload']['intent_leaves']) items = {'SignedClockPairUpgrade.ps1':script.encode(),'new-helper.json':settings,'new-agent-pin.json':pin, 'draft-payload.json':canonical(draft)} files = {} for name,raw in items.items(): write(folder/name,raw);files[name]=dict(bytes=len(raw),sha256=raw_sha(raw)) for name,expected in [('rmm-agent-windows.exe',NEW_AGENT),('rmm-helper-windows.exe',NEW_HELPER)]: source=CANDIDATE/name;metadata=source.lstat() require(metadata.st_nlink == 1 and metadata.st_mode&0o777 == 0o500 and sha(source) == expected, 'exact private linked candidate artifact') dependencies=prior.dependencies();dependencies[str(Path(prior.__file__).relative_to(ROOT))]=PRIOR_SOURCE manifest=dict(profile='rmm.windows.signed-clock.passive-pair-controller.preparation.v1',id=ident, generator_sha256=sha(__file__),controller_sha256=script_sha,files=files,dependencies=dependencies, original_case=OLD_CASE,original_result_sha256=ORIGINAL_RESULT,original_intent_sha256=ORIGINAL_INTENT, original_runtime_index_sha256=RUNTIME_INDEX,original_component_index_sha256=COMPONENT_INDEX, candidate_receipt_sha256=CANDIDATE_RECEIPT,qualification_sha256=QUALIFICATION, artifacts={name:receipt['artifacts'][name] for name in ('rmm-agent-windows.exe','rmm-helper-windows.exe')}, server_qualification_bound=False,enter_enabled=False,time_configuration_created=False, calibration_created=False,target_called=False,main_indices_modified=False, remaining=['independent source review','native PS AST/C# compile-only', 'actual server quality/broker/public-time-key/mTLS-route gate binding in separately reviewed source', 'fresh native baseline and closed server witnesses','new once-only stage/enter/read operator']) write(folder/'manifest.json',canonical(manifest));print(json.dumps(dict(id=ident,prepared_locally=True, controller_sha256=script_sha,enter_enabled=False,target_called=False))) def main(): parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('action',choices=('guards','prepare')) args=parser.parse_args();os.umask(0o077);script=controller();source_guards(script) if args.action=='guards':print('PASS: source guards only; no target actions');return prepare(script) if __name__=='__main__': main()