Friday, August 19, 2005

Script to detect a modified file

Some times it is necessary to detect whether a file has been modified before performing a number of activities. These activities could be defensive in nature if the file was not to be changed for security reasons, for example, or it could be routine in nature such as archiving the file. Here is an example script that will identify a file change.

The script simply runs a infinite loop that checks whether the fingerprint of the file (the md5 checksum) has been modified. If it detects a change the script will notify the administrator via an email.

#!/bin/sh
target=target.txt
baseline=/tmp/passwd.base
timer=60
md5sum $target > $baseline
while [ 1 = 1 ] ; do
if [ "`md5sum $target`" != "`cat $baseline`" ] ; then
echo File $target was changed at `date` mail -s "$target changed!" root
exit
fi
sleep $timer
done

However, the reader should note that the above file will not detect changes if the intruder made an attempt to cover his tracks. One way of detecting whether someone has changed files and then covered his tracks is to use the suditing facilities provided within the operating system kernel. For example is Solaris, the reader could use the BSM audit facility to determine who did what to the file under consideration.