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');"Acommontechniqueusedbydevelopersistofilterfor
&{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.
Table21.2CharacterRepresentation
CodethathandlesURLscanbevulnerable.Reviewyourcodetoseeifitisvulnerabletothefollowingcommonattacks:
Whilenotareplacementforcheckingthatinputiswell-formedandcorrect,youshouldcheckthatHtmlEncodeisusedtoencodeHTMLoutputthatincludesanytypeofinput.AlsocheckthatUrlEncodeisusedtoencodeURLstrings.Inputdatacancomefromquerystrings,formfields,cookies,HTTPheaders,andinputreadfromadatabase,particularlyifthedatabaseissharedbyotherapplications.Byencodingthedata,youpreventthebrowserfromtreatingtheHTMLasexecutablescript.
Tohelppreventattackersusingcanonicalizationandmulti-byteescapesequencestotrickyourinputvalidationroutines,checkthatthecharacterencodingissetcorrectlytolimitthewayinwhichinputcanberepresented.
CheckthattheapplicationWeb.configfilehassettherequestEncodingandresponseEncodingattributesconfiguredbythe
Webapplicationsthatarebuiltusingthe.NETFrameworkversion1.1orlaterperforminputfilteringtoeliminatepotentiallymaliciousinput,suchasembeddedscript.Donotrelyonthis,butuseitfordefenseindepth.Checkthe
InternetExplorer6SP1supportsanewHttpOnlycookieattributethatpreventsclient-sidescriptfromaccessingthecookiefromthedocument.cookieproperty.Instead,anemptystringisreturned.ThecookieisstillsenttotheserverwhenevertheuserbrowsestoaWebsiteinthecurrentdomain.Formoreinformation,seethe"Cross-SiteScripting"sectioninChapter10,"BuildingSecureASP.NETPagesandControls."
InternetExplorer6andlatersupportsanewsecurityattributeontheand
Ifyoucreateapagewithuntrustedinput,verifythatyouusetheinnerTextpropertyinsteadofinnerHTML.TheinnerTextpropertyrenderscontentsafeandensuresthatscriptisnotexecuted.
FormoreinformationaboutXSS,seethefollowingarticles:
YourcodeisvulnerabletoSQLinjectionattackswhereveritusesinputparameterstoconstructSQLstatements.AswithXSSbugs,SQLinjectionattacksarecausedbyplacingtoomuchtrustinuserinputandnotvalidatingthattheinputiscorrectandwell-formed.
ThefollowingprocesshelpsyoulocateSQLinjectionvulnerabilities:
FormoreinformationaboutSQLinjection,seethefollowingarticle:
Whenyoureviewcodeforbufferoverflows,focusyourrevieweffortsonyourcodethatcallsunmanagedcodethroughtheP/InvokeorCOMinteroplayers.Managedcodeitselfissignificantlylesssusceptibletobufferoverflowsbecausearrayboundsareautomaticallycheckedwheneveranarrayisaccessed.AssoonasyoucallaWin32DLLoraCOMobject,youshouldinspecttheAPIcallsclosely.
Thefollowingprocesshelpsyoutolocatebufferoverflowvulnerabilities:
Ifyourmanagedcodeusesexplicitcodeaccesssecurityfeatures,see"CodeAccessSecurity"laterinthischapterforadditionalreviewpoints.Thefollowingreviewquestionshelpyoutoidentifymanagedcodevulnerabilities:
Anassemblyisonlyassecureastheclassesandothertypesitcontains.Thefollowingquestionshelpyoutoreviewthesecurityofyourclassdesigns:
Multithreadedcodeispronetosubtletiming-relatedbugsorraceconditionsthatcanresultinsecurityvulnerabilities.Tolocatemultithreadedcode,searchsourcecodeforthetext"Thread"toidentifywherenewThreadobjectsarecreated,asshowninthefollowingcodefragment:
Threadt=newThread(newThreadStart(someObject.SomeThreadStartMethod));Thefollowingreviewquestionshelpyoutoidentifypotentialthreadingvulnerabilities:
ClassesthatsupportserializationareeithermarkedwiththeSerializableAttributeorderivefromISerializable.Tolocateclassesthatsupportserialization,performatextsearchforthe"Serializable"string.Then,reviewyourcodeforthefollowingissues:
Tohelplocatecodethatusesreflection,searchfor"System.Reflection"—thisisthenamespacethatcontainsthereflectiontypes.Ifyoudousereflection,reviewthefollowingquestionstohelpidentifypotentialvulnerabilities:
Secureexceptionhandlingisrequiredforrobustcode,toensurethatsufficientexceptiondetailsareloggedtoaidproblemdiagnosisandtohelppreventinternalsystemdetailsbeingrevealedtotheclient.Reviewthefollowingquestionstohelpidentifypotentialexceptionhandlingvulnerabilities:
Ifso,checkthatyourcodedoesnotimplementitsowncryptographicroutines.Instead,codeshouldusetheSystem.Security.CryptographynamespaceoruseWin32encryptionsuchasDataProtectionApplicationProgrammingInterface(DPAPI).Reviewthefollowingquestionstohelpidentifypotentialcryptographyrelatedvulnerabilities:
Ifyourassemblystoressecrets,reviewthedesigntocheckthatitisabsolutelynecessarytostorethesecret.Ifyouhavetostoreasecret,reviewthefollowingquestionstodosoassecurelyaspossible:
Anycodecanassociateamethodwithadelegate.Thisincludespotentiallymaliciouscoderunningatalowertrustlevelthanyourcode.
Allmanagedcodeissubjecttocodeaccesssecuritypermissiondemands.Manyoftheissuesareonlyapparentwhenyourcodeisusedinapartialtrustenvironment,wheneitheryourcodeorthecallingcodeisnotgrantedfulltrustbycodeaccesssecuritypolicy.
Usethefollowingreviewpointstocheckthatyouareusingcodeaccesssecurityappropriatelyandsafely:
Ifyourcodesupportspartial-trustcallers,ithasevengreaterpotentialtobeattackedandasaresultitisparticularlyimportanttoperformextensiveandthoroughcodereviews.Reviewthe
Thefollowingquestionshelpyoutoidentifypotentiallyvulnerableareas:
Youcanusecodeaccesssecurityidentitydemandstolimitaccesstopublictypesandmembers.Thisisausefulwayofreducingtheattacksurfaceofyourassembly.
DeclarativesecurityattributescanbedisplayedwithtoolssuchasPermview.exe.Thisgreatlyhelpstheconsumersandadministratorsofyourassembliestounderstandthesecurityrequirementsofyourcode.
ScanyourcodeforAssertcalls.ThismayturnupinstancesofDebug.Assert.LookforwhereyourcodecallsAssertonaCodeAccessPermissionobject.Whenyouassertacodeaccesspermission,youshort-circuitthecodeaccesssecuritypermissiondemandstackwalk,whichisariskypractice.WhatstepsdoesyourcodetaketoensurethatmaliciouscallersdonottakeadvantageoftheassertiontoaccessasecuredresourceorprivilegedoperationReviewthefollowingquestions:
Yourcodeisalwayssubjecttopermissiondemandchecksfromthe.NETFrameworkclasslibrary,butifyourcodeusesexplicitpermissiondemands,checkthatthisisdoneappropriately.Searchyourcodeforthe".Demand"stringtoidentitydeclarativeandimperativepermissiondemands,andthenreviewthefollowingquestions:
Linkdemands,unlikeregulardemands,onlychecktheimmediatecaller.Theydonotperformafullstackwalk,andasaresult,codethatuseslinkdemandsissubjecttoluringattacks.ForinformationonLuringAttacks,see"LinkDemands"inChapter8,"CodeAccessSecurityinPractice."
Searchyourcodeforthe".LinkDemand"stringtoidentifywherelinkdemandsareused.Theycanonlybeuseddeclaratively.Anexampleisshowninthefollowingcodefragment:
[StrongNameIdentityPermission(SecurityAction.LinkDemand,PublicKey="00240000048...97e85d098615")]publicstaticvoidSomeOperation(){}Formoreinformationabouttheissuesraisedinthissection,see"LinkDemands"inChapter8,"CodeAccessSecurityinPractice."Thefollowingquestionshelpyoutoreviewtheuseoflinkdemandsinyourcode:
Checkthatthefollowingpermissiontypesareonlygrantedtohighlytrustedcode.Mostofthemdonothavetheirowndedicatedpermissiontype,butusethegenericSecurityPermissiontype.Youshouldcloselyscrutinizecodethatusesthesetypestoensurethattheriskisminimized.Also,youmusthaveaverygoodreasontousethesepermissions.
Table21.3DangerousPermissions
UseVisualStudio.NETtochecktheprojectpropertiestoseewhetherAllowUnsafeCodeBlocksissettotrue.Thissetsthe/unsafecompilerflag,whichtellsthecompilerthatthecodecontainsunsafeblocksandrequeststhataminimumSkipVerificationpermissionisplacedintheassembly.
Ifyoucompiledwith/unsafe,reviewwhyyouneedtodoso.Ifthereasonislegitimate,takeextracaretoreviewthesourcecodeforpotentialvulnerabilities.
Givespecialattentiontocodethatcallsunmanagedcode,includingWin32DLLsandCOMobjects,duetotheincreasedsecurityrisk.Unmanagedcodeisnotverifiablytypesafeandintroducesthepotentialforbufferoverflows.Resourceaccessfromunmanagedcodeisnotsubjecttocodeaccesssecuritychecks.Thisistheresponsibilityofthemanagedwrapperclass.
Usethefollowingreviewquestionstovalidateyouruseofunmanagedcode:
Ifyouletanexceptionpropagatebeyondtheapplicationboundary,ASP.NETcanreturndetailedinformationtothecaller.Thisincludesfullstacktracesandotherinformationthatisusefultoanattacker.Checkthe
BesuretoreviewyourWebpagesforXSSvulnerabilities.Formoreinformation,see"Cross-SiteScripting(XSS)"earlierinthischapter.
CheckthatyourcodevalidatesinputfieldspassedbyURLquerystringsandinputfieldsextractedfromcookies.Tolocatevulnerablecodesearchforthefollowingtextstrings:
Checkthatinputisvalidatedfortype,range,format,andlengthusingtypedobjects,andregularexpressionsasyouwouldforformfields(seetheprevioussection,"DoYouValidateFormFieldInput").AlsoconsiderHTMLorURLencodinganyoutputderivedfromuserinput,asthiswillnegateanyinvalidconstructsthatcouldleadtoXSSbugs.
Ifyourapplicationusesviewstate,isittamperproofReviewthefollowingquestions:
Formoreinformationaboutsecuringviewstate,seethefollowingarticle:
Theglobal.asaxfilecontainseventhandlingcodeforapplication-leveleventsgeneratedbyASP.NETandbyHTTPmodules.Reviewthefollowingeventhandlerstoensurethatthecodedoesnotcontainvulnerabilities:
Reviewthefollowingquestionstoverifyyourauthorizationapproach:
IfyourWebserviceexposesrestrictedoperationsordata,checkthattheserviceauthenticatescallers.YoucanuseplatformauthenticationmechanismssuchasNTLM,Kerberos,BasicauthenticationorClientX.509Certificates,oryoucanpassauthenticationtokensinSOAPheaders.
Ifyoupassauthenticationtokens,youcanusetheWebServicesEnhancements(WSE)touseSOAPheadersinawaythatconformstotheemergingWS-Securitystandard.
Chooseappropriateauthorizationschemesprovidedbyeither.NETFramework(suchasURLauthorization,Fileauthorization,.NETRoles)orplatformoptionssuchasFileACLs.
ThetrustlevelofthecodeaccesssecuritypolicydeterminesthetypeofresourcetheWebservicecanaccess.Checkthe
UsefeaturesprovidedbyWebServiceEnhancements(WSE)insteadofcreatingyourownauthenticationschemes.
CheckthatallpubliclyexposedWebmethodsvalidatetheirinputparametersiftheinputisreceivedfromsourcesoutsidethecurrenttrustboundary,beforeusingthemorpassingthemtoadownstreamcomponentordatabase.
IfyouusecustomSOAPheadersinyourapplication,checkthattheinformationisnottamperedorreplayed.Digitallysigntheheaderinformationtoensurethatithasnotbeentampered.YoucanusetheWSEtohelpsignWebservicemessagesinastandardmanner.
CheckthatSoapExceptionandSoapHeaderExceptionobjectsareusedtohandleerrorsgracefullyandtoprovideminimalrequiredinformationtotheclient.Verifythatexceptionsareloggedappropriatelyfortroubleshootingpurposes.
CheckthatyouuseassemblylevelmetadatatodefineEnterpriseServicessecuritysettings.Usetheassemblyinfo.csfileanduseattributestodefineauthenticationandauthorizationconfiguration.Thishelpstoensurethatthesettingsareestablishedcorrectlyatadministrationtime.Althoughtheadministratorcanoverridethesesettings,itprovidestheadministratorwithacleardefinitionofhowyouexpectthesettingstobeconfigured.
CheckthatyourcodespecifiesanauthenticationlevelusingtheApplicationAccessControlattribute.Searchforthe"AuthenticationOption"stringtolocatetherelevantattribute.Checkthatyouuseatleastcall-levelauthenticationtoensurethateachcalltoyourcomponentisauthenticated.
[assembly:ApplicationAccessControl(Authentication=AuthenticationOption.Call)]DoYouUseaRestrictedImpersonationLevelTheimpersonationlevelyoudefineforyourservicedcomponentsdeterminestheimpersonationcapabilitiesofanyremoteserverthatyoucommunicatewith.Searchforthe"ImpersonationLevel"stringtocheckthatyourcodesetsthelevel.
[assembly:ApplicationAccessControl(ImpersonationLevel=ImpersonationLevelOption.Identify)]Checkthatyousetthemostrestrictedlevelnecessaryfortheremoteserver.Forexample,iftheserverneedstoidentifyyouforauthenticationpurposes,butdoesnotneedtoimpersonateyou,usetheidentifylevelasshownabove.Usedelegation-levelimpersonationwithcautiononWindows2000becausethereisnolimittothenumberoftimesthatyoursecuritycontextcanbepassedfromcomputertocomputer.WindowsServer2003introducesconstraineddelegation.
NoteInWindowsServer2003andWindows****2000ServicePack4andlater,theimpersonationprivilegeisnotgrantedtoallusers.
Ifyourcomponentsareinaserverapplication,theassemblylevelattributeshownabovecontrolstheinitialconfigurationforthecomponentwhenitisregisteredwithEnterpriseServices.
Ifyourcomponentsareinalibraryapplication,theclientprocessdeterminestheimpersonationlevel.IftheclientisanASP.NETWebapplication,checkthecomImpersonationLevelsettingonthe
Checkthatyourcodeusesrole-basedsecuritycorrectlytopreventunauthorizedaccessbyreviewingthefollowingquestions:
Searchyourcodefor"ConstructionEnabled"tolocateclassesthatuseobjectconstructionstrings.
[ConstructionEnabled(Default="")]publicclassYourServicedComponent:ServicedComponent,ISomeInterfaceIfyouuseobjectconstructorstrings,reviewthefollowingquestions:
Youshouldauditacrossthetiersofyourdistributedapplication.Checkthatyourservicecomponentslogoperationsandtransactions.TheoriginalcalleridentityisavailablethroughtheSecurityCallContextobject.Thisisonlyavailableifthesecuritylevelforyourapplicationisconfiguredforprocessandcomponent-levelchecksbyusingthefollowingattribute:
IfyouusetheTcpChannelandyourcomponentAPIacceptscustomobjectparameters,orifcustomobjectsarepassedthroughthecallcontext,yourcodehastwosecurityvulnerabilities.
Topreventcustomobjectsbeingpassedtoyourremotecomponenteitherbyreferenceorbyvalue,settheTypeFilterLevelpropertyonyourserver-sideformatterchannelsinktoTypeFilterLevel.Low.
Tolocateobjectsthatarepassedinthecallcontext,searchforthe"ILogicalThreadAffinative"string.Onlyobjectsthatimplementthisinterfacecanbepassedinthecallcontext.
Ifyouusecustomauthentication,doyourelyonprincipalobjectspassedfromtheclientThisispotentiallydangerousbecausemaliciouscodecouldcreateaprincipalobjectthatcontainsextendedrolestoelevateprivileges.Ifyouusethisapproach,checkthatyouonlyuseitwithout-of-bandmechanismssuchasIPSecpoliciesthatrestricttheclientcomputersthatcanconnecttoyourcomponent.
Reviewhowyourclientcodeconfigurescredentialsontheremotingproxy.Ifexplicitcredentialsareused,wherearethosecredentialsmaintainedTheyshouldbeencryptedandstoredinasecurelocationsuchasarestrictedregistrykey.Theyshouldnotbehard-codedinplaintext.Ideally,yourclientcodeshouldusetheclientprocesstokenandusedefaultcredentials.
CheckthatyourcodepreventsSQLinjectionattacksbyvalidatinginput,usingleastprivilegedaccountstoconnecttothedatabase,andusingparameterizedstoredproceduresorparameterizedSQLcommands.Formoreinformation,see"SQLInjection"earlierinthischapter.
ByusingWindowsauthentication,youdonotpasscredentialsacrossthenetworktothedatabaseserver,andyourconnectionstringsdonotcontainusernamesandpasswords.WindowsauthenticationconnectionstringseitheruseTrusted_Connection='Yes'orIntegratedSecurity='SSPI'asshowninthefollowingexamples.
"server='YourServer';database='YourDatabase'Trusted_Connection='Yes'""server='YourServer';database='YourDatabase'IntegratedSecurity='SSPI'"DoYouSecureDatabaseConnectionStringsReviewyourcodeforthecorrectandsecureuseofdatabaseconnectionstrings.Thesestringsshouldnotbehardcodedorstoredinplaintextinconfigurationfiles,particularlyiftheconnectionstringsincludeusernamesandpasswords.
Searchforthe"Connection"stringtolocateinstancesofADO.NETconnectionobjectsandreviewhowtheConnectionStringpropertyisset.
Ifyouhavewrittenadataaccessclasslibrary,howdoyoupreventunauthorizedcodefromaccessingyourlibrarytoaccessthedatabaseOneapproachistouseStrongNameIdentityPermissiondemandstorestrictthecallingcodetoonlythatcodethathasbeensignedwithspecificstrongnameprivatekeys.
NoteIn.Net2.0StrongNameIdentityPermissiononlyworksforpartialtrustcallers.Anydemandincludinglinkdemandwillalwayssucceedforfulltrustcallersregardlessofthestrongnameofthecallingcode.
Ifyoustoresensitivedata,suchascreditcardnumbers,inthedatabase,howdoyousecurethedataYoushouldcheckthatitisencryptedbyusingastrongsymmetricencryptionalgorithmsuchas3DES.
Ifyouusethisapproach,howdoyousecurethe3DESencryptionkeyYourcodeshoulduseDPAPItoencryptthe3DESencryptionkeyandstoretheencryptedkeyinarestrictedlocationsuchastheregistry.
Checkthatalldataaccesscodeisplacedinsidetry/catchblocksandthatthecodehandlestheSqlExceptions,OleDbExceptionsorOdbcExceptions,dependingontheADO.NETdataproviderthatyouuse.
Checkthatyourcodeisnotvulnerabletoleavingopendatabaseconnectionsif,forexample,exceptionsoccur.CheckthatthecodeclosesconnectionsinsideafinallyblockorthattheconnectionobjectisconstructedinsideaC#usingstatementasshownbelow.Thisautomaticallyensuresthatitisclosed.
using((SqlConnectionconn=newSqlConnection(connString))){conn.Open();//Connectionwillbeclosedifanexceptionisgeneratedorifcontrolflow//leavesthescopeoftheusingstatementnormally.}SummarySecuritycodereviewsaresimilartoregularcodereviewsorinspectionsexceptthatthefocusisontheidentificationofcodingflawsthatcanleadtosecurityvulnerabilities.Theaddedbenefitisthattheeliminationofsecurityflawsoftenmakesyourcodemorerobust.
ThischapterhasshownyouhowtoreviewmanagedcodefortopsecurityissuesincludingXSS,SQLinjection,andbufferoverflows.Ithasalsoshownyouhowtoidentifyothermoresubtleflawsthatcanleadtosecurityvulnerabilitiesandsuccessfulattacks.
Securitycodereviewsarenotapanacea.However,theycanbeveryeffectiveandshouldfeatureasaregularmilestoneinthedevelopmentlifecycle.