summaryrefslogtreecommitdiff
path: root/get-host-keys
blob: f55b6cdf11365b53c6d201bbb5b699095ef13dc2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#!/bin/sh
die()
{
    printf "Error: %s\n" "$*" >&2
    exit 1
}

b16_to_b32()
{
    printf %s "$1" | basez -x -d | basez -j -l | tr -d =
}

to_domain_suffix()
{
    local hashtype=2
    local keystring keytype sshfp_b16 sshfp_b32
    [ -f "$1" ] || return
    [ -s "$1" ] || return
    sshfp_raw=$(ssh-keygen -r . -f "$1" | grep -E -e "^. IN SSHFP [0-9]+ $hashtype ")
    case "$sshfp_raw" in
        '. IN SSHFP 1 '*) keytype=1; keystring=rsa ;;
        '. IN SSHFP 4 '*) keytype=4; keystring=ed25519 ;;
        *) return 1 ;;
    esac
    sshfp_b16=$(printf '%s' "$sshfp_raw" | sed -ne "s/^. IN SSHFP $keytype $hashtype //p") &&
        [ "$sshfp_b16" ] || die "could not determine ssh client fingerprint"
    sshfp_b32=$(b16_to_b32 "$sshfp_b16")

    printf %s.%s.%s "$sshfp_b32" "$keystring" cryptonomic.net | tail -c64
}

crypto_validate_hostname()
{
    local host="$1" t r
    t=$(mktemp)
    case "$host" in
        *.ed25519.cryptonomic.net)
            ssh-keyscan -t ed25519 "$host" 2>/dev/null | while read h keytype keydata comment
            do
                case "$h $keytype" in
                    "$host ssh-ed25519")
                        echo "$keytype $keydata" >> "$t"
                        break
                        ;;
                esac
            done ;;
        *) die "unsupported hostname: $host" ;;
    esac
    if validated=$(to_domain_suffix "$t")
    then
        case "$host" in
            "$validated" | *."$validated" )
                read line < "$t"
                echo "$host $line"
                rm -f "$t"
                return 0
                ;;
        esac
    fi
    rm -f "$t"
    false
}

set -e
_TEMP_DIR_=$(mktemp -d)
cd "$_TEMP_DIR_"
trap 'rm -rf "$_TEMP_DIR_"' EXIT
host=${1:-borges}

# ssh-keygen -F "${host#*@}" | grep -v '^#' > ssh_known_hosts 2>/dev/null
# touch ssh_known_hosts.stamp -r ssh_known_hosts

line=$(crypto_validate_hostname "$host") || die "could not validate hostname cryptographically"

echo "$line" > ssh_known_hosts
cp ssh_known_hosts ssh_known_hosts~

ssh \
    -F /dev/null \
    -o GlobalKnownHostsFile=$PWD/ssh_known_hosts \
    -o UserKnownHostsFile=$PWD/ssh_known_hosts \
    -o UpdateHostKeys=yes \
    -o PasswordAuthentication=no \
    -o StrictHostKeyChecking=yes \
    -n -T \
    "$host" >/dev/null 2>&1

cat ssh_known_hosts