#!/bin/bash
# central firewall script
# called by /sbin/firewall.on

PATH=/usr/sbin:/sbin:/bin:/usr/bin

logger -t firewall "running firewall script $PID"

if [ -f /etc/default/firewall ]; then
   source /etc/default/firewall
fi

source /lib/firewall/firewall.off

( echo "define ifwan = $IFWAN" ;
#  echo "define sshbursttime = ${SSHBURSTTIME:-1s}"; # doesn't work; workaround sed
#  echo "define sshburstcount = ${SSHBURSTTIME:-6}";
#  echo "define sshreptime = ${SSHBLOCKTIME:-6s}";
#  echo "define sshblocktime = ${SSHBLOCKTIME:-5m}";
  cat <<EOF
table ip ipv4firewall {

    chain input {
        type filter hook input priority 0; policy drop;
        iifname "lo" accept
        iifname \$ifwan icmp type echo-request limit rate 5/second counter accept
        iifname \$ifwan tcp dport 22 goto sshin 
        iifname \$ifwan goto wanin
    }

    chain forward {
        type filter hook forward priority 0; policy drop;
    }

    chain output {
        type filter hook output priority 0; policy drop;
        oifname "lo" accept
        counter accept
        # oifname $ifwan goto wanout
    }

EOF
  cat /etc/firewall/nft/*.chain
  cat /lib/firewall/nft/sshin.chain
  echo "}" ) \
    | sed "1,\$ s/\$sshbursttime\b/${SSHBURSTTIME:-2s}/g; 1,\$ s/\$sshburstcount\b/${SSHBURSTCOUNT:-6}/g; 1,\$ s/\$sshreptime\b/${SSHREPTIME:-6s}/g; 1,\$ s/\$sshblocktime\b/${SSHBLOCKTIME:-5m}/g; " \
    | nft -f -
