#!/bin/sh
#
# firewall        Start the firewall in paranoid mode
#

# COLORS
NORMAL="\033[1;0m"
GREEN="\033[1;32m"
RED="\033[1;31m"

# limit icmp rate
icmp_rate()
{
  echo -n "Limit ICMP echo reply rate : "
  (/sbin/iptables -A INPUT -p icmp --icmp-type echo-request 	\
    -m limit --limit 10 --limit-burst 20 -j ACCEPT) || 	    	\
	(echo -e "[$RED""FAILED$NORMAL]" && /bin/false) || exit 1
  echo -e "[$GREEN""OK$NORMAL]"
}

# accept only established connections in input
# NEW are droped
# accept all for lo interface
input()
{
  echo -n "Accept only established connection in input : "
  (/sbin/iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT &&
   /sbin/iptables -A INPUT -i lo -m state --state NEW,ESTABLISHED,RELATED \
   -j ACCEPT) || (echo -e "[$RED""FAILED$NORMAL]" && /bin/false) || exit 1
  echo -e "[$GREEN""OK$NORMAL]"
}

# accept all in output
output()
{
  echo -n "Accept all connections in output : "
  (/sbin/iptables -A OUTPUT -m state --state NEW,ESTABLISHED,RELATED 	\
	-j ACCEPT) || (echo -e "[$RED""FAILED$NORMAL]" && /bin/false) || exit 1
  echo -e "[$GREEN""OK$NORMAL]"
}

case "$1" in
  start)
	echo "Starting Firewall..."
	(/sbin/iptables -P INPUT DROP &&
	/sbin/iptables -P OUTPUT DROP &&
	/sbin/iptables -P FORWARD DROP) || 	\
	  (echo -e "[$RED""FAILED$NORMAL]" && /bin/false) || exit 1
	icmp_rate
	input
	output
	echo -e "Firewall Loaded [$GREEN""OK$NORMAL]"
	;;
  stop)
	echo -n "Stopping Firewall : "
	(/sbin/iptables -P INPUT ACCEPT &&
	/sbin/iptables -P OUTPUT ACCEPT &&
	/sbin/iptables -P FORWARD ACCEPT &&
	/sbin/iptables -F INPUT &&
	/sbin/iptables -F OUTPUT &&
	/sbin/iptables -F FORWARD) || 	\
	  (echo -e "[$RED""FAILED$NORMAL]" && /bin/false) || exit 1
	echo -e "[$GREEN""OK$NORMAL]"
	;;
  allowX)
	echo -n "Allow X connections : "
	(/sbin/iptables -A INPUT -p tcp --dport 6000 -j ACCEPT &&
	/sbin/iptables -A OUTPUT -p tcp --dport 6000 -j ACCEPT)	\
	  || (echo -e "[$RED""FAILED$NORMAL]" && /bin/false) || exit 1
	echo -e "[$GREEN""OK$NORMAL]"
	;;
  restart)
	$0 stop
	$0 start
	;;
  *)
	echo "Usage : $0 {start|stop|restart|allowX}"
	;;
esac
