HPFortifyStaticCodeAnalyzer SoftwareVersion4.21 HPFortifyStaticCodeAnalyzerCustomRulesGuide DocumentReleaseDate:October2014 SoftwareReleaseDate:October2014 Legal Notices Warranty TheonlywarrantiesforHPproductsandservicesaresetforthintheexpresswarrantystatements accompanyingsuchproductsandservices.Nothinghereinshouldbeconstruedasconstitutinganadditional warranty.HPshallnotbeliablefortechnicaloreditorialerrorsoromissionscontainedherein. Theinformationcontainedhereinissubjecttochangewithoutnotice. Restricted Rights Legend Confidentialcomputersoftware.ValidlicensefromHPrequiredforpossession,useorcopying.Consistentwith FAR12.211and12.212,CommercialComputerSoftware,ComputerSoftwareDocumentation,andTechnical DataforCommercialItemsarelicensedtotheU.S.Governmentundervendor'sstandardcommerciallicense. Copyright Notice ©Copyright2014Hewlett‐PackardDevelopmentCompany,L.P. Documentation Updates Thetitlepageofthisdocumentcontainsthefollowingidentifyinginformation: • SoftwareVersionnumber • DocumentReleaseDate,whichchangeseachtimethedocumentisupdated • SoftwareReleaseDate,whichindicatesthereleasedateofthisversionofthesoftware Tocheckforrecentupdatesortoverifythatyouareusingthemostrecenteditionofadocument,goto: http://h20230.www2.hp.com/selfsolve/manuals ThissiterequiresthatyouregisterforanHPPassportandsignin.ToregisterforanHPPassportID,goto: http://h20229.www2.hp.com/passport‐registration.html Youwillalsoreceiveupdatedorneweditionsifyousubscribetotheappropriateproductsupportservice. ContactyourHPsalesrepresentativefordetails. PartNumber:1‐143‐2014‐10‐421‐01 Contents Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .vi ContactingHPFortifySoftware........................................................................ vi TechnicalSupport ................................................................................. vi CorporateHeadquarters........................................................................... vi Website ........................................................................................... vi AbouttheSoftwareSecurityCenterDocumentationSet ................................................vi Chapter 1: Introduction..............................................................................8 IntendedAudience ..................................................................................... 8 DocumentStructure ................................................................................ 8 RelatedDocuments ..................................................................................... 9 Chapter 2: CustomRulesOverview.................................................................. 10 HPFortifySecureCodingRulepacks .................................................................. 10 CustomRules......................................................................................... 10 CustomRulesandUserRoles ..................................................................... 11 RulepacksandCommonRuleElements............................................................... 12 Rulepacks ........................................................................................ 12 CommonRuleElements.......................................................................... 13 CustomDescriptions ................................................................................. 16 AddingCustomDescriptionstoHPFortifyRules.................................................. 16 AddingHPFortifyDescriptionstoCustomRules.................................................. 17 Chapter 3: DataflowAnalyzerandCustomRules ..................................................... 18 UnderstandingDataflowAnalyzerandCustomRules .................................................. 18 DataflowAnalyzerandCustomRulesConcepts........................................................ 19 TaintSource ..................................................................................... 19 TaintEntrypoint ................................................................................. 19 TaintSink ........................................................................................ 19 TaintPassthrough................................................................................ 20 TaintCleanse..................................................................................... 20 TaintFlags....................................................................................... 20 TaintPath........................................................................................ 21 XMLRepresentationofDataflowRules ........................................................... 22 CustomDataflowRuleScenarios ...................................................................... 26 ScenarioOverview............................................................................... 26 PathManipulationScenario ...................................................................... 26 SourceCode...................................................................................... 27 Rules............................................................................................. 27 SQLInjectionandAccessControlScenario ........................................................ 29 SourceCode...................................................................................... 29 Rules............................................................................................. 31 Contents iii PersistentCross‐siteScripting .................................................................... 35 CommandInjectionScenario..................................................................... 39 Chapter 4: CustomStructuralRules ................................................................. 43 UnderstandingStructuralAnalyzerandCustomRules ................................................. 43 StructuralTree ................................................................................... 43 StructuralTreeQueryLanguage .................................................................. 44 StructuralTreeExamples ............................................................................. 44 Example1........................................................................................ 44 Example2........................................................................................ 45 Example3........................................................................................ 46 Example4........................................................................................ 47 XMLRepresentationofStructuralRules............................................................... 48 StructuralCustomRuleScenarios ..................................................................... 48 ScenarioOverview............................................................................... 49 LeftoverDebugScenario ......................................................................... 49 DangerousFunctionCallsScenario ............................................................... 50 OverlyBroadCatchBlocks........................................................................ 52 PasswordinCommentsScenario ................................................................. 54 PoorLoggingPracticeScenario ................................................................... 55 EmptyCatchBlockScenario...................................................................... 56 Chapter 5: CustomControlFlowRules ............................................................... 58 UnderstandingControlFlowAnalyzerandCustomRules .............................................. 58 ControlFlowAnalyzerandCustomRuleConcepts..................................................... 60 RulePattern...................................................................................... 60 RuleVariable..................................................................................... 60 RuleBinding..................................................................................... 60 XMLRepresentationofControlFlowRules............................................................ 61 Definition........................................................................................ 61 FunctionIdentifiers.............................................................................. 61 FunctionCallIdentifiers .......................................................................... 61 Limits ............................................................................................ 61 PrimaryState .................................................................................... 62 CustomControlFlowRuleScenarios .................................................................. 63 ScenarioOverview............................................................................... 63 ResourceLeakScenario .......................................................................... 63 NullPointerCheckScenario...................................................................... 68 Chapter 6: CustomContentandConfigurationRules ................................................. 72 UnderstandingContentAnalyzerandCustomRules ................................................... 72 UnderstandingConfigurationAnalyzerandCustomRules ............................................. 72 XMLRepresentationofContentRules ................................................................. 72 XMLRepresentationofConfigurationRules ........................................................... 73 Contents iv CustomContentandConfigurationRuleScenarios .................................................... 74 CustomRuleScenarioOverview.................................................................. 74 PropertyFileScenario............................................................................ 75 SourceCode...................................................................................... 75 Rules............................................................................................. 75 TomcatFileScenario............................................................................. 76 Chapter 7: StructuralRulesLanguageReference..................................................... 78 SyntaxandGrammar................................................................................. 78 Types............................................................................................ 78 ReferenceResolution............................................................................. 80 NullResolutions.................................................................................. 81 Relations......................................................................................... 81 ResultsReporting................................................................................ 82 Call‐GraphReachability .......................................................................... 83 Chapter 8: ControlFlowRuleReference............................................................. 85 ControlFlowSyntaxandGrammar.................................................................... 85 UnderstandingControlFlowRules.................................................................... 86 ControlFlowRuleIdentifiers ..................................................................... 86 ControlFlowRuleFormat........................................................................ 86 Declarations ..................................................................................... 86 Transitions....................................................................................... 87 FunctionCalls .................................................................................... 88 Contents v Preface Thisguidedescribeshowtousecustomrulestoresolvesecurityissuesinyourcode. Contacting HP Fortify Software Ifyouhavequestionsorcommentsaboutanypartofthisguide,contactHPFortifyat: Technical Support 650.735.2215 [email protected] Corporate Headquarters MoffettTowers 1140EnterpriseWay Sunnyvale,CA94089 650.358.5600 [email protected] Website http://www.hpenterprisesecurity.com About the HP Fortify Software Security Center Documentation Set TheHPFortifySoftwareSecurityCenterdocumentationsetcontainsinstallation,user,anddeploymentguides forallHPFortifySoftwareSecurityCenterproductsandcomponents.Inaddition,youwillfindtechnicalnotes andreleasenotesthatdescribenewfeatures,knownissues,andlast‐minuteupdates.Youcanaccessthelatest versionsofthesedocumentsfromthefollowingsources: • YoucanaccessalldocumentsinPDFfileformatontheHPESPusercommunityProtect724website (https://protect724.hp.com/welcome).Youwillneedtoregisterforanaccount. • YoucanaccessalldocumentsinPDFfileformatandinstallationguidesandusersguidesinHTMLformat ontheHPSoftwareProductManualssite(http://support.openview.hp.com/selfsolve/manuals).To register,gotohttp://h20229.www2.hp.com/passport‐registration.html. Preface vi Change Log ThefollowingtabletrackschangesmadetotheHPFortifyStaticCodeAnalyzerCustomRulesGuide. Software Release‐version Date Change 3.90‐01 4/5/2013 Addedbluecolortocustomruletagsthroughoutguide. 4.10‐01 3/22/2014 Updatedto4.10release. 4.20‐01 9/9/2014 Updatedto4.20release. 4.21‐01 10/17/2014 Updatedreleaseinformation. Change Log vii Chapter 1: Introduction ThisdocumentprovidestheinformationthatyouneedtocreatecustomrulesforHPFortifyStaticCode Analyzer.Thisincludesbothconceptualcontentthatfocusesoncustomizingtopicsaswellasanumberof examplesthatapplyrule‐writingconceptstoreal‐worldproblems Intended Audience Thisdocumentisintendedforpeoplewhoareexperiencedwithbothsecurityandprogramming.Someofthe contentinthisguidemightbedifficulttounderstandwithoutprogrammingexperience. Document Structure Thisdocumentisstructuredtofacilitatethefollowing: • LearningaboutHPFortifyStaticCodeAnalyzerandcustomrules—ThesechaptersdescribehowSCAworks withspecificanalyzers.Thisincludescustomrulescenariosforeachanalyzertype. Chaptersare: • DataflowAnalyzerandCustomRules—ThischapterdescribeshowtheDataflowAnalyzerworkswith SCAtodiscovervulnerabilitiesincode.Thischapterincludescustomdataflowscenariosthatshowhow toresolvereal‐worldproblemsusingcustomdataflowrules. • • CustomStructuralRules—ThischapterdescribeshowtheStructuralAnalyzerworkswithSCAto discovervulnerabilitiesincode.Thischapterincludescustomstructuralscenariosthatshowhowto resolvereal‐worldproblemsusingcustomstructuralrules. • CustomControlFlowRules—ThischapterdescribeshowtheControlflowAnalyzerworkswithSCAto discovervulnerabilitiesincode.Thischapterincludescustomcontrolflowscenariosthatshowhowto resolvereal‐worldproblemsusingcustomcontrolflowrules. • CustomContentandConfigurationRules—ThischapterdescribeshowthecontentandConfiguration AnalyzersworkwithSCAtodiscovervulnerabilitiesincode.Thischapterincludescontentand configurationscenariosthatshowhowtoresolvereal‐worldproblemsusingcustomcontentand configurationrules. Usingreferencecontenttowritecustomrules—Thesechaptersandotherresourcesprovidethecontent thatyouneedtobuildcustomrulesforSCA. Chaptersandotherresourcesare: • ControlFlowRuleReference—Thischapterprovidessyntaxandgrammarforcontrolflowrules.Usethis chapterasareferencewhenwritingcustomcontrolflowrules. • StructuralRulesLanguageReference—Thischapterprovidessyntaxandgrammarforstructuralrules. Usethischapterasareferencewhenwritingcustomstructuralrules. • HPFortifyXMLSchema—ThisHTMLcontentprovidestheHPFortifyXMLschema,including:valid attributesandelements,childandparentrelationshipsbetweenelements,whetheranelementisempty orcanincludetext,elementdatatypes,aswellaselementandattributedefaultandfixedvalues. • TheHPFortifyXMLSchemaisavailablefromtheHPFortifyCustomerPortal.Itwasalsoincludedinthe zipfilefromwhichyouextractedthisdocument. HPFortifyStructuralTypeandPropertiesReference—ThisHTMLcontentprovidestypeandproperties referenceforstructuralrules.Usethiscontentwhencreatingcustomstructuralrules. TheHPFortifyStructuralTypeandPropertiesReferenceisavailablefromtheHPFortifyCustomerPortal. Itwasalsoincludedinthezipfilefromwhichyouextractedthisdocument. Chapter 1: Introduction 8 Related Documents ThefollowingdocumentsprovideadditionalinformationaboutHPFortifyStaticCodeAnalyzer: • HPFortifyStaticCodeAnalyzerInstallationandConfigurationGuide ThisdocumentprovidesinstallationandconfigurationinstructionsforSCA. • HPFortifyStaticCodeAnalyzerUserGuide Thisdocumentprovidesinstructionsonusingtheanalyzerstoidentifyvulnerabilitiesinyourcode. • HPFortifyStaticCodeAnalyzerUtilitiesUserGuide Thisdocumentprovidesinformationonthecommand‐linetoolsthatprovideadditionalmanagementand accesstothefunctionsprovidedbySCA. • HPFortifyStaticCodeAnalyzerPerformanceGuide Thisdocumentdescribestheissuesinvolvedwhentryingtoselecthardwaretoscancertaincodebases, providesguidelinesformakingthosedecisions,andofferstipsforoptimizingmemoryusage and performance. Chapter 1: Introduction 9 Chapter 2: Custom Rules Overview Thischapterprovidesthefollowingtopics: • HPFortifySecureCodingRulepacks—UsethissectiontolearnaboutHPFortifySecureCodingRulepacks. • CustomRules—Usethissectiontolearnaboutusingcustomrules. • CommonRuleElements—Usethissectiontolearnabouttheelementsthatarecommontodifferenttypeof rules. • CustomDescriptions—Usethissectiontolearnhowtocreatecustomdescriptions. HP Fortify Secure Coding Rulepacks HPFortifyStaticCodeAnalyzerusesaknowledgebaseofrulestomodelimportantattributesoftheprogram underanalysis.Theserulesprovidemeaningtorelevantdatavaluesandenforcesecurecodingstandards applicabletothecodebase.TheSecureCodingRulepacksdescribegeneralsecurecodingidiomsforpopular languagesandpublicAPIs,outofthebox.CustomrulesareavailableforJavaand.NETcode,butdonotcurrently supportJavaScript,PHP,ClassicASP,VisualBasic,orCobol. AlthoughHPFortifyprovidesawiderangeofrules,itispossiblethatyourprojectsleverageunsupportedthird‐ partyAPIs,includeorganization‐specificlibraries,orfallunderthepurviewofproprietarysecure‐coding guidelines.Inthiscase,HPFortifyprovidestheabilitytocreatecustomrulesthatsuityourneeds. Customrulescangreatlyimprovethecompletenessandaccuracyoftheanalysisperformedbyastaticanalysis tool.Theydothisbymodelingthebehaviorofthesecurity‐relevantlibraries,describingproprietarybusiness andinputvalidation,andenforcingorganizationandindustry‐specificcodingstandards. Custom Rules YoucanextendthefunctionalityofSCAandtheSecureCodingRulepacksbywritingcustomrules.Forexample, youmightneedtoenforceproprietarysecurityguidelinesoranalyzeaprojectthatusesthird‐partylibrariesor otherpre‐compiledbinariesthatarenotalreadycoveredbytheSecureCodingRulepacks. Ifaprojectusesresourcesforwhichsourcecodeisnotavailableatanalysistime,analysisoftheprojectwill succeed,butmightbeincompleteuntilyouwritethecustomrulesthatprovideSCAwithsecurityknowledge abouttheseresources. Towriteeffectivecustomrules,itisimportanttobecomefamiliarwithknownsecurityvulnerabilitycategories andthecodeconstructswithwhichtheyareoftenrelated.Developinganunderstandingofthetypesof functionsthatoftenappearinparticulartypesofvulnerabilitiesfacilitatestheprocessoftargetingsecurity‐ relevantfunctionsforcustomrulewriting.Becausethetaskofdeterminingthesecurityrelevanceofafunction canbechallenging,timespentlearningabouttherelationshipsbetweentypesoffunctionsandvulnerability categorieswillproveuseful. Youmustexaminetheindividualbehaviorofeachsecurity‐relevantfunction,eitherbyreviewingsourcecode orwiththehelpofAPIdocumentation,todeterminethecorrecttypeofruletorepresentthespecificbehavior andvulnerabilitycategoryassociatedwitheachofthefunctions. Fromhere,youcandevelopsmalltestcasesthatexemplifytheundesirablebehavioryouwantyourrulesto identify.Conversely,testcasesdesignedtoreflectcorrectbehaviorthatshouldnotbeflaggedwillalsohelpyou eliminatefalsepositivesfromtherulesyoucreate.Onceyouaresatisfiedyourrulesperformcorrectlyinthis controlledenvironment,thenextstepistousethemtoperformananalysisonabroadrangeofprojectsto ensurethattheybehavewiththeexpectedleveloffidelity. Tosimplifytheprocessofcreatingcustomrules,HPFortifyAuditWorkbenchincludesaCustomRulesEditor thatcanbelaunchedfromAuditWorkbenchorbyrunningtheCustomRulesEditorscriptorcommandfromthe Chapter 2: Custom Rules Overview 10 bindirectorywhereyouinstalledyourHPFortifysoftware.Formoreinformation,seetheHPFortifyAudit WorkbenchUserGuide. Custom Rules and User Roles Userrolesalsoplayanimportantpartincreatingandusingcustomrules.Forexample,anindividualauditor mightrequiredifferentcustomrulesthanasecurityteam.Therestofthissectiondescribescommonuserroles andidentifiescustomrulesspecifictothatrole. Individual Auditor Anindividualauditorperformsasinglesecurityreviewofaprojectforaspecificorganization.Asecurity researcherlookingforbugsinapieceofpublicsoftwarealsofitsintothisrole.Thegoalofthisuseristoidentify specificvulnerabilitiesbasedonanarrowsetofsecuritycriteria. Apersoninthisroledevelopsandusescustomrulesalonganarrowsetofparametersanddoesnotstrivefor breadthofcoverage.Anexampleofthisisaddressingthestrategicshortcomingofthebuilt‐inknowledgebaseof rules. ThisincludesidentifyingspecificclassesofbugsormodelingthebehaviorofAPIsthatarelikelytoleadto vulnerabilitiestargetedinthecurrentaudit. Inthiscase,customizationisatoolintheauditor'sbelt.Developingalargebodyofcustomrulesisnota requirementforthisuser.Anyeffortthatthisindividualputsintocustomizationshouldbeweighedagainstthe benefitthatthecustomizationwillprovide. Central Security Team Acentralsecurityteamistypicallyresponsiblefordevelopingcustomrulesthatidentifyabroadsetof vulnerabilitiesacrossmultiplecodebaseswithinanorganization.Thecentralsecurityteamprovidesvalueby developinglargedatabasesofrulesthatimprovethestaticanalysisresultsduringongoingaudits. Ifthecentralsecurityteamisresponsibleforauditingtheresultsproducedbythecustomrules,thenitcanbe appropriatetoincluderulesthatprovideanauditorachecklistofpropertiestoverifyduringtheaudit. However,iftheresultsofthestaticanalysistoolarerevieweddirectlybythedevelopmentteamresponsiblefor eachprojectrespectively,thenthetoleranceforissuesthatdonotcorresponddirectlytosecurity vulnerabilitiesorotherprogrammingbugswillinvariablybemuchlower. Ineithercase,itisdesirabletoproducealargeknowledgebaseofcustomrulesrelevanttoprojectsunder analysis,sincetherulewritersareincentivizedtoimproveanalysisresultsduringongoingaudits. Development Team Ifadevelopmentteamisresponsibleforbothimplementingcustomrulesandauditingtheresultsofthestatic analysistool,theextenttowhichyouwanttocustomizevariesbasedonthesecurityexperienceofthe developmentteam.Ifthedevelopmentteamisontangentiallyinvolvedinsecurity,theiruseofcustomruleswill mostlikelyfocusonanarrowfieldofrelevantbugs.Inthiscase,theywillnotinvestinalargebodyofcustom rules. Chapter 2: Custom Rules Overview 11 Rulepacks and Common Rule Elements SCAcomprisesmultipleanalyzersthatperformdifferenttypesofanalysisandfinddifferenttypesofproblems incode.Eachanalyzersupportsoneormoredistinctruletype. Thisdocumentcoverstheseruletypes: • Dataflow • Structural • Configuration • Controlflow Thefollowingruletypesareoutsidethescopeofthisdocument: • CharacterizationRule • DeprecationRule • GlobalFieldRule • InputSetRule • InternalRule • NonReturningRule • StatisticalRule • SuppressionRule Rulepacks ARulepackcomprisesoneormorerulesofanarbitrarytype.SecureCodingRulepacksarerepresentedinXML. EachRulepackmusthaveaRulepackdefinitionthatincludesavarietyofheaderinformationthatdescribesthat Rulepack. Listing1showsanexampleRulepackdefinitionthatdoesnotcontainanyrules. Listing 1: Secure Coding Rulepacks Definition without Rules <RulePack> <RulePackID>06A6CC97-8C3F-4E73-9093-3E74C64A2AAF</RulePackID> <Name><![CDATA[Sample Custom Fortify Rulepack]]></Name> <Version>0000.0.0.0000</Version> <Language>java</Language> <Description><![CDATA[Custom Rules for Java]]></Description> <Rules version="3.28"> <RuleDefinitions> <!--... rules definitions go here ...--> </RuleDefinitions> </Rules> ... </RulePack> Table1showsseveraloftheXMLelementsintroducedintheRulepackdefinitionshowninListing1. Table 1: XML Elements Element Description <RulePackID> AuniqueidentifierfortheRulepack,whichcanbeanarbitrary string.ByconventionHPFortifyusesagloballyuniqueidentifier (GUID)generatortodefineRulepackandruleidentifierstoensure thatbothreceiveuniqueidentifiers. Chapter 2: Custom Rules Overview 12 Table 1: XML Elements (Continued) Element Description <Name> Human‐readablenamefortheRulepack. <Language> TheprogramminglanguagetowhichtheRulepackapplies. <Version> Arbitrarynumericversionusedtorelatemultipleversionsofthe sameRulepack(RulepackswiththesameRulepackidentifier). <Description> Human‐readabledescriptionoftheRulepack. <RuleDefinitions> Oneormoreruledefinitions. Theremainderofthissectionenumeratesseveralcommonelementssharedbetweenmultipleruletypes. Common Rule Elements SCArulesshareafewuniversalelementsthatgoverntheiruse. Table2showstheseelements. Table 2: Universal Rule Elements Element/Attributes Language <RuleID> Uniqueidentifierfortherule,whichcanbecomposedofan arbitrarystringofcharacters.AswithRulepackIDs,by conventionHPFortifyusesagloballyuniqueidentifier(GUID) generatortodefineRulepackanduniqueruleidentifiers. language Theprogramminglanguagetowhichtheruleapplies.The languageattributeispartofthetop‐levelruledefinition. formatVersion TheminimumversionoftheSCARuleEnginewithwhichthe ruleiscompatible.TheformatVersionattributeispartof thetop‐levelruledefinition. Someruleattributesarecommontoonlythoserulesthatdirectlycausetherespectiveanalyzertoreportan issue. Table3showstheruleattributescommontovulnerability‐producingrules. Table 3: Vulnerability Producing Rules Common Elements Element Description <VulnCategory> Vulnerabilitycategoryassociatedwithrulesthatgenerateissues. <VulnKingdom> (Optional)Vulnerabilitykingdomassociatedwithrulesthat generateissues. <VulnSubcategory> (Optional)Vulnerabilitysub‐categoryassociatedwithrulesthat generateissues. <Description> Human‐readabledescriptionofthevulnerabilityidentifiedbythe rule.Descriptionelementscancontainanyof<Abstract>, <Explanation>, <Recommendations>, <References> and<Tips>. Chapter 2: Custom Rules Overview 13 Rulesthatrefertofunctionormethodcalls(asopposedtoconfigurationfiles,propertyfiles,HTML,andother content)canuseacommonrepresentationcalledafunctionidentifier(<FunctionIdentifier>). Table4showstheelementsofafunctionidentifier. Table 4: Function Identifier Elements Element Description <FunctionName> Thenameofthemethodorfunctionthattherulematches. Function,class,andnamespacenamesareeitherexpressedwith a<Value>element,whichcausesSCAtointerpretthemasa standardstring,ora<Pattern>element,whichcausesSCAto interpretthemasaJavaregularexpression. <ClassName> (Optional)Thenameoftheclassthattherulematches.See <FunctionName>. <NamespaceName> (Optional)Thenameofthepackageornamespacethattherule matches.See<FunctionName>. <ApplyTo> (Optional)Controlshowtherulematchesagainstclassesthat extendthespecifiedclassorimplementthespecifiedinterface. Thiselementcontainsthefollowingattributes: • implements:trueindicatesthattheruleshouldmatch methodsthatimplementtheinterfacespecifiedbythe rule. • overrides:trueindicatesthattheruleshouldmatch methodsdefinedinsub‐classesthatoverridethe methodspecifiedbytherule. • extends:trueindicatesthattheruleshouldmatch methodsinclassesthatextendtheclassspecifiedby therule. Ifleftunspecified,allthreeattributesofthe<ApplyTo>element defaulttofalse. Functionidentifierscanalsooptionallyincludeelementsthatfurtherrestrictthemethodstherulewillmatch. The<Parameters>elementrestrictsthemethodsruleswillmatchtothosedeclaredwiththeformal parametersspecifiedbythe<ParamType>elementsitcontains. Table5showsadescriptionoftheparameterelements. Table 5: Elements used to specify parameters in a function identifier Elements Descriptions <ParamType> (Optional)Specifiesasingleparameterusingthenative‐ languagetype,suchasintforanintegerinCorjava.lang.String forastringinJava. <WildCard> (Optional)Representsavariablenumberofarbitrarily‐typed parametersattheendparameterlistforthemethod.Themin attributespecifiesthefewestnumberofwildcardparameters allowedbytherule,whilethemaxattributespecifiesthe maximumnumberofwildcardparametersallowedbytherule. Chapter 2: Custom Rules Overview 14 Likethe<Parameters>element,the<Modifiers>elementcontainsanarbitrarynumberof<Modifier> elements,whichrestrictthemethodstherulewillmatchtothosewithdeclaredwiththespecifiedmodifiers.HP Fortifysupportsthefollowingmodifiers: • native • private • protected • public • static Manyruletypesallowmatchingtobefurtherrestrictedthroughtheuseofaconditionalexpression (<Conditional>).Functionidentifiersspecifywhichfunctionsormethodsareinterestingtotherule. Conditionalexpressionsrestrictwhichcallstothosefunctionsareactuallymatchedbytherule.Conditional expressionscanbewrittentoexamineconstantvaluesusedinmethodcallsandthetypesofmethodarguments (asdistinctfromthedeclaredformalparametertypesofthemethod).Fordataflowsinks,conditional expressionscanalsoexaminetaintflags. Table6describesthebasicelementsthatcanappearinaconditionalexpression. Table 6: Conditional Types Element Description <Or>, Booleanlogicoperatorsthatcombineapplythecorresponding logicaloperationtothenodestheycontain. <And>, <Not> <IsConstant> Trueiftheargumentspecifiedbythezero‐indexedargument attributeisacompile‐timeconstantornot. <ConstantEq> Trueiftheargumentspecifiedbythezero‐indexedargument attributeisacompile‐timeconstantthatmatchesthevalue specifiedbythevalueattribute. <ConstantGt> Trueiftheargumentspecifiedbythezero‐indexedargument attributeisacompile‐timeconstantthatisstrictlygreaterthan thevaluespecifiedbythevalueattribute. <ConstantLt> Trueiftheargumentspecifiedbythezero‐indexedargument attributeisacompile‐timeconstantthatisstrictlylessthanthe valuespecifiedbythevalueattribute. <TaintFlagSet> Truefortaintpathswhichincludethetaintflagspecifiedbythe taintFlagattribute.Thiselementisonlyvalidfordataflowsink rules. <IsType> Trueiftheargumentspecifiedbythezero‐indexedargument attributematchesthe<NamespaceName>,<ClassName>,and <FunctionName>elementsspecifiedinsidethe<IsType> element. Chapter 2: Custom Rules Overview 15 Custom Descriptions SomeorganizationswanttoeitheraddcustomdescriptionstoHPFortifyrulesoraddHPFortifydescriptionsto customrules.Customdescriptionsenableyoutoaddorganization‐specificcontenttoissuesproducedbytheHP FortifySecureCodingRulepacks.Customdescriptioncontentcanincludeorganization‐specificsecurecoding guidelines,bestpractices,referencestointernaldocumentationandsoon.AddingHPFortifydescriptionsto customrulesenablesyoutoleveragedescriptionscreatedbyHPFortifyincustomrulesthatidentifycategories ofvulnerabilitiesalreadyreportedbytheSecureCodingRulepacks. • AddingCustomDescriptionstoHPFortifyRules • AddingHPFortifyDescriptionstoCustomRules Adding Custom Descriptions to HP Fortify Rules Youaddcustomdescriptionswiththenew<CustomDescriptionRule>element.Eachcustomdescriptionrule definesnewdescriptioncontentandspecifiesasetofHPFortifyrulestowhichitshouldbeapplied. ToaddcustomdescriptionstoHPFortifyrules,dothefollowing: • DefineCustomDescriptionContent—usethe<Description>elementofthecustomdescriptionruleto definethecustomdescriptioncontent. • IdentifyRulestoModify—usethe<RuleMatch>elementtoidentifytherulestowhichSCAwilladdthe customdescriptioncontent. Define Custom Description Content The<Description>elementofthecustomdescriptionrulehasthesamestructureasastandardrule description,with<Abstract>,<Explanation>,<Recommendations>,<Tips>,and<References>children. Thecustomdescriptioncanspecifyallorasubsetoftheseelements.Thecustomdescriptioncanuseallofthe sameconstructsasastandarddescription,includingreferencestootherelementsusingtheref/idmechanism. Customdescriptiondefinitionscannotcontainanother<CustomDescription>tag. Identify Rules to Modify Acustomdescriptioncancontainseveralrulematches.Eachrulematchspecifiesrulesbasedonany combinationofcategory,subcategory,ruleidentifier,anddescriptionidentifier.InorderforSCAtoapplya customdescriptiontoissuesproducedbyarule,therulemustmatchallcriteriaspecifiedintherulematch. Forexample,arulematchthatspecifies<Category>Buffer Overflow</Category> and <Subcategory>Format String</Subcategory>willmatchonlyBufferOverflow:Obsoleteissues.The customdescriptioncontentwillnotbeappliedtoissuesinotherBufferOverflowsubcategories,suchasBuffer Overflow:Off‐by‐One. Aruleneedonlysatisfyoneormorerulematchesforacustomdescriptionrule.Forexample,acustom descriptionrulewitharulematchfor<Category>Buffer Overflow</Category>andanotherdistinctrule matchfor<Subcategory>Format String</Subcategory>,willmatchanyissuesintheBufferOverflow categoryortheFormatStringsubcategory. Chapter 2: Custom Rules Overview 16 Custom Description Example ThecustomdescriptionruleshowninListing2addsacustom<Abstract>and<Explanation>forSQL InjectionandAccessControl:Databaseissues. Listing 2: Abstract and Explanation for SQL Injection and Access Control: Database rules <CustomDescriptionRule formatVersion="3.15"> <RuleID>D40B319C-F9D6-424F-9D62-BB1FA3B3C644</RuleID> <RuleMatch> <Category> <Value>SQL Injection</Value> </Category> </RuleMatch> <RuleMatch> <Category> <Value>Access Control</Value> </Category> <Subcategory> <Value>Database</Value> </Subcategory> </RuleMatch> <Description> <Abstract>[custom abstract text]</Abstract> <Explanation>[custom explanation text]</Explanation> </Description> </CustomDescriptionRule> CustomdescriptionelementsalsohavearuleIDattributethatreferstothecustomdescriptionrule(nottothe matchedrule,aswiththeclassIDattributeof<Description>). Adding HP Fortify Descriptions to Custom Rules YoucanuseHPFortifydescriptionstodescribeissuesfoundbycustomrules.TouseanHPFortifydescriptionin acustomrule,youmustfirstdeterminetheidentifierforthedescriptionyouwanttouse.Descriptionidentifiers areavailableonhttp://vulncat.fortify.com.Onceyouhavelocatedtheidentifierforthedescriptionyouwantto use,setthe"ref"attributeofthecustomruletotheidentifieroftheHPFortifydescription. Forexample,theruleshowninListing3willproduceSQLInjectionresultswiththesamedescriptionasSQL InjectionresultsfromHPFortifyrulesforJava: Listing 3: HP Fortify Description SQL Injection Output Example <DataflowSinkRule language="java" formatVersion="3.9"> […] <Description ref="desc.dataflow.java.sql_injection"/> […] </DataflowSinkRule> Inordertousethisfeature,descriptionIDsmustbeuniqueacrossallRulepacks. Chapter 2: Custom Rules Overview 17 Chapter 3: Dataflow Analyzer and Custom Rules Thischapterprovidesthefollowingtopics: • UnderstandingDataflowAnalyzerandCustomRules—usethissectiontolearnabouttheDataflowAnalyzer andthewaythatitusescustomrulestofinddataflow‐relatedsecurityissues. • DataflowAnalyzerandCustomRulesConcepts—usethissectiontolearnaboutDataflowAnalyzerrulesand concepts. • XMLRepresentationofDataflowRules—usethissectiontolearnwhichdataflowrulesareavailable. • CustomDataflowRuleScenarios—usethissectiontolearnhowtocreatecustomdataflowrules. Understanding Dataflow Analyzer and Custom Rules TheSCADataflowAnalyzerenablesSCAtofindsecurityissuesthatinvolvetainteddataenteringaprogram fromonepoint(thetaintsource)andflowingthroughtoanotherpoint(thetaintsink).Ataintsinkisapointin thecodewheretheuseofun‐validatedinputisinherentlydangerous. ThisanalysisenablesSCAtopreciselyidentifymanydifferenttypesofsecurityproblems.Acommonexampleis anSQLinjection.InanSQLinjectionthetainteddataacquiredfromthetaintsource(suchasanHTTPrequest parameter)iseventuallyusedbytheprogramtoconstructanSQLquery(ataintsink).Inthiscase,theDataflow AnalyzerreportsaSQLinjectionissue. BecausetheDataflowAnalyzerperformsinter‐proceduralanalysis,itiscapableoftrackingtainteddataacross methodcallsandthroughglobalvariablesintheprogram. TheDataflowAnalyzeroperatesonamodeloftheprogram.SCAconstructsthismodelfromprogramsource codeandrules.Theprogramsourcecodeprovidesthebaselayerforthemodel.Thislayerdescribesthe behaviorofmethods,therelationshipsbetweendifferentmethods,andtherelationshipbetweenmethodsand globalvariables.SCAthenaugmentsthemodelwithrules.Theserulesdescribethepointsintheprogramthat actastaintsourcesandsinks.Theyalsodescribeprogrampointsthatcanmanipulateortransfertainteddata. Listing4showsasimpleprogramthatillustratesacommandinjectionvulnerability. ThecallreadFromNetwork()readsthetaintedinputintothebuffer.Theanalyzerthenconcatenatesitwitha stringliteraltoformcommandandpassedtotheexecute()function,whichexecutesanewprocessspecified bythecommandstring. Listing 4: Command Injection Vulnerability function run() { readFromNetwork(buffer); command = concatenate("/usr/bin" buffer); execute(command); } Bybuildingamodelfromthesourcecode,theDataflowAnalyzerisabletounderstandthatthreeexternal functionsarecalledfromrun()andthatthereisadataflowrelationshipbetweenthosecallsthroughlocal variables. Becausethesourcecodeforthosefunctionsisnotpartoftheprogram,themodelisincompletewithoutasetof ruleswhichdescribetherelevantcharacteristicsofthosefunctions.Withoutanyknowledgeoftheexternal functions,theDataflowAnalyzerdoesn'tunderstandhowtainteddataentersandmovesthroughtheprogram. Chapter 3: Dataflow Analyzer and Custom Rules 18 Inthiscase,theDataflowAnalyzercandetectthevulnerabilitywiththefollowingrules: • ATaintSourceruleforreadFromNetwork() • ATaintPass‐throughruleforconcatenate() • ATaintSinkruleforexecute() Dataflow Analyzer and Custom Rules Concepts Thissectionprovidesinformationondataflowcoreconcepts.Theseconceptsmapdirectiontorulesthatyoucan writetoinformtheDataflowAnalyzer’smodelingofthecode.Thissectionalsoprovidesmoreadvanced conceptsthatillustratehowtheDataflowAnalyzerperformsinagivensituation. Conceptsare: • TaintSource • TaintEntrypoint • TaintSink • TaintPassthrough • TaintFlagBehavior • ValidationFunctions Taint Source Tainteddataentersaprogramthroughaprogrampointcalledataintsource.Commonexamplesinclude: • AfunctionthatreadsdatafromnetworksourcessuchasanHTTPrequest • Afunctionthatreadsdatafromanuntrusteddatasources(adatabasewrittentobyotherprograms). Taint Entrypoint Ataintentrypointisspecialtypeoftaintsourcethatdescribesafunctionwhichisinvokedwithtaintedinputby theenvironmentorframework.Commonexamplesinclude: • Themainfunctionoftheprogram,calledwiththeargumentsspecifiedinthecommandstring • Afunctioninawebapplicationframework,calleddirectlybytheframeworkwithaninputparameter Taint Sink Taintsinksareprogrampointstowhichtainteddatamustnotflow.WhentheDataflowAnalyzerdetectsapath throughwhichtainteddatacanflowfromsourcetosink,itreportsanissue.Ataintsinkrulecancontaina conditionalexpressionwhichlimitspathsreportedtoataintsinkbyexaminingtaintflags. Commonexamplesinclude: • AfunctionthattakesaSQLstringandexecutesaqueryagainstadatabaseconnection • Afunctionthattakesastringandexecutesthecommanddescribedbythestring Chapter 3: Dataflow Analyzer and Custom Rules 19 Taint Passthrough TheDataflowAnalyzerautomaticallyderivespassthroughbehaviorsforfunctionsdefinedinthesourcecode. Externallydefinedfunctionswithpassthroughbehavior(suchasintheJDKlibrary),mustbemodeledwitha rule. Forexample,defaultHPFortifySecureCodingRulepackscontainarulethatdescribesthepass‐through behaviorofStringBuilder.append(). Apass‐throughrulemightaddorremovetaintflagsfromthetainteddata. Taint Cleanse Ataintcleanseisapointatwhichtaintisremovedormodified.Typicallythisisavalidationfunction. Therearetwotypesoftaintcleansepoints: Completecleanse—arulethatdescribesataintcleansewhichdoesnotspecifytaintflagstobeaddedor removed.TheDataflowAnalyzerwillstoptaintpropagationcompletelyatthispoint. Partialcleanse—arulethatspecifiestaintflagstobeaddedorremoved.Inthisinstancethedataisstilltainted, butthetaintflagsetischanged. Cleanserulesarealwaysthelastappliedatanypointintheprogram.Ifafunctioncallismatchedbyacleanse rule,thecleanseruleappliestotheendofanytaintpaththatgoesthroughthatfunction.Itwillcomeafterany passthroughorsourcerulesthatmatchedthesamefunctioncall. Inmanycases,itisimpossibletodescribeafunctioneitherintermsofapassthroughoracleanserule.Seethe noteonwritingrulesforvalidationfunctionsinthischapterforadiscussionofthedifferencesbetween passthroughrulesandpartialcleanserules. Taint Flags AtaintflagisanattributeoftainteddatathatenablestheDataflowAnalyzertodiscriminatebetweendifferent typesoftaint.ThisisimportantbecauseitenablestheDataflowAnalyzertoaccuratelyidentifyissues. Forexample,theinputfrombothHTTPparametersandlocalconfigurationfilesofawebapplicationmightbe tainted.Theattackvectorsineachinstancearesubstantiallydifferent.AnattackercaneasilymanipulateHTTP parameters.Manipulatingconfigurationfilesonthesystemismuchmoredifficult. ConsiderafunctionwhichchecksinputforSQLmetacharacters.Oncetainteddatahaspassedthroughthis function,itshouldbesafetouseinataintsinkforSQLinjection.However,thedatacannotbeconsidered untainted.Itisstilldangeroustouseinothercontexts,suchasataintsinkforcommandinjection.Theuseof taintflagsinrulesenablestheDataflowAnalyzertodeterminewhetherthetainteddataissafeinaspecific context. Eachtaintpaththroughtheprogramcarriesasetoftaintflags.TheDataflowAnalyzercanaddorremovetaint flagsthatoriginatedatthetaintsourcepointastaintpassesthroughpass‐throughandcleansepointsinthe program.Ataintsinkcancheckforthepresenceorabsenceoftaintflagswhichdeterminewhetherthe DataflowAnalyzerwillreportaparticularpathfromsourcetosink. Taint Flag Types SCAprovidesthreetypesoftaintflags.Thesetaintflagtypeshelptosimplifywritingconditionalexpressionsfor taintsinks. General—Thisisthedefaulttaintflagtype. Neutral—Thesetaintflagsrepresent“informational”content.Neutraltaintflagsaremostoftenusedtonotethat aspecificvulnerabilitycategoryhasbeenvalidated.Neutraltaintflagsareusefulinfilteringoutfalsepositives. Chapter 3: Dataflow Analyzer and Custom Rules 20 Specific—Thesetaintflagsarecreatedbyincludingadeclarationwhichdescribesthecategoryoftaintflaginthe Rulepack. Taintflagtypingprovidesaneasywaytointroducenewtypesoftaintintothesystemwithoutproducing unexpectedresults.Specifictaintflagsenablearulewritertocreateapairingofsourceandsinkrules.Insucha pairing,taintfromthepairedsourcerulewillnotinteractwithothersinks.Likewise,anytaintfromother sourcesintheprogramcannotinteractwiththepairedsink. Forexample: ConsideraprogramthatusestheAPIsgetSecret()andshareData().InthisexamplegetSecret()returns secretdata,theoutputofwhichshouldnevergetpassedtoshareData().Youcanwritearulethatpreventsthis bydescribinggetSecret()asataintsourceandshareData()asataintsink. Thisworksfineifthesearetheonlyrulesusedtoanalyzetheprogram.However,ifyouusethedefaultSecure CodingRulepackstoscantheprogram,SCAmightreportunintendedissues.Forexample,SCAmightreport inputfromHTTPparametersreachingshareData(),orinputfromgetSecret()beingusedinaSQLquery, eventhoughtheseusagesaresafe. Inorderfortheserulestoworkmoreprecisely,youcanintroduceanewtaintflag(SECRET)tothesourceand sinkrules.ThesourcerulewouldaddtheSECRETtaintflag,andthesinkrulewouldcheckforthepresenceof theSECRETtaintflag. Thissolveshalfoftheproblem;thesinkatshareData()onlyreportsinputfromgetSecret()andnotfrom othersources.However,inputfromgetSecret()mightunintentionallytriggerthereportingofissuesatother sinks,becausethosesinkswillnotexplicitlycheckagainsttheabsenceofthenewSECRETtaintflag.Thisis whereSpecifictaintflagscomeintoplay.BydeclaringtheSECRETTaintFlagasSpecific,wepreventthattaint fromthegetSecret()sourcefrominteractingwithexistingsinksinunintendedways.Sinkswhichdonot explicitlycheckfortheSpecificTaintFlagsSECRETwillignorethetaintfromgetSecret(). Taint Flag Behavior Understandingtheexactbehaviorofsinksinthepresenceofdifferenttypesoftaintcanbechallenging.The followingdefinitionisprovidedasanadvancedconcept. Foranysinkthatdoesnotexplicitlycheckforthepresenceorabsenceofanyspecifictaintflaginthetaintflag set,SCAwillautomaticallyaddacheckwhichensuresthatthetaintflagsetisnotspecific,wherethetaintflag setisconsideredtobespecificifitcontainsoneormorespecifictaintflagsanddoesnotcontainanygeneral taintflags. Taint Path TheDataflowAnalyzerreportsavulnerabilitywhenitfindsoneormoretaintpathsbetweenasourceandasink intheprogram. Ataintpathcontainsasequenceofmethodcalls,stores(assignmentvariablesorfields)andloads(readsfrom variablesorfields).Itdenotesapathalongwhichtainteddataispropagatedfromataintsourcepointtoataint sinkpoint.Infact,sinceaprogrammaycontainloopsorrecursion,theremaybeaninfinitenumberofpaths. ThoughtheDataflowAnalyzercannotconsideralltaintpathsformasourcetoasink,itwillconsideratleast oneforeachuniquesetofpossibletaintflagsfromasourcetoasink.ThisguaranteesthattheDataflow Analyzerwillconsiderthispathwhentaintflowsfromsourcetosinkalongtwopaths,onlyoneofwhich performsvalidation. Chapter 3: Dataflow Analyzer and Custom Rules 21 Validation Functions Oneofthemostbasicrule‐writingtasksforSCAistowriterulesforvalidationfunctions.Youcandothisby eitherbywritingapass‐throughorcleanserule.Whichruleisappropriatedependsonthecircumstances. Incaseswherethefunctioncompletelyvalidatestheinputforallcases,acompletecleanserule(whichwill removealltaint)isappropriate. Inmostcases,itispreferabletoaddataintflagtothetaintpathindicatingthatacertaintypeofvalidationwas performed. Ifthefunctionispartofanexternallibraryandit'ssourceisnotincludedinthescan,youshouldwriteapass‐ throughwiththeappropriatetaintflagmodifications.Thepass‐throughruleneedstodescribetotheDataflow Analyzerthattainteddatadoesflowthroughthefunction,butthatvalidationisperformedintheprocess. Ifthefunctionispartofthesourcecodebeingscanned,acleanseruleismoreappropriate.BecausetheDataflow Analyzeralreadyderivedthepass‐throughbehaviorofthefunctionbylookingatitscode,youonlyneedto describethetaintflagsthattheanalyzeraddsorremoves. Youshoulddothiswithacleanserule,becausetheanalyzerwillapplythecleanseruletothetaintpathafterthe derivedpass‐through.Apass‐throughruleisappliedinparallel,creatingaseparatetaintpathandwouldnot havethedesiredeffect. XML Representation of Dataflow Rules ThissectiondescribestheXMLrepresentationofthefollowingdataflowrules: • DataflowSourceRule • DataflowPassthroughRule • DataflowEntrypointRule • DataflowCleanseRule Dataflow Source Rule Usedataflowsourcerulestoidentifypointsatwhichtainteddataentersaprogram. Listing5showsadataflowsourcerulethatidentifiestheJavamethodServletRequest.getParameter()asa sourceoftainteddata. Listing 5: Dataflow Source Rule Java Method <DataflowSourceRule language="java" formatVersion="3.8"> <RuleID>D312DFA3-EF02-46A5-A25B-29D218E96EF1</RuleID> <FunctionIdentifier> <NamespaceName> <Pattern>javax\.servlet</Pattern> </NamespaceName> <ClassName> <Pattern>ServletRequest</Pattern> </ClassName> <FunctionName> <Pattern>getParameter</Pattern> </FunctionName> <ApplyTo implements="true" overrides="true" extends="true"> </FunctionIdentifier> <OutArguments>return</OutArguments> <TaintFlags>+WEB,+XSS</TaintFlags> </DataflowSourceRule> Chapter 3: Dataflow Analyzer and Custom Rules 22 Table7describestheXMLelementsintroducedinthedataflowsinkruleshowninListing5. Table 7: Dataflow Sink Rule XML Elements Element Description <InArguments> Determineswhichofthemethod'sparametersmustnotreceive taint.Iftaintreachesoneoftheseparameters,SCAwillreportan issue. Parametersarespecifiedasacomma‐delimitedlistofeitherthe returnkeyword,thiskeyword,orthezero‐basedindexofthetarget parameter. <TaintFlags> (Optional)Specifiesthetaintflagstoassociatewithtaintintroduced bythemethodmatchedbytherule. TaintFlagsarespecifiedasacomma‐delimitedlist,andmusthavea plus(+)orminus(‐)prefixtoindicateiftheyshouldbeaddedtoor removedfromthetaintpath.Onlytheplusprefixisvalidinsource andentrypointrules. Dataflow Sink Rule Usedataflowsinkrulestoidentifypointsinaprogramthattainteddatamustnotreach. Listing6showsadataflowsinkrulethatindicatestaintmustnotreachtheStatement.executeQuery() method. Listing 6: Dataflow Sink Rule for Statement.executeQuery() <DataflowSinkRule language="java" formatVersion="3.8"> <RuleID>9B5F0161-88EC-4104-B70B-0182FEB53BF2</RuleID> <VulnCategory>SQL Injection</VulnCategory> <DefaultSeverity>4.0</DefaultSeverity> <Sink> <InArguments>0</InArguments> </Sink> <FunctionIdentifier> <NamespaceName> <Pattern>java\.sql</Pattern> </NamespaceName> <ClassName> <Pattern>Statement</Pattern> </ClassName> <FunctionName> <Pattern>executeQuery</Pattern> </FunctionName> <ApplyTo overrides="true" overrides="true" extends="true"/> </FunctionIdentifier> </DataflowSinkRule> Table8describestheXMLelementsintroducedinthedataflowsinkruleshowninListing6 Table 8: XML Elements for sink rule Element Description <InArguments> Determineswhichofthemethod'sparametersmustnot receivetaint.Iftaintreachesoneoftheseparameters,SCA reportsanissue.Parametersarespecifiedasacomma‐ delimitedlistofeitherthereturnkeyword,thethiskeyword, orthezero‐basedindexofthetargetparameter. Chapter 3: Dataflow Analyzer and Custom Rules 23 Dataflow Passthrough Rule Usedataflowpassthroughrulestodescribehowfunctionsandmethodspropagatetaintfromtheirinputto output. Listing7showsadataflowpassthroughrulethatindicatesthattaintonthestringonwhichthetrim()method iscalledisalsoreturnedfromthemethod. Listing 7: Dataflow Passthrough Rule for String.trim() <DataflowPassthroughRule language="java" formatVersion="3.8"> <RuleID>BCF67129-1C61-4ACA-9425-0F32E4A6D496</RuleID> <FunctionIdentifier> <NamespaceName> <Pattern>java\.lang</Pattern> </NamespaceName> <ClassName> <Pattern>String</Pattern> </ClassName> <FunctionName> <Pattern>trim</Pattern> </FunctionName> </FunctionIdentifier> <InArguments>this</InArguments> <OutArguments>return</OutArguments> <DataflowPassthroughRule> ThedataflowpassthroughruleshowninListing7combinestheconceptsof<InArguments> and <OutArguments>tomaptaintenteringthemethodononeparametertotaintexitingthemethodonanother parameter.Ifapassthroughruleincludestaintflags,whichtheexampleabovedoesnot,thosetaintflagswill eitherbeadded(flagsprependedwitha+)orremoved(tagsprependedwitha -)fromtheparameterspecified bythe<OutArguments>element. Dataflow Entrypoint Rule Usedataflowentrypointrulestodescribeprogrampointsthatintroducetainteddatatoaprogram.Entrypoint rulesdothisbydescribingthefunctionsandmethodsthattheprogramcaninvoke(eitherexternallyorthrough aninternalframeworkorothermechanismforwhichthesourcecodeisnotincludedintheanalysis). Listing8showsadataflowentrypointrulethatindicatesthearrayofstringspassedasthefirstparametertothe javamain()methodistainted. Chapter 3: Dataflow Analyzer and Custom Rules 24 Listing 8: Dataflow Entrypoint for Java main() Method <DataflowEntryPointRule formatVersion="3.8" language="java"> <RuleID>F0B4AD7A-22C9-4C6A-B665-FCE9FD033A69</RuleID> <TaintFlags>+ARGS</TaintFlags> <FunctionIdentifier> <NamespaceName> <Pattern>.*</Pattern> </NamespaceName> <ClassName> <Pattern>.*</Pattern> </ClassName> <FunctionName> <Pattern>main</Pattern> </FunctionName> <Parameters> <ParamType>java.lang.String[]</ParamType> </Parameters> <ApplyTo implements="true" overrides="true" extends="true"/> <Modifiers><Modifier>static</Modifier></Modifiers> </FunctionIdentifier> <InArguments>0</InArguments> </DataflowEntryPointRule> ThedataflowentrypointruleinListing8usesthe<InArguments>elementtodefinewhichparametersshould beconsideredtaintedwhenanalyzingthebodyofthespecifiedmethod. Dataflow Cleanse Rule Usedataflowcleanserulestodescribevalidationlogicandotheractionsthatrendertainteddataeitherpartially orcompletelycleansed. Listing9showsadataflowcleanserulethatshowshowthedeclareSafe()methodcleansesvaluesthatpass throughit. Listing 9: Dataflow Cleanse Rule for declareSafe() <DataflowCleanseRule formatVersion="3.8" language="java"> <RuleID>EA569241-6645-4C57-8E7B-FA4A955AE225</RuleID> <FunctionIdentifier> <NamespaceName> <Pattern>com\.fortify\.dev</Pattern> </NamespaceName> <ClassName> <Pattern>Security</Pattern> </ClassName> <FunctionName> <Pattern>declareSafe</Pattern> </FunctionName> <ApplyTo implements="true" overrides="true" extends="true"/> </FunctionIdentifier> <OutArguments>0</OutArguments> </DataflowCleanseRule> ThedataflowcleanseruleinListing9usesthe<OutArguments> elementtospecifywhichparametersshould beconsideredcleansedafteracalltothespecifiedmethod.Ifacleanseruleincludestaintflags,whichthe exampleabovedoesnot,thenthosetaintflagswilleitherbeadded(flagsprependedwitha+)orremoved(tags prependedwitha-)fromtheparameterspecifiedbythe<OutArguments>element. Chapter 3: Dataflow Analyzer and Custom Rules 25 Custom Dataflow Rule Scenarios Thissectionprovidesexamplesofcustomdataflowrules.Usetheseexamplesasthebasisforwritingcustom rules.Matchyourrequirementwithoneoftheexamples,andtailortherulestosuityoursoftware. Thissectionprovidesthefollowing: • ScenarioOverview • PathManipulationScenario • SQLInjectionandAccessControlScenario • PersistentCross‐siteScripting Scenario Overview ThescenariosinthissectionarewrittenagainstasampleapplicationcalledRichesWealthOnline(RWO).This applicationenablesuserstoperformthefollowingonlinebankingoperations: • Transferringmoney • Viewingaccountstatements • Receivingmessagesfromthebank TheRWOapplicationdemonstratesthediverserangeofapplicationsecurityvulnerabilitiesthataretypically encounteredinreal‐worldapplicationsthatprovidefunctionalitysimilartoRWO.Theapplicationisbuiltwith JavaScript,Struts2,Hibernate2,andJavaEnterpriseEdition. EachscenariohighlightsspecificvulnerabilitiesinRWOanddemonstrateshowtoidentifythemusingcustom rules. ThescenariodoesthisbyshowinghowanattackercanexploitvulnerabilitiesinRWOsourcecode.The scenario,whereapplicable,willhighlighthowSCAandtheSecureCodingRulepacksdetectthevulnerability. Thescenariothenexplainsthetypeofcustomrulesnecessarytodetectthevulnerabilityandshowsyouhowto createthem. YoucanthenreproducetheresultsbyanalyzingRWOwitheithertheSecureCodingRulepacksorbyusingthe providedcustomrules.Inordertousetheprovidedcustomerrules,youmustfirstdisabletheSecureCoding Rulepacks Path Manipulation Scenario ThisscenariohighlightstherulesnecessaryfortheSCADataflowAnalyzertodetectpathmanipulation vulnerabilities.Thescenariodemonstrateshowanattackercanexploitapathmanipulationvulnerability.Itthen showshowtheDataflowAnalyzerusessource,sinkandpassthroughrulestoidentifyapathmanipulation vulnerability. Thisscenariohighlightsthefollowingvulnerability: • Pathmanipulation—thistypeofvulnerabilityenablesanattackerinputtocontrolthepathsusedin filesystemoperations.Anattackercanexploitthistypeofvulnerabilitytoaccessormodifyotherwise‐ protectedsystemresources. Chapter 3: Dataflow Analyzer and Custom Rules 26 Thisscenariohighlightsthefollowinganalysisandruleconcepts: • Conditional • Constructortoken • Entrypoint • Generaltaint • Inputargument • Label • Modifier • Neutraltaint • Parametersignature • Sink Source Code Theapplicationinthisscenariocontainsapathmanipulationvulnerabilityinitsbanneradvertisementweb service.ThewebserviceenablesaffiliatestoprovideanidentifierandretrieveaJPEGimagethatcontainsan advertisement.Anattackercanenteramaliciousidentifierinthewebservicerequest,whichwillcausethe servertorespondtotherequestwiththecontentsofsensitivefiles. Listing10showscodethatretrievesbanneradsfortheaffiliates. Listing 10: Banner Retrieval Code public class BannerAdServer implements BannerAdSource { static private String baseDirectory = "/images/bannerAds/"; public File retrieveBannerAd(String clientAd) { // Retrieve banner with given guid File targetFile = new File(baseDirectory + clientAd); return targetFile; } ... } WhenanaffiliateexecutesanRMIcalltothemethodBannerAdServer.retreiveBannerAd(),theapplication returnstheimagefileassociatedwiththeaffiliateidentifierclientAd. Thecodeassumesthattheincomingaffiliateidentifierspecifiedonlyasinglefilename,butifanattacker providestheidentifier'../../../../../windows/system.ini',theserverwillretrievethefile/images/ bannerAds/../../../../../windows/system.ini.Onmostsystems,thisisequivalentto/windows/ system.ini. Rules InListing11,untrusteddataentersthroughtheJavaRMIentrypointandispassedtoafileconstructor.The analyzermodelsthatentrypointasasourceoftaintusingaDataflowEntrypointrule. Listing11showstherulethatmodelsthismethodasasourceoftaint. Chapter 3: Dataflow Analyzer and Custom Rules 27 Listing 11: Banner Retrieval Code <DataflowEntryPointRule formatVersion="3.8" language="java"> <RuleID>547ECA61-7D70-44AF-8669-A117AB78C988</RuleID> <TaintFlags>+WEBSERVICE</TaintFlags> <FunctionIdentifier> <NamespaceName> <Pattern>com\.fortify\.samples\.riches\.webservices</Pattern> </NamespaceName> <ClassName> <Pattern>BannerAdServer</Pattern> </ClassName> <FunctionName> <Pattern>retrieveBannerAd</Pattern> </FunctionName> <Modifiers> <Modifier>public</Modifier> </Modifiers> <Parameters> <ParamType>java.lang.String</ParamType> </Parameters> <ApplyTo overrides="true" </FunctionIdentifier> <InArguments>0</InArguments> </DataflowEntryPointRule> TheentrypointruleinListing11matchesthemethodBannerAdServer.retrieveBannerAd().The <Modifier>elementrestrictstheruletomatchonlypublicmethodsandthe<Parameters>elementenforces thatthemethodacceptsonlyonestringargument. Listing12describesthesinkthatmatchesthecorrespondingconstructor. Listing 12: Banner Retrieval Code <DataflowSinkRule formatVersion="3.8" language="java"> <RuleID>98558CD1-708D-48E8-8C68-F93481CB15A9</RuleID> <VulnCategory>Path Manipulation</VulnCategory> <DefaultSeverity>3.0</DefaultSeverity> <Description ref="desc.dataflow.java.path_manipulation"/> <Sink> <InArguments>0</InArguments> <Conditional> <Not> <TaintFlagSet taintFlag="VALIDATED_PATH_MANIPULATION"/> </Not> </Conditional> </Sink> <FunctionIdentifier> <NamespaceName> <Pattern>java\.io</Pattern> </NamespaceName> <ClassName> <Pattern>File</Pattern> </ClassName> <FunctionName> <Pattern>init\^</Pattern> </FunctionName> <Parameters> <ParamType>java.lang.String</ParamType> </Parameters> <ApplyTo overrides="true" </FunctionIdentifier> </DataflowSinkRule> Thesinkruleusesthespecialkeywordinit^tomatchtheFile.File()constructor.Thiskeywordisreserved forclassconstructorsandallowsrulestomatchacrossinheritancerelationships. Chapter 3: Dataflow Analyzer and Custom Rules 28 Whentaintreachesthesink,the<Conditional>elementensuresnovulnerabilityisreportediftheneutral taintflagVALIDATED_PATH_MANIPULATIONisalsopresent.Thistaintflagindicatesthatthedatahasbeen correctlyvalidatedbeforehand.Youcanwriteaseparatecleanseorpassthroughruletoaddtheneutraltaintflag VALIDATED_PATH_MANIPULATIONtodatathatpassesthroughtheappropriatevalidationmethod. SQL Injection and Access Control Scenario ThisscenariohighlightstherulesthatarenecessaryforSCA’sDataflowAnalyzertodetectaccesscontrol vulnerabilitiesintheapplication.Theexampleinthescenariofocusesonanaccesscontrolvulnerability. BecausetheanalyzerdetectsSQLinjectionvulnerabilitieswithsimilarrules,thisscenarioalsocoversSQL injectionvulnerabilitiesandcorrespondingdetectionrules. First,thescenariowalksyouthroughtheapplication’ssourcecodetoshowyouhowtoconductaSQLinjection attack.Then,thescenarioshowsyouhowtheDataflowAnalyzerusessource,sink,andpassthroughrulesto identifythistypeofvulnerability Thisscenariohighlightsthefollowingvulnerabilities: • Accesscontrol—withoutproperaccesscontrol,executinganSQLstatementcontainingauser‐controlled primarykeycanenableanattackertoviewunauthorizedrecords. • SQLInjection—constructingadynamicSQLstatementwithuserinputcanenableanattackertomodifythe meaningofastatementortoexecutearbitrarySQLcommands. Thisscenariohighlightsthefollowinganalysisandruleconcepts: • Conditionals • Fullcleansefunction • Neutraltaint • Pairedsinks • Partialcleansefunctions • Passthrough Source Code Theapplicationcontainsanaccesscontrolvulnerabilityinitstransactionservice.Theapplicationenablesusers toprovidetheiraccountidentifierandretrievetheiraccountdetails.Anattackercanenteranyuser'saccount identifierinthetransactionservicerequest,whichwillcausetheservertorespondwiththeaccountdetailsof theuser. Chapter 3: Dataflow Analyzer and Custom Rules 29 Listing13showstheJSPpagethatshowstransactiondetailsandhasanaccesscontrolvulnerability. Listing 13: JSP Page: Transaction Details; Access Control Vulnerability <% String accountNumber = request.getParameter("acctno");%> ... <% if ((accountNumber != null) && (accountNumber.length() > 0)) { Long account = Long.valueOf(accountNumber); List transactions = TransactionService.getTransactions(account); PrintWriter outputWriter = response.getWriter(); outputWriter.println("<h1>Transactions reported from database for account <i>"+accountNumber+"</i></h1>"); try { ... } %> TheJSPcallsTransactionService.getTransactions()withtheaccountnumberasanargumentto retrievetheaccountdetails.Thetransactionservicequeriesthedatabasefortheassociatedtransactions. Listing14showshowthismethodretrievestheaccounts. Listing 14: Access Control Vulnerability: Transaction Service public static List getTransactions(Long acctno) throws Exception { Session session = ConnectionFactory.getInstance().getSession(); String queryStr = "from Transaction transaction where transaction.acctno ='" + acctno + "'ORDER BY date DESC"; if (ServletActionContext.getServletContext() != null) { ServletActionContext.getServletContext().log(queryStr); } Query query = session.createQuery(queryStr); List transactions = query.list(); session.close(); return transactions; } ThemethodgeneratesadynamicSQLstatementusingtheaccountnumberreadfromarequestparameter.The codeassumesthattheaccountnumberwillonlybelongtothecurrentuser.Thecodedoesnotverifythatthe userhassufficientauthorizationtoviewthereturneddata. ThisvulnerabilitytypeiscloselyrelatedtotheSQLinjectionvulnerabilitytype.AnSQLinjectionvulnerability existswhencodeappendsanuntrustedstringwhichcancontainarbitrarycharacters.Anattackercaninput additionalSQLcodeandchangetheentiremeaningofthequery. TheexampleinListing14doesnotcontainaSQLinjectionvulnerabilitybecausetheattackvectorisaLongand canonlycontaindigits,notarbitrarycharacters. Chapter 3: Dataflow Analyzer and Custom Rules 30 Listing15showsanequivalentSQLinjectionvulnerability: Listing 15: Equivalent Code: SQL Injection Vulnerability public static List getTransactions(String acctno) throws Exception { Session session = ConnectionFactory.getInstance().getSession(); String queryStr = "from Transaction transaction where transaction.acctno ='" + acctno + "' ORDER BY date DESC"; if (ServletActionContext.getServletContext() != null) ServletActionContext.getServletContext().log(queryStr); Query query = session.createQuery(queryStr); List transactions = query.list(); session.close(); } Rules InListing13,untrusteddataenterstheapplicationthroughamethodcalltogetParameter(). Listing16showsarulethatmodelsthatcallasasourceoftainteddata. Listing 16: Source Rule: ServletRequest.getParameter() <DataflowSourceRule formatVersion="3.8" language="java"> <RuleID>120E80B3-7EA2-4A18-82F2-0F7E53E97480</RuleID> <FunctionIdentifier> <NamespaceName> <Pattern>javax\.servlet</Pattern> </NamespaceName> <ClassName> <Pattern>ServletRequest</Pattern> </ClassName> <FunctionName> <Pattern>getParameter</Pattern> </FunctionName> <ApplyTo implements="true"/> </FunctionIdentifier> <OutArguments>return</OutArguments> </DataflowSourceRule> ThesourceruleinListing16matchesthemethodServletRequest.getParameter().The<OutArguments> elementindicatesthatthereturnvalueofthemethodistainted.Thelackofa<TaintFlags> elementindicates thatthisisageneralsourceoftaint,whichdoesnotassignanytaintflags. TheJSPcodeinListing13processestheincomingaccountnumberbyconvertingitfromastringtypetoa numerictype. Chapter 3: Dataflow Analyzer and Custom Rules 31 Listing17showsthepassthroughrulethatenablestheDataflowAnalyzertofollowtaintfromthe accountNumbervariabletotheaccountvariable. Listing 17: Passthrough Rule: Track Taint through Long.valueOf() <DataflowPassthroughRule formatVersion="3.8" language="java"> <RuleID>73371DA9-10AD-4D13-823D-4BD0C9F2104F</RuleID> <TaintFlags>-XSS,+NUMBER</TaintFlags> <FunctionIdentifier> <NamespaceName> <Pattern>java\.lang</Pattern> </NamespaceName> <ClassName> <Pattern>Long</Pattern> </ClassName> <FunctionName> <Pattern>valueOf</Pattern> </FunctionName> </FunctionIdentifier> <InArguments>0</InArguments> <OutArguments>return</OutArguments> </DataflowPassthroughRule> Thepassthroughruletargetsthe Long.valueOf()method.The<InArguments>and<OutArgument> elementsspecifyhowtainteddataflowsthroughthemethod.Whencodecallsthemethodwithatainted parameter,SCAwillconsiderthereturnvaluefromthecalltobetainted.Theruleaddsaspecifictaintflag NUMBERtothereturnedvaluetoindicatetheobjectisstrictlynumericinnature.TheruleremovesanyXSS taintflagfromthereturnedvaluebecauseitcannolongerbeusedtoconductaXSSattack. Eventually,theJSPcodeinListing13executestheTransactionService.getTransactions()method,which inturnexecutestheSession.createQuery()method. Listing18showsthesinkrulethatdetectstheaccesscontrolvulnerability. ItchecksthattheVALIDATED_ACCESS_CONTROL_DATABASEtaintflagisnotpresent.Ifavalidationfunctionis laterintroducedtotheflowofdatainthesourcecode,youcanwritearuleforthevalidationfunctionthatadds theVALIDATED_ACCESS_CONTROL_DATABASEtaintflag.ThisensuresthatSCAwillnotreportavulnerability forpathswhichflowthroughthatfunction. Chapter 3: Dataflow Analyzer and Custom Rules 32 Listing 18: Access Control Vulnerability Sink Rule: Session.createQuery(). <DataflowSinkRule formatVersion="3.8" language="java"> <RuleID>2B8502DE-E54E-4C59-AFC6-B6E3BCA67B3B</RuleID> <VulnCategory>Access Control</VulnCategory> <DefaultSeverity>2.0</DefaultSeverity> <Description/> <Sink> <InArguments>0</InArguments> <Conditional> <And> <And> <TaintFlagSet taintFlag="NUMBER"/> <IsType argument="0"> <NamespaceName> <Pattern>java\.lang</Pattern> </NamespaceName> <ClassName> <Pattern>String</Pattern> </ClassName> </IsType> </And> <Not> <TaintFlagSet taintFlag="VALIDATED_ACCESS_CONTROL_DATABASE"/> </Not> </And> </Conditional> </Sink> <FunctionIdentifier> <NamespaceName> <Pattern>net\.sf\.hibernate</Pattern> </NamespaceName> <ClassName> <Pattern>Session</Pattern> </ClassName> <FunctionName> <Pattern>createQuery</Pattern> </FunctionName> <ApplyTo implements="true/> </FunctionIdentifier> </DataflowSinkRule> Often,anaccesscontrolsinkruleispairedwithaSQLinjectionrule.ThemethodSession.createQuery() containsanaccesscontrolvulnerability.YoucanconvertanaccesscontrolsinkruletoanSQLinjectionsinkrule. Chapter 3: Dataflow Analyzer and Custom Rules 33 Listing19showstheequivalentSQLinjectionsinkruletothepreviousaccesscontrolsinkrule. Listing 19: SQL Injection Sink Rule <DataflowSinkRule formatVersion="3.8" language="java"> <RuleID>AE637178-A9D2-4BE6-A7B2-EEEA293B506F</RuleID> <VulnCategory>SQL Injection</VulnCategory> <DefaultSeverity>4.0</DefaultSeverity> <Description/> <Sink> <InArguments>0</InArguments> <Conditional> <And> <Not> <TaintFlagSet taintFlag="NUMBER"/> </Not> <Not> <TaintFlagSet taintFlag="VALIDATED_SQL_INJECTION"/> </Not> </And> </Conditional> </Sink> <FunctionIdentifier> <NamespaceName> <Pattern>net\.sf\.hibernate</Pattern> </NamespaceName> <ClassName> <Pattern>Session</Pattern> </ClassName> <FunctionName> <Pattern>createQuery</Pattern> </FunctionName> <ApplyTo implements="true/> </FunctionIdentifier> </DataflowSinkRule> Bothrulestargetthefirstparameterofthesamemethod.Asopposedtotheaccesscontrolsinkrule,theSQL injectionsinkrulemusthaveanincomingparameterthatisnotanumber.Theanalyzerchecksforthepresence oftheneutraltaintflagVALIDATED_SQL_INJECTION.Ifthattaintispresent,novulnerabilitycanoccur.SCA doesnotreportavulnerability. Chapter 3: Dataflow Analyzer and Custom Rules 34 Persistent Cross‐site Scripting ThisscenariohighlightstherulesthatarenecessaryforHPFortifytodetectcross‐sitescripting(XSS) vulnerabilitiesintheapplication.TheDataflowAnalyzerusesthesourcesinkandpassthroughrulestoidentify thistypeofvulnerability. Thescenariodemonstrateshowanattackercanexploitacross‐sitescriptingvulnerability.Itthenshowshow theDataflowAnalyzerusessource,sink,andpassthroughrulestoidentifythistypeofvulnerability. Thisscenariohighlightsthefollowingvulnerability: • Cross‐sitescripting—sendingunvalidateddatatoawebbrowsercanresultinthebrowserexecuting maliciouscode. Thisscenariohighlightsthefollowinganalysisandruleconcepts: • Generaltaint • Neutraltaint • Passthrough • Sink • Source • Specifictaint Source Code Theapplicationcontainsacross‐sitescriptingvulnerabilityinthetransactionpage.Anattackercanenter maliciouscontentintoatransaction'sdescription.Thevictimreceivesatransactionnotice.Uponviewingthe transactiondetails,theapplicationdeliversmaliciouscontentthevictim'sbrowser.Theattackercanusethis vectortoexecuteJavascriptorothermaliciouscontentinthevictim'sbrowser. Anycodethatrendersthedetailsofatransactionispotentiallyvulnerabletothisattack. Listing20showsaJSPpagethatrendersthesedetailsforagivenaccountnumber. Listing 20: JSP Page: Displays Transactions; Vulnerable to Cross‐Site Scripting Attacks <% String accountNumber = request.getParameter("acctno"); if ((accountNumber != null) && (accountNumber.length() > 0)) { Long account = Long.valueOf(accountNumber); List transactions = TransactionService.getTransactions(account); pageContext.getOut().println( "<h1>Transactions reported from database for account <i>" + accountNumber + "</i></h1>"); try { for (Iterator it = transactions.iterator(); it.hasNext();) { Transaction transaction = (Transaction)it.next(); String transactionDescription = "Transaction reported["+transaction.getId()+"]: " + "Account "+ transaction.getAcctno() + "; " + "Amount " + transaction.getAmount() + "; " + "Date " + transaction.getDate() + "; " + "Description " + transaction.getDescription(); pageContext.getOut().flush(); pageContext.getOut().println("<pre>"+transactionDescription+"</ pre>"); } ... Chapter 3: Dataflow Analyzer and Custom Rules 35 Thecodeenumeratesanaccount'stransactionsandprintseachtransaction'sdetailstotheresponsestream.To dothis,theJSPpagecallsTransactionService.getTransactions()toretrievethetransactionsassociated withtheaccountspecifiedbyacctno. Listing21showsthesourcecodethatretrievesthedatafromthedatabase. Listing 21: Implementation: TransactionService.getTransactions() public static List getTransactions(Long acctno) throws Exception { Session session = ConnectionFactory.getInstance().getSession(); String queryStr = "from Transaction transaction where transaction.acctno ='" + acctno + "' ORDER BY date DESC"; if (ServletActionContext.getServletContext() != null) ServletActionContext.getServletContext().log(queryStr); Query query = session.createQuery(queryStr); List transactions = query.list(); session.close(); return transactions; } ThismethodcallsQuery.list()toretrievetheassociatedtransactionsfromthedatabase.ThecodeinListing 21callsthismethodanddoesnotvalidatethetransactionslist.Thiscodecontainsacross‐sitescripting vulnerability. Rules First,theJSPcodecallsamethodtoretrievedatafromthedatabase.Adataflowsourcerulemodelsthismethod asasourceoftaintforSCA.Then,theJSPcodecallsmethodstotraversethedata.SCAusesdataflowpassthrough rulestotrackthetainteddatathroughthesemethods.Finally,theJSPcodewritesthedatatotheresponse stream.SCAusesdataflowsinkrulestodetectthefinaloutput. ThedataflowsourceruleinListing22modelsthecalltoQuery.list()asasourceoftainteddata. Listing 22: Source Rule: Query.list() <DataflowSourceRule formatVersion="3.8" language="java"> <RuleID>9ECA2C61-7625-41DB-967B-92768358C811</RuleID> <TaintFlags>+XSS</TaintFlags> <FunctionIdentifier> <NamespaceName> <Pattern>net\.sf\.hibernate</Pattern> </NamespaceName> <ClassName> <Pattern>Query</Pattern> </ClassName> <FunctionName> <Pattern>list</Pattern> </FunctionName> <ApplyTo implements="true" </FunctionIdentifier> <OutArguments>return</OutArguments> </DataflowSourceRule> The<OutArguments>elementintheruleaboveindicatesthatthereturnvalueofthemethodshouldbe consideredtainted.TherulealsoaddsthetaintflagXSS.ThisisaspecifictaintflagthatenablestheDataflow Analyzertoassociatesourcesofdatathatmaybeusedforacross‐sitescriptingattackwithsinksthatare potentiallyvulnerabletocross‐sitescripting. ThecodeinListing1iteratesthroughthetransactionlistobjectreturnedfromthecallto TransactionService.getTransactions().TheDataflowAnalyzerappliesthesourcerulefromListing3, withtheresultthatthelistobjectisconsideredtainted. Chapter 3: Dataflow Analyzer and Custom Rules 36 Listing23showsapassthroughrulethatallowstheDataflowAnalyzertopropagateandtracktaintfromthe transactionslistinListing21totheititeratorvariable. Listing 23: Passthrough Rule: Propagates Taint from a Collection to its Iterator <DataflowPassthroughRule formatVersion="3.8" language="java"> <RuleID>217417FB-7E50-41BA-ACB7-8159BD5211AC</RuleID> <FunctionIdentifier> <NamespaceName> <Pattern>java\.util</Pattern> </NamespaceName> <ClassName> <Pattern>Collection</Pattern> </ClassName> <FunctionName> <Pattern>iterator</Pattern> </FunctionName> <ApplyTo implements="true" </FunctionIdentifier> <InArguments>this</InArguments> <OutArguments>return</OutArguments> </DataflowPassthroughRule> Theinandoutargumentsspecifyhowtainteddataflowsthroughthemethod.Whentheapplicationcodecalls themethodonataintedtargetobject(this),theDataflowAnalyzerpropagatestainttothereturnvalue. Listing24showsthepassthroughrulethatallowstheanalyzertounderstandhowtaintisreturnedfromthe iteratorobjectonthecalltoIterator.next(). Listing 24: Passthrough Rule: Passes Propagates Taint from an Iterator to its Elements <DataflowPassthroughRule formatVersion="3.8" language="java"> <RuleID>D56C1363-C303-4AAB-99A9-98075D0FEB80</RuleID> <FunctionIdentifier> <NamespaceName> <Pattern>java\.util</Pattern> </NamespaceName> <ClassName> <Pattern>Iterator</Pattern> </ClassName> <FunctionName> <Pattern>next</Pattern> </FunctionName> <ApplyTo implements="true" </FunctionIdentifier> <InArguments>this</InArguments> <OutArguments>return</OutArguments> </DataflowPassthroughRule> Finally,theJSPcodeinListing20constructsatransactiondescriptionanddisplaysittotheuserusingthecode below(repeatedforconvenience). Chapter 3: Dataflow Analyzer and Custom Rules 37 Listing 25: JSP Code from Listing 20 ... String transactionDescription = "Transaction reported["+transaction.getId()+"]: " + "Account "+ transaction.getAcctno() + "; " + "Amount " + transaction.getAmount() + "; " + "Date " + transaction.getDate() + "; " + "Description " + transaction.getDescription(); outputWriter.flush(); outputWriter.println("<pre>"+transactionDescription+"</pre>"); ... SCAhasaccesstoallofthesourcecodeforthetransactionobject,whichmeanstheDataflowAnalyzercan automaticallytracktaintthroughtheobject'sgettermethods.ThismeanstheDataflowAnalyzercan successfullytracktaintfromthetransactionobjecttothetransactionDescriptionstringwithouttheneed foradditionalrules. Listing26showsthesinkruleusedbytheDataflowAnalyzertoidentifytheXSSvulnerability. ThisrulemarkstheJspWriter.println()functionasasink.TherulechecksthattheXSSflagispresent,and thattheVALIDATED_CROSS_SITE_SCRIPTINGflagisnot.Adevelopermaylaterintroduceavalidationfunction thatverifiesthecontentsofthedata.SCAwillrequireanewcleansingruleforthatvalidationfunctionwhich addstheVALIDATED_CROSS_SITE_SCRIPTINGtaintflagtothedata.ThisensuresthatSCAwillnotreporta vulnerabilityforpathswhichflowthroughthatfunction. Listing 26: XSS Sink Rule: JspWriter.println() <DataflowSinkRule formatVersion="3.8" language="java"> <RuleID>5F0C1BA2-3F30-483F-9232-9DB09442801E</RuleID> <VulnCategory>Cross-Site Scripting</VulnCategory> <DefaultSeverity>4.0</DefaultSeverity> <Sink> <InArguments>0</InArguments> <Conditional> <And> <TaintFlagSet taintFlag="XSS"/> <Not> <TaintFlagSet taintFlag="VALIDATED_CROSS_SITE_SCRIPTING"/> </Not> </And> </Conditional> </Sink> <FunctionIdentifier> <NamespaceName> <Pattern>javax\.ioservlet\.jsp</Pattern> </NamespaceName> <ClassName> <Pattern>JspWriter</Pattern> </ClassName> <FunctionName> <Pattern>println</Pattern> </FunctionName> <Parameters> <ParamType>java.lang.String</ParamType> <WildCard min="0" max="2"/> </Parameters> <ApplyTo implements="true" overrides="true" extends="true"/> </FunctionIdentifier> </DataflowSinkRule> The<Parameters>elementinthefunctionidentifierensuresthatthisruleonlymatchesversionsofthe JspWriter.println()functionwhichtakeaStringasthefirstparameter.The<Sink>elementspecifiesthat Chapter 3: Dataflow Analyzer and Custom Rules 38 thefirstparameteristheparameterwhichissensitivetotaint,andspecifiesthesetoftaintflagconstraintsin the<Conditional>element. Command Injection Scenario ThisscenariohighlightsrulesthatarenecessaryfortheDataflowAnalyzertodetectcommandinjection vulnerabilities.Thescenariodemonstrateshowanattackercanexploitacommandinjectionvulnerability.It thenillustrateshowDataflowAnalyzerusessource,sink,andpassthroughrulestoidentifythistypeof vulnerability. Thissectionhighlightsthefollowingvulnerability: • Commandinjection—executingcommandsfromanuntrustedsourceorinanuntrustedenvironmentcan causeanapplicationtoexecutemaliciouscommandsonbehalfofanattacker. Thisscenariohighlightsthefollowinganalysisandruleconcepts: • Inputarguments • Outputarguments • Passthrough • Sink • Source Source Code Theapplicationcontainsacommandinjectionvulnerabilityinitsmessagingservice.Toconducttheattack,an attackerformulatesane‐mailusingthemessagingservice.Theattackerentersmaliciouscommandsintoa messagesubject,body,to‐address,orfrom‐address.Then,theattackersubmitsthemessagetotheserverfor processing.Uponreceivingthemessage,theserverexecutestheembeddedcommands. Codethatformulatese‐mailsusinganinternalmessagingclassisvulnerabletothisattack. Chapter 3: Dataflow Analyzer and Custom Rules 39 Listing27showsaJSPpagethatusesthisclasstobroadcastalertmessages. Listing 27: Vulnerable JSP Code: Broadcasts an Alert. <% String alertMessage = request.getParameter("message"); int messageCount = 0; if ((alertMessage != null) && (alertMessage.length() > 0)) { SendMessage msgClass = new SendMessage(); String specifiedUsers = request.getParameter("users"); if ((specifiedUsers != null) && (specifiedUsers.length() > 0)) { PrintWriter outputWriter = response.getWriter(); outputWriter.flush(); outputWriter.print("<h1>Emergency Broadcast sent to users:</ h1><pre>"); String[] users = specifiedUsers.split(";"); for (int index=0; index < users.length; index++) { String emailAddress = users[index]; outputWriter.println(emailAddress); msgClass.setTo(emailAddress); msgClass.setSubject("Technical Difficulties"); String processedMessage = alertMessage.replaceAll("<code1>" "The system is currently experiencing technical difficulties."); msgClass.setBody(processedMessage); msgClass.setSeverity("Highest"); msgClass.execute(); messageCount++; } ... TheJSPdoessomesuperficialprocessingofthemessageandthencallsSendMessage.execute(). Listing28showshowthismethodhandlestheprocessedmessage. Listing 28: SendMessage.execute() Method: Retrieves Command String to Execute public String execute() { if (isInvalidEmail(to)) return INPUT; String[] cmd = getMailCommand(); String message = sendMail(cmd); addActionMessage(message); return SUCCESS; } TheSendMessage.execute()methodcallsSendMessage.getMailCommand()togenerateacommand stringthatisexecutedtosendthee‐mail. Chapter 3: Dataflow Analyzer and Custom Rules 40 Listing29showshowthecommandstringisgenerated. Listing 29: Java Code: Generate the Command String public String[] getMailCommand() { ... cmd[2] = java + " -cp "+ cp +" com.fortify.samples.riches.legacy.mail.SendMail \"" + subject + "\" \"" + severity + "\" \"" + body + "\" " + to; return cmd; } Thiscodeassumesthatthee‐mailmessagefieldsdonotcontain'|', ';', or '&'symbols.Thesesymbols representcommandstringdelimitersondifferentplatforms.Thesedelimiterscanbeincludedinacommand stringtoexecutemultiplecommandswithinthesamestring.Forexample,anattackermayprovidethemessage body'" & dir C:\ > c:\files.txt &'.TheJSPcodeinListing27eventuallycallsthe SendMessage.execute()methodtogenerateandexecuteashellcommandstringbasedonthemail command.ThismethodcallstheSendMessage.sendMail()methodtoexecutethecommandstring: Listing 30: Message Service Code: Execute the Command String public String sendMail(String[] cmd) { Runtime rt = Runtime.getRuntime(); //call "legacy" mail program Process proc = null; StringBuilder message = new StringBuilder(); try { proc = rt.exec(cmd); ... Ifanattackersubmitsthesamplemessagebody,theshellwillexecutetheoriginalcommandandtheadditional commandsspecifiedinthesamplemessagebody. Rules TainteddataenterstheJSPcodethroughacalltoServletRequest.getParameter().Listing31illustrates thismethodcallonthefirstline. Listing31showsarulethatcausesSCAtomodelthatcallasasourceoftainteddata. Listing 31: Source Rule: ServletRequest.getParameter() <DataflowSourceRule formatVersion="3.8" language="java"> <RuleID>1D76BD43-638A-4B46-94F7-5A537B2FB11D</RuleID> <TaintFlags>+WEB,+XSS</TaintFlags> <FunctionIdentifier> <NamespaceName> <Pattern>javax\.servlet</Pattern> </NamespaceName> <ClassName> <Pattern>ServletRequest</Pattern> </ClassName> <FunctionName> <Pattern>getParameter</Pattern> </FunctionName> <ApplyTo implements="true"/> </FunctionIdentifier> <OutArguments>return</OutArguments> </DataflowSourceRule> The<OutArguments>elementspecifiesthatthereturnvalueofthemethodistainted.Theruletaintsthereturn valuewithWEBtainttoindicatethattheobjectcontainsdatawhichoriginatesfromtheweb.Traditionally,we Chapter 3: Dataflow Analyzer and Custom Rules 41 associateWEBtaintwithXSStaintbecauseobjectscomingfromawebsourcemightalsocontainJavaScript. Thisextrataintisusedbyotherrulestoidentifycross‐sitescriptingvulnerabilitiesandisnotdirectlyapplicable tocommandinjectionvulnerabilitydetection. TheJSPcodeinListing27processestheincominge‐mailmessagebycallingtheString.replaceAll() methodtoreplaceidentifierkeyswithmessagetext. Listing32showsthepassthroughrulethatallowsSCAtofollowtaintfromthealertMessage variabletothe processedMessagevariable. Listing 32: Passthrough Rule: Taint Track through String.replaceALL() <DataflowPassthroughRule formatVersion="3.8" language="java"> <RuleID>B1D159AE-EE88-4760-A112-8BFC5F774DE3</RuleID> <FunctionIdentifier> <NamespaceName> <Pattern>java\.lang</Pattern> </NamespaceName> <ClassName> <Pattern>String</Pattern> </ClassName> <FunctionName> <Pattern>replaceAll</Pattern> </FunctionName> </FunctionIdentifier> <InArguments>this</InArguments> <OutArguments>return</OutArguments> </DataflowPassthroughRule> Listing33showsthesinkruleusedtodetectthecommandinjectionvulnerability.ThisrulemarksJava's Runtime.exec()methodasasink.ItchecksthattheVALIDATED_COMMAND_INJECTIONtaintflagisnot present.Ifthedeveloperwishestoaddavalidationfunctiontovalidatethecontentsofthedata,youcanwritea ruleforthevalidationfunctionthataddstheVALIDATED_COMMAND_INJECTIONtaintflagtothedataobjects.This ensurethatSCAwillnotreportavulnerabilityforpathswhichflowthroughthatfunction. Listing 33: Command Injection Sink Rule: Runtime.exec() <DataflowSinkRule formatVersion="3.8" language="java"> <RuleID>E6E0AC3D-1C7B-48B1-B80D-2AC4619B0D81</RuleID> <VulnKingdom>Input Validation and Representation</VulnKingdom> <VulnCategory>Command Injection</VulnCategory> <DefaultSeverity>4.0</DefaultSeverity> <Description/> <Sink> <InArguments>0...</InArguments> <Conditional> <Not> <TaintFlagSet taintFlag="VALIDATED_COMMAND_INJECTION"/> </Not> </Conditional> </Sink> <FunctionIdentifier> <NamespaceName> <Pattern>java\.lang</Pattern> </NamespaceName> <ClassName> <Pattern>Runtime</Pattern> </ClassName> <FunctionName> <Pattern>exec</Pattern> </FunctionName> </FunctionIdentifier> </DataflowSinkRule> Chapter 3: Dataflow Analyzer and Custom Rules 42 Chapter 4: Custom Structural Rules Thischapterprovidesthefollowingtopics: • UnderstandingStructuralAnalyzerandCustomRules—usethissectiontolearnabouttheControlflow Analyzerandthewaythatitusescustomrulestofindsecurityissues. • StructuralTreeExamples—usethissectiontofamiliarizewithstructuraltrees. • XMLRepresentationofStructuralRules—usethissectiontolearnhowyoucanrepresentstructuralrulesin XML. • StructuralCustomRuleScenarios—usethissectiontolearnhowtocreatecustomstructuralrules. Understanding Structural Analyzer and Custom Rules TheStructuralAnalyzermatchesarbitraryprogramconstructsinsourcecode.Unlikeothercodeanalyzersin SCA,itisnotdesignedtofindproblemsarisingfromflowofexecutionordata.Rather,itspecializesindetecting issueswhichcanbedetectedbyidentifyingcertainpatternsofcode. Structural Tree TheStructuralAnalyzeroperatesonamodeloftheprogramsourcecodecalledthestructuraltree.The structuraltreeismadeupofasetofnodeswhichrepresentprogramconstructssuchasclasses,functions,fields, codeblocks,statementsandexpressions. Nodesinthestructuraltreecanhaveasingleparentandmanychildren.Forexample,anoderepresentingafield isthechildofanoderepresentingtheclassinwhichthatfieldisdeclared.Likewise,anoderepresentingan expressionisthechildofanoderepresentingthestatementinwhich+thatexpressionappears. Eachnodeinthestructuraltreealsohasasetofproperties.Somepropertiesencodesimplevalues,suchasthe nameofafunctionorthetypeofavariable.Propertiescanalsoexpressrelationshipsbetweennodeswhichare notdirectlyconnectedbyaparent‐childrelationship.Forinstanceapropertymightbeusedtoconnecttheuse ofavariableinonepartofafunctiontoitsdeclarationinanother,aclassdeclarationtoaninterfaceit implements,orafunctioncallexpressiontothedeclarationofthefunctionitcalls. Insomecases,anodemaybeconnectedtoanothernodebothviaaparentorchildconnectionandbya property.Anassignmentstatement,forexample,hastwochildexpressions(oneontheleft‐handsideofthe= andoneontheright‐handside).Theseexpressionscanalsobereachedindividuallybythelhsandrhs properties.Thisallowsrulestoperformmoreprecisequeriesagainstthetree.Forinstance,aquerythatlooks foranassignmentwithxasachildwouldmatchboth"x = y"and"y" = x,butaquerythatlooksforan assignmentwithxaslhswouldmatch"x = y"butnot"y = x." Anodeinthestructuraltreehasatype,referredtoasthestructuraltype.Thestructuraltypeofanodewhich representsafunctiondeclarationisdifferentthanthestructuraltypeofanodethatrepresentsaclass declaration,andlikewisedifferentfromthestructuraltypeofanodethatrepresentsanexpression. Structuraltypesmakeiteasytowritequeriesthatlookforcertaintypesofnodes.Thestructuraltypeofanode alsodeterminesthesetofpropertiesthatitwillhave.Afulllistingofallstructuraltypesandtheirproperties canbefoundintheStructuralTypeandPropertyReference. Chapter 4: Custom Structural Rules 43 Structural Tree Query Language Thestructuraltreequerylanguageenablestheanalyzertoperformcomplexmatchesagainstthestructuraltree. Eachstructuralrulecontainsasinglequery.TheStructuralAnalyzerreportsanissueforeachconstructinthe programthatmatchesthatquery. Writingaquerythatmatchesaparticularcodeconstructinvolvesunderstandinghowthecodewilllookwhen representedinastructuraltree.Thequeryshouldexpressconstraintsintermsofthestructuraltypeofnodesto matchandtherelationshipsbetweenthosenodes(parent‐childandpropertyrelationships). Structural Tree Examples ThefollowingexamplesdemonstratestheconstructionofasimplifiedstructuraltreeforaverysmallJava program.Eachexampleincludesprogramsourcecode,adiagramofthestructuraltree,andanexplanation. Theseexamplesincludestructuraltreediagramsforillustrativepurposes.Thesediagramsexcludesome databaseattributesforthesakeofsimplicity.Astheexampleprogrambecomesmorecomplex,someofthe edgesshowninthetreeareomitted.Thisistomaketheillustrationeasiertoread. Usethefollowinglegendtointerpretdiagramsintheexamples.Youcanprintthispageanduseitasareference whengoingthroughtheexamples. Figure 1: Diagram Legend Example 1 Thefollowingprogramconsistsonlyofaclasswithasinglememberfield. Listing 34: Class with Single Member Field class C { private int f; } Inthestructuraltreethefieldisrelatedtotheclassviathefieldsproperty,whichlistsallfieldsofaclass. Chapter 4: Custom Structural Rules 44 Figure 2: Class with a Single Member Field Example 2 Thisexampleaddsanemptyfunctiontotheclass. Listing 35: Empty Function Added to Class class C { private int f; void func() { } } Thestructuraltreenowincludesnodesforthefunctionanditsbodyblock. Figure 3: Class with Function and Body Block Chapter 4: Custom Structural Rules 45 Aquerytoveryspecificallymatchthefieldinthiscodecouldlooklikethis: Listing 36: Code Match Query Field field: field.name == "f" and field.enclosingClass is [Class class: class.name == "C"] Thequeryincludesconstraintsonthenamepropertiesoftheclassandfieldnodes,soitwouldnolongermatch thecodeiftheclassorfieldwererenamed.Normally,structuralqueriesaredesignedtobelessspecificthanthis example. Example 3 Thisexampleaddsalocalvariabledeclarationtothefunction. Listing 37: Local Declaration Added to Function class C { private int f; void func() { int x; } Thebodyblocknowhasachildnodeforthestatementwhichdeclaresthevariable. Figure 4: Body Block with Child Node Chapter 4: Custom Structural Rules 46 Example 4 Thisfinalversionoftheprogramaddsastatementwhichperformsarithmeticonthevalueofthefieldand assignstheresulttothelocalvariable. Listing 38: Added Arithmetic Statement class C { private int f; void func() { int x; x = f + 1; } } Thestructuraltreenowincludesanassignmentstatement,whichrelatestwoexpressions.Thelefthandside expression(lhs)denotesthelocationbeingassignedto,whiletherighthandside(rhs)isthevaluebeing assigned.Theexpressionontherighthandsideoftheassignmentbreaksdownfurtherintoanoperation(add) ontwocomponents:thefieldandaninteger.Theexpressionswhichaccessthefieldandvariableinclude propertieswhichconnecttothecorrespondingdeclarations. Figure 5: Assignment Statement with Related Expressions Asanexample,thefollowingquerymatchesanyassignmentintheprograminwhichthelocationbeingwritten toisalocalvariableandtheexpressionforthevalueincludesareadofafieldwhichbelongstothesameclassas theclassinwhichthefunctionappears.Thiswouldmatchtheexamplecodeabove.UnlikethequeryinExample 2,itdoesnotincludeconstraintsonnames.Itisgeneralenoughtomatchsimilarcodepatternsinotherpartsof theprogram. Chapter 4: Custom Structural Rules 47 Listing 39: Assignment Query AssignmentStatement a: a.lhs is [VariableAccess:] and a.rhs contains [FieldAccess fa: fa.field.enclosingClass == a.enclosingFunction.enclosingClass] XML Representation of Structural Rules TheXMLrepresentationofastructuralrulecontainsalloftheelementscommontorulesthatproduce vulnerabilities.Inadditiontotheseelements,astructuralrulecontainsoneormore<Predicate>tags.These predicatescontainstructuralqueries.Ifaprogramconstructmatchesthequerycontainedinany<Predicate> tag,theStructuralAnalyzerwillreportavulnerabilityforthatprogramconstruct.Itisoftenusefultoenclose thecontentsofthe<Predicate>tagin<![CDATA[ … ]]>toavoidtheneedtoescapeXMLspecialcharacters inthequery. Listing 40: XML Representation of Structural Rules <StructuralRule formatVersion="3.8" language="java"> <RuleID>5707596F-F163-7D69-35F6-B18C9FEFDB1B</RuleID> <VulnCategory>Confusing Method Name</VulnCategory> <DefaultSeverity>2.0</DefaultSeverity> <Description ref="confusingmethod.hashcode"/> <Predicate><![CDATA[ Function: name is "hashcode" ]]></Predicate> </StructuralRule> Structural Custom Rule Scenarios Thissectionprovidesexamplesofstructuralrules.Youcanusetheseexamplesasthebasisforwritingcustom rules.Matchyourrequirementwithoneoftheexamples,andtailortherulestosuityoursoftware. • ScenarioOverview • LeftoverDebugScenario • DangerousFunctionCallsScenario • OverlyBroadCatchBlocks • PasswordinCommentsScenario • PoorLoggingPracticeScenario • EmptyCatchBlockScenario Chapter 4: Custom Structural Rules 48 Scenario Overview ThescenariosinthissectionarewrittenagainstsampleapplicationcalledRichesWealthOnline(RWO).This applicationenablesusestoperformthefollowingonlinebankingoperations: • Transferringmoney • Viewingaccountstatements • Receivingmessagesfromthebank TheRWOapplicationdemonstratesthediverserangeofapplicationsecurityvulnerabilitiesthataretypically encounteredinreal‐worldapplicationsthatprovidefunctionalitysimilartoRWO.Theapplicationisbuiltwith JavaScript,Struts2,Hibernate2,andJavaEnterpriseEdition. EachscenariohighlightsspecificvariabilitiesinRWOanddemonstrateshowtoidentifythemusingcustom rules. ThescenariodoesthisbyshowinghowanattackercanexploitvulnerabilitiesinRWOsourcecode.The scenario,whereapplicable,willhighlighthowSCAandtheSecureCodingRulepacksdetectthevulnerability. Thescenariothenexplainsthetypeofcustomrulesnecessarytodetectthevulnerabilityandshowsyouhowto createthem. YoucanthenreproducetheresultsbyanalyzingRWOwitheitherSecureCodingRulepacksorbyusingthe providedcustomrules.Inordertousetheprovidedcustomerrules,youmustfirstdisableSecureCoding Rulepacks. Leftover Debug Scenario ThisscenariohighlightstherulesnecessaryfortheStructuralAnalyzertodetectleftoverdebugcode.This scenariodemonstrateshowleftoverdebugcodecanintroduceunexpectedvulnerabilitiesinaproduction environment.Itthenshowstherulesthatidentifythistypeofvulnerability. Thisscenariohighlightsthefollowingtypeofvulnerability: • Leftoverdebugcode—debugcodecanexposeunintendedfunctionalityinadeployedapplication. Thisscenariohighlightsthefollowinganalysisandruleconcepts: • Functionconstructobjects • Slotconstructobjects • Startswithoperator • Structuralrule Source Code Theapplicationcontainsmethodsthatarecalledbydeveloperstodebugtheretrievalofsensitivedata.Thecode inListing41showshowadevelopertemporarilydebugsthismethod. Listing 41: Method that retrieves a list of transactions public static List getTransactions(String acctno) throws Exception { ... // TODO: remove this before deploying to production debugTransactions(transactions); return transactions; } Here,thedevelopercallsthedebugTransactions()methodtoexaminethecontentsofthetransactions. Chapter 4: Custom Structural Rules 49 Listing42showhowtheapplicationdebugsthetransaction: Listing 42: Temporary Debug Code: debug a List of Transactions. public static void debugTransactions(List transactions) throws Exception { Logger debugLogger = Logger.getLogger(TransactionService.class.getName()); debugLogger.setLevel(Level.FINEST); FileHandler fh = new FileHandler("debug.log"); fh.setLevel(Level.FINEST); debugLogger.addHandler(fh); for (int index=0; index < transactions.size(); index++) { Transaction proposedTransaction = (Transaction)transactions.get(index); debugLogger.finest("Request transaction statement: "+proposedTransaction.getId()+": " + proposedTransaction.getAcctno() + "; " + proposedTransaction.getAmount() + "; " + proposedTransaction.getDate() + "; " + proposedTransaction.getDescription()); } } Thismethodrecordssensitivedatatoanunencryptedlogfile.Iftheapplicationexecutesthismethodwithina productionenvironment,sensitivedatawillbewrittentoanunencryptedfile.Thisraisestheriskofaccidental disclosureofsensitivedatatoathirdparty. Rules Thereisacommonmethodsignaturethatidentifieseverydebugmethodintheapplication.Thecodein Listing41illustratesthateachdebugmethod'snamestartswiththeword“debug.” Also,themethodaccepts oneparameteroftypejava.util.List. ThestructuralruleinListing43identifiesallmethodsthatmatchthisdebugsignature. Listing 43: Structural rule that highlights debug code. <StructuralRule formatVersion="3.8" language="java"> <RuleID>8206ED21-9FB0-44AC-9058-6FCDA601E699</RuleID> <Notes>Leftover Debug Code</Notes> <VulnCategory>J2EE Bad Practices</VulnCategory> <DefaultSeverity>2.0</DefaultSeverity> <Predicate> Function: name startsWith "debug" and parameterTypes.length == 1 and parameterTypes[0].name == "java.util.List" </Predicate> </StructuralRule> Theanalyzerusesthisruletoidentifyandreportalldebugmethods.First,theruleinspectseachfunction object'snamepropertytoverifythemethod'snamebeginswiththeword“debug.”Then,theruleverifiesthat thereisonlyoneparametertothismethod.Therulethenverifiesthattheparameterisoftype java.util.List. Dangerous Function Calls Scenario ThisscenariohighlightstherulesthatarenecessaryfortheStructuralAnalyzertodetectdangerousfunction callvulnerabilities.Thescenarioillustrateswhyanapplicationshouldnevercallparticularmethods.Itthen showshowtheStructuralAnalyzerusesstructuralrulestoidentifythedangerousfunctioncallvulnerability. Chapter 4: Custom Structural Rules 50 Thisscenariohighlightsthefollowingvulnerabilities: • Cross‐sitescripting—sendingunvalidateddatatoawebbrowsercanresultinthebrowserexecuting maliciouscode • Dangerousmethod—neverusefunctionsthatareunsafe Thisscenariohighlightsthefollowinganalysisandrulesconcepts: • FunctionCallconstructobject • Structuralrule Source Code Across‐sitescriptingvulnerabilityexistsintheapplication.Avalidationfunctionattemptstomitigatethis vulnerability.However,itisinadequateanddoesnotfullyeliminatetheXSSvulnerability.Youshouldnotuse thisfunctionforanycurrentorfutureprojectswithintheorganization. Theapplicationreceivesmessagesfromtheuserandwritesthecontentstoadatabase.persistentcross‐site scriptingvulnerabilitiesmightresult. Listing44showsamethodthatiscalledtofilteranymaliciouscharactersfromthemessagesbeforethe applicationwritesthemtodisc. Listing 44: Inadequate Validation Function. private static Message validateMessage(Message incomingMessage) throws Exception { // Validate sender String incomingSender = incomingMessage.getSender(); if ((incomingSender == null) || (incomingSender.length() == 0)) throw new Exception("invalid sender in message"); // Validate subject String incomingSubject = incomingMessage.getSubject(); if (incomingSubject == null) throw new Exception("invalid subject in message"); // Validate severity String incomingSeverity = incomingMessage.getSeverity(); if ((incomingSeverity == null) || (incomingSeverity.length() == 0)) throw new Exception("invalid sender in message"); // Validate body String incomingBody = incomingMessage.getBody(); if (incomingBody == null) throw new Exception("invalid sender in message"); return incomingMessage; } Thefunctiondoesnotperformwhite‐listvalidationoftheincomingMessagemessageandshouldneverbe calledbyanyapplicationcode. Rules ThestructuralruleinListing45identifiesallinstanceswheretheapplicationcallsthe MessageService.validateMessage()method. Chapter 4: Custom Structural Rules 51 Listing 45: Inadequate Validation Function. <StructuralRule formatVersion="3.8" language="java"> <RuleID>95C67A96-5AF7-402E-B451-6CEFF4EB8973</RuleID> <VulnKingdom>API Abuse</VulnKingdom> <VulnCategory>Dangerous Method</VulnCategory> <DefaultSeverity>4.0</DefaultSeverity> <Predicate> FunctionCall call: call.function.name == "validateMessage" and call.function.enclosingClass.name == "com.fortify.samples.riches.model.MessageService" </Predicate> </StructuralRule> TheruleusestheFunctionCallconstructobjecttoinspecteverymethodthattheapplicationcalls.The analyzerreportsavulnerabilitywhentheconditionsoftherulearemet. Overly Broad Catch Blocks Thisscenariodemonstrateshowoverlyboardcatchblockscancausesecurityissues.Thescenariothen providesexamplesofrulesthatworkwiththeStructuralAnalyzertofindvulnerabilitiescausedbyoverlybroad catchblocks. Thisscenariohighlightsthefollowingvulnerability: • Poorerrorhandling‐broadcatch—thecatchblockhandlesabroadswathofexceptions,potentiallytrapping dissimilarissuesorproblemsthatshouldnotbedealtwithatthispointintheprogram. Thisscenariohighlightsthefollowinganalysisandrulesconcepts: • CatchBlockconstructobject • Containsoperator • Exceptionconstructobject • Notoperator • ThrowStatementconstructobject • StructuralRule Chapter 4: Custom Structural Rules 52 Source Code Listing46showsanexampleofoverlybroadexceptionhandlingcode. Listing 46: Unacceptable Use: Broad Catch Blocks public static void addMessage(Message message) { Session session = null; try { session = ConnectionFactory.getInstance().getSession(); Transaction tx = session.beginTransaction(); session.save(message); tx.commit(); session.flush(); session.close(); } catch(Exception e) { // Treat all exceptions the same here } } ThecatchblockcatchesthegenericExceptionclass.Ideally,separatecatchblockshandlespecificorrelevant securityexceptionsindividually.Programsshouldprocessthesesecurityexceptionsseparatelytocreateaudits whicharenecessaryfortrackingbugsanddetectingsecuritybreaches. Noteveryoverlybroadcatchblockrepresentsaproblem.Forexample,thecodeinListing47catchesall exceptionsandthrowsthemupthecallstack. Listing 47: Acceptable Overly Broad Catch Block: Throws the Exception public static boolean isAdmin(int roleid) throws Exception { boolean auth = false; Connection conn = ConnFactory.getInstance().getConnection(); ResultSet rs = null; try { Statement statement = conn.createStatement(); rs = statement.executeQuery("SELECT rolename FROM auth WHERE roleid = " + roleid); rs.next(); if (rs !=null && rs.getString("rolename").equals("admin")) auth = true; conn.close(); } catch(Exception e) { throw e; } return auth; } Ahighercatchblockcanhandletheexceptioninacorrectmanner.Itisalsoacceptabletoperformabroadcatch atthehighest‐levelmethodoftheapplication. ThecodeinListing48showsanexampleofanappropriatelybroadcatchblockthatcatchesallexceptions immediatelybeforetheyexittheprogram. Chapter 4: Custom Structural Rules 53 Listing 48: An Acceptable Way to Perform Broad Exception Catching public static void main(String args[]) { try { BannerAdServer obj = new BannerAdServer(); BannerAdSource stub = (BannerAdSource)UnicastRemoteObject.exportObject(obj, 0); // Bind the remote object's stub in the registry Registry registry = LocateRegistry.getRegistry(); registry.bind("BannerAdSource" stub); } catch (Exception e) { // Process any exceptions that aren't handled anywhere else } Rules Aruleneedstoreportalloverlybroadcatchblocksthatarenotdefinedwithinthemain()methodanddoesnot throwtheexceptionupthecallstack. Listing49showstherulethatreportscatchblocksthatmeettheserequirements. Listing 49: : Structural Rule that Identifies Overly Broad Catch Blocks <StructuralRule formatVersion="3.8" language="java"> <RuleID>C9ECD6EC-DAA1-41BE-9715-033F74CE664F</RuleID> <VulnCategory>Poor Error Handling</VulnCategory> <DefaultSeverity>2.0</DefaultSeverity> <Description> <Predicate> CatchBlock: exception.type.name == "java.lang.Exception" and not contains [ThrowStatement: ] and not (enclosingFunction.name == "main") </Predicate> </StructuralRule> Thisruleidentifiesallcatchblocksintheprogramusingthecatchblockerandinspectstheclasstypeofthe exceptionbeingcaughtineachcatchblock.Theexception.type.namepropertydescribesthenameofthe classspecifiedbythecatchblock.Thispropertymustequalthegenericexceptionclassjava.lang.Exception fortheruletoreportthiscatchblock. TherulethenexcludescatchblocksthatcontainaThrowStatement,whichrepresentsathrowstatementinside thecatchblock. Thecatchblockconstructobject'senclosingFunction.namepropertydefinesthenameofthemethodthat containsthecatchblock,whichmustnotequalthevaluemain. Whenacatchblocksatisfiesallthreeoftheseconditions,theStructuralAnalyzerwillreportanoverlybroad catchvulnerability. Password in Comments Scenario ThisscenariodemonstratestherulesthatenabletheStructuralAnalyzertodetectpasswordsincomments.This includeshowpasswordsmightappearincommentsandhowanattackercanexploitthisvulnerability.The scenariothenshowshowtheStructuralAnalyzerusesrulestoidentifythistypeofvulnerability. Thisscenariohighlightsthefollowingvulnerability: • Passwordmanagement:passwordsincomments—hardcodedpasswordscancompromisesystemsecurity inawaythatyoucannoteasilyremedy. Chapter 4: Custom Structural Rules 54 Thisscenariohighlightsthefollowinganalysisandrulesconcepts: • Commentconstructobject • Javaregularexpressions • Structuralrules Source Code Ifthesourcecodeofanapplicationcontainsauthenticationcredentialsfortheproductiondatabase,anyonewith accesstothedevelopmentenvironmentanditssourcecodecanaccessdatainproductionenvironment. ThecodeinListing50showshardheadedcredentialsintheProfileServiceclass. Listing 50: Structural Rule: Overly Broad Catch Blocks public class ProfileService { // NOTE: sample profiles can be reproduced through internal server // host: db1.riches.com; username: service, password: passw0rd1! { Rules ThestructuralruleinListing51identifiestextthatcontainstheword'password' inacommentblock,inline comment,orJavaDoc. Listing 51: :Structural Rule: Identifies Passwords in Comments <StructuralRule formatVersion="3.8" language="java"> <RuleID>C938AE93-EA38-403b-ABDA-3F01BEFA7933</RuleID> <VulnCategory>Password Management</VulnCategory> <DefaultSeverity>2.0</DefaultSeverity> <Description/> <Predicate> Comment c: (c.doc or c.inline or c.block) and c.text matches "(?i).*password.*" </Predicate> </StructuralRule> First,thisruleinspectsthedoc,inline,andblockpropertiesofeverycommentconstructobjectinthe application.Ifoneofthesepropertiesistrue,thecommentsatisfiesthecriteriathatitmustbeablock,inline,or JavaDoccomment. Thentheruleinspectsthetextpropertyoftheobjecttexttoseeifthevalueofthepropertyvaluematchesthe Javaregularexpression'(?i).*password.*'.Thisexpressionwillmatchanytextthatcontains'password' anywherewithinitsvalue,regardlessofcapitalization. Therulewillreportanissuewhenitfindsacommentthatsatisfiesbothsetsoftheseconditions. Poor Logging Practice Scenario ThisscenariodemonstratestherulesthatenabletheStructuralAnalyzertoidentifyloggingobjectsthatarenot declaredstaticandfinal.Thescenariodemonstratesapoorloggingpractice.Thenitillustratesthewaythe StructuralAnalyzerusesrulestoidentifythistypeofissue. Thisscenariohighlightsthefollowingvulnerability: • Poorloggingpractice:loggernotdeclaredstaticfinal—declareloggerstobestaticandfinal. Chapter 4: Custom Structural Rules 55 Thisscenariohighlightsthefollowinganalysisandrulesconcepts: • Classconstructobjects • Containsoperator • Fieldconstructobjects • Notoperator • StructuralRules Source Code Itisgoodprogrammingpracticetoshareasingleloggerobjectbetweenalloftheinstancesofaparticularclass andtousethesameloggerthroughoutthedurationoftheprogram.Thewaytheapplicationimplements ConnectionClassclassinListing52illustratesaviolationofthispractice. Listing 52: Incorrect Declaration of Logger Object public class ConnectionFactory { private static Logger log = Logger.getLogger(ConnectionFactory.class.getName()); private static ConnectionFactory instance = null; Rules Listing53showsarulethatreportsanyinstanceofjava.util.logging.Loggerobjectthattheprogram declaresasafieldbutdoesnotdeclaredusingboththestaticandfinalkeywords. Listing 53: Rule: Detect Improperly Declared Logger Objects <StructuralRule formatVersion="3.8" language="java"> <RuleID>B95EB686-8EBC-498F-B332-55E31F9DFB8A</RuleID> <VulnCategory>Poor Logging Practice</VulnCategory> <DefaultSeverity>2.0</DefaultSeverity> <Description/> <Predicate> Field f: not (static and final) and type.definition.supers contains [Class: name == "java.util.logging.Logger </Predicate> </StructuralRule> ToidentifyanimproperlydeclaredLoggerfieldobject,theStructuralAnalyzerinspectsthestaticandfinal propertiesofeveryFieldconstructobject.Ifeithervalueisfalse,thefieldsatisfiestherule'sfirstsetof conditions. OnceaFieldconstructobjectsatisfiesthesefirstconditions,theruleinspectstheFieldobject'sdeclaredtype. Thefieldbeaninstanceofajava.util.logging.Loggeroranextensionthatinheritsfromthatclass. WhenaFieldconstructobjectsatisfiesbothsetsofconditions,theanalyzerreportsthefielddeclarationasan issue. Empty Catch Block Scenario ThisscenariohighlightstherulesthatarenecessaryfortheStructuralAnalyzertodetectemptycatchblock vulnerabilities.Thescenariodemonstrateshowanattackercanexploitanemptycatchblockvulnerability.It thenshowhowtheStructuralAnalyzerusesstructuralrulestoidentifythistypeofvulnerability. Thescenariohighlightsthefollowingvulnerability: • Poorerrorhandling:emptycatchblock—Ignoringanexceptioncancausetheprogramtooverlook unexpectedstatesandconditions. Chapter 4: Custom Structural Rules 56 Thescenariohighlightsthefollowinganalysisandrulesconcepts: • Catchblockconstructobject • Structuralrules Source Code ThecodeinListing54buildsHibernatesessionsthatareusedbytheapplicationinsubsequentdatabase operations.TheConnectionFactoryclass'constructorcontainscodethatmaythrowsoftwareexceptions: Listing 54: Class Constructor Missing Catch Block Code private ConnectionFactory() { try { String pFile = System.getProperty("ConnectionFactory.pfile"); if (pFile != null) { java.util.Properties props = new java.util.Properties(); props.load( new java.io.FileInputStream(pFile) ); } } catch (Exception e) { //TODO: fill in this code } ... Inthiscode,thecatchblockisempty.Theapplicationcannotmaintainanaccuratelogofanysecurityevents thatmightoccur. Rules ToidentifytheemptycatchblockinListing54,theStructuralAnalyzershouldexamineeachCatchBlock constructobjects'emptyproperty.Thisbooleanpropertyindicatesthatthecorrespondingcatchblockdoesnot containanycode. TheruleinListing55illustratesthisstrategyforidentifyingemptycatchblocks. Listing 55: Structural Rule to Detect Empty Catch Blocks <StructuralRule formatVersion="3.8" language="java"> <RuleID>D693090B-3F8C-48BD-BCDE-C6DCA2266710</RuleID> <VulnCategory>Poor Error Handling</VulnCategory> <DefaultSeverity>2.0</DefaultSeverity> <Description/> <Predicate> CatchBlock: empty </Predicate> </StructuralRule> Theanalyzerusesthisconfigurationruletohighlightanyemptycatchblocksintheapplication. Chapter 4: Custom Structural Rules 57 Chapter 5: Custom Control Flow Rules Thischapterprovidesthefollowingtopics: • UnderstandingControlFlowAnalyzerandCustomRules—usethissectiontolearnabouttheControlflow Analyzerandthewaythatitusescustomrulestofindcontrolflow‐relatedsecurityissues. • ControlFlowAnalyzerandCustomRuleConcepts—usethissectiontolearnaboutControlflowAnalyzerand ruleconcepts. • XMLRepresentationofControlFlowRules—usethissectiontolearnhowyoucanrepresentcontrolflow rulesinXML. • CustomControlFlowRuleScenarios—usethissectiontolearnhowtocreatecustomcontrolflowrules. Understanding Control Flow Analyzer and Custom Rules TheControlflowAnalyzerfindssecurityissuesinprogramsthathaveinsecuresequencesofoperations.This enablesSCAtoidentifymanytypesofsecurityproblems. TheControlflowAnalyzermodelseachsecuritypropertyasastatemachine.Eachstatemachinehasthe followingstates: • Initialstate • Anynumberofinternalstates • Oneormoreerrorstates Thestatemachineisintheinitialstateatthebeginningofafunction.TheControlflowAnalyzerreportsa vulnerabilitywhenastatemachineentersanerrorstate. Thestatesinthestatemachineareconnectedbytransitions.Atransitionleadsfromonestate(thesourcestate) toanotherstate(thedestinationstate)andhasoneormoreassociaterulepatterns.Rulepatternsspecify programconstructs.Thestateofastatemachinechangesfromsourcetodestinationwhenoneofthe transition’srulepatternsmatchesastatementthattheControlflowAnalyzerisanalyzing. Astatecanhaveanynumberoftransitionsleadingoutoforintoit.TheControlflowAnalyzerchecksthe transitionsleadingoutofastateoneatatimeintheorderinwhichtheyappearinthestatemachinedefinition. TheControlflowAnalyzerexecutesthefirststatementthatmatchesastatement.TheControlflowAnalyzer ignoresanyothertransitionoutofthesamestate. Youcanusethistolimitthenumberoffunctionsthattheprogramcancallinagivencontext:thestate representingthatcontextwouldhaveatransitiontoasafestate(possiblyitself)iftheprogramcallsanallowed function,andatransitiontoanerrorstateiftheprogramcallsanyfunction. TheControlflowAnalyzeroperatesinterprocedurally,soifonefunctioncallsasecondfunction,andastate transitionoccursinsidethatsecondfunction,thestateinthefirst(calling)functionisupdatedaswell. ThefollowingexampleprogramusesalockingAPI.TheAPIcontractstatesthatafunctionthatacquiresthelock mustreleaseitbeforereturning.Insomecases,thesampleprogramdoesnotreleasethelockbeforereturning. Listing56showsasampleprogramthatdoesnotalwaysreleasethelockbeforereturning. Chapter 5: Custom Control Flow Rules 58 Listing 56: Locking API function readFile(File file) { Lock fileLock = getLock(file); if (!isReadable(file)) { return; } doRead(file); releaseLock(fileLock); return; } ThecontractforthelockingAPIisdescribedasastatemachine. Table9showsthestatesandtransitionsofthestatemachineprovidedinListing57. Table 9: State machine states Source State Destination State Program Construct Causing Transition Unlocked(startstate) Locked CalltogetLock() Locked Released CalltoreleaseLock() Locked Leaked(errorstate) Functionends Listing57showsthecontrolflowrulethatencodesthisstatemachine. Listing 57: State Machine Control Flow Rule state Unlocked (start); state Locked; state Released; state Leaked (error); var lock; Unlocked -> Locked { lock = getLock(...) } Locked -> Released { releaseLock(lock) } Locked -> Leaked { #end_function() } WhentheControlflowAnalyzerusesthisruletochecktheexamplefunctionabove,thestatema‐chineis initiallyintheUnlockedstate.Whentheprogramacquiresthelockonline2,thestatemachinetransitionstothe Lockedstate,andtherulevariablemapstherulevariable"lock"totheprogramvariable"fileLock"(see belowformorediscussionofrulevariables).Atthebranchonline3,theControlflowAnalyzercopiesthestate machine.Onecopyrunsinthe"true"branchoftheconditional,andtheothercopyrunsinthe"false"branch. Bothcopiesareinitiallyinthe"Locked"state.Whenthecopyrunningonthe"true"branchencountersthe returnstatementonline4,ittransitionstothe"Leaked"state.Because"Leaked"isanerrorstate,theControl flowAnalyzerreportsavulnerability.Meanwhile,thecopyofthemachinerunningonthe"false"branchwill encountertheprogramreleasingthelockonline7andtransitiontotheReleasedstate.Whenthiscopy encountersthereturnstatementonline8,itwillnottransitiontotheerrorstatebecausethereisnotransition fromReleasedtoLeaked. Chapter 5: Custom Control Flow Rules 59 Control Flow Analyzer and Custom Rule Concepts ThissectionprovidesinformationonthefollowingControlflowAnalyzerandruleconcepts: • RulePattern • RuleVariable • RuleBinding Rule Pattern Arulepatternspecifiestheprogramconstructsthatcauseastatetransitiontooccur.Therulepatternsarethe partsenclosedin{ … }. Rule Variable Arulevariableisapartofarulepatternthatisaplaceholderforanactualprogramvalue.Rulevariablestie togethervaluesusedindifferentrulepatterns.InListing57,therulevariable"lock"tiestogetherthereturn valuefromgetLock()andtheparametertoreleaseLock().Withoutthisrulevariable,thestatemachine wouldtransitiontotheReleasedstatewheneveranylockisre‐leased,evenifsomelocksinthefunctionarestill unreleased. Rule Binding Arulebindingisamappingbetweenarulevariableandaprogramvalue(orasetofprogramvalues).In Listing57,theanalyzercreatesarulebindingthattiestherulevariable"lock"tothe"fileLock" which is a local variable. Whentheanalyzerevaluatesotherrulepatternsthatusetherulevariable"lock"the patternonlymatchesiftherulebindingfor"lock"matchestheprogramvalueusedinitsplace. RulevariablesandrulebindingsenabletheControlflowAnalyzertomodelthebehaviorofspecificobjectsinthe program,ratherthanjusttheglobalstateoftheprogram. Listing58showsanexample. Listing 58: Rule Variable and Bindings function useTwoLocks() { Lock lock1 = getLock(); Lock lock2 = getLock(); releaseLock(lock1); return; } Thisfunctionacquirestwolocks,butonlyreleasesoneofthem.Withoutrulevariables,theControlflow Analyzerisnotabletodetectthiserror,becauseitwouldseeonlythat"releaseLock"iscalled,without correlatingthecallsto"getLock"and"releaseLock."WiththerulevariablesinListing58,however,the analyzercorrelatesthesetwocalls. Whentheanalyzerencountersthefirst"getLock"callonline2,itcreatesarulebindingbetweentherule variable"lock"andtheprogramvariable"lock1,"andmovestotheLockedstate.Italsocreatesacopyofthe statemachinethatremainsintheUnlockedstate.Theanalyzerthenencountersthesecondcallto "getLock." ThecopyofthestatemachinethatisintheLockedstateignoresthiscall,becauseitdoesn'tmatchany transitionsoutoftheLockedstate.ThecopythatisintheUnlockedstate,however,doesmatchthiscall.The analyzercreatesasecondrulebindingthatmapstherulevariable"lock"totheprogramvariable"lock2," andthissecondcopyofthestatema‐chinechangestotheLockedstate. Chapter 5: Custom Control Flow Rules 60 InListing58thefirststatemachinetransitionstotheReleasedstate,whilethesecondmachineremainsinthe Lockedstate.Atthereturnstatement,thesecondmachineremainsintheLockedstate,andtheanalyzer reportsanissue. XML Representation of Control Flow Rules TheXMLrepresentationofacontrolflowruleisbasedontherepresentationofavulnerability‐causingrule.In additiontotheelementscommontoallsuchrules,therearesomeXMLtagsthatarespecifictocontrolflowrules orthatareuseddifferentlyincontrolflowrules. TheseXMLtagsare: • Definition • FunctionIdentifiers • FunctionCallIdentifiers • Limits • PrimaryState Definition Thecontrolflowstatemachinedefinitionisenclosedinthe<Definition>tag.InXML,youcanenclosethe contentsofthistagin<![CDATA[ … ]]>toavoidtheneedtoescapeXMLspecialcharactersinthestate machinedefinition. Function Identifiers Likeotherruletypes,controlflowrulesuse<FunctionIdentifier>tagstoidentifyfunctions.Unlikemost otherruletypes,controlflowrulescancontainmultiplefunctionidentifiers.Thisisbecauseastatemachine definedbyacontrolflowrulecanrefertomultiplefunctions.The"id" attributeofthe <FunctionIdentifier>tagspecifiesthenamebywhichyoucanusethefunctionidentifierwithintherule definitions. Function Call Identifiers Functioncallidentifierscombineand<Conditional>tomatchspecificcallstoafunction.The <FunctionCallIdentifier>tagusesidattributesinmuchthesamewayasthe<FunctionIdentifier> tag;the“id”attributeofthefunctionidentifierinsidethefunctioncallidentifierisnotused. Limits Controlflowrulesshouldonlycheckspecificpropertiesincertainfunctions.Forexample,acontrolflowrule couldcheckthateveryfunctioncalledProcessRequestmustcalltheCheckCredentialsfunctionbefore callingthefunctionAccessPrivateData. YoucanpreventthisrulefromrunningonmethodsotherthanProcessRequestbyaddinga<Limit>section totheruledefinition.Inthiscase,the<Limit>tagcontainsoneormore<FunctionIdentifier>tags.Therule willonlyevaluatefunctionsthatmatchoneofthesefunctionidentifiers. Arulewithano<Limit>tagwillrunonallfunctions. Chapter 5: Custom Control Flow Rules 61 Primary State Controlflowstatemachinescontainmultiplestates.Youcandesignateoneofthesestatesastheprimary.When youviewanissue,thetraceelementthatdisplaysfirstisthefirstonethattransitionedintoitsprimarystate. Ifseveralcontrolflowtracestransitionintotheirprimarystateatthesameprogramlocation,theControlflow Analyzerwillgroupthesetracesintoonecontrolflowissue.Thisissuewillcontainmultipletraces. Youspecifytheprimarystatebyputtingthestatenameinsidethe<PrimaryState>XMLtag.Iftheruledoesnot explicitlyspecifyaprimarystate,theerrorstateisprimary. Listing59showsaprimarystateruleexample. Listing 59: Primary State Rule <ControlflowRule formatVersion="3.8" language="java"> <RuleID>6FC83768-C5A0-0E26-044B-59E8A1EBA0BA</RuleID> <VulnCategory>Resource Leak</VulnCategory> <DefaultSeverity>3.0</DefaultSeverity> <Limit> <FunctionIdentifier> <FunctionName> <Value>ProcessRequest</Value> </FunctionName> </FunctionIdentifier> </Limit> <FunctionCallIdentifier id="allocate"> <FunctionIdentifier> <FunctionName> <Value>AllocateResource</Value> </FunctionName> </FunctionIdentifier> <Conditional> <Not><ConstantEq argument="0" value="0"/></Not> </Conditional> </FunctionCallIdentifier> <FunctionIdentifier id="deallocate"> <FunctionName> <Value>ReleaseResource</Value> </FunctionName> </FunctionIdentifier> <PrimaryState>Allocated</PrimaryState> <Definition><![CDATA[ state Unallocated (start); state Allocated; state Deallocated; state Leaked; var resource; Unallocated -> Allocated { resource = allocate(…) } Allocated -> Deallocated { deallocate(resource) } Allocated -> Leaked { #end_scope(resource) } ]]></Definition> </ControlflowRule> Chapter 5: Custom Control Flow Rules 62 Custom Control Flow Rule Scenarios Thissectionprovidesexamplesofcustomcontrolflowrules.Youcanusetheseexamplesasthebasisfor creatingcustomrules.Matchyourrequirementwithoneoftheexamples,andtailortherulestosuiteyour software. • ResourceLeakScenario • NullPointerCheckScenario Scenario Overview ThescenariosinthissectionarewrittenagainstsampleapplicationcalledRichesWealthOnline(RWO).This applicationenablesusestoperformthefollowingonlinebankingoperations: • Transferringmoney • Viewingaccountstatements • Receivingmessagesfromthebank TheRWOapplicationdemonstratesthediverserangeofapplicationsecurityvulnerabilitiesthataretypically encounteredinreal‐worldapplicationsthatprovidefunctionalitysimilartoRWO.Theapplicationisbuiltwith JavaScript,Struts2,Hibernate2,andJavaEnterpriseEdition. EachscenariohighlightsspecificvulnerabilitiesinRWOanddemonstrateshowtoidentifythemusingcustom rules. ThescenariodoesthisbyshowinghowanattackercanexploitvulnerabilitiesinRWOsourcecode.The scenario,whereapplicable,willhighlighthowSCAandtheSecureCodingRulepacksdetectthevulnerability. Thescenariothenexplainsthetypeofcustomrulesnecessarytodetectthevulnerabilityandshowsyouhowto createthem. YoucanthenreproducetheresultsbyanalyzingRWOwitheithertheSecureCodingRulepacksorbyusingthe providedcustomrules.Inordertousetheprovidedcustomrules,youmustfirstdisabletheSecureCoding Rulepacks. Resource Leak Scenario ThisscenariohighlightstherulesthatarenecessaryfortheControlflowAnalyzertodetectresourceleaks.This scenariodemonstrateshowanattackercanexploitaresourceleakvulnerability.Then,itshowshowtheControl flowAnalyzerusescontrolflowrulestoidentifythistypeofvulnerability. Thisscenariohighlightsthefollowingvulnerability: • Poorcodequality:resourceleaks—theprogramcanpotentiallyfailtoreleaseasystemresource. Thisscenariohighlightsthefollowinganalysisandruleconcepts: • Controlflowrules • Finitestatemachines • Non‐returningrules • #endscopeoperator • #ifblockoperator Chapter 5: Custom Control Flow Rules 63 Source Code Anattackerexploitsaresourceleakvulnerabilityasalogicaldenial‐of‐serviceattack.Imaginecodethatusesa scarcesystemresourceandcontainsaresourceleak.Theattackerdepletestheassociatedresourcebyexecuting thecoderepeatedly.Thisleadstoresourcedepletionthatpreventslegitimateusersfromusingtheservice. ThecodeinListing60containsmanyresourceleaks.Itillustrateshowtheapplicationtypicallysetsupa connectiontoitsdatabaseandperformssomequeryfornecessarydata.Thisparticularmethodretrieves detaileddataaboutalistofrolesandreportstheonesthathaveadministrativeprivileges: Listing 60: Original Debug Code: Contains Resource Leaks public static void debugAdminRoles(List roles) throws Exception { boolean auth = false; Connection conn = null; Statement statement = null; ResultSet rs = null; try { conn = ConnFactory.getInstance().getConnection(); statement = conn.createStatement(); for (int index=0; index < roles.size(); index++) { int roleid = ((Integer)roles.get(index)).intValue(); rs = statement.executeQuery("SELECT rolename FROM auth WHERE roleid = " + roleid); rs.next(); if (rs !=null && rs.getString("rolename").equals("admin")) { System.err.println("Roleid: "+roleid+" is an admin"); rs.close(); rs = null; } } }catch(Exception e) { if (rs != null) { rs.close(); rs = null; } throw e; } finally { System.err.println("Terminating here temporarily"); System.exit(-1); if (statement != null) { statement.close(); statement = null; } } } First,thecodecreatesaconnectionobjectbasedonanexistingHibernatedatabaseconnection.Then,thecode createsastatementobjectusingthenewconnectionobject.Finally,thecodeexecutesthestatementobject's querymethodthatreturnsaresult‐setobject.Afterwards,thecodeneedstofreealloftheassociatedresources byclosingtheconnection,statement,andresult‐setobjects. Thecodefailstoclosetheseobjectsunderallconditions.Thecodeneverclosestheconnectionobjectunderany conditions.Also,thecodeattemptstoclosethestatementobjectwithinthefinallyblock.However,thecode executestheSystem.exit()methodfirstandtheStatement.close()methodisneverreached.Finally,the codedoesnotclosetheresult‐setobjectwhentheroleisnotanadministratorandanexceptiondoesnotoccur. Chapter 5: Custom Control Flow Rules 64 Source Code TheControlflowAnalyzerusesanobject'sfinitestatemachine(FSM)toidentifyunsafesequencesof operationsthatshouldnotbeperformedonthatobject. Figure6describesthepossiblestatesofanobject. Figure 6: Dynamically Allocated/Deallocated Object States First,theanalyzerallocatesaseparateFSMforeachobject.Then,theanalyzersetstheobject'sinitialstateas unallocatedbeforecodeallocatestheobject.Oncecodeallocatesanobject,theanalyzerupdatestheobject's FSMstatetotheallocatedstate.Then,theanalyzerexaminesallcodepathsthatarewithintheobject'sscope. Theanalyzerencountersacodepathwherethecodecallstheobject'sclose()method.Insuchacase,the analyzerupdatestheobject'sFSMstatetothesafereleasedstate.Eventually,theobjectfallsoutofscope.This particularcodepathcorrectlyreleasestheresourceandnovulnerabilityexists.Theanalyzerwillnotreporta vulnerabilityforthispathbecausetheobjectfallsoutofscopeinasafestate. Theanalyzerencounterscodepathswheretheobjectfallsout‐of‐scopeandthecodehasnotpreviouslycalled theobject'sclose()method.Insuchacase,theanalyzerupdatestheobject'sFSMstatetotheunsafeleaked state.Theanalyzerreportsthevulnerabilitybecausetheanalyzerhasexplicitlysettheobject'sFSMstatetoan unsafestate. TheruleinListing60describestheFSMmodelthatappliesforthesafeandunsafeallocationofthe Connection,Statement,orResultSetobjects. Chapter 5: Custom Control Flow Rules 65 Listing 61: Control Flow Rule: Resource Leak <ControlflowRule formatVersion="3.8" language="java"> <RuleID>84C341ED-9917-4901-A792-C93E6D72C5A6</RuleID> <VulnCategory>Unreleased Resource</VulnCategory> <DefaultSeverity>3.0</DefaultSeverity> <Description/> <FunctionIdentifier id="resource1"> <NamespaceName> <Pattern>javax\.sql</Pattern> </NamespaceName> <ClassName> <Pattern>DataSource</Pattern> </ClassName> <FunctionName> <Pattern>getConnection</Pattern> </FunctionName> <ApplyTo implements="true" </FunctionIdentifier> <FunctionIdentifier id="resource2"> <NamespaceName> <Pattern>java\.sql</Pattern> </NamespaceName> <ClassName> <Pattern>Connection</Pattern> </ClassName> <FunctionName> <Pattern>createStatement</Pattern> </FunctionName> <ApplyTo implements="true" </FunctionIdentifier> <FunctionIdentifier id="resource3"> <NamespaceName> <Pattern>java\.sql</Pattern> </NamespaceName> <ClassName> <Pattern>Statement</Pattern> </ClassName> <FunctionName> <Pattern>executeQuery</Pattern> </FunctionName> <ApplyTo implements="true" </FunctionIdentifier> <FunctionIdentifier id="release1"> <NamespaceName> <Pattern>java\.sql</Pattern> </NamespaceName> <ClassName> <Pattern>Connection</Pattern> </ClassName> <FunctionName> <Pattern>close</Pattern> </FunctionName> <ApplyTo implements="true" Chapter 5: Custom Control Flow Rules 66 Listing 61: Control Flow Rule: Resource Leak (Continued) </FunctionIdentifier> <FunctionIdentifier id="release2"> <NamespaceName> <Pattern>java\.sql</Pattern> </NamespaceName> <ClassName> <Pattern>Statement</Pattern> </ClassName> <FunctionName> <Pattern>close</Pattern> </FunctionName> <ApplyTo implements="true" </FunctionIdentifier> <FunctionIdentifier id="release3"> <NamespaceName> <Pattern>java\.sql</Pattern> </NamespaceName> <ClassName> <Pattern>ResultSet</Pattern> </ClassName> <FunctionName> <Pattern>close</Pattern> </FunctionName> <ApplyTo implements="true" </FunctionIdentifier> <Definition> <![CDATA[ state unallocated (start); state allocated; state released; state leaked (error); var c; unallocated -> allocated{ c = resource1(...) | c = resource2(...) | c = resource3(...) } allocated-> released { c.release1(...) | c.release2(...) | c.release3(...) | #ifblock(c == null, true) } allocated-> leaked { #end_scope(c) } ]]> </Definition> </ControlflowRule> Theruledeclarestheinitialstateunallocatedusingtheadditional(start)keyword.Also,theruledeclaresthe unsafeleakedstateusingtheadditional(error)keyword.EachmethodthatallocatesaConnection, Statement,orResultSetobjectshasaseparatefunctionidentifierelementresource1,resource2,or resource3.Thecorrespondingmethodsforreleasingtheseobjectsareidentifiedasrelease1,release2,and release3.Theanalyzertransitionsbetweenthedeclaredstatesforagivenobjectbasedondeclaredconditions intherulesuchastheexecutionofthedeclaredfunctions. Thecondition#endscope(x)describesthespecialcircumstancewheretheobject xhasexitedscopeandis nolongeraccessible.Inthisrule,theobjecthasbeenallocatedintheallocatedstate.Itreachestheerrorstate leakediftheobjectfallsoutofscopeandisintheallocatedstateatthetime. Thecondition#ifblock(x == y,z)describesthepresenceofanif‐blockstatementwithinthecode.Itstates thatifxequalsywitharesultofz,theconditionissatisfiedandtheanalyzershouldtransitiontothedeclared state.Inthisrule,theconditional'#ifblock(c, null, true)'describesanequalitycomparisonbetweenthe trackedobjectcandthevaluenull.Ifcisequaltonull,codedidnotsuccessfullyallocateobject c.The analyzershouldsafelytransitiontheobjectctoitssafestatereleasedasitisimpossiblefortheobjecttoleak resources. Thereisaleakthattheanalyzerdoesnotcorrectlyidentifyusingjustthisrule.Thecodedeallocatesthe StatementobjectwithinthefinallyblockafteritcallstheSystem.exit()method.Thecodeneverdeallocates Chapter 5: Custom Control Flow Rules 67 theobjectcorrectlybecausetheSystem.exit()methodprematurelyexitsthecode.Theallocatedobject reachestheend‐of‐scopeconditionprematurely. Theanalyzerneedsspecialknowledgeofmethodsthatprematurelyforceanout‐of‐scopecondition.Otherwise, theanalyzercannotalwaysidentifywhencodeforcesanend‐of‐scopecondition.Thenon‐returningrulein Listing62describesthisspecialqualityoftheSystem.exit()method: Listing 62: Non returning rule for System.exit() method <NonReturningRule formatVersion="3.8" language="java"> <RuleID>775F5047-856C-4874-92A0-ADCE882AE4BB</RuleID> <FunctionIdentifier> <NamespaceName> <Pattern>java\.lang</Pattern> </NamespaceName> <ClassName> <Pattern>System</Pattern> </ClassName> <FunctionName> <Pattern>exit</Pattern> </FunctionName> </FunctionIdentifier> </NonReturningRule> WhenSCAincludesthenon‐returningruleandcontrolflowrulesinascan,theControlflowAnalyzeridentifies thattheStatementobjectisnotproperlydisposedofbeforeitreachesitsprematureend‐of‐scopecondition. Null Pointer Check Scenario ThisscenariohighlightsrulesthatenabletheControlflowAnalyzertodetectmissingnullpointercheck vulnerabilities.Thescenariodemonstrateshowtoexploitamissingnullpointercheckvulnerability.Thenit illustrateshowtheControlflowAnalyzerusesrulestoidentifythistypeofvulnerability. Thisscenariohighlightsthefollowingvulnerability. • Missingcheckagainstnull—theprogramcandereferenceanullpointerbecauseitdoesnotcheckthe returnvalueofafunctionthatmightreturnnull. Thisscenariohighlightsthefollowinganalysisandrulesconcepts: • Errorstate • Finitestatemachine • Startingstate Chapter 5: Custom Control Flow Rules 68 Source Code Theapplicationcontainsamissingnullpointercheckwithinitsmessagingservice.Anattackercansubmita requesttodisplayamessageandomitnecessarypiecesofinformationfromtherequest.Theapplication throwsanexception,anddisclosesarchitectureandconfigurationinformationtotheattacker. Listing63showsJSPcodefromtheapplicationthatretrievesanddisplaysamessage. Listing 63: JSP: Displays E‐mails and Contains a Missing Null Check Vulnerability <% String incomingParameter = request.getParameter("id"); Long decodedParameter = Long.decode(incomingParameter.trim()); Message msg = (Message)(MessageService.getMessage(decodedParameter).get(0)); pageContext.setAttribute("severity" msg.getSeverity()); pageContext.setAttribute("sender" msg.getSender()); pageContext.setAttribute("subject" msg.getSubject()); pageContext.setAttribute("body, msg.getBody()); %> ... Toviewamessage,theuser'sbrowsersubmitsaHTTPrequestonbehalfoftheuser: http://localhost:8080/riches/pages/content/ViewMessage.jsp?id=1 Toexploitthemissingnullcheckvulnerability,theattackersubmitsamodifiedHTTPrequest: http://localhost:8080/riches/pages/content/ViewMessage.jsp TheidparameterisnolongerpresentandtheincomingParametervariableissettonull.Then,theJSPcode callsincomingParameter.trim()andanullpointerexceptionoccurs.Finally,theframeworksendsthe unhandledexceptionandothersensitiveinformationtotheattacker'sbrowser. Rules Theapplicationcontainsamissingnullpointercheckwithinitsmessagingservice.Anattackercansubmita requesttodisplayamessageandomitnecessarypiecesofinformationfromtherequest.Theapplication throwsanexceptionanddisclosessensitiveinformationtotheuserpertainingtoitsarchitectureand configuration. Figure7showsJSPcodefromtheapplicationthatretrievesanddisplaysamessage. Chapter 5: Custom Control Flow Rules 69 Figure 7: Proposed FSM Model: Describes Missing Null Checks InFigure7,theControlflowAnalyzerwillsettheFSMstateto'may be null'whenitobservesthattheJSP codeassignsavaluetotheincomingParametervariable.Atthispoint,thecodehasnotyetverifiedthatthe variable'svalueisnotnull. Then,theanalyzerobservesthatthecodecallsamethodontheincomingParametervariablewithout inspectingitsvalue.Theanalyzertransitionsthevariable'sFSMfromthe'may be null'statetothe 'dereferenced'errorstate.TheanalyzerreportsthevulnerabilitywhenittransitionstheFSMintotheerror state. Ideally,thecodeshouldhaveinspectedtheobject'svaluebeforeusingit.Theanalyzerwouldthenobservethat thecodeperformsthischeckandwouldtransitiontheobject'sFSMfromthe'may be null' statetothe 'checked'safestate. Listing64describestheFSMmodelasacontrolflow. Chapter 5: Custom Control Flow Rules 70 Listing 64: Null PointerDereference Detection Rule <ControlflowRule formatVersion="3.8" language="java"> <RuleID>4A2D77FD-C901-4F22-9994-23330BC56D96</RuleID> <VulnCategory>Missing Check against Null</VulnCategory> <DefaultSeverity>3.0</DefaultSeverity> <Description/> <FunctionIdentifier id="get"> <NamespaceName> <Pattern>javax\.servlet</Pattern> </NamespaceName> <ClassName> <Pattern>ServletRequest</Pattern> </ClassName> <FunctionName> <Pattern>getParameter</Pattern> </FunctionName> <ApplyTo implements="true" </FunctionIdentifier> <FunctionIdentifier id="any"> <NamespaceName> <Pattern>.*</Pattern> </NamespaceName> <ClassName> <Pattern>.*</Pattern> </ClassName> <FunctionName> <Pattern>.*</Pattern> </FunctionName> </FunctionIdentifier> <Definition> <![CDATA[ state start (start); state mayBeNull; state checked; state dereferenced (error); var f; start -> mayBeNull { f = $get(...) } mayBeNull -> checked { #compare(f, null) } mayBeNull -> dereferenced { f.$any(...) | *f } ]]> </Definition> </ControlflowRule> TheanalyzerinitializestheFSMinthestartstatestart.ThetransitionfromthestartstatetothemayBeNull stateoccurswhentheanalyzerobservesacalltoafunctionmatchedby$get,andtheFSMisboundtothevalue returnedbythatfunction. TheanalyzerwilltransitiontheFSMfromthemayBeNulltocheckedstatewhenitencounterscodethat comparesthevaluetonull.The#compare(f,null)statementdescribesthistransition. Alternatively,theanalyzerwilltransitiontheFSMfromthemayBeNullstatetothedereferencederrorstateif codedereferencesthevaluewhileinthisstate.Thestatementallocated -> used { f.$any(...) | *f } describesthistransition. Chapter 5: Custom Control Flow Rules 71 Chapter 6: Custom Content and Configuration Rules Thischapterprovidesthefollowingtopics: • UnderstandingContentAnalyzerandCustomRules—usethissectiontolearnaboutthecontentanalyzer andhowitusescustomrulestofindsecurityissues. • UnderstandingConfigurationAnalyzerandCustomRules—usethissectiontolearnabouttheConfiguration Analyzerandhowitusescustomrulestofindsecurityissues. • XMLRepresentationofContentRules—usethissectiontolearnhowyoucanrepresentcontentrulesinXML. • XMLRepresentationofConfigurationRules—usethissectiontolearnhowyoucanrepresentconfiguration rulesinXML. • CustomContentandConfigurationRuleScenarios—usethissectiontolearnhowtocreatecustomcontent andconfigurationrules. Understanding Content Analyzer and Custom Rules ThecontentanalyzerfindssecurityissuesandpolicyviolationsinHTMLcontent.InadditiontostaticHTML pages,thecontentanalyzerperformsthesechecksonfilesthatcontaindynamicHTML,suchasPHP,JSP,and classicASPfiles. ContentanalyzerrulesuseXML‐XPATHnotationtodescribeproblematicconstructsinHTMLfiles.Thecontent analyzerconvertstheHTMLcontentintoanXMLformandappliestheXPathrulestothisXMLform. Understanding Configuration Analyzer and Custom Rules TheConfigurationAnalyzerfindssecurityissuesinapplicationconfigurationfiles.Thisanalysiscanfind instanceswhereanapplicationisconfiguredinsecurely,andcanalsoenforcesecuritypoliciesbyidentifying configurationfilesthatarenotincompliancewiththosepolicies. ConfigurationAnalyzerrulesspecifyconstraintsonconfigurationproperties. TheConfigurationAnalyzerunderstandsXMLfilesandJavapropertiesfiles.Eachruleoperatesononetypeof file.RulesthatanalyzeXMLfilesuseXPathnotationtodescribeXMLconstructsthatshouldbereportedbythe analyzer.Rulesthatanalyzepropertiesfilesspecifyeitherpropertynamesorpropertyvaluesthatshouldbe reported.Rulesofeithertypecanberestrictedtorunonlyonfileswithspecificnames. XML Representation of Content Rules InadditiontotheXMLelementscommontoallvulnerability‐producingrules,rulesforthecontentanalyzer containan<XPathMatch>element.The"expression"attributeofthiselementspecifiestheXPathexpression thattheConfigurationAnalyzerevaluatesagainsttheXMLrepresentationofHTMLdocuments. Listing65showstheexpressionattributeforcontentrules. Listing 65: Expression Attribute <ContentRule formatVersion="3.8"> <RuleID>941E1563-D3A2-B73D-10D1-8C035CCCDE66</RuleID> <VulnCategory>Form Definition</VulnCategory> <DefaultSeverity>2.0</DefaultSeverity> <XPathMatch expression="//*[local-name()='form']"/> </ContentRule> Chapter 6: Custom Content and Configuration Rules 72 XML Representation of Configuration Rules RuleswrittenfortheConfigurationAnalyzercheckeitherXMLorpropertiesfiles.Bothtypesofconfiguration rulesshareelementsthatarecommontoallvulnerability‐findingrules.Configurationrulesalsohaveasequence of<Check>XMLtags. Each<Check>tagspecifiesthepropertiesandfilesthattheConfigurationAnalyzerchecks.Thecontentsofthe <Check>tagvariesdependingonthetypeoffilethattheConfigurationAnalyzerischecking. Every<Check>tagcontainsa<ConfigFile>tagthatspecifiesthefilesforwhichthecheckapplies.The <ConfigFile>taghasa"type"attributethatmustbesettoeither"xml"or"properties."Thisdefinesthe typeofconfigurationfileforwhichthecheckshouldbeperformed.The<ConfigFile>tagalsocontainsa <Value>or<Pattern>tagthatischeckedagainstthefilenameofeveryfileofthespecifiedtype.Thecheck willonlybeappliedtofilesforwhichthefiletypematchesthe"type"attributeandthefilenamematchesthe <Value>or<Pattern>insidethe<ConfigFile>tag. ForXMLfiles,the"type"attributeofthe<ConfigFile>tagshouldbesetto"xml."The<Check>tagmust alsocontainan<XPathMatch>tag.Thistagisidenticaltotheoneusedincontentrules. Listing66showstypeattributesforconfigurationrules. Listing 66: Type Attribute <ConfigurationRule formatVersion="3.8"> <RuleID>8104EB17-C54C-7F22-C308-42C207C74BBD</RuleID> <VulnCategory>Servlet Mapping</VulnCategory> <DefaultSeverity>2.0</DefaultSeverity> <Check> <ConfigFile type="xml"> <Value>web.xml</Value> </ConfigFile> <XPathMatch expression="//servlet-mapping"/> </Check> </ConfigurationRule> Forpropertiesfiles,the"type"attributeofthe<ConfigFile>tagshouldbesetto"properties."The <Check>tagmustcontaina<NameMatch>tagthatspecifiesthepropertynametobechecked.The<Check>tag mayalsoincludeeithera<ValueMatch>tagora<NotPresent>tag.The<ValueMatch>tagspecifiesa <Pattern>or<Value>thatshouldbecheckedagainstthevalueofpropertieswhosenamematchesthe <NameMatch>tag.The<NotPresent>tag,whichhasnocontents,specifiesthattheanalyzershouldreportan issueifnopropertymatchingthe<NameMatch>tagappearsinapropertiesfilematchedbythe<ConfigFile> tag. Chapter 6: Custom Content and Configuration Rules 73 Listing67showsanameorvaluematchexample. Listing 67: Name or Value Match <ConfigurationRule formatVersion="3.8"> <RuleID>FEC3D9F0-F29A-231B-3BD5-765CCEAF1CE5</RuleID> <VulnCategory>Security Not Enabled</VulnCategory> <DefaultSeverity>5.0</DefaultSeverity> <Check> <ConfigFile type="properties"> <Value>security.properties</Value> </ConfigFile> <NameMatch><Value>security</Value></NameMatch> <ValueMatch><Value>security</Value></ValueMatch> </Check> <Check> <ConfigFile type="properties"> <Value>security.properties</Value> </ConfigFile> <NameMatch><Value>security</Value></NameMatch> <NotPresent/> </Check> </ConfigurationRule> Custom Content and Configuration Rule Scenarios Thissectionprovidesexamplesofcustomconfigurationrules.Youcanusetheseexamplesasthebasisfor writingcustomrules.Matchyourrequirementwithoneoftheexamples,andtailortherulestosuityour software. • CustomRuleScenarioOverview • PropertyFileScenario • TomcatFileScenario Custom Rule Scenario Overview ThescenariosinthissectionarewrittenagainstsampleapplicationcalledRichesWealthOnline(RWO).This applicationenablesusestoperformthefollowingonlinebankingoperations: • Transferringmoney • Viewingaccountstatements • Receivingmessagesfromthebank TheRWOapplicationdemonstratesthediverserangeofapplicationsecurityvulnerabilitiesthataretypically encounteredinreal‐worldapplicationsthatprovidefunctionalitysimilartoRWO.Theapplicationisbuiltwith JavaScript,Struts2,Hibernate2,andJavaEnterpriseEdition. EachscenariohighlightsspecificvulnerabilitiesinRWOanddemonstrateshowtoidentifythemusingcustom rules. ThescenariodoesthisbyshowinghowanattackercanexploitvulnerabilitiesinRWOsourcecode.The scenario,whereapplicable,willhighlighthowSCAandSecureCodingRulepacksdetectthevulnerability.The scenariothenexplainsthetypeofcustomrulesnecessarytodetectthevulnerabilityandshowsyouhowto createthem. YoucanthenreproducetheresultsbyanalyzingRWOwitheitherSecureCodingRulepacksorbyusingthe providedcustomrules.Inordertousetheprovidedcustomrules,youmustfirstdisableSecureCoding Rulepacks. Chapter 6: Custom Content and Configuration Rules 74 Property File Scenario ThisscenariodemonstratestherulesthatenabletheConfigurationAnalyzertodetectconfiguration vulnerabilities.Thescenarioillustratesthewayhowincorrectsettingcanleadtounexpecteddowntimeina productionenvironment.ThenitshowshowtheConfigurationAnalyzerusesrulestoidentifyandreportthese incorrectsettings. Thisscenariohighlightsthefollowingvulnerability: • Environmentmisconfiguration—configurationfilesforanapplicationcontainincorrectvaluesina productionenvironment.Thesemisconfigurationstypicallyintroduceothervulnerabilities,includingthose relatedtocommunicationsecurity,authentication,authorization,datasecurity,andexceptionhandling. Thisscenariohighlightsthefollowinganalysisandruleconcepts: • Configurationrules • Javaregularexpressions • Propertyfiles Source Code Byconvention,usersshouldsendandreceivemessagesthroughthegatewayoftheproductionmailsystem.In testcases,however,thesystemroutesmessagesthroughthegatewayofthetestenvironment.Inthisscenario, theincorrectSMTPsettingarereleasedintotheproductionenvironment. Listing68showsthesampleSMTPconfiguration. Listing 68: Incorrect SMTP Configuration File Released into Production riches.mail.smtpHostname = mail.test.riches.com riches.mail.smtpPort = 25 riches.mail.username = test riches.mail.password = passw0rd1! Afterloadingtheseincorrectvalues,themailhandlingcodesendsmessagesthroughmail.test.riches.com insteadoftheproductiongateway. Rules Listing69showstheconfigurationrulethatdetectstheinvalidSMTPhostnamevalueinthepropertiesfile: Listing 69: Incorrect Configuration Detection Rule <ConfigurationRule formatVersion="3.8"> <RuleID>B8319D1B-65B3-4BFA-A0BE-8F1891D727E9</RuleID> <VulnCategory>J2EE Misconfiguration</VulnCategory> <DefaultSeverity>3.0</DefaultSeverity> <Description/> <ConfigFile type="properties"> <Value>mailserver.legacy.properties</Value> </ConfigFile> <PropertyMatch> <NameMatch> <Value>riches.mail.smtpHostname</Value> </NameMatch> <ValueMatch> <Pattern caseInsensitive="true">(.*)\.test.riches.com'/Pattern> </ValueMatch> </PropertyMatch> </ConfigurationRule> Chapter 6: Custom Content and Configuration Rules 75 Theconfigurationruletargetsthemailserver.legacy.propertiespropertiesfile.Itcomparesthevalueofthe propertyriches.mail.smtpHostnametotheJavaregularexpression'(.*)\.test.riches.com'.Thevalue shouldnevermatchastringwiththefollowingsequence:zeroormorecharacters;aperiod;andthenthe characters'test.riches.com'.Ifthissequenceoccurs,theConfigurationAnalyzeridentifiesaconfiguration vulnerability Tomcat File Scenario ThisscenariohighlightstherulesthatenabletheConfigurationAnalyzertoidentifyspecificconfiguration vulnerabilities.Thescenariodemonstrateshowamisconfigurationintheapplicationcanleadtothedisclosure ofsensitiveinformation.ItthenshowsthehowtheConfigurationAnalyzerusesrulestoidentifythistypeof misconfiguration. Thisscenariohighlightsthefollowingvulnerability: • J2EEMisconfiguration—theunderlyinginfrastructuresupportingtheapplicationisimproperlyconfigured. Thisresultsinnewvulnerabilitiesrelatedtocommunicationsecurity,datasecurity,andexceptionhandling. Thisscenariohighlightsthefollowinganalysisandrulesconcepts: • Configurationrules • Javaregularexpressions • XMLfiles • XPathexpressions Source Code TheapplicationisdeployedinaTomcatWebserversharedbymultipleapplications.Someoftheapplications relyontheservertoauthenticateincomingrequests.TheTomcatconfigurationfilecontainsarealmthat describestheauthenticationconfigurationofanotherapplication. Listing 70: Incorrect Configuration Detection Rule <Realm className="org.apache.catalina.realm.JAASRealm" appName="RichesDiscover" userClassNames="com.fortify.samples.riches.security.UserPrincipal" roleClassNames="com.fortify.samples.riches.security.RolePrincipal" debug = "3"/> Therealmdescriptoraboveapplicationusesanauthenticationconfigurationwithadebuglevelgreaterthan two.Withthisconfiguration,theauthenticationservicewilllogusernamesandpasswordsinaplaintextlogfile, whichcancompromisetheirsecurity. Chapter 6: Custom Content and Configuration Rules 76 Rule Listing71showsarulethatidentifiesanXMLdocumentthatcontainsanodeRealmwithadebugattribute's valuesettoanumbergreaterthantwo. Listing 71: Configuration Rule: Identifies Misconfigured Realm <ConfigurationRule formatVersion="3.8"> <RuleID>E9E3B4F0-CBDA-4695-94FD-3D41D68D19CB</RuleID> <VulnCategory>J2EE Misconfiguration</VulnCategory> <DefaultSeverity>3.0</DefaultSeverity> <Description/> <ConfigFile type="xml"> <Pattern>(.*)\.xml</Pattern> </ConfigFile> <XPathMatch expression="count(//Realm[@debug > 2]) > 0" reporton="// Realm[@debug > 2]/@debug"/> </ConfigurationRule> TheXPathexpression'//Realm[@debug > 2])'describestheXMLcontentnecessaryfortheConfiguration Analyzertoidentifythemisconfiguration. TheexpressionidentifiesanyRealmelementsthathaveadebugattributewithvaluegreaterthantwo.The <XPathMatch reporton>conditionspecifiesthatSCAshouldhighlighttheproblematicdebugattribute insteadoftheparentrealmelement. Chapter 6: Custom Content and Configuration Rules 77 Chapter 7: Structural Rules Language Reference Thisdocumentprovidesthefollowingtopics: • SyntaxandGrammar—usethissectionasareferenceforstructuralrulesyntaxandgrammar. • Types—usethissectiontounderstandthetypesystemusedbystructuredrules. Syntax and Grammar ThefollowingisasimplifiedBNF‐stylegrammarfortheStructuralTreeQueryLanguage.Notethatfor readabilitypurposesitisinsomecasesmoreandinsomecaseslessstrictthantheactualgrammar. Listing72showsthestructuraltreequerylanguage. Listing 72: Structural Tree Query Language <Rule> := <Label> <Expression> <Label> := <TypeName> [ <Identifier> ] ':' <Expression> := <Literal> | <Reference> | <RelationExpression> | 'not' <Expression> | <Expression> 'and' <Expression> | <Expression> 'or' <Expression> | '(' <Expression> ')' <Reference> := [ <Reference> '.' ] <Identifier> <RelationExpression> := [ <Reference> | <Literal> ] <Relation> ( <Reference> | <Literal> | <SubRule> ) <Relation> := 'is' | 'in' | 'contains' | 'reachedBy' | 'reaches' | '===' | '==' | '!=' | '<=' | '>=' | '<' | '>' | 'startsWith' | 'endsWith' | 'matches' <SubRule> := '[' [ <Label> ] <Expression> ']' [ '*' ] <Literal> := 'true' | 'false' | <StringLiteral> | <NumberLiteral> | <TypeSignatureLiteral> <StringLiteral> := '"' <Text> '"' <NumberLiteral> := ('0'-'9')+ <TypeSignatureLiteral> := 'T' '"' <Text> '" Types Theruleslanguageisstronglytyped.Typesintheruleslanguagearecalledstructuraltypestodistinguishthem fromthelanguagetypesofthesourcelanguage.Thetypesareorganizedintoahierarchywithsourcecode constructsorganizedundertheConstructbase.Everytypeinheritsthepropertiesofeachofitsancestors. Eachpropertyhasafixedresolutiontype.Asaresult,thestructuraltypeofeverysubexpressionintherules languageisknownduringrulesspecification.Statictype‐checkingisperformedwhenaruleisloaded. Forafullreferenceforthestructuraltypehierarchy,seetheStructuralTypeandPropertiesReference. Thestructurallanguagealsosupportslistsofobjects.Theseobjectsdonothaveofficialtypenames.Thismeans thattheycannotappearasthesubjectofarule.However,propertiescanstillresolvetolists.Theanalyzercan accesslistsusingthecontainsandinrelations,justlikeconstructs.Forexample,theFunctionconstructhasa propertyparamaterTypesthatreturnsalistofTypeobjects. Chapter 7: Structural Rules Language Reference 78 Listing73showsarulethatmatchesfunctionsthathaveanyparameteroftypeint. Listing 73: Int Type Matching Rule Function f: f.parameterTypes contains [Type t: t.name = "int"] Thisruleisinterpretedasthefollowingquery:Selectanyfunctionffromthestructureoftheprogram,inwhich theparametersoftypef containanytypeof“int”. Youcanalsoreferencewithzero‐basedindexnotation,usingstandard,bracketedaccessors. Listing74showsarulethatmatchesfunctionsinwhichthefirstparameterhastype “int.” Listing 74: Zero‐Based Index Notation Function: parameterTypes[0] == T"int" T"…"denotesaspecialtypeofconstantinthestructurallanguage.Itprovidesaconvenientwaytoinspect languagetypes.Whenthestructuralevaluatorencounterssuchaconstantitconvertsthestringbetweenthe quotesintoastructuralTypeSignatureobject(whichiscomparablewithType)usingtherulesofthesource codelanguagebeingexamined(Java,C,andsoon). Properties TheStructuralTypeandPropertiesReferenceprovidesalistofallpropertiesrecognizedbythestructural analyzer.Allstructuraltypes,includinglistsandprimitivestructuraltypes,haveassociatedproperties.Every typeinheritsthepropertiesofeachofitsancestors.Listtypeshaveonlyoneproperty,length,whichrepresents thenumberofitemsinthelist. Propertiesoftenresolvetosubtypesoftheirdeclaredtypes. Listing75showsanexample. Listing 75: Java Code x = 30; ThistranslatestoanAssignmentStatementinthestructuraltree. Inthestructuralruleslanguage,youcanexamineanassignment'sright‐handsideusingtheproperty AssignmentStatement.rhs,whichnominallyresolvestoanExpression.Inthiscaseitresolvestoan IntegerLiteral,asubtypeofLiteralwhichisitselfasubtypeofExpression. Listing76showsarulethatmatcheseveryassignmenttherighthandsideofwhichhasthelanguagetypeint. Listing 76: Matching Rule AssignmentStatement a: a.rhs.type == T"int" YoucanusethisrulebecausetypeisapropertyofallExpressionobjects.Butifyouwanttomatchevery assignment,theright‐handsideofwhichistheintegerliteral30,youmustcastAssignmentStatement.rhsusing asubrule. Chapter 7: Structural Rules Language Reference 79 Listing77showsasubrulethatcastsanAssignmentStatement.rhs. Listing 77: Matching Rule AssignmentStatement a: a.rhs is [IntegerLiteral n: n.value == 30] ThisisbecausevalueisnotapropertyofExpression.Tomaintaintype‐safety,youmustassertthatrhs actuallyisanIntegerLiteralbeforeyoucanaccessthepropertyvalue. Reference Resolution AReference(seeSyntaxandGrammar)isanIdentifierorchainofidentifiersconnectedbydotswhichresolves toalabeledobjectorapropertyofanobject.Resolutionofthefirstidentifierfollowstherulesdescribedhere. Subsequentidentifiersinthereferencearealwayspropertiesoftheinnerobject. Toresolvethefirstidentifieridentinareference,thestructuralevaluatorfirstcheckstoseeifidentappearsina LabelintheenclosingSubRule,inaparentSubRule,orintheinitialLabelwhichstartstheRule. Listing78showsaruleinwhichfandvareresolvedbyexaminingthelabelsfortheenclosingcontexts. Listing 78: f and v Resolution Rule Function f: f contains [Variable v: v.name == f.name] Inthecasethatidentdoesnotresolvetoalabeledobject,identisresolvedasapropertyoftheobjectselectedby theimmediatelyenclosingsubrule(ortheruleitselfifidentdoesnotappearinasubrule). Listing79showsandexampleinwhich,nameresolvesinbothcasestothenameofthefunction. Listing 79: Name Resolution Example1:Function: name == "func" Example 2: Variable v: v in [Function: name == "func"] Chapter 7: Structural Rules Language Reference 80 Null Resolutions Somepropertiesarevalidonlyforcertaininstancesofastructuraltype.Forexample,TryBlockhasaproperty, finallyBlock,whichresolvestotheassociatedfinallyblockofatryblock.However,notalltryblockshave associatedfinallyblocks. Inthesecases,propertiesresolvetonull.Thereisnoneedforrulestocheckforthis,becausetheStructural Analyzerhandlesoperationsonnullinawell‐definedmanner: • Everypropertyofnullresolvestonull • Everysubrulerelationonanullobjectresolvestofalse Listing80showshowBooleanconnectivesresolve. Listing 80: Boolean Connectives Resolution null null null null null null and null -> null or null -> null and true -> null or true -> true and false -> false or false -> null IftheBooleanvalueisdeterminate,itisresolved;otherwiseitisnull. Relations Youcanusetheequalityandinequalityrelations,==and!=,tocompareanytwoobjectsrecognizedbythe StructuralAnalyzer.Forequalitytohold,thestructuraltypesoftheobjectsmustagree.Equalityhastheobvious meaningforprimitivestructuraltypes;forconstructs,theconditionisthatthetwoobjectsmustbestructurally identical. TheStructuralAnalyzerconfirmsthestructuralidentityinoneoftwoways: • TheStructuralAnalyzerconfirmsdeclarationsbycomparingthecanonicalnamesofthesymbols. • TheStructuralAnalyzerconfirmsotherconstructsbycomparingtheunderlyingnodesintheprogram representation.Listsareequaliftheyenumerateequalelementsinthesameorder. Thestrictequalityrelation,===,holdstrueonlyiftheobjectsbeingcomparedarethesameobject. Theorderrelations,<,>,<=,and>=,havetheirusualmeaningsforstrings,numbers,andBooleans.Types, lists,andconstructscannotbecomparedwithorderrelations. Thereareseveralspecialrelations: • ismeansthesamethingas ==,exceptitcanbeusedtoprefaceasubrule. • inandcontainscanbeusedwithstringsandlists,withobviousmeanings.Forotherconstructsthey examineparentandchildrelationships.inwillsearchtheparentandgrandparentsofthenodetothetopof thetree.containswillsearchthechildrenand‐normally‐thegrandchildrenofthenodetothebottomofthe tree.TheexceptiontothisbehaviorisfortheClassandCompilationUnitstructuraltypes,forwhichcontains willonlyexaminethefirstgenerationofchildren(thispreventswritingquerieswhichareunreasonably expensivetoexecute). • startsWith,endsWith,andmatchescanonlybeusedtorelatetwostrings.matchesinterpretstheright‐hand sideoftherelationasaJavaregularexpression,anditistrueonlyiftheleft‐handsideismatchedbythat regularexpression. • reachesandreachedBycanonlybeusedtorelatetwoFunctionsortwoClasses.TheyarediscussedintheCall GraphReachabilitysection. Chapter 7: Structural Rules Language Reference 81 Youcanomittheleft‐handsideofanyoftheserelations.Ifyouomitthem,theleft‐handsidedefaultstothe constructthattheruleiscurrentlymatching. Listing81showsarulethatmatchesanyclassthathasapropersuperclass. Listing 81: Class Matching Super Class Rule Class c: c.supers contains [Class c2: c2 != c] BecausesupersresolvestoaClass[],youcanabbreviatetheruleinListing81totheruleprovidedin Listing82. Listing82showsanabbreviatedclassmatchingsuperclassrule. Listing 82: Abbreviated Class Matching Super Class Rule Class c: supers contains [!= c] AlthoughtheversionprovidedinListing81ismorecompact,theversioninListing80greaterclarityandis morereadabletohumans. Results Reporting RecalltheexampleinListing83,whichmatchesreturnstatementsthatappearinsideafinallyblock. Listing 83: Return Statement Example 1 ReturnStatement r: r in [FinallyBlock:] TheruleinListing84issimilar. Listing 84: Return Statement Example 2 FinallyBlock f: f contains [ReturnStatement:] However,therearetwosignificantdifferences.First,ifasinglefinallyblockcontainsmultiplereturnstatements, theruleinListing84willgeneratemultiplevulnerabilitieswhiletheruleinListing84willproducejustone. Theseconddifferenceisthewayinwhichtherulesreportvulnerabilities.Theprimarysourcelocation,as reportedintheanalysisoutput,alwayspointstotherule'soutermostconstruct.TheruleinListing83highlights thereturnstatement.TheruleinListing84highlightstheblock. Bydefault,theStructuralAnalyzerreportsnoinformationotherthanthesourcelocationoftheoutermost constructthatitmatchesForsomerules,thisissufficient.Otherrulesrequiremoreinformationinorderto createacompletereport. Youcanenablereportingforasubrulebyappendinganasterisktothesubrule.Listing85showsthis. Listing 85: Subrule Marked with a Asterisk 1 ReturnStatement: in [FinallyBlock:]* Thisruleislogicallyequivalenttotheun‐asteriskedonebecauseitmatchesexactlythesamecodeconstructs. However,whenanalyzermatchesit,boththereturnstatementanditsenclosingfinallyblockarereported.The returnstatementisstilltheprimaryreportinglocation. Chapter 7: Structural Rules Language Reference 82 Asteriskedsubrulematchesarereportedonlyforsubrulesthatactuallycontributetoamatch.Thesubrule providedinListing86showsthis. Listing 86: Subrule Marked with a Asterisk 2 Function: contains [AssignmentStatement:]* and public or contains [ReturnStatement:]* and private Thisrulematchesanypublicmethodcontaininganassignmentstatement,oranyprivatemethodcontaininga returnstatement.TheStructuralAnalyzeralwaysreportsthematchingstatement,becausebothsubrulesare asterisked.However,ifamethodcontainsbothanassignmentstatementandareturnstatement,theanalyzer reportsasfollows: • Assignmentstatement—ifthemethodispublic • Returnstatement—ifthereturnstatementofthemethodisprivate Call‐Graph Reachability Manystructuralrulesapplyonlyincertaincontexts.Forexample,EnterpriseJavaBeans(EJBs)areadvised nevertocallthejava.iolibrariesdirectly.Youcanimplementarulethatmatcheseverycalltojava.io. Listing87showsarulethatmatcheseverycalltojavatuilrl: Listing 87: Matches Every Call to Java tuirl FunctionCall call: call.function.enclosingClass.name startsWith "java.io." TheissuewiththeruleinListing87isthatitgeneratesalargenumberoffalsepositives.Thisisbecausethe mostcallstoJava.iodonotinvolveEJBs.Abetterapproximationistorestricttofunctioncallsthatappearwithin anEnterpriseBean.Theenclosingclassofthefunctioncalldiffersfromtheenclosingclassofthefunction. Listing88showsarulewithanEnterpriseBeanrestriction. Listing 88: EnterpriseBean Restriction 1 FunctionCall call: call.function.enclosingClass.supers contains [Class c: c.name == "javax.ejb.EnterpriseBean"] and // The enclosing class of the function itself call.function.enclosingClass.name startsWith "java.io." Listing89showsmorecontentonanEnterpriseBeanrestriction. Listing 89: EnterpriseBean Restriction 2 // The enclosing class of the function itself call.function.enclosingClass.name startsWith "java.io." TheruleprovidedbyListing89missesmanycasesinwhichanEnterpriseJavaBeanindirectlycallsjava.io.For example,thisrulewillmisswhenaEnterpriseJavaBeancallsautilitymethodinadifferentclass,andtheutility methodopensafile.Thisshouldbeaviolation. TheStructuralAnalyzerprovidestworelationsreachesandreached by,thattraversethecallgraphofa program.Youcanusetheserelationstohandlethetypeofsituationdescribedabove. Chapter 7: Structural Rules Language Reference 83 Listing90showsanexampleofareachesrelation. Listing 90: Relation that traverses a Call Graph f reaches [subrule] Thisistruejustifthereissomepaththroughthecallgraphoriginatingwithfandterminatingatafunctionthat matchesthesubrule.reachedByissimilar,withthepathproceedingintheoppositedirection. Listing91showsaFunctionCallthatisthebestwaytoencodetheaboveEJBrule: Listing 91: Encode EJB Rule FunctionCall call: call.enclosingClass.supers contains [Class: name == "javax.ejb.EnterpriseBean"] and call.function reaches [Function fnReached: fnReached.enclosingClass.name startsWith "java.io."]* YoucanalsousethereachesandreachedByrelationsonclasses.ClassAreachesclassBifsomefunctionofA reachessomefunctionofB.Forexample,theruleprovidedbyfollowingrulematchespublicfieldsinclassesthat anAppletcanreach. Listing 92: Public Fields Reachable by an Applet Field f: f.public and not f.final and f.enclosingClass reachedBy [Class a: a.supers contains [Class super: super.name == "java.applet.Applet"]] ThefieldcannotappearaspartofareachedByrelation‐onlyfunctionsandclassescansatisfy reachesor reachedBy. Forperformancereasons,variablescopesdonotextendacrossreaches orreachedBypredicates. Listing93showsanillegalrule. Listing 93: Illegal reaches Rule Function f: reaches [Function g: g != f] Thevariablefcannotappearinthesubruleofareachesrelation. Chapter 7: Structural Rules Language Reference 84 Chapter 8: Control Flow Rule Reference Thischapterprovidesthefollowingtopics: • ControlFlowSyntaxandGrammar—usethissectionasareferenceforcontrolflowrulesyntaxandgrammar. • UnderstandingControlFlowRules—usethissectiontolearnaboutcontrolflowrules. Control Flow Syntax and Grammar ThefollowingisasimplifiedBNF‐stylegrammarfortheStructuralPredicateLanguage.Forreadability purposes,thegrammarinthisguideismorestrictthanitisinpractice. Listing94showstheStructuralPredicateLanguage. Listing 94: Structural Predicate Language <MachineSpecification> := <Declaration>* <Transition>* <Declaration> := <StateDeclaration> | <PatternDeclaration> | <VariableDeclaration> <StateDeclaration> := 'state' <StateName> [ '(start)' | '(error)' ] ';' <StateName> := <Identifier> <PatternDeclaration> := 'pattern' <Identifier> '{' <StatementList> '}' <VariableDeclaration> := 'var' <Identifier> ';' <Transition> := <StateName> '->' <StateName> '{' <StatementList> '}' <StatementList> := <Statement> [ '|' <StatementList> ] <Statement> := <PatternUse> | <MetaFunction> | <Declaration> | <AssignmentStatement> | <Expression> <PatternUse> := 'pattern' <Identifier> <MetaFunction> := '#end_scope' '(' <RuleVariable> ')' | '#end_function' '(' ')' | '#return' '(' [ <Expression> ] ')' | '#compare' '(' <RuleVariable> ',' ( <Literal> | <Wildcard> ) ')' | '#param' '(' <RuleVariable> ',' ( <Wildcard> | <NumberLiteral> ) ')' | '#ifblock' '(' <RuleVariable> <IfBlockComparisonOperator> ( <Literal> | <Wildcard> ) ',' ( 'true' | 'false' ) ')' <IfBlockComparisonOperator> := '==' | '!=' | '<' | '<=' | '>' | '>=' <Declaration> := ( '#any_declaration' | '#simple_declaration' | '#complex_declaration' | '#buffer_declaration' ) '(' <RuleVariable> ')' <AssignmentStatement> := ( <RuleVariable> | <Wildcard> | <OpExp> ) '=' <Expression> <Expression> := ( <Literal> | <OpExp> | <Call> | <QualifiedCall> | <Wildcard> | <RuleVariable> ) <Literal> := <StringLiteral> | <NumberLiteral> | 'true' | 'false' | 'null' <StringLiteral> := '"' <Text> '"' <NumberLiteral> := ('0'-'9')+ <OpExp> := '&' <Expression> | '*' <Expression> <RuleVariable> := <Identifier> <Wildcard> := '?' <QualifiedCall> := ( <RuleVariable> | <Wildcard> ) '.' <Call> <Call> := ( <Identifier> | '#any_function' ) '(' [ <ArgumentList> ] ')' <ArgumentList> := ( <Argument> [ ',' <ArgumentList> ] ) | '...' <Argument> := [ '...' ',' ] <Expression> Chapter 8: Control Flow Rule Reference 85 Understanding Control Flow Rules Controlflowrulesprovidedefinitionsofstatemachinesthatcharacterizeunsafebehaviorsuchaspotentially dangeroussequencesofoperations. Control Flow Rule Identifiers Controlflowrulescanhavemultiplefunctionidentifiers.Thefunctionidentifiersareusedinthecontrolflow definition.ThedefinitionusesthevalueofthereferenceIdentifierasavariabletoaccessthefunctional identifiers.Mostofthecontrolflowfunctionidentifiersaredescribedin“FunctionIdentifiers”onpage16.The functionidentifierpanelforcontrolflowrulesalsocontainsadditionalfieldsandfunctionality,describedinthis section. Control Flow Rule Format Unlikedataflowrules,acontrolflowruledoesnotspecifyasinglefunction;instead,itspecifiesasequenceof programelements(whichcouldbefunctioncallsorotherentitiesinaprogram).Thisdefinition,whichgoesin theDefinitionfieldoftherule,resemblesasimpleprogramminglanguage. ControlflowrulessupportC++andJava‐stylecommentsasfollows://createsacommenttotheendoftheline/ *createsacommentuntilamatching*/Eachruledefinitiondefinesastatemachine.Eachstatemachinehas exactlyonestartstate,oneormoreerrorstates,andanynumberofintermediatestates.Themachinealways hasacurrentstate. Whenthecurrentstateisanerrorstate,thecontrolflowanalyzerreportsavulnerability. Statesareconnectedbytransitions.Eachtransitionhasasourcestate,adestinationstate,andsomenumberof patterns.Ifatransition'ssourcestateisthecurrentstateandoneofthattransition'spatternsmatchesa fragmentoftheprogram,thenthetransition'sdestinationstatebecomesthenewcurrentstate.Inthiscase,the machineissaidtohavetransitionedfromthesourcestatetothedestinationstate.Theprogramfragmentis referredtoasthe"input"tothepattern.Thedefinitionofamachineconsistsoftwomajorparts:declarations andtransitions. Thissectionprovidesthefollowingtopics: •Declarations •Transitions •Functioncalls Declarations Machinedefinitionsbeginwithdeclarationsofthestatesofthemachine.Statesaredefinedwiththestate keyword,optionallyfollowedbystartorerrortodesignatethestartanderrorstates,respectively,followedby thestatename.Asimplemachinecanhavethefollowingstatedefinitions. Listing95showsstatemachinestatedefinitions. Listing 95: State Machine State Definitions state state1 start; state state; state state3 error; Machinescanalsoincludevariables,whicharedeclaredwiththevarkeyword.Avariablecanmatchany expressionintheprogram.Thefirsttimeavariableisused,itisboundtotheexpressionitmatches.For subsequentusesofthesamevariable,thevariableonlymatchesiftheinputisthesameastheexpressionto whichthevariableisbound. Chapter 8: Control Flow Rule Reference 86 Listing96showsasampledeclaration. Listing 96: Sample Variable Definition var f; Finally,patternscanbegivennamestoavoidtheneedtoenterthesamepatternmanytimes.Patternsare namedwiththepatternkeyword,followedbythepatternenclosedincurlybraces. Forexample,thefollowinglinedeclaresapatternnamedalloc,whichmatchesthemallocandcalloc functions: pattern alloc { malloc(...) | calloc(...) }Formoreonpatterns,see“Transitions”onpage87. Ifacontrolflowrulecontainsalineoftheformlimit <refid>;,thenthatcontrolflowruleonlyappliesinthe bodyoffunctionsthatmatchthefunctionidentifierwithreferenceIDrefid. Transitions Transitionsdefinehowthecurrentstateofthemachinemaychange.Asdescribedabove,eachtransitionhasa sourcestate,adestinationstate,andapattern.Theremaybemultipletransitionswiththesamesourcestate;in thiscase,thenewcurrentstatewillbethedestinationstateofthefirsttransitionwithapatternthatmatches theinput. Transitionsaredefinedbythenameofthesourcestate,thesymbol->,thenameofthedestinationstate,and oneormorepatternssurroundedbycurlybraces.Multiplepatternsinthesametransitionshouldbeseparated with|characters. Listing97showsanexampleofatransitionwithmultiplepatternsseparatedwith|characters. Listing 97: Transition with Multiple Patterns source -> destination { pattern1 | pattern2 } Apatternconsistsofoneofthefollowingelements: • Usesofanamedpattern Patternsdeclaredwiththepatternkeywordinthedeclarationsectionmaybeusedintransitionsby specifyingthepatternkeywordfollowedbythepatternname,suchas:state1 -> state2 { pattern alloc } • Assignmentstatements Controlflowrulesoftenrefertothereturnvaluesoffunctioncalls,particularlyobjectconstructorsandother functionsthatreturnhandlestoresources.Thereturnvalueofafunction,oranyassignmentstatement,can bematchedwiththenameofarulevariablefollowedbyanequal(=)symbolandanexpression.(Seebelow forexpressions.)Theleft‐handsideoftheassignmentoperatormustbeapreviouslydeclaredrulevariable. • Expressions Anexpressioncanbeanyoneofthefollowing: • Astring,enclosedindouble‐quotes(C‐style) • Acharacter,insingle‐quotes(C‐style) • Aninteger • Afloating‐pointnumber • Thebooleans"true"and"false"(withoutquotes) • Thevalue"null"(withoutquotes) • *<Expression>:Adereferenceof<Expression> Chapter 8: Control Flow Rule Reference 87 • • &<Expression>:Areferenceto<Expression>(C‐style) • Afunctioncall:SeeFunctionCallsbelow • A?character:Matchesanyexpressionintheinput • Thenameofarulevariable:Iftherulevariableisunbound,matchesanyexpressionandbindstherule variabletothatexpression.Iftherulevariableisbound,matchestheexpressiontowhichthevariable wasfirstbound. Languagefeaturestatements Someaspectsofprogramscannotberepresentedusingtheexpressionsabove.Fortheseaspects,thereare specialtypesofpatterns.ThesepatternsresemblefunctioncallsinCorJava,butallofthefunctionnames beginwitha#character. Thevalidlanguagefeaturestatementsare: • #end_scope(var):Matchestheendoftheenclosingscopefortheexpressionboundtotherulevariable var • #return(expr):Matchesareturnstatementwithareturnexpressionmatchingexpr • #return():Matchesanyreturnstatement • #compare(var, const):Matchesacomparison(==, !=, <, >, <=, >=)betweenvar(arule variable)andconst(astring,character,integer,floating‐pointnumber,boolean,null,or'?'expression) • #simple_declaration(var):Matchesthedeclarationofasimpletype‐‐aninteger,pointer,reference, orotherprimitivedatatype.Bindstherulevariablevartothevariabledeclaredintheprogram • #declaration(var):Isidenticalto#simple_declaration(var) • #complex_declaration(var):Matchesthedeclarationofacomplexdatatype(structorobject)inCor C++.Pointerstostructs,pointersandreferencestoC++objects,andreferencestoJavaobjectsarenot matched;usethe#simple_declarationpatternforthesedatatypes. • #buffer_declaration(var):MatchesthedeclarationofastackbufferinCorC++ • #any_declaration(var):Matchesanyoftheabove • #ifblock (var, const, which):Matchesacomparisonbetweenvarandconstasdefinedfor #compare,withtheadditionalrestrictionsthatthecomparisonoperatormustbeanequalitytest(==,!=, orasimilaroperator),andthatthecomparisonmustoccurwithinthepredicateofabranchingor loopingconstruct(suchasifstatements,forloops,andwhileloops).Thespecifiedstatetransitiononly occursonthebranchwherevar ==constevaluatestowhich. Function Calls Mostinterestingsecuritypropertiesinvolvetheuseoffunctionmatchingsyntaxbasedonfunctionidentifiers. ControlflowrulesusethereferenceIDfieldfromfunctionidentifierstospecifyfunctionsfortransitions.For example,ifthereisafunctionidentifierwithareferenceIDofallocator,thenthecontrolflowpatternv = $allocator(?)wouldassigntherulevariablevtothereturnvalueofanyfunctionthatmatchedthe $allocatorfunctionidentifierandtookexactlyoneargument. Ingeneral,theargumentstotherulefunctionshouldexactlymatchtheexpectedargumentstotheinput function.Therefore,towritearulethatbindsthesecondargumenttothelinksystemcalltotherulevariable var,therulewouldread$link(?, var),assumingafunctionidentifiermatchingthelinksystemcallhad alreadybeendefinedwithareferenceIDoflink.Thereisoneexceptiontothe"oneexpressionperargument" rule:anellipsis(...)intheargumentstoafunctionmatches0ormoreexpressions.Itisthereforepossibleto matchthelastargumentofafunctionbyspecifyingfunction(..., var),andfunction(...)willmatchany invocationofthespecifiedfunction,withoutpayingattentiontotheargumentstothatfunction. Chapter 8: Control Flow Rule Reference 88
© Copyright 2026 Paperzz