Skip to content

Instantly share code, notes, and snippets.

@mpontillo
Last active March 30, 2017 16:21
Show Gist options
  • Save mpontillo/711444fcdc3112907014d4aab97e306f to your computer and use it in GitHub Desktop.
Save mpontillo/711444fcdc3112907014d4aab97e306f to your computer and use it in GitHub Desktop.
#!/bin/bash -x
if ! iptables -t filter -L FORWARD | grep PORT_FORWARD; then
iptables -t filter -N PORT_FORWARD
iptables -t filter -I FORWARD -j PORT_FORWARD
fi
if ! iptables -t nat -L PREROUTING | grep PORT_FORWARD_DNAT; then
iptables -t nat -N PORT_FORWARD_DNAT
iptables -t nat -I PREROUTING -j PORT_FORWARD_DNAT
fi
if ! iptables -t nat -L POSTROUTING | grep PORT_FORWARD_SNAT; then
iptables -t nat -N PORT_FORWARD_SNAT
iptables -t nat -I POSTROUTING -j PORT_FORWARD_SNAT
fi
iptables -t filter -F PORT_FORWARD
iptables -t nat -F PORT_FORWARD_DNAT
iptables -t nat -F PORT_FORWARD_SNAT
SNAT_SOURCE="$(ip route get 8.8.8.8 | grep -o 'src.*' | tail -1 | awk '{ print $2 }')"
# Note: entries beginning with # are comments.
# There must not be any whitespace after a comment.
FORWARDS="
#$SNAT_SOURCE,2222,172.16.100.151,22
"
# XXX: It's not clear if the SNAT or POSTROUTING/SNAT rules actually match
# anything in some setups. They might not be required, depending on how
# strict other firewall rules may be.
for forward in $FORWARDS; do
if echo $forward | grep '^#'; then
continue
fi
SOURCE_IP="$(echo $forward | cut -d, -f1)"
SOURCE_PORT="$(echo $forward | cut -d, -f2)"
DEST_IP="$(echo $forward | cut -d, -f3)"
DEST_PORT="$(echo $forward | cut -d, -f4)"
iptables -t filter -A PORT_FORWARD \
-p tcp --dport $SOURCE_PORT -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT
iptables -t nat -A PORT_FORWARD_DNAT \
-p tcp --dport $SOURCE_PORT -j DNAT --to-destination $DEST_IP:$DEST_PORT
iptables -t nat -A PORT_FORWARD_SNAT \
-p tcp -m tcp -s $DEST_IP --sport $DEST_PORT -j SNAT --to-source $SOURCE_IP
done
#!/bin/bash -x
iptables -t filter -F PORT_FORWARD
iptables -t filter -D FORWARD -j PORT_FORWARD
iptables -t filter -X PORT_FORWARD
iptables -t nat -F PORT_FORWARDING_DNAT
iptables -t nat -D PREROUTING -j PORT_FORWARD_DNAT
iptables -t nat -X PORT_FORWARD_DNAT
iptables -t nat -F PORT_FORWARDING_SNAT
iptables -t nat -D POSTROUTING -j PORT_FORWARD_SNAT
iptables -t nat -X PORT_FORWARD_SNAT
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment