Thursday, May 5, 2011

PHP and HTML hacked

Last week I ran into the exact hack described here:

http://frazierit.com/blog/?p=103

Nearly all php and html files had a script injected that would cause a client browser to perform a request from airschk.com. Apparently this is used to enlist browsers into making distributed pagerank requests from Google and reporting the results to a third party. The Dr3w had a Perl one-liner for sanitizing html files affected by the attack, but not for the php files. Here's a quick python script I threw together that addresses the php infection:

removeWebBug.py



#!/usr/bin/python

import argparse, sys, string, re

parser = argparse.ArgumentParser(description='Remove defaced code from infected php files')
parser.add_argument('--filelist', metavar='F', nargs=1, type=str, help='List of possibly infected files. Files will be overwritten, so make a backup.')
args = parser.parse_args()

filelist = args.filelist
if not filelist:
 parser.print_usage()
 exit()
filelist_file = open(filelist[0], "r")
filenames = filelist_file.readlines()

php_infection_reg = [re.compile("//{{[0-9a-f]{8}"), re.compile("//}}[0-9a-f]{8}")]
for filename in filenames:
 filename = filename.rstrip()
 print "Processing %s" % filename

 infected_file = open(filename, "r")
 lines = infected_file.readlines()
 clean_result = []

 snip = False
 remove_count = 0
 for line in lines:
  if not snip and php_infection_reg[0].match(line):
   snip = True
  if snip:
   remove_count += 1
  else:
   clean_result.append(line)
  if snip and php_infection_reg[1].match(line):
   snip = False
   print 'Removing %d lines' % remove_count

 if not snip:
  infected_file.close()

  # Save in place
  clean_file = open(filename, "w")
  clean_file.writelines(clean_result)
  clean_file.close()
 else:
  'End sequence not found. Aborting!'



Conveniently, the attackers left some tags around their handiwork that makes it easy to excise just the portions that don't belong.

Definitely make a backup before running the above script. It could conceivably remove more than just the exploit, though I haven't seen that happen.

find . -name "*.php" > filelist.txt
python ./removeWebBug.py --filelist filelist.txt | less

The output of the script should look something like:

Processing ./php/lib/modifier.sprintf.php
Removing 105 lines
Processing ./php/lib/modifier.strip_linefeeds
.php
Removing 105 lines