applicaon security - hd7exploit.files.wordpress.com · modules • web applicaon security [season...
TRANSCRIPT
WhoamI?
• SecurityResearcherandDeveloper.• FocusonWebsiteApplica'onVulnerabilityAnalystandExploita'on.
• Hackingforfun…
Applica'onSecurity-Nam.Dinh 2
Modules• WebApplica'onSecurity[season1]
1. NodeJsApplica'onSecurity.[3hours]2. PHPApplica'onSecurity,WebApplica'onFirewall,
IntrusionDetec'onSystem.[3hours]• Wri'ngExploita'on[season2]
1. C/C++,Assembly,Disassembly,ReverseEngineering,WriVngShellcode…[8hours]
2. Exploit:StackOverflow,HeapOverflow,Off-By-One,FormatString,UseA^erFree…[8hours]
3. SEHoverwrite,Egghun'ng,ROPchains,bypassDEP,ASLR…[8hours]
Applica'onSecurity-Nam.Dinh 3
AgendaSeason1.1NodeJsApplica'onSecurity
I. Introduc'onII. NodeArchitectureIII. VulnerabilityManagementIV. CrossSiteScrip'ng–XSSV. CrossSiteRequestForgery–CSRFVI. DirectoryTraversalVII. CommandInjec'onVIII. Objec'onInjec'onIX. SQLInjec'on–SQLiX. DOSXI. BruteForceXII. MemoryLeakXIII. ProtectdataXIV. Authen'ca'on&Authoriza'onXV. LogXVI. Misconfigura'on,SSLXVII. HelmetXVIII. Demo&&Q&A
Applica'onSecurity-Nam.Dinh 4
I.Introduc'onElementsofInforma'onsecurity
Confiden/ality–dataandinforma'onassetsmustbeconfinedtopeopleauthorizedtoaccessandnotbedisclosedtoothers;Integrity–keepingthedataintact,completeandaccurate,andITsystemsopera'onal;Availability–authorizeduserswhenneeded.
Applica'onSecurity-Nam.Dinh 5
hkp://resources.infosecins'tute.com/key-elements-informa'on-security-policy
I.Introduc'onToolsandServices
• Acune/x:testsforSQLInjec'on,XSS,XXE,SSRF,HostHeaderInjec'onandover3000otherwebvulnerabili'es.
• BurpSuite:Coverageofover100genericvulnerabili/es,suchasSQLinjec'onandcross-sitescrip'ng(XSS),withgreatperformanceagainstallvulnerabili'esintheOWASPtop10.
• sucuri.net:Mi'gateDDoSakacks,improveandop'mizeyourwebsite'sperformance,andstophackersfromexploi'ngso^warevulnerabili'es(i.e.,SQLi,XSS,RCE,etc.).Cloud-basedprotec'on,noinstalla'onrequired.
• Nmap,Netcat,Metasploit,Kali2…
Applica'onSecurity-Nam.Dinh 8
I.Introduc'onSta'cSecurityAnalyst
–PakernMatching§ Ischeckedagainstalistofan'pakerns.
–Tain'ng
§ Givenanakackvectorcomingthroughreq.query/req.body§ Checkifitreachesnon-sani'zedhtmlcontexts(XSS)orSQL
calls(SQLi)
–SymbolicExecu'on(mostcomputa'onallyexpensive)§ Exploreallbranchesthatmightbetraversed§ Executeaprogramwithoutaconcretevalueliketain'ng§ Determinewhatconstraintscanreachapar'cularbranch(if(s==1)fail())
Applica'onSecurity-Nam.Dinh 9
NodeJsApplica'onSecurity
-Somedemosandexamplesexploitrealmodulesandapplica'onsthatisrequire:
Ø BasicunderstandingwebprogramingØ JavascriptØ NodejsØ Top10OWASPwebapplica'on.
-Don’ttrainprogramingwithnodejsandjavascript-A^erthismoduleyoucan:
Ø UnderstandingandApplingbestsecurityprac'cesforrealapplica'ons.
Ø CanexploitNodejsApplica'on.Applica'onSecurity-Nam.Dinh 10
VulnerabilityManagement• CVE:hkp://cve.mitre.org/inuse/:Astheinterna'onalindustrystandardforcybersecurityvulnerabilityandexposurenames,CVEIden'fiersareincludedinnumerousproductsandservicesandarethefounda'onofothers.
• Securityupdates:– hkps://nodejs.org/en/blog/vulnerability/-Nodejs– hkps://expressjs.com/en/advanced/security-updates.html-Express
– Snyk-ThirdParty– hkps://nodesecurity.io/-ThirdParty
Applica'onSecurity-Nam.Dinh 11
Firstofall• Strictmodechangesbothsyntaxandrun'mebehaviortobelesstolerantoferrorsandambiguousconstructs.
• JavaScriptrepresentsallnumbersasdoublefloa'ngpointnumbers.
• ParseInt,ParseFloat.• Bydefault,variablesareglobal.• Usestrictcomparison===toavoidconversionissueswithcomparisons.
• _.isEmpty(11)-Lodash• PreventParameterPollu'ontoStopPossibleUncaughtExcep'ons
• …hkps://nodesource.com/blog/nine-security-'ps-to-keep-express-from-geVng-pwned/
Applica'onSecurity-Nam.Dinh 13
1.Crosssitescrip'ng-XSS
• Allowakackertoinjectclient-clientscriptsintouser’sbrowser.
• 3types:Reflected,Stored,andDOM.• CheckUrl,HTMLbody,submikeddata,CSSakributes,Javascript…
• Templateenginelibrarydoesthiswellenoughbydefault?
• Akackvectors:post,comment,form,email…
Applica'onSecurity-Nam.Dinh 14
2.CrossSiteRequestForgery-CSRF
• Forceuser’sbrowertosendrequestsdonotintend.
• Protec'on:– Csurf
<inputtype="hidden"name=“csrf”value={{csr^oken}}/>
– Doublecookies• Check:hkps://hd7exploit.wordpress.com/2017/05/27/dvwa-csrf-high-level/
Applica'onSecurity-Nam.Dinh 16
3.Dic/onarytraversal
• Allowhackerstoaccessfilesrestrictedoutsiterootwebdirectory.varreadStream=fs.createReadStream(fullFilePath);readStream.on('error',func'on(err){res.json({'error':err});});readStream.pipe(res);
hkps://pentest.wp/salary?file=..%2F..%2F..%2F..%2Fetc%2Fpasswd
Applica'onSecurity-Nam.Dinh 17
4.Commandinjec'on
• Commandsexecutedthroughthechild_processmodule,usingexec[/bin/sh],execFile,spawn,orfork.
• execFile,however,executesthefiledirectly,givingakackersamuchsmallerakacksurface(limitedbythefilebeingexecuted).varparsedUrl=url.parse(request.url,true);response.writeHead(200,{"Content-Type":"text/html"});exe.exec('ping-c2'+parsedUrl.query.ping,func'on(err,data){ response.write("Hello"+data); response.end();});
hkps://nodesecurity.io/advisories/117
Applica'onSecurity-Nam.Dinh 18
WTH
• shell-quotecannotcorrectlyescapetheredirec'onoperators‘>’,‘<’whenusedinsideofthe.quote()func'on.
• Vulcode:hkps://github.com/substack/node-shell-quote/blob/1.6.0/index.js
hkps://www.npmjs.com/package/shell-quoteApplica'onSecurity-Nam.Dinh 19
5.Objec'onInjec'on
• eval()func'onisacommonfunc'onofnodejsthatiseasytoexploitifdatapassedtoitnotfilteredcorrectly
• hkps://hd7exploit.wordpress.com/2017/05/29/exploi'ng-node-js-deserializa'on-bug-for-
remote-code-execu'on-cve-2017-5941/
Applica'onSecurity-Nam.Dinh 20
WOW• Dust.jshelper• Ref:hkp://artsploit.blogspot.com/2016/08/pprce2.html?m=1
hkps://github.com/hapijs/bassmasterTheLibusedbyPaypalisvulsinthepastApplica'onSecurity-Nam.Dinh 21
6.SQLinjec'on• Injectarbitrarydataintoqueryleadtobypassauthen'ca'on,controldata,
executecommandsontheopera'ngsystem…• Error-basedSQLi• Union-basedSQLi
– SELECT*FROMuserWHEREid='1'UNIONALLSELECTNULL,CONCAT(0x717a7a6a71,(CASEWHEN(ISNULL(TIMESTAMPADD(MINUTE,6999,NULL)))THEN1ELSE0END),0x717a6b7a71),NULL–Melq’
– SELECT*FROMuserWHEREid='1'UNIONALLSELECTNULL,CONCAT(0x717a7a6a71,IFNULL(CAST(schema_nameASCHAR),0x20),0x717a6b7a71),NULLFROMINFORMATION_SCHEMA.SCHEMATA–jPek’
• BlindSQLi– SELECT*FROMuserWHEREid='1'AND7507=IF((48=48),SLEEP(5),7507)–SXqI’– SELECT*FROMuserWHEREid='1'AND23=23AND'xWyF'='xWyF’
• Libs:Node-mysql,serialize…• SeVng:mul'pleStatements:false
Applica'onSecurity-Nam.Dinh 22
WOW
./sqlmap.py-u"hkps://pentest.wp/sqli?id=1"--fresh-queries--techniqueu--dbs
hkps://s3.amazonaws.com/snyk-rules-pre-repository/snapshots/master/patches/npm/sequelize/20160106/sequelize_20160106_d198d78182cbf1ea3ef1706740b35813a6aa0838.patch
serialize
Applica'onSecurity-Nam.Dinh 23
7.MemoryLeak
• Bufferwillbeeasilyrunoutofmemory.• BuffersinV8[32bit]cannotbebiggerthan0x3FFFFFFFbytes(aliklebitlessthan1GB)
• Readchunksinto1bufferandreturnthisbufferwhenit'sdone.
• vardata=newBuffer(inputData);???
Applica'onSecurity-Nam.Dinh 24
8.Protec'ondata• Cryptographyisaresource-heavyprocess.• hkps://github.com/rzcoder/node-rsa• hkps://github.com/brix/crypto-js• hkps://nodejs.org/api/crypto.html
Applica'onSecurity-Nam.Dinh 25
varcrypto=require('crypto'),algorithm='aes-256-ctr',password='d6F3Efeq’;func'onencrypt(text){varcipher=crypto.createCipher(algorithm,password)varcrypted=cipher.update(text,'u�8','hex')crypted+=cipher.final('hex');returncrypted;}func'ondecrypt(text){vardecipher=crypto.createDecipher(algorithm,password)vardec=decipher.update(text,'hex','u�8')dec+=decipher.final('u�8');returndec;}varhw=encrypt("helloworld")//outputshelloworldconsole.log(decrypt(hw));
Pre-sharekey
hkps://github.com/chris-rock/node-crypto-examples/blob/master/crypto-stream.jsApplica'onSecurity-Nam.Dinh 26
9.Authen'ca'on&Authoriza'on• Timeoutsesssion,HTTPonly,Secure=true• Hash+saltwithbcrypt,makestrongrule.Passwordsal9ngmeansadding
asecretstringtoallpasswordsbeforehashingtheminordertoavoidgeVngthesamehashforcommonpasswords.
• User2password,2factorauthen'ca'on,2user,OTP• Checken/tyowneronAPI,Route,Datasentbyclientoranother
services...
app.use(session({secret:'mySecretCookieSalt',key:'myCookieSessionId',cookie:{hkpOnly:true,secure:true,domain:'example.com',path:'/foo/bar',//Cookiewillexpirein1hourfromwhenit'sgeneratedexpires:newDate(Date.now()+60*60*1000)}}));
Applica'onSecurity-Nam.Dinh 28
10.Bruteforce• Dic'onary• Rainbowtable• Randomize• express-limiter-whicheffec'velyblocksanIPaddressfrommakinganoutrageous
numberofrequests.
varclient=require('redis').createClient()varlimiter=require('express-limiter')(app,client)//BruceForcepreventlimiter({path:'/bf',method:'get',lookup:'headers.x-forwarded-for',//behindaproxy//10requestsperminutetotal:10,expire:1000*60})
Applica'onSecurity-Nam.Dinh 29
hkps://www.howtogeek.com/166832/brute-force-akacks-explained-how-all-encryp'on-is-vulnerable/
11.DOS• EvilRegexes:ARegexiscalled"evil"ifitcanstuckoncra^ed
input.Thatcausesanalgorithmtoruninthemostinefficientwaypossible
• EvilRegexpaYerncontains:– Groupingwithrepe''on– Insidetherepeatedgroup:– Repe''on– Alterna'onwithoverlapping
• ExamplesofEvilPaYerns:– (a+)– ([a-zA-Z]+)*– (a|aa)– (a|a?)+– (.*a){x}|forx>10
• Detec/on:RXRR(sta'canalysis),SDLRegExFuzzer.Applica'onSecurity-Nam.Dinh 30
HowRegExEnginesWork
• WhenapplyingcattoHecapturedaca[ishforhiscat.Whathappened?
• MomentJS-varMONTHS_IN_FORMAT=/D[oD]?(\[[^\[\]]*\]|\s+)+MMMM?/;[exploited]+varMONTHS_IN_FORMAT=/D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/;[fixed]
Applica'onSecurity-Nam.Dinh 31
hkp://www.regular-expressions.info/engine.htmlhkp://www.regular-expressions.info/catastrophic.html
11.DOS&DDOS• Exploitweeknessonsourcecode.• Preventvalidrequest• Synchronousac/onislongwillleadto
DOS…
• Nginxforsta'cfileserving• Usingmul/pleprocesses• process.nextTick:runbeforeanyI/Ois
firedoneventqueue[willbeinvokedonnextevenloop]
• setImmediate:pushedontheendofeventqueueofeventI/O
hkp://www.cisco.com/c/en/us/about/press/internet-protocol-journal/back-issues/table-contents-30/dos-akacks.html Applica'onSecurity-Nam.Dinh 32
12.Log
• Donotlogsensi'veinforma'on.• Logrequest/response.• LogUsertransac'ons.• Libs:Winston,morgan…• …• ThinkofLogcentralize,SIEM
Applica'onSecurity-Nam.Dinh 34
13.EnableTLS/SSL
• NginxandNodejs.• NginxSSLtermina'onwithNodejs.• Runsslyze,a2sv,NmaptovalidateSSLtransmission.
Applica'onSecurity-Nam.Dinh 35
OpenSSLHeartbleed• Thevulnerabilityaffectsallapplica'onsthatuseOpenSSLversions1.0.1-1.0.1fand
permitsanakackertoreadupto64kofservermemory.Thismemorycancontain:• HTTPrequestsmadebyotheruserstotheserver,whichmayinclude:
– Sessioncookies– Usernamesandpasswordssentinformfields– Useragentandotherheaderssentbytheclient
• HTTPresponsessentbytheservertootheruserscontainingsensi'veinforma'on• SSLencryp'onkeys• Emailmessages(incaseofSMTP,IMAPorPOP3)• Othersensi'vedatastoredinservermemory
Applica'onSecurity-Nam.Dinh 36
hkps://securityintelligence.com/heartbleed-openssl-vulnerability-what-to-do-protect/
SSLv3POODLE• (PaddingOracleOnDowngradedLegacyEncryp'on)• Thisvulnerabilitymayallowanakackerwhoisalreadyman-in-the-middle(atthenetwork
level)todecryptthesta'cdatafromanSSLcommunica'onbetweenthevic'muserandavulnerableserver.
• TheakackerwillprobablytrytoobtaintheHTTPcookiesorothersta'cdata.• Forthat,heneedstoconvinceboththevic'm'sbrowserandtheservertospeakSSLv3and
touseavulnerablecipher(inCipherBlockChainingmode).• ThiscouldbedonebyforcingadowngradeduringtheSSL/TLSnegocia'on.
Applica'onSecurity-Nam.Dinh 37
hkp://www.digitaltsunami.com/2014/10/15/poodle-sslv3-vulnerability/
1.ContentSecurityPolicy• ContentSecurityPolicyisanW3Cspecifica'onofferingthe
possbilitytoinstructtheclientbrowserfromwhichloca'onand/orwhichtypeofresourcesareallowedtobeloaded.
• Todefinealoadingbehavior,theCSPspecifica'onuse"direc've"whereadirec'vedefinesaloadingbehaviorforatargetresourcetype.
Applica'onSecurity-Nam.Dinh
hkps://www.html5rocks.com/en/tutorials/security/content-security-policy/
40
2.expectCt-Bhpkp• expectCtforhandlingCer'ficateTransparency• Cer'ficateTransparencyisanopenframeworkformonitoringand
audi'ngthecer'ficatesissuedbyCer'ficateAuthori'esinnearreal-'me.• ByrequiringaCAtologallcer'ficatestheygenerate.• Siteownerscanquicklyiden'fymis-issuedcer'ficatesanditbecomes
mucheasiertodetectarogueCA.
• GoogleannouncedinOctober2016thatallcer9ficatesissuedinOctober2017andbeyondwouldneedtobeloggedinCTorChromewouldnottrustthem.ThismeansthatifyouoperateawebsitethatusesHTTPSyouatleastneedtomakesureyourcer9ficateswillcomplywithChrome'sCTpolicybeforeOctober2017April2018(update)ifyouwantyoursitetoworkinChrome.
hkp://thehackernews.com/2016/04/ssl-cer'ficate-transparency.html
Applica'onSecurity-Nam.Dinh 41
3.HTTPPublicKeyPinning
• IfanakackerisabletocompromiseasingleCA,theycanperformMITMakacksonvariousTLSconnec'ons.
• HPKPcancircumventthisthreatfortheHTTPSprotocolbytellingtheclientwhichpublickeybelongstoacertainwebserver
Applica'onSecurity-Nam.Dinh
hkps://developer.mozilla.org/en-US/docs/Web/HTTP/Public_Key_Pinning
44
4.noCache-hidePowered
• noCachetodisableclient-sidecaching.• hidePoweredtoremovetheX-Powered-Byheader.
Applica'onSecurity-Nam.Dinh 45
5.hstsforHTTPStrictTransportSecurity
• Unfortunately,HSTSdoesn’tprotectthefirstrequestevermadebytheusertotheapplica'on.Somebrowsersworkwiththislimita'onbyreferencingapredefinedlistofsitesusingHSTS.
Applica'onSecurity-Nam.Dinh 46
WOW
hkps://www.nginx.com/blog/hkp-strict-transport-security-hsts-and-nginx/
Applica'onSecurity-Nam.Dinh 47
6.noSniff-ieNoOpen• TokeepclientsfromsniffingtheMIMEtype:• Ifafile’sextension,thesignatureandtheContent-Typediffer,IEwilldeterminetheMIMEtypebyitsfirst256bytes.
• However,ifanuploadedimagecontainsHTMLand/orJavaScriptcodeandtheuserclicksonalinktodownloadthefile,IEwillexecutethatcode.
• X-Download-Op9ons:noopen• FixedonIE8
File.open(“security_logo_en.jpg”,“r”)do|f|puts“rejectfile”iff.read(256)=~/<(.)+>(.)*<\/(.)+>/iEnd
Applica'onSecurity-Nam.Dinh 48
7.frameguard
• Topreventclickjacking:• SendingtheproperX-Frame-Op'onsHTTPresponseheadersthatinstructthebrowsertonotallowframingfromotherdomains.
Applica'onSecurity-Nam.Dinh
hkps://www.owasp.org/index.php/Clickjacking_Defense_Cheat_Sheet49
8.dnsPrefetchControl
• ControlsbrowserDNSprefetching.• Thisimprovesperformancewhentheuserclicksthelink,buthasprivacyimplica'onsforusers.
• Itcanappearasifauserisvisi'ngthingstheyaren’tvisi'ng.
Applica'onSecurity-Nam.Dinh 50
9.referrerPolicy• Websitescanseewhereusersarecomingfrom.
• no-referrer-when-downgrade(default)• Theoriginissentasreferrertoa-priorias-much-securedes'na'on(HTTPS->HTTPS),butisn'tsenttoalesssecuredes'na'on(HTTPS->HTTP).
Applica'onSecurity-Nam.Dinh
hkps://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy
51
9.xssFilter
ParameterValueMeaning– 0XSSfilterdisabled– 1XSSfilterenabledandsani'zethepageifakackdetected1;mode=block XSSfilterenabledandpreventrenderingthepageifakackdetected1;report=hkp://example.com/report_URI XSSfilterenabledandreporttheviola'onifakackdetected
Applica'onSecurity-Nam.Dinh 52
10.HkpOnly
• NotallowthecookietobeaccessedviaaclientsidescriptsuchasJavaScript.
• TheHTTPTRACEresponseincludesalltheHTTPheadersincludingauthen'ca'ondataandHTTPcookiecontents,whicharethenavailabletothescript.
• Canbypassusing:hkps://www.owasp.org/index.php/Cross_Site_Tracing->disableTRACEmethodaswell.
Applica'onSecurity-Nam.Dinh 54
Synk
-npminstall–gsnyk-snykwizard
• Snykcon'nuouslyfindsandfixesvulnerabili'esinyourdependencies.
• ProtectandmonitoryourJavaScript,RubyandJavaapps
Applica'onSecurity-Nam.Dinh 56
JsLint• JSHintscansaprogramwrikeninJavaScriptandreports
aboutcommonlymademistakesandpoten'albugs.• ESLintdoesn’toffersecurityscanningoutofthebox• Toinstall:$npminstalleslint$npminstalleslint-plugin-scanjs-rules$npminstalleslint-plugin-no-unsafe-innerhtml• Downloadrulehkps://github.com/18F/compliance-toolkit/blob/master/configs/sta'c/.eslintrc• Runeslint.
Applica'onSecurity-Nam.Dinh 57
Tips• DisablingtheROOTaccountandenablingkeybasedauthen'ca'on.• Crea'ngalowprivilegeaccountandrunningourservicesunderit.• SeVngupsystemstoforkourserviceandtorestarttheserviceiftheservershould
reboot.• ConfiguringaproxyinfrontofourservertohandlefileservingandSSL.• Obtainingalegi'mateSSLcer'ficateforourservice.• Helmet.• Configuringourfirewall.• Updatelatestso^ware.• Runscanner.• Donotshowerror.• Uninstallunnecessaryservice.• Checkconfigura'ondefault.• Developershouldbeawarewebsitesecurity.• …
Applica'onSecurity-Nam.Dinh 58
Reference1. TheWebApplica/onHacker'sHandbook:Findingand
Exploi/ngSecurityFlaws2ndEdi'on2. NodejsdesignpaYern2ndEdi/on3. SecureYourNode.jsWebApplica/on:KeepAYackers
OutandUsersHappy4. hkps://kb.sucuri.net/warnings/hardening/disable-server-
banners5. hkps://www.blackhat.com/docs/us-15/materials/us-15-
Siman-The-Node-Js-Highway-Akacks-Are-At-Full-Throkle.pdf
6. hkps://pdfs.seman'cscholar.org/187d/26258dc57d794ce4badb094e64cf8d3f7d88.pdf
7. …
Applica'onSecurity-Nam.Dinh 60