SSH Agent and Key Management

Using an agent for SSH key exchange can be sometime hard, since you need to remember how to launch the agent, how to add the keys, and so on. In my last setup, I’m trying to clean up all the details so that I can quickly restore my configuration (not the keys!) and get up and running as soon as possible. In order to achieve this, I’ve: 1) created an ssh_config user configuration file to handle connection details; 2) created a SystemD user configuration file to handle the SSH Agent; 3) changed my shell setup configuration to handle the agent running. In the following, I describe how to perform the above steps.

The ssh_config file

This is a quite simple step, and there is nothing so special in here. As an example, here it is the part of the file to manage my repository connections:

Host *.github.com *.gitlab.com
     User fluca1978
     ForwardAgent yes
     AddKeysToAgent  yes


The ForwardAgent is the important part: it tells the connection to exploit the agent. The AddKeysToAgent tells the agent to automagically add the keys the first time it is run. This way there is no need to execute the ssh-add part on login.

Create the SystemD user service

SystemD is not something I really like, but a very nice feature it has is the capability to create user services, that are services that can be managed as system services but do not require the user to be a superuser.
In order to create the ssh-agent service, there must be a file placed on ~/.config/systemd/user/ssh-agent.service with the following content:

[Unit]
Description=SSH Agent Service

[Service]
Type=simple
Environment=SSH_AUTH_SOCK=%t/ssh-agent.socket
ExecStart=/usr/bin/ssh-agent -D -a $SSH_AUTH_SOCK

[Install]
WantedBy=default.target



Once the file is in place, the user can enable and start the service:

% systemctl --user enable ssh-agent
% systemctl --user start ssh-agent



Configure the Shell

In your shell profile, ensure that the the ssh-agent socket can be found:

SSH_SYSTEMD_SERVICE_FILE="$HOME/.config/systemd/user/ssh-agent.service"
if [ -f $SSH_SYSTEMD_SERVICE_FILE ]; then
   export SSH_AUTH_SOCK="$XDG_RUNTIME_DIR/ssh-agent.socket"
fi



The above checks that the SystemD file exists, and in such case assumes something will run and sets the SSH_AUTH_SOCK environment variable.

Test

Having everything in place, it is quite simple to test that the configuration is working:

% ssh -T git@github.com
Hi fluca1978! You've successfully authenticated, but GitHub does not provide shell access.

% ssh -T git@gitlab.com
Welcome to GitLab, @fluca1978!


Conclusions

It is easy enough to configure SSH and the agent to get rid of management madness!

The article SSH Agent and Key Management has been posted by Luca Ferrari on July 14, 2023