Files
rust-discovery/deploy/windows/Bootstrap-DevAccess.ps1
2026-11-13 14:42:44 +01:00

151 lines
10 KiB
PowerShell

#requires -Version 5.1
#requires -RunAsAdministrator
[CmdletBinding()]
param([switch]$MaintainTunnel)
$ErrorActionPreference = 'Stop'
$statePath = Join-Path $env:ProgramData 'RmmDevAccess'
function Protect-AdminFile([string]$Path, [switch]$SystemOwner) {
$directory = (Get-Item -LiteralPath $Path).PSIsContainer
if ($directory) { $acl = New-Object Security.AccessControl.DirectorySecurity }
else { $acl = New-Object Security.AccessControl.FileSecurity }
$acl.SetAccessRuleProtection($true, $false)
$admins = New-Object Security.Principal.SecurityIdentifier 'S-1-5-32-544'
$system = New-Object Security.Principal.SecurityIdentifier 'S-1-5-18'
if ($SystemOwner) { $acl.SetOwner($system) } else { $acl.SetOwner($admins) }
foreach ($sid in @($admins, $system)) {
if ($directory) {
$rule = New-Object Security.AccessControl.FileSystemAccessRule($sid, 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow')
} else { $rule = New-Object Security.AccessControl.FileSystemAccessRule($sid, 'FullControl', 'Allow') }
[void]$acl.AddAccessRule($rule)
}
Set-Acl -LiteralPath $Path -AclObject $acl
}
function Write-Utf8([string]$Path, [string]$Text) {
[IO.File]::WriteAllText($Path, $Text, (New-Object Text.UTF8Encoding($false)))
}
if ($MaintainTunnel) {
$config = Get-Content -LiteralPath (Join-Path $statePath 'bootstrap-public.json') -Raw | ConvertFrom-Json
$expires = [DateTimeOffset]::Parse($config.expires_at)
$sshPath = Join-Path $env:WINDIR 'System32\OpenSSH\ssh.exe'
$sshArguments = @('-N', '-T', '-i', (Join-Path $statePath 'tunnel_ed25519'),
'-o', 'BatchMode=yes', '-o', 'IdentitiesOnly=yes', '-o', 'ForwardAgent=no',
'-o', 'StrictHostKeyChecking=yes', '-o', ('UserKnownHostsFile=' + (Join-Path $statePath 'known_hosts')),
'-o', 'GlobalKnownHostsFile=NUL', '-o', 'ExitOnForwardFailure=yes',
'-o', 'ServerAliveInterval=30', '-o', 'ServerAliveCountMax=3', '-o', 'ConnectTimeout=10',
'-R', '127.0.0.1:22240:127.0.0.1:22222', 'rmm-win-tunnel@discovery.ease-technologies.de')
while ([DateTimeOffset]::UtcNow -lt $expires) {
$start = New-Object Diagnostics.ProcessStartInfo
$start.FileName = $sshPath
# Fixed arguments contain neither quotes nor a final backslash. Quoting
# every argument preserves ProgramData paths containing spaces on PS5.1.
foreach ($argument in $sshArguments) { if ($argument.Contains('"') -or $argument.EndsWith('\')) { throw 'Unsafe SSH argument' } }
$start.Arguments = ($sshArguments | ForEach-Object { '"' + $_ + '"' }) -join ' '
$start.UseShellExecute = $false; $start.CreateNoWindow = $true
$start.RedirectStandardOutput = $true; $start.RedirectStandardError = $true
$tunnelProcess = New-Object Diagnostics.Process
$tunnelProcess.StartInfo = $start
try {
[void]$tunnelProcess.Start()
$stdoutTask = $tunnelProcess.StandardOutput.ReadToEndAsync()
$stderrTask = $tunnelProcess.StandardError.ReadToEndAsync()
while (-not $tunnelProcess.WaitForExit(15000)) {
if ([DateTimeOffset]::UtcNow -ge $expires) { $tunnelProcess.Kill(); break }
}
} finally { $tunnelProcess.Dispose() }
if ([DateTimeOffset]::UtcNow -lt $expires) { Start-Sleep -Seconds 30 }
}
exit 0
}
if ($env:OS -ne 'Windows_NT' -or $env:PROCESSOR_ARCHITECTURE -ne 'AMD64') { throw 'Windows x64 and elevated 64-bit PowerShell required' }
$publicPath = Join-Path $PSScriptRoot 'bootstrap-public.json'
$config = Get-Content -LiteralPath $publicPath -Raw | ConvertFrom-Json
if ($config.schema_version -ne 1 -or $config.server -ne 'discovery.ease-technologies.de') { throw 'Invalid bootstrap configuration' }
$expires = [DateTimeOffset]::Parse($config.expires_at)
if ($expires -le [DateTimeOffset]::UtcNow -or $expires -gt [DateTimeOffset]::UtcNow.AddHours(25)) { throw 'Bootstrap window expired or invalid' }
if ($config.notebook_public_key -notmatch '^ssh-(ed25519|rsa) [A-Za-z0-9+/=]+$') { throw 'Invalid notebook public key' }
if ($config.server_host_key -notmatch '^ssh-ed25519 [A-Za-z0-9+/=]+$') { throw 'Invalid pinned server host key' }
if ((Test-Path -LiteralPath $statePath) -or (Get-LocalUser -Name 'rmm-dev' -ErrorAction SilentlyContinue)) { throw 'Existing RMM bootstrap retained; do not overwrite or reset it' }
$existingSsh = Get-Service -Name sshd -ErrorAction SilentlyContinue
if ($existingSsh -and $existingSsh.Status -eq 'Running') { throw 'Existing running SSH service requires separate review' }
if (Get-ScheduledTask -TaskName 'RmmDevReverseTunnel' -ErrorAction SilentlyContinue) { throw 'Existing tunnel task retained' }
# Installs only the Windows optional OpenSSH capabilities. Never reboot or run
# an OS/package update. RestartNeeded stops before account/service provisioning.
foreach ($capability in @('OpenSSH.Client~~~~0.0.1.0', 'OpenSSH.Server~~~~0.0.1.0')) {
if ((Get-WindowsCapability -Online -Name $capability).State -ne 'Installed') {
$installed = Add-WindowsCapability -Online -Name $capability
if ($installed.RestartNeeded) { throw 'OpenSSH reports RestartNeeded; no reboot was initiated. Review before continuing.' }
}
}
[void](New-Item -ItemType Directory -Path $statePath); Protect-AdminFile $statePath
Copy-Item -LiteralPath $PSCommandPath -Destination (Join-Path $statePath 'Bootstrap-DevAccess.ps1')
Copy-Item -LiteralPath $publicPath -Destination (Join-Path $statePath 'bootstrap-public.json')
Write-Utf8 (Join-Path $statePath 'known_hosts') ('discovery.ease-technologies.de ' + $config.server_host_key + "`n")
$sshDirectory = Join-Path $env:WINDIR 'System32\OpenSSH'
$keygen = Join-Path $sshDirectory 'ssh-keygen.exe'
$keyPath = Join-Path $statePath 'tunnel_ed25519'
$keyStart = New-Object Diagnostics.ProcessStartInfo
$keyStart.FileName = $keygen; $keyStart.Arguments = '-q -t ed25519 -N "" -f "' + $keyPath + '"'
$keyStart.UseShellExecute = $false; $keyStart.CreateNoWindow = $true
$keyProcess = [Diagnostics.Process]::Start($keyStart)
$keyProcess.WaitForExit()
if ($keyProcess.ExitCode -ne 0) { throw 'Tunnel key generation failed; retained bootstrap requires inspection' }
$keyProcess.Dispose(); Protect-AdminFile $keyPath
# Dedicated temporary local administrator; password stays in VM memory, SSH is
# public-key only. Notebook private key and cloud root credentials are not used.
$random = New-Object byte[] 48
$rng = [Security.Cryptography.RandomNumberGenerator]::Create(); $rng.GetBytes($random); $rng.Dispose()
$password = ConvertTo-SecureString ('Rmm!7' + [Convert]::ToBase64String($random)) -AsPlainText -Force
$account = New-LocalUser -Name 'rmm-dev' -Password $password -AccountExpires $expires.LocalDateTime -Description 'Temporary RMM development SSH access'
$password.Dispose(); [Array]::Clear($random, 0, $random.Length)
$adminGroup = Get-LocalGroup -SID 'S-1-5-32-544'
Add-LocalGroupMember -Group $adminGroup -Member $account
$sshData = Join-Path $env:ProgramData 'ssh'
[void](New-Item -ItemType Directory -Path $sshData -Force)
Protect-AdminFile $sshData -SystemOwner
$sshdConfig = Join-Path $sshData 'sshd_config'
if (Test-Path -LiteralPath $sshdConfig) { Copy-Item -LiteralPath $sshdConfig -Destination (Join-Path $statePath 'sshd_config.before') }
$authorized = Join-Path $sshData 'administrators_authorized_keys'
if (Test-Path -LiteralPath $authorized) { Copy-Item -LiteralPath $authorized -Destination (Join-Path $statePath 'administrators_authorized_keys.before') }
Write-Utf8 $authorized ($config.notebook_public_key + "`n"); Protect-AdminFile $authorized -SystemOwner
$serverConfig = @('Port 22222', 'ListenAddress 127.0.0.1', 'PubkeyAuthentication yes',
'PasswordAuthentication no', 'AuthenticationMethods publickey', 'AllowUsers rmm-dev',
'AuthorizedKeysFile __PROGRAMDATA__/ssh/administrators_authorized_keys',
'AllowTcpForwarding no', 'AllowAgentForwarding no', 'PermitTTY yes',
'Subsystem sftp sftp-server.exe') -join "`n"
Write-Utf8 $sshdConfig ($serverConfig + "`n"); Protect-AdminFile $sshdConfig -SystemOwner
& $keygen -A | Out-Null
if ($LASTEXITCODE -ne 0) { throw 'SSH host key generation failed' }
foreach ($name in @('ssh_host_rsa_key', 'ssh_host_ecdsa_key', 'ssh_host_ed25519_key')) {
$hostPrivatePath = Join-Path $sshData $name
if (Test-Path -LiteralPath $hostPrivatePath) { Protect-AdminFile $hostPrivatePath -SystemOwner }
}
& (Join-Path $sshDirectory 'sshd.exe') -t
if ($LASTEXITCODE -ne 0) { throw 'SSH configuration rejected; retained files require inspection' }
[void](New-Item -Path 'HKLM:\SOFTWARE\OpenSSH' -Force)
New-ItemProperty -Path 'HKLM:\SOFTWARE\OpenSSH' -Name DefaultShell -Value (Join-Path $env:WINDIR 'System32\WindowsPowerShell\v1.0\powershell.exe') -PropertyType String -Force | Out-Null
Set-Service -Name sshd -StartupType Automatic; Start-Service -Name sshd
Get-NetFirewallRule -Name 'OpenSSH-Server-In-TCP' -ErrorAction SilentlyContinue | Disable-NetFirewallRule
$taskScript = Join-Path $statePath 'Bootstrap-DevAccess.ps1'
$action = New-ScheduledTaskAction -Execute (Join-Path $env:WINDIR 'System32\WindowsPowerShell\v1.0\powershell.exe') -Argument ('-NoProfile -NonInteractive -ExecutionPolicy RemoteSigned -File "' + $taskScript + '" -MaintainTunnel')
$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -MultipleInstances IgnoreNew -ExecutionTimeLimit ([TimeSpan]::Zero) -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries
$principal = New-ScheduledTaskPrincipal -UserId 'SYSTEM' -LogonType ServiceAccount -RunLevel Highest
$task = New-ScheduledTask -Action $action -Trigger (New-ScheduledTaskTrigger -AtStartup) -Settings $settings -Principal $principal
Register-ScheduledTask -TaskName 'RmmDevReverseTunnel' -InputObject $task | Out-Null
Start-ScheduledTask -TaskName 'RmmDevReverseTunnel'
$hostKeyPath = Join-Path $sshData 'ssh_host_ed25519_key.pub'
$hostPublic = ((Get-Content -LiteralPath $hostKeyPath -Raw).Trim() -split '\s+')[0..1] -join ' '
$tunnelPublic = ((Get-Content -LiteralPath ($keyPath + '.pub') -Raw).Trim() -split '\s+')[0..1] -join ' '
Write-Host 'Bitte nur diese oeffentliche Ausgabe zurueckgeben; der Tunnel verbindet nach Hinterlegung des Public Keys automatisch:'
[ordered]@{ windows_user='rmm-dev'; tunnel_public_key=$tunnelPublic; windows_host_public_key=$hostPublic;
expires_at=$config.expires_at; windows_architecture=$env:PROCESSOR_ARCHITECTURE } | ConvertTo-Json
& $keygen -lf $hostKeyPath