Write a bash script to checking for file integrity and tampering

In this article, we are going to learn how to check the integrity of a file and how to check for tampering by writing a simple shell script. Why do we need to check integrity? The answer is simple: administrators check integrity when there are passwords and libraries present on a server, as well as when files contain highly sensitive data.

Prerequisites

Besides having a terminal open, you need to make sure the necessary files and directories are present.

Write script

We are going to write a script to check whether a file in a directory has been tampered with. Create an integrity_check.sh script and add the following code to it:

integrity_check.sh

#!/bin/bash 
E_DIR_NOMATCH=50 
E_BAD_DBFILE=51 
dbfile=Filerec.md5 
# storing records. 
set_up_database () 
{ 
	echo ""$directory"" > "$dbfile" 
	# Write directory name to first line of file. 
	md5sum "$directory"/* >> "$dbfile" 
	# Append md5 checksums and filenames. 
} 
check_database () 
{ 
	local n=0 
	local filename 
	local checksum 
	if [ ! -r "$dbfile" ] 
	then 
		echo "Unable to read checksum database file!" 
		exit $E_BAD_DBFILE 
	fi 
	
	while read rec[n] 
	do 
		directory_checked="${rec[0]}" 
		if [ "$directory_checked" != "$directory" ] 
		then 
			echo "Directories do not match up!" 
			# Tried to use file for a different directory. 
			exit $E_DIR_NOMATCH 
		fi 
		if [ "$n" -gt 0 ] 
		then 
			filename[n]=$( echo ${rec[$n]} | awk '{ print $2 }' ) 
			# md5sum writes recs backwards, 
			#+ checksum first, then filename. 
			checksum[n]=$( md5sum "${filename[n]}" ) 
			if [ "${rec[n]}" = "${checksum[n]}" ] 
			then 
				echo "${filename[n]} unchanged." 
			else 
				echo "${filename[n]} : CHECKSUM ERROR!" 
			fi 
		fi 
		let "n+=1" 
	done <"$dbfile" # Read from checksum database file. 
} 
if [ -z "$1" ] 
then 
	directory="$PWD" # If not specified, 
else 
	directory="$1" 
fi 
clear 
if [ ! -r "$dbfile" ] 
then 
	echo "Setting up database file, \""$directory"/"$dbfile"\"."; 
	echo 
	set_up_database 
fi 
check_database 
echo 
exit 0

How script works

When we run this script, it will create a database file named filerec.md5, which will have data about all the files present in that directory. We’ll use those files for reference.

0 Comments

Submit a Comment

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

18 + 18 =

Related Articles