Checking your site for malicious changes

Today a couple of hours back my site got compromised. Not much changes to the code, but the .htacces was changed and some code like the below was added to the .htaccess file, which redirected the traffic coming from search engines to a malware site.

It has now been removed and to prevent any such changes to the .htaccess file in the future, I’ve written a small php script that compares the hash (SHA1) of the two major files that usually get compromised and compare them to the one originally stored. The script will run as a cron job and notify me by email if any changes are seen. This is a quick workaround which needs some more work done.

$hash1 = sha1_file('.htaccess');
$hash2 = sha1_file('index.php');

if(($hash1 == 'fa7cdb22b81b0b713bfed609acc984591f9bed2f') && 
   ($hash2 == 'b4bb6070800a340566d7d6872516d248d4a7aff3')) {
    mail("EMAIL", "Status Ok!", "Status Ok!");
} else {
    mail("EMAIL", "Alert!", "Files have changed!");

Of-course there are other ways the site can get hacked, but the last couple of times my site got compromised was for these reasons. So at-least I’ve one area covered.

10 thoughts to “Checking your site for malicious changes”

  1. Yeah, chrome is giving me a ‘malware detected’ when visiting your site. How did you end up finding out about this? Sucks…

  2. I’m curious as to why you have it email you if nothing has changed. Won’t this result in a lot of unnecessary emails, depending on how often it runs?

  3. I’m being paranoid here; what if for some reasons the cron stops working or I accidentally delete the cron file; this will stop all the messages, even legitimate ones if the site gets infected again.

  4. I use a cronjob which checks for changed files and sends a mail notification if it founds anything:

    0 ) {

    // put your mail mechanism

    // do nothing

  5. Or you could put your site under git and mail to you the ‘git status’ to see if your site has changed

  6. Nifty piece of code, Sameer. I like it.

    @Carl – I think in most cases, they don’t need to be, but it’s not always practical to have them not be (writable by the webserver user). For example, in a WordPress install, changing permalinks from the backend requires the .htaccess file to be writeable by the web user. Upgrading from the backend requires the same (unless you enter FTP credentials, which is a fine workaround, just a little annoying).

Leave a Reply

Your email address will not be published.