Auto update iptables DDWRT

custom script:

wan=`nvram get wan_ipaddr`
last=`cat /tmp/last_wan_ipaddr`
echo "WAN IP: $wan" > /tmp/ipv6forward.log
echo "Last WAN IP: $last" >> /tmp/ipv6forward.log
# Check if IP is updated
if [ "$wan" != "$last" ]; then
  echo "New WAN IP detected." >> /tmp/ipv6forward.log
  # If this is the first time script is adding rules, add a FILTER rule that accept the DNAT FORWARD rule
  if [ -f /tmp/last_wan_ipaddr ]; then
    # Not first time, delete old DNAT
    iptables -t nat -D PREROUTING -j DNAT -d $last -p 41 --to-destination >> /tmp/ipv6forward.log    
    # First time, wait for router to settle (ddwrt will clear iptables on startup)
    sleep 30
    # Remove DROP policy
    iptables -t filter -D FORWARD -j DROP >> /tmp/ipv6forward.log
    # Add DNAT rule
    iptables -t filter -A FORWARD -j ACCEPT -p 41 -d >> /tmp/ipv6forward.log
    # Add DROP polocy (last place)
    iptables -t filter -A FORWARD -j DROP >> /tmp/ipv6forward.log
  iptables -t nat -A PREROUTING -j DNAT -p 41 -d $wan --to-destination >> /tmp/ipv6forward.log
  # write wan_ipaddr to tmp
  echo $wan > /tmp/last_wan_ipaddr

startup script:

nvram get rc_custom > /tmp/
chmod +x /tmp/


* * * * * root /tmp/

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>