#!/bin/sh

# Autoupdater for modsec rulesets.
#
# This script will attempt to update your rulefiles, and restart apache.
# If it apache does not start after changing rules, it will roll back to
# the old ruleset and restart apache again.
#
# Version: $Id: modsec.sh,v 2.0 2006/09/03 23:58:00 olei Exp $
# Based on a script by:
# URL: http://cs.evilnetwork.org/cycro
# 
# Copyleft 2006, SkyHorse.Org, No Rights Reserved
# URL: http://www.skyhorse.org/web-server-administration/auto-update-modsecurity-rules-modsecsh/ 

APACHESTART="/usr/local/apache/bin/apachectl startssl"
MODSECPATH="/etc/modsecurity"
APACHEPID="/usr/local/apache/logs/httpd.pid"

##########################################################################
######### you probably don't need to change anything below here ##########
##########################################################################

# internal
PID=`cat ${APACHEPID}`
UPDATED=0

echo -n "Changing PWD: "
cd ${MODSECPATH}
echo `pwd`


#generic by skyhorse


listOfRules="exclude blacklist rules useragents blacklist2 proxy rootkits badips jitp"
baseUrl="http://www.gotroot.com/downloads/ftp/mod_security/"

for theRule in $listOfRules
do
echo -n "Updating $theRule: "
/usr/bin/wget -t 30 -O ${theRule}.conf.1 -q ${baseUrl}${theRule}.conf
if [ `md5sum ${theRule}.conf | cut -d " " -f1` != `md5sum ${theRule}.conf.1 | cut -d " " -f1` ] ; then

	/bin/mv ${theRule}.conf ${theRule}.conf.bak
	/bin/mv ${theRule}.conf.1 ${theRule}.conf
	UPDATED=`expr $UPDATED + 1`
	echo "ok."
else
	echo "allready up to date."
	/bin/rm -f ${theRule}.conf.1
fi
done

# try restart
if [ "$UPDATED" -gt "0" ]; then
	echo -n "Restarting apache: "
	/bin/kill -HUP ${PID} 2>/dev/null
	# did it work?
	if `/bin/kill -CHLD ${PID} >/dev/null 2>&1`; then
		echo "Apache restarted ok."
		exit 0
	fi
	echo "error. Apache not running."

	#roll back everything
	for theRule in $listOfRules
	do
	echo -n "Rolling back ${theRule}"
	/bin/mv ${theRule}.conf ${theRule}.conf.new
	/bin/mv ${theRule}.conf.bak ${theRule}.conf
	echo "rolled back ok."
	done
	
	# try starting httpd again
	`${APACHESTART}`
	PID=`cat ${APACHEPID}`
	
	# did that fix the problem?
	if `/bin/kill -CHLD ${PID} >/dev/null 2>&1`; then
		echo "That did the trick."
		exit 0
	fi

	echo "Fatal: Apache still not running! Run apachectl -t to find the error."
	exit 999
fi

