# fido — autenticação SSH com duas YubiKeys, no GitHub e em servidores. # # Credenciais esperadas no token: # YUC (USB-C): comentário "github-yuc" ou "server-yuc" # YUA (USB-A): comentário "github-yua" ou "server-yua" # # Sem argumentos, pergunta no terminal. # Com -Batch, executa o comando informado sem menu. Use -Batch help. param( [switch]$Batch ) $ErrorActionPreference = 'Stop' $App = 'fido' if ([string]::IsNullOrEmpty($env:USERPROFILE)) { throw 'Erro: USERPROFILE não está definido.' } $SshDir = Join-Path $env:USERPROFILE '.ssh' $ConfigFile = Join-Path $SshDir 'fido.conf' $LegacyConfigFile = Join-Path $SshDir 'yubikey-github.conf' $MainConfig = Join-Path $SshDir 'config' $IncludeLine = 'Include ~/.ssh/fido.conf' $LegacyIncludeLine = 'Include ~/.ssh/yubikey-github.conf' $ServerHosts = Join-Path $SshDir 'fido-server.hosts' $ServerFavs = Join-Path $SshDir 'fido-server.favs' $LegacyServerHosts = Join-Path $SshDir 'yubikey-server.hosts' $AccountsFile = Join-Path $SshDir 'fido-github.accounts' $ServerAccounts = Join-Path $SshDir 'fido-server.accounts' $script:Account = '' $script:ServerName = '' $script:YkSerial = '' $script:ConnectedLabels = @() $script:ConnectedModels = @() $script:ConnectedSerials = @() $script:ConnectedScanned = $false $Utf8 = New-Object System.Text.UTF8Encoding $false function Stop-Helper([string]$Message) { throw "Erro: $Message" } function Test-UseColor { return [string]::IsNullOrEmpty($env:NO_COLOR) } function Write-Info([string]$Message) { if (Test-UseColor) { Write-Host "➜ $Message" -ForegroundColor Cyan } else { Write-Host "➜ $Message" } } function Write-Ok([string]$Message) { if (Test-UseColor) { Write-Host "✓ $Message" -ForegroundColor Green } else { Write-Host "✓ $Message" } } function Write-Warn([string]$Message) { if (Test-UseColor) { Write-Host "Aviso: $Message" -ForegroundColor Yellow } else { Write-Host "Aviso: $Message" } } function Write-MenuRow([string]$Number, [string]$Title, [string]$Detail) { if (Test-UseColor) { Write-Host ' ' -NoNewline Write-Host $Number -ForegroundColor Cyan -NoNewline Write-Host ' ' -NoNewline Write-Host $Title -NoNewline Write-Host " $Detail" -ForegroundColor DarkGray } else { Write-Host " $Number $Title $Detail" } } function Get-LabelName([string]$Label) { switch ($Label) { 'yuc' { 'YUC' } 'yua' { 'YUA' } default { $Label } } } function Show-Usage { Write-Host @" fido — helper para autenticação SSH com duas YubiKeys Sem argumentos, pergunta no terminal o que fazer. Para executar direto, use a flag -Batch: -Batch create [conta] 1|2|yuc|yua [série] Cria a credencial da conta no token -Batch add [conta] 1|2|yuc|yua Recupera a chave da conta no token conectado -Batch use [conta] 1|2|yuc|yua Ativa essa conta em git@github.com -Batch test Autentica em git@github.com com a chave ativa -Batch pub [conta] Mostra as chaves públicas da conta -Batch pub [conta] 1|2|yuc|yua Mostra e copia a chave escolhida -Batch undo Remove só o que este helper gravou neste computador -Batch status Mostra a configuração ativa -Batch list Lista chaves recuperadas neste computador -Batch server-create [nome] 1|2|yuc|yua [série] Cria a credencial residente para servidor -Batch server-add [nome] 1|2|yuc|yua Recupera a credencial de servidor do token -Batch server-install [nome] 1|2 user@ip Instala a chave pública no servidor -Batch server-connect [nome] 1|2 user@ip Abre ssh com a chave do token -Batch server-pub [nome] Mostra o comando para o authorized_keys -Batch server-pub [nome] 1|2|yuc|yua Mostra e copia o comando da chave escolhida -Batch server-undo Remove só as chaves de servidor deste computador -Batch help Mostra esta ajuda Pela URL, no Windows: & ([scriptblock]::Create((irm https://fido.polidev.cloud/script.ps1))) & ([scriptblock]::Create((irm https://fido.polidev.cloud/script.ps1))) -Batch use yuc O nome escolhe a conta do GitHub. Cada YubiKey dessa conta precisa da própria chave pública cadastrada nela. Exemplo: -Batch create trabalho 1 Sem nome, -Batch create 1 grava a credencial github-yuc. Com mais de uma YubiKey no Criar, a série vai no fim. Exemplo: -Batch create trabalho 1 12345678 A recuperação pede PIN e toque na YubiKey. O nome do servidor funciona como a conta do GitHub. Exemplo: -Batch server-create casa 1 Sem nome, -Batch server-create 1 grava a credencial server-yuc. O handle local fica em ~/.ssh. A credencial continua na YubiKey. "@ } function Test-InteractiveConsole { try { return -not [Console]::IsInputRedirected } catch { return $false } } function Read-ConsoleLine([string]$Prompt) { if (-not (Test-InteractiveConsole)) { Stop-Helper 'Terminal interativo não encontrado. Use -Batch para executar sem perguntas.' } try { return Read-Host $Prompt } catch { Stop-Helper 'Terminal interativo não encontrado. Use -Batch para executar sem perguntas.' } } function Assert-Tools { foreach ($name in @('ssh', 'ssh-keygen')) { if (-not (Get-Command $name -ErrorAction SilentlyContinue)) { Stop-Helper "Comando necessário não encontrado: $name. Ative o recurso opcional Cliente OpenSSH do Windows." } } } function Assert-OpenSshSk { $banner = & ssh -V 2>&1 | Out-String if ($banner -match 'OpenSSH_(\d+)\.(\d+)') { $major = [int]$Matches[1] $minor = [int]$Matches[2] if ($major -gt 8 -or ($major -eq 8 -and $minor -ge 2)) { return } Stop-Helper "OpenSSH $major.$minor não recupera credenciais residentes. É necessário OpenSSH 8.2 ou mais recente." } Write-Warn 'Não foi possível detectar a versão do OpenSSH. É necessário 8.2 ou mais recente para chaves FIDO.' } function Resolve-Label([string]$Value) { $label = '' if ($null -ne $Value) { $label = $Value.Trim().ToLowerInvariant() } switch ($label) { '1' { return 'yuc' } 'yuc' { return 'yuc' } '2' { return 'yua' } 'yua' { return 'yua' } default { Stop-Helper 'Informe 1 (YUC, USB-C) ou 2 (YUA, USB-A). Exemplo: -Batch add 1' } } } function Test-AccountName([string]$Name) { return $Name -match '^[a-z0-9][a-z0-9-]{0,31}$' } function Set-Account([string]$Name) { if ([string]::IsNullOrEmpty($Name)) { $script:Account = '' return } $normalized = $Name.Trim().ToLowerInvariant() if (-not (Test-AccountName $normalized)) { Stop-Helper "Nome de conta inválido: $normalized. Use letras minúsculas, números e hífen. Exemplo: trabalho" } $script:Account = $normalized } function Save-Account { if ([string]::IsNullOrEmpty($script:Account)) { return } Ensure-SshDir $lines = New-Object System.Collections.Generic.List[string] if (Test-Path -LiteralPath $AccountsFile) { foreach ($line in [System.IO.File]::ReadAllLines($AccountsFile)) { if ($line -eq $script:Account) { Protect-UserFile $AccountsFile return } [void]$lines.Add($line) } } [void]$lines.Add($script:Account) [System.IO.File]::WriteAllText($AccountsFile, ([string]::Join("`n", $lines.ToArray()) + "`n"), $Utf8) Protect-UserFile $AccountsFile } function Test-KeyLabel([string]$Value) { if ([string]::IsNullOrEmpty($Value)) { return $false } return $Value.Trim().ToLowerInvariant() -in @('1', '2', 'yuc', 'yua') } function Get-Comment([string]$Label) { if ([string]::IsNullOrEmpty($script:Account)) { return ('github-' + $Label) } return ('github-' + $script:Account + '-' + $Label) } function Get-KeyPath([string]$Label, [string]$Account) { $name = $script:Account if ($PSBoundParameters.ContainsKey('Account')) { $name = $Account } if ([string]::IsNullOrEmpty($name)) { return (Join-Path $SshDir ($Label + '_github_id_ed25519_sk')) } return (Join-Path $SshDir ($name + '_' + $Label + '_github_id_ed25519_sk')) } function Get-ActiveAccountText([string]$Identity) { $base = [System.IO.Path]::GetFileName(($Identity -replace '\\', '/')) if ($base -eq 'yuc_github_id_ed25519_sk') { return 'Conta ativa: sem nome (YUC)' } if ($base -eq 'yua_github_id_ed25519_sk') { return 'Conta ativa: sem nome (YUA)' } if ($base -match '^([a-z0-9][a-z0-9-]{0,31})_(yuc|yua)_github_id_ed25519_sk$') { $label = 'YUA' if ($Matches[2] -eq 'yuc') { $label = 'YUC' } return ('Conta ativa: ' + $Matches[1] + ' (' + $label + ')') } return "Chave ativa: $Identity" } function Convert-ToSshPath([string]$Path) { if ([string]::IsNullOrEmpty($Path)) { return '' } return ($Path -replace '\\', '/') } function Read-Identity { if (-not (Test-Path -LiteralPath $ConfigFile)) { return '' } foreach ($line in [System.IO.File]::ReadAllLines($ConfigFile)) { if ($line -match '^\s*IdentityFile\s+(.+)$') { return $Matches[1].Trim().Trim('"') } } return '' } function Protect-UserFile([string]$Path) { $account = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name $grant = '{0}:(F)' -f $account & icacls.exe $Path '/inheritance:r' '/grant:r' $grant | Out-Null if ($LASTEXITCODE -ne 0) { Write-Warn "Não foi possível restringir as permissões de $Path" } } function Protect-UserDir([string]$Path) { $account = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name $grant = '{0}:(OI)(CI)F' -f $account & icacls.exe $Path '/inheritance:r' '/grant:r' $grant | Out-Null if ($LASTEXITCODE -ne 0) { Write-Warn "Não foi possível restringir as permissões de $Path" } } function Ensure-SshDir { if (-not (Test-Path -LiteralPath $SshDir)) { New-Item -ItemType Directory -Path $SshDir | Out-Null } Protect-UserDir $SshDir } function Ensure-Include { if (-not (Test-Path -LiteralPath $MainConfig)) { [System.IO.File]::WriteAllText($MainConfig, '', $Utf8) } $text = [System.IO.File]::ReadAllText($MainConfig) $found = $false foreach ($line in ($text -split "`r`n|`n")) { if ($line -eq $IncludeLine) { $found = $true break } } if (-not $found) { [System.IO.File]::WriteAllText($MainConfig, ($IncludeLine + "`n" + $text), $Utf8) } Protect-UserFile $MainConfig } function Write-GithubConfig([string]$Identity) { $sshPath = Convert-ToSshPath $Identity $text = @" # Gerenciado por $App. Edite com cuidado. Host github.com HostName github.com User git IdentityFile "$sshPath" IdentitiesOnly yes IdentityAgent none "@ [System.IO.File]::WriteAllText($ConfigFile, $text, $Utf8) Protect-UserFile $ConfigFile Ensure-Include } function Copy-PublicKey([string]$Path) { if (-not (Get-Command Set-Clipboard -ErrorAction SilentlyContinue)) { return } try { Set-Clipboard -Value ([System.IO.File]::ReadAllText($Path)) Write-Ok 'Chave pública copiada para a área de transferência.' } catch { return } } function Get-AuthorizedKeysCommand([string]$PublicPath) { $raw = [System.IO.File]::ReadAllText($PublicPath) $key = (($raw -split '\r?\n') | Where-Object { -not [string]::IsNullOrWhiteSpace($_) } | Select-Object -First 1) if ([string]::IsNullOrWhiteSpace($key)) { Stop-Helper 'Não foi possível ler a chave pública.' } $key = $key.Trim() $quoted = $key.Replace("'", "'\''") $suffix = @' && { case "$key" in sk-*|ssh-*|ecdsa-*) ;; COLE_A_CHAVE_PUBLICA) echo "Substitua COLE_A_CHAVE_PUBLICA pela linha da chave pública."; exit 1 ;; *) echo "A chave precisa ser a linha pública, começando com sk-, ssh- ou ecdsa-."; exit 1 ;; esac; } && mkdir -p -- "$HOME/.ssh" && chmod 700 "$HOME/.ssh" && touch "$HOME/.ssh/authorized_keys" && chmod 600 "$HOME/.ssh/authorized_keys" && { grep -qxF "$key" "$HOME/.ssh/authorized_keys" && echo "A chave já estava em ~/.ssh/authorized_keys." || { printf '%s\n' "$key" >> "$HOME/.ssh/authorized_keys" && echo "Chave adicionada em ~/.ssh/authorized_keys."; }; } '@ return "key='$quoted' " + $suffix.Trim() } function Copy-CommandText([string]$Text) { if (-not (Get-Command Set-Clipboard -ErrorAction SilentlyContinue)) { return } try { Set-Clipboard -Value $Text Write-Ok 'Comando copiado para a área de transferência.' } catch { return } } function Write-AuthorizedKeysCommand([string]$PublicPath) { $cmd = Get-AuthorizedKeysCommand $PublicPath Write-Info 'No servidor, cole este comando. Ele grava a chave em ~/.ssh/authorized_keys:' Write-Host '' Write-Host $cmd Write-Host '' Copy-CommandText $cmd } function Get-CredentialDisplayName([string]$Comment) { switch -Regex ($Comment) { '^(github-yuc|github-yua|server-yuc|server-yua)$' { return $Comment } '^github-(.+)-(yuc|yua)$' { return $Matches[1] } '^server-(.+)-(yuc|yua)$' { return $Matches[1] } default { return $Comment } } } function Get-CredentialApplication([string]$Comment) { $display = Get-CredentialDisplayName $Comment if ($Comment.StartsWith('server-')) { return "ssh:server:$display" } return "ssh:git:$display" } function Get-ResidentNote([string]$Comment, [string]$BaseName) { if ($Comment.StartsWith('ssh:') -and $Comment -ne 'ssh:') { $rest = $Comment.Substring(4) foreach ($prefix in @('id_ed25519_sk_rk_', 'id_ecdsa_sk_rk_')) { $marker = $prefix + $rest + '_' if ($BaseName.StartsWith($marker) -and $BaseName.Length -gt $marker.Length) { return $BaseName.Substring($marker.Length) } } return $Comment } if ($Comment -eq 'ssh:') { foreach ($prefix in @('id_ed25519_sk_rk_', 'id_ecdsa_sk_rk_')) { if ($BaseName.StartsWith($prefix) -and $BaseName.Length -gt $prefix.Length) { return $BaseName.Substring($prefix.Length) } } } return $Comment } function Test-ResidentMatch([string]$Expected, [string]$Comment, [string]$BaseName) { if ($Comment -eq $Expected) { return $true } if ($Comment -eq 'ssh:') { return ($BaseName -eq "id_ed25519_sk_rk_$Expected") -or ($BaseName -eq "id_ecdsa_sk_rk_$Expected") } if ($Comment -ne (Get-CredentialApplication $Expected)) { return $false } return ($BaseName -like "id_ed25519_sk_rk_*_$Expected") -or ($BaseName -like "id_ecdsa_sk_rk_*_$Expected") } function Set-RecoveredComment([string]$PublicPath, [string]$Expected) { if (-not (Test-Path -LiteralPath $PublicPath)) { return } $line = ([System.IO.File]::ReadAllText($PublicPath)).Trim() $parts = @($line -split '\s+' | Where-Object { $_ -ne '' }) if ($parts.Count -lt 3) { return } $note = [string]$parts[$parts.Count - 1] if (-not $note.StartsWith('ssh:')) { return } if ($note -eq $Expected) { return } if ($parts[0] -notlike 'sk-*') { return } if ($parts[1] -eq $note) { return } $text = $parts[0] + ' ' + $parts[1] + ' ' + $Expected + "`n" [System.IO.File]::WriteAllText($PublicPath, $text, $Utf8) } function Invoke-ResidentSearch([string]$Comment, [string]$Destination) { $script:ResidentNotes = New-Object System.Collections.Generic.List[string] $tmp = Join-Path ([System.IO.Path]::GetTempPath()) ('fido-' + [guid]::NewGuid().ToString('n')) New-Item -ItemType Directory -Path $tmp | Out-Null $previous = Get-Location try { Set-Location -LiteralPath $tmp $previousPreference = $ErrorActionPreference $ErrorActionPreference = 'Continue' & ssh-keygen -K -N '' | Out-Null $status = $LASTEXITCODE $ErrorActionPreference = $previousPreference if ($status -ne 0) { return 'failed' } $pubs = @(Get-ChildItem -LiteralPath $tmp -Filter '*.pub' -File -ErrorAction SilentlyContinue) $found = '' foreach ($pub in $pubs) { $line = ([System.IO.File]::ReadAllText($pub.FullName)).Trim() $parts = @($line -split '\s+' | Where-Object { $_ -ne '' }) if ($parts.Count -lt 1) { continue } $base = [System.IO.Path]::GetFileNameWithoutExtension($pub.Name) $note = Get-ResidentNote ([string]$parts[$parts.Count - 1]) $base [void]$script:ResidentNotes.Add($note) if ($parts[0] -notlike 'sk-*') { continue } if ([string]::IsNullOrEmpty($found) -and (Test-ResidentMatch $Comment ([string]$parts[$parts.Count - 1]) $base)) { $found = $pub.FullName -replace '\.pub$', '' } } if (-not [string]::IsNullOrEmpty($found)) { if (-not [string]::IsNullOrEmpty($Destination)) { Copy-Item -LiteralPath $found -Destination $Destination -Force Copy-Item -LiteralPath ($found + '.pub') -Destination ($Destination + '.pub') -Force Set-RecoveredComment ($Destination + '.pub') $Comment } return 'found' } return 'absent' } finally { Set-Location $previous if (Test-Path -LiteralPath $tmp) { Remove-Item -LiteralPath $tmp -Recurse -Force } } } function Install-RecoveredKey([string]$Comment, [string]$Destination, [string]$Display, [string]$Audience) { Assert-Tools Assert-OpenSshSk Ensure-SshDir Write-Info "Conecte somente a YubiKey $Display." Write-Info 'Será solicitado o PIN e, em seguida, o toque no dispositivo.' Write-Host '' $result = Invoke-ResidentSearch $Comment $Destination if ($result -eq 'failed') { Stop-Helper 'Não foi possível recuperar as credenciais residentes. Verifique a YubiKey, o PIN e se o OpenSSH tem suporte a FIDO.' } if ($result -ne 'found') { if ($script:ResidentNotes.Count -gt 0) { Write-Warn "Credenciais encontradas no token, mas nenhuma tem o comentário esperado: $Comment" Write-Warn 'Comentários encontrados:' $onlySsh = $true foreach ($note in $script:ResidentNotes) { Write-Host (' - ' + $note) # OpenSSH 10 com -O user guarda o user id no nome do arquivo. # "ssh:" sem sufixo é a credencial antiga, gravada sem nome. if ($note -ne 'ssh:') { $onlySsh = $false } } if ($onlySsh) { Write-Warn 'O comentário ssh: é o identificador padrão do OpenSSH quando a credencial foi gravada sem nome de usuário. Crie a chave de novo. A credencial antiga continua no token até ser apagada.' } } else { Write-Warn 'Nenhuma credencial residente foi recuperada.' } Stop-Helper "Confirme se a chave foi criada com -C `"$Comment`"." } Protect-UserFile $Destination Write-Ok "Credencial $Display recuperada em:" Write-Host " $Destination" & ssh-keygen -lf ($Destination + '.pub') if ($LASTEXITCODE -ne 0) { Write-Warn 'Não foi possível calcular o fingerprint.' } Write-Host '' if ($Audience -eq 'github') { Write-Info 'Cadastre esta chave pública no GitHub, caso ainda não tenha feito:' Write-Host '' Write-Host ([System.IO.File]::ReadAllText($Destination + '.pub')) Copy-PublicKey ($Destination + '.pub') Write-Host '' Write-Info "Ative-a em seguida pela opção de usar a YubiKey $Display." } else { Write-AuthorizedKeysCommand ($Destination + '.pub') Write-Info 'Depois escolha Instalar ou Conectar.' } } function Add-ResidentKey([string]$Value) { $label = Resolve-Label $Value Save-Account $script:YkSerial = '' Assert-ConnectedLabel $label Install-RecoveredKey (Get-Comment $label) (Get-KeyPath $label) (Get-LabelName $label) 'github' } function Add-ServerResidentKey([string]$Value) { $label = Resolve-Label $Value $script:YkSerial = '' Assert-ConnectedLabel $label Install-RecoveredKey (Get-ServerComment $label) (Get-ServerKeyPath $label) (Get-LabelName $label) 'server' } function Assert-NoExistingHandle([string]$Destination, [string]$Display, [string]$MenuName) { $public = $Destination + '.pub' if ((Test-Path -LiteralPath $Destination) -or (Test-Path -LiteralPath $public)) { Stop-Helper "Já existe um handle local para $Display. Use Desfazer no menu $MenuName antes de criar de novo." } } function Confirm-CreatedKey([string]$Destination, [string]$PublicPath, [string]$Comment) { Protect-UserFile $Destination $pubText = '' if (Test-Path -LiteralPath $PublicPath) { $pubText = [System.IO.File]::ReadAllText($PublicPath) } if (-not $pubText.StartsWith('sk-ssh-ed25519@openssh.com ')) { Remove-Item -LiteralPath $Destination, $PublicPath -Force -ErrorAction SilentlyContinue Stop-Helper 'A chave criada não é uma credencial ed25519 residente. Nada foi mantido.' } $result = Invoke-ResidentSearch $Comment '' if ($result -eq 'failed') { Write-Warn 'A chave FIDO foi gravada, mas não foi possível confirmar a credencial no token. O handle local foi mantido.' return 'failed' } if ($result -ne 'found') { if ($script:YkMulti) { Write-Warn 'A confirmação não encontrou o comentário. Com mais de uma YubiKey conectada, o handle local foi mantido.' return 'failed' } Remove-Item -LiteralPath $Destination, $PublicPath -Force -ErrorAction SilentlyContinue Stop-Helper 'A credencial não está no token. O handle local foi removido.' } return 'found' } function Use-ResidentKey([string]$Value) { $label = Resolve-Label $Value $display = Get-LabelName $label Assert-Tools Assert-OpenSshSk Ensure-SshDir Save-Account $identity = Get-KeyPath $label $public = $identity + '.pub' $who = $display $hint = "-Batch add $label" if (-not [string]::IsNullOrEmpty($script:Account)) { $who = "$($script:Account) $display" $hint = "-Batch add $($script:Account) $label" } if (-not (Test-Path -LiteralPath $identity) -or -not (Test-Path -LiteralPath $public)) { Stop-Helper "Chave $who não encontrada neste computador. Recupere-a antes com $hint." } Write-GithubConfig $identity Write-Ok (Get-ActiveAccountText $identity) Write-Host (' IdentityFile ' + (Convert-ToSshPath $identity)) Write-Host '' Write-Info 'Para conferir, escolha Testar no menu ou rode -Batch test.' } function Show-Status { if (-not (Test-Path -LiteralPath $ConfigFile)) { Write-Host 'Nenhuma YubiKey selecionada.' Write-Host 'Recupere a chave e escolha Usar para ativá-la.' return } $identity = Read-Identity if ([string]::IsNullOrEmpty($identity)) { Write-Host 'Arquivo de configuração existe, mas não contém IdentityFile.' return } Write-Host (Get-ActiveAccountText $identity) if (Test-Path -LiteralPath $identity) { Write-Host 'Arquivo local: presente' } else { Write-Host 'Arquivo local: ausente' } } function Get-TokenLabelFromText([string]$Text) { if ($Text -match 'USB-C') { return 'yuc' } if ($Text -match 'USB-A') { return 'yua' } if ($Text -match 'Security Key C([^0-9A-Za-z]|$)') { return 'yuc' } if ($Text -match 'Security Key([^0-9A-Za-z]|$)') { return 'yua' } return '' } function Get-DeviceModelName([string]$Line) { $name = $Line -replace '\s*Serial:\s*\d+.*$', '' $name = $name -replace '\s*\(.*$', '' return $name.Trim() } function Get-TokenPort([string]$Label) { if ($Label -eq 'yuc') { return 'USB-C' } if ($Label -eq 'yua') { return 'USB-A' } return $Label } function Update-ConnectedTokens { $script:ConnectedLabels = @() $script:ConnectedModels = @() $script:ConnectedSerials = @() $script:ConnectedScanned = $false if (-not (Get-Command ykman -ErrorAction SilentlyContinue)) { return } $previous = $ErrorActionPreference $ErrorActionPreference = 'Continue' $list = & ykman list 2>&1 | Out-String $ErrorActionPreference = $previous if ($list -match '') { return } $devices = New-Object System.Collections.Generic.List[string] $models = New-Object System.Collections.Generic.List[string] $serials = New-Object System.Collections.Generic.List[string] foreach ($line in ($list -split "`r`n|`n")) { $trim = $line.Trim() if ($trim.Length -eq 0) { continue } if ($trim -match '^(Usage:|Error:|Failed )') { continue } if ($trim -match 'No YubiKey') { continue } [void]$devices.Add($trim) [void]$models.Add((Get-DeviceModelName $trim)) if ($trim -match 'Serial:\s*(\d+)') { [void]$serials.Add($Matches[1]) } else { [void]$serials.Add('') } } $script:ConnectedScanned = $true if ($devices.Count -eq 0) { return } $labels = New-Object System.Collections.Generic.List[string] $keptModels = New-Object System.Collections.Generic.List[string] $keptSerials = New-Object System.Collections.Generic.List[string] $indexes = @(0) if ($devices.Count -gt 1) { $indexes = 0..($devices.Count - 1) } foreach ($i in $indexes) { $info = '' $ErrorActionPreference = 'Continue' if ($devices.Count -eq 1) { $info = & ykman info 2>&1 | Out-String } elseif (-not [string]::IsNullOrEmpty($serials[$i])) { $info = & ykman --device $serials[$i] info 2>&1 | Out-String } $ErrorActionPreference = $previous $text = $devices[$i] + "`n" + $models[$i] + "`n" + $info $classified = Get-TokenLabelFromText $text if ([string]::IsNullOrEmpty($classified)) { continue } [void]$labels.Add($classified) [void]$keptModels.Add($models[$i]) [void]$keptSerials.Add($serials[$i]) } $script:ConnectedLabels = $labels.ToArray() $script:ConnectedModels = $keptModels.ToArray() $script:ConnectedSerials = $keptSerials.ToArray() } function Get-ConnectedModel([string]$Label) { for ($i = 0; $i -lt $script:ConnectedLabels.Count; $i++) { if ($script:ConnectedLabels[$i] -eq $Label) { return [string]$script:ConnectedModels[$i] } } return '' } function Get-ConnectedSummary { $parts = New-Object System.Collections.Generic.List[string] for ($i = 0; $i -lt $script:ConnectedLabels.Count; $i++) { $name = Get-LabelName $script:ConnectedLabels[$i] $port = Get-TokenPort $script:ConnectedLabels[$i] [void]$parts.Add("$name ($($script:ConnectedModels[$i]), $port)") } return ($parts -join ', ') } function Test-LabelMatchesConnected([string]$Label) { if (-not $script:ConnectedScanned) { return $true } if ($script:ConnectedLabels.Count -eq 0) { return $true } if (-not [string]::IsNullOrEmpty($script:YkSerial)) { $saw = $false for ($i = 0; $i -lt $script:ConnectedSerials.Count; $i++) { if ($script:ConnectedSerials[$i] -ne $script:YkSerial) { continue } $saw = $true if ($script:ConnectedLabels[$i] -eq $Label) { return $true } } if (-not $saw) { return $true } return $false } foreach ($item in $script:ConnectedLabels) { if ($item -eq $Label) { return $true } } return $false } function Get-TokenMismatchMessage([string]$Label) { $hint = 'A YUA é a Security Key NFC, com USB-A.' if ($Label -eq 'yuc') { $hint = 'A YUC é a Security Key C NFC, com USB-C.' } if (-not [string]::IsNullOrEmpty($script:YkSerial)) { for ($i = 0; $i -lt $script:ConnectedSerials.Count; $i++) { if ($script:ConnectedSerials[$i] -eq $script:YkSerial) { $name = Get-LabelName $script:ConnectedLabels[$i] $port = Get-TokenPort $script:ConnectedLabels[$i] return "A série $($script:YkSerial) é a $name ($($script:ConnectedModels[$i]), $port). $hint" } } } return "Conectada agora: $(Get-ConnectedSummary). $hint" } function Assert-ConnectedLabel([string]$Label) { Update-ConnectedTokens if (Test-LabelMatchesConnected $Label) { return } Stop-Helper (Get-TokenMismatchMessage $Label) } function Write-AccountKeyLine([string]$Account, [string]$Label, [string]$Active) { $identity = Get-KeyPath $Label $Account $display = Get-LabelName $Label $title = $display if (-not [string]::IsNullOrEmpty($Account)) { $title = "$Account $display" } $public = $identity + '.pub' $connected = Get-ConnectedModel $Label if ((Test-Path -LiteralPath $identity) -and (Test-Path -LiteralPath $public)) { $color = 'Green' if ((Convert-ToSshPath $identity) -eq $Active) { $line = "✓ $title — presente neste computador, ativa" } else { $line = "✓ $title — presente neste computador" } if (-not [string]::IsNullOrEmpty($connected)) { $line = "$line, token conectado" } } elseif (-not [string]::IsNullOrEmpty($connected)) { $color = 'Yellow' $port = Get-TokenPort $Label $line = "· $title — conectada agora ($connected, $port), chave ainda não recuperada neste computador" } else { $color = 'DarkGray' $line = "· $title — ausente neste computador" } if (Test-UseColor) { Write-Host $line -ForegroundColor $color } else { Write-Host $line } } function Get-AccountNames { $names = New-Object System.Collections.Generic.List[string] if (-not (Test-Path -LiteralPath $AccountsFile)) { return @() } foreach ($line in [System.IO.File]::ReadAllLines($AccountsFile)) { $name = $line.Trim().ToLowerInvariant() if (Test-AccountName $name) { [void]$names.Add($name) } } foreach ($name in $names) { $name } } function Test-LegacyGithubKeys { return ( (Test-Path -LiteralPath (Get-KeyPath 'yuc' '')) -or (Test-Path -LiteralPath ((Get-KeyPath 'yuc' '') + '.pub')) -or (Test-Path -LiteralPath (Get-KeyPath 'yua' '')) -or (Test-Path -LiteralPath ((Get-KeyPath 'yua' '') + '.pub')) ) } function Show-List { Ensure-SshDir Update-ConnectedTokens $active = Convert-ToSshPath (Read-Identity) $names = @(Get-AccountNames) if ((Test-LegacyGithubKeys) -or $names.Count -eq 0) { foreach ($label in @('yuc', 'yua')) { Write-AccountKeyLine '' $label $active } } foreach ($account in $names) { foreach ($label in @('yuc', 'yua')) { Write-AccountKeyLine $account $label $active } } } function Show-Help { Write-Host '' if (Test-UseColor) { Write-Host 'Ajuda' -ForegroundColor Cyan } else { Write-Host 'Ajuda' } Write-Host 'O nome da conta escolhe qual GitHub está ativo. Cada YubiKey dessa conta tem a própria chave pública.' Write-Host 'YUC é a Security Key C NFC, com USB-C. YUA é a Security Key NFC, com USB-A, a reserva da mesma conta.' Write-Host 'O helper reconhece a conectada pelo nome Security Key que o ykman mostra. O 5.8.0 é só o firmware.' Write-Host 'Uma conta sem nome usa os comentários github-yuc e github-yua.' Write-Host '' Write-Host '1. Escolha o nome e Criar para gravar a credencial no token.' Write-Host '2. Ou recupere a credencial que já existe nesse token.' Write-Host '3. Usar define a conta e a YubiKey que git@github.com vai apresentar.' Write-Host '4. Testar mostra o usuário Hi do GitHub.' Write-Host '' Write-Host 'Sem menu: -Batch create trabalho 1, -Batch use trabalho 2, -Batch pub trabalho 1' } function Show-TokenHelp { Write-Host '' if (Test-UseColor) { Write-Host 'Qual número escolher' -ForegroundColor Cyan } else { Write-Host 'Qual número escolher' } Write-Host '1 YUC USB-C Security Key C NFC' Write-Host '2 YUA USB-A Security Key NFC' Write-Host 'O helper marca a que está conectada. Conecte o token correspondente antes de criar ou recuperar.' } function Write-ActiveSummary { $identity = Read-Identity if ([string]::IsNullOrEmpty($identity)) { if (Test-UseColor) { Write-Host 'Nenhuma chave ativa' -ForegroundColor Yellow } else { Write-Host 'Nenhuma chave ativa' } return } $text = Get-ActiveAccountText $identity if (Test-UseColor) { Write-Host $text -ForegroundColor Green } else { Write-Host $text } } function Test-KeyPresent([string]$Label) { $identity = Get-KeyPath $Label return ((Test-Path -LiteralPath $identity) -and (Test-Path -LiteralPath ($identity + '.pub'))) } function Write-PublicKey([string]$Label) { $pub = (Get-KeyPath $Label) + '.pub' $display = Get-LabelName $Label $port = 'USB-A' if ($Label -eq 'yuc') { $port = 'USB-C' } $title = "$display ($port)" if (-not [string]::IsNullOrEmpty($script:Account)) { $title = "$($script:Account) $title" } Write-Host '' Write-Info $title Write-Host '' Write-Host ([System.IO.File]::ReadAllText($pub)) } function Show-PublicKeys { $present = @() foreach ($label in @('yuc', 'yua')) { if (Test-KeyPresent $label) { Write-PublicKey $label $present += $label } } if ($present.Count -eq 0) { Write-Warn 'Nenhuma chave recuperada. Escolha Recuperar antes de cadastrar no GitHub.' return } if ($present.Count -eq 1) { Copy-PublicKey ((Get-KeyPath $present[0]) + '.pub') return } while ($true) { Write-Host '' Write-Host 'Qual chave copiar para cadastrar no GitHub?' Write-MenuRow '1' 'YUC' 'USB-C' Write-MenuRow '2' 'YUA' 'USB-A' Write-MenuRow '3' 'Voltar' 'retorna ao menu' $choice = Read-ConsoleLine 'Número' if ($null -eq $choice) { $choice = '' } $choice = $choice.Trim().ToLowerInvariant() switch ($choice) { { $_ -in @('1', 'yuc') } { Copy-PublicKey ((Get-KeyPath 'yuc') + '.pub'); return } { $_ -in @('2', 'yua') } { Copy-PublicKey ((Get-KeyPath 'yua') + '.pub'); return } { $_ -in @('3', 'voltar', 'q') } { return } default { if (Test-UseColor) { Write-Host 'Escolha um número da lista.' -ForegroundColor Yellow } else { Write-Host 'Escolha um número da lista.' } } } } } function Show-PublicKeysBatch([string]$Selector) { if ([string]::IsNullOrEmpty($Selector)) { $found = $false foreach ($label in @('yuc', 'yua')) { if (Test-KeyPresent $label) { Write-PublicKey $label $found = $true } } if (-not $found) { Stop-Helper 'Nenhuma chave recuperada. Escolha Recuperar antes de cadastrar no GitHub.' } return } $label = Resolve-Label $Selector if (-not (Test-KeyPresent $label)) { $display = Get-LabelName $label Stop-Helper "Chave $display não recuperada neste computador. Escolha Recuperar antes de cadastrar no GitHub." } Write-PublicKey $label Copy-PublicKey ((Get-KeyPath $label) + '.pub') } function Get-OwnedPaths { $paths = New-Object System.Collections.Generic.List[string] foreach ($path in @( $ConfigFile, $LegacyConfigFile, $AccountsFile, (Get-KeyPath 'yuc' ''), ((Get-KeyPath 'yuc' '') + '.pub'), (Get-KeyPath 'yua' ''), ((Get-KeyPath 'yua' '') + '.pub') )) { [void]$paths.Add($path) } if (Test-Path -LiteralPath $SshDir) { foreach ($item in (Get-ChildItem -LiteralPath $SshDir -File -ErrorAction SilentlyContinue)) { if ($item.Name -like '*_github_id_ed25519_sk' -or $item.Name -like '*_github_id_ed25519_sk.pub') { [void]$paths.Add($item.FullName) } } } return @($paths.ToArray()) } function Test-OwnedLink([string]$Path) { if (-not (Test-Path -LiteralPath $Path)) { return $false } $item = Get-Item -LiteralPath $Path -Force if ($item.Attributes -band [System.IO.FileAttributes]::ReparsePoint) { return $true } $link = $item.PSObject.Properties['LinkType'] if ($link -and $link.Value) { return $true } return $false } function Write-IgnoredLinks { foreach ($path in (Get-OwnedPaths)) { if (Test-OwnedLink $path) { Write-Warn "Atalho ignorado: $path" } } if (Test-OwnedLink $MainConfig) { Write-Warn "Atalho ignorado: $MainConfig" } } function Get-ConfigLine([string]$Line) { if ($null -eq $Line) { return '' } return $Line.TrimStart([char]0xFEFF).TrimEnd("`r") } function Test-MainConfigInclude { if (-not (Test-Path -LiteralPath $MainConfig)) { return $false } if (Test-OwnedLink $MainConfig) { return $false } foreach ($line in [System.IO.File]::ReadAllLines($MainConfig)) { $current = Get-ConfigLine $line if ($current -eq $IncludeLine -or $current -eq $LegacyIncludeLine) { return $true } } return $false } function Test-UndoWork { foreach ($path in (Get-OwnedPaths)) { if ((Test-Path -LiteralPath $path) -and -not (Test-OwnedLink $path)) { $item = Get-Item -LiteralPath $path -Force if (-not $item.PSIsContainer) { return $true } } } if (Test-MainConfigInclude) { return $true } return $false } function Remove-IncludeLine { $text = [System.IO.File]::ReadAllText($MainConfig) $newline = "`n" if ($text -match "`r`n") { $newline = "`r`n" } $kept = New-Object System.Collections.Generic.List[string] $any = $false foreach ($line in ($text -split "`r`n|`n")) { $current = Get-ConfigLine $line if ($current -eq $IncludeLine -or $current -eq $LegacyIncludeLine) { continue } $kept.Add((Get-ConfigLine $line)) | Out-Null if ((Get-ConfigLine $line).Trim().Length -gt 0) { $any = $true } } if (-not $any) { Remove-Item -LiteralPath $MainConfig -Force Write-Ok "Removido: $MainConfig" return } $body = [string]::Join($newline, $kept.ToArray()) [System.IO.File]::WriteAllText($MainConfig, $body, $Utf8) Write-Ok "Removida a linha Include de $MainConfig" } function Invoke-Undo { Write-IgnoredLinks $removed = $false foreach ($path in (Get-OwnedPaths)) { if (-not (Test-Path -LiteralPath $path)) { continue } if (Test-OwnedLink $path) { continue } $item = Get-Item -LiteralPath $path -Force if ($item.PSIsContainer) { continue } Remove-Item -LiteralPath $path -Force Write-Ok "Removido: $path" $removed = $true } if (Test-MainConfigInclude) { Remove-IncludeLine $removed = $true } if (-not $removed) { Write-Warn 'Nada deste helper foi encontrado. O SSH não foi alterado.' } } function Invoke-UndoInteractive { Write-Host '' if (-not (Test-UndoWork)) { Write-IgnoredLinks Write-Warn 'Nada deste helper foi encontrado. O SSH não foi alterado.' return } Write-Host 'Isto será removido:' foreach ($path in (Get-OwnedPaths)) { if ((Test-Path -LiteralPath $path) -and -not (Test-OwnedLink $path)) { $item = Get-Item -LiteralPath $path -Force if (-not $item.PSIsContainer) { Write-Host " $path" } } } if (Test-MainConfigInclude) { Write-Host " linha Include em $MainConfig" } while ($true) { Write-Host '' Write-MenuRow '1' 'Confirmar' 'apaga só estes itens' Write-MenuRow '2' 'Voltar' 'não altera nada' $choice = Read-ConsoleLine 'Número' if ($null -eq $choice) { $choice = '' } $choice = $choice.Trim().ToLowerInvariant() switch ($choice) { { $_ -in @('1', 'confirmar') } { Invoke-Undo; return } { $_ -in @('2', 'voltar', 'q') } { Write-Info 'Nada foi alterado.'; return } default { if (Test-UseColor) { Write-Host 'Escolha um número da lista.' -ForegroundColor Yellow } else { Write-Host 'Escolha um número da lista.' } } } } } function Read-Label { $script:YkSerial = '' Update-ConnectedTokens while ($true) { $yucDetail = 'USB-C' $yuaDetail = 'USB-A' $yucModel = Get-ConnectedModel 'yuc' $yuaModel = Get-ConnectedModel 'yua' if (-not [string]::IsNullOrEmpty($yucModel)) { $yucDetail = "USB-C, conectada agora ($yucModel)" } if (-not [string]::IsNullOrEmpty($yuaModel)) { $yuaDetail = "USB-A, conectada agora ($yuaModel)" } Write-Host '' Write-Host 'Qual YubiKey?' Write-MenuRow '1' 'YUC' $yucDetail Write-MenuRow '2' 'YUA' $yuaDetail Write-MenuRow '3' 'Ajuda' 'o que significa cada uma' Write-MenuRow '4' 'Voltar' 'retorna ao menu' $choice = Read-ConsoleLine 'Número' if ($null -eq $choice) { $choice = '' } $choice = $choice.Trim().ToLowerInvariant() $label = '' switch ($choice) { { $_ -in @('1', 'yuc') } { $label = 'yuc' } { $_ -in @('2', 'yua') } { $label = 'yua' } { $_ -in @('3', 'ajuda', 'help', '?') } { Show-TokenHelp } { $_ -in @('4', 'voltar', 'q') } { return } default { if (Test-UseColor) { Write-Host 'Escolha um número da lista.' -ForegroundColor Yellow } else { Write-Host 'Escolha um número da lista.' } } } if ([string]::IsNullOrEmpty($label)) { continue } if (-not (Test-LabelMatchesConnected $label)) { $message = Get-TokenMismatchMessage $label if (Test-UseColor) { Write-Host $message -ForegroundColor Yellow } else { Write-Host $message } continue } return $label } } function Test-Github { Assert-Tools $identity = Read-Identity if ([string]::IsNullOrEmpty($identity) -or -not (Test-Path -LiteralPath $identity)) { Write-Warn 'Nenhuma chave ativa. Escolha Usar antes de testar.' return $false } Write-Info 'Testando git@github.com. O PIN e o toque são os pedidos do SSH.' $previous = $ErrorActionPreference $ErrorActionPreference = 'Continue' $output = & ssh -T -i $identity -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new git@github.com 2>&1 | Out-String $status = $LASTEXITCODE $ErrorActionPreference = $previous Write-Host $output if ($output -match 'successfully authenticated') { if ($output -match 'Hi ([^!]+)!') { Write-Ok "GitHub autenticou como $($Matches[1])." } else { Write-Ok 'GitHub autenticou.' } return $true } if ($output -match 'permission denied') { Write-Warn 'GitHub não autenticou. A chave ativa pode não estar cadastrada na conta.' return $false } Write-Warn "Não foi possível confirmar a autenticação (código $status)." return $false } $YubicoYkmanUrl = 'https://www.yubico.com/support/download/yubikey-manager/' function Get-YkmanManager { if ($env:OS -eq 'Windows_NT') { if (Get-Command winget -ErrorAction SilentlyContinue) { return 'winget' } return '' } $uname = '' try { $uname = & uname -s 2>$null } catch { $uname = '' } if ($uname -eq 'Darwin') { if (Get-Command brew -ErrorAction SilentlyContinue) { return 'brew' } return '' } if (Get-Command apt-get -ErrorAction SilentlyContinue) { return 'apt' } if (Get-Command dnf -ErrorAction SilentlyContinue) { return 'dnf' } return '' } function Get-YkmanInstallCommand { switch (Get-YkmanManager) { 'brew' { return 'brew install yubikey-manager' } 'apt' { return 'sudo apt-get install -y yubikey-manager' } 'dnf' { return 'sudo dnf install -y yubikey-manager' } 'winget' { return 'winget install --id Yubico.YubiKeyManagerCLI -e' } default { return '' } } } function Install-YkmanPackage { switch (Get-YkmanManager) { 'brew' { & brew install yubikey-manager } 'apt' { & sudo apt-get install -y yubikey-manager } 'dnf' { & sudo dnf install -y yubikey-manager } 'winget' { & winget install --id Yubico.YubiKeyManagerCLI -e } default { return $false } } return ($LASTEXITCODE -eq 0) } function Confirm-Ykman([bool]$BatchMode) { if (Get-Command ykman -ErrorAction SilentlyContinue) { return $true } $cmd = Get-YkmanInstallCommand if ([string]::IsNullOrEmpty($cmd)) { Stop-Helper "ykman não encontrado. Baixe em $YubicoYkmanUrl" } if ($BatchMode) { Stop-Helper "ykman não encontrado. Instale com: $cmd" } Write-Host '' Write-Host 'O ykman não está instalado.' Write-Host " $cmd" while ($true) { Write-Host '' Write-MenuRow '1' 'Instalar' 'executa o comando acima' Write-MenuRow '2' 'Voltar' 'não instala nada' $choice = Read-ConsoleLine 'Número' if ($null -eq $choice) { $choice = '' } $choice = $choice.Trim().ToLowerInvariant() switch ($choice) { { $_ -in @('1', 'instalar') } { if (-not (Install-YkmanPackage)) { Stop-Helper 'Não foi possível instalar o ykman.' } if (-not (Get-Command ykman -ErrorAction SilentlyContinue)) { Stop-Helper 'O ykman foi instalado, mas não está no PATH deste terminal. Abra um novo terminal e rode o helper de novo.' } return $true } { $_ -in @('2', 'voltar', 'q') } { return $false } default { if (Test-UseColor) { Write-Host 'Escolha um número da lista.' -ForegroundColor Yellow } else { Write-Host 'Escolha um número da lista.' } } } } } $script:YkSerial = '' $script:YkMulti = $false function Invoke-Ykman { param([Parameter(ValueFromRemainingArguments = $true)][string[]]$YkArgs) if (-not [string]::IsNullOrEmpty($script:YkSerial)) { & ykman --device $script:YkSerial @YkArgs return } & ykman @YkArgs } function Select-Token([bool]$BatchMode, [string]$Requested, [string]$CommandName) { $script:YkSerial = '' $script:YkMulti = $false $previous = $ErrorActionPreference $ErrorActionPreference = 'Continue' $list = & ykman list | Out-String $ErrorActionPreference = $previous $devices = New-Object System.Collections.Generic.List[string] $serials = New-Object System.Collections.Generic.List[string] $models = New-Object System.Collections.Generic.List[string] $denied = $false foreach ($line in ($list -split "`r`n|`n")) { $trim = $line.Trim() if ($trim.Length -eq 0) { continue } if ($trim -match '^(Usage:|Error:|Failed )') { continue } if ($trim -match 'No YubiKey') { continue } if ($trim -match '') { $denied = $true } [void]$devices.Add($trim) if ($trim -match 'Serial:\s*(\d+)') { $serial = $Matches[1] $model = ($trim -replace '\s*Serial:\s*\d+.*$', '').Trim() [void]$serials.Add($serial) [void]$models.Add($model) } } if ($denied) { Stop-Helper 'A YubiKey está conectada, mas o ykman não tem permissão para falar com ela. No Linux, seu usuário precisa do grupo plugdev ou da regra udev da Yubico.' } if ($devices.Count -eq 0) { Stop-Helper 'Nenhuma YubiKey encontrada. Conecte um token e tente de novo.' } if ($devices.Count -le 1) { return $true } $script:YkMulti = $true if ($serials.Count -eq 0) { Stop-Helper 'Há mais de uma YubiKey conectada. Deixe somente a que vai receber a credencial.' } if ($BatchMode) { if ([string]::IsNullOrEmpty($Requested)) { Write-Host 'Séries conectadas:' for ($i = 0; $i -lt $serials.Count; $i++) { Write-Host (" " + $serials[$i] + " " + $models[$i]) } Stop-Helper "Há mais de uma YubiKey. Informe a série. Exemplo: -Batch $CommandName 1 $($serials[0])" } $wanted = $Requested.Trim() $known = $false foreach ($serial in $serials) { if ($serial -eq $wanted) { $known = $true; break } } if (-not $known) { Stop-Helper "Série $wanted não está conectada." } $script:YkSerial = $wanted return $true } while ($true) { Write-Host '' Write-Host 'Qual YubiKey recebe a credencial?' for ($i = 0; $i -lt $serials.Count; $i++) { Write-MenuRow ([string]($i + 1)) $serials[$i] $models[$i] } Write-MenuRow ([string]($serials.Count + 1)) 'Voltar' 'retorna ao menu' $choice = Read-ConsoleLine 'Número' if ($null -eq $choice) { $choice = '' } $choice = $choice.Trim().ToLowerInvariant() if ($choice -eq ([string]($serials.Count + 1)) -or $choice -eq 'voltar' -or $choice -eq 'q') { return $false } foreach ($serial in $serials) { if ($choice -eq $serial) { $script:YkSerial = $serial return $true } } $number = 0 if ([int]::TryParse($choice, [ref]$number) -and $number -ge 1 -and $number -le $serials.Count) { $script:YkSerial = $serials[$number - 1] return $true } if (Test-UseColor) { Write-Host 'Escolha um número da lista.' -ForegroundColor Yellow } else { Write-Host 'Escolha um número da lista.' } } } function Confirm-FidoPin { $previous = $ErrorActionPreference $ErrorActionPreference = 'Continue' $info = Invoke-Ykman fido info 2>&1 | Out-String $ErrorActionPreference = $previous if ($info -match 'not set|not configured|no pin') { if (-not (Test-InteractiveConsole)) { Stop-Helper 'Terminal interativo não encontrado. Defina o PIN FIDO em um terminal e rode o helper de novo.' } Write-Info 'Este token ainda não tem PIN FIDO. Você vai definir um agora.' Invoke-Ykman fido access change-pin if ($LASTEXITCODE -ne 0) { Stop-Helper 'Não foi possível definir o PIN FIDO.' } } } function Write-CreateTarget([string]$Display) { if ($script:YkMulti -and -not [string]::IsNullOrEmpty($script:YkSerial)) { Write-Info "Toque a YubiKey de série $($script:YkSerial). O OpenSSH usa a primeira que você tocar." } else { Write-Info "Conecte somente a YubiKey $Display." } } function New-ResidentKey([string]$Value, [bool]$BatchMode, [string]$Serial = '') { $label = Resolve-Label $Value Save-Account $comment = Get-Comment $label $display = Get-LabelName $label $who = $display if (-not [string]::IsNullOrEmpty($script:Account)) { $who = "$($script:Account) $display" } Assert-Tools Assert-OpenSshSk if (-not (Confirm-Ykman $BatchMode)) { return } if (-not (Select-Token $BatchMode $Serial 'create')) { return } Assert-ConnectedLabel $label Confirm-FidoPin Ensure-SshDir $destination = Get-KeyPath $label $public = $destination + '.pub' Assert-NoExistingHandle $destination $who 'GitHub' Write-CreateTarget $display Write-Info 'O OpenSSH vai gravar a credencial residente.' Write-Info 'Digite o PIN quando aparecer Enter PIN. Toque na YubiKey quando ela piscar, depois do PIN.' Write-Info 'Se aparecer Overwrite key in token, responda y para substituir a credencial desse nome.' $previous = $ErrorActionPreference $ErrorActionPreference = 'Continue' $application = Get-CredentialApplication $comment & ssh-keygen -q -t ed25519-sk -O resident -O verify-required -O "application=$application" -O "user=$comment" -C $comment -N '' -f $destination $status = $LASTEXITCODE $ErrorActionPreference = $previous if ($status -ne 0) { Remove-Item -LiteralPath $destination, $public -Force -ErrorAction SilentlyContinue Stop-Helper 'Não foi possível criar a credencial. Se aparecer Overwrite key in token, responda y. Confira o PIN, o toque e se há somente uma YubiKey conectada.' } $confirmed = Confirm-CreatedKey $destination $public $comment if ($confirmed -eq 'found') { Write-Ok "Credencial $display criada em:" } else { Write-Ok 'Handle local gravado em:' } Write-Host " $destination" Write-Host '' Write-Host ([System.IO.File]::ReadAllText($public)) Copy-PublicKey $public Write-Info 'Ative-a em seguida pela opção Usar.' } function Read-Account { while ($true) { $names = @(Get-AccountNames) $slots = New-Object System.Collections.Generic.List[string] Write-Host '' Write-Host 'Qual conta?' if ((Test-LegacyGithubKeys) -or $names.Count -eq 0) { [void]$slots.Add('') Write-MenuRow ([string]$slots.Count) 'sem nome' 'chaves github-yuc e github-yua' } foreach ($name in $names) { [void]$slots.Add($name) Write-MenuRow ([string]$slots.Count) $name 'conta do GitHub' } $nova = $slots.Count + 1 $voltar = $slots.Count + 2 Write-MenuRow ([string]$nova) 'Nova' 'grava um nome novo' Write-MenuRow ([string]$voltar) 'Voltar' 'retorna ao menu' $choice = Read-ConsoleLine 'Número' if ($null -eq $choice) { $choice = '' } $choice = $choice.Trim().ToLowerInvariant() if ($choice -eq ([string]$voltar) -or $choice -eq 'voltar' -or $choice -eq 'q') { return $null } foreach ($slot in $slots) { if (-not [string]::IsNullOrEmpty($slot) -and $choice -eq $slot) { return $slot } } if ($choice -eq ([string]$nova) -or $choice -eq 'nova') { $typed = Read-ConsoleLine 'Nome' if ($null -eq $typed) { $typed = '' } $typed = $typed.Trim().ToLowerInvariant() if (-not (Test-AccountName $typed)) { if (Test-UseColor) { Write-Host 'Use letras minúsculas, números e hífen. Exemplo: trabalho' -ForegroundColor Yellow } else { Write-Host 'Use letras minúsculas, números e hífen. Exemplo: trabalho' } continue } $script:Account = $typed Save-Account return $typed } $number = 0 if ([int]::TryParse($choice, [ref]$number) -and $number -ge 1 -and $number -le $slots.Count) { return $slots[$number - 1] } if (Test-UseColor) { Write-Host 'Escolha um número da lista.' -ForegroundColor Yellow } else { Write-Host 'Escolha um número da lista.' } } } function Invoke-GithubAccountAction([string]$Action) { $account = Read-Account if ($null -eq $account) { return } $script:Account = $account if ($Action -eq 'pub') { Show-PublicKeys return } $label = Read-Label if (-not $label) { return } switch ($Action) { 'create' { New-ResidentKey $label $false '' } 'add' { Add-ResidentKey $label } 'use' { Use-ResidentKey $label } } } function Invoke-GithubMenu { while ($true) { Write-Host '' if (Test-UseColor) { Write-Host 'GitHub' -ForegroundColor Cyan } else { Write-Host 'GitHub' } Write-ActiveSummary Write-Host '' Write-MenuRow '1' 'Criar' 'grava a credencial da conta no token' Write-MenuRow '2' 'Recuperar' 'lê a chave dessa conta no token' Write-MenuRow '3' 'Usar' 'ativa a conta em git@github.com' Write-MenuRow '4' 'Testar' 'autentica em git@github.com' Write-MenuRow '5' 'Status' 'mostra a conta ativa' Write-MenuRow '6' 'Listar' 'mostra a YubiKey conectada e as chaves recuperadas' Write-MenuRow '7' 'Públicas' 'mostra a chave para cadastrar nessa conta' Write-MenuRow '8' 'Ajuda' 'explica o nome, YUC, YUA e o fluxo' Write-MenuRow '9' 'Desfazer' 'remove o que este helper gravou neste computador' Write-MenuRow '10' 'Voltar' 'retorna ao menu inicial' $choice = Read-ConsoleLine 'Número' if ($null -eq $choice) { $choice = '' } $choice = $choice.Trim().ToLowerInvariant() switch ($choice) { { $_ -in @('1', 'criar', 'create') } { Invoke-GithubAccountAction 'create' } { $_ -in @('2', 'recuperar', 'add') } { Invoke-GithubAccountAction 'add' } { $_ -in @('3', 'usar', 'use') } { Invoke-GithubAccountAction 'use' } { $_ -in @('4', 'testar', 'test') } { Test-Github | Out-Null } { $_ -in @('5', 'status') } { Show-Status } { $_ -in @('6', 'listar', 'list') } { Show-List } { $_ -in @('7', 'publicas', 'pub') } { Invoke-GithubAccountAction 'pub' } { $_ -in @('8', 'ajuda', 'help', '?') } { Show-Help } { $_ -in @('9', 'desfazer', 'undo') } { Invoke-UndoInteractive } { $_ -in @('10', 'voltar', 'q') } { return } default { if (Test-UseColor) { Write-Host 'Escolha um número da lista.' -ForegroundColor Yellow } else { Write-Host 'Escolha um número da lista.' } } } } } function Set-ServerName([string]$Name) { if ([string]::IsNullOrEmpty($Name)) { $script:ServerName = '' return } $normalized = $Name.Trim().ToLowerInvariant() if (-not (Test-AccountName $normalized)) { Stop-Helper "Nome inválido: $normalized. Use letras minúsculas, números e hífen. Exemplo: casa" } $script:ServerName = $normalized Save-ServerName } function Save-ServerName { if ([string]::IsNullOrEmpty($script:ServerName)) { return } Ensure-SshDir $lines = New-Object System.Collections.Generic.List[string] if (Test-Path -LiteralPath $ServerAccounts) { foreach ($line in [System.IO.File]::ReadAllLines($ServerAccounts)) { if ($line -eq $script:ServerName) { Protect-UserFile $ServerAccounts return } [void]$lines.Add($line) } } [void]$lines.Add($script:ServerName) [System.IO.File]::WriteAllLines($ServerAccounts, $lines.ToArray(), $Utf8) Protect-UserFile $ServerAccounts } function Get-ServerNames { $names = New-Object System.Collections.Generic.List[string] if (-not (Test-Path -LiteralPath $ServerAccounts)) { return @() } foreach ($line in [System.IO.File]::ReadAllLines($ServerAccounts)) { $name = $line.Trim().ToLowerInvariant() if (Test-AccountName $name) { [void]$names.Add($name) } } return ,$names.ToArray() } function Get-ServerKeyPath([string]$Label) { if (-not [string]::IsNullOrEmpty($script:ServerName)) { return (Join-Path $SshDir ($script:ServerName + '_' + $Label + '_server_id_ed25519_sk')) } Join-Path $SshDir ($Label + '_server_id_ed25519_sk') } function Get-ServerComment([string]$Label) { if (-not [string]::IsNullOrEmpty($script:ServerName)) { return ('server-' + $script:ServerName + '-' + $Label) } switch ($Label) { 'yuc' { 'server-yuc' } 'yua' { 'server-yua' } } } function Get-ServerOwnedPaths { $paths = New-Object System.Collections.Generic.List[string] foreach ($extra in @($ServerHosts, $LegacyServerHosts, $ServerAccounts, $ServerFavs)) { [void]$paths.Add($extra) } if (Test-Path -LiteralPath $SshDir) { Get-ChildItem -LiteralPath $SshDir -File -ErrorAction SilentlyContinue | ForEach-Object { if ($_.Name -like '*_server_id_ed25519_sk' -or $_.Name -like '*_server_id_ed25519_sk.pub') { [void]$paths.Add($_.FullName) } } } return ,$paths.ToArray() } function Test-SshTarget([string]$Target) { return $Target -match '^[A-Za-z0-9._+-]+@([A-Za-z0-9._%-]+|\[[A-Za-z0-9.:%-]+\])$' } function Test-ServerKeyPresent([string]$Label) { $identity = Get-ServerKeyPath $Label return ((Test-Path -LiteralPath $identity) -and (Test-Path -LiteralPath ($identity + '.pub'))) } function Add-RecentServer([string]$Target, [string]$Label) { Ensure-SshDir $line = "$Target $Label" if (-not [string]::IsNullOrEmpty($script:ServerName)) { $line = "$Target $($script:ServerName) $Label" } $kept = New-Object System.Collections.Generic.List[string] $kept.Add($line) | Out-Null if (Test-Path -LiteralPath $ServerHosts) { foreach ($current in [System.IO.File]::ReadAllLines($ServerHosts)) { if ([string]::IsNullOrEmpty($current) -or $current -eq $line) { continue } if ($kept.Count -ge 6) { break } $kept.Add($current) | Out-Null } } $body = [string]::Join("`n", $kept.ToArray()) + "`n" [System.IO.File]::WriteAllText($ServerHosts, $body, $Utf8) Protect-UserFile $ServerHosts } function Get-RecentTitle([string]$Name, [string]$Label, [string]$Target) { $who = Get-LabelName $Label if ([string]::IsNullOrEmpty($Name)) { return "Servidor > Conectar > $who > $Target" } return "Servidor > Conectar > $Name > $who > $Target" } function Get-FavoriteDetail([string]$Target, [string]$Label) { return ($Target + ' · ' + (Get-LabelName $Label)) } function Get-RecentServers { $rows = New-Object System.Collections.Generic.List[object] if (Test-Path -LiteralPath $ServerHosts) { foreach ($line in [System.IO.File]::ReadAllLines($ServerHosts)) { $parts = @($line -split '\s+' | Where-Object { $_ -ne '' }) $name = '' $label = '' if ($parts.Count -eq 2) { $label = $parts[1] } elseif ($parts.Count -eq 3) { $name = $parts[1] $label = $parts[2] } else { continue } if (-not (Test-SshTarget $parts[0])) { continue } if ($label -ne 'yuc' -and $label -ne 'yua') { continue } if (-not [string]::IsNullOrEmpty($name) -and -not (Test-AccountName $name)) { continue } $rows.Add([pscustomobject]@{ Target = $parts[0] Name = $name Label = $label }) | Out-Null } } return ,$rows.ToArray() } function Get-FavoriteServers { $rows = New-Object System.Collections.Generic.List[object] if (Test-Path -LiteralPath $ServerFavs) { foreach ($line in [System.IO.File]::ReadAllLines($ServerFavs)) { $parts = @($line -split '\s+' | Where-Object { $_ -ne '' }) if ($parts.Count -ne 4) { continue } $name = $parts[2] $label = $parts[3] if (-not (Test-AccountName $parts[0])) { continue } if (-not (Test-SshTarget $parts[1])) { continue } if ($label -ne 'yuc' -and $label -ne 'yua') { continue } if ($name -eq '-') { $name = '' } elseif (-not (Test-AccountName $name)) { continue } $rows.Add([pscustomobject]@{ Alias = $parts[0] Target = $parts[1] Name = $name Label = $label }) | Out-Null } } return ,$rows.ToArray() } function Write-FavoriteRows([System.Collections.Generic.List[object]]$Rows) { if ($null -eq $Rows -or $Rows.Count -eq 0) { if (Test-Path -LiteralPath $ServerFavs) { Remove-Item -LiteralPath $ServerFavs -Force } return } Ensure-SshDir $lines = New-Object System.Collections.Generic.List[string] foreach ($row in $Rows) { $stored = '-' if (-not [string]::IsNullOrEmpty($row.Name)) { $stored = $row.Name } $lines.Add("$($row.Alias) $($row.Target) $stored $($row.Label)") | Out-Null } $body = [string]::Join("`n", $lines.ToArray()) + "`n" [System.IO.File]::WriteAllText($ServerFavs, $body, $Utf8) Protect-UserFile $ServerFavs } function Save-Favorite([string]$Alias, [string]$Target, [string]$Label) { $stored = '-' if (-not [string]::IsNullOrEmpty($script:ServerName)) { $stored = $script:ServerName } $line = "$Alias $Target $stored $Label" $kept = New-Object System.Collections.Generic.List[string] $found = $false if (Test-Path -LiteralPath $ServerFavs) { foreach ($current in [System.IO.File]::ReadAllLines($ServerFavs)) { if ([string]::IsNullOrEmpty($current)) { continue } $currentAlias = ($current -split '\s+', 2)[0] if ($currentAlias -eq $Alias) { $kept.Add($line) | Out-Null $found = $true } else { $kept.Add($current) | Out-Null } } } if (-not $found) { $kept.Add($line) | Out-Null } Ensure-SshDir $body = [string]::Join("`n", $kept.ToArray()) + "`n" [System.IO.File]::WriteAllText($ServerFavs, $body, $Utf8) Protect-UserFile $ServerFavs } function Get-HomeShortcuts { $items = New-Object System.Collections.Generic.List[object] $seen = @{} foreach ($fav in @(Get-FavoriteServers)) { $seen["$($fav.Target)|$($fav.Name)|$($fav.Label)"] = $true $items.Add([pscustomobject]@{ Title = $fav.Alias Detail = (Get-FavoriteDetail $fav.Target $fav.Label) Name = $fav.Name Label = $fav.Label Target = $fav.Target }) | Out-Null } $added = 0 foreach ($recent in @(Get-RecentServers)) { if ($added -ge 6) { break } $key = "$($recent.Target)|$($recent.Name)|$($recent.Label)" if ($seen.ContainsKey($key)) { continue } $items.Add([pscustomobject]@{ Title = (Get-RecentTitle $recent.Name $recent.Label $recent.Target) Detail = 'conecta agora' Name = $recent.Name Label = $recent.Label Target = $recent.Target }) | Out-Null $added++ } return ,$items.ToArray() } function Read-FavoriteAlias { while ($true) { $typed = Read-ConsoleLine 'Nome do servidor' if ($null -eq $typed) { $typed = '' } $typed = $typed.Trim().ToLowerInvariant() if ([string]::IsNullOrEmpty($typed)) { return '' } if (Test-AccountName $typed) { return $typed } if (Test-UseColor) { Write-Host 'Use letras minúsculas, números e hífen. Exemplo: casa' -ForegroundColor Yellow } else { Write-Host 'Use letras minúsculas, números e hífen. Exemplo: casa' } } } function Read-SshTarget { while ($true) { $target = Read-ConsoleLine 'user@ip' if ($null -eq $target) { $target = '' } $target = $target.Trim() if (Test-SshTarget $target) { return $target } if (Test-UseColor) { Write-Host 'Use o formato user@ip, sem espaços.' -ForegroundColor Yellow } else { Write-Host 'Use o formato user@ip, sem espaços.' } } } function New-ServerKey([string]$Value, [bool]$BatchMode, [string]$Serial = '') { $label = Resolve-Label $Value $comment = Get-ServerComment $label $display = Get-LabelName $label $who = $display if (-not [string]::IsNullOrEmpty($script:ServerName)) { $who = "$($script:ServerName) $display" } Assert-Tools Assert-OpenSshSk if (-not (Confirm-Ykman $BatchMode)) { return } if (-not (Select-Token $BatchMode $Serial 'server-create')) { return } Assert-ConnectedLabel $label Confirm-FidoPin Ensure-SshDir $destination = Get-ServerKeyPath $label $public = $destination + '.pub' Assert-NoExistingHandle $destination $who 'Servidor' Write-CreateTarget $display Write-Info 'A credencial será residente no token.' Write-Info 'Digite o PIN quando aparecer Enter PIN. Toque na YubiKey quando ela piscar, depois do PIN.' Write-Info 'Se aparecer Overwrite key in token, responda y para substituir a credencial desse nome.' $previous = $ErrorActionPreference $ErrorActionPreference = 'Continue' $application = Get-CredentialApplication $comment & ssh-keygen -q -t ed25519-sk -O resident -O verify-required -O "application=$application" -O "user=$comment" -C $comment -N '' -f $destination $status = $LASTEXITCODE $ErrorActionPreference = $previous if ($status -ne 0) { Remove-Item -LiteralPath $destination, $public -Force -ErrorAction SilentlyContinue Stop-Helper 'Não foi possível criar a credencial residente. Se aparecer Overwrite key in token, responda y. Confira o PIN, o toque e se há somente uma YubiKey conectada.' } $confirmed = Confirm-CreatedKey $destination $public $comment if ($confirmed -eq 'found') { Write-Ok "Credencial residente $display criada em:" } else { Write-Ok 'Handle local gravado em:' } Write-Host " $destination" Write-Host '' Write-AuthorizedKeysCommand $public Write-Info 'Depois escolha Conectar.' } function Write-ServerInstallHelp([string]$PublicPath) { Write-Host '' Write-AuthorizedKeysCommand $PublicPath Write-Info 'Ou, neste computador, com a senha do servidor uma vez:' Write-Host " ssh-copy-id -i $PublicPath user@ip" } function Copy-ServerKey([string]$PublicPath, [string]$Target, [string]$Label) { if (-not (Test-SshTarget $Target)) { Stop-Helper 'Informe user@ip. Exemplo: -Batch server-install 1 user@10.0.0.8' } Write-Info "Enviando a chave pública para $Target." & ssh-copy-id -i $PublicPath -o IdentitiesOnly=yes -o IdentityAgent=none $Target if ($LASTEXITCODE -ne 0) { Stop-Helper "Não foi possível instalar a chave em $Target." } Add-RecentServer $Target $Label Write-Ok "Chave pública instalada em $Target." } function Install-ServerKey([string]$Value, [bool]$BatchMode, [string]$Target) { $label = Resolve-Label $Value Assert-Tools $public = (Get-ServerKeyPath $label) + '.pub' if (-not (Test-ServerKeyPresent $label)) { Stop-Helper "Chave $(Get-LabelName $label) do servidor não existe neste computador. Escolha Criar ou Recuperar antes." } Write-ServerInstallHelp $public if ($BatchMode) { if (-not (Get-Command ssh-copy-id -ErrorAction SilentlyContinue)) { Write-Warn 'ssh-copy-id não encontrado. Use o comando acima no servidor.' return } Copy-ServerKey $public $Target $label return } while ($true) { Write-Host '' Write-MenuRow '1' 'Enviar' 'roda ssh-copy-id com a senha do servidor' Write-MenuRow '2' 'Voltar' 'deixa só o texto na tela' $choice = Read-ConsoleLine 'Número' if ($null -eq $choice) { $choice = '' } $choice = $choice.Trim().ToLowerInvariant() switch ($choice) { { $_ -in @('1', 'enviar') } { if (-not (Get-Command ssh-copy-id -ErrorAction SilentlyContinue)) { Write-Warn 'ssh-copy-id não encontrado. Use o comando acima no servidor.' return } $typed = Read-SshTarget Copy-ServerKey $public $typed $label return } { $_ -in @('2', 'voltar', 'q') } { return } default { if (Test-UseColor) { Write-Host 'Escolha um número da lista.' -ForegroundColor Yellow } else { Write-Host 'Escolha um número da lista.' } } } } } function Connect-Server([string]$Value, [bool]$BatchMode, [string]$Target) { $label = Resolve-Label $Value Assert-Tools $identity = Get-ServerKeyPath $label if (-not (Test-ServerKeyPresent $label)) { Stop-Helper "Chave $(Get-LabelName $label) do servidor não existe neste computador. Escolha Criar ou Recuperar antes." } $asked = $false if ([string]::IsNullOrEmpty($Target)) { if ($BatchMode) { Stop-Helper 'Informe user@ip. Exemplo: -Batch server-connect 1 user@10.0.0.8' } $Target = Read-SshTarget $asked = $true } if (-not (Test-SshTarget $Target)) { Stop-Helper 'Informe user@ip. Exemplo: -Batch server-connect 1 user@10.0.0.8' } if ($asked) { $ready = $false while (-not $ready) { Write-Host '' Write-MenuRow '1' 'Conectar' 'abre ssh agora' Write-MenuRow '2' 'Salvar favorito' 'grava o nome e conecta' Write-MenuRow '3' 'Voltar' 'não conecta' $choice = Read-ConsoleLine 'Número' if ($null -eq $choice) { $choice = '' } $choice = $choice.Trim().ToLowerInvariant() if ($choice -eq '1' -or $choice -eq 'conectar') { $ready = $true } elseif ($choice -eq '2' -or $choice -eq 'favorito' -or $choice -eq 'salvar') { $alias = Read-FavoriteAlias if ([string]::IsNullOrEmpty($alias)) { continue } Save-Favorite $alias $Target $label Write-Ok "Favorito $alias salvo." $ready = $true } elseif ($choice -eq '3' -or $choice -eq 'voltar' -or $choice -eq 'q') { return } elseif (Test-UseColor) { Write-Host 'Escolha um número da lista.' -ForegroundColor Yellow } else { Write-Host 'Escolha um número da lista.' } } } Write-Info "Conectando em $Target com a YubiKey $(Get-LabelName $label). O PIN e o toque são os pedidos do token." Write-Info 'Sem este script:' Write-Host " ssh -i $identity -o IdentitiesOnly=yes -o IdentityAgent=none -- $Target" & ssh -i $identity -o IdentitiesOnly=yes -o IdentityAgent=none -- $Target if ($LASTEXITCODE -ne 0) { if ($BatchMode) { exit $LASTEXITCODE } return } Add-RecentServer $Target $label } function Show-RecentServers { $rows = @(Get-RecentServers) if ($rows.Count -eq 0) { Write-Warn 'Nenhum servidor recente neste computador.' return } Write-Host '' Write-Host 'Servidores recentes' for ($i = 0; $i -lt $rows.Count; $i++) { $detail = Get-LabelName $rows[$i].Label if (-not [string]::IsNullOrEmpty($rows[$i].Name)) { $detail = $rows[$i].Name + ' ' + $detail } Write-MenuRow ([string]($i + 1)) $rows[$i].Target $detail } Write-MenuRow ([string]($rows.Count + 1)) 'Voltar' 'retorna ao menu' while ($true) { $choice = Read-ConsoleLine 'Número' if ($null -eq $choice) { $choice = '' } $choice = $choice.Trim().ToLowerInvariant() if ($choice -eq ([string]($rows.Count + 1)) -or $choice -eq 'voltar' -or $choice -eq 'q') { return } $number = 0 if ([int]::TryParse($choice, [ref]$number) -and $number -ge 1 -and $number -le $rows.Count) { $script:ServerName = $rows[$number - 1].Name Connect-Server $rows[$number - 1].Label $false $rows[$number - 1].Target return } if (Test-UseColor) { Write-Host 'Escolha um número da lista.' -ForegroundColor Yellow } else { Write-Host 'Escolha um número da lista.' } } } function Remove-FavoritePrompt { $rows = @(Get-FavoriteServers) if ($rows.Count -eq 0) { return } Write-Host '' Write-Host 'Qual favorito remover?' for ($i = 0; $i -lt $rows.Count; $i++) { Write-MenuRow ([string]($i + 1)) $rows[$i].Alias (Get-FavoriteDetail $rows[$i].Target $rows[$i].Label) } Write-MenuRow ([string]($rows.Count + 1)) 'Voltar' 'não apaga nada' while ($true) { $choice = Read-ConsoleLine 'Número' if ($null -eq $choice) { $choice = '' } $choice = $choice.Trim().ToLowerInvariant() if ($choice -eq ([string]($rows.Count + 1)) -or $choice -eq 'voltar' -or $choice -eq 'q') { return } $number = 0 if ([int]::TryParse($choice, [ref]$number) -and $number -ge 1 -and $number -le $rows.Count) { $kept = New-Object System.Collections.Generic.List[object] for ($i = 0; $i -lt $rows.Count; $i++) { if ($i -ne ($number - 1)) { $kept.Add($rows[$i]) | Out-Null } } Write-FavoriteRows $kept Write-Ok 'Favorito removido.' return } if (Test-UseColor) { Write-Host 'Escolha um número da lista.' -ForegroundColor Yellow } else { Write-Host 'Escolha um número da lista.' } } } function Show-Favorites { while ($true) { $rows = @(Get-FavoriteServers) if ($rows.Count -eq 0) { Write-Warn 'Nenhum favorito neste computador.' return } Write-Host '' Write-Host 'Favoritos' for ($i = 0; $i -lt $rows.Count; $i++) { Write-MenuRow ([string]($i + 1)) $rows[$i].Alias (Get-FavoriteDetail $rows[$i].Target $rows[$i].Label) } $remover = $rows.Count + 1 $voltar = $rows.Count + 2 Write-MenuRow ([string]$remover) 'Remover' 'apaga um favorito' Write-MenuRow ([string]$voltar) 'Voltar' 'retorna ao menu' $choice = Read-ConsoleLine 'Número' if ($null -eq $choice) { $choice = '' } $choice = $choice.Trim().ToLowerInvariant() if ($choice -eq ([string]$voltar) -or $choice -eq 'voltar' -or $choice -eq 'q') { return } if ($choice -eq ([string]$remover) -or $choice -eq 'remover') { Remove-FavoritePrompt continue } $number = 0 if ([int]::TryParse($choice, [ref]$number) -and $number -ge 1 -and $number -le $rows.Count) { $script:ServerName = $rows[$number - 1].Name Connect-Server $rows[$number - 1].Label $false $rows[$number - 1].Target return } if (Test-UseColor) { Write-Host 'Escolha um número da lista.' -ForegroundColor Yellow } else { Write-Host 'Escolha um número da lista.' } } } function Show-ServerPublicKeys { $present = @() foreach ($label in @('yuc', 'yua')) { if (Test-ServerKeyPresent $label) { $present += $label } } if ($present.Count -eq 0) { Write-Warn 'Nenhuma chave de servidor neste computador. Escolha Criar ou Recuperar antes.' return } Write-Info 'No servidor, cole o comando da chave. Ele grava a linha em ~/.ssh/authorized_keys:' foreach ($label in $present) { $port = 'USB-A' if ($label -eq 'yuc') { $port = 'USB-C' } $public = (Get-ServerKeyPath $label) + '.pub' Write-Host '' Write-Info "$(Get-LabelName $label) ($port)" Write-Host '' Write-Host (Get-AuthorizedKeysCommand $public) Write-Host '' } if ($present.Count -eq 1) { Copy-CommandText (Get-AuthorizedKeysCommand ((Get-ServerKeyPath $present[0]) + '.pub')) } } function Show-ServerPublicBatch([string]$Selector) { if ([string]::IsNullOrEmpty($Selector)) { $present = @() foreach ($label in @('yuc', 'yua')) { if (Test-ServerKeyPresent $label) { $present += $label } } if ($present.Count -eq 0) { Stop-Helper 'Nenhuma chave de servidor neste computador.' } Write-Info 'No servidor, cole o comando da chave. Ele grava a linha em ~/.ssh/authorized_keys:' foreach ($label in $present) { $port = 'USB-A' if ($label -eq 'yuc') { $port = 'USB-C' } Write-Host '' Write-Info "$(Get-LabelName $label) ($port)" Write-Host '' Write-Host (Get-AuthorizedKeysCommand ((Get-ServerKeyPath $label) + '.pub')) Write-Host '' } return } $label = Resolve-Label $Selector if (-not (Test-ServerKeyPresent $label)) { Stop-Helper "Chave $(Get-LabelName $label) do servidor não existe neste computador." } $port = 'USB-A' if ($label -eq 'yuc') { $port = 'USB-C' } $public = (Get-ServerKeyPath $label) + '.pub' Write-Info 'No servidor, cole este comando. Ele grava a chave em ~/.ssh/authorized_keys:' Write-Host '' Write-Info "$(Get-LabelName $label) ($port)" Write-Host '' Write-Host (Get-AuthorizedKeysCommand $public) Write-Host '' Copy-CommandText (Get-AuthorizedKeysCommand $public) } function Show-ServerHelp { Write-Host '' if (Test-UseColor) { Write-Host 'Servidor' -ForegroundColor Cyan } else { Write-Host 'Servidor' } Write-Host 'A chave fica dentro da YubiKey. O arquivo local só aponta para ela.' Write-Host 'O nome separa as credenciais. Sem nome usa server-yuc e server-yua.' Write-Host '1. Crie a credencial residente no token.' Write-Host '2. Ou recupere a credencial, se ela já estiver no token.' Write-Host '3. Cole no servidor o comando que o script mostra para o authorized_keys.' Write-Host '4. Conecte com user@ip. O token pede PIN e toque.' Write-Host 'No Conectar, Salvar favorito grava um nome para esse user@ip.' Write-Host 'O menu inicial mostra os favoritos e as 6 últimas conexões. Um número conecta.' Write-Host 'Sem este script, o comando é o que Conectar imprime. A forma é:' Write-Host ' ssh -i ARQUIVO -o IdentitiesOnly=yes -o IdentityAgent=none -- user@ip' Write-Host 'Desfazer apaga só esses arquivos, não as chaves do GitHub.' } function Invoke-ServerUndo { $removed = $false $paths = @(Get-ServerOwnedPaths) foreach ($path in $paths) { if (-not (Test-Path -LiteralPath $path)) { continue } if (Test-OwnedLink $path) { Write-Warn "Atalho ignorado: $path" continue } $item = Get-Item -LiteralPath $path -Force if ($item.PSIsContainer) { continue } Remove-Item -LiteralPath $path -Force Write-Ok "Removido: $path" $removed = $true } if (-not $removed) { Write-Warn 'Nada do helper de servidor foi encontrado. O SSH não foi alterado.' } } function Invoke-ServerUndoInteractive { $paths = @(Get-ServerOwnedPaths) $found = @() foreach ($path in $paths) { if ((Test-Path -LiteralPath $path) -and -not (Test-OwnedLink $path)) { $item = Get-Item -LiteralPath $path -Force if (-not $item.PSIsContainer) { $found += $path } } } if ($found.Count -eq 0) { Write-Warn 'Nada do helper de servidor foi encontrado. O SSH não foi alterado.' return } Write-Host '' Write-Host 'Isto será removido:' foreach ($path in $found) { Write-Host " $path" } while ($true) { Write-Host '' Write-MenuRow '1' 'Confirmar' 'apaga só as chaves de servidor' Write-MenuRow '2' 'Voltar' 'não altera nada' $choice = Read-ConsoleLine 'Número' if ($null -eq $choice) { $choice = '' } $choice = $choice.Trim().ToLowerInvariant() switch ($choice) { { $_ -in @('1', 'confirmar') } { Invoke-ServerUndo; return } { $_ -in @('2', 'voltar', 'q') } { Write-Info 'Nada foi alterado.'; return } default { if (Test-UseColor) { Write-Host 'Escolha um número da lista.' -ForegroundColor Yellow } else { Write-Host 'Escolha um número da lista.' } } } } } function Read-ServerName { while ($true) { $names = @(Get-ServerNames) $slots = New-Object System.Collections.Generic.List[string] Write-Host '' Write-Host 'Qual nome?' [void]$slots.Add('') Write-MenuRow ([string]$slots.Count) 'sem nome' 'chaves server-yuc e server-yua' foreach ($name in $names) { [void]$slots.Add($name) Write-MenuRow ([string]$slots.Count) $name 'credencial de servidor' } $nova = $slots.Count + 1 $voltar = $slots.Count + 2 Write-MenuRow ([string]$nova) 'Nova' 'grava um nome novo' Write-MenuRow ([string]$voltar) 'Voltar' 'retorna ao menu' $choice = Read-ConsoleLine 'Número' if ($null -eq $choice) { $choice = '' } $choice = $choice.Trim().ToLowerInvariant() if ($choice -eq ([string]$voltar) -or $choice -eq 'voltar' -or $choice -eq 'q') { return $null } foreach ($slot in $slots) { if (-not [string]::IsNullOrEmpty($slot) -and $choice -eq $slot) { return $slot } } if ($choice -eq ([string]$nova) -or $choice -eq 'nova') { $typed = Read-ConsoleLine 'Nome' if ($null -eq $typed) { $typed = '' } $typed = $typed.Trim().ToLowerInvariant() if (-not (Test-AccountName $typed)) { if (Test-UseColor) { Write-Host 'Use letras minúsculas, números e hífen. Exemplo: casa' -ForegroundColor Yellow } else { Write-Host 'Use letras minúsculas, números e hífen. Exemplo: casa' } continue } $script:ServerName = $typed Save-ServerName return $typed } $number = 0 if ([int]::TryParse($choice, [ref]$number) -and $number -ge 1 -and $number -le $slots.Count) { return $slots[$number - 1] } if (Test-UseColor) { Write-Host 'Escolha um número da lista.' -ForegroundColor Yellow } else { Write-Host 'Escolha um número da lista.' } } } function Enter-ServerAction([string]$Action) { $name = Read-ServerName if ($null -eq $name) { return } $script:ServerName = $name if ($Action -eq 'pub') { Show-ServerPublicKeys return } $label = Read-Label if (-not $label) { return } switch ($Action) { 'create' { New-ServerKey $label $false } 'add' { Add-ServerResidentKey $label } 'install' { Install-ServerKey $label $false '' } 'connect' { Connect-Server $label $false '' } } } function Invoke-ServerMenu { while ($true) { Write-Host '' if (Test-UseColor) { Write-Host 'Servidor' -ForegroundColor Cyan } else { Write-Host 'Servidor' } Write-Host '' Write-MenuRow '1' 'Criar' 'grava a credencial residente no token' Write-MenuRow '2' 'Recuperar' 'lê a chave do token conectado agora' Write-MenuRow '3' 'Instalar' 'envia a chave pública para o servidor' Write-MenuRow '4' 'Conectar' 'abre ssh em user@ip com essa chave' Write-MenuRow '5' 'Recentes' 'entra de novo em um servidor já usado' Write-MenuRow '6' 'Favoritos' 'conecta ou remove um user@ip salvo' Write-MenuRow '7' 'Públicas' 'mostra o comando para o authorized_keys' Write-MenuRow '8' 'Ajuda' 'explica criar, instalar e conectar' Write-MenuRow '9' 'Desfazer' 'remove só as chaves de servidor deste computador' Write-MenuRow '10' 'Voltar' 'retorna ao menu inicial' $choice = Read-ConsoleLine 'Número' if ($null -eq $choice) { $choice = '' } $choice = $choice.Trim().ToLowerInvariant() switch ($choice) { { $_ -in @('1', 'criar', 'create') } { Enter-ServerAction 'create' } { $_ -in @('2', 'recuperar', 'add') } { Enter-ServerAction 'add' } { $_ -in @('3', 'instalar', 'install') } { Enter-ServerAction 'install' } { $_ -in @('4', 'conectar', 'connect') } { Enter-ServerAction 'connect' } { $_ -in @('5', 'recentes') } { Show-RecentServers } { $_ -in @('6', 'favoritos') } { Show-Favorites } { $_ -in @('7', 'publicas', 'pub') } { Enter-ServerAction 'pub' } { $_ -in @('8', 'ajuda', 'help', '?') } { Show-ServerHelp } { $_ -in @('9', 'desfazer', 'undo') } { Invoke-ServerUndoInteractive } { $_ -in @('10', 'voltar', 'q') } { return } default { if (Test-UseColor) { Write-Host 'Escolha um número da lista.' -ForegroundColor Yellow } else { Write-Host 'Escolha um número da lista.' } } } } } function Invoke-Interactive { if (-not (Test-InteractiveConsole)) { Stop-Helper 'Terminal interativo não encontrado. Use -Batch para executar sem perguntas.' } while ($true) { Write-Host '' if (Test-UseColor) { Write-Host 'fido' -ForegroundColor Cyan } else { Write-Host 'fido' } Write-Host '' Write-MenuRow '1' 'GitHub' 'alterna as YubiKeys na conta do GitHub' Write-MenuRow '2' 'Servidor' 'entra em um servidor com a YubiKey' $shortcuts = @(Get-HomeShortcuts) $n = 2 for ($i = 0; $i -lt $shortcuts.Count; $i++) { $n++ Write-MenuRow ([string]$n) $shortcuts[$i].Title $shortcuts[$i].Detail } $sair = $n + 1 Write-MenuRow ([string]$sair) 'Sair' 'encerra' $choice = Read-ConsoleLine 'Número' if ($null -eq $choice) { $choice = '' } $choice = $choice.Trim().ToLowerInvariant() if ($choice -eq '1' -or $choice -eq 'github') { Invoke-GithubMenu continue } if ($choice -eq '2' -or $choice -eq 'servidor' -or $choice -eq 'ssh') { Invoke-ServerMenu continue } if ($choice -eq 'q' -or $choice -eq 'sair' -or $choice -eq ([string]$sair)) { return } $number = 0 if ([int]::TryParse($choice, [ref]$number) -and $number -ge 3 -and $number -lt $sair) { $item = $shortcuts[$number - 3] $script:ServerName = $item.Name Connect-Server $item.Label $false $item.Target continue } if (Test-UseColor) { Write-Host 'Escolha um número da lista.' -ForegroundColor Yellow } else { Write-Host 'Escolha um número da lista.' } } } function Resolve-GithubInvocation([string[]]$CommandArgs) { $script:Account = '' $parsed = @{ Label = ''; Serial = '' } $first = '' if ($null -ne $CommandArgs -and $CommandArgs.Count -ge 2) { $first = $CommandArgs[1] } if ([string]::IsNullOrEmpty($first)) { Stop-Helper 'Informe a YubiKey ou o nome da conta. Exemplo: -Batch create trabalho 1' } if (Test-KeyLabel $first) { $parsed.Label = $first if ($CommandArgs.Count -ge 3) { $parsed.Serial = $CommandArgs[2] } return ,$parsed } Set-Account $first $second = '' if ($CommandArgs.Count -ge 3) { $second = $CommandArgs[2] } if (-not (Test-KeyLabel $second)) { Stop-Helper "Informe a YubiKey depois do nome. Exemplo: -Batch create $($script:Account) 1" } $parsed.Label = $second if ($CommandArgs.Count -ge 4) { $parsed.Serial = $CommandArgs[3] } return ,$parsed } function Resolve-PublicInvocation([string[]]$CommandArgs) { $script:Account = '' $parsed = @{ Label = '' } $first = '' if ($null -ne $CommandArgs -and $CommandArgs.Count -ge 2) { $first = $CommandArgs[1] } if ([string]::IsNullOrEmpty($first)) { return ,$parsed } if (Test-KeyLabel $first) { $parsed.Label = $first return ,$parsed } Set-Account $first if ($CommandArgs.Count -ge 3 -and -not [string]::IsNullOrEmpty($CommandArgs[2])) { if (-not (Test-KeyLabel $CommandArgs[2])) { Stop-Helper "Informe a YubiKey depois do nome. Exemplo: -Batch pub $($script:Account) 1" } $parsed.Label = $CommandArgs[2] } return ,$parsed } function Resolve-ServerInvocation([string[]]$CommandArgs, [bool]$RequireLabel) { $script:ServerName = '' $parsed = @{ Label = ''; Serial = ''; Target = '' } $first = '' if ($null -ne $CommandArgs -and $CommandArgs.Count -ge 2) { $first = $CommandArgs[1] } if ([string]::IsNullOrEmpty($first)) { if ($RequireLabel) { Stop-Helper 'Informe a YubiKey ou o nome. Exemplo: -Batch server-create casa 1' } return ,$parsed } if (Test-KeyLabel $first) { $parsed.Label = $first $second = '' if ($CommandArgs.Count -ge 3) { $second = $CommandArgs[2] } if (Test-SshTarget $second) { $parsed.Target = $second } else { $parsed.Serial = $second } return ,$parsed } Set-ServerName $first $second = '' if ($CommandArgs.Count -ge 3) { $second = $CommandArgs[2] } if ([string]::IsNullOrEmpty($second)) { if ($RequireLabel) { Stop-Helper "Informe a YubiKey depois do nome. Exemplo: -Batch server-create $($script:ServerName) 1" } return ,$parsed } if (-not (Test-KeyLabel $second)) { Stop-Helper "Informe a YubiKey depois do nome. Exemplo: -Batch server-create $($script:ServerName) 1" } $parsed.Label = $second $third = '' if ($CommandArgs.Count -ge 4) { $third = $CommandArgs[3] } if (Test-SshTarget $third) { $parsed.Target = $third } else { $parsed.Serial = $third } return ,$parsed } function Invoke-Batch([string[]]$CommandArgs) { if ($null -eq $CommandArgs -or $CommandArgs.Count -lt 1 -or [string]::IsNullOrEmpty($CommandArgs[0])) { Stop-Helper 'No modo -Batch informe o comando. Exemplo: -Batch add 1' } $command = $CommandArgs[0] $label = '' if ($CommandArgs.Count -ge 2) { $label = $CommandArgs[1] } switch ($command) { 'create' { $parsed = Resolve-GithubInvocation $CommandArgs New-ResidentKey $parsed.Label $true $parsed.Serial } 'add' { $parsed = Resolve-GithubInvocation $CommandArgs Add-ResidentKey $parsed.Label } 'use' { $parsed = Resolve-GithubInvocation $CommandArgs Use-ResidentKey $parsed.Label } 'test' { if (-not (Test-Github)) { Stop-Helper 'O teste com o GitHub não autenticou.' } } 'pub' { $parsed = Resolve-PublicInvocation $CommandArgs Show-PublicKeysBatch $parsed.Label } 'status' { Show-Status } 'list' { Show-List } 'undo' { Invoke-Undo } 'server-create' { $parsed = Resolve-ServerInvocation $CommandArgs $true New-ServerKey $parsed.Label $true $parsed.Serial } 'server-add' { $parsed = Resolve-ServerInvocation $CommandArgs $true Add-ServerResidentKey $parsed.Label } 'server-install' { $parsed = Resolve-ServerInvocation $CommandArgs $true Install-ServerKey $parsed.Label $true $parsed.Target } 'server-connect' { $parsed = Resolve-ServerInvocation $CommandArgs $true Connect-Server $parsed.Label $true $parsed.Target } 'server-pub' { $parsed = Resolve-ServerInvocation $CommandArgs $false Show-ServerPublicBatch $parsed.Label } 'server-undo' { Invoke-ServerUndo } { $_ -in @('help', '-h', '--help') } { Show-Usage } default { Show-Usage Stop-Helper "Comando desconhecido: $command" } } } function Migrate-LegacyNames { if ((Test-Path -LiteralPath $LegacyConfigFile) -and -not (Test-Path -LiteralPath $ConfigFile) -and -not (Test-OwnedLink $LegacyConfigFile)) { Move-Item -LiteralPath $LegacyConfigFile -Destination $ConfigFile } if ((Test-Path -LiteralPath $LegacyServerHosts) -and -not (Test-Path -LiteralPath $ServerHosts) -and -not (Test-OwnedLink $LegacyServerHosts)) { Move-Item -LiteralPath $LegacyServerHosts -Destination $ServerHosts } if (-not (Test-Path -LiteralPath $MainConfig)) { return } if (Test-OwnedLink $MainConfig) { return } $text = [System.IO.File]::ReadAllText($MainConfig) $hasLegacy = $false foreach ($line in ($text -split "`r`n|`n")) { if ((Get-ConfigLine $line) -eq $LegacyIncludeLine) { $hasLegacy = $true; break } } if (-not $hasLegacy) { return } $hasNew = $false foreach ($line in ($text -split "`r`n|`n")) { if ((Get-ConfigLine $line) -eq $IncludeLine) { $hasNew = $true; break } } $newline = "`n" if ($text -match "`r`n") { $newline = "`r`n" } $kept = New-Object System.Collections.Generic.List[string] $wroteNew = $false foreach ($line in ($text -split "`r`n|`n")) { if ((Get-ConfigLine $line) -eq $LegacyIncludeLine) { if (-not $hasNew -and -not $wroteNew) { $kept.Add($IncludeLine) | Out-Null $wroteNew = $true } continue } $kept.Add((Get-ConfigLine $line)) | Out-Null } $body = [string]::Join($newline, $kept.ToArray()) [System.IO.File]::WriteAllText($MainConfig, $body, $Utf8) } Migrate-LegacyNames if (-not $Batch -and $args.Count -eq 1 -and $args[0] -in @('help', '-h', '--help')) { Show-Usage } elseif (-not $Batch) { if ($args.Count -gt 0) { Stop-Helper 'Este helper pergunta no terminal. Para um comando direto, use -Batch. Exemplo: -Batch add 1' } Invoke-Interactive } else { Invoke-Batch -CommandArgs ([string[]]@($args)) }