SSH Key Selection Why -i Might Not Work as Expected

· Björn-Eric's Developer notes

How I learned why SSH may ignore the `-i` option if ssh-agent has other keys loaded and how to force SSH to use the correct key.

Understanding SSH Key Selection: Why -i Might Not Work as Expected #

When trying to reach the admin of my (this) blog at Prose.sh from a new computer I ran into some unexpected bahaviour.

Hen using ssh, I assumed that specifying a key with -i (or in ~/.ssh/config) is enough to ensure it's used. Nope. If you have other keys loaded in ssh-agent, SSH might ignore your specified key.

The Unexpected Behavior #

Imagine this scenario:

  1. You have a key already added to ssh-agent.
  2. You try to connect using a different key with -i:
    1ssh -i ~/.ssh/correct_key.pem user@host
    
  3. SSH fails to authenticate despite explicitly pointing to the right key.
  4. But when you add the key to ssh-agent, it suddenly works:
    1ssh-add ~/.ssh/correct_key.pem
    

When trying to authenticate https://pico.sh/ it does not fail per se. But instead of showing me my logged in user, it thinks that I am somebody new (after all, the first id_rsa key I sent is new) and asks me to choose a username.

But why did this happen?

How SSH Selects Keys #

By default, SSH tries keys in this order:

  1. Keys already loaded in ssh-agent
  2. Keys specified in ~/.ssh/config (IdentityFile ~/.ssh/correct_key.pem)
  3. Keys provided via -i

If SSH-agent has a key that doesn't work, SSH may fail before trying the one from -i.

How to Ensure SSH Uses the Right Key #

To force SSH to use only the key you specify, use:

1ssh -i ~/.ssh/correct_key.pem -o IdentitiesOnly=yes user@host

Or, configure it in ~/.ssh/config:

1Host myserver
2    IdentityFile ~/.ssh/correct_key.pem
3    IdentitiesOnly yes

This ensures that SSH ignores any keys in ssh-agent and only tries the specified key.

Takeaways #


Home