Sub topic 9
Using ssh-agent to avoid retyping your passphrase
What you need before starting
This chapter assumes you have already done the following:
- Generated an Ed25519 key pair with
ssh-keygenand protected the private key with a passphrase. - Installed the public key on a server and logged in with it at least once.
- Used a Linux or macOS shell comfortably, including environment variables and shell startup files.
If your key has no passphrase, you do not need an agent. You also have a weaker setup, because anyone who copies the private key file can use it.
The problem the agent solves
A passphrase encrypts your private key file on disk. That is good protection, but ssh must decrypt the key every time it signs a login challenge. Without help, you type the passphrase on every ssh, scp, rsync or git push over SSH.
ssh-agent is a small background program that holds decrypted private keys in memory. You unlock a key once with ssh-add. After that, ssh asks the agent to sign challenges for it. The agent never hands the private key to ssh. It only returns signatures.
This keeps the passphrase benefit (the file on disk stays encrypted) and removes the repeated typing.
How the pieces talk to each other
The agent listens on a Unix domain socket, which is a special file that programs use to talk to each other on the same machine. The environment variable SSH_AUTH_SOCK holds the path to that socket. Any ssh process that inherits this variable can find the agent.
Two consequences follow from this design:
- The decrypted key lives only in the agent's memory. It is not written back to disk.
- Anyone who can reach the agent's socket as your user (or as root) can ask it to sign. The socket's file permissions are the protection, so treat the agent as a sensitive resource.
Starting an agent and adding a key
Start an agent for the current shell and load your key:
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_ed25519The first command starts the agent and prints shell commands that set SSH_AUTH_SOCK and SSH_AGENT_PID. The eval runs those commands in your current shell. If you run ssh-agent without eval, the agent starts but your shell never learns where it is, so ssh-add fails with "Could not open a connection to your authentication agent."
ssh-add prompts for the passphrase and then prints Identity added. Check what the agent holds:
ssh-add -lThe output lists each key's size, fingerprint, comment and type. If the agent is running but empty, you see The agent has no identities. If no agent is reachable, you get an error and exit status 2.
To compare a listed fingerprint against a file on disk:
ssh-keygen -lf ~/.ssh/id_ed25519.pubChecking that the agent is used
Log in with verbose output and look for the agent offering your key:
ssh -v [email protected]You should see a line similar to Offering public key: /home/alice/.ssh/id_ed25519 ED25519 SHA256:... agent. The word agent at the end tells you the key came from the agent, not from a file prompt. You should not be asked for a passphrase.
Removing keys and stopping the agent
Remove one key from the agent, or all of them:
ssh-add -d ~/.ssh/id_ed25519
ssh-add -DStop the agent you started with eval:
ssh-agent -kThe -k option uses SSH_AGENT_PID to kill the agent and prints commands that unset the two variables. Closing a terminal does not stop an agent that was started with eval. Repeated manual starts can leave several idle agents running, which is a common source of confusion.
Limiting how long keys stay loaded
Keeping a key in memory indefinitely is a convenience that carries risk. You can set a lifetime in seconds:
ssh-add -t 3600 ~/.ssh/id_ed25519After one hour the agent forgets the key and you must run ssh-add again. You can also set a default for every key added to an agent by starting it with ssh-agent -t 3600.
A related option, -c, requires confirmation each time the key is used. It needs a working askpass helper (a small program that shows a confirmation prompt), so it is mostly useful on desktops.
| Option | Effect | Typical use |
|---|---|---|
| `ssh-add -l` | List loaded keys | Check agent state |
| `ssh-add -d key` | Remove one key | Stop using a key now |
| `ssh-add -D` | Remove all keys | Leaving a shared machine |
| `ssh-add -t secs` | Expire the key after a time | Reduce exposure window |
| `ssh-add -c key` | Confirm each use | Desktop use with a prompt helper |
Making the agent start automatically
Typing eval "$(ssh-agent -s)" in every terminal creates a new agent each time. Better setups reuse one agent. Which one you use depends on your system.
Desktop Linux
Most desktop environments (GNOME, KDE) start an agent at login and unlock keys through a keyring. Check first:
echo "$SSH_AUTH_SOCK"
ssh-add -lIf SSH_AUTH_SOCK already has a value, do not start another agent.
macOS
macOS runs an agent for you through launchd. To store the passphrase in the Keychain so it is not requested after a reboot, use:
ssh-add --apple-use-keychain ~/.ssh/id_ed25519Older macOS versions use -K instead of --apple-use-keychain. To load the key automatically, add these lines to ~/.ssh/config:
Host *
AddKeysToAgent yes
UseKeychain yesUseKeychain is an Apple-specific option. On other systems an OpenSSH client that does not know it will report an error unless you also add IgnoreUnknown UseKeychain at the top of the block.
Systemd user service
On Linux systems with a systemd user session, you can run one agent per user. Create ~/.config/systemd/user/ssh-agent.service:
[Unit]
Description=SSH key agent
[Service]
Type=simple
Environment=SSH_AUTH_SOCK=%t/ssh-agent.socket
ExecStart=/usr/bin/ssh-agent -D -a $SSH_AUTH_SOCK
[Install]
WantedBy=default.targetEnable it, and point your shell at the socket by adding this line to ~/.profile or ~/.bashrc:
systemctl --user enable --now ssh-agent.service
export SSH_AUTH_SOCK="$XDG_RUNTIME_DIR/ssh-agent.socket"Run the systemctl command once in a terminal. Put only the export line in your shell startup file. The ssh-agent path may differ on your distribution, so confirm it with command -v ssh-agent.
Letting ssh add keys on first use
The simplest option, available in OpenSSH 7.2 and later, is a client setting that adds a key to the agent the first time you use it:
Host *
AddKeysToAgent yesYou still type the passphrase once. After that, the agent holds the key. You can also write AddKeysToAgent 4h to add an expiry. This works only when an agent is already running and SSH_AUTH_SOCK is set.
Agent forwarding and its risks
Agent forwarding lets you hop from one server to another using the keys on your laptop, without copying any private key to the first server. You enable it for one connection with -A:
ssh -A [email protected]On the bastion, ssh to a third machine now asks your laptop's agent to sign. The private key never leaves your laptop.
The risk is that the forwarded socket appears on the intermediate server. A user with root access there, or the same user ID, can use that socket to sign logins as you for as long as your session lasts. They cannot steal the key, but they can use it. Follow these rules:
- Forward the agent only to hosts you trust fully. Never put
ForwardAgent yesunderHost *. - Prefer
ProxyJump, which tunnels the connection through the bastion without exposing your agent:ssh -J [email protected] [email protected]. - Combine forwarding with
ssh-add -cor short key lifetimes where you can.
Common problems
| Symptom | Likely cause | Fix |
|---|---|---|
| `Could not open a connection to your authentication agent` | No agent running, or `SSH_AUTH_SOCK` not set in this shell | Run `eval "$(ssh-agent -s)"` or fix your startup file |
| `ssh-add -l` says no identities, yet passphrase prompts continue | Key was never added, or the agent expired it | Run `ssh-add` again, or set `AddKeysToAgent yes` |
| Passphrase requested on every connection despite `ssh-add` | Terminal is using a different agent than the one you loaded | Compare `echo $SSH_AUTH_SOCK` across terminals |
| Too many authentication failures | The agent offers many keys and the server counts each as a failure | Set `IdentitiesOnly yes` and `IdentityFile` in `~/.ssh/config` |
| Key works inside tmux but not outside | tmux kept an old `SSH_AUTH_SOCK` value | Reattach and re-export the variable from a live shell |
The "Too many authentication failures" case is worth understanding. By default ssh tries every key in the agent before it tries the file you named. Most servers allow only about six attempts (the MaxAuthTries setting), so a crowded agent can lock you out before the right key is offered. IdentitiesOnly yes makes ssh offer only the keys named in your config, which is why the host entry from the earlier chapter includes it.
Security trade-offs
- A loaded key is usable by any process running as your user. Malware on your account can ask the agent to sign without knowing the passphrase.
- Root on your machine can read process memory and the socket, so an agent does not defend against a compromised host.
- A short lifetime (
-t) limits how long a stolen session can be abused. - On shared machines, run
ssh-add -Dor log out when you finish.
For stronger protection, hardware-backed keys (ed25519-sk created with a security key) require a physical touch for each signature, which an agent cannot bypass.
Exercise
You run ssh-agent -s in a terminal, then ssh-add ~/.ssh/id_ed25519, and you get "Could not open a connection to your authentication agent." What went wrong, and what is the correct command?
Show answer
Running ssh-agent -s only prints shell commands that set SSH_AUTH_SOCK and SSH_AGENT_PID. They were never executed, so the shell does not know where the agent is. Use eval "$(ssh-agent -s)" so the variables are set in the current shell, then run ssh-add again.
Exercise
Your server rejects logins with "Too many authentication failures" even though the right key is loaded in the agent, which holds eight keys. Name the cause and give the config lines that fix it.
Show answer
By default ssh offers every key held by the agent, and the server counts each rejected offer against MaxAuthTries, so the correct key is never reached. Add IdentityFile ~/.ssh/id_ed25519 and IdentitiesOnly yes to the Host entry in ~/.ssh/config so only that key is offered.
Exercise
You must reach internal.example.com through bastion.example.com. Which approach exposes your agent less, ssh -A or ssh -J, and why?
Show answer
ssh -J [email protected] [email protected] exposes it less. ProxyJump tunnels the connection through the bastion, and authentication happens end to end from your laptop, so no agent socket appears on the bastion. With -A a forwarded socket exists on the bastion, and anyone with root there can use it to sign logins as you during the session.