#!/bin/sh
#
# Firewall rules
#

PERSISTENCY="/home/charge/persistency"
NFT=/opt/ebee/usr/sbin/nft
ENABLE_IPV4_FORWARDING=/opt/ebee/usr/sbin/ipv4_forwarding

limit_ssh_access_to_interface()
{
    local FILENAME="$1"
    local INTERFACE="$2"
    if [ ! -f $PERSISTENCY/$FILENAME ] && grep -qi 'Off' $PERSISTENCY/${FILENAME}_default 2>/dev/null \
       || grep -qi 'Off' $PERSISTENCY/$FILENAME 2>/dev/null
    then
        $NFT add rule ip global input iifname "$INTERFACE" tcp dport {22,23} drop
    fi
}

# Enable ipv4 forwarding in case of GSM and WAN routing set to 'On'
start_ipv4_forwarding()
{
    # ipv4 forwarding only in case of GSM and WAN routing set to 'On'
    if    ! grep -qi 'GSM' $PERSISTENCY/Type_dl 2>/dev/null \
       || (     ! grep -qi 'On' $PERSISTENCY/WANRouter_tcpip 2>/dev/null \
            &&  ! grep -qi 'GSM' $PERSISTENCY/WANRouter_tcpip 2>/dev/null )
    then
        return
    fi

    $ENABLE_IPV4_FORWARDING --enable
    $NFT add rule ip nat postrouting oifname ppp0 masquerade
    # no proxy
    # $NFT add rule ip nat forward iifname ppp0 oifname ppp0 reject

    echo "WAN routing enabled. LAN packets can be routed via WAN (GSM)"
}

start_firewall()
{
    echo -n "Starting firewall: "

    # load rules from file
    $NFT -f /opt/ebee/etc/nftables.conf

    # start forwarding and masquerading
    start_ipv4_forwarding

    # limiting SSH access to specific interfaces
    # USB
    limit_ssh_access_to_interface "SSHAccessUsb_custom" "br-usb-device"
    # eth0
    limit_ssh_access_to_interface "SSHAccessEthernet_custom" "eth0"
    # GSM
    limit_ssh_access_to_interface "SSHAccessGsm_custom" "ppp0"
    # WLAN
    limit_ssh_access_to_interface "SSHAccessWlanNetwork_custom" "wlan0"
    # WLAN Hotspot
    limit_ssh_access_to_interface "SSHAccessWlanHotspot_custom" "ap0"

    echo "done"
}


case "$1" in
    start)
        start_firewall
        ;;
    stop)
        ;;
    restart|reload)
        "$0" start
        ;;
    *)
        echo "Usage: $0 {start|stop|restart}"
        exit 1
        ;;
esac


# Local variables:
# tab-width: 4
# indent-tabs-mode: nil
# End:
