Files
rust-discovery/deploy/windows/signed_clock_capture_completion.py
2026-11-15 08:45:38 +01:00

244 lines
23 KiB
Python

#!/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()