Files
rust-discovery/deploy/windows/Open-TimeProfileReceiptWindow.ps1
T
2026-11-15 20:29:08 +01:00

138 lines
8.6 KiB
PowerShell

#requires -Version 5.1
#requires -RunAsAdministrator
# The relay receives a fixed public receipt. There is no command reader.
param([Parameter(Mandatory)][DateTimeOffset]$Until)
$ErrorActionPreference = 'Stop'
$deadline = [DateTimeOffset]::UtcNow.AddMinutes(12)
if ($deadline -gt $until) { $deadline = $until }
if ($deadline -le [DateTimeOffset]::UtcNow) { throw 'Das Wartungsfenster ist abgelaufen.' }
$base = 'https://gitea.incoso.eu/kevin_janssen/rust-discovery/raw/commit/38e6df51ea57a76ec2d5462513d59e855f36c0f4/deploy/windows'
$bootstrap = 'C:\ProgramData\RustDiscoveryBootstrap'
$caseId = 'ad9fd154-b2be-4f5d-9e17-65abb721ceaf'
$case = Join-Path $bootstrap "time-profile-$caseId"
$access = 'C:\ProgramData\RmmDevAccess'
$sshBin = Join-Path $env:WINDIR 'System32\OpenSSH'
$known = Join-Path $access 'known_hosts'
$key = Join-Path $access 'tunnel_ed25519'
$fp = & "$sshBin\ssh-keygen.exe" -lf $known
if ($LASTEXITCODE -ne 0 -or @($fp).Count -ne 1 -or
$fp.Split(' ')[1] -cne 'SHA256:+NEin4XJc3CbhjQi7/ZpMIgxOrXn8AT2tlpTaXW5quw') { throw 'Server-Hostpin stimmt nicht.' }
$session = [guid]::NewGuid().ToString()
$work = Join-Path $bootstrap "time-receipt-$session"
$null = New-Item -ItemType Directory -Path $work
$listener = $null
$ssh = $null
$scripts = [ordered]@{
'Complete-OriginalTimeProfile.ps1' = 'c2fb92ebd0f4ab19545b55ad92d7a9b21ec6e3604d33107d0dd78882162be131'
'Read-PassiveTimeSamples.ps1' = 'd9e2b9344c19af1296b86ec70ba754ef820f369ac5ec897979bd4233e0722d04'
}
try {
foreach ($name in $scripts.Keys) {
$path = Join-Path $work $name
Invoke-WebRequest -UseBasicParsing -Uri "$base/$name" -OutFile $path -TimeoutSec 30
if ((Get-FileHash -LiteralPath $path).Hash -ne $scripts[$name]) { throw "Downloadhash: $name" }
Unblock-File -LiteralPath $path
}
$listener = [Net.Sockets.TcpListener]::new([Net.IPAddress]::Loopback, 0)
$listener.Start(4)
$port = $listener.LocalEndpoint.Port
$options = @('-F','NUL','-N','-T','-o','BatchMode=yes','-o','IdentitiesOnly=yes',
'-o','ForwardAgent=no','-o','StrictHostKeyChecking=yes','-o','GlobalKnownHostsFile=NUL',
'-o',"UserKnownHostsFile=$known",'-o','ExitOnForwardFailure=yes','-o','ConnectTimeout=10',
'-o','ServerAliveInterval=15','-o','ServerAliveCountMax=2','-i',$key,
'-R',"127.0.0.1:22240:127.0.0.1:$port",'rmm-win-tunnel@discovery.ease-technologies.de')
$ssh = Start-Process -FilePath "$sshBin\ssh.exe" -ArgumentList $options -PassThru -NoNewWindow
if ($ssh.WaitForExit(1800)) { throw "SSH Exit $($ssh.ExitCode)" }
Write-Host 'Wartungsfenster aktiv. Dieses Fenster offen lassen. Strg+C beendet es.'
$receipt = [ordered]@{session=$session; case_id=$caseId; method='initial_create'; phase='preflight'; read_only_channel=$true}
$result = Join-Path $case 'console-initial-create-result.json'
$intentPath = Join-Path $case 'console-initial-create-intent.json'
$failurePath = Join-Path $case 'console-initial-create-error.json'
$receipt.finalizer_invoked = $false
try {
if (Test-Path -LiteralPath $failurePath) { throw 'Previous profile finalization error recorded' }
if (!(Test-Path -LiteralPath $result)) {
if (Test-Path -LiteralPath $intentPath) { throw 'Previous profile finalization intent without result' }
$receipt.finalizer_invoked = $true
$null = & (Join-Path $work 'Complete-OriginalTimeProfile.ps1') -InitialCreate
}
$record = Get-Content -LiteralPath $result -Raw | ConvertFrom-Json
$actual = Get-FileHash -LiteralPath 'C:\ProgramData\RustDiscoverySystem\time-attestation.json'
if ($record.id -cne $caseId -or $record.installed -ne $true -or
$record.initial_create -ne $true -or $record.source_candidate_preserved -ne $true -or
$record.services_changed -ne $false -or $record.private_key_read -ne $false -or $record.clock_runtime_qualified -ne $false -or
$actual.Hash -ne '2b4a8a7080770304b80e2a665fa5f5ee1ebbd9182e7c80b184e75b114575b42b') { throw 'Unexpected publication result' }
$marker = Get-Content -LiteralPath $intentPath -Raw | ConvertFrom-Json
if ($marker.id -cne $caseId -or $marker.utc -cne $record.publication_since -or
$marker.config_sha256 -ne $actual.Hash -or $record.configuration.sha256 -ne $actual.Hash -or
$record.original_candidate.file_id -cne '6d990300000003000000000000000000' -or
$record.configuration.file_id -cnotmatch '^[0-9a-f]{32}$' -or $record.configuration.file_id -ceq '6d990300000003000000000000000000') { throw 'Unexpected finalization intent' }
$receipt.phase = 'published'
$receipt.publication_since = $record.publication_since
$receipt.initial_create = $record.initial_create
$receipt.source_candidate_preserved = $record.source_candidate_preserved
$receipt.services_changed = $record.services_changed
$receipt.private_key_read = $record.private_key_read
$receipt.clock_runtime_qualified = $record.clock_runtime_qualified
$receipt.source_id = $record.original_candidate.file_id
$receipt.target_id = $record.configuration.file_id
$receipt.config_sha256 = $actual.Hash.ToLowerInvariant()
$receipt.result_sha256 = (Get-FileHash -LiteralPath $result).Hash
} catch {
$receipt.phase = 'finalization_failed'
$receipt.exception_type = $_.Exception.GetBaseException().GetType().FullName
$receipt.line = $_.InvocationInfo.ScriptLineNumber
$receipt.file = [IO.Path]::GetFileName($_.InvocationInfo.ScriptName)
Write-Warning $_.Exception.Message
if (Test-Path -LiteralPath $failurePath) {
$failure = Get-Content -LiteralPath $failurePath -Raw | ConvertFrom-Json
if ($failure.id -ceq $caseId -and $failure.hresult -cmatch '^0x[0-9A-Fa-f]{8}$') {
$receipt.hresult = $failure.hresult
if ($failure.phase -cmatch '^[A-Za-z][A-Za-z0-9_.-]{0,63}$') { $receipt.failure_phase = $failure.phase }
$descriptor = $failure.creation_descriptor
if ($failure.phase -ceq 'verify_creation' -and $null -ne $descriptor -and
$descriptor.expected_sddl -is [string] -and $descriptor.expected_sddl.Length -le 4096 -and
$descriptor.actual_sddl -is [string] -and $descriptor.actual_sddl.Length -le 4096) {
$receipt.creation_descriptor = @{
expected_sddl=$descriptor.expected_sddl; actual_sddl=$descriptor.actual_sddl; bytes=$descriptor.bytes
}
if ($descriptor.file_id -cmatch '^[0-9a-f]{32}$' -and $descriptor.volume_serial -cmatch '^[0-9]{1,20}$') {
$receipt.creation_descriptor.file_id = $descriptor.file_id
$receipt.creation_descriptor.volume_serial = $descriptor.volume_serial
}
}
}
}
}
$readScript = Join-Path $work 'Read-PassiveTimeSamples.ps1'
$readInput = @{id=$session; agent_sha256='0549d9ebea73cff996938f859b92192cc333de194128d7c6859a3f1d2e85893c'; helper_sha256='59675a3cbb3a5d213fc764f38379d6b81baaf9d47a7124470cc2767d4985763e'} | ConvertTo-Json -Compress
while ([DateTimeOffset]::UtcNow -lt $deadline -and !$ssh.HasExited) {
if (!$listener.Pending()) { Start-Sleep -Milliseconds 250; continue }
$client = $listener.AcceptTcpClient()
try {
if ($receipt.phase -eq 'published') {
$receipt.native = $null
try {
$json = $readInput | & "$env:WINDIR\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -ExecutionPolicy RemoteSigned -File $readScript
if ($LASTEXITCODE -eq 0) { $receipt.native = ($json -join "`n") | ConvertFrom-Json }
} catch { Write-Warning 'Passive Zeitbelege aktuell nicht lesbar.' }
}
$client.SendTimeout = 3000
$body = [Text.Encoding]::UTF8.GetBytes(($receipt | ConvertTo-Json -Depth 16 -Compress))
if ($body.Length -gt 65536) { throw 'Ergebnis zu gross.' }
$client.GetStream().Write($body,0,$body.Length)
} catch { Write-Warning $_.Exception.Message } finally { $client.Dispose() }
}
} finally {
if ($null -ne $ssh) {
try { if (!$ssh.HasExited) { $ssh.Kill(); $ssh.WaitForExit() } } finally { $ssh.Dispose() }
}
if ($null -ne $listener) { $listener.Stop() }
foreach ($name in $scripts.Keys) {
$path = Join-Path $work $name
if (Test-Path -LiteralPath $path) { Remove-Item -LiteralPath $path }
}
if ((Get-ChildItem -LiteralPath $work -Force | Measure-Object).Count -eq 0) { [IO.Directory]::Delete($work) }
}