ssh key choices

This weekend, Rob and I had been testing the use of hardware keys to secure ssh sessions, especially for back-end console access and certain administrative functions. Since the hardware keys are a special case, and cannot be added to the ssh-agent, we were slinging around a fair number of command lines with -i <keyfile> on them to point ssh at the key we wanted it to offer. Also as part of the diagnostics, I was running with -v, so that I could tell exactly what was going on. This is when I was reminded that ssh's choice of keys isn't always what I expect (a problem I'd run into previously when maintaining keys for a number of customer projects on the same device).

Without looking at the code, the observed key offer sequence appears to be:

  1. Keys added to your currently-available ssh-agent (unless you have disabled that with -o IdentitiesOnly=yes)

  2. Keys in your ~/.ssh/config file referenced by the IdentityFile directive and matching the host pattern (these are cumulative).

  3. Keys specified with -i on the command line

With that said, here are a few useful ssh-related notes:

  • When you know you're going to need to use a password (as opposed to a key), use

    ssh -o PubkeyAuthentication=no

    which I have used Keyboard Maestro to alias to sshP in Terminal. This prevents running out of login attempts before you get a chance to enter the password, as most ssh servers will only allow 3-5 attempts, including pubkeys and interactive passwords.

  • If you need to prevent your config file from being used, -F /dev/null will override your config file with an empty one.

  • Of course, you can always use ssh-add -D to remove all keys from the ssh-agent, but that affects all terminal sessions on your machine. As an alternative, you can avoid consulting the ssh-agent by unsetting the shell variable SSH_AUTH_SOCK, which is used to locate the authentication socket. Since this is a shell variable, it only affects the shell that you perform it in, so it leaves your other terminal windows able to use the agent's keys.

  • None of the identity commands affect the operation of the -A command line switch (or the corresponding ForwardAgent yes directive in your config file). So, even if you use -o IdentitiesOnly=yes to keep the session initiation from offering the keys in the agent at the time, an -A flag on the command line will allow you to use the keys on further communication from the target host (useful for things like bastion hosts, such as the ones we're securing).