host info updates
[distro-setup] / vpn-mail-forward
1 #!/bin/bash
2 # I, Ian Kelling, follow the GNU license recommendations at
3 # https://www.gnu.org/licenses/license-recommendations.en.html. They
4 # recommend that small programs, < 300 lines, be licensed under the
5 # Apache License 2.0. This file contains or is part of one or more small
6 # programs. If a small program grows beyond 300 lines, I plan to switch
7 # its license to GPL.
8
9 # Copyright 2024 Ian Kelling
10
11 # Licensed under the Apache License, Version 2.0 (the "License");
12 # you may not use this file except in compliance with the License.
13 # You may obtain a copy of the License at
14
15 # http://www.apache.org/licenses/LICENSE-2.0
16
17 # Unless required by applicable law or agreed to in writing, software
18 # distributed under the License is distributed on an "AS IS" BASIS,
19 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20 # See the License for the specific language governing permissions and
21 # limitations under the License.
22
23
24 set -eE -o pipefail
25 trap 'echo "$0:$LINENO:error: \"$BASH_COMMAND\" returned $?" >&2' ERR
26 m() { printf "%s\n" "$*"; "$@"; }
27 found=false
28
29 ifname=$1
30 shift
31
32 # wait up to 10 seconds for the gateway to appear
33 for ((i=0; i<10; i++)); do
34 gw=$(/usr/sbin/ip route | sed -rn 's/^default via .* dev (\S+).*/\1/p')
35 if [[ $gw ]]; then
36 found=true
37 fi
38 sleep 1
39 done
40 if ! $found; then
41 echo $0: error: couldnt find gateway interface in 10 seconds >&2
42 exit 1
43 fi
44 do-forward() {
45 cmd=$1; shift
46 for port; do
47 m /sbin/iptables -t nat $cmd PREROUTING -i $gw -p tcp -m tcp --dport $port -j DNAT --to-destination 10.8.0.4
48 m /sbin/ip6tables -t nat $cmd PREROUTING -i $gw -p tcp -m tcp --dport $port -j DNAT --to-destination 2600:3c00:e002:3800::4
49 done
50 # for bk to talk to MAIL_HOST, only need port 25.
51 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
52 # we could leave these on all the time but its convenient to do it here
53 m /sbin/iptables $cmd FORWARD -i $ifname -o $gw -j ACCEPT
54 m /sbin/iptables $cmd FORWARD -i $gw -o $ifname -j ACCEPT
55
56 case $ifname in
57 wg*)
58 /sbin/iptables -t nat $cmd POSTROUTING -s 10.8.0.0/24 -o $gw -j MASQUERADE
59 /sbin/ip6tables -t nat $cmd POSTROUTING -s 2600:3c00:e002:3800::/64 -o $gw -j MASQUERADE
60 ;;
61 esac
62
63 }
64
65 ports=(25 143 587)
66 case $1 in
67 start)
68 do-forward -A ${ports[@]}
69 ;;
70 stop)
71 do-forward -D ${ports[@]}
72 ;;
73 *)
74 echo "$0: error: expected 1 argument of start or stop"
75 exit 1
76 ;;
77 esac