#!/bin/sh
# p0f		This shell script takes care of starting and stopping
#		the p0f monitoring program
#
# chkconfig:	2345 52 48
#
# description:	p0f - the p0f monitoring program. \
#		p0f performs passive OS fingerprinting technique bases on \
#		information coming from remote host when it establishes \
#		connection to our system. Captured packets contains enough \
#		information to determine OS - and, unlike active scanners \
#		(nmap, queSO) - without sending anything to this host.
#
# processname:	p0f
# pidfile:	/var/run/p0f.pid

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

# Get network config
. /etc/sysconfig/network

# Get service config
[ -f /etc/sysconfig/p0f ] && . /etc/sysconfig/p0f

# Check that networking is up.
if is_yes "${NETWORKING}"; then
	if [ ! -f /var/lock/subsys/network ]; then
		msg_network_down p0f
		exit 1
	fi
else
	exit 0
fi

RETVAL=0
# See how we were called.
case "$1" in
  start)
	# Check if the service is already running?
	if [ ! -f /var/lock/subsys/p0f ]; then
		msg_starting "p0f"
		# The command in backticks returns all the local IP addresses on this machine.
		for OneIP in `/sbin/ip -f inet addr show | awk '/inet/{print $2}' | awk -F/ '{print $1}' | LC_ALL=C sort -u`; do
			if [ -z "$BpfFilter" ]; then
				BpfFilter="not src host $OneIP"
			else
				BpfFilter="$BpfFilter and not src host $OneIP"
			fi
		done
		RULE="$BpfFilter"
		if [ -n "$P0F_RULE" ]; then
			if [ -n "$RULE" ]; then
				RULE="$RULE and $P0F_RULE"
			else
				RULE="$P0F_RULE"
			fi
		fi
		OPTIONS=""
		if [ -n "$P0F_INTERFACE" ]; then
			OPTIONS="$OPTIONS -i $P0F_INTERFACE"
		fi
		if [ -n "$P0F_SOCKET" ]; then
			# read the manual first and then ask why the umask
			umask 007
			OPTIONS="$OPTIONS -s $P0F_SOCKET"
		fi
		if [ -n "$P0F_USER" ]; then
			OPTIONS="$OPTIONS -u $P0F_USER"
		fi
		# Start up p0f and filter out all packets originating from any of this machines IP's.
		/usr/sbin/p0f $OPTIONS $P0F_OPTIONS -d -o /var/log/p0f "$RULE" >/dev/null 2>&1
		RETVAL=$?
		if [ $RETVAL -eq 0 ]; then
			# this is secure, as socket is always created with current umask and root
			if [ "$P0F_USER" ] && [ "$P0F_SOCKET" ]; then
				chown ${P0F_USER}: $P0F_SOCKET
			fi
			touch /var/lock/subsys/p0f
			ok;
		else
			fail;
		fi
	else
		msg_already_running "p0f"
	fi
	;;
  stop)
	if [ -f /var/lock/subsys/p0f ]; then
		msg_stopping "p0f"
		killproc p0f
		rm -f /var/lock/subsys/p0f >/dev/null 2>&1
	else
		msg_not_running "p0f"
	fi
	;;
  restart|force-reload)
	$0 stop
	$0 start
	exit $?
	;;
  status)
	status p0f
	exit $?
	;;
  *)
	msg_usage "$0 {start|stop|restart|force-reload|status}"
	exit 3
esac

exit $RETVAL
