From 82fec967ad17b80f743a387b993ef018f0afc273 Mon Sep 17 00:00:00 2001 From: Kevin Janssen Date: Tue, 17 Nov 2026 17:10:16 +0100 Subject: [PATCH] Complete bounded Windows maintenance setup and audited development teardown --- AGENTS.md | 3 + Rust_RMM_Implementierungsspezifikation.md | 2 + .../Inspect-DevelopmentWindowsUpdate.ps1 | 68 ++++ .../Retire-DevelopmentWindowsUpdate.ps1 | 136 +++++++ .../windows/Set-DevelopmentWindowsUpdate.ps1 | 206 +++++++++++ docs/development.md | 4 + .../windows-update-window-20261117.json | 91 +++++ docs/handover.md | 4 +- docs/mvp-completion-plan.md | 19 +- docs/project-decisions.md | 2 +- docs/windows-update-dev-window.md | 36 ++ tools/windows_update_detach.py | 250 +++++++++++++ tools/windows_update_scope.py | 336 ++++++++++++++++++ 13 files changed, 1148 insertions(+), 9 deletions(-) create mode 100644 deploy/windows/Inspect-DevelopmentWindowsUpdate.ps1 create mode 100644 deploy/windows/Retire-DevelopmentWindowsUpdate.ps1 create mode 100644 deploy/windows/Set-DevelopmentWindowsUpdate.ps1 create mode 100644 docs/evidence/windows-update-window-20261117.json create mode 100644 docs/windows-update-dev-window.md create mode 100644 tools/windows_update_detach.py create mode 100644 tools/windows_update_scope.py diff --git a/AGENTS.md b/AGENTS.md index e7443fc..c045777 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -26,3 +26,6 @@ Ein Server mit WebUI und MCP verwaltet Linux- und Windows-Clients. Die Clients m ## Nachweise und Umfang Teste die betroffene Funktion und den konkreten Fehlerpfad. Verwende vorhandene native Belege weiter. Kennzeichne geplante, noch nicht ausgeführte Befehle sowie fehlende Zugänge oder Werkzeuge. Historische APT-/MSI-/Rebootabnahmen, Terminal, RustDesk, PVE/PBS, Cluster und Backups sind keine Voraussetzungen für den aktuellen Lieferplan. + + +Für ein benötigtes Windows-Update-Wartungsfenster den [dokumentierten Operator](docs/windows-update-dev-window.md) wiederverwenden. Der temporäre SYSTEM-Helper bindet das aktuelle signierte Agentpaar und die Geräteidentität. Nach terminalem Ergebnis das Fenster schließen und den normalen Agent-/Updatebetrieb nachlesen. Eine echte OS-Installation gilt erst mit ihrem eigenen Zielergebnis als nachgewiesen. diff --git a/Rust_RMM_Implementierungsspezifikation.md b/Rust_RMM_Implementierungsspezifikation.md index 99f8f35..efcf3f5 100644 --- a/Rust_RMM_Implementierungsspezifikation.md +++ b/Rust_RMM_Implementierungsspezifikation.md @@ -118,6 +118,8 @@ Minuten nach Empfang nutzbar (bisher 100 ms). Details Kapitel 0.3. Der Betreiber hat die Löschung des als `closed_unknown` abgeschlossenen Entwicklungsantrags und das Entfernen blockierender Entwicklungsdaten ausdrücklich beauftragt. Für die MVP-Abnahme darf ein Testgerät mit neuer Identität über den Installer aufgenommen werden. Ein bereinigter Testauftrag erzeugt keine Ausführung und keinen neuen Versuch. Bei einem regulären Selbstupdate behält das Gerät seine Identität. Der verbindliche Nachweis steht im [Lieferplan](docs/mvp-completion-plan.md). +Nach einem abgeschlossenen temporären Windows-Wartungsfenster darf der Entwicklungsoperator eindeutig terminale lokale Arbeitsprojektionen mit ihren Nachweisen archivieren und die an dieses Fenster gebundene Helper-Zuordnung lösen. Vorbedingungen sind der geschlossene zentrale Scope, eine leere aktive Auftragsliste und die geprüfte Geräte-/Releasebindung. Serverseitige Ergebnisse bleiben erhalten. + Der dedizierte Produktgateway liefert Jobs ausschließlich in Antworten auf HTTPS-Anfragen des Geräts. Der Windows-GNU-Entwicklungsrelease trägt sein tatsächliches Buildziel `x86_64-pc-windows-gnu` und einen eigenen Signaturschlüssel. Der Windows-MSVC-Kanal ist separat adressiert. Für die mitgelieferte PowerShell-Vorlage „Windows-Updates installieren“ darf der feste Plan ein längeres Ausführungsfenster bis 3600 Sekunden auswählen. Es gilt nur für die geprüften Originalbytes und die ausgewählte Bibliotheksrevision. Server- und Gerätescope müssen das längere Fenster ausdrücklich erlauben, und der Agent muss es unterstützen. Der engste der gesetzten Grenzwerte gilt. Das Ergebnis meldet den von Windows festgestellten Neustartbedarf. Ein Neustart ist ein eigener Wartungsauftrag. diff --git a/deploy/windows/Inspect-DevelopmentWindowsUpdate.ps1 b/deploy/windows/Inspect-DevelopmentWindowsUpdate.ps1 new file mode 100644 index 0000000..20ef2b0 --- /dev/null +++ b/deploy/windows/Inspect-DevelopmentWindowsUpdate.ps1 @@ -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 diff --git a/deploy/windows/Retire-DevelopmentWindowsUpdate.ps1 b/deploy/windows/Retire-DevelopmentWindowsUpdate.ps1 new file mode 100644 index 0000000..994d4d4 --- /dev/null +++ b/deploy/windows/Retire-DevelopmentWindowsUpdate.ps1 @@ -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()} +} diff --git a/deploy/windows/Set-DevelopmentWindowsUpdate.ps1 b/deploy/windows/Set-DevelopmentWindowsUpdate.ps1 new file mode 100644 index 0000000..d5954d7 --- /dev/null +++ b/deploy/windows/Set-DevelopmentWindowsUpdate.ps1 @@ -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()}} diff --git a/docs/development.md b/docs/development.md index ef60ca3..35dfc67 100644 --- a/docs/development.md +++ b/docs/development.md @@ -84,3 +84,7 @@ Für den gezielten Austausch des stabilen Workers zuerst die fertige Datei mit ` Dieser Weg wurde am 17. November für den Worker `de75510b…` ausgeführt. Der anschließende reguläre Abruf aktivierte Windows `0.1.3` auf derselben Geräteidentität. [Nativer Beleg](evidence/windows-https-release-20261117.json) Für die separate Veröffentlichung eines korrigierten stabilen Workers ohne neues Agentpaket verwendet der Entwicklungsrunner `--rotate-worker-only --rotate-bootstrap-from SHA256` zusammen mit `--artifacts` und `--build-receipt`. Die Quittung muss die passende Plattform und den übertragenen Worker binden. Der Aufruf prüft den gespeicherten Worker und rotiert nur den Bootstrap-Pin des gewählten Mandanten. [Veröffentlichungs- und Rotationsnachweis](evidence/agent-release-worker-rotation-20261117.json) + +## Windows-Wartungsvorlage im Entwicklungsbetrieb nutzen + +Der [Operatorablauf](windows-update-dev-window.md) beschreibt die Einrichtung der SYSTEM-Rechte auf dem aufgenommenen Testgerät. `python3 tools/windows_update_scope.py inspect` liest den Iststand. `plan` zeigt den vorgesehenen Eingriff. `window --minutes 15` öffnet ein geräte- und releasegebundenes Fenster. Der Befehl bleibt während der Wartung aktiv und schließt das Fenster anschließend. Ein vorzeitiges `close --case UUID` entzieht die zentrale Richtlinie, wartet auf terminale Aufträge und baut den lokalen Helper zurück. Der feste Skriptauftrag wird in der WebUI geprüft und genehmigt. diff --git a/docs/evidence/windows-update-window-20261117.json b/docs/evidence/windows-update-window-20261117.json new file mode 100644 index 0000000..8975012 --- /dev/null +++ b/docs/evidence/windows-update-window-20261117.json @@ -0,0 +1,91 @@ +{ + "schema_version": 1, + "date": "2026-11-17", + "environment": "development", + "platform": "windows-x86_64-gnu", + "agent_version": "0.1.4", + "enrollment": { + "tenant_id": "11111111-1111-4111-8111-111111111111", + "asset_id": "26d4cdef-dc84-47c3-8f49-49e22ef64ea8", + "agent_id": "858a27db-8ba3-4a75-af51-66f6a0909a91", + "release_id": "3dcb2484-fb2d-418d-84f0-aa54f5c4c209" + }, + "maintenance_window": { + "case_id": "05d961c0-5181-4d97-8b3a-73e97b5911b8", + "expires_at": "2026-11-17T16:04:14.639840+00:00", + "policy_sha256": "81d23c071ad23f369cb3d4c1104f4d17030ff6eb296e67226b1b7b599df8b7ef", + "wua_max_runtime_seconds": 3600, + "sid_max_runtime_seconds": 30, + "helper_image_sha256": "eeb81736a3ddf297230d808b81f4fbf29f5ebe29723fc298455746f3e4b8f2b7", + "agent_image_sha256": "f30ffac8b9f674c4933d50645bf93f6ee89442608ff73f597cedef3a42172292", + "actor_identity": "NT AUTHORITY\\LocalService", + "helper_identity": "LocalSystem", + "authenticated_pipe": true, + "signed_helper_clock_qualified": true, + "narrow_capabilities": [ + "helper.system.v1", + "system:run_script", + "script.windows_update.long/1" + ], + "general_system_script_capability": false, + "observed_at": "2026-11-17T15:56:30.378564Z" + }, + "sid_probe": { + "source": "Windows SYSTEM Identität prüfen", + "revision_id": "50c09079-7aae-47c9-90bd-e2b1baedefd5", + "script_version": 1, + "script_sha256": "567d7343eecee57a9232b3549ef7c504260cb26da46436ede61e2f354ff3c874", + "plan_id": "d4a5252d-fbf9-48cf-a0f3-f7a79b366519", + "plan_sha256": "eb4600198e79c36c14e901e7085d3758c3386f417851d3c87a89b8060fb72fb4", + "job_payload_sha256": "deba7ecbc41a5f54bdedb5af2025cb20258064d514387e4a84f00517e0f3c5c0", + "operation_id": "e18d6294-532c-42cf-a24a-5eb3fa17ed9a", + "job_id": "48bf885c-42d7-4d84-b62e-b76bddf037c6", + "attempt_id": "84a1176a-90f2-438d-b171-cb376b8a211e", + "executable_jobs_before_ui_approval": 0, + "principal": "simulated-testprincipal-a", + "approval_origin": "dev_test_browser_simulation", + "approved_at": "2026-11-17T15:55:59.493Z", + "webui_observed_at": "2026-11-17T15:56:08.206Z", + "mcp_observed_at": "2026-11-17T15:56:31.953212+00:00", + "exit_code": 0, + "stdout": "S-1-5-18", + "truncated": false, + "matching_completed_consumptions_in_native_helper_ledger": 1 + }, + "decommission": { + "central_scope_revoked": true, + "archived_consumption_and_decision_verified": true, + "signed_decision": "9f8b5067-609b-4706-8677-73998b12d3d0", + "detached_helper_journal": "44960320-a32a-4212-82b2-f831e7bcfcc0", + "original_helper_checkpoint": 9, + "agent_journal": "0c1ec1d3-c868-42f7-a783-70d99a4f9636", + "archived_attempts": 1, + "new_server_sync_at": "2026-11-17T16:08:06.446555+00:00", + "final_device_contact": "2026-11-17T16:08:33.98385+00:00", + "active_agent_process": "Running", + "release_puller": "Running", + "active_system_helper": false, + "enrollment_unchanged": true, + "agent_image_sha256": "f30ffac8b9f674c4933d50645bf93f6ee89442608ff73f597cedef3a42172292", + "sync_ready": true, + "system_run_capability": false, + "open_jobs": 0, + "helper_journal": null, + "helper_checkpoint": 0, + "regular_checkpoint": 325, + "same_result_after_close": { + "job_id": "48bf885c-42d7-4d84-b62e-b76bddf037c6", + "attempt_id": "84a1176a-90f2-438d-b171-cb376b8a211e", + "job_count": 1, + "state": "succeeded", + "exit_code": 0, + "stdout": "S-1-5-18", + "observed_at": "2026-11-17T16:08:53.722666+00:00" + }, + "new_window_read_only_plan_succeeded": true + }, + "scope_notes": [ + "The deployed Windows Update Agent catalog template was not executed. No operating-system update or reboot was requested.", + "The final operator pauses release polling during future windows and waits for a ready signed helper clock before central activation. The final native read-only plan succeeded. No second window was opened." + ] +} diff --git a/docs/handover.md b/docs/handover.md index 80c4015..fe9e537 100644 --- a/docs/handover.md +++ b/docs/handover.md @@ -2,9 +2,9 @@ **Der nächste Auftrag steht im [Umsetzungsplan](mvp-completion-plan.md).** Er enthält den letzten Betriebsbefund je Nutzeranforderung und die Reihenfolge für die nächste Lieferung. [Entwicklungsbefehle](development.md) und [Zugänge](operations-access.md) beschreiben den Arbeitsweg. -**Fortgesetzt am 17. November, 16:45 Uhr MEZ.** API und Gateway laufen mit Revision `a799272` und Datenbankschema 25. Der abgegrenzte Integrationsstand liegt auf `codex/mvp-pull-library`. Der ausgecheckte Arbeitsbaum auf `main` enthält zusätzlich ältere, noch gesondert zu prüfende Arbeiten. +**Abschlussstand am 17. November, 17:08 Uhr MEZ.** API und Gateway laufen mit Revision `a799272` und Datenbankschema 25. Der abgegrenzte Lieferstand liegt auf `codex/mvp-development-release`. Der ausgecheckte Lieferstand liegt auf `codex/mvp-development-release`. Ältere, noch gesondert zu prüfende Arbeiten sind im Arbeitsbaum erhalten. -Der Windows-Agent hat um 15:45:22 UTC nach der gezielten Workerreparatur selbstständig `0.1.3` aktiviert. Beide Dienste laufen, Sync ist bereit, die Geräteidentität `858a27db…` blieb gleich und der Prozesshash stimmt mit dem signierten Release überein. Der zuvor unter `0.1.2` ausgeführte Bibliotheksauftrag ist genau einmal erfolgreich abgeschlossen. Der stabile Prüfer `de75510b…` ist außerdem für neue Installer im Entwicklungsmandanten veröffentlicht. Für die Wartungseinrichtung ist `0.1.4` vorbereitet. Die nächste Abnahme steht im [Lieferplan](mvp-completion-plan.md). [Windows-Beleg](evidence/windows-https-release-20261117.json) +Der Windows-Agent hat um 15:45:22 UTC nach der gezielten Workerreparatur selbstständig `0.1.3` aktiviert. Beide Dienste laufen, Sync ist bereit, die Geräteidentität `858a27db…` blieb gleich und der Prozesshash stimmt mit dem signierten Release überein. Der zuvor unter `0.1.2` ausgeführte Bibliotheksauftrag ist genau einmal erfolgreich abgeschlossen. Der stabile Prüfer `de75510b…` ist außerdem für neue Installer im Entwicklungsmandanten veröffentlicht. Auch der nächste reguläre Versionswechsel auf `0.1.4` ist nativ mit passendem Prozesshash und bereitem Sync nachgewiesen. Die separate SYSTEM-Identitätsprobe lieferte über WebUI und MCP `S-1-5-18` mit Exitcode 0. Der zentrale Wartungsscope ist geschlossen und der temporäre Helper entfernt. Nach der kontrollierten Archivierung der terminalen Arbeitsprojektionen meldeten beide Produktgeräte um 16:08 UTC wieder bereiten Sync. Windows-Agent und Updatedienst laufen, die SYSTEM-Capability ist entzogen. Die nächste Abnahme steht im [Lieferplan](mvp-completion-plan.md). [Windows-Beleg](evidence/windows-https-release-20261117.json) Die ausdrücklich zur Löschung benannte Entwicklungsanfrage ist entfernt. Beide registrierten Testgeräte laufen über HTTPS-Polling. Den Bereinigungs- und Journalnachweis sowie die aktiven Buildrevisionen im [Lieferplan](mvp-completion-plan.md) verwenden. Die [frühere Bestandsaufnahme](evidence/product-audit-20261117.json) zeigt den Zustand vor der Bereinigung. diff --git a/docs/mvp-completion-plan.md b/docs/mvp-completion-plan.md index 970e831..9961b5d 100644 --- a/docs/mvp-completion-plan.md +++ b/docs/mvp-completion-plan.md @@ -1,6 +1,6 @@ # Lieferplan für Skriptverwaltung, Installation und Agentupdates -**Stand 17. November 2026, 16:46 Uhr MEZ.** Beide per HTTPS aufgenommenen Clients haben ihren Bibliotheksauftrag abgeschlossen und eine neue Agentversion automatisch übernommen. Als nächster Schritt folgt die lesende Prüfung der gerätespezifischen Windows-Wartungseinrichtung. Ziel ist ein Gerät, das sich per HTTPS-Installer anmeldet, im Leerlauf Inventar meldet, einen Bibliotheksauftrag abholt, sein Ergebnis liefert und den nächsten signierten Release selbst übernimmt. [Produktvertrag](../Rust_RMM_Implementierungsspezifikation.md) +**Stand 17. November 2026. Die Kernstrecke des Entwicklungs-MVP ist auf Linux und Windows nativ nachgewiesen.** Ziel ist ein Gerät, das sich per HTTPS-Installer anmeldet, im Leerlauf Inventar meldet, einen Bibliotheksauftrag abholt, sein Ergebnis liefert und den nächsten signierten Release selbst übernimmt. [Produktvertrag](../Rust_RMM_Implementierungsspezifikation.md) ## Produkt und Betriebsstand @@ -8,7 +8,7 @@ | --- | --- | --- | | Server, WebUI und MCP | Dedizierter ARM64-Server mit TLS, getrenntem Gateway und privater Verwaltung. Die WebUI genehmigte je eine feste Skriptrevision auf Linux und Windows. MCP und WebUI lieferten dieselbe Ausgabe und dieselbe Versuch-ID. | [Ergebnisse beider Geräte](evidence/script-library-acceptance-20261117.json) | | Linux- und Windows-Client | Auf beiden Gästen HTTPS-Polling mit mehreren echten Kontakten. Ein Leerlaufkontakt übermittelt Inventar und Heartbeats auch bei leerer Auftragsliste. | [Bereinigung und Geräteabgleich](evidence/dev-cleanup-pull-20261117.json) | -| Skriptbibliothek | Versionierte, mandantengebundene Skripte, feste Revision im Plan, WebUI und MCP. Die Windows-Update-Vorlage ist enthalten. | SYSTEM-Provisionierung auf einem neuen Windows-Client, siehe Schritt 3. | +| Skriptbibliothek | Versionierte, mandantengebundene Skripte, feste Revision im Plan, WebUI und MCP. Die Windows-Update-Vorlage ist enthalten. | SYSTEM-Identitätsprobe über WebUI/Pull mit Exitcode 0. Eigentliche OS-Updateinstallation braucht einen eigenen Wartungsauftrag. | | Veröffentlichung und Erstaufnahme | Auf dem dedizierten Server liegen signierte Linux- und Windows-GNU-Releases. Beide öffentlichen Installer wurden mit einem per WebUI erzeugten Einmalcode auf den Testgästen erfolgreich ausgeführt. | Regulärer PowerShell-Auftrag auf dem frisch aufgenommenen Windows-Gerät mit Exitcode 0. | | Selbstupdate | Linux wechselte auf `0.1.0-mvp.2`, der frische Windows-GNU-Client nach seinem Skriptauftrag auf `0.1.3` und anschließend `0.1.4`. Prozesshash und Geräteidentität wurden nativ geprüft. | [Linux](evidence/linux-public-installer-update-20261117.json) · [Windows](evidence/windows-https-release-20261117.json) | | Entwicklungsbereitstellung | Linux-, Windows- und ARM64-Builder nutzen feste Git-Revisionen. SSH-Staging prüft den übertragenen Hash. Der Serverrunner prüft laufende Binärdatei, Migrationen, beide TLS-Healthchecks und die ausgelieferte WebUI. | Siehe [Entwicklungsbefehle](development.md). | @@ -26,11 +26,11 @@ „Linux-Kernelversion“ und „Windows-PowerShell-Version“ wurden je als v1 geplant, anschließend als v2 geändert und als v1 in der sichtbaren dev/test-WebUI genehmigt. Vor dem Klick gab es je null ausführbare Jobs, danach je einen. Die Testgeräte lieferten `Linux 6.8.0-149-generic` und `PowerShell 5.1.26100.9818` mit Exitcode 0. Die Ausgaben und Versuch-IDs stimmen in WebUI und MCP überein. Fremdmandant über MCP abgewiesen. Die Updatevorlage wurde hierbei nicht ausgeführt. [Nativer Beleg](evidence/script-library-acceptance-20261117.json) -### 3 · Windows-Updates als Bibliotheksfunktion abbilden — Vorlage vorhanden, administrative Ausführung gesondert prüfen +### 3 · Windows-Updates als Bibliotheksfunktion abbilden — Vorlage und administrative Skriptstrecke geprüft „Windows-Updates installieren“ ist eine versionierte PowerShell-Vorlage im serverseitigen Katalog. Sie verwendet die Windows Update Agent API, protokolliert die Ergebnisse je Update und meldet den Neustartbedarf. Der feste Plan bindet Skriptinhalt, Ziel, SYSTEM-Rechte und Zeitlimit. Nur für die freigegebene Vorlagenrevision kann die gesonderte Wartungsrichtlinie bis zu 3.600 Sekunden zulassen. [Vorlagentext](../crates/domain/src/windows_update.ps1) · [Laufzeitprüfung](../crates/domain/src/jobs.rs) -Der Windows-Installer richtet den Agenten als LocalService ein. Zur administrativen Verwendung den SYSTEM-Helper und die Richtlinie für das konkrete Gerät provisionieren. Vor einem Einsatz die Einrichtung mit einer separat genehmigten, lesenden Identitätsabfrage prüfen. Eine tatsächliche Betriebssystemaktualisierung oder ein Neustart wurde für diese Entwicklungslieferung nicht beauftragt. +Der Windows-Installer richtet den Agenten als LocalService ein. Der [Dev-Operator](windows-update-dev-window.md) richtet für die konkrete Geräteidentität und das signierte Agentpaar ein befristetes Wartungsfenster ein. Auf Windows `0.1.4` wurde die feste lesende Identitätsabfrage über die sichtbare dev/test-WebUI genehmigt und als regulärer Pullauftrag genau einmal mit Exitcode 0 und `S-1-5-18` ausgeführt. WebUI und MCP zeigen denselben Versuch. Anschließend wurden der zentrale Scope entzogen, der lokale Helper entfernt und die exakt gebundenen abgeschlossenen Arbeitsprojektionen archiviert. Ein neuer Geräteabgleich bestätigte um 16:08 UTC `sync_ready=true` ohne SYSTEM-Capability, bei laufendem Agent und Updatedienst. Die tatsächliche OS-Updateinstallation bleibt ein eigener Wartungsauftrag. [Nachweis für Einrichtung, Ausführung und Rückbau](evidence/windows-update-window-20261117.json) ### 4 · Signierte Binaries zentral veröffentlichen — im Entwicklungsmandanten nachgewiesen @@ -46,10 +46,17 @@ Das über den Installer neu aufgenommene Linux-Gerät `dda2c891…` führte die Windows-A meldete sich mit neuer Identität `1626b5a3…`, Version `0.1.0` und gültigem `windows.base`. Der reguläre Updaterdienst aktivierte um 15:10 UTC Version `0.1.1` mit derselben Identität. Die Manipulationskontrolle wies eine um ein Byte veränderte Helperkopie ab. Das neu aufgenommene Windows-GNU-Gerät `858a27db…` mit Prüfer v2 führte unter `0.1.2` die PowerShell-Bibliotheksrevision erfolgreich aus. WebUI und MCP bestätigen denselben Versuch und Exitcode 0. Beim ersten nachfolgenden Abruf lagen die geprüften Dateien bereits auf dem Gast. Eine Windows-Dateisperre verhinderte zunächst das atomare Umschalten. Der stabile Updater wurde über den direkten Entwicklungsweg korrigiert und mit dem wiederverwendbaren Repo-Befehl übernommen. Anschließend aktivierte er um 15:45:22 UTC selbstständig `0.1.3`. Der Prozesshash stimmt mit dem signierten D-Paket überein, beide Dienste laufen und die Geräteidentität ist gleich. Der nächste reguläre Abruf aktivierte um 15:50 UTC auch `0.1.4`, wiederum mit Hash- und Gerätekontrolle. [Nativer Windows-Beleg](evidence/windows-https-release-20261117.json) -### 7 · Lieferung von einem frischen Checkout nachvollziehen — geprüft +### 7 · Lieferung von einem frischen Checkout nachvollziehen — geprüft und im Lieferbranch gesichert Aus einem sauberen Klon von `95aa707` wurden drei Buildpläne geprüft und der Rustserver offline mit dem Lockfile gebaut. Releasewerkzeug, SSH-Staging und Deploymentrunner sind im Checkout vorhanden. Fünf Linux-Installerregressionen sowie die Release-, Mandanten-, Token- und Rotationstests gegen einen isolierten TLS-Server und echtes PostgreSQL 17 bestanden. Der Migrationsbenutzer ohne Superuserrechte wendete alle 25 Migrationen an. Der Direktweg für ein bereits gebautes WebUI-Bundle wurde zusätzlich auf dem Entwicklungsserver ausgeführt. [Befehle](development.md) **Abnahme.** Ein zweiter Entwickler kann Build, Bereitstellung, Release, Erstaufnahme und Ergebnisabruf den dokumentierten Einstiegspunkten zuordnen. Für beide Geräte gibt es die Kette Installer → Leerlauf → Bibliotheksskript/Ergebnis → automatischer Versionswechsel. Bereits ausreichend belegte Schritte werden referenziert. -**Arbeitsverteilung.** Der Integrator bündelt die noch fehlenden Zielbelege. Je ein Verantwortlicher bearbeitet Windows-Provisionierung, Releaseverwaltung und Skriptbibliothek. Sie ändern getrennte Dateien oder stimmen gemeinsame Routen vorher ab. Bei einem Blocker die nächste fehlende Beobachtung hier im betroffenen Schritt eintragen. Abnahmeprotokolle liefern den Beleg, keine weitere Aufgabenliste. Zusätzliche native Provider, Relay/Terminal, RustDesk und Hypervisor-/Backupfunktionen liegen außerhalb dieser Lieferung. +**Arbeitsverteilung.** Der Integrator bündelt die noch fehlenden Zielbelege. Künftige Teilaufträge bekommen jeweils einen konkreten Fehler oder ein gesondert beauftragtes Nutzerergebnis. Sie ändern getrennte Dateien oder stimmen gemeinsame Routen vorher ab. Bei einem Blocker die nächste fehlende Beobachtung hier im betroffenen Schritt eintragen. Abnahmeprotokolle liefern den Beleg, keine weitere Aufgabenliste. Zusätzliche native Provider, Relay/Terminal, RustDesk und Hypervisor-/Backupfunktionen liegen außerhalb dieser Lieferung. + + +## Fortsetzung nach dieser Lieferung + +Den aktuellen Kernablauf mit den vorhandenen Build-, Deployment- und Operatorbefehlen benutzen. Eine tatsächliche Windows-Updateinstallation mit Ergebnis je Update und festgestelltem Neustartbedarf kann als eigener Wartungsauftrag abgenommen werden. Dafür das dokumentierte Fenster öffnen, die gespeicherte Updatevorlage wählen und den festen Plan in der WebUI genehmigen. Den automatischen Agentversionswechsel und bereits erfolgreiche Bibliotheksaufträge nur bei einem betroffenen Fehler erneut abnehmen. + +Der integrierte Quellstand liegt auf `codex/mvp-development-release`. Die auf dem dedizierten Server aktivierte API-/Gatewayrevision ist `a799272`, Datenbankschema 25. Linux betreibt Release `0.1.0-mvp.2`, Windows GNU `0.1.4`. Ältere, aufgabenfremde Arbeiten liegen weiterhin gesondert im Arbeitsbaum. diff --git a/docs/project-decisions.md b/docs/project-decisions.md index 9423423..20d23ab 100644 --- a/docs/project-decisions.md +++ b/docs/project-decisions.md @@ -4,7 +4,7 @@ Stand: **2026-11-17**, Spezifikation **1.34** (`Rust_RMM_Implementierungsspezifi ## Entwicklungsdaten und MVP-Abnahme (Version 1.34) -Der Betreiber hat für das Entwicklungssystem die Löschung der benannten Anfrage und der blockierenden Testdaten freigegeben. Eine frische Geräteidentität ist für die Installationsabnahme zulässig. Der reguläre Updatepfad erhält die Identität. Der Windows-GNU-Entwicklungsbuild ist als eigener signierter Release adressierbar. Für die mitgelieferte unveränderte Windows-Update-Vorlage dürfen feste Freigabe, Server- und Helperpolicy bei passender Capability bis 3600 Sekunden erlauben. Der dedizierte Gateway stellt den Geräteauftrag über HTTPS-Polling zu. [Bereinigungsnachweis](evidence/dev-cleanup-pull-20261117.json) +Der Betreiber hat für das Entwicklungssystem die Löschung der benannten Anfrage und der blockierenden Testdaten freigegeben. Eine frische Geräteidentität ist für die Installationsabnahme zulässig. Der reguläre Updatepfad erhält die Identität. Der Windows-GNU-Entwicklungsbuild ist als eigener signierter Release adressierbar. Für die mitgelieferte unveränderte Windows-Update-Vorlage dürfen feste Freigabe, Server- und Helperpolicy bei passender Capability bis 3600 Sekunden erlauben. Der dedizierte Gateway stellt den Geräteauftrag über HTTPS-Polling zu. Der Entwicklungsoperator darf nach geschlossenem Wartungsscope, terminalem Ergebnis und geprüftem Geräte-/Releasebezug die abgeschlossenen lokalen Arbeitsprojektionen archivieren und die dazugehörige Helper-Zuordnung lösen. Das ermöglicht den Rückbau eines temporären Wartungshelpers. Serverergebnisse und native Ausführungsnachweise werden dabei erhalten. [Bereinigungsnachweis](evidence/dev-cleanup-pull-20261117.json) ## Skriptverwaltung, HTTPS-Installation und automatischer Releasewechsel (Version 1.33) diff --git a/docs/windows-update-dev-window.md b/docs/windows-update-dev-window.md new file mode 100644 index 0000000..d8bb350 --- /dev/null +++ b/docs/windows-update-dev-window.md @@ -0,0 +1,36 @@ +# Entwicklungsfenster für Windows Update + +Auf dem per HTTPS aufgenommenen Windows-Testgerät läuft der Agent als LocalService. Das temporäre Wartungsfenster verwendet den SYSTEM-Helper desselben veröffentlichten Agentpaares. Die beiden zulässigen Skripttexte sind in der [Domain](../crates/domain/src/jobs.rs) festgelegt. Alle Anträge laufen über die reguläre Gerätewarteschlange und die sichtbare WebUI-Genehmigung. + +1. Aus dem Checkout den angemeldeten Entwicklungsclient, seine laufenden Prozesse und den zentralen Zustand lesen. + + ```sh + python3 tools/windows_update_scope.py inspect + python3 tools/windows_update_scope.py plan + ``` + +2. Ein Fenster öffnen und den Befehl während der Wartung im Vordergrund laufen lassen. + + ```sh + python3 tools/windows_update_scope.py window --minutes 15 + ``` + + Der Befehl gibt die Fall-ID aus. Der Dev-Operator setzt die aktuelle HTTPS-Erstaufnahme mit Enrollmentgeneration 1 und Zuweisungsversion 1 voraus. Beim Öffnen prüft er die signierte Paarversion, den laufenden Agenten und seine Gerätebindung. Der Server aktiviert die Richtlinie erst nach einem aktuellen, passenden Geräte-Heartbeat. Die einzige zugelassene Bedienperson im Entwicklungsprofil ist `simulated-testprincipal-a`. Das Release-Polling pausiert während des Fensters. Die Ablaufzeit des Fensters steht in UTC in der Ausgabe. Ein anderes noch aktives SYSTEM-Fenster bleibt dem bisherigen Betreiber zugeordnet. + +3. In der privaten WebUI das Windows-Gerät und die gewünschte gespeicherte Skriptversion wählen. Zur Prüfung der Identität eine Bibliotheksrevision für Windows PowerShell und Identität `system` verwenden. Der Skripttext ist die folgende Zeile mit genau einem abschließenden LF. + + ```powershell + Write-Output ([System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value) + ``` + + Bei der Identitätsprobe höchstens 30 Sekunden wählen. Den unveränderlichen Plan prüfen, den Antrag absenden und in der sichtbaren dev/test-WebUI genehmigen. Erwartete Ausgabe ist `S-1-5-18` bei Exitcode 0. Die separate Katalogvorlage „Windows-Updates installieren“ darf bei einem entsprechenden Wartungsauftrag bis 3.600 Sekunden laufen. Sie meldet Updateergebnisse und den Neustartbedarf. + +4. Nach dem Ergebnis mit Strg+C schließen oder die Ablaufzeit abwarten. Die Zentrale entzieht den Scope, der Controller wartet auf terminale Versuche, entfernt den temporären Helper und stellt die geschützte Agentkonfiguration wieder her. Endgültige Arbeitsprojektionen dieses Fensters werden unter ihrem ursprünglichen Job-/Grant-Schlüssel lokal archiviert. Zentrale Ergebnisse, Startnachweise, Signaturen und alte Checkpoints bleiben lesbar. Ein neuer Geräteabgleich darf denselben Job oder Grant nicht wieder annehmen. Er prüft LocalService, Release-Polling und den nachfolgenden Heartbeat ohne SYSTEM-Capability. Bei unterbrochener SSH-Verbindung oder einem abrupt beendeten Controller den Rückbau mit der angezeigten Fall-ID fortsetzen. + + ```sh + python3 tools/windows_update_scope.py close --case FALL-UUID + ``` + + Die zentrale Richtlinie läuft auch bei Verbindungsverlust ab. Der lokale Helper hält den nächsten Agent-Paarwechsel bis zum abgeschlossenen Rückbau an. Ein noch laufender beziehungsweise ungeklärter Auftrag wird im regulären Auftragsablauf geklärt. Der Befehl zum Schließen kann anschließend erneut ausgeführt werden. + +Die native Identitätsabfrage und der vollständige Rückbau sind im [Entwicklungsnachweis vom 17. November](evidence/windows-update-window-20261117.json) dokumentiert. diff --git a/tools/windows_update_detach.py b/tools/windows_update_detach.py new file mode 100644 index 0000000..b3a810b --- /dev/null +++ b/tools/windows_update_detach.py @@ -0,0 +1,250 @@ +"""Detach one closed development maintenance window from its signed sync head.""" +import fcntl +import hashlib +import http.client +import json +import os +from pathlib import Path +import re +import shlex +import socket +import ssl +import stat +import subprocess +from datetime import datetime, timezone + +import windows_update_scope as scope + + +BASE = Path('/opt/rust-discovery/devstate') +PRINCIPAL = 'simulated-testprincipal-a' +SCRIPTS = { + '567d7343eecee57a9232b3549ef7c504260cb26da46436ede61e2f354ff3c874': 30, + '0fa5f513a06b6cf902a3f9ac1989987642c181eedd6c305b3912771bd10f2ebf': 3600, +} +PSQL = ['docker', 'exec', '-i', 'rust-discovery-server-postgres-1', 'psql', + '-XqAt', '-v', 'ON_ERROR_STOP=1', '-U', 'postgres', '-d', 'rmm'] +require = scope.require + + +def sql(statement): + result = subprocess.check_output(PSQL, input=statement.encode(), timeout=15) + return json.loads(result) + + +def private_read(path, owner=0): + info = path.lstat() + require(stat.S_ISREG(info.st_mode) and stat.S_IMODE(info.st_mode) == 0o600 + and info.st_uid == owner and info.st_nlink == 1 and info.st_size <= 512 * 1024, + 'Unexpected maintenance record or access mode') + return path.read_bytes() + + +def public_key(): + """Read the server's own public signing key from its authenticated management API.""" + tls = ssl.create_default_context(cafile=str(BASE / 'pki/ca.pem')) + + class Loopback(http.client.HTTPSConnection): + def connect(self): + self.sock = self._context.wrap_socket(socket.create_connection(('127.0.0.1', 18443), 5), + server_hostname='rmm-dev.internal') + + conn = Loopback('rmm-dev.internal', timeout=5, context=tls) + try: + token = (BASE / 'operator-a.token').read_text().strip() + conn.request('GET', '/api/v1/job-signing-key', headers={'Authorization': 'Bearer ' + token}) + reply = conn.getresponse() + require(reply.status == 200, 'Cannot verify the original signed decision against this server') + key = json.loads(reply.read(4097)) + raw = bytes.fromhex(key['public_key_hex']) + require(key['algorithm'] == 'Ed25519' and len(raw) == 32 + and key['key_id'] == hashlib.sha256(raw).hexdigest(), 'Invalid public signing key') + from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey + return key['key_id'], Ed25519PublicKey.from_public_bytes(raw) + finally: + conn.close() + + +def observation(ids, opened, cutoff): + """Only canonical UUIDs and normalized datetimes reach the query.""" + tenant, asset, agent = (ids[k] for k in ('tenant_id', 'asset_id', 'agent_id')) + return f""" + SELECT jsonb_build_object( + 'open_jobs',(SELECT count(*) FROM jobs j WHERE j.tenant_id=i.tenant_id AND j.agent_id=i.agent_id + AND j.state NOT IN ('succeeded','failed','cancelled','expired','closed_unknown')), + 'journal_id',s.journal_id,'checkpoint',s.checkpoint,'decision_id',s.decision_id, + 'helper_id',s.helper_journal_id,'helper_checkpoint',s.helper_checkpoint, + 'signed',encode(c.payload,'hex'),'signature',encode(c.signature,'hex'), + 'jobs',COALESCE((SELECT jsonb_agg(jsonb_build_object( + 'job',j.job_id,'attempt',j.attempt_id,'grant',g.grant_id,'state',j.state, + 'payload_sha256',j.payload_hash,'bytes_hash',encode(sha256(j.payload),'hex'), + 'payload_binding',p-'action','action',p->'action', + 'principal',z.principal,'window_approval',z.created_at BETWEEN '{opened}' AND '{cutoff}', + 'dev',z.testsimulation AND z.approval_origin='dev_test_browser_simulation', + 'plan_hash',z.plan_hash,'authorization_id',z.authorization_id, + 'in_window',g.created_at BETWEEN '{opened}' AND '{cutoff}', + 'reserved',j.start_reserved,'result_grant',j.result->>'grant_id','revision',j.revision) + ORDER BY j.job_id) + FROM jobs j JOIN authorizations z USING(tenant_id,operation_id) + CROSS JOIN LATERAL (SELECT convert_from(j.payload,'UTF8')::jsonb AS p) jp + LEFT JOIN execution_permits g USING(tenant_id,job_id,attempt_id) + WHERE j.tenant_id=i.tenant_id AND j.agent_id=i.agent_id AND p->>'execution_identity'='system' + AND (z.created_at BETWEEN '{opened}' AND '{cutoff}' OR g.created_at BETWEEN '{opened}' AND '{cutoff}')), + '[]'::jsonb)) AS observation + FROM agent_installations i JOIN agent_sync_state s USING(tenant_id,agent_id) + JOIN sync_checkpoints c USING(tenant_id,agent_id,decision_id) + WHERE i.tenant_id='{tenant}' AND i.asset_id='{asset}' AND i.agent_id='{agent}' AND i.revoked_at IS NULL + AND i.assignment_version=1 AND i.enrollment_generation=1 + AND NOT i.sync_recovery_required AND NOT i.sequence_regressed AND NOT i.restore_blocked + """ + + +def verify(snapshot, ids): + require(snapshot['open_jobs'] == 0, 'Device has open or uncertain jobs') + require(snapshot['helper_id'] and snapshot['helper_checkpoint'] > 0, 'Expected bound helper journal') + raw = bytes.fromhex(snapshot['signed']) + key_id, public = public_key() + public.verify(bytes.fromhex(snapshot['signature']), raw) + d = json.loads(raw) + fields = ('journal_id', 'checkpoint', 'decision_id', 'helper_checkpoint') + require(d['domain'] == 'rmm.reconciliation-decision' and d['schema_version'] == 1 + and d['key_id'] == key_id and all(d[k] == ids[k] for k in ('tenant_id','asset_id','agent_id')) + and d['enrollment_generation'] == d['assignment_version'] == 1 + and d['ready'] is True and d['helper_ready'] is True and d['reason'] == 'CONSISTENT' + and d['helper_journal_id'] == snapshot['helper_id'] + and all(d[k] == snapshot[k] for k in fields), 'The signed helper decision does not match the current head') + outcomes = {a['job_id']: a for a in d['attempts'] if a['execution_identity'] == 'system'} + require(len(outcomes) == sum(a['execution_identity'] == 'system' for a in d['attempts']), + 'Duplicate SYSTEM decision') + attempts = [] + for j in snapshot['jobs']: + require(j['grant'], 'A grantless SYSTEM job requires separate reconciliation') + require(j['state'] in ('succeeded','failed'), 'A non-definitive SYSTEM result requires separate reconciliation') + p = j['payload_binding'] + act = dict(j['action']) + script = hashlib.sha256(act.pop('script_utf8').encode()).hexdigest() + require(script in SCRIPTS and 0 < p['max_runtime_seconds'] <= SCRIPTS[script] + and act == {'action':'run_script', 'arguments':[], 'expected_stdout':None, 'interpreter':'powershell', + 'privileged_script_profile':'full_maintenance_v1','windows_execution_profile':'powershell_51_remote_signed'}, + 'Job is outside the two maintenance-window scripts') + a = outcomes.pop(j['job'], {}) + require(j['dev'] and j['principal'] == PRINCIPAL and j['window_approval'] and j['in_window'] + and j['reserved'] and j['result_grant'] == j['grant'] and j['bytes_hash'] == j['payload_sha256'] + and all(p[k] == ids[k] for k in ('tenant_id','asset_id','agent_id')) + and p['enrollment_generation'] == p['assignment_version'] == 1 + and p['job_id'] == j['job'] and p['attempt_id'] == j['attempt'] + and a.get('unlock') is True and a['reason'] == 'DEFINITIVE_OUTCOME_RECONCILED' + and a['attempt_id'] == j['attempt'] and a['grant_id'] == j['grant'] + and a['outcome_state'] == j['state'] and a['revision'] == j['revision'] + and a['job_payload_hash'] == j['payload_sha256'] and a['authorization_id'] == j['authorization_id'] + and a['plan_hash'] == j['plan_hash'] and re.fullmatch('[0-9a-f]{64}',a['outcome_sha256'] or ''), + 'Missing signed evidence of exact consumed grant and terminal result') + attempts.append({**{k:j[k] for k in ('job','attempt','grant','state','payload_sha256')}, + 'outcome_sha256':a['outcome_sha256']}) + require(not outcomes, 'The helper still owns SYSTEM attempts outside this window') + return {**ids, **{k:snapshot[k] for k in (*fields,'helper_id')}, 'attempts':attempts} + + +def server(action, data): + require(action in ('witness','detach'), 'Only witness and detach are supported') + ids = {k:scope.identifier(data[k]) for k in ('case_id','tenant_id','asset_id','agent_id')} + path = scope.policy_location() + case = path.parent.parent.parent / ('update-window-' + ids['case_id']) + lockfd = os.open(BASE / '.windows-system-scope.lock', os.O_RDWR | os.O_NOFOLLOW) + with os.fdopen(lockfd, 'rb') as lock: + fcntl.flock(lock, fcntl.LOCK_EX) + current = private_read(path, 10001) + current_policy = json.loads(current) + require(current_policy['profile'] == 'development' and + (not current_policy['scopes'] or scope.stamp(current_policy['expires_at']) <= scope.utc()), + 'Central development policy must be closed on API and gateway') + window = case / 'window.json' + if case.exists(): + mode = case.lstat() + require(case.resolve() == case and stat.S_ISDIR(mode.st_mode) and mode.st_uid == 0 + and stat.S_IMODE(mode.st_mode) == 0o700, 'Unsafe development window directory') + if not window.exists(): + # Even a failed opening can already have registered a real helper journal. + row = sql(f"""SELECT json_build_object('empty',EXISTS ( + SELECT 1 FROM agent_installations i LEFT JOIN agent_sync_state s USING(tenant_id,agent_id) + WHERE i.tenant_id='{ids['tenant_id']}' AND i.agent_id='{ids['agent_id']}' AND i.asset_id='{ids['asset_id']}' + AND i.revoked_at IS NULL AND s.helper_journal_id IS NULL AND coalesce(s.helper_checkpoint,0)=0 + AND NOT EXISTS (SELECT 1 FROM jobs j WHERE j.tenant_id=i.tenant_id AND j.agent_id=i.agent_id AND + (j.state NOT IN ('succeeded','failed','cancelled','expired','closed_unknown') + OR convert_from(j.payload,'UTF8')::jsonb->>'execution_identity'='system'))))""") + require(row['empty'] and action == 'witness', 'A helper or SYSTEM history exists without an opened scope') + return None + policy = json.loads(private_read(window)) + require(private_read(case/'closed') == b'closed\n' and private_read(case/'original.json') == current, + 'Expected this closed scope and its original policy') + only, = policy['scopes'] + hashes = ('helper_binary_sha256','helper_policy_sha256') + expected_scope = {k:ids[k] for k in ('tenant_id','agent_id','asset_id')} + expected_scope.update(acceptance_evidence_id=ids['case_id'], principals=[PRINCIPAL], allowed_services=[], + enrollment_generation=1, assignment_version=1, max_runtime_seconds=30, + windows_update_max_runtime_seconds=3600) + for k in hashes: + require(re.fullmatch('[a-f0-9]{64}',only[k]) and data.get(k,only[k]) == only[k], 'Helper pin differs') + expected_scope[k] = only[k] + require(policy['schema_version'] == 3 and policy['profile'] == 'development' and only == expected_scope, + 'Case identity, privileges or original policy differ') + opened = datetime.fromtimestamp(window.stat().st_mtime, timezone.utc) + cutoff = min(scope.stamp(policy['expires_at']), datetime.fromtimestamp((case/'closed').stat().st_mtime,timezone.utc)) + require(opened <= cutoff, 'Invalid maintenance horizon') + query = observation(ids,opened.isoformat(),cutoff.isoformat()) + record = sql(query) + require(record['open_jobs'] == 0, 'Open jobs require separate reconciliation') + saved = case/'detach-intent.json' + done = case/'detached.json' + receipt = json.loads(private_read(saved)) if saved.exists() else None + if done.exists(): + require(receipt and json.loads(private_read(done)) == receipt, 'Completion receipt differs from detach intent') + return receipt + if record['helper_id'] is None: + require(receipt and receipt['journal_id'] == record['journal_id'] and record['helper_checkpoint'] == 0, + 'Missing evidence of the original detach transaction') + if action == 'detach': + scope.atomic(done,scope.encode(receipt)) + return receipt + witness = verify(record,ids) + require(receipt in (None,witness) and data.get('witness',witness) == witness, 'Device or witness changed') + if action == 'witness': + return witness + if receipt is None: + scope.atomic(saved,scope.encode(witness)) + # Fence a concurrent signed sync (same lock order as the gateway). The server-owned + # approved jobs, outcomes and signed decisions remain immutable throughout detachment. + # PostgreSQL jsonb canonical ordering differs from Python: bind our checked snapshot + # back as JSONB and compare directly under lock, including jobs, grants and head. + observed_hex = scope.encode(record).hex() + statements = f"""BEGIN TRANSACTION ISOLATION LEVEL SERIALIZABLE; + SET LOCAL lock_timeout='5s'; SET LOCAL statement_timeout='10s'; + DO $$ BEGIN PERFORM 1 FROM agent_installations WHERE tenant_id='{ids['tenant_id']}' AND agent_id='{ids['agent_id']}' FOR UPDATE; END $$; + WITH checked AS ({query}), changed AS ( + UPDATE agent_sync_state s SET helper_journal_id=NULL,helper_checkpoint=0 + FROM checked WHERE s.tenant_id='{ids['tenant_id']}' AND s.agent_id='{ids['agent_id']}' + AND s.journal_id='{witness['journal_id']}' AND s.decision_id='{witness['decision_id']}' + AND s.checkpoint={witness['checkpoint']} AND s.helper_journal_id='{witness['helper_id']}' + AND s.helper_checkpoint={witness['helper_checkpoint']} + AND checked.observation = convert_from(decode('{observed_hex}','hex'),'UTF8')::jsonb + RETURNING 1) + SELECT to_json(count(*)) FROM changed; + COMMIT;""" + require(sql(statements) == 1, 'Concurrent job or sync transition. Inspect the existing intent before retrying') + scope.atomic(done,scope.encode(witness)) + return witness + + +def remote_server(action, data): + """Run only the two fixed modules over the existing pinned server SSH transport.""" + import dev_stage + modules = [Path(scope.__file__).read_text(), Path(__file__).read_text()] + payload = ('import types,sys,json\n' + 'scope=types.ModuleType("windows_update_scope");sys.modules[scope.__name__]=scope\n' + f'exec({modules[0]!r},scope.__dict__)\n' + 'detach=types.ModuleType("windows_update_detach")\n' + f'exec({modules[1]!r},detach.__dict__)\n' + f'print(json.dumps(detach.server({action!r},json.loads({scope.encode(data)!r}))))\n') + command = shlex.join(['python3','-I','-']) + return json.loads(subprocess.check_output([*dev_stage.ssh_prefix('server'),command], + input=payload.encode(),timeout=35)) diff --git a/tools/windows_update_scope.py b/tools/windows_update_scope.py new file mode 100644 index 0000000..c123157 --- /dev/null +++ b/tools/windows_update_scope.py @@ -0,0 +1,336 @@ +#!/usr/bin/env python3 +"""Open and revoke a device-bound development window for the built-in Windows Update template.""" +import argparse +import base64 +from datetime import datetime, timedelta, timezone +import fcntl +import gzip +import json +import os +from pathlib import Path +import re +import shlex +import stat +import subprocess +import sys +import tempfile +import time +import uuid + + +def require(ok, message): + if not ok: + raise ValueError(message) + + +def identifier(value): + raw = str(value) + parsed = uuid.UUID(raw) + require(parsed.int and str(parsed) == raw, 'A canonical, nonempty UUID is required') + return raw + + +def utc(): + return datetime.now(timezone.utc) + + +def stamp(value): + result = datetime.fromisoformat(value.replace('Z', '+00:00')) + require(result.tzinfo is not None, 'Timestamp lacks timezone') + return result + + +def encode(value): + return json.dumps(value, separators=(',', ':'), sort_keys=True).encode() + + +def atomic(path, data, owner=None): + with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as handle: + temp = Path(handle.name) + try: + if owner is not None: + os.fchown(handle.fileno(), *owner) + os.fchmod(handle.fileno(), 0o600) + handle.write(data) + handle.flush() + os.fsync(handle.fileno()) + os.replace(temp, path) + directory = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY) + try: + os.fsync(directory) + finally: + os.close(directory) + finally: + temp.unlink(missing_ok=True) + + +def read_registry(data): + tenant, asset, agent = [identifier(data[k]) for k in ('tenant_id', 'asset_id', 'agent_id')] + # Each interpolated value is a canonical UUID; this invocation cannot mutate Postgres. + sql = f"""BEGIN READ ONLY; + SELECT json_build_object('install',(SELECT json_build_object( + 'contact',last_contact_at,'ready',sync_ready AND NOT restore_blocked,'helper_ready',helper_sync_ready, + 'fresh',last_authenticated_at > now() - interval '2 minutes' + AND certificate_sha256=last_authenticated_certificate_sha256 AND last_contact_at > now() - interval '2 minutes', + 'enrollment_generation',enrollment_generation,'assignment_version',assignment_version,'capabilities',capabilities) + FROM agent_installations WHERE tenant_id='{tenant}' AND asset_id='{asset}' AND agent_id='{agent}' AND revoked_at IS NULL), + 'open_jobs',(SELECT count(*) FROM jobs WHERE tenant_id='{tenant}' AND agent_id='{agent}' + AND state NOT IN ('succeeded','failed','cancelled','expired','closed_unknown')), + 'principal_authorized',EXISTS (SELECT 1 FROM memberships WHERE tenant_id='{tenant}' AND principal='simulated-testprincipal-a' + AND revoked_at IS NULL AND kind='test_human' AND 'scripts:execute'=ANY(permissions) AND 'system:execute'=ANY(permissions))); + COMMIT;""" + raw = subprocess.check_output(['docker', 'exec', '-i', 'rust-discovery-server-postgres-1', + 'psql', '-XqAt', '-v', 'ON_ERROR_STOP=1', '-U', 'postgres', '-d', 'rmm'], input=sql.encode()) + return json.loads(raw) + + +def policy_location(): + base = Path('/opt/rust-discovery/devstate/windows-system-policy') + mounts = [] + for role in ('api', 'gateway'): + container = f'rust-discovery-server-{role}-1' + settings = subprocess.check_output(['docker','exec', container, 'printenv','RMM_PROFILE', + 'RMM_DEV_SYSTEM_ENABLED','RMM_DEV_SYSTEM_POLICY_FILE'], text=True).splitlines() + require(settings == ['development','true','/system-policy/policy.json'], 'Development policy unavailable on '+role) + bind = json.loads(subprocess.check_output(['docker','inspect','--format','{{json .Mounts}}', container])) + dirs = [Path(m['Source']) for m in bind if m['Destination']=='/system-policy' and m['Type']=='bind' and not m['RW']] + require(len(dirs)==1 and dirs[0].parent.parent==base and dirs[0].name=='mounted' + and dirs[0].resolve()==dirs[0], 'Unexpected or writable SYSTEM policy mount') + mounts.append(dirs[0]) + require(mounts[0]==mounts[1], 'API and gateway must use the same directory') + return mounts[0]/'policy.json' + + +def usable(observation): + install = observation.get('install') or {} + return (observation['open_jobs']==0 and observation['principal_authorized'] + and install.get('fresh') and install['ready'] + and install['enrollment_generation']==install['assignment_version']==1) + + +def scoped(data, observation): + if not usable(observation) or not observation['install']['helper_ready']: + return False + caps=set(observation['install']['capabilities']) + needed={'windows.base/1','rmm.sync.v1','helper.system.v1','system:run_script','script.windows_update.long/1', + 'helper.policy.sha256:'+data['helper_policy_sha256'], 'helper.binary.sha256:'+data['helper_binary_sha256'], + 'run_script','script.powershell/1','script.powershell.process_remote_signed/1'} + return needed<=caps and not any(c in caps for c in + ('script.full_maintenance/1','system:set_service_state','system:ensure_package','system:reboot','linux.base/1')) + + +def server(action, data): + if action=='read': + return read_registry(data) + case = identifier(data['case_id']) + path = policy_location() + if action=='preflight': + current=json.loads(path.read_bytes()) + require(current['profile']=='development' and (stamp(current['expires_at'])<=utc() or not current['scopes']), + 'Another live maintenance window is active') + return {'dev_scope_available':True} + history = path.parent.parent.parent/('update-window-'+case) + lockpath = Path('/opt/rust-discovery/devstate/.windows-system-scope.lock') + fd = os.open(lockpath, os.O_RDWR|os.O_CREAT|os.O_NOFOLLOW, 0o600) + with os.fdopen(fd,'rb') as mutex: + fcntl.flock(mutex, fcntl.LOCK_EX) + st=path.lstat() + require(stat.S_ISREG(st.st_mode) and st.st_uid==st.st_gid==10001 and stat.S_IMODE(st.st_mode)==0o600 + and st.st_size<=65536 and st.st_nlink==1, 'Unexpected policy file or ownership') + current=path.read_bytes() + if action=='revoke': + history.mkdir(mode=0o700,exist_ok=True) + if history.exists(): + original, window=history/'original.json', history/'window.json' + # The candidate is recorded durably before replacing the live policy. + if not window.exists(): + require(not original.exists() or original.read_bytes()==current,'Partial opening has a different live policy') + if not (history/'closed').exists(): + atomic(history/'closed',b'closed\n') + return {'central_scope_closed':True} + saved=original.read_bytes() + candidate=window.read_bytes() + require(current in (candidate,saved), 'Central policy changed since opening. Reconcile before replacing it.') + if current!=saved: + atomic(path,saved,(st.st_uid,st.st_gid)) + if not (history/'closed').exists(): + atomic(history/'closed',b'closed\n') + return {'central_scope_closed':True} + require(action=='enable', 'Unsupported central operation') + for key in ('helper_binary_sha256','helper_policy_sha256'): + require(re.fullmatch('[a-f0-9]{64}',data[key]),'Invalid helper hash') + require(scoped(data, read_registry(data)), 'Device has no current authenticated narrow helper capabilities') + expires=stamp(data['expires_at']) + require(utc()=started + and not {'helper.system.v1','system:run_script'} & set(row['install']['capabilities']), + 180,'Still awaiting a new synchronized non-SYSTEM heartbeat after closing') + emit({'closed_case':data['case_id'],'normal_agent_contact':ended['install']['contact']}) + + +if __name__=='__main__': + try: + if len(sys.argv)==4 and sys.argv[1]=='--on-server': + emit(server(sys.argv[2],json.loads(base64.b64decode(sys.argv[3],validate=True)))) + else: + local() + except subprocess.SubprocessError as exc: + sys.exit('Remote command failed: '+type(exc).__name__+' (see target diagnostic above)') + except (ValueError,OSError,KeyError) as exc: + sys.exit(str(exc))