diff --git a/TASKS.md b/TASKS.md index 7ee2727..70bf074 100644 --- a/TASKS.md +++ b/TASKS.md @@ -101,6 +101,7 @@ open until it is run on disposable machines with the required account setups. requiring elevation. - [x] Add targeted application adapters or registry settings for concrete needs. - [x] Document key-based remote administration from a Linux workstation. +- [x] Add reversible temporary SSH access for quick cross-platform debugging. - [ ] Add explicit package removal or managed-file cleanup if requested. ## Requested desktop configuration diff --git a/tests/TemporarySsh.Tests.ps1 b/tests/TemporarySsh.Tests.ps1 new file mode 100644 index 0000000..268ba48 --- /dev/null +++ b/tests/TemporarySsh.Tests.ps1 @@ -0,0 +1,12 @@ +BeforeAll { + $script:temporarySshPath = "$PSScriptRoot/../tools/TemporarySsh.ps1" +} + +Describe 'Temporary SSH helper' { + It 'parses under the PowerShell language parser' { + $tokens = $null + $errors = $null + [void][System.Management.Automation.Language.Parser]::ParseFile($temporarySshPath, [ref]$tokens, [ref]$errors) + $errors.Count | Should -Be 0 + } +} diff --git a/tools/TemporarySsh.ps1 b/tools/TemporarySsh.ps1 new file mode 100644 index 0000000..88d65a3 --- /dev/null +++ b/tools/TemporarySsh.ps1 @@ -0,0 +1,145 @@ +#requires -Version 5.1 +[CmdletBinding()] +param( + [ValidateSet('Enable', 'Disable')][string]$Action = $(if ($env:CONFIG_CENTRAL_TEMP_SSH -eq 'disable') { 'Disable' } else { 'Enable' }) +) + +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' + +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" + try { + Invoke-RestMethod -Uri $scriptUrl -OutFile $temporaryScript -UseBasicParsing + $arguments = "-NoProfile -ExecutionPolicy Bypass -File `"$temporaryScript`" -Action $Action" + 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)." } + } + finally { Remove-Item -LiteralPath $temporaryScript -Force -ErrorAction SilentlyContinue } +} + +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') { + $state = if (Test-Path -LiteralPath $statePath -PathType Leaf) { + Get-Content -LiteralPath $statePath -Raw | ConvertFrom-Json + } + else { $null } + + Remove-NetFirewallRule -Name $temporaryFirewallRule -ErrorAction SilentlyContinue + if ($null -eq $state) { + Write-Warning '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) { + Set-NetFirewallRule -Name 'OpenSSH-Server-In-TCP' -Enabled ([bool]$state.standardRuleEnabled) + } + 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 + } + 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 } + +$capability = Get-WindowsCapability -Online -Name 'OpenSSH.Server~~~~0.0.1.0' +if ($capability.State -ne 'Installed') { + Write-Host 'Installing the Windows OpenSSH Server capability...' + Add-WindowsCapability -Online -Name 'OpenSSH.Server~~~~0.0.1.0' | Out-Null +} + +$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, use one of:' +foreach ($address in $addresses) { Write-Host " ssh $env:USERNAME@$address" } +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 'Disable access afterward with:' +Write-Host " `$env:CONFIG_CENTRAL_TEMP_SSH='disable'; irm '$scriptUrl' | iex"