Stop MITM on the first SSH connection, on any VPS or cloud provider
This little script stops attacks on the first SSH connection to a new VM, even on providers (like Hetzner Cloud) that don't offer a proprietary solution; we only need cloud-init, which is widely supported.
Summary (for experts; read on for a longer explanation): inject a temporary SSH host (private) key via cloud-init, and trust that temporary SSH host key just long enough to generate and retrieve the "real" (long-term) SSH host keys. The script is a simple but hardened implementation of this technique; the comments in the script discuss implementation choices. The technique appears to be new: I haven't found a proper write-up of this, nor of any other provider-independent solution (but I'd welcome a correction).
This technique actually protects the first connection, whereas just answering "yes" when ssh asks " The authenticity of host [...] can't be established " (i.e. Trust On First Use) leaves you open to an attacker rerouting your traffic to a proxy, or to an attacker generously deciding to provide your VM (... for now).
This technique also makes leaks of the cloud-init userdata harmless. Injecting a long-term SSH host (private) key via cloud-init does allow you to authenticate the first connection (by adding the public part of the injected key to ~/.ssh/known_hosts ), but leaves valuable (private) key material in the cloud-init userdata, where an attacker can often obtain it from
Security analysis / threat model
Throughout, we trust the (Open)SSH protocol and implementation, and we do not rely on you, the administrator, detecting the attack.
We are secure against a network attacker
We protect
the integrity of the administrator's workstation, and
... continue reading