113 lines
6.3 KiB
PowerShell
113 lines
6.3 KiB
PowerShell
#requires -Version 5.1
|
|
#requires -RunAsAdministrator
|
|
[CmdletBinding()]
|
|
param(
|
|
[Parameter(Mandatory)][DateTimeOffset]$PreviousExpiry,
|
|
[Parameter(Mandatory)][DateTimeOffset]$Until,
|
|
[switch]$ResumeInterrupted
|
|
)
|
|
$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'
|
|
$expectedState = if ($ResumeInterrupted) { 'Disabled' } else { 'Ready' }
|
|
$expectedExpiry = if ($ResumeInterrupted) { $Until } else { $PreviousExpiry }
|
|
$mismatches = @(
|
|
if ($task.State -ne $expectedState) { "task state $($task.State) (expected $expectedState)" }
|
|
if (!$user.Enabled) { 'rmm-dev is disabled' }
|
|
if (!$user.AccountExpires) {
|
|
'rmm-dev has no account expiry'
|
|
} elseif ($user.AccountExpires.ToUniversalTime() -ne $expectedExpiry.UtcDateTime) {
|
|
"account expiry $($user.AccountExpires.ToUniversalTime().ToString('o')) (expected $($expectedExpiry.UtcDateTime.ToString('o')))"
|
|
}
|
|
if ([DateTimeOffset]::Parse($cfg.expires_at) -ne $expectedExpiry) {
|
|
"configuration expiry $($cfg.expires_at) (expected $($expectedExpiry.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')
|
|
$originalRaw = $raw
|
|
if ($ResumeInterrupted) {
|
|
$owners = @(Get-CimInstance Win32_Process -Filter "Name='powershell.exe' OR Name='pwsh.exe' OR Name='ssh.exe'" | Where-Object {
|
|
$_.ProcessId -ne $PID -and ($_.CommandLine -match '(?:rmm-window-[0-9a-f-]+|Open-ConsoleMaintenanceWindow)\.ps1' -or
|
|
($_.Name -eq 'ssh.exe' -and $_.CommandLine -match '127\.0\.0\.1:22240:127\.0\.0\.1:22222'))
|
|
})
|
|
if ($owners.Count) { throw 'An existing maintenance console or forwarding process is still active. End the original console with Ctrl+C first.' }
|
|
$copies = @(Get-ChildItem -LiteralPath $dir -Filter 'console-window-*.bak' -File -Force)
|
|
if ($copies.Count -ne 1 -or $copies[0].Name -notmatch '^console-window-[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}\.bak$' -or
|
|
($copies[0].Attributes -band [IO.FileAttributes]::ReparsePoint) -or $copies[0].Length -gt 32768) {
|
|
throw 'Expected one original maintenance-window backup.'
|
|
}
|
|
$backup = $copies[0].FullName
|
|
if (Test-Path -LiteralPath ($backup + '.closed')) { throw 'Backup already closed.' }
|
|
$originalRaw = [IO.File]::ReadAllText($backup)
|
|
$original = $originalRaw | ConvertFrom-Json
|
|
if ([DateTimeOffset]::Parse($original.expires_at) -ne $PreviousExpiry) { throw 'Backup expiry differs.' }
|
|
$original.expires_at = $Until.ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:sszzz')
|
|
if (($original | ConvertTo-Json -Compress) -cne $raw) { throw 'Backup does not reconstruct the current public configuration.' }
|
|
}
|
|
$candidate = $backup + '.new'
|
|
$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 {
|
|
if (!$ResumeInterrupted) {
|
|
$cfg.expires_at = $Until.ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:sszzz')
|
|
[IO.File]::WriteAllText($candidate, ($cfg | ConvertTo-Json -Compress), (New-Object Text.UTF8Encoding($false)))
|
|
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.' }
|
|
if ($ResumeInterrupted) {
|
|
$disabled = $true
|
|
} else {
|
|
[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 ($disabled -and (Test-Path -LiteralPath $backup)) { [IO.File]::Replace($backup, $configPath, ($backup + '.closed')) }
|
|
if ($disabled -and [IO.File]::ReadAllText($configPath) -ceq $originalRaw) { Enable-ScheduledTask -InputObject $task | Out-Null }
|
|
if (!$ResumeInterrupted -and (Test-Path -LiteralPath $candidate)) { Remove-Item -LiteralPath $candidate }
|
|
}
|