CodeReviewMicrosoftLearn

Accesstothispagerequiresauthorization.Youcantrychangingdirectories.

Thiscontentisoutdatedandisnolongerbeingmaintained.Itisprovidedasacourtesyforindividualswhoarestillusingthesetechnologies.ThispagemaycontainURLsthatwerevalidwhenoriginallypublished,butnowlinktositesorpagesthatnolongerexist.

ImprovingWebApplicationSecurity:ThreatsandCountermeasures

J.D.Meier,AlexMackman,MichaelDunner,SrinathVasireddy,RayEscamillaandAnandhaMurukanMicrosoftCorporation

Published:June2003

LastRevised:January2006

Summary:Thischaptershowsyouhowtoreviewcodebuiltusingthe.NETFrameworkforpotentialsecurityvulnerabilities.Itshowsyouthespecificreviewquestionstoaskanddiscussesthetoolsthatyoushoulduse.Inadditiontogeneralcodingconsiderations,thechapterincludesreviewquestionstohelpyoureviewyourapplicationsforcross-sitescripting,SQLinjectionandbufferoverflowvulnerabilities.

InThisChapterOverviewFxCopPerformingTextSearchesCross-SiteScripting(XSS)SQLInjectionBufferOverflowsManagedCodeCodeAccessSecurityUnmanagedCodeASP.NETPagesandControlsWebServicesServicedComponentsRemotingDataAccessCodeSummaryAdditionalResource

Codereviewsshouldbearegularpartofyourdevelopmentprocess.Securitycodereviewsfocusonidentifyinginsecurecodingtechniquesandvulnerabilitiesthatcouldleadtosecurityissues.Thereviewgoalistoidentifyasmanypotentialsecurityvulnerabilitiesaspossiblebeforethecodeisdeployed.Thecostandeffortoffixingsecurityflawsatdevelopmenttimeisfarlessthanfixingthemlaterintheproductdeploymentcycle.

ThischapterhelpsyoureviewmanagedASP.NETWebapplicationcodebuiltusingtheMicrosoft.NETFramework.Inaddition,itcoversreviewingcallstounmanagedcode.Thechapterisorganizedbyfunctionalarea,andincludessectionsthatpresentgeneralcodereviewquestionsapplicabletoalltypesofmanagedcodeaswellassectionsthatfocusonspecifictypesofcodesuchasWebservices,servicedcomponents,dataaccesscomponents,andsoon.

Thischaptershowsthequestionstoasktoexposepotentialsecurityvulnerabilities.YoucanfindsolutionstothesequestionsintheindividualbuildingchaptersinPartIIIofthisguide.Youcanalsousethecodereviewchecklistsinthe"Checklists"sectionoftheguidetohelpyouduringthereviewprocess.

AgoodwaytostartthereviewprocessistorunyourcompiledassembliesthroughtheFxCopanalysistool.Thetoolanalyzesbinaryassemblies(notsourcecode)toensurethattheyconformtothe.NETFrameworkDesignGuidelines,availableonMSDN.Italsochecksthatyourassemblieshavestrongnames,whichprovidetamperproofingandothersecuritybenefits.Thetoolcomeswithapredefinedsetofrules,althoughyoucancustomizeandextendthem.

Formoreinformation,seethefollowingresources:

Toassistthereviewprocess,checkthatyouarefamiliarwithatextsearchtoolthatyoucanusetolocatestringsinfiles.Thistypeoftoolallowsyoutoquicklylocatevulnerablecode.Manyofthereviewquestionspresentedlaterinthechapterindicatethebeststringstosearchforwhenlookingforspecificvulnerabilities.

Youmayalreadyhaveafavoritesearchtool.Ifnot,youcanusetheFindinFilesfacilityinVisualStudio.NETortheFindstrcommandlinetool,whichisincludedwiththeMicrosoftWindowsoperatingsystem.

NoteIfyouusetheWindowsXPSearchtoolfromWindowsExplorer,andusetheAwordorphraseinthefileoption,checkthatyouhavethelatestWindowsXPservicepack,orthesearchmayfail.Formoreinformation,seeMicrosoftKnowledgeBasearticle309173,"Usingthe'AWordorPhraseintheFile'SearchCriterionMayNotWork."

Beforeyouperformadetailedline-by-lineanalysisofyoursourcecode,startwithaquicksearchthroughyourentirecodebasetoidentifyhard-codedpasswords,accountnames,anddatabaseconnectionstrings.Scanthroughyourcodeandsearchforcommonstringpatternssuchasthefollowing:"key,""secret,""password,""pwd,"and"connectionstring."

Forexample,tosearchforthestring"password"intheWebdirectoryofyourapplication,usetheFindstrtoolfromacommandpromptasfollows:

findstr/S/M/I/d:c:\projects\yourweb"password"*.*Findstrusesthefollowingcommand-lineparameters:

Youcancreateatextfilewithcommonsearchstrings.Findstrcanthenreadthesearchstringsfromthetextfile,asshownbelow.Runthefollowingcommandfromadirectorythatcontains.aspxfiles.

findstr/N/G:SearchStrings.txt*.aspx/Nprintsthecorrespondinglinenumberwhenamatchisfound./Gindicatesthefilethatcontainsthesearchstrings.Inthisexample,allASP.NETpages(*.aspx)aresearchedforstringscontainedwithinSearchStrings.txt.

YoucanalsousetheFindstrcommandinconjunctionwiththeildasm.exeutilitytosearchbinaryassembliesforhard-codedstrings.Thefollowingcommandusesildasm.exetosearchfortheldstrintermediatelanguagestatement,whichidentifiesstringconstants.Noticehowtheoutputshownbelowrevealsahard-codeddatabaseconnectionandthepasswordofthewellknownsaaccount.

Ildasm.exesecureapp.dll/text|findstrldstrIL_000c:ldstr"RegisterUser"IL_0027:ldstr"@userName"IL_0046:ldstr"@passwordHash"IL_0065:ldstr"@salt"IL_008b:ldstr"Exceptionaddingaccount."IL_000e:ldstr"LookupUser"IL_0027:ldstr"@userName"IL_007d:ldstr"SHA1"IL_0097:ldstr"Execeptionverifyingpassword."IL_0009:ldstr"SHA1"IL_003e:ldstr"Logonsuccessful:Userisauthenticated"IL_0050:ldstr"Invalidusernameorpassword"IL_0001:ldstr"Server=AppServer;database=users;username='sa'password=password"NoteIldasm.exeislocatedinthe\ProgramFiles\MicrosoftVisualStudio{versionnumber}\SDK\{FrameworkVersionnumber}\binfolder.Formoreinformationaboutthesupportedcommand-linearguments,runildasm.exe/.

Yourcodeisvulnerabletocross-sitescripting(XSS,alsoreferredtoasCSS)attackswhereveritusesinputparametersintheoutputHTMLstreamreturnedtotheclient.Evenbeforeyouconductacodereview,youcanrunasimpletesttocheckifyourapplicationisvulnerabletoXSS.Searchforpageswhereuserinputinformationissentbacktothebrowser.

XSSbugsareanexampleofmaintainingtoomuchtrustindataenteredbyauser.Forexample,yourapplicationmightexpecttheusertoenteraprice,butinsteadtheattackerincludesapriceandsomeHTMLandJavaScript.Therefore,youshouldalwaysensurethatdatathatcomesfromuntrustedsourcesisvalidated.Whenreviewingcode,alwaysaskthequestion,"Isthisdatavalidated"KeepalistofallentrypointsintoyourASP.NETapplication,suchasHTTPheaders,querystrings,formdata,andsoon,andmakesurethatallinputischeckedforvalidityatsomepoint.Donottestforincorrectinputvaluesbecausethatapproachassumesthatyouareawareofallpotentiallyriskyinput.ThemostcommonwaytocheckthatdataisvalidinASP.NETapplicationsistouseregularexpressions.

Youcanperformasimpletestbytypingtextsuchas"XYZ"informfieldsandtestingtheoutput.Ifthebrowserdisplays"XYZ"orifyousee"XYZ"whenyouviewthesourceoftheHTML,thenyourWebapplicationisvulnerabletoXSS.Ifyouwanttoseesomethingmoredynamic,inject.Thistechniquemightnotworkinallcasesbecauseitdependsonhowtheinputisusedtogeneratetheoutput.

ThefollowingprocesshelpsyoutoidentifycommonXSSvulnerabilities:

Viewthepageoutputsourcefromthebrowsertoseeifyourcodeisplacedinsideanattribute.Ifitis,injectthefollowingcodeandretesttoviewtheoutput.

"onmouseover=alert('hello');"Acommontechniqueusedbydevelopersistofilterforcharacters.Ifthecodethatyoureviewfiltersforthesecharacters,thentestusingthefollowingcodeinstead:

&{alert('hello');}Ifthecodedoesnotfilterforthosecharacters,thenyoucantestthecodebyusingthefollowingscript:

;Youmayhavetocloseatagbeforeusingthisscript,asshownbelow.

">Searchingfor".Write"Searchforthe".Write"stringacross.aspxsourcecodeandcodecontainedinanyadditionalassemblyyouhavedevelopedforyourapplication.ThislocatesoccurrencesofResponse.Write,andanyinternalroutinesthatmaygenerateoutputthrougharesponseobjectvariable,suchasthecodeshownbelow.

publicvoidWriteOutput(ResponserespObj){respObj.Write(Request.Form["someField"]);}Youshouldalsosearchforthe"<%="stringwithin.aspxsourcecode,whichcanalsobeusedtowriteoutput,asshownbelow:

<%=myVariable%>ThefollowingtableshowssomecommonsituationswhereResponse.Writeisusedwithinputfields.

Table21.1PossibleSourcesofInput

Response.Write(name.Text);Response.Write(Request.Form["name"]);QueryStringsResponse.Write(Request.QueryString["name"]);CookiesResponse.Write(Request.Cookies["name"].Values["name"]);SessionandApplicationvariablesResponse.Write(Session["name"]);Response.Write(Application["name"]);DatabasesanddatastoresSqlDataReaderreader=cmd.ExecuteReader();Response.Write(reader.GetString(1));IdentifyPotentiallyDangerousHTMLTagsandAttributesWhilenotexhaustive,thefollowingcommonlyusedHTMLtagscouldallowamalicioususertoinjectscriptcode:

Forexample,thesrcattributeofthetagcanbeasourceofinjectionasshowninthefollowingexamples.

TheChecktoseeifyourcodeattemptstosanitizeinputbyfilteringoutcertainknownriskycharacters.Donotrelyuponthisapproachbecausemalicioususerscangenerallyfindanalternativerepresentationtobypassyourvalidation.Instead,yourcodeshouldvalidateforknownsecure,safeinput.Thefollowingtableshowsvariouswaystorepresentsomecommoncharacters:

Table21.2CharacterRepresentation

CodethathandlesURLscanbevulnerable.Reviewyourcodetoseeifitisvulnerabletothefollowingcommonattacks:

Whilenotareplacementforcheckingthatinputiswell-formedandcorrect,youshouldcheckthatHtmlEncodeisusedtoencodeHTMLoutputthatincludesanytypeofinput.AlsocheckthatUrlEncodeisusedtoencodeURLstrings.Inputdatacancomefromquerystrings,formfields,cookies,HTTPheaders,andinputreadfromadatabase,particularlyifthedatabaseissharedbyotherapplications.Byencodingthedata,youpreventthebrowserfromtreatingtheHTMLasexecutablescript.

Tohelppreventattackersusingcanonicalizationandmulti-byteescapesequencestotrickyourinputvalidationroutines,checkthatthecharacterencodingissetcorrectlytolimitthewayinwhichinputcanberepresented.

CheckthattheapplicationWeb.configfilehassettherequestEncodingandresponseEncodingattributesconfiguredbytheelementasshownbelow.

CharacterencodingcanalsobesetatthepagelevelusingatagorResponseEncodingpage-levelattributeasshownbelow.

Webapplicationsthatarebuiltusingthe.NETFrameworkversion1.1orlaterperforminputfilteringtoeliminatepotentiallymaliciousinput,suchasembeddedscript.Donotrelyonthis,butuseitfordefenseindepth.ChecktheelementinyourconfigurationfiletoconfirmthatthevalidateRequestattributeissettotrue.Thiscanalsobesetasapage-levelattribute.Scanyour.aspxsourcefilesforvalidateRequest,andcheckthatitisnotsettofalseforanypage.

InternetExplorer6SP1supportsanewHttpOnlycookieattributethatpreventsclient-sidescriptfromaccessingthecookiefromthedocument.cookieproperty.Instead,anemptystringisreturned.ThecookieisstillsenttotheserverwhenevertheuserbrowsestoaWebsiteinthecurrentdomain.Formoreinformation,seethe"Cross-SiteScripting"sectioninChapter10,"BuildingSecureASP.NETPagesandControls."

InternetExplorer6andlatersupportsanewsecurityattributeontheand