Page 1
19/09/17
1
OffensivetechnologiesFall2017
Lecture1-GeneralIntroduc1ontoVulnerabili1esinWebApplica1ons
FabioMassacci
h<ps://securitylab.disi.unitn.it/doku.php?id=course_on_offensive_technologies
1
Aboutthislecture
• Thewholecourseisdedicatedtotheiden1fica1on,tes1ngandmi1ga1onofvariousformsofsecurityvulnerabili1es
• Thepurposeofthislectureistobrieflyintroducethebackgroundneededforrecognizingsomeofthevulnerabili1esinthesourcecode
• Wewilltestthisabilityusingaprac1calexerciseonWednesday:itisimportantforthela<erpartofthecourse
2
Page 2
19/09/17
2
Outline
• Vulnerabili1esinwebapplica1ons• Injec1onvulnerabili1es• Informa1onDisclosurevulnerabili1es• SessionFixa1onvulnerabili1es• DenialofServicevulnerabili1es
3
Vulnerabili;esinwebapplica;ons
• ManysecurityholesincorporateITarenotduetowormsorviruses,butduetovulnerabili1esinthesourcecodeofapplica1ons– Thesevulnerabili4esareo6enexploitedbya<ackersforbothfunandprofit
• Differencesbetweenwebandclient-serverapplica1onsopenenterprisestosignificantrisk– JavaScripthasdiffusedboundariesbetweenclientandserver– Easiertodeploy,hardertomaintainsecurely
• Webapplica1onsecurityiscri1calforbusinesses• Findingandfixingwebapplica1onvulnerabili1esismostlyaboutlookingatthesourcecode
4
Page 3
19/09/17
3
Prac;calApproachesinVulnerabilityDiscovery(con;nued)• Plantohaveeverythingcompromised– Everythingisvulnerable
• RelyontoolstodetectandcorrectSPECIFICproblemsbutnotreplaceeverythingbytools– Toolscanhelpfindingcertainvulnerabili4esbuttheyarenothingwithoutknowledge
• Learnfrom(preferably)other’smistakes– WecanuseOpenSourceSo6waretolearn
5
WhylookingatopensourcesoHware?
• Thereisli<ledifferencewithcommercialso[ware
• Thesourcecodeanddevelopmenthistoriesareavailable
• O[en,opensourcemaintainersaredoingagoodjobindocumen1ngvulnerabili1es,soitispossibletoreverse-engineerthem
• Manycommercialsystemsareusingopensourcecomponents,thusthelearningeffortwillbeuseful
6
Page 4
19/09/17
4
Aquicklookatvulnerabili;estaxonomy
• Therearedifferentcategories,classifica1onsanddatabases– OpenWebApplica4onSecurityProject(OWASP)Top10list– CommonWeaknessEnumera4on(CWE)– CommonWeaknessScoringSystem(CWSS)– TheNa4onalVulnerabilityDatabase(NVD)– Open-sourcedVulnerabilityDatabase(OSVDB)– IARPASecurelyTakingOnNewExecutableSo6wareofUncertain
Provenance(STONESOUP)
• Almostallthesevulnerabili1esarerelatedtoproblemsinthesourcecode– Designerrors– Implementa4onerrors– ManyofthemareLanguage/Frameworkindependent
7
OWASPTop10(2013)A3:Cross-siteScrip4ng(XSS)A1:Injec4on
A2:BrokenAuth.andSessionManagement
A4:InsecureDirectObjectReferences
A5:SecurityMisconfigura4on
A6:Sensi4veDataExposure
A7:MissingFunc4onLevelAccessControl
A8:Cross-siteRequestForgery
(CSRF)
A9:UsingComponentWithKnownVulns.
A10:UnvalidatedRedirectsandForwards
8
Page 5
19/09/17
5
CommonWeaknessEnumera;on(CWE)
• h<ps://cwe.mitre.org/• Aformaldic1onaryofcommonso[warebugs/flawsthatoccurinso[warearchitecture,design,andimplementa1onthatcanleadtoexploitablesecurityvulnerabili1es(>800entries)
• Acommonlanguagefordescribingandastandardformeasuringsuchbugs/flaws
• Informa1onaboutiden1fica1on/mi1ga1on/preven1onefforts
9
CommonWeaknessEnumera;on(CWE)
10
Page 6
19/09/17
6
CommonWeaknessEnumera;on(CWE)
11
TheNa;onalVulnerabilityDatabase(NVD)
• h<ps://nvd.nist.gov/• TheUSGovernmentrepositoryofvulnerabilitydata• Enablesautoma1onofvulnerabilitymanagement,securitymeasurementandcompliance
• Includesdatabasesofsecurity-relatedso[wareflaws/bugs,productnames,andimpactmetrics
• SupportstheCommonVulnerabilityScoringSystem(CVSS)scores– Quan4fiescharacteris4csofeachvulnerabilitysothattheycanbecompared
12
Page 7
19/09/17
7
TheNa;onalVulnerabilityDatabase(NVD)
13
Outline
• Vulnerabili1esinwebapplica1ons• Injec1onvulnerabili1es• Informa1onDisclosurevulnerabili1es• SessionFixa1onvulnerabili1es• DenialofServicevulnerabili1es
14
Page 8
19/09/17
8
Injec;onvulnerabili;es
• Assumeanapplica1oniswri<eninmul1plelanguages:Java,JavaScript,HTML,SQL…
• Anapplica1onacceptsanyuserinputwithoutsani1za1on– Problem:someinputthatlookslikeaStringinJavacanbeacceptedasapieceofexecutablecodebySQL,JavaScript,orHTMLinterpreters
– Thesearealsocalled”polyglot”vulnerabili4es• Consequences?
– Websitedefacement– …– Completecontroloverthemachinethathoststhevulnerableapplica4on
15
SQL/NoSQLinjec;on
• Descrip1on:– Duetoinsufficientinputfiltering(oroutputescaping)a<acker-controlledinputmaybeinterpretedascodebyadatabaseinterpreterandexecuted[1].Eventualoutcomeiscodeexecu4on.
• RelatedThreats:Informa1onDisclosure,DataModifica1on/Dele1on,Eleva1onofPrivileges.
• TechnicalImpact:Severe.16
Page 9
19/09/17
9
SQLinjec;on:exampleUserDatadata=getDataFromUser();StringuserId=data.getUserId();Stringpasswd=data.getPasswd();SomeDB.executeQuery("SELECT*FROMusersWHEREusers.userId=’
+userId+”’ANDusers.passwd='”+passwd+“'");
query<-"SELECT*FROMusersWHEREusers.userId=’Batman’OR’1’==’1’;DROPTABLEusers;--’ANDusers.passwd=’’"
userId<-“Batman’OR’1’==’1’;DROPTABLEusers;--”passwd<-“”
userid<-”JohnDoe”passwd<-”qweJk@#4kw”query<-"SELECT*FROMusersWHEREusers.userId=’JohnDoe’ANDuser.passwd=’qweJk@#4kw’”
17
NoSQLinjec;on:example
*Theimageistakenfromh<p://www.busanhlf4.org/18
Page 10
19/09/17
10
NoSQLinjec;on:example
*Theimageistakenfromh<p://www.busanhlf4.org/19
SQL/NoSQLinjec;on:howtofindit?
• Youshouldbesuspiciousifanapplica1on– Getsuserinput– Doesnotcheck/sani4zetheinput– Usesthisinputtoconstructaquerytoadatabase– Usesstringopera4ons(e.g.,concatena4on,replacement)tobuildaquery
Language KeywordsJava(+JDBC) sql,java.sql
Python pymssql,
C# Sql,SqlClient,OracleClient,SqlDataAdapter
PHP mysql_connect
Node.js require("mysql”),require(”mssql"),require("mongodb") 20
Page 11
19/09/17
11
Cross-SiteScrip;ng(XSS)
• Descrip1on:– "Insufficientinputvalida4onoroutputescapingcanallowana<ackertoplanthisownHTMLorscriptsonavulnerablesite.Theinjectedscriptswillhaveaccesstotheen4retyofthetargetedwebapplica4on…"[2].
– Thereflectedvarianttakestheadvantagewhentheinputisincorrectlyechoedbacktothebrowser;thepersistentvariantgoesabitfurther:italsotakestheadvantageonthelackofsani4za4onofthedatathatgoestoaDB.
• RelatedThreats:– Informa4onDisclosure,Eleva4onofPrivileges.
• TechnicalImpact:– Moderate/Severe
21
Cross-SiteScrip;ng(XSS):reflected
…<%StringuserId=request.GetParameter(”userId")%>…<html>...<h1>
Hello,<%=userId%>!</h1>...</html>
h<p://homepage.jsp?userId=John
22
Page 12
19/09/17
12
Cross-SiteScrip;ng(XSS):reflected
…<%StringuserId=request.GetParameter(”userId")%>…<html>...<h1>
Hello,<%=userId%>!</h1>...</html>
h<p://homepage.jsp?userId=<script>alert(’XSS');</script>
23
Cross-SiteScrip;ng(XSS):stored
Database
*Thediagramisadaptedfrom[3].
Step0->developerwritesvulnerablepages:1stonestoresinvalidatedinput;2ndonereadsitfromadatabaseandwithnovalida4on.
Step1->A<ackersendsmalformedinput(code)toavulnerablewebpage.
Step2->Userbrowsesthesite.Step3->Websitereadsuncheckeddataandsendsitalongwitha<acker’scodetotheuser’sbrowser.
Step4->User’sbrowserrendersthewebpageandrunsthea<acker’scode(every4methepageisrequested!)
24
Page 13
19/09/17
13
Cross-SiteScrip;ng(XSS):someexamples(reflected)
publicclassXSSextendsHttpServlet{protectedvoiddoGet(HttpServletRequestrequest,
HttpServletResponseresponse){/*...*/
response.sendError(HttpServletResponse.SC_NOT_FOUND, "Thepage\""+
request.getParameter("page")+ "\"wasnotfound.");
}}
h<p://homepage.jsp?page=123
25
Cross-SiteScrip;ng(XSS):someexamples(reflected)
publicclassXSSextendsHttpServlet{protectedvoiddoGet(HttpServletRequestrequest,
HttpServletResponseresponse){/*...*/
response.sendError(HttpServletResponse.SC_NOT_FOUND, "Thepage\""+
request.getParameter("page")+ "\"wasnotfound.");
}}
h<p://homepage.jsp?page=<script>alert(’XSS')</script>
26
Page 14
19/09/17
14
Cross-SiteScrip;ng(XSS):someexamples(stored)
<%...Stringeid=request.GetParameter(”eid”);Statementstmt=conn.createStatement();ResultSetrs=stmt.executeQuery(”select*
fromempwhereid='”+eid+”'”);if(rs!=null){rs.next();}Stringbio=rs.getString(”bio”);Employeebiography:<%=bio%> …%>
h<p://show-employee.jsp?eid=123
27
Cross-SiteScrip;ng(XSS):someexamples(stored)
<%...Stringeid=request.GetParameter(”eid”);Statementstmt=conn.createStatement();ResultSetrs=stmt.executeQuery(”select*
fromempwhereid='”+eid+”'”);if(rs!=null){rs.next();}Stringbio=rs.getString(”bio”);Employeebiography:<%=bio%> …%>
h<p://show-employee.jsp?eid=qwe‘or’1’==’1’;insertintoemp(bio)values('<script>alert(\"XSS\")</script>’)select*fromemp;--
28
Page 15
19/09/17
15
Cross-SiteScrip;ng(XSS):howtofindit?
• Youshouldbesuspiciousifanapplica1on– GetsaninputfromanHTTPen4tysuchasquerystring,headerorform,orrequestobject
– Doesnotchecktheinputforvalidity– Echoesitbacktothebrowser(eitherHTMLorHTTPheaders),savingittoorretrievingfromadatabaseunchecked
29
Cross-SiteScrip;ng(XSS):howtofindit?
Language Keywords
Java(JSP) addCookie,getRequest,request.getParameterfollowedby<jsp:setPropertyor<%=orresponse.sendRedirect
Python form.getvalue,SimpleCookiewhenthedataisnotvalidatedcorrectly.
C# Request.*,Response.*,and<%=whenthedataisnotvalidatedcorrectly.
PHP Accessing$_REQUEST,$_GET,$_POST,or$_SERVERfollowedbyecho,print,header,orprintf.
Node.js request,response,…
30
Page 16
19/09/17
16
Outline
• Vulnerabili1esinwebapplica1ons• Injec1onvulnerabili1es• Informa1onDisclosurevulnerabili1es• SessionFixa1onvulnerabili1es• DenialofServicevulnerabili1es
31
Informa;onDisclosurevulnerabili;es
• Descrip1on:– A<ackerisabletogetdatathatleadstoabreachinsecurityorprivacypolicy.Thedataitselfcouldbethegoal,orthedatacanprovideinforma4onthatleadsthea<ackertothegoal.
– Inten;onal:thedesignteamhasamismatchwiththeenduserastowhetherdatashouldbeprotected(privacyissues).
– Accidental:thedatacouldleakduetoanerrorinthecode,oranonobviouschannel.
– Mistake:verbose[error]messagesthatdevelopersthinkaresafe,buta<ackersfindthemhelpful,e.g.,thenameortheipaddressofaserver
– Threemaincategories:hardcodedcreden4als,commentsinthesourcecode,andverboseerrormessages.
• Technicalimpact:couldbeanything
32
Page 17
19/09/17
17
Informa;onDisclosure:example0
try{/*...*/
}catch(Exceptione){
System.out.println(e);e.printStackTrace();
}
33
Informa;onDisclosure:example1
34
Page 18
19/09/17
18
Informa;onDisclosure:example2
publicbooleanauthenticate(Requestreq,Responseres){/*...*/if(config.getRealmName()==null){
authenticateCC.append(request.getServerName());authenticateCC.append(':');authenticateCC.append(Integer.toString( request.getServerPort()));
}else{
authenticateCC.append(config.getRealmName());}return(false);}
35
Informa;onDisclosure:example2
publicbooleanauthenticate(Requestreq,Responseres){/*...*/if(config.getRealmName()==null){
authenticateCC.append(request.getServerName());authenticateCC.append(':');authenticateCC.append(Integer.toString( request.getServerPort()));
}else{
authenticateCC.append(config.getRealmName());}return(false);}
36
Page 19
19/09/17
19
Informa;onDisclosure:example2
publicbooleanauthenticate(Requestreq,Responseres){/*...*/if(config.getRealmName()==null){
authenticateCC.append(request.getServerName());authenticateCC.append(':');authenticateCC.append(Integer.toString( request.getServerPort()));
}else{
authenticateCC.append(config.getRealmName());}return(false);}
37
Informa;onDisclosure:example3
Loginsuccessful:"authen4cate"methodreturns”true”
38
Page 20
19/09/17
20
Informa;onDisclosure:example3(con;nued)
password=null;
Maythrownullreferenceexcep4on
39
Informa;onDisclosure:howtofindit?
• Applica1onreturns”default”informa1onsuchasservertype/configura1on/ipaddress/hostname.
• Toomanydetailsinerrormessages,unhandledexcep1ons,stacktraces;differenterrormessageswhenhandlinguserlogin.
• Lookfor”password”,”creden1als”,“login”andsimilarkeywords,youmightfindsomethingquiteinteres1ng.
40
Page 21
19/09/17
21
PathTraversal
• Descrip1on:– Anapplica4oncanbetrickedintoreadingorwri4ngfilesatarbitraryloca4ons(o6enbypassingapplica4on-levelrestric4ons).Thiso6enhappensduetoimproperrecogni4onof”../”segmentsinunuser-suppliedparameters.Unconstrainedfilewri4ngbugsareo6enexploitedfordeployinga<acker-controlledcode[2].
• Relatedthreats:Informa1ondisclosure,codeinjec1on,denialofservice
• Technicalimpact:Moderate/Severe
41
PathTraversal:someexamples
Stringpath=getInputPath();if(path.startsWith("/safe_dir/")){Filef=newFile(path);f.delete();}
Thecodea<emptstovalidatetheinput
bywhitelis4ng.
Ifthefileiswithinthe”/safe_dir/”
folder,thefilegetsdeleted.
Ana<ackercouldprovideaninputsuch
as:/safe_dir/../data.db
Database
42
Page 22
19/09/17
22
PathTraversal:someexamples(con;nued)
publicvoidsendUserFile(Socketsock,Stringuser){BufferedReaderfilenameReader=newBufferedReader(newInputStreamReader(sock.getInputStream(),"UTF-8"));
Stringfilename=filenameReader.readLine();BufferedReaderfileReader=
newBufferedReader(newFileReader("/home/"+user+"/"+filename));
StringfileLine=fileReader.readLine();while(fileLine!=null){sock.getOutputStream().write(fileLine.getBytes());fileLine=fileReader.readLine();}}
43
PathTraversal:someexamples(con;nued)
publicvoidsendUserFile(Socketsock,Stringuser){BufferedReaderfilenameReader=newBufferedReader(newInputStreamReader(sock.getInputStream(),"UTF-8"));
Stringfilename=filenameReader.readLine();BufferedReaderfileReader=
newBufferedReader(newFileReader("/home/"+user+"/"+filename));
StringfileLine=fileReader.readLine();while(fileLine!=null){sock.getOutputStream().write(fileLine.getBytes());fileLine=fileReader.readLine();}}
44
Page 23
19/09/17
23
PathTraversal:howtofindit?
• Youshouldbesuspiciousifanapplica1on– Getsaninputfromuser– Theinputisusedtoconstructapathforanypurpose(downloading/uploadingfiles,redirects,etc.)
– Eveniftheinputlookslikeitissani4zed,sani4za4onfunc4onso6encontainerrors,soyoupayclosea<en4ontosani4zers
– Some4mestherearenopathconstraintsatall
45
Outline
• Vulnerabili1esinwebapplica1ons• Injec1onvulnerabili1es• Informa1onDisclosurevulnerabili1es• SessionFixa1onvulnerabili1es• DenialofServicevulnerabili1es
46
Page 24
19/09/17
24
SessionFixa;onvulnerabili;es
• Descrip1on:– Ana<ackthatallowstohijackavalidusersession.Whenauthen4ca4ngauser,anappdoesn’tassignanewsessionID,makingitpossibletouseanexistentsessionID.Thea<ackerhastoprovidealegi4mateWebapplica4onsessionIDandtrytomakethevic4m'sbrowseruseit.[5]
• Technicalimpact:Severe
47
SessionFixa;on:example*
*Thisexampleistakenfrom[4]. 48
Page 25
19/09/17
25
SessionFixa;on:example
1. Thea<ackerestablishesalegi1mateconnec1onwithawebserver;
2. ThewebserverissuesasessionID;3. Thea<ackerhastosendalinkwiththeestablishedsessionIDto
thevic1m;shehastoclickonthelink,accessingthesite;4. Thewebserver”sees”thatthesessionhasbeenalready
established(bythea<acker),soitdoesn’tcreateanewone;5. Thevic1mprovideshercreden1alstothewebserver;thea<acker
canaccessheraccountknowingthesessionID.
(sessionIDcanbealsosentviaacookieorahiddenfieldintheDOMcontainer)
49
SessionFixa;on:example(con;nued)
protectedbooleanparseRequest(Requestreq,Responseres){if(isURLRewritingDisabled(req)){clearRequestedSessionURL(req);}/*...*/ StringsessionID=
req.getPathParameter(Globals.SESSION_PARAMETER_NAME);if(sessionID!=null){req.setRequestedSessionId(sessionID);req.setRequestedSessionURL(true);}/*...*/ } 50
Page 26
19/09/17
26
SessionFixa;on:example(con;nued)
protectedbooleanparseRequest(Requestreq,Responseres){if(isURLRewritingDisabled(req)){clearRequestedSessionURL(req);}/*...*/ StringsessionID=
req.getPathParameter(Globals.SESSION_PARAMETER_NAME);if(sessionID!=null){req.setRequestedSessionId(sessionID);req.setRequestedSessionURL(true);}/*...*/ } 51
SessionFixa;on:example(con;nued)
protectedbooleanparseRequest(Requestreq,Responseres){if(isURLRewritingDisabled(req)){clearRequestedSessionURL(req);}/*...*/ StringsessionID=
req.getPathParameter(Globals.SESSION_PARAMETER_NAME);if(sessionID!=null){req.setRequestedSessionId(sessionID);req.setRequestedSessionURL(true);}/*...*/ } 52
Page 27
19/09/17
27
SessionFixa;on:example(con;nued)
protectedbooleanparseRequest(Requestreq,Responseres){if(isURLRewritingDisabled(req)){clearRequestedSessionURL(req);}/*...*/ StringsessionID=
req.getPathParameter(Globals.SESSION_PARAMETER_NAME);if(sessionID!=null&&!isURLRewritingDisabled(req)){req.setRequestedSessionId(sessionID);req.setRequestedSessionURL(true);}/*...*/ } 53
SessionFixa;on:howtofindit?[5]
• Youshouldbesuspiciousiftheusualflowisbroken[6]– Userenterscorrectcreden4als– Theapplica4onauthen4catestheusersuccessfully– Sessioninforma4on(temporarydata)isstoredinatemporaryloca4on
– Sessionisinvalidated(session.invalidate())– Anytemporarydataisrestoredtonewsession(newsessionID)
– UsergoestosuccessfulloginlandingpageusingnewsessionID
54
Page 28
19/09/17
28
SessionFixa;on:howtofindit?(con;nued)[5]
• Checkforsessionfixa1onifausertriestologinusingasessionIDthathasbeenspecificallyinvalidated(requiresmaintainingthislistinsometypeofURLcache)
• Checkforsessionfixa1onifausertriestouseanexis1ngsessionIDalreadyinusefromanotherIPaddress(requiresmaintainingthisdatainsometypeofmap)
• Someserverapplica1ons(e.g.,JBOSS,Tomcat)haveaserngfordisablingURLrewri1ng->thismi1gatesthea<ackwhensessionIDisexposedviaGETparameterofaURL(aswellasbeingstoredinbrowserhistory,proxyservers,etc)
55
Outline
• Vulnerabili1esinwebapplica1ons• Injec1onvulnerabili1es• Informa1onDisclosurevulnerabili1es• SessionFixa1onvulnerabili1es• DenialofServicevulnerabili1es
56
Page 29
19/09/17
29
DenialofServicevulnerabili;es
• Descrip1on:– TheDenialofService(DoS)a<ackisfocusedonmakingaresource(site,applica4on,server)unavailableforthepurposeitwasdesigned.Ifaservicereceivesaverylargenumberofrequests,itmayceasetobeavailabletolegi4mateusers.Inthesameway,aservicemaystopifaprogrammingvulnerabilityisexploited,orthewaytheservicehandlesresourcesituses.
• Technicalimpact:Severe
57
DenialofService:example1
Wemay"kill”theserverbyfillingallof
itsmemory
58
Page 30
19/09/17
30
DenialofService:example2
Theuserhascontrolovertheloopcounter:wemaydecreaseserver’s
performanceorevenkillit.59
DenialofService:example3
BothConnec4onandCallableStatementobjectsshouldbeclosedinthe
“finally”block60
Page 31
19/09/17
31
DenialofService:howtofindit?
• Youshouldbesuspiciousif– User-controlledvaluesdefinethesizeofallocatedmemory,arraysorbuffers;
– User-controlledvaluesinfluenceloopcondi4ons;– ”Heavy”resourcesareneverreleased(filelocks/descriptors,databaseconnec4ons,datastreams,etc.)
– Thereisan"infinite"amountofresourcesthatasingleusercanallocate(e.g.,thenumberofworkingprocessesorserversockets);
61
References• [1]WebApplica1onVulnerabili1esandAvoidingApplica1onExposure
h<ps://f5.com/resources/white-papers/web-applica1on-vulnerabili1es-and-avoiding-applica1on-exposure
• [2]Zalewski,Michal.ThetangledWeb:Aguidetosecuringmodernwebapplica1ons.NoStarchPress,2012.
• [3]Howard,Michael,DavidLeBlanc,andJohnViega.24deadlysinsofso[waresecurity:programmingflawsandhowtofixthem.McGraw-Hill,Inc.,2009.
• [4]OWASP:thefreeandopenso[waresecuritycommunityh<ps://www.owasp.org/index.php/Main_Page
• [5]TheWhiteHatSecurityblogonSessionFixa1onpreven1on:h<ps://www.whitehatsec.com/blog/session-fixa1on-preven1on-in-java/
• [6]TheOWASPEnterpriseSecurityAPIsessionhandlingexample:h<ps://code.google.com/p/owasp-esapi-java/source/browse/trunk/src/main/java/org/owasp/esapi/reference/DefaultHTTPU1li1es.java
• [7]SecureCodingGuidelinesforJavaSEh<p://www.oracle.com/technetwork/java/seccodeguide-139067.html
62