Lists keys in ~/.ssh, generates regular and FIDO2 (YubiKey) keys, imports resident keys, manages ssh-agent, copies/installs public keys. Passphrases and PINs are handled by ssh-keygen in the handed-over terminal. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
141 lines
4.1 KiB
Go
141 lines
4.1 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/base64"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"sort"
|
|
"strings"
|
|
)
|
|
|
|
// Key is one public key in the ssh dir, plus its private half if present.
|
|
type Key struct {
|
|
Name string
|
|
Path string // private key path
|
|
PubPath string
|
|
HasPrivate bool
|
|
Bits string
|
|
Fingerprint string
|
|
Comment string
|
|
Type string // e.g. ED25519, RSA, ED25519-SK
|
|
InAgent bool
|
|
}
|
|
|
|
func (k Key) Hardware() bool { return strings.HasSuffix(k.Type, "-SK") }
|
|
|
|
func sshDir() string {
|
|
if d := os.Getenv("YSM_SSH_DIR"); d != "" {
|
|
return d
|
|
}
|
|
home, _ := os.UserHomeDir()
|
|
return filepath.Join(home, ".ssh")
|
|
}
|
|
|
|
// parseFingerprint parses `ssh-keygen -l` / `ssh-add -l` lines:
|
|
// "256 SHA256:abc user@host (ED25519)".
|
|
func parseFingerprint(line string) (bits, fp, comment, typ string, ok bool) {
|
|
f := strings.Fields(line)
|
|
if len(f) < 3 {
|
|
return "", "", "", "", false
|
|
}
|
|
return f[0], f[1], strings.Join(f[2:len(f)-1], " "), strings.Trim(f[len(f)-1], "()"), true
|
|
}
|
|
|
|
func agentFingerprints() map[string]bool {
|
|
out, _ := exec.Command("ssh-add", "-l").Output() // exits 1 when agent is empty
|
|
m := map[string]bool{}
|
|
for _, l := range strings.Split(string(out), "\n") {
|
|
if _, fp, _, _, ok := parseFingerprint(l); ok {
|
|
m[fp] = true
|
|
}
|
|
}
|
|
return m
|
|
}
|
|
|
|
func loadKeys(dir string) ([]Key, error) {
|
|
pubs, err := filepath.Glob(filepath.Join(dir, "*.pub"))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
agent := agentFingerprints()
|
|
var keys []Key
|
|
for _, pub := range pubs {
|
|
out, err := exec.Command("ssh-keygen", "-l", "-f", pub).Output()
|
|
if err != nil {
|
|
continue // not a key file
|
|
}
|
|
bits, fp, comment, typ, ok := parseFingerprint(strings.TrimSpace(string(out)))
|
|
if !ok {
|
|
continue
|
|
}
|
|
priv := strings.TrimSuffix(pub, ".pub")
|
|
_, perr := os.Stat(priv)
|
|
keys = append(keys, Key{
|
|
Name: filepath.Base(priv), Path: priv, PubPath: pub, HasPrivate: perr == nil,
|
|
Bits: bits, Fingerprint: fp, Comment: comment, Type: typ, InAgent: agent[fp],
|
|
})
|
|
}
|
|
sort.Slice(keys, func(i, j int) bool { return keys[i].Name < keys[j].Name })
|
|
return keys, nil
|
|
}
|
|
|
|
func validateName(dir, name string) error {
|
|
if name == "" || name != filepath.Base(name) || strings.HasPrefix(name, ".") {
|
|
return errors.New("name must be a plain file name")
|
|
}
|
|
if strings.HasSuffix(name, ".pub") {
|
|
return errors.New("name must not end in .pub")
|
|
}
|
|
for _, p := range []string{name, name + ".pub"} {
|
|
if _, err := os.Stat(filepath.Join(dir, p)); err == nil {
|
|
return fmt.Errorf("%s already exists", p)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// yubikeyStatus returns a description of the first attached YubiKey, or "".
|
|
func yubikeyStatus() string {
|
|
if _, err := exec.LookPath("ykman"); err == nil {
|
|
out, _ := exec.Command("ykman", "list").Output()
|
|
return strings.TrimSpace(strings.SplitN(string(out), "\n", 2)[0])
|
|
}
|
|
out, _ := exec.Command("lsusb").Output()
|
|
for _, l := range strings.Split(string(out), "\n") {
|
|
if strings.Contains(strings.ToLower(l), "yubico") {
|
|
return "YubiKey (" + strings.TrimSpace(l[strings.Index(l, "ID "):]) + ")"
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// interactive wraps a command so its output stays visible when it fails;
|
|
// the TUI hands the terminal over so ssh-keygen can prompt for passphrase/PIN/touch.
|
|
func interactive(dir, name string, args ...string) *exec.Cmd {
|
|
script := `"$@" || { s=$?; printf '\nPress Enter to return to ysm…'; read _; exit $s; }`
|
|
c := exec.Command("sh", append([]string{"-c", script, "sh", name}, args...)...)
|
|
c.Dir = dir
|
|
// The terminal is ours to hand over, so prompt there instead of in a GUI askpass popup.
|
|
c.Env = append(os.Environ(), "SSH_ASKPASS_REQUIRE=never")
|
|
return c
|
|
}
|
|
|
|
func copyToClipboard(text string) string {
|
|
for _, c := range [][]string{{"wl-copy"}, {"xclip", "-selection", "clipboard"}, {"xsel", "-ib"}, {"pbcopy"}} {
|
|
if _, err := exec.LookPath(c[0]); err != nil {
|
|
continue
|
|
}
|
|
cmd := exec.Command(c[0], c[1:]...)
|
|
cmd.Stdin = strings.NewReader(text)
|
|
if cmd.Run() == nil {
|
|
return c[0]
|
|
}
|
|
}
|
|
// OSC 52: asks the terminal itself to set the clipboard (works over ssh too).
|
|
fmt.Fprintf(os.Stdout, "\x1b]52;c;%s\a", base64.StdEncoding.EncodeToString([]byte(text)))
|
|
return "terminal (OSC 52)"
|
|
}
|