Quick and Dirty Integrity Check Script

Altered Data

Here is a quick and dirty bash script which will take care of your files integrity. Integrity is a component of the CIA triad, I’ll not come back on this.

For a personal project, I should be able to monitor any change in a specific file. I quickly wrote the code below. Nothing fancy, straight to the point.

Basically, it computes the SHA1 digest of the files passed as arguments and save them. The next time the script is run, it will compare the existing SHA1 digest with the new one. If it changed, it will print some details on the console.

This script runs perfectly from a crontab (does only write to stdout when something happen). Feel free to re-use it.

As examples, you can easily monitor your websites index.[php|html] files (to quickly detect potential defacements) or your /etc/passwd or /etc/inetd.conf (to detect any new user or new service installed by a rootkit).

#!/bin/bash
#
# Usage: $0 [file ...]
#
# Check file integrity based on SHA1 digest.
# Requires sha1sum.
#
# Use this script from crontab:
# */15 * * * * integrity_check.sh [file ...]
#

# Change to your preferred location
SHA1DB=/var/sha1db

# sha1sum is required
if [ ! -x `which sha1sum` ]; then
	echo "This script requires sha1sum!"
	exit 1
fi

[ -d $SHA1DB ] || mkdir $SHA1DB || exit 1
if [ "$1" = "" -o "$1" = "-h" ]; then
	echo "Usage: $0 [file ...]"
	exit 1
fi

RCODE=0
while [ ! -z "$1" ]
do
	FILE=$1
	if [ ! -r "$1" ]; then
		echo "File \"$FILE\" not found or not readable!"
		RCODE=1
		shift; continue
	fi


	SHA1FILE=$SHA1DB/`basename $FILE`.sha1
	if [ ! -r "$SHA1FILE" ]; then
		sha1sum $FILE | awk '{ print $1; }' > $SHA1FILE
		if [ "$?" != "0" ]; then
			echo "Cannot create the SHA1 digest for \
				\"$FILE\"!"
			RCODE=1
			shift; continue
		fi
		echo "Initial SHA1 digest created."
		shift; continue
	else
		sha1sum $FILE | awk '{ print $1; }' > $SHA1FILE.new
		if [ "$?" != "0" ]; then
			echo "Cannot create the SHA1 digest for \
				\"$FILE\"!"
			RCODE=1
			shift; continue
		fi
		diff $SHA1FILE.new $SHA1FILE >/dev/null 2>&1
		if [ "$?" != "0" ]; then
			echo "SHA1 changed! Security breach?"
			echo -n "Old digest: "; cat $SHA1FILE
			echo -n "New digest: "; cat $SHA1FILE.new
			RCODE=1
		fi
		mv $SHA1FILE.new $SHA1FILE 
	fi
	shift
done

exit $RCODE

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.