Script to detect firewall misconfiguration
#! /bin/bash
####################################################
# Returns success if SSH is reachable from $remote #
####################################################
if [ -z $remote ]; then
echo '$remote must be defined!' >&2;
exit 255
fi
host_key_seen_by_remote=$(ssh $remote ssh-keyscan -t rsa '${SSH_CLIENT%% *}' 2>/dev/null | awk '{print $NF}')
host_key_local=$(ssh-keyscan -t rsa 127.0.0.1 2>/dev/null|awk '{print $NF}' )
if [ ! -z $host_key_seen_by_remote ] && \
[ ! -z $host_key_local ] && \
[ $host_key_seen_by_remote == $host_key_local ];
then
printf "ssh_host_key:\t%s\n" $host_key_seen_by_remote >&2
printf "ssh_connection:\t%s\n" "$(ssh $remote echo \$SSH_CLIENT)" >&2
exit 0
fi
exit 1
How it works
When you connect to a remote SSH server, your IP address is automatically exported to the remote environment via the $SSH_CLIENT
environment variable.
On a remote SSH server, the ssh keyscan command is run, on the host with an address corresponding to the $SSH_CLIENT
.
The SSH keyscan command dumps the SSH host key of a specified host. If the host key of the $SSH_CLIENT
matches our true host key, then this means our local instance of SSH must be reachable to the remote server.
Other uses
This script can also be used to detect man in the middle attacks occurring on the remote server