Ssh – Ignore or replace host key if it differs

hostkeyssh

Quite often i put servers into a rescue mode and that obviously changes the host key.
So there are situations when i know that SSH host key will be changed temporarily or permanently.
And each time i need to do:

  • ssh-keygeyn -R x.x.x.x
  • ssh x.x.x.x and confirm addition of a new key
  • Do something in rescue mode and reboot the server
  • ssh-keygen -R x.x.x.x
  • ssh x.x.x.x if needed and accept new host key

I wounder if somebody came up with a smart alias or there is an ssh client's config option which in case of different host key asks to replace curent hostkey or just ignore the problem temporarily and proceed.

Best Answer

Solution 1

You can scan remote host new public key before login with ssh-keyscan command.

ssh-keygen -R x.x.x.x
ssh-keyscan x.x.x.x >> ~/.ssh/known_hosts
ssh x.x.x.x

Then you can make a script from that, using the host as an argument and put it in your PATH.

To check if public keys differ you can do this :

diff -q <(ssh-keygen -F x.x.x.x | sed '1d') <(ssh-keyscan x.x.x.x 2>/dev/null)

Solution 2

Now, if you have a DNS server in your infrastructure, you should set up SSHFP DNS records to handle your machine's public key changes a centralized way and avoid the hassle of homemade scripts everywhere.

Retrieve DNS entries to configure :

ssh-keygen -r /etc/ssh/ssh_host_key.pub

The result will look like :

IN SSHFP 1 1 d3fa9bcf2d51979c53bcac2961f38b60e4e60886
IN SSHFP 2 1 f1f09814dd79eea523f490808cf3c096f1d1a432

Little explanation :

  • First field : IN = Internet class
  • Second field : SSHFP record type
  • Third field : Algorithm (1=RSA, 2=DSA, 3=ECDSA)
  • Fourth field : Fingerprint type (1=SHA-1, 2=SHA256)

Prefix these records with the server name and put them in your DNS configuration.

Then make sure all your machines will contact your DNS server in /etc/resolv.conf.

Finally, put VerifyHostKeyDNS=yes option in .ssh/config file on each server.