Debian Codegraph @

file-integrity.sh

raw symbols SCIP
1 #!/bin/bash
2 # file-integrity.sh: Checking whether files in a given directory
3 # have been tampered with.
4
5 E_DIR_NOMATCH=80
6 E_BAD_DBFILE=81
7
8 dbfile=File_record.md5
9 # Filename for storing records (database file).
10
11
12 set_up_database ()
13 {
14 echo ""$directory"" > "$dbfile"
15 # Write directory name to first line of file.
16 md5sum "$directory"/* >> "$dbfile"
17 # Append md5 checksums and filenames.
18 }
19
20 check_database ()
21 {
22 local n=0
23 local filename
24 local checksum
25
26 # ------------------------------------------- #
27 # This file check should be unnecessary,
28 #+ but better safe than sorry.
29
30 if [ ! -r "$dbfile" ]
31 then
32 echo "Unable to read checksum database file!"
33 exit $E_BAD_DBFILE
34 fi
35 # ------------------------------------------- #
36
37 while read record[n]
38 do
39
40 directory_checked="${record[0]}"
41 if [ "$directory_checked" != "$directory" ]
42 then
43 echo "Directories do not match up!"
44 # Tried to use file for a different directory.
45 exit $E_DIR_NOMATCH
46 fi
47
48 if [ "$n" -gt 0 ] # Not directory name.
49 then
50 filename[n]=$( echo ${record[$n]} | awk '{ print $2 }' )
51 # md5sum writes records backwards,
52 #+ checksum first, then filename.
53 checksum[n]=$( md5sum "${filename[n]}" )
54
55
56 if [ "${record[n]}" = "${checksum[n]}" ]
57 then
58 echo "${filename[n]} unchanged."
59
60 elif [ "`basename ${filename[n]}`" != "$dbfile" ]
61 # Skip over checksum database file,
62 #+ as it will change with each invocation of script.
63 # ---
64 # This unfortunately means that when running
65 #+ this script on $PWD, tampering with the
66 #+ checksum database file will not be detected.
67 # Exercise: Fix this.
68 then
69 echo "${filename[n]} : CHECKSUM ERROR!"
70 # File has been changed since last checked.
71 fi
72
73 fi
74
75
76
77 let "n+=1"
78 done <"$dbfile" # Read from checksum database file.
79
80 }
81
82 # =================================================== #
83 # main ()
84
85 if [ -z "$1" ]
86 then
87 directory="$PWD" # If not specified,
88 else #+ use current working directory.
89 directory="$1"
90 fi
91
92 clear # Clear screen.
93 echo " Running file integrity check on $directory"
94 echo
95
96 # ------------------------------------------------------------------ #
97 if [ ! -r "$dbfile" ] # Need to create database file?
98 then
99 echo "Setting up database file, \""$directory"/"$dbfile"\"."; echo
100 set_up_database
101 fi
102 # ------------------------------------------------------------------ #
103
104 check_database # Do the actual work.
105
106 echo
107
108 # You may wish to redirect the stdout of this script to a file,
109 #+ especially if the directory checked has many files in it.
110
111 exit 0
112
113 # For a much more thorough file integrity check,
114 #+ consider the "Tripwire" package,
115 #+ http://sourceforge.net/projects/tripwire/.