A simple intrusion detection script

If you have a very static Linux server and you want to make sure it's not messed with, here's a simple script that will tell you if any files have been tampered with. It's not as fancy or as secure as tripwire or those others, but it is very simple. It can be easily adapted to any *NIX OS.

#!/bin/sh
## How often to run (in seconds)
PERIOD=3600

## Any files or directories that always change, add here:
EXCLUDE="/proc/ /sys/ /dev/ /var/log /var/run/ /var/lock/ /var/cache/ /var/tmp/ /tmp/ /var/lib/ldap/"
EXCLUDE="$EXCLUDE /var/spool/ /etc/prelink.cache /etc/ld.so.cache /var/lib/logrotate.status /var/lib/slocate/"
EXCLUDE="$EXCLUDE /.*\.viminfo /var/lib/md5sigs"

SIGS=/var/lib/md5sigs
TEMP=/tmp/sigs-$$

umask 077
#
while true; do 

# calculate md5sum of all files not in EXCLUDE
exclude_re=`echo "^("$EXCLUDE")" | sed 's/  */|/g'`
find / -type f -print 2>/dev/null |
        grep -Ev "$exclude_re" |
        LC_ALL=C sort |
        xargs md5sum 2>/dev/null  >$TEMP

# Compare against existing database (or use this one for new database)
if test -f /root/.md5sigs ;then
        diff -w -h $SIGS $TEMP  >$TEMP.diff
        if [ -s $TEMP.diff ]; then
           mail -s "File scan Report" root <$TEMP.diff
           exit 1
        fi
        rm -f $TEMP $TEMP.diff
else
        mv $TEMP $SIGS
        echo "No prior existing report."
fi

sleep $PERIOD
done

# Copyright 2009 by Otheus, licensed under GNU v2 Public License

I worked on root kit hunter at sourceforge.net for a while. There are similar capabilities in the scripts in that app as well.

You may be missing something essential - as an example:
root kits may change a lot of utilities in /usr/bin to avoid detection. md5sum is one of them. It "knows" how to report the old value for a given system file, even though the file is now completely different. The same is true for ls, find and so on. If you ldd those files and ldd is not corrupt you may see odd libraries linked into them.

I would:
create a separate hidden tree of ls, find, md5sum, etc. that your script points to with it's own version of PATH. Populate the directory with known good versions of the files. If you're even a little more paranoid, consider rebuilding & linking those files statically which eliminates shared library masquerading.

It all depends on your level of exposure - if you're inside a good firewall, my suggestions may be overkill.

Might I suggest as well:

@@ -29,6 +29,7 @@
         rm -f $TEMP $TEMP.diff
 else
         mv $TEMP $SIGS
+        chmod 600 $SIGS
         echo "No prior existing report."
 fi

--
qneill

Ah yes. Very important point. Better yet... set umask before creating the file. I have updated the post with the umask setting.