190 lines
19 KiB
Python
190 lines
19 KiB
Python
#!/usr/bin/env python3
|
|
"""Fixed once-only passive route fixture operator. All target phases initially closed."""
|
|
import argparse
|
|
import base64
|
|
import hashlib
|
|
import json
|
|
from pathlib import Path
|
|
import subprocess
|
|
import uuid
|
|
import signed_clock_capture_acceptance as original
|
|
import time_route_context as collector
|
|
|
|
ROOT=original.ROOT
|
|
STATE=ROOT/'devstate/windows-time-route-native'
|
|
QUAL=ROOT/'devstate/windows-signed-clock/time-route-fixture-qualification-3fdf513e-197b-41ab-b161-9dfc2adc94da'
|
|
RECEIPT_SHA='fce8c42cce33a35be1ee0468c97010ac3797a713668503783e449d30ea538678'
|
|
EXE_SHA='4ef3fc85f5d140f2ad0ff14745dc5d5453a058203d785235d7dabafdf522b088'
|
|
EXE_BYTES=19172660
|
|
PIN=ROOT/'devstate/server-time-source-bootstrap/qualified-time-public-key.json'
|
|
PIN_SHA='c31d31d2d61f881d04f55f704abbbf98f4822650c016f39e39d4d2318bc3f6e2'
|
|
# Root pins {id, receipt_sha256} only after the actual post-deploy collector read.
|
|
CONTEXT_GATE=None
|
|
require,save,load,sha=original.require,original.save,original.load,original.sha
|
|
|
|
SCRIPT=r'''$ErrorActionPreference='Stop';$p=([Console]::In.ReadLine()|ConvertFrom-Json)
|
|
if(!$p-or$p.action-isnot[string]-or$p.action-cnotin@('stage','run','read')-or[guid]::ParseExact($p.id,'D').ToString()-cne$p.id){throw 'Exact route action/case'}
|
|
if((($p.PSObject.Properties.Name|Sort-Object)-join',')-cne'action,context_base64,context_sha256,id,manifest_sha256,pin_base64'-or$p.context_sha256-cnotmatch'^[a-f0-9]{64}$'-or$p.manifest_sha256-cnotmatch'^[a-f0-9]{64}$'){throw 'Fixed route payload'}
|
|
$base='C:\ProgramData\RustDiscoveryBootstrap';$root=Join-Path $base 'time-route';$controlRoot=Join-Path $base 'time-route-control';$case=Join-Path $root $p.id;$control=Join-Path $controlRoot $p.id
|
|
$exe=Join-Path $case 'TimeRouteProbe.exe';$source=Join-Path (Join-Path $base '4ef3fc85f5d140f2ad0ff14745dc5d5453a058203d785235d7dabafdf522b088') 'TimeRouteProbe.exe'
|
|
function Check($path,[bool]$directory){$i=Get-Item -LiteralPath $path -Force;if($i.PSIsContainer-ne$directory-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Protected regular route path'};$parent=$i.Directory;if($directory){$parent=$i.Parent};while($null-ne$parent){if($parent.Attributes-band[IO.FileAttributes]::ReparsePoint){throw 'No route reparse ancestry'};$parent=$parent.Parent};$a=Get-Acl -LiteralPath $path;if($a.GetOwner([Security.Principal.SecurityIdentifier]).Value-cnotin@('S-1-5-18','S-1-5-32-544')){throw 'Route owner'};$rules=@($a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if(!$rules.Count){throw 'Route empty DACL'};foreach($r in $rules){if($r.AccessControlType-ne'Allow'-or$r.IdentityReference.Value-cnotin@('S-1-5-18','S-1-5-32-544')){throw 'Route DACL'}}}
|
|
function Get-RmmRouteBytesSha256([byte[]]$raw){$h=[Security.Cryptography.SHA256]::Create();try{return([BitConverter]::ToString($h.ComputeHash($raw))).Replace('-','').ToLowerInvariant()}finally{$h.Dispose()}}
|
|
function FH($path){Check $path $false;return(Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant()}
|
|
function WriteNew($path,[byte[]]$raw){if($raw.Length-gt32768){throw 'Route record bound'};$f=[IO.File]::Open($path,'CreateNew','Write','Read');try{$f.Write($raw,0,$raw.Length);$f.Flush($true)}finally{$f.Dispose()}}
|
|
function Record($name,$value){WriteNew (Join-Path $control $name) ([Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 20 -Compress)))}
|
|
function DirectoryNew($path){New-Item -ItemType Directory -Path $path|Out-Null;$a=New-Object Security.AccessControl.DirectorySecurity;$a.SetSecurityDescriptorSddlForm('O:BAG:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)');Set-Acl -LiteralPath $path -AclObject $a;Check $path $true}
|
|
function ReadOwn{
|
|
$records=[ordered]@{};if(Test-Path -LiteralPath $control){Check $control $true;foreach($name in @('stage-intent.json','stage-complete.json','run-attempt.json','process.json','exit.json','stdout.txt','stderr.txt')){$path=Join-Path $control $name;if(Test-Path -LiteralPath $path){Check $path $false;$i=Get-Item -LiteralPath $path;if($i.Length-gt32768){throw 'Bounded own control read'};$records[$name]=[Convert]::ToBase64String([IO.File]::ReadAllBytes($path))}}}
|
|
if(Test-Path -LiteralPath $case){Check $case $true;foreach($name in @('intent.json','report.json','positive-request.json','positive-response.json','positive-agent-result.json','tenant-mismatch-result.json','stale-connection-result.json')){$path=Join-Path $case $name;if(Test-Path -LiteralPath $path){Check $path $false;if((Get-Item -LiteralPath $path).Length-gt32768){throw 'Bounded own result read'};$records[$name]=[Convert]::ToBase64String([IO.File]::ReadAllBytes($path))}}}
|
|
return @{id=$p.id;read_only=$true;records=$records;manifest_sha256=$p.manifest_sha256}
|
|
}
|
|
Check $base $true
|
|
if($p.action-ceq'read'){ReadOwn|ConvertTo-Json -Depth 20 -Compress;exit 0}
|
|
$context=[Convert]::FromBase64String($p.context_base64);$pin=[Convert]::FromBase64String($p.pin_base64)
|
|
if($context.Length-gt4096-or(Get-RmmRouteBytesSha256 $context)-cne$p.context_sha256-or$pin.Length-gt4096-or(Get-RmmRouteBytesSha256 $pin)-cne'c31d31d2d61f881d04f55f704abbbf98f4822650c016f39e39d4d2318bc3f6e2'){throw 'Exact actual public route inputs'}
|
|
$c=[Text.Encoding]::UTF8.GetString($context)|ConvertFrom-Json;if($c.case_id-cne$p.id){throw 'Actual context own case'}
|
|
if($p.action-ceq'stage'){
|
|
if((Test-Path -LiteralPath $case)-or(Test-Path -LiteralPath $control)){throw 'Original route stage exists; read only'}
|
|
foreach($directory in @($root,$controlRoot)){if(Test-Path -LiteralPath $directory){Check $directory $true}else{DirectoryNew $directory}}
|
|
DirectoryNew $control;Record 'stage-intent.json' @{id=$p.id;manifest_sha256=$p.manifest_sha256;context_sha256=$p.context_sha256;once=$true}
|
|
DirectoryNew $case
|
|
if((FH $source)-cne'4ef3fc85f5d140f2ad0ff14745dc5d5453a058203d785235d7dabafdf522b088'-or(Get-Item -LiteralPath $source).Length-ne19172660){throw 'Exact route EXE source'}
|
|
[IO.File]::Copy($source,$exe,$false);$f=[IO.File]::Open($exe,'Open','ReadWrite','Read');try{$f.Flush($true)}finally{$f.Dispose()}
|
|
WriteNew (Join-Path $case 'context.json') $context;WriteNew (Join-Path $case 'time-public-key.json') $pin
|
|
if((FH $exe)-cne'4ef3fc85f5d140f2ad0ff14745dc5d5453a058203d785235d7dabafdf522b088'-or(FH (Join-Path $case 'context.json'))-cne$p.context_sha256-or(FH (Join-Path $case 'time-public-key.json'))-cne'c31d31d2d61f881d04f55f704abbbf98f4822650c016f39e39d4d2318bc3f6e2'){throw 'Actual own staged inputs'}
|
|
Record 'stage-complete.json' @{id=$p.id;manifest_sha256=$p.manifest_sha256;context_sha256=$p.context_sha256;staged=$true}
|
|
@{id=$p.id;staged=$true;manifest_sha256=$p.manifest_sha256}|ConvertTo-Json -Compress;exit 0
|
|
}
|
|
if($p.action-cne'run'){throw 'Exact run required before process start'}
|
|
Check $case $true;Check $control $true;Check (Join-Path $control 'stage-complete.json') $false
|
|
$stage=Get-Content -LiteralPath (Join-Path $control 'stage-complete.json') -Raw|ConvertFrom-Json
|
|
if($stage.id-cne$p.id-or$stage.manifest_sha256-cne$p.manifest_sha256-or$stage.context_sha256-cne$p.context_sha256-or$stage.staged-ne$true){throw 'Original completed route stage'}
|
|
if((FH $exe)-cne'4ef3fc85f5d140f2ad0ff14745dc5d5453a058203d785235d7dabafdf522b088'-or(FH (Join-Path $case 'context.json'))-cne$p.context_sha256-or(FH (Join-Path $case 'time-public-key.json'))-cne'c31d31d2d61f881d04f55f704abbbf98f4822650c016f39e39d4d2318bc3f6e2'){throw 'Immediate original route input CAS'}
|
|
Record 'run-attempt.json' @{id=$p.id;manifest_sha256=$p.manifest_sha256;once=$true;no_retry=$true}
|
|
$start=New-Object Diagnostics.ProcessStartInfo;$start.FileName=$exe;$start.Arguments='probe '+$p.id;$start.UseShellExecute=$false;$start.CreateNoWindow=$true;$start.RedirectStandardOutput=$true;$start.RedirectStandardError=$true
|
|
$process=New-Object Diagnostics.Process;$process.StartInfo=$start;if(!$process.Start()){throw 'Own route probe start failed; read only'}
|
|
try{$held=$process.Handle;$birth=$process.StartTime.ToUniversalTime().ToFileTimeUtc().ToString();Record 'process.json' @{id=$p.id;pid=$process.Id;birth=$birth;held_kernel_handle=$true;exe_sha256='4ef3fc85f5d140f2ad0ff14745dc5d5453a058203d785235d7dabafdf522b088'}
|
|
$output=$process.StandardOutput.ReadToEndAsync();$errors=$process.StandardError.ReadToEndAsync();$timedOut=!$process.WaitForExit(20000)
|
|
if($timedOut){$process.Kill();if(!$process.WaitForExit(5000)){throw 'Own held route process exit uncertain'}}
|
|
if(!$output.Wait(5000)-or!$errors.Wait(5000)){throw 'Own route pipe drain uncertain'};$stdout=$output.Result;$stderr=$errors.Result
|
|
if($stdout.Length-gt32768-or$stderr.Length-gt32768){throw 'Bounded fixed route output'}
|
|
WriteNew (Join-Path $control 'stdout.txt') ([Text.Encoding]::UTF8.GetBytes($stdout));WriteNew (Join-Path $control 'stderr.txt') ([Text.Encoding]::UTF8.GetBytes($stderr))
|
|
Record 'exit.json' @{id=$p.id;pid=$process.Id;birth=$birth;kernel_process_exited=$process.HasExited;exit_code=$process.ExitCode;timed_out=$timedOut}
|
|
if($timedOut-or$process.ExitCode-ne0-or$stderr.Length){throw 'Actual route probe did not complete successfully; original read only'}
|
|
ReadOwn|ConvertTo-Json -Depth 20 -Compress
|
|
}finally{$process.Dispose()}
|
|
'''
|
|
|
|
|
|
def guards():
|
|
require(original.sha(ROOT/'deploy/windows/signed_clock_capture_acceptance.py')=='dd6c575a119751429448e40e6f306cf79efa3a86c49bf2cd32a7783937177770','fixed prior witnesses')
|
|
require("$p.action-isnot[string]-or$p.action-cnotin@('stage','run','read')" in SCRIPT
|
|
and "if($p.action-cne'run'){throw 'Exact run required before process start'}" in SCRIPT,'no action case fallthrough')
|
|
require(all(v not in SCRIPT for v in ('Start-Service','Stop-Service','Restart-Service','Remove-Item','Invoke-Expression','Bypass','Snapshot','TimeBegin')),'own files/process only')
|
|
require(sha(QUAL/'receipt.json')==RECEIPT_SHA and sha(QUAL/'TimeRouteProbe.exe')==EXE_SHA
|
|
and (QUAL/'TimeRouteProbe.exe').stat().st_size==EXE_BYTES and sha(PIN)==PIN_SHA,'exact actual qualified artifacts and public time key')
|
|
|
|
|
|
def gate():
|
|
require(isinstance(CONTEXT_GATE,dict) and set(CONTEXT_GATE)=={'id','receipt_sha256'},'ACTUAL_CONTEXT_GATE_NOT_BOUND')
|
|
ident=CONTEXT_GATE['id'];require(str(uuid.UUID(ident))==ident,'actual canonical context case')
|
|
folder=collector.STATE/ident;receipt=load(folder/'receipt.json')
|
|
require(sha(folder/'receipt.json')==CONTEXT_GATE['receipt_sha256'] and receipt['id']==ident
|
|
and receipt['collector_sha256']==sha(Path(collector.__file__)) and receipt['read_only'] is True
|
|
and sha(folder/'response.json')==receipt['response_sha256'] and sha(folder/'context.json')==receipt['context_sha256'],
|
|
'original actual postdeploy read context only')
|
|
return ident,folder,receipt
|
|
|
|
|
|
def prepare():
|
|
guards();ident,context,receipt=gate();STATE.mkdir(mode=0o700,parents=True,exist_ok=True);folder=STATE/ident;folder.mkdir(mode=0o700)
|
|
for name,path in [('TimeRouteProbe.exe',QUAL/'TimeRouteProbe.exe'),('time-public-key.json',PIN),('context.json',context/'context.json')]:original.write(folder/name,path.read_bytes())
|
|
original.write(folder/'TimeRouteAcceptance.ps1',SCRIPT.encode())
|
|
save(folder/'manifest.json',dict(id=ident,operator_sha256=sha(__file__),script_sha256=hashlib.sha256(SCRIPT.encode()).hexdigest(),
|
|
fixture_receipt_sha256=RECEIPT_SHA,exe_sha256=EXE_SHA,pin_sha256=PIN_SHA,context_gate=CONTEXT_GATE,
|
|
context_sha256=sha(folder/'context.json'),context_response_sha256=receipt['response_sha256'],dependencies=original.dependencies()))
|
|
print(json.dumps(dict(id=ident,prepared_locally=True)))
|
|
|
|
|
|
def case(ident):
|
|
require(str(uuid.UUID(ident))==ident,'original case only');folder=STATE/ident;manifest=load(folder/'manifest.json')
|
|
require(manifest['id']==ident and manifest['operator_sha256']==sha(__file__)
|
|
and manifest['script_sha256']==hashlib.sha256(SCRIPT.encode()).hexdigest()
|
|
and manifest['dependencies']==original.dependencies() and sha(folder/'TimeRouteProbe.exe')==EXE_SHA
|
|
and sha(folder/'context.json')==manifest['context_sha256'] and sha(folder/'time-public-key.json')==PIN_SHA,'exact original prepared case')
|
|
return folder,manifest
|
|
|
|
|
|
def stage_exe(access,folder):
|
|
name='TimeRouteProbe.exe';prepare=original.pipe.u.transport.PREPARE_SCRIPT.replace('TransportAcceptance.ps1',name)
|
|
observed=access.powershell(prepare,dict(sha256=EXE_SHA))
|
|
if not observed['already_uploaded']:
|
|
credentials=original.pipe.cb.contract.protected_json(access.root/'credentials/windows-dev-access.json');prefix=credentials['ssh_prefix']
|
|
argv=['sftp']+[v for v in prefix[1:-1] if v!='-T']+['-b','-',prefix[-1]]
|
|
target='/C:/ProgramData/RustDiscoveryBootstrap/'+EXE_SHA+'/'+name
|
|
result=subprocess.run(argv,input=('put '+json.dumps(str(folder/name))+' '+json.dumps(target)+'\n').encode(),capture_output=True,timeout=60)
|
|
save(folder/('transfer-'+str(uuid.uuid4())+'.json'),dict(returncode=result.returncode,stdout_b64=base64.b64encode(result.stdout).decode(),stderr_b64=base64.b64encode(result.stderr).decode()))
|
|
require(result.returncode==0,'one exact route EXE transfer; lost reply read only')
|
|
observed=access.powershell(prepare,dict(sha256=EXE_SHA));require(observed['already_uploaded'] is True and observed['sha256']==EXE_SHA,'actual immutable EXE stage')
|
|
|
|
|
|
def validate(response,manifest):
|
|
records=response['records'];require('report.json' in records and 'exit.json' in records,'actual report and kernel exit required')
|
|
report=json.loads(base64.b64decode(records['report.json'],validate=True));exited=json.loads(base64.b64decode(records['exit.json'],validate=True))
|
|
require(exited['kernel_process_exited'] is True and exited['exit_code']==0 and exited['timed_out'] is False
|
|
and report['context_sha256']==manifest['context_sha256'] and report['server_context_evidence_sha256']==manifest['context_response_sha256']
|
|
and report['verified'] is True and report['case_id']==response['id'] and report['public_time_pin_sha256']==PIN_SHA
|
|
and [v['http_status'] for v in report['reports']]==[200,403,409]
|
|
and report['reports'][0]['signature_verified'] is True and report['reports'][0]['whole_request_context_bound'] is True
|
|
and all(report[key] is False for key in ('private_key_exported','private_key_hashed','private_key_copied_to_evidence',
|
|
'certificate_verification_disabled','service_role_proven','trusted_clock_proven','clock_freshness_qualified','sync_ready','jobs_created','grants_created')),
|
|
'actual passive signature/context route only, no role/clock/job claim')
|
|
|
|
|
|
def run(action,ident):
|
|
guards();folder,manifest=case(ident);access=original.CaptureAccess(original.ACCESS_ROOT)
|
|
operation='read-'+str(uuid.uuid4()) if action=='read' else action
|
|
require(action in ('stage','run','read'),'fixed local action')
|
|
if action=='run':
|
|
stage=load(folder/'stage-reply.json');proof=load(folder/'stage-preservation.json')
|
|
require(stage.get('staged') is True and stage['id']==ident and stage['manifest_sha256']==sha(folder/'manifest.json')
|
|
and proof['id']==ident and proof['operation_id']=='stage' and proof['action']=='stage' and proof['read_only'] is False
|
|
and proof['operator_sha256']==sha(__file__) and proof['manifest_sha256']==sha(folder/'manifest.json')
|
|
and proof['raw_reply']==dict(filename='stage-reply.json',sha256=sha(folder/'stage-reply.json')),'original complete linked stage before the single run')
|
|
for name in ('server','native'):
|
|
link=proof[name+'_witness'];require(link['filename']=='stage-'+name+'.json' and sha(folder/link['filename'])==link['sha256'],'original stage witness links')
|
|
if action!='read':
|
|
gate_id,context,receipt=gate();require(gate_id==ident and manifest['context_gate']==CONTEXT_GATE,'actual original sealed context gate')
|
|
fresh=collector.rpc(access,dict(id=ident,deployment_result_sha256=receipt['deployment_result_sha256'],image=collector.IMAGE),folder)
|
|
require(fresh==load(context/'response.json'),'actual current DB boot/generation/gateway still exact before action')
|
|
save(folder/(operation+'-attempt.json'),dict(action=action,once=True,no_retry=True,operator_sha256=sha(__file__)))
|
|
else:save(folder/(operation+'-intent.json'),dict(action='read',read_only=True,operator_sha256=sha(__file__)))
|
|
before_server,before_native=original.server_closed(access),original.native_witness(access)
|
|
baseline=folder/'baseline.json'
|
|
if not baseline.exists():save(baseline,dict(server=before_server,native=before_native))
|
|
original.preserved(load(baseline)['native'],before_native);require(load(baseline)['server']==before_server,'same original closed server scope')
|
|
if action=='stage':stage_exe(access,folder)
|
|
payload=dict(action=action,id=ident,manifest_sha256=sha(folder/'manifest.json'),context_sha256=manifest['context_sha256'],
|
|
context_base64=base64.b64encode((folder/'context.json').read_bytes()).decode(),pin_base64=base64.b64encode((folder/'time-public-key.json').read_bytes()).decode())
|
|
response=access.powershell(SCRIPT,payload,timeout=90)
|
|
raw=folder/(operation+'-reply.json');save(raw,response) # raw first, before outcome/witness assertions
|
|
after_server,after_native=original.server_closed(access),original.native_witness(access)
|
|
require(before_server==after_server,'closed server gates and counters preserved');original.preserved(before_native,after_native)
|
|
binding=dict(id=ident,operation_id=operation,action=action,read_only=action=='read',operator_sha256=sha(__file__),
|
|
raw_reply=dict(filename=raw.name,sha256=sha(raw)),manifest_sha256=sha(folder/'manifest.json'))
|
|
server=folder/(operation+'-server.json');native=folder/(operation+'-native.json')
|
|
save(server,dict(binding,before=before_server,after=after_server));save(native,dict(binding,before=before_native,after=after_native))
|
|
save(folder/(operation+'-preservation.json'),dict(binding,server_witness=dict(filename=server.name,sha256=sha(server)),
|
|
native_witness=dict(filename=native.name,sha256=sha(native)),no_rmm_jobs=True,no_service_action=True))
|
|
require(response['id']==ident and response['manifest_sha256']==sha(folder/'manifest.json'),'same original route case response')
|
|
if action=='stage':require(response['staged'] is True,'actual complete stage')
|
|
elif action=='run' or 'report.json' in response.get('records',{}):validate(response,manifest)
|
|
print(json.dumps(dict(id=ident,action=action,preserved=True,completed='report.json' in response.get('records',{}),read_only=action=='read')))
|
|
|
|
|
|
if __name__=='__main__':
|
|
p=argparse.ArgumentParser(description=__doc__);p.add_argument('action',choices=('guards','prepare','stage','run','read'));p.add_argument('--case');a=p.parse_args()
|
|
if a.action=='guards':guards();print('PASS source guards; no target call')
|
|
elif a.action=='prepare':require(a.case is None,'actual sealed context determines own case');prepare()
|
|
else:require(a.case is not None,'original case required');run(a.action,a.case)
|