#!/bin/bash
#
# firwall : Bring up/down the firewall
#
# chkconfig: 2345 08 92
# description: Activate/Deactivate the firewall.
#
# this script should be in /etc/init.d
#
# greetz,
#    harry

IPTABLES=/sbin/iptables

case $1 in
	start)
		echo 1 > /proc/sys/net/ipv4/conf/all/log_martians
		echo 0 > /proc/sys/net/ipv4/ip_forward
		$IPTABLES -F
		$IPTABLES -X
		$IPTABLES -P INPUT   DROP
		$IPTABLES -P OUTPUT  ACCEPT
		$IPTABLES -P FORWARD ACCEPT
		$IPTABLES -N Icmp_Related_And_New
	
		# established,related doorlaten
		$IPTABLES -I INPUT   1 ! -p icmp -m state --state RELATED,ESTABLISHED -j ACCEPT
		# icmp regels behandelen
		$IPTABLES -I INPUT   2 -p   icmp -j Icmp_Related_And_New
		# alles wat niet nieuw is nu... drop (hou je fw logs clean)
		$IPTABLES -I INPUT   3 -m state ! --state NEW -j DROP
	
		# -----------
		# INPUT rules
		# -----------
	
		# default input rules
		$IPTABLES -A INPUT -p tcp --destination-port ssh -j ACCEPT
		#$IPTABLES -A INPUT -p tcp -m multiport --ports 137,138 -j DROP
		#$IPTABLES -A INPUT -p udp -m multiport --ports 137,138 -j DROP
	 
		# allow all loopback traffic
		$IPTABLES -A INPUT -i lo  -j ACCEPT
	
		# log all that's not matched by the rules
		#$IPTABLES -A INPUT -j LOG  --log-prefix "illegal INPUT: " --log-level notice
	      
		# ----------
		# ICMP rules
		# ----------
	
		$IPTABLES -A Icmp_Related_And_New -p icmp --icmp-type echo-reply              -m state --state ESTABLISHED -j ACCEPT
		$IPTABLES -A Icmp_Related_And_New -p icmp --icmp-type echo-request            -m state --state NEW     -j ACCEPT
		$IPTABLES -A Icmp_Related_And_New -p icmp --icmp-type destination-unreachable -m state --state RELATED -j ACCEPT
		$IPTABLES -A Icmp_Related_And_New -p icmp --icmp-type source-quench           -m state --state RELATED -j ACCEPT
		$IPTABLES -A Icmp_Related_And_New -p icmp --icmp-type parameter-problem       -m state --state RELATED -j ACCEPT
		$IPTABLES -A Icmp_Related_And_New -p icmp --icmp-type time-exceeded           -m state --state RELATED -j ACCEPT
		# log all that's not matched by the rules
		$IPTABLES -A Icmp_Related_And_New -j LOG  --log-prefix "illegal Icmp: " --log-level notice
		$IPTABLES -A Icmp_Related_And_New -j DROP
		;;
	stop)
		$IPTABLES -F;
		$IPTABLES -X;
		$IPTABLES -F -t nat;
		$IPTABLES -X -t nat;
		$IPTABLES -F -t mangle;
		$IPTABLES -X -t mangle;
		$IPTABLES -P INPUT ACCEPT;
		$IPTABLES -P OUTPUT ACCEPT;
		$IPTABLES -P FORWARD ACCEPT;
	;;
	restart|reload)
		$0 stop;
		$0 start;
	;;
	panic|shutdown)
		echo 0 > /proc/sys/net/ipv4/ip_forward
		$IPTABLES -F;
		$IPTABLES -X;
		$IPTABLES -F -t nat;
		$IPTABLES -X -t nat;
		$IPTABLES -F -t mangle;
		$IPTABLES -X -t mangle;
		$IPTABLES -P INPUT   -j DROP;
		$IPTABLES -P OUTPUT  -j DROP;
		$IPTABLES -P FORWARD -j DROP;
		echo "PANIC: default policy now DROP and all rules flushed";
	;;
	*)
		echo "Usage: $0 start|stop|restart|reload|panic|shutdown";
	;;
esac
