-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathstart
More file actions
executable file
·96 lines (84 loc) · 2.49 KB
/
start
File metadata and controls
executable file
·96 lines (84 loc) · 2.49 KB
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
#!/usr/bin/env bash
# Get public IP
if [ "$PUBLIC_IP" = "1.2.3.4" ]; then
PUBLIC_IP=$(wget -q -O - ifconfig.so)
export PUBLIC_IP
fi
# postup script
if [ ! -e /etc/wireguard/postup ]; then
cat >/etc/wireguard/postup <<EOF
#!/bin/sh
iptables -t nat -A POSTROUTING -o $INTERFACE -j MASQUERADE
iptables -A FORWARD -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --set-mss $TCPMSS
iptables -t mangle -A POSTROUTING -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --set-mss $TCPMSS
EOF
chmod +x /etc/wireguard/postup
fi
# postup script
if [ ! -e /etc/wireguard/postdown ]; then
cat >/etc/wireguard/postdown <<EOF
#!/bin/sh
iptables -t nat -D POSTROUTING -o $INTERFACE -j MASQUERADE
iptables -D FORWARD -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --set-mss $TCPMSS
iptables -t mangle -D POSTROUTING -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --set-mss $TCPMSS
EOF
chmod +x /etc/wireguard/postup
fi
# Initialize first key if it doesn't exist
if [ ! -e /etc/wireguard/wg0.conf ]; then # Was wg*.conf
echo "$(date): wireguard init config - /etc/wireguard/wg0.conf"
wg genkey | tee /etc/wireguard/wg0.key | wg pubkey >/etc/wireguard/wg0.pub
SERV_KEY=$(cat /etc/wireguard/wg0.key)
cat >/etc/wireguard/wg0.conf <<EOF
[Interface]
Address = $SUBNET_IP
ListenPort = $PORT
PrivateKey = $SERV_KEY
PostUp = /etc/wireguard/postup
PostDown = /etc/wireguard/postdown
EOF
chmod go-rw /etc/wireguard/wg0.key /etc/wireguard/wg0.conf
fi
wg_up() {
for conf in /etc/wireguard/wg*.conf; do
echo "$(date): wireguard up interface - $conf"
wg-quick up "$conf"
done
# Print first configuration on each container start (useful for quick setup)
addclient test
for NAME in /etc/wireguard/clients/*.pub; do
PUB=$(cat "$NAME")
CONF=${NAME/pub/conf}
IP=$(awk '/Address/{print $3}' "$CONF" | awk -F/ '{print $1}')
ALLOW=$(awk '/^AllowedIPs/{print $3}' "$CONF")
if [ "$ALLOW" != "" ]; then
IP="$IP,$ALLOW"
fi
wg set wg0 peer "$PUB" allowed-ips "$IP"
done
}
wg_down() {
for conf in /etc/wireguard/wg*.conf; do
echo "$(date): wireguard down interface - $conf"
wg-quick down "$conf"
done
}
wg_up
if [ "$NAT" -eq 1 ]; then
echo "$(date): setup NAT"
iptables -t nat -A POSTROUTING -o "$INTERFACE" -j MASQUERADE
fi
# Handle shutdown behavior
finish() {
echo "$(date): stopping wireguard"
wg_down
if [ "$NAT" -eq 1 ]; then
iptables -t nat -D POSTROUTING -o "$INTERFACE" -j MASQUERADE
fi
exit 0
}
trap finish TERM INT QUIT
while inotifywait -e modify -e create /etc/wireguard; do
wg_down
wg_up
done