Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#!/usr/bin/env bash
set -e
error() {
local sourcefile=$1
local lineno=$2
printf "Error: ${sourcefile}:${lineno}\n\n"
}
trap 'error "${BASH_SOURCE}" "${LINENO}"' ERR
IPTABLES_EXEC="iptables"
ZT_INTERFACE=${ZT_INTERFACE:-}
LAN_INTERFACE=${LAN_INTERFACE:-}
if [ -z "$ZT_INTERFACE" ]; then
echo "ZT_INTERFACE not set"
exit 1
elif [ -z "$LAN_INTERFACE" ]; then
echo "LAN_INTERFACE not set"
exit 1
fi
function add_rules() {
${IPTABLES_EXEC} -t nat -A POSTROUTING -i $ZT_INTERFACE -o $LAN_INTERFACE -j MASQUERADE
${IPTABLES_EXEC} -A FORWARD -i $LAN_INTERFACE -o $ZT_INTERFACE -m state --state RELATED,ESTABLISHED -j ACCEPT
${IPTABLES_EXEC} -A FORWARD -i $ZT_INTERFACE -o $LAN_INTERFACE -j ACCEPT
}
function gen_rules() {
cat <<EOF
*nat
:PREROUTING ACCEPT [0:0]
:INPUT ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
:POSTROUTING ACCEPT [0:0]
-A POSTROUTING -o ${LAN_INTERFACE} -j MASQUERADE
COMMIT
*filter
:INPUT ACCEPT [0:0]
:FORWARD DROP [0:0]
:OUTPUT ACCEPT [0:0]
-A FORWARD -i ${LAN_INTERFACE} -o ${ZT_INTERFACE} -m state --state RELATED,ESTABLISHED -j ACCEPT
-A FORWARD -i ${ZT_INTERFACE} -o ${LAN_INTERFACE} -j ACCEPT
COMMIT
EOF
}
USAGE=$(cat <<'EOF'
Usage zerotier-nat.sh
add-rules Add rules to netfilter by invoking iptables
gen-rules Generate iptables persistent rules
ZT_INTERFACE and LAN_INTERFACE must be set before invoking add-rules or gen-rules
EOF
)
if [ -z "$1" ] || [ "$1" == "-h" ] || [ "$1" == "--help" ]; then
echo "${USAGE}"
exit 0
elif [ "$1" == "add-rules" ]; then
add_rules
elif [ "$1" == "gen-rules" ]; then
gen_rules
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment