Firewall Example

From Wiki
Jump to navigation Jump to search
#!/bin/sh

if [ -r /lib/lsb/init-functions ]; then
    . /lib/lsb/init-functions
fi

firewall_start()
{
    # Flush all rules
    iptables -F INPUT
    iptables -F OUTPUT
    iptables -F FORWARD

    # Default policies
    iptables -P INPUT   DROP
    iptables -P OUTPUT  ACCEPT
    iptables -P FORWARD DROP

    # Allow everything on the loopback network
    iptables -A INPUT -i lo -j ACCEPT

    # Allow ICMP
    iptables -A INPUT --protocol icmp -j ACCEPT

    # Allow everything from the home server
    iptables -A INPUT --source 123.45.67.89 -j ACCEPT

    # Allow established sessions
    iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

    # Allow incoming SSH sessions
    iptables -A INPUT --protocol tcp --dport 22 --source 123.45.0.0/16 -m state --state NEW -j ACCEPT

    # Allow incoming nfs4
    iptables -A INPUT --protocol tcp --dport 2049 --source 123.45.0.0/16 -m state --state NEW -j ACCEPT

    # Allow samba
    iptables -A INPUT --protocol tcp --dport 139 --source 123.45.0.0/16 -m state --state NEW -j ACCEPT
    iptables -A INPUT --protocol tcp --dport 445 --source 123.45.0.0/16 -m state --state NEW -j ACCEPT

    # Drop intranet broadcasts
    iptables -A INPUT --protocol udp --destination 123.45.67.255 -j DROP

    # Drop other packets
    iptables -A INPUT   -j DROP
    iptables -A FORWARD -j DROP
}

firewall_stop()
{
    # Flush all rules
    iptables -F INPUT
    iptables -F OUTPUT
    iptables -F FORWARD

    # Default policies
    iptables -P INPUT   ACCEPT
    iptables -P OUTPUT  ACCEPT
    iptables -P FORWARD ACCEPT
}

case "$1" in
    start)
        log_begin_msg "Starting firewall..."
        firewall_start
        log_end_msg 0
        ;;

    stop)
        log_begin_msg "Stopping firewall..."
        firewall_stop
        log_end_msg 0
        ;;

    restart)
        log_begin_msg "Restarting firewall..."
        firewall_stop
        firewall_start
        log_end_msg 0
        ;;

    *)
        echo "Usage: $0 {start|stop|restart}"
        exit 1
esac