Files
rust-discovery/deploy/windows/Open-ConsoleMaintenanceWindow.ps1
T
2026-11-15 15:59:26 +01:00

84 lines
4.4 KiB
PowerShell

#requires -Version 5.1
#requires -RunAsAdministrator
[CmdletBinding()]
param(
[Parameter(Mandatory)][DateTimeOffset]$PreviousExpiry,
[Parameter(Mandatory)][DateTimeOffset]$Until
)
$ErrorActionPreference = 'Stop'
$utcNow = [DateTimeOffset]::UtcNow
if ($PreviousExpiry -ge $utcNow -or $Until -le $utcNow -or $Until -gt $utcNow.AddHours(4)) {
throw 'Expected an expired previous window and a new deadline within four hours.'
}
$dir = 'C:\ProgramData\RmmDevAccess'
$configPath = Join-Path $dir 'bootstrap-public.json'
$raw = [IO.File]::ReadAllText($configPath)
$cfg = $raw | ConvertFrom-Json
$user = Get-LocalUser -Name 'rmm-dev'
$task = Get-ScheduledTask -TaskPath '\' -TaskName 'RmmDevReverseTunnel'
$mismatches = @(
if ($task.State -ne 'Ready') { "task state $($task.State) (expected Ready)" }
if (!$user.Enabled) { 'rmm-dev is disabled' }
if (!$user.AccountExpires) {
'rmm-dev has no account expiry'
} elseif ($user.AccountExpires.ToUniversalTime() -ne $PreviousExpiry.UtcDateTime) {
"account expiry $($user.AccountExpires.ToUniversalTime().ToString('o')) (expected $($PreviousExpiry.UtcDateTime.ToString('o')))"
}
if ([DateTimeOffset]::Parse($cfg.expires_at) -ne $PreviousExpiry) {
"configuration expiry $($cfg.expires_at) (expected $($PreviousExpiry.UtcDateTime.ToString('o')))"
}
if ($cfg.server -cne 'discovery.ease-technologies.de') { 'configured server differs' }
$sshdState = (Get-Service -Name sshd).Status
if ($sshdState -ne 'Running') { "sshd state $sshdState (expected Running)" }
)
if ($mismatches.Count -gt 0) {
throw ('Maintenance window preflight failed: ' + ($mismatches -join ', '))
}
$pinned = (Get-Content -LiteralPath (Join-Path $dir 'known_hosts') -Raw).Trim()
if ($pinned -cne ('discovery.ease-technologies.de ' + $cfg.server_host_key)) {
throw 'Unexpected SSH host pin.'
}
$listeners = @(Get-NetTCPConnection -State Listen -LocalPort 22222)
if ($listeners.Count -ne 1 -or $listeners[0].LocalAddress -ne '127.0.0.1') {
throw 'Expected only the original loopback SSH listener.'
}
$backup = Join-Path $dir ('console-window-' + [guid]::NewGuid().ToString() + '.bak')
$candidate = $backup + '.new'
$cfg.expires_at = $Until.ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:sszzz')
[IO.File]::WriteAllText($candidate, ($cfg | ConvertTo-Json -Compress), (New-Object Text.UTF8Encoding($false)))
$sshArgs = @('-F','NUL','-N','-T','-o','BatchMode=yes','-o','IdentitiesOnly=yes',
'-o','ForwardAgent=no','-o','StrictHostKeyChecking=yes','-o','GlobalKnownHostsFile=NUL',
'-o',('UserKnownHostsFile=' + $dir + '\known_hosts'),'-o','ExitOnForwardFailure=yes',
'-o','ConnectTimeout=10','-o','ServerAliveInterval=15','-o','ServerAliveCountMax=2',
'-i',($dir + '\tunnel_ed25519'),'-R','127.0.0.1:22240:127.0.0.1:22222',
'rmm-win-tunnel@discovery.ease-technologies.de')
$ssh = $null
$disabled = $false
$accountChanged = $false
try {
Disable-ScheduledTask -InputObject $task | Out-Null
$disabled = $true
if ((Get-ScheduledTask -TaskPath '\' -TaskName $task.TaskName).State -ne 'Disabled' -or
[IO.File]::ReadAllText($configPath) -cne $raw) { throw 'Existing bootstrap changed.' }
[IO.File]::Replace($candidate, $configPath, $backup)
Set-LocalUser -SID $user.SID -AccountExpires $Until.LocalDateTime
$accountChanged = $true
if ((Get-LocalUser -SID $user.SID).AccountExpires.ToUniversalTime() -ne $Until.UtcDateTime) {
throw 'Unexpected account expiry after renewal.'
}
$ssh = Start-Process -FilePath "$env:WINDIR\System32\OpenSSH\ssh.exe" -ArgumentList $sshArgs -PassThru -NoNewWindow
if ($ssh.WaitForExit(1500)) { throw "SSH exited with code $($ssh.ExitCode)." }
Write-Host "Tunnelfenster gestartet bis $($Until.LocalDateTime). Zum Beenden Strg+C druecken."
while ([DateTimeOffset]::UtcNow -lt $Until) {
if ($ssh.WaitForExit(500)) { throw "SSH exited with code $($ssh.ExitCode)." }
}
} finally {
if ($null -ne $ssh) {
try { if (!$ssh.HasExited) { $ssh.Kill(); $ssh.WaitForExit() } } finally { $ssh.Dispose() }
}
if ($accountChanged) { Set-LocalUser -SID $user.SID -AccountExpires $PreviousExpiry.LocalDateTime }
if (Test-Path -LiteralPath $backup) { [IO.File]::Replace($backup, $configPath, ($backup + '.closed')) }
if ($disabled -and [IO.File]::ReadAllText($configPath) -ceq $raw) { Enable-ScheduledTask -InputObject $task | Out-Null }
if (Test-Path -LiteralPath $candidate) { Remove-Item -LiteralPath $candidate }
}