#!/bin/sh

#######
#     Firewall
#######

start_firewall(){
	# Close all ports
	DO=DROP ; iptables -P INPUT $DO ; iptables -P OUTPUT $DO ;  iptables -P FORWARD $DO

	# remove old rules
	iptables -F

	# allow local connections
	iptables -A INPUT -i lo -j ACCEPT
	iptables -A OUTPUT -o lo -j ACCEPT

	# allow some eth0 connections
	# ssh
	PORT=22; PROT=tcp; iptables -A OUTPUT -p $PROT -o eth0 --sport $PORT -j ACCEPT ;iptables -A INPUT -p $PROT -i eth0 --dport $PORT -j ACCEPT

	# telnet
	PORT=23; PROT=tcp; iptables -A OUTPUT -p $PROT -o eth0 --sport $PORT -j ACCEPT ;iptables -A INPUT -p $PROT -i eth0 --dport $PORT -j ACCEPT

	# DHCP
	PORT=67:68; PROT=udp; iptables -I INPUT -i eth0 -p $PROT --dport $PORT -j ACCEPT

	# boa-Weberver
	PORT=80; PROT=tcp; iptables -A OUTPUT -p $PROT -o eth0 --sport $PORT -j ACCEPT ;iptables -A INPUT -p $PROT -i eth0 --dport $PORT -j ACCEPT

	# apache
	PORT=81; PROT=tcp; iptables -A OUTPUT -p $PROT -o eth0 --sport $PORT -j ACCEPT ;iptables -A INPUT -p $PROT -i eth0 --dport $PORT -j ACCEPT

	# artis
	PORT=660; PROT=tcp; iptables -A OUTPUT -p $PROT -o eth0 --sport $PORT -j ACCEPT ;iptables -A INPUT -p $PROT -i eth0 --dport $PORT -j ACCEPT
	PORT=44873; PROT=udp; iptables -A OUTPUT -p $PROT -o eth0 --sport $PORT -j ACCEPT ;iptables -A INPUT -p $PROT -i eth0 --dport $PORT -j ACCEPT

	# CAN-EthernetGateway
	PORT=8234; PROT=tcp; iptables -A OUTPUT -p $PROT -o eth0 --sport $PORT -j ACCEPT ;iptables -A INPUT -p $PROT -i eth0 --dport $PORT -j ACCEPT
	PORT=8235; PROT=tcp; iptables -A OUTPUT -p $PROT -o eth0 --sport $PORT -j ACCEPT ;iptables -A INPUT -p $PROT -i eth0 --dport $PORT -j ACCEPT	

	# FTP
	PORT=21; PROT=tcp; iptables -A OUTPUT -p $PROT -o eth0 --sport $PORT -j ACCEPT ;iptables -I INPUT 2 -p $PROT -i eth0 --dport $PORT -j ACCEPT
	PORT=21; PROT=udp; iptables -A OUTPUT -p $PROT -o eth0 --sport $PORT -j ACCEPT ;iptables -I INPUT 2 -p $PROT -i eth0 --dport $PORT -j ACCEPT
	PORT=20; PROT=tcp; iptables -A OUTPUT -p $PROT -o eth0 --sport $PORT -j ACCEPT ;iptables -A INPUT -p $PROT -i eth0 --dport $PORT -j ACCEPT
	PORT=20; PROT=udp; iptables -A OUTPUT -p $PROT -o eth0 --sport $PORT -j ACCEPT ;iptables -A INPUT -p $PROT -i eth0 --dport $PORT -j ACCEPT
	PORT=30000:30100; PROT=tcp; iptables -A OUTPUT -p $PROT -o eth0 --sport $PORT -j ACCEPT ;iptables -I INPUT 2 -p $PROT -i eth0 --dport $PORT -j ACCEPT
	PORT=30000:30100; PROT=udp; iptables -A OUTPUT -p $PROT -o eth0 --sport $PORT -j ACCEPT ;iptables -I INPUT 2 -p $PROT -i eth0 --dport $PORT -j ACCEPT
}

action=$1

case "$action" in
	start*)
		# start firewall in background
		start_firewall &
		;;
	stop)
		DO=ACCEPT
		iptables -P INPUT $DO 
		iptables -P OUTPUT $DO  
		iptables -P FORWARD $DO
		iptables -F
		;;	
	*)
		echo "Unknown action=$action !!"
		;;
esac
