Skip to content

Instantly share code, notes, and snippets.

@denpamusic
Last active November 21, 2022 01:48
Show Gist options
  • Save denpamusic/3594166c578dbd55e6aed4c530b9a29c to your computer and use it in GitHub Desktop.
Save denpamusic/3594166c578dbd55e6aed4c530b9a29c to your computer and use it in GitHub Desktop.
Script to forward port through vpn tunnel on Ubuntu/Debian.
#!/usr/bin/env bash
WAN_IFACE="eth0"
VPN_IFACE="wg0"
IPTABLES=/usr/sbin/iptables
NP=/usr/sbin/netfilter-persistent
default_drop_forward() {
$IPTABLES -P FORWARD DROP
}
iface_to_ip() {
local iface="$1"
ip -4 -o addr show "$iface" | awk '{print $4}' | cut -d "/" -f 1
}
forward_port() {
local port="$1"
local proto="$2"
local gw peer ipt_options last_pre_nat_rule last_post_nat_rule
[ -z "$port" ] && return 1
[ -z "$proto" ] && proto=tcp
case "$proto" in
tcp)
ipt_options="--syn"
;;
tcpudp|udptcp)
forward_port "$port" tcp
forward_port "$port" udp
return
;;
*)
ipt_options=""
;;
esac
last_pre_nat_rule=$($IPTABLES -t nat -L PREROUTING --line-numbers | tail -n +3 | tail -1 | awk '{print $1}')
[ -z "$last_pre_nat_rule" ] && last_pre_nat_rule=1
last_post_nat_rule=$($IPTABLES -t nat -L POSTROUTING --line-numbers | tail -n +3 | tail -1 | awk '{print $1}')
[ -z "$last_post_nat_rule" ] && last_post_nat_rule=1
gw=$(iface_to_ip "$VPN_IFACE")
[ -z "$gw" ] && return 1
peer=${gw%?}2
$IPTABLES -I FORWARD 1 -i $WAN_IFACE -o $VPN_IFACE -p $proto -m $proto --dport $port $ipt_options -m conntrack --ctstate NEW -m comment --comment "${VPN_IFACE}-${proto}-port-${port}-forward-rule" -j ACCEPT
$IPTABLES -t nat -I PREROUTING "$last_pre_nat_rule" -i $WAN_IFACE -p $proto -m $proto --dport "$port" -m comment --comment "${VPN_IFACE}-${proto}-port-${port}-nat-rule" -j DNAT --to-destination "$peer"
$IPTABLES -t nat -I POSTROUTING "$last_post_nat_rule" -o $VPN_IFACE -p $proto -m $proto --dport "$port" -d "$peer" -m comment --comment "${VPN_IFACE}-${proto}-port-${port}-nat-rule" -j SNAT --to-source "$gw"
}
PORT="$1"
PROTO="$2"
[ -z "$PORT" ] && exit 1
default_drop_forward
forward_port "$PORT" "$PROTO"
$NP save
$NP reload
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment