You are here

Regenerating/renewing the SSH key for a known host which has been reinstalled

Submitted by Druss on Sat, 2014-08-30 14:25

I ran into the following spiel when I attempted to SSH to a host just now:

$ ssh bar.example.com
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
Someone could be eavesdropping on you right now (man-in-the-middle attack)!
It is also possible that the RSA host key has just been changed.
The fingerprint for the RSA key sent by the remote host is
4a:c7:83:c3:a1:a2:33:d0:34:17:93:91:da:e2:f1:05.
Please contact your system administrator.
Add correct host key in /var/foo/.ssh/known_hosts to get rid of this message.
Offending key in /var/foo/.ssh/known_hosts:6
RSA host key for bar.example.com has changed and you have requested strict checking.
Host key verification failed.

Very scary. But what had happened was that the host bar.example.com had been reinstalled and this effectively also changed its SSH keys. The fix is, as the message notes, to add the correct host key and remove the offending key from the .ssh/known_hosts file. SSH also helpfully provides the line number (number 6 in the excerpt above) of the entry for the offending key as there is no way to identify it otherwise.

While this will work fine, the solution is a little icky. A neater alternative would be nice and unsurprisingly, exists. Simply type:

ssh-keygen -R bar.example.com

This will remove the entry for bar.example.com from the known_hosts file. Clean and hassle-free :)

Sometimes, you might also need to repeat the process for the host's IP address (in case you have SSH'd in using it). In that case, you might additionally want to remove the entry for the IP as well:

ssh-keygen -R 10.11.12.13

Hope this helps!


Yet another solution, however, one that is not recommended is to disabled the strict checking that SSH is configured with by default. This can be done on the go using something like: ssh -o Stricthostkeychecking=no bar.example.com

You can disable this permanently by editing /etc/ssh/ssh_config and setting StrictHostKeyChecking to no. However, this will avoid checking the key for ALL hosts. A better solution would be to edit/create the .ssh/config file in your own home directory and adding something like:

Host foo.example.com
   StrictHostKeyChecking no

This will only disable the strict key checking for the single host, foo.example.com.