117 lines
11 KiB
Python
117 lines
11 KiB
Python
#!/usr/bin/env python3
|
|
"""Source-only until reviewed: create two fixed private delegation-store leaves.
|
|
|
|
No service operations, jobs, policy changes, keys, request contents or retries.
|
|
The parent orchestrator alone runs native phases after review/qualification.
|
|
"""
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
from pathlib import Path
|
|
import uuid
|
|
|
|
import client_bootstrap as cb
|
|
import system_helper_bootstrap as helper
|
|
|
|
STATE=cb.EVIDENCE/'system-intent-bootstrap'
|
|
require=cb.contract.require
|
|
SCRIPT=r'''$ErrorActionPreference='Stop'
|
|
$p=([Console]::In.ReadLine()|ConvertFrom-Json)
|
|
if($p.action-notin@('create','readback')-or([guid]::ParseExact($p.id,'D').ToString())-cne$p.id){throw 'Fixed intent-store case'}
|
|
foreach($field in @('agent_sha','helper_sha','config_sha','policy_sha','pin_sha')){if($p.$field-notmatch'^[a-f0-9]{64}$'){throw 'Bound current component hashes'}}
|
|
$root='C:\ProgramData\RustDiscoverySystem';$store=Join-Path $root 'agent-intents';$folder=Join-Path 'C:\ProgramData\RustDiscoveryBootstrap' ('intent-store-'+$p.id)
|
|
$sys='S-1-5-18';$admin='S-1-5-32-544';$actor=(New-Object Security.Principal.NTAccount('NT SERVICE','RmmDiscoveryWindows')).Translate([Security.Principal.SecurityIdentifier]).Value
|
|
function Hash($path){return (Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant()}
|
|
function Check($path,[bool]$directory,[bool]$actorRead,[bool]$actorWrite){
|
|
$i=Get-Item -LiteralPath $path -Force;if($i.PSIsContainer-ne$directory-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Fixed regular intent path'}
|
|
$a=Get-Acl -LiteralPath $path;if(!$a.AreAccessRulesProtected-or$a.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@($sys,$admin)){throw 'Protected SYSTEM/Admin intent ownership'}
|
|
$seen=@{};foreach($r in $a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])){
|
|
$id=$r.IdentityReference.Value;$mask=[int64]$r.FileSystemRights
|
|
if($r.AccessControlType-ne'Allow'){throw 'Exact allow-only intent ACL'}
|
|
if($id-in@($sys,$admin)){if($mask-ne2032127){throw 'Exact controller rights'}}
|
|
elseif($id-ceq$actor-and$actorWrite-and!$directory){if($mask-ne1180063){throw 'Leaf Actor read/write/synchronize only'}}
|
|
elseif($id-ceq$actor-and$actorRead){if($mask-ne1179817){throw 'Actor directory read-execute only'}}
|
|
else{throw 'Foreign or excessive intent writer'};$seen[$id]=$true
|
|
}
|
|
if(!$seen[$sys]-or!$seen[$admin]-or(($actorRead-or$actorWrite)-and!$seen[$actor])){throw 'Missing fixed principal'}
|
|
}
|
|
function Protect($path,[bool]$directory,[bool]$actorRead,[bool]$actorWrite){
|
|
$acl=if($directory){[Security.AccessControl.DirectorySecurity]::new()}else{[Security.AccessControl.FileSecurity]::new()}
|
|
$acl.SetAccessRuleProtection($true,$false);$acl.SetOwner([Security.Principal.SecurityIdentifier]::new($admin))
|
|
# No inheritable Actor writer. Neither directory-create nor DELETE_CHILD is granted.
|
|
foreach($id in @($sys,$admin)){$acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new([Security.Principal.SecurityIdentifier]::new($id),[Security.AccessControl.FileSystemRights]::FullControl,[Security.AccessControl.InheritanceFlags]::None,[Security.AccessControl.PropagationFlags]::None,[Security.AccessControl.AccessControlType]::Allow))}
|
|
if($actorRead-or$actorWrite){$rights=if($actorWrite){[Security.AccessControl.FileSystemRights]::Read-bor[Security.AccessControl.FileSystemRights]::Write}else{[Security.AccessControl.FileSystemRights]::ReadAndExecute};$acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new([Security.Principal.SecurityIdentifier]::new($actor),$rights,[Security.AccessControl.InheritanceFlags]::None,[Security.AccessControl.PropagationFlags]::None,[Security.AccessControl.AccessControlType]::Allow))}
|
|
Set-Acl -LiteralPath $path -AclObject $acl;Check $path $directory $actorRead $actorWrite
|
|
}
|
|
function WriteNew($path,$value){$bytes=[Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 12 -Compress));$f=[IO.File]::Open($path,'CreateNew','Write','Read');try{$f.Write($bytes,0,$bytes.Length);$f.Flush($true)}finally{$f.Dispose()};Protect $path $false $false $false}
|
|
function Baseline{
|
|
$out=[ordered]@{}
|
|
foreach($pair in @(@('RmmDiscoveryWindows',$p.agent_pid,$p.agent_sha,'C:\Program Files\RustDiscovery\rmm-agent-windows.exe','NT AUTHORITY\LocalService'),@('RmmDiscoverySystemHelper',$p.helper_pid,$p.helper_sha,'C:\Program Files\RustDiscovery\rmm-helper-windows.exe','LocalSystem'))){
|
|
$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[4]-or(Hash $pair[3])-cne$pair[2]){throw 'Retained running component'}
|
|
$proc=[Diagnostics.Process]::GetProcessById([int]$s.ProcessId);try{$birth=$proc.StartTime.ToUniversalTime().ToFileTimeUtc()}finally{$proc.Dispose()}
|
|
$out[$pair[0]]=@{pid=$s.ProcessId;birth=$birth;command=$s.PathName;account=$s.StartName;mode=$s.StartMode;binary_sha=$pair[2]}
|
|
}
|
|
if((Hash 'C:\ProgramData\RustDiscovery\config.json')-cne$p.config_sha-or(Hash (Join-Path $root 'helper.json'))-cne$p.policy_sha-or(Hash (Join-Path $root 'agent-pin.json'))-cne$p.pin_sha){throw 'Retained config/public pins'}
|
|
$cfg=Get-Content -LiteralPath (Join-Path $root 'helper.json') -Raw|ConvertFrom-Json
|
|
if($cfg.enable_effects-ne$false-or$cfg.allow_reboot-ne$false-or@($cfg.allowed_services).Count-ne0){throw 'Passive empty helper policy only'}
|
|
$out['private_helper_metadata']=@(Get-ChildItem -LiteralPath (Join-Path $root 'state') -File -Force|Sort-Object Name|ForEach-Object{@{name=$_.Name;length=$_.Length;written=$_.LastWriteTimeUtc.Ticks;sddl=(Get-Acl -LiteralPath $_.FullName).Sddl}})
|
|
$out['agent_key_metadata']=@{length=(Get-Item -LiteralPath 'C:\ProgramData\RustDiscovery\state\device.key').Length;sddl=(Get-Acl -LiteralPath 'C:\ProgramData\RustDiscovery\state\device.key').Sddl}
|
|
return $out
|
|
}
|
|
# Parent root is only inspected: never normalize an existing component's ACL.
|
|
$r=Get-Item -LiteralPath $root -Force;$a=Get-Acl -LiteralPath $root
|
|
if(($r.Attributes-band[IO.FileAttributes]::ReparsePoint)-or$a.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@($sys,$admin)){throw 'Retained protected public root'}
|
|
foreach($rule in $a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])){if($rule.AccessControlType-ne'Allow'-or($rule.IdentityReference.Value-notin@($sys,$admin)-and([int64]$rule.FileSystemRights-band(-bnot 1179817)))){throw 'Parent cannot grant Actor delete/create rights'}}
|
|
$before=Baseline
|
|
if($p.action-ceq'create'){
|
|
if((Test-Path -LiteralPath $folder)-or(Test-Path -LiteralPath $store)){throw 'Existing intent-store case: readback only'}
|
|
New-Item -ItemType Directory -Path $folder|Out-Null;Protect $folder $true $false $false
|
|
WriteNew (Join-Path $folder 'intent.json') @{payload=$p;before=$before;create_only=$true;no_service_operations=$true;no_jobs=$true}
|
|
New-Item -ItemType Directory -Path $store|Out-Null;Protect $store $true $true $false
|
|
foreach($name in @('system-intents.sqlite','system-intents.sqlite-journal')){$path=Join-Path $store $name;$f=[IO.File]::Open($path,'CreateNew','Write','Read');$f.Dispose();Protect $path $false $false $true}
|
|
WriteNew (Join-Path $folder 'created.json') @{leaves_created=$true;database_initialized=$false;create_only=$true}
|
|
}
|
|
Check $folder $true $false $false;Check (Join-Path $folder 'intent.json') $false $false $false
|
|
$intent=Get-Content -LiteralPath (Join-Path $folder 'intent.json') -Raw|ConvertFrom-Json
|
|
if(($intent.payload|ConvertTo-Json -Depth 12 -Compress)-cne(($p|Select-Object -Property * -ExcludeProperty action|ConvertTo-Json -Depth 12 -Compress))){
|
|
# Compare each immutable field; action is the sole readback difference.
|
|
foreach($field in @('id','agent_pid','helper_pid','agent_sha','helper_sha','config_sha','policy_sha','pin_sha')){if($intent.payload.$field-cne$p.$field){throw 'Exact retained intent-store intent'}}
|
|
}
|
|
Check $store $true $true $false
|
|
$items=@(Get-ChildItem -LiteralPath $store -Force);if((($items.Name|Sort-Object)-join ',')-cne'system-intents.sqlite,system-intents.sqlite-journal'){throw 'No unexpected SQLite WAL/temp/other leaves'}
|
|
$metadata=@();foreach($name in @('system-intents.sqlite','system-intents.sqlite-journal')){$path=Join-Path $store $name;Check $path $false $false $true;$i=Get-Item -LiteralPath $path;$metadata+=@{name=$name;length=$i.Length;sddl=(Get-Acl -LiteralPath $path).Sddl}}
|
|
$after=Baseline;if(($intent.before|ConvertTo-Json -Depth 12 -Compress)-cne($after|ConvertTo-Json -Depth 12 -Compress)){throw 'Original services/private metadata changed'}
|
|
@{verified=$true;id=$p.id;created_receipt_exists=(Test-Path -LiteralPath (Join-Path $folder 'created.json'));readback=$true;actor_directory_create_or_delete=$false;actor_leaf_owner_dacl_or_delete=$false;sqlite_mode_required='PERSIST';leaves=$metadata;no_service_operations=$true;no_jobs=$true;private_data_read=$false}|ConvertTo-Json -Depth 12 -Compress
|
|
'''
|
|
|
|
|
|
def prepare(helper_case):
|
|
require(str(uuid.UUID(helper_case))==helper_case,'exact existing helper bootstrap case')
|
|
index,association,native=helper.current_runtime()
|
|
existing=cb.contract.protected_json(cb.EVIDENCE/'system-helper-bootstrap'/helper_case/'intent.json')['payload']
|
|
require(existing['agent_sha256']==index['binary_sha256'],'retained helper-to-agent pin')
|
|
ident=str(uuid.uuid4());helper.private_dir(STATE);folder=STATE/ident;folder.mkdir(mode=0o700)
|
|
payload=dict(id=ident,agent_pid=native['service']['process_id'],helper_pid=6240,agent_sha=index['binary_sha256'],helper_sha=existing['helper_sha256'],config_sha=native['config_sha256'],policy_sha=existing['policy_sha256'],pin_sha=existing['pin_sha256'])
|
|
helper.store(folder,'intent.json',dict(payload=payload,source_sha=helper.sha(__file__),script_sha=hashlib.sha256(SCRIPT.encode()).hexdigest(),runtime_index=association,helper_case=helper_case))
|
|
helper.store(folder,'create-attempt.json',{'once':True,'no_jobs':True})
|
|
report=cb.powershell(SCRIPT,dict(payload,action='create'),timeout=90)
|
|
helper.store(folder,'created.json',report);print(json.dumps({'id':ident,'native':report}))
|
|
|
|
|
|
def readback(ident):
|
|
require(str(uuid.UUID(ident))==ident,'same canonical intent-store case')
|
|
folder=STATE/ident;intent=cb.contract.protected_json(folder/'intent.json')
|
|
require(helper.sha(__file__)==intent['source_sha'] and hashlib.sha256(SCRIPT.encode()).hexdigest()==intent['script_sha'],'exact source; no intent rebase')
|
|
report=cb.powershell(SCRIPT,dict(intent['payload'],action='readback'),timeout=90)
|
|
helper.store(folder,'readback-'+str(uuid.uuid4())+'.json',report);print(json.dumps({'id':ident,'native':report}))
|
|
|
|
|
|
def main():
|
|
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('action',choices=['prepare','readback']);parser.add_argument('--helper-case');parser.add_argument('--id');args=parser.parse_args()
|
|
if args.action=='prepare':require(args.helper_case is not None,'explicit retained helper case required');prepare(args.helper_case)
|
|
else:require(args.id is not None,'explicit existing intent-store case required');readback(args.id)
|
|
|
|
|
|
if __name__=='__main__':main()
|