#!/bin/bash set -eE -o pipefail trap 'echo "$0:$LINENO:error: \"$BASH_COMMAND\" returned $?" >&2' ERR m() { printf "%s\n" "$*"; "$@"; } found=false ifname=$1 shift # wait up to 10 seconds for the gateway to appear for ((i=0; i<10; i++)); do gw=$(/usr/sbin/ip route | sed -rn 's/^default via .* dev (\S+).*/\1/p') if [[ $gw ]]; then found=true fi sleep 1 done if ! $found; then echo $0: error: couldnt find gateway interface in 10 seconds >&2 exit 1 fi do-forward() { cmd=$1; shift for port; do m /sbin/iptables -t nat $cmd PREROUTING -i $gw -p tcp -m tcp --dport $port -j DNAT --to-destination 10.8.0.4 m /sbin/ip6tables -t nat $cmd PREROUTING -i $gw -p tcp -m tcp --dport $port -j DNAT --to-destination 2600:3c00:e002:3800::4 done # for bk to talk to MAIL_HOST, only need port 25. ip6tables -t nat $cmd PREROUTING -i $ifname -s 2600:3c00:e002:3800::5 -d 2600:3c00:e000:280::2 -p tcp -m tcp --dport 25 -j DNAT --to-destination 2600:3c00:e002:3800::4 # we could leave these on all the time but its convenient to do it here m /sbin/iptables $cmd FORWARD -i $ifname -o $gw -j ACCEPT m /sbin/iptables $cmd FORWARD -i $gw -o $ifname -j ACCEPT case $ifname in wg*) /sbin/iptables -t nat $cmd POSTROUTING -s 10.8.0.0/24 -o $gw -j MASQUERADE /sbin/ip6tables -t nat $cmd POSTROUTING -s 2600:3c00:e002:3800::/64 -o $gw -j MASQUERADE ;; esac } ports=(25 143 587) case $1 in start) do-forward -A ${ports[@]} ;; stop) do-forward -D ${ports[@]} ;; *) echo "$0: error: expected 1 argument of start or stop" exit 1 ;; esac