One of our sites was recently hacked and we didn't notice for a while, because nothing was broken, until we became aware of our site appearing with spammy words in Google searches. Since our site was using git
, I came up with a quick and dirty solution for monitoring the site for unauthorised file changes using the git diff
command.
It is a bash script (but is simple enough to be modified into a batch script for Windows environments) that runs periodically via something like cron
.
#!/bin/bash
# change the following two params,
# set up a cron job and there you go!
email="[email protected]"
site="your site"
cd "$(dirname "$0")"
if [ ! -f snitch.log ]; then
touch snitch.log
fi
# if git diff finds a difference between
# HEAD and what we have now, snitch!
if [[ -n $(git diff --name-only HEAD) ]]; then
git diff --name-only HEAD > snitchtemp.log
if [[ -n $(diff snitch.log snitchtemp.log) ]]; then
git diff --name-only HEAD > snitch.log
cat snitch.log | mail -s "snitch@$site" "$email"
fi
else
echo "OK"
fi
What it does is very simple. On every invocation it uses git diff
to see if any files have been modified since the last commit, and if so sends an email with the list of files that have been tampered. To avoid sending the same email over and over again until you pay attention, it saves the list of files that were tampered with the last time it ran and checks against that to see if the list of files have changed, in which case it can send another email.
Note that git diff
will only list modified files that git
is tracking, so if the intruder creates brand new files, they won't be caught. However since they would need to tamper with at least one existing file to create the brand new file in the first place, this script should be fine.