Hairpin NAT Hotplug script

Hi!
I have quite some subnets connected to my router. I want all of them to be able to be able to enter my DMZ using the external Router-IP (Port Forwarding). Using the OpenWRT-Port-Forwardings, I could access it from outside, but not from any interface inside.

Therefore, I wrote myself a quick&dirty hotplug-script today as a replacement to the uci port forwardings and got it working. Just wanted to share the code if someone is interested:
(USAGE AT YOUR OWN RISK)
(/etc/hotplug.d/iface/25-HairpinNAT)

#!/bin/sh
WANT_IF=wan
PORTS="22,80,110,443"
DEST_IP="the IP of the destination"
COMMENT="MYNAT_${WANT_IF}_${PORTS}_${DEST_IP}" #IMPORTANT:Has to be unique in order to delete the correct rule on ifdown

[ "$INTERFACE" = "$WANT_IF" ] || exit 0

source /lib/functions/network.sh
case "$ACTION" in
	ifup)
		network_get_ipaddr ipaddr "$WANT_IF"
		iptables -t nat -I PREROUTING -d $ipaddr -p tcp -m tcp --match multiport --dports "$PORTS" -m comment --comment "$COMMENT" -j DNAT --to-destination "$DEST_IP"
		;;
	ifdown)
		#DELETE the last Rule FIFO-style; delete it delayed some hours until all dns caches are cleared (the DMZ can be reached using both IPs during this duration)
		(sleep 10000; iptables -t nat -D PREROUTING $(iptables -t nat --line-number -nL PREROUTING | grep "$COMMENT" | awk '{print $1}' | tail -n 1);) &
		;;
esac

If you have some improvements, you are very welcome!

  • Are there some scenarios in which such code could lead to bad events? (Deleting the wrong iptables rule?)
  • Is the code well enough to put it somewhere into the wiki?

God bless you!
Thomas