227 lines
17 KiB
Python
227 lines
17 KiB
Python
#!/usr/bin/env python3
|
|
"""Prepare the preserving passive Windows pair with fixed actual route evidence.
|
|
|
|
Preparation reads only the public expires_at from the current protected access
|
|
configuration. Before effects the guest must match that same expiration in its
|
|
existing account and bootstrap-public configuration, with a full first-stop
|
|
budget and a smaller remaining budget at the second stop. No account/tunnel
|
|
change, RMM job, reboot or clock configuration is performed by this generator.
|
|
"""
|
|
import argparse
|
|
import base64
|
|
import datetime as dt
|
|
import re
|
|
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"
|
|
"# Enter effects require the fixed actual protocol/exit proof below.\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")
|
|
# Compare JSON objects by their contents; serialized member order is not
|
|
# identity. Arrays retain exact order and empty/null values stay distinct.
|
|
prefix = replace_once(prefix,
|
|
"function JsonEqual($a,$b){return(($a|ConvertTo-Json -Depth 40 -Compress)-ceq($b|ConvertTo-Json -Depth 40 -Compress))}",
|
|
r'''function CanonicalStateValue($value,[int]$depth=0){
|
|
if($depth-gt40){throw 'Bounded state comparison depth'}
|
|
if($null-eq$value){return $null}
|
|
if($value-is[Collections.IDictionary]){$result=[ordered]@{};foreach($key in @($value.Keys|Sort-Object -CaseSensitive)){if($key-isnot[string]-or$result.Contains($key)){throw 'Nonunique state object key'};$result[$key]=CanonicalStateValue $value[$key] ($depth+1)};return $result}
|
|
if($value-is[pscustomobject]){$result=[ordered]@{};foreach($property in @($value.PSObject.Properties|Sort-Object -Property Name -CaseSensitive)){if($property.Name-isnot[string]-or$result.Contains($property.Name)){throw 'Nonunique state object key'};$result[$property.Name]=CanonicalStateValue $property.Value ($depth+1)};return $result}
|
|
if($value-is[Collections.IEnumerable]-and$value-isnot[string]){$result=New-Object 'Collections.Generic.List[object]';foreach($item in $value){$result.Add((CanonicalStateValue $item ($depth+1)))};return ,$result.ToArray()}
|
|
return $value
|
|
}
|
|
function JsonEqual($a,$b){return((ConvertTo-Json -InputObject (CanonicalStateValue $a) -Depth 40 -Compress)-ceq(ConvertTo-Json -InputObject (CanonicalStateValue $b) -Depth 40 -Compress))}''')
|
|
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"
|
|
"RequireQualifiedTimeRoute\nRequireAccessBudget 420\n" + boundary)
|
|
phases = phases.replace(" $live=Service $role;", " if($role-ceq'agent'){RequireAccessBudget 420}else{RequireAccessBudget 300}\n $live=Service $role;", 1)
|
|
route_gate = r'''function RequireAccessBudget([int]$minimumSeconds=420){
|
|
if($p.access_expiry_utc-isnot[string]-or$p.access_expiry_utc-cnotmatch'^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,7})?Z$'){throw 'Exact protected access expiry'}
|
|
$limit=[DateTimeOffset]::Parse($p.access_expiry_utc,[Globalization.CultureInfo]::InvariantCulture).UtcDateTime;$actual=(Get-LocalUser -Name 'rmm-dev').AccountExpires.ToUniversalTime()
|
|
$configPath='C:\ProgramData\RmmDevAccess\bootstrap-public.json';CheckControl $configPath $false;if((Get-Item -LiteralPath $configPath).Length-gt32768){throw 'Bounded public access config'}
|
|
$public=Get-Content -LiteralPath $configPath -Raw|ConvertFrom-Json;$configured=[DateTimeOffset]::Parse($public.expires_at,[Globalization.CultureInfo]::InvariantCulture).UtcDateTime
|
|
if($actual-ne$limit-or$configured-ne$limit-or($limit-[DateTime]::UtcNow).TotalSeconds-lt$minimumSeconds){throw 'Insufficient or mismatched actual SSH access budget before service stop'}
|
|
}
|
|
function RequireQualifiedTimeRoute{
|
|
$route='C:\ProgramData\RustDiscoveryBootstrap\time-route\68b841a5-784f-4a34-a8a4-060b267713f0';$control='C:\ProgramData\RustDiscoveryBootstrap\time-route-control\68b841a5-784f-4a34-a8a4-060b267713f0'
|
|
CheckControl $route $true;CheckControl $control $true
|
|
foreach($entry in @(@((Join-Path $route 'TimeRouteProbe.exe'),'4ef3fc85f5d140f2ad0ff14745dc5d5453a058203d785235d7dabafdf522b088'),@((Join-Path $route 'report.json'),'9f1635c19c801f95c9828e9e31071a487b430f105a61977ee2d60f076f3d3623'),@((Join-Path $control 'exit.json'),'6d131d2796936913f53286573e56f7fb3e515d04ebbd55ae9d6794440e6053b5'),@((Join-Path $route 'context.json'),'3c0e4ff3b16b86fb4e98d2ff163686305ea533570c40ae3bef1270ab89648ed3'),@((Join-Path $route 'time-public-key.json'),'c31d31d2d61f881d04f55f704abbbf98f4822650c016f39e39d4d2318bc3f6e2'))){CheckControl $entry[0] $false;if((Hash $entry[0])-cne$entry[1]){throw 'Actual passive route and kernel-exit proof changed'}}
|
|
$report=Get-Content -LiteralPath (Join-Path $route 'report.json') -Raw|ConvertFrom-Json;$exit=Get-Content -LiteralPath (Join-Path $control 'exit.json') -Raw|ConvertFrom-Json
|
|
if($report.case_id-cne'68b841a5-784f-4a34-a8a4-060b267713f0'-or$report.verified-ne$true-or$report.service_role_proven-ne$false-or$report.trusted_clock_proven-ne$false-or($report.reports.http_status-join',')-cne'200,403,409'-or$report.reports[0].signature_verified-ne$true-or$report.reports[0].whole_request_context_bound-ne$true-or$exit.kernel_process_exited-ne$true-or$exit.exit_code-ne0-or$exit.timed_out-ne$false){throw 'Fixed actual passive protocol proof only'}
|
|
}
|
|
'''
|
|
phases = route_gate+phases
|
|
# 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("$p.action-isnot[string]-or$p.action-cnotin@('baseline','enter','finish','readback')" in script and "$p.action-notin@" not in script,'exact case sensitive actions')
|
|
require("if($p.action-cne'enter'){throw 'EXACT_ENTER_ACTION_REQUIRED'}\nRequireQualifiedTimeRoute\nRequireAccessBudget 420\n" in script,'actual route and access bound before effects')
|
|
require(" if($role-ceq'agent'){RequireAccessBudget 420}else{RequireAccessBudget 300}\n $live=Service $role;" in script,'access budget before each actual stop')
|
|
require('9f1635c19c801f95c9828e9e31071a487b430f105a61977ee2d60f076f3d3623' in script and '6d131d2796936913f53286573e56f7fb3e515d04ebbd55ae9d6794440e6053b5' in script,'actual route report and exit binding')
|
|
require('TimeBegin' not in script and 'TimeComplete' not in script and 'Restart-Computer' not in script,'no clock/job/reboot scope')
|
|
|
|
|
|
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()
|
|
grant = prior.cb.contract.protected_json(MAIN/'credentials/windows-dev-access.json')
|
|
expiry = grant.get('expires_at')
|
|
require(type(expiry) is str and re.fullmatch(r'\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,7})?(?:Z|\+00:00)',expiry) is not None,'protected current access expiry')
|
|
expiry = expiry.removesuffix('+00:00')+'Z' if expiry.endswith('+00:00') else expiry
|
|
deadline = dt.datetime.fromisoformat(expiry.replace('Z','+00:00'))
|
|
require((deadline-dt.datetime.now(dt.timezone.utc)).total_seconds() >= 420,'current authorization window has insufficient total maintenance/readback budget')
|
|
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,access_expiry_utc=expiry,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')},
|
|
access_expiry_utc=expiry,access_expiry_source='protected current windows-dev-access.json public expires_at; exact VM account/bootstrap-public match before effects',
|
|
server_qualification_bound=True,enter_enabled=True,time_configuration_created=False,
|
|
calibration_created=False,target_called=False,main_indices_modified=False,
|
|
remaining=['fresh current authorized SSH window and exact VM account/public expiry match',
|
|
'fresh native baseline and closed server witnesses','once-only preserving maintenance and independent readback'])
|
|
write(folder/'manifest.json',canonical(manifest));print(json.dumps(dict(id=ident,prepared_locally=True,
|
|
controller_sha256=script_sha,enter_enabled=True,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()
|