#!/bin/sh
#
# Startup script to for SnortSAM
#
# chkconfig: 2345 98 02
# description: SnortSAM dynamic firewall plug-in for Snort

# Source function library.
. /etc/rc.d/init.d/functions

# Source networking configuration.
. /etc/sysconfig/network

# Check that networking is up.
[ ${NETWORKING} = "no" ] && exit 0

# Source auto-configure functions
[ -e /etc/init.d/functions-automagic ] && source /etc/init.d/functions-automagic
[ -e /etc/sysconfig/automagic ] && source /etc/sysconfig/automagic

RETVAL=0
prog="snortsam"

automagic() {
	# Bail if no-automagic is required
	if [ "$AUTOMAGIC" == "off" ]; then
		return
	fi

	# Leave last known state if no external interfaces are up
	if [ -z "$AUTOMAGIC_EXTIFS" ]; then
		return
	fi

	# Implant all WAN interfaces into configuration file

	rm -f /etc/snortsam.conf.automagic

	while read -r LINE; do
		PARAM=`echo $LINE | awk '{ print $1 }'`
		if [ "$PARAM" == "iptables" ]; then
			for INTERFACE in $AUTOMAGIC_EXTIFS; do
				echo "iptables $INTERFACE syslog.info" >> /etc/snortsam.conf.automagic
			done
			AUTOMAGIC_EXTIFS=""
		else
			echo "$LINE" >> /etc/snortsam.conf.automagic
		fi

	done </etc/snortsam.conf

	mv /etc/snortsam.conf.automagic /etc/snortsam.conf
}

# Add or delete existing firwall block rules
firewallconfig() {
	if [ "$1" == "start" ]; then
		FLAG="-I"
	else
		FLAG="-D"
	fi

	[ -e /etc/init.d/functions-automagic ] && source /etc/init.d/functions-automagic

	export UTC=`date +"%s"`
	IPS=`snortsam-state -qd, 2>/dev/null | awk -F, '$6+$7 > ENVIRON["UTC"] { print $2 }'`
	for INTERFACE in $AUTOMAGIC_EXTIFS; do
		for IP in $IPS; do
			/sbin/iptables $FLAG INPUT -i $INTERFACE -s $IP -j DROP >/dev/null 2>&1
			/sbin/iptables $FLAG OUTPUT -o $INTERFACE -d $IP -j DROP >/dev/null 2>&1
			/sbin/iptables $FLAG FORWARD -i $INTERFACE -s $IP -j DROP >/dev/null 2>&1
			/sbin/iptables $FLAG FORWARD -o $INTERFACE -d $IP -j DROP >/dev/null 2>&1
		done
	done
}

# See how we were called.
case "$1" in
  start)
	echo -n $"Starting $prog: "
	automagic
	daemon /usr/local/nsc/bin/snortsam /etc/snortsam.conf >/dev/null 2>&1
	RETVAL=$?
	if [ $RETVAL -eq 0 ]; then
		success
		touch /var/lock/snortsam
		firewallconfig start
	else
		failure
	fi
	echo
	;;
  stop)
	echo -n $"Stopping $prog: "
	killproc snortsam
	RETVAL=$?
	echo
	if [ $RETVAL -eq 0 ]; then
		rm -f /var/lock/snortsam
		firewallconfig stop
	fi
	;;
  status)
	status snortsam
	RETVAL=$?
	;;
  condrestart)
	if test "x`/sbin/pidof snortsam`" != x; then
		$0 stop
		sleep 2
		$0 start
		RETVAL=$?
	fi
	;;
  restart|reload)
	$0 stop
	sleep 2
	$0 start
	RETVAL=$?
	;;
  *)
	echo "Usage: $prog {start|stop|status|restart|reload}"
	exit 1
esac

exit $RETVAL

