Complete isolated Windows capture fixture with preserved native evidence
Rust development slice / linux (push) Failing after 6s

This commit is contained in:
2026-11-15 08:45:38 +01:00
parent ef4d8adc97
commit a5eacc0e40
4 changed files with 671 additions and 0 deletions
@@ -0,0 +1,243 @@
#!/usr/bin/env python3
"""Local builder: one original-case setup completion and bounded delta controller.
No transport or target actions. The original failed setup/controller are never
rewritten. Completion owns ACLs, two new role dirs and one exact EXE copy only;
the separate delta owns explicit role start/read/stopped cleanup phases only.
"""
import argparse
import hashlib
import json
import os
from pathlib import Path
import stat
import uuid
ROOT = Path(__file__).resolve().parents[2]
CASE = 'efd17b43-7e04-49a7-9bd4-862d13365eec'
ORIGINAL = ROOT / 'devstate/windows-signed-clock-capture-native' / CASE
REPAIR = ROOT / 'devstate/windows-signed-clock-capture-system-repair/cff25311-d30b-495a-8b50-e0e28e2e5b48'
OLD_SCRIPT_SHA = '89c19138e2804f263f1875c7697a7d53f54f40722101677b4d29538c917196f4'
OLD_MANIFEST_SHA = '806c062bdd458627cf44ff1ef3f27738e1ebf2f407a96f772223efef267db0b1'
REPAIR_SCRIPT_SHA = 'ac3da3d86bd93497e8ecfe55369cb228ed0ce30c7f2301afb74463c789bb50ca'
REPAIR_REPLY_SHA = 'b87746dc066fc255d2cbf1871698811203d38410e27c8d6d51d2d38ea7752c96'
REPAIR_PRESERVATION_SHA = 'a1bb8a42e22f2d0263dc381bd675134effe6555867b57b7f4fae28eb6f319ad6'
EXE_SHA = '601c27a43fb67c662f926f9dc289a23a5c31c7e27f62901a77fc9ceaafaea7fb'
EXE_BYTES = 8566784
COMPLETE_PROFILE = 'rmm.windows.raw-clock.original-completion.v1'
DELTA_PROFILE = 'rmm.windows.raw-clock.original-delta.v1'
def require(value, reason):
if not value:
raise RuntimeError(reason)
def sha(raw):
return hashlib.sha256(raw).hexdigest()
def read(path, limit=2 * 1024 * 1024):
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
with os.fdopen(fd, 'rb') as stream:
before = os.fstat(stream.fileno())
require(stat.S_ISREG(before.st_mode) and before.st_nlink == 1 and before.st_uid == os.getuid()
and stat.S_IMODE(before.st_mode) == 0o600 and before.st_size <= limit, 'private bounded input')
raw = stream.read(limit + 1)
after = os.fstat(stream.fileno())
require(len(raw) <= limit and (before.st_ino, before.st_size, before.st_mtime_ns, before.st_ctime_ns)
== (after.st_ino, after.st_size, after.st_mtime_ns, after.st_ctime_ns), 'same retained input')
return raw
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())
fd = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
try:
os.fsync(fd)
finally:
os.close(fd)
def encoded(value):
return (json.dumps(value, sort_keys=True, separators=(',', ':')) + '\n').encode()
def between(source, start, end):
require(source.count(start) == source.count(end) == 1, 'unique frozen source boundaries')
return source[source.index(start):source.index(end)]
def replace_once(source, old, new):
require(source.count(old) == 1, 'exact single frozen delta replacement')
return source.replace(old, new, 1)
QUERY_NATIVE = r'''
Add-Type -TypeDefinition @'
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
public static class RmmCaptureCompletionStatus {
[DllImport("advapi32.dll",EntryPoint="OpenSCManagerW",ExactSpelling=true,CharSet=CharSet.Unicode,SetLastError=true)] static extern IntPtr Manager(string machine,string database,uint access);
[DllImport("advapi32.dll",EntryPoint="OpenServiceW",ExactSpelling=true,CharSet=CharSet.Unicode,SetLastError=true)] static extern IntPtr OpenService(IntPtr manager,string name,uint access);
[DllImport("advapi32.dll",SetLastError=true)] [return:MarshalAs(UnmanagedType.Bool)] static extern bool CloseServiceHandle(IntPtr handle);
[DllImport("advapi32.dll",SetLastError=true)] [return:MarshalAs(UnmanagedType.Bool)] static extern bool QueryServiceStatusEx(Service handle,int level,out Status value,int size,out int needed);
[StructLayout(LayoutKind.Sequential)] public struct Status {public uint Type,State,Controls,Win32Exit,SpecificExit,Checkpoint,WaitHint,Pid,Flags;}
public sealed class Service:SafeHandleZeroOrMinusOneIsInvalid {
internal Service(IntPtr value):base(true){SetHandle(value);}
protected override bool ReleaseHandle(){return CloseServiceHandle(handle);}
public Status Read(){Status value;int needed;if(!QueryServiceStatusEx(this,0,out value,Marshal.SizeOf(typeof(Status)),out needed)){int code=Marshal.GetLastWin32Error();throw new Win32Exception(code,"CAPTURE_COMPLETION_QueryServiceStatusEx");}return value;}
}
static Service OpenFixed(string name){IntPtr manager=Manager(null,null,1);if(manager==IntPtr.Zero){int code=Marshal.GetLastWin32Error();throw new Win32Exception(code,"CAPTURE_COMPLETION_OpenSCManagerW");}try{IntPtr handle=OpenService(manager,name,4);if(handle==IntPtr.Zero){int code=Marshal.GetLastWin32Error();throw new Win32Exception(code,"CAPTURE_COMPLETION_OpenServiceW");}return new Service(handle);}finally{CloseServiceHandle(manager);}}
public static Service Local(){return OpenFixed("RmmSignedClockCaptureLocalService");}
public static Service System(){return OpenFixed("RmmSignedClockCaptureSystem");}
}
'@
'''
COMPLETE_HEAD = r'''
$ErrorActionPreference='Stop';$request=$global:RmmCaptureCompletionPayload
if(!$request-or(($request.PSObject.Properties.Name|Sort-Object)-join',')-cne'action,id,profile,script_sha256'-or$request.id-cne'efd17b43-7e04-49a7-9bd4-862d13365eec'-or$request.profile-cne'rmm.windows.raw-clock.original-completion.v1'-or$request.action-notin@('complete','read')-or$request.script_sha256-notmatch'^[a-f0-9]{64}$'){throw 'Fixed original completion request'}
$p=@{id='efd17b43-7e04-49a7-9bd4-862d13365eec'};$base='C:\ProgramData\RustDiscoverySignedClockCapture';$case=Join-Path $base $p.id;$control=Join-Path $case 'control';$exe=Join-Path $case 'SignedClockCapture.exe';$boot='C:\ProgramData\RustDiscoveryBootstrap'
$names=@('RmmSignedClockCaptureLocalService','RmmSignedClockCaptureSystem');$tags=@('local-service','system');$accounts=@('NT AUTHORITY\LocalService','LocalSystem');$sys='S-1-5-18';$admin='S-1-5-32-544'
# Fixed own capabilities: two reader ACLs, two create-only role dirs, one exact
# 601c27a4 EXE copy and completion records. NO SCM mutation/start/stop/delete.
'''
COMPLETE_BODY = r'''
if($PSCommandPath-cne(Join-Path (Join-Path $boot $request.script_sha256) 'SignedClockCaptureCompletion.ps1')-or(HashFile $PSCommandPath)-cne$request.script_sha256){throw 'Actual exact completion controller'}
Check $PSCommandPath $false
$originalScript=Join-Path (Join-Path $boot '89c19138e2804f263f1875c7697a7d53f54f40722101677b4d29538c917196f4') 'SignedClockCaptureAcceptance.ps1';Check $originalScript $false;if((HashFile $originalScript)-cne'89c19138e2804f263f1875c7697a7d53f54f40722101677b4d29538c917196f4'){throw 'Original controller bytes'}
$repairScript=Join-Path (Join-Path $boot 'ac3da3d86bd93497e8ecfe55369cb228ed0ce30c7f2301afb74463c789bb50ca') 'SignedClockCaptureSystemRepair.ps1';Check $repairScript $false;if((HashFile $repairScript)-cne'ac3da3d86bd93497e8ecfe55369cb228ed0ce30c7f2301afb74463c789bb50ca'){throw 'Exact system repair bytes'}
$sids=@();foreach($name in $names){$sids+=((New-Object Security.Principal.NTAccount('NT SERVICE',$name)).Translate([Security.Principal.SecurityIdentifier]).Value)}
if($sids.Count-ne2-or$sids[0]-ceq$sids[1]-or@($sids|Where-Object{$_-notmatch'^S-1-5-80(-[0-9]+){5}$'}).Count-ne0){throw 'Two actual fixed service SIDs'}
Check $base $true $sids;Check $case $true $sids;Check $control $true
$intent=ReadJson (Join-Path $control 'intent.json');$active=ReadJson (Join-Path $base 'active.json') $sids
if($intent.id-cne$p.id-or$intent.action-cne'setup'-or$intent.profile-cne'rmm.windows.raw-clock.two-role-bootstrap.v1'-or$intent.script_sha256-cne'89c19138e2804f263f1875c7697a7d53f54f40722101677b4d29538c917196f4'-or$intent.manifest_sha256-cne'806c062bdd458627cf44ff1ef3f27738e1ebf2f407a96f772223efef267db0b1'-or$intent.exe_sha256-cne'601c27a43fb67c662f926f9dc289a23a5c31c7e27f62901a77fc9ceaafaea7fb'-or$intent.exe_bytes-ne8566784-or$active.id-cne$p.id-or$active.script_sha256-cne$intent.script_sha256-or$active.manifest_sha256-cne$intent.manifest_sha256-or$active.no_retry-ne$true){throw 'Original failed setup intent and active binding'}
$ls=ReadJson (Join-Path $control 'local-service-created.json');$system=ReadJson (Join-Path $control 'system-create-repair-created.json');$repairAttempt=ReadJson (Join-Path $control 'system-create-repair-attempt.json')
if($ls.create_once-ne$true-or$system.id-cne$p.id-or$system.profile-cne'rmm.windows.raw-clock.original-system-create-repair.v1'-or$system.script_sha256-cne'ac3da3d86bd93497e8ecfe55369cb228ed0ce30c7f2301afb74463c789bb50ca'-or$system.stopped-ne$true-or$system.create_once-ne$true-or$system.setup_completed-ne$false-or$system.service_started-ne$false-or$repairAttempt.id-cne$p.id-or$repairAttempt.script_sha256-cne$system.script_sha256-or$repairAttempt.original_manifest_sha256-cne$intent.manifest_sha256-or$repairAttempt.original_controller_sha256-cne$intent.script_sha256-or$repairAttempt.system_account_null_inside_csharp-ne$true-or$repairAttempt.no_retry-ne$true){throw 'Original LS and exact successful SYSTEM repair'}
for($n=0;$n-lt2;$n++){$attempt=ReadJson (Join-Path $control ($tags[$n]+'-create-attempt.json'));if($attempt.create_once-ne$true-or$attempt.command-cne(Command $n)){throw 'Original service attempt binding'}}
$currentLocal=Service 0;$currentSystem=Service 1;if(!$currentLocal-or!$currentSystem-or!(Equal $currentLocal $ls.service)-or!(Equal $currentSystem $system.service)){throw 'Both exact original stopped service definitions'}
$localHandle=[RmmCaptureCompletionStatus]::Local();$systemHandle=$null
try{
$systemHandle=[RmmCaptureCompletionStatus]::System();if($localHandle.Read().State-ne1-or$systemHandle.Read().State-ne1){throw 'Both fixed services must remain stopped'}
$allowed=@('intent.json','local-service-create-attempt.json','local-service-created.json','system-create-attempt.json','system-create-repair-attempt.json','system-create-repair-created.json','setup-repair-attempt.json','setup-repair-complete.json','setup-repair-failure.json');foreach($item in @(Get-ChildItem -LiteralPath $control -Force)){if($item.PSIsContainer-or$item.Name-notin$allowed){throw 'Unexpected role entry/progress: original read only'}}
$attemptPath=Join-Path $control 'setup-repair-attempt.json';$completePath=Join-Path $control 'setup-repair-complete.json';$failurePath=Join-Path $control 'setup-repair-failure.json'
if($request.action-ceq'read'){$records=[ordered]@{};foreach($path in @($attemptPath,$completePath,$failurePath)){$records[[IO.Path]::GetFileName($path)]=$null;if(Test-Path -LiteralPath $path){$records[[IO.Path]::GetFileName($path)]=ReadJson $path}};@{id=$p.id;read_only=$true;both_exact_stopped=$true;roles=$sids;records=$records;role_dirs=@(Test-Path -LiteralPath (Join-Path $case 'local-service');Test-Path -LiteralPath (Join-Path $case 'system'));case_executable_present=(Test-Path -LiteralPath $exe);service_actions=$false;clock_authority=$false;calibrated=$false}|ConvertTo-Json -Depth 24 -Compress;exit 0}
if((Test-Path -LiteralPath $attemptPath)-or(Test-Path -LiteralPath $completePath)-or(Test-Path -LiteralPath $failurePath)-or(Test-Path -LiteralPath $exe)-or(Test-Path -LiteralPath (Join-Path $case 'local-service'))-or(Test-Path -LiteralPath (Join-Path $case 'system'))){throw 'Completion already attempted or progressed; original read only'}
$staged=Join-Path (Join-Path $boot '601c27a43fb67c662f926f9dc289a23a5c31c7e27f62901a77fc9ceaafaea7fb') 'SignedClockCapture.exe';Check $staged $false;if((Get-Item -LiteralPath $staged).Length-ne8566784-or(HashFile $staged)-cne'601c27a43fb67c662f926f9dc289a23a5c31c7e27f62901a77fc9ceaafaea7fb'){throw 'Only original exact staged image'}
WriteNew $attemptPath @{id=$p.id;profile=$request.profile;script_sha256=$request.script_sha256;original_manifest_sha256=$intent.manifest_sha256;original_controller_sha256=$intent.script_sha256;system_repair_script_sha256=$system.script_sha256;roles=$sids;exe_sha256=$intent.exe_sha256;create_only=$true;no_retry=$true;service_actions=$false}
try{
foreach($path in @($base,$case)){$a=New-Object Security.AccessControl.DirectorySecurity;$a.SetAccessRuleProtection($true,$false);$a.SetOwner((New-Object Security.Principal.SecurityIdentifier($admin)));foreach($sid in @($sys,$admin)){$a.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule((New-Object Security.Principal.SecurityIdentifier($sid)),'FullControl','ContainerInherit,ObjectInherit','None','Allow')))};foreach($sid in $sids){$a.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule((New-Object Security.Principal.SecurityIdentifier($sid)),'ReadAndExecute','ContainerInherit,ObjectInherit','None','Allow')))};Set-Acl -LiteralPath $path -AclObject $a;Check $path $true $sids}
for($n=0;$n-lt2;$n++){NewDir (Join-Path $case $tags[$n]) $sids @($sids[$n])}
[IO.File]::Copy($staged,$exe,$false);$a=New-Object Security.AccessControl.FileSecurity;$a.SetAccessRuleProtection($true,$false);$a.SetOwner((New-Object Security.Principal.SecurityIdentifier($admin)));foreach($sid in @($sys,$admin)){$a.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule((New-Object Security.Principal.SecurityIdentifier($sid)),'FullControl','Allow')))};foreach($sid in $sids){$a.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule((New-Object Security.Principal.SecurityIdentifier($sid)),'ReadAndExecute','Allow')))};Set-Acl -LiteralPath $exe -AclObject $a;$file=[IO.File]::Open($exe,'Open','ReadWrite','Read');try{$file.Flush($true)}finally{$file.Dispose()};Check $exe $false $sids;if((Get-Item -LiteralPath $exe).Length-ne8566784-or(HashFile $exe)-cne$intent.exe_sha256){throw 'Final exact image copy'}
if($localHandle.Read().State-ne1-or$systemHandle.Read().State-ne1-or!(Equal (Service 0) $ls.service)-or!(Equal (Service 1) $system.service)){throw 'Both unchanged stopped definitions after completion'}
WriteNew $completePath @{schema_version=1;id=$p.id;profile=$request.profile;script_sha256=$request.script_sha256;original_manifest_sha256=$intent.manifest_sha256;original_controller_sha256=$intent.script_sha256;system_repair_script_sha256=$system.script_sha256;roles=$sids;exe_sha256=$intent.exe_sha256;exe_bytes=8566784;completed=$true;service_actions=$false;calibrated=$false;clock_authority=$false}
@{id=$p.id;setup_repair_completed=$true;original_setup_replayed=$false;service_actions=$false;calibrated=$false;clock_authority=$false}|ConvertTo-Json -Compress
}catch{if(!(Test-Path -LiteralPath $failurePath)){WriteNew $failurePath @{id=$p.id;script_sha256=$request.script_sha256;failed=$true;read_original_case_only=$true}};throw 'Completion failed; original read only; no retry'}
}finally{if($null-ne$systemHandle){$systemHandle.Dispose()};$localHandle.Dispose()}
'''
def completion(original):
helpers = between(original, 'function HashBytes', 'function Original')
return (COMPLETE_HEAD + helpers + QUERY_NATIVE + COMPLETE_BODY).encode('ascii')
def delta(original, completion_sha):
value = original
# Remove the actual setup branch and all of its unused creation helpers.
start = value.index("if($p.action-ceq'setup'){")
end = value.index("if($p.action-ceq'read'-and!(Test-Path -LiteralPath (Join-Path $control 'setup-complete.json')))", start)
value = value[:start] + value[end:]
newdir = between(value, 'function NewDir', 'function WriteNew')
value = replace_once(value, newdir, '')
create = between(value, ' public static Service CreateOnce', ' public static Service OpenOwn')
value = replace_once(value, create, '')
for line in value.splitlines(keepends=True):
if any(name in line for name in ('extern IntPtr CreateService(', 'extern bool ChangeServiceConfig2(',
'extern bool SetServiceObjectSecurity(', 'extern bool ConvertStringSecurityDescriptorToSecurityDescriptor(')):
value = replace_once(value, line, '')
value = replace_once(value, "@('setup','start-local-service','start-system','read','cleanup-local-service','cleanup-system')",
"@('start-local-service','start-system','read','cleanup-local-service','cleanup-system')")
value = replace_once(value, '$global:RmmSignedClockCapturePayload', '$global:RmmCaptureDeltaPayload')
value = value.replace("$p.profile-cne'rmm.windows.raw-clock.two-role-bootstrap.v1'", "$p.profile-cne'" + DELTA_PROFILE + "'")
value = replace_once(value, "$base='C:\\ProgramData\\RustDiscoverySignedClockCapture';", "if($p.id-cne'" + CASE + "'-or$p.manifest_sha256-cne'" + OLD_MANIFEST_SHA + "'){throw 'Only fixed original delta case'}\n# Own phase capabilities: explicit role start/read/held-process watchdog/stopped cleanup only. No service creation, setup, directory creation or image copy.\n$base='C:\\ProgramData\\RustDiscoverySignedClockCapture';")
value = replace_once(value, '||bytes!=Marshal.SizeOf(typeof(Status))', '')
value = replace_once(value, "'SignedClockCaptureAcceptance.ps1'", "'SignedClockCaptureDelta.ps1'")
value = value.replace("'setup-complete.json'", "'setup-repair-complete.json'")
old_original = between(value, 'function Original', 'function ReadAll')
new_original = "function Original([int]$n){$leaf='local-service-created.json';if($n-eq1){$leaf='system-create-repair-created.json'};$made=ReadJson (Join-Path $control $leaf);if($made.create_once-ne$true){throw 'Original created proof'};if($n-eq1-and($made.id-cne$p.id-or$made.profile-cne'rmm.windows.raw-clock.original-system-create-repair.v1'-or$made.script_sha256-cne'" + REPAIR_SCRIPT_SHA + "'-or$made.stopped-ne$true-or$made.service_started-ne$false)){throw 'Exact SYSTEM repair created proof'};$s=Service $n;if(!$s-or!(Equal $s $made.service)){throw 'Same original fixture definition'};return $s}\n"
value = replace_once(value, old_original, new_original)
marker_path = "$path=Join-Path $control ($tags[$n]+'-'+$leaf+'.json');"
value = replace_once(value, marker_path,
"if($n-eq1-and$leaf-ceq'created'){$path=Join-Path $control 'system-create-repair-created.json'}else{" + marker_path + "};")
value = replace_once(value, "@('id','profile','exe_sha256','exe_bytes','script_sha256','manifest_sha256')", "@('id','exe_sha256','exe_bytes','manifest_sha256')")
value = replace_once(value, "$a.script_sha256-cne$p.script_sha256", "$a.script_sha256-cne'" + OLD_SCRIPT_SHA + "'")
anchor = "$setup=ReadJson (Join-Path $control 'setup-repair-complete.json');"
validate = "$setup=ReadJson (Join-Path $control 'setup-repair-complete.json');if($setup.schema_version-ne1-or$setup.id-cne$p.id-or$setup.profile-cne'" + COMPLETE_PROFILE + "'-or$setup.script_sha256-cne'" + completion_sha + "'-or$setup.original_controller_sha256-cne'" + OLD_SCRIPT_SHA + "'-or$setup.original_manifest_sha256-cne'" + OLD_MANIFEST_SHA + "'-or$setup.system_repair_script_sha256-cne'" + REPAIR_SCRIPT_SHA + "'-or$setup.exe_sha256-cne$p.exe_sha256-or$setup.exe_bytes-ne8566784-or$setup.completed-ne$true-or$setup.service_actions-ne$false-or$setup.clock_authority-ne$false-or$setup.calibrated-ne$false){throw 'Exact repaired completion proof'};"
value = replace_once(value, anchor, validate)
anchor = "$i=ReadJson (Join-Path $control 'intent.json');"
value = replace_once(value, anchor, anchor + "if($i.profile-cne'rmm.windows.raw-clock.two-role-bootstrap.v1'-or$i.script_sha256-cne'" + OLD_SCRIPT_SHA + "'-or$i.action-cne'setup'){throw 'Original failed setup context'};")
# The old controller is an immutable provenance input, never executed.
anchor = "if($p.action-ceq'read'-and!(Test-Path -LiteralPath $case))"
original_guard = "$oldController=Join-Path (Join-Path $boot '" + OLD_SCRIPT_SHA + "') 'SignedClockCaptureAcceptance.ps1';if((HashFile $oldController)-cne'" + OLD_SCRIPT_SHA + "'){throw 'Original controller bytes'}\n"
value = replace_once(value, anchor, original_guard + anchor)
require(all(token not in value for token in ('CreateOnce(', 'CreateService(', 'ChangeServiceConfig2(',
'function NewDir', '[IO.File]::Copy(', "if($p.action-ceq'setup')", '||bytes!=')), 'removed setup capability, not merely unreachable')
require(value.count('StartOnce()') == 2 and value.count('DeleteOnce()') == 2,
'unchanged single native start/delete wrappers and explicit callsites')
return value.encode('ascii')
def prepare():
original_raw = read(ORIGINAL / 'SignedClockCaptureAcceptance.ps1')
require(sha(original_raw) == OLD_SCRIPT_SHA and sha(read(ORIGINAL / 'manifest.json')) == OLD_MANIFEST_SHA,
'unchanged original campaign/controller')
reply_raw, witness_raw = read(REPAIR / 'repair-reply.json'), read(REPAIR / 'repair-preservation.json')
require(sha(reply_raw) == REPAIR_REPLY_SHA and sha(witness_raw) == REPAIR_PRESERVATION_SHA,
'actual original SYSTEM repair and six-field/server preservation')
reply = json.loads(reply_raw)
require(reply['id'] == CASE and reply['system_created_stopped'] is True
and reply['setup_completed'] is False and reply['service_started'] is False,
'actual stopped repaired fixture, no role execution')
complete = completion(original_raw.decode())
changed = delta(original_raw.decode(), sha(complete))
require(len(complete) <= 32768 and len(changed) <= 65536, 'finite bounded controllers')
state = ROOT / 'devstate/windows-signed-clock-capture-completion'
state.mkdir(mode=0o700, parents=True, exist_ok=True)
require(state.stat().st_uid == os.getuid() and stat.S_IMODE(state.stat().st_mode) == 0o700, 'private local artifacts')
folder = state / str(uuid.uuid4())
folder.mkdir(mode=0o700)
write(folder / 'SignedClockCaptureCompletion.ps1', complete)
write(folder / 'SignedClockCaptureDelta.ps1', changed)
for action in ('complete', 'read'):
write(folder / ('completion-' + action + '.json'), encoded(dict(id=CASE, profile=COMPLETE_PROFILE,
action=action, script_sha256=sha(complete))))
for action in ('start-local-service', 'start-system', 'read', 'cleanup-local-service', 'cleanup-system'):
write(folder / ('delta-' + action + '.json'), encoded(dict(id=CASE, profile=DELTA_PROFILE,
action=action, exe_sha256=EXE_SHA, exe_bytes=EXE_BYTES,
script_sha256=sha(changed), manifest_sha256=OLD_MANIFEST_SHA)))
manifest = {'original_case': CASE, 'original_controller_sha256': OLD_SCRIPT_SHA,
'original_manifest_sha256': OLD_MANIFEST_SHA, 'actual_repair_reply_sha256': REPAIR_REPLY_SHA,
'actual_repair_preservation_sha256': REPAIR_PRESERVATION_SHA,
'generator_sha256': sha(Path(__file__).read_bytes()),
'completion': {'sha256': sha(complete), 'bytes': len(complete), 'profile': COMPLETE_PROFILE},
'delta': {'sha256': sha(changed), 'bytes': len(changed), 'profile': DELTA_PROFILE},
'exe_sha256': EXE_SHA, 'exe_bytes': EXE_BYTES, 'target_executed': False,
'clock_authority': False, 'calibrated': False}
write(folder / 'manifest.json', encoded(manifest))
print(json.dumps({'path': str(folder), **manifest}, sort_keys=True))
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('command', choices=['prepare'])
parser.parse_args()
prepare()
@@ -0,0 +1,253 @@
#!/usr/bin/env python3
"""Fixed original-case completion/capture operator; no automatic next action.
Each mutation has a create-only local intent. After an uncertain reply use read;
never repeat a mutation or invent its missing reply, exit proof or outcome.
"""
import argparse
import json
from pathlib import Path
import subprocess
import uuid
import signed_clock_capture_acceptance as original
import signed_clock_capture_completion as completion
ROOT = Path(__file__).resolve().parents[2]
FOLDER = ROOT / 'devstate/windows-signed-clock-capture-completion/ccba6d8f-c58f-4d2d-a51c-1efb3bfbabdf'
GENERATOR_SHA = '65dbbd148e4a7d24843167b984c0d3c8ad5a8a065cff7d47dfd5516d9c97cde6'
ORIGINAL_RUNNER_SHA = 'dd6c575a119751429448e40e6f306cf79efa3a86c49bf2cd32a7783937177770'
COMPLETE_SHA = 'a36f318fb549071765bd92aa405c2ea3cf16b3696151afe857c4f601e36f624c'
DELTA_SHA = '2240d7846c82a56e2e13a48bed2c836fae3c836ce89d585c3390540fef76ef14'
ARTIFACTS = (('SignedClockCaptureCompletion.ps1', COMPLETE_SHA, 16673),
('SignedClockCaptureDelta.ps1', DELTA_SHA, 23306))
ACTIONS = ('stage', 'complete', 'read', 'start-local-service', 'start-system',
'cleanup-local-service', 'cleanup-system')
require, save, load = original.require, original.save, original.load
LAUNCH = r'''$ErrorActionPreference='Stop';$p=([Console]::In.ReadLine()|ConvertFrom-Json)
if(!$p-or$p.id-cne'efd17b43-7e04-49a7-9bd4-862d13365eec'){throw 'Fixed original completion case'}
if($p.action-ceq'complete'){
if((($p.PSObject.Properties.Name|Sort-Object)-join',')-cne'action,id,profile,script_sha256'-or$p.profile-cne'rmm.windows.raw-clock.original-completion.v1'-or$p.script_sha256-cne'a36f318fb549071765bd92aa405c2ea3cf16b3696151afe857c4f601e36f624c'){throw 'Fixed completion action'}
$name='SignedClockCaptureCompletion.ps1';$bytes=16673
}else{
if((($p.PSObject.Properties.Name|Sort-Object)-join',')-cne'action,exe_bytes,exe_sha256,id,manifest_sha256,profile,script_sha256'-or$p.action-notin@('read','start-local-service','start-system','cleanup-local-service','cleanup-system')-or$p.profile-cne'rmm.windows.raw-clock.original-delta.v1'-or$p.script_sha256-cne'2240d7846c82a56e2e13a48bed2c836fae3c836ce89d585c3390540fef76ef14'-or$p.exe_sha256-cne'601c27a43fb67c662f926f9dc289a23a5c31c7e27f62901a77fc9ceaafaea7fb'-or$p.exe_bytes-ne8566784-or$p.manifest_sha256-cne'806c062bdd458627cf44ff1ef3f27738e1ebf2f407a96f772223efef267db0b1'){throw 'Fixed delta action'}
$name='SignedClockCaptureDelta.ps1';$bytes=23306
}
$script=Join-Path (Join-Path 'C:\ProgramData\RustDiscoveryBootstrap' $p.script_sha256) $name
$i=Get-Item -LiteralPath $script -Force;if($i.PSIsContainer-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)-or$i.Length-ne$bytes-or(Get-FileHash -LiteralPath $script -Algorithm SHA256).Hash.ToLowerInvariant()-cne$p.script_sha256){throw 'Exact fixed controller bytes'}
$parent=$i.Directory;while($null-ne$parent){if($parent.Attributes-band[IO.FileAttributes]::ReparsePoint){throw 'No controller reparse ancestry'};$parent=$parent.Parent}
$a=Get-Acl -LiteralPath $script;if($a.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Controller owner'};$rules=@($a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if(!$rules.Count){throw 'Nonempty controller DACL'};foreach($r in $rules){if($r.AccessControlType-ne'Allow'-or$r.IdentityReference.Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Private controller DACL'}}
if($p.action-ceq'complete'){$global:RmmCaptureCompletionPayload=$p}else{$global:RmmCaptureDeltaPayload=$p}
& $script
'''
def verify():
require(original.sha(ROOT / 'deploy/windows/signed_clock_capture_acceptance.py') == ORIGINAL_RUNNER_SHA
and original.sha(ROOT / 'deploy/windows/signed_clock_capture_completion.py') == GENERATOR_SHA,
'reviewed original operator and completion generator unchanged')
original.private(FOLDER, True)
manifest = load(FOLDER / 'manifest.json')
require(manifest['original_case'] == completion.CASE and manifest['generator_sha256'] == GENERATOR_SHA
and manifest['original_controller_sha256'] == completion.OLD_SCRIPT_SHA
and manifest['original_manifest_sha256'] == completion.OLD_MANIFEST_SHA
and manifest['completion'] == dict(sha256=COMPLETE_SHA, bytes=16673,
profile=completion.COMPLETE_PROFILE)
and manifest['delta'] == dict(sha256=DELTA_SHA, bytes=23306, profile=completion.DELTA_PROFILE),
'exact reviewed two-controller package')
for name, digest, size in ARTIFACTS:
path = FOLDER / name
original.private(path)
require(path.stat().st_size == size and original.sha(path) == digest, 'original exact controller bytes')
require(original.sha(completion.ORIGINAL / 'manifest.json') == completion.OLD_MANIFEST_SHA
and original.sha(completion.ORIGINAL / 'SignedClockCaptureAcceptance.ps1') == completion.OLD_SCRIPT_SHA
and original.sha(completion.REPAIR / 'repair-reply.json') == completion.REPAIR_REPLY_SHA
and original.sha(completion.REPAIR / 'repair-preservation.json') == completion.REPAIR_PRESERVATION_SHA,
'original failed setup and actual successful stopped SYSTEM repair')
def payload(action):
require(action in ACTIONS and action != 'stage', 'fixed code-selected controller action')
if action == 'complete':
return dict(id=completion.CASE, profile=completion.COMPLETE_PROFILE,
action=action, script_sha256=COMPLETE_SHA)
return dict(id=completion.CASE, profile=completion.DELTA_PROFILE, action=action,
exe_sha256=completion.EXE_SHA, exe_bytes=completion.EXE_BYTES,
manifest_sha256=completion.OLD_MANIFEST_SHA, script_sha256=DELTA_SHA)
def stage(access):
for name, digest, _ in ARTIFACTS:
require(name in ('SignedClockCaptureCompletion.ps1', 'SignedClockCaptureDelta.ps1'),
'only literal two new stage names')
prepare = original.pipe.u.transport.PREPARE_SCRIPT.replace('TransportAcceptance.ps1', name)
observed = access.powershell(prepare, dict(sha256=digest))
if not observed['already_uploaded']:
credentials = original.pipe.cb.contract.protected_json(access.root / 'credentials/windows-dev-access.json')
prefix = credentials['ssh_prefix']
args = ['sftp'] + [part for part in prefix[1:-1] if part != '-T'] + ['-b', '-', prefix[-1]]
target = '/C:/ProgramData/RustDiscoveryBootstrap/' + digest + '/' + name
transferred = subprocess.run(args, input=('put ' + json.dumps(str(FOLDER / name)) + ' '
+ json.dumps(target) + '\n').encode(), capture_output=True, timeout=60)
require(transferred.returncode == 0, 'one exact transfer; uncertain reply means original read only')
observed = access.powershell(prepare, dict(sha256=digest))
require(observed['already_uploaded'] is True and observed['sha256'] == digest,
'immutable staged exact controller')
return dict(staged=True, original_case=completion.CASE,
completion_sha256=COMPLETE_SHA, delta_sha256=DELTA_SHA)
def linked_receipt(path, action):
receipt = load(path)
ident = receipt['operation_id']
if action == 'read':
require(ident.startswith('read-') and str(uuid.UUID(ident[5:])) == ident[5:]
and uuid.UUID(ident[5:]).version == 4, 'canonical unique actual read operation')
else:
require(ident == action, 'exact once-only actual mutation operation')
require(path.parent == FOLDER and path.name == ident + '-receipt.json'
and receipt['original_case'] == completion.CASE and receipt['action'] == action
and receipt['read_only'] is (action == 'read')
and receipt['operator_sha256'] == original.sha(Path(__file__))
and receipt['completion_sha256'] == COMPLETE_SHA and receipt['delta_sha256'] == DELTA_SHA
and receipt['calibrated'] is False and receipt['clock_authority'] is False,
'same original operation/action/operator/controller receipt')
raw = receipt['raw_reply']
require(set(raw) == {'filename', 'sha256'} and raw['filename'] == ident + '-reply.json'
and original.sha(FOLDER / raw['filename']) == raw['sha256'], 'exact original operation raw reply')
binding = {key: receipt[key] for key in ('original_case', 'action', 'read_only', 'operation_id',
'raw_reply', 'operator_sha256', 'completion_sha256', 'delta_sha256')}
witnesses = {}
for field, suffix in (('server_witness', '-server.json'), ('native_witness', '-native.json'),
('preservation', '-preservation.json')):
link = receipt[field]
require(set(link) == {'filename', 'sha256'} and link['filename'] == ident + suffix
and original.sha(FOLDER / link['filename']) == link['sha256'],
'same separately saved operation witness link')
witness = load(FOLDER / link['filename'])
require(all(witness[key] == value for key, value in binding.items()),
'all witness metadata bind same operation/action/read-only/raw reply')
witnesses[field] = witness
server, native, preservation = (witnesses[key] for key in ('server_witness', 'native_witness', 'preservation'))
require(preservation['server_witness'] == receipt['server_witness']
and preservation['native_witness'] == receipt['native_witness']
and server['before'] == server['after'] == preservation['server']
and native['after'] == preservation['native'] and preservation['no_rmm_jobs'] is True
and preservation['calibrated'] is False and preservation['clock_authority'] is False,
'actual complete linked server/native preservation format')
original.preserved(native['before'], native['after'])
return load(FOLDER / raw['filename'])
def completion_proof():
reply = linked_receipt(FOLDER / 'complete-receipt.json', 'complete')
require(reply.get('id') == completion.CASE and reply.get('setup_repair_completed') is True
and reply.get('original_setup_replayed') is False and reply.get('service_actions') is False
and reply.get('calibrated') is False and reply.get('clock_authority') is False,
'actual completed original-case reply; never synthesize missing replies or proof')
def positive_local_service():
# A fresh linked read may establish an actual saved outcome after a lost
# reply. Never manufacture the missing start reply, process proof or exit.
candidates = [FOLDER / 'start-local-service-receipt.json']
candidates += sorted(FOLDER.glob('read-*-receipt.json'), key=lambda path: path.name)
for path in candidates:
if not path.exists():
continue
response = linked_receipt(path, 'start-local-service' if path.name.startswith('start-') else 'read')
value = response.get('roles', {}).get('local-service')
if value is None or value['markers']['outcome'] is None:
continue
original.validate_role('local-service', value, completion.CASE)
return
raise RuntimeError('actual successful LocalService capture and exact kernel exit required before SYSTEM start')
def witnesses(access, baseline):
server, native = original.server_closed(access), original.native_witness(access)
require(server == baseline['server'], 'original closed server counters and policy unchanged')
original.preserved(baseline['native'], native)
return server, native
def run(action):
verify()
access = original.CaptureAccess(original.ACCESS_ROOT)
baseline = load(completion.ORIGINAL / 'baseline.json')
before_server, before_native = witnesses(access, baseline)
ident = 'read-' + str(uuid.uuid4()) if action == 'read' else action
if action != 'read':
if action != 'stage':
staged = load(FOLDER / 'stage-reply.json')
require(staged == dict(staged=True, original_case=completion.CASE,
completion_sha256=COMPLETE_SHA, delta_sha256=DELTA_SHA), 'one completed original stage')
if action in ('start-local-service', 'start-system', 'cleanup-local-service', 'cleanup-system'):
completion_proof()
if action.startswith('start-'):
require(not any(FOLDER.glob('cleanup-*-attempt.json')), 'cleanup began; no new starts')
if action == 'start-system':
positive_local_service()
require(not (FOLDER / (action + '-reply.json')).exists(), 'no completed mutation replay')
save(FOLDER / (action + '-attempt.json'), dict(original_case=completion.CASE, action=action,
once=True, no_retry=True, operator_sha256=original.sha(Path(__file__)),
completion_sha256=COMPLETE_SHA, delta_sha256=DELTA_SHA))
else:
save(FOLDER / (ident + '-intent.json'), dict(original_case=completion.CASE, read_only=True,
operator_sha256=original.sha(Path(__file__)), controller_sha256=DELTA_SHA))
response = stage(access) if action == 'stage' else access.powershell(LAUNCH, payload(action), timeout=90)
raw_path = FOLDER / (ident + '-reply.json')
save(raw_path, response) # Preserve exact canonical raw response before validation or witnesses.
raw_link = dict(filename=raw_path.name, sha256=original.sha(raw_path))
binding = dict(original_case=completion.CASE, action=action, read_only=action == 'read',
operation_id=ident, raw_reply=raw_link, operator_sha256=original.sha(Path(__file__)),
completion_sha256=COMPLETE_SHA, delta_sha256=DELTA_SHA)
after_server, after_native = witnesses(access, baseline)
require(before_server == after_server, 'server preserved throughout action')
original.preserved(before_native, after_native)
server_path, native_path = FOLDER / (ident + '-server.json'), FOLDER / (ident + '-native.json')
save(server_path, dict(binding, before=before_server, after=after_server))
save(native_path, dict(binding, before=before_native, after=after_native))
server_link = dict(filename=server_path.name, sha256=original.sha(server_path))
native_link = dict(filename=native_path.name, sha256=original.sha(native_path))
preservation_path = FOLDER / (ident + '-preservation.json')
save(preservation_path, dict(binding, server=after_server, native=after_native,
server_witness=server_link, native_witness=native_link,
no_rmm_jobs=True, calibrated=False, clock_authority=False))
# No success/complete-role assertion is made before both linked witnesses.
completed = []
if action == 'complete':
require(response.get('id') == completion.CASE and response.get('setup_repair_completed') is True
and response.get('original_setup_replayed') is False and response.get('service_actions') is False,
'only own setup completion; no service action')
if action not in ('stage', 'complete'):
require(response.get('id') == completion.CASE and response.get('calibrated') is False
and response.get('clock_authority') is False, 'same non-authoritative original case response')
if action == 'read':
require(response.get('read_only') is True, 'actual delta read only')
for role, value in response.get('roles', {}).items():
require(role in ('local-service', 'system'), 'fixed own two roles')
if value['markers']['outcome'] is not None:
original.validate_role(role, value, completion.CASE)
completed.append(role)
if action.startswith('start-'):
require(action.removeprefix('start-') in completed, 'actual successful own capture, exact kernel exit')
if action.startswith('cleanup-'):
role = action.removeprefix('cleanup-')
value = response['roles'][role]
require(value['service'] is None and value['markers']['deleted']['service_absent'] is True,
'actual original stopped fixture removal')
receipt_path = FOLDER / (ident + '-receipt.json')
save(receipt_path, dict(binding, server_witness=server_link, native_witness=native_link,
preservation=dict(filename=preservation_path.name, sha256=original.sha(preservation_path)),
completed_roles=sorted(completed), calibrated=False, clock_authority=False))
print(json.dumps(dict(action=action, original_case=completion.CASE,
completed_roles=sorted(completed), receipt_filename=receipt_path.name,
receipt_sha256=original.sha(receipt_path), read_only=action == 'read')))
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('action', choices=ACTIONS)
run(parser.parse_args().action)