Top Banner
HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release Date: October 2014 Software Release Date: October 2014
88

HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Oct 09, 2020

Download

Documents

dariahiddleston
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

HPFortifyStaticCodeAnalyzerSoftwareVersion4.21

HPFortifyStaticCodeAnalyzerCustomRulesGuide

DocumentReleaseDate:October2014

SoftwareReleaseDate:October2014

Page 2: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Legal Notices

Warranty

TheonlywarrantiesforHPproductsandservicesaresetforthintheexpresswarrantystatementsaccompanyingsuchproductsandservices.Nothinghereinshouldbeconstruedasconstitutinganadditionalwarranty.HPshallnotbeliablefortechnicaloreditorialerrorsoromissionscontainedherein.

Theinformationcontainedhereinissubjecttochangewithoutnotice.

Restricted Rights Legend

Confidentialcomputersoftware.ValidlicensefromHPrequiredforpossession,useorcopying.ConsistentwithFAR12.211and12.212,CommercialComputerSoftware,ComputerSoftwareDocumentation,andTechnicalDataforCommercialItemsarelicensedtotheU.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

Page 3: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Contents  iii

Contents

Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .vi

ContactingHPFortifySoftware........................................................................vi

TechnicalSupport .................................................................................viCorporateHeadquarters...........................................................................viWebsite ........................................................................................... 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 ........................................................................................ 12CommonRuleElements.......................................................................... 13

CustomDescriptions ................................................................................. 16

AddingCustomDescriptionstoHPFortifyRules.................................................. 16AddingHPFortifyDescriptionstoCustomRules.................................................. 17

Chapter 3: DataflowAnalyzerandCustomRules ..................................................... 18

UnderstandingDataflowAnalyzerandCustomRules .................................................. 18

DataflowAnalyzerandCustomRulesConcepts........................................................ 19

TaintSource ..................................................................................... 19TaintEntrypoint ................................................................................. 19TaintSink ........................................................................................ 19TaintPassthrough................................................................................ 20TaintCleanse..................................................................................... 20TaintFlags....................................................................................... 20TaintPath........................................................................................ 21XMLRepresentationofDataflowRules ........................................................... 22

CustomDataflowRuleScenarios ...................................................................... 26

ScenarioOverview............................................................................... 26PathManipulationScenario ...................................................................... 26SourceCode...................................................................................... 27Rules............................................................................................. 27SQLInjectionandAccessControlScenario ........................................................ 29SourceCode...................................................................................... 29Rules............................................................................................. 31

Page 4: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Contents  iv

PersistentCross‐siteScripting .................................................................... 35CommandInjectionScenario..................................................................... 39

Chapter 4: CustomStructuralRules ................................................................. 43

UnderstandingStructuralAnalyzerandCustomRules ................................................. 43

StructuralTree ................................................................................... 43StructuralTreeQueryLanguage .................................................................. 44

StructuralTreeExamples ............................................................................. 44

Example1........................................................................................ 44Example2........................................................................................ 45Example3........................................................................................ 46Example4........................................................................................ 47

XMLRepresentationofStructuralRules............................................................... 48

StructuralCustomRuleScenarios ..................................................................... 48

ScenarioOverview............................................................................... 49LeftoverDebugScenario ......................................................................... 49DangerousFunctionCallsScenario ............................................................... 50OverlyBroadCatchBlocks........................................................................ 52PasswordinCommentsScenario ................................................................. 54PoorLoggingPracticeScenario ................................................................... 55EmptyCatchBlockScenario...................................................................... 56

Chapter 5: CustomControlFlowRules ............................................................... 58

UnderstandingControlFlowAnalyzerandCustomRules .............................................. 58

ControlFlowAnalyzerandCustomRuleConcepts..................................................... 60

RulePattern...................................................................................... 60RuleVariable..................................................................................... 60RuleBinding..................................................................................... 60

XMLRepresentationofControlFlowRules............................................................ 61

Definition........................................................................................ 61FunctionIdentifiers.............................................................................. 61FunctionCallIdentifiers .......................................................................... 61Limits ............................................................................................ 61PrimaryState .................................................................................... 62

CustomControlFlowRuleScenarios .................................................................. 63

ScenarioOverview............................................................................... 63ResourceLeakScenario .......................................................................... 63NullPointerCheckScenario...................................................................... 68

Chapter 6: CustomContentandConfigurationRules ................................................. 72

UnderstandingContentAnalyzerandCustomRules ................................................... 72

UnderstandingConfigurationAnalyzerandCustomRules ............................................. 72

XMLRepresentationofContentRules ................................................................. 72

XMLRepresentationofConfigurationRules ........................................................... 73

Page 5: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Contents  v

CustomContentandConfigurationRuleScenarios .................................................... 74

CustomRuleScenarioOverview.................................................................. 74PropertyFileScenario............................................................................ 75SourceCode...................................................................................... 75Rules............................................................................................. 75TomcatFileScenario............................................................................. 76

Chapter 7: StructuralRulesLanguageReference..................................................... 78

SyntaxandGrammar................................................................................. 78

Types............................................................................................ 78ReferenceResolution............................................................................. 80NullResolutions.................................................................................. 81Relations......................................................................................... 81ResultsReporting................................................................................ 82Call‐GraphReachability .......................................................................... 83

Chapter 8: ControlFlowRuleReference............................................................. 85

ControlFlowSyntaxandGrammar.................................................................... 85

UnderstandingControlFlowRules.................................................................... 86

ControlFlowRuleIdentifiers ..................................................................... 86ControlFlowRuleFormat........................................................................ 86Declarations ..................................................................................... 86Transitions....................................................................................... 87FunctionCalls .................................................................................... 88

Page 6: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Preface   vi

PrefaceThisguidedescribeshowtousecustomrulestoresolvesecurityissuesinyourcode.

Contacting HP Fortify SoftwareIfyouhavequestionsorcommentsaboutanypartofthisguide,contactHPFortifyat:

Technical Support650.735.2215

[email protected]

Corporate HeadquartersMoffettTowers1140EnterpriseWaySunnyvale,CA94089

650.358.5600

[email protected]

Websitehttp://www.hpenterprisesecurity.com

About the HP Fortify Software Security Center Documentation SetTheHPFortifySoftwareSecurityCenterdocumentationsetcontainsinstallation,user,anddeploymentguidesforallHPFortifySoftwareSecurityCenterproductsandcomponents.Inaddition,youwillfindtechnicalnotesandreleasenotesthatdescribenewfeatures,knownissues,andlast‐minuteupdates.Youcanaccessthelatestversionsofthesedocumentsfromthefollowingsources:

• YoucanaccessalldocumentsinPDFfileformatontheHPESPusercommunityProtect724website(https://protect724.hp.com/welcome).Youwillneedtoregisterforanaccount.

• YoucanaccessalldocumentsinPDFfileformatandinstallationguidesandusersguidesinHTMLformatontheHPSoftwareProductManualssite(http://support.openview.hp.com/selfsolve/manuals).Toregister,gotohttp://h20229.www2.hp.com/passport‐registration.html.

Page 7: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Change Log   vii

Change LogThefollowingtabletrackschangesmadetotheHPFortifyStaticCodeAnalyzerCustomRulesGuide.

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.

Page 8: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 1: Introduction   8

Chapter 1: IntroductionThisdocumentprovidestheinformationthatyouneedtocreatecustomrulesforHPFortifyStaticCodeAnalyzer.Thisincludesbothconceptualcontentthatfocusesoncustomizingtopicsaswellasanumberofexamplesthatapplyrule‐writingconceptstoreal‐worldproblems

Intended AudienceThisdocumentisintendedforpeoplewhoareexperiencedwithbothsecurityandprogramming.Someofthecontentinthisguidemightbedifficulttounderstandwithoutprogrammingexperience.

Document StructureThisdocumentisstructuredtofacilitatethefollowing:

• LearningaboutHPFortifyStaticCodeAnalyzerandcustomrules—ThesechaptersdescribehowSCAworkswithspecificanalyzers.Thisincludescustomrulescenariosforeachanalyzertype.

Chaptersare:

• DataflowAnalyzerandCustomRules—ThischapterdescribeshowtheDataflowAnalyzerworkswithSCAtodiscovervulnerabilitiesincode.Thischapterincludescustomdataflowscenariosthatshowhowtoresolvereal‐worldproblemsusingcustomdataflowrules.

• CustomStructuralRules—ThischapterdescribeshowtheStructuralAnalyzerworkswithSCAtodiscovervulnerabilitiesincode.Thischapterincludescustomstructuralscenariosthatshowhowtoresolvereal‐worldproblemsusingcustomstructuralrules.

• CustomControlFlowRules—ThischapterdescribeshowtheControlflowAnalyzerworkswithSCAtodiscovervulnerabilitiesincode.Thischapterincludescustomcontrolflowscenariosthatshowhowtoresolvereal‐worldproblemsusingcustomcontrolflowrules.

• CustomContentandConfigurationRules—ThischapterdescribeshowthecontentandConfigurationAnalyzersworkwithSCAtodiscovervulnerabilitiesincode.Thischapterincludescontentandconfigurationscenariosthatshowhowtoresolvereal‐worldproblemsusingcustomcontentandconfigurationrules.

• Usingreferencecontenttowritecustomrules—ThesechaptersandotherresourcesprovidethecontentthatyouneedtobuildcustomrulesforSCA.

Chaptersandotherresourcesare:

• ControlFlowRuleReference—Thischapterprovidessyntaxandgrammarforcontrolflowrules.Usethischapterasareferencewhenwritingcustomcontrolflowrules.

• StructuralRulesLanguageReference—Thischapterprovidessyntaxandgrammarforstructuralrules.Usethischapterasareferencewhenwritingcustomstructuralrules.

• HPFortifyXMLSchema—ThisHTMLcontentprovidestheHPFortifyXMLschema,including:validattributesandelements,childandparentrelationshipsbetweenelements,whetheranelementisemptyorcanincludetext,elementdatatypes,aswellaselementandattributedefaultandfixedvalues.

TheHPFortifyXMLSchemaisavailablefromtheHPFortifyCustomerPortal.Itwasalsoincludedinthezipfilefromwhichyouextractedthisdocument.

• HPFortifyStructuralTypeandPropertiesReference—ThisHTMLcontentprovidestypeandpropertiesreferenceforstructuralrules.Usethiscontentwhencreatingcustomstructuralrules.

TheHPFortifyStructuralTypeandPropertiesReferenceisavailablefromtheHPFortifyCustomerPortal.Itwasalsoincludedinthezipfilefromwhichyouextractedthisdocument.

Page 9: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 1: Introduction   9

Related DocumentsThefollowingdocumentsprovideadditionalinformationaboutHPFortifyStaticCodeAnalyzer:

• HPFortifyStaticCodeAnalyzerInstallationandConfigurationGuide

ThisdocumentprovidesinstallationandconfigurationinstructionsforSCA.

• HPFortifyStaticCodeAnalyzerUserGuide

Thisdocumentprovidesinstructionsonusingtheanalyzerstoidentifyvulnerabilitiesinyourcode.

• HPFortifyStaticCodeAnalyzerUtilitiesUserGuide

Thisdocumentprovidesinformationonthecommand‐linetoolsthatprovideadditionalmanagementandaccesstothefunctionsprovidedbySCA.

• HPFortifyStaticCodeAnalyzerPerformanceGuide

Thisdocumentdescribestheissuesinvolvedwhentryingtoselecthardwaretoscancertaincodebases,providesguidelinesformakingthosedecisions,andofferstipsforoptimizingmemoryusage and performance.

Page 10: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 2: Custom Rules Overview   10

Chapter 2: Custom Rules OverviewThischapterprovidesthefollowingtopics:

• HPFortifySecureCodingRulepacks—UsethissectiontolearnaboutHPFortifySecureCodingRulepacks.

• CustomRules—Usethissectiontolearnaboutusingcustomrules.

• CommonRuleElements—Usethissectiontolearnabouttheelementsthatarecommontodifferenttypeofrules.

• CustomDescriptions—Usethissectiontolearnhowtocreatecustomdescriptions.

HP Fortify Secure Coding RulepacksHPFortifyStaticCodeAnalyzerusesaknowledgebaseofrulestomodelimportantattributesoftheprogramunderanalysis.Theserulesprovidemeaningtorelevantdatavaluesandenforcesecurecodingstandardsapplicabletothecodebase.TheSecureCodingRulepacksdescribegeneralsecurecodingidiomsforpopularlanguagesandpublicAPIs,outofthebox.CustomrulesareavailableforJavaand.NETcode,butdonotcurrentlysupportJavaScript,PHP,ClassicASP,VisualBasic,orCobol.

AlthoughHPFortifyprovidesawiderangeofrules,itispossiblethatyourprojectsleverageunsupportedthird‐partyAPIs,includeorganization‐specificlibraries,orfallunderthepurviewofproprietarysecure‐codingguidelines.Inthiscase,HPFortifyprovidestheabilitytocreatecustomrulesthatsuityourneeds.

Customrulescangreatlyimprovethecompletenessandaccuracyoftheanalysisperformedbyastaticanalysistool.Theydothisbymodelingthebehaviorofthesecurity‐relevantlibraries,describingproprietarybusinessandinputvalidation,andenforcingorganizationandindustry‐specificcodingstandards.

Custom RulesYoucanextendthefunctionalityofSCAandtheSecureCodingRulepacksbywritingcustomrules.Forexample,youmightneedtoenforceproprietarysecurityguidelinesoranalyzeaprojectthatusesthird‐partylibrariesorotherpre‐compiledbinariesthatarenotalreadycoveredbytheSecureCodingRulepacks.

Ifaprojectusesresourcesforwhichsourcecodeisnotavailableatanalysistime,analysisoftheprojectwillsucceed,butmightbeincompleteuntilyouwritethecustomrulesthatprovideSCAwithsecurityknowledgeabouttheseresources.

Towriteeffectivecustomrules,itisimportanttobecomefamiliarwithknownsecurityvulnerabilitycategoriesandthecodeconstructswithwhichtheyareoftenrelated.Developinganunderstandingofthetypesoffunctionsthatoftenappearinparticulartypesofvulnerabilitiesfacilitatestheprocessoftargetingsecurity‐relevantfunctionsforcustomrulewriting.Becausethetaskofdeterminingthesecurityrelevanceofafunctioncanbechallenging,timespentlearningabouttherelationshipsbetweentypesoffunctionsandvulnerabilitycategorieswillproveuseful.

Youmustexaminetheindividualbehaviorofeachsecurity‐relevantfunction,eitherbyreviewingsourcecodeorwiththehelpofAPIdocumentation,todeterminethecorrecttypeofruletorepresentthespecificbehaviorandvulnerabilitycategoryassociatedwitheachofthefunctions.

Fromhere,youcandevelopsmalltestcasesthatexemplifytheundesirablebehavioryouwantyourrulestoidentify.Conversely,testcasesdesignedtoreflectcorrectbehaviorthatshouldnotbeflaggedwillalsohelpyoueliminatefalsepositivesfromtherulesyoucreate.Onceyouaresatisfiedyourrulesperformcorrectlyinthiscontrolledenvironment,thenextstepistousethemtoperformananalysisonabroadrangeofprojectstoensurethattheybehavewiththeexpectedleveloffidelity.

Tosimplifytheprocessofcreatingcustomrules,HPFortifyAuditWorkbenchincludesaCustomRulesEditorthatcanbelaunchedfromAuditWorkbenchorbyrunningtheCustomRulesEditorscriptorcommandfromthe

Page 11: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 2: Custom Rules Overview   11

bindirectorywhereyouinstalledyourHPFortifysoftware.Formoreinformation,seetheHPFortifyAuditWorkbenchUserGuide.

Custom Rules and User RolesUserrolesalsoplayanimportantpartincreatingandusingcustomrules.Forexample,anindividualauditormightrequiredifferentcustomrulesthanasecurityteam.Therestofthissectiondescribescommonuserrolesandidentifiescustomrulesspecifictothatrole.

Individual Auditor

Anindividualauditorperformsasinglesecurityreviewofaprojectforaspecificorganization.Asecurityresearcherlookingforbugsinapieceofpublicsoftwarealsofitsintothisrole.Thegoalofthisuseristoidentifyspecificvulnerabilitiesbasedonanarrowsetofsecuritycriteria.

Apersoninthisroledevelopsandusescustomrulesalonganarrowsetofparametersanddoesnotstriveforbreadthofcoverage.Anexampleofthisisaddressingthestrategicshortcomingofthebuilt‐inknowledgebaseofrules.

ThisincludesidentifyingspecificclassesofbugsormodelingthebehaviorofAPIsthatarelikelytoleadtovulnerabilitiestargetedinthecurrentaudit.

Inthiscase,customizationisatoolintheauditor'sbelt.Developingalargebodyofcustomrulesisnotarequirementforthisuser.Anyeffortthatthisindividualputsintocustomizationshouldbeweighedagainstthebenefitthatthecustomizationwillprovide.

Central Security Team

Acentralsecurityteamistypicallyresponsiblefordevelopingcustomrulesthatidentifyabroadsetofvulnerabilitiesacrossmultiplecodebaseswithinanorganization.Thecentralsecurityteamprovidesvaluebydevelopinglargedatabasesofrulesthatimprovethestaticanalysisresultsduringongoingaudits.

Ifthecentralsecurityteamisresponsibleforauditingtheresultsproducedbythecustomrules,thenitcanbeappropriatetoincluderulesthatprovideanauditorachecklistofpropertiestoverifyduringtheaudit.

However,iftheresultsofthestaticanalysistoolarerevieweddirectlybythedevelopmentteamresponsibleforeachprojectrespectively,thenthetoleranceforissuesthatdonotcorresponddirectlytosecurityvulnerabilitiesorotherprogrammingbugswillinvariablybemuchlower.

Ineithercase,itisdesirabletoproducealargeknowledgebaseofcustomrulesrelevanttoprojectsunderanalysis,sincetherulewritersareincentivizedtoimproveanalysisresultsduringongoingaudits.

Development Team

Ifadevelopmentteamisresponsibleforbothimplementingcustomrulesandauditingtheresultsofthestaticanalysistool,theextenttowhichyouwanttocustomizevariesbasedonthesecurityexperienceofthedevelopmentteam.Ifthedevelopmentteamisontangentiallyinvolvedinsecurity,theiruseofcustomruleswillmostlikelyfocusonanarrowfieldofrelevantbugs.Inthiscase,theywillnotinvestinalargebodyofcustomrules.

Page 12: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 2: Custom Rules Overview   12

Rulepacks and Common Rule ElementsSCAcomprisesmultipleanalyzersthatperformdifferenttypesofanalysisandfinddifferenttypesofproblemsincode.Eachanalyzersupportsoneormoredistinctruletype.

Thisdocumentcoverstheseruletypes:

• Dataflow

• Structural

• Configuration

• Controlflow

Thefollowingruletypesareoutsidethescopeofthisdocument:

• CharacterizationRule

• DeprecationRule

• GlobalFieldRule

• InputSetRule

• InternalRule

• NonReturningRule

• StatisticalRule

• SuppressionRule

RulepacksARulepackcomprisesoneormorerulesofanarbitrarytype.SecureCodingRulepacksarerepresentedinXML.EachRulepackmusthaveaRulepackdefinitionthatincludesavarietyofheaderinformationthatdescribesthatRulepack.

Listing1showsanexampleRulepackdefinitionthatdoesnotcontainanyrules.

Table1showsseveraloftheXMLelementsintroducedintheRulepackdefinitionshowninListing1.

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>

Table 1: XML Elements  

Element Description

<RulePackID> AuniqueidentifierfortheRulepack,whichcanbeanarbitrarystring.ByconventionHPFortifyusesagloballyuniqueidentifier(GUID)generatortodefineRulepackandruleidentifierstoensurethatbothreceiveuniqueidentifiers.

Page 13: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 2: Custom Rules Overview   13

Theremainderofthissectionenumeratesseveralcommonelementssharedbetweenmultipleruletypes.

Common Rule ElementsSCArulesshareafewuniversalelementsthatgoverntheiruse.

Table2showstheseelements.

Table 2: Universal Rule Elements

Element/Attributes Language

<RuleID> Uniqueidentifierfortherule,whichcanbecomposedofanarbitrarystringofcharacters.AswithRulepackIDs,byconventionHPFortifyusesagloballyuniqueidentifier(GUID)generatortodefineRulepackanduniqueruleidentifiers.

language Theprogramminglanguagetowhichtheruleapplies.Thelanguageattributeispartofthetop‐levelruledefinition.

formatVersion TheminimumversionoftheSCARuleEnginewithwhichtheruleiscompatible.TheformatVersionattributeispartofthetop‐levelruledefinition.

Someruleattributesarecommontoonlythoserulesthatdirectlycausetherespectiveanalyzertoreportanissue.

Table3showstheruleattributescommontovulnerability‐producingrules.

Table 3: Vulnerability Producing Rules Common Elements

Element Description

<VulnCategory> Vulnerabilitycategoryassociatedwithrulesthatgenerateissues.

<VulnKingdom> (Optional)Vulnerabilitykingdomassociatedwithrulesthatgenerateissues.

<VulnSubcategory> (Optional)Vulnerabilitysub‐categoryassociatedwithrulesthatgenerateissues.

<Description> Human‐readabledescriptionofthevulnerabilityidentifiedbytherule.Descriptionelementscancontainanyof<Abstract>, <Explanation>, <Recommendations>, <References> and<Tips>.

<Name> Human‐readablenamefortheRulepack.

<Language> TheprogramminglanguagetowhichtheRulepackapplies.

<Version> ArbitrarynumericversionusedtorelatemultipleversionsofthesameRulepack(RulepackswiththesameRulepackidentifier).

<Description> Human‐readabledescriptionoftheRulepack.

<RuleDefinitions> Oneormoreruledefinitions.

Table 1: XML Elements  (Continued)

Element Description

Page 14: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 2: Custom Rules Overview   14

Rulesthatrefertofunctionormethodcalls(asopposedtoconfigurationfiles,propertyfiles,HTML,andothercontent)canuseacommonrepresentationcalledafunctionidentifier(<FunctionIdentifier>).

Table4showstheelementsofafunctionidentifier.

Table 4: Function Identifier Elements

Element Description

<FunctionName> Thenameofthemethodorfunctionthattherulematches.Function,class,andnamespacenamesareeitherexpressedwitha<Value>element,whichcausesSCAtointerpretthemasastandardstring,ora<Pattern>element,whichcausesSCAtointerpretthemasaJavaregularexpression.

<ClassName> (Optional)Thenameoftheclassthattherulematches.See<FunctionName>.

<NamespaceName> (Optional)Thenameofthepackageornamespacethattherulematches.See<FunctionName>.

<ApplyTo> (Optional)Controlshowtherulematchesagainstclassesthatextendthespecifiedclassorimplementthespecifiedinterface.Thiselementcontainsthefollowingattributes:

Ifleftunspecified,allthreeattributesofthe<ApplyTo>elementdefaulttofalse.

Functionidentifierscanalsooptionallyincludeelementsthatfurtherrestrictthemethodstherulewillmatch.The<Parameters>elementrestrictsthemethodsruleswillmatchtothosedeclaredwiththeformalparametersspecifiedbythe<ParamType>elementsitcontains.

Table5showsadescriptionoftheparameterelements.

Table 5: Elements used to specify parameters in a function identifier

Elements Descriptions

<ParamType> (Optional)Specifiesasingleparameterusingthenative‐languagetype,suchasintforanintegerinCorjava.lang.StringforastringinJava.

<WildCard> (Optional)Representsavariablenumberofarbitrarily‐typedparametersattheendparameterlistforthemethod.Theminattributespecifiesthefewestnumberofwildcardparametersallowedbytherule,whilethemaxattributespecifiesthemaximumnumberofwildcardparametersallowedbytherule.

• implements:trueindicatesthattheruleshouldmatchmethodsthatimplementtheinterfacespecifiedbytherule.

• overrides:trueindicatesthattheruleshouldmatchmethodsdefinedinsub‐classesthatoverridethemethodspecifiedbytherule.

• extends:trueindicatesthattheruleshouldmatchmethodsinclassesthatextendtheclassspecifiedbytherule.

Page 15: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 2: Custom Rules Overview   15

Likethe<Parameters>element,the<Modifiers>elementcontainsanarbitrarynumberof<Modifier>elements,whichrestrictthemethodstherulewillmatchtothosewithdeclaredwiththespecifiedmodifiers.HPFortifysupportsthefollowingmodifiers:

• native

• private

• protected

• public

• static

Manyruletypesallowmatchingtobefurtherrestrictedthroughtheuseofaconditionalexpression(<Conditional>).Functionidentifiersspecifywhichfunctionsormethodsareinterestingtotherule.Conditionalexpressionsrestrictwhichcallstothosefunctionsareactuallymatchedbytherule.Conditionalexpressionscanbewrittentoexamineconstantvaluesusedinmethodcallsandthetypesofmethodarguments(asdistinctfromthedeclaredformalparametertypesofthemethod).Fordataflowsinks,conditionalexpressionscanalsoexaminetaintflags.

Table6describesthebasicelementsthatcanappearinaconditionalexpression.

Table 6:  Conditional Types

Element Description

<Or>,

<And>,

<Not>

Booleanlogicoperatorsthatcombineapplythecorrespondinglogicaloperationtothenodestheycontain.

<IsConstant> Trueiftheargumentspecifiedbythezero‐indexedargumentattributeisacompile‐timeconstantornot.

<ConstantEq> Trueiftheargumentspecifiedbythezero‐indexedargumentattributeisacompile‐timeconstantthatmatchesthevaluespecifiedbythevalueattribute.

<ConstantGt> Trueiftheargumentspecifiedbythezero‐indexedargumentattributeisacompile‐timeconstantthatisstrictlygreaterthanthevaluespecifiedbythevalueattribute.

<ConstantLt> Trueiftheargumentspecifiedbythezero‐indexedargumentattributeisacompile‐timeconstantthatisstrictlylessthanthevaluespecifiedbythevalueattribute.

<TaintFlagSet> TruefortaintpathswhichincludethetaintflagspecifiedbythetaintFlagattribute.Thiselementisonlyvalidfordataflowsinkrules.

<IsType> Trueiftheargumentspecifiedbythezero‐indexedargumentattributematchesthe<NamespaceName>,<ClassName>,and<FunctionName>elementsspecifiedinsidethe<IsType>element.

Page 16: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 2: Custom Rules Overview   16

Custom DescriptionsSomeorganizationswanttoeitheraddcustomdescriptionstoHPFortifyrulesoraddHPFortifydescriptionstocustomrules.Customdescriptionsenableyoutoaddorganization‐specificcontenttoissuesproducedbytheHPFortifySecureCodingRulepacks.Customdescriptioncontentcanincludeorganization‐specificsecurecodingguidelines,bestpractices,referencestointernaldocumentationandsoon.AddingHPFortifydescriptionstocustomrulesenablesyoutoleveragedescriptionscreatedbyHPFortifyincustomrulesthatidentifycategoriesofvulnerabilitiesalreadyreportedbytheSecureCodingRulepacks.

• AddingCustomDescriptionstoHPFortifyRules

• AddingHPFortifyDescriptionstoCustomRules

Adding Custom Descriptions to HP Fortify RulesYouaddcustomdescriptionswiththenew<CustomDescriptionRule>element.EachcustomdescriptionruledefinesnewdescriptioncontentandspecifiesasetofHPFortifyrulestowhichitshouldbeapplied.

ToaddcustomdescriptionstoHPFortifyrules,dothefollowing:

• DefineCustomDescriptionContent—usethe<Description>elementofthecustomdescriptionruletodefinethecustomdescriptioncontent.

• IdentifyRulestoModify—usethe<RuleMatch>elementtoidentifytherulestowhichSCAwilladdthecustomdescriptioncontent.

Define Custom Description Content

The<Description>elementofthecustomdescriptionrulehasthesamestructureasastandardruledescription,with<Abstract>,<Explanation>,<Recommendations>,<Tips>,and<References>children.Thecustomdescriptioncanspecifyallorasubsetoftheseelements.Thecustomdescriptioncanuseallofthesameconstructsasastandarddescription,includingreferencestootherelementsusingtheref/idmechanism.Customdescriptiondefinitionscannotcontainanother<CustomDescription>tag.

Identify Rules to Modify

Acustomdescriptioncancontainseveralrulematches.Eachrulematchspecifiesrulesbasedonanycombinationofcategory,subcategory,ruleidentifier,anddescriptionidentifier.InorderforSCAtoapplyacustomdescriptiontoissuesproducedbyarule,therulemustmatchallcriteriaspecifiedintherulematch.

Forexample,arulematchthatspecifies<Category>Buffer Overflow</Category> and<Subcategory>Format String</Subcategory>willmatchonlyBufferOverflow:Obsoleteissues.ThecustomdescriptioncontentwillnotbeappliedtoissuesinotherBufferOverflowsubcategories,suchasBufferOverflow:Off‐by‐One.

Aruleneedonlysatisfyoneormorerulematchesforacustomdescriptionrule.Forexample,acustomdescriptionrulewitharulematchfor<Category>Buffer Overflow</Category>andanotherdistinctrulematchfor<Subcategory>Format String</Subcategory>,willmatchanyissuesintheBufferOverflowcategoryortheFormatStringsubcategory.

Page 17: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 2: Custom Rules Overview   17

Custom Description Example

ThecustomdescriptionruleshowninListing2addsacustom<Abstract>and<Explanation>forSQLInjectionandAccessControl:Databaseissues.

CustomdescriptionelementsalsohavearuleIDattributethatreferstothecustomdescriptionrule(nottothematchedrule,aswiththeclassIDattributeof<Description>).

Adding HP Fortify Descriptions to Custom RulesYoucanuseHPFortifydescriptionstodescribeissuesfoundbycustomrules.TouseanHPFortifydescriptioninacustomrule,youmustfirstdeterminetheidentifierforthedescriptionyouwanttouse.Descriptionidentifiersareavailableonhttp://vulncat.fortify.com.Onceyouhavelocatedtheidentifierforthedescriptionyouwanttouse,setthe"ref"attributeofthecustomruletotheidentifieroftheHPFortifydescription.

Forexample,theruleshowninListing3willproduceSQLInjectionresultswiththesamedescriptionasSQLInjectionresultsfromHPFortifyrulesforJava:

Inordertousethisfeature,descriptionIDsmustbeuniqueacrossallRulepacks.

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>

Listing 3: HP Fortify Description SQL Injection Output Example

<DataflowSinkRule language="java" formatVersion="3.9"> […] <Description ref="desc.dataflow.java.sql_injection"/> […]</DataflowSinkRule>

Page 18: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 3: Dataflow Analyzer and Custom Rules   18

Chapter 3: Dataflow Analyzer and Custom RulesThischapterprovidesthefollowingtopics:

• UnderstandingDataflowAnalyzerandCustomRules—usethissectiontolearnabouttheDataflowAnalyzerandthewaythatitusescustomrulestofinddataflow‐relatedsecurityissues.

• DataflowAnalyzerandCustomRulesConcepts—usethissectiontolearnaboutDataflowAnalyzerrulesandconcepts.

• XMLRepresentationofDataflowRules—usethissectiontolearnwhichdataflowrulesareavailable.

• CustomDataflowRuleScenarios—usethissectiontolearnhowtocreatecustomdataflowrules.

Understanding Dataflow Analyzer and Custom RulesTheSCADataflowAnalyzerenablesSCAtofindsecurityissuesthatinvolvetainteddataenteringaprogramfromonepoint(thetaintsource)andflowingthroughtoanotherpoint(thetaintsink).Ataintsinkisapointinthecodewheretheuseofun‐validatedinputisinherentlydangerous.

ThisanalysisenablesSCAtopreciselyidentifymanydifferenttypesofsecurityproblems.AcommonexampleisanSQLinjection.InanSQLinjectionthetainteddataacquiredfromthetaintsource(suchasanHTTPrequestparameter)iseventuallyusedbytheprogramtoconstructanSQLquery(ataintsink).Inthiscase,theDataflowAnalyzerreportsaSQLinjectionissue.

BecausetheDataflowAnalyzerperformsinter‐proceduralanalysis,itiscapableoftrackingtainteddataacrossmethodcallsandthroughglobalvariablesintheprogram.

TheDataflowAnalyzeroperatesonamodeloftheprogram.SCAconstructsthismodelfromprogramsourcecodeandrules.Theprogramsourcecodeprovidesthebaselayerforthemodel.Thislayerdescribesthebehaviorofmethods,therelationshipsbetweendifferentmethods,andtherelationshipbetweenmethodsandglobalvariables.SCAthenaugmentsthemodelwithrules.Theserulesdescribethepointsintheprogramthatactastaintsourcesandsinks.Theyalsodescribeprogrampointsthatcanmanipulateortransfertainteddata.

Listing4showsasimpleprogramthatillustratesacommandinjectionvulnerability.

ThecallreadFromNetwork()readsthetaintedinputintothebuffer.Theanalyzerthenconcatenatesitwithastringliteraltoformcommandandpassedtotheexecute()function,whichexecutesanewprocessspecifiedbythecommandstring.

Bybuildingamodelfromthesourcecode,theDataflowAnalyzerisabletounderstandthatthreeexternalfunctionsarecalledfromrun()andthatthereisadataflowrelationshipbetweenthosecallsthroughlocalvariables.

Becausethesourcecodeforthosefunctionsisnotpartoftheprogram,themodelisincompletewithoutasetofruleswhichdescribetherelevantcharacteristicsofthosefunctions.Withoutanyknowledgeoftheexternalfunctions,theDataflowAnalyzerdoesn'tunderstandhowtainteddataentersandmovesthroughtheprogram.

Listing 4: Command Injection Vulnerability

function run() { readFromNetwork(buffer); command = concatenate("/usr/bin" buffer); execute(command);}

Page 19: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 3: Dataflow Analyzer and Custom Rules   19

Inthiscase,theDataflowAnalyzercandetectthevulnerabilitywiththefollowingrules:

• ATaintSourceruleforreadFromNetwork()

• ATaintPass‐throughruleforconcatenate()

• ATaintSinkruleforexecute()

Dataflow Analyzer and Custom Rules ConceptsThissectionprovidesinformationondataflowcoreconcepts.TheseconceptsmapdirectiontorulesthatyoucanwritetoinformtheDataflowAnalyzer’smodelingofthecode.ThissectionalsoprovidesmoreadvancedconceptsthatillustratehowtheDataflowAnalyzerperformsinagivensituation.

Conceptsare:

• TaintSource

• TaintEntrypoint

• TaintSink

• TaintPassthrough

• TaintFlagBehavior

• ValidationFunctions

Taint SourceTainteddataentersaprogramthroughaprogrampointcalledataintsource.Commonexamplesinclude:

• AfunctionthatreadsdatafromnetworksourcessuchasanHTTPrequest

• Afunctionthatreadsdatafromanuntrusteddatasources(adatabasewrittentobyotherprograms).

Taint EntrypointAtaintentrypointisspecialtypeoftaintsourcethatdescribesafunctionwhichisinvokedwithtaintedinputbytheenvironmentorframework.Commonexamplesinclude:

• Themainfunctionoftheprogram,calledwiththeargumentsspecifiedinthecommandstring

• Afunctioninawebapplicationframework,calleddirectlybytheframeworkwithaninputparameter

Taint SinkTaintsinksareprogrampointstowhichtainteddatamustnotflow.WhentheDataflowAnalyzerdetectsapaththroughwhichtainteddatacanflowfromsourcetosink,itreportsanissue.Ataintsinkrulecancontainaconditionalexpressionwhichlimitspathsreportedtoataintsinkbyexaminingtaintflags.

Commonexamplesinclude:

• AfunctionthattakesaSQLstringandexecutesaqueryagainstadatabaseconnection

• Afunctionthattakesastringandexecutesthecommanddescribedbythestring

Page 20: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 3: Dataflow Analyzer and Custom Rules   20

Taint PassthroughTheDataflowAnalyzerautomaticallyderivespassthroughbehaviorsforfunctionsdefinedinthesourcecode.Externallydefinedfunctionswithpassthroughbehavior(suchasintheJDKlibrary),mustbemodeledwitharule.

Forexample,defaultHPFortifySecureCodingRulepackscontainarulethatdescribesthepass‐throughbehaviorofStringBuilder.append().

Apass‐throughrulemightaddorremovetaintflagsfromthetainteddata.

Taint CleanseAtaintcleanseisapointatwhichtaintisremovedormodified.Typicallythisisavalidationfunction.

Therearetwotypesoftaintcleansepoints:

Completecleanse—arulethatdescribesataintcleansewhichdoesnotspecifytaintflagstobeaddedorremoved.TheDataflowAnalyzerwillstoptaintpropagationcompletelyatthispoint.

Partialcleanse—arulethatspecifiestaintflagstobeaddedorremoved.Inthisinstancethedataisstilltainted,butthetaintflagsetischanged.

Cleanserulesarealwaysthelastappliedatanypointintheprogram.Ifafunctioncallismatchedbyacleanserule,thecleanseruleappliestotheendofanytaintpaththatgoesthroughthatfunction.Itwillcomeafteranypassthroughorsourcerulesthatmatchedthesamefunctioncall.

Inmanycases,itisimpossibletodescribeafunctioneitherintermsofapassthroughoracleanserule.Seethenoteonwritingrulesforvalidationfunctionsinthischapterforadiscussionofthedifferencesbetweenpassthroughrulesandpartialcleanserules.

Taint FlagsAtaintflagisanattributeoftainteddatathatenablestheDataflowAnalyzertodiscriminatebetweendifferenttypesoftaint.ThisisimportantbecauseitenablestheDataflowAnalyzertoaccuratelyidentifyissues.

Forexample,theinputfrombothHTTPparametersandlocalconfigurationfilesofawebapplicationmightbetainted.Theattackvectorsineachinstancearesubstantiallydifferent.AnattackercaneasilymanipulateHTTPparameters.Manipulatingconfigurationfilesonthesystemismuchmoredifficult.

ConsiderafunctionwhichchecksinputforSQLmetacharacters.Oncetainteddatahaspassedthroughthisfunction,itshouldbesafetouseinataintsinkforSQLinjection.However,thedatacannotbeconsidereduntainted.Itisstilldangeroustouseinothercontexts,suchasataintsinkforcommandinjection.TheuseoftaintflagsinrulesenablestheDataflowAnalyzertodeterminewhetherthetainteddataissafeinaspecificcontext.

Eachtaintpaththroughtheprogramcarriesasetoftaintflags.TheDataflowAnalyzercanaddorremovetaintflagsthatoriginatedatthetaintsourcepointastaintpassesthroughpass‐throughandcleansepointsintheprogram.AtaintsinkcancheckforthepresenceorabsenceoftaintflagswhichdeterminewhethertheDataflowAnalyzerwillreportaparticularpathfromsourcetosink.

Taint Flag Types

SCAprovidesthreetypesoftaintflags.Thesetaintflagtypeshelptosimplifywritingconditionalexpressionsfortaintsinks.

General—Thisisthedefaulttaintflagtype.

Neutral—Thesetaintflagsrepresent“informational”content.Neutraltaintflagsaremostoftenusedtonotethataspecificvulnerabilitycategoryhasbeenvalidated.Neutraltaintflagsareusefulinfilteringoutfalsepositives.

Page 21: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 3: Dataflow Analyzer and Custom Rules   21

Specific—ThesetaintflagsarecreatedbyincludingadeclarationwhichdescribesthecategoryoftaintflagintheRulepack.

Taintflagtypingprovidesaneasywaytointroducenewtypesoftaintintothesystemwithoutproducingunexpectedresults.Specifictaintflagsenablearulewritertocreateapairingofsourceandsinkrules.Insuchapairing,taintfromthepairedsourcerulewillnotinteractwithothersinks.Likewise,anytaintfromothersourcesintheprogramcannotinteractwiththepairedsink.

Forexample:

ConsideraprogramthatusestheAPIsgetSecret()andshareData().InthisexamplegetSecret()returnssecretdata,theoutputofwhichshouldnevergetpassedtoshareData().YoucanwritearulethatpreventsthisbydescribinggetSecret()asataintsourceandshareData()asataintsink.

Thisworksfineifthesearetheonlyrulesusedtoanalyzetheprogram.However,ifyouusethedefaultSecureCodingRulepackstoscantheprogram,SCAmightreportunintendedissues.Forexample,SCAmightreportinputfromHTTPparametersreachingshareData(),orinputfromgetSecret()beingusedinaSQLquery,eventhoughtheseusagesaresafe.

Inorderfortheserulestoworkmoreprecisely,youcanintroduceanewtaintflag(SECRET)tothesourceandsinkrules.ThesourcerulewouldaddtheSECRETtaintflag,andthesinkrulewouldcheckforthepresenceoftheSECRETtaintflag.

Thissolveshalfoftheproblem;thesinkatshareData()onlyreportsinputfromgetSecret()andnotfromothersources.However,inputfromgetSecret()mightunintentionallytriggerthereportingofissuesatothersinks,becausethosesinkswillnotexplicitlycheckagainsttheabsenceofthenewSECRETtaintflag.ThisiswhereSpecifictaintflagscomeintoplay.BydeclaringtheSECRETTaintFlagasSpecific,wepreventthattaintfromthegetSecret()sourcefrominteractingwithexistingsinksinunintendedways.SinkswhichdonotexplicitlycheckfortheSpecificTaintFlagsSECRETwillignorethetaintfromgetSecret().

Taint Flag Behavior

Understandingtheexactbehaviorofsinksinthepresenceofdifferenttypesoftaintcanbechallenging.Thefollowingdefinitionisprovidedasanadvancedconcept.

Foranysinkthatdoesnotexplicitlycheckforthepresenceorabsenceofanyspecifictaintflaginthetaintflagset,SCAwillautomaticallyaddacheckwhichensuresthatthetaintflagsetisnotspecific,wherethetaintflagsetisconsideredtobespecificifitcontainsoneormorespecifictaintflagsanddoesnotcontainanygeneraltaintflags.

Taint PathTheDataflowAnalyzerreportsavulnerabilitywhenitfindsoneormoretaintpathsbetweenasourceandasinkintheprogram.

Ataintpathcontainsasequenceofmethodcalls,stores(assignmentvariablesorfields)andloads(readsfromvariablesorfields).Itdenotesapathalongwhichtainteddataispropagatedfromataintsourcepointtoataintsinkpoint.Infact,sinceaprogrammaycontainloopsorrecursion,theremaybeaninfinitenumberofpaths.ThoughtheDataflowAnalyzercannotconsideralltaintpathsformasourcetoasink,itwillconsideratleastoneforeachuniquesetofpossibletaintflagsfromasourcetoasink.ThisguaranteesthattheDataflowAnalyzerwillconsiderthispathwhentaintflowsfromsourcetosinkalongtwopaths,onlyoneofwhichperformsvalidation.

Page 22: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 3: Dataflow Analyzer and Custom Rules   22

Validation Functions

Oneofthemostbasicrule‐writingtasksforSCAistowriterulesforvalidationfunctions.Youcandothisbyeitherbywritingapass‐throughorcleanserule.Whichruleisappropriatedependsonthecircumstances.

Incaseswherethefunctioncompletelyvalidatestheinputforallcases,acompletecleanserule(whichwillremovealltaint)isappropriate.

Inmostcases,itispreferabletoaddataintflagtothetaintpathindicatingthatacertaintypeofvalidationwasperformed.

Ifthefunctionispartofanexternallibraryandit'ssourceisnotincludedinthescan,youshouldwriteapass‐throughwiththeappropriatetaintflagmodifications.Thepass‐throughruleneedstodescribetotheDataflowAnalyzerthattainteddatadoesflowthroughthefunction,butthatvalidationisperformedintheprocess.

Ifthefunctionispartofthesourcecodebeingscanned,acleanseruleismoreappropriate.BecausetheDataflowAnalyzeralreadyderivedthepass‐throughbehaviorofthefunctionbylookingatitscode,youonlyneedtodescribethetaintflagsthattheanalyzeraddsorremoves.

Youshoulddothiswithacleanserule,becausetheanalyzerwillapplythecleanseruletothetaintpathafterthederivedpass‐through.Apass‐throughruleisappliedinparallel,creatingaseparatetaintpathandwouldnothavethedesiredeffect.

XML Representation of Dataflow RulesThissectiondescribestheXMLrepresentationofthefollowingdataflowrules:

• DataflowSourceRule

• DataflowPassthroughRule

• DataflowEntrypointRule

• DataflowCleanseRule

Dataflow Source Rule

Usedataflowsourcerulestoidentifypointsatwhichtainteddataentersaprogram.

Listing5showsadataflowsourcerulethatidentifiestheJavamethodServletRequest.getParameter()asasourceoftainteddata.

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>

Page 23: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 3: Dataflow Analyzer and Custom Rules   23

Table7describestheXMLelementsintroducedinthedataflowsinkruleshowninListing5.

Table 7: Dataflow Sink Rule XML Elements

Element Description

<InArguments> Determineswhichofthemethod'sparametersmustnotreceivetaint.Iftaintreachesoneoftheseparameters,SCAwillreportanissue.Parametersarespecifiedasacomma‐delimitedlistofeitherthereturnkeyword,thiskeyword,orthezero‐basedindexofthetargetparameter.

<TaintFlags> (Optional)Specifiesthetaintflagstoassociatewithtaintintroducedbythemethodmatchedbytherule.

TaintFlagsarespecifiedasacomma‐delimitedlist,andmusthaveaplus(+)orminus(‐)prefixtoindicateiftheyshouldbeaddedtoorremovedfromthetaintpath.Onlytheplusprefixisvalidinsourceandentrypointrules.

Dataflow Sink Rule

Usedataflowsinkrulestoidentifypointsinaprogramthattainteddatamustnotreach.

Listing6showsadataflowsinkrulethatindicatestaintmustnotreachtheStatement.executeQuery()method.

Table8describestheXMLelementsintroducedinthedataflowsinkruleshowninListing6

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>

Table 8:  XML Elements for sink rule

Element Description

<InArguments> Determineswhichofthemethod'sparametersmustnotreceivetaint.Iftaintreachesoneoftheseparameters,SCAreportsanissue.Parametersarespecifiedasacomma‐delimitedlistofeitherthereturnkeyword,thethiskeyword,orthezero‐basedindexofthetargetparameter.

Page 24: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 3: Dataflow Analyzer and Custom Rules   24

Dataflow Passthrough Rule

Usedataflowpassthroughrulestodescribehowfunctionsandmethodspropagatetaintfromtheirinputtooutput.

Listing7showsadataflowpassthroughrulethatindicatesthattaintonthestringonwhichthetrim()methodiscalledisalsoreturnedfromthemethod.

ThedataflowpassthroughruleshowninListing7combinestheconceptsof<InArguments> and<OutArguments>tomaptaintenteringthemethodononeparametertotaintexitingthemethodonanotherparameter.Ifapassthroughruleincludestaintflags,whichtheexampleabovedoesnot,thosetaintflagswilleitherbeadded(flagsprependedwitha+)orremoved(tagsprependedwitha -)fromtheparameterspecifiedbythe<OutArguments>element.

Dataflow Entrypoint Rule

Usedataflowentrypointrulestodescribeprogrampointsthatintroducetainteddatatoaprogram.Entrypointrulesdothisbydescribingthefunctionsandmethodsthattheprogramcaninvoke(eitherexternallyorthroughaninternalframeworkorothermechanismforwhichthesourcecodeisnotincludedintheanalysis).

Listing8showsadataflowentrypointrulethatindicatesthearrayofstringspassedasthefirstparametertothejavamain()methodistainted.

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>

Page 25: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 3: Dataflow Analyzer and Custom Rules   25

ThedataflowentrypointruleinListing8usesthe<InArguments>elementtodefinewhichparametersshouldbeconsideredtaintedwhenanalyzingthebodyofthespecifiedmethod.

Dataflow Cleanse Rule

Usedataflowcleanserulestodescribevalidationlogicandotheractionsthatrendertainteddataeitherpartiallyorcompletelycleansed.

Listing9showsadataflowcleanserulethatshowshowthedeclareSafe()methodcleansesvaluesthatpassthroughit.

ThedataflowcleanseruleinListing9usesthe<OutArguments> elementtospecifywhichparametersshouldbeconsideredcleansedafteracalltothespecifiedmethod.Ifacleanseruleincludestaintflags,whichtheexampleabovedoesnot,thenthosetaintflagswilleitherbeadded(flagsprependedwitha+)orremoved(tagsprependedwitha-)fromtheparameterspecifiedbythe<OutArguments>element.

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>

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>

Page 26: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 3: Dataflow Analyzer and Custom Rules   26

Custom Dataflow Rule ScenariosThissectionprovidesexamplesofcustomdataflowrules.Usetheseexamplesasthebasisforwritingcustomrules.Matchyourrequirementwithoneoftheexamples,andtailortherulestosuityoursoftware.

Thissectionprovidesthefollowing:

• ScenarioOverview

• PathManipulationScenario

• SQLInjectionandAccessControlScenario

• PersistentCross‐siteScripting

Scenario OverviewThescenariosinthissectionarewrittenagainstasampleapplicationcalledRichesWealthOnline(RWO).Thisapplicationenablesuserstoperformthefollowingonlinebankingoperations:

• Transferringmoney

• Viewingaccountstatements

• Receivingmessagesfromthebank

TheRWOapplicationdemonstratesthediverserangeofapplicationsecurityvulnerabilitiesthataretypicallyencounteredinreal‐worldapplicationsthatprovidefunctionalitysimilartoRWO.TheapplicationisbuiltwithJavaScript,Struts2,Hibernate2,andJavaEnterpriseEdition.

EachscenariohighlightsspecificvulnerabilitiesinRWOanddemonstrateshowtoidentifythemusingcustomrules.

ThescenariodoesthisbyshowinghowanattackercanexploitvulnerabilitiesinRWOsourcecode.Thescenario,whereapplicable,willhighlighthowSCAandtheSecureCodingRulepacksdetectthevulnerability.Thescenariothenexplainsthetypeofcustomrulesnecessarytodetectthevulnerabilityandshowsyouhowtocreatethem.

YoucanthenreproducetheresultsbyanalyzingRWOwitheithertheSecureCodingRulepacksorbyusingtheprovidedcustomrules.Inordertousetheprovidedcustomerrules,youmustfirstdisabletheSecureCodingRulepacks

Path Manipulation ScenarioThisscenariohighlightstherulesnecessaryfortheSCADataflowAnalyzertodetectpathmanipulationvulnerabilities.Thescenariodemonstrateshowanattackercanexploitapathmanipulationvulnerability.ItthenshowshowtheDataflowAnalyzerusessource,sinkandpassthroughrulestoidentifyapathmanipulationvulnerability.

Thisscenariohighlightsthefollowingvulnerability:

• Pathmanipulation—thistypeofvulnerabilityenablesanattackerinputtocontrolthepathsusedinfilesystemoperations.Anattackercanexploitthistypeofvulnerabilitytoaccessormodifyotherwise‐protectedsystemresources.

Page 27: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 3: Dataflow Analyzer and Custom Rules   27

Thisscenariohighlightsthefollowinganalysisandruleconcepts:

• Conditional

• Constructortoken

• Entrypoint

• Generaltaint

• Inputargument

• Label

• Modifier

• Neutraltaint

• Parametersignature

• Sink

Source CodeTheapplicationinthisscenariocontainsapathmanipulationvulnerabilityinitsbanneradvertisementwebservice.ThewebserviceenablesaffiliatestoprovideanidentifierandretrieveaJPEGimagethatcontainsanadvertisement.Anattackercanenteramaliciousidentifierinthewebservicerequest,whichwillcausetheservertorespondtotherequestwiththecontentsofsensitivefiles.

Listing10showscodethatretrievesbanneradsfortheaffiliates.

WhenanaffiliateexecutesanRMIcalltothemethodBannerAdServer.retreiveBannerAd(),theapplicationreturnstheimagefileassociatedwiththeaffiliateidentifierclientAd.

Thecodeassumesthattheincomingaffiliateidentifierspecifiedonlyasinglefilename,butifanattackerprovidestheidentifier'../../../../../windows/system.ini',theserverwillretrievethefile/images/bannerAds/../../../../../windows/system.ini.Onmostsystems,thisisequivalentto/windows/system.ini.

RulesInListing11,untrusteddataentersthroughtheJavaRMIentrypointandispassedtoafileconstructor.TheanalyzermodelsthatentrypointasasourceoftaintusingaDataflowEntrypointrule.

Listing11showstherulethatmodelsthismethodasasourceoftaint.

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; } ...}

Page 28: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 3: Dataflow Analyzer and Custom Rules   28

TheentrypointruleinListing11matchesthemethodBannerAdServer.retrieveBannerAd().The<Modifier>elementrestrictstheruletomatchonlypublicmethodsandthe<Parameters>elementenforcesthatthemethodacceptsonlyonestringargument.

Listing12describesthesinkthatmatchesthecorrespondingconstructor.

Thesinkruleusesthespecialkeywordinit^tomatchtheFile.File()constructor.Thiskeywordisreservedforclassconstructorsandallowsrulestomatchacrossinheritancerelationships.

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>

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>

Page 29: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 3: Dataflow Analyzer and Custom Rules   29

Whentaintreachesthesink,the<Conditional>elementensuresnovulnerabilityisreportediftheneutraltaintflagVALIDATED_PATH_MANIPULATIONisalsopresent.Thistaintflagindicatesthatthedatahasbeencorrectlyvalidatedbeforehand.YoucanwriteaseparatecleanseorpassthroughruletoaddtheneutraltaintflagVALIDATED_PATH_MANIPULATIONtodatathatpassesthroughtheappropriatevalidationmethod.

SQL Injection and Access Control ScenarioThisscenariohighlightstherulesthatarenecessaryforSCA’sDataflowAnalyzertodetectaccesscontrolvulnerabilitiesintheapplication.Theexampleinthescenariofocusesonanaccesscontrolvulnerability.BecausetheanalyzerdetectsSQLinjectionvulnerabilitieswithsimilarrules,thisscenarioalsocoversSQLinjectionvulnerabilitiesandcorrespondingdetectionrules.

First,thescenariowalksyouthroughtheapplication’ssourcecodetoshowyouhowtoconductaSQLinjectionattack.Then,thescenarioshowsyouhowtheDataflowAnalyzerusessource,sink,andpassthroughrulestoidentifythistypeofvulnerability

Thisscenariohighlightsthefollowingvulnerabilities:

• Accesscontrol—withoutproperaccesscontrol,executinganSQLstatementcontainingauser‐controlledprimarykeycanenableanattackertoviewunauthorizedrecords.

• SQLInjection—constructingadynamicSQLstatementwithuserinputcanenableanattackertomodifythemeaningofastatementortoexecutearbitrarySQLcommands.

Thisscenariohighlightsthefollowinganalysisandruleconcepts:

• Conditionals

• Fullcleansefunction

• Neutraltaint

• Pairedsinks

• Partialcleansefunctions

• Passthrough

Source CodeTheapplicationcontainsanaccesscontrolvulnerabilityinitstransactionservice.Theapplicationenablesuserstoprovidetheiraccountidentifierandretrievetheiraccountdetails.Anattackercanenteranyuser'saccountidentifierinthetransactionservicerequest,whichwillcausetheservertorespondwiththeaccountdetailsoftheuser.

Page 30: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 3: Dataflow Analyzer and Custom Rules   30

Listing13showstheJSPpagethatshowstransactiondetailsandhasanaccesscontrolvulnerability.

TheJSPcallsTransactionService.getTransactions()withtheaccountnumberasanargumenttoretrievetheaccountdetails.Thetransactionservicequeriesthedatabasefortheassociatedtransactions.

Listing14showshowthismethodretrievestheaccounts.

ThemethodgeneratesadynamicSQLstatementusingtheaccountnumberreadfromarequestparameter.Thecodeassumesthattheaccountnumberwillonlybelongtothecurrentuser.Thecodedoesnotverifythattheuserhassufficientauthorizationtoviewthereturneddata.

ThisvulnerabilitytypeiscloselyrelatedtotheSQLinjectionvulnerabilitytype.AnSQLinjectionvulnerabilityexistswhencodeappendsanuntrustedstringwhichcancontainarbitrarycharacters.AnattackercaninputadditionalSQLcodeandchangetheentiremeaningofthequery.

TheexampleinListing14doesnotcontainaSQLinjectionvulnerabilitybecausetheattackvectorisaLongandcanonlycontaindigits,notarbitrarycharacters.

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 {

...

}

%>

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;

}

Page 31: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 3: Dataflow Analyzer and Custom Rules   31

Listing15showsanequivalentSQLinjectionvulnerability:

RulesInListing13,untrusteddataenterstheapplicationthroughamethodcalltogetParameter().

Listing16showsarulethatmodelsthatcallasasourceoftainteddata.

ThesourceruleinListing16matchesthemethodServletRequest.getParameter().The<OutArguments>elementindicatesthatthereturnvalueofthemethodistainted.Thelackofa<TaintFlags> elementindicatesthatthisisageneralsourceoftaint,whichdoesnotassignanytaintflags.

TheJSPcodeinListing13processestheincomingaccountnumberbyconvertingitfromastringtypetoanumerictype.

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();

}

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>

Page 32: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 3: Dataflow Analyzer and Custom Rules   32

Listing17showsthepassthroughrulethatenablestheDataflowAnalyzertofollowtaintfromtheaccountNumbervariabletotheaccountvariable.

Thepassthroughruletargetsthe Long.valueOf()method.The<InArguments>and<OutArgument>elementsspecifyhowtainteddataflowsthroughthemethod.Whencodecallsthemethodwithataintedparameter,SCAwillconsiderthereturnvaluefromthecalltobetainted.TheruleaddsaspecifictaintflagNUMBERtothereturnedvaluetoindicatetheobjectisstrictlynumericinnature.TheruleremovesanyXSStaintflagfromthereturnedvaluebecauseitcannolongerbeusedtoconductaXSSattack.

Eventually,theJSPcodeinListing13executestheTransactionService.getTransactions()method,whichinturnexecutestheSession.createQuery()method.

Listing18showsthesinkrulethatdetectstheaccesscontrolvulnerability.

ItchecksthattheVALIDATED_ACCESS_CONTROL_DATABASEtaintflagisnotpresent.Ifavalidationfunctionislaterintroducedtotheflowofdatainthesourcecode,youcanwritearuleforthevalidationfunctionthataddstheVALIDATED_ACCESS_CONTROL_DATABASEtaintflag.ThisensuresthatSCAwillnotreportavulnerabilityforpathswhichflowthroughthatfunction.

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>

Page 33: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 3: Dataflow Analyzer and Custom Rules   33

Often,anaccesscontrolsinkruleispairedwithaSQLinjectionrule.ThemethodSession.createQuery()containsanaccesscontrolvulnerability.YoucanconvertanaccesscontrolsinkruletoanSQLinjectionsinkrule.

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>

Page 34: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 3: Dataflow Analyzer and Custom Rules   34

Listing19showstheequivalentSQLinjectionsinkruletothepreviousaccesscontrolsinkrule.

Bothrulestargetthefirstparameterofthesamemethod.Asopposedtotheaccesscontrolsinkrule,theSQLinjectionsinkrulemusthaveanincomingparameterthatisnotanumber.TheanalyzerchecksforthepresenceoftheneutraltaintflagVALIDATED_SQL_INJECTION.Ifthattaintispresent,novulnerabilitycanoccur.SCAdoesnotreportavulnerability.

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>

Page 35: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 3: Dataflow Analyzer and Custom Rules   35

Persistent Cross‐site Scripting

ThisscenariohighlightstherulesthatarenecessaryforHPFortifytodetectcross‐sitescripting(XSS)vulnerabilitiesintheapplication.TheDataflowAnalyzerusesthesourcesinkandpassthroughrulestoidentifythistypeofvulnerability.

Thescenariodemonstrateshowanattackercanexploitacross‐sitescriptingvulnerability.ItthenshowshowtheDataflowAnalyzerusessource,sink,andpassthroughrulestoidentifythistypeofvulnerability.

Thisscenariohighlightsthefollowingvulnerability:

• Cross‐sitescripting—sendingunvalidateddatatoawebbrowsercanresultinthebrowserexecutingmaliciouscode.

Thisscenariohighlightsthefollowinganalysisandruleconcepts:

• Generaltaint

• Neutraltaint

• Passthrough

• Sink

• Source

• Specifictaint

Source Code

Theapplicationcontainsacross‐sitescriptingvulnerabilityinthetransactionpage.Anattackercanentermaliciouscontentintoatransaction'sdescription.Thevictimreceivesatransactionnotice.Uponviewingthetransactiondetails,theapplicationdeliversmaliciouscontentthevictim'sbrowser.TheattackercanusethisvectortoexecuteJavascriptorothermaliciouscontentinthevictim'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>"); } ...

Page 36: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 3: Dataflow Analyzer and Custom Rules   36

Thecodeenumeratesanaccount'stransactionsandprintseachtransaction'sdetailstotheresponsestream.Todothis,theJSPpagecallsTransactionService.getTransactions()toretrievethetransactionsassociatedwiththeaccountspecifiedbyacctno.

Listing21showsthesourcecodethatretrievesthedatafromthedatabase.

ThismethodcallsQuery.list()toretrievetheassociatedtransactionsfromthedatabase.ThecodeinListing21callsthismethodanddoesnotvalidatethetransactionslist.Thiscodecontainsacross‐sitescriptingvulnerability.

Rules

First,theJSPcodecallsamethodtoretrievedatafromthedatabase.AdataflowsourcerulemodelsthismethodasasourceoftaintforSCA.Then,theJSPcodecallsmethodstotraversethedata.SCAusesdataflowpassthroughrulestotrackthetainteddatathroughthesemethods.Finally,theJSPcodewritesthedatatotheresponsestream.SCAusesdataflowsinkrulestodetectthefinaloutput.

ThedataflowsourceruleinListing22modelsthecalltoQuery.list()asasourceoftainteddata.

The<OutArguments>elementintheruleaboveindicatesthatthereturnvalueofthemethodshouldbeconsideredtainted.TherulealsoaddsthetaintflagXSS.ThisisaspecifictaintflagthatenablestheDataflowAnalyzertoassociatesourcesofdatathatmaybeusedforacross‐sitescriptingattackwithsinksthatarepotentiallyvulnerabletocross‐sitescripting.

ThecodeinListing1iteratesthroughthetransactionlistobjectreturnedfromthecalltoTransactionService.getTransactions().TheDataflowAnalyzerappliesthesourcerulefromListing3,withtheresultthatthelistobjectisconsideredtainted.

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;}

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>

Page 37: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 3: Dataflow Analyzer and Custom Rules   37

Listing23showsapassthroughrulethatallowstheDataflowAnalyzertopropagateandtracktaintfromthetransactionslistinListing21totheititeratorvariable.

Theinandoutargumentsspecifyhowtainteddataflowsthroughthemethod.Whentheapplicationcodecallsthemethodonataintedtargetobject(this),theDataflowAnalyzerpropagatestainttothereturnvalue.

Listing24showsthepassthroughrulethatallowstheanalyzertounderstandhowtaintisreturnedfromtheiteratorobjectonthecalltoIterator.next().

Finally,theJSPcodeinListing20constructsatransactiondescriptionanddisplaysittotheuserusingthecodebelow(repeatedforconvenience).

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>

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>

Page 38: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 3: Dataflow Analyzer and Custom Rules   38

SCAhasaccesstoallofthesourcecodeforthetransactionobject,whichmeanstheDataflowAnalyzercanautomaticallytracktaintthroughtheobject'sgettermethods.ThismeanstheDataflowAnalyzercansuccessfullytracktaintfromthetransactionobjecttothetransactionDescriptionstringwithouttheneedforadditionalrules.

Listing26showsthesinkruleusedbytheDataflowAnalyzertoidentifytheXSSvulnerability.

ThisrulemarkstheJspWriter.println()functionasasink.TherulechecksthattheXSSflagispresent,andthattheVALIDATED_CROSS_SITE_SCRIPTINGflagisnot.Adevelopermaylaterintroduceavalidationfunctionthatverifiesthecontentsofthedata.SCAwillrequireanewcleansingruleforthatvalidationfunctionwhichaddstheVALIDATED_CROSS_SITE_SCRIPTINGtaintflagtothedata.ThisensuresthatSCAwillnotreportavulnerabilityforpathswhichflowthroughthatfunction.

The<Parameters>elementinthefunctionidentifierensuresthatthisruleonlymatchesversionsoftheJspWriter.println()functionwhichtakeaStringasthefirstparameter.The<Sink>elementspecifiesthat

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>"); ...

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>

Page 39: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 3: Dataflow Analyzer and Custom Rules   39

thefirstparameteristheparameterwhichissensitivetotaint,andspecifiesthesetoftaintflagconstraintsinthe<Conditional>element.

Command Injection ScenarioThisscenariohighlightsrulesthatarenecessaryfortheDataflowAnalyzertodetectcommandinjectionvulnerabilities.Thescenariodemonstrateshowanattackercanexploitacommandinjectionvulnerability.ItthenillustrateshowDataflowAnalyzerusessource,sink,andpassthroughrulestoidentifythistypeofvulnerability.

Thissectionhighlightsthefollowingvulnerability:

• Commandinjection—executingcommandsfromanuntrustedsourceorinanuntrustedenvironmentcancauseanapplicationtoexecutemaliciouscommandsonbehalfofanattacker.

Thisscenariohighlightsthefollowinganalysisandruleconcepts:

• Inputarguments

• Outputarguments

• Passthrough

• Sink

• Source

Source Code

Theapplicationcontainsacommandinjectionvulnerabilityinitsmessagingservice.Toconducttheattack,anattackerformulatesane‐mailusingthemessagingservice.Theattackerentersmaliciouscommandsintoamessagesubject,body,to‐address,orfrom‐address.Then,theattackersubmitsthemessagetotheserverforprocessing.Uponreceivingthemessage,theserverexecutestheembeddedcommands.

Codethatformulatese‐mailsusinganinternalmessagingclassisvulnerabletothisattack.

Page 40: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 3: Dataflow Analyzer and Custom Rules   40

Listing27showsaJSPpagethatusesthisclasstobroadcastalertmessages.

TheJSPdoessomesuperficialprocessingofthemessageandthencallsSendMessage.execute().

Listing28showshowthismethodhandlestheprocessedmessage.

TheSendMessage.execute()methodcallsSendMessage.getMailCommand()togenerateacommandstringthatisexecutedtosendthee‐mail.

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++; } ...

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;}

Page 41: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 3: Dataflow Analyzer and Custom Rules   41

Listing29showshowthecommandstringisgenerated.

Thiscodeassumesthatthee‐mailmessagefieldsdonotcontain'|', ';', or '&'symbols.Thesesymbolsrepresentcommandstringdelimitersondifferentplatforms.Thesedelimiterscanbeincludedinacommandstringtoexecutemultiplecommandswithinthesamestring.Forexample,anattackermayprovidethemessagebody'" & dir C:\ > c:\files.txt &'.TheJSPcodeinListing27eventuallycallstheSendMessage.execute()methodtogenerateandexecuteashellcommandstringbasedonthemailcommand.ThismethodcallstheSendMessage.sendMail()methodtoexecutethecommandstring:

Ifanattackersubmitsthesamplemessagebody,theshellwillexecutetheoriginalcommandandtheadditionalcommandsspecifiedinthesamplemessagebody.

Rules

TainteddataenterstheJSPcodethroughacalltoServletRequest.getParameter().Listing31illustratesthismethodcallonthefirstline.

Listing31showsarulethatcausesSCAtomodelthatcallasasourceoftainteddata.

The<OutArguments>elementspecifiesthatthereturnvalueofthemethodistainted.TheruletaintsthereturnvaluewithWEBtainttoindicatethattheobjectcontainsdatawhichoriginatesfromtheweb.Traditionally,we

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;}

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); ...

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>

Page 42: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 3: Dataflow Analyzer and Custom Rules   42

associateWEBtaintwithXSStaintbecauseobjectscomingfromawebsourcemightalsocontainJavaScript.Thisextrataintisusedbyotherrulestoidentifycross‐sitescriptingvulnerabilitiesandisnotdirectlyapplicabletocommandinjectionvulnerabilitydetection.

TheJSPcodeinListing27processestheincominge‐mailmessagebycallingtheString.replaceAll()methodtoreplaceidentifierkeyswithmessagetext.

Listing32showsthepassthroughrulethatallowsSCAtofollowtaintfromthealertMessage variabletotheprocessedMessagevariable.

Listing33showsthesinkruleusedtodetectthecommandinjectionvulnerability.ThisrulemarksJava'sRuntime.exec()methodasasink.ItchecksthattheVALIDATED_COMMAND_INJECTIONtaintflagisnotpresent.Ifthedeveloperwishestoaddavalidationfunctiontovalidatethecontentsofthedata,youcanwritearuleforthevalidationfunctionthataddstheVALIDATED_COMMAND_INJECTIONtaintflagtothedataobjects.ThisensurethatSCAwillnotreportavulnerabilityforpathswhichflowthroughthatfunction.

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>

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>

Page 43: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 4: Custom Structural Rules   43

Chapter 4: Custom Structural RulesThischapterprovidesthefollowingtopics:

• UnderstandingStructuralAnalyzerandCustomRules—usethissectiontolearnabouttheControlflowAnalyzerandthewaythatitusescustomrulestofindsecurityissues.

• StructuralTreeExamples—usethissectiontofamiliarizewithstructuraltrees.

• XMLRepresentationofStructuralRules—usethissectiontolearnhowyoucanrepresentstructuralrulesinXML.

• StructuralCustomRuleScenarios—usethissectiontolearnhowtocreatecustomstructuralrules.

Understanding Structural Analyzer and Custom RulesTheStructuralAnalyzermatchesarbitraryprogramconstructsinsourcecode.UnlikeothercodeanalyzersinSCA,itisnotdesignedtofindproblemsarisingfromflowofexecutionordata.Rather,itspecializesindetectingissueswhichcanbedetectedbyidentifyingcertainpatternsofcode.

Structural TreeTheStructuralAnalyzeroperatesonamodeloftheprogramsourcecodecalledthestructuraltree.Thestructuraltreeismadeupofasetofnodeswhichrepresentprogramconstructssuchasclasses,functions,fields,codeblocks,statementsandexpressions.

Nodesinthestructuraltreecanhaveasingleparentandmanychildren.Forexample,anoderepresentingafieldisthechildofanoderepresentingtheclassinwhichthatfieldisdeclared.Likewise,anoderepresentinganexpressionisthechildofanoderepresentingthestatementinwhich+thatexpressionappears.

Eachnodeinthestructuraltreealsohasasetofproperties.Somepropertiesencodesimplevalues,suchasthenameofafunctionorthetypeofavariable.Propertiescanalsoexpressrelationshipsbetweennodeswhicharenotdirectlyconnectedbyaparent‐childrelationship.Forinstanceapropertymightbeusedtoconnecttheuseofavariableinonepartofafunctiontoitsdeclarationinanother,aclassdeclarationtoaninterfaceitimplements,orafunctioncallexpressiontothedeclarationofthefunctionitcalls.

Insomecases,anodemaybeconnectedtoanothernodebothviaaparentorchildconnectionandbyaproperty.Anassignmentstatement,forexample,hastwochildexpressions(oneontheleft‐handsideofthe=andoneontheright‐handside).Theseexpressionscanalsobereachedindividuallybythelhsandrhsproperties.Thisallowsrulestoperformmoreprecisequeriesagainstthetree.Forinstance,aquerythatlooksforanassignmentwithxasachildwouldmatchboth"x = y"and"y" = x,butaquerythatlooksforanassignmentwithxaslhswouldmatch"x = y"butnot"y = x."

Anodeinthestructuraltreehasatype,referredtoasthestructuraltype.Thestructuraltypeofanodewhichrepresentsafunctiondeclarationisdifferentthanthestructuraltypeofanodethatrepresentsaclassdeclaration,andlikewisedifferentfromthestructuraltypeofanodethatrepresentsanexpression.

Structuraltypesmakeiteasytowritequeriesthatlookforcertaintypesofnodes.Thestructuraltypeofanodealsodeterminesthesetofpropertiesthatitwillhave.AfulllistingofallstructuraltypesandtheirpropertiescanbefoundintheStructuralTypeandPropertyReference.

Page 44: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 4: Custom Structural Rules   44

Structural Tree Query Language

Thestructuraltreequerylanguageenablestheanalyzertoperformcomplexmatchesagainstthestructuraltree.Eachstructuralrulecontainsasinglequery.TheStructuralAnalyzerreportsanissueforeachconstructintheprogramthatmatchesthatquery.

Writingaquerythatmatchesaparticularcodeconstructinvolvesunderstandinghowthecodewilllookwhenrepresentedinastructuraltree.Thequeryshouldexpressconstraintsintermsofthestructuraltypeofnodestomatchandtherelationshipsbetweenthosenodes(parent‐childandpropertyrelationships).

Structural Tree ExamplesThefollowingexamplesdemonstratestheconstructionofasimplifiedstructuraltreeforaverysmallJavaprogram.Eachexampleincludesprogramsourcecode,adiagramofthestructuraltree,andanexplanation.

Theseexamplesincludestructuraltreediagramsforillustrativepurposes.Thesediagramsexcludesomedatabaseattributesforthesakeofsimplicity.Astheexampleprogrambecomesmorecomplex,someoftheedgesshowninthetreeareomitted.Thisistomaketheillustrationeasiertoread.

Usethefollowinglegendtointerpretdiagramsintheexamples.Youcanprintthispageanduseitasareferencewhengoingthroughtheexamples.

Figure 1: Diagram Legend

Example 1Thefollowingprogramconsistsonlyofaclasswithasinglememberfield.

Inthestructuraltreethefieldisrelatedtotheclassviathefieldsproperty,whichlistsallfieldsofaclass.

Listing 34: Class with Single Member Field

class C { private int f; }

Page 45: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 4: Custom Structural Rules   45

Figure 2: Class with a Single Member Field

Example 2Thisexampleaddsanemptyfunctiontotheclass.

Thestructuraltreenowincludesnodesforthefunctionanditsbodyblock.

Figure 3: Class with Function and Body Block

Listing 35: Empty Function Added to Class

class C { private int f; void func() { }}

Page 46: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 4: Custom Structural Rules   46

Aquerytoveryspecificallymatchthefieldinthiscodecouldlooklikethis:

Thequeryincludesconstraintsonthenamepropertiesoftheclassandfieldnodes,soitwouldnolongermatchthecodeiftheclassorfieldwererenamed.Normally,structuralqueriesaredesignedtobelessspecificthanthisexample.

Example 3Thisexampleaddsalocalvariabledeclarationtothefunction.

Thebodyblocknowhasachildnodeforthestatementwhichdeclaresthevariable.

Figure 4: Body Block with Child Node

Listing 36: Code Match Query

Field field: field.name == "f" and field.enclosingClass is[Class class: class.name == "C"]

Listing 37: Local Declaration Added to Function

class C { private int f; void func() { int x; }

Page 47: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 4: Custom Structural Rules   47

Example 4Thisfinalversionoftheprogramaddsastatementwhichperformsarithmeticonthevalueofthefieldandassignstheresulttothelocalvariable.

Thestructuraltreenowincludesanassignmentstatement,whichrelatestwoexpressions.Thelefthandsideexpression(lhs)denotesthelocationbeingassignedto,whiletherighthandside(rhs)isthevaluebeingassigned.Theexpressionontherighthandsideoftheassignmentbreaksdownfurtherintoanoperation(add)ontwocomponents:thefieldandaninteger.Theexpressionswhichaccessthefieldandvariableincludepropertieswhichconnecttothecorrespondingdeclarations.

Figure 5: Assignment Statement with Related Expressions

Asanexample,thefollowingquerymatchesanyassignmentintheprograminwhichthelocationbeingwrittentoisalocalvariableandtheexpressionforthevalueincludesareadofafieldwhichbelongstothesameclassastheclassinwhichthefunctionappears.Thiswouldmatchtheexamplecodeabove.UnlikethequeryinExample2,itdoesnotincludeconstraintsonnames.Itisgeneralenoughtomatchsimilarcodepatternsinotherpartsoftheprogram.

Listing 38: Added Arithmetic Statement

class C { private int f; void func() { int x; x = f + 1; }}

Page 48: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 4: Custom Structural Rules   48

XML Representation of Structural RulesTheXMLrepresentationofastructuralrulecontainsalloftheelementscommontorulesthatproducevulnerabilities.Inadditiontotheseelements,astructuralrulecontainsoneormore<Predicate>tags.Thesepredicatescontainstructuralqueries.Ifaprogramconstructmatchesthequerycontainedinany<Predicate> tag,theStructuralAnalyzerwillreportavulnerabilityforthatprogramconstruct.Itisoftenusefultoenclosethecontentsofthe<Predicate>tagin<![CDATA[ … ]]>toavoidtheneedtoescapeXMLspecialcharactersinthequery.

Structural Custom Rule ScenariosThissectionprovidesexamplesofstructuralrules.Youcanusetheseexamplesasthebasisforwritingcustomrules.Matchyourrequirementwithoneoftheexamples,andtailortherulestosuityoursoftware.

• ScenarioOverview

• LeftoverDebugScenario

• DangerousFunctionCallsScenario

• OverlyBroadCatchBlocks

• PasswordinCommentsScenario

• PoorLoggingPracticeScenario

• EmptyCatchBlockScenario

Listing 39: Assignment Query

AssignmentStatement a: a.lhs is [VariableAccess:] and a.rhs contains[FieldAccess fa: fa.field.enclosingClass == a.enclosingFunction.enclosingClass]

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>

Page 49: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 4: Custom Structural Rules   49

Scenario Overview

ThescenariosinthissectionarewrittenagainstsampleapplicationcalledRichesWealthOnline(RWO).Thisapplicationenablesusestoperformthefollowingonlinebankingoperations:

• Transferringmoney

• Viewingaccountstatements

• Receivingmessagesfromthebank

TheRWOapplicationdemonstratesthediverserangeofapplicationsecurityvulnerabilitiesthataretypicallyencounteredinreal‐worldapplicationsthatprovidefunctionalitysimilartoRWO.TheapplicationisbuiltwithJavaScript,Struts2,Hibernate2,andJavaEnterpriseEdition.

EachscenariohighlightsspecificvariabilitiesinRWOanddemonstrateshowtoidentifythemusingcustomrules.

ThescenariodoesthisbyshowinghowanattackercanexploitvulnerabilitiesinRWOsourcecode.Thescenario,whereapplicable,willhighlighthowSCAandtheSecureCodingRulepacksdetectthevulnerability.Thescenariothenexplainsthetypeofcustomrulesnecessarytodetectthevulnerabilityandshowsyouhowtocreatethem.

YoucanthenreproducetheresultsbyanalyzingRWOwitheitherSecureCodingRulepacksorbyusingtheprovidedcustomrules.Inordertousetheprovidedcustomerrules,youmustfirstdisableSecureCodingRulepacks.

Leftover Debug ScenarioThisscenariohighlightstherulesnecessaryfortheStructuralAnalyzertodetectleftoverdebugcode.Thisscenariodemonstrateshowleftoverdebugcodecanintroduceunexpectedvulnerabilitiesinaproductionenvironment.Itthenshowstherulesthatidentifythistypeofvulnerability.

Thisscenariohighlightsthefollowingtypeofvulnerability:

• Leftoverdebugcode—debugcodecanexposeunintendedfunctionalityinadeployedapplication.

Thisscenariohighlightsthefollowinganalysisandruleconcepts:

• Functionconstructobjects

• Slotconstructobjects

• Startswithoperator

• Structuralrule

Source Code

Theapplicationcontainsmethodsthatarecalledbydeveloperstodebugtheretrievalofsensitivedata.ThecodeinListing41showshowadevelopertemporarilydebugsthismethod.

Here,thedevelopercallsthedebugTransactions()methodtoexaminethecontentsofthetransactions.

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;}

Page 50: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 4: Custom Structural Rules   50

Listing42showhowtheapplicationdebugsthetransaction:

Thismethodrecordssensitivedatatoanunencryptedlogfile.Iftheapplicationexecutesthismethodwithinaproductionenvironment,sensitivedatawillbewrittentoanunencryptedfile.Thisraisestheriskofaccidentaldisclosureofsensitivedatatoathirdparty.

Rules

Thereisacommonmethodsignaturethatidentifieseverydebugmethodintheapplication.ThecodeinListing41illustratesthateachdebugmethod'snamestartswiththeword“debug.” Also,themethodacceptsoneparameteroftypejava.util.List.

ThestructuralruleinListing43identifiesallmethodsthatmatchthisdebugsignature.

Theanalyzerusesthisruletoidentifyandreportalldebugmethods.First,theruleinspectseachfunctionobject'snamepropertytoverifythemethod'snamebeginswiththeword“debug.”Then,theruleverifiesthatthereisonlyoneparametertothismethod.Therulethenverifiesthattheparameterisoftypejava.util.List.

Dangerous Function Calls ScenarioThisscenariohighlightstherulesthatarenecessaryfortheStructuralAnalyzertodetectdangerousfunctioncallvulnerabilities.Thescenarioillustrateswhyanapplicationshouldnevercallparticularmethods.ItthenshowshowtheStructuralAnalyzerusesstructuralrulestoidentifythedangerousfunctioncallvulnerability.

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()); }}

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>

Page 51: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 4: Custom Structural Rules   51

Thisscenariohighlightsthefollowingvulnerabilities:

• Cross‐sitescripting—sendingunvalidateddatatoawebbrowsercanresultinthebrowserexecutingmaliciouscode

• Dangerousmethod—neverusefunctionsthatareunsafe

Thisscenariohighlightsthefollowinganalysisandrulesconcepts:

• FunctionCallconstructobject

• Structuralrule

Source Code

Across‐sitescriptingvulnerabilityexistsintheapplication.Avalidationfunctionattemptstomitigatethisvulnerability.However,itisinadequateanddoesnotfullyeliminatetheXSSvulnerability.Youshouldnotusethisfunctionforanycurrentorfutureprojectswithintheorganization.

Theapplicationreceivesmessagesfromtheuserandwritesthecontentstoadatabase.persistentcross‐sitescriptingvulnerabilitiesmightresult.

Listing44showsamethodthatiscalledtofilteranymaliciouscharactersfromthemessagesbeforetheapplicationwritesthemtodisc.

Thefunctiondoesnotperformwhite‐listvalidationoftheincomingMessagemessageandshouldneverbecalledbyanyapplicationcode.

Rules

ThestructuralruleinListing45identifiesallinstanceswheretheapplicationcallstheMessageService.validateMessage()method.

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;}

Page 52: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 4: Custom Structural Rules   52

TheruleusestheFunctionCallconstructobjecttoinspecteverymethodthattheapplicationcalls.Theanalyzerreportsavulnerabilitywhentheconditionsoftherulearemet.

Overly Broad Catch BlocksThisscenariodemonstrateshowoverlyboardcatchblockscancausesecurityissues.ThescenariothenprovidesexamplesofrulesthatworkwiththeStructuralAnalyzertofindvulnerabilitiescausedbyoverlybroadcatchblocks.

Thisscenariohighlightsthefollowingvulnerability:

• Poorerrorhandling‐broadcatch—thecatchblockhandlesabroadswathofexceptions,potentiallytrappingdissimilarissuesorproblemsthatshouldnotbedealtwithatthispointintheprogram.

Thisscenariohighlightsthefollowinganalysisandrulesconcepts:

• CatchBlockconstructobject

• Containsoperator

• Exceptionconstructobject

• Notoperator

• ThrowStatementconstructobject

• StructuralRule

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>

Page 53: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 4: Custom Structural Rules   53

Source Code

Listing46showsanexampleofoverlybroadexceptionhandlingcode.

ThecatchblockcatchesthegenericExceptionclass.Ideally,separatecatchblockshandlespecificorrelevantsecurityexceptionsindividually.Programsshouldprocessthesesecurityexceptionsseparatelytocreateauditswhicharenecessaryfortrackingbugsanddetectingsecuritybreaches.

Noteveryoverlybroadcatchblockrepresentsaproblem.Forexample,thecodeinListing47catchesallexceptionsandthrowsthemupthecallstack.

Ahighercatchblockcanhandletheexceptioninacorrectmanner.Itisalsoacceptabletoperformabroadcatchatthehighest‐levelmethodoftheapplication.

ThecodeinListing48showsanexampleofanappropriatelybroadcatchblockthatcatchesallexceptionsimmediatelybeforetheyexittheprogram.

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 }}

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;}

Page 54: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 4: Custom Structural Rules   54

Rules

Aruleneedstoreportalloverlybroadcatchblocksthatarenotdefinedwithinthemain()methodanddoesnotthrowtheexceptionupthecallstack.

Listing49showstherulethatreportscatchblocksthatmeettheserequirements.

Thisruleidentifiesallcatchblocksintheprogramusingthecatchblockerandinspectstheclasstypeoftheexceptionbeingcaughtineachcatchblock.Theexception.type.namepropertydescribesthenameoftheclassspecifiedbythecatchblock.Thispropertymustequalthegenericexceptionclassjava.lang.Exceptionfortheruletoreportthiscatchblock.

TherulethenexcludescatchblocksthatcontainaThrowStatement,whichrepresentsathrowstatementinsidethecatchblock.

Thecatchblockconstructobject'senclosingFunction.namepropertydefinesthenameofthemethodthatcontainsthecatchblock,whichmustnotequalthevaluemain.

Whenacatchblocksatisfiesallthreeoftheseconditions,theStructuralAnalyzerwillreportanoverlybroadcatchvulnerability.

Password in Comments ScenarioThisscenariodemonstratestherulesthatenabletheStructuralAnalyzertodetectpasswordsincomments.Thisincludeshowpasswordsmightappearincommentsandhowanattackercanexploitthisvulnerability.ThescenariothenshowshowtheStructuralAnalyzerusesrulestoidentifythistypeofvulnerability.

Thisscenariohighlightsthefollowingvulnerability:

• Passwordmanagement:passwordsincomments—hardcodedpasswordscancompromisesystemsecurityinawaythatyoucannoteasilyremedy.

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}

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" andnot contains [ThrowStatement: ] andnot (enclosingFunction.name == "main") </Predicate></StructuralRule>

Page 55: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 4: Custom Structural Rules   55

Thisscenariohighlightsthefollowinganalysisandrulesconcepts:

• Commentconstructobject

• Javaregularexpressions

• Structuralrules

Source Code

Ifthesourcecodeofanapplicationcontainsauthenticationcredentialsfortheproductiondatabase,anyonewithaccesstothedevelopmentenvironmentanditssourcecodecanaccessdatainproductionenvironment.

ThecodeinListing50showshardheadedcredentialsintheProfileServiceclass.

Rules

ThestructuralruleinListing51identifiestextthatcontainstheword'password' inacommentblock,inlinecomment,orJavaDoc.

First,thisruleinspectsthedoc,inline,andblockpropertiesofeverycommentconstructobjectintheapplication.Ifoneofthesepropertiesistrue,thecommentsatisfiesthecriteriathatitmustbeablock,inline,orJavaDoccomment.

ThentheruleinspectsthetextpropertyoftheobjecttexttoseeifthevalueofthepropertyvaluematchestheJavaregularexpression'(?i).*password.*'.Thisexpressionwillmatchanytextthatcontains'password'anywherewithinitsvalue,regardlessofcapitalization.

Therulewillreportanissuewhenitfindsacommentthatsatisfiesbothsetsoftheseconditions.

Poor Logging Practice ScenarioThisscenariodemonstratestherulesthatenabletheStructuralAnalyzertoidentifyloggingobjectsthatarenotdeclaredstaticandfinal.Thescenariodemonstratesapoorloggingpractice.ThenitillustratesthewaytheStructuralAnalyzerusesrulestoidentifythistypeofissue.

Thisscenariohighlightsthefollowingvulnerability:

• Poorloggingpractice:loggernotdeclaredstaticfinal—declareloggerstobestaticandfinal.

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! {

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>

Page 56: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 4: Custom Structural Rules   56

Thisscenariohighlightsthefollowinganalysisandrulesconcepts:

• Classconstructobjects

• Containsoperator

• Fieldconstructobjects

• Notoperator

• StructuralRules

Source Code

Itisgoodprogrammingpracticetoshareasingleloggerobjectbetweenalloftheinstancesofaparticularclassandtousethesameloggerthroughoutthedurationoftheprogram.ThewaytheapplicationimplementsConnectionClassclassinListing52illustratesaviolationofthispractice.

Rules

Listing53showsarulethatreportsanyinstanceofjava.util.logging.Loggerobjectthattheprogramdeclaresasafieldbutdoesnotdeclaredusingboththestaticandfinalkeywords.

ToidentifyanimproperlydeclaredLoggerfieldobject,theStructuralAnalyzerinspectsthestaticandfinalpropertiesofeveryFieldconstructobject.Ifeithervalueisfalse,thefieldsatisfiestherule'sfirstsetofconditions.

OnceaFieldconstructobjectsatisfiesthesefirstconditions,theruleinspectstheFieldobject'sdeclaredtype.Thefieldbeaninstanceofajava.util.logging.Loggeroranextensionthatinheritsfromthatclass.

WhenaFieldconstructobjectsatisfiesbothsetsofconditions,theanalyzerreportsthefielddeclarationasanissue.

Empty Catch Block ScenarioThisscenariohighlightstherulesthatarenecessaryfortheStructuralAnalyzertodetectemptycatchblockvulnerabilities.Thescenariodemonstrateshowanattackercanexploitanemptycatchblockvulnerability.ItthenshowhowtheStructuralAnalyzerusesstructuralrulestoidentifythistypeofvulnerability.

Thescenariohighlightsthefollowingvulnerability:

• Poorerrorhandling:emptycatchblock—Ignoringanexceptioncancausetheprogramtooverlookunexpectedstatesandconditions.

Listing 52: Incorrect Declaration of Logger Object

public class ConnectionFactory { private static Logger log = Logger.getLogger(ConnectionFactory.class.getName()); private static ConnectionFactory instance = null;

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>

Page 57: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 4: Custom Structural Rules   57

Thescenariohighlightsthefollowinganalysisandrulesconcepts:

• Catchblockconstructobject

• Structuralrules

Source Code

ThecodeinListing54buildsHibernatesessionsthatareusedbytheapplicationinsubsequentdatabaseoperations.TheConnectionFactoryclass'constructorcontainscodethatmaythrowsoftwareexceptions:

Inthiscode,thecatchblockisempty.Theapplicationcannotmaintainanaccuratelogofanysecurityeventsthatmightoccur.

Rules

ToidentifytheemptycatchblockinListing54,theStructuralAnalyzershouldexamineeachCatchBlockconstructobjects'emptyproperty.Thisbooleanpropertyindicatesthatthecorrespondingcatchblockdoesnotcontainanycode.

TheruleinListing55illustratesthisstrategyforidentifyingemptycatchblocks.

Theanalyzerusesthisconfigurationruletohighlightanyemptycatchblocksintheapplication.

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}...

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>

Page 58: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 5: Custom Control Flow Rules   58

Chapter 5: Custom Control Flow RulesThischapterprovidesthefollowingtopics:

• UnderstandingControlFlowAnalyzerandCustomRules—usethissectiontolearnabouttheControlflowAnalyzerandthewaythatitusescustomrulestofindcontrolflow‐relatedsecurityissues.

• ControlFlowAnalyzerandCustomRuleConcepts—usethissectiontolearnaboutControlflowAnalyzerandruleconcepts.

• XMLRepresentationofControlFlowRules—usethissectiontolearnhowyoucanrepresentcontrolflowrulesinXML.

• CustomControlFlowRuleScenarios—usethissectiontolearnhowtocreatecustomcontrolflowrules.

Understanding Control Flow Analyzer and Custom RulesTheControlflowAnalyzerfindssecurityissuesinprogramsthathaveinsecuresequencesofoperations.ThisenablesSCAtoidentifymanytypesofsecurityproblems.

TheControlflowAnalyzermodelseachsecuritypropertyasastatemachine.Eachstatemachinehasthefollowingstates:

• Initialstate

• Anynumberofinternalstates

• Oneormoreerrorstates

Thestatemachineisintheinitialstateatthebeginningofafunction.TheControlflowAnalyzerreportsavulnerabilitywhenastatemachineentersanerrorstate.

Thestatesinthestatemachineareconnectedbytransitions.Atransitionleadsfromonestate(thesourcestate)toanotherstate(thedestinationstate)andhasoneormoreassociaterulepatterns.Rulepatternsspecifyprogramconstructs.Thestateofastatemachinechangesfromsourcetodestinationwhenoneofthetransition’srulepatternsmatchesastatementthattheControlflowAnalyzerisanalyzing.

Astatecanhaveanynumberoftransitionsleadingoutoforintoit.TheControlflowAnalyzerchecksthetransitionsleadingoutofastateoneatatimeintheorderinwhichtheyappearinthestatemachinedefinition.TheControlflowAnalyzerexecutesthefirststatementthatmatchesastatement.TheControlflowAnalyzerignoresanyothertransitionoutofthesamestate.

Youcanusethistolimitthenumberoffunctionsthattheprogramcancallinagivencontext:thestaterepresentingthatcontextwouldhaveatransitiontoasafestate(possiblyitself)iftheprogramcallsanallowedfunction,andatransitiontoanerrorstateiftheprogramcallsanyfunction.

TheControlflowAnalyzeroperatesinterprocedurally,soifonefunctioncallsasecondfunction,andastatetransitionoccursinsidethatsecondfunction,thestateinthefirst(calling)functionisupdatedaswell.

ThefollowingexampleprogramusesalockingAPI.TheAPIcontractstatesthatafunctionthatacquiresthelockmustreleaseitbeforereturning.Insomecases,thesampleprogramdoesnotreleasethelockbeforereturning.

Listing56showsasampleprogramthatdoesnotalwaysreleasethelockbeforereturning.

Page 59: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 5: Custom Control Flow Rules   59

ThecontractforthelockingAPIisdescribedasastatemachine.

Table9showsthestatesandtransitionsofthestatemachineprovidedinListing57.

Table 9: State machine states

Source State Destination StateProgram Construct Causing Transition

Unlocked(startstate) Locked CalltogetLock()

Locked Released CalltoreleaseLock()

Locked Leaked(errorstate) Functionends

Listing57showsthecontrolflowrulethatencodesthisstatemachine.

WhentheControlflowAnalyzerusesthisruletochecktheexamplefunctionabove,thestatema‐chineisinitiallyintheUnlockedstate.Whentheprogramacquiresthelockonline2,thestatemachinetransitionstotheLockedstate,andtherulevariablemapstherulevariable"lock"totheprogramvariable"fileLock"(seebelowformorediscussionofrulevariables).Atthebranchonline3,theControlflowAnalyzercopiesthestatemachine.Onecopyrunsinthe"true"branchoftheconditional,andtheothercopyrunsinthe"false"branch.

Bothcopiesareinitiallyinthe"Locked"state.Whenthecopyrunningonthe"true"branchencountersthereturnstatementonline4,ittransitionstothe"Leaked"state.Because"Leaked"isanerrorstate,theControlflowAnalyzerreportsavulnerability.Meanwhile,thecopyofthemachinerunningonthe"false"branchwillencountertheprogramreleasingthelockonline7andtransitiontotheReleasedstate.Whenthiscopyencountersthereturnstatementonline8,itwillnottransitiontotheerrorstatebecausethereisnotransitionfromReleasedtoLeaked.

Listing 56: Locking API

function readFile(File file) { Lock fileLock = getLock(file); if (!isReadable(file)) { return; } doRead(file); releaseLock(fileLock); return;}

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() }

Page 60: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 5: Custom Control Flow Rules   60

Control Flow Analyzer and Custom Rule ConceptsThissectionprovidesinformationonthefollowingControlflowAnalyzerandruleconcepts:

• RulePattern

• RuleVariable

• RuleBinding

Rule PatternArulepatternspecifiestheprogramconstructsthatcauseastatetransitiontooccur.Therulepatternsarethepartsenclosedin{ … }.

Rule VariableArulevariableisapartofarulepatternthatisaplaceholderforanactualprogramvalue.Rulevariablestietogethervaluesusedindifferentrulepatterns.InListing57,therulevariable"lock"tiestogetherthereturnvaluefromgetLock()andtheparametertoreleaseLock().Withoutthisrulevariable,thestatemachinewouldtransitiontotheReleasedstatewheneveranylockisre‐leased,evenifsomelocksinthefunctionarestillunreleased.

Rule BindingArulebindingisamappingbetweenarulevariableandaprogramvalue(orasetofprogramvalues).InListing57,theanalyzercreatesarulebindingthattiestherulevariable"lock"tothe"fileLock" which is a local variable. Whentheanalyzerevaluatesotherrulepatternsthatusetherulevariable"lock"thepatternonlymatchesiftherulebindingfor"lock"matchestheprogramvalueusedinitsplace.

RulevariablesandrulebindingsenabletheControlflowAnalyzertomodelthebehaviorofspecificobjectsintheprogram,ratherthanjusttheglobalstateoftheprogram.

Listing58showsanexample.

Thisfunctionacquirestwolocks,butonlyreleasesoneofthem.Withoutrulevariables,theControlflowAnalyzerisnotabletodetectthiserror,becauseitwouldseeonlythat"releaseLock"iscalled,withoutcorrelatingthecallsto"getLock"and"releaseLock."WiththerulevariablesinListing58,however,theanalyzercorrelatesthesetwocalls.

Whentheanalyzerencountersthefirst"getLock"callonline2,itcreatesarulebindingbetweentherulevariable"lock"andtheprogramvariable"lock1,"andmovestotheLockedstate.ItalsocreatesacopyofthestatemachinethatremainsintheUnlockedstate.Theanalyzerthenencountersthesecondcallto"getLock."

ThecopyofthestatemachinethatisintheLockedstateignoresthiscall,becauseitdoesn'tmatchanytransitionsoutoftheLockedstate.ThecopythatisintheUnlockedstate,however,doesmatchthiscall.Theanalyzercreatesasecondrulebindingthatmapstherulevariable"lock"totheprogramvariable"lock2,"andthissecondcopyofthestatema‐chinechangestotheLockedstate.

Listing 58: Rule Variable and Bindings

function useTwoLocks() { Lock lock1 = getLock(); Lock lock2 = getLock(); releaseLock(lock1); return; }

Page 61: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 5: Custom Control Flow Rules   61

InListing58thefirststatemachinetransitionstotheReleasedstate,whilethesecondmachineremainsintheLockedstate.Atthereturnstatement,thesecondmachineremainsintheLockedstate,andtheanalyzerreportsanissue.

XML Representation of Control Flow RulesTheXMLrepresentationofacontrolflowruleisbasedontherepresentationofavulnerability‐causingrule.Inadditiontotheelementscommontoallsuchrules,therearesomeXMLtagsthatarespecifictocontrolflowrulesorthatareuseddifferentlyincontrolflowrules.

TheseXMLtagsare:

• Definition

• FunctionIdentifiers

• FunctionCallIdentifiers

• Limits

• PrimaryState

DefinitionThecontrolflowstatemachinedefinitionisenclosedinthe<Definition>tag.InXML,youcanenclosethecontentsofthistagin<![CDATA[ … ]]>toavoidtheneedtoescapeXMLspecialcharactersinthestatemachinedefinition.

Function IdentifiersLikeotherruletypes,controlflowrulesuse<FunctionIdentifier>tagstoidentifyfunctions.Unlikemostotherruletypes,controlflowrulescancontainmultiplefunctionidentifiers.Thisisbecauseastatemachinedefinedbyacontrolflowrulecanrefertomultiplefunctions.The"id" attributeofthe<FunctionIdentifier>tagspecifiesthenamebywhichyoucanusethefunctionidentifierwithintheruledefinitions.

Function Call IdentifiersFunctioncallidentifierscombineand<Conditional>tomatchspecificcallstoafunction.The<FunctionCallIdentifier>tagusesidattributesinmuchthesamewayasthe<FunctionIdentifier> tag;the“id”attributeofthefunctionidentifierinsidethefunctioncallidentifierisnotused.

LimitsControlflowrulesshouldonlycheckspecificpropertiesincertainfunctions.Forexample,acontrolflowrulecouldcheckthateveryfunctioncalledProcessRequestmustcalltheCheckCredentialsfunctionbeforecallingthefunctionAccessPrivateData.

YoucanpreventthisrulefromrunningonmethodsotherthanProcessRequestbyaddinga<Limit>sectiontotheruledefinition.Inthiscase,the<Limit>tagcontainsoneormore<FunctionIdentifier>tags.Therulewillonlyevaluatefunctionsthatmatchoneofthesefunctionidentifiers.

Arulewithano<Limit>tagwillrunonallfunctions.

Page 62: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 5: Custom Control Flow Rules   62

Primary StateControlflowstatemachinescontainmultiplestates.Youcandesignateoneofthesestatesastheprimary.Whenyouviewanissue,thetraceelementthatdisplaysfirstisthefirstonethattransitionedintoitsprimarystate.

Ifseveralcontrolflowtracestransitionintotheirprimarystateatthesameprogramlocation,theControlflowAnalyzerwillgroupthesetracesintoonecontrolflowissue.Thisissuewillcontainmultipletraces.

Youspecifytheprimarystatebyputtingthestatenameinsidethe<PrimaryState>XMLtag.Iftheruledoesnotexplicitlyspecifyaprimarystate,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>

Page 63: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 5: Custom Control Flow Rules   63

Custom Control Flow Rule ScenariosThissectionprovidesexamplesofcustomcontrolflowrules.Youcanusetheseexamplesasthebasisforcreatingcustomrules.Matchyourrequirementwithoneoftheexamples,andtailortherulestosuiteyoursoftware.

• ResourceLeakScenario

• NullPointerCheckScenario

Scenario OverviewThescenariosinthissectionarewrittenagainstsampleapplicationcalledRichesWealthOnline(RWO).Thisapplicationenablesusestoperformthefollowingonlinebankingoperations:

• Transferringmoney

• Viewingaccountstatements

• Receivingmessagesfromthebank

TheRWOapplicationdemonstratesthediverserangeofapplicationsecurityvulnerabilitiesthataretypicallyencounteredinreal‐worldapplicationsthatprovidefunctionalitysimilartoRWO.TheapplicationisbuiltwithJavaScript,Struts2,Hibernate2,andJavaEnterpriseEdition.

EachscenariohighlightsspecificvulnerabilitiesinRWOanddemonstrateshowtoidentifythemusingcustomrules.

ThescenariodoesthisbyshowinghowanattackercanexploitvulnerabilitiesinRWOsourcecode.Thescenario,whereapplicable,willhighlighthowSCAandtheSecureCodingRulepacksdetectthevulnerability.Thescenariothenexplainsthetypeofcustomrulesnecessarytodetectthevulnerabilityandshowsyouhowtocreatethem.

YoucanthenreproducetheresultsbyanalyzingRWOwitheithertheSecureCodingRulepacksorbyusingtheprovidedcustomrules.Inordertousetheprovidedcustomrules,youmustfirstdisabletheSecureCodingRulepacks.

Resource Leak ScenarioThisscenariohighlightstherulesthatarenecessaryfortheControlflowAnalyzertodetectresourceleaks.Thisscenariodemonstrateshowanattackercanexploitaresourceleakvulnerability.Then,itshowshowtheControlflowAnalyzerusescontrolflowrulestoidentifythistypeofvulnerability.

Thisscenariohighlightsthefollowingvulnerability:

• Poorcodequality:resourceleaks—theprogramcanpotentiallyfailtoreleaseasystemresource.

Thisscenariohighlightsthefollowinganalysisandruleconcepts:

• Controlflowrules

• Finitestatemachines

• Non‐returningrules

• #endscopeoperator

• #ifblockoperator

Page 64: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 5: Custom Control Flow Rules   64

Source Code

Anattackerexploitsaresourceleakvulnerabilityasalogicaldenial‐of‐serviceattack.Imaginecodethatusesascarcesystemresourceandcontainsaresourceleak.Theattackerdepletestheassociatedresourcebyexecutingthecoderepeatedly.Thisleadstoresourcedepletionthatpreventslegitimateusersfromusingtheservice.

ThecodeinListing60containsmanyresourceleaks.Itillustrateshowtheapplicationtypicallysetsupaconnectiontoitsdatabaseandperformssomequeryfornecessarydata.Thisparticularmethodretrievesdetaileddataaboutalistofrolesandreportstheonesthathaveadministrativeprivileges:

First,thecodecreatesaconnectionobjectbasedonanexistingHibernatedatabaseconnection.Then,thecodecreatesastatementobjectusingthenewconnectionobject.Finally,thecodeexecutesthestatementobject'squerymethodthatreturnsaresult‐setobject.Afterwards,thecodeneedstofreealloftheassociatedresourcesbyclosingtheconnection,statement,andresult‐setobjects.

Thecodefailstoclosetheseobjectsunderallconditions.Thecodeneverclosestheconnectionobjectunderanyconditions.Also,thecodeattemptstoclosethestatementobjectwithinthefinallyblock.However,thecodeexecutestheSystem.exit()methodfirstandtheStatement.close()methodisneverreached.Finally,thecodedoesnotclosetheresult‐setobjectwhentheroleisnotanadministratorandanexceptiondoesnotoccur.

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; } }}

Page 65: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 5: Custom Control Flow Rules   65

Source Code

TheControlflowAnalyzerusesanobject'sfinitestatemachine(FSM)toidentifyunsafesequencesofoperationsthatshouldnotbeperformedonthatobject.

Figure6describesthepossiblestatesofanobject.

Figure 6: Dynamically Allocated/Deallocated Object States

First,theanalyzerallocatesaseparateFSMforeachobject.Then,theanalyzersetstheobject'sinitialstateasunallocatedbeforecodeallocatestheobject.Oncecodeallocatesanobject,theanalyzerupdatestheobject'sFSMstatetotheallocatedstate.Then,theanalyzerexaminesallcodepathsthatarewithintheobject'sscope.

Theanalyzerencountersacodepathwherethecodecallstheobject'sclose()method.Insuchacase,theanalyzerupdatestheobject'sFSMstatetothesafereleasedstate.Eventually,theobjectfallsoutofscope.Thisparticularcodepathcorrectlyreleasestheresourceandnovulnerabilityexists.Theanalyzerwillnotreportavulnerabilityforthispathbecausetheobjectfallsoutofscopeinasafestate.

Theanalyzerencounterscodepathswheretheobjectfallsout‐of‐scopeandthecodehasnotpreviouslycalledtheobject'sclose()method.Insuchacase,theanalyzerupdatestheobject'sFSMstatetotheunsafeleakedstate.Theanalyzerreportsthevulnerabilitybecausetheanalyzerhasexplicitlysettheobject'sFSMstatetoanunsafestate.

TheruleinListing60describestheFSMmodelthatappliesforthesafeandunsafeallocationoftheConnection,Statement,orResultSetobjects.

Page 66: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 5: Custom Control Flow Rules   66

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"

Page 67: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 5: Custom Control Flow Rules   67

Theruledeclarestheinitialstateunallocatedusingtheadditional(start)keyword.Also,theruledeclarestheunsafeleakedstateusingtheadditional(error)keyword.EachmethodthatallocatesaConnection,Statement,orResultSetobjectshasaseparatefunctionidentifierelementresource1,resource2,orresource3.Thecorrespondingmethodsforreleasingtheseobjectsareidentifiedasrelease1,release2,andrelease3.Theanalyzertransitionsbetweenthedeclaredstatesforagivenobjectbasedondeclaredconditionsintherulesuchastheexecutionofthedeclaredfunctions.

Thecondition#endscope(x)describesthespecialcircumstancewheretheobject xhasexitedscopeandisnolongeraccessible.Inthisrule,theobjecthasbeenallocatedintheallocatedstate.Itreachestheerrorstateleakediftheobjectfallsoutofscopeandisintheallocatedstateatthetime.

Thecondition#ifblock(x == y,z)describesthepresenceofanif‐blockstatementwithinthecode.Itstatesthatifxequalsywitharesultofz,theconditionissatisfiedandtheanalyzershouldtransitiontothedeclaredstate.Inthisrule,theconditional'#ifblock(c, null, true)'describesanequalitycomparisonbetweenthetrackedobjectcandthevaluenull.Ifcisequaltonull,codedidnotsuccessfullyallocateobject c.Theanalyzershouldsafelytransitiontheobjectctoitssafestatereleasedasitisimpossiblefortheobjecttoleakresources.

Thereisaleakthattheanalyzerdoesnotcorrectlyidentifyusingjustthisrule.ThecodedeallocatestheStatementobjectwithinthefinallyblockafteritcallstheSystem.exit()method.Thecodeneverdeallocates

</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>

Listing 61: Control Flow Rule: Resource Leak (Continued)

Page 68: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 5: Custom Control Flow Rules   68

theobjectcorrectlybecausetheSystem.exit()methodprematurelyexitsthecode.Theallocatedobjectreachestheend‐of‐scopeconditionprematurely.

Theanalyzerneedsspecialknowledgeofmethodsthatprematurelyforceanout‐of‐scopecondition.Otherwise,theanalyzercannotalwaysidentifywhencodeforcesanend‐of‐scopecondition.Thenon‐returningruleinListing62describesthisspecialqualityoftheSystem.exit()method:

WhenSCAincludesthenon‐returningruleandcontrolflowrulesinascan,theControlflowAnalyzeridentifiesthattheStatementobjectisnotproperlydisposedofbeforeitreachesitsprematureend‐of‐scopecondition.

Null Pointer Check ScenarioThisscenariohighlightsrulesthatenabletheControlflowAnalyzertodetectmissingnullpointercheckvulnerabilities.Thescenariodemonstrateshowtoexploitamissingnullpointercheckvulnerability.ThenitillustrateshowtheControlflowAnalyzerusesrulestoidentifythistypeofvulnerability.

Thisscenariohighlightsthefollowingvulnerability.

• Missingcheckagainstnull—theprogramcandereferenceanullpointerbecauseitdoesnotcheckthereturnvalueofafunctionthatmightreturnnull.

Thisscenariohighlightsthefollowinganalysisandrulesconcepts:

• Errorstate

• Finitestatemachine

• Startingstate

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>

Page 69: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 5: Custom Control Flow Rules   69

Source Code

Theapplicationcontainsamissingnullpointercheckwithinitsmessagingservice.Anattackercansubmitarequesttodisplayamessageandomitnecessarypiecesofinformationfromtherequest.Theapplicationthrowsanexception,anddisclosesarchitectureandconfigurationinformationtotheattacker.

Listing63showsJSPcodefromtheapplicationthatretrievesanddisplaysamessage.

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,theJSPcodecallsincomingParameter.trim()andanullpointerexceptionoccurs.Finally,theframeworksendstheunhandledexceptionandothersensitiveinformationtotheattacker'sbrowser.

Rules

Theapplicationcontainsamissingnullpointercheckwithinitsmessagingservice.Anattackercansubmitarequesttodisplayamessageandomitnecessarypiecesofinformationfromtherequest.Theapplicationthrowsanexceptionanddisclosessensitiveinformationtotheuserpertainingtoitsarchitectureandconfiguration.

Figure7showsJSPcodefromtheapplicationthatretrievesanddisplaysamessage.

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()); %> ...

Page 70: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 5: Custom Control Flow Rules   70

Figure 7: Proposed FSM Model: Describes Missing Null Checks

InFigure7,theControlflowAnalyzerwillsettheFSMstateto'may be null'whenitobservesthattheJSPcodeassignsavaluetotheincomingParametervariable.Atthispoint,thecodehasnotyetverifiedthatthevariable'svalueisnotnull.

Then,theanalyzerobservesthatthecodecallsamethodontheincomingParametervariablewithoutinspectingitsvalue.Theanalyzertransitionsthevariable'sFSMfromthe'may be null'statetothe'dereferenced'errorstate.TheanalyzerreportsthevulnerabilitywhenittransitionstheFSMintotheerrorstate.

Ideally,thecodeshouldhaveinspectedtheobject'svaluebeforeusingit.Theanalyzerwouldthenobservethatthecodeperformsthischeckandwouldtransitiontheobject'sFSMfromthe'may be null' statetothe'checked'safestate.

Listing64describestheFSMmodelasacontrolflow.

Page 71: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 5: Custom Control Flow Rules   71

TheanalyzerinitializestheFSMinthestartstatestart.ThetransitionfromthestartstatetothemayBeNullstateoccurswhentheanalyzerobservesacalltoafunctionmatchedby$get,andtheFSMisboundtothevaluereturnedbythatfunction.

TheanalyzerwilltransitiontheFSMfromthemayBeNulltocheckedstatewhenitencounterscodethatcomparesthevaluetonull.The#compare(f,null)statementdescribesthistransition.

Alternatively,theanalyzerwilltransitiontheFSMfromthemayBeNullstatetothedereferencederrorstateifcodedereferencesthevaluewhileinthisstate.Thestatementallocated -> used { f.$any(...) | *f }describesthistransition.

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>

Page 72: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 6: Custom Content and Configuration Rules   72

Chapter 6: Custom Content and Configuration RulesThischapterprovidesthefollowingtopics:

• UnderstandingContentAnalyzerandCustomRules—usethissectiontolearnaboutthecontentanalyzerandhowitusescustomrulestofindsecurityissues.

• UnderstandingConfigurationAnalyzerandCustomRules—usethissectiontolearnabouttheConfigurationAnalyzerandhowitusescustomrulestofindsecurityissues.

• XMLRepresentationofContentRules—usethissectiontolearnhowyoucanrepresentcontentrulesinXML.

• XMLRepresentationofConfigurationRules—usethissectiontolearnhowyoucanrepresentconfigurationrulesinXML.

• CustomContentandConfigurationRuleScenarios—usethissectiontolearnhowtocreatecustomcontentandconfigurationrules.

Understanding Content Analyzer and Custom RulesThecontentanalyzerfindssecurityissuesandpolicyviolationsinHTMLcontent.InadditiontostaticHTMLpages,thecontentanalyzerperformsthesechecksonfilesthatcontaindynamicHTML,suchasPHP,JSP,andclassicASPfiles.

ContentanalyzerrulesuseXML‐XPATHnotationtodescribeproblematicconstructsinHTMLfiles.ThecontentanalyzerconvertstheHTMLcontentintoanXMLformandappliestheXPathrulestothisXMLform.

Understanding Configuration Analyzer and Custom RulesTheConfigurationAnalyzerfindssecurityissuesinapplicationconfigurationfiles.Thisanalysiscanfindinstanceswhereanapplicationisconfiguredinsecurely,andcanalsoenforcesecuritypoliciesbyidentifyingconfigurationfilesthatarenotincompliancewiththosepolicies.

ConfigurationAnalyzerrulesspecifyconstraintsonconfigurationproperties.

TheConfigurationAnalyzerunderstandsXMLfilesandJavapropertiesfiles.Eachruleoperatesononetypeoffile.RulesthatanalyzeXMLfilesuseXPathnotationtodescribeXMLconstructsthatshouldbereportedbytheanalyzer.Rulesthatanalyzepropertiesfilesspecifyeitherpropertynamesorpropertyvaluesthatshouldbereported.Rulesofeithertypecanberestrictedtorunonlyonfileswithspecificnames.

XML Representation of Content RulesInadditiontotheXMLelementscommontoallvulnerability‐producingrules,rulesforthecontentanalyzercontainan<XPathMatch>element.The"expression"attributeofthiselementspecifiestheXPathexpressionthattheConfigurationAnalyzerevaluatesagainsttheXMLrepresentationofHTMLdocuments.

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>

Page 73: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 6: Custom Content and Configuration Rules   73

XML Representation of Configuration RulesRuleswrittenfortheConfigurationAnalyzercheckeitherXMLorpropertiesfiles.Bothtypesofconfigurationrulesshareelementsthatarecommontoallvulnerability‐findingrules.Configurationrulesalsohaveasequenceof<Check>XMLtags.

Each<Check>tagspecifiesthepropertiesandfilesthattheConfigurationAnalyzerchecks.Thecontentsofthe<Check>tagvariesdependingonthetypeoffilethattheConfigurationAnalyzerischecking.

Every<Check>tagcontainsa<ConfigFile>tagthatspecifiesthefilesforwhichthecheckapplies.The<ConfigFile>taghasa"type"attributethatmustbesettoeither"xml"or"properties."Thisdefinesthetypeofconfigurationfileforwhichthecheckshouldbeperformed.The<ConfigFile>tagalsocontainsa<Value>or<Pattern>tagthatischeckedagainstthefilenameofeveryfileofthespecifiedtype.Thecheckwillonlybeappliedtofilesforwhichthefiletypematchesthe"type"attributeandthefilenamematchesthe<Value>or<Pattern>insidethe<ConfigFile>tag.

ForXMLfiles,the"type"attributeofthe<ConfigFile>tagshouldbesetto"xml."The<Check>tagmustalsocontainan<XPathMatch>tag.Thistagisidenticaltotheoneusedincontentrules.

Listing66showstypeattributesforconfigurationrules.

Forpropertiesfiles,the"type"attributeofthe<ConfigFile>tagshouldbesetto"properties."The<Check>tagmustcontaina<NameMatch>tagthatspecifiesthepropertynametobechecked.The<Check>tagmayalsoincludeeithera<ValueMatch>tagora<NotPresent>tag.The<ValueMatch>tagspecifiesa<Pattern>or<Value>thatshouldbecheckedagainstthevalueofpropertieswhosenamematchesthe<NameMatch>tag.The<NotPresent>tag,whichhasnocontents,specifiesthattheanalyzershouldreportanissueifnopropertymatchingthe<NameMatch>tagappearsinapropertiesfilematchedbythe<ConfigFile>tag.

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>

Page 74: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 6: Custom Content and Configuration Rules   74

Listing67showsanameorvaluematchexample.

Custom Content and Configuration Rule ScenariosThissectionprovidesexamplesofcustomconfigurationrules.Youcanusetheseexamplesasthebasisforwritingcustomrules.Matchyourrequirementwithoneoftheexamples,andtailortherulestosuityoursoftware.

• CustomRuleScenarioOverview

• PropertyFileScenario

• TomcatFileScenario

Custom Rule Scenario OverviewThescenariosinthissectionarewrittenagainstsampleapplicationcalledRichesWealthOnline(RWO).Thisapplicationenablesusestoperformthefollowingonlinebankingoperations:

• Transferringmoney

• Viewingaccountstatements

• Receivingmessagesfromthebank

TheRWOapplicationdemonstratesthediverserangeofapplicationsecurityvulnerabilitiesthataretypicallyencounteredinreal‐worldapplicationsthatprovidefunctionalitysimilartoRWO.TheapplicationisbuiltwithJavaScript,Struts2,Hibernate2,andJavaEnterpriseEdition.

EachscenariohighlightsspecificvulnerabilitiesinRWOanddemonstrateshowtoidentifythemusingcustomrules.

ThescenariodoesthisbyshowinghowanattackercanexploitvulnerabilitiesinRWOsourcecode.Thescenario,whereapplicable,willhighlighthowSCAandSecureCodingRulepacksdetectthevulnerability.Thescenariothenexplainsthetypeofcustomrulesnecessarytodetectthevulnerabilityandshowsyouhowtocreatethem.

YoucanthenreproducetheresultsbyanalyzingRWOwitheitherSecureCodingRulepacksorbyusingtheprovidedcustomrules.Inordertousetheprovidedcustomrules,youmustfirstdisableSecureCodingRulepacks.

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>

Page 75: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 6: Custom Content and Configuration Rules   75

Property File ScenarioThisscenariodemonstratestherulesthatenabletheConfigurationAnalyzertodetectconfigurationvulnerabilities.Thescenarioillustratesthewayhowincorrectsettingcanleadtounexpecteddowntimeinaproductionenvironment.ThenitshowshowtheConfigurationAnalyzerusesrulestoidentifyandreporttheseincorrectsettings.

Thisscenariohighlightsthefollowingvulnerability:

• Environmentmisconfiguration—configurationfilesforanapplicationcontainincorrectvaluesinaproductionenvironment.Thesemisconfigurationstypicallyintroduceothervulnerabilities,includingthoserelatedtocommunicationsecurity,authentication,authorization,datasecurity,andexceptionhandling.

Thisscenariohighlightsthefollowinganalysisandruleconcepts:

• Configurationrules

• Javaregularexpressions

• Propertyfiles

Source CodeByconvention,usersshouldsendandreceivemessagesthroughthegatewayoftheproductionmailsystem.Intestcases,however,thesystemroutesmessagesthroughthegatewayofthetestenvironment.Inthisscenario,theincorrectSMTPsettingarereleasedintotheproductionenvironment.

Listing68showsthesampleSMTPconfiguration.

Afterloadingtheseincorrectvalues,themailhandlingcodesendsmessagesthroughmail.test.riches.cominsteadoftheproductiongateway.

RulesListing69showstheconfigurationrulethatdetectstheinvalidSMTPhostnamevalueinthepropertiesfile:

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!

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>

Page 76: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 6: Custom Content and Configuration Rules   76

Theconfigurationruletargetsthemailserver.legacy.propertiespropertiesfile.Itcomparesthevalueofthepropertyriches.mail.smtpHostnametotheJavaregularexpression'(.*)\.test.riches.com'.Thevalueshouldnevermatchastringwiththefollowingsequence:zeroormorecharacters;aperiod;andthenthecharacters'test.riches.com'.Ifthissequenceoccurs,theConfigurationAnalyzeridentifiesaconfigurationvulnerability

Tomcat File ScenarioThisscenariohighlightstherulesthatenabletheConfigurationAnalyzertoidentifyspecificconfigurationvulnerabilities.Thescenariodemonstrateshowamisconfigurationintheapplicationcanleadtothedisclosureofsensitiveinformation.ItthenshowsthehowtheConfigurationAnalyzerusesrulestoidentifythistypeofmisconfiguration.

Thisscenariohighlightsthefollowingvulnerability:

• J2EEMisconfiguration—theunderlyinginfrastructuresupportingtheapplicationisimproperlyconfigured.Thisresultsinnewvulnerabilitiesrelatedtocommunicationsecurity,datasecurity,andexceptionhandling.

Thisscenariohighlightsthefollowinganalysisandrulesconcepts:

• Configurationrules

• Javaregularexpressions

• XMLfiles

• XPathexpressions

Source Code

TheapplicationisdeployedinaTomcatWebserversharedbymultipleapplications.Someoftheapplicationsrelyontheservertoauthenticateincomingrequests.TheTomcatconfigurationfilecontainsarealmthatdescribestheauthenticationconfigurationofanotherapplication.

Therealmdescriptoraboveapplicationusesanauthenticationconfigurationwithadebuglevelgreaterthantwo.Withthisconfiguration,theauthenticationservicewilllogusernamesandpasswordsinaplaintextlogfile,whichcancompromisetheirsecurity.

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"/>

Page 77: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 6: Custom Content and Configuration Rules   77

Rule

Listing71showsarulethatidentifiesanXMLdocumentthatcontainsanodeRealmwithadebugattribute'svaluesettoanumbergreaterthantwo.

TheXPathexpression'//Realm[@debug > 2])'describestheXMLcontentnecessaryfortheConfigurationAnalyzertoidentifythemisconfiguration.

TheexpressionidentifiesanyRealmelementsthathaveadebugattributewithvaluegreaterthantwo.The<XPathMatch reporton>conditionspecifiesthatSCAshouldhighlighttheproblematicdebugattributeinsteadoftheparentrealmelement.

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>

Page 78: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 7: Structural Rules Language Reference   78

Chapter 7: Structural Rules Language ReferenceThisdocumentprovidesthefollowingtopics:

• SyntaxandGrammar—usethissectionasareferenceforstructuralrulesyntaxandgrammar.

• Types—usethissectiontounderstandthetypesystemusedbystructuredrules.

Syntax and GrammarThefollowingisasimplifiedBNF‐stylegrammarfortheStructuralTreeQueryLanguage.Notethatforreadabilitypurposesitisinsomecasesmoreandinsomecaseslessstrictthantheactualgrammar.

Listing72showsthestructuraltreequerylanguage.

TypesTheruleslanguageisstronglytyped.Typesintheruleslanguagearecalledstructuraltypestodistinguishthemfromthelanguagetypesofthesourcelanguage.ThetypesareorganizedintoahierarchywithsourcecodeconstructsorganizedundertheConstructbase.Everytypeinheritsthepropertiesofeachofitsancestors.

Eachpropertyhasafixedresolutiontype.Asaresult,thestructuraltypeofeverysubexpressionintheruleslanguageisknownduringrulesspecification.Statictype‐checkingisperformedwhenaruleisloaded.

Forafullreferenceforthestructuraltypehierarchy,seetheStructuralTypeandPropertiesReference.

Thestructurallanguagealsosupportslistsofobjects.Theseobjectsdonothaveofficialtypenames.Thismeansthattheycannotappearasthesubjectofarule.However,propertiescanstillresolvetolists.Theanalyzercanaccesslistsusingthecontainsandinrelations,justlikeconstructs.Forexample,theFunctionconstructhasapropertyparamaterTypesthatreturnsalistofTypeobjects.

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> '"

Page 79: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 7: Structural Rules Language Reference   79

Listing73showsarulethatmatchesfunctionsthathaveanyparameteroftypeint.

Thisruleisinterpretedasthefollowingquery:Selectanyfunctionffromthestructureoftheprogram,inwhichtheparametersoftypef containanytypeof“int”.

Youcanalsoreferencewithzero‐basedindexnotation,usingstandard,bracketedaccessors.

Listing74showsarulethatmatchesfunctionsinwhichthefirstparameterhastype “int.”

T"…"denotesaspecialtypeofconstantinthestructurallanguage.Itprovidesaconvenientwaytoinspectlanguagetypes.WhenthestructuralevaluatorencounterssuchaconstantitconvertsthestringbetweenthequotesintoastructuralTypeSignatureobject(whichiscomparablewithType)usingtherulesofthesourcecodelanguagebeingexamined(Java,C,andsoon).

Properties

TheStructuralTypeandPropertiesReferenceprovidesalistofallpropertiesrecognizedbythestructuralanalyzer.Allstructuraltypes,includinglistsandprimitivestructuraltypes,haveassociatedproperties.Everytypeinheritsthepropertiesofeachofitsancestors.Listtypeshaveonlyoneproperty,length,whichrepresentsthenumberofitemsinthelist.

Propertiesoftenresolvetosubtypesoftheirdeclaredtypes.

Listing75showsanexample.

ThistranslatestoanAssignmentStatementinthestructuraltree.

Inthestructuralruleslanguage,youcanexamineanassignment'sright‐handsideusingthepropertyAssignmentStatement.rhs,whichnominallyresolvestoanExpression.InthiscaseitresolvestoanIntegerLiteral,asubtypeofLiteralwhichisitselfasubtypeofExpression.

Listing76showsarulethatmatcheseveryassignmenttherighthandsideofwhichhasthelanguagetypeint.

YoucanusethisrulebecausetypeisapropertyofallExpressionobjects.Butifyouwanttomatcheveryassignment,theright‐handsideofwhichistheintegerliteral30,youmustcastAssignmentStatement.rhsusingasubrule.

Listing 73: Int Type Matching Rule

Function f: f.parameterTypes contains [Type t: t.name = "int"]

Listing 74: Zero‐Based Index Notation

Function: parameterTypes[0] == T"int"

Listing 75: Java Code 

x = 30;

Listing 76: Matching Rule

AssignmentStatement a: a.rhs.type == T"int"

Page 80: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 7: Structural Rules Language Reference   80

Listing77showsasubrulethatcastsanAssignmentStatement.rhs.

ThisisbecausevalueisnotapropertyofExpression.Tomaintaintype‐safety,youmustassertthatrhsactuallyisanIntegerLiteralbeforeyoucanaccessthepropertyvalue.

Reference ResolutionAReference(seeSyntaxandGrammar)isanIdentifierorchainofidentifiersconnectedbydotswhichresolvestoalabeledobjectorapropertyofanobject.Resolutionofthefirstidentifierfollowstherulesdescribedhere.Subsequentidentifiersinthereferencearealwayspropertiesoftheinnerobject.

Toresolvethefirstidentifieridentinareference,thestructuralevaluatorfirstcheckstoseeifidentappearsinaLabelintheenclosingSubRule,inaparentSubRule,orintheinitialLabelwhichstartstheRule.

Listing78showsaruleinwhichfandvareresolvedbyexaminingthelabelsfortheenclosingcontexts.

Inthecasethatidentdoesnotresolvetoalabeledobject,identisresolvedasapropertyoftheobjectselectedbytheimmediatelyenclosingsubrule(ortheruleitselfifidentdoesnotappearinasubrule).

Listing79showsandexampleinwhich,nameresolvesinbothcasestothenameofthefunction.

Listing 77: Matching Rule

AssignmentStatement a: a.rhs is [IntegerLiteral n: n.value == 30]

Listing 78: f and v Resolution Rule

Function f: f contains [Variable v: v.name == f.name]

Listing 79: Name Resolution

Example1:Function: name == "func"Example 2: Variable v: v in [Function: name == "func"]

Page 81: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 7: Structural Rules Language Reference   81

Null Resolutions

Somepropertiesarevalidonlyforcertaininstancesofastructuraltype.Forexample,TryBlockhasaproperty,finallyBlock,whichresolvestotheassociatedfinallyblockofatryblock.However,notalltryblockshaveassociatedfinallyblocks.

Inthesecases,propertiesresolvetonull.Thereisnoneedforrulestocheckforthis,becausetheStructuralAnalyzerhandlesoperationsonnullinawell‐definedmanner:

• Everypropertyofnullresolvestonull

• Everysubrulerelationonanullobjectresolvestofalse

Listing80showshowBooleanconnectivesresolve.

IftheBooleanvalueisdeterminate,itisresolved;otherwiseitisnull.

RelationsYoucanusetheequalityandinequalityrelations,==and!=,tocompareanytwoobjectsrecognizedbytheStructuralAnalyzer.Forequalitytohold,thestructuraltypesoftheobjectsmustagree.Equalityhastheobviousmeaningforprimitivestructuraltypes;forconstructs,theconditionisthatthetwoobjectsmustbestructurallyidentical.

TheStructuralAnalyzerconfirmsthestructuralidentityinoneoftwoways:

• TheStructuralAnalyzerconfirmsdeclarationsbycomparingthecanonicalnamesofthesymbols.

• TheStructuralAnalyzerconfirmsotherconstructsbycomparingtheunderlyingnodesintheprogramrepresentation.Listsareequaliftheyenumerateequalelementsinthesameorder.

Thestrictequalityrelation,===,holdstrueonlyiftheobjectsbeingcomparedarethesameobject.

Theorderrelations,<,>,<=,and>=,havetheirusualmeaningsforstrings,numbers,andBooleans.Types,lists,andconstructscannotbecomparedwithorderrelations.

Thereareseveralspecialrelations:

• ismeansthesamethingas ==,exceptitcanbeusedtoprefaceasubrule.

• inandcontainscanbeusedwithstringsandlists,withobviousmeanings.Forotherconstructstheyexamineparentandchildrelationships.inwillsearchtheparentandgrandparentsofthenodetothetopofthetree.containswillsearchthechildrenand‐normally‐thegrandchildrenofthenodetothebottomofthetree.TheexceptiontothisbehaviorisfortheClassandCompilationUnitstructuraltypes,forwhichcontainswillonlyexaminethefirstgenerationofchildren(thispreventswritingquerieswhichareunreasonablyexpensivetoexecute).

• startsWith,endsWith,andmatchescanonlybeusedtorelatetwostrings.matchesinterpretstheright‐handsideoftherelationasaJavaregularexpression,anditistrueonlyiftheleft‐handsideismatchedbythatregularexpression.

• reachesandreachedBycanonlybeusedtorelatetwoFunctionsortwoClasses.TheyarediscussedintheCallGraphReachabilitysection.

Listing 80: Boolean Connectives Resolution

null and null -> nullnull or null -> nullnull and true -> nullnull or true -> truenull and false -> falsenull or false -> null

Page 82: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 7: Structural Rules Language Reference   82

Youcanomittheleft‐handsideofanyoftheserelations.Ifyouomitthem,theleft‐handsidedefaultstotheconstructthattheruleiscurrentlymatching.

Listing81showsarulethatmatchesanyclassthathasapropersuperclass.

BecausesupersresolvestoaClass[],youcanabbreviatetheruleinListing81totheruleprovidedinListing82.

Listing82showsanabbreviatedclassmatchingsuperclassrule.

AlthoughtheversionprovidedinListing81ismorecompact,theversioninListing80greaterclarityandismorereadabletohumans.

Results ReportingRecalltheexampleinListing83,whichmatchesreturnstatementsthatappearinsideafinallyblock.

TheruleinListing84issimilar.

However,therearetwosignificantdifferences.First,ifasinglefinallyblockcontainsmultiplereturnstatements,theruleinListing84willgeneratemultiplevulnerabilitieswhiletheruleinListing84willproducejustone.

Theseconddifferenceisthewayinwhichtherulesreportvulnerabilities.Theprimarysourcelocation,asreportedintheanalysisoutput,alwayspointstotherule'soutermostconstruct.TheruleinListing83highlightsthereturnstatement.TheruleinListing84highlightstheblock.

Bydefault,theStructuralAnalyzerreportsnoinformationotherthanthesourcelocationoftheoutermostconstructthatitmatchesForsomerules,thisissufficient.Otherrulesrequiremoreinformationinordertocreateacompletereport.

Youcanenablereportingforasubrulebyappendinganasterisktothesubrule.Listing85showsthis.

Thisruleislogicallyequivalenttotheun‐asteriskedonebecauseitmatchesexactlythesamecodeconstructs.However,whenanalyzermatchesit,boththereturnstatementanditsenclosingfinallyblockarereported.Thereturnstatementisstilltheprimaryreportinglocation.

Listing 81: Class Matching Super Class Rule

Class c: c.supers contains [Class c2: c2 != c]

Listing 82: Abbreviated Class Matching Super Class Rule

Class c: supers contains [!= c]

Listing 83: Return Statement Example 1

ReturnStatement r: r in [FinallyBlock:]

Listing 84: Return Statement Example 2

FinallyBlock f: f contains [ReturnStatement:]

Listing 85: Subrule Marked with a Asterisk 1

ReturnStatement: in [FinallyBlock:]*

Page 83: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 7: Structural Rules Language Reference   83

Asteriskedsubrulematchesarereportedonlyforsubrulesthatactuallycontributetoamatch.ThesubruleprovidedinListing86showsthis.

Thisrulematchesanypublicmethodcontaininganassignmentstatement,oranyprivatemethodcontainingareturnstatement.TheStructuralAnalyzeralwaysreportsthematchingstatement,becausebothsubrulesareasterisked.However,ifamethodcontainsbothanassignmentstatementandareturnstatement,theanalyzerreportsasfollows:

• Assignmentstatement—ifthemethodispublic

• Returnstatement—ifthereturnstatementofthemethodisprivate

Call‐Graph ReachabilityManystructuralrulesapplyonlyincertaincontexts.Forexample,EnterpriseJavaBeans(EJBs)areadvisednevertocallthejava.iolibrariesdirectly.Youcanimplementarulethatmatcheseverycalltojava.io.

Listing87showsarulethatmatcheseverycalltojavatuilrl:

TheissuewiththeruleinListing87isthatitgeneratesalargenumberoffalsepositives.ThisisbecausethemostcallstoJava.iodonotinvolveEJBs.AbetterapproximationistorestricttofunctioncallsthatappearwithinanEnterpriseBean.Theenclosingclassofthefunctioncalldiffersfromtheenclosingclassofthefunction.

Listing88showsarulewithanEnterpriseBeanrestriction.

Listing89showsmorecontentonanEnterpriseBeanrestriction.

TheruleprovidedbyListing89missesmanycasesinwhichanEnterpriseJavaBeanindirectlycallsjava.io.Forexample,thisrulewillmisswhenaEnterpriseJavaBeancallsautilitymethodinadifferentclass,andtheutilitymethodopensafile.Thisshouldbeaviolation.

TheStructuralAnalyzerprovidestworelationsreachesandreached by,thattraversethecallgraphofaprogram.Youcanusetheserelationstohandlethetypeofsituationdescribedabove.

Listing 86: Subrule Marked with a Asterisk 2

Function: contains [AssignmentStatement:]* and public or contains [ReturnStatement:]* and private

Listing 87: Matches Every Call to Java tuirl

FunctionCall call: call.function.enclosingClass.name startsWith "java.io."

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."

Listing 89: EnterpriseBean Restriction 2

// The enclosing class of the function itself call.function.enclosingClass.name startsWith "java.io."

Page 84: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 7: Structural Rules Language Reference   84

Listing90showsanexampleofareachesrelation.

Thisistruejustifthereissomepaththroughthecallgraphoriginatingwithfandterminatingatafunctionthatmatchesthesubrule.reachedByissimilar,withthepathproceedingintheoppositedirection.

Listing91showsaFunctionCallthatisthebestwaytoencodetheaboveEJBrule:

YoucanalsousethereachesandreachedByrelationsonclasses.ClassAreachesclassBifsomefunctionofAreachessomefunctionofB.Forexample,theruleprovidedbyfollowingrulematchespublicfieldsinclassesthatanAppletcanreach.

ThefieldcannotappearaspartofareachedByrelation‐onlyfunctionsandclassescansatisfy reachesorreachedBy.

Forperformancereasons,variablescopesdonotextendacrossreaches orreachedBypredicates.

Listing93showsanillegalrule.

Thevariablefcannotappearinthesubruleofareachesrelation.

Listing 90: Relation that traverses a Call Graph

f reaches [subrule]

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."]*

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"]]

Listing 93: Illegal reaches Rule

Function f: reaches [Function g: g != f]

Page 85: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 8: Control Flow Rule Reference   85

Chapter 8: Control Flow Rule ReferenceThischapterprovidesthefollowingtopics:

• ControlFlowSyntaxandGrammar—usethissectionasareferenceforcontrolflowrulesyntaxandgrammar.

• UnderstandingControlFlowRules—usethissectiontolearnaboutcontrolflowrules.

Control Flow Syntax and GrammarThefollowingisasimplifiedBNF‐stylegrammarfortheStructuralPredicateLanguage.Forreadabilitypurposes,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>

Page 86: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 8: Control Flow Rule Reference   86

Understanding Control Flow RulesControlflowrulesprovidedefinitionsofstatemachinesthatcharacterizeunsafebehaviorsuchaspotentiallydangeroussequencesofoperations.

Control Flow Rule IdentifiersControlflowrulescanhavemultiplefunctionidentifiers.Thefunctionidentifiersareusedinthecontrolflowdefinition.ThedefinitionusesthevalueofthereferenceIdentifierasavariabletoaccessthefunctionalidentifiers.Mostofthecontrolflowfunctionidentifiersaredescribedin“FunctionIdentifiers”onpage16.Thefunctionidentifierpanelforcontrolflowrulesalsocontainsadditionalfieldsandfunctionality,describedinthissection.

Control Flow Rule FormatUnlikedataflowrules,acontrolflowruledoesnotspecifyasinglefunction;instead,itspecifiesasequenceofprogramelements(whichcouldbefunctioncallsorotherentitiesinaprogram).Thisdefinition,whichgoesintheDefinitionfieldoftherule,resemblesasimpleprogramminglanguage.

ControlflowrulessupportC++andJava‐stylecommentsasfollows://createsacommenttotheendoftheline/*createsacommentuntilamatching*/Eachruledefinitiondefinesastatemachine.Eachstatemachinehasexactlyonestartstate,oneormoreerrorstates,andanynumberofintermediatestates.Themachinealwayshasacurrentstate.

Whenthecurrentstateisanerrorstate,thecontrolflowanalyzerreportsavulnerability.

Statesareconnectedbytransitions.Eachtransitionhasasourcestate,adestinationstate,andsomenumberofpatterns.Ifatransition'ssourcestateisthecurrentstateandoneofthattransition'spatternsmatchesafragmentoftheprogram,thenthetransition'sdestinationstatebecomesthenewcurrentstate.Inthiscase,themachineissaidtohavetransitionedfromthesourcestatetothedestinationstate.Theprogramfragmentisreferredtoasthe"input"tothepattern.Thedefinitionofamachineconsistsoftwomajorparts:declarationsandtransitions.

Thissectionprovidesthefollowingtopics:

•Declarations

•Transitions

•Functioncalls

DeclarationsMachinedefinitionsbeginwithdeclarationsofthestatesofthemachine.Statesaredefinedwiththestatekeyword,optionallyfollowedbystartorerrortodesignatethestartanderrorstates,respectively,followedbythestatename.Asimplemachinecanhavethefollowingstatedefinitions.

Listing95showsstatemachinestatedefinitions.

Machinescanalsoincludevariables,whicharedeclaredwiththevarkeyword.Avariablecanmatchanyexpressionintheprogram.Thefirsttimeavariableisused,itisboundtotheexpressionitmatches.Forsubsequentusesofthesamevariable,thevariableonlymatchesiftheinputisthesameastheexpressiontowhichthevariableisbound.

Listing 95: State Machine State Definitions

state state1 start;state state;state state3 error;

Page 87: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 8: Control Flow Rule Reference   87

Listing96showsasampledeclaration.

Finally,patternscanbegivennamestoavoidtheneedtoenterthesamepatternmanytimes.Patternsarenamedwiththepatternkeyword,followedbythepatternenclosedincurlybraces.

Forexample,thefollowinglinedeclaresapatternnamedalloc,whichmatchesthemallocandcallocfunctions:

pattern alloc { malloc(...) | calloc(...) }Formoreonpatterns,see“Transitions”onpage87.

Ifacontrolflowrulecontainsalineoftheformlimit <refid>;,thenthatcontrolflowruleonlyappliesinthebodyoffunctionsthatmatchthefunctionidentifierwithreferenceIDrefid.

TransitionsTransitionsdefinehowthecurrentstateofthemachinemaychange.Asdescribedabove,eachtransitionhasasourcestate,adestinationstate,andapattern.Theremaybemultipletransitionswiththesamesourcestate;inthiscase,thenewcurrentstatewillbethedestinationstateofthefirsttransitionwithapatternthatmatchestheinput.

Transitionsaredefinedbythenameofthesourcestate,thesymbol->,thenameofthedestinationstate,andoneormorepatternssurroundedbycurlybraces.Multiplepatternsinthesametransitionshouldbeseparatedwith|characters.

Listing97showsanexampleofatransitionwithmultiplepatternsseparatedwith|characters.

Apatternconsistsofoneofthefollowingelements:

• Usesofanamedpattern

Patternsdeclaredwiththepatternkeywordinthedeclarationsectionmaybeusedintransitionsbyspecifyingthepatternkeywordfollowedbythepatternname,suchas:state1 -> state2 { pattern alloc }

• Assignmentstatements

Controlflowrulesoftenrefertothereturnvaluesoffunctioncalls,particularlyobjectconstructorsandotherfunctionsthatreturnhandlestoresources.Thereturnvalueofafunction,oranyassignmentstatement,canbematchedwiththenameofarulevariablefollowedbyanequal(=)symbolandanexpression.(Seebelowforexpressions.)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>

Listing 96: Sample Variable Definition

var f;

Listing 97: Transition with Multiple Patterns

source -> destination { pattern1 | pattern2 }

Page 88: HP Fortify Static Code Analyzer - Micro Focus Community€¦ · HP Fortify Static Code Analyzer Software Version 4.21 HP Fortify Static Code Analyzer Custom Rules Guide Document Release

Chapter 8: Control Flow Rule Reference   88

• &<Expression>:Areferenceto<Expression>(C‐style)

• Afunctioncall:SeeFunctionCallsbelow

• A?character:Matchesanyexpressionintheinput

• Thenameofarulevariable:Iftherulevariableisunbound,matchesanyexpressionandbindstherulevariabletothatexpression.Iftherulevariableisbound,matchestheexpressiontowhichthevariablewasfirstbound.

• Languagefeaturestatements

Someaspectsofprogramscannotberepresentedusingtheexpressionsabove.Fortheseaspects,therearespecialtypesofpatterns.ThesepatternsresemblefunctioncallsinCorJava,butallofthefunctionnamesbeginwitha#character.

Thevalidlanguagefeaturestatementsare:

• #end_scope(var):Matchestheendoftheenclosingscopefortheexpressionboundtotherulevariablevar

• #return(expr):Matchesareturnstatementwithareturnexpressionmatchingexpr

• #return():Matchesanyreturnstatement

• #compare(var, const):Matchesacomparison(==, !=, <, >, <=, >=)betweenvar(arulevariable)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)inCorC++.Pointerstostructs,pointersandreferencestoC++objects,andreferencestoJavaobjectsarenotmatched;usethe#simple_declarationpatternforthesedatatypes.

• #buffer_declaration(var):MatchesthedeclarationofastackbufferinCorC++

• #any_declaration(var):Matchesanyoftheabove

• #ifblock (var, const, which):Matchesacomparisonbetweenvarandconstasdefinedfor#compare,withtheadditionalrestrictionsthatthecomparisonoperatormustbeanequalitytest(==,!=,orasimilaroperator),andthatthecomparisonmustoccurwithinthepredicateofabranchingorloopingconstruct(suchasifstatements,forloops,andwhileloops).Thespecifiedstatetransitiononlyoccursonthebranchwherevar ==constevaluatestowhich.

Function CallsMostinterestingsecuritypropertiesinvolvetheuseoffunctionmatchingsyntaxbasedonfunctionidentifiers.ControlflowrulesusethereferenceIDfieldfromfunctionidentifierstospecifyfunctionsfortransitions.Forexample,ifthereisafunctionidentifierwithareferenceIDofallocator,thenthecontrolflowpatternv = $allocator(?)wouldassigntherulevariablevtothereturnvalueofanyfunctionthatmatchedthe$allocatorfunctionidentifierandtookexactlyoneargument.

Ingeneral,theargumentstotherulefunctionshouldexactlymatchtheexpectedargumentstotheinputfunction.Therefore,towritearulethatbindsthesecondargumenttothelinksystemcalltotherulevariablevar,therulewouldread$link(?, var),assumingafunctionidentifiermatchingthelinksystemcallhadalreadybeendefinedwithareferenceIDoflink.Thereisoneexceptiontothe"oneexpressionperargument"rule:anellipsis(...)intheargumentstoafunctionmatches0ormoreexpressions.Itisthereforepossibletomatchthelastargumentofafunctionbyspecifyingfunction(..., var),andfunction(...)willmatchanyinvocationofthespecifiedfunction,withoutpayingattentiontotheargumentstothatfunction.