Useful to use SSH securely using a smart card / hardware token / yubikey / etc.

Prerequisites

Of course, you need to have GPG installed on your system, and possibly some drivers and applications to support your smart card / hardware token if used.

This guide assumes you already have set up GPG and your keys (and possibly hardware token) and now you just want to know how to SSH!

Enabling SSH in the GPG agent

On Mac, nothing further needs to be done. On Windows you have to add enable-putty-support to %appdata%\gnupg\gpg-agent.conf and on Linux enable-ssh-support to ~/.gnupg/gpg-agent.conf create these files if they don’t already exist, but make sure the folder has already been there or you’re at the wrong place.

echo 'enable-ssh-support' >> ~/.gnupg/gpg-agent.conf

Using the GPG agent

And make sure you are using the GPG agent by adding this to your “.profile” or shell’s rc file (and then restart the terminal session):

Linux (Debian and Ubuntu)

Add the following to your ~/.bashrc

export GPG_TTY="$(tty)"
export SSH_AUTH_SOCK="/run/user/$UID/gnupg/S.gpg-agent.ssh"
gpg-connect-agent updatestartuptty /bye > /dev/null

Mac (and some Linux distros)

Add the following to your ~/.profile or ~/.bashrc (“macOS Big Sur” users should put this into ~/.zprofile)

export GPG_TTY="$(tty)"
export SSH_AUTH_SOCK=$(gpgconf --list-dirs agent-ssh-socket)
gpgconf --launch gpg-agent

Windows

Windows has no such thing as a shell rc, but instead, you’ll have to manually run commands in the CMD (or create a batch file and add it to autostart) with the following contents:

gpg-connect-agent.exe killagent /bye
gpg-connect-agent.exe /bye

Exporting your public key and adding it to the server

Simply run gpg --export-ssh-key MY_KEY_ID and copy the output to your remote server’s ~/.ssh/authorized_keys file!

Connecting to the SSH server

Now, if you did all the above, simply restart your terminal session and try to SSH to your server as usual. You might now be asked to enter your GPG key passphrase, or the pin of your smart card.

On Windows, you’ll be using PuTTY instead.

I hope this helped.

If I forgot something or you’re running into issues, just leave a comment.