I'm having a hard time finding proper docs on the order in which the OpenSSH client tries private keys for authenticating against a server, given that all of the following are present:
- key files with default names in
~/.ssh
, e.g.~/.ssh/id_rsa
, - key files with non-default names that are configured to be used with a specific host via
~/.ssh/config
, - keys managed by
ssh-agent
.
Are all of these locations always tried (provided that the host matches an entry in ~/.ssh/config
), and in which order?
Background: I have ~/.ssh/id_rsa
which can only be used to authenticate against server A, and I have another key managed by ssh-agent
that can only be used to authenticate against server B. When trying to ssh
to B, authentications fails, apparently because only ~/.ssh/id_rsa
is tried. There does not seem to be a fallback to try the key managed by ssh-agent
.
Best Answer
Use the source, Luke!
OpenSSH is open source so instead of trial-error, you can read the code to get better understanding what is going on there.
ssh.c
is a good place to start. It has a functionload_public_identity_files(void)
, which takes care of this. In the first place, the keys from PKCS#11 (Smartcard, HSM) are used:and then the keys provided by
options.identity_files
:This variable is set in
readconf.c
:The real paths of the files are defined in
pathnames.h
:To the background question:
This is exactly why the
IdentitiesOnly
option exists and why you should use it in the~/.ssh/config
if you have more than one key to manage. Thessh-agent
identities are used after the default ones.