Skip to content

Instantly share code, notes, and snippets.

@WoozyMasta
Last active February 14, 2023 13:13
Show Gist options
  • Save WoozyMasta/6c9703b88346f44f9601b47c12d737e3 to your computer and use it in GitHub Desktop.
Save WoozyMasta/6c9703b88346f44f9601b47c12d737e3 to your computer and use it in GitHub Desktop.
Wireguard PostUp PostDown script
#!/usr/bin/env bash
# wg-post %i UP/DOWN
set -euo pipefail
: "${WG_IFACE:=${1:-wg0}}"
: "${WG_ACTION:=${2:-down}}"
: "${WG_CONF:=/etc/wireguard/$WG_IFACE.conf}"
[ -f "$WG_CONF" ] || { >&2 echo "File $WG_CONF not accessible"; exit 1; }
: "${WG_CHAIN:=WIREGUARD_$WG_IFACE}"
: "${WG_NET:=$(
grep -w1oP '^Address\s*=\s*\K(\d{1,3}\.?){3}\.\d{1,3}/\d{1,2}' "$WG_CONF"
)}"
: "${WG_OUT_IFACE:=$(route | grep '^default' | grep -o '[^ ]*$')}"
if [ "${WG_ACTION,,}" == 'up' ]; then
iptables -t nat -I POSTROUTING -o "$WG_OUT_IFACE" -j MASQUERADE -s "$WG_NET"
# Add a WIREGUARD_wg0 chain to the FORWARD chain
iptables -N "$WG_CHAIN"
iptables -A FORWARD -j "$WG_CHAIN"
# Accept related or established traffic
iptables -A "$WG_CHAIN" -o "$WG_IFACE" -m conntrack \
--ctstate RELATED,ESTABLISHED -j ACCEPT
# Accept traffic from any Wireguard IP address connected to the server
iptables -A "$WG_CHAIN" -s "$WG_NET" -i "$WG_IFACE" -j ACCEPT
# Drop everything else coming through the Wireguard interface
iptables -A "$WG_CHAIN" -i "$WG_IFACE" -j DROP
# Return to FORWARD chain
iptables -A "$WG_CHAIN" -j RETURN
else
iptables -t nat -D POSTROUTING -o "$WG_OUT_IFACE" -j MASQUERADE -s "$WG_NET"
# Remove and delete the WIREGUARD_wg0 chain
iptables -D FORWARD -j "$WG_CHAIN"
iptables -F "$WG_CHAIN"
iptables -X "$WG_CHAIN"
fi
#!/usr/bin/env bash
# wireguard post up/down
# place this in /usr/sbin/wg-post and set exec attr
# Usage:
# PostUp = wg-post %i up
# PostDown = wg-post %i down
set -euo pipefail
wg_if="${1:-wg0}"
net=$(
grep -oP '^Address\s*=\s*\K(\d{1,3}\.?){3}\.\d{1,3}/\d{1,2}' \
"/etc/wireguard/$wg_if.conf"
)
df_if=$(route | grep '^default' | grep -o '[^ ]*$')
manage-network() {
local st=${1:-D} mode=${2:-0} action=${3:-ACCEPT}
sysctl -w -q net.ipv4.ip_forward="$mode"
iptables -P FORWARD "$action"
iptables "-$st" FORWARD -i "$wg_if" -o "$wg_if" -s "$net" -d "$net" -j ACCEPT
iptables "-$st" FORWARD -i "$wg_if" -o "$df_if" -s "$net" -j ACCEPT
iptables "-$st" FORWARD -i "$df_if" -o "$wg_if" -d "$net" -j ACCEPT
iptables -t nat "-$st" POSTROUTING -o "$df_if" -j MASQUERADE
}
if [ "${2:-down}" == 'up' ]; then
manage-network A 1 DROP
echo 'PostUp hook executed'
else
manage-network D 0 ACCEPT
echo 'PostDown hook executed'
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment