Verify passive Windows time route tooling on the test guest
Rust development slice / linux (push) Failing after 6s
Rust development slice / linux (push) Failing after 6s
This commit is contained in:
@@ -0,0 +1,189 @@
|
||||
#!/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)
|
||||
@@ -0,0 +1,102 @@
|
||||
#!/usr/bin/env python3
|
||||
"""One fixed post-deployment public context read. No SQL/HTTP writes or secrets."""
|
||||
import argparse
|
||||
import base64
|
||||
import hashlib
|
||||
import inspect
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import uuid
|
||||
import signed_clock_capture_acceptance as original
|
||||
|
||||
ROOT=original.ROOT
|
||||
STATE=ROOT/'devstate/windows-time-route-context'
|
||||
# Root binds the actual successful deployment result SHA after its separate read.
|
||||
DEPLOYMENT_RESULT_SHA=None
|
||||
DEPLOYMENT_PATH='/opt/rust-discovery/devstate/time-gateway-deploy-fb87aa88-2b67-4cff-9c90-4cd713380889/result.json'
|
||||
IMAGE='sha256:422c2c28a91ac512e9317908f4d1fb22247eef857ca95d45e1b1880598b0d611'
|
||||
BINDING_SHA='05c5678fed81e0a2a7cdaaeaf18c64f9837cfbe76c140699a47306c9b4598a18'
|
||||
require,save,load,sha=original.require,original.save,original.load,original.sha
|
||||
|
||||
|
||||
def server_read(p):
|
||||
import hashlib,json,os,stat,subprocess,uuid
|
||||
from pathlib import Path
|
||||
def need(v):
|
||||
if not v:raise RuntimeError('FIXED_READONLY_CONTEXT_INCOMPLETE')
|
||||
need(set(p)=={'id','deployment_result_sha256','image'})
|
||||
need(str(uuid.UUID(p['id']))==p['id'] and isinstance(p['deployment_result_sha256'],str) and len(p['deployment_result_sha256'])==64
|
||||
and all(v in '0123456789abcdef' for v in p['deployment_result_sha256'])
|
||||
and p['image']=='sha256:422c2c28a91ac512e9317908f4d1fb22247eef857ca95d45e1b1880598b0d611')
|
||||
path=Path('/opt/rust-discovery/devstate/time-gateway-deploy-fb87aa88-2b67-4cff-9c90-4cd713380889/result.json')
|
||||
metadata=path.lstat();need(stat.S_ISREG(metadata.st_mode) and metadata.st_uid==0 and metadata.st_nlink==1
|
||||
and stat.S_IMODE(metadata.st_mode)==0o600 and metadata.st_size<=65536)
|
||||
def identity(m):return(m.st_dev,m.st_ino,m.st_mode,m.st_uid,m.st_gid,m.st_nlink,m.st_size,m.st_mtime_ns,m.st_ctime_ns)
|
||||
raw=path.read_bytes();need(identity(path.lstat())==identity(metadata) and hashlib.sha256(raw).hexdigest()==p['deployment_result_sha256'])
|
||||
deployed=json.loads(raw);need(deployed['deployed'] is True and deployed['rmm_jobs_created'] is False
|
||||
and deployed['approvals_created'] is False and deployed['gateway_only_readonly_broker_mount'] is True)
|
||||
def command(args,data=None):
|
||||
r=subprocess.run(args,input=data,stdin=None,stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=10)
|
||||
need(r.returncode==0 and len(r.stdout)<=65536 and len(r.stderr)<=65536);return r.stdout
|
||||
def gateway():
|
||||
value=json.loads(command(['docker','inspect','rust-discovery-server-gateway-1','--format',
|
||||
'[{{json .Id}},{{json .Image}},{{json .Config.User}},{{json .State.Running}},{{json .HostConfig.PidMode}}]']))
|
||||
need(value[1]==p['image'] and value[2]=='10001:10001' and value[3] is True and value[4]!='host');return value
|
||||
boot=Path('/proc/sys/kernel/random/boot_id').read_text().strip();need(str(uuid.UUID(boot))==boot)
|
||||
before=gateway()
|
||||
query=("BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY; SET LOCAL statement_timeout='3s'; "
|
||||
"SELECT json_build_object('tenant_id',tenant_id,'agent_id',agent_id,'asset_id',asset_id,"
|
||||
"'enrollment_generation',enrollment_generation,'assignment_generation',assignment_version,"
|
||||
"'connection_generation',connection_generation,'windows_boot_id',connection_boot_id,'capabilities',capabilities) "
|
||||
"FROM agent_installations WHERE tenant_id='11111111-1111-4111-8111-111111111111' "
|
||||
"AND agent_id='63ea15b2-0643-403d-b5b4-cba1288dbea3' AND revoked_at IS NULL; COMMIT;")
|
||||
raw=command(['docker','exec','-i','rust-discovery-server-postgres-1','psql','-X','-qAt','-v','ON_ERROR_STOP=1','-U','postgres','-d','rmm'],query.encode())
|
||||
row=json.loads(raw)
|
||||
need(row['tenant_id']=='11111111-1111-4111-8111-111111111111' and row['agent_id']=='63ea15b2-0643-403d-b5b4-cba1288dbea3'
|
||||
and row['asset_id']=='a176520e-8a91-4e93-a78b-8e7620f430e0' and row['enrollment_generation']==1
|
||||
and row['assignment_generation']==1 and type(row['connection_generation']) is int and row['connection_generation']>1
|
||||
and str(uuid.UUID(row['windows_boot_id']))==row['windows_boot_id'] and 'windows.base/1' in row['capabilities'])
|
||||
need(before==gateway() and Path('/proc/sys/kernel/random/boot_id').read_text().strip()==boot)
|
||||
return dict(profile='rmm.windows.time-route.actual-public-context.v1',id=p['id'],server_boot_id=boot,
|
||||
installation=row,gateway=before,deployment_result_sha256=p['deployment_result_sha256'],sql_read_only=True,secrets_read=False)
|
||||
|
||||
|
||||
def rpc(access,payload,folder):
|
||||
# Same strict Main SSH configuration parser as CaptureAccess.server; never source/eval.
|
||||
cloud=original.pipe.u.transport.cloud
|
||||
cfg=cloud.bootstrap.access.load_config(access.root/'credentials/server.conf')
|
||||
prefix=['ssh','-F','/dev/null','-T','-p',cfg.get('port','22'),'-o','StrictHostKeyChecking=yes','-o','BatchMode=yes',
|
||||
'-o','IdentitiesOnly=yes','-o','ForwardAgent=no','-o','ConnectTimeout=10','-i',str(Path(cfg['ssh_key_path']).expanduser()),cfg['username']+'@'+cfg['address'],'python3 -']
|
||||
code=inspect.getsource(server_read)+'\nimport json\nprint(json.dumps(server_read('+repr(payload)+')))\n'
|
||||
r=subprocess.run(prefix,input=code.encode(),capture_output=True,timeout=30)
|
||||
save(folder/('transport-'+str(uuid.uuid4())+'.json'),dict(returncode=r.returncode,stdout_b64=base64.b64encode(r.stdout).decode(),stderr_b64=base64.b64encode(r.stderr).decode()))
|
||||
require(r.returncode==0 and len(r.stdout)<=65536,'bounded actual context transport; original read only')
|
||||
return json.loads(r.stdout,object_pairs_hook=original.pipe.cb.contract.strict_object)
|
||||
|
||||
|
||||
def collect():
|
||||
require(type(DEPLOYMENT_RESULT_SHA) is str and re.fullmatch('[0-9a-f]{64}',DEPLOYMENT_RESULT_SHA) is not None,'ACTUAL_DEPLOYMENT_GATE_NOT_BOUND')
|
||||
original.original_main();STATE.mkdir(mode=0o700,parents=True,exist_ok=True)
|
||||
ident=str(uuid.uuid4());folder=STATE/ident;folder.mkdir(mode=0o700)
|
||||
payload=dict(id=ident,deployment_result_sha256=DEPLOYMENT_RESULT_SHA,image=IMAGE)
|
||||
save(folder/'intent.json',dict(id=ident,collector_sha256=sha(__file__),read_only=True,payload=payload))
|
||||
response=rpc(original.CaptureAccess(original.ACCESS_ROOT),payload,folder)
|
||||
save(folder/'response.json',response)
|
||||
require(response['id']==ident and response['sql_read_only'] is True and response['secrets_read'] is False,'actual original public context only')
|
||||
context=dict(schema_version=1,case_id=ident,connection_generation=response['installation']['connection_generation'],
|
||||
windows_boot_id=response['installation']['windows_boot_id'],server_boot_id=response['server_boot_id'],
|
||||
server_context_evidence_sha256=sha(folder/'response.json'),binding_sha256=BINDING_SHA)
|
||||
save(folder/'context.json',context)
|
||||
save(folder/'receipt.json',dict(id=ident,collector_sha256=sha(__file__),deployment_result_sha256=DEPLOYMENT_RESULT_SHA,
|
||||
response_sha256=sha(folder/'response.json'),context_sha256=sha(folder/'context.json'),gateway=response['gateway'],read_only=True))
|
||||
print(json.dumps(dict(id=ident,read_only=True,receipt_sha256=sha(folder/'receipt.json'),context_sha256=sha(folder/'context.json'))))
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('action',choices=('collect','guards'));a=parser.parse_args()
|
||||
if a.action=='collect':collect()
|
||||
else:
|
||||
require('READ ONLY' in inspect.getsource(server_read) and 'UPDATE ' not in inspect.getsource(server_read),'fixed SQL read only')
|
||||
print('PASS source guards; no target action')
|
||||
Reference in New Issue
Block a user