#!/bin/sh

##################################################
#              Apache audit script               #
#                                                #
# Cron this script to check for illegal software #
# running as the Apache user.                    #
#                                                #
# Last update: 07/04/2006                        #
# Version: 1.02                                  #
##################################################

APACHE_USER=www
APACHE_PATH=/usr/local/sbin/httpd
MAIL_TO=root@localhost
MAIL_SUBJ_WARNING='Audit: Suspicious activity detected!'
MAIL_SUBJ_BAD='Audit: Bad activity detected!'
ALLOWED_PORTS="80"






# Nothing to be modified below this line.

PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin

# We need the lsof command, check for it.
if [ "`which lsof 2> /dev/null`" == "" ]; then
	echo "lsof command not found."
	exit 1
fi

# Transform "ALLOWED_PORTS" into command format.
GREP_PORTS=""
for PORTS in $ALLOWED_PORTS; do
	# Ports appear as :PORT followed by " " or "-"
	GREP_PORTS="| grep -v -E :$PORTS[\ \|\-] $GREP_PORTS"
done

# Non-Apache processes running as Apache user.
OSTYPE=`uname`
if [ "$OSTYPE" == "Linux" ]; then
	PSAUX=`ps --user $APACHE_USER f -f | grep "\_ "`
elif [ "$OSTYPE" == "FreeBSD" ]; then
	PSAUX=`ps -U $APACHE_USER -o user,pid,%cpu,%mem,stat,start,time,command | grep -v ^USER | grep -v "<defunct>$" | grep -v $APACHE_PATH`
else
	echo "Unsupported OS."
	exit 1
fi

if [ "$PSAUX" != "" ]; then
	KILLED_PID=""
	# Get list of PIDs
	PID_LIST=`echo "$PSAUX" | awk '{ print $2 }'`
	for ONEPID in $PID_LIST; do
		SOCK_LIST="lsof -n -P -a -i -p $ONEPID | grep -v ^COMMAND $GREP_PORTS"
		#echo $SOCK_LIST
		SOCK_LIST=`eval $SOCK_LIST`

		if [ "$SOCK_LIST" != "" ]; then
			# Something nasty appears to be happening.
			# Kill the process.
			kill -9 $ONEPID
			# Build killed process list.
			KILLED_PID=`echo -e "PID: $ONEPID\nSocket info: $SOCK_LIST\n\n$KILLED_PID"`
		fi
	done

	# Send the email.
	if [ "$KILLED_PID" == "" ]; then
		# Just a warning.
		echo -e "Process info:\n$PSAUX" | mail -s "$MAIL_SUBJ_WARNING" $MAIL_TO
	else
		# Bad things happening.
		echo -e "Process info:\n$PSAUX\n\nThe following PIDs were killed:\n\n$KILLED_PID" | mail -s "$MAIL_SUBJ_BAD" $MAIL_TO
	fi
fi

exit 0
