#!/usr/bin/env python3 """Fixed two-role raw Windows clock bootstrap; never an RMM job or calibration. prepare is local only. Every mutation is create-once. After a lost reply use read on the original case; cleanup is separately explicit and stopped-only. """ import argparse import base64 import hashlib import json import os from pathlib import Path import stat import subprocess import uuid import system_pipe_upgrade as pipe ROOT = Path(__file__).resolve().parents[2] ACCESS_ROOT = ROOT.parent / 'rust-discovery' STATE = ROOT / 'devstate/windows-signed-clock-capture-native' QUALIFICATION = ROOT / 'devstate/windows-signed-clock/raw-capture-qualification-6bcd72a7-6de7-48e6-9e9b-3ad2cd3d9b09' RECEIPT_SHA = 'ba9ba8d88ed71952dd8dc803f2e38d5da72edeae392818cd320c6fd532ac7f4d' INPUTS_SHA = '2d21da4d137d2efd48cb2679fb791a9055839b042373d0f38c5af8d9ea8c5a8c' CAP_SHA = '91c75ba877764345b3267731f3880580d02a72df40420479e3c4b76d37064982' EXE_SHA = '601c27a43fb67c662f926f9dc289a23a5c31c7e27f62901a77fc9ceaafaea7fb' EXE_BYTES = 8566784 NATIVE_CASE = ROOT / 'devstate/windows-raw-clock-native-linux/dcef489d-2a24-47cc-b3ca-6628545cdacf' LINUX_READ = NATIVE_CASE / 'read-80f83bff-183b-4697-80b2-9b96a8182e8d.json' LINUX_READ_SHA = '91a750e4de266f5effccbd418a680c1ba4f5e0aff5082489fc021922bdfcafa3' MAIN_CASE = ACCESS_ROOT / 'devstate/windows-client/system-pipe-upgrade/14fb176a-f653-4573-a8d7-6f9fe47a3020' MAIN_INTENT_SHA = '374adc97bec41bd798409f7c4f8c7716b085e20d2b6fb64b33f7ab675e6483e2' MAIN_RESULT_SHA = 'd5c4996821911a5bdac5014e9f985c56bbb592b803f2e33411dd28bb986b8eed' INDEX_SHAS = {'current-runtime.json': 'e49231e72aff7b001189b8507200c6c701f73e47f77c29194116cf1da41ca0c2', 'current-components.json': '005317e652f50de3e1277be3bc42717318226208015e7c8011e1b73469cc7562'} ROOT_POLICY = 'cf15cbb68b590475df6def28e7dcffb7d88e0ca2d2555a06174fb654eeff05f4' PROFILE = 'rmm.windows.raw-clock.two-role-bootstrap.v1' STABLE = ('files', 'service', 'helper_service', 'agent_kernel', 'helper_kernel', 'helper_witness') JOURNAL = ('database_file_id', 'database_creation', 'identity_sha256', 'schema', 'core_counts') require = pipe.require def sha(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest() def canonical(value): return json.dumps(value, ensure_ascii=True, separators=(',', ':'), sort_keys=True).encode() def private(path, directory=False): metadata = Path(path).lstat() require(metadata.st_uid == os.getuid() and stat.S_IMODE(metadata.st_mode) == (0o700 if directory else 0o600) and (stat.S_ISDIR(metadata.st_mode) if directory else stat.S_ISREG(metadata.st_mode) and metadata.st_nlink == 1), 'private own case') def load(path): private(path) require(Path(path).stat().st_size <= 2 * 1024 * 1024, 'bounded private evidence') return json.loads(Path(path).read_bytes(), object_pairs_hook=pipe.cb.contract.strict_object) def write(path, raw): private(path.parent, True) fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_WRONLY, 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 save(path, value): write(path, canonical(value)) # Exact previously reviewed kernel-handle/account/image proof only. No original # replacement, stop/start, state or recovery functions are imported into SCRIPT. NATIVE_BASE = pipe.NATIVE.split("'@\nfunction FileIdentity", 1)[0] NATIVE = NATIVE_BASE + r''' public static class RmmCaptureControl { [DllImport("advapi32.dll",SetLastError=true,CharSet=CharSet.Unicode)] static extern IntPtr OpenSCManager(string machine,string database,uint access); [DllImport("advapi32.dll",SetLastError=true,CharSet=CharSet.Unicode)] static extern IntPtr CreateService(IntPtr manager,string name,string display,uint access,uint type,uint start,uint error,string command,string group,IntPtr tag,string dependencies,string account,string password); [DllImport("advapi32.dll",SetLastError=true,CharSet=CharSet.Unicode)] static extern IntPtr OpenService(IntPtr manager,string name,uint access); [DllImport("advapi32.dll",SetLastError=true)] static extern bool CloseServiceHandle(IntPtr handle); [DllImport("advapi32.dll",SetLastError=true)] static extern bool ChangeServiceConfig2(IntPtr handle,uint level,ref uint value); [DllImport("advapi32.dll",SetLastError=true)] static extern bool StartService(IntPtr handle,uint count,IntPtr args); [DllImport("advapi32.dll",SetLastError=true)] static extern bool DeleteService(IntPtr handle); [DllImport("advapi32.dll",SetLastError=true)] static extern bool QueryServiceStatusEx(IntPtr handle,int level,out Status value,int size,out int needed); [DllImport("advapi32.dll",SetLastError=true)] static extern bool SetServiceObjectSecurity(IntPtr handle,uint info,IntPtr descriptor); [DllImport("advapi32.dll",SetLastError=true,CharSet=CharSet.Unicode)] static extern bool ConvertStringSecurityDescriptorToSecurityDescriptor(string text,uint revision,out IntPtr descriptor,out uint size); [DllImport("kernel32.dll")] static extern IntPtr LocalFree(IntPtr value); [DllImport("kernel32.dll",SetLastError=true)] static extern IntPtr OpenProcess(uint access,bool inherit,int pid); [DllImport("kernel32.dll",SetLastError=true)] static extern bool TerminateProcess(RmmPipeNative.Held handle,uint code); [DllImport("kernel32.dll",SetLastError=true)] static extern bool GetExitCodeProcess(RmmPipeNative.Held handle,out uint code); [DllImport("kernel32.dll")] public static extern ulong GetTickCount64(); [StructLayout(LayoutKind.Sequential)] public struct Status {public uint Type,State,Controls,Win32Exit,SpecificExit,Checkpoint,WaitHint,Pid,Flags;} public sealed class Service : SafeHandleZeroOrMinusOneIsInvalid { public Service(IntPtr value):base(true){SetHandle(value);} protected override bool ReleaseHandle(){return CloseServiceHandle(handle);} public Status Read(){Status s;int bytes;if(!QueryServiceStatusEx(handle,0,out s,Marshal.SizeOf(typeof(Status)),out bytes)||bytes!=Marshal.SizeOf(typeof(Status)))throw new Win32Exception();return s;} public void StartOnce(){if(!StartService(handle,0,IntPtr.Zero))throw new Win32Exception();} public void DeleteOnce(){if(!DeleteService(handle))throw new Win32Exception();} } static IntPtr Manager(uint access){IntPtr value=OpenSCManager(null,null,access);if(value==IntPtr.Zero)throw new Win32Exception();return value;} public static Service CreateOnce(string name,string command,string account){ IntPtr manager=Manager(3);try{IntPtr value=CreateService(manager,name,name,0xf01ff,16,3,1,command,null,IntPtr.Zero,null,account,null);if(value==IntPtr.Zero)throw new Win32Exception(); Service service=new Service(value);try{uint sid=1;if(!ChangeServiceConfig2(value,5,ref sid))throw new Win32Exception();IntPtr sd;uint size;if(!ConvertStringSecurityDescriptorToSecurityDescriptor("D:P(A;;GA;;;SY)(A;;GA;;;BA)",1,out sd,out size))throw new Win32Exception();try{if(!SetServiceObjectSecurity(value,4,sd))throw new Win32Exception();}finally{LocalFree(sd);}return service;}catch{service.Dispose();throw;} }finally{CloseServiceHandle(manager);} } public static Service OpenOwn(string name){IntPtr manager=Manager(1);try{IntPtr value=OpenService(manager,name,0x10015);if(value==IntPtr.Zero)throw new Win32Exception();return new Service(value);}finally{CloseServiceHandle(manager);}} public static RmmPipeNative.Held Hold(int pid){IntPtr value=OpenProcess(0x101001,false,pid);if(value==IntPtr.Zero)throw new Win32Exception();return new RmmPipeNative.Held(value);} public static void KillHeld(RmmPipeNative.Held process){if(!TerminateProcess(process,1460))throw new Win32Exception();} public static uint Exit(RmmPipeNative.Held process){uint code;if(!GetExitCodeProcess(process,out code))throw new Win32Exception();return code;} } '@ ''' SCRIPT = r''' $ErrorActionPreference='Stop';$p=$global:RmmSignedClockCapturePayload if(!$p-or[guid]::ParseExact($p.id,'D').ToString()-cne$p.id-or$p.id-notmatch'^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$'-or$p.profile-cne'rmm.windows.raw-clock.two-role-bootstrap.v1'-or$p.action-notin@('setup','start-local-service','start-system','read','cleanup-local-service','cleanup-system')-or$p.exe_sha256-cne'601c27a43fb67c662f926f9dc289a23a5c31c7e27f62901a77fc9ceaafaea7fb'-or$p.exe_bytes-ne8566784-or$p.script_sha256-notmatch'^[a-f0-9]{64}$'-or$p.manifest_sha256-notmatch'^[a-f0-9]{64}$'){throw 'Fixed capture request'} if((($p.PSObject.Properties.Name|Sort-Object)-join',')-cne'action,exe_bytes,exe_sha256,id,manifest_sha256,profile,script_sha256'){throw 'Exact capture payload fields'} $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');$owners=@('S-1-5-19','S-1-5-18');$accounts=@('NT AUTHORITY\LocalService','LocalSystem');$sys='S-1-5-18';$admin='S-1-5-32-544' function HashBytes([byte[]]$raw){$h=[Security.Cryptography.SHA256]::Create();try{return([BitConverter]::ToString($h.ComputeHash($raw))).Replace('-','').ToLowerInvariant()}finally{$h.Dispose()}} function HashFile($path){return(Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant()} function Check($path,[bool]$dir,[string[]]$readers=@(),[string[]]$writers=@()){ $i=Get-Item -LiteralPath $path -Force;if($i.PSIsContainer-ne$dir-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Regular fixed fixture'};$parent=$i.Parent;if(!$dir){$parent=$i.Directory};while($null-ne$parent){if($parent.Attributes-band[IO.FileAttributes]::ReparsePoint){throw 'Reparse ancestor'};$parent=$parent.Parent} $a=Get-Acl -LiteralPath $path;if(($a.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@($sys,$admin)-and!(!$dir-and$writers.Count-gt0-and$sids-and$writers[0]-ceq$sids[0]-and$a.GetOwner([Security.Principal.SecurityIdentifier]).Value-ceq'S-1-5-19'))-or($dir-and!$a.AreAccessRulesProtected)){throw 'Fixture owner/protection'} $rules=@($a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if(!$rules.Count){throw 'Empty fixture DACL'} foreach($r in $rules){$sid=$r.IdentityReference.Value;$rights=[int64]$r.FileSystemRights;if($r.AccessControlType-ne'Allow'-or($r.PropagationFlags-band[Security.AccessControl.PropagationFlags]::InheritOnly)){throw 'Fixture ACE'};if($sid-in@($sys,$admin)){if($rights-ne2032127){throw 'Trusted fixture rights'}}elseif($sid-in$writers){if($rights-ne2032127){throw 'Own role rights'}}elseif($sid-in$readers){if($rights-ne131241-and$rights-ne1179817){throw 'Reader rights'}}else{throw 'Foreign fixture ACE'}} } function NewDir($path,[string[]]$readers=@(),[string[]]$writers=@()){ if(Test-Path -LiteralPath $path){throw 'Create-only fixture directory'};$a=New-Object Security.AccessControl.DirectorySecurity;$a.SetAccessRuleProtection($true,$false);$a.SetOwner((New-Object Security.Principal.SecurityIdentifier($admin))) foreach($sid in @($sys,$admin)+$writers){$a.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule((New-Object Security.Principal.SecurityIdentifier($sid)),'FullControl','ContainerInherit,ObjectInherit','None','Allow')))} foreach($sid in @($readers|Where-Object{$_-notin$writers})){$a.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule((New-Object Security.Principal.SecurityIdentifier($sid)),'ReadAndExecute','ContainerInherit,ObjectInherit','None','Allow')))} [IO.Directory]::CreateDirectory($path,$a)|Out-Null;Check $path $true $readers $writers } function WriteNew($path,$value){$raw=[Text.Encoding]::ASCII.GetBytes(($value|ConvertTo-Json -Depth 24 -Compress));if($raw.Length-gt65536){throw 'Bounded own controller record'};$f=[IO.File]::Open($path,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::Read);try{$f.Write($raw,0,$raw.Length);$f.Flush($true)}finally{$f.Dispose()};$a=New-Object Security.AccessControl.FileSecurity;$a.SetSecurityDescriptorSddlForm('O:BAG:BAD:P(A;;FA;;;SY)(A;;FA;;;BA)');Set-Acl -LiteralPath $path -AclObject $a} function ReadJson($path,[string[]]$readers=@(),[string[]]$writers=@(),[int]$limit=65536){Check $path $false $readers $writers;if((Get-Item -LiteralPath $path).Length-gt$limit){throw 'Bounded own JSON'};return([IO.File]::ReadAllText($path,[Text.Encoding]::UTF8)|ConvertFrom-Json)} function Command([int]$n){return('"'+$exe+'" --service '+$p.id+' '+$tags[$n])} function Service([int]$n){ $s=Get-CimInstance Win32_Service -Filter ("Name='"+$names[$n]+"'") -OperationTimeoutSec 5;if(!$s){return $null} if($s.PathName-cne(Command $n)-or$s.StartMode-cne'Manual'-or$s.ServiceType-cne'Own Process'-or$s.StartName-cne$accounts[$n]-or@((Get-Service -Name $names[$n]).ServicesDependedOn).Count-ne0){throw 'Exact own fixture SCM configuration'} if((Get-ItemPropertyValue -LiteralPath ('HKLM:\SYSTEM\CurrentControlSet\Services\'+$names[$n]) -Name ServiceSidType)-ne1){throw 'Own service SID type'} $text=(@(& 'C:\Windows\System32\sc.exe' sdshow $names[$n])-join"`n").Trim();if($LASTEXITCODE-ne0-or!$text-or$text.Length-gt8192){throw 'Bounded own SCM DACL'} $security=New-Object Security.AccessControl.RawSecurityDescriptor($text);if(!$security.DiscretionaryAcl-or!($security.ControlFlags-band[Security.AccessControl.ControlFlags]::DiscretionaryAclProtected)){throw 'Protected own SCM DACL'} foreach($ace in $security.DiscretionaryAcl){if($ace.AceQualifier-ne'AccessAllowed'-or$ace.SecurityIdentifier.Value-notin@($sys,$admin)){throw 'Own service controllers only'}} return [ordered]@{command=$s.PathName;account=$s.StartName;start=$s.StartMode;type=$s.ServiceType;sid_type=1;acl_sha256=(HashBytes ([Text.Encoding]::ASCII.GetBytes($text)))} } function Equal($a,$b){return(($a|ConvertTo-Json -Depth 24 -Compress)-ceq($b|ConvertTo-Json -Depth 24 -Compress))} function Original([int]$n){$made=ReadJson (Join-Path $control ($tags[$n]+'-created.json'));$s=Service $n;if(!$s-or!(Equal $s $made.service)){throw 'Same original fixture definition'};return $s} function ReadAll{ $roles=[ordered]@{};for($n=0;$n-lt2;$n++){$output=Join-Path $case $tags[$n];Check $output $true $sids @($sids[$n]);$reports=[ordered]@{};foreach($leaf in @('intent','report','end')){$path=Join-Path $output ($leaf+'.json');$reports[$leaf]=$null;if(Test-Path -LiteralPath $path){$reports[$leaf]=ReadJson $path $sids @($sids[$n]) 16384}};$s=Service $n;$status=$null;if($s){$h=[RmmCaptureControl]::OpenOwn($names[$n]);try{$status=$h.Read()}finally{$h.Dispose()}};$markers=[ordered]@{};foreach($leaf in @('created','start-attempt','process','timeout-attempt','exit','outcome','delete-attempt','deleted')){$path=Join-Path $control ($tags[$n]+'-'+$leaf+'.json');$markers[$leaf]=$null;if(Test-Path -LiteralPath $path){$markers[$leaf]=ReadJson $path}};$reportHash=$null;if($null-ne$reports.report){$reportHash=HashFile (Join-Path $output 'report.json')};$roles[$tags[$n]]=@{service=$s;status=$status;markers=$markers;reports=$reports;raw_report_sha256=$reportHash}} return @{id=$p.id;read_only=($p.action-ceq'read');roles=$roles;calibrated=$false;clock_authority=$false;no_rmm_jobs=$true} } '''+NATIVE+r''' if($PSCommandPath-cne(Join-Path (Join-Path $boot $p.script_sha256) 'SignedClockCaptureAcceptance.ps1')-or(HashFile $PSCommandPath)-cne$p.script_sha256){throw 'Actual exact executing controller'} if($p.action-ceq'read'-and!(Test-Path -LiteralPath $case)){@{id=$p.id;read_only=$true;remote_case_absent=$true}|ConvertTo-Json -Compress;exit 0} if($p.action-ceq'setup'){ if((Test-Path -LiteralPath $base)-or(Service 0)-or(Service 1)){throw 'Existing capture namespace: original read only'} NewDir $base;NewDir $case;NewDir $control;WriteNew (Join-Path $control 'intent.json') $p;WriteNew (Join-Path $base 'active.json') @{id=$p.id;manifest_sha256=$p.manifest_sha256;script_sha256=$p.script_sha256;no_retry=$true} for($n=0;$n-lt2;$n++){WriteNew (Join-Path $control ($tags[$n]+'-create-attempt.json')) @{create_once=$true;command=(Command $n)};$account=$accounts[$n];if($n-eq1){$account=$null};$h=[RmmCaptureControl]::CreateOnce($names[$n],(Command $n),$account);$h.Dispose();WriteNew (Join-Path $control ($tags[$n]+'-created.json')) @{service=(Service $n);create_once=$true}} $sids=@();foreach($name in $names){$sids+=((New-Object Security.Principal.NTAccount('NT SERVICE',$name)).Translate([Security.Principal.SecurityIdentifier]).Value)} # Set exact explicit reader ACLs before putting any executable in this case. 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])} $staged=Join-Path (Join-Path $boot $p.exe_sha256) 'SignedClockCapture.exe';if((Get-Item -LiteralPath $staged).Length-ne8566784-or(HashFile $staged)-cne$p.exe_sha256){throw 'Exact staged probe'} [IO.File]::Copy($staged,$exe,$false);$ea=New-Object Security.AccessControl.FileSecurity;$ea.SetAccessRuleProtection($true,$false);$ea.SetOwner((New-Object Security.Principal.SecurityIdentifier($admin)));foreach($sid in @($sys,$admin)){$ea.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule((New-Object Security.Principal.SecurityIdentifier($sid)),'FullControl','Allow')))};foreach($sid in $sids){$ea.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule((New-Object Security.Principal.SecurityIdentifier($sid)),'ReadAndExecute','Allow')))};Set-Acl -LiteralPath $exe -AclObject $ea;$f=[IO.File]::Open($exe,'Open','ReadWrite','Read');try{$f.Flush($true)}finally{$f.Dispose()};Check $exe $false $sids;if((HashFile $exe)-cne$p.exe_sha256){throw 'Exact own probe copy'} WriteNew (Join-Path $control 'setup-complete.json') @{id=$p.id;roles=$sids;exe_sha256=$p.exe_sha256};@{id=$p.id;setup=$true;calibrated=$false;clock_authority=$false}|ConvertTo-Json -Compress;exit 0 } if($p.action-ceq'read'-and!(Test-Path -LiteralPath (Join-Path $control 'setup-complete.json'))){$raw=@();foreach($name in $names){$v=Get-CimInstance Win32_Service -Filter ("Name='"+$name+"'") -OperationTimeoutSec 5;$raw+=@{name=$name;present=[bool]$v;state=$(if($v){$v.State}else{$null});pid=$(if($v){[uint32]$v.ProcessId}else{0});definition_unverified=$true}};@{id=$p.id;read_only=$true;partial_setup=$true;own_services=$raw;calibrated=$false;clock_authority=$false}|ConvertTo-Json -Depth 8 -Compress;exit 0} $setup=ReadJson (Join-Path $control 'setup-complete.json');$sids=@($setup.roles);if($sids.Count-ne2-or@($sids|Where-Object{$_-notmatch'^S-1-5-80(-[0-9]+){5}$'}).Count-ne0-or$sids[0]-ceq$sids[1]){throw 'Original two fixture SIDs'} Check $base $true $sids;Check $case $true $sids;Check $control $true $i=ReadJson (Join-Path $control 'intent.json');foreach($field in @('id','profile','exe_sha256','exe_bytes','script_sha256','manifest_sha256')){if($i.$field-cne$p.$field){throw 'Original exact capture intent'}} $a=ReadJson (Join-Path $base 'active.json') $sids;if($a.id-cne$p.id-or$a.manifest_sha256-cne$p.manifest_sha256-or$a.script_sha256-cne$p.script_sha256){throw 'Same active capture case'} Check $exe $false $sids;if((Get-Item -LiteralPath $exe).Length-ne8566784-or(HashFile $exe)-cne$p.exe_sha256){throw 'Original immutable probe'} if($p.action-ceq'read'){ReadAll|ConvertTo-Json -Depth 32 -Compress;exit 0} $n=0;if($p.action-in@('start-system','cleanup-system')){$n=1};$tag=$tags[$n];$output=Join-Path $case $tag $null=Original $n if($p.action-in@('start-local-service','start-system')){ if((Test-Path -LiteralPath (Join-Path $control 'local-service-delete-attempt.json'))-or(Test-Path -LiteralPath (Join-Path $control 'system-delete-attempt.json'))){throw 'Campaign cleanup began; no further starts'} if(Test-Path -LiteralPath (Join-Path $control ($tag+'-start-attempt.json'))){throw 'Start already attempted; read only'} if($n-eq1){$first=ReadJson (Join-Path $control 'local-service-outcome.json');if($first.success-ne$true){throw 'LocalService must complete first'}} $h=[RmmCaptureControl]::OpenOwn($names[$n]);$process=$null;$proof=$null;$timed=$false;$start=[RmmCaptureControl]::GetTickCount64() try{ if($h.Read().State-ne1){throw 'Own service initially stopped'} WriteNew (Join-Path $control ($tag+'-start-attempt.json')) @{start_once=$true;service=(Original $n)} $h.StartOnce() do{ $state=$h.Read() if($state.Pid-gt0-and$null-eq$process){$process=[RmmCaptureControl]::Hold([int]$state.Pid);$proof=[RmmPipeNative]::Proof($process,[int]$state.Pid,$owners[$n],$sids[$n],$exe);$cli=(Get-CimInstance Win32_Process -Filter ('ProcessId='+$state.Pid) -OperationTimeoutSec 5).CommandLine;if($cli-cne(Command $n)-or![RmmPipeNative]::Alive($process)-or$h.Read().Pid-ne$state.Pid){throw 'Exact own process CLI/generation'};WriteNew (Join-Path $control ($tag+'-process.json')) @{proof=$proof;command=$cli;image_sha256=$p.exe_sha256}} if($state.State-eq1){break} if([RmmCaptureControl]::GetTickCount64()-$start-ge40000){$timed=$true;break} if($null-ne$process){$null=[RmmPipeNative]::Exited($process,25)}else{Start-Sleep -Milliseconds 10} }while($true) if($timed){if($null-eq$process-or$null-eq$proof){throw 'Timeout without held process; manual original read only'};$fresh=[RmmPipeNative]::Proof($process,[int]$proof.pid,$owners[$n],$sids[$n],$exe);if($fresh.creation_filetime-cne$proof.creation_filetime-or$h.Read().Pid-ne$proof.pid-or(Original $n).command-cne(Command $n)){throw 'Timeout target changed; no termination'};$cli=(Get-CimInstance Win32_Process -Filter ('ProcessId='+$proof.pid) -OperationTimeoutSec 5).CommandLine;if($cli-cne(Command $n)){throw 'Timeout CLI changed'};WriteNew (Join-Path $control ($tag+'-timeout-attempt.json')) @{proof=$proof;terminate_own_handle_once=$true};[RmmCaptureControl]::KillHeld($process)} if($null-eq$process-or![RmmPipeNative]::Exited($process,5000)){throw 'Own process exit not bound'} $exit=[RmmCaptureControl]::Exit($process);$state=$h.Read();if($state.State-ne1){throw 'Own SCM stop not observed'};WriteNew (Join-Path $control ($tag+'-exit.json')) @{process=$proof;kernel_process_exited=$true;exit_code=$exit;timed_out=$timed;scm_exit=$state.Win32Exit;scm_specific_exit=$state.SpecificExit} $report=ReadJson (Join-Path $output 'report.json') $sids @($sids[$n]) 16384;$end=ReadJson (Join-Path $output 'end.json') $sids @($sids[$n]) 16384;$intent=ReadJson (Join-Path $output 'intent.json') $sids @($sids[$n]) 16384 if($timed-or$exit-ne0-or$state.Win32Exit-ne0-or$state.SpecificExit-ne0-or$end.success-ne$true-or$report.pid-ne$proof.pid-or[string]$report.process_birth_filetime-cne$proof.creation_filetime-or$report.image_sha256-cne$p.exe_sha256-or$report.role-cne$tag-or$report.case_id-cne$p.id-or$intent.pid-ne$report.pid-or$intent.process_birth_filetime-ne$report.process_birth_filetime-or$end.case_id-cne$p.id-or$end.role-cne$tag-or$report.calibrated-ne$false-or$report.clock_authority-ne$false-or$report.capture.calibrated-ne$false-or$report.capture.clock_authority-ne$false-or$report.capture.sample_count-ne128-or@($report.capture.samples_100ns).Count-ne128-or$report.capture.elapsed_monotonic_ns-gt250000000-or$report.capture.elapsed_interrupt_ns-gt250000000-or$end.report_sha256-cne(HashFile (Join-Path $output 'report.json'))){throw 'Exact noncalibrating report/end/exit proof'} WriteNew (Join-Path $control ($tag+'-outcome.json')) @{success=$true;exit_code=$exit;process=$proof;scm_exit=$state.Win32Exit;scm_specific_exit=$state.SpecificExit;report_sha256=$end.report_sha256;calibrated=$false;clock_authority=$false} }finally{if($null-ne$process){$process.Dispose()};$h.Dispose()} ReadAll|ConvertTo-Json -Depth 32 -Compress;exit 0 } if($p.action-in@('cleanup-local-service','cleanup-system')){ if(Test-Path -LiteralPath (Join-Path $control ($tag+'-delete-attempt.json'))){throw 'Delete already attempted; read only'} if(Test-Path -LiteralPath (Join-Path $control ($tag+'-start-attempt.json'))){$exited=ReadJson (Join-Path $control ($tag+'-exit.json'));$originalProcess=ReadJson (Join-Path $control ($tag+'-process.json'));if($exited.kernel_process_exited-ne$true-or!(Equal $exited.process $originalProcess.proof)){throw 'Original started process exit not durably observed'}} $h=[RmmCaptureControl]::OpenOwn($names[$n]);try{if($h.Read().State-ne1){throw 'Cleanup only stopped original service'};$null=Original $n;WriteNew (Join-Path $control ($tag+'-delete-attempt.json')) @{delete_once=$true;service=(Original $n)};$h.DeleteOnce()}finally{$h.Dispose()} if(Service $n){throw 'Service absence not observed; read only'};WriteNew (Join-Path $control ($tag+'-deleted.json')) @{deleted=$true;service_absent=$true;id=$p.id} ReadAll|ConvertTo-Json -Depth 32 -Compress;exit 0 } throw 'Fixed capture phase only' ''' LAUNCH = r'''$ErrorActionPreference='Stop';$p=([Console]::In.ReadLine()|ConvertFrom-Json) if($p.script_sha256-notmatch'^[a-f0-9]{64}$'-or$p.id-notmatch'^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$'-or$p.action-notin@('setup','start-local-service','start-system','read','cleanup-local-service','cleanup-system')){throw 'Fixed controller request'} $script='C:\ProgramData\RustDiscoveryBootstrap\'+$p.script_sha256+'\SignedClockCaptureAcceptance.ps1' if(!(Test-Path -LiteralPath $script)){ if($p.action-cne'read'){throw 'Staged controller absent'} @{id=$p.id;read_only=$true;controller_absent=$true;remote_case_absent=!(Test-Path -LiteralPath ('C:\ProgramData\RustDiscoverySignedClockCapture\'+$p.id))}|ConvertTo-Json -Compress;exit 0 } $i=Get-Item -LiteralPath $script -Force;if($i.PSIsContainer-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)-or$i.Length-gt65536-or(Get-FileHash -LiteralPath $script -Algorithm SHA256).Hash.ToLowerInvariant()-cne$p.script_sha256){throw 'Exact staged controller'} $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'};foreach($r in $a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])){if($r.AccessControlType-ne'Allow'-or$r.IdentityReference.Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Private controller DACL'}} $global:RmmSignedClockCapturePayload=$p & $script ''' class CaptureAccess(pipe.Access): def stage_capture(self, path, name): require(name in ('SignedClockCapture.exe', 'SignedClockCaptureAcceptance.ps1'), 'two fixed capture artifacts only') path = Path(path) private(path) size = path.stat().st_size require(size == EXE_BYTES if name.endswith('.exe') else size <= 65536, 'fixed bounded capture transfer') digest = sha(path) prepare = pipe.u.transport.PREPARE_SCRIPT.replace('TransportAcceptance.ps1', name) observed = self.powershell(prepare, dict(sha256=digest)) if not observed['already_uploaded']: # Credentials are read only by the actual operator phase. The # existing strict pinned ssh prefix is reused without modification. access = pipe.cb.contract.protected_json(self.root / 'credentials/windows-dev-access.json') prefix = access['ssh_prefix'] args = ['sftp'] + [p for p in prefix[1:-1] if p != '-T'] + ['-b', '-', prefix[-1]] target = '/C:/ProgramData/RustDiscoveryBootstrap/' + digest + '/' + name result = subprocess.run(args, input=('put ' + json.dumps(str(path.resolve())) + ' ' + json.dumps(target) + '\n').encode(), capture_output=True, timeout=60) require(result.returncode == 0, 'fixed create-once capture transfer; lost reply read only') observed = self.powershell(prepare, dict(sha256=digest)) require(observed['already_uploaded'] is True and observed['sha256'] == digest, 'exact immutable staged capture artifact') def dependencies(): paths = set(pipe.dependencies()) | {'deploy/windows/system_pipe_upgrade.py'} return {path: sha(ROOT / path) for path in sorted(paths)} def original_main(): for name, digest in INDEX_SHAS.items(): path = ACCESS_ROOT / 'devstate/windows-client' / name require(sha(path) == digest, 'unchanged accepted Main component indices') require(sha(MAIN_CASE / 'intent.json') == MAIN_INTENT_SHA and sha(MAIN_CASE / 'result.json') == MAIN_RESULT_SHA, 'original accepted 14fb proof') intent = load(MAIN_CASE / 'intent.json') require(intent['script_sha256'] == pipe.raw_sha(pipe.SCRIPT.encode()), 'original 14fb read-only finish implementation') return intent def source_qualification(): require(sha(QUALIFICATION / 'receipt.json') == RECEIPT_SHA and sha(QUALIFICATION / 'inputs.json') == INPUTS_SHA and sha(QUALIFICATION / 'readonly-capabilities.json') == CAP_SHA, 'original reviewed raw source qualification') inputs = load(QUALIFICATION / 'inputs.json') receipt = load(QUALIFICATION / 'receipt.json') require(len(inputs) == 190 and receipt['calibrated'] is False and receipt['clock_authority'] is False and receipt['module_sha256'] == 'd9dd843db7c17ac4c8f242c9f20063c2a7ce6ad11d3c75826516a22dc5e7685e' and receipt['example_sha256'] == '23f7c8d832bf9042fb89226729aa1cfe2a65ad33b76cda15cc69f8995d5834d0', 'reviewed exact non-authoritative probe') seen = set() for item in inputs: path = Path(item['path']) require(not path.is_absolute() and '..' not in path.parts and str(path) not in seen, 'unique frozen relative input') seen.add(str(path)) file = QUALIFICATION / 'source' / path metadata = file.lstat() require(stat.S_ISREG(metadata.st_mode) and metadata.st_nlink == 1 and metadata.st_size == item['bytes'] and metadata.st_size <= 2 * 1024 * 1024 and sha(file) == item['sha256'], 'original frozen source bytes') binary = QUALIFICATION / 'SignedClockCapture.exe' require(binary.stat().st_size == EXE_BYTES and sha(binary) == EXE_SHA, 'exact qualified AMD64 probe') native = load(LINUX_READ) require(sha(LINUX_READ) == LINUX_READ_SHA and native['read_only'] is True and native['entered'] is True and native['id'] == NATIVE_CASE.name, 'actual original Linux-first pass readback') result = native['result'] require(result['passed'] == 5 and result['listed'] == 15 and result['filtered'] == 10 and result['ignored'] == 0 and result['source_receipt_sha256'] == RECEIPT_SHA and result['source_manifest_sha256'] == sha(NATIVE_CASE / 'manifest.json') and result['before'] == result['after'] == native['current_witness'] and result['no_rmm_jobs'] is True and result['no_service_control'] is True and result['binary_sha256'] == 'dceee96d9e58d8b5c3606c724b4d390c2eea6472bf33d317e7a5a9102c0c5e06', 'actual five Linux guards and retained original state') native_manifest = load(NATIVE_CASE / 'manifest.json') require(native_manifest['source_files'] == inputs and native_manifest['receipt_sha256'] == RECEIPT_SHA, 'same Linux proof source generation') return inputs def prepare(): original_main() inputs = source_qualification() STATE.mkdir(mode=0o700, parents=True, exist_ok=True); private(STATE, True) ident = str(uuid.uuid4()) # One original campaign for this exact frozen source. An incomplete case # cannot be bypassed by asking prepare for another UUID. save(STATE / 'active-intent.json', dict(id=ident, runner_sha256=sha(__file__), no_retry=True)) folder = STATE / ident; folder.mkdir(mode=0o700) for name in ('receipt.json', 'inputs.json', 'readonly-capabilities.json'): write(folder / name, (QUALIFICATION / name).read_bytes()) for item in inputs: destination = folder / 'source' / item['path'] destination.parent.mkdir(mode=0o700, parents=True, exist_ok=True) write(destination, (QUALIFICATION / 'source' / item['path']).read_bytes()) write(folder / 'SignedClockCapture.exe', (QUALIFICATION / 'SignedClockCapture.exe').read_bytes()) write(folder / 'SignedClockCaptureAcceptance.ps1', SCRIPT.encode()) write(folder / 'linux-first-read.json', LINUX_READ.read_bytes()) manifest = dict(id=ident, profile=PROFILE, runner_sha256=sha(__file__), dependencies=dependencies(), source_files=inputs, source_receipt_sha256=RECEIPT_SHA, readonly_capabilities_sha256=CAP_SHA, exe_sha256=EXE_SHA, exe_bytes=EXE_BYTES, script_sha256=hashlib.sha256(SCRIPT.encode()).hexdigest(), linux_first_read_sha256=LINUX_READ_SHA, main_indices=INDEX_SHAS, main_result_sha256=MAIN_RESULT_SHA, calibrated=False, clock_authority=False, target_executed=False) save(folder / 'manifest.json', manifest) print(json.dumps(dict(id=ident, prepared_locally=True, target_executed=False))) def case(ident): require(str(uuid.UUID(ident)) == ident and uuid.UUID(ident).version == 4, 'original canonical UUIDv4') folder = STATE / ident; private(folder, True) manifest = load(folder / 'manifest.json') require(manifest['id'] == ident and manifest['profile'] == PROFILE and manifest['runner_sha256'] == sha(__file__) and manifest['dependencies'] == dependencies() and load(STATE / 'active-intent.json')['id'] == ident, 'original source and active case only') require(sha(folder / 'SignedClockCapture.exe') == EXE_SHA and (folder / 'SignedClockCapture.exe').stat().st_size == EXE_BYTES and sha(folder / 'SignedClockCaptureAcceptance.ps1') == manifest['script_sha256'] == hashlib.sha256(SCRIPT.encode()).hexdigest() and sha(folder / 'receipt.json') == RECEIPT_SHA and sha(folder / 'inputs.json') == INPUTS_SHA and sha(folder / 'readonly-capabilities.json') == CAP_SHA and sha(folder / 'linux-first-read.json') == LINUX_READ_SHA, 'same exact original sources/proofs/artifacts') require(manifest['source_files'] == load(folder / 'inputs.json') and len(manifest['source_files']) == 190, 'fixed original source manifest') for item in manifest['source_files']: relative = Path(item['path']) require(not relative.is_absolute() and '..' not in relative.parts, 'fixed relative source path') path = folder / 'source' / relative; private(path) require(path.stat().st_size == item['bytes'] and sha(path) == item['sha256'], 'original retained 190 input bytes') original_main() return folder, manifest def server_closed(access): observed = access.server_state() require(observed['counts'] == dict(windows=dict(jobs=0, outbox=0, permits=0, unresolved=0), linux=dict(jobs=31, outbox=31, permits=27, unresolved=0)) and observed['flags']['root_policy_sha256'] == ROOT_POLICY, 'actual accepted current counts and closed Rootpolicy') return observed def native_witness(access): observed = pipe.remote(access, original_main(), 'finish') require(observed['read_only'] is True and observed['completed'] is True, 'only original existing 14fb finish reader') native = observed['native'] require(native['private_key_read'] is False and all(value == 0 for value in native['journal']['core_counts'].values()), 'passive identity, no core job rows') return dict(stable={field: native[field] for field in STABLE}, journal={field: native['journal'][field] for field in JOURNAL}, sequence=native['journal']['sequence']) def preserved(before, after): require(before['stable'] == after['stable'] and before['journal'] == after['journal'] and after['sequence'] >= before['sequence'], 'all six native fields and journal identity/schema/core counts preserved') def baseline(access, folder): save(folder / 'baseline-attempt.json', dict(read_only=True)) server = server_closed(access); native = native_witness(access) save(folder / 'baseline.json', dict(server=server, native=native, indices=INDEX_SHAS)) print(json.dumps(dict(id=folder.name, baseline_read_only=True))) def payload(folder, manifest, phase): return dict(id=folder.name, profile=PROFILE, action=phase, exe_sha256=EXE_SHA, exe_bytes=EXE_BYTES, script_sha256=manifest['script_sha256'], manifest_sha256=sha(folder / 'manifest.json')) def validate_role(role, value, ident): require(role in ('local-service', 'system'), 'fixed role validation') report = value['reports']['report']; end = value['reports']['end']; intent = value['reports']['intent'] outcome = value['markers']['outcome']; exited = value['markers']['exit']; process = value['markers']['process'] require(report is not None and end is not None and outcome is not None and exited is not None and process is not None and outcome['success'] is True and end['success'] is True and exited['kernel_process_exited'] is True and exited['exit_code'] == 0 and exited['timed_out'] is False and exited['scm_exit'] == exited['scm_specific_exit'] == 0 and report['role'] == end['role'] == role and report['case_id'] == end['case_id'] == intent['case_id'] == ident and value['raw_report_sha256'] == end['report_sha256'] == outcome['report_sha256'] and report['pid'] == intent['pid'] == process['proof']['pid'] and str(report['process_birth_filetime']) == process['proof']['creation_filetime'] and report['image_sha256'] == EXE_SHA and report['calibrated'] is report['clock_authority'] is False, 'actual own role/process/end/exit proof') expected = 'S-1-5-19' if role == 'local-service' else 'S-1-5-18' require(report['token']['user_sid'] == process['proof']['owner_sid'] == expected and report['token']['service_sid_sha256'] == hashlib.sha256(process['proof']['service_sid'].encode()).hexdigest() and process['proof']['service_sid_enabled'] is True and process['proof']['kernel_handle_bound'] is True, 'actual token and enabled own service SID') capture = report['capture']; rows = capture['samples_100ns'] require(capture['schema_version'] == 1 and capture['calibrated'] is capture['clock_authority'] is False and capture['sample_count'] == len(rows) == 128 and capture['elapsed_monotonic_ns'] <= 250_000_000 and capture['elapsed_interrupt_ns'] <= 250_000_000 and all(isinstance(row, list) and len(row) == 5 and all(type(number) is int and 0 <= number < 2**64 for number in row) for row in rows), 'bounded numeric raw capture, never calibration') if value['service'] is None: require(value['markers']['delete-attempt'] is not None and value['markers']['deleted']['service_absent'] is True, 'original own cleanup and actual absence') else: require(value['status'] is not None and value['status']['State'] == 1 and value['status']['Pid'] == 0, 'own service stopped') def read(access, folder, manifest): read_id = str(uuid.uuid4()) raw_path = folder / ('read-' + read_id + '.json') server_path = folder / ('read-server-' + read_id + '.json') native_path = folder / ('read-native-' + read_id + '.json') preservation_path = folder / ('read-preservation-' + read_id + '.json') receipt_path = folder / ('read-receipt-' + read_id + '.json') response = access.powershell(LAUNCH, payload(folder, manifest, 'read'), timeout=90) # Save/fsync the exact canonical raw read before creating any linked proof. save(raw_path, response) raw_link = dict(filename=raw_path.name, sha256=sha(raw_path)) binding = dict(case_id=folder.name, read_id=read_id, raw_read_filename=raw_path.name, raw_read_sha256=raw_link['sha256'], runner_sha256=sha(__file__), controller_sha256=manifest['script_sha256'], read_only=True) completed = [] for role, value in response.get('roles', {}).items(): if value['markers']['outcome'] is not None: validate_role(role, value, folder.name) completed.append(role) old = load(folder / 'baseline.json') server = server_closed(access); native = native_witness(access) require(server == old['server'], 'current server gates unchanged') preserved(old['native'], native) # Each independently captured witness binds this exact same saved read. save(server_path, dict(binding, witness=server)) save(native_path, dict(binding, witness=native)) server_link = dict(filename=server_path.name, sha256=sha(server_path)) native_link = dict(filename=native_path.name, sha256=sha(native_path)) cleaned = sorted(role for role, value in response.get('roles', {}).items() if value['service'] is None and value['markers']['deleted'] is not None and value['markers']['deleted']['service_absent'] is True) save(preservation_path, dict(binding, server=server, native=native, server_witness=server_link, native_witness=native_link, completed_roles=sorted(completed), cleanup_verified_roles=cleaned, calibrated=False, clock_authority=False)) preservation_link = dict(filename=preservation_path.name, sha256=sha(preservation_path)) # Final create-only receipt is published only after A, both witnesses and B # have been persisted. Missing files never become a completed read receipt. save(receipt_path, dict(binding, schema_version=1, raw_read=raw_link, preservation=preservation_link, server_witness=server_link, native_witness=native_link, calibrated=False, clock_authority=False)) print(json.dumps(dict(id=folder.name, read_only=True, completed_roles=sorted(completed), read_receipt_filename=receipt_path.name, read_receipt_sha256=sha(receipt_path)))) def mutate(access, folder, manifest, phase): old = load(folder / 'baseline.json') require(server_closed(access) == old['server'], 'same closed server before action') preserved(old['native'], native_witness(access)) if phase != 'setup': require((folder / 'setup-reply.json').exists(), 'one completed original setup') if phase.startswith('start-'): require(not any(folder.glob('cleanup-*-attempt.json')), 'cleanup already began; no new starts') save(folder / (phase + '-attempt.json'), dict(id=folder.name, once=True, no_retry=True)) if phase == 'setup': access.stage_capture(folder / 'SignedClockCapture.exe', 'SignedClockCapture.exe') access.stage_capture(folder / 'SignedClockCaptureAcceptance.ps1', 'SignedClockCaptureAcceptance.ps1') observed = access.powershell(LAUNCH, payload(folder, manifest, phase), timeout=90) save(folder / (phase + '-reply.json'), observed) require(observed['id'] == folder.name and observed['calibrated'] is observed['clock_authority'] is False, 'original non-authoritative native response') if phase.startswith('start-'): validate_role(phase.removeprefix('start-'), observed['roles'][phase.removeprefix('start-')], folder.name) if phase.startswith('cleanup-'): role = phase.removeprefix('cleanup-') require(observed['roles'][role]['service'] is None and observed['roles'][role]['markers']['deleted']['service_absent'] is True, 'exact own stopped service deleted once and absence observed') after_server = server_closed(access); after_native = native_witness(access) require(after_server == old['server'], 'current server policy/counts/hooks unchanged') preserved(old['native'], after_native) save(folder / (phase + '-preserved.json'), dict(server=after_server, native=after_native, no_rmm_jobs=True)) print(json.dumps(dict(id=folder.name, phase=phase, preserved=True, calibrated=False, clock_authority=False))) def static_guards(): require(SCRIPT.count('$h.StartOnce()') == SCRIPT.count('$h.DeleteOnce()') == SCRIPT.count('[RmmCaptureControl]::KillHeld($process)') == 1, 'single fixed own action primitives') require(all(token not in SCRIPT for token in ('RmmDiscoveryWindows', 'RmmDiscoverySystemHelper', 'device.key', 'Restart-Service', 'Restart-Computer', 'Stop-Computer', 'Set-Date', 'w32tm', 'Invoke-Expression', 'Bypass')), 'no RMM/W32Time/setter/general execution path') require('function FileIdentity' not in NATIVE and 'function ActualState' not in NATIVE and 'function Swap' not in NATIVE, 'only original read-only handle proof reused') require(len(SCRIPT.encode()) <= 65536 and len(base64.b64encode(LAUNCH.encode('utf-16le'))) + 2048 < 32767, 'bounded staged controller and launch command') def main(): os.umask(0o077) static_guards() parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('phase', choices=('prepare', 'baseline', 'setup', 'start-local-service', 'start-system', 'read', 'cleanup-local-service', 'cleanup-system')) parser.add_argument('--case') args = parser.parse_args() if args.phase == 'prepare': require(args.case is None, 'one new local campaign only'); prepare(); return require(args.case is not None, 'original case required') folder, manifest = case(args.case) access = CaptureAccess(ACCESS_ROOT) if args.phase == 'baseline': baseline(access, folder) elif args.phase == 'read': read(access, folder, manifest) else: mutate(access, folder, manifest, args.phase) if __name__ == '__main__': main()