text
stringlengths 64
2.99M
|
---|
andChatGPTarecapableofproducingeffectivecommentsforthe language-reference?view=msvc-170 construction of SCTs. Specifically, the SCTs created by GPT3.5- [2] 2023.CVE. https://cve.mitre.org/ [3] 2023.OpenAI. https://platform.openai.com/docs/guides/gptbest-practices instructdemonstratedanenhancementinPrecisionandF1score, [4] 2023.Qemu. https://www.qemu.org/ showingimprovementof5.49%and1.98%,respectively,overthe [5] 2023.Tree-sitter. https://tree-sitter.github.io/tree-sitter/ [6] [n.d.].RoughAuditToolforSecurity. https://code.google.com/archive/p/rough- best-performingbaselineCodeT5,asshowninTable3.Inacom- auditing-tool-for-security. parativeanalysiswithSCTsgeneratedbyChatGPT,theGPT3.5- [7] RobertoBaldoni,EmilioCoppa,DanieleConoD’Elia,CamilDemetrescu,and instruct’sresultsarecomparablyeffective.Theyexhibitsuperiority IreneFinocchi.2018.ASurveyofSymbolicExecutionTechniques.ACMComput. Surv.51,3(2018),50:1–50:39. inrecallandF1score,whereasChatGPToutperformsinaccuracy [8] TomBrown,BenjaminMann,NickRyder,MelanieSubbiah,JaredDKaplan, andprecisionmetrics. PrafullaDhariwal,ArvindNeelakantan,PranavShyam,GirishSastry,Amanda Thesefindingssuggestthatemployingdifferentlargelanguage Askell,etal.2020.LanguageModelsareFew-ShotLearners.InAdvancesinNeural InformationProcessingSystems33:AnnualConferenceonNeuralInformation models(LLMs)forcommentgenerationonsourcecodeaidsinim- ProcessingSystems2020,NeurIPS2020,December6-12,2020,virtual. provingthepre-trainedmodel’scomprehension,therebyenhancing [9] SicongCao,XiaobingSun,LiliBo,YingWei,andBinLi.2021. BGNN4VD: ConstructingBidirectionalGraphNeural-NetworkforVulnerabilityDetection. theeffectivenessofvulnerabilitydetection. Inf.Softw.Technol.136(2021),106576. [10] SaikatChakraborty,RahulKrishna,YangruiboDing,andBaishakhiRay.2020. Deep Learning based Vulnerability Detection: Are We There Yet? CoRR 6.2 ThreattoValidity abs/2009.07235(2020). [11] ChatGPT.2022.ChatGPT.https://chat.openai.com/. GeneralizabilityonOtherProgrammingLanguages.Inthispaper,we [12] Chun-Fu(Richard)Chen,QuanfuFan,andRameswarPanda.2021. CrossViT: employthetree-sitterlibrarytoparseASTsforC/C++programming Cross-AttentionMulti-ScaleVisionTransformerforImageClassification.In2021 IEEE/CVFInternationalConferenceonComputerVision,ICCV2021,Montreal,QC, languages.Asaresult,ourexperimentalanalysisfocusessolelyon Canada,October10-17,2021.IEEE,347–356. C/C++datasets,excludingotherpopularlanguagessuchasJava [13] XiaoCheng,XuNie,NingkeLi,HaoyuWangandZhengZheng,andYuleiSui. 2022. HowAboutBug-TriggeringPaths?-UnderstandingandCharacterizing andPython.Infutureresearch,weintendtoevaluatetheefficacyof Learning-BasedVulnerabilityDetectors.IEEETransactionsonDependableand SCALEinthecontextofabroaderrangeofprogramminglanguages. SecureComputing. ConstraintsofDomainKnowledgeinStructuredNaturalLanguage [14] RolandCroft,MuhammadAliBabar,andM.MehdiKholoosi.2023.DataQuality forSoftwareVulnerabilityDatasets.CoRRabs/2301.05456(2023). Rules.ForthecontextofC/C++languagereference,SCALEoffers [15] Pieter-TjerkdeBoer,DirkP.Kroese,ShieMannor,andReuvenY.Rubinstein. elevenstructurednaturallanguagerulestofacilitatethecorrelation 2005. ATutorialontheCross-EntropyMethod. Ann.Oper.Res.134,1(2005), betweencodeanditsassociatedcomments.Althoughitiscompre- 19–67. [16] Facebook.[n.d.].Infer. https://fbinfer.com/. hensiveenoughinmostcases,itstillcannotcoversomestatements, [17] JiahaoFan,YiLi,ShaohuaWang,andTienN.Nguyen.2020. AC/C++Code suchasexpressionstatements.Thislimitationcouldpotentially VulnerabilityDatasetwithCodeChangesandCVESummaries.InMSR’20: 17thInternationalConferenceonMiningSoftwareRepositories,Seoul,Republicof introducebiasesintothemodel’spredictions.Apotentialresolution Korea,29-30June,2020,SunghunKim,GeorgiosGousios,SarahNadi,andJoseph tothisissuecouldinvolvemoretypesofASTnodestobroaden Hejderup(Eds.).ACM,508–512. the structured natural language rules, thereby enabling a more [18] ZhangyinFeng,DayaGuo,DuyuTang,NanDuan,XiaochengFeng,MingGong, LinjunShou,BingQin,TingLiu,DaxinJiang,andMingZhou.2020.CodeBERT: thoroughintegrationofcommentinformation. APre-TrainedModelforProgrammingandNaturalLanguages.InFindingsof Experimentsonthelargerpre-trainedmodel.Inthisexperiment, theAssociationforComputationalLinguistics:EMNLP2020,OnlineEvent,16-20 weevaluateSCALEonthreepre-trainedmodels.Thesemodelsare November2020(FindingsofACL,Vol.EMNLP2020),TrevorCohn,YulanHe,and YangLiu(Eds.).AssociationforComputationalLinguistics,1536–1547. allrepresentativeandhaveshownstate-of-the-artperformanceon [19] DanielFried,ArmenAghajanyan,JessyLin,SidaWang,EricWallace,FredaShi, |
benchmarks.However,thesizeofthesemodelsislessthan1B.In RuiqiZhong,Wen-tauYih,LukeZettlemoyer,andMikeLewis.2022.InCoder:A GenerativeModelforCodeInfillingandSynthesis.CoRRabs/2204.05999(2022). thefuture,weplantovalidatetheeffectivenessofSCALEonlarger [20] MichaelFuandChakkritTantithamthavorn.2022.LineVul:ATransformer-based LLMssuchasCodeLlama[47]. Line-LevelVulnerabilityPrediction.InMSR.ACM,608–620.ISSTA2024,16-20September,2024,Vienna,Austria TrovatoandTobin,etal. [21] MichaelFu,ChakkritTantithamthavorn,VanNguyen,andTrungLe.2023.Chat- ProceedingsofDeepLearningInsideOut:The3rdWorkshoponKnowledgeExtraction GPTforVulnerabilityDetection,Classification,andRepair:HowFarAreWe? andIntegrationforDeepLearningArchitectures,DeeLIO@ACL2022,Dublin,Ireland CoRRabs/2310.09810(2023). andOnline,May27,2022.AssociationforComputationalLinguistics,100–114. [22] ShuzhengGao,WenxinMao,CuiyunGao,LiLi,XingHu,XinXia,andMichaelR. [41] ShuaiLu,DayaGuo,ShuoRen,JunjieHuang,AlexeySvyatkovskiy,Ambrosio Lyu.2024.LearningintheWild:TowardsLeveragingUnlabeledDataforEffec- Blanco,ColinB.Clement,DawnDrain,DaxinJiang,DuyuTang,GeLi,Lidong tivelyTuningPre-trainedCodeModels.CoRRabs/2401.01060(2024). Zhou,LinjunShou,LongZhou,MicheleTufano,MingGong,MingZhou,Nan [23] ShuzhengGao,Xin-ChengWen,CuiyunGao,WenxuanWang,HongyuZhang, Duan,NeelSundaresan,ShaoKunDeng,ShengyuFu,andShujieLiu.2021. andMichaelR.Lyu.2023. WhatMakesGoodIn-ContextDemonstrationsfor CodeXGLUE:AMachineLearningBenchmarkDatasetforCodeUnderstanding CodeIntelligenceTaskswithLLMs?.In38thIEEE/ACMInternationalConference andGeneration.InProceedingsoftheNeuralInformationProcessingSystemsTrack onAutomatedSoftwareEngineering,ASE2023,Luxembourg,September11-15,2023. onDatasetsandBenchmarks1,NeurIPSDatasetsandBenchmarks2021,December IEEE,761–773. 2021,virtual,JoaquinVanschorenandSai-KitYeung(Eds.). [24] GPT3.5-instruc.2022.GPT3.5-instruc.https://platform.openai.com/docs/models. [42] GaryMcGrawandBrucePotter.2004. SoftwareSecurityTesting. IEEESecur. [25] DayaGuo,ShuaiLu,NanDuan,YanlinWang,MingZhou,andJianYin.2022. Priv.2,5(2004),81–85. UniXcoder:UnifiedCross-ModalPre-trainingforCodeRepresentation.InPro- [43] ChaoNi,XinYin,KaiwenYang,DehaiZhao,ZhenchangXing,andXinXia.2023. ceedingsofthe60thAnnualMeetingoftheAssociationforComputationalLinguistics DistinguishingLook-AlikeInnocentandVulnerableCodebySubtleSemantic (Volume1:LongPapers),ACL2022,Dublin,Ireland,May22-27,2022,Smaranda RepresentationLearningandExplanation.CoRRabs/2308.11237(2023). Muresan,PreslavNakov,andAlineVillavicencio(Eds.).AssociationforCompu- [44] OpenAI.2023.GPT-4TechnicalReport.CoRRabs/2303.08774(2023). tationalLinguistics,7212–7225. [45] YunPeng,ChaozhengWang,WenxuanWang,CuiyunGao,andMichaelR.Lyu. [26] DayaGuo,ShuoRen,ShuaiLu,ZhangyinFeng,DuyuTang,ShujieLiu,Long 2023.GenerativeTypeInferenceforPython.CoRRabs/2307.09163(2023). Zhou,NanDuan,AlexeySvyatkovskiy,ShengyuFu,MicheleTufano,ShaoKun [46] BenPrystawskiandNoahD.Goodman.2023.Whythinkstep-by-step?Reasoning Deng,ColinB.Clement,DawnDrain,NeelSundaresan,JianYin,DaxinJiang, emergesfromthelocalityofexperience.CoRRabs/2304.03843(2023). andMingZhou.2021.GraphCodeBERT:Pre-trainingCodeRepresentationswith [47] BaptisteRozière,JonasGehring,FabianGloeckle,StenSootla,ItaiGat,Xi- DataFlow.In9thInternationalConferenceonLearningRepresentations,ICLR2021, aoqingEllenTan,YossiAdi,JingyuLiu,TalRemez,JérémyRapin,Artyom VirtualEvent,Austria,May3-7,2021.OpenReview.net. Kozhevnikov,IvanEvtimov,JoannaBitton,ManishBhatt,CristianCanton-Ferrer, [27] TongHe,WeilinHuang,YuQiao,andJianYao.2016.Text-AttentionalConvolu- AaronGrattafiori,WenhanXiong,AlexandreDéfossez,JadeCopet,FaisalAzhar, tionalNeuralNetworkforSceneTextDetection.IEEETrans.ImageProcess.25,6 HugoTouvron,LouisMartin,NicolasUsunier,ThomasScialom,andGabrielSyn- (2016),2529–2541. naeve.2023.CodeLlama:OpenFoundationModelsforCode.CoRRabs/2308.12950 [28] XinyiHou,YanjieZhao,YueLiu,ZhouYang,KailongWang,LiLi,XiapuLuo, (2023). DavidLo,JohnC.Grundy,andHaoyuWang.2023.LargeLanguageModelsfor [48] RebeccaL.Russell,LouisY.Kim,LeiH.Hamilton,TomoLazovich,JacobHarer, SoftwareEngineering:ASystematicLiteratureReview. CoRRabs/2308.10620 OnurOzdemir,PaulM.Ellingwood,andMarcW.McConley.2018.Automated (2023). VulnerabilityDetectioninSourceCodeUsingDeepRepresentationLearning.In [29] Huggingfacehub.2023.HuggingFace.https://huggingface.co/. ICMLA.IEEE,757–762. |
[30] IBM.2023.CostofaDataBreachReport2023. https://www.ibm.com/reports/ [49] Statista.2023.CommonITvulnerabilitiesandexposuresworldwide2009-2023. data-breach https://www.statista.com/statistics/ [31] Israel.[n.d.].Checkmarx. https://www.checkmarx.com/. [50] YuleiSui,DingYe,andJinglingXue.2012.Staticmemoryleakdetectionusing [32] HongzheLi,TaebeomKim,MunkhbayarBat-Erdene,andHeejoLee.2013.Soft- full-sparsevalue-flowanalysis.InInternationalSymposiumonSoftwareTesting wareVulnerabilityDetectionUsingBackwardTraceAnalysisandSymbolic andAnalysis,ISSTA2012,Minneapolis,MN,USA,July15-20,2012,MatsPerErik Execution.In2013InternationalConferenceonAvailability,ReliabilityandSe- HeimdahlandZhendongSu(Eds.).ACM,254–264. curity,ARES2013,Regensburg,Germany,September2-6,2013.IEEEComputer [51] HugoTouvron,ThibautLavril,GautierIzacard,XavierMartinet,Marie-Anne Society,446–454. Lachaux,TimothéeLacroix,BaptisteRozière,NamanGoyal,EricHambro,Faisal [33] RaymondLi,LoubnaBenAllal,YangtianZi,NiklasMuennighoff,DenisKocetkov, Azhar,AurélienRodriguez,ArmandJoulin,EdouardGrave,andGuillaumeLam- ChenghaoMou,MarcMarone,ChristopherAkiki,JiaLi,JennyChim,QianLiu, ple.2023. LLaMA:OpenandEfficientFoundationLanguageModels. CoRR EvgeniiZheltonozhskii,TerryYueZhuo,ThomasWang,OlivierDehaene,Mishig abs/2302.13971(2023). Davaadorj,JoelLamy-Poirier,JoãoMonteiro,OlehShliazhko,NicolasGontier, [52] HugoTouvron,LouisMartin,KevinStone,PeterAlbert,AmjadAlmahairi,Yas- NicholasMeade,ArmelZebaze,Ming-HoYee,LogeshKumarUmapathi,Jian mineBabaei,NikolayBashlykov,SoumyaBatra,PrajjwalBhargava,ShrutiBhos- Zhu,BenjaminLipkin,MuhtashamOblokulov,ZhiruoWang,RudraMurthyV, ale,DanBikel,LukasBlecher,CristianCanton-Ferrer,MoyaChen,GuillemCucu- JasonStillerman,SivaSankalpPatel,DmitryAbulkhanov,MarcoZocca,Manan rull,DavidEsiobu,JudeFernandes,JeremyFu,WenyinFu,BrianFuller,Cynthia Dey,ZhihanZhang,NourMoustafa-Fahmy,UrvashiBhattacharyya,WenhaoYu, Gao,VedanujGoswami,NamanGoyal,AnthonyHartshorn,SagharHosseini, SwayamSingh,SashaLuccioni,PauloVillegas,MaximKunakov,FedorZhdanov, RuiHou,HakanInan,MarcinKardas,ViktorKerkez,MadianKhabsa,Isabel ManuelRomero,TonyLee,NadavTimor,JenniferDing,ClaireSchlesinger,Hailey Kloumann,ArtemKorenev,PunitSinghKoura,Marie-AnneLachaux,Thibaut Schoelkopf,JanEbert,TriDao,MayankMishra,AlexGu,JenniferRobinson, Lavril,JenyaLee,DianaLiskovich,YinghaiLu,YuningMao,XavierMartinet, CarolynJaneAnderson,BrendanDolan-Gavitt,DanishContractor,SivaReddy, TodorMihaylov,PushkarMishra,IgorMolybog,YixinNie,AndrewPoulton, DanielFried,DzmitryBahdanau,YacineJernite,CarlosMuñozFerrandis,Sean JeremyReizenstein,RashiRungta,KalyanSaladi,AlanSchelten,RuanSilva, Hughes,ThomasWolf,ArjunGuha,LeandrovonWerra,andHarmdeVries.2023. EricMichaelSmith,RanjanSubramanian,XiaoqingEllenTan,BinhTang,Ross StarCoder:maythesourcebewithyou!CoRRabs/2305.06161(2023). Taylor,AdinaWilliams,JianXiangKuan,PuxinXu,ZhengYan,IliyanZarov, [34] WenLi,HaipengCai,YuleiSui,andDavidManz.2020.PCA:memoryleakdetec- YuchenZhang,AngelaFan,MelanieKambadur,SharanNarang,AurélienRo- tionusingpartialcall-pathanalysis.InESEC/FSE’20:28thACMJointEuropean driguez,RobertStojnic,SergeyEdunov,andThomasScialom.2023. Llama2: SoftwareEngineeringConferenceandSymposiumontheFoundationsofSoftware OpenFoundationandFine-TunedChatModels.CoRRabs/2307.09288(2023). Engineering,VirtualEvent,USA,November8-13,2020,PremDevanbu,MyraB. [53] LilapatiWaikhomandRiponPatgiri.2023.Asurveyofgraphneuralnetworksin Cohen,andThomasZimmermann(Eds.).ACM,1621–1625. variouslearningparadigms:methods,applications,andchallenges.Artif.Intell. [35] YueLi,TianTan,AndersMøller,andYannisSmaragdakis.2018.Precision-guided Rev.56,7(2023),6295–6364. contextsensitivityforpointeranalysis.Proc.ACMProgram.Lang.2,OOPSLA [54] XiaomengWang,TaoZhang,RunpuWu,WeiXin,andChangyuHou.2018. (2018),141:1–141:29. CPGVA:CodePropertyGraphbasedVulnerabilityAnalysisbyDeepLearning. [36] YueLi,TianTan,AndersMøller,andYannisSmaragdakis.2020.APrincipled In10thInternationalConferenceonAdvancedInfocommTechnology,ICAIT2018, ApproachtoSelectiveContextSensitivityforPointerAnalysis. ACMTrans. Stockholm,Sweden,August12-15,2018.IEEE,184–188. Program.Lang.Syst.42,2(2020),10:1–10:40. [55] YueWang,WeishiWang,ShafiqR.Joty,andStevenC.H.Hoi.2021. CodeT5: |
[37] YiLi,ShaohuaWang,andTienN.Nguyen.2021.Vulnerabilitydetectionwith Identifier-awareUnifiedPre-trainedEncoder-DecoderModelsforCodeUnder- fine-grainedinterpretations.InESEC/SIGSOFTFSE.ACM,292–303. standingandGeneration.InProceedingsofthe2021ConferenceonEmpirical [38] ZhenLi,DeqingZou,ShouhuaiXu,HaiJin,YaweiZhu,andZhaoxuanChen.2022. MethodsinNaturalLanguageProcessing,EMNLP2021,VirtualEvent/Punta SySeVR:AFrameworkforUsingDeepLearningtoDetectSoftwareVulnerabilities. Cana,DominicanRepublic,7-11November,2021,Marie-FrancineMoens,Xuanjing IEEETrans.DependableSecur.Comput.19,4(2022),2244–2258. Huang,LuciaSpecia,andScottWen-tauYih(Eds.).AssociationforComputational [39] ZhenLi,DeqingZou,ShouhuaiXu,XinyuOu,HaiJin,SujuanWang,Zhijun Linguistics,8696–8708. Deng,andYuyiZhong.2018.VulDeePecker:ADeepLearning-BasedSystemfor [56] JasonWei,XuezhiWang,DaleSchuurmans,MaartenBosma,BrianIchter,Fei VulnerabilityDetection.In25thAnnualNetworkandDistributedSystemSecurity Xia,EdH.Chi,QuocV.Le,andDennyZhou.2022.Chain-of-ThoughtPrompting Symposium,NDSS2018,SanDiego,California,USA,February18-21,2018.The ElicitsReasoninginLargeLanguageModels.InNeurIPS. InternetSociety. [57] Xin-ChengWen,YupanChen,CuiyunGao,HongyuZhang,JieM.Zhang,and [40] JiachangLiu,DinghanShen,YizheZhang,BillDolan,LawrenceCarin,and QingLiao.2023.VulnerabilityDetectionwithGraphSimplificationandEnhanced WeizhuChen.2022. WhatMakesGoodIn-ContextExamplesforGPT-3?.In GraphRepresentationLearning.In45thIEEE/ACMInternationalConferenceonSCALE:ConstructingStructuredNaturalLanguageCommentTreesforSoftwareVulnerabilityDetection ISSTA2024,16-20September,2024,Vienna,Austria SoftwareEngineering,ICSE2023,Melbourne,Australia,May14-20,2023.IEEE, IEEE/ACM44thInternationalConferenceonSoftwareEngineering,ICSE2022,Pitts- 2275–2286. burgh,PA,USA,May25-27,2022.ACM,2365–2376. [58] Xin-ChengWen,CuiyunGao,JiaxinYe,ZhihongTian,YanJia,andXuanWang. [63] JunweiZhang,ZhongxinLiu,XingHu,XinXia,andShanpingLi.2023.Vulnera- 2022. Meta-PathBasedAttentionalGraphLearningModelforVulnerability bilityDetectionbyLearningFromSyntax-BasedExecutionPathsofCode.IEEE Detection.CoRRabs/2212.14274(2022). Trans.SoftwareEng.49,8(2023),4196–4212. [59] Xin-ChengWen,XinchenWang,CuiyunGao,ShaohuaWang,YangLiu,and [64] QinkaiZheng,XiaoXia,XuZou,YuxiaoDong,ShanWang,YufeiXue,Zihan ZhaoquanGu.2023. WhenLessisEnough:PositiveandUnlabeledLearning Wang,LeiShen,AndiWang,YangLi,etal.2023. CodeGeeX:APre-Trained ModelforVulnerabilityDetection.(2023),345–357. ModelforCodeGenerationwithMultilingualEvaluationsonHumanEval-X. [60] DavidA.Wheeler.[n.d.].Flawfinder. https://dwheeler.com/flawfinder/ CoRRabs/2303.17568(2023). [61] FangWu,JigangWang,JiqiangLiu,andWeiWang.2017.Vulnerabilitydetection [65] YaqinZhou,ShangqingLiu,JingKaiSiow,XiaoningDu,andYangLiu.2019.De- withdeeplearning.In20173rdIEEEinternationalconferenceoncomputerand vign:EffectiveVulnerabilityIdentificationbyLearningComprehensiveProgram communications(ICCC).IEEE,1298–1302. SemanticsviaGraphNeuralNetworks.InAdvancesinNeuralInformationPro- [62] YuemingWu,DeqingZou,ShihanDou,WeiYang,DuoXu,andHaiJin.2022. cessingSystems32:AnnualConferenceonNeuralInformationProcessingSystems VulCNN:AnImage-inspiredScalableVulnerabilityDetectionSystem.In44th 2019,NeurIPS2019.10197–10207. |
2403.19112 Uncover the Premeditated Attacks: Detecting Exploitable Reentrancy Vulnerabilities by Identifying Attacker Contracts ShuoYang JiachiChen∗ MingyuanHuang SunYat-senUniversity SunYat-senUniversity SunYat-senUniversity Zhuhai,China Zhuhai,China Zhuhai,China yangsh233@mail2.sysu.edu.cn chenjch86@mail.sysu.edu.cn huangmy83@mail2.sysu.edu.cn ZibinZheng YuanHuang SunYat-senUniversity SunYat-senUniversity Zhuhai,China Zhuhai,China zhzibin@mail.sysu.edu.cn huangyuan5@mail.sysu.edu.cn ABSTRACT KEYWORDS Reentrancy,anotoriousvulnerabilityinsmartcontracts,hasledto SmartContract;DataflowAnalysis;Reentrancy;AttackerIdentifi- millionsofdollarsinfinancialloss.However,currentsmartcontract cation;Ethereum vulnerabilitydetectiontoolssufferfromahighfalsepositiverate inidentifyingcontractswithreentrancyvulnerabilities.Moreover, ACMReferenceFormat: ShuoYang,JiachiChen,MingyuanHuang,ZibinZheng,andYuanHuang. onlyasmallportionofthedetectedreentrantcontractscanactually 2024.UncoverthePremeditatedAttacks:DetectingExploitableReentrancy beexploitedbyhackers,makingthesetoolslesseffectiveinsecuring VulnerabilitiesbyIdentifyingAttackerContracts.In2024IEEE/ACM46th theEthereumecosysteminpractice. InternationalConferenceonSoftwareEngineering(ICSE’24),April14–20, Inthispaper,weproposeBlockWatchdog,atoolthatfocuses 2024,Lisbon,Portugal.ACM,NewYork,NY,USA,12pages.https://doi.org/ ondetectingreentrancyvulnerabilitiesbyidentifyingattackercon- 10.1145/3597503.3639153 tracts.Theseattackercontractsaredeployedbyhackerstoexploit vulnerablecontractsautomatically.Byfocusingonattackercon- tracts,BlockWatchdogeffectivelydetectstrulyexploitablereen- 1 INTRODUCTION trancyvulnerabilitiesbyidentifyingreentrantcallflow.Addition- Inrecentyears,Ethereumhasexperiencedsignificantgrowthin ally,BlockWatchdogiscapableofdetectingnewtypesofreentrancy popularity and market cap [15], primarily due to its ability to vulnerabilitiescausedbypoordesignswhenusingERCtokensor supportawiderangeofdecentralizedapplications(DApps)[55], user-definedinterfaces,whichcannotbedetectedbycurrentrule- suchasdecentralizedfinance(DeFi)[53]andnon-fungibletokens basedtools.WeimplementBlockWatchdogusingcross-contract (NFTs)[57].Thisismadepossiblethroughtheuseofsmartcon- staticdataflowtechniquesbasedonattacklogicobtainedfroman tracts[59],whichareTuring-completeprogramsthatrunonthe empiricalstudythatanalyzesattackercontractsfrom281attack blockchain.However,asthevalueofEthereumcontinuestorise, incidents.BlockWatchdogisevaluatedon421,889Ethereumcon- attackersareincreasinglytargetingcontractswithvulnerabilities tractbytecodesandidentifies113attackercontractsthattarget159 that can be exploited to make unfair profits. Reentrancy is one victimcontracts,leadingtothetheftofEtherandtokensvalued oftheinfamousvulnerabilities,whichhascausedhugefinancial atapproximately908.6millionUSD.Notably,only18oftheiden- losses[60]sincethe150millionUSDDAOattackin2016[25],and tified159victimcontractscanbereportedbycurrentreentrancy newreentrancyattackskeeppoppingupinmoreandmorecomplex detectiontools. forms.Forexample,anattackerexploitedareentrancyvulnerability todrainapproximately1,300ETH(1.43millionUSD)fromtheNFT CCSCONCEPTS moneymarketplatformcalledOmni[1]byusingthehookfunction •Softwareanditsengineering→Softwareverificationand onERC721Received()declaredintheERC721standard[18]. validation. Numerousstudieshavefocusedondetectingvulnerabilitiesin smartcontracts[16,23,28],proposingvariousmethodssuchas staticanalysisanddynamictestingtoidentifypotentialissues.How- ∗correspondingauthor ever,theseworksfacetwomainlimitations.First,thereisahigh false-positiverateindetectingreentrancyvulnerabilities[60],as Permissiontomakedigitalorhardcopiesofallorpartofthisworkforpersonalor theycannotcorrectlydetectsomeprotectionpatterns.Furthermore, classroomuseisgrantedwithoutfeeprovidedthatcopiesarenotmadeordistributed forprofitorcommercialadvantageandthatcopiesbearthisnoticeandthefullcitation thesemethodsmainlyfocusonreentrancycausedbycall.value() onthefirstpage.Copyrightsforcomponentsofthisworkownedbyothersthanthe operations,whichcannotcovermorecomplexreentrancyvulner- author(s)mustbehonored.Abstractingwithcreditispermitted.Tocopyotherwise,or abilities(leadingtofalsenegatives)causedbypoordesignswhen republish,topostonserversortoredistributetolists,requirespriorspecificpermission and/orafee.Requestpermissionsfrompermissions@acm.org. usingstandardERCtokens,e.g.,ERC721,oruser-definedinterfaces ICSE2024,April2024,Lisbon,Portugal (seeSection2.2).Second,only2.68%ofcontractswithreentrancy ©2024Copyrightheldbytheowner/author(s).PublicationrightslicensedtoACM. vulnerabilitiescantrulybeexploitedbyhackers,andonly0.4%of ACMISBN979-8-4007-0217-4/24/04...$15.00 https://doi.org/10.1145/3597503.3639153 theEthersatstakecouldbeexploited[35].Real-worldattackers 4202 raM 82 ]RC.sc[ |
1v21191.3042:viXraICSE2024,April2024,Lisbon,Portugal ShuoYang,JiachiChen,MingyuanHuang,ZibinZheng,andYuanHuang intendtoevaluatethecostandbenefitofanattack,butmostcon- • WeevaluatetheperformanceofBlockWatchdogonadataset tractsdonothavethebalancethatcanbeextracted.Specifically, consistingof421,889contractsbytecode.Ourexperiments onEthereum,only3%ofthecontractshaveanon-zerobalance. showthatBlockWatchdogidentifies113attackercontracts Thus,mostofthevulnerablecontractslabeledbythetoolscannot and 159 victim contracts, which hold Ethers and tokens beexploitedandarefalsealarms,whichmakesitlesseffectivein worthapproximately908.6millionUSD.Only18ofthe159 securingtheEthereumecosysteminpractice. victimscanbedetectedbythecurrenttools.Wepublicizethe Exploitingreentrancyvulnerabilitiesrequiresdeployingmali- sourcecodeofBlockWatchdogandtheexperimentalresults ciouscontractsthatinitiatecallbackstothevictimcontract.Inthis inourrepository1. paper,weshiftourfocusfromvulnerabilitydetectiontoanalyzing attackercontracts.Toinvestigatehowattackersimplementcallback 2 BACKGROUNDANDMOTIVATION logiconvictims,weconductanempiricalstudybyanalyzing281 2.1 SoliditySmartContracts attackincidentreportsfromvariousplatforms,e.g.,Twitter[49], Asmartcontractisaself-executingagreementthatisenforcedby Medium[2],andPeckshield[34],spanningfromJune2016toJuly therulesencodedinitscode[46].Solidityisthemostpopularpro- 2022.Theseplatformsprovidecomprehensiveandtimelydescrip- gramminglanguageforsmartcontractsonEthereum.Thebytecode tionsofattackincidents,whicharealsoadoptedbyotherworks[57]. andtransactionsofthedeployedsmartcontractsarepermanently Consequently,wesummarizethreetypesofreentrancyattacktypes storedontheblockchain[59].Theimmutabilityofsmartcontracts basedonthefunctionsthatattackercontractsusedtomakecall- ensuresthattheircodeandbehaviorcannotbemodifiedoncede- backs(seeSection3).Furthermore,weproposeBlockWatchdog,a ployed,andtheyexecuteautomaticallybasedontheirpredefined toolthatutilizescross-contractstaticdataflowtechniquestoiden- logic.EthereumVirtualMachine(EVM)isastack-basedvirtual tifyreentrancyattackercontracts.First,BlockWatchdogdecompiles machinethatexecutestransactionsbysplittingtheEVMbytecode thecontract’sbytecodetotheintermediaterepresentation(IR)and intooperationcodes(opcodes)andfollowingtheirinstructions. extractsflowandexternalcallinformationinthefunctions.Sec- ond,BlockWatchdogidentifiesthecontractsinthecallchainand constructsthecross-contractcontrolflowgraph(xCFG)andthe 2.2 Reentrancy cross-contractcallgraph(xCG)ofthecontractbasedondataflow Thereentrancyvulnerabilityhasresultedinsignificantfinancial rules.Then,ittracesallcallchainstoperformataintanalysisto lossesoverthepastfewyears.Therearemanyworksthatfocus determinewhethertheattackercanmanipulatethecallchain,mak- ondetectingreentranciescausedbycall.value()pattern[60].So- ingitselfcalledagaintoimplementreentrancy.Basedondetection liditysmartcontractshaveauniquemechanismthatrequiresany patternsdesignedincollaborationwithexternalcallanddataflow contractthatreceivesEtherstoimplementafallbackfunction.The information,BlockWatchdogreportswhetherthecontractisan fallbackfunctionwillbeexecutedifthecontractreceivesEther attackercontractornotandidentifiesvulnerablevictimcontracts. fromotheraddresses.IfthevictimcontracttransfersEtherstothe Intheexperiment,wefirstevaluateBlockWatchdogonourcol- maliciousattackercontract,themaliciousonecantakeoverthe lectedground-truthdataset,whichcontains18reentrancyattacker controlflowandrepetitivelycallthevictiminitsfallbackfunction. contracts.Then,werunBlockWatchdogonareal-worlddatasetcon- Manyattackershaveexploitedthisfallbackmechanismtodrain taining421,889contracts’bytecodesobtainedbyreplayingtransac- fundsfromvictims.Notonlythosecausedbycall.value(),there tionsfromblocknumber10millionto15.5millionontheEthereum aresomenewreentrancytypes.Forexample,Lenf.me[24]and mainnet.Theaveragedetectiontimeofitis17.66seconds.Further- Omni[1]wereattackedbythebaddesignofusingERC777[14] more,BlockWatchdogidentifies249attackersmartcontractsinthis andERC721[18]tokens,respectively. dataset,and113ofthemarelabeledastruepositives.Amongthem, Inaddition,poordesignwhenusinguser-definedinterfacescan 40are0-dayattackercontracts,whichinvolve159victimcontracts. alsoleadtoreentrancyissues.Figure1showstheattackercontract Ethersandtokensworthapproximately908.6millionUSDinthese thathacked8.2millionUSDthroughareentrancyattackonIVi- contractshavebeenstolenbyattackers.Furthermore,werunseven sor[19],aliquiditymanagementprotocolofUniswapV3[51].The toolsforreentrancyvulnerabilitydetectiononidentifiedvictim functiondelegatedTransferERC20()(L25)isdefinedbythedevelop- contracts;only18(11.3%)ofthemcanbecorrectlyreported. ers,whichisnotdeclaredintheERCtokenstandard.Theattacker Themaincontributionsofourworkareasfollows. contractinjectsexternalcallsintothefunctiondelegatedTransfer- ERC20()(L13-L17)invokedbythevictimcontractRewardHypervisor |
(L20).Indetail,theattackercontractinvokesthefunctiondeposit() • Weshiftthedetectionfocusfromvulnerablecontractsto (L8) of the contract RewardHypervisor. Then, RewardHypervisor attackercontracts,whichalleviatesthehighfalsepositive callsthedelegatedTransferERC20()(L25)ofcontractfrom,which problemandlimitedcapabilityofcurrenttoolsinfinding issetbytheattackercontractwithaddress(this),i.e.,theattacker reentrancy. contract itself (L25). However, the attacker makes a callback to • Wesummarizethreetypesofreentrancyattacksfromanem- RewardHypervisoragaintodepositagainonline8,whichmakes piricalstudyandintroduceBlockWatchdog,across-contract itsufferfromareentrancyvulnerability.ThecontractRewardsHy- staticdataflowanalysistooltofindattackercontractsand pervisordoesnotcontaincall.value()reentrancyvulnerabilitytype, vulnerablevictimcontractstheytarget.Additionally,Block- whichcurrentdetectiontoolsfocuson.Yet,itwasstillattackedby Watchdogisextensibleforuserstoprogrammorerulesto covernewattacktypes. 1https://github.com/shuo-young/BlockWatchdogUncoverthePremeditatedAttacks:DetectingExploitableReentrancyVulnerabilitiesbyIdentifyingAttackerContracts ICSE2024,April2024,Lisbon,Portugal themaliciousattackercontracttomakeunfairgainsduetothebad Furthermore,existingtoolscannotcovernewtypesofreentrancies designwhenusinguser-definedinterfacedelegatedTransferERC20(). causedbypoordesignwhenusingERCtokens,whichcanresult infalsenegatives.Thisisbecauserule-basedtoolshavelimited scalability,aseachrulecanonlycheckaspecificreentrancytype 1 // the decompiled IR of the attacker contract bytecode 2 contract Attacker { (e.g.,reentrancycausedbycall.value())andcannotcoveremerging 3 function 0x4a0b0c38() public payable { types,suchasnewERCstandards[33](e.g.,reentrancycausedby 4 0x28e();} ERC721andERC1155[13]),oruser-definedinterfaces,e.g.,dele- 5 gateTransferERC20()inFigure1. 6 function 0x28e() private { Toaddresstheselimitations,amoregeneraldetectionmethod 7 require(_pool.code.size); 8 v0, v1 = _pool.deposit(0x52b7d2dcc80cd2e4000000, isneededtoreducebothfalsepositivesandfalsenegatives.Reen- address(this), _admin); trancyvulnerabilitiesaremainlycharacterizedbythemutualin- 9 require(v0); vocationofthevictimcontractandtheattackercontractwithcall- 10 require(RETURNDATASIZE() >= 32); backflowfeatures,butvictimcontractscontainlimitedandnon- 11 return ;} homogeneousinformation,makingitchallengingtosummarizea 12 13 function delegatedTransferERC20(address varg0, address genericsignatureforrule-basedtools.Itmotivatesustorecover varg1, uint256 varg2) public payable { reentrancyfeaturesfromtheattackercontractsperspective. 14 require(msg.data.length - 4 >= 96); 15 _count += 1; 3 ATTACKERSMARTCONTRACTSFOR 16 if (_count < 2) { 17 0x28e();}} REENTRANCY 18 } Inthissection,wepresentanempiricalstudyaimedatidentify- 19 // the source code of the victim contract ingthecharacteristicsofattackercontractsinvolvedinhistorical 20 contract RewardsHypervisor { 21 function deposit(uint256 visrDeposit, address payable reentrancyattacks.Ourgoalistouncoverreentrancyvulnerabili- from, address to) external returns (uint256 tiesthatexistingtoolshavemissed.Weapproachtheanalysisof shares) { attackercontractsthroughadatacollectionprocess,followedby 22 ... adataanalysisandfeatureidentificationprocess,asillustratedin 23 if(isContract(from)) { 24 require(IVisor(from).owner() == msg.sender); Figure2anddescribedinsubsequentsubsections. 25 IVisor(from).delegatedTransferERC20(address(visr), address(this), visrDeposit);} 26 else { 27 visr.safeTransferFrom(from, address(this), visrDeposit);} 28 vvisr.mint(to, shares);} 29 } Figure1:ReentrancyattacktowardVisorFinance. Figure2:Workflowoffindingnewreentrancytypes. 2.3 PriorResearchandTheirLimitations 3.1 DataCollection Unexploitableforthedetectedcontracts. Previousresearch hasfocusedondetectingreentrancyvulnerabilities,butmostof Togainacomprehensiveunderstandingofattacks,itisnecessaryto thecontractsdetectedareeithertoycontractswithnovalueor collectandanalyzerelevantdata.Webeganbysearchingforattack cannotbeexploitedbyattackers[35].Specifically,only1.98%of reportspublishedbyreputableblockchainsecurityfirmssuchas the23,327reportedvulnerablecontractsfromsixacademicprojects PeckShield,as wellas information fromsocial media platforms havebeenexploitedsincedeployment,affectingonly0.27%ofthe likeTwitterandpublishingplatformslikeMedium.Intotal,we fundsinthecontracts[16,21,23,28,32,48].Thereasonisthat identified281incidentsthatoccurredbetweenJune2016andJuly themajorityofEtherortokensareheldbyonlyasmallnumber 2022.Foreachreport,werecordedkeyinformationsuchasthe ofvulnerablecontracts,whicharelucrativeforhackers,making targetproject,thevictimcontractaddress,theattacktime,andthe mostofthedetectedcontractsunexploitable.However,detecting associatedlosses.Allthedatacollectedandtheirsourcelinksare |
attackercontractscanhelpidentifytrulyexploitableyetvulnerable availableforpublicaccessinouropenrepository. contracts. 3.2 DataAnalysis Poorperformanceindetectingreentrancy.Existingreentrancy detectiontoolshaveanextremelyhighfalsepositiverate.More Attackercontractidentification. Aswedonotknowhowhack- than99.8%ofthereentrantcontractsdetectedbythetools[7,28, ersperformtheattack,weintendtofindtheattackercontractsto 29,39,48]arefalsepositives[60],asthesetoolsdonotdetectsome analyzetheattacklogicfromthecollecteddata.Specifically,two protectionpatterns,suchasthereentrancylock.Toreducefalsepos- ofourauthors,bothwithmorethantwoyearsofexperiencein itives,detectingattackercontractscanhelpfindthosehackerswho blockchainsecurity,manuallyanalyzedthe281incidentscollected aimattrulyexploitablecontractswithoutreentrancyprotections. using the open card sorting approach [43]. During the manualICSE2024,April2024,Lisbon,Portugal ShuoYang,JiachiChen,MingyuanHuang,ZibinZheng,andYuanHuang check,weidentifiedtwodistincttypesofattacks:thosedirectly theattackercontractautomaticallyexecutesandinitiatesexternal attackedbyexternallyownedaccounts(EOAs)ofhackersandthose callstothevictimcontracts.Notably,inreentrancyattacks,the attackedbyattackercontractsthathackersdeployed. attackercontractcanpassparameterstovictimcontracts,which makesthemcallbacktotheattackercontractagain,andtherecan Table1:AttackTypesObtainedfromCollectedData bemultiplevictimsinthiscallchain.AsshowninFigure3,wesum- marizethreetypesofreentrancybasedonthefunctionsutilizedby DoS BR IO RE IA CI CAD FL Others attackercontractstoperformreentrancy,i.e.,(1)fallback(),poor AC/EOA designswhenusing(2)ERCtokens,or(3)user-definedinterfaces. CA Specifically,theattackercontractcanimplementreentrancylogic (cid:71)(cid:35) (cid:32) (cid:35) (cid:32) (cid:35) (cid:35) (cid:35) (cid:32) (cid:71)(cid:35) (cid:47) (cid:47) (cid:47) (cid:47) (cid:47) (cid:47) (cid:47) (cid:47) (cid:47) inthefallback()functionwhenreceivingEthers.Itcanalsoinject callbacksintohookfunctionswhenusingERCtokens,e.g.,hook Wethenclassifytheattacktypesbasedonthenecessityofanat- tackercontractandtheavailabilityoftheattackercontract’ssource functiononERC721ReceivedwhenusingERC721,oruser-defined interfaces,e.g.,thecaseshowninFigure1,toimplementreentrancy. code.Table1showstheeighttypesofattackthatweidentified fromour281collectedincidents.Weusethe“Others”categoryto 3.3 AttackerContractFeatures coverattacksthattargetspecificdesignflawsofvictims,e.g.,infi- niteapprovaltovulnerablecontracts[37].The and symbolsin Figure4showsanexamplethatillustratesthehigh-levelfeatures thecolumn“AttackerContract”representattacktypesthatrequire ofthereentrancyattackfocusingonthecallflow.Toperformthe (cid:32) (cid:35) deployingtheattackercontract(AC)orusingEOAtransactions, reentrancyattack,theattackercontract(1)firstcallsthevictim respectively. The symbol represents attack typesthat do not contract(stepiinFigure4)tomakethevictiminvokeacallback requirethedeploymentofanattackercontractinsomecases.The (stepii)totheattacker’shookfunctionortransferEthertothe (cid:71)(cid:35) symbolinthe“CodeAvailability”(CA)columnrepresentsat- attackercontract(stepiii),(2)thentheattackercontractcallsthe tackercontractswhosesourcecodeisnotavailable.Amongthe281 victim again in the hook function or the fallback function, and (cid:47) samples,wefound31attackercontractsfrom28reports,classified reenters(stepiv)toinvokefunctionsthatcangenerateunfairprofits asDenialofService(DoS),BadRandomness(BR),Reentrancy(RE), (step v), (3) next, the profits can be transferred to the attacker Flashloan(FL),andOthers.AttackssuchasIntegerOverflow(IO), EOA (step vi) to complete the reentrancy attack. This call flow ImproperAuthentication(IA),CallInjection(CI),andCall-after- informationshowshowtheattackercontractinteractswiththe destruct(CAD),whichdonotinvolveattackercontracts,areout victimcontract.Thesummarizedthreetypesofreentrancyhelpus ofthescopeofouranalysis.Asthispaperfocusesonnewtypes identifythereentrancyfromfunction-levelcallinformation.The ofreentrancyvulnerabilitiesmissedbyexistingvulnerabilityde- designofourmethodshowninthefollowingsectionisbasedon tectiontools,wewillillustratereentrancyvulnerabilitiesfromthe thesefeaturesobtainedfromourempiricalstudy. perspectiveofthe18reentrancyattackercontractscollected. Figure3:Anoverviewofreentrancyattacks. Figure4:Anexampletoillustratereentrancyattack. Decompilationandunderstanding. Togainadeeperunder- 4 METHODOLOGY standingoftheattackerbehaviorsemployedbyreentrancyattacker contracts,wecollectedthebytecodeofattackercontractsforanaly- Inthissection,weintroducetheBlockWatchdogtool,whichcan sis,asnoneoftheidentifiedattackercontractsreleasedtheirsource detectattackercontractsthatperformreentrancyattacks.Wefirst |
codetothepublic.WedecompiledtheEVMbytecodetorecovera giveanoverviewoftheapproachandthenprovidethedetailsfrom readableintermediaterepresentation(IR)oftheattackercontract. theperspectivesofflowinformationextraction,cross-contractstatic Wethenfollowedtheattackprocessanddescriptionaccordingto analysis,andattackercontractdetection. thereporttounderstandhowtheattackerimplementstheattack logicfromitsbytecode.Figure3providesanoverviewofhowat- 4.1 Overview tackercontractsexploitvictimcontracts.Thehackerfirstprograms BlockWatchdogconsistsofthreemaincomponents:Decompiler, theattackercontractanddeploysitontheblockchain.Subsequently, Cross-ContractDataflowAnalyzer,andAttackIdentifier.Figure5UncoverthePremeditatedAttacks:DetectingExploitableReentrancyVulnerabilitiesbyIdentifyingAttackerContracts ICSE2024,April2024,Lisbon,Portugal showsanoverviewoftheBlockWatchdogapproach.Thetoolcan decompilation,whichspecifieswhichfunctionscanbeinvoked acceptacontractbytecodeorarealaddressonEthereumasinput.If ineachexternalcall.Foreachexternalcallidentifiedinthecaller acontractaddressisprovided,thetoolretrievesthebytecodefrom contract,weobtainthecalleecontractandfunctionsignatureto theWeb3API[52].BlockWatchdogdecompilesthebytecodetothe locatethecalleesiteofthecontractbeingcalled,allowingustocon- IRandextractscriticalflowinformationfordataflowanalysisin structtheentirexCFGandxCGforinter-procedurecross-contract Decompiler.Next,theCross-contractDataflowAnalyzerconstructs analysis. thexCFGandxCGofthecontractaccordingtotheinformation Flowandexternalcallinformationextraction. Toextractthe obtainedfromthedecompilation.WeusexCFGandxCGtobridge flowinformationfromacontract,wefirstobtaineveryentrance theflowinformationofallcontractsinthecallchainsfortaint andexitofthecontract.Foreverypublicfunctionidentifiedbythe analysis.Taintsoriginatingfromtheattackercontractarepropa- decompiler,weextractitsfunctionargumentsandreturnparame- gatedthroughthefunctioncallargumentsandreturnsbasedon ters,whichdenotethestartandendpointsofthedataflowwithin designedtransferruleswhiletracingallpossiblecallchainsinthe thefunction,respectively.Functionargumentscanalsoflowtothe xCG.Finally,theAttackIdentifieridentifiesandreportsthethree parametersofexternalcallsmadewithinthefunction,whilethe attacktypesbasedonourdetectionpatternsbasedontheresultof returnvaluesofexternalcallscanflowbacktothefunction’sreturn thetaintflowanalysis. parameters.Therefore,wedesignfivedataflowrulesinTable2for ToimplementBlockWatchdog,weadoptapublicnodeprovided eachpublicfunctioninthecontract.Weillustrateeachrulebased byAlchemy[3]torequestdatafromtheblockchain.Specifically, onFigure6.TakingtheFuncArgToCallArgandFuncArgToCalleeas weusetheWeb3APIgetCodetofetchthebytecodeofacontract anexample,inFigure6,functionargumentv2ofthefunctionbar() andusegetStorageAt toobtainthestoragedatainaspecificslot (L2-L10)flowstotheargumentsoftheexternalcalltarget.foo()(L4) andoffsetfromacontractaccount.Fordecompilation,weusethe byruleFuncArgToCallArg.Incontracttarget,thefunctionargument EVMbytecodedecompilerElipmoc,whichimprovesoverallthe v1offoo()(L16-L22),whichissetbythecallercontractfrom(line notable past decompilers [17, 22]. Elipmoc can disassemble the (i)inFigure6),canflowtothecalleevariablev1ofthecalloper- EVMbytecodeintoEVMopcodesandconstructthecontrolflow ationv1.hook(v2)(L19)throughruleFuncArgToCallee(line(ii)in graphbasedonidentifyingflow-relatedopcodeslikeJUMPand Figure6).Bycombiningthesetworules,wecanobtaintheflow JUMPI. The function borders and the IR are then recovered for informationthataddress(this)(L4)setbycontractfromcanflow furtheranalysis. tothecalleevariablev1(L19)incontracttarget.Inthiscase,the contractfromcanmakethecontracttarget callitsimplemented functionhook throughthedataflowprocess.Then,thecallflow returnstothecontractfrom,whichmakesitcapableofcallingback tothetarget.foo()again(L12),andleadstothereentrancy. Table2:DataflowRulesinIntra-ProcedureAnalysis FlowType Meaning FuncArgToCallArg flowfromfunctionargumentstocallargu- ments FuncArgToFuncRet flowfromfunctionargumentstofunction returns Figure5:AnoverviewoftheapproachofBlockWatchdog. FuncArgToCallee flowfromfunctionargumentstocalleevari- ables 4.2 FlowInformationExtraction CallRetToCallArg flowfromcallreturnstocallarguments Whenanalyzinganinputcontract,thefirststepinBlockWatchdog CallRetToFuncRet flowfromcallreturnstofunctionreturns istodecompileitsEVMbytecodetotheIR.IntheDecompilercom- ponent,weextractflowinformationfromtheIRtoenabledataflow Additionally, we focus on whether the input contract imple- analysisandattackervectoridentification. ments an external call in the hook or fallback function, which Constantcontractaddressandfunctionsignatureidentifica- attackerscanleveragetomakeothercontractscallbackandsuc- tion. Toconductcross-contractstaticdataflowanalysis,weneed ceedinreenteringtheattackercontract.Wesummarizesixhook toidentifythetargetcontractsandfunctionsthattheinputcontract functionsfromfiveEthereumImprovementProposals(EIPs)[10] intendstocall.Basedonouranalysisofpreviousattackincidents, thatwefindtobeinvolvedinourcollectedreentrancyattacker |
we observe that attacker contracts typically hard-code the con- contracts,asshowninTable3.Noticeably,welistthesehookfunc- tractaddresswithwhichtheywanttointeractorstorethetarget tionstoillustratethefeaturesoftheattackercontracts;ourBlock- contract’saddressinstorage.Therefore,weusethedecompilerto Watchdogdoesnotrelyonthesespecificfunctionsignaturesbut identifytheconstantvalue(conformingtoEIP-55[11])ofthecallee focusesonthecallflowfeatures.Furthermore,thefallbackfunc- contractaddress.Theslotnumberwithspecificoffsetstolocate tioncalledwhenreceivingEthersanduser-definedinterfaces,e.g., thestorageaddresscanbeobtainedthroughtheWeb3API getStor- IVisor.delegatedTransferERC20(),canalsobeusedtoperformreen- ageAt.Additionally,weidentifythefunctionsignaturesthrough trancy.Therefore,basedontheexternalcallinformationfoundinICSE2024,April2024,Lisbon,Portugal ShuoYang,JiachiChen,MingyuanHuang,ZibinZheng,andYuanHuang Algorithm1:Cross-contractStaticAnalysisforIdentifyingAttacks input:𝐶,theinputcontractbytecode output:𝐴𝐶←[],thelistofpossibleattackcallchains 1:𝐸 𝑓 ←𝑓𝑖𝑛𝑑𝐹𝑢𝑛𝑐𝑡𝑖𝑜𝑛𝑠𝑊𝑖𝑡ℎ𝐸𝑥𝑡𝑒𝑟𝑛𝑎𝑙𝐶𝑎𝑙𝑙(𝐶) 2:foreachfunction𝑓 ∈𝐸 𝑓 do 3: 𝑃𝑐 ←𝑠𝑒𝑎𝑟𝑐ℎ𝐶𝑎𝑙𝑙𝑃𝑎𝑡ℎ𝑠𝐵𝑦𝐷𝐹𝑆(𝑓) 4: 𝑠←𝑔𝑒𝑡𝑆𝑜𝑢𝑟𝑐𝑒(𝑓) 5: foreachpath𝑝∈𝑃𝑐do 6: 𝑡 ←𝑔𝑒𝑡𝑃𝑜𝑠𝑠𝑖𝑏𝑙𝑒𝑆𝑖𝑛𝑘(𝑝) 7: if𝑖𝑠𝑅𝑒𝑎𝑐ℎ𝑎𝑏𝑙𝑒(𝑠,𝑡,𝑟𝑢𝑙𝑒𝑠) 8: 𝐴𝐶←𝐴𝐶∪𝑝,𝑏𝑟𝑒𝑎𝑘 9:return𝐴𝐶 of the input contract. We obtain the bytecode of the interacted contractsbasedonthecontractaddressidentifiedduringdecompi- lation.Then,foreveryexternalcalloftheinputcontract,wefind thecall-targetcontractaddressandfunctionsignature.Basedon thetuple<callsite,caller_address,caller_funcSign,target_contract, target_funcSign>,wefindeverycallsitethatexecutestheCALL Figure6:Toycontractsforflowinformationillustration. opcodeanditscalltarget.WethenusetheDFSalgorithmtocon- structthexCFGandgatherallpossiblecallchainsoriginatingfrom thesetypesoffunctionsandflowinformationextractedduringthe thepublicfunctionsoftheinputcontracttoconstructxCGforthe intra-procedureanalysis,BlockWatchdogdetermineswhethera dataflowanalysis. reentrancyattackercontractispresent. 4.3.2 Cross-contractDataflowAnalysis. Wedefinethetaintedsource, sinksite,andtransferrulesinourdataflowanalysisforidentifying Table3:HookFunctionsDeclaredbyEIP attacksinTable4.ForacontractCanditsexternalcallf withargu- mentssetAintheexample,wedefineallexternalcallarguments𝐴 𝑠 Standard FunctionName FunctionSignature incontractCastainted.Then,foreverycontractcalled,wemark EIP-20 transferFrom 0x01c6adc3 everycalleevariablethatdeterminesthecalltargetaddress𝐶 as EIP-721 onERC721Received 0x150b7a02 𝑡 thesinksite.WeapplytherulesshowninTable2todetermine EIP-1155 onERC1155Received 0xf23a6e61 whetherthetaintedsourcecanflowtothesinksite.Ifthereisa EIP-777 tokensToSend 0x75ab9782 EIP-777 tokensReceived 0x0023de29 possiblepathforthatdataflowpath,itispossiblethattheinput EIP-1820 canImplementInterfaceForAddress 0x249cb3fa contractcanmakethecalledcontractcallaspecificaddressthatthe attackerdesigned,whichhelpsusfindwhetherthereisreentrancy. 4.3 Cross-contractStaticAnalysis Table4:DataflowRulesforIdentifyingAttackerContracts Inthissubsection,wedescribehowweusedecompiledintermediate representation(IR)andintra-procedureinformationtoconstruct C.f(A),f isanexternalcalltocontractC;Aisthe Example thexCFGandxCGoftheattackercontractanditsinteractingcon- setofarguments tracts.Algorithm1presentsanoverviewofhowtoidentifythe Source externalcallargumentsset𝐴 𝑠 ofinputcontract attackercontract.Wefirstconstructthecallchainofeverypub- Rules 5intra-proceduredataflowrulesinTable2 licfunctionthatcontainsanexternalcall𝐸 𝑓 usingtheextracted Sink callee𝐶 𝑡 ofexternalcallsincalledcontracts flowinformation(L1).Then,weusethedepth-firstsearch(DFS) algorithmforeachpublicfunction𝑓 tofinditsexternalcalltarget contractsandfunctionstoconstructthexCFGandxCG(L2-L3). 4.4 AttackerContractDetection Weapplythetaintedsourceidentificationrulestofindthetainted Inthissubsection,wepresentspecificrulesfordetectingreentrancy source𝑠 intheinputcontract’sfunction(L4).Then,weusesink attacksintheattackercontractusingflowinformationandcross- identificationrulesforeachcallchainintheconstructedxCGtofind contractdataflowanalysis. sensitivevariables𝑡thatcancausetheattack(L6),suchasfunction Thereentrancyattackcanbereflectedinthecallchainthatwe argumentsflowingtocalleevariables.Todeterminewhethercon- recoverbycross-contractstaticanalysis.Specifically,wedetectthe tractCcansuccessfullymaketheothercontractcallbacktoitself, attackercontractthatcanperformareentrancyattackinthree weusethetransferrulesfromsourcetosinktoobtainreachability steps.Step1:Wefirstdeterminewhetherthereisacallpaththat (L7)andfindpossibleattackcallchains. causestaintedvariablestoflowtothesinksiteusingtheruleswe 4.3.1 xCFGConstruction&CallChainGathering. Toperformstatic designedinthecross-contractanalysisillustratedinSection4.3.2. dataflowanalysis,wefirstneedtoconstructthexCGandxCFG Forexample,inFigure6,theattackercancallfunctionbar()(L2-L10)UncoverthePremeditatedAttacks:DetectingExploitableReentrancyVulnerabilitiesbyIdentifyingAttackerContracts ICSE2024,April2024,Lisbon,Portugal toinvokeexternalcalltarget.foo()(L16-L22).Thefunctionargument 5.2 AnswertoRQ1:EffectivenessontheGround |
v1(L16)canflowtothecalleeoftheexternalcallv1.hook(v2)(L19) TruthDataset incontracttarget,whichmeanscontractfromcanmanipulatethe ToanswerRQ1,werunBlockWatchdogonourgroundtruthdataset calltargetofv1.hook().Wethenfindthetargetcallfunctionhook() with18attackercontractsfromourcollectedreports.BlockWatch- (L11-L12) of the reachable sink site v1.hook() (L19). Step 2: We dogcorrectlyreports15outof18reentrancyattackercontracts,as determine whether there is an implementation of the function showninTable5.Thesecondandthirdcolumnsshowthenameof hook()(L11-L12)oftheinputcontract,i.e.,contractfrom.Step3:If theDAppandthetimeitwasattacked;thefourthandfifthcolumns Step2istrue,wefindthecalltargetcontractaddressandfunction representthelossoftheattackandtheplatformtheDAppwas signaturetodeterminewhethertheyarevisitedinthecallpath, deployed.Columnssixthtoeighthshowtheaddressoftheexploiter, andjudgewhetherthereisareentrancyattack.Intheexample, theattackercontract,andthevictimcontractintheattack,respec- contractfromcallsbacktothefunctionfoo()againinthefunction tively.ThelastcolumndenoteswhetherBlockWatchdogcaniden- hook()toperformreentrancy. tifytheattackercontract.Itisnoticeablethatwefindtwoexploiters Weusethefollowingexpressiontodefinetheconditionsfora (0xceand0x80)intheCreamFinanceattackfromourcollected reentrancyattack.Wefirstfindthereachabilityofthesinksitein incidents,andthesetwoexploitersdeployed2(0xbdand0x38)and contracttar,whichcallsthefunctionf ofcontractto.Theaddress 1(0x32)attackercontracts,respectively,toattackthesamevictim ofcontracttocanbesetbytheattacker,whichisthetaintedsource contract(0xce).Similarly,theexploiter(0x61)thatattackedtheFei denotedby𝐴 𝑠.Furthermore,thefunctionf shouldbeimplemented protocolandRariDAppsdeployedtwoattackercontracts(0xE3 intheattackercontract’spublicfunctionlist𝐶 ,andtheexternal 𝐹 and0x32)toattackthevictimcontract(0xfb).WefindthatBlock- calls𝑓 ,includingthecalltargetaddressandfunctionsignature, 𝐸𝐶 Watchdogfailstoidentifythreereentrancyattackercontractsdue should be visited in the call path. If all conditions are met, we totworeasons.ThefirstfactoristheinabilityofBlockWatchdogto consideritareentrancyattack. recoverthecallchainwhenthecalltargetaddressesandfunctions intheattackercontractsareobtainedfrommemory.Giventhat thememoryvaluecannotbedeterminedviastaticanalysis,Block- 𝑅𝑒𝑎𝑐ℎ𝑎𝑏𝑙𝑒(𝑡𝑎𝑟,𝑓,𝑡𝑜), 𝑡𝑜 ∈𝐴 𝑠 Watchdogreliesontheconstantvalueofcalleeaddressesorcall 𝑅𝑒𝑒𝑛𝑡𝑟𝑎𝑛𝑐𝑦⇐ 𝑓 ∈𝐶 𝐹, 𝑓 𝐸𝐶 ∈𝑉𝑖𝑠𝑖𝑡𝑒𝑑 targetfunctionsignaturesforcompletecallchainrecovery.Inthe casesoftheFeiProtocolandRariincident,BlockWatchdogcannot identifythembecausethecalltargetcontractaddressisloaded 5 EVALUATION fromthememory.However,thememoryvaluecanonlybedeter- Inthissection,weevaluatetheeffectivenessofBlockWatchdog minedduringruntime,makingBlockWatchdogfailtodeducethe basedonthegroundtruthdatasetcollectedfromattackreports calltargetandrecoverthecallchain.Thesecondreasonpertains andalarge-scaledatasetobtainedthroughblockchaintransaction tothelimitationsinthefunctionsignatureidentificationofBlock- replay. Watchdog.SinceBlockWatchdogisbasedonElipmoc[17],which maynotbeabletorecoverallfunctionsignatures,thislimitation mayleadBlockWatchdogtofailtoidentifysomeexternalcalls.For 5.1 EvaluationSetup example,BlockWatchdogcannotdetectthereentrancyattackinthe TheexperimentwasconductedonaserverrunningUbuntu20.04.1 Spankchainincident,asthecalltargetfunctionLCOpenTimeout() LTS and equipped with 18 Intel(R) Core(TM) i9-10980XE CPUs isnotidentifiedinthevictimcontract.Asthedataflowprocedure @3.00GHzand250GBmemory. endswithanunknowntarget,BlockWatchdogfailstorecoverthe callchainandidentifythereentrancy.Despitesuchcases,therecall Dataset. WeusetwodatasetstoevaluateBlockWatchdog.The ofBlockWatchdogreaches83.3%inourexperiments. firstoneisthegroundtruthdataset,whichcomprisesreentrancy attackercontractsthatwecollectbyanalyzingtheattackincidents reports.Thisdatasetcontains18attackercontractsfrom15inci- dents.Thesecondlarge-scaleconsistsof421,889real-worldcontract bytecode(bothcreationandruntime).Thesecontractsareobtained 5.3 AnswertoRQ2:AttackerContracts viareplayingtransactionsfromblocknumber10millionto15.5 DetectioninaLarge-scaleDataset millionontheEthereummainnet. ToanswerRQ2,weranBlockWatchdogon421,889smartcontracts EvaluationMetrics. Wesummarizethefollowingresearchques- obtainedfromblockchaintransactionreplay.Theexperimentalre- tions(RQs)toevaluateBlockWatchdog. sultsshowthatBlockWatchdogreports253contractsasattacker contracts.WenextevaluatetheperformanceofBlockWatchdog, RQ1. HoweffectivelyisBlockWatchdogindetectingreentrancy usingamanuallabelingprocess.Twoauthorsmanuallyinspectthe attacksintheground-truthdataset? 253samplesreportedasattackercontracts,followingafour-step RQ2. HowistheperformanceofBlockWatchdoginfindingattacker procedure.Firstly,thedecompiledintermediaterepresentation(IR) contractsinthelarge-scaledataset? oftheattackercontractwasthoroughlyexamined.Secondly,the RQ3. Howmuchfinanciallossiscausedbytheidentifiedattacks, functionthatperformstheattackreportedbyBlockWatchdogis |
andarevulnerabilitydetectiontoolsabletofindthosevul- located.Thirdly,thecallchainsreportedbyBlockWatchdogare nerablevictims? checked. Finally, based on these examinations, it is determinedICSE2024,April2024,Lisbon,Portugal ShuoYang,JiachiChen,MingyuanHuang,ZibinZheng,andYuanHuang Table5:AttackerContractsintheDatasetandDetectionResultsofBlockWatchdog(BW) # DApp AttackTime Loss($) Platform Exploiter AttackerContract VictimContract BW 1 Spankchain 2018/10/9 38K ETH 0xcf267eA3f1eb 0xc5918a927C4F 0xf91546835f75 × 2 Uniswap 2020/4/18 220K ETH 0x60f3FdB85B2F 0xBD2250D713bf 0x1f9840a85d5a ✓ 3 Lendf.Me 2020/4/19 24.7M ETH 0xa9bf70a420d3 0x538359785a8D 0x0eEe3E3828A4 ✓ 4 Akropolis 2020/11/12 2M ETH 0xe2307837524D 0x38c40427efbA 0x1cec0e358f88 ✓ 5 DeFiPie 2021/7/12 350K BSC 0xf6f43f77ef9e 0x6d741523F1Fc 0x607C794cDa77 ✓ 6 xSurge 2021/8/16 25M BSC 0x59c686272e6f 0x1514aaa4dcf5 0xE1E1Aa58983F ✓ 0xbd51Cb8c06F7 ✓ 0xce1f4b4f1722 7 CreamFinance 2021/8/31 5M ETH 0x38c40427efbA 0xce1f4b4f1722 ✓ 0x8036EbD0Fc9C 0x32d77947aACa ✓ 8 GrimFinance 2021/10/16 30M FTM 0xDefC385D7038 0xb08cCb39741d 0x279b2c897737 ✓ 9 VisorFinance 2021/12/21 8.2M ETH 0x8efab89b497b 0x10C509AA9ab2 0xc9f27a50f825 ✓ 10 Paraluni 2022/3/13 1.7M BSC 0xA386F30853A7 0x4770b5cb9d51 0x94bC1d555E63 ✓ 11 Agave&Hundred 2022/3/15 5.5M ETH 0xcE1F4B4F1722 0x38c40427efbA 0xf8D1677c8a0c ✓ 12 Revest 2022/3/27 120K ETH 0xef967ece5322 0xb480ac726528 0x2320a28f5233 ✓ 0xE39f3C40966D × 13 FeiProtocal&Rari 2022/4/30 80.3M ETH 0x6162759eDAd7 0xfbD8Aaf46Ab3 0x32075bAd9050 × 14 Omni 2022/7/10 1.4M ETH 0x00000000c251 0x3c10e78343c4 0x3c10e78343c4 ✓ 15 SushiBar 2022/10/25 15K ETH 0x8ca72f46056d 0x9C5A2A643152 0x2321537fd8EF ✓ whetheracontractisanattackercontract,andtheassociatedfinan- example, 19 attacker contracts were designed with attack logic ciallossisrecorded.Thelabeledresultsshowthat113samplesare to hack victim contracts, but these attempts failed, resulting in indeedattackercontractsthatperformreentrancyattacks. revertedtransactions.Mostofthesecontractsonlyhavetwotrans- Inthelarge-scaleexperiment,somemetricsarecollectedtohelp actions,i.e.,thecontractcreationtransactionandthefailedattack usevaluateBlockWatchdogmorecomprehensively.Forthestruc- transaction.Moreover,someexploitationfunctionnames,suchas ture of the constructed xCFG and xCG, the average number of Attack,Rugpull,Exploit,andTrigger,arecommonlyusedinattacker visitedcontractsandthecalldepthoftherecoveredxCGare0.95 contracts.Thisinterestingdiscoveryprovidesinformationforfunc- and0.21,respectively.Thesameindicatorsoftrueattackercontracts tion signature or name identification to find potential attacker are7.66and2.55,respectively.Thisindicatesthatmanyattacker contracts,andprovidesinsightsintothedevelopmentpreferences contractsdirectlyhardcodethevictimcontracts’addressesforim- ofhackers. plementingtheattack.Inaddition,theaveragedetectiontimefor Falsepositives. Weidentifytwotypesoffalsepositivesgenerated BlockWatchdogtoanalyzeanattackercontractis17.66seconds.An byBlockWatchdogwhendetectingreentrancyattackercontracts. attackercontractcaninteractwithamaximumnumberof105con- Thefirsttypeinvolvestheuseofgetterfunctionstomakeexternal tractsinasinglecallchain,withthemaximumcalldepthreaching callsinthereentranthookfunction,withoutperforminganyother 21.Suchdeepcallchainsinvolvingmultiplecontractsandfunctions profitableexternalcalloperations.Thesecondtypeinvolvesthe exposethelimitationsofsimplepattern-basedrulesincovering usageofapermissioncheckmechanism,wheresomecontracts complexreentrancyattacks. usemsg.sender asthetransfertargetortoconstrainthecallerof thehookfunction,withnointentionofmakingexternalcallsto Table6:Top5HookFunctionsandCallTargetFunctionsin attackothers.BlockWatchdogreportsallcasesbasedonthereen- IdentifiedAttackerContractswithOccurrenceTimes trancypathtominimizefalsenegatives,whichmaygeneratefalse positives. HookFunction Times CallTarget Times uniswapV2Call 73 balanceOf 111 5.4 AnswertoRQ3:FinancialLossofVictims onFlashLoan 13 transfer 102 Duringthelabelingprocess,wefoundthatthetotalfinancialloss onERC721Received 9 approve 53 causedbythetruepositiveattackswas908.4millionUSD.Thisloss delegatedTransferERC20 2 withdraw 25 comprisedapproximately840Ethers(about1.7millionUSD)andto- onERC1155Received 2 deposit 23 kensworth906.9millionUSD.Notably,thelossoftokensaccounted for99.8%ofthetotalfinancialloss,indicatingthatnewtypesof Table 6 shows the signatures of the call targets in the hook reentrancyattacksareprimarilycausedbypoordesignswhenusing |
functionoftheattackercontractsfromourlabeleddataset.The andtransferringERCtokens,ratherthanEthertransfers. uniswapV2Call()isarequiredhookfunctioninUniswapV2[50], Table7showsthetop5attacksidentifiedbyBlockWatchdog, whileonFlashloan()isdeclaredbyERC3156[12].Wealsohavesome rankedbytheirfinancialloss.Wefindthatvulnerablecontractsmay interestingfindingsrelatedtothedesignofattackercontracts.For beattackedmultipletimesiftheyhavebeenexploitedsuccessfullyUncoverthePremeditatedAttacks:DetectingExploitableReentrancyVulnerabilitiesbyIdentifyingAttackerContracts ICSE2024,April2024,Lisbon,Portugal once.Specifically,BlockWatchdogidentified9,4,and3attacker areextractedbywhitehats,thussavingpossiblefinanciallosses.In contractsthatweredeployedtoattackprojectsCreamFinance[9], addition,BlockWatchdogtakes25secondstodetectthisattacker Omni[1],andVisorFinance[19],respectively,resultinginatotal contract(showninFigure1)andthepotentiallyexploitablevictim financiallossof906.7millionUSD.CreamFinancewashackedby inVisorFinance[19].Sincetheattackoccurredabout6minutes thehookfunctiontokensReceived()intheattackercontract.Itimple- afterthedeploymentoftheattackercontract,theprotectioncan mentsmultipletoken-borrowlogictoperformtheflashloanattack beperformedinthistimegap. inareentrancycallpath,whichdemonstratesthecomplexityofthe newtypesofreentrancyattacks.Omniwasattackedbyattacker contractsthatimplementedreentrancylogicinthehookfunction 1 function uniswapV2Call(address varg0, uint256 varg1, onERC721Received()whentransferringNFTs.Hackersrepeatedly uint256 varg2, bytes varg3) public nonPayable { minted,borrowed,andwithdrewNFTsbeforechangingtheliq- 2 v18, v19 = stor_18_0_19.call(0x2e236bc, address(this), 1, ...); uidationstate.VisorFinancewasexploitedbyattackercontracts 3 ... thatimplementeddelegatedTransferERC20(),whichisauser-defined 4 v39 = stor_18_0_19.withdrawFNFT(v36, 1 + v2[0]);} hookfunction,asshowninFigure1.Inaddition,BlockWatchdog 5 identified40zero-dayattackercontractsandatotalof159victim 6 function onERC1155Received(address varg0, address varg1, uint256 varg2, uint256 varg3, bytes varg4) public contracts,whichweretargetedbytheattackercontractstoperform nonPayable { reentrancyattacks. 7 ... 8 if (_onERC1155Received != 0) { 9 if (_onERC1155Received == 1) { Table7:Top5AttacksRankedbyFinancialLoss 10 v0 = 0x2007(_onERC1155Received); 11 _onERC1155Received = v0; AttakerContract HookFunction Loss(USD) 12 v1, v2 = stor_19_0_19.getNextId(); 0x10c509aa9ab2 delegatedTransferERC20 904million 13 v3, v4 = stor_18_0_19.depositAdditionalToFNFT(v2 - 0xc51bdc9aebba tokensReceived 0.56million 1, stor_4, 1);} 0x86f28c7030bd onERC721Received 0.28million 14 } else { 15 v5 = 0x2007(_onERC1155Received); 0xbc82ab5a8223 tokensReceived 0.28million 16 _onERC1155Received = v5;} 0x3292818dB514 uniswapV2Call 0.28million 17 return 0xf23a6e61;} Figure7:TheattackercontractthathackedtheRevest. 6 DISCUSSION Inthissection,wefirstgiveacasestudytoshowhowBlockWatch- Theabovecasestudyshowsthepracticalityoftimelyprotection dogcanenhancethesecurityofEthereumbyidentifyingattacker byusingourBlockWatchdog.Intheblockchainsystem,attacks contracts.WethenpresentthecapabilityofBlockWatchdogtofind areirreversible,makingitcriticaltodetectpotentiallythreatening vulnerabilitiesanddiscussthelimitationsofourwork. contractsbeforethestartofanytransaction.BlockWatchdogcan quicklyidentifysuchvulnerablecontracts,therebyimprovingthe 6.1 CaseStudy securityoftheEthereumecosystemintwoways. Figure7showsacodesnippetoftheattackercontractthataimed Firstly,ourtoolcanbeusedforthereal-timedetectionofat- toattackRevest[40]identifiedbyBlockWatchdog.Thisattacker tackercontractsonEthereum,allowingsecurityfirmstoreport contractwasfirstdeployedatMar-27-202201:10:05AM+UTC,and suspiciousattackercontractsinminutes.Sincewedonotrequire abouthalfanhourlater,thefirstattackwaslaunchedatMar-27- transactioninformation,itispossibletopreventattacks.White- 202201:41:46AM+UTC.Specifically,thefunctionwithsignature hats[54],Etherscan[15],andsecurityanalysisfirms,suchasCon- 0xdd869c35wasinvokedbytheexploitertocallvictims.Then,the sensys[8],canquicklyidentifypotentialattackercontractsand call chain was turned back and controlled by the attacker con- victimswithattackfootprintsreportedbyBlockWatchdog(17.66 tracttwicethroughfunctioninvocationbythehookfunctions,i.e., secondsonaverage)beforeattacktransactionsaresent(asshownin uniswapV2Call() (L1-L4)andonERC1155Received() (L6-L17).The theabovecase).However,itiscrucialtoaddresstheethicalimplica- attackercontractqueriedforthenextNFTid(functiongetNextId() tionsofsuchpreemptiveactionsinthispaper.Whileourapproach |
(L12))anddepositedanotheroneviathefunctiondepositAddition- facilitatesearlydetectionandprovidesanopportunityforrapid alFNFT()(L13).Finally,anotherNFTwassuccessfullymintedto response,weconsciouslydonotperformon-chainfrontrunning theattackerwithoutbeingpaidinthisreentrancyattack.Ittakes thatcouldbedeemedasethicalissuesorpotentialdisruptivenessto BlockWatchdog64secondstoidentifythisattackercontractandits theblockchain’sintegrity.Furthermore,weusetransactionreplay victimcontract.Thetimegapofhalfanhourbetweenthedeploy- onlytoretrievethebytecodeofthedeployedsmartcontracts. mentoftheattackercontractandtheactualattackfarexceedsthe Secondly,ourtoolcanfindnewtypesofreentrancyvulnera- timecostsofthedetectionprocess.Thisprovidesanopportunity bilitiesthatothertoolsmayhavemissed.Securityfirmscanuse forwhitehatstofront-runthehackersandprotectthevulnerable BlockWatchdogtoidentifyundiscoveredattackercontractsand deployedcontracts.Specifically,whitehatscancopythebytecodeof reentrancyvulnerabilitiesinpractice.PlatformslikeEtherscanla- theattackercontracttoperformtheimitationattack[38]beforethe bel the attacker’s EOA as an attacker account, and warn about realattackislaunched.Therefore,theintendedprofitsofhackers newlydeployedcontractsandrelatedtransactions.ICSE2024,April2024,Lisbon,Portugal ShuoYang,JiachiChen,MingyuanHuang,ZibinZheng,andYuanHuang Forcontractdevelopers,topreventtheircontractsfrombeing conditionalcheckswhentracingpaths,whichyieldsfalsepositives. attackedafterthedeployment,theexternalcalltargetcontract’sad- Third,wesummarizetheattacktypesanddesignthedetectionrules dressshouldbeverifiedin“sensitive”functions,e.g.,tokentransfer basedonthereportedattackincidents.Therefore,itispossiblethat orswaplogic,thusblockingthepremeditatedattacksthatmalicious wemaynotcovernewattacktypesthathavenotyetoccurredor attackercontractscouldlaunch. beenreported.Overall,despitetheabovelimitations,wefocuson detectingnewtypesofreentrancyvulnerabilitiesthatothertools cannotcover.Othertypesofattacksthatinvolveattackercontracts 6.2 CapabilityofFindingVulnerabilities mentionedinSection3arenotaddressedinthispaper,whichwe BlockWatchdogfindsasignificantnumberofexploitablevictim willcoverinfuturework. contractswithexploitablevulnerabilities,andmostofthemcannot bedetectedbycurrenttools.Wechoosesevenreentrancydetec- tiontoolstodetectvictimcontracts:Mythril[30],NFTGuard[57], 6.4 ThreatstoValidity Oyente[28],Sailfish[39],Securify1[48],Securify2[42],andSmar- Regardingourexperiment,themanuallabelingprocessmayhave tian[7],referringtothefourselectrules[57,60],i.e.,(1)availability introducederrorsindifferentiatingfalsepositivesandtruepositives. ofthetoolsourcecode;(2)usabilityofthecommand-lineinterface However,wehaveusedadouble-checkprocesstomitigatethis forlarge-scaleexperiment;(3)supportingSoliditysourcecode;(4) issueandupdatedthelabeleddatasetinatimelymannertoensure abilitytoreportvulnerablecodelocationformanualexamination. accuracy.WevalidatedwhethertherewasanattackonEtherscan Weruntheseseventoolson159victimcontracts,andalloutputs using the call chains reported by BlockWatchdog, collaborated aregiveninouropenrepository. withthetransactiontracerecordedontheonlinetransactiontrace TheresultsshowthatonlyMythrilandSailfishreport1and explorerPhalcon[36],andrecordedfinanciallossaccordingtothe 17victims,respectively,whiletheotherfivetoolsdonotreport transactioninformationobtainedfromEtherscan.Anotherthreat anyreentrancyvulnerability.Therefore,only18outof159(11.3%) tovalidityisthatwedidnotverifythatvulnerablecontractscanbe victimscanbedetectedbycurrenttools.AsBlockWatchdogex- exploitedduetoethicalconcernsaboutattackingthem.Weintend tractsmorefeaturesfromattackercontracts,whichmaybemissed toaddressthisinourfuturework. byotherworks,BlockWatchdogcanmoreeffectivelyidentifyex- Therearesomeothertypesofattackercontracts,e.g.,BadRan- ploitablecontractswithreentrancyvulnerabilitiesinpracticewith domnessandFlashloan,aswementionin3.2,whicharenotcovered betterperformanceandgeneralizability.Therearethreereasons bythiswork.ThedesignofourBlockWatchdogfocusesoncallflow fortheresults.First,manyidentifiedattackercontractsextractto- analysis,whichmakesitpossibletobeextendedtodetectFlashloan kensbutnotEthersfromvictims.However,mostexistingtools attackercontractsthatalsocontainsomeflowfeatures.However, focusoncall.value(),whichonlyinvolvesEthertransfer.Second, morecontractsemanticsandoperationalfeaturesshouldbeana- rule-basedmethodsstruggletocoverissuescausedbypatterns lyzedtocoverotherattackercontracttypeslikeBadRandomness, thathavenotbeenpreviouslyreported,anditisevenharderto whichrequiresunderstandingspecificcontractbehaviors. identifyreentranciesrelatedtouser-definedinterfacesthatcannot Despitethelimitationsmentionedabove,BlockWatchdoghas begeneralizedintoadetectionpattern.Third,existingtoolsdetect detected40zero-dayattackersmartcontractsthatwerepreviously reentrancybasedonstatemodificationinconsistency.However, |
unreported,whichhadreentrancyfeatures.SinceBlockWatchdog newreentrancyattacks,e.g.,read-onlyreentrancy,canmakeuseof doesnotrequiretransactioninformationandcanprovidedetection justviewfunctions,e.g.,balanceOf()andgetPrice()toimplement resultswithinminutes,itcanmonitornewlydeployedcontractsand reentrancy.Theseviewfunctionsdonotmodifyanystateandare detectattackercontractsbeforetheycanexecuteattacks,preventing usuallynotprotected,makingexistingtoolsdifficulttodetect. potentialattacksandheavyfinanciallosses. 6.3 Limitations 7 RELATEDWORK DespitethestrengthsofBlockWatchdog,weidentifythreepotential limitations.First,BlockWatchdogreportswhetheraninputcontract Reentrancydetectiontoolsforsmartcontracts. Asreentrancy isanattackercontractornotbasedsolelyonstaticanalysiswithout isoneofthenotoriousvulnerabilitiesinsmartcontracts[41],many transactioninformation.Wecanrecoverthepossiblecallchains programanalysistoolshavebeendevelopedtodetectsuchissuesby oftheinputcontract,includingtransactiondata,whichcanhelp staticanalysisordynamictesting[4–6].Thegoalofthesetoolsisto enhancetheprecisionofdetection.AsweaimtodeployBlock- preventvulnerablecontractsfrombeingdeployedontheblockchain. Watchdogasareal-timedetectionplatformforEthereuminthe For example, Oyente [28], Securify [48], Mythril [30], and Sail- future,transactionsareconsideredasadditionalinformationto fish[39]usestaticanalysistechnologiestodiscoverreentrancy achieveamoreprecisedetectionresultSecond,weidentifyinter- vulnerability.Inaddition,therearedynamictestingandanalysis actedcontractsfromtheconstantaddressorstorage,andbydefault, toolssuchasContractFuzzer[20],sFuzz[31],Smartian[7],RLF[44], werelyontheassumptionthattheattackercontracthardcodesthe andReGuard[27],andapproachesbasedonmachinelearninglike victims’addresses.Althoughwefindthatallthecollectedcases ReVulDL[58].Ascontractcodeandvulnerabilitiesbecomemore belongtothesetwoscenarios,itispossiblethattheattackercon- complex, there are works that focus on cross-contract analysis, tractscansetthetargetcontractintheargumentsofthefunction, suchasClairvoyance[56]andSmartDagger[26].However,many whichwecannotobtainthroughstaticanalysis,thusleadingto ofthesetoolssufferfromhighfalsepositiveratesandmaynot falsenegatives.Inaddition,ourtaintanalysisdoesnotaccountfor identifyrealvulnerablecontractsinpractice[35].UncoverthePremeditatedAttacks:DetectingExploitableReentrancyVulnerabilitiesbyIdentifyingAttackerContracts ICSE2024,April2024,Lisbon,Portugal Toourknowledge,BlockWatchdogisthefirstdetectiontoolto REFERENCES identifyattackercontractsandtheircallchains.Thisfeatureen- [1] 2022. Hacker drains $1.4 million worth of ETH from NFT lender ablesthetooltodetectrealvulnerablevictimcontractsinpractice. Omni. https://www.theblock.co/post/156800/hacker-drains-1-4-million-worth- of-eth-from-nft-lender-omniSection:Hacks. Additionally,BlockWatchdogaddressesthelimitationofcurrent [2] 2022.Medium–Wheregoodideasfindyou. https://medium.com/ reentrancydetectioncapability[60],andcandetectcomplexreen- [3] alchemy2023.alchemy. https://www.alchemy.com/. trancyattacksinthewild. [4] EarlT.Barr,MarkHarman,PhilMcMinn,MuzammilShahbaz,andShinYoo.2015. TheOracleProbleminSoftwareTesting:ASurvey.IEEETransactionsonSoftware SecurityanalysisonattackincidentsonEthereum. Priorre- Engineering41,5(2015),507–525. https://doi.org/10.1109/TSE.2014.2372785 searchonattackanalysisonEthereumhasfocusedonunderstand- [5] AntoniaBertolino.2007.Softwaretestingresearch:Achievements,challenges, dreams.InFutureofSoftwareEngineering(FOSE’07).IEEE,85–103. ingattackincidentsatthetransactionlevel.Forexample,Torreset [6] CristianCadar,DanielDunbar,DawsonREngler,etal.2008.Klee:Unassisted al.[47]conductedanempiricalstudyoffront-runningattackson andautomaticgenerationofhigh-coveragetestsforcomplexsystemsprograms.. Ethereum,whileZhouetal.[61]evaluatedreal-worldattacksand InOSDI,Vol.8.209–224. [7] JaeseungChoi,DoyeonKim,SoominKim,GustavoGrieco,AlexGroce,and defensesintheEthereumecosystem.Theyanalyzedhowattackers SangKilCha.2021.Smartian:Enhancingsmartcontractfuzzingwithstaticand have destroyed applications in Ethereum and discussed how to dynamicdata-flowanalyses.In202136thIEEE/ACMInternationalConferenceon defendagainstattacksfromthevictimcontract’sperspective.Suet AutomatedSoftwareEngineering(ASE).IEEE,227–239. [8] consensys2023.Consensys. https://consensys.net/. al.[45]focusedonDAppsecurityandanalyzedrelatedtransactions [9] C.R.E.A.M.Finance2023.C.R.E.A.M.Finance. https://docs.cream.finance/. tounderstandhowtodetectattacksthroughtransactionanalysis. [10] EIP2023.EthereumImprovementProposals. https://eips.ethereum.org/. [11] eip-552023.EIP-55. https://eips.ethereum.org/EIPS/eip-55. TheydevelopedatoolcalledDEFIERthatcanidentifythestageof [12] ERC-3156: Flash Loans 2023. ERC-3156: Flash Loans. |
apotentialattack.However,BlockWatchdogcandetectattacker https://eips.ethereum.org/EIPS/eip-3156. [13] erc1155 2023. ERC-1155 MULTI-TOKEN STANDARD. contractswithoutanyattacktransactions,makingitpossibleto https://ethereum.org/en/developers/docs/standards/tokens/erc-1155/. preventfinancialloss. [14] erc777 2022. ERC-777 TOKEN STANDARD. https://ethereum.org/en/developers/docs/standards/tokens/erc-777/. [15] etherscan 2023. Etherscan - The Ethereum Blockchain Explorer. 8 CONCLUSIONANDFUTUREWORKS https://etherscan.io/. [16] NevilleGrech,MichaelKong,AntonJurisevic,LexiBrent,BernhardScholz,and Inthispaper,wepresentBlockWatchdog,atoolfordetectingreen- YannisSmaragdakis.2018.Madmax:Survivingout-of-gasconditionsinethereum trancyattackercontractsandidentifyingvulnerablevictimswith smartcontracts.ProceedingsoftheACMonProgrammingLanguages2,OOPSLA reentrancyvulnerabilities.Toreducefalsepositives,weusethe (2018),1–27. [17] NevilleGrech,SifisLagouvardos,IliasTsatiris,andYannisSmaragdakis.2022. detectionofattackercontractsasanentrypoint,andidentifyvul- Elipmoc:advanceddecompilationofEthereumsmartcontracts.Proceedingsof nerablevictimcontractsbasedoncallbackflow.TodesignBlock- theACMonProgrammingLanguages6,OOPSLA1(2022),1–27. Watchdog, we conducted an empirical study to understand the [18] Harvard CodeBlue 2018. EIP-721: Non-Fungible Token Standard. https://eips.ethereum.org/EIPS/eip-721. attacklogicusedbyhackersinattackercontracts.BlockWatchdog [19] ivisor2021. VisorFinanceSuffersanotherDeFiHackasLossesMountUpto disassemblesacontract’sbytecodeandmonitorsallpotentialcall $8.2M. https://www.fxempire.com/news/article/defi-protocols-have-lost-680- million-so-far-in-2021-795829. chainsthatinitiatefromitspublicfunctionsandextendtoacces- [20] BoJiang,YeLiu,andWingKwongChan.2018.Contractfuzzer:Fuzzingsmartcon- siblecontractsandfunctions.Besides,BlockWatchdogformulates tractsforvulnerabilitydetection.In201833rdIEEE/ACMInternationalConference thexCFGandxCGtofacilitatecross-contractdataflowanalysisbe- onAutomatedSoftwareEngineering(ASE).IEEE,259–269. [21] SukritKalra,SeepGoel,MohanDhawan,andSubodhSharma.2018. Zeus: tweendifferentproceduresandtodeterminewhetherthecallback analyzingsafetyofsmartcontracts..InNdss.1–12. flowcanbeexploitedbymaliciouscontractstoexecuteasuccessful [22] QuepingKong,JiachiChen,YanlinWang,ZiguiJiang,andZibinZheng.2023. reentrancyattack.OurexperimentresultsdemonstratethatBlock- DeFiTainter:DetectingPriceManipulationVulnerabilitiesinDeFiProtocols. InProceedingsofthe32ndACMSIGSOFTInternationalSymposiumonSoftware Watchdogeffectivelydetects113attackercontractsamong421,889 TestingandAnalysis.1144–1156. real-worldcontractsandidentifies159victimcontractswithreen- [23] JohannesKruppandChristianRossow.2018.teether:Gnawingatethereumto trancyvulnerabilities.ThesevulnerablecontractscontainEthers automaticallyexploitsmartcontracts.In27th{USENIX}SecuritySymposium ({USENIX}Security18).1317–1333. andtokensworthapproximately908.6millionUSD.Only18of [24] lendfme 2020. About Recent Uniswap and Lendf.Me Reentrancy At- themareidentifiedbyotherdetectiontools. tacks. https://medium.com/imtoken/about-recent-uniswap-and-lendf-me- reentrancy-attacks-7cebe834cb3. Furthermore,werevealallpotentialcallchainsofthe421,889 [25] XiaoqiLi,PengJiang,TingChen,XiapuLuo,andQiaoyanWen.2020.Asurvey real-worldcontracts,andwhethertheycontainexternalcallsin onthesecurityofblockchainsystems.Futuregenerationcomputersystems107 hookfunctionsidentifiedbyBlockWatchdog.Thedetectionresults (2020),841–853. [26] ZeqinLiao,ZibinZheng,XiaoChen,andYuhongNan.2022. SmartDagger:a canbehelpfulforfurthersecurityanalysis.Inthefuture,weplan bytecode-basedstaticanalysisapproachfordetectingcross-contractvulnerability. todeployBlockWatchdogforreal-timedetectionpurposes,inorder InProceedingsofthe31stACMSIGSOFTInternationalSymposiumonSoftware tofindmorevulnerablecontractsinpracticeandhelppreventthem TestingandAnalysis.752–764. [27] ChaoLiu,HanLiu,ZhaoCao,ZhongChen,BangdaoChen,andBillRoscoe. frombeingattacked.Inaddition,wewillextendBlockWatchdog 2018.Reguard:findingreentrancybugsinsmartcontracts.InProceedingsofthe tocovernewtypesofattacks,remainingeffectiveinthefaceof 40thInternationalConferenceonSoftwareEngineering:CompanionProceeedings. 65–68. ever-evolvingthreatsonEthereum. [28] LoiLuu,Duc-HiepChu,HrishiOlickel,PrateekSaxena,andAquinasHobor. 2016.Makingsmartcontractssmarter.InProceedingsofthe2016ACMSIGSAC conferenceoncomputerandcommunicationssecurity.254–269. ACKNOWLEDGMENTS [29] BernhardMueller.2018. Smashingethereumsmartcontractsforfunandreal Thisresearch/projectissupportedbytheNationalKeyR&DPro- profit.HITBSECCONFAmsterdam9(2018),54. [30] Mythril2023.Mythril. https://mythril-classic.readthedocs.io/en/master/module- |
gram of China (2022YFB2702203), the National Natural Science list.html. FoundationofChina(No.62302534andNo.62332004),andtheAnt [31] TaiDNguyen,LongHPham,JunSun,YunLin,andQuangTranMinh.2020. GroupResearchFund. sfuzz:Anefficientadaptivefuzzerforsoliditysmartcontracts.InProceedingsofICSE2024,April2024,Lisbon,Portugal ShuoYang,JiachiChen,MingyuanHuang,ZibinZheng,andYuanHuang theACM/IEEE42ndInternationalConferenceonSoftwareEngineering.778–788. [60] ZibinZheng,NengZhang,JianzhongSu,ZhijieZhong,MingxiYe,andJiachi [32] IvicaNikolić,AashishKolluri,IlyaSergey,PrateekSaxena,andAquinasHobor. Chen.2023. TurntheRudder:ABeaconofReentrancyDetectionforSmart 2018.Findingthegreedy,prodigal,andsuicidalcontractsatscale.InProceedings ContractsonEthereum. arXiv:2303.13770[cs.SE] ofthe34thannualcomputersecurityapplicationsconference.653–663. [61] ShunfanZhou,ZheminYang,JieXiang,YinzhiCao,MinYang,andYuanZhang. [33] RobertNorvill,BeltranFiz,RaduState,andAndreaCullen.2019.Standardising 2020.Anever-evolvinggame:Evaluationofreal-worldattacksanddefensesin smartcontracts:AutomaticallyinferringERCstandards.In2019IEEEInternational ethereumecosystem.InProceedingsofthe29thUSENIXConferenceonSecurity ConferenceonBlockchainandCryptocurrency(ICBC).IEEE,192–195. Symposium.2793–2809. [34] peckshield2023.Peckshield-IndustryLeadingBlockchainSecurityCompany. https://peckshield.com/. [35] DanielPerezandBenjaminLivshits.2021.SmartContractVulnerabilities:Vul- nerableDoesNotImplyExploited..InUSENIXSecuritySymposium.1325–1341. [36] Phalcon2023.PowerfulTransactionExplorerDesignedForDeFiCommunity. https://explorer.phalcon.xyz/. [37] primitivefinance2023. WhitehackbyPrimitiveFinance:MOSTFUNDSARE SAFE.Useractionrequired. https://primitivefinance.medium.com/whitehack- by-primitive-finance-most-funds-are-safe-user-action-required-4dd31c387b8. [38] KaihuaQin,StefanosChaliasos,LiyiZhou,BenjaminLivshits,DawnSong, andArthurGervais.2023. Theblockchainimitationgame. arXivpreprint arXiv:2303.17877(2023). [39] SriramRao,RaghuRamakrishnan,AdamSilberstein,MikeOvsiannikov,and DamianReeves.2012.Sailfish:Aframeworkforlargescaledataprocessing.In ProceedingsoftheThirdACMSymposiumonCloudComputing.1–14. [40] revest 2022. Revest Finance Vulnerabilities: More than Re-entrancy. https://blocksecteam.medium.com/revest-finance-vulnerabilities-more- than-re-entrancy-1609957b742f. [41] MichaelRodler,WentingLi,GhassanOKarame,andLucasDavi.2018.Sereum: Protectingexistingsmartcontractsagainstre-entrancyattacks.arXivpreprint arXiv:1812.05934(2018). [42] Securify2.02023.Securify2.0. https://github.com/eth-sri/securify2. [43] DonnaSpencer.2009.Cardsorting:Designingusablecategories.RosenfeldMedia. [44] JianzhongSu,Hong-NingDai,LingjunZhao,ZibinZheng,andXiapuLuo.2022. Effectivelygeneratingvulnerabletransactionsequencesinsmartcontractswith reinforcementlearning-guidedfuzzing.InProceedingsofthe37thIEEE/ACM InternationalConferenceonAutomatedSoftwareEngineering.1–12. [45] LiyaSu,XinyueShen,XiangyuDu,XiaojingLiao,XiaoFengWang,LuyiXing, andBaoxuLiu.2021.Evilunderthesun:understandinganddiscoveringattacks onEthereumdecentralizedapplications.In30thUSENIXSecuritySymposium (USENIXSecurity21).1307–1324. [46] NickSzabo.1997.Formalizingandsecuringrelationshipsonpublicnetworks. Firstmonday(1997). [47] ChristofFerreiraTorres,RamiroCamino,andRaduState.2021. Frontrunner jonesandtheraidersofthedarkforest:Anempiricalstudyoffrontrunningon theethereumblockchain.arXivpreprintarXiv:2102.03347(2021). [48] PetarTsankov,AndreiDan,DanaDrachsler-Cohen,ArthurGervais,Florian Buenzli,andMartinVechev.2018.Securify:Practicalsecurityanalysisofsmart contracts.InProceedingsofthe2018ACMSIGSACConferenceonComputerand CommunicationsSecurity.67–82. [49] Twitter2023.Twitter. https://twitter.com/. [50] UniswapV2 2023. UniswapV2. https://github.com/Uniswap/v2- core/blob/master/contracts/UniswapV2Pair.sol. [51] uniswap_v3 2023. The Uniswap V3 Smart Contracts. https://docs.uniswap.org/contracts/v3/overvie. [52] web3py2023.web3py. https://web3py.readthedocs.io/en/stable/web3.eth.html. [53] SamWerner,DanielPerez,LewisGudgeon,AriahKlages-Mundt,DominikHarz, andWilliamKnottenbelt.2022.Sok:Decentralizedfinance(defi).InProceedings ofthe4thACMConferenceonAdvancesinFinancialTechnologies.30–46. [54] whitehats2023. WhyWhiteHatHackersAreVitaltotheCryptoEcosys- tem. https://www.coindesk.com/layer2/2022/02/23/why-white-hat-hackers- are-vital-to-the-crypto-ecosystem/. [55] KaidongWu.2019.Anempiricalstudyofblockchain-baseddecentralizedappli- cations.arXivpreprintarXiv:1902.04969(2019). |
[56] YinxingXue,MingliangMa,YunLin,YuleiSui,JiamingYe,andTianyongPeng. 2020. Cross-contractstaticanalysisfordetectingpracticalreentrancyvulner- abilitiesinsmartcontracts.InProceedingsofthe35thIEEE/ACMInternational ConferenceonAutomatedSoftwareEngineering.1029–1040. [57] ShuoYang,JiachiChen,andZibinZheng.2023. DefinitionandDetectionof DefectsinNFTSmartContracts.InProceedingsofthe32ndACMSIGSOFTInter- nationalSymposiumonSoftwareTestingandAnalysis(Seattle,WA,USA)(ISSTA 2023).AssociationforComputingMachinery,NewYork,NY,USA,373–384. https://doi.org/10.1145/3597926.3598063 [58] ZhuoZhang,YanLei,MengYan,YueYu,JiachiChen,ShangwenWang,and XiaoguangMao.2022. Reentrancyvulnerabilitydetectionandlocalization:A deeplearningbasedtwo-phaseapproach.InProceedingsofthe37thIEEE/ACM InternationalConferenceonAutomatedSoftwareEngineering.1–13. [59] ZibinZheng,ShaoanXie,Hong-NingDai,WeiliChen,XiangpingChen,Jian Weng,andMuhammadImran.2020.Anoverviewonsmartcontracts:Challenges, advancesandplatforms.FutureGenerationComputerSystems105(2020),475–491. |
2404.02056 1 Multitask-based Evaluation of Open-Source LLM on Software Vulnerability Xin Yin, Chao Ni⋆, and Shaohua Wang Abstract— This paper proposes a pipeline for quantitatively evaluating interactive Large Language Models (LLMs) using publicly available datasets. We carry out an extensive technical evaluation of LLMs using Big-Vul covering four different common software vulnerability tasks. This evaluation assesses the multi-tasking capabilities of LLMs based on this dataset. We find that the existing state-of-the-artapproachesandpre-trainedLanguageModels(LMs)aregenerallysuperiortoLLMsinsoftwarevulnerabilitydetection. However,insoftwarevulnerabilityassessmentandlocation,certainLLMs(e.g.,CodeLlamaandWizardCoder)havedemonstratedsu- periorperformancecomparedtopre-trainedLMs,andprovidingmorecontextualinformationcanenhancethevulnerabilityassessment capabilitiesofLLMs.Moreover,LLMsexhibitstrongvulnerabilitydescriptioncapabilities,buttheirtendencytoproduceexcessiveoutput significantlyweakenstheirperformancecomparedtopre-trainedLMs.Overall,thoughLLMsperformwellinsomeaspects,theystill needimprovementinunderstandingthesubtledifferencesincodevulnerabilitiesandtheabilitytodescribevulnerabilitiestofullyrealize theirpotential.OurevaluationpipelineprovidesvaluableinsightsintothecapabilitiesofLLMsinhandlingsoftwarevulnerabilities. IndexTerms—SoftwareVulnerabilityAnalysis,LargeLanguageModel. ✦ 1 INTRODUCTION Software Vulnerabilities (SVs) can expose software sys- to individuals. As a cornerstone of software quality assur- temstorisksituationsandeventuallycausehugeeconomic ance,theseamlessintegrationoftheseactivitiesunderscores lossesoreventhreatenpeople’slives.Therefore,completing the importance of a proactive and thorough approach to software vulnerabilities is an important task for software managing software vulnerabilities in today’s dynamic and quality assurance (SQA). Generally, there are many impor- interconnecteddigitallandscape. tant software quality activities for software vulnerabilities such as SV detection, SV assessment, SV location, and SV description. The relationship among the SQA activities is RQ-2 Vulnerability intricateandinterdependentandcanbeillustratedinFig.1. Assessment SV detection serves as the initial phase, employing various Source Vulnerability Vulnerability Vulnerability LLM tools and techniques to identify potential vulnerabilities Code Detection Location Description Output within the software. Once detected, the focus shifts to SV RQ-1 RQ-3 RQ-4 assessment, where the severity and potential impact of Fig. 1: The relationship among software vulnerability anal- each vulnerability are meticulously evaluated. This critical ysisactivities evaluation informs the subsequent steps in the process. SV locationfollowstheassessment,pinpointingtheexactareas within the software’s code or architecture where vulner- Recently, Large Language Models (LLMs) [1] have been abilities exist. This step is crucial for precise remediation widely adopted since the advances in Natural Language efforts and to prevent the recurrence of similar vulnera- Processing (NLP) which enable LLM to be well-trained bilities in the future. The intricacies of SV location feed with both billions of parameters and billions of training intothecomprehensiveSVdescription,whichencapsulates samples, consequently bringing a large performance im- detailed information about each vulnerability, including its provement on tasks adopted by LLMs. LLMs can be easily origin,characteristics,andpotentialexploits.Inessence,the used for a downstream task by being fine-tuned [2] or synergy among SV detection, SV assessment, SV location, beingprompted[3]sincetheyaretrainedtobegeneraland andSVdescriptioncreatesarobustpipelineforaddressing theycancapturedifferentknowledgefromvariousdomain software vulnerabilities comprehensively. This systematic data. Fine-tuning is used to update model parameters for approach not only enhances the overall quality of the soft- a particular downstream task by iterating the model on ware but also fortifies it against potential threats, thereby a specific dataset while prompting can be directly used safeguarding against economic losses and potential harm by providing natural language descriptions or a few ex- amples of the downstream task. Compared to prompting, fine-tuning is expensive since it requires additional model BothXinYinandChaoNiarewiththeStateKeyLaboratoryofBlockchainand DataSecurity,ZhejiangUniversity,Hangzhou,China.ChaoNiisalsowith trainingandhaslimitedusagescenarios,especiallyincases HangzhouHigh-TechZone(Binjiang)BlockchainandDataSecurityResearch wheresufficienttrainingdatasetsareunavailable. Institute,Hangzhou,China.E-mail:{xyin,chaoni}@zju.edu.cn. LLMshavedemonstratedremarkablelanguagecompre- ShaohuaWangiswithCentralUniversityofFinanceandEconomics,China. hension and generation capabilities, and have been able to E-mail:davidshwang@ieee.org. ChaoNiisthecorrespondingauthor. perform well on a variety of natural language processing 4202 luJ 6 ]ES.sc[ 3v65020.4042:viXra2 Detection Detection Detection* Description* Assessment Description Assessment Description Assessment* Location* Detection Detection Location Location Detection DeepSeek 6.7B CodeLlama 7B StarCoder 7B DeepSeek 6.7B DeepSeek 33B StarCoder 7B CodeLlama 34B WizardCoder 7B Mistral 7B Phi-2 2.7B StarCoder 7B StarCoder 15.5B WizardCoder 7B WizardCoder 34B (a) LLMs’performanceondifferentsoftwarevulnerabilitytasks (b) TheimpactsofparametersizesonLLMs’performanceacrossdiffer- (∗referstotheresultsunderfine-tuningsetting) entsoftwarevulnerabilitytasks Fig.2:ThecapabilitycomparisonofLLMswithdifferentparametersizesondifferentsoftwarevulnerabilitytasks |
tasks,suchastextsummarization[4].Giventheoutstanding SV assessment frameworks CVSS (Common Vulnera- performanceofLLMs,thereisagrowingfocusonexploring bilityScoringSystem)[20],whichcharacterizesSVsby their potential in software engineering tasks and seeking considering three metric groups: Base, Temporal, and newopportunitiestoaddressthem.Currently,asmoreand Environmental. The metrics that are in the groups can more LLMs designed for software engineering tasks are befurtherusedasthecriterionforselectingseriousSVs deployed[5]–[11],manyresearchworksfocusedontheap- to fix early. Therefore, we aim to explore the ability plicationofLLMsinthesoftwareengineeringdomain[12]– of LLMs to assess vulnerabilities and compare their [16].However,intheexistingliterature,adequatesystematic performancewithpre-trainedLMs. reviewsandsurveyshavebeenconductedonLLMsinareas • RQ-3: How do LLMs perform on vulnerability lo- suchasgeneratinghigh-qualitycodeandhigh-coveragetest cation? Identifying the precise location of vulnerabil- cases [17], [18], but a systematic review and evaluation of ities in software systems is of critical importance for open-source LLMs in the field of software vulnerability is mitigating risks and improving software quality. The stillmissing. vulnerability location task involves pinpointing these Inthispaper,wefocusonevaluatingLLMs’performance weaknesses accurately and helps to narrow the scope in various software vulnerability (SV)-related tasks in few- fordeveloperstofixproblems.Therefore,weaimtoin- shot and fine-tuning settings to obtain a basic, comprehen- vestigateLLMs’capabilityineffectivelyidentifyingthe sive, and better understanding of their multi-task ability, precise location of vulnerabilities in software systems, andweaimtoanswerthefollowingresearchquestions. alongside evaluating their performance against state- of-the-artapproachesandpre-trainedLMs. • RQ-1: How do LLMs perform on vulnerability de- • RQ-4: How do LLMs perform on vulnerability de- tection?SoftwareVulnerabilities(SVs)canexposesoft- scription? The vulnerability description task focuses ware systems to risk situations and consequently soft- onconveyingadetailedexplanationoftheseidentified ware function failure. Therefore, detecting these SVs is issues in the source codes and helps participants to an important task for software quality assurance. We better understand the risk as well as its impacts. Un- aim to explore the ability of LLMs on vulnerability derstandingtheintricaciesofvulnerabilitiesinsoftware detection as well as the performance difference com- systemsplaysapivotalroleinalleviatingrisksandbol- pared with state-of-the-art approaches and pre-trained stering software quality. The vulnerability description LanguageModels(LMs). task focuses on conveying a detailed explanation of • RQ-2: How do LLMs perform on vulnerability as- these identified issues in the source codes and helps sessment? In practice, due to the limitation of SQA participants to better understand the risk as well as resources [19], it is impossible to treat all detected SVs its impacts. Our goal is to evaluate LLMs’ ability to equallyandfixallSVssimultaneously.Thus,itisneces- effectively generate vulnerability descriptions within sarytoprioritizethesedetectedsoftwarevulnerabilities software systems and compare their performance with for better treatment. An effective solution to prioritize thatofpre-trainedLMs. those SVs is to use one of the most widely known3 To extensively and comprehensively analyze the LLMs’ language model InstructGPT [28] with a dialog interface ability, we use a large-scale dataset containing real-world that is fine-tuned using the Reinforcement Learning with project vulnerabilities (named Big-Vul [21]). We carefully HumanFeedback(RLHF)approach[28]–[30].RLHFinitially design experiments to discover the findings by answering fine-tunesthebasemodelusingasmalldatasetofprompts fourRQs.Themaincontributionofourworkissummarized as input and the desired output, typically human-written, as follows and takeaway findings are shown in Table 1. to refine its performance. Subsequently, a reward model is Eventually,wepresentthecomparisonofLLMsacrossfour trainedonalargersetofpromptsbysamplingoutputsgen- softwarevulnerabilitytasksunderdifferentsettings,aswell erated by the fine-tuned model. These outputs are then re- as the impact of varying model sizes on performance, as orderedbyhumanlabelerstoprovidefeedbackfortraining depicted in Fig. 2(a) and Fig. 2(b). In summary, the key therewardmodel.Reinforcementlearning[31]isthenused contributionsofthispaperinclude: to calculate rewards for each output generated based on • We extensively evaluate the performance of LLMs on the reward model, updating LLM parameters accordingly. different software vulnerability tasks and conduct an With fine-tuning and alignment with human preferences, extensive comparison among LLMs and learning-based LLMs better understand input prompts and instructions, approachestosoftwarevulnerability. enhancingperformanceacrossvarioustasks[28],[32]. • We design four RQs to comprehensively understand The application of LLMs in software engineering has LLMs from different dimensions, and provide detailed seen a surge, with models like ChatGPT being employed resultswithexamples. for various tasks (e.g., code review, code generation, and • Wereleaseourreplicationpackageforfurtherstudy[22]. vulnerability detection). Although some works use LLMs forvulnerabilitytasks[33],[34],ourworkdiffersfromthese |
previousstudiesinthefollowingaspects.(1)Closed-source 2 BACKGROUND AND RELATED WORK ChatGPT vs. Open-source LLMs: They only explore the 2.1 LargeLanguageModel capabilities of the closed-source ChatGPT in vulnerability Since the advancements in Natural Language Processing, tasks, whereas we investigate the abilities of both open- Large Language Models (LLMs) [1] have seen widespread sourcecode-relatedLLMsandgeneralLLMsinthesetasks. adoptionduetotheircapacitytobeeffectivelytrainedwith (2) Prompts vs. Few-shot and Fine-tuning Settings: They billions of parameters and training samples, resulting in focus solely on the performance of LLMs using prompts, significantperformanceenhancements.LLMscanreadilybe whichintroducesrandomnessandhindersthereproducibil- applied to downstream tasks through either fine-tuning [2] ityoftheirfindings.Incontrast,weexaminethecapabilities orprompting[3].Theirversatilitystemsfrombeingtrained ofLLMsunderbothfew-shotandfine-tuningsettings,pro- topossessabroadunderstanding,enablingthemtocapture viding the source code and corresponding model files to diverse knowledge across various domains. Fine-tuning ensurethereproducibilityofourexperimentalresults. involves updating the model parameters specifically for a given downstream task through iterative training on a 2.2 SoftwareVulnerability specificdataset.Incontrast,promptingallowsfordirectuti- Software Vulnerabilities (SVs) can expose software systems lizationbyprovidingnaturallanguagedescriptionsorafew to risk situations and consequently make the software un- examplesofthedownstreamtask.Comparedtoprompting, dercyber-attacks,eventuallycausinghugeeconomiclosses fine-tuningisresource-intensiveasitnecessitatesadditional andeventhreateningpeople’slives.Therefore,vulnerability modeltrainingandisapplicableinlimitedscenarios,partic- databaseshavebeencreatedtodocumentandanalyzepub- ularlywhenadequatetrainingdatasetsareunavailable. liclyknownsecurityvulnerabilities.Forexample,Common LLMs are usually built on the transformer architec- VulnerabilitiesandExposures(CVE)[35],[36]andSecurity- ture [23] and can be classified into three types of ar- Focus[37]aretwowell-knownvulnerabilitydatabases.Be- chitectures: encoder-only, encoder-decoder, and decoder- sides, Common Weakness Enumeration (CWE) defines the only. Encoder-only (e.g., CodeBERT [24], GraphCode- commonsoftwareweaknessesofindividualvulnerabilities, BERT [25], and UniXcoder [26]) and Encoder-Decoder which are often referred to as vulnerability types of CVEs. (e.g., PLBART [27], CodeT5 [7], and CodeT5+ [8]) mod- To better address these vulnerabilities, researchers have els are trained using Masked Language Modeling (MLM) proposed many approaches for understanding the effects or Masked Span Prediction (MSP) objective, respectively, of software vulnerabilities, including SV detection [38]– whereasmallportion(e.g.,15%)ofthetokensarereplaced [50],SVassessment[20],[51]–[54],SVlocation[55]–[57],SV with either masked tokens or masked span tokens, LLMs repair [58]–[61] as well as SV description [62]–[65]. Many are trained to recover the masked tokens. These models novel technologies are adopted to promote the progress are trained as general ones on the code-related data and of software vulnerability management, including software then are fine-tuned for the downstream tasks to achieve analysis [66], [67], machine learning [38], [45], and deep superior performance. Decoder-only models also attract a learning[51],[56],especiallyLLMs[63],[64]. small portion of people’s attention and they are trained by using Causal Language Modeling objectives to predict 3 EXPERIMENTAL DESIGN the probability of the next token given all previous tokens. GPT[2]anditsvariantsarethemostrepresentativemodels, In this section, we present our studied dataset, our studied whichbringthelargelanguagemodelsintopracticalusage. LLMs,thetechniquesforfine-tuning,thepromptengineer- Recently, the ChatGPT model attracts the widest atten- ing,thebaselineapproaches,theevaluationmetrics,andthe tion from the world, which is the successor of the large experimentsettings.4 TABLE1:Takeaways:EvaluatingLLMsonSoftwareVulnerability Dimension FindingorGuidance 1 .LLMscandetectvulnerabilities,butfine-tunedLLMsperformweakerthantransformer-based approaches.ConsideringthecomputationalresourcesandtimecostsofdeployingLLMs, transformer-basedapproachesforvulnerabilitydetectionareamoreefficientchoice. 2 .After fine-tuning,thedetectioncapabilityofLLMshasimproved.Largermodelsusuallyperformbetter, VulnerabilityDetection butperformancecanalsobeinfluencedbymodeldesignandpre-trainingdata.Therefore, fine-tuningtheLLMondomain-specificdatabeforeusingitasavulnerabilitydetectorisnecessary. 3 .Ingeneral,differentLLMscomplementingeachother,whileCodeLlamaobtainsbetter performanceintermsofF1-score,Precision,andRecall. 4 .Overall,fine-tunedcode-relatedLLMsoutperformpre-trainedlanguagemodelsinvulnerability assessment.Whenresourcespermit,fine-tuningDeepSeek-Coder6.7Bforvulnerabilityassessmentis VulnerabilityAssessment optimal,asitoutperformsthepre-trainedlanguagemodelsacrossfourmetrics. 5 .LLMshavethe capacityforassessmentofvulnerabilityseveritybasedonsourcecode,andcanbeimprovedby |
providingmorecontextinformation. 6 .Few-shotsettingexposesLLM’slimitations,andfine-tuningcangreatlyenhancethe VulnerabilityLocation vulnerabilitylocationcapabilitiesofLLMs. 7 .Fine-tuningcode-relatedLLMsasvulnerability locatorsisbeneficial,astheycanoutperformpre-trainedlanguagemodelsintermsofF1-score, precision,andFPR. 8 .LLMsexhibitsignificantlyweakerperformanceingeneratingvulnerabilitydescriptions VulnerabilityDescription comparedtopre-trainedlanguagemodels.Therefore,fine-tuningpre-trainedlanguagemodelsfor vulnerabilitydetectionisrecommended. 3.1 StudiedDataset TABLE2:Statisticofthestudieddataset Weadoptthewidelyuseddataset(namedBig-Vul)provided byFanetal.[21]byconsideringthefollowingreasons.The Datasets #Vul. #Non-Vul. #Total %Vul.:Non-Vul. mostimportantoneistosatisfythedistinctcharacteristicsof OriginalBig-Vul 10,900 177,736 188,636 0.061 therealworldaswellasthediversityinthedataset,which FilteredBig-Vul 5,260 96,308 101,568 0.055 is suggested by previous works [45], [47]. Big-Vul, to the Training 8,720 8,720 17,440 1 bestofourknowledge,isthemostlarge-scalevulnerability Validation 1,090 17,774 18,864 0.061 Testing 1,090 17,774 18,864 0.061 dataset with diverse information about the vulnerabilities, ∗Weundersamplethenon-vulnerablefunctionstoproduceapproximately which are collected from practical projects and these vul- balancedtrainingdata. nerabilitiesarerecordedintheCommonVulnerabilitiesand Exposures(CVE)1.Thesecondoneistocomparefairlywith existing state-of-the-art (SOTA) approaches (e.g., LineVul, 3.2 StudiedLLMs Devign,andSVulD). ThegeneralLLMsarepre-trainedontextualdata,including Big-Vul totally contains 3,754 code vulnerabilities col- natural language and code, and can be used for a variety lected from 348 open-source projects spanning 91 different oftasks.Incontrast,code-relatedLLMsarespecificallypre- vulnerabilitytypesfrom2002to2019.Ithas188,636C/C++ trainedtoautomatecode-relatedtasks.Duetotheempirical functionswithavulnerableratioof5.7%(i.e.,10,900vulner- nature of this work, we are interested in assessing the abilityfunctions).Theauthorslinkedthecodechangeswith effectiveness of both LLM categories in vulnerability tasks. CVEs and their descriptive information to enable a deeper For the code-related LLMs, we select the top four models analysisofthevulnerabilities. released recently (in 2023), namely DeepSeek-Coder [9], We follow the same strategy to build the training data, CodeLlama[11],StarCoder[10],andWizardCoder[68].For validation data, and testing data from the original dataset the general LLMs, we select the top two models, result- withpreviousworkdoes[39],[48],[58].Specifically,80%of ing in the selection of Mistral [69], and Phi-2 [70]. For functions are treated as training data, 10% of functions are the few-shot setting, we select the models with no more treatedasvalidationdata,andtheleft10%offunctionsare than 34B parameters from the Hugging Face Open LLM treatedastestingdata.Wealsokeepthedistributionassame Leaderboard [71], as for the fine-tuning setting, we select astheoriginalonesintraining,validation,andtestingdata. the models with 7B parameters or less. The constraint on Notice that we undersample the non-vulnerable functions the number of parameters is imposed by our computing to produce approximately balanced training data at the resources (i.e., 192GB RAM, 10 × NVIDIA RTX 3090 GPU). functionlevel,whilethevalidationandtestingdataremain Table3summarizesthecharacteristicsofthestudiedLLMs, in the original imbalanced ratio. To clean and normalize we briefly introduce these LLMs to make our paper self- the dataset, we remove empty lines, leading and trailing contained. spaces in each line, as well as comments from the source Group 1: Code-related LLMs.DeepSeek-Coderdeveloped code.Finally,thesplitdatasetisusedforevaluationandthe byDeepSeekAI[9]iscomposedofaseriesofcodelanguage statisticsareshowninTable2. models, each trained from scratch on 2T tokens, with a 1.https://cve.mitre.org/ compositionof87%codeand13%naturallanguageinboth5 TABLE3:OverviewofthestudiedLLMs thingslikewriting,summarizingtexts,andcoding,butwith bettercommonsenseandunderstandingthanitsearlierver- Code-relatedLLMs GeneralLLMs Models sion,Phi-1.5.Phi-2’sevaluationdemonstratesitsproficiency DeepSeek-Coder CodeLlama StarCoder WizardCoder Mistral Phi-2 Fine-Tuning 6.7B 7B 7B 7B 7B 2.7B overlargermodelsinaggregatedbenchmarks,emphasizing Few-Shot 6.7B&33B 7B&34B 7B&34B 7B&15.5B 7B 2.7B the potential of smaller models to achieve comparable or ReleaseDate Nov’23 Aug’23 May’23 June’23 Sep’23 Dec’23 superior performance to their larger counterparts. This is particularly evident in its comparison with Google Gemini English and Chinese. They provide various sizes of the Nano2,wherePhi-2outshinesdespiteitssmallersize. code model, ranging from 1B to 33B versions. Each model is pre-trained on project-level code corpus by employing 3.3 ModelFine-Tuning a window size of 16K and an extra fill-in-the-blank task, to support project-level code completion and infilling. For Thefoursoftwarevulnerabilitytaskscanbecategorizedinto coding capabilities, DeepSeek-Coder achieves state-of-the- two types: discriminative task (i.e., software vulnerability |
artperformanceamongopen-sourcecodemodelsonmulti- detection, software vulnerability assessment, and software pleprogramminglanguagesandvariousbenchmarks. vulnerability location) and generative task (i.e., software CodeLlama proposed by Rozie`re et al. [11] is a set of vulnerability description). Therefore, fine-tuning LLMs for large pre-trained language models for code built on Llama software vulnerability tasks can be undertaken through 2. They achieve state-of-the-art performance among open both discriminative and generative methods, each method modelsoncodetasks,provideinfillingcapabilities,support specifically designed to make LLMs aligned with the task. largeinputcontexts,anddemonstratezero-shotinstruction Inparticular,wetreatthediscriminativetasksasbinaryclas- followingforprogrammingproblems.CodeLlamaiscreated sification, while treating the generative task as generation by further training Llama 2 using increased sampling of one.Thearchitecturesforthetwoparadigmsarepresented code data. As with Llama 2, the authors applied extensive inFig.3. safetymitigationstothefine-tunedCodeLlamaversions. StarCoder proposed by Li et al. [10] is a large pre- trained language model specifically designed for code. It 0 1 0 CVE description: A remote code ... was pre-trained on a large amount of code data to acquire Classifier Decoder programming knowledge and trained on permissive data ... ... ... ... from GitHub, including over 80 programming languages, Encoder / Decoder Encoder / Decoder Git commits, GitHub issues, and Jupyter notebooks. Star- Coder can perform code editing tasks, understand natural void set () { . . . write ( length ... . . . } void set () { . . . write ( length ... . . . } languageprompts,andgeneratecodethatconformstoAPIs. StarCoder represents the advancement of applying large (a) DiscriminativeFine-Tuning (b) GenerativeFine-Tuning languagemodelsinprogramming. WizardCoder proposed by Luo et al. [68] is a large Fig.3:Fine-tuningLLMsforsoftwarevulnerabilitytasks pre-trained language model that empowers Code LLMs withcomplexinstructionfine-tuning,byadaptingtheEvol- Discriminative Fine-Tuning. For vulnerability detec- Instruct method to the domain of code. Through compre- tion and vulnerability assessment, we utilize the “Au- hensive experiments on four prominent code generation toModelForSequenceClassification” class provided by the benchmarks,namelyHumanEval,HumanEval+,MBPP,and Transformers library to implement discriminative fine- DS-1000, the authors unveil the exceptional capabilities of tuning. “AutoModelForSequenceClassification” is a generic their model. It surpasses all other open-source Code LLMs model class that will be instantiated as one of the by a substantial margin. Moreover, WizardCoder even out- sequence classification model classes of the library performs the largest closed LLMs, Anthropic’s Claude and when created with the “AutoModelForSequenceClassifica- Google’sBard,onHumanEvalandHumanEval+. tion.from pretrained(model name or path)”classmethod. Group 2: General LLMs. Mistral is a 7-billion-parameter For vulnerability location, we follow previous language model released by Mistral AI [69]. Mistral 7B is works [72], [73] that use LLMs to classify individual code a carefully designed language model that provides both lines as either vulnerable or non-vulnerable. For a token efficiency and high performance to enable real-world ap- sequence T = {t 1,t 2,...,t n} of the function, the model’s plications.Duetoitsefficiencyimprovements,themodelis decoder component, denoted as M, processes T to yield a suitableforreal-timeapplicationswherequickresponsesare sequence of output vectors: O = M(T) = {o 1,o 2,...,o L}, essential.Atthetimeofitsrelease,Mistral7Boutperformed where O represents the output tensor with dimensions the best open source 13B model (Llama 2) in all evaluated L×H, L signifies the sequence length, and H denotes the benchmarks. hidden dimension size. During the process, the contextual Phi-2proposedbyMicrosoft[70]packedwith2.7billion information is captured by the masked self-attention parameters.Itisdesignedtomakemachinesthinkmorelike mechanisms in the decoder of LLMs, where masked self- humansanddoitsafely.Phi-2isnotjustaboutnumbers;it attention limits the sight to the preceding part of tokens. is about a smarter, safer way for computers to understand Each output vector o i that represents the last token of one and interact with the world. Phi-2 stands out because it is lineissubsequentlyassociatedwithalabel(i.e.,0or1).The been taught with a mix of new language data and careful optimization process employs the binary cross-entropy as checks to make sure it acts right. It is built to do many thelossfunction.6 TABLE4:Thetaskdescriptionsandindicatorsfordifferentsoftwarevulnerabilitytasks Dimension TaskDescription Indicator VulnerabilityDetection IfthisCcodesnippethasvulnerabilities,outputYes;otherwise,outputNo. //Detection VulnerabilityAssessment ProvideaqualitativeseverityratingsofCVSSv2.0forthevulnerableCcodesnippet. //Assessment VulnerabilityLocation ProvideavulnerabilitylocationresultforthevulnerableCcodesnippet. //Location VulnerabilityDescription ProvideaCVEdescriptionforthevulnerableCcodesnippet. //Description Generative Fine-Tuning. Generative fine-tuning aims to Prompt equip LLMs with the ability to perform Sequence-to- 1 Task Description: Sequence (Seq2Seq) tasks. Specifically, this involves in- |
putting vulnerable code and generating the corresponding If this C code snippet has vulnerabilities, output Yes; otherwise, output No. CVEdescriptionsrelatedtothevulnerabilities.Tocalculate 2 Source Code: thelossduringfine-tuning,weutilizethecross-entropyloss // Code Start function, which is commonly used for Seq2Seq tasks. In void SendStatus(struct mg_connection* connection, const struct this context, the loss measures the difference between the mg_request_info* request_info, void* user_data) { generatedoutputsequenceandthetargetsequence. std::string response = "HTTP/1.1 200 OK\r\n" "Content-Length:2\r\n\r\n" "ok"; 3.4 PromptEngineering mg_write(connection, response.data(), response.length()); Forfew-shotsetting,wefollowthepromptsimilartothose } used in the artifacts, papers, or technical reports associated // Code End with each corresponding model [5], [10], [11], where each 3 Indicator: prompt contains three pieces of information: (1) task de- // Detection scription, (2) source code, and (3) indicator. Using the soft- warevulnerabilitydetectiontaskasanexample,theprompt Fig. 4: The prompt contains three pieces of information: (1) utilized for LLM consists of three crucial components, as taskdescription,(2)sourcecode,and(3)indicator depictedinFig.4: • Task Description (marked as ①). We provide LLM with the description constructed as ‘‘If this C code are designed for learning data representations and trained snippet has vulnerabilities, output Yes; using the Masked Language Modeling (MLM) objective. otherwise, output No’’. The task description used Encoder-decoder LMs (i.e., PLBART [27], CodeT5 [7], and in the SV detection task varies based on the source CodeT5+[8])havebeenproposedforsequence-to-sequence programminglanguageweemploy. tasks. They are trained to recover the correct output se- • Source Code (marked as ②). We provide LLM with the quencegiventheoriginalinput,oftenthroughspanpredic- codewrappedin‘‘// Code Start’’and‘‘// Code tion tasks where random spans are replaced with artificial End’’SinceweillustrateanexampleinC,weusetheC tokens. Recently, researchers have combined MLM with commentformatof‘‘//’’asaprefixforthedescription. generative models for bidirectional and autoregressive text We also employ different comment prefixes based on the generationorinfilling[74].AlltheseLMscanpotentiallybe programminglanguageofthecode. usedforourtasks,soweevaluatetheseLMs. • Indicator(markedas③).WeinstructLLMtothinkabout the results. In this paper, we follow the best practice in TABLE5:OverviewofthestudiedLMs previous work [12] and adopt the same prompt named ‘‘// Detection’’. Models #Para. ModelType Models #Para. ModelType CodeBERT 125M Encoder-onlyLM PLBART 140M Encoder-decoderLM Depending on the specific software vulnerability tasks, GraphCodeBERT 125M Encoder-onlyLM CodeT5 220M Encoder-decoderLM the task descriptions and indicators in the prompts may UniXcoder 125M Encoder-onlyLM CodeT5+ 220M Encoder-decoderLM ∗ForUniXcoder,weuseencoder-onlymode. vary.Thetaskdescriptionsandindicatorsfordifferentsoft- warevulnerabilitytasksarepresentedinTable4. Forvulnerabilitylocation,wealsoconsiderDevign[38], Reveal [47], IVDetect [56], and LineVul [39] as baselines. 3.5 Baselines In addressing vulnerability detection, we also include TocomprehensivelycomparetheperformanceofLLMswith SVulD [48] in addition to the aforementioned approaches. existing approaches, in this study, we consider the various Webrieflyintroducethemasfollows. pre-trained Language Models (LMs). As shown in Table 5, Devign proposed by Zhou et al. [38] is a general graph these models have fewer than 220 million parameters and neural network-based model for graph-level classification can be categorized into two categories: encoder-only LMs through learning on a rich set of code semantic representa- and encoder-decoder LMs. Encoder-only LMs (i.e., Code- tionsincludingAST,CFG,DFG,andcodesequences.Ituses BERT[24],GraphCodeBERT[25],andUniXcoder[26])con- a novel Conv module to efficiently extract useful features tain only the encoder component of a Transformer. They in the learned rich node representations for graph-level7 classification. our computing resources. Table 3 summarizes the charac- RevealproposedbyChakrabortyetal.[47]containstwo teristics of the studied LLMs. Furthermore, considering the main phases. In the feature extraction phase, it translates limitation of LLM’s conversation windows, we manually code into a graph embedding, and in the training phase, selectthreeexamplesforthefew-shotsettingfromthetrain- ittrainsarepresentationlearnerontheextractedfeaturesto ingdata.Regardingbaselines(i.e.,pre-trainedLMs,Reveal, obtainamodelthatcandistinguishthevulnerablefunctions IVDetect, Devign, LineVul, and SVulD), we utilize their fromnon-vulnerableones. publiclyavailablesourcecodeandperformfine-tuningwith IVDetect proposed by Li et al. [56] contains the coarse- thedefaultparametersprovidedintheiroriginalcode.Con- grainedvulnerabilitydetectioncomponentandfine-grained sidering Devign’s code is not publicly available, we make interpretation component. In particular, IVDetect repre- everyefforttoreplicateitsfunctionalityandachievesimilar sents source code in the form of a program dependence results on the original paper’s dataset. All these models |
graph(PDG)andtreatsthevulnerabilitydetectionproblem are implemented using the PyTorch [75] framework. The as graph-based classification via graph convolution net- evaluationisconductedona16-coreworkstationequipped workwithfeatureattention.Asforinterpretation,IVDetect withanIntel(R)Xeon(R)Gold6226RCPU@2.90Ghz,192GB adopts a GNNExplainer to provide fine-grained interpre- RAM, and 10 × NVIDIA RTX 3090 GPU, running Ubuntu tations that include the sub-graph in PDG with crucial 20.04.1LTS. statementsthatarerelevanttothedetectedvulnerability. LineVul proposed by Fu et al. [39] is a Transformer- 4 EXPERIMENTAL RESULTS based line-level vulnerability prediction approach. LineVul leveragesBERTarchitecturewithself-attentionlayerswhich Thissectionpresentstheexperimentalresultsbyevaluating cancapturelong-termdependencieswithinalongsequence. LLMs performances on the widely used comprehensive Besides, benefiting from the large-scale pre-trained model, dataset(i.e.,Big-Vul[21])coveringfourSV-relatedtasks. LineVulcanintrinsicallycapturemorelexicalandlogicalse- manticsforthegivencodeinput.Moreover,LineVuladopts TABLE 6: The comparison between LLMs and eleven base- the attention mechanism of BERT architecture to locate the linesonsoftwarevulnerabilitydetection(RQ1) vulnerablelinesforfiner-graineddetection. SVulD proposed by Ni et al. [48] is a function-level Methods F1-score Recall Precision Accuracy subtlesemanticembeddingforvulnerabilitydetectionalong Devign 0.200 0.660 0.118 0.726 withheuristicexplanations.Particularly,SVulDadoptscon- Reveal 0.232 0.354 0.172 0.811 IVDetect 0.231 0.540 0.148 0.815 trastive learning to train the UniXcoder semantic embed- LineVul 0.272 0.620 0.174 0.828 ding model for learning distinguishing semantic represen- SVulD 0.336 0.414 0.282 0.915 tationoffunctionsregardlessoftheirlexicallysimilarinfor- CodeBERT 0.270 0.608 0.173 0.830 GraphCodeBERT 0.246 0.721 0.148 0.771 mation. UniXcoder 0.256 0.787 0.153 0.764 PLBART 0.255 0.692 0.157 0.791 CodeT5 0.237 0.759 0.141 0.748 3.6 EvaluationMetrics CodeT5+ 0.218 0.508 0.139 0.812 Forconsideredsoftwarevulnerability-relatedtasks,wewill Fine-TuningSetting performevaluationsusingthewidelyadoptedperformance DeepSeek-Coder6.7B 0.270 0.627 0.172 0.824 metrics. More precisely, to evaluate the effectiveness of CodeLlama7B 0.259 0.806 0.154 0.761 StarCoder7B 0.220 0.607 0.135 0.778 LLMs on vulnerability detection and vulnerability assess- WizardCoder7B 0.214 0.365 0.151 0.861 ment,weconsiderthefollowingfourmetrics:F1-score,Re- Mistral 0.220 0.607 0.135 0.778 call,Precision,andAccuracy.Additionally,forvulnerability Phi-2 0.241 0.557 0.154 0.818 location, besides the four aforementioned metrics, we also Few-ShotSetting consider the Top-k Accuracy and FPR metrics. For vulner- DeepSeek-Coder6.7B 0.084 0.156 0.057 0.823 DeepSeek-Coder33B 0.107 0.688 0.058 0.404 ability description, we use Rouge-1, Rouge-2, and Rouge-L CodeLlama7B 0.098 0.449 0.055 0.570 metrics. CodeLlama34B 0.117 0.281 0.074 0.781 StarCoder7B 0.094 0.443 0.053 0.560 StarCoder15.5B 0.097 0.557 0.053 0.463 3.7 Implementation WizardCoder7B 0.086 0.380 0.049 0.583 WizardCoder34B 0.128 0.559 0.072 0.607 WedevelopthegenerationpipelineinPython,utilizingPy- Mistral 0.126 0.401 0.074 0.711 Torch[75]implementationsofDeepSeekCoder,CodeLlama, Phi-2 0.099 0.563 0.054 0.471 StarCoder, WizardCoder, Mistral, and Phi-2. We use the Huggingface [76] to load the model weights and generate outputs. We also adhere to the best-practice guide [77] 4.1 RQ-1:EvaluatingVulnerabilityDetectionofLLMs for each prompt. For the fine-tuning setting, we select the models with 7B parameters or less, and for the few-shot InthisRQ,wefirstinvestigatethevulnerabilitydetectionof setting, we use models with fewer than 34B parameters. LLMsandmakeacomparisonwiththeexistingstate-of-the- To directly compare the fine-tuning setting with the few- art (SOTA) approaches. Then, we conduct a more detailed shot setting, we employ models with the same parameter analysisoftheresults,comparingthedetectionperformance in both settings (i.e., DeepSeek-Coder 6.7B, CodeLlama 7B, ofLLMsundertheTop-10CWEtypes. StarCoder7B,WizardCoder7B,Mistral7B,andPhi-22.7B). ExperimentalSetting.WeinstructLLMswiththefollowing The constraint on the number of parameters is imposed by taskdescriptiontotellittoactasavulnerabilitydetector.8 TABLE7:ThesoftwarevulnerabilitydetectioncomparisononTop-10CWEsamongfine-tunedLLMs(RQ1) DeepSeek-Coder CodeLlama StarCoder WizardCoder Mistral Phi-2 DeepSeek-Coder CodeLlama StarCoder WizardCoder Mistral Phi-2 CWEType #Total #Vul. F1-score Precision CWE-119 1549 128 0.321 0.309 0.316 0.269 0.258 0.281 0.223 0.197 0.212 0.215 0.181 0.197 CWE-20 1082 80 0.269 0.273 0.229 0.216 0.145 0.269 0.173 0.163 0.141 0.165 0.096 0.175 |
CWE-264 800 64 0.486 0.468 0.337 0.348 0.356 0.477 0.357 0.316 0.232 0.308 0.269 0.361 CWE-399 697 35 0.355 0.286 0.209 0.274 0.227 0.306 0.227 0.169 0.125 0.191 0.143 0.196 CWE-125 582 29 0.233 0.267 0.213 0.195 0.179 0.180 0.145 0.156 0.129 0.128 0.108 0.109 CWE-200 573 27 0.269 0.261 0.241 0.180 0.162 0.229 0.182 0.159 0.151 0.132 0.106 0.152 CWE-189 442 21 0.235 0.208 0.255 0.273 0.178 0.293 0.145 0.119 0.151 0.180 0.108 0.182 CWE-362 413 16 0.031 0.086 0.075 0.050 0.026 0.032 0.017 0.045 0.040 0.029 0.014 0.018 CWE-416 406 12 0.193 0.178 0.148 0.145 0.146 0.141 0.113 0.101 0.083 0.093 0.086 0.082 CWE-476 367 11 0.091 0.109 0.053 0.057 0.037 0.019 0.049 0.057 0.028 0.032 0.020 0.010 DeepSeek-Coder CodeLlama StarCoder WizardCoder Mistral Phi-2 DeepSeek-Coder CodeLlama StarCoder WizardCoder Mistral Phi-2 CWEType #Total #Vul. Recall Accuracy CWE-119 1549 128 0.570 0.719 0.625 0.359 0.453 0.492 0.801 0.735 0.777 0.839 0.785 0.792 CWE-20 1082 80 0.609 0.844 0.609 0.313 0.297 0.578 0.804 0.735 0.758 0.866 0.793 0.814 CWE-264 800 64 0.763 0.900 0.613 0.400 0.525 0.700 0.839 0.795 0.759 0.850 0.810 0.846 CWE-399 697 35 0.815 0.926 0.630 0.481 0.556 0.704 0.885 0.821 0.815 0.901 0.854 0.877 CWE-125 582 29 0.586 0.931 0.621 0.414 0.517 0.517 0.808 0.746 0.771 0.830 0.763 0.765 CWE-200 573 27 0.514 0.743 0.600 0.286 0.343 0.457 0.829 0.743 0.770 0.841 0.784 0.812 CWE-189 442 21 0.625 0.813 0.813 0.563 0.500 0.750 0.853 0.776 0.828 0.891 0.833 0.869 CWE-362 413 16 0.200 0.800 0.600 0.200 0.200 0.200 0.847 0.794 0.821 0.908 0.821 0.855 CWE-416 406 12 0.667 0.750 0.667 0.333 0.500 0.500 0.835 0.796 0.773 0.884 0.828 0.820 CWE-476 367 11 0.571 1.000 0.429 0.286 0.286 0.143 0.782 0.687 0.706 0.820 0.719 0.725 Task Description: If this C code snippet has vulnerabilities, Accuracy, which surpass the fine-tuned LLMs by 24.4% to outputYes;otherwise,outputNo. 57.0%, 64.0% to 108.9%, and 6.3% to 20.2% in terms of F1- score,Precision,andAccuracy,respectively.Notably,theF1- score performance of LineVul is significantly lower (0.272) In addition to pre-trained LMs, we also consider the than that reported in the original paper (0.910). We further following five SOTA baselines: Devign [38], Reveal [47], analyzethisdiscrepancyinSection5.1. IVDetect [56], LineVul [39], and SVulD [48]. These base- (2)Theperformanceoffine-tunedLLMsiscomparable lines can be divided into two groups: graph-based (i.e., to graph-based approaches. For example, in terms of F1- Devign, Reveal, and IVDetect) and transformer-based (i.e., score, fine-tuned LLMs achieve a range of 0.214 to 0.270. pre-trained LMs, LineVul, and SVulD). Besides, in order In comparison, graph-based approaches achieve a range of tocomprehensivelycomparetheperformanceamongbase- 0.200to0.232. linesandLLMs,weconsiderfourwidelyusedperformance (3) LLMs under few-shot setting have poor perfor- measures(i.e.,Precision,Recall,F1-score,andAccuracy)and mance compared with baselines. LLMs ranging from 2.7B conduct experiments on the popular dataset. Since graph- to 34B parameters perform less favorably than baselines in based approaches need to obtain the structure information terms of F1-score and Precision. However, as for Accuracy, (e.g., control flow graph (CFG), data flow graph (DFG)) SVulD (transformer-based) obtains the best performance of the studied functions, we adopt the same toolkit with (0.915) and DeepSeek-Coder 6.7B under few-shot setting Joerntotransformfunctions.Thefunctionsaredroppedout achieves a performance of 0.823, which is better than the directlyiftheycannotbetransformedbyJoernsuccessfully. threegraph-basedapproaches. Finally, the filtered dataset (shown in Table 2) is used for evaluation.Wefollowthesamestrategytobuildthetraining Finding-1. LLMs can detect vulnerabilities, but fine-tuned data, validation data, and testing data from the original LLMs perform weaker than transformer-based approaches. datasetwithpreviousworkdoes[39],[58].Specifically,80% Consideringthecomputationalresourcesandtimecostsofde- of functions are treated as training data, 10% of functions ployingLLMs,transformer-basedapproachesforvulnerability aretreatedasvalidationdata,andtheleft10%offunctions detectionareamoreefficientchoice. are treated as testing data. We also keep the distribution as same as the original ones in training, validation, and [B] Fine-Tuning vs. Few-Shot.Theexperimentalresults testingdata.Weundersamplethenon-vulnerablefunctions are presented in Table 6. Based on these experimental find- |
to produce approximately balanced training data at the ings, we can draw the following observations: (1) LLMs functionlevel,whilethevalidationandtestingdataremain fine-tunedforvulnerabilitydetectiondemonstratesuperior in the original imbalanced ratio. Apart from presenting the performance on the task compared to LLMs in the few- overall performance comparison, we also give the detailed shot setting. The average F1-score and average Precision performanceofLLMsontheTop-10CWEtypesforabetter havedoubled,whiletheaverageRecallhasalsoshownim- analysis. provement.(2)LLMswithmoreparameterstypicallyexhibit Results.[A] LLMs vs. Baselines.Table6showstheoverall betterperformance.Forexample,CodeLlama34Bimproves performancemeasuresbetweenLLMsandelevenbaselines upon CodeLlama 7B by 19.4%, 34.5%, and 37.0% in terms andthebestperformancesarehighlightedinbold.Accord- ofF1-score,Precision,andAccuracy,respectively.However, ing to the results in Table 6, we can obtain the following different LLMs may exhibit performance variations due to observations: differences in model design and the quality of pre-training (1)Fine-tunedLLMshavepoorperformancecompared data. (3) Phi-2 achieves performance approximating that of withtransformer-basedapproacheswhenconsideringF1- other LLMs with 7 billion parameters, even with a param- score,Precision,andAccuracy.Inparticular,SVulDobtains eter size of 2.7 billion. This may be attributed to the higher 0.336, 0.282, and 0.915 in terms of F1-score, Precision, and qualityofitspre-trainingdata.9 Finding-2.Afterfine-tuning,thedetectioncapabilityofLLMs from 0.512 to 0.854. This underscores the necessity of fine- hasimproved.Largermodelsusuallyperformbetter,butperfor- tuninginvulnerabilityassessmenttask.Overall,fine-tuned mancecanalsobeinfluencedbymodeldesignandpre-training code-related LLMs outperform pre-trained LMs in vulner- data. Therefore, fine-tuning the LLM on domain-specific data ability assessment. It is worth noting that DeepSeek-Coder, beforeusingitasavulnerabilitydetectorisnecessary. after fine-tuning, achieves the best performance compared to other LLMs and pre-trained LMs. If researchers need to perform tasks such as vulnerability assessment with LLM, [C] The comparisons of Top-10 CWE types between fine-tuning DeepSeek-Coder is a more efficient choice. We LLMs. Table 7 shows the detailed comparisons of Top- also find that Mistral exhibits a relatively smaller improve- 10 CWE types between fine-tuned LLMs. In this table, ment after fine-tuning, which aligns with our expectations, we highlight the best performance for each performance asitisageneralLLM. metric in bold. According to the results, we can achieve the following observations: (1) In most cases, CodeLlama TABLE8:ThecomparisonbetweenLLMsandsixbaselines obtainsbetterperformancethanotherLLMsintermsofF1- onsoftwarevulnerabilityassessment(RQ2) score, Precision, and Recall. Different LLMs have certain advantages in different CWE types, complementing each Methods F1-score Recall Precision Accuracy other. (2) Considering the performance of F1-score, Preci- CodeBERT 0.753 0.730 0.788 0.828 sion,andRecall,CodeLlamaachievesthebestperformances GraphCodeBERT 0.701 0.666 0.772 0.802 on CWE-125 (“Out-of-bounds Read”), CWE-362 (“Concurrent UniXcoder 0.745 0.761 0.734 0.817 ExecutionusingSharedResourcewithImproperSynchronization PLBART 0.735 0.741 0.731 0.789 CodeT5 0.743 0.750 0.741 0.817 (’Race Condition’)”), and CWE-476 (“NULL Pointer Derefer- CodeT5+ 0.706 0.677 0.755 0.789 ence”),whichindicatesCodeLlamaisexceptionallyskilledat Fine-TuningSetting detecting and mitigating vulnerabilities related to memory DeepSeek-Coder6.7B 0.814 0.785 0.854 0.860 handlingandsynchronizationissues. CodeLlama7B 0.768 0.749 0.794 0.827 StarCoder7B 0.671 0.677 0.666 0.764 Finding-3. In general, different LLMs complementing each WizardCoder7B 0.793 0.778 0.813 0.842 Mistral 0.525 0.539 0.512 0.759 other,whileCodeLlamaobtainsbetterperformanceintermsof Phi-2 0.747 0.732 0.767 0.802 F1-score,Precision,andRecall. Few-ShotSetting DeepSeek-Coder6.7B 0.229 0.339 0.310 0.262 DeepSeek-Coder33B 0.290 0.323 0.336 0.335 4.2 RQ-2: Evaluating Vulnerability Assessment of CodeLlama7B 0.310 0.331 0.334 0.373 CodeLlama34B 0.265 0.323 0.327 0.294 LLMs StarCoder7B 0.265 0.342 0.333 0.330 StarCoder15.5B 0.285 0.315 0.329 0.326 In this RQ, we delineate two task descriptions for vulner- WizardCoder7B 0.244 0.351 0.336 0.250 ability assessment: (1) code-based and (2) code-based with WizardCoder34B 0.306 0.330 0.325 0.379 additionalkeyinformation.Wecomparetheperformanceof Mistral 0.283 0.308 0.296 0.424 Phi-2 0.269 0.359 0.355 0.282 LLMsinbothtaskdescriptionsforvulnerabilityassessment and concurrently conduct a case study to illustrate the effectivenessofincorporatingkeyimportantinformation. Finding-4.Overall,fine-tunedcode-relatedLLMsoutperform ExperimentalSetting. We instruct LLM with the following pre-trained LMs in vulnerability assessment. When resources |
task descriptions (i.e., Task Description 1 and Task De- permit, fine-tuning DeepSeek-Coder 6.7B for vulnerability scription 2) to tell it to act as a vulnerability assessor. We assessment is optimal, as it outperforms the pre-trained LMs first provide LLM with the vulnerable codes to explore its acrossfourmetrics. performance (Task Description 1). Moreover, we provide LLM with some key important information, including the CVEdescription,theproject,thecommitmessageaswellas Case Study.Toillustratetheeffectivenessofkeyimpor- thefilenamewhenthevulnerablecodeexiststoinvestigate tant information, we present an instance of a vulnerability theperformancedifferences(TaskDescription2). (CWE-119) in Big-Vul that is exclusively assess by CodeL- lama,asdepictedinTable9.Thisexampleisavulnerability Task Description 1: Provide a qualitative severity rating of intheLinuxproject,categorizedunderCWE-119(Improper CVSSv2.0forthevulnerableCcodesnippet. Restriction of Operations within the Bounds of a Memory Task Description 2: Provide a qualitative severity rating of Buffer Vulnerability). In an initial assessment without criti- CVSS v2.0 for the vulnerable C code snippet (with additional calinformation,CodeLlamadidnotfullygrasptheseverity information). ofthisvulnerabilityandlabeleditas“Medium”.However, with the provision of crucial details, CodeLlama can more Results. Table 8 shows the detailed results of LLMs and accurately evaluate the risk level of this vulnerability. The six baselines on vulnerability assessment. Based on these CVE description for this vulnerability highlights multiple experimentalresults,wecanobserveasignificantimprove- buffer overflows in the net/wireless/nl80211.c file of the ment in the vulnerability assessment capability of LLMs Linux kernel prior to version 2.6.39.2. These vulnerabilities after fine-tuning. Specifically, the accuracy has increased allow local users to gain elevated privileges by leveraging from0.282to0.424,reachingarangeof0.759to0.860,while the CAP NET ADMIN capability during scan operations precision has improved from 0.296 to 0.355, now ranging with an excessively long SSID value. In this scenario, the10 TABLE9:AvulnerablecodeforCodeLlamatoassesswithdifferentprompts(RQ2) ImproperRestrictionofOperationswithintheBoundsofaMemoryBufferVulnerability(CWE-119)inLinux TaskDescription1 ProvideaqualitativeseverityratingsofCVSSv2.0forthevulnerableCcodesnippet. Input1 AnexampleofaCcodesnippetwithvulnerabilities(CVE-2011-2517). Response1 Severity:Medium TaskDescription2 Provide a qualitative severity rating of CVSS v2.0 for the vulnerable C code snippet (with additional information). Input2 Project:Linux FileName:net/wireless/nl80211.c CVE Description: Multiple buffer overflows in net/wireless/nl80211.c in the Linux kernel before 2.6.39.2 allowlocaluserstogainprivilegesbyleveragingtheCAP NET ADMINcapabilityduringscanoperations withalongSSIDvalue. Commit Message: nl80211: fix check for valid SSID size in scan operations. In both trigger scan and sched scanoperations,wewerecheckingfortheSSIDlengthbeforeassigningthevaluecorrectly.Sincethe memorywasjustkzalloc’ed,thecheckwasalwaysfailingandSSIDwithover32characterswereallowedto gothrough.ThiswascausingabufferoverflowwhencopyingtheactualSSIDtotheproperplace.Thisbug hasbeentheresince2.6.29-rc4. Response2 Severity:High Analysis ThetrueSeverityisHigh.Afterprovidingadditionalkeyinformation,CodeLlamaoutputfortheSeverity changedfromMediumtoHigh. lack of proper validation of the SSID length leads to buffer ExperimentalSetting. We select the vulnerable functions overflows, enabling attackers to exploit the vulnerability, withinformationonvulnerablelinesfromthetestingsetfor escalate privileges, and execute malicious code. The com- theevaluationandinstructLLMwiththefollowingtaskde- mit message described that this bug has existed since ver- scriptiontoexploreitsvulnerabilitylocationperformance. sion 2.6.29-rc4 of the Linux kernel. Given this information, CodeLlama reassesses the risk level of this vulnerability Task Description: Provide a vulnerability location result for as “High”. This is because it allows attackers to escalate thevulnerableCcodesnippet. privileges and execute malicious code, and it has persisted foraconsiderableperiodoftime.Itiscrucialtoaddressand For the fine-tuning setting of LLMs and pre-trained patchthisvulnerabilitypromptlybyupdatingtheoperating LMs, we treat the vulnerability location task as a binary systemorkerneltoensuresecurity. classification problem, determining whether each line of To compare the vulnerability assessment capabilities of codeisvulnerableornot.Forthefew-shotsetting,aspecific LLMs after providing key information, we have created a vulnerable function may contain one or several vulnerable performancecomparisonbarchart,asshowninFig.5.LLMs lines, and LLM may also predict one or several potential have limited capacity for assessing vulnerability severity vulnerablelines(Lines predict).WeconvertLines predictinto based solely on source code. However, when provided a binary classification format. For example, if a given vul- withkeyimportantinformation,mostLLMs(i.e.,DeepSeek- nerable function consists of five lines and contains two Coder, CodeLlama, WizardCoder, and Mistral) exhibit sig- vulnerable lines [2, 3], and the LLM predicts one potential nificantly improved vulnerability assessment capabilities, |
vulnerableline[2],weconvertthistoabinaryclassification particularly in terms of the Accuracy metric. The Accuracy format as [0, 0, 1, 0, 0] for ease of computation. To better hasincreasedfromtherangeof0.26-0.42totherangeof0.27- evaluate the vulnerability location performance of LLM 0.56. StarCoder and Phi-2 are showing a declining trend, on a specific vulnerable function, we consider five widely and we believe this may be attributed to the addition of usedperformancemeasures(i.e.,Precision,Recall,F1-score, key information, resulting in an increase in the number of Accuracy,andFPR). inputtokens.TheseLLMsmaynotexcelinhandlingexces- In addition to pre-trained LMs, we also consider the sively long text sequences, and we analyze this further in following four SOTA baselines: Devign [38], Reveal [47], Section5.2.Incontrast,DeepSeek-CoderandMistralexhibit IVDetect [56], and LineVul [39]. For the graph-based ap- significant improvements, possibly due to their proficiency proaches (i.e., Devign, Reveal, and IVDetect), we use GN- inhandlinglongsequentialtext. NExplainer[78],[79]forvulnerabilitylocation.Wecompare the performance of LLMs and these baselines using Top-k Finding-5. LLMs have the capacity for assessment of vulner- Accuracy,asemployedinpreviousworks[39],[79]. ability severity based on source code, and can be improved by Results. Table 10 presents the overall performance of vul- providingmorecontextinformation. nerability location between LLMs and seven baselines. Based on this table, we can achieve the following observa- tions:(1)Fine-tuningcangreatlyenhancethevulnerability 4.3 RQ-3:EvaluatingVulnerabilityLocationofLLMs location capabilities of LLMs. For example, after fine- In this RQ, we first outline how to assess the vulnerability tuning, CodeLlama 7B’s F1-score increases from 0.082 to locationcapabilitiesofLLMs.Then,weproceedtocompare 0.504,recallincreasesfrom0.063to0.396,precisionincreases the vulnerability location abilities of LLMs across different from 0.116 to 0.691, accuracy increases from 0.882 to 0.919, settings, both at a general level and in detail, and analyze and FPR decreases from 0.043 to 0.021. (2) Code-related thereasonsbehindtheobserveddifferences. LLMs often outperform pre-trained LMs in terms of F1-11 ' H H S 6 H H N & |