# win-ssh-kit: make this Windows box reachable over SSH (key auth only) in one go. # Two ways to run it: # USB: enable-ssh.bat -> installs OpenSSH from the MSI in the kit (offline) # Web: irm ssh.saweisra.com | iex -> keys are embedded by build-web.sh, # MSI is downloaded from GitHub and checked against a pinned SHA256 # Falls back to Add-WindowsCapability if neither MSI source works. # Everything it changes is recorded under HKLM:\SOFTWARE\win-ssh-kit so # disable-ssh.ps1 can put the machine back exactly as it was. param( [string]$User = 'fixer', # local admin account created for remote login [switch]$UseCurrentUser # skip creating $User, log in as whoever ran this ) $ErrorActionPreference = 'Stop' if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole( [Security.Principal.WindowsBuiltInRole]::Administrator)) { Write-Host 'Run this from an ADMIN PowerShell (right-click > Run as administrator).' -ForegroundColor Red return } $Web = -not $PSScriptRoot # irm | iex has no script path $WebBase = 'https://ssh.saweisra.com' $MsiUrl = 'https://github.com/PowerShell/Win32-OpenSSH/releases/download/10.4.0.0p1-Preview/OpenSSH-Win64-v10.4.0.0.msi' $MsiSha256 = '788d8643464a01eb63640a2fd746f9ed23d106b5a901a35f88dc8cd40e446ac9' $EmbeddedKeys = @('ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAILUoFEo9AJYZmgqRnekJRhoL+XQDCbf9xz1nEs5CS/QT win-ssh-kit') if ($Web) { $Kit = $null } else { $Kit = Split-Path $PSScriptRoot -Parent } $State = 'HKLM:\SOFTWARE\win-ssh-kit' $Home_ = Join-Path $env:ProgramData 'win-ssh-kit' $SshDir = Join-Path $env:ProgramData 'ssh' $AdminsSid = 'S-1-5-32-544' Start-Transcript -Path (Join-Path $env:TEMP 'win-ssh-kit.log') -Append | Out-Null function Step($m) { Write-Host "==> $m" -ForegroundColor Cyan } function Note($m) { Write-Host " $m" } function Warn($m) { Write-Host " !! $m" -ForegroundColor Yellow } # New-Item -Force on an existing registry key recreates it EMPTY (wipes values), # so only create keys that aren't there. function Ensure-Key($k) { if (-not (Test-Path $k)) { New-Item $k -Force | Out-Null } } Ensure-Key $State New-Item $Home_ -ItemType Directory -Force | Out-Null # Keep a copy of the cleanup script on the machine: works after the USB is gone # and when run over SSH. [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 if ($Web) { Invoke-WebRequest "$WebBase/disable-ssh.ps1" -UseBasicParsing -OutFile (Join-Path $Home_ 'disable-ssh.ps1') } else { Copy-Item (Join-Path $PSScriptRoot 'disable-ssh.ps1') $Home_ -Force } # --- 1. OpenSSH Server ------------------------------------------------------ Step 'OpenSSH Server' if (Get-Service sshd -ErrorAction SilentlyContinue) { Note 'already installed, leaving it as is' } else { $msiPath = $null if ($Kit) { $msiPath = (Get-ChildItem $Kit -Filter 'OpenSSH-Win64-*.msi' | Select-Object -First 1).FullName } if (-not $msiPath) { try { Note 'downloading OpenSSH MSI from GitHub' $msiPath = Join-Path $env:TEMP 'OpenSSH-Win64.msi' $ProgressPreference = 'SilentlyContinue' # PS 5.1 download is 10x slower with the progress bar Invoke-WebRequest $MsiUrl -UseBasicParsing -OutFile $msiPath if ((Get-FileHash $msiPath -Algorithm SHA256).Hash -ne $MsiSha256) { Remove-Item $msiPath -Force; $msiPath = $null; Warn 'MSI checksum mismatch, not using it' } } catch { $msiPath = $null; Warn "download failed: $($_.Exception.Message)" } } if ($msiPath) { Note "installing $(Split-Path $msiPath -Leaf)" $p = Start-Process msiexec.exe -Wait -PassThru ` -ArgumentList "/i `"$msiPath`" /qn /norestart" if ($p.ExitCode -notin 0, 3010) { throw "msiexec exit code $($p.ExitCode)" } Set-ItemProperty $State InstalledVia 'msi' } else { Note 'no MSI, trying Windows optional feature (needs internet)' Add-WindowsCapability -Online -Name 'OpenSSH.Server~~~~0.0.1.0' | Out-Null Set-ItemProperty $State InstalledVia 'capability' } } # First start generates host keys and %ProgramData%\ssh\sshd_config. Set-Service sshd -StartupType Automatic Start-Service sshd for ($i = 0; $i -lt 20 -and -not (Test-Path "$SshDir\sshd_config"); $i++) { Start-Sleep 1 } # --- 2. Login account ------------------------------------------------------- Step 'Login account' $Login = $null if (-not $UseCurrentUser) { try { if (-not (Get-LocalUser $User -ErrorAction SilentlyContinue)) { $chars = [char[]]'abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789' # Never typed by anyone: login is key-only. Just satisfies complexity policy. $pw = (-join (1..24 | ForEach-Object { $chars | Get-Random })) + 'a7Z!' New-LocalUser -Name $User -Password (ConvertTo-SecureString $pw -AsPlainText -Force) ` -PasswordNeverExpires -AccountNeverExpires -Description 'win-ssh-kit temporary' | Out-Null Set-ItemProperty $State CreatedUser $User # Hide it from the sign-in screen so operators don't see a stray account. $ul = 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\SpecialAccounts\UserList' Ensure-Key $ul New-ItemProperty $ul -Name $User -Value 0 -PropertyType DWord -Force | Out-Null Note "created local user '$User' (hidden from sign-in screen)" } else { Note "local user '$User' already exists" } # Not Get-LocalGroupMember: it throws on AzureAD-joined boxes (orphan SIDs). try { Add-LocalGroupMember -SID $AdminsSid -Member $User } catch [Microsoft.PowerShell.Commands.MemberExistsException] { } $Login = $User } catch { Warn "could not create '$User' ($($_.Exception.Message)); falling back to current user" } } if (-not $Login) { $Login = (whoami) } Note "login as: $Login" # --- 3. Authorized keys ----------------------------------------------------- # Admin accounts read %ProgramData%\ssh\administrators_authorized_keys (not ~\.ssh), # and sshd silently ignores it unless only SYSTEM + Administrators can touch it. Step 'Authorized keys' $akf = Join-Path $SshDir 'administrators_authorized_keys' $have = @(); if (Test-Path $akf) { $have = @(Get-Content $akf) } if ($Kit) { $src = Get-ChildItem (Join-Path $Kit 'keys') -Filter *.pub | Get-Content } else { $src = $EmbeddedKeys } $new = @($src | Where-Object { $_ -match '^(ssh-|ecdsa-|sk-)' -and $have -notcontains $_ }) if (-not ($have + $new | Where-Object { $_ -match '^(ssh-|ecdsa-|sk-)' })) { throw 'no public key to install (keys/ empty?)' } if ($new.Count) { [IO.File]::WriteAllLines($akf, [string[]]($have + $new), (New-Object Text.UTF8Encoding $false)) $prev = @((Get-ItemProperty $State -Name AddedKeys -ErrorAction SilentlyContinue).AddedKeys) New-ItemProperty $State -Name AddedKeys -PropertyType MultiString -Force ` -Value ([string[]](@($prev | Where-Object { $_ }) + $new)) | Out-Null } icacls $akf /inheritance:r /grant '*S-1-5-32-544:F' /grant '*S-1-5-18:F' | Out-Null Note "$($new.Count) key(s) added, $(@(Get-Content $akf).Count) total" # --- 4. sshd config --------------------------------------------------------- Step 'sshd config' # The stock config matches 'Match Group administrators' by name; on Spanish / # Portuguese Windows the group is 'Administradores', so point it at the real name. $adminsName = (Get-LocalGroup -SID $AdminsSid).Name $cfgPath = Join-Path $SshDir 'sshd_config' $cfg = Get-Content $cfgPath -Raw $orig = $cfg if ($adminsName -ne 'Administrators' -and $cfg -match '(?m)^Match Group administrators\s*$') { $cfg = $cfg -replace '(?m)^Match Group administrators\s*$', "Match Group `"$adminsName`"" Note "admins group is '$adminsName', Match line fixed" } # Key-only while sshd is up: nobody on the LAN can guess other accounts' passwords. # Must sit above any Match block (sshd keeps the first value it sees). if ($cfg -notmatch '(?m)^PasswordAuthentication no') { $cfg = "# win-ssh-kit: key-only login`r`nPasswordAuthentication no`r`n" + $cfg Note 'password login disabled (keys only)' } if ($cfg -ne $orig) { # Keep the very first original; a re-run must not overwrite it with a patched copy. if (-not (Test-Path "$cfgPath.win-ssh-kit.bak")) { Copy-Item $cfgPath "$cfgPath.win-ssh-kit.bak" } [IO.File]::WriteAllText($cfgPath, $cfg, (New-Object Text.UTF8Encoding $false)) Set-ItemProperty $State PatchedConfig 1 } # Default shell: PowerShell instead of cmd. $osh = 'HKLM:\SOFTWARE\OpenSSH' Ensure-Key $osh if (-not (Get-ItemProperty $osh -Name DefaultShell -ErrorAction SilentlyContinue)) { New-ItemProperty $osh -Name DefaultShell -PropertyType String -Force ` -Value "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe" | Out-Null Set-ItemProperty $State SetDefaultShell 1 Note 'default shell -> PowerShell' } # --- 5. Firewall ------------------------------------------------------------ Step 'Firewall' Remove-NetFirewallRule -Name 'win-ssh-kit' -ErrorAction SilentlyContinue New-NetFirewallRule -Name 'win-ssh-kit' -DisplayName 'win-ssh-kit (sshd 22)' -Direction Inbound ` -Protocol TCP -LocalPort 22 -Action Allow -Profile Any | Out-Null Note 'TCP 22 allowed on all profiles (incl. Public)' # --- 6. Restart & check ----------------------------------------------------- Step 'Restart sshd' Restart-Service sshd Start-Sleep 2 $listening = Get-NetTCPConnection -LocalPort 22 -State Listen -ErrorAction SilentlyContinue if ($listening) { Note 'sshd is listening on 22' } else { Warn 'sshd is NOT listening on 22' } # --- 7. Tell the human what to send back ----------------------------------- $ips = Get-NetIPAddress -AddressFamily IPv4 | Where-Object { $_.IPAddress -ne '127.0.0.1' -and $_.InterfaceAlias -notmatch 'vEthernet|Loopback' } | Sort-Object { $_.IPAddress -like '169.254.*' } $lines = @("host: $env:COMPUTERNAME ($(Get-Date -Format 'yyyy-MM-dd HH:mm'))") foreach ($ip in $ips) { $tag = $ip.InterfaceAlias if ($ip.IPAddress -like '169.254.*') { $tag += ', no DHCP / direct cable' } $lines += ('ssh {0}@{1} ({2})' -f $Login, $ip.IPAddress, $tag) } $bar = '=' * 64 Write-Host '' Write-Host $bar -ForegroundColor Green $lines | ForEach-Object { Write-Host " $_" -ForegroundColor Green } Write-Host $bar -ForegroundColor Green Write-Host ' Take a photo of this box and send it over.' -ForegroundColor Green if ($Web) { $undo = "irm $($WebBase -replace '^https://')/d | iex" } else { $undo = 'disable-ssh.bat' } Write-Host " Undo everything: $undo (or $Home_\disable-ssh.ps1)" -ForegroundColor Green Write-Host '' # Leave a note on the kit itself (the USB comes home with it). if ($Kit) { try { $logDir = Join-Path $Kit 'logs' New-Item $logDir -ItemType Directory -Force | Out-Null $lines | Set-Content (Join-Path $logDir "$env:COMPUTERNAME.txt") } catch { } } Stop-Transcript | Out-Null