-
Notifications
You must be signed in to change notification settings - Fork 1
/
tunnel.sh
executable file
·97 lines (80 loc) · 2.49 KB
/
tunnel.sh
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
#!/bin/bash
set -Eeuo pipefail
trap "down &> /dev/null" ERR
function set_dns_get_ipv4 {
local -r username=$1
local -r update_key=$2
local -r tunnel_id=$3
local -r base_url=$4
local -r url="https://$username:$update_key@$base_url/nic/update?hostname=$tunnel_id"
mapfile -td " " -n 2 status_ip < <(\
setpriv --reuid=1000 --regid=1000 --clear-groups \
curl -4s "$url" | tr -d "\n")
# See https://help.dyn.com/server-access-api/return-codes/ for
# possible returned statuses.
if [[ "${#status_ip[@]}" -lt 2 ]]; then
echo "Failed with ${status_ip[0]}" >&2
exit 2
fi
local -r status="${status_ip[0]}"
local -r ip="${status_ip[1]}"
if [[ "$status" != "good" ]] && [[ "$status" != "nochg" ]]; then
echo "Bad response: ${status_ip[*]}" >&2
exit 3
elif [[ "$ip" == "127.0.0.1" ]]; then
echo "Failed with ${status_ip[*]}; unreachable via ICMP" >&2
exit 4
fi
echo "$ip"
}
# shellcheck disable=SC2153
function main {
if [[ $# -ne 1 ]]; then
echo "$0 takes exactly one argument; $# provided"
exit 1
fi
export interface="${INTERFACE:-he-ipv6}"
export username="$USERNAME"
export update_key="$UPDATE_KEY"
export tunnel_id="$TUNNEL_ID"
export server_ipv4="$SERVER_IPV4"
export client_ipv6="$CLIENT_IPV6"
export base_url="$BASE_URL"
if [[ $1 == "up" ]]; then
up
elif [[ $1 == "down" ]]; then
down
else
echo "Argument must be either \"up\" or \"down\"" >&2
exit 1
fi
}
function up {
local client_ipv4
client_ipv4="$(set_dns_get_ipv4 \
"$username" "$update_key" "$tunnel_id" "$base_url")"
# If forwarding protocol 41 use local IPv4 address instead.
#client_ipv4="$(ip -j -4 route | jq -r .[0].prefsrc)"
ip tunnel add "$interface" \
mode sit \
remote "$server_ipv4" \
local "$client_ipv4" \
ttl 255
# Kernel bug workaround
# Assuming server_ipv6=2001:470:18:8e3::1/64
#ip tunnel 6rd dev "$interface" \
# 6rd-prefix 2001:470:18:8e3::1/64 \
# 6rd-relay_prefix $server_ipv4/32
ip link set "$interface" up mtu 1480
ip address add "$client_ipv6" dev "$interface"
ip route add ::/0 dev "$interface"
}
function down {
ip route del ::/0 dev "$interface"
ip address del "$client_ipv6" dev "$interface"
ip link set "$interface" down
ip tunnel del "$interface"
}
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
main "$@"
fi