Skip to content

Instantly share code, notes, and snippets.

@hucsmn
Last active April 25, 2023 05:11
Show Gist options
  • Save hucsmn/7dab453087351d5878d14ad3e4d8008e to your computer and use it in GitHub Desktop.
Save hucsmn/7dab453087351d5878d14ad3e4d8008e to your computer and use it in GitHub Desktop.
NetworkManager dispatcher script for wireguard server ip forwarding
# enable ipv4 forwarding, under /etc/sysctl.d
net.ipv4.ip_forward=1
#!/bin/bash
# NetworkManager-dispatcher.service script, under /etc/NetworkManager/dispatcher.d
# automatically setup ip forwarding in wireguard server
iface="$1"
event="$2"
uuid="" # wireguard nm connection uuid to match
outbound_iface="" # optional, manually specify outbound nic
outbound_ip="" # optional, auto search outbound nic
run() {
echo "[RUN] $@"
$@
}
if [[ "${CONNECTION_UUID}" == "${uuid}" ]]; then
echo "[EVENT] ${event} ${CONNECTION_ID}@${iface}(uuid=${CONNECTION_UUID})"
if [[ -z "${outbound_iface}" ]] && [[ -n "${outbound_ip}" ]]; then
outbound_iface="$(ip -o addr show scope global | grep "${outbound_ip}" | head -n 1 | cut -d' ' -f2)"
fi
case "${event}" in
up)
if [[ -n "${outbound_iface}" ]]; then
run iptables -A FORWARD -i "${iface}" -j ACCEPT
run iptables -A FORWARD -o "${iface}" -j ACCEPT
run iptables -t nat -A POSTROUTING -o "${outbound_iface}" -j MASQUERADE
else
echo '[DEBUG] missing $outbound_iface'
fi
;;
down)
if [[ -n "${outbound_iface}" ]]; then
run iptables -D FORWARD -i "${iface}" -j ACCEPT
run iptables -D FORWARD -o "${iface}" -j ACCEPT
run iptables -t nat -D POSTROUTING -o "${outbound_iface}" -j MASQUERADE
else
echo '[DEBUG] missing $outbound_iface'
fi
;;
*)
echo "[DEBUG] ignore event '${event}'"
;;
esac
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment