How to Remove the if(!isset($GLOBALS[…])) Malware Code from WordPress Themes

While editing a WordPress theme, I unexpectedly found a block of code like this at the top of every theme file:

if(!isset($GLOBALS["x61156x75156x61"])) { $ua=strtolower($_SERVER["x48124x54120x5f125x53105x52137x41107x45116x54"]); ...

I did not know exactly what the code was doing, and nothing looked obviously broken on the site. Even so, we cannot just let malicious code stay hidden inside a theme, so I searched for a solution and found an approach on Stack Overflow.

How to clean up the malicious code

The following Bash script can be uploaded to the server. Run ./remove_malware.sh /var/www/wp_path/ clean to remove the malicious code.

#!/bin/bash
#
# This script remove malware of PHP files.
#

if [[ -z "$1" ]]; then
  echo "Directory where to find is required."
else
  grep -rnwl $1 --include *.php -e "\x48\124\x54\120\x5f\125\x53\105\x52\137\x41\107\x45\116\x54" | while read -r filename ; do

    if [[ ! -z "$2" ]]; then
       echo "Found file $filename. Cleaning..."
       awk 'BEGIN {matches=0} matches < 1 && /1/ { sub(/^.*<?php/,"<?php"); matches++ } { print $0 }' $filename > $filename.purged
       mv $filename $filename.bck
       mv $filename.purged $filename
    else
      echo "Found file $filename."
    fi

  done
  echo "Done."
fi

Testing showed that the script may occasionally misidentify a normal file and delete the first line of valid code. The odds are relatively low, but to be safe, back up the whole site before removing anything.

After running the script above, it creates some backup files with the .bck suffix. If you want to clean up those files too, run the command below.

find . -name *.bck | xargs rm -vf

Related Posts

Leave a Reply

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