Setting up ssh-agent with Caching of Keys on First Use
If you use a password protected SSH key, ssh
in a standard setup will
ask for your password each time you use the key. You can use ssh-agent
to save the key for later use after decryption. In this use case ssh-agent
is a program that caches the encryption key for you so that you can use it
later without having to enter the password again. For other scenarios ssh-agent
has some more advantages.
Since there are quite different setup strategies out in the wild I just want to
quickly take notes about my approach in which the first usage of the key will
query for the password and subsequent uses will use the key from ssh-agent
.
Other approaches include:
- decrypting the key automatically with PAM
- manually adding the key to
ssh-agent
withssh-add
- adding the keys automatically to the
ssh-agent
with delay of the decryption until first usage
I start ssh-agent
with a script in my .bashrc
file (or respective
file if you use another shell). However, running ssh-agent
as a systemd service
is also possible.
Usage of ssh-agent
will require a few
environment variables to be set. ssh-agent
will print them during startup,
but it is your own responsibility to source them. .bashrc
is a good place
for this if you start your programs from there. You also have to make sure
to start ssh-agent
only once, otherwise different shells will use different
agents and thus will not share the same decrypted keys (which means you will
have to decrypt the same key again).
# Check whether ssh-agent is already running as a process
# if not start it and create a run file with the environment
# variables that ssh-agent gives us and wants us to source
if ! pgrep -u "$USER" ssh-agent > /dev/null; then
ssh-agent > "$XDG_RUNTIME_DIR/ssh-agent.env"
fi
# If the environment variable $SSH_AUTH_SOCK has not been set
# yet, source the environment variables from our instance of
# ssh-agent
# Redirect the output to /dev/null; otherwise each bash would show
# the ssh-agent PID
if [[ ! "$SSH_AUTH_SOCK" ]]; then
eval "$(<"$XDG_RUNTIME_DIR/ssh-agent.env")" > /dev/null
fi
Next, you need to tell ssh
to automatically send decrypted keys to the
agent. For this, add the line AddKeysToAgent yes
to your ~/.ssh/config
.
With this setup SSH will ask you for your SSH password on first usage and will then send it
I do not maintain a comments section. If you have any questions or comments regarding my posts, please do not hesitate to send me an e-mail to blog@stefan-koch.name.