From 655572aa5b5495be6d98972a3f4076ecc021d7c3 Mon Sep 17 00:00:00 2001 From: Kevin Janssen Date: Sat, 14 Nov 2026 07:19:50 +0100 Subject: [PATCH] Prepare protected empty Windows delegation store without runtime changes --- deploy/windows/system_intent_bootstrap.py | 116 ++++++++++++++++++++++ docs/handover.md | 7 ++ docs/windows-intent-store-preparation.md | 35 +++++++ 3 files changed, 158 insertions(+) create mode 100644 deploy/windows/system_intent_bootstrap.py create mode 100644 docs/windows-intent-store-preparation.md diff --git a/deploy/windows/system_intent_bootstrap.py b/deploy/windows/system_intent_bootstrap.py new file mode 100644 index 0000000..e20fcab --- /dev/null +++ b/deploy/windows/system_intent_bootstrap.py @@ -0,0 +1,116 @@ +#!/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() diff --git a/docs/handover.md b/docs/handover.md index 6dd35c6..80281e1 100644 --- a/docs/handover.md +++ b/docs/handover.md @@ -53,6 +53,13 @@ Zugänge und private Rohbelege bleiben gitignoriert. ## Aktuelle Windowsfortsetzung +Eigene Intentablage auf dem Windowsgast einmal vorbereitet und separat nur +lesend verifiziert, Fall `f322a4d2…`: geschütztes Verzeichnis und genau zwei +Admin-owned0B-Leaves mit Actor-RW/Synchronize ohne Delete/Owner/DACLrechte. +Agent5140/Helper6240 und ursprüngliche Metadaten/Policies erhalten, zentrale +Zähler unverändert. Keine SQLiteinitialisierung, keine PERSIST-/Hotjournal- +oder Agenttoken-Funktionsabnahme. [Tatsächlicher Vorbereitungsbeleg](windows-intent-store-preparation.md). + Direkter produktiver Prozess-Peerproof im neuen Fall `d792c4c6…` bestanden: eigener SYSTEM-Parent3992 prüfte unverändert Agent5140 mit tatsächlicher Startzeit `134390970107200328`, SCM-/Token-/Image-/Dateibindung,20ms. Kein diff --git a/docs/windows-intent-store-preparation.md b/docs/windows-intent-store-preparation.md new file mode 100644 index 0000000..74b10dd --- /dev/null +++ b/docs/windows-intent-store-preparation.md @@ -0,0 +1,35 @@ +# Windows: geschützte leere Intentablage vorbereitet + +Stand2026-11-14. Tatsächlicher Windows-11-Testgast am endgültigen Cloudserver; +Notebook weiterhin ausschließlich Entwicklungsrechner. Dies ist eine eng +begrenzte Vorbereitung eigener Komponenten, keine RMM-Jobausführung. + +Die unabhängig quellgeprüfte Quelle `deploy/windows/system_intent_bootstrap.py` +(SHA256 `7597ac0f3176cc43a2f2d955f38650d74bfdcd6eda898d2221a2842082cfe7bd`) +wurde im neuen Fall `f322a4d2-c537-4842-bf04-658ad8f814b0` einmal ausgeführt. +Anschließender separater Readback bestand ohne neue Remoteänderung. + +Erstellt wurden ausschließlich: + +- `C:\ProgramData\RustDiscoverySystem\agent-intents`, SYSTEM-/Adminbesitz, + Agent-Service-SID nur ReadAndExecute, ohne Anlage-/Löschrecht; +- `system-intents.sqlite` und `system-intents.sqlite-journal`, beide0Bytes, + Adminbesitz, SYSTEM/Administratoren FullControl, tatsächliche Agent-Service-SID + exakt Read/Write/Synchronize (`0x12019f`). Keine Owner-/DACL-/Delete-Rechte. + +Native ACL-/Owner-/Reparseprüfungen und Vorher-/Nachhervergleich bestanden. +Agent5140 und Helper6240, deren Konfiguration und öffentliche Pins sowie private +Helper-/Geräteschlüsselmetadaten blieben erhalten. Keine privaten Schlüssel +gelesen, kein Dienststart/-stop, keine Clock-, Policy- oder Capabilityänderung. +Zentrale Jobzähler und Flags wurden separat gelesen und stimmten mit dem +vorhergehenden Peer-Kontrollbeleg überein: Windows0/0/0/0, Linux30/30/26/0. + +Die privaten unveränderten Rohbelege und `acceptance.json` liegen unter +`devstate/windows-client/system-intent-bootstrap/f322a4d2-c537-4842-bf04-658ad8f814b0/`. +Der ursprüngliche Helper-Bootstrapfall wird nicht überschrieben. + +**Noch offen:** tatsächliche SQLite-PERSIST-/Sharing-/Hotjournalfunktion und +Zugriff unter dem echten Agenttoken. Keine SQLiteinitialisierung oder +synthetischen Grants/Requests in diesen Dateien. Die Dateivorbereitung belegt +keinen SYSTEM-Nichtstart-/Mirror-/Sync- oder Jobpfad. Dessen unveränderte Grenzen +stehen im [Abandonvertrag](windows-system-abandon.md).