From 2f75ff88fc55098c0dbd23247b12ee325103f445 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Mon, 19 Oct 2026 14:27:08 +0200 Subject: [PATCH] Fix SSH disable restoration and report elevated failure details --- TASKS.md | 1 + docs/advanced-remote-access.md | 9 ++ tests/TemporarySsh.Tests.ps1 | 68 +++++++++++ tools/TemporarySsh.ps1 | 214 ++++++++++++++++++++------------- 4 files changed, 206 insertions(+), 86 deletions(-) diff --git a/TASKS.md b/TASKS.md index 2741600..69f6e66 100644 --- a/TASKS.md +++ b/TASKS.md @@ -134,3 +134,4 @@ open until it is run on disposable machines with the required account setups. - [x] Accept signed registry DWORD/QWORD exports and validate the complete MPC-HC declaration with mocked registry writes. - [x] Color terminal item statuses while preserving plain redirected output and supporting NO_COLOR. - [x] Preserve existing registry keys during MPC-HC apply and document registry-only storage and capture filtering. +- [x] Restore SSH firewall state using enum names, preserve retry state on cleanup failure, and show the elevated error without a wrapper stack trace. diff --git a/docs/advanced-remote-access.md b/docs/advanced-remote-access.md index a05b6cd..22fdeb1 100644 --- a/docs/advanced-remote-access.md +++ b/docs/advanced-remote-access.md @@ -307,3 +307,12 @@ Run `ssh -vvv cc-office` on CachyOS for client diagnostics. Windows records SSH events under **Applications and Services Logs > OpenSSH > Operational** in Event Viewer. Keep one known-working session open while changing keys or `sshd_config`. + + +If disabling fails, the helper now shows the underlying administrator error +instead of only an exit code. Retry from a local administrator PowerShell window. +The saved restoration state at `%ProgramData%\ConfigCentral\temporary-ssh.json` +is retained if firewall restoration or launching the service-stop helper fails. +Do not delete it before retrying. Disabling from SSH may disconnect the session +when the delayed service stop runs. An SSH service that was already running +before temporary access is intentionally left running. diff --git a/tests/TemporarySsh.Tests.ps1 b/tests/TemporarySsh.Tests.ps1 index 268ba48..4bc685e 100644 --- a/tests/TemporarySsh.Tests.ps1 +++ b/tests/TemporarySsh.Tests.ps1 @@ -1,5 +1,16 @@ BeforeAll { $script:temporarySshPath = "$PSScriptRoot/../tools/TemporarySsh.ps1" + $tokens = $null; $errors = $null + $ast = [System.Management.Automation.Language.Parser]::ParseFile($temporarySshPath, [ref]$tokens, [ref]$errors) + foreach ($name in @('Disable-TemporarySsh', 'Invoke-ElevatedCopy')) { + $node = $ast.Find({ param($n) $n -is [System.Management.Automation.Language.FunctionDefinitionAst] -and $n.Name -eq $name }, $true) + . ([scriptblock]::Create($node.Extent.Text)) + } + function Get-NetFirewallRule { param($Name) } + function Remove-NetFirewallRule { param($Name) } + function Set-NetFirewallRule { param($Name, $Enabled) } + function Disable-NetFirewallRule { param($Name) } + } Describe 'Temporary SSH helper' { @@ -10,3 +21,60 @@ Describe 'Temporary SSH helper' { $errors.Count | Should -Be 0 } } + +Describe 'Temporary SSH disable' { + BeforeEach { + $script:stateFile = Join-Path $TestDrive 'temporary-ssh.json' + '{"standardRuleExisted":true,"standardRuleEnabled":false,"serviceWasRunning":true}' | Set-Content $stateFile + Mock Get-NetFirewallRule { [pscustomobject]@{ Name = $Name } } + Mock Remove-NetFirewallRule {} + Mock Set-NetFirewallRule {} + Mock Disable-NetFirewallRule {} + Mock Start-Process {} + } + It 'restores a disabled rule using its enum name and keeps a previously running service' { + Disable-TemporarySsh -statePath $stateFile -temporaryFirewallRule 'temporary' + Should -Invoke Set-NetFirewallRule -Times 1 -ParameterFilter { $Enabled -is [string] -and $Enabled -eq 'False' } + Should -Invoke Start-Process -Times 0 + Test-Path $stateFile | Should -BeFalse + } + It 'retains state and the original error when firewall restoration fails' { + Mock Set-NetFirewallRule { throw 'Firewall access denied' } + { Disable-TemporarySsh -statePath $stateFile -temporaryFirewallRule 'temporary' } | Should -Throw '*Firewall access denied*' + Test-Path $stateFile | Should -BeTrue + Should -Invoke Start-Process -Times 0 + } + It 'retains state if it cannot launch the delayed service stop' { + '{"standardRuleExisted":true,"standardRuleEnabled":true,"serviceWasRunning":false}' | Set-Content $stateFile + Mock Start-Process { throw 'Could not launch service stop' } + { Disable-TemporarySsh -statePath $stateFile -temporaryFirewallRule 'temporary' } | Should -Throw '*Could not launch service stop*' + Test-Path $stateFile | Should -BeTrue + Should -Invoke Set-NetFirewallRule -Times 1 -ParameterFilter { $Enabled -eq 'True' } + } + It 'does not modify the standard service or rule when no saved state exists' { + Remove-Item $stateFile + Disable-TemporarySsh -statePath $stateFile -temporaryFirewallRule 'temporary' + Should -Invoke Set-NetFirewallRule -Times 0 + Should -Invoke Start-Process -Times 0 + } +} + +Describe 'Elevated SSH failure details' { + It 'returns the worker reason and removes temporary transport files' { + $previousTemp = $env:TEMP + $env:TEMP = $TestDrive + $scriptUrl = 'https://example.test/helper.ps1' + $Action = 'Disable'; $InstallMethod = 'Fast' + Mock Invoke-RestMethod { 'script' | Set-Content $OutFile } + Mock Start-Process { + $resultFile = [regex]::Match($ArgumentList, '-ResultPath "([^"]+)"').Groups[1].Value + '{"message":"Firewall access denied"}' | Set-Content $resultFile + [pscustomobject]@{ ExitCode = 1 } + } + try { + { Invoke-ElevatedCopy } | Should -Throw '*Firewall access denied*' + @(Get-ChildItem $TestDrive -Filter 'config-central-temporary-ssh-*').Count | Should -Be 0 + } + finally { $env:TEMP = $previousTemp } + } +} diff --git a/tools/TemporarySsh.ps1 b/tools/TemporarySsh.ps1 index 49b5dd7..bb0392d 100644 --- a/tools/TemporarySsh.ps1 +++ b/tools/TemporarySsh.ps1 @@ -2,7 +2,8 @@ [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]$InstallMethod = $env:CONFIG_CENTRAL_TEMP_SSH_INSTALL, + [string]$ResultPath ) Set-StrictMode -Version 2.0 @@ -22,16 +23,25 @@ function Test-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" + $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) { throw "Temporary SSH setup failed with exit code $($process.ExitCode)." } + 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-Host "Temporary SSH $($Action.ToLowerInvariant()) completed." + } - finally { Remove-Item -LiteralPath $temporaryScript -Force -ErrorAction SilentlyContinue } + finally { Remove-Item -LiteralPath $temporaryScript, $resultFile -Force -ErrorAction SilentlyContinue } } function Install-OpenSshServer { @@ -64,24 +74,15 @@ function Install-OpenSshServer { } } -if ([Environment]::OSVersion.Platform -ne [PlatformID]::Win32NT) { - throw 'Temporary SSH setup runs only on Windows.' -} -if (-not (Test-Administrator)) { - Invoke-ElevatedCopy - return -} - -$stateRoot = Join-Path $env:ProgramData 'ConfigCentral' -$statePath = Join-Path $stateRoot 'temporary-ssh.json' - -if ($Action -eq 'Disable') { +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 } - Remove-NetFirewallRule -Name $temporaryFirewallRule -ErrorAction SilentlyContinue + $temporaryRule = Get-NetFirewallRule -Name $temporaryFirewallRule -ErrorAction SilentlyContinue + if ($temporaryRule) { Remove-NetFirewallRule -Name $temporaryFirewallRule -ErrorAction Stop } if ($null -eq $state) { Write-Warning 'No temporary SSH state was found. The dedicated firewall rule was removed.' return @@ -89,87 +90,128 @@ if ($Action -eq 'Disable') { $standardRule = Get-NetFirewallRule -Name 'OpenSSH-Server-In-TCP' -ErrorAction SilentlyContinue if ($state.standardRuleExisted -and $standardRule) { - Set-NetFirewallRule -Name 'OpenSSH-Server-In-TCP' -Enabled ([bool]$state.standardRuleEnabled) + $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' } - Remove-Item -LiteralPath $statePath -Force - Write-Host 'Temporary SSH access is disabled and the previous service/firewall state is restored.' 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-Host '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 } -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') +try { + if ([Environment]::OSVersion.Platform -ne [PlatformID]::Win32NT) { + throw 'Temporary SSH setup runs only on Windows.' } - $state | ConvertTo-Json | Set-Content -LiteralPath $statePath -Encoding UTF8 + 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-Warning '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-Warning '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-Host '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-Warning '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 } -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' +catch { + $message = $_.Exception.Message + if ($ResultPath) { + @{ message = $message } | ConvertTo-Json | Set-Content -LiteralPath $ResultPath -Encoding UTF8 + } + Write-Host '' + Write-Host "Temporary SSH $($Action.ToLowerInvariant()) could not complete." -ForegroundColor Yellow + 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 } -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-Warning '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-Warning '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-Host '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-Warning '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"