text
stringlengths 64
2.99M
|
---|
areparticularlyerror-prone[10,33,61,121,132]. thattheydonotprotectagainstcacheattacks.Similarly,Ronenetal. [109]showedthatpaddingoraclesleadingtoBleichenbacher-like ECDSA.Despiteextensiveresearchonmitigatingscalarmultipli- attackswerestillpresentinlibrariessuchasMbedTLS,s2n,orNSS, cationinECDSA,Garciaetal. [60]identifiedexploitableusageof duetoearlyterminationinpaddingverification. modularinversionwiththevulnerableBEEA[5].Thevulnerable codepathwastakenbecauseofamissingCTflagonthenonce. 5.2 Vulnerabilitiesinnewfunctionalities SM2.TheintegrationoftheSM2standardintoOpenSSLdidnot Arithmetic functions.Genkin et al. [65] targeted the X25519 inheritfromlessonslearnedinECDSA[121].Inparticular,SM2 keyexchangeimplementedinLibgcrypt,findingthat,whilescalar signaturegenerationdirectlycalledthevulnerablewNAFscalar multiplicationisdoneusingabranchlessMontgomeryladder,the multiplicationwithnopaddingdoneonthescalar,allowingtiming underlyingfinitefieldarithmeticfunctionswerenotconstant-time. attacks[24].FailuretosettheappropriateCTflagalsoresultedin Anearlyexitinthemodularreductionfunctionallowedtheauthors themodularinversionusingBEEA. tomountacacheattackrecoveringthekey.Aranhaetal.[18]dis- Key generation.The RSA key generation process did not use coveredasimilarissueinOpenSSLbranchlessMontgomeryLadder side-channelprotections,assingle-traceattackswerethoughtto usedforECDSA.Wheninitializingthealgorithm,aconditionalCCS’23,November26–30,2023,Copenhagen,Denmark Geimeretal. swapisdonedependingonasecretvalue.Whiletheswapitselfis reformulatedaswhether∃𝑘 1,𝑘 2 ∈𝐾,𝑓(𝑘 1,𝑚)≠𝑓(𝑘 2,𝑚),with𝐾 constant-time,thefollowingfinitefieldmultiplicationisnot. thesetofpossiblesecrets.ContrarytopriorworkusingDSE[128], Hash-to-element.TheDragonflyhandshakeusedinWi-Fiau- A anb dac 𝑘u 2s ,ad soe its in so ot ftu es ne sS uM ffiT cis eo nlv te tr os tb riu gt gr ea rn td ho em lely akp aic gk es . valuesfor𝑘 1 thenticationconvertsasharedpasswordtoanellipticcurvepoint, Inpractice,thedevelopermustindicatewhichvariableissecret by computing the point coordinate derived from the password eitherthroughanannotationorwritingacustomPintool.Wenoted andacounter.Whentheobtainedpointisinvalid,thecounteris aflawinthatAbacusonlyregistersthefirstannotationandignores incrementedandtheoperationrepeated,thuscreatingatiming thesubsequentones.Assuch,forourexperiments,wewrotea channel.Whilethestandardsuggestsfixingtherepetitionsnumber Pintoollettingusmarkassecretanarbitrarynumberofbuffers byaddingdummyones,VanhoefandRonen[126]foundthatsuch ofarbitrarylength.Finally,Abacuscomputesanestimationofthe mitigationswereoftenincorrectlyimplemented,ifatall,leaving numberofbitsleaked. implementationsvulnerabletocacheattacks[32]. Post-QuantumCryptography(PQC).BLISS-Bsignaturegen- 6.2 Binsec/Rel erationinvolvessamplingasecretpolynomialfromaGaussian Binsec/Rel[51]usesSEforbug-findingandbounded-verification distribution.Samplingmethodsbasedonpre-computedtableswere ofconstant-timeatbinarylevel.ItliftsthetargetbinarytoanIR, showntobevulnerabletocacheattacks[98]andbranchtracing performsSEalongallprogrampaths,andchecksthatcontrol-flow attacks[120].AcommonapproachinPQCistoconstructacrypto- andmemoryaccessesdonotdependonsecret.Moreprecisely,Bin- graphicschemesecureagainstchosenplaintextattacksthenmaking sec/RelusesrelationalSEtomodeltwoexecutionsofaprogram itsecureagainstchosenciphertextattacksusingagenerictrans- inthesameSEinstance,withthesamepublicinputbutdistinct formation.Suchtransformationcanleadtokey-recoveryattacksif secretinputs.SMTqueriesallowcheckingwhetherthesepairsof notconstanttime[72]. pathcandivergeoncontrol-flowormemoryaddresses.Ifaqueryis 5.3 Insights satisfiable,theprogramisinsecureandthesolverreturnsacounter- exampletriggeringthevulnerability.Conversely,ifallqueriesare Themajorityofrecentpublicationsreproducevulnerabilitieswhich unsatisfiableandtheexplorationisexhaustive,theprogramisse- havebeenlongknown,butinnewcontextandlibraries.Analysis cure.Inpractice,thesequeriesareexpensive,soBinsec/Reluses shouldnotfocusondetectingconstant-timeviolationsintheircode, optimizations to spare unsatisfiable queries, making it scale on butratherdetecttheirincorrectuseinthewidercode-base.Test secureprograms.However,satisfiablequeriesmayremainabottle- methodologieslikeTriggerFlow[69]arepromisinginthisregard, neckoninsecureprograms. andcomplementingthemwithfuzzingapproachescouldallowfor Binsec/Rel2. The Binsec/Rel team has recently developed a widerexplorationofcryptographiclibraries.Newvulnerabilitiesare secondversion,Binsec/Rel2[27],withbettergeneralperformance notfoundinusualcryptographicprimitivesdirectly,butinnewer andarchitecturesupport(basedonthelatestversionofthesymbolic protocols/schemes,orinlower-levelutilityfunctions.Detection engine),easiersetup(core-dumpbasedinitialization),anddedicated tools thus need to be able to fully analyze programs, including optimizationforsatisfiablequeries—basedonevaluationoverpre- |
utilityfunctions,andscaletofullprotocolruns. chosenconcretevalues. 6 Toolsconsidered 6.3 MicroWalk-CI Therestofthispaperisdedicatedtocomparingtheseapproaches MicroWalk[134]recordsmultipleexecutionsofthetargetfunction and characterizing them with regards to known vulnerabilities. underdifferentinputsusingIntelPin.Therecordedtracecontains Werestrictourselvestofivetools:Abacus[20],Binsec/Rel[51], branchtargetsandmemoryaddressesencounteredduringtheex- MicroWalk-CI[135],dudect[107],andct-grind[86].Together,they ecution.Mutualinformationscoresarethencomputedbetween arerepresentativeofthediversityofmethodsoftheliteratureand theleakagetraceandtheinputset,givingaquantificationofthe usedinpractice,withamixofstaticanddynamictools.Thefirst numberofinputbitsleaked.MicroWalkoffersvariousMIscore threetoolsarefromacademicpublications,whilethelasttwoare granularity/performancetradeoffs,rangingfromwholeprogram knowntobeusedbydevelopers[74].Ourselectionisbasedon MI—givingacoarseleakagequantification—tosingleinstructions— availability,abilitytoanalyzebinarycode,scalability(fromthe forexactleakagelocalization.MicroWalk-CI[135]addssupport claimsintheirpublications),andguaranteesprovidedbythetool. forJavascript.Specialattentionhasbeenpaidtotheframework’s 6.1 Abacus usability,withhumanreadablereportscompatiblewithCIfeatures. Abacus[20]firstobtainsanexecutiontracebyrunningthetarget 6.4 dudect programwithconcreteinputsusingthebinaryinstrumentation frameworkIntelPin[91].Then,theSEenginereplaysthetracewith dudect[107]detectstimingleakagethroughrepeatedtimingmea- thesecretdatasettosymbolicvalues.Formulasaregeneratedonly surementsandcomparisonusingastatisticaltest.Thebinaryis for instructions manipulating secret values, otherwise concrete executedundertwodifferentclassesofsecretinputs:onesetto valuesareused.Acontrolflowormemoryaccessisrepresented constantvaluesandonesettovaluesrandomlyselectedbefore asafunction𝑓 ofthesecretsymbolicinputs𝑘andpublicconcrete eachmeasurement.Theexecutiontimingsofthetargetfunction inputs𝑚.TheproblemofwhetheraninstructionviolatesCTis arethenrecordedbyprobingCPUcyclecounters.MeasurementsASystematicEvaluationofAutomatedToolsforSide-ChannelVulnerabilitiesDetectioninCryptographicLibraries CCS’23,November26–30,2023,Copenhagen,Denmark aboveacertainpercentile𝑝 areassumedtobenoiseandarere- leakage,notablyforAES.ForOpenSSLweincludethevulnerable moved.Anonlinet-testisthenappliedtodeterminewhetherthe T-tableimplementationandthesecurevectorpermutation(VP)im- twodistributionsaredistinguishable,withleakagebeingreported plementation.ForBearSSL,weincludeitsT-tableimplementation ifthevaluepassesapredefinedthreshold.Whilethisapproachis anditsconstant-timeimplementation,basedonabit-slicing(BS) simpleandeasytodeploy,itonlygivesguaranteesuptoacertain approach.SuchimplementationsalsoexistforOpenSSL,butnot numberofmeasurements. forour32-bitsconfiguration.Finally,weaddabenchmarkusing OpenSSL’sEVPAPI,whichistheintendedentrypointfordevelop- 6.5 ctgrind ersanddynamicallyselectsthebestimplementationavailable. ctgrind[86]usesValgrind’smemoryerrordetector,Memcheck, Limits.Thesecommonoperationsarenotallsupportedinthesame todetectpotentialside-channelleakages.AsMemcheckalready way.BearSSLonlysupportsRSAdecryptionwithOAEPpadding, detectsbranchesandmemoryaccessescomputedonuninitialized whereonlyOpenSSLsupportsEdDSA.Whilewefavordeterministic memory, side-channel vulnerabilities can be found by marking ECDSAasitderivesthesecretfromthekeywithoutanyPRNG, secretvariablesasundefined,throughaspecificcodeannotation. OpenSSLdoesnotsupportitatthetimeofourexperiments[3].We Internally, Memcheck detects errors by shadowing every bit of thususethenon-deterministicversion. datamanipulatedbytheprogramwithadefinednessbitV[114], propagatedthroughouttheexecutionsimilarlytoataintanalysis Benchmarkdesign.Welimitourselvestosimpletestharnesses, andcheckedwhencomputinganaddressorajump. limitingthenumberofauxiliaryoperationsbeforethetargetcryp- Appliedtoside-channelanalysishowever,thisapproachyieldsa tographicoperationinordertoavoidintroducingextraissuesin considerablenumberoffalsepositives,aserrorsunrelatedtosecret termsofscalability,instructionsupport,ornon-determinism.Only valuesarealsoreported.Still,ctgrindisparticularlypopularin theinputofthetargetoperationaremarkedassecret.Forsymmet- cryptographiclibrariesforitssimplicityandeaseofdeployment: riccipherswemarkthesharedkeyassecret,forRSAthesecret ctgrindisusedby5outofthe6cryptographiclibrariesperforming keyparameters(includingtheCRTparameters),forellipticcurves CTtestsasreportedby[74]. thesecretscalar.Foreachbenchmark,thearrayscontainingsecret 7 Unifiedbenchmark valuesarealsomarkedassuchatthebeginningofthemain.While ideallywewouldrunalltheselecteddetectiontoolsonthesame Tofairlycomparethescalabilityandvulnerabilitiesreportedby binaryforagivenbenchmark,thetoolshaveconflictingrequire- existingapproaches(RQ1),wecreateaunifiedbenchmark,com- ments.Assuch,foreachbenchmarkweproducebotha32-bitsand prisedofrepresentativecryptographicoperationsfrom3libraries, a64-bitsversion,thelatterbeingusedonlybyMicroWalk. |
totaling25benchmarks.Table2presentsourresults. 7.1 Descriptionandsetup Evaluationprotocol.Wecomparethenumbersofvulnerabili- tiesfoundbyeachtoolandtherunningtimesoftheanalysis.All Libraries.WeincludeOpenSSL[4],asitisoneofthemostpopular experimentsarerunonalaptopequippedwithani7-8650Uproces- cryptographiclibrary[95]andhasalonghistoryofside-channel sorrunningUbuntu20.04LTS.ForAbacus,MicroWalkandboth vulnerabilities.MbedTLS[58]isanotherpopularlibrary,particu- versionsof Binsec/Rel,thevulnerabilitycountistakendirectly larlyforembeddedtargets.Itsmaintainersconsiderside-channel fromthetooloutput,correspondingtothenumberofuniqueleaky attacksintheirthreatmodel,thoughitisaworkinprogressrele- instructions.Forctgrind,somepost-processingisneededonthe vantmainlyfornewcode.BearSSL[100]isasmallerlibrarywith output. anemphasisoneaseofdeploymentandsecurity.Inparticular,the First,ctgrindreportsasingleleakinginstructionmultipletimesif authormakesclearclaimsonwhichfunctionsareconstant-time, itisreachedindifferentcontexts,sowededuplicatethereporteder- whichhelpsusestablishagroundtruthforourbenchmark.For rorcount.Second,asctgrindisbasedonValgrind,errorsunrelated eachoftheselibrarieswepickthelatestversionsatthetimesof toconstant-timearealsobereported.Forexample,onstatically experiment(3.0.5,3.1and0.6respectively),andcompilethelibraries linkedprograms,Valgrindreportsproblemsfromglibcfunctions[2]. asstatic32-bitsobjects,tomeetthedetectiontoolrequirements. Toremedythis,wegenerateasuppressionfilebyfirstrunningthe Whilewekeeplibraryconfigurationsclosetotheirdefaults,for programwithoutannotatingthesecret.Asaresult,errorsinde- MbedTLS,wedisablesupportforVIAPadLockinstructionsand pendentofthesecretarenotreported.Therunningtimeofthe AEStablegenerationcode. analysisismeasuredasthetotaltimefromfirstinvokingthetoolto Algorithms.Wechosewidely-usedcryptographicoperationsfrom itsexit.ForBinsec/Rel,thisincludesgenerationofthecoredump whenneeded.ForAbacus,thisincludesthetimeneededtorecorda bothsymmetricandasymmetricschemes.WetargetAESencryp- traceusingPin,assuchourrunningtimesaregenerallylongerthan tion,inbothCBCandtheauthenticatedGCMmode,aswellas thoseintheoriginalpublication[20].Fordudect,computationsof thePoly1305-Chacha20AEADscheme.WetargetRSAdecryption thet-testscorearedoneinbatchesof5000measurements,repeated withbothPKCS#1v1.5andOAEPpaddingscheme.ECDSAsigna- untiltheanalysiseitherfinishesortimesout.Newinputsaregen- turegenerationusingP-256andEdDSAsignaturegenerationusing eratedforeachmeasurement.Weadditionallythrashthecacheby Curve25519arealsoincluded. accessingalargearraybetweeneachrunofthetargetedalgorithm Implementations.Alibrarycanincludedifferentimplementa- tolimitcacheside-effects.MicroWalkissetuptogenerate16traces, tionsofasinglealgorithmwithdifferingimpactsonside-channel asrecommendedbytheauthors[135].CCS’23,November26–30,2023,Copenhagen,Denmark Geimeretal. Table2:Vulnerabilitydetection.#V:numberofreportedvulnerabilities,S:status( secure; insecure; unknown),t:timeto firstbuginseconds,T:analysistimeinseconds. (cid:32) (cid:35) (cid:71)(cid:35) Binsec/Rel Binsec/Rel2 Abacus ctgrind MicroWalk dudect Benchmarks #V S t(s) T(s) #V S t(s) T(s) #V S T(s) #V S T(s) #V S T(s) S T(s) AES-CBC-bearssl(T) 20 0.05 (cid:220) 36 0.02 0.10 36 3.65 36 0.16 36 1.39 100.51 AES-CBC-bearssl(BS) 0 (cid:35) – 16.77 0 (cid:35) – 0.31 0 (cid:35) 10.69 0 (cid:35) 0.17 0 (cid:35) 1.55 (cid:35) (cid:220) AES-GCM-bearssl(T) 20 (cid:32) 0.05 (cid:220) 36 (cid:32) 0.02 0.22 36 (cid:71)(cid:35) 6.23 36 (cid:71)(cid:35) 0.18 36 (cid:71)(cid:35) 1.51 (cid:71)(cid:35) 8.69 AES-GCM-bearssl(BS) 0 (cid:35) – 53.32 0 (cid:35) – 0.48 0 (cid:35) 14.79 0 (cid:35) 0.17 0 (cid:35) 1.73 (cid:35) (cid:220) AES-CBC-mbedtls(T) 20 (cid:32) 0.1 (cid:220) 68 (cid:32) 0.03 0.17 68 (cid:71)(cid:35) 5.73 68 (cid:71)(cid:35) 0.19 68 (cid:71)(cid:35) 1.54 (cid:71)(cid:35) 0.63 AES-GCM-mbedtls(T) 20 (cid:35) 0.27 (cid:220) 84 (cid:35) 0.05 0.4 84 (cid:35) 261.76 76 (cid:35) 0.19 71 (cid:35) 1.90 (cid:35) 0.89 AES-CBC-openssl(EVP) 0 (cid:35) – (cid:220) 0†‡ (cid:35) – 21.92 0 (cid:35) 103.59 0 (cid:35) 0.66 9 (cid:35) 5.35 (cid:35) (cid:220) |
AES-GCM-openssl(EVP) 0 (cid:71)(cid:35) – (cid:220) 0†‡ (cid:71)(cid:35) – 21.19 0 (cid:71)(cid:35) 104.27 70 (cid:71)(cid:35) 0.71 8 (cid:35) 5.66 (cid:71)(cid:35) (cid:220) AES-CBC-openssl(T) 20 (cid:71)(cid:35) 0.05 (cid:220) 36 (cid:71)(cid:35) 0.02 0.16 36 (cid:71)(cid:35) 3.02 36 (cid:35) 0.18 20 (cid:35) 1.38 (cid:71)(cid:35) (cid:220) AES-CBC-openssl(VP) 0† (cid:35) – 0.06 0‡ (cid:35) – 0.59 0 (cid:35) 1.01 0 (cid:35) 0.19 0 (cid:35) 1.68 (cid:71)(cid:35) (cid:220) PolyChacha-bearssl(CT) 0 (cid:71)(cid:35) – 9.72 0 (cid:32) – 0.18 0 (cid:71)(cid:35) 1.3 0 (cid:71)(cid:35) 0.16 0 (cid:71)(cid:35) 1.43 (cid:71)(cid:35) (cid:220) PolyChacha-bearssl(SSE2) 0† (cid:32) – 0.05 0 (cid:32) – 0.11 0 (cid:71)(cid:35) 1.17 0 (cid:71)(cid:35) 0.15 0 (cid:71)(cid:35) 1.34 (cid:71)(cid:35) (cid:220) PolyChacha-mbedtls 0 (cid:71)(cid:35) – 18.62 0 (cid:32) – 0.49 0 (cid:71)(cid:35) 5.02 0 (cid:71)(cid:35) 0.18 0 (cid:71)(cid:35) 2.95 (cid:71)(cid:35) (cid:220) PolyChacha-openssl(EVP) 0 (cid:32) – (cid:220) 0‡ (cid:32) – 21.55 X (cid:71)(cid:35) 100.19 0 (cid:71)(cid:35) 0.67 8 (cid:71)(cid:35) 5.41 (cid:71)(cid:35) (cid:220) Chacha20-openssl 0 (cid:71)(cid:35) – 0.77 0 (cid:32) – 0.09 0 (cid:71)(cid:35) 3.77 0 (cid:71)(cid:35) 0.15 0 (cid:35) 1.36 (cid:71)(cid:35) (cid:220) Poly1305-openssl 0 (cid:32) – 0.26 0‡ (cid:32) – 0.35 X (cid:71)(cid:35) 1.19 0 (cid:71)(cid:35) 0.17 0 (cid:71)(cid:35) 1.70 (cid:71)(cid:35) (cid:220) RSA-bearssl(OAEP) 0 (cid:32) – (cid:220) 2 (cid:32) 0.03 (cid:220) X (cid:71)(cid:35) 356.41 87 (cid:71)(cid:35) 0.57 0 (cid:71)(cid:35) 146.52 (cid:71)(cid:35) (cid:220) RSA-mbedtls(PKCS) 1 (cid:71)(cid:35) 1.60 (cid:220) 5‡ (cid:35) 0.21 (cid:220) X (cid:71)(cid:35) 2193.2 39 (cid:35) 0.96 137 (cid:71)(cid:35) 826.23 (cid:71)(cid:35) (cid:220) RSA-mbedtls(OAEP) 1 (cid:35) 1.46 (cid:220) 5‡ (cid:35) 0.21 (cid:220) X (cid:71)(cid:35) 2203.89 48 (cid:35) 0.98 137 (cid:35) 847.27 (cid:71)(cid:35) (cid:220) RSA-openssl(PKCS) 1 (cid:35) 26.50 (cid:220) 1‡ (cid:35) 0.44 (cid:220) 0 (cid:71)(cid:35) 551.72 321 (cid:35) 1.32 46 (cid:35) 52.06 (cid:71)(cid:35) 618.73 RSA-openssl(OAEP) 1 (cid:35) 29.02 (cid:220) 1‡ (cid:35) 0.46 (cid:220) X (cid:71)(cid:35) 535.91 546 (cid:35) 1.73 61 (cid:35) 59.90 (cid:35) 771.3 ECDSA-bearssl 2 (cid:35) 1.82 (cid:220) 2 (cid:35) 0.84 (cid:220) 0 (cid:71)(cid:35) 246.62 7 (cid:35) 0.41 0 (cid:35) 109.31 (cid:35) (cid:220) ECDSA-mbedtls 0 (cid:35) – 0.54 0†‡ (cid:35) – 0.19 0 (cid:71)(cid:35) 467.11 50 (cid:35) 0.81 132 (cid:71)(cid:35) 314.26 (cid:71)(cid:35) 224.30 ECDSA-openssl 0 (cid:71)(cid:35) – 2252.36 1‡ (cid:71)(cid:35) 51. (cid:220) 0 (cid:71)(cid:35) 202.72 14 (cid:35) 1.22 28 (cid:35) 13.76 (cid:35) (cid:220) EdDSA-openssl 0 (cid:32) – (cid:220) 0‡ (cid:35) – 25.63 0 (cid:71)(cid:35) 59.87 0 (cid:35) 1.03 8 (cid:35) 9.86 (cid:71)(cid:35) (cid:220) X:thetoolcrashed.(cid:220):theanalysis(cid:71)(cid:35) timed-outafter3600s.†:thea(cid:32) nalysisterminatedearly(e(cid:71)(cid:35) .g.,unsupportedinstru(cid:71)(cid:35) ctions).‡:theanaly(cid:35) sisstartsfrom(cid:71)(cid:35) acore-dump (Binsec/Rel2only) 7.2 Resultsanddiscussion uponencounteringtwoconsecutivevulnerablememoryaccesses, Table2reports,foreachtool,therunningtimeoftheanalysis(T) theerrorreportingforonewill“shadow”theother.Thisisrelevant |
andthenumberofvulnerabilities(#V)foundwhenappropriate. inthisbenchmarkasMbedTLS’GHASHfunctionisimplemented WealsoreportincolumnSwhethertheanalysisfindstheoverall using64-bitintegerswhich,in32-bit,arecompiledintotwomovin- programissecure( ),insecure( )orifnostatementcanbemade structions.Wehavenotencounteredthisissueinotherbenchmarks. ( ).Asdynamicto(cid:32)olsonlymode(cid:35)lalimitednumberofexecutions, Forthelatter,thiscanbeexplainedbythefactthatMicroWalkdoes t(cid:71)(cid:35)heycanonlyreport and .Statictoolscanreport and , notreportCTviolationwheretheleakagequantifiedistoosmall, reporting whenthe(cid:35)analys(cid:71)(cid:35)istimesoutorstopsearly(cid:32)witho(cid:35)ut whereasothertoolswillreporttheseviolations.Second,inthe finding vu(cid:71)(cid:35)lnerabilities. For Binsec/Rel we also report the time OpenSSL’sEVPimplementationofAES-GCM,ctgrindreportsa requiredtofindafirstvulnerability(t). largenumberofvulnerabilitieswhileothertoolsdonot.ForBin- sec/Rel2,thisisunsurprisingasitsanalysisstopsuponreaching Symmetricprimitives.Forsimplersymmetriccryptographysuch unsupportedAES-NIinstructionsusedbytheEVPimplementation. asAES-CBCandauthenticatedschemeslikeAES-GCMorPoly1305- ThevulnerabilitiesreportedbyctgrindarealllocatedintheGHASH Chacha20,toolsthatreportanumberofvulnerabilitiestendtoagree implementation,whichemploystablelook-upstoperformmulti- witheachother.Ingeneral,thetoolsscalereasonablywellonsuch plicationsin𝐺𝐹(2128),apotentialvulnerabilityidentifiedin[78]. primitives.Implementationsusingconstant-timetechniquessuch asvectorpermutations(VP)orbit-slicing(BS)arereportedassecure Asymmetricprimitives.Inthecaseofmorecomplexasymmetric whilethosebasedontablelookups(T)yieldaconsistentnumberof cryptography,resultsvaryhighlybetweentools.ForAbacus,no vulnerabilities.dudectcandeterminethattheseimplementations vulnerabilitiesarefoundwhentheanalysisfinishes,however,we areinsecure,buttheOpenSSLT-tableimplementationasitpreloads observemultiplecrashes.AnalysesoftentimeoutonbothBin- tablesinthecachebeforeaccessingthem. sec/RelandBinsec/Rel2,onlyfindingahandfulofvulnerabili- Whilethesenumbersareconsistent,therearetwonotableex- ties.ForOpenSSLandMbedTLSthesevulnerabilitiesarelocated ceptions.First,ctgrindandMicroWalkshowlessvulnerabilities in BIGNUM conversion functions called before the target cryp- inMbedTLSAES-GCMimplementationthanothertools.Forthe tographicoperation.Suchfunctionshavebeenfoundtobevul- former,thisdiscrepancystemsfromabugwithinValgrind,where nerablebefore[131,142],weseeherethattheyarealsoasourceASystematicEvaluationofAutomatedToolsforSide-ChannelVulnerabilitiesDetectioninCryptographicLibraries CCS’23,November26–30,2023,Copenhagen,Denmark ofscalabilityissues.Fordudect,theneedtogenerateinputsfor issueisalleviatedinBinsec/Rel2thankstothechosenvalueopti- eachmeasurementisasignificantbottleneck,inparticularforRSA mization.Binsec/Rel2isabletofinishanalyzingsymmetricprim- wherekeygenerationisacostlyoperation.Asaresultofslowerkey itivesintimescomparabletoevendynamictaintingapproaches generationinMbedTLSandBearSSL,therespectiveRSAbench- likectgrind,findingthesamenumberofvulnerabilities.Whilescal- markstimeoutbeforefinishingasinglesetofmeasurements.Inthe abilityremainsanissueforasymmetricprimitives,Binsec/Rel2 caseofctgrind,analysesfinishesveryquickly,howeverthelarge isabletoanalyzetheOpenSSLimplementationofEd25519faster numberofvulnerabilitiesfoundmakesinterpretingtheseresults thanadynamicmethodlikeAbacus.Theabilitytostarttheanalysis complicated,withmostvulnerabilitiesbeingfoundinBIGNUM fromacoredumpsolvesinitializationissues(e.g.,globalfunction functions.MicroWalkprovidessimilarlyhighvulnerabilitycounts, pointers)thatcannotbeavoidedinBinsec/Rel,whilelimitingthe thoughwithanalysistimesintheorderofminutes. amountofinstrumentationrequired. Unsupportedinstructions.Unsupportedinstructionscanhave 8 Case-study:vulnerabilityvalidation acrucialimpactontheanalysi’results.ThevulnerableGHASH WenowemploythetoolsdescribedinSection6todetermineifthe implementationisrarelyreachedinpractice,asOpenSSLsteers vulnerabilitiesinSection5couldhavebeendiscoveredautomati- theexecutiontoconstant-timevariantsmakingusesofcarry-less cally(RQ2),anddeterminefeaturesthataremissingfromexisting multiplication(CLMUL)instructions.HoweverValgrindemulates frameworkstofindthem(RQ3). theresultsofcpuidtoonlyincludeinstructionsetsitsupports.Its analysisthusdoesnotreachtheCLMULimplementation,instead 8.1 Descriptionandsetup defaultingtoavulnerablefunction.Theresultsweobtainedwith Abacuscontrastwiththeauthors’ownRSAandECDSAbench- Targetedvulnerabilities.Weconsidervulnerabilitiesfromthree marks[20].Whiletheauthorsdidnotdisclosewhichconfigurations publications: [10] focused on RSA key generation in OpenSSL |
wereusedtocompilethelibraries,disassemblingtheirbenchmarks 1.0.2k, [61] focused on key format handling in OpenSSL 1.1.1a, showsthat,atleastforOpenSSL,assemblyimplementationswere andMbedTLS2.18.1(inparticularP256keysfortheformerand disabled.Suchimplementationsareincludedinourbenchmark, RSAkeysforthelatter,and[65]focusedonECDHdecryptionin yieldingSIMDinstructionsunsupportedbyAbacus.Whileinsome Libgcrypt1.7.6.Thefirsttwopapersdescribevulnerabilitiesstem- casesthesecauseAbacustocrash,itisalsopossibletheyleadto mingfromfunctionsknowntobevulnerable,butaccidentallyused under-tainting,explainingthelowvulnerabilitycounts. inanewcontext,whilethethirdonerepresentsanewvulnerability. Benchmarkdesign.WhileweareinterestedincheckingforCT Falsepositives.BothctgrindandBinsec/Rel2reportviolationsin violationsinthesevulnerablefunctions,alibrarydeveloperwithout RSA-bearsslandECDSA-bearssl,whichissurprisinggivenBearSSL priorknowledgeisunlikelytoanalyzetherightfunction(e.g.,GCD, constant-timepolicies.AcloserinspectionrevealsthattheRSA modularexponentiation).Morerealistically,suchdeveloperwould implementationcomputestheactualbitlengthofRSAprimesby instead check the larger context in which this function is used countingthenumberofnonzerobytes,triggeringsecret-dependent (e.g.,RSAkeygeneration).Assuch,weareinterestedindetecting control-flow, while ECDSA performs an early exit if the key is CTviolationsnotjustinthevulnerablefunctionitself,butalso notwell-defined.WhiletheseviolationsaretechnicallytrueCT initscallingcontext,wheredetectiontoolsmightstrugglewith violations,theyarenotexploitablevulnerabilities.MicroWalkon scalability,orotherusabilityissues.Wethusrunthedetectiontools theotherhanddoesnotreporttheseCTviolationsastheydonot onsimpleprogramscallingthevulnerablefunctionsdirectlyand resultindifferencesintracesfortheinputsweused.Inbothcases, thehigher-leveloperation. Binsec/Rel2 reports a subset of the vulnerabilities reported by ctgrind,whichcanbeexplainedbyadifferentnotionofunique Evaluationprotocol.Wecomparethenumberofvulnerabilities vulnerabilitybetweenbothtools.Indeed,Binsec/Rel2onlyreports andrunningtimesoftheanalysisfromBinsec/Rel2,Abacus,ct- asingleviolationwhenleakingthesamedataondifferentlocations, grindanddudectwiththeirconfigurationsfromSection7. whereasctgrindreportsmultiplelocationsleakingthesamedata. 8.2 Resultsanddiscussion Forprimitiveswithdynamicimplementationselection(i.e.,EVPand EdDSA-openssl),MicroWalkreports(likelyspurious)violationsin Table3reports,foreachtool,therunningtimeoftheanalysis(T) theinitialselectioncode,notreportedbyothertools.Finally,viola- andthenumberofvulnerabilities(#V)foundwhenavailable.Aba- tionsarereportedinRSAandECDSAimplementationsofOpenSSL cusreportvulnerabilitiesonlyuponfinishingtheanalysis,andthus andMbedTLS,howevertheseimplementationuseblinding,making reportsnonewhenthereisatimeout.Thehigher-leveloperations theviolationsunexploitableinpractice. arelistedinbold,whilethevulnerablefunctionsusedarelisted immediatelybelowthecorrespondingoperation. Leakagequantification.Wedidnotreportthenumbersgiven byAbacusandMicroWalk,asthereisnostandardwayofcomput- Generalresults.Ingeneral,Binsec/Rel2,ctgrind,anddudectre- ingleakagequantificationordeterminingtheirseverity.Moreover, portthesameprogramsassecure(i.e., P256signandRSAkeygen), leakagequantificationisfarfromapracticalnotionofexploitability, and the rest as insecure, with the exception of the modular re- asevenasinglebitofleakageorlesscanbeexploited[18]. ductioninLibgcrypt,forwhichBinsec/Rel2times-outwithout findingvulnerabilities.Incontrast,Abacusonlyreportsasingle ImprovementsoverBinsec/Rel.Binsec/Relmaystrugglesto programasinsecure.Thisispossiblyduetounsupportedinstruc- fullyanalyzeinsecureprograms,evensimpleroneslikeAES.This tions,onceagainlimitingthetoolabilitytoproperlytaintsecretCCS’23,November26–30,2023,Copenhagen,Denmark Geimeretal. Table3:Vulnerabilitydetection.V:whethertherightvulnerabilityisfound#V:numberofreportedvulnerabilities,S:status( secure; insecure; unknown),T:analysistimeinseconds. (cid:32) (cid:35) (cid:71)(cid:35) Binsec/Rel2 Abacus ctgrind MicroWalk dudect Benchmarks V #V S T(s) V #V S T(s) V #V S T(s) V #V S T(s) S T(s) P256sign(OpenSSL) 0 16.09 X 5.69 0 0.75 ✓ 33 71.44 – wNAFmultiplication 5 (cid:32) (cid:220) – (cid:71)(cid:35) (cid:220) ✓ 222 (cid:71)(cid:35) 0.54 ✓ 35 (cid:35) 62.55 (cid:71)(cid:35) 24.5 RSAvalid.(MbedTLS) 5 (cid:35) (cid:220) 0 (cid:71)(cid:35) 490.01 ✓ 31 (cid:35) 0.40 ✓ 41 (cid:35) 278.94 (cid:35) 2205.07 GCD 5 (cid:35) (cid:220) 0 (cid:71)(cid:35) 37.74 14 (cid:35) 0.21 ✓ 8 (cid:35) 22.96 (cid:35) 4.26 |
modularinversion 3 (cid:35) (cid:220) 0 (cid:71)(cid:35) 242.1 ✓ 19 (cid:35) 0.24 ✓ 17 (cid:35) 141.82 (cid:35) 17.7 RSAkeygen(OpenSSL) 0 (cid:35) 0.17 X (cid:71)(cid:35) 8.66 0 (cid:35) 6.36 ✓ 123 (cid:35) 842.02 (cid:35) – GCD ✓ 3 (cid:32) (cid:220) – (cid:71)(cid:35) (cid:220) 53 (cid:71)(cid:35) 0.19 ✓ 4 (cid:35) 3.61 (cid:71)(cid:35) 0.7 modularexponentiation 1 (cid:35) (cid:220) ✓ 4 (cid:71)(cid:35) 110.73 ✓ 6 (cid:35) 0.24 ✓ 25 (cid:35) 13.52 (cid:35) 6.96 modularinversion 1 (cid:35) (cid:220) – (cid:35) (cid:220) ✓ 115 (cid:35) 0.21 ✓ 15 (cid:35) 5.96 (cid:35) 1.69 ECDHdecryption(Libgcrypt) 2 (cid:35) (cid:220) 0 (cid:71)(cid:35) 386.76 ✓ 359 (cid:35) 1. 34 (cid:35) 146.50 (cid:35) 89.46 modularreduction 0 (cid:35) (cid:220) 0 (cid:71)(cid:35) 2.35 ✓ 9 (cid:35) 0.22 0 (cid:35) 1.59 (cid:35) 0.41 (cid:71)(cid:35) (cid:71)(cid:35) (cid:35) (cid:71)(cid:35) (cid:35) data.Additionally,theanalysiswilltimesoutinmultiplecases, thesecretappropriatelyandassuch,thedetectiontoolsweused returningnoresults.Theabilitytooutputviolationsassoonasthey cannotfindvulnerabilities.Inpractice,itispossibletomarksuch arefoundwould,thus,greatlyimproveusability.Ingeneral,we secretsbydeviatingfromoursetup.Forexample,theauthorsof findthatctgrindisabletofindmostrelevantvulnerabilitiesinboth Abacuswroteaspecialpintooltomarkthecryptographicnonceas thetargetfunctionsandtheircallingcontexts.Whiletherelevant secret,buttheirsolutionlacksgenerality.Anotheroptionistoadd vulnerabilitiescangenerallybefound,thehighnumberofreported annotationswithinlibrary’ssourcecode,somethingthatdevelopers vulnerabilitiescomplexifiestheinterpretationoftheseresults.We aregenerallyopposedto. notethatmostofthesevulnerabilitiesstemfromBIGNUMmanip- ulationfunctions.TheseCTviolationsareoftenalreadyknownby 9 Recommendations developers,andso,aspointedoutbyJancaretal.[74],theability Wenowformulaterecommendationstotheresearchcommunity toignoreviolationsinpartsofthecodewouldrepresentaclearus- andtocryptographiclibrarydevelopersbasedontheinsightsob- abilityimprovement.Contrastingwithctgrind,Binsec/Rel2found tainedwithourexperimentalevaluation. fewvulnerabilities.Wenotethattheanalysisoftengetsstuckearly intheprogram,duringBIGNUMconversionsteps,andtimesout. 9.1 Recommendationstoresearchcommunity Specifically,benchmarksinvolvingGCDcomputationsandmodular inversionaresusceptibletopathexplosion,acommonlimitation R1.SupportofSIMDinstructions.ResearchprototypeslikeAba- ofstaticSE,whichleadstounexploredprogrambehaviors. cusoftenonlysupportbasicx86instructions.However,asshown inSection7,librariesheavilyuseSIMDinstructionsets(e.g.,AVX2), Implicitflows.Implicitflowshappenwhenthevalueofavariable nowcommonlysupportedinCPUs.Theseimplementationsare maydifferdependingonsecret-dependentcontrolflow.Noneofthe nowtypicallyselectedinpriority.Assuch,supportingSIMDin- fourtoolsweconsidertracksimplicitinformationflows.Ourbench- structionsindetectiontoolsisnowcrucial,andevaluatingatoolon marksshowsthatignoringthemleadstoanunderestimationofthe implementationsspecificallyselectedtonotuseSIMDinstructions numbervulnerabilitiesincryptographicprograms.Forexample, maymisleaddevelopersonthetoolusability. MbedTLSimplementsacomparisonfunctioninwhichthereturn valuedependsonwhetherasecret-dependentbranchistaken(a R2.Supportofimplicitinformationflows.Futuretoolsshould typicalcaseofanimplicitflow).MbedTLSGCDfunctionusesthe investigatethepossibilityofdetectingCTviolationsstemmingfrom resultofthiscomparisonfunctionina(secret-dependent)condi- implicitinformationflows.Wearguethatbyignoringthem,ade- tionaljump.Asaresult,ctgrindonlyreportsthesecret-dependent tectiontoolcanunderestimatetheamountofvulnerabilities,giving branchinthecomparisonfunctionasvulnerable,butnottheonein developersafalsesenseofsecurity.Yet,consideringimplicitflows theGCDcomputation.WhileaCTviolationisstillreported,ade- ischallengingandcanimpactscalability.Onlythreetoolsexplicitly veloperisnotabletofullyappreciatehowvulnerabletheprogram supportimplicitflows[75,108,142],whiletrace-comparison-based iswithouttakingintoaccounttheseimplicitflows. dynamictoolsmightonlyprovideapartialsupport. Internalsecrets.Thewaythesecretisutilizedinsomeoperations R3.Supportofinternalsecrets.Thecommunityshouldinvesti- canposeproblemsfordetectiontools.ForRSAkeygeneration, gateside-channelvulnerabilitiesinoperationswherethesecretis thereisbydefinition,noinitialvaluestomarkassecret.ForP256 generatedinternally,suchaskeygenerationandPRNG[10,49,102]. signaturegeneration,thesecretexploitedinpublicationsisthe Yet,noneofthetoolsinourclassificationexplicitlysupportthem. |
cryptographicnoncegeneratedinternally.Otheroperationsmaking Recently,atestmethodologytodetectusageofvulnerablefunctions use of PRNG are also affected similarly. In both of these cases inkeygenerationwasproposed[69],howeveritrequiresknowing our “black-box” experimental setup does not allow us to mark vulnerablepointsinadvance.ASystematicEvaluationofAutomatedToolsforSide-ChannelVulnerabilitiesDetectioninCryptographicLibraries CCS’23,November26–30,2023,Copenhagen,Denmark R4.Supportforrandomization-baseddefense.Blindingintro- References ducesrandomizationduringcomputationstohinderinferenceof [1] [n.d.].BearSSL-Constant-TimeCrypto.https://bearssl.org/constanttime.html. secretsviaside-channels[76].Itposesanadditionalchallengefor [2] [n.d.].Bug200535-Valgrindflagslotsofuninitializedlocationswithprograms detectiontoolsastheleakagedoesdependonthesecret,butnotin compiledwith"-static".https://bugzilla.redhat.com/show_bug.cgi?id=200535. [3] [n.d.].ImplementdeterministicECDSAsign(RFC6979).https://github.com/ anexploitableway,leadingtofalsepositives.Only3outofthe34 openssl/openssl/pull/18809. toolsweconsideredinTable1supportblinding. [4] [n.d.].OpenSSL.https://www.openssl.org/. [5] O.Aciiçmez,S.Gueron,andJ.-P.Seifert.2007.NewBranchPredictionVulnera- R5.Usageofastandardizedbenchmark.Werecommendthe bilitiesinOpenSSLandNecessarySoftwareCountermeasures.InIMACC. [6] OnurAciiçmez,ÇetinKayaKoç,andJean-PierreSeifert.2007.PredictingSecret communitytoadoptastandardizedbenchmarkofcryptographic KeysViaBranchPrediction.InCT-RSA. implementations to evaluate side-channel detection tools. Such [7] JohanAgat.2000.TransformingOutTimingLeaks.InPOPL. benchmarkwouldfacilitatecomparingdetectiontoolstoonean- [8] MartinR.AlbrechtandKennethG.Paterson.2016. LuckyMicroseconds:A TimingAttackonAmazon’ss2nImplementationofTLS.InEUROCRYPT. other,inparticularintermsofusabilityandscalability.Wethereby [9] AlejandroCabreraAldaya,BillyBobBrumley,SohaibulHassan,CesarPereida proposetothecommunityourbenchmark,whichcanbereadily García,andNicolaTuveri.2019.PortContentionforFunandProfit.InS&P. [10] A.CabreraAldaya,C.PereidaGarcía,L.M.AlvarezTapia,andB.B.Brumley. adoptedandextendedinthefuture. 2019.Cache-TimingAttacksonRSAKeyGeneration.TCHES(2019). R6.Improveusability.AspointedoutinSection8,reportingre- [11] NadhemJ.AlFardanandKennethG.Paterson.2013.LuckyThirteen:Breaking theTLSandDTLSRecordProtocols.InS&P. sultsbeforetheanalysisendiscrucialforbenchmarksthattimes [12] J.BacelarAlmeida,M.Barbosa,G.Barthe,A.Blot,B.Grégoire,V.Laporte,T. out.Wealsoechoapointmadein[74]:beingabletoignorevulner- Oliveira,H.Pacheco,B.Schmidt,andP.-Y.Strub.2017.Jasmin:High-Assurance andHigh-SpeedCryptography.InCCS. abilitiesfromsomepartsofthecodehelpsinterpretingtheresults, [13] JoséBacelarAlmeida,ManuelBarbosa,GillesBarthe,FrançoisDupressoir,and particularlyforapproacheslikectgrind.Forstatictools,theability MichaelEmmi.2016.VerifyingConstant-TimeImplementations.InUSENIX. [14] J.BacelarAlmeida,M.Barbosa,G.Barthe,B.Grégoire,A.Koutsos,V.Laporte,T. towritestubsaddinglimitedsupportforsystemcallsanddynamic Oliveira,andP-Y.Strub.2020.TheLastMile:High-AssuranceandHigh-Speed allocationwasessentialinourexperimentswithBinsec/Rel,as CryptographicImplementations.InS&P. wecannotexpectdeveloperstoavoidusingthem.Theabilityto [15] J.BacelarAlmeida,M.Barbosa,J.SousaPinto,andB.Vieira.2013.Formalveri- ficationofside-channelcountermeasuresusingself-composition.Sci.Comput. starttheanalysisfromacoredump(asinBinsec/Rel2)alsogreatly Program.(2013). simplifiestheinstrumentationneededtoinitializetheanalysis. [16] M.Andrysco,D.Kohlbrenner,K.Mowery,R.Jhala,S.Lerner,andH.Shacham. 2015.OnSubnormalFloatingPointandAbnormalTiming.InS&P. 9.2 Recommendationstodevelopers [17] TimosAntonopoulos,PaulGazzillo,MichaelHicks,EricKoskinen,TachioTer- auchi,andShiyiWei.2017. Decompositioninsteadofself-compositionfor R7.Makelibrariesmoreanalysisfriendly.Staticanalysistools provingtheabsenceoftimingchannels.InPLDI. [18] D.F.Aranha,F.RodriguesNovaes,A.Takahashi,M.Tibouchi,andY.Yarom. oftenrequiremoreinstrumentationthandynamicones.Inparticu- 2020.LadderLeak:BreakingECDSAwithLessthanOneBitofNonceLeakage. lar,runtimeimplementationselection(e.g.,EVP)posesachallenge. InCCS. [19] KonstantinosAthanasiou,ByronCook,MichaelEmmi,ColmMacCárthaigh, WhileforexperimentsusingBinsec/Rel2wewereabletobypass DanielSchwartz-Narbonne,andSerdarTasiran.2018.SideTrail:VerifyingTime- thisissuebyinitializingthememoryfromacoredump,wecanonly BalancingofCryptosystems.InVSTTE. [20] QinkunBao,ZihaoWang,XiaotingLi,JamesR.Larus,andDinghaoWu.2021. |
analyzeoneimplementationandhavelittlecontroloverwhichone Abacus:PreciseSide-ChannelAnalysis.InICSE. ischosen.WerecommendthatlibrariesexposeintheirAPI,atleast [21] M.Barbosa,G.Barthe,K.Bhargavan,B.Blanchet,C.Cremers,K.Liao,andB. fortestingpurposes,functionstodirectlycalldifferentimplemen- Parno.2021.SoK:Computer-AidedCryptography.InS&P. [22] G.Barthe,G.Betarte,J.DiegoCampo,C.DanielLuna,andD.Pichardie.2014. tations,asdoneforexamplebyOpenSSLAESimplementations. System-levelNon-interferenceforConstant-timeCryptography.InCCS. [23] GillesBarthe,PedroR.D’Argenio,andTamaraRezk.2011.Secureinformation 10 Conclusion flowbyself-composition.Math.Struct.Comput.Sci.21,6(2011),1207–1252. [24] N.Benger,J.vandePol,N.P.Smart,andY.Yarom.2014. "OohAah...Justa Wesurveyedandclassifiedstate-of-the-artside-channeldetection LittleBit":ASmallAmountofSideChannelCanGoaLongWay.InCHES. [25] DanielJBernstein.2005.Cache-TimingAttacksonAES. tools,andproposeaunifiedbenchmarkallowingfairexperimental [26] DanielJ.Bernstein,TanjaLange,andPeterSchwabe.2012.TheSecurityImpact comparison.Ourfindingsshowthatexistingtoolscanstillstruggle ofaNewCryptographicLibrary.InLATINCRYPT. toanalyzecomplexprimitivesandcanmiss vulnerabilities.We [27] BinsecRel2.2023.BinsecRel2.https://binsec.github.io/releases/binsec/2023/02/ 14/binsec-0.7.1.html. issuedrecommendationsfortheresearchanddevelopercommunity [28] SandrineBlazy,DavidPichardie,andAlixTrieu.2017.VerifyingConstant-Time toimproveexistingtoolsandencouragetheirusage. ImplementationsbyAbstractInterpretation.InESORICS. Beyondtheserecommendationswenotethattheresearchcom- [29] DanielBleichenbacher.1998. ChosenCiphertextAttacksAgainstProtocols BasedontheRSAEncryptionStandardPKCS#1.InCRYPTO. munitiesformicroarchitecturalandphysicalside-channeldetec- [30] B.Bond,C.Hawblitzel,M.Kapritsos,K.R.M.Leino,J.R.Lorch,B.Parno,A. tionbothevolvedindependently,withlittleoverlap[39].Withthe Rane,S.T.V.Setty,andL.Thompson.2017.Vale:VerifyingHigh-Performance CryptographicAssemblyCode.InUSENIXSecurity. adventoffrequencyscalingside-channelslikeHertzbleed[130] [31] PietroBorrello,DanieleConoD’Elia,LeonardoQuerzoni,andCristianoGiuf- extractingatimingside-channelfrompowerconsumption,this frida.2021.Constantine:AutomaticSide-ChannelResistanceUsingEfficient boundaryisblurred.Toproperlyaddresssuchvulnerabilities,the ControlandDataFlowLinearization.InCCS. [32] D.DeAlmeidaBraga,P.-A.Fouque,andM.Sabt.2020. DragonbloodisStill twocommunitiesshouldfocusonbridgingthegapbetweenthem, Leaking:PracticalCache-basedSide-ChannelintheWild.InACSAC. borrowinginsightsfromphysicalside-channeldetectionandmove [33] D.DeAlmeidaBraga,P.-A.Fouque,andM.Sabt.2021.PARASITE:PAssword beyondtheconstant-timemodel. RecoveryAttackagainstSrpImplementationsinThEwild.InCCS. [34] TeganBrennan,SeemantaSaha,TevfikBultan,andCorinaS.Pasareanu.2018. Symbolicpathcostanalysisforside-channeldetection.InISSTA. Acknowledgments [35] RobertBrotzman,ShenLiu,DanfengZhang,GangTan,andMahmutT.Kandemir. 2019. CaSym:CacheAwareSymbolicExecutionforSideChannelDetection ThisworkbenefitedfromthesupportoftheANR-19-CE39-0007 andMitigation.InS&P. MIAOUS,ANR-20-CE25-0009TAVAandPEPRPPSecurevalprojects.CCS’23,November26–30,2023,Copenhagen,Denmark Geimeretal. [36] B.B.BrumleyandR.M.Hakala.2009. Cache-TimingTemplateAttacks.In [69] I.Gridin,C.PereidaGarcía,N.Tuveri,andB.B.Brumley.2019. Triggerflow: ASIACRYPT. RegressionTestingbyAdvancedExecutionPathInspection.InDIMVA. [37] BillyBobBrumleyandNicolaTuveri.2011.RemoteTimingAttacksAreStill [70] JohannGroßschädl,ElisabethOswald,DanPage,andMichaelTunstall.2009. Practical.InESORICS. Side-ChannelAnalysisofCryptographicSoftwareviaEarly-TerminatingMulti- [38] DavidBrumleyandDanBoneh.2005. Remotetimingattacksarepractical. plications.InICISC. Comput.Networks48,5(2005),701–716. [71] D.Gruss,R.Spreitzer,andS.Mangard.2015.CacheTemplateAttacks:Automat- [39] IleanaBuhan,LejlaBatina,YuvalYarom,andPatrickSchaumont.2022. SoK: ingAttacksonInclusiveLast-LevelCaches.InUSENIXSecurity. DesignToolsforSide-Channel-AwareImplementations.InAsiaCCS. [72] QianGuo,ThomasJohansson,andAlexanderNilsson.2020.AKey-Recovery [40] JoVanBulck,FrankPiessens,andRaoulStrackx.2017.SGX-Step:APractical TimingAttackonPost-quantumPrimitivesUsingtheFujisaki-OkamotoTrans- AttackFrameworkforPreciseEnclaveExecutionControl.InSysTEX@SOSP. formationandItsApplicationonFrodoKEM.InCRYPTO. [41] C.Cadar,D.Dunbar,andD.R.Engler.2008.KLEE:UnassistedandAutomatic [73] ShaoboHe,MichaelEmmi,andGabrielaF.Ciocarlie.2020.ct-fuzz:Fuzzingfor |
GenerationofHigh-CoverageTestsforComplexSystemsPrograms.InOSDI. TimingLeaks.InICST. [42] CristianCadarandKoushikSen.2013.Symbolicexecutionforsoftwaretesting: [74] JanJancar,MarcelFourné,DanielDeAlmeidaBraga,MohamedSabt,Peter threedecadeslater.Commun.ACM56,2(2013),82–90. Schwabe,GillesBarthe,Pierre-AlainFouque,andYaseminAcar.2022."They’re [43] GiovanniCamurati,SebastianPoeplau,MariusMuench,TomHayes,andAu- notthathardtomitigate":WhatCryptographicLibraryDevelopersThinkAbout rélienFrancillon.2018.ScreamingChannels:WhenElectromagneticSideChan- TimingAttacks.InS&P. nelsMeetRadioTransceivers.InCCS. [75] K.Jiang,Y.Bao,S.Wang,Z.Liu,andT.Zhang.2022.CacheRefinementType [44] C.Canella,J.VanBulck,M.Schwarz,M.Lipp,B.vonBerg,P.Ortner,F.Piessens, forSide-ChannelDetectionofCryptographicSoftware.InCCS. D.Evtyushkin,andD.Gruss.2019. ASystematicEvaluationofTransient [76] MarcJoyeandChristopheTymen.2001.ProtectionsagainstDifferentialAnalysis ExecutionAttacksandDefenses.InUSENIXSecurity. forEllipticCurveCryptography.InCHES. [45] C.Canella,D.Genkin,L.Giner,D.Gruss,M.Lipp,M.Minkin,D.Moghimi, [77] M.JoyeandS-MYen.2002.TheMontgomeryPoweringLadder.InCHES. F.Piessens,M.Schwarz,B.Sunar,J.VanBulck,andY.Yarom.2019. Fallout: [78] EmiliaKäsperandPeterSchwabe.2009.FasterandTiming-AttackResistant LeakingDataonMeltdown-resistantCPUs.InCCS. AES-GCM.InCHES. [46] SunjayCauligi,GarySoeller,BrianJohannesmeyer,FraserBrown,RiadS.Wahby, [79] Thierry Kaufmann, Hervé Pelletier, Serge Vaudenay, and Karine Villegas. JohnRenner,BenjaminGrégoire,GillesBarthe,RanjitJhala,andDeianStefan. 2016. WhenConstant-TimeSourceYieldsVariable-TimeBinary:Exploiting 2019.FaCT:aDSLfortiming-sensitivecomputation.InPLDI. Curve25519-donnaBuiltwithMSVC2015.InCANS. [47] S.ChattopadhyayandA.Roychoudhury.2018.SymbolicVerificationofCache [80] TaesooKim,MarcusPeinado,andGloriaMainar-Ruiz.2012.STEALTHMEM: Side-ChannelFreedom.Trans.Comput.AidedDes.Integr.CircuitsSyst.(2018). System-LevelProtectionAgainstCache-BasedSideChannelAttacksinthe [48] JiaChen,YuFeng,andIsilDillig.2017. PreciseDetectionofSide-Channel Cloud.InUSENIXSecurity. VulnerabilitiesusingQuantitativeCartesianHoareLogic.InCCS. [81] Y.Kim,R.Daly,J.S.Kim,C.Fallin,J-HLee,D.Lee,C.Wilkerson,K.Lai,andO. [49] S.Cohney,A.Kwong,S.Paz,D.Genkin,N.Heninger,E.Ronen,andY.Yarom. Mutlu.2014.Flippingbitsinmemorywithoutaccessingthem:Anexperimental 2020.PseudorandomBlackSwans:CacheAttacksonCTR_DRBG.InS&P. studyofDRAMdisturbanceerrors.InISCA. [50] PatrickCousotandRadhiaCousot.1977. AbstractInterpretation:AUnified [82] J.C.King.1976. SymbolicExecutionandProgramTesting. Commun.ACM LatticeModelforStaticAnalysisofProgramsbyConstructionorApproximation (1976)(1976). ofFixpoints.InPOPL. [83] PaulC.Kocher.1996.TimingAttacksonImplementationsofDiffie-Hellman, [51] L.-A.Daniel,S.Bardin,andT.Rezk.2020. Binsec/Rel:EfficientRelational RSA,DSS,andOtherSystems.InCRYPTO. SymbolicExecutionforConstant-TimeatBinary-Level.InS&P. [84] P.C.Kocher,J.Jaffe,andB.Jun.1999.DifferentialPowerAnalysis.InCRYPTO. [52] Lesly-AnnDaniel,SébastienBardin,andTamaraRezk.2022.Binsec/Rel:Sym- [85] BorisKöpfandHeikoMantel.2007.Transformationaltypingandunification bolicBinaryAnalyzerforSecuritywithApplicationstoConstant-Timeand forautomaticallycorrectinginsecureprograms.Int.J.Inf.Sec.(2007). Secret-Erasure.ACMTransactionsonPrivacyandSecurity(2022). [86] AdamLangley.2010. Ctgrind. https://www.imperialviolet.org/2010/04/01/ [53] DorothyE.DenningandPeterJ.Denning.1977.CertificationofProgramsfor ctgrind.html. SecureInformationFlow.Commun.ACM20,7(1977),504–513. [87] SanghoLee,Ming-WeiShih,PrasunGera,TaesooKim,HyesoonKim,and [54] C.Disselkoen,S.Cauligi,D.Tullsen,andD.Stefan.2020.FindingandEliminating MarcusPeinado.2017.InferringFine-grainedControlFlowInsideSGXEnclaves TimingSide-ChannelsinCryptoCodewithPitchfork.InTECHCON. withBranchShadowing.InUSENIXSecurity. [55] G.Doychev,D.Feld,B.Köpf,L.Mauborgne,andJ.Reineke.2013.CacheAudit: [88] ChenLiu,AbhishekChakraborty,NikhilChawla,andNeerRoggel.2022.Fre- AToolfortheStaticAnalysisofCacheSideChannels.InUSENIXSecurity. quencyThrottlingSide-ChannelAttack.InCCS. [56] GoranDoychevandBorisKöpf.2017.Rigorousanalysisofsoftwarecounter- [89] FangfeiLiu,YuvalYarom,QianGe,GernotHeiser,andRubyB.Lee.2015.Last- measuresagainstcacheattacks.InPLDI. LevelCacheSide-ChannelAttacksarePractical.InS&P. |
[57] DmitryEvtyushkin,RyanRiley,NaelB.Abu-Ghazaleh,andDmitryPonomarev. [90] XiaoxuanLou,TianweiZhang,JunJiang,andYinqianZhang.2022.ASurvey 2018.BranchScope:ANewSide-ChannelAttackonDirectionalBranchPredictor. ofMicroarchitecturalSide-channelVulnerabilities,Attacks,andDefensesin InASPLOS. Cryptography.ACMComput.Surv.54,6(2022),122:1–122:37. [58] TrustedFirmware.[n.d.].MbedTLS.https://www.trustedfirmware.org/projects/ [91] C-KLuk,R.S.Cohn,R.Muth,H.Patil,A.Klauser,P.GeoffreyLowney,S.Wallace, mbed-tls/. V.JanapaReddi,andK.M.Hazelwood.2005.Pin:buildingcustomizedprogram [59] CRoCS:CentreforResearchonCryptographyandSecurity.[n.d.].Constant- analysistoolswithdynamicinstrumentation.(2005). timenessverificationtools.https://crocs-muni.github.io/ct-tools/. [92] HeikoMantel,AlexandraWeber,andBorisKöpf.2017.ASystematicStudyof [60] CesarPereidaGarcíaandBillyBobBrumley.2017.Constant-TimeCalleeswith CacheSideChannelsAcrossAESImplementations.InESSoS. Variable-TimeCallers.InUSENIXSecurity. [93] ThomasS.Messerges.2000.SecuringtheAESFinalistsAgainstPowerAnalysis [61] C.PereidaGarcía,S.ulHassan,N.Tuveri,I.Gridin,A.CabreraAldaya,andB.B. Attacks.InFSE. Brumley.2020.CertifiedSideChannels.InUSENIXSecurity. [94] DavidMolnar,MattPiotrowski,DavidSchultz,andDavidA.Wagner.2005. [62] QianGe,YuvalYarom,DavidCock,andGernotHeiser.2018.Asurveyofmicroar- TheProgramCounterSecurityModel:AutomaticDetectionandRemovalof chitecturaltimingattacksandcountermeasuresoncontemporaryhardware.J. Control-FlowSideChannelAttacks.InICISC. Cryptogr.Eng.8,1(2018),1–27. [95] M.Nemec,D.Klinec,P.Svenda,P.Sekan,andV.Matyas.2017. Measuring [63] Antoine Geimer, Mathéo Vergnolle, Frédéric Recoules, Lesly-Ann Daniel, PopularityofCryptographicLibrariesinInternet-WideScans.InACSAC. SébastienBardin,andClémentineMaurice.2023.ASystematicEvaluationof [96] ShirinNilizadeh,YannicNoller,andCorinaS.Pasareanu.2019.DifFuzz:differ- AutomatedToolsforSide-ChannelVulnerabilitiesDetectioninCryptographic entialfuzzingforside-channelanalysis.InICSE. Libraries(EvaluationFramework).https://TODO/. [97] ColinPercival.2005.CacheMissingforFunandProfit.InBSDCan. [64] DanielGenkin,AdiShamir,andEranTromer.2014. RSAKeyExtractionvia [98] P.Pessl,L.GrootBruinderink,andY.Yarom.2017. ToBLISS-Bornottobe: Low-BandwidthAcousticCryptanalysis.InCRYPTO. AttackingstrongSwan’sImplementationofPost-QuantumSignatures.InCCS. [65] DanielGenkin,LukeValenta,andYuvalYarom.2017. MaytheFourthBe [99] P.Pessl,D.Gruss,C.Maurice,M.Schwarz,andS.Mangard.2016. DRAMA: WithYou:AMicroarchitecturalSideChannelAttackonSeveralReal-World ExploitingDRAMAddressingforCross-CPUAttacks.InUSENIXSecurity. ApplicationsofCurve25519.InCCS. [100] ThomasPornin.[n.d.].BearSSL.https://bearssl.org/. [66] JovanDj.GolicandChristopheTymen.2002.MultiplicativeMaskingandPower [101] J.Protzenko,B.Parno,A.Fromherz,C.Hawblitzel,M.Polubelova,K.Bhar- AnalysisofAES.InCHES. gavan,B.Beurdouche,J.Choi,A.Delignat-Lavaud,C.Fournet,N.Kulatova, [67] B.Gras,C.Giuffrida,M.Kurth,H.Bos,andK.Razavi.2020.ABSynthe:Automatic T.Ramananandro,A.Rastogi,N.Swamy,C.M.Wintersteiger,andS.Zanella BlackboxSide-channelSynthesisonCommodityMicroarchitectures.InNDSS. Béguelin.2020. EverCrypt:AFast,Verified,Cross-PlatformCryptographic [68] BenGras,KavehRazavi,HerbertBos,andCristianoGiuffrida.2018.Translation Provider.InS&P. Leak-asideBuffer:DefeatingCacheSide-channelProtectionswithTLBAttacks. [102] I.Puddu,M.Schneider,M.Haller,andS.Capkun.2021.FrontalAttack:Leaking InUSENIXSecurity. Control-FlowinSGXviatheCPUFrontend.InUSENIXSecurity.ASystematicEvaluationofAutomatedToolsforSide-ChannelVulnerabilitiesDetectioninCryptographicLibraries CCS’23,November26–30,2023,Copenhagen,Denmark [103] A.Purnal,L.Giner,D.Gruss,andI.Verbauwhede.2021.SystematicAnalysisof [137] YuanXiao,MengyuanLi,SanchuanChen,andYinqianZhang.2017.STACCO: Randomization-basedProtectedCacheArchitectures.InS&P. DifferentiallyAnalyzingSide-ChannelTracesforDetectingSSL/TLSVulnera- [104] HanyRagab,EnricoBarberis,HerbertBos,andCristianoGiuffrida.2021.Rage bilitiesinSecureEnclaves.InCCS. AgainsttheMachineClear:ASystematicAnalysisofMachineClearsandTheir [138] YuanzhongXu,WeidongCui,andMarcusPeinado.2015.Controlled-Channel ImplicationsforTransientExecutionAttacks.InUSENIXSecurity. Attacks:DeterministicSideChannelsforUntrustedOperatingSystems.InS&P. |
[105] AshayRane,CalvinLin,andMohitTiwari.2015. Raccoon:ClosingDigital [139] YuvalYaromandNaomiBenger.2014.RecoveringOpenSSLECDSANonces Side-ChannelsthroughObfuscatedExecution.InUSENIXSecurity. UsingtheFLUSH+RELOADCacheSide-channelAttack. IACRCryp.ePrint [106] JosyulaR.RaoandPankajRohatgi.2001.EMpoweringSide-ChannelAttacks. (2014). IACRCryptol.ePrintArch.(2001). http://eprint.iacr.org/2001/037 [140] YuvalYaromandKatrinaFalkner.2014.FLUSH+RELOAD:AHighResolution, [107] O.Reparaz,J.Balasch,andI.Verbauwhede.2017.Dude,ismycodeconstant LowNoise,L3CacheSide-ChannelAttack.InUSENIXSecurity. time?.InDATE. [141] T.Yavuz,F.Fowze,G.Hernandez,K.Y.Bai,K.Butler,andD.J.Tian.2022. [108] B.Rodrigues,F.MagnoQuintãoPereira,andD.F.Aranha.2016. Sparserep- ENCIDER:DetectingTimingandCacheSideChannelsinSGXEnclavesand resentationofimplicitflowswithapplicationstoside-channeldetection.In CryptographicAPIs.TransactionsonDependableandSecureComputing(2022). CC. [142] Y.Yuan,Z.Liu,andS.Wang.2023.CacheQL:QuantifyingandLocalizingCache [109] E.Ronen,R.Gillham,D.Genkin,A.Shamir,D.Wong,andY.Yarom.2019.The Side-ChannelVulnerabilitiesinProductionSoftware.InUSENIXSecurity. 9LivesofBleichenbacher’sCAT:NewCacheATtacksonTLSImplementations. [143] YuanyuanYuan,QiPang,andShuaiWang.2022. AutomatedSideChannel InS&P. AnalysisofMediaSoftwarewithManifoldLearning.InUSENIXSecurity. [110] EyalRonen,KennethG.Paterson,andAdiShamir.2018.PseudoConstantTime [144] TaoZhang,TimothyLesch,KennethKoltermann,andDmitryEvtyushkin.2022. ImplementationsofTLSAreOnlyPseudoSecure.InCCS. STBPU:AReasonablySecureBranchPredictionUnit.InDSN. [111] AlexanderSchaub.2020.Formalmethodsfortheanalysisofcache-timingleaks [145] J.K.Zinzindohoué,K.Bhargavan,J.Protzenko,andB.Beurdouche.2017.HACL*: andkeygenerationincryptographicimplementations.Ph.D.Dissertation.Institut AVerifiedModernCryptographicLibrary.InCCS. PolytechniquedeParis. https://theses.hal.science/tel-03205242 [112] M.Schwarz,S.Weiser,D.Gruss,C.Maurice,andS.Mangard.2017.Malware GuardExtension:UsingSGXtoConcealCacheAttacks.InDIMVA. [113] MartinSchwarzl,ErikKraft,andDanielGruss.2023.LayeredBinaryTemplating: EfficientDetectionofCompiler-andLinker-introducedLeakage.InACNS. [114] JulianSewardandNicholasNethercote.2005.UsingValgrindtoDetectUnde- finedValueErrorswithBit-Precision.InUSENIXATC. [115] Y-jShin,H.ChanKim,D.Kwon,J-HJeong,andJ.Hur.2018.UnveilingHardware- basedDataPrefetcher,aHiddenSourceofInformationLeakage.InCCS. [116] LaurentSimon,DavidChisnall,andRossJ.Anderson.2018.WhatYouGetis WhatYouC:ControllingSideEffectsinMainstreamCCompilers.InEuroS&P. [117] LuigiSoaresandFernandoMagnoQuintãoPereira.2021.Memory-SafeElimi- nationofSideChannels.InCGO.IEEE,200–210. [118] ChunghaSung,BrandonPaulsen,andChaoWang.2018. CANAL:acache timinganalysisframeworkviaLLVMtransformation.InASE. [119] JakubSzefer.2019. SurveyofMicroarchitecturalSideandCovertChannels, Attacks,andDefenses.J.Hardw.Syst.Secur.3,3(2019),219–234. [120] M.TibouchiandA.Wallet.2021.OneBitisAllItTakes:ADevastatingTiming AttackonBLISS’sNon-ConstantTimeSignFlips.J.Math.Cryptol.(2021). [121] N.Tuveri,S.ulHassan,C.PereidaGarcía,andB.B.Brumley.2018.Side-Channel AnalysisofSM2:ALate-StageFeaturizationCaseStudy.InACSAC. [122] ReiUenoandNaofumiHomma.2023.HowSecureIsExponent-blindedRSA- CRTwithSlidingWindowExponentiation?TCHES(2023). [123] S. ul Hassan, I. Gridin, I. M. Delgado-Lozano, C. Pereida García, J-J Chi- Domínguez,A.CabreraAldaya,andB.B.Brumley.2020.DéjàVu:Side-Channel AnalysisofMozilla’sNSS.InCCS. [124] JoVanBulck.2020.MicroarchitecturalSide-channelAttacksforPrivilegedSoft- wareAdversaries.Ph.D.Dissertation.KULeuven. [125] J.VanBulck,D.Moghimi,M.Schwarz,M.Lipp,M.Minkin,D.Genkin,Y.Yarom, B.Sunar,D.Gruss,andF.Piessens.2020.LVI:HijackingTransientExecution throughMicroarchitecturalLoadValueInjection.InS&P. [126] MathyVanhoefandEyalRonen.2020.Dragonblood:AnalyzingtheDragonfly HandshakeofWPA3andEAP-pwd.InS&P. [127] ShuaiWang,YuyanBao,XiaoLiu,PeiWang,DanfengZhang,andDinghao Wu.2019.IdentifyingCache-BasedSideChannelsthroughSecret-Augmented AbstractInterpretation.InUSENIXSecurity. [128] S.Wang,P.Wang,X.Liu,D.Zhang,andD.Wu.2017. CacheD:Identifying Cache-BasedTimingChannelsinProductionSoftware.InUSENIXSecurity. [129] W.Wang,Y.Zhang,andZ.Lin.2019.TimeandOrder:TowardsAutomatically IdentifyingSide-ChannelVulnerabilitiesinEnclaveBinaries.InRAID. |
[130] Y.Wang,R.Paccagnella,E.TangHe,H.Shacham,C.W.Fletcher,andD.Kohlbren- ner.2022.Hertzbleed:TurningPowerSide-ChannelAttacksIntoRemoteTiming Attacksonx86.InUSENIXSecurity. [131] SamuelWeiser,DavidSchrammel,LukasBodner,andRaphaelSpreitzer.2020. BigNumbers-BigTroubles:SystematicallyAnalyzingNonceLeakagein (EC)DSAImplementations.InUSENIXSecurity. [132] SamuelWeiser,RaphaelSpreitzer,andLukasBodner.2018.SingleTraceAttack AgainstRSAKeyGenerationinIntelSGXSSL.InAsiaCCS. [133] SamuelWeiser,AndreasZankl,RaphaelSpreitzer,KatjaMiller,StefanMangard, andGeorgSigl.2018. DATA-DifferentialAddressTraceAnalysis:Finding Address-basedSide-ChannelsinBinaries.InUSENIXSecurity. [134] JanWichelmann,AhmadMoghimi,ThomasEisenbarth,andBerkSunar.2018. MicroWalk:AFrameworkforFindingSideChannelsinBinaries.InACSAC. [135] J.Wichelmann,F.Sieck,A.Pätschke,andT.Eisenbarth.2022.Microwalk-CI: PracticalSide-ChannelAnalysisforJavaScriptApplications.InCCS. [136] MengWu,ShengjianGuo,PatrickSchaumont,andChaoWang.2018.Eliminat- ingtimingside-channelleaksusingprogramrepair.InISSTA. |
2310.08275 Harnessing the Power of LLM to Support Binary Taint Analysis PuzhuoLiu ChengnianSun YaowenZheng InstituteofInformationEngineering, SchoolofComputerScience, NanyangTechnologicalUniversity ChineseAcademyofSciences UniversityofWaterloo Singapore SchoolofCyberSecurity,University Waterloo,Ontario,Canada yaowen.zheng@ntu.edu.sg ofChineseAcademyofSciences cnsun@uwaterloo.ca Beijing,China liupuzhuo@iie.ac.cn XuanFeng ChuanQin YunchengWang MicrosoftResearch InstituteofInformationEngineering, InstituteofInformationEngineering, China ChineseAcademyofSciences ChineseAcademyofSciences xuanfeng@microsoft.com SchoolofCyberSecurity,University SchoolofCyberSecurity,University ofChineseAcademyofSciences ofChineseAcademyofSciences Beijing,China Beijing,China qinchuan@iie.ac.cn wangyuncheng@iie.ac.cn ZhiLi LiminSun InstituteofInformationEngineering, InstituteofInformationEngineering, ChineseAcademyofSciences ChineseAcademyofSciences SchoolofCyberSecurity,University SchoolofCyberSecurity,University ofChineseAcademyofSciences ofChineseAcademyofSciences Beijing,China Beijing,China lizhi@iie.ac.cn sunlimin@iie.ac.cn ABSTRACT Toreducetheimpactofvulnerabilitiesinreleasedbinariessuch ThispaperproposesLATTE,thefirststaticbinarytaintanalysisthat asfirmwareofembeddeddevices[8,9,44,59]andcommercialsoft- ispoweredbyalargelanguagemodel(LLM).LATTEissuperiorto wareapplications[4,21,39,50],third-partysecurityauditsemerged thestateoftheart(e.g.,Emtaint,Arbiter,Karonte)inthreeaspects. asanindispensableforce.Theseaudits,conductedbyentitieswith- First,LATTEisfullyautomatedwhilepriorstaticbinarytaintana- out access to the source code, apply various post-development lyzersneedrelyonhumanexpertisetomanuallycustomizetaint analysis[9,30,42,58]andtestingtechniques[8,44,50,59]directly propagationrulesandvulnerabilityinspectionrules.Second,LATTE onthereleasedbinarieswhichareusuallystrippedofdebuginfor- issignificantlyeffectiveinvulnerabilitydetection,demonstratedby mationandsymboltables. ourcomprehensiveevaluations.Forexample,LATTEhasfound37 Taint analysis is suitable. Among these techniques, static newbugsinreal-worldfirmwarewhichthebaselinesfailedtofind, binarytaintanalysis(referredtoastaintanalysisforbrevityin and7ofthemhavebeenassignedCVEnumbers.Lastly,LATTE thispaper)standsoutasaneffectiveapproachforvulnerability incursremarkablylowengineeringcost,makingitacost-efficient inspection.Itcandirectlyanalyzebinarieswithseveraladvantages, andscalablesolutionforsecurityresearchersandpractitioners.We including high test code coverage, independence from the con- stronglybelievethatLATTEopensupanewdirectiontoharness creteexecutionenvironmentofbinaries,andtheabilitytodiscover therecentadvanceinLLMstoimprovevulnerabilityanalysisfor previouslyunknownexploitablevulnerabilities[8,44,50]. binaryprograms. Thestandardtaintanalysisworkflowcomprisesthreesteps. 1 IdentifyingTaintSources:Taintsourcesareexternalinputthatcould potentiallybemanipulatedbyanattacker.Thesesourcesareusually functionsthatreceiveexternaldata.Forexample,thefunctionrecv 1 INTRODUCTION readsdatathroughasocket,getenvretrievesinformationfroman Binarytestingisnecessary. Fordecades,softwaretestinghas environmentvariable,andfgetsloadsdatafromafile. 2 Propagat- remainedthedominantmethodforsoftwarequalityassurance,pri- ingTaintLabels:Initially,theexternaldatareceivedthroughtaint marilyduetoitscost-effectiveness.However,asEdsgerDijkstra sourcesarelabeledtainted.Thentheanalysistracestheflowof emphasized [14], software testing can only reveal the presence thetainteddatathroughtheprogram;itpropagatesthetaintlabels ofbugs,nottheirabsence.Consequently,itisnotuncommonto alongdatadependencies,suchasassignments,computations,and encounterbugsinreleasedbinaries[46,50].Certainbugscanbe functioncalls,todiscoverhowthetainteddataspreadsthroughout particularlycriticalandmaybeexploitedasvulnerabilitiestoini- theprogram.Meanwhile,ifamemoryregionwithataintlabel tiatecyberattacks,e.g.,unauthorizedaccesstosystems,stealing isoverwrittenwithuntainteddataortheregionissanitizedwith sensitivedata,anddisruptingnormalsystemoperations[3,25]. 3202 tcO 21 ]RC.sc[ 1v57280.0132:viXraConference’17,July2017,Washington,DC,USA PuzhuoLiu,etal. certain checks, then the taint label is removed from that mem- codecontext:Toconductaccuratevulnerabilityanalysis,having oryregion. 3 IdentifyingandInspectingSinks:Sinksarepotential adequatecodecontext,includingfunctioncallstacks,datadepen- pointsintheprogramwheretainteddatamightbemisusedorlead dencies,andcontrolflow,iscrucialtodeterminewhetherapieceof tosecurityvulnerabilities.Theyareusuallysensitiveoperations codeisvulnerable.However,mostLLMscurrentlyacceptonlyalim- includingmanipulatingstrings(e.g.,strcpy,strcat),executing itedamountofcontext,strikingabalancebetweencomputational commands (e.g., system, execl), and formatted outputting (e.g., costsandresponsequality.Forexample,thestate-of-the-artLLM printf,fprintf),etc. GPT-4.0supportscontextsconsistingofjust32,000tokens(approx- LimitationsofTaintAnalysis. Taintanalysisremainsapar- imately24,000words)forbothpromptsandresponses[36].Conse- |
tiallyautomatedprocess,demandingconsiderablehumaneffortfor quently,whendealingwithrealbinaries,encodingthecodecontext itsexecution.Theeffectivenessofthisanalysisheavilyrelieson tofitthissizeconstraintofLLMsbecomesnecessary.Analyzing theaccuracyandqualityofrulesgoverningtaintlabelpropagation theentirebinarydirectlyisoftenimpractical,asthedecompiled andsinkinspection.Regrettably,designingtheserulesnecessitates codeitselfusuallysurpassesthissizelimitation. meticulousmanualcrafting,resultinginanon-trivialanderror- LATTE. WeproposeLATTE1,thefirsttechniquetoinspectvul- pronetask.Previousresearch[7,8,20,28,44,50]hasheavilyrelied nerabilitiesinreleasedbinariesbycombiningthepowerofLLMs onhumanexpertisetomanuallydefinetheserules,therebyintro- andtheconceptoftaintanalysis.Itconquersthepracticallimita- ducingtheriskoffalsepositivesorfalsenegativesintheanalysis tionsoftaintanalysisbyharnessingtheabilityofLLMsincode resultsduetopotentialruleerrorsandabsences[6,28].Allthree understandingtoautomateandstreamlinethemanualcomponents aforementionedstepsinvolvedintaintanalysisrequiresaprofound oftaintanalysis,andaddressesthechallengesofusingLLMswith understandingofthesemanticsofthebinaryprogramunderanal- dedicatedstaticanalysisandpromptengineering.Thekeyidea ysis.Forinstance,determiningtaintsourcesinvolvesidentifying of LATTEistodrivecodeslicingandconstructpromptsthrough functionsthatreceiveexternaldata,andestablishingtheinitialtaint dangerous flow analysis. To achieve this, we preprocess the bi- labelsrequiresthespecificationofthesefunctions.Additionally, nary,performinganalysissuchasdisassemblyanddecompilation thesanitizationchecksthattransformtainteddataintosafedata torecoverthecodestructure.Basedonthepreprocessingresults, inpropagationrulesarevariousandrelatedtofunctionsemantics. we identify potentially vulnerable destinations, i.e., call sites of Furthermore,theinspectionrulesalsovarybasedonthetypesof securitysensitivefunctions,whichneedtobeinspected.Weuse vulnerabilitiesandsinksinvolved(furtherdetailsin§3). LLMstoidentifysecuritysensitivefunctionsandperformbackward Insights. Thelimitationoftaintanalysisprimarilyarisesfrom intraproceduralandinterproceduraldatadependencytracingto therequirementofanin-depthunderstandingofthesemanticsof establishfunctioncallchainsstartingfromthevulnerabledestina- theprogrambeinganalyzed.Thishashistoricallyimposedasignif- tions.Weconsiderchainsinvolvingexternalinputdataprocess- icantburdenonhumanswhenapplyingtaintanalysistodifferent ingasdangerousflows.Tothisend,wefirstuseLLMstoidentify binaries.Toovercomethislimitation,wefirmlybelievethatlarge sourcesthatpassexternallycontrollabledataintotheprogramand languagemodels(LLMs)canprovidevaluableassistance,benefit- thengeneratedangerousflowsfromthecallchains.Basedonthe ingfromtheirrecentadvancesincodeunderstanding,including dangerousflows,weusefunctionsasnodesandcombinethemwith codegeneration[38,52,55]andcodesummarization[2,49].LLMs programanalysistasks,suchasflowanalysis,aliasanalysisand advantagesincode-relatedtasksbyprovidingcontextawareness, taintanalysis,toformpromptsequences.Thesepromptsequences semanticunderstanding,naturallanguageinteraction,andcontin- aregeneratedtoconversewithLLMs,completingthevulnerability uousupdatesforeffective.WhileLLMshavetheiradvantages,it’s inspection. essentialtonotethattheyarenotasilverbullet.Therefore,inthis Evaluations. Ourcomprehensiveevaluationsdemonstratethat paper,weembarkonthefirststudyforvulnerabilitydiscoverythat LATTEsignificantlyoutperformsthestate-of-the-artbinarytaint exploresthesynergisticcombinationoftheLLM’sabilityincode analyzers.Specifically,WefirstevaluatedLATTEbasedonthetaint- understandingandtheconceptoftaintanalysis. stylevulnerabilitytestcases(compiledandstripped)inthestandard ChallengeofUsingLLMs. Thereareunexploredchallengesin datasetJulietTestSuite[17].TheaccuracyandF1of LATTE’svul- applyingLLMsforvulnerabilityinspectioninbinaries. 1 Prompt nerabilityinspectionsurpassedthestate-of-the-artEmtaint[8]and engineering:PromptsplayacrucialroleininstructingLLMsto Arbiter[50]oneachvulnerabilitytype.Moreover,LATTEachieved generateresponses,andtheirdesignsignificantlyinfluencesthe 100%correctcoverageforidentifyingsecuritysensitivefunctions performanceofLLMs.Inthecontextofvulnerabilityanalysis,well- andexternalinputsourcesinthetestcasetargetscenario.Fortest constructedpromptsmustincludethecodesnippetstobeanalyzed caseslabeledwithcontainingvulnerabilities,LATTEsuccessfully andacleardescriptionoftheanalysistasks.However,currentLLMs extractedmorethan95%ofthecorrectdangerousflowsthatcov- havetheirlimitations:providingallthecodesnippetsrelatedto eredthepathstriggeringpotentialvulnerabilities.Furthermore,we potentialvulnerabilitiesatonceordirectlyinstructingvulnerability assessedtheeffectivenessof LATTEinreal-worldbinariesusing analysisoftenleadstounsatisfactoryresults.Therefore,itisprefer- theembeddeddevicefirmwaredatasetprovidedbyKaronte[44]. abletobreakdowntherelevantcodesnippetsandvulnerability LATTEdetectedatotalof119uniquebugs,including37previously |
analysistasks,andpromptLLMstoperformstep-by-stepanalysis. unknownbugs(7CVEnumbershavebeengivenduetohighthreat), Furthermore,thepromptengineeringprocessshouldbedesigned tobegeneral,withoutrequiringhumaninterventionwhenever theprogramorvulnerabilityanalysistaskchanges. 2 Encodingof 1LLM-PoweredBinaryTaintAnalyzer.HarnessingthePowerofLLMtoSupportBinaryTaintAnalysis Conference’17,July2017,Washington,DC,USA whichoutperformsthestateoftheart[8,44,50]. 1 void bad(void) { 2 signed char a, b, c, d; 3 int e; Contributions. Wemakethefollowingmajorcontributions. 4 bool f; • WeproposeLATTE,thefirststaticbinarytaintanalysispowered 5 a = ' '; 6 fscanf(stdin, "%c", &a); byLLMs. 7 b = a; • LATTE conquers the limitations of taint analysis. Prior taint 8 a = '0x1'; analyzersheavilyrelyonhumanexpertisetodefinerulesfor 9 e = b + '0x1'; 10 printf("%d\n",(ulong)e); propagatingtaintlabelsandinspectingsinksandcustomizerules 11 //No integer overflow after type conversion fordifferentbinariesandvulnerabilitytypes,whereasLATTE 12 if (b == '0x7f'){ 13 printLine("data value is too larger"); harnessestheabilityofLLMsincodeunderstandingtofully 14 } automatetaintanalysis. 15 else{ • LATTEpresentsanoveltysolutiontoaddressthepracticalchal- 16 c = b + '0x1'; 17 printf("%02x\n",(ulong)(uint)(int)c); lengesofusingLLMs,withdedicatedmultiple-stepstaticanaly- 18 //No integer overflow after sanitization sesandautomatedpromptengineeringtoeffectivelyelicitLLMs 19 } togenerateaccurateanalysisresponses. 20 return; 21 } • Comprehensive evaluations demonstrate the effectiveness of LATTE. Compared with the state of the art, LATTE achieved Figure1:Anexampleofanintegeroverflowvulnerability. higheraccuracyandF1scoreonthestandarddataset,andon relyingonhumanexpertiseandheuristicsforruledefinitioncan thefirmwaredataset,LATTEfound117uniquebugs(including beerror-proneandmayleadtoalackofcomprehensivenessin 37previouslyunknownbugswith7awardedCVEnumbers),at vulnerabilitydetection(furtherdetailsin§3). least21morethanthebaselines. 2.2 LargeLanguageModel 2 BACKGROUND AnLLMconsistsofbillionsofparametersandistrainedonbillions 2.1 Taint-StyleVulnerability ofsamplestobehighlygeneral.Downstreamtaskscanbeaccom- Taintanalysiscaneffectivelyfindvulnerabilitiescausedbyexter- plishedusingLLMsthrougheitherpromptingprompting[12,23, nalinputs,commonlyreferredtoastaint-stylevulnerabilities[54]. 26,53]orfine-tuning[13].Inthecontextofprompting,thedown- Nevertheless,variouspreviousbinarytainttechniques[6–8,20,28, streamtaskisdirectlyprovidedasanatural-languagedescription 43,44]usedifferentdescriptionstodenotethetypesofvulnera- totheLLM,promptingittogeneratearesponsetocompletethe bilitiestheysupport.Tofacilitatecomparisonandstandardization, task.Unlikefine-tuning,whichinvolvesretrainingtheLLMwith wecategorizethevulnerabilitytypessupportedbypreviousbinary additionaldata,promptingdoesnotnecessitateextratrainingdata taintanalyzersaccordingtotheCommonWeaknessEnumeration andavoidsthehighcomputationalresourcecostsassociatedwith (CWE)[33].CWEisacommunity-developedlistofsoftwareweak- fine-tuning. Additionally, certain advanced LLMs, such as GPT- nesstypesusedtoclassifysecurityvulnerability[32]. 3.5,donotallowfine-tuning.Therefore,forourresearchproblem, Toensuretheindependenceandunityofvulnerabilitytypes,we promptingisthemoresuitableandconvenientoption. followthefollowingprinciplestoclassifytaint-stylevulnerability Promptengineeringisacriticalprocessthatinvolvesconstruct- types. 1 VulnerabilitytypesaremappedtotheCWE’sbasiclevel, ingpromptstoelicitdesiredresponsesfromLLMs.Itplaysadirect whichisusedtopresentspecifictypesofweaknesses. 2 Classifica- roleininfluencingtheperformanceofLLMsacrossvarioustasks. tionisbasedonthereasonthevulnerabilityistriggered,regardless Withdeliberatedpromptengineering,LLMshavedemonstrated ofthereasonfortheintroductionoftainteddata.Forexample,ifa excellentcodeunderstandingcapabilitiesonmanycode-related commandinjectionvulnerability(CWE-78)iscausedbyunchecked tasks,suchascodegeneration[37]andcodesummarization[2]. inputdata,itwillbeclassifiedasCWE-78,notCWE-76(Improper Thesesuccesseshavealsoinspiredourworktoexploreextending NeutralizationofEquivalentSpecialElements). 3 Classificationis thepowerofLLMsintothedomainofvulnerabilityanalysis. basedonthefirstreasonthevulnerabilityistriggered.Forinstance, ifthereisanintegeroverflowvulnerability(CWE-190)intheoper- 3 MOTIVATION ationofinputdata,andthesubsequentuseoftheoperationresult leadstoabufferoverflow(CWE-680:IntegerOverflowtoBuffer RevisitingTable1,wefindthatprevioustechniquesdemonstrated Overflow),wewillstillclassifyitasCWE-190. supportforonlycertaintypesoftaint-stylevulnerabilities.Thislimi- Asummaryoftaint-stylevulnerabilitytypesandthecapabilities tationarisesfromthedifficultyinmanuallydefiningcomprehensive |
ofexistingbinarytaintanalyzersispresentedinTable1.Previ- propagationandinspectionrulesfortaintanalysis.Effortssuchas oustechniquesrelyonhumanexpertiseorheuristicmethodsto SATC[6]andFBI[28]haveattemptedtooptimizeKaronte’s[44] definetaintanalysisrules,includingpropagationandinspection, rulesusinghumanexperienceandheuristicmethods,resultingin todiscovertaint-stylevulnerabilitiesinbinaries.Unfortunately, reducedfalsenegativesandfalsepositives.However,duetothe noneoftheseprevioustechniquescanbeeasilyextendedtoother complexityandvarietyoftaintanalysis,themanual-dependent vulnerabilitytypesorbinaries.Theengineeringworkinvolvedin naturestillhinderstheoverallperformanceofthesebinarytaint definingpropagationandinspectionrulesissignificantandoften analyzers.WetaketheintegeroverflowvulnerabilityinFigure1as impracticalforhandlingdifferentvulnerabilitytypes.Moreover, anexampletointuitivelyillustratethefollowingconcretereasons.Conference’17,July2017,Washington,DC,USA PuzhuoLiu,etal. Table1:Mappingbetweentaint-stylevulnerabilitytypesandCWE,comparisonofbinarytaintanalyzercapabilities.“✓”means thatthecorrespondingtaintanalyzersupportsthecorrespondingvulnerabilitytype.“*”indicatesthatthetaintanalyzer Arbiterdoesnotprovidethecorrespondinginspectionrulesandadditionalengineeringeffortisrequired. BinaryTaintAnalyzer VulnerabilityType Saluki[20] Dtaint[7] Karonte[44] SATC[6] FBI[28] Arbiter[50] Emtaint[8] LATTE CWE-78 OSCommandInjection ✓ ✓ ✓ ✓ ✓∗ ✓ ✓ CWE-120 ClassicBufferOverflow ✓ ✓ ✓ ✓ ✓∗ ✓ ✓ CWE-134 ControlledFormatString ✓ ✓ ✓ ✓ CWE-190 IntegerOverfloworWraparound ✓ ✓ CWE-606 UncheckedLoopCondition ✓ ✓ firstargument%d,wefirstneedtocheckwhetherthesecondargu- Determinesourcesandinitialtaintlabels: Manuallyidentifying mentofprintfistainted,andifitistainted,furthercheckwhether taintsourcesthatreceiveexternalinputinabinaryisalaborious thecalculationprocessofthisargumentoverflows.Notethatitis process,becausenotonlystandardC/C++functions(suchasrecv, notscalableorreliabletodependsolelyonhumanexperienceto fscanf,fgets)butalsothird-partyfunctions(e.g.,SSL_readand understandsinkfunctionsandvulnerabilitytypes,andmanually BIO_readinOpenSSL)canreceiveexternaldata.Moreimportantly, formulateaccurateandcomprehensiveinspectionrules[8,44,50]. determiningtheinitialtaintlabelsforthereturnvaluesandparam- Binarytaintanalysistechniquesarehamperedbytheaforemen- etersrequiresdeepunderstandingofthesemanticsofthesources. tionedmanualefforts.Themanualeffortsprimarilyarisesfromthe Forexample,onlywiththesemanticsof fscanfcanwedetermine requirementofanin-depthunderstandingofthesemanticsofthe thethirdparameteraof fscanf(line6)tobetaintedasastores programbeinganalyzed.LLMshavetheabilitytoprovidecontext theexternalinputretrievedbyfscanf.Notethatitisevenmore awareness,adapttovarioussemantics,whileprovidinghuman-like challengingtodetermineinitialtaintlabelsforthird-partyfunc- understandingintermsofcode-relatedwork,unlikestaticorauto- tionsthanstandardC/C++functionsbecausetheformerusually matedtoolsthatrelyonpredefinedpatternsandrules.Webelieve donothavegooddocumentationwhereasthelatterareatleast LLMscanprovideinvaluableassistanceandreplacemanualwork documentedintheC/C++languagestandard.Mislabelingoften tomakethetaintenginemoreefficient. leadsthetaintinformationofdatatobepropagatedincorrectly. Definepropagationoftaintlabels: Initialtaintlabelsareprop- 3.1 LATTE agatedthroughouttheprogram,e.g.,byassignment(line7)and WepresentLATTE,anLLM-poweredbinaryvulnerabilitymethod- calculation(line9),whichcanbeautomaticallyidentifiedthrough ologythatutilizesLLMstoanalyzecodesnippetsandinspectpoten- datadependencyanalysis.Theprocessofpropagatingtaintlabels tialvulnerabilities.Thecoreof LATTEliesincombiningcodeand involvesnotonlylabeldeliverybutalsolabelsanitization.Inaddi- analysistaskstoconstructpromptsthatinstructLLMstoperform tiontothesanitizationcausedbydirectlyassigningorcopyingsafe vulnerabilityinspection.Thisapproachraisesthemainresearch datatotaintedregion(line8),therearealsosanitizationsituations question:howtopracticallyandproperlypreparethepromptsex- relatedtosemantics.Forexample,checkingthecontentof bin pectedbyLLMstocompletevulnerabilityinspection.Properprompts line12excludesthepossibilityofoverflowof c = b + ’0x1’in mustprovideLLMswithsufficientcodecontextinformationforvul- line16.Previouswork[8,28,44]ignoressuchcasesofsemanticsan- nerabilityanalysisandcorrespondinganalysisinstructions.How- itizationduetotheconsiderablemanualworkloadbroughtabout ever,achievingthisinputentailsovercomingtwomainchallenges. bydifferentbinaries,whichleadstomanyfalsepositives. Formulateinspectionrulesbasedonsinksandvulnerabilitytypes: 3.1.1 Challenge1:Theconflictbetweenthelargeinputspacecaused Taintanalysiscandiscoverdataflowsensitivevulnerabilitiescaused bycodecomplexityandthelimitedtokencontextoftheLLM. The byexternalinput,includingvarioustypesofvulnerabilitieslisted complexityofbinarycodemakesitimpracticaltodirectlypass |
inTable1.Thesevulnerabilitiescanbetriggeredbydifferentsinks anentirebinaryprogramtotheLLMforanalysis.Onesignificant invariousways,leadingtoacomplexmany-to-manyrelationship. limitationisthetokencontextofLLMs,whichimposesrestrictions Foreachpairofavulnerabilitytypeandasink,itisoftennecessary ontheamountofinputitcanprocess.Whentheinputexceeds tomanuallyformulateacustomizedinspectionrule.Theprocess thislimit,LLMsmayforgetwhatithasalreadyanalyzed,affecting startswithidentifyingsinks,whichcanincludenotonlystandard subsequentcodeanalysis.Evenwithouttokencontextlimitations, C/C++functionslikeprintfandsystembutalsothird-partyfunc- effectivelyinspectingvulnerabilitiesinthecompletecodespaceof tionsfromvariouslibrarieslikeBIO_printfinOpenSSL[19]and areal-worldsoftwareprojectpresentsadauntingchallenge. BIO_printfinOpenSSL[19].Whentaintanalysisisappliedto Solution:Combinedwiththeideaoftaintanalysis,thedan- anewbinarythatislinkedwithdifferentlibraries,humaneffort gerousflowisextractedforanalysis. Byslicingtheprogram, isindispensabletoidentifythesinks,becausesinkidentification wecaneasetheanalysisdifficultyforLLMs.Inthisapproach,we involvescomprehendingthebehavioroffunctionsinthebinary. employtheprinciplesoftaintanalysistoperformdependencyanal- Afterdeterminingsinks,inspectionrulesareformulatedaccording ysisondangerousdatarelatedtotheexternalinputoftheprogram. tothepotentialvulnerabilitytypes.Forexample,toinspectwhether However,unliketraditionaltaintanalysis,wedonotperformsani- theprintfcallonline10cantriggeraCWE-134vulnerability,we tizationandvulnerabilityinspections;instead,wefocussolelyon checkwhetherthefirstargumentof printfistainted;toinspect extractingdangerousflows. Adangerousflowisdefinedasaslice whetherthecallcantriggeraCWE-190vulnerabilitybasedonthe offunctionsinvolvedindatadependenciesbetweentheexternaldataHarnessingthePowerofLLMtoSupportBinaryTaintAnalysis Conference’17,July2017,Washington,DC,USA D Dis ea cs os mem pib ll ay ti a on nd Binary Warning Report SeP qr uo em np ct e s GPT Preprocess Input Output Conversation (((( ((ss ((ss pp eeyytt rr xxrr ss iicc tt eenneepp ccttmmyy ff ll,,;;;; 11;; 1122 11 )))))) )) AnC aa lyll s is s s( (y y0 0s sx xt te e1 2m m2 33 4; ;l l4 5o o5 6c c6 7a a7 8l l_ _8 9 21 ;; ))B Ta rc ak cw ina grd F F F Fu u u un n n nc c c c_ _ _ _0 1 2 3 … F F F Fu u u un n n nc c c c_ _ _ _1 2 3 4 (( g (f( fesr ge tc e e …c a n tv n sv; f ;2 ;; 1r3) )e) )M (If a Ft uc nCh c_a w 2l l c i aCth llh s F a thiu enn ssc outi ro cen .) F Fu un nc c_ _2 3…F F Fu uun nnc cc_ __2 43DeduplactionF F FF F Fu uu u uun nn n nnc cc c cc_ __ _ __2 32 3 44 … F F FF F Fu u uu u un n nn n nc c cc c c_ _ __ _ _2 3 42 3 4 A Tali ia ns t a a ..n n .a al ly ys siis s 1 2 3 P P Pr rr o oo m mm p pp t tt …… … Destination Destination Iden FSt ui et nny cs S ti ite oivc neu s rity DV eu sl tn ie nr aa tb iole n Function Call Chains ExtI Sed r oe n un a rt l ci f eIy n s put DanC ga en rod uid s a Fte lo ws Da Fn lg oe wro sus Da Fng loe wro us TP er mom plp att e SP eqro um enp ct e ❶❶FFuunnccttiioonn CCaallll CChhaaiinn GGeenneerraattiioonn ❷❷DDaannggeerroouuss FFllooww GGeenneerraattiioonn ❸❸PPrroommpptt SSeeqquueennccee CCoonnssttrruuccttiioonn Program Slicing and Prompt Construction Figure2:WorkflowofLATTE. inputfunctionandpotentialdestinationsthatcouldleadtovulner- involvedatadependenciesbetweenexternalinputandpotentialvul- abilities. Throughthisprocess,multipledangerousflowscanbe nerabilitytriggers.Fromthisslice,wegeneratethecorresponding extractedfromtheprogram,constitutingasupersetofpotential promptsequencethatinstructstheLLMforvulnerabilityanalysis. vulnerabilities. This solution reduces the analysis space for the Thethirdmoduleinvolvesusingthegeneratedpromptsequence LLM,whileavoidingtheoverheadofcomplexslicingalgorithms toengageinaconversationwiththeLLM.TheLLMisguidedstep- andminimizingtheriskoffalsenegatives.Theextracteddangerous by-steptoperformvariousanalysistaskstoinspectthepotential flowsprovidetheLLMwithrelevantandcontextuallyconciseinput, vulnerabilitiesinthebinary. enhancingtheaccuracyandefficiencyofvulnerabilityanalysis. Thecodeslicingandpromptconstructionmoduleserveasthe 3.1.2 Challenge2:Theconflictbetweentheobscurityofthevulner- coreofLATTE,andweprovideanintuitiveexplanationofitsthree abilitydiscoveryandthegeneralanalysisinstructionoftheLLM.. phasesinFigure2. Vulnerabilitydiscoveryinherentlyinvolvesexploringtheunknown, ❶ Function Call Chain Generation. In this phase, we begin by makingitdistinctfromtaskslikepatchgenerationorcodegenera- identifyingvulnerabledestinationswithinthebinary.Toachieve tionthatfollowthe"GenerateandValidate"paradigm[29].Unlike this,weutilizetheLLMtoanalyzeeachexternalfunctiontoidentify straightforwardrequirementsthatcanbegeneratedandvalidated, securitysensitivefunctionsandtheirrelatedparameters,whichmay |
describingvulnerabilityinspectioninstructionsinpromptsshould potentiallytriggervulnerabilities.Weconsiderthecallstothese remaingeneric,requiringnoadditionaleffortwhenthecodeor securitysensitivefunctionsasthevulnerabledestinations.Next, vulnerabilitytypechanges. we conductbackwarddata dependencyanalysis, encompassing Solution:Task-drivenconstructionofthepromptsequence. bothintraproceduralandinterproceduralaspects,startingfrom TheeffectivenessoftheLLManalysisdependsheavilyonthecon- eachvulnerabledestination.Thisanalysishelpsusreconstructthe structionoftheprompt,soweneedtoexplicitlyindicatewhatit functioncallchainsleadingtothesedestinations. needstodo.Bycombiningthevariousanalysistasksessentialfor ❷DangerousFlowGeneration.Thesecondphasefocusonidentify- vulnerabilityinspection,suchasaliasanalysis,taintanalysis,and ingexternalinputsourcesandmatchingthemtothepreviouslygen- dataflowanalysis,withtherelevantcodeslices,wecreateacom- eratedfunctioncallchainstogeneratedangerousflows.Toachieve prehensivepromptsequence.Thispromptsequenceisthenusedto this,weonceagainrelyontheLLMtoidentifysourcesfromexter- instructtheLLMstepbystep,engagingitinaformofconversation nalfunctionsanddeterminetheircalls.Then,wematchthecaller toperformtheanalysis.Byfollowingthistask-drivenconstruction, ofthesourceswithinthefunctioncallchains.Ifthecallerexists theLLMgainspreciseinstructionsandguidancethroughoutthe inachain,weconsiderthechainasacandidatedangerousflow vulnerabilityinspectionprocess.Consequently,theLLM,canex- whosestartingpointisthecaller.Byapplyingasequence-sensitive ploreanddiscovervulnerabilitiesmoreeffectively,eveninscenarios filtering process, we eliminate repeated flows among candidate withchangingcodeorvulnerabilitytypes. dangerousflows,resultinginasetofdistinctdangerousflows. ❸PromptSequenceConstruction.Thethirdphaseinvolvescon- 4 OVERVIEWOFLATTE structingpromptsequencesbycombiningtheidentifieddangerous flows with specific analysis tasks. For each dangerous flow, we WeproposeLATTE,anautomatedbinaryvulnerabilityanalysis createmultiplepromptsusingfunctionsasnodes.Thefirstprompt techniquethatleveragescodeslicingtoenableLLMstoinspect elucidatestheanalysissourceandinstructstheLLMtoconduct vulnerabilitiesinbinaries.Theoverallworkflowof LATTEisde- dataaliasing,datadependency,andtaintanalysistofacilitatethe pictedinFigure2,anditprimarilycomprisesthreemodulesto subsequentvulnerabilityinspection.Ifthereisanextfunctioncall accomplishvulnerabilityinspection.Firstly,wepreprocessthein- intheflow,wecontinuetoconstructpromptsfordataflowanaly- putbinaryusingdisassemblyanddecompilationtechniques.This sisuntilwereachtheendofthedangerousflow.Thelastprompt moduleprovidestherecoveredfilestructureandcodestructurefor instructstheLLMtoinitiatethefinalvulnerabilityanalysis. furtheranalysis.Inthesecondmodule,weslicethedangerousflow ofthedecompiledprogram,isolatingrelevantportionsofcodethatConference’17,July2017,Washington,DC,USA PuzhuoLiu,etal. 5 LATTEDESIGN Algorithm1:ProgramSlicingandPromptConstruction. Weintroduceanoveltechniqueforconstructingpromptsequences, Input:Bin:decompilationresultofabinary knownasdangerousflow(DF)basedpromptsequence(PS)con- Input:PT:prompttemplate struction,enablingLLMstoconducteffectivevulnerabilityinspec- Output:PSSet:promptsequencesetforvulnerabilityinspection tionsinbinaries.DFsareobtainedbyperformingbackwarddata //FunctionCallChainGeneration dependencytracingfromcallstosecuritysensitivefunctions(SSFs) 1 [Fext]←extractexternalfunctioninBin andmatchingexternalinputsources(EISs).Theanalysisof DFs 2 [(SSF;Para)]←LLManalysisforeachFext focusessolelyondatadependencyanalysisanddoesnotinvolve 3 [(Loc;SSF;Arg)]←callanalysisforeach(SSF;Para) sanitationorvulnerabilityinspection.BasedontheextractedDFs, 4 foreachvulnerabledestinationVDin[(Loc;SSF;Arg)]do combinedwiththetaskofprogramanalysis,theLLMinspectscode 5 Call_ChainVD←backwarddataflowtracingforeachVD slicesforpotentialvulnerabilities.Below,wepresentAlgorithm1, 6 Call_Chain_Set.𝑎𝑑𝑑(Call_ChainVD) whichprovidesadetailedexplanationoftheprogramslicingand //DangerousFlowGeneration promptconstructionprocess. 7 [(EIS;Para)]←LLManalysisforeachFext 8 foreachCall_ChaininCall_Chain_Setdo 9 Candidate_DF←matcheachSourcein[(EIS;Para)]with 5.1 FunctionCallChainGeneration Call_Chain IntheFunctionCallChainGenerationphase,wefocusonextracting 10 Candidate_DF_Set.𝑎𝑑𝑑(Candidate_DF) functioncallchainsthatarerelevanttopotentialvulnerabilities 11 DFSet←deduplicateCandidate_DF_Set inthebinary.Thisprocessinvolvestwomainsteps:vulnerable //PromptSequenceConstruction destinations(VDs)identificationandbackwardtracing. 12 foreachDFinDFSetdo 13 PS←constructpromptsequencecombiningPTandDF 5.1.1 VulnerableDestinationsIdentification. Thefirststepisabout 14 PSSet.𝑎𝑑𝑑(PS) findingthecallsitesof SSFswithinthebinary.Toinspectallpo- 15 returnPSSet tentialvulnerabilities,weneedtolocateallSSFspresentinthe branchesandreducestheoverheadofanalyzingthesameVDmul- binary.SSFsoftendependonexternallibrarieslinkedtothebinary, tipletimes[7]. |
as described in §3. To automatically identify SSFs, we leverage thepoweroftheLLM.Fordynamicallylinkedlibraries,thenames 5.2 DangerousFlowGeneration ofexternalfunctionsarepreserved,soweprovidethesenames totheLLMandinstructittoanalyzewhetherafunctioncanbe IntheDangerousFlowGenerationphase,ourgoalistoidentifythe usedasasinkfortaintanalysis.Ifso,theLLMprovidestheorder chainsinwhichexternalinputisreachablewithinthecallchainsof oftheparameter(Para)thatmightleadtothevulnerability.For VDs.Thisprocessinvolvestwomainsteps:wefirstneedtoidentify staticallylinkedlibraries,thebodyofthefunctionisincludedin theexternalinputsource(EIS)intheprogramandthenperform thebinary.WeutilizetheLLMforcodesummaryanalysisofthese matchinganddeduplicationinthefunctioncallchainsofVDsto externallibraryfunctionstoidentifySSFsandthecorresponding determinetheDFs. Para.Theoutputresultisalistofthetuple(SSF;Para),asshown 5.2.1 SourceIdentification. ThefirststepistoidentifyEISsinthe inAlgorithm1.Forexample,(system;1)indicatesthatthefirst program.SimilartotheidentificationofSSFs,wealsoutilizethe parameterofthesystemfunctionneedstobecheckedforpotential LLMforthistask.However,inthiscase,theanalysistaskischanged vulnerabilities.AfteridentifyingtheSSFsandthecorresponding tofindfunctionsthatcandirectlyreceiveexternalinputorgenerate Para,wetraversethebinarytolocatethecallsitesofeachSSF, pseudo-randomnumbers.TheLLMjudgesandrespondsbasedon formingaVDlistofthetriplet(Loc;SSF;Arg)list.Forinstance, thefunctionnameorcodesummary,providingthenameofthe (0x12345678;system;local_1)meansthatthesystemfunction sourceandtheParaforintroducingexternalinput.Forinstance, iscalledataddress0x12345678,andtheargumentlocal_1needs (recv;2)indicatesthattherecvfunctionisusedasthesource, tobecheckedforpotentialvulnerabilities. andthesecondparameterisexternallycontrollable. 5.1.2 BackwardTracing. Thesecondstep,backwardtracing,in- 5.2.2 MatchingandDeduplication. WiththeidentifiedEISs,we volvesobtainingtheoperationsperformedontheVD’sarguments proceed to match them in the extracted function call chains to beforetheSSFcall.Thisstepreliesonbothintraproceduraland identifyDFs.Specifically,foreachfunctioninthecallchain,we interproceduraldataflowanalyses.Weadoptadepth-firstback- checkifitisthecallerofanyoftheidentifiedEISs.Ifso,wefurther ward(bottom-up)approachtotraversethecallgraphandbuild analyzewhethertheexternalcontrollableParaofthesourceoverlap dataflowsfromeachVD.Specifically,wefirstextractthecallgraph withthedataflowoftheVD.Ifthereisanoverlap,theflowis oftheentireprogram.Then,weperformintraproceduraldatade- consideredaDF.Asafunctioncallchainmaygeneratemultiple pendencyanalysiswithinthecalleroftheVD.Ifthereisadepen- DFsduetomultiplesources,weonlykeepthelongestDFwithin dencybetweentheargumentsoftheVDandtheparametersof thesamefunctioncallchainwhengeneratingDFs.Additionally, thecaller,weproceedtoanalyzethecallgraphforinterprocedural differentfunctioncallchainsmayproducethesameDForsub- datadependencyanalysis.Werecursivelyanalyzethedependencies chain.Toavoidredundancyandreduceunnecessaryinspection untileithernothingisrelevanttothecaller’sparametersorthere requests,wefilteroutcandidatedangerousflows(Candidate_DFs) isnocaller.Thisapproachhelpsavoidanalyzingnon-vulnerable thataresub-chainsofotherDFs.HarnessingthePowerofLLMtoSupportBinaryTaintAnalysis Conference’17,July2017,Washington,DC,USA 5.3 PromptSequenceConstruction and other relevant information from the binary for subsequent InthePromptSequenceConstructionphase,ourobjectiveisto analysis.UsingtheAPIofGPT-4.0,LATTEautomaticallyidentifies constructthepromptsequence(PS)thatinstructstheLLMtoper- SSFsandEISsinthebinary.Afterthat,LATTEperformsbackward formvulnerabilityinspectionbasedontheidentifiedDFs.ThePS datadependencyanalysistotracethedataflowfromthecallsites isdesignedtoenabletheLLMtoconductvulnerabilityinspection of SSFs.LATTEthenmatchesEISsinthefunctioncallchainsto inageneralandcomprehensivemanner.Toachievethis,weuse generateDFs.TheDFsrepresentthepotentialpathsintheprogram naturallanguagedescriptionscombinedwitheachDFtobuildthe thatmayleadtovulnerabilities.BasedontheextractedDFsand correspondingPS.Specifically,weusethefunctionspresentineach prompttemplates,LATTEconstructspromptsequencestoinstruct DFasnodestoconstructthecorrespondingprompts.Theconstruc- GPT-4.0forvulnerabilityinspection.GPT-4.0analyzesthecode tionprocessinvolvesthreeprompttemplates(PTs)usedasthestart, snippetsinthecontextoftheprovidedinstructionsandperforms middle,andendofthePS,respectively.IfaDFcontainsonlyone theinspectiontoidentifypotentialvulnerabilitiesinthebinary. function,thecorrespondingPSwillhavetwoprompts:thestartand Dataset. Fortheevaluationof LATTE,weusedtwodatasets: endprompts.IfaDFcontainsmultiplefunctions,werecursively • JulietTestSuite(v1.3)[17]:Thisdatasetincludesavulnerability usethemiddletemplatetocontinuebuildingthePSwiththecallee testsetwritteninC/C++andclassifiedaccordingtoCWE.The |
functionbodies. fourvulnerabilitytypes(CWE-78,CWE-134,CWE-190,CWE- Thestartpromptincludesthetaskdescriptionandthefirstfunc- 606)inTable1areincludedinJuliet(CWE-120inevaluatedusing tionbodyoftheDF.Thetaskdescriptionisformulatedasfollows: theKarontedataset).Thetestcasesinthisdatasetwerecompiled "Asaprogramanalyst,IgiveyousnippetsofCcodegeneratedbyde- intobinariesforLATTE’sevaluation.Toensureconsistencywith compilation,usingstartasthetaintsource,andparametermarked real-worldscenarios,westrippeddebuginformationandsym- asthetaintlabeltoextractthetaintdataflow.Payattentiontothe boltablesfromthebinaries.Additionally,testcasesbasedon dataaliasandtainteddataoperations.Outputintheformofdata constant-valuesourceswereremovedsinceLATTEisdesigned flows."Here,startandparameterarefilledinwiththecorrespond- todetectvulnerabilitiescausedbyexternalinputs.Thenumber ingmatchingsource,suchasrecvandthe second parameter.If oftestcasesusedforevaluationismentionedinTable2. therearestillfunctioncallsintheDF,wecontinuebuildingthe • KaronteDataset[44]:TheKarontetechniqueprovidesadataset promptusingthemiddletemplateandthecalleefunction. of real-world embedded device firmware from various popu- Themiddlepromptincludesananalysistaskdescriptionthat larvendors,suchasNETGEAR,D-Link,TP-Link,andTenda. instructstheLLMtocontinueanalyzingthefunctionbasedonthe Firmware is a typical binary used to evaluate the efficacy of taintanalysisresultsobtainedfromthepreviousprompts.Thetask LATTEinreal-worldprograms.Thedatasetconsistsof49Linux- descriptionisasfollows:"Continuetoanalyzefunctionaccording basedfirmwaresamples.Similartoothertechniques(SATC[6], totheabovetaintanalysisresults.Payattentiontothedataalias, FBI[28],Emtaint[8]),LATTEwasevaluatedbasedonthem. tainteddataoperations,andsources."Thefunctioninthedescription Baseline. OnthestandarddatasetJuliet,wechosetwostate- isfilledinwiththecalleefunctionbody,andiftherearenewtaint of-the-artbinarytaintanalysistechniques,Arbiter[50]andEm- sourcesinthecallee,theyarealsoincludedintheprompt. taint[8],forcomparisonwithLATTEintermsofvulnerabilityin- Afteranalyzingallthefunctionsinthedangerousflow,weuse spectioneffectivenessandperformance.WealsocomparedLATTE theendprompttoperformvulnerabilityinspection.Theendprompt withtheKarontetechniquefortheKarontedatasetsinceKaronte containsthetaskdescription:"Basedontheabovetaintanalysis isspecifictofirmwareanddoesnotworkontraditionalbinaries. results,analyzewhetherthecodehasvulnerabilities.Ifthereisa Additionally,theresultsofSATCandFBIwerenotshowninthe vulnerability,pleaseexplainwhatkindofvulnerabilityaccording comparisonbecauseEmtainthadachievedthebestresultsonthe toCWE." Karontedatasetuptothatpoint. Metric. IntheevaluationbasedontheJulietTestSuite,wemea- 6 EVALUATION suredtheeffectivenessof LATTEusingsixindicators:truepositive Theevaluationsof LATTEaredesignedtoaddressthefollowing (TP),falsenegative(FN),truenegative(TN),falsepositive(FP), fourresearchquestions: accuracy(𝑇𝑃+𝑇𝑇 𝑁𝑃+ +𝑇 𝐹𝑁 𝑃+𝐹𝑁),andF1score(2 𝑝∗𝑝 𝑟𝑒𝑟 𝑐𝑒 𝑖𝑐 𝑠𝑖 𝑖𝑠 𝑜𝑖𝑜 𝑛𝑛 +∗ 𝑟𝑟 𝑒𝑒 𝑐𝑐 𝑎𝑎 𝑙𝑙𝑙𝑙 ,where RQ1:HowwellLATTEperformforvulnerabilityinspection? 𝑝𝑟𝑒𝑐𝑖𝑠𝑖𝑜𝑛 = 𝑇𝑃𝑇 +𝑃 𝐹𝑃,𝑟𝑒𝑐𝑎𝑙𝑙 = 𝑇𝑃𝑇 +𝑃 𝐹𝑁).Fortheevaluationonthe RQ2:Howeffectiveistheidentificationofsecuritysensitivefunc- real-worldfirmwaredatasetprovidedbyKaronte,sincethereare tions(SSFs)andexternalinputsources(EISs)? nolabels,wemainlymeasuredtheTPandFPintheanalysisalerts. RQ3:Howeffectiveistheextractionofdangerousflows(DFs)? Moreover,weverifiedthenumberofuniquebugsamongtheTPs RQ4:DoesLATTEscaletoreal-worldbinaryvulnerabilityanalysis? tofurtherassessLATTE’seffectiveness. RunningEnvironment. Allexperimentswereperformedona 6.1 Evaluationsetup LinuxworkstationwithanIntelCorei7-8750HCPUand64GRAM. Implementation. TheimplementationofLATTEisbasedonthe reverseengineeringframeworkGhidra[34]andthelargelanguage 6.2 VulnerabilityInspection(RQ1) modelGPT-4.0[35].Wedescribeanoverviewoftheimplementation processbelow.ThebinaryisloadedandanalyzedbywritingGhidra Effectiveness. LATTEperformsautomaticvulnerabilityinspec- plugins(about2,500linesofpython).Ghidraallowstheextractionof tiononthebinarycompiledfromJulietafterstripping.Foragiven decompiledcode,controlflowgraphs,importtables,stackframes, testcase,weonlyinspectthespecificCWEthatthetestcaseisConference’17,July2017,Washington,DC,USA PuzhuoLiu,etal. Table2:EvaluationresultsofvulnerabilityinspectionbasedonJuliet.✕indicatesthatthevulnerabilitytypeisnotsupported. CWE-78(960/960)+ CWE-134(1200/1200)+ CWE-190(2860/2860)+ CWE-606(240/240)+ Emtaint Arbiter LATTE Emtaint Arbiter LATTE Emtaint Arbiter∗ LATTE Emtaint Arbiter LATTE TP 820 408 892 1115 1166 1151 ✕ 2091 1773 ✕ ✕ 210 FN 140 552 68 85 34 49 ✕ 769 1087 ✕ ✕ 30 TN 960 430 960 1132 30 1102 ✕ 444 1779 ✕ ✕ 142 FP 0 530 0 68 1170 98 ✕ 2416 1081 ✕ ✕ 98 Accuracy 92.7% 42.76% 96.46% 93.63% 49.83% 93.88% ✕ 44.32% 62.1% ✕ ✕ 73.33% F1Score 92.14% 43.25% 96.33% 93.58% 65.95% 93.99% ✕ 56.76% 62.05% ✕ ✕ 74.24% |
Avg.Time(s) 5.2 122 13.5 5.6 73.6 14.2 ✕ 7.8 15.1 ✕ ✕ 13.9 + Thenumbersinparenthesesindicatethenumberoftestcases(bad/good)forthisvulnerabilitytype. * Arbiterreliesonsymboltable,suchasprintIntLine,printHexCharLine,andprintLongLongLine,toassistinoverflowjudgment.IfLATTEisalsoanalyzedbasedonthe binarywithoutthestrippedsymboltable,TPis2576,FNis284,TNis1939,FPis921,Accuracyis78.93%,F1is81.04%. writtenfor.Duringourevaluationof LATTE,weconductedfive figure.ThisshowsthatLATTEdemonstratesacceptablestability, roundsofteststoensurerobustnessandaccuracy.Asshownin exceptforCWE-190.TherelativelylargefluctuationinCWE-190 Table2,theaverageinspectionaccuracyforthefourtypesofvul- resultsisconsistentwiththeissuementionedearlier,causedby nerabilitiesis77%,withCWE-78achievingthehighestaccuracy wrong data type judgments without the assistance of function at96.46%,andCWE-190obtainingthelowestat62.1%.Compared names. toadvancedtechniquesEmtaintandArbiter,LATTEoutperformed themintermsofaccuracyandF1score,whilealsosupportinga wider range of vulnerability inspections. Note that Arbiter can 900 detectmoretruepositivesthanLATTEinthecaseofCWE-190. 800 However,thisisattributedtothefactthatArbiterreliesonthe 700 symboltableforinspection,andifthisinformationisprovided 600 toLATTE,LATTEcanoutperformArbiterbydetecting2576true 500 positives. 400 WefurtheranalyzedthereasonsbehindFNsandFPsinLATTE’s 300 vulnerability inspection. The first reason is that sometimes the 200 dangerousflowofthebinaryisnotcorrectlyextracted.Thismay 100 occurduetoprogramanalysisproblems,suchasindirectcallsand 0 CWE-78 aliases,whichcanleadtofalseorfailedextractionofdangerous flows(furtherdetailsin§6.4).Thesecondreasonisrelatedtothe creativityofGPT-4.0,whichcanleadtodifferentresponsestothe samepromptsequence,resultinginunstableanalysisresults.How- ever,thevulnerabilityinspectiontaskitselfhasthepropertyof explorationratherthansimplerulematching.Therefore,theinsta- bilitybroughtaboutbythecreativityofGPT-4.0isnotnecessarily badforvulnerabilityinspection.Wefurtheranalyzethestabilityof theLATTEresult. Stability. Asanartificialintelligencegenerationmodel,GPT-4.0 exhibitsacertaindegreeofrandomnessinthegeneratedresponse. Thetemperatureparameterplaysasignificantroleincontrolling thecreativityanddiversityofthecontentproducedbyGPT-4.0. Thetemperaturevalueisafloating-pointnumberbetween0and 1,wherehighervaluesresultinmorediverseandrandomoutputs, whilelowervaluesproducemoreconservativeanddeterministic outputs.Weconductedtwosetsofexperimentstoassessthestabil- ityofLATTE’sanalysisresultsandtheinfluenceoftemperatureon theoutcomes. Stability of results at temperature = 0.5. To strike a balance betweencreativityandstability,weusedamediantemperature valueof 0.5inthefiveroundsoftestingmentionedearlier.We measuredthestabilitybyevaluatingtheintersectionofTPsamong thefiverounds.Figure3showssmallfluctuationsinthenumberof TPsindifferentroundsofthesameCWEtype.Therecallsofthe intersectionofthefiveroundsforthefourCWEtypesare90.42%, 88.42%,58.04%,and82.5%,respectively,fromlefttorightinthe sevitisoP eurT Number of intersections 1200 1800 250 1100 1600 1000 900 1400 200 800 1200 700 150 1000 600 500 800 100 400 600 300 200 400 50 100 200 0 0 0 CWE-134 CWE-190 CWE-606 Figure 3: The TP intersection among the five test rounds indicatesthestabilityofLATTE.Theintersectionnumbers ofthefourvulnerabilitytypesare868,1061,1660,198. Effectofdifferenttemperaturesontheresults.Toexplorethe impact of temperature on LATTE’s vulnerability inspection, we conducted11setsofexperimentswithvaryingtemperaturevalues (withastepof0.1).Eachsetwasperformedfiveroundstoensure reliability.Duetothepagelimitations,weonlyshowtheresultsof CWE-78inFigure4.Thetrendofthedatainthefiguregenerally conformstoanormaldistribution,includingthemedian,minimum, andmaximumvalues.Weobservethatwhenthetemperatureis lessthan0.4,theinspectionresultsaremoreconcentrated,butthe numberofTPsisrelativelylow.Conversely,whenthetemperature isgreaterthan0.6,theinspectionresultsaremorescattered,but thereisapossibilityofdetectingmoreTPs.Thetemperatureof 0.4-0.6canachieveabalancebetweenstabilityandinspection effect.SimilartrendswereobservedfortheanalysisofCWE-134, CWE-190,andCWE-606. Performance. Intermsofperformance,weanalyzedthetime overheadandthemonetarycostof LATTEwheninspectingfor vulnerabilities. Theaveragetimetakentoanalyzedifferenttestcasesissum- marizedinTable2.TheresultsindicatethatLATTEcancomplete theanalysisofatestcasewithintwentyseconds.Thetimeover- headcanbedividedintotwoparts:dangerousflowextractionand conversationwithGPT-4.0.TheextractionofdangerousflowscanHarnessingthePowerofLLMtoSupportBinaryTaintAnalysis Conference’17,July2017,Washington,DC,USA 900 895 890 885 880 875 870 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 Temperature sevitisoP eurT InadditiontotheSSFandEISidentifiedforthetargetscenarios, thereareotherfunctionsinthebinarythatcouldbeusedasSSFs andEISs,buttheydonotcausevulnerabilitiesinthecurrenttest |
case.LATTEidentifiedthecorrectSSFandEISwithanaverage precisionof83.33%.TheFPsobservedintheidentificationresults aremainlyattributedtotheinstabilityofGPT-4.0.Insomecases, GPT-4.0mistakenlyconsideredrecvasanSSF,leadingtothefalse positive.Thishighlightsthechallengeofmanagingthecreativity anddiversityofthelanguagemodel,whichcansometimesresult inunintendedoutcomes. WhileEmtaintandArbiterrelyonmanuallydefiningsources andsinks,LATTE’sidentificationresultscanbeusedtoassistthese techniquesinreducingthemanualworkload.Byprovidingmoreac- curateandautomatedSSFandEISidentification,LATTEcontributes Figure4:AccuracyofCWE-78analysisforLATTEatdifferent tostreamliningthevulnerabilityanalysisprocessandenhancing temperatures. theefficiencyofothertechniques. becompletedwithintwoseconds,whichisarelativelyefficient process.Themajorityoftheanalysistimeisspentontheconver- AnswertoRQ2:LATTEautomaticallyidentifiesSSFand sationwithGPT-4.0,asthisstepinvolvesinstructingthemodel EISwithanaverageprecisionof78%.Theidentification andwaitingforitsresponse.Thetimetakenforthisstepcanbe results100%correctlycoveredtheSSFandEISofthetest influencedbynetworkqualityandtheresponsespeedofGPT-4.0. casetargetscenario. ComparingLATTEwithEmtaintandArbiter,wefindthatthetime overheadof LATTEisslightlygreaterthanthatofEmtaint,with a difference of about eight seconds. However, this difference is 6.4 DangerousFlowExtraction(RQ3) consideredacceptablegiventheautomationthatcomeswithusing GPT-4.0. Theeffectivenessof DFextractionisacrucialfactorthatdirectly Regardingthemonetarycost,theevaluatedcostofLATTEan- impactstheaccuracyandsuccessofGPT-4.0ininspectingforvul- alyzingadangerousflowis0.35$,whichisconsideredacceptable nerabilities.Thegoalof DFextractionistocoverallcodesnippets comparedtotheexpenditureofhiringaprogramanalysisexpert thatpotentiallycontainvulnerabilitieswithinthebinary.Toevalu- formanualinspection.Moreover,withthedevelopmentofLLM atethis,weanalyzedvulnerablebinaries(labeledas"bad")inthe technology,thecostofusingsuchmodelsisexpectedtodecrease Juliet. overtime,whiletheperformanceislikelytoimprove,makingitan Ouranalysisshowsthatfordifferenttypesofvulnerabilities, evenmoreattractiveoptionforvulnerabilityanalysis. theproportionofvulnerablebinariesthatsuccessfullyextractDFs isgreaterthan95%(asdepictedinFigure5).Notably,theDFof eachsuccessfullyextractedtestcaseiscorrect,andonlyoneDF AnswertoRQ1:TheaverageaccuracyofLATTEvulnera- isgenerated.ThisindicatesthatLATTE’sDFextractionishighly bilityinspectionis77%.Comparedtothestate-of-the-art effective, as it correctly captures the potential paths leading to EmtaintandArbiter,LATTEoutperformsthemindifferent vulnerabilitiesinthemajorityofcases. vulnerabilitytypes.Moreover,theaveragerecalloftheTP However,therearecaseswhereLATTEdidnotsuccessfullyex- intersectionacrossdifferenttestroundsis79.85%,which tractDFs.Weinvestigatedthesecasesandidentifiedtwoprimary showsthattheinspectionresultsof LATTEarestable. reasons: 1 Ghidradecompilationerror.Insomecases,thedecom- pilationenginemayencounterissueswhileparsingtheparameters offunctioncalls.Thiscanleadtodisruptionsindatadependen- 6.3 SSFandEISIdentification(RQ2) cies,whichultimatelyaffectstheextractionof DFs. 2 Purevirtual LATTE’sabilitytoautomaticallyidentifytheSSFandEISneededfor functioncalls.Certainfunctionsinthebinarymaybepurevirtual, vulnerabilityanalysiswasverifiedandtheresultsarepresentedin meaningtheyhavenofunctionbodyandmustbeimplementedin Table3.Foreachtestcase,thevulnerabilityistriggeredbyaspecific derivedclasses.ThisscenariocausesLATTEtofailinextractingthe pairof SSFandEIS,suchasrecvandsystem.LATTEsuccessfully DF,asthereisnoconcreteimplementationtoanalyze. identifiedtheSSFandEISforthetestcasetargetscenariowith No dangerous flow True dangerous flow 100%precision. 4.2% 1.8% 4.5% 4.2% Table3:SSFandEISidentificationresults Avg.#SSF Precision Coverage∗ Avg.#EIS Precision Coverage∗ 95.8% 98.2% 95.5% 95.8% CWE-78 6.12 85.42% 100% 4.72 76.17% 100% CWE-134 6.71 86.2% 100% 4.52 80.21% 100% CWE-190 5.2 90.21% 100% 5.63 72.14% 100% CWE-78 CWE-134 CWE-190 CWE-606 CWE-606 6.79 85.18% 100% 4.46 81.11% 100% Figure5:Dangerousflowextractionresults. ∗theproportionofidentificationresultscoveringthetestcasetargetscenario.Conference’17,July2017,Washington,DC,USA PuzhuoLiu,etal. Table4:Vulnerabilityinspectionresultsbasedonreal-worldfirmwaredatasetcollectedbyKaronte. Karonte Emtaint Arbiter LATTE Vendor Samples Unique Avg. Unique Avg. Unique Avg. Unique Avg. Alerts TP FP Alerts TP FP Alerts TP FP Alerts TP FP Bugs Time Bugs Time Bugs Time Bugs Time NETGEAR 17 36 23 13 14 17:13 849 849 0 47 00:05 131 63 68 26 02:20 142 124 18 54 00:38 D-Link 9 24 15 9 5 14:09 299 234 65 29 00:02 99 48 51 14 03:18 65 59 6 42 00:21 TP-Link 16 2 2 0 1 01:30 73 73 0 3 00:05 21 18 3 6 02:40 29 23 6 10 00:33 Tenda 7 12 6 6 3 01:01 362 362 0 19 00:05 49 22 27 6 03:25 19 16 3 13 00:29 Total 49 74 46 28 23 451:06 1583 1518 65 98 03:38 300 151 149 52 135:57 255 222 33 119 26:06 |
Alerts:thenumberofbugsconsideredbythetechnique. TP:thedataflowofexternalinput(source)andvulnerabilitytriggerlocation(sink)istrulyreachable. FP:externalinput(source)andvulnerabilitytriggerlocation(sink)dataflowisactuallyunreachable.Ornotcausedbyexternalinputdata. UniqueBugs:user-controllableexternalinputswithdifferent(source;sink)pairsinTP. Avg.Time:averagetimespentanalyzingafirmwarerepresentedbyhh:mm. alsoanalyzesthecallerandcallee,variablename,andoutputin- Answer to RQ3: LATTE successfully and correctly ex- formationtounderstandsthesemanticsofthefunction.Basedon tracts dangerous flows covering more than 95% of test theunderstandingofthefunction,GPT-4.0performsvulnerability casescontainingpotentialvulnerabilities. inspectionthroughtaintanalysis.Whilegivingthevulnerability triggerpathanddatadependencies,theresponsesalsoincludere- pair opinions, which greatly helps analysts identify and fix the 6.5 Real-worldVulnerabilityInspection(RQ4) vulnerability. Intheevaluationofthereal-worldfirmwaredatasetfromKaronte, LATTEoutperformsKaronte,Emtaint,andArbiter,discovering119 AnswertoRQ4:LATTEeffectivelyinspects119unique uniquebugs(includingCWE-78andCWE-120)on49firmwares, bugs(including37previouslyunknownbugs)inthereal- andcoveringallbugsfoundbyKaronteandArbiter.ForEmtaint, worldfirmwaredataset,whichisbetterthanthestate-of- therewere16bugsLATTEcouldnotdiscover,whichwerecausedby the-artKaronte,Emtaint,andArbiter. thefailureofDFextractionduetopointeraliasing.LATTEfound37 previouslyunknownbugs,and7CVEnumbershavebeenobtained duetothehighthreatofthesebugs. 7 DISCUSSION The false positive rate and total analysis time of LATTE are 12.9%and26.1hours,respectively,whicharebetterthanKaronte VulnerabilityType. PreviousworksuchasArbiterandEmtaint andArbiter,butslightlyworsethanEmtaint.However,Emtaint relyonpriorknowledgeandmanuallycustomizedrulesforbinary generatedmorealertsandFPsthanLATTE,makingLATTEeasier vulnerabilityinspection.LATTEutilizesdangerousflowcodeslicing foranalyststouse.Additionally,LATTEprovidesvaluableanalysis andLLM’scodeunderstandingabilitytorealizeautomaticbinary informationdescribedinnaturallanguage,aidingresultanalysis. vulnerabilityinspectionwithouthumanintervention,resulting CaseStudy. WeusearealvulnerabilitydiscoveredbyLATTEas inimprovingtheeffectivenessofanalysis.However,LATTEmay anexampletoillustratetheadvantagesoftheLLM-poweredtaint facechallengesinhandlingcertaintypesofvulnerabilities,such analysis.Duetopagelimitations,weonlyshowthecondensedGPT- aslogicvulnerabilitiesandthoseinvolvingcomplexmathematical 4.0response,whichcanbedividedintothefollowingtwoparts.9 calculations(e.g.,competitionvulnerabilitieswithtimewindows). FunctionSemanticsDescription:"ThefunctionFUN_0001bab0 These vulnerabilities often involve intricate code snippets with takesasingleparameter,apointertoachar(char*param_1),and complexnestingandjumping,makingthemdifficultfortheLLM returnsanundefined4typevalue.Thefunctionappearstobechecking to effectively analyze. Furthermore, due to the lack of publicly thestatusofaprocessbasedonafile.Thefunctioncanreturnthree availableinformationonsuchvulnerabilities,theLLM’sanalysis differentvalues:0,0xffffffff,and0xfffffffe.Here’sananalysisofthe abilityintheseareasislimited. function:1.Iftheinputparameter(param_1)isNULLoranempty LargeLanguageModel. LATTEleveragesthestate-of-the-art string,thefunctionreturns0xffffffff.2.IftheparameterisnotNULLor GPT-4.0asitsvulnerabilityinspectionengine.Whilethereareother empty,thefunctionattemptstoopenthefilespecifiedbytheparameter LLMslikeOPT,LaMDA,andLLaMAbeingstudied,ourmaincon- (param_1)inread-onlymode(0).Omitted... 9TaintAnalysisof tributionliesinleveragingprogramanalysistechniquestogenerate Vulnerabilities:"Basedontheprovidedcodesnippet,thereisapoten- promptsthatmakeLLMsworktoaidinvulnerabilityinspection.In tialvulnerabilityrelatedtoCWE-120(BufferCopywithoutChecking §6,weillustratedtheeffectivenessofthisapproachbasedonstan- SizeofInput).Thevulnerabilityarisesfromthefollowingcodeblock: darddatasetsandrealfirmwareevaluations.AsLLMtechnology memset(acStack_50,0,0x40);sVar2=read(__fd,acStack_50,0x3f);Here, continuestoevolve,itisexpectedthattheabilityofvulnerability thebufferacStack_50hasasizeof68bytes,andthecodeattemptsto inspectionwillalsoimprove.Oneofthestrengthsof LATTEisits readupto63bytesfromthefileintothebuffer.Omitted...Tomitigate flexibility,whichallowstheLLMinterfaceusedinthetooltobe thisvulnerability,youcanaddanullterminatorexplicitlyafterthe easilyportedtootherLLMsifdesired. readoperation:sVar2=read(__fd,acStack_50,0x3f);acStack_50[sVar2] =’0’;Byaddingthenullterminator,youensurethatstringmanipu- 8 RELATEDWORK lationfunctionswillnotreadpastthebuffer’sboundary,preventing potentialbufferoverflowissues." BinaryVulnerbilityAnalysis. Forvulnerabilityanalysisof |
Fromtheresponses,wecanfindthatGPT-4.0notonlyanalyzes binary, there are both dynamic and static techniques. Dynamic thefunctionFUN_0001bab0owndataflowandcontrolflow,but techniquesmonitorunexpectedbehaviorsoftesttargetsastheyHarnessingthePowerofLLMtoSupportBinaryTaintAnalysis Conference’17,July2017,Washington,DC,USA executetestcases,suchasfuzzing[5,16,27,45,59],concolicexe- Kallitsis.2017.Understandingthemiraibotnet.In26thUSENIXsecuritysympo- cution[11,40,48,57],emulationanalysis[10,15,22,24,31].The sium.1093–1110. [4] MarcelBusch,AravindMachiry,ChadSpensky,GiovanniVigna,Christopher resultsofdynamicanalysisarereliable,butthetestcodecoverage Kruegel,andMathiasPayer.2023.Teezz:Fuzzingtrustedapplicationsoncots islowandthetestexecutiondependsonthespecificoperating androiddevices.In20232023IEEESymposiumonSecurityandPrivacy(SP)(SP). environment.Binaryexecutionenvironmentsvarydependingon 220–235. [5] JiongyiChen,WenruiDiao,QingchuanZhao,ChaoshunZuo,ZhiqiangLin, theoperatingsystem,architecture,andevenperipherals.Asare- XiaoFengWang,WingCheongLau,MenghanSun,RonghaiYang,andKehuan sult,theapplicationandperformanceofdynamicanalysisisoften Zhang.2018.IoTFuzzer:DiscoveringMemoryCorruptionsinIoTThroughApp- basedFuzzing..InNDSS. limited.Staticanalysistechniquesaresuitableforbinaryanaly- [6] LiboChen,YanhaoWang,QuanpuCai,YunfanZhan,HongHu,JiaqiLinghu, sis due to their high code test coverage and not limited to the QinshengHou,ChaoZhang,HaixinDuan,andZhiXue.2021. SharingMore executionenvironment.BootStomp[43],Saluki[20],Dtaint[7], andCheckingLess:LeveragingCommonInputKeywordstoDetectBugsin EmbeddedSystems..InUSENIXSecuritySymposium.303–319. Karonte[44],SATC[6],Arbiter[50],andEmtaint[8]techniques [7] KaiCheng,QiangLi,LeiWang,QianChen,YaowenZheng,LiminSun,and primarilyleveragetaintanalysiscombinedwithprogramanalysis, ZhenkaiLiang.2018.DTaint:detectingthetaint-stylevulnerabilityinembed- symbol execution, and machine learning to analyze binary vul- deddevicefirmware.In201848thAnnualIEEE/IFIPInternationalConferenceon DependableSystemsandNetworks(DSN).IEEE,430–441. nerabilities.However,thesemethodscommonlyrelyonhuman [8] KaiCheng,YaowenZheng,TaoLiu,LeGuan,PengLiu,HongLi,Hongsong experiencetodefinepropagationandinspectionrules.LATTE,on Zhu,KejiangYe,andLiminSun.2023.DetectingVulnerabilitiesinLinux-based EmbeddedFirmwarewithSSE-basedOn-demandAliasAnalysis.In2023ACM theotherhand,isthefirsttoproposeataintanalysistechnique SIGSOFTInternationalSymposiumonSoftwareTestingandAnalysis.ACM. combinedwithLLMsforbinaryvulnerabilityinspection,offeringa [9] JakeChristensen,IonutMugurelAnghel,RobTaglang,MihaiChiroiu,andRadu novelapproachthatavoidstheneedformanualruledefinition. Sion.2020.DECAF:Automatic,AdaptiveDe-bloatingandHardeningofCOTS Firmware.In29thUSENIXSecuritySymposium(USENIXSecurity20).USENIX LLM-assistedCodeAnalysis. TheLLMisaclassofdeeplearn- Association,1713–1730. https://www.usenix.org/conference/usenixsecurity20/ ingmodelsthathavesignificantlyimpactednaturallanguagepro- presentation/christensen [10] AbrahamAClements,EricGustafson,TobiasScharnowski,PaulGrosen,David cessing. In recent years, with the excellent code understanding Fritz,ChristopherKruegel,GiovanniVigna,SaurabhBagchi,andMathiasPayer. ability of LLMs, they have been widely applied in code-related 2020.HALucinator:Firmwarere-hostingthroughabstractionlayeremulation. tasks,suchascodegeneration[1,18,37,56],patchgeneration[41, In29thUSENIXSecuritySymposium(USENIXSecurity20).1201–1218. [11] EmilioCoppa,HengYin,andCamilDemetrescu.2022.Symfusion:hybridinstru- 47,51,52],andcodesummarization[2].Forcodevulnerabilityanal- mentationforconcolicexecution.InProceedingsofthe37thIEEE/ACMInterna- ysis, it is often necessary to combine various program analysis tionalConferenceonAutomatedSoftwareEngineering.1–12. techniquesonthebasisofLLMs’codeunderstandingtoconduct [12] YinlinDeng,ChunqiuStevenXia,HaoranPeng,ChenyuanYang,andLingming Zhang.2023. LargeLanguageModelsareZero-ShotFuzzers:FuzzingDeep- effectivevulnerabilityauditing.Forinstance,FuzzGPT[13]and LearningLibrariesviaLargeLanguageModels.InProceedingsofthe32ndACM TitanFuzz[12]utilizetheLLMtoanalyzeexistingcodesnippets SIGSOFTInternationalSymposiumonSoftwareTestingandAnalysis.423–435. [13] YinlinDeng,ChunqiuStevenXia,ChenyuanYang,ShizhuoDylanZhang,Shujing andgeneratetestcasestoassistinAPIfuzzing.CODAMOSA[26] Yang,andLingmingZhang.2023.Largelanguagemodelsareedge-casefuzzers: usestheLLMtoanalyzecodecoverageinformationandmodify Testingdeeplearninglibrariesviafuzzgpt.arXivpreprintarXiv:2304.02014(2023). testcasestoimprovetestcoverage.UnliketheseLLM-assisteddy- [14] EdsgerWDijkstra.2002.Ewd1308:Whatledto“notesonstructuredprogramming”. Springer. namicanalysistechniques,LATTEutilizestheLLMtoassiststatic [15] BoFeng,AlejandroMera,andLongLu.2020. P2IM:Scalableandhardware- |
analysisandworksonbinariesthatprovidelesscodeinformation independentfirmwaretestingviaautomaticperipheralinterfacemodeling.In thansourcecode. 29thUSENIXSecuritySymposium(USENIXSecurity20).1237–1254. [16] XiaotaoFeng,RuoxiSun,XiaogangZhu,MinhuiXue,ShengWen,DongxiLiu, SuryaNepal,andYangXiang.2021.Snipuzz:Black-boxfuzzingofiotfirmware 9 CONCLUSION viamessagesnippetinference.InProceedingsofthe2021ACMSIGSACConference onComputerandCommunicationsSecurity.337–350. ThispaperproposesLATTE,thefirststaticbinarytaintanalysis [17] NSA Center for Assured Software. 2017. Juliet C/C++ 1.3. https://samate.nist.gov/SARD/test-suites/112. Accessed2023-5-1. poweredbyLLMs.Traditionaltaintanalyzersrelyonhumanex- [18] DanielFried,ArmenAghajanyan,JessyLin,SidaWang,EricWallace,FredaShi, perience to manually define patterns and rules, which severely RuiqiZhong,Wen-tauYih,LukeZettlemoyer,andMikeLewis.2022.Incoder:A limitstheeffectivenessandperformanceofthetechnique.LATTE generativemodelforcodeinfillingandsynthesis.arXivpreprintarXiv:2204.05999 (2022). performsdangerousflowslicingbytracingvulnerabledestinations [19] Github.2023.OpenSSL.https://github.com/openssl/openssl. Accessed2023-5-1. backtoexternalinputsources.LATTEthencombinescodesnippets [20] IvanGotovchits,RijnardVanTonder,andDavidBrumley.2018.Saluki:finding toconstructpromptsequences,leveragingLLMs’context-aware taint-stylevulnerabilitieswithstaticpropertychecking.InProceedingsofthe NDSSWorkshoponBinaryAnalysisResearch,Vol.2018. assistanceandhuman-likeunderstandingcapabilitiesforcodevul- [21] H.Han,J.Kyea,Y.Jin,J.Kang,B.Pak,andI.Yun.2023. QueryX:Symbolic nerabilityinspection.Basedonthesubstantialevaluations,LATTE QueryonDecompiledCodeforFindingBugsinCOTSBinaries.In20232023 IEEESymposiumonSecurityandPrivacy(SP)(SP).IEEEComputerSociety,Los outperformsthestateoftheartacrossalltaint-stylevulnerabil- Alamitos,CA,USA,3279–3295. https://doi.org/10.1109/SP46215.2023.00064 itytypes,suchasbufferoverflow,commandinjection,etc.LATTE [22] GrantHernandez,MariusMuench,DominikMaier,AlyssaMilburn,ShinjoPark, shedslightonthecombinationofprogramanalysisandLLMsfor TobiasScharnowski,TylerTucker,PatrickTraynor,andKevinButler.2022. FIRMWIRE:Transparentdynamicanalysisforcellularbasebandfirmware.In vulnerabilityanalysis. NetworkandDistributedSystemsSecuritySymposium(NDSS)2022. [23] SungminKang,JuyeonYoon,andShinYoo.2023.Largelanguagemodelsarefew- REFERENCES shottesters:Exploringllm-basedgeneralbugreproduction.In2023IEEE/ACM 45thInternationalConferenceonSoftwareEngineering(ICSE).IEEE,2312–2323. [1] WasiUddinAhmad,SaikatChakraborty,BaishakhiRay,andKai-WeiChang. [24] MingeunKim,DongkwanKim,EunsooKim,SuryeonKim,YeongjinJang,and 2021. Unifiedpre-trainingforprogramunderstandingandgeneration. arXiv YongdaeKim.2020.Firmae:Towardslarge-scaleemulationofiotfirmwarefor preprintarXiv:2103.06333(2021). dynamicanalysis.InAnnualcomputersecurityapplicationsconference.733–745. [2] ToufiqueAhmedandPremkumarDevanbu.2022.Few-shottrainingLLMsfor [25] R.Langner.2011. Stuxnet:DissectingaCyberwarfareWeapon. IEEESecurity project-specificcode-summarization.arXivpreprintarXiv:2207.04237(2022). Privacy9,3(2011),49–51. [3] ManosAntonakakis,TimApril,MichaelBailey,MattBernhard,ElieBursztein, JaimeCochran,ZakirDurumeric,JAlexHalderman,LucaInvernizzi,andMichalisConference’17,July2017,Washington,DC,USA PuzhuoLiu,etal. [26] CarolineLemieux,JeevanaPriyaInala,ShuvenduKLahiri,andSiddharthaSen. TiffanyBao,RuoyuWang,etal.2022. Arbiter:BridgingtheStaticandDy- 2023. CODAMOSA:Escapingcoverageplateausintestgenerationwithpre- namicDivideinVulnerabilityDiscoveryonBinaryPrograms.In31stUSENIX trainedlargelanguagemodels.InInternationalconferenceonsoftwareengineering SecuritySymposium(USENIXSecurity22).413–430. (ICSE). [51] ChunqiuStevenXiaandLingmingZhang.2022.Lesstraining,morerepairing [27] Wenqiang Li, Jiameng Shi, Fengjun Li, Jingqiang Lin, Wei Wang, and Le please:revisitingautomatedprogramrepairviazero-shotlearning.InProceedings Guan.2022.uAFL:Non-IntrusiveFeedback-DrivenFuzzingforMicrocontroller ofthe30thACMJointEuropeanSoftwareEngineeringConferenceandSymposium Firmware.InProceedingsofthe44thInternationalConferenceonSoftwareEngineer- ontheFoundationsofSoftwareEngineering.959–971. ing(Pittsburgh,Pennsylvania)(ICSE’22).AssociationforComputingMachinery, [52] ChunqiuStevenXiaandLingmingZhang.2023. Conversationalautomated NewYork,NY,USA,1–12. https://doi.org/10.1145/3510003.3510208 programrepair.arXivpreprintarXiv:2301.13246(2023). [28] PuzhuoLiu,DongliangFang,ChuanQin,KaiCheng,ShichaoLv,HongsongZhu, [53] ChunqiuStevenXiaandLingmingZhang.2023. KeeptheConversationGo- |
andLiminSun.2022. FindingVulnerabilitiesinInternal-binaryofFirmware ing:Fixing162outof337bugsfor0.42eachusingChatGPT. arXivpreprint withClues.InICC2022-IEEEInternationalConferenceonCommunications.IEEE, arXiv:2304.00385(2023). 5397–5402. [54] FabianYamaguchi,AlwinMaier,HugoGascon,andKonradRieck.2015.Auto- [29] FanLongandMartinRinard.2016.Ananalysisofthesearchspacesforgenerate maticinferenceofsearchpatternsfortaint-stylevulnerabilities.In2015IEEE andvalidatepatchgenerationsystems.InProceedingsofthe38thInternational SymposiumonSecurityandPrivacy.IEEE,797–812. ConferenceonSoftwareEngineering.702–713. [55] BurakYetiştiren,IşıkÖzsoy,MirayAyerdem,andErayTüzün.2023. Evalu- [30] XiaozhuMengandBartonPMiller.2016.Binarycodeisnoteasy.InProceedings atingtheCodeQualityofAI-AssistedCodeGenerationTools:AnEmpirical ofthe25thInternationalSymposiumonSoftwareTestingandAnalysis.24–35. StudyonGitHubCopilot,AmazonCodeWhisperer,andChatGPT.arXivpreprint [31] AlejandroMera,BoFeng,LongLu,andEnginKirda.2021. DICE:Automatic arXiv:2304.10778(2023). emulationofdmainputchannelsfordynamicfirmwareanalysis.In2021IEEE [56] BurakYetistiren,IsikOzsoy,andErayTuzun.2022. Assessingthequalityof SymposiumonSecurityandPrivacy(SP).IEEE,1938–1954. GitHubcopilot’scodegeneration.InProceedingsofthe18thInternationalConfer- [32] Mitre.2023. CommonVulnerabilityEnumeration. https://cve.mitre.org/. Ac- enceonPredictiveModelsandDataAnalyticsinSoftwareEngineering.62–71. cessed2023-5-1. [57] InsuYun,SanghoLee,MengXu,YeongjinJang,andTaesooKim.2018.QSYM:A [33] Mitre.2023.CommonWeaknessEnumeration.https://cwe.mitre.org/. Accessed practicalconcolicexecutionenginetailoredforhybridfuzzing.In27thUSENIX 2023-5-1. SecuritySymposium(USENIXSecurity18).745–761. [34] NSA.2013.Ghidra.https://ghidra-sre.org. Accessed2023-5-1. [58] ZhuoZhang,YapengYe,WeiYou,GuanhongTao,Wen-chuanLee,Yonghwi [35] OPENAI.2013.GPT-4.0.hhttps://platform.openai.com. Accessed2023-5-1. Kwon,YousraAafer,andXiangyuZhang.2021. Osprey:Recoveryofvariable [36] OpenAI.2023. Tokenizer. https://platform.openai.com/tokenizer. Accessed anddatastructureviaprobabilisticanalysisforstrippedbinary.In2021IEEE 2023-5-1. SymposiumonSecurityandPrivacy(SP).IEEE,813–832. [37] HammondPearce,BaleeghAhmad,BenjaminTan,BrendanDolan-Gavitt,and [59] YaowenZheng,AliDavanian,HengYin,ChengyuSong,HongsongZhu,and RameshKarri.2022. Asleepatthekeyboard?assessingthesecurityofgithub LiminSun.2019.FIRM-AFL:High-ThroughputgreyboxfuzzingofIoTfirmware copilot’scodecontributions.In2022IEEESymposiumonSecurityandPrivacy viaaugmentedprocessemulation.In28thUSENIXSecuritySymposium(USENIX (SP).IEEE,754–768. Security19).1099–1114. [38] NeilPerry,MeghaSrivastava,DeepakKumar,andDanBoneh.2022.DoUsers WriteMoreInsecureCodewithAIAssistants?arXivpreprintarXiv:2211.03622 (2022). [39] JannikPewny,BehradGarmany,RobertGawlik,ChristianRossow,andThorsten Holz.2015. Cross-architecturebugsearchinbinaryexecutables.In2015IEEE SymposiumonSecurityandPrivacy.IEEE,709–724. [40] SebastianPoeplauandAurélienFrancillon.2020. Symbolicexecutionwith SymCC:Don’tinterpret,compile!.In29thUSENIXSecuritySymposium(USENIX Security20).181–198. [41] JulianAronPrenner,HlibBabii,andRomainRobbes.2022.CanOpenAI’scodex fixbugs?anevaluationonQuixBugs.InProceedingsoftheThirdInternational WorkshoponAutomatedProgramRepair.69–75. [42] RuiQiaoandRSekar.2017.Functioninterfaceanalysis:Aprincipledapproachfor functionrecognitioninCOTSbinaries.In201747thAnnualIEEE/IFIPInternational ConferenceonDependableSystemsandNetworks(DSN).IEEE,201–212. [43] NiloRedini,AravindMachiry,DipanjanDas,YanickFratantonio,AntonioBianchi, EricGustafson,YanShoshitaishvili,ChristopherKruegel,andGiovanniVigna. 2017. BootStomp:Onthesecurityofbootloadersinmobiledevices.In26th USENIXSecuritySymposium(USENIXSecurity17).781–798. [44] NiloRedini,AravindMachiry,RuoyuWang,ChadSpensky,AndreaContinella, YanShoshitaishvili,ChristopherKruegel,andGiovanniVigna.2020.Karonte: Detectinginsecuremulti-binaryinteractionsinembeddedfirmware.In2020IEEE SymposiumonSecurityandPrivacy(SP).IEEE,1544–1561. [45] TobiasScharnowski,NilsBars,MoritzSchloegel,EricGustafson,MariusMuench, GiovanniVigna,ChristopherKruegel,ThorstenHolz,andAliAbbasi.2022.Fuz- zware:UsingPreciseMMIOModelingforEffectiveFirmwareFuzzing.In31st USENIXSecuritySymposium(USENIXSecurity22).1239–1256. [46] YanShoshitaishvili,RuoyuWang,ChristopherSalls,NickStephens,MarioPolino, AndrewDutcher,JohnGrosen,SijiFeng,ChristopheHauser,ChristopherKruegel, andGiovanniVigna.2016.SOK:(Stateof)TheArtofWar:OffensiveTechniques |
inBinaryAnalysis.In2016IEEESymposiumonSecurityandPrivacy(SP).138–157. https://doi.org/10.1109/SP.2016.17 [47] DominikSobania,MartinBriesch,CarolHanna,andJustynaPetke.2023. An analysisoftheautomaticbugfixingperformanceofchatgpt. arXivpreprint arXiv:2301.08653(2023). [48] NickStephens,JohnGrosen,ChristopherSalls,AndrewDutcher,RuoyuWang, JacopoCorbetta,YanShoshitaishvili,ChristopherKruegel,andGiovanniVigna. 2016. Driller:Augmentingfuzzingthroughselectivesymbolicexecution..In NDSS,Vol.16.1–16. [49] WeisongSun,ChunrongFang,YuduYou,YunMiao,YiLiu,YuekangLi,Gelei Deng,ShenghanHuang,YuchenChen,QuanjunZhang,HanweiQian,YangLiu, andZhenyuChen.2023.AutomaticCodeSummarizationviaChatGPT:HowFar AreWe? arXiv:2305.12865[cs.SE] [50] JayakrishnaVadayath,MoritzEckert,KyleZeng,NicolaasWeideman,Gokulkr- ishnaPraveenMenon,YanickFratantonio,DavideBalzarotti,AdamDoupe, |
2310.08837 Static Code Analysis in the AI Era: An In-depth Exploration of the Concept, Function, and Potential of Intelligent Code Analysis Agents GangFan XiaohengXie XunjinZheng fangang@antgroup.com xiexie@antgroup.com zhengxunjin.zx@antgroup.com AntGroup AntGroup AntGroup Shenzhen,China Shenzhen,China Shenzhen,China YinanLiang PengDi lyn249877@antgroup.com dipeng.dp@antgroup.com AntGroup AntGroup Shenzhen,China HangZhou,China ABSTRACT The traditional techniques of code error detection and func- Theescalatingcomplexityofsoftwaresystemsandaccelerating tionallogicverification,includingcodereviews,unittesting,and developmentcyclesposeasignificantchallengeinmanagingcode integratedtesting,havebeenthecornerstoneofsoftwarequality errorsandimplementingbusinesslogic.Traditionaltechniques, assurancefordecades.However,theyareinherentlylabor-intensive whilecornerstoneforsoftwarequalityassurance,exhibitlimita- andoftenfallshortwhenconfrontedwithcomplexfunctionallogic. tionsinhandlingintricatebusinesslogicandextensivecodebases. Thesemethodsareheavilyreliantontheexpertiseofthedevelopers To address these challenges, we introduce the Intelligent Code andthecomprehensivenessofthetestcases,bothofwhichmay AnalysisAgent(ICAA),anovelconceptcombiningAImodels,en- notsufficientlyaccountforallpossibleusagescenariosorintricate gineeringprocessdesigns,andtraditionalnon-AIcomponents.The functionallogicpaths. ICAAemploysthecapabilitiesoflargelanguagemodels(LLMs) Therapidadvancementofsoftwaredevelopmentmethodolo- suchasGPT-3orGPT-4toautomaticallydetectanddiagnosecode gies, such as Agile and DevOps, emphasizes the need for swift errorsandbusinesslogicinconsistencies.Inourexplorationofthis developmentanddeploymentcycles.Thisaccelerationamplifies concept,weobservedasubstantialimprovementinbugdetection the necessity for an automated, intelligent, and efficient mech- accuracy,reducingthefalse-positiverateto66%fromthebaseline’s anismfortheidentificationandrectificationofcodeerrorsand 85%,andapromisingrecallrateof60.8%.However,thetokencon- functionallogicinconsistencies.Theurgencyforsuchasystemis sumptioncostassociatedwithLLMs,particularlytheaveragecost particularlypronouncedinthecontextofmodernsoftwaresystems, foranalyzingeachlineofcode,remainsasignificantconsideration characterizedbyextensivecodebases,multifacetedarchitectures, forwidespreadadoption.Despitethischallenge,ourfindingssug- andsophisticatedfunctionallogic. gestthattheICAAholdsconsiderablepotentialtorevolutionize ThecontemporarydigitallandscapeheraldstheadventofLLMs softwarequalityassurance,significantlyenhancingtheefficiency andintelligentagenttechniques,withexamplessuchasAutoGPT andaccuracyofbugdetectioninthesoftwaredevelopmentprocess. standingout.Theseburgeoningtechnologiescarvenewtrajectories Wehopethispioneeringworkwillinspirefurtherresearchand fordealingwithenduringchallengesinsoftwareengineering.By innovationinthisfield,focusingonrefiningtheICAAconceptand harnessingthepowerofartificialintelligenceandmachinelearning, exploringwaystomitigatetheassociatedcosts. thesestate-of-the-arttechnologiesofferautomated,intelligent,and efficientsolutions,therebybreathingnewlifeintolongstanding, KEYWORDS unresolvedproblems. Thenotionofanintelligentagentrepresentsasystemthatper- SoftwareEngineering,CodeErrorDetection,BusinessLogicVerifi- ceivesitsenvironmentandtakesactionstomaximizeitschancesof cation,MachineLearning,ArtificialIntelligence,IntelligentCode achievingitsgoals.Appliedtosoftwareengineering,theseagents AnalysisAgent canbeprogrammedtoautomaticallyidentifyanddiagnosecode errorsandfunctionallogicissues,potentiallyrevolutionizingsoft- 1 INTRODUCTION waredevelopmentprocesses. Therisingcomplexityofsoftwaresystemsinourdigitizedworld Inthisresearch,weintroducetheconceptofanICAA—anovel poseschallengesinsoftwareengineering,particularlyinmanaging ideathat,tothebestofourknowledge,hasnotbeenpreviously codeerrorsandimplementingfunctionallogic.Failuretoaddress exploredinexistingliterature.Thisagentleveragesthepowerof theseissuespromptlycanresultinsystemmalfunctions,security AI models, engineering process designs, and traditional non-AI vulnerabilities,andanegativeuserexperience.Theconsequences components to significantly improve bug detection in software includeeconomiclosses,reputationdamage,andpotentialsocietal developmentprocesses. disruption.Timelyidentificationandresolutionofcodeerrorsand functionallogicissuesarecriticalforensuringthereliabilityand properfunctioningofsoftwaresystems. 3202 tcO 31 ]ES.sc[ 1v73880.0132:viXraTrovatoandTobin,etal. Ourobjectiveistoinvestigateandexplorewhethertheapplica- rapiditerations,continuousintegration,andseamlesscollabora- tionofintelligentagents,inconjunctionwithcutting-edgetech- tionbetweendevelopmentandoperationsteams[Becketal.2001; nologieslikeLLMs,couldserveasapowerfultooltomitigatethese Kimetal.2016].Thesemethodologieshaverevolutionizedsoftware entrenchedissues.Weproposeasolutionthatleveragesanintel- production,enablingtheswiftcreationofrobustandresponsive ligentagentgroundedinstate-of-the-artLLMssuchasGPT-3or software.However,theyalsointroducenewchallenges,particularly GPT-4.Thisintelligentagentaimstoautomaticallydetectanddi- inmaintainingcodequalityandensuringtheaccurateimplementa- |
agnosecodeerrorsandfunctionallogicinconsistenciesthrougha tionofbusinesslogicinlarge-scale,complexsoftwaresystems. sophisticatedprocessofanalysisanddecision-making.Weposit thatourapproachwillconsiderablyaugmentthefieldofsoftware 2.2 AutomatedCodeErrorDetection qualityassurance,renderingitmoreefficient,precise,andcost- Automatederrordetectionisawell-establishedareaofresearch, effective. withtheobjectivetoreducetheburdenofmanualcodereviews TheconceptoftheICAAisabroadandversatileone,withthe andtesting[Besseyetal.2010].Severaltoolshavebeendeveloped potentialtoencompassawidevarietyofdesignsandmethodologies. forthispurpose,withstaticanalysistools,suchasFindBugsfor Inthiswork,wepresentonepossiblerealizationofthisconcept. Java, being widely used [Ayewah and Pugh 2008]. These tools Ourimplementationdoesnotclaimtobetheonlyordefinitive inspectcodewithoutexecutingit,detectingpotentialbugsand approachtodesigningaICAA.Rather,itaimstoprovideaninitial vulnerabilities.Despitetheirbenefits,suchtoolsoftenproducefalse explorationoftheconcept’spotential,demonstratingthepowerof positivesandstrugglewiththecomprehensionofcomplexbusiness combiningAImodels,engineeringprocessdesigns,andtraditional logic[Johnsonetal.2013a],whichaddsnoiseanduncertaintytothe non-AIcomponents. developmentprocess.Dynamicanalysistools,whichanalyzecode Ourprimarycontributionsareasfollows: duringorafteritsexecution,offeranalternativeapproach.While thesetoolscandetecterrorsthatstaticanalysismightmiss,they (1) We propose the concept of the ICAA This is, to our alsohavelimitations,suchasperformanceoverheadanddifficulty knowledge,thefirstworkthatintroducesandexploresthis inidentifyingnon-deterministicbugs[Cornelissenetal.2009]. concept,markingasignificantadvancementinthefieldof codeanalysis. 2.3 FunctionalLogicVerification (2) Wepresentaspecificexplorationofthisconcept,demon- stratingitspotentialtosignificantlyimprovebugdetection. Ensuringtheaccurateexecutionofintendedfunctionallogicisan- OurapproachcombinesAImodels,engineeringprocess othervitalaspectofsoftwarequalityassurance.Traditionalmeth- designs, and traditional non-AI components, effectively odsofteninvolvemanualinspectionandextensivedocumentation, leveragingthestrengthsofeach. whichcanbebothlaboriousandpronetohumanerror[Balzarotti (3) Weprovideempiricalevidence,nottoshowsuperior- etal.2010].Automatedsolutions,suchassymbolicexecutionand ity,buttoshedlightonthepotentialofourapproach.We modelchecking,havebeenproposed;however,thesesolutionsof- presentdataandresultsthathelpillustratethecapabili- tenfacechallengeswhendealingwithlarge-scale,intricatesystems tiesandpossibilitiesofthisnewmethodintermsofbug duetoscalabilityandstateexplosionproblems[Clarkeetal.1999; detectionaccuracyandfalse-positiverate. King1976]. Bypresentingthisnewconceptandasuccessfulexplorationof 2.4 LLMsandIntelligentAgents it,wehopetoinspirefurtherinnovationsandvariedapproachesin TheadventofLLMssuchasGPT-3andGPT-4hasrevolutionizedau- thefieldofcodeanalysis. tomatedsoftwareengineering,offeringaprofoundunderstanding Theremainderofthispaperdelvesintothechallengesincode oflanguage,context,andsyntax[Brownetal.2020;OpenAI2021]. errordetectionandfunctionallogicverification,providingacom- Thesemodels,builtuponextensivetexttraining,havefounddiverse prehensivebackgroundandreviewingrelatedworkinthisfield.We applicationsincodingtaskslikecodecompletion,codetranslation, thenintroducetheconceptoftheICAAandshowcasetwospecific andbugdetection,wheretheyhaveshownpromisingresults[Feng implementationsasexamples.Followingthis,wepresenttheresults etal.2020;KarampatsisandSutton2020;Svyatkovskiyetal.2020]. ofourexperiments,focusingontheperformanceoftheintelligent AsignificantstrideintheLLMfieldwastheintroductionofCode- agentsindetectingcodeerrorsandfunctionallogicissues.Wecon- BERTbyMicrosoftandthemorerecentCodeLlama[Rozièreetal. cludebydiscussingtheimplicationsofourfindings,comparingthis 2023].Thesetransformer-basedmodels,trainedonavastcorpusof newmethodwithtraditionaltechniques,andsuggestingpotential codefromGitHubrepositories,haveshownremarkablecapabilities directionsforfutureresearch. intaskssuchascodesummarization,codetranslation,andgen- eratingcodefromnaturallanguageprompts.Theirperformance 2 BACKGROUNDANDRELATEDWORK underscoresthepotentialofLLMsinunderstandingandgenerating code,openingupexcitingopportunitiesfortheirincorporationinto 2.1 EvolutionofSoftwareDevelopment intelligentagentsforstaticcodeanalysis. Methodologies Atthesametime,theconceptofintelligentagents—systems Thelandscapeofsoftwareengineeringhasundergonesignificant capableofinterpretingtheirenvironmentandtakingactionsto transformationoverthepastdecades.Traditionalwaterfalldevelop- achievetheirgoals—hasbeengarneringinterestinsoftwareengi- mentmodelshavegivenwaytoAgileandDevOps,whichpromote neering.AcaseinpointisAutoGPT[Richards2023],anintelligentStaticCodeAnalysisintheAIEra:AnIn-depthExplorationoftheConcept,Function,andPotentialofIntelligentCodeAnalysisAgents agentusedinautomatedsoftwaretesting,requirementsanalysis, andgeneratetextakintohumancommunicationhassparkedthe |
andbugdetection[Chenetal.2018;Radfordetal.2019]. prospectoftheirapplicationincodeanalysisandbugdetection. LangChain[Yaoetal.2023]isapowerfulframeworkfordevel- However,directlyapplyingthesemodelstocodeanalysisand oping applications powered by language models, serving as an bugdetectionrevealsseverallimitations.Thoughtheyhavedemon- intelligentagentinvariouscode-relatedscenarios,includingcode stratedabilitiesintaskssuchascodegeneration,summarization, analysis. LangChain enables developers to build context-aware andevencertaintypesofbugdetection,theireffectivenessinde- applicationsthatleveragethecapabilitiesoflanguagemodelsto tectingbugsrelatedtofunctionalcorrectnessandunderstanding reason,providecodeinsights,andtakeappropriateactionsbased codesemanticsisquestionable[Johnsonetal.2013b]. ontheprovidedcontext. 3.2.1 InvestigatingthePerformanceofLLMsinBugDetection. To SemanticKernel[Microsoft2023]isanopen-sourceSDKthat delvedeeperintotheselimitations,anempiricalinvestigationwas enables easy integration of AI services, such as OpenAI, Azure conductedusingGPT-3.5-turbo[Pengetal.2023],avariantofGPT-3, OpenAI,andHuggingFace,withprogramminglanguageslikeC# toidentifyinconsistenciesbetweencodecommentsandtheircorre- andPython.ByutilizingSemanticKernel,developerscancreate spondingimplementations.Thedataset,composedofcodeblocks AIapplicationsthatcombinethestrengthsofbothconventional fromvariousGitHubrepositories,coveredarangeofprogramming programmingandAIservices. languagesandapplicationdomains. TheBabyAGI[Nakajima2023]projectisanopen-sourceimple- Theexperimententailedseveralstages: mentationofanintelligentagenthostedonGitHub.Thisagent utilizesartificialintelligence(AI)capabilities,particularlynatural (1) Arandomsamplingtechniquewasemployedon540million languageprocessing(NLP),tomanagetasks.Itmakesuseofthe methodcodeblocksinGitHubrepositorieswithstarratings OpenAIAPIandvectordatabaseslikeChromaorWeaviate. greaterthan10,ensuringdiverseprogramminglanguage Intelligentagents[TalebiradandNadiri2023]aresoftwaresys- caseswereconsidered.Atotalof6000datasampleswere temsdesignedtoperceivetheirenvironment,reasonaboutit,and selected,eachrepresentingthecodecontentofafile. takeappropriateactionstoachievespecificgoals.Theypossessad- (2) The6000datasampleswerededuplicated,yielding5712 vancedcapabilitiessuchasdataanalysis,decision-making,learning uniquedatasamples. fromexperience,andinteractionwithusersorothersystems. (3) A second round of random sampling was conducted on theseuniquesamples,drawing500samplesperlanguage, Inlightofthesedevelopments,thispaperextendstheselinesof summinguptoatotalof3000datasamples. researchbydevelopinganintelligentagentthatleveragesanLLM (4) Thesesampleswerethensplitintocode-commentpairs, forautomatedcodeerrordetectionandfunctionallogicverification. selectingonlythosewithnon-emptymethodbodiesand OurworkaimstobridgethegapbetweenthepotentialofLLMs commentsofmorethan100characters.Thisresultedina andintelligentagentsandtheirpracticalapplicationinenhancing totalof2380datasamples. softwarequalityassurance. (5) GPT-3.5-turbowasthentaskedwithanalyzingthesepairs forinconsistenciesusingaprompttemplate(Listing1). 3 LIMITATIONSANDMOTIVATIONS Listing1:Prompttemplateforanalyzingcodeinconsistencies 3.1 ConstraintsofStaticCodeAnalyzers Staticcodeanalysistoolsserveasapivotalelementinensuring Donotinclude anyexplanations in yourresponses. Find if software quality, facilitating the recognition of potential issues there are inconsistencies betweenthesource codeandthe withincode,includingbugs,codesmells,andsecurityvulnerabili- comment. Forget aboutthe details and just focus onanyinconsistency ties.Theseinstrumentsconducttheiranalysisonsourcecodeprior betweenthe intention of the commentandthe toexecution,primarilyconcentratingonthecode’ssyntacticand implementationofthe code. Thegenerated result shouldbe in JSONformat,withthe structuralcharacteristics. following fields: Nonetheless, these apparatuses have noteworthy limitations. "is_inconsistent": This shouldbe true if the codeandthe Their reliance on rules often culminates in a high incidence of commentareinconsistent, and false otherwise. "explanations_and_suggestion": Adescription of whythecode falsepositivesandnegatives[Besseyetal.2010],therebyunder- andthe commentareinconsistent, andsuggestions onhow miningtrustinthesetoolsandhamperingproductivityduetothe to fix it. necessityofmanualreviewforflaggedconcerns.Additionally,tra- "fixed_comment":Therevised comment,edited to remain consistent withthe code. ditionalstaticanalysistoolsencounterdifficultiesinidentifying "fixed_code": Therevised code, edited to remain consistent bugspertainingtofunctionalcorrectnessorbusinesslogic–they withthe comment. Theoutputformat is as follows: aredeficientintheircapacitytoapprehendtheintricatemeanings {{ encapsulatedincommentsandtheobjectivesofthedevelopers, "is_inconsistent": <is_inconsistent> whichiscrucialtodetectmoreelusivebugs. "explanations_and_suggestion": <explanations_and_suggestion >, "fixed_comment":<fixed_comment> 3.2 ThePotentialandChallengesofLLMsin "fixed_code": <fixed_code> }} BugDetection Code: TheadventofLLMs,likeGPT-3[Brownetal.2020],hasinstigated ```<CodeLanguage> asignificantshiftinvariousAIfields.Theirabilitytocomprehend <CodetoInspect>TrovatoandTobin,etal. |
``` GPT-3.5-turboResponse ManualInterpretation Count FalseNegative 2 Comment: Yes,theyareconsistent TruePositive 218 <CommenttoInspect> Unknown Ambiguous 34 FalsePositive 147 No,theyarenotconsistent TrueNegative 31 3.2.2 AnalysisandInterpretationofExperimentalResults. There- Indeterminate 8 sultsrevealedthatwhile53.4%ofresponsesindicatedinconsisten- Table1:InterpretationofGPT-3.5-turboResponses cies,46.1%didnot.Amanualinspectionandlabelingof440ran- domlyselectedcaseswereconductedtounderstandtheseresults better,assummarizedinTable1.Themanualinspectionrevealed The comment mentions that the kernel size must be thatasignificantportionoftheresponsesindicatingnoinconsis- odd, but the code does not enforce this. To tencywereincorrect,despiteamajorityofresponsesindicating make the code consistent with the comment, inconsistenciesbeingaccurate. add a check to ensure that the kernel size is ThesefindingsunderscorethepotentialofLLMsindetecting odd. Also, there is a typo in the comment ( semanticinconsistencies—ataskoftenchallengingfortraditional simga instead of sigma). staticcodeanalyzers.Anillustrativecaseofthispotentialisshown inFigure2,whereaninconsistencywasdetectedinSaliencyMapper Theobservedelevatedfalse-positiverateinusingLLMsforbug [DabkowskiandGal2017],aPytorchimplementationofRealTime detectioncouldpotentiallystemfromacombinationofseveralfac- ImageSaliencyforBlackBoxClassifiers.Thecommentimpliesthe tors.Herearethethreeprimaryfactorsthatmightbecontributing needforanoddvalueforaparticularparameter,butthereisno tothehighfalse-positiverate: correspondingenforcementinthecode,unequivocallyindicatinga (1) SyntaxvsSemantics:LLMslikeGPT-3.5-turbo,whilepro- requirementthathasbeenoverlooked. ficientinunderstandingsyntaxandgrammar,maystruggle However,theresultsalsohighlightaconsiderablefalse-positive withthesemanticsofcode.Understandingcodesemantics rate,surpassingwhatistypicallyobservedwithstandardstatic requiresagraspoftheunderlyinglogic,variouscodestruc- analysistools.ThissuggeststhatwhileLLMsarepotenttoolsfor tures,anddevelopers’intentions,whichmightnotbefully understanding and generating text, their direct deployment for capturedbythesemodels. staticcodeanalysisremainsachallenge. (2) ContextualGaps:Codeisoftenwrittenwithinaspecific context,whichiscrucialforunderstandingtherationale behindacommentoracodesnippet.LLMsmaynotfully Listing2:Prompttemplateforanalyzingcodeinconsistencies comprehendthebroadercontextofthecode,potentially leadingtomisinterpretationsandfalsepositives. Code: (3) DomainKnowledgeandLLMLimitations:Certaincode def gaussian_blur(_images, kernel_size=55, sigma commentsrequiredomain-specificknowledge,suchasfa- =11): ''' Very fast, linear time gaussian blur, miliaritywithspecificalgorithms,softwareframeworks,or using separable convolution. Operates on applicationdomains.Ageneral-purposelanguagemodel batch of images [N, C, H, W]. likeGPT-3.5-turbomightlackthisdomain-specificknowl- Returns blurred images of the same size. edge,leadingtoinaccuracies.Additionally,inherentLLM Kernel size must be odd. phenomenalikehallucinations(generatinginformationnot Increasing kernel size over 4*simga yields presentintheinput)andrandomness(theinherentunpre- little improvement in quality. So kernel dictabilityofthemodel)couldalsopotentiallycontribute size = 4*sigma is a good choice.''' tofalsepositives. kernel_a, kernel_b = _gaussian_kernels( kernel_size=kernel_size, sigma=sigma, Anotherissueobservedwastheuncontrollableoutput.Wewere chans=_images.size(1)) unabletoeffectivelycontrolLLMs’outputcontent,particularly kernel_a = torch.Tensor(kernel_a) theformat,leadingtofrequentgenerationofmalformedjsonre- kernel_b = torch.Tensor(kernel_b) sponses.Furthermore,LLMssometimesattempttooutputtheline if _images.is_cuda: numberandthepositionofprogrammaticcode.However,inmost kernel_a = kernel_a.cuda() cases(147/186),theseoutputswereincorrect,posingchallenges kernel_b = kernel_b.cuda() forpotentialintegrationandautomaticprocessingwithstaticcode _rows = conv2d(_images, Variable(kernel_a, analyzers. requires_grad=False), groups=_images.size Theseobservationsunderscoretheneedforamorerefinedap- (1), padding=(kernel_size / 2, 0)) return conv2d(_rows, Variable(kernel_b, proachtocodeanalysis.WhileLLMsofferpromisingcapabilities, requires_grad=False), groups=_images.size theirlimitations,particularlyintermsoffalse-positiveratesand (1), padding=(0, kernel_size / 2)) outputcontrol,posesignificantchallenges.Thereisaclearneces- sityforasolutionthatcanleveragethestrengthsofLLMswhile GPT-3.5-turbo Response: controllingtheirlimitationseffectively.ThissolutionshouldalsobeStaticCodeAnalysisintheAIEra:AnIn-depthExplorationoftheConcept,Function,andPotentialofIntelligentCodeAnalysisAgents abletoadapttoautomatedprocessesandintegratesmoothlywith learningalgorithmsallowittolearnfromboththeinputsitreceives staticcodeanalyzers,addressingthechallengesposedbycurrent andtheoutputsitgeneratesduringtheanalysisprocess. methodologiesinbugdetection. AstheICAAbeginstheanalysis,ittakesintoaccounttheinput |
Toaddresstheserequirements,inthefollowingsection,wewill sourcecode,itsstructure,andthevariousdependencieswithinthe introduceanddefinetheconceptofanICAAandexplorehowit code.ThemachinelearningalgorithmsallowtheICAAtolearn canenhancetheaccuracyandefficiencyofcodeanalysistasks. fromtheseinputs,incrementallybuildingamodelofthecode’s structureandbehavior.ThismodelevolvesastheICAAencounters 4 THEINTELLIGENTCODEANALYSISAGENT newcodepatterns,enhancingitsunderstandingoftheoverallcode landscape. Theexplorationofexistingmethodologies,namelytraditionalstatic Similarly,theICAAlearnsfromtheoutputsgeneratedduring codeanalysistoolsandLLMs,hasunderscoreddistinctstrengths theanalysisprocess.EachtimetheICAAflagsapotentialissue andchallenges.Staticcodeanalysistoolsexcelinanalyzingthesyn- or evaluates the impact of a particular code pattern, it records taxandstructureofthecode,whereasLLMsdemonstrateapromis- andlearnsfromtheoutcome.Thiscontinuouslearningallowsthe ingabilitytounderstandandgeneratehuman-liketext.However, ICAAtobecomemoreaccurateandefficientovertimeinidentifying theformeroftenstruggleswithsemanticinconsistencies,andthe potentialissuesandtheirassociatedimpact. latterexhibitshighfalse-positiveratesinbugdetection. Inlightoftheseinsights,weproposetheconceptofanICAA. Thisisnotaspecificdesign,butratherastrategicapproachthataims 4.3 ICAAasaDecision-makingAgent tosynthesizethestrengthsofbothstaticcodeanalysistoolsand Beyonditsanalyticalcapabilities,theICAAisanagent,signifying LLMs.Itisanembodimentofanintelligentlayerthatorganically thatitpossessesdecision-makingcapabilities.Thisrepresentsa integratesthesetools,aimingtoleveragetheirindividualstrengths significant departure from traditional static code analysis tools, whilemitigatingtheirlimitations. which are typicallynot designed tomake decisions. The ICAA, TheICAAisenvisionedtoharnessthestructuralandsyntactic however,canevaluateandprioritizepotentialissuesbasedontheir analysisstrengthsofstaticcodeanalysistools.Simultaneously,it anticipatedimpactonthesoftware’sfunctionality.Thiscapability aimstocapitalizeonthesemanticandcontextualunderstanding allowsdeveloperstofocusonresolvingthemostsignificantissues providedbyLLMs.Theagentisthusdesignedtoprovideamore first,therebyimprovingtheefficiencyofthedebuggingprocess. comprehensiveunderstandingofthecode,itssemantics,andthe In summary, the ICAA is a dynamic, learning, and decision- intentionsencapsulatedinthecomments. makingsystemwithintherealmofstaticcodeanalysis.Itsability Therefore,themotivationforproposingthisconceptisrooted tocontinuouslylearnfromthecodeitanalyzes,andfromtheinputs inthedesiretobuilduponthepotentialsandovercomethelimi- andoutputsduringtheanalysisprocess,combinedwithitsability tationsofcurrentmethodologies.ByemployinganICAA,weaim tomakeinformeddecisionsaboutbugprioritization,representsa toprovideamorerobust,efficient,andholisticapproachtocode substantialadvancementinthefieldofstaticcodeanalysis.The analysis. introductionoftheICAAisanticipatedtosignificantlyenhance theefficiencyofthedebuggingprocess,improvecodequality,and 4.1 DistinguishingtheICAAfromTraditional contributetothedevelopmentofmorerobustsoftwaresystems. StaticCodeAnalysis TobetterunderstandthepracticalimplementationofanICAA, wewillintroducetwoexampledesignsthathighlightitscapabilities Traditionalstaticcodeanalyzerstypicallyrelyonfixedrulesand andfunctionalitiesinnextsection. patternstoidentifypotentialissueswithinthesourcecode,actingas arule-basedsystemthatflagsprogrammingerrors,bugs,orother issuesaccordingtopredefinedpatterns.Whilethesetraditional 5 AGENTEXAMPLES toolshavebeeninstrumentalinachievingacertainlevelofsoftware HavingintroducedtheconceptoftheICAA,thissectionaimsto quality,theireffectivenessisinherentlylimitedbythestaticsetof provideconcreteexamplestoenhanceunderstandingofitsdesign rulestheyemploy.Thislimitationpotentiallyresultsinoverlooking andfunctionality.WewillpresenttwodistinctexamplesofICAA, complexorrarebugsthatfalloutsidethesepredefinedpatterns. eachshowcasingauniqueapplication:bugdetectionandintention- codeconsistencychecking. 4.2 ICAA:AStepBeyondThroughMachine Ourapproachtodesigningtheseagentsinvolvescreatingaspe- LearningIntegration cificchainofmodelsorthoughtprocesses.Thisenablesustode- TheICAAtranscendstheselimitationsbyingeniouslyintegrating composethebroadertaskofcodeanalysisintomultiplemanageable machinelearningalgorithmsintoitsoperationalframework.This components.Eachagent’scompositionalstructureencompasses integrationallowstheICAAtocontinuouslylearnfromthecode bothartificialintelligenceandconventionalcomponentssuchas itanalyzes,facilitatingthedevelopmentofasophisticatedunder- parsers.Thisinnovativemethodologyillustrateshowintegrating standingofthemakeupof"good"codeandthepatternsthatmight machinelearningcanamplifythecapabilitiesoftraditionalstatic denotepotentialissues. codeanalysistechniques. Thefirstexamplewepresentisanagentdesignedforbugdetec- 4.2.1 LearningfromInputsandOutputs. Thelearningaspectofthe tion,highlightinghowanICAAcaneffectivelyidentifyandflag |
ICAAisnotlimitedtothecodeitanalyzes.TheICAA’smachine potentialerrorswithinacodebase.Thesecondexample,ontheTrovatoandTobin,etal. otherhand,focusesonanagenttaskedwithensuringintention- (2) Actions:Actionsarethestepstakenbytheagentbased codeconsistency,demonstratinghowanICAAcanassistinmain- onitsthoughts.Theseincludesendingpromptsorcode tainingalignmentbetweenadeveloper’sintentionsandtheactual snippets to the LLM, processing the received responses, implementationincode. andutilizingtoolssuchasstaticanalyzersandparserstoin- Bydetailingtheseexamples,weaimtoprovideaclearerinsight teractmoreeffectivelywiththeenvironment.Theprimary intothepotentialapplicationsofanICAAandhowitcantransform goaloftheseactionsistoenhancetheagent’sunderstand- thelandscapeofcodeanalysis.Thefollowingsubsectionsprovide ingofthecodeandimproveitsanalysiscapabilities. anin-depthexplorationofeachexample,elucidatingourapproach (3) Observations:Observationsarethefeedbackorresponses andtheuniquefunctionalityofeachagent. receivedfromtheLLM.Theagentusestheseobservations torefineitsthoughtsanddecideonthenextactions,ensur- 5.1 ReActBugDetectionAgent ingadynamicandresponsiveinteractionprocess. Wefirstoutlinetheimplementationdetailsofanintelligentagent Theagent’soperationsignificantlybenefitsfromitsinteraction designedforcodeanalysis,drawinginspirationfromtheReAct withtheLLM,enablingittogenerateinsightfulperspectivesand framework[Yaoetal.2023].Theagentformsahierarchicalstruc- boostitsperformanceincodeanalysistasks.Byreferencingpre- turecomposedofseveralsub-agents,eachcontributingtoitsoverall viousdialogues,theagentavoidsredundantqueries,ensuringa capability.ThisisinaccordancewiththeconceptinAIthatintel- moreefficientandeffectiveinteractionprocess.Thisstrategynot ligentagentscanbecomprehendedasahierarchyofsub-agents onlyconservescomputationalresourcesbutalsoallowstheagent workinginunison.Thisagentintegratesatoolboxthatincludes toconcentrateontherelevantaspectsofthecodeanalysistask. context-awaresplitting,coderetrieval,documentationretrieval, websearch,andstaticcodeanalysistools,alldesignedtoaidde- 5.1.4 ActionsandTools. Oncetheinputisreceived,theagentem- velopersinanalyzingandcomprehendingcode-relatedqueries.As ploysitstoolboxoftoolstoperformvariousactionsbasedonthe depictedinFigure1,theagentiscomposedofseveralcomponents, requirements.Theseactionsinclude: theindividualfunctionalitiesofwhichwewilldiscussinfurther • Context-AwareSplittingTool:Toaddressthechallenge detail. ofanalyzinglargecodesnippets,wehaveincorporateda 5.1.1 TaskInterpretationandPlaning. Inthisstep,theagentre- context-awaresplittingtool.Thistoolconsidersthecode ceivesauserqueryasinput.ByusingaprompttoqueryaLLM,the context and intelligently splits large code snippets into agentcaninterpretthetaskanddeviseabasicworkplanforbug smaller,manageablesegments.Byprovidingtheagentwith detection.Thiscouldinvolve,forexample,examiningaparticular moregranularinput,thistoolenhancestheagent’sperfor- codesnippetordefiningthetypesofbugsofinterestforaspecific manceineffectivelyanalyzinganddetectingbugswithin query.Thereturnedworkplanservesasaguidelinefortheentire largecodesnippets. analysisprocess. • CodeRetrievalTool:Implementedusingavectorstore, thistoolconvertsthequeryintoavectorandperformsa 5.1.2 Codeprepossessing. Atthisstage,theagentdownloadsthe searchinthevectorspace.Thismethodenablestheagent appropriatecodefromtheinputandperformspreprocessing.The tosearchandretrieverelevantcodeexamplesorsnippets primarytaskhereinvolvescategorizingthesourcefilesbasedon fromcoderepositorieslikeGitHub.Toensureaccurateand theirtypesandprogramminglanguages.Additionally,weparsethe meaningfulvectorrepresentations,wecarefullyselected sourcecodeandstoreitinastructuredmannerwithinadatabase. anadvancedembeddingmodel[Wangetal.2022],which Thus, we store all the documents in one database and all code istrainedonlarge-scaletextcorpora,capturingsemantic snippetsinanother.Thisarrangementfacilitatesefficientquerying relationshipsandcontextualinformation. duringtheoperationoftheReActloop. • DocumentationRetrievalTool:SimilartotheCodeRe- 5.1.3 ReAct-basedAnalysisAgent. Thecentralpartoftheagent’s trievalTool,thistoolusesvectorspaceforefficientretrieval designinvolvestheintelligentagentthatacceptsaninputqueryora ofrelevantdocumentationorAPIreferencesforvarious codesnippetforanalysis.Thisinputcouldbeaspecificcode-related programminglanguages,frameworks,orlibraries.Itaidsin questionorapieceofcodethatneedsthoroughscrutiny. providinginformationaboutusage,syntax,andavailable Theintelligentagent’sfunctionalityisdeeplyrootedintheRe- featuresrelatedtotheinputqueryorcodesnippet. Actframework,realizedthroughitsinteractionswiththeLanguage • WebSearchTool:Thistoolperformssearchestocollect LearningModel(LLM).Thisframeworkincludesthreecriticalcom- additionalinformationfromexternalresourcesrelatedto ponents:Thoughts,Actions,andObservations. theinputqueryorcodesnippet.Itcanretrievetutorials, articles,andforumdiscussionstosupplementtheanalysis. (1) Thoughts:Thethoughtscomponentservesasthebrain • StaticCodeAnalysisTool:Thistoolperformsstaticcode |
oftheagent,assessingthecurrentsituationandguiding analysisontheprovidedcodesnippet.Itchecksforcom- theentireanalysisprocess.Itusestheconversationhistory moncodingerrors,suggestsimprovements,providescode -thecomprehensiverecordofthedialoguebetweenthe metrics,andidentifiespotentialperformancebottlenecks. agentandtheLLM,includingthesequenceofpromptsand responses - toinform its thinking. This context enables Astheagentexecutesitstoolboxactions,itengagesinadynamic theagenttogeneratewell-informed,contextuallyrelevant thinkingprocessthatmakesitsapproachadaptiveandintelligent. thoughts. Thisthinkingprocessisiterative,whereeachcycleofactionsandStaticCodeAnalysisintheAIEra:AnIn-depthExplorationoftheConcept,Function,andPotentialofIntelligentCodeAnalysisAgents Figure1:ReActBugDetectionAgent observationsrefinestheagent’sunderstandingoftheinputquery ThedecisionbetweenLLMsandstaticanalysistoolsdependson orcodesnippet.Astheagentinteractswiththeenvironment,it factorssuchasthecomplexityofthecodebase,theavailabilityof continuouslyupdatesitsinternalmodel,adjustsitsactions,and labeleddatasets,andthedesiredaccuracylevel.Regardlessofthe incorporatesnewobservations.Thisprocessallowstheagentto chosenapproach,theFalsePrunerAgentisdesignedtoincrease evolveitsstrategiesonthefly,makingitcapableofhandlingawide thereliabilityoftheresponse. arrayofcode-relatedtaskswithimprovedproficiencyovertime. Theagent’sdesignisnotonlyadaptiveandintelligentbutalso 5.2 Code-IntentionConsistencyChecking anticipatespotentialenhancements.Onesuchkeyenhancement Agent is the integration of a Human-in-the-Loop (HITL) strategy[Wu ThesecondexampledesignoftheICAA,asillustratedinFigure2, etal.2022],whereahumancollaboratorcouldbeinvolvedinthe targetstheidentificationofinconsistenciesbetweentheintended decision-makingprocess,providingreal-timeinputstotheagent. functionalitiesofacodesegmentanditsactualimplementation. ThepotentialofthisHITLstrategy,althoughnotcurrentlyimple- Thisdesignsignifiesanadvancementovertraditionalstaticcodean- mented,couldbeasignificantsteptowardscreatingmorerobust alyzersbyencompassinganunderstandingoftheintentbehindthe andefficientsystems. codeuses,semanticsofcomments,implicationsofdocumentation, andthenamingconventionsoffunctionsandvariables.Thisunder- 5.1.5 ReportAgent. TheReportAgentisresponsibleforextract- standingisthenjuxtaposedagainsttheactualcodeimplementation ing information from the LLM responses and converting them torevealpotentialdiscrepancies. intostructuredbugreports.Whileitisnotinherentlynecessary ThemotivationforthisparticularapplicationofICAAstems toutilizeLLMsinthisstep,theiruseinthisdesignsignificantly fromthelimitationsoftraditionalstaticcodeanalyzers.Whilethese enhancestheconversionprocess.TheLLMisparticularlyeffective analyzershavebeenlargelysuccessfulindetectingsyntacticaland atdealingwiththenaturallanguageoutputsproducedbytheCon- certaintypesoflogicalerrors,theyoftenfalterwhenitcomesto sistencyCheckingAgent,convertingtheseoutputsintoactionable inferringtheintentbehindapieceofcode.Inferringintentinvolves bugreports.Thisprocessleveragessophisticatedtextextraction understanding the semantics of not only the code but also the techniquesandemploysstrategiessuchas’guardrails’,aimedat associatedcomments,documentation,andnamingconventionsof controllingtheoutputschemaoftheLLMs.Bydefiningcertain functionsandvariables.Traditionalstaticcodeanalyzers,being parametersandconstraints,the’guardrails’techniqueensuresthe rule-basedsystems,strugglewithsuchtasksduetotheirinherent LLMproducesoutputsthatalignwiththeexpectedformatofthe limitationsindealingwithsemanticinformation. bugreport,therebyfacilitatingaseamlesstranslationprocess. In contrast, ICAA, with its ability to utilize LLMs, can effec- tivelydecipherthesubtlesemanticsembeddedinthecodeandits 5.1.6 FalsePrunerAgent. TheFalsePrunerAgentisanessential associatedartefacts.ThisenablestheICAAtoinfertheprogram- componentinthesystemthatmeticulouslyinspectsandrefinesthe mer’s intent and compare it against the actual implementation, bugreportproducedbytheReportAgent,withtheexplicitgoalof therebyrevealinganyinconsistencies.Thisdesignchoicemakes reducingfalsepositiveresults. ICAAparticularlysuitableforapplicationswhereunderstanding ThisagentcanbeimplementedusingeitherLLMsorstaticanal- thesemanticsandintentionsbehindthecodeiscrucial. ysis tools. When utilizing LLMs, the agent applies their under- 5.2.1 Components. ThisICAAstructureiscomposedofthreepri- standingofcodesemanticsandpatternstoidentifypotentialfalse marycomponents: positives.Ontheotherhand,whenusingstaticanalysistools,the agentcross-validatestheinitialresultstorecognizeandremove (1) Context&PromptIncubationAgent:Thiscomponent falsepositives. acceptscodeasinputanddynamicallynavigatesthroughaTrovatoandTobin,etal. Context & Prompt Incubation Agent Bug Hunter Agent Prompt In-context Learning Code Docs Thinking Bug Detection Using LLMs Relevant Code Snippets Decision Related Comments Report Agent Use information Action Code to Inspect Report Post Process Relevant Context Actions Doc Retrieval and Alignment Bug Reports Relevant Code Snippets Search parsing and align Docstring and Comments Static Usage analysis Location Encoding Figure2:Code-IntentionConsistencyCheckingAgent seriesofthinking,decision-making,andactionstepstogen- complexityofsourcecodes,LLMsoftenhavedifficultymapping |
erateacontext-sensitiveprompt.Theseactionsincludethe their outputs to the correct code lines. By embedding location extractionandselectionofrelevantinformationfromthe information within the code, this complexity is managed more code,anessentialprocessgiventhewindowsizelimitations effectively. ofcurrentLLMs.Notallpertinentinformationisreadily Althoughthisapproachdoesconsumeadditionaltokens,iten- availableorwithintheLLM’swindowsize,necessitating hancestheprecisionoflocatingpotentialissuesinthecode,thereby anin-contextlearningapproachtocarefullyselectandpri- improvingtheoveralleffectivenessoftheICAA.Asaresult,the oritizetheinformationthatwillbestaidinbugdetection. generatedbugreportsaremoreaccurate,providingamorereli- In-contextlearning,asdefinedby[Dongetal.2023],allows ablebasisforfurtheranalysis.Moreover,locationencodingalso the model to adapt its predictions based on the specific improvestheinteroperabilitywithothertechnicalcomponents.By sequenceoftokensit’scurrentlyprocessing.Thisintricate, providingastructured,location-basedreferencesystemwithinthe dynamicprocessisdesignedtocultivateacomprehensive code,othertoolsandsystemscanmoreeasilyinteractwithand understandingofthecode’scontext,therebyenablinga understandtheoutputfromtheLLM. moreaccurateandeffectiveanalysis. 5.2.3 Context&PromptIncubationActions. TheContext&Prompt (2) ConsistencyCheckingAgent:TheConsistencyCheck- IncubationAgentemploysamulti-stepprocedureincorporating ing Agent leverages prompt engineering techniques to variousactions.Theseinclude"DocumentRetrievalandAlignment", queryaLLMwiththeobjectiveofdetectinginconsistencies "RelevantCodeSnippetsSearch","ParsingandAligningDocstrings betweenthecode’simplementationanditscontext.This andComments",and"StaticUsageAnalysis".Eachstepcontributes agentacceptsinputfromtheContext&PromptIncubation toconstructingacomprehensivecontextfortheLLM,enablingit Agent,harnessingtheadvancedcapabilitiesoftheLLMto togainadeeperunderstandingofthecodeunderanalysis. identifyandanalyzepotentialdiscrepancies.Tofacilitate Contrarytoarigidprocedure,thedeploymentoftheseactions thesubsequentstep,theLLMisconfiguredtogeneratefor- isdynamicallymanagedbyathinking-decision-actionloop.This mattedoutputsthatcanbeefficientlyparsedbytheReport meansthereisnopredefinedorderinwhichthesestepsoccur.The Agent.Thisstrategicusageofformattedoutputssimpli- agent,actingasthe’brain’,determineswhetherornottoexecute fiestheextractionandconversionprocessoftheLLM’s anaction,thenumberoftimesanactionisexecuted,andinwhat responses,therebyenhancingtheoverallbugdetectionand order.Thisdynamicdecision-makingprocessenhancesadaptabil- reportingprocess. ityandefficiencywhendealingwithvaryingcodescenariosand (3) ReportAgent:Thiscomponenthasbeenintroducedin complexities. previoussection5.1.5. Theprocesscancommencewith"DocumentRetrievalandAlign- 5.2.2 LocationEncoding. The"LocationEncoding"stepisaninte- ment",whererelevantdocumentsareidentifiedandalignedfor gralpartoftheICAAprocess.Thisstepinvolvesinsertinganchor acoherentunderstandingofthecode’scontext."RelevantCode symbolsintoeachlineofthesourcecode,creatingaformof’geo- SnippetsSearch"canthenlocatekeysectionsofthecode,providing graphical’landmarkswithinthecode.TheLLMcanthenreferto criticalinsightsintothecode’sfunctionality."ParsingandAligning theselandmarkstomapitsresponsestotheexactlinesofcodethey DocstringsandComments"interpretsandalignsdocstringsand relateto. commentswiththecorrespondingcodesections,offeringanarra- ThisapproachaddressesacommonchallengewhenusingLLMs tiveforthecode’soperation.The"StaticUsageAnalysis"action forcodeanalysis—maintainingaccuratelinenumbers.Duetothe leveragesstaticanalysistoolstodecipherthecode’sstructureandStaticCodeAnalysisintheAIEra:AnIn-depthExplorationoftheConcept,Function,andPotentialofIntelligentCodeAnalysisAgents behavior.Thisprocessconstructsacallgraphanduncoversrelevant theICAAtoextractmorerelevantinformationanddrawinsights codesnippets,potentiallyrevealingtheprogrammer’sintent.Itpro- fromtheLLM’sresponses.Thisapproachisbothflexibleandadapt- videsdeepercontexttotheLLMbyanalyzingthegraph,function able,permittingtheICAAtomodifypromptsdynamicallyanduse usage,andcodesimilarity. theLLM’scontextualunderstandingtomakecoderecommenda- In-contextlearningisemployedtoeffectivelyconveythiscontext- tions,identifypotentialissues,andexplaincodebehavior. richinformationtotheLLM.ThisapproachenablestheLLMto WeoptedforGPT-3.5-turbooverGPT-4forourbaselinedueto adaptitspredictionsbasedonthespecificsequenceoftokensit’s itsspeedandcost-efficiency.However,wemaintainthatthecom- currentlyprocessing,facilitatingamoreaccurateandmeaningful parisonremainsvalidaslongasthesamebasemodelisused.This codeanalysis. comparisonservestoemphasizethevalueofouragentdesignand Inthenextsection,weevaluatetwoexampledesignsandcom- itspotentialtoenhancethesystem’scapabilityandperformance. parethemwiththebaselinestodemonstratetheeffectivenessand Consequently,ourevaluationstrategyunderscorestheaddedvalue usefulnessoftheICAA. andenhancementsbroughtaboutbytheagentframework. Intheexperimentweusetobenchmarkdataset: 6 EVALUATIONANDFIELDTEST |
6.1.1 BenchmarkDataset-Non-FunctionalBugsDataset(T1). The ThissectionconductsanevaluationoftheICAAimplementations. benchmarkdataset,sourcedfromthe"Non-FunctionalBugsDataset" Ratherthanpresentinganexhaustiveassessment,ourobjective availableat[RaduandNadi2019],consistsofreal-worldbugsre- istohighlightthepotentialoftheICAAconceptandtoprovide latedtonon-functionalrequirements.Itcomprises138bugsfrom67 insightsintotheperformanceconsiderationsofthetwoexample opensourceprojects,with44non-functionalbugsinPythonand94 implementations.Inessence,ourevaluationsserveasfieldtests non-functionalbugsinJava.Thedatasetprovidesscriptstoprocess thatillustratethepracticalutilityoftheICAAinreal-worldsce- thedataandincludesseparatefoldersforJavaandPythonprojects, narios.Ourfieldtestsaredesignedtoaddresscriticalaspectsof containingmetadata,problemdescriptions,andcodeimprovement systemperformance,suchasrecallrate,falsepositiverate,andthe examples. costassociatedwithusingintelligentagent-basedapproachesfor Forourevaluation,wefedthebenchmarkdatasettoourintelli- identifyingcodeerrors. gentagentandmeasureditsperformanceindetectingandresolving Ourevaluationstrategyincorporatesmultiplebenchmarksto non-functionalbugs.Weanalyzedtheagent’sfalsepositive,recall, provide diverse perspectives on our system’s capabilities: First, andtokenconsumptioninidentifyingthesebugs,consideringboth acomparativeanalysiswithestablishedbaselinemodelsoffersa language-specificandcross-languagescenarios. referencepointforoursystem’sperformance.Thiscomparisonis 6.1.2 CuratedTestSuite(T2). Inadditiontothebenchmarkdataset, notdesignedtoassertsuperiority,butrathertoclarifytherelative wehavemeticulouslycuratedacollectionof23testcasesextracted strengthsandlimitationsofourapproach.Next,anexamination fromclosedissuesonGitHubwhichfocusingonAPImisusesce- ofactualsourcecoderepositoriesprovidesarealistictestbed.This narios.TheAPImisusetestcasesshedlightoncommonmistakes allowsustoevaluatethesystem’sutilityindetectingandaddressing andmisusesofAPIsencounteredinsoftwaredevelopment.They real-worldbugs,providinginsightsintoitspracticalperformance. provideexamplesofcodeerrorsresultingfromincorrectAPIusage. Finally,abenchmarkingexerciseusingcodesnippetscontaining Toevaluatetheperformanceofourintelligentagentonthese different types of intentional errors serves to test our system’s testcases,weexecutedtheagentoneachindividualtestcaseand bugdetectioncapabilitiesincontrolledconditions.Thishelpsin meticulouslyanalyzeditsabilitytodetectandaddresscodeerrors. appreciatingthesystem’sprecision,recall,andtokenconsumption Wequantifiedthefalsepositiveandrecalloftheagentinidentifying metrics. codeerrors. Throughthisevaluation,weaimtodemonstratethepotential Throughtheevaluationofthesetwodatasets,wewereableto oftheICAAconceptandprovideinsightsintotheperformance assessthestrengthsandlimitationsofourproposedapproachinde- considerationsofourexampleimplementations.Byshowcasing tectingandresolvingbothfunctionalandnon-functionalbugs.The thepracticalapplicationofoursysteminreal-worldscenarios,we resultsobtainedfromtheseexperimentsyieldedvaluableinsights contributetotheunderstandingandadoptionofICAAtechnology. intotheeffectivenessandapplicabilityofourapproach,particularly intermsofrecall.Thecuratedtestsuitewillbepubliclyavailable, 6.1 ExperimentSetup enabling researchers and developers to access and utilize it for Ourevaluationstrategyusesbaselinestoillustratetheadvantages furtherevaluationandnewresearchpurposes. ofourICAAapproach.Theprimarybaselineforcomparisonisthe Allexperimentsareconductedonalaptopwitha6-coreIntel(R) ChatGPTmodel,specificallytheGPT-3.5-turbovariant,whichisa Core(TM)i7-9750HCPU@2.60GHzand16GBofRAM. significantpartofouragentdesignandoffersavaluablereference point. 6.2 EvaluationoftheFalsePositiveRate Inthebaselinedesign,aprompttemplateisusedtodirectlyquery Table2:ComparisonofFalse-PositiveRatesbetweenReAct theLLMforbugdetection.TheLLM,withtrainingonanextensive BugDetectionAgentandBaseline corpusofcodeandnaturallanguagedata,providesresponsesbased onitslearnedcapabilities. Benchmark ReActBugDetectionAgent Baseline Buildinguponthisbaseline,ourICAAapproachoptimizesthe T1 66% 85% useoftheLLM.AdvancedpromptengineeringtechniquesenableTrovatoandTobin,etal. OurstudydemonstratestheimprovedperformanceofourReAct codeanalysis,suchasCodeReviews.However,itisworthnoting BugDetectionAgent(see5.1.3)overabaseline.Bothweretested thatthecostoflanguagemodelusagehasalreadybeendecreas- onidenticalcodebases,resultinginadirectcomparison. ingalongsidethedevelopmentofLLMsandthetrendshowsthe Ouragentsoutperformedthebaselineinbugdetectionaccuracy, pricewillcontinuetodrop.Therefore,futureresearchshouldfocus notablyreducingthefalse-positiverateto66%fromthebaseline’s ondevelopingmethodstofurtherdecreasetokenconsumptionto 85%.Thishighlightstheenhancementinlanguagemodel-basedsys- maketheseagentsmorecost-effective. tems’capabilityachievedbyourapproach,despiteastillrelatively 6.5 CaseStudy highfalse-positiverate. Severalfactorscontributedtothehigherfalse-positiverate.These Listing3:Errorcode include the function check agent’s incomplete caller recall, the useofaninadequatelytrainedembeddingmodel,andthechoice |
@Override of prompts and configuration settings. Potential improvements 161 public boolean onOptionsItemSelected(@NonNull includeenhancingcallerrecall,usingmoresuitablemodelslike 162 MenuItem item) { CodeBERT,andfine-tuningpromptsandsettings. if (!super.onOptionsItemSelected(item)) { 163 Thesepotentialenhancementscoulddecreasethefalse-positive switch (item.getItemId()) { 164 rateandfurtherboostouragents’performance,pointingtowardsa case R.id.clear_history_item: 165 promisingfutureforlanguagemodel-basedsystems. DBWriter.clearDownloadLog(); 166 return true; 167 6.3 EvaluationoftheRecall case R.id.refresh_item: 168 ... 169 } Table 3: Recall Performance of the ReAct Bug Detection 170 AgentonBenchmark2 ThisisacasestudythathighlightsabugdetectedbyourIntention- Benchmark ReActBugDetectionAgent CodeConsistencyAgent.Thebugwasfoundinthetestprojectof T2 60.8% benchmarkT2,specificallyintheAntennaPod1repositoryhosted onGitHub.Ouragentreportedthatstartingfromline165(asshown intheabovecodesnippet3),whereid.clear_history_itemisshown, InordertoevaluatetherecalloftheCode-IntentionConsistency thesubsequentfunctioncallshouldinvokeclearHistory instead CheckingAgent(see5.2),wehaveassembledabenchmarksuite ofclearDownloadLog.Thisobservationpointstoaninconsistency derivedfromreal-worldissues.Thiscuratedsuiteincludes23test inthecodeimplementation,suggestingthattheintendedbehav- casesthatprimarilyfocusonAPImisuse. ioristoclearthehistoryratherthanthedownloadlog.There- TheReActBugDetectionAgentwasexecutedonthisdatasetand portedinconsistencyisindeedacaseofincorrectimplementation. thefindingsarepresentedinTable3.Outofatotalof23testcases, ThecorrectactionshouldbetochangeR.id.clear_history_itemto theagentwasabletodetect14issues,whichequatestoarecallrate R.id.clear_log_item.Fromtheperspectiveofdetectinginconsisten- of60.8%.Thisrecallperformanceisnotonlycomparabletothatof cies,thisreportisvalid. thestate-of-the-arttechniquesfordetectingfunctionalbugs[Xiong etal.2023],butalsounderscoresthepotentialandeffectivenessof Listing4:Relevantcode theproposedagentdesigninidentifyingbugs. TheseresultsdemonstratethatourBugDetectionAgenthas @Override 154 the capability to accurately identify a significant proportion of public void onPrepareOptionsMenu(@NonNull Menu 155 real-worldbugs.This,coupledwiththefactthattheagent’srecall menu) { menu.findItem(R.id.episode_actions). ratealignscloselywiththeperformanceofcurrentstate-of-the-art 156 setVisible(false); techniques,providesstrongevidenceoftheefficacyandpotential menu.findItem(R.id.clear_logs_item). oftheagent’sdesigninthefieldofbugdetection. 157 setVisible(!downloadLog.isEmpty()); 6.4 Tokenconsumption ThereasonbehindourassumptionthattheLLMwasableto FromtheobtaineddatashowninTable4,thebaselineimplementa- identifythisinconsistencyliesinthefactthatweutilizedastatic tionofthetwoagentsexhibitssimilartokencosts,rangingapprox- parsertoprovidetheLLMwithrelevantcodeinformation.This imatelyfrom355.2to996.9tokensperlineofcode.Thisindicatesa includedthefilenameDownloadLogFragment.java,theclassname considerablecost.GivenOpenAI’spricingatthetimeofwriting DownloadLogFragment,andthefollowingrelevantcodesnippet4. thispaper,whichis$0.0015per1Ktokensforinputand$0.002per ThecodesnippetexplicitlyreferencesanotherR.idresourcecalled 1Ktokensforoutput,theaveragecostforanalyzingeachlineof R.id.clear_log_item,whichservesasahinttotheLLMregarding codeisestimatedtobebetween$0.000812and$0.001032.Conse- theexistenceofthecorrectR.id. quently,foraprojectcomprisingonemillionlinesofcode,thecost Inourinvestigation,wedeliberatelyremovedthecontextual forasingleanalysisroundisapproximately$1000.Thisexpense information from the prompt provided to the LLM. As a result, couldpotentiallyhinderwidespreadadoptionoftheseagentsand maylimitthepotentialusescenariostothoserequiringonlypartial 1https://github.com/ByteHamster/AntennaPodStaticCodeAnalysisintheAIEra:AnIn-depthExplorationoftheConcept,Function,andPotentialofIntelligentCodeAnalysisAgents Table4:ComparisonofTokenConsumptionPerLineforBaselineandExampleAgentsonDifferentBenchmarks Code-IntentionConsistency Benchmark Baseline ReActBugDetectionAgent CheckingAgent T1 600.3 355.2 417.8 T2 510.0 996.9 834.6 theLLMfailedtodetectthementionedissues.Weacknowledge work.Despitethis,ourapproachexhibitsatangibleimprovement thatsolelyattributingthedetectionofsuchissuestothecontext overthebaseline,furtherunderliningitspotentialinthefieldof fedtotheLLMisnotfeasible,asLLMsposesignificantchallenges codeerrordetection. intermsofinterpretability[Linardatosetal.2020].Althoughthe Applicability:Throughourexperiments,wehaveestablished explainabilityofLLMsremainsachallenge,wehypothesizethat thatourapproach,despiteitschallengessuchasahighfalse-positive theabsenceofrelevantcontextualinformationsignificantlyim- rateandsubstantialtokenconsumption,holdspromise.Itpresents pactedtheLLM’sabilitytoidentifythereportedissues.Wewill severaladvantagesovertraditionalstaticanalysis,includingthe continueourexplorationinthisdirectiontogainfurtherinsights abilitytohandleincompletecode,easierintegration,andaunique andunderstanding. |
potential to detect complex bugs often missed by conventional methods.Thesecasestudieshavenotonlyenabledadeeperun- 6.6 SummaryandConclusion derstandingofoursystem’soperationinrealisticscenariosbut Overthecourseofourevaluation,wehavepresentedacompre- also underscored the potential of machine learning techniques hensiveanalysisofourICAAimplementations,focusingontheir inenhancingbugpredictionbasedonpastdetections.Whileour potentialandperformanceinreal-worldscenarios.Weconducted approachisnotfullypracticalinitscurrentstate,theseinsightssug- aseriesoffieldtestsdesignedtoassesscrucialaspectsofsystem gestitspotentialapplicabilityandroomforfutureenhancements performancesuchasrecallrate,falsepositiverate,andtheassoci- inreal-worldscenarios. atedcostimplicationsofusingintelligentagent-basedapproaches Limitations:Recognizingthepotentiallimitationsofourre- foridentifyingcodeerrors. searchisessentialforunderstandingthevalidityofourfindings. Ourintelligentagentdemonstratedimprovedperformanceover Onepotentialthreattointernalvaliditycouldarisefrombiasesin- thebaselinemodelinbugdetectionaccuracy,reducingthefalse- troducedbyourexperimentalsetup,suchastheselectionofspecific positiverateto66%fromthebaseline’s85%.Meanwhile,therecall codebases,tools,andourrelianceonaspecificLLM—GPT-3.5- ratestoodatapromising60.8%,showcasingtheagent’scapability turbo.AlthoughGPTiscurrentlystate-of-the-art,theperformance toaccuratelyidentifyasignificantproportionofreal-worldbugs. resultsmayvarywhendifferentLLMsareused.Furthermore,our Thisalignscloselywiththeperformanceofcurrentstate-of-the-art curatedbenchmark,whilecarefullyselected,isnotonaverylarge techniques,providingstrongevidenceoftheefficacyandpotential scale,whichmaylimitthegeneralizabilityofourresults.Tobolster oftheagent’sdesigninthefieldofbugdetection. externalvalidity,futureworkcouldinvolvetestingoursystemona However,despitethesepromisingresults,therearestillchal- broaderrangeofcodebases,usingavarietyofLLMs,andcomparing lengestoovercome.Thecostassociatedwithtokenconsumption itsperformancewithawiderspectrumofbugdetectiontools. isasignificantconsideration,andtheaveragecostforanalyzing AninherentfeatureofourAI-basedsystem,whichalsorepre- eachlineofcodecouldpotentiallyhinderthewidespreadadoption sentsapotentialthreattoreproducibility,isitsnon-deterministic oftheseagents.Futureresearchshouldthereforefocusondevelop- nature.Toaddressthis,wedesignedexperimentsthatincludemul- ingmethodstofurtherdecreasetokenconsumptiontomakethese tiplerunsofourAIagentoneachcodebase,averagingtheresults agentsmorecost-effective. toderiveamorerobustperformanceestimate. Buildinguponthesefindings,wenowturnourattentiontothe ConclusionandFuturework:Inconclusion,ourworkserves discussionoftheimplicationsoftheICAAandexplorepotential asaninitialsteptowardsexploringnewdirectionsinfunctional avenuesforfurtherimprovementandrefinementoftheICAAin correctnessbugdetectionmethodologies.Weanticipatethatourre- nextsection. searchwillinspirefurtherinvestigationandinnovation,ultimately leadingtothecreationofmorereliableandefficientsoftware.Our 7 DISCUSSION researchopensseveralavenuesforfuturework.Techniquestoim- Inthissection,wediscusstheimplicationsofourexperimental provethedeterministicbehaviorofourAIagentwhileretaining resultsandtheirimpactsonthefieldofsoftwarebugdetection. itsabilitytouncoverbugsmissedbytraditionaltoolscouldbede- veloped.Furthermore,extendingoursystemtomoreprogramming PerformanceandPotential:Ourapproachhasdemonstrated languageswouldexpanditsusabilityandimpact. acceptableperformanceindetectionrateandfalse-positiverate, suggestingthatthedesignofouragentcouldbeaviabledirection 8 CONCLUSION forenhancingcodeerrordetection.Duringourevaluation,wedid notcompareourmethodwithexistingstaticanalyzers,leaving Inthisresearch,wepresentedanddiscussedtheconceptofthe thequestionofwhetheritcansurpassthesetoolsintermsoffalse ICAA.Oursystemsignifiesastepforwardinthefieldofbugdetec- positivesandrecallunresolved.Thisstandsasadirectionforfuture tion,showingthefeasibilityandpotentialofthisapproach.WhileTrovatoandTobin,etal. therearestillchallengestoovercomeandoursystemmaynotout- performallexistingmethods,theresultsobtainedprovideaclear indicationofthepossibilitiesinthisnoveldirectionofresearch. OurexplorationoftheICAAconceptunderscoresitspotential to bring about improvements in bug detection during software developmentprocesses.Theeffectivenessofourimplementation suggeststhatthisisjustoneinstanceofnumerouspossibledesigns withinthisbroadconcept,indicatingthatfurtherexplorationcould leadtoadditionaladvancementsincodeanalysis. Inconclusion,ourworkhashighlightedapromisingdirectionfor enhancingstaticcodeanalysistools.Weanticipatethatourresearch willinspirefurtherinnovationsanddiversifiedapproachesinthe fieldofcodeanalysis.Thiscouldultimatelyleadtothedevelopment ofmoreeffectiveandefficienttoolsforsoftwaredevelopers,thereby improvingthesoftwaredevelopmentprocess.StaticCodeAnalysisintheAIEra:AnIn-depthExplorationoftheConcept,Function,andPotentialofIntelligentCodeAnalysisAgents REFERENCES YasharTalebiradandAmirhosseinNadiri.Multi-agentcollaboration:Harnessingthe |
NathanielAyewahandWilliamPugh. Usingfindbugsonproductionsoftware. In powerofintelligentllmagents,2023. Proceedingsofthe16thACMSIGSOFTInternationalSymposiumonFoundationsof LiangWang,NanYang,XiaolongHuang,BinxingJiao,LinjunYang,DaxinJiang,Ran- softwareengineering,pages345–348.ACM,2008. ganMajumder,andFuruWei.Textembeddingsbyweakly-supervisedcontrastive DavideBalzarotti,MarcoCova,ViktoriaFelmetsger,NenadJovanovic,EnginKirda, pre-training.arXivpreprintarXiv:2212.03533,2022. ChristopherKruegel,andGiovanniVigna.Businesslogicvulnerabilitiesinweb XingjiaoWu,LuweiXiao,YixuanSun,JunhangZhang,TianlongMa,andLiangHe.A applications.InBlackHatDC,2010. surveyofhuman-in-the-loopformachinelearning.FutureGener.Comput.Syst., KentBecketal.Agilemanifesto.AgileAlliance,2001. 135(C):364–381,oct2022.ISSN0167-739X.doi:10.1016/j.future.2022.05.014.URL AlBessey,KenBlock,BenChelf,AndyChou,BryanFulton,SethHallem,Charles https://doi.org/10.1016/j.future.2022.05.014. Henri-Gros,AsyaKamsky,ScottMcPeak,andDawsonEngler.Afewbillionlines YihengXiong,MengqianXu,TingSu,JinglingSun,JueWang,HeWen,GeguangPu, ofcodelater:usingstaticanalysistofindbugsintherealworld.Communications JifengHe,andZhendongSu.Anempiricalstudyoffunctionalbugsinandroidapps. oftheACM,53(2):66–75,2010. InProceedingsofthe32ndACMSIGSOFTInternationalSymposiumonSoftwareTesting TomBBrown,BenjaminMann,NickRyder,MelanieSubbiah,JaredKaplan,Prafulla andAnalysis,ISSTA2023,page1319–1331,NewYork,NY,USA,2023.Association Dhariwal,ArvindNeelakantan,PranavShyam,GirishSastry,AmandaAskell,etal. forComputingMachinery. ISBN9798400702211. doi:10.1145/3597926.3598138. Languagemodelsarefew-shotlearners.InAdvancesinneuralinformationprocessing URLhttps://doi.org/10.1145/3597926.3598138. systems,volume33,2020. ShunyuYao,JeffreyZhao,DianYu,NanDu,IzhakShafran,KarthikNarasimhan,and MiaXChen,OrhanFirat,AnkurBapna,MelvinJohnson,WolfgangMacherey,George YuanCao.React:Synergizingreasoningandactinginlanguagemodels,2023. Foster,LlionJones,NikiParmar,MikeSchuster,YonghuiWu,etal.Thebestofboth worlds:Combiningrecentadvancesinneuralmachinetranslation.arXivpreprint Received28September2023 arXiv:1804.09849,2018. EdmundMClarke,OrnaGrumberg,andDoronAPeled.Modelchecking.InEncyclo- pediaofComputerScience.Wiley,1999. BasCornelissen,AndyZaidman,ArievanDeursen,LeonMoonen,andRainerKoschke. Asystematicsurveyofprogramcomprehensionthroughdynamicanalysis.IEEE TransactionsonSoftwareEngineering,35(5):684–702,2009. PiotrDabkowskiandYarinGal. Realtimeimagesaliencyforblackboxclassifiers, 2017. QingxiuDong,LeiLi,DamaiDai,CeZheng,ZhiyongWu,BaobaoChang,XuSun, JingjingXu,LeiLi,andZhifangSui.Asurveyonin-contextlearning,2023. ZhangyinFeng,DayaGuo,DuyuTang,NanDuan,XiaojiangFeng,MingGong,Lin Shou,BingQin,TingLiu,DaxinJiang,etal. Codebert:Apre-trainedmodelfor programmingandnaturallanguages. InProceedingsofthe28thACMSIGKDD ConferenceonKnowledgeDiscoveryandDataMining.ACM,2020. BrittanyJohnson,YangSong,EmersonMurphy-Hill,andRobertBowdidge.Whydon’t peopleusestaticanalysistoolstofindbugs?IEEESoftware,30(4):22–28,2013a. BrittanyJohnson,YoonkiSong,EmersonMurphy-Hill,andRobertBowdidge.Why don’tsoftwaredevelopersusestaticanalysistoolstofindbugs? In201335th InternationalConferenceonSoftwareEngineering(ICSE),pages672–681,2013b.doi: 10.1109/ICSE.2013.6606613. Rafael-MichaelKarampatsisandCharlesSutton.Bigcode!=bigvocabulary:Open- vocabularymodelsforsourcecode.InProceedingsofthe42ndInternationalConfer- enceonSoftwareEngineering,pages719–731.ACM,2020. GeneKim,JezHumble,PatrickDebois,andJohnWillis.Thedevopshandbook:How tocreateworld-classagility,reliability,andsecurityintechnologyorganizations. 2016. JamesCKing. Symbolicexecutionandprogramtesting. InCommunicationsofthe ACM.ACM,1976. PantelisLinardatos,VasilisPapastefanopoulos,andSotirisB.Kotsiantis.Explainable ai:Areviewofmachinelearninginterpretabilitymethods.Entropy,23,2020.URL https://api.semanticscholar.org/CorpusID:229722844. Microsoft.SemanticKernel:Integratecutting-edgellmtechnologyquicklyandeasily intoyourapps.[Online].Available:https://github.com/microsoft/semantic-kernel, 2023.Accessed:01092023. YoheiNakajima.GitHub-yoheinakajima/babyagi.https://github.com/yoheinakajima/ babyagi,2023.[Accessed28-09-2023]. OpenAI.Gpt-4:Traininglargelanguagemodels.OpenAIBlog,2021. AndrewPeng,MichaelWu,JohnAllard,LoganKilpatrick,andStevenHeidel.Gpt- 3.5turbofine-tuningandapiupdates. OpenAIBlog,August2023. URLhttps: //openai.com/blog/gpt-3-5-turbo-fine-tuning-and-api-updates. AlecRadford,JeffWu,RewonChild,DavidLuan,DarioAmodei,andIlyaSutskever. Languagemodelsareunsupervisedmultitasklearners.OpenAIBlog,2019. |
AidaRaduandSarahNadi.Adatasetofnon-functionalbugs.In2019IEEE/ACM16th InternationalConferenceonMiningSoftwareRepositories(MSR),pages399–403,2019. doi:10.1109/MSR.2019.00066. ToranBruceRichards. GitHub-Significant-Gravitas/AutoGPT:Anexperimental open-sourceattempttomakeGPT-4fullyautonomous.—github.com. https: //github.com/Significant-Gravitas/AutoGPT,2023.[Accessed27-09-2023]. BaptisteRozière,JonasGehring,FabianGloeckle,StenSootla,ItaiGat,XiaoqingEllen Tan,YossiAdi,JingyuLiu,TalRemez,JérémyRapin,ArtyomKozhevnikov,Ivan Evtimov,JoannaBitton,ManishBhatt,CristianCantonFerrer,AaronGrattafiori, WenhanXiong,AlexandreDéfossez,JadeCopet,FaisalAzhar,HugoTouvron,Louis Martin,NicolasUsunier,ThomasScialom,andGabrielSynnaeve.Codellama:Open foundationmodelsforcode,2023. AlexeySvyatkovskiy,YingZhao,ShengyuFu,andNeelSundaresan.Pythia:Ai-assisted codecompletionsystem. InProceedingsofthe26thACMSIGKDDInternational ConferenceonKnowledgeDiscovery&DataMining,pages2775–2785.ACM,2020. |
2310.09810 ChatGPT for Vulnerability Detection, Classification, and Repair: How Far Are We? Michael Fu Chakkrit (Kla) Tantithamthavorn Van Nguyen Trung Le Monash University Monash University Monash University Monash University Clayton, Australia Clayton, Australia Clayton, Australia Clayton, Australia yeh.fu@monash.edu chakkrit@monash.edu Van.Nguyen1@monash.edu trunglm@monash.edu Abstract—Large language models (LLMs) like ChatGPT (i.e., Leveraging ChatGPT’s considerable scale, with 175 billion gpt-3.5-turbo and gpt-4) exhibited remarkable advancement in parameters for gpt-3.5-turbo [2] and 1.7 trillion parameters a range of software engineering tasks associated with source for gpt-4 [16], offers the potential for its application in code such as code review and code generation. In this paper, we vulnerability-relatedtasks.However,tothebestofourknowl- undertake a comprehensive study by instructing ChatGPT for fourprevalentvulnerabilitytasks:functionandline-levelvulner- edge,nocomprehensivestudieshavebeenconductedtoevalu- abilityprediction,vulnerabilityclassification,severityestimation, ate the entire vulnerability workflow, spanning from detecting and vulnerability repair. We compare ChatGPT with state- vulnerabilities and explaining their types to estimating their of-the-art language models designed for software vulnerability severity and repair suggestions. purposes. Through an empirical assessment employing extensive In this paper, we conduct a thorough analysis to assess real-world datasets featuring over 190,000 C/C++ functions, we found that ChatGPT achieves limited performance, trailing ChatGPT’s ability for the four vulnerability prediction tasks behind other language models in vulnerability contexts by a mentioned above. Noteworthy is the fact that ChatGPT’s 1.7 significant margin. The experimental outcomes highlight the trillion parameters surpass the count of parameters in source challenging nature of vulnerability prediction tasks, requiring code-oriented pre-trained language models like CodeBERT domain-specific expertise. Despite ChatGPT’s substantial model and GraphCodeBERT by nearly 14,000 times. Therefore, the scale, exceeding that of source code-pre-trained language mod- els (e.g., CodeBERT) by a factor of 14,000, the process of prevalent approach to utilizing ChatGPT involves furnishing fine-tuning remains imperative for ChatGPT to generalize for it with appropriate prompts and task examples, rather than vulnerability prediction tasks. We publish the studied dataset, engaging in fine-tuning for these specific downstream tasks. experimentalpromptsforChatGPT,andexperimentalresultsat It is important to note that the model parameters of ChatGPT https://github.com/awsm-research/ChatGPT4Vul. remain proprietary by OpenAI, thereby precluding the possi- Index Terms—ChatGPT, Large Language Models, Cybersecu- bility of fine-tuning its parameters for vulnerability tasks. rity, Software Vulnerability, Software Security Thus, we compare prompting ChatGPT with other fine- tuned language models specifically designed for source code I. INTRODUCTION purposes.Weconductexperimentstocomparetwoversionsof Softwarevulnerabilitiesareweaknessesorflawsinsoftware ChatGPT (i.e., gpt-3.5-turbo and gpt-4) with four competitive code that can be exploited by attackers to compromise the baseline approaches (i.e., AIBugHunter [10], CodeBERT [7], security of a system, gain unauthorized access, or cause un- GraphCodeBERT [12], and VulExplainer [8]) designed for intended behavior. Recently, there have been advancements in software vulnerability on four different vulnerability tasks. employinglanguagemodelsforsourcecode(e.g.,CodeBERT, Through an extensive evaluation of ChatGPT on two vulnera- GraphCodeBERT, and CodeT5) to automatically achieve the bilitydatasets(i.e.,Big-Vul[6]andCVEFixes[1])encompass- following tasks: (1) pinpoint vulnerable functions and state- ing over 190,000 C/C++ functions, we answer the following ments [9] within source code; (2) recognize vulnerability four research questions: types to explain detected vulnerabilities [10]; (3) estimate (RQ1) How accurate is ChatGPT for function and line-level the severity of vulnerabilities [10]; and (4) suggest repair vulnerability predictions? patches[3],[11].Inparticular,adeeplearning-basedsoftware Results. ChatGPT achieves F1-measure of 10% and 29% security tool named AIBugHunter was proposed in VSCode and top-10 accuracy of 25% and 65%, which are the lowest that achieves promising results for the aforementioned four compared with other baseline methods. vulnerability tasks using multiple fine-tuned language models (RQ2) How accurate is ChatGPT for vulnerability types for source code [10]. classification? On the contrary, large language models (LLMs) like Chat- Results. ChatGPT achieves the lowest multiclass accuracy of GPT have effectively demonstrated their competence in tasks 13%and20%,whichis45%-52%lowerthanthebestbaseline. relatedtocode,suchasthesimulationofsystembehaviorfrom (RQ3) How accurate is ChatGPT for vulnerability severity provided requirements, the formulation of API specifications, estimation? andthediscernmentofimplicitassumptionswithincode[19]. Results. ChatGPT gave the most inaccurate severity estima- 3202 tcO 51 ]ES.sc[ 1v01890.0132:viXrationwiththehighestmeansquarederror(MSE)of5.4and5.85 We provide a return template, anticipating that ChatGPT will |
while other baseline methods achieve MSE of 1.8 to 1.86. generate an output consisting of a line number accompanied (RQ4) How accurate is ChatGPT for automated vulnerability by its corresponding code statement as predictions. repair? Results. ChatGPT failed to generate any correct repair patches while other baselines correctly repaired 7%-30% of vulnerable functions. Novelty & Contributions. This paper represents one of the pioneering pilot studies that comprehensively assess Chat- GPT’s (gpt-3.5-turbo and gpt-4) performance in vulnerability detection,vulnerabilitytypeidentification,severityestimation, and patch recommendation. In addition, we conduct com- parative analyses with other state-of-the-art language models, specifically fine-tuned for software vulnerability-related tasks. II. RELATEDWORK Recently,researchershavebeeninvestigatingtheapplicabil- ity of ChatGPT for software vulnerability tasks. Cheshkov et al. [4] investigated the base ChatGPT (gpt-3.5-turbo) per- formance for vulnerability prediction and classification us- Fig.1. Anexamplepromptforfunctionandline-levelvulnerabilityprediction. ing 120 samples across five different CWE-IDs. Zhang et al. [21] designed suitable prompts for ChatGPT to enhance B. Prompt ChatGPT for Software Vulnerability Classification its performance for vulnerability prediction. On the other Problem. Weformulatevulnerabilityclassificationasamulti- hand, Napoli et al. [14] investigated ChatGPT’s performance class classification task where the model identifies a CWE-ID for the smart contracts vulnerability correction task. Some foraninputvulnerablefunction.CommonWeaknessEnumer- previous studies have evaluated ChatGPT’s performance for ation Identifier (CWE-ID) is a community-developed list of the automated program repair (APR) task where the model common software weaknesses and vulnerabilities [5], which was asked to fix general bugs [17], [18], [20]. In particular, allows security professionals to categorize and communicate Pearceetal.[17]assessedlargelanguagemodels’performance about security issues in a standardized manner. for the program repair, however, the most advanced two Prompt. We present example prompts for CWE-ID classi- versions of ChatGPT were not included in their experiments. fication in Fig 2. In particular, we inform ChatGPT that the III. PROBLEMSTATEMENT&PROMPTDESIGN input function is vulnerable and request it to identify its cor- responding CWE-ID. Additionally, we limit the classification In this section, we introduce the problem statements of the scope by providing a list of potential CWE-IDs to ensure a four vulnerability tasks, i.e., (1) function and line-level soft- fair comparison with other fine-tuned models. warevulnerabilityprediction(SVP),(2)softwarevulnerability classification(SVC),(3)severityestimation,and(4)automated vulnerability repair (APR). After each problem statement, we illustrate how we design the prompts for ChatGPT to perform the prediction task. A. Prompt ChatGPT for Software Vulnerability Prediction Fig.2. AnexamplepromptforCWE-IDclassification. Problem. We formulate vulnerability prediction as a binary classification task where the model predicts whether the input C. Prompt ChatGPT for Vulnerability Severity Estimation source code function is vulnerable. For vulnerable functions, we formulate the line-level vulnerability localization task as a Problem. We formulate vulnerability severity estimation as a rankingproblem,wherethemodelranksvulnerablestatements regression task where the model predicts a continuous value onthetoptoreducethemanualanalysisworkloadforsecurity based on input vulnerable functions to estimate their severity. analysts. CVSS(CommonVulnerabilityScoringSystem)severityscore Prompt. We present example prompts for function and line- is a standardized numerical system used to assess the serious- level vulnerability prediction in Fig 1. In the initial prompt, ness of security vulnerabilities in software and systems. We we provide ChatGPT with a task description focusing on use CVSS version 3.1 ranging from 0 to 10. function-level predictions, along with a clear instruction for Prompt. Wepresentexamplepromptsforseverityestimation return. In the subsequent prompt, we inform ChatGPT that in Fig 3. We inform ChatGPT that the input function is the given function is vulnerable and request it to rank the top vulnerableandspecifytheCVSSversionandtheoutputrange 10 most vulnerable-prone statements from the given function. tomakeitgenerateaseverityestimationforthegivenfunction.For the automated vulnerability repair (RQ4), we leverage the Big-Vul and CVEFixes [1] datasets pre-processed by Chen et al. [3]. The dataset has been adopted to evaluate vulnerability repair approaches [3], [11], which contains 5.5k pairs of vulnerable functions and their repair patches. Similar Fig.3. Anexamplepromptforseverityestimation. to previous studies [3], [11], we split the data into 70% for training, 10% for validation, and 20% for testing. D. Prompt ChatGPT for Automated Vulnerability Repair B. Parameter Settings and Execution Environment Problem. We formulate vulnerability repair as a sequence- We replicate the baseline methods using the original au- to-sequence generation task where the model generates corre- thors’ specified parameter settings, running experiments on sponding repair patches for input vulnerable functions. a Linux machine equipped with an AMD Ryzen 9 5950X Prompt. Wepresentexamplepromptsforvulnerabilityrepair processor, 64 GB RAM, and an NVIDIA RTX 3090 GPU. inFig4.Giventhatmodeloutputsarerepairpatchesdesigned The ChatGPT prompting was completed via paid API access |
by Chen et al. [3] instead of the complete repaired program, provided by OpenAI [15]. we provide three repair examples in each prompt to make C. Experimental Results ChatGPT comprehend our repair task. We then request Chat- GPT to create repair patches for vulnerable functions using (RQ1) How accurate is ChatGPT for function and line-level the templates provided in those examples. vulnerability predictions? Approach. To answer this RQ, we focus on the function and line-levelvulnerabilitypredictionsandcompareChatGPT(i.e., gpt-3.5-turbo and gpt-4) with three other fine-tuned baseline language models as follows: 1) AIBugHunter: A recently proposed deep learning-based software security tool that utilizes fine-tuned language models [9], [11] to perform vulnerability prediction, classification, severity estimation, and repair [10]. 2) CodeBERT: A language model originally pre-trained for tasks related to source code, CodeBERT underwent pre- training using the Codesearchnet dataset [13], encom- passing various programming languages. CodeBERT has demonstrated its capability to effectively perform tasks associated with source code [7]. 3) GraphCodeBERT: A language model that was also pre- Fig.4. Anexamplepromptforautomatedvulnerabilityrepair. trained on the Codesearchnet dataset to perform source code-related tasks. Notably, when forming the input for IV. EXPERIMENTALDESIGNANDRESULTS the model, GraphCodeBERT considers the data flow graph in addition to source code tokens [12]. In this section, we introduce our experimental datasets selected for each vulnerability task followed by the parameter Similar to the previous study [9], we report F1-measure, settings and hardware environment used to reproduce the precision, and recall to evaluate function-level performance. baseline language models fine-tuned for vulnerability tasks. For line-level performance, we report top-10 accuracy that Finally, we present our experimental approach along with the measures the percentage of vulnerable functions where at results for each research question. least one actual vulnerable line appears in the model’s top- 10 ranking. This metric has been previously used to evaluate A. Experimental Datasets the prediction of line-level vulnerability prediction [9]. We use the Big-Vul dataset constructed by Fan et al. [6] to Result. Fig 5 presents the experimental results of function evaluate vulnerability prediction (RQ1), classification (RQ2), and line-level vulnerability prediction. ChatGPT failed to and severity estimation (RQ3). Big-Vul has been widely accuratelypredictatthefunctionlevelwithanF1-measure adopted for software vulnerability tasks [9], [10], which of10%andtop-10accuracyof25%atthestatementlevel. comprises 188k C/C++ functions gathered from 348 Github Theleading-edgegpt-4with1.7trillionparametersachievesan projects, encompassing 3,754 code vulnerabilities across 91 F1-measure of 29% along with a top-10 accuracy of 65%. In types. Each vulnerable function is labeled with a CWE-ID contrast, the fine-tuned AIBugHunter achieves an F1-measure and a CVSS severity score. Its data distribution mirrors real- of 94% along with a top-10 accuracy of 99% with only world conditions, with a vulnerable-to-benign function ratio 120 million parameters. Despite gpt-4’s extensive model size of1:20.Similartopreviousstudies[9],[10],wesplitthedata and pre-training data, it faced challenges in generalizing the into80%fortraining,10%forvalidation,and10%fortesting. vulnerability prediction task without undergoing fine-tuning.F1 Precision Recall Top−10 Accuracy 1.00 94% 87% 1.00 98% 92% 1.00 90% 83% 1.00 99% 99% 87% 0.75 0.75 0.75 0.75 65% 0.50 0.50 50% 0.50 0.50 0.25 35% 29% 0.25 25% 0.25 33% 27% 0.25 25% 10% 11% 9% 0.00 0.00 0.00 0.00 AIBugHunte Cr od Gre aB pE hR CT odeBERT g gpt pt− −4 3.5−turbo AIBugHunte Cr od Gre aB pE hR CT odeBERT g gpt pt− −4 3.5−turbo AIBugHunte Cr odeBERT Grag ppt h− C4 odeB gE ptR −T 3.5−turbo AIBugHunte Cr od Gre aB pE hR CT odeBERT g gpt pt− −4 3.5−turbo Fig.5. (RQ1)Theexperimentalresultsoffunction-levelandline-levelvulnerabilityprediction.(↗)Forallmetrics,higher=better. Multiclass Accuracy Mean Squared Error Mean Absolute Error 0.6 65% 65% 63% 62% 6 5.4 5.85 2.0 1.84 1.86 1.5 4 0.4 1.0 0.83 0.88 0.93 0.2 20% 13% 2 1.8 1.85 1.86 0.5 0 0.0 0 AI.0 BugHunt Ver ulExplainer Code GrB aE phRT CodeBERT gp gt p− t4 −3.5−turbo GraphCodeBERT AIBugHunter CodeBER gT pt−3.5−turbo gpt−4 CodeBERT AIBugH Gu rnt ae pr hCodeBER gT pt−3.5−turbo gpt−4 Fig.7. (RQ3)Theexperimentalresultsofvulnerabilityseverityestimation. Fig.6. (RQ2)Theexperimentalresultsofvulnerabilitytype(i.e.,CWE-ID) (↘)LowerMSE,MAE=better. classification.(↗)HigherMulticlassAccuracy=better. (RQ3) How accurate is ChatGPT for vulnerability severity These results highlight that the vulnerability prediction task estimation? requires models to learn domain-specific knowledge (e.g., Approach. To answer this RQ, we focus on predicting the vulnerabilitypatterns)andfine-tuningisstillrequiredforlarge CVSS score of vulnerable functions. We compare ChatGPT language models despite their significant model size. (gpt-3.5-turbo and gpt-4) with the three baselines introduced in RQ1, where CodeBERT has been shown to be effective for |
severity estimation [10]. Similar to the previous study [10], (RQ2) How accurate is ChatGPT for vulnerability types we use Mean Squared Error (MSE) and Mean Absolute Error classification? (MAE) to assess the performance of each method. Result. Fig7presentstheexperimentalresultsoftheseverity Approach. To answer this RQ, we focus on the vulnerability score estimation. ChatGPT failed to accurately estimate classificationtaskwhereweaimtoidentifyCWE-IDsforvul- the CVSS severity score, resulting in an MSE of 5.4 nerable functions. We compare ChatGPT (i.e., gpt-3.5-turbo and an MAE of 1.84. The gpt-3.5-turbo and gpt-4 have and gpt-4) with three fine-tuned baseline language models MSE of 5.4 and 5.85 while the fine-tuned language model introduced in RQ1. Additionally, we include VulExplainer [8] baselines achieve 1.8-1.86. Similar to vulnerability prediction whichleverageslanguagemodelswithadistillationframework and classification tasks, accurately estimating severity scores to mitigate the data imbalances in the CWE-ID classification also demands software security expertise that ChatGPT has task.Similartopreviousstudies[8],[10],weusethemulticlass not acquired during its extensive pre-training phase, hindering accuracymeasuretoevaluatetheperformanceofeachmethod. its ability to provide accurate predictions in this context. Result. Fig 6 presents the experimental results of CWE- (RQ4)HowaccurateisChatGPTforautomatedvulnerability ID classification. The accuracy of ChatGPT in correctly repair? identifying CWE-IDs for vulnerable functions is limited, standing at a mere 13%. The gpt-3.5-turbo and gpt-4 Approach. To answer this RQ, we focus on generating vul- achieve 13%-20% accuracy while the fine-tuned language nerabilityrepairpatchesforvulnerablefunctions.Wecompare model baselines achieve 62%-65%. These findings suggest ChatGPT(i.e.,gpt-3.5-turboandgpt-4)withthethreebaseline that the accurate identification of CWE-ID for a vulnerable methods introduced in RQ1. Notably, AIBugHunter leverages function requires the model to learn to map specific patterns theVulRepair[11]modelforrepairpatchesgeneration,which (e.g., buffer overflow) in vulnerable functions to a CWE- achieves state-of-the-art results in the vulnerability repair ID. However, ChatGPT has not adequately acquired such problem. Similar to previous studies [3], [11], we use the per- knowledgeduringthepre-trainingphaseofChatGPTsoafine- centageofperfectprediction(%PP)measuretoassesstheper- tuning stage is still required to boost its performance. formanceofeachmethod.Onlyifthegeneratedrepairpatches%PP BLEU METEOR REFERENCES 100 100 100 [1] G. Bhandari, A. Naseer, and L. Moonen, “Cvefixes: automated collec- 75 75 59 75 68 64 59 tion of vulnerabilities and their fixes from open-source software,” in 50 50 49 44 50 Proceedingsofthe17thInternationalConferenceonPredictiveModels 30 35 andDataAnalyticsinSoftwareEngineering,2021,pp.30–39. 25 25 25 19 [2] T.Brown,B.Mann,N.Ryder,M.Subbiah,J.D.Kaplan,P.Dhariwal, 0 9 7 0 0 0 5 3 0 A.Neelakantan,P.Shyam,G.Sastry,A.Askelletal.,“Languagemod- AIB Gru ag pH hu Cnt oe dr eBE CoR dT ge pB tE −3R .T 5−turbo gpt−4 AIB Gru ag pH hu Cnt oe dr eBE CoR dT eBERT gpg tp −t 3− .4 5−turbo AIB Gru ag pH hu Cnt oe dr eBE CoR dT eBERT gpg tp −t 3− .4 5−turbo [3] e s lZ eyl .s as rt nea Cmr ine hs ge,f ne v ,w fo ol- S r.sh .3o 3 ret K, pl p o ae p m ia r.r imn n1e g8 rr u7s s7,” sc– eh1 cA ,9 ud 0 rv a i1 ta n y,n d2ce 0 vs M2 u0 li . n.n erMn ae bou in lr ia p til e er si rn uf so i, nrm “a cNti eo cun ora dp l er ,o ”tc re a Is n Es si Efn e Eg r TransactionsonSoftwareEngineering(TSE),2022.[Online].Available: Fig.8. (RQ4)Theexperimentalresultsofautomatedvulnerabilityrepair.(↗) https://arxiv.org/pdf/2104.08308 Higher%PP,BLEU,METEOR=better. [4] A. Cheshkov, P. Zadorozhny, and R. Levichev, “Evaluation of chatgpt model for vulnerability detection,” arXiv preprint arXiv:2304.07232, 2023. [5] M. Corporation, “Common weakness enumeration (cwe),” https://cwe. are identical to the ground-truth patches, we count it as a mitre.org/index.html,2006. correctprediction.The%PPiscomputedas totalcorrectpredictions. [6] J.Fan,Y.Li,S.Wang,andT.N.Nguyen,“Ac/c++codevulnerability totaltestingsamples dataset with code changes and cve summaries,” in Proceedings of the We use greedy decoding to return one repair candidate for 17thInternationalConferenceonMiningSoftwareRepositories(MSR), fine-tunedlanguagemodelsandensureafaircomparisonwith 2020,pp.508–512. [7] Z.Feng,D.Guo,D.Tang,N.Duan,X.Feng,M.Gong,L.Shou,B.Qin, ChatGPT. Furthermore, we incorporate BLEU and METEOR T.Liu,D.Jiangetal.,“Codebert:Apre-trainedmodelforprogramming scorestoevaluatethedegreeofsimilaritybetweenthepatches andnaturallanguages,”inFindingsoftheAssociationforComputational |
produced by the model and the actual patches. Linguistics:EMNLP2020,2020,pp.1536–1547. [8] M. Fu, V. Nguyen, C. K. Tantithamthavorn, T. Le, and D. Phung, Result. Fig 8 presents the experimental results of the vulner- “Vulexplainer:Atransformer-basedhierarchicaldistillationforexplain- ability repair. ChatGPT failed to generate correct repair ing vulnerability types,” IEEE Transactions on Software Engineering, patches for all of the vulnerable functions in our testing pp.1–17,2023. [9] M. Fu and C. Tantithamthavorn, “Linevul: A transformer-based line- data.Incontrast,thefine-tunedlanguagemodelbaselinescan level vulnerability prediction,” in 2022 IEEE/ACM 19th International correctly repair 7%-30% of the testing function. The BLEU ConferenceonMiningSoftwareRepositories(MSR). IEEE,2022. and METEOR scores further demonstrate that repair patches [10] M.Fu,C.Tantithamthavorn,T.Le,Y.Kume,V.Nguyen,D.Phung,and J.Grundy,“Aibughunter:Apracticaltoolforpredicting,classifyingand generated using baseline methods exhibit greater proximity to repairing software vulnerabilities,” arXiv preprint arXiv:2305.16615, the true patches compared to those generated through Chat- 2023. GPT methods. These results indicate that vulnerability repair [11] M.Fu,C.Tantithamthavorn,T.Le,V.Nguyen,andD.Phung,“Vulre- pair:at5-basedautomatedsoftwarevulnerabilityrepair,”inProceedings is a more challenging task compared with other vulnerability ofthe30thACMJointEuropeanSoftwareEngineeringConferenceand prediction tasks, where ChatGPT struggle to generate correct Symposium on the Foundations of Software Engineering (ESEC/FSE), repairsforvulnerablefunctions.Thus,afine-tuningstepusing 2022,pp.935–947. [12] D. Guo, S. Ren, S. Lu, Z. Feng, D. Tang, L. Shujie, L. Zhou, domain-specific data is crucial for ChatGPT to generalize its N. Duan, A. Svyatkovskiy, S. Fu et al., “Graphcodebert: Pre-training ability for the vulnerability repair task. code representations with data flow,” in International Conference on LearningRepresentations,2021. [13] H. Husain, H.-H. Wu, T. Gazit, M. Allamanis, and M. Brockschmidt, V. CONCLUSION “Codesearchnetchallenge:Evaluatingthestateofsemanticcodesearch,” arXivpreprintarXiv:1909.09436,2019. [14] E.A.NapoliandV.Gatteschi,“Evaluatingchatgptforsmartcontracts In this paper, we empirically evaluate the performance of vulnerability correction,” in 2023 IEEE 47th Annual Computers, Soft- promptingtwoversionsofChatGPT(gpt-3.5-turboandgpt-4) ware, and Applications Conference (COMPSAC). IEEE, 2023, pp. 1828–1833. for four common vulnerability tasks: locating vulnerabilities, [15] OpenAI,“Chatgpt,”https://openai.com/blog/chatgpt,2022. identifying vulnerability types, estimating severity scores, and [16] ——,“Gpt-4technicalreport,”2023. suggesting repair patches. We compare the performance of [17] H.Pearce,B.Tan,B.Ahmad,R.Karri,andB.Dolan-Gavitt,“Examining zero-shotvulnerabilityrepairwithlargelanguagemodels,”in2023IEEE ChatGPT with other pre-trained language models that have SymposiumonSecurityandPrivacy(SP). IEEE,2023,pp.2339–2356. significantlysmallermodelsizesthanChatGPTbuthavebeen [18] D. Sobania, M. Briesch, C. Hanna, and J. Petke, “An analysis of fine-tuned to perform software vulnerability prediction tasks. the automatic bug fixing performance of chatgpt,” arXiv preprint arXiv:2301.08653,2023. Throughanassessmentencompassingover190,000real-world [19] J.White,S.Hays,Q.Fu,J.Spencer-Smith,andD.C.Schmidt,“Chatgpt C/C++ functions, ChatGPT yielded the least favorable out- prompt patterns for improving code quality, refactoring, requirements comesacrossallvulnerability-relatedtasks,notablystruggling elicitation, and software design,” arXiv preprint arXiv:2303.07839, 2023. to generate accurate patches for the vulnerability repair task. [20] C. S. Xia and L. Zhang, “Keep the conversation going: Fixing These findings highlight the imperative of possessing security 162 out of 337 bugs for $0.42 each using chatgpt,” arXiv preprint expertiseinaddressingsoftwarevulnerabilitypredictiontasks, arXiv:2304.00385,2023. [21] C. Zhang, H. Liu, J. Zeng, K. Yang, Y. Li, and H. Li, “Prompt- a facet not assimilated by ChatGPT during its extensive pre- enhancedsoftwarevulnerabilitydetectionusingchatgpt,”arXivpreprint trainingphase.Thus,anadditionalroundoffine-tuningstands arXiv:2308.12697,2023. asapivotalrequirementforChatGPTtoeffectivelygeneralize and undertake software vulnerability tasks. |
2310.12419 Toward Unbiased Multiple-Target Fuzzing with Path Diversity HuanyaoRong WeiYou∗ IndianaUniversityBloomington RenminUniversityofChina XiaoFengWang TiaohaoMao IndianaUniversityBloomington IndianaUniversityBloomington Abstract 1 Introduction Fuzzingisatestingtechniquethatexaminesaprogram’sbe- Directedfuzzing is an advancedsoftware testing approach haviorbysubjectingittoarangeofgeneratedinputs,identi- thatsystematicallyguidesthefuzzingcampaigntowarduser- fyinganyanomalousbehaviorsthatariseandreportinginputs defined target sites, enabling efficient discovery of vulner- causing such anomalies. In recent years, coverage-guided abilities related to these sites. However,we have observed fuzzing[1,4,5,20]hasmadeasignificantstrideinuncovering thatsomecomplexvulnerabilitiesremainundetectedbydi- softwarevulnerabilities.However,coverage-guidedfuzzing rectedfuzzersevenwhentheflawedtargetsitesarefrequently isdesignedtotestallcoderegionswithinaprogram,butin testedbythegeneratedtestcases,becausetriggeringthese certainsecurityscenarios,suchasstaticanalysisreportver- bugs often requires the execution of additional code in re- ification[15]andpatchtesting[11],thefocusisonfuzzing latedprogramlocations.Furthermore,whenfuzzingmultiple specificcodelocationsknownastargetsites.Asaresult,di- targets,the existing energy assignment in directed fuzzing rectedfuzzing[12],buildinguponcoverage-guidedfuzzing, lacks precision anddoes notensure the fairness across tar- hasemergedasanalternative,receivingalotofresearchat- gets,whichleadstoinsufficientfuzzingeffortspentonsome tention [13,19,24,30,35,43,44]. Thekeyidea ofdirected deepertargets. fuzzingistoapproachandtestthetargetsitesbyprioritizing Inthispaper,weproposeanoveldirectedfuzzingsolution the seeds (stored test cases) whose execution traces get to namedAFLRUN,whichfeaturestargetpath-diversitymetric thevicinityofthetargetsites.Thisisachievedbyevaluating andunbiasedenergyassignment.Firstly,wedevelopanew theseedsusingadistanceoracleandassigningmoreenergy coverage metric by maintaining extra virgin map for each (whichdeterminestheeffortspentonfuzzingagivenseed)to coveredtargettotrackthecoveragestatusofseedsthathitthe thosecomingclosertothetargetsthanothers.Inthisway,the target.Thisapproachenablesthestorageofwaypointsthathit fuzzerisexpectedtoquicklydiscoverthetestcasescapable atargetthroughinterestingpathintothecorpus,thusenriching ofreachingthetargetsitesandactivatingthesecurityflaws thepathdiversityforeachtarget.Additionally,weproposea (thevulnerabilities)atthesesites(i.e.,triggeringthecrash). corpus-levelenergyassignmentstrategythatensuresfairness foreachtarget.AFLRUNstartswithuniformtargetweight Listing1ExampleofPreconditionedTrigger and propagates this weight to seeds to get a desired seed 1 const char* get_string() { weightdistribution.Byassigningenergytoeachseedinthe 2 if (/*Easy Constraint*/) return "default"; corpusaccordingtosuchdesireddistribution,apreciseand 3 ... // Constaints solvable by genetic approach 4 return get_input(); // Get attacker-controllable input unbiasedenergyassignmentcanbeachieved. 5 } Webuiltaprototypesystemandassesseditsperformance 6 void foo() { 7 char victim[128]; usingastandardbenchmarkandseveralextensivelyfuzzed 8 const char* p = get_string(); real-worldapplications.Theevaluationresultsdemonstrate 9 if (/*Hard Constraint*/) thatAFLRUNoutperformsstate-of-the-artfuzzersintermsof 10 strcpy(victim, p); // Potential Overflow 11 } vulnerabilitydetection,bothinquantityandspeed.Moreover, AFLRUNuncovers29previouslyunidentifiedvulnerabilities, including8CVEs,acrossfourdistinctprograms. Limitationsandchallenges.However,directedfuzzingtoday are impeded by the limitations of techniques, rendering it ∗Correspondingauthor. less effective than expected in discovering vulnerabilities. 1 4202 nuJ 6 ]RC.sc[ 2v91421.0132:viXraSpecifically,asobservedinourresearch,oftentimes,hitting both PFA and PTA. For this purpose, AFLRUN maintains atargetsitedoesnotnecessarilytriggerthevulnerabilityit an extra virgin map for each target to record the coverage carries:thatis,thefuzzingfailstoproduceadetectablecrash. statusofallseedsthathitthetarget.Whendecidingwhether Instead,toactivatetheflaw,theexecutiontraceneedstocover amutatedtestcaseshouldbeusedtofuzzaprogramagain someothercodelocations,whichcouldbefarawayfromthis (thatis,storingthetestcaseintothefuzzer’scorpusasaseed), targetsite.Forexample,inListing1,theflawatthetargetsite AFLRUNnotonlychecksitsexecutiontracewiththevirgin (Line10)canonlybeactivatedwhentheseed’sexecutiongoes mapofthecoverage-guidedfuzzertoevaluateitspotentialto throughLine4,insteadofLine2,sincereceivingalonginput improvethetotalcodecoverage,butalsowithourextravirgin isthepreconditionforoverflowingthevulnerablebufferat mapstodetermineitscapabilityofdiversifyingtheexecution thetargetsite.Wecallsuchascenario,inwhichauniquepath pathsinvolvingthetargetsite.Itisimportanttonotethatthe needstobecoveredbeforehittingthevulnerabletargetsitefor extravirginmapassociatedwiththetargetcapturescoverage |
triggeringsuchvulnerabilityatthetarget,preconditionedflaw bothbeforeandafterexecutionreachesthetarget.Thisap- activationorPFA.Tosumup,PFAcapturesbugsrequiring proachenablesthecomprehensivecaptureofbothPFAand certainpreviouspathstotrigger.Anotherscenarioisthatat PTA. thetargetsiteonlytherootcauseofasecurityflawispresent Second,weintroduceunbiasedenergyassignmenttoen- whiletheflawcanonlybeactivatedinadifferentprogram ablefairexplorationandexploitationofeachtarget.AFLRUN location:asillustratedbytheexampleinListing2,thetarget firstassignseachtargetblock(thebasicblockcontainingthe site(Line15-20)introducesanuninitializedpointer,which targetsite) a weight,whichtakes the same value to ensure hasonlybedereferenced(therebycausingacrash)atLine28 theirfairchancetobevisited.Thenitpropagatestheweights and29.Wecallthisscenariopost-targetactivationorPTA, fromthetargetstoasetofcriticalblocks,whichincludeboth whichcapturesbugstriggeredatcertainpathsfollowingthe the targetblocks visitedbefore anda setofcriticalbound- rootcause. aryblocks:thatis,avisitedblockleadingtoatargetviathe Moreover, in the presence of multiple target sites, a di- inter-proceduralcontrolflowgraph(ICFG),withnoneofother rectedfuzzerissupposedtogeneratetestcasestofuzzthese blocks(includingthetarget)fromtheblocktothetargetbeing sitesinanunbiasedway.However,today’senergyassignment coveredbefore.Foragivenseed,ourapproachcomputesits strategyreliesprimarilyonascalardistanceoraclethatde- energy(whichdeterminesitsmutationpriority)byaddingthe terminesaseed’spriorityusingaverage.Aspointedbythe weightsofthecriticalblocksitcovers.Inthisway,AFLRUN priorwork[29,40,43],thisstrategyfailstotakeintoaccount alwaysprioritizestheseedswiththehighestpotentialstoget the dynamic status of each target(e.g.,whetherit is easier toanewtargetsiteandtheseedsthatcoveranytargetsites, thanotherstoreach),causingglobaloptimumdiscrepancy, andalsoensureseachtargettohaveafairchancetobetested. which could lead to a bias against certain targets or even Whenappliedtogetherwiththetargetedpath-diversitymetric, favortheseedunabletoreachanytarget.Asaresult,deeper theenergyassignmentstrategycanfurtherimprovethepath targetsitesmayreceiveinsufficientfuzzingeffort,potentially diversityofeachtarget. leavingsomevulnerabilitiesattheselocationsundiscovered. We implemented AFLRUN on top of AFL++ [20] and Prior attempts to address the problem mostly focus on de- AFLGo [12], and evaluated it on a standard benchmark signofdifferentdistanceoraclestomitigatethebias[13,29]. Magma[22]andreal-worldprogramsintensivelyfuzzedby Theseapproaches,however,arestilllesseffectiveduetotheir the OSS-Fuzz project [7]. Our evaluation on the Magma continueduseofaggregateinformationlikeaverageacross benchmarkshowsthatcomparedwithstate-of-the-artfuzzers alltargets,therebymissingtheindividualinformationofeach (AFL++ [20],AFLGo [12],Parmesan [35],FishFuzz [43], target,suchastheextenttowhichthepathstoaspecifictar- Hawkeye[13],WindRanger[19]andMOpt[31]),AFLRUN gethavebeencoveredbythecurrentcorpus.Eventhemost achievesanaveragespeedupof168%,109%,235%,183%, recentapproach,FishFuzz[43],whichutilizesavector-based 147%,157%and78%,andtriggers38%,20%,138%,29%, oracleinsteadofadistanceoracle,stilldoesnotpayenough 24%, 14% and 50% more vulnerabilities. In addition, attention to the pathdiversity,ignoring the seedthathits a AFLRUN has discovered 29 previously unknown vulnera- targetvisitedfrequentlybutisassociatedwiththepathsmuch bilitiesinreal-worldprograms,with8CVEIDsassignedso lesstraversedthanothers. far. Solutions.Toaddressthoselimitations,wedevelopedanew Contributions.Wehavemadethefollowingcontributions: directedfuzzerbyenhancingthegreyboxfuzzerwithtwoin- •Newtechniques.Tothebestofourknowledge,wepresent novativetechniques.First,weintroducetargetpath-diversity thefirstdirectedfuzzingtechniquethatimprovespathdiver- metric.Morespecifically,ourfuzzer,calledAFLRUN,aimsat sityandfairnessinenergyassignmentforeachtargetatthe generatingtheseedsnotonlyreachingagiventargetsitebut sametime,inasystematicway.Servingthispurposearetwo coveringasmanypathsinvolvingthetargetaspossible.The new techniques,including a new coverage metric that cap- criticalityofthesepathsinactivatingbugsisemphasizedby tures bothPFA andPTA to improve the chance to activate thefactthatenhancingpathdiversitycaneffectivelyaddress theflawsrelatedtotargetsites,andanewenergyassignment 2strategythatensuresthetargetfairnessandprioritizestesting thathasnotbeencoveredbyanypreviousseeds’execution ofthenewpathsinvolvingthetargets.Botharefoundtobe traces,thetestcasewillbeaddedtothecorpusasaseed.By highlyeffective. incrementallyaddingnewseedsintocorpus,totalcoverage • Implementation, evaluation and findings. We imple- ofthePUTcanbeimproved. mented a prototype system and released its code at In addition,AFL++ maintains a record of the best seed https://github.com/Mem2019/AFLRun.AFLRUNhasdiscov- foreachedge using an array,basedon metrics suchas the |
ered29zero-dayvulnerabilitiesfromthereal-worldsoftware seed’s lengthand execution time. We referto this array as thathavebeenintensivelyfuzzedbefore,whichprovidesevi- thetop-ratedarrayinthispaper.Whenanewseedisadded dencetotheefficacyofourtechniques. tothecorpus,AFL++attemptstoupdatethetop-ratedarray basedontheseed’sedgecoverageandmetrics.Ifanyupdates occur,aprocesscalledqueuecullingselectsasubsetofseeds 2 Background fromthecorpustobemarkedasfavored,andthesefavored seedsarechosenforfuzzingmorefrequentlythantheothers. In this section, we introduce the basic concepts and over- allworkflowofcoverage-guidedfuzzing(§2.1)anddirected fuzzing(§2.2). 2.2 DirectedFuzzing 2.1 Coverage-guidedFuzzing Directedfuzzing,builtuponcoverage-basedfuzzing,focuses Theworkflowofthecurrentcoverage-guidedfuzzingtech- on testing a specific set of user-defined target sites rather nique can be summarizedas follows: (1) Atthe beginning than all code regions. The main concept involves using a ofafuzzingcampaign,oneormoreinputsareprovidedas seedoracle(i.e.,dynamicinformationgatheredbyexecuting the initial seed corpus. (2) The fuzzer selects a seed from thePUTwiththeseedasinput)todeterminetheproximity thecorpus,whichisthenmutatedtocreateatestcasethatis betweentheseedandthetargetsites.Thisoracleisthenused executedbytheprogramundertest(PUT);thismutationand to assign energy for preferentially testing these sites. The executionprocessisrepeatedseveraltimesforeachselected energyassignedtoaseedisdefinedbythenumberoftimes seed. (3) If the testcase triggers any new behaviornot yet thefuzzerisgoingtomutatetheseedandexecutethePUT triggeredbythecurrentcorpus,itisstoredasaseedforfuture usingthemutatedtestcaseasinput. mutation.(4)Thefuzzerrepeatssteps2-3inaninfiniteloop. Theseedoracleiscommonlyreferredtoasthedistance Sinceourapproachfocusesonimprovingenergyassignment inthecontextofdirectedfuzzing.Toachievesuchanoracle, andseedstoragebymodifyingsteps2and3inAFL++[1,20], both static analysis and dynamic information are required. wewilldiscusshowAFL++implementsthesetwostepsin StaticanalysisofthePUTcomputesthedistancefromeach greaterdetail. codelocation(e.g.,basicblock)toalltargetsites,typically InAFL++,thefuzzerprocessandthePUTprocesssharea averagedusingthe harmonicmean. Duringa fuzzingcam- segmentofmemorytorecordtheexecutionpathofthePUT, paign,eachtimethePUTisexecutedwithaparticularseed allowingthefuzzertoaccessthisinformation.Eachbytein as input,the seed’s distance value to targetsites (i.e.,seed thesharedmemoryrepresentsanedgeconnectingtwobasic oracle)canbeobtainedbycalculatingthearithmeticmean blocks.ThePUTisinstrumentedsothateachtimeanedge ofthedistancevaluesoftherelevantcodelocationscovered is traversedduring execution,the corresponding byte is in- crementedbyone1.Inthesharedmemory,thefuzzerobtains duringtheexecution. a bitmap that abstractly represents the execution path of a Withthisseedoracle,directedfuzzingassignsenergyto singlerun.Inthispaper,werefertothisbitmapastheexecu- eachseedsuchthatseedswithlowerdistancevaluesreceive tiontrace.Additionally,AFL++maintainsaglobalbitmapto higheramountsofenergy.Byadjustingenergyassignment recordallbitscoveredbyatleastoneexecutiontraceofseeds tofavorseedsclosertothetargetsites,thefuzzingcampaign inthecorpussofar.Werefertothisbitmapasthevirginmap focusesontestingthesespecificsites. inthispaper.Specifically,thevirginmapisanarraywiththe samelengthastheexecutiontrace,initializedwithallbitsset to1.Whenanewseedcoversanewbit,thecorresponding 3 Motivation bitinthevirginmapissetto0.Eachtimeamutatedtestcase isexecuted,AFL++comparesthegeneratedexecutiontrace withthevirginmap.Iftheexecutiontracecoversanewbit In this section,we present a PTA vulnerability as our mo- tivating example and discuss the directed fuzzing scenario 1AFL++classifiesvalueofeachnon-zerobyteaccordingto8predefined intendedtodiscoversuchavulnerability.(§3.1)Wealsoex- ranges,eachcorrespondingtoabitinthebyte.Ultimately,thebyteissetto aminehowcurrentdirectedfuzzingapproachesfailtofindit, thebitcorrespondingtotheclassifiedrange.Thecomparisonbetweenthe executiontraceandthevirginmapisperformedatbitlevel. whileAFLRUNiscapableofsuccessfullydetectingit.(§3.2) 32 Listing2Simplifiedvulnerablecodesnippet. dump_bfd 1 typedef struct bfd_symbol { 2 struct bfd *the_bfd; 0 3 /* other fields are omitted */ 1 1 bfd_mach_o_ 4 } asymbol; slurp_symtab disassemble_data 5 get_synthetic_ 6 asymbol *synthsyms; symtab 7 long *(bfd_get_synthetic_symtab)(...); 8 0 compare_symbols 9 void dump_bfd (...) { xmalloc 10 bfd_get_synthetic_symtab(..., &synthsyms); 11 disassemble_data(...); 12 } Figure1:Partialcallgraphthatinvolvesthecriticalfunctions 13 totriggerthevulnerability.Anothertargetinxmallocisalso 14 /* bfd_get_synthetic_symtab for Mach-O executable */ |
included. The distance value ofeachfunction is annotated 15 long bfd_mach_o_get_synthetic_symtab(..., asymbol **ret) { 16 size_t size = count * sizeof(asymbol) + 1; abovetherectangularinred. 17 char *s_start = bfd_malloc(size); 18 *ret = (asymbol *) s_start; 19 /* intialize each field of the asymbol structure, 3.1 VulnerabilityandFuzzingScenario 20 except for the the_bfd pointer field */ 21 } We use the discovery of a zero-day vulnerability (CVE- 22 23 /* disassemble_data finally calls compare_symbols */ 2023-25588) in binutils as an example to demonstrate 24 int compare_symbols(const void *ap, const void *bp) { the limitations of existing techniques and motivate the 25 /* a and b point to the elements in synthsyms. */ ideas of AFLRUN. Listing 2 shows the simplified vul- 2 26 7 c co on ns st t a as sy ym mb bo ol l * *a b = = * * ( (c co on ns st t a as sy ym mb bo ol l * ** *) ) a bp p; ; nerable code snippet. The dump_bfd function invokes the 28 /* code to dereference a->the_bfd and b->the_bfd, bfd_get_synthetic_symtab function pointer (Line 10) 29 resulting in access of uninitialized pointer */ to create synthetic symbols for indirect symbols and in- 30 } 31 vokes the disassemble_data function (Line 11) to dis- 32 /* Another target site detected by static analysis */ assemble the contents of an object file. When processing 33 void * xmalloc (size_t size) { a Mach-O executable, the function pointer points to the 34 void *newmem = malloc (size); 35 return (newmem); bfd_mach_o_get_synthetic_symtab function (Line 15- 36 } 21), in which an array of the asymbol structure is allo- catedwithoutinitializationforitsthe_bfdpointerfield.A pointer to the allocated array is stored in the global vari- ablesynthsyms.Thedisassemble_datafunctionperforms Whenemployingsuchacheckeronbinutils,itreportsmul- complexlogicandfinallycallsthecompare_symbolsfunc- tipleprogramlocations,whicharetreatedastargetsitesfor tiontosortsymbols.Duringcomparison,thethe_bfdfield directedfuzzing.Therootcauseofthisvulnerability,located oftheelementsstoredinthesynthsymsarraywillbederef- atLine17,isoneofthesetargetsites.Additionally,thereare otherfalsepositivetargetsites,includingLine34atxmalloc, erenced,resultinginaccessofuninitializedpointer. whichissimplyawrapperforthemallocfunction.Figure1 Figure1illustratesthepartialcallgraphinvolvingthecriti- alsoincludessomefunctionsthatinvokexmalloc.Forsim- calfunctionsneededtotriggerthevulnerability.Inthefigure, plicity,weonlyshowtwofunctionsthatcallxmalloc,asit thesolidlinesrepresentnormalfunctioncallslinkingcaller isautilitycommonlyusedbynumerousfunctions.Thus,an andcallee,thedashedlineindicatesaindirectcallunableto idealdirectedfuzzershouldbeabletodiscoverthevulnerabil- beidentifiedbystaticdistancecomputation,andthezigzag itybygeneratingatestcasethatbothcreatesanddereferences lineshowsmultiplenormalcallswithomittedintermediate theuninitializedvariable,despitetheinterferencefromfalse nodes.Asdepicted,inordertotriggerthevulnerabilityatthe positive target sites like Line 34. Besides, it is worth not- locationofdereference(Line28incompare_symbols),atest ing that these target locations conform to the format used casemustcoverthislocationafterexecutingthelocationofal- byAFLGo[12],insteadoftargetswithexplicitdependency location(Line17inbfd_mach_o_get_synthetic_symtab, informationrequiredbysomeworks[27,34]. therootcauselocationofthevulnerability).Itisimportantto notethatthesetwolocationsaredistantfromeachotherin thecodebase. 3.2 LimitationsandSolutions Considerasecurityscenariothatutilizesdirectedfuzzing toverifyareportfromstaticanalysis.Anaggressive,yetcom- However,the current state-of-the-art directed fuzzer strug- prehensiveandscalablestaticcheckermightidentifypotential gles to efficiently trigger this bug under the scenario risksifitdetectsafunctionthatallocatesapieceofheapmem- we described earlier, even if the flawed target site at orywithoutinitializingthecontentwithinthefunctionscope. bfd_mach_o_get_synthetic_symtab is already covered 4bythecorpusduringthefuzzingcampaign.Weoutlinetwo seedinS andS doesnotdiffergreatly.However,sincethe a b limitationsthatcontributetothisissueandexplainhowour sizeofS issmall,thetotalenergyassignedtoseeds in S a a approachesaddressthem. isalsolow,causingthefuzzingcampaigntolosedirectness First,currentdirectedfuzzersstillrelyonthecoveragemet- towardtargetsiteLine17andbecomebiasedtowardLine34. ricofcoverage-guidedfuzzing,whichisdesignedtoimprove Instead,aswedonotknowwhichtargetsitecontainsthe the total code coverage of the corpus. Specifically,once a vulnerability beforehand, the importance of each target is constraintissolved,theedgeoftheconstraintwillbemarked unknownapriori.Therefore,abestschemeistotreateach asnon-virgininthevirginmap,meaningthatsubsequenttest target(e.g.,Line17andLine34)equallyduringthefuzzing casesthatcoverthesameedgewillnotbestoredinthecorpus. campaign. Our approach achieves this by assigning a uni- Inthisexamplevulnerability,iftheconstraintsonthepathto formweighttoeachtargetandpropagatingsuchweightto |
Line28(i.e.,thedereferenceofthe_bfd)aresolvedwitha seedsforenergyassignment. Tobespecific,theweightas- seedthatcannotcoverLine17(i.e.,thelocationthatcreates signedtoS a is |S1 a|+ |Sa|+1 |Sb|,andtheweightassignedtoS b theuninitializedpointer),theedgesoftheseconstraintsare is 1 .2Since|S |isamuchsmallervaluethan|S |,the nolongerconsideredvirgin.Consequently,ifatestcasethat |Sa|+|Sb| a b weightassignedtoeachseedofS issignificantlygreaterthan a coversthetargetsiteofuninitializedpointerallocationlater thatofS .Therefore,eventhoughS comprisesonlyasmall b a solves any of these constraints,it will not be stored in the setofseedsinthecorpus,Line17willstillbeassignedan corpus. As a result,seeds that coverthis target site cannot equalamountofweightastheothers,ensuringthatitreceives makeprogressontheseconstraintsbytakingadvantageof enoughenergytotriggerthebug. thegeneticapproachemployedbythegreyboxfuzzer,which ultimately restricts the subsequent fuzzing campaign from discoveringthispotentialcrash. 4 DesignOverview We have observedthat,in orderto triggerthis bug,path In this section, we provide a brief design overview of diversity of the target site with the uninitialized pointeral- locationiscrucial.Inotherwords,weaimtomaximizethe AFLRUN,includingitsworkflow(§4.1)andthefuzzingloop (§4.2). totalcodecoveragegiventhetargetsiteLine17iscovered, inordertoincreasethelikelihoodofexecutingthecodeloca- tionthataccessestheuninitializedpointer.Ourapproach,by 4.1 Workflow maintaininganadditionalvirginmapforthistargetsite,does storetestcasesthatimprovepathdiversityofthistargetsite Figure2illustratestheworkflowofAFLRUN.Inthestatic inthecorpus,eveniftheoriginalcoveragemetricofAFL++ stage,AFLRUNfirsttakestheprogramsourcecodeandtar- woulddeemthetestcaseuninteresting. get sites forstatic analysis and instrumentation. The static analysisgeneratesapartialICFGwithverticesrepresenting Second,theenergyassignmentinexistingdirectedfuzzing, basicblocksthatcanreachatleastoneofthetargetblocks, whichreliesonthescalardistanceoracle,maybebiasedto- alongwithdistancevaluestothesetargetblocksforeachver- wardcertaintargets,resultingininadequatefuzzingefforts tex. Eachoftheseblocksisinstrumentedwithourruntime spentonthevulnerabletargetsite.Inthisparticularexample callbackfunction.Inthedynamicstage,ourunbiasedenergy scenario,wedemonstratethebiastowardthetargetLine34. assignmentgeneratesenergyvaluesforallseeds,whichdeter- Forsimplicity,we only considerthese two target sites and minethenumberofmutationsandexecutionsforeachseed. partoftheprogramillustratedinFigure1,andassumethere For each execution of a mutated test case,we employ our are only two categories of seeds in the corpus: S and S . a b targetpath-diversitymetrictodeterminewhetherthetestcase Seeds in S can visit target site Line 17,while those in S a b shouldbestoredinthecorpus.Ifso,wealsouseittoupdate cannot.Bothcategoriesofseedsareabletocoverxmalloc criticalblocksandtargetclusters.Targetclustersareutilized throughslurp_symtabanddisassemble_data.SinceLine togrouptargetsexhibitingsimilarbehavior,therebyreducing 17 is an uncommonly covered target, S makes up only a a theruntimeoverhead,particularlywhenthenumberoftargets smallproportionofthecorpus.Toavoidlossofgenerality,we issubstantial(discussedin§5.2). calculatetheseeddistancevaluesusingasimplifiedmethod that approximately represents current directed fuzzing ap- proaches[12,13,35]:thedistancevalueofeachblockiscom- 4.2 FuzzingLoop putedbytheaverageofminimumdistancestoalltargetsthat itcanreachviathegraph.Usingthedistancevalueofeach Algorithm1providesahigh-leveloverviewofthefuzzing functioninFigure1,wecancalculatethedistancevaluesof loopinAFLRUN.Eachiterationoftheoutermostloopcon- S andS as 2+1+1+0+0 =0.8and 2+1+1+0 =1,respectively. stitutesonecycle,duringwhichallseedsin thecorpusare a b 5 4 ItisworthnotingthatcoveringLine17onlycontributesone additionaltermanddoesnotsignificantlyinfluencetheaver- 2Here,weassumethattheseedsin|Sa|and|Sb|haveequalimportance; however,inreality,theenergyassignmentamongseedsinsuchsetisnot agescalarvalue.Asaresult,thefinalenergyassignedtoeach uniform.See§6.3formoredetails. 5Instrumented Targets Clusters t1 t2 t3 Source Program Seed with Code Critical Energy t1 t2 t3 new bits Updates Static A &nalysis Distance Blocks New Seed Values Instrumentation Seeds Mutation Updates Targets & Target Path-Diversity Metric Partial Execution Critical Blocks ICFG Unbiased Energy Assignment Seed Corpus Figure2:WorkflowofAFLRUN. Algorithm1FuzzingLoopofAFLRUN 5 TargetPath-DiversityMetric Require: Initialcorpus 1: repeat Inthissection,wewilldiscusshowourcoveragemetricim- 2: seed_energy:=assign_energy(E,corpus) provesthepathdiversityofalready-coveredtargets.Wein- 3: for(seed,energy)∈seed_energyindescendingorderdo troduceourmultiplevirginmapsin§5.1andexplainhowwe 4: forifrom1toenergydo 5: s′:=mutate_input(seed) reduceoverheadthroughclusteringin§5.2. 6: t′:=execute(s′) 7: ift′crashesthen 8: adds′tocrashes 5.1 VirginMapsforTargetPathDiversity 9: elseifhas_new_coverage(t′)then |
10: adds′tocorpus 11: ift′updatescriticalblocksthen Algorithm2CoverageMetricforTestCase 12: breaktheoutermostloop 13: endif Require: path_traceandvirgin_maps 14: endif 1: store:=false 15: endfor 2: data:=set() 16: endfor 3: fori:=1toNdo 17: untiltimeoutreachedorabort-signal 4: ifpath_trace[i]=1then 18: return crashes 5: updates:=set() 6: formap∈virgin_mapsdo 7: ifmap[i]=1then 8: map[i]:=0 supposedtobeselectedforfuzzingonce.Atthebeginning 9: store:=true ofeachcycle,theassign_energyfunction,ourunbiaseden- 10: updates.insert(map) 11: endif ergyassignment,isinvokedtoassignanenergyvaluetoeach 12: endfor seed. Unlike other greybox fuzzing approaches, including 13: if|updates|̸=0then directedones,ourenergyassignmentalgorithmoperatesglob- 14: data.insert(updates) 15: endif ally for the entire corpus rather than locally for individual 16: endif seeds.Thisglobalperspectiveiscrucialforensuringunbiased 17: endfor energyassignment. 18: return store,data Inthesecondloop,weiteratethrougheachseed-energypair returnedfromassign_energyindescendingorderbasedon Givenaparticularcorpusstateduringafuzzingcampaign, energy, which allows AFLRUN to fuzz seeds with higher thepathdiversityofatargetisdefinedbythetotalcoverage energyfirst. Theseedismutatedusingmutate_input,the ofseedsthatcoverthistarget.Toenhancethispathdiversity, mutationalgorithmfromAFL++[20],andexecutedbythe weproposetointroduceanextrasetofvirginmaps.Aswe PUTwithourinstrumentationusingexecute.Theexecution discussed in §2.1,AFL++ [20] uses a virgin map to store results t′ are examined similarly to other greybox fuzzing thecoverageinformationofthecurrentseedcorpus.When methods.However,has_new_coverageisnowreplacedby theexecutiontraceofatestcasecoversanynewbitsnotyet ourtargetpath-diversitymetric,ratherthanthepreviouscover- coveredbythecorpus,thevirginmapisupdated,andthetest agemetricusedinAFL++.Additionally,ifanewseedupdates caseisstoredtothecorpus.Inourapproach,ratherthanusing thecurrentcriticalblocks,thecycleisimmediatelyhaltedto asinglevirginmap,wemaintainandcomparetheexecution restartthe nextcycle. This is because ourunbiasedenergy traceofeachtestcaseagainstmultiplevirgin maps. These assignmentdependsoncriticalblocks;thus,ifanyupdates multiplevirginmapsconsistoftheoriginalvirginmapused occurwiththem,AFLRUN shoulddiscardtheobsoleteen- byAFL++,referredto as primaryvirgin map,anda setof ergyresultsandre-assignenergyusingtheupdatedcritical extravirginmapsderivedfromalltargetscoveredbythetest blocks. case,referredtoastargetvirginmaps.Afterexecutingeach 6testcase,besidescomparingitsexecutiontracewithprimary ationrule[9]betweentwoitems,denotedasi ⇒i ,where a b virgin maplike AFL++,we also compare itwithourextra i ∈I andi ∈I.Intuitively,thisrulesuggeststhatwheni a b a targetvirginmaps.Ifanyofthesevirginmapsindicatethat appearsinasett withinthedatabase,i isalsolikelytoap- b new bits have been covered,the test case will be stored to pear.Severalmetricshavebeendefinedtomeasuretheextent thecorpus,andthebitsofcorrespondingvirginmapwillbe towhichagivenruleholdsinagivendatabase.Thesupport markedasnon-virgin. countofanitemsetX ⊆I isthenumberoftimestheitemset ThisapproachisdetailedinAlgorithm2.Theparameter appears in the database. In otherwords,the support count, path_traceisabitarrayoflengthN,whichistheexecution denotedasσ(X),isthenumberoft∈DsuchthatX ⊆t.The traceoftestcasethathasjustbeenexecuted.Theparameter confidenceofarulei ⇒i isaratiomeasuringthefrequency a b virgin_mapsisasetofvirginmapsincludingprimaryvirgin ofi appearinggiventhati appears,calculatedby σ({ia,ib}) . mapandtargetvirginmaps,eachofwhichisalsoabitarray Inthb ispaper,weconsideraa rulei ⇒i tobevalidifbσ o( ti ha) its a b oflengthN.Thealgorithmissomewhatsimilartotheoriginal supportcountσ({i ,i })anditsconfidencearelargerthana a b oneofAFL++,exceptwecompareexecutiontracewithmul- specifiedthreshold. tiplevirginmapsinsteadofasinglevirginmap.Furthermore, Whenanewtargetiscoveredbythecorpus,anewclus- foreachbitlocationwhereanupdateoccurs,werecordall tercontaining only that target is created. At this point,the thevirginmapsthathaveexperiencedanupdateatthatbit virginmapselectionforthistargetisequivalenttothenaive location.Whilethisinformationisnotusefulfordetermining implementationmentionedearlier.Asthefuzzingcampaign whethertostorethetestcase,itisusefulfortargetclustering, progresses,moredynamicinformationisgathered,enabling whichwillbediscussedlater. us to merge clusters together. Specifically, we use data from all seeds in the corpus, collected through Algorithm 5.2 TargetClustering 2,asadatabaseforassociationrulemining[9].Thisallows AFLRUNtoidentifytargetvirginmapsthatcanbeclustered Anotherquestiontoconsiderishowtoobtainthesetoftar- together.InAlgorithm2,wecanobservethatdataconsists getvirginmapsfromasetoftargetscoveredbyatestcase. ofsetsofclusters,aseachvirginmapcorrespondstoacluster. Anaiveapproachwouldbetomaintainatargetvirginmap |
We treat each clusteras an item and considerthe union of for each of the targets that have been covered by seeds in datafromallseedsinthecorpusasthedatabaseinthecon- thecorpus.However,thisapproachcouldsufferfromperfor- textofassociationrulemining.Additionally,sinceourdataset manceoverhead:sincecomparingtheexecutiontracewith isconstructedbyjoiningthedatasetofeachindividualseed, virgin maps is a frequent event, a large number of targets wedenotethedatasetofasingleseeds,whichisasubsetof coveredbyeachtestcasewouldrequirecomparisonswitha theentiredataset,asI . s correspondinglylargenumberofvirginmaps,resultingina Algorithm3outlinestheprocessofupdatingsupportcount non-negligibleoverhead.Initially,weimplementedthisnaive afteranewseedisaddedtothecorpus.Theparameterdata approachand,byobservinghoweachtargetvirginmapwas comesfromthereturnvalueofAlgorithm2,andtheparameter updatedwithnewbitsfromtheexecutiontrace,wediscovered support_count is a global map used to record the support thatsomevirginmapsfrequentlyupdatethesamebitssimul- count of each itemset with one or two elements. For each taneously.Thegeneralideaisthatwecanclusterthesevirgin setindata,wecountbothsingleitemsandpairsofitemsby mapsintoasinglevirginmap.Thiscanreducetheoverhead 1 insteadof1.Thisdesignchoiceismadetopreventbias |data| causedbyrepeatedcomparisonswhilestillmaintainingthe causedbysomeseedsthattriggermanynewbits.(Remember desiredpathdiversity. that each element in data corresponds to a new bit.) As a Obtainingclusters.Toselectthesetofclusterscorrespond- result,weonlyassignatotalsupportcountof1foreachseed, ingtotheexecutionofatestcase,AFLRUNmergesallclus- whichisthendistributeduniformlyamongallsetsofitemsit terscontainingthetargetscoveredduringtheexecution.Each contains. clustercorrespondstoonevirginmapandviceversa.Byas- semblingtheseclusterstogetherwiththeprimarycluster,we Algorithm3SupportCountUpdateforEachNewSeed can getthe setofvirgin maps usedin Algorithm 2. Foran Require: dataandsupport_count in-depthdepiction,refertoAppendixG. 1: foritems∈datado Association rule mining. Before discussing the details of 2: foreachsingleitemi∈itemsdo 3: support_count[{i}]+= 1 ourclustering algorithm,we will first introduce some con- |data| 4: endfor cepts related to association rule mining used in this paper, 5: foreachpairofitems{ia,ib}⊆itemsdo whichdifferslightlyfrom the originaldefinitions. Assume 6: support_count[{ia,ib}]+= |da1 ta| wehaveagivensetofitemsI={i ,i ,...,i }andadatabase 7: endfor 1 2 n D={t ,t ,...,t }.Eachelementt inDisdefinedasasubset 8: endfor 1 2 m ofI(i.e.,∀ t⊆I).Inotherwords,thedatabaseconsistsof t∈D multiplesubsetsofitems.Inthispaper,wedefineanassoci- UsingthesupportcountfromAlgorithm3,wecancalculate 7theconfidencevalueofagivenrulei a⇒i busingtheformula A describedearlier. B K Clustering.Givenanassociationrulei ⇒i ,ifbothitssup- a b C D 2 L portcountandconfidencearehigherthanthethresholdvalues, wecanconsiderittobevalid.Thissemanticallyimpliesthat H F E iftheexecutiontraceofanewseedcoversanewvirginbit G I ini ,itwilltypicallyalsocoverthesamenewvirginbitini . a b 1 J Inotherwords,thebehaviorofvirginbitupdatesini isvery a similartothatofi b,sowecanmergesuchredundantcluster Figure3:Inter-proceduralControlFlowGraph i into i to reduce overhead while keeping the capability a b ofimprovingpathdiversityofcoveredtargets.Finally,itis importanttonotethattheprimaryclustercannotbemerged t, we can define a path3 toward the target in the ICFG as intoanyothercluster,butotherclusterscanbemergedinto follows: it. v →v →...→v →t 1 2 n In the path above, v with i∈{1,...,n} are basic block i 6 UnbiasedEnergyAssignment verticesintheICFG,andeacharrowiseitheracontrolflow edge or a call edge that connects two adjacent vertices in Inthissection,wedescribethedefinitionofcriticalblocks the ICFG. The idea behind critical boundary blocks is to for each target (§6.1) and the process of selecting favored findeachblockvisitedbythecorpussuchthatthereexistsa seeds(§6.2). Wethenintroducehow AFLRUN assignsen- pathfromthisblocktotarget,andallverticesalongthispath ergyamongseedsatthebeginningofeachcyclewithsuch arebasicblocksnotyetvisitedbythecorpusexceptforthe information(§6.3). blockitself.Thisdefinitionalignswiththeintuitionoffinding coveredblocksattheboundarymentionedearlier,withthe uncoveredblocksconsideredastheunexploredpart.Formally, 6.1 CriticalBlocks criticalblocksofanuncoveredtargett canbedefinedasall blocksv ∈Rsuchthatthereexistsapathfromv tot with 1 1 WefirstlydefineasetRasthesetofallbasicblocksthathave ∀ v∈/R. beencoveredbythecurrentseedcorpus,withv∈Rdenoting v∈{v2,v3,...,vn,t} Example. We provide an example to illustrate concept of acoveredblockwithintheset.Next,wedefinecriticalblocks criticalblocks.Figure3istheICFGofaprogram,with1and C foreachtargett asasubsetofR.Theunderlyingideaisto t 2astargetblocks.Wenowhavethreeseedsincorpuswith identifyasetofblocksforeachtargetatagivenstate,sothat pathsA→B→C→H,A→B→D→E andA→K→2. weshouldconcentrateourfuzzingenergyonseedsthatcover Wemarkbasicblockscoveredbythecorpusingray.Among |
theseblocks,ultimatelyenablingmoreefficientexploration theseblocks,CandDarecriticalblocksoftarget1,because orexploitationofthetarget.Inthissection,weintroducethis wecanhavetwopathstotargetC→1andD→F →G→ concept. 1 respectively,with F,G,1 not yet covered by the corpus. For covered targets. During a fuzzing campaign,we can Furthermore,2itselfisthecriticalblockoftarget2,because categorizethesetofalltargetsintotwogroups:onesetcon- thetargethasalreadybeencoveredbythecorpus. sists of targets already covered by the current corpus (i.e., t∈R),andtheothersetcontainstargetsnotyetcoveredby 6.2 FavoredSeedSelection thecurrentcorpus(i.e.,t∈/R).Ifatargetisalreadycovered, thecriticalblockforthistargetissimplythetargetblockitself. Besidesatargetvirginmapforeachclusterintroducedin§5.2, Consequently,tofuzzthistarget,weshouldfocusonfuzzing AFLRUN also maintains a top-ratedarrayforeachcluster, seedsthatcoversuchatarget. similartotheoriginaltop-ratedarraydiscussedin§2.1.When For uncovered targets. If a target is not yet covered, we anewseedisaddedtothecorpus,asetoftop-ratedarrays shouldinsteadattempttofindaseedthatcoversthetargetby areselectedusingAlgorithm5,andweupdatethesetop-rated fuzzingseedsinthecurrentcorpus.Drawingontheintuition arraysusingthesamemethodasAFL++. from[37],wedefinethecriticalblocksforsuchatargetasthe Usingthesetop-ratedarrays,wecanselectasetoffavored blocksthatlieattheboundarybetweentheexploredpartsand seeds. We can apply the queue culling algorithm, similar unexploredpartsofthepathtowardthetargetintheICFG, to AFL++, on top-rated arrays of all clusters to select the knownascriticalboundaryblocks. favored seeds. For each top-rated array, we use the queue Wefirstlyneedtodefinesomenotationstointroducethe 3Here,theterm“path"doesnotrefertotheprogram’sexecutionpath. exactdefinitionofcriticalblocks.Givenatargetbasicblock Instead,itreferstotheconceptofapathasdefinedingraphtheory. 8cullingalgorithmfromAFL++toselectasetoffavoredseeds, rowofSrepresentsaseedinthecorpus.Anelementatrows andwethentaketheunionofeachsetoffavoredseedsfrom andcolumnbcanbedefinedasfollows: eachtop-ratedarraytoobtainthetotalsetoffavoredseeds. score[s] iffavoredscoversb 6.3 EnergyAssignment S = 0.05·score[s] ifunfavoredscoversb s,b 0 otherwise In this section,we willintroduce themethodforassigning energyamongseedsusingcriticalblocksofeachtarget.In Next,matrixS isalsonormalizedtoSˆtoensure thatthe previousdirectedfuzzingworks,adistance-to-targetmetric sumofeachcolumnisequalto1.Thetermscore[s]represents for each seed is used as the oracle for energy assignment. theenergyassignedtoseedswhenfuzzedincoverage-guided Bycontrast,insteadofusingsuchdistanceoracle,weutilize mode,ascomputedbythealgorithmfromAFL++.Thisen- critical blocks covered by each seed as the oracle for en- ergycan,insomesense,representthepreferenceofaseed ergyassignment.Theprimaryconceptbehindouralgorithm fromAFL++’sperspective.Weutilizethispreferencewhen involves distributing uniform weight from targets through distributingweightfromeachcriticalblocktoseeds.Addi- criticalblockstoseeds.Ourgoalistoassignenergytoeach tionally,AFL++skipsunfavoredseedswitha95%probability. seedat the beginning ofa cycle so thatthe total energy of Wealsofollowthisdesignbycalculatinganexpectedenergy eachseedafterassignmentcan approachthe proportion of forunfavoredseeds.Thefavorabilityofaseedisdetermined suchseedweightasmuchaspossible. using the favored seeds selected. Finally,we can calculate Targetweight.Asmentionedearlier,AFLRUNstartswith theseedweightvectorbycomputingSˆBˆ1+c.Thisfinalseed uniformweightvaluesforalltargetbasicblock.Specifically, weightvectorisalsonormalizedtor,representingthefinal we have a vector of ones representing the weight for each ratiotobeapproached. target,denotedas1.However,ourapproachdoesallowusers Preventing local optima. One problem of our energy as- to specify a customized weight value for each target. We signment based on critical blocks is the potential for local provideadetaileddescriptionofthisby-productinAppendix optima.Tomitigatesuchissue,duringthecalculationofthe B. seedweightvector,weaddavectorc,whichrepresentsthe Block weight. In this part, we discuss how we distribute energyassignmentofeachseedincoverage-guidedfuzzing. weightfromeachtargettoitscriticalblocks.Foreachtarget The sum of c is calculated by multiplying the total energy t,wehaveasetofcriticalblocksC t ⊆R.Bytakingtheunion (i.e.,thenumberoftargets)byasmallfraction. ofC t forall targets,we obtain the set of all critical blocks Seedenergyassignment.Now,AFLRUNcanassignenergy C⊆R,whereRisthesetofallcoveredblocksdefinedearlier. to seeds using the obtained r. AFLRUN also maintains a WecannowdefineamatrixBforweightdistribution:each vectorbrepresentingtheenergythathasbeenassignedtoeach columnofBrepresentsacorrespondingtarget,andeachrow seedpreviously.GivenatotalenergyvalueE forthiscycle, ofBrepresentsablockinC.Anelementofthematrixatrow weassignenergyE toeachseedintheformofvectorx,such bandcolumnt isdefinedasfollows: thatx+bcanapproachtheratiorascloselyaspossible,under (cid:40) |
theconstraint∑ ix i=E.Insteadofusingageneralalgorithm B = distanc1 e[b,t]+k ifb∈C t ofmathematicaloptimization,wedevelopanalgorithmwith b,t aworst-casecomplexityofO(n2)thatguaranteestheoptimal 0 otherwise solution. WediscussthisalgorithminAppendixA,asitis Intheequation,thetermdistance[b,t]representsthedis- unrelatedtofuzzing. tancefromthebasicblockbtothetargett,computedusing themethoddescribedinAppendixD,becausethisdistance 7 Evaluation computationisonlyanauxiliarycomponentofourapproach. Theconstantk isapositivevaluethatcontrolshowsignifi- Inthissection,weexplorethefollowingresearchquestions cantlythedistancevalueinfluencesthepreferenceforablock. throughexperiments.RQ1:HoweffectiveisAFLRUNattrig- Thelargerthevalueofk,thesmallertheeffectwillbe.Next, geringvulnerabilitiescomparedtootherfuzzersandablated thematrixBisnormalizedtoBˆ,ensuringthateachcolumnof versionsofAFLRUN?(§7.1andAppendixH)RQ2:Howef- thematrixsumsto1.Now,thedistributionofthesetofcritical fectiveisAFLRUNinensuringfairnessforeachtarget?(§7.2) blockscanbeobtainedbycalculatingtheproductBˆ1,which RQ3:Whatistheruntimeoverheadincurredby AFLRUN distributesweightfromeachtargettoeachcriticalblock. duringfuzzingcampaign? (§7.3)RQ4: Can AFLRUN dis- Seedweight.Theprocessofdistributingweightfromeach covernewzero-dayvulnerabilitiesinprogramsextensively criticalblocktoseedsisquitesimilartothedistributionmen- fuzzedbyOSS-Fuzzusingstate-of-the-artindustrialfuzzers? tionedearlier.WealsohaveamatrixSforthisdistribution: (§7.4)RQ5:DotheextraseedsgeneratedbyAFLRUNassist eachcolumnofSrepresentsacriticalblockinC,whileeach intriggeringvulnerabilities?(AppendixF) 9Experiment setup. Unless otherwise specified,all experi- workscanbeappliedontopofAFLRUNwithoutmodifying mentswereconductedonanUbuntu20.04.5LTSmachine bothmethods. equippedwithanIntel(R)Xeon(R)Gold5318SCPUfeatur- Morefine-grainedablationstudy.InadditiontoAFLRUN-, ing96logicalcoresand256GBofRAM. we introduced a more fine-grained ablation variant named AFLRUN--.Thisablatedversionnotonlyremovesthetarget path-diversitymetricbutalsodiscardstheconceptofcritical 7.1 FuzzerComparison block.Insteadofapplyingcriticalblocks,AFLRUN--assigns energyusingallpreviouslycoveredblocksthatcanreachthe We use two sets of vulnerabilities for experiments. Firstly, targetviatheICFG.Thepurposeofthisablationstudyisto to compare AFLRUN with other fuzzers, we employ the underscoretheimpactofthecriticalblockdesign. Magma[22],abenchmarkcommonlyusedbymanyfuzzing works,toevaluatemulti-targetdirectedfuzzingforbugrepro- Target locations. Magma inserts one or more MAGMA_LOG duction.Additionally,todemonstratetheindividualcontribu- macrosintothetestedprogramforeachbugtonotifywhen tionfromeachcomponentofAFLRUN,weuseanotherset thebugiscoveredortriggeredduringexecution.Wesetthe ofvulnerabilitiesinareal-worldbugdiscoveryscenarioto locationsofthesemacrosastargetsforeachbug.Furthermore, conductanablationstudy. Magmapatchestheprogramtoinvertthecommitsthatfixthe bugs,andwesettheselocationsastargetsaswell. Settings. We setthe confidence thresholdto 100% to only Results. The results are presented in Table 1. Each entry clustertarget blocks that consistently dominate each other, in the table represents the average exposure time required because the target sites do not cause significant overhead for the fuzzer to trigger the vulnerability,calculated using intheseexperiments.Wealsoindividuallyremovetwokey survivalanalysis.Wealsocomputedp-valuesusingtheMann- componentsfromAFLRUN,resultinginvariationsdenoted Whitney U test [33],employing the alternative hypothesis asAFLRUN-andAFLRUN*.AFLRUN-referstoAFLRUN devoidofthetargetpath-diversitymetric,whileAFLRUN* thatAFLRUNhasashorterexposuretime.P-valuesarein- cludedintheparenthesis.T.O.indicatesthatthebugwasnot denotes AFLRUN employingAFL++’senergyassignment triggeredinanyfuzzingcampaign.NotethatParmesanand ratherthanourunbiasedenergyassignment.Followingthe WindRangerfailedtorunonsomeprogramsateithercompile fuzzingpapers’generalexperimentalapproach,weraneach timeorruntime,evenafterwefixedsomeofthebugs,sowe fuzzing campaign for 24 hours and repeated 10 times. To preventinterferencebetweenexperiments,weleftsomeCPU markthoseentriesasN/A.WeobservethatAFLRUN(-)out- performsothercounterpartsinmostcases.Onaverage,using coresunused,inlinewithpreviousresearchpractices. thegeometricmean,AFLRUNachievesspeedupfactorsof 168%,109%,235%,183%,147%,157%,78%and56%,and 7.1.1 EvaluationonMagma discovers38%,20%,138%,29%,24%,14%,50%and16% morevulnerabilitiescomparedtoAFL++,AFLGo,Parmesan, Magmaoperatesbyreintroducingmultiple1-daybugsinto FishFuzz,Hawkeye,WindRanger,MOptandAFLRUN--,re- real-worldprogramsusingpatches,enablingustosetmulti- spectively.Besides,accordingtotheresults,AFLRUN can pletargetsbasedonthesepatchesandsimultaneouslyfuzz discovera bug that otherfuzzers so farhave not triggered, multiplebugs.Weexcludedsomebugsthatcanbefoundin |
LUA002. We observe that the effectiveness of AFLRUN-- less than ten minutes bycoverage-guidedfuzzers,as these diminished with the ablation; however,it still outperforms bugscanalsobediscoveredbydirectedfuzzerswhilestillin otherfuzzers.Thisdemonstratesthatthedesignofthecritical coverage-guidedmode,whichwouldnoteffectivelydemon- blockindeedcontributestoitsenhancedeffectiveness.More- stratetheefficacyofdirectedfuzzing. over,the fact that AFLRUN-- still surpasses other fuzzers Fuzzersforcomparison.WecompareAFLRUNwithseven highlightsthevalueofitsunbiasedenergyassignment,even fuzzers: AFL++ [20],AFLGo [12],Hawkeye [13],Parme- intheabsenceofthecriticalblockdesign. san[35],FishFuzz[43],WindRanger[19]andMOpt[31].We choseAFL++becauseitisthegreyboxfuzzeruponwhichwe 7.1.2 EvaluationonRealScenario buildAFLRUN,andselectedAFLGoandParmesanasthey areopen-sourcedirectedfuzzerscommonlyusedforcompari- TheresultsfromtheMagmabenchmarkrevealthatAFLRUN son.MOptwaschosenduetoitsoutstandingperformanceon doesnotsignificantlyoutperformAFLRUN-.Uponfurtherin- theMagmabenchmark,whereitcurrentlyleadsasthemost vestigation,wediscoveredthatmostbugsinMagmaarequite effectivefuzzer. We alsoincludedHawkeye,FishFuzzand simple,probablybecauseMagmarequireseasydetectionof WindRanger,as theyallattemptto address the globalopti- bugtrigger.However,ourtargetpath-diversitymetricisde- mumdiscrepancyproblem.However,sinceHawkeyeisnot signedtohandlecomplexbugsthatrequirepathdiversityfor open-source,weimplementedourownprototypebasedon triggering,thusthebenchmarkresultsfailtofullyillustrate theapproachesdescribedinthepaper.Weexcludeworksthat theimpactofourmethod.Moreover,theMagmaexperiments areorthogonaltoourapproach[24,30,38,44],becausethese aredesignedtotestbugreproductioncapabilitywhenthebug 10Table1:MagmaBenchmarkResults BugID AFL++ AFLGo Parmesan FishFuzz Hawkeye WindRanger MOpt AFLRUN-- AFLRUN AFLRUN- LUA002 T.O.(0.18) T.O.(0.18) T.O.(0.18) T.O.(0.18) T.O.(0.18) N/A T.O.(0.18) T.O.(0.18) T.O. 23.32h LUA004 4.23h(1.00) 8.69h(0.96) T.O.(<.01) 5.93h(0.99) 3.37h(1.00) N/A 7.47h(0.97) 13.95h(0.61) 15.41h 20.42h PDF002 T.O.(0.04) T.O.(0.04) N/A T.O.(0.04) 21.72h(0.14) 21.32h(0.23) 22.26h(0.12) 20.90h(0.35) 17.10h 21.65h PDF003 6.60h(<.01) 3.84h(0.03) N/A 5.74h(0.01) 7.78h(<.01) 5.58h(0.02) 7.48h(<.01) 88.99m(0.95) 4.04h 2.15h PDF006 17.49h(0.95) T.O.(0.18) N/A T.O.(0.18) T.O.(0.18) T.O.(0.18) T.O.(0.18) 20.59h(0.79) 22.81h T.O. PDF011 22.83h(0.86) T.O.(1.00) N/A T.O.(1.00) T.O.(1.00) 22.74h(0.86) 21.14h(0.94) T.O.(1.00) T.O. T.O. PDF014 T.O.(0.08) T.O.(0.08) N/A T.O.(0.08) T.O.(0.08) 22.67h(0.29) T.O.(0.08) T.O.(0.08) 21.32h 21.69h PDF018 14.87h(<.01) 21.67h(<.01) N/A 19.37h(<.01) 22.48h(<.01) 2.59h(<.01) 40.01m(0.30) 2.79h(<.01) 36.39m 3.13h PDF019 20.51h(0.22) 21.63h(0.06) N/A T.O.(<.01) T.O.(<.01) 23.64h(<.01) 21.26h(0.08) 19.27h(0.28) T.O. 18.44h PDF021 23.89h(0.50) 23.47h(0.50) N/A T.O.(0.18) T.O.(0.18) 22.73h(0.50) T.O.(0.18) 18.80h(0.90) T.O. 22.55h PHP004 17.97h(<.01) 8.66m(0.76) N/A 77.75m(0.45) 48.82m(0.21) N/A 12.20m(0.97) 34.19m(<.01) 9.85m 12.86m PHP009 25.55m(<.01) 7.04m(0.11) N/A 50.93m(<.01) 6.96m(0.89) N/A 5.91m(0.14) 9.05m(<.01) 2.81m 8.01m PNG001 T.O.(0.02) 22.73h(0.07) T.O.(0.02) T.O.(0.02) 21.61h(0.11) 23.24h(0.06) T.O.(0.02) T.O.(0.02) 22.12h 18.46h PNG007 9.97h(<.01) 3.86h(<.01) T.O.(<.01) 4.07h(<.01) 1.68h(<.01) 10.54h(<.01) 9.88h(<.01) 46.99m(<.01) 8.44m 29.83m SND017 15.02m(0.55) 17.23m(0.24) N/A 31.44m(0.14) 10.99h(<.01) 27.68m(0.04) 32.40s(1.00) 13.18m(0.56) 13.27m 15.10m SND020 37.07m(<.01) 38.38m(<.01) N/A 3.04h(<.01) 19.92h(<.01) 68.89m(<.01) 11.74m(0.92) 27.17m(0.21) 20.96m 25.15m |
SQL002 67.21m(<.01) 13.84m(0.14) N/A 55.77m(<.01) 6.55m(0.76) 45.34m(<.01) 37.15m(<.01) 9.84m(0.17) 13.68m 7.73m SQL003 21.87h(0.19) 21.83h(0.19) N/A 22.57h(0.17) T.O.(0.04) 22.57h(0.17) T.O.(0.04) T.O.(0.04) 23.79h 20.12h SQL012 20.06h(0.06) 22.61h(<.01) N/A 20.09h(0.05) 23.88h(<.01) 16.67h(0.28) T.O.(<.01) 17.77h(0.23) 19.15h 15.70h SQL013 22.81h(0.44) 22.93h(0.25) N/A 22.91h(0.25) 23.29h(0.25) 18.73h(0.84) T.O.(0.08) 22.15h(0.44) T.O. 21.42h SQL014 3.45h(<.01) 2.29h(<.01) N/A 3.63h(<.01) 2.17h(0.06) 3.20h(<.01) 4.43h(<.01) 44.51m(0.06) 25.32m 22.26m SQL015 23.10h(0.86) 22.68h(0.86) N/A 21.39h(0.94) 20.03h(0.97) T.O.(1.00) T.O.(1.00) T.O.(1.00) T.O. T.O. SQL020 18.33h(<.01) 22.41h(<.01) N/A 20.90h(<.01) 14.94h(0.01) 17.85h(<.01) T.O.(<.01) 13.02h(0.01) 15.16h 5.96h SSL001 6.49h(<.01) 10.19h(<.01) 21.26h(<.01) 9.30h(<.01) 14.40h(<.01) 4.98h(0.21) 18.61h(<.01) 3.64h(0.03) 3.61h 59.40m SSL020 21.59h(<.01) 21.07h(<.01) 3.74h(0.03) 21.03h(<.01) 22.89h(<.01) 10.21h(0.01) 16.66h(<.01) 6.79h(<.01) 1.68h 2.41h TIF001 T.O.(0.18) T.O.(0.18) T.O.(0.18) T.O.(0.18) 23.32h(0.56) T.O.(0.18) T.O.(0.18) T.O.(0.18) 23.91h T.O. TIF002 T.O.(<.01) 9.93h(0.96) T.O.(<.01) 16.09h(0.61) 11.31h(0.93) 21.30h(0.05) 16.73h(0.55) 14.39h(0.69) 19.90h 16.38h TIF005 T.O.(0.18) 23.60h(0.50) 10.45h(0.99) 23.85h(0.50) T.O.(0.18) T.O.(0.18) 22.12h(0.56) 21.97h(0.56) T.O. 23.38h TIF006 13.12h(0.58) 15.35h(0.45) 8.89h(0.93) 17.43h(0.28) 10.09h(0.90) 17.20h(0.22) 8.90h(0.90) 9.32h(0.83) 14.12h 17.25h TIF008 T.O.(0.04) T.O.(0.04) T.O.(0.04) 22.26h(0.19) T.O.(0.04) 23.33h(0.17) T.O.(0.04) T.O.(0.04) 22.09h T.O. TIF009 11.63h(<.01) 15.96h(<.01) T.O.(<.01) 23.25h(<.01) 11.98h(<.01) 7.94h(<.01) 6.08h(<.01) 4.61h(0.01) 56.93m 8.78h TIF014 53.89m(<.01) 92.69m(<.01) 15.84h(<.01) 64.99m(<.01) 81.53m(<.01) 81.67m(<.01) 16.86m(0.03) 28.20m(0.31) 8.21m 43.59m XML001 T.O.(<.01) 21.72h(<.01) 8.86h(<.01) 20.37h(<.01) 15.35h(<.01) 22.12h(<.01) 13.81h(<.01) 4.77h(<.01) 83.88m 54.90m XML002 T.O.(1.00) T.O.(1.00) T.O.(1.00) T.O.(1.00) 22.11h(0.94) T.O.(1.00) T.O.(1.00) 21.06h(0.97) T.O. T.O. XML003 31.68m(0.04) 22.08m(0.05) 2.61m(0.99) 1.71h(<.01) 39.14m(<.01) 2.84h(<.01) 55.83m(0.02) 13.82m(0.66) 14.56m 16.06m XML006 T.O.(0.18) T.O.(0.18) T.O.(0.18) 23.18h(0.50) T.O.(0.18) T.O.(0.18) T.O.(0.18) 22.10h(0.56) 22.36h T.O. XML009 42.69m(<.01) 6.69m(0.37) 13.28h(<.01) 37.59m(<.01) 11.95m(0.06) 1.68h(<.01) 16.41m(<.01) 28.22m(0.17) 8.04m 9.31m XML010 T.O.(<.01) 23.18h(<.01) T.O.(<.01) T.O.(<.01) 22.36h(<.01) T.O.(<.01) T.O.(<.01) 18.89h(0.01) 14.63h 8.75h XML012 T.O.(<.01) 20.48h(<.01) T.O.(<.01) 21.71h(<.01) 13.93h(0.05) 22.43h(<.01) 11.64h(0.09) 22.21h(<.01) 19.68h 8.82h Table2:AblationResults withoutFalsePositives withFalsePositives BugID AFLRUN AFLRUN- AFLRUN* AFLRUN AFLRUN- AFLRUN* CVE-2023-25588 11.26h T.O. 9.25h 14.97h T.O. 16.91h CVE-2023-25587 6.86h T.O. 5.62h 10.44h T.O. 11.86h CVE-2022-44408 0.31h 13.14h 1.20h 0.59h 5.58h 23.50h CVE-2018-13785 0.55h T.O. 0.92h 0.42h T.O. 0.56h |
CVE-2013-6954 0.57h 3.50h 0.37h 0.46h 2.74h 0.32h sitesareknown.Yet,inrealvulnerabilitydiscoveryscenario suchastheonedetailedin§3.1,numerousfalsepositivetar- getsmightalsoexist.Thissituationhasnotbeenevaluatedin theaforementionedbenchmarkingexperiment. ToaddressthisdeficiencyofMagmabenchmark,wecon- duct an additional experiment in a different setting, using somebugsthatalignwithourscenario.Todemonstratethe impactofencounteringfalse-positivetargets(emulatingreal- Figure4:Pathdiversitycurves worldbugdetection),wecarryouttheexperimentundertwo 11conditions:withandwithouttheintroductionoffalse-positive targets.Thosefalse-positivetargetsarerandomlychosenfrom thebugreportsdetectedbyClangstaticanalyzer[3]. We didnotinclude AFLRUN-- in this experimentas its primarygoalwastodemonstrateAFLRUN’seffectivenesson complexbugsthatrequirepathdiversityforactivation.Incon- trast,AFLRUN--wasdesignedtodemonstratethecontribu- tionsofdifferentcomponentsofunbiasedenergyassignment intheMagmaexperiment. ThebugtriggeringtimeresultsaredisplayedinTable2.We observethatAFLRUNsignificantlyoutperformsAFLRUN-. Furthermore,withtheintroductionoffalse-positivetargets, AFLRUNgenerallyexhibitssuperiorbug-triggeringcapabil- itycomparedtoAFLRUN*.Thisindicatesthattheunbiased energyassignmentindeedhelpsinmanagingtheseedexplo- sioncausedbytheincreasedtargetcount. Theseresultsarefurtherelucidatedbygraphingthepath diversity curves from several experiments. For the corpus createdbyeachfuzzingcampaign,wetracktheincreasein Figure5:Energyspentoneachtarget pathdiversityofbasicblockcoveragenecessarytotriggerthe vulnerabilityovertime.Foreachsetofrepeatedexperiments, 7.3 OverheadMeasurement wecomputethemeanandthecorrespondingconfidencein- terval.TheoutcomesaredepictedinFigure4.Asseeninthe ToevaluatetheoverheadincurredbyAFLRUNatruntimein figure,thetargetpath-diversitymetricsignificantlyenhances responsetoRQ3,wealsoscaleupthetotalnumberoftargets thepathdiversityofthetarget. byutilizingtargetsitesofrecentcommitsfrom§7.2.Similarly, thefuzzingcampaignisconductedwiththevulnerabilities introducedintotheseprogramsdisabled. 7.2 TargetFairnessComparison To demonstrate the effectiveness of our clustering algo- Inthisexperiment,weevaluatetheeffectivenessofAFLRUN rithm, we conducted overhead experiments under five dif- inbalancingeachtargetcomparedtoitscounterparts,address- ferent configurations: for three of them,we enabled target ingRQ2.Weaimtoscaleupthetotalnumberoftargetsby clusteringwithvaryingconfidencethresholdvaluesof50%, utilizingrecentlyintroducedcommitsastargetsitesforeach 70%,and90%andaconsistentsupportcountthresholdvalue programintheMagmabenchmark[22].Wealsodisablethe of500;foroneofthem,theclusteringwasdisabled,meaning bugs introduced by Magma,as we are not concerned with eachtargetcorrespondstoadistinctvirginmapandtop-rated their triggering in this experiment. Furthermore, since the array;forthelastone,weremovedourpathdiversitycom- primarygoalofthisexperimentistoassesstheeffectiveness ponent (AFLRUN-). We ran each experiment for 3 hours, ofourunbiasedenergyassignment,wehaveablatedthetarget which was repeated 20 times. We recorded the number of path-diversitymetric(i.e.,weuseAFLRUN-). clustersattheendofeachfuzzingcampaignandcalculated We conducted the experiment forthree directed fuzzers: thearithmeticmeanacrossallrepeatedexperimentsforeach Hawkeye,FishFuzz,andAFLRUN-.Foreachfuzzer,wecar- configuration.Similarly,weprofiledtheproportionoftime riedoutan8-hourfuzzingcampaign,repeatingeachexper- spentinAFLRUNprocesstototaltimeforeachfuzzingcam- iment 10 times. We recorded the energy assigned (i.e.,the paignandcalculatedthemean.TheresultsareshowninTable numberofmutationsandexecutionsperformed)toeachseed. 3.Additionally,wemeasuredtheoverheadincurredbythe Additionally,we used a modified version of afl-showmap instrumentedcode.However,suchoverheadisnegligible:it todeterminethetargetcoverageofeachseed.Withthisin- occupieslessthan0.01%oftotaltimeineveryfuzzingcam- formation,we computed the total energy spent on fuzzing paign. eachtarget.Wesortedtheenergyforeachtargetandplotted Eachrowinthetablerepresentsadifferentconfiguration. agraphsimilartotheoneinFishFuzz[43].Theresultsareil- Thefirstthreecolumnsrepresentexperimentswithvarying lustratedinFigure5.Thex-axisrepresentsalltargetsordered confidence threshold values; the fourth column represents incrementallybyenergyspentonthem,andthey-axisisthe anexperimentwithouttheclusteringalgorithm;andthelast correspondingenergy.WecanseethatAFLRUNgenerates columnrepresentsanexperimentwithAFLRUN-.Eachentry flatter curves compared to other counterparts,indicating a displaysapairofvalues:theuppervaluerepresentstheaver- morebalancedenergyassignmentforeachtarget,especially agenumberofclusterswhenthefuzzingcampaignsterminate, forlibtiffandlibxml2. andthelowervalueistheaverageratiooftimespentexecut- 12Table3:OverheadResults:Theuppervaluesofeachprogram Wediscovered29previouslyunknownvulnerabilitiesin |
areaveragenumberofclusters;thelowervaluesaretimeratio theseprograms,whicharelistedinTable4.Weresponsibly spentinthePUT. reportedthemtothevendors.Allvulnerabilitiesmarkedas Fixedhavealreadybeenaddressedbythedevelopersinthe Program Threshold=50% Threshold=70% Threshold=90% w/oCluster w/oDiversity upstream.Atthetimeofwriting,28vulnerabilitieshavebeen 157.85 159.35 157.05 327.05 1.0 libpng 86.03% 86.07% 86.31% 80.41% 93.26% fixed,and8CVEIDshavebeenassigned. 303.05 302.35 307.95 332.6 1.0 libsndfile 97.60% 97.66% 97.62% 97.08% 98.33% libtiff 188.75 190.2 189.25 188.3 1.0 8 Discussion 78.27% 80.00% 77.29% 81.97% 91.24% 156.45 171.95 188.25 366.15 1.0 libxml2 96.85% 96.97% 96.79% 95.46% 98.23% In this section, we discuss the scope and limitation of 342.2 326.85 339.2 335.2 1.0 lua AFLRUN,andthepotentialenhancementsthatcouldbeap- 97.73% 97.69% 97.70% 97.75% 99.45% 159.95 169.35 164.85 173.65 1.0 pliedtoourworkinthefuturetoaddressanylimitations. poppler 99.06% 99.08% 99.07% 98.98% 99.48% 8.1 Scope ingthePUToverthetotaltimeofeachfuzzingcampaign.We canobservethattheoverheadincurredbytheAFLRUNpro- Targetpath-diversitymetric.Ourtargetpath-diversitymet- cessisnotsignificantcomparedtothetimespentinexecuting ric aims to address PFA and PTA,as previously stated. In thePUT.Additionally,theclusteringalgorithmthatreduces caseswherethebugdoesnotrequireextrapathsforactivation thetotalnumberofvirginmapssignificantlydoesdecrease and can be triggered through mutations of seeds covering someoverheadspentinthefuzzerprocess. thebuggytargetlocationonly,extraseedsaimedatenhanc- ingpathdiversitybecomeredundant. Ifthisinformationis knownin advance,usersmaychoosetoexclusivelyutilize 7.4 VulnerabilityDiscovery theunbiasedenergyassignment(i.e.,AFLRUN-). Lastly,wepresentallvulnerabilitiesfoundbyAFLRUNto Unbiased energy assignment. The scope of unbiased en- answerRQ4.WeuseAFLRUNtofuzzthelatestversionsof ergyassignmentissignificantlybroaderbycomparison.This somefamousprogramsthathavebeencontinuouslyfuzzed method can be applied to nearly all scenarios of directed bytheOSS-Fuzzproject[7]usingpowerfulGooglemachines. fuzzing.ThescenarioinwhichAFLRUNmaybecomeless We integrate AFLRUN into OSS-Fuzz to simplify fuzzing effective occurs when the buggy target location is shallow eachprogramwithoutstrugglingwiththeenvironment.Since andeasilyreachable,whereasfalse-positivetargetlocations AFLRUNisadirectedfuzzer,wesettargetlocationsusing aredeepandchallengingtoreach.Insuchinstances,thebi- twoapproaches.First,weattempttofuzzrecentlyintroduced ased energy assignment utilized by other directed fuzzing commitsbysettingrecentlychangedcodelocationsastargets. approachesmightcoincidentallybiastothecorrecttarget. Theintuitionbehindthisisthatrecentlymodifiedcodemay bemoreerror-pronebecauseoldercodehasalreadybeenthor- 8.2 LimitationsandPotentialSolutions oughlyfuzzedbyOSS-Fuzz,whilenewcodeislessfuzzed. Second,weusethestaticanalysistooltoidentifysuspicious Seedexplosion.Similartootherworksthatproposeamore codelocations.Specifically,wewriteCodeQL[17]queries fine-grainedcoveragemetric[14,16,32,39],ourtechnique tofindpotentiallyvulnerablecodelocationsasourtargets. also suffers from problem of seed explosion. This phe- nomenon can lead to substantial overhead when the target Table4:Zero-dayvulnerabilitiesfoundbyAFLRUN. count reaches into the thousands,given that the cost asso- ciated with processing each new seed is significant. In the Project ID Type Status currentdesign,eachtargetclustercorrespondstoavirginmap wabt CVE-2022-44407 Out-of-boundsRead Fixed wabt CVE-2022-44408 TypeConfusion Fixed thatisexactlythesameastheprimaryvirginmap.However, wabt CVE-2022-44409 Out-of-boundsRead Fixed asnotedin[30],notalledgesarerelevanttotargets,andthese skia issue-40045089 UncontrolledRecursion Accepted irrelevantedgescanbediscardedthroughstaticanalysis.Con- freetype issue-1159 UncontrolledRecursion Fixed binutils CVE-2023-25585 AccessofUninitializedPointer Fixed sequently,theirorthogonalapproachcouldbeintegratedwith binutils CVE-2023-25587 NULLPointerDereference Fixed ourworktopotentiallymitigatetheseedexplosionproblem. binutils CVE-2023-25588 AccessofUninitializedPointer Fixed binutils CVE-2023-25586 UseofUninitializedVariable Fixed Localoptimum.Inthecurrentdesign,thecriticalboundary binutils CVE-2023-255844 Out-of-boundsRead Fixed blockrequiresthatthepathtowardthetargetshouldnotin- cludeanypreviouslycoveredblocks.However,thiscanlead to directedfuzzing getting stuckin a localoptimum,since 4ThisCVEconsistsofagroupof20vulnerabilitiesintotal.Weconduct progress toward the target may not necessarily result from acasestudyforthisCVEandlisteachoftheindividualvulnerabilityIDsin theAppendixC. mutatingtheseedthatcoverstheboundaryblock.Although 13theadditionofavectorctoseedweightvectorasamitiga- onlyservesthepathdiversitybutalsotacklestheseedexplo- |
tion strategy is proposed in §6.3,it fails to tackle the root sionproblem. oftheissue.Apotentialsolutioncouldinvolverelaxingthe restrictiononthenumberofnon-coveredblocksinthepath: 9.2 DirectedFuzzing ratherthaninsistingthatnoblockscanbecovered,permitting asmallnumber,n,ofblockstobecoveredmightbeaviable AFLGo [12] firstly proposes directed greybox fuzzing to approach. guide greybox fuzzing towarda setofuser-definedtargets. Clusteringalgorithm.Currently,AFLRUNemploysasim- It proposes a distance oracle for each seed, which is used pleandnaiveclusteringalgorithmbasedonasimplifiedver- forenergyassignmenttofavorseedclosertotargets.How- sionofassociationrulemining.However,moreaccurateclus- ever,suchdistanceoracleisaverycrudemetricrepresenting tering algorithms in the contextofassociation rule mining preferenceofseedwithrespecttotargets.Hawkeye[13]im- exist[21].Asafuturedirection,theclusteringalgorithmcould proves directed fuzzing on top of design of AFLGo based beimprovedbyadoptingamoresophisticatedapproachwith- onseveraldesiredpropertiesitshouldhold.Parmesan[35] outsacrificingefficiency. findstargetsusinginformationfromcompilersanitizerpasses, anditalsoproposessomemethodsofdirectedfuzzingsuch asdynamicallyconstructingICFGduringfuzzingcampaign. 9 RelatedWork WindRanger[19]improvesdistancecomputationfromaseed totargetsbyonlyconsideringbasicblocksthatdeviatefrom 9.1 ImprovingCoverageMetric pathtowardtargets.However,itdoesnottakemultipletargets intoaccountwhenobtainingsuchblocks.Inaddition,their Numerousstudiesaimtoenhancefuzzingeffectivenessbyre- definitionofdeviationblockislocalandisbasedononlyone finingthecoveragemetric.Angora[14]considerscallcontext seed,whileourcriticalblocksareglobalandtakeallseeds underwhicheachedgeiscoveredtomakecoveragemetric in corpus into account. LeoFuzz [29] is the first work that context-sensitive. MemFuzz [16] uses address of memory realizestheproblemofusingharmonicaveragedistanceofall accessasextracoveragemetric.Ankou[32]designsanew targets,anditproposesamethodbasedontargetsequencein fitnessfunctionbasedondistancebetweenexecutionpathsof ordertosolveit.FishFuzz[43]alsoaddressessuchproblem testcases,andtheirapproachalsoallowstostoreextraseeds byusingadistancevectorforeachseedinsteadofanaverage thatdonotachievenewcoverage.Ijon[10]improvescover- agemetrictoexploredeepstateinspecifictestedprogramby distance. By contrast,energy assignment of AFLRUN not onlysolvessuchprobleminamorefine-grainedway,butalso takingadvantageoftheguidanceofuser-definedannotations servesforourpathdiversitycomponent.Finally,CAFL[27] marked on important data in the program. AFL-Hier [39] takes sequence of locations with constraints as target, but proposesamulti-levelcoveragemetricandareinforcement- suchsequencerequiresmoremanualeffortthanotherdirected learning-basedhierarchicalschedulerinordertohandleseed fuzzers. explosionproblemintroducedbymorefine-grainedcoverage Thereareotherworksthattrytoimproveperformanceof metric. directedfuzzingbytrimmingredundantpartsconsideredir- Someotherworksalsohaveproposedcoveragemetricinor- relevanttotargetsinfuzzingcampaign.FuzzGuard[44]uses dertofinddomain-specificbugs.SlowFuzz[36]usesnumber deeplearningtofilterouttestcaseconsideredtobeunhelpful ofexecutedinstructionsasmetrictofindbugscausedbyworst forreachingtarget,soitisnotexecutedbytestedprogrambe- caseofalgorithmcomplexity.PerfFuzz[28]similarlyuses forehand.BEACON[24]appliesstaticanalysistoterminate maximumcountofeachprogramlocationasstoragemetric programearlyifcurrentprogramstateisguaranteedtobeun- ofnewseedtoalsofindcomplexitybugs.MemLock[41]pro- abletoreachanytargets.SieveFuzz[38]alsoterminatesthe posesmemoryusageasguidancetostoreextraseedsinorder programearlybyrestrictingfuzzingtosearchspaceguaran- tofinduncontrolledmemoryconsumptionbugs.Krace[42] teedrelevanttoreachingtargets.SelectFuzz[30]selectively designsacoveragetrackingmetricspeciallydesignedtofind instrumentsandexploresonlytarget-relevantcode,anditalso bugscausedbydataracesinkernelfilesystem. proposesanoveldistancemetricfromabasicblocktotarget Alloftheseworkshavedevelopednewcoveragemetricsfor basedonmulti-pathreachingprobability.Theseworksabout coverage-guidedfuzzing,whileincontrast,AFLRUNintro- trimmingareconsideredorthogonaltoourapproach. ducesanewcoveragemetricspecificallyfordirectedfuzzing. To the best of ourknowledge,we are the first to primarily focus on this task, utilizing the coverage metric based on 10 Conclusion multiplevirginmapsfortargets.Moreover,someofthemen- tionedworks[32,39]devisenovelseedschedulingalgorithms WeproposedAFLRUN,whichincludestargetpath-diversity toaddresstheseedexplosionproblemcausedbytheirnew metricandunbiasedenergyassignment.Throughevaluation, coveragemetrics.Similarly,AFLRUNalsoproposesanew wedemonstratedtheeffectivenessofAFLRUNintriggering energyassignmentalgorithmfordirectedfuzzing,whichnot knownandzero-daybugs. 14References [20] Andrea Fioraldi,DominikMaier,Heiko Eißfeldt,andMarcHeuse. Afl++:Combiningincrementalstepsoffuzzingresearch.InWOOT@ |
[1] American fuzzy lop. https://lcamtuf.coredump.cx/afl/ USENIXSecuritySymposium,2020. technical_details.txt. [21] Eui-HongHan,GeorgeKarypis,VipinKumar,andBamshadMobasher. [2] Analyzing data flow in c and c++. https:// Clusteringbasedonassociationrulehypergraphs. InWorkshopon codeql.github.com/docs/codeql-language-guides/ ResearchIssuesonDataMiningandKnowledgeDiscovery,1997. analyzing-data-flow-in-cpp/. [22] AhmadHazimeh,Adrián Herrera,andMathias Payer. Magma: A [3] Clangstaticanalyzer.https://clang-analyzer.llvm.org/. ground-truthfuzzingbenchmark. ACMSIGMETRICSPerformance [4] Honggfuzz.https://honggfuzz.dev/. EvaluationReview,49:81–82,2020. [5] libfuzzer-alibraryforcoverage-guidedfuzztesting.https://llvm. [23] Marc Heuse, Heiko Eißfeldt, Andrea Fioraldi, and Dominik org/docs/LibFuzzer.html. Maier. afl-clang-lto - collision free instrumentation at link time. https://github.com/AFLplusplus/AFLplusplus/blob/ [6] Llvmlinktimeoptimization: Designandimplementation. https: stable/instrumentation/README.lto.md,12022. //llvm.org/docs/LinkTimeOptimization.html. [24] HeqingHuang,YiyuanGuo,QingkaiShi,PeisenYao,RongxinWu, [7] Oss-fuzz.https://google.github.io/oss-fuzz/. andCharlesZhang.Beacon:Directedgrey-boxfuzzingwithprovable [8] robin_hoodunorderedmap&set.https://github.com/martinus/ pathpruning. 2022IEEESymposiumonSecurityandPrivacy(SP), robin-hood-hashing. pages36–50,2022. [9] RakeshAgrawal,TomaszImielinski,andArunN.Swami. Mining [25] TaeEunKim,JaeseungChoi,KihongHeo,andSangKilCha. Dafl: associationrulesbetweensetsofitemsinlargedatabases. InACM Directedgrey-boxfuzzingguidedbydatadependency. InUSENIX SIGMODConference,1993. SecuritySymposium,2023. [10] Cornelius Aschermann, Sergej Schumilo, Ali Reza Abbasi, and [26] ChrisLattnerandVikramS.Adve.Llvm:acompilationframeworkfor ThorstenHolz. Ijon:Exploringdeepstatespacesviafuzzing. 2020 lifelongprogramanalysis&transformation.InternationalSymposium IEEESymposiumonSecurityandPrivacy(SP),pages1597–1612, onCodeGenerationandOptimization,2004.CGO2004.,pages75–86, 2020. 2004. [11] MarcelBöhme,BrunoC.d.S.Oliveira,andAbhikRoychoudhury. [27] GwangmuLee,Woo-JaeShim,andByoungyoungLee. Constraint- Regression tests to expose change interaction errors. In Bertrand guideddirectedgreyboxfuzzing. InUSENIXSecuritySymposium, Meyer,LucianoBaresi,andMiraMezini,editors,JointMeetingofthe 2021. EuropeanSoftwareEngineeringConferenceandtheACMSIGSOFT [28] CarolineLemieux,RohanPadhye,KoushikSen,andDawnXiaodong SymposiumontheFoundationsofSoftwareEngineering,ESEC/FSE’13, Song.Perffuzz:automaticallygeneratingpathologicalinputs.Proceed- SaintPetersburg,RussianFederation,August18-26,2013,pages334– ingsofthe27thACMSIGSOFTInternationalSymposiumonSoftware 344.ACM,2013. TestingandAnalysis,2018. [12] MarcelBöhme,Van-ThuanPham,Manh-DungNguyen,andAbhik [29] HongliangLiang,XianglinCheng,JieLiu,andJinLi.Multipletargets Roychoudhury. Directedgreyboxfuzzing. Proceedingsofthe2017 directedgreyboxfuzzing.ArXiv,abs/2206.14977,2022. ACMSIGSACConferenceonComputerandCommunicationsSecurity, 2017. [30] ChanghuaLuo,WeiMeng,andPenghuiLi. Selectfuzz:Efficientdi- rectedfuzzingwithselectivepathexploration.In2023IEEESympo- [13] HongxuChen,YinxingXue,YuekangLi,BihuanChen,XiaofeiXie, siumonSecurityandPrivacy(SP),pages1050–1064.IEEEComputer XiuhengWu,andYangLiu. Hawkeye:Towardsadesireddirected Society,2022. grey-boxfuzzer.Proceedingsofthe2018ACMSIGSACConference onComputerandCommunicationsSecurity,2018. [31] Chenyang Lyu,Shouling Ji,Chao Zhang,Yuwei Li,Wei-Han Lee, YuSong,andRaheemA.Beyah.Mopt:Optimizemutationscheduling [14] PengChenandHaoChen. Angora:Efficientfuzzingbyprincipled forfuzzers.2019. search. 2018IEEESymposiumonSecurityandPrivacy(SP),pages 711–725,2018. [32] ValentinJ.M.Manès,SoominKim,andSangKilCha.Ankou:Guiding grey-boxfuzzingtowardscombinatorialdifference.2020IEEE/ACM [15] MariaChristakis,PeterMüller,andValentinWüstholz. Guidingdy- 42ndInternationalConferenceonSoftwareEngineering(ICSE),pages namicsymbolicexecutiontowardunverifiedprogramexecutions.In 1024–1036,2020. LauraK.Dillon,WillemVisser,andLaurieA.Williams,editors,Pro- ceedingsofthe38thInternationalConferenceonSoftwareEngineering, [33] HenryB.MannandDouglasR.Whitney.Onatestofwhetheroneof ICSE2016,Austin,TX,USA,May14-22,2016,pages144–155.ACM, tworandomvariablesisstochasticallylargerthantheother.Annalsof 2016. MathematicalStatistics,18:50–60,1947. [16] NicolasCoppik,OliverSchwahn,andNeerajSuri. Memfuzz: Us- [34] Manh-DungNguyen,SébastienBardin,RichardBonichon,Roland ingmemoryaccessestoguidefuzzing. 201912thIEEEConference Groz,andMatthieuLemerre. Binary-leveldirectedfuzzingforuse- |
onSoftwareTesting,ValidationandVerification(ICST),pages48–58, after-freevulnerabilities. InInternationalSymposiumonRecentAd- 2019. vancesinIntrusionDetection,2020. [17] OegedeMoor,MathieuVerbaere,ElnarHajiyev,PavelAvgustinov, [35] SebastianÖsterlund,KavehRazavi,HerbertBos,andCristianoGiuf- TorbjörnEkman,NeilOngkingco,DamienSereni,andJulianTibble. frida.Parmesan:Sanitizer-guidedgreyboxfuzzing.InUSENIXSecu- Keynoteaddress:.qlforsourcecodeanalysis.SeventhIEEEInterna- ritySymposium,2020. tionalWorkingConferenceonSourceCodeAnalysisandManipulation [36] Theofilos Petsios, Jason Zhao, Angelos D. Keromytis, and (SCAM2007),pages3–16,2007. Suman Sekhar Jana. Slowfuzz: Automated domain-independent [18] EdsgerW.Dijkstra.Anoteontwoproblemsinconnexionwithgraphs. detectionofalgorithmiccomplexityvulnerabilities.Proceedingsofthe NumerischeMathematik,1:269–271,1959. 2017ACMSIGSACConferenceonComputerandCommunications Security,2017. [19] Zhengjie Du,Yuekang Li,Yang Liu,andBing Mao. Windranger: Adirectedgreyboxfuzzerdrivenbydeviationbasicblocks. 2022 [37] DongdongShe,AbhishekShah,andSumanSekharJana. Effective IEEE/ACM44thInternationalConferenceonSoftwareEngineering seedschedulingforfuzzingwithgraphcentralityanalysis.2022IEEE (ICSE),pages2440–2451,2022. SymposiumonSecurityandPrivacy(SP),pages2194–2211,2022. 15[38] PrashastSrivastava,StefanNagy,MatthewHicks,AntonioBianchi,and tionisapairoffilenameandlinenumber,usuallyinformat MathiasPayer. Onefuzzdoesn’tfitall:Optimizingdirectedfuzzing file.c:123. Target basic block, on the other hand,is the viatarget-tailoredprogramstaterestriction. Proceedingsofthe38th basicblockintestedprogramthatcontainsatleastonetarget AnnualComputerSecurityApplicationsConference,2022. location.Weshowhowwecomputeweightoftargetblock [39] JinghanWang,ChengyuSong,andHengYin.Reinforcementlearning- from weight of target location in this section. Each target basedhierarchicalseedschedulingforgreyboxfuzzing. InNetwork andDistributedSystemSecuritySymposium,2021. locationcanbecontainedbyoneormoretargetbasicblocks, [40] PengfeiWangandXuZhou.Sok:Theprogress,challenges,andper- andeachtargetblockcanalsocontainoneormoretargetloca- spectivesofdirectedgreyboxfuzzing.ArXiv,abs/2005.11907,2020. tions.Withsuchinformation,wedistributeweightfromtarget [41] ChengWen,HaijunWang,YuekangLi,ShengchaoQin,YangLiu, locationstotargetblocksusingdistributionmatrix.Eachcol- ZhiwuXu,HongxuChen,XiaofeiXie,GeguangPu,andTingLiu. umnofthematrixrepresentatargetlocation,andeachrow Memlock: Memoryusageguidedfuzzing. 2020IEEE/ACM42nd ofthematrixrepresentatargetblock.WedefinematrixΦas InternationalConferenceonSoftwareEngineering(ICSE),pages765– follows: 777,2020. [42] MengXu,SanidhyaKashyap,HanqingZhao,andTaesooKim.Krace: Dataracefuzzingforkernelfilesystems. 2020IEEESymposiumon (cid:40) SecurityandPrivacy(SP),pages1643–1660,2020. 1 iftargetblockbcontainstargetlocationl Φ b,l = Nl [43] HanZheng,JiayuanZhang,YuhangHuang,ZezhongRen,HeWang, 0 otherwise ChunjieCao,YuqingZhang,FlavioToffalini,andMathiasPayer.Fish- fuzz:Throwinglargernetstocatchdeeperbugs.ArXiv,abs/2207.13393, N isthetotalnumberoftargetblocksthatcontaintarget 2022. l locationl,andweshouldnotethateachcolumnofthismatrix [44] PeiyuanZong,TaoLv,DaweiWang,ZizhuangDeng,RuigangLiang, sums to 1. Finally,we can multiply Φ by weightvectorof andKaiChen.Fuzzguard:Filteringoutunreachableinputsindirected grey-boxfuzzingthroughdeeplearning.InUSENIXSecuritySympo- target locations to obtain weight of each target block. At sium,2020. thispoint,wecandiscardthesetargetlocations,andunless otherwisespecified,weusetargettodenotetargetbasicblock A MathematicalOptimizationAlgorithm insteadoftargetlocationinthispaper. We can state the problem as follows. We are given with a C CVE-2023-25584 ratiovectorr∈Rnthatsatisfies∑n i=1r i=1,avectorb∈Rn andascalarvalueE∈R,andthesevaluesshouldallbenon- WedemonstratehowwewereabletofindCVE-2023-25584, negative.Wewanttofindanon-negativevectorx∈Rnsuch agroupofout-of-boundsreadvulnerabilitiesinbinutils, that∑n i=1x i =E,so thatdistribution ofx+b can approach using AFLRUN. The first vulnerability in this group we ratio vectorr as muchas possible. A naive algorithm is to havediscoveredoccursattheparse_modulefunctioninthe converttheproblemintoaconvexoptimizationproblemby vms-alpha.cfile.Thisbugwasdiscoveredbytargetingre- minimizingcrossentropylossbetweennormalizedx+band centlychangedcodelocations,andindeed,thefilehadbeen rundercertainconstraints.However,ifnislarge,state-of-art recently modified to fix some bugs. The root cause of this solvers are not able to get the optimal solution in feasible bug,althoughnotdirectlyrelatedtothesechangedcodeloca- timelimit.Instead,wedevelopanalgorithmwithworsttime tions,couldalsobetestedwhenfuzzingthesetargets,which complexityO(n2)thatguaranteestheoptimalsolution. ultimatelyledtoitsdiscovery. Thekeyintuitionofthealgorithmistocalculatethesum Wesubsequentlyanalyzedthisvulnerabilityanddiscovered |
oftotalvalueafterassignmentbyE′=E+∑n i=1b i,withsuch thatnumerousnearbylocationsappearedtoexhibitasimilar valuewecancalculatethemostdesirableresultforx+bby issueduetotheaccessofthesamepointer,ptr. Wewrote d=E′r.Inidealsituationwhered ≥b fori∈{1,...,n},we i i asimplestatictaintanalysisqueryusingCodeQL[2,17]to canachievesuchmostdesirableresultbyx=d−b. collectalllocationsthataccessptr.Wetheninitiatedseveral However,inreality,theremustbesomeentrieswhered < i concurrentfuzzingcampaignsusingtheselocationsastargets. b. Since elements of x cannot be negative, we cannot do i Consequently,a significant numberof vulnerabilities were x =d−b. The idea is that for all i such that d <b, we i i uncoveredwithin24hours. canknowthatwemustletx =0.Therefore,wecanremove i Forthesefuzzingcampaigns,theinitialcorpuswasunable all such entries to create another sub-problem, and we do tocoveranyblocksthatcouldreachanytargetsintheICFG thisrecursivelyuntild ≥b alwaysholds.Thealgorithmis i i duetotheindirectcall.Thisresultedinanemptysetofcritical detailedinAlgorithm6. block,prompting AFLRUN tofirstrunincoverage-guided mode. B TargetWeightCalculation As the fuzzing campaigns progress, coverage-guided fuzzing manages to find a seed that covers some of these At compile time, AFLRUN can be provided with a set of blocks,generatingcriticalblocksandpromptingAFLRUN targetlocationswiththeircorrespondingweight.Targetloca- to transition into directed fuzzing mode. However,certain 16constraints along the pathto the targetsites are difficultto Algorithm4DistanceComputation solve,preventingotherfuzzersfromhittingthesetargetsand Require: ICFG causingthesevulnerabilitiestoremainundetectedbyOSS- 1: ICFG’=transpose(ICFG) Fuzz.Thankstoourenergyassignmentalgorithm,AFLRUN 2: distance:V×T →R assignsasignificantamountofenergytofuzzthisseed,ef- 3: fort∈T do fectivelypassingtheseconstraintsandsubsequentlycovering 4: for(b,d)∈Dijkstra(ICFG’,t)do thetargets.Byfuzzingthesetargets,agroupofout-of-bounds 5: distance[b,t]=d readvulnerabilitieshasbeenidentified. 6: endfor WelistallvulnerabilityIDsofthisCVEasfollows:29848, 7: endfor 29882,29873,29874,29875,29876,29877,29878,29879, 8: return distance 29880,29881,29883,29884,29885,29886,29887,29888, 29889,29890,29891. AFLGo[12],totalingover5,000linesofC/C++code.Inthis D StaticDistanceComputation section,wewilldiscusssomeimplementationdetails. Staticanalysisandinstrumentation.Thecompilationstage We have developed an efficient method for computing the of AFLRUN is built upon the LLVM [26] Link Time Op- distance from each block to each target in O(|T||E|+ timization (LTO) pass [6] by modifying the AFL++ LTO |T||V|log|V|),whereV andE representvertices andedges compiler[23].First,weidentifyalltargetbasicblocks.Then, oftheICFG,andT ⊂V denotesthetargetblocks.Wefirstly usinginformationfromLLVM,weconstructtheICFGofthe definetheweightofeachedgefromvertexv srctovertexv dst PUT.WiththeICFG,wegatherallbasicblocksthatcanreach asfollows: atleastoneofthetargetblocks,includingthetargetblocks themselves,andcalculatetheirdistancestoeachtargetblock (cid:40) using the method described in Appendix D. Each of these log (N (v )) forcontrol-flowedge W(v ,v )= 2 out src basicblocksisassignedauniqueID.Moreover,toobtaincrit- src dst 0 forcalledge icalblocksatruntime,werecordthesubgraphoftheICFG withtheseblocksasvertices.Theseblocksareinstrumented ThetermN (v )representsthenumberofcontrol-flow out src withafunctionatthebeginning,whichwillbecalledwiththe outgoingedgesofvertexv .Therationalebehindthisweight src blockIDasanargumentwhentheblockisexecuted. definition is to assign higher weight to edges that are less Virginmapcomparison. InAFL++,whencomparingthe likely to be traversed after executing the basic block v . src execution trace with the virgin map,it avoids inefficiently Asaresult,theweightofbothcalledgesandunconditional comparingeachbitindividually.Instead,itcompares64bits control-flow edges shouldbe 0,while the weightofcondi- atatimebycastingpointersinto64-bitarrays.Foreach64-bit tionalcontrol-flowedgesgrowslogarithmicallywithrespect valueintheexecutiontraceandvirginmap,AFL++calculates tothenumberofoutgoingedges. theirbitwiseANDvalue,andanon-zeroresultindicatesnew Afterobtaining the weight foreach edge,we can define bit coverage by the execution trace. We employ the same the distance from block v to targett as the sum of weight techniqueforefficientcomparisonswithmultiplevirginmaps along the shortest path from v to t. This can be computed bycalculatingthebitwiseANDvaluebetweentheexecution usingDijkstra’salgorithm[18].Anaiveapproachinvolves traceandeachvirginmap.Eachnon-zeroANDvalueateach applying Dijkstra’s algorithm for each v ∈V, as done by location for each virgin map is also recorded and used to AFLGo [12]. However,this methodhas a time complexity ofO(|V||E|+|V|2log|V|),whichcanbeveryslowforlarge obtaindatainAlgorithm2. |
ICFGs.Instead,wecomputethisdistancebyreversingeach Targetclusters.WeassigneachclusteranID,andeachclus- edgeoftheICFGandapplyingDijkstra’salgorithmforeach tercontainsasetoftargetsrecordedusinganarrayindexed t ∈T,sincetheshortestdistancefromvtot intheICFGis bytheclusterID.Inadditiontorecordingthesetoftargets equalto the shortestdistance fromt to v in the transposed ineachcluster,wealsoneedtomapeachtargettoitsrespec- ICFG.AsthesetoftargetsT isusuallymuchsmallerthan tive clusterin orderto efficientlyimplementget_cluster thesetofbasicblocksV indirectedfuzzing,thismethodis functioninAlgorithm5.Thisisachievedusinghashmap[8]. significantlymoreefficientthanthenaiveone.Wedescribe Association rule mining. We implement support_count thismethodinAlgorithm4. inAlgorithm3usingtwodatastructures: oneforcounting 1-itemsets and another for counting 2-itemsets. We record E Implementation 1-itemset supportcounts using an array indexed by cluster ID,while2-itemsetsupportcountsarerecordedusinghash Wehaveimplemented AFLRUN,aprototypebasedonthe map[8],utilizingorder-insensitivepairsaskeys. ideaspresented,usingthesourcecodefromAFL++[20]and Covered blocks. For efficiency,we only consider covered 17blocksthatcanreachatleastonetargetintheICFG,eachof Table5:StatisticsaboutUniqueCrashes whichisassignedanIDduringstaticanalysis.Totracethe setofblockscoveredbytheexecutionofatestcase,weusea Program No.DiversityCrashes No.TotalCrashes Ratio sharedmemorywithnbits,wherenisthenumberofblocks libpng 1336 1437 92.97% assignedwithanID.Eachbitinmemoryrepresentsadistinct libsndfile 97 169 57.40% block.Intheinstrumentedfunctionforeachblock,theblock libtiff 4485 5476 81.90% IDisobtainedfromtheargument,allowinginstrumentedcode libxml2 3711 4448 83.43% lua 430 584 73.63% tosetthecorrespondingbitinthesharedmemoryto1toindi- openssl 31 38 81.58% catethattheblockiscoveredduringexecution.Furthermore, php 943 1084 86.99% similartothevirginmap,wealsohaveavirginblockbitmap poppler 753 1076 69.98% withn bits to recordeachblockcoveredbythe corpus,en- sqlite3 675 1395 48.39% ablingAFLRUNtodeterminewhetheranewseedcoversany newblocks. Energyassignment.Theenergyassignmentalgorithmdis- tercontainingit,andinsertthereturnedclusterintoclusters. cussedin§6.3involvesmatrixmultiplication.However,since Sincetargetsarenowclusteredanddifferenttargetscanreturn therelatedmatricesaretypicallysparse,computingmatrix thesameclusterfromget_cluster,weuseauniquesetasthe multiplicationexplicitlycanbeinefficient. Toaddressthis, datatypeforclusterstopreventduplicationofelements. werepresenteachweightvectorasahashmap[8]andusethe relevantinformationtodirectlydistributeweightfromone Algorithm5ObtainingSetofClusters hashmaptoanother. Require: covered_targetsandprimary_cluster 1: clusters=unique_set() 2: clusters.insert(primary_cluster) F QualityofExtraSeeds 3: fortarget∈covered_targetsdo 4: clusters.insert(get_cluster(target)) 5: endfor In this appendix section,we address RQ5 by counting the 6: return clusters number of unique crashes that are mutated from the extra seedsgeneratedbyourtargetpath-diversitymetricandcalcu- latingitsratiooverthetotalnumberofcrashes.Wecontinued H AdditionalExperiments tousetheresultsfromtheMagmabenchmark[22]anden- abled the fatal canary feature in Magma,causing any bug InadditiontotheMagmabenchmark,weconductedfurther triggerto resultin acrash. Foreachseedgeneratedduring experimentstoevaluatetheeffectivenessofAFLRUNcom- thefuzzingcampaign,AFLRUNannotatesitsfilenamewith paredtootherfuzzersusingasetofvulnerabilitiesusedin thefactorcontributingtoitsstorage. Specifically,ifaseed theevaluationsofpreviousdirectedfuzzingworks[24,25]. covers any new bits in the primary virgin map, AFLRUN Allfuzzersin§7.1.1areincludedinthisexperimentexcept marksacovflaginitsfilename,andsimilarlyaddsadivflag forAFLRUN--,theablatedversionofAFLRUNthatdoesnot ifanynewbitsarecoveredinthetargetvirginmap.Moreover, containthetargetpath-diversitymetricandcriticalblocksfor eachuniquecrashismarkedwiththeseedIDfromwhichthe evaluatingtheeffectivenessofcriticalblocksinourenergyas- uniquecrashismutated,alsoknownasthesourceseed.Using signmentmethod,ataskwehavealreadyaccomplishedusing thisinformation,wecantracktheflagsofthesourceseedfor theMagmabenchmark.However,westillincludeAFLRUN- eachuniquecrash.Weconsiderauniquecrashtobemutated foritsdescentabilityto findthe vulnerabilities thatdonot fromtheextraseedonlyifitssourceseedcontainssolelythe requirepathdiversitytotrigger. divflag.Wedenotesuchuniquecrashasthediversitycrash. Theexperimentalsetupwasidenticaltothatdescribedin TheresultsarepresentedinTable5.Weobservethatforthe §7.1.1:eachfuzzingcampaignwasconducted10times,with majorityofprograms,morethanhalfoftheuniquecrashes eachlasting24hours.However,wedirectlyusedthebuggy aremutatedfromourextraseeds,demonstratingtheability version of the tested program instead of reintroducing old oftheseextraseedstodiscovervulnerabilities. bugsintonewerversions.Additionally,welackedtheauto- maticvulnerabilitytriggertimerecordingfeatureprovided |
G ObtainingClusters byMagma.Toovercomethislimitation,eachfuzzerwascon- figured to record the time when a crashing input is saved. Algorithm5outlinestheprocessofselectingthesetofclus- Aftereachfuzzingcampaignends,weexecutedthefilesin tersfromtargetscoveredbytheexecutionofatestcase.First, the crash directory and identified the specific vulnerability weinsertprimaryclustercorrespondingtotheprimaryvirgin thatcauseseachcrash,basedontheexecution’soutput.This map.Then,foreachtargetcoveredbythetestcase,wefindits allows us to determine the triggering time of a vulnerabil- clusterusingget_cluster,whichmapseachtargettotheclus- ityin eachfuzzing campaign. Forthe initialfuzzing setup, 18Table6:AdditionalResults Program CVEID AFL++ AFLGo Parmesan FishFuzz Hawkeye WindRanger MOpt AFLRUN AFLRUN- 2016-4487 15.37m(0.01) 13.90m(0.08) N/A 18.27m(<.01) 33.01m(0.04) 26.54m(<.01) 51.80m(<.01) 5.31m 6.70m 2016-4489 37.33m(<.01) 37.55m(<.01) N/A 25.28m(<.01) 15.96m(<.01) 31.79m(<.01) 68.94m(<.01) 3.87m 2.88m cxxfilt 2016-4490 6.98m(<.01) 9.22m(<.01) N/A 9.25m(<.01) 3.78m(<.01) 8.31m(<.01) 19.82m(<.01) 52.20s 84.20s 2016-4491 21.90h(0.86) 17.29h(0.97) N/A 18.45h(0.97) 19.91h(0.97) 22.50h(0.86) 23.60h(0.86) T.O. T.O. 2016-4492 41.92m(0.17) 38.44m(0.09) N/A 46.37m(0.09) 2.94h(0.04) 77.24m(0.07) 97.45m(<.01) 30.30m 59.77m strip 2017-7303 2.95m(0.96) 2.88m(0.95) 8.45h(<.01) 36.72m(0.34) 6.70m(0.76) 74.21m(<.01) 4.47m(0.24) 7.39m 23.49m 2017-8393 27.67m(0.17) 36.43m(0.21) 13.30h(<.01) 3.55h(0.02) 4.48h(0.02) 1.79h(0.09) 28.95m(0.43) 62.99m 36.18m objcopy 2017-8394 26.95m(0.92) 14.34m(0.94) 5.15h(0.48) 6.17h(<.01) 3.00h(0.19) 9.10m(0.98) 8.92m(1.00) 67.11m 1.97h 2017-8395 6.64m(0.09) 1.88m(0.29) 30.34m(<.01) 3.71h(<.01) 94.10s(0.63) 2.03m(0.09) 2.94m(<.01) 1.73m 2.39m 2017-8392 97.68m(<.01) 6.31m(<.01) 82.40s(<.01) 8.14h(<.01) 3.73m(<.01) 2.86m(<.01) 8.67m(<.01) 16.50s 33.60s 2017-8396 6.42h(1.00) 22.58h(0.56) 19.30h(0.79) T.O.(0.18) T.O.(0.18) T.O.(0.18) 22.71h(0.56) T.O. 23.89h objdump 2017-8397 19.75h(0.03) 21.99h(<.01) 21.62h(<.01) 21.15h(<.01) 21.44h(<.01) 18.66h(0.05) 20.41h(0.02) 13.61h 12.51h 2017-8398 1.81h(0.50) 6.88m(0.26) 7.53h(<.01) 8.44h(<.01) 20.14m(0.01) 4.03m(0.87) 9.10m(0.07) 7.56m 13.10m 2016-9827 4.01m(<.01) 1.67m(0.02) N/A 86.70s(0.04) 62.10s(0.37) 89.00s(0.04) 86.50s(0.03) 61.20s 89.10s 2016-9829 33.59m(<.01) 9.14m(0.03) N/A 8.30m(0.57) 7.96m(0.71) 11.39m(0.26) 4.95m(0.71) 7.60m 6.55m 2016-9831 14.52m(<.01) 8.57m(0.03) N/A 11.23m(0.01) 6.90m(0.12) 7.89m(0.11) 10.86m(<.01) 4.31m 6.84m 2017-11728 66.83m(0.01) 24.57m(0.14) N/A 45.58m(0.02) 21.74m(0.04) 78.32m(<.01) 55.13m(0.01) 2.81h 46.11m 2017-11729 4.54m(<.01) 2.74m(0.10) N/A 7.00m(0.05) 2.87m(0.26) 12.55m(<.01) 19.49m(<.01) 1.80m 4.02m 2017-9988 7.17h(<.01) 59.18m(0.26) N/A 2.32h(0.19) 3.82h(0.21) 17.66h(<.01) 53.43m(0.15) 52.56m 5.11h 2017-7578 12.48m(<.01) 7.41m(<.01) N/A 3.30m(0.01) 7.59m(0.02) 5.82m(0.02) 6.55m(<.01) 1.70m 1.95m swftophp 2018-11095 1.72h(<.01) 83.75m(<.01) N/A 8.13h(<.01) 5.52h(<.01) 80.06m(<.01) 4.25h(<.01) 33.31m 7.58m 2018-11225 14.27h(0.32) 16.72h(0.05) N/A 19.95h(<.01) T.O.(<.01) 13.65h(0.45) 18.61h(0.02) 20.66h 9.77h 2018-20427 11.94h(0.28) 12.57h(0.09) N/A 14.46h(0.04) 14.52h(0.02) 7.37h(0.79) 9.22h(0.31) 12.74h 6.28h 2018-7868 3.25h(0.83) 3.19h(0.74) N/A 8.59h(0.08) 11.75h(<.01) 3.02h(0.81) 5.93h(0.11) 7.42h 3.48h |
2018-8807 2.27h(0.26) 2.47h(0.52) N/A 7.37h(<.01) 3.79h(0.14) 2.40h(0.66) 4.48h(<.01) 5.69h 2.06h 2019-12982 8.80h(0.42) 14.52h(0.20) N/A 15.08h(0.01) 20.80h(<.01) 6.21h(0.93) 13.72h(0.07) 21.13h 6.93h 2020-6628 2.69h(0.08) 1.93h(0.71) N/A 7.64h(<.01) 4.56h(0.08) 83.77m(0.96) 4.25h(<.01) 4.08h 1.96h 2019-9114 5.30h(0.94) 19.03h(<.01) N/A 14.22h(0.01) 19.23h(<.01) 9.56h(0.40) 17.01h(0.02) 13.63h 7.30h 2017-9047 23.46h(<.01) 22.00h(<.01) N/A 22.49h(<.01) T.O.(<.01) 18.49h(0.02) T.O.(<.01) 23.26h 12.74h xmllint 2017-5969 30.08m(<.01) 50.30s(1.00) N/A 28.10m(<.01) 28.30s(0.99) 57.05m(<.01) T.O.(<.01) 3.17m 2.36m 2017-9048 23.68h(0.06) T.O.(0.02) N/A T.O.(0.02) T.O.(0.02) 23.16h(0.07) T.O.(0.02) 22.75h 20.99h 2017-8846 18.89h(<.01) T.O.(<.01) N/A 2.15h(0.69) 4.77h(0.40) 2.96h(0.89) 21.61h(<.01) 7.43h 56.77m lrzip 2018-11496 14.10s(0.66) 47.10s(0.09) N/A 23.20s(0.83) 35.60s(0.58) 10.60s(0.85) 47.50s(0.11) 24.60s 51.50s weutilizedthesameseedcorpusasthepreviouswork[25]. fuzzers,demonstratingitssuperiorityacrossadiversesetof However, the target locations were different: we adjusted bugswithoutanyoverfitting. thetargetlocationstotheroot-causelocationsinsteadofthe vulnerability-trigger locations commonly used in previous works;besides,similarto§7.1.1,weutilizedmultiple-target settingstofindmultiplevulnerabilitiessimultaneously.These twodifferencesintargetlocationsalignwiththetwomain issuesaddressedinourwork. TheresultsarepresentedinTable6,formattedsimilarlyto Table1.ComparedtoAFL++,AFLGo,Parmesan,FishFuzz, Hawkeye, WindRanger, and MOpt, AFLRUN(-) achieves speedups of 164%, 77%, 819%, 319%, 136%, 118%, and 194% respectively. We observe the deviation ofthe results fromthoseobtainedfromMagma:AFLGoinsteadofMOpt becomesthebestperformeramongallnon-AFLRUNfuzzers, andtheeffectivenessofParmesandropssignificantly(even whenexcludingunrunnablecampaignsduetoitsbuggyim- plementation).Furthermore,ourresultsalsodifferfromthose ofprevious studies,as AFLGo outperforms the works that followed it. We believe this inconsistency arises from our differentconfigurationofthetargetlocationsmentionedear- lier.Nevertheless,AFLRUNstilloutperformstheothertested 19Algorithm6approach_ratio Require: E∈R,b∈Rnandr∈Rn 1: d :=(E+∑n i=1b i)r 2: remove:=set() 3: fori:=1tondo 4: ifd i<b ithen 5: remove.insert(i) 6: endif 7: endfor 8: x∈Rn 9: if|remove|=0then 10: fori:=1tondo 11: x i:=d i−b i 12: endfor 13: return x 14: endif 15: x′∈Rn−|remove|,b′∈Rn−|remove|,r′∈Rn−|remove| 16: j:=1 17: fori:=1tondo 18: ifi∈/ removethen 19: b′ j :=b i,r′ j :=r i 20: j:=j+1 21: endif 22: endfor 23: x′:=approach_ratio(E,b′,r′) 24: j:=1 25: fori:=1tondo 26: ifi∈removethen 27: x i:=0 28: else 29: x i:=x′ j 30: j:=j+1 31: endif 32: endfor 33: return x 20 |
2310.14137 FINDING VULNERABILITIES IN MOBILE APPLICATION APIS: A MODULAR PROGRAMMATIC APPROACH RESEARCHPAPER NateHaris,KendreeChen∗,AnnSong,BenjaminPou AdditionalContributors:AbhinavSood,AndrewCao,TiffanyLi,RonitBarman October24,2023 ABSTRACT Currently,ApplicationProgrammingInterfaces(APIs)arebecomingincreasinglypopulartofacilitate datatransferinavarietyofmobileapplications. TheseAPIsoftenprocesssensitiveuserinformation throughtheirendpoints,whicharepotentiallyexploitableduetodevelopermisimplementation. In thispaper,acustom,modularendpointvulnerabilitydetectiontoolwascreatedandimplementedto presentcurrentstatisticsonthedegreeofinformationleakageinvariousmobileAndroidapplications. OurendpointvulnerabilitydetectiontoolprovidedanautomatedapproachtoAPItesting,program- maticallymodifyingrequestsmultipletimesusingspecificinformationattackmethods(IAMs)and heuristicallyanalyzingresponsesforpotentiallyvulnerableendpoints(PVEs). AfteranalysisofAPI requestsinanencompassingrangeofapplications,findingsshowedthateasilyexploitableBroken AccessControl(BAC)vulnerabilitiesofvaryingseveritywerecommoninover50%ofapplications. ThesevulnerabilitiesrangedfromsmalldataleakagesduetounintendedAPIuse,tofulldisclosure ofsensitiveuserdata,includingpasswords,names,addresses,andSSNs. Thisinvestigationaimsto demonstratethenecessityofcompleteAPIendpointsecuritywithinAndroidapplications,aswell asprovideanopensourceexampleofamodularprogramwhichdeveloperscouldusetotestfor endpointvulnerabilities. Keywords API·APISecurity·APIVulnerability·APITesting·BAC·EndpointVulnerability·OWASPVulnerability 1 Introduction APIs serve as a multi-purpose communication medium complexorpoorlydocumentedAPIscanobstructdevelop- betweenclientandserver. APIschanneleveryuser-sent ersfromtestingextensivelyforsecurityflaws. Thus,itis requesttotheserver,carryingbackaresponse. Without oftensimpleforthirdpartiestogainsensitiveinformation APIs, many applications would not be able to function fromserver-sidedevicesortransferunauthorizedcontrols asitwouldbeimpossibletotransporttherequestedand inanetwork. providedinformation. APIvulnerabilitiesarecharacterizedbasedonweakpoints, Duetotheireffectivenessandeaseofuse,APIsarecom- commonality,andseveritytousersandapplications. The monly used by application developers. However, APIs Open Web Application Security Project (OWASP), one becomesecurityriskswhentheyareimproperlydesigned oftheleadingcommunityorganizationsofcybersecurity orimplemented.HackerscanexploitAPIvulnerabilitiesto professionalsandpenetrationtesters,publishesastandard harmserversorcausethemtoperformunintendedactions, awarenessdocumentforthestateofwebapplicationsecu- whichcanhavedireconsequencesfordevelopersandtheir rityeveryfouryears. users. Many small applications implementing personal APIsinstantiatevulnerabilitiesintheirbackendduetothe diverse number of potential attack points. Excessively BrokenAccessControl(BAC). Brokenaccesscontrol isavulnerabilityallowinguserstoaccessresourcesorper- ∗Co-LeadAuthor,LeadDeveloper 3202 tcO 22 ]RC.sc[ 1v73141.0132:viXraRESEARCHPAPER formactionsthattheyshouldnothaveauthorizationfor. In assessingtheeffectivenessofpotentialmethodsofabusing 2021,OWASP’s“TopTen”mostvulnerablewebapplica- this insecurity. The free web traffic applications HTTP tionsecurityrisksfeaturedBrokenAccessControl,most ToolkitandInsomniaRESTwereusedtoanalyzerequests notablytheCommonWeaknessEnumerationsCWE-200 fromamultitudeofAndroidapplications. Furthermore,a andCWE-201–exposureorinsertionofsensitivedataby scripttosendmodifiedAPIrequestswasrunonacross- auser–risingfourplacestothehighestposition,A01,due sectionofAndroidapplicationstoanalyzesusceptibility toitsmassmaxcoveragerateof94.55%. Asdefinedby to programmatic data scraping. After finding numerous OWASP,BrokenAccessControl(BAC)is“unauthorized exploitablevulnerabilities,onecanconcludethatproper informationdisclosure,modification,ordestructionofall APIsecurityshouldbeprioritizedbyapplicationdevelop- dataorperformingabusinessfunctionoutsidetheuser’s ers,withatminimumrigoroustestingnecessitatedinthe limits.” contextofsensitiveinformation. Wehopethatourefforts and conclusion will raise awareness among developers SinceBACsarelistedasawidespreadvulnerabilityamong that user data and API endpoint protection is of utmost applicationstestedbyOWASP,thispaperwasdedicatedto importance. 2 LiteratureReview Throughout the last twenty years, more and more com- complicated,andtime-consumingnatureoftheseanalysis panieshavebegunstoringdatainlarge-formatdatabases methodssometimesrenderstheminaccessibletoindepen- (Isha et al. [2018], Keary [2022]). The entry of data to dentornovicedevelopers(Korolov[2023]). thesedatabasesisfacilitatedbyvariousApplicationPro- Althoughthispresentsachallengeformanydevelopers, grammingInterfaces(APIs). APIsallowforeasytransfer there also exist open-source methods of assessing API of data between applications but are not always secure security(Bhuiyanetal.[2018],Sunetal.[2022],Wang (Sunetal.[2022]). Numerousprivatecorporationshave [2019]). UsingfreeAPImodificationprograms,onecan experienced large-scale information leakage due to API independentlyinterceptandscrutinizeAPIrequests(Perry vulnerabilitiesinrecentyears(Gibsonetal.[2021],Labs [2017],Google[2013],Inc.[2019])andcreateaprogram- |
[2021]). TheseAPIendpointvulnerabilitiesarebecoming maticapproachwhereAPIsaretestedusingacustomsetof increasinglycommoninapplications(Keary[2022]),pos- criteria(Bhuiyanetal.[2018]). However,suchprograms ingamassivethreattoorganizationsthatrelyonAPIsto oftenlacktheflexibilityrequiredtotestdifferentAPIs,or transportdatathroughtheweb(Zuoetal.[2019]). failtocorroboratewithalternativetestingprogramsonthe The most prevalent API vulnerability pertains to BACs status of vulnerabilities in these applications (Kim et al. (Shkedy[2019]).Datashowsthatthisspecificvulnerability [2016]). isbecomingincreasinglycommon,whilealsopresenting Due to the confusing state of API program testing, pro- criticallevelsecuritythreatsinapplications(Keary[2022], gramswithsimplisticyetmodularframeworksareimpera- Wang[2019]). Therealreadyexistmanycommercialtools tivetoassistingdevelopersfindvulnerabilities(Sunetal. that can test for this vulnerability (Afrose et al. [2023], [2022]). Thispaperaimstoimprovethestateofprogram- Ed-douibietal.[2018]),aswellasadvancedtheoretical maticAPItestingbycreatinganewflexible,expandable, detectionmethods(Barabanovetal.[2022],Yamaguchi andaccessibleframeworkforapplicationdevelopers. etal.[2011],Yamaguchietal.[2015]),howeverthecostly, 3 Methodology To understand and assess the current state of the API vulnerabilities in Android applications, an inclusive range of applications was analyzed. 72 applications were downloaded and tested using a static environment of Android Emulatortoreducesystematicdifferencesbetweentesterhardware. AfteranextensivetestofAPIfunctioncallsineach application,contributorsutilizedHTTPToolkittodownload.harfilescontainingrequestdatafromeachAPI.Inthe caseofarequestnecessitatingmanualtesting,InsomniaRESTwasusedtomodifyrequests. Similarly,casestudiesor severevulnerabilitieswerefurtheranalyzedusingInsomniaREST. TheprocessofsendingrequeststoAPIswasautomatedthroughaJavaprogramthatparsedlargequantitiesofapptraffic as.hardata. DatawasstoredinaSQLdatabasewithtwotables. Table1heldcollectedrequestdataandtheresultsof modifiedrequests,whiletheTable2heldrequestheadersforeachrequeststoredinTable1. Table1recordedrequestid number,requestmethod,url,requestbody,responsestatus,type,andbody,andadescriptionofthemodificationthat wasmade. ForeachheaderstoredinTable2,headeridnumber,theidnumberoftherequesttheheaderbelongedto, headername,andvaluewereincluded[Figure1]. 2RESEARCHPAPER Information Attack Method (IAM) In- formation Attack Method (IAM). Request modificationsweremadethroughprogrammatic generationstrategies,whichtargetedcommon BACvulnerabilitiessuchasIDORparameters to find API endpoints vulnerable to the ex- tractionofsensitiveinformation. Inthescript, eachIAMimplementedaparentinterfacethat allowedeachstrategytomodifydifferentparts ofarequesttoexploitpotentialvulnerabilities [Figure 2]. This modular approach maintains programscalability. IAMscanbeeasilyadded orupdatedtotestvaryingstrategiesandtestfor differenttypesofvulnerabilitieswithintheAPI. Themodificationstestedincludediteratinguser IDnumbers,removingheaders,changingURL parameters, removing request bodies, adding texttoheaders,andappendingJSONdata. Potentially Vulnerable Endpoint (PVE). Responsesfrommodifiedrequestswerestored inthefirstdatabasetableandparsedforregex keywordsandLevenshteindistancecomparison to the original returned data [Figure 3, 4], except for those that returned website CSS, HTML, or JavaScript code or text strings greater than 100,000 characters long; these wererecordedandparsedmanuallyforruntime efficiency. Responses with greater than 90% dissimilarity that contained data-sensitive Figure1: Examplelayoutshowingentriesofdatabasetables keywordswereflaggedasPVEs. Statisticsfor storinginformationonsentrequestsandrequestheaders. thesuccessrate,numberofdissimilarresponses, and number of PVEs generated by each IAM weregeneratedforeachapptested[Figure3]. ThescriptforprogrammaticIAMtestingwas runoneachoftheapplicationsinthecollected cross-section to provide statistics about PVE prevalenceinthemarket. Figure2: SimplisticviewofIAMinterfaceimplementedbyall methods. Therelevantmodificationfunctionsareoverriddenby eachimplementationtoeditAPIrequestbody,headers,orURL inawaypertainingtothestrategy. Figure4: Regexstringstoparseresponsesforsensitive information. Figure3: Regexstringstoparseresponsesforsensitiveinformation. 3RESEARCHPAPER ResponsePVEHeuristics Responseswithgreater than90%dissimilaritythatcontaineddata-sensitive keywordswereflaggedasPVEs. Statisticsforthesuc- cessrate,numberofdissimilarresponses,andnumber ofPVEsgeneratedbyeachIAMweregeneratedfor each app tested [Figure 5]. The script for program- matic IAM testing was run on each of the applica- tionsinthecollectedcross-sectiontoprovidestatistics aboutPVEprevalenceinthemarket. Figure 5: Flowchart detailing workflow sequence of program- maticrequestmodificationandvulnerabilitydetection. 4 Results 72 Android applications were analyzed in total. PVEs were recorded for 54.3% of applications, denoting that theycontainedpotentiallysensitivenewinformationthat hadlessthan90%similaritytotheoriginalresult[Figure 6]. Figure6: ExampleofaflaggedPVEresponse. Highlightedtext DifferentIAMsvariedinthenumberofPVEsproduced signifiesresponsedissimilarities. [Figure 7], with IAMs manipulating API request URLs producingthemostbyfar. Thissuggeststhatmanyofthe |
detected PVEs were due to insecure direct object refer- ences(anexampleofBAC),asmanipulationofreferences intheparametersoftheAPIrequestURLgeneratedthe greatestnumberofPVEs. Althoughthemajorityofanalyzedapplicationscontained PVEs, flagging them was susceptible to false positives, suchasifarequestreturnedtheuser’sowndatawithother dissimilartext. Nevertheless,PVEsefficientlyindicated potentialattackroutesforsensitiveinformationhandled by an API. With manual parsing of PVEs, the method undertakenexpeditedandsimplifiedfindingPVEsinap- plications. Approximately25%ofPVEsdisplayedserious exploitablevulnerabilitieswhenmanuallytested,mainly includingthereleaseofsensitivedata,demonstratingthe Figure7: Histogramshowingaveragenumberofflaggedcalls potentialofprogrammaticrequestmodificationtounearth perIAM privateinformation. Examplesofsuchexploitablevulnerabilitieswerenoticed innumerousapplications(mainlyconsistingofthefollow- ingCWEs: 200,201,285,359,538,540,862). Tobetter understandsomeofthesecriticalvulnerabilitiesfoundin applicationanalysis,anumberofcasestudieswillbein- cluded. 5 CWEVulnerabilities200,201,285,359,and862(Case1). Intheanalysisof72variousAndroidapplications,vulnerabilitiespertainingtoCWEs200,201,285,359,and862 (informationdataleakagethroughinsecureobjectsorauthentication)werefoundtobethemostprevalentandmost severe. Roughly20%ofPVEscontainedsomeformofthesevulnerabilities. NumerousvulnerableAPIendpointcalls wereidentifiedwhere,throughsimpleprogrammaticmodificationsofAPIURLs,headers,orauthenticationfunctions, athirdpartycouldaccesssensitiveuserdataofvariousprivateaccounts. 4RESEARCHPAPER Brokenaccesscontrol,thesubgroupingoftheaforementionedCWEs,asdefinedbyOWASP,ischaracterizedbya vulnerabilityallowingausertoaccessinformationoutsideoftheirspecifiedpermissions.IntheinstancesoftheAndroid applications, many vulnerabilities were caused by IDORs, allowing for horizontal privilege escalation. One such possibleexampleofavulnerableAPIrequestcouldbedemonstratedbythefollowingURL,classifiedasaCWE-359: https://example-site/users/get-info/?user=13495 InthisURL,“user”isaninsecuredirectobjectreferenceandanexampleofaBACvulnerability. Modeledaftera specificissuedetectedinanumberofAndroidapplications,iteratingthe“user”parametercouldallowonetoaccess users’data. Thisisahighlycriticalprivilegeescalationvulnerabilitythatcouldleadtotheleakageofsensitivedatain theresponsebody[Figure8]. Figure 8: Example of original and modified responses of exploitable IDOR vulnerability ThemosteffectiveapproachtonegatingthisvulnerabilityisthroughanimplementationofauthenticationinuserAPI requests. Withfunctionalauthenticationkeys,onlyauthorizeduserswillbeabletoaccessdata,regardlessoftheuser-id parameter. Anattemptataccessingprivatedatawouldresultina401errorcode(unauthorizedresponse). 5.1 CWEVulnerabilities538and540(Case2). In some select cases during analysis, the programmatic flaggingmethodandsensitiveinformationregexidentifier detected instances of CWE-538 and CWE-540. Both of thesevulnerabilitiesareassociatedwithleakageofsensitive datainsourcecodeorexternalfiles.IncertainAPIendpoint calls,modificationoftheURL,header,orbodywouldresult inthedisclosureofsourcecodeorexternalfilescontaining sensitivedata[Figure9]. IAMshadvaryingproportionsof callsthatreturnedcode,withURLmodificationsreturning themost. ThissupportedtheclaimthatURLmodification often serves as the entry point for many broken access controlvulnerabilities[Figure7,9]. Suchvulnerabilityisanexampleofinsecureinformation managementandsusceptibilitytoBAC.Duetotheiterative Figure9: Histogramshowingtheaveragenum- natureofthisvulnerability,simpleprogrammaticrequest ber of calls returning application source code modificationcouldrevealsensitiveinformation. Apossible perIAM. vulnerableAPIrequestdemonstratingthisvulnerabilityis asfollows: 5RESEARCHPAPER https://example-site/retrieve-data/?source=ABPQqLF6Vjt6Pzz7lHjE-CRrâĂę. InthisURL,amodificationofthesourcetextfieldcanexposeaninsecureinformationmanagementvulnerability. Withenoughiterationofthesourcetextfield,previouslyinaccessibledatacouldbedisclosedtoanunauthorizeduser. Althoughthisvulnerabilitycanleakhighlysensitiveinformation, itismuchmoredifficultandtime-consumingto exploit. Amongthenumerousapplicationsanalyzed,thisvulnerabilitywasonlydiscoveredafewtimes. The most effective approach to negating this vulnerability would be through the implementation of authentication duringAPIrequests. Inthisexample,accessprivilegeswouldbedeniedtouserswithoutanauthkeyortoken. This addedsecuritywouldprotectsensitiveinformation,causingunauthenticatedAPIrequestswouldresultina401error (unauthorizedresponse). 5.2 FalsePositivePotentiallyVulnerableEndpoints(FPPVEs). AlthoughflaggedPVEsoftenindicatedvulnerabilities,thereweresomecaseswherePVEsproducedfalsepositives,or APIresponseswhichdidnotexploitorrevealsensitiveinformation(FPPVEs). FPPVEsoccurredduetothecriteriaforclassifyingmodifiedAPIresponsesasPVEs,whichwasintentionallygeneralized toallowforvulnerabilitydetectioninawiderangeofapplications. ThepurposeoftheLevenshteindistanceformula andsensitiveinformationregexeswastoidentifymodifiedrequestswhichcontainedsomeformofsensitivedata,yet |
werealsodifferentfromtheoriginalresponse,astoeliminateclassifyingacallasaPVEwithsensitiveinformation pertainingtotheoriginaluser. Forexample,consideranAPIcallwhichreturnstheuser’sid,authentication,andlogin credentials. IfanymodificationtothisAPIcallsimilarlyreturnstheoriginaluser’sowndata,althoughtheinformation issensitive,itwaspreviouslyavailabletothatuser,meaningitshouldnotbeconsideredasavulnerability. The90% dissimilaritythresholdwasestablishedtotrytoreduceFPPVEsofthistype,flaggingonlyuniquedata,howeverspecific casesstillsatisfiedtheconditionsforaPVEwithoutcontainingtrulysensitiveinformation. AcasewhichcausedthistypeofFPPVEwastheexposureofuniqueandsensitive,butpublic,information. Thiscase wasmanuallydetectedinmanycommerciallocaterAPIs. Imaginethemobileapplicationofanexamplerestaurant. Whenorderingtakeoutonsuchanapplication,thereisasearchfeaturetofindonlytheclosestrestaurantstotheuser. ThisisauthorizedthroughanAPI,butuponmodifyingtheserequests,userscanextractaddressesofpreviouslyhidden restaurantlocations[Figure10]. Thiswouldresultinaresponseover90%dissimilartotheoriginalrequest,whilealso satisfyingtheaddressregextodetectsensitiveinformation,thusflaggingtherequestasaPVE. Figure10: Exampleoffalsepositivepotentiallyvulnerableendpoint(FPPVE) However,inthiscasethelocationsoftheexamplerestaurantarepubliclyavailable,possibletoaccessthroughthe intendeduseoftheAPIandalocationmodificationsoftwaresuchasaVPN,sotheextractedaddressesthroughthe modifiedrequestdonotleakanysensitiveinformation. ThisresultsinaFPPVEwheretheuniquesensitiveinformation revealedwas,inreality,notsensitive. FPPVEswerecommonamongapplicationswithidentifiedPVEs,andthusmanualrevisionwasnecessaryfordistinct cases. Upon analysis, PVE’s could easily be sorted into major vulnerabilities or FPPVEs. These FPPVEs could 6RESEARCHPAPER thenofferinsightonminorvulnerabilities,suchaspotentialattackroutesthroughexploitableAPIendpointbehavior. FPPVEsmightnothavedirectlycausedtheexposureoftrulysensitivedata,howevertheyfrequentlyperformedactions outsideoftheintendeduseoftheAPIendpoint,oraccesseddataoutsidethescopeoftheuser’sprivileges. Therefore, FPPVEsmeaningfullycontributedtoafurtherunderstandingofthelimitsandminorvulnerabilitiespersistentinanAPI endpoint. ThroughthemanualparsingofallPVEs—includingFPPVEs—theintegrityofanAPI’saccesscontrol protocolscouldbeholisticallyanalyzedandcategorizedintoitsminorandmajorvulnerabilities. 6 Conclusion Withtheconclusionofthisinvestigation,wehopetoreinforcetheconcerningstatisticsofthenatureofAPIvulnerabili- ties,andprovideaflexibleprogrammaticapproachtoAPIendpointtesting. Vulnerabilities,specificallypertainingto BAC,arebecomingincreasinglycommonamongAndroidapplicationsduetoimproperAPIimplementation.Amajority ofapplicationscontainsomeformofminorvulnerability,whileasmallerproportioncontainamajorsecurityflaw pertainingtothestorageofsensitiveuserinformation. (Ourteamhasnotifiedapplicationswherethesevulnerabilities werefound,presentingthenatureoftheflawandhowtoproperlysecuretheAPI).Wehopetoprovideamodular, open-sourceJavaprogramthatmaybeusedasatooltotestforBACvulnerabilities. Ourcode,availableonGitHub, canbeusedtohelpidentifythesespecificvulnerabilitiesquicklyandefficientlyinmasstestingofAPIfunctioncalls. Duetothedatapresentedonthecommonalityofthesevulnerabilities,weurgeapplicationdeveloperstobeconscious ofthepotentiallyinsecurenatureoftheirAPIendpoints. Withthecurrentportfolioofapplicationsandopen-sourceAPI testingprograms,weadviseeachdevelopertopersonalizeextensivetestingforanypotentialattackpointsintheirAPIs. 7 Acknowledgements ThankstoBenjaminZhuandYirayWangforassistanceindatacollection. References Isha,AbhinavSharma,andM.Revathi. Automatedapitesting. In20183rdInternationalConferenceonInventive ComputationTechnologies(ICICT),pages788–791,2018. doi:10.1109/ICICT43934.2018.9034254. TimKeary. 94URLhttps://venturebeat.com/security/api-security-incidents/. RonghuaSun,QianxunWang,andLiangGuo. Researchtowardskeyissuesofapisecurity. InWeiLu,YuqingZhang, WeipingWen,HanbingYan,andChaoLi,editors,CyberSecurity,pages179–192,Singapore,2022.SpringerNature Singapore. ISBN978-981-16-9229-1. BrandonGibson,SpencerTownes,DanielLewis,andSumanBhunia. Vulnerabilityinmassiveapiscraping: 2021 linkedindatabreach. In2021InternationalConferenceonComputationalScienceandComputationalIntelligence (CSCI),pages777–782,2021. doi:10.1109/CSCI54926.2021.00191. Salt Labs. Api threat research, Jul 2021. URL https://salt.security/blog/ api-threat-research-detailed-financial-records-exposed-on-financial-services-platform. Chaoshun Zuo, Zhiqiang Lin, and Yinqian Zhang. Why does your data leak? uncovering the data leakage in cloud from mobile apps. In 2019 IEEE Symposium on Security and Privacy (SP), pages 1296–1310, 2019. doi:10.1109/SP.2019.00009. Inon Shkedy. A deep dive on the most critical api vulnerability!!!FIX ME!!!-!!!FIX ME!!!bola, Dec 2019. URL https://inonst.medium.com/ a-deep-dive-on-the-most-critical-api-vulnerability-bola-1342224ec3f2. HuiWang. Preventinginsecuredirectobjectreferencesinappdevelopment,2019. URLhttps://www.cs.tufts. edu/comp/116/archive/fall2014/hwang.pdf. |
SharminAfrose,YaXiao,SazzadurRahaman,BartonP.Miller,andDanfengYao. Evaluationofstaticvulnerability detectiontoolswithjavacryptographicapibenchmarks. IEEETransactionsonSoftwareEngineering,49(2):485–497, 2023. doi:10.1109/TSE.2022.3154717. HamzaEd-douibi,JavierLuisCánovasIzquierdo,andJordiCabot. Automaticgenerationoftestcasesforrestapis: A specification-basedapproach. In2018IEEE22ndInternationalEnterpriseDistributedObjectComputingConference (EDOC),pages181–190,2018. doi:10.1109/EDOC.2018.00031. 7RESEARCHPAPER AlexanderBarabanov,,DenisDergunov,DenisMakrushin,AlekseyTeplov,,andand. AUTOMATICDETECTION OF ACCESS CONTROL VULNERABILITIES VIA API SPECIFICATION PROCESSING. Voprosy kiberbe- zopasnosti,(1(47)):49–65,2022. doi:10.21681/2311-3456-2022-1-49-65. URLhttps://doi.org/10.21681/ 2311-3456-2022-1-49-65. Fabian Yamaguchi, Felix "FX" Lindner, and Konrad Rieck. Vulnerability extrapolation: Assisted discovery of vulnerabilities using machine learning. In 5th USENIX Workshop on Offensive Technologies (WOOT 11), San Francisco, CA, August 2011. USENIX Association. URL https://www.usenix.org/conference/woot11/ vulnerability-extrapolation-assisted-discovery-vulnerabilities-using-machine. FabianYamaguchi,AlwinMaier,HugoGascon,andKonradRieck.Automaticinferenceofsearchpatternsfortaint-style vulnerabilities. In2015IEEESymposiumonSecurityandPrivacy,pages797–812,2015. doi:10.1109/SP.2015.54. MariaKorolov. Whyapiattacksareincreasingandhowtoavoidthem,Jul2023. URLhttps://www.csoonline. com/article/646557/why-api-attacks-are-increasing-and-how-to-avoid-them.html. Touhid Bhuiyan, Afsana Begum, s Rahman, and I. Hadid. Api vulnerabilities: Current status and dependencies. InternationalJournalofEngineeringandTechnology(UAE),7:9–13,032018. doi:10.14419/ijet.v7i2.3.9957. TimPerry. TheHTTPToolkitDocs. HTTPToolKit,2017. Google. DeveloperGuides. AndroidStudio,2013. KongInc. InsomniaDocs. InsomniaRest,2019. Sung Soo Kim, Da Eun Lee, and Choong Seon Hong. Vulnerability detection mechanism based on open api for multi-user’sconvenience. In2016InternationalConferenceonInformationNetworking(ICOIN),pages458–462, 2016. doi:10.1109/ICOIN.2016.7427159. 8 |
2310.15436 VGX: Large-Scale Sample Generation for Boosting Learning-Based Software Vulnerability Analyses YuNong RichardFang GuangbeiYi WashingtonStateUniversity WashingtonStateUniversity WashingtonStateUniversity yu.nong@wsu.edu richardfang2005@gmail.com guangbei.yi@wsu.edu KunsongZhao XiapuLuo FengChen HongKongPolytechnicUniversity HongKongPolytechnicUniversity TheUniversityofTexasatDallas kunsong.zhao@connect.polyu.hk csxluo@comp.polyu.edu.hk feng.chen@utdallas.edu HaipengCai∗ WashingtonStateUniversity haipeng.cai@wsu.edu ABSTRACT CCSCONCEPTS Accompanyingthesuccessesoflearning-baseddefensivesoftware •Securityandprivacy→Softwaresecurityengineering. vulnerabilityanalysesisthelackoflargeandqualitysetsofla- KEYWORDS beledvulnerableprogramsamples,whichimpedesfurtheradvance- mentofthosedefenses.Existingautomatedsamplegenerationap- vulnerabilitydataset,vulnerabilityinjection,dataquality,vulnera- proacheshaveshownpotentialsyetstillfallshortofpracticalexpec- bilityanalysis,deeplearning,programgeneration tationsduetothehighnoiseinthegeneratedsamples.Thispaper ACMReferenceFormat: proposesVGX,anewtechniqueaimedforlarge-scalegenerationof YuNong,RichardFang,GuangbeiYi,KunsongZhao,XiapuLuo,FengChen, high-qualityvulnerabilitydatasets.Givenanormalprogram,VGX andHaipengCai.2024.VGX:Large-ScaleSampleGenerationforBoosting identifiesthecodecontextsinwhichvulnerabilitiescanbeinjected, Learning-BasedSoftwareVulnerabilityAnalyses.In2024IEEE/ACM46th usingacustomizedTransformerfeaturedwithanewvalue-flow- InternationalConferenceonSoftwareEngineering(ICSE’24),April14–20, basedpositionencodingandpre-trainedagainstnewobjectives 2024,Lisbon,Portugal.ACM,NewYork,NY,USA,13pages.https://doi.org/ particularlyforlearningcodestructureandcontext.Then,VGX 10.1145/3597503.3639116 materializesvulnerability-injectioncodeeditingintheidentified 1 INTRODUCTION contextsusingpatternsofsucheditsobtainedfrombothhistorical fixesandhumanknowledgeaboutreal-worldvulnerabilities. Modernsoftwareiswidelyafflictedbysecurityvulnerabilities[30, Compared to four state-of-the-art (SOTA) (i.e., pattern-, 31,40,41],whichareincreasinglyconsequential[9,42].Thus,it Transformer-,GNN-,andpattern+Transformer-based)baselines, iscrucialtodevelopeffectivedefensesagainstvulnerabilities,for VGXachieved99.09-890.06%higherF1and22.45%-328.47%higher whichdata-driven,especiallydeep-learning-basedmethodshave labelaccuracy.Forin-the-wildsampleproduction,VGXgenerated demonstratedtremendouspotential,includingvulnerabilitydetec- 150,392vulnerablesamples,fromwhichwerandomlychose10%to tion[64,70–72],localization[28,35,44],andrepair[20,29,34]. assess how much these samples help vulnerability detection, Yetaccompanyingtherisingmomentumofdeeplearning(DL)in localization, and repair. Our results show SOTA techniques for softwareassuranceistheglaringlackofqualitytrainingdata.Infact, thesethreeapplicationtasksachieved19.15–330.80%higherF1, thisproblemhasdrawngrowingattentionfrombothacademiaand 12.86–19.31% higher top-10 accuracy, and 85.02–99.30% higher industryinrecentyears[10–12,18,19,52,53,68].Manualcuration top-50 accuracy, respectively, by adding those samples to their ofsuchdatasetsisintuitivelytedioushenceclearlyundesirable,and original training data. These samples also helped a SOTA itcanatbestproducerelativelysmalldatasetshenceunscalable[15, vulnerabilitydetectordiscover13morereal-worldvulnerabilities 26,50,62].Therefore,automaticallygeneratingvulnerablesamples (CVEs)incriticalsystems(e.g.,Linuxkernel)thatwouldbemissed atlargescaleandwithhighqualityisofparamountsignificance. bytheoriginalmodel. Inresponse,afewdatagenerationtechniqueshavebeendevel- oped,includingneuralcodeediting[18,25,65,66]andcontrol- ∗HaipengCaiisthecorrespondingauthor. flow-basedcodestitching[49].However,theformersuffersamajor chicken-eggproblem—trainingtheneuralcodeeditorrequiresa Permissiontomakedigitalorhardcopiesofpartorallofthisworkforpersonalor largesetofqualityvulnerablesampleswhicharewhatwearelack- classroomuseisgrantedwithoutfeeprovidedthatcopiesarenotmadeordistributed ing.Thelatter,byinsertingartificialvulnerablecodepatternsto forprofitorcommercialadvantageandthatcopiesbearthisnoticeandthefullcitation real-worldcode,resultsinunrealisticvulnerabilitieswhichonly onthefirstpage.Copyrightsforthird-partycomponentsofthisworkmustbehonored. Forallotheruses,contacttheowner/author(s). havelimitedusage.Other,evenearlierapproaches[38,39,68,69], ICSE’24,April14–20,2024,Lisbon,Portugal includingadaptableonesoriginallydesignedforprogrambugre- ©2024Copyrightheldbytheowner/author(s). pair[14,25]aresubjecttoevengreaterlimitations(e.g.,higher ACMISBN979-8-4007-0217-4/24/04. https://doi.org/10.1145/3597503.3639116 noise[66]andlowercoverageofvulnerabilityclasses[67]).Lately, 4202 naJ 4 ]ES.sc[ |
2v63451.0132:viXraICSE’24,April14–20,2024,Lisbon,Portugal YuNong,RichardFang,GuangbeiYi,KunsongZhao,XiapuLuo,FengChen,andHaipengCai VulGen[55]madegoodprogress;yetitstillsuffersfromhighnoise Inthethirdexperimentset,wedeployedVGXinthewildon inthegenerateddataduetoitslowgenerationaccuracy,aswellas 738Ksamples,henceproducing150Kvulnerablesamplesin50hours overfittingtotheseedvulnerablesamplesitlearnsfrom. 48minuteswitha90.13%successrate,118.07%moreaccuratethan Inthispaper,aimingatlarge-scalegenerationofhigh-quality VulGen—thebestbaseline.Then,inthefourthset,weaugmented vulnerableprogramsamples,wedevelopedanadvancedvulner- thetrainingsetsofSOTAdefensivevulnerabilityanalyseswith10% abilityinjectiontechnique,namedVGX(shortforVulnerability ofthose150Ksamples,consideringthescalabilityoftheanalysis GenerationeXpanded).VGXcombinesStep(1)semantics-aware tools.Inthisway,VGXhelpedimprove(1)(function-level)vulner- contextualization, which identifies the context of vulnerability- abilitydetectionby19.15%-330.80%intermsofF1;(2)(line-level) injectioncodeedits,withStep(2)human-knowledge-enhancededit vulnerabilitylocalizationby12.86%-19.31%intermsoftop-10ac- patternformation,usingthematerializedcontextualizedcodeedits. curacy;and(3)vulnerabilityrepairby85.02%-99.30%intermsof InStep(1),VGXbuildsaTransformer-basedcontextualization top-50accuracy.Thisis4.19%-266.42%higherthanaddingVulGen’s modelbydesigninganovelattentionmechanismwithabsolute generatedandexistingsyntheticsamples.Finally,inthefifthsetof andrelativepositionencodingbothbasedonvalueflowrelation- experiments,weappliedtheaugmentedversionofaSOTAvulner- shipsamongcodetokens,andthenpre-trainingthecustomized abilitydetectorto71latestCVEsinreal-worldprojectsandfound Transformer on a large code corpus, followed by fine-tuning it 62,including13thatwouldbemissedbytheoriginalmodel. onanexisting(task-specific)datasetofvulnerability-introducing WhilewecurrentlyimplementhenceevaluateVGXforCpro- codelocations.Tobenefitmorefromthepre-trainedmodel,VGX grams,ourVGXapproach/methodologyisnotlimitedtoapartic- alsointroducesnewpre-trainingobjectivesexplicitlygearedtoour ularprogramminglanguage.Theproposedcontextualizationand particulartask(ofcontextualizinginjectionedits). patternminingtechniquescanbereadilyadaptedforadifferent InStep(2),VGXstartswithextractingvulnerability-introducing language,ifgiventheASTandvalueflowparserforthatlanguage. codeeditpatternsfromthesametask-specificdatasetandthen Thestepofenhancingvulnerability-injectioneditpatternsbased enrichestheextractedpatternswithmanuallyidentified,different onhumanknowledgealsofollowsaprincipledprocedure,which patterns,followedbydiversifyingtheenrichedpatternsthrough canbereasonablyreplicatedforotherlanguagesaswell. manuallyderivedpatternmutationrules.Boththemanualpattern Insummary,thispapercontributesthefollowing: andmutationruledefinitionsarebasedonhumanknowledgeabout • Anoveldesignforinjection-basedvulnerablesamplegenera- existingreal-worldvulnerabilitiesgarneredfromCWE/CVEson tionthatleveragescodestructure-andcontext-awaresourcecode NVD[50]andbug/issuereportsonGitHub. pre-training,codesemantics-awareTransformerattention,data Thesemantics-informeddesigninStep(1)helpsVGXachieve augmentation,andhumanknowledgetoovercomekeylimita- effective contextualization of vulnerability-injecting code edits, tionsofexistingpeerapproaches. whilethehumanknowledgeincorporationinStep(2)helpsVGX • An implementation and evaluation of the design that shows overcomepotentialoverfittingtothesmalltask-specificdataset.In itssignificantlysuperiorperformanceoverfourSOTAbaselines, addition,wealso(1)pre-traintheprogramminglanguagemodelon includingthelatest,best-performingpeertechnique. theASTsoftheinputcodecorpusinordertobetterlearnsyntactic • Alargeandqualitysetof150Kvulnerablesamplesproducedusing andstructuralinformationinprogramsand(2)improvethetrain- theimplementation,whichcomeswithcorrespondingnormal ingwithdataaugmentation(throughsemantics-preservingcode code,ground-truthvulnerabilityandlocations,andhighlabel refactoring),asinspiredbyearlierworks[49,51]. accuracy,hencereadyforpublicuse. ToassessVGX,wepre-traineditscontextualizationmodelon • Empiricalevidencesthatshowthepracticalusefulnessofthe 1,214KCfunctionsandfine-tunediton7Kreal-worldvulnerability- generated dataset in terms of the substantial improvement it fixing samples augmented by 156K of their refactored versions. broughttovulnerabilitydetection,localization,andrepair,aswell Fromthese7Ksamplesalongwithmanualpatternrefinementand asitsabilitytoenablethediscoveryofreal-worldvulnerabilities diversification,weobtained604vulnerability-introducingeditpat- (CVEs)thatoriginalmodelsmiss. terns.Wethenconductedfivesetsofexperiments. Inthefirstset,weevaluatedtheaccuracyofVGXversusfour Openscience.SourcecodeofVGXalongwithalloftheexperi- |
state-of-the-artbaselines(VulGen[55],CodeT5[63],Getafix[14], mentalandresultingdatasetsareavailablehere. andGraph2Edit[65])against775testing(normal)sampleswith ground-truth(vulnerableversions).VGXachieves59.46%precision, 2 BACKGROUNDANDMOTIVATION 22.71%recall,and32.87%F1(239.77%-1173.23%,44.28%-780.23%, 99.09%-890.06%higherthanthebaselines),whenconsideringas Toautomaticallygeneratevulnerablesamples,anintuitiveideais truepositivesthegeneratedvulnerablesamplesexactlymatching to(1)learnthepatternsofknowncodeeditsthatintroducevulner- groundtruths.Whencountingallofthegeneratedsamplesthatare abilities(i.e.,vulnerability-introducingedits)andthen(2)applytoa indeedvulnerable(i.e.,notexactlymatchingthegroundtruthbut normalprogramthepatternsthatarecompatiblewithit,resulting stillexploitable)assuccesscases,VGXachieveda93.02%success inavulnerableversionoftheprogram.Suchanapproachhasbeen rate,22.45%-328.47%higherthanthebaselines.Inthesecondset demonstratedtobemeritoriousinearlierworks[14,55,66].Most ofexperiments,weshowedthateachofthenoveldesignelements recently,Nongetal.proposedVulGen[55],aninjection-basedvul- ofVGX(especiallythevalue-flow-basedsemantics-awareatten- nerablecodegenerationtechniquethatalsoleveragesthisstrategy. tionmechanismandhuman-knowledge-basedenhancementofedit Besidesthelearnedpatterns,itutilizesaTransformer-basedlocal- patterns)playedasignificantroleinitsoverallperformancemerits. izationmodeltolocatewheretoinjectvulnerabilities.WhileanVGX:Large-ScaleSampleGenerationforBoostingLearning-BasedSoftwareVulnerabilityAnalyses ICSE’24,April14–20,2024,Lisbon,Portugal dependsonwhetherthepatternisappliedintherightcodecon- 1 2 i {nt foo(char *password) Arrowed lines indicate text.Identifyingtherightinjectioncontextsisclearlyreliantoncode 3 char *buf=malloc(BUFSIZE*sizeof(char)) ; value flow, with different semantics,whichcanbelearnedbymakingthepositionencoding 4 5 i in ft ( br ue fs =; =NULL) c tho elo vr as lj uu es t f ld oi wffe or fe dn it fi fa et rin eg n t explicitlyawareofsemanticcodeinformationlikevalueflows[33] 6 return ‐ENOMEM; variables (e.g., `password’ (e.g.,valueflowofpasswordasillustratedinFigure1). 7 if(strlen(password)>=BUFSIZE) and `buf’). 8 return ‐EINVAL; 9 strcpy(buf, password); Grey background marks 3 TECHNICALDESIGN 10 res=check(buf); where vulnerabilities may 11 if(res==1) { be injected (e.g., Lines 5‐8). ThissectiondescribesthetechnicaldesignofVGX.Westartwith 12 printf("auth successful.\n"); anoverviewofVGXandthendescribethedetailsofeachmodule. 13 free(buf); 14 return res; 15 } else { 3.1 Overview 16 printf("auth failed.\n"); 17 free(buf); TheoverarchingdesigngoalofVGXistwo-fold:(1)large-scale— 18 return res;} 19} beingabletogenerateamassivenumberofsamplestomeetthe Fi2g0ure1:Amotivatingexampleonvulnerabilityinjection. thirstyneedoftrainingpowerfuldefensivemodels,whichrequires theabilitytoinjectvulnerabilitiestonormalcodeinthewildwhen followingtheinjection-basedmethodology,and(2)high-quality— importantstep,VulGenstillfallsshortoflarge-scalehigh-quality notincludingtoomanynoisysamples(i.e.,thosethatareconsidered vulnerabilitydatagenerationduetothefollowinglimitations: Limitation○1:Thelearnedvulnerability-injectioncode vulnerablebutactuallynot)amongthegeneratedones,without edit patterns are limited to those seen in the small whichthelargescalewouldnotbemeaningful.Withrespecttothe vulnerabilitydataset.VulGenminessuchpatternsfromexisting advancesmadebypriorworksandthechallengestheyface(§2), VGXachievesthisgoalwiththedesignshowninFigure2.VGX vulnerability-introducingcodeedits.Yetsinceavailabledatasetsof consistsoftwomainphases:learning/trainingandproduction. sucheditsare(evencollectively)limited,thepatternsminedarea Inthelearning/trainingphase,VGXgetsitselfbuiltupthrough small subset of the extant knowledge about how real-world twomaintasks:(1)trainadeeplearningbasedmodelthatcaniden- vulnerabilities can be introduced to software (as embodied in tifythecodecontextsinagiven(normal)programwherevulnera- extantvulnerabilitydocumentationsuchasCWE/CVEsinNVD bilitiescanbeinjectedand(2)minevulnerability-introducingcode andissues/bugreportsonGitHub).Forexample,inFigure1,the editpatternsthatcanmaterializetheinjectionintheidentifiedcon- statements marked gray at Lines 5-6 and 7-8 can be injected texts.Thesetwotasksareachievedintwosteps:semantics-aware "null-pointer-dereference" and "buffer-overflow" vulnerabilities, respectively,bydeletingtheif-statements.However,patternsas contextualizationandhuman-knowledge-enhancededitpatternfor- suchmaybetoogeneral suchthattheconditionandthereturn mation,followedbypreprocessingthedatasetsneededbythisphase. valuesinLines5and6arenotspecified,ortoospecificsuchthatall Intheproductionphase,withtheeditpatternsandtrainedcon- textualizationmodel,VGXstartswithpreprocessing(usingthesame |
the tokens for the condition in Line 7 are specified. Only the module)agivensetofnormalprogramsasinput.Then,themodel tokens"NULL","ENOMEM","EINVAL"arecrucialforvulnerability predictspotentialvulnerability-injectioncodeeditcontexts,fol- injectioninthisexample,buttherespectivepatternsaredifficultto lowedbymatchingandapplyingthemostsuitableeditpatterns mine due to the lack of available code samples covering them. Thus,toleveragetheirfullpotential,thepatternsneedtobettercover (forthecontexts),resultingin(expectedly)vulnerablesamples. theextantknowledge,ascanbeachievedbyincorporatinghuman 3.2 Preprocessing knowledgeintothepatternminingprocess. Limitation○2:Thelocalizationmodelistrainedonsource To enable semantics-aware contextualization via the customized codeasnaturallanguagetokensequences,ignoringsemantic Transformer,weusesyntacticinformationinsteadofprocessing informationthatisessentialforaccuratelyidentifyingwhere codeasnaturallanguage.Thus,westartbyconvertingsourcecode vulnerabilitiesmaybeinjectedinagivenprogram. While intoAbstractSyntaxTrees(ASTs),usingtree-sitter[47]astheAST theTransformer-basedlocalizationmodelinVulGenhasshownto parser.AnASTisatreecomposedofnodes,eachofwhichhasa bereasonablycapableof(e.g.,faulty)codelocalizationthanksto nodetype,asetofchildnodes,andavalueifitisaterminal. itsexplicitlearningaboutlocationsthroughpositionencoding,the SinceTransformertakestextasinputs,welinearizetheASTs goalofeffectivelycontextualizingvulnerability-injectioncodeedits intotext.Asin[51],wedoapre-ordertraversalontheASTto ishardtoachievewithavanillaTransformerpositionencoder.The getasequenceofnodetypesandonlykeepthenodesabovethe reasonisthatcodevulnerabilitiesarecontext-sensitive:thesame expressionleveltoreducesequencelength.Wethenconcatenate linesofcode(e.g.,copyinganarraytoabuffer)maycauseavul- thesourcecodeandthelinearizedASTforeachsamplewitha nerabilitywhenplacedinonecodecontext(e.g.,wherethereisno specialtoken[SEP]betweenthem.Weusethismixed/dualinput boundarycheckagainstthebuffer’ssize)butwouldnotleadtoany asithelpslearnthesyntacticandcontextualstructuresofcode[51]. vulnerablebehaviorinanothercontext(e.g.,wherethebufferhas TomakethecustomizedTransformerusesemanticinformation, beenensuredtobelargeenoughtoholdthearray).Forexample,in whichcanbeachievedviapositionencodingthatisexplicitlyaware Figure1,thesamplecannotbeinjecteda"buffer-overflow"vulnera- ofvalueflowasdiscussedin§2,weconstructavalueflowgraph bilitybyjustremovingLines7-8ifpassword[BUFSIZE-1]has (VFG)foreachsampleasin[33]—becauseitcancapturevulnera- beensetto’\0’.Thus,whetherpattern-basedinjectionisfruitful bilityrelatedcodesemantics[33,71].AVFGisamulti-edgegraphICSE’24,April14–20,2024,Lisbon,Portugal YuNong,RichardFang,GuangbeiYi,KunsongZhao,XiapuLuo,FengChen,andHaipengCai Learning/training Production Step 1: Semantics‐aware contextualization (model training) Pre‐training Preprocessing Customized Transformer Normal code corpus Value flow Sub‐graph Relative and Fine‐tuning programs Source analysis VFGs extraction ab suso bl gu rt ae p V hF sG pv oa slu ite i…o‐f nlo …ew n‐ cb oa ds ie nd g Pre‐training code (objectives: Preprocessing AST parsing Linearizationlinearized + Code input embedding CAP, ISP,…) vulE nx eis rt ai bn ig lity ASTs ASTs +AST Preprocessing fixes Trained contextualization model Step 2: Human‐knowledge‐enhanced edit pattern formation vulnerability‐injection AST parsing ASTs Pattern extraction e px at tr ta ec rt ne sd Pattern filtering/ranking code edit patterns m aa pP t pca h lt icit ne ag tr in oa n nd filtered patterns Vulnerability knH ou wm lea dn g e manually defined patterns Pattern refinement refined patterns diveP ra st ift ie cr an t ion documentation discovery manually derived pattern mutation rules (via mutation) Vulnerabl e samples Figure2:DesignoverviewoftheVGXapproach,highlightingitstwomainphases:learning/trainingandproduction. 𝑔(𝑉,𝐸),whereVisasetofnodeseachrepresentingavariableand vE ai rs iaa bs le et s.o Ff oe rd ig ne ss tath na ct e,e ia nch anre ap sr se igse nn mt eth ne tsv ta al tu ee mfl eo nw ts cb =e at +w be ,en edt gw eo s 𝑎 𝑖𝑗 = √1 2𝑑(𝑥 𝑖𝑊𝑄 )(𝑥 𝑗𝑊𝐾 +𝑟 𝑖𝐾 𝑗 +𝑟 𝑖𝐾 𝑗𝑉𝐹𝐺)𝑇 w Fio gu ul rd e1ex si hs ot wfro pm arta soto ftc hea vn ad luf ero flm owb st io nc th. eT mhe ota ivrr ao tiw nged exli an mes pli en . + √1 2𝑑(𝑎𝑄 𝑖 )(𝑎𝐾 𝑗 )𝑇 + √1 2𝑑(𝑎𝑄 𝑖 𝑉𝐹𝐺)(𝑎𝐾 𝑗𝑉𝐹𝐺)𝑇 (2) Ourvalue-flow-basedpositionencodingisbasedonthetradi- where𝑧 𝑖 istheoutputhiddenrepresentationforthe𝑖-thtoken, tionalone,whereabsolutepositionencodingiscalculatedasper 𝑎 𝑖𝑗 istheattentionbetweenthe𝑖-thand𝑗-thtokens;𝑥 𝑖 and𝑥 𝑗 are theabsoluteposition(i.e.,index)ofagiventoken.Yetwecalculate thisencodingofavariablebasedonitsrespectiveabsoluteVFGsub- thehiddenrepresentationofthe𝑖-thand𝑗-thtokensfromthepre- graph.Toobtainthissub-graph,wetraversetheVFGfromthenode viouslayer,respectively;𝑊𝑉 ,𝑊𝑄 ,and𝑊𝐾 aretheweightmatrix |
ofthatvariableuntilnonewnodescanbefound.Forinstance,in ofvalue,query,andkey,respectively;𝑟 𝑖𝑉 𝑗,𝑟 𝑖𝐾 𝑗 arethetraditionalrel- Figure1,thetokenpasswordatLine9hasthevalueflowmarked ativepositionencodingsand𝑎𝑄 𝑖 and𝑎𝐾 𝑗 arethetraditionalabsolute asred,andthusitsabsoluteVFGsub-graphconsistsofitselfand positionencodings;and𝑑isthedimensionofthehiddenrepresen- thenodeoftokenpasswordatLine1. tations.Thistraditionalpositionencodingissolelybasedonthe Similarly,wecalculatestherelativepositionencodingforapair positions(indexes)oftokenshencelackssemanticunderstandingof ofvariables(𝑣1,𝑣2)basedontheirrespectiverelativeVFGsub-graph. code.Forexample,avariableisdefinedatonelinebutusedmany Toobtainthissub-graph,wetraversetheVFGfromthenodeof𝑣1 linesafter.Inthiscase,thedistance(𝑖−𝑗)usedbythetraditional untilwereachthenodeof𝑣2.Forexample,inFigure1,thepairof relativepositionencodingmaybetoolarge,althoughthetwovari- variablesbufatLine5andBUFSIZEatLine3havetheirrelative abletokensmayshareadirectdefinition-userelationshipandhave VFGsub-graphconsistofthenodesoftokensbufatLine5,buf aclosesemantic(i.e.,value-flow)distance. atLine3,andBUFSIZEatLine3. Toaddressthislimitation,weutilizetheVFGsub-graphsob- Next,theresultingabsoluteandrelativeVFGsub-graphswillbe tainedduringpreprocessingtoincorporatesemanticinformation usedforpositionencodingaselaboratedin§3.3.1. intothepositionencoding.Specifically,weaddourvalue-flow-based 3.3 Semantics-AwareContextualization relativepositionencoding𝑟 𝑖𝑉 𝑗𝑉𝐹𝐺 and𝑟 𝑖𝐾 𝑗𝑉𝐹𝐺,aswellasvalue-flow- basedabsolutepositionencoding𝑎𝑄 𝑖 𝑉𝐹𝐺,and𝑎𝐾 𝑗𝑉𝐹𝐺 totheself- Inthisstep,wetrainacustomized Transformerinorder attentionblock,whereeachofthepositionencodingisthegraph toachievesemantics-awarecontextualization.Givenanormalpro- encodingoftherespectivesub-graph. gramwiththeCode+AST input,weexpectthemodeltooutputa TocomputetheencodingofagivenVFGsub-graph𝑔(𝑉,𝐸),we codefragmentthatcanbemanipulatedtointroduceavulnerabil- firstuseapre-trainedFastText[17]modelforClanguagetoconvert ity,basedonthesemanticsandcontextofthecode.Tothatend, thevariablenameineachnodeintoanembedding.Then,weusea thecustomizedTransformerleveragesvalue-flow-basedposition gatedgraphneuralnetwork(GGNN)toperformmessagepassing encoding,pre-training,andfine-tuningwithdataaugmentation.We aggregationandupdatethenodeembeddingasfollows: separatelydescribetheseinthefollowingsubsections. 𝑥 𝑣′ =𝐺𝑅𝑈(𝑥 𝑣, ∑︁ 𝑔(𝑥 𝑢)) (3) 3.3.1 Value-flow-basedPositionEncoding. Intheencoderofour (𝑢,𝑣)∈𝐸 customized Transformer,thecoremoduleisself-attention whereGRUisthegatedrecurrentfunction[21],𝑔(.) isthefunc- blockswithpositionencoding: 𝑧 𝑖 =∑︁ 𝑗𝑛 =1 (cid:205)𝑛 𝑗′𝑒 =𝑥 1𝑝 𝑒𝑥(𝑎 𝑝𝑖 (𝑗 𝑎) 𝑖𝑗′)(𝑥 𝑗𝑊𝑉 +𝑟 𝑖𝑉 𝑗 +𝑟 𝑖𝑉 𝑗𝑉𝐹𝐺) (1) t n ti heo ein g ght rh b aa o pt r ha n ts o os dim ge ei o tla f tt h𝑥e e𝑣s . Vt Th Fhe Gen n se , ui wg bh -e gb s ro u ar pmn ho u ed p me es b’ m ee dbm dedb inde gd in .d Fgin is ng o a, f la lt yn h ,d e th𝑥 n e𝑢 o gdis re ast ph i hneVGX:Large-ScaleSampleGenerationforBoostingLearning-BasedSoftwareVulnerabilityAnalyses ICSE’24,April14–20,2024,Lisbon,Portugal embeddingismultipliedwithaweightmatrixtogetthevalue-flow- Table1:ManuallyDefinedVulnerability-InjectionPatterns basedpositionencoding𝑟 𝑖𝑉 𝑗𝑉𝐹𝐺,𝑟 𝑖𝐾 𝑗𝑉𝐹𝐺,𝑎𝑄 𝑖 𝑉𝐹𝐺,and𝑎𝐾 𝑗𝑉𝐹𝐺 Patterns:*mutex*(h0);=>EMPTY Notethatnotallcodetokensarevariables.Thus,weonlycom- Justification:“RaceCondition”mostlyhappenswithalackofmutexrelatedstatements,butthere putethevalue-flow-basedpositionencodingwhenthetokenor aremanymutexrelatedfunction[6].Thus,oncethelocatedstatementinvolve“mutex”,wedeleteit. Patterns:*TCHECK*(h0);=>EMPTY *assert*(h0);=>EMPTY boththetokensinthepairarevariables.Otherwise,thevalue-flow- Justification:Therearemanysamplesinthetrainingsetdeletingstatementsinvolving"TCHECK" basedpositionencodingiszero. and"assert",buttheyusuallyusedifferentfunctionnames[3].Thus,oncelocatedstatementinvolve “TCHECK”or“assert”,wedeleteit. Patterns:*free*(h0);=>EMPTY *Free*(h0);=>EMPTY *destruct*(h0);=>EMPTY 3.3.2 Pre-Training. Togaintheawarenessofcodesemantics,we *destroy*(h0);=>EMPTY *unref*(h0);=>EMPTY *clear*(h0);=>EMPTY performedpre-trainingbeforefine-tuningthemodelforsemantics- Justification:"MemoryLeak"mostlyhappenswithnotreleasingassignedmemory.However,there maybemanydifferentfunctionsforreleasingthememory[4].Thus,oncethethelocatedstatement awarecontextualization.Weusethreeexistinggeneralprogramming involvememoryreleaserelatedfunctions,wedeleteit. Patterns:unsignedh0;=>h0; int64_th0;=>inth0; statich0h1=h2;=>h0h1=h2; language-orientedobjectivesfromCodeT5[63]andintroducetwo Justification:"TypeError"usuallyhappenswithnotusingstatic,unsigned,large-sizetypes,butthe newcodecontextualization-specificobjectives(CAPandISP). currentpatternsspecifytoomanydetailslikeidentifiernamesorassignedvaluesinthepatterns[7]. |
CodeT5Objectives.Weutilizethreepre-trainingobjectives T Ph au tts e, rw ne s:m ma ek me sth ete (s he 0d );e =ta >il Es Mho Pl Tes Ysot hh 0at =t *h Ee Ry Ra *r ;e =m >o Er Meg Pe Tn Yeral. h0=*NONE*=>EMPTY fromCodeT5[63]tolearngeneralcodecomprehensionforcode- h0=0;=>EMPTY h0=NULL;=>EMPTY *buf*=h0;=>EMPTY to-codetransformation.Thefirstismaskspanprediction(MSP), J au bls et si ,fi bc ua tt ci uo rn re: n"U tpse ato tef rU nn si sn pi et cia ifl yiz te od oV ma ari na ybl de es t" aiu lssu lia kl ely idh ea np tp ifie en rs nw amith esn ao nt din vait li ua eli sz ii nng thd ee pc ala ttr ee rd nsva [8ri ]- . where we randomly mask 15% of the source code tokens in an Thus,wemakethesedetailsholesanduseregularexpressiontorepresentthecommoninitialized value,sothattheyaremoregeneral. input that contains both source code and AST, with each mask Patterns:h0=kcalloc(hole1,hole2,hole3);=>h0=kzalloc(h1*h2,h3); havingaspanlengthuniformlyrangingfrom1to5tokens.We h0=calloc(hole0,hole1);=>h0=malloc(h1*h2); Justification:"MemoryAllocationVulnerability"usuallyhappenswhenusingunsafememory trainthemodeltorecoverthemaskedtokensbasedonthecontext. allocationfunctions,butcurrentpatternsspecifytoomanydetailslikeidentifiernamesandvalues Thesecondobjectiveisidentifiertagging(IT),wherethemodelis inthepatterns[5].Thus,wemakethemholestomakethepatternsmoregeneral. trainedtopredictwhethereachsourcecodetokenisanidentifier. Thethirdobjectiveismaskedidentifierprediction(MIP),wherewe existingvulnerabilityfixes.Toaddressthelackoffine-tuningdata, weperformdataaugmentationthroughcoderefactoringonthe maskalltheidentifiersinthesourcecode,andthemodelistrained fine-tuning samples. Following the approach in [54], we apply torecovertheidentifiersbasedonthecodesemantics.Wefollowthe three types of semantics-preserving refactoring: (1) reverse the pre-trainingapproachofCodeT5,andfeedthethreepre-training conditioninanif-statementandswapthecodeintheifand objectivesalternativelyduringtrainingwithanequalprobability. Code-ASTPrediction(CAP).Sinceourmodeltakessource elseblocks;(2)convertaforloopintoanequivalentwhile loop;and(3)insertunrelatedjunkcodegeneratedbySaBabi[61]to codeandASTsasinput,similartoSPT-Code[51],weadopttheir thecode.Weapplythesetransformationscombinatoriallyoneach approachandpre-trainourmodelwiththeCode-ASTPrediction originalsample,leadingtosubstantiallymorefine-tuningsamples. (CAP)objective.WeassignthecorrectASTtothecorresponding sourcecodein50%ofthepre-trainingsamples,whileintheother 3.4 EditPatternFormation 50%werandomlyassignanincorrectAST.Ourmodelistrainedto predictiftheassignedASTcorrespondstotheinputsourcecode. ThissectiondescribestheprocessofVGXonlearning(fromthe IrrelevantStatementPrediction(ISP).Foreachpre-training existingvulnerabilityfixes)tomaterializethecodeeditingforreal- sample,weinsertatarandomlocationarandomlychosenstate- izingvulnerabilityinjection,includingpatternextraction,pattern mentfromanothersample.Inthiscase,thefunctionalityofthe filtering/ranking,andpatternrefinementanddiversification. sampleisnotimpactedbyremovingtheinsertedstatement.Thus, 3.4.1 PatternExtraction. WefirstparsethesourcecodeintoASTs theinsertedstatementissemanticallyirrelevanttotheoriginalsam- liketheoneforsemantics-awarecontextualizationbutwithadif- ple.Wepre-trainthemodeltoidentifyandoutputtheirrelevant ferentASTparsersrcML[22],asitbettersupportseditpattern statementineachsample.Weadoptthispre-trainingobjectivebe- extractionandapplication[14,55].Then,wefollowtheapproach causeitresemblesourvulnerabilityinjectionlocalizationobjective. inGetafix[14]toextracttheeditpatternsviaanti-unification.Be- Sincevulnerabilitiesarecontext-sensitivebasedoncodesemantics, causeofthespacelimit,wereferreaderstotheoriginalGetafix learningtodifferentiate(semantically)irrelevantstatements(from paper[14]fordetails.Aneditpatternisapairofcodefragmentsin relevantones)intuitivelyhelpsidentifytherightcodecontextthatis termsofASTsrepresentingacodeedit.Forexample,"ℎ0[ℎ1−1] = (semantically)relevanttothevulnerabilitiestobeinjected. 0;=⇒ℎ0[ℎ1] =0;"representsremoving"-1"fromthecodewhere We conduct pre-training in the following order: first against h0andh1areplaceholderswhichcanmatchanyidentifiersand CAP,thenthethreeCodeT5objectives,andfinallyISP,asjustified literals.Afterthepatternextraction,wegetmanyeditpatternsthat bytheinter-dependenciesamongtheseobjectives.Also,forCAP rangefromverygeneral(i.e.,thepatternsthatcanmatchandapply andIT,thepre-trainingisdoneontheencoderonly,whileforall onmanydifferentcodesamples)toveryspecific(i.e.,thepatterns theotherobjectives(ISP,MSP,MIP)wepre-trainboththeencoder thatcanonlymatchandapplyonafewcodesamples)[14]. and decoder. These decisions are justified by the nature of the Transformerarchitecture. 3.4.2 PatternFiltering/Ranking. Toobtaintheappropriateeditpat- |
ternsforintroducingvulnerabilities,weestablishrulestofilterand 3.3.3 Fine-Tuning. After pre-training, we fine-tune the ranktheextractedpatterns.First,wecomputethreescoresforeach semantics-awarecontextualizationmodeltolocatecodefragments oftheextractededitpatterns: that can be edited to introduce vulnerabilities, using the (1) Prevalence score (𝑠 𝑝𝑟𝑒𝑣𝑎𝑙): Assuming knowing the vulnerability-introducing code locations retrieved from the vulnerabi-lity-introducinglocations,theprevalencescoreistheICSE’24,April14–20,2024,Lisbon,Portugal YuNong,RichardFang,GuangbeiYi,KunsongZhao,XiapuLuo,FengChen,andHaipengCai Table2:PatternMutationRules numberofsamplesthatcanbeinjectedthevulnerabilitiescorrectly by this pattern in the training set, as it is proportional to the Rule:function_name(parameters);=>new_function_name(new_parameters);⇔ h0=function_name(parameters);=>h0=new_function_name(new_parameters); probabilitythatthepatterncaninjectvulnerabilitiessuccessfully. Justification:Somefunctioncallslikestrncpymayreturnsomevaluesbutthereturnvalues (2)Specializationscore(𝑠 𝑠𝑝𝑒𝑐):Inthetrainingsamples,we donotalwaysassigntoavariable.Mutatingsuchpatternssothattheyhaveorremovethe returnvalueassignmentsincreasesthegeneralizabilityofthepatternset. computetheaveragenumberofASTsubtreesthatthepatterncan Rule:if(condition)returnNULL/0/-1;=>EMPTY⇔ match.Thereciprocaloftheaveragenumberisthespecialization if(condition)return-EINVAL/EBADFD/ENOTSOCK/EPERM/ENODEV/ENOMEM;=>EMPTY Justification:Thetypicalsafetyissuechecksdosomecheckinanifstatementconditionand score,asitindicateswhetherthepatternisspecificsothatitwill thenreturnanerrorcodewhenfoundtheissue.However,therearemanypossiblereturned notmatchASTsubtreeswhichcannotbeinjectedvulnerabilities. errorcodes.Wemutatethesereturnederrorcodestomakethepatternsmoregeneral. Rule:if(specific_condition)returnerror_code;=>EMPTY⇒ (3)Identifierscore(𝑠 𝑖𝑑𝑒𝑛𝑡):Theidentifierscoreisthenumber if(hole)returnerror_code;=>EMPTY ofspecifiedidentifiernamesinthepattern,astheidentifiernames Justification:Inourautomaticpatternmining,theminedsafetychecksifstatementsmaybe toospecificinthecondition.However,ifanifstatementonlyhasonereturnstatement,itis informaboutthecodesemanticssignificantly,whicharecrucial verylikelythatitisasafetycheckifstatement.Thus,weremovethespecificconditionsin forcorrectlyinjectingvulnerabilities. theseifstatementsanduseaholetomakethepatternsmoregeneral. Rule:if(condition)returnerror_code;=>EMPTY⇔if(condition)break/continue;=>EMPTY Theproductofthethreescoresisthefinalrankingscore. Justification:Whenthesafetychecksifstatementsfindissues,theymaynotalwaysexitthe 𝑠 𝑟𝑎𝑛𝑘 =𝑠 𝑝𝑟𝑒𝑣𝑎𝑙 ×𝑠 𝑠𝑝𝑒𝑐 ×𝑠 𝑖𝑑𝑒𝑛𝑡 (4) f cu on nc tt inio un eu tosin eg xia t.r Te htu ur sn ,. wIf et mhe us taa tf eet ty hc eh ee xc ik tsis tai tn ema efo nr t/w toh mile a/ ks ew ti htc eh pb al to tc ek rn,i st mm oa ry eu gs ee na erb ar le .akor Then,weranktheeditpatternsby𝑠 𝑟𝑎𝑛𝑘 inanon-ascending checkedthetraditionalmutationoperatorsforClanguage[13]. order.Thethreeindividualscoresarenotnormalizedsinceonly Wethenselectedthosethatdonotchangethecodefunctionality relativerankingsmatter.Thehigherthescore,themorelikelythe significantly and finally derived four types of pattern mutation patterncansuccessfullyinjectvulnerabilities.Finally,weonlykeep rules.Table2showsthepatternmutationruleswederivedand thetop300editpatterns,soastofilteroutthosethatarenotlikely therespectivejustificationsforthem.Thered⇔meansthatthe toinjectvulnerabilitiessuccessfully. mutationisbidirectional,while⇒meansthatthemutationisunidi- 3.4.3 PatternRefinementandDiversification. Whilethepatterns rectional.Afterthemutation,weobtainedatotalof604high-quality extractedandfiltered/rankedenabletoinjectvulnerabilitiesinsome vulnerability-injectionpatterns. cases,theydonotfullycapturetheknowledgeabouthowreal-world Currently, the pattern refinement and pattern mutation-rule vulnerabilitiescanbeintroducedtosoftwareasembodiedinthe derivationarecarriedoutmanuallyandaimedattheClanguage.Yet extantvulnerabilitydocumentationsuchasCWE/CVEsinNVD theprocesscanbereadilyreproducedandreplicatedbyfollowing andissues/bugreportsonGitHub,becausetheavailabledatasets theprincipledstepslaidoutabove.Thisalsolargelymakesour ofvulnerability-introducingeditsarestilllimited,asdiscussedin VGXapproachadaptableforotherprogramminglanguages. §2.Toaddressthislimitation,werefinethepatterns.Weapplied 3.5 VulnerabilityProduction the300patternstothevulnerability-introducingtrainingsamples, assumingknowingthevulnerability-introducinglocations.Asa With the trained contextualization model and the vulnerability- result,weencounteredfalsepositives,wherethepatternwasapplied injectioncodeeditpatterns,VGXisreadytoproducevulnerability butthegeneratedsamplewasnotactuallyvulnerable,aswellas data.Givenanormalprogram,weagainpreprocessitlikewedoin falsenegatives,wherenoneofthe300patternscouldbeapplied. thelearning/trainingphase.Next,thecontextualizationmodeliden- Forthefalsepositives,weconsiderthatthepatternsappliedon |
tifiesacodefragment(asthecontext)forvulnerabilityinjection. themaretoogeneral.Weremovedthepatternsagainstwhichmore Then,VGXappliesthemostsuitablepatterntotheidentifiedcon- thanhalfoftheapplicationsarefalsepositives.Intotal,weremoved text.Todoso,werankthepatternsinthefinalsetofvulnerability- 21patternsinthismanner. injectioncodeeditpatternsbythescorecomputedinEquation4and Forthefalsenegatives,weconsiderthatthecorrespondingpat- applythefirstpatterninthesetthatcanmatchthecontext.Note terns are too specific. Thus, we manually define new patterns thatVGXonlyinjectsthevulnerabilitywhenoneofthepatterns thatarenecessarilymoregeneral.Specifically,weexaminedthe matchesthecontext.Ifnoneofthepatternsmatches,VGXdiscards vulnerability-fixingcommitassociatedwiththefalse-negativetrain- thesampletoreducefalsepositives.Otherwise,theprogramwith ingsampleandidentifiedthecorrespondingCWEID[2].Then, thepatternappliedisexpectedtobevulnerable. wereadtheCWEdocumentationandchecktheexamplesusedto describethatCWE.Wefurtherexaminedotherreal-worldvulnera- 4 EVALUATION bilitysampleswiththesameCWEIDintheNVD/CVEdatabase[50]. WeevaluatetheeffectivenessofVGXforgeneratingvulnerability Basedonthefalsenegative,theexamples,andotherreal-world data.Weseektoanswerthefollowingresearchquestions: samples,wecomposeseveralpossiblepatternsthatwouldbeable • RQ1:HoweffectiveisVGXinvulnerabilitygenerationcompared toinjecttherespectivevulnerabilities.Then,wewentbacktothe tootherapproaches? existingpatternsetandfoundpatternsclosetothecomposedones. • RQ2:Howdothenoveldesigncomponentscontribute? Wefinallymodifiedthosepatternsintothecomposedoneswith • RQ3:HowefficientisVGXinvulnerabilitygeneration? theuseofregularexpression(regex).Thesemodifiedpatternsare the20manuallydefined,newpatternsdescribedinTable1. 4.1 Implementation Sincemanualrefinementiscostly,wearenotabletoderivemany newpatterns.Someremainingpatternsarestilltoospecificinsyn- Toensuretheaccuracy/reliabilityofthevalueflowgraphscreated tacticstructure.Thus,wefurtherderivedasetofpatternmutation inthepreprocessingmodule,weleveragethevalueflowextraction rulestomaketheeditpatternssufficientlygeneral.Wecarefully toolfromGraphCodeBERT[33]toconstructthevalueflowgraphVGX:Large-ScaleSampleGenerationforBoostingLearning-BasedSoftwareVulnerabilityAnalyses ICSE’24,April14–20,2024,Lisbon,Portugal ofeachsample.WemodifythesourcecodeofTPTrans[58]tobuild Table3:Effectiveness(andimprovementsinparentheses)of ourcustomizedTransformerasitprovidespositionencodingimple- VGXoverthebaselinesforvulnerabilitygenerationinRQ1. mentationwhichiseasytoadapt/customize.WeusetheGetafix implementationinVulGen[55]fortheanti-unification-basedpat- Technique Precision Recall F1 SuccessRate ternextraction.Ourexperimentswereperformedonamachine V VG ulX Gen 5 19 7. .4 56 0% %(239.77%↑) 2 12 5. .7 71 4% %(44.28%↑) 3 12 6. .8 57 1% %(99.09%↑) 79 53 .. 90 62 %% (22.45%↑) witha32CoresAMDRyzen3970X(3.7GHz)CPU,twoNvidiaRTX CodeT5 12.65%(370.04%↑) 12.65%(79.53%↑) 12.65%(159.84%↑) 24.81%(274.93%↑) Getafix 4.67%(1173.23%↑) 2.58%(780.23%↑) 3.32%(890.06%↑) 57.75%(67.07%↑) 3090GPUs,and256GBDDRmemory. Graph2Edit 13.97%(325.62%↑) 13.97%(65.56%↑) 13.97%(135.29%↑) 21.71%(328.47%↑) 4.2 Dataset Forthepre-traininginSemantics-AwareContextualization,weuse • CodeT5[63]isapre-trainedmodelgoodatcode-to-codetransfor- mation,whichcanbedirectlyfine-tunedtogeneratevulnerable theIBMCodeNet[59]dataset.Weextract1,213,907functionsinC languagefromittobuildthepre-trainingdataset.Forthefine-tuning codeforgivennormalprograms. inSemantics-AwareContextualizationandEditPatternFormation, • Getafix[14]isapatternminingandapplicationtechniquefor bugfixing.Wedirectlyuseitforvulnerabilitygeneration. weuse thedatasetinVulGen[55]which isthecombinationof • Graph2Edit[65]isacodeeditingmodeltakingaprogram’sAST fivewidelyusedvulnerabilitydatasets.Weremovetheoverlapped asinputandpredictingasequenceofeditsonit,whichcanbe samplesandeventuallyobtain7,764samplesfortheevaluation.We trainedforvulnerabilityinjection. splitthedatasetby9:1fortraining(6,989)andtesting(775).We thenaugment(§3.3.3)the6,989samplesinto156,665forfine-tuning. Table3showstheeffectivenessofVGXandthebaselinesagainst the775testingsamples.VGXgenerates296samples,ofwhich176 4.3 Metrics exactlymatchthegroundtruth.Thus,theprecision,recall,and F1is59.46%,22.71%,and32.87%,respectively.Thehighprecision Giventhatahigh-qualityvulnerabilitysampleshouldbeatruly indicatesthegoodqualityofthegeneratedsamples,andthe22.71% exploitableprogram[23],weevaluatewhetherthecodechanges recallsuggeststhegeneralizabilityforsupportinglarge-scalevul- |
maketheprogramexploitablefortheattackers.Forthesamples nerabilitygeneration.The32.87%F1showstheoverallpromising exactly-matchingtheirgroundtruths,theyareknownasexploitable effectivenessofVGX—99%higherthanthebestbaseline.Notably, becausetheyareconfirmedreal-worldvulnerabilities.Forthese Column3showsVGX’ssuccessrateof93.02%,indicatingthatthe cases,weevaluatevulnerabilitygenerationintermsofprecision,re- vastmajorityofitsgeneratedsamplesarevulnerable/exploitable. call,andF1.Wecompute:𝑝𝑟𝑒𝑐𝑖𝑠𝑖𝑜𝑛= #𝑚𝑎𝑡𝑐ℎ𝑒𝑑𝑠𝑎𝑚𝑝𝑙𝑒𝑠 ;𝑟𝑒𝑐𝑎𝑙𝑙 = Table3Rows3-6showtheeffectivenessofthefourbaselines, #𝑔𝑒𝑛𝑒𝑟𝑎𝑡𝑒𝑑𝑠𝑎𝑚𝑝𝑙𝑒𝑠 #𝑚𝑎𝑡𝑐ℎ𝑒𝑑𝑠𝑎𝑚𝑝𝑙𝑒𝑠 and𝐹1= 2×𝑟𝑒𝑐𝑎𝑙𝑙×𝑝𝑟𝑒𝑐𝑖𝑠𝑖𝑜𝑛 . andthenumbersinparenthesesindicateVGX’srelativeimprove- #𝑡𝑒𝑠𝑡𝑖𝑛𝑔𝑠𝑎𝑚𝑝𝑙𝑒𝑠 𝑝𝑟𝑒𝑐𝑖𝑠𝑖𝑜𝑛+𝑟𝑒𝑐𝑎𝑙𝑙 mentsoverthebaselines.VGXoutperformstheGNN-basedcode Sincethegeneratedsamplesmaybeexploitablealthoughdonot editorGraph2Editbysubstantialmargins.WhileGraph2Editisa exactlymatchthegroundtruth[54,55],werandomlysampledand general-purposecodeeditorwithapromisingeditingprocess(i.e., manuallyinspectedsomeofthemtocomputethe𝑠𝑢𝑐𝑐𝑒𝑠𝑠𝑟𝑎𝑡𝑒 = predictingasequenceeditsontheAST)[54],itsuffersfromthe # #𝑒 𝑔𝑥 𝑒𝑝 𝑛𝑙 𝑒𝑜 𝑟𝑖 𝑎𝑡𝑎 𝑡𝑒𝑏 𝑑𝑙𝑒 𝑠𝑠 𝑎𝑎 𝑚𝑚 𝑝𝑝 𝑙𝑙 𝑒𝑒 𝑠𝑠 where the𝑒𝑥𝑝𝑙𝑜𝑖𝑡𝑎𝑏𝑙𝑒 𝑠𝑎𝑚𝑝𝑙𝑒𝑠 also include lackoftrainingsamplesasGNNneedsalargenumberofsamples the𝑚𝑎𝑡𝑐ℎ𝑒𝑑𝑠𝑎𝑚𝑝𝑙𝑒𝑠.Weinspected258cases,asamplesizethatis tobereasonablytrained[55].VGXoutperformstheCodeT5and statisticallysignificantat95%confidenceleveland5%marginof Getafixalsoquitesignificantly. Thismaybejustifiedbythemerits errorwithrespecttothepopulation(i.e.,testingset)sizeof775. ofcombiningdeeplearningtolocateinjectionwithapattern-based Themanualinspectionofasampleassessesifanexploitcanbe methodtomaterializeinjectionedits.WhileVulGenalsoworks writtentoattackit.Yetmanuallywritingexploitsforallthenon- inanoverallsimilarway,VGXstillgreatlyoutperformsit.Thisis exactly-matchingsamplesgeneratedbyVGXandbaselinetech- duetoVGXtakingtheadvantagesofhuman-knowledge-enhanced niquesisquitedifficult.Thus,wewroteexploitsfor30%ofthose editpatternsandsemantics-awarecontextualization,whichlargely samplesinRQ1andRQ4.Eachexploitisanexecutablethatcan overcomeVulGen’sLimitation○1 andLimitation○2,respectively. attackthegeneratedprogrambutnotthenormalone,ensuringthe exploitabilityisintroducedbythecodechange.Thisprocesshelps 4.5 RQ2:ContributionsofNovelComponents uslearnhowtodecidewhetherasampleisexploitable,basedon Inthissection,weinvestigatethecontributionofeachnovelcom- whichwedeterminedtheexploitabilityoftheremaining70%with- ponentinVGXthroughablationstudies.Weremoveeachofthose outactuallywriting/runningtheexploits.Theinspectionwasfirst componentsandcomparetheeffectivenessbeforeandafterthe donebythefirstauthor,checkedbythethirdandfourthauthors, removal.TheresultsareshowninTable4.Toshowtheimpacts andthenverified/calibratedbyallthreetoensurethecorrectness. ofthecontextualizationdesigns,wealsoreportthelocalization accuracyinColumn2.ThenumbersinparenthesesindicateVGX’s 4.4 RQ1:EffectivenessofVGX relativeimprovementscomparedtotheablatedversions. Toassesstheimpactofthecontextualization-specificpre-training WeassesstheeffectivenessofVGXoverfourbaselines: objectives,weremovethepre-trainingforCAPandISP.Table4 • VulGen[55]isavulnerabilitygenerationtoolwhichfine-tunes Row3showstheresults.Withthetwopre-trainingtasks,VGX CodeT5[63]forlocalizationandusesGetafix[14]tomineedit improvesthelocalizationaccuracyby4.37%,andthusimproves patternsforvulnerabilityinjection. thevulnerabilitygenerationby9.38%,8.55%,and8.87%intermsICSE’24,April14–20,2024,Lisbon,Portugal YuNong,RichardFang,GuangbeiYi,KunsongZhao,XiapuLuo,FengChen,andHaipengCai Table4:ThecontributionofVGX’scomponentsforvulner- 4.6 RQ3:EfficiencyofVGX abilitygeneration.ThenumbersinparenthesesareVGX’s AsVGX,VulGen,andGetafixsupportmultiprocessinggeneration relativeimprovementscomparedtotheablatedversions. butCodeT5andGraph2Editdonot,weusesingle-processgener- ationforafaircomparison.Onaverage,VGXinjectsvulnerabili- Experiment LocAcc Precision Recall F1 tieson189.02samplesperminute,whilethenumbersforVulGen, VGX 55.35% 59.46% 22.71% 32.87% NoCAPandISP 53.03%(4.37%↑) 54.36%(9.38%↑) 20.90%(8.66%↑) 30.19%(8.87%↑) GetafixCodeT5,andGraph2Editare132.85,276.78,29.88,and89.08, NoAST 49.67%(11.44%↑) 53.90%(10.32%↑) 19.61%(15.81%↑) 28.76%(14.29%↑) NoVFG 52.13%(6.18%↑) 53.29%(11.58%↑) 21.93%(3.56%↑) 31.07%(5.79%↑) indicatingVGXiscomparabletothebaselinesintermsofefficiency. NoAugmentation 51.61%(7.25%↑) 53.33%(11.49%↑) 19.61%(15.81%↑) 28.67%(14.65%↑) NoDiversification 55.35%(0.00%↑) 62.45%(-4.78%↑) 20.38%(11.43%↑) 30.73%(6.96%↑) 5 USEFULNESSOFVGX NoRefinement 55.35%(0.00%↑) 71.91%(-17.31%↑) 16.51%(37.55%↑) 26.85%(22.42%↑) |
WeuseVGXtogeneratealarge-scalevulnerabilitydatasetandeval- uatetheusefulnessofthedatafortrainingdownstreamDL-based vulnerabilityanalysistools.AsVulGenisalsodesignedforvulner- ofprecision,recall,andF1,respectively.Thisindicatesthatthe abilitydatagenerationandisshowntoberelativelyeffectivein contextualization-specificobjectivesareeffectiveforpre-training. theoriginalpaper[55],wealsodirectlycompareVGX’susefulness TounderstandthecontributionofthelinearizedAST,weremove withVulGen.Weanswerthefollowingresearchquestions: theASTpartintheTransformerinputandonlyusethesource • RQ4:HoweffectiveisVGXingeneratinglarge-scalevulnerable code.Table4Row4showstheresults.WithlinearizedAST,VGX datausingnormalprogramsinthewild? improvesthelocalizationaccuracyby11.44%,andthusimprovesthe • RQ5:CanthegeneratedsamplesimprovethedownstreamDL- vulnerabilitygenerationeffectivenessby10.32%,15.81%,and14.29% basedvulnerabilityanalysistools? intermsofprecision,recall,andF1,respectively.Thisindicates • RQ6:Cantheimprovedvulnerabilitydetectionmodelsfindmore thataddingthelinearizedASTtotheinputtexteffectivelyhelps latestreal-worldvulnerabilities? themodelunderstandthesyntacticstructureofthecode,hence notablyimprovingvulnerabilityinjection. 5.1 RQ4:Large-ScaleProduction ToshowtheeffectivenessoftheVFG-basedpositionencoding, we remove it and only use traditional position encoding in the To get a large number of normal samples for VGX to generate Transformermodel.Table4Row5showstheresults.Withour vulnerabilitydata,wefollowtheapproachin[26]tocollectthe newpositionencoding,VGXimprovesthelocalizationaccuracyby latestsourcecodeof238projectsthatareinvolvedintheCVE/NVD 6.18%,andthusimprovesthevulnerabilitygenerationeffectiveness database[50].Then,weextractthefunctionsintheseprojectsand by11.58%,3.56%,and5.79%intermsofprecision,recall,andF1, obtain738,453normalfunctionsforvulnerabilityinjection. respectively.ThisindicatesthattheVFG-basedpositionencoding WeapplyVGXonthesefunctionsanditgenerates150,392sam- helpstheTransformerunderstandthesemanticsofthecode,thus plesin50hours48minutes.Werandomlysamplesometomanually improvesthevulnerabilitygenerationsignificantly. inspect.Withthesameprocedurein§4.3,thesamplesizeis375. Tomeasuretheimpactofthedataaugmentationwhenfine-tuning Again, we write exploits for 30% (102) of the samples and then the contextualization model, we use the original 6,989 training directlylabeltheremainingsamples.Thesuccessrateis90.13%, samplesonlytotrainit.Table4Row6showstheresults.Withthe whichisclosetothesuccessrate(93.03%)forRQ1(§4.4).Incom- dataaugmentation,Thelocalizationaccuracyimprovesby7.25%, parison,VulGengenerates686,513samples.Withthesamplesize andthusimprovesthevulnerabilitygenerationeffectivenessby 384,thesuccessrateis41.33%.Thisisnotonlymuchlowerthan 11.49%,15.81%,and14.65%intermsofprecision,recall,andF1, VGX’s,butalsomuchlowerthanitsown(75.96%)in§4.4.Therea- respectively.Thisindicatesthatthedataaugmentationmitigates sonisthatVulGen’seditpatternsarevaguehenceappliedonthe thelackoftrainingdata,thusishelpfulforvulnerabilitygeneration. statementsthatcannotbeinjectedvulnerabilities(Limitation○1) To see the impact of pattern diversification, we only use the andthelocalizationmodelisnotsemantics-awarehencelessaccu- editpatternspriortothediversification(mutation).Table4Row7 rate(Limitation○2).ThisshowsthatVGXiseffectivetogenerate showstheresults.Whilepatterndiversificationmakestheprecision large-scalevulnerabilitydatafromthewildwhileVulGenisnot. decreaseby4.78%,therecallandF1improveby11.43%and6.96%, Wealsocheckedthevulnerabilitytypesrepresentedbythese375 respectively.Whilethemutationmakesthevulnerabilityinjection samplesandfoundthattheycover23types(CWEs).Figure3shows moregeneral,italsomakesthepatternslessrestrictiveagainstthe thedistributionofthem.Itisworthnotingthatthesetypesinclude injectioncontextidentified.Theimprovementofrecallindicates manyofthemost(e.g.,top-25)dangerousonesaccordingtothe thatVGXisabletogeneratemorevulnerablesamples,whichis recentCWEreport[2],suchasCWE-787,CWE-20,CWE-125,etc. importantforgeneratinglarge-scalevulnerabilitydatasets. Thisindicatesthatourgeneratedvulnerabilitysamplesarediverse. Wefurtherrollbacktheeditpatternsettotheonewithoutpat- 5.2 RQ5:DownstreamAnalysisImprovement ternrefinement.Table4Row8showstheresults.Wecanseethe recallandF1furtherdecreaseto16.51%,and26.85%,respectively, Giventhevulnerabilitygenerationprocess,ourdatasupportsmodel whiletheprecisionincreasesto71.91%.Thisindicatesthatpatterns trainingforatleastthreedownstreamtasks:(1)function-levelvul- withoutrefinementaretoostrictandspecific,makingitdifficult nerabilitydetection;(2)line-levelvulnerabilitylocalization;and(3) forVGXtogeneratelarge-scalevulnerabilitydata.Thus,ourre- vulnerability repair. We use the generated data to augment the |
finementimprovesthegeneralizabilityofthepatterns,makingthe trainingsetsofthemodelsandshowtheimprovementafterthe overallvulnerabilitygenerationmorescalable. augmentation.SincesomemodelsaredesignedfortheexistingVGX:Large-ScaleSampleGenerationforBoostingLearning-BasedSoftwareVulnerabilityAnalyses ICSE’24,April14–20,2024,Lisbon,Portugal 100 Table 6: Improvement of vulnerability localization using 80 VGX’s,VulGen’sgeneratedsamples,andsamplesfromSARD. 60 40 Model Top-10Accuracy Model Top-10Accuracy 20 LineVul-ori 48.84% LineVD-ori 59.25% 0 LineVul-aug-VGX 58.27%(19.31%↑) LineVD-aug-VGX 66.87%(12.86%↑) LineVul-aug-VulGen 53.43%(9.39%↑) LineVD-aug-VulGen 52.68%(-11.09%↑) LineVul-aug-SARD 49.85%(2.07%↑) LineVD-aug-SARD 64.18%(8.32%↑) Figure3:Thevulnerabilitytype(CWE)distributionofgener- Table7:ImprovementofvulnerabilityrepairusingVGX’s, atedvulnerablesamplesinthelarge-scaleproduction. VulGen’sgeneratedsamples,andsamplesfromSARD. Model Top-1Accuracy Top-5Accuracy Top-50Accuracy Table5:ImprovementofvulnerabilitydetectionusingVGX’s, VulRepair-ori 8.55% 11.81% 16.29% VulGen’sgeneratedsamples,andsamplesfromSARD. VulRepair-aug-VGX 21.05%(146.20%↑) 29.12%(146.57%↑) 30.14%(85.02%↑) VulRepair-aug-VulGen 11.81%(38.13%↑) 16.77%(41.20%↑) 17.85%(9.85%↑) VulRepair-aug-SARD 11.07%(29.47%↑) 13.92%(17.87%↑) 17.18%(5.46%↑) Model Precision Recall F1 VRepair-ori 2.58% 5.16% 8.62% Devign-ori 9.82% 50.19% 16.43% VV RR ee pp aa ii rr -- aa uu gg -- VVG ulX Gen 24 .. 84 51 %% (( 17 00 .. 49 63 %% ↑↑) ) 1 70 .2.5 69 %% (4(1 00 .75 0.2 %3 ↑% )↑) 11 47 .. 01 58 %% (( 69 29 .. 93 90 %%↑ ↑) ) Devign-aug-VGX 12.37%(25.97%↑) 52.47%(4.54%↑) 20.01%(21.79%↑) VRepair-aug-SARD 1.36%(-47.28%↑) 3.46%(-32.94%↑) 4.96%(-42.45%↑) Devign-aug-VulGen 11.23%(14.35%↑) 30.03%(-40.17%↑) 16.35%(-0.49%↑) Devign-aug-SARD 15.27%(55.49%↑) 15.21%(-69.69%↑) 15.24%(-7.24%↑) LineVul-ori 26.42% 2.52% 4.61% LineVul-aug-VGX 11.38%(-56.93%↑) 78.00%(2995%↑) 19.86%(330.80%↑) where-orimeansthatthemodelistrainedontheoriginaltraining LineVul-aug-VulGen 9.97%(-62.26%↑) 3.73%(48.01%↑) 5.42%(17.57%↑) setand-aug-VGXmeansthatthemodelistrainedontheaugmented LineVul-aug-SARD 9.19%(-65.21%↑) 85.70%(3300%↑) 16.60%(260.09%↑) IVDetect-ori 9.06% 75.52% 16.18% trainingsetusingVGX’sgeneratedsamples.Weusethemostwidely IVDetect-aug-VGX 13.21%(45.81%↑) 35.66%(-52.78%↑) 19.28%(19.15%↑) adoptedmetricsforthevulnerabilitydetectionmodels,whichare IVDetect-aug-VulGen 7.90%(-12.80%↑) 65.03%(-13.89%↑) 14.09%(-12.92%↑) IVDetect-aug-SARD 10.04%(10.81%↑) 55.94%(-25.92%↑) 17.02%(5.19%↑) precision,recall,andF1,toassesstheimprovement.Wenoticethat theF1scores,whichrepresenttheoverallperformanceofthetools, improveby21.79%,330.80%,and19.15%forDevign,LineVul,and small vulnerability datasets, they are not scalable for our large IVDetect,respectively.ThisindicatesthatVGX’sgenerateddatais datasetintermsofthetimecostandthememoryusage.Thus,we abletoimprovevulnerabilitydetectionsignificantly. use10%ofVGX’sgeneratedsamples(15,039)andVulGen’sgener- WealsodothesameprocesswithVulGen’sgeneratedsamples atedsamples(68,651)toimprovethedownstreammodels.Toshow andSARDsamples.Wenoticethattheimprovementsaremuch thatVGX’sgeneratedsamplesaremorepracticalthantheexisting lowerthantheonewithVGX’sgeneratedsamples(e.g.,17.57%and syntheticsamples,wealsousethesamenumber(15,039)ofsamples 260.09%versus330.80%F1againstLineVul)andtheymayeven fromthewidelyusedsyntheticdatasetSARD[1]toimprovethe decreasetheperformance(e.g.,0.49%and7.24%F1decreaseagainst downstreamtasksforcomparison.Sincetheoriginaltestingsets Devign).Besides,VulGen’sgeneratedsamplesmaybeevenworse ofthesemodelsaresplitfromtheirtrainingsetswhichhavethe thantheSARDsamples.ThereasonisthatVulGen’sgenerated samedistribution,testingthemodelsonthemmaynotshowtheir sampleshavealowsuccessrate(41.33%)forlarge-scaleproduction realperformance[56].Thus,wefollowtheapproachesin[54,55] andthelabelnoiseweakensthedataaugmentationseriously. toleveragetheindependenttestingsetting:foreachdownstream task,weuseathird-partytestingsetthatisfromadifferentsource 5.2.2 Line-LevelVulnerabilityLocalization. Weimprovetwovul- |
fromtheoriginaltrainingsets.Again,weensurethatthereisno nerability localization tools LineVul [28] and LineVD [35] with overlappingbetweenthetrainingsetsandtestingsets. VGX’sgeneratedsamples.TheirtrainingsetisalsoFan[26]men- tionedin§5.2.1.Thus,weusethesameaugmentationsetting.We 5.2.1 Function-LevelVulnerabilityDetection. Weimprovethreevul- againtestthemodelsontheReVealdatasetbecauseitprovidesthe nerabilitydetectors,Devign[71],LineVul[28],andIVDetect[43], vulnerablelinesforthe1,664vulnerablesamples.Table6shows astheyaretheSOTAtoolspubliclyavailableforreplicationexper- theresultsofbeforeandaftertheimprovement.Weadoptthecom- iments.Theoriginaltrainingsetofeachtoolhasvulnerableand monlyusedmetricinLineVulandLineVD,whichistop-10accuracy, non-vulnerablesamples.Toimproveeachtrainingset,weaddthe toevaluatetheimprovement.TheimprovementsbroughtbyVGX’s 15,039generatedsamplesbyVGXandthesameproportionofnon- generatedsamplesare19.31%and12.86%forLineVulandLineVD, vulnerablesamplesfromournormalsamplesetusedtogenerate respectively.Thisindicatesthatthesamplesareusefulforimprov- vulnerabledata.Specifically,thetrainingsetofDevignhas9,744 ingvulnerabilitylocalization.Incomparison,VulGen’sgenerated vulnerableand11,012non-vulnerablesamples,thusweaddVGX’s samplesandSARDsampleshavelowerimprovementscompared 15,039generatedsamplesand16,996non-vulnerablesamplestothe toVGX’sgeneratedsamplesorevendecreaseperformance(9.39% trainingset.BothLineVulandIVDetectusetheFan[26]trainingset and2.07%improvementsforLineVul,respectively;and-11.09%and with10,547vulnerableand168,752non-vulnerablesamples,thus 8.32%improvementsforLineVD,respectively). weaddVGX’s15,039generatedsamplesand240,624non-vulnerable samplestothetrainingsettoimprovethemodels. 5.2.3 Vulnerability Repair. We improve the latest two vulnera- Toleverageindependenttesting,wetestthemodelsontheReVeal bilityrepairtoolsVulRepair[29]andVRepair[20].Bothusethe dataset [19]. It has 1,664 vulnerable and 16,505 non-vulnerable vulnerabilityrepairsamplesfromthecombinationofFan[26]and sampleswhicharemanuallycollectedfromreal-worldprojects. CVEFixes[15],whichconsistof8,482pairsofvulnerableandthere- Table5showstheresultsofthetrainedmodelsofthethreetools, spectivenon-vulnerableprograms,totrainthemodels.WethususeICSE’24,April14–20,2024,Lisbon,Portugal YuNong,RichardFang,GuangbeiYi,KunsongZhao,XiapuLuo,FengChen,andHaipengCai Table 8: Latest CVEs Detected by Improved LineVul but 1 static int hi3660_stub_clk_probe(struct platform_device *pdev){ missedbytheoriginalone. 2 struct device *dev = &pdev->dev; 3 struct resource *res; CVEID Project CWEID CVE-ID Project CWEID 4 stub_clk_chan.cl.dev = dev; 5 stub_clk_chan.mbox = mbox_request_channel(&stub_clk_chan.cl, 0); 2022-46149 Cap’nProto CWE-125 2021-3764 LinuxKernel CWE-401 6 if (IS_ERR(stub_clk_chan.mbox)) return PTR_ERR(stub_clk_chan.mbox); 2023-27478 libmemcached-awesome CWE-200 2022-47938 LinuxKernel CWE-125 7 res = platform_get_resource(pdev, IORESOURCE_MEM, 0); 2022-28388 LinuxKernel CWE-415 2023-23002 LinuxKernel CWE-476 8 if (!res) return -EINVAL; 2023-22996 LinuxKernel CWE-772 2022-42895 LinuxKernel CWE-824 9 freq_reg = devm_ioremap(dev, res->start, resource_size(res)); 2021-3743 LinuxKernel CWE-125 2022-34495 LinuxKernel CWE-415 10 if (!freq_reg) return -ENOMEM; ... 2022-24958 LinuxKernel CWE-763 2022-47520 LinuxKernel CWE-125 11} 2022-30594 LinuxKernel CWE-863 Figure4:AnexamplewhereVGXcorrectlypredictsthestate- ment at Line 8 (marked as cyan), but without value-flow- the15,039pairsofVGX’sgeneratedvulnerableandtherespective basedpositionencodingitwouldincorrectlylocatesLine2 non-vulnerableprogramstoaugmentthetrainingset.Wetestthe (markedasyellow). modelsonthePatchDBdataset[62]becauseitsvulnerabilityrepair samplesarefromreal-worldprojectsandconfirmedbyhumans. Table7showsimprovementresults.Weadoptthecommonlyused 1 static void __del_gref(struct gntalloc_gref *gref){ … settingswherethebeamsearchsizesare1,5,and50andthusthey 2 gref->notify.flags = 0; 3 if (gref->gref_id > 0){ reporttop-1,top-5,top-50accuracy.WithVGX’sgeneratedsam- 4 if (gnttab_query_foreign_access(gref->gref_id)) return; ples,thetop-1,top-5,andtop-50accuracyofVulRepairimproves 5 if (!gnttab_end_foreign_access_ref(gref->gref_id, 0)) return; 6 gnttab_free_grant_reference(gref->gref_id); ... by 146.20%, 146.57%, and 85.02%, respectively. The top-1, top-5, 7 } andtop-50accuracyofVRepairimprovesby70.93%,105.23%,and Figure5:AnexamplewhereVGXsuccessfullyremovethe |
99.30%,respectively.Thisindicatesthatthesamplesarequiteuseful statementatLine6(markedascyan)toinjectamemoryleak toboostvulnerabilityrepair.Incomparison,VulGen’sgenerated vulnerability,butwithoutmanualpatternrefinementvia samplesand SARDsamples bringlowerimprovementsoreven regexitwouldnotbeabletodoso. decreasetheperformance(e.g.,9.85%and5.46%improvementsfor VulRepair’sTop-50accuracy,respectively;and62.99%and-42.45% forVRepair’sTop-50accuracy,respectively). anddevice,whichappearedonvulnerablestatementsofsome 5.3 RQ6:Real-WorldVulnerabilityDiscovery trainingsamples,butthatstatementhasnothingtodowithinject- ingavulnerabilityasperthecodesemanticshere.VGXtakesthe Wescrapedthelatest71vulnerabilitiescovering17CWEsfrom advantageofthevalue-flow-basedpositionencodingwhichmakes 6criticalsoftwareprojects(e.g.,Linuxkernel)reportedbetween themodelsemantics-awarehencebettercontextualizationperfor- 2021-2023,fromtheCVE/NVDdatabase[50].WeuseLineVulasit mance,overcomingLimitation○2 forvulnerabilitygeneration. isthelatestavailablevulnerabilitydetector.Table8showsthelatest Manualpatternrefinementwithregexmakesthepatterns vulnerabilitiesdetectedbytheLineVulmodelimprovedbyVGX’s necessarilygeneralhencemoreuseful.Figure5showsanex- generatedsamplesbutcannotbedetectedbytheoriginalone.The amplewhereVGXsuccessfullyremovesthestatementatLine6 improved LineVul found 13 more CVEs, indicating its enhanced (markedascyan)toinjecta“memoryleak(CWE-401)"vulnera- potentialfordiscoveringreal-worldzero-dayvulnerabilities. bilitybuttheonewithoutmanualpatternrefinementviaregex 6 DISCUSSION cannot.Thereasonisthatthisprogramusesaself-definedfree functiontoreleasethepointer.Thus,thepatternsminedthrough In this section, we discuss why VGX has good performance on anti-unificationmaynotcoverthefunctionnameofthisfree generatingvulnerabilitydataandwhythegeneratedsamplesby function.Theuseofself-definedfunctionsrelatedtomemoryallo- VGXeffectivelyimprovetheperformanceofdownstreamtasks. cation,memoryinitialization,memoryrelease,safetycheck,and multi-threadingmanagementarecommonbasedonourmanualin- 6.1 VulnerabilityGenerationPerformance spection.Thus,ourmanuallyaddededitpatternswithregexshown Asdiscussedin§3,thekeydesignsofVGXaresemantics-aware inTable1maketheeditpatternsnecessarilymoregeneral,improv- contextualizationandhuman-knowledge-enhancededitpatternsfor- ingtheperformanceofVGXforvulnerabilitygeneration,which mation.WedissectVGX’sperformancemeritsfromtheseaspects. effectivelyovercomesLimitation○1 forvulnerabilitygeneration. Thevalue-flow-basedpositionencodingmakesthecontex- Patterndiversificationmakesthepatternsmorediverse tualizationsemantics-aware.Figure4showsanexamplewhere hencemoreapplicable.Figure6showsanexamplewhereVGX VGXcorrectlypredictsthevulnerabilityinjectionlocationduetoits successfullyinjectsaCWE-20vulnerabilityduetoitspatterndi- value-flow-basedpositionencoding.Thereasonisthatthisencod- versification.Thereasonisthattheinputvalidationcheckingat ingexplicitlyenhancestheattentionbetweenvariablesthathave Line4maybeverydifferentindifferentprograms.Itisdifficultfor valueflowrelationships.Forexample,inthecaseshowninthefig- thepatternsextractedfromexistingexamplestocoverallofthem. ure,thevariablereshasvalueflowsfrompdev,IORESOURCE_- Yetbasedonourhumanknowledge,thereturnvalue-EINVAL MEM.Thesevariablesarehighlyrelatedtovulnerabilityinjection. hasindicatedthatthisisavaluevalidationchecking.Thus,we Thus,whiletheyarenotinthestatementtobelocated,VGXpays buildpatternmutationrules(Table2Row4)suchthatoncesuch moreattentiontothesevariableswhenlocatingthecorrectstate- returnerrorvaluesareintheifstatement,wedonotneedto ment.However,theonewithoutvalue-flow-basedpositionencod- matchtheconditionanymore.Therefore,thepatterndiversifica- ingsimplylocatesLine2becauseithasthetokensdev, pdev, tionintegratesourhumanknowledge,makingtheeditpatternsVGX:Large-ScaleSampleGenerationforBoostingLearning-BasedSoftwareVulnerabilityAnalyses ICSE’24,April14–20,2024,Lisbon,Portugal 1 int vrend_create_vertex_elements_state(…,unsigned num_elements,…){ itbyusingmanuallyconfirmedreal-worlddatasetlikeCVE/NVD 2 struct vrend_vertex_element_array *v = CALLOC_STRUCT(…); 3 if (!v) return ENOMEM; andremovinganydatasetoverlapsduringevaluation. 4 if (num_elements > PIPE_MAX_ATTRIBS) return -EINVAL; 5 v->count = num_elements; 8 RELATEDWORK 6 ... 7 } Vulnerabilitydatasetcuration.SARD[1]andSATEIV[57]are Figure6:AnexamplewhereVGXsuccessfullyremovetheif syntheticdatasetscontaining60K+vulnerabilitysamples,while statementatLine4(markedascyan)toinjectanimproper BigVul[26]andCVEFixes[15]arereal-worlddatasetscontaining inputvalidation(CWE-20)vulnerability,butwithoutpattern muchless(<10K)samples.FixReverter[68]usesmanuallyderived mutationitwouldnotbeabletoinjectcorrectly. patternstoinjectvulnerabilitiestoexistingcode.VulGen[55]in- |
jectsvulnerabilitiesbyaddressingwhereandhowtoinjectsepa- morediverseandapplicablehenceimprovingVGXforvulnerability rately.However,thelabelprecisionofthesegenerateddatasets generation,overcomingLimitation○1 ofpeerapproaches. islow.Incontrast,VGXisthemostaccuratewith>90%precision. Apocalypse[60]usesformaltechniquestoautomaticallyinjectbugs 6.2 UsefulnessofGeneratedSamples inlargesoftwarecodebases.Fuzzle[37]synthesizesbuggypro- gramsbyencodingmovesinamazeaschainsoffunctioncalls.In In§5,weshowthatVGX-generatedsamplesarehigh-qualityand comparison,VGXleveragesvalue-flow-baseddeeprepresentation thusareeffectiveforimprovingvariousdownstreamvulnerability learningandhumanknowledgeforvulnerabilityinjection. analysistasks.Specifically,ourgeneratedsampleshavemeritsin Source-codepre-training.Deeplearningmodelpre-training fourmainaspectsofhighdatasetquality: Datasetsize.Trainingdatasetsizeiscrucialfortrainingadeep hasbeenwidelyemployed.BERT[24]isapre-trainedmodelfor naturallanguages.CodeBERT[27],CodeT5[63],andSPT-Code[51] learningmodelwell.AlmostalltheDL-basedcodeanalysistech- borrowtheideafromBERTtopre-trainmodelsforprogramming niquesusemorethan10,000samplestotrainthemodels[16].How- languages.Incontrast,VGX’spre-trainingistask-specific,explicitly ever,previousworks[54,55]likeVulGencanonlygenerateasmall gearedtowardourfine-tuningtaskforvulnerabilityinjection. numberofvulnerabilitysamples(e.g.,<1,000)ortheirqualityplum- Humanknowledgeintegration.Integratinghumanknowl- mets.Incontrast,VGXcangeneratelarge-scalequalityvulnerability edge into learning-based approaches has been explored. Liu et samplesinashorttime.Thelargenumberofgeneratedsamples al.[48]combineGNNwithhumanknowledgetodetectsmartcon- allowstheDLmodeltolearnrelevantknowledgeingeneral. Complexity.Somepreviousvulnerabilityanalysesusesynthetic tractvulnerabilities.ComNet.[32]integrateshumanknowledge intoDLtoimproveorthogonalreceivers.DATGAN[36]integrates datasetstotraintheirmodels[45,46].However,syntheticsamples DLwithexpertknowledgetogeneratetabulardata.Incompari- areusuallyverysimpleandmakethetrainedmodelsnotgeneraliz- son,VGXintegrateshumanknowledgeintovulnerabilityinjection abletoreal-worldvulnerabilityanalysis[19].Thisisalsoconfirmed patternstoboostvulnerabilitygeneration. inourexperimentsin§5.2.Incontrast,VGX’sgeneratedsamples arebasedonreal-worldnormalsamples,thusthegeneratedsam- 9 CONCLUSION plesareascomplexasreal-worldvulnerabilitydataandensurethe modellearnstheknowledgeforchallengingvulnerabilityanalysis. WepresentedVGX,anoveltechniqueforlarge-scalegeneration Noise. Another important aspect of the usefulness is noise. ofhigh-qualityvulnerableprogramsamples.VGXgeneratessuch WhileVulGen[55]cangeneratevulnerablesamples,thesuccess samplesusingvulnerability-introducingcodeeditpatterns.These rateislow(41.33%),makingthesamplesunreadytouse.Incontrast, patternsareinitiallyextractedfromreal-worldvulnerabilityfixes, VGX’sgeneratedsamplesachievea90.13%successrate,whichcan augmentedbymanuallydefinedadditionalpatterns,anddiversi- beusedtoimprovethemodeltrainingofdownstreamtasksdirectly. fiedthroughmanuallyderivedpatternmutationrulesaccordingto Diversity.Previousworks[67,68]onlygenerateoneorafew humanknowledgeaboutreal-worldvulnerabilities.VGX’sdesign numbertypesofvulnerabilities,whichcannottrainvulnerability alsofeaturesasemantics-awarecontextualizationTransformerto analysismodelsingeneral.Incontrast,VGXisalreadyabletogen- identifyrightinjectioncontexts,whichiscustomizedbyvalue-flow- eratevulnerabilitysamplesofdiversetypes(CWEs)whilespanning basedpositionencodingandpre-trainedagainstnewobjectivesto avarietyof(238)projects,makingitsaugmentedmodeltraining facilitatelearningsyntacticandcontextualstructuresofcode.With fordownstreamvulnerabilityanalysiseffective. thisnoveldesign,VGXlargelyoutperformsallofthestate-of-the- artpeerapproachesintermsofthequalityofgeneratedsamples.We 7 THREATSTOVALIDITY alsocontributealargevulnerabilitydatasetresultingfromVGX’s in-the-wildsampleproduction.Wefurtherdemonstratedtheprac- ApossiblethreattointernalvalidityisthatVGXmayhaveimple- ticalusefulnessofthisdatasetviathesubstantialimprovementit mentationerrors.Wemitigateitbyinspectingcodecarefully,doing broughttovulnerabilitydetection,localization,andrepair,andits unittestingwhenimplementingeachmodule,andusingasmall abilitytohelpfindmorereal-worldvulnerabilities(CVEs). datasettotestbeforeofficialexperiments.Anotherthreatisthat themanualinspectionforthesuccesssamplesmaybeinaccurate. ACKNOWLEDGMENT We mitigate it by writing exploits for some of the samples and confirmingresultsbymultipleauthorsviacrossvalidation. Wethankthereviewersfortheirconstructivecomments,which Themainexternalvaliditythreatisthatthedatasetweusemay helpedusimproveourpaper.Thisresearchwassupportedbythe |
notrepresentreal-worldvulnerabilitydatadistribution.Wemitigate ArmyResearchOffice(ARO)throughgrantW911NF-21-1-0027.ICSE’24,April14–20,2024,Lisbon,Portugal YuNong,RichardFang,GuangbeiYi,KunsongZhao,XiapuLuo,FengChen,andHaipengCai REFERENCES [28] MichaelFuandChakkritTantithamthavorn.2022.LineVul:atransformer-based [1] 2017.SARD:ASoftwareAssuranceReferenceDataset.https://samate.nist.gov/ line-levelvulnerabilityprediction.InProceedingsofthe19thInternationalConfer- SARD/. enceonMiningSoftwareRepositories(MSR).608–620. [2] 2022. 2022CWETop25MostDangerousSoftwareWeaknesses. https:// [29] MichaelFu,ChakkritTantithamthavorn,TrungLe,VanNguyen,andDinhPhung. cwe.mitre.org/top25/archive/2022/2022_cwe_top25.html. 2022. VulRepair:aT5-basedautomatedsoftwarevulnerabilityrepair.InPro- [3] 2022. CVE-2017-12991. https://github.com/the-tcpdump-group/tcpdump/ ceedingsofthe30thACMJointEuropeanSoftwareEngineeringConferenceand commit/50a44b6b8e4f7c127440dbd4239cf571945cc1e7. SymposiumontheFoundationsofSoftwareEngineering(ESEC/FSE).935–947. [4] 2022.MemoryLeak.https://cwe.mitre.org/data/definitions/401.html. [30] XiaoqinFuandHaipengCai.2019. Adynamictaintanalyzerfordistributed [5] 2022. OpenBSD. https://github.com/bukhalo/openbsd-src/commit/ systems.InProceedingsofthe201927thACMJointMeetingonEuropeanSoftware a88c32bfabe8a7fd0b25703230d4adba1d204e0a. EngineeringConferenceandSymposiumontheFoundationsofSoftwareEngineering. [6] 2022.RaceCondition.https://cwe.mitre.org/data/definitions/362.html. 1115–1119. [7] 2022. RawStudio. https://github.com/rawstudio/rawstudio/commit/ [31] XiaoqinFuandHaipengCai.2021. FlowDist:Multi-StagedRefinement-Based 04cf4f537ffdce5f3e5207bead0ac2d254114cc2. DynamicInformationFlowAnalysisforDistributedSoftwareSystems.In30th [8] 2022. UseofUninitializedVariables. https://cwe.mitre.org/data/definitions/ USENIXSecuritySymposium(USENIXSecurity21).2093–2110. 457.html. [32] XuanxuanGao,ShiJin,Chao-KaiWen,andGeoffreyYeLi.2018. ComNet: [9] 2023. Cybersecurity vulnerability statistics and facts of 2023. CombinationofdeeplearningandexpertknowledgeinOFDMreceivers.IEEE https://www.comparitech.com/blog/information-security/cybersecurity- CommunicationsLetters22,12(2018),2627–2630. vulnerability-statistics/. [33] DayaGuo,ShuoRen,ShuaiLu,ZhangyinFeng,DuyuTang,LIUShujie,Long [10] 2023. Data Quality Considerations for Machine Learning Models. Zhou,NanDuan,AlexeySvyatkovskiy,ShengyuFu,etal.2020.GraphCodeBERT: https://towardsdatascience.com/data-quality-considerations-for-machine- Pre-trainingCodeRepresentationswithDataFlow.InInternationalConference learning-models-dcbe9cab34cb. onLearningRepresentations(ICLR). [11] 2023. HowMuchDataIsNeededForMachineLearning? https://graphite- [34] JacobAHarer,OnurOzdemir,TomoLazovich,ChristopherPReale,RebeccaL note.com/how-much-data-is-needed-for-machine-learning. Russell,LouisYKim,andPeterChin.2018.Learningtorepairsoftwarevulnerabil- [12] 2023.TheSizeandQualityofaDataSet.https://developers.google.com/machine- itieswithgenerativeadversarialnetworks.InProceedingsofthe32ndInternational learning/data-prep/construct/collect/data-size-quality. ConferenceonNeuralInformationProcessingSystems.7944–7954. [13] HiralalAgrawal,RichardADeMillo,R_Hathaway,WilliamHsu,WynneHsu, [35] DavidHin,AndreyKan,HuamingChen,andMAliBabar.2022. LineVD: EdwardWKrauser,RhondaJMartin,AdityaPMathur,andEugeneSpafford. statement-levelvulnerabilitydetectionusinggraphneuralnetworks.InPro- 1989. DesignofmutantoperatorsfortheCprogramminglanguage. Technical ceedingsofthe19thInternationalConferenceonMiningSoftwareRepositories Report.TechnicalReportSERC-TR-41-P,SoftwareEngineeringResearchCenter, (MSR).596–607. Purdue. [36] GaelLederrey,TimHillel,andMichelBierlaire.2022. DATGAN:Integrating [14] JohannesBader,AndrewScott,MichaelPradel,andSatishChandra.2019.Getafix: expertknowledgeintodeeplearningforsynthetictabulardata.arXivpreprint Learningtofixbugsautomatically. ProceedingsoftheACMonProgramming arXiv:2203.03489(2022). Languages3,OOPSLA(2019),1–27. [37] HaeunLee,SoominKim,andSangKilCha.2022. Fuzzle:MakingaPuzzle [15] GuruBhandari,AmaraNaseer,andLeonMoonen.2021.CVEfixes:automated forFuzzers.InProceedingsofthe37thIEEE/ACMInternationalConferenceon collectionofvulnerabilitiesandtheirfixesfromopen-sourcesoftware.InProceed- AutomatedSoftwareEngineering.1–12. ingsofthe17thInternationalConferenceonPredictiveModelsandDataAnalytics [38] WenLi,LiLi,andHaipengCai.2022.Onthevulnerabilitypronenessofmultilin- inSoftwareEngineering(PROMISE).30–39. gualcode.InProceedingsofthe30thACMJointEuropeanSoftwareEngineering [16] YingzhouBi,JiangtaoHuang,PenghuiLiu,andLianmeiWang.2023. Bench- ConferenceandSymposiumontheFoundationsofSoftwareEngineering(ESEC/FSE). |
markingSoftwareVulnerabilityDetectionTechniques:ASurvey.arXivpreprint 847–859. arXiv:2303.16362(2023). [39] WenLi,LiLi,andHaipengCai.2022. PolyFax:atoolkitforcharacterizing [17] PiotrBojanowski,ÉdouardGrave,ArmandJoulin,andTomášMikolov.2017.En- multi-languagesoftware.InProceedingsofthe30thACMJointEuropeanSoftware richingWordVectorswithSubwordInformation.TransactionsoftheAssociation EngineeringConferenceandSymposiumontheFoundationsofSoftwareEngineering forComputationalLinguistics5(2017),135–146. (ESEC/FSE-Demo).1662–1666. [18] HaipengCai,YuNong,YuzheOu,andFengChen.2023.GeneratingVulnerable [40] WenLi,JiangMing,XiapuLuo,andHaipengCai.2022.{PolyCruise}:A{Cross- CodeviaLearning-BasedProgramTransformations.InAIEmbeddedAssurance Language}DynamicInformationFlowAnalysis.In31stUSENIXSecuritySympo- forCyberSystems.Springer,123–138. sium(USENIXSecurity22).2513–2530. [19] SaikatChakraborty,RahulKrishna,YangruiboDing,andBaishakhiRay.2022. [41] WenLi,JinyangRuan,GuangbeiYi,LongCheng,XiapuLuo,andHaipengCai. DeepLearningBasedVulnerabilityDetection:AreWeThereYet?IEEETransac- 2023.PolyFuzz:HolisticGreyboxFuzzingofMulti-LanguageSystems.In32nd tionsonSoftwareEngineering48,09(2022),3280–3296. USENIXSecuritySymposium(USENIXSecurity23).1379–1396. [20] ZiminChen,SteveKommrusch,andMartinMonperrus.2022.Neuraltransfer [42] WenLi,HaoranYang,XiapuLuo,LongCheng,andHaipengCai.2023.PyRTFuzz: learningforrepairingsecurityvulnerabilitiesinccode. IEEETransactionson DetectingBugsinPythonRuntimesviaTwo-LevelCollaborativeFuzzing.In SoftwareEngineering49,1(2022),147–165. Proceedingsofthe2023ACMSIGSACConferenceonComputerandCommunications [21] JunyoungChung,CaglarGulcehre,KyungHyunCho,andYoshuaBengio.2014. Security.1645–1659. Empiricalevaluationofgatedrecurrentneuralnetworksonsequencemodeling. [43] YiLi,ShaohuaWang,andTienNNguyen.2021.Vulnerabilitydetectionwith arXivpreprintarXiv:1412.3555(2014). fine-grainedinterpretations.InProceedingsofthe29thACMJointMeetingon EuropeanSoftwareEngineeringConferenceandSymposiumontheFoundationsof [22] MichaelLCollard,MichaelJohnDecker,andJonathanIMaletic.2013.srcML:An infrastructurefortheexploration,analysis,andmanipulationofsourcecode:A SoftwareEngineering.292–303. tooldemonstration.In2013IEEEInternationalConferenceonSoftwareMaintenance. [44] ZhenLi,DeqingZou,ShouhuaiXu,ZhaoxuanChen,YaweiZhu,andHaiJin. 516–519. 2021.Vuldeelocator:adeeplearning-basedfine-grainedvulnerabilitydetector. [23] RolandCroft,MAliBabar,andMMehdiKholoosi.2023.Dataqualityforsoftware IEEETransactionsonDependableandSecureComputing19,4(2021),2821–2837. vulnerabilitydatasets.In2023IEEE/ACM45thInternationalConferenceonSoftware [45] ZhenLi,DeqingZou,ShouhuaiXu,HaiJin,YaweiZhu,andZhaoxuanChen.2021. Engineering(ICSE).IEEE,121–133. SySeVR:Aframeworkforusingdeeplearningtodetectsoftwarevulnerabilities. [24] JacobDevlin,Ming-WeiChang,KentonLee,andKristinaToutanova.2018.Bert: IEEETransactionsonDependableandSecureComputing19,4(2021),2244–2258. Pre-trainingofdeepbidirectionaltransformersforlanguageunderstanding.arXiv [46] ZhenLi,DeqingZou,ShouhuaiXu,XinyuOu,HaiJin,SujuanWang,Zhijun preprintarXiv:1810.04805(2018). Deng,andYuyiZhong.2018. Vuldeepecker:Adeeplearning-basedsystem [25] ElizabethDinella,HanjunDai,ZiyangLi,MayurNaik,LeSong,andKeWang. forvulnerabilitydetection.InNetworkandDistributedSystemSecurity(NDSS) 2020.Hoppity:Learninggraphtransformationstodetectandfixbugsinprograms. Symposium. InInternationalConferenceonLearningRepresentations(ICLR). [47] LinusEriksson.2022.Tree-Sitter.https://github.com/tree-sitter/tree-sitter. [26] JiahaoFan,YiLi,ShaohuaWang,andTienNNguyen.2020. AC/C++Code [48] ZhenguangLiu,PengQian,XiaoyangWang,YuanZhuang,LinQiu,andXun VulnerabilityDatasetwithCodeChangesandCVESummaries.InProceedingsof Wang.2023. CombiningGraphNeuralNetworksWithExpertKnowledgefor the17thInternationalConferenceonMiningSoftwareRepositories(MSR).508–512. SmartContractVulnerabilityDetection.IEEETransactionsonKnowledge&Data [27] ZhangyinFeng,DayaGuo,DuyuTang,NanDuan,XiaochengFeng,MingGong, Engineering35,02(2023),1296–1310. LinjunShou,BingQin,TingLiu,DaxinJiang,etal.2020. CodeBERT:APre- [49] YisroelMirsky,GeorgeMacon,MichaelBrown,CarterYagemann,Matthew TrainedModelforProgrammingandNaturalLanguages.InFindingsoftheAsso- Pruett,EvanDowning,SukarnoMertoguno,andWenkeLee.2023.VulChecker: ciationforComputationalLinguistics:EMNLP2020.1536–1547. Graph-basedVulnerabilityLocalizationinSourceCode.InUSENIXSecurity Symposium. [50] NationalInstituteofStandardsandTechnology(NIST).2022.NationalVulnera- |
bilityDatabase(NVD).https://nvd.nist.gov.VGX:Large-ScaleSampleGenerationforBoostingLearning-BasedSoftwareVulnerabilityAnalyses ICSE’24,April14–20,2024,Lisbon,Portugal [51] ChanganNiu,ChuanyiLi,VincentNg,JidongGe,LiguoHuang,andBinLuo. [62] XindaWang,ShuWang,PengbinFeng,KunSun,andSushilJajodia.2021.Patchdb: 2022. SPT-code:sequence-to-sequencepre-trainingforlearningsourcecode Alarge-scalesecuritypatchdataset.In202151stAnnualIEEE/IFIPInternational representations.InProceedingsofthe44thInternationalConferenceonSoftware ConferenceonDependableSystemsandNetworks(DSN).149–160. Engineering(ICSE).2006–2018. [63] YueWang,WeishiWang,ShafiqJoty,andStevenCHHoi.2021.CodeT5:Identifier- [52] YuNongandHaipengCai.2020.Apreliminarystudyonopen-sourcememory awareUnifiedPre-trainedEncoder-DecoderModelsforCodeUnderstandingand vulnerabilitydetectors.In2020IEEE27thInternationalConferenceonSoftware Generation.InProceedingsofthe2021ConferenceonEmpiricalMethodsinNatural Analysis,EvolutionandReengineering(SANER).IEEE,557–561. LanguageProcessing.8696–8708. [53] YuNong,HaipengCai,PengfeiYe,LiLi,andFengChen.2021. Evaluating [64] YuemingWu,DeqingZou,ShihanDou,WeiYang,DuoXu,andHaiJin.2022.Vul- andcomparingmemoryerrorvulnerabilitydetectors.InformationandSoftware CNN:Animage-inspiredscalablevulnerabilitydetectionsystem.InProceedings Technology137(2021),106614. ofthe44thInternationalConferenceonSoftwareEngineering.2365–2376. [54] YuNong,YuzheOu,MichaelPradel,FengChen,andHaipengCai.2022.Gen- [65] ZiyuYao,FrankFXu,PengchengYin,HuanSun,andGrahamNeubig.2021. eratingrealisticvulnerabilitiesvianeuralcodeediting:anempiricalstudy.In LearningStructuralEditsviaIncrementalTreeTransformations.InInternational Proceedingsofthe30thACMJointEuropeanSoftwareEngineeringConferenceand ConferenceonLearningRepresentations(ICLR). SymposiumontheFoundationsofSoftwareEngineering.1097–1109. [66] LechenYu,JoachimProtze,OscarHernandez,andVivekSarkar.2020.AStudy [55] YuNong,YuzheOu,MichaelPradel,FengChen,andHaipengCai.2023.VulGen: ofMemoryAnomaliesinOpenMPApplications.InInternationalWorkshopon RealisticVulnerabilityGenerationViaPatternMiningandDeepLearning.In OpenMP.Springer,328–342. 2023IEEE/ACM45thInternationalConferenceonSoftwareEngineering(ICSE). [67] ShashaZhang.2021. AFrameworkofVulnerableCodeDatasetGeneration 2527–2539. byOpen-SourceInjection.In2021IEEEInternationalConferenceonArtificial [56] YuNong,RainySharma,AbdelwahabHamou-Lhadj,XiapuLuo,andHaipeng IntelligenceandComputerApplications(ICAICA).1099–1103. Cai.2022.Openscienceinsoftwareengineering:Astudyondeeplearning-based [68] ZenongZhang,ZachPatterson,MichaelHicks,andShiyiWei.2022. FIXRE- vulnerabilitydetection.IEEETransactionsonSoftwareEngineering49,4(2022), VERTER:ARealisticBugInjectionMethodologyforBenchmarkingFuzzTesting. 1983–2005. In31stUSENIXSecuritySymposium(USENIXSecurity22).3699–3715. [57] VadimOkun,AurelienDelaitre,PaulEBlack,etal.2013. Reportonthestatic [69] YunhuiZheng,SaurabhPujar,BurnLewis,LucaBuratti,EdwardEpstein,Bo analysistoolexposition(sate)iv.NISTSpecialPublication500(2013),297. Yang,JimLaredo,AlessandroMorari,andZhongSu.2021. D2A:Adataset [58] HanPeng,GeLi,WenhanWang,YunfeiZhao,andZhiJin.2021. Integrating builtforai-basedvulnerabilitydetectionmethodsusingdifferentialanalysis.In treepathintransformerforcoderepresentation.AdvancesinNeuralInformation 2021IEEE/ACM43rdInternationalConferenceonSoftwareEngineering:Software ProcessingSystems34(2021),9343–9354. EngineeringinPractice(ICSE-SEIP).111–120. [59] RuchirPuri,DavidSKung,GeertJanssen,WeiZhang,GiacomoDomeniconi, [70] XinZhouandRakeshMVerma.2022.VulnerabilityDetectionviaMultimodal VladimirZolotov,JulianDolby,JieChen,MihirChoudhury,LindseyDecker,etal. Learning:DatasetsandAnalysis.InProceedingsofthe2022ACMonAsiaConfer- 2021.CodeNet:ALarge-ScaleAIforCodeDatasetforLearningaDiversityof enceonComputerandCommunicationsSecurity(AsiaCCS).1225–1227. CodingTasks.InThirty-fifthConferenceonNeuralInformationProcessingSystems [71] YaqinZhou,ShangqingLiu,JingkaiSiow,XiaoningDu,andYangLiu.2019. DatasetsandBenchmarksTrack(Round2). Devign:effectivevulnerabilityidentificationbylearningcomprehensiveprogram [60] SubhajitRoy,AwanishPandey,BrendanDolan-Gavitt,andYuHu.2018. Bug semanticsviagraphneuralnetworks.InProceedingsofthe33rdInternational synthesis:Challengingbug-findingtoolswithdeepfaults.InProceedingsofthe ConferenceonNeuralInformationProcessingSystems.10197–10207. 201826thACMJointMeetingonEuropeanSoftwareEngineeringConferenceand [72] DeqingZou,YutaoHu,WenkeLi,YuemingWu,HaojunZhao,andHaiJin. SymposiumontheFoundationsofSoftwareEngineering.224–234. 2022. mVulPreter:AMulti-GranularityVulnerabilityDetectionSystemWith [61] CarsonDSestili,WilliamSSnavely,andNathanMVanHoudnos.2018.Towards Interpretations.IEEETransactionsonDependableandSecureComputing(TDSC) |
2310.18532 SkipAnalyzer: A Tool for Static Code Analysis with Large Language Models Mohammad Mahdi Mohajer∗, Reem Aleithan†, Nima Shiri Harzevili‡, Moshi Wei§, Alvine Boaye Belle¶, Hung Viet Pham∥, Song Wang∗∗ Lassonde School of Engineering, York University Toronto, Ontario, Canada {∗mmm98,†reem1100,‡nshiri, §moshiwei,∥hvpham,∗∗wangsong}@yorku.ca; ¶alvine.belle@lassonde.yorku.ca Abstract—WeintroduceSkipAnalyzer,alargelanguagemodel time-consuming and labor-intensive process [8]. Additionally, (LLM)-powered tool for static code analysis. It can detect bugs, these detected bugs still require manual fixes, demanding filterfalsepositivewarnings,andpatchthedetectedbugswithout developers’expertiseandknowledge,whichcanbearesource- human intervention. SkipAnalyzer consists of three components, intensive task [9], [10]. 1) an LLM-based static bug detector that scans source code and reports specific types of bugs, 2) an LLM-based false- Recently, Large Language Models (LLMs) such as Chat- positive filter that can identify false-positive bugs in the results GPT have demonstrated significant potential in various rea- of static bug detectors (e.g., the result of step 1) to improve soning and decision-making roles, serving as intelligent detection accuracy, and 3) an LLM-based patch generator that agents [11], [12], especially in SE tasks such as code genera- cangeneratepatchesforthedetectedbugsabove.Asaproof-of- tion, understanding, and debugging. However, to date, there concept,SkipAnalyzerisbuiltonChatGPT,whichhasexhibited outstanding performance in various software engineering tasks. has yet to be research exploring the capabilities of LLM- ToevaluateSkipAnalyzer,wefocusontwotypesoftypicaland based tools for various static code analysis tasks. To address critical bugs that are targeted by static bug detection, i.e., Null this gap, in this paper, we take a step toward developing a DereferenceandResourceLeakasoursubjects.WeemployInfer tool for code analysis based on LLMs named SkipAnalyzer. to aid the gathering of these two bug types from 10 open-source It contains three components: 1) an LLM-based static bug projects. Consequently, our experiment dataset contains 222 detector that is capable of scanning source code and reporting instances of Null Dereference bugs and 46 instances of Resource Leak bugs. Our study demonstrates that SkipAnalyzer achieves specific types of bugs, 2) an LLM-based false-positive filter remarkable performance in the mentioned static analysis tasks, for identifying false-positive bugs (e.g., those from step 1) to includingbugdetection,false-positivewarningremoval,andbug improve the detection accuracy, and 3) an LLM-based patch repair. In static bug detection, SkipAnalyzer achieves accuracy generator that can generate patches for the detected bugs. values of up to 68.37% for detecting Null Dereference bugs and As a proof-of-concept, SkipAnalyzer is built on ChatGPT, 76.95%fordetectingResourceLeakbugs,improvingtheprecision ofthecurrentleadingbugdetector,Inferby12.86%and43.13% which has consistently demonstrated outstanding performance respectively. For removing false-positive warnings, SkipAnalyzer in various software engineering tasks [13]. canreachaprecisionofupto93.88%forNullDereferencebugs ToevaluateSkipAnalyzer,weselecttwotypicalandwidely- and 63.33% for Resource Leak bugs. Additionally, SkipAnalyzer studied bugs commonly targeted by static bug detection: Null surpasses state-of-the-art false-positive warning removal tools. Dereference and Resource Leak as our subjects. Following Furthermore,inbugrepair,SkipAnalyzercangeneratesyntacti- cally correct patches to fix its detected bugs with a success rate existing works [14], [15], we utilize Infer to facilitate the of up to 97.30%. collection of these two types of bugs from 10 open-source IndexTerms—Staticanalysis,ChatGPT,Largelanguagemod- projects. As a result, our experiment dataset includes 222 els NullDereferencebugsand46ResourceLeak bugs.Whenem- ploying ChatGPT, we leverage two different model versions: I. INTRODUCTION 1) ChatGPT-3.5 Turbo and 2) ChatGPT-4. In this study, we Numerousstaticcodeanalysistechniqueshavebeenutilized adhere to the best practices of prompt engineering [16], [17] in the literature for the automatic detection of real-world and create precise and context-aware prompts to effectively softwarebugs[1]–[5].Thesetoolstypicallyrelyonpredefined harness the language models’ capabilities. We explore vari- heuristicrulestoscanandanalyzethecodebasesorbinariesof ous prompting strategies, including zero-shot, one-shot, and software projects [3]–[5]. During this analysis, any violations few-shot prompting, to evaluate the performance of different of these rules are categorized as a bug, leading the tools ChatGPT models across various scenarios. By strategically to flag the corresponding code artifact, such as a line or adapting our prompts and methodologies, we aim to identify a group of lines, as buggy. However, employing static bug the most efficient and accurate ways of leveraging LLMs in detectors presents specific challenges. One primary issue is static analysis. thatmoststaticbugdetectorsgeneratenumerousfalse-positive OurexperimentsrevealthatSkipAnalyzerachievesremark- warnings [6], [7]. Consequently, additional manual review is able performance with significant improvements when com- essential to validate the reported potential bugs, resulting in a pared to previous baseline methods for each respective task: 3202 ceD 81 |
]ES.sc[ 2v23581.0132:viXra1) Its LLM-based static bug detector achieves a precision rate methods have been created to perform static bug detection that is 12.86% higher for Null Dereference bugs and 43.13% within the body of research and industry [22]. Infer, created higherforResourceLeakbugscomparedtoInfer.2)ItsLLM- byMeta,isastaticbugdetectiontoolcapableofbeingutilized basedfalse-positivefiltercanenhanceInfer’sprecisionrateby across various programming languages, including Java, C, 28.68% for Null Dereference bugs and 9.53% for Resource C++, Objective-C, and C#. It accomplishes this by utilizing Leak bugs, surpassing the performance of existing baselines. a predetermined set of rules to identify potential bugs and Additionally, it can enhance the precision of SkipAnalyzer’s conducting inter-procedural analysis as part of the project first component by 16.31% for Null Dereference bugs. 3) compilationprocess[23].SpotBugs[24],anenhancediteration Its LLM-based patch generator can generate patches for the of findBugs [25], [26], employs a methodology similar to buggycodesandrepairthemwithcorrectnessratesof97.30% Infer. It leverages the concept of bug patterns, which consist and 91.77% for Null Dereference and Resource Leak bugs, of specific rules and templates designed to identify particular respectively.Furthermore,onaverage,98.77%ofthegenerated types of bugs. That being said, applying SpotBugs is limited code for both Null Dereference and Resource Leak bugs are only to Java byte codes and does not support other lan- syntactically correct. guages’ source codes or binaries. Google has also introduced As a summary, this paper contributes to the field in the ErrorProne, a static bug detector tailored for Java programs following ways: [27]. ErrorProne is designed to catch common programming • WeproposeSkipAnalyzer,alargelanguagemodel(LLM) errors and potential bugs during compilation. It enhances the poweredtoolforstaticcodeanalysisthatcandetectbugs, compiler’stypeanalysis,enablingdeveloperstoidentifymore filterfalsepositivewarnings,andpatchthedetectedbugs mistakes before advancing to production. In this study, we without human intervention. employInferasabaselineforcomparisonwithSkipAnalyzer’s • WeshowthatSkipAnalyzercanbeaneffectivestaticbug firstcomponentandasthetoolforgeneratingwarningsforour detector, improving the base results of the current state- data collection. of-the-art tool, Infer. B. False-Positive Warning Removal • We demonstrate that SkipAnalyzer can effectively elimi- natefalse-positivewarningsfromtheoutputofstaticbug A significant issue associated with the use of static bug detectors such as Infer and its first component, thereby detectors is their tendency to generate a considerable volume enhancingtheirprecisionandsurpassingtheperformance of inaccurate warnings, which are essentially alerts that are of existing baseline methods in false-positive warning not genuine indicators of actual bugs [14], [28]–[34]. Recent removal. research demonstrates that the false-positive warning rate • We illustrate that SkipAnalyzer exhibits the capability to can escalate to as high as 91% [28]. Also, removing high repair bugs identified by static bug detectors through the false positive warnings in static analysis tools is very time- generationofaccuratepatches,whichwecompareagainst consuming for developers since it requires them to verify the a baseline approach from prior research. generatedwarningsmanually,anditoftenresultsinfrustration • We release the dataset and the source code for our anddiminishedutilizationofthesetools[35],[36].Therefore, experiments for future usages1. exploring strategies for reducing false positive warnings in static bug detectors is crucial to increasing the developer’s The structure of the remainder of this paper is as follows: trust and confidence while using such tools [36], [37]. Recent Section II presents the background of the study. Section III studies have addressed this issue by providing various tech- presents the data collection of the study. Section IV describes niques in detecting and eliminating false-positive warnings. the proposed approach. Section V presents the experiment Junkeretal.[38]introducedamethodtoaddressfalse-positive settings. Section VI presents the results of our work. Section warnings by transforming this issue into a syntactic model- VII presents the discussion. Section IX presents the related checking problem and employing SMT solvers to evaluate work.SectionVIIIpresentsthethreatstovalidity,andSection the feasibility of violation of formula in model checking as X concludes the paper. a counter-example. Wang et al. [39] have proposed a “Golden II. BACKGROUND Features” set to detect actionable warnings and eliminate the A. Static Bug Detection unactionable ones. Hanam et al. [29] proposed an approach based on machine learning, where they created a warning Static bug detection is an automated technique for inspect- prediction model to distinguish between actionable and non- ing and analyzing a program’s source code, object code, or actionable warnings. Recently, Kharkar et al. [14] introduced binaries, all without executing the program [18], [19]. This distinct tools that leverage state-of-the-art neural models, process identifies potential bugs by examining how the code’s mostly transformer-based models, which are widely regarded controlanddataflowalignwithspecificbugpatternsandrules as the most effective approach for eliminating false-positive [19], [20]. If a code section violates any of these rules, the warnings. In this work, we opt to utilize the tools outlined staticbugdetectorwillissueawarningconcerningtheviolated in this study as our baselines for comparison. These tools are |
rule for that particular piece of code [21]. Multiple tools and referred to as feature-based approach, DeepInferEnhance, and 1https://doi.org/10.5281/zenodo.10043170 a GPT-C powered approach [14].C. Automated Program Repair the capabilities of two state-of-the-art GPT models, specifi- cally, GPT-3.5 Turbo [52] and GPT-4 [53]. Utilizing LLMs Automated program repair (APR) techniques have recently like ChatGPT as decision making components introduces a garnered significant attention from researchers [9], [16], [40], novel approach to systematically interact with instruction- [41]. The core concept of program repair is to automatically tuned LLMs, a method known as prompt engineering. Prompt generate program fixes to facilitate the testing and validation engineering is the practice of creating tailored input queries of software systems [10], [42]. The APR tools usually take thateffectivelycommunicatewithLLMs[16],[17].Numerous two inputs, a flawed code and a localization of the bug in investigations leverage prompt engineering in their utilization the flawed code or a description of the program’s expected ofLLMs[9],[16],[54]–[56].Promptengineeringasapractice behaviour [43]. Automated program repair can be both done offers the flexibility to utilize various strategies, including the dynamicallyandstatically.Inthedynamicsetting,thelocaliza- zero-shot approach, where the LLM is prompted without any tion or description of the bug usually comes in the test suites prior input/output examples; the one-shot method, involving associated with that flawed code and should be executed to an additional example; and the few-shot strategy, denoted as test the validation of the generated patch by the tool [9], [43]. K-shot, which provides K examples as previous input/output As an example, Liu et al. [1] introduced a method known pairsfortheLLM[17],[54].Moreover,inpromptengineering, as Phoenix, which utilizes fix patterns derived from the static techniques like Chain-of-Thought (COT) are employed to en- analysis of bug violations to generate patches. Their research hancethecorrectnessofgeneratedoutput.Thisisachievedby involved the utilization of the Defects4J benchmark dataset, either including the thinking steps in examples or requesting which includes test suites used to validate the effectiveness an explanation of the decision-making process from the LLM of the generated patches for the faulty code. Furthermore, [17], [57], [58]. Xia et al. [9] investigated utilizing Large Language Models (LLMs) for the first time for Automated Program Repair III. DATACOLLECTION (APR).TheyexaminedninerecentandadvancedLLMsusing In this work, we take two types of typical and critical bugs five benchmark datasets. All the patches they generated for thataretargetedbystaticbugdetection,i.e.,NullDereference the faulty codes were validated against the accompanying and Resource Leak as our subjects. To accelerate the data test suites in their respective datasets. In a static context, the collection, we first applied Infer [23] to our experimental bug’s description or localization is not provided through test projects with a focus on detecting Null Dereference and suites; instead, it is presented using alternative heuristic or ResourceLeakbugs.TherationalebehindselectingInferisits formalmethods[1],[2],[44].Forexample,TonderandGoues extensiveadoptioninvariouscompanies,includingMicrosoft. [2] proposed an APR technique for fixing general pointer Furthermore, Infer exhibits higher precision in comparison to safety properties using Separation Logic [45]. Bavishi et al. alternative static analysis tools, leading to the generation of [1] introduced a method for generating patches and verifying more valid warnings [14]. We apply Infer to a selection of them using a static analyzer as the oracle, eliminating the seven prominent GitHub projects (with at least more than 200 need for a test suite. Fu et al. [44] introduced VulRepair, a stars), along with three projects featured in prior research, to neural Automated Program Repair (APR) method founded on generate warnings [14]. These projects are shown in Table I. the CodeT5 model [46]. Their research involved generating Note that, as Infer can report false positives [14], [15], for patchesforlocalizedbugsfoundinapre-existingdataset[47], each warning, reported, we further manually check whether it [48]. They evaluated the effectiveness of their approach using is a true bug and not a false positive. This manual labeling a perfect prediction metric and compared the results to the process involves three authors with at least four years of ground truth data within the same dataset. development experience, each independently reviewing all the In this study, we select VulRepair [44] as our baseline tool reported warnings by Infer. For each warning, they assign a to compare with SkipAnalyzer. This choice is made because binary label, i.e., zero indicating a “false positive”, signifying VulRepair, similar to our approach, does not necessitate the that the warning generated by Infer is incorrect and does not execution of test cases for validation. represent a true bug, and one indicating a “true positive”, D. Large Language Models indicatingthatthewarningisaccurateanddemonstratesareal bug. Following this individual labeling, the authors then col- Large Language Models (LLMs) have gained significant laborate to identify and resolve any discrepancies or conflicts popularity in recent research and industrial applications. Nu- in their assessments. After resolving these conflicts, we have merousrecentstudiesareinvestigatingtheutilizationofLLMs our comprehensive dataset containing warnings generated by |
inthefieldofSoftwareEngineering(SE),drivenbythesignif- Infer,alongwiththeircorrespondinggroundtruthlabels.Also, icant progress and advancements achieved by LLMs [9], [41], for each of the true bugs, the participants work together to [49]. ChatGPT [50], one of the most renowned LLMs, has create a patch that can fix the bug. gainedwidespreadrecognitionrecentlyinperformingsoftware engineering tasks [9], [16], [17], [51]. ChatGPT is accessible IV. APPROACH throughout an API2 and has been created by harnessing Figure 1 provides an overview of SkipAnalyzer’s pipeline, 2https://platform.openai.com/docs/api-reference which contains 1) an LLM-based static bug detector that canTABLE I: Summary of analyzed projects. In this table, projects highlighted in are from a recent study done by Kharkar et al. [14], and projects highlighted in are the ones we collected from the popular repositories. The warnings reported in this table are generated by Infer [23] and manually verified. Project ProjectDescription Version LOC RepositoryGroup NumberofVerifiedWarnings nacos Dynamicnamingandconfigurationservice 2.0.2 217,653 Alibaba 58 azure-maven-plugins MavenpluginsforAzureservices 2.2.2 53,025 Microsoft 45 JavalibrarytoautomateChromium, playwright-java 1.13.0 67,548 Microsoft 5 Firefox,andWebKitwithasingleAPI JavaDebugServer,animplementationof java-debug 0.47.0 22,852 Microsoft 2 VisualStudioCode(VSCode)DebugProtocol dolphinscheduler Moderndataorchestrationplatform 2.0.9 215,808 Apache 100 high-performance,Java-based dubbo 3.2 350,957 Apache 193 open-sourceRPCframework atooltomanipulateAndroidAppBundles bundletool 1.15.1 135,711 Google 51 andAndroidSDKBundles setofcoreJavalibrariesfromGoogle guava 32.1.1 698,201 Google 35 thatincludesnewdatastructures releaseautomationtoolfor jreleaser 1.7.0 114,914 Community 30 Javaandnon-Javaprojects Javalibraryforworkingwith jsoup 1.16.1 33,689 Community 33 HTMLDocumentObjectModel(DOM) TotalNumberofVerifiedWarnings 552 scan source code and report specific types of bugs (Sec- B. LLM-based False-Positive Warning Filter tion IV-A), 2) an LLM-based false positive filter that can identifyfalse-positivebugsintheresultofstep1forimproving In the second component, SkipAnalyzer’s objective is to the detection accuracy (Section IV-B), and 3) an LLM-based improve the precision of static bug detection by eliminating patchgeneratorthatcangeneratepatchesforthedetectedbugs false-positive warnings. To achieve this, SkipAnalyzer takes (Section IV-C). both the buggy code snippet and the warning associated with that code snippet, which is generated by a static bug detector. Thesewarningscanoriginatefromvariousstaticbugdetectors, such as Infer or SkipAnalyzer itself. Subsequently, the LLM, A. LLM-based Static Bug Detector previouslyinstructedwithspecializedguidelines,evaluatesthe buggy code snippet and its corresponding warning. Similar to In the first component, SkipAnalyzer takes the buggy code the first component, the prompt in this stage allow for the snippet as input for in-depth analysis by the LLM. The LLM inclusion of additional examples, enabling the application of has been given a specialized prompt with specifications for one-shot or few-shot strategies. each bug type to increase its detection validity. For example, to address Null Dereference bugs, we collect common bug patternsforthistypeofbug,likenothavingnullchecksbefore dereferencing an object. We then provide this information to C. LLM-based Static Bug Repair the LLM in the initial prompt. This specialization helps the LLM understand the task at hand. Additionally, for Resource In the third component, SkipAnalyzer processes the buggy Leak bugs, a similar approach is used. Moreover, specific code snippet and the warning related to that particular bug structured output requirements are defined to facilitate easy in the code. It then proceeds to generate a patch for the parsing and extracting necessary information from the LLM’s buggy code, ultimately producing the fixed version of the responses. Moreover, the prompt of this component supports code. This component feeds the inputs mentioned above to adding additional examples to apply one-shot or few-shot the LLM, which has previously received tailored instructions strategies. Given that we possess a ground truth for the on addressing our specific types of bugs. It is worth noting provided buggy code snippet, we expect SkipAnalyzer to that the prompt of this component does not support additional recognizetheproblempreviouslyidentifiedbyInferandissue examplesforone-shotorfew-shotstrategiessinceexamplesin a valid warning for it. Furthermore, SkipAnalyzer offers an our dataset usually have multiple implementations of methods additional explanation for each potential bug it detects and withvaryinglengthsandviolatethemaximumtokenlimitation the warnings it generates. of our opted LLMs (more details in Section V-B).OpenAIAPI3.Accordingtothemodeldocumentation,thereis a wide range of options available for each of the models, and each option comes with its distinct characteristics, including varyingtokenlengths,associatedcosts,andupdatefrequencies [50]. For ChatGPT-4 and ChatGPT-3.5 Turbo, we utilize the default settings, which provide maximum token support of 8,192and4,097,respectively[52],[53].Duetothislimitation in the maximum input token, we constrain the code inputs to the method scope, implying that we only provide the methods themselves as input code snippets to the LLMs. Fig. 1: The overview of SkipAnalyzer. C. Prompting Strategies |
IneachoftheSkipAnalyzer’scomponents,weusedifferent promptengineeringstrategiessuchaszero-shot,one-shot,and V. EXPERIMENTSETTINGS few-shot strategies. In the zero-shot strategy, the LLM is A. Research Questions promptedwithoutprecedingexamplesfromthepreviousLLM input and output pairs. In contrast, the few-shot and one-shot To evaluate the performance of SkipAnalyzer, we design strategies incorporate examples from the previous LLM input experiments to answer the following research questions: and output pairs. The difference between the one-shot and RQ1 (Static Bug Detection): What is the performance of few-shot strategies lies in the number of examples included: SkipAnalyzer in detecting bugs? In this research question, theone-shotstrategyemploysasingleexampleintheprompt, weexplorethepotentialofSkipAnalyzerintherealmofstatic whilethefew-shotstrategyencompassesmultipleexamples.In bugdetection.Wepresenttheperformanceofourapproachfor the first component (LLM-based static bug detector) and the static bug detection and compare it with our baseline, Infer, second component (LLM-based false-positive warning filter), while also conducting comparisons under various prompting we use zero-shot, one-shot, and few-shot strategies. In this strategies. paper, for the few-shot strategy, (K-shot), we input the model with three examples (K = 3). The rationale for selecting RQ2 (False Positive Warning Removal): What is the K = 3 is based on the consideration that opting for values effectiveness of SkipAnalyzer in filtering false positive exceeding three could potentially violate the maximum token warnings? In this research question, we delve into the effec- limit constraint imposed on our inputs for ChatGPT models tiveness of SkipAnalyzer’s second component in identifying (details in Section V-B). In the third component (LLM-based and eliminating false-positive warnings from the output of bug repair), we only use the zero-shot strategy due to the a static bug detector. This analysis is applied to both the limitationsmentionedinSectionsV-BandIV-C.Furthermore, warnings generated by Infer and those produced in response in the prompts for all of SkipAnalyzer’s components, we to RQ1. Eventually, we compare the results of our developed request the LLM to explain its decision-making process and approach with recent state-of-the-art baselines provided by the steps it takes to arrive at its conclusions. According to the Kharkaretal.[14]thatutilizefeature-basedandneuralmodels literature,thisapproach,knownaszero-shotChain-of-Thought for false-positive warning removal. reasoning, can enhance the output’s robustness and validity RQ3 (Static Bug Repair): What is SkipAnalyzer’s perfor- [57], [58]. manceinrepairingabuggycodeforaspecifictypeofbug? This RQ examines the potential of SkipAnalyzer in repairing D. Data Sampling instances of bugs identified. Note that, as we do not have Our experiments employ N-fold cross-validation to remove test cases for the identified bugs, most generate-and-validate potentialdatasamplingbias,withN setto5inthisstudy[60]. program repair techniques cannot be our baselines, as these This approach involves splitting the dataset into five subsets, approaches require a set of test cases as the ground truth. In whereone-fifthofthedataservesasthevalidationset,andthe this work, we choose VulRepair [44], a CodeT5-based static remaining four-fifths function are used for selecting examples automatedprogramrepairmodel[59]thatdoesneedtestcases in the process of prompting the LLMs for one-shot and few- as the ground truth. shot strategies. We select the examples for these strategies randomly in a uniform distribution. Also, in each of the B. ChatGPT Versions examples utilized in one-shot and few-shot strategies, we We choose the latest variations of ChatGPT models [50], incorporate one instance of a true-positive record and one ChatGPT-4 [53] and ChatGPT-3.5 Turbo [52], as the primary instanceofanfalse-positiverecordtopreventanybiastowards backbone to build SkipAnalyzer. These models have demon- a particular group of examples when applying these strategies strated strong performance in various software engineering to the LLM. tasks, including code generation, code comprehension, and debugging [9], [56]. We interact with these models using 3https://platform.openai.com/docs/introductionTABLE II: Summary of SkipAnalyzer’s results for each of the model-strategy combination in Static Bug Detection (RQ1) using two datasets. In this table, rows highlighted in indicate the most effective combination of model and strategy for Null Dereference bugs, and rows in indicate the most effective one for Resource Leak bugs. Dataset BugType Infer’sPrecision Strategy Model Accuracy Precision Recall F1-Score GPT-3.5-Turbo 50.66% 52.32% 40.64% 45.75% ZeroShot GPT-4 68.37% 63.76% 88.93% 74.27% GPT-3.5-Turbo 60.67% 62.49% 59.76% 61.09% NullDereference 50.9% OneShot GPT-4 64.54% 62.20% 79.18% 69.67% GPT-3.5-Turbo 60.47% 66.14% 48.63% 56.05% FewShot GPT-4 64.31% 65.21% 64.96% 65.09% Ourcollection GPT-3.5-Turbo 56.31% 44.34% 40.44% 42.30% ZeroShot GPT-4 76.95% 82.73% 55.11% 66.15% GPT-3.5-Turbo 34.87% 35.03% 72.22% 47.18% ResourceLeak 39.6% OneShot GPT-4 72.78% 68.39% 63.55% 65.88% GPT-3.5-Turbo 49.31% 41.49% 65.55% 50.82% FewShot |
GPT-4 75.25% 74.12% 59.55% 66.04% GPT-3.5-Turbo 50.31% 69.85% 41.53% 52.09% ZeroShot GPT-4 77.90% 81.87% 85.51% 83.65% GPT-3.5-Turbo 58.25% 70.90% 59.87% 64.92% NullDereference 65.2% OneShot GPT-4 70.51% 80.95% 72.56% 76.53% GPT-3.5-Turbo 56.47% 75.60% 51.28% 61.11% FewShot GPT-4 68.52% 80.57% 67.56% 73.50% Projectsfrom[14] GPT-3.5-Turbo 61.66% 50.0% 50.0% 50% ZeroShot GPT-4 84.61% 100% 71.42% 83.32% GPT-3.5-Turbo 46.66% 50% 70% 58.33% ResourceLeak 53.8% OneShot GPT-4 73.33% 60% 50% 54.54% GPT-3.5-Turbo 48.33% 36.66% 40% 38.26% FewShot GPT-4 68.33% 60% 40% 48% E. Evaluation Metrics usingtwodifferentChatGPTmodels,i.e.,ChatGPT-3.5Turbo and ChatGPT-4 (more details in Section V-B). We employ the following evaluation metrics to assess our Baselines: As a baseline for SkipAnalyzer’s first component, experiments concerning each of our research questions: weselectInfer,astate-of-the-artstaticbugdetector.Usingour ForStaticBugDetection(RQ1)andFalse-PositiveWarn- collected dataset, we compare SkipAnalyzer’s performance in ing Removal (RQ2), since we have a ground truth for the static bug detection with Infer. warnings we generated for our dataset for evaluation, we Result: Table II summarizes the results of SkipAnalyzer’s use Accuracy, Precision, and Recall metrics. Also, to choose static bug detection task under different prompting strategies the best combination of strategy and model, we use the F1- with different ChatGPT models using Infer on our collected score metric. For Static Bug Repair (RQ3), we assess the dataset and the projects used in the prior study by Kharkar performance using two key measures that we devised: “Logic et al [14]. We also show the optimal combination of model Rate”, which signifies the proportion of repaired code with and strategy for the static bug detection task for each of the correct logic, and “Syntax Rate”, indicating the proportion datasets, which is the one that has the highest F1-Score for a of repaired code with correct syntax. To evaluate the “Logic specific bug type. Notably, in our collected dataset, the most Rate”, we assess correctness by comparing the repaired code effectivecombinationforbothNullDereferenceandResource to manually crafted ground truth fix patches prepared by our Leak bugs involves utilizing ChatGPT-4 in conjunction with team. In the case of the “Syntax Rate”, we employ a Java the zero-shot strategy. Considering this, in static bug detec- parser to validate the syntax of the generated code. tion, SkipAnalyzer can achieve accuracy, precision, and recall VI. RESULTANALYSIS rates of 68.37%, 63.76%, and 88.93%, respectively, for Null Dereference bugs. Likewise, for Resource Leak bugs, these This section presents the results and answers the research metrics can attain values of 76.95%, 82.73%, and 55.11%, questions we asked in Section V-A. respectively. This indicates that SkipAnalyzer exhibits preci- sion levels that are 12.86% and 43.13% higher than Infer, A. RQ1:PerformanceofSkipAnalyzeronStaticBugDetection surpassing the performance of the state-of-the-art static bug Approach: In the case of static bug detection, we input the detector baseline. Furthermore, it is noteworthy that some code snippet of each record in our dataset to the SkipAna- other model-strategy combinations also demonstrate superior lyzer’s first component. We expect that SkipAnalyzer will performance when compared to Infer. For instance, ChatGPT- identify the issue previously described and detected by Infer 3.5-Turbo with the one-shot strategy continues to outperform and produce a valid warning. We perform our experiments Infer in the detection of Null Dereference bugs, achieving a under different prompting strategies such as zero-shot, one- rate of 62.49% compared to Infer’s 50.9%. We can also see a shot, and few-shot strategies (more details in Section V-C) by similarresultinthedatasetfromtheprojectsusedbyKharkaret al. [14]. In this scenario, the most effective strategy and that Kharkar et al. [14] did not provide the results of the model combination is the zero-shot strategy coupled with the feature-basedlogisticregressionmodelandDeepInferEnhance ChatGPT-4 model. Compared to Infer’s base results on this forResourceLeakbugs.Therefore,wespecifiedthemwith“–” dataset depicted in Table II, we have a 16.6% and 46.2% in Table IV. boost in precision for Null Dereference and Resource Leak 2) Option2–SkipAnalyzer: TableIIIalsoshowstheresult bugs, respectively. of false-positive warning removal on the warnings generated by SkipAnalyzer in Section VI-A. Given that these warn- Answer to RQ1: SkipAnalyzer can significantly enhance ings may arise from various model-strategy combinations, we the state-of-the-art static bug detection tool (i.e., Infer) on selected the most effective model-strategy combination for detecting Null Dereference and Resource Leak bugs. warning generation further to enhance precision through the false-positive warning removal process. Therefore, we opted bugs. for the zero-shot strategy with the ChatGPT-4 model. Moreover, it is worth noting that no false-positive warnings B. RQ2:PerformanceofSkipAnalyzeronFalse-PositiveWarn- were associated with Resource Leak issues in the warnings ing Removal generated by this specific model-strategy combination. Con- |
Approach: For answering this RQ, we input both a code sequently, our primary focus remains improving the false- snippet and the warning linked to the code snippet generated positive warnings related to Null Dereference issues. by a bug detector to SkipAnalyzer. To examine the general- As we can see in Table III, by selecting a proper model- izability of SkipAnalyzer in removing false positives, we use strategy combination, which is, in this case, the few-shot the warnings generated by both Infer and SkipAnalyzer (as strategy with the ChatGPT-4 model, we can improve the described in Section VI-A). We also perform our experiments precisionbyremovingfalse-positivewarningsofthewarnings under different prompting strategies such as zero-shot, one- generated in Section VI-A by 16.31%. shot, and few-shot strategies (more details in Section V-B) by usingtwodifferentChatGPTmodels,i.e.,ChatGPT-3.5Turbo Answer to RQ2: SkipAnalyzer can remove false-positive and ChatGPT-4 (more details in Section V-B). warnings effectively and it outperforms the previous state- Baselines: We select the state-of-the-art false-positive re- of-the-art false-positive warning removal baselines. moval approach proposed in the recent study conducted by Kharkar et al. [14], i.e., GPT-C and also they created two C. RQ3: Performance of SkipAnalyzer on Bug Repair baselines to evaluate GPT-C, which are a feature-based lo- Approach: For this RQ, we input SkipAnalyzer with the true gistic regression model [14] and DeepInferEnhance (based positive buggy code snippets. We instruct the SkipAnalyzer on CodeBERTa) [14]. However, the authors neither disclosed to understand the code and its corresponding warning and the source code for their tool nor their experiments due to generate a potential patch to repair the buggy code. Sub- confidential issues. They also did not release their collected sequently, we manually assess the generated code patches dataset. Thus, to enable a meaningful comparison with the for their syntactical and logical correctness. We perform our baseline tools outlined in their study, we gathered data that experimentsunderthezero-shotstrategybyusingtwodifferent closelymirroredtheonedescribedintheirpaper,includingthe ChatGPT models, i.e., ChatGPT-3.5 Turbo and ChatGPT-4 same projects and similar versions. Ultimately, we conducted (more details in Section V-B). It is important to note that we our experiments on a dataset akin to the one they utilized, do not employ the one-shot or few-shot strategy for static bug allowing for a fair and direct comparison between our tool repair due to the limitations mentioned in Sections IV-C and and their baseline tools. V-B. Result: As we explained, we have two options for the static Baselines: We compare the results of our tool with a recent bug detector utilized for false-positive warning removal: baseline tool called VulRepair [44]. We used the model and 1) Option1–Infer: TableIIIshowstheresultsofapplying experiment codes offered by the authors to test this baseline SkipAnalyzer as a false-positive warning removal tool on tool on our collected dataset. We followed the same configu- warnings generated by Infer and SkipAnalyzer. ration for training and evaluating their model on our dataset. Asdemonstrated,whendealingwithNullDereferencebugs, Result: Our research findings indicate that SkipAnalyzer can we can enhance Infer’s precision by 28.68% by employing serve as a robust bug repair tool. Table V displays the the zero-shot strategy alongside the ChatGPT-4 model. In performance of SkipAnalyzer in fixing Null Dereference and the case of Resource Leak bugs, Infer’s precision can be ResourceLeakagebugsfordifferentmodels.Theresultsreveal improvedbyupto9.53%whenutilizingthezero-shotstrategy that SkipAnalyzersurpasses the baseline tool,VulRepair [44], combined with the ChatGPT-3.5-Turbo model. Furthermore, with a substantial improvement. Specifically, SkipAnalyzer in comparison to the current baselines [14], as indicated in achieves a logic rate increase of up to 78.91% for Null Table IV, our findings reveal that SkipAnalyzer can surpass Dereference bugs and a rate increase of 78.87% for Resource theexistingbaselinesintermsofprecisionimprovement,with Leak bugs compared to VulRepair. Furthermore, it is worth a margin of at least 11.21% and 3.97% for Null Dereference noting that SkipAnalyzer does not require training or fine- and Resource Leak bugs, respectively. Also, it is worth noting tuning. In contrast, VulRepair mandates the adaptation andTABLE III: Summary of SkipAnalyzer’s results in False-Positive Warning Removal (RQ2) on warnings generated by Infer and SkipAnalyzer. In this table, P is the precision of the static bug detector for the corresponding bug type and P Original After is the precision of the static bug detector after applying False-Positive Warning Removal process. “Imp.” indicates the amount of precision improvement. Rows highlighted in indicate the most effective combination of model and strategy for Null Dereference bugs, and rows in indicate the most effective one for Resource Leak bugs. Also, the records that have no improvement in precision are shown with “–”. StaticBugDetector BugType Strategy Model POriginal PAfter Imp. Recall Accuracy F1-Score GPT-3.5-Turbo 40% - 13.07% 37.91% 19.71% ZeroShot GPT-4 95% +29.8 27.30% 51.41% 42.42% GPT-3.5-Turbo 59.32% - 43.71% 43.91% 50.33% NullDereference OneShot 65.2% GPT-4 95% +29.8 51.66% 66.29% 66.93% GPT-3.5-Turbo 53.63% - 52.17% 41.40% 52.89% FewShot GPT-4 93.88% +28.68 64.23% 73.46% 76.27% Infer |
GPT-3.5-Turbo 63.33% +9.53 80% 75% 70.69% ZeroShot GPT-4 60% +6.2% 60% 80% 60% GPT-3.5-Turbo 40% - 60% 50% 48% ResourceLeak OneShot 53.8% GPT-4 60% +6.2% 50% 75% 54.54% GPT-3.5-Turbo 50% - 80% 50% 61.53% FewShot GPT-4 60% +6.2% 60% 80% 60% GPT-3.5-Turbo 70% - 19.27% 32.93% 30.22% ZeroShot GPT-4 86% +4.13% 26.72% 37.45% 40.78% GPT-3.5-Turbo 67% - 30.72% 32.72% 42.26% SkipAnalyzer NullDereference OneShot 81.87% GPT-4 97.5% +15.63 52.72% 59.92% 68.44% GPT-3.5-Turbo 73.97% - 38.18% 38.90% 50.36% FewShot GPT-4 98.18% +16.31 77.45% 80.25% 86.59% TABLE IV: Performance of False-Positive Warning Removal TABLE V: Summary of SkipAnalyzer’s results in static bug of baseline tools proposed by [14]. In this table column repair. The “Syntax Rate” column indicates the proportion “Precision Imp.” indicates the precision improvement of Infer of generated patches that are syntactically correct. “Logic after applying each of the baseline tools. Also, column “S.A. Rate” column represents the rate of generated patches that Recall Imp.” shows SkipAnalyzer ’s improvement in Recall are logically correct. for each bug type compared to the baseline tool. Bug Type Model Logic Rate Syntax Rate Baseline BugType PrecisionImp. Recall SA.RecallImp. GPT-3.5-Turbo 94.25% 100.0% NullDereference +8.26% 65.1% +12.35% Feature-based NullDereference GPT-4 97.30% 99.55% ResourceLeak – – – NullDereference +15.13% 88.3% -10.85% VulRepair 18.39% – DeepInferEnhance ResourceLeak – – – GPT-3.5-Turbo 87.11% 97.77% NullDereference +17.47% 83.7% -6.25% GPT-C ResourceLeak GPT-4 91.77% 97.77% ResourceLeak +5.56% 64.5% +15.5% VulRepair 12.90% – training of our dataset for patch generation, showing the superiority of SkipAnalyzer over the recent state-of-the-art For our analysis, we first collect all the missing bugs that baseline tool, VulRepair. Also, VulRepair-generated patches SkipAnalyzer can not detect. Then, we manually examine are not self-contained Java codes and should be appended to all the missing bugs and observe the possible recurring and the buggy code. Hence, they are not parsable, and we specify common patterns among them. the Syntax Rate for VulRepair’s generated patches with VI-C 1) Null Dereference: We have identified three patterns in Table V. fromNullDereferencebugsthatSkipAnalyzermissed.Firstly, SkipAnalyzer struggles to distinguish Null Dereferences of Answer to RQ3:SkipAnalyzeriseffectiveinpatchingthe objects within a null check for another object. This is often detected bugs. In addition, SkipAnalyzer can significantly observed when SkipAnalyzer overlooks objects that might outperform a recent state-of-the-art baseline tool, i.e., Vul- become null and dereferenced later within a null check for Repair. another object. This issue becomes more pronounced when theseobjectshavesomeformofrelationshipwithoneanother, suchaswhenthefirstobjectservesasanargumenttoamethod VII. DISCUSSIONS call of the second object. Figure 2 shows an example bug that A. Reasons for Missing Detecting Bugs is missing by SkipAnalyzer. SkipAnalyzer also has limitations such as it can miss de- Second, we have observed that SkipAnalyzer sometimes tectingbugsinRQ1.Inthissection,weexploretheunderlying makes random assumptions about the method, API call, class reasons behind the bugs that SkipAnalyzer cannot detect. variable, and instance variable that are usually outside the1public DependentParameters getDependency() { 1private void cacheNormalInvokers(BitList<Invoker<T>> 2 if (this.dependency == null) { 2 invokers) { 3 Map<String, Object> taskParamsMap = 3 BitList<Invoker<T>> clonedInvokers = invokers.clone(); 4 JSONUtils.parseObject(this.getTaskParams(), new 4 clonedInvokers.removeIf((invoker) −> 5 TypeReference<Map<String, Object>>() {}); 5 invoker.getUrl(). getProtocol ().equals(MOCK PROTOCOL)); 6 this.dependency = JSONUtils.parseObject((String) 6 normalInvokers = clonedInvokers; 7 taskParamsMap.get(Constants.DEPENDENCE), 7} 8 DependentParameters.class); 9 } Ground Truth Warning: object returned by “in- 10 return this.dependency; voker.getUrl().getProtocol()” could be null and is derefer- 11} enced at line 5. Ground Truth Warning: object “taskParamsMap” last SkipAnalyzer’s Explanation:The‘normalInvokers‘object assigned on line 3 could be null and is dereferenced at line isassignedthevalueof‘clonedInvokers‘,whichisacloned 7. version of ‘invokers‘. However, there is no null check for ‘clonedInvokers‘ before assigning it to ‘normalInvokers‘. SkipAnalyzer’s Explanation: The code checks if If ‘invokers.clone()‘ returns null, it will result in a null “this.dependency” is null before assigning a value to it. dereference bug. Therefore, there is no potential null dereference bug in this code. Fig. 4: An example of a missing Null Dereference bug by Fig. 2: An example of a missing Null Dereference. SkipAnalyzer. In this example, SkipAnalyzer missed the Null Dereference issue in the method call chain and did not report anything about it. 1private static void registerContextBeans(ConfigurableListableBeanFactory 2beanFactory, DubboSpringInitContext context) { |
3 // register singleton Third,anotherprevalentpatternisSkipAnalyzer’sdifficulty 4 registerSingleton (beanFactory, context); in detecting Null Dereferences that occur in a single line 5 registerSingleton (beanFactory, through a chain of method invocations. While SkipAnalyzer 6 context.getApplicationModel()); may be able to detect the first object invoking a method, it 7 registerSingleton (beanFactory, oftenfailstoidentifythesubsequentmethodschainedthrough 8 context.getModuleModel()); 9} methodcallstotheinitialobject,whichcouldalsoreturnnull. As an example, we can look at Figure 4. Ground Truth Warning: object returned by “con- 2) Resource Leak: The prevalent pattern of overlooked text.getApplicationModel()” could be null and is derefer- Resource Leak bugs involves cases where the code partially enced by call to “registerSingleton(...)” at line 6. handles the release of resources. This implies that while some SkipAnalyzer’s Explanation: The values of resources are properly released after their use, there are still “context.getApplicationModel()” and “con- otherresourcesthatremainunreleased.Figure5isanexample text.getModuleModel()” are being checked for null of a missing Resource Leak bug due to this issue. before being registered as singletons, so there is no null dereference bug in this code. VIII. THREATSTOVALIDITY In this research, our focus is solely on Java projects, and Fig. 3: An example of a missing Null Dereference bug by we do not consider projects developed in other programming SkipAnalyzer.Inthiscase,the“registerSingleton”isafunction languages. This choice stems from the limitation that Infer, declared as outside of the method where the Null Dereference the tool we employ for generating warnings and the dataset, is detected. Consequently, SkipAnalyzer attempts to establish is not capable of handling multiple programming languages. aconnectionbetweentheregisteringforsingletonandtheNull However, it is worth noting that Infer can be used with Dereference issue, even though they are not directly related. languages like C and C#. Therefore, conducting a similar analysis on additional languages that Infer is compatible with can contribute to the validity of our research. current method’s scope. SkipAnalyzer’s inability to access the Another potential challenge to the validity of our work implementation details of these entities hinders its ability to is that the evaluation is conducted exclusively on a dataset determine whether they can return null or not. Consequently, created from warnings generated by Infer, without taking SkipAnalyzeroccasionallymakesincorrectassumptionsabout into account warnings generated by alternative static analysis the return values of such entities, leading to missing potential tools like SpotBugs [24] or Error-Prone [27]. In this study, Null Dereference bugs. Figure 3 shows an example bug that we opted not to include SpotBugs and Error-Prone as static cannot be detected by SkipAnalyzer because of the above bug detectors. This decision was made because these tools reason. categorize bug types differently, and we aimed to maintainIX. RELATEDWORK 1private void executeForSdkArchive() { 2 try (TempDirectory tempDir = new A. LLM Applications in Software Engineering 3 TempDirectory(getClass().getSimpleName()); Recently, there has been a considerable volume of research 4 ZipFile asarZip = new 5 ZipFile(getSdkArchivePath().get(). toFile ())) { dedicated to exploring the capabilities of Large Language 6 Path modulesPath = Models (LLMs) within the domain of Software Engineering 7 tempDir.getPath(). resolve(EXTRACTED SDK); (SE). For example, several studies focus on automated pro- 8 try (ZipFile modulesZip = getModulesZip(asarZip, gram repair [9], [16], [41], [44], [61]–[67]. For instance, Xia 9 modulesPath)) { etal.[9]conductedthefirstempiricalstudytoevaluateninere- 10 SdkAsarValidator.validateModulesFile(modulesZip); 11 SdkAsar sdkAsar = SdkAsar.buildFromZip(asarZip, centstate-of-the-artLLMsforautomatedprogramrepairtasks 12 modulesZip, modulesPath); on five different repair datasets. Mashhadi and Hemmati [67] 13 generateAppApks(sdkAsar.getModule(), tempDir); fine-tuned a repair dataset of single-line Java bugs on the 14 } CodeBERTmodel.Also,numerousstudiesinsoftwaretesting 15 } catch (ZipException e) { and fuzzing utilize LLMs [54], [68]–[70]. For example, Deng 16 throw CommandExecutionException.builder() 17 .withInternalMessage(”ASAR is not a valid zip file .”) et al. [69] proposed FuzzGPT, a novel LLM-based fuzzer that 18 .withCause(e) canproduceunusualprogramsforfuzzingreal-worldsystems. 19 .build(); The same authors also provide TitanFuzz [70], the first LLM- 20 } catch (IOException e) { based approach for fuzzing Deep Learning (DL) libraries. 21 throw new UncheckedIOException(”An error occurred when Kang et al. [54] proposed LIBRO, a framework that uses 22 processing the SDK archive.”, e); 23 } LLMs to automate test generation from general bug reports. 24 } Furthermore, there are studies that focus on Oracle genera- tion [71]–[73]. For example, Tufano et al. [71] proposed a Ground Truth Warning: resource of type novelassertiongenerationapproachusingaBARTtransformer “java.util.zip.ZipFile” acquired by call to “ZipFile(...)” at model. Nie et al. [72] proposed an approach for predicting line 4 is not released after line 20. the next statement in test methods that need reasoning about |
SkipAnalyzer’s Explanation: The resources “tempDir” the code execution by utilizing CodeT5 model. Dinella et al. and “asarZip” are allocated using the try-with-resources [73] introduced TOGA, a neural transformer-based method syntax, which means they will be automatically released for inferring both exceptional and assertion test conditions by and closed after the try block finishes. Therefore, there is considering the context of the main method. Also, there are no resource leakage bug in this code. studies that focus on mobile applications such as Android. [17], [74]. Feng et al. [17] introduced an automated technique Fig. 5: An example of a missing Resource Leak bug by Skip- forAndroidbugreproduction,utilizingChatGPT-3.5toextract Analyzer. In this example, Although SkipAnalyzer correctly reproducible steps and automate the bug replay procedure. identify“tempDir”asnotbuggy,itcannotdetectthe“asarZip”, Taebetal.[74]proposedanautomatedapproachforproducing which is an actual Resource Leak bug. The code does not anavigablevideofromamanualaccessibilitytestofamobile useJava7try-with-resources(try(...))syntaxforthe“asarZip” application by utilizing ChatGPT-4. object. It only uses it for “tempDir” and also “modulesZip” in the next lines. X. CONCLUSION This paper introduces a novel LLM-based tool for static code analysis. Our developed tool, SkipAnalyzer, can show- case the capabilities of LLMs like ChatGPT models in car- consistency in our bug classification [15]. Additionally, Infer rying out code analysis tasks, including static bug detection, has better precision and outperforms them in accuracy [14]. false-positive warning removal, and bug repair. To generate Also,weexclusivelyemployedLLMmodelsfromOpenAI, warnings,weemployedInfer,awell-establishedstaticanalysis specificallyChatGPT-4andChatGPT-3.5Turbo.Itisessential tool,onprominentopen-sourceJavaprojectsandprojectsfrom to recognize that other companies have also introduced their prior research. Subsequently, we meticulously labeled each of LLM models, such as Meta’s Llama2 and Google’s PaLM2 thegeneratedwarningsfortwotypesofbugs:NullDereference and Bard. These alternative models may bring their own and Resource Leak, thereby creating a new dataset for our unique features and performance characteristics, which could analytical work. We then harnessed the power of different potentially impact the validity of our findings. ChatGPTmodels(i.e.,ChatGPT-3.5Turbo,ChatGPT-4)under Furthermore, it is important to acknowledge that the per- different prompting strategies. Our experiments reveal that formance of our SkipAnalyzer may exhibit variations across SkipAnalyzer’s components can outperform baseline counter- different sets of projects. To account for this variability and parts, all while offering significant advantages in terms of enhance the generalizability of our results, we have included reduced costs and complexity. a diverse array of projects from various repositories and In the future, our research endeavors will broaden in scope backgrounds. asweaimtoexploreawiderarrayofLargeLanguageModels(LLMs), such as Meta’s Llama, Google’s Bard, and PaLM2, [16] J.Cao,M.Li,M.Wen,andS.-c.Cheung,“Astudyonpromptdesign, and integrate them into SkipAnalyzer. We also intend to advantagesandlimitationsofchatgptfordeeplearningprogramrepair,” arXivpreprintarXiv:2304.08191,2023. delve into a comparative analysis between fine-tuned LLMs [17] S. Feng and C. Chen, “Prompting is all your need: Automated and LLMs that are specialized for specific tasks through android bug replay with large language models,” arXiv preprint prompt engineering. Additionally, we find it intriguing to arXiv:2306.01987,2023. [18] L.Li,T.F.Bissyande´,M.Papadakis,S.Rasthofer,A.Bartel,D.Octeau, assessSkipAnalyzer’sperformanceondifferenttypesofbugs. J. Klein, and L. Traon, “Static analysis of android apps: A systematic Furthermore, adding additional components to SkipAnalyzer literature review,” Information and Software Technology, vol. 88, pp. to further examine coding practices and styles would be 67–95,2017. [19] Q. Ashfaq, R. Khan, and S. Farooq, “A comparative analysis of static helpful. code analysis tools that check java code adherence to java coding standards,” in 2019 2nd International Conference on Communication, REFERENCES ComputingandDigitalsystems(C-CODE). IEEE,2019,pp.98–103. [20] C. Vassallo, S. Panichella, F. Palomba, S. Proksch, H. C. Gall, and [1] R.Bavishi,H.Yoshida,andM.R.Prasad,“Phoenix:Automateddata- A. Zaidman, “How developers engage with static analysis tools in drivensynthesisofrepairsforstaticanalysisviolations,”inProceedings differentcontexts,”EmpiricalSoftwareEngineering,vol.25,pp.1419– ofthe201927thACMJointMeetingonEuropeanSoftwareEngineering 1457,2020. ConferenceandSymposiumontheFoundationsofSoftwareEngineering, [21] D.A.TomassiandC.Rubio-Gonza´lez,“Onthereal-worldeffectiveness 2019,pp.613–624. ofstaticbugdetectorsatfindingnullpointerexceptions,”in202136th [2] R. van Tonder and C. L. Goues, “Static automated program repair for IEEE/ACMInternationalConferenceonAutomatedSoftwareEngineer- heap properties,” in Proceedings of the 40th International Conference ing(ASE),2021,pp.292–303. onSoftwareEngineering,2018,pp.151–162. [22] N. S. Harzevili et al., “Automatic static bug detection for machine |
[3] K. Liu, A. Koyuncu, D. Kim, and T. F. Bissyande`, “Avatar: Fixing learning libraries: Are we there yet?” ArXiv, 2023, accessed 18 Oct. semantic bugs with fix patterns of static analysis violations,” in 2019 2023.[Online].Available:https://arxiv.org/abs/2307.04080 IEEE 26th International Conference on Software Analysis, Evolution [23] Infer.Inferofficialwebsite.[Online].Available:https://fbinfer.com/ andReengineering(SANER),2019,pp.1–12. [24] D.A.Tomassi,“Bugsinthewild:Examiningtheeffectivenessofstatic [4] D. Marcilio, R. Bonifa´cio, E. Monteiro, E. Canedo, W. Luz, and analyzersatfindingreal-worldbugs,”inProceedingsofthe201826th G. Pinto, “Are static analysis violations really fixed? a closer look at ACMJointMeetingonEuropeanSoftwareEngineeringConferenceand realistic usage of sonarqube,” in 2019 IEEE/ACM 27th International SymposiumontheFoundationsofSoftwareEngineering,ser.ESEC/FSE ConferenceonProgramComprehension(ICPC),2019,pp.209–219. 2018. New York, NY, USA: Association for Computing Machinery, [5] A. Carvalho, W. Luz, D. Marc´ılio, R. Bonifa´cio, G. Pinto, and 2018,p.980–982. E. Dias Canedo, “C-3pr: A bot for fixing static analysis violations via [25] D. Hovemeyer and W. Pugh, “Finding bugs is easy,” SIGPLAN pullrequests,”in2020IEEE27thInternationalConferenceonSoftware Not., vol. 39, no. 12, p. 92–106, dec 2004. [Online]. Available: Analysis,EvolutionandReengineering(SANER),2020,pp.161–171. https://doi.org/10.1145/1052883.1052895 [6] S.Afrose,Y.Xiao,S.Rahaman,B.P.Miller,andD.Yao,“Evaluation [26] B. Cole, D. Hakim, D. Hovemeyer, R. Lazarus, W. Pugh, and ofstaticvulnerabilitydetectiontoolswithjavacryptographicapibench- K. Stephens, “Improving your software using static analysis to find marks,”IEEETransactionsonSoftwareEngineering,vol.49,no.2,pp. bugs,” in Companion to the 21st ACM SIGPLAN Symposium on 485–497,2023. Object-Oriented Programming Systems, Languages, and Applications, [7] S. Lipp, S. Banescu, and A. Pretschner, “An empirical study on the ser. OOPSLA ’06. New York, NY, USA: Association for Computing effectiveness of static c code analyzers for vulnerability detection,” in Machinery, 2006, p. 673–674. [Online]. Available: https://doi.org/10. Proceedings of the 31st ACM SIGSOFT International Symposium on 1145/1176617.1176667 SoftwareTestingandAnalysis,ser.ISSTA2022. NewYork,NY,USA: [27] Google. (2023) Errorprone. Accessed on Date. [Online]. Available: Association for Computing Machinery, 2022, p. 544–555. [Online]. https://errorprone.info/index Available:https://doi.org/10.1145/3533767.3534380 [28] H. J. Kang, K. L. Aw, and D. Lo, “Detecting false alarms from [8] Y.Pan,X.Ge,C.Fang,andY.Fan,“Asystematicliteraturereviewof automaticstaticanalysistools:Howfararewe?”inProceedingsofthe android malware detection using static analysis,” IEEE Access, vol. 8, 44thInternationalConferenceonSoftwareEngineering,ser.ICSE’22. pp.116363–116379,2020. New York, NY, USA: Association for Computing Machinery, 2022, p. [9] C. S. Xia, Y. Wei, and L. Zhang, “Automated program repair 698–709. in the era of large pre-trained language models,” in Proceedings [29] Q. Hanam, L. Tan, R. Holmes, and P. Lam, “Finding patterns of the 45th International Conference on Software Engineering, ser. in static analysis alerts: Improving actionable alert ranking,” in ICSE ’23. IEEE Press, 2023, p. 1482–1494. [Online]. Available: Proceedings of the 11th Working Conference on Mining Software https://doi.org/10.1109/ICSE48619.2023.00129 Repositories, ser. MSR 2014. New York, NY, USA: Association [10] L.Gazzola,D.Micucci,andL.Mariani,“Automaticsoftwarerepair:A for Computing Machinery, 2014, p. 152–161. [Online]. Available: survey,”inProceedingsofthe40thInternationalConferenceonSoftware https://doi.org/10.1145/2597073.2597100 Engineering,2018,pp.1219–1219. [30] X. Yang, J. Chen, R. Yedida, Z. Yu, and T. Menzies, “Learning [11] G.Wang,Y.Xie,Y.Jiang,A.Mandlekar,C.Xiao,Y.Zhu,L.Fan,and to recognize actionable static code warnings (is intrinsically easy),” A. Anandkumar, “Voyager: An open-ended embodied agent with large Empirical Softw. Engg., vol. 26, no. 3, may 2021. [Online]. Available: languagemodels,”arXivpreprintarXiv:2305.16291,2023. https://doi.org/10.1007/s10664-021-09948-6 [12] C.H.Song,J.Wu,C.Washington,B.M.Sadler,W.-L.Chao,andY.Su, [31] H. Shen, J. Fang, and J. Zhao, “Efindbugs: Effective error ranking for “Llm-planner: Few-shot grounded planning for embodied agents with findbugs,” in 2011 Fourth IEEE International Conference on Software largelanguagemodels,”inProceedingsoftheIEEE/CVFInternational Testing,VerificationandValidation,2011,pp.299–308. ConferenceonComputerVision,2023,pp.2998–3009. [32] Z. P. Reynolds, A. B. Jayanth, U. Koc, A. A. Porter, R. R. Raje, and [13] X. Hou, Y. Zhao, Y. Liu, Z. Yang, K. Wang, L. Li, X. Luo, D. Lo, J.H.Hill,“Identifyinganddocumentingfalsepositivepatternsgenerated |
J.Grundy,andH.Wang,“Largelanguagemodelsforsoftwareengineer- by static code analysis tools,” in 2017 IEEE/ACM 4th International ing: A systematic literature review,” arXiv preprint arXiv:2308.10620, Workshop on Software Engineering Research and Industrial Practice 2023. (SER&IP),2017,pp.55–61. [14] A. Kharkar, R. Z. Moghaddam, M. Jin, X. Liu, X. Shi, C. Clement, [33] T.MuskeandA.Serebrenik,“Techniquesforefficientautomatedelim- and N. Sundaresan, “Learning to reduce false positives in analytic ination of false positives,” in 2020 IEEE 20th International Working bugdetectors,”inProceedingsofthe44thInternationalConferenceon ConferenceonSourceCodeAnalysisandManipulation(SCAM),2020, SoftwareEngineering,2022,pp.1307–1316. pp.259–263. [15] N. S. Harzevili, J. Shin, J. Wang, and S. Wang, “Characterizing and [34] S.HeckmanandL.Williams,“Asystematicliteraturereviewofaction- understanding software security vulnerabilities in machine learning able alert identification techniques for automated static code analysis,” libraries,”arXivpreprintarXiv:2203.06502,2022. InformationandSoftwareTechnology,vol.53,no.4,pp.363–387,2011.[35] M. Christakis and C. Bird, “What developers want and need from [52] OpenAI. (2023) Chatgpt-3.5. Accessed on Date. [Online]. Available: program analysis: an empirical study,” in Proceedings of the 31st https://platform.openai.com/docs/models/gpt-3-5 IEEE/ACMinternationalconferenceonautomatedsoftwareengineering, [53] “Gpt-4technicalreport,”ArXiv,2023,accessed17Oct.2023.[Online]. 2016,pp.332–343. Available:https://arxiv.org/abs/2303.08774 [36] B. Johnson, Y. Song, E. Murphy-Hill, and R. Bowdidge, “Why don’t [54] S. Kang, J. Yoon, and S. Yoo, “Large language models are few- softwaredevelopersusestaticanalysistoolstofindbugs?”in201335th shot testers: Exploring llm-based general bug reproduction,” in 2023 International Conference on Software Engineering (ICSE), 2013, pp. IEEE/ACM 45th International Conference on Software Engineering 672–681. (ICSE). IEEE,2023,pp.2312–2323. [37] U.Koc,S.Wei,J.S.Foster,M.Carpuat,andA.A.Porter,“Anempirical [55] D. Zan, B. Chen, F. Zhang, D. Lu, B. Wu, B. Guan, W. Yongji, assessmentofmachinelearningapproachesfortriagingreportsofajava and J.-G. Lou, “Large language models meet NL2Code: A survey,” static analysis tool,” in 2019 12th ieee conference on software testing, in Proceedings of the 61st Annual Meeting of the Association for validationandverification(icst). IEEE,2019,pp.288–299. ComputationalLinguistics(Volume1:LongPapers). Toronto,Canada: [38] M. Junker, R. Huuck, A. Fehnker, and A. Knapp, “Smt-based false AssociationforComputationalLinguistics,Jul.2023,pp.7443–7464. positive elimination in static program analysis,” in Formal Methods [56] B.Min,H.Ross,E.Sulem,A.P.B.Veyseh,T.H.Nguyen,O.Sainz, and Software Engineering: 14th International Conference on Formal E.Agirre,I.Heintz,andD.Roth,“Recentadvancesinnaturallanguage Engineering Methods, ICFEM 2012, Kyoto, Japan, November 12-16, processing via large pre-trained language models: A survey,” ACM 2012.Proceedings14. Springer,2012,pp.316–331. Comput.Surv.,vol.56,no.2,sep2023. [39] J.Wang,S.Wang,andQ.Wang,“Istherea”golden”featuresetforstatic [57] J.Weiandetal.,“Chain-of-thoughtpromptingelicitsreasoninginlarge warning identification? an experimental evaluation,” in Proceedings of languagemodels,”arXiv,2022,accessed19Oct.2023. the 12th ACM/IEEE International Symposium on Empirical Software [58] T. Kojima, S. S. Gu, M. Reid, Y. Matsuo, and Y. Iwasawa, “Large EngineeringandMeasurement,ser.ESEM’18. NewYork,NY,USA: language models are zero-shot reasoners,” in Advances in Neural In- AssociationforComputingMachinery,2018. formation Processing Systems, S. Koyejo, S. Mohamed, A. Agarwal, [40] A.Arcuri,“Ontheautomationoffixingsoftwarebugs,”inCompanion D. Belgrave, K. Cho, and A. Oh, Eds., vol. 35. Curran Associates, of the 30th International Conference on Software Engineering, ser. Inc.,2022,pp.22199–22213. ICSE Companion ’08. New York, NY, USA: Association for [59] Y. Wang, W. Wang, S. Joty, and S. C. Hoi, “Codet5: Identifier-aware Computing Machinery, 2008, p. 1003–1006. [Online]. Available: unifiedpre-trainedencoder-decodermodelsforcodeunderstandingand https://doi.org/10.1145/1370175.1370223 generation,”arXivpreprintarXiv:2109.00859,2021. [60] T.-T.WongandP.-Y.Yeh,“Reliableaccuracyestimatesfromk-foldcross [41] Z.Fan,X.Gao,A.Roychoudhury,andS.H.Tan,“Improvingautomat- validation,” IEEE Transactions on Knowledge and Data Engineering, icallygeneratedcodefromcodexviaautomatedprogramrepair,”arXiv vol.32,no.8,pp.1586–1594,2020. preprintarXiv:2205.10583,2022. [61] H. Joshi, J. Cambronero Sanchez, S. Gulwani, V. Le, G. Verbruggen, [42] W. Weimer, T. Nguyen, C. Le Goues, and S. Forrest, “Automatically and I. Radicˇek, “Repair is nearly generation: Multilingual program findingpatchesusinggeneticprogramming,”in2009IEEE31stInterna- repair with llms,” Proceedings of the AAAI Conference on Artificial |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.