From b08a426fb36ae6272f2ff514b8d2e058093db773 Mon Sep 17 00:00:00 2001 From: Alessandro Digilio Date: Mon, 9 Nov 2026 20:20:23 +0100 Subject: [PATCH 1/2] feat(ssh): add optional authorized key import --- .github/workflows/shell-quality.yml | 9 ++ FUTURE_IDEAS.md | 1 + README.md | 18 +++ docs/linux.md | 4 + docs/macos.md | 4 + docs/windows.md | 6 + install.ps1 | 7 + install.sh | 9 ++ scripts/import-ssh-keys.ps1 | 214 ++++++++++++++++++++++++++++ scripts/import-ssh-keys.sh | 188 ++++++++++++++++++++++++ tests/test-ssh-key-import.sh | 54 +++++++ tests/windows-smoke.ps1 | 11 ++ tests/windows-ssh-key-tests.ps1 | 78 ++++++++++ 13 files changed, 603 insertions(+) create mode 100644 scripts/import-ssh-keys.ps1 create mode 100755 scripts/import-ssh-keys.sh create mode 100755 tests/test-ssh-key-import.sh create mode 100644 tests/windows-ssh-key-tests.ps1 diff --git a/.github/workflows/shell-quality.yml b/.github/workflows/shell-quality.yml index e96f71a..3fbd25a 100644 --- a/.github/workflows/shell-quality.yml +++ b/.github/workflows/shell-quality.yml @@ -43,7 +43,9 @@ jobs: lib/tool-manifest.sh \ scripts/health-check.sh \ scripts/tool-health-check.sh \ + scripts/import-ssh-keys.sh \ tests/test-installer-functions.sh \ + tests/test-ssh-key-import.sh \ tests/test-shell-functions.sh \ tests/docker-ubuntu-smoke.sh \ macos/defaults.sh \ @@ -70,7 +72,9 @@ jobs: lib/tool-manifest.sh \ scripts/health-check.sh \ scripts/tool-health-check.sh \ + scripts/import-ssh-keys.sh \ tests/test-installer-functions.sh \ + tests/test-ssh-key-import.sh \ tests/test-shell-functions.sh \ tests/docker-ubuntu-smoke.sh \ macos/defaults.sh \ @@ -120,6 +124,9 @@ jobs: - name: Test interactive installer functions with stubs run: ./tests/test-installer-functions.sh + - name: Test SSH key import in a temporary home + run: ./tests/test-ssh-key-import.sh + ubuntu-container-smoke: runs-on: ubuntu-latest timeout-minutes: 10 @@ -239,6 +246,8 @@ jobs: windows-smoke: runs-on: windows-latest + env: + DOTFILES_DISPOSABLE_WINDOWS: '1' steps: - name: Checkout uses: actions/checkout@v7 diff --git a/FUTURE_IDEAS.md b/FUTURE_IDEAS.md index 78d6035..2545de6 100644 --- a/FUTURE_IDEAS.md +++ b/FUTURE_IDEAS.md @@ -18,6 +18,7 @@ A parking lot for possible enhancements. Active items are prioritized; finished - Delta configuration is now an explicit opt-in with conservative Git state restoration. - Legacy PATH de-duplication lines are migrated automatically during shell startup updates. - The installer now offers interactive `gh auth login` only when explicitly approved, with SSH/GPG setup hints. +- Optional incoming SSH key import is separate from client authentication and requires explicit confirmation. - `scripts/tool-health-check.sh` validates the curated tool manifest with `jq` and reports versions. - nvm upgrades now offer an explicit migration of global npm packages from the previous Node version. - Remote bootstrap helpers now support optional SHA-256 verification, with dynamic upstream channels documented as explicit exceptions. diff --git a/README.md b/README.md index f10d009..ba2da6f 100644 --- a/README.md +++ b/README.md @@ -201,6 +201,24 @@ For local-only package entries, edit the scaffold created at: The public template is [`windows/packages.private.example.psd1`](windows/packages.private.example.psd1). +### Incoming SSH access + +Interactive installers can optionally import public keys from a GitHub or GitLab.com username. The helper shows the destination and fingerprints and asks again before writing. It does not install or start an SSH server. `--all --yes`, `-Force`, minimal, sync, and dry-run modes do not import keys automatically. + +To preview or run the helper independently: + +```bash +bash scripts/import-ssh-keys.sh --provider github --username USERNAME --dry-run +bash scripts/import-ssh-keys.sh --provider github --username USERNAME +``` + +```powershell +.\scripts\import-ssh-keys.ps1 -Provider github -Username USERNAME -DryRun +.\scripts\import-ssh-keys.ps1 -Provider github -Username USERNAME +``` + +These are keys authorized for incoming connections, not keys used by `gh auth login`. Removing a key from the provider does not revoke it here; remove its line from the selected `authorized_keys` file manually. See the [Windows guide](docs/windows.md#incoming-ssh-keys) for the shared administrator file and ACL requirements. + ## Safety and recovery - Run the appropriate dry-run before the first installation and after material configuration changes. Review package manifests separately because the Unix dry-run skips the package/tool phase. diff --git a/docs/linux.md b/docs/linux.md index a8a02eb..19aace0 100644 --- a/docs/linux.md +++ b/docs/linux.md @@ -208,6 +208,10 @@ After optional tools are approved, an interactive run can offer `gh auth login` Authentication is not started in automatic, minimal, sync, dry-run, or non-interactive flows. +## Incoming SSH keys + +Run `bash scripts/import-ssh-keys.sh --provider github --username USERNAME --dry-run` to preview, then omit `--dry-run` to confirm an import. `gitlab` is also supported. The helper uses `~/.ssh/authorized_keys`, preserves existing lines, and makes a backup before replacement. It does not configure or start sshd. Removing a key from the provider does not revoke it here; remove its line manually. + ## Local configuration ### Private aliases diff --git a/docs/macos.md b/docs/macos.md index 7f88cfb..6375e7e 100644 --- a/docs/macos.md +++ b/docs/macos.md @@ -195,6 +195,10 @@ Apply it only after reviewing the tracked app list: This operation is intentionally separate and destructive with respect to the existing Dock arrangement. +## Incoming SSH keys + +Run `bash scripts/import-ssh-keys.sh --provider github --username USERNAME --dry-run` to preview, then omit `--dry-run` to confirm an import. `gitlab` is also supported. The helper uses `~/.ssh/authorized_keys`, preserves existing lines, and makes a backup before replacement. It does not configure or start sshd. Removing a key from the provider does not revoke it here; remove its line manually. + ## Local configuration ### Private aliases diff --git a/docs/windows.md b/docs/windows.md index 66f109d..3b44781 100644 --- a/docs/windows.md +++ b/docs/windows.md @@ -220,6 +220,12 @@ There should not be a standalone `Program Files\nodejs\node.exe` shadowing NVM. This repo does not require a root `.nvmrc`; individual Node projects can maintain their own. The shared `npmupg` function continues to operate on whichever Node version is active. +## Incoming SSH keys + +Run `.\scripts\import-ssh-keys.ps1 -Provider github -Username USERNAME -DryRun` to preview; omit `-DryRun` to confirm an import. `gitlab` is also supported. The helper requires `ssh-keygen`, checks fingerprints and ACLs, and refuses reparse points. It does not modify sshd configuration, start the service, or open the firewall. + +When the effective `AuthorizedKeysFile` cannot be determined, inspect `sshd_config` and explicitly select `-Destination User` or `-Destination Administrators`. The latter is a shared file for administrator accounts, requires an elevated shell for writes, and only permits SYSTEM and Administrators ACL entries. An unusual custom path is not written automatically. Existing keys are preserved and a backup is made on replacement. Removing a key from the provider does not revoke access here; remove its line manually. + ## Local configuration ### PowerShell overlays diff --git a/install.ps1 b/install.ps1 index cd3ce6d..c3d6a4a 100644 --- a/install.ps1 +++ b/install.ps1 @@ -907,6 +907,13 @@ if (-not $Minimal -and -not $Sync) { Write-Info "Minimal or sync mode: skipping package manager bootstrap." } +if (-not $Minimal -and -not $Sync -and -not $Force -and -not $DryRun -and -not $CleanBackups -and -not $RestoreGitDefaults -and -not [Console]::IsInputRedirected) { + $importSshKeys = Read-Host 'Import public SSH keys to allow incoming connections to this machine? [y/N]' + if ($importSshKeys -match '^[Yy]$') { + & (Join-Path $PSScriptRoot 'scripts\import-ssh-keys.ps1') + } +} + Write-WindowsAliasSummary Write-Section "Complete" diff --git a/install.sh b/install.sh index 4f0388d..35c5241 100755 --- a/install.sh +++ b/install.sh @@ -842,4 +842,13 @@ fi report_git_identity_hint print_install_summary +if ! $MINIMAL_MODE && ! $SYNC_MODE && ! $UNINSTALL_MODE && ! $CLEAN_BACKUPS && ! $DRY_RUN && ! $YES_MODE && ! $INSTALL_ALL && [ -t 0 ]; then + read -r -p 'Import public SSH keys to allow incoming connections to this machine? [y/N] ' import_ssh_keys + if [[ "$import_ssh_keys" =~ ^[Yy]$ ]]; then + if ! bash "$DOTFILES_HOME/scripts/import-ssh-keys.sh"; then + echo 'SSH key import failed; review the message above.' >&2 + fi + fi +fi + echo -e "\nšŸš€ Setup complete. You may need to restart your shell or source the new config." diff --git a/scripts/import-ssh-keys.ps1 b/scripts/import-ssh-keys.ps1 new file mode 100644 index 0000000..182ea47 --- /dev/null +++ b/scripts/import-ssh-keys.ps1 @@ -0,0 +1,214 @@ +[CmdletBinding()] +param( + [ValidateSet('github', 'gitlab')][string]$Provider, + [string]$Username, + [ValidateSet('User', 'Administrators')][string]$Destination, + [switch]$DryRun +) + +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' + +function Read-PublicKeys { + param([string]$Url) + $request = [Net.HttpWebRequest]::Create($Url) + $request.AllowAutoRedirect = $false + $request.Timeout = 30000 + $request.ReadWriteTimeout = 30000 + $response = $request.GetResponse() + try { + if ([int]$response.StatusCode -ne 200 -or $response.ContentLength -gt 1048576) { throw 'Unexpected or oversized response.' } + $stream = $response.GetResponseStream() + $buffer = New-Object byte[] 8192 + $memory = New-Object IO.MemoryStream + try { + while (($count = $stream.Read($buffer, 0, $buffer.Length)) -gt 0) { + if ($memory.Length + $count -gt 1048576) { throw 'Public-key response exceeds 1 MiB.' } + $memory.Write($buffer, 0, $count) + } + return [Text.Encoding]::UTF8.GetString($memory.ToArray()) + } finally { $memory.Dispose(); $stream.Dispose() } + } finally { $response.Dispose() } +} + +function Test-SafeAcl { + param([string]$Path, [string[]]$AllowedSids) + $acl = Get-Acl -LiteralPath $Path + Assert-SafeAcl -Acl $acl -Path $Path -AllowedSids $AllowedSids +} + +function Assert-SafeAcl { + param($Acl, [string]$Path, [string[]]$AllowedSids) + $owner = $acl.GetOwner([Security.Principal.SecurityIdentifier]).Value + if ($owner -notin $AllowedSids) { throw "Unexpected owner on $Path; inspect its ACL before importing." } + foreach ($rule in $acl.GetAccessRules($true, $true, [Security.Principal.SecurityIdentifier])) { + if ($rule.AccessControlType -eq 'Allow' -and $rule.IdentityReference.Value -notin $AllowedSids) { + throw "Unexpected allowed identity on $Path; inspect its ACL before importing." + } + } +} + +function Get-UserSshTarget { + Join-Path $HOME '.ssh\authorized_keys' +} + +function Resolve-AuthorizedKeysDestination { + param([string]$Line) + if ($Line -notmatch '^authorizedkeysfile\s+') { return $null } + $value = ($Line -replace '^authorizedkeysfile\s+', '').Trim().Replace('\', '/') + if ($value -match '^\.ssh/authorized_keys(?:\s|$)') { return 'User' } + if ($value -match '^(?:__PROGRAMDATA__|%programdata%)/ssh/administrators_authorized_keys(?:\s|$)') { return 'Administrators' } + return $null +} + +function Invoke-DotfilesSshKeyImport { +param( + [ValidateSet('github', 'gitlab')][string]$Provider, + [string]$Username, + [ValidateSet('User', 'Administrators')][string]$Destination, + [switch]$DryRun +) + +if (-not $Provider) { $Provider = Read-Host 'Provider (github/gitlab)' } +if ($Provider -notin @('github', 'gitlab')) { throw 'Provider must be github or gitlab.' } +if (-not $Username) { $Username = Read-Host 'Username' } +if ($Username -notmatch '^[A-Za-z0-9_][A-Za-z0-9_.-]*$' -or $Username.Contains('..')) { throw 'Invalid username.' } +if (-not (Get-Command ssh-keygen.exe -ErrorAction SilentlyContinue)) { throw 'ssh-keygen is required.' } + +$identity = [Security.Principal.WindowsIdentity]::GetCurrent() +$userSid = $identity.User.Value +$adminSid = 'S-1-5-32-544' +$systemSid = 'S-1-5-18' +$groups = @(whoami.exe /groups /fo csv /nh | ConvertFrom-Csv -Header Name, Type, Sid, Attributes) +if ($LASTEXITCODE -ne 0) { throw 'Cannot determine Windows group membership.' } +$isAdminMember = @($groups | Where-Object Sid -eq $adminSid).Count -gt 0 +$elevated = (New-Object Security.Principal.WindowsPrincipal($identity)).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) +$userTarget = Get-UserSshTarget +$adminTarget = Join-Path $env:ProgramData 'ssh\administrators_authorized_keys' + +# Ask when the effective sshd configuration cannot be established safely. +$resolved = $null +$sshd = Get-Command sshd.exe -ErrorAction SilentlyContinue +if (-not (Get-Service -Name sshd -ErrorAction SilentlyContinue)) { Write-Warning 'OpenSSH Server service was not found; it will not be installed or started.' } +if ($sshd) { + $config = @(& $sshd.Source -T -C "user=$env:USERNAME,host=localhost,addr=127.0.0.1" 2>$null) + if ($LASTEXITCODE -eq 0) { + $line = @($config | Where-Object { $_ -match '^authorizedkeysfile\s+' } | Select-Object -First 1) + if ($line.Count -eq 1) { + $resolved = Resolve-AuthorizedKeysDestination -Line $line[0] + } + } +} else { Write-Warning 'OpenSSH Server was not found; it will not be installed or started.' } +if ($Destination -and $resolved -and $Destination -ne $resolved) { throw 'Selected destination conflicts with the effective sshd configuration.' } +if ($resolved) { Write-Warning 'The sshd configuration was checked for localhost; Match rules can select a different file for remote clients.' } +if ($Destination -and -not $resolved) { Write-Warning 'The effective AuthorizedKeysFile could not be verified; confirm that this destination matches sshd_config.' } +if (-not $Destination) { $Destination = $resolved } +if (-not $Destination) { + Write-Warning 'Could not determine the effective AuthorizedKeysFile. Check sshd_config before selecting a destination.' + $Destination = Read-Host 'Destination (User/Administrators; anything else cancels)' + if ($Destination -notin @('User', 'Administrators')) { throw 'No destination selected.' } +} +if ($Destination -eq 'Administrators') { + if (-not $isAdminMember) { throw 'The shared administrators file is only intended for administrator accounts.' } + Write-Warning 'This file grants access to administrator accounts and is shared between administrators.' + if (-not $DryRun -and -not $elevated) { throw 'Run this helper from an elevated PowerShell session to modify the shared file.' } + $target = $adminTarget + $allowedSids = @($adminSid, $systemSid) +} else { + $target = $userTarget + $allowedSids = @($userSid, $adminSid, $systemSid) +} +$folder = Split-Path -Parent $target +foreach ($path in @($folder, $target)) { + if (Test-Path -LiteralPath $path) { + if ((Get-Item -LiteralPath $path -Force).Attributes -band [IO.FileAttributes]::ReparsePoint) { throw "Refusing a reparse point: $path" } + Test-SafeAcl -Path $path -AllowedSids $allowedSids + } +} + +$hostName = if ($Provider -eq 'github') { 'github.com' } else { 'gitlab.com' } +$payload = Read-PublicKeys -Url "https://$hostName/$Username.keys" +if ([string]::IsNullOrWhiteSpace($payload)) { throw 'No public keys returned.' } +$temp = Join-Path ([IO.Path]::GetTempPath()) ('dotfiles-ssh-key-' + [guid]::NewGuid().ToString('N')) +New-Item -ItemType Directory -Path $temp | Out-Null +try { + $keys = @() + foreach ($line in ($payload -split "`r?`n")) { + if ([string]::IsNullOrWhiteSpace($line)) { continue } + if ($line -match '\p{Cc}') { throw 'Public key contains control characters.' } + if ($line -notmatch '^(ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp(?:256|384|521)|sk-ssh-ed25519@openssh\.com|sk-ecdsa-sha2-nistp256@openssh\.com)\s+[A-Za-z0-9+/]+={0,3}(?:\s+[^\r\n]*)?$') { throw 'Invalid or unsupported public key.' } + $keyFile = Join-Path $temp 'key.pub' + [IO.File]::WriteAllText($keyFile, $line + "`n", (New-Object Text.UTF8Encoding($false))) + $fingerprint = @(& ssh-keygen.exe -lf $keyFile 2>&1) + if ($LASTEXITCODE -ne 0) { throw "Public-key validation failed: $($fingerprint -join ' ')" } + Write-Host ($fingerprint -join ' ') + $keys += $line + } + if ($keys.Count -eq 0) { throw 'No valid public keys returned.' } + $original = if (Test-Path -LiteralPath $target) { [IO.File]::ReadAllBytes($target) } else { $null } + $existingText = if ($null -ne $original) { [Text.Encoding]::UTF8.GetString($original) } else { '' } + # SSH key base64 is case-sensitive; PowerShell hashtables are not. + $seen = [Collections.Generic.HashSet[string]]::new([StringComparer]::Ordinal) + foreach ($line in ($existingText -split "`r?`n")) { + $fields = $line.TrimStart([char]0xFEFF) -split '\s+' + for ($i = 0; $i -lt $fields.Count - 1; $i++) { + if ($fields[$i] -match '^(ssh-(rsa|ed25519)|ecdsa-sha2-nistp(256|384|521)|sk-(ssh-ed25519|ecdsa-sha2-nistp256)@openssh\.com)$') { [void]$seen.Add("$($fields[$i]) $($fields[$i+1])"); break } + } + } + $newKeys = @() + foreach ($line in $keys) { + $parts = $line -split '\s+', 3 + $id = "$($parts[0]) $($parts[1])" + if ($seen.Add($id)) { $newKeys += $line } + } + Write-Host "Destination: $target" + Write-Host "New keys: $($newKeys.Count); already present or duplicate: $($keys.Count - $newKeys.Count)" + Write-Warning 'Removing a key from the provider does not revoke it here. Remove it from authorized_keys manually.' + if ($DryRun -or $newKeys.Count -eq 0) { return } + if ((Read-Host 'Add these keys to allow incoming SSH access? [y/N]') -notmatch '^[Yy]$') { Write-Host 'No changes made.'; return } + + if (-not (Test-Path -LiteralPath $folder)) { + if ($Destination -ne 'User') { throw 'Shared SSH folder does not exist.' } + New-Item -ItemType Directory -Path $folder | Out-Null + $folderAcl = New-Object Security.AccessControl.DirectorySecurity + $folderAcl.SetAccessRuleProtection($true, $false) + foreach ($sid in $allowedSids) { + $rule = New-Object Security.AccessControl.FileSystemAccessRule((New-Object Security.Principal.SecurityIdentifier($sid)), 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow') + $folderAcl.AddAccessRule($rule) + } + Set-Acl -LiteralPath $folder -AclObject $folderAcl + } + foreach ($path in @($folder, $target)) { + if ((Test-Path -LiteralPath $path) -and ((Get-Item -LiteralPath $path -Force).Attributes -band [IO.FileAttributes]::ReparsePoint)) { throw "SSH path changed to a reparse point: $path" } + } + Test-SafeAcl -Path $folder -AllowedSids $allowedSids + if (Test-Path -LiteralPath $target) { + if ($null -eq $original -or (Get-FileHash -LiteralPath $target -Algorithm SHA256).Hash -ne ([BitConverter]::ToString([Security.Cryptography.SHA256]::Create().ComputeHash($original)).Replace('-', ''))) { throw 'authorized_keys changed; retry.' } + Test-SafeAcl -Path $target -AllowedSids $allowedSids + } elseif ($null -ne $original) { throw 'authorized_keys was removed; retry.' } + $staged = Join-Path $folder ('.authorized_keys.dotfiles.' + [guid]::NewGuid().ToString('N')) + try { + $suffix = if ($existingText.Length -gt 0 -and -not $existingText.EndsWith("`n")) { "`r`n" } else { '' } + $bytes = [Text.Encoding]::UTF8.GetBytes($suffix + (($newKeys -join "`r`n") + "`r`n")) + $file = [IO.File]::Open($staged, [IO.FileMode]::CreateNew, [IO.FileAccess]::Write, [IO.FileShare]::None) + try { if ($null -ne $original) { $file.Write($original, 0, $original.Length) }; $file.Write($bytes, 0, $bytes.Length) } finally { $file.Dispose() } + $fileAcl = New-Object Security.AccessControl.FileSecurity + $fileAcl.SetAccessRuleProtection($true, $false) + foreach ($sid in $allowedSids) { $fileAcl.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule((New-Object Security.Principal.SecurityIdentifier($sid)), 'FullControl', 'Allow'))) } + Set-Acl -LiteralPath $staged -AclObject $fileAcl + if ($null -ne $original) { + $backup = Join-Path $folder ('authorized_keys.bak.' + [guid]::NewGuid().ToString('N')) + [IO.File]::Replace($staged, $target, $backup) + Write-Host "Previous authorized_keys saved to $backup" + } else { [IO.File]::Move($staged, $target) } + Write-Host 'Keys imported.' + } finally { if (Test-Path -LiteralPath $staged) { Remove-Item -LiteralPath $staged -Force } } +} finally { + Remove-Item -LiteralPath (Join-Path $temp 'key.pub') -Force -ErrorAction SilentlyContinue + Remove-Item -LiteralPath $temp -Force -ErrorAction SilentlyContinue +} +} + +if ($MyInvocation.InvocationName -ne '.') { + Invoke-DotfilesSshKeyImport @PSBoundParameters +} diff --git a/scripts/import-ssh-keys.sh b/scripts/import-ssh-keys.sh new file mode 100755 index 0000000..d40109a --- /dev/null +++ b/scripts/import-ssh-keys.sh @@ -0,0 +1,188 @@ +#!/usr/bin/env bash +# Import public keys into the current user's authorized_keys after confirmation. +set -eu + +provider='' +username='' +dry_run=false +while [ "$#" -gt 0 ]; do + case "$1" in + --provider) + [ "$#" -ge 2 ] || { + echo 'Missing provider.' >&2 + exit 2 + } + provider=$2 + shift 2 + ;; + --username) + [ "$#" -ge 2 ] || { + echo 'Missing username.' >&2 + exit 2 + } + username=$2 + shift 2 + ;; + --dry-run) + dry_run=true + shift + ;; + *) + echo "Unknown argument: $1" >&2 + exit 2 + ;; + esac +done + +if [ -z "$provider" ]; then + printf 'Provider (github/gitlab): ' + IFS= read -r provider +fi +if [ -z "$username" ]; then + printf 'Username: ' + IFS= read -r username +fi +case "$provider" in + github) base='https://github.com' ;; + gitlab) base='https://gitlab.com' ;; + *) + echo 'Provider must be github or gitlab.' >&2 + exit 2 + ;; +esac +case "$username" in + '' | *[!a-zA-Z0-9_.-]* | -* | .* | *..*) + echo 'Invalid username.' >&2 + exit 2 + ;; +esac +for cmd in curl ssh-keygen awk grep mktemp; do + command -v "$cmd" >/dev/null 2>&1 || { + echo "Missing required command: $cmd" >&2 + exit 1 + } +done + +umask 077 +temp_dir=$(mktemp -d "${TMPDIR:-/tmp}/dotfiles-ssh-keys.XXXXXXXX") +cleanup() { + rm -f "$temp_dir/download" "$temp_dir/keys" "$temp_dir/one" "$temp_dir/existing" "$temp_dir/new" + rmdir "$temp_dir" 2>/dev/null || true +} +trap cleanup EXIT HUP INT TERM +status=$(curl --fail --silent --show-error --proto '=https' --connect-timeout 10 --max-time 30 --max-filesize 1048576 "$base/$username.keys" -o "$temp_dir/download" -w '%{http_code}') +[ "$status" = 200 ] || { + echo "Unexpected HTTP status: $status" >&2 + exit 1 +} +[ -s "$temp_dir/download" ] || { + echo 'No public keys returned.' >&2 + exit 1 +} +: >"$temp_dir/keys" +while IFS= read -r line || [ -n "$line" ]; do + [ -n "$line" ] || continue + if printf '%s' "$line" | LC_ALL=C grep -q '[[:cntrl:]]'; then + echo 'Public key contains control characters.' >&2 + exit 1 + fi + # A downloaded line must begin with a supported public-key type, not options. + type=${line%%[[:space:]]*} + case "$type" in + ssh-ed25519 | ssh-rsa | ecdsa-sha2-nistp256 | ecdsa-sha2-nistp384 | ecdsa-sha2-nistp521 | sk-ssh-ed25519@openssh.com | sk-ecdsa-sha2-nistp256@openssh.com) ;; + *) + echo 'Invalid or unsupported public key.' >&2 + exit 1 + ;; + esac + printf '%s\n' "$line" >"$temp_dir/one" + ssh-keygen -lf "$temp_dir/one" >/dev/null 2>&1 || { + echo 'Invalid public key.' >&2 + exit 1 + } + printf '%s\n' "$line" >>"$temp_dir/keys" +done <"$temp_dir/download" +[ -s "$temp_dir/keys" ] || { + echo 'No valid public keys returned.' >&2 + exit 1 +} + +ssh_dir="$HOME/.ssh" +target="$ssh_dir/authorized_keys" +[ ! -L "$ssh_dir" ] && [ ! -L "$target" ] || { + echo 'Refusing symlinked SSH paths.' >&2 + exit 1 +} +if [ -e "$target" ] && [ ! -f "$target" ]; then + echo 'authorized_keys is not a regular file.' >&2 + exit 1 +fi +target_existed=false +if [ -f "$target" ]; then + target_existed=true + cp -p "$target" "$temp_dir/existing" +else + : >"$temp_dir/existing" +fi +# Compare type + base64, including existing entries with authorized_keys options. +awk ' + FILENAME == ARGV[1] { for (i=1; i"$temp_dir/new" +count=$(awk 'END { print NR+0 }' "$temp_dir/new") +total=$(awk 'END { print NR+0 }' "$temp_dir/keys") +printf 'Destination: %s\nNew keys: %s; already present or duplicate: %s\n' "$target" "$count" "$((total - count))" +ssh-keygen -lf "$temp_dir/keys" +echo 'Removing a key from the provider does not revoke access here; remove it from authorized_keys manually.' +if $dry_run || [ "$count" -eq 0 ]; then exit 0; fi +printf 'Add these keys to allow incoming SSH access? [y/N] ' +IFS= read -r answer || exit 1 +case "$answer" in y | Y) ;; *) + echo 'No changes made.' + exit 0 + ;; +esac + +mkdir -p "$ssh_dir" +chmod 700 "$ssh_dir" +[ ! -L "$ssh_dir" ] && [ ! -L "$target" ] || { + echo 'SSH path changed; no keys written.' >&2 + exit 1 +} +if $target_existed && [ -f "$target" ]; then + cmp -s "$target" "$temp_dir/existing" || { + echo 'authorized_keys changed; retry.' >&2 + exit 1 + } +elif $target_existed || [ -e "$target" ]; then + echo 'authorized_keys changed; retry.' >&2 + exit 1 +fi +staged=$(mktemp "$ssh_dir/.authorized_keys.dotfiles.XXXXXXXX") +trap 'rm -f "$staged"; cleanup' EXIT HUP INT TERM +if [ -s "$temp_dir/existing" ]; then + cat "$temp_dir/existing" >"$staged" + # Separate the new entry from a last line without a newline. + [ "$(tail -c 1 "$staged" | wc -l | tr -d ' ')" -ne 0 ] || printf '\n' >>"$staged" +fi +cat "$temp_dir/new" >>"$staged" +chmod 600 "$staged" +if $target_existed; then + backup=$(mktemp "$ssh_dir/authorized_keys.bak.XXXXXXXX") + cp -p "$target" "$backup" + chmod 600 "$backup" + echo "Previous authorized_keys saved to $backup" + cmp -s "$target" "$temp_dir/existing" || { + echo 'authorized_keys changed; retry.' >&2 + exit 1 + } + mv "$staged" "$target" +else + # Creating a hard link fails atomically if another process created the target. + ln "$staged" "$target" || { + echo 'authorized_keys changed; retry.' >&2 + exit 1 + } + rm -f "$staged" +fi +echo 'Keys imported.' diff --git a/tests/test-ssh-key-import.sh b/tests/test-ssh-key-import.sh new file mode 100755 index 0000000..3b01923 --- /dev/null +++ b/tests/test-ssh-key-import.sh @@ -0,0 +1,54 @@ +#!/usr/bin/env bash +set -euo pipefail + +repo_root=$(cd "$(dirname "$0")/.." && pwd) +test_root=$(mktemp -d /tmp/dotfiles-ssh-import.XXXXXXXX) +case "$test_root" in /tmp/dotfiles-ssh-import.*) ;; *) exit 1 ;; esac +trap 'rm -rf -- "$test_root"' EXIT +mkdir -p "$test_root/bin" "$test_root/home" +ssh-keygen -q -t ed25519 -N '' -f "$test_root/key" +cat >"$test_root/bin/curl" <<'EOF' +#!/usr/bin/env bash +while [ "$#" -gt 0 ]; do + if [ "$1" = -o ]; then cp "$SSH_TEST_RESPONSE" "$2"; printf '%s' "${SSH_TEST_STATUS:-200}"; exit "${SSH_TEST_CURL_EXIT:-0}"; fi + shift +done +exit 1 +EOF +chmod +x "$test_root/bin/curl" +export PATH="$test_root/bin:$PATH" HOME="$test_root/home" SSH_TEST_RESPONSE="$test_root/key.pub" + +bash "$repo_root/scripts/import-ssh-keys.sh" --provider github --username example --dry-run >/dev/null +test ! -e "$HOME/.ssh" +printf 'y\n' | bash "$repo_root/scripts/import-ssh-keys.sh" --provider github --username example >/dev/null +test "$(wc -l <"$HOME/.ssh/authorized_keys" | tr -d ' ')" = 1 +test "$(stat -c %a "$HOME/.ssh")" = 700 +test "$(stat -c %a "$HOME/.ssh/authorized_keys")" = 600 +cp "$HOME/.ssh/authorized_keys" "$test_root/before" +printf 'y\n' | bash "$repo_root/scripts/import-ssh-keys.sh" --provider gitlab --username example >/dev/null +cmp -s "$test_root/before" "$HOME/.ssh/authorized_keys" +printf 'not a key\n' >"$test_root/invalid" +export SSH_TEST_RESPONSE="$test_root/invalid" +if printf 'y\n' | bash "$repo_root/scripts/import-ssh-keys.sh" --provider github --username example >/dev/null 2>&1; then exit 1; fi +cmp -s "$test_root/before" "$HOME/.ssh/authorized_keys" +printf 'ssh-ed25519 AAAA\033[31m\n' >"$test_root/control" +export SSH_TEST_RESPONSE="$test_root/control" +if printf 'y\n' | bash "$repo_root/scripts/import-ssh-keys.sh" --provider github --username example >/dev/null 2>&1; then exit 1; fi +cmp -s "$test_root/before" "$HOME/.ssh/authorized_keys" +export SSH_TEST_RESPONSE="$test_root/key.pub" SSH_TEST_STATUS=302 +if printf 'y\n' | bash "$repo_root/scripts/import-ssh-keys.sh" --provider github --username example >/dev/null 2>&1; then exit 1; fi +unset SSH_TEST_STATUS +export SSH_TEST_CURL_EXIT=22 +if printf 'y\n' | bash "$repo_root/scripts/import-ssh-keys.sh" --provider github --username example >/dev/null 2>&1; then exit 1; fi +unset SSH_TEST_CURL_EXIT +cmp -s "$test_root/before" "$HOME/.ssh/authorized_keys" +ssh-keygen -q -t ed25519 -N '' -f "$test_root/second" +printf '# manual comment without newline' >>"$HOME/.ssh/authorized_keys" +cp "$HOME/.ssh/authorized_keys" "$test_root/before-second" +export SSH_TEST_RESPONSE="$test_root/second.pub" +printf 'y\n' | bash "$repo_root/scripts/import-ssh-keys.sh" --provider github --username example >/dev/null +cmp -s "$test_root/before-second" "$(find "$HOME/.ssh" -maxdepth 1 -name 'authorized_keys.bak.*' -print -quit)" +grep -Fq '# manual comment without newline' "$HOME/.ssh/authorized_keys" +test "$(ssh-keygen -lf "$HOME/.ssh/authorized_keys" | wc -l | tr -d ' ')" = 2 +if bash "$repo_root/scripts/import-ssh-keys.sh" --provider github --username '../bad' --dry-run >/dev/null 2>&1; then exit 1; fi +echo 'SSH key import tests passed.' diff --git a/tests/windows-smoke.ps1 b/tests/windows-smoke.ps1 index 0ec3b94..a75eb8a 100644 --- a/tests/windows-smoke.ps1 +++ b/tests/windows-smoke.ps1 @@ -14,6 +14,8 @@ $sources = @( 'tests/windows-powershell-msi-tests.ps1' 'windows/Dotfiles.WindowsNode.psm1' 'tests/windows-node-tests.ps1' + 'scripts/import-ssh-keys.ps1' + 'tests/windows-ssh-key-tests.ps1' 'windows/start-menu-shortcuts.ps1' ) @@ -74,6 +76,15 @@ if ($env:OS -ne 'Windows_NT') { return } +& (Join-Path $repoRoot 'tests/windows-ssh-key-tests.ps1') + +# PowerShell's $HOME and Windows profile paths do not follow $env:HOME. +# The lifecycle below invokes the installer and must only run on a disposable VM. +if ($env:DOTFILES_DISPOSABLE_WINDOWS -ne '1') { + Write-Host 'Windows installer lifecycle skipped: use a disposable Windows environment and set DOTFILES_DISPOSABLE_WINDOWS=1.' + return +} + $originalHome = $env:HOME $originalGitConfig = $env:GIT_CONFIG_GLOBAL $testHome = Join-Path ([System.IO.Path]::GetTempPath()) "dotfiles-windows-lifecycle-$PID" diff --git a/tests/windows-ssh-key-tests.ps1 b/tests/windows-ssh-key-tests.ps1 new file mode 100644 index 0000000..4cfbaa4 --- /dev/null +++ b/tests/windows-ssh-key-tests.ps1 @@ -0,0 +1,78 @@ +[CmdletBinding()] +param() +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' + +$repoRoot = Split-Path -Parent $PSScriptRoot +. (Join-Path $repoRoot 'scripts/import-ssh-keys.ps1') +if ((Resolve-AuthorizedKeysDestination 'authorizedkeysfile .ssh/authorized_keys .ssh/authorized_keys2') -ne 'User') { throw 'User destination was not recognized.' } +if ((Resolve-AuthorizedKeysDestination 'authorizedkeysfile __PROGRAMDATA__\ssh\administrators_authorized_keys') -ne 'Administrators') { throw 'Shared destination was not recognized.' } +if ($null -ne (Resolve-AuthorizedKeysDestination 'authorizedkeysfile C:/custom/keys')) { throw 'Custom destination must not be guessed.' } +$testRoot = Join-Path ([IO.Path]::GetTempPath()) ('dotfiles-ssh-import-' + [guid]::NewGuid().ToString('N')) +New-Item -ItemType Directory -Path $testRoot | Out-Null +$testRoot = (Resolve-Path -LiteralPath $testRoot).Path +$tempRoot = [IO.Path]::GetFullPath([IO.Path]::GetTempPath()).TrimEnd('\') + '\' +if (-not $testRoot.StartsWith($tempRoot, [StringComparison]::OrdinalIgnoreCase)) { throw 'Unexpected test directory.' } + +function Get-UserSshTarget { Join-Path $testRoot '.ssh\authorized_keys' } +function Test-SafeAcl { param($Path, $AllowedSids) } +function Read-PublicKeys { param($Url) if ($script:failDownload) { throw 'Simulated network failure.' }; return $script:payload } +function Read-Host { param($Prompt) return $script:confirmation } +function Get-Command { + param($Name, $ErrorAction) + if ($Name -eq 'sshd.exe') { return $null } + Microsoft.PowerShell.Core\Get-Command $Name -ErrorAction SilentlyContinue +} + +try { + $identitySid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value + $acl = New-Object Security.AccessControl.FileSecurity + $acl.SetOwner((New-Object Security.Principal.SecurityIdentifier($identitySid))) + $acl.SetAccessRuleProtection($true, $false) + $acl.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule((New-Object Security.Principal.SecurityIdentifier($identitySid)), 'FullControl', 'Allow'))) + Assert-SafeAcl -Acl $acl -Path 'fixture' -AllowedSids @($identitySid, 'S-1-5-32-544', 'S-1-5-18') + $acl.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule((New-Object Security.Principal.SecurityIdentifier('S-1-1-0')), 'Read', 'Allow'))) + $aclRejected = $false + try { Assert-SafeAcl -Acl $acl -Path 'fixture' -AllowedSids @($identitySid, 'S-1-5-32-544', 'S-1-5-18') } catch { $aclRejected = $true } + if (-not $aclRejected) { throw 'An ACL allowing Everyone must be rejected.' } + $script:payload = 'ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIJ0cTStxdRoWnKOMcJlXMLKfTr2Km6eKqLhc9eYLCQ1y test-fixture' + $script:failDownload = $false + $script:confirmation = 'n' + $target = Get-UserSshTarget + Invoke-DotfilesSshKeyImport -Provider github -Username test-user -Destination User -DryRun + if (Test-Path -LiteralPath $target) { throw 'Dry run created a target.' } + Invoke-DotfilesSshKeyImport -Provider github -Username test-user -Destination User + if (Test-Path -LiteralPath $target) { throw 'Declined confirmation created a target.' } + $script:confirmation = 'y' + Invoke-DotfilesSshKeyImport -Provider github -Username test-user -Destination User + $original = [IO.File]::ReadAllBytes($target) + $script:payload = $script:payload -replace 'test-fixture$', 'different-comment' + Invoke-DotfilesSshKeyImport -Provider gitlab -Username test-user -Destination User + if ([Convert]::ToBase64String($original) -ne [Convert]::ToBase64String([IO.File]::ReadAllBytes($target))) { throw 'Duplicate key changed the file.' } + $script:payload = 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCoQ9S7V+CufAgwoehnf2TqsJ9LTsu8pUA3FgpS2mdVwcMcTs++8P5sQcXHLtDmNLpWN4k7NQgxaY1oXy5e25x/4VhXaJXWEt3luSw+Phv/PB2+aGLvqCUirsLTAD2r7ieMhd/pcVf/HlhNUQgnO1mupdbDyqZoGD/uCcJiYav8i/V7nJWJouHA8yq31XS2yqXp9m3VC7UZZHzUsVJA9Us5YqF0hKYeaGruIHR2bwoDF9ZFMss5t6/pzxMljU/ccYwvvRDdI7WX4o4+zLuZ6RWvsU6LGbbb0pQdB72tlV41fSefwFsk4JRdKbyV3Xjf25pV4IXOTcqhy+4JTB/jXxrF second-fixture' + Invoke-DotfilesSshKeyImport -Provider github -Username test-user -Destination User + $updated = [IO.File]::ReadAllBytes($target) + if ($updated.Length -le $original.Length -or [Convert]::ToBase64String($updated[0..($original.Length - 1)]) -ne [Convert]::ToBase64String($original)) { throw 'Existing contents were not preserved.' } + $backups = @(Get-ChildItem -LiteralPath (Split-Path -Parent $target) -Filter 'authorized_keys.bak.*') + if ($backups.Count -ne 1 -or [Convert]::ToBase64String([IO.File]::ReadAllBytes($backups[0].FullName)) -ne [Convert]::ToBase64String($original)) { throw 'Expected a backup of the previous file.' } + $original = $updated + foreach ($failure in @('invalid', 'network')) { + $script:payload = 'not a key' + $script:failDownload = $failure -eq 'network' + $failed = $false + try { Invoke-DotfilesSshKeyImport -Provider github -Username test-user -Destination User } catch { $failed = $true } + if (-not $failed) { throw "Expected $failure failure." } + if ([Convert]::ToBase64String($original) -ne [Convert]::ToBase64String([IO.File]::ReadAllBytes($target))) { throw "File changed after $failure failure." } + } + $script:failDownload = $false + $script:payload = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIJ0cTStxdRoWnKOMcJlXMLKfTr2Km6eKqLhc9eYLCQ1y $([char]27)[31m" + $failed = $false + try { Invoke-DotfilesSshKeyImport -Provider github -Username test-user -Destination User } catch { $failed = $true } + if (-not $failed) { throw 'Keys containing terminal control characters must be rejected.' } + if ([Convert]::ToBase64String($original) -ne [Convert]::ToBase64String([IO.File]::ReadAllBytes($target))) { throw 'File changed after a control-character failure.' } + Write-Host 'Windows SSH key import tests passed.' +} finally { + if ((Test-Path -LiteralPath $testRoot) -and $testRoot.StartsWith($tempRoot, [StringComparison]::OrdinalIgnoreCase)) { + Remove-Item -LiteralPath $testRoot -Recurse -Force -ErrorAction SilentlyContinue + } +} From 2860f79a6c6c66821fdf47ba2bf4086f86c22495 Mon Sep 17 00:00:00 2001 From: Alessandro Digilio Date: Mon, 9 Nov 2026 20:22:10 +0100 Subject: [PATCH 2/2] fix(ssh): satisfy shellcheck on CI --- scripts/import-ssh-keys.sh | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/scripts/import-ssh-keys.sh b/scripts/import-ssh-keys.sh index d40109a..bd8ba68 100755 --- a/scripts/import-ssh-keys.sh +++ b/scripts/import-ssh-keys.sh @@ -109,10 +109,10 @@ done <"$temp_dir/download" ssh_dir="$HOME/.ssh" target="$ssh_dir/authorized_keys" -[ ! -L "$ssh_dir" ] && [ ! -L "$target" ] || { +if [ -L "$ssh_dir" ] || [ -L "$target" ]; then echo 'Refusing symlinked SSH paths.' >&2 exit 1 -} +fi if [ -e "$target" ] && [ ! -f "$target" ]; then echo 'authorized_keys is not a regular file.' >&2 exit 1 @@ -145,10 +145,10 @@ esac mkdir -p "$ssh_dir" chmod 700 "$ssh_dir" -[ ! -L "$ssh_dir" ] && [ ! -L "$target" ] || { +if [ -L "$ssh_dir" ] || [ -L "$target" ]; then echo 'SSH path changed; no keys written.' >&2 exit 1 -} +fi if $target_existed && [ -f "$target" ]; then cmp -s "$target" "$temp_dir/existing" || { echo 'authorized_keys changed; retry.' >&2