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:
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).
~/.ssh/known_hosts.text@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
StrictHostKeyChecking=yes is set in your SSH client config (~/.ssh/config or /etc/ssh/ssh_config).textHost * StrictHostKeyChecking yes UserKnownHostsFile ~/.ssh/known_hosts
If you control the server, you can use SSH certificates (signed by a trusted Certificate Authority, or CA) instead of raw public keys.
~/.ssh/known_hosts or a separate file).bashssh-keygen -s /path/to/ca_key -I "cert_id" -n "host" -V +52w server_host_key.pub
~/.ssh/known_hosts with a @cert-authority marker:
text@cert-authority mydomain.com ssh-rsa AAAAB3NzaC1yc2E...
/etc/ssh/sshd_config:
textHostCertificate /etc/ssh/ssh_host_rsa_key-cert.pub
If the server is publicly accessible, you can publish its SSH public key fingerprint in DNS as an SSHFP record.
textexample.com. IN SSHFP 1 1 a1b2c3d4e5f6...
~/.ssh/config:
textHost example.com VerifyHostKeyDNS yes
If you want manual control, you can:
bashssh-keyscan example.com | grep "ssh-rsa" | cut -d' ' -f3 > current_key.pub diff current_key.pub trusted_key.pub
ssh-ca or ssh-auditknown_hostsStrictHostKeyChecking and manually verify changes.Would you like help setting up any of these methods?
Vibe can make mistakes. Check answers. Learn more