#!/bin/zsh -fuC

# Get the fingerprint of a SSL-connection via SSH from different hosts to check
# that it's the same from everywhere, i.e. there's no or the same man in the
# middle.

ssh_local_port=13724

process_fp()
{
    if [[ ${#master_fp:-} -gt 0 && $master_fp != $1 ]]
    then
        print "\e[1m$1\e[0m"
    else
        print $1
    fi
    if [[ ${#master_fp:-} -eq 0 ]]
    then
        master_fp=$1
    fi
}

if [[ $1 == (-l|--local-openssl) ]]
then
    local_openssl=true
    shift
else
    local_openssl=false
fi

dest=$1
shift
hosts=( $@ )

if [[ $dest != *:* ]]
then
    dest+=:443
fi

if $local_openssl
then
    sock_dir=$(mktemp -d)
    trap 'for i in $sock_dir/*(N); do ssh -S $i -O exit 2>/dev/null; done;
      rm -r $sock_dir' EXIT INT TERM KILL

    for host in $hosts
    do
        ssh_socket=$sock_dir/$host
        if ssh -S $ssh_socket -NTf -o ExitOnForwardFailure=yes \
          -L ${ssh_local_port}:$dest $host
        then
            out=$(openssl s_client -connect localhost:$ssh_local_port \
              </dev/null 2>/dev/null \
              |openssl x509 -fingerprint -noout \
              || true)
            ssh -S $ssh_socket -O exit $host 2>/dev/null
            print -n "${host}: "
            process_fp $out
        else
            print "connection to $host via ssh failed" >&2
        fi
    done
else
    for host in $hosts
    do
        out=$(ssh -n $host openssl s_client -connect $dest 2\>/dev/null \
          \|openssl x509 -fingerprint -noout \
          || true)
        print -n "${host}: "
        process_fp $out
    done
fi
