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

77 lines
5.9 KiB
PowerShell

#requires -Version 5.1
#requires -RunAsAdministrator
[CmdletBinding()]
param()
$ErrorActionPreference = 'Stop'
$statePath = Join-Path $env:ProgramData 'RmmDevAccess'
$sshData = Join-Path $env:ProgramData 'ssh'
$repairConfig = Get-Content -LiteralPath (Join-Path $PSScriptRoot 'repair-public.json') -Raw | ConvertFrom-Json
$bootstrapScript = Join-Path $statePath 'Bootstrap-DevAccess.ps1'
if ((Get-FileHash -LiteralPath $bootstrapScript -Algorithm SHA256).Hash.ToLowerInvariant() -ne $repairConfig.previous_bootstrap_sha256) { throw 'Existing bootstrap differs; no overwrite performed' }
$config = Get-Content -LiteralPath (Join-Path $statePath 'bootstrap-public.json') -Raw | ConvertFrom-Json
if ($config.server -ne 'discovery.ease-technologies.de' -or [DateTimeOffset]::Parse($config.expires_at) -le [DateTimeOffset]::UtcNow) { throw 'Existing bootstrap expired or invalid' }
if (-not (Get-LocalUser -Name 'rmm-dev' -ErrorAction SilentlyContinue)) { throw 'Expected existing development account missing' }
$sshdConfig = Join-Path $sshData 'sshd_config'
if ((Get-FileHash -LiteralPath $sshdConfig -Algorithm SHA256).Hash.ToLowerInvariant() -ne $repairConfig.previous_sshd_config_sha256) { throw 'SSH configuration changed; retained for inspection' }
$backupPath = Join-Path $statePath ('service-repair-' + [Guid]::NewGuid().ToString('N'))
[void](New-Item -ItemType Directory -Path $backupPath)
function Protect-SystemPath([string]$Path) {
$item = Get-Item -LiteralPath $Path
if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) { throw 'Reparse point refused' }
if ($item.PSIsContainer) { $acl = New-Object Security.AccessControl.DirectorySecurity }
else { $acl = New-Object Security.AccessControl.FileSecurity }
$acl.SetAccessRuleProtection($true, $false)
$system = New-Object Security.Principal.SecurityIdentifier 'S-1-5-18'
$admins = New-Object Security.Principal.SecurityIdentifier 'S-1-5-32-544'
$acl.SetOwner($system)
foreach ($sid in @($system, $admins)) {
if ($item.PSIsContainer) { $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
}
$paths = @($sshData, $sshdConfig, (Join-Path $sshData 'administrators_authorized_keys'))
foreach ($name in @('ssh_host_rsa_key', 'ssh_host_ecdsa_key', 'ssh_host_ed25519_key')) {
$candidate = Join-Path $sshData $name
if (Test-Path -LiteralPath $candidate) { $paths += $candidate }
}
$acls = @()
foreach ($path in $paths) { $acls += [ordered]@{ path=$path; sddl=(Get-Acl -LiteralPath $path).Sddl } }
$acls | ConvertTo-Json -Depth 4 | Set-Content -LiteralPath (Join-Path $backupPath 'acls-before.json') -Encoding UTF8
Copy-Item -LiteralPath $sshdConfig -Destination (Join-Path $backupPath 'sshd_config.before')
foreach ($path in $paths) { Protect-SystemPath $path }
Write-Host 'SSH directory, configuration and host-key ACLs set for SYSTEM and Administrators; keys preserved.'
$sshd = Join-Path $env:WINDIR 'System32\OpenSSH\sshd.exe'
& $sshd -t
if ($LASTEXITCODE -ne 0) { throw 'SSH configuration rejected; no key/account reset performed' }
try { Start-Service -Name sshd -ErrorAction Stop }
catch {
# Keep the original config/ACLs. Enable private startup logging for the
# service context; do not reinstall/regenerate identities or loosen access.
$logPath = Join-Path $sshData 'logs'
[void](New-Item -ItemType Directory -Path $logPath -Force); Protect-SystemPath $logPath
[IO.File]::AppendAllText($sshdConfig, "SyslogFacility LOCAL0`nLogLevel DEBUG3`n", (New-Object Text.UTF8Encoding($false)))
try { Start-Service -Name sshd -ErrorAction Stop } catch { Write-Host 'Service still fails; private service-context log follows.' }
Get-Content -LiteralPath (Join-Path $logPath 'sshd.log') -Tail 35 -ErrorAction SilentlyContinue
if ((Get-Service -Name sshd).Status -ne 'Running') { throw 'SSH service still stopped; retain repair evidence and report the startup log' }
}
Set-Service -Name sshd -StartupType Automatic
Get-NetFirewallRule -Name 'OpenSSH-Server-In-TCP' -ErrorAction SilentlyContinue | Disable-NetFirewallRule
if (-not (Get-NetTCPConnection -State Listen -LocalAddress 127.0.0.1 -LocalPort 22222 -ErrorAction SilentlyContinue)) { throw 'Expected loopback SSH listener absent' }
if (Get-ScheduledTask -TaskName 'RmmDevReverseTunnel' -ErrorAction SilentlyContinue) { throw 'Existing tunnel task retained; inspect instead of replacing' }
$action = New-ScheduledTaskAction -Execute (Join-Path $env:WINDIR 'System32\WindowsPowerShell\v1.0\powershell.exe') -Argument ('-NoProfile -NonInteractive -ExecutionPolicy RemoteSigned -File "' + $bootstrapScript + '" -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 (Join-Path $statePath 'tunnel_ed25519.pub') -Raw).Trim() -split '\s+')[0..1] -join ' '
[ordered]@{ windows_user='rmm-dev'; tunnel_public_key=$tunnelPublic; windows_host_public_key=$hostPublic;
expires_at=$config.expires_at; windows_architecture=$env:PROCESSOR_ARCHITECTURE; ssh_service='Running' } | ConvertTo-Json
& (Join-Path $env:WINDIR 'System32\OpenSSH\ssh-keygen.exe') -lf $hostKeyPath