OffensivetechnologiesFall2016
Lecture1- GeneralIntroductiontoVulnerabilitiesinWebApplications
StanislavDashevskyi
https://securitylab.disi.unitn.it/doku.php?id=course_on_offensive_technologies
1
Aboutthislecture
• Thewholecourseisdedicatedtotheidentification,testingandmitigationofvariousformsofsecurityvulnerabilities
• Thepurposeofthislectureistobriefly introducethebackgroundneededforrecognizingsomeofthevulnerabilitiesinthesourcecode
• WewilltestthisabilityusingapracticalexerciseonWednesday:itisimportantforthelatterpartofthecourse
2
Outline
• Vulnerabilitiesinwebapplications• Injectionvulnerabilities• InformationDisclosurevulnerabilities• SessionFixationvulnerabilities• DenialofServicevulnerabilities
3
Vulnerabilitiesinwebapplications
• ManysecurityholesincorporateITarenotduetowormsorviruses,butduetovulnerabilitiesinthesourcecodeofapplications– Thesevulnerabilitiesareoftenexploitedbyattackersforboth funandprofit
• Differencesbetweenwebandclient-serverapplicationsopenenterprisestosignificantrisk– JavaScripthasdiffusedboundaries betweenclientandserver– Easiertodeploy,hardertomaintainsecurely
• Webapplicationsecurityiscriticalforbusinesses• Findingandfixingwebapplicationvulnerabilitiesismostlyaboutlookingatthesourcecode
4
PracticalApproachesinVulnerabilityDiscovery
• Softwaresecurityisaproblemthatisveryhardtodefine
• ”Asystemissecureifandonlyifitstartsinasecurestateandcannotenteraninsecurestate”– theBell-LaPadula model– Evenifwecoulddefineit,it’simpossible toformalize:
• ”Idonotwantmyemail tobereadbyothers”– Thereisnowaytodefineadesiredbehavior foraconsiderablycomplex
system• Differentstakeholdersactaccordingtothe“tragedyofcommons"dilemma
– Itisnearlyimpossible toanalyzesoftwarebehaviorconclusively• A.Turing’shaltingproblem• H.G.Rice’s theorem
• Fornow,securityislargelyanon-algorithmicproblem– Eventually,securityfield specialistsfallbacktosetofempiricalrecipes
5
PracticalApproachesinVulnerabilityDiscovery(continued)
• Plantohaveeverythingcompromised– Everythingisvulnerable
• RelyontoolstodetectandcorrectSPECIFICproblemsbutnotreplaceeverythingbytools– Toolscanhelpfindingcertainvulnerabilitiesbuttheyarenothingwithoutknowledge
• Learnfrom(preferably)other’smistakes–WecanuseOpenSourceSoftwaretolearn
6
Whylookingatopensourcesoftware?
• Thereislittledifferencewithcommercialsoftware
• Thesourcecodeanddevelopmenthistoriesareavailable
• Often,opensourcemaintainersaredoingagoodjobindocumentingvulnerabilities,soitispossibletoreverse-engineerthem
• Manycommercialsystemsareusingopensourcecomponents,thusthelearningeffortwillbeuseful
7
Aquicklookatvulnerabilitiestaxonomy
• Therearedifferentcategories,classificationsanddatabases– OpenWebApplicationSecurityProject(OWASP)Top10list– CommonWeaknessEnumeration(CWE)– CommonWeaknessScoringSystem(CWSS)– TheNationalVulnerabilityDatabase(NVD)– Open-sourcedVulnerabilityDatabase(OSVDB)– IARPASecurelyTakingOnNewExecutableSoftwareofUncertain
Provenance(STONESOUP)
• Almostallthesevulnerabilitiesarerelatedtoproblemsinthesourcecode– Designerrors– Implementationerrors– ManyofthemareLanguage/Frameworkindependent
8
OWASPTop10(2013)A3:Cross-siteScripting(XSS)A1:Injection
A2:BrokenAuth.andSessionManagement
A4:InsecureDirectObjectReferences
A5:SecurityMisconfiguration
A6:SensitiveDataExposure
A7:MissingFunctionLevelAccessControl
A8:Cross-siteRequestForgery
(CSRF)
A9:UsingComponentWithKnownVulns.
A10:UnvalidatedRedirectsandForwards
9
CommonWeaknessEnumeration(CWE)
• https://cwe.mitre.org/• Aformaldictionaryofcommonsoftwarebugs/flawsthatoccurinsoftwarearchitecture,design,andimplementationthatcanleadtoexploitablesecurityvulnerabilities(>800entries)
• Acommonlanguagefordescribingandastandardformeasuringsuchbugs/flaws
• Informationaboutidentification/mitigation/preventionefforts
10
CommonWeaknessEnumeration(CWE)
11
CommonWeaknessEnumeration(CWE)
12
TheNationalVulnerabilityDatabase(NVD)
• https://nvd.nist.gov/• TheUSGovernmentrepositoryofvulnerabilitydata• Enablesautomationofvulnerabilitymanagement,securitymeasurementandcompliance
• Includesdatabasesofsecurity-relatedsoftwareflaws/bugs,productnames,andimpactmetrics
• SupportstheCommonVulnerabilityScoringSystem(CVSS)scores– Quantifiescharacteristicsofeachvulnerabilitysothattheycanbecompared
13
TheNationalVulnerabilityDatabase(NVD)
14
Outline
• Vulnerabilitiesinwebapplications• Injectionvulnerabilities• InformationDisclosurevulnerabilities• SessionFixationvulnerabilities• DenialofServicevulnerabilities
15
Injectionvulnerabilities
• Assumeanapplicationiswritteninmultiplelanguages:Java,JavaScript,HTML,SQL…
• Anapplicationacceptsanyuserinputwithoutsanitization– Problem:someinputthatlookslikeaString inJavacanbe
acceptedasapieceofexecutablecodebySQL,JavaScript,orHTMLinterpreters
– Thesearealsocalled”polyglot”vulnerabilities• Consequences?
– Websitedefacement– …– Completecontroloverthemachinethathoststhevulnerable
application
16
SQL/NoSQLinjection
• Description:– Duetoinsufficientinputfiltering(oroutputescaping)attacker-controlledinputmaybeinterpretedascodebyadatabaseinterpreterandexecuted[1].Eventualoutcomeiscodeexecution.
• RelatedThreats:InformationDisclosure,DataModification/Deletion,ElevationofPrivileges.
• TechnicalImpact:Severe.17
SQLinjection:exampleUserData data = getDataFromUser();String userId = data.getUserId();String passwd = data.getPasswd();SomeDB.executeQuery("SELECT * FROM users WHERE users.userId = ’
+ userId + ”’ AND users.passwd ='” + passwd + “'");
query <- "SELECT * FROM users WHERE users.userId = ’Batman’ OR ’1’ == ’1’; DROP TABLE users; --’ AND users.passwd= ’’"
userId <- “Batman’ OR ’1’ == ’1’; DROP TABLE users; --”passwd <- “”
userid <- ”John Doe”passwd <- ”qweJk@#4kw”query <- "SELECT * FROM users WHERE users.userId = ’John Doe’ AND user.passwd = ’qweJk@#4kw’”
18
NoSQLinjection:example
*Theimageistakenfromhttp://www.busanhlf4.org/19
NoSQLinjection:example
*Theimageistakenfromhttp://www.busanhlf4.org/20
SQL/NoSQLinjection:howtofindit?
• Youshouldbesuspiciousifanapplication– Getsuserinput– Doesnotcheck/sanitizetheinput– Usesthisinputtoconstructaquerytoadatabase– Usesstringoperations(e.g.,concatenation,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") 21
Cross-SiteScripting(XSS)
• Description:– "InsufficientinputvalidationoroutputescapingcanallowanattackertoplanthisownHTMLorscriptsonavulnerablesite.Theinjectedscriptswillhaveaccesstotheentiretyofthetargetedwebapplication…"[2].
– Thereflectedvarianttakestheadvantagewhentheinputisincorrectlyechoedbacktothebrowser;thepersistentvariantgoesabitfurther:italsotakestheadvantageonthelackofsanitizationofthedatathatgoestoaDB.
• RelatedThreats:– InformationDisclosure,ElevationofPrivileges.
• TechnicalImpact:– Moderate/Severe
22
Cross-SiteScripting(XSS):reflected
…<% String userId = request.GetParameter(”userId") %>…
<html>...<h1>
Hello, <%= userId %>!</h1>...
</html>
http://homepage.jsp?userId=John
23
Cross-SiteScripting(XSS):reflected
…<% String userId = request.GetParameter(”userId") %>…
<html>...<h1>
Hello, <%= userId %>!</h1>...
</html>
http://homepage.jsp?userId=<script>alert(’XSS');</script>
24
Cross-SiteScripting(XSS):stored
Database
*Thediagramisadaptedfrom[3].
Step0->developerwritesvulnerablepages:1st onestoresinvalidatedinput;2nd onereadsitfromadatabaseandwithnovalidation.
Step1->Attackersendsmalformedinput(code)toavulnerablewebpage.
Step2->Userbrowsesthesite.Step3->Websitereadsuncheckeddataandsendsitalongwithattacker’scodetotheuser’sbrowser.
Step4->User’sbrowserrendersthewebpageandrunstheattacker’scode(everytimethepageisrequested!)
25
Cross-SiteScripting(XSS):someexamples(reflected)
public class XSS extends HttpServlet {protected void doGet(HttpServletRequest request,
HttpServletResponse response) {
/* ... */response.sendError(HttpServletResponse.SC_NOT_FOUND,
"The page \"" + request.getParameter("page") +"\" was not found.");
}}
http://homepage.jsp?page=123
26
Cross-SiteScripting(XSS):someexamples(reflected)
public class XSS extends HttpServlet {protected void doGet(HttpServletRequest request,
HttpServletResponse response) {
/* ... */response.sendError(HttpServletResponse.SC_NOT_FOUND,
"The page \"" + request.getParameter("page") +"\" was not found.");
}}
http://homepage.jsp?page=<script>alert(’XSS')</script>
27
Cross-SiteScripting(XSS):someexamples(stored)
<%...String eid = request.GetParameter(”eid”);Statement stmt = conn.createStatement();ResultSet rs = stmt.executeQuery(”select *
from emp where id='” + eid + ”'”);if (rs != null) {
rs.next();}String bio = rs.getString(”bio”);
Employee biography: <%= bio %>…%>
http://show-employee.jsp?eid=123
28
Cross-SiteScripting(XSS):someexamples(stored)
<%...String eid = request.GetParameter(”eid”);Statement stmt = conn.createStatement();ResultSet rs = stmt.executeQuery(”select *
from emp where id='” + eid + ”'”);if (rs != null) {
rs.next();}String bio = rs.getString(”bio”);
Employee biography: <%= bio %>…%>
http://show-employee.jsp?eid=qwe‘or’1’==’1’;insertintoemp (bio)values('<script>alert(\"XSS\")</script>’)select*fromemp;--
29
Cross-SiteScripting(XSS):howtofindit?
• Youshouldbesuspiciousifanapplication– GetsaninputfromanHTTPentitysuchasquerystring,headerorform,orrequestobject
– Doesnotchecktheinputforvalidity– Echoesitbacktothebrowser(eitherHTMLorHTTPheaders),savingittoorretrievingfromadatabaseunchecked
30
Cross-SiteScripting(XSS):howtofindit?
Language Keywords
Java (JSP) addCookie,getRequest,request.getParameterfollowedby<jsp:setProperty or<%= orresponse.sendRedirect
Python form.getvalue, SimpleCookie whenthedataisnotvalidatedcorrectly.
C# Request.*, Response.*,and<%=whenthedataisnotvalidatedcorrectly.
PHP Accessing$_REQUEST,$_GET,$_POST,or$_SERVER followedbyecho,print,header,orprintf.
Node.js request,response, …
31
Outline
• Vulnerabilitiesinwebapplications• Injectionvulnerabilities• InformationDisclosurevulnerabilities• SessionFixationvulnerabilities• DenialofServicevulnerabilities
32
InformationDisclosurevulnerabilities
• Description:– Attackerisabletogetdatathatleadstoabreachinsecurityor
privacypolicy.Thedataitselfcouldbethegoal,orthedatacanprovideinformationthatleadstheattackertothegoal.
– Intentional:thedesignteamhasamismatchwiththeenduserastowhetherdatashouldbeprotected(privacyissues).
– Accidental:thedatacouldleakduetoanerrorinthecode,oranonobviouschannel.
– Mistake:verbose[error]messagesthatdevelopersthinkaresafe,butattackersfindthemhelpful,e.g.,thenameortheipaddressofaserver
– Threemaincategories:hardcodedcredentials,commentsinthesourcecode, andverboseerrormessages.
• Technicalimpact:couldbeanything
33
InformationDisclosure:example0
try {/* ... */
}catch (Exception e) {
System.out.println(e);e.printStackTrace();
}
34
InformationDisclosure:example1
35
InformationDisclosure:example2
public boolean authenticate(Request req, Response res) {/* ... */if (config.getRealmName() == null) {
authenticateCC.append(request.getServerName()); authenticateCC.append(':'); authenticateCC.append(Integer.toString(
request.getServerPort())); } else {
authenticateCC.append(config.getRealmName()); } return (false);
}
36
InformationDisclosure:example2
public boolean authenticate(Request req, Response res) {/* ... */if (config.getRealmName() == null) {
authenticateCC.append(request.getServerName()); authenticateCC.append(':'); authenticateCC.append(Integer.toString(
request.getServerPort())); } else {
authenticateCC.append(config.getRealmName()); } return (false);
}
37
InformationDisclosure:example2
public boolean authenticate(Request req, Response res) {/* ... */if (config.getRealmName() == null) {
authenticateCC.append(request.getServerName()); authenticateCC.append(':'); authenticateCC.append(Integer.toString(
request.getServerPort())); } else {
authenticateCC.append(config.getRealmName()); } return (false);
}
38
InformationDisclosure:example3
Loginsuccessful:"authenticate"methodreturns”true”
39
InformationDisclosure:example3(continued)
password=null;
Maythrownullreferenceexception
40
InformationDisclosure:howtofindit?
• Applicationreturns”default ” informationsuchasservertype/configuration/ipaddress/hostname.
• Toomanydetailsinerrormessages,unhandledexceptions,stacktraces;differenterrormessageswhenhandlinguserlogin.
• Lookfor”password”,”credentials”,“login”andsimilarkeywords,youmightfindsomethingquiteinteresting.
41
PathTraversal
• Description:– Anapplicationcanbetrickedintoreadingorwritingfilesatarbitrarylocations(oftenbypassingapplication-levelrestrictions).Thisoftenhappensduetoimproperrecognitionof”../”segmentsinunuser-suppliedparameters.Unconstrainedfilewritingbugsareoftenexploitedfordeployingattacker-controlledcode[2].
• Relatedthreats:Informationdisclosure,codeinjection,denialofservice
• Technicalimpact:Moderate/Severe
42
PathTraversal:someexamples
String path = getInputPath();if (path.startsWith("/safe_dir/")) {
File f = new File(path);f.delete();
} Thecodeattemptstovalidatetheinput
bywhitelisting.
Ifthefileiswithinthe”/safe_dir/”
folder,thefilegetsdeleted.
Anattackercouldprovideaninputsuch
as:/safe_dir/../data.db
Database
43
PathTraversal:someexamples(continued)
public void sendUserFile(Socket sock, String user) {BufferedReader filenameReader = new BufferedReader(
new InputStreamReader(sock.getInputStream(), "UTF-8"));
String filename = filenameReader.readLine();BufferedReader fileReader =
new BufferedReader(new FileReader("/home/" + user + "/" + filename));
String fileLine = fileReader.readLine();while(fileLine != null) {sock.getOutputStream().write(fileLine.getBytes());fileLine = fileReader.readLine();
}}
44
PathTraversal:someexamples(continued)
public void sendUserFile(Socket sock, String user) {BufferedReader filenameReader = new BufferedReader(
new InputStreamReader(sock.getInputStream(), "UTF-8"));
String filename = filenameReader.readLine();BufferedReader fileReader =
new BufferedReader(new FileReader("/home/" + user + "/" + filename));
String fileLine = fileReader.readLine();while(fileLine != null) {sock.getOutputStream().write(fileLine.getBytes());fileLine = fileReader.readLine();
}}
45
PathTraversal:howtofindit?
• Youshouldbesuspiciousifanapplication– Getsaninputfromuser– Theinputisusedtoconstructapathforanypurpose(downloading/uploadingfiles,redirects,etc.)
– Eveniftheinputlookslikeitissanitized,sanitizationfunctionsoftencontainerrors,soyoupaycloseattentiontosanitizers
– Sometimestherearenopathconstraintsatall
46
Outline
• Vulnerabilitiesinwebapplications• Injectionvulnerabilities• InformationDisclosurevulnerabilities• SessionFixationvulnerabilities• DenialofServicevulnerabilities
47
SessionFixationvulnerabilities
• Description:– Anattackthatallowstohijackavalidusersession.Whenauthenticatingauser,anappdoesn’tassignanewsessionID,makingitpossibletouseanexistentsessionID.TheattackerhastoprovidealegitimateWebapplicationsessionIDandtrytomakethevictim'sbrowseruseit. [5]
• Technicalimpact:Severe
48
SessionFixation:example*
*Thisexampleistakenfrom[4]. 49
SessionFixation:example
1. Theattackerestablishesalegitimateconnectionwithawebserver;
2. ThewebserverissuesasessionID;3. TheattackerhastosendalinkwiththeestablishedsessionIDto
thevictim;shehastoclickonthelink,accessingthesite;4. Thewebserver”sees”thatthesessionhasbeenalready
established(bytheattacker),soitdoesn’tcreateanewone;5. Thevictimprovideshercredentialstothewebserver;theattacker
canaccessheraccountknowingthesessionID.
(sessionIDcanbealsosentviaacookieorahiddenfieldintheDOMcontainer)
50
SessionFixation:example(continued)
protected boolean parseRequest(Request req, Response res) {if (isURLRewritingDisabled(req)) {
clearRequestedSessionURL(req);}
/* ... */
String sessionID = req.getPathParameter(Globals.SESSION_PARAMETER_NAME);
if (sessionID != null) {req.setRequestedSessionId(sessionID);req.setRequestedSessionURL(true);
}
/* ... */} 51
SessionFixation:example(continued)
protected boolean parseRequest(Request req, Response res) {if (isURLRewritingDisabled(req)) {
clearRequestedSessionURL(req);}
/* ... */
String sessionID = req.getPathParameter(Globals.SESSION_PARAMETER_NAME);
if (sessionID != null) {req.setRequestedSessionId(sessionID);req.setRequestedSessionURL(true);
}
/* ... */} 52
SessionFixation:example(continued)
protected boolean parseRequest(Request req, Response res) {if (isURLRewritingDisabled(req)) {
clearRequestedSessionURL(req);}
/* ... */
String sessionID = req.getPathParameter(Globals.SESSION_PARAMETER_NAME);
if (sessionID != null) {req.setRequestedSessionId(sessionID);req.setRequestedSessionURL(true);
}
/* ... */} 53
SessionFixation:example(continued)
protected boolean parseRequest(Request req, Response res) {if (isURLRewritingDisabled(req)) {
clearRequestedSessionURL(req);}
/* ... */
String sessionID = req.getPathParameter(Globals.SESSION_PARAMETER_NAME);
if (sessionID != null && !isURLRewritingDisabled(req)) {req.setRequestedSessionId(sessionID);req.setRequestedSessionURL(true);
}
/* ... */} 54
SessionFixation:howtofindit?[5]
• Youshouldbesuspiciousiftheusualflowisbroken[6]– Userenterscorrectcredentials– Theapplicationauthenticatestheusersuccessfully– Sessioninformation(temporarydata)isstoredinatemporarylocation
– Sessionisinvalidated(session.invalidate())– Anytemporarydataisrestoredtonewsession(newsessionID)
– UsergoestosuccessfulloginlandingpageusingnewsessionID
55
SessionFixation:howtofindit?(continued)[5]
• CheckforsessionfixationifausertriestologinusingasessionIDthathasbeenspecificallyinvalidated(requiresmaintainingthislistinsometypeofURLcache)
• CheckforsessionfixationifausertriestouseanexistingsessionIDalreadyinusefromanotherIPaddress(requiresmaintainingthisdatainsometypeofmap)
• Someserverapplications(e.g.,JBOSS,Tomcat)haveasettingfordisablingURLrewriting->thismitigatestheattackwhensessionIDisexposedviaGETparameterofaURL(aswellasbeingstoredinbrowserhistory,proxyservers,etc)
56
Outline
• Vulnerabilitiesinwebapplications• Injectionvulnerabilities• InformationDisclosurevulnerabilities• SessionFixationvulnerabilities• DenialofServicevulnerabilities
57
DenialofServicevulnerabilities
• Description:– TheDenialofService(DoS)attackisfocusedonmakingaresource(site,application,server)unavailableforthepurposeitwasdesigned.Ifaservicereceivesaverylargenumberofrequests,itmayceasetobeavailabletolegitimateusers.Inthesameway,aservicemaystopifaprogrammingvulnerabilityisexploited,orthewaytheservicehandlesresourcesituses.
• Technicalimpact:Severe
58
DenialofService:example1
Wemay"kill”theserverbyfillingallof
itsmemory
59
DenialofService:example2
Theuserhascontrolovertheloopcounter:wemaydecreaseserver’s
performanceorevenkillit.60
DenialofService:example3
BothConnectionandCallableStatement objectsshouldbeclosedinthe
“finally”block61
DenialofService:howtofindit?
• Youshouldbesuspiciousif– User-controlledvaluesdefinethesizeofallocatedmemory,arraysorbuffers;
– User-controlledvaluesinfluenceloopconditions;– ”Heavy”resourcesareneverreleased(filelocks/descriptors,databaseconnections,datastreams,etc.)
– Thereisan"infinite"amountofresourcesthatasingleusercanallocate(e.g.,thenumberofworkingprocessesorserversockets);
62
References• [1]WebApplicationVulnerabilitiesandAvoidingApplicationExposure
https://f5.com/resources/white-papers/web-application-vulnerabilities-and-avoiding-application-exposure
• [2]Zalewski,Michal. ThetangledWeb:Aguidetosecuringmodernwebapplications.NoStarchPress,2012.
• [3]MichaelHoward,DavidLeBlanc,andJohnViega. 24deadlysinsofsoftwaresecurity: programmingflawsandhowtofixthem.McGraw-Hill, Inc.,2009.
• [4]OWASP:thefreeandopensoftwaresecurity communityhttps://www.owasp.org/index.php/Main_Page
• [5]TheWhiteHatSecurity blogonSessionFixationprevention:https://www.whitehatsec.com/blog/session-fixation-prevention-in-java/
• [6]TheOWASPEnterpriseSecurity APIsessionhandlingexample:https://code.google.com/p/owasp-esapi-java/source/browse/trunk/src/main/java/org/owasp/esapi/reference/DefaultHTTPUtilities.java
• [7]SecureCodingGuidelines forJavaSEhttp://www.oracle.com/technetwork/java/seccodeguide-139067.html
63