Prepare reviewed preserving joint Windows component upgrade
Rust development slice / linux (push) Failing after 6s

This commit is contained in:
2026-11-14 08:09:58 +01:00
parent 3963d04c56
commit 31a76ab289
3 changed files with 643 additions and 0 deletions
+476
View File
@@ -0,0 +1,476 @@
#!/usr/bin/env python3
"""Preserving, passive joint upgrade of the two existing Windows components.
No install/re-enrollment, job, clock/policy enablement or automatic recovery.
The original helper bootstrap and runtime evidence remain immutable. A lost
mutation reply permits finish/readback only; enter and starts are create-once.
"""
import argparse
import base64
import fcntl
import hashlib
import json
import os
from pathlib import Path
import re
import subprocess
import uuid
import client_bootstrap as cb
import auto_transport_acceptance as auto
import transport_acceptance as transport
import system_delegation_acceptance as qualification
import system_helper_bootstrap as original_helper
require = cb.contract.require
ROOT = cb.ROOT
STATE = cb.EVIDENCE / 'system-delegation-upgrade'
CURRENT = cb.EVIDENCE / 'current-runtime.json'
COMPONENTS = cb.EVIDENCE / 'current-components.json'
OLD_AGENT = '2beed7fa50a6c6379edcbc7c90374a8d648ac9e4a47ab280ec441b0bfc434a24'
OLD_HELPER = '921cf1822f128c3e37ca4c0250f08309a14d760453fa3b56a589229c6614353e'
OLD_POLICY = 'a049a747579e7e6155609fc4f095e714aff27272a3dc34e8b98e77eb445012b0'
OLD_PIN = '6aacf100bac02e2e0dd432a85c5745879fb15cc35cb4f81bce411af2052d025e'
ORIGINAL_HELPER = cb.EVIDENCE / 'system-helper-bootstrap/59c2fd6f-0503-46fd-88f3-985bca376c51/intent.json'
INTENT_PREPARATION = cb.EVIDENCE / 'system-intent-bootstrap/f322a4d2-c537-4842-bf04-658ad8f814b0/acceptance.json'
INTENT_PREPARATION_SHA = 'c4ef6fed8440d3405e0a1e65c0b97f37563d44d2c41d406020400a288e670e7b'
def sha(path):
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def raw_sha(value):
return hashlib.sha256(value).hexdigest()
def canonical(value):
return json.dumps(value, ensure_ascii=False, separators=(',', ':')).encode()
def save(path, value):
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
cb.contract.write_private(path, value)
def passive_settings(old, agent, helper):
require(set(old) == {'schema_version', 'binding', 'agent', 'helper', 'allowed_services',
'max_runtime_seconds', 'enable_effects', 'allow_reboot'} and type(old['schema_version']) is int and old['schema_version'] == 1
and old['allowed_services'] == [] and old['enable_effects'] is False and old['allow_reboot'] is False
and type(old['max_runtime_seconds']) is int and old['max_runtime_seconds'] == 30, 'exact closed passive settings')
require(old['agent']['binary_sha256'] == OLD_AGENT and old['helper']['binary_sha256'] == OLD_HELPER,
'independently known old image pins')
for value in (agent, helper):
require(isinstance(value, str) and len(value) == 64 and all(c in '0123456789abcdef' for c in value), 'exact new image hash')
new = json.loads(canonical(old))
new['agent']['binary_sha256'] = agent
new['helper']['binary_sha256'] = helper
policy = raw_sha(canonical(new))
pin = dict(schema_version=1, binding=new['binding'], policy_sha256=policy, agent=new['agent'], helper=new['helper'])
return canonical(new), canonical(pin), policy
SCRIPT = r'''
$ErrorActionPreference='Stop';$p=$global:RmmDelegationUpgradePayload
if(!$p-or[guid]::ParseExact($p.id,'D').ToString()-cne$p.id-or$p.action-notin@('state','enter','finish','readback')){throw 'Fixed passive joint intent'}
foreach($field in @('old_agent','old_helper','new_agent','new_helper','old_policy','old_pin','new_policy','new_pin','config_sha256','probe_sha256','system_probe_sha256','manifest_sha256','qualification_sha256')){if($p.$field-notmatch'^[a-f0-9]{64}$'){throw 'Exact joint pins'}}
if($p.old_agent-cne'2beed7fa50a6c6379edcbc7c90374a8d648ac9e4a47ab280ec441b0bfc434a24'-or$p.old_helper-cne'921cf1822f128c3e37ca4c0250f08309a14d760453fa3b56a589229c6614353e'-or$p.old_policy-cne'a049a747579e7e6155609fc4f095e714aff27272a3dc34e8b98e77eb445012b0'-or$p.old_pin-cne'6aacf100bac02e2e0dd432a85c5745879fb15cc35cb4f81bce411af2052d025e'){throw 'Known original component generation'}
$boot='C:\ProgramData\RustDiscoveryBootstrap';$folder=Join-Path $boot ('system-delegation-'+$p.id);$active=Join-Path $boot 'system-delegation-active-intent.json'
$agentRoot='C:\ProgramData\RustDiscovery';$agentState=Join-Path $agentRoot 'state';$helperRoot='C:\ProgramData\RustDiscoverySystem';$helperState=Join-Path $helperRoot 'state'
$config=Join-Path $agentRoot 'config.json';$settings=Join-Path $helperRoot 'helper.json';$pin=Join-Path $helperRoot 'agent-pin.json'
$agentBinary='C:\Program Files\RustDiscovery\rmm-agent-windows.exe';$helperBinary='C:\Program Files\RustDiscovery\rmm-helper-windows.exe'
$agentName='RmmDiscoveryWindows';$helperName='RmmDiscoverySystemHelper';$sys='S-1-5-18';$admin='S-1-5-32-544'
$agentSid=(New-Object Security.Principal.NTAccount('NT SERVICE',$agentName)).Translate([Security.Principal.SecurityIdentifier]).Value
$helperSid=(New-Object Security.Principal.NTAccount('NT SERVICE',$helperName)).Translate([Security.Principal.SecurityIdentifier]).Value
function Check($path,[bool]$directory,[bool]$agentOwned=$false){
$item=Get-Item -LiteralPath $path -Force;if($item.PSIsContainer-ne$directory-or($item.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Fixed regular path'}
$parent=$item.Directory;if($directory){$parent=$item.Parent};while($null-ne$parent){if($parent.Attributes-band[IO.FileAttributes]::ReparsePoint){throw 'Reparse ancestor'};$parent=$parent.Parent}
$acl=Get-Acl -LiteralPath $path;$allowed=@($sys,$admin,$agentSid,$helperSid);if($agentOwned){$allowed+=@('S-1-5-19')}
if($acl.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin$allowed){throw 'Protected owner'}
$rules=@($acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if(!$rules.Count){throw 'Empty private DACL'}
foreach($rule in $rules){if($rule.AccessControlType-ne'Allow'-or$rule.IdentityReference.Value-notin$allowed){throw 'Broad private DACL'}}
}
function BytesHash([byte[]]$bytes){$h=[Security.Cryptography.SHA256]::Create();try{return([BitConverter]::ToString($h.ComputeHash($bytes))).Replace('-','').ToLowerInvariant()}finally{$h.Dispose()}}
function Hash($path,[bool]$agentOwned=$false){Check $path $false $agentOwned;return(Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant()}
function AclHash($path){return BytesHash ([Text.Encoding]::UTF8.GetBytes((Get-Acl -LiteralPath $path).Sddl))}
function CheckControl($path,[bool]$directory){Check $path $directory;$acl=Get-Acl -LiteralPath $path;if($acl.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@($sys,$admin)){throw 'Bootstrap controller owner'};foreach($rule in $acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])){if($rule.AccessControlType-ne'Allow'-or$rule.IdentityReference.Value-notin@($sys,$admin)){throw 'Bootstrap controller DACL'}}}
function PrivateBackupAcl($path){$acl=New-Object Security.AccessControl.FileSecurity;$acl.SetSecurityDescriptorSddlForm('O:BAG:BAD:P(A;;FA;;;SY)(A;;FA;;;BA)');Set-Acl -LiteralPath $path -AclObject $acl;CheckControl $path $false}
function JsonEqual($a,$b){return(($a|ConvertTo-Json -Depth 40 -Compress)-ceq($b|ConvertTo-Json -Depth 40 -Compress))}
function WriteBytes($path,[byte[]]$bytes){$file=[IO.File]::Open($path,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::Read);try{$file.Write($bytes,0,$bytes.Length);$file.Flush($true)}finally{$file.Dispose()}}
function WriteNew($path,$value){WriteBytes $path ([Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 40 -Compress)))}
function FlushCopy($path){$file=[IO.File]::Open($path,[IO.FileMode]::Open,[IO.FileAccess]::ReadWrite,[IO.FileShare]::Read);try{$file.Flush($true)}finally{$file.Dispose()}}
function Service($role){
if($role-ceq'agent'){$name=$agentName;$image=$agentBinary;$owner='S-1-5-19';$mode='Auto';$command='"C:\Program Files\RustDiscovery\rmm-agent-windows.exe" --service --config "C:\ProgramData\RustDiscovery\config.json"'}elseif($role-ceq'helper'){$name=$helperName;$image=$helperBinary;$owner=$sys;$mode='Manual';$command='"C:\Program Files\RustDiscovery\rmm-helper-windows.exe" --service'}else{throw 'Fixed component role'}
$service=Get-CimInstance Win32_Service -Filter ("Name='"+$name+"'") -OperationTimeoutSec 10
if(!$service-or$service.StartMode-cne$mode-or$service.PathName-cne$command-or$service.ServiceType-cne'Own Process'){throw 'Original SCM configuration'}
if(($role-ceq'agent'-and$service.StartName-cne'NT AUTHORITY\LocalService')-or($role-ceq'helper'-and$service.StartName-notin@('LocalSystem','NT AUTHORITY\SYSTEM'))){throw 'Original service account'}
if(@((Get-Service -Name $name).ServicesDependedOn).Count-ne0){throw 'No implicit dependency starts'}
$sidType=Get-ItemPropertyValue -LiteralPath ('HKLM:\SYSTEM\CurrentControlSet\Services\'+$name) -Name ServiceSidType;if($sidType-ne1){throw 'Original unrestricted service SID'}
$sddl=@(& 'C:\Windows\System32\sc.exe' sdshow $name);if($LASTEXITCODE-ne0){throw 'SCM ACL query'};$text=($sddl-join"`n").Trim();if(!$text-or$text.Length-gt8192){throw 'Bounded service ACL'}
$processId=[int]$service.ProcessId;$creation=$null;$actualOwner=$null
if($service.State-ceq'Running'){$process=Get-CimInstance Win32_Process -Filter ('ProcessId='+$processId) -OperationTimeoutSec 10;$actualOwner=(Invoke-CimMethod -InputObject $process -MethodName GetOwnerSid -OperationTimeoutSec 10).Sid;if($actualOwner-cne$owner-or$process.ExecutablePath-cne$image){throw 'Actual component role'};$native=[Diagnostics.Process]::GetProcessById($processId);try{$creation=$native.StartTime.ToUniversalTime().ToFileTimeUtc().ToString()}finally{$native.Dispose()}}
elseif($service.State-cne'Stopped'-or$processId-ne0){throw 'Unsettled component service'}
return [ordered]@{state=$service.State;pid=$processId;creation_filetime=$creation;owner_sid=$actualOwner;start_name=$service.StartName;start_mode=$service.StartMode;path=$service.PathName;service_type=$service.ServiceType;sid_type=$sidType;service_acl_sha256=(BytesHash ([Text.Encoding]::UTF8.GetBytes($text)))}
}
function Probe($kind){
if($kind-ceq'agent'){$hash=$p.probe_sha256;$name='RuntimeStateProbe.exe'}elseif($kind-ceq'helper'){$hash=$p.system_probe_sha256;$name='SystemStateProbe.exe'}else{throw 'Fixed witness'}
$binary=Join-Path (Join-Path $boot $hash) $name;if((Hash $binary)-cne$hash){throw 'Qualified readonly witness bytes'}
$start=New-Object Diagnostics.ProcessStartInfo;$start.FileName=$binary;$start.UseShellExecute=$false;$start.CreateNoWindow=$true;$start.RedirectStandardOutput=$true;$start.RedirectStandardError=$true
$process=New-Object Diagnostics.Process;$process.StartInfo=$start;if(!$process.Start()){throw 'Witness start'}
try{$output=$process.StandardOutput.ReadToEndAsync();$errorOutput=$process.StandardError.ReadToEndAsync();if(!$process.WaitForExit(20000)){$process.Kill();throw 'Readonly witness timeout'};if($process.ExitCode-ne0-or$output.Result.Length-gt65536-or$errorOutput.Result.Length){throw 'Readonly witness refusal'};return($output.Result|ConvertFrom-Json)}finally{$process.Dispose()}
}
function Diagnostic($path,[bool]$agent){
if(!(Test-Path -LiteralPath $path)){return $null};Check $path $false $agent;$item=Get-Item -LiteralPath $path -Force;$limit=1024;if($agent){$limit=8192};if($item.Length-gt$limit){throw 'Bounded fixed diagnostic'}
return(Get-Content -LiteralPath $path -Raw|ConvertFrom-Json)
}
function RawAgentProbe{ $path=Join-Path $agentState 'helper-probe.json';if(!(Test-Path -LiteralPath $path)){return $null};Check $path $false $true;if((Get-Item -LiteralPath $path).Length-gt8192){throw 'Bounded native probe bytes'};return [Convert]::ToBase64String([IO.File]::ReadAllBytes($path)) }
function EmptyIntentStore($witness){
$directory=Join-Path $helperRoot 'agent-intents';Check $directory $true;$acl=Get-Acl -LiteralPath $directory;if(!$acl.AreAccessRulesProtected-or$acl.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@($sys,$admin)){throw 'Prepared intent directory owner/DACL'}
$seen=@{};foreach($rule in $acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])){$id=$rule.IdentityReference.Value;$rights=[int64]$rule.FileSystemRights;if($rule.AccessControlType-ne'Allow'-or$id-notin@($sys,$admin,$agentSid)-or($id-ceq$agentSid-and$rights-ne0x1200a9)-or($id-cne$agentSid-and$rights-ne2032127)){throw 'No actor directory create/delete'};$seen[$id]=$true};foreach($id in @($sys,$admin,$agentSid)){if(!$seen[$id]){throw 'Prepared directory role missing'}}
$children=@(Get-ChildItem -LiteralPath $directory -Force);if($children.Count-ne2-or!$witness-or$witness.sqlite_initialized-ne$false){throw 'Exactly two uninitialized leaves'}
foreach($label in @('database','journal')){$expected=$p.intent_leaves.$label;$path=Join-Path $directory $expected.name;Check $path $false;$item=Get-Item -LiteralPath $path -Force;if($item.Length-ne0-or(AclHash $path)-cne$expected.acl_sha256-or$witness.leaves.$label.bytes-ne0){throw 'Original exact zero-byte leaf/ACL'};if($expected.name-notin@('system-intents.sqlite','system-intents.sqlite-journal')){throw 'Fixed intent leaf'}}
}
function State([bool]$new){
foreach($directory in @('C:\Program Files\RustDiscovery',$agentRoot,$agentState,$helperRoot,$helperState,$boot)){Check $directory $true}
if((Hash $config)-cne$p.config_sha256){throw 'Exact unchanged auto config'};$cfg=Get-Content -LiteralPath $config -Raw|ConvertFrom-Json
if((($cfg.PSObject.Properties.Name|Sort-Object)-join',')-cne'ca_file,connect_address,enrollment_token_file,server_name,state_directory,transport'-or$cfg.transport-cne'auto'-or$cfg.server_name-cne'discovery.ease-technologies.de'-or$cfg.state_directory-cne$agentState-or$cfg.ca_file-cne(Join-Path $agentRoot 'server-ca.pem')-or$cfg.enrollment_token_file-cne(Join-Path $agentState 'enrollment.token')){throw 'Original six-field passive config'}
foreach($absent in @($cfg.enrollment_token_file,(Join-Path $agentRoot 'binding.json'),(Join-Path $agentState 'consumption.sqlite'),(Join-Path $agentState 'jobs'))){if(Test-Path -LiteralPath $absent){throw 'No binding or job ledger in passive upgrade'}}
$expectedAgent=$p.old_agent;$expectedHelper=$p.old_helper;$expectedPolicy=$p.old_policy;$expectedPin=$p.old_pin;if($new){$expectedAgent=$p.new_agent;$expectedHelper=$p.new_helper;$expectedPolicy=$p.new_policy;$expectedPin=$p.new_pin}
if((Hash $agentBinary)-cne$expectedAgent-or(Hash $helperBinary)-cne$expectedHelper-or(Hash $settings)-cne$expectedPolicy-or(Hash $pin)-cne$expectedPin){throw 'Complete exact component generation'}
$setting=Get-Content -LiteralPath $settings -Raw|ConvertFrom-Json;$agentPin=Get-Content -LiteralPath $pin -Raw|ConvertFrom-Json
if($setting.enable_effects-isnot[bool]-or$setting.enable_effects-or$setting.allow_reboot-isnot[bool]-or$setting.allow_reboot-or@($setting.allowed_services).Count-ne0-or$setting.max_runtime_seconds-ne30-or$setting.schema_version-ne1-or$agentPin.policy_sha256-cne$expectedPolicy-or$setting.agent.binary_sha256-cne$expectedAgent-or$setting.helper.binary_sha256-cne$expectedHelper-or!(JsonEqual $setting.binding $agentPin.binding)-or!(JsonEqual $setting.agent $agentPin.agent)-or!(JsonEqual $setting.helper $agentPin.helper)){throw 'Exact closed reciprocal settings'}
$identity=Get-Content -LiteralPath (Join-Path $agentState 'identity.json') -Raw|ConvertFrom-Json;if($identity.agent_id-cne'63ea15b2-0643-403d-b5b4-cba1288dbea3'-or$identity.asset_id-cne'a176520e-8a91-4e93-a78b-8e7620f430e0'){throw 'Original enrolled identity'}
$public=[ordered]@{};$acls=[ordered]@{};foreach($entry in @(@('ca',$cfg.ca_file),@('identity',(Join-Path $agentState 'identity.json')),@('certificate',(Join-Path $agentState 'device.pem')))){$public[$entry[0]]=Hash $entry[1] $true;$acls[$entry[0]]=AclHash $entry[1]}
$key=Join-Path $agentState 'device.key';Check $key $false $true;$keyItem=Get-Item -LiteralPath $key -Force;$acls.private_key=AclHash $key
$agentService=Service 'agent';$helperService=Service 'helper';$agentProbe=Probe 'agent';$helperProbe=Probe 'helper'
if($agentProbe.read_only-ne$true-or$agentProbe.integrity-cne'ok'-or$agentProbe.private_key_read-ne$false-or$agentProbe.consumption_exists-ne$false-or$agentProbe.jobs_directory_exists-ne$false-or$helperProbe.schema_version-ne1-or$helperProbe.read_only-ne$true-or$helperProbe.bootstrap_administrator-ne$true-or$helperProbe.type-cne'rmm.windows.system-state-witness'-or$helperProbe.helper_ledger.integrity-cne'ok'-or$helperProbe.helper_ledger.connected_native_file_id_verified-ne$true-or$helperProbe.helper_ledger.journal_mode-cne'delete'-or$helperProbe.helper_ledger.page_size-ne4096-or$helperProbe.private_key_read-ne$false-or$helperProbe.private_rows_returned-ne$false-or$helperProbe.jobs_created-ne$false-or$helperProbe.clock_queried-ne$false){throw 'Readonly original journal witnesses'}
EmptyIntentStore $helperProbe.intent_store
$fixed=@('ledger.sqlite','executor.lock','pipe-last-error.json','.pipe-last-error.pending');foreach($item in Get-ChildItem -LiteralPath $helperState -Force){if($item.Name-notin$fixed-or$item.PSIsContainer){throw 'Unexpected helper state child'};Check $item.FullName $false;if($item.Name-in@('pipe-last-error.json','.pipe-last-error.pending')-and$item.Length-gt1024){throw 'Bounded helper diagnostic staging'}}
$frozen=$null;if($agentService.state-ceq'Stopped'-and$helperService.state-ceq'Stopped'){$frozen=[ordered]@{telemetry=(Hash (Join-Path $agentState 'telemetry.sqlite') $true);helper_ledger=(Hash (Join-Path $helperState 'ledger.sqlite'));executor_lock=(Hash (Join-Path $helperState 'executor.lock'))}}
return [ordered]@{agent_id=$identity.agent_id;asset_id=$identity.asset_id;binary_sha256=$expectedAgent;helper_sha256=$expectedHelper;policy_sha256=$expectedPolicy;pin_sha256=$expectedPin;config_sha256=$p.config_sha256;config_acl_sha256=(AclHash $config);binary_acl_sha256=(AclHash $agentBinary);helper_binary_acl_sha256=(AclHash $helperBinary);settings_acl_sha256=(AclHash $settings);pin_acl_sha256=(AclHash $pin);public_hashes=$public;identity_acls=$acls;private_key_metadata=[ordered]@{length=$keyItem.Length;creation_ticks=$keyItem.CreationTimeUtc.Ticks.ToString();last_write_ticks=$keyItem.LastWriteTimeUtc.Ticks.ToString()};private_key_read=$false;service=$agentService;helper_service=$helperService;journal=$agentProbe;helper_witness=$helperProbe;frozen_sha256=$frozen;agent_probe_raw_base64=(RawAgentProbe);agent_probe=(Diagnostic (Join-Path $agentState 'helper-probe.json') $true);helper_diagnostic=(Diagnostic (Join-Path $helperState 'pipe-last-error.json') $false)}
}
function Preserved($before,$after,[bool]$frozen){
foreach($field in @('agent_id','asset_id','config_sha256','config_acl_sha256','binary_acl_sha256','helper_binary_acl_sha256','settings_acl_sha256','pin_acl_sha256','public_hashes','identity_acls','private_key_metadata')){if(!(JsonEqual $before.$field $after.$field)){throw 'Preserved identity config or ACL'}}
foreach($role in @('service','helper_service')){foreach($field in @('start_name','start_mode','path','service_type','sid_type','service_acl_sha256')){if(!(JsonEqual $before.$role.$field $after.$role.$field)){throw 'Original SCM invariant'}}}
foreach($field in @('database_file_id','database_creation','identity_sha256','schema')){if(!(JsonEqual $before.journal.$field $after.journal.$field)){throw 'Original telemetry identity/schema'}}
if($after.journal.sequence-lt$before.journal.sequence){throw 'Sequence regression'};foreach($field in $after.journal.core_counts.PSObject.Properties){if($field.Value-ne0){throw 'Unexpected job/sync rows'}}
foreach($field in @('helper_ledger','executor_lock','intent_store')){if(!(JsonEqual $before.helper_witness.$field $after.helper_witness.$field)){throw 'Original helper database/rows/lock/zero-byte intent leaves'}}
if($frozen){if(!(JsonEqual $before.frozen_sha256 $after.frozen_sha256)){throw 'Stopped database byte change'};foreach($field in @('metadata_sha256','events_sha256','sequence')){if(!(JsonEqual $before.journal.$field $after.journal.$field)){throw 'Stopped telemetry rows changed'}}}
}
function ReadIntent{CheckControl $folder $true;CheckControl (Join-Path $folder 'intent.json') $false;$intent=Get-Content -LiteralPath (Join-Path $folder 'intent.json') -Raw|ConvertFrom-Json;foreach($field in $p.PSObject.Properties.Name){if($field-cne'action'-and!(JsonEqual $intent.payload.$field $p.$field)){throw 'Original joint intent'}};if(Test-Path -LiteralPath $active){CheckControl $active $false;$current=Get-Content -LiteralPath $active -Raw|ConvertFrom-Json;if($current.id-cne$p.id-or$current.manifest_sha256-cne$p.manifest_sha256){throw 'Another joint transition'}}elseif($p.action-cne'readback'){throw 'Original active intent missing'};return $intent}
function PinProcess($role,$record){$expected=5140;if($role-ceq'helper'){$expected=6240};if($record.state-cne'Running'-or$record.pid-ne$expected){throw 'Known original live PID'};$process=[Diagnostics.Process]::GetProcessById($expected);$null=$process.Handle;if($process.HasExited-or$process.StartTime.ToUniversalTime().ToFileTimeUtc().ToString()-cne$record.creation_filetime){$process.Dispose();throw 'Pinned original process birth'};return $process}
function StopPinned($role,$held,$record){$live=Service $role;if($live.pid-ne$record.pid-or$live.creation_filetime-cne$record.creation_filetime-or$held.HasExited){throw 'Original process changed before stop'};$name=$agentName;if($role-ceq'helper'){$name=$helperName};WriteNew (Join-Path $folder ($role+'-stop-attempt.json')) @{pid=$record.pid;creation=$record.creation_filetime;stop_once=$true};Stop-Service -Name $name;(Get-Service -Name $name).WaitForStatus([ServiceProcess.ServiceControllerStatus]::Stopped,[TimeSpan]::FromSeconds(20));if(!$held.WaitForExit(20000)){throw 'Original process still alive'};WriteNew (Join-Path $folder ($role+'-stopped.json')) @{pid=$record.pid;creation=$record.creation_filetime;process_exited=$true}}
function Backup($label,$path,$expected){if((Hash $path)-cne$expected){throw 'Known original backup bytes'};$backup=Join-Path $folder ($label+'-original');[IO.File]::Copy($path,$backup,$false);PrivateBackupAcl $backup;FlushCopy $backup;if((Hash $backup)-cne$expected){throw 'Original backup mismatch'};WriteNew (Join-Path $folder ($label+'-backup.json')) @{sha256=$expected;original_sddl=(Get-Acl -LiteralPath $path).Sddl}}
function Swap($label,$destination,$source,$oldHash,$newHash){if((Get-Service -Name $agentName).Status-ne[ServiceProcess.ServiceControllerStatus]::Stopped-or(Get-Service -Name $helperName).Status-ne[ServiceProcess.ServiceControllerStatus]::Stopped){throw 'Both stopped throughout all four replacements'};if((Hash $destination)-cne$oldHash-or(Hash $source)-cne$newHash-or(Hash (Join-Path $folder ($label+'-original')))-cne$oldHash){throw 'Four-file CAS'};$candidate=Join-Path $folder ($label+'-candidate');$sddl=(Get-Acl -LiteralPath $destination).Sddl;[IO.File]::Copy($source,$candidate,$false);FlushCopy $candidate;WriteNew (Join-Path $folder ($label+'-replace-attempt.json')) @{old_sha256=$oldHash;new_sha256=$newHash;original_sddl=$sddl};[IO.File]::Replace($candidate,$destination,$null);$acl=New-Object Security.AccessControl.FileSecurity;$acl.SetSecurityDescriptorSddlForm($sddl);Set-Acl -LiteralPath $destination -AclObject $acl;if((Hash $destination)-cne$newHash){throw 'Replaced exact file bytes'};WriteNew (Join-Path $folder ($label+'-replaced.json')) @{old_sha256=$oldHash;new_sha256=$newHash;backup_sha256=(Hash (Join-Path $folder ($label+'-original')));acl_sha256=(AclHash $destination)}}
function StartOnce($role){$name=$helperName;if($role-ceq'agent'){$name=$agentName};if((Service $role).state-cne'Stopped'){throw 'Exact first start only'};WriteNew (Join-Path $folder ($role+'-start-attempt.json')) @{start_once=$true};Start-Service -Name $name;(Get-Service -Name $name).WaitForStatus([ServiceProcess.ServiceControllerStatus]::Running,[TimeSpan]::FromSeconds(20));WriteNew (Join-Path $folder ($role+'-started.json')) (Service $role)}
CheckControl $boot $true
if($p.action-ceq'state'){State $false|ConvertTo-Json -Depth 40 -Compress;exit 0}
if($p.action-ceq'readback'){$intent=ReadIntent;$hashes=[ordered]@{agent=(Hash $agentBinary);helper=(Hash $helperBinary);settings=(Hash $settings);pin=(Hash $pin)};$phases=[ordered]@{};foreach($label in @('agent-stopped','helper-stopped','frozen','agent-backup','helper-backup','settings-backup','pin-backup','agent-replaced','helper-replaced','settings-replaced','pin-replaced','swapped','helper-start-attempt','helper-started','agent-start-attempt','agent-started','entered')){$phases[$label]=Test-Path -LiteralPath (Join-Path $folder ($label+'.json'))};@{read_only=$true;id=$p.id;hashes=$hashes;service=(Service 'agent');helper_service=(Service 'helper');phase_receipts=$phases}|ConvertTo-Json -Depth 40 -Compress;exit 0}
if($p.action-ceq'finish'){$intent=ReadIntent;$after=State $true;foreach($role in @('agent','helper')){$startedPath=Join-Path $folder ($role+'-started.json');CheckControl $startedPath $false;$started=Get-Content -LiteralPath $startedPath -Raw|ConvertFrom-Json;$live=$after.service;if($role-ceq'helper'){$live=$after.helper_service};if($live.pid-ne$started.pid-or$live.creation_filetime-cne$started.creation_filetime){throw 'Original single-start component instance changed'}};Preserved $intent.before $after $false;$frozen=Get-Content -LiteralPath (Join-Path $folder 'frozen.json') -Raw|ConvertFrom-Json;Preserved $frozen $after $false;if($after.service.state-cne'Running'-or$after.helper_service.state-cne'Running'){throw 'Selected components not running; no repeated start'};@{read_only=$true;completed=$true;id=$p.id;native=$after;original=$intent.before;frozen=$frozen}|ConvertTo-Json -Depth 40 -Compress;exit 0}
if((Test-Path -LiteralPath $folder)-or(Test-Path -LiteralPath $active)){throw 'Existing joint intent: readback only'}
$before=State $false;if($before.journal.pending_inventory_events-ne0){throw 'Concrete original inventory ACK required'}
$heldAgent=PinProcess 'agent' $before.service;$heldHelper=PinProcess 'helper' $before.helper_service
try{
New-Item -ItemType Directory -Path $folder|Out-Null;CheckControl $folder $true
WriteNew (Join-Path $folder 'intent.json') @{payload=$p;before=$before};WriteNew $active @{id=$p.id;manifest_sha256=$p.manifest_sha256;no_jobs=$true}
StopPinned 'agent' $heldAgent $before.service;StopPinned 'helper' $heldHelper $before.helper_service
$frozen=State $false;Preserved $before $frozen $false;if($frozen.service.state-cne'Stopped'-or$frozen.helper_service.state-cne'Stopped'-or$frozen.journal.pending_inventory_events-ne0){throw 'Both stopped and original inventory settled'};WriteNew (Join-Path $folder 'frozen.json') $frozen
Backup 'agent' $agentBinary $p.old_agent;Backup 'helper' $helperBinary $p.old_helper;Backup 'settings' $settings $p.old_policy;Backup 'pin' $pin $p.old_pin
$settingBytes=[Convert]::FromBase64String($p.settings_base64);$pinBytes=[Convert]::FromBase64String($p.pin_base64);if((BytesHash $settingBytes)-cne$p.new_policy-or(BytesHash $pinBytes)-cne$p.new_pin){throw 'Deterministic public settings bytes'}
WriteBytes (Join-Path $folder 'new-helper.json') $settingBytes;WriteBytes (Join-Path $folder 'new-agent-pin.json') $pinBytes
Swap 'agent' $agentBinary (Join-Path (Join-Path $boot $p.new_agent) 'rmm-agent-windows.exe') $p.old_agent $p.new_agent
Swap 'helper' $helperBinary (Join-Path (Join-Path $boot $p.new_helper) 'rmm-helper-windows.exe') $p.old_helper $p.new_helper
Swap 'settings' $settings (Join-Path $folder 'new-helper.json') $p.old_policy $p.new_policy
Swap 'pin' $pin (Join-Path $folder 'new-agent-pin.json') $p.old_pin $p.new_pin
$swapped=State $true;Preserved $frozen $swapped $true;if($swapped.service.state-cne'Stopped'-or$swapped.helper_service.state-cne'Stopped'){throw 'No mixed component start'};WriteNew (Join-Path $folder 'swapped.json') $swapped
StartOnce 'helper';StartOnce 'agent';$after=State $true;Preserved $before $after $false;WriteNew (Join-Path $folder 'entered.json') $after
@{entered=$true;id=$p.id;native=$after;no_jobs=$true;no_reboot=$true;no_clock_change=$true}|ConvertTo-Json -Depth 40 -Compress
}catch{if(Test-Path -LiteralPath $folder){WriteNew (Join-Path $folder ('incomplete-'+[guid]::NewGuid().ToString()+'.json')) @{incomplete=$true;error_type=$_.Exception.GetType().FullName;line=$_.InvocationInfo.ScriptLineNumber;readback_only=$true;no_retry=$true}};throw}finally{$heldAgent.Dispose();$heldHelper.Dispose()}
'''
PREPARE = transport.PREPARE_SCRIPT.replace('TransportAcceptance.ps1', 'SystemDelegationUpgrade.ps1')
LAUNCH = transport.LAUNCH_SCRIPT.replace('TransportAcceptance.ps1', 'SystemDelegationUpgrade.ps1').replace('RmmTransportPayload', 'RmmDelegationUpgradePayload')
def script_guards():
ordered = (" StopPinned 'agent'", "StopPinned 'helper'", " Backup 'agent'", "Backup 'pin'",
" Swap 'agent'", "Swap 'pin'", '$swapped=State $true', " StartOnce 'helper'", "StartOnce 'agent'")
positions = [SCRIPT.index(value) for value in ordered]
require(positions == sorted(positions) and len(set(positions)) == len(positions), 'reviewed stop/backup/four-replace/start ordering')
require(SCRIPT.count('Start-Service -Name $name') == SCRIPT.count('Stop-Service -Name $name') == 1,
'one fixed-role service control implementation')
require(all(value not in SCRIPT + LAUNCH for value in ('ScriptBlock', 'Invoke-Expression', 'Bypass',
'Restart-Service', 'New-Service', 'Set-Service', 'Remove-Item', 'Restart-Computer', 'Stop-Computer')),
'no free interpreter, install, cleanup or recovery actions')
def qualified(manifest_path, proof_path):
script_guards()
manifest = qualification.verified(manifest_path)
proof = cb.contract.protected_json(proof_path)
require(proof.get('verified') is True and proof['manifest_path'] == str(manifest_path.resolve())
and proof['manifest_sha256'] == sha(manifest_path) and proof.get('no_jobs') is True
and proof.get('clock_adapter_qualified') is False and proof.get('local_service_proof') is False,
'actual source-bound native units, never an execution/clock capability')
require(set(manifest['artifacts']) == {'agent', 'helper', 'probe', 'system_probe', 'lib', 'bin'}, 'joint artifacts and both readonly witnesses')
for kind, expected in manifest['native_counts_expected'].items():
actual = proof['native']['reports'][kind]
require(actual['sha256'] == manifest['artifacts'][kind]['sha256'] and len(actual['names']) == expected and len(set(actual['names'])) == expected
and actual['listed']['exit_code'] == actual['result']['exit_code'] == 0
and actual['listed']['timed_out'] is False and actual['result']['timed_out'] is False
and re.search(r'test result: ok\. ' + str(expected) + r' passed; 0 failed; 0 ignored; 0 measured; 0 filtered out;', actual['result']['stdout']),
'all real qualified lib/bin native units')
return manifest
def prior():
index = cb.contract.protected_json(CURRENT)
require(index['binary_sha256'] == OLD_AGENT and index.get('system_helper_client_feature') is True
and index['windows_jobs_enabled'] is False and index['clock_adapter_qualified'] is False
and index['transport'] == 'auto', 'accepted current passive agent')
evidence = Path(index['evidence']['path'])
require(evidence.resolve().is_relative_to(cb.EVIDENCE.resolve()) and sha(evidence) == index['evidence']['sha256'], 'accepted old runtime evidence')
result = cb.contract.protected_json(evidence)
require(result['verified'] is True and result['completed'] is True and result['no_jobs'] is True
and result['native']['binary_sha256'] == OLD_AGENT, 'accepted actual 2bee runtime')
helper = cb.contract.protected_json(ORIGINAL_HELPER)
payload = helper['payload']
settings = base64.b64decode(payload['settings_base64'], validate=True)
pin = base64.b64decode(payload['pin_base64'], validate=True)
require(payload['helper_sha256'] == OLD_HELPER and payload['agent_sha256'] == OLD_AGENT
and raw_sha(settings) == OLD_POLICY and raw_sha(pin) == OLD_PIN, 'original immutable helper bootstrap pins')
require(not COMPONENTS.exists(), 'first joint generation only; never adopt an unknown components index')
return index, result, json.loads(settings, object_pairs_hook=cb.contract.strict_object)
def intent_preparation():
require(sha(INTENT_PREPARATION) == INTENT_PREPARATION_SHA, 'independently accepted zero-byte preparation')
proof = cb.contract.protected_json(INTENT_PREPARATION)
require(proof['verified'] is True and proof['phase'] == 'fixed-empty-leaf-preparation-only'
and proof['sqlite_initialized'] is False and proof['sqlite_persist_or_hotjournal_qualified'] is False
and proof['agent_token_store_access_qualified'] is False, 'preparation is not store or job qualification')
created_path = INTENT_PREPARATION.parent / 'created.json'
require(sha(created_path) == proof['native_created_sha256'], 'original native preparation receipt')
created = cb.contract.protected_json(created_path)
require(created['verified'] is True and created['no_jobs'] is True and created['private_data_read'] is False
and created['actor_directory_create_or_delete'] is False and created['actor_leaf_owner_dacl_or_delete'] is False,
'actual narrow prepared ACLs only')
leaves = {leaf['name']: leaf for leaf in created['leaves']}
require(set(leaves) == {'system-intents.sqlite', 'system-intents.sqlite-journal'}
and all(v['length'] == 0 for v in leaves.values()), 'two exact native empty leaves')
return {label: dict(name=name, acl_sha256=raw_sha(leaves[name]['sddl'].encode()))
for label, name in [('database', 'system-intents.sqlite'), ('journal', 'system-intents.sqlite-journal')]}
def stage_script():
raw = SCRIPT.encode(); digest = raw_sha(raw)
result = cb.powershell(PREPARE, dict(sha256=digest))
if not result['already_uploaded']:
path = STATE / 'source' / (digest + '.ps1'); path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
if not path.exists():
fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600)
with os.fdopen(fd, 'wb') as out: out.write(raw); out.flush(); os.fsync(out.fileno())
require(sha(path) == digest, 'immutable staged source')
prefix = cb.contract.protected_json(ROOT / 'credentials/windows-dev-access.json')['ssh_prefix']
args = ['sftp'] + [a for a in prefix[1:-1] if a != '-T'] + ['-b', '-', prefix[-1]]
remote = '/C:/ProgramData/RustDiscoveryBootstrap/' + digest + '/SystemDelegationUpgrade.ps1'
done = subprocess.run(args, input=('put ' + json.dumps(str(path.resolve())) + ' ' + json.dumps(remote) + '\n').encode(), capture_output=True, timeout=60)
require(done.returncode == 0 and cb.powershell(PREPARE, dict(sha256=digest))['already_uploaded'], 'exact pinned source transfer')
return digest
def remote(intent, action):
require(intent['script_sha256'] == raw_sha(SCRIPT.encode()), 'original immutable joint source')
return cb.powershell(LAUNCH, dict(sha256=intent['script_sha256'], payload=dict(intent['payload'], action=action)), timeout=150, remote_signed=True)
def upgrade(manifest_path, proof_path):
manifest = qualified(manifest_path, proof_path)
index, previous, old_settings = prior()
settings, pin, policy = passive_settings(old_settings, manifest['artifacts']['agent']['sha256'], manifest['artifacts']['helper']['sha256'])
ident = str(uuid.uuid4()); folder = STATE / ident; folder.mkdir(mode=0o700, parents=True)
payload = dict(id=ident, old_agent=OLD_AGENT, old_helper=OLD_HELPER, old_policy=OLD_POLICY, old_pin=OLD_PIN,
new_agent=manifest['artifacts']['agent']['sha256'], new_helper=manifest['artifacts']['helper']['sha256'],
new_policy=policy, new_pin=raw_sha(pin), config_sha256=previous['native']['config_sha256'],
probe_sha256=manifest['artifacts']['probe']['sha256'], system_probe_sha256=manifest['artifacts']['system_probe']['sha256'],
manifest_sha256=sha(manifest_path), qualification_sha256=sha(proof_path), settings_base64=base64.b64encode(settings).decode(), pin_base64=base64.b64encode(pin).decode())
payload['intent_leaves'] = intent_preparation()
intent = dict(id=ident, type='rmm.windows.passive-joint-upgrade', started_at=cb.contract.now().isoformat(),
runner_sha256=sha(__file__), script_sha256=raw_sha(SCRIPT.encode()), manifest_path=str(manifest_path.resolve()),
qualification_path=str(proof_path.resolve()), qualification_sha256=sha(proof_path), payload=payload,
original_runtime_index=index, original_runtime_index_sha256=sha(CURRENT), original_helper_intent_sha256=sha(ORIGINAL_HELPER),
intent_preparation_path=str(INTENT_PREPARATION.resolve()), intent_preparation_sha256=INTENT_PREPARATION_SHA,
no_jobs=True, sqlite_initialized=False)
for name, data in [('runner.py', Path(__file__).read_bytes()), ('upgrade.ps1', SCRIPT.encode())]:
fd = os.open(folder / name, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600)
with os.fdopen(fd, 'wb') as out: out.write(data); out.flush(); os.fsync(out.fileno())
save(folder / 'intent.json', intent)
counts = auto.scopes(); flags = auto.status()
require(auto.flags_disabled(flags), 'closed server test hooks')
save(folder / 'server-before.json', dict(counts=counts, flags=flags))
for kind in ('agent', 'helper', 'probe', 'system_probe'):
item = manifest['artifacts'][kind]
# A previously qualified immutable stage is verified in place. Never
# overwrite/retransfer its bytes merely because this is a new case.
staged = qualification.previous.upload(item)
require(staged['uploaded'] is True and staged['sha256'] == item['sha256'] and staged['size'] == item['bytes'],
'exact existing-or-new staged artifact')
require(stage_script() == intent['script_sha256'], 'exact source stage')
before = remote(intent, 'state'); save(folder / 'before.json', before)
central = transport.observe(ident)['device']
require(central and central['agent_id'] == transport.AGENT, 'original authenticated stored device')
save(folder / 'central-before.json', central)
for field in ('binary_sha256', 'binary_acl_sha256', 'config_sha256', 'config_acl_sha256', 'public_hashes', 'identity_acls'):
require(before[field] == previous['native'][field], 'accepted old agent preservation')
require({k: int(v) for k, v in before['private_key_metadata'].items()}
== {k: int(v) for k, v in previous['native']['private_key_metadata'].items()}, 'original key metadata without key reads')
require(sha(CURRENT) == intent['original_runtime_index_sha256'] and sha(ORIGINAL_HELPER) == intent['original_helper_intent_sha256']
and auto.scopes() == counts and auto.status() == flags, 'same local/server generation before mutation')
save(folder / 'enter-attempt.json', dict(enter_once=True))
try:
result = remote(intent, 'enter')
except Exception as error:
save(folder / 'reply-incomplete.json', dict(error_type=type(error).__name__, readback_only=True, no_repeated_start=True))
raise
save(folder / 'entered.json', result)
print(json.dumps(dict(id=ident, entered=True, continuation='finish reads only; no repeated enter')))
def load_case(ident):
ident = str(uuid.UUID(ident)); folder = STATE / ident
intent = cb.contract.protected_json(folder / 'intent.json')
require(intent['id'] == ident and intent['runner_sha256'] == sha(__file__)
and intent['original_helper_intent_sha256'] == sha(ORIGINAL_HELPER)
and intent['intent_preparation_sha256'] == sha(INTENT_PREPARATION) == INTENT_PREPARATION_SHA,
'original exact joint case/source/preparation')
qualified(Path(intent['manifest_path']), Path(intent['qualification_path']))
require(sha(intent['qualification_path']) == intent['qualification_sha256'], 'original qualification receipt')
return folder, intent
def actual_pipe_proof(native, intent):
# Preserve native u64 volume IDs as exact JSON integers. PowerShell's JSON
# number conversion is not used to compare them to the witness's strings.
encoded = native.get('agent_probe_raw_base64')
if encoded is None:
return False
raw = base64.b64decode(encoded, validate=True)
require(len(raw) <= 8192, 'bounded actual producer receipt')
probe = json.loads(raw, object_pairs_hook=cb.contract.strict_object)
if probe.get('authenticated_pipe_exchange') is not True:
return False
expected = dict(schema_version=1, source='actual_local_service_runtime',
agent_process_id=native['service']['pid'], agent_service='RmmDiscoveryWindows',
agent_id=transport.AGENT, asset_id=transport.ASSET, helper_service='RmmDiscoverySystemHelper',
verified_helper_user_sid='S-1-5-18', verified_helper_service_sid=original_helper.service_sid('RmmDiscoverySystemHelper'),
helper_binary_sha256=intent['payload']['new_helper'], policy_sha256=intent['payload']['new_policy'],
client_service_pid_verified_by_helper=True, system_capability_advertised=False,
helper_clock_qualified=False, helper_ready=False, no_jobs=True)
require(all(probe.get(k) == v and (not isinstance(v, bool) or type(probe.get(k)) is bool) for k, v in expected.items()),
'actual current LocalService/SYSTEM producer, all capabilities still closed')
challenge = uuid.UUID(probe['challenge'])
require(challenge.int != 0 and str(challenge) == probe['challenge']
and cb.contract.timestamp(probe['observed_at']) >= cb.contract.timestamp(intent['started_at']),
'fresh original native challenge')
for label, witness in [('ledger_file_id', native['helper_witness']['helper_ledger']['file']['file_id']),
('executor_lock_file_id', native['helper_witness']['executor_lock']['file_id'])]:
actual = probe[label]
require(type(actual['volume_serial']) is int and str(actual['volume_serial']) == witness['volume_serial']
and isinstance(actual['file_id'], list) and len(actual['file_id']) == 16
and all(type(v) is int and 0 <= v <= 255 for v in actual['file_id'])
and bytes(actual['file_id']).hex() == witness['id_hex'], 'same independently witnessed native helper file identities')
return True
def publish(folder, intent, result):
evidence = dict(path=str(result.resolve()), sha256=sha(result))
index = dict(schema_version=1, type='rmm.windows.current-runtime', case_id=folder.name,
agent_id=transport.AGENT, asset_id=transport.ASSET, binary_sha256=intent['payload']['new_agent'],
transport='auto', evidence=evidence, windows_jobs_enabled=False, clock_adapter_qualified=False, system_helper_client_feature=True)
components = dict(schema_version=1, type='rmm.windows.current-components', case_id=folder.name, evidence=evidence,
agent_sha256=intent['payload']['new_agent'], helper_sha256=intent['payload']['new_helper'],
policy_sha256=intent['payload']['new_policy'], pin_sha256=intent['payload']['new_pin'],
previous_runtime_index_sha256=intent['original_runtime_index_sha256'], original_helper_intent_sha256=intent['original_helper_intent_sha256'],
windows_jobs_enabled=False, clock_adapter_qualified=False, helper_effects_enabled=False)
# Idempotent LOCAL publication only, after actual preservation finish. Never
# infer or repeat a target-side stop/start from an incomplete local receipt.
lock = STATE / 'publication.lock'
fd = os.open(lock, os.O_WRONLY | os.O_CREAT | os.O_NOFOLLOW, 0o600)
with os.fdopen(fd, 'w') as held:
fcntl.flock(held, fcntl.LOCK_EX | fcntl.LOCK_NB)
current = cb.contract.protected_json(CURRENT)
require(sha(CURRENT) == intent['original_runtime_index_sha256'] or current == index, 'current-runtime compare-and-set')
if COMPONENTS.exists(): require(cb.contract.protected_json(COMPONENTS) == components, 'same original joint publication')
else: save(COMPONENTS, components)
if current != index:
previous = folder / 'previous-runtime-index.json'
if previous.exists(): require(cb.contract.protected_json(previous) == current, 'original retained index backup')
else: save(previous, current)
candidate = folder / 'new-runtime-index.json'
if candidate.exists(): require(cb.contract.protected_json(candidate) == index, 'same create-only new index candidate')
else: save(candidate, index)
require(sha(CURRENT) == intent['original_runtime_index_sha256'], 'current-runtime still original immediately before replace')
os.replace(candidate, CURRENT)
publication = dict(current_runtime_sha256=sha(CURRENT), current_components_sha256=sha(COMPONENTS))
completed = folder / 'publication-completed.json'
if completed.exists(): require(cb.contract.protected_json(completed) == publication, 'same completed local publication')
else: save(completed, publication)
def finish(ident, read_only=False):
folder, intent = load_case(ident)
observed = remote(intent, 'readback' if read_only else 'finish'); save(folder / ('readback-' + str(uuid.uuid4()) + '.json'), observed)
require(observed['read_only'] is True and observed['id'] == ident, 'original read-only case; never a repeated start')
if read_only:
print(json.dumps(dict(id=ident, read_only=True, phase_receipts=observed['phase_receipts']))); return
require(observed['completed'] is True, 'actual complete joint finish')
result = folder / 'result.json'
if result.exists():
original = cb.contract.protected_json(result)
require(original['verified'] is True and original['completed'] is True and original['id'] == ident
and original['manifest_sha256'] == intent['payload']['manifest_sha256'], 'original successful finish proof')
for role in ('service', 'helper_service'):
require(all(observed['native'][role][field] == original['native'][role][field] for field in ('pid', 'creation_filetime')),
'same qualified live component instances before local publication recovery')
publish(folder, intent, result)
print(json.dumps(dict(id=ident, verified=True, retained_original_finish=True))); return
before = cb.contract.protected_json(folder / 'before.json')
central = cb.contract.protected_json(folder / 'central-before.json')
online = transport.wait_mode(ident, 'wss', cb.contract.timestamp(intent['started_at']), central)
after = remote(intent, 'finish'); save(folder / ('after-' + str(uuid.uuid4()) + '.json'), after)
native = after['native']
require(native['journal']['pending_inventory_events'] == 0 and native['journal']['sequence'] > before['journal']['sequence'], 'fresh sequence and concrete inventory ACK')
device = transport.read_device(); denied = transport.foreign_denied()
require(cb.contract.timestamp(device['observed_at']) >= cb.contract.timestamp(intent['started_at']), 'fresh same-identity stored inventory')
server = cb.contract.protected_json(folder / 'server-before.json')
require(auto.scopes() == server['counts'] and auto.status() == server['flags'] and auto.flags_disabled(server['flags']), 'both target jobs/policies unchanged')
pipe = actual_pipe_proof(native, intent)
value = dict(verified=True, completed=True, restored=False, id=ident, native=native, original=after['original'], frozen=after['frozen'],
online=online, stored_inventory=device, foreign_denied=denied, no_jobs=True, windows_jobs_enabled=False,
clock_adapter_qualified=False, system_helper_client_feature=True, native_pipe_peer_test=bool(pipe),
configuration_unchanged=True, private_key_read=False, no_reboot=True, no_clock_change=True,
manifest_path=intent['manifest_path'], manifest_sha256=intent['payload']['manifest_sha256'], qualification_sha256=intent['qualification_sha256'])
save(result, value)
publish(folder, intent, result)
print(json.dumps(dict(id=ident, verified=True, passive_preservation=True, native_pipe_peer_test=bool(pipe), windows_jobs_enabled=False)))
def main():
os.umask(0o077)
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('phase', choices=('upgrade-passive', 'finish', 'readback'))
parser.add_argument('--manifest', type=Path); parser.add_argument('--qualification', type=Path); parser.add_argument('--id')
args = parser.parse_args()
if args.phase == 'upgrade-passive':
require(args.manifest and args.qualification and not args.id, 'qualified fresh joint upgrade only')
upgrade(args.manifest, args.qualification)
else:
require(args.id and not (args.manifest or args.qualification), 'same original case only')
finish(args.id, read_only=args.phase == 'readback')
if __name__ == '__main__':
try: main()
except Exception as error:
print('WINDOWS_JOINT_UPGRADE_INCOMPLETE:' + type(error).__name__)
raise SystemExit(2) from None
@@ -0,0 +1,86 @@
"""Local guard checks only. No credentials, Windows API, VM or RMM operation."""
import contextlib
import copy
import io
import json
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch
import system_delegation_upgrade as upgrade
def settings():
return dict(schema_version=1, binding={'test_public_binding': 'fixture'},
agent=dict(binary_sha256=upgrade.OLD_AGENT, user_sid='S-1-5-19'),
helper=dict(binary_sha256=upgrade.OLD_HELPER, user_sid='S-1-5-18'),
allowed_services=[], max_runtime_seconds=30, enable_effects=False, allow_reboot=False)
class JointUpgradeGuards(unittest.TestCase):
def test_only_two_image_pins_change_and_reciprocal_policy_hash_matches_exact_bytes(self):
original = settings()
preserved = copy.deepcopy(original)
raw, pin, policy = upgrade.passive_settings(original, 'a' * 64, 'b' * 64)
new = json.loads(raw)
restored = copy.deepcopy(new)
restored['agent']['binary_sha256'] = upgrade.OLD_AGENT
restored['helper']['binary_sha256'] = upgrade.OLD_HELPER
self.assertEqual(restored, preserved)
self.assertEqual(original, preserved)
self.assertEqual(policy, upgrade.raw_sha(raw))
public = json.loads(pin)
self.assertEqual(public['policy_sha256'], policy)
self.assertEqual(public['binding'], new['binding'])
self.assertEqual(public['agent'], new['agent'])
self.assertEqual(public['helper'], new['helper'])
def test_scope_enablement_extra_fields_wrong_images_and_mistyped_values_are_refused(self):
for field, value in [('enable_effects', True), ('enable_effects', 'false'),
('allow_reboot', True), ('allowed_services', ['foreign-service']),
('max_runtime_seconds', 31), ('max_runtime_seconds', 30.0), ('schema_version', True),
('extra_command', 'not-allowed')]:
changed = settings(); changed[field] = value
with self.subTest(field=field, value=value), self.assertRaises(RuntimeError):
upgrade.passive_settings(changed, 'a' * 64, 'b' * 64)
changed = settings(); changed['helper']['binary_sha256'] = 'f' * 64
with self.assertRaises(RuntimeError): upgrade.passive_settings(changed, 'a' * 64, 'b' * 64)
with self.assertRaises(RuntimeError): upgrade.passive_settings(settings(), 'not-a-hash', 'b' * 64)
def test_readback_uses_readonly_phase_and_never_starts_publishes_or_queries_server(self):
upgrade.script_guards()
ident = '00000000-0000-4000-8000-000000000001'
with tempfile.TemporaryDirectory() as folder, patch.object(upgrade, 'load_case', return_value=(Path(folder), {})), \
patch.object(upgrade, 'remote', return_value={'id': ident, 'read_only': True, 'phase_receipts': {}}) as remote, \
patch.object(upgrade, 'save'), patch.object(upgrade, 'publish', side_effect=AssertionError('publication forbidden')), \
patch.object(upgrade.auto, 'scopes', side_effect=AssertionError('server contact forbidden')), \
contextlib.redirect_stdout(io.StringIO()):
upgrade.finish(ident, read_only=True)
remote.assert_called_once_with({}, 'readback')
def test_local_index_cas_recovers_partial_publication_idempotently_and_rejects_foreign_index(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory); case = root / 'unit-fixture'; case.mkdir(mode=0o700)
current = root / 'current.json'; components = root / 'components.json'
upgrade.save(current, {'old_unit_fixture': True})
result = case / 'result.json'; upgrade.save(result, {'unit_fixture_only': True})
intent = dict(original_runtime_index_sha256=upgrade.sha(current), original_helper_intent_sha256='0' * 64,
payload=dict(new_agent='a' * 64, new_helper='b' * 64, new_policy='c' * 64, new_pin='d' * 64))
with patch.object(upgrade, 'STATE', root), patch.object(upgrade, 'CURRENT', current), patch.object(upgrade, 'COMPONENTS', components):
with patch.object(upgrade.os, 'replace', side_effect=OSError('unit fixture: local reply lost before replace')):
with self.assertRaises(OSError): upgrade.publish(case, intent, result)
self.assertEqual(upgrade.sha(current), intent['original_runtime_index_sha256'])
upgrade.publish(case, intent, result)
before = (current.read_bytes(), components.read_bytes())
upgrade.publish(case, intent, result)
self.assertEqual(before, (current.read_bytes(), components.read_bytes()))
current.write_text('{"foreign_unit_fixture":true}')
foreign = current.read_bytes()
with self.assertRaises(RuntimeError): upgrade.publish(case, intent, result)
self.assertEqual(current.read_bytes(), foreign)
self.assertEqual(components.read_bytes(), before[1])
if __name__ == '__main__':
unittest.main()
+81
View File
@@ -0,0 +1,81 @@
# Gemeinsames passives Windows-Komponentenupgrade
Stand 2026-11-14: **Source vorbereitet; dieser Upgradefall wurde noch nicht auf
der VM ausgeführt.** Lokale Guards und PowerShell-Parserprüfung ersetzen weder
die neuen nativen Unitnachweise noch den tatsächlichen Erhaltungs-/Pipebeleg.
Der Notebookhost bleibt ausschließlich Entwicklungsrechner.
`deploy/windows/system_delegation_upgrade.py` ist eine eigene enge Strecke für
den vorhandenen Agenten `2beed7fa…` und Helper `921cf182…`, zuletzt PID5140/6240.
Die historischen Runtime- und Helperbootstraprunner bleiben unverändert. Sie
eignen sich absichtlich nicht zur erneuten Installation oder zum Neustart eines
bereits vorhandenen Helperjournals. Der Originalfall `59c2fd6f…` bleibt erhalten.
Die neue Strecke benötigt das gemeinsame Artefaktmanifest und den tatsächlichen
nativen Unitbeleg aus `system_delegation_acceptance.py`. Sie bindet Agent, Helper,
unveränderten `RuntimeStateProbe.exe` und den neuen lesenden `SystemStateProbe.exe`.
Die gemeinsame Core-Qualifikation Linux80→Windows58 ist eine Voraussetzung;
sie ist keine native Windows-Pipe- oder SCM-Wirkungsabnahme.
Der feste Ablauf speichert vor der Mutation lokale und entfernte Create-only-
Intents. Er hält die tatsächlichen Prozesshandles samt Startzeit, stoppt zuerst
den ursprünglichen Agenten und wartet auf dessen Prozessende; erst danach stoppt
er den ursprünglichen Helper. Beide Dienste müssen während sämtlicher
Dateitausche gestoppt bleiben. Alle vier Originalbackups werden vor dem ersten
`File.Replace` geschrieben und geprüft. Agent-EXE, Helper-EXE, `helper.json` und
`agent-pin.json` erhalten jeweils eigene CAS-/Phasenbelege und ihre bisherigen
Datei-ACLs. Erst nach Prüfung aller vier neuen Dateien darf der Helper einmal,
anschließend der Agent einmal gestartet werden. Die beiden Startbelege binden
PID und Prozessstartzeit auch beim späteren Finish.
Die beiden öffentlichen Konfigurationen ändern ausschließlich die zwei
Binaryhashes und den daraus berechneten Policyhash. Die sechs Agentconfigfelder,
Geräteidentität, Zertifikate und Schlüsselmetadaten bleiben erhalten. Private
Schlüsselbytes werden nicht gelesen oder übertragen. Dienste behalten Konten,
Startmodi, Service-SID-Typ, Kommandozeilen und Service-ACL-Hashes. Telemetrie und
Helperledger behalten ihre Dateiidentitäten, Erstellungszeiten, bestehenden
Schemas und Zeilenbelege. Zwischen Stopp und Neustart werden zusätzlich ihre
Dateibytes verglichen; danach darf die passive Telemetrie nur regulär fortschreiten.
Die separat nativ vorbereiteten Intentdateien aus Fall `f322a4d2…` werden über
dessen unveränderten Beleg `c4ef6fed…` gebunden: genau zwei reguläre 0-Byte-Blätter
mit unveränderten Dateiidentitäten und engen ACLs. Der Runner initialisiert sie
nicht und öffnet sie nicht als SQLite. Vorbereitung bedeutet weiterhin keine
PERSIST-/Hotjournal-, Agenttoken-Zugriffs- oder Delegationsqualifikation.
`enable_jobs=false`, kein Jobbinding, unqualifizierter Produktionsclockadapter,
`allowed_services=[]`, `enable_effects=false` und `allow_reboot=false` bleiben
unverändert. Der Runner führt keine RMM-Jobs, Paket-/Diensttests, Reboots,
Uhränderungen, Freigaben oder Servermutationen aus. Die einzigen Dienstaktionen
sind die ausdrücklich beauftragten Stopps/Starts dieser beiden eigenen
Komponenten. Staging benutzt den bekannten gepinnten SSH-/SFTP-Pfad und feste
hashgeprüfte PowerShell-Dateien mit RemoteSigned, keine freien Befehle oder
ExecutionPolicy-Umgehung. Bereits qualifiziert vorhandene Stageartefakte werden
anhand ihres exakten Hashpointers ausschließlich lesend verifiziert und nicht
erneut übertragen oder überschrieben.
Diagnosen sind auf den bestehenden Agentbeleg `state/helper-probe.json` und die
zwei festen Helperdateien `state/pipe-last-error.json` sowie deren bekannte
Stagingdatei `.pipe-last-error.pending` begrenzt. Helperdiagnosen sind maximal
1024Byte und enthalten ausschließlich Prozess-ID, Beobachtungszeit und feste
Fehlerstufen/-codes. Sie liefern keinen positiven Pipebeweis. Dieser benötigt
den frischen Beleg des tatsächlichen neuen Agentprozesses mit Challenge,
reziproken Pins und erfolgreich authentisiertem Austausch.
Bei Antwortverlust ist ausschließlich `readback --id …` zulässig. Dieser liest
auch einen Teilstand und wiederholt keinen Stop, Dateitausch oder Start. Es
gibt keinen automatischen Rollback, Retry, Journalreset oder Markerabbau.
`finish --id …` benötigt beide tatsächlichen neuen Einzelstartinstanzen,
Erhaltungsbelege, frische gespeicherte WSS-Heartbeats/Inventar-ACKs und unveränderte
Windows-/Linux-Jobzählungen sowie Servergates. Erst danach wird der bisherige
Runtimeindex per lokalem CAS um einen neuen Komponentenbeleg ergänzt. Ein noch
fehlgeschlagener Pipebeleg bleibt ausdrücklich fehlgeschlagen; ein erfolgreiches
passives Komponentenupgrade behauptet keine Jobfähigkeit.
Geplante Befehle, **nicht ausgeführt**:
```text
python3 deploy/windows/system_delegation_upgrade.py upgrade-passive --manifest <manifest.json> --qualification <passed.json>
python3 deploy/windows/system_delegation_upgrade.py readback --id <ursprüngliche UUID>
python3 deploy/windows/system_delegation_upgrade.py finish --id <ursprüngliche UUID>
```