3

Is there a way with OpenSSH (ssh) to specify the expected host key fingerprint as a command-line argument so that a connection will only be allowed if the key fingerprint sent by the server matches the one given as a command line argument ?

I am trying to provide a similar level of functionality in Windows and Posixly versions of application. On Windows, the usual SSH client is plink (also available on Linux) which has a --hostkey command-line option for this purpose:

$ plink -hostkey "d0:e4:ad:11:7d:6a:8c:c0:36:2b:ff:ee:16:cf:f7:46" user@host

Is that possible with the OpenSSH ssh command ?

  • By default no; I guess you could write a wrapper script that disables the default known_hosts lookups, accepts the supplied key (or keys?) writes that to a temporary file, then exec ssh -o UserKnownHostsFile=$URTMPFILE ... – thrig Mar 28 '17 at 14:36
6

You could set the expected key in known_hosts before running ssh, but I think you'd need the whole key then, not just the fingerprint.

But ssh prints the key fingerprint when connecting if it isn't saved in known_hosts, so we could use that and expect our way out of it.

The script here would take the hostname (or user@host) and expected fingerprint as arguments, force an empty known_hosts, and compare the printed fingerprint to the given one.

#!/usr/bin/expect -f

set host   [lindex $argv 0];
set fp     [lindex $argv 1];

spawn ssh -oUserKnownHostsFile=/dev/null $host
expect -indices -re "key fingerprint is (\[^.\]+)"
set fp_got $expect_out(1,string)

expect "Are you sure you want to continue connecting (yes/no)"
if { $fp_got == $fp } {
        send "yes\r"
} else {
        send "no\r"
}       
interact

So, given the correct fingerprint, the connection should succeed:

$ ./ssh.expect localhost 60:6e:...:e1 
spawn ssh -oUserKnownHostsFile=/dev/null localhost
The authenticity of host 'localhost (::1)' can't be established.
ECDSA key fingerprint is 60:6e:...:e1.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'localhost' (ECDSA) to the list of known hosts.
itvirta@localhost's password: 
|improve this answer|||||
  • 1
    Note OpenSSH since 6.8 fingerprint display defaults to base64 (of SHA256) no longer hex with colons (of MD5). Putty/plink/etc hasn't followed suit. – dave_thompson_085 Mar 28 '17 at 18:45
  • @dave_thompson_085, right, I had a vague memory of that, but didn't happen to have a new enough version at hand. I changed the pattern to assume less of the format. – ilkkachu Mar 28 '17 at 19:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.