35
OWASP TOP 10 2007 RELEASE CANDIDATE 1 THE TEN MOST CRITICAL WEB APPLICATION SECURITY VULNERABILITIES 2007 UPDATE © 2002‐2007 OWASP Foundation This document is licensed under the Creative Commons Attribution‐ShareAlike 2.5 license

OWASP Web Security Guide

Embed Size (px)

DESCRIPTION

The10 Most Critical Web Application Security Vulnerabilities

Citation preview

OWASPTOP102007RELEASECANDIDATE1

THETENMOSTCRITICALWEBAPPLICATIONSECURITYVULNERABILITIES

2007UPDATE

©2002‐2007OWASPFoundation

ThisdocumentislicensedundertheCreativeCommonsAttribution‐ShareAlike2.5license

2

T A B L E O F C ON T EN T S

TableofContents ..................................................................................................................................................................2

Introduction ...........................................................................................................................................................................3

Summary ................................................................................................................................................................................4

Methodology .........................................................................................................................................................................5

A1–CrossSiteScripting(XSS) ..............................................................................................................................................8

A2–InjectionFlaws............................................................................................................................................................ 11

A3–MaliciousFileExecution ............................................................................................................................................ 13

A4–InsecureDirectObjectReference ............................................................................................................................. 17

A5–CrossSiteRequestForgery(CSRF) ............................................................................................................................ 19

A6–InformationLeakageandImproperErrorHandling ................................................................................................ 22

A7–BrokenAuthenticationandSessionManagement .................................................................................................. 24

A8–InsecureCryptographicStorage................................................................................................................................ 26

A9–InsecureCommunications......................................................................................................................................... 28

A10–FailuretoRestrictURLAccess................................................................................................................................. 30

WhereToGoFromHere.................................................................................................................................................... 32

References .......................................................................................................................................................................... 35

OWASPTop102007

3

I N T RO DUC T IO N

WelcometotheOWASPTop102007!Thistotallyre‐writteneditionliststhemostseriouswebapplicationvulnerabilities,discusseshowtoprotectagainstthem,andprovideslinkstomoreinformation.

AIM

TheprimaryaimoftheOWASPTop10 i stoeducatedevelopers, designers, architec tsandorganizationsabouttheconsequencesofthemostcommonwebapplicationsecurityvulnerabilities.TheTop10providesbasicmethodstoprotectagainstthesevulnerabilities–agreatstarttoyoursecurecodingsecurity

program.

Securi ty i snotaone‐timeevent .Itisinsufficienttosecureyourcodejustonce.By2008,thisTop10willhavechanged,andwithoutchangingalineofyourapplication’scode,youmaybevulnerable.Pleasereviewthe

adviceinWheretogofromhereformoreinformation.

Asecurecoding initiativemustdeal withal l stagesofaprogram’s l i fecycle .Securewebapplications

areonly possiblewhenasecureSDLCisused.Secureprogramsaresecurebydesign,duringdevelopment,andbydefault.Thereareatleast300issuesthataffecttheoverallsecurityofawebapplication.These300+issuesare

detailedintheOWASPGuide,whichisessentialreadingforanyonedevelopingwebapplicationstoday.

Thi sdocument i s f ir standforemostaneducationpiece, nota standard .Pleasedonotadoptthisdocumentasapolicyorstandardwithouttalkingtousfirst!Ifyouneedasecurecodingpolicyorstandard,OWASP

hassecurecodingpoliciesandstandardsprojectsinprogress.Pleaseconsiderjoiningorfinanciallyassistingwiththeseefforts.

4

SUMMARY

A1– CrossS iteSc ript ing (XSS) XSSflawsoccurwheneveranapplicationtakesusersupplieddataandsendsit

toawebbrowserwithoutfirstvalidatingorencodingthatcontent.XSSallowsattackerstoexecutescriptinthevictim’sbrowserwhichcanhijackuser

sessions,defacewebsites,etc.

A2– Inject ion Flaws Injectionflaws,particularlySQLinjection,arecommoninwebapplications.

Injectionoccurswhenuser‐supplieddataissenttoaninterpreteraspartofacommandorquery.Theattacker’shostiledatatrickstheinterpreterinto

executingunintendedcommandsorchangingdata.

A3– Insecure RemoteF ile

IncludeCodevulnerabletoremotefileinclusionallowsattackerstoincludehostile

codeanddata,resultingindevastatingattacks,suchastotalserver

compromise.

A4– Insecure DirectObjectReference

Adirectobjectreferenceoccurswhenadeveloperexposesareferencetoan

internalimplementationobject,suchasafile,directory,databaserecord,orkey,asaURLorformparameter.Attackerscanmanipulatethosereferencestoaccessotherobjectswithoutauthorization.

A5– CrossS iteRequest

Forgery(CSRF)ACSRFattackforcesalogged‐onvictim’sbrowsertosendapre‐authenticated

requesttoavulnerablewebapplication,whichthenforcesthevictim’sbrowser

toperformahostileactiontothebenefitoftheattacker.

A6– InformationLeakageandImproperErrorHandl ing

Applicationscanunintentionallyleakinformationabouttheirconfiguration,internalworkings,orviolateprivacythroughavarietyofapplicationproblems.

Attackersusethisweaknesstoviolateprivacy,orconductfurtherattacks.

A7– BrokenAuthenticationandSessionManagement

Accountcredentialsandsessiontokensareoftennotproperlyprotected.

Attackerscompromisepasswords,keys,orauthenticationtokenstoassumeotherusers’identities.

A8– Insecure Cryptograph icStorage

Webapplicationsrarelyusecryptographicfunctionsproperlytoprotectdata

andcredentials.Attackersuseweaklyprotecteddatatoconductidentitytheftandothercrimes,suchascreditcardfraud.

A9– Insecure Communications

Applicationsfrequentlyfailtoencryptnetworktrafficwhenitisnecessaryto

protectsensitivecommunications.

A10–Failure toRest rict URLAccess

Frequently,theonlyprotectionforsensitiveareasofanapplicationislinksor

URLsarenotpresentedtounauthorizedusers.Attackerscanusethisweaknesstoaccessandperformunauthorizedoperations.

Table1: Top10Webapp licationvu lnerabi lit ies for2006

OWASPTop102007

5

ME THODO LOG Y

OurmethodologyfortheTop102007wassimple:taketheMITREVulnerabilityTrendsfor2006,anddistilltheTop10webapplicationsecurityissues.Therankedresultsareasfollows:

Figure2: MITREdataonTop 10webapp licationvu lnerabi lit ies for2006

Althoughwehavetriedtopreservetheorder,wehavedeliberatelynotchosensomeweaknesses,suchasbufferoverflowsastheyarenotwidelyapplicabletowebapplicationsecurity.Inaddition,wehavetransformedsome

rawfindingsinto“meta”issuestofullycapturetherootcauseofanissuerepresentedbythatdata.

CrossSiteRequestForgery(CSRF)isthemajornewadditiontothiseditionoftheOWASPTop10.Althoughrawdataranksitat#36,wefeelthatitisimportantenoughthatapplicationsshouldstartprotectioneffortstoday,

particularlyforhighvalueapplicationsandapplicationswhichdealwithsensitivedata.

Wehavenotincludedlanguagespecific(C,C++,etc)issues,suchasbufferoverflows,formatstringattacks,oranyoftheothercommonweaknesseswhichplaguedesktopandserversoftware.Ifyouaredeliveringprogramsfor

desktoporserverplatforms,orareincludingtools,plug‐ins,orexternalprogramstobecalledbyyourwebapplication,westronglyrecommendyoureferencetheOWASPGuideandthebooksinthereferencessectionfor

moreinformationonhowtobuildorusethesesafely.

Alloftheprotectionrecommendationsprovidesolutionsforthethreemostprevalentwebapplication

frameworks:JavaEE,ASP.NET,andPHP.Othercommonwebapplicationframeworks,suchasRubyonRailsorPerlcaneasilyadapttherecommendationstosuittheirspecificneeds.

BIASES

ThemethodologydescribedabovenecessarilybiasestheTop10towardsdiscoveriesbythesecurityresearchercommunity.Thispatternofdiscoveryissimilartothemethodsofactualattack,particularlyasitrelatestoentry‐

level("scriptkiddy")attackers.ProtectingyoursoftwareagainsttheTop10willprovideamodicumofprotectionagainstthemostcommonformsofattack,butfarmoreimportantly,helpsetacourseforimprovingthesecurityof

yoursoftware.

6

MAPPING

Therehavebeenchangestotheheadings,evenwherecontentmapscloselytopreviouscontent.WenolongerusetheWASXMLnamingschemeasithasnotkeptuptodatewithmodernvulnerabilities,attacks,andcountermeasures.ThetablebelowdepictshowthiseditionmapstotheTop102004,andtherawMITREranking:

OWASPTop 102007 OWASPTop 102004 MITRE2006RawRanking

A1.CrossSite Scripting(XSS) A4.CrossSite Scripting(XSS) 1

A2.InjectionF laws A6.InjectionF laws 2

A3.InsecureRemote Fi le Include(NEW) 3

A4.InsecureD irectObjectReference A2.B rokenAccessCont rol (split in 2007T10) 5

A5.CrossSite RequestForgery(CSRF)(NEW) 36

A6.InformationLeakage and ImproperE rrorHandl ing

A7.ImproperE rrorHand ling 6

A7.B rokenAuthenticationandSession Management

A3.B rokenAuthenticationandSession Management

14

A8.InsecureCryptographicStorage A8.InsecureStorage 8

A9.InsecureCommunications(NEW) DiscussedunderA10.InsecureConf igurationManagement

8

A10.Fa iluretoRestr ict URLAccess A2.B rokenAccessCont rol (split in 2007T10) 14

A1.UnvalidatedInput 7

A5.BufferOverf lows 4,8, and10

A9.Den ialof Service 17

A10.InsecureConfiguration Management 29

WHYWEHAVEDROPPEDSOMEIMPORTANTISSUES

Unval idated inputisamajorchallengeforanydevelopmentteam,andisattherootofmanyapplicationsecurityproblems.Infact,manyoftheotheritemsinthelistrecommendvalidatinginputasapartofthesolution.

Westillstronglyrecommendcreatingacentralizedinputvalidationmechanismasapartofyourwebapplications.Formoreinformation,readthefollowingdatavalidationarticlesatOWASP:

http://www.owasp.org/index.php/Data_Validation http://www.owasp.org/index.php/Testing_for_Data_Validation

Bufferoverflows, integeroverflowsandformatstr ing issuesareextremelyseriousvulnerabilitiesforprogramswritteninlanguagessuchasCorC++.Remediationfortheseissuesiscoveredbythetraditionalnon‐webapplicationsecuritycommunity,suchasSANS,CERT,andprogramminglanguagetoolvendors.Ifyourcodeis

OWASPTop102007

7

writteninalanguagethatislikelytosufferbufferoverflows,weencourageyoutoreadthebufferoverflowcontentonOWASP:

http://www.owasp.org/index.php/Buffer_overflow http://www.owasp.org/index.php/Testing_for_Buffer_Overflow

Denial ofservice isaseriousattackthatcanaffectanysitewritteninanylanguage.TherankingofDoSbyMITREisinsufficienttomaketheTop10thisyear.Ifyouhaveconcernsaboutdenialofservice,youshouldconsult

theOWASPsiteandTestingGuide: http://www.owasp.org/index.php/Category:Denial_of_Service_Attack

http://www.owasp.org/index.php/Testing_for_Denial_of_Service

Insecureconfigurationmanagement affectsallsystemstosomeextent,particularlyPHP.However,therankingbyMITREdoesnotallowustoincludethisissuethisyear.Whendeployingyourapplication,youshould

consultthelatestOWASPGuideandtheOWASPTestingGuidefordetailedinformationregardingsecureconfigurationmanagementandtesting:

http://www.owasp.org/index.php/Configuration http://www.owasp.org/index.php/Testing_for_infrastructure_configuration_management

VULNERABILITIES,NOTATTACKS

ThepreviouseditionoftheTop10containedamixtureofattacks,vulnerabilitiesandcountermeasures.Thistimearound,wehavefocusedsolelyonvulnerabilities.Iforganizationsusethisdocumenttosecuretheirapplications,

andreducetheriskstotheirbusiness,itwillleadtoadirectreductioninthelikelihoodof:

Phishingattacksthatcanexploitanyofthesevulnerabilities,particularlyXSS,andweakornon‐existentauthenticationorauthorizationchecks(A1,A4,A7,A10)

Privacyviolationsfrompoorvalidation,businessruleandweakauthorizationchecks(A2,A4,A6,A7,A10)

Identitytheftthroughpoorornon‐existentcryptographiccontrols(A8andA9),remotefileinclude(A3)andauthentication,businessrule,andauthorizationchecks(A4,A7,A10)

Systemscompromisethroughremotefileinclude(A3)andendofbusinessclassofdataalterationordestructionattacksviaInjections(A2)

FinanciallossthroughunauthorizedtransactionsandCSRFattacks(A4,A5,A7,A10)

Reputationlossthroughexploitationofanyoftheabovevulnerabilities(A1…A10)

Onceanorganizationmovesawayfromworryingaboutreactivecontrols,andmovesforwardtoproactivelyreducingrisksapplicabletotheirbusiness,theywillimprovecompliancewithregulatoryregimes,reduceoperationalcosts,andhopefullywillhavefarmorerobustandsecuresystemsasaresult.

ACKNOWLEDGEMENTS

WethanktheMITREProjectformakingVulnerabilityTypeDistributioninCVEdatafreelyavailableforuse.TheOWASPTopTenprojectisledandsponsoredbyAspect

Security.

8

A 1 – C RO S S S I T E S C R I P T I N G ( X S S )

Crosssitescripting,betterknownasXSS,isthemostprevalentandperniciouswebapplicationsecurityissue.XSSflawsoccurwheneveranapplicationtakesdatathatoriginatedfromauserandsendsittoawebbrowserwithoutfirstvalidatingorencodingthatcontent.

XSSallowsattackerstoexecutescriptinthevictim’sbrowser,whichcanhijackusersessions,defacewebsites,inserthostilecontent,conductphishingattacks,andtakeovertheuser’sbrowserusingscriptingmalware.ThemaliciousscriptisusuallyJavaScriptbutanyscriptinglanguagesupportedbythevictim’sbrowserisapotential

targetforthisattack.

ENVIRONMENTSAFFECTED

Allwebapplicationframeworksarevulnerabletocrosssitescripting.

VULNERABILITY

Therearethreeknowntypesofcrosssitescripting:reflected,stored,andDOMinjection.ReflectedXSSistheeasiesttoexploit–apagewillreflectusersupplieddatadirectlybacktotheuser:

echo $_REQUEST['userinput'];

StoredXSStakeshostiledata,storesitinafile,adatabase,orotherbackendsystem,andthenatalaterstage,displaysthedatatotheuser,unfiltered.ThisisextremelydangerousinsystemssuchasCMS,blogs,orforums,

wherealargenumberofuserswillseeinputfromotherindividuals.

WithDOMbasedXSSattacks,thesite’sJavaScriptcodeandvariablesaremanipulatedratherthanHTMLelements.Alternatively,attackscanbeablendorhybridofallthreetypes.Thedangerwithcrosssitescriptingisnotthetype

ofattack,butthatitispossible.

AttacksareusuallyimplementedinJavaScript,whichisapowerfulscriptinglanguage.UsingJavaScriptallowsattackerstomanipulateanyaspectoftherenderedpage,includingaddingnewelements(suchasaddingalogin

tilewhichforwardscredentialstoahostilesite),manipulatinganyaspectoftheinternalDOMtree,anddeletingorchangingthewaythepagelooksandfeels.JavaScriptallowstheuseofXmlHttpRequest,whichistypicallyusedby

sitesusingAJAXtechnologies,evenifvictimsitedoesnotuseAJAXtoday.

UsingXmlHttpRequest,itissometimespossibletogetaroundabrowser’ssamesourceoriginationpolicy‐thus

forwardingvictimdatatohostilesites,andtocreatecomplexwormsandmaliciouszombiesthatlastaslongasthebrowserstaysopen.AJAXattacksdonothavetobevisibleorrequireuserinteractiontoperformdangerouscross

siterequestforgery(CSRF)attacks(seeA‐5).

VERIFYINGSECURITY

Thegoalistoverifythatalltheparametersintheapplicationarevalidatedand/orencodedbeforebeingincludedinHTMLpages.

OWASPTop102007

9

Automatedapproaches:BothvulnerabilityscanningtoolsandstaticcodeanalysistoolscanfindsimpleXSSproblems,particularlyreflectedones.Theyfrequentlycan'tfindcomplexXSSflaws,suchaswhentheinjection

occursinapeculiarHTMLstructureorscript.TheyarealsonotlikelytofindinstancesofDOMbasedXSS.

Manualapproaches:Ifacentralizedvalidationandencodingmechanismisused,themostefficientwaytoverify

securityistocheckthecode.Ifadistributedimplementationisused,thentheverificationwillbeconsiderablymoretime‐consuming.Testingistime‐consumingbecausetheattacksurfaceofmostapplicationsissolarge.

PROTECTION

ThebestprotectionforXSSisacombinationof"whitelist"validationofallincomingdataandappropriateencodingofalloutputdata.Validationallowsthedetectionofattacks,andencodingpreventsanysuccessfulscriptinjection

fromrunninginthebrowser.

PreventingXSSacrossanentireapplicationrequiresaconsistentarchitecturalapproach:

Inputval idation. Useastandardinputvalidationmechanismtovalidateallinputdataforlength,type,

syntax,andbusinessrulesbeforeacceptingthedatatobedisplayedorstored.Usean"acceptknowngood"validationstrategy.Rejectinvalidinputratherthanattemptingtosanitizepotentiallyhostiledata.

Strongoutputencoding. Ensurethatalluser‐supplieddataisHTMLentityencodedbeforerendering

inHTML,takingtheapproachtoencodeallcharactersotherthanaverylimitedsubset.ThisistheapproachoftheMicrosoftAnti‐XSSlibrary,andtheforthcomingOWASPPHPAnti‐XSSlibrary.

Donotuse "blackl i st" val idationtodetectXSSininputortoencodeoutput.Searchingforandreplacingjustafewcharacters("<"">"andothersimilarcharacters)isweakandhasbeenattackedsuccessfully.

Languagespecificrecommendations:

Java:UseStrutsoutputmechanismssuchas<bean:write…>,orusethedefaultJSTLescapeXML="true"attributein<c:out…>.DoNOTuse<%=…%>unnested(thatis,outsideofaproperlyencodedoutput

mechanism).

.NET:UsetheMicrosoftAnti‐XSSLibrary1.5freelyavailablefromMSDN.DonotassignformfieldsdatadirectlyfromtheRequestobject:username.Text = Request.QueryString("username");withoutusing

thislibrary.Understandwhich.NETcontrolsautomaticallyencodeoutputdata.

PHP:Ensureoutputispassedthroughhtmlentities()orhtmlspecialchars()orusethesoontobereleasedOWASPPHPAnti‐XSSlibrary.

SAMPLES http://cve.mitre.org/cgi‐bin/cvename.cgi?name=CVE‐2006‐4206

http://cve.mitre.org/cgi‐bin/cvename.cgi?name=CVE‐2005‐3966 http://cve.mitre.org/cgi‐bin/cvename.cgi?name=CVE‐2006‐5204

REFERENCES OWASP–Crosssitescripting,http://www.owasp.org/index.php/Cross_Site_Scripting

OWASP–TestingforXSS,http://www.owasp.org/index.php/Testing_for_Cross_site_scripting

10

OWASPStingerProject(AJavaEEvalidationfilter)–http://www.owasp.org/index.php/Category:OWASP_Stinger_Project

OWASPPHPFilterProject‐http://www.owasp.org/index.php/OWASP_PHP_Filters OWASPEncodingProject‐http://www.owasp.org/index.php/Category:OWASP_Encoding_Project

RSnake,XSSCheatSheet,http://ha.ckers.org/xss.html Klein,A.,DOMBasedCrossSiteScripting,http://www.webappsec.org/projects/articles/071105.shtml

.NETAnti‐XSSLibrary‐http://www.microsoft.com/downloads/details.aspx?FamilyID=efb9c819‐53ff‐4f82‐bfaf‐e11625130c25&DisplayLang=en

OWASPTop102007

11

A 2 – I N J E C T IO N F L AW S

Injectionflaws,particularlySQLinjection,arecommoninwebapplications.Injectionoccurswhenuser‐supplieddataissenttoaninterpreteraspartofacommandorquery.Theattacker’sdatatrickstheinterpreterintoexecutingunintendedcommands.Injectionflawsallowattackerstocreate,read,update,ordeleteanyarbitrary

dataavailabletotheapplication.Intheworstcasescenario,theseflawsallowanattackertocompletelycompromisetheapplication.

ENVIRONMENTSAFFECTED

Allwebapplicationframeworksthatuseinterpretersarevulnerabletoinjectionattacks.

VULNERABILITY

Ifuserinputispassedintoaninterpreterwithoutvalidationorencoding,theapplicationisvulnerable.Checkifuserinputissuppliedtodynamicqueries,suchas:

$sql = "SELECT * FROM table WHERE id = '" . $_REQUEST['id’] . "’";

VERIFYINGSECURITY

Thegoalistoverifythatuserdatacannotmodifythemeaningofcommandsandqueriessenttoanyoftheinterpretersinvokedbytheapplication.

Automatedapproaches:Manyvulnerabilityscanningtoolssearchforinjectionproblems,particularlySQLinjection.

Detectingwhethertheinjectionworkedornotisdifficultandpronetoerror.StaticanalysistoolsthatsearchforusesofunsafeinterpreterAPIsareuseful,butfrequentlycannotverifythatappropriatevalidationorencoding

mightbeinplacetoprotectagainstthevulnerability.

Manualapproaches:Themostefficientandaccurateapproachistocheckthecodethatinvokesinterpreters.ThereviewershouldverifytheuseofasafeAPIorthatappropriatevalidationand/orencodinghasoccurred.Testing

canbeextremelytime‐consumingandspottybecausetheattacksurfaceofmostapplicationsissolarge.

PROTECTION

Avoidtheuseofinterpreterswhenpossible.Ifyoumustinvokeaninterpreter,thekeymethodtoavoidinjectionsistheuseofsafeAPIs,suchasstronglytypedparameterizedqueriesandobjectrelationalmapping(ORM)libraries.Theseinterfaceshandlealldataescaping,ordonotrequireescaping.Notethatwhilesafeinterfacessolvethe

problem,validationisstillrecommendedinordertodetectattacks.

Usinginterpretersisdangerous,soit'sworthittotakeextracare,suchasthefollowing:

Enforce leastprivi lege whenconnectingtodatabasesandotherbackendsystems

Avoiddetai lederrormessagesthatareusefultoanattacker

Donotsenddynamicqueries intoaparameterizedinterface

Becareful whenusing storedproceduresastheycanbeinjectable

12

Donotusedynamicquery inter faces(suchasmysql_query()orsimilar)

Donotuse simpleescapingfunctions,suchasPHP’saddslashes()orcharacterreplacement

functionslikestr_replace("’","’’").Theseareweakandhavebeensuccessfullyexploitedbyattackers.

Languagespecificrecommendations: JavaEE–usestronglytypedPreparedStatement,orORMssuchasHibernateorSpring

.NET–usestronglytypedparameterizedqueries,suchasSqlCommandwithSqlParameteroranORMlikeHibernate.

PHP–usePDOwithstronglytypedparameterizedqueries(usingbindParam())

SAMPLES

http://cve.mitre.org/cgi‐bin/cvename.cgi?name=CVE‐2006‐5121 http://cve.mitre.org/cgi‐bin/cvename.cgi?name=CVE‐2006‐4953

http://cve.mitre.org/cgi‐bin/cvename.cgi?name=CVE‐2006‐4592

REFERENCES

OWASP,http://www.owasp.org/index.php/SQL_Injection

OWASP,http://www.owasp.org/index.php/Guide_to_SQL_Injection

OWASP,http://www.owasp.org/index.php/Reviewing_Code_for_SQL_Injection

OWASP,http://www.owasp.org/index.php/Testing_for_SQL_Injection

SQLInjection,http://www.spidynamics.com/papers/SQLInjectionWhitePaper.pdf

AdvancedSQLInjection,http://www.ngssoftware.com/papers/advanced_sql_injection.pdf

MoreAdvancedSQLInjection,http://www.nextgenss.com/papers/more_advanced_sql_injection.pdf

Hibernate,anadvancedobjectrelationalmanager(ORM)forJ2EEand.NET,http://www.hibernate.org/

J2EEPreparedStatements,http://java.sun.com/docs/books/tutorial/jdbc/basics/prepared.html

Howto:ProtectfromSQLinjectioninASP.Net,http://msdn2.microsoft.com/en‐us/library/ms998271.aspx

PHPPDOfunctions,http://php.net/pdo

OWASPTop102007

13

A 3 – MA L I C I OU S F I L E E X E C UT I ON

Maliciousfileexecutionvulnerabilitiesarefoundinmanyapplications.Developerswilloftendirectlyuseorconcatenatepotentiallyhostileinputwithfileorstreamfunctions,orimproperlytrustinputfiles.Onmanyplatforms,frameworksallowtheuseofexternalobjectreferences,suchasURLsorfilesystemreferences.When

thedataisinsufficientlychecked,thiscanleadtoarbitraryremoteandhostilecontentbeingincluded,processedorinvokedbythewebserver.

Thisallowsattackerstoperform:

Remotecodeexecution

Remoterootkitinstallationandcompletesystemcompromise

OnWindows,internalsystemcompromisemaybepossiblethroughtheuseofPHP’sSMBfilewrappers

ThisattackisparticularlyprevalentonPHP,andextremecaremustbetakenwithanystreamorfilefunctiontoensurethatusersuppliedinputdoesnotinfluencefilenames.

ENVIRONMENTSAFFECTED

Allwebapplicationframeworksthatallowuploadedfilestobeexecutedarevulnerabletoremotefileinclude.By

default,PHP4.0.4andlaterand5.xarevulnerabletoremotefileinclusion.Otherenvironmentsaresusceptibleiftheyallowfileuploadintowebdirectories.

VULNERABILITY

Acommonvulnerableconstructis:

include $_REQUEST['filename’];

Notonlydoesthisallowevaluationofremotehostilescripts,itcanbeusedtoaccesslocalfileservers(ifPHPishosteduponWindows)duetoSMBsupportinPHP’sfilesystemwrappers.

Othermethodsofattackinclude:

Hostiledatabeinguploadedtosessionfiles,logdata,andviaimageuploads(typicalofforumsoftware)

Usingcompressionoraudiostreams,suchaszlib://orogg://whichdonotinspecttheinternalPHPURLflagandthusallowaccesstoremoteresourcesevenifallow_url_fopenorallow_url_includeisdisabled

UsingPHPwrappers,suchasphp://inputandotherstotakeinputfromtherequestPOSTdataratherthanafile

UsingPHP’sdata:wrapper,suchasdata:;base64,PD9waHAgcGhwaW5mbygpOz8+

Asthislistisextensive(andperiodicallychanges),itisvitaltouseaproperlydesignedsecurityarchitectureandrobustdesignwhendealingwithusersuppliedinputsinfluencingthechoiceofserversidefilenamesandaccess.

14

AlthoughPHPexampleshavebeengiven,thisattackisalsoapplicableindifferentwaysto.NETandJ2EE.Applicationswritteninthoseframeworksneedtopayparticularattentiontocodeaccesssecuritymechanismsto

ensurethatfilenamessuppliedbyorinfluencedbytheuserdonotallowsecuritycontrolstobeobviated.

Forexample,itispossiblethatXMLdocumentssubmittedbyanattackerwillhaveahostileDTDthatforcesthe

XMLparsertoloadaremoteDTD,andparseandprocesstheresults.AnAustraliansecurityfirmhasdemonstratedthisapproachtoportscanningbehindfirewalls.See[SIF01]inthischapter’sreferencesformoreinformation.

Thedamagethisparticularvulnerabilitycausesisdirectlyrelatedtothestrengthofthesandbox/platformisolationcontrolsintheframework.AsPHPisrarelyisolatedandhasnosandboxconceptorsecurityarchitecture,thedamageisfarworseforanattackthanotherplatformswithlimitedorpartialtrust,orarecontainedwithina

suitablesandbox,suchaswhenawebappisrunningunderaJVMwiththesecuritymanagerproperlyenabledandconfigured(whichisrarelythedefault).

VERIFYINGSECURITY

Automatedapproaches:Vulnerabilityscanningtoolswillhavedifficultyidentifyingtheparametersthatareusedinafileincludeorthesyntaxformakingthemwork.StaticanalysistoolscansearchfortheuseofdangerousAPIs,

butcannotverifythatappropriatevalidationorencodingmightbeinplacetoprotectagainstthevulnerability.

Manualapproaches:Acodereviewcansearchforcodethatmightallowafiletobeincludedintheapplication,buttherearemanypossiblemistakestorecognize.Testingcanalsodetectthesevulnerabilities,butidentifyingthe

particularparametersandtherightsyntaxcanbedifficult.

PROTECTION

Preventingremotefileincludeflawstakessomecarefulplanningatthearchitecturalanddesignphases,throughtothoroughtesting.Ingeneral,awell‐writtenapplicationwillnotuseuser‐suppliedinputinanyfilenameforany

server‐basedresource(suchasimages,XMLandXSLtransformdocuments,orscriptinclusions),andwillhavefirewallrulesinplacepreventingnewoutboundconnectionstotheInternetorinternallybacktoanyotherserver.

However,manylegacyapplicationswillcontinuetohaveaneedtoacceptusersuppliedinput.

Amongthemostimportantconsiderationsare:

Consideravariablenamingschemetoassistwithtaintchecking:

$hostile = &$_POST; // refer to POST variables, not $_REQUEST

$safe[‘filename’]= validate_file_name($hostile[‘unsafe_filename’]); // make it safe

Thereforeanyoperationbaseduponhostileinputisimmediatelyobvious:

require_once($_POST[‘unsafe_filename’] . ‘inc.php’);

require_once($safe[‘filename’] . ‘inc.php’);

Stronglyvalidateuserinputusing"acceptknowngood"asastrategy

Hideserver‐sidefilenamesfromtheuser.Forexample,insteadofincluding$language.".lang.php",use

anarrayindexlikethis:

OWASPTop102007

15

<select name="language"><option value="1">Français</option></select>

$language = intval($_POST['language’]);

if ($language > 0) {

require_once($lang[$language]); // lang is array of strings eg "fr.lang.php"

}

Disableallow_url_fopenandallow_url_includeinphp.iniandconsiderbuildingPHPlocallytonotincludethisfunctionality.

Addfirewallrulestopreventwebserversmakingnewconnectionstoexternalwebsitesandinternalsystems.Forhighvaluesystems,isolatethewebserverinitsownVLANorprivatesubnet.

Ensurethatfileandstreamsfunctions(stream_*)arecarefullyvetted.Ensurethattheuserinputisnotsuppliedanyfunctionwhichtakesafilenameargument,including:

include() include_once() require() require_once() fopen() imagecreatefromXXX() file() file_get_contents() copy() delete() unlink() upload_tmp_dir() $_FILES move_uploaded_file()

Beextremelycautiousifdataispassedtosystem()eval()passthru()or`(thebacktickoperator).

Checkthatanyfilestakenfromtheuserforlegitimatepurposescannotbeotherwiseobviated,suchasincludingusersupplieddatainthesessionobject,avatarsandimages,PDFreports,temporaryfiles,andsoon.

WithPHP,considerimplementingachrootjailorothersandboxmechanismssuchasvirtualizationtoisolateapplicationsfromeachother

WithJ2EE,ensurethatthesecuritymanagerisenabledandproperlyconfiguredandthattheapplicationisdemandingpermissionsappropriately

WithASP.NET,pleaserefertothedocumentationonpartialtrust,anddesignyourapplicationstobesegmentedintrust,sothatmostoftheapplicationexistsinthelowestpossibletruststatepossible

SAMPLES http://cve.mitre.org/cgi‐bin/cvename.cgi?name=CVE‐2007‐0360

http://cve.mitre.org/cgi‐bin/cvename.cgi?name=CVE‐2006‐5220 http://cve.mitre.org/cgi‐bin/cvename.cgi?name=CVE‐2006‐4722

REFERENCES

OWASPGuide,http://www.owasp.org/index.php/File_System#Includes_and_Remote_files

OWASPTestingGuide,http://www.owasp.org/index.php/Testing_for_Directory_Traversal

OWASPPHPTop5,http://www.owasp.org/index.php/PHP_Top_5#P1:_Remote_Code_Execution

16

StefanEsser,http://blog.php‐security.org/archives/45‐PHP‐5.2.0‐and‐allow_url_include.html

[SIF01]SiftNetworks,WebServices:Teachinganolddognewtricks,http://www.ruxcon.org.au/files/2006/web_services_security.ppt

http://www.owasp.org/index.php/OWASP_Java_Table_of_Contents#Defining_a_Java_Security_Policy

Microsoft‐ProgrammingforPartialTrust,http://msdn2.microsoft.com/en‐us/library/ms364059(VS.80).aspx

OWASPTop102007

17

A 4 – I N SE CU RE D I R E C T O B J E C T R E FE RE N CE

Adirectobjectreferenceoccurswhenadeveloperexposesareferencetoaninternalimplementationobject,suchasafile,directory,databaserecord,orkey,asaURLorformparameter.Unlessanaccesscontrolcheckisinplace,anattackercanmanipulatethosereferencestoaccessotherobjectswithoutauthorization.

ENVIRONMENTSAFFECTED

Allwebapplicationframeworksarevulnerabletoattacksoninsecuredirectobjectreferences.

VULNERABILITY

Manyapplicationsexposetheirinternalobjectreferencestousers.Attackersuseparametertamperingtochangereferencesandviolatetheintendedbutunenforcedaccesscontrolpolicy.Frequently,thesereferencespointtofilesystemsanddatabases,butanyexposedapplicationconstructcouldbevulnerable.

Forexample,ifcodeallowsuserinputtospecifyfilenamesorpaths,itmayallowattackerstojumpoutoftheapplication’sdirectory,andaccessotherresources.

<select name="language"><option value="fr">Français</option></select>

require_once ($_REQUEST['language’]."lang.php");

Suchcodecanbeattackedusingastringlike"../../../../etc/passwd%00"usingnullbyteinjection(seetheOWASPGuideformoreinformation)toaccessanyfileonthewebserver’sfilesystem.

Similarly,referencestodatabasekeysarefrequentlyexposed.Anattackercanattacktheseparameterssimplyby

guessingorsearchingforanothervalidkey.Often,thesearesequentialinnature.Intheexamplebelow,evenifanapplicationdoesnotpresentanylinkstounauthorizedcarts,andnoSQLinjectionispossible,anattackercanstill

changethecartIDparametertowhatevercarttheywant.

int cartID = Integer.parseInt( request.getParameter( "cartID" ) );

String query = "SELECT * FROM table WHERE cartID=" + cartID;

VERIFYINGSECURITY

Thegoalistoverifythattheapplicationdoesnotallowdirectobjectreferencestobemanipulatedbyanattacker.

Automatedapproaches:Vulnerabilityscanningtoolswillhavedifficultyidentifyingwhichparametersaresusceptibletomanipulationorwhetherthemanipulationworked.Staticanalysistoolsreallycannotknowwhichparametersmusthaveanaccesscontrolcheckbeforeuse.

Manualapproaches:Codereviewcantracecriticalparametersandidentifywhethertheyaresusceptibletomanipulationinmanycases.Penetrationtestingcanalsoverifythatmanipulationispossible.However,bothof

thesetechniquesaretime‐consumingandcanbespotty.

18

PROTECTION

Thebestprotectionistoavoidexposingdirectobjectreferencestousersbyusinganindex,map,orotherindirectmethodthatiseasytovalidate.Ifadirectobjectreferencemustbeused,ensurethattheuserisauthorizedbeforeusingit.

Establishingastandardwayofreferringtoapplicationobjectsisimportant: Avoidexposingyourprivateobjectreferencestouserswheneverpossible

Validateanyprivateobjectreferencesextensivelywithan"acceptknowngood"approach Verifyauthorizationtoallreferencedobjects

Ifyoumustexposeafilesystemreference,useanindexvalueoramaptopreventpathandfilenamemanipulation.

http://www.example.com/application?file=1

Ifyoumustexposedirectreferencestodatabasestructures,ensurethatSQLstatementsandotherdatabaseaccessmethodsonlyallowauthorizedrecordstobeshown:

int cartID = Integer.parseInt( request.getParameter( "cartID" ) );

User user = (User)request.getSession().getAttribute( "user" );

String query = "SELECT * FROM table WHERE cartID=" + cartID + " AND userID=" + user.getID();

SAMPLES

http://cve.mitre.org/cgi‐bin/cvename.cgi?name=CVE‐2007‐0329 http://cve.mitre.org/cgi‐bin/cvename.cgi?name=CVE‐2006‐4369

http://cve.mitre.org/cgi‐bin/cvename.cgi?name=CVE‐2005‐0229

REFERENCES

OWASP,http://www.owasp.org/index.php/Testing_for_business_logic

OWASP,http://www.owasp.org/index.php/Testing_for_Directory_Traversal

OWASP,http://www.owasp.org/index.php/Category:Access_Control_Vulnerability

OWASPTop102007

19

A 5 – C RO S S S I T E R E QUE ST FO RGE RY ( C SR F )

Crosssiterequestforgeryisnotanewattack,butissimpleanddevastating.ACSRFattackforcesalogged‐onvictim’sbrowsertosendarequesttoavulnerablewebapplication,whichthenperformsthechosenactiononbehalfofthevictim,tothebenefitoftheattacker.Thisvulnerabilityisextremelywidespread,asanyweb

applicationthatauthorizesrequestsbasedonlyoncredentialsthatareautomaticallysubmittedbythebrowserisvulnerable.Unfortunately,today,mostwebapplicationsrelysolelyonautomaticallysubmittedcredentialssuchas

sessioncookies,BasicAuthenticationcredentials,sourceIPaddresses,SSLcertificates,Windowsdomaincredentials,etc.

ThisvulnerabilityisalsoknownbyseveralothernamesincludingSessionRiding,One‐ClickAttacks,CrossSiteReferenceForgery,HostileLinking,andAutomationAttack.TheacronymXSRFisalsofrequentlyused.OWASPandMITREhavebothstandardizedonthetermCrossSiteRequestForgeryandCSRF.

ENVIRONMENTSAFFECTED

AllwebapplicationframeworksarevulnerabletoCSRF.

VULNERABILITY

AtypicalCSRFattackagainstaforummighttaketheformofdirectingtheusertoinvokesomefunction,suchastheapplication’slogoutpage.Thefollowingtaginanywebpageviewedbythevictimwillgeneratearequestwhichlogsthemout:

<img src="http://www.example.com/logout.php">

Ifanonlinebankalloweditsapplicationtoprocessrequests,suchastransferfunds,asimilarattackmightallow:

<img src="http://www.example.com/transfer.do?frmAcct=document.form.frmAcct &toAcct=4345754&toSWIFTid=434343&amt=3434.43">

Bothoftheseattacksworkbecausetheuser’sauthorizationcredential(typicallythesessioncookie)wouldautomaticallybeincludedwithsuchrequestsbythebrowser,eventhoughtheattackerdidn’tsupplythatcredential.

Ifthetagcontainingtheattackcanbepostedtoavulnerableapplication,thenthelikelihoodoffindingloggedinvictimsissignificantlyincreased,similartotheincreaseinriskbetweenstoredandreflectedXSSflaws.XSSflawsarenotrequiredforaCSRFattacktowork,althoughanyapplicationwithXSSflawsissusceptibletoCSRFbecause

aCSRFattackcanexploittheXSSflawtostealanynon‐automaticallysubmittedcredentialthatmightbeinplacetoprotectagainstaCSRFattack.Manyapplicationwormshaveusedbothtechniquesincombination.

WhenbuildingdefensesagainstCSRFattacks,youmustalsofocusoneliminatingXSSvulnerabilitiesinyourapplicationsincesuchflawscanbeusedtogetaroundmostCSRFdefensesyoumightputinplace.

VERIFYINGSECURITY

ThegoalistoverifythattheapplicationprotectsagainstCSRFattacksbygeneratingandthenrequiringsometypeofauthorizationtokenthatisnotautomaticallysubmittedbythebrowser.

20

Automatedapproaches:VulnerabilityscannersshouldbeabletodetectthelackofCSRFprotectioninapplicationswithalittlebitoftraining.Staticanalysistools,ontheotherhand,willhaveadifficulttimerecognizingacustom

mechanismforprotectingagainstthisattack.

Manualapproaches:PenetrationtestingisaquickwaytoverifythatCSRFprotectionisinplace.Toverifythatthe

mechanismisstrongandproperlyimplemented,checkingthecodeisthemostefficientcourse.

PROTECTION

Applicationsmustensurethattheyarenotrelyingoncredentialsortokensthatareautomaticallysubmittedbybrowsers.Theonlysolutionistouseacustomtokenthatthebrowserwillnot‘remember’andthenautomaticallyincludewithaCSRFattack.

Thefollowingstrategiesshouldbeinherentinallwebapplications:

EnsurethattherearenoXSSvulnerabilitiesinyourapplication(seeA1–CrossSiteScripting)

InsertcustomrandomtokensintoeveryformandURLthatwillnotbeautomaticallysubmittedbythebrowser.Forexample,

<form action="/transfer.do" method="post">

<input type="hidden" name="8438927730" value="43847384383">

… </form>

andthenverifythatthesubmittedtokeniscorrectforthecurrentuser.Suchtokenscanbeuniquetothat

particularfunctionorpageforthatuser,orsimplyuniquetotheoverallsession.Themorefocusedthetokenistoaparticularfunctionand/orparticularsetofdata,thestrongertheprotectionwillbe,butthe

morecomplicateditwillbetoconstructandmaintain.

Forsensitivedataorvaluetransactions,re‐authenticateorusetransactionsigningtoensurethattherequestisgenuine.Considersendingane‐mailorphoningthecustomeriftheactivityseemssuspicious,

toalerttheuserandpotentiallybackoutthetransaction.

DonotuseGETrequests(URLs)forsensitivedataortoperformvaluetransactions.UseonlyPOSTmethodswhenprocessingsensitivedatafromtheuser.

ForASP.NET, setaViewStateUserKey. (Seereferences).Thisprovidesasimilartypeofchecktoarandomtokenasdescribedabove.

Whilethesesuggestionswilldiminishyourexposuredramatically,advancedCSRFattackscanbypassmanyof

theserestrictions.Thestrongesttechniqueistheuseofuniquetokens,andeliminatingallXSSvulnerabilitiesinyourapplication.

SAMPLES http://cve.mitre.org/cgi‐bin/cvename.cgi?name=CVE‐2007‐0192 http://cve.mitre.org/cgi‐bin/cvename.cgi?name=CVE‐2006‐5116

MySpaceWormExplanationhttp://namb.la/popular/tech.html

OWASPTop102007

21

AnattackwhichusesQuicktimetoperformCSRFattackshttp://www.computerworld.com/action/article.do?command=viewArticleBasic&articleId=9005607&intsr

c=hm_list

REFERENCES

OWASPCSRF,http://www.owasp.org/index.php/Cross‐Site_Request_Forgery

OWASP,https://www.owasp.org/index.php/Testing_for_CSRF

OWASPCSRFGuard,http://www.owasp.org/index.php/CSRF_Guard

OWASPPHPCSRFGuard,http://www.owasp.org/index.php/PHP_CSRF_Guard

RSnake,"WhatisCSRF?",http://ha.ckers.org/blog/20061030/what‐is‐csrf/

Microsoft,ViewStateUserKeydetails,http://msdn2.microsoft.com/en‐us/library/ms972969.aspx#securitybarriers_topic2

22

A 6 – I N FO RMAT ION L E AK AGE AND IM P RO PE R E R RO R HANDL IN G

Applicationscanunintentionallyleakinformationabouttheirconfiguration,internalworkings,orviolateprivacythroughavarietyofapplicationproblems.Applicationscanalsoleakinternalstateviahowlongtheytaketoprocesscertainoperationsorviadifferentresponsestodifferinginputs,suchasdisplayingthesameerrortextwith

differenterrornumbers.Webapplicationswilloftenleakinformationabouttheirinternalstatethroughdetailedordebugerrormessages.

ENVIRONMENTSAFFECTED

Allwebapplicationframeworksarevulnerabletoinformationleakageandimpropererrorhandling.

VULNERABILITY

Applicationsfrequentlygenerateerrormessagesanddisplaythemtousers.Manytimestheseerrormessagesarequiteusefultoattackers,astheyrevealimplementationdetailsorinformationthatisusefulinexploringavulnerability.Thereareseveralcommonexamplesofthis:

Detailederrorhandling,whereinducinganerrordisplaystoomuchinformation,suchasstacktraces,failedSQLstatements,orotherdebugginginformation.

Functionsthatproducedifferentresultsbasedupondifferentinputs.Forexample,supplyingthesame

usernamebutdifferentpasswordstoaloginfunctionshouldproducethesametextfornosuchuser,andbadpassword.However,manysystemsproducedifferenterrorcodes.

VERIFYINGSECURITY

Thegoalistoverifythattheapplicationdoesnotleakinformationviaerrormessagesorothermeans.

Automatedapproaches:Vulnerabilityscanningtoolscanandprobablywillcauseerrormessagestobegenerated.Detectingwhetherthemessagesleakinformationisthechallenge.Staticanalysistoolscansearchfortheuseof

APIsthatleakinformation,butwillnotbeabletoverifythemeaningofthosemessages.

Manualapproaches:Acodereviewcansearchforimpropererrorhandlingandotherpatternsthatleakinformation,butitistime‐consuming.Testingwillalsogenerateerrormessages,butknowingwhaterrorpaths

werecoveredisachallenge.

PROTECTION

DevelopersshouldusetoolslikeOWASP'sWebScarabtotrytomaketheirapplicationgenerateerrors.Applicationsthathavenotbeentestedinthiswaywillalmostcertainlygenerateunexpectederroroutput.Applicationsshould

alsoincludeastandardexceptionhandlingarchitecturetopreventunwantedinformationfromleakingtoattackers.

Preventinginformationleakagerequiresdiscipline.Thefollowingpracticeshaveproveneffective: Ensurethattheentiresoftwaredevelopmentteamsharesacommonapproachtoexceptionhandling.

Disableorlimitdetailederrorhandling.Inparticular,donotdisplaydebuginformationtoendusers,stacktraces,orpathinformation.

OWASPTop102007

23

Ensurethatsecurepathsthathavemultipleoutcomesreturnsimilaroridenticalerrormessagesinroughlythesametime.Ifthisisnotpossible,considerimposingarandomwaittimeforalltransactionsto

hidethisdetailfromtheattacker.

SAMPLES

http://cve.mitre.org/cgi‐bin/cvename.cgi?name=CVE‐2006‐4899 http://cve.mitre.org/cgi‐bin/cvename.cgi?name=CVE‐2006‐3389

http://cve.mitre.org/cgi‐bin/cvename.cgi?name=CVE‐2002‐0580

REFERENCES

OWASP,http://www.owasp.org/index.php/Error_Handling

OWASP,http://www.owasp.org/index.php/Category:Sensitive_Data_Protection_Vulnerability

24

A 7 – B RO KE N A UT HEN T I CA T IO N A ND S E S S ION MANAGEMEN T

Properauthenticationandsessionmanagementiscriticaltowebapplicationsecurity.Flawsinthisareamostfrequentlyinvolvethefailuretoprotectcredentialsandsessiontokensthroughtheirlifecycle.Theseflawscanleadtothehijackingofuseroradministrativeaccounts,undermineauthorizationandaccountabilitycontrols,andcause

privacyviolations.

ENVIRONMENTSAFFECTED

Allwebapplicationframeworksarevulnerabletoauthenticationandsessionmanagementflaws.

VULNERABILITY

Flawsinthemainauthenticationmechanismarenotuncommon,butweaknessesaremoreoftenintroducedthroughancillaryauthenticationfunctionssuchaslogout,passwordmanagement,timeout,rememberme,secret

question,andaccountupdate.

VERIFYINGSECURITY

Thegoalistoverifythattheapplicationproperlyauthenticatesusersandproperlyprotectsidentitiesandtheirassociatedcredentials.

Automatedapproaches:Vulnerabilityscanningtoolshaveaverydifficulttimedetectingvulnerabilitiesincustom

authenticationandsessionmanagementschemes.Staticanalysistoolsarealsonotlikelytodetectauthenticationandsessionmanagementproblemsincustomcode.

Manualapproaches:Codereviewandtesting,especiallyincombination,arequiteeffectiveatverifyingthattheauthentication,sessionmanagement,andancillaryfunctionsareallimplementedproperly.

PROTECTION

Authenticationreliesonsecurecommunicationandcredentialstorage.FirstensurethatSSListheonlyoptionforallauthenticatedpartsoftheapplication(seeA9–InsecureCommunications)andthatallcredentialsarestoredinhashedorencryptedform(seeA8–InsecureCryptographicStorage).

Preventingauthenticationflawstakescarefulplanning.Amongthemostimportantconsiderationsare:

Useasingleauthenticationmechanismwithappropriatestrengthandnumberoffactors Usethecontainerprovidedsessionmanagementmechanismandnocustomcookies

Createanewsessionuponsuccessfulauthentication Ensurethateverypagehasalogoutlink,andthatlogoutdestroysallserversidesessionstateandclient

sidecookies Ensureancillaryauthenticationfunctions(questionsandanswers,passwordreset)areasstrongasthe

mainonesanddon'tcontainflaws DonotexposeanycredentialsinURLsorlogs(nosessionrewriting)

OWASPTop102007

25

SAMPLES

http://cve.mitre.org/cgi‐bin/cvename.cgi?name=CVE‐2006‐6145 http://cve.mitre.org/cgi‐bin/cvename.cgi?name=CVE‐2006‐6229

http://cve.mitre.org/cgi‐bin/cvename.cgi?name=CVE‐2006‐6528

REFERENCES

OWASP,http://www.owasp.org/index.php/Guide_to_Authentication OWASP,http://www.owasp.org/index.php/Reviewing_Code_for_Authentication

OWASP,http://www.owasp.org/index.php/Testing_for_authentication

26

A 8 – I N SE CU RE C RY P TO GRA PH I C S TO RAG E

Protectingsensitivedatawithcryptographyhasbecomeakeypartofmostwebapplications.Simplyfailingtoencryptsensitivedataisverywidespread.Applicationsthatdoencryptfrequentlycontainpoorlydesignedcryptography,eitherusinginappropriateciphersormakingseriousmistakesusingstrongciphers.Theseflawscan

leadtodisclosureofsensitivedataandcomplianceviolations.

ENVIRONMENTSAFFECTED

Allwebapplicationframeworksarevulnerabletoinsecurecryptographicstorage.

VULNERABILITY

Preventingcryptographicflawstakescarefulplanning.Themostcommonproblemsare:

Notencryptingsensitivedata

Usinghomegrownalgorithms

Insecureuseofstrongalgorithms

Continueduseofprovenweakalgorithms(MD5,SHA‐1,RC3,RC4,etc…)

Hardcodingkeys,andstoringkeysinunprotectedstores

VERIFYINGSECURITY

Thegoalistoverifythattheapplicationproperlyencryptssensitiveinformationinstorage.

Automatedapproaches:Vulnerabilityscanningtoolscannotverifycryptographicstorageatall.CodescanningtoolscandetectuseofknowncryptographicAPIs,butcannotdetectifitisbeingusedproperlyoriftheencryptionisperformedinanexternalcomponent.

Manualapproaches:Likescanning,testingcannotverifycryptographicstorage.Codereviewisthebestwaytoverifythatanapplicationencryptssensitivedataandhasproperlyimplementedthemechanismandkeymanagement.Thismayinvolvetheexaminationoftheconfigurationofexternalsystemsinsomecases.

PROTECTION

Themostimportantaspectistoensurethateverythingthatshouldbeencryptedisactuallyencrypted.Thenyou

mustensurethatthecryptographyisimplementedproperly.Astherearesomanywaysofusingcryptographyimproperly,thefollowingrecommendationsshouldbetakenaspartofyourtestingregimetohelpensuresecure

cryptographicmaterialshandling:

Donotallowunqualifiedstafftotrytocreatecryptographicalgorithms.UseonlyapprovedpublicalgorithmssuchasAES,RSApublickeycryptography,andSHA‐256orbetterforhashing.

Donotuseweakalgorithms,suchasMD5/SHA1.Favorsaferalternatives,suchasSHA‐256orbetter.

OWASPTop102007

27

Generatekeysofflineandstoreprivatekeyswithextremecare

EnsurethatinfrastructurecredentialssuchasdatabasecredentialsorMQqueueaccessdetailsare

securelyencryptedandnoteasilydecryptedbylocalorremoteusers

Ensurethatencrypteddatastoredondiskisnoteasytodecrypt.Forexample,databaseencryptionisworthlessifthedatabaseconnectionpoolprovidesunencryptedaccess.Allthisdoesisslowdownthe

databaseandmakequeriesveryslow.

UnderPCIDataSecurityStandardrequirement3,youmustprotectcardholderdata.PCIDSScomplianceismandatoryby2008formerchantsandanyoneelsedealingwithcreditcards.Goodpracticeistonever

storeunnecessarydata,suchasthemagneticstripeinformationortheprimaryaccountnumber(PAN,otherwiseknownasthecreditcardnumber).IfyoustorethePAN,theDSScompliancerequirementsare

heftyandcontinuing.Forexample,youareNEVERallowedtostoretheCVVnumber(thethreedigitnumberontherearofthecard)underanycircumstances.Formoreinformation,pleaseseethePCIDSS

Guidelinesandimplementcontrolsasnecessary.

SAMPLES

http://cve.mitre.org/cgi‐bin/cvename.cgi?name=CVE‐2006‐6145 http://cve.mitre.org/cgi‐bin/cvename.cgi?name=CVE‐2005‐1664

http://cve.mitre.org/cgi‐bin/cvename.cgi?name=CVE‐1999‐1101(TrueofmostJavaEEservletcontainers,too)

REFERENCES

OWASP,http://www.owasp.org/index.php/Cryptography

OWASP,http://www.owasp.org/index.php/Guide_to_Cryptography

OWASP,http://www.owasp.org/index.php/Insecure_Storage

OWASP,http://www.owasp.org/index.php/How_to_protect_sensitive_data_in_URL’s

PCIDataSecurityStandardv1.1,https://www.pcisecuritystandards.org/pdfs/pci_dss_v1‐1.pdf

BruceSchneier,http://www.schneier.com/

CryptoAPINextGeneration,http://msdn2.microsoft.com/en‐us/library/aa376210.aspx

28

A 9 – I N SE CU RE COMMUN IC A T ION S

Applicationsfrequentlyfailtoencryptnetworktrafficwhenitisnecessarytoprotectsensitivecommunications.Encryption(usuallySSL)mustbeusedforallauthenticatedconnections,especiallyinternetaccessiblewebpagesbutbackendconnectionsaswell.Otherwise,theapplicationwillexposeanauthenticationorsessiontoken.In

addition,encryptionshouldbeusedwheneversensitivedata,suchascreditcardorhealthinformationistransmitted.Applicationsthatfallbackorcanbeforcedoutofanencryptingmodecanbeabusedbyattackers.

ThePCIstandardrequiresthatallcreditcardinformationbeingtransmittedovertheinternetbeencrypted.

ENVIRONMENTSAFFECTED

Allwebapplicationframeworksarevulnerabletoinsecurecommunications.

VULNERABILITY

Failuretoencryptsensitivecommunicationsmeansthatanattackerwhocansnifftrafficfromthenetworkwillbeabletoaccesstheconversation,includinganycredentialsorsensitiveinformationtransmitted.Considerthatdifferentnetworkswillbemoreorlesssusceptibletosniffing.However,itisimportanttorealizethateventuallya

hostwillbecompromisedonalmosteverynetwork,andattackerswillquicklyinstallasniffertocapturethecredentialsofothersystems.

UsingSSLforcommunicationswithendusersiscritical,astheyareverylikelytobeusinginsecurenetworkstoaccessapplications.BecauseHTTPincludesauthenticationcredentialsorasessiontokenwitheverysinglerequest,

allauthenticatedtrafficneedstogooverSSL,notjusttheactualloginrequest.

Encryptingcommunicationswithbackendserversisalsoimportant.Althoughthesenetworksarelikelytobemoresecure,theinformationandcredentialstheycarryismoresensitiveandmoreextensive.ThereforeusingSSLon

thebackendisquiteimportant.

Encryptingsensitivedata,suchascreditcardsandsocialsecuritynumbers,hasbecomeaprivacyandfinancialregulationformanyorganizations.NeglectingtouseSSLforconnectionshandlingsuchdatacreatesacompliance

risk.

VERIFYINGSECURITY

Thegoalistoverifythattheapplicationproperlyencryptsallauthenticatedandsensitivecommunications.

Automatedapproaches:VulnerabilityscanningtoolscanverifythatSSLisusedonthefrontend,andcanfindmanySSLrelatedflaws.However,thesetoolsdonothaveaccesstobackendconnectionsandcannotverifythattheyare

secure.Staticanalysistoolsmaybeabletohelpwithanalyzingsomecallstobackendsystems,butprobablywillnotunderstandthecustomlogicrequiredforalltypesofsystems.

Manualapproaches:TestingcanverifythatSSLisusedandfindmanySSLrelatedflawsonthefrontend,buttheautomatedapproachesareprobablymoreefficient.CodereviewisquiteefficientforverifyingtheproperuseofSSLforallbackendconnections.

OWASPTop102007

29

PROTECTION

ThemostimportantprotectionistouseSSLonanyauthenticatedconnectionorwheneversensitivedataisbeingtransmitted.ThereareanumberofdetailsinvolvedwithconfiguringSSLforwebapplicationsproperly,sounderstandingandanalyzingyourenvironmentisimportant.

UseSSLforallconnectionsthatareauthenticatedortransmittingsensitiveorvaluedata,suchas

credentials,creditcarddetails,healthandotherprivateinformation. Ensurethatcommunicationsbetweeninfrastructureelements,suchasbetweenwebserversand

databasesystemsareappropriatelyprotectedviatheuseoftransportlayersecurityorprotocollevelencryptionforcredentialsandintrinsicvaluedata.

IE7.0providesagreenbarforhightrustSSLcertificates,butthisisnotasuitablecontroltoprovesafeuseofcryptographyalone.Itjustmeansyoupaidalotmoreforacertificatethanmostfolks.

UnderPCIDataSecurityStandardrequirement4,youmustprotectcardholderdataintransit.PCIDSScomplianceismandatoryby2008formerchantsandanyoneelsedealingwithcreditcards.Ingeneral,

client,partner,staffandadministrativeonlineaccesstosystemsmustbeencryptedusingSSLorsimilar.Formoreinformation,pleaseseethePCIDSSGuidelinesandimplementcontrolsasnecessary.

SAMPLES http://cve.mitre.org/cgi‐bin/cvename.cgi?name=CVE‐2006‐6430

http://cve.mitre.org/cgi‐bin/cvename.cgi?name=CVE‐2005‐4704 http://www.schneier.com/blog/archives/2005/10/scandinavian_at_1.html

REFERENCES

OWASPTestingGuide,TestingforSSL/TLS,https://www.owasp.org/index.php/Testing_for_SSL‐TLS

OWASPGuide,http://www.owasp.org/index.php/Guide_to_Cryptography

Foundstone‐SSLDigger,

http://www.foundstone.com/index.htm?subnav=services/navigation.htm&subcontent=/services/overview_s3i_des.htm

NIST,SP800‐52Guidelinesfortheselectionanduseoftransportlayersecurity(TLS)Implementations,http://csrc.nist.gov/publications/nistpubs/800‐52/SP800‐52.pdf

NISTSP800‐95Guidetosecurewebservices,http://csrc.nist.gov/publications/drafts.html#sp800‐95

30

A 1 0 – F A I L U RE TO R E S T R I C T U R L A C C E S S

Frequently,theonlyprotectionforaURListhatlinkstothatpagearenotpresentedtounauthorizedusers.However,amotivated,skilled,orjustplainluckyattackermaybeabletofindandaccessthesepages,invokefunctions,andviewdata.Securitybyobscurityisnotsufficienttoprotectsensitivefunctionsanddatainan

application.Accesscontrolchecksmustbeperformedbeforearequesttoasensitivefunctionisgrantedwhichensuretheuserisauthorizedtoaccessthatfunction.

ENVIRONMENTSAFFECTED

AllwebapplicationframeworksarevulnerabletofailuretorestrictURLaccess.

VULNERABILITY

Theprimaryattackmethodforthisvulnerabilityiscalled"forcedbrowsing",whichencompassesguessinglinksandbruteforcetechniquestofindunprotectedpages.Applicationsfrequentlyallowaccesscontrolcodetoevolveandspreadthroughoutacodebase,resultinginacomplexmodelthatisdifficulttounderstandfordevelopersand

securityspecialistsalike.Thiscomplexitymakesitlikelythaterrorswilloccurandpageswillbemissed,leavingthemexposed.

Somecommonexamplesoftheseflawsinclude: "Hidden"or"special"URLs,renderedonlytoadministratorsorprivilegedusersinthepresentationlayer,

butaccessibletoallusersiftheyknowitexists,suchas/admin/adduser.phpor/approveTransfer.do.This

isparticularlyprevalentwithmenucode. Applicationsoftenallowaccessto"hidden"files,suchasstaticXMLorsystemgeneratedreports,trusting

securitythroughobscuritytohidethem. Codethatenforcesanaccesscontrolpolicybutisoutofdateorinsufficient.Forexample,imagine

/approveTransfer.dowasonceavailabletoallusers,butsinceSOXcontrolswerebroughtin,itisonlysupposedtobeavailabletoapprovers.Afixmighthavebeentonotpresentittounauthorizedusers,but

noaccesscontrolisactuallyenforcedwhenrequestingthatpage. Codethatevaluatesprivilegesontheclientbutnotontheserver,asinthisattackonMacWorld2007,

whichapproved"Platinum"passesworth$1700viaJavaScriptonthebrowserratherthanontheserver.

VERIFYINGSECURITY

ThegoalistoverifythataccesscontrolisenforcedconsistentlyinthepresentationlayerandthebusinesslogicforallURLsintheapplication.

Automatedapproaches:BothvulnerabilityscannersandstaticanalysistoolshavedifficultywithverifyingURL

accesscontrol,butfordifferentreasons.Vulnerabilityscannershavedifficultyguessinghiddenpagesanddeterminingwhichpagesshouldbeallowedforeachuser,whilestaticanalysisenginesstruggletoidentifycustom

accesscontrolsinthecodeandlinkthepresentationlayerwiththebusinesslogic.

Manualapproaches:Themostefficientandaccurateapproachistouseacombinationofcodereviewandsecuritytestingtoverifytheaccesscontrolmechanism.Ifthemechanismiscentralized,theverificationcanbequite

efficient.Ifthemechanismisdistributedacrossanentirecodebase,verificationcanbemoretime‐consuming.Ifthemechanismisenforcedexternally(WebSEALorSiteMinder),theconfigurationmustbeexaminedandtested.

OWASPTop102007

31

PROTECTION

TakingthetimetoplanauthorizationbycreatingamatrixtomaptherolesandfunctionsoftheapplicationisakeystepinachievingprotectionagainstunrestrictedURLaccess.WebapplicationsmustenforceaccesscontroloneveryURLandbusinessfunction.Itisnotsufficienttoputaccesscontrolintothepresentationlayerandleavethe

businesslogicunprotected.Itisalsonotsufficienttocheckonceduringtheprocesstoensuretheuserisauthorized,andthennotcheckagainonsubsequentsteps.Otherwise,anattackercansimplyskipthestepwhere

authorizationischecked,andforgetheparametervaluesnecessarytocontinueonatthenextstep.

EnablingURLaccesscontroltakessomecarefulplanning.Amongthemostimportantconsiderationsare:

Ensurethattheenforcementofyouraccesscontrolmatrixispartofthebusiness,architecture,anddesignoftheapplication.

EnsurethatallURLsandbusinessfunctionsareprotectedbyaneffectiveaccesscontrolmechanismthat

verifiestheuser’sroleandentitlementspriortoanyprocessingtakingplace.Makesurethisisdoneduringeverystepoftheway,notjustoncetowardsthebeginningofanymulti‐stepprocess.

Performapenetrationtestpriortodeploymentorcodedeliverytoensurethattheapplicationcannotbemisusedbyamotivatedskilledattacker.

DonotassumethatuserswillbeunawareofspecialorhiddenURLsorAPIs.Alwaysensurethat

administrativeandhighprivilegeactionsareprotected. Blockaccess toallfiletypesthatyourapplicationshouldneverserve.Ideally,thisfilterwouldfollowthe

"acceptknowngood"approachandonlyallowfiletypesthatyouintendtoserve,e.g.,.html,.pdf,.php.Thiswouldthenblockanyattemptstoaccesslogfiles,xmlfiles,etc.thatyouneverintendtoserve

directly.

SAMPLES

http://cve.mitre.org/cgi‐bin/cvename.cgi?name=CVE‐2007‐0147 http://cve.mitre.org/cgi‐bin/cvename.cgi?name=CVE‐2007‐0131

http://cve.mitre.org/cgi‐bin/cvename.cgi?name=CVE‐2006‐1227

REFERENCES

OWASP,http://www.owasp.org/index.php/Testing_for_Directory_Traversal

OWASP,http://www.owasp.org/index.php/Forced_browsing

OWASP,http://www.owasp.org/index.php/Guide_to_Authorization

32

WH ER E T O GO F ROM H E RE

TheOWASPTop10isjustthebeginningofyourwebapplicationsecurityjourney.

Theworld'ssixbillionpeoplecanbedividedintotwogroups:groupone,whoknowwhyeverygoodsoftwarecompanyshipsproductswithknownbugs;andgrouptwo,whodon't.Thoseingroup1tendtoforgetwhatlifewaslikebeforeouryouthfuloptimismwasspoiledbyreality.Sometimesweencounterapersoningrouptwo…whoisshockedthatanysoftwarecompanywouldshipaproductbeforeeverylastbugisfixed.

EricSink,GuardianMay25,2006

Mostofyourusersandcustomersareingrouptwo.Howyoudealwiththisproblemisanopportunitytoimprove

yourcodeandthestateofwebapplicationsecurityingeneral.Billionsofdollarsarelosteveryyear,andmanymillionsofpeoplesufferidentitytheftandfraudduetothevulnerabilitiesdiscussedinthisdocument.

FORARCHITECTSANDDESIGNERS

Toproperlysecureyourapplications,youmustknowwhatyou’resecuring(assetclassification),knowthethreatsandrisksofinsecurity,andaddresstheseinastructuredway.Designinganynon‐trivialapplicationrequiresagood

doseofsecurity.

Ensurethatyouapply"justenough"securitybaseduponthreatriskmodelingandassetclassification

Askquestionsaboutbusinessrequirements,particularlymissingnon‐functionalrequirements

WorkthroughtheOWASPSecureSoftwareContractAnnexwithyourcustomer

Encouragesaferdesign–includedefenseindepthandsimplerconstructs

Ensurethatyouhaveconsideredconfidentiality,integrity,andavailability

Ensureyourdesignsareconsistentwithsecuritypolicyandstandards,suchasCOBITorPCIDSS1.1

FORDEVELOPERS

Manydevelopersalreadyhaveagoodhandleonwebapplicationsecuritybasics.Toensureeffectivemasteryofthewebapplicationsecuritydomainrequirespractice.Anyonecandestroy(i.e.performpenetrationtesting)–ittakesamastertobuildsecuresoftware.Aimtobecomeamaster.

ConsiderjoiningOWASPandattendinglocalchaptermeetings

Askforsecurecodetrainingifyouhaveatrainingbudget.Askforatrainingbudgetifyoudon’thaveone

Designyourfeaturessecurely–considerdefenseindepthandsimplicityindesign

Adoptcodingstandardswhichencouragesafercodeconstructs

Refactorexistingcodetousesaferconstructsinyourchosenplatform,suchasparameterizedqueries

OWASPTop102007

33

ReviewtheOWASPGuideandstartapplyingselectedcontrolstoyourcode.Unlikemostsecurityguides,itisdesignedtohelpyoubuildsecuresoftware,notbreakit

Testyourcodeforsecuritydefectsandmakethispartofyourunitandwebtestingregime Buyacopyof"TheSecurityDevelopmentLifecycle"(see[HOW1]inthebookreferences)andadoptmany

ofitspractices.

FOROPENSOURCEPROJECTS

Opensourceisaparticularchallengeforwebapplicationsecurity.Thereareliterallymillionsofopensourceprojects,fromonedeveloperpersonal"itches"throughtomajorprojectssuchasApache,Tomcat,andlargescalewebapplications,suchasPostNuke.

ConsiderjoiningOWASPandattendinglocalchaptermeetings

Ifyourprojecthasmorethan4developers,considermakingatleastonedeveloperasecurityperson

Designyourfeaturessecurely–considerdefenseindepthandsimplicityindesign

Adoptcodingstandardswhichencouragesafercodeconstructs

Adopttheresponsibledisclosurepolicytoensurethatsecuritydefectsarehandledproperly

Buyacopyof"TheSecurityDevelopmentLifecycle"andadoptmanyofitspractices.

FORAPPLICATIONOWNERS

Applicationownersincommercialsettingsareoftentimeandresourceconstrained.Applicationownersshould:

WorkthroughtheOWASPSecureSoftwareContractAnnexwiththesoftwareproducers

Ensurebusinessrequirementsincludenon‐functionalrequirements(NFRs)suchassecurityrequirements

Encouragedesignswhichincludesecurebydefaultfeatures,defenseindepthandsimplicityindesign

Employ(ortrain)developerswhohaveastrongsecuritybackground

Testforsecuritydefectsthroughouttheproject:design,build,test,anddeployment

Allowresources,budgetandtimeintheprojectplantoremediatesecurityissues

FORC‐LEVELEXECUTIVES

Yourorganizationmusthaveasecuredevelopmentlifecycle(SDLC)inplacethatsuitsyourorganization.AreasonableSDLCnotonlyincludestestingfortheTop10,itincludes:

Forofftheshelfsoftware,ensurepurchasingpoliciesandcontractsincludesecurityrequirements

Forcustomcode,adoptsecurecodingprinciplesinyourpoliciesandstandards

34

Trainyourdevelopersinsecurecodingtechniquesandensuretheykeeptheseskillsuptodate

Trainyourarchitects,designers,andbusinesspeopleinwebapplicationsecurityfundamentals

Adopttheresponsibledisclosurepolicytoensurethatsecuritydefectsarehandledproperly

OWASPTop102007

35

R E FE R EN CE S

OWASPPROJECTS

OWASPisthepremiersiteforwebapplicationsecurity.TheOWASPsitehostsmanyprojects,forums,blogs,presentations,tools,andpapers.OWASPhoststwomajorwebapplicationsecurityconferencesperyear,andhas

over80localchapters.

ThefollowingOWASPprojectsaremostlikelytobeuseful: OWASPGuidetoBuildingSecureWebApplications

OWASPTestingGuide OWASPCodeReviewProject(indevelopment)

OWASPPHPProject(indevelopment) OWASPJavaProject

OWASP.NETProject

BOOKS

[GAL1]GallagherT.,LandauerL.,JeffriesB.,"HuntingSecurityBugs",MicrosoftPress,ISBN073562187X

[HOW1]HowardM.,LipnerS.,"TheSecurityDevelopmentLifecycle",MicrosoftPress,ISBN0735622140

[HOW2]HowardM.,LeBlancD.,"WritingSecureCode",2nded.,MicrosoftPress,ISBN0735617228

[SCH1]SchneierB.,"PracticalCryptography",Wiley,ISBN047122894X

WEBSITES

OWASP,http://www.owasp.org

MITRE,CommonWeaknesses–VulnerabilityTrends,http://cwe.mitre.org/documents/vuln‐trends.html

SANSTop20,http://www.sans.org/top20/

PCISecurityStandardsCouncil,publishersofthePCIstandards,relevanttoallorganizationsprocessingorholdingcreditcarddata,https://www.pcisecuritystandards.org/

PCIDSSv1.1,https://www.pcisecuritystandards.org/pdfs/pci_dss_v1‐1.pdf

BuildSecurityIn,USCERT,https://buildsecurityin.us‐cert.gov/daisy/bsi/home.html