It is wise to protect your private SSH keys with a strong password so in case somebody manages to get your private key somehow he will still need password for it to be able to use it and that should hopefully give you enough time to change your keys. When you have password protected private key you need to enter your password every time you use it which can be problematic, especially when you use your key a lot. This is where ssh-agent and similar software comes in handy.

Since I don’t use Gnome on my Fedora machine I don’t have it’s key agent to automatically cache my private key, instead, I need to set up ssh-agent to do that for me. There are multiple ways to set up ssh-agent but simplest one in my opinion is to set up SystemD user service.

SystemD has a feature to execute and start services as user at user login. To do that we need to make some tweaks in your /etc/pam.d/system-auth PAM policy. By default pam_systemd.so is commented out:

-session     optional      pam_systemd.so

so go ahead and change that line to:

session     optional      pam_systemd.so

Another prerequisite you may need to enable is “AddKeysToAgent” option in your /etc/ssh/ssh_config file to enable this option system-wide or in ~/.ssh/config file to enable option just for your user. Doing this will enable caching your keys in ssh-agent.

After we made sure all requirements are met we can proceed with creating SystemD user service. SystemD by default looks into ~/.config/systemd/user/ directory to find user service files but as you may notice this directory doesn’t exist so we’ll create it manually:

mkdir -p ~/.config/systemd/user/

After that create ssh-agent.service file:

vi ~/.config/systemd/user/ssh-agent.service

and place following in there:

[Unit]
Description=SSH key agent
[Service]
Type=forking
Environment=SSH_AUTH_SOCK=%t/ssh-agent.socket
ExecStart=/usr/bin/ssh-agent -a $SSH_AUTH_SOCK
[Install]
WantedBy=default.target

After you have finished with that save file and your SystemD service should be available when you list all user services. To do that you can use:

systemctl --user list-unit-files

To enable service to start on boot use:

systemctl --user enable ssh-agent.service

You should additionally place following entry in your start-up file (eg. .bash_profile):

export SSH_AUTH_SOCK="$XDG_RUNTIME_DIR/ssh-agent.socket"

Reboot your system after that and everything should hopefully work as expected. SSH will still ask you for a password when connecting to a server, but just once and then password will be cached in your ssh-agent.