Ruby SSH Scripts with Net::SSH: Verify the Host Key

Updated

ruby on rails

A script that prints your password to standard output every time the connection fails — and exits 0 while doing it — is not a style problem. The exception it swallows includes Net::SSH::HostKeyMismatch, which is the signal that the host key of the server you are about to authenticate to has changed. Use this instead:

require 'net/ssh'          # 'rubygems' has not been needed since Ruby 1.9

host = ENV.fetch('SSH_HOST')
user = ENV.fetch('SSH_USER')
key  = ENV.fetch('SSH_KEY')
cmd  = ARGV.fetch(0)

begin
  Net::SSH.start(host, user,
                 keys:            [key],
                 keys_only:       true,
                 non_interactive: true,
                 verify_host_key: :always) do |ssh|
    status = nil
    out = String.new
    err = String.new
    ssh.open_channel do |ch|
      ch.exec(cmd) do |_, ok|
        abort "could not start a shell channel" unless ok
        ch.on_data                   { |_, d| out << d }
        ch.on_extended_data          { |_, _, d| err << d }
        ch.on_request("exit-status") { |_, data| status = data.read_long }
      end
    end
    ssh.loop
    $stdout.print out
    $stderr.print err
    exit(status.nil? ? 1 : status)
  end
rescue Net::SSH::HostKeyMismatch => e
  abort "HOST KEY CHANGED for #{host}: #{e.message}\nStop. Do not send credentials to this host."
rescue Net::SSH::HostKeyUnknown => e
  abort "unknown host key for #{host}: #{e.message}\nRecord it with ssh-keyscan first."
rescue Net::SSH::AuthenticationFailed
  abort "authentication failed for #{user}@#{host} (no password is printed by design)"
end

The two scripts, same server, same broken state

A throwaway sshd was started on 127.0.0.1:22022, its key recorded, then the server restarted with a different host key — what a machine-in-the-middle looks like from the client side. The script that prints the password:

$ ruby old_script.rb
Unable to connect to 127.0.0.1 using deploy/hunter2
$ echo $?
0

Password on stdout, exit status 0 — a green tick in cron or CI. The replacement, same server, same moment:

$ ruby remote_run.rb 'true'
HOST KEY CHANGED for 127.0.0.1: fingerprint SHA256:UHeBMhEMK5KYOjHTUeNHDitEfjtMNxcF97b5wnRSioo does not match for "[127.0.0.1]:22022"
Stop. Do not send credentials to this host.
$ echo $?
1

A bare rescue catches every StandardError, and Net::SSH‘s exceptions all are ones. Such a handler distinguishes nothing: a typo in the hostname, a wrong password and a substituted server produce the same line.

net-ssh’s default host-key policy is labelled insecure by net-ssh

A script that never passes verify_host_key takes the default. From lib/net/ssh.rb in the installed gem (7.3.3):

#   In order of increasing strictness:
#   * :never (very insecure) ::Net::SSH::Verifiers::Never
#   * :accept_new_or_local_tunnel (insecure) ::Net::SSH::Verifiers::AcceptNewOrLocalTunnel
#   * :accept_new (insecure) ::Net::SSH::Verifiers::AcceptNew
#   * :always (secure) ::Net::SSH::Verifiers::Always

And from lib/net/ssh/transport/session.rb, the line that decides what “unset” means:

when :accept_new_or_local_tunnel, nil then
  Net::SSH::Verifiers::AcceptNewOrLocalTunnel.new

nil — no option given — selects the entry the docs mark (insecure). It accepts any key it has not seen before, and its source adds a second exemption: “A connection is potentially being tunnelled if the port is not 22, and the ip refers to the localhost”, in which case it returns true without checking anything. That is why the demonstration above had to set verify_host_key: :always before the mismatch was detected at all. With it set, the three states behave as you would want — run, not described:

empty known_hosts : Net::SSH::HostKeyUnknown
                    fingerprint SHA256:tAzg7wa8QJOoomOkCAZ6MPhqwUG7esprSdF6Jc+VHuA is unknown for "[127.0.0.1]:22022"
key recorded      : CONNECTED  uname=Darwin
server key swapped: Net::SSH::HostKeyMismatch
                    fingerprint SHA256:UHeBMhEMK5KYOjHTUeNHDitEfjtMNxcF97b5wnRSioo does not match for "[127.0.0.1]:22022"

exec! returns output, and mixes stderr into it

Take a script that does res = ssh.exec!(@cmd); puts res. Running cat /no/such/file through it:

exec! returned      : "cat: /no/such/file: No such file or directory\n"
exec! return class  : Net::SSH::Connection::Session::StringWithExitstatus
out.exitstatus      : 1
channel exit-status : 1
channel stderr      : cat: /no/such/file: No such file or directory

The exit status is reachable — net-ssh returns a String subclass carrying .exitstatus — but puts res throws it away, so the script cannot tell a successful command from a failed one. Remote stderr is concatenated into the same string as stdout, so the caller cannot separate those either. The channel API in the replacement keeps all three apart.

Passwords do not belong on the command line

If a script takes -p PASSWORD as an argument, this is what every other account on that machine can read while it runs:

$ ps -Ao user,pid,args | grep '[s]shrun'
USER  52611 ruby /…/sshrun.rb -h db01.example.com -u deploy -p S3cr3t-Pa55w0rd -c ls -al

Unlike mysqldump, Ruby does not scrub its own argv, and the password is in your shell history too. Use a key, or read the secret from the environment — the replacement above takes no password at all, and the same reasoning applies to scp.

Two key-file surprises worth knowing before you debug them

net-ssh cannot read a key generated by a current ssh-keygen unless two extra gems are present — including RSA keys, because the container format is what it objects to. Handing it a default -----BEGIN OPENSSH PRIVATE KEY----- file:

OpenSSH keys only supported if ED25519 is available (NotImplementedError)
net-ssh requires the following gems for ed25519 support:
 * ed25519 (>= 1.2, < 2.0)
 * bcrypt_pbkdf (>= 1.0, < 2.0)

Install those two gems (needed for ed25519 keys anyway), or export as PEM: the identical key re-emitted with ssh-keygen -m PEM connected on the next attempt.

net-ssh does not enforce private key file permissions. Same key at mode 0644, two clients:

$ ssh -i id_pem_644 …
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@         WARNING: UNPROTECTED PRIVATE KEY FILE!          @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Permissions 0644 for 'id_pem_644' are too open.
This private key will be ignored.

$ ruby probe.rb …
CONNECTED  uname=Darwin

OpenSSH refuses; net-ssh reads the file and carries on. A working Ruby script is not evidence that the key is stored safely — chmod 600 it yourself.

What was executed, and what was not

Ruby 2.6.10p210 and net-ssh 7.3.3 on macOS 26.6 arm64, against a temporary OpenSSH 10.3p1 server run by hand on 127.0.0.1:22022 with throwaway host keys and stopped afterwards. Every output block is from that setup, unedited apart from replacing a username and absolute paths. No production or third-party host was contacted, and no real credential appears on this page — hunter2 and S3cr3t-Pa55w0rd are invented. The three host-key states above, net-ssh's own "(insecure)" label on the default verifier, the OpenSSH-versus-PEM key restriction and the password visible in ps are re-checked by ssh-script-example.sh, which builds its own sshd if it can and skips the live checks if it cannot. The default-verifier claim is read from the installed gem's own source, quoted above.

Photo of author
Sudhir P. founded HeatWare.com in 1999 and has built and operated it full-stack ever since; it is now used by more than 88,000 people. He writes here about the PostgreSQL, MySQL, Linux and DevOps work that keeps it running. Articles are rewritten only after the commands in them have actually been run, and the verification scripts are published alongside them so anyone can check the claims. Reach him at blog@heatware.net.