Files
rust-discovery/deploy/windows/helper_peer_controls.py
2026-11-14 06:48:00 +01:00

313 lines
30 KiB
Python

#!/usr/bin/env python3
"""Native negative peer controls and bounded SDK diagnostic, never an RMM job.
Only Root executes native phases after source review. Failed/ambiguous starts
permit readback of the same case only; no token/key/private ledger data export.
"""
import argparse
import base64
import hashlib
import json
import os
from pathlib import Path
import shutil
import subprocess
import uuid
import client_bootstrap as cb
import transport_acceptance as base
import runtime_feature_upgrade as feature
import system_helper_bootstrap as helper
import auto_transport_acceptance as auto
require=cb.contract.require
STATE=cb.EVIDENCE/'helper-peer-controls'
NAME='RmmDiscoveryPeerControl'
PARENT='RmmDiscoveryPeerParent'
ROOT=r'C:\ProgramData\RustDiscoveryPeerControls'
# Shared by real Protect and read-only memory guards. Normalize the collection,
# never an invalid individual SID. PS5 if {...} else {@()} assigns $null.
ACL_CONSTRUCTORS=r'''function ControlIdentities([string[]]$readers,[string[]]$writers){
if($null-eq$readers){$readers=@()};if($null-eq$writers){$writers=@()}
$ids=@('S-1-5-18','S-1-5-32-544')+$readers+$writers
foreach($id in $ids){if([string]::IsNullOrWhiteSpace($id)){throw 'EMPTY_CONTROL_SID'}}
return $ids
}
function ControlRule([string]$id,[bool]$directory,[bool]$reader,[bool]$writer){
[Security.AccessControl.InheritanceFlags]$inheritFlags=[Security.AccessControl.InheritanceFlags]::None
if($directory){$inheritFlags=[Security.AccessControl.InheritanceFlags]::ContainerInherit-bor[Security.AccessControl.InheritanceFlags]::ObjectInherit}
[Security.AccessControl.FileSystemRights]$rights=[Security.AccessControl.FileSystemRights]::FullControl
if($writer){$rights=[Security.AccessControl.FileSystemRights]::Read-bor[Security.AccessControl.FileSystemRights]::Write}
elseif($reader){$rights=[Security.AccessControl.FileSystemRights]::ReadAndExecute}
$identity=[Security.Principal.SecurityIdentifier]::new($id)
return [Security.AccessControl.FileSystemAccessRule]::new($identity,$rights,$inheritFlags,[Security.AccessControl.PropagationFlags]::None,[Security.AccessControl.AccessControlType]::Allow)
}
'''
MEMORY_GUARD=ACL_CONSTRUCTORS+r'''$ErrorActionPreference='Stop'
$rows=@()
foreach($kind in @('root','controller','admin-leaf','writer-leaf')){
$readers=if($kind-ceq'root'){@('S-1-5-80-1','S-1-5-80-2')}else{@()}
$writers=if($kind-ceq'writer-leaf'){@('S-1-5-80-3')}else{@()}
$ids=@(ControlIdentities $readers $writers);$expected=if($kind-ceq'root'){4}elseif($kind-ceq'writer-leaf'){3}else{2}
if($ids.Count-ne$expected-or@($ids|Where-Object{[string]::IsNullOrWhiteSpace($_)}).Count){throw 'NORMALIZED_ROLE_COUNT'}
$masks=@();foreach($id in $ids){$r=ControlRule $id ($kind-in@('root','controller')) ($id-in$readers) ($id-in$writers);$masks+=[int64]$r.FileSystemRights}
if($masks[0]-ne2032127-or$masks[1]-ne2032127){throw 'EXACT_ADMIN_MASKS'}
if($kind-ceq'root'-and($masks[2]-ne1179817-or$masks[3]-ne1179817)){throw 'EXACT_READER_MASKS'}
if($kind-ceq'writer-leaf'-and$masks[2]-ne1180063){throw 'EXACT_LEAF_WRITER_MASK'}
$rows+=@{case=$kind;constructor_count=$ids.Count;input_readers_null=($null-eq$readers);input_writers_null=($null-eq$writers);masks=$masks}
}
@{verified=$true;read_only=$true;filesystem_or_acl_mutations=$false;service_changes=$false;cases=$rows}|ConvertTo-Json -Depth 6 -Compress
'''
PREPARE=r'''$ErrorActionPreference='Stop'
$p=([Console]::In.ReadLine()|ConvertFrom-Json)
if($p.sha -notmatch '^[a-f0-9]{64}$' -or $p.name -notin @('HelperPeerControls.exe','PeerControls.ps1')){throw 'Fixed control artifact'}
$root='C:\ProgramData\RustDiscoveryPeerControls'
$agent=(New-Object Security.Principal.NTAccount('NT SERVICE','RmmDiscoveryWindows')).Translate([Security.Principal.SecurityIdentifier]).Value
$readers=@($agent,$p.control_sid)
if($p.control_sid -notmatch '^S-1-5-80-([0-9]+-){4}[0-9]+$'){throw 'Fixed control SID'}
function Check($path){$i=Get-Item -LiteralPath $path -Force;if($i.Attributes-band[IO.FileAttributes]::ReparsePoint){throw 'Control reparse'};$a=Get-Acl -LiteralPath $path;if($a.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Control owner'};foreach($r in $a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])){if($r.AccessControlType-ne'Allow'){throw 'Control deny'};if($r.IdentityReference.Value-in@('S-1-5-18','S-1-5-32-544')){continue};if($r.IdentityReference.Value-notin$readers-or([int64]$r.FileSystemRights-band(-bnot 1179817))){throw 'Control reader'}}}
if(!(Test-Path -LiteralPath $root)){
New-Item -ItemType Directory -Path $root|Out-Null;$a=New-Object Security.AccessControl.DirectorySecurity;$a.SetAccessRuleProtection($true,$false);$a.SetOwner((New-Object Security.Principal.SecurityIdentifier('S-1-5-32-544')))
foreach($id in @('S-1-5-18','S-1-5-32-544')+$readers){$right=if($id-in$readers){'ReadAndExecute'}else{'FullControl'};$a.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule((New-Object Security.Principal.SecurityIdentifier($id)),$right,'ContainerInherit,ObjectInherit','None','Allow')))};Set-Acl -LiteralPath $root -AclObject $a
}
Check $root;$version=Join-Path $root $p.sha;if(!(Test-Path -LiteralPath $version)){New-Item -ItemType Directory -Path $version|Out-Null};Check $version
$file=Join-Path $version $p.name;$exists=Test-Path -LiteralPath $file;if($exists){Check $file;if((Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash.ToLowerInvariant()-cne$p.sha){throw 'Immutable control artifact'}}
@{exists=$exists;sha=$p.sha}|ConvertTo-Json -Compress
'''
SCRIPT=r'''$ErrorActionPreference='Stop'
$p=$global:RmmPeerControlPayload
if($p.action-notin@('prepare','admin','service','parent','cleanup','readback')-or([guid]::ParseExact($p.id,'D').ToString())-cne$p.id-or$p.binary-notmatch'^[a-f0-9]{64}$'-or$p.source-notmatch'^[a-f0-9]{64}$'-or$p.direct_peer_proof-isnot[bool]){throw 'Fixed control intent'}
if($p.direct_peer_proof-and$p.action-notin@('prepare','parent','cleanup','readback')){throw 'Direct proof case has no child, administrator or LocalService probe'}
$root='C:\ProgramData\RustDiscoveryPeerControls';$case=Join-Path $root $p.id;$controller=Join-Path $case 'controller';$exe=Join-Path (Join-Path $root $p.binary) 'HelperPeerControls.exe'
$agentName='RmmDiscoveryWindows';$helperName='RmmDiscoverySystemHelper';$name='RmmDiscoveryPeerControl';$parentName='RmmDiscoveryPeerParent'
$agentSid=(New-Object Security.Principal.NTAccount('NT SERVICE',$agentName)).Translate([Security.Principal.SecurityIdentifier]).Value
$controlSid=$p.control_sid
function Hash($path){return (Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant()}
function WriteNew($path,$data){$b=[Text.Encoding]::UTF8.GetBytes(($data|ConvertTo-Json -Depth 24 -Compress));$f=[IO.File]::Open($path,'CreateNew','Write','Read');try{$f.Write($b,0,$b.Length);$f.Flush($true)}finally{$f.Dispose()}}
function Check($path,[bool]$directory,[string[]]$readers,[string[]]$writers){
$i=Get-Item -LiteralPath $path -Force;if($i.PSIsContainer-ne$directory-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Fixed regular control path'}
$a=Get-Acl -LiteralPath $path;$owner=$a.GetOwner([Security.Principal.SecurityIdentifier]).Value
if($owner-notin@('S-1-5-18','S-1-5-32-544')){throw 'SYSTEM/Admin report ownership required'}
$rules=@($a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if(!$rules.Count){throw 'Empty control DACL'}
foreach($r in $rules){
$id=$r.IdentityReference.Value;$mask=[int64]$r.FileSystemRights
if($r.AccessControlType-ne'Allow'){throw 'Unexpected control ACE'}
if($id-in@('S-1-5-18','S-1-5-32-544')){if($mask-ne2032127){throw 'Exact controller administrative rights'}}
elseif($id-in$writers){if($mask-ne1180063-or$directory){throw 'Writer only on fixed precreated output leaf'}}
elseif($id-in$readers){if($mask-band(-bnot 1179817)){throw 'Reader-only role'}}
else{throw 'Foreign control/report principal'}
}
}
function Protect($path,[bool]$directory,[string[]]$readers,[string[]]$writers){
$a=if($directory){[Security.AccessControl.DirectorySecurity]::new()}else{[Security.AccessControl.FileSecurity]::new()};$a.SetAccessRuleProtection($true,$false);$a.SetOwner([Security.Principal.SecurityIdentifier]::new('S-1-5-32-544'))
foreach($id in (ControlIdentities $readers $writers)){
$rule=ControlRule $id $directory ($id-in$readers) ($id-in$writers)
$a.AddAccessRule($rule)
}
Set-Acl -LiteralPath $path -AclObject $a;Check $path $directory $readers $writers
}
function ReportPath($name){
if($name-in@('admin-token','admin-result')){return Join-Path (Join-Path $case 'admin') ($name+'.json')}
if($name-in@('service-token','service-result')){return Join-Path (Join-Path $case 'service') ($name+'.json')}
if($name-in@('child-token','child-sdk-prechecks','child-result')){return Join-Path (Join-Path $case 'child') ($name+'.json')}
return Join-Path $controller ($name+'.json')
}
function Metadata($path){$i=Get-Item -LiteralPath $path -Force;if($i.Attributes-band[IO.FileAttributes]::ReparsePoint){throw 'Existing component reparse'};return [ordered]@{name=$i.Name;length=$i.Length;created=$i.CreationTimeUtc.Ticks;written=$i.LastWriteTimeUtc.Ticks;sddl=(Get-Acl -LiteralPath $path).Sddl}}
function Baseline {
$services=[ordered]@{}
foreach($pair in @(@($agentName,$p.agent_pid,'NT AUTHORITY\LocalService',$p.agent_binary,'C:\Program Files\RustDiscovery\rmm-agent-windows.exe'),@($helperName,$p.helper_pid,'LocalSystem',$p.helper_binary,'C:\Program Files\RustDiscovery\rmm-helper-windows.exe'))){
$s=Get-CimInstance Win32_Service -Filter ("Name='"+$pair[0]+"'") -OperationTimeoutSec 10
if($s.State-cne'Running'-or$s.ProcessId-ne$pair[1]-or$s.StartName-cne$pair[2]-or(Hash $pair[4])-cne$pair[3]){throw 'Original current agent/helper identity'}
$process=Get-CimInstance Win32_Process -Filter ('ProcessId='+$s.ProcessId) -OperationTimeoutSec 10
$owner=(Invoke-CimMethod -InputObject $process -MethodName GetOwnerSid -OperationTimeoutSec 10).Sid;$expected=if($pair[0]-ceq$agentName){'S-1-5-19'}else{'S-1-5-18'}
if($owner-cne$expected-or$process.ExecutablePath-cne$pair[4]){throw 'Original running process identity'}
# Process.StartTime uses GetProcessTimes/FromFileTime. CIM CreationDate
# rounded away actual100ns ticks on this VM; no tolerance is permitted.
$nativeProcess=[Diagnostics.Process]::GetProcessById([int]$s.ProcessId)
try{$creationFiletime=$nativeProcess.StartTime.ToUniversalTime().ToFileTimeUtc()}finally{$nativeProcess.Dispose()}
$services[$pair[0]]=[ordered]@{pid=$s.ProcessId;path=$s.PathName;start_mode=$s.StartMode;account=$s.StartName;owner_sid=$owner;creation_filetime=$creationFiletime;binary_sha256=(Hash $pair[4])}
}
$settings='C:\ProgramData\RustDiscoverySystem\helper.json';$pin='C:\ProgramData\RustDiscoverySystem\agent-pin.json'
if((Hash $settings)-cne$p.policy-or(Hash $pin)-cne$p.pin_sha256){throw 'Original passive helper public pin'}
$cfg=Get-Content -LiteralPath $settings -Raw|ConvertFrom-Json
if($cfg.enable_effects-ne$false-or$cfg.allow_reboot-ne$false-or@($cfg.allowed_services).Count-ne0){throw 'Empty passive policy only'}
$files=@(Get-ChildItem -LiteralPath 'C:\ProgramData\RustDiscoverySystem\state' -File -Force|Sort-Object Name|ForEach-Object{Metadata $_.FullName})
# Metadata only: never read/hash/copy private ledger or key contents.
return [ordered]@{services=$services;private_helper_metadata=$files;agent_config=(Metadata 'C:\ProgramData\RustDiscovery\config.json');agent_config_sha256=(Hash 'C:\ProgramData\RustDiscovery\config.json');device_key_metadata=(Metadata 'C:\ProgramData\RustDiscovery\state\device.key');helper_public_pin_sha256=(Hash $pin);helper_public_settings_sha256=(Hash $settings);helper_private_bytes_read=$false}
}
function Same($before,$after){if(($before|ConvertTo-Json -Depth 24 -Compress)-cne($after|ConvertTo-Json -Depth 24 -Compress)){throw 'Original agent/helper or private file metadata changed'}}
function ReadIntent{Check $case $true @($agentSid,$controlSid) @();Check $controller $true @() @();Check (Join-Path $controller 'intent.json') $false @() @();$i=Get-Content -LiteralPath (Join-Path $controller 'intent.json') -Raw|ConvertFrom-Json;foreach($field in @('id','binary','source','agent_pid','helper_pid','agent_binary','helper_binary','policy','pin_sha256','control_sid','direct_peer_proof')){if($i.payload.$field-cne$p.$field){throw 'Exact retained control intent'}};return $i}
if((Hash $exe)-cne$p.binary){throw 'Exact control executable'}
if($p.action-ceq'prepare'){
if((Test-Path -LiteralPath $case)-or(Get-Service -Name $name -ErrorAction SilentlyContinue)-or(Get-Service -Name $parentName -ErrorAction SilentlyContinue)){throw 'No preexisting control case/services'}
$before=Baseline;New-Item -ItemType Directory -Path $case|Out-Null;Protect $case $true @($agentSid,$controlSid) @()
foreach($dir in @('controller','admin','service','child')){
$path=Join-Path $case $dir;New-Item -ItemType Directory -Path $path|Out-Null
$readers=if($dir-ceq'service'){@($controlSid)}elseif($dir-ceq'child'){@($agentSid)}else{@()}
Protect $path $true $readers @()
}
WriteNew (Join-Path $controller 'intent.json') @{payload=$p;before=$before;no_jobs=$true}
# Precreate fixed leaves before ANY actor starts. Their owner stays Admin;
# no actor may create files in a report directory or acquire owner WRITE_DAC.
foreach($report in @('admin-token','admin-result','service-token','service-result','child-token','child-sdk-prechecks','child-result')){
$path=ReportPath $report;$f=[IO.File]::Open($path,'CreateNew','Write','Read');$f.Dispose()
$writers=if($report.StartsWith('service-')){@($controlSid)}elseif($report.StartsWith('child-')){@($agentSid)}else{@()}
Protect $path $false @() $writers
}
$pin=Get-Content -LiteralPath 'C:\ProgramData\RustDiscoverySystem\agent-pin.json' -Raw|ConvertFrom-Json
WriteNew (Join-Path $case 'input.json') @{schema_version=1;case_id=$p.id;pin=$pin;expected_agent_pid=$p.agent_pid;expected_helper_pid=$p.helper_pid;expected_agent_creation=$before.services.RmmDiscoveryWindows.creation_filetime;control_binary_sha256=$p.binary};Protect (Join-Path $case 'input.json') $false @($agentSid,$controlSid) @()
@{prepared=$true;baseline=$before;no_jobs=$true}|ConvertTo-Json -Depth 24 -Compress;exit 0
}
$intent=ReadIntent;Same $intent.before (Baseline)
if($p.action-ceq'admin'){
WriteNew (Join-Path $controller 'admin-start-intent.json') @{once=$true;raw_probe_only=$true}
$si=New-Object Diagnostics.ProcessStartInfo;$si.FileName=$exe;$si.Arguments='--admin '+$p.id;$si.UseShellExecute=$false;$si.CreateNoWindow=$true;$si.RedirectStandardError=$true;$si.RedirectStandardOutput=$true
$proc=New-Object Diagnostics.Process;$proc.StartInfo=$si
if(!$proc.Start()){throw 'Own administrator probe start'}
try{$out=$proc.StandardOutput.ReadToEndAsync();$err=$proc.StandardError.ReadToEndAsync();if(!$proc.WaitForExit(20000)){$proc.Kill();$proc.WaitForExit(5000)|Out-Null;throw 'Own administrator probe timeout'};WriteNew (Join-Path $controller 'admin-exit.json') @{pid=$proc.Id;exit_code=$proc.ExitCode;stdout_bytes=$out.Result.Length;stderr_bytes=$err.Result.Length};if($proc.ExitCode-ne0){throw 'Own administrator probe incomplete'}}finally{$proc.Dispose()}
}
if($p.action-in@('service','parent')){
$kind=$p.action;$serviceName=if($kind-ceq'service'){$name}else{$parentName};$mode=if($kind-ceq'service'){'--service'}elseif($p.direct_peer_proof){'--peer-proof'}else{'--parent'};$command='"'+$exe+'" '+$mode+' '+$p.id
if(Get-Service -Name $serviceName -ErrorAction SilentlyContinue){throw 'Existing control service: readback only'}
WriteNew (Join-Path $controller ($kind+'-start-intent.json')) @{once=$true;service=$serviceName;command=$command;probe_only=$true;no_jobs=$true}
if($kind-ceq'service'){$credential=New-Object Management.Automation.PSCredential('NT AUTHORITY\LocalService',(New-Object Security.SecureString));New-Service -Name $serviceName -BinaryPathName $command -StartupType Manual -Credential $credential|Out-Null}
else{New-Service -Name $serviceName -BinaryPathName $command -StartupType Manual|Out-Null}
& "$env:WINDIR\System32\sc.exe" sidtype $serviceName unrestricted|Out-Null;if($LASTEXITCODE-ne0){throw 'Own control service SID'}
Start-Service -Name $serviceName
}
$deadline=[DateTime]::UtcNow.AddSeconds(35)
foreach($kind in @('service','parent')){
$serviceName=if($kind-ceq'service'){$name}else{$parentName};$mode=if($kind-ceq'service'){'--service'}elseif($p.direct_peer_proof){'--peer-proof'}else{'--parent'};$command='"'+$exe+'" '+$mode+' '+$p.id
$s=Get-CimInstance Win32_Service -Filter ("Name='"+$serviceName+"'") -OperationTimeoutSec 10
if($s){
$expected=if($kind-ceq'service'){'NT AUTHORITY\LocalService'}else{'LocalSystem'}
if($s.PathName-cne$command-or$s.StartName-cne$expected-or$s.StartMode-cne'Manual'){throw 'Exact own control service only'}
while($s.State-cne'Stopped'-and[DateTime]::UtcNow-lt$deadline){Start-Sleep -Milliseconds 100;$s=Get-CimInstance Win32_Service -Filter ("Name='"+$serviceName+"'") -OperationTimeoutSec 10}
if($p.action-in@('service','parent','cleanup')){
if($s.State-cne'Stopped'){throw 'Own control still active: retain and readback only'}
$cleanup=Join-Path $controller ($kind+'-cleanup-intent.json')
if(!(Test-Path -LiteralPath $cleanup)){WriteNew $cleanup @{service=$serviceName;command=$command;remove_only_own_stopped_service=$true}}
else{Check $cleanup $false @() @();$c=Get-Content -LiteralPath $cleanup -Raw|ConvertFrom-Json;if($c.service-cne$serviceName-or$c.command-cne$command){throw 'Retained cleanup intent'}}
& "$env:WINDIR\System32\sc.exe" delete $serviceName|Out-Null;if($LASTEXITCODE-ne0){throw 'Exact stopped own service cleanup'}
}
}
}
Same $intent.before (Baseline)
$reports=[ordered]@{};$reportTrust=[ordered]@{}
foreach($name in @('admin-token','admin-result','service-token','service-result','parent-token','parent-result','child-create-intent','child-started','child-token','child-sdk-prechecks','child-result')){
$path=ReportPath $name;$reports[$name]=$null
$writers=if($name-in@('service-token','service-result')){@($controlSid)}elseif($name-in@('child-token','child-sdk-prechecks','child-result')){@($agentSid)}else{@()}
$readers=if($name-in@('service-token','service-result')){@($controlSid)}elseif($name-in@('child-token','child-sdk-prechecks','child-result')){@($agentSid)}else{@()}
Check ([IO.Path]::GetDirectoryName($path)) $true $readers @()
if(Test-Path -LiteralPath $path){Check $path $false @() $writers;$i=Get-Item -LiteralPath $path -Force;if($i.Length-gt8192){throw 'Bounded own report'};if($i.Length-gt0){$reports[$name]=Get-Content -LiteralPath $path -Raw|ConvertFrom-Json;$reportTrust[$name]=@{owner_sid=(Get-Acl -LiteralPath $path).GetOwner([Security.Principal.SecurityIdentifier]).Value;allowed_actor_writers=$writers;provenance=$(if($name-in@('child-token','child-sdk-prechecks','child-result')){'agent_token_assertion'}elseif($name-in@('service-token','service-result')){'control_service_assertion'}else{'system_or_bootstrap_administrator'})}}}
}
@{readback=$true;id=$p.id;reports=$reports;report_trust=$reportTrust;writer_binding_checked=$true;original_preserved=$true;own_services_removed=(!(Get-Service -Name 'RmmDiscoveryPeerControl' -ErrorAction SilentlyContinue)-and!(Get-Service -Name 'RmmDiscoveryPeerParent' -ErrorAction SilentlyContinue));no_jobs=$true;no_private_data_read=$true}|ConvertTo-Json -Depth 24 -Compress
'''
SCRIPT=ACL_CONSTRUCTORS+SCRIPT
LAUNCH=base.LAUNCH_SCRIPT.replace('TransportAcceptance.ps1','PeerControls.ps1').replace('RmmTransportPayload','RmmPeerControlPayload').replace('RustDiscoveryBootstrap','RustDiscoveryPeerControls')
def sources():
value=feature.source_files();value['deploy/windows/helper_peer_controls.py']=helper.sha(__file__)
return dict(sorted(value.items()))
def build():
os.umask(0o077);helper.private_dir(STATE);folder=STATE/('build-'+str(uuid.uuid4()));folder.mkdir(mode=0o700)
before=sources();helper.store(folder,'source-before.json',before)
target=cb.ROOT/'devstate/windows-peer-controls-target';target.mkdir(mode=0o700,parents=True,exist_ok=True)
command='cargo clippy --locked --offline --target '+feature.TARGET+' -p rmm-agent-windows --features system-helper --all-targets -- -D warnings && cargo build --locked --offline --release --target '+feature.TARGET+' -p rmm-agent-windows --features system-helper --example helper_peer_controls'
feature.previous.command(['docker','run','--rm','--network','none','--read-only','--tmpfs','/tmp:rw,size=512m','-v',str(cb.ROOT)+':/src:ro','-v',str(target)+':/target','-e','CARGO_TARGET_DIR=/target','--entrypoint','sh',feature.IMAGE,'-c',command])
require(before==sources(),'control source unchanged during build')
path=folder/'HelperPeerControls.exe';shutil.copyfile(target/feature.TARGET/'release/examples/helper_peer_controls.exe',path);path.chmod(0o600)
manifest=dict(schema_version=1,type='rmm.windows.helper-peer-controls',source_files=before,system_helper_feature=True,artifact=dict(path=str(path.resolve()),sha256=helper.sha(path)),cross_clippy_D_warnings=True,all_targets_checked=True,release_build=True,native_tested=False,no_jobs=True)
helper.store(folder,'manifest.json',manifest);print(json.dumps({'manifest':str((folder/'manifest.json').resolve()),'native_tested':False}))
def stage(path,name):
digest=helper.sha(path);payload=dict(sha=digest,name=name,control_sid=helper.service_sid(NAME));exists=cb.powershell(PREPARE,payload)
if not exists['exists']:
access=cb.contract.protected_json(cb.ROOT/'credentials/windows-dev-access.json')['ssh_prefix'];args=['sftp']+[p for p in access[1:-1] if p!='-T']+['-b','-',access[-1]]
target='/C:/ProgramData/RustDiscoveryPeerControls/'+digest+'/'+name
transferred=subprocess.run(args,input=('put '+json.dumps(str(path.resolve()))+' '+json.dumps(target)+'\n').encode(),capture_output=True,timeout=120)
require(transferred.returncode==0 and cb.powershell(PREPARE,payload)['exists'],'exact staged control artifact')
return digest
def prepare(manifest_path,helper_case,direct_peer_proof=False):
manifest=cb.contract.protected_json(manifest_path)
require(manifest['type']=='rmm.windows.helper-peer-controls' and manifest['system_helper_feature'] is True and manifest['source_files']==sources() and helper.sha(manifest['artifact']['path'])==manifest['artifact']['sha256'],'new source-bound control artifact, not old 27-unit proof')
index,association,native=helper.current_runtime()
require(str(uuid.UUID(helper_case))==helper_case,'exact existing passive helper case')
helper_intent=cb.contract.protected_json(cb.EVIDENCE/'system-helper-bootstrap'/helper_case/'intent.json');profile=helper_intent['payload']
require(profile['agent_sha256']==index['binary_sha256'] and profile['helper_sha256']==helper.HELPER_SHA,'exact retained current helper/agent association')
ident=str(uuid.uuid4());helper.private_dir(STATE);folder=STATE/ident;folder.mkdir(mode=0o700)
source=folder/'PeerControls.ps1';fd=os.open(source,os.O_CREAT|os.O_EXCL|os.O_WRONLY|os.O_NOFOLLOW,0o600)
with os.fdopen(fd,'wb') as out:out.write(SCRIPT.encode());out.flush();os.fsync(out.fileno())
payload=dict(id=ident,binary=manifest['artifact']['sha256'],source=hashlib.sha256(SCRIPT.encode()).hexdigest(),control_sid=helper.service_sid(NAME),agent_pid=native['service']['process_id'],helper_pid=6240,agent_binary=index['binary_sha256'],helper_binary=helper.HELPER_SHA,policy=profile['policy_sha256'],pin_sha256=profile['pin_sha256'],direct_peer_proof=bool(direct_peer_proof))
require(payload['agent_pid']==5140,'explicit current accepted agent process; no silent PID adoption')
intent=dict(payload=payload,source_file_sha256=helper.sha(__file__),manifest_path=str(manifest_path.resolve()),manifest_sha256=helper.sha(manifest_path),runtime_index=association,helper_case=helper_case,no_jobs=True)
helper.store(folder,'intent.json',intent);helper.store(folder,'prepare-attempt.json',{'create_once':True})
stage(Path(manifest['artifact']['path']),'HelperPeerControls.exe');stage(source,'PeerControls.ps1')
before=dict(counts=auto.scopes(),flags=auto.status());helper.store(folder,'server-before.json',before)
report=cb.powershell(LAUNCH,{'sha256':payload['source'],'payload':dict(payload,action='prepare')},timeout=90,remote_signed=True)
helper.store(folder,'prepared.json',report);print(json.dumps({'id':ident,'prepared':True,'no_jobs':True}))
def run(ident,action):
require(str(uuid.UUID(ident))==ident,'same canonical control case')
folder=STATE/ident;intent=cb.contract.protected_json(folder/'intent.json');payload=intent['payload']
require(helper.sha(__file__)==intent['source_file_sha256'] and payload['source']==hashlib.sha256(SCRIPT.encode()).hexdigest(),'exact prepared source; no case rebase')
require(helper.sha(intent['manifest_path'])==intent['manifest_sha256'] and helper.sha(intent['runtime_index']['path'])==intent['runtime_index']['sha256'],'retained control manifest and current runtime index')
cb.contract.protected_json(folder/'prepared.json')
if action!='readback':helper.store(folder,action+'-attempt.json',{'once':True,'probe_only':True})
report=cb.powershell(LAUNCH,{'sha256':payload['source'],'payload':dict(payload,action=action)},timeout=90,remote_signed=True)
helper.store(folder,action+'-readback-'+str(uuid.uuid4())+'.json',report)
before=cb.contract.protected_json(folder/'server-before.json');require(auto.scopes()==before['counts'] and auto.status()==before['flags'],'all Windows/Linux job counts and server policy flags unchanged')
if action=='readback':
print(json.dumps({'id':ident,'read_only':True,'native':report,'no_jobs':True}));return
result=summarize(report,payload,ident)
helper.store(folder,'result-'+str(uuid.uuid4())+'.json',result);print(json.dumps(result))
def summarize(report,payload,ident):
require(report.get('writer_binding_checked') is True,'native owner and exact writer-role checks required')
require(report['original_preserved'] is True and report['own_services_removed'] is True,'original services/files preserved and own stopped services removed')
result={'id':ident,'original_preserved':True,'own_services_removed':True,'no_jobs':True,'parent_diagnostic':report['reports'].get('parent-result'),'parent_token':report['reports'].get('parent-token'),'report_trust':report.get('report_trust',{}),'controls':{}}
if payload.get('direct_peer_proof') and report['reports'].get('parent-result'):
value=report['reports']['parent-result'];token=report['reports'].get('parent-token',{})
require(token.get('user_sid')=='S-1-5-18' and token.get('parent_service_sid_enabled') is True,'actual own SYSTEM diagnostic parent')
require(value.get('source')=='own_system_direct_production_agent_peer_proof' and value.get('case_id')==ident and value.get('expected_agent_pid')==payload['agent_pid'] and value.get('no_jobs') is True and value.get('read_only') is True and value.get('pipe_used') is False and value.get('token_duplicated') is False and value.get('service_or_process_acl_changed') is False,'exact read-only direct proof scope')
require(value['result'].get('direct_agent_peer_proof') is True and isinstance(value['result'].get('verified'),bool),'actual direct proof result, never pipe proof')
if value['result']['verified']:
require(value['result']['identity']['pid']==payload['agent_pid'],'actual original Agent process')
result['direct_agent_peer_proof']=value
for kind in ('admin','service'):
value=report['reports'].get(kind+'-result')
if value:
require(value['pipe']['sdk_self_check_used'] is False,'raw peer test, never SDK self-refusal')
require(value.get('case_id')==ident and value.get('mode')==kind and value.get('no_jobs') is True and value.get('read_only') is True,'exact native control receipt')
if kind=='admin':require(value['token']['administrator_enabled'] is True and value['token']['user_sid'] not in ('S-1-5-18','S-1-5-19'),'actual bootstrap administrator')
if kind=='service':require(value['token']['user_sid']=='S-1-5-19' and value['token']['control_service_sid_enabled'] is True and value['token']['agent_service_sid_enabled'] is False,'actual distinct LocalService service-SID')
error=value['pipe'].get('win32_error');opened=value['pipe'].get('opened')
require(value['pipe']['rejected'] is True and ((opened is False and error==5) or (opened is True and error in (109,232,233) and value['pipe'].get('actual_server_pid')==payload['helper_pid'])),'BUSY/timeout/response is inconclusive, never claim a denied peer')
result['controls'][kind]={'verified_negative':True,'pipe':value['pipe'],'token':value['token']}
if report['reports'].get('child-result'):
value=report['reports']['child-result'];require(value['token']['user_sid']=='S-1-5-19' and value['token']['agent_service_sid_enabled'] is True and value['token']['actual_process_id']!=payload['agent_pid'],'actual wrong-PID/image child with Agent primary identity')
require(value['pipe'].get('received_reply') is False,'impostor unexpectedly received a helper reply')
result['controls']['agent_token_child']={'diagnostic_only':True,'report':value,'parent':report['reports'].get('parent-result'),'prechecks':report['reports'].get('child-sdk-prechecks')}
return result
def main():
p=argparse.ArgumentParser(description=__doc__);p.add_argument('action',choices=['build-local','memory-guard','prepare','admin','service','parent','cleanup','readback']);p.add_argument('--manifest',type=Path);p.add_argument('--helper-case');p.add_argument('--id');p.add_argument('--direct-peer-proof',action='store_true',help='New prepare case: own SYSTEM parent only runs the exact production Agent peer proof, no child or pipe');a=p.parse_args()
if a.action=='build-local':build()
elif a.action=='memory-guard':
value=cb.powershell(MEMORY_GUARD,{},timeout=30);require(value.get('verified') is True and value.get('filesystem_or_acl_mutations') is False,'actual memory-only ACL constructor guard');print(json.dumps(value))
elif a.action=='prepare':require(a.manifest is not None and a.helper_case is not None,'new control manifest and explicit existing passive helper case required');prepare(a.manifest,a.helper_case,a.direct_peer_proof)
else:require(a.id is not None,'existing explicit control case required');run(a.id,a.action)
if __name__=='__main__':main()