config-central/tools/TemporarySsh.ps1

241 lines
11 KiB
PowerShell

#requires -Version 5.1
[CmdletBinding()]
param(
[ValidateSet('Enable', 'Disable')][string]$Action = $(if ($env:CONFIG_CENTRAL_TEMP_SSH -eq 'disable') { 'Disable' } else { 'Enable' }),
[string]$InstallMethod = $env:CONFIG_CENTRAL_TEMP_SSH_INSTALL,
[string]$ResultPath
)
# Kept identical in standalone entrypoints; verified by Output.Tests.ps1.
function Write-ConfigCentralMessage {
param([string]$Message, [ValidateSet('Info', 'Success', 'Warning', 'Error')][string]$Level = 'Info')
$color = switch ($Level) {
'Success' { 'Green' }
'Warning' { 'Yellow' }
'Error' { 'Red' }
default { 'Cyan' }
}
$redirected = if ($Level -eq 'Error') { [Console]::IsErrorRedirected } else { [Console]::IsOutputRedirected }
$useColor = -not $redirected -and $null -eq [Environment]::GetEnvironmentVariable('NO_COLOR')
if ($Level -eq 'Error') {
$previous = $null
try {
if ($useColor) { $previous = [Console]::ForegroundColor; [Console]::ForegroundColor = $color }
[Console]::Error.WriteLine($Message)
}
finally { if ($null -ne $previous) { [Console]::ForegroundColor = $previous } }
}
elseif ($useColor) { Write-Host $Message -ForegroundColor $color }
else { Write-Host $Message }
}
Set-StrictMode -Version 2.0
$ErrorActionPreference = 'Stop'
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$scriptUrl = 'https://proxy.dandaedre.com/gitea/Beffroi/config-central/raw/branch/main/tools/TemporarySsh.ps1'
$temporaryFirewallRule = 'ConfigCentral-Temporary-SSH'
if ([string]::IsNullOrWhiteSpace($InstallMethod)) { $InstallMethod = 'Fast' }
if ($InstallMethod -notin @('Fast', 'Inbox')) { throw "Unknown SSH install method '$InstallMethod'. Use Fast or Inbox." }
function Test-Administrator {
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = New-Object Security.Principal.WindowsPrincipal($identity)
return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}
function Invoke-ElevatedCopy {
$temporaryScript = Join-Path $env:TEMP "config-central-temporary-ssh-$([guid]::NewGuid().ToString('N')).ps1"
$resultFile = "$temporaryScript.result.json"
try {
Invoke-RestMethod -Uri $scriptUrl -OutFile $temporaryScript -UseBasicParsing
$arguments = "-NoProfile -ExecutionPolicy Bypass -File `"$temporaryScript`" -Action $Action -InstallMethod $InstallMethod -ResultPath `"$resultFile`""
try {
$process = Start-Process -FilePath 'powershell.exe' -Verb RunAs -ArgumentList $arguments -Wait -PassThru
}
catch { throw "Administrator approval was cancelled or could not start: $($_.Exception.Message)" }
if ($process.ExitCode -ne 0) {
if (Test-Path -LiteralPath $resultFile -PathType Leaf) {
$failure = Get-Content -LiteralPath $resultFile -Raw | ConvertFrom-Json
throw [string]$failure.message
}
throw "The administrator helper exited with code $($process.ExitCode) without reporting details."
}
Write-ConfigCentralMessage -Level Success -Message "Temporary SSH $($Action.ToLowerInvariant()) completed."
}
finally { Remove-Item -LiteralPath $temporaryScript, $resultFile -Force -ErrorAction SilentlyContinue }
}
function Install-OpenSshServer {
if (Get-Service -Name sshd -ErrorAction SilentlyContinue) { return }
if ($InstallMethod -eq 'Fast' -and (Get-Command winget.exe -ErrorAction SilentlyContinue)) {
Write-Host 'Installing the Microsoft OpenSSH Preview server through WinGet (fast path)...'
& winget.exe install `
--id Microsoft.OpenSSH.Preview `
--exact `
--source winget `
--scope machine `
--silent `
--disable-interactivity `
--accept-package-agreements `
--accept-source-agreements `
--override 'REMOVE=Client'
if ($LASTEXITCODE -eq 0 -and (Get-Service -Name sshd -ErrorAction SilentlyContinue)) { return }
Write-ConfigCentralMessage -Level Warning -Message "The fast OpenSSH install did not produce the sshd service (WinGet exit $LASTEXITCODE); falling back to the Windows capability."
}
$capability = Get-WindowsCapability -Online -Name 'OpenSSH.Server~~~~0.0.1.0'
if ($capability.State -ne 'Installed') {
Write-Host 'Installing the supported Windows OpenSSH capability through DISM; Windows servicing can take several minutes.'
& dism.exe /Online /Add-Capability /CapabilityName:OpenSSH.Server~~~~0.0.1.0 /NoRestart
if ($LASTEXITCODE -ne 0) { throw "DISM failed to install OpenSSH Server (exit $LASTEXITCODE)." }
}
if (-not (Get-Service -Name sshd -ErrorAction SilentlyContinue)) {
throw 'OpenSSH installation completed without creating the sshd service.'
}
}
function Disable-TemporarySsh {
param([string]$statePath, [string]$temporaryFirewallRule)
$state = if (Test-Path -LiteralPath $statePath -PathType Leaf) {
Get-Content -LiteralPath $statePath -Raw | ConvertFrom-Json
}
else { $null }
$temporaryRule = Get-NetFirewallRule -Name $temporaryFirewallRule -ErrorAction SilentlyContinue
if ($temporaryRule) { Remove-NetFirewallRule -Name $temporaryFirewallRule -ErrorAction Stop }
if ($null -eq $state) {
Write-ConfigCentralMessage -Level Warning -Message 'No temporary SSH state was found. The dedicated firewall rule was removed.'
return
}
$standardRule = Get-NetFirewallRule -Name 'OpenSSH-Server-In-TCP' -ErrorAction SilentlyContinue
if ($state.standardRuleExisted -and $standardRule) {
$enabled = if ($state.standardRuleEnabled) { 'True' } else { 'False' }
Set-NetFirewallRule -Name 'OpenSSH-Server-In-TCP' -Enabled $enabled -ErrorAction Stop
}
elseif ($standardRule) {
Disable-NetFirewallRule -Name 'OpenSSH-Server-In-TCP'
}
if (-not $state.serviceWasRunning) {
# Delay the stop so cleanup and output complete when Disable is invoked over SSH.
$stopCommand = 'Start-Sleep -Seconds 1; Stop-Service -Name sshd -ErrorAction SilentlyContinue'
Start-Process -FilePath 'powershell.exe' -WindowStyle Hidden -ArgumentList @('-NoProfile', '-Command', $stopCommand) | Out-Null
}
Remove-Item -LiteralPath $statePath -Force
Write-ConfigCentralMessage -Level Success -Message 'Temporary SSH firewall cleanup completed.'
if (-not $state.serviceWasRunning) { Write-Host 'The SSH service will stop shortly; an active SSH session may disconnect.' }
else { Write-Host 'SSH was already running before temporary access and has been left running.' }
return
}
try {
if ([Environment]::OSVersion.Platform -ne [PlatformID]::Win32NT) {
throw 'Temporary SSH setup runs only on Windows.'
}
if (-not (Test-Administrator)) {
Invoke-ElevatedCopy
$global:LASTEXITCODE = 0
return
}
$stateRoot = Join-Path $env:ProgramData 'ConfigCentral'
$statePath = Join-Path $stateRoot 'temporary-ssh.json'
if ($Action -eq 'Disable') {
Disable-TemporarySsh -statePath $statePath -temporaryFirewallRule $temporaryFirewallRule
$global:LASTEXITCODE = 0
return
}
New-Item -ItemType Directory -Path $stateRoot -Force | Out-Null
$existingState = if (Test-Path -LiteralPath $statePath -PathType Leaf) {
Get-Content -LiteralPath $statePath -Raw | ConvertFrom-Json
}
else { $null }
if ($null -eq $existingState) {
$service = Get-Service -Name sshd -ErrorAction SilentlyContinue
$standardRule = Get-NetFirewallRule -Name 'OpenSSH-Server-In-TCP' -ErrorAction SilentlyContinue
$state = [ordered]@{
schemaVersion = 1
serviceWasRunning = [bool]($service -and $service.Status -eq 'Running')
standardRuleExisted = [bool]$standardRule
standardRuleEnabled = [bool]($standardRule -and $standardRule.Enabled -eq 'True')
}
$state | ConvertTo-Json | Set-Content -LiteralPath $statePath -Encoding UTF8
}
else { $state = $existingState }
Install-OpenSshServer
$standardRule = Get-NetFirewallRule -Name 'OpenSSH-Server-In-TCP' -ErrorAction SilentlyContinue
if ($standardRule -and -not $state.standardRuleEnabled) {
Disable-NetFirewallRule -Name 'OpenSSH-Server-In-TCP'
}
Remove-NetFirewallRule -Name $temporaryFirewallRule -ErrorAction SilentlyContinue
New-NetFirewallRule `
-Name $temporaryFirewallRule `
-DisplayName 'Config Central temporary SSH access' `
-Enabled True `
-Profile Private `
-Direction Inbound `
-Protocol TCP `
-Action Allow `
-LocalPort 22 `
-RemoteAddress LocalSubnet | Out-Null
Start-Service -Name sshd
$sshdConfig = Join-Path $env:ProgramData 'ssh\sshd_config'
if (Test-Path -LiteralPath $sshdConfig -PathType Leaf) {
$passwordDisabled = Select-String -LiteralPath $sshdConfig -Pattern '^\s*PasswordAuthentication\s+no\s*$' -Quiet
if ($passwordDisabled) { Write-ConfigCentralMessage -Level Warning -Message 'Password authentication is disabled in sshd_config; use an existing SSH key.' }
}
$privateProfiles = @(Get-NetConnectionProfile -ErrorAction SilentlyContinue | Where-Object NetworkCategory -eq 'Private')
if ($privateProfiles.Count -eq 0) {
Write-ConfigCentralMessage -Level Warning -Message 'No active Private network profile was found. The temporary firewall rule will remain closed on Public networks.'
}
$addresses = @(
Get-NetIPConfiguration |
Where-Object { $_.NetAdapter.Status -eq 'Up' -and $_.IPv4Address } |
ForEach-Object { $_.IPv4Address.IPAddress } |
Where-Object { $_ -and $_ -notlike '169.254.*' } |
Sort-Object -Unique
)
Write-Host ''
Write-ConfigCentralMessage -Level Success -Message 'Temporary SSH access is ready. From CachyOS, open PowerShell directly with one of:'
foreach ($address in $addresses) { Write-Host " ssh -t $env:USERNAME@$address powershell.exe -NoLogo -NoProfile" }
if ($addresses.Count -eq 0) {
Write-ConfigCentralMessage -Level Warning -Message 'No usable IPv4 address was found. Run ipconfig and use the address of the Private network adapter.'
}
Write-Host ''
Write-Host 'Use the Windows account password, not a Windows Hello PIN.'
Write-Host "If a normal SSH login opens cmd.exe, type 'powershell.exe' before using PowerShell commands such as irm."
Write-Host 'Disable access afterward with:'
Write-Host " `$env:CONFIG_CENTRAL_TEMP_SSH='disable'; irm '$scriptUrl' | iex"
$global:LASTEXITCODE = 0
}
catch {
$message = $_.Exception.Message
if ($ResultPath) {
@{ message = $message } | ConvertTo-Json | Set-Content -LiteralPath $ResultPath -Encoding UTF8
}
Write-Host ''
Write-ConfigCentralMessage -Level Error -Message "Temporary SSH $($Action.ToLowerInvariant()) could not complete."
Write-Host $message
if ($Action -eq 'Disable') {
Write-Host 'Access may still be enabled. Retry Disable from a local administrator PowerShell window.'
Write-Host 'Saved cleanup state is kept until cleanup can be completed.'
}
if ($MyInvocation.MyCommand.PSObject.Properties['Path']) { exit 1 }
$global:LASTEXITCODE = 1
return
}