#!/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 service config
[ -f /etc/sysconfig/p0f ] && . /etc/sysconfig/p0f

# 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/ifconfig 2>/dev/null | grep 'inet addr' | sed -e 's/.*addr://' -e 's/ .*//'` ; do
			if [ -z "$BpfFilter" ]; then
				BpfFilter="not src host $OneIP"
			else
				BpfFilter="$BpfFilter and not src host $OneIP"
			fi
		done
		if [ -n "$P0F_INTERFACE" ]; then
			OPTIONS="-i $P0F_INTERFACE"
		fi
		if [ $P0F_UNKNOWN_SIGNATURES = "yes" ]; then
			OPTIONS="$OPTIONS -U"
		fi
		if [ $P0F_KNOWN_SIGNATURES = "yes" ]; then
			OPTIONS="$OPTIONS -K"
		fi
		if [ $P0F_TIMESTAMPS = "yes" ]; then
			OPTIONS="$OPTIONS -t"
		fi
		#Start up p0f and filter out all packets originating from any of this machines IP's.
		nohup /usr/sbin/p0f -v "$BpfFilter" $OPTIONS >>/var/log/p0f 2>&1 &

                ps -C p0f >/dev/null 2>&1
                RETVAL=$?
                CPID=$!
                if [ $RETVAL -eq 0 ]; then
                        touch /var/lock/subsys/p0f
                        echo $CPID >/var/run/p0f.pid
                        deltext; ok;
                else
                        deltext; fail;
                fi
        else
                msg_already_running "p0f"
                exit 1
        fi
	;;

  stop)
        if [ -f /var/lock/subsys/p0f ]; then
                msg_stopping "p0f"
                #busy
                killproc p0f
                #deltext; ok;
                rm -f /var/lock/subsys/p0f >/dev/null 2>&1
                rm -f /var/run/p0f.pid >/dev/null 2>&1
        else
                msg_not_running "p0f"
                exit 1
        fi
        ;;

  restart)
	$0 stop
	$0 start
	;;

  status)
	status p0f
	exit $?
	;;

  *)
	msg_usage "$0 {start|stop|status|restart}"
	exit 1
	;;

esac

exit $RETVAL
