ssh-agent: unlock once, use all day

SSH · Practical · 9 min

Passphrase-protected keys are only practical with an agent, and Git over SSH depends on it.

A passphrase-protected private key must be decrypted before use. ssh-agent is a small background process that keeps decrypted keys in memory and performs signatures on behalf of ssh, so the key material never has to be re-read and you type the passphrase once.

Most desktops already run an agent (macOS launchd, GNOME Keyring, Windows' OpenSSH Authentication Agent service). Check with ssh-add -l: "The agent has no identities" means it is running but empty; "Could not open a connection" means none is running, so start one with eval "$(ssh-agent -s)".

  • ssh-add adds default keys, ssh-add ~/.ssh/work_ed25519 a specific one.
  • ssh-add -t 8h key keeps it only for eight hours; ssh-add -D removes all keys.
  • AddKeysToAgent yes in ~/.ssh/config adds a key automatically the first time you use it.
  • On macOS, UseKeychain yes stores the passphrase in the Keychain.

The client finds the agent through the SSH_AUTH_SOCK environment variable, which points at a Unix socket. If ssh keeps asking for the passphrase, that variable is usually missing or stale (a common situation inside tmux or after sudo).

Anyone who can access your agent socket can use your keys while they are loaded, which is why agent forwarding (-A) to untrusted servers is risky; the jump hosts lesson shows the safer alternative.

Example

ssh-add -l                     # list loaded keys (or: no identities)
eval "$(ssh-agent -s)"         # start an agent if none is running
ssh-add ~/.ssh/id_ed25519      # asks for the passphrase once
ssh-add -t 8h ~/.ssh/work_ed25519
echo "$SSH_AUTH_SOCK"          # /tmp/ssh-XXXX/agent.1234
ssh-add -D                     # forget all keys

# ~/.ssh/config
# Host *
#   AddKeysToAgent yes
#   UseKeychain yes            # macOS only

Remember

  • The agent signs with decrypted keys so you enter the passphrase once
  • ssh-add -l / ssh-add key / ssh-add -D
  • SSH_AUTH_SOCK tells clients where the agent is

Watch out for

  • Running eval $(ssh-agent) in every shell, starting dozens of agents; reuse the desktop's agent.

Check yourself

  1. ssh keeps asking for your key's passphrase even though you ran ssh-add earlier in another terminal. Most likely?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: man.openbsd.org/ssh-agent