#!/bin/sh

# Firewall script
# Copyright (C) 2016  Dominic Walden

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

if ! [ -x /sbin/iptables ]; then  
    exit 0
fi

fw_start () {

    iptables-restore < /etc/iptables.rules

    # Other network protections
    # (some will only work with some kernel versions)
    echo 1 > /proc/sys/net/ipv4/tcp_syncookies
    echo 0 > /proc/sys/net/ipv4/ip_forward 
    echo 1 > /proc/sys/net/ipv4/icmp_echo_ignore_broadcasts 
    echo 1 > /proc/sys/net/ipv4/conf/all/log_martians 
    #echo 1 > /proc/sys/net/ipv4/ip_always_defrag
    echo 1 > /proc/sys/net/ipv4/icmp_ignore_bogus_error_responses
    echo 1 > /proc/sys/net/ipv4/conf/all/rp_filter
    echo 0 > /proc/sys/net/ipv4/conf/all/send_redirects
    echo 0 > /proc/sys/net/ipv4/conf/all/accept_source_route

}

fw_stop () {
    /sbin/iptables -F
    /sbin/iptables -t nat -F
    /sbin/iptables -t mangle -F
    /sbin/iptables -P INPUT DROP
    /sbin/iptables -P FORWARD DROP
    /sbin/iptables -P OUTPUT ACCEPT
}

fw_clear () {
    /sbin/iptables -F
    /sbin/iptables -t nat -F
    /sbin/iptables -t mangle -F
    /sbin/iptables -P INPUT ACCEPT
    /sbin/iptables -P FORWARD ACCEPT
    /sbin/iptables -P OUTPUT ACCEPT
}

case "$1" in
    start|restart)
        echo -n "Starting firewall.."
        fw_stop 
        fw_start
        echo "done."
        ;;
    stop)
        echo -n "Stopping firewall.."
        fw_stop
        echo "done."
        ;;
    clear)
        echo -n "Clearing firewall rules.."
        fw_clear
        echo "done."
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|clear}"
        exit 1
        ;;
esac
exit 0
