Complete bounded Windows maintenance setup and audited development teardown

This commit is contained in:
2026-11-17 17:10:16 +01:00
parent c0b4b27a3e
commit 82fec967ad
13 changed files with 1148 additions and 9 deletions
@@ -0,0 +1,68 @@
# Inspect the enrolled test guest, its actual executables and public helper metadata.
# No private identity fields, service changes, job submission or update calls.
[CmdletBinding()]
param([bool]$ClockOnly=$false)
$ErrorActionPreference = 'Stop'
function JsonFile([string]$Path) {
if (Test-Path -LiteralPath $Path -PathType Leaf) {
return Get-Content -Raw -LiteralPath $Path | ConvertFrom-Json
}
}
function ImageHash([string]$Path) {
if ($Path -and (Test-Path -LiteralPath $Path -PathType Leaf)) {
return (Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash.ToLowerInvariant()
}
}
function ReadService($Name) {
$s = Get-CimInstance Win32_Service -Filter "Name='$Name'"
if (!$s) { return $null }
$match = [regex]::Match($s.PathName, '^\s*(?:"([^"]+)"|(.+?\.exe)(?:\s|$))')
$image = $match.Groups[1].Value
if (!$image) { $image = $match.Groups[2].Value }
$processImage=$null
if ($s.ProcessId -gt 0) {$processImage=(Get-CimInstance Win32_Process -Filter ('ProcessId='+$s.ProcessId)).ExecutablePath}
return [ordered]@{pid=$s.ProcessId;process_image=$processImage;process_sha256=(ImageHash $processImage);name=$s.Name; state=$s.State; identity=$s.StartName; image=$image; sha256=(ImageHash $image)}
}
$data = Join-Path $env:ProgramData 'RustDiscovery'
$helperData = Join-Path $env:ProgramData 'RustDiscoverySystem'
$probe=JsonFile (Join-Path $data 'state\helper-probe.json')
$timeSample=JsonFile (Join-Path $data 'state\helper-time-sample.json')
$refresh=JsonFile (Join-Path $data 'state\time-refresh-system_helper.json')
$lastError=@([regex]::Matches([string]$refresh.error,'(?:TIME|HELPER)_[A-Z_]{2,64}')|ForEach-Object {$_.Value})
$validated=[ordered]@{observed_at=$probe.observed_at;authenticated=$probe.authenticated_pipe_exchange;helper_ready=$probe.helper_ready;
agent_pid=$probe.agent_process_id;agent_id=$probe.agent_id;helper_sha256=$probe.helper_binary_sha256;policy_sha256=$probe.policy_sha256;clock_qualified=$probe.helper_clock_qualified;advertised=$probe.system_capability_advertised;diagnostic=$probe.diagnostic.code;
clock_verified_at=$timeSample.observed_at;clock_role=$timeSample.role;last_clock_error=$lastError;clock_refresh_at=$refresh.observed_at_utc}
if($ClockOnly) {
$service=Get-CimInstance Win32_Service -Filter "Name='RmmDiscoveryWindows'"
$validated['current_agent_pid']=$service.ProcessId
$validated|ConvertTo-Json -Compress
return
}
$identity = JsonFile (Join-Path $data 'state\identity.json')
$release = JsonFile (Join-Path $data 'release-state\installed-release.json')
if (!$release) {$release=JsonFile (Join-Path $data 'installed-release.json')}
$conf=JsonFile (Join-Path $data 'config.json')
$agent = ReadService 'RmmDiscoveryWindows'
$helper = ReadService 'RmmDiscoverySystemHelper'
$settings = JsonFile (Join-Path $helperData 'helper.json')
$pin = JsonFile (Join-Path $helperData 'agent-pin.json')
$clock = JsonFile (Join-Path $data 'job-time.json')
$case=JsonFile (Join-Path $helperData 'windows-update-enrollment.json')
$prerequisites = @()
if (!$identity.agent_id -or !$identity.asset_id) { $prerequisites += 'enrolled_identity' }
if (!$agent -or !$agent.sha256) { $prerequisites += 'agent_image' }
if (!$helper -or !$helper.sha256) { $prerequisites += 'system_helper_service' }
if (!$settings -or !$identity -or $settings.binding.agent_id -ne $identity.agent_id -or
$settings.binding.asset_id -ne $identity.asset_id -or $settings.agent.binary_sha256 -ne $agent.sha256 -or
$settings.helper.binary_sha256 -ne $helper.sha256) { $prerequisites += 'matching_settings_and_images' }
if (!$pin -or $pin.binding.agent_id -ne $identity.agent_id -or $pin.agent.binary_sha256 -ne $agent.sha256 -or
$pin.helper.binary_sha256 -ne $helper.sha256) { $prerequisites += 'matching_agent_pin' }
if (!$clock -or $clock.tenant_id -ne $release.tenant_id -or !$conf.localservice_time_policy) { $prerequisites += 'enrolled_signed_time_policy' }
if (!$conf.windows_update_helper) {$prerequisites += 'agent_windows_update_opt_in'}
if (!$settings.windows_update_max_runtime_seconds -or $settings.allowed_script_profiles -or $settings.allow_reboot -or $settings.allowed_services -or $settings.allowed_msi_recipe_sha256) {$prerequisites += 'narrow_update_helper_settings'}
[ordered]@{probe=$validated;case_id=$case.case_id;tenant_id=$release.tenant_id;release_pull=(ReadService 'RmmDiscoveryReleasePull');agent_id=$identity.agent_id;asset_id=$identity.asset_id;release_id=$release.release_id;
agent=$agent;helper=$helper;helper_settings_binding=$settings.binding.agent_id;
existing_helper_policy_sha256=$pin.policy_sha256;
windows_update_max_runtime_seconds=$settings.windows_update_max_runtime_seconds;
missing=$prerequisites} | ConvertTo-Json -Depth 4 -Compress
@@ -0,0 +1,136 @@
# Detach only definitive, centrally witnessed attempts after the SYSTEM service has been removed.
[CmdletBinding()]
param([Parameter(Mandatory)]$Witness,[Parameter(Mandatory)][Guid]$CaseId,
[Parameter(Mandatory)][Guid]$AgentId,[Parameter(Mandatory)][Guid]$AssetId,
[Parameter(Mandatory)][Guid]$ReleaseId,[ValidateSet('Verify','Apply')][string]$Action='Verify')
$ErrorActionPreference='Stop'
function Check($ok,$reason){if(!$ok){throw $reason}}
function Uuid($s){$g=[guid]::Parse([string]$s);Check ($g -ne [guid]::Empty -and $g.ToString() -ceq [string]$s) 'Invalid identifier';return $g.ToString()}
function SafePath($p) {
$item=Get-Item -LiteralPath $p -Force
while($item) {
Check (!($item.Attributes -band [IO.FileAttributes]::ReparsePoint)) 'Reparse point in enrolled state'
if($item -is [IO.FileInfo]){$item=$item.Directory}else{$item=$item.Parent}
}
}
function HashBytes([byte[]]$bytes){
$sha=[Security.Cryptography.SHA256]::Create()
try{return [BitConverter]::ToString($sha.ComputeHash($bytes)).Replace('-','').ToLowerInvariant()}finally{$sha.Dispose()}
}
# Keep all database handles private to this administrator invocation. Nothing here grants or dispatches jobs.
Add-Type -TypeDefinition @'
using System;
using System.Text;
using System.Runtime.InteropServices;
public sealed class EnrollmentWindowDb : IDisposable {
[DllImport("winsqlite3",CallingConvention=CallingConvention.Cdecl)] static extern int sqlite3_open_v2(byte[] path,out IntPtr db,int flags,IntPtr vfs);
[DllImport("winsqlite3",CallingConvention=CallingConvention.Cdecl)] static extern int sqlite3_close(IntPtr db);
[DllImport("winsqlite3",CallingConvention=CallingConvention.Cdecl)] static extern int sqlite3_exec(IntPtr db,byte[] sql,IntPtr callback,IntPtr arg,IntPtr err);
[DllImport("winsqlite3",CallingConvention=CallingConvention.Cdecl)] static extern int sqlite3_prepare_v2(IntPtr db,byte[] sql,int n,out IntPtr stmt,IntPtr tail);
[DllImport("winsqlite3",CallingConvention=CallingConvention.Cdecl)] static extern int sqlite3_finalize(IntPtr stmt);
[DllImport("winsqlite3",CallingConvention=CallingConvention.Cdecl)] static extern int sqlite3_step(IntPtr stmt);
[DllImport("winsqlite3",CallingConvention=CallingConvention.Cdecl)] static extern IntPtr sqlite3_column_blob(IntPtr stmt,int i);
[DllImport("winsqlite3",CallingConvention=CallingConvention.Cdecl)] static extern int sqlite3_column_bytes(IntPtr stmt,int i);
static byte[] Z(string s){return Encoding.UTF8.GetBytes(s+"\0");}
IntPtr db;
public EnrollmentWindowDb(string path,bool write){if(sqlite3_open_v2(Z(path),out db,(write?2:1)|64,IntPtr.Zero)!=0)throw new Exception("Could not open existing enrolled SQLite database");}
public void Dispose(){if(db!=IntPtr.Zero){sqlite3_close(db);db=IntPtr.Zero;}}
public void Exec(string sql){int rc=sqlite3_exec(db,Z(sql),IntPtr.Zero,IntPtr.Zero,IntPtr.Zero);if(rc!=0)throw new Exception("SQLite statement failed ("+rc+")");}
public byte[] Bytes(string sql){
IntPtr stmt;if(sqlite3_prepare_v2(db,Z(sql),-1,out stmt,IntPtr.Zero)!=0)throw new Exception("Invalid SQLite query");
try{if(sqlite3_step(stmt)!=100)throw new Exception("Expected a matching row");int n=sqlite3_column_bytes(stmt,0);if(n>1048576)throw new Exception("Oversized local witness");byte[] result=new byte[n];if(n>0)Marshal.Copy(sqlite3_column_blob(stmt,0),result,0,n);
if(sqlite3_step(stmt)!=101)throw new Exception("Non-unique local witness");return result;}finally{sqlite3_finalize(stmt);}
}
public string Scalar(string sql){return Encoding.UTF8.GetString(Bytes(sql));}
}
'@
function Attach($db,$p,$alias,$readonly){
# Only fixed, validated local file paths are accepted. Joining databases permits atomic rollback-journal commits.
$u=[Uri]::new($p)
$uri=$u.AbsoluteUri.Replace("'","''")
$mode=if($readonly){'ro'}else{'rw'}
$db.Exec("ATTACH DATABASE '${uri}?mode=$mode' AS $alias")
}
$agent='RmmDiscoveryWindows'
$data=Join-Path $env:ProgramData 'RustDiscovery'
$state=Join-Path $data 'state'
$archive=Join-Path $env:ProgramData ('RustDiscoverySystem.closed-'+$CaseId.ToString())
$mark=Join-Path $archive 'windows-update-enrollment.json'
SafePath $mark
$m=Get-Content $mark -Raw|ConvertFrom-Json
Check ($m.case_id -ceq $CaseId.ToString() -and $m.agent_id -ceq $AgentId.ToString() -and $m.asset_id -ceq $AssetId.ToString() -and $m.release_id -ceq $ReleaseId.ToString()) 'Archived enrollment differs'
$case=$CaseId.ToString();$id=$AgentId.ToString()
$identity=Get-Content (Join-Path $state 'identity.json') -Raw|ConvertFrom-Json
Check ($identity.agent_id -ceq $id -and $identity.asset_id -ceq $AssetId.ToString()) 'Enrolled identity changed'
Check (!(Get-CimInstance Win32_Service -Filter "Name='RmmDiscoverySystemHelper'")) 'SYSTEM helper must be closed'
Check (!(Get-Content (Join-Path $data 'config.json') -Raw|ConvertFrom-Json).windows_update_helper) 'SYSTEM execution is still enabled'
$dbPath=Join-Path $state 'telemetry.sqlite';$ledgerPath=Join-Path $state 'consumption.sqlite';$proofPath=Join-Path $archive 'state\ledger.sqlite'
foreach($p in @($dbPath,$ledgerPath,$proofPath)){SafePath $p}
$journal=Uuid $Witness.journal_id;$helper=Uuid $Witness.helper_id;$decision=Uuid $Witness.decision_id
$checkpoint=[long]$Witness.helper_checkpoint
Check ($checkpoint -gt 0) 'Missing closed helper checkpoint'
$rows=@($Witness.attempts|Where-Object {$null -ne $_})
$gate=$null;$db=$null;$transaction=$false;$stopped=$false
try {
$gate=[IO.File]::Open((Join-Path $data 'release-job.lock'),'Open','ReadWrite','None')
if((Get-Service $agent).Status -ne 'Stopped'){Stop-Service $agent;$stopped=$true}
$apply=$Action -eq 'Apply'
$db=[EnrollmentWindowDb]::new($dbPath,$apply)
if($apply){
Check ($db.Scalar('PRAGMA journal_mode=DELETE') -ceq 'delete') 'Cannot prepare atomic cross-database journal'
$db.Exec('PRAGMA synchronous=FULL')
}
Attach $db $ledgerPath local (!$apply);Attach $db $proofPath proof $true
if($apply){Check ($db.Scalar('PRAGMA local.journal_mode') -ceq 'delete') 'Local consumption journal mode differs';$db.Exec('PRAGMA local.synchronous=FULL')}
$db.Exec($(if($apply){'BEGIN IMMEDIATE'}else{'BEGIN'}));$transaction=$true
$done=$db.Scalar("SELECT count(*) FROM sqlite_master WHERE type='table' AND name='retired_windows_update_windows'") -eq '1'
if($done -and $db.Scalar("SELECT count(*) FROM retired_windows_update_windows WHERE case_id='$case' AND helper_id='$helper' AND journal_id='$journal'") -eq '1'){
$db.Exec('ROLLBACK');$transaction=$false
[ordered]@{already_retired=$true;case_id=$case;attempts=$rows.Count}|ConvertTo-Json -Compress;return
}
Check ($db.Scalar("SELECT count(*) FROM reconcile_meta WHERE id=1 AND journal_id='$journal' AND helper_id='$helper' AND helper_checkpoint=$checkpoint AND last_decision='$decision' AND pending_request IS NULL AND (fault IS NULL OR fault='HELPER_JOURNAL_DISAPPEARED')") -eq '1') 'Agent and signed central final checkpoint differ'
Check ($db.Scalar("SELECT count(*) FROM proof.helper_sync_meta WHERE journal_id='$helper' AND agent_journal_id='$journal' AND checkpoint>=$checkpoint AND last_decision='$decision' AND fault IS NULL") -eq '1') 'Archived helper has not applied the same signed final decision'
Check ($db.Scalar("SELECT count(*) FROM job_attempts WHERE state NOT IN ('succeeded','failed','cancelled','expired','closed_unknown')") -eq '0') 'Local unfinished attempt'
Check ($db.Scalar('SELECT count(*) FROM proof.consumed') -eq [string]$rows.Count -and $db.Scalar('SELECT count(*) FROM proof.execution_evidence') -eq [string]$rows.Count) 'Central and archived helper attempt counts differ'
if($apply){
$db.Exec(@'
CREATE TABLE IF NOT EXISTS retired_windows_update_windows(case_id TEXT PRIMARY KEY,helper_id TEXT NOT NULL,journal_id TEXT NOT NULL,decision_id TEXT NOT NULL,helper_checkpoint INTEGER NOT NULL);
CREATE TABLE IF NOT EXISTS retired_windows_update_attempts AS SELECT '' AS case_id,* FROM job_attempts WHERE 0;
CREATE UNIQUE INDEX IF NOT EXISTS retired_windows_update_job ON retired_windows_update_attempts(job,attempt);
CREATE TABLE IF NOT EXISTS local.retired_windows_update_consumed AS SELECT '' AS case_id,* FROM consumed WHERE 0;
CREATE UNIQUE INDEX IF NOT EXISTS local.retired_windows_update_grant ON retired_windows_update_consumed(grant_id);
CREATE TABLE IF NOT EXISTS local.retired_windows_update_evidence AS SELECT '' AS case_id,* FROM execution_evidence WHERE 0;
CREATE UNIQUE INDEX IF NOT EXISTS local.retired_windows_update_start ON retired_windows_update_evidence(grant_id);
CREATE TRIGGER IF NOT EXISTS deny_retired_windows_update_offer BEFORE INSERT ON job_attempts WHEN EXISTS(SELECT 1 FROM retired_windows_update_attempts WHERE job=NEW.job OR attempt=NEW.attempt) BEGIN SELECT RAISE(ABORT,'retired Windows maintenance attempt'); END;
CREATE TRIGGER IF NOT EXISTS local.deny_retired_windows_update_grant BEFORE INSERT ON consumed WHEN EXISTS(SELECT 1 FROM retired_windows_update_consumed WHERE grant_id=NEW.grant_id OR job=NEW.job OR attempt=NEW.attempt) BEGIN SELECT RAISE(ABORT,'retired Windows maintenance grant'); END;
'@)
}
foreach($r in $rows) {
$j=Uuid $r.job;$a=Uuid $r.attempt;$g=Uuid $r.grant
Check ($r.state -in @('succeeded','failed') -and $r.payload_sha256 -cmatch '^[0-9a-f]{64}$') 'Missing definitive central outcome'
$selector="job='$j' AND attempt='$a' AND grant_id='$g'"
Check ($db.Scalar("SELECT count(*) FROM job_attempts WHERE $selector AND state='$($r.state)'") -eq '1') 'Missing current attempt'
foreach($lane in @('local','proof')){
Check ($db.Scalar("SELECT count(*) FROM $lane.consumed WHERE $selector AND agent='$id' AND result IS NOT NULL") -eq '1') 'Consumption disagrees with approved target'
$start=$db.Scalar("SELECT start FROM $lane.execution_evidence WHERE grant_id='$g'")|ConvertFrom-Json
Check ((HashBytes ([byte[]]$start.request.job_bytes)) -ceq $r.payload_sha256) 'Native start differs from signed payload'
}
Check ($db.Scalar("SELECT count(*) FROM local.execution_evidence l JOIN proof.execution_evidence p USING(grant_id) WHERE l.grant_id='$g' AND l.outcome=p.outcome AND length(l.outcome)>0") -eq '1') 'Agent and archived helper outcomes differ'
if ($r.outcome_sha256) {
$digest=HashBytes ($db.Bytes("SELECT outcome FROM proof.execution_evidence WHERE grant_id='$g'"))
Check ($digest -ceq $r.outcome_sha256) 'Archived helper outcome differs from the signed decision'
}
if($apply){
$db.Exec("INSERT INTO retired_windows_update_attempts SELECT '$case',* FROM job_attempts WHERE $selector; INSERT INTO local.retired_windows_update_consumed SELECT '$case',* FROM local.consumed WHERE $selector; INSERT INTO local.retired_windows_update_evidence SELECT '$case',* FROM local.execution_evidence WHERE grant_id='$g'; DELETE FROM job_attempts WHERE $selector; DELETE FROM local.consumed WHERE $selector; DELETE FROM local.execution_evidence WHERE grant_id='$g';")
}
}
if($apply){
$db.Exec("INSERT INTO retired_windows_update_windows VALUES('$case','$helper','$journal','$decision',$checkpoint); UPDATE reconcile_meta SET helper_id=NULL,helper_checkpoint=0,fault=NULL WHERE id=1; COMMIT")
} else {$db.Exec('ROLLBACK')}
$transaction=$false
[ordered]@{verified=$true;applied=$apply;case_id=$case;attempts=$rows.Count;helper_id=$helper;decision_id=$decision}|ConvertTo-Json -Compress
} finally {
if($db){if($transaction){$db.Exec('ROLLBACK')};$db.Dispose()}
if($gate -and (Get-Service $agent).Status -ne 'Running'){Start-Service $agent}
if($gate){$gate.Dispose()}
}
@@ -0,0 +1,206 @@
# Run as an administrator on an enrolled development device.
# A separate server policy and normal WebUI job approval are still required.
[CmdletBinding()]
param(
[ValidateSet('Plan','Install','Remove','Resume')][string]$Action = 'Plan',
[Parameter(Mandatory=$true)][Guid]$AgentId,
[Parameter(Mandatory=$true)][Guid]$AssetId,
[Parameter(Mandatory=$true)][Guid]$ReleaseId,
[Parameter(Mandatory=$true)][Guid]$CaseId,
[ValidateRange(121,3600)][int]$Seconds = 3600
)
$ErrorActionPreference = 'Stop'
$actor = 'RmmDiscoveryWindows'
$helper = 'RmmDiscoverySystemHelper'
$data = Join-Path $env:ProgramData 'RustDiscovery'
$root = Join-Path $env:ProgramData 'RustDiscoverySystem'
$app = Join-Path $env:ProgramFiles 'RustDiscovery'
$cfg = Join-Path $data 'config.json'
$jobPolicy = Join-Path $data 'job-time.json'
$marker = Join-Path $root 'windows-update-enrollment.json'
$admin = [Security.Principal.SecurityIdentifier]::new('S-1-5-32-544')
$system = [Security.Principal.SecurityIdentifier]::new('S-1-5-18')
$utf8 = [Text.UTF8Encoding]::new($false)
function Check($condition, $message) { if (!$condition) { throw $message } }
function NoLink([string]$path) {
for ($p=Get-Item -LiteralPath $path -Force; $null -ne $p; $p=$p.Parent) {
if ($p.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'Reparse point in fixed path.' }
if ($p -is [IO.FileInfo]) { NoLink $p.DirectoryName; break }
}
}
function JsonFile($p) {
NoLink $p
return [IO.File]::ReadAllText($p) | ConvertFrom-Json
}
function WriteFixed($p,$s) {
if (Test-Path -LiteralPath $p) { Check ([IO.File]::ReadAllText($p) -ceq $s) "Different existing file: $p";return }
$f=[IO.File]::Open($p,[IO.FileMode]::CreateNew);try {$b=$utf8.GetBytes($s);$f.Write($b,0,$b.Length);$f.Flush($true)}finally{$f.Dispose()}
}
function GetHash($p) { NoLink $p;return (Get-FileHash -LiteralPath $p -Algorithm SHA256).Hash.ToLowerInvariant() }
function Service($name) { return Get-CimInstance Win32_Service -Filter ("Name='"+$name+"'") }
function GetSid($name) { return [Security.Principal.NTAccount]::new('NT SERVICE',$name).Translate([Security.Principal.SecurityIdentifier]) }
function DirectoryAcl($readers) {
$a=[Security.AccessControl.DirectorySecurity]::new()
$a.SetOwner($admin);$a.SetAccessRuleProtection($true,$false)
foreach ($id in @($system,$admin)) {$a.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($id,'FullControl','ContainerInherit,ObjectInherit','None','Allow'))}
foreach ($id in $readers) {$a.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($id,'ReadAndExecute','ContainerInherit,ObjectInherit','None','Allow'))}
return $a
}
function NewPrivateDir($path,$readers) {
if (!(Test-Path -LiteralPath $path)){[void][IO.Directory]::CreateDirectory($path,(DirectoryAcl $readers))}
NoLink $path
}
Check ($AgentId -ne [guid]::Empty -and $AssetId -ne [guid]::Empty -and $ReleaseId -ne [guid]::Empty -and $CaseId -ne [guid]::Empty) 'Exact IDs required.'
$who=[Security.Principal.WindowsPrincipal]::new([Security.Principal.WindowsIdentity]::GetCurrent())
Check ($who.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) 'Elevated operator required.'
$id=JsonFile (Join-Path $data 'state\identity.json')
$active=Join-Path $data 'release-state\installed-release.json'
if(!(Test-Path -LiteralPath $active)){$active=Join-Path $data 'installed-release.json'}
$installed=JsonFile $active
$conf=JsonFile $cfg
$clock=JsonFile $jobPolicy
Check ($id.agent_id -ceq $AgentId.ToString() -and $id.asset_id -ceq $AssetId.ToString() -and $installed.release_id -ceq $ReleaseId.ToString()) 'The selected enrollment or release changed.'
Check ($conf.enable_jobs -eq $true -and $conf.localservice_time_policy -ceq $jobPolicy -and $clock.tenant_id -ceq $installed.tenant_id -and $clock.job_signing_public_key_hex -cmatch '^[a-f0-9]{64}$') 'Authenticated LocalService bootstrap required.'
$images=Join-Path $app ('releases\'+$ReleaseId.ToString())
$agentExe=Join-Path $images 'rmm-agent-windows.exe';$helperExe=Join-Path $images 'rmm-helper-windows.exe'
$a=Service $actor;$h=Service $helper
Check ($a -and $a.StartName -ieq 'NT AUTHORITY\LocalService' -and $a.PathName -ceq ('"'+$agentExe+'" --service --config "'+$cfg+'"')) 'Fixed enrolled LocalService command required.'
if($Action -in @('Plan','Install')){
$live=Get-CimInstance Win32_Process -Filter ('ProcessId='+$a.ProcessId)
Check ($a.State -ceq 'Running' -and $live.ExecutablePath -ieq $agentExe -and (GetHash $live.ExecutablePath) -ceq (GetHash $agentExe)) 'The live SCM process differs from the enrolled agent.'
}
$helperCommand='"'+$helperExe+'" --service'
if ($h) {Check ($h.PathName -ceq $helperCommand -and $h.StartName -eq 'LocalSystem') 'Existing helper belongs to a different pair.'}
$manifest=Join-Path $images 'manifest.json'
Check ((GetHash $manifest) -ceq $installed.manifest_sha256) 'Installed release manifest changed.'
$updater=Join-Path $app 'rmm-updater-windows.exe'
$pull=Service 'RmmDiscoveryReleasePull'
Check ($pull -and $pull.StartName -eq 'LocalSystem' -and $pull.PathName -ceq ('"'+$updater+'" --release-service')) 'Expected the enrolled ReleasePull service.'
if($Action -eq 'Plan'){Check ($pull.StartMode -eq 'Auto' -and $pull.State -eq 'Running') 'ReleasePull must be running normally before a new maintenance window.'}
$envelope=Join-Path $images 'envelope.json'
$ring=Join-Path $data 'release-keyring.json'
foreach($f in @($agentExe,$helperExe,$updater,$envelope,$ring)){NoLink $f}
$verified=& $updater --verify-bootstrap $ring $envelope $agentExe $helperExe
Check ($LASTEXITCODE -eq 0 -and (($verified|ConvertFrom-Json).release_id -ceq $ReleaseId.ToString())) 'Signed image pair verification failed.'
$scopeVersion=& $helperExe --windows-update-scope-version
Check ($scopeVersion -ceq 'enrolled-windows-update/1' -and $LASTEXITCODE -eq 0) 'Release a helper with enrolled-windows-update/1 before provisioning.'
$binding=[ordered]@{tenant_id=$clock.tenant_id;asset_id=$AssetId.ToString();agent_id=$AgentId.ToString();enrollment_generation=1;assignment_version=1;public_key_hex=$clock.job_signing_public_key_hex}
$inputDto=[ordered]@{binding=$binding;release_id=$ReleaseId.ToString();agent_sha256=(GetHash $agentExe);helper_sha256=(GetHash $helperExe);max_runtime_seconds=$Seconds}
$markerJson=([ordered]@{case_id=$CaseId.ToString();release_id=$ReleaseId.ToString();agent_id=$AgentId.ToString();asset_id=$AssetId.ToString()}|ConvertTo-Json -Compress)
$archive=$root+'.closed-'+$CaseId.ToString()
$backup=Join-Path $root 'original-agent-config.json'
$written=Join-Path $root 'active-agent-config.json'
$gate=$null
function VerifyMarker($dir) {
NoLink $dir
$file=Join-Path $dir 'windows-update-enrollment.json'
Check ((Test-Path -LiteralPath $file) -and ([IO.File]::ReadAllText($file) -ceq $markerJson)) 'Protected helper directory belongs to another case.'
}
function ReplaceConfig($text) {
$staged=$cfg+'.windows-update-'+$CaseId.ToString()
WriteFixed $staged $text
# PowerShell 5.1 marshals $null as an empty backup path. Provide a real path.
$previous=Join-Path $root ('replaced-config-'+[guid]::NewGuid().ToString()+'.json')
[IO.File]::Replace($staged,$cfg,$previous)
}
function StartNormal {
Set-Service 'RmmDiscoveryReleasePull' -StartupType Automatic
if((Get-Service $actor).Status -ne 'Running'){Start-Service $actor}
if((Get-Service 'RmmDiscoveryReleasePull').Status -ne 'Running'){Start-Service 'RmmDiscoveryReleasePull'}
}
function RemoveWindow {
if (!(Test-Path -LiteralPath $root)) {
Check (!(Service $helper) -and !(JsonFile $cfg).windows_update_helper) 'Helper SCM or configuration present without its protected case marker.'
if(Test-Path -LiteralPath $archive){VerifyMarker $archive}
if((Get-Service $actor).Status -ne 'Running'){Start-Service $actor}
return
}
VerifyMarker $root
$cs=JsonFile $cfg
$registered=Service $helper
if($registered){Check ($registered.StartName -eq 'LocalSystem' -and $registered.PathName -ceq $helperCommand) 'Foreign helper SCM.'}
if($cs.windows_update_helper){
Check ((Test-Path -LiteralPath $written) -and (GetHash $written) -ceq (GetHash $cfg) -and (Test-Path -LiteralPath $backup)) 'Operator configuration changed since opening. Review before restoring.'
}
if((Get-Service $actor).Status -ne 'Stopped'){Stop-Service $actor}
try {
if($registered){
if((Get-Service $helper).Status -ne 'Stopped'){Stop-Service $helper}
& "$env:SystemRoot\System32\sc.exe" delete $helper |Out-Null
Check ($LASTEXITCODE -eq 0) 'Helper SCM removal failed.'
for($i=0;$i -lt 15 -and (Service $helper);$i++){Start-Sleep -Seconds 1}
Check (!(Service $helper)) 'Helper SCM deletion pending.'
}
if($cs.windows_update_helper){ReplaceConfig ([IO.File]::ReadAllText($backup))}
Check (!(Test-Path -LiteralPath $archive)) 'Case archive already exists.'
[IO.Directory]::Move($root,$archive)
} finally {
if((Get-Service $actor).Status -ne 'Running'){Start-Service $actor}
}
}
if(Test-Path -LiteralPath $root){VerifyMarker $root}
if($Action -eq 'Plan'){[ordered]@{planned=$true;tenant_id=$binding.tenant_id;agent_id=$AgentId;asset_id=$AssetId;release_id=$ReleaseId;agent_sha256=$inputDto.agent_sha256;helper_sha256=$inputDto.helper_sha256;seconds=$Seconds;requires_helper_creation=(!$h);case_id=$CaseId}|ConvertTo-Json -Depth 6 -Compress;return}
try {
# The updater and agent hold the same file throughout a transition or execution.
$gate=[IO.File]::Open((Join-Path $data 'release-job.lock'),'Open','ReadWrite','None')
Check ((JsonFile $active).release_id -ceq $ReleaseId.ToString()) 'Release switched during preparation.'
if($Action -eq 'Resume'){
Check (!(Service $helper) -and !(JsonFile $cfg).windows_update_helper -and !(Test-Path -LiteralPath $root)) 'Helper still active.'
if(Test-Path -LiteralPath $archive){VerifyMarker $archive}
StartNormal
[ordered]@{actor_running=((Get-Service $actor).Status -eq 'Running');release_pull_running=((Get-Service 'RmmDiscoveryReleasePull').Status -eq 'Running')}|ConvertTo-Json -Compress
return
}
if($Action -eq 'Remove'){
RemoveWindow
[ordered]@{closed=$true;case_id=$CaseId;agent_id=$AgentId;release_id=$ReleaseId;helper_registered=[bool](Service $helper);actor_running=((Get-Service $actor).Status -eq 'Running');release_pull_running=((Get-Service 'RmmDiscoveryReleasePull').Status -eq 'Running')}|ConvertTo-Json -Compress
return
}
Check (!(Test-Path -LiteralPath $archive)) 'Case already closed.'
Check ((!$h) -or (Test-Path -LiteralPath $marker)) 'Existing helper service has no matching protected case.'
$actorSid=GetSid $actor
# The helper runs as SYSTEM; its service SID is optional on file DACLs.
NewPrivateDir $root @($actorSid);WriteFixed $marker $markerJson
Check (!(Test-Path -LiteralPath (Join-Path $data 'release-state\release-transition.json'))) 'Release transition must finish before maintenance.'
Set-Service 'RmmDiscoveryReleasePull' -StartupType Manual
if((Get-Service 'RmmDiscoveryReleasePull').Status -ne 'Stopped'){Stop-Service 'RmmDiscoveryReleasePull'}
if (!$h) {
New-Service -Name $helper -BinaryPathName $helperCommand -StartupType Manual | Out-Null
& "$env:SystemRoot\System32\sc.exe" sidtype $helper unrestricted | Out-Null
Check ($LASTEXITCODE -eq 0) 'Could not set helper service SID.'
}
$rendered=($inputDto|ConvertTo-Json -Compress -Depth 6)|& $helperExe --prepare-enrolled-windows-update
Check ($LASTEXITCODE -eq 0) 'Typed helper policy renderer failed.'
$prepared=$rendered|ConvertFrom-Json
NewPrivateDir (Join-Path $root 'state') @()
$intents=Join-Path $root 'agent-intents'
NewPrivateDir $intents @($actorSid)
foreach($leaf in @('system-intents.sqlite','system-intents.sqlite-journal')){
$p=Join-Path $intents $leaf
if(!(Test-Path -LiteralPath $p)){[IO.File]::Open($p,'CreateNew').Dispose()}
NoLink $p
$acl=[Security.AccessControl.FileSecurity]::new();$acl.SetOwner($admin);$acl.SetAccessRuleProtection($true,$false)
foreach($trusted in @($system,$admin)){$acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($trusted,'FullControl','Allow'))}
$acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($actorSid,[Security.AccessControl.FileSystemRights]0x12019f,'Allow'))
Set-Acl -LiteralPath $p -AclObject $acl
}
WriteFixed (Join-Path $root 'helper.json') $prepared.helper_settings
WriteFixed (Join-Path $root 'agent-pin.json') $prepared.agent_pin
if(!$conf.windows_update_helper) {
if((Get-Service $actor).Status -ne 'Stopped'){Stop-Service -Name $actor}
WriteFixed $backup ([IO.File]::ReadAllText($cfg))
$conf|Add-Member -NotePropertyName windows_update_helper -NotePropertyValue $true -Force
WriteFixed $written ($conf|ConvertTo-Json -Depth 12 -Compress)
ReplaceConfig ([IO.File]::ReadAllText($written))
}
if((Get-Service $helper).Status -ne 'Running'){Start-Service $helper}
if((Get-Service $actor).Status -ne 'Running'){Start-Service $actor}
[ordered]@{installed=$true;case_id=$CaseId;tenant_id=$binding.tenant_id;asset_id=$AssetId;agent_id=$AgentId;release_id=$ReleaseId;agent_sha256=$inputDto.agent_sha256;helper_binary_sha256=$inputDto.helper_sha256;helper_policy_sha256=$prepared.helper_policy_sha256;seconds=$Seconds} |ConvertTo-Json -Compress
} catch {
$failure=$_
if ($Action -eq 'Install' -and $gate -and (Test-Path -LiteralPath $marker)) {
RemoveWindow
StartNormal
}
throw $failure
} finally {if($gate){$gate.Dispose()}}