Post on 23-Mar-2020
transcript
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved i
ISO/IECJTC1/SC22/WG23N0751Posted
Date:17October2017
ISO/IECTR24772-1
Edition3
ISO/IECJTC1/SC22/WG23
Secretariat:ANSI
InformationTechnology—Programminglanguages—Guidancetoavoidingvulnerabilitiesinprogramminglanguages
Élémentintroductif—Élémentprincipal—Partien:Titredelapartie
Warning
ThisdocumentisnotanISOInternationalStandard.Itisdistributedforreviewandcomment.ItissubjecttochangewithoutnoticeandmaynotbereferredtoasanInternationalStandard.
Recipientsofthisdraftareinvitedtosubmit,withtheircomments,notificationofanyrelevantpatentrightsofwhichtheyareawareandtoprovidesupportingdocumentation.
Documenttype:InternationalstandardDocumentsubtype:ifapplicableDocumentstage:(10)developmentstageDocumentlanguage:E
Deleted: 42
Deleted: 0280Deleted: 684Formatted: Font:12 ptDeleted: 6Deleted: August7June10January
WG23/N0720
ii ©ISO/IEC2013–Allrightsreserved
Deleted: 664
Copyrightnotice
ThisISOdocumentisaworkingdraftorcommitteedraftandiscopyright-protectedbyISO.WhilethereproductionofworkingdraftsorcommitteedraftsinanyformforusebyparticipantsintheISOstandardsdevelopmentprocessispermittedwithoutpriorpermissionfromISO,neitherthisdocumentnoranyextractfromitmaybereproduced,storedortransmittedinanyformforanyotherpurposewithoutpriorwrittenpermissionfromISO.
RequestsforpermissiontoreproducethisdocumentforthepurposeofsellingitshouldbeaddressedasshownbelowortoISO’smemberbodyinthecountryoftherequester:
ISOcopyrightoffice
Casepostale56,CH-1211Geneva20
Tel.+41227490111
Fax+41227490947
E-mailcopyright@iso.org
Webwww.iso.org
Reproductionforsalespurposesmaybesubjecttoroyaltypaymentsoralicensingagreement.
Violatorsmaybeprosecuted.
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved iii
Contents Page
FOREWORD..................................................................................................................................................VII
INTRODUCTION...........................................................................................................................................VIII
1.SCOPE.........................................................................................................................................................9
2.NORMATIVEREFERENCES...........................................................................................................................9
3.TERMSANDDEFINITIONS,SYMBOLSANDCONVENTIONS..........................................................................93.1TERMSANDDEFINITIONS.....................................................................................................................................93.2SYMBOLSANDCONVENTIONS.............................................................................................................................13
4.BASICCONCEPTS......................................................................................................................................144.1PURPOSEOFTHISTECHNICALREPORT..................................................................................................................144.2INTENDEDAUDIENCE........................................................................................................................................144.3HOWTOUSETHISDOCUMENT............................................................................................................................15
5VULNERABILITYISSUESANDGENERALAVOIDANCEMECHANISMS............................................................165.1PREDICTABLEEXECUTION...................................................................................................................................165.2SOURCESOFUNPREDICTABILITYINLANGUAGESPECIFICATION..................................................................................175.2.1INCOMPLETEOREVOLVINGSPECIFICATION.........................................................................................................175.2.2UNDEFINEDBEHAVIOUR.................................................................................................................................185.2.3UNSPECIFIEDBEHAVIOUR...............................................................................................................................185.2.4IMPLEMENTATION-DEFINEDBEHAVIOUR...........................................................................................................185.2.5DIFFICULTFEATURES......................................................................................................................................185.2.6INADEQUATELANGUAGESUPPORT...................................................................................................................185.3SOURCESOFUNPREDICTABILITYINLANGUAGEUSAGE.............................................................................................185.3.1PORTINGANDINTEROPERATION......................................................................................................................185.3.2COMPILERSELECTIONANDUSAGE....................................................................................................................195.4TOPAVOIDANCEMECHANISMS...........................................................................................................................19
6.PROGRAMMINGLANGUAGEVULNERABILITIES.........................................................................................216.1GENERAL........................................................................................................................................................216.2TYPESYSTEM[IHN].........................................................................................................................................226.3BITREPRESENTATIONS[STR].............................................................................................................................246.4FLOATING-POINTARITHMETIC[PLF]....................................................................................................................266.5ENUMERATORISSUES[CCB].............................................................................................................................296.6CONVERSIONERRORS[FLC]...............................................................................................................................316.7STRINGTERMINATION[CJM]............................................................................................................................336.8BUFFERBOUNDARYVIOLATION(BUFFEROVERFLOW)[HCB]...................................................................................346.9UNCHECKEDARRAYINDEXING[XYZ]...................................................................................................................366.10UNCHECKEDARRAYCOPYING[XYW]................................................................................................................386.11POINTERTYPECONVERSIONS[HFC].................................................................................................................396.12POINTERARITHMETIC[RVG]...........................................................................................................................40
WG23/N0720
iv ©ISO/IEC2013–Allrightsreserved
Deleted: 664
6.13NULLPOINTERDEREFERENCE[XYH].................................................................................................................416.14DANGLINGREFERENCETOHEAP[XYK]..............................................................................................................426.15ARITHMETICWRAP-AROUNDERROR[FIF].........................................................................................................446.16USINGSHIFTOPERATIONSFORMULTIPLICATIONANDDIVISION[PIK]......................................................................466.17CHOICEOFCLEARNAMES[NAI].......................................................................................................................476.18DEADSTORE[WXQ].....................................................................................................................................496.19UNUSEDVARIABLE[YZS]................................................................................................................................506.20IDENTIFIERNAMEREUSE[YOW]......................................................................................................................516.21NAMESPACEISSUES[BJL]...............................................................................................................................536.22INITIALIZATIONOFVARIABLES[LAV].................................................................................................................556.23OPERATORPRECEDENCEANDASSOCIATIVITY[JCW]............................................................................................576.24SIDE-EFFECTSANDORDEROFEVALUATIONOFOPERANDS[SAM]..........................................................................586.25LIKELYINCORRECTEXPRESSION[KOA]..............................................................................................................606.26DEADANDDEACTIVATEDCODE[XYQ]..............................................................................................................626.27SWITCHSTATEMENTSANDSTATICANALYSIS[CLL]..............................................................................................646.28DEMARCATIONOFCONTROLFLOW[EOJ]..........................................................................................................666.29LOOPCONTROLVARIABLES[TEX].....................................................................................................................676.30OFF-BY-ONEERROR[XZH]..............................................................................................................................686.31STRUCTUREDPROGRAMMING[EWD]...............................................................................................................706.32PASSINGPARAMETERSANDRETURNVALUES[CSJ]..............................................................................................716.33DANGLINGREFERENCESTOSTACKFRAMES[DCM]..............................................................................................736.34SUBPROGRAMSIGNATUREMISMATCH[OTR].....................................................................................................756.35RECURSION[GDL]........................................................................................................................................776.36IGNOREDERRORSTATUSANDUNHANDLEDEXCEPTIONS[OYB].............................................................................786.37TYPE-BREAKINGREINTERPRETATIONOFDATA[AMV]..........................................................................................816.38DEEPVS.SHALLOWCOPYING[YAN].................................................................................................................836.39MEMORYLEAKSANDHEAPFRAGMENTATION[XYL]............................................................................................846.40TEMPLATESANDGENERICS[SYM]...................................................................................................................866.41INHERITANCE[RIP]........................................................................................................................................886.42VIOLATIONSOFTHELISKOVSUBSTITUTIONPRINCIPLEORTHECONTRACTMODEL[BLP].............................................906.43REDISPATCHING[PPH]..................................................................................................................................916.44POLYMORPHICVARIABLES[BKK].....................................................................................................................936.45EXTRAINTRINSICS[LRM]...............................................................................................................................956.46ARGUMENTPASSINGTOLIBRARYFUNCTIONS[TRJ].............................................................................................966.47INTER-LANGUAGECALLING[DJS].....................................................................................................................976.48DYNAMICALLY-LINKEDCODEANDSELF-MODIFYINGCODE[NYY]............................................................................996.49LIBRARYSIGNATURE[NSQ]...........................................................................................................................1006.50UNANTICIPATEDEXCEPTIONSFROMLIBRARYROUTINES[HJW]...........................................................................1016.51PRE-PROCESSORDIRECTIVES[NMP]...............................................................................................................1036.52SUPPRESSIONOFLANGUAGE-DEFINEDRUN-TIMECHECKING[MXB]...................................................................1046.53PROVISIONOFINHERENTLYUNSAFEOPERATIONS[SKL].....................................................................................1056.54OBSCURELANGUAGEFEATURES[BRS]............................................................................................................1066.55UNSPECIFIEDBEHAVIOUR[BQF]....................................................................................................................1086.56UNDEFINEDBEHAVIOUR[EWF].....................................................................................................................109
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved v
6.57IMPLEMENTATION-DEFINEDBEHAVIOUR[FAB]................................................................................................1116.58DEPRECATEDLANGUAGEFEATURES[MEM].....................................................................................................1136.59CONCURRENCY–ACTIVATION[CGA]............................................................................................................1146.60CONCURRENCY–DIRECTEDTERMINATION[CGT].............................................................................................1166.61CONCURRENTDATAACCESS[CGX]................................................................................................................1176.62CONCURRENCY–PREMATURETERMINATION[CGS].........................................................................................1196.63LOCKPROTOCOLERRORS[CGM]..................................................................................................................1216.64UNCONTROLLEDFORMATSTRING[SHL].........................................................................................................123
7.APPLICATIONVULNERABILITIES...............................................................................................................1267.1GENERAL......................................................................................................................................................1267.2UNRESTRICTEDFILEUPLOAD[CBF]..................................................................................................................1267.3DOWNLOADOFCODEWITHOUTINTEGRITYCHECK[DLB].....................................................................................1277.4EXECUTINGORLOADINGUNTRUSTEDCODE[XYS]...............................................................................................1287.5INCLUSIONOFFUNCTIONALITYFROMUNTRUSTEDCONTROLSPHERE[DHU]...........................................................1297.6USEOFUNCHECKEDDATAFROMANUNCONTROLLEDORTAINTEDSOURCE[EFS].....................................................1307.7CROSS-SITESCRIPTING[XYT]...........................................................................................................................1317.8URLREDIRECTIONTOUNTRUSTEDSITE('OPENREDIRECT')[PYQ].........................................................................1337.9INJECTION[RST]...........................................................................................................................................1347.10UNQUOTEDSEARCHPATHORELEMENT[XZQ].................................................................................................1377.11PATHTRAVERSAL[EWR]..............................................................................................................................1387.12RESOURCENAMES[HTS]..............................................................................................................................1407.13RESOURCEEXHAUSTION[XZP]......................................................................................................................1417.14AUTHENTICATIONLOGICERROR[XZO]............................................................................................................1437.15IMPROPERRESTRICTIONOFEXCESSIVEAUTHENTICATIONATTEMPTS[WPL]...........................................................1457.16HARD-CODEDPASSWORD[XYP]....................................................................................................................1457.17INSUFFICIENTLYPROTECTEDCREDENTIALS[XYM].............................................................................................1467.18MISSINGORINCONSISTENTACCESSCONTROL[XZN].........................................................................................1477.19INCORRECTAUTHORIZATION[BJE]................................................................................................................1487.20ADHERENCETOLEASTPRIVILEGE[XYN]..........................................................................................................1497.21PRIVILEGESANDBOXISSUES[XYO].................................................................................................................1497.22MISSINGREQUIREDCRYPTOGRAPHICSTEP[XZS]..............................................................................................1517.23IMPROPERLYVERIFIEDSIGNATURE[XZR].........................................................................................................1517.24USEOFAONE-WAYHASHWITHOUTASALT[MVX]...........................................................................................1527.25INADEQUATELYSECURECOMMUNICATIONOFSHAREDRESOURCES[CGY..............................................................1537.26MEMORYLOCKING[XZX].............................................................................................................................1547.27SENSITIVEINFORMATIONUNCLEAREDBEFOREUSE[XZK]...................................................................................1557.28TIMECONSUMPTIONMEASUREMENT[CCM]...................................................................................................1567.29DISCREPANCYINFORMATIONLEAK[XZL].........................................................................................................1577.30UNSPECIFIEDFUNCTIONALITY[BVQ]..............................................................................................................1587.31FAULTTOLERANCEANDFAILURESTRATEGIES[REU].........................................................................................1597.32DISTINGUISHEDVALUESINDATATYPES[KLK]...................................................................................................1627.33CLOCKISSUES[CCI].....................................................................................................................................1637.34TIMEDRIFTANDJITTER[CDJ].......................................................................................................................165
Deleted: 125
Deleted: 125
Deleted: 125
Deleted: 126
Deleted: 127
Deleted: 128
Deleted: 129
Deleted: 130
Deleted: 132
Deleted: 133
Deleted: 136
Deleted: 137
Deleted: 139
Deleted: 140
Deleted: 142
Deleted: 144
Deleted: 144
Deleted: 145
Deleted: 146
Deleted: 147
Deleted: 148
Deleted: 148
Deleted: 150
Deleted: 150
Deleted: 151
Deleted: 152
Deleted: 153
Deleted: 154
Deleted: 155
Deleted: 156
Deleted: 157
Deleted: 158
Deleted: 161
Deleted: 162
Deleted: 164
WG23/N0720
vi ©ISO/IEC2013–Allrightsreserved
Deleted: 664
8.1GENERAL......................................................................................................................................................1678.2MODIFYINGCONSTANTS[UJO].......................................................................................................................167
ANNEXA(INFORMATIVE)VULNERABILITYTAXONOMYANDLIST.................................................................169A.1GENERAL......................................................................................................................................................169A.2OUTLINEOFPROGRAMMINGLANGUAGEVULNERABILITIES...................................................................................169A.3OUTLINEOFAPPLICATIONVULNERABILITIES.......................................................................................................171A.4VULNERABILITYLIST.......................................................................................................................................172
ANNEXB.....................................................................................................................................................175
THESEARERECOMMENDATIONSFORTHELANGUAGEDEVELOPERS’COMMUNITY,STANDARDSTHATIFDEVELOPEDCOULDBEOFUSETOALLLANGUAGESSUCHASTHESTANDARDSISO/IEC/IEC60559FLOATING-POINTARITHMETIC,ISO/IEC10967-1:2012,PART1:INTEGERANDFLOATINGPOINTARITHMETIC,ANDISO/IEC10967-2:2001,PART2:ELEMENTARYNUMERICALFUNCTIONS:....................................................................175
SELECTLISTOFWHATALANGUAGESHOULDHAVEORDO.THESEWEREEXTRACTEDFROMGUIDANCETOLANGUAGEDESIGNERSFROMCLAUSE6.X.6INTR24772-1.WORDINGHASBEENADJUSTEDTOPROVIDEAMOREGENERALCONTEXT,WHEREAPPLICABLE............................................................................................175
ANNEXC(INFORMATIVE)LANGUAGESPECIFICVULNERABILITYTEMPLATE..................................................177BIBLIOGRAPHY.....................................................................................................................................................180
INDEX..........................................................................................................................................................183
Deleted: 165
Deleted: 166
Deleted: 168
Deleted: 168
Deleted: 168
Deleted: 170
Deleted: 171
Deleted: 174
Deleted: 174
Deleted: 174
Deleted: 176
Deleted: 179
Deleted: 182
Deleted: FOREWORD VII ... [1]
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved vii
Foreword
ISO(theInternationalOrganizationforStandardization)andIEC(theInternationalElectrotechnicalCommission)formthespecializedsystemforworldwidestandardization.NationalbodiesthataremembersofISOorIECparticipateinthedevelopmentofInternationalStandardsthroughtechnicalcommitteesestablishedbytherespectiveorganizationtodealwithparticularfieldsoftechnicalactivity.ISOandIECtechnicalcommitteescollaborateinfieldsofmutualinterest.Otherinternationalorganizations,governmentalandnon-governmental,inliaisonwithISOandIEC,alsotakepartinthework.Inthefieldofinformationtechnology,ISOandIEChaveestablishedajointtechnicalcommittee,ISO/IECJTC1.
InternationalStandardsaredraftedinaccordancewiththerulesgivenintheISO/IECDirectives,Part2.
ThemaintaskofthejointtechnicalcommitteeistoprepareInternationalStandards.DraftInternationalStandardsadoptedbythejointtechnicalcommitteearecirculatedtonationalbodiesforvoting.PublicationasanInternationalStandardrequiresapprovalbyatleast75%ofthenationalbodiescastingavote.
Inexceptionalcircumstances,whenthejointtechnicalcommitteehascollecteddataofadifferentkindfromthatwhichisnormallypublishedasanInternationalStandard(“stateoftheart”,forexample),itmaydecidetopublishaTechnicalReport.ATechnicalReportisentirelyinformativeinnatureandshallbesubjecttorevieweveryfiveyearsinthesamemannerasanInternationalStandard.
Attentionisdrawntothepossibilitythatsomeoftheelementsofthisdocumentmaybethesubjectofpatentrights.ISOandIECshallnotbeheldresponsibleforidentifyinganyorallsuchpatentrights.
ThecommitteeresponsibleforthisdocumentisJointTechnicalCommitteeISO/IECJTC1,Information
technology,SubcommitteeSC22,Programminglanguages,theirenvironmentsandsystemsoftwareinterfaces.
ThiseditioncancelsandreplacesISOIECTR24772:2012.Themainchangesbetweenthisdocumentandthepreviousversionare:
• Language-specificannexes(AnnexesCthroughH)havebeenremovedfromthedocumentandarebeingrepublishedaslanguage-specificparts,TR24772-2ProgrammingLanguageVulnerabilities–SpecificguidanceforAda,TR24772-3ProgrammingLanguageVulnerabilities–SpecificguidanceforC,etc.
• Vulnerabilitiesthatweredocumentedinclause8ofversion2arenowdocumentedaspartofclauses6and7.
• Newvulnerabilitiesareadded.• Guidancematerialforeachvulnerabilitygiveninsubclause6.X.5isrewordedtobemoreexplicitand
directive.• Additionmaterialforsomevulnerabilitieshasbeenadded.
Deleted:
Deleted:
WG23/N0720
viii ©ISO/IEC2013–Allrightsreserved
Deleted: 664
Introduction
Allprogramminglanguagescontainconstructsthatareincompletelyspecified,exhibitundefinedbehaviour,areimplementation-dependent,oraredifficulttousecorrectly.Theuseofthoseconstructsmaythereforegiverisetovulnerabilities,asaresultofwhich,softwareprogramscanexecutedifferentlythanintendedbythewriter.Insomecases,thesevulnerabilitiescancompromisethesafetyofasystemorbeexploitedbyattackerstocompromisethesecurityorprivacyofasystem.
ThisTechnicalReportisintendedtoprovideguidancespanningmultipleprogramminglanguages,sothatapplicationdeveloperswillbebetterabletoavoidtheprogrammingconstructsthatleadtovulnerabilitiesinsoftwarewrittenintheirchosenlanguageandtheirattendantconsequences.Thisguidancecanalsobeusedbydeveloperstoselectsourcecodeevaluationtoolsthatcandiscoverandeliminatesomeconstructsthatcouldleadtovulnerabilitiesintheirsoftwareortoselectaprogramminglanguagethatavoidsanticipatedproblems.
ItshouldbenotedthatthisTechnicalReportisinherentlyincomplete.Itisnotpossibletoprovideacompletelistofprogramminglanguagevulnerabilitiesbecausenewweaknessesarediscoveredcontinually.Anysuchreportcanonlydescribethosethathavebeenfound,characterized,anddeterminedtohavesufficientprobabilityandconsequence.
Deleted:
Deleted:
Deleted:
Formatted: No bullets or numberingDeleted: Deleted:
TechnicalReport ISO/IECTR24772:2013(E)
©ISO/IEC2013–Allrightsreserved 9
InformationTechnology—ProgrammingLanguages—Guidancetoavoidingvulnerabilitiesinprogramminglanguages
1.Scope
Thisdocumentspecifiessoftwareprogramminglanguagevulnerabilitiestobeavoidedinthedevelopmentofsystemswhereassuredbehaviourisrequiredforsecurity,safety,mission-criticalandbusiness-criticalsoftware.Ingeneral,thisguidanceisapplicabletothesoftwaredeveloped,reviewed,ormaintainedforanyapplication.
Vulnerabilitiesaredescribedinagenericmannerthatisapplicabletoabroadrangeofprogramminglanguages.
2.Normativereferences
Thefollowingreferenceddocumentsareindispensablefortheapplicationofthisdocument.Fordatedreferences,onlytheeditioncitedapplies.Forundatedreferences,thelatesteditionofthereferenceddocument(includinganyamendments)applies.
ISO/IEC/IEEE60559:2011,Informationtechnology--MicroprocessorSystems--Floating-Pointarithmetic
ISO/IEC10967-1:2012…
ISO/IEC10967-2:2001…
ISO/IEC10967-3:2006…
3.Termsanddefinitions,symbolsandconventions
3.1Termsanddefinitions
Forthepurposesofthisdocument,thetermsanddefinitionsgiveninISO/IEC2382–1andthefollowingapply.Othertermsaredefinedwheretheyappearinitalictype.
ISOandIECmaintainterminologydatabasesforuseinstandardizationareavailableat:
• IECGlossary,std.iec.ch/glossary• ISOOnlineBrowsingPlatform,www.iso.ch/obp/ui
3.1.1Communication3.1.1.1protocol
Deleted: throughlanguageselectionanduse
Deleted:
Deleted:
Deleted:
Deleted:
WG23/N0720
10 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
setofrulesandsupportingstructuresfortheinteractionofthreads
Note1:Aprotocolcanbetightlyembeddedandrelyupondatainmemoryandhardwaretocontrolinteractionofthreadsorcanbeappliedtomorelooselycoupledarrangements,suchasmessagecommunicationspanningnetworksandcomputersystems.
3.1.1.2statelessprotocolcommunicationorcooperationbetweenthreadswherenostateispreservedintheprotocolitself(exampleHTTPordirectaccesstoasharedresource)
Note1:Sincemostinteractionbetweenthreadsrequiresthatstatebepreserved,thecooperatingthreadsmustusevaluesoftheresources(s)themselvesoraddadditionalcommunicationexchangestomaintainstate.Statelessprotocolsrequirethattheapplicationprovideexplicitresourceprotectionandlockingmechanismstoguaranteethecorrectcreation,view,accessto,modificationof,anddestructionoftheresource–forexample,thestateneededforcorrecthandlingoftheresource.
3.1.2Executionmodel3.1.2.1threadsequentialstreamofexecution
Note1:Althoughthetermthreadisusedhereandthecontextportrayedisthatofshared-memorythreadsexecutingaspartofaprocess,everythingdocumentedappliesequallytoothervariantsofconcurrencysuchasinterrupthandlersbeingenabledbyaprocess,processesbeingcreatedonthesamesystemusingoperatingsystemroutines,orprocessescreatedasaresultofdistributedmessagessentoveranetwork.Themitigationapproacheswillbesimilartothoselistedintherelevantvulnerabilitydescriptions,buttheimplicationsforstandardizationwouldbedependentonhowmuchlanguagesupportisprovidedfortheprogrammingoftheconcurrentsystem.
3.1.2.2threadactivationcreationandsetupofathreaduptothepointwherethethreadbeginsexecution
Note1:Athreadmaydependupononeormoreotherthreadstodefineitsaccesstootherobjectstobeaccessedandtodetermineitsduration.
3.1.2.3activatedthreadthreadthatiscreatedandthenbeginsexecutionasaresultofthreadactivation
3.1.2.4activatingthreadthreadthatexistsfirstandmakesthelibrarycallsorcontainsthelanguagesyntaxthatcausestheactivatedthreadtobeactivated
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 11
Note1:Theactivatingthreadmayormaynotwaitfortheactivatedthreadtofinishactivationandmayormaynotcheckforerrorsiftheactivationfails.Theactivatingthreadmayormaynotbepermittedtoterminateuntilaftertheactivatedthreadterminates.
3.1.2.5staticthreadactivationcreationandinitiationofathreadbyprograminitiation,anoperatingsystemorruntimekernel,orbyanotherthreadaspartofadeclarativepartofthethreadbeforeitbeginsexecution
Note1:Instaticactivation,astaticanalysiscandetermineexactlyhowmanythreadswillbecreatedandhowmuchresource,intermsofmemory,processors,CPUcycles,priorityrangesandinter-threadcommunicationstructures,willbeneededbytheexecutingprogrambeforetheprogrambegins.
3.1.2.6dynamicthreadactivationcreationandinitiationofathreadbyanotherthread(includingthemainprogram)asanexecutable,repeatablecommand,statementorsubprogramcall
3.1.2.7threadabortrequesttostopandshutdownathreadimmediately
Note1:Therequestisasynchronousiffromanotherthread,orsynchronousiffromthethreaditself.Theeffectoftheabortrequest(suchaswhetheritistreatedasanexception)anditsimmediacy(thatis,howlongthethreadmaycontinuetoexecutebeforeitisshutdown)dependonlanguage-specificrules.Immediateshutdownminimizeslatencybutmayleaveshareddatastructuresinacorruptedstate.
3.1.2.8termination-directingthreadthread(includingtheOS)thatrequeststheabortionofoneormorethreads
3.1.2.9threadterminationcompletionandorderlyshutdownofathread,wherethethreadispermittedtomakedataobjectsconsistent,releaseanyacquiredresources,andnotifyanydependentthreadsthatitisterminating
Note1:Thereareanumberofstepsintheterminationofathreadaslistedbelow,butdependinguponthemultithreadingmodel,someofthesestepsmaybecombined,maybeexplicitlyprogrammed,ormaybemissing:
• theterminationofprogrammedexecutionofthethread,includingterminationofanysynchronouscommunication;
• thefinalizationofthelocalobjectsofthethread;• waitingforanythreadsthatmaydependonthethreadtoterminate;• finalizationofanystateassociatedwithdependentthreads;• notificationthatfinalizationiscomplete,includingpossiblenotificationoftheactivatingtask;
WG23/N0720
12 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
• removalandcleanupofthreadcontrolblocksandanystateaccessiblebythethreadorbyotherthreadsinouterscopes.
3.1.2.10terminatedthreadthreadthathasbeenhaltedfromanyfurtherexecution
3.1.2.11masterthreadthreadwhichmustwaitforaterminatedthreadbeforeitcantakefurtherexecutionsteps(includingterminationofitself)
3.1.2.12processsingleexecutionofaprogram,orportionofanapplication
Note1:Processesdonotnormallyshareacommonmemoryspace,butoftenshare
• processor,• network,• operatingsystem,• filingsystem,• environmentvariables,or• otherresources.
Processesareusuallystartedandstoppedbyanoperatingsystemandmayormaynotinteractwithotherprocesses.Aprocessmaycontainmultiplethreads.
3.1.3Properties3.1.3.1softwarequalitydegreetowhichsoftwareimplementstherequirementsdescribedbyitsspecificationandthedegreetowhichthecharacteristicsofasoftwareproductfulfillitsrequirements
3.1.3.2predictableexecutionpropertyoftheprogramsuchthatallpossibleexecutionshaveresultsthatcanbepredictedfromthesourcecode
3.1.4Safety3.1.4.1safetyhazardpotentialsourceofharm
Note1:IEC61508–4:definesa“Hazard”asa“potentialsourceofharm”,where“harm”is“physicalinjuryordamagetothehealthofpeopleeitherdirectlyorindirectlyasaresultofdamagetopropertyortotheenvironment”.Somederivedstandards,suchasUKDefenceStandard00-56,broadenthedefinitionof
Deleted:
Deleted:
Deleted:
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 13
“harm”toincludematerialandenvironmentaldamage(notjustharmtopeoplecausedbypropertyandenvironmentaldamage).
3.1.4.2safety-criticalsoftwaresoftwareforapplicationswherefailurecancauseveryseriousconsequencessuchashumaninjuryordeath
Note1:IEC61508–4:defines“Safety-relatedsoftware”as“softwarethatisusedtoimplementsafetyfunctionsinasafety-relatedsystem.Notwithstandingthatinsomedomainsadistinctionismadebetweensafety-related(canleadtoanyharm)andsafety-critical(lifethreatening),thisTechnicalReportusesthetermsafety-criticalforallvulnerabilitiesthatcanresultinsafetyhazards.
3.1.5Vulnerabilities3.1.5.1applicationvulnerabilitysecurityvulnerabilityorsafetyhazard,ordefect
3.1.5.2languagevulnerabilityproperty(ofaprogramminglanguage)thatcancontributeto,orthatisstronglycorrelatedwith,applicationvulnerabilitiesinprogramswritteninthatlanguage
Note1:Theterm"property"canmeanthepresenceortheabsenceofaspecificfeature,usedsinglyorincombination.Asanexampleoftheabsenceofafeature,encapsulation(controlofwherenamescanbereferencedfrom)isgenerallyconsideredbeneficialsinceitnarrowstheinterfacebetweenmodulesandcanhelppreventdatacorruption.Theabsenceofencapsulationfromaprogramminglanguagecanthusberegardedasavulnerability.Notethatapropertytogetherwithitscomplementcanbothbeconsideredlanguagevulnerabilities.Forexample,automaticstoragereclamation(garbagecollection)canbeavulnerabilitysinceitcaninterferewithtimepredictabilityandresultinasafetyhazard.Ontheotherhand,theabsenceofautomaticstoragereclamationcanalsobeavulnerabilitysinceprogrammerscanmistakenlyfreestorageprematurely,resultingindanglingreferences.
3.1.5.3securityvulnerabilityweaknessinaninformationsystem,systemsecurityprocedures,internalcontrols,orimplementationthatcouldbeexploitedortriggeredbyathreat
3.2Symbolsandconventions
3.2.1Symbols
Forthepurposesofthisdocument,thesymbolsgiveninISO80000–2apply.Othersymbolsaredefinedwheretheyappearinthisdocument.
3.2.2Conventions
Programminglanguagetokensandsyntactictokensappearincourierfont.
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
WG23/N0720
14 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
4.Basicconcepts
4.1PurposeofthisTechnicalReport
Thisdocumentspecifiessoftwareprogramminglanguagevulnerabilitiestobeavoidedinthedevelopmentofsystemswhereassuredbehaviourisrequiredforsecurity,safety,missioncriticalandbusinesscriticalsoftware.Ingeneral,thisguidanceisapplicabletothesoftwaredeveloped,reviewed,ormaintainedforanyapplication.
Thisdocumentdoesnotaddresssoftwareengineeringandmanagementissuessuchashowtodesignandimplementprograms,useconfigurationmanagementtools,usemanagerialprocesses,andperformprocessimprovement.Furthermore,thespecificationofpropertiesandapplicationstobeassuredarenottreated.
Whilethisdocumentdoesnotdiscussspecificationordesignissues,thereisrecognitionthatboundariesamongthevariousactivitiesarenotclear-cut.Thisdocumentseekstoavoidthedebateaboutwherelow-leveldesignendsandimplementationbeginsbytreatingselectedissuesthatsomemightconsiderdesignissuesratherthancodingissues.
Thebodyofthisdocumentprovidesusersofprogramminglanguageswithalanguage-independentoverviewofpotentialvulnerabilitiesintheirusage.Annexesdescribehowthegeneralobservationsapplytospecificlanguages.
4.2Intendedaudience
Theintendedaudienceforthisdocumentarethosewhoareconcernedwithassuringthepredictableexecutionofthesoftwareoftheirsystem;thatis,thosewhoaredeveloping,qualifying,ormaintainingasoftwaresystemandneedtoavoidlanguageconstructsthatcouldcausethesoftwaretoexecuteinamannerotherthanintended.
Developersofapplicationsthathaveclearsafety,securityormission-criticalityareexpectedtobeawareoftherisksassociatedwiththeircodeandcouldusethisdocumenttoensurethattheirdevelopmentpracticesaddresstheissuespresentedbythechosenprogramminglanguages,forexamplebysubsettingorprovidingcodingguidelines.
Itshouldnotbeassumed,however,thatotherdeveloperscanignorethisTechnicalReport.Aweaknessinanon-criticalapplicationmayprovidetheroutebywhichanattackergainscontrolofasystemorotherwisedisruptsco-hostedapplicationsthatarecritical.ItishopedthatalldeveloperswouldusethisTechnicalReporttoensurethatcommonvulnerabilitiesareremovedoratleastminimizedfromallapplications.
Specificaudiencesforthisdocumentincludedevelopers,maintainersandregulatorsof:
• Safety-criticalapplicationsthatmightcauselossoflife,humaninjury,ordamagetotheenvironment.• Security-criticalapplicationsthatmustensurepropertiesofconfidentiality,integrity,andavailability.• Mission-criticalapplicationsthatmustavoidlossordamagetopropertyorfinance.• Business-criticalapplicationswherecorrectoperationisessentialtothesuccessfuloperationofthe
business.• Scientific,modelingandsimulationapplicationsthatrequirehighconfidenceintheresultsofpossibly
complex,expensiveandextendedcalculation.
Deleted: TechnicalReport
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted: which
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 15
4.3Howtousethisdocument
Thisdocumentgathersdescriptionsofprogramminglanguagevulnerabilities,aswellasselectedapplicationvulnerabilities,whichhaveoccurredinthepastandarelikelytooccuragain.Eachvulnerabilityanditspossiblemitigationsaredescribedinthebodyofthereportinalanguage-independentmanner,thoughillustrativeexamplesmaybelanguagespecific.Inaddition,annexesforparticularlanguagesdescribethevulnerabilitiesandtheirmitigationsinamannerspecifictothelanguage.
Becausenewvulnerabilitiesarealwaysbeingdiscovered,itisanticipatedthatthisdocumentwillberevisedandnewdescriptionsadded.Forthatreason,aschemethatisdistinctfromsub-clausenumberinghasbeenadoptedtoidentifythevulnerabilitydescriptions.Eachdescriptionhasbeenassignedanarbitrarilygenerated,uniquethree-lettercode.Thesecodesshouldbeusedinpreferencetosub-clausenumberswhenreferencingdescriptionsbecausetheywillnotchangeasadditionaldescriptionsareaddedtofutureeditionsofthisdocument.
ThemainpartofthisDocumentcontainsdescriptionsthatareintendedtobelanguage-independenttothegreatestpossibleextent.Annexesapplythegenericguidancetoparticularprogramminglanguages.
Thisdocumenthasbeenwrittenwithseveralpossibleusagesinmind:
• Programmersfamiliarwiththevulnerabilitiesofaspecificlanguagecanreferencetheguideformoregenericdescriptionsandtheirmanifestationsinlessfamiliarlanguages.
• Toolvendorscanusethethree-lettercodesasasuccinctwayto“profile”theselectionofvulnerabilitiesconsideredbytheirtools.
• Individualorganizationsmaywishtowritetheirowncodingstandardsintendedtoreducethenumberofvulnerabilitiesintheirsoftwareproducts.Theguidecanassistintheselectionofvulnerabilitiestobeaddressedinthosestandardsandtheselectionofcodingguidelinestobeenforced.
• Organizationsorindividualsselectingalanguageforuseinaprojectmaywanttoconsiderthevulnerabilitiesinherentinvariouscandidatelanguages.
• Scientists,engineers,economists,statisticians,orotherswhowritecomputerprogramsastoolsoftheirchosencraftcanreadthisdocumenttobecomemorefamiliarwiththeissuesthatmayaffecttheirwork.
Thedescriptionsincludesuggestionsforwaysofavoidingthevulnerabilities.Somearesimplytheavoidanceofparticularcodingconstructs,butothersmayinvolveincreasedrevieworotherverificationandvalidationmethods.Sourcecodecheckingtoolscanbeusedtoautomaticallyenforcesomecodingrulesandstandards.
Clause2providesnormativereferences.
Clause3providesterms,definitions,symbolsandconventions.
Clause4providesthebasicconceptsusedforthisdocument.
Clause5,VulnerabilityIssues,providesrationaleforthisdocumentandexplainshowmanyofthevulnerabilitiesoccur.
Clause6,ProgrammingLanguageVulnerabilities,provideslanguage-independentdescriptionsofvulnerabilitiesinprogramminglanguagesthatcanleadtoapplicationvulnerabilities.Eachdescriptionprovides:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
WG23/N0720
16 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
• asummaryofthevulnerability,• characteristicsoflanguageswherethevulnerabilitymaybefound,• typicalmechanismsoffailure,• techniquesthatprogrammerscanusetoavoidthevulnerability,and• waysthatlanguagedesignerscanmodifylanguagespecificationsinthefuturetohelpprogrammers
mitigatethevulnerability.
Clause7,ApplicationVulnerabilities,providesdescriptionsofselectedvulnerabilitieswhichhavebeenfoundandexploitedinanumberofapplicationsandwhichhavewellknownmitigationtechniques,andwhichresultfromdesigndecisionsmadebycodersintheabsenceofsuitablelanguagelibraryroutinesorothermechanisms.Forthesevulnerabilities,eachdescriptionprovides:
• asummaryofthevulnerability,• typicalmechanismsoffailure,and• techniquesthatprogrammerscanusetoavoidthevulnerability.
Clause8,NewVulnerabilities,providesnewvulnerabilitiesthathavenotyethadcorrespondingprogramminglanguagetextdeveloped.
AnnexA,VulnerabilityTaxonomyandList,isacategorizationofthevulnerabilitiesofthisreportintheformofahierarchicaloutlineandalistofthevulnerabilitiesarrangedinalphabeticorderbytheirthreelettercode.
AnnexB,LanguageSpecificVulnerabilityTemplate,isatemplateforthewritingofprogramminglanguagespecificannexesthatexplainhowthevulnerabilitiesfromclause6arerealizedinthatprogramminglanguage(orshowhowtheyareabsent),andhowtheymightbemitigatedinlanguage-specificterms.
ThisdocumentissupportedbyasetofTechnicalReportsnumberedTR24772-2,TR24772-3,andsoon.EachadditionalpartisnamedforaparticularprogramminglanguageliststhevulnerabilitiesdescribedinClauses6and7ofthisdocumentanddescribehoweachvulnerabilityappearsinthatspecificlanguageandspecifieshowitmaybemitigatedinthatlanguage,wheneverpossible.Allofthelanguage-dependentdescriptionsassumethattheuseradherestothestandardforthelanguageaslistedinthesub-clauseofeachPart.
5Vulnerabilityissuesandgeneralavoidancemechanisms
5.1Predictableexecution
Therearemanyreasonswhysoftwaremightnotexecuteasexpectedbyitsdevelopers,itsusersorotherstakeholders.Reasonsincludeincorrectspecifications,configurationmanagementerrorsandamyriadofothers.ThisDocumentfocusesononecause—theusageofprogramminglanguagesinwaysthatrendertheexecutionofthecodelesspredictable.
Predictableexecutionisapropertyofaprogramsuchthatallpossibleexecutionshaveresultsthatcanbepredictedfromexaminationofthesourcecode.Achievingpredictabilityiscomplicatedbythatfactthatsoftwaremaybeused:
• onunanticipatedplatforms(forexample,portedtoadifferentprocessor)
Deleted:
Deleted:
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 17
• inunanticipatedways(asusagepatternschange),• inunanticipatedcontexts(forexample,softwarereuseandsystem-of-systemintegrations),and• byunanticipatedusers(forexample,thoseseekingtoexploitandpenetrateasoftwaresystem).
Furthermore,today’subiquitousconnectivityofsoftwaresystemsvirtuallyguaranteesthatmostsoftwarewillbeattacked—eitherbecauseitisatargetforpenetrationorbecauseitoffersaspringboardforpenetrationofothersoftware.Accordingly,today’sprogrammersmusttakeadditionalcaretoensurepredictableexecutiondespitethenewchallenges.
Softwarevulnerabilitiesareunwantedcharacteristicsofsoftwarethatmayallowsoftwaretoexecuteinwaysthatareunexpected.Programmersintroducevulnerabilitiesintosoftwarebyusinglanguagefeaturesthatareinherentlyunpredictableinthevariablecircumstancesoutlinedaboveorbyusingfeaturesinamannerthatreduceswhatpredictabilitytheycouldoffer.Ofcourse,completepredictabilityisanideal(particularlybecausenewvulnerabilitiesareoftendiscoveredthroughexperience),butanyprogrammercanimprovepredictabilitybycarefullyavoidingtheintroductionofknownvulnerabilitiesintocode.
ThisDocumentfocusesonaparticularclassofvulnerabilities,languagevulnerabilities.Thesearepropertiesofprogramminglanguagesthatcancontributeto(orarestronglycorrelatedwith)applicationvulnerabilities—securityweaknesses,safetyhazards,ordefects.Anexamplemayclarifytherelationship.Theprogrammer’suseofastringcopyingfunctionthatdoesnotchecklengthmaybeexploitedbyanattackertoplaceincorrectreturnvaluesontheprogramstack,hencepassingcontroloftheexecutiontocodeprovidedbytheattacker.Thestringcopyingfunctionisthelanguagevulnerabilityandtheresultingweaknessoftheprograminthefaceofthestackattackistheapplicationvulnerability.Theprogramminglanguagevulnerabilityenablestheapplicationvulnerability.Thelanguagevulnerabilitycanbeavoidedbyusingastringcopyingfunctionthatdoessetappropriateboundsonthelengthofthestringtobecopied.Byusingaboundedcopyfunctiontheprogrammerimprovesthepredictabilityofthecode’sexecution.
TheprimarypurposeofthisDocumentistosurveycommonprogramminglanguagevulnerabilities;thisisdoneinClause6.Eachdescriptionexplainshowanapplicationvulnerabilitycanresult.InClause7,afewadditionalapplicationvulnerabilitiesaredescribed.Theseareselectedbecausetheyareassociatedwithlanguageweaknesseseveniftheydonotdirectlyresultfromlanguagevulnerabilities.Forexample,aprogrammermighthavestoredapasswordinplaintext(seeError!Referencesourcenotfound.)becausetheprogramminglanguagedidnotprovideasuitablelibraryfunctionforstoringthepasswordinanon-recoverableformat.
Inadditiontoconsideringtheindividualvulnerabilities,itisinstructivetoconsiderthesourcesofuncertaintythatcandecreasethepredictabilityofsoftware.Thesesourcesarebrieflyconsideredintheremainderofthisclause.
5.2Sourcesofunpredictabilityinlanguagespecification
5.2.1Incompleteorevolvingspecification
Thedesignandspecificationofaprogramminglanguageinvolvesconsiderationsthatareverydifferentfromtheuseofthelanguageinprogramming.Languagespecifiersoftenneedtomaintaincompatibilitywitholderversionsofthelanguage—eventotheextentofretaininginherentlyvulnerablefeatures.Sometimesthesemanticsofneworcomplexfeaturesarenotcompletelyknown,especiallywhenusedincombinationwithotherfeatures.
Deleted:
Deleted:
Deleted:
Deleted:
Deleted: Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted: Deleted: Deleted: Deleted: Deleted: Error!Referencesourcenotfound.Error!Referencesourcenotfound.
Deleted:
Deleted:
Deleted:
Deleted: n’t
WG23/N0720
18 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
5.2.2Undefinedbehaviour
It’ssimplynotpossibleforthespecifierofaprogramminglanguagetodescribeeverypossiblebehaviour.Forexample,theresultofusingavariabletowhichnovaluehasbeenassignedisleftundefinedbymanylanguages.Insuchcases,aprogrammightdoanything—includingcrashingwithnodiagnosticorexecutingwithwrongdata,leadingtoincorrectresults.
5.2.3Unspecifiedbehaviour
Thebehaviourofsomefeaturesmaybeincompletelydefined.Thelanguageimplementerwouldhavetochoosefromafinitesetofchoices,butthechoicemaynotbeapparenttotheprogrammer.Insuchcases,differentcompilersmayleadtodifferentresults.
5.2.4Implementation-definedbehaviour
Insomecases,theresultsofexecutionmaydependuponcharacteristicsofthecompilerthatwasused,theprocessoruponwhichthesoftwareisexecuted,ortheothersystemswithwhichthesoftwarehasinterfaces.Inprinciple,onecouldpredicttheexecutionwithsufficientknowledgeoftheimplementation,butsuchknowledgeissometimesdifficulttoobtain.Furthermore,dependenceonaspecificimplementation-definedbehaviourwillleadtoproblemswhenadifferentprocessororcompilerisused—sometimesifdifferentcompilerswitchsettingsareused.
5.2.5Difficultfeatures
Somelanguagefeaturesmaybedifficulttounderstandortouseappropriately,eitherduetocomplicatedsemantics(forexample,floatingpointinnumericalanalysisapplications)orhumanlimitations(forexample,deeplynestedprogramconstructsorexpressions).Sometimessimpletypingerrorscanleadtomajorchangesinbehaviourwithoutadiagnostic(forexample,typing“=”forassignmentwhenonereallyintended“==”forcomparison).
5.2.6Inadequatelanguagesupport
Nolanguageissuitableforeverypossibleapplication.Furthermore,programmerssometimesdonothavethefreedomtoselectthelanguagethatismostsuitableforthetaskathand.Inmanycases,librariesmustbeusedtosupplementthefunctionalityofthelanguage.Then,thelibraryitselfbecomesapotentialsourceofuncertaintyreducingthepredictabilityofexecution.
5.3Sourcesofunpredictabilityinlanguageusage
5.3.1Portingandinteroperation
Whenaprogramisrecompiledusingadifferentcompiler,recompiledusingdifferentswitches,executedwithdifferentlibraries,executedonadifferentplatform,oreveninterfacedwithdifferentsystems,itsbehaviourwillchange.Changesresultfromdifferentchoicesforunspecifiedandimplementation-definedbehaviour,differencesinlibraryfunction,anddifferencesinunderlyinghardwareandoperatingsystemsupport.Theproblemisfar
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 19
worseiftheoriginalprogrammerchosetouseimplementation-dependentextensionstothelanguageratherthanstayingwiththestandardizedlanguage.
5.3.2Compilerselectionandusage
Nearlyallsoftwarehasbugsandcompilersarenoexception.Theyshouldbecarefullyselectedfromtrustedsourcesandqualifiedpriortouse.Perhapslessobvious,though,istheuseofcompilerswitches.Differentswitchsettingscanresultindifferencesingeneratedcode.Acarefulselectionofsettingscanimprovethepredictabilityofcode,forexample,asettingthatcausestheflaggingofanyusageofanimplementation-definedbehaviour.
5.4Topavoidancemechanisms
Eachvulnerabilitylistedinsections6and7providesasetofwaysthatthevulnerabilitycanbeavoidedormitigated.Manyofthemitigationsandavoidancemechanismsarecommon.Thissubclauseprovidesthemostmosteffectiveandthemostcommonmitigations,togetherwithreferencestowhichvulnerabilitiestheyapply.Thereferencesarehyperlinkedtoprovidethereaderwitheasyaccesstothosevulnerabilitiesforrationaleandfurtherexploration.
Theexpectationisthatusersofthisdocumentwilldevelopanduseacodingstandardbasedonthisdocumentthatistailoredtotheirriskenvironment.Number Recommendedavoidancemechanism References1 Validateinput.Donotmakeassumptionsaboutthevaluesofparameters.
Checkparametersforvalidrangesandvaluesinthecallingand/orcalledfunctionsbeforeperforminganyoperations.
6.6 7.13
7.187.28
2 Whenfunctionsreturnerrorvalues,checktheerrorreturnvaluesbeforeprocessinganyotherreturneddata.
6.366.60
3 Enablecompilerstaticanalysischeckingandresolvecompilerwarnings. 6.8 6.10 6.14 6.15
6.16 6.17 6.18 6.19
6.22 6.25 6.26 6.27
6.29 6.30 6.34 6.36
6.38 6.39 6.47 6.54
6.56 6.57 6.60 6.61
6.62 7.28.
Deleted:
Deleted: Deleted: Deleted:
Deleted: Deleted:
Deleted: Deleted: Deleted:
Deleted: Deleted:
WG23/N0720
20 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
4 Runastaticanalysistooltodetectanomaliesnotcaughtbythecompiler. 6.3 6.6 6.7 6.8
6.10 6.14 6.15 6.16
6.17 6.18 6.19 6.22
6.25 6.26 6.27 6.29
6.30 6.34 6.36 6.38
6.39 6.47 6.54 6.56
6.57 6.60 6.61 6.62
7.28
5 Performexplicitrangecheckingwhenitcannotbeshownstaticallythatrangeswillbeobeyed,whenrangecheckingisnotprovidedbytheimplementation,orifautomaticrangecheckingisdisabled.
6.66.86.16
6 Allocateandfreeresources,suchasmemory,threadsorlocks,atthesamelevelofabstraction.
6.14
7 Avoidconstructsthathaveunspecifiedbutboundedbehavior,andiftheconstructisneeded,testforallpossiblebehaviours.
6.24 6.56
8 Makeerrordetection,errorreporting,errorcorrection,andrecoveryanintegralpartofasystemdesign.
6.36
10 Useonlythosefeaturesoftheprogramminglanguagethatenforcealogicalstructureontheprogram.
6.31
11 Avoidusingfeaturesofthelanguagewhicharenotspecifiedtoanexactbehaviourorthatareundefined,implementation-definedordeprecated.
6.55 6.56 6.576.58 6.59
12 Avoidusinglibrarieswithoutpropersignatures. 6.34
13 Donotmodifyloopcontrolvariablesinsidetheloopbody. 6.29
14 DonotperformassignmentswithinBooleanexpressions,evenifallowedbythelanguage.
6.25
15 Donotdependonsideeffectsofatermintheexpressionitself. 6.31 6.24
16 Usenamesthatareclearandvisuallyunambiguous.Beconsistentinchoosingnames.
6.17
17 Usecarefulprogrammingpracticewhenprogrammingbordercases. 6.6 6.29
6.30
18 Beawareofshort-circuitingbehaviourwhenexpressionswithsideeffectsareusedontherightsideofaBooleanexpressionsuchasifthefirst
6.246.25
Deleted:
Deleted: Deleted: Deleted: Deleted:
Deleted: wherepossibleinDeleted: system
Deleted:
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 21
expressionevaluatestofalseinanandexpression,thentheremainingexpressions,includingfunctionscalls,willnotbeevaluated.
19 Avoidfall-throughfromonecase(orswitch)statementintothefollowingcasestatement:ifafall-throughisnecessarythenprovideacommenttoinformthereaderthatitisintentional.
6.27
20 Donotusefloating-pointarithmeticwhenintegerswouldsuffice,especiallyforcountersassociatedwithprogramflow,suchasloopcontrolvariables.
6.4
21 Sanitize,eraseorencryptdatathatwillbevisibletoothers(forexample,freedmemory,transmitteddata).
7.117.12
6.Programminglanguagevulnerabilities
6.1General
Thisclauseprovideslanguage-independentdescriptionsofvulnerabilitiesinprogramminglanguagesthatcanleadtoapplicationvulnerabilities.Eachdescriptionprovides:
• asummaryofthevulnerability,• characteristicsoflanguageswherethevulnerabilitymaybefound,• typicalmechanismsoffailure,• techniquesthatprogrammerscanusetoavoidthevulnerability,and• waysthatlanguagedesignerscanmodifylanguagespecificationsinthefuturetohelpprogrammers
mitigatethevulnerability.
Descriptionsofhowvulnerabilitiesaremanifestedinparticularprogramminglanguagesareprovidedinannexesofthisdocument.Ineachcase,thebehaviourofthelanguageisassumedtobeasspecifiedbythestandardcitedintheannex.Clearly,programscouldhavedifferentvulnerabilitiesinanon-standardimplementation.Examplesofnon-standardimplementationsinclude:
• compilerswrittentoimplementsomespecificationotherthanthestandard,• useofnon-standardvendorextensionstothelanguage,and• useofcompilerswitchesprovidingalternativesemantics.
Thefollowingdescriptionsarewritteninalanguage-independentmannerexceptwhenspecificlanguagesareusedinexamples.Theannexesmaybeconsultedforlanguagespecificdescriptions.
Thisclausewill,ingeneral,usetheterminologythatismostnaturaltothedescriptionofeachindividualvulnerability.Henceterminologymaydifferfromdescriptiontodescription.
Deleted: orbooleans
Formatted: Font color: Auto
Deleted:
Deleted:
Deleted:
WG23/N0720
22 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
6.2Typesystem[IHN]
6.2.1Descriptionofapplicationvulnerability
Whendatavaluesareconvertedfromonedatatypetoanother,evenwhendoneintentionally,unexpectedresultscanoccur.
6.2.2Crossreference
JSFAVRules:148and183MISRAC2012:4.6,10.1,10.3,and10.4MISRAC++2008:3-9-2,5-0-3to5-0-14CERTCguidelines:DCL07-C,DCL11-C,DCL35-C,EXP05-CandEXP32-CAdaQualityandStyleGuide:3.4
6.2.3Mechanismoffailure
Thetypeofadataobjectinformsthecompilerhowvaluesshouldberepresentedandwhichoperationsmaybeapplied.Thetypesystemofalanguageisthesetofrulesusedbythelanguagetostructureandorganizeitscollectionoftypes.Anyattempttomanipulatedataobjectswithinappropriateoperationsisatypeerror.Aprogramissaidtobetypesafe(ortypesecure)ifitcanbedemonstratedthatithasnotypeerrors[27].
Everyprogramminglanguagehassomesortoftypesystem.Alanguageisstaticallytypedifthetypeofeveryexpressionisknownatcompiletime.Thetypesystemissaidtobestrongifitguaranteestypesafetyandweakifitdoesnot.Therearestronglytypedlanguagesthatarenotstaticallytypedbecausetheyenforcetypesafetywithruntimechecks[27].
Inpracticalterms,nearlyeverylanguagefallsshortofbeingstronglytyped(inanidealsense)becauseoftheinclusionofmechanismstobypasstypesafetyinparticularcircumstances.Forthatreasonandbecauseeverylanguagehasadifferenttypesystem,thisdescriptionwillfocusontakingadvantageofwhateverfeaturesfortypesafetymaybeavailableinthechosenlanguage.
Sometimesitisappropriateforadatavaluetobeconvertedfromonetypetoanothercompatibleone.Forexample,considerthefollowingprogramfragment,writteninnospecificlanguage:
float a; integer i; a := a + i;
Thevariable"i"isofintegertype.Itisconvertedtothefloattypebeforeitisaddedtothedatavalue.Thisisanimplicittypeconversion.If,ontheotherhand,theconversionmustbespecifiedbytheprogram,forexample,"a := a + float(i)",thenitisanexplicittypeconversion.
Typeequivalenceisthestrictestformoftypecompatibility;twotypesareequivalentiftheyarecompatiblewithoutusingimplicitorexplicitconversion.Typeequivalenceisusuallycharacterizedintermsofnametype
equivalence—twovariableshavethesametypeiftheyaredeclaredinthesamedeclarationordeclarationsthatusethesametypename—orstructuretypeequivalence—twovariableshavethesametypeiftheyhaveidentical
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 23
structures.Therearevariationsoftheseapproachesandmostlanguagesusedifferentcombinationsofthem[28].Therefore,aprogrammerskilledinonelanguagemayverywellcodeinadvertenttypeerrorswhenusingadifferentlanguage.
Itisdesirableforaprogramtobetypesafebecausetheapplicationofoperationstooperandsofaninappropriatetypemayproduceunexpectedresults.Inaddition,thepresenceoftypeerrorscanreducetheeffectivenessofstaticanalysisforotherproblems.Searchingfortypeerrorsisavaluableexercisebecausetheirpresenceoftenrevealsdesignerrorsaswellascodingerrors.Manylanguagescheckfortypeerrors—someatcompile-time,othersatrun-time.Obviously,compile-timecheckingismorevaluablebecauseitcancatcherrorsthatarenotexecutedbyaparticularsetoftestcases.
Makingthemostuseofthetypesystemofalanguageisusefulintwoways.First,dataconversionsalwaysbeartheriskofchangingthevalue.Forexample,aconversionfromintegertofloatrisksthelossofsignificantdigitswhiletheinverseconversionrisksthelossofanyfractionalvalue.Conversionofanintegervaluefromatypewithalongerrepresentationtoatypewithashorterrepresentationrisksthelossofsignificantdigits.Thiscanproduceparticularlypuzzlingresultsifthevalueisusedtoindexanarray.Conversionofafloating-pointvaluefromatypewithalongerrepresentationtoatypewithashorterrepresentationrisksthelossofprecision.Thiscanbeparticularlysevereincomputationswherethenumberofcalculationsincreasesasapoweroftheproblemsize.(Itshouldbenotedthatsimilarsurprisescanoccurwhenanapplicationisretargetedtoamachinewithdifferentrepresentationsofnumericvalues.)
Second,aprogrammercanusethetypesystemtoincreasetheprobabilityofcatchingdesignerrorsorcodingblunders.Forexample,thefollowingAdafragmentdeclarestwodistinctfloating-pointtypes:
type Celsius is new Float; type Fahrenheit is new Float;
ThedeclarationmakesitimpossibletoaddavalueoftypeCelsiustoavalueoftypeFahrenheitwithoutexplicitconversion.
6.2.4Applicablelanguagecharacteristics
Thisvulnerabilityisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Languagesthatsupportmultipletypesandallowconversionsbetweentypes.
6.2.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Takeadvantageofanyfacilityofferedbytheprogramminglanguagetodeclaredistincttypesanduseanymechanismprovidedbythelanguageprocessorandrelatedtoolstocheckfororenforcetypecompatibility.
• Useavailablelanguageandtoolsfacilitiestoprecludeordetecttheoccurrenceofimplicittypeconversions,suchasthoseinmixedtypearithmetic.Ifitisnotpossible,usehumanreviewtoassistinsearchingforimplicitconversions.
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
WG23/N0720
24 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
• Avoidexplicittypeconversionofdatavaluesexceptwhenthereisnoalternative.Documentsuchoccurrencessothatthejustificationismadeavailabletomaintainers.
• Usethemostrestricteddatatypethatsufficestoaccomplishthejob.Forexample,useanenumerationtypetoselectfromalimitedsetofchoices(suchas,aswitchstatementorthediscriminantofauniontype)ratherthanamoregeneraltype,suchasinteger.Thiswillmakeitpossiblefortoolingtocheckifallpossiblechoiceshavebeencovered.
• Treateverycompiler,tool,orrun-timediagnosticconcerningtypecompatibilityasaseriousissue.Donotresolvetheproblembymodifyingthecodetoincludeanexplicitconversion,withoutfurtheranalysis;insteadexaminetheunderlyingdesigntodetermineifthetypeerrorisasymptomofadeeperproblem.
• Neverignoreinstancesofimplicittypeconversion;iftheconversionisnecessary,changeittoanexplicitconversionanddocumenttherationaleforusebymaintainers.
• Analyzetheproblemtobesolvedtolearnthemagnitudesand/ortheprecisionsofthequantitiesneededasauxiliaryvariables,partialresultsandfinalresults.
6.2.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Languagespecifiersshouldstandardizeonacommon,uniformterminologytodescribetheirtypesystemssothatprogrammersexperiencedinotherlanguagescanreliablylearnthetypesystemofalanguagethatisnewtothem.
• Provideamechanismforselectingdatatypeswithsufficientcapabilityfortheproblemathand.• Provideawayforthecomputationtodeterminethelimitsofthedatatypesactuallyselected.• Languageimplementersshouldconsiderprovidingcompilerswitchesorothertoolstoprovidethehighest
possibledegreeofcheckingfortypeerrors.
6.3Bitrepresentations[STR]
6.3.1Descriptionofapplicationvulnerability
Interfacingwithhardware,othersystemsandprotocolsoftenrequiresaccesstooneormorebitsinasinglecomputerword,oraccesstobitfieldsthatmaycrosscomputerwordsforthemachineinquestion.Mistakescanbemadeastowhatbitsaretobeaccessedbecauseofthe“endianness”oftheprocessor(seebelow)orbecauseofmiscalculations.Accesstothosespecificbitsmayaffectsurroundingbitsinwaysthatcompromisetheirintegrity.Thiscanresultinthewronginformationbeingreadfromhardware,incorrectdataorcommandsbeinggiven,orinformationbeingmangled,whichcanresultinarbitraryeffectsoncomponentsattachedtothesystem.
6.3.2Crossreference
JSFAVRules147,154and155MISRAC2012:1.1,6.1,6.2,and10.1MISRAC++2008:5-0-21,5-2-4to5-2-9,and9-5-1CERTCguidelines:EXP38-C,INT00-C,INT07-C,INT12-C,INT13-C,andINT14-CAdaQualityandStyleGuide:7.6.1through7.6.9,and7.3.1
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 25
6.3.3Mechanismoffailure
Computerlanguagesfrequentlyprovideavarietyofsizesforintegervariables.Languagesmaysupportshort,integer,long,andevenbigintegers.Interfacingwithprotocols,devicedrivers,embeddedsystems,lowlevelgraphicsorotherexternalconstructsmayrequireeachbitorsetofbitstohaveaparticularmeaning.Thosebitsetsmayormaynotcoincidewiththesizessupportedbyaparticularlanguageimplementation.Whentheydonot,itiscommonpracticetopackallofthebitsintooneword.Maskingandshiftingofthewordusingpowersoftwotopickoutindividualbitsorusingsumsofpowersof2topickoutsubsetsofbits(forexample,using28=22+23+24tocreatethemask11100andthenshifting2bits)providesawayofextractingthosebits.Knowledgeoftheunderlyingbitstorageisusuallynotnecessarytoaccomplishsimpleextractionssuchasthese.Problemscanarisewhenprogrammersmixtheirtechniquestoreferencethebitsoroutputthebits.Problemscanarisewhenprogrammersmixarithmeticandlogicaloperationstoreferencethebitsoroutputthebits.Thestorageorderingofthebitsmaynotbewhattheprogrammerexpects.
Packingofbitsinanintegerisnotinherentlyproblematic.However,anunderstandingoftheintricaciesofbitlevelprogrammingmustbeknown.Somecomputersorotherdevicesstorethebitsleft-to-rightwhileothersstorethemright-to-left.Thekindofstoragecancauseproblemswheninterfacingwithexternaldevicesthatexpectthebitsintheoppositeorder.Oneproblemariseswhenassumptionsaremadewheninterfacingwithexternalconstructsandtheorderingofthebitsorwordsarenotthesameasthereceivingentity.Programmersmayinadvertentlyusethesignbitinabitfieldandthenmaynotbeawarethatanarithmeticshift(signextension)isbeingperformedwhenrightshiftingcausingthesignbittobeextendedintootherfields.Alternatively,aleftshiftcancausethesignbittobeone.Bitmanipulationscanalsobeproblematicwhenthemanipulationsaredoneonbinaryencodedrecordsthatspanmultiplewords.Thestorageandorderingofthebitsmustbeconsideredwhendoingbit-wiseoperationsacrossmultiplewordsasbytesmaybestoredinbig-endianorlittle-endianformat.
6.3.4Applicablelanguagecharacteristics
Thisvulnerabilitydescriptionisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Languagesthatallowbitmanipulations.
6.3.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Explicitlydocumentanyrelianceonbitorderingsuchasexplicitbitpatterns,shifts,orbitnumbers.• Understandthewaybitorderingisdoneonthehostsystemandonthesystemswithwhichthebit
manipulationswillbeinterfaced.• Wherethelanguagesupportsit,usebitfieldsinpreferencetobinary,octal,orhexrepresentations.• Avoidbitoperationsonsignedoperands.• Localizeanddocumentthecodeassociatedwithexplicitmanipulationofbitsandbitfields.• Usestaticanalysistoolsthatidentifyandreportrelianceuponbitorderingorbitrepresentation.
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
WG23/N0720
26 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
6.3.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Forlanguagesthatarecommonlyusedforbitmanipulations,anAPI(ApplicationProgrammingInterface)forbitmanipulationsthatisindependentofwordsizeandmachineinstructionsetshouldbedefinedandstandardized.
6.4Floating-pointarithmetic[PLF]
6.4.1Descriptionofapplicationvulnerability
Mostrealnumberscannotberepresentedexactlyinacomputer.Torepresentrealnumbers,mostcomputersuseIEC60559Informationtechnology--MicroprocessorSystems--Floating-Pointarithmetic.IfIEC60559isnotfollowed,thenthebitrepresentationforafloating-pointnumbercanvaryfromcompilertocompilerandondifferentplatforms,however,relyingonaparticularrepresentationcancauseproblemswhenadifferentcompilerisusedorthecodeisreusedonanotherplatform.Regardlessoftherepresentation,manyrealnumberscanonlybeapproximatedsincerepresentingtherealnumberusingabinaryrepresentationmaywellrequireanendlesslyrepeatingstringofbitsormorebinarydigitsthanareavailableforrepresentation.Thereforeitshouldbeassumedthatafloating-pointnumberisonlyanapproximation,eventhoughitmaybeanextremelygoodone.Floating-pointrepresentationofarealnumberoraconversiontofloating-pointcancausesurprisingresultsandunexpectedconsequencestothoseunaccustomedtotheidiosyncrasiesoffloating-pointarithmetic.
Manyalgorithmsthatusefloatingpointcanhaveanomalousbehaviourwhenusedwithcertainvalues.Themostcommonresultsareerroneousresultsoralgorithmsthatneverterminateforcertainsegmentsofthenumericdomain,orforisolatedvalues.Thosewithouttrainingorexperienceinnumericalanalysismaynotbeawareofwhichalgorithms,or,foraparticularalgorithm,ofwhichdomainvaluesshouldbethefocusofattention.
Insomehardware,precisionforintermediatefloatingpointcalculationsmaybedifferentthanthatsuggestedbythedatatype,causingdifferentroundingresultswhenmovingtostandardprecisionmodes.
6.4.2Crossreference
JSFAVRules:146,147,184,197,and202MISRAC2012:1.1and14.1MISRAC++2008:0-4-3,3-9-3,and6-2-2CERTCguidelines:FLP00-C,FP01-C,FLP02-CandFLP30-CAdaQualityandStyleGuide:5.5.6and7.2.1through7.2.8
6.4.3Mechanismoffailure
Floating-pointnumbersaregenerallyonlyanapproximationoftheactualvalue.Expressedinbase10world,thevalueof1/3is0.333333…Thesametypeofsituationoccursinthebinaryworld,butthenumbersthatcanberepresentedwithalimitednumberofdigitsinbase10,suchas1/10=0.1becomeendlesslyrepeatingsequencesinthebinaryworld.So1/10representedasabinarynumberis:
0.0001100110011001100110011001100110011001100110011…
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 27
Whichis0*1/2+0*1/4+0*1/8+1*1/16+1*1/32+0*1/64…andnomatterhowmanydigitsareused,therepresentationwillstillonlybeanapproximationof1/10.Thereforewhenadding1/10tentimes,thefinalresultmayormaynotbeexactly1.
Accumulatingfloatingpointvaluesthroughtherepeatedadditionofvalues,particularlyrelativelysmallvalues,canprovideunexpectedresults.Usinganaccumulatedvaluetoterminatealoopcanresultinanunexpectednumberofiterations.Roundingandtruncationcancausetestsoffloating-pointnumbersagainstothervaluestoyieldunexpectedresults.Anothercauseoffloatingpointerrorsisrelianceuponcomparisonsoffloatingpointvaluesorthecomparisonofafloatingpointvaluewithzero.Testsofequalityorinequalitycanvaryduetoroundingortruncationerrors,whichmaypropagatefarfromtheoperationoforigin.Evencomparisonsofconstantsmayfailwhenadifferentroundingmodewasemployedbythecompilerandbytheapplication.Differencesinmagnitudesoffloating-pointnumberscanresultinnochangeofaverylargefloating-pointnumberwhenarelativelysmallnumberisaddedtoorsubtractedfromit.
Manipulatingbitsinfloating-pointnumbersisalsoveryimplementationdependentiftheimplementationisnotIEC60559compliantorintheinterpretationofNAN’s.Typicallyspecialrepresentationsarespecifiedforpositiveandnegativezero;infinityandsubnormalnumbersveryclosetozero.Relyingonaparticularbitrepresentationisinherentlyproblematic,especiallywhenanewcompilerisintroducedorthecodeisreusedonanotherplatform.Theuncertaintiesarisingfromfloating-pointcanbedividedintouncertaintyabouttheactualbitrepresentationofagivenvalue(suchas,big-endianorlittle-endian)andtheuncertaintyarisingfromtheroundingofarithmeticoperations(forexample,theaccumulationoferrorswhenimprecisefloating-pointvaluesareusedasloopindices).
Notethatmostfloatingpointimplementationsarebinary.DecimalfloatingpointnumbersareavailableonsomehardwareandhasbeenstandardizedinISO/IEC/IEEE60559:2011(IEEE754:2008),butbeawarewhatprecisionguaranteesyourprogramminglanguagemakes.Ingeneral,fixedpointarithmeticmaybeabettersolutiontocommonproblemsinvolvingdecimalfractions(suchasfinancialcalculations).
Implementations(libraries)fordifferentprecisionsareoftenimplementedinthehighestprecision.Thiscanyielddifferentresultsinalgorithmssuchasexponentiationthaniftheprogrammerhadperformedthecalculationdirectly.
Floatingpointsystemshavemorethanoneroundingmode.Roundtothenearestevennumberisthedefaultforalmostallimplementations.Repeatedlyroundingiterativecalculationstowardszeroorawayfromzerocanresultinalossofprecision,andcancauseunexpectedoutcome.
Floatingpointminandmaxcanreturnanarbitrarysignwhenbothparametersarezero(andofdifferentsign).Teststhatusethesignofanumberratherthanitsrelationshiptozerocanreturnunexpectedresults.
6.4.4Applicablelanguagecharacteristics
Thisvulnerabilitydescriptionisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Alllanguageswithfloating-pointvariablescanbesubjecttoroundingortruncationerrors.
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
WG23/N0720
28 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
6.4.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Unlesstheprogram’suseoffloating-pointistrivial,obtaintheassistanceofanexpertinnumericalanalysisandinthehardwarepropertiesofyoursystemtocheckthestabilityandaccuracyofthealgorithmemployed.
• Donotuseafloating-pointexpressioninaBooleantestforequalityunlessitcanbeshownthatthelogicimplementedbytheequalitytestcannotbeaffectedbypriorroundingerrors.Instead,usecodingthatdeterminesthedifferencebetweenthetwovaluestodeterminewhetherthedifferenceisacceptablysmallenoughsothattwovaluescanbeconsideredequal.Notethatifthetwovaluesareverylarge,the“smallenough”differencecanbeaverylargenumber.
• VerifythattheunderlyingimplementationisIEC60559(IEEE754)orthatitincludessubnormalnumbers(fixedpointnumbersthatareclosetozero).Beawarethatimplementationsthatdonothavethiscapabilitycanunderflowtozeroinunexpectedsituations.
• Beawarethatinfinities,NANandsubnormalnumbersmaybepossibleandgivespecialconsiderationtoteststhatcheckforthoseconditionsbeforeusingtheminfloatingpointcalculations.
• Uselibraryfunctionswithknownnumericalcharacteristics.Avoidtheuseofafloating-pointvariableasaloopcounter.Ifitisnecessarytouseafloating-pointvalueforloopcontrol,useinequalitytodeterminetheloopcontrol(thatis,<,<=,>or>=).
• Understandthefloating-pointformatusedtorepresentthefloating-pointnumbers.Thiswillprovidesomeunderstandingoftheunderlyingidiosyncrasiesoffloating-pointarithmetic.
• Avoidmanipulatingthebitrepresentationofafloating-pointnumber.Preferbuilt-inlanguageoperatorsandfunctionsthataredesignedtoextractthemantissa,exponentorsign.
• Donotusefloating-pointforexactvaluessuchasmonetaryamounts.Usefloating-pointonlywhennecessarysuchasforfundamentallyinexactvaluessuchasmeasurementsorvaluesofdiversemagnitudes.Considertheuseoffixedpointarithmetic/librariesordecimalfloatingpointwhenappropriate.
• Useknownprecisionmodestoimplementalgorithms• AvoidchangingtheroundingmodefromRNE(roundnearesteven)• AvoidrelianceonthesignofthefloatingpointMinandMaxoperationswhenbothnumbersarezero.• Whenadding(orsubtracting)sequencesofnumbers,sortandadd(orsubtract)themfromsmallestto
largestinabsolutevaluetoavoidlossofprecision.
6.4.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• LanguagesthatdonotalreadyadheretooronlyadheretoasubsetofIEC60559[7]shouldconsideradheringcompletelytothestandard.Examplesofstandardizationthatshouldbeconsidered:
• Languagesshouldconsiderprovidingameanstogeneratediagnosticsforcodethatattemptstotest
equalityoftwofloatingpointvalues.
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 29
• LanguagesshouldconsiderstandardizingtheirdatatypetoISO/IEC10967-1:2012andISO/IEC10967-2:2001.
6.5Enumeratorissues[CCB]
6.5.1Descriptionofapplicationvulnerability
Enumerationsareafinitelistofnamedentitiesthatcontainafixedmappingfromasetofnamestoasetofintegralvalues(calledtherepresentation)andanorderbetweenthemembersoftheset.Insomelanguagestherearenootheroperationsavailableexceptorder,equality,first,last,previous,andnext;inothersthefullunderlyingrepresentationoperatorsareavailable,suchasinteger“+”and“-”andbit-wiseoperations.
Mostlanguagesthatprovideenumerationtypesalsoprovidemechanismstosetnon-defaultrepresentations.Ifthesemechanismsdonotenforcewhole-typeoperationsandcheckforconflictsthensomemembersofthesetmaynotbeproperlyspecifiedormayhavethewrongmappings.Ifthevalue-settingmechanismsarepositionalonly,thenthereisariskthatimpropercountsorchangesinrelativeorderwillresultinanincorrectmapping.
Forarraysindexedbyenumerationswithnon-defaultrepresentations,thereisariskofstructureswithholes,andifthoseindexescanbemanipulatednumerically,thereisariskofout-of-boundaccessesofthesearrays.
Mostoftheseerrorscanbereadilydetectedbystaticanalysistoolswithappropriatecodingstandards,restrictionsandannotations.Similarlymismatchesinenumerationvaluespecificationcanbedetectedstatically.Withoutsuchrules,errorsintheuseofenumerationtypesarecomputationallyhardtodetectstaticallyaswellasbeingdifficulttodetectbyhumanreview.
6.5.2Crossreference
JSFAVRule:MISRAC2012:8.12,9.2,and9.3MISRAC++2008:8-5-3CERTCguidelines:INT09-CHolzmannrule6AdaQualityandStyleGuide:3.4.2
6.5.3Mechanismoffailure
Asaprogramisdevelopedandmaintainedthelistofitemsinanenumerationoftenchangesinthreebasicways:newelementsareaddedtothelist;orderbetweenthemembersofthesetoftenchanges;andrepresentation(themapofvaluesoftheitems)change.Expressionsthatdependonthefullsetorspecificrelationshipsbetweenelementsofthesetcancreatevalueerrorsthatcouldresultinwrongresultsorinunboundedbehavioursifusedasarrayindices.
Improperlymappedrepresentationscanresultinsomeenumerationvaluesbeingunreachable,ormaycreate“holes”intherepresentationwherevaluesthatcannotbedefinedarepropagated.
Deleted: 1994
Deleted:
Deleted:
Deleted:
Deleted:
WG23/N0720
30 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
Ifarraysareindexedbyenumerationscontainingnon-defaultrepresentations,someimplementationsmayleavespaceforvaluesthatareunreachableusingtheenumeration,withapossibilityofunnecessarilylargememoryallocationsorawaytopassinformationundetected(hiddenchannel).
Whenenumeratorsaresetandinitializedexplicitlyandthelanguagepermitsincompleteinitializers,thenchangestotheorderofenumeratorsortheadditionordeletionofenumeratorscanresultinthewrongvaluesbeingassignedordefaultvaluesbeingassignedimproperly.Subsequentindexingcanresultininvalidaccessesandpossiblyunboundedbehaviours.
6.5.4ApplicablelanguageCharacteristics
Thisvulnerabilitydescriptionisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Languagesthatpermitincompletemappingsbetweenenumeratorspecificationandvalueassignment,orthatprovideapositional-onlymappingrequireadditionalstaticanalysistoolsandannotationstohelpidentifythecompletemappingofeveryliteraltoitsvalue.
• Languagesthatprovideatrivialmappingtoatypesuchasintegerrequireadditionalstaticanalysistoolstopreventmixedtypeerrors.Theyalsocannotpreventinvalidvaluesfrombeingplacedintovariablesofsuchenumeratortypes.Forexample:
enum Directions {back, forward, stop}; enum Directions a = forward, b = stop, c = a + b;
Inthisexample,cmayhaveavaluenotdefinedbytheenumeration,andanyfurtheruseasthatenumerationwillleadtoerroneousresults.
• Somelanguagesprovidenoenumerationcapability,leavingittotheprogrammertodefinenamedconstantstorepresentthevaluesandranges.
6.5.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Usestaticanalysistoolsthatwilldetectinappropriateuseofenumerators,suchasusingthemasintegersorbitmaps,andthatdetectenumerationdefinitionexpressionsthatareincompleteorincorrect.Forlanguageswithacompleteenumerationabstractionthisisthecompiler.
• Incodethatperformsdifferentcomputationsdependingonthevalueofanenumeration,ensurethateachpossibleenumerationvalueiscovered,orprovideadefaultthatraisesanerrororexception.
• Useanenumeratedtypetoselectfromalimitedsetofchoicesandusetoolsthatstaticallydetectomissionsofpossiblevaluesinanenumeration
6.5.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Languagesthatcurrentlypermitarithmeticandlogicaloperationsonenumerationtypescouldprovideamechanismtobansuchoperationsprogram-wide.
Deleted:
Deleted:
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 31
• Languagesthatprovideautomaticdefaultsorthatdonotenforcestaticmatchingbetweenenumeratordefinitionsandinitializationexpressionscouldprovideamechanismtoenforcesuchmatching.
6.6Conversionerrors[FLC]
6.6.1Descriptionofapplicationvulnerability
Certaincontextsinvariouslanguagesmayrequireexactmatcheswithrespecttotypes[32]:
aVar := anExpression value1 + value2 foo(arg1, arg2, arg3, … , argN)
Typeconversionseekstofollowtheseexactmatchruleswhileallowingprogrammerssomeflexibilityinusingvaluessuchas:structurally-equivalenttypesinaname-equivalentlanguage,typeswhosevaluerangesmaybedistinctbutintersect(forexample,subranges),anddistincttypeswithsensible/meaningfulcorrespondingvalues(forexample,integersandfloats).
Conversionscanleadtoalossofdata,ifthetargetrepresentationisnotcapableofrepresentingtheoriginalvalue.Forexample,convertingfromanintegertypetoasmallerintegertypecanresultintruncationiftheoriginalvaluecannotberepresentedinthesmallersizeandconvertingafloatingpointtoanintegercanresultinalossofprecisionoranout-of-rangevalue.Convertingfromacharactertypetoasmallercharactertypecanresultinthemisrepresentationofthecharacter.
Type-conversionerrorscanleadtoerroneousdatabeinggenerated,algorithmsthatfailtoterminate,arraybounds-errors,orarbitraryprogramexecution.
Seealso6.44Polymorphicvariables[BKK]
forupcastingerrors.
6.6.2Crossreference
CWE:192.IntegerCoercionErrorMISRAC2012:7.2,10.1,10.3,10.4,10.6-10.8,and11.1-11.8MISRAC++2008:2-13-3,5-0-3,5-0-4,5-0-5,5-0-6,5-0-7,5-0-8,5-0-9,5-0-10,5-2-5,5-2-9,and5-3-2CERTCguidelines:FLP34-C,INT02-C,INT08-C,INT31-C,andINT35-C
6.6.3Mechanismoffailure
Conversionerrorsresultindataintegrityissues,andmayalsoresultinanumberofsafetyandsecurityvulnerabilities.
Whentheconversionresultsinnochangeinrepresentationbutachangeinvalueforthenewtype,thismayresultinavaluethatisnotexpressibleinthenewtype,orthathasadramaticallydifferentorderormeaning.Onesuchsituationisthechangeofsignbetweentheoriginanddestination(negative->positiveorpositive->negative),whichchangestherelativeorderofmembersofthetwotypesandcouldresultinmemoryaccess
Deleted:
Deleted:
Deleted: 6.44Polymorphicvariables[BKK]
Deleted:
WG23/N0720
32 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
failuresifthevaluesareusedinaddresscalculations.Numerictypeconversionscanbelessobviousbecausesomelanguageswillsilentlyconvertbetweennumerictypes.
Vulnerabilitiestypicallyoccurwhenappropriaterangecheckingisnotperformed,andunanticipatedvaluesareencountered.Thesecanresultinsafetyissues,forexample,whentheAriane5launcherfailureoccurredduetoanimproperlyhandledconversionerrorresultingintheprocessorbeingshutdown[29].
Conversionerrorscanalsoresultinsecurityissues.Anattackermayinputaparticularnumericvaluetoexploitaflawintheprogramlogic.Theresultingerroneousvaluemaythenbeusedasanarrayindex,aloopiterator,alength,asize,statedata,orinsomeothersecurity-criticalmanner.Forexample,atruncatedintegervaluemaybeusedtoallocatememory,whiletheactuallengthisusedtocopyinformationtothenewlyallocatedmemory,resultinginabufferoverflow[30].
Numerictype-conversionerrorscanleadtoundefinedstatesofexecutionresultingininfiniteloopsorcrashes.Insomecases,integertype-conversionerrorscanleadtoexploitablebufferoverflowconditions,resultingintheexecutionofarbitrarycode.Integertype-conversionerrorsresultinanincorrectvaluebeingstoredforthevariableinquestion.
6.6.4Applicablelanguagecharacteristics
Thisvulnerabilitydescriptionisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Languagesthatperformimplicittypeconversion(coercion).• Languagesthatpermitconversionsbetweensubtypesofapolymorphictype.See6.44Polymorphic
Variables[BKK]upcastsanddowncasts.• Weaklytypedlanguagesthatdonotstrictlyenforcetyperules.• Languagesthatsupportlogical,arithmetic,orcircularshiftsonintegervalues.• Languagesthatdonotgenerateexceptionsonproblematicconversions.
6.6.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Ifrangecheckingisnotprovidedbythelanguage,useexplicitrangechecks,typechecksorvaluecheckstovalidatethecorrectnessofallvaluesoriginatingfromasourcethatisnottrusted.However,itisdifficulttoguaranteethatmultipleinputvariablescannotbemanipulatedtocauseanerrortooccurinsomeoperationsomewhereinaprogram[30].
• Alternatively,useexplicitrangecheckstoprotecteachoperation.Becauseofthelargenumberofintegeroperationsthataresusceptibletotheseproblemsandthenumberofchecksrequiredtopreventordetectexceptionalconditions,thisapproachcanbeprohibitivelylaborintensiveandexpensivetoimplement.
• Choosealanguagethatgeneratesexceptionsonerroneousdataconversions.• Designobjectsandprogramflowsuchthatmultipleorcomplexexplicittypeconversionsareunnecessary.
Understandanyexplicittypeconversionthatyoumustusetoreducetheplausibilityoferrorinuse.• Usestaticanalysistoolstoidentifywhetherornotunacceptableconversionswilloccur,totheextent
possible.
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Comment [SM1]: Linksarenotobvious.Findallofthemandcolourthem.
Deleted:
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 33
• Avoidtheuseof“plausiblebutwrong”defaultvalueswhenacalculationcannotbecompletedcorrectly.Eithergenerateanerrororproduceavaluethatisoutofrangeandiscertaintobedetected.Takecarethatanyerrorprocessingdoesnotleadtoadenial-of-servicevulnerability.
6.6.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Languagesshouldprovidemechanismstopreventprogrammingerrorsduetoconversions.• Languagesshouldconsidermakingalltype-conversionsexplicitoratleastgeneratingwarningsforimplicit
conversionswherelossofdatamightoccur.
6.7Stringtermination[CJM]
6.7.1Descriptionofapplicationvulnerability
Someprogramminglanguagesuseaterminationcharactertoindicatetheendofastring.Relyingontheoccurrenceofthestringterminationcharacterwithoutverificationcanleadtoeitherexploitationorunexpectedbehaviour.
6.7.2Crossreference
CWE:170.ImproperNullTermination
CERTCguidelines:STR03-C,STR31-C,STR32-C,andSTR36-C
6.7.3Mechanismoffailure
Stringterminationerrorsoccurwhentheterminationcharacterissolelyreliedupontostopprocessingonthestringandtheterminationcharacterisnotpresent.Continuedprocessingonthestringcancauseanerrororpotentiallybeexploitedasabufferoverflow.Thismayoccurasaresultofaprogrammermakinganassumptionthatastringthatispassedasinputorgeneratedbyalibrarycontainsastringterminationcharacterwhenitdoesnot.
Programmersmayforgettoallocatespaceforthestringterminationcharacterandexpecttobeabletostoreannlengthcharacterstringinanarraythatisncharacterslong.Doingsomayworkinsomeinstancesdependingonwhatisstoredafterthearrayinmemory,butitmayfailorbeexploitedatsomepoint.
6.7.4Applicablelanguagecharacteristics
Thisvulnerabilitydescriptionisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Languagesthatuseaterminationcharactertoindicatetheendofastring.• Languagesthatdonotdoboundscheckingwhenaccessingastringorarray.
6.7.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
WG23/N0720
34 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
• Donotrelysolelyonthestringterminationcharacter.• Uselibrarycallsthatdonotrelyonstringterminationcharacterssuchasstrncpyinsteadofstrcpyin
thestandardClibrary.• Usestaticanalysistoolsthatdetecterrorsinstringtermination.
6.7.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Eliminatinglibrarycallsthatmakeassumptionsaboutstringterminationcharacters.• Checkingboundswhenanarrayorstringisaccessed,CBoundsCheckingLibrary[13].• Specifyingastringconstructthatdoesnotneedastringterminationcharacter.
6.8Bufferboundaryviolation(bufferoverflow)[HCB]
6.8.1Descriptionofapplicationvulnerability
Abufferboundaryviolationariseswhen,duetouncheckedarrayindexingoruncheckedarraycopying,storageoutsidethebufferisaccessed.Usuallyboundaryviolationsdescribethesituationwheresuchstorageisthenwritten.Dependingonwherethebufferislocated,logicallyunrelatedportionsofthestackortheheapcouldbemodifiedmaliciouslyorunintentionally.Usually,bufferboundaryviolationsareaccessestocontiguousmemorybeyondeitherendofthebufferdata,accessingbeforethebeginningorbeyondtheendofthebufferdataisequallypossible,dangerousandmaliciouslyexploitable.
6.8.2Crossreference
CWE:120.BuffercopywithoutCheckingSizeofInput(‘ClassicBufferOverflow’)122.Heap-basedBufferOverflow124.BoundaryBeginningViolation(‘BufferUnderwrite’)129.UncheckedArrayIndexing131.IncorrectCalculationofBufferSize787.Out-of-boundsWrite805.BufferAccesswithIncorrectLengthValue
JSFAVRule:15and25MISRAC2012:21.1MISRAC++2008:5-0-15to5-0-18CERTCguidelines:ARR30-C,ARR32-C,ARR33-C,ARR38-C,MEM35-CandSTR31-C
6.8.3Mechanismoffailure
Theprogramstatementsthatcausebufferboundaryviolationsareoftendifficulttofind.
Thereareseveralkindsoffailures(inallcasesanexceptionmayberaisediftheaccessedlocationisoutsideofsomepermittedrangeoftherun-timeenvironment):
Deleted:
Deleted:
Deleted:
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 35
• Areadaccesswillreturnavaluethathasnorelationshiptotheintendedvalue,suchas,thevalueofanothervariableoruninitializedstorage.
• Anout-of-boundsreadaccessmaybeusedtoobtaininformationthatisintendedtobeconfidential.• Awriteaccesswillnotresultintheintendedvaluebeingupdatedandmayresultinthevalueofan
unrelatedobject(thathappenstoexistatthegivenstoragelocation)beingmodified,includingthepossibilityofchangesinexternaldevicesresultingfromthememorylocationbeinghardware-mapped.
• Whenanarrayhasbeenallocatedstorageonthestackanout-of-boundswriteaccessmaymodifyinternalruntimehousekeepinginformation(forexample,afunction'sreturnaddress)whichmightchangeaprogram’scontrolflow.
• Aninadvertentormaliciousoverwriteoffunctionpointersthatmaybeinmemory,causingthemtopointtoanunexpectedlocationortheattacker'scode.Eveninapplicationsthatdonotexplicitlyusefunctionpointers,therun-timewillusuallystorepointerstofunctionsinmemory.Forexample,objectmethodsinobject-orientedlanguagesaregenerallyimplementedusingfunctionpointersinadatastructureorstructuresthatarekeptinmemory.Theconsequenceofabufferboundaryviolationcanbetargetedtocausearbitrarycodeexecution;thisvulnerabilitymaybeusedtosubvertanysecurityservice.
6.8.4Applicablelanguagecharacteristics
Thisvulnerabilitydescriptionisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Languagesthatdonotdetectandpreventanarraybeingaccessedoutsideofitsdeclaredbounds(eitherbymeansofanindexorbypointer0F
1).• Languagesthatdonotautomaticallyallocatestoragewhenaccessinganarrayelementforwhichstorage
hasnotalreadybeenallocated.• Languagesthatprovideboundscheckingbutpermitthechecktobesuppressed.• Languagesthatallowacopyormoveoperationwithoutanautomaticlengthcheckensuringthatsource
andtargetlocationsareofatleastthesamesize.Thedestinationtargetcanbelargerthanthesourcebeingcopied.
6.8.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Useofimplementation-providedfunctionalitytoautomaticallycheckarrayelementaccessesandpreventout-of-boundsaccesses.
• Useofstaticanalysistoverifythatallarrayaccessesarewithinthepermittedbounds.Suchanalysismayrequirethatsourcecodecontaincertainkindsofinformation,suchas,thattheboundsofalldeclaredarraysbeexplicitlyspecified,orthatpre-andpost-conditionsbespecified.
• Performsanitychecksonallcalculatedexpressionsusedasanarrayindexorforpointerarithmetic.• Ascertainwhetherornotthecompilercaninsertboundscheckswhilestillmeetingtheperformance
requirementsoftheprogramanddirectthecompilertoinsertsuchcheckswhereappropriate
1Usingthephysicalmemoryaddresstoaccessthememorylocation.
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
WG23/N0720
36 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
Someguidelinedocumentsrecommendonlyusingvariableshavinganunsigneddatatypewhenindexinganarray,onthebasisthatanunsigneddatatypecanneverbenegative.Thisrecommendationsimplyconvertsanindexingunderflowtoanindexingoverflowbecausethevalueofthevariablewillwraptoalargepositivevalueratherthananegativeone.Alsosomelanguagessupportarrayswhoselowerboundisgreaterthanzero,soanindexcanbepositiveandbelessthanthelowerbound.Somelanguagessupportzero-sizedarrays,soanyreferencetoalocationwithinsuchanarrayisinvalid.
Inthepasttheimplementationofarrayboundcheckinghassometimesincurredwhathasbeenconsideredtobeahighruntimeoverhead(oftenbecauseunnecessarycheckswereperformed).Itisnowpracticalfortranslatorstoperformsophisticatedanalysisthatsignificantlyreducestheruntimeoverhead(becauseruntimechecksareonlymadewhenitcannotbeshownstaticallythatnoboundviolationscanoccur).
6.8.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Languagesshouldprovidesafecopyingofarraysasbuilt-inoperation.• Languagesshouldconsideronlyprovidingarraycopyroutinesinlibrariesthatperformchecksonthe
parameterstoensurethatnobufferoverruncanoccur.• Languagesshouldperformautomaticboundscheckingonaccessestoarrayelements,unlessthecompiler
canstaticallydeterminethatthecheckisunnecessary.Thiscapabilitymayneedtobeoptionalforperformancereasons.
• Languagesthatusepointertypesshouldconsiderspecifyingastandardizedfeatureforapointertypethatwouldenablearrayboundschecking.
6.9Uncheckedarrayindexing[XYZ]
6.9.1Descriptionofapplicationvulnerability
Uncheckedarrayindexingoccurswhenavalueisusedasanindexintoanarraywithoutcheckingthatitfallswithintheacceptableindexrange.
6.9.2Crossreference
CWE:129.UncheckedArrayIndexing676.UseofPotentiallyDangerousFunction
JSFAVRules:164and15MISRAC2012:21.1MISRAC++2008:5-0-15to5-0-18CERTCguidelines:ARR30-C,ARR32-C,ARR33-C,andARR38-CAdaQualityandStyleGuide:5.5.1,5.5.2,7.6.7,and7.6.8
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 37
6.9.3Mechanismoffailure
Asinglefaultcouldallowbothanoverflowandunderflowofthearrayindex.Anindexoverflowexploitmightusebufferoverflowtechniques,butthiscanoftenbeexploitedwithouthavingtoprovide"largeinputs."Arrayindexoverflowscanalsotriggerout-of-boundsreadoperations,oroperationsonthewrongobjects;thatis,"bufferoverflows"arenotalwaystheresult.Uncheckedarrayindexing,dependingonitsinstantiation,canberesponsibleforanynumberofrelatedissues.Mostprominentofthesepossibleflawsisthebufferoverflowcondition,withconsequencesrangingfromdenialofservice,anddatacorruption,toarbitrarycodeexecution.Themostcommonsituationleadingtouncheckedarrayindexingistheuseofloopindexvariablesasbufferindexes.Iftheendconditionfortheloopissubjecttoaflaw,theindexcangroworshrinkunbounded,thereforecausingabufferoverfloworunderflow.Anothercommonsituationleadingtothisconditionistheuseofafunction'sreturnvalue,ortheresultingvalueofacalculationdirectlyasanindexintoabuffer.Uncheckedarrayindexingcanresultinthecorruptionofrelevantmemoryandperhapsinstructions,leadtotheprogramhalting,ifthevaluesareoutsideofthevalidmemoryarea.Ifthememorycorruptedisdata,ratherthaninstructions,thesystemmightcontinuetofunctionwithimpropervalues.Ifthecorruptedmemorycanbeeffectivelycontrolled,itmaybepossibletoexecutearbitrarycode,aswithastandardbufferoverflow.
Languageimplementationsmightormightnotstaticallydetectoutofboundaccessandgenerateacompile-timediagnostic.Atruntimetheimplementationmightormightnotdetecttheout-of-boundaccessandprovideanotification.Thenotificationmightbetreatablebytheprogramoritmightnotbe.Accessesmightviolatetheboundsoftheentirearrayorviolatetheboundsofaparticularindex.Itispossiblethattheformerischeckedanddetectedbytheimplementationwhilethelatterisnot.Theinformationneededtodetecttheviolationmightormightnotbeavailabledependingonthecontextofuse.(Forexample,passinganarraytoasubroutineviaapointermightdeprivethesubroutineofinformationregardingthesizeofthearray.)
Asidefromboundschecking,somelanguageshavewaysofprotectingagainstout-of-boundsaccesses.Somelanguagesautomaticallyextendtheboundsofanarraytoaccommodateaccessesthatmightotherwisehavebeenbeyondthebounds.However,thismayormaynotmatchtheprogrammer'sintentandcanmaskerrors.Somelanguagesprovideforwholearrayoperationsthatmayobviatetheneedtoaccessindividualelementsthuspreventinguncheckedarrayaccesses.
6.9.4Applicablelanguagecharacteristics
Thisvulnerabilitydescriptionisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Languagesthatdonotautomaticallyboundscheckarrayaccesses.• Languagesthatdonotautomaticallyextendtheboundsofanarraytoaccommodatearrayaccesses.
6.9.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Includesanitycheckstoensurethevalidityofanyvaluesusedasindexvariables.• Thechoicecouldbemadetousealanguagethatisnotsusceptibletotheseissues.• Whenavailable,usewholearrayoperationswheneverpossible.
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted: Deleted:
Deleted:
Deleted:
Deleted:
Deleted: Deleted:
WG23/N0720
38 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
6.9.6Implicationsforlanguagedesigners
Infuturelanguagedesignandevolution,thefollowingitemsshouldbeconsidered:
• Providecompilerswitchesorothertoolstocheckthesizeandboundsofarraysandtheirextentsthatarestaticallydeterminable.
• Providingwholearrayoperationsthatmayobviatetheneedtoaccessindividualelements.• Languagesshouldconsiderthecapabilitytogenerateexceptionsorautomaticallyextendtheboundsof
anarraytoaccommodateaccessesthatmightotherwisehavebeenbeyondthebounds.
6.10Uncheckedarraycopying[XYW]
6.10.1Descriptionofapplicationvulnerability
Abufferoverflowoccurswhensomenumberofbytes(orotherunitsofstorage)iscopiedfromonebuffertoanotherandtheamountbeingcopiedisgreaterthanisallocatedforthedestinationbuffer.
6.10.2Crossreference
CWE:121.Stack-basedBufferOverflow
JSFAVRule:15MISRAC2012:21.1MISRAC++2008:5-0-15to5-0-18CERTCguidelines:ARR33-CandSTR31-CAdaQualityandStyleGuide:7.6.7and7.6.8
6.10.3Mechanismoffailure
Manylanguagesandsomethirdpartylibrariesprovidefunctionsthatefficientlycopythecontentsofoneareaofstoragetoanotherareaofstorage.Mostoftheselibrariesdonotperformanycheckstoensurethatthecopiedfrom/tostorageareaislargeenoughtoaccommodatetheamountofdatabeingcopied.
Theargumentstotheselibraryfunctionsincludetheaddressesofthecontentsofthetwostorageareasandthenumberofbytes(orsomeothermeasure)tocopy.Passingtheappropriatecombinationofincorrectstartaddressesornumberofbytestocopymakesitpossibletoreadorwriteoutsideofthestorageallocatedtothesource/destinationarea.Whenpassedincorrectparametersthelibraryfunctionperformsoneormoreuncheckedarrayindexaccesses,asdescribedin6.9Uncheckedarrayindexing[XYZ].
6.10.4Applicablelanguagecharacteristics
Thisvulnerabilitydescriptionisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Languagesthatcontainstandardlibraryfunctionsforperformingbulkcopyingofstorageareas.• Thesamerangeoflanguageshavingthecharacteristicslistedin6.9Uncheckedarrayindexing[XYZ].
Deleted:
Deleted: Deleted:
Formatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: Blue
Deleted: 6.9Uncheckedarrayindexing[XYZ]
Formatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: Blue
Deleted: 6.9Uncheckedarrayindexing[XYZ]6.9UncheckedArrayIndexing[XYZ]
Formatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: Blue
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 39
6.10.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Onlyuselibraryfunctionsthatperformchecksontheargumentstoensurenobufferoverruncanoccur(perhapsbywritingawrapperfortheStandardprovidedfunctions).PerformchecksontheargumentexpressionspriortocallingtheStandardlibraryfunctiontoensurethatnobufferoverrunwilloccur.
• Usestaticanalysistoverifythattheappropriatelibraryfunctionsareonlycalledwithargumentsthatdonotresultinabufferoverrun.Suchanalysismayrequirethatsourcecodecontaincertainkindsofinformation,forexample,thattheboundsofalldeclaredarraysbeexplicitlyspecified,orthatpre-andpost-conditionsbespecifiedasannotationsorlanguageconstructs.
6.10.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Languagesshouldconsideronlyprovidinglibrariesthatperformchecksontheparameterstoensurethatnobufferoverruncanoccur.
• Languagesshouldconsiderprovidingfullarrayassignment.
6.11Pointertypeconversions[HFC]
6.11.1Descriptionofapplicationvulnerability
Thecodeproducedforaccessviaadataorfunctionpointerrequiresthatthetypeofthepointerisappropriateforthedataorfunctionbeingaccessed.Otherwiseundefinedbehaviourcanoccur.Specifically,“accessviaadatapointer”isdefinedtobe“fetchorstoreindirectlythroughthatpointer”and“accessviaafunctionpointer”isdefinedtobe“invocationindirectlythroughthatpointer.”Thedetailedrequirementsforwhatismeantbythe“appropriate”typemayvaryamonglanguages.
Evenifthetypeofthepointerisappropriatefortheaccess,erroneouspointeroperationscanstillcauseafault.
6.11.2Crossreference
CWE:136.TypeErrors188.RelianceonData/MemoryLayout
JSFAVRules:182and183MISRAC2012:11.1-11.8MISRAC++2008:5-2-2to5-2-9CERTCguidelines:INT11-CandEXP36-AHatton13:PointercastsAdaQualityandStyleGuide:7.6.7and7.6.8
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
WG23/N0720
40 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
6.11.3Mechanismoffailure
Ifapointer’stypeisnotappropriateforthedataorfunctionbeingaccessed,datacanbecorruptedorprivacycanbebrokenbyinappropriatereadorwriteoperationusingtheindirectionprovidedbythepointervalue.Withasuitabletypedefinition,largeportionsofmemorycanbemaliciouslyoraccidentallymodifiedorread.Suchmodificationofdataobjectswillgenerallyleadtovaluefaultsoftheapplication.Modificationofcodeelementssuchasfunctionpointersorinternaldatastructuresforthesupportofobject-orientationcanaffectcontrolflow.Thiscanmakethecodesusceptibletotargetedattacksbycausinginvocationviaapointer-to-functionthathasbeenmanipulatedtopointtoanattacker’smaliciouscode.
6.11.4Applicablelanguagecharacteristics
Thisvulnerabilitydescriptionisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Pointers(and/orreferences)canbeconvertedtodifferentpointertypes.• Pointerstofunctionscanbeconvertedtopointerstodata.
6.11.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Treatthecompiler’spointer-conversionwarningsasseriouserrors.• Adoptprogrammingguidelines(preferablyaugmentedbystaticanalysis)thatrestrictpointerconversions.
Forexample,considertherulesitemizedabovefromJSFAV[15],CERTC[11],Hatton[18],orMISRAC[12].
• Useothermeansofassurancesuchasproofsofcorrectness,analysiswithtools,verificationtechniques,orothermethodstocheckthatpointerconversionsdonotleadtolaterundefinedbehaviour.
6.11.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Languagesshouldconsidercreatingamodethatprovidesaruntimecheckofthevalidityofallaccessedobjectsbeforetheobjectisread,writtenorexecuted.
6.12Pointerarithmetic[RVG]
6.12.1Descriptionofapplicationvulnerability
Usingpointerarithmeticincorrectlycanresultinaddressingarbitrarylocations,whichinturncancauseaprogramtobehaveinunexpectedways.
6.12.2Crossreference
JSFAVRule:215MISRAC2012:18.1-18.4MISRAC++2008:5-0-15to5-0-18CERTCguidelines:EXP08-C
Deleted:
Deleted:
Deleted:
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 41
6.12.3Mechanismoffailure
Pointerarithmeticusedincorrectlycanproduce:
• Addressingarbitrarymemorylocations,includingbufferunderflowandoverflow.• Arbitrarycodeexecution.• Addressingmemoryoutsidetherangeoftheprogram.
6.12.4Applicablelanguagecharacteristics
Thisvulnerabilitydescriptionisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Languagesthatallowpointerarithmetic.
6.12.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Avoidusingpointerarithmeticforaccessinganythingexceptcompositetypes.• Preferindexingforaccessingarrayelementsratherthanusingpointerarithmetic.• Limitpointerarithmeticcalculationstotheadditionandsubtractionofintegers.
6.12.6Implicationsforlanguagedesignandevolution
[None]
6.13Nullpointerdereference[XYH]
6.13.1Descriptionofapplicationvulnerability
Anull-pointerdereferencetakesplacewhenapointerwithavalueofNULLisusedasthoughitpointedtoavalidmemorylocation.Thisisaspecialcaseofaccessingstorageviaaninvalidpointer.
6.13.2Crossreference
CWE:476.NULLPointerDereference
JSFAVRule174CERTCguidelines:EXP34-CAdaQualityandStyleGuide:5.4.5
6.13.3Mechanismoffailure
WhenapointerwithavalueofNULLisusedasthoughitpointedtoavalidmemorylocation,thenanull-pointerdereferenceissaidtotakeplace.Thiscanresultinasegmentationfault,unhandledexception,oraccessingunanticipatedmemorylocations.
Deleted:
WG23/N0720
42 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
6.13.4Applicablelanguagecharacteristics
Thisvulnerabilitydescriptionisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Languagesthatpermittheuseofpointersandthatdonotcheckthevalidityofthelocationbeingaccessedpriortotheaccess.
• LanguagesthatallowtheuseofaNULLpointer.
6.13.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Beforedereferencingapointer,ensureitisnotequaltoNULL.
6.13.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• AlanguagefeaturethatwouldcheckapointervalueforNULLbeforeperforminganaccessshouldbeconsidered.
6.14Danglingreferencetoheap[XYK]
6.14.1Descriptionofapplicationvulnerability
Adanglingreferenceisareferencetoanobjectwhoselifetimehasendedduetoexplicitdeallocationorthestackframeinwhichtheobjectresidedhasbeenfreedduetoexitingthedynamicscope.Thememoryfortheobjectmaybereused;therefore,anyaccessthroughthedanglingreferencemayaffectanapparentlyarbitrarylocationofmemory,corruptingdataorcode.
Thisdescriptionconcernstheformercase,danglingreferencestotheheap.Thedescriptionofdanglingreferencestostackframesis[DCM].Inmanylanguagesreferencesarecalledpointers;theissuesareidentical.
Anotablespecialcaseofusingadanglingreferenceiscallingadeallocator,forexample,free(), twiceonthesamepointervalue.Sucha“DoubleFree”maycorruptinternaldatastructuresoftheheapadministration,leadingtofaultyapplicationbehaviour(suchasinfiniteloopswithintheallocator,returningthesamememoryrepeatedlyastheresultofdistinctsubsequentallocations,ordeallocatingmemorylegitimatelyallocatedtoanotherrequestsincethefirstfree()call,tonamebutafew),oritmayhavenoadverseeffectsatall.
Memorycorruptionthroughtheuseofadanglingreferenceisamongthemostdifficultoferrorstolocate.
Withsufficientknowledgeabouttheheapmanagementscheme(oftenprovidedbytheOS(OperatingSystem)orrun-timesystem),useofdanglingreferencesisanexploitablevulnerability,sincethedanglingreferenceprovidesamethodwithwhichtoreadandmodifyvaliddatainthedesignatedmemorylocationsafterfreedmemoryhasbeenre-allocatedbysubsequentallocations.
Deleted:
Deleted:
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 43
6.14.2Crossreference
CWE:415.DoubleFree(NotethatDoubleFree(415)isaspecialcaseofUseAfterFree(416))416.UseAfterFree
MISRAC2012:18.1-18.6MISRAC++2008:0-3-1,7-5-1,7-5-2,7-5-3,and18-4-1CERTCguidelines:MEM01-C,MEM30-C,andMEM31.CAdaQualityandStyleGuide:5.4.5,7.3.3,and7.6.6
6.14.3Mechanismoffailure
Thelifetimeofanobjectistheportionofprogramexecutionduringwhichstorageisguaranteedtobereservedforit.Anobjectexistsandretainsitslast-storedvaluethroughoutitslifetime.Ifanobjectisreferredtooutsideofitslifetime,thebehaviourisundefined.Explicitdeallocationofheap-allocatedstorageendsthelifetimeoftheobjectresidingatthismemorylocation(asdoesleavingthedynamicscopeofadeclaredvariable).Thevalueofapointerbecomesindeterminatewhentheobjectitpointstoreachestheendofitslifetime.Suchpointersarecalleddanglingreferences.
Theuseofdanglingreferencestopreviouslyfreedmemorycanhaveanynumberofadverseconsequences—rangingfromthecorruptionofvaliddatatotheexecutionofarbitrarycode,dependingontheinstantiationandtimingofthedeallocationcausingallremainingcopiesofthereferencetobecomedangling,ofthesystem'sreuseofthefreedmemory,andofthesubsequentusageofadanglingreference.
Likememoryleaksanderrorsduetodoublede-allocation,theuseofdanglingreferenceshastwocommonandsometimesoverlappingcauses:
• Anerrorconditionorotherexceptionalcircumstancesthatunexpectedlycauseanobjecttobecomeundefined.
• Developerconfusionoverwhichpartoftheprogramisresponsibleforfreeingthememory.
Ifapointertopreviouslyfreedmemoryisused,itispossiblethatthereferencedmemoryhasbeenreallocated.Therefore,assignmentusingtheoriginalpointerhastheeffectofchangingthevalueofanunrelatedvariable.Thisinducesunexpectedbehaviourintheaffectedprogram.Ifthenewlyallocateddatahappenstoholdaclassdescription,inanobject-orientedlanguageforexample,variousfunctionpointersmaybescatteredwithintheheapdata.Ifoneofthesefunctionpointersisoverwrittenwithanaddressofmaliciouscode,executionofarbitrarycodecanbeachieved.
6.14.4Applicablelanguagecharacteristics
Thisvulnerabilitydescriptionisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Languagesthatpermittheuseofpointersandthatpermitexplicitdeallocationbythedeveloperorprovideforalternativemeanstoreallocatememorystillpointedtobysomepointervalue.
• Languagesthatpermitdefinitionsofconstructsthatcanbeparameterizedwithoutenforcingtheconsistencyoftheuseofparameteratcompiletime.
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
WG23/N0720
44 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
6.14.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Useanimplementationthatcheckswhetherapointerisusedthatdesignatesamemorylocationthathasalreadybeenfreed.
• Useacodingstylethatdoesnotpermitdeallocation.• Incomplicatederrorconditions,besurethatclean-uproutinesrespectthestateofallocationproperly.If
thelanguageisobject-oriented,ensurethatobjectdestructorsdeleteeachchunkofmemoryonlyonce.EnsuringthatallpointersaresettoNULLoncethememorytheypointtohavebeenfreedcanbeaneffectivestrategy.Theutilizationofmultipleorcomplexdatastructuresmaylowertheusefulnessofthisstrategy.
• Useastaticanalysistoolthatiscapableofdetectingsomesituationswhenapointerisusedafterthestorageitreferstoisnolongerapointertovalidmemorylocation.
• Memoryshouldbeallocatedandfreedatthesamelevelofabstraction,andideallyinthesamecodemodule2.
6.14.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Implementationsofthefreefunctioncouldtoleratemultiplefreesonthesamereference/pointerorfreesofmemorythatwasneverallocated.
• Languagespecifiersshoulddesigngenericsinsuchawaythatanyattempttoinstantiateagenericwithconstructsthatdonotprovidetherequiredcapabilitiesresultsinacompile-timeerror.
• Forpropertiesthatcannotbecheckedatcompiletime,languagespecifiersshouldprovideanassertionmechanismforcheckingpropertiesatrun-time.Itshouldbepossibletoinhibitassertioncheckingifefficiencyisaconcern.
• AstorageallocationinterfaceshouldbeprovidedthatwillallowthecalledfunctiontosetthepointerusedtoNULLafterthereferencedstorageisdeallocated.
6.15Arithmeticwrap-arounderror[FIF]
6.15.1Descriptionofapplicationvulnerability
Wrap-arounderrorscanoccurwheneveravalueisincrementedpastthemaximumordecrementedpasttheminimumvaluerepresentableinitstypeand,dependingupon
• whetherthetypeissignedorunsigned,• thespecificationofthelanguagesemanticsand/or• implementationchoices,
2 Allocatingandfreeingmemoryindifferentmodulesandlevelsofabstractionburdenstheprogrammerwithtrackingthelifetimeofthatblockofmemory.Thismaycauseconfusionregardingwhenandifablockofmemoryhasbeenallocatedorfreed,leadingtoprogrammingdefectssuchasdouble-freevulnerabilities,accessingfreedmemory,ordereferencingNULLpointersorpointersthatarenotinitialized.
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 45
"wrapsaround"toanunexpectedvalue.Thisvulnerabilityisrelatedto6.16Usingshiftoperationsformultiplicationanddivision[PIK]3.
6.15.2Crossreference
CWE:128.Wrap-aroundError190.IntegerOverfloworWraparound
JSFAVRules:164and15MISRAC2012:7.2,10.1,10.3,10.4,10.6,10.7,and12.4MISRAC++2008:2-13-3,5-0-3to5-0-10,and5-19-1CERTCguidelines:INT30-C,INT32-C,andINT34-C
6.15.3Mechanismoffailure
Duetohowarithmeticisperformedbycomputers,ifavariable’svalueisincreasedpastthemaximumvaluerepresentableinitstype,thesystemmayfailtoprovideanoverflowindicationtotheprogram.Oneofthemostcommonprocessorbehaviouristo“wrap”toaverylargenegativevalue,orsetaconditionflagforoverfloworunderflow,orsaturateatthelargestrepresentablevalue.
Wrap-aroundoftengeneratesanunexpectednegativevalue;thisunexpectedvaluemaycausealooptocontinueforalongtime(becausetheterminationconditionrequiresavaluegreaterthansomepositivevalue)oranarrayboundsviolation.Awrap-aroundcansometimestriggerbufferoverflowsthatcanbeusedtoexecutearbitrarycode.
Itshouldbenotedthatthepreciseconsequencesofwrap-arounddifferdependingon:
• Whetherthetypeissignedorunsigned.• Whetherthetypeisamodulustype.• Whetherthetype’srangeisviolatedbyexceedingthemaximumrepresentablevalueorfallingshortof
theminimumrepresentablevalue.• Thesemanticsofthelanguagespecification.• Implementationdecisions.
However,inallcases,theresultingproblemisthatthevalueyieldedbythecomputationmaybeunexpected.
6.15.4Applicablelanguagecharacteristics
Thisvulnerabilitydescriptionisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Languagesthatdonottriggeranexceptionconditionwhenawrap-arounderroroccurs.
6.15.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
3ThisdescriptionisderivedfromWrap-AroundError[XYY],whichappearedinEdition1ofthisinternationaltechnicalreport.
Formatted: Font:Italic, Underline, Font color: Blue
Formatted: Font:Italic, Underline, Font color: Blue
Formatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: Blue
Deleted: 6.16Usingshiftoperationsformultiplicationanddivision
[PIK]6.16UsingShiftOperationsforMultiplicationandDivision[PIK]
Formatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueDeleted:
WG23/N0720
46 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
• Determineapplicableupperandlowerboundsfortherangeofallvariablesanduselanguagemechanismsorstaticanalysistodeterminethatvaluesareconfinedtotheproperrange.
• Analyzethesoftwareusingstaticanalysislookingforunexpectedconsequencesofarithmeticoperations.
6.15.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Languagestandardsdevelopersshouldconsiderprovidingfacilitiestospecifyeitheranerror,asaturatedvalue,oramoduloresultwhennumericoverflowoccurs.Ideally,theselectionamongthesealternativescouldbemadebytheprogrammer.
6.16Usingshiftoperationsformultiplicationanddivision[PIK]
6.16.1Descriptionofapplicationvulnerability
Usingshiftoperationsasasurrogateformultiplyordividemayproduceanunexpectedvaluewhenthesignbitischangedorwhenvaluebitsarelost.Thisvulnerabilityisrelatedto6.15Arithmeticwrap-arounderror[FIF]4.
6.16.2Crossreference
CWE:128.Wrap-aroundError190.IntegerOverfloworWraparound
JSFAVRules:164and15MISRAC2012:7.2,10.1,10.3,10.4,10.6,10.7,and12.4MISRAC++2008:2-13-3,5-0-3to5-0-10,and5-19-1CERTCguidelines:INT30-C,INT32-C,andINT34-C
6.16.3Mechanismoffailure
Shiftoperationsintendedtoproduceresultsequivalenttomultiplicationordivisionfailtoproducecorrectresultsiftheshiftoperationaffectsthesignbitorshiftssignificantbitsfromthevalue.
Sucherrorsoftengenerateanunexpectednegativevalue;thisunexpectedvaluemaycausealooptocontinueforalongtime(becausetheterminationconditionrequiresavaluegreaterthansomepositivevalue)oranarrayboundsviolation.Theerrorcansometimestriggerbufferoverflowsthatcanbeusedtoexecutearbitrarycode.
6.16.4Applicablelanguagecharacteristics
Thisvulnerabilitydescriptionisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Languagesthatpermitlogicalshiftoperationsonvariablesofarithmetictype.
4ThisdescriptionisderivedfromWrap-AroundError[XYY],whichappearedinEdition1ofthisinternationaltechnicalreport.
Deleted:
Deleted: Formatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: Blue
Formatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: Blue
Formatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: Blue
Formatted: Font:Italic, Underline, Font color: Blue
Deleted: 6.15Arithmeticwrap-arounderror[FIF]6.15Arithmetic
Wrap-aroundError[FIF]
Formatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueDeleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 47
6.16.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Determineapplicableupperandlowerboundsfortherangeofallvariablesanduselanguagemechanismsorstaticanalysistodeterminethatvaluesareconfinedtotheproperrange.
• Analyzethesoftwareusingstaticanalysislookingforunexpectedconsequencesofshiftoperations.• Avoidusingshiftoperationsasasurrogateformultiplicationanddivision.Mostcompilerswillusethe
correctoperationintheappropriatefashionwhenitisapplicable.
6.16.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Notprovidinglogicalshiftingonarithmeticvaluesorflaggingitforreviewers.
6.17Choiceofclearnames[NAI].
6.17.1Descriptionofapplicationvulnerability
Humanssometimeschoosesimilaroridenticalnamesforobjects,types,aggregatesoftypes,subprogramsandmodules.Theytendtousecharacteristicsthatarespecifictothenativelanguageofthesoftwaredevelopertoaidinthiseffort,suchasuseofmixed-casing,underscoresandperiods,oruseofpluralandsingularformstosupporttheseparationofitemswithsimilarnames.Similarly,developmentconventionssometimesusecasingfordifferentiation(forexample,alluppercaseforconstants).
Humancognitiveproblemsoccurwhendifferent(butsimilar)objects,subprograms,types,orconstantsdifferinnamesolittlethathumanreviewersareunlikelytodistinguishbetweenthem,orwhenthesystemmapssuchentitiestoasingleentity.
Conventionssuchastheuseofcapitalization,andsingular/pluraldistinctionsmayworkinsmallandmediumprojects,butthereareanumberofsignificantissuestobeconsidered:
• Largeprojectsoftenhavemixedlanguagesandsuchconventionsareoftenlanguage-specific.• Manyimplementationssupportidentifiersthatcontaininternationalcharactersetsandsomelanguage
charactersetshavedifferentnotionsofcasingandplurality.• Differentword-formstendtobelanguageanddialectspecific,suchasapidgin,andmaybemeaningless
tohumansthatspeakotherdialects.
Animportantgeneralissueisthechoiceofnamesthatdifferfromeachothernegligibly(inhumanterms),forexamplebydifferingbyonlyunderscores,(none,"_""__"),plurals("s"),visuallysimilarcharacters(suchas"l"and"1","O"and"0"),orunderscores/dashes("-","_").[Thereisalsoanissuewhereidentifiersappeardistincttoahumanbutidenticaltothecomputer,suchasFOO,Foo,andfooinsomecomputerlanguages.]Charactersetsextendedwithdiacriticalmarksandnon-Latincharactersmayofferadditionalproblems.Somelanguagesortheirimplementationsmaypayattentiontoonlythefirstncharactersofanidentifier.
Theproblemsdescribedabovearedifferentfromoverloadingoroverridingwherethesamenameisusedintentionally(anddocumented)toaccesscloselylinkedsetsofsubprograms.Thisisalsodifferentthanusing
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
WG23/N0720
48 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
reservednameswhichcanleadtoaconflictwiththereserveduseandtheuseofwhichmayormaynotbedetectedatcompiletime.
Nameconfusioncanleadtotheapplicationexecutingdifferentcodeoraccessingdifferentobjectsthanthewriterintended,orthanthereviewersunderstood.Thiscanleadtooutrighterrors,orleaveinplacecodethatmayexecutesometimeinthefuturewithunacceptableconsequences.
Althoughmostsuchmistakesareunintentional,itisplausiblethatsuchusagescanbeintentional,ifmaskingsurreptitiousbehaviourisagoal.
6.17.2Crossreference
JSFAVRules:48,49,50,51,52MISRAC2012:1.1CERTCguidelines:DCL02-CAdaQualityandStyleGuide:3.2
6.17.3MechanismofFailure
Callstothewrongsubprogramorreferencestothewrongdataelement(thatwasmissedbyhumanreview)canresultinunintendedbehaviour.Languageprocessorswillnotmakeamistakeinnametranslation,buthumancognitionlimitationsmaycausehumanstomisunderstand,andthereforemaybemissedinhumanreviews.
6.17.4Applicablelanguagecharacteristics
Thisvulnerabilitydescriptionisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Languageswithrelativelyflatnamespaceswillbemoresusceptible.Systemswithmodules,classes,packagescanusequalificationtodisambiguatenamesthatoriginatefromdifferentparents.
• Languagesthatprovidepreconditions,postconditions,invariancesandassertionsorredundantcodingofsubprogramsignatureshelptoensurethatthesubprogramsinthemodulewillbehaveasexpected,butdonothingifdifferentsubprogramsarecalled.
• Languagesthattreatlettercaseassignificant.Somelanguagesdonotdifferentiatebetweennameswithdifferingcase,whileothersdo.
6.17.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Usestaticanalysistoolstoshowthetargetofcallsandaccessesandtoproducealphabeticallistsofnames.Humanreviewcanthenoftenspotthenamesthataresortedatanunexpectedlocationorwhichlookalmostidenticaltoanadjacentnameinthelist.
• Uselanguageswitharequirementtodeclarenamesbeforeuseoruseavailabletoolorcompileroptionstoenforcesucharequirement.
• Donotchoosenamesthatconflictwith(unreserved)keywordsorlanguage-definedlibrarynamesforthelanguagebeingused.
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 49
• Donotusenamesthatonlydifferbycharactersthatmaybeconfusedvisuallyinthealphabetusedindevelopment.FortheRomanalphabetthesewouldincludeas‘O’and‘0’,‘l’(lowercase‘L’),‘I’(capital‘I’)and‘1’,‘S’and‘5’,‘Z’and‘2’,and‘n’and‘h’.
• Donotusenamesthatonlydifferintheuseofupperandlowercasetoothernames
6.17.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Languagesthatdonotrequiredeclarationsofnamesshouldconsiderprovidinganoptionthatdoesimposethatrequirement.
6.18Deadstore[WXQ]
6.18.1Descriptionofapplicationvulnerability
Avariable'svalueisassignedbutneversubsequentlyused,eitherbecausethevariableisnotreferencedagain,orbecauseasecondvalueisassignedbeforethefirstisused.Thismaysuggestthatthedesignhasbeenincompletelyorinaccuratelyimplemented,forexample,avaluehasbeencreatedandthen‘forgottenabout’.
Thisvulnerabilityisverysimilarto6.19Unusedvariable[YZS].
6.18.2Crossreference
CWE:563.UnusedVariable
MISRAC++2008:0-1-4and0-1-6CERTCguidelines:MSC13-CSeealso6.19Unusedvariable[YZS]
6.18.3Mechanismoffailure
Avariableisassignedavaluebutthisisneversubsequentlyused.Suchanassignmentisthengenerallyreferredtoasadeadstore.
Adeadstoremaybeindicativeofcarelessprogrammingorofadesignorcodingerror;aseithertheuseofthevaluewasforgotten(almostcertainlyanerror)ortheassignmentwasperformedeventhoughitwasnotneeded(atbestinefficient).Deadstoresmayalsoariseastheresultofmistypingthenameofavariable,ifthemistypednamematchesthenameofavariableinanenclosingscope.
Therearelegitimateusesforapparentdeadstores.Forexample,thevalueofthevariablemightbeintendedtobereadbyanotherexecutionthreadoranexternaldevice.Insuchcases,though,thevariableshouldbemarkedasvolatile.Commoncompileroptimizationtechniqueswillremoveapparentdeadstoresifthevariablesarenotmarkedasvolatile,hencecausingincorrectexecution.
Adeadstoreisjustifiableif,forexample:
Deleted:
Formatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: Blue, (Asian)Chinese (PRC)
Formatted: Font:Italic, Underline, Font color: Blue, (Asian)Chinese (PRC)Formatted: Font:Italic, Underline, Font color: Blue, (Asian)Chinese (PRC)Formatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: Blue
Formatted: Font:Italic, Underline, Font color: Blue, (Asian)Chinese (PRC)
Formatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueDeleted: 6.19Unusedvariable[YZS]6.19UnusedVariable[YZS]
Formatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: Blue, (Asian)Chinese (PRC)Formatted: Font:Italic, Underline, Font color: Blue, (Asian)Chinese (PRC)Formatted: Font:Italic, Underline, Font color: Blue, (Asian)Chinese (PRC)Formatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: Blue, (Asian)Chinese (PRC)Formatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: Blue, (Asian)Chinese (PRC)Formatted: Font:Italic, Underline, Font color: Blue, (Asian)Chinese (PRC)Formatted: Font:Italic, Underline, Font color: Blue, (Asian)Chinese (PRC)Formatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted ... [2]Formatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueDeleted: 6.19Unusedvariable[YZS]6.19UnusedVariable[YZS]
Formatted: Font:Italic, Underline, Font color: BlueFormatted ... [3]Formatted ... [4]Formatted ... [5]Formatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted ... [6]Formatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueDeleted:
WG23/N0720
50 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
• Thecodehasbeenautomaticallygenerated,whereitiscommonplacetofinddeadstoresintroducedtokeepthegenerationprocesssimpleanduniform.
• Thecodeisinitializingasparsedataset,whereallmembersarecleared,andthenselectedvaluesassignedavalue.
6.18.4Applicablelanguagecharacteristics
Thisvulnerabilitydescriptionisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Anyprogramminglanguagethatprovidesassignment.
6.18.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Usestaticanalysistoidentifyanydeadstoresintheprogram,andensurethatthereisajustificationforthem.
• Ifvariablesareintendedtobeaccessedbyotherexecutionthreadsorexternaldevices,markthemasvolatile.
• Avoiddeclaringvariablesofcompatibletypesinnestedscopeswithsimilarnames.• Forsecurity,assignzero(orsomeotherinformationfreevalue)afterthelastintendedread.
6.18.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Languagesshouldconsiderprovidingoptionalwarningmessagesfordeadstore.
6.19Unusedvariable[YZS]
6.19.1Descriptionofapplicationvulnerability
Anunusedvariableisonethatisdeclaredbutneitherreadnorwrittenintheprogram.Thistypeoferrorsuggeststhatthedesignhasbeenincompletelyorinaccuratelyimplemented.
Unusedvariablesbythemselvesareinnocuous,buttheymayprovidememoryspacethatattackerscoulduseincombinationwithothertechniques.
Thisvulnerabilityissimilarto6.18Deadstore[WXQ]ifthevariableisinitializedbutneverused.
6.19.2Crossreference
CWE:563.UnusedVariable
MISRAC++2008:0-1-3CERTCguidelines:MSC13-CSeealso6.18Deadstore[WXQ]
Formatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: Blue
Formatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: Blue
Formatted: Font:Italic, Underline, Font color: Blue
Formatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueDeleted: 6.18Deadstore[WXQ]6.18DeadStore[WXQ]
Formatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueDeleted: 6.18Deadstore[WXQ]6.18DeadStore[WXQ]
Formatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: Blue
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 51
6.19.3Mechanismoffailure
Avariableisdeclared,butneverused.Theexistenceofanunusedvariablemayindicateadesignorcodingerror.
Becausecompilersroutinelydiagnoseunusedlocalvariables,theirpresencemaybeanindicationthatcompilerwarningsareeithersuppressedorarebeingignored.
Whileunusedvariablesareinnocuous,theymayprovideavailablememoryspacetobeusedbyattackerstoexploitothervulnerabilities.
6.19.4Applicablelanguagecharacteristics
Thisvulnerabilitydescriptionisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Languagesthatprovidevariabledeclarations.
6.19.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Enabledetectionofunusedvariablesinthecompiler.• Usestaticanalysistoidentifyanyunusedvariablesintheprogram,andensurethatthereisajustification
forthem.
6.19.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Languagesshouldconsiderrequiringmandatorydiagnosticsforunusedvariables.
6.20Identifiernamereuse[YOW]
6.20.1Descriptionofapplicationvulnerability
Whendistinctentitiesaredefinedinnestedscopesusingthesamenameitispossiblethatprogramlogicwilloperateonanentityotherthantheoneintended.
Whenitisnotclearwhichidentifierisused,theprogramcouldbehaveinwaysthatwerenotpredictedbyreadingthesourcecode.Thiscanbefoundbytesting,butcircumstancescanarise(suchasthevaluesofthesame-namedobjectsbeingmostlythesame)whereharmfulconsequencesoccur.Thisweaknesscanalsoleadtovulnerabilitiessuchashiddenchannelswherehumansbelievethatimportantobjectsarebeingrewrittenoroverwrittenwheninfactotherobjectsarebeingmanipulated.
Forexample,theinnermostdefinitionisdeletedfromthesource,theprogramwillcontinuetocompilewithoutadiagnosticbeingissued(butexecutioncanproduceunexpectedresults).
6.20.2Crossreference
JSFAVRules:120,135,136and137,
Deleted:
Deleted:
Deleted:
WG23/N0720
52 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
MISRAC2012:5.3,5.8,5.9,21.1,21.2MISRAC++2008:2-10-2,2-10-3,2-10-4,2-10-5,2-10-6,17-0-1,17-0-2,and17-0-3CERTCguidelines:DCL01-CandDCL32-CAdaQualityandStyleGuide:5.6.1and5.7.1
6.20.3Mechanismoffailure
Manylanguagessupporttheconceptofscope.Oneoftheideasbehindtheconceptofscopeistoprovideamechanismfortheindependentdefinitionofidentifiersthatmaysharethesamename.
Forinstance,inthefollowingcodefragment:
int some_var; { int t_var; int some_var; /* definition in nested scope */ t_var = 3; some_var = 2; }
anidentifiercalledsome_varhasbeendefinedindifferentscopes.
Ifeitherthedefinitionofsome_varort_varthatoccursinthenestedscopeisdeleted(forexample,whenthesourceismodified)itisnecessarytodeleteallotherreferencestotheidentifier’sscope.Ifadeveloperdeletesthedefinitionoft_varbutfailstodeletethestatementthatreferencesit,thenmostlanguagesrequireadiagnostictobeissued(suchasreferencetoundefinedvariable).However,ifthenesteddefinitionofsome_varisdeletedbutthereferencetoitinthenestedscopeisnotdeleted,thennodiagnosticwillbeissued(becausethereferenceresolvestothedefinitionintheouterscope).
Insomecasesnon-uniqueidentifiersinthesamescopecanalsobeintroducedthroughtheuseofidentifierswhosecommonsubstringexceedsthelengthofcharacterstheimplementationconsiderstobedistinct.Forexample,inthefollowingcodefragment:
extern int global_symbol_definition_lookup_table_a[100]; extern int global_symbol_definition_lookup_table_b[100];
theexternalidentifiersarenotuniqueonimplementationswhereonlythefirst31charactersaresignificant.Thissituationonlyoccursinlanguagesthatallowmultipledeclarationsofthesameidentifier(otherlanguagesrequireadiagnosticmessagetobeissued).
Arelatedproblemexistsinlanguagesthatallowoverloadingoroverridingofkeywordsorstandardlibraryfunctionidentifiers.Suchoverloadingcanleadtoconfusionaboutwhichentityisintendedtobereferenced.
Definitionsfornewidentifiersshouldnotuseanamethatisalreadyvisiblewithinthescopecontainingthenewdefinition.Alternately,utilizelanguage-specificfacilitiesthatcheckforandpreventinadvertentoverloadingofnamesshouldbeused.
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 53
6.20.4Applicablelanguagecharacteristics
Thisvulnerabilityisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Languagesthatallowthesamenametobeusedforidentifiersdefinedinnestedscopes.• Languageswhereuniquenamescanbetransformedintonon-uniquenamesaspartofthenormaltool
chain.
6.20.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Ensurethatadefinitionofanentitydoesnotoccurinascopewhereadifferententitywiththesamenameisaccessibleandcanbeusedinthesamecontext.Alanguage-specificprojectcodingconventioncanbeusedtoensurethatsucherrorsaredetectablewithstaticanalysis.
• Ensurethatadefinitionofanentitydoesnotoccurinascopewhereadifferententitywiththesamenameisaccessibleandhasatypethatpermitsittooccurinatleastonecontextwherethefirstentitycanoccur.
• Uselanguagefeatures,ifany,whichexplicitlymarkdefinitionsofentitiesthatareintendedtohideotherdefinitions.
• Developorusetoolsthatidentifynamecollisionsorreusewhentruncatedversionsofnamescauseconflicts.
• Ensurethatallidentifiersdifferwithinthenumberofcharactersconsideredtobesignificantbytheimplementationsthatarelikelytobeused,anddocumentallassumptions.
6.20.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Languagesshouldrequiremandatorydiagnosticsforvariableswiththesamenameinnestedscopes.• Languagesshouldrequiremandatorydiagnosticsforvariablenamesthatexceedthelengththatthe
implementationconsidersunique.• Languagesshouldconsiderrequiringmandatorydiagnosticsforoverloadingoroverridingofkeywordsor
standardlibraryfunctionidentifiers.
6.21Namespaceissues[BJL]
6.21.1DescriptionofApplicationVulnerability
Ifalanguageprovidesseparate,non-hierarchicalnamespaces,auser-controlledorderingofnamespaces,andameanstomakenamesdeclaredinthesenamespacesdirectlyvisibletoanapplication,thepotentialofunintentionalandpossibledisastrouschangeinapplicationbehaviourcanarise,whennamesareaddedtoanamespaceduringmaintenance.
Namespacesincludeconstructslikepackages,modules,libraries,classesoranyothermeansofgroupingdeclarationsforimportintootherprogramunits.
Deleted:
WG23/N0720
54 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
6.21.2Crossreferences
MISRAC++2008:7-3-1,7-3-3,7-3-5,14-5-1,and16-0-2
6.21.3MechanismofFailure
Thefailureisbestillustratedbyanexample.NamespaceN1providesthenameA,butnotB.NamespaceN2providesthenameBbutnotA.TheapplicationwishestouseAfromN1andBfromN2.Atthispoint,therearenoobviousissues.Theapplicationchooses(orneeds)toimportbothnamespacestoobtainnamesfordirectusage,foranexample.
UseN1,N2;–presumedtomakeallnamesinN1andN2directlyvisibleinthescopeofintendeduse
… X := A + B;
Thesemanticsoftheaboveexampleareintuitiveandunambiguous.
Later,duringmaintenance,thenameBisaddedtoN1.Thechangetothenamespaceusuallyimpliesarecompilationofdependentunits.Atthispoint,twodeclarationsofBareapplicablefortheuseofBintheaboveexample.
Somelanguagestrytodisambiguatetheabovesituationbystatingpreferencerulesincaseofsuchambiguityamongnamesprovidedbydifferentnamespaces.If,intheaboveexample,N1ispreferredoverN2,themeaningoftheuseofBchangessilently,presumingthatnotypingerrorarises.Consequentlythesemanticsoftheprogramchangesilentlyandassuredlyunintentionally,sincetheimplementerofN1cannotassumethatallusersofN1wouldprefertotakeanydeclarationofBfromN1ratherthanitspreviousnamespace.
Itdoesnotmatterwhatthepreferencerulesactuallyare,aslongasthenamespacesaremutable.TheaboveexampleiseasilyextendedbyaddingAtoN2toshowasymmetricerrorsituationforadifferentprecedencerule.
Ifalanguagesupportsoverloadingofsubprograms,thenotionof“samename”usedintheaboveexampleisextendedtomeannotonlythesamename,butalsothesamesignatureofthesubprogram.Forvulnerabilitiesassociatedwithoverloadingandoverriding,see6.20Identifiernamereuse[YOW].Inthecontextofnamespaces,however,addingsignaturematchingtothenamebindingprocess,merelyextendsthedescribedproblemfromsimplenamestofullsignatures,butdoesnotalterthemechanismorqualityofthedescribedvulnerability.Inparticular,overloadingdoesnotintroducemoreambiguityforbindingtodeclarationsindifferentnamespaces.Thisvulnerabilitynotonlycreatesunintentionalerrors,butitalsocanbeexploitedmaliciously,ifthesourceoftheapplicationandofthenamespacesisknowntotheaggressorandoneofthenamespacesismutablebytheattacker.
6.21.4ApplicableLanguageCharacteristics
Thevulnerabilityisapplicabletolanguageswiththefollowingcharacteristics:
• Languagesthatsupportnon-hierarchicalseparatename-spaces,havemeanstoimportallnamesofanamespace“wholesale”fordirectuse,andhavepreferencerulestochooseamongmultipleimporteddirecthomographs.Allthreeconditionsneedtobesatisfiedforthevulnerabilitytoarise.
Deleted:
Deleted: Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted: Deleted:
Formatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: Blue
Deleted: 6.20Identifiernamereuse[YOW]6.20IdentifierName
Reuse[YOW]
Formatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueDeleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 55
6.21.5AvoidingtheVulnerabilityorMitigatingitsEffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Avoid“wholesale”importdirectives,i.e.directivesthatgiveallimportednamesthesamevisibilitylevelaseachotherand/orthesamevisibilitylevelaslocalnames(providedthatthelanguageofferstherespectivecapabilities);
• Useonlyselective“singlename”importdirectivesorusingfullyqualifiednames(providedthatthelanguageofferstherespectivecapabilities)
6.21.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Languagesshouldnothavepreferencerulesamongmutablenamespaces.Ambiguitiesshouldbeinvalidandavoidablebytheuser,forexample,byusingnamesqualifiedbytheiroriginatingnamespace.
6.22Initializationofvariables[LAV]
6.22.1Descriptionofapplicationvulnerability
Readingavariablethathasnotbeenassignedavalueappropriatetoitstypecancauseunpredictableexecutionintheblockthatusesthevalueofthatvariable,andhasthepotentialtoexportbadvaluestocallers,ortocauseout-of-boundsmemoryaccesses.
Uninitializedvariableusageisfrequentlynotdetecteduntilaftertestingandoftenwhenthecodeinquestionisdeliveredandinuse,becausehappenstancewillprovidevariableswithadequatevalues(suchasdefaultdatasettingsoraccidentalleft-overvalues)untilsomeotherchangeexposesthedefect.
Variablesthataredeclaredduringmoduleconstruction(byaclassconstructor,instantiation,orelaboration)mayhavealternatepathsthatcanreadvaluesbeforetheyareset.Thiscanhappeninstraightsequentialcodebutismoreprevalentwhenconcurrencyorco-routinesarepresent,withthesameimpactsdescribedabove.
Anothervulnerabilityoccurswhencompoundobjectsareinitializedincompletely,ascanhappenwhenobjectsareincrementallybuilt,orfieldsareaddedundermaintenance.
Whenpossibleandsupportedbythelanguage,whole-structureinitializationispreferabletofield-by-fieldinitializationstatements,andnamedassociationispreferabletopositional,asitfacilitateshumanreviewandislesssusceptibletoerrorinjectionundermaintenance.Forclasses,thedeclarationandinitializationmayoccurinseparatemodules.Insuchcasesitmustbepossibletoshowthateveryfieldthatneedsaninitialvaluereceivesthatvalue,andtodocumentonesthatdonotrequireinitialvalues.
6.22.2Crossreference
CWE:457.UseofUninitializedVariable
JSFAVRules:71,143,and147MISRAC2012:9.1,9.2,and9.3
Deleted:
Deleted:
WG23/N0720
56 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
MISRAC++2008:8-5-1CERTCguidelines:DCL14-CandEXP33-CAdaQualityandStyleGuide:5.9.6
6.22.3Mechanismoffailure
Uninitializedobjectsmayhaveinvalidvalues,validbutwrongvalues,orvalidanddangerousvalues.Wrongvaluescouldcauseunboundedbranchesinconditionalsorunboundedloopexecutions,orcouldsimplycausewrongcalculationsandresults.
Thereisaspecialcaseofpointersoraccesstypes.Whensuchatypecontainsnullvalues,aboundviolationandhardwareexceptioncanresult.Whensuchatypecontainsplausiblebutmeaninglessvalues,randomdatareadsandwritescancollecterroneousdataorcandestroydatathatisinusebyanotherpartoftheprogram;whensuchatypeisanaccesstoasubprogramwithaplausible(butwrong)value,theneitherabadinstructiontrapmayoccuroratransfertoanunknowncodefragmentcanoccur.Allofthesescenarioscanresultinundefinedbehaviour.
Uninitializedvariablesaredifficulttoidentifyanduseforattackers,butcanbearbitrarilydangerousinsafetysituations.
Thegeneralproblemofshowingthatallprogramobjectsareinitializedisintractable;
6.22.4Applicablelanguagecharacteristics
Thisvulnerabilitydescriptionisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Languagesthatpermitvariablestobereadbeforetheyareassigned.
6.22.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Carefullystructureprogramstoshowthatallvariablesaresetbeforefirstreadoneverypaththroughouteachsubprogram.
• Whenanobjectisvisiblefrommultiplemodules,identifyamodulethatmustsetthevaluebeforereadscanoccurfromanyothermodulethatcanaccesstheobject,andensurethatthismoduleisexecutedfirst.
• Whenconcurrency,interruptsandco-routinesarepresent,identifywhereearlyinitializationoccursandshowthatthecorrectorderissetviaprogramstructure,notbytiming,OSprecedence,orchance.
• Initializeeachobjectatelaborationtime,orimmediatelyaftersubprogramexecutioncommencesandbeforeanybranches.
• Ifthesubprogrammustcommencewithconditionalstatements,showthateveryvariabledeclaredandnotinitializedearlierisinitializedoneachbranch.
• Ensurethattheinitialobjectvalueisasensiblevalueforthelogicoftheprogram.Theso-called"junkinitialization"(suchas,forexample,settingeveryvariabletozero)preventstheuseoftoolstodetectotherwiseuninitializedvariables.
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 57
• Defineorreservefieldsorportionsoftheobjecttoonlybesetwhenfullyinitialized.Consider,however,thatthisapproachhastheeffectofsettingthevariabletopossiblymistakenvalueswhiledefeatingtheuseofstaticanalysistofindtheuninitializedvariables.
• Usestaticanalysistoolstoshowthatallobjectsaresetbeforeuse.Asthegeneralproblemisintractable,keepinitializationalgorithmssimplesothattheycanbeanalyzed.
• Whendeclaringandinitializingtheobjecttogether,ifthelanguagedoesnotrequirethecompilertostaticallyverifythatthedeclarativestructureandtheinitializationstructurematch,usestaticanalysistoolstohelpdetectanymismatches.
• Whensettingcompoundobjects,ifthelanguageprovidesmechanismstosetallcomponentstogether,usethoseinpreferencetoasequenceofinitializationsasthisfacilitatescoverageanalysis;otherwiseusetoolsthatperformsuchcoverageanalysisanddocumenttheinitialization.Donotperformpartialinitializationsunlessthereisnochoice,anddocumentanydeviationsfromfullinitialization.
• Wheredefaultassignmentsofmultiplecomponentsareperformed,explicitdeclarationofthecomponentnamesand/orrangeshelpsstaticanalysisandidentificationofcomponentchangesduringmaintenance.
• Usenamedassignmentsinpreferencetopositionalassignmentwherethelanguagehasnamedassignmentsthatcanbeusedtobuildreviewableassignmentstructuresthatcanbeanalyzedbythelanguageprocessorforcompleteness.Usecommentsandsecondarytoolstohelpshowcorrectassignmentwherethelanguageonlysupportspositionalassignmentnotation.
6.22.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Somelanguageshavewaystodetermineifmodulesandregionsareelaboratedandinitializedandtoraiseexceptionsifthisdoesnotoccur.Languagesthatdonot,couldconsideraddingsuchcapabilities.
• Languagescouldconsidersettingasidefieldsinallobjectstoidentifyifinitializationhasoccurred,especiallyforsecurityandsafetydomains.
• Languagesthatdonotsupportwhole-objectinitialization,couldconsideraddingthiscapability.
6.23Operatorprecedenceandassociativity[JCW]
6.23.1Descriptionofapplicationvulnerability
Eachlanguageprovidesrulesofprecedenceandassociativity,foreachexpressionthatoperandsbindtowhichoperators.Theserulesarealsoknownas“grouping”or“binding”.
Experienceandexperimentalevidenceshowsthatdeveloperscanhaveincorrectbeliefsabouttherelativeprecedenceofmanybinaryoperators.See,Developerbeliefsaboutbinaryoperatorprecedence.CVu,18(4):14-21,August2006
6.23.2Crossreference
JSFAVRules:204and213MISRAC2012:10.1,12.1,13.2,14.4,20.7,20.10,and20.11MISRAC++2008:4-5-1,4-5-2,4-5-3,5-0-1,5-0-2,5-2-1,5-3-1,16-0-6,16-3-1,and16-3-2CERTCguidelines:EXP00-C
Deleted:
Deleted:
Deleted:
Deleted:
WG23/N0720
58 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
AdaQualityandStyleGuide:7.1.8and7.1.9
6.23.3Mechanismoffailure
InCandC++,thebitwiseoperators(bitwiselogicalandbitwiseshift)aresometimesthoughtofbytheprogrammerhavingsimilarprecedencetoarithmeticoperations,sojustasonemightcorrectlywrite“x – 1 == 0”(“xminusoneisequaltozero”),aprogrammermighterroneouslywrite“x & 1 == 0”,mentallymeaning“x and-edwith1isequaltozero”,whereastheoperatorprecedencerulesofCandC++actuallybindtheexpressionas“compute1==0,producing‘false’interpretedaszero,thenbitwise-andtheresultwithx”,producing(aconstant)zero,contrarytotheprogrammer’sintent.
ExamplesfromanoppositeextremecanbefoundinprogramswritteninAPL,whichisnoteworthyfortheabsenceofanydistinctionsofprecedence.Onecommonlymademistakeistowrite“a * b + c”,intendingtoproduce“atimesbplusc”,whereasAPL’suniformright-to-leftassociativityproduces“bplusc,timesa”.
6.23.4Applicablelanguagecharacteristics
Thisvulnerabilitydescriptionisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Languageswhoseprecedenceandassociativityrulesaresufficientlycomplexthatdevelopersmaynotfullyrememberthem.
6.23.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Adoptprogrammingguidelines(preferablyaugmentedbystaticanalysis).Forexample,usethelanguage-specificrulescross-referencedin6.24.2.
• Useparenthesesaroundbinaryoperatorcombinationsthatareknowntobeasourceoferror(forexample,mixedarithmetic/bitwiseandbitwise/relationaloperatorcombinations).
• Breakupcomplexexpressionsandusetemporaryvariablestomaketheintendedorderclearer.
6.23.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Languagedefinitionsshouldavoidprovidingprecedenceoraparticularassociativityforoperatorsthatarenottypicallyorderedwithrespecttooneanotherinarithmetic,andinsteadrequirefullparenthesizationtoavoidmisinterpretation.
6.24Side-effectsandorderofevaluationofoperands[SAM]
6.24.1Descriptionofapplicationvulnerability
Someprogramminglanguagesallowsubexpressionstocauseside-effects(suchasassignment,increment,ordecrement).Forexample,someprogramminglanguagespermitsuchside-effects,andif,withinoneexpression(suchas“i = v[i++]”),twoormoreside-effectsmodifythesameobject,undefinedbehaviourresults.
Deleted:
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 59
Somelanguagesallowsubexpressionstobeevaluatedinanunspecifiedordering,orevenremovedduringoptimization.Ifthesesubexpressionscontainside-effects,thenthevalueofthefullexpressioncanbedependentupontheorderofevaluation.Furthermore,theobjectsthataremodifiedbytheside-effectscanreceivevaluesthataredependentupontheorderofevaluation.
Ifaprogramcontainstheseunspecifiedorundefinedbehaviours,testingtheprogramandseeingthatityieldstheexpectedresultsmaygivethefalseimpressionthattheexpressionwillalwaysyieldtheexpectedresult.
6.24.2Crossreference
JSFAVRules:157,158,204,204.1,and213MISRAC2012:12.1,13.2,13.5and13.6MISRAC++2008:5-0-1CERTCguidelines:EXP10-C,EXP30-CAdaQualityandStyleGuide:7.1.8and7.1.9
6.24.3Mechanismoffailure
Whensubexpressionswithsideeffectsareusedwithinanexpression,theunspecifiedorderofevaluationcanresultinaprogramproducingdifferentresultsondifferentplatforms,orevenatdifferenttimesonthesameplatform.
(AllexampleshereusethesyntaxofCorJavaforbrevity;theeffectscanbecreatedinanylanguagethatallowsfunctionswithside-effectsintheplaceswhereCallowstheincrementoperations.)
Consider
a = f(b) + g(b);
wherefandgbothmodifyb.Iff(b)isevaluatedfirst,thenthebusedasaparametertog(b)maybeadifferentvaluethanifg(b)isperformedfirst.Likewise,ifg(b)isperformedfirst,f(b)maybecalledwithadifferentvalueofb.
Otherexamplesofunspecifiedorder,orevenundefinedbehaviour,canbemanifested,suchas
a = f(i) + i++;
or
a[i++] = b[i++];
Parenthesesaroundexpressionscanassistinremovingambiguityaboutgrouping,buttheissuesregardingside-effectsandorderofevaluationarenotchangedbythepresenceofparentheses.Consider
j = i++ * i++;
whereevenifparenthesesareplacedaroundthei++subexpressions:undefinedbehaviourstillremains.
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
WG23/N0720
60 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
Theunpredictablenatureofthecalculationmeansthattheprogramcannotbetestedadequatelytoanydegreeofconfidence.Aknowledgeableattackercantakeadvantageofthischaracteristictomanipulatedatavaluestriggeringexecutionthatwasnotanticipatedbythedeveloper.
6.24.4Applicablelanguagecharacteristics
Thisvulnerabilitydescriptionisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Languagesthatpermitexpressionstocontainsubexpressionswithsideeffects.• Languageswhosesubexpressionsarecomputedinanunspecifiedordering.
6.24.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Makeuseofoneormoreprogrammingguidelines,which(a)prohibittheseunspecifiedorundefinedbehaviours,and(b)canbeenforcedbystaticanalysis.(SeeJSFAVandMISRArulesinCrossreferenceclause[SAM])
• Keepexpressionssimple.Complicatedcodeispronetoerroranddifficulttomaintain.• Ensurethateachexpressionresultsinthesamevalue,regardlessoftheorderofevaluationorexecution
oftermsoftheexpression.
6.24.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Indevelopingneworrevisedlanguages,giveconsiderationtolanguagefeaturesthatwilleliminateormitigatethisvulnerability,suchaspurefunctions.
6.25Likelyincorrectexpression[KOA]
6.25.1Descriptionofapplicationvulnerability
Certainexpressionsaresymptomaticofwhatislikelytobeamistakemadebytheprogrammer.Thestatementisnotcontrarytothelanguagestandard,butisunlikelytobeintended.Thestatementmayhavenoeffectandeffectivelyisanullstatementormayintroduceanunintendedside-effect.Acommonexampleistheuseof=inanifexpressioninC-basedlanguageswheretheprogrammermeanttodoanequalitytestusingthe==operator.OthereasilyconfusedoperatorsinC-basedlanguagesarethelogicaloperatorssuchas&&forthebitwiseoperator&,orviceversa.Itisvalidandpossiblethattheprogrammerintendedtodoanassignmentwithintheifexpression,butduetothisbeingacommonerror,aprogrammerdoingsowouldbeusingapoorprogrammingpractice.Alesslikelyoccurrence,butstillpossibleisthesubstitutionof==for=inwhatissupposedtobeanassignmentstatement,butwhicheffectivelybecomesanullstatement.Thesemistakesmaysurvivetestingonlytomanifestthemselvesindeployedcodewheretheymaybemaliciouslyexploited.
6.25.2Crossreference
CWE:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 61
480.UseofIncorrectOperator481.AssigninginsteadofComparing482.ComparinginsteadofAssigning570.ExpressionisAlwaysFalse571.ExpressionisAlwaysTrue
JSFAVRules:160MISRAC2012:2.2,13.3-13.6,and14.3MISRAC++2008:0-1-9,5-0-1,6-2-1,and6-5-2CERTCguidelines:MSC02-CandMSC03-C
6.25.3Mechanismoffailure
Someofthefailuresaresimplyacaseofprogrammercarelessness.Substitutionof=inplaceof==inaBooleantestiseasytodoandmostCandC++programmershavemadethismistakeatonetimeoranother.Otherinstancescanbetheresultofintricaciesofthelanguagedefinitionthatspecifieswhatpartofanexpressionmustbeevaluated.Forinstance,havinganassignmentexpressioninaBooleanstatementislikelyassumingthatthecompleteexpressionwillbeexecutedinallcases.However,thisisnotalwaysthecaseassometimesthetruth-valueoftheBooleanexpressioncanbedeterminedafteronlyexecutingsomeportionoftheexpression.Forinstance:
if ((a == b) || (c = (d-1)))
Should(a==b)bedeterminedtobetrue,thenthereisnoneedforthesubexpression(c=(d-1))tobeexecutedandassuch,theassignment(c=(d-1))willnotoccur.
Embeddingexpressionsinotherexpressionscanyieldunexpectedresults.Incrementanddecrementoperators(++and--)canalsoyieldunexpectedresultswhenmixedintoacomplexexpression.
Incorrectlycalculatedresultscanleadtoawidevarietyoferroneousprogramexecution.
6.25.4Applicablelanguagecharacteristics
Thisvulnerabilitydescriptionisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Alllanguagesaresusceptibletolikelyincorrectexpressions.
6.25.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Simplifyexpressions.• Donotuseassignmentexpressionsasfunctionparameters.Sometimestheassignmentmaynotbe
executedasexpected.Instead,performtheassignmentbeforethefunctioncall.• DonotperformassignmentswithinaBooleanexpression.Thisislikelyunintended,butifitisnot,then
movetheassignmentoutsideoftheBooleanexpressionforclarityandrobustness.• Usestaticanalysistoolsthatdetectandwarnofexpressionsthatincludeassignmentwithinthe
expression.
Deleted:
Deleted:
Deleted:
Deleted:
WG23/N0720
62 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
• Onsomerareoccasions,somestatementsintentionallydonothavesideeffectsanddonotcausecontrolflowtochange.Theseshouldbeannotatedthroughcommentsandmadeobviousthattheyareintentionallyno-opswithastatedreason.Ifpossible,suchrelianceonnullstatementsshouldbeavoided.Ingeneral,exceptforthoserareinstances,allstatementsshouldeitherhaveasideeffectorcausecontrolflowtochange.
6.25.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Languagesshouldconsiderprovidingwarningsforstatementsthatareunlikelytoberightsuchasstatementswithoutsideeffects.Anull(no-op)statementmayneedtobeaddedtothelanguageforthoserareinstanceswhereanintentionalnullstatementisneeded.Havinganullstatementaspartofthelanguagewillreduceconfusionastowhyastatementwithnosideeffectsispresentinthecode.
• Languagesshouldconsidernotallowingassignmentsusedasfunctionparameters.• LanguagesshouldconsidernotallowingassignmentswithinaBooleanexpression.• Languagedefinitionsshouldavoidsituationswhereeasilyconfusedsymbols(suchas=and==,or;and
:,or!=and/=)arevalidinthesamecontext.Forexample,=isnotgenerallyvalidinanifstatementinJavabecauseitdoesnotnormallyreturnaBooleanvalue.
6.26Deadanddeactivatedcode[XYQ]
6.26.1Descriptionofapplicationvulnerability
DeadandDeactivatedcodeiscodethatexistsintheexecutable,butwhichcanneverbeexecuted,eitherbecausethereisnocallpaththatleadstoit(forexample,afunctionthatisnevercalled),orthepathissemanticallyinfeasible(forexample,itsexecutiondependsonthestateofaconditionalthatcanneverbeachieved).
DeadandDeactivatedcodemaybeundesirablebecauseitmayindicatethepossibilityofacodingerror.Asecurityissueisalsopossibleifa“jumptarget”isinjected.Manysafetystandardsprohibitdeadcodebecausedeadcodeisnottraceabletoarequirement.
Alsocoveredinthisvulnerabilityiscodewhichisbelievedtobedead,butwhichisinadvertentlyexecuted.
DeadandDeactivatedcodeisconsideredseparatelyfromthedescriptionofUnusedVariable,whichisprovidedby[YZS].
6.26.2Crossreference
CWE:561.DeadCode570.ExpressionisAlwaysFalse571.ExpressionisAlwaysTrue
JSFAVRules:127and186MISRAC2012:2.1and4.4MISRAC++2008:0-1-1to0-1-10,2-7-2,and2-7-3
Deleted:
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 63
CERTCguidelines:MSC07-CandMSC12-CDO-178B/C
6.26.3Mechanismoffailure
DO-178BdefinesDeadandDeactivatedcodeas:
• Deadcode–Executableobjectcode(ordata)whichcannotbeexecuted(code)orused(data)inanoperationalconfigurationofthetargetcomputerenvironmentandisnottraceabletoasystemorsoftwarerequirement.
• Deactivatedcode–Executableobjectcode(ordata)whichbydesigniseither(a)notintendedtobeexecuted(code)orused(data),forexample,apartofapreviouslydevelopedsoftwarecomponent,or(b)isonlyexecuted(code)orused(data)incertainconfigurationsofthetargetcomputerenvironment,forexample,codethatisenabledbyahardwarepinselectionorsoftwareprogrammedoptions.
Deadcodeiscodethatexistsinanapplication,butwhichcanneverbeexecuted,eitherbecausethereisnocallpathtothecode(forexample,afunctionthatisnevercalled)orbecausetheexecutionpathtothecodeissemanticallyinfeasible,asin
integer i = 0; if (i == 0)
then fun_a(); else fun_b();
fun_b()isDeadcode,asonlyfun_a()caneverbeexecuted.
Compilersthatoptimizesometimesgenerateandthenremovedeadcode,includingcodeplacedtherebytheprogrammer.Thedeadnessofcodecanalsodependonthelinkingofseparatelycompiledmodules.
Thepresenceofdeadcodeisnotinitselfanerror.Theremayalsobelegitimatereasonsforitspresence,forexample:
• Defensivecode,onlyexecutedastheresultofahardwarefailure.• Codethatispartofalibrarynotrequiredintheprograminquestion.• Diagnosticcodenotexecutedintheoperationalenvironment.• Codethatistemporarilydeactivatedbutmaybeneededsoon.Thismayoccurasawaytomakesurethe
codeisstillacceptedbythelanguagetranslatortoreduceopportunitiesforerrorswhenitisreactivated.• Codethatismadeavailablesothatitcanbeexecutedmanuallyviaadebugger.
Suchcodemaybereferredtoasdeactivated.Thatis,deadcodethatistherebyintent.
Thereisasecondaryconsiderationfordeadcodeinlanguagesthatpermitoverloadingoffunctionsandotherconstructsthatusecomplexnameresolutionstrategies.Thedevelopermaybelievethatsomecodeisnotgoingtobeused(deactivated),butitsexistenceintheprogrammeansthatitappearsinthenamespace,andmaybeselectedasthebestmatchforsomeusethatwasintendedtobeofanoverloadingfunction.Thatis,althoughthedeveloperbelievesitisnevergoingtobeused,inpracticeitmaybeusedinpreferencetotheintendedfunction.
Deleted:
Deleted:
WG23/N0720
64 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
However,itmaybethecasethat,becauseofsomeothererror,thecodeisrenderedunreachable.Therefore,anydeadcodeshouldbereviewedanddocumented.
Beawarethatsomedefensivecode,suchasthatcreatedtocatchhardwareerror,maybeoptimizedawaybythecompiler.Useofoptimizationfencessuchasvolatileaccesses(consultlanguageandcompilermanuals)mayhelp.
6.26.4Applicablelanguagecharacteristics
Thisvulnerabilitydescriptionisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Languagesthatallowcodetoexistinaprogramorexecutable,whichcanneverbeexecuted.
6.26.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Removedeadcodefromanapplicationunlessitspresenceservesadocumentedpurpose.• Whenadeveloperidentifiescodethatisdeadbecauseaconditionalconsistentlyevaluatestothesame
value,thiscouldbeindicativeofanearlierbugoritcouldbeindicativeofinadequatepathcoverageinthetestregimen.Additionalinvestigationmaybeneededtoascertainwhythesamevalueisoccurring.
• Identifyanydeadcodeintheapplication,andprovideajustificationastowhyitisthere.• Ensurethatanycodethatwasexpectedtobeunusedisdocumentedasdeadcode.• Forcodethatappearstobedeadcodebutisinrealityaccessibleonlybyasynchronouseventsorerror
handlers,orpresentfordebuggingpurposes,preventtheoptimizationsthatremovethecodeinquestion.Examplesincludethejudicioususeofvolatileaccesses,pragmas,orcompilerswitches.
• Applystandardbranchcoveragemeasurementtoolsandensureby100%coveragethatallbranchesareneitherdeadnordeactivated.
• Usestaticanalysistoolstoidentifyunreachablecode.
6.26.6Implicationsforlanguagedesignandevolution
[None]
6.27Switchstatementsandstaticanalysis[CLL]
6.27.1Descriptionofapplicationvulnerability
Manyprogramminglanguagesprovideaconstruct,suchasaC-likeswitchstatement,thatchoosesamongmultiplealternativecontrolflowsbasedupontheevaluatedresultofanexpression.Theuseofsuchconstructsmayintroduceapplicationvulnerabilitiesifnotallpossiblecasesappearwithintheswitchorifcontrolunexpectedlyflowsfromonealternativetoanother.
6.27.2Crossreference
JSFAVRules:148,193,194,195,and196MISRAC2012:16.3-16.6
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 65
MISRAC++2008:6-4-3,6-4-5,6-4-6,and6-4-8CERTCguidelines:MSC01-CAdaQualityandStyleGuide:5.6.1and5.6.10
6.27.3Mechanismoffailure
Thefundamentalchallengewhenusingaswitchstatementistomakesurethatallpossiblecasesare,infact,treatedcorrectly.
6.27.4Applicablelanguagecharacteristics
Thisvulnerabilitydescriptionisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Languagesthatcontainaconstruct,suchasa switch statement,thatprovidesaselectionamongalternativecontrolflowsbasedontheevaluationofanexpression.
• Languagesthatdonotrequirefullcoverageofallpossiblealternativesofaswitchstatement.• Languagesthatprovideadefaultcase(choice)inaswitchstatement.
6.27.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Ensurethateveryvalidchoicehasabranchthatcoversthechoice.• Avoiddefaultbrancheswhereitcanbestaticallyshownthateachchoiceiscoveredbyabranch.• Useadefaultbranchthatinitiateserrorprocessingwherecoverageofallchoicesbybranchescannotbe
staticallyshown.• Usearestrictedsetofenumerationvaluestoimprovecoverageanalysiswherethelanguageprovides
suchcapability.• Avoid“flowingthrough”fromonecasetoanother.Evenifcorrectlyimplemented,itisdifficultfor
reviewersandmaintainerstodistinguishwhethertheconstructwasintendedorisanerrorofomission3F
5.• Incaseswhereflow-throughisnecessaryandintended,useanexplicitlycodedbranchtoclearlymarkthe
intent.Providecommentsexplainingtheintentioncanbehelpfultoreviewersandmaintainers.• Performstaticanalysistodetermineifallcasesare,infact,coveredbythecode.(Notethattheuseofa
defaultcasecanhampertheeffectivenessofstaticanalysissincethetoolcannotdetermineifomittedalternativeswereorwerenotintendedfordefaulttreatment.)
• Useothermeansofmitigationincludingmanualreview,boundstesting,toolanalysis,verificationtechniques,andproofsofcorrectness.
6.27.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Languagespecificationscouldrequirecompilerstoensurethatacompletesetofalternativesisprovidedincaseswherethevaluesetoftheswitchvariablecanbestaticallydetermined.
5Usingmultiplelabelsonindividualalternativesisnotaviolationofthisrecommendation,though.
Deleted: Deleted:
Deleted:
WG23/N0720
66 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
6.28Demarcationofcontrolflow[EOJ]
6.28.1Descriptionofapplicationvulnerability
Someprogramminglanguagesexplicitlymarktheendofanifstatementoraloop,whereasotherlanguagesmarkonlytheendofablockofstatements.Languagesofthelattercategoryarepronetooversightsbytheprogrammer,causingunintendedsequencesofcontrolflow.
6.28.2Crossreference
JSFAVRules:59and192MISRAC2012:15.6and15.7MISRAC++2008:6-3-1,6-4-1,6-4-2,6-4-3,6-4-8,6-5-1,6-5-6,6-6-1to6-6-5,and16-0-2Hatton18:Controlflow–ifstructureAdaQualityandStyleGuide:3,5.6.1through5.6.10
6.28.3Mechanismoffailure
Programmersmayrelyonindentationtodetermineinclusionofstatementswithinconstructs.Testingofthesoftwaremaynotrevealthatstatementsthatappeartobeincludedinaconstruct(duetoformatting)actuallylayoutsideofitbecauseoftheabsenceofaterminator.Moreover,foranestedif-then-elsestatementtheprogrammermaybeconfusedaboutwhichifstatementcontrolstheelsepartdirectly.Thiscanleadtounexpectedresults.
6.28.4Applicablelanguagecharacteristics
Thisvulnerabilitydescriptionisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Languagesthatcontainloopsandconditionalstatementsthatarenotexplicitlyterminatedbyan“end”construct.
6.28.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Wherethelanguagedoesnotprovidedemarcationoftheendofacontrolstructure,adoptaconventionformarkingtheclosingofaconstructthatcanbecheckedbyatool,toensurethatprogramstructureisapparent.
• Adoptprogrammingguidelines(preferablyaugmentedbystaticanalysis).Forexample,considertherulesdocumentedin6.29.2.
• Useothermeansofassurance,suchasproofsofcorrectness,analysiswithtools,anddynamicverificationtechniques.
• Usepretty-printersandsyntax-awareeditorstohelpfindsuchproblems.Beawarethatsuchtoolssometimesdisguisesucherrors.
• Wherethelanguagepermitssinglestatementsafterloopsandconditionalstatementsbutpermitsoptionalcompoundstatements(suchasCif (...) statement else statement;orPascal
Deleted:
Deleted:
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 67
if expression then statement else statement;)alwaysusethecompoundversion(i.e.C's{ ... }orPascal'sbegin ... end).
6.28.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Addingamodethatstrictlyenforcescompoundconditionalandloopingconstructswithexplicittermination,suchas“end if”oraclosingbracket.
• Syntaxforexplicitterminationofloopsandconditionalstatements.• Featurestoterminatenamedloopsandconditionalsanddetermineifthestructureasnamedmatches
thestructureasinferred.
6.29Loopcontrolvariables[TEX]
6.29.1Descriptionofapplicationvulnerability
Manylanguagessupportaloopingconstructwhosenumberofiterationsiscontrolledbythevalueofaloopcontrolvariable.Loopingconstructsprovideamethodofspecifyinganinitialvalueforthisloopcontrolvariable,atestthatterminatestheloopandthequantitybywhichitshouldbedecrementedorincrementedoneachloopiteration.
Insomelanguagesitispossibletomodifythevalueoftheloopcontrolvariablewithinthebodyoftheloop.Experienceshowsthatsuchvaluemodificationsaresometimesoverlookedbyreadersofthesourcecode,resultinginfaultsbeingintroduced.
Somelanguages,suchasC-basedlanguagesdonotexplicitlyspecifywhichofthevariablesappearinginaloopheaderisthecontrolvariablefortheloop.MISRAC[12]andMISRAC++[16]haveproposedalgorithmsfordeducingwhich,ifany,ofthesevariablesistheloopcontrolvariableintheprogramminglanguagesCandC++(thesealgorithmscouldalsobeappliedtootherlanguagesthatsupportaC-likefor-loop).
6.29.2Crossreference
JSFAVRule:201MISRAC2012:14.2MISRAC++2008:6-5-1to6-5-6
6.29.3Mechanismoffailure
Readersofsourcecodeoftenmakeassumptionsaboutwhathasbeenwritten.Acommonassumptionisthataloopcontrolvariableisnotmodifiedinthebodyoftheloop.Aprogrammermaywriteincorrectcodebasedonthisassumption.
6.29.4Applicablelanguagecharacteristics
Thisvulnerabilitydescriptionisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Languagesthatallowaloopcontrolvariabletobemodifiedinthebodyofitsassociatedloop.
Deleted:
Deleted:
Deleted:
Deleted:
WG23/N0720
68 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
6.29.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Donotmodifyaloopcontrolvariableinthebodyofitsassociatedloopbody.• Useastaticanalysistoolthatidentifiesthemodificationofaloopcontrolvariable.
6.29.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Languagedesignersshouldconsidertheadditionofanidentifiertypeforloopcontrolthatcannotbemodifiedbyanythingotherthantheloopcontrolconstruct.
6.30Off-by-oneerror[XZH]
6.30.1Descriptionofapplicationvulnerability
Aprogramusesanincorrectmaximumorminimumvaluethatis1moreor1lessthanthecorrectvalue.Thisusuallyarisesfromoneofanumberofsituationswheretheboundsasunderstoodbythedeveloperdifferfromthedesign,suchas:
• Confusionbetweentheneedfor<and<=or>and>=inatest.• Confusionastotheindexrangeofanalgorithm,suchas:beginninganalgorithmat1whentheunderlying
structureisindexedfrom0;beginninganalgorithmat0whentheunderlyingstructureisindexedfrom1(orsomeotherstartpoint);orusingthelengthofastructureasitsboundinsteadofthesentinelvalues.
• Failingtoallowforstorageofasentinelvalue,suchastheNULLstringterminatorthatisusedintheCandC++programminglanguages.
Theseissuesarisefrommistakesinmappingthedesignintoaparticularlanguage,inmovingbetweenlanguages(suchasbetweenlanguageswhereallarraysstartat0andotherlanguageswherearraysstartat1),andwhenexchangingdatabetweenlanguageswithdifferentdefaultarraybounds.
Theissuealsocanariseinalgorithmswhererelationshipsexistbetweencomponents,andtheexistenceofaboundsvaluechangestheconditionsofthetest.
Theexistenceofthispossibleflawcanalsobeaserioussecurityholeasitcanpermitsomeonetosurreptitiouslyprovideanunusedlocation(suchas0orthelastelement)thatcanbeusedforundocumentedfeaturesorhiddenchannels.
6.30.2Crossreference
CWE:193.Off-by-oneError
6.30.3Mechanismoffailure
Anoff-by-oneerrorcouldleadto:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 69
• anout-ofboundsaccesstoanarray(bufferoverflow),• incompletecomparisonsorcalculationmistakes,• areadfromthewrongmemorylocation,or• anincorrectconditional.
Suchincorrectaccessescancausecascadingerrorsorreferencestoinvalidlocations,resultinginpotentiallyunboundedbehaviour.
Off-by-oneerrorsarenotoftenexploitedinattacksbecausetheyaredifficulttoidentifyandexploitexternally,butthecascadingerrorsandboundary-conditionerrorscanbesevere.
6.30.4Applicablelanguagecharacteristics
Asthisvulnerabilityarisesbecauseofanalgorithmicerrorbythedeveloper,itcaninprincipleariseinanylanguage;however,itismostlikelytooccurwhen:
• Thelanguagereliesonthedeveloperhavingimplicitknowledgeofstructurestartandendindices(forexample,knowingwhetherarraysstartat0or1–orindeedsomeothervalue).
• Wherethelanguagereliesuponexplicitboundsvaluestoterminatevariablelengtharrays.
6.30.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Followasystematicdevelopmentprocess,useofdevelopment/analysistoolsandthoroughtestingareallcommonwaysofpreventingerrors,andinthiscase,off-by-oneerrors.
• Usestaticanalysistoolsthatwarnofpotentialoff-by-oneerrors. • Wherereferencesarebeingmadetoarrayindicesandthelanguagesprovideconstructstospecifythe
wholearrayorthestartingandendingindicesexplicitly(forexample,Adaprovidestheattributes'Firstand'Lastforeachdimension),usethelanguage-providedconstructsinsteadofnumericliterals.Wherethelanguagedoesnotprovidesuchconstructs,declarenamedconstantsandusetheminpreferencetonumericliterals.
• Wherethelanguagedoesnotencapsulatevariablelengtharrays,encapsulationshouldbeprovidedthroughlibraryobjectsandacodingstandarddevelopedthatrequiressucharraystoonlybeusedviathoselibraryobjects,sothedeveloperdoesnotneedtobeexplicitlyconcernedwithmanagingboundsvalues.
6.30.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Languagesshouldprovideencapsulationsforarraysthat:o Preventtheneedforthedevelopertobeconcernedwithexplicitboundsvalues.o Providethedeveloperwithsymbolicaccesstothearraystart,endanditerators.
Deleted: waysDeleted: xxxDeleted: xxxDeleted: theseshouldbeDeleted: dalwaysDeleted: Deleted: 'Deleted: theseDeleted: canbedeclaredDeleted: dDeleted: ’
WG23/N0720
70 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
6.31Structuredprogramming[EWD]
6.31.1Descriptionofapplicationvulnerability
Programsthathaveaconvolutedcontrolstructurearelikelytobemoredifficulttobehumanreadable,lessunderstandable,hardertomaintain,hardertostaticallyanalyze,moredifficulttomatchtheallocationandreleaseofresources,andmorelikelytobeincorrect.
6.31.2Crossreference
JSFAVRules:20,113,189,190,and191MISRAC2012:15.1-15.3,and21.4MISRAC++2008:6-6-1,6-6-2,6-6-3,and17-0-5CERTCguidelines:SIG32-CAdaQualityandStyleGuide:3,4,5.4,5.6,and5.7
6.31.3Mechanismoffailure
Lackofstructuredprogrammingcanleadto:
• Memoryorresourceleaks.• Error-pronemaintenance.• Designthatisdifficultorimpossibletovalidate.• Sourcecodethatisdifficultorimpossibletostaticallyanalyze.
6.31.4Applicablelanguagecharacteristics
Thisvulnerabilitydescriptionisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Languagesthatallowleavingaloopwithoutconsiderationfortheloopcontrol.• Languagesthatallowlocaljumps(gotostatement).• Languagesthatallownon-localjumps(setjmp/longjmpintheCprogramminglanguage).• Languagesthatsupportmultipleentryandexitpointsfromafunction,procedure,subroutineormethod.
6.31.5Avoidingthevulnerabilityormitigatingitseffects
Useonlythosefeaturesoftheprogramminglanguagethatenforcealogicalstructureontheprogram.Theprogramflowfollowsasimplehierarchicalmodelthatemploysloopingconstructssuchasfor,repeat,do,andwhile.
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Avoidusinglanguagefeaturessuchasgoto.• Avoidusinglanguagefeaturessuchascontinueand breakinthemiddleofloops.• Avoidusinglanguagefeaturesthattransfercontroloftheprogramflowviaajump.• Avoidtheuseofmultipleexitpointsfromafunction/procedure/method/subroutineunlessitcanbe
shownthatthecodewithmultipleexitpointsissuperior.
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 71
• Avoidmultipleentrypointstoafunction/procedure/method/subroutine.
6.31.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Languagesshouldsupportandfavorstructuredprogrammingthroughtheirconstructstotheextentpossible.
6.32Passingparametersandreturnvalues[CSJ]
6.32.1Descriptionofapplicationvulnerability
Nearlyeveryprocedurallanguageprovidessomemethodofprocessabstractionpermittingdecompositionoftheflowofcontrolintoroutines,functions,subprograms,ormethods.(Forthepurposeofthisdescription,thetermsubprogramwillbeused.)Tohaveanyeffectonthecomputation,thesubprogrammustchangedatavisibletothecallingprogram.Itcandothisbychangingthevalueofanon-localvariable,changingthevalueofaparameter,or,inthecaseofafunction,providingareturnvalue.Becausedifferentlanguagesusedifferentmechanismswithdifferentsemanticsforpassingparameters,aprogrammerusinganunfamiliarlanguagemayobtainunexpectedresults.
6.32.2Crossreference
JSFAVRules:20,116MISRAC2012:8.2,8.3,8.13,and17.1-17.3MISRAC++2008:0-3-2,7-1-2,8-4-1,8-4-2,8-4-3,and8-4-4CERTCguidelines:EXP12-CandDCL33-CAdaQualityandStyleGuide:5.2and8.3
6.32.3Mechanismoffailure
Themechanismsforparameterpassinginclude:callbyreference,callbycopy,andcallbyname.Thelastissospecializedandsupportedbysofewprogramminglanguagesthatitwillnotbetreatedinthisdescription.
Incallbyreference,thecallingprogrampassestheaddressesoftheargumentstothecalledsubprogram.Whenthesubprogramreferencesthecorrespondingformalparameter,itisactuallysharingdatawiththecallingprogram.Ifthesubprogramchangesaformalparameter,thenthecorrespondingactualargumentisalsochanged.Iftheactualargumentisanexpressionoraconstant,thentheaddressofatemporarylocationispassedtothesubprogram;thismaybeanerrorinsomelanguages.
Incallbycopy,thecalledsubprogramdoesnotsharedatawiththecallingprogram.Instead,formalparametersactaslocalvariables.Valuesarepassedbetweentheactualargumentsandtheformalparametersbycopying.Somelanguagesmaycontrolchangestoformalparametersbasedonlabelssuchasin,out,orinout.Therearethreecasestoconsider:callbyvalueforinparameters;callbyresultforoutparametersandfunctionreturnvalues;andcallbyvalue-resultforinoutparameters.Forcallbyvalue,thecallingprogramevaluatestheactualargumentsandcopiestheresulttothecorrespondingformalparametersthatarethentreatedaslocalvariablesbythesubprogram.Forcallbyresult,thevaluesofthelocalscorrespondingtoformalparametersarecopiedto
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted: Deleted:
Deleted:
Deleted:
WG23/N0720
72 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
thecorrespondingactualarguments.Forcallbyvalue-result,thevaluesarecopiedinfromtheactualargumentsatthebeginningofthesubprogram'sexecutionandbackouttotheactualargumentsatitstermination.
Theobviousdisadvantageofcallbycopyisthatextracopyoperationsareneededandexecutiontimeisrequiredtoproducethecopies.Particularlyifparametersrepresentsizableobjects,suchaslargearrays,thecostofcallbycopycanbehigh.Forthisreason,manylanguagesalsoprovidethecallbyreferencemechanism.Thedisadvantageofcallbyreferenceisthatthecallingprogramcannotbeassuredthatthesubprogramhasnotchangeddatathatwasintendedtobeunchanged.Forexample,ifanarrayispassedbyreferencetoasubprogramintendedtosumitselements,thesubprogramcouldalsochangethevaluesofoneormoreelementsofthearray.However,somelanguagesenforcethesubprogram'saccesstotheshareddatabasedonthelabelingofactualargumentswithmodes—suchasin,out,orinout orbyconstantpointers.
Anotherproblemwithcallbyreferenceisunintendedaliasing.Itispossiblethattheaddressofoneactualargumentisthesameasanotheractualargumentorthattwoargumentsoverlapinstorage.Asubprogram,assumingthetwoformalparameterstobedistinct,maytreattheminappropriately.Forexample,ifonecodesasubprogramtoswaptwovaluesusingtheexclusive-ormethod,thenacalltoswap(x,x)willzerothevalueofx.Aliasingcanalsooccurbetweenargumentsandnon-localobjects.Forexample,ifasubprogrammodifiesanon-localobjectasaside-effectofitsexecution,referencingthatobjectbyaformalparameterwillresultinaliasingand,possibly,unintendedresults.
Somelanguagesprovideonlysimplemechanismsforpassingdatatosubprograms,leavingittotheprogrammertosynthesizeappropriatemechanisms.Often,theonlyavailablemechanismistousecallbycopytopasssmallscalarvaluesorpointervaluescontainingaddressesofdatastructures.Ofcourse,thelatteramountstousingcallbyreferencewithnocheckingbythelanguageprocessor.Insuchcases,subprogramscanpassbackpointerstoanythingwhatsoever,includingdatathatiscorruptedorabsent.
Somelanguagesusecallbycopyforsmallobjects,suchasscalars,andcallbyreferenceforlargeobjects,suchasarrays.Thechoiceofmechanismmayevenbeimplementation-defined.Becausethetwomechanismsproducedifferentresultsinthepresenceofaliasing,itisveryimportanttoavoidaliasing.
Anadditionalproblemmayoccurifthecalledsubprogramfailstoassignavaluetoaformalparameterthatthecallerexpectsasanoutputfromthesubprogram.Inthecaseofcallbyreference,theresultmaybeanuninitializedvariableinthecallingprogram.Inthecaseofcallbycopy,theresultmaybethatalegitimateinitializationvalueprovidedbythecallerisoverwrittenbyanuninitializedvaluebecausethecalledprogramdidnotmakeanassignmenttotheparameter.Thiserrormaybedifficulttodetectthroughreviewbecausethefailuretoinitializeishiddeninthesubprogram.
Anadditionalcomplicationwithsubprogramsoccurswhenoneormoreoftheargumentsareexpressions.Insuchcases,theevaluationofoneargumentmighthaveside-effectsthatresultinachangetothevalueofanotherorunintendedaliasing.Implementationchoicesregardingorderofevaluationcouldaffecttheresultofthecomputation.ThisparticularproblemisdescribedinSide-effectsandOrderofEvaluationclause[SAM].
6.32.4Applicablelanguagecharacteristics
Thisvulnerabilitydescriptionisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
Deleted:
Deleted:
Deleted:
Deleted: hasn't
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted: Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 73
• Languagesthatprovidemechanismsfordefiningsubprogramswherethedatapassesbetweenthecallingprogramandthesubprogramviaparametersandreturnvalues.Thisincludesmethodsinmanypopularobject-orientedlanguages.
6.32.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Useavailablemechanismstolabelparametersasconstantsorwithmodeslikein,out,orinout.• Whenachoiceofmechanismsisavailable,passsmallsimpleobjectsusingcallbycopy.• Whenachoiceofmechanismsisavailableandthecomputationalcostofcopyingistolerable,passlarger
objectsusingcallbycopy.• Whenthechoiceoflanguageorthecomputationalcostofcopyingforbidsusingcallbycopy,thentake
safeguardstopreventaliasing:o Minimizeside-effectsofsubprogramsonnon-localobjects;whenside-effectsarecoded,ensure
thattheaffectednon-localobjectsarenotpassedasparametersusingcallbyreference.o Toavoidunintentionalaliasing,avoidusingexpressionsorfunctionsasactualarguments;instead
assigntheresultoftheexpressiontoatemporarylocalandpassthelocal.o Utilizetoolsorotherformsofanalysistoensurethatnon-obviousinstancesofaliasingareabsent.o Performreviewsoranalysistodeterminethatcalledsubprogramsfulfilltheirresponsibilitiesto
assignvaluestoalloutputparameters.
6.32.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Programminglanguagespecificationscouldprovidelabels—suchasin,out,andinout—thatcontrolthesubprogram’saccesstoitsformalparameters,andenforcetheaccess.
6.33Danglingreferencestostackframes[DCM]
6.33.1Descriptionofapplicationvulnerability
Manylanguagesallowtreatingtheaddressofalocalvariableasavaluestoredinothervariables.ExamplesaretheapplicationoftheaddressoperatorinCorC++,orofthe‘Accessor‘AddressattributesinAda.Insomelanguages,thisfacilityisalsousedtomodelthecall-by-referencemechanismbypassingtheaddressoftheactualparameterby-value.Anobvioussafetyrequirementisthatthestoredaddressshallnotbeusedafterthelifetimeofthelocalvariablehasexpired.Thissituationcanbedescribedasa“danglingreferencetothestack”.
6.33.2Crossreference
CWE:562.ReturnofStackVariableAddress
JSFAVRule:173MISRAC2012:4.1and18.6MISRAC++2008:0-3-1,7-5-1,7-5-2,and7-5-3
Deleted:
Deleted:
Deleted:
WG23/N0720
74 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
CERTCguidelines:EXP35-CandDCL30-CAdaQualityandStyleGuide:7.6.7,7.6.8,and10.7.6
6.33.3Mechanismoffailure
Theconsequencesofdanglingreferencestothestackcomeintwovariants:adeterministicallypredictablevariant,whichthereforecanbeexploited,andanintermittent,non-deterministicvariant,whichisnexttoimpossibletoelicitduringtesting.Thefollowingcodesampleillustratesthetwovariants;thebehaviourisnotlanguage-specific:
struct s { … }; typedef struct s array_type[1000]; array_type* ptr; array_type* F() { struct s Arr[1000]; ptr = &Arr; // Risk of variant 1; return &Arr; // Risk of variant 2; } … struct s secret; array_type* ptr2; ptr2 = F(); secret = (*ptr2)[10]; // Fault of variant 2 …
secret = (*ptr)[10]; // Fault of variant 1
Theriskofvariant1istheassignmentoftheaddressofArrtoapointervariablethatsurvivesthelifetimeofArr.Thefaultisthesubsequentuseofthedanglingreferencetothestack,whichreferencesmemorysincealteredbyothercallsandpossiblyvalidlyownedbyotherroutines.Aspartofacall-back,thefaultallowssystematicexaminationofportionsofthestackcontentswithouttriggeringanarray-bounds-checkingviolation.Thus,thisvulnerabilityiseasilyexploitable.Asafault,theeffectscanbemostastounding,asmemorygetscorruptedbycompletelyunrelatedcodeportions.(Alife-timecheckaspartofpointerassignmentcanpreventtherisk.Inmanycases,suchasthesituationsabove,thecheckisstaticallydecidablebyacompiler.However,forthegeneralcase,adynamiccheckisneededtoensurethatthecopiedpointervaluelivesnolongerthanthedesignatedobject.)
Theriskofvariant2isanidiom“seeninthewild”toreturntheaddressofalocalvariabletoavoidanexpensivecopyofafunctionresult,aslongasitisconsumedbeforethenextroutinecalloccurs.Theidiomisbasedontheill-foundedassumptionthatthestackwillnotbeaffectedbyanythinguntilthisnextcallisissued.Theassumptionisfalse,however,ifaninterruptoccursandinterrupthandlingemploysastrategycalled“stackstealing”,whichis,usingthecurrentstacktosatisfyitsmemoryrequirements.Thus,thevalueofArrcanbeoverwrittenbeforeitcanberetrievedafterthecallonF.Asthisfaultwillonlyoccuriftheinterruptarrivesafterthecallhasreturnedbutbeforethereturnedresultisconsumed,thefaultishighlyintermittentandnexttoimpossibletore-createduringtesting.Thus,itisunlikelytobeexploitable,butalsoexceedinglyhardtofindbytesting.Itcanbegintooccurafteracompletelyunrelatedinterrupthandlerhasbeencodedoraltered.Onlystaticanalysiscanrelativelyeasilydetectthedanger(unlessthecodecombinesitwithrisksofvariant1).Somecompilersissuewarningsfor
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted: Deleted: Deleted: Deleted: Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 75
thissituation;suchwarningsneedtobeheeded,andsomeformsofstaticanalysisareeffectiveinidentifyingsuchproblems.
6.33.4Applicablelanguagecharacteristics
Thisvulnerabilitydescriptionisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Theaddressofalocalentity(orformalparameter)ofaroutinecanbeobtainedandstoredinavariableorcanbereturnedbythisroutineasaresult.
• Nocheckismadethatthelifetimeofthevariablereceivingtheaddressisnolargerthanthelifetimeofthedesignatedentity.
6.33.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Donotusetheaddressoflocallydeclaredentitiesasstorable,assignableorreturnablevalue(exceptwhereidiomsofthelanguagemakeitunavoidable).Whensuchanaddressisstored,ensurethatthelifetimeofthevariablecontainingtheaddressiscompletelyenclosedbythelifetimeofthedesignatedobject.
• Neverreturntheaddressofalocalvariableastheresultofafunctioncall.
6.33.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Donotprovidemeanstoobtaintheaddressofalocallydeclaredentityasastorablevalue;or• Defineimplicitcheckstoimplementtheassuranceofenclosedlifetimeexpressedinsub-clause5ofthis
vulnerability.Notethat,inmanycases,thecheckisstaticallydecidable,forexample,whentheaddressofalocalentityistakenaspartofareturnstatementorexpression.
6.34Subprogramsignaturemismatch[OTR]
6.34.1Descriptionofapplicationvulnerability
Ifasubprogramiscalledwithadifferentnumberofparametersthanitexpects,orwithparametersofdifferenttypesthanitexpects,thentheresultswillbeincorrect.Dependingonthelanguage,theoperatingenvironment,andtheimplementation,theerrormightbeasbenignasadiagnosticmessageorasextremeasaprogramcontinuingtoexecutewithacorruptedstack.Thepossibilityofacorruptedstackprovidesopportunitiesforpenetration.
6.34.2Crossreference
CWE:628.FunctionCallwithIncorrectlySpecifiedArguments686.FunctionCallwithIncorrectArgumentType683.FunctionCallwithIncorrectOrderofArguments
Deleted: <#>
Formatted: Bulleted + Level: 1 + Aligned at: 0.63 cm + Tabafter: 1.27 cm + Indent at: 1.27 cm
Deleted: . ... [7]Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
WG23/N0720
76 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
JSFAVRule:108MISRAC2012:8.2-8.4,17.1,and17.3MISRAC++2008:0-3-2,3-2-1,3-2-2,3-2-3,3-2-4,3-3-1,3-9-1,8-3-1,8-4-1,and8-4-2CERTCguidelines:DCL31-C,andDCL35-C
6.34.3Mechanismoffailure
Whenasubprogramiscalled,theactualargumentsofthecallarepushedontotheexecutionstack.Whenthesubprogramterminates,theformalparametersarepoppedoffthestack.Ifthenumberandtypeoftheactualargumentsdonotmatchthenumberandtypeoftheformalparameters,thendependinguponthecallingmechanismusedbythelanguagetranslator,thepushandthepopwillnotbeconsistentand,ifso,thestackwillbecorrupted.Stackcorruptioncanleadtounpredictableexecutionoftheprogramandcanprovideopportunitiesforexecutionofunintendedormaliciouscode.
Thecompilationsystemsformanylanguagesandimplementationscanchecktoensurethatthelistofactualparametersandanyexpectedreturnmatchthedeclaredsetofformalparametersandreturnvalue(thesubprogramsignature)inbothnumberandtype.(Insomecases,programmersshouldobserveasetofconventionstoensurethatthisistrue.)However,whenthecallisbeingmadetoanexternallycompiledsubprogram,anobject-codelibrary,oramodulecompiledinadifferentlanguage,theprogrammermusttakeadditionalstepstoensureamatchbetweentheexpectationsofthecallerandthecalledsubprogram.
6.34.4Applicablelanguagecharacteristics
Thisvulnerabilitydescriptionisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Languagesthatdonotrequiretheirimplementationstoensurethatthenumberandtypesofactualargumentsareequaltothenumberandtypesoftheformalparameters.
• Implementationsthatpermitprogramstocallsubprogramsthathavebeenexternallycompiled(withoutameanstocheckforamatchingsubprogramsignature),subprogramsinobjectcodelibraries,andanysubprogramscompiledinotherlanguages.
6.34.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Uselanguageorcompilersupportorstaticanalysistoolstodetectmismatchesincallingsignaturesandtheactualsubprogram,particularlyinmultilingualenvironments.
• Takeadvantageofanymechanismprovidedbythelanguagetoensurethatsubprogramsignaturesmatch.
• Avoidanylanguagefeaturesthatpermitvariablenumbersofactualargumentswithoutamethodofenforcingamatchforanyinstanceofasubprogramcall.
• Takeadvantageofanylanguageorimplementationfeaturethatwouldguaranteematchingthesubprogramsignatureinlinkingtootherlanguagesortoseparatelycompiledmodules.
• Intensivelyreviewsubprogramcallswherethematchisnotguaranteedbytooling.• Ensurethatonlyatrustedsourceisusedwhenusingnon-standardimportedmodules.
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 77
6.34.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Languagespecifierscouldensurethatthesignaturesofsubprogramsmatchwithinasinglecompilationunitandcouldprovidefeaturesforassertingandcheckingthematchwithexternallycompiledsubprograms.
6.35Recursion[GDL]
6.35.1Descriptionofapplicationvulnerability
Recursionisanelegantmathematicalmechanismfordefiningthevaluesofsomefunctions.Itistemptingtowritecodethatmirrorsthemathematics.However,theuseofrecursioninacomputercanhaveaprofoundeffectontheconsumptionoffiniteresources,leadingtodenialofservice.
6.35.2Crossreference
CWE:674.UncontrolledRecursion
JSFAVRule:119MISRAC2012:17.2MISRAC++2008:7-5-4CERTCguidelines:MEM05-CAdaQualityandStyleGuide:5.6.6
6.35.3Mechanismoffailure
Recursionprovidesfortheeconomicaldefinitionofsomemathematicalfunctions.However,economicaldefinitionandeconomicalcalculationaretwodifferentsubjects.Itistemptingtocalculatethevalueofarecursivefunctionusingrecursivesubprogramsbecausetheexpressionintheprogramminglanguageisstraightforwardandeasytounderstand.However,theimpactonfinitecomputingresourcescanbeprofound.Eachinvocationofarecursivesubprogrammayresultinthecreationofanewstackframe,completewithlocalvariables.Ifstackspaceislimitedandthecalculationofsomevalueswillleadtoanexhaustionofresourcesresultingintheprogramterminating.
Incalculatingthevaluesofmathematicalfunctionstheuseofrecursioninaprogramisusuallyobvious,butthisisnottruewhenconsideringcomputeroperationsgenerally,especiallywhenprocessingerrorconditions.Forexample,finalizationofacomputingcontextaftertreatinganerrorconditionmightresultinrecursion(suchasattemptingtorecoverresourcesbyclosingafileafteranerrorwasencounteredinclosingthesamefile).Althoughsuchsituationsmayhaveotherproblems,theytypicallydonotresultinexhaustionofresourcesbutmayotherwiseresultinadenialofservice.
6.35.4Applicablelanguagecharacteristics
Thisvulnerabilitydescriptionisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted: Deleted: Deleted:
Deleted:
Deleted:
WG23/N0720
78 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
• Anylanguagethatpermitstherecursiveinvocationofsubprograms.
6.35.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Minimizetheuseofrecursion.• Convertingrecursivecalculationstothecorrespondingiterativecalculation.Inprinciple,anyrecursive
calculationcanberemodeledasaniterativecalculationwhichwillhaveasmallerimpactonsomecomputingresourcesbutwhichmaybeharderforahumantocomprehend.Thecosttohumanunderstandingmustbeweighedagainstthepracticallimitsofcomputingresource.
• Incaseswherethedepthofrecursioncanbeshowntobestaticallyboundedbyatolerablenumber,thenrecursionmaybeacceptable,butshouldbedocumentedfortheuseofmaintainers.
Itshouldbenotedthatsomelanguagesorimplementationsprovidespecial(moreeconomical)treatmentofaformofrecursionknownastail-recursion.Inthiscase,theimpactoncomputingeconomyisreduced.Whenusingsuchalanguage,tailrecursionmaybepreferredtoaniterativecalculation.
6.35.6Implicationsforlanguagedesignandevolution
[None]
6.36IgnorederrorStatusandunhandledexceptions[OYB]
6.36.1Descriptionofapplicationvulnerability
Unpredictedfaultsandexceptionalsituationsariseduringtheexecutionofcode,preventingtheintendedfunctioningofthecode.Theyaredetectedandreportedbythelanguageimplementationorbyexplicitcodewrittenbytheuser.Differentstrategiesandlanguageconstructsareusedtoreportsucherrorsandtotakeremedialaction.Seriousvulnerabilitiesarisewhendetectederrorsarereportedbutignoredornotproperlyhandled.
6.36.2Crossreference
CWE:754.ImproperCheckforUnusualorExceptionalConditionsJSFAVRules:115and208MISRAC2012:4.7MISRAC++2008:15-3-2and19-3-1CERTCguidelines:DCL09-C,ERR00-C,andERR02-C
6.36.3Mechanismoffailure
Thefundamentalmechanismoffailureisthattheprogramdoesnotreacttoadetectederrororreactsinappropriatelytoit.Executionmaycontinueoutsidetheenvelopeprovidedbyitsspecification,making
Deleted:
Deleted:
Deleted: Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 79
additionalerrorsorseriousmalfunctionofthesoftwarelikely.Alternatively,executionmayterminate.Themechanismcanbeeasilyexploitedtoperformdenial-of-serviceattacks.
Thespecificmechanismoffailuredependsontheerrorreportingandhandlingschemeprovidedbyalanguageorappliedidiomaticallybyitsusers.
Inlanguagesthatexpectroutinestoreporterrorsviastatusvariables,returncodes,orthread-localerrorindicators,theerrorindicationsneedtobecheckedaftereachcall.Asthesefrequentcheckscostexecutiontimeandclutterthecodeimmenselytodealwithsituationsthatmayoccurrarely,programmersarereluctanttoapplytheschemesystematicallyandconsistently.Failuretocheckforandhandleanarisingerrorconditioncontinuesexecutionasiftheerrorneveroccurred.Inmostcases,thiscontinuedexecutioninanill-definedprogramstatewillsoonerorlaterfail,possiblycatastrophically.
Theraisingandhandlingofexceptionswasintroducedintolanguagestoaddresstheseproblems.Theybundletheexceptionalcodeinexceptionhandlers,theyneednotcostexecutiontimeifnoerrorispresent,andtheywillnotallowtheprogramtocontinueexecutionbydefaultwhenanerroroccurs,sinceuponraisingtheexception,controlofexecutionisautomaticallytransferredtoahandlerfortheexceptionfoundonthecallstack.Theriskandthefailuremechanismisthatthereisnosuchhandler(unlessthelanguageenforcesrestrictionsthatguaranteesitsexistence),resultingintheterminationofthecurrentthreadofcontrol.Also,ahandlerthatisfoundmightnotbegearedtohandlethemultitudeoferrorsituationsthatarevectoredtoit.Exceptionhandlingisthereforeinpracticemorecomplexfortheprogrammerthan,forexample,theuseofstatusparameters.Furthermore,differentlanguagesprovideexception-handlingmechanismsthatdifferindetailsoftheirdesign,whichinturnmayleadtomisunderstandingsbytheprogrammer.
Thecauseforthefailuremightbesimplylazinessorignoranceonthepartoftheprogrammer,or,morecommonly,amismatchintheexpectationsofwherefaultdetectionandfaultrecoveryistobedone.Particularlywhencomponentsmeetthatemploydifferentfaultdetectionandreportingstrategies,theopportunityformishandlingrecognizederrorsincreasesandcreatesvulnerabilities.
Anothercauseofthefailureisthescantattentionthatmanylibraryproviderspaytodescribeallerrorsituationsthatcallsontheirroutinesmightencounterandreport.Inthiscase,thecallercannotpossiblyreactsensiblytoallerrorsituationsthatmightarise.Asyetanothercause,theerrorinformationprovidedwhentheerroroccursmaybeinsufficientlycompletetoallowrecoveryfromtheerror.
Differenterrorhandlingmechanismshavedifferentstrengthsandweaknesses.Dealingwithexceptionhandlinginsomelanguagescanstressthecapabilitiesofstaticanalysistoolsandcan,insomecases,reducetheeffectivenessoftheiranalysis.Inversely,theuseoferrorstatusvariablescanleadtoconfusinglycomplicatedcontrolstructures,particularlywhenrecoveryisnotpossiblelocally.Therefore,forsituationswherethehighestofreliabilityisrequired,thedecisionfororagainstexceptionhandlingdeservescarefulthought.Inanycase,exception-handlingmechanismsshouldbereservedfortrulyunexpectedsituationsandothersituationswherenolocalrecoveryispossible.Situationswhicharemerelyunusual,liketheendoffilecondition,shouldbetreatedbyexplicittesting—eitherpriortothecallwhichmightraisetheerrororimmediatelyafterward.Ingeneral,errordetection,reporting,correction,andrecoveryshouldnotbealateopportunisticadd-on,butshouldbeanintegralpartofasystemdesign.
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
WG23/N0720
80 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
6.36.4Applicablelanguagecharacteristics
Whethersupportedbythelanguageornot,errorreportingandhandlingisidiomaticallypresentinalllanguages.Ofcourse,vulnerabilitiescausedbyexceptionsrequirealanguagethatsupportsexceptions.
6.36.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Reserveexception-handlingmechanismsfortrulyunexpectedsituationsandothersituationswherenolocalrecoveryispossible.
• Handleexceptionsbytheexceptionhandlersofanenclosingconstructascloseaspossibletotheoriginoftheexceptionbutasfaroutasnecessarytobeabletodealwiththeerror.Considerpreventingimplicitexceptionsbycheckingtheerrorconditioninthecodepriortoexecutingtheconstructthatcausestheexception.
• Equally,checkerrorreturnvaluesorauxiliarystatusvariablesfollowingacalltoasubprogram,unlessitisdemonstratedthattheerrorconditionisimpossible.
• Whenfunctionsreturnerrorvalues,checktheerrorreturnvaluesbeforeprocessinganyotherreturneddata.
• Foreachroutine,documentallerrorconditions,matchingerrordetectionandreportingneeds,andprovidesufficientinformationforhandlingtheerrorsituation.
• Usestaticanalysistoolstodetectandreportmissingorineffectiveerrordetectionorhandling.• Whenexecutionwithinaparticularcontextisabandonedduetoanexceptionorerrorcondition,finalize
thecontextbyclosingopenfiles,releasingresourcesandrestoringanyinvariantsassociatedwiththecontext.
• Retreattoacontextwherethefaultcanbehandledcompletely(afterfinalizingandterminatingthecurrentcontext)whenitisnotappropriatetorepairanerrorsituationandretrytheoperation.
• Alwaysenableerrorcheckingprovidedbythelanguage,thesoftwaresystem,orthehardwareintheabsenceofaconclusiveanalysisthattheerrorconditionisrenderedimpossible.
• Carefullyreviewallerrorhandlingmechanisms,becauseofthecomplexityoferrorhandling.• Inapplicationswiththehighestrequirementsforreliability,usedefense-in-depthapproaches,for
example,checkingandhandlingerrorsevenifthoughttobeimpossible.
6.36.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Astandardizedsetofmechanismsfordetectingandtreatingerrorconditionsshouldbedevelopedsothatalllanguagestotheextentpossiblecouldusethem.Thisdoesnotmeanthatalllanguagesshouldusethesamemechanismsasthereshouldbeavariety,buteachofthemechanismsshouldbestandardized.
Deleted:
Deleted:
Formatted: Font:+Theme Body (Calibri)
Formatted: Font:
Formatted: Font:
Deleted: Equally,cDeleted: canbe
Deleted:
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 81
6.37Type-breakingreinterpretationofdata[AMV]
6.37.1Descriptionofapplicationvulnerability
Inmostcases,objectsinprogramsareassignedlocationsinprocessorstoragetoholdtheirvalue.Ifthesamestoragespaceisassignedtomorethanoneobject—eitherstaticallyortemporarily—thenachangeinthevalueofoneobjectwillhaveaneffectonthevalueoftheother.Furthermore,iftherepresentationofthevalueofanobjectisreinterpretedasbeingtherepresentationofthevalueofanobjectwithadifferenttype,unexpectedresultsmayoccur.
6.37.2Crossreference
JSFAVRules153and183MISRA2012:19.1,and19.2MISRAC++2008:4-5-1to4-5-3,4-10-1,4-10-2,and5-0-3to5-0-9CERTCguidelines:MEM08-CAdaQualityandStyleGuide:7.6.7and7.6.8
6.37.3Mechanismoffailure
Sometimesthereisalegitimateneedforapplicationstoplacedifferentinterpretationsuponthesamestoredrepresentationofdata.Themostfundamentalexampleisaprogramloaderthattreatsabinaryimageofaprogramasdatabyloadingit,andthentreatsitasaprogrambyinvokingit.Mostprogramminglanguagespermittype-breakingreinterpretationofdata,however,someofferlesserror-pronealternativesforcommonlyencounteredsituations.
Unintentionalormaliciousreinterpretationofdatacancauseoverwritingordisclosureofarbitrarymemoryregions.Inaddition,type-breakingreinterpretationofrepresentationpresentsobstaclestohumanunderstandingofthecode,theabilityoftoolstoperformeffectivestaticanalysis,andtheabilityofcodeoptimizerstodotheirjob.
Examplesinclude:
• Providingalternativemappingsofobjectsintoblocksofstorageperformedeitherstatically(suchasFortrancommon)ordynamically(suchaspointers).
• Uniontypes,particularlyunionsthatdonothaveadiscriminantstoredaspartofthedatastructure.(Discriminantsareadditionalcomponentsofthedatastructurethatdeterminethelayoutoftherestofthedata.Ifthediscriminantcapabilityisnotprovidedbythelanguage,thenitistheprogrammer’sresponsibilitytoensureconsistency).
• Operationsthatpermitastoredvaluetobeinterpretedasadifferenttype(suchastreatingtherepresentationofapointerasaninteger).
Inallofthesecasesaccessingthevalueofanobjectmayproduceanunanticipatedresult.
Deleted:
Deleted:
Deleted:
Deleted:
Deleted: Deleted: T
WG23/N0720
82 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
Arelatedproblem,thealiasingofparameters,occursinlanguagesthatpermitcallbyreferencebecausesupposedlydistinctparametersmightrefertothesamestoragearea,oraparameterandanon-localobjectmightrefertothesamestoragearea.ThatvulnerabilityisdescribedinPassingParametersandReturnValues[CSJ].
Itiseasiertoavoidoperationsthatreinterpretthesamestoredvalueasrepresentingadifferenttypewhenthelanguageclearlyidentifiesthem.Forexample,AdaforcestheprogrammertoexplicitlydeclaretheconversiontobeaninstantiationofUnchecked_Conversion.
Amuchmoredifficultsituationoccurswhenpointersareusedtoachievetypereinterpretation.Manylanguagesperformtype-checkingofpointersandplacerestrictionsontheabilityofpointerstoaccessarbitrarylocationsinstorage.
6.37.4Applicablelanguagecharacteristics
Thisvulnerabilitydescriptionisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Aprogramminglanguagethatpermitsmultipleinterpretationsofthesamebitpattern.
6.37.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Avoidreinterpretationperformedasamatterofconvenience;forexample,avoidanintegerpointertomanipulatecharacterstringdata.Whentype-breakingreinterpretationisnecessary,documentitcarefullyinthecode.
• Whenusinguniontypes,usediscriminatedunionsinpreferencetonon-discriminatedunions• Avoidoperationsthatreinterpretthesamestoredvalueasrepresentingadifferenttype.• Whenpointerswithdifferentunderlyingtypesareusedtoreinterpretdata,uselanguage-defined
capabilitiestoflagandchecksuchusage(suchasAda’s‘Validattribute),orusestaticanalysistoshowthattheoperationalwayssucceeds.
• Usestaticanalysistoolstolocatesituationswhereunintendedreinterpretationoccurs.• Asthepresenceofreinterpretationgreatlycomplicatesstaticanalysisforotherproblems,consider
segregatingintendedreinterpretationoperationsintodistinctsubprograms.
6.37.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Becausetheabilitytoperformreinterpretationissometimesnecessary,buttheneedforitisrare,programminglanguagedesignersmightconsiderputtingcautionlabelsonoperationsthatpermitreinterpretation.Forexample,theoperationinAdathatpermitsunconstrainedreinterpretationiscalledUnchecked_Conversion.
• Becauseofthedifficultieswithnon-discriminatedunions,programminglanguagedesignersmightconsiderofferinguniontypesthatincludedistinctdiscriminantswithappropriateenforcementofaccesstoobjects.
Moved (insertion) [1]Deleted: suchoperationsDeleted: Forexample,thenameofAda'sUnchecked_Conversionfunctionexplicitlywarnsoftheproblem.
Deleted: Deleted: Some
Deleted: Deleted: Otherspermitthefreeuseofpointers.Insuchcases,reviewthecodecarefullyinasearchforunintendedreinterpretationofstoredvalues.Thereforeexplicitlyidentifyplacesinthesourcecodewhereintendedreinterpretationsoccur.Make3(or2?)bullets.
Deleted:
Deleted: AI–Steve-fix
Deleted:
Deleted: .Deleted: Howeverthisvulnerabilitycannotbecompletelyavoidedbecausesomeapplicationsviewstoreddatainalternativeways.
Deleted: preferthe
Deleted: ofDeleted: .Deleted: Thisisatypeofaunionwhereastoredvalueindicateswhichinterpretationistobeplaceduponthedata.
Moved up [1]: Itiseasiertoavoidsuchoperationswhenthelanguageclearlyidentifiesthem.Forexample,thenameofAda'sUnchecked_Conversionfunctionexplicitlywarnsoftheproblem.Amuchmoredifficultsituationoccurswhenpointersareusedtoachievetypereinterpretation.Somelanguagesperformtype-checkingofpointersandplacerestrictionsontheabilityofpointerstoaccessarbitrarylocationsinstorage.Otherspermitthefreeuseofpointers.Insuchcases,reviewthecodecarefullyinasearchforunintendedreinterpretationofstoredvalues.Thereforeexplicitlyidentifyplacesinthesourcecodewhereintendedreinterpretationsoccur.Make3(or2?)bullets.
Deleted: inDeleted: ingDeleted:
Deleted: considersegregatingDeleted: Deleted: un
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 83
6.38Deepvs.shallowcopying[YAN]
6.39.1Descriptionofapplicationvulnerability
Whenstructurescontainingreferencesasdatacomponentsarecopied,onemustdecidewhetherthereferencesaretobecopied(shallowcopy)or,instead,theobjectsdesignatedbythereferencesaretobecopiedandareferencetothenewlycreatedobjectusedasthecomponentvalueofthecopiedstructure(deepcopy).Almostalllanguagesdefinestructure-copyingoperationsasshallowcopies,i.e.,thecopiedstructurereferencesthesameobject.Deepcopyingisalgorithmicallymorechallenging,sincenoobjectshallbecopiedtwicealthoughitmaybereachablebymultiplepathswithinthegraphspannedbythereferences.Further,deepcopyingmaybeexpensiveintimeandmemoryconsumption.If,however,ashallowcopyismadewhereadeepcopywasneeded,seriousaliasingproblemscanariseintheobjectsthatarepartofthegraphsspannedbythecopiedreferences.Subsequentmodificationofsuchanobjectisvisibleviaboththeoldandthenewstructure.
Anidenticalproblemariseswhenarrayindicesarestoredascomponentvalues(inlieuofpointersorreferences)andusedtoaccessobjectsinanarrayoutsidethecopieddatastructure.
6.38.2Crossreference
CWE:<<TBD>>JSFAVRule76,77,80CERTCguidelines:<<TBD>>AdaQualityandStyleGuide:<<TBD>>
6.38.3Mechanismoffailure
Problemswithshallowcopyingarisewhenvaluesintheobjects(transitively)referencedbytheoriginalorthecopyareassignedto:inadeepcopy,suchassignmentsaffectonlytheoriginalorthecopyofthegraph,respectively;inashallowcopy,thevalueoftheobjectischangedinbothgraphs,whichmaynothavebeentheintentionoftheprogrammer.Consequently,theproblemmaymanifestitselfonlyduringmaintenancewhen,forthefirsttime,suchasassignmenttoacontainedobjectisintroduced,whileshallowcopyingwasoriginallychosenforreasonsofefficiencybutrelyingontheabsenceofassignments.
Knowledgeoftheuseofshallowcopyinginlieuofdeepcopyingcanbeexploitedinattacksbycausingunintendedchangesindatastructuresviathedescribedaliasingeffect.
Theexposureandeffectsaresimilartoanyotherunintendedaliasing,suchasCSJPassingParametersandReturnValues.
6.38.4Applicablelanguagecharacteristics
Thisvulnerabilitydescriptionisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Languagesthathavepointersorreferencesaspartofcompositedatastructures.• Languagesthatsupportarrays.
Deleted: ]
Deleted:
WG23/N0720
84 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
6.38.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Useshallowcopyingonlywherethealiasingcausedisintended.• Usedeepcopyingifthereisanypossibilitythatthealiasingofashallowcopywouldaffecttheapplication
adversely,orifindoubt.• Useabstractionstoensuredeepcopieswhereneeded,e.g.,by(re-)definingassignmentoperations,
constructors,andotheroperationsthatcopycomponentvalues.
6.38.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Providemechanismstocreateabstractionsthatguaranteedeepcopyingwhereneeded.
6.39Memoryleaksandheapfragmentation[XYL]
6.39.1Descriptionofapplicationvulnerability
Amemoryleakoccurswhensoftwaredoesnotreleaseallocatedmemoryafteritceasestobeused.Repeatedoccurrencesofamemoryleakcanconsumeconsiderableamountsofavailablememory.Amemoryleakcanbeexploitedbyattackerstogeneratedenial-of-servicebycausingtheprogramtoexecuterepeatedlyasequencethattriggerstheleak.Moreover,amemoryleakcancauseanylong-runningcriticalprogramtoshutdownprematurely.
6.39.2Crossreference
CWE:401.FailuretoReleaseMemoryBeforeRemovingLastReference(aka‘MemoryLeak’)
JSFAVRule:206MISRAC2012:4.12CERTCguidelines:MEM00-CandMEM31-CAdaQualityandStyleGuide:5.4.5,5.9.2,and7.3.3
6.39.3Mechanismoffailure
Asaprocessorsystemruns,anymemorytakenfromdynamicmemoryandnotreturnedorreclaimed(bytheruntimesystem,theapplication,oragarbagecollector)afteritceasestobeused,mayresultinfuturememoryallocationrequestsfailingforlackoffreespace.
Alternatively,memoryclaimedandreturnedcancausetheheaptofragmentintoprogressivelysmallerblocks,which,withtheusualallocators,willresultinahighermemoryconsumptionandsteadilyincreasingsearchtimesforblocksofsuitablesize,untilthesystemspendsmostoftheCPU-timeforsearchingtheheapforsuitableblocks.
Deleted: means
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 85
Eitherconditioncanthusresultinamemoryexhaustionexception,progressivelyslowerperformancebytheallocatingapplication,programterminationorasystemcrash.
Ifanattackercandeterminethecauseofanexistingmemoryleakorcanincreasetheallocationrateforblocksofdifferentsizes,theattackerwillbeabletocausetheapplicationtoleakorfragmentquicklyandthereforecausetheapplicationtocrashorfailtoperformwithinacceptabletimelimits.Denial-of-Serviceattackscanthusoccur.
6.39.4Applicablelanguagecharacteristics
Thisvulnerabilitydescriptionisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Languagesreclaimmemoryunderprogrammercontrolcanexhibitheapfragmentationandmemoryleaks.
• Languagesthatsupportmechanismstodynamicallyallocatememoryandemploygarbagecollectioncanexhibitmemoryleaks.
6.39.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Usegarbagecollectorsthatreclaimmemorynolongeraccessiblebytheapplication.Somegarbagecollectorsarepartofthelanguagewhileothersareadd-ons.
• Insystemswithgarbagecollectors,setallnon-localpointersorreferencestonull,whenthedesignateddataisnolongerneeded,sincethedatatransitivelyreachablefromsuchapointerorreferencewillnotbegarbage-collectedotherwise,effectivelycausingmemoryleaks.
• Insystemswithoutgarbagecollectors,causedeallocationofthedatabeforethelastpointerorreferencetothedataislost.
• Allocateandfreememoryatthesamelevelofabstraction,andideallyinthesamecodemodule.Allocatingandfreeingmemoryindifferentmodulesandlevelsofabstractionmaymakeitdifficultfordeveloperstomatchrequeststofreestoragewiththeappropriatestorageallocationrequest.Thismaycauseconfusionregardingwhenandifablockofmemoryhasbeenallocatedorfreed,leadingtomemoryleaks.
• UseStoragepoolswhenavailableincombinationwithstrongtyping.Storagepoolsareaspecializedmemorymechanismwhereallofthememoryassociatedwithaclassofobjectsisallocatedfromaspecificboundedregionsuchthatstorageexhaustioninonepooldoesnotaffectthecodeoperatingonothermemory.
• Usestoragepoolsofequally-sizedblockstoavoidfragmentationwithineachstoragepool.Ifnecessary,provideapplication-specific(de-)allocatorstoachievethisfunctionality.
• Avoidtheuseofdynamicallyallocatedstorageentirely,orallocateonlyduringsysteminitializationandneverallocateoncethemainexecutioncommences,particularlyinsafety-criticalsystemsandlongrunningsystems.
• Usestaticanalysis,whichcansometimesdetectwhenallocatedstorageisnolongerusedandhasnotbeenfreed.
Deleted:
Deleted:
Deleted:
WG23/N0720
86 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
6.39.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Languagescanprovidesyntaxandsemanticstoguaranteeprogram-widethatdynamicmemoryisnotused(suchastheconfigurationpragmas featureofferedbysomeprogramminglanguages).
• Languagescandocumentorspecifythatimplementationsmustdocumentchoicesfordynamicmemorymanagementalgorithms,tohopedesignersdecideonappropriateusagepatternsandrecoverytechniquesasnecessary
6.40Templatesandgenerics[SYM]
6.40.1Descriptionofapplicationvulnerability
Manylanguagesprovideamechanismthatallowsobjectsand/orfunctionstobedefinedparameterizedbytypeandtheninstantiatedforspecifictypes.InC++andrelatedlanguages,thesearereferredtoas“templates”,andinAdaandJava,“generics”.Toavoidhavingtokeepwriting‘templates/generics’,inthisclausethesewillsimplybereferredtocollectivelyasgenerics.
Usedwell,genericscanmakecodeclearer,morepredictableandeasiertomaintain.Usedbadly,theycanhavethereverseeffect,makingcodedifficulttoreviewandmaintain,leadingtothepossibilityofprogramerror.
6.40.2Crossreference
JSFAVRules:101,102,103,104,and105MISRAC++2008:14-6-1,14-6-2,14-7-1to14-7-3,14-8-1,and14-8-2CERTC++:AdaQualityandStyleGuide:8.3.1through8.3.8,and8.4.2
6.40.3Mechanismoffailure
Thevalueofgenericscomesfromhavingasinglepieceofcodethatsupportssomebehaviourinatypeindependentmanner.Thissimplifiesdevelopmentandmaintenanceofthecode.Itshouldalsoassistintheunderstandingofthecodeduringreviewandmaintenance,byprovidingthesamebehaviourforalltypeswithwhichitisinstantiated.
Problemsarisewhentheuseofagenericactuallymakesthecodehardertounderstandduringreviewandmaintenance,bynotprovidingconsistentbehaviour.
Inmostcases,thegenericdefinitionwillhavetomakeassumptionsaboutthetypesitcanlegallybeinstantiatedwith.Forexample,asortfunctionrequiresthattheelementstobesortedcanbecopiedandcompared.Iftheseassumptionsarenotmet,theresultislikelytobeacompilererror.Forexampleifthesortfunctionisinstantiatedwithauserdefinedtypethatdoesnothavearelationaloperator.Where‘misuse’ofagenericleadstoacompilererror,thiscanberegardedasadevelopmentissue,andnotasoftwarevulnerability.
Confusion,andhencepotentialvulnerability,canarisewheretheinstantiatedcodeisapparentlyinvalid,butdoesnotresultinacompilererror.Forexample,agenericclassdefinesasetofmembers,asubsetofwhichrelyona
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted: n’tDeleted:
Deleted: n’t
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 87
particularpropertyoftheinstantiationtype(suchasagenericcontainerclasswithasortmemberfunction,onlythesortfunctionreliesontheinstantiatingtypehavingadefinedrelationaloperator).Insomelanguages,suchasC++,ifthegenericisinstantiatedwithatypethatdoesnotmeetalltherequirementsbuttheprogramneversubsequentlymakesuseofthesubsetofmembersthatrelyonthepropertyoftheinstantiatingtype,thecodewillcompileandexecute(forexample,thegenericcontainerisinstantiatedwithauserdefinedclassthatdoesnotdefinearelationaloperator,buttheprogramnevercallsthesortmemberofthisinstantiation).Whenthecodeisreviewedthegenericclasswillappeartoreferenceamemberoftheinstantiatingtypethatdoesnotexist.
Theproblemasdescribedinthetwopriorparagraphscanbereducedbyalanguagefeature(suchastheconcepts
languagefeaturebeingdesignedbytheC++committee).(RESEARCH–AIClive.).
Similarconfusioncanariseifthelanguagepermitsspecificmethodsofaninstanceofagenerictobeexplicitlydefined,ratherthanusingthecommoncode,sothatbehaviourisnotconsistentforallinstantiations.Forexample,forthesamegenericcontainerclass,thesortmembernormallysortstheelementsofthecontainerintoascendingorder.Insomelanguages,a‘specialcase’canbecreatedfortheinstantiationofthegenericwithaparticulartype.Forexample,thesortmemberfora‘float’containermaybeexplicitlydefinedtoprovidedifferentbehaviour,saysortingtheelementsintodescendingorder.Specializationthatdoesnotaffecttheapparentbehaviouroftheinstantiationisnotanissue.
(C++-specifictext,movewhenappropriate–AIClive.).Again,forC++,therearesomeirregularitiesinthe
semanticsofarraysandpointersthatcanleadtothegenerichavingdifferentbehaviourfordifferent,but
apparentlyverysimilar,types.Insuchcases,specializationcanbeusedtoenforceconsistentbehaviour.
6.40.4Applicablelanguagecharacteristics
Thisvulnerabilityisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Languagesthatpermitdefinitionsofobjectsorfunctionstobeparameterizedbytype,forlaterinstantiationwithspecifictypes,suchas:
o TemplatesinC++o GenericsinAda,Java.
6.40.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Documentthepropertiesofaninstantiatingtypenecessaryforagenerictobevalid.• Ifaninstantiatingtypehastherequiredproperties,ensurethatalloperationsofthegenericarevalidor
areunavailable,whetheractuallyusedintheprogramornot.• Avoid,orcarefullydocument,any‘specialcases’whereagenericisinstantiatedwithaspecifictypebut
doesnotbehaveasitdoesforothertypes.
6.40.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
Deleted:
Deleted: n’t
Deleted: n’t
Deleted:
Deleted: n’t
Deleted: Deleted: Erhard
Deleted:
Deleted: Deleted: n’tDeleted:
Deleted:
Deleted: n’t
WG23/N0720
88 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
• Languagespecifiersshouldstandardizeonacommon,uniformterminologytodescribegenerics/templatessothatprogrammersexperiencedinonelanguagecanreliablylearnandrefertothetypesystemofanotherlanguagethathasthesameconcept,butwithadifferentname.
• Languagespecifiersshoulddesigngenericsinsuchawaythatanyattempttoinstantiateagenericwithconstructsthatdonotprovidetherequiredcapabilitiesresultsinacompile-timeerror.
• Languagespecifiersshouldprovideanassertionmechanismforcheckingpropertiesatrun-time,forthosepropertiesthatcannotbecheckedatcompiletime.Itshouldbepossibletoinhibitassertioncheckingifefficiencyisaconcern.
6.41Inheritance[RIP]
6.41.1Descriptionofapplicationvulnerability
Inheritance,theabilitytocreateenhancedand/orrestrictedobjectclassesbasedonexistingobjectclassescanintroduceanumberofvulnerabilities,bothinadvertentandmalicious.BecauseInheritanceallowstheoverridingofmethodsoftheparentclassandbecauseobjectorientedsystemsaredesignedtoseparateandencapsulatecodeanddata,itcanbedifficulttodeterminewhereinthehierarchyaninvokedmethodisactuallydefined.Also,sinceanoverridingmethoddoesnotneedtocallthemethodintheparentclassthathasbeenoverridden,essentialinitializationandmanipulationofclassdatamaybebypassed.Thiscanbeespeciallydangerousduringconstructoranddestructormethods.
Languagesthatallowmultipleinheritanceaddadditionalcomplexitiestotheresolutionofmethodinvocations.Differentobjectbrokeragesystemsmayresolvethemethodidentitytodifferentclasses,basedonhowtheinheritancetreeistraversed.
6.41.2Crossreference
JSFAVRules:78,79,80,81,86,87,88,89,89,90,91,92,93,94,95,96and97MISRAC++2008:0-1-12,8-3-1,10-1-1to10-1-3,and10-3-1to10-3-3CERTC++guidelines:AdaQualityandStyleGuide:9(completeclause)
6.41.3Mechanismoffailure
Theuseofinheritancecanleadtoanexploitableapplicationvulnerabilityornegativelyimpactsystemsafetyinseveralways:
• Executionofmaliciousredefinitions,thiscanoccurthroughtheinsertionofaclassintotheclasshierarchythatoverridescommonlycalledmethodsintheparentclasses.
• Accidentalredefinition,whereamethodisdefinedthatinadvertentlyoverridesamethodthathasalreadybeendefinedinaparentclass.
• Accidentalfailureofredefinition,whenamethodisincorrectlynamedortheparametersarenotdefinedproperly,andthusdoesnotoverrideamethodinaparentclass.
• Breakingofclassinvariants,thiscanbecausedbyredefiningmethodsthatinitializeorvalidateclassdatawithoutincludingthatinitializationorvalidationintheoverridingmethods.
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 89
• Considertheinteractionofautomaticallygeneratedmemberfunctionswiththedirectreadingandwritingofvisibleclassmembers.
Thesevulnerabilitiescanincreasedramaticallyasthecomplexityofthehierarchyincreases,especiallyintheuseofmultipleinheritance.
Asmethodsareinheritedfrommultiplechainsofancestors,thedeterminationofwhichmethodsimplementationsexistandarebeingcalled,becomesincreasinglymoredifficultfortheprogrammer.Understandingwhichmethodsanddatacomponentsapplytoagiven(sub)classbecomesexceedinglydifficultifthesemethodsorcomponentsareinheritedhomographs(i.e.,datacomponentswithidenticalnamesormethodswithidenticalsignatures).Differentlanguageshavedifferentrulestoresolvetheresultingambiguities.Misunderstandingsleadtoinadvertentcodingerrors.Thecomplexityincreasesevenmorewhenmultipleinheritanceisusedtomodel„has-a“-relationships(seealso<<referencetoBLP,Liskov>>):methodsneverintendedtobeapplicabletoinstancesofasubclassareinheritednevertheless.Forexample,aninstanceofclassaircraftCarriermaybe„turn“edmerelybecauseitobtaineditspropulsionscrewbya„has-a“-inheritancewith„turn“beinganobviouslymeaningfulmethodfortheclassofpropulsionScrew.Meanwhiletheuserhasaquitedifferentexpectationofwhatitmeanstoturnanaircraftcarrier.ThecomplicationsincreaseifthecarrierinheritstwicefromtheclasspropulsionScrewbecauseithastwopropulsionscrews.
Finally,ifambiguitiesinmethodorcomponentnamingsareresolvedbypreferencerules,changesintheexecutionofmethodscanbeintroducedbyaddingyetanotherunrelatedbuthomographicmethodordatadeclarationanywhereisthehierarchiesofancestorclassesduringmaintenanceofthecode.Maliciousimplementationscanthusbeaddedwitheachreleaseofanobject-orientedlibraryandaffectthebehaviorofpreviouslyverifiedcode.(seealso<<referencetoBJL,namespaces>>)
Themechanismoffailurefortheseadditionaldangerscausedbymultipleinheritanceistheinadvertentuseofthewrongdatacomponentsormethods.Knowledgeofsuchincorrectusemightbeexploitable,asinstancesoftheaffected(sub)classmaybecorruptedbyinappropriateoperations.
6.41.4Applicablelanguagecharacteristics
Thisvulnerabilitydescriptionisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Languagesthatallowsingleandmultipleinheritances.
6.41.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Avoidtheuseofmultipleinheritancewheneverpossible.• Providecompletedocumentationofallencapsulateddata,andhoweachmethodaffectsthatdatafor
eachobjectinthehierarchy.• Inheritonlyfromtrustedsources,and,wheneverpossible,checktheversionoftheparentclassesduring
compilationand/orinitialization.• Provideamethodthatprovidesversioninginformationforeachclass.• Prohibittheuseofvisibleinheritancefor“has-a”relationships.
Deleted:
Deleted:
WG23/N0720
90 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
• Usecomponentsoftherespectiveclassfor“has-a”-relationships.• Avoidthecreationofbaseclassesthatarebothvirtualandnon-virtualinthesamehierarchy.(Clive-C++)
6.41.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Languagespecificationshouldincludethedefinitionofacommonversioningmethod.• Compilersshouldprovideanoptiontoreporttheclassinwhicharesolvedmethodresides.• Runtimeenvironmentsshouldprovideatraceofallruntimemethodresolutions.
6.42ViolationsoftheLiskovsubstitutionprincipleorthecontractmodel[BLP]
6.42.1Descriptionofapplicationvulnerability
Objectorientationtypicallyallowspolymorphicvariablescontainingvaluesofsubclassesofthedeclaredclassofthevariable.Methodsofthedeclaredclassofareceivingobjectcanbeinvokedandthecallerhastherighttoexpectthatthesemanticsoftheinterfacecalleduponareobservedregardlessoftheprecisenatureofthevalueofthereceivingobject.Similarly,theexistenceofaccessedcomponentsofthedeclaredclassneedstobeensured.Instancesofsubclassesthusneedtobebothtechnicallyandlogicallyspecializedinstancesoftheparentclass.ThisisthebasisoftheLiskovprinciple.
TheLiskovPrinciplestatesthataninstanceofasubclassisalwaysaninstanceofthesuperclassaswellifoneignorestheaddedspecializations.Itimpliesthatinheritanceisusedonlyifthereisalogical“is-a”-relationshipbetweenthesubclassandthesuperclass.Moreover,preconditionsofmethodscanatmostbeweakenedandneverstrengthenedastheyareredefinedforasubclass.Inversely,postconditionscanatmostbestrengthenedandneverbeweakenedbysucharedefinition.Thecallerofaninterfaceneedstoguaranteeonlythepreconditionsoftheinterfaceandisallowedtorelyonitspostconditions.TherulesstatedmakesureofthispropertywhichisalsoknownastheContractModel.
ViolationsoftheLiskovPrincipleortheContractModelcanresultinsystemmalfunctionsasadditionalpreconditionsofredefinitionsorpromisedpostconditionsofinterfacesarenotmet.
Analternativeinheritancesemanticsisthatof“has-a”-relationships,usuallyappearinginprogramsinlanguageswithmultipleinheritance,wheretheparadigmissometimesreferredtoasa“mix-in”.ItisinstarkconflictwiththeLiskowPrinciple:Apolymorphicvariablemotorofclassengineshouldnotbeabletoholdacar,merelybecausethesubclasscarwascreatedbyamix-inoftheclassenginetotheclassvehicle.
Theprinciplesstatedaboveapplytoimplicitaswellasexplicitpreconditionsandpostconditions.Explicitconditionspermitformalreasoningtoolstobeapplied.
6.42.2Crossreference
CWE:(cwe)JSFAVRules:89,91,92,93CERTC++guidelines:(Clive??)AdaQualityandStyleGuideLnone)
Deleted: Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted: :Deleted: WIKIBooksversion???
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 91
6.42.3Mechanismoffailure
Whenaclientcallsthemethodofaclasswhichredispatchestotheimplementationofasubclasswithastrengthenedprecondition,theclienthasmechanismtoknowabouttheaddedpreconditionstobesatisfied.Hencethecallmayfailonaviolatedprecondition.Similarly,ifthecalledimplementationhasaweakerpostcondition,thepostconditionassertedtotheclientmightnotbesatisfied.Asaconsequence,theclientmayfail.Failingtomeetpreconditionsortoguaranteepostconditionsisboundtocauseexceptionsorsystemfailures.Thespecificscenariosareextensiveandrangefromfaultsthathappentobehandledbythesystemtocompletelossofsecurityandsafety.
Usingvisibleinheritancetoimplementa“has-a”-relationshipsdeterioratesclassdesignandtherebymaybethecauseofconsequentialerrors.Thereisnoimmediatefailuremode,however.
6.42.4Applicablelanguagecharacteristics
Thisvulnerabilitydescriptionisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Languagesthathavepolymorphicvariables,particularlyobject-orientedlanguages.• Languagesthatprovideinheritanceamongclasses.
6.42.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Obeyallpreconditionsandpostconditionsofeachmethod,whethertheyarespecifiedinthelanguageornot.
• Prohibitthestrengtheningofpreconditions(specifiedornot)byredefinitionsofmethods.• Prohibittheweakeningofpostconditions(specifiedornot)byredefinitionsofmethods.• Prohibittheuseofvisibleinheritancefor“has-a”relationships.Usecomponentsoftherespectiveclass
for“has-a”-relationshipsinstead.• Usestaticanalysistoolsthatidentifymisuseofinheritanceinthecontractmodel.
6.42.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Providelanguagemechanismstoformallyspecifypreconditionsandpostconditions.
6.43Redispatching[PPH]
6.43.1Descriptionofapplicationvulnerability
Whenverysimilarfunctionalityisprovidedbymethodsorinterfaceswithvaryingparameterstructures,afrequentlyfoundimplementationstrategyistodesignateoneofthemasthe“workhorse”andhaveallotherscallonittoperformthe(common)work.Aprimeexampleareconstructororinitializationmethodswheredifferentsetsofinitialvaluesforcertaincomponentsareprovidedandtheremainingcomponentsaresettodefaultvalues.
Deleted:
Deleted:
Deleted:
Deleted:
WG23/N0720
92 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
Whenthesemanticsofinnercallsofdispatchingmethodsaskfordispatchinginturn,thecallissaidtobe“redispatching”.Inthiscase,thefollowingscenariocanevolve:InclassC,theimplementationofmethodAdispatchestomethodB,theworkhorse.InaderivedclassCD,theimplementationofBneedstobechanged.TheprogrammerfindsthesignatureoftheinheritedmethodAmatchinghisneedsandcallsAaspartoftheredefinitionofB.TheoutcomeofapreviouslycorrectdispatchingcallonBinCforapolymorphicvariableofclassCholdingareferencetoanobjectofclassCDnowcausesinfiniterecursionbetweentheredefinedmethodBandtheinheritedmethodAofclassCD.
Thisvulnerabilityisnotrestrictedtotheexampleabove,butcanhappenwheneverthedesigncallsformultipleservicesconvergingtoasingleimplementation.
6.43.2Crossreference
CWE:(none)JSFAVRules:(none)MISRAC++:(none)CERTC++guidelines:(none)AdaQualityandStyleGuide:(none)
6.43.3Mechanismoffailure
Themechanismistheintrinsiccallsemanticsofthelanguage.Ifitdemandsdispatchingfornestedmethodcalls,thefailurescenarioisguaranteed.Whiletheexampleaboveistractable,theinfiniterecursioncaninvolvemultipleobjectsalongareferencechainand,thus,itbecomesquicklyundecidablewhethersuchasituationexistsornot.Evenforsimplecases,avoidancerequiresknowledgeabouttheimplementationofallcalledmethodsinheritedfromsuperclassesandneedstoapplythisknowledgetransitively.Sucharequirementisdiametricallyopposedtofundamentalsoftwareengineeringaxioms.
Ithasbeenshownthatreleasedlibrarieshavecontainedmanyinstancesofinfiniterecursions.
Maliciousexploitofthevulnerabilityaddsasubclassthatcontainsthisinfiniterecursionconditionallyonsometriggervalue.Therecursioncanbesufficientlyobscuredsothatnoanalysistoolorreviewercandetectitwithanycertainty.Thesystemcanthenbecausedtofaultwithastackoverflowanytimethistriggerisused.ThevulnerabilitycanthusbeusedforDenial-of-Serviceattacks.
6.43.4Applicablelanguagecharacteristics
Thisvulnerabilitydescriptionisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Languagesthatdemandorallowdispatchingforcallswithindispatchingoperations.
6.43.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 93
• Enforceaprinciplethat,evenacrossclasshierarchies,convergingservicesuseasingleimplementation• Agreeonanddocumentaredispatchhierarchywithingroupsofmethods,suchasinitializersor
constructors,anduseitconsistentlythroughouttheclasshierarchy.• Avoiddispatchingcallsinmethodswherepossible.Seeupcastconsequencesinsubclause[BKK].
6.43.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Findasolutiontotheproblem.
6.44Polymorphicvariables[BKK]
6.44.1Descriptionofapplicationvulnerability
Object-orientedlanguagesallowpolymorphicvariables,inwhichvaluesofdifferentclassescanbestoredatdifferenttimes.Inmostoftheselanguages,variablesaredeclaredtobeofsomeclass,whiletheactualvaluemaybeofamorespecializedsubclass.Polymorphicvariablesgohandinhandwithmethodselectionatruntime,whenthemethoddefinedfortheactualsubclassofthereceivingobjectorcontrollingargumentisinvoked.Thisapproachissafe,asmethodimplementationandactualtypeoftheobjectmatchbyconstruction.If,however,thelanguagepermitscastingofthepolymorphicreferencetoprocesstheobjectasifitwereoftheclasscastedto,severalvulnerabilitiesarise.Wedistinguishthefollowingcasts:
• “upcasts”,wherethecastistoasuperclass• “downcasts”,wherethecastistoasubclassandacheckismadethattheobjectisindeedofthetarget
classofthecast(orasubclassthereof)• unsafecasts,wherethereisnoassurancethattheobjectisofthecastedclass.
Distinctvulnerabilitiesariseforeachofthesecasttypes:
Upcastsareneededsothatredefinedmethodscancalluponthecorrespondingmethodoftheparentclasstoachievetherespectiveportionoftheneededfunctionalityandthencompleteitfortheextensionsaddedbythesubclass.Withoutcallingtheparent’simplementationofamethodintheredefinedmethod,theprivatecomponentsoftheparentclassareinaccessibletotheredefinedmethod.Hencethereisariskthattheyarenolongerconsistentwiththeoverallstateoftheobject.Inversely,iftheissueisavoidedbyinheritingratherthanredefiningthemethodforasubclass,thereistheriskthatthesubclass-specificpartsareinconsistentwiththeoverallstateoftheobjectorevenuninitialized.
Downcastscarrytheriskthattheobjectisnotofthecorrectclass.Ifcheckedbythelanguage,aslanguage-defineddowncaststypicallyare,anexceptionwilloccurinthiscase.
Uncheckedcastsallowarbitrarybreachesofsafetyandsecurity.Seesubclause[HFC].
Notethatsomelanguagesalsohaveimplicitupcastsanddowncastsaspartofthelanguagesemantics.Thesameissuesapplyasforexplicitcasts.
Comment [SM2]: •.(Erhardtoconsiderclearerwording(withPatrice)).Thislikelywillreplacethetwofollowingones
Deleted: .(Erhardtoconsiderclearerwording(withPatrice)).Thislikelywillreplacethetwofollowingones
Comment [SM3]: Steve–makethisarealreferencetoBKK
Deleted: Some
Deleted: typesorDeleted: Forexample,object-orientedlanguages
Deleted: permit
Deleted: tobeDeleted: (Fortechnicalreasons,thiscapabilityisusuallyrestrictedtovariablesthatarereferencesorpointerswhosedesignatedobjectisofsomesuchsubclass.)
Deleted: Deleted: Deleted: nature
Deleted:
Deleted:
WG23/N0720
94 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
6.44.2Crossreference
CWE:(none)JSFAVRules:
67Makealldatamembersprivate78Virtualmethodandvirtualdestructor94redefinitionofaninheritednon-virtualfunction178Limiteddowncast179Pointercasts185UseC++upcastsinplaceofCcasts
CERTC++guidelines:(none)AdaQualityandStyleGuide:(none)
6.44.3Mechanismoffailure
Objectsleftinaninconsistentstatebymeansofanupcastandasubsequentlegitimatemethodcalloftheparentclasscanbeexploitedtocausesystemmalfunctions.
ExceptionsraisedbyfailingdowncastsallowDenial-of-Serviceattacks.Typicalscenariosincludetheadditionofobjectsofsomeunexpectedsubclassesingenericcontainers.
Uncheckedcaststoclasseswiththeneededcomponentsallowreadingandmodifyingarbitrarymemoryareas.Seesubclause[HFC]formoredetails.
6.44.4Applicablelanguagecharacteristics
Thisvulnerabilitydescriptionisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Languagesthathavepolymorphicvariables,particularlyobject-orientedlanguages.• Languagesthatpermitupcasts,downcasts,oruncheckedcasts.
6.44.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Forbidtheuseofuncheckedcasts.• Whenupcasting,ensurefunctionalconsistencyofthesubclass-specificdatatothechangesaffectedvia
theupcastedreference.• Trytoavoiddowncasts.Whereadowncastisnecessary,makesurethatyouhandleanyresultingerror
situation.
6.44.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Donotallowuncheckedcasts.
Deleted:
Deleted:
Deleted: <#>Insteadpreferdynamicmethodselectionbasedontheactualclassofthereceivingobjectorcontrollingargumenttothedowncastingofthereferencetotherespectiveclass. ... [8]
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 95
6.45Extraintrinsics[LRM]
6.45.1Descriptionofapplicationvulnerability
Mostlanguagesdefineintrinsicprocedures,whichareeasilyavailable,oralways"simplyavailable",toanytranslationunit.Ifatranslatorextendsthesetofintrinsicsbeyondthosedefinedbythestandard,andthestandardspecifiesthatintrinsicsareselectedbeforeproceduresofthesamesignaturedefinedbytheapplication,adifferentproceduremaybeunexpectedlyusedwhenswitchingbetweentranslators.
6.45.2Crossreference
[None]
6.45.3Mechanismoffailure
Moststandardprogramminglanguagesdefineasetofintrinsicproceduresthatmaybeusedinanyapplication.Somelanguagestandardsallowatranslatortoextendthissetofintrinsicprocedures.Somelanguagestandardsspecifythatintrinsicproceduresareselectedaheadofanapplicationprocedureofthesamesignature.Thismaycauseadifferentproceduretobeusedwhenswitchingbetweentranslators.
Forexample,mostlanguagesprovidearoutinetocalculatethesquarerootofanumber,usuallynamedsqrt().Ifatranslatoralsoprovided,asanextension,acuberootroutine,saynamedcbrt(),thatextensionmayoverrideanapplicationdefinedprocedureofthesamesignature.Ifthetwodifferentcbrt()routineschosedifferentbranchcutswhenappliedtocomplexarguments,theapplicationcouldunpredictablygowrong.
Ifthelanguagestandardspecifiesthatapplicationdefinedproceduresareselectedaheadofintrinsicproceduresofthesamesignature,theuseofthewrongproceduremaymaskalinkingerror.
6.45.4Applicablelanguagecharacteristics
Thisvulnerabilitydescriptionisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Anylanguagewheretranslatorsmayextendthesetofintrinsicproceduresandwhereintrinsicproceduresareselectedaheadofapplicationdefined(orexternallibrarydefined)proceduresofthesamesignature.
6.45.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Usewhateverlanguagefeaturesareavailabletomarkaprocedureaslanguagedefinedorapplicationdefined.
• Avoidusingproceduresignaturesmatchingthosedefinedbythetranslatorasextendingthestandardset.
Deleted:
Deleted:
Deleted:
WG23/N0720
96 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
6.45.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Clearlystatewhethertranslatorscanextendthesetofintrinsicproceduresornot.• Clearlystatewhattheprecedenceisforresolvingcollisions.• Clearlyprovidewaystomarkaproceduresignatureasbeingtheintrinsicoranapplicationprovided
procedure.• Requirethatadiagnosticisissuedwhenanapplicationprocedurematchesthesignatureofanintrinsic
procedure.
6.46Argumentpassingtolibraryfunctions[TRJ]
6.46.1Descriptionofapplicationvulnerability
Librariesthatsupplyobjectsorfunctionsareinmostcasesnotrequiredtocheckthevalidityofparameterspassedtothem.Inthosecaseswhereparametervalidationisrequiredtheremightnotbeadequateparametervalidation.
6.46.2Crossreference
CWE:114.ProcessControl
JSFAVRules16,18,19,20,21,22,23,24,and25MISRAC2012:1.3,4.11,21.2-21.8,and21.10MISRAC++2008:17-0-1,17-0-5,18-0-2,18-0-3,18-0-4,18-2-1,18-7-1and27-0-1CERTCguidelines:INT03-CandSTR07-C
6.46.3Mechanismoffailure
Whencallingalibrary,eitherthecallingfunctionorthelibrarymaymakeassumptionsaboutparameters.Forexample,itmaybeassumedbyalibrarythataparameterisnon-zerosodivisionbythatparameterisperformedwithoutcheckingthevalue.Sometimessomevalidationisperformedbythecallingfunction,butthelibrarymayusetheparametersinwaysthatwereunanticipatedbythecallingfunctionresultinginapotentialvulnerability.Evenwhenlibrariesdovalidateparameters,theirresponsetoaninvalidparameterisusuallyundefinedandcancauseunanticipatedresults.
6.46.4Applicablelanguagecharacteristics
Thisvulnerabilitydescriptionisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Languagesprovidingorusinglibrariesthatdonotvalidatetheparametersacceptedbyfunctions,methodsandobjects.
6.46.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
Deleted:
Deleted:
Deleted:
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 97
• Uselibrariesthatvalidateanyvaluespassedtothelibraryfunctionsbeforethevalueisused.• Developwrappersaroundlibraryfunctionsthatchecktheparametersbeforecallingthefunction.• Demonstratestaticallythattheparametersareneverinvalidusingstaticanalysistoolscapableof
detectingdatavalidationroutines.• Useonlylibrariesthatareknowntohavebeendevelopedwithconsistentandvalidatedinterface
requirements.
Itisnotedthatseveralapproachescanbetaken,someworkbestifusedinconjunctionwitheachother.
6.46.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Ensurethatalllibraryfunctionsdefinedoperateasintendedoverthespecifiedrangeofinputvaluesandreactinadefinedmannertovaluesthatareoutsidethespecifiedrange.
• Languagesshoulddefinelibrariesthatprovidethecapabilitytovalidateparametersduringcompilation,duringexecutionorbystaticanalysis.
6.47Inter-languagecalling[DJS]
6.47.1 Descriptionofapplicationvulnerability
Whenanapplicationisdevelopedusingmorethanoneprogramminglanguage,complicationsarise.Thecallingconventions,datalayout,errorhandingandreturnconventionsalldifferbetweenlanguages;ifthesearenotaddressedcorrectly,stackoverflow/underflow,datacorruption,andmemorycorruptionarepossible.
Inmulti-languagedevelopmentenvironmentsitisalsodifficulttoreusedatastructuresandobjectcodeacrossthelanguages.
6.47.2Crossreference
[None]
6.47.3Mechanismoffailure
Whencallingafunctionthathasbeendevelopedusingalanguagedifferentfromthecallinglanguage,thecallconventionandthereturnconventionusedmustbetakenintoaccount.Iftheseconventionsarenothandledcorrectly,thereisagoodchancethecallingstackwillbecorrupted,see6.34Subprogramsignaturemismatch
[OTR].Thecallconventioncovershowthelanguageinvokesthecall;see6.32Passingparametersandreturn
values[CSJ],andhowtheparametersarehandled.
Manylanguagesrestrictthelengthofidentifiers,thetypeofcharactersthatcanbeusedasthefirstcharacter,andthecaseofthecharactersused.Alloftheseneedtobetakenintoaccountwheninvokingaroutinewritteninalanguageotherthanthecallinglanguage.Otherwisetheidentifiersmightbindinamannerdifferentthanintended.
Characterandaggregatedatatypesrequirespecialtreatmentinamulti-languagedevelopmentenvironment.Thedatalayoutofalllanguagesthataretobeusedmustbetakenintoconsideration;thisincludespaddingand
Deleted: Deleted:
Formatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: Blue
Formatted: Font:Italic, Underline, Font color: BlueDeleted: 6.34Subprogramsignaturemismatch[OTR]6.34
SubprogramSignatureMismatch[OTR]
Formatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: Blue
Deleted:
Formatted: Font:Italic, Underline, Font color: Blue
Formatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: Blue
Deleted: 6.32Passingparametersandreturnvalues[CSJ]6.32
PassingParametersandReturnValues[CSJ]
Formatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueDeleted:
WG23/N0720
98 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
alignment.Ifthesedatatypesarenothandledcorrectly,thedatacouldbecorrupted,thememorycouldbecorrupted,orbothmaybecomecorrupt.Thiscanhappenbywriting/readingpasteitherendofthedatastructure,see6.8Bufferboundaryviolation(bufferoverflow)[HCB].Forexample,aPascalSTRINGdatatype
VAR str: STRING(10);
correspondstoaCstructure
struct { int length; char str [10]; };
andnottotheCstructure
char str [10]
wherelengthcontainstheactuallengthofSTRING.ThesecondCconstructisimplementedwithaphysicallengththatisdifferentfromphysicallengthofthePascalSTRINGandassumesanullterminator.
Mostnumericdatatypeshavecounterpartsacrosslanguages,butagainthelayoutshouldbeunderstood,andonlythosetypesthatmatchthelanguagesshouldbeused.Forexample,insomeimplementationsofC++a
signed char
wouldmatchaFortran
integer(1)
andwouldmatchaPascal
PACKED -128..127
Thesecorrespondencescanbeimplementation-definedandshouldbeverified.
6.47.4Applicablelanguagecharacteristics
Thevulnerabilityisapplicabletolanguageswiththefollowingcharacteristics:
• Allhighlevelprogramminglanguagesandlowlevelprogramminglanguagesaresusceptibletothisvulnerabilitywhenusedinamulti-languagedevelopmentenvironment.
6.47.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Usetheinter-languagemethodsandsyntaxspecifiedbytheapplicablelanguagestandard(s)6.• Understandthecallingconventionsofalllanguagesused.
6Forexample,FortranandAdaspecifyhowtocallCfunctions.
Deleted:
Deleted:
Formatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: Blue
Formatted: Font:Italic, Underline, Font color: Blue
Formatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueDeleted: 6.8Bufferboundaryviolation(bufferoverflow)[HCB]6.8BufferBoundaryViolation(BufferOverflow)[HCB]
Formatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: Blue
Formatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueDeleted:
Deleted:
Deleted:
Deleted: Deleted:
Deleted: Moved [2]: Forexample,FortranandAdaspecifyhowtocallCfunctions.
Moved (insertion) [2]
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 99
• Foritemscomprisingtheinter-languageinterface:o Understandthedatalayoutofalldatatypesused.o Understandthereturnconventionsofalllanguagesused.o Ensurethatthelanguageinwhicherrorcheckoccursistheonethathandlestheerror.o Avoidassumingthatthelanguagemakesadistinctionbetweenuppercaseandlowercaseletters
inidentifiers.o Avoidusingaspecialcharacterasthefirstcharacterinidentifiers.o Avoidusinglongidentifiernames.
6.47.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Developstandardprovisionsforinter-languagecallingwithlanguagesmostoftenusedwiththeirprogramminglanguage.
6.48Dynamically-linkedcodeandself-modifyingcode[NYY]
6.48.1Descriptionofapplicationvulnerability
Codethatisdynamicallylinkedmaybedifferentfromthecodethatwastested.ThismaybetheresultofreplacingalibrarywithanotherofthesamenameorbyalteringanenvironmentvariablesuchasLD_LIBRARY_PATHonUNIXplatformssothatadifferentdirectoryissearchedforthelibraryfile.Executingcodethatisdifferentthanthatwhichwastestedmayleadtounanticipatederrorsorintentionalmaliciousactivity.
Onsomeplatforms,andinsomelanguages,instructionscanmodifyotherinstructionsinthecodespace.Historicallyself-modifyingcodewasneededforsoftwarethatwasrequiredtorunonaplatformwithverylimitedmemory.Itisnowprimarilyused(ormisused)tohidefunctionalityofsoftwareandmakeitmoredifficulttoreverseengineerorforspecialtyapplicationssuchasgraphicswherethealgorithmistunedatruntimetogivebetterperformance.Self-modifyingcodecanbedifficulttowritecorrectlyandevenmoredifficulttotestandmaintaincorrectlyleadingtounanticipatederrors.
6.48.2Crossreference
JSFAVRule:2
6.48.3Mechanismoffailure
Throughthealterationofalibraryfileorenvironmentvariable,thecodethatisdynamicallylinkedmaybedifferentfromthecodewhichwastestedresultingindifferentfunctionality.
Onsomeplatforms,apointer-to-datacanerroneouslybegivenanaddressvaluethatdesignatesalocationintheinstructionspace.Ifsubsequentlyamodificationismadethroughthatpointer,thenanunanticipatedbehaviourcanresult.
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
WG23/N0720
100 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
6.48.4Applicablelanguagecharacteristics
Thisvulnerabilitydescriptionisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Languagesthatallowapointer-to-datatobeassignedanaddressvaluethatdesignatesalocationintheinstructionspace.
• Languagesthatallowexecutionofcodethatexistsindataspace.• Languagesthatpermittheuseofdynamicallylinkedorsharedlibraries.• LanguagesthatexecuteonanOSthatpermitsprogrammemorytobebothwritableandexecutable.
6.48.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Verifythatthedynamicallylinkedorsharedcodebeingusedisthesameasthatwhichwastested.• Retesttheapplicationbeforeusewhenitispossiblethatthedynamicallylinkedorsharedcodehas
changed.• Donotwriteself-modifyingcodeexceptinextremelyrareinstances.Mostsoftwareapplicationsshould
neverhavearequirementforself-modifyingcode.• Inthoseextremelyrareinstanceswhereitsuseisjustified,limittheamountofself-modifyingcodeand
heavilydocumentthem.
6.48.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Provideameanssothataprogramcaneitherautomaticallyormanuallycheckthatthedigitalsignatureofalibrarymatchestheoneinthecompile/testenvironment
6.49Librarysignature[NSQ]
6.49.1Descriptionofapplicationvulnerability
Programswritteninmodernlanguagesmayuselibrarieswritteninotherlanguagesthantheprogramimplementationlanguage.Ifthelibraryislarge,theeffortofaddingsignaturesforallofthefunctionsusebyhandmaybetediousanderror-prone.Portablecross-languagesignatureswillrequiredetailedunderstandingofbothlanguages,whichaprogrammermaylack.
Integratingtwoormoreprogramminglanguagesintoasingleexecutablereliesuponknowinghowtointerfacethefunctioncalls,argumentlistandglobaldatastructuressothesymbolsmatchintheobjectcodeduringlinking.
Bytealignmentcanbeasourceofdatacorruptionifmemoryboundariesbetweentheprogramminglanguagesaredifferent.Eachlanguagemayalsoalignstructuredatadifferently.
6.49.2Crossreference
MISRAC2012:1.1MISRAC++2008:1-0-2
Deleted:
Deleted:
Deleted:
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 101
6.49.3Mechanismoffailure
Whenthelibraryandtheapplicationinwhichitistobeusedarewrittenindifferentlanguages,thespecificationofsignaturesiscomplicatedbyinter-languageissues.
Asusedinthisvulnerabilitydescription,thetermlibraryincludestheinterfacetotheoperatingsystem,whichmaybespecifiedonlyforthelanguageusedtocodetheoperatingsystemitself.Inthiscase,anyprogramwritteninanyotherlanguagefacestheinter-languageinteroperabilityissueofcreatingafully-functionalsignature.
Whentheapplicationlanguageandthelibrarylanguagearedifferent,thentheabilitytospecifysignaturesaccordingtoeitherstandardmaynotexist,orbeverydifficult.Thus,atranslator-by-translatorsolutionmaybeneeded,whichmaximizestheprobabilityofincorrectsignatures(sincethesolutionmustberecreatedforeachtranslatorpair).Incorrectsignaturesmayormaynotbecaughtduringthelinkingphase.
6.49.4Applicablelanguagecharacteristics
Thisvulnerabilitydescriptionisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Languagesthatdonotspecifyhowtodescribesignaturesforsubprogramswritteninotherlanguages.
6.49.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Usetoolstocreatethesignatures.• Avoidusingtranslatoroptionsorlanguagefeaturestoreferencelibrarysubprogramswithoutproper
signatures.
6.49.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Providecorrectlinkageevenintheabsenceofcorrectlyspecifiedproceduresignatures.(Notethatthismaybeverydifficultwheretheoriginalsourcecodeisunavailable.)
• Providespecifiedmeanstodescribethesignaturesofsubprograms.
6.50Unanticipatedexceptionsfromlibraryroutines[HJW]
6.50.1Descriptionofapplicationvulnerability
Alibraryinthiscontextistakentomeanasetofsoftwareroutinesproducedoutsidethecontrolofthemainapplicationdeveloper,usuallybyathirdparty,andwheretheapplicationdevelopermaynothaveaccesstothesource.Insuchcircumstancestheapplicationdeveloperhaslimitedknowledgeofthelibraryfunctions,otherthanfromtheirbehaviouralinterface.
Whilsttheuseoflibrariescanpresentanumberofvulnerabilities,thefocusofthisvulnerabilityisanyundesirablebehaviourthatalibraryroutinemayexhibit,inparticularthegenerationofunexpectedexceptions.
Deleted:
Deleted:
Deleted:
Deleted:
WG23/N0720
102 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
6.50.2Crossreference
JSFAVRule:208MISRAC2012:4.11MISRAC++2008:15-3-1,15-3-2,17-0-4AdaQualityandStyleGuide:5.8and7.5
6.50.3Mechanismoffailure
Insomelanguages,unhandledexceptionsleadtoimplementation-definedbehaviour.Thiscanincludeimmediatetermination,withoutforexample,releasingpreviouslyallocatedresources.Ifalibraryroutineraisesanunanticipatedexception,thisundesirablebehaviourmayresult.
Itshouldbenotedthattheconsiderationsof[OYB],IgnoredErrorStatusandUnhandledExceptions,arealsorelevanthere.
6.50.4Applicablelanguagecharacteristics
Thisvulnerabilitydescriptionisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Languagesthatcanlinkpreviouslydevelopedlibrarycode(wherethedeveloperandcompilerdonothaveaccesstothelibrarysource).
• Languagesthatpermitexceptionstobethrownbutdonotrequirehandlersforthem.
6.50.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Wrapalllibrarycallswithina‘catch-all’exceptionhandler(ifthelanguagesupportssuchaconstruct),sothatanyunanticipatedexceptionscanbecaughtandhandledappropriately.Thiswrappingmaybedoneforeachlibraryfunctioncallorfortheentirebehaviouroftheprogram,forexample,havingtheexceptionhandlerinmainforC++.However,notethatthelatterisnotacompletesolution,asstaticobjectsareconstructedbeforemainisenteredandaredestroyedafterithasbeenexited.Consequently,MISRAC++[16]barsclassconstructorsanddestructorsfromthrowingexceptions(unlesshandledlocally).
• Alternatively,useonlylibraryroutinesforwhichallpossibleexceptionsarespecified.
6.50.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Forlanguagesthatprovideexceptions,provideamechanismforcatchingallpossibleexceptions(forexample,a‘catch-all’handler).Thebehaviouroftheprogramwhenencounteringanunhandledexceptionshouldbefullydefined.
• Provideamechanismtodeterminewhichexceptionsmightbethrownbyacalledlibraryroutine.
Deleted:
Deleted:
Deleted: don’t
Deleted:
Deleted: Deleted: isn’t
Deleted:
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 103
6.51Pre-processordirectives[NMP]
6.51.1Descriptionofapplicationvulnerability
Pre-processorreplacementshappenbeforeanysourcecodesyntaxcheck,thereforethereisnotypechecking–thisisespeciallyimportantinfunction-likemacroparameters.
Ifgreatcareisnottakeninthewritingofmacros,theexpandedmacrocanhaveanunexpectedmeaning.Inmanycasesifexplicitdelimitersarenotaddedaroundthemacrotextandaroundallmacroargumentswithinthemacrotext,unexpectedexpansionistheresult.
Sourcecodethatreliesheavilyoncomplicatedpre-processordirectivesmayresultinobscureandhardtomaintaincodesincethesyntaxtheyexpectmaybedifferentfromtheexpressionsprogrammersregularlyexpectinagivenprogramminglanguage.
6.51.2Crossreference
Holzmann-8JSFAVRules:26,27,28,29,30,31,and32 MISRAC2012:1.3,4.9,20.5,and20.6MISRAC++2008:16-0-3,16-0-4,and16-0-5CERTCguidelines:PRE01-C,PRE02-C,PRE10-C,andPRE31-C
6.51.3Mechanismoffailure
Readabilityandmaintainabilitymaybegreatlydecreasedifpre-processingdirectivesareusedinsteadoflanguagefeatures.
Whilestaticanalysiscanidentifymanyproblemsearly;heavyuseofthepre-processorcanlimittheeffectivenessofmanystaticanalysistools,whichtypicallyworkonthepre-processedsourcecode.
Inmanycaseswherecomplicatedmacrosareused,theprogramdoesnotdowhatisintended.Forexample:
defineamacroasfollows,
#define CD(x, y) (x + y - 1) / y whosepurposeistodivide.Thensupposeitisusedasfollows
a = CD (b & c, sizeof (int)); whichexpandsinto
a = (b & c + sizeof (int) - 1) / sizeof (int); whichmosttimeswillnotdowhatisintended.Definingthemacroas
#define CD(x, y) ((x) + (y) - 1) / (y) willprovidethedesiredresult.
Deleted:
Deleted:
Deleted:
Deleted:
WG23/N0720
104 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
6.51.4Applicablelanguagecharacteristics
Thisvulnerabilitydescriptionisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Languagesthathavealexical-levelpre-processor.• Languagesthatallowunintendedgroupingsofarithmeticstatements.• Languagesthatallowcascadingmacros.• Languagesthatallowduplicationofsideeffects.• Languagesthatallowmacrosthatreferencethemselves.• Languagesthatallownestedmacrocalls.• Languagesthatallowcomplicatedmacros.
6.51.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Donotusepre-processordirectiveswhereitispossibletoachievethedesiredfunctionalitywithoutthepre-processordirectives.
6.51.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Reduceoreliminatedependenceonlexical-levelpre-processorsforessentialfunctionality(suchasconditionalcompilation).
• Providecapabilitiestoinlinefunctionsandprocedurecalls,toreducetheneedforpre-processormacros.
6.52Suppressionoflanguage-definedrun-timechecking[MXB]
6.52.1Descriptionofapplicationvulnerability
Somelanguagesincludetheprovisionforruntimecheckingtopreventvulnerabilitiestoarise.Canonicalexamplesareboundsorlengthchecksonarrayoperationsornull-valuechecksupondereferencingpointersorreferences.Inmostcases,thereactiontoafailedcheckistheraisingofalanguage-definedexception.
Asrun-timecheckingrequiresexecutiontimeandassomeprojectguidelinesexcludetheuseofexceptions,languagesmaydefineawaytooptionallysuppresssuchcheckingforregionsofthecodeorfortheentireprogram.Analogously,compileroptionsmaybeusedtoachievethiseffect.
6.52.2Crossreference
[None]
6.52.3MechanismofFailure
Vulnerabilitiesthatcouldhavebeenpreventedbytherun-timechecksareundetected,resultinginmemorycorruption,propagationofincorrectvaluesorunintendedexecutionpaths.
Deleted:
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 105
6.52.4Applicablelanguagecharacteristics
Thisvulnerabilitydescriptionisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Languagesthatdefineruntimecheckstopreventcertainvulnerabilitiesand• Languagesthatallowtheabovecheckstobesuppressed,• Languagesorcompilersthatsuppresscheckingbydefault,orwhosecompilersorinterpretersprovide
optionstoomittheabovechecks
6.52.5Avoidingthevulnerability
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Donotsuppresschecksatallorrestrictthesuppressionofcheckstoregionsofthecodethathavebeenprovedtobeperformance-critical.
• Ifthedefaultbehaviourofthecompilerorthelanguageistosuppresschecks,thenexplicitlyenablethosechecks.
• Wherechecksaresuppressed,verifythateachsuppressedcheckcannotfail.• Clearlyidentifycodesectionswherechecksaresuppressed.• Donotassumethatchecksincodeverifiedtosatisfyallcheckscouldnotfailneverthelessdueto
hardwarefaults.
6.52.6Implicationsforlanguagedesignandevolution
[None]
6.53Provisionofinherentlyunsafeoperations[SKL]
6.53.1Descriptionofapplicationvulnerability
Languagesdefinesemanticrulestobeobeyedbyconformingprograms.Compilersenforcetheserulesanddiagnoseviolatingprograms.
Acanonicalexamplearetherulesoftypechecking,intendedamongotherreasonstopreventsemanticallyincorrectassignments,suchascharacterstopointers,metertofeet,eurotodollar,realnumberstobooleans,orcomplexnumberstotwo-dimensionalcoordinates.
Occasionallytherearisesaneedtostepoutsidetherulesofthetypemodeltoachieveneededfunctionality.Onesuchsituationisexplicittypeconversionofmemoryaspartoftheimplementationofaheapallocatortothetypeofobjectforwhichthememoryisallocated.Atype-safeassignmentisimpossibleforthisfunctionality.Thus,acapabilityforuncheckedexplicittypeconversionbetweenarbitrarytypestointerpretthebitsinadifferentfashionisanecessarybutinherentlyunsafeoperation,withoutwhichthetype-safeallocatorcannotbeprogrammed.
Anotherexampleistheprovisionofoperationsknowntobeinherentlyunsafe,suchasthedeallocationofheapmemorywithoutpreventionofdanglingreferences.
Athirdexampleisanyinterfacingwithanotherlanguage,sincethechecksensuringtype-safenessrarelyextendacrosslanguageboundaries.
Theseinherentlyunsafeoperationsconstituteavulnerability,sincetheycan(andwill)beusedbyprogrammersinsituationswheretheiruseisneithernecessarynorappropriate.
Deleted: them
Deleted: theDeleted: sDeleted: couldnothaveDeleted: ed
Deleted:
Deleted:
Deleted: Deleted:
WG23/N0720
106 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
Thevulnerabilityiseminentlyexploitabletoviolateprogramsecurity.
6.53.2Crossreference
[None]
6.53.3MechanismofFailure
Theuseofinherentlyunsafeoperationsorthesuppressionofcheckingcircumventsthefeaturesthatarenormallyappliedtoensuresafeexecution.Controlflow,datavalues,andmemoryaccessescanbecorruptedasaconsequence.Seetherespectivevulnerabilitiesresultingfromsuchcorruption.
6.53.4Applicablelanguagecharacteristics
Thisvulnerabilitydescriptionisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Languagesthatallowcompile-timechecksforthepreventionofvulnerabilitiestobesuppressedbycompilerorinterpreteroptionsorbylanguageconstructs,or
• Languagesthatprovideinherentlyunsafeoperations
6.53.5Avoidingthevulnerability
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Restrictthesuppressionofcompile-timecheckstowherethesuppressionisfunctionallyessential.• Useinherentlyunsafeoperationsonlywhentheyarefunctionallyessential.• Clearlyidentifyprogramcodethatsuppresseschecksorusesunsafeoperations.Thispermitsthefocusing
ofreviewefforttoexaminewhetherthefunctioncouldbeperformedinasafermanner.
6.53.6Implicationsforlanguagedesignandevolution
[None]
6.54Obscurelanguagefeatures[BRS]
6.54.1Descriptionofapplicationvulnerability
Everyprogramminglanguagehasfeaturesthatareobscure,difficulttounderstandordifficulttousecorrectly.Theproblemiscompoundedifasoftwaredesignmustbereviewedbypeoplewhomaynotbelanguageexperts,suchas,hardwareengineers,human-factorsengineers,orsafetyofficers.Evenifthedesignandcodeareinitiallycorrect,maintainersofthesoftwaremaynotfullyunderstandtheintent.Theconsequencesoftheproblemaremoresevereifthesoftwareistobeusedintrustedapplications,suchassafetyormission-criticalones.
Misunderstoodlanguagefeaturesormisunderstoodcodesequencescanleadtoapplicationvulnerabilitiesindevelopmentorinmaintenance.
6.54.2Crossreference
JSFAVRules:84,86,88,and97
Deleted:
Deleted:
Deleted:
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 107
MISRAC2012:1.1,10.4,13.4,13.6,18.5,21.4,21.5,21.6,21.7and21.8MISRAC++2008:0-2-1,2-3-1,and12-1-1CERTCguidelines:FIO03-C,MSC05-C,MSC30-C,andMSC31-C.ISO/IECTR15942:2000:5.4.2,5.6.2and5.9.3
6.54.3Mechanismoffailure
Theuseofobscurelanguagefeaturescanleadtoanapplicationvulnerabilityinseveralways:
• Theoriginalprogrammermaymisunderstandthecorrectusageofthefeatureandcouldutilizeitincorrectlyinthedesignorcodeitincorrectly.
• Reviewersofthedesignandcodemaymisunderstandtheintentortheusageandoverlookproblems.• Maintainersofthecodecannotfullyunderstandtheintentortheusageandcouldintroduceproblems
duringmaintenance.
6.54.4Applicablelanguagecharacteristics
Thisvulnerabilitydescriptionisintendedtobeapplicabletoanylanguage.
6.54.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Avoidtheuseoflanguagefeaturesthatareobscureordifficulttouse,especiallyincombinationwithotherdifficultlanguagefeatures.Adoptcodingstandardsthatdiscourageuseofsuchfeaturesorshowhowtousethemcorrectly.
• Whendevelopingsoftwarewithcriticallyimportantrequirements,adopt(organizations)amechanismtomonitorwhichlanguagefeaturesarecorrelatedwithfailuresduringthedevelopmentprocessandduringdeployment.
• (Organizations)Adoptordevelopstereotypicalidiomsfortheuseofdifficultlanguagefeatures,codifytheminorganizationalstandards,andenforcethemviareviewprocesses.
• Avoidtheuseofcomplicatedfeaturesofalanguage.• Avoidtheuseofrarelyusedconstructsthatcouldbedifficultforentry-levelmaintenancepersonnelto
understand.• Usetool-basedstaticanalysistofindincorrectusageofsomelanguagefeatures.
Itshouldbenotedthatconsistencyincodingisdesirableforeachofreviewandmaintenance.Therefore,thedesirabilityoftheparticularalternativeschosenforinclusioninacodingstandarddoesnotneedtobeempiricallyproven.
6.54.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Languagedesignersshouldconsiderremovingordeprecatingobscure,difficulttounderstand,ordifficulttousefeatures.
• Languagedesignersshouldprovidelanguagedirectivesthatoptionallydisableobscurelanguagefeatures.
Deleted: Deleted: Organizationsshoulda
Deleted:
WG23/N0720
108 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
6.55Unspecifiedbehaviour[BQF]
6.55.1Descriptionofapplicationvulnerability
Theexternalbehaviourofaprogramwhosesourcecodecontainsoneormoreinstancesofconstructshavingunspecifiedbehaviourmaynotbefullypredictablewhenthesourcecodeis(re)compiledor(re)linked.
6.55.2Crossreference
JSFAVRules:17,18,19,20,21,22,23,24,25MISRAC2012:1.1,1.3,19.1,and20.2MISRAC++2008:5-0-1,5-2-6,7-2-1,and16-3-1CERTCguidelines:MSC15-CSee:6.56Undefinedbehaviour[EWFand6.57Implementation-definedbehaviour[FAB].
6.55.3Mechanismoffailure
Languagespecificationsdonotalwaysuniquelydefinethebehaviourofaconstruct.Whenaninstanceofaconstructthatisnotuniquelydefinedisencountered(thismightbeatanyofcompile,link,orruntime)implementationsarepermittedtochoosefromthesetofbehavioursallowedbythelanguagespecification.Theterm'unspecifiedbehaviour'issometimesappliedtosuchbehaviours,(languagespecificguidelinesneedtoanalyzeanddocumentthetermsusedbytheirrespectivelanguage).
Adevelopermayuseaconstructinawaythatdependsonasubsetofthepossiblebehavioursoccurring.Thebehaviourofaprogramcontainingsuchausageisdependentonthetranslatorusedtobuilditalwaysselectingthe'expected'behaviour.
Manylanguageconstructsmayhaveunspecifiedbehaviourandunconditionallyrecommendingagainstanyuseoftheseconstructsmaybeimpractical.Forinstance,inmanylanguagestheorderofevaluationoftheoperandsappearingontheleft-andright-handsideofanassignmentisunspecified,butinmostcasesthesetofpossiblebehavioursalwaysproducethesameresult.
Theappearanceofunspecifiedbehaviourinalanguagespecificationisrecognitionbythelanguagedesignersthatinsomecasesflexibilityisneededbysoftwaredevelopersandprovidesaworthwhilebenefitforlanguagetranslators;thisusageisnotadefectinthelanguage.
Theimportantcharacteristicisnottheinternalbehaviourexhibitedbyaconstruct(suchasthesequenceofmachinecodegeneratedbyatranslator)butitsexternalbehaviour(thatis,theonevisibletoauserofaprogram).Ifthesetofpossibleunspecifiedbehaviourspermittedforaspecificuseofaconstructallproducethesameexternaleffectwhentheprogramcontainingthemisexecuted,thenrebuildingtheprogramcannotresultinachangeofbehaviourforthatspecificusageoftheconstruct.
Forinstance,whilethefollowingassignmentstatementcontainsunspecifiedbehaviourinmanylanguages(thatis,itispossibletoevaluateeithertheAorBoperandfirst,followedbytheotheroperand):
A = B;
Formatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: Blue
Deleted: 6.56Undefinedbehaviour[EWF6.56Undefined
Behaviour[EWF]
Formatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: Blue
Deleted: 6.57Implementation-definedbehaviour[FAB]6.57
Implementation-definedBehaviour[FAB]
Formatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueDeleted:
Deleted: Deleted: Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 109
inmostcasestheorderinwhichAandBareevaluateddoesnotaffecttheexternalbehaviourofaprogramcontainingthisstatement.
6.55.4Applicablelanguagecharacteristics
Thisvulnerabilityisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Languageswhosespecificationallowsafinitesetofmorethanonebehaviourforhowatranslatorhandlessomeconstruct,wheretwoormoreofthebehaviourscanresultindifferencesinexternalprogrambehaviour.
6.55.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Uselanguageconstructsthathavespecifiedbehaviour.• Usestaticanalysistoolsthatidentifyconditionsthatcanresultinunspecifiedbehavior.• Ensurethataspecificuseofaconstructhavingunspecifiedbehaviourproducesaresultthatisthesame
forallofthepossiblebehaviourspermittedbythelanguagespecification.• Whendevelopingcodingguidelinesforaspecificlanguage
• identifyallconstructsthathaveunspecifiedbehaviour,and
• foreachconstructwherethesetofpossiblebehaviourscanvary,mandatethatthealternativesbeenumerated.
6.55.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Languagesshouldminimizetheamountofunspecifiedbehaviours,minimizethenumberofpossiblebehavioursforanygiven"unspecified"choice,anddocumentwhatmightbethedifferenceinexternaleffectassociatedwithdifferentchoices.
6.56Undefinedbehaviour[EWF]
6.56.1Descriptionofapplicationvulnerability
Theexternalbehaviourofaprogramcontaininganinstanceofaconstructhavingundefinedbehaviour,asdefinedbythelanguagespecification,isnotpredictable.
6.56.2Crossreference
JSFAVRules:17,18,19,20,21,22,23,24,25MISRAC2012:1.1,1.3,5.4,18.2,18.3,and20.2MISRAC++2008:2-13-1,5-2-2,16-2-4,and16-2-5CERTCguidelines:MSC15-CSee:6.55Unspecifiedbehaviour[BQF]and6.57Implementation-definedbehaviour[FAB].
Deleted: ,Formatted
Deleted: Deleted:
Formatted: Font:Italic, Underline, Font color: Blue
Formatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: Blue
Formatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: Blue
Formatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: Blue
Deleted: 6.55Unspecifiedbehaviour[BQF]6.55UnspecifiedBehaviour[BQF]
Formatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: Blue
Formatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: Blue
Formatted: Font:Italic, Underline, Font color: Blue
Deleted: 6.57Implementation-definedbehaviour[FAB]6.57
Implementation-definedBehaviour[FAB]
Formatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: BlueFormatted: Font:Italic, Underline, Font color: Blue
WG23/N0720
110 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
6.56.3Mechanismoffailure
Languagespecificationsmaycategorizethebehaviourofalanguageconstructasundefinedratherthanasasemanticviolation(thatis,anerroneoususeofthelanguage)becauseofthepotentiallyhighimplementationcostofdetectinganddiagnosingalloccurrencesofit.Inthiscasenospecificbehaviourisrequiredandthetranslatororruntimesystemisatlibertytodoanythingitpleases(whichmayincludeissuingadiagnostic).
Thebehaviourofaprogrambuiltfromsuccessfullytranslatedsourcecodecontainingaconstructhavingundefinedbehaviourisnotpredictable.Forexample,insomelanguagesthevalueofavariableisundefinedbeforeitisinitialized.
6.56.4Applicablelanguagecharacteristics
Thisvulnerabilityisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Languagesthatdonotfullydefinetheextenttowhichtheuseofaparticularconstructisaviolationofthelanguagespecification.
• Languagesthatdonotfullydefinethebehaviourofconstructsduringcompile,linkandprogramexecution.
6.56.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Ensurethatundefinedlanguageconstructsarenotused.• Ensurethatauseofaconstructhavingundefinedbehaviourdoesnotoperatewithinthedomaininwhich
thebehaviourisundefined.Whenitisnotpossibletocompletelyverifythedomainofoperationduringtranslationaruntimecheckmayneedtobeperformed.
• Whendevelopingcodingguidelinesforaspecificlanguage,documentallconstructsthathaveundefinedbehaviour.Theitemsonthislistmightbeclassifiedbytheextenttowhichthebehaviourislikelytohavesomecriticalimpactontheexternalbehaviourofaprogram(thecriticalitymayvarybetweendifferentimplementations,forexample,whetherconversionbetweenobjectandfunctionpointershaswelldefinedbehaviour).
• Usestaticanalysistoolsthatidentifyconditionsthatcanresultinundefinedbehaviour.• Documentallusesoflanguageextensionsneededforcorrectoperation• Whendevelopingcodingguidelinesforaspecificlanguageallconstructsthathaveundefinedbehavior,
documentedforeachconstruct,thesituationswherethesetofpossiblebehaviourscanvary.• Whenapplyingthisguidelineonaproject,documentthefunctionalityprovidedbyandforchangingits
undefinedbehaviour.
6.56.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Languagedesignersshouldminimizetheamountofundefinedbehaviourtotheextentpossibleandpractical.
Deleted:
Deleted:
Deleted:
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 111
• Languagedesignersshouldenumerateallthecasesofundefinedbehaviour.• Languagedesignersshouldprovidemechanismsthatpermitthedisablingordiagnosingofconstructsthat
mayproduceundefinedbehaviour.
6.57Implementation-definedbehaviour[FAB]
6.57.1Descriptionofapplicationvulnerability
Someconstructsinprogramminglanguagesarenotfullydefined(see6.55Unspecifiedbehaviour[BQF])andthusleavecompilerimplementationstodecidehowtheconstructwilloperate.Thebehaviourofaprogram,whosesourcecodecontainsoneormoreinstancesofconstructshavingimplementation-definedbehaviour,canchangewhenthesourcecodeisrecompiledorrelinked.
6.57.2Crossreference
JSFAVRules:17,18,19,20,21,22,23,24,25MISRAC2012:1.1,1.3,5.4,18.2,18.3,and20.2MISRAC++2008:5-2-9,5-3-3,7-3-2,and9-5-1CERTCguidelines:MSC15-CISO/IECTR15942:2000:5.9AdaQualityandStyleGuide:7.1.5and7.1.6See:6.55Unspecifiedbehaviour[BQF]and6.56Undefinedbehaviour[EWF.
6.57.3Mechanismoffailure
Languagespecificationsdonotalwaysuniquelydefinethebehaviourofaconstruct.Whenaninstanceofaconstructthatisnotuniquelydefinedisencountered(thismightbeatanyoftranslation,link-time,orprogramexecution)implementationsarepermittedtochoosefromasetofbehaviours.Theonlydifferencefromunspecifiedbehaviouristhatimplementationsarerequiredtodocumenthowtheybehave.
Adevelopermayuseaconstructinawaythatdependsonaparticularimplementation-definedbehaviouroccurring.Thebehaviourofaprogramcontainingsuchausageisdependentonthetranslatorusedtobuilditalwaysselectingthe'expected'behaviour.
Someimplementationsprovideamechanismforchanginganimplementation'simplementation-definedbehaviour(forexample,useofpragmasinsourcecode).Useofsuchachangemechanismcreatesthepotentialforadditionalhumanerrorinthatadevelopermaybeunawarethatachangeofbehaviourwasrequestedearlierinthesourcecodeandmaywritecodethatdependsontheimplementation-definedbehaviourthatoccurredpriortothatexplicitchangeofbehaviour.
Manylanguageconstructsmayhaveimplementation-definedbehaviourandunconditionallyrecommendingagainstanyuseoftheseconstructsmaybecompletelyimpractical.Forinstance,inmanylanguagesthenumberofsignificantcharactersinanidentifierisimplementation-defined.Developersneedtochooseaminimumnumberofcharactersandrequirethatonlytranslatorssupportingatleastthatnumber,N,ofcharactersbeused.
Formatted ... [9]
Deleted: 6.55Unspecifiedbehaviour[BQF]6.55UnspecifiedBehaviour[BQF]
Formatted ... [10]Deleted:
Formatted ... [11]
Deleted: 6.55Unspecifiedbehaviour[BQF]6.57UnspecifiedBehaviour[BQF]
Formatted ... [12]
Formatted ... [13]
Deleted: 6.56Undefinedbehaviour[EWF6.56Undefined
Behaviour[EWF]
Formatted ... [14]Deleted: …Whenaninstanceofaconstructthatisnotuniquely... [15]
Deleted:
Deleted:
Deleted: …Forinstance,inmanylanguagesthenumberof... [16]
WG23/N0720
112 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
Theappearanceofimplementation-definedbehaviourinalanguagespecificationisrecognitionbythelanguagedesignersthatinsomecasesimplementationflexibilityprovidesaworthwhilebenefitforlanguagetranslators;thisusageisnotadefectinthelanguage.
6.57.4Applicablelanguagecharacteristics
Thisvulnerabilityisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Languageswhosespecificationallowssomevariationinhowatranslatorhandlessomeconstruct,whererelianceononeformofthisvariationcanresultindifferencesinexternalprogrambehaviour.
• Languageimplementationsmaynotberequiredtoprovideamechanismforcontrollingimplementation-definedbehaviour.
6.57.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Documentthesetofimplementation-definedfeaturesanapplicationdependsupon,sothatuponachangeoftranslator,developmenttools,ortargetconfigurationitcanbeensuredthatthosedependenciesarestillmet.
• Ensurethataspecificuseofaconstructhavingimplementation-definedbehaviourproducesanexternalbehaviourthatisthesameforallofthepossiblebehaviourspermittedbythelanguagespecification.
• Usealanguageimplementationwhoseimplementation-definedbehavioursarewithinanacceptablesubsetofallimplementation-definedbehaviours.Thesubsetisacceptableifthe'sameexternalbehaviour'conditiondescribedaboveismet.
• Createhighlyvisibledocumentation(perhapsatthestartofasourcefile)thatthedefaultimplementation-definedbehaviourischangedwithinthecurrentfile.
• Whendevelopingcodingguidelinesforaspecificlanguageallconstructsthathaveimplementation-definedbehavior,documentedforeachconstruct,thesituationswherethesetofpossiblebehaviourscanvaryandenumeratedthevariations.
• Whenapplyingthisguidelineonaproject,documentthefunctionalityprovidedbyandforchangingitsimplementation-definedbehaviour.
• Verifycodebehaviourusingatleasttwodifferentcompilerswithtwodifferenttechnologies.
6.57.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Portabilityguidelinesforaspecificlanguageshouldprovidealistofcommonimplementation-definedbehaviours.
• Languagespecifiersshouldenumerateallthecasesofimplementation-definedbehaviour.• Languagedesignersshouldprovidelanguagedirectivesthatoptionallydisableobscurelanguagefeatures.
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 113
6.58Deprecatedlanguagefeatures[MEM]
6.58.1Descriptionofapplicationvulnerability
Ideallyallcodeshouldconformtothecurrentstandardfortherespectivelanguage.Inrealitythough,alanguagestandardmaychangeduringthecreationofasoftwaresystemorsuitablecompilersanddevelopmentenvironmentsmaynotbeavailableforthenewstandardforsomeperiodoftimeafterthestandardispublished.Tosmooththeprocessofevolution,featuresthatarenolongerneededorwhichserveastherootcauseoforcontributingfactorforsafetyorsecurityproblemsareoftendeprecatedtotemporarilyallowtheircontinuedusebuttoindicatethatthosefeaturesmayberemovedinthefuture.Thedeprecationofafeatureisastrongindicationthatitshouldnotbeused.Otherfeatures,althoughnotformallydeprecated,arerarelyusedandthereexistothermorecommonwaysofexpressingthesamefunction.Useoftheserarelyusedfeaturescanleadtoproblemswhenothersareassignedthetaskofdebuggingormodifyingthecodecontainingthosefeatures.
6.58.2Crossreference
JSFAVRules:8and11MISRAC2012:1.1and4.2MISRAC++2008:1-0-1,2-3-1,2-5-1,2-7-1,5-2-4,and18-0-2AdaQualityandStyleGuide:7.1.1
6.58.3Mechanismoffailure
Mostlanguagesevolveovertime.Sometimesnewfeaturesareaddedmakingotherfeaturesextraneous.Languagesmayhavefeaturesthatarefrequentlythebasisforsecurityorsafetyproblems.Thedeprecationofthesefeaturesindicatesthatthereisabetterwayofaccomplishingthedesiredfunctionality.However,thereisalwaysatimelagbetweentheacknowledgementthataparticularfeatureisthesourceofsafetyorsecurityproblems,thedecisiontoremoveorreplacethefeatureandthegenerationofwarningsorerrormessagesbycompilersthatthefeatureshouldnotbeused.Giventhatsoftwaresystemscantakemanyyearstodevelop,itispossibleandevenlikelythatalanguagestandardwillchangecausingsomeofthefeaturesusedtobesuddenlydeprecated.Modifyingthesoftwarecanbecostlyandtimeconsumingtoremovethedeprecatedfeatures.However,ifthescheduleandresourcespermit,thiswouldbeprudentasfuturevulnerabilitiesmayresultfromleavingthedeprecatedfeaturesinthecode.Ultimatelythedeprecatedfeatureswilllikelyneedtoberemovedwhenthefeaturesareremoved.
6.58.4Applicablelanguagecharacteristics
Thisvulnerabilitydescriptionisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Alllanguagesthathavestandards,thoughsomeonlyhavedefactostandards.• Alllanguagesthatevolveovertimeandassuchcouldpotentiallyhavedeprecatedfeaturesatsomepoint.
6.58.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted: Deleted: Deleted:
Deleted:
Deleted: n’tDeleted:
Deleted: Deleted:
Deleted:
WG23/N0720
114 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
• Adheretothelatestpublishedstandardforwhichasuitablecomplieranddevelopmentenvironmentisavailable.
• Avoidtheuseofdeprecatedfeaturesofalanguage.• StayabreastoflanguagediscussionsinlanguageusergroupsandstandardsgroupsontheInternet.
Discussionsandmeetingnoteswillgiveanindicationofproblempronefeaturesthatshouldnotbeusedorshouldbeusedwithcaution.
6.58.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Obscurelanguagefeaturesforwhichtherearecommonlyusedalternativesshouldbeconsideredforremovalfromthelanguagestandard.
• Obscurelanguagefeaturesthathaveroutinelybeenfoundtobetherootcauseofsafetyorsecurityvulnerabilities,orthatareroutinelydisallowedinsoftwareguidancedocumentsshouldbeconsideredforremovalfromthelanguagestandard.
• Languagedesignersshouldprovidelanguagemechanismsthatoptionallydisabledeprecatedlanguagefeatures.
6.59Concurrency–Activation[CGA]
6.59.1Descriptionofapplicationvulnerability
Avulnerabilitycanoccurifanattempthasbeenmadetoactivateathread,butaprogrammingerrororthelackofsomeresourcepreventstheactivationfromcompleting.Theactivatingthreadmaynothavesufficientvisibilityorawarenessintotheexecutionoftheactivatedthreadtodetermineiftheactivationhasbeensuccessful.Theunrecognizedactivationfailurecancauseaprotocolfailureintheactivatingthreadorinotherthreadsthatrelyuponsomeactionbytheunactivatedthread.Thismaycausetheotherthread(s)towaitforeverforsomeeventfromtheunactivatedthread,ormaycauseanunhandledeventorexceptionintheotherthreads.
6.59.2CrossReferences
CWE:364.SignalHandlerRaceCondition
JSF:(none)MISRA:(none)HoareA.,"CommunicatingSequentialProcesses",PrenticeHall,1985HolzmannG.,"TheSPINModelChecker:PrinciplesandReferenceManual",AddisonWesleyProfessional.2003UPPAAL,availablefromwww.uppaal.com,Larsen,Peterson,Wang,"ModelCheckingforReal-TimeSystems",Proceedingsofthe10thInternationalConferenceonFundamentalsofComputationTheory,1995RavenscarTaskingProfile,specifiedinISO/IEC8652:1995AdawithTC1:2001andAM1:2007
Deleted:
Deleted:
Deleted:
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 115
6.59.3MechanismofFailure
Thecontextoftheproblemisthatallthreadsexceptthemainthreadareactivatedbyprogramstepsofanotherthread.Theactivationofeachthreadrequiresthatdedicatedresourcesbecreatedforthatthread,suchasathreadstack,threadattributes,andcommunicationports.Ifinsufficientresourcesremainwhentheactivationattemptismade,theactivationwillfail.Similarly,ifthereisaprogramerrorintheactivatedthreadoriftheactivatedthreaddetectsanerrorthatcausesittoterminatebeforebeginningitsmainwork,thenitmayappeartohavefailedduringactivation.Whentheactivationis“static”,resourceshavebeenpreallocated,soactivationfailurebecauseofalackofresourceswillnotoccur.Howevererrorsmayoccurforreasonsotherthanresourceallocationandtheresultsofanactivationfailurewillbesimilar.
Iftheactivatingthreadwaitsforeachactivatedthread,thentheactivatingthreadwilllikelybenotifiedofactivationfailures(iftheparticularconstructorcapabilitysupportsactivationfailurenotification)andcanbeprogrammedtotakealternateaction.Ifnotificationoccursbutalternateactionisnotprogrammed,thentheprogramwillexecuteerroneously.Iftheactivatingthreadislooselycoupledwiththeactivatedthreads,andtheactivatingthreaddoesnotreceivenotificationofafailuretoactivate,thenitmaywaitindefinitelyfortheunactivatedthreadtodoitswork,ormaymakewrongcalculationsbecauseofincompletedata.
Activationofasinglethreadisaspecialcaseofactivationsofcollectionsofthreadssimultaneously.Thisparadigm(activationofcollectionsofthreads)canbeusedinlanguagesthatparallelisecalculationsandcreateanonymousthreadstoexecuteeachsliceofdata.Insuchsituationstheactivatingthreadisunlikelytoindividuallymonitoreachactivatedthread,soafailureofsometoactivatewithoutexplicitnotificationtotheactivatingthreadcanresultinerroneouscalculations.
Iftherestoftheapplicationisunawarethatanactivationhasfailed,anincorrectexecutionoftheapplicationalgorithmmayoccur,suchasdeadlockofthreadswaitingfortheactivatedthread,orpossiblycausingerrorsorincorrectcalculations.
6.59.4Applicablelanguagecharacteristics
Thisvulnerabilityisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Alllanguagesthatpermitconcurrencywithinthelanguage,orthatusesupportlibrariesandoperatingsystems(suchasPOSIXorWindows)thatprovideconcurrencycontrolmechanisms.Inessencealltraditionallanguagesonfullyfunctionaloperatingsystems(suchasPOSIX-compliantOSorWindows)canaccesstheOS-providedmechanisms.
6.59.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Alwayscheckerrorreturncodesonoperatingsystemcommand,libraryprovidedorlanguagethreadactivationmechanisms.
• Usestaticanalysistoolstoverifythatreturncodesarechecked.• Whenfunctionsreturnerrorvalues,checktheerrorreturnvaluesbeforeprocessinganyotherreturned
data.
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Formatted: Font:11 pt, English (CAN)Deleted: e
WG23/N0720
116 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
• Handleerrorsandexceptionsthatoccuronactivation.• Createexplicitsynchronizationprotocols,toensurethatallactivationshaveoccurredbeforebeginning
theparallelalgorithm,ifnotprovidedbythelanguageorbythethreadingsubsystem.• Useprogramminglanguageprovidedfeaturesorthread-libraryprovidedfeaturesthatcouplethe
activatedthreadwiththeactivatingthreadtodetectactivationerrorssothaterrorscanbereportedandrecoverymade.
• Usestaticactivationinpreferencetodynamicactivationsothatstaticanalysiscanguaranteecorrectactivationofthreads.
6.59.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Considerincludingautomaticsynchronizationofthreadinitiationaspartoftheconcurrencymodel.• Provideamechanismpermittingqueryofactivationsuccess.
6.60Concurrency–Directedtermination[CGT]
6.60.1Descriptionofapplicationvulnerability
Thisdiscussionisassociatedwiththeeffectsofunsuccessfulorlateterminationofathread.Foradiscussionofprematuretermination,see6.63.
Whenathreadisworkingcooperativelywithotherthreadsandisdirectedtoterminate,thereareanumberoferrorsituationsthatmayoccurthatcanleadtocompromiseofthesystem.Theterminationdirectingthreadmayrequestthatoneormoreotherthreadsabortorterminate,buttheterminatedthread(s)maynotbeinastatesuchthattheterminationcanoccur,mayignorethedirection,ormaytakelongertoabortorterminatethantheapplicationcantolerate.Inanycase,onmostsystems,thethreadwillnotterminateuntilitisnextscheduledforexecution.
Unexpectedlydelayedterminationortheconsumptionofresourcesbytheterminationitselfmaycauseafailuretomeetdeadlines,which,inturn,mayleadtootherfailures.
6.60.2Crossreferences
CWE:364.SignalHandlerRaceCondition
JSF:(none)MISRA:(none)HoareC.A.R.,"CommunicatingSequentialProcesses",PrenticeHall,1985HolzmannG.,"TheSPINModelChecker:PrinciplesandReferenceManual",AddisonWesleyProfessional.2003Larsen,Peterson,Wang,"ModelCheckingforReal-TimeSystems",Proceedingsofthe10thInternationalConferenceonFundamentalsofComputationTheory,1995TheRavenscarTaskingProfile,specifiedinISO/IEC8652:1995AdawithTC1:2001andAM1:2007
Deleted:
Deleted:
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 117
6.60.3Mechanismoffailure
Theabortofathreadmaynothappenifathreadisinanabort-deferredregionanddoesnotleavethatregion(forwhateverreason)aftertheabortdirectiveisgiven.Similarly,ifabortisimplementedasaneventsenttoathreadanditispermittedtoignoresuchevents,thentheabortwillnotbeobeyed.
Theterminationofathreadmaynothappenifthethreadignoresthedirectivetoterminate,orifthefinalizationofthethreadtobeterminateddoesnotcomplete.
Iftheterminationdirectingthreadcontinuesonthefalseassumptionthatterminationhascompleted,thenanysortoffailuremayoccur.
6.60.4Applicablelanguagecharacteristics
Thisvulnerabilityisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Alllanguagesthatpermitconcurrencywithinthelanguage,orsupportlibrariesandoperatingsystems(suchasPOSIX-compliantorWindowsoperatingsystems)thatprovidehooksforconcurrencycontrol.
6.60.5Avoidingthevulnerabilityormitigatingitseffect
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Usemechanismsofthelanguageorsystemtodeterminethatabortedthreadsorthreadsdirectedtoterminatehavesuccessfullyterminated7.
• Providemechanismstodetectand/orrecoverfromfailedtermination.• Usestaticanalysistechniques,suchasCSPormodel-checkingtoshowthatthreadterminationissafely
handled.• Whereappropriate,useschedulingmodelswherethreadsneverterminate.
6.60.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Provideamechanism(eitheralanguagemechanismoraservicecall)tosignaleitheranotherthreadoranentitythatcanbequeriedbyotherthreadswhenathreadterminates.
6.61Concurrentdataaccess[CGX]
6.61.1Descriptionofapplicationvulnerability
Concurrencypresentsasignificantchallengetoprogramcorrectly,andhasalargenumberofpossiblewaysforfailurestooccur,quiteafewknownattackvectors,andmanypossiblebutundiscoveredattackvectors.Inparticular,datavisiblefrommorethanonethreadandnotprotectedbyasequentialaccesslockcanbecorrupted
7Thesemechanismsmayincludedirectcommunication,runtime-levelchecks,explicitdependencyrelationships,orprogresscountersinsharedcommunicationcodetoverifyprogress.
Deleted:
Deleted: Deleted: Suchmechanismsmayincludedirectcommunication,runtime-levelchecks,explicitdependencyrelationships,orprogresscountersinsharedcommunicationcodetoverifyprogress.
Deleted:
WG23/N0720
118 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
byout-of-orderaccesses.This,inturn,canleadtoincorrectcomputation,prematureprogramtermination,livelock,orsystemcorruption.
6.61.2Crossreferences
CWE:214.InformationExposureThroughProcessEnvironment362.ConcurrentExecutionusingSharedResourcewithImproperSynchronization('RaceCondition')366.RaceConditionWithinaThread368.ContextSwitchingRaceConditions413.ImproperResourceLocking764.MultipleLocksofaCriticalResource765.MultipleUnlocksofaCriticalResource820.MissingSynchronization821.IncorrectSynchronization
JSF:(none)MISRA:(none)ISOIEC8692ProgrammingLanguageAda,withTC1:2001andAM1:2007.BurnsA.andWellingsA.,LanguageVulnerabilities-Let’snotforgetConcurrency,IRTAW14,2009.C.A.RHoare,Amodelforcommunicatingsequentialprocesses,1980
6.61.3Mechanismoffailure
Shareddatacanbemonitoredorupdateddirectlybymorethanonethread,possiblycircumventinganyaccesslockprotocolinoperation.Someconcurrentprogramsdonotuseaccesslockmechanismsbutrelyuponothermechanismssuchastimingorotherprogramstatetodetermineifshareddatacanbereadorupdatedbyathread.Regardless,directvisibilitytoshareddatapermitsdirectaccesstosuchdataconcurrently.Arbitrarybehaviourofanykindcanresult.
6.61.4Applicablelanguagecharacteristics
Thevulnerabilityisintendedtobeapplicableto
• Alllanguagesthatprovideconcurrentexecutionanddatasharing,whetheraspartofthelanguageorbyuseofunderlyingoperationsystemfacilities,includingfacilitiessuchaseventhandlersandinterrupthandlers.
6.61.5Avoidingthevulnerabilityormitigatingitseffect
Softwaredeveloperscanavoidthevulnerabilityormitigateitseffectsinthefollowingways.
• Placealldatainmemoryregionsaccessibletoonlyonethreadatatime.• Uselanguagesandthoselanguagefeaturesthatprovidearobustsequentialprotectionparadigmto
protectagainstdatacorruption
Deleted:
Deleted:
Deleted: Deleted:
Deleted: .Comment [SM5]:
Deleted: Forexample,Ada'sprotectedobjectsandJava'sProtectedclass,provideasafeparadigmwhenaccessingobjectsthatareexclusivetoasingleprogram.
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 119
• Useoperatingsystemprimitives,suchasthePOSIXlockingprimitivesforsynchronization,todevelopaprotocolfollowingtheprinciplesoftheAda“protected”andJava“synchronized”paradigm.
• Whereorderofaccessisimportantforcorrectness,implementblockingandreleasingparadigms,orprovideatestinthesameprotectedregiontocheckforcorrectorderandgenerateerrorsifthetestfails.
6.61.6Implicationsforlanguagedesignandevolution
Infuturestandardisationactivities,thefollowingitemsshouldbeconsidered:
• Languagesthatdonotpresentlyconsiderconcurrencyshouldconsidercreatingprimitivesthatletapplicationsspecifyregionsofsequentialaccesstodata.Mechanismssuchasprotectedregions,Hoaremonitorsorsynchronousmessagepassingbetweenthreadsresultinsignificantlyfewerresourceaccessmistakesinaprogram.
• Providethepossibilityofselectingalternativeconcurrencymodelsthatsupportstaticanalysis,suchasoneofthemodelsthatareknowntohavesafeproperties.Forexamples,see[9],[10],and[17].
6.62Concurrency–Prematuretermination[CGS]
6.62.1Descriptionofapplicationvulnerability
Whenathreadisworkingcooperativelywithotherthreadsandterminatesprematurelyforwhateverreasonbutunknowntootherthreads,thentheportionoftheinteractionprotocolbetweentheterminatedthreadandotherthreadsisdamaged.Thismayresultin:
• indefiniteblockingoftheotherthreadsastheywaitfortheterminatedthreadiftheinteractionprotocolwassynchronous;
• otherthreadsreceivingwrongorincompleteresultsiftheinteractionwasasynchronous;or• deadlockifallotherthreadsweredependingupontheterminatedthreadforsomeaspectoftheir
computationbeforecontinuing.
6.62.2Crossreferences
CWE:364.SignalHandlerRaceCondition
JSF:(none)MISRA:(none)HoareC.A.R.,"CommunicatingSequentialProcesses",PrenticeHall,1985HolzmannG.,"TheSPINModelChecker:PrinciplesandReferenceManual",AddisonWesleyProfessional.2003Larsen,Peterson,Wang,"ModelCheckingforReal-TimeSystems",Proceedingsofthe10thInternationalConferenceonFundamentalsofComputationTheory,1995TheRavenscarTaskingProfile,specifiedinISO/IEC8652:1995AdawithTC1:2001andAM1:2007
Deleted: equivalenttoDeleted: Protected
Deleted:
Deleted:
Formatted: Outline numbered + Level: 1 + Numbering Style:Bullet + Aligned at: 0.63 cm + Indent at: 1.27 cm
Deleted:
Deleted:
WG23/N0720
120 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
6.62.3Mechanismoffailure
Ifathreadterminatesprematurely,threadsthatdependuponservicesfromtheterminatedthread(inthesenseofwaitingexclusivelyforaspecificactionbeforecontinuing)maywaitforeversinceheldlocksmaybeleftinalockedstateresultinginwaitingthreadsneverbeingreleasedormessagesoreventsexpectedfromtheterminatedthreadwillneverbereceived.
Ifathreaddependsontheterminatingthreadandreceivesnotificationoftermination,butthedependentthreadignorestheterminationnotification,thenaprotocolfailurewilloccurinthedependentthread.Forasynchronousterminationevents,anunexpectedeventmaycauseimmediatetransferofcontrolfromtheexecutionofthedependentthreadtoanother(possibleunknown)location,resultingincorruptedobjectsorresources;ormaycauseterminationinthemasterthread6F
8.
Theseconditionscanresultin
• prematureshutdownofthesystem;• corruptionorarbitraryexecutionofcode;• livelock;• deadlock;
dependinguponhowotherthreadshandletheterminationerrors.
Ifthethreadterminationistheresultofanabortandtheabortisimmediate,thereisnothingthatcanbedonewithintheabortedthreadtopreparedataforreturntomastertasks,exceptpossiblythemanagementthread(oroperatingsystem)notifyingotherthreadsthattheeventoccurred.Iftheabortedthreadwasholdingresourcesorperformingactiveupdateswhenaborted,thenanydirectaccessbyotherthreadstosuchlocks,resourcesormemorymayresultincorruptionofthosethreadsorofthecompletesystem,uptoandincludingarbitrarycodeexecution.
6.62.4Applicablelanguagecharacteristics
Thisvulnerabilityisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Languagesthatpermitconcurrencywithinthelanguage,orsupportlibrariesandoperatingsystems(suchasPOSIX-compliantorWindowsoperatingsystems)thatprovidehooksforconcurrencycontrol.
6.62.5Avoidingthevulnerabilityormitigatingitseffect
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Useconcurrencymechanismsthatareknowntoberobust.
8Thismaycausethefailuretopropagatetootherthreads.
Deleted:
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 121
• Atappropriatetimesusemechanismsofthelanguageorsystemtodeterminethatnecessarythreadsarestilloperating9.
• • Handleeventsandexceptionsfromtermination.• Providemanagerthreadstomonitorprogressandtocollectandrecoverfromimproperterminationsor
abortionsofthreads.• Usestaticanalysistechniques,suchasmodelchecking,toshowthatthreadterminationissafelyhandled.
6.62.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Provideamechanismtoprecludetheabortofathreadfromanotherthreadduringcriticalpiecesofcode.Somelanguages(forexample,AdaorReal-TimeJava)provideanotionofanabort-deferredregion.
• Provideamechanismtosignalanotherthread(oranentitythatcanbequeriedbyotherthreads)whenathreadterminates.
• Provideamechanismthat,withincriticalpiecesofcode,defersthedeliveryofasynchronousexceptionsorasynchronoustransfersofcontrol.
6.63Lockprotocolerrors[CGM]
6.63.1Descriptionofapplicationvulnerability
Concurrentprogramsuseprotocolstocontrol
• Thewaythatthreadsinteractwitheachother,• Howtoscheduletherelativeratesofprogress,• Howthreadsparticipateinthegenerationandconsumptionofdata,• Theallocationofthreadstothevariousroles,• Thepreservationofdataintegrity,and• Thedetectionandcorrectionofincorrectoperations.
Whenprotocolsarenotcorrect,orwhenavulnerabilityletsanexploitdestroyaprotocol,thentheconcurrentportionsfailtoworkco-operativelyandthesystembehavesincorrectly.
Thisvulnerabilityisrelatedto6.61Concurrentdataaccess,whichdiscussessituationswheretheprotocoltocontrolaccesstoresourcesisexplicitlyvisibletotheparticipatingpartnersandmakesuseofvisiblesharedresources.Incomparison,thisvulnerabilitydiscussesscenarioswheresuchresourcesareprotectedbyprotocols,andconsiderswaysthattheprotocolitselfmaybemisused.
• 9Suchmechanismsmaybedirectcommunication,runtime-levelchecks,explicitdependencyrelationships,orprogresscountersinsharedcommunicationcodetoverifyprogress.
Deleted:
Moved [3]: Suchmechanismsmaybedirectcommunication,runtime-levelchecks,explicitdependencyrelationships,orprogresscountersinsharedcommunicationcodetoverifyprogress.Handleeventsandexceptionsfromtermination.
Deleted:
Formatted: hyper CharDeleted: 6.61Concurrentdataaccess6.62ConcurrentDataAccess[CGX]
Formatted: hyper Char
Formatted: Normal, Outline numbered + Level: 1 +Numbering Style: Bullet + Aligned at: 0.63 cm + Indent at: 1.27 cm
Moved (insertion) [3]
Deleted: ... [17]
WG23/N0720
122 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
6.63.2Crossreferences
CWE:413.ImproperResourceLocking414.MissingLockCheck609.DoubleCheckedLocking667.ImproperLocking821.IncorrectSynchronization833.Deadlock
JSF:(none)MISRA:(none)C.A.R.Hoare,Amodelforcommunicatingsequentialprocesses,1980Larsen,K.G.,Petterssen,P,Wang,Y,UPPAALinanutshell,1997
6.63.3Mechanismoffailure
Threadsuselocksandprotocolstoscheduletheirwork,controlaccesstoresources,exchangedata,andtoeffectcommunicationwitheachother.Protocolerrorsoccurwhentheexpectedrulesforco-operationarenotfollowed,orwhentheorderoflockacquisitionsandreleasecausesthethreadstoquitworkingtogether.Theseerrorscanbeasaresultof:
• deliberateterminationofoneormorethreadsparticipatingintheprotocol,• disruptionofmessagesorinteractionsintheprotocol,• errorsorexceptionsraisedinthreadsparticipatingintheprotocol,or• errorsintheprogrammingofoneormorethreadsparticipatingintheprotocol.
Insuchsituations,thereareanumberofpossibleconsequences:
• deadlock,whereeverythreadeventuallyquitscomputingasitwaitsforresultsfromanotherthread,nofurtherprogressinthesystemismade,
• livelock,whereoneormorethreadscommandeerallofthecomputingresourceandeffectivelylockouttheotherportions,nofurtherprogressinthesystemismade,
• datamaybecorruptedorlackcurrency(timeliness),or• oneormorethreadsdetectanerrorassociatedwiththeprotocolandterminateprematurely,leavingthe
protocolinanunrecoverablestate.
Thepotentialdamagefromattacksonprotocolsdependsuponthenatureofthesystemusingtheprotocolandtheprotocolitself.Self-containedsystemsusingprivateprotocolscanbedisrupted,butitishighlyunlikelythatpredeterminedexecutions(includingarbitrarycodeexecution)canbeobtained.Ontheotherextreme,threadscommunicatingopenlybetweensystemsusingwell-documentedprotocolscanbedisruptedinanyarbitraryfashionwitheffectssuchasthedestructionofsystemresources(suchasadatabase),thegenerationofwrongbutplausibledata,orarbitrarycodeexecution.Infact,manydocumentedclient-serverbasedattacksconsistofsomeabuseofaprotocolsuchasSQLtransactions.
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 123
6.63.4Applicablelanguagecharacteristics
Thevulnerabilityisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Languagesthatsupportconcurrencydirectly.• Languagesthatpermitcallstooperatingsystemprimitivestoobtainconcurrentbehaviours.• LanguagesthatpermitIOorotherinteractionwithexternaldevicesorservices.• Languagesthatsupportinterrupthandlingdirectlyorindirectly(viatheoperatingsystem).
6.63.5Avoidingthevulnerabilityormitigatingitseffect
Softwaredeveloperscanavoidthevulnerabilityormitigateitseffectsinthefollowingways:
• Considertheuseofsynchronousprotocols,suchasdefinedbyCSP,PetriNetsorbytheAdarendezvousprotocolsincethesecanbestaticallyshowntobefreefromprotocolerrorssuchasdeadlockandlivelock.
• Considertheuseofsimpleasynchronousprotocolsthatexclusivelyuseconcurrentthreadsandprotectedregions,suchasdefinedbytheRavenscarTaskingProfile,whichcanalsobeshownstaticallytohavecorrectbehaviourusingmodelcheckingtechnologies,asshownby[46].
• Whenstaticverificationisnotpossible,considertheuseofdetectionandrecoverytechniquesusingsimplemechanismsandprotocolsthatcanbeverifiedindependentlyfromthemainconcurrencyenvironment.Watchdogtimerscoupledwithcheckpointsconstituteonesuchapproach.
• Usehigh-levelsynchronizationparadigms,forexamplemonitors,rendezvous,orcriticalregions.• Designthearchitectureoftheapplicationtoensurethatsomethreadsortasksneverblock,andcanbe
availablefordetectionofconcurrencyerrorconditionsandforrecoveryinitiation.• Usemodelcheckerstomodeltheconcurrentbehaviourofthecompleteapplicationandcheckforstates
whereprogressfails.• Placealllocksandreleasesinthesamesubprograms,andensurethattheorderofcallsandreleasesof
multiplelocksarecorrect.
6.63.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Raisethelevelofabstractionforconcurrencyservices.• Provideservicesormechanismstodetectandrecoverfromprotocollockfailures.• Designconcurrencyservicesthathelptoavoidtypicalfailuressuchasdeadlock.
6.64Uncontrolledformatstring[SHL]
6.64.1Descriptionofapplicationvulnerability
Manylanguagesuseformatstringtocontrolhowoutputisgeneratedorinputacquired.Ifthecontentsoftheformatstringcanbeinfluencedbyexternaldata,thereisanopportunityforanattackertogainaccesstowhatshouldbeprivatedata,toexecutearbitrarycode,ortocauseresourceexhaustionorbufferoverrun.Evenwithoutanattacker,mistakesinformatstringsmaycauseseriousprogramerrors.
Formatted: Space After: 0 pt
Deleted:
Deleted: RelianceonexternalDeleted: Deleted: [SHLComment [SGM6]: Materialinthisclause(6.64)replacedwithsubmissionbyClivePygott(N0746)andreviewedatpre-meeting51WebEx.
Deleted: Manylanguagesuseformatstringtocontrolhowoutputisgeneratedorinputacquired.Ifpartofthecontentsoftheformatstringcanbeinfluencedbyexternaldata,thereisanopportunityforthemtogainaccesstowhatshouldbeprivatedataandtoexecutearbitrarycode.Thesoftwareusesexternallycontrolledformatstringsininput/outputfunctions,whichcanleadtobufferoverflowsordatarepresentationproblems.
WG23/N0720
124 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
6.64.2Crossreference
CWE:134.UncontrolledFormatString
6.64.3Mechanismoffailure
Formatstringsareparametersofinputoroutputfunctions.Theyconsistoffixedtextandcontrolsequencesthatareassociatedwithotherparametersofthefunction,andwhichcontrolhowtheparametersaredisplayedorloaded.
Thereareanumberofmechanismsrelatingtoformatstringsthatcanleadtosafetyandsecurityproblems.
1. Firstly,foranoutputfunction,theformatstringcontrolswhatiswrittentoanoutputchannel(fileorprinter)oracharacterbuffer.Inthelattercaseparticularlythereisthepossibilityofbufferoverrun,whentheformatstringcausesdatatobewrittenbeyondtheendofthebuffer.InmostlanguagesthatprovideI/Ocontrolusingformatstrings,itispossibleforcontrolsequencesintheformatstringtocontrolthesizeofthevaluewritten(e.g.thecontrolsequence%6dinCbasedlanguagesmeanswriteanintegervalueina6characterfield,paddingwithspacesifnecessary).Ifthesizeofthetargetfieldisaccidentallyormaliciouslyincreased(sayto%6000d)atruntimethenbufferoverrunorresourceexhaustioncanoccur.
2. Astheformatstringcontrolswhatiswrittentoanoutputchannel,ifanattackercaninfluencetheformatstring,thentheycancontrolwhatiswrittentoabuffer,whichcouldincludeexecutablecode.Iftheattackercanthencausecorruptionoftheprogramstack,itmaybepossibletoexecutethiscode.
3. Astheformatstringisinterpretedatrun-timeandexpectstofindaparameterforeachcontrolsequence,iftheformatstringhasmorecontrolsequencesthansuppliedparameters,itislikelythatadditionalvalueswillbereadoffthestack.Thiscanleadtovaluesbeingoutputthatcanleaksensitiveinformation.
4. Formatstringsareabletomodifydatavaluespassedforoutput,withtheresultthatvaluesgeneratedbytheapplicationcanbearbitrarilychanged,withseriousconsequencesforapplicationsthatrelyupontheoutput.AgainusingC-basedlanguagesasanexample,the%ncontrolsequencemeanswritethenumberofcharactersoutputsofarbythisfunctiontothevaluepointedtobytheassociatedparameter.Ifthefunctionshouldbewritingthevalueofanobjectthat’saddresswassuppliedbyapointer,theniftheintendedcontrolsequenceismodifiedto%n,thatvaluewillbechangedinstead.
Theprogrammerrarelyintendsforaformatstringtobeuser-controlled.However,thisweaknessfrequentlyoccursincodethatreadslogmessagesfromafile(forinternationalizationorusercustomization).Suchmessagesmaysafelybeoutputusingaformatstringthatisinterpretedas‘outputastring’,butitisnotunknownfortheprogrammertoomittheformatstringandusethemessagetobeoutputastheformatstring,expectingittoconsistsolelyofliteraltext.Ifthemessagehasbeencorrupted,sothatitincludescontrolsequences,anyoftheissuesmentionedabovemayoccur..
6.64.4Applicablelanguagecharacteristics
Thisvulnerabilityisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Languagesthatsupportformatstringsforinput/outputfunctions.
Deleted: Theprogrammerrarelyintendsforaformatstringtobeuser-controlledatall.Thisweaknessfrequentlyoccursincodethatconstructslogmessages,whereaconstantformatstringisomitted.... [18]
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 125
6.64.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Ensurethatallformatstringfunctionsarepassedasstaticstringwhichcannotbecontrolledbytheuserandthatthepropernumberofargumentsisalwayssenttothatfunction.Inparticular,whereafunctionexpectsaformatstring,alwayssupplyone,evenifitistheapparentlyredundant‘writeastring’.Neverletanon-statictextstringbeoutputastheformatstring.
• EnsureallcontrolsequencesusedtoformatI/Omatchtheassociatedparameter.
6.64.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Ensureallformatstringsareverifiedtobecorrectinregardtotheassociatedargumentorparameter.
Deleted: Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways: ... [19]
WG23/N0720
126 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
7.Applicationvulnerabilities
7.1General
Thisclauseprovidesdescriptionsofselectedapplicationvulnerabilitieswhichhavebeenfoundandexploitedinanumberofapplicationsandwhichhavewellknownmitigationtechniques,andwhichresultfromdesigndecisionsmadebycodersintheabsenceofsuitablelanguagelibraryroutinesorothermechanisms.Forthesevulnerabilities,eachdescriptionprovides:
• asummaryofthevulnerability,• typicalmechanismsoffailure,and• techniquesthatprogrammerscanusetoavoidthevulnerability
Thesevulnerabilitiesareapplication-relatedratherthanlanguage-related.Theyarewritteninalanguage-independentmanner,andtherearenocorrespondingsectionsintheannexes.
7.2Unrestrictedfileupload[CBF]
7.2.1Descriptionofapplicationvulnerability
Afirststepoftenusedtoattackistogetanexecutableonthesystemtobeattacked.Thentheattackonlyneedstoexecutethiscode.Manytimesthisfirststepisaccomplishedbyunrestrictedfileupload.Inmanyoftheseattacks,themaliciouscodecanobtainthesameprivilegeofaccessastheapplication,orevenadministratorprivilege.
7.2.2Crossreference
CWE:434.UnrestrictedUploadofFilewithDangerousType
7.2.3Mechanismoffailure
Thereareseveralfailuresassociatedwithanuploadedfile:
• Executingarbitrarycode.• Phishingpageaddedtoawebsite.• Defacingawebsite.• Creatingavulnerabilityforotherattacks.• Browsingthefilesystem.• Creatingadenialofservice.• Uploadingamaliciousexecutabletoaserver,whichcouldbeexecutedwithadministratorprivilege.
7.2.4Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Allowonlycertainfileextensions,commonlyknownasawhite-list.
Deleted:
Deleted:
Deleted:
Deleted: Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 127
• Disallowcertainfileextensions,commonlyknownasablack-list.• Useautilitytocheckthetypeofthefile.• Checkthecontent-typeintheheaderinformationofallfilesthatareuploaded.Thepurposeofthe
content-typefieldistodescribethedatacontainedinthebodycompletelyenoughthatthereceivingagentcanpickanappropriateagentormechanismtopresentthedatatotheuser,orotherwisedealwiththedatainanappropriatemanner.
• Useadedicatedlocation,whichdoesnothaveexecutionprivileges,tostoreandvalidateuploadedfiles,andthenservethesefilesdynamically.
• Requireauniquefileextension(namedbytheapplicationdeveloper),soonlytheintendedtypeofthefileisusedforfurtherprocessing.Eachuploadfacilityofanapplicationcouldhandleauniquefiletype.
• RemoveallUnicodecharactersandallcontrolcharacters4F
10fromthefilenameandtheextensions.• Setalimitforthefilenamelength;includingthefileextension.InanNTFS(NewTechnologyFileSystem)
partition,usuallyalimitof255characters,withoutpathinformationwillsuffice.• Setupperandlowerlimitsonfilesize.Settingtheselimitscanhelpindenialofserviceattacks.
Alloftheabovehavesomeshortcomings,forexample,aGIF(.gif)filemaycontainafree-formcommentfield,andthereforeasanitycheckofthefile’scontentsisnotalwayspossible.Anattackercanhidecodeinafilesegmentthatwillstillbeexecutedbytheapplicationorserver.Inmanycasesitwilltakeacombinationofthetechniquesfromtheabovelisttoavoidthisvulnerability.
7.3Downloadofcodewithoutintegritycheck[DLB]
7.3.1Descriptionofapplicationvulnerability
Someapplicationsdownloadsourcecodeorexecutablesfromaremote,andimplicitlytrusted,location(suchastheapplicationauthor)andusethesourcecodeorinvoketheexecutableswithoutsufficientlyverifyingtheintegrityofthedownloadedfiles.
7.3.2Crossreference
CWE:494.DownloadofCodeWithoutIntegrityCheck
7.3.3Mechanismoffailure
Anattackercanexecutemaliciouscodebycompromisingthehostserverusedtodownloadcodeorexecutables,performingDNSspoofing,ormodifyingthecodeintransit.
7.3.4Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• PerformproperforwardandreverseDNSlookupstodetectDNSspoofing.Encryptthecodewitha
10Seehttp://www.ascii.cl/control-characters.htm
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
WG23/N0720
128 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
reliableencryptionschemebeforetransmitting.Thisisonlyapartialsolutionsinceitwillnotpreventyourcodefrombeingmodifiedonthehostingsiteorintransit.
• Useavettedlibraryorframeworkthatdoesnotallowthisweaknesstooccurorprovidesconstructsthatmakethisweaknesseasiertoavoid.Specifically,itmaybehelpfultousetoolsorframeworkstoperformintegritycheckingonthetransmittedcode.
Ifprovidingcodethatistobedownloaded,suchasforautomaticupdatesofsoftware,thenusecryptographicsignaturesforthecodeandmodifythedownloadclientstoverifythesignatures.
7.4Executingorloadinguntrustedcode[XYS]
7.4.1Descriptionofapplicationvulnerability
Executingcommandsorloadinglibrariesfromanuntrustedsourceorinanuntrustedenvironmentcancauseanapplicationtoexecutemaliciouscommands(andpayloads)onbehalfofanattacker.
7.4.2Crossreference
CWE:114.ProcessControl306.MissingAuthenticationforCriticalFunction
CERTCguidelines:PRE09-C,ENV02-C,andENV03-C
7.4.3Mechanismoffailure
Processcontrolvulnerabilitiestaketwoforms:
• Anattackercanchangethecommandthattheprogramexecutessothattheattackerexplicitlycontrolswhatthecommandis.
• Anattackercanchangetheenvironmentinwhichthecommandexecutessothattheattackerimplicitlycontrolswhatthecommandmeans.
Consideringonlythefirstscenario,thepossibilitythatanattackermaybeabletocontrolthecommandthatisexecuted,processcontrolvulnerabilitiesoccurwhen:
• Dataenterstheapplicationfromasourcethatisnottrusted.• Thedataisusedasoraspartofastringrepresentingacommandthatisexecutedbytheapplication.• Byexecutingthecommand,theapplicationgivesanattackeraprivilegeorcapabilitythattheattacker
wouldnototherwisehave.
7.4.4Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Ensurethatlibrariesthatareloadedarewellunderstoodandcomefromatrustedsourcewithadigitalsignature.Theapplicationcanexecutecodecontainedinnativelibraries,whichoftencontaincallsthataresusceptibletoothersecurityproblems,suchasbufferoverflowsorcommandinjection.
Deleted: LDeleted: UDeleted: Code
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 129
• Validateallnativelibraries.• Determineiftheapplicationrequirestheuseofthenativelibrary.Itcanbeverydifficulttodetermine
whattheselibrariesactuallydo,andthepotentialformaliciouscodeishigh.• Tohelppreventbufferoverflowattacks,validateallinputtonativecallsforcontentandlength.• Ifthenativelibrarydoesnotcomefromatrustedsource,reviewthesourcecodeofthelibrary.The
libraryshouldbebuiltfromthereviewedsourcebeforeusingit.11
7.5Inclusionoffunctionalityfromuntrustedcontrolsphere[DHU]
7.5.1Descriptionofapplicationvulnerability
Thesoftwareimports,requires,orincludesexecutablefunctionality(suchasalibrary)fromasourcethatisunknowntotheuser,unexpectedorotherwise.Anycalloruseoftheincludedfunctionallycanresultinunexpectedbehaviour,uptoandincludingarbitraryexecution.
7.5.2Crossreference
CWE:98.ImproperControlofFilenameforInclude/RequireStatementinPHPProgram('PHPFileInclusion')829.InclusionofFunctionalityfromUntrustedControlSphere
7.5.3Mechanismoffailure
Whenincludingthird-partyfunctionality,suchasawebwidget,library,orothersourceoffunctionality,thesoftwaremusteffectivelytrustthatfunctionality.Withoutsufficientprotectionmechanisms,thefunctionalitycouldbemaliciousinnature(eitherbycomingfromanuntrustedsource,beingspoofed,orbeingmodifiedintransitfromatrustedsource).Thefunctionalitymightalsocontainitsownweaknesses,orgrantaccesstoadditionalfunctionalityandstateinformationthatshouldbekeptprivatetothebasesystem,suchassystemstateinformation,sensitiveapplicationdata,ortheDOMofawebapplication.
Thismightleadtomanydifferentconsequencesdependingontheincludedfunctionality,butsomeexamplesincludeinjectionofmalware,informationexposurebygrantingexcessiveprivilegesorpermissionstotheuntrustedfunctionality,DOM-basedXSSvulnerabilities,stealinguser'scookies,oropenredirecttomalware.
7.5.4Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Useavettedlibraryorframeworkthatdoesnotallowthisweaknesstooccurorprovideconstructsthatmakethisweaknesseasiertoavoid.
• Whenthesetofacceptableobjects,suchasfilenamesorURLs,islimitedorknown,createamappingfromasetoffixedinputvalues(suchasnumericIDs)totheactualfilenamesorURLs,andrejectallother
11Thismayrequireescrowonthesourcecodeforproprietarysoftware.
Deleted:
Formatted: Line spacing: multiple 1.15 li, Outline numbered+ Level: 1 + Numbering Style: Bullet + Aligned at: 0.71 cm +Tab after: 1.35 cm + Indent at: 1.35 cm
Deleted:
Deleted:
WG23/N0720
130 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
inputs12.
• Foranysecuritychecksthatareperformedontheclientside,ensurethatthesechecksareduplicatedontheserverside,inordertoavoidCWE-60213.
7.6Useofuncheckeddatafromanuncontrolledortaintedsource[EFS]
7.6.1Descriptionofapplicationvulnerability
Thisvulnerabilitycoversageneralclassofbehaviours,theidentificationofwhichisreferredtoas‘taintanalysis’.
Wheneveraprogramgetsdatafromanexternalsource,thereisapossibilitythatthatdatamayhavebeentamperedwithbyanattackerattemptingtoinducetheprogramintoperformingsomedamagingaction,ormayhavebeencorruptedaccidentlyleadingtothesameresult.Suchdataiscalled‘tainted’.
Thegeneralprincipleshouldbethatbeforetainteddataisused,itshouldbecheckedtoensurethatitiswithinacceptableboundsorhasanappropriatestructure,orotherwisecanbeacceptedasuntainted,andsosafetouse.
7.6.2Crossreference
[TS17961]Csecurecodingrulesannex
7.6.3Mechanismoffailure
Theprinciplemechanismsoffailureare:
• Useofthedatainanarithmeticexpression,causingtheoneoftheproblemsdescribedinsection6.• Useofthedatainacalltoafunctionthatexecutesasystemcommand.• Useofthedatainacalltoafunctionthatestablishesacommunicationsconnection.
7.6.4Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitseffectsinthefollowingways.
Differentmechanismsoffailurerequiredifferentmitigations,whichalsomaydependonhowthetainteddataistobeused:
• Testpotentiallytainteddatausedinanarithmeticexpressiontoensurethatitdoesnotcausearithmeticoverflow,dividebyzeroorbufferoverflow
• Checkintegerdatausedtoallocatememoryorotherresourcestoensurethatitwonotcauseresourceexhaustion
12Forexample,ID1couldmapto"inbox.txt"andID2couldmapto"profile.txt".FeaturessuchastheESAPIAccessReferenceMapprovidethiscapability.
13Attackerscanbypasstheclient-sidechecksbymodifyingvaluesafterthecheckshavebeenperformed,orbychangingtheclienttoremovetheclient-sidechecksentirely.Then,thesemodifiedvalueswouldbesubmittedtotheserver.
Deleted:
Moved [4]: Forexample,ID1couldmapto"inbox.txt"andID2couldmapto"profile.txt".FeaturessuchastheESAPIAccessReferenceMapprovidethiscapability.
Comment [SM8]: AI–steve–summarizethatCWEandcheckthefootnotes.
Moved [5]: Attackerscanbypasstheclient-sidechecksbymodifyingvaluesafterthecheckshavebeenperformed,orbychangingtheclienttoremovetheclient-sidechecksentirely.Then,thesemodifiedvalueswouldbesubmittedtotheserver.
Deleted: [EFS
Deleted:
Deleted: n’t
Deleted: n’t
Moved (insertion) [4]
Moved (insertion) [5]
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 131
• Checkstringspassedtosystemfunctionstoensurethattheyarewellformedandhaveanexpectedstructure1415.
7.7Cross-sitescripting[XYT]
7.7.1Descriptionofapplicationvulnerability
Cross-sitescripting(XSS)occurswhendynamicallygeneratedwebpagesdisplayinput,suchaslogininformationthatisnotproperlyvalidated,allowinganattackertoembedmaliciousscriptsintothegeneratedpageandthenexecutethescriptonthemachineofanyuserthatviewsthesite.Ifsuccessful,cross-sitescriptingvulnerabilitiescanbeexploitedtomanipulateorstealcookies,createrequeststhatcanbemistakenforthoseofavaliduser,compromiseconfidentialinformation,orexecutemaliciouscodeontheendusersystemsforavarietyofnefariouspurposes.
7.7.2Crossreference
CWE:79.FailuretoPreserveWebPageStructure('Cross-siteScripting')80.FailuretoSanitizeScript-RelatedHTMLTagsinaWebPage(BasicXSS)81.FailuretoSanitizeDirectivesinanErrorMessageWebPage82.FailuretoSanitizeScriptinAttributesofIMGTagsinaWebPage83.FailuretoSanitizeScriptinAttributesinaWebPage84.FailuretoResolveEncodedURISchemesinaWebPage85.DoubledCharacterXSSManipulations86.InvalidCharactersinIdentifiers87.AlternateXSSSyntax
7.7.3Mechanismoffailure
Cross-sitescripting(XSS)vulnerabilitiesoccurwhenanattackerusesawebapplicationtosendmaliciouscode,generallyJavaScript,toadifferentenduser.Whenawebapplicationusesinputfromauserintheoutputitgenerateswithoutfilteringit,anattackercaninsertanattackinthatinputandthewebapplicationsendstheattacktootherusers.Theendusertruststhewebapplication,andtheattacksexploitthattrusttodothingsthatwouldnotnormallybeallowed.Attackersfrequentlyuseavarietyofmethodstoencodethemaliciousportionofthetag,suchasusingUnicode,sotherequestlookslesssuspicioustotheuser.
XSSattackscangenerallybecategorizedintotwocategories:storedandreflected.Storedattacksarethosewheretheinjectedcodeispermanentlystoredonthetargetserversinadatabase,messageforum,visitorlog,andsoforth.Reflectedattacksarethosewheretheinjectedcodetakesanotherroutetothevictim,suchasinanemail
14Thisvulnerabilityisdescribedas‘datafromanuncontrolledsource’,asadistinctionmayneedtobedrawnbetweendatafromoutsidetheprogram,butwhichisstilltrustworthy,anddatathatcomesfromasourcethatcouldcrediblybemodifiedbyanattacker,orotherwisecorrupted.
15Forexample,datareadfromafilemayberegardedastrustworthy(untainted)ifthefileisread-onlyandinsideafirewall,butpotentiallytaintedifitisfromamoregenerallyaccessiblelocation.See7.22,Missingrequiredcryptographicstep.
Deleted: (forexamplesee
Moved [6]: Thisvulnerabilityisdescribedas‘datafromanuncontrolledsource’,asadistinctionmayneedtobedrawnbetweendatafromoutsidetheprogram,butwhichisstilltrustworthy,anddatathatcomesfromasourcethatcouldcrediblybemodifiedbyanattacker,orotherwisecorrupted.
Moved [7]: Forexample,datareadfromafilemayberegardedastrustworthy(untainted)ifthefileisread-onlyandinsideafirewall,butpotentiallytaintedifitisfromamoregenerallyaccessiblelocation.See7.11,MissingCryptographicStep.
Deleted: S
Deleted:
Deleted:
Deleted:
Deleted:
Moved (insertion) [6]
Moved (insertion) [7]Deleted: 11Deleted: CDeleted: S
WG23/N0720
132 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
message,oronsomeotherserver.Whenauseristrickedintoclickingalinkorsubmittingaform,theinjectedcodetravelstothevulnerablewebserver,whichreflectstheattackbacktotheuser'sbrowser.Thebrowserthenexecutesthecodebecauseitcamefroma'trusted'server.ForareflectedXSSattacktowork,thevictimmustsubmittheattacktotheserver.Thisisstillaverydangerousattackgiventhenumberofpossiblewaystotrickavictimintosubmittingsuchamaliciousrequest,includingclickingalinkonamaliciousWebsite,inanemail,orinaninter-officeposting.
XSSflawsareverycommoninwebapplications,astheyrequireagreatdealofdeveloperdisciplinetoavoidtheminmostapplications.ItisrelativelyeasyforanattackertofindXSSvulnerabilities.Someofthesevulnerabilitiescanbefoundusingscanners,andsomeexistinolderwebapplicationservers.TheconsequenceofanXSSattackisthesameregardlessofwhetheritisstoredorreflected.
Thedifferenceisinhowthepayloadarrivesattheserver.XSScancauseavarietyofproblemsfortheenduserthatrangeinseverityfromanannoyancetocompleteaccountcompromise.ThemostsevereXSSattacksinvolvedisclosureoftheuser'ssessioncookie,whichallowsanattackertohijacktheuser'ssessionandtakeovertheiraccount.Otherdamagingattacksincludethedisclosureofenduserfiles,installationofTrojanhorseprograms,redirectingtheusertosomeotherpageorsite,andmodifyingpresentationofcontent.
Cross-sitescripting(XSS)vulnerabilitiesoccurwhen:
• DataentersaWebapplicationthroughanuntrustedsource,mostfrequentlyawebrequest.Thedataisincludedindynamiccontentthatissenttoawebuserwithoutbeingvalidatedformaliciouscode.
• ThemaliciouscontentsenttothewebbrowseroftentakestheformofasegmentofJavaScript,butmayalsoincludeHTML,Flashoranyothertypeofcodethatthebrowsermayexecute.ThevarietyofattacksbasedonXSSisalmostlimitless,buttheycommonlyincludetransmittingprivatedatalikecookiesorothersessioninformationtotheattacker,redirectingthevictimtowebcontentcontrolledbytheattacker,orperformingothermaliciousoperationsontheuser'smachineundertheguiseofthevulnerablesite.
Cross-sitescriptingattackscanoccurwhereveranuntrusteduserhastheabilitytopublishcontenttoatrustedwebsite.Typically,amalicioususerwillcraftaclient-sidescript,which—whenparsedbyawebbrowser—performssomeactivity(suchassendingallsitecookiestoagivene–mailaddress).Iftheinputisunchecked,thisscriptwillbeloadedandrunbyeachuservisitingthewebsite.Sincethesiterequestingtorunthescripthasaccesstothecookiesinquestion,themaliciousscriptdoesalso.Thereareseveralotherpossibleattacks,suchasrunning"ActiveX"controls(underMicrosoftInternetExplorer)fromsitesthatauserperceivesastrustworthy;cookietheftishoweverbyfarthemostcommon.Alloftheseattacksareeasilypreventedbyensuringthatnoscripttags—orforgoodmeasure,HTMLtagsatall—areallowedindatatobepostedpublicly.
SpecificinstancesofXSSare:
• 'Basic'XSSinvolvesacompletelackofcleansingofanyspecialcharacters,includingthemostfundamentalXSSelementssuchas"<",">",and"&".
• Awebdeveloperdisplaysinputonanerrorpage(suchasacustomized403Forbiddenpage).Ifanattackercaninfluenceavictimtoview/requestawebpagethatcausesanerror,thentheattackmaybesuccessful.
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 133
• AWebapplicationthattrustsinputintheformofHTMLIMGtagsispotentiallyvulnerabletoXSSattacks.AttackerscanembedXSSexploitsintothevaluesforIMGattributes(suchasSRC)thatisstreamedandthenexecutedinavictim'sbrowser.Notethatwhenthepageisloadedintoauser'sbrowser,theexploitwillautomaticallyexecute.
• Thesoftwaredoesnotfilter"JavaScript:"orotherURI's(UniformResourceIdentifier)fromdangerousattributeswithintags,suchasonmouseover,onload,onerror,orstyle.
• ThewebapplicationfailstofilterinputforexecutablescriptdisguisedwithURIencodings.• Thewebapplicationfailstofilterinputforexecutablescriptdisguisedusingdoublingoftheinvolved
characters.• Thesoftwaredoesnotstripoutinvalidcharactersinthemiddleoftagnames,schemes,andother
identifiers,whicharestillrenderedbysomewebbrowsersthatignorethecharacters.• Thesoftwarefailstofilteralternatescriptsyntaxprovidedbytheattacker.
Cross-sitescriptingattacksmayoccuranywherethatpossiblymalicioususersareallowedtopostunregulatedmaterialtoatrustedwebsitefortheconsumptionofothervalidusers.Themostcommonexamplecanbefoundinbulletin-boardwebsitesthatprovidewebbasedmailinglist-stylefunctionality.Themostcommonattackperformedwithcross-sitescriptinginvolvesthedisclosureofinformationstoredinusercookies.Insomecircumstancesitmaybepossibletorunarbitrarycodeonavictim'scomputerwhencross-sitescriptingiscombinedwithotherflaws.
7.7.4Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Carefullycheckeachinputparameteragainstarigorouspositivespecification(white-list)definingthespecificcharactersandformatallowed.
• Sanitizeallinput,notjustparametersthattheuserissupposedtospecify,butalldataintherequest,includinghiddenfields,cookies,headers,theURL(UniformResourceLocator)itself,andsoforth16.
• ValidateallpartsoftheHTTP(HypertextTransferProtocol)request.Dataisfrequentlyencounteredfromtherequestthatisreflectedbytheapplicationserverortheapplicationthatthedevelopmentteamdidnotanticipate.Also,afieldthatisnotcurrentlyreflectedmaybeusedbyafuturedeveloper.
7.8URLredirectiontountrustedsite('openredirect')[PYQ]
7.8.1Descriptionofapplicationvulnerability
Awebapplicationacceptsauser-controlledinputthatspecifiesalinktoanexternalsite,andusesthatlinkinaredirectwithoutcheckingthattheURLpointstoatrustedlocation.Thissimplifiesphishingattacks.
7.8.2Crossreference
CWE:601.URLRedirectiontoUntrustedSite('OpenRedirect')
16AcommonmistakethatleadstocontinuingXSSvulnerabilitiesistovalidateonlyfieldsthatareexpectedtoberedisplayedbythesite.
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Moved [8]: AcommonmistakethatleadstocontinuingXSSvulnerabilitiesistovalidateonlyfieldsthatareexpectedtoberedisplayedbythesite.
Deleted:
Formatted: Space After: 0 pt, Outline numbered + Level: 1+ Numbering Style: Bullet + Aligned at: 0.71 cm + Tab after: 1.35 cm + Indent at: 1.35 cm, Tabs: 1.9 cm, List tab
Deleted:
Deleted: Comment [SM9]: Huh?AI–Larry–lookat7.7again.
Deleted: RDeleted: UDeleted: SDeleted: ODeleted: RDeleted: ]
Moved (insertion) [8]
WG23/N0720
134 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
7.8.3Mechanismoffailure
AnhttpparametermaycontainaURLvalueandcouldcausethewebapplicationtoredirecttherequesttothespecifiedURL.BymodifyingtheURLvaluetoamalicioussite,anattackermaysuccessfullylaunchaphishingscamandstealusercredentials.Becausetheservernameinthemodifiedlinkisidenticaltotheoriginalsite,phishingattemptshaveamoretrustworthyappearance.
7.8.4Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• InputValidationo Assumeallinputismalicious.Usean"acceptknowngood"inputvalidationstrategy,forexample,
useawhitelistofacceptableinputsthatstrictlyconformtospecifications.Rejectanyinputthatdoesnotstrictlyconformtospecifications,ortransformitintosomethingthatdoes.Donotrelyexclusivelyonlookingformaliciousormalformedinputs(forexample,donotrelyonablacklist).However,blacklistscanbeusefulfordetectingpotentialattacksordeterminingwhichinputsaresomalformedthattheyshouldberejectedoutright.
o Considerallpotentiallyrelevantproperties,includinglength,typeofinput,thefullrangeofacceptablevalues,missingorextrainputs,syntax,consistencyacrossrelatedfields,andconformancetobusinessrules.Asanexampleofbusinessrulelogic,"boat"maybesyntacticallyvalidbecauseitonlycontainsalphanumericcharacters,butitisnotvalidifacolorsuchas"red"or"blue"wasexpected.UseawhitelistofapprovedURLsordomainstobeusedforredirection.
7.9Injection[RST]
7.9.1Descriptionofapplicationvulnerability
Injectionproblemsspanawiderangeofinstantiations.Thebasicformofthisweaknessinvolvesthesoftwareallowinginjectionofadditionaldataininputdatatoalterthecontrolflowoftheprocess.Commandinjectionproblemsareasubsetofinjectionproblems,inwhichtheprocesscanbetrickedintocallingexternalprocessesofanattacker’schoicethroughtheinjectionofcommandsyntaxintotheinputdata.Multipleleading/internal/trailingspecialelementsinjectedintoanapplicationthroughinputcanbeusedtocompromiseasystem.Asdataisparsed,improperlyhandledmultipleleadingspecialelementsmaycausetheprocesstotakeunexpectedactionsthatresultinanattack.Softwaremayallowtheinjectionofspecialelementsthatarenon-typicalbutequivalenttotypicalspecialelementswithcontrolimplications.Thisfrequentlyoccurswhentheproducthasprotecteditselfagainstspecialelementinjection.Softwaremayallowinputstobefeddirectlyintoanoutputfilethatislaterprocessedascode,suchasalibraryfileortemplate.Lineorsectiondelimitersinjectedintoanapplicationcanbeusedtocompromiseasystem.
Manyinjectionattacksinvolvethedisclosureofimportantinformation—intermsofbothdatasensitivityandusefulnessinfurtherexploitation.Insomecasesinjectablecodecontrolsauthentication;thismayleadtoaremotevulnerability.Injectionattacksarecharacterizedbytheabilitytosignificantlychangetheflowofagivenprocess,andinsomecases,totheexecutionofarbitrarycode.Datainjectionattacksleadtolossofdataintegrity
Formatted
Deleted:
Deleted: Whenperforminginputvalidation,c
Formatted: Font:Formatted: Font:
Deleted:
Formatted: Font:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 135
innearlyallcasesasthecontrol-planedatainjectedisalwaysincidentaltodatarecallorwriting.Oftentheactionsperformedbyinjectedcontrolcodearenotlogged.
SQLinjectionattacksareacommoninstantiationofinjectionattack,inwhichSQLcommandsareinjectedintoinputtoeffecttheexecutionofpredefinedSQLcommands.SinceSQLdatabasesgenerallyholdsensitivedata,lossofconfidentialityisafrequentproblemwithSQLinjectionvulnerabilities.IfpoorlyimplementedSQLcommandsareusedtocheckusernamesandpasswords,itmaybepossibletoconnecttoasystemasanotheruserwithnopreviousknowledgeofthepassword.IfauthorizationinformationisheldinaSQLdatabase,itmaybepossibletochangethisinformationthroughthesuccessfulexploitationoftheSQLinjectionvulnerability.Justasitmaybepossibletoreadsensitiveinformation,itisalsopossibletomakechangesorevendeletethisinformationwithaSQLinjectionattack.
Injectionproblemsencompassawidevarietyofissues—allmitigatedinverydifferentways.Themostimportantissuetonoteisthatallinjectionproblemsshareonethingincommon—theyallowfortheinjectionofcontroldataintotheusercontrolleddata.Thismeansthattheexecutionoftheprocessmaybealteredbysendingcodeinthroughlegitimatedatachannels,usingnoothermechanism.Whilebufferoverflowsandmanyotherflawsinvolvetheuseofsomefurtherissuetogainexecution,injectionproblemsneedonlyforthedatatobeparsed.Manyinjectionattacksinvolvethedisclosureofimportantinformationintermsofbothdatasensitivityandusefulnessinfurtherexploitation.Insomecasesinjectablecodecontrolsauthentication,thismayleadtoaremotevulnerability.
7.9.2Crossreference
CWE:74.FailuretoSanitizeDataintoaDifferentPlane('Injection')76.FailuretoResolveEquivalentSpecialElementsintoaDifferentPlane78.FailuretoSanitizeDataintoanOSCommand(aka‘OSCommandInjection’)89:ImproperNeutralizationofSpecialElementsusedinanSQLCommand('SQLInjection')90.FailuretoSanitizeDataintoLDAPQueries(aka‘LDAPInjection’)91.XMLInjection(akaBlindXPathInjection)92.CustomSpecialCharacterInjection95.InsufficientControlofDirectivesinDynamicallyCodeEvaluatedCode(aka'EvalInjection')97.FailuretoSanitizeServer-SideIncludes(SSI)WithinaWebPage98.InsufficientControlofFilenameforInclude/RequireStatementinPHPProgram(aka‘PHPFileInclusion’)99.InsufficientControlofResourceIdentifiers(aka‘ResourceInjection’)144.FailuretoSanitizeLineDelimiters145.FailuretoSanitizeSectionDelimiters161.FailuretoSanitizeMultipleLeadingSpecialElements163.FailuretoSanitizeMultipleTrailingSpecialElements165.FailuretoSanitizeMultipleInternalSpecialElements166.FailuretoHandleMissingSpecialElement167.FailuretoHandleAdditionalSpecialElement168.FailuretoResolveInconsistentSpecialElements564.SQLInjection:Hibernate
CERTCguidelines:FIO30-C
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
WG23/N0720
136 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
7.9.3Mechanismoffailure
Asoftwaresystemthatacceptsandexecutesinputintheformofoperatingsystemcommands(suchassystem(),exec(),open())couldallowanattackerwithlesserprivilegesthanthetargetsoftwaretoexecutecommandswiththeelevatedprivilegesoftheexecutingprocess.Commandinjectionisacommonproblemwithwrapperprograms.Often,partsofthecommandtoberunarecontrollablebytheenduser.Ifamalicioususerinjectsacharacter(suchasasemi-colon)thatdelimitstheendofonecommandandthebeginningofanother,hemaythenbeabletoinsertanentirelynewandunrelatedcommandtodowhateverhepleases.
Dynamicallygeneratingoperatingsystemcommandsthatincludeuserinputasparameterscanleadtocommandinjectionattacks.Anattackercaninsertoperatingsystemcommandsormodifiersintheuserinputthatcancausetherequesttobehaveinanunsafemanner.Suchvulnerabilitiescanbeverydangerousandleadtodataandsystemcompromise.Ifnovalidationoftheparametertotheexeccommandexists,anattackercanexecuteanycommandonthesystemtheapplicationhastheprivilegetoaccess.
Therearetwoformsofcommandinjectionvulnerabilities.Anattackercanchangethecommandthattheprogramexecutes(theattackerexplicitlycontrolswhatthecommandis).Alternatively,anattackercanchangetheenvironmentinwhichthecommandexecutes(theattackerimplicitlycontrolswhatthecommandmeans).Thefirstscenariowhereanattackerexplicitlycontrolsthecommandthatisexecutedcanoccurwhen:
• Dataenterstheapplicationfromanuntrustedsource.• Thedataispartofastringthatisexecutedasacommandbytheapplication.• Byexecutingthecommand,theapplicationgivesanattackeraprivilegeorcapabilitythattheattacker
wouldnototherwisehave.
Evalinjectionoccurswhenthesoftwareallowsinputstobefeddirectlyintoafunction(suchas"eval")thatdynamicallyevaluatesandexecutestheinputascode,usuallyinthesameinterpretedlanguagethattheproductuses.Evalinjectionisprevalentinhandler/dispatchproceduresthatmightwanttoinvokealargenumberoffunctions,orsetalargenumberofvariables.
APHPfileinclusionoccurswhenaPHPproductusesrequireorincludestatements,orequivalentstatements,thatuseattacker-controlleddatatoidentifycodeorHTML(HyperTextMarkupLanguage)tobedirectlyprocessedbythePHPinterpreterbeforeinclusioninthescript.
Aresourceinjectionissueoccurswhenthefollowingtwoconditionsaremet:
• Anattackercanspecifytheidentifierusedtoaccessasystemresource.Forexample,anattackermightbeabletospecifypartofthenameofafiletobeopenedoraportnumbertobeused.
• Byspecifyingtheresource,theattackergainsacapabilitythatwouldnototherwisebepermitted.Forexample,theprogrammaygivetheattackertheabilitytooverwritethespecifiedfile,runwithaconfigurationcontrolledbytheattacker,ortransmitsensitiveinformationtoathird-partyserver.Note:Resourceinjectionthatinvolvesresourcesstoredonthefilesystemgoesbythenamepathmanipulationandisreportedinseparatecategory.SeetheError!Referencesourcenotfound.descriptionforfurtherdetailsofthisvulnerability.Allowinguserinputtocontrolresourceidentifiersmayenableanattackertoaccessormodifyotherwiseprotectedsystemresources.
Deleted:
Deleted: Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted: Deleted: Error!Referencesourcenotfound.Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 137
Lineorsectiondelimitersinjectedintoanapplicationcanbeusedtocompromiseasystem.Asdataisparsed,aninjected/absent/malformeddelimitermaycausetheprocesstotakeunexpectedactionsthatresultinanattack.OneexampleofasectiondelimiteristheboundarystringinamultipartMIME(MultipurposeInternetMailExtensions)message.Inmanycases,doubledlinedelimiterscanserveasasectiondelimiter.
7.9.4Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Assumeallinputismalicious,anduseanappropriatecombinationofblack-listsandwhite-liststoensureonlyvalid,expectedandappropriateinputisprocessedbythesystem.
• Narrowlydefinethesetofsafecharactersbasedontheexpectedvaluesoftheparameterintherequest.• Anticipatethatdelimitersandspecialelementswouldbeinjected/removed/manipulatedintheinput
vectorsoftheirsoftwaresystemandprogramappropriatemechanismstohandlethem.• ImplementSQLstringsusingpreparedstatementsthatbindvariables.• Usevigorouswhite-liststylecheckingonanyuserinputthatmaybeusedinaSQLcommand.Ratherthan
escapemeta-characters,itissafesttodisallowthementirelysincethelateruseofdatathathavebeenenteredinthedatabasemayneglecttoescapemeta-charactersbeforeuse.
• FollowtheprincipleofleastprivilegewhencreatinguseraccountstoaSQLdatabase.Iftherequirementsofthesystemindicatethatusersarepermittedtoreadandmodifytheirowndata,thenlimittheirprivilegessotheycannotread/writeothers'data.
• Assignpermissionstothesoftwaresystemthatpreventstheuserfromaccessing/openingprivilegedfiles.• Restructurecodesothatthereisnotaneedtousetheeval()utility.
7.10Unquotedsearchpathorelement[XZQ]
7.10.1Descriptionofapplicationvulnerability
Stringsinjectedintoasoftwaresystemthatarenotquotedcanpermitanattackertoexecutearbitrarycommands.
7.10.2Crossreference
CWE:428.UnquotedSearchPathorElement
CERTCguidelines:ENV04-C
7.10.3Mechanismoffailure
Themechanismoffailurestemsfrommissingquotingofstringsinjectedintoasoftwaresystem.Byallowingwhite-spacesinidentifiers,anattackercouldpotentiallyexecutearbitrarycommands.Thisvulnerabilitycovers"C:\Program Files"andspace-in-search-pathissues.TheoreticallythiscouldapplytootheroperatingsystemsbesidesWindows,especiallythosethatmakeiteasyforspacestobeinfilenamesorfoldersnames.
Deleted:
Deleted:
Deleted: eDeleted: .U
Deleted: .Ratherthanescapemeta-characters,itissafesttodisallowthementirelysincethelateruseofdatathathavebeenenteredinthedatabasemayneglecttoescapemeta-charactersbeforeuse.
Deleted: .Usersshouldonlyhavetheminimumprivilegesnecessarytousetheiraccount
Deleted: aDeleted: canDeleted:
Deleted:
Deleted:
Deleted:
WG23/N0720
138 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
7.10.4Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Examinestringsthataretobeinterpretedtoensurethattheydonotcontainconstructsdesignedtoexploitthesystem,suchasseparators.
7.11Pathtraversal[EWR]
7.11.1Descriptionofapplicationvulnerability
Thesoftwareconstructsapaththatcontainsrelativetraversalsequencesuchas".."oranabsolutepathsequencesuchas"/path/here."Attackersrunthesoftwareinaparticulardirectorysothatthehardlinkorsymboliclinkusedbythesoftwareaccessesafilethattheattackerhasundertheircontrol.Indoingthis,theattackermaybeabletoescalatetheirprivilegeleveltothatoftherunningprocess.
7.11.2Crossreference
CWE:22.PathTraversal24.PathTraversal:-'../filedir'25.PathTraversal:'/../filedir'26.PathTraversal:'/dir/../filename’27.PathTraversal:'dir/../../filename'28.PathTraversal:'..\filename'29.PathTraversal:'\..\filename'30.PathTraversal:'\dir\..\filename'31.PathTraversal:'dir\..\filename'32.PathTraversal:'...'(TripleDot)33.PathTraversal:'....'(MultipleDot)34.PathTraversal:'....//'35.PathTraversal:'.../...//'37.PathTraversal:‘/absolute/pathname/here’38.PathTraversal:‘\absolute\pathname\here’39.PathTraversal:'C:dirname'40.PathTraversal:'\\UNC\share\name\'(WindowsUNCShare)61.UNIXSymbolicLink(Symlink)Following62.UNIXHardLink64.WindowsShortcutFollowing(.LNK)65.WindowsHardLink
CERTCguidelines:FIO02-C
7.11.3Mechanismoffailure
Therearetwoprimarywaysthatanattackercanorchestrateanattackusingpathtraversal.Inthefirst,theattackeraltersthepathbeingusedbythesoftwaretopointtoalocationthattheattackerhascontrolover.
Formatted: Normal, Indent: Left: 0.63 cm, Outlinenumbered + Level: 1 + Numbering Style: Bullet + Aligned at: 1.27 cm + Tab after: 1.9 cm + Indent at: 1.9 cm, Tabs: 1.27cm, List tab + Not at 1.9 cm
Deleted: Deleted: T
Deleted:
Deleted:
Deleted:
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 139
Alternatively,theattackerhasnocontroloverthepath,butcanalterthedirectorystructuresothatthepathpointstoalocationthattheattackerdoeshavecontrolover.
Forinstance,asoftwaresystemthatacceptsinputintheformof:'..\filename','\..\filename','/directory/../filename','directory/../../filename','..\filename','\..\filename','\directory\..\filename','directory\..\..\filename','...','....'(multipledots),'....//',or'.../...//'withoutappropriatevalidationcanallowanattackertotraversethefilesystemtoaccessanarbitraryfile.Notethat'..'isignoredifthecurrentworkingdirectoryistherootdirectory.Someoftheseinputformscanbeusedtocauseproblemsforsystemsthatstripout'..'frominputinanattempttoremoverelativepathtraversal.
Thereareseveralcommonwaysthatanattackercanpointafileaccesstoafiletheattackerhasundertheircontrol.Asoftwaresystemthatacceptsinputintheformof'/absolute/pathname/here'or'\absolute\pathname\here'withoutappropriatevalidationcanalsoallowanattackertotraversethefilesystemtounintendedlocationsoraccessarbitraryfiles.AnattackercaninjectadriveletterorWindowsvolumeletter('C:dirname')intoasoftwaresystemtopotentiallyredirectaccesstoanunintendedlocationorarbitraryfile.Asoftwaresystemthatacceptsinputintheformofabackslashabsolutepathwithoutappropriatevalidationcanallowanattackertotraversethefilesystemtounintendedlocationsoraccessarbitraryfiles.AnattackercaninjectaWindowsUNC(UniversalNamingConventionorUniformNamingConvention)share('\\UNC\share\name')intoasoftwaresystemtopotentiallyredirectaccesstoanunintendedlocationorarbitraryfile.AsoftwaresystemthatallowsUNIXsymboliclinks(symlink)aspartofpathswhetherininternalcodeorthroughuserinputcanallowanattackertospoofthesymboliclinkandtraversethefilesystemtounintendedlocationsoraccessarbitraryfiles.Thesymboliclinkcanpermitanattackertoread/write/corruptafilethattheyoriginallydidnothavepermissionstoaccess.Failureforasystemtocheckforhardlinkscanresultinvulnerabilitytodifferenttypesofattacks.Forexample,anattackercanescalatetheirprivilegesifhe/shecanreplaceafileusedbyaprivilegedprogramwithahardlinktoasensitivefile,forexample,etc/passwd.Whentheprocessopensthefile,theattackercanassumetheprivilegesofthatprocess.
AsoftwaresystemthatallowsWindowsshortcuts(.LNK)aspartofpathswhetherininternalcodeorthroughuserinputcanallowanattackertospoofthesymboliclinkandtraversethefilesystemtounintendedlocationsoraccessarbitraryfiles.Theshortcut(filewiththe.lnkextension)canpermitanattackertoread/writeafilethattheyoriginallydidnothavepermissionstoaccess.
Failureforasystemtocheckforhardlinkscanresultinvulnerabilitytodifferenttypesofattacks.Forexample,anattackercanescalatetheirprivilegesifhe/shecanreplaceafileusedbyaprivilegedprogramwithahardlinktoasensitivefile(suchasetc/passwd).Whentheprocessopensthefile,theattackercanassumetheprivilegesofthatprocessorpossiblypreventaprogramfromaccuratelyprocessingdatainasoftwaresystem.
Asanitizingmechanismcanremovecharacterssuchas‘.'and‘;'whichmayberequiredforsomeexploits.Anattackercantrytofoolthesanitizingmechanisminto"cleaning"dataintoadangerousform.Supposetheattackerinjectsa‘.'insideafilename(say,"sensi.tiveFile")andthesanitizingmechanismremovesthecharacterresultinginthevalidfilename,"sensitiveFile".Iftheinputdataarenowassumedtobesafe,thenthefilemaybecompromised.
Whentwoormoreusers,oragroupofusers,havewritepermissiontoadirectory,thepotentialforsharinganddeceptionisfargreaterthanitisforsharedaccesstoafewfiles.Thevulnerabilitiesthatresultfrommaliciousrestructuringviahardandsymboliclinkssuggestthatitisbesttoavoidshareddirectories.
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
WG23/N0720
140 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
Securelycreatingtemporaryfilesinashareddirectoryiserror-proneanddependentontheversionoftheruntimelibraryused,theoperatingsystem,andthefilesystem.Codethatworksforalocallymountedfilesystem,forexample,maybevulnerablewhenusedwitharemotelymountedfilesystem.
Themitigationshouldbecenteredonconvertingrelativepathsintoabsolutepathsandthenverifyingthattheresultingabsolutepathmakessensewithrespecttotheconfigurationandrightsorpermissions.Thismayincludecheckingwhite-listsandblack-lists,authorizedsuperuserstatus,accesscontrollists,orotherfullytrustedstatus.
7.11.4Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Assumeallinputismalicious.Attackerscaninsertpathsintoinputvectorsandtraversethefilesystem.• Useanappropriatecombinationofblack-listsandwhite-liststoensureonlyvalidandexpectedinputis
processedbythesystem.• Usesanitizerstoscrubinputforsensitiveprograms.Ensurethatsanitizersworkproperly17.• Comparemultipleattributesofthefiletoimprovethelikelihoodthatthefileistheexpectedone18.• Followtheprincipleofleastprivilegewhenassigningaccessrightstofiles.• Denyaccesstoafilecanpreventanattackerfromreplacingthatfilewithalinktoasensitivefile.• Ensuregoodcompartmentalizationinthesystemtoprovideprotectedareasthatcanbetrusted.• Restricttheuseofshareddirectories;preferfilespulledfromconfigurationmanagementsystems.• Donotpermittemporaryfilestobecreatedinshareddirectories.
7.12Resourcenames[HTS]
7.12.1Descriptionofapplicationvulnerability
Interfacingwiththedirectorystructureorotherexternalidentifiersonasystemonwhichsoftwareexecutesisverycommon.Differencesintheconventionsusedbyoperatingsystemscanresultinsignificantchangesinbehaviourwhenthesameprogramisexecutedunderdifferentoperatingsystems.Forinstance,thedirectorystructure,permissiblecharacters,casesensitivity,andsoforthcanvaryamongoperatingsystemsandevenamongvariationsofthesameoperatingsystem.Forexample,Microsoftprohibits“/?:&\*”<>|#%”;butUNIX,Linux,andOSXoperatingsystemsallowanycharacterexceptforthereservedcharacter‘/’tobeusedinafilename.
Someoperatingsystemsarecasesensitivewhileothersarenot.Onnon-casesensitiveoperatingsystems,dependingonthesoftwarebeingused,thesamefilenamecouldbedisplayed,as“filename”,“Filename”or“FILENAME”andallwouldrefertothesamefile.
17e.g.asanitizershouldremove“.”or“..”atastringbeginning,butnotinthemiddleofavalidfilesystemaddress.
18Filescanoftenbeidentifiedbyotherattributesinadditiontothefilename,forexample,bycomparingfileownershiporcreationtime.Informationregardingafilethathasbeencreatedandclosedcanbestoredandthenusedlatertovalidatetheidentityofthefilewhenitisreopened.
Deleted:
Deleted:
Deleted:
Deleted: (
Moved [9]: e.g.asanitizershouldremove“.”or“..”atastringbeginning,butnotinthemiddleofavalidfilesystemaddress.
Deleted: )Moved [10]: Filescanoftenbeidentifiedbyotherattributesinadditiontothefilename,forexample,bycomparingfileownershiporcreationtime.Informationregardingafilethathasbeencreatedandclosedcanbestoredandthenusedlatertovalidatetheidentityofthefilewhenitisreopened.
Deleted: N
Deleted:
Deleted:
Deleted:
Deleted:
Moved (insertion) [9]
Moved (insertion) [10]Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 141
Someoperatingsystems,particularlyolderones,onlyrelyonthesignificanceofthefirstncharactersofthefilename.ncanbeunexpectedlysmall,suchasthefirst8charactersinthecaseofWin16architectureswhichwouldcause“filename1”,“filename2”and“filename3”toallmaptothesamefile.
Variationsinthefilename,namedresourceorexternalidentifierbeingreferencedcanbethebasisforvariouskindsofproblems.Suchmistakesorambiguitycanbeunintentional,orintentional,andineithercasetheycanbepotentiallyexploited,ifsurreptitiousbehaviourisagoal.
7.12.2Crossreference
JSFAVRules:46,51,53,54,55,and56MISRAC2012:1.1CERTCguidelines:MSC09-CandMSC10-C
7.12.3MechanismofFailure
Thewrongnamedresource,suchasafile,maybeusedwithinaprograminaformthatprovidesaccesstoaresourcethatwasnotintendedtobeaccessed.Attackerscouldexploitthissituationtointentionallymisdirectaccessofanamedresourcetoanothernamedresource.
7.12.4Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Wherepossible,useanAPIthatprovidesaknowncommonsetofconventionsfornamingandaccessingexternalresources,suchasPOSIX,ISO/IEC9945:2003(IEEEStd1003.1-2001).
• Analyzetherangeofintendedtargetsystems,developasuitableAPIfordealingwiththem,anddocumenttheanalysis.
• Ensurethatprogramsadapttheirbehaviourtotheplatformonwhichtheyareexecuting,sothatonlytheintendedresourcesareaccessed.Themeansthatinformationonsuchcharacteristicsasthedirectoryseparatorstringandmethodsofaccessingparentdirectoriesneedtobeparameterizedandnotexistasfixedstringswithinaprogram.
• Avoidcreatingresourcenamesthatarelongerthantheguaranteeduniquelengthofallpotentialtargetplatforms.
• Avoidcreatingresources,whicharedifferentiatedonlybythecaseintheirnames.• AvoidallUnicodecharactersandallcontrolcharacters5F
19infilenamesandtheextensions.
7.13Resourceexhaustion[XZP]
7.13.1Descriptionofapplicationvulnerability
Theapplicationissusceptibletogeneratingand/oracceptinganexcessivenumberofrequeststhatcouldpotentiallyexhaustlimitedresources,suchasmemory,filesystemstorage,databaseconnectionpoolentries,or
19Seehttp://www.ascii.cl/control-characters.htm
Deleted:
Deleted:
Deleted:
Deleted:
Deleted: E
WG23/N0720
142 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
CPU.Thiscouldultimatelyleadtoadenialofservicethatcouldpreventanyotherapplicationsfromaccessingtheseresources.
7.13.2Crossreference
CWE:400.ResourceExhaustion
7.13.3Mechanismoffailure
Therearetwoprimaryfailuresassociatedwithresourceexhaustion.Themostcommonresultofresourceexhaustionisdenialofservice.Insomecasesanattackeroradefectmaycauseasystemtofailinanunsafeorinsecurefashionbycausinganapplicationtoexhausttheavailableresources.
Resourceexhaustionissuesaregenerallyunderstoodbutarefarmoredifficulttoprevent.Takingadvantageofvariousentrypoints,anattackercouldcraftawidevarietyofrequeststhatwouldcausethesitetoconsumeresources.DatabasequeriesthattakealongtimetoprocessaregoodDoS(DenialofService)targets.AnattackerwouldonlyhavetowriteafewlinesofPerlcodetogenerateenoughtraffictoexceedthesite'sabilitytokeepup.Thiswouldeffectivelypreventauthorizedusersfromusingthesiteatall.
Resourcescanbeexhaustedsimplybyensuringthatthetargetmachinemustdomuchmoreworkandconsumemoreresourcestoservicearequestthantheattackermustdotoinitiatearequest.Preventionoftheseattacksrequiresthatthetargetsystemeitherrecognizestheattackanddeniesthatuserfurtheraccessforagivenamountoftimeoruniformlythrottlesallrequeststomakeitmoredifficulttoconsumeresourcesmorequicklythantheycanagainbefreed.Thefirstofthesesolutionsisanissueinitselfthough,sinceitmayallowattackerstopreventtheuseofthesystembyaparticularvaliduser.Iftheattackerimpersonatesthevaliduser,hemaybeabletopreventtheuserfromaccessingtheserverinquestion.Thesecondsolutionissimplydifficulttoeffectivelyinstituteandevenwhenproperlydone,itdoesnotprovideafullsolution.Itsimplymakestheattackrequiremoreresourcesonthepartoftheattacker.
Thefinalconcernthatmustbediscussedaboutissuesofresourceexhaustionisthatofsystemswhich"failopen."Thismeansthatintheeventofresourceconsumption,thesystemfailsinsuchawaythatthestateofthesystem—andpossiblythesecurityfunctionalityofthesystem—arecompromised.Aprimeexampleofthiscanbefoundinoldswitchesthatwerevulnerableto"macof"attacks(sonamedforatooldevelopedbyDugsong).TheseattacksfloodedaswitchwithrandomIP(InternetProtocol)andMAC(MediaAccessControl)addresscombinations,thereforeexhaustingtheswitch'scache,whichheldtheinformationofwhichportcorrespondedtowhichMACaddresses.Oncethiscachewasexhausted,theswitchwouldfailinaninsecurewayandwouldbegintoactsimplyasahub,broadcastingalltrafficonallportsandallowingforbasicsniffingattacks.
7.13.4Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Implementthrottlingmechanismsintothesystemarchitecture.1. Thebestprotectionistolimittheamountofresourcesthatanapplicationcancausetobe
expended.Astrongauthenticationandaccesscontrolmodelwillhelppreventsuchattacks
Deleted:
Deleted:
Deleted:
Deleted:
Deleted: Deleted: Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Formatted: Tabs:Not at 2.06 cm
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 143
fromoccurringinthefirstplace.Theauthenticationapplicationshouldbeprotectedagainstdenialofserviceattacksasmuchaspossible.
• Limitthecriticalresource(suchasdatabase)access,perhapsbycachingoften-usedresultsets,toreducetheresourcesexpended.
• Considertrackingtherateofrequestsreceivedfromusersandblockingrequeststhatexceedadefinedratethresholdtofurtherlimitthepotentialforadenialofserviceattack..
• Ensurethatapplicationshavespecificlimitsofscaleplacedonthem,andensurethatallfailuresinresourceallocationcausetheapplicationtofailsafely.
7.14Authenticationlogicerror[XZO]
7.14.1Descriptionofapplicationvulnerability
Thesoftwaredoesnotproperlyensurethattheuserhasproventheiridentity.
7.14.2Crossreference
CWE:287.ImproperAuthentication288.AuthenticationBypassbyAlternatePath/Channel289.AuthenticationBypassbyAlternateName290.AuthenticationBypassbySpoofing294.AuthenticationBypassbyCapture-replay301.ReflectionAttackinanAuthenticationProtocol302.AuthenticationBypassbyAssumed-ImmutableData303.ImproperImplementationofAuthenticationAlgorithm305.AuthenticationBypassbyPrimaryWeakness
7.14.3Mechanismoffailure
Therearemanywaysthatanattackercanpotentiallybypassthevalidationofauser.Someofthewaysaremeansofimpersonatingalegitimateuserwhileothersaremeansofbypassingtheauthenticationmechanismsthatareinplace.Ineithercase,auserwhoshouldnothaveaccesstothesoftwaresystemgainsaccess.
Authenticationbypassbyalternatepathorchanneloccurswhenaproductrequiresauthentication,buttheproducthasanalternatepathorchannelthatdoesnotrequireauthentication.NotethatthisisoftenseeninwebapplicationsthatassumethataccesstoaparticularCGI(CommonGatewayInterface)programcanonlybeobtainedthrougha"front"screen,butthisproblemisnotjustinwebapplications.Authenticationbypassbyalternatenameoccurswhenthesoftwareperformsauthenticationbasedonthenameoftheresourcebeingaccessed,buttherearemultiplenamesfortheresource,andnotallnamesarechecked.Authenticationbypassbycapture-replayoccurswhenitispossibleforamalicioususertosniffnetworktrafficandbypassauthenticationbyreplayingittotheserverinquestiontothesameeffectastheoriginalmessage(orwith
Deleted:
Deleted:
Formatted: Indent: Left: 1.43 cm, Tabs:Not at 1.27 cm
Deleted: ing
Deleted: canhelpminimize
Deleted:
Deleted: Tofurtherlimitthepotentialforadenialofserviceattack,c
Comment [SM10]: Thisismultiplerecommendations.Needsresectioning.AI-Larry
Deleted: LDeleted: E
Deleted:
Deleted:
Deleted:
WG23/N0720
144 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
minorchanges).Messagessentwithacapture-relayattackallowaccesstoresourcesthatarenototherwiseaccessiblewithoutproperauthentication.Capture-replayattacksarecommonandcanbedifficulttodefeatwithoutcryptography.Theyareasubsetofnetworkinjectionattacksthatrelyonlisteninginonpreviouslysentvalidcommands,thenchangingthemslightlyifnecessaryandresendingthesamecommandstotheserver.Sinceanyattackerwhocanlistentotrafficcanseesequencenumbers,itisnecessarytosignmessageswithsomekindofcryptographytoensurethatsequencenumbersarenotsimplydoctoredalongwithcontent.Reflectionattackscapitalizeonmutualauthenticationschemestotrickthetargetintorevealingthesecretsharedbetweenitandanothervaliduser.Inabasicmutual-authenticationscheme,asecretisknowntobothavaliduserandtheserver;thisallowsthemtoauthenticate.Inorderthattheymayverifythissharedsecretwithoutsendingitplainlyoverthewire,theyutilizeaDiffie-Hellman-styleschemeinwhichtheyeachpickavalue,thenrequestthehashofthatvalueaskeyedbythesharedsecret.Inareflectionattack,theattackerclaimstobeavaliduserandrequeststhehashofarandomvaluefromtheserver.Whentheserverreturnsthisvalueandrequestsitsownvaluetobehashed,theattackeropensanotherconnectiontotheserver.Thistime,thehashrequestedbytheattackeristhevaluethattheserverrequestedinthefirstconnection.Whentheserverreturnsthishashedvalue,itisusedinthefirstconnection,authenticatingtheattackersuccessfullyastheimpersonatedvaliduser.Authenticationbypassbyassumed-immutabledataoccurswhentheauthenticationschemeorimplementationuseskeydataelementsthatareassumedtobeimmutable,butcanbecontrolledormodifiedbytheattacker,forexample,ifawebapplicationreliesonacookie"Authenticated=1".Authenticationlogicerroroccurswhentheauthenticationtechniquesdonotfollowthealgorithmsthatdefinethemexactlyandsoauthenticationcanbejeopardized.Forinstance,amalformedorimproperimplementationofanalgorithmcanweakentheauthorizationtechnique.Anauthenticationbypassbyprimaryweaknessoccurswhentheauthenticationalgorithmissound,buttheimplementedmechanismcanbebypassedastheresultofaseparateweaknessthatisprimarytotheauthenticationerror.
7.14.4Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Funnelallaccessthroughasinglechokepointtosimplifyhowuserscanaccessaresource.• Foreveryaccess,performachecktodetermineiftheuserhaspermissionstoaccesstheresource.• Avoidmakingdecisionsbasedonnamesofresources(forexample,files)ifthoseresourcescanhave
alternatenames.• Canonicalizethenametomatchthatofthefilesystem'srepresentationofthename20.• Ensurethatmessagescanbeparsedonlyonce,e.g.,byincludingasequencenumberortimestampina
checksum.
20ThiscansometimesbeachievedwithanavailableAPI(forexample,inWin32theGetFullPathNamefunction).
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Moved [11]: ThiscansometimesbeachievedwithanavailableAPI(forexample,inWin32theGetFullPathNamefunction).
Deleted: UtilizeDeleted: some
Deleted: Deleted: ingDeleted: functionalityalongwithaDeleted: thattakesthisintoaccounttoensurethatmessagescanbeparsedonlyonce.
Moved (insertion) [11]
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 145
• Usedifferentkeysfortheinitiatorandresponderorofadifferenttypeofchallengefortheinitiatorandresponder.
7.15Improperrestrictionofexcessiveauthenticationattempts[WPL]
7.15.1Descriptionofapplicationvulnerability
Thesoftwaredoesnotimplementsufficientmeasurestopreventmultiplefailedauthenticationattemptswithininashorttimeframe,makingitmoresusceptibletobruteforceattacks.
7.15.2Crossreference
CWE:307.ImproperRestrictionofExcessiveAuthenticationAttempts
7.15.3Mechanismoffailure
Inarecentincidentanattackertargetedamemberofapopularsocialnetworkingsitessupportteamandwasabletosuccessfullyguessthemember'spasswordusingabruteforceattackbyguessingalargenumberofcommonwords.Oncetheattackergainedaccessasthememberofthesupportstaff,heusedtheadministratorpaneltogainaccesstoanumberofaccountsthatbelongedtocelebritiesandpoliticians.Ultimately,fakemessagesweresentthatappearedtocomefromthecompromisedaccounts.
7.15.4Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingway:
• Disconnecttheuserafterasmallnumberoffailedattempts• Implementatimeoutonauthentication• Lockoutatargetedaccount• Requireacomputationaltaskontheuser'spart.• Useavettedlibraryorframeworkthatdoesnotallowthisweaknesstooccurorprovidesconstructsthat
makethisweaknesseasiertoavoid.• ConsiderusinglibrarieswithauthenticationcapabilitiessuchasOpenSSLortheESAPIAuthenticator.
7.16Hard-codedpassword[XYP]
7.16.1Descriptionofapplicationvulnerability
Hardcodedpasswordswillcompromisesystemsecurityinawaythatcannotbeeasilyremedied.Itisneveragoodideatohardcodeapassword.Notonlydoeshardcodingapasswordallowalloftheproject'sdeveloperstoviewthepassword,italsomakesfixingtheproblemextremelydifficult.Oncethecodeisinproduction,thepasswordcannotbechangedwithoutpatchingthesoftware.Iftheaccountprotectedbythepasswordiscompromised,theownersofthesystemwillbeforcedtochoosebetweensecurityandavailability.
Deleted:
Deleted:
Deleted:
Deleted:
Formatted: Bulleted + Level: 1 + Aligned at: 0.63 cm +Indent at: 1.27 cm
Deleted: P
Deleted: may
Deleted: Deleted: Deleted: Deleted:
WG23/N0720
146 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
7.16.2Crossreference
CWE:259.Hard-CodedPassword798.UseofHard-codedCredentials
7.16.3Mechanismoffailure
Theuseofahard-codedpasswordhasmanynegativeimplications–themostsignificantofthesebeingafailureofauthenticationmeasuresundercertaincircumstances.Onmanysystems,adefaultadministrationaccountexistswhichissettoasimpledefaultpasswordthatishard-codedintotheprogramordevice.Thishard-codedpasswordisthesameforeachdeviceorsystemofthistypeandoftenisnotchangedordisabledbyendusers.Ifamalicioususercomesacrossadeviceofthiskind,itisasimplematteroflookingupthedefaultpassword(whichislikelyfreelyavailableandpublicontheInternetorthemalicioususercanviewfirmwareastexttofindtextstringsthatresemblepasswords)andlogginginwithcompleteaccess.Insystemsthatauthenticatewithaback-endservice,hard-codedpasswordswithinclosedsourceordrop-insolutionsystemsrequirethattheback-endserviceuseapasswordthatcanbeeasilydiscovered.Client-sidesystemswithhard-codedpasswordspresentevenmoreofathreat,sincetheextractionofapasswordfromabinaryisexceedinglysimple.Ifhard-codedpasswordsareused,itisalmostcertainthatunauthorizeduserswillgainaccessthroughtheaccountinquestion.
7.16.4Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Usea"firstlogin"modethatrequirestheusertoenterauniquestrongpasswordratherthanhardcodeadefaultusernameandpasswordforfirsttimelogins.
• Forfront-endtoback-endconnections,useoneormoreofthefollowingsolutions:1. Useofgeneratedpasswordsthatarechangedautomaticallyandmustbeenteredatgiventime
intervalsbyasystemadministrator.Thesepasswordswillbeheldinmemoryandonlybevalidforthetimeintervals.
2. Thepasswordsusedshouldbelimitedatthebackendtoonlyperformingactionsforthefrontend,asopposedtohavingfullaccess.
3. Themessagessentshouldbetaggedwithachecksumthatincludestimesensitivevaluessoastopreventreplaystyleattacks.
7.17Insufficientlyprotectedcredentials[XYM]
7.17.1Descriptionofapplicationvulnerability
Thisweaknessoccurswhentheapplicationtransmitsorstoresauthenticationcredentialsandusesaninsecuremethodthatissusceptibletounauthorizedinterceptionand/orretrieval.
7.17.2Crossreference
CWE:256.PlaintextStorageofaPassword
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted: R
Deleted: ,utilizea"firstlogin"modethatrequirestheusertoenterauniquestrongpassword.
Deleted: therearethreeDeleted: thatmaybeused.
Deleted:
Deleted: andDeleted: med
Deleted: withDeleted: PDeleted: C
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 147
257.StoringPasswordsinaRecoverableFormat
7.17.3Mechanismoffailure
Storingapasswordinplaintextmayresultinasystemcompromise.Passwordmanagementissuesoccurwhenapasswordisstoredinplaintextinanapplication'spropertiesorconfigurationfile.Aprogrammercanattempttoremedythepasswordmanagementproblembyobscuringthepasswordwithanencodingfunction,suchasBase64encoding,butthiseffortdoesnotadequatelyprotectthepassword.Storingaplaintextpasswordinaconfigurationfileallowsanyonewhocanreadthefileaccesstothepassword-protectedresource.Developerssometimesbelievethattheycannotdefendtheapplicationfromsomeonewhohasaccesstotheconfiguration,butthisattitudemakesanattacker'sjobeasier.Goodpasswordmanagementguidelinesrequirethatapasswordneverbestoredinplaintext.
Thestorageofpasswordsinarecoverableformatmakesthemsubjecttopasswordreuseattacksbymalicioususers.Ifasystemadministratorcanrecoverthepassworddirectlyoruseabruteforcesearchontheinformationavailabletohim,hecanusethepasswordonotheraccounts.
Theuseofrecoverablepasswordssignificantlyincreasesthechancethatpasswordswillbeusedmaliciously.Infact,itshouldbenotedthatrecoverableencryptedpasswordsprovidenosignificantbenefitoverplain-textpasswordssincetheyaresubjectnotonlytoreusebymaliciousattackersbutalsobymaliciousinsiders.
7.17.4Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Avoidstoringpasswordsineasilyaccessiblelocations.• Neverstoreapasswordinplaintext.• Ensurethatstrong,non-reversibleencryptionisusedtoprotectstoredpasswords.• Storecryptographichashesofpasswordsasanalternativetostoringinplaintext.
7.18Missingorinconsistentaccesscontrol[XZN]
7.18.1Descriptionofapplicationvulnerability
Thesoftwaredoesnotperformaccesscontrolchecksinaconsistentmanneracrossallpotentialexecutionpaths.
7.18.2Crossreference
CWE:285.MissingorInconsistentAccessControl352.Cross-SiteRequestForgery(CSRF)807.RelianceonUntrustedInputsinaSecurityDecision862.MissingAuthorization
CERTCguidelines:FIO06-C
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted: ConsidersFormatted: Normal, Bulleted + Level: 1 + Aligned at: 0.63cm + Indent at: 1.27 cm
Deleted: ing
Deleted: IDeleted: AccessDeleted: C
WG23/N0720
148 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
7.18.3Mechanismoffailure
Forwebapplications,attackerscanissuearequestdirectlytoapage(URL)thattheymaynotbeauthorizedtoaccess.Iftheaccesscontrolpolicyisnotconsistentlyenforcedoneverypagerestrictedtoauthorizedusers,thenanattackercouldgainaccesstoandpossiblycorrupttheseresources.
7.18.4Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Forwebapplications,makesurethattheaccesscontrolmechanismisenforcedcorrectlyattheserversideoneverypage.Usersshouldnotbeabletoaccessanyinformationsimplybyrequestingdirectaccesstothatpage,iftheydonothaveauthorization.
• Ensurethatallpagescontainingsensitiveinformationarenotcached,andthatallsuchpagesrestrictaccesstorequeststhatareaccompaniedbyanactiveandauthenticatedsessiontokenassociatedwithauserwhohastherequiredpermissionstoaccessthatpage.
7.19Incorrectauthorization[BJE]
7.19.1Descriptionofapplicationvulnerability
Thesoftwareperformsaflawedauthorizationcheckwhenanactorattemptstoaccessaresourceorperformanaction.Thisallowsattackerstobypassintendedaccessrestrictions.
7.19.2Crossreference
CWE:863.IncorrectAuthorization
7.19.3Mechanismoffailure
Authorizationistheprocessofdeterminingwhetherthatusercanaccessagivenresource,basedontheuser'sprivilegesandanypermissionsorotheraccess-controlspecificationsthatapplytotheresource.
Whenaccesscontrolchecksareincorrectlyapplied,usersareabletoaccessdataorperformactionsthattheyshouldnotbeallowedtoperform.Thiscanleadtoawiderangeofproblems,includinginformationexposures,denialofservice,andarbitrarycodeexecution.
7.19.4Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Ensurethatyouperformaccesscontrolchecksrelatedtoyourbusinessneeds21.
21Thesechecksmaybedifferentandmoredetailedthanthoseappliedtomoregenericresourcessuchasfiles,connections,processes,memory,anddatabaserecords.Forexample,adatabasemayrestrictaccessformedicalrecordstoaspecificdatabaseuser,buteachrecordmightonlybeintendedtobeaccessibletothepatientandthepatient'sdoctor.
Deleted:
Formatted: List Paragraph, Bulleted + Level: 1 + Aligned at: 1.35 cm + Indent at: 1.98 cm
Deleted: Deleted:
Moved [12]: Thesechecksmaybedifferentandmoredetailedthanthoseappliedtomoregenericresourcessuchasfiles,connections,processes,memory,anddatabaserecords.Forexample,adatabasemayrestrictaccessformedicalrecordstoaspecificdatabaseuser,buteachrecordmightonlybeintendedtobeaccessibletothepatientandthepatient'sdoctor.
Moved (insertion) [12]
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 149
7.20Adherencetoleastprivilege[XYN]
7.20.1Descriptionofapplicationvulnerability
Failuretoadheretotheprincipleofleastprivilegeamplifiestheriskposedbyothervulnerabilities.
7.20.2Crossreference
CWE:250.DesignPrincipleViolation:FailuretoUseLeastPrivilege
CERTCguidelines:POS02-C
7.20.3Mechanismoffailure
Thisvulnerabilitytypereferstocasesinwhichanapplicationgrantsgreateraccessrightsthannecessary.Dependingonthelevelofaccessgranted,thismayallowausertoaccessconfidentialinformation.Forexample,programsthatrunwithrootprivilegeshavecausedinnumerableUNIXsecuritydisasters.Itisimperativethatyoucarefullyreviewprivilegedprogramsforallkindsofsecurityproblems,butitisequallyimportantthatprivilegedprogramsdropbacktoanunprivilegedstateasquicklyaspossibletolimittheamountofdamagethatanoverlookedvulnerabilitymightbeabletocause.Privilegemanagementfunctionscanbehaveinsomeless-than-obviousways,andtheyhavedifferentquirksondifferentplatforms.Theseinconsistenciesareparticularlypronouncedifyouaretransitioningfromonenon-rootusertoanother.Signalhandlersandspawnedprocessesrunattheprivilegeoftheowningprocess,soifaprocessisrunningasrootwhenasignalfiresorasub-processisexecuted,thesignalhandlerorsub-processwilloperatewithrootprivileges.Anattackermaybeabletoleveragetheseelevatedprivilegestodofurtherdamage.Togranttheminimumaccesslevelnecessary,firstidentifythedifferentpermissionsthatanapplicationoruserofthatapplicationwillneedtoperformtheiractions,suchasfilereadandwritepermissions,networksocketpermissions,andsoforth.Thenexplicitlyallowthoseactionswhiledenyingallelse.
7.20.4Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Carefullymanagethesetting,managementandhandlingofprivileges.• Explicitlymanagetrustzonesinthesoftware.• Followtheprincipleofleastprivilegewhenassigningaccessrightstoentitiesinasoftwaresystem.
7.21Privilegesandboxissues[XYO]
7.21.1Descriptionofapplicationvulnerability
Avarietyofvulnerabilitiesoccurwithimproperhandling,assignment,ormanagementofprivileges.Theseareespeciallypresentinsandboxenvironments,althoughitcouldbearguedthatanyprivilegeproblemoccurswithinthecontextofsomesortofsandbox.
Deleted: LeastDeleted: Privilege
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Formatted: Bulleted + Level: 1 + Aligned at: 0.71 cm +Indent at: 1.35 cm
Deleted:
Deleted: SDeleted: Issues
Deleted:
WG23/N0720
150 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
7.21.2Crossreference
CWE:266.IncorrectPrivilegeAssignment267.PrivilegeDefinedWithUnsafeActions268.PrivilegeChaining269.PrivilegeManagementError270.PrivilegeContextSwitchingError272.LeastPrivilegeViolation273.FailuretoCheckWhetherPrivilegeswereDroppedSuccessfully274.FailuretoHandleInsufficientPrivileges276.InsecureDefaultPermissions732.IncorrectPermissionAssignmentforCriticalResource
CERTCguidelines:POS36-C
7.21.3Mechanismoffailure
Thefailuretodropsystemprivilegeswhenitisreasonabletodosoisnotanapplicationvulnerabilitybyitself.Itdoes,however,servetosignificantlyincreasetheseverityofothervulnerabilities.Accordingtotheprincipleofleastprivilege,accessshouldbeallowedonlywhenitisabsolutelynecessarytothefunctionofagivensystem,andonlyfortheminimalnecessaryamountoftime.Anyfurtherallowanceofprivilegewidensthewindowoftimeduringwhichasuccessfulexploitationofthesystemwillprovideanattackerwiththatsameprivilege.
Manysituationscouldleadtoamechanismoffailure:
• Aproductcouldincorrectlyassignaprivilegetoaparticularentity.• Aparticularprivilege,role,capability,orrightcouldbeusedtoperformunsafeactionsthatwerenot
intended,evenwhenitisassignedtothecorrectentity.(Notethattherearetwoseparatesub-categorieshere:privilegeincorrectlyallowsentitiestoperformcertainactions;andtheobjectisincorrectlyaccessibletoentitieswithagivenprivilege.)
• Twodistinctprivileges,roles,capabilities,orrightscouldbecombinedinawaythatallowsanentitytoperformunsafeactionsthatwouldnotbeallowedwithoutthatcombination.
• Thesoftwaremaynotproperlymanageprivilegeswhileitisswitchingbetweendifferentcontextsthatcrossprivilegeboundaries.
• Aproductmaynotproperlytrack,modify,record,orresetprivileges.• Insomecontexts,asystemexecutingwithelevatedpermissionswillhandoffaprocess/fileorother
objecttoanotherprocess/user.Iftheprivilegesofanentityarenotreduced,thenelevatedprivilegesarespreadthroughoutasystemandpossiblytoanattacker.
• Thesoftwaremaynotproperlyhandlethesituationinwhichithasinsufficientprivilegestoperformanoperation.
• Aprogram,uponinstallation,maysetinsecurepermissionsforanobject.
7.21.4Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
Deleted:
Deleted:
Deleted:
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 151
• Followtheprincipleofleastprivilegewhenassigningaccessrightstoentitiesinasoftwaresystem.Thesetting,managementandhandlingofprivilegesshouldbemanagedverycarefully.
• Uponchangingsecurityprivileges,verifythatthechangewassuccessful.• Followtheprincipleofseparationofprivilege.Requiremultipleconditionstobemetbeforepermitting
accesstoasystemresource.• Explicitlymanagetrustzonesinthesoftware.Ifatallpossible,limittheallowanceofsystemprivilegeto
small,simplesectionsofcodethatmaybecalledatomically.• Ensurethattheoperatingsystemdropstheelevatedprivilegeandreturnstotheprivilegelevelofthe
invokinguserassoonaspossibleaftercallingaprivilegedfunctionsuchaschroot().
7.22Missingrequiredcryptographicstep[XZS]
7.22.1Descriptionofapplicationvulnerability
Cryptographicimplementationsshouldfollowthealgorithmsthatdefinethemexactly,otherwiseencryptioncanbefaulty.
7.22.2Crossreference
CWE:325.MissingRequiredCryptographicStep327.UseofaBrokenorRiskyCryptographicAlgorithm
7.22.3Mechanismoffailure
Notfollowingthealgorithmsthatdefinecryptographicimplementationsexactlycanleadtoweakencryption.Thiscouldbetheresultofmanyfactorssuchasaprogrammermissingarequiredcryptographicsteporusingweakrandomizationalgorithms.
7.22.4Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Implementcryptographicalgorithmsprecisely.• Usesystemfunctionsandlibrariesratherthanwritingthefunction.
7.23Improperlyverifiedsignature[XZR]
7.23.1Descriptionofapplicationvulnerability
Thesoftwaredoesnotverify,orimproperlyverifies,thecryptographicsignaturefordata.Bynotadequatelyperformingtheverificationstep,thedatabeingreceivedshouldnotbetrustedandmaybecorruptedormadeintentionallyincorrectbyanadversary.
Deleted:
Deleted:
Deleted: oneshouldDeleted: ensureDeleted: ConsiderfDeleted: ingDeleted:
Formatted: Indent: Left: 0.63 cm, Space After: 0 pt,Outline numbered + Level: 1 + Numbering Style: Bullet +Aligned at: 1.27 cm + Tab after: 1.9 cm + Indent at: 1.9cm, Tabs: 1.27 cm, List tab + Not at 1.9 cm
Deleted: ADeleted: acquiringelevatedprivilegetoDeleted: ),theprogramshoulddroprootprivilegeandreturntotheprivilegeleveloftheinvokinguser. ... [20]
Deleted: RDeleted: CDeleted: S
Deleted:
Deleted: IDeleted:
Formatted: Normal, Bulleted + Level: 1 + Aligned at: 0.63cm + Tab after: 1.27 cm + Indent at: 1.27 cm, Tabs: 1.27cm, LeftDeleted: VDeleted: S
Deleted:
WG23/N0720
152 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
7.23.2Crossreference
CWE:347.ImproperlyVerifiedSignature
7.23.3Mechanismoffailure
Dataissignedusingtechniquesthatassuretheintegrityofthedata.Therearetwowaysthattheintegritycanbeintentionallycompromised.Theexchangeofthecryptologickeysmayhavebeencompromisedsothatanattackercouldprovideencrypteddatathathasbeenaltered.Alternatively,thecryptologicverificationcouldbeflawedsothattheencryptionofthedataisflawedwhichagainallowsanattackertoalterthedata.
7.23.4Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Usedatasignaturestotheextentpossibletohelpensuretrustindata.• Usebuilt-inverificationsfordata
7.24Useofaone-wayhashwithoutasalt[MVX]
7.24.1Descriptionofapplicationvulnerability
Thesoftwareusesaone-waycryptographichashagainstaninputthatshouldnotbereversible,suchasapassword,butthesoftwaredoesnotalsouseasalt22aspartoftheinput.
7.24.2Crossreference
CWE:325.MissingRequiredCryptographicStep327.UseofaBrokenorRiskyCryptographicAlgorithm759.UseofaOne-WayHashwithoutaSalt
7.24.3Mechanismoffailure
Thismakesiteasierforattackerstopre-computethehashvalueusingdictionaryattacktechniquessuchasrainbowtables.
7.24.4Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Forasalto Generatearandomsalteachtimeanewpasswordisprocessed.o Addthesalttotheplaintextpasswordbeforehashingit.
22Incryptography,asaltconsistsofrandombits,earlysystemsuseda12-bitsalt,modernimplementationsuse48to128bits.
Deleted:
Deleted:
Deleted:
Deleted:
Formatted
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 153
o Whenthehashisstored,alsostorethesalt.o Donotusethesamesaltforeverypasswordthatyouprocess.
• Useone-wayhashingtechniquesthatallowtheconfigurationofalargenumberofrounds,suchasbcrypt23.
• Useindustry-approvedtechniquescorrectly.Neverskipresource-intensivesteps(seeCWE-325).Thesestepsareoftenessentialforpreventingcommonattacks.
7.25Inadequatelysecurecommunicationofsharedresources[CGY
7.25.1Descriptionofapplicationvulnerability
Aresourcethatisdirectlyvisiblefrommorethanoneprocess(atthesameapproximatetime)andisnotprotectedbyaccesslockscanbehijackedorusedtocorrupt,controlorchangethebehaviourofotherprocessesinthesystem.Manyvulnerabilitiesthatareassociatedwithconcurrentaccesstofiles,sharedmemoryorsharednetworkresourcesfallunderthisvulnerability,includingresourcesaccessedviastatelessprotocolssuchasHTTPandremotefileprotocols.
7.25.2Crossreferences
CWE:15.ExternalControlofSystemorConfigurationSetting311.MissingEncryptionofSensitiveData642.ExternalControlofCriticalStateData367:Timeofcheck,timeofuse
BurnsA.andWellingsA.,LanguageVulnerabilities-Let’snotforgetConcurrency,IRTAW14,2009.
7.25.3Mechanismoffailure
Anytimethatasharedresourceisopentogeneralinspection,theresourcecanbemonitoredbyaforeignprocesstodetermineusagepatterns,timingpatterns,andaccesspatternstodeterminewaysthataplannedattackcansucceed7F
24.Suchmonitoringcouldbe,butisnotlimitedto:
• Readingresourcevaluestoobtaininformationofvaluetotheapplications.• Monitoringaccesstimeandaccessthreadtodeterminewhenaresourcecanbeaccessedundetectedby
otherthreads(forexample,Time-of-Check-Time-Of-Useattacksrelyuponadeterminableamountoftimebetweenthecheckonaresourceandtheuseoftheresourcewhentheresourcecouldbemodifiedtobypassthecheck).
• Monitoringaresourceandmodificationpatternstohelpdeterminetheprotocolsinuse.
23Thismayincreasetheexpensewhenprocessingincomingauthenticationrequests,butifthehashedpasswordsareeverstolen,itsignificantlyincreasestheeffortforconductingabruteforceattack,includingrainbowtables.Withtheabilitytoconfigurethenumberofrounds,onecanincreasethenumberofroundswheneverCPUspeedsorattacktechniquesbecomemoreefficient.
24Suchmonitoringisalmostalwayspossiblebyaprocessexecutingwithsystemprivilege,butevensmallslipsinaccesscontrolsandpermissionsletsuchresourcesbeseenfromother(nonsystemlevel)processes.Eventheexistenceoftheresource,itssize,oritsaccessdates/timesandhistory(suchas“lastaccessedtime”)cangivevaluableinformationtoanobserver.
Moved [13]: Thismayincreasetheexpensewhenprocessingincomingauthenticationrequests,butifthehashedpasswordsareeverstolen,itsignificantlyincreasestheeffortforconductingabruteforceattack,includingrainbowtables.Withtheabilitytoconfigurethenumberofrounds,onecanincreasethenumberofroundswheneverCPUspeedsorattacktechniquesbecomemoreefficient.
Deleted: When
Deleted: areused,theymustbeused
Deleted:
Deleted:
Deleted:
Moved (insertion) [13]
WG23/N0720
154 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
• Monitoringaccesstimesandpatternstodeterminequiettimesintheaccesstoaresourcethatcouldbeusedtofindsuccessfulattackvectors.
Thismonitoringcanthenbeusedtoconstructasuccessfulattack,usuallyinalaterattack.
Anytimethataresourceisopentogeneralupdate,theattackercanplananattackbyperformingexperimentsto:
• Discoverhowchangesaffectpatternsofusage,timing,andaccess.• Discoverhowapplicationthreadsdetectandrespondtoforgedvalues.
Anytimethatasharedresourceisopentosharedupdatebyathread,theresourcecanbechangedinwaystofurtheranattackonceitisinitiated.Forexample,inawell-knownattack,aprocessmonitorsacertainchangetoaknownfileandthenimmediatelyreplacesavirusfreefilewithaninfectedfiletobypassviruscheckingsoftware.
Withcarefulplanning,similarscenarioscanresultintheforeignprocessdeterminingaweaknessoftheattackedprocessleadingtoanexploitconsistingofanythinguptoandincludingarbitrarycodeexecution.
7.25.4Avoidingthevulnerabilityormitigatingitseffect
Softwaredeveloperscanavoidthevulnerabilityormitigateitseffectsinthefollowingways.
• Placeallsharedresourcesinmemoryregionsaccessibletoonlyoneprocessatatime.• Protectresourcesthatmustbevisiblewithencryptionorwithchecksumstodetectunauthorized
modifications.• Obtainanunforgeableaccesspathsuchasthefilehandleobtainedonfirstaccess• Protectaccesstosharedresourcesusinganunforgeableaccesspath,permissions,accesscontrol,or
obfuscation.• Haveandenforceclearruleswithrespecttopermissionstochangesharedresources.• Detectattemptstoaltersharedresourcesandtakeimmediateaction.
7.26Memorylocking[XZX]
7.26.1Descriptionofapplicationvulnerability
Sensitivedatastoredinmemorythatwasnotlockedorthathasbeenimproperlylockedmaybewrittentoswapfilesondiskbythevirtualmemorymanager.
7.26.2Crossreference
CWE:591.SensitiveDataStorageinImproperlyLockedMemory
CERTCguidelines:MEM06-C
7.26.3Mechanismoffailure
Sensitivedatathatisnotkeptcryptographicallysecuremaybecomevisibletoanattackerbyanyofseveralmechanisms.Someoperatingsystemsmaywritememorytoswaporpagefilesthatmaybevisibletoanattacker.
Deleted:
Deleted:
Deleted: Locking
Formatted: No widow/orphan control, Don't adjust spacebetween Latin and Asian text, Don't adjust space betweenAsian text and numbersDeleted: Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 155
Someoperatingsystemsmayprovidemechanismstoexaminethephysicalmemoryofthesystemorthevirtualmemoryofanotherapplication.Applicationdebuggersmaybeabletostopthetargetapplicationandexamineoraltermemory.Systemsthatprovidea"hibernate"facility(suchaslaptops)willwriteallofphysicalmemorytoafilethatmaybevisibletoanattackeronresume.
7.26.4Avoidingthevulnerabilityormitigatingitseffects
Inalmostallcases,theseattacksrequireelevatedorappropriateprivilege.
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Removedebuggingtoolsfromproductionsystems.• Logandauditallprivilegedoperations.• Identifydatathatneedstobeprotectedanduseappropriatecryptographicandotherdataobfuscation
techniquestoavoidkeepingplaintextversionsofthisdatainmemoryorondisk.25• Iftheoperatingsystemallows,cleartheswapfileonshutdown.
7.27Sensitiveinformationunclearedbeforeuse[XZK]
7.27.1Descriptionofapplicationvulnerability
Thesoftwaredoesnotfullyclearpreviouslyusedinformationinadatastructure,file,orotherresource,beforemakingthatresourceavailabletoanotherpartythatdidnothaveaccesstotheoriginalinformation.
7.27.2Crossreference
CWE:226.SensitiveInformationUnclearedBeforeRelease
CERTCguidelines:MEM03-C
7.27.3Mechanismoffailure
Thistypicallyinvolvesmemoryinwhichthenewdataoccupieslessmemorythantheolddata,whichleavesportionsoftheolddatastillavailable("memorydisclosure").However,equivalenterrorscanoccurinothersituationswherethelengthofdataisvariablebuttheassociateddatastructureisnot.Thiscanoverlapwithcryptographicerrorsandcross-boundarycleansinginformationleaks.
25Note:SeveralimplementationsofthePOSIXmlock()andtheMicrosoftWindowsVirtualLock()functionswillpreventthenamedmemoryregionfrombeingwrittentoaswaporpagefile.However,suchusageisnotportable.
Deleted:
Moved (insertion) [14]
Moved [15]: Note:SeveralimplementationsofthePOSIXmlock()andtheMicrosoftWindowsVirtualLock()functionswillpreventthenamedmemoryregionfrombeingwrittentoaswaporpagefile.However,suchusageisnotportable.
Moved up [14]: Systemsthatprovidea"hibernate"facility(suchaslaptops)willwriteallofphysicalmemorytoafilethatmaybevisibletoanattackeronresume.
Deleted: IDeleted: UDeleted: BDeleted: UDeleted: [XZKDeleted: ]
Deleted:
Deleted:
Moved (insertion) [15]Deleted:
WG23/N0720
156 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
Dynamicmemorymanagersarenotrequiredtoclearfreedmemoryandgenerallydonotbecauseoftheadditionalruntimeoverhead.Furthermore,dynamicmemorymanagersarefreetoreallocatethissamememory.Asaresult,itispossibletoaccidentallyleaksensitiveinformationifitisnotclearedbeforecallingafunctionthatfreesdynamicmemory.Programmersshouldnotandcannotrelyonmemorybeingclearedduringallocation.
7.27.4Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Uselibraryfunctionsandorprogramminglanguagefeatures(suchasdestructorsorfinalizationprocedures)thatprovideautomaticclearingoffreedbuffersorthefunctionalitytoclearbuffers.
7.28Timeconsumptionmeasurement[CCM]
7.28.1Descriptionofapplicationvulnerability
Allapplicationsconsumeresourcesastheyexecute,inparticularTime.Eachthread,event,interruptandOSserviceconsumeCPUtimethatmaybeseparatelymeasurablebythesystem.
Acommonparadigminmanagingapplicationsistomonitorsuchresourceusagebythreadandtakeactiontoceasethecalculationforthatthread,suchasabort,raiseexception,lowerpriorityorsuspendingthethread.Ifthecalculationcannotbecompletedintimeorwithintheresourceconstraintsimposeduponit,thentheapplicationmayfail.
TheconsumptionofCPUresources(executiontime)canbeaffectedbychangesintheCPUitself:forexample,CPU’smayslowdowntomanageheat,resultinginmoreexecutiontimetoachievearesult.Similarly,cachemissesduetothewayaprogramisorganizedandexecuted,duetomultiprocessoreffects,canincreasetheexecutiontimeneededtocompleteacalculation.
Themeasurementofresourcetimingandconsumptioncanbeusedtobreaksensitivealgorithms.Forexample,somedevicesdrawpowerfromsystemsthattheypiggybackonto(suchaschipcardsandproximity-basedpassivesystems).
7.28.2Crossreferences
TBD
7.28.3Mechanismoffailure
Manyapplicationsmeasureresourceconsumptiontodetectfailuresofportionsofportionsofthealgorithmandtomakedecisionsaboutalternativeactions.Forexample,excessiveconsumptionofCPUmayindicatethatathreadisexecutingerroneously;orthatotherneededthreadsmaynotbeabletoexecuteduetoexcessiveresourceconsumption.
Otherfactors,suchaCPUspeedchangesandcachemissescancauseathreadtoconsumesignificantlymoreCPUresourcesthanexpectedtoperformthesamecalculations.
Deleted: Deleted:
Deleted:
Deleted: can’t
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 157
AthreadconsumingmoreCPUresourcesthanplannedcanresultinmisseddeadlinesforitself,orcantakeCPUresourcesneededbyotherthreads,causingincorrectprocessingormisseddeadlinesforotherthreads.Misseddeadlinesarecatastrophicforhardreal-timesystems,andcovertherangeofcausingwrongresultsthroughtocompletefailureoftheapplication.
Forsystemsthatliveinthelowpoweredconsumptiondomainbutrequiremodernencryption,thedeviceprovidingthepowercanuseknowledgeaboutpowerconsumedtonarrowthepossiblehashingalgorithmsorencryptionalgorithmsusedwhichmaylettheattackerdefeatencrypt-ionordigitalsigningsecuritysystems.
7.28.4Avoidingthevulnerabilityormitigatingitseffect
Software developers can avoid the vulnerability or mitigate its effects in the following ways: • THINKABOUTTHIS.Scenariosexistwheresuccessattheslowspeed/=>successatnormalspeed.• Wherecachemissesprovideasignificantpotentialhindrance,executetheapplicationwithcachedisabled• Forultra-lowpowereddevices(andforencryption-basedsystemsingeneral),basetheprotectionon
morethanencryption,suchasobfuscationandindirectioninsideoftheencryptionprotection.
7.29Discrepancyinformationleak[XZL]
7.29.1Descriptionofapplicationvulnerability
Adiscrepancyinformationleakisaninformationleakinwhichtheproductbehavesdifferently,orsendsdifferentresponses,inawaythatrevealssecurity-relevantinformationaboutthestateoftheproduct,suchaswhetheraparticularoperationwassuccessfulornot.
7.29.2Crossreference
CWE:203.DiscrepancyInformationLeaks204.ResponseDiscrepancyInformationLeak206.InternalBehaviouralInconsistencyInformationLeak207.ExternalBehavorialInconsistencyInformationLeak208.TimingDiscrepancyInformationLeak
7.29.3Mechanismoffailure
Aresponsediscrepancyinformationleakoccurswhentheproductsendsdifferentmessagesindirectresponsetoanattacker'srequest,inawaythatallowstheattackertolearnabouttheinnerstateoftheproduct.Theleakscanbeinadvertent(bug)orintentional(design).
Abehaviouraldiscrepancyinformationleakoccurswhentheproduct'sactionsindicateimportantdifferencesbasedon(1)theinternalstateoftheproductor(2)differencesfromotherproductsinthesameclass.AttackssuchasOSfingerprintingrelyheavilyonbothbehaviouralandresponsediscrepancies.Aninternalbehaviouralinconsistencyinformationleakisthesituationwheretwoseparateoperationsinaproductcausetheproducttobehavedifferentlyinawaythatisobservabletoanattackerandrevealssecurity-relevantinformationabouttheinternalstateoftheproduct,suchaswhetheraparticularoperationwassuccessfulornot.Anexternalbehaviouralinconsistencyinformationleakisthesituationwherethesoftwarebehavesdifferentlythanother
Deleted: 5
Formatted: Font color: RedComment [SM12]: AI–Steve–Thinkaboutthis.
Formatted: List Paragraph, Bulleted + Level: 1 + Aligned at: 0.63 cm + Indent at: 1.27 cm
Deleted: Deleted: IDeleted: L
Deleted:
Deleted:
Deleted:
Deleted:
WG23/N0720
158 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
productslikeit,inawaythatisobservabletoanattackerandrevealssecurity-relevantinformationaboutwhichproductisbeingused,oritsoperatingstate.
Atimingdiscrepancyinformationleakoccurswhentwoseparateoperationsinaproductrequiredifferentamountsoftimetocomplete,inawaythatisobservabletoanattackerandrevealssecurity-relevantinformationaboutthestateoftheproduct,suchaswhetheraparticularoperationwassuccessfulornot.
7.29.4Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Compartmentalizethesystemtohave"safe"areaswheretrustboundariescanbeunambiguouslydrawn. • Donotallowsensitivedatatogooutsideofthetrustboundaryandalwaysbecarefulwheninterfacing
withacompartmentoutsideofthesafearea.
7.30Unspecifiedfunctionality[BVQ]
7.30.1Descriptionofapplicationvulnerability
Unspecifiedfunctionalityiscodethatmaybeexecuted,butwhosebehaviourdoesnotcontributetotherequirementsoftheapplication.Whilethismaybenomorethananamusing‘EasterEgg’,liketheflightsimulatorinaspreadsheet,itdoesraisequestionsaboutthelevelofcontrolofthedevelopmentprocess.
Inasecurity-criticalenvironmentparticularly,thedeveloperofanapplicationcouldincludea‘trap-door’toallowillegitimateaccesstothesystemonwhichitiseventuallyexecuted,irrespectiveofwhethertheapplicationhasobvioussecurityrequirements.
7.30.2Crossreference
JSFAVRule:127MISRAC2012:1.2,2.1,3.1,and4.4XYQ:DeadandDeactivatedcode.
7.30.3Mechanismoffailure
Unspecifiedfunctionalityisnotasoftwarevulnerabilityperse,butmoreadevelopmentissue.Insomecases,unspecifiedfunctionalitymaybeaddedbyadeveloperwithouttheknowledgeofthedevelopmentorganization.Inothercases,typicallyEasterEggs,thefunctionalityisunspecifiedasfarastheuserisconcerned(nobodybuysaspreadsheetexpectingtofinditincludesaflightsimulator),butisspecifiedbythedevelopmentorganization.Ineffecttheyonlyrevealasubsetoftheprogram’sbehaviourtotheusers.
Inthefirstcase,onewouldexpectawell-manageddevelopmentenvironmenttodiscovertheadditionalfunctionalityduringvalidationandverification.Inthesecondcase,theuserisrelyingonthesuppliernottoreleaseharmfulcode.
Ineffect,aprogram’srequirementsare‘theprogramshouldbehaveinthefollowingmanneranddonothingelse’.The‘anddonothingelse’clauseisoftennotexplicitlystated,andcanbedifficulttodemonstrate.
Deleted: Formatted: Font:Times New RomanFormatted: Bulleted + Level: 1 + Aligned at: 0.63 cm + Tabafter: 1.27 cm + Indent at: 1.27 cm
Deleted: Functionality
Deleted:
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 159
7.30.4Avoidingthevulnerabilityormitigatingitseffects
Enduserscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Ensurethatprogramsanddevelopmenttoolsthataretobeusedincriticalapplicationscomefromadeveloperororganizationthatusesarecognizedandauditeddevelopmentprocessforthedevelopmentofthoseprogramsandtools.
• Ensurethatthedevelopmentprocessgeneratesdocumentationshowingtraceabilityfromsourcecodetorequirements,ineffectanswering‘whyisthisunitofcodeinthisprogram?’.Whereunspecifiedfunctionalityisthereforalegitimatereason(suchasdiagnosticsrequiredfordevelopermaintenanceorenhancement),thedocumentationshouldalsorecordthis.Itisnotunreasonableforcustomersofbespokecriticalcodetoasktoseesuchtraceabilityaspartoftheiracceptanceoftheapplication.
7.31Faulttoleranceandfailurestrategies[REU]
7.31.1Descriptionofapplicationvulnerability
Inspiteofthebestintentions,systemcomponentsmayfail,eitherfrominternallypoorlywrittensoftwareorexternalforcessuchaspoweroutages/variations,radiationorinadmissibleuserinput.Systemsareoftendesignedwithfaulttolerancetodetectanddealwithsuchfailures.Faulttoleranceisitselfapotentialsourceofvulnerabilities,particularlywheninappropriateorincompletestrategiesareimplemented.
Fault-handlingcodeisdifficulttodesignandprogram,sinceitneedstoexecuteinanalreadydamagedenvironment.Handlercodeisalsodifficulttotest,sinceitisexecutedonlywhenprimaryfailureshaveoccurred.Thesefailures,e.g.radiationdamage,maybeimpossibletorecreatewithsufficientcoverageinatestingenvironment.Moreover,itisnoteasytodeterminetherightkindoffaulttoleranceforagivenfault.Forsecurity,terminationofthemalfunctioningsystemmaybethebestaction;forsafety,terminationmaybemorecatastrophicthananyotherfaulttolerancemechanism.Recoveryinalocalcontextmaybeimpossible,e.g.,queryingafaultylocationsensor,whilea(transitively)callingroutinemayhavesufficientcontentforarecoveryaction,e.g.,obtaininglocationinformationfromanothersource.
Reasonsforfailuresareplentifulandvaried,stemmingfrombothhard-andsoftware.Hencethemechanismsofprimaryfailurecanbedescribedonlyinverygeneralterms:
• omissionfailures:aserviceisaskedforbutneverrendered.Theclientmightwaitforeverorbenotifiedaboutthefailure(termination)oftheservice.
• commissionfailures:aserviceinitiatesunexpectedactions,e.g.,communicationthatisunexpectedbythereceiver.Theservicemightwaitforever,causingomissionfailuresforsubsequentcallsbyclients.Thereceivermightbehinderedtodoitslegitimateactionsintime.Ataminimum,resourcesareconsumedthatarepossiblyneededbyothers.
• timingfailures:aserviceisnotrenderedbeforeanimposeddeadline.Systemresponseswillbe(too)late,causingcorrespondingdamagestotherealworldaffectedbythesystem.
• Valuefailures:aservicedeliversincorrectortaintedresults.Theclientcontinuescomputationswiththesecorruptedvalues,causingaspreadofconsequentialapplicationerrors.
Deleted:
Formatted: Space After: 0 pt, Bulleted + Level: 1 + Alignedat: 0.63 cm + Tab after: 1.27 cm + Indent at: 1.27 cm
Deleted:
Deleted:
Deleted: TDeleted: FDeleted: Strategies
Comment [SM13]: AI–Erhard–finishup.
Deleted:
WG23/N0720
160 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
Faultsarethepointsinexecutionwhereafailuremanifestsbyprocessinggoingwrong.Ifunnoticedorunhandled,theyturnintofailuresattheboundariesofenclosingcontrolunitsorcomponents.Failuresofservicesarefaultstotheirclientsand,ifnothandled,leadtoafailureoftheclientandconsequentlytofaultsandfailuresinitsclients,possiblyuntiltheentiresystemfails.
Detectionandhandlingoffaultsconstitutesthefaulttolerancecodeofthesystem.Themechanismsoffaulttolerancearemanifold,correspondingtothenatureofthefailureandtheneedsoftheapplication,andrangefromrecoverywithsubsequentnormalcontinuationofthesystem(“fullfaulttolerance”)orrestrictedcontinuation(“gracefuldegradation”,“failsoft”)toterminationofthesystem(“failstop”,“failsafe”,“fail-secure”),possiblycombinedwithasubsequentrestart.
Arisingvulnerabilitiesare,forexample:
• Thefaultisnotrecognizedandthesystemmalfunctionsorterminatesasaconsequence• Thefaultisrecognizedbutthedamagealreadydoneisincompletelyrepaired,withthesame
consequencesasinthefirstbullet• Avaluefaultisrecognizedtoolate,allowingtheincorrectvaluetobeusedinthecomputationsofother,
thuscorrupted,values(which,ifnotrepaired,cancausevulnerabilitiessuchasbufferoverflows)• Thefaulttoleranceprocessingtakestoolongtomeettimingdemands• Recoveryispreventedbythecauseofapermanentfault,e.g.,aprogrammingerror,leadingtoaninfinite
seriesofrecoveryattempts• Thefaulttolerancemechanismcausesitselfnewfaults
Forvulnerabilitiescausedbyterminationissuesassociatedwithmultiplethreads,multipleprocessorsorinterruptsalso6.60Concurrency–Directedtermination[CGT]and6.62Concurrency–Prematuretermination.Situationsthatcauseanapplicationtoterminateunexpectedlyorthatcauseanapplicationtonotterminatebecauseofothervulnerabilitiesarecoveredinthosevulnerabilities.Thevulnerabilityathanddiscussestheoverallfaulttreatmentstrategyapplicabletosingle-threadedormulti-threadedprograms.
TriggeringknownfaultdetectionmechanismscanbeusedtoinitiateoraggravateDenial-of-Serviceattacks.Knowledgeofalackoffaultdetection,particularlyofvaluefaults,canbeusedtoinitiatesystemintrusionsthroughmechanismsexplainedelsewhereinthisdocument.Whateverthefailureorterminationprocess,theterminationofanapplicationshouldnotresultindamagetosystemelementsthatrelyuponit.Thus,itshouldperform“lastwishes”tominimizetheeffectsofthefailureonenclosingcomponents(e.g.,releasesoftwarelocks)andtherealworld(e.g.closevalves).
7.31.2Crossreference
JSFAVRule:24MISRAC2012:4.1MISRAC++2008:0-3-2,15-5-2,15-5-3,and18-0-3CERTCguidelines:ERR04-C,ERR06-CandENV32-CAdaQualityandStyleGuide:5.8and7.5
Deleted:
Deleted: 6.60Concurrency–Directedtermination[CGT]6.60Concurrency–Directedtermination[CGT]
Deleted: 6.62Concurrency–Prematuretermination6.62Concurrency–PrematureTermination[CGS]
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 161
7.31.3Mechanismoffailure
Reasonsforfailuresareplentifulandvaried,stemmingfrombothhard-andsoftware.Hencethemechanismsoffailurefromfaulttoleranceorthelackthereofcanbedescribedonlyinverygeneralterms:
• Faulttolerancecode,inparticularfaultcheckingcode,mayinterferewiththetimelinessofthecomponentstomeettheirdeadlines
• Aninappropriatefaulttolerancemechanismorstrategymayleadtofailuresinfaultdetectionandothersecondaryfailures
• Considerablelatencyandprocessorusecanarisefromfinalizationandgarbagecollectioncausedbytheterminationofaservice.Thus,terminationmustbedesignedcarefullytoavoidcausingtimingfailuresofotherservices.Theterminationofservicescanbemaliciouslyusedtopreventon-timeperformanceofotheractiveservices.
• Inconsistentapproachestodetectingandhandlingafaultoralackofoveralldesignforthefaulttolerancecodecanpotentiallybeavulnerability,asfaultsmightescapethenecessaryattention.
7.31.4Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Decideonastrategyforfaulthandling.Consistencyinfaulthandlingshouldbethesamewithrespecttocriticallysimilarparts.
• Useamulti-tieredapproachoffaultprevention,faultdetectionandfaultreaction.• Unambiguouslydescribethefailuremodesofeachpossiblyfailingservice.• Checkearlyforanyfaults,particularlyvaluefaults.Numerouschecksonvaluescanandshouldbemade
(valuerange,plausibilitywithinhistory,reversalchecks,checksums,structuralchecks,etc.)toestablishthevalidityofcomputedresultsorinputreceived.
• Validateincomingdataandcomputedresultsatstrategicpointstodiscovervaluefailures.• Checkpre-andpostconditionsnotvalidatedotherwise.Seealsoclause6.43.• Detecttimingfailuresbywatch-dogtimersorsimilarmechanisms.• Useenvironment-orlanguage-providedmeanstostopservicesthatsubstantiallyexceeddeadlines.• Alwaysprepareforthepossibilitythataservicedoesnotreturnwitharequestedresultinduetime.• Keepfaulthandlingsimple.Ifindoubt,decideforalesserleveloffaulttolerance.• Inthecaseofcontinuedexecution,makesurethatanycorruptedvariablesoftheprogramstatehave
beencorrectedtoanactualandcorrectoratleastsafevalue.• Usesystem-definedcomponentsthatassistinuniformityoffaulthandlingwhenavailable.• Priortoanyabnormalterminationofacomponent,perform“lastwishes”tominimizetheeffectsofthe
failureonenclosingcomponents(e.g.,releasesoftwarelocksheldlocally)andtherealworld(e.g.closevalvesopenedbythecomponent).
• Specifyafault-handlingpolicywherebyaservice,intheabsenceoffullfaulttoleranceorgracefuldegradation,willhaltsafelyandsecurelyrespectively.
Deleted:
Deleted: <#>Iffaultsarenotdetectedintimeandrepaired
completely,thefollowingfailuresarise: ... [21]Deleted: 5
Deleted:
WG23/N0720
162 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
7.32Distinguishedvaluesindatatypes[KLK]
7.32.1Descriptionofapplicationvulnerability
Sometimes,inatyperepresentation,certainvaluesaredistinguishedasnotbeingmembersofthetype,butratherasprovidingauxiliaryinformation.Examplesincludespecialcharactersusedasstringterminators,distinguishedvaluesusedtoindicateoutoftypeentriesinSQL(Structuredquerylanguage)databasefields,andsentinelsusedtoindicatetheboundsofqueuesorotherdatastructures.Whentheusagepatternofcodecontainingdistinguishedvaluesischanged,itmayhappenthatthedistinguishedvaluehappenstocoincidewithalegitimatein-typevalue.Insuchacase,thevalueisnolongerdistinguishablefromanin-typevalueandthesoftwarewillnolongerproducetheintendedresults.
7.32.2Crossreference
CWE:20.Improperinputvalidation137.Representationerrors
JSFAVRule:151
7.32.3Mechanismoffailure
A“distinguishedvalue”ora"magicnumber"intherepresentationofadatatypemightbeusedtorepresentout-of-typeinformation.Someexamplesincludethefollowing:
• Theuseofaspecialcode,suchas“00”,toindicatetheterminationofacodedcharacterstring.• Theuseofaspecialvalue,suchas“999…9”,astheindicationthattheactualvalueiseithernotknownor
isinvalid.
Iftheuseofthesoftwareislatergeneralized,theonce-specialvaluecanbecomeindistinguishablefromvaliddata.Notethattheproblemmayoccursimplyifthepatternofusageofthesoftwareischangedfromthatanticipatedbythesoftware’sdesigners.Itmayalsooccurifthesoftwareisreusedinothercircumstances.
Anexampleofachangeinthepatternofusageisthis:Anorganizationlogsvisitorstoitsbuildingsbyrecordingtheirnamesandnationalidentitynumbersorsocialsecuritynumbersinadatabase.Ofcourse,somevisitorslegitimatelydonothaveordonotknowtheirsocialsecuritynumber,sothereceptionistsenternumbersto“makethecomputerhappy.”Receptionistsatonebuildinghaveadoptedtheconventionofusingthecode“555-55-5555”todesignatechildrenofemployees.Receptionistsatanotherbuildinghaveusedthesamecodetodesignateforeignnationals.Whenthedatabasesaremerged,thechildrenarereclassifiedasforeignnationalsorvice-versadependingonwhichsetofreceptionistsareusingthenewlymergeddatabase.
Anexampleofanunanticipatedchangeduetoreuseisthis:Supposeasoftwarecomponentanalyzesradardata,recordingdataeverydegreeofazimuthfrom0to359.Packetsofdataaresenttoothercomponentsforprocessing,updatingdisplays,recording,andsoon.Sincealldegreevaluesarenon-negative,adistinguishedvalueof-1isusedasasignaltostopprocessing,computesummarydata,closefiles,andsoon.Manyofthecomponentsaretobereusedinanewsystemwithanewradaranalysiscomponent.Howeverthenewcomponentrepresentsdirectionbynumbersintherange-180degreesto179degrees.Whenanazimuthvalueof
Deleted: VDeleted: DDeleted: T
Deleted:
Deleted: QDeleted: LDeleted:
Deleted:
Deleted: don’tDeleted: don’tDeleted: Deleted: Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 163
-1isprovided,thedownstreamcomponentswillinterpretthatastheindicationtostopprocessing.Ifthemagicvalueischangedto,say,-999,thesoftwareisstillatriskoffailingwhenfutureenhancements(say,countingaccumulateddegreesoncompleterevolutions)bring-999intotherangeofvaliddata.
Distinguishedvaluesshouldbeavoided.Instead,thesoftwareshouldbedesignedtousedistinctvariablestoencodethedesiredout-of-typeinformation.Forexample,thelengthofacharacterstringmightbeencodedinadopevectorandvalidityofdataentriesmightbeencodedindistinctBooleanvalues.
Thisvulnerabilityextendstonumbersplacedinthecode,suchas7,hexF00F.suchnumbersarealmostuniversallyusedinmultipleplaces.Thefirstissueisthatthereisrarelyafullexplanationgivenforthevalueinallplaceswhereitisdefined,andundermaintenancemaintainersareleftguessingatitsmeaning.Asecondissueisthat,undermaintenance(orbefore),thevaluechanges,butnotalloccurrencesgetupdated,causingerroneousalgorithms.Athirdissueisthatsuch“magicvalues”arealmostalwaysplacedinthedatasectionofthefilethatcontainstheexecutableprogram,andsimplesearcheswithdatadumpingtoolsrevealssuchvalues(sayforexampleapassword)toapossibleattackertouseinattemptingtobreaktheapplication
7.32.4Avoidingthevulnerabilityormitigatingitseffects
Enduserscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Useauxiliaryvariables(perhapsenclosedinvariantrecords)toencodeout-of-typeinformation.• Useenumerationtypestoconveycategoryinformation.Donotrelyuponlargerangesofintegers,with
distinguishedvalueshavingspecialmeanings.• Usenamedconstantstomakeiteasiertochangedistinguishedvalues.
7.33Clockissues[CCI]
7.33.1Descriptionofapplicationvulnerability
All processors and operating systems maintain multiple representations of time internal to the system. In a typical system there are the following notions of time, and potentially identifiable clocks:
• CPU time • Process/task/thread execution time • Calendar clock time, local and/or GMT • Elapsed time - i.e. time since system inception in seconds, or in fixed portions thereof • Network time
These times have different representations, different scaling, and different semantics. For example, a time-of-day clock must account for leap years, leap seconds and standard/daylight saving times but a CPU or processor clock is a monotonic clock that must maintain time used by a task, thread, or process in a granularity appropriate to CPU speed - possibly sub-nanosecond. A real time clock is a monotonic clock that manages and represents time to a granularity and representation needed to correctly manage the algorithms of the system. Both are usually associated with inputs from external devices or systems and outputs to initiate events in connected systems.
Some of these clocks are manifested in programming languages. For example, most languages have time of day clock lookup, while real time languages often include monotonic clocks for various purposes. Alternatively, some
Deleted:
Deleted:
Deleted:
Deleted: . A
WG23/N0720
164 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
languages provide library services to access and manipulate time bases, and to schedule activity based upon one of the time bases.
Time Conversion
When multiple time bases are supported, there are mechanisms to convert from one time format to another to support calculations done. Conversion errors, rounding errors or cumulative errors can develop
• if the conversion is not done from the most precise time formats to less precise time formats, • if conversions are done from one format to another and then back for comparison, or • if iterative calculations are done using less than the most precise time base possible.
This can lead to missed deadlines or wrong calculations that depended on accurate time representation and can result in catastrophic loss of the application or the parent system. A classic example of this is the common (wrong) paradigm to use the calendar clock to derive values to be programmed into the monotonic clock.
Clock Drift
When code is written for an application, the developer usually assumes that there is a common time base for all portions of the application that are in communication with each other. When the system is spread over multiple processors, the time base used by each processor will either drift from each other, or the time delay in communicating between these partitions will cause apparent drift.
Time Roll-over
Because each clock has a fixed internal representation of time which is updated periodically by some amount, eventually, if the system runs long enough, the time representation will overflow, resulting in a roll-over, returning it to zero or the initial time.This can also happen if the time base is external, such as the global positioning satellite time base. Code that relies upon the time-base constantly increasing will fail when a rollover occurs, leading to failure of the computational system and possible catastrophic loss of the parent system, unless the application is programmed to account for this rollover.
Most systems create a real-time time base such that the system will never roll over within the expected operational time of the system. Modifications to the system, however, such as speeding up the clock that feeds the time base or dramatically increasing the expected operational lifetime of the system can make such errors happen, with potential catastrophic loss of the system and any systems that depend upon it.
7.33.2CrossReferences
TBD
7.33.3Mechanismoffailure
Thetimeofdayclockisadjustedinternallytojumportobesetbackwardswhengoingtoorleavingsummertime,insertingleapseconds,switchingtimezonesorcorrectingtimetosynchronizetheclockwithatimebaseoranotherclock.Usingthewrongclock,especiallythetime-of-dayclock,toscheduleeventscanresultinjitterinthe
Deleted: :
Deleted: IDeleted: IDeleted: I
Formatted: Font:(Default) +Theme Body (Calibri)Formatted: Indent: Left: 1.37 cm, No bullets or numbering
Deleted: Synchroni
Deleted: city
Deleted: it
Deleted: is
Deleted: -enough lived
Deleted: completely
Deleted: fill the storage
Deleted: and will
Deleted: and
Deleted: ,Formatted: Font:(Default) Times New RomanDeleted: if/
Comment [SM15]: AI–Steve–getreferences
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 165
system,eventsbeingscheduledearly,ortheeventbeinglate.Themis-schedulingofeventscanhaverealworldapplicationsuptoandincludingcatastrophiclossoftheparentsystem.
Convertingfromonetime-basetoanothertime-basecanresultinlossofprecision,roundingerrors,andconversionerrorswhichcanleadtocompletejitterintheapplicationbehaviororcompletefailureoftheapplication
Roll-overofaclockcancausefailureofapplicationsthatareexpectinguniformlyincreasingtime,whichcanleadtotransientfailureoftheapplicationandpossiblytheparentsystem.
7.33.4Avoidingthevulnerabilityormitigatingitseffect
Software developers can avoid the vulnerability or mitigate its effects in the following ways:
• Always convert time from the most precise and stable time base to less precise time bases. • Avoid conversions from calendar clocks or network clocks to real time clocks.• Avoid using the time of day clock to schedule events, unless the event is demonstrably connected with real
world time of day, such as setting an alarm for 7 am. • Avoid resetting or reprogramming the real-time clock or execution timers, unless the complete application
is being reset. Allow some variability or errormargin in the reading of time and the scheduling of timebasedontheread.
• Useonlyclocksthathaveknownsynchronizationproperties. • Protect any code that uses real-time time bases with any potential of roll-over from going from a large
value to a zero or a negative value. This is done by assuming that a rollover can occur and if it is expected that always T1<T2, but is found that T1 is nearing Time_Base'Last, then T2<<T1 will be accepted.
7.34Timedriftandjitter[CDJ]
7.34.1Descriptionofapplicationvulnerability
Many real time systems are characterized by collections of jobs waiting for a start-time for a time-based iteration, or an event for sporadic activities. A common mistake in programming such systems is to base the start time of the next iteration upon either a non-monotonic or a non-real time clock, or to base it upon an offset from the start time or completion time of the last iteration. In the first case, conversion errors and possible drift of the real time clock can cause the next iteration to be wrongly programmed. In the second case, higher priority work may have delayed the actual start or completion of the task in an individual iteration, resulting again in time drift.
With enough drift, an iterative task will begin missing its deadlines, and will either produce the wrong results, or will fail completely, resulting in arbitrary failures up to catastrophic loss of the enclosing system.
Many systems have moved to a virtualization approach to fielding systems. Sometimes the virtual system is only an OS change, such as running Windows and Linux on the same hardware. Sometimes the virtual system is hardware and software. Sometimes hardware is dedicated, such as 2 cores from an 8 core system, while in others the virtual system under consideration only executes when needed. The discussion of virtualization includes the common notions, such as hypervisors, but also include systems as diverse as satisfying ARINC 653[ARINC 653], which uses a time-based partition approach to schedule mixed criticality systems on a single CPU.
Deleted: DDeleted: JitterDeleted: [CDJ]
WG23/N0720
166 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
In any case, when a system is virtual, its connection with the real world (i.e. hardware and virtualizer) clocks is indirect. Clocks for the virtualized system are updated when the virtualized system resumes, and time may “jump” or may advance much faster than normal until the clocks are synchronized with the real world. Similarly, time may run slowly or erratically in an executing virtualized system. These behaviours can result in processes being mis-synchronized or missing deadlines if time jumps or progresses too quickly for the task to get its work completed.
If an attacker is aware that an application is virtualized, or that it is depending upon a non-realtime clock, and can determine what other applications share the same resource, they may be able to generate load for the other virtualized applications so that the one in question can not retain enough resources to function correctly.
7.34.2Crossreferences
TBD
7.34.3Mechanismoffailure
Anychangeintheprogressionoftimecanresultinadisconnectbetweenthespacingofthedeliveryoftimeeventstotheapplication,andcanmakejobswithintheapplicationrunpasttheirdeadlines(asviewedbythetimingevents).
Deadlineoverrunisaseriousflawintheapplication,andusuallyresultsinfailureofportionsoftheapplicationuptocatastrophicfailureoftheapplication,andmayresultinlossoftheparentsystem.
Whenasystemisvirtualized,anattackercanuseinfluenceoverotherapplicationstoconsumeresourcesneededbythecriticalsystemthatcouldtriggersuchsystems.
Programmingmistakes,suchasfailuretousemonotonicclockstoscheduleiterations,orincorrectlyprogrammingthenextiterationcalculations(suchassettingthenextwaketimebasedonthethestartofthecurrentwaketimevsafixedoffsetfromthepreviousscheduledstarttime)resultindriftorjitterwhichmayresultinmissedrealworldinputsorlossofsynchronizationwithexternalsystems.
7.34.4Avoidingthevulnerabilityormitigatingitseffect
Software developers can avoid the vulnerability or mitigate its effects in the following ways:
• Always set the next (absolute) start time for the iteration from the start time of the previous programmed iteration.
• Only use the real-time clock in scheduling tasks or events. • Create management jobs that can monitor and detect application parts that exceed time bounds, such as
execution time or elapsed time. • Ensure that the behaviour of a virtualized application cannot be compromised by changes to the
environment of the virtualized system.
Comment [SM16]: AI–Steve-complete
Deleted: the
Formatted: List Paragraph, Justified, Outline numbered +Level: 1 + Numbering Style: Bullet + Aligned at: 0.63 cm +Indent at: 1.27 cm
Deleted: ... [22]
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 167
8NewVulnerabilities
8.1General
Thisclauseprovideslanguage-independentdescriptionsofvulnerabilitiesunderconsiderationforinclusioninthe
nexteditionofthisInternationalTechnicalReport.Itisintendedthatrevisionsofthesedescriptionswillbe
incorporatedintoClauses6and7ofthenexteditionandthattheywillbetreatedinthelanguage-specificPartsof
thatfollowthatedition.
Thefollowingdescriptionsarewritteninalanguage-independentmannerexceptwhenspecificlanguagesare
usedinexamples.
8.2ModifyingConstants[UJO]
8.2.1Descriptionofapplicationvulnerability
Manyprogramminglanguagesallowtheusertospecifysomedeclaredentitytobe“constant”.The“constant”qualificationassistsinstaticverificationandoptimizationofthecode,andhenceisveryuseful.
However,someoftheselanguagesallowalterationofthevalueofthisentityinsomecasesafterall.Thesemanticsthenrangefromlegitimateanddeterministicbehaviortoimplementation-definedorundefinedbehavior.Often,thealterationsareperformedbymeansofindirection.
8.2.2Crossreference
CWE:<<none?Ididnotfindany,butlotsof“makeconst”-advice>>CERTCguidelines:DCL52-CPP,EXP40-C,EXP55-CPP,EXP05-C
MISRAC:11.8
MISRAC++:5.2.5,7-1-1,9-3-3
CCG:ES.50
8.2.3Mechanismoffailure
Incodereviewsandmanualcodeinspections,userstendtorelyonthebeliefthatanentitydeclaredtobeconstantdoesnotchangeitsvalueduringtheexecutionoftheprogram(regardlessoftheexactsemanticsofthelanguage).Theinitializingvalueistakentobeitsvaluethroughouttheexecution.Forexample,theupperboundofaringbufferarraymightbedeclaredasaconstant.If,however,thevaluecanbechangedduringtheexecution,thebeliefinimmutabilitycanbefalsified.Intheexample,afterchangingtheupper-boundconstant,insufficientlylargebufferallocationsorout-of-boundsbufferaccesses,seeminglycheckedagainstthe“constant”upperbound,mayoccur.
Eventhewell-meantalterationofconstantsisveryriskyifthelanguagepermitsoptimizationsbasedontheknowninitialvalueoftheconstantentity.Theoptimization“constantpropagation”mayreplaceusesofthe
Formatted: English (CAN)Formatted: Heading 3
Formatted: Font:11 ptFormatted: No bullets or numbering, Tabs:Not at 0.39 cm+ 1.27 cm
Formatted: Space After: 12 pt, Line spacing: at least 18 pt,No widow/orphan control, Don't adjust space between Latinand Asian text, Don't adjust space between Asian text andnumbersDeleted: StealJB’swordsfromedition2.
Formatted: Font:(Default) Times, 12 pt
Deleted: of
WG23/N0720
168 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
constantbyitsinitializingvalue.Thealterationofthevalueatrun-timethenhasnoeffectonthisuseoftheconstant,whileitchangesotherusesoftheconstantwhereconstantpropagationdidnottakeplace.Moreover,differentcompilersoreventhesamecompilerunderdifferentswitchsettingcanoptimizedifferentusesoftheconstantdifferently,leadingtonon-deterministicexecutionsthatoftenresultindangerousmalfunctions.
Thevulnerabilitycanbeexploitedifthemodificationofconstantsisknowntotheattackerandthecodethatmodifiestheconstantcanbetriggeredbytheattacker.
Thevulnerabilitymaybedifficulttodetectiflevelsofindirectionareinvolvedinthemodificationoftheconstant.
8.2.4Applicablelanguagecharacteristics
Thisvulnerabilitydescriptionisintendedtobeapplicabletolanguageswiththefollowingcharacteristics:
• Languagesthatallowthespecificationofanentitytobe“constant”and,atthesametime,legitimizeortoleratechangesofitsvalue.
8.2.5Avoidingthevulnerabilityormitigatingitseffects
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
• Qualifyentitiesthatarenotchangedwithintheirscopeasconstants.• Donotchangethevalueofentitiesdeclaredtobeconstant.• Donotcreatereferencesorpointerstoentitiesdeclaredtobeconstant.Thisincludespassingconstants
asactualparametersbyreference,unlessimmutabilityoftheformalparameterisensured.• Usestaticanalysistoolsthatdetectthealterationofconstantentities.
8.2.6Implicationsforlanguagedesignandevolution
Infuturelanguagedesignandevolutionactivities,thefollowingitemsshouldbeconsidered:
• Avoidlanguageconstructsthatallowthemodificationofconstantentities.• Ensurethatthepropertytobeimmutablecannotbechangedbylanguageoperationssuchasassignment
orconversion.
Formatted: Indent: Left: 0.63 cm, Hanging: 0.63 cm,Bulleted + Level: 1 + Aligned at: 0.63 cm + Tab after: 1.27cm + Indent at: 1.27 cm
Deleted: Deleted: Thissectionisintentionallyblank.
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 169
AnnexA(informative)
VulnerabilityTaxonomyandList
A.1General
Thisdocumentisacatalogthatwillcontinuetoevolve.Forthatreason,aschemethatisdistinctfromsub-clausenumberinghasbeenadoptedtoidentifythevulnerabilitydescriptions.Eachdescriptionhasbeenassignedanarbitrarilygenerated,uniquethree-lettercode.Thesecodesshouldbeusedinpreferencetosub-clausenumberswhenreferencingdescriptionsbecausetheywillnotchangeasadditionaldescriptionsareaddedtofutureeditionsofthisdocument.However,itisrecognizedthatreadersmayneedassistanceinlocatingdescriptionsofinterest.
Thisannexprovidesataxonomicalhierarchyofvulnerabilities,whichusersmayfindtobehelpfulinlocatingdescriptionsofinterest.A.2isataxonomyoftheprogramminglanguagevulnerabilitiesdescribedinClause6andA.3isataxonomyoftheapplicationvulnerabilitiesdescribedinClause7.A.4liststhevulnerabilitiesinthealphabeticalorderoftheirthree-lettercodesandprovidesacross-referencetotherelevantsub-clause.
A.2OutlineofProgrammingLanguageVulnerabilities
A.2.1.TypesA.2.1.1.Representation
A.2.1.1.1.[IHN]TypeSystemA.2.1.1.2.[STR]BitRepresentations
A.2.1.2.Floating-pointA.2.1.2.1.[PLF]Floating-pointArithmetic
A.2.1.3.EnumeratedTypesA.2.1.3.1.[CCB]EnumeratorIssues
A.2.1.4.IntegersA.2.1.4.1.[FLC]NumericConversionErrors
A.2.1.5.CharactersandstringsA.2.1.5.1[CJM]StringTerminationA.2.1.5.2.[SHL]RelianceonExternalFormatString
A.2.1.6.ArraysA.2.1.6.1.[HCB]BufferBoundaryViolation(BufferOverflow)A.2.1.6.2.[XYZ]UncheckedArrayIndexingA.2.1.6.3.[XYW]UncheckedArrayCopying
A.2.1.7.PointersA.2.1.7.1.[HFC]PointerCastingandPointerTypeChangesA.2.1.7.2.[RVG]PointerArithmeticA.2.1.7.3.[XYH]NullPointerDereferenceA.2.1.7.4.[XYK]DanglingReferencetoHeap
A.2.2.Type-Conversions/LimitsA.2.2.1.[FIF]ArithmeticWrap-aroundErrorA.2.2.1[PIK]UsingShiftOperationsforMultiplicationandDivision
A.2.3.DeclarationsandDefinitionsA.2.3.1.[NAI]ChoiceofClearNamesA.2.3.2.[WXQ]Deadstore
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
WG23/N0720
170 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
A.2.3.3.[YZS]UnusedVariable A.2.3.4.[YOW]IdentifierNameReuseA.2.3.5.[BJL]NamespaceIssuesA.2.3.6.[LAV]InitializationofVariables
A.2.4.Operators/ExpressionsA.2.4.1.[JCW]OperatorPrecedence/OrderofEvaluationA.2.4.2.[SAM]Side-effectsandOrderofEvaluationA.2.4.3.[KOA]LikelyIncorrectExpressionA.2.4.4.[XYQ]DeadandDeactivatedCode
A.2.5.ControlFlowA.2.5.1.ConditionalStatements
A.2.5.1.1.[CLL]SwitchStatementsandStaticAnalysisA.2.5.1.2.[EOJ]DemarcationofControlFlow
A.2.5.2.LoopsA.2.5.2.1.[TEX]LoopControlVariablesA.2.5.2.2.[XZH]Off-by-oneError
A.2.5.3.Subroutines(Functions,Procedures,Subprograms)A.2.5.3.1.[EWD]StructuredProgrammingA.2.5.3.2.[CSJ]PassingParametersandReturnValuesA.2.5.3.3.[DCM]DanglingReferencestoStackFramesA.2.5.3.4.[OTR]SubprogramSignatureMismatchA.2.5.3.5.[GDL]RecursionA.2.5.3.6.[OYB]IgnoredErrorStatusandUnhandledExceptions
A.2.6.MemoryModelsA.2.6.1.[AMV]Type-breakingReinterpretationofDataA.2.6.2.{YAN]DeepvsShallowCopyingA.2.6.3.[XYL]MemoryLeaksandHeapFragmentation
A.2.7.ContractModelA.2.7.1.[SYM]TemplatesandGenericsA.2.7.2.[RIP]InheritanceA.2.7.3.[BLP]ViolationsoftheLiskovSubstitutionPrincipleortheContractModelA.2.7.4[PPH]RedispatchingA.2.7.5[BKK]PolymorphicVariables
A.2.8.LibrariesA.2.8.1[LRM]ExtraIntrinsicsA.2.8.2.[TRJ]ArgumentPassingtoLibraryFunctionsA.2.8.3.[DJS]Inter-languageCallingA.2.8.4.[NYY]Dynamically-linkedCodeandSelf-modifyingCodeA.2.8.5.[NSQ]LibrarySignatureA.2.8.6.[HJW]UnanticipatedExceptionsfromLibraryRoutines
A.2.9.MacrosA.2.9.1.[NMP]Pre-processorDirectives
A.2.10.Compile/RunTimeA.2.10.1[MXB]SuppressionofLanguage-DefinedRun-TimeCheckingA.2.10.2[SKL]ProvisionofInherentlyUnsafeOperations
A.2.11.LanguageSpecificationIssuesA.2.11.1.[BRS]ObscureLanguageFeaturesA.2.11.2.[BQF]UnspecifiedBehaviourA.2.11.3.[EWF]UndefinedBehaviourA.2.11.4.[FAB]Implementation-definedBehaviour
Deleted:
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 171
A.2.11.5.[MEM]DeprecatedLanguageFeaturesA.2.12.Concurrency
A.2.12.1[CGA]Concurrency–ActivationA.2.12.2[CGT]Concurrency–DirectedterminationA.2.12.3[CGS]Concurrency–PrematureTerminationA.2.12.4[CGX]ConcurrentDataAccessA.2.12.6[CGM]ProtocalLockErrors
A.3OutlineofApplicationVulnerabilities
A.3.1.DesignIssuesA.3.1.1.[BVQ]UnspecifiedFunctionalityA.3.1.2.[REU]FaultToleranceandFailureStrategiesA.3.1.3.[KLK]DistinguishedValuesinDataTypes
A.3.2.EnvironmentA.3.2.1.[XYN]AdherencetoLeastPrivilegeA.3.2.2.[XYO]PrivilegeSandboxIssuesA.3.2.3.[XYS]ExecutingorLoadingUntrustedCode
A.3.3.ResourceManagementA.3.3.1.MemoryManagement
A.3.3.1.1.[XZX]MemoryLockingA.3.3.1.2.[XZP]ResourceExhaustion
A.3.3.2.InputA.3.3.2.1.[CBF]UnrestrictedfileuploadA.3.3.2.2.[HTS]ResourcenamesA.3.3.2.3.[RST]InjectionA.3.3.2.4.[XYT]Cross-siteScriptingA.3.3.2.5.[XZQ]UnquotedSearchPathorElementA.3.3.2.7.[XZL]DiscrepancyInformationLeakA.3.3.2.8.[EFS]Useofuncheckeddatafromanuncontrolledortaintedsource
A.3.3.3.OutputA.3.3.3.1.[XZK]SensitiveInformationUnclearedBeforeUse
A.3.3.4.FilesA.3.3.4.1.[EWR]PathTraversal
A.3.4ConcurrencyandParallelismA.3.4.1[CGY]InadequatelySecureCommunicationofSharedResources
A.3.5.FlawsinSecurityFunctionsA.3.5.1.[XZS]MissingRequiredCryptographicStepA.3.5.2.[MVX]UseofaOne-WayHashwithoutaSaltA.3.5.2.Authentication
A.3.5.2.1.[XZR]ImproperlyVerifiedSignatureA.3.5.2.2.[XYM]InsufficientlyProtectedCredentialsA.3.5.2.3.[XZN]MissingorInconsistentAccessControlA.3.5.2.4.[XZO]AuthenticationLogicErrorA.3.5.2.5.[XYP]Hard-codedPasswordA.3.5.2.6.[DLB]DownloadofCodeWithoutIntegrityCheckA.3.5.2.7.[BJE]IncorrectAuthorizationA.3.5.2.8.[DHU]InclusionofFunctionalityfromUntrustedControlSphereA.3.5.2.9.[WPL]ImproperRestrictionofExcessiveAuthenticationAttempts
WG23/N0720
172 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
A.3.5.2.10.[PYQ]URLRedirectiontoUntrustedSite('OpenRedirect')
A.4VulnerabilityList
Code VulnerabilityName Sub-clause Page[AMV] Type-breaking Reinterpretation of Data 6.37 81 [BJL] Namespace Issues 6.21 53 [BJE] Incorrect Authorization 7.23 Error!
Bookmark not defined.
[BLP] Violations of the Liskov Substitution Principle 6.42 [BQF] Unspecified Behaviour 6.55 108 [BRS] Obscure Language Features 6.54 106 [BVQ] Unspecified Functionality 7.25 126 [CBF] Unrestricted File Upload 7.2 130 [CCB] Enumerator Issues 6.5 29 [CCI] Clock Issues 7.32 [CCM] Time Consumption Measurement 7.22 [CDJ] Clock Drift and Jitter 7.33 [CGA] Concurrency - Activation 6.59 [CGM] Protocol Lock Errors 6.63 [CGS] Concurrency - Premature Termination 6.62 [CGT] Concurrency - Directed termination 6.60 [CGX] Concurrent Data Access 6.61 [CGY] Inadequately Secure Communication of Shared
Resources 7.19
[CJM] String Termination 6.7 33 [CLL] Switch Statements and Static Analysis 6.27 64 [CSJ] Passing Parameters and Return Values 6.32 71 [DCM] Dangling References to Stack Frames 6.33 73 [DHU] Inclusion of Functionality from Untrusted Control
Sphere 7.4 154
[DJS] Inter-language Calling 6.47 97 [DLB] Download of Code Without Integrity Check 7.3 [EFS] Use of unchecked data from an uncontrolled or
tainted source 7.6
[EOJ] Demarcation of Control Flow 6.28 66 [EWD] Structured Programming 6.31 70 [EWF] Undefined Behaviour 6.56 109 [EWR] Path Traversal 7.30 [FAB] Implementation-defined Behaviour 6.57 111 [FIF] Arithmetic Wrap-around Error 6.15 44 [FLC] Numeric Conversion Errors 6.6 31 [GDL] Recursion 6.35 77 [HCB] Buffer Boundary Violation (Buffer Overflow) 6.8 34 [HFC] Pointer Casting and Pointer Type Changes 6.11 39
Formatted TableDeleted: 8175
Deleted: 5345
Deleted: Error! Bookmark not defined.142
Formatted: Font:(Default) Courier New
Deleted: 108103
Deleted: 107101
Deleted: 125120
Deleted: 129124
Deleted: 2921
Deleted: 3325
Deleted: 6456
Deleted: 7163
Deleted: 7365
Deleted: 153143
Deleted: 9792
Deleted: 6657
Deleted: 7061
Deleted: 110104
Deleted: 111106
Deleted: 4436
Deleted: 3123
Deleted: 7769
Deleted: 3426
Deleted: 3931
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 173
[HJW] Unanticipated Exceptions from Library Routines 6.50 101 [HTS] Resource Names 7.28 [IHN] Type System 6.2 22 [JCW] Operator Precedence/Order of Evaluation 6.23 57 [KLK] Distinguished Values in Data Types 7.27 [KOA] Likely Incorrect Expression 6.25 60 [LAV] Initialization of Variables 6.22 55 [LRM] Extra Intrinsics 6.45 90 [MEM] Deprecated Language Features 6.58 113 [MVX] Use of a One-Way Hash without a Salt 7.18 [MXB] Suppression of Language-defined Run-time Checking 6.52 104 [NAI] Choice of Clear Names 6.17 47 [NMP] Pre-processor Directives 6.51 103 [NSQ] Library Signature 6.49 100 [NYY] Dynamically-linked Code and Self-modifying Code 6.48 99 [OTR] Subprogram Signature Mismatch 6.34 75 [OYB] Ignored Error Status and Unhandled Exceptions 6.36 78 [PIK] Using Shift Operations for Multiplication and
Division 6.16 46
[PLF] Floating-point Arithmetic 6.4 26 [PPH] Redispatching 6.43 [PYQ] URL Redirection to Untrusted Site 7.5 ?? [REU] Fault Tolerance and Failure Strategies 7.26 ?? [RIP] Inheritance 6.41 88 [RST] Injection 7.27 141 [RVG] Pointer Arithmetic 6.12 40 [SAM] Side-effects and Order of Evaluation 6.24 58 [SHL] Reliance on External Format String 6.65 [SKL] Provision of Inherently Unsafe Operations 6.54 105 [STR] Bit Representations 6.3 24 [SYM] Templates and Generics 6.41 86 [TEX] Loop Control Variables 6.29 67 [TRJ] Argument Passing to Library Functions 6.47 96 [WPL] Improper Restriction of Excessive Authentication
Attempts 7.24
[WXQ] Dead Store 6.18 49 [XYH] Null Pointer Dereference 6.13 41 [XYK] Dangling Reference to Heap 6.14 42 [XYL] Memory Leak and Heap Fragmentation 6.40 83 [XYM] Insufficiently Protected Credentials 7.12 [XYN] Adherence to Least Privilege 7.8 [XYO] Privilege Sandbox Issues 7.9 [XYP] Hard-coded Password 7.15 [XYQ] Dead and Deactivated Code 6.26 62 [XYS] Executing or Loading Untrusted Code 7.7
Deleted: 10296
Deleted: 2214
Deleted: 5749
Deleted: 6052
Deleted: 5547
Deleted: 9084
Deleted: 113108
Deleted: 10599
Deleted: 4739
Deleted: 10397
Deleted: 10195
Deleted: 9994
Deleted: 7567
Deleted: 7870
Deleted: 4638
Deleted: 2618
Deleted: 8882
Deleted: 140130
Deleted: 4032
Deleted: 5850
Deleted: 106100
Deleted: 2416
Deleted: 8680
Deleted: 6759
Deleted: 9691
Deleted: 4941
Deleted: 4133
Deleted: 4234
Deleted: 8377
Deleted: 6254
WG23/N0720
174 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
[XYT] Cross-site Scripting 7.7 [XYW] Unchecked Array Copying 6.10 38 [XYZ] Unchecked Array Indexing 6.9 36 [XZH] Off-by-one Error 6.30 68 [XZK] Sensitive Information Uncleared Before Use 7.16 Error!
Bookmark not defined.
[XZL] Discrepancy Information Leak 7.31 [XZN] Missing or Inconsistent Access Control 7.13 151 [XZO] Authentication Logic Error 7.14 [XZP] Resource Exhaustion 7.21 [XZQ] Unquoted Search Path or Element 7.30 143 [XZR] Improperly Verified Signature 7.17 [XZS] Missing Required Cryptographic Step 7.11 [XZX] Memory Locking 7.20 [YAN] Deep vs Shallow Copying 6.38 [YOW] Identifier Name Reuse 6.20 51 [YZS] Unused Variable 6.19 50
Deleted: 3830
Deleted: 3628
Deleted: 6860
Deleted: Error! Bookmark not defined.135
Deleted: 150139
Deleted: 142132
Deleted: 5143
Deleted: 5042
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 175
AnnexB
SelectedGuidancetoLanguageDesigners
Thesearerecommendationsforthelanguagedevelopers’community,standardsthatifdevelopedcouldbeofusetoalllanguagessuchasthestandardsISO/IEC/IEC60559Floating-Pointarithmetic,ISO/IEC10967-1:2012,Part1:Integerandfloatingpointarithmetic,andISO/IEC10967-2:2001,Part2:Elementarynumericalfunctions:
1. Standardizedterminologyfortypesystemsa. Standardizeonacommon,uniformterminologytodescribetypesystemssothatprogrammers
experiencedinotherlanguagescanreliablylearnthetypesystemofalanguagethatisnewtothem.
b. Standardizeonacommon,uniformterminologytodescribegenerics/templatessothatprogrammersexperiencedinonelanguagecanreliablylearnandrefertothetypesystemofanotherlanguagethathasthesameconcept,butwithadifferentname.
2. Standardizedcallinga. Standardizeprovisionsforinter-languagecalling.b. Standardizeonwhereparameterchecksaredone;thatis,thereceivingprogramdoesthe
parameterchecks,notthecallingprogram.(thisisoneIadded)(ThisneedswordinginPart1tosubstantiate.)
(Dealwithcompilationandstaticanalysisthateliminatetheneedforruntimechecks)3. Standardizedfaulthandling
a. Standardizetheterminologyandmeanstoperformfaulthandling.b. Standardizeasetofmechanismsfordetectingandtreatingerrorconditionssothatalllanguages
totheextentpossiblecouldusethem.Thisdoesnotmeanthatalllanguagesshouldusethesamemechanismsasthereshouldbeavariety,buteachofthemechanismsshouldbestandardized.
c. (Faulttoleranceandfailurestrategieshasmovedfrom6.37to7.??).Inordertojustifysucha
treatment,itmayneedresurrectionasaveryvisibleclause7issue.)
Selectlistofwhatalanguageshouldhaveordo.Thesewereextractedfromguidancetolanguagedesignersfromclause6.X.6inTR24772-1.Wordinghasbeenadjustedtoprovideamoregeneralcontext,whereapplicable.
1. Floatingpointshouldadheretoarecognizedstandarddefinitiona. AlanguageshouldadheretoISO/IEC/IEC60559Floating-Pointarithmetic.b. AlanguageshouldadheretoISO/IEC10967-1:2012Part1:Integerandfloatingpointarithmetic,
andISO/IEC10967-2:2001,Part2:Elementarynumericalfunctions.2. Conversionsshouldbetype-safe
a. Alanguageshouldnotallowuncheckedcastsorshouldmakethemimmediatelyrecognizableasbeingunsafe.
b. Alanguageshouldprovidemechanismstopreventprogrammingerrorsduetoconversions.
Formatted: Heading 1, Centered, Space Before: 6 pt
Formatted: Centered
Formatted: Font:11 pt, Not BoldFormatted: Font:11 pt, Not Bold
Formatted: Font:11 pt, Not Bold
Formatted: Font:Not BoldFormatted: Font:11 pt, Not Bold
Formatted: Font:11 pt, Not Bold
WG23/N0720
176 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
3. Boundscheckingshouldbemandatory
a. Alanguageshouldperformautomaticboundscheckingonaccessestoarrayelements,unlessthecompilerorstaticanalysiscanstaticallydeterminethatthecheckisunnecessary.
4. Wholearrayoperationsshouldbeprovideda. Alanguageshouldprovidewholearrayoperations,suchasfullarrayassignmentandsafecopying
ofarraysthatmayobviatetheneedtoaccessindividualelements.5. Subprograms,andinparticularlibraries,shouldhavecontractsforcallers
a. Providelanguagemechanismstoformallyspecifypreconditionsandpostconditions.b. Language-definedlibrariesshouldprovidethepreconditionsandpostconditionsforeachcallso
thatfunctionargumentscanbevalidatedduringcompilation,executionorviaotherstaticanalysistools.(changeinTR24772-1clause6.46.5toreflectthismoregeneralstatement)
c. Alanguageshouldspecifymeanstodescribethesignaturesofsubprograms.6. Overflowerrorsshouldbedetectedandhandled
a. Languageshouldprovidefacilitiestospecifyeitheranerror,asaturatedvalue,oramoduloresultwhennumericoverflowoccurs.Ideally,theselectionamongthesealternativescouldbemadebytheprogrammer.
7. Undefined/unspecified/implementationdefinedbehaviourshouldbeminimized
a. Alanguageshouldprovidealistofundefined,unspecifiedandimplementation-definedbehaviours.
b. Alanguageshouldminimizetheamountofunspecifiedandundefinedbehaviours,andminimizethenumberofpossiblebehavioursforanyconstructwithunspecifiedbehaviour.
8. Useofdeprecatedfeaturesshouldbediagnosed
a. Alanguageshouldprovidelanguagemechanismsthatoptionallydisabledeprecatedlanguagefeatures,inparticularwheredeprecationforsecurityorsafetyreasons.(thisonecouldbedroppedinplaceofamoreworthy“top10”recommendation)
9. Synchronizationamongparallel/concurrentconstructsshouldbesupported
a. Alanguageshouldcreateprimitivesthatletapplicationsspecifyregionsofsequentialaccesstodatausingmechanismssuchasprotectedregions,Hoaremonitors,orsynchronousmessagepassingbetweenthreads.
10. Terminationofforloopsshouldbeeasiertoguarantee
a. Alanguageshouldaddanidentifiertypeforloopcontrolthatcannotbemodifiedbyanythingotherthantheloopcontrolconstruct.(Addthenotionof1-timeevaluationofthebounds)
(considerinmaindocumentalso)
Formatted: Font:(Default) +Theme Body (Calibri), 11 pt
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 177
AnnexC(informative)
LanguageSpecificVulnerabilityTemplate
Eachlanguage-specificannexshouldhavethefollowingheadinginformationandinitialsections:
ISOIECTR24772-X(Informative)
Vulnerabilitydescriptionsforlanguage[language]
Forward
[ISO(theInternationalOrganizationforStandardization)andIEC(theInternationalElectrotechnicalCommission)formthespecializedsystemforworldwidestandardization.NationalbodiesthataremembersofISOorIECparticipateinthedevelopmentofInternationalStandardsthroughtechnicalcommitteesestablishedbytherespectiveorganizationtodealwithparticularfieldsoftechnicalactivity.ISOandIECtechnicalcommitteescollaborateinfieldsofmutualinterest.Otherinternationalorganizations,governmentalandnon-governmental,inliaisonwithISOandIEC,alsotakepartinthework.Inthefieldofinformationtechnology,ISOandIEChaveestablishedajointtechnicalcommittee,ISO/IECJTC1.InternationalStandardsaredraftedinaccordancewiththerulesgivenintheISO/IECDirectives,Part2.ThemaintaskofthejointtechnicalcommitteeistoprepareInternationalStandards.DraftInternationalStandardsadoptedbythejointtechnicalcommitteearecirculatedtonationalbodiesforvoting.PublicationasanInternationalStandardrequiresapprovalbyatleast75%ofthenationalbodiescastingavote.Inexceptionalcircumstances,whenthejointtechnicalcommitteehascollecteddataofadifferentkindfromthatwhichisnormallypublishedasanInternationalStandard(“stateoftheart”,forexample),itmaydecidetopublishaTechnicalReport.ATechnicalReportisentirelyinformativeinnatureandshallbesubjecttorevieweveryfiveyearsinthesamemannerasanInternationalStandard.Attentionisdrawntothepossibilitythatsomeoftheelementsofthisdocumentmaybethesubjectofpatentrights.ISOandIECshallnotbeheldresponsibleforidentifyinganyorallsuchpatentrights.ISO/IECTR24772,waspreparedbyJointTechnicalCommitteeISO/IECJTC1,Informationtechnology,SubcommitteeSC22,Programminglanguages,theirenvironmentsandsystemsoftwareinterfaces.]
Introduction
ThisDocumentprovidesguidancefortheprogramminglanguage[language]sothatapplicationdevelopersconsidering[language]orusing[language]willbebetterabletoavoidtheprogrammingconstructsthatleadtovulnerabilitiesinsoftwarewritteninthe[language]languageandtheirattendantconsequences.Thisguidancecanalsobeusedbydeveloperstoselectsourcecodeevaluationtoolsthatcandiscoverandeliminatesomeconstructsthatcouldleadtovulnerabilitiesintheirsoftware.Thistechnicalcanalsobeusedincomparisonwithcompaniontechnicalreportsandwiththelanguage-independentreport,TR24772-1,toselectaprogramminglanguagethatprovidestheappropriatelevelofconfidencethatanticipatedproblemscanbeavoided.ThisdocumentpartisintendedtobeusedwithTR24772-1,whichdiscussesprogramminglanguagevulnerabilitiesinalanguageindependentfashion.ItshouldbenotedthatthisDocumentisinherentlyincomplete.Itisnotpossibletoprovideacompletelistofprogramminglanguagevulnerabilitiesbecausenewweaknessesarediscoveredcontinually.Anysuchreportcanonlydescribethosethathavebeenfound,characterized,anddeterminedtohavesufficientprobabilityand
Deleted: B
Deleted:
Deleted: Deleted:
Deleted: Deleted:
WG23/N0720
178 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
consequence.
1Scope
Thisdocumentspecifiessoftwareprogramminglanguagevulnerabilitiestobeavoidedinthedevelopmentofsystemswhereassuredbehaviourisrequiredforsecurity,safety,mission-criticalandbusiness-criticalsoftware.Ingeneral,thisguidanceisapplicabletothesoftwaredeveloped,reviewed,ormaintainedforanyapplication.Vulnerabilitiesdescribedinthisdocumentthewaythatthevulnerabilitydescribedinthelanguage-independentwriteup(inTR24772-1)aremanifestedin[language].
2NormativeReferences
Thefollowingreferenceddocumentsareindispensablefortheapplicationofthisdocument.Fordatedreferences,onlytheeditioncitedapplies.Forundatedreferences,thelatesteditionofthereferenceddocument(includinganyamendments)applies.[Thissub-clauseshouldlisttherelevantlanguagestandardsandotherdocumentsthatdescribethelanguagetreatedintheannex.Itneednotbesimplyalistofstandards.Itshoulddowhateverisrequiredtodescribethelanguagethatisthebaseline.]
3Termsanddefinitions,symbolsandconventions(Checktitle)Forthepurposesofthisdocument,thetermsanddefinitionsgiveninISO/IEC2382–1,inTR24772-1andthefollowingapply.Othertermsaredefinedwheretheyappearinitalictype.
4Concepts
[Thissub-clauseshouldprovideanoverviewofgeneralterminologyandconceptsthatareutilizedthroughouttheannex.]
EveryvulnerabilitydescriptionofClause6ofthemaindocumentshouldbeaddressedintheannexinthesameorderevenifthereissimplyanotationthatitisnotrelevanttothelanguageinquestion.Eachvulnerabilitydescriptionshouldhavethefollowingformat:
5GeneralGuidancefor[language]
[SeeTemplate][Thoughtswelcomedastowhatcouldbeprovidedhere.Possiblyanopportunityforthelanguage
communitytoaddressissuesthatdonotcorrelatetotheguidanceofsection6.Forlanguagesthatprovidenon-
mandatorytools,howthosetoolscanbeusedtoprovideeffectivemitigationofvulnerabilitiesdescribedinthe
followingsections]
6LanguageVulnerabilies
Deleted:
Deleted:
Deleted: Deleted:
Deleted:
Deleted:
Deleted:
Deleted:
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 179
6.x<VulnerabilityName>[<3lettertag>]
6.<x>.0Status,history,andbibliography
[Revisionhistory.Thisclausewilleventuallyberemoved.]
6.<x>.1Applicabilitytolanguage
[Thissectiondescribeswhatthelanguagedoesordoesnotdoinordertodealwiththevulnerability.]
6.<x>.2Guidancetolanguageusers
[Thissectiondescribeswhattheprogrammerorusershoulddoregardingthevulnerability.]
Inthosecaseswhereavulnerabilityissimplynotapplicabletothelanguage,thefollowingformatshouldbeusedinstead:
6.<x><VulnerabilityName>[<3lettertag>]
Thisvulnerabilityisnotapplicableto<language>.
Followingthefinalvulnerabilitydescription,thereshouldbeasinglesub-clauseasfollows:
7.<y>LanguagespecificVulnerabilitiesfor[language]
[ThissectioniswherevulnerabilitiesnotcoveredbyTR24772-1willbeplaced].Itispossiblethattherearenoneforanygivenlanguage.
8Implicationsforstandardizationorfuturerevision
[Thissectionprovidestheopportunitytodiscusschangesanticipatedforfutureversionsofthelanguagespecification.Thesectionmaybeleftempty]
Deleted:
Deleted:
WG23/N0720
180 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
Bibliography
[1] ISO/IEC9899:2011,Informationtechnology—Programminglanguages—C,withCor.1:2012,TechnicalCorrigendum1
[2] ISO/IEC30170:2012,Informationtechnology—Programminglanguages—Ruby
[3] ISO/IEC/IEEE60559:2011Informationtechnology-MicroprocessorSystems-Floating-Pointarithmetic
[4] ISO/IEC1539-1:2010,Informationtechnology—Programminglanguages—Fortran—Part1:Baselanguage
[5] ISO/IEC8652:1995,Informationtechnology—Programminglanguages—Ada
[6] ISO/IEC14882:2011,Informationtechnology—Programminglanguages—C++
[7] R.Seacord,TheCERTCSecureCodingStandard.Boston,MA:Addison-Westley,2008.
[8] MotorIndustrySoftwareReliabilityAssociation.GuidelinesfortheUseoftheCLanguageinVehicleBasedSoftware,2012(thirdedition)16F
26.
[9] ISO/IECTR24731–1,Informationtechnology—Programminglanguages,theirenvironmentsandsystem
softwareinterfaces—ExtensionstotheClibrary—Part1:Bounds-checkinginterfaces
[10] ISO/IECTR15942:2000,Informationtechnology—Programminglanguages—Guidefortheuseofthe
Adaprogramminglanguageinhighintegritysystems
[11] JointStrikeFighterAirVehicle:C++CodingStandardsfortheSystemDevelopmentandDemonstrationProgram.LockheedMartinCorporation.December2005.
[12] MotorIndustrySoftwareReliabilityAssociation.GuidelinesfortheUseoftheC++Languageincriticalsystems,June2008
[13] ISO/IECTR24718:2005,Informationtechnology—Programminglanguages—Guidefortheuseofthe
AdaRavenscarProfileinhighintegritysystems,InternationalStandardsOrganization/InternationalElectrotechnicalCommission,Geneva,Switzerland,2005.
[14] L.Hatton,SaferC:developingsoftwareforhigh-integrityandsafety-criticalsystems.McGraw-Hill1995
[15] RTCADO178C/ED12C:2011SoftwareConsiderationsinAirborneSystemsandEquipmentCertification.IssuedintheUSAbytheRequirementsandTechnicalConceptsforAviationandinEuropebytheEuropeanOrganizationforCivilAviationElectronics2011
[16] IEC61508Parts1-7,Functionalsafety:safety-relatedsystems.2010(Part3920160isconcernedwithsoftware).InternationalElectrotechnicalCommission.GenevaSwitzerland,2010,2016.
26Thefirsteditionshouldnotbeusedorquotedinthiswork.
Formatted: Not Strikethrough
Deleted: [1] ISO/IECDirectives,Part2,RulesforthestructureanddraftingofInternationalStandards,2004 ... [23]Deleted: 4
Deleted: 6
Formatted: calibriDeleted: 7
Formatted: Font:(Default) +Theme Body (Calibri), 11 pt,Italic, Font color: Auto
Deleted: ???
Formatted: Font:ItalicDeleted: 8Deleted: 9
Deleted: 10Deleted: 11
Deleted: 12
Deleted: 13
Deleted: 4
Deleted: 5
Deleted: 6
Deleted: 7Deleted: 8Deleted: 20
Formatted: Not StrikethroughFormatted: Not StrikethroughFormatted: Not StrikethroughFormatted: Not Strikethrough
Deleted: (documentRTCASC167/DO-178B)
Deleted: (EUROCAEdocumentED-12B).December1992.
Deleted: 21Formatted: Not Strikethrough
Deleted: :Deleted: 1998.
Formatted: Not StrikethroughFormatted: Not Strikethrough
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 181
[17] ISO/IEC15408:2009Informationtechnology.Securitytechniques.EvaluationcriteriaforITsecurity.
[18] JBarnes,HighIntegritySoftware-theSPARKApproachtoSafetyandSecurity.Addison-Wesley.2002.
[19] SteveChristy,VulnerabilityTypeDistributionsinCVE,V1.0,2006/10/04
[20] ARIANE5:Flight501Failure,ReportbytheInquiryBoard,July19,1996http://esamultimedia.esa.int/docs/esa-x-1819eng.pdf
[21] Hogaboom,Richard,AGenericAPIBitManipulationinC,EmbeddedSystemsProgramming,Vol12,No7,July1999http://www.embedded.com/1999/9907/9907feat2.htm(LinkBroken)stillexistsonsite)
[21] CarloGhezziandMehdiJazayeri,ProgrammingLanguageConcepts,3rdedition,ISBN-0-471-10426-4,JohnWiley&Sons,1998
[23] Lions,J.L.ARIANE5Flight501FailureReport.Paris,France:EuropeanSpaceAgency(ESA)&NationalCenterforSpaceStudy(CNES)InquiryBoard,July1996.
[24] Seacord,R.SecureCodinginCandC++.Boston,MA:Addison-Wesley,2005.Seehttp://www.cert.org/books/secure-codingfornewsanderrata.
[25] JohnDavidN.Dionisio.TypeChecking.http://myweb.lmu.edu/dondi/share/pl/type-checking-v02.pdf
[26] MISRALimited."MISRAC:2012GuidelinesfortheUseoftheCLanguageinCriticalSystems."Warwickshire,UK:MIRALimited,March2013(ISBN978-1-906400-10-1and978-1-906400-11-8).
[27] TheCommonWeaknessEnumeration(CWE)Initiative,MITRECorporation,(http://cwe.mitre.org/)
[28] Goldberg,David,WhatEveryComputerScientistShouldKnowAboutFloating-PointArithmetic,ACMComputingSurveys,vol23,issue1(March1991),ISSN0360-0300,pp5-48.
[29] RobertW.Sebesta,ConceptsofProgrammingLanguages,8thedition,ISBN-13:978-0-321-49362-0,ISBN-10:0-321-49362-1,PearsonEducation,Boston,MA,2008
[29] BoEinarsson,ed.AccuracyandReliabilityinScientificComputing,SIAM,July2005http://www.nsc.liu.se/wg25/book
[30] GAOReport,PatriotMissileDefense:SoftwareProblemLedtoSystemFailureatDhahran,SaudiArabia,B-247094,Feb.4,1992,http://archive.gao.gov/t2pbat6/145960.pdf
[31] RobertSkeel,RoundoffErrorCripplesPatriotMissile,SIAMNews,Volume25,Number4,July1992,page11,http://www.siam.org/siamnews/general/patriot.htm
[32] CERT.CERTC++SecureCodingStandard.https://www.securecoding.cert.org/confluence/pages/viewpage.action?pageId=637(2009).
[33] Holzmann,GarardJ.,Computer,vol.39,no.6,pp95-97,Jun.,2006,ThePowerof10:RulesforDevelopingSafety-CriticalCode
Deleted: 22
Deleted: 199Deleted: 23
Deleted: 25
Deleted: 6
Deleted: 7
Deleted: 8
Deleted: 9
Deleted: 30
Deleted: 31Deleted: Deleted: 32
Deleted: 33
Deleted: 34
Deleted: 36
Deleted: 37
Deleted: 38
Deleted: 9
Deleted: 40Deleted:
Deleted: 41
WG23/N0720
182 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
[34] P.V.Bhansali,Asystematicapproachtoidentifyingasafesubsetforsafety-criticalsoftware,ACMSIGSOFTSoftwareEngineeringNotes,v.28n.4,July2003
[35] AdaQualityandStyleandGuide,Guidelinesforprofessionalprogrammers.Availablefromhttps://en.wikibooks.org/wiki/Ada_Style_Guide
[36] Ghassan,A.,&Alkadi,I.(2003).ApplicationofaRevisedDITMetrictoRedesignanOODesign.JournalofObjectTechnology,127-134.
[37] Subramanian,S.,Tsai,W.-T.,&Rayadurgam,S.(1998).DesignConstraintViolationDetectioninSafety-CriticalSystems.The3rdIEEEInternationalSymposiumonHigh-AssuranceSystemsEngineering,109-116.
Deleted: 42
Deleted: 43
Deleted: 44
Deleted: 45
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 183
Index
Ada,23,71,75,83,88AMV–Type-breakingreinterpretationofdata,83API
ApplicationProgrammingInterface,26APL,59Apple
OSX,144Applicationvulnerabilities,17Applicationvulnerabilities
Useofuncheckeddatafromanuncontrolledortaintedsource[EFS],133
ApplicationvulnerabilitiesAdherencetoleastprivilege[XYN],153Authenticationlogicerror[XZO],147Clockissues[CGM],169Cross-sitescripting[XYT],134Discrepancyinformationleak[XZL],162Distinguishedvaluesindatatypes[KLK],167Downloadofcodewithoutintegritycheck[DLB],130Executingorloadinguntrustedcode[XYS],131Faulttoleranceandfailurestrategies[REU],164Hard-codedpassword[XYP],149Improperrestrictionofexcessiveauthentication
attempts[WPL],149Improperlyverifiedsignature[XZR],156Inadequatelysecurecommunicationofshared
resources[CGY],158Inclusionoffunctionalityfromuntrustedcontrol
sphere[DHU],132Incorrectauthorization[BJE],152Injection[RST],138Insufficientlyprotectedcredentials[XYM],150Memorylocking[XZX],159Missingorinconsistentaccesscontrol[XZN],151Missingrequiredcryptographicstep[XZS],155Pathtraversal[EWR],141Privilegesandboxissues[XYO],154Resourceexhaustion[XZP],145Resourcenames[HTS],144Timeconsumptionmeasurement[CCM],161Timedriftandjitter[CDJ],171Unquotedsearchpathorelement[XZQ],141Unrestrictedfileupload[CBF],129Unspecifiedfunctionality[BVQ],163URLredirectiontountrustedsite('openredirect')
[PYQ],137
Useofaone-wayhashwithoutasalt[MVX],157Applicationvulnerabilities
SensitiveinformationunclearedbeforeUse[XZK],160applicationvulnerability,13Ariane5,32bitwiseoperators,59BJE–Incorrectauthorization,152BJL–Namespaceissues,54BKK–Polymorphicvariables,31,95black-list,130,140BLP–ViolationsoftheLiskovsubstitutionprinciple
orcontractmodel,92BQF–Unspecifiedbehaviour,111BQF–Unspecifiedbehaviour,113,114break,72BRS–Obscurelanguagefeatures,109bufferboundaryviolation,34bufferoverflow,34,37bufferunderwrite,34BVQ–Unspecifiedfunctionality,163C,59,61,62,69,70,72,75C++,59,62,70,75,88,89,105callbycopy,73callbyname,73callbyreference,73callbyresult,73callbyvalue,73callbyvalue-result,73CBF–Unrestrictedfileupload,129CCB–Enumeratorissues,29CCM-Timeconsumptionmeasurement,161CDJ–Timedriftandjitter,171CGA–Concurrency–Activation,117CGM–Clockissues,169CGM–Lockprotocolerrors,124CGS–Concurrency–Prematuretermination,122CGT-Concurrency–Directedtermination,119CGX–Concurrentdataaccess,121CGY–Inadequatelysecurecommunicationofshared
resources,158CJM–Stringtermination,33CLL–Switchstatementsandstaticanalysis,66concurrency,10continue,72cryptologic,156CSJ–Passingparametersandreturnvalues,73,100danglingreference,43DCM–Danglingreferencestostackframes,75
Formatted: Number of columns: 2
WG23/N0720
184 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
Deactivatedcode,64Deadcode,64deadlock,125DHU–Inclusionoffunctionalityfromuntrusted
controlsphere,132Diffie-Hellman-style,148digitalsignature,103DJS–Inter-languagecalling,100DLB–Downloadofcodewithoutintegritycheck,130DoS
DenialofService,146dynamicallylinked,102EFS–Useofuncheckeddatafromanuncontrolled
ortaintedsource,133encryption,155,156endian
big,25little,25
endianness,24Enumerations,29EOJ–Demarcationofcontrolflow,67EWD–Structuredprogramming,71EWF–Undefinedbehaviour,112EWF–Undefinedbehaviour,111,114EWR–Pathtraversal,141exceptionhandler,105FAB–Implementation-definedbehaviour,114FAB–Implementation-definedbehaviour,111,113FIF–Arithmeticwrap-arounderror,47FIF–Arithmeticwrap-arounderror,45FLC–Conversionerrors,31Fortran,83GDL–Recursion,79generics,88GIF,130goto,72HCB–Bufferboundaryviolation(bufferoverflow),
34HCB–Bufferboundaryviolation(bufferoverflow),
100HFC–Pointertypeconversions,40HJW–unanticipatedexceptionsfromlibrary
routines,104HTML
HyperTextMarkupLanguage,140HTS–Resourcenames,144HTTP
HypertextTransferProtocol,137IEC60559,26IHN–Typesystem,22
inheritance,90IPaddress,146Java,61,63,88JavaScript,135,136JCW–Operatorprecedenceandassociativity,59KLK–Distinguishedvaluesindatatypes,167KOA–Likelyincorrectexpression,62Languagevulnerabilities
Argumentpassingtolibraryfunctions[TRJ],98Arithmeticwrap-arounderror[FIF],45Bitrepresentations[STR],24Bufferboundaryviolation(bufferoverflow)[HCB],34Choiceofclearnames[NAI],48Concurrency–Activation[CGA],117Concurrency–Directedtermination[CGT],119Concurrency–Prematuretermination[CGS],122Concurrentdataaccess[CGX],121Conversionerrors[FLC],31Danglingreferencetoheap[XYK],43Danglingreferencestostackframes[DCM],75Deadanddeactivatedcode[XYQ],64Deadstore[WXQ],50Deepvsshallowcopying[YAN],85Demarcationofcontrolflow[EOJ],67Deprecatedlanguagefeatures[MEM],116Dynamically-linkedcodeandself-modifyingcode[NYY],
102Enumeratorissues[CCB],29Extraintrinsics[LRM],97Floating-pointarithmetic[PLF],26Identifiernamereuse[YOW],52Ignorederrorstatusandunhandledexceptions[OYB],
80Implementation-definedbehaviour[FAB],114Inheritance[RIP],90Initializationofvariables[LAV],56Inter-languagecalling[DJS],100Librarysignature[NSQ],103Likelyincorrectexpression[KOA],62Lockprotocolerrors[CGM],124Loopcontrolvariables[TEX],69Memoryleaksandheapfragmentation[XYL],86Namespaceissues[BJL],54Nullpointerdereference[XYH],42Obscurelanguagefeatures[BRS],109Off-by-oneerror[XZH],70Operatorprecedenceandassociativity[JCW],59Passingparametersandreturnvalues[CSJ],73,100
BaselineEdition–3 TR24772-1
©ISO/IEC2013–Allrightsreserved 185
Pointerarithmetic[RVG],41Pointertypeconversions[HFC],40Polymorphicvariables[BKK],31,95Pre-processordirectives[NMP],105Provisionofinherentlyunsafeoperations[SKL],108Recursion[GDL],79Redispatching[PPH],94Relianceonexternalformatstring[SHL],127Side-effectsandorderofevaluation[SAM],60Stringtermination[CJM],33Structuredprogramming[EWD],71Subprogramsignaturemismatch[OTR],77Suppressionoflanguage-definedrun-timechecking
[MXB],107Switchstatementsandstaticanalysis[CLL],66Templatesandgenerics[SYM],88Typesystem[IHN],22Type-breakingreinterpretationofdata[AMV],83Unanticipatedexceptionsfromlibraryroutines[HJW],
104Uncheckedarraycopying[XYW],38Uncheckedarrayindexing[XYZ],37Undefinedbehaviour[EWF],112Unspecifiedbehaviour[BFQ],111Unusedvariable[YZS],51Usingshiftoperationsformultiplicationanddivision
[PIK],47ViolationsoftheLiskovsubstitutionprincipleor
contractmodel[BLP],92languagevulnerability,13LAV–Initializationofvariables,56Linux,144livelock,126longjmp,72LRM–Extraintrinsics,97MACaddress,146macof,146MEM–Deprecatedlanguagefeatures,116memorydisclosure,160Microsoft
Win16,144Windows,160WindowsXP,144
MIMEMultipurposeInternetMailExtensions,140
MISRAC,41MISRAC++,105mlock(),160MVX–useofaone-wayhashwithoutasalt,157
MXB–Suppressionoflanguage-definedrun-timechecking,107
NAI–Choiceofclearnames,48nametypeequivalence,23NMP–Pre-processorDirectives,105NSQ–Librarysignature,103NTFS
NewTechnologyFileSystem,130NULL,42,70NULL pointer,42null-pointer,42NYY–Dynamically-linkedcodeandself-modifying
code,102OTR–Subprogramsignaturemismatch,100OTR–Subprogramsignaturemismatch,77OYB–Ignorederrorstatusandunhandled
exceptions,80Pascal,100PHP,140PIK–Usingshiftoperationsformultiplicationand
division,45PIK–Usingshiftoperationsformultiplicationand
division,47PLF–Floating-pointarithmetic,26POSIX,118PPH–Redispatching,94pragmas,88,115predictableexecution,12,16PYQ–URLredirectiontountrustedsite('open
redirect'),137realnumbers,26Real-TimeJava,124resourceexhaustion,145REU–Faulttoleranceandfailurestrategies,164RIP–Inheritance,90RST–Injection,138RVG–Pointerarithmetic,41safetyhazard,12safety-criticalsoftware,13SAM–Side-effectsandorderofevaluation,60securityvulnerability,13SeImpersonatePrivilege,155setjmp,72SHL–Relianceonexternalformatstring,127SKL–Provisionofinherentlyunsafeoperations,108softwarequality,12softwarevulnerabilities,17SQL
Structuredquerylanguage,167STR–Bitrepresentations,24
WG23/N0720
186 ©ISO/IEC2013–Allrightsreserved
Deleted: 664
strcpy,34strncpy,34structuretypeequivalence,23switch,66SYM–TemplatesandGenerics,88symlink,143tail-recursion,80templates,88,89TEX–Loopcontrolvariables,69thread,10TRJ–Argumentpassingtolibraryfunctions,98typecoercion,31typesafe,22typesecure,22typesystem,22UNC
UniformNamingConvention,143UniversalNamingConvention,143
Unchecked_Conversion,83UNIX,102,143,144,153Unspecifiedfunctionality,163URI
UniformResourceIdentifier,136URL
UniformResourceLocator,136VirtualLock(),160white-list,130,136,140Windows,118WPL–Improperrestrictionofexcessive
authenticationattempts,149WXQ–Deadstore,50WXQ–Deadstore,51
XSSCross-sitescripting,134
XYH–Nullpointerdeference,42XYK–Danglingreferencetoheap,43XYL–Memoryleaksandheapfragmentation,86XYM–Insufficientlyprotectedcredentials,150XYN–Adherencetoleastprivilege,153XYO–Privilegesandboxissues,154XYP–Hard-codedpassword,149XYQ–Deadanddeactivatedcode,64XYS–Executingorloadinguntrustedcode,131XYT–Cross-sitescripting,134XYW–Uncheckedarraycopying,38XYZ–Uncheckedarrayindexing,37XYZ–Uncheckedarrayindexing,39XZH–Off-by-oneerror,70XZK–Sensitiveinformationunclearedbeforeuse,
160XZL–Discrepancyinformationleak,162XZN–Missingorinconsistentaccesscontrol,151XZO–Authenticationlogicerror,147XZP–Resourceexhaustion,145XZQ–Unquotedsearchpathorelement,141XZR–Improperlyverifiedsignature,156XZS–Missingrequiredcryptographicstep,155XZX–Memorylocking,159YAN–Deepvsshallowcopying,85YOW–Identifiernamereuse,52YOW–Identifiernamereuse,55YZS–Unusedvariable,50YZS–Unusedvariable,51
Closed
Page vi: [1] Deleted Stephen Michell 8/20/17 12:14:00 PM
FOREWORD..................................................................................................................................................VII
INTRODUCTION...........................................................................................................................................VIII
1.SCOPE.........................................................................................................................................................9
2.NORMATIVEREFERENCES...........................................................................................................................9
3.TERMSANDDEFINITIONS,SYMBOLSANDCONVENTIONS..........................................................................93.1TERMSANDDEFINITIONS.....................................................................................................................................93.2SYMBOLSANDCONVENTIONS.............................................................................................................................13
4.BASICCONCEPTS......................................................................................................................................144.1PURPOSEOFTHISTECHNICALREPORT..................................................................................................................144.2INTENDEDAUDIENCE........................................................................................................................................144.3HOWTOUSETHISDOCUMENT............................................................................................................................15
5VULNERABILITYISSUESANDGENERALAVOIDANCEMECHANISMS............................................................165.1PREDICTABLEEXECUTION...................................................................................................................................165.2SOURCESOFUNPREDICTABILITYINLANGUAGESPECIFICATION..................................................................................175.2.1INCOMPLETEOREVOLVINGSPECIFICATION.........................................................................................................175.2.2UNDEFINEDBEHAVIOUR.................................................................................................................................185.2.3UNSPECIFIEDBEHAVIOUR...............................................................................................................................185.2.4IMPLEMENTATION-DEFINEDBEHAVIOUR...........................................................................................................185.2.5DIFFICULTFEATURES......................................................................................................................................185.2.6INADEQUATELANGUAGESUPPORT...................................................................................................................185.3SOURCESOFUNPREDICTABILITYINLANGUAGEUSAGE.............................................................................................185.3.1PORTINGANDINTEROPERATION......................................................................................................................185.3.2COMPILERSELECTIONANDUSAGE....................................................................................................................195.4TOPAVOIDANCEMECHANISMS...........................................................................................................................19
6.PROGRAMMINGLANGUAGEVULNERABILITIES.........................................................................................216.1GENERAL........................................................................................................................................................216.2TYPESYSTEM[IHN].........................................................................................................................................226.3BITREPRESENTATIONS[STR].............................................................................................................................246.4FLOATING-POINTARITHMETIC[PLF]...................................................................................................................266.5ENUMERATORISSUES[CCB]..............................................................................................................................296.6CONVERSIONERRORS[FLC]..............................................................................................................................316.7STRINGTERMINATION[CJM].............................................................................................................................336.8BUFFERBOUNDARYVIOLATION(BUFFEROVERFLOW)[HCB]..................................................................................346.9UNCHECKEDARRAYINDEXING[XYZ]...................................................................................................................366.10UNCHECKEDARRAYCOPYING[XYW]................................................................................................................386.11POINTERTYPECONVERSIONS[HFC].................................................................................................................396.12POINTERARITHMETIC[RVG]...........................................................................................................................406.13NULLPOINTERDEREFERENCE[XYH].................................................................................................................41
6.14DANGLINGREFERENCETOHEAP[XYK]..............................................................................................................426.15ARITHMETICWRAP-AROUNDERROR[FIF].........................................................................................................446.16USINGSHIFTOPERATIONSFORMULTIPLICATIONANDDIVISION[PIK].....................................................................466.17CHOICEOFCLEARNAMES[NAI].......................................................................................................................476.18DEADSTORE[WXQ]......................................................................................................................................496.19UNUSEDVARIABLE[YZS]................................................................................................................................506.20IDENTIFIERNAMEREUSE[YOW]......................................................................................................................516.21NAMESPACEISSUES[BJL]................................................................................................................................536.22INITIALIZATIONOFVARIABLES[LAV].................................................................................................................556.23OPERATORPRECEDENCEANDASSOCIATIVITY[JCW]............................................................................................576.24SIDE-EFFECTSANDORDEROFEVALUATIONOFOPERANDS[SAM]..........................................................................586.25LIKELYINCORRECTEXPRESSION[KOA]..............................................................................................................606.26DEADANDDEACTIVATEDCODE[XYQ]..............................................................................................................626.27SWITCHSTATEMENTSANDSTATICANALYSIS[CLL]..............................................................................................646.28DEMARCATIONOFCONTROLFLOW[EOJ]..........................................................................................................666.29LOOPCONTROLVARIABLES[TEX].....................................................................................................................676.30OFF-BY-ONEERROR[XZH]..............................................................................................................................686.31STRUCTUREDPROGRAMMING[EWD]...............................................................................................................706.32PASSINGPARAMETERSANDRETURNVALUES[CSJ].............................................................................................716.33DANGLINGREFERENCESTOSTACKFRAMES[DCM].............................................................................................736.34SUBPROGRAMSIGNATUREMISMATCH[OTR]....................................................................................................756.35RECURSION[GDL].........................................................................................................................................776.36IGNOREDERRORSTATUSANDUNHANDLEDEXCEPTIONS[OYB].............................................................................786.37TYPE-BREAKINGREINTERPRETATIONOFDATA[AMV]..........................................................................................816.38DEEPVS.SHALLOWCOPYING[YAN].................................................................................................................836.39MEMORYLEAKSANDHEAPFRAGMENTATION[XYL]............................................................................................846.40TEMPLATESANDGENERICS[SYM]....................................................................................................................866.41INHERITANCE[RIP]........................................................................................................................................886.42VIOLATIONSOFTHELISKOVSUBSTITUTIONPRINCIPLEORTHECONTRACTMODEL[BLP]............................................906.43REDISPATCHING[PPH]...................................................................................................................................916.44POLYMORPHICVARIABLES[BKK]......................................................................................................................936.45EXTRAINTRINSICS[LRM]................................................................................................................................956.46ARGUMENTPASSINGTOLIBRARYFUNCTIONS[TRJ].............................................................................................966.47INTER-LANGUAGECALLING[DJS]......................................................................................................................976.48DYNAMICALLY-LINKEDCODEANDSELF-MODIFYINGCODE[NYY]...........................................................................996.49LIBRARYSIGNATURE[NSQ]...........................................................................................................................1016.50UNANTICIPATEDEXCEPTIONSFROMLIBRARYROUTINES[HJW]...........................................................................1026.51PRE-PROCESSORDIRECTIVES[NMP]...............................................................................................................1036.52SUPPRESSIONOFLANGUAGE-DEFINEDRUN-TIMECHECKING[MXB]...................................................................1056.53PROVISIONOFINHERENTLYUNSAFEOPERATIONS[SKL].....................................................................................1066.54OBSCURELANGUAGEFEATURES[BRS]............................................................................................................1076.55UNSPECIFIEDBEHAVIOUR[BQF]....................................................................................................................108
6.56UNDEFINEDBEHAVIOUR[EWF].....................................................................................................................1106.57IMPLEMENTATION-DEFINEDBEHAVIOUR[FAB].................................................................................................1116.58DEPRECATEDLANGUAGEFEATURES[MEM].....................................................................................................1136.59CONCURRENCY–ACTIVATION[CGA]..............................................................................................................1146.60CONCURRENCY–DIRECTEDTERMINATION[CGT]..............................................................................................1166.61CONCURRENTDATAACCESS[CGX]................................................................................................................1186.62CONCURRENCY–PREMATURETERMINATION[CGS]..........................................................................................1196.63PROTOCOLLOCKERRORS[CGM]...................................................................................................................1216.64RELIANCEONEXTERNALFORMATSTRING[SHL]...............................................................................................124
7.APPLICATIONVULNERABILITIES...............................................................................................................1257.1GENERAL......................................................................................................................................................1257.2UNRESTRICTEDFILEUPLOAD[CBF]..................................................................................................................1257.3DOWNLOADOFCODEWITHOUTINTEGRITYCHECK[DLB]....................................................................................1267.4EXECUTINGORLOADINGUNTRUSTEDCODE[XYS]..............................................................................................1277.5INCLUSIONOFFUNCTIONALITYFROMUNTRUSTEDCONTROLSPHERE[DHU]...........................................................1287.6USEOFUNCHECKEDDATAFROMANUNCONTROLLEDORTAINTEDSOURCE[EFS]......................................................1297.7CROSS-SITESCRIPTING[XYT]...........................................................................................................................1307.8URLREDIRECTIONTOUNTRUSTEDSITE('OPENREDIRECT')[PYQ]........................................................................1327.9INJECTION[RST]............................................................................................................................................1337.10UNQUOTEDSEARCHPATHORELEMENT[XZQ].................................................................................................1367.11PATHTRAVERSAL[EWR]..............................................................................................................................1377.12RESOURCENAMES[HTS]..............................................................................................................................1397.13RESOURCEEXHAUSTION[XZP].......................................................................................................................1407.14AUTHENTICATIONLOGICERROR[XZO]............................................................................................................1427.15IMPROPERRESTRICTIONOFEXCESSIVEAUTHENTICATIONATTEMPTS[WPL]..........................................................1447.16HARD-CODEDPASSWORD[XYP]....................................................................................................................1447.17INSUFFICIENTLYPROTECTEDCREDENTIALS[XYM].............................................................................................1457.18MISSINGORINCONSISTENTACCESSCONTROL[XZN].........................................................................................1467.19INCORRECTAUTHORIZATION[BJE].................................................................................................................1477.20ADHERENCETOLEASTPRIVILEGE[XYN]..........................................................................................................1487.21PRIVILEGESANDBOXISSUES[XYO].................................................................................................................1487.22MISSINGREQUIREDCRYPTOGRAPHICSTEP[XZS]..............................................................................................1507.23IMPROPERLYVERIFIEDSIGNATURE[XZR].........................................................................................................1507.24USEOFAONE-WAYHASHWITHOUTASALT[MVX]..........................................................................................1517.25INADEQUATELYSECURECOMMUNICATIONOFSHAREDRESOURCES[CGY]............................................................1527.26MEMORYLOCKING[XZX]..............................................................................................................................1537.27SENSITIVEINFORMATIONUNCLEAREDBEFOREUSE[XZK]..................................................................................1547.28TIMECONSUMPTIONMEASUREMENT[CCM]...................................................................................................1557.29DISCREPANCYINFORMATIONLEAK[XZL].........................................................................................................1567.30UNSPECIFIEDFUNCTIONALITY[BVQ]..............................................................................................................1577.31FAULTTOLERANCEANDFAILURESTRATEGIES[REU]..........................................................................................158
7.32DISTINGUISHEDVALUESINDATATYPES[KLK]..................................................................................................1617.33CLOCKISSUES[CCI]......................................................................................................................................1627.34TIMEDRIFTANDJITTER[CDJ]........................................................................................................................164
ANNEXA(INFORMATIVE)VULNERABILITYTAXONOMYANDLIST.................................................................167A.1GENERAL......................................................................................................................................................167A.2OUTLINEOFPROGRAMMINGLANGUAGEVULNERABILITIES...................................................................................167A.3OUTLINEOFAPPLICATIONVULNERABILITIES.......................................................................................................169A.4VULNERABILITYLIST.......................................................................................................................................170
ANNEXB(INFORMATIVE)LANGUAGESPECIFICVULNERABILITYTEMPLATE..................................................173BIBLIOGRAPHY.....................................................................................................................................................176
INDEX..........................................................................................................................................................179
FOREWORD..................................................................................................................................................VII
INTRODUCTION...........................................................................................................................................VIII
1.SCOPE.........................................................................................................................................................1
2.NORMATIVEREFERENCES...........................................................................................................................1
3.TERMSANDDEFINITIONS,SYMBOLSANDCONVENTIONS..........................................................................13.1TERMSANDDEFINITIONS.....................................................................................................................................13.2SYMBOLSANDCONVENTIONS...............................................................................................................................5
4.BASICCONCEPTS........................................................................................................................................64.1PURPOSEOFTHISTECHNICALREPORT....................................................................................................................64.2INTENDEDAUDIENCE..........................................................................................................................................64.3HOWTOUSETHISDOCUMENT..............................................................................................................................7
5VULNERABILITYISSUESANDGENERALAVOIDANCEMECHANISMS..............................................................85.1PREDICTABLEEXECUTION.....................................................................................................................................85.2SOURCESOFUNPREDICTABILITYINLANGUAGESPECIFICATION....................................................................................95.2.1INCOMPLETEOREVOLVINGSPECIFICATION...........................................................................................................95.2.2UNDEFINEDBEHAVIOUR.................................................................................................................................105.2.3UNSPECIFIEDBEHAVIOUR...............................................................................................................................105.2.4IMPLEMENTATION-DEFINEDBEHAVIOUR...........................................................................................................105.2.5DIFFICULTFEATURES......................................................................................................................................105.2.6INADEQUATELANGUAGESUPPORT...................................................................................................................105.3SOURCESOFUNPREDICTABILITYINLANGUAGEUSAGE.............................................................................................105.3.1PORTINGANDINTEROPERATION......................................................................................................................105.3.2COMPILERSELECTIONANDUSAGE....................................................................................................................115.4TOPAVOIDANCEMECHANISMS(GUIDANCE?)........................................................................................................11
6.PROGRAMMINGLANGUAGEVULNERABILITIES.........................................................................................136.1GENERAL........................................................................................................................................................13
6.2TYPESYSTEM[IHN].........................................................................................................................................146.3BITREPRESENTATIONS[STR]............................................................................................................................166.4FLOATING-POINTARITHMETIC[PLF]...................................................................................................................186.5ENUMERATORISSUES[CCB].............................................................................................................................216.6CONVERSIONERRORS[FLC]..............................................................................................................................236.7STRINGTERMINATION[CJM].............................................................................................................................256.8BUFFERBOUNDARYVIOLATION(BUFFEROVERFLOW)[HCB]..................................................................................266.9UNCHECKEDARRAYINDEXING[XYZ]...................................................................................................................286.10UNCHECKEDARRAYCOPYING[XYW]................................................................................................................306.11POINTERTYPECONVERSIONS[HFC].................................................................................................................316.12POINTERARITHMETIC[RVG]...........................................................................................................................326.13NULLPOINTERDEREFERENCE[XYH].................................................................................................................336.14DANGLINGREFERENCETOHEAP[XYK]..............................................................................................................346.15ARITHMETICWRAP-AROUNDERROR[FIF].........................................................................................................366.16USINGSHIFTOPERATIONSFORMULTIPLICATIONANDDIVISION[PIK].....................................................................386.17CHOICEOFCLEARNAMES[NAI].......................................................................................................................396.18DEADSTORE[WXQ]......................................................................................................................................416.19UNUSEDVARIABLE[YZS]................................................................................................................................426.20IDENTIFIERNAMEREUSE[YOW]......................................................................................................................436.21NAMESPACEISSUES[BJL]................................................................................................................................456.22INITIALIZATIONOFVARIABLES[LAV].................................................................................................................476.23OPERATORPRECEDENCEANDASSOCIATIVITY[JCW]............................................................................................496.24SIDE-EFFECTSANDORDEROFEVALUATIONOFOPERANDS[SAM]..........................................................................506.25LIKELYINCORRECTEXPRESSION[KOA]..............................................................................................................526.26DEADANDDEACTIVATEDCODE[XYQ]..............................................................................................................546.27SWITCHSTATEMENTSANDSTATICANALYSIS[CLL]..............................................................................................566.28DEMARCATIONOFCONTROLFLOW[EOJ]..........................................................................................................576.29LOOPCONTROLVARIABLES[TEX].....................................................................................................................596.30OFF-BY-ONEERROR[XZH]..............................................................................................................................606.31STRUCTUREDPROGRAMMING[EWD]...............................................................................................................616.32PASSINGPARAMETERSANDRETURNVALUES[CSJ].............................................................................................636.33DANGLINGREFERENCESTOSTACKFRAMES[DCM].............................................................................................656.34SUBPROGRAMSIGNATUREMISMATCH[OTR]....................................................................................................676.35RECURSION[GDL].........................................................................................................................................696.36IGNOREDERRORSTATUSANDUNHANDLEDEXCEPTIONS[OYB].............................................................................706.37TYPE-BREAKINGREINTERPRETATIONOFDATA[AMV]..........................................................................................726.38DEEPVS.SHALLOWCOPYING[YAN].................................................................................................................746.39MEMORYLEAKSANDHEAPFRAGMENTATION[XYL]............................................................................................766.40TEMPLATESANDGENERICS[SYM]....................................................................................................................776.41INHERITANCE[RIP]........................................................................................................................................796.42VIOLATIONSOFTHELISKOVSUBSTITUTIONPRINCIPLEORTHECONTRACTMODEL[BLP]...........................................816.43REDISPATCHING[PPH]...................................................................................................................................83
6.44POLYMORPHICVARIABLES[BKK]......................................................................................................................856.45EXTRAINTRINSICS[LRM]................................................................................................................................876.46ARGUMENTPASSINGTOLIBRARYFUNCTIONS[TRJ].............................................................................................886.47INTER-LANGUAGECALLING[DJS]......................................................................................................................896.48DYNAMICALLY-LINKEDCODEANDSELF-MODIFYINGCODE[NYY]...........................................................................916.49LIBRARYSIGNATURE[NSQ].............................................................................................................................926.50UNANTICIPATEDEXCEPTIONSFROMLIBRARYROUTINES[HJW].............................................................................936.51PRE-PROCESSORDIRECTIVES[NMP].................................................................................................................946.52SUPPRESSIONOFLANGUAGE-DEFINEDRUN-TIMECHECKING[MXB].....................................................................966.53PROVISIONOFINHERENTLYUNSAFEOPERATIONS[SKL].......................................................................................976.54OBSCURELANGUAGEFEATURES[BRS]..............................................................................................................986.55UNSPECIFIEDBEHAVIOUR[BQF]....................................................................................................................1006.56UNDEFINEDBEHAVIOUR[EWF].....................................................................................................................1016.57IMPLEMENTATION-DEFINEDBEHAVIOUR[FAB].................................................................................................1036.58DEPRECATEDLANGUAGEFEATURES[MEM].....................................................................................................1056.59CONCURRENCY–ACTIVATION[CGA]..............................................................................................................1066.60CONCURRENCY–DIRECTEDTERMINATION[CGT]..............................................................................................1086.61CONCURRENTDATAACCESS[CGX]................................................................................................................1096.62CONCURRENCY–PREMATURETERMINATION[CGS]..........................................................................................1116.63PROTOCOLLOCKERRORS[CGM]...................................................................................................................1136.64RELIANCEONEXTERNALFORMATSTRING[SHL]...............................................................................................115
7.APPLICATIONVULNERABILITIES...............................................................................................................1177.1GENERAL......................................................................................................................................................1177.2UNRESTRICTEDFILEUPLOAD[CBF]..................................................................................................................1177.3DOWNLOADOFCODEWITHOUTINTEGRITYCHECK[DLB]....................................................................................1187.4INCLUSIONOFFUNCTIONALITYFROMUNTRUSTEDCONTROLSPHERE[DHU]...........................................................1197.5URLREDIRECTIONTOUNTRUSTEDSITE('OPENREDIRECT')[PYQ]........................................................................1207.6USEOFUNCHECKEDDATAFROMANUNCONTROLLEDORTAINTEDSOURCE[EFS]......................................................1217.7CROSS-SITESCRIPTING[XYT]...........................................................................................................................1227.8ADHERENCETOLEASTPRIVILEGE[XYN]............................................................................................................1247.9PRIVILEGESANDBOXISSUES[XYO]...................................................................................................................1257.10EXECUTINGORLOADINGUNTRUSTEDCODE[XYS]............................................................................................1267.11MISSINGREQUIREDCRYPTOGRAPHICSTEP[XZS]..............................................................................................1277.12INSUFFICIENTLYPROTECTEDCREDENTIALS[XYM].............................................................................................1287.13MISSINGORINCONSISTENTACCESSCONTROL[XZN].........................................................................................1297.14AUTHENTICATIONLOGICERROR[XZO]............................................................................................................1297.15HARD-CODEDPASSWORD[XYP]....................................................................................................................1317.16SENSITIVEINFORMATIONUNCLEAREDBEFOREUSE[XZK]..................................................................................1327.17IMPROPERLYVERIFIEDSIGNATURE[XZR].........................................................................................................1337.18USEOFAONE-WAYHASHWITHOUTASALT[MVX]..........................................................................................1347.19INADEQUATELYSECURECOMMUNICATIONOFSHAREDRESOURCES[CGY]............................................................134
7.20MEMORYLOCKING[XZX]..............................................................................................................................1367.21RESOURCEEXHAUSTION[XZP].......................................................................................................................1377.22TIMECONSUMPTIONMEASUREMENT[CCM]...................................................................................................1387.23INCORRECTAUTHORIZATION[BJE].................................................................................................................1397.24IMPROPERRESTRICTIONOFEXCESSIVEAUTHENTICATIONATTEMPTS[WPL]..........................................................1407.25UNSPECIFIEDFUNCTIONALITY[BVQ]..............................................................................................................1407.26FAULTTOLERANCEANDFAILURESTRATEGIES[REU]..........................................................................................1417.27DISTINGUISHEDVALUESINDATATYPES[KLK]..................................................................................................1447.28RESOURCENAMES[HTS]..............................................................................................................................1467.29INJECTION[RST]..........................................................................................................................................1477.30UNQUOTEDSEARCHPATHORELEMENT[XZQ].................................................................................................1507.31DISCREPANCYINFORMATIONLEAK[XZL].........................................................................................................1517.32PATHTRAVERSAL[EWR]..............................................................................................................................1527.33CLOCKISSUES[CCI]......................................................................................................................................1547.34TIMEDRIFTANDJITTER[CDJ]........................................................................................................................156
ANNEXA(INFORMATIVE)VULNERABILITYTAXONOMYANDLIST.................................................................158A.1GENERAL......................................................................................................................................................158A.2OUTLINEOFPROGRAMMINGLANGUAGEVULNERABILITIES...................................................................................158A.3OUTLINEOFAPPLICATIONVULNERABILITIES.......................................................................................................160A.4VULNERABILITYLIST.......................................................................................................................................161
ANNEXB(INFORMATIVE)LANGUAGESPECIFICVULNERABILITYTEMPLATE..................................................164BIBLIOGRAPHY.....................................................................................................................................................167
INDEX..........................................................................................................................................................170
Page 49: [2] Formatted Stephen Michell 10/19/17 11:10:00 AM
Font:Italic,Underline,Fontcolor:Blue,(Asian)Chinese(PRC)
Page 49: [3] Formatted Stephen Michell 6/18/17 2:43:00 PM
Font:Italic,Underline,Fontcolor:Blue,(Asian)Chinese(PRC)
Page 49: [4] Formatted Stephen Michell 6/18/17 2:43:00 PM
Font:Italic,Underline,Fontcolor:Blue,(Asian)Chinese(PRC)
Page 49: [5] Formatted Stephen Michell 6/18/17 2:43:00 PM
Font:Italic,Underline,Fontcolor:Blue,(Asian)Chinese(PRC)
Page 49: [6] Formatted Stephen Michell 6/18/17 2:43:00 PM
Font:Italic,Underline,Fontcolor:Blue,(Asian)Chinese(PRC)
Page 75: [7] Deleted Stephen Michell 6/20/17 5:01:00 AM
.
W•
Page 94: [8] Deleted Stephen Michell 6/20/17 6:36:00 AM
Insteadpreferdynamicmethodselectionbasedontheactualclassofthereceivingobjectorcontrollingargumenttothedowncastingofthereferencetotherespectiveclass.
Inlanguageswithstaticnamebindingofmethods,thelastrecommendationleadstospecificationsofmethodsinsuperclassesmerelytobeabletocallthemforsubclasses.Thiscandestroyproperclassdesignandcancreateclasseswithhundredsofmethods.Inlanguageswithdynamicnamebindingofmethods,ittradesthe“inappropriateclass”-exceptionofthedowncastagainstthe“method-not-found”-exceptionofthedispatchingcall.
Page 111: [9] Formatted Stephen Michell 10/19/17 11:10:00 AM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [9] Formatted Stephen Michell 10/19/17 11:10:00 AM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [9] Formatted Stephen Michell 10/19/17 11:10:00 AM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [9] Formatted Stephen Michell 10/19/17 11:10:00 AM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [9] Formatted Stephen Michell 10/19/17 11:10:00 AM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [9] Formatted Stephen Michell 10/19/17 11:10:00 AM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [9] Formatted Stephen Michell 10/19/17 11:10:00 AM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [9] Formatted Stephen Michell 10/19/17 11:10:00 AM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [9] Formatted Stephen Michell 10/19/17 11:10:00 AM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [10] Formatted Stephen Michell 6/18/17 2:43:00 PM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [10] Formatted Stephen Michell 6/18/17 2:43:00 PM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [10] Formatted Stephen Michell 6/18/17 2:43:00 PM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [10] Formatted Stephen Michell 6/18/17 2:43:00 PM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [10] Formatted Stephen Michell 6/18/17 2:43:00 PM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [10] Formatted Stephen Michell 6/18/17 2:43:00 PM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [10] Formatted Stephen Michell 6/18/17 2:43:00 PM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [10] Formatted Stephen Michell 6/18/17 2:43:00 PM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [10] Formatted Stephen Michell 6/18/17 2:43:00 PM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [11] Formatted Stephen Michell 10/19/17 11:10:00 AM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [11] Formatted Stephen Michell 10/19/17 11:10:00 AM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [11] Formatted Stephen Michell 10/19/17 11:10:00 AM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [11] Formatted Stephen Michell 10/19/17 11:10:00 AM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [11] Formatted Stephen Michell 10/19/17 11:10:00 AM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [11] Formatted Stephen Michell 10/19/17 11:10:00 AM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [11] Formatted Stephen Michell 10/19/17 11:10:00 AM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [11] Formatted Stephen Michell 10/19/17 11:10:00 AM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [11] Formatted Stephen Michell 10/19/17 11:10:00 AM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [12] Formatted Stephen Michell 6/18/17 2:43:00 PM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [12] Formatted Stephen Michell 6/18/17 2:43:00 PM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [12] Formatted Stephen Michell 6/18/17 2:43:00 PM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [12] Formatted Stephen Michell 6/18/17 2:43:00 PM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [12] Formatted Stephen Michell 6/18/17 2:43:00 PM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [12] Formatted Stephen Michell 6/18/17 2:43:00 PM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [12] Formatted Stephen Michell 6/18/17 2:43:00 PM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [12] Formatted Stephen Michell 6/18/17 2:43:00 PM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [12] Formatted Stephen Michell 6/18/17 2:43:00 PM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [13] Formatted Stephen Michell 10/19/17 11:10:00 AM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [13] Formatted Stephen Michell 10/19/17 11:10:00 AM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [13] Formatted Stephen Michell 10/19/17 11:10:00 AM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [13] Formatted Stephen Michell 10/19/17 11:10:00 AM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [13] Formatted Stephen Michell 10/19/17 11:10:00 AM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [13] Formatted Stephen Michell 10/19/17 11:10:00 AM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [13] Formatted Stephen Michell 10/19/17 11:10:00 AM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [13] Formatted Stephen Michell 10/19/17 11:10:00 AM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [14] Formatted Stephen Michell 6/18/17 2:43:00 PM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [14] Formatted Stephen Michell 6/18/17 2:43:00 PM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [14] Formatted Stephen Michell 6/18/17 2:43:00 PM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [14] Formatted Stephen Michell 6/18/17 2:43:00 PM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [14] Formatted Stephen Michell 6/18/17 2:43:00 PM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [14] Formatted Stephen Michell 6/18/17 2:43:00 PM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [14] Formatted Stephen Michell 6/18/17 2:43:00 PM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [14] Formatted Stephen Michell 6/18/17 2:43:00 PM
Font:Italic,Underline,Fontcolor:Blue
Page 111: [15] Deleted Stephen Michell 6/20/17 9:01:00 AM
Page 111: [15] Deleted Stephen Michell 6/20/17 9:01:00 AM
Page 111: [16] Deleted Stephen Michell 6/20/17 9:01:00 AM
Page 111: [16] Deleted Stephen Michell 6/20/17 9:01:00 AM
Page 121: [17] Deleted Stephen Michell 6/17/17 5:12:00 AM
Handleeventsandexceptionsfromtermination.
•
Page 124: [18] Deleted Stephen Michell 10/16/17 8:19:00 PM
Theprogrammerrarelyintendsforaformatstringtobeuser-controlledatall.Thisweaknessfrequentlyoccursincodethatconstructslogmessages,whereaconstantformatstringisomitted.
Incasessuchaslocalizationandinternationalization,thelanguage-specificmessagerepositoriescouldbeanavenueforexploitation,buttheformatstringissuewouldberesultant,sinceattackercontrolofthoserepositorieswouldalsoallowmodificationofmessagelength,format,andcontent
Page 125: [19] Deleted Stephen Michell 10/16/17 8:22:00 PM
Softwaredeveloperscanavoidthevulnerabilityormitigateitsilleffectsinthefollowingways:
Ensurethatallformatstringfunctionsarepassedasstaticstringwhichcannotbecontrolledbytheuserandthatthepropernumberofargumentsisalwayssenttothatfunction.
Ensureallspecifiersusedmatchtheassociatedparameter. Avoidformatstringsthatwillwritetoamemorylocationthatispointedtobyitsargument
•
Page 151: [20] Deleted Stephen Michell 6/20/17 8:30:00 AM
),theprogramshoulddroprootprivilegeandreturntotheprivilegeleveloftheinvokinguser.
InnewerWindowsimplementations,makesurethattheprocesstokenhastheSeImpersonatePrivilege.[SM1]
Page 161: [21] Deleted Stephen Michell 6/20/17 8:42:00 AM
Iffaultsarenotdetectedintimeandrepairedcompletely,thefollowingfailuresarise: omissionfailures:aserviceisaskedforbutneverrendered.Theclientmightwaitforever
orbenotifiedtoolateaboutthefailure(termination)oftheservice. commissionfailures:aserviceinitiatesunexpectedactions,e.g.,communicationthatis
unexpectedbythereceiver.Theservicemightwaitforever,causingomissionfailuresforsubsequentcallsbyclients,ortheactionsmightinterferewiththeregularprocessinggoingoninthemeantime.Ataminimum,itconsumesresourcespossiblyneededbyotherstomeetdeadlines.
timingfailures:aserviceisnotrenderedbeforeanimposeddeadline.Systemresponseswillbe(too)late,causingcorrespondingdamagestotherealworldaffectedbythesystem.
Valuefailures:aservicedeliversincorrectortaintedresults.Ifnottheclientcontinuescomputationswiththesecorruptedvalues,causingaspreadofconsequentialapplicationerrorsandimplementationvulnerabilitiescausedbycorruptedvaluesasdiscussedelsewhereinthisdocument.
Page 166: [22] Deleted Stephen Michell 8/20/17 12:20:00 PM
.
•
Page 180: [23] Deleted Stephen Michell 3/10/17 11:50:00 AM
[1] ISO/IECDirectives,Part2,RulesforthestructureanddraftingofInternationalStandards,2004
[2] ISO/IECTR10000-1,Informationtechnology—FrameworkandtaxonomyofInternationalStandardizedProfiles—Part1:Generalprinciplesanddocumentationframework