Monitor Files on an Internet Server


Overview


Purpose

The goal is to setup a monitoring system, that can monitor the file system on which a webserver stores its data.

It will create a list of the files that were modified, and send a regular report about all changes on the file system to the admin user.
Although this cannot prevent an actual attack on the website, it can help to identify successful attacks on web-sites and remove malicious software from them.

The system will use the incron-daemon to keep track of all files in the /var/www folder, excluding the data stores for wikis and other software.

Any changes detected will then be logged in a log-file, which is regularily sent to the admin by mail.

Requirements


As a tool to monitor the file system, we will use incrond. Incrond is a daemon very similar to crond, however, it does not execute a command at specific time, but when a monitored file or directory was changed.

We can install it with:

aptitude install incron


We will use incrond to monitor the /var/www directory and all it's subdirectories. Whenever a file is added, modified or removed, this will be noted in a log file. In a regular interval, this logfile will be sent to the admin by e-mail.

Although incron is easy to use, it cannot monitor subdirectories. This means that every subdirectory needs it's own line in the incrontab file. And here comes the tricky bit: When a new subdirectory is created, the script will detect this, and add it to the watch list, while, when the directory was removed, it will be removed from the watchlist.

Since it is a system-wide function, the table will be kept in the /etc/incron.d/ directory.

Script

inotifylogger
#!/bin/bash

# fetch the parameters
PATH=$1
FNAME=$2
EVENT=$3

# set the logfile to store the events in
LOGFILE=/var/log/inotifylogger.log

QFN=$PATH/$FNAME


# if the file is a directory, check if we are already monitoring it
case $EVENT in
  IN_CREATE,IN_ISDIR)
        ESCFILE=$(printf '%q' "$QFN" )
        echo "$ESCFILE IN_CREATE,IN_MODIFY,IN_DELETE /usr/local/bin/inotifylogger \$@ \$# $%" >>/etc/incron.d/apache.incron
        ;;
  IN_DELETE,IN_ISDIR)
        ESCFILE=$(printf '%q' "$QFN")
        /bin/sed -i "\|${ESCFILE//\\/\\\\}|d" /etc/incron.d/apache.incron
        ;;
esac

# we don't want to log the cron jobs from owncloud
if [ ${FNAME: -4} == ".log" ] || [ ${FNAME: -5} == ".lock" ] || [ ${FNAME: -4} == ".spc" ]
then
  exit 0
fi

NOW=$(/bin/date +"%Y-%m-%d %T")
echo "[$NOW] $EVENT has been performed on $QFN" >> $LOGFILE


And the mail script:
inotifymail
#!/bin/bash

# get the parameters
RECIPIANT=$1
FILE=$2

if [ -e $FILE ]
then
  cat $FILE | mail -s "[ORCA-CENTRAL.DE] Webserver Status Report" $RECIPIANT
  rm $FILE
fi
There are no comments on this page.
Valid XHTML :: Valid CSS: :: Powered by WikkaWiki