Let us consider a first SSH connection to a server that I know the correct public key. Can I setup something such that even if the SSH server public key changes, I am able to figure out if there is not a man-in-the-middle attack?
Jun 2, 3:49pm
Yes, you can protect yourself against man-in-the-middle (MITM) attacks during an SSH connection, even if the server's public key changes, by using SSH key verification best practices. Here’s how you can achieve this:
1. Use SSH Known Hosts with Strict Host Key Checking
By default, SSH clients store the server's public key in the ~/.ssh/known_hosts file. If the key changes, SSH will warn you and refuse to connect (unless you explicitly disable this check).
How it works:
On your first connection, SSH saves the server's public key in ~/.ssh/known_hosts.
On subsequent connections, SSH compares the server's key with the stored one.
If the key does not match, SSH will display a warning like:
text
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
This is your first line of defense against MITM attacks.
How to enforce it:
Ensure StrictHostKeyChecking=yes is set in your SSH client config (~/.ssh/config or /etc/ssh/ssh_config).