Files
rust-discovery/deploy/windows/Retire-DevelopmentWindowsUpdate.ps1
T

137 lines
12 KiB
PowerShell

# 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
try {
$gate=[IO.File]::Open((Join-Path $data 'release-job.lock'),'Open','ReadWrite','None')
if((Get-Service $agent).Status -ne 'Stopped'){Stop-Service $agent}
$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' AND decision_id='$decision' AND helper_checkpoint=$checkpoint") -eq '1'){
$db.Exec('ROLLBACK');$transaction=$false
[ordered]@{already_retired=$true;verified=$true;applied=$true;case_id=$case;helper_id=$helper;decision_id=$decision;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()}
}