#!/bin/bash
# firetero - Per-host firewall for workstations and servers.
# Don't edit this file, edit /etc/firetero/rules
 
# http://www.iki.fi/karvinen/iptables_firewall.html
# (c) 2003-2006 Karvinen et al. 
# GNU General Public License, version 2 or later

# Requires: iptables. Suggests: ulogd	
# In Ubuntu: enable universe, 'sudo apt-get install iptables ulogd' 

# Tero Karvinen - tero karvinen at iki fi - http://www.iki.fi/karvinen 

# ChangeLog
# 2006-10-01	Improved name server handling. Config file 
#		in /etc. Rules.d. Logging to separate file with 
#		ulog (if installed). Firetero 0.2. Tero Karvinen
# 2006-08-18	Init.d script by Torstein Johansen http://www.skybert.nu/
# ...	Versions for Fedora Core and Debian - Tero Karvinen
# 2003	Initial version on Red Hat - Tero Karvinen

stop_fw() 
{
	echo -n "Stopping `basename $0`..." 
	iptables --flush
	iptables -t mangle --flush PREROUTING
	iptables --delete-chain
	iptables -P INPUT ACCEPT
	iptables -P OUTPUT ACCEPT
	iptables -P FORWARD ACCEPT
	echo "Firewall disabled, all traffic allowed trough. ";
}

start_fw() 
{
	echo -n "Starting $(basename $0)..." 
	# Cleanup old rules # All the time firewall is in a secure, closed state
	iptables -P INPUT DROP
	iptables -P FORWARD DROP
	iptables --flush		# Flush all rules, but keep policies 
	iptables -t mangle --flush PREROUTING
	iptables --delete-chain

	if [ -x /usr/sbin/ulogd ]; then
		LOG="ULOG"; # ulogd is only suggested package
	else
		LOG="LOG"; # fall back to builtin target
	fi

	## Workstation Minimal firewall ###
	iptables -A INPUT -i lo --source 127.0.0.1 --destination 127.0.0.1 -j ACCEPT
	iptables -A INPUT -m state --state "ESTABLISHED,RELATED" -j ACCEPT  # All client connections: Web browsing, email...
	iptables -A INPUT -m state --state "ESTABLISHED" -j ACCEPT # for DNS
	iptables -A INPUT -p icmp --icmp-type destination-unreachable -j ACCEPT # for setting MTU (fragmenting)
	iptables -A INPUT -p icmp --icmp-type time-exceeded -j ACCEPT # allow us to traceroute others
	iptables -A INPUT -p icmp --icmp-type echo-reply -j ACCEPT # allow us to ping others

	source /etc/firetero/rules; # user defined rules
	source /etc/firetero/rules.d/*; # don't use this to automatically enable servers from server deb install scipts
	
	# "/var/log/ulog/syslogemu.log", requires "ulogd"
	iptables -A INPUT -j $LOG -m limit --limit 40/minute
	iptables -A INPUT -j DROP
	echo "done."
}

fw_status()
{
	# --numeric makes --list a lot faster
	echo "iptables --list   # if this is too slow, try 'iptables --list --numeric'";
	iptables --list #--numeric
	echo "";
	echo "iptables -t mangle --list PREROUTING   # typically used for traffic shaping";
	iptables -t mangle --list PREROUTING
}

case "$1" in
	"start" | "restart" | "force-reload")
		start_fw
		;;
	"stop")
		stop_fw
		;;
	"status")
		fw_status
		;;
	*)
		echo "Usage:" $0 "{start|restart|force-reload|stop|status}";
		exit 1;
		;;
esac

exit 0

