diff --git a/README.md b/README.md index ce1e386..0ef6ff9 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ For YubiKey detection it uses `ykman` if installed, otherwise `lsusb`. | `n` | new key (ed25519 / rsa-4096 / ecdsa) | | `y` | new key on the YubiKey (ed25519-sk / ecdsa-sk, resident, PIN-per-use) | | `i` | import resident keys from the YubiKey (`ssh-keygen -K`) | -| `a` / `x` | add to / remove from ssh-agent | +| `a` / `x` | add to / remove from ssh-agent (`a` starts an agent if none is running) | | `c` | copy public key (wl-copy, xclip, xsel, pbcopy, or OSC 52) | | `s` | install the public key on a server (`ssh-copy-id`) | | `p` | change passphrase | @@ -23,3 +23,7 @@ For YubiKey detection it uses `ykman` if installed, otherwise `lsusb`. Passphrases, PINs and touch are handled by `ssh-keygen` itself. ysm hands it the terminal, so secrets never pass through the app. The YubiKey is polled every 2s, so plugging it in or removing it shows up in the header. + +If no ssh-agent is running, `a` starts one on `$XDG_RUNTIME_DIR/ysm-agent.sock`. +It keeps running after you quit, and later ysm runs reuse it. To use it from your +shell, run the `export SSH_AUTH_SOCK=…` line shown in the header. diff --git a/keys.go b/keys.go index dce57cc..9cca8c4 100644 --- a/keys.go +++ b/keys.go @@ -7,6 +7,7 @@ import ( "os" "os/exec" "path/filepath" + "regexp" "sort" "strings" ) @@ -55,6 +56,63 @@ func agentFingerprints() map[string]bool { return m } +// agentRunning reports whether SSH_AUTH_SOCK points at a live agent +// (ssh-add -l exits 1 for an empty agent, 2 when it can't connect). +func agentRunning() bool { + err := exec.Command("ssh-add", "-l").Run() + var ee *exec.ExitError + return err == nil || errors.As(err, &ee) && ee.ExitCode() == 1 +} + +// agentSocket is where ysm starts its own agent, so later runs can find it again. +func agentSocket() string { + dir := os.Getenv("XDG_RUNTIME_DIR") + if dir == "" { + dir = sshDir() + } + return filepath.Join(dir, "ysm-agent.sock") +} + +// connectAgent uses the current agent, or falls back to ysm's own if it is alive. +func connectAgent() bool { + if agentRunning() { + return true + } + old, had := os.LookupEnv("SSH_AUTH_SOCK") + os.Setenv("SSH_AUTH_SOCK", agentSocket()) + if agentRunning() { + return true + } + if had { + os.Setenv("SSH_AUTH_SOCK", old) + } else { + os.Unsetenv("SSH_AUTH_SOCK") + } + return false +} + +// ensureAgent connects to an agent, starting ysm's own one if none is running. +func ensureAgent() (started bool, err error) { + if connectAgent() { + return false, nil + } + sock := agentSocket() + os.Remove(sock) // stale socket left by a dead agent; connectAgent proved nothing listens + out, err := exec.Command("ssh-agent", "-s", "-a", sock).Output() + if err != nil { + var ee *exec.ExitError + if errors.As(err, &ee) && len(ee.Stderr) > 0 { + err = errors.New(strings.TrimSpace(string(ee.Stderr))) + } + return false, fmt.Errorf("start ssh-agent: %w", err) + } + os.Setenv("SSH_AUTH_SOCK", sock) + if m := regexp.MustCompile(`SSH_AGENT_PID=(\d+)`).FindSubmatch(out); m != nil { + os.Setenv("SSH_AGENT_PID", string(m[1])) + } + return true, nil +} + func loadKeys(dir string) ([]Key, error) { pubs, err := filepath.Glob(filepath.Join(dir, "*.pub")) if err != nil { diff --git a/keys_test.go b/keys_test.go index e16f3a6..ad88e3d 100644 --- a/keys_test.go +++ b/keys_test.go @@ -40,3 +40,25 @@ func TestLoadKeysAndValidate(t *testing.T) { } } } + +func TestEnsureAgent(t *testing.T) { + t.Setenv("XDG_RUNTIME_DIR", t.TempDir()) + t.Setenv("SSH_AUTH_SOCK", "/nonexistent/agent.sock") + t.Setenv("SSH_AGENT_PID", "") + + started, err := ensureAgent() + if err != nil || !started || !agentRunning() { + t.Fatalf("started=%v err=%v running=%v", started, err, agentRunning()) + } + pid := os.Getenv("SSH_AGENT_PID") + defer exec.Command("kill", pid).Run() + + if started, err := ensureAgent(); err != nil || started { + t.Fatalf("second call started=%v err=%v", started, err) + } + // A new ysm run without SSH_AUTH_SOCK finds the agent it started before. + os.Unsetenv("SSH_AUTH_SOCK") + if !connectAgent() || os.Getenv("SSH_AUTH_SOCK") != agentSocket() { + t.Fatal("did not reconnect to ysm's agent") + } +} diff --git a/main.go b/main.go index 1f5a7f3..5d008c3 100644 --- a/main.go +++ b/main.go @@ -40,8 +40,14 @@ const ( type ( keysMsg struct { - keys []Key - err error + keys []Key + agent bool + err error + } + agentMsg struct { + started bool + err error + key Key } ykMsg string tickMsg struct{} @@ -106,6 +112,7 @@ type model struct { form *form detail string yubikey string + agent bool busy bool // an external command owns the terminal / YubiKey status string statusB bool // status is an error @@ -122,7 +129,7 @@ func defaultComment() string { } func (m model) loadCmd() tea.Cmd { - return func() tea.Msg { k, err := loadKeys(m.dir); return keysMsg{k, err} } + return func() tea.Msg { k, err := loadKeys(m.dir); return keysMsg{k, agentRunning(), err} } } func ykCmd() tea.Msg { return ykMsg(yubikeyStatus()) } @@ -154,7 +161,7 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { if msg.err != nil { m.setStatus(msg.err.Error(), true) } - m.keys = msg.keys + m.keys, m.agent = msg.keys, msg.agent m.cursor = min(m.cursor, max(len(m.keys)-1, 0)) case tickMsg: if m.busy { // don't poke the YubiKey while ssh-keygen waits for touch @@ -169,6 +176,17 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { } else if was != "" && m.yubikey == "" { m.setStatus("YubiKey removed", false) } + case agentMsg: + if msg.err != nil { + m.setStatus("✗ "+msg.err.Error(), true) + return m, nil + } + m.agent = true + what := "add " + msg.key.Name + " to agent" + if msg.started { + what = "start ssh-agent and " + what + } + return m, m.run(what, interactive(m.dir, "ssh-add", msg.key.Path)) case detailMsg: m.detail, m.mode = string(msg), detailMode case execMsg: @@ -289,7 +307,8 @@ func (m model) updateList(msg tea.KeyMsg) (tea.Model, tea.Cmd) { return m, m.run("import keys from YubiKey", interactive(m.dir, "ssh-keygen", "-K")) case "a": if needPriv() { - return m, m.run("add "+k.Name+" to agent", interactive(m.dir, "ssh-add", k.Path)) + key := *k + return m, func() tea.Msg { started, err := ensureAgent(); return agentMsg{started, err, key} } } case "x": if needKey() { @@ -412,7 +431,15 @@ func (m model) View() string { if m.yubikey != "" { yk = goodSt.Render("● " + m.yubikey) } - b.WriteString(titleSt.Render("🔑 ysm") + mutedSt.Render(" — SSH keys in "+m.dir) + " " + yk + "\n\n") + agent := badSt.Render("○ no ssh-agent") + mutedSt.Render(" (a starts one)") + if m.agent { + agent = goodSt.Render("● ssh-agent") + if sock := os.Getenv("SSH_AUTH_SOCK"); sock == agentSocket() { + // ysm's own agent: the user's shell needs this to use it. + agent += mutedSt.Render(" export SSH_AUTH_SOCK=" + sock) + } + } + b.WriteString(titleSt.Render("🔑 ysm") + mutedSt.Render(" — SSH keys in "+m.dir) + " " + yk + "\n" + agent + "\n\n") switch m.mode { case detailMode: @@ -541,6 +568,7 @@ func main() { fmt.Fprintln(os.Stderr, err) os.Exit(1) } + connectAgent() if _, err := tea.NewProgram(model{dir: dir}, tea.WithAltScreen()).Run(); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1)