Files
rust-discovery/deploy/windows/Use-FirstLocalServiceJobWindow.ps1
T
2026-11-15 22:13:07 +01:00

240 lines
13 KiB
PowerShell

#requires -Version 5.1
#requires -RunAsAdministrator
# The operator supervises this one VM and uses MCP/WebUI separately for the job.
[CmdletBinding()]
param(
[Parameter(Mandatory)][ValidateSet('Open','Close','Unknown','Recover','Readback')][string]$Action,
[guid]$SampleId, [string]$SampleSha256,
[ValidateSet('passive','after-restart')][string]$SampleMode = 'passive',
[guid]$JobId, [guid]$AttemptId, [string]$ResultSha256
)
$ErrorActionPreference = 'Stop'
$installer = Join-Path $PSScriptRoot 'Set-FirstLocalServiceJobConfig.ps1'
$installerHash = '6ddc554bf85bb4a1382e14363351495d7a3515f281edf9ac56e16775d943850e'
if ((Get-FileHash -LiteralPath $installer).Hash -ne $installerHash) { throw 'Wrong configuration controller' }
$code = [Text.Encoding]::UTF8.GetString([IO.File]::ReadAllBytes($installer))
$first = "`n`$caseId = "
$last = "`nAssert-DirectoryAcl `$boot `$false`n"
$i = $code.IndexOf($first,[StringComparison]::Ordinal)
$j = $code.IndexOf($last,[StringComparison]::Ordinal)
if ($i -lt 0 -or $j -le $i -or $i -ne $code.LastIndexOf($first,[StringComparison]::Ordinal) -or
$j -ne $code.LastIndexOf($last,[StringComparison]::Ordinal)) { throw 'Configuration definition boundary' }
# Import the hash-pinned fixed paths and file checks. Its action body is excluded.
. ([scriptblock]::Create($code.Substring($i,$j-$i)))
Assert-DirectoryAcl $boot $false
Assert-DirectoryAcl $case $false
Assert-DirectoryAcl $root $true
$pairCase = Join-Path $boot ('job-passive-pair-'+$caseId)
$opened = Join-Path $case 'window-open-intent.json'
$started = Join-Path $case 'window-job-started.json'
$closed = Join-Path $case 'window-passive-confirmed.json'
$request = Join-Path $case 'window-close-request.json'
$restoreStage = Join-Path $case 'window-restore.candidate.json'
$replaced = Join-Path $case 'window-restored-job-config.json'
$svcName = 'RmmDiscoveryWindows'
$helperName = 'RmmDiscoverySystemHelper'
$command = '"' + $image + '" --service --config "' + $config + '"'
function Save-WindowRecord([string]$Name,$Data) {
Save-Record (Join-Path $case ('window-'+$Name+'.json')) $Data
}
function Get-WindowReadback {
$events = [ordered]@{}
foreach ($f in @(Get-ChildItem -LiteralPath $case -Filter 'window-*.json' -File)) {
$events[$f.Name] = Get-PublicHash $f.FullName
}
$result = Get-Readback
$result['events'] = $events
$result['job_config_sha256'] = (Read-PublicJson $ready).config_sha256
return $result
}
function Get-AgentService {
$s = Get-CimInstance Win32_Service -Filter "Name='RmmDiscoveryWindows'"
if ($s.PathName -ine $command -or $s.StartName -ine 'NT AUTHORITY\LocalService' -or $s.StartMode -ne 'Auto') {
throw 'Agent SCM registration changed'
}
return $s
}
function Get-LiveProcess([string]$Name,[string]$ExpectedPath,[string]$ExpectedHash) {
$s = Get-CimInstance Win32_Service -Filter ("Name='" + $Name + "'")
if ($s.State -ne 'Running' -or !$s.ProcessId) { throw "Service unavailable: $Name" }
$proc = [Diagnostics.Process]::GetProcessById($s.ProcessId)
try {
$null = $proc.Handle
$birth = $proc.StartTime.ToUniversalTime().ToFileTimeUtc().ToString([Globalization.CultureInfo]::InvariantCulture)
$after = Get-CimInstance Win32_Service -Filter ("Name='" + $Name + "'")
if ($proc.MainModule.FileName -ine $ExpectedPath -or (Get-PublicHash $ExpectedPath) -cne $ExpectedHash -or
$proc.HasExited -or $after.State -ne 'Running' -or $after.ProcessId -ne $proc.Id) { throw "Process changed: $Name" }
return @{pid=$proc.Id; birth=$birth}
} finally { $proc.Dispose() }
}
function Stop-WindowAgent($Expected) {
$null = Get-AgentService
$live = Get-LiveProcess $svcName $image $newAgent
if ($null -ne $Expected -and ($live.pid -ne $Expected.pid -or $live.birth -cne $Expected.birth)) {
throw 'Unexpected agent generation before stopping'
}
$proc = [Diagnostics.Process]::GetProcessById([int]$live.pid)
$svc = Get-Service $svcName
try {
$null = $proc.Handle
if ($proc.StartTime.ToUniversalTime().ToFileTimeUtc().ToString() -cne $live.birth -or
(Get-AgentService).ProcessId -ne $proc.Id) { throw 'Agent generation changed at stop' }
$svc.Stop()
$svc.WaitForStatus('Stopped',[TimeSpan]::FromSeconds(35))
if (!$proc.WaitForExit(5000)) { throw 'Old agent process still present' }
} finally { $proc.Dispose(); $svc.Dispose() }
}
function Start-WindowAgent([string]$Kind) {
$s = Get-AgentService
if ($s.State -ne 'Stopped' -or $s.ProcessId -ne 0) { throw 'Agent must be stopped before start' }
# Preserve the original SCM error and never repeat a start in the same mode.
Save-WindowRecord ($Kind+'-start-intent') @{utc=[DateTime]::UtcNow.ToString('o'); config_sha256=(Get-PublicHash $config)}
$svc = Get-Service $svcName
try { $svc.Start(); $svc.WaitForStatus('Running',[TimeSpan]::FromSeconds(30)) }
finally { $svc.Dispose() }
return Get-LiveProcess $svcName $image $newAgent
}
function Confirm-Samples {
if ($SampleId -eq [guid]::Empty -or $SampleSha256 -cnotmatch '^[0-9a-f]{64}$') { throw 'Validated server readback required' }
Assert-DirectoryAcl $pairCase $false
$samplePath = Join-Path $pairCase ('samples-'+$SampleMode+'-'+$SampleId.ToString()+'.json')
if ((Get-PublicHash $samplePath) -cne $SampleSha256) { throw 'Sample receipt hash mismatch' }
Assert-NormalPath $samplePath $false
if ((Get-Item -LiteralPath $samplePath).Length -gt 131072) { throw 'Sample receipt too large' }
$r = $utf8.GetString([IO.File]::ReadAllBytes($samplePath)) | ConvertFrom-Json
$profileReceipt = Join-Path $pairCase 'profile-published.json'
$pub = Read-PublicJson $profileReceipt
$a = Get-LiveProcess $svcName $image $newAgent
$h = Get-LiveProcess $helperName $helperImage $helper
if ($r.session_id -cne $SampleId.ToString() -or $r.pair_case_id -cne $caseId -or $r.mode -cne $SampleMode -or
$r.profile_sha256 -cne (Get-PublicHash $clock) -or $r.profile_receipt_sha256 -cne (Get-PublicHash $profileReceipt) -or
$pub.configuration.sha256 -cne $r.profile_sha256 -or $r.publication_since -cne $pub.publication_since -or
$r.agent_pid -ne $a.pid -or [string]$r.agent_birth_filetime -cne $a.birth -or
$r.helper_pid -ne $h.pid -or [string]$r.helper_birth_filetime -cne $h.birth -or
$r.connection_generation -lt 1 -or $r.agent_sample_sha256 -cnotmatch '^[0-9a-f]{64}$' -or
$r.helper_sample_sha256 -cnotmatch '^[0-9a-f]{64}$' -or $r.agent_sample_sha256 -ceq $r.helper_sample_sha256) {
throw 'Samples no longer bind the installed profile and both live service instances'
}
return $a
}
function Restore-Passive {
$intent = Read-PublicJson $opened
$jobHash = (Read-PublicJson $ready).config_sha256
if ($intent.case_id -cne $caseId -or $intent.config_sha256 -cne $jobHash -or $intent.original_sha256 -cne $oldConfig -or
(Get-PublicHash $original) -cne $oldConfig -or (Get-BytesDigest ($utf8.GetBytes($intent.passive_sddl))) -cne $oldConfigAcl) {
throw 'Original passive configuration proof missing'
}
$s = Get-AgentService
if ($s.State -in 'Start Pending','Stop Pending') {
$svc=Get-Service $svcName
try {
$waitFor = if ($s.State -eq 'Start Pending') { 'Running' } else { 'Stopped' }
$svc.WaitForStatus($waitFor,[TimeSpan]::FromSeconds(35))
} finally { $svc.Dispose() }
$s = Get-AgentService
}
$actual = Get-PublicHash $config
if ($actual -cne $oldConfig) {
if ($s.State -eq 'Running') { Stop-WindowAgent $null }
if ($actual -cne $jobHash -or (Get-AgentService).State -ne 'Stopped') { throw 'Unexpected live config: keep agent stopped' }
$acl = [Security.AccessControl.FileSecurity]::new()
$acl.SetSecurityDescriptorSddlForm($intent.passive_sddl)
if (!(Test-Path -LiteralPath $restoreStage)) {
Write-Once $restoreStage ([IO.File]::ReadAllBytes($original)) $acl
}
if ((Get-PublicHash $restoreStage) -cne $oldConfig -or (Get-PublicHash $config) -cne $jobHash -or
(Test-Path -LiteralPath $replaced)) { throw 'Unconfirmed restore state' }
Assert-FileAcl $restoreStage $acl
[IO.File]::Replace($restoreStage,$config,$replaced,$false)
if ((Get-PublicHash $replaced) -cne $jobHash) { throw 'Restored predecessor binding failed' }
}
if ((Get-PublicHash $config) -cne $oldConfig) { throw 'Passive configuration not restored' }
$acl = [Security.AccessControl.FileSecurity]::new()
$acl.SetSecurityDescriptorSddlForm($intent.passive_sddl)
Assert-FileAcl $config $acl
$s = Get-AgentService
if ($s.State -eq 'Running' -and (Test-Path -LiteralPath $started)) {
$jobGeneration = (Read-PublicJson $started).agent
$live = Get-LiveProcess $svcName $image $newAgent
if ($live.pid -eq $jobGeneration.pid -and $live.birth -ceq $jobGeneration.birth) {
Stop-WindowAgent $jobGeneration
$s = Get-AgentService
}
}
if ($s.State -eq 'Stopped') { $live = Start-WindowAgent 'passive' }
else { $live = Get-LiveProcess $svcName $image $newAgent }
if (!(Test-Path -LiteralPath $closed)) {
Save-WindowRecord 'passive-confirmed' @{utc=[DateTime]::UtcNow.ToString('o'); agent=$live; config_sha256=$oldConfig;
close_request_present=(Test-Path -LiteralPath $request); service_start_mode=$s.StartMode}
}
}
if ($Action -eq 'Readback') { Get-WindowReadback | ConvertTo-Json -Depth 8; return }
if ($Action -in 'Close','Unknown') {
if (!(Test-Path -LiteralPath $opened) -or (Test-Path -LiteralPath $closed)) { throw 'No open window' }
if ($Action -eq 'Close' -and ($JobId -eq [guid]::Empty -or $AttemptId -eq [guid]::Empty -or
$ResultSha256 -cnotmatch '^[0-9a-f]{64}$')) { throw 'Exact server terminal result reference required' }
Save-Record $request @{utc=[DateTime]::UtcNow.ToString('o'); action=$Action; job_id=$JobId;
attempt_id=$AttemptId; result_sha256=$ResultSha256}
'Close request recorded'
return
}
$lockPath = Join-Path $case 'window.lock'
$lock = [IO.File]::Open($lockPath,'OpenOrCreate','ReadWrite','None')
try {
if ($Action -eq 'Recover') {
if (!(Test-Path -LiteralPath $opened)) { throw 'No original open intent' }
Restore-Passive
Get-WindowReadback | ConvertTo-Json -Depth 8
return
}
if (Test-Path -LiteralPath $opened) { throw 'Existing window: readback or recover only' }
if ((Get-PublicHash $config) -cne $oldConfig -or (Get-PublicHash $original) -cne $oldConfig) { throw 'Expected original passive configuration' }
$null = Get-AgentService
$expected = Confirm-Samples
$passiveAcl = Get-OriginalAcl
$prepared = Read-PublicJson $ready
$deadline = [DateTime]::UtcNow.AddMinutes(12)
Save-Record $opened @{case_id=$caseId; utc=[DateTime]::UtcNow.ToString('o'); deadline=$deadline.ToString('o');
config_sha256=$prepared.config_sha256; original_sha256=$oldConfig; passive_sddl=$passiveAcl.Sddl;
sample_id=$SampleId; sample_sha256=$SampleSha256; passive_agent=$expected}
try {
Stop-WindowAgent $expected
$null = & $installer -Mode Activate
if ((Get-PublicHash $config) -cne $prepared.config_sha256 -or !(Test-Path -LiteralPath $done)) { throw 'Job configuration readback missing' }
$running = Start-WindowAgent 'job'
Save-Record $started @{utc=[DateTime]::UtcNow.ToString('o'); agent=$running; config_sha256=$prepared.config_sha256}
Write-Output 'Job window open. Awaiting the separate approved test and receipt.'
$watch = [Diagnostics.Stopwatch]::StartNew()
while ($watch.Elapsed.TotalMinutes -lt 12 -and [DateTime]::UtcNow -lt $deadline -and !(Test-Path -LiteralPath $request)) {
Start-Sleep -Seconds 2
$s = Get-AgentService
if ($s.State -ne 'Running' -or $s.ProcessId -ne $running.pid) { throw 'Active agent process lost; result unknown' }
}
if (!(Test-Path -LiteralPath $request)) { Save-Record $request @{utc=[DateTime]::UtcNow.ToString('o'); action='TimeoutUnknown'} }
} catch {
$errorRecord = Join-Path $case 'window-error.json'
if (!(Test-Path -LiteralPath $errorRecord)) {
$s = Get-CimInstance Win32_Service -Filter "Name='RmmDiscoveryWindows'"
Save-Record $errorRecord @{utc=[DateTime]::UtcNow.ToString('o'); type=$_.Exception.GetBaseException().GetType().FullName;
hresult=('0x{0:X8}' -f $_.Exception.GetBaseException().HResult); line=$_.InvocationInfo.ScriptLineNumber;
service_state=$s.State; service_exit_code=$s.ExitCode; service_specific_exit_code=$s.ServiceSpecificExitCode}
}
throw
} finally {
try { Restore-Passive }
catch {
$failure = Join-Path $case 'window-restore-error.json'
if (!(Test-Path -LiteralPath $failure)) {
$s = Get-CimInstance Win32_Service -Filter "Name='RmmDiscoveryWindows'"
Save-Record $failure @{utc=[DateTime]::UtcNow.ToString('o'); type=$_.Exception.GetBaseException().GetType().FullName;
hresult=('0x{0:X8}' -f $_.Exception.GetBaseException().HResult); line=$_.InvocationInfo.ScriptLineNumber;
service_state=$s.State; service_exit_code=$s.ExitCode; service_specific_exit_code=$s.ServiceSpecificExitCode}
}
throw
}
}
Get-WindowReadback | ConvertTo-Json -Depth 8
} finally { $lock.Dispose() }