Collect the successor service pair time reports from the Windows console

This commit is contained in:
2026-11-15 22:07:10 +01:00
parent bddfb26e67
commit 7a64002f74
2 changed files with 223 additions and 0 deletions
+184
View File
@@ -0,0 +1,184 @@
#requires -Version 5.1
#requires -RunAsAdministrator
[CmdletBinding()]
param(
[Parameter(Mandatory)][ValidateRange(1,9223372036854775807)][long]$Generation,
[switch]$AfterRestart
)
$ErrorActionPreference = 'Stop'
$caseId = '49c230d8-fb5d-4c64-96b6-e0edce03ed90'
$bootDir = 'C:\ProgramData\RustDiscoveryBootstrap'
$caseDir = Join-Path $bootDir "job-passive-pair-$caseId"
$publication = Join-Path $caseDir 'profile-published.json'
$profile = 'C:\ProgramData\RustDiscoverySystem\time-attestation.json'
$reader = Join-Path $PSScriptRoot 'Read-PassiveTimeSamples.ps1'
$readerHash = 'd9e2b9344c19af1296b86ec70ba754ef820f369ac5ec897979bd4233e0722d04'
$agentHash = 'df80b00fc2119b973d690053b9f9e4bdedd8fbc211f67599c3301eeb42e7702f'
$helperHash = '59675a3cbb3a5d213fc764f38379d6b81baaf9d47a7124470cc2767d4985763e'
$sessionId = [guid]::NewGuid().ToString()
function Assert-CasePath([string]$Path, [bool]$Directory) {
$item = Get-Item -LiteralPath $Path -Force
if ($item.PSIsContainer -ne $Directory -or ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)) {
throw 'Unexpected local evidence path type'
}
$sid = [Security.Principal.SecurityIdentifier]
$trusted = @('S-1-5-18','S-1-5-32-544')
$acl = Get-Acl -LiteralPath $Path
$rules = @($acl.GetAccessRules($true,$true,$sid))
if ($acl.GetOwner($sid).Value -notin $trusted -or !$rules.Count) { throw 'Unprotected local evidence path' }
foreach ($rule in $rules) {
if ($rule.AccessControlType -ne 'Allow' -or $rule.IdentityReference.Value -notin $trusted) {
throw 'Unexpected local evidence path access'
}
}
}
function Get-FileDigest([string]$Path) {
return (Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash.ToLowerInvariant()
}
function Get-ByteDigest([byte[]]$Bytes) {
$hash = [Security.Cryptography.SHA256]::Create()
try { return [BitConverter]::ToString($hash.ComputeHash($Bytes)).Replace('-','').ToLowerInvariant() }
finally { $hash.Dispose() }
}
function Get-BootUuid([string]$Ticks) {
if ($Ticks -cnotmatch '^[0-9]{17,19}$') { throw 'Invalid CIM boot ticks' }
$hash = Get-ByteDigest ([Text.Encoding]::ASCII.GetBytes("rmm.windows.boot.cim.ticks.v1:$Ticks"))
$variant = '89ab'[[Convert]::ToInt32($hash.Substring(16,1),16) -band 3]
return $hash.Substring(0,8)+'-'+$hash.Substring(8,4)+'-8'+$hash.Substring(13,3)+'-'+$variant+$hash.Substring(17,3)+'-'+$hash.Substring(20,12)
}
function Get-UtcNs($Value) {
if ($Value -is [datetime]) { $Value = $Value.ToUniversalTime().ToString('o') }
if ($Value -cnotmatch '^(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d)(?:\.(\d{1,9}))?Z$') { throw 'Expected UTC timestamp' }
$fraction = ([string]$Matches[2]).PadRight(9,'0')
$seconds = [datetime]::ParseExact($Matches[1],"yyyy-MM-dd'T'HH:mm:ss",[Globalization.CultureInfo]::InvariantCulture)
return [decimal]$seconds.Ticks * 100 + [decimal]$fraction
}
function Get-FiletimeNs([string]$Value) {
if ($Value -cnotmatch '^[0-9]{1,19}$') { throw 'Invalid filetime' }
return [decimal]([datetime]::FromFileTimeUtc([long]$Value).Ticks) * 100
}
function Get-VerifiedRecord($Wrapped, [string]$Role, $Native, $BootUuid, [decimal]$Since, [decimal]$Now) {
if ($null -eq $Wrapped) { throw 'Waiting for both service samples' }
$raw = [Convert]::FromBase64String($Wrapped.raw_base64)
if ($raw.Length -lt 1 -or $raw.Length -gt 8192 -or (Get-ByteDigest $raw) -cne $Wrapped.sha256 -or $Wrapped.metadata.dacl_checked -ne $true) {
throw 'Invalid wrapped report'
}
# Preserve JSON scalar types and duplicate keys, including all nine fractional digits.
$xmlReader = [Runtime.Serialization.Json.JsonReaderWriterFactory]::CreateJsonReader($raw,[Xml.XmlDictionaryReaderQuotas]::Max)
try { $doc = [xml]::new(); $doc.Load($xmlReader) } finally { $xmlReader.Close() }
$fields = @{}
$numbers = @('schema_version','agent_pid','connection_generation')
$strings = @('observed_at','role','windows_boot_id','verifier_incarnation','request_sha256','response_sha256')
if ($doc.DocumentElement.GetAttribute('type') -cne 'object') { throw 'Invalid report root' }
foreach ($node in $doc.DocumentElement.ChildNodes) {
$name = $node.Name
if ($fields.ContainsKey($name)) { throw 'Duplicate report field' }
$type = $node.GetAttribute('type')
if ($name -cin $numbers -and $type -ceq 'number' -and $node.InnerText -cmatch '^[1-9][0-9]*$') {
$fields[$name] = [long]$node.InnerText
} elseif ($name -cin $strings -and $type -ceq 'string') {
$fields[$name] = $node.InnerText
} else { throw 'Unrecognized report field or type' }
}
if ($fields.Count -ne 9 -or $fields.schema_version -ne 1 -or $fields.role -cne $Role -or
$fields.windows_boot_id -cne $BootUuid -or $fields.agent_pid -ne $Native.runtime.agent.pid -or
$fields.connection_generation -ne $Generation) { throw 'Waiting for current role, process, boot and generation' }
$uuid = [guid]::ParseExact($fields.verifier_incarnation,'D')
if ($uuid -eq [guid]::Empty -or $uuid.ToString() -cne $fields.verifier_incarnation -or
$fields.request_sha256 -cnotmatch '^[a-f0-9]{64}$' -or $fields.response_sha256 -cnotmatch '^[a-f0-9]{64}$') { throw 'Invalid report identity' }
$observed = Get-UtcNs $fields.observed_at
$written = Get-FiletimeNs $Wrapped.metadata.last_write_filetime
$birth = Get-FiletimeNs $Native.runtime.agent.birth_filetime
if ($Role -ceq 'system_helper') { $birth = [math]::Max($birth,(Get-FiletimeNs $Native.runtime.helper.birth_filetime)) }
if ($observed -lt $Since -or $observed -lt $birth -or $Now -lt $observed -or $Now -lt $written -or
$Now-$observed -gt 180000000000 -or $Now-$written -gt 180000000000 -or
$written-$observed -lt -2000000000 -or $written-$observed -gt 90000000000) { throw 'Waiting for fresh samples from current services' }
return $fields
}
function Read-NativeSamples([string]$Request) {
$start = [Diagnostics.ProcessStartInfo]::new()
$start.FileName = Join-Path ([Environment]::SystemDirectory) 'WindowsPowerShell\v1.0\powershell.exe'
$start.Arguments = '-NoProfile -NonInteractive -ExecutionPolicy RemoteSigned -File "'+$reader+'"'
$start.UseShellExecute = $false
$start.RedirectStandardInput = $true
$start.RedirectStandardOutput = $true
$start.RedirectStandardError = $true
$child = [Diagnostics.Process]::Start($start)
try {
$out = $child.StandardOutput.ReadToEndAsync()
$err = $child.StandardError.ReadToEndAsync()
$child.StandardInput.WriteLine($Request)
$child.StandardInput.Close()
if (!$child.WaitForExit(30000)) { throw 'Bounded public report read timed out' }
if (!$out.Wait(2000) -or !$err.Wait(2000) -or $child.ExitCode -ne 0 -or $err.Result.Length -gt 0 -or
$out.Result.Length -gt 65536) { throw 'Original reader did not return a complete native observation' }
return ($out.Result | ConvertFrom-Json)
} finally {
try { if (!$child.HasExited) { $child.Kill() } } finally { $child.Dispose() }
}
}
Assert-CasePath $bootDir $true
Assert-CasePath $caseDir $true
Assert-CasePath $publication $false
$publishedHash = Get-FileDigest $publication
$pub = Get-Content -LiteralPath $publication -Raw | ConvertFrom-Json
$profileHash = Get-FileDigest $profile
if ($pub.id -cne $caseId -or $pub.configuration.sha256 -cne $profileHash -or
$pub.agent.image_file.sha256 -cne $agentHash -or $pub.helper.image_file.sha256 -cne $helperHash -or
$pub.successor_revision -ne 2 -or $pub.job_mode -ne $false) { throw 'Unexpected pair publication' }
$since = Get-UtcNs $pub.publication_since
$request = @{id=$sessionId;agent_sha256=$agentHash;helper_sha256=$helperHash} | ConvertTo-Json -Compress
$clock = [Diagnostics.Stopwatch]::StartNew()
$mode = 'passive'
if ($AfterRestart) { $mode = 'after-restart' }
$readerHandle = [IO.File]::Open($reader,'Open','Read','Read')
try {
if ((Get-FileDigest $reader) -cne $readerHash) { throw 'Original public sample reader changed' }
do {
$native = Read-NativeSamples $request
if ($native.id -cne $sessionId -or $native.read_only -ne $true) { throw 'Invalid read response' }
$agent = $native.runtime.agent
$helper = $native.runtime.helper
if ($helper.birth_filetime -cne $pub.helper.kernel.creation_filetime -or $helper.pid -ne $pub.helper.kernel.pid) { throw 'Helper generation changed' }
if ($AfterRestart) {
if ([long]$agent.birth_filetime -le [long]$pub.agent.kernel.creation_filetime) { throw 'Waiting for a later agent generation' }
} elseif ($agent.birth_filetime -cne $pub.agent.kernel.creation_filetime -or $agent.pid -ne $pub.agent.kernel.pid) { throw 'Published agent generation changed' }
$bootId = Get-BootUuid $native.boot_ticks
$now = Get-UtcNs $native.observed_at
try {
$agentFile = $native.reports.'agent-time-sample.json'
$helperFile = $native.reports.'helper-time-sample.json'
$a = Get-VerifiedRecord $agentFile 'agent' $native $bootId $since $now
$h = Get-VerifiedRecord $helperFile 'system_helper' $native $bootId $since $now
foreach ($key in 'verifier_incarnation','request_sha256','response_sha256') {
if ($a[$key] -ceq $h[$key]) { throw 'Time roles are not independent' }
}
break
} catch {
if (!$_.Exception.Message.StartsWith('Waiting for ') -or $clock.Elapsed.TotalSeconds -ge 120) { throw }
Start-Sleep -Seconds 2
}
} while ($true)
} finally { $readerHandle.Dispose() }
if ((Get-FileDigest $profile) -cne $profileHash -or (Get-FileDigest $publication) -cne $publishedHash) { throw 'Profile changed during read' }
$result = [ordered]@{
session_id=$sessionId; pair_case_id=$caseId; mode=$mode; profile_sha256=$profileHash
profile_receipt_sha256=$publishedHash; publication_since=$pub.publication_since; observed_at=$native.observed_at
agent_pid=$agent.pid; agent_birth_filetime=$agent.birth_filetime; helper_pid=$helper.pid; helper_birth_filetime=$helper.birth_filetime
windows_boot_id=$bootId; connection_generation=$Generation; agent_sample_sha256=$agentFile.sha256; helper_sample_sha256=$helperFile.sha256
agent_observed_at=$a.observed_at; helper_observed_at=$h.observed_at; agent_verifier_id=$a.verifier_incarnation; helper_verifier_id=$h.verifier_incarnation
reader_sha256=$readerHash
}
$result.native = $native
$bytes = [Text.Encoding]::UTF8.GetBytes(($result | ConvertTo-Json -Depth 16 -Compress))
$file = Join-Path $caseDir "samples-$mode-$sessionId.json"
$out = [IO.File]::Open($file,'CreateNew','Write','None')
try { $out.Write($bytes,0,$bytes.Length); $out.Flush($true) } finally { $out.Dispose() }
Assert-CasePath $file $false
$receiptHash = Get-FileDigest $file
if ($receiptHash -cne (Get-ByteDigest $bytes)) { throw 'Receipt readback failed' }
$result.Remove('native')
$result.receipt_sha256 = $receiptHash
$result | ConvertTo-Json -Depth 5 -Compress
+39
View File
@@ -149,3 +149,42 @@ Beim separaten Rücklesen stimmten die zwei ursprünglichen Rollenberichte
mit den validierten Einträgen überein. Der Server führte weiterhin nur
`windows.base/1`, `heartbeat/1` und `agent.update/1`. Für einen späteren
Auftrag muss die Uhr beim Prüfen des Grants erneut die Frischegrenzen erfüllen.
### Konsolenlesung des nachfolgenden Dienstpaars
`deploy/windows/Read-JobPairTimeSamples.ps1` bindet den ursprünglichen Leser
mit SHA-256 `d9e2b9344c19af1296b86ec70ba754ef820f369ac5ec897979bd4233e0722d04`
an den Paarfall `49c230d8-fb5d-4c64-96b6-e0edce03ed90`. Vor dem Aufruf
muss die tatsächliche Verbindungsgeneration auf dem Projektserver gelesen
werden. Der Wrapper prüft die aktuelle Profilquittung und die Prozessgeburt
beider Dienste, die Rechte und Dateikennungen anhand der Leserausgabe,
den CIM-Bootbezug, die zwei unterschiedlichen Rollen und die Frische der
ungeschmälerten Originalreports. Bei fehlenden oder alten Beispielen liest
er bis zu zwei Minuten erneut. Für einen bereits laufenden Leseprozess
gilt ein maximales Einzelbudget von 30 Sekunden.
**Geplanter Aufruf als Administrator auf dem Gast:**
`Read-JobPairTimeSamples.ps1 -Generation <aktuelle Servergeneration>`.
Der unveränderte `Read-PassiveTimeSamples.ps1` muss daneben liegen. Die
lokale Quittung entsteht je Aufruf einmalig als
`samples-passive-<Sitzungs-ID>.json` im Paarfall. Sie enthält die
Originalreports in Base64, ihre SHA-256, Sicherheits-/Dateimetadaten und
Prozesszeugen. Die Konsolenausgabe nennt den SHA-256 der Quittung. Für
die vollständige Abnahme muss der Betreiber danach die identische
Servergeneration und denselben Windows-Boot sowie die Zeit des Reads
unabhängig anhand der Serveruhr bestätigen. Der Wrapper meldet seinen
lokalen Befund, ohne eine serverseitige Prüfung zu behaupten.
`-AfterRestart` verlangt die Geburt eines später gestarteten Agentprozesses
und aktuelle Belege für genau diese Instanz. Der Build `fcec400` publiziert
die Dateien jeweils beim ersten erfolgreichen Vergleich einer **passiven**
Verbindung. Nach Umschaltung auf Jobbetrieb müssen Job-Sync und
Startgrant die aktuelle Freigabe belegen. Dateien aus einem früheren
Prozess können diesen Nachweis nicht erbringen.
Lokal bestanden die Parserprüfung, je ein unverändertes Fixture für Agent
und Helper sowie neun Ablehnungsfälle für doppelte Felder, falschen Typ,
PID, Boot, Rolle, Generation, Schema und Zeitgrenzen. Die Boot-ID stimmte
mit dem vorhandenen Python-Prüfer überein. Zeitvergleiche unterschieden
eine Nanosekunde auch bei der neunstelligen Rust-Ausgabe. Die lokale Prüfung
enthielt keine Ausführung des Lesers auf dem Windowsgast.