forked from cmulk/wireguard-docker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrun
94 lines (69 loc) · 2.5 KB
/
run
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
#!/bin/bash
# Find a Wireguard interface
interfaces=`find /etc/wireguard -name "*wg0*.conf" -type f`
if [[ -z $interfaces ]]; then
echo "$(date): Interface not found in /etc/wireguard" >&2
exit 1
fi
# Start WG
start_interfaces() {
for interface in $interfaces; do
echo "$(date): Starting Wireguard $interface"
wg-quick up $interface
done
}
# Shut down interface
stop_interfaces() {
echo "$(date): Shutting down vpn"
for interface in $interfaces; do
wg-quick down $interface
done
}
# Bring up WG
start_interfaces
## Verify thet wireguard module is installed:
wg_module=`find /lib/modules/$(uname -r) -type f -name '*.ko' | grep -i wireguard`
echo "Module output: $wg_module"
if [[ -z $wg_module ]]; then
echo "$(date): Wireguard module not installed.. Installing" >&2
apt update ; apt install -y linux-headers-amd64 wireguard-dkms
else
echo "Wireguard module seems to be installed: $wg_module Moving on... "
fi
# Add masquerade rule for NAT'ing VPN traffic bound for the Internet
if [[ $IPTABLES_MASQ -eq 1 ]]; then
echo "$(date): ---INFO--- Adding iptables NAT rule"
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
fi
### Fix route back to local network
if [[ -z $LOCAL_NETWORK ]]; then
echo "$(date): ---INFO--- No network provides. Ignoring route back to local network"
else
echo "$(date): ---INFO--- Adding route back to local network: $LOCAL_NETWORK"
gw=$(ip route |awk '/default/ {print $3}')
ip route add to $LOCAL_NETWORK via $gw dev eth0
fi
## Get the endpoint IP in the wg config
endpoint_in_conf=$(grep -Po 'Endpoint\s=\s\K[^:]*' $interfaces | ( read hostname ;dig $hostname +short ))
## Get the active endpoint from WireGuard
function active_wg {
active_endpoint=$( wg | grep -Po 'endpoint:\s\K[^:]*')
}
trap stop_interfaces SIGTERM SIGINT SIGQUIT
active_wg
echo "$(date): ---INFO--- Endpoint in config: $endpoint_in_conf"
echo "$(date): ---INFO--- Active EndPoint : $active_endpoint"
sleep 3
# Every minute we check to our IP address
while [[ $endpoint_in_conf == $active_endpoint ]] && [[ $active_endpoint =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]];
do
# Update the active wg endpoint ip
active_wg
# For debug printing endpoints
# echo "$(date): ---INFO--- Endpoint in config: $endpoint_in_conf"
# echo "$(date): ---INFO--- Active EndPoint : $active_endpoint"
sleep 10;
done
# done
echo "$(date): Expected endpoint not found in WireGuard. Shuting down!!"
function stop_interfaces