#!/bin/sh

# Add the IPsec/L2TP rules if they have not already been added
iptables-save | grep -- "-A INPUT -p udp -m udp --dport 500 -j ACCEPT" > /dev/null
if [ $? = 1 ]; then
    # Allow IPSEC connections
    iptables -A INPUT -p udp -m udp --dport 500 -j ACCEPT
    iptables -A INPUT -p udp -m udp --dport 4500 -j ACCEPT

    # Allow L2TP connections
    iptables -A INPUT -p udp -m udp --dport 1701 -j ACCEPT

fi

# If the logdrop rule exists, we need to move it to the end
#   - This helps if our manual rules were added (above).
#   - This also fixes what appears to be a Tomato bug. With some services,
#     like the PPTP server, their rules will be placed after the logdrop
#     rule. The result is incorrectly dropping packets for valid services.
iptables-save | grep -- "-A INPUT -j logdrop" > /dev/null
if [ $? = 0 ]; then
    # Get the number of the logdrop rule in the INPUT chain
    LINENUM=`iptables -L INPUT|grep -nr logdrop|cut -f 1 -d :`
    RULENUM=`expr $LINENUM - 2`

    # Delete the logdrop rule from the INPUT chain
    iptables -D INPUT $RULENUM

    # Readd the logdrop rule at the end of the INPUT chain
    iptables -A INPUT -j logdrop
fi

# Set manual policy (this is needed for clients behind nat, because racoon generates the wrong policy)
#
# Source: http://tomatousb.org/forum/t-625093/ipsec-l2tp-racoon-xl2tpd-tomato-shibby-asus-rt-n16
myServer=`nvram get wan_ipaddr`
ip xfrm policy add src $myServer dst 0.0.0.0/0 proto udp sport 1701 dir out tmpl proto esp mode transport level required
ip xfrm policy add src 0.0.0.0/0 dst $myServer proto udp dport 1701 dir in tmpl proto esp mode transport level required
