#!/bin/bash # I, Ian Kelling, follow the GNU license recommendations at # https://www.gnu.org/licenses/license-recommendations.en.html. They # recommend that small programs, < 300 lines, be licensed under the # Apache License 2.0. This file contains or is part of one or more small # programs. If a small program grows beyond 300 lines, I plan to switch # its license to GPL. # Copyright 2024 Ian Kelling # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. 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