summaryrefslogtreecommitdiff
path: root/cryptonomic-vpn
blob: 0ad0d1a75266d97ccb93cd7e04488ed548fe20c0 (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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
#!/bin/bash
set -e
[ "$UID" = 0 ] || exec sudo -- "$0" "$@"

help()
{
    prefixU="Usage: $0 "
    prefix0="       $0 "
    prefix1=${prefix0//?/ }
    cat <<EOF
Usage:

$prefix0 [--remote-name] <hostname>

$prefix0 --remote-name <hostname> \\
$prefix1 --remote-ip <IP address> \\
$prefix1 --remote-key-type rsa    \\
$prefix1 --local-key <filename>

Options:

    --remote-name       Specify the name that we give to the remote side.

                        Remote name is mandatory, except that if a single
                        non-option argument is given, then it is treated as if
                        it were the argument to --remote-name.

    --remote-ip         The address of the VPN gateway.

                        If not specified, the hostname specified with the
                        --remote-name option will be resolved to obtain an IP.

    --remote-key-type   The type of key to request from the remote IP via the SSH
                        protocol. If specified, it must be 'rsa'.

    --local-key         The location of the private key file.

                        The filename is considered relative to /etc/ssh if it
                        has no slashes. The default is 'ssh_host_rsa_key'. It
                        must be an RSA key.

EOF
}

# Default command line argument values.
NO_ACT=y
REMOTE_KEY_TYPE=rsa
LOCAL_KEY=ssh_host_rsa_key

die()    { printf 'Error: %s\n' "$*"   >&2; exit 1; }
warn()   { [ "$QUIET" ] || printf 'Warning: %s\n' "$*" >&2; }
notice() { [ "$QUIET" ] || printf 'Notice: %s\n' "$*"  >&2; }

parse_options()
{
    OPTS=$(getopt \
               --options 'hynfq' \
               --longoptions 'help,yes-act,no-act,quiet,remote-ip:,remote-name:,remote-key-type:,local-key:' \
               -n connect-vpn \
               -- "$@")
    eval set -- "$OPTS"
    unset OPTS
    if [ $# = 0 ]
    then
        help
        exit
    fi

    while true
    do
        case "$1" in
            -h | --help       ) help; exit;;
            -y | --yes-act    ) NO_ACT=;;
            -n | --no-act     ) NO_ACT=y;;
            -q | --quiet      ) QUIET=y;;
            --remote-ip       ) shift; REMOTE_IP=$1;;
            --remote-name     ) shift; REMOTE_NAME=$1;;
            --remote-key-type ) shift; REMOTE_KEY_TYPE=$1;;
            --local-key       ) shift; LOCAL_KEY=$1;;
            --                ) shift; break;;
        esac
        shift
    done

    if [ $# = 1 -a -z "$REMOTE_NAME" ]
    then
        REMOTE_NAME=$1
    elif [ $# != 0 -o -z "$REMOTE_NAME" ]
    then
        help
        exit 1
    fi
}

resolve_domain_name()
{
    normalize_address "$@"
}

normalize_address()
{
    local IP
    [ "$1" ] || return
    IP=$(getent ahosts "$1")
    IP=${IP%% *}
    [ "$IP" ] || return
    echo "$IP"
}

validate_remote_ip()
{
    REMOTE_IP=$(normalize_address "${REMOTE_IP:-$REMOTE_NAME}")
}

validate_remote_name()
{
    domain_name_regexp='^[[:alpha:]][-.[:alnum:]]*[[:alnum:]]*$'
    [[ $REMOTE_NAME =~ $domain_name_regexp ]]
}

validate_remote_key_type()
{
    [ "$REMOTE_KEY_TYPE" = rsa ]
}

validate_local_key()
{
    case "$LOCAL_KEY" in
        */*) ;;
        *) LOCAL_KEY=/etc/ssh/$LOCAL_KEY ;;
    esac
    [ -f "$LOCAL_KEY" -a -r "$LOCAL_KEY" ] || die "could not read local key (filename=$LOCAL_KEY)"

    LOCAL_KEY_DEST_BASENAME=$(sshfp_rsa_filename_string "$LOCAL_KEY") || die "parsing local key (filename=$LOCAL_KEY)"
    LOCAL_PRIVATE_KEY_DEST=/etc/swanctl/private/$LOCAL_KEY_DEST_BASENAME
    LOCAL_PUBLIC_KEY_DEST=/etc/swanctl/pubkey/$LOCAL_KEY_DEST_BASENAME.pub
}

main()
{
    parse_options "$@"

    # The validation functions modify the values to normalize them.
    validate_remote_name     || die 'invalid remote name'
    validate_remote_ip       || die 'invalid remote ip'
    validate_remote_key_type || die 'invalid remote key type'
    validate_local_key       || die 'invalid local key'

    if [ "$NO_ACT" ]
    then
        exec 2>&1
        # Start with the remote public key, to fail early if the server is
        # unavailable.
        install_remote_public_rsa_key
        install_local_private_rsa_key
        test_new_config
    else
        die unimplemented
    fi
    exit
}

test_new_config()
{
    NO_ACT ipsec stop

    install_stronswan_config

    NO_ACT ipsec start
    NO_ACT sleep 2
    NO_ACT swanctl -c
    NO_ACT ipsec listpubkeys
    NO_ACT ipsec up "${REMOTE_NAME}"
}

write_if_successful()
{
    local out="$1" f
    [ "$2" = -- ] || return
    shift 2
    f=$(mktemp) || return
    if "$@" > "$f"
    then
        if [ "$NO_ACT" ]
        then
            simulate_write "$f" "$out"
            rm -f "$f"
        else
            mv "$f" "$out"
        fi
    else
        rm -f "$f"
        return 1
    fi
}

simulate_write()
{
    (
        exec >&2
        echo "Write $2:"
        case "$(file --mime-encoding "$1")" in
            *': binary') xxd "$1" ;;
            *) cat "$1" ;;
        esac | sed 's/^/    /'
        echo
    )
}

quiet_if_successful()
{
    local t=$(mktemp)
    if "$@" 2>"$t"
    then
        rm -f "$t"
    else
        cat "$t" >&2
    fi
}

write_public_rsa_key()
{
    quiet_if_successful openssl rsa -in "$1" -outform DER -pubout
}

write_private_rsa_key()
{
    quiet_if_successful openssl rsa -in "$1" -outform DER
}

write_remote_rsa_key()
{
    case "$REMOTE_KEY_TYPE" in
        rsa) ssh-keygen -e -f "$1" -m PEM | quiet_if_successful openssl rsa -RSAPublicKey_in -outform DER ;;
        *) echo "Unsupported key type." >&2; exit 1 ;;
    esac
}

sshfp_rsa_filename_string()
{
    local keytype=1 hashtype=2
    ssh-keygen -r. -f "$1" | sed -ne "/^. IN SSHFP $keytype $hashtype / { s/. IN //; y/ /_/; p; q; }"
}


install_local_private_rsa_key()
{
    private_key_tmp=$(mktemp) || return
    cp "$LOCAL_KEY" "$private_key_tmp"
    ssh-keygen -N '' -p -m PEM -f "$private_key_tmp" >/dev/null 2>&1
    trap 'rm -f "$private_key_tmp"' EXIT

    write_if_successful "$LOCAL_PRIVATE_KEY_DEST" -- write_private_rsa_key "$private_key_tmp"
    write_if_successful "$LOCAL_PUBLIC_KEY_DEST"  -- write_public_rsa_key  "$private_key_tmp"

    trap - EXIT
    rm -f "$private_key_tmp"
}

scan_knownhosts_files()
{
    local host="$1" f files
    [ "$host" ] || return
    files=$(ssh -G "$host" | sed -E -ne 's/(global|user)knownhostsfile //p')
    for f in $files
    do
        [ -e "$f" ] || continue
        egrep -v '^(#|$)' "$f" | while read _hosts keytype key comment
        do
            echo "$keytype $key"
        done
    done
}

find_known_ssh_host_rsa_key_by_name()
{
    local target="$1" name="$2" keytype_wanted='ssh-rsa'
    scan_knownhosts_files "$name" | (
        while read keytype key
        do
            [ "$keytype" = "$keytype_wanted" ] || continue
            notice "found host key: $name $keytype $key"
            echo "$keytype $key" > "$target"
            exit
        done
        false
    )
}

install_remote_public_rsa_key()
{
    trap 'rm -f "$t"' EXIT
    t=$(mktemp)

    if find_known_ssh_host_rsa_key_by_name "$t" "$REMOTE_NAME"
    then
        notice "using host key from OpenSSH KnownHostsFiles for $REMOTE_NAME"
    else
        notice "scanning the network for host keys for $REMOTE_NAME"
        ./ssh-update-host-keys "$REMOTE_NAME" || die ssh-update-host-keys
        find_known_ssh_host_rsa_key_by_name "$t" "$REMOTE_NAME" || die "could not find host rsa key for $REMOTE_NAME"
    fi

    REMOTE_PUBLIC_KEY_DEST=/etc/swanctl/pubkey/$(sshfp_rsa_filename_string "$t").pub
    write_if_successful "$REMOTE_PUBLIC_KEY_DEST" -- write_remote_rsa_key "$t"

    trap - EXIT
    rm -f "$t"
}

strongswan_config()
{
    local conn="$1" remote_addrs="$2" local_key="$3"
    local public_key_file="$4" private_key_file="$5" remote_public_key_file="$6"
    local remote_ts=0::0/0 vips=::
    id=$(rsa_key_to_ip_suffix "$local_key") || return
    sed -e 's/^        //' <<END
        connections {
            ${conn} {
                remote_addrs = ${remote_addrs}
                vips = ${vips}
                local {
                    pubkeys = ${public_key_file}
                    id = ${id}
                }
                remote {
                    id = "${remote_addrs}"
                    pubkeys = ${remote_public_key_file}
                }
                children {
                    child {
                        remote_ts = ${remote_ts}
                        dpd_action = restart
                    }
                }
            }
        }
        secrets {
            private {
                file = ${private_key_file}
            }
        }
END
}

rsa_key_to_ip_suffix()
{
    local keytype=1 hashtype=2
    ssh-keygen -r . -f "$1" | sed -E -ne 's/^. IN SSHFP '"$keytype $hashtype"' .{48}(.{4})(.{4})(.{4})(.{4})$/\1:\2:\3:\4/p'
}

NO_ACT()
{
    [ "$NO_ACT" ] || "$@"
}

install_stronswan_config()
{
    write_if_successful /etc/swanctl/conf.d/"$REMOTE_NAME".conf -- \
                       strongswan_config \
                                "$REMOTE_NAME" \
                                "$REMOTE_IP" \
                                "$LOCAL_KEY" \
                                "$LOCAL_PUBLIC_KEY_DEST" \
                                "$LOCAL_PRIVATE_KEY_DEST" \
                                "$REMOTE_PUBLIC_KEY_DEST"
}

main "$@"