Verify which key was used to connect to SSH

Super User Asked by Ricky on December 5, 2020

I usually connect to a particular server with a specific key, like so:

$ ssh -i key.pem ec2-user@server

Yesterday I realised that the key I have been using isn’t actually in ec2-user‘s authorized_keys file. There is only one key listed, which I do also have on my machine.

I am trying to understand how I’ve been able to successfully connect using the above command. Is there a way to get the ssh program to explicity describe which key it used to connect?

One Answer

When providing -v in the connection command of ssh it will show a couple of lines like

debug1: Offering public key: /home/foo/.ssh/id_rsa SHA256:hash debug1: Server accepts key: /home/foo/.ssh/id_rsa SHA256:hash

where you can view the key used from the client point of view.

At the server it should be logged at /var/log/auth.log like:

sshd[1668]: Accepted publickey for <user> from <ip> port <port> ssh2: RSA SHA256:`

I suspect you will actually have the key appearing on authorized_keys, perhaps in ~/.ssh/id_rsa or similar (they are loeaded by default). If you want to use the key provided, and only that one, even if there are other public key files, or keys on the agent, you should also set IdentitiesOnly=yes, e.g.

ssh -oIdentitiesOnly=yes -i key.pem ec2-user@server

Although for hosts you frequently connect to, I would recommend setting that up on ~/.ssh/ssh_config:

Host server
User ec2-user
IdentitiesOnly yes
IdentityFile key.pem

so you can just do ssh server

Correct answer by Ángel on December 5, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP