text
stringlengths
64
2.99M
Table2:PerformanceofChatGPTonVulnerabilityDetectionusingDifferentPrompts.Bestresultsareshowninbold. Java C/C++ Vulnerable Non-Vulnerable All Vulnerable Non-Vulnerable All Prompt P R F1 Det. P R F1 Det. Acc P R F1 Det. P R F1 Det. Acc CFGNN 0.831 0.144 0.245 143/995 0.383 0.948 0.546 529/558 0.437 1.000 0.105 0.191 2/19 0.393 1.000 0.564 11/11 0.433 Bugram 0.469 0.032 0.061 38/1171 0.435 0.953 0.598 874/917 0.436 0.507 0.514 0.51 511/995 0.459 0.453 0.456 411/908 0.484 Pb 0.659 0.932 0.772 1091/1171 0.815 0.384 0.522 352/917 0.691 0.524 0.992 0.686 1007/1015 0.429 0.007 0.013 6/922 0.523 Pr-r-b 0.727 0.450 0.556 527/1171 0.528 0.784 0.631 719/917 0.597 0.500 0.136 0.214 138/1015 0.472 0.850 0.607 784/922 0.476 Pr-b 0.726 0.817 0.769 957/1171 0.722 0.606 0.659 556/917 0.725 0.523 0.982 0.682 1009/1015 0.523 0.002 0.004 2/922 0.522 Pr-a-b 0.894 0.622 0.734 728/1171 0.652 0.906 0.759 831/917 0.747 0.521 0.758 0.618 646/852 0.490 0.250 0.331 198/791 0.514 Pr-b-d 0.784 0.564 0.656 661/1171 0.590 0.802 0.680 735/917 0.669 0.525 0.970 0.682 985/1015 0.516 0.035 0.065 32/922 0.525 Pr-a-b-d 0.636 0.735 0.682 861/1171 0.578 0.462 0.514 424/917 0.615 0.564 0.159 0.249 136/852 0.489 0.867 0.626 686/791 0.500 detectedvulnerabilitiesandasmalldecreaseinthenumberofnon- vulnerabilitiesdetected,andtheoverallaccuracyremainsalmost unchanged. Finding2:Includingataskroleinthepromptmayenhance theperformanceofChatGPTonvulnerabilitydetectionbutthe improvementisprogramming-language-specific. BiasofPrediction.Tab.2alsoshowsthat,onbothJavaandC/C++ data,mostfunctionsarepredictedtobevulnerablebyChatGPT whenusingbasicprompts.Giventheunbalancedprediction,itis Figure2:Ratingdistributionsforvulnerabilityexplanations. essentialtoinvestigatewhether ChatGPTsimplypredictsmost functionsasvulnerablewithoutinspectingthedetailsofthesource code due to the reason that the question contains the keyword “buggy”.Therefore,wedesignthereverse-questionpromptP r-r-b Finding4:Withthebasicprompt,ChatGPTismorecapable and replace “buggy” with “correct” in the prompt. From Tab. 2, ofidentifyingvulnerabilitiesinJavaprogramsthaninC/C++ wecanseethatusingP r-r-b,ChatGPTtendstobebiasedtoward programs,butitcannotunderstandvulnerabilitiescomprehen- predictingthefunctionasnon-vulnerable,suggestingthatChatGPT sively. tendstoguesstheansweraccordingtothekeywordintheprompt. 5.3 UsefulnessofAuxiliaryInformation(RQ2) Finding3:Withthesimplebasicprompt,theresponseofChat- GPTisbiasedtowardthekeywordintheprompt. Next,weinvestigatetheimpactofincorporatingauxiliaryinforma- tionintheprompt.ItcanbeseenfromTab.2that,onbothdatasets, theaccuracyof P andP decreasesondetectingvulnerable r-a-b r-d-b datacomparedtoP .Onthenon-vulnerabilitydata,theaccuracy ComprehensionofVulnerability.ToinvestigatewhetherChat- r-b of P andP significantlyincreases.Wecanalsoseethat, GPTwithbasicpromptscancorrectlyunderstandvulnerabilities. r-a-b r-d-b ontheJavadataset,addingAPIcallstothepromptresultsinan Wedraw200samplesfromthetruepositiveresultsofvulnerable accuracyof0.747,whichisabout8%higherthanP .OntheC/C++ samples(100fromeachdataset)usingP andaskChatGPTthe r-b b dataset,thepromptincludingdataflowinformationworksbestbut followingquestionfollowingthepromptP : b itdoesnotexceedP byalargemargin. b Iftheanswerisyes,pleasedescribethevulnerability. Finding5:Differentauxiliaryinformationhasdiverseeffects ondifferentprogramminglanguages.IncorporatingAPIcalls ismoreeffectivefordetectingvulnerabilityinJavafunctions, WeinvitedfivemasterstudentsmajoringinComputerScienceto whileincludingdataflowinformationcontributesalittletothe manuallyassessthequalityofthe200vulnerabilityexplanations understandingofC/C++vulnerableprograms. bygivingeachexplanationascoreonafive-pointscale.Theresult isreportedinFig.2.Wecanseethathighscores(4or5)account 5.4 EffectivenessofChain-of-Thought for52%and64%ontheC/C++datasetandtheJavadataset,respec- Prompting(RQ3) tively.Inotherwords,ChatGPTwiththebasicpromptP does b notunderstandalmosthalfofthevulnerabilitiesit“detects”.The 5.4.1 PerformanceofVulnerabilityDetectioninStep2. InTab.3, observationcanbethereasonforthedetectionbiasinFinding3. wereporttheperformanceofvulnerabilitydetectionofstep2inPrompt-EnhancedSoftwareVulnerabilityDetectionUsingChatGPT Conference’17,July2017,Washington,DC,USA Table3:Resultsofchain-of-thoughtprompting.Bestresultsareshowninbold. Java C/C++ Vulnerable Non-Vulnerable All Vulnerable Non-Vulnerable All
Prompt P R F1 Det. P R F1 Det. Acc P R F1 Det. P R F1 Det. Acc P(chain) 0.668 0.93 0.777 1089/1171 0.821 0.409 0.546 375/917 0.701 0.675 0.973 0.797 988/1015 0.943 0.485 0.640 447/922 0.741 2,r-b P(chain) 0.688 0.703 0.695 823/1171 0.609 0.592 0.601 543/917 0.654 0.661 0.855 0.746 728/852 0.771 0.527 0.626 417/791 0.697 2,r-a-b P(chain) 0.704 0.651 0.676 762/1171 0.593 0.65 0.620 596/917 0.65 0.794 0.614 0.692 623/1015 0.660 0.824 0.733 760/922 0.714 2,r-b-d P(chain) 0.714 0.545 0.618 638/1171 0.554 0.721 0.626 661/917 0.622 0.814 0.589 0.684 502/852 0.659 0.855 0.744 676/791 0.717 2,r-a-b-d (chain) chain-of-thought prompting. We can see that P achieves 2,r-b thebestaccuracyonbothJavaandC/C++dataset.Surprisingly, (chain) (chain) P andP ,whichincorporateauxiliaryinformation,per- 2,r-a-b 2,r-b-d (chain) formworsethanP regardingaccuracy.Takingacloserlook, 2,r-b wefindthataddinginformationonAPIcallsordataflowcauses ChatGPTtoidentifymorenon-vulnerablesamplescorrectly.The numberofdetectednon-vulnerablesamplesisincreasingwhilethe detectedvulnerableonesaredecreasingasauxiliaryinformationis Figure3:Ratingdistributionsforsampledanswerstostep1. added.Besides,fortheJavadataset,theresultsofchain-of-thought promptingareworsethanthebasicpromptsshowninTab.2.How- ever,forC/C++dataset,allthechain-of-thoughtpromptsachieve Table4:Accuracybefore/afteraddingcodesummary. superiorresultsthanbasicprompts.Wespeculatethatthediffer- enceiscausedbythepositionofextrainformationandcodeinthe P P P P b r-b s-b r-s-b promptandwewillinvestigatetheimpactofthepositionofthe Java 0.691 0.725 0.657 0.671 compositionsofpromptsinSec.5.5. C/C++ 0.523 0.522 0.526 0.531 Finding6:Chain-of-thoughtpromptinghasdifferenteffects onJavaandC/C++.ItprovidesagreatimprovementonC/C++ callsanddataflow.Weuse𝑠torepresentthecodesummaryinthe datasetbutdegradesthedetectionperformanceonJavadataset. prompt.Theresultsusingsummary-aidedpromptsareshownin Tab.4.Wecanseethattheaccuracydecreasesafteraddingcode 5.4.2 ImpactsofIncludingtheSummaryofCode. Theintermediate summarytotheprompttodetectvulnerabilityontheJavadataset. stepinchain-of-thoughtpromptingaffectsthequalityofthefinal Differently,theperformanceincreasesonC/C++dataset. answer.Althoughwefocusonthedetectionperformanceofstep 2(i.e.,P(chain) )inthechain-of-thoughtprompting,wealsotake Finding8:Addinghigh-qualitycodesummariestoprompts 2 asteptochecktheanswerinstep1.Werandomlyselected200 canimprovethedetectionperformanceofChatGPT.Butthe (chain) impactisprogramming-language-specific. answerstoP generatedbyChatGPT.Theanswerscorrespond 1 to100vulnerabletestcodeand100non-vulnerabletestcoderan- domlysampledfrombothJavaandC/C++data.Weaskfivemaster 5.5 ImpactsofPosition(RQ4) studentsmajoringinComputerSciencetogivearatingusing5 Sincetherearevariousoptionsforthepositionsofdifferentauxil- pointratingscaletoeachanswertoassesswhetherChatGPTcan iaryinformationintheprompt,wealsoinvestigatehowtheposition understandthefunctionalityofthecode.Thedistributionofratings ofadditionalinformationaffectsthedetection.Weattempttwoor- isshowninFig.3.Wecanseethattherearenoanswersthatare dersbyplacing[APIdescription]or[DFdescription]beforeorafter givenaratingof1andnearly90%oftheanswershaveascoreof4 thesourcecode[CODE]forbothbasicpromptP androle-based b orhigher.TheresultdemonstratesthatChatGPTcanunderstand basicpromptP .Anexampleisshownbelow: r-b thepurposeofthefunctionprecisely. BasicPrompt:[POS1].P .[POS2]. Finding7:ChatGPTcanaccuratelyunderstandthefunctional- b ityofcodeinvulnerabilitydetection. RolePrompt:Pr.[POS1].P b.[POS2]. where[POS1]and[POS2]representthetwopositionstoplace[API Chain-of-thoughtpromptingdemandsthemodeltosummarize description]and[DFdescription].Tab.5providestheresultsusing thecodefirstandthendetectthevulnerabilityAlternatively,we differentpositions. canregardthecodesummaryasauxiliaryinformationlikeAPI Wecanseethattherole-basedpromptwith[APIdescription] callsanddataflowtoconstructasinglepromptinsteadoftwo-step locatedin[POS1]achievesthebestaccuracy.Specifically,wecan chain-of-thoughtprompts.Duetotherestrictionofinputlength findthattheoverallaccuracyofplacing[APIdescription]in[POS1] ofChatGPT,weonlytestbasicpromptsthatdonotcontainAPI ishigherthanthatin[POS2]forbothbasicpromptandrole-basedConference’17,July2017,Washington,DC,USA ChenyuanZhang,HaoLiu,JiutianZeng,KejingYang,YuhongLi,andHuiLi Figure4:AccuracyofdifferentvulnerabilitytypesontheJavadataset.ycoordinateindicatestheaccuracyandthenumbers abovethebarsdenotethenumbersofsamplesineachvulnerabilitytype.
Table5:Resultsforusingdifferentsettingsofpositionintheprompts.Bestresultsareshowninbold. Java C/C++ Vulnerable Non-Vulnerable All Vulnerable Non-Vulnerable All Prompt P R F1 Det. P R F1 Det. Acc P R F1 Det. P R F1 Det. Acc Pb-a 0.623 0.832 0.712 974/1171 0.624 0.357 0.454 327/917 0.623 0.480 0.028 0.053 24/852 0.480 0.967 0.642 765/791 0.480 Pa-b 0.832 0.435 0.571 509/1171 0.551 0.888 0.680 814/917 0.634 0.518 0.532 0.525 453/852 0.481 0.467 0.473 369/791 0.500 Pr-b-a 0.721 0.687 0.704 805/1171 0.623 0.660 0.641 605/917 0.675 0.519 0.965 0.675 822/852 0.492 0.037 0.068 29/791 0.518 Pr-a-b 0.894 0.622 0.734 728/1171 0.652 0.906 0.759 831/917 0.747 0.521 0.758 0.618 646/852 0.490 0.250 0.331 198/791 0.514 Pb-d 0.683 0.754 0.717 883/1171 0.638 0.554 0.593 508/917 0.666 0.522 0.943 0.672 957/1015 0.442 0.050 0.090 46/922 0.518 Pd-b 0.648 0.438 0.523 513/1171 0.492 0.696 0.577 638/917 0.551 0.536 0.610 0.571 619/1015 0.494 0.420 0.415 387/922 0.519 Pr-b-d 0.784 0.564 0.656 661/1171 0.590 0.802 0.680 735/917 0.669 0.525 0.970 0.682 985/1015 0.516 0.035 0.065 32/922 0.525 Pr-d-b 0.614 0.743 0.672 870/1171 0.551 0.402 0.465 369/917 0.593 0.502 0.742 0.599 753/1015 0.401 0.190 0.258 175/922 0.479 prompt.Buttheimprovementforthebasicpromptisnotassignifi- WeshowtheaccuracyforthepromptP w.r.t.eachvulnerabil- r-a-b cantasfortherole-basedprompt,suggestingthatdifferentprompts itytypeinFig.4.WecanseethatChatGPTachieves100%accuracy havevaryingsensitivityfortheposition. on7vulnerabilitytypesandwefindthatsometypesamongthe7 Inaddition,wecanobservethattheperformanceonvulnerable perfectly-detecttypes,suchasCWE-193(Off-by-oneError),CWE- andnon-vulnerabledataisdifferentwhenthepositionofAPIinfor- 511(Logic/TimeBomb)andCWE-570(ExpressionisAlwaysFalse), mationvaries.Thenumberoftruepositivesamplesdecreaseson areeasytoidentifybecausetheyhaveobviousboundaryissuesor vulnerabledatabutincreasesonnon-vulnerabledatawhenplacing logicalerrors.Besides,ChatGPTcanachieveanaccuracyofover [APIdescription]in[POS1].TheinjectionofAPIinformationseems 0.5inmorethan80%ofvulnerabilitytypes(41/50),indicatingthat moreconducivetojudgmentonnon-vulnerabledata.However,the ChatGPTcandetectmanyvulnerabilitytypeseventhoughsome situationiscompletelydifferentwhenaddingdataflowinformation. vulnerablecasesarewronglyclassified. Theoverallaccuracyofthepromptswithdataflowinformationin Wealsocheckthetypesthatgetalowaccuracyscorelower [POS2]outperformsthoseplacingdataflowinformationin[POS1]. than0.5.Forexample,noneofthesamplesinCWE-759(Useofa Consequently,thepositionofAPIcallsordataflowinformationhas One-WayHashwithoutaSalt)arepredictedcorrectly.Thiskindof agreatinfluenceontheperformanceofChatGPT,andthesuitable vulnerabilityusuallyoccurswhentheoperationofaddingsaltis choiceofpositionvariesfordifferentauxiliaryinformation. missing.Weinferthatitrequireshumaninterventiontosetrules orinjectextraknowledgeandthusitisdifficultforChatGPTto detectsolelybasedoncodeandtheauxiliaryinformationusedin Finding9:Promptingcanachievebetterperformancewhen thispaper.CWE-328(UseofWeakHash)hasasimilarissue,but placingAPIcallsbeforethecodeandplacingdataflowinforma- ChatGPTachievesabetteraccuracyof0.411onCWE-328than tionafterthecode.Inaddition,addingAPIcallinformationcon- CWE-759.Apartfromthat,ChatGPTperformspoorlyonCWE- tributesmoretothecorrectpredictionofnon-vulnerablesam- 482(ComparinginsteadofAssigning)andCWE-546(Suspicious ples,whileincludingdataflowinformationcontributesmoreto Comment)aswell.ForCWE-482,thevulnerabilityoccurswhen theaccuratepredictionofvulnerablesamples. the“==”symbolismistakenlyusedas“=”.Forexample,“if((isZero ==(zeroOrOne==0))==true)”,whichisalineextractedfroma samplefunctioninCWE-482,shouldbe“(isZero=(zeroOrOne== 5.6 PerformanceonDifferentVulnerability 0))”.Thereisnogrammaticalerrorinthesample,indicatingthat ChatGPTcannotdistinguish“==”and“=”viaunderstandingthe Types(RQ5) context. For CWE-546, it is triggered for suspicious comments, Duetothepagelimit,weonlyreporttheresultsontheJavadataset whichdoesnotactuallyaffectthefunctionalityoftheprogram. whenillustratingthedetectionperformanceofdifferentvulnerabil- itytypes.SimilartrendscanbeobservedontheC/C++dataset.Prompt-EnhancedSoftwareVulnerabilityDetectionUsingChatGPT Conference’17,July2017,Washington,DC,USA Therefore, without processing the comments, ChatGPT cannot [2] SidBlack,StellaBiderman,EricHallahan,QuentinAnthony,LeoGao,Laurence
predictCWE-546correctly. Golding,HoraceHe,ConnorLeahy,KyleMcDonell,JasonPhang,MichaelPieler, USVSNSaiPrashanth,ShivanshuPurohit,LariaReynolds,JonathanTow,Ben Wang,andSamuelWeinbach.2022.GPT-NeoX-20B:AnOpen-SourceAutoregres- Finding 10: ChatGPT can detect vulnerabilities well on siveLanguageModel.arXivPreprint(2022). https://arxiv.org/abs/2204.06745 [3] RishiBommasani,DrewA.Hudson,EhsanAdeli,RussB.Altman,SimranArora, grammar-relatedorsomeboundary-relatedvulnerabilitytypes. SydneyvonArx,MichaelS.Bernstein,JeannetteBohg,AntoineBosselut,Emma Butitcannotachieveahighaccuracyontypesthatarebasically Brunskill,ErikBrynjolfsson,ShyamalBuch,DallasCard,RodrigoCastellon, irrelevanttothecontextorthosethatrequirethemodeltofully NiladriS.Chatterji,AnnieS.Chen,KathleenCreel,JaredQuincyDavis,Dorottya Demszky,ChrisDonahue,MoussaDoumbouya,EsinDurmus,StefanoErmon, understandthecontext. JohnEtchemendy,KawinEthayarajh,LiFei-Fei,ChelseaFinn,TrevorGale,Lauren Gillespie,KaranGoel,NoahD.Goodman,ShelbyGrossman,NeelGuha,Tatsunori Hashimoto,PeterHenderson,JohnHewitt,DanielE.Ho,JennyHong,Kyle 6 THREATSOFVALIDITY Hsu,JingHuang,ThomasIcard,SaahilJain,DanJurafsky,PratyushaKalluri, SiddharthKaramcheti,GeoffKeeling,FereshteKhani,OmarKhattab,PangWei VersionofChatGPT:SinceChatGPTisstillbeingactivelyup- Koh,MarkS.Krass,RanjayKrishna,RohithKuditipudi,andetal.2021.Onthe OpportunitiesandRisksofFoundationModels. arXivPreprint(2021). https: dated,theexperimentalresultsinthispaperonlyrepresentthe //arxiv.org/abs/2108.07258 performanceofChatGPT4.Forfutureversions,theconclusionsin [4] TomB.Brown,BenjaminMann,NickRyder,MelanieSubbiah,JaredKaplan, PrafullaDhariwal,ArvindNeelakantan,PranavShyam,GirishSastry,Amanda thispapermaybecomeinvalid. Askell,SandhiniAgarwal,ArielHerbert-Voss,GretchenKrueger,TomHenighan, DifferentProgrammingLanguages:Weconductexperiments RewonChild,AdityaRamesh,DanielM.Ziegler,JeffreyWu,ClemensWinter, ChristopherHesse,MarkChen,EricSigler,MateuszLitwin,ScottGray,Benjamin onbothJavaandC/C++datasets.Butasobservedinthispaper, Chess,JackClark,ChristopherBerner,SamMcCandlish,AlecRadford,Ilya ChatGPTsometimesperformsdifferentlyonthetwoprogramming Sutskever,andDarioAmodei.2020.LanguageModelsareFew-ShotLearners.In NeurIPS,Vol.33.1877–1901. languages.ItispossiblethatChatGPTmayshowdifferentdetection [5] JialunCao,MeiziniuLi,MingWen,andShing-ChiCheung.2023. Astudyon performance on vulnerability detection for other programming PromptDesign,AdvantagesandLimitationsofChatGPTforDeepLearning languages. ProgramRepair.arXivPreprinthttps://arxiv.org/abs/2304.08191(2023). [6] SicongCao,XiaobingSun,LiliBo,RongxinWu,BinLi,andChuanqiTao.2022. HumanAnnotator.Weasksomemasterstudentsmajoringin MVD:Memory-RelatedVulnerabilityDetectionBasedonFlow-SensitiveGraph NeuralNetworks.InICSE.1456–1468. ComputerSciencetoevaluatethequalityofvulnerabilityexpla- [7] SaikatChakraborty,RahulKrishna,YangruiboDing,andBaishakhiRay.2022. nationsandcodesummaries.Duetothedifferenceofknowledge DeepLearningBasedVulnerabilityDetection:AreWeThereYet?IEEETrans. SoftwareEng.48,9(2022),3280–3296. background,thehumanevaluationmaynotbecompletelycorrect [8] XiaoCheng,GuanqinZhang,HaoyuWang,andYuleiSui.2022.Path-sensitive andunbiased. codeembeddingviacontrastivelearningforsoftwarevulnerabilitydetection.In ISSTA.519–531. VulnerabilityTypes.Thenumberofsamplesindifferentvulner- [9] Min-JeChoi,SehunJeong,HakjooOh,andJaegulChoo.2017.End-to-EndPre- abilitytypesvariesasshowninFig.4.Therefore,thefindingsin dictionofBufferOverrunsfromRawSourceCodeviaNeuralMemoryNetworks. InIJCAI.1546–1553. thisstudymaynotbeuniversalacrossallvulnerabilitytypes.Itis [10] AakankshaChowdhery,SharanNarang,JacobDevlin,MaartenBosma,Gaurav necessarytocollectmorevulnerabilitysamplestoenrichthetwo Mishra,AdamRoberts,PaulBarham,HyungWonChung,CharlesSutton,Sebas- datasetstoverifythefindingsonmoredata. tianGehrmann,ParkerSchuh,KensenShi,SashaTsvyashchenko,JoshuaMaynez, AbhishekRao,ParkerBarnes,YiTay,NoamShazeer,VinodkumarPrabhakaran, EmilyReif,NanDu,BenHutchinson,ReinerPope,JamesBradbury,JacobAustin, 7 CONCLUSION MichaelIsard,GuyGur-Ari,PengchengYin,TojuDuke,AnselmLevskaya,Sanjay Ghemawat,SunipaDev,HenrykMichalewski,XavierGarcia,VedantMisra,Kevin LLMswithstunningintelligencehavesignificantlyaffectedvari- Robinson,LiamFedus,DennyZhou,DaphneIppolito,DavidLuan,Hyeontaek ousareas.Inthispaper,westudytheabilityofprompt-enhanced Lim,BarretZoph,AlexanderSpiridonov,RyanSepassi,DavidDohan,Shivani Agrawal,MarkOmernick,AndrewM.Dai,ThanumalayanSankaranarayana
ChatGPTinsoftwarevulnerabilitydetection,animportanttask Pillai,MariePellat,AitorLewkowycz,EricaMoreira,RewonChild,Oleksandr toensurethesecurityofsoftware.Inparticular,wedesignsev- Polozov,KatherineLee,ZongweiZhou,XuezhiWang,BrennanSaeta,MarkDiaz, eralpromptsthataretailoredforvulnerabilitydetection,including OrhanFirat,MicheleCatasta,JasonWei,KathyMeier-Hellstern,DouglasEck, JeffDean,SlavPetrov,andNoahFiedel.2022.PaLM:ScalingLanguageModeling addingextrainformation(i.e.,APIcallsanddataflowinformation) withPathways.arXivPreprint(2022). https://arxiv.org/abs/2204.02311 and leveraging chain-of-thought prompting. We conduct exten- [11] LeiCui,ZhiyuHao,YangJiao,HaiqiangFei,andXiaochunYun.2021.VulDetector: DetectingVulnerabilitiesUsingWeightedFeatureGraphComparison. IEEE siveexperimentsontwovulnerabilitydatasetstodemonstratethe Trans.Inf.ForensicsSecur.16(2021),2004–2017. effectiveness of prompt-enhanced vulnerability detection using [12] HoaKhanhDam,TruyenTran,TrangPham,ShienWeeNg,JohnGrundy,and ChatGPT.Ourstudyalsopointsoutthemeritanddemeritofusing AdityaGhose.2017. Automaticfeaturelearningforvulnerabilityprediction. arXivPreprint(2017). https://arxiv.org/abs/1708.02368 ChatGPTforvulnerabilitydetection. [13] AshitaDiwan,MilesQ.Li,andBenjaminC.M.Fung.2022.VDGraph2Vec:Vul- nerabilityDetectioninAssemblyCodeusingMessagePassingNeuralNetworks. REFERENCES InICMLA.1039–1046. [14] FengDong,JunfengWang,QiLi,GuoaiXu,andShaodongZhang.2018.Defect [1] RohanAnil,AndrewM.Dai,OrhanFirat,MelvinJohnson,DmitryLepikhin, PredictioninAndroidBinaryExecutablesUsingDeepNeuralNetwork.Wirel. AlexandrePassos,SiamakShakeri,EmanuelTaropa,PaigeBailey,ZhifengChen, Pers.Commun.102,3(2018),2261–2285. EricChu,JonathanH.Clark,LaurentElShafey,YanpingHuang,KathyMeier- [15] DawsonR.Engler,DavidYuChen,andAndyChou.2001. BugsasDeviant Hellstern,GauravMishra,EricaMoreira,MarkOmernick,KevinRobinson,Sebas- Behavior:AGeneralApproachtoInferringErrorsinSystemsCode.InSOSP. tianRuder,YiTay,KefanXiao,YuanzhongXu,YujingZhang,GustavoHernández 57–72. Ábrego,JunwhanAhn,JacobAustin,PaulBarham,JanA.Botha,JamesBradbury, [16] QingGao,SenMa,SihaoShao,YuleiSui,GuoliangZhao,LuyaoMa,XiaoMa, SiddharthaBrahma,KevinBrooks,MicheleCatasta,YongCheng,ColinCherry, FuyaoDuan,XiaoDeng,ShikunZhang,andXianglongChen.2018. CoBOT: ChristopherA.Choquette-Choo,AakankshaChowdhery,ClémentCrepy,Shachi staticC/C++bugdetectioninthepresenceofincompletecode.InICPC.385–388. Dave,MostafaDehghani,SunipaDev,JacobDevlin,MarkDíaz,NanDu,Ethan [17] TianyuGao,AdamFisch,andDanqiChen.2021.MakingPre-trainedLanguage Dyer,VladimirFeinberg,FangxiaoyuFeng,VladFienber,MarkusFreitag,Xavier ModelsBetterFew-shotLearners.InACL/IJCNLP(1).3816–3830. Garcia,SebastianGehrmann,LucasGonzalez,andetal.2023.PaLM2Technical [18] GustavoGrieco,GuillermoLuisGrinblat,LucasC.Uzal,SanjayRawat,Josselin Report.arXivPreprint(2023). https://arxiv.org/abs/2305.10403 Feist,andLaurentMounier.2016.TowardLarge-ScaleVulnerabilityDiscoveryConference’17,July2017,Washington,DC,USA ChenyuanZhang,HaoLiu,JiutianZeng,KejingYang,YuhongLi,andHuiLi usingMachineLearning.InCODASPY.85–96. [43] ZiyangLuo,CanXu,PuZhao,QingfengSun,XiuboGeng,WenxiangHu, [19] XiaodongGu,HongyuZhang,DongmeiZhang,andSunghunKim.2016.Deep ChongyangTao,JingMa,QingweiLin,andDaxinJiang.2023. WizardCoder: APIlearning.InSIGSOFTFSE.631–642. EmpoweringCodeLargeLanguageModelswithEvol-Instruct.arXivPreprint [20] YuxianGu,XuHan,ZhiyuanLiu,andMinlieHuang.2022. PPT:Pre-trained (2023). https://arxiv.org/abs/2306.08568 PromptTuningforFew-shotLearning.InACL(1).8410–8423. [44] PaulaMaddiganandTeoSusnjak.2023.Chat2VIS:GeneratingDataVisualisations [21] DayaGuo,ShuoRen,ShuaiLu,ZhangyinFeng,DuyuTang,ShujieLiu,Long viaNaturalLanguageusingChatGPT,CodexandGPT-3LargeLanguageModels. Zhou,NanDuan,AlexeySvyatkovskiy,ShengyuFu,MicheleTufano,ShaoKun arXivPreprint(2023). https://arxiv.org/abs/2302.02094 Deng,ColinB.Clement,DawnDrain,NeelSundaresan,JianYin,DaxinJiang, [45] TomásMikolov,KaiChen,GregCorrado,andJeffreyDean.2013. Efficient andMingZhou.2021.GraphCodeBERT:Pre-trainingCodeRepresentationswith EstimationofWordRepresentationsinVectorSpace.InICLR. https://arxiv.org/ DataFlow.InICLR. https://openreview.net/pdf?id=jLoC4ez43PZ abs/1301.3781
[22] JacobA.Harer,LouisY.Kim,RebeccaL.Russell,OnurOzdemir,LeonardR.Kosta, [46] KhineYinMon,MasanariKondo,EunjongChoi,andOsamuMizuno.2023. AkshayRangamani,LeiH.Hamilton,GabrielI.Centeno,JonathanR.Key,PaulM. Commit-BasedClass-LevelDefectPredictionforPythonProjects.IEICETrans. Ellingwood,MarcW.McConley,JeffreyM.Opper,PeterChin,andTomoLazovich. Inf.Syst.106,2(2023),157–165. 2018.Automatedsoftwarevulnerabilitydetectionwithmachinelearning.arXiv [47] Van-AnhNguyen,DaiQuocNguyen,VanNguyen,TrungLe,QuanHungTran, Preprint(2018). https://arxiv.org/abs/1803.04497 andDinhPhung.2022.ReGVD:RevisitingGraphNeuralNetworksforVulnera- [23] DavidHin,AndreyKan,HuamingChen,andMuhammadAliBabar.2022.LineVD: bilityDetection.InICSE-Companion.178–182. Statement-levelVulnerabilityDetectionusingGraphNeuralNetworks.InMSR. [48] OpenAI.2023.GPT-4TechnicalReport.arXivPreprint(2023). https://arxiv.org/ 596–607. abs/2303.08774 [24] JordanHoffmann,SebastianBorgeaud,ArthurMensch,ElenaBuchatskaya, [49] OpenAI.2023.gpt-best-practices. https://platform.openai.com/docs/guides/gpt- TrevorCai,ElizaRutherford,DiegodeLasCasas,LisaAnneHendricks,Jo- best-practices hannesWelbl,AidanClark,TomHennigan,EricNoland,KatieMillican,George [50] YuleiPang,XiaozhenXue,andAkbarSiamiNamin.2015.PredictingVulnerable vandenDriessche,BogdanDamoc,AureliaGuy,SimonOsindero,KarenSi- SoftwareComponentsthroughN-GramAnalysisandStatisticalFeatureSelection. monyan, Erich Elsen, Jack W. Rae, Oriol Vinyals, and Laurent Sifre. 2022. InICMLA.543–548. TrainingCompute-OptimalLargeLanguageModels. arXivPreprint(2022). [51] HaoPeng,LiliMou,GeLi,YuxuanLiu,LuZhang,andZhiJin.2015.Building https://arxiv.org/abs/2203.15556 ProgramVectorRepresentationsforDeepLearning.InKSEM,Vol.9403.547–553. [25] Israel.2021.Checkmarx. https://www.checkmarx.com/ [52] SilviuPitis,MichaelR.Zhang,AndrewWang,andJimmyBa.2023. Boosted [26] ZhengbaoJiang,FrankF.Xu,JunAraki,andGrahamNeubig.2020.HowCan PromptEnsemblesforLargeLanguageModels. arXivPreprint(2023). https: WeKnowWhatLanguageModelsKnow.Trans.Assoc.Comput.Linguistics8 //arxiv.org/abs/2304.05970 (2020),423–438. [53] GuanghuiQinandJasonEisner.2021.LearningHowtoAsk:QueryingLMswith [27] TueLe,TuanNguyen,TrungLe,DinhQ.Phung,PaulMontague,OlivierY.de MixturesofSoftPrompts.InNAACL-HLT.5203–5212. Vel,andLizhenQu.2019. MaximalDivergenceSequentialAutoencoderfor [54] RebeccaL.Russell,LouisY.Kim,LeiH.Hamilton,TomoLazovich,JacobHarer, BinarySoftwareVulnerabilityDetection.InICLR. https://openreview.net/pdf? OnurOzdemir,PaulM.Ellingwood,andMarcW.McConley.2018.Automated id=ByloIiCqYQ VulnerabilityDetectioninSourceCodeUsingDeepRepresentationLearning.In [28] BrianLester,RamiAl-Rfou,andNoahConstant.2021.ThePowerofScalefor ICMLA.757–762. Parameter-EfficientPromptTuning.InEMNLP(1).3045–3059. [55] RiccardoScandariato,JamesWalden,AramHovsepyan,andWouterJoosen. [29] XiangLisaLiandPercyLiang.2021. Prefix-Tuning:OptimizingContinuous 2014.PredictingVulnerableSoftwareComponentsviaTextMining.IEEETrans. PromptsforGeneration.InACL/IJCNLP(1).4582–4597. SoftwareEng.40,10(2014),993–1006. [30] ZhenminLiandYuanyuanZhou.2005. PR-Miner:automaticallyextracting [56] CarsonD.Sestili,WilliamS.Snavely,andNathanM.VanHoudnos.2018.Towards implicitprogrammingrulesanddetectingviolationsinlargesoftwarecode.In securitydefectpredictionwithAI.arXivPreprint(2018). https://arxiv.org/abs/ ESEC/SIGSOFTFSE.306–315. 1808.09897 [31] ZhenLi,DeqingZou,ShouhuaiXu,HaiJin,YaweiZhu,andZhaoxuanChen.2022. [57] LwinKhinShar,LionelC.Briand,andHeeBengKuanTan.2015.WebApplication SySeVR:AFrameworkforUsingDeepLearningtoDetectSoftwareVulnerabilities. VulnerabilityPredictionUsingHybridProgramAnalysisandMachineLearning. IEEETrans.DependableSecur.Comput.19,4(2022),2244–2258. IEEETrans.DependableSecur.Comput.12,6(2015),688–707. [32] ZhenLi,DeqingZou,ShouhuaiXu,XinyuOu,HaiJin,SujuanWang,Zhijun [58] LwinKhinSharandHeeBengKuanTan.2013. PredictingSQLinjectionand Deng,andYuyiZhong.2018.VulDeePecker:ADeepLearning-BasedSystemfor crosssitescriptingvulnerabilitiesthroughmininginputsanitizationpatterns. VulnerabilityDetection.InNDSS. Inf.Softw.Technol.55,10(2013),1767–1780. [33] GuanjunLin,ShengWen,Qing-LongHan,JunZhang,andYangXiang.2020. [59] TaylorShin,YasamanRazeghi,RobertL.LoganIV,EricWallace,andSameer SoftwareVulnerabilityDetectionUsingDeepNeuralNetworks:ASurvey.Proc. Singh.2020. AutoPrompt:ElicitingKnowledgefromLanguageModelswith
IEEE108,10(2020),1825–1848. AutomaticallyGeneratedPrompts.InEMNLP(1).4222–4235. [34] GuanjunLin,JunZhang,WeiLuo,LeiPan,OlivierY.deVel,PaulMontague, [60] DominikSobania,MartinBriesch,CarolHanna,andJustynaPetke.2023. An andYangXiang.2021. SoftwareVulnerabilityDiscoveryviaLearningMulti- AnalysisoftheAutomaticBugFixingPerformanceofChatGPT.arXivPreprint DomainKnowledgeBases.IEEETrans.DependableSecur.Comput.18,5(2021), (2023). https://arxiv.org/abs/2301.08653 2469–2485. [61] Aarohi Srivastava, Abhinav Rastogi, Abhishek Rao, Abu Awal Md Shoeb, [35] GuanjunLin,JunZhang,WeiLuo,LeiPan,andYangXiang.2017. POSTER: AbubakarAbid,AdamFisch,AdamR.Brown,AdamSantoro,AdityaGupta, VulnerabilityDiscoverywithFunctionRepresentationLearningfromUnlabeled AdriàGarriga-Alonso,AgnieszkaKluska,AitorLewkowycz,AkshatAgarwal, Projects.InCCS.2539–2541. AletheaPower,AlexRay,AlexWarstadt,AlexanderW.Kocurek,AliSafaya,Ali [36] GuanjunLin,JunZhang,WeiLuo,LeiPan,YangXiang,OlivierY.deVel,andPaul Tazarv,AliceXiang,AliciaParrish,AllenNie,AmanHussain,AmandaAskell, Montague.2018.Cross-ProjectTransferRepresentationLearningforVulnerable AmandaDsouza,AmeetRahane,AnantharamanS.Iyer,AndersAndreassen, FunctionDiscovery.IEEETrans.Ind.Informatics14,7(2018),3289–3297. AndreaSantilli,AndreasStuhlmüller,AndrewM.Dai,AndrewLa,AndrewK. [37] StephanLipp,SebastianBanescu,andAlexanderPretschner.2022.Anempirical Lampinen,AndyZou,AngelaJiang,AngelicaChen,AnhVuong,AnimeshGupta, studyontheeffectivenessofstaticCcodeanalyzersforvulnerabilitydetection. AnnaGottardi,AntonioNorelli,AnuVenkatesh,ArashGholamidavoodi,Arfa InISSTA.544–555. Tabassum,ArulMenezes,ArunKirubarajan,AsherMullokandov,AshishSab- [38] ChaoLiu,XuanlinBao,HongyuZhang,NengZhang,HaiboHu,XiaohongZhang, harwal,AustinHerrick,AviaEfrat,AykutErdem,AylaKarakas,andetal.2022. andMengYan.2023.ImprovingChatGPTPromptforCodeGeneration.arXiv BeyondtheImitationGame:Quantifyingandextrapolatingthecapabilitiesof Preprint(2023). https://arxiv.org/abs/2305.08360 languagemodels.arXivPreprint(2022). https://arxiv.org/abs/2206.04615 [39] JiachangLiu,DinghanShen,YizheZhang,BillDolan,LawrenceCarin,and [62] YuleiSuiandJinglingXue.2016.SVF:interproceduralstaticvalue-flowanalysis WeizhuChen.2022. WhatMakesGoodIn-ContextExamplesforGPT-3?.In inLLVM.InCC.265–266. DeeLIO@ACL.100–114. [63] YiTay,MostafaDehghani,VinhQ.Tran,XavierGarcia,JasonWei,XuezhiWang, [40] PengfeiLiu,WeizheYuan,JinlanFu,ZhengbaoJiang,HiroakiHayashi,and HyungWonChung,DaraBahri,TalSchuster,HuaixiuStevenZheng,DennyZhou, GrahamNeubig.2023.Pre-train,Prompt,andPredict:ASystematicSurveyof NeilHoulsby,andDonaldMetzler.[n.d.]. UL2:UnifyingLanguageLearning PromptingMethodsinNaturalLanguageProcessing.ACMComput.Surv.55,9 Paradigms.InICLR. https://openreview.net/pdf?id=6ruVLB727MC (2023),195:1–195:35. [64] HugoTouvron,ThibautLavril,GautierIzacard,XavierMartinet,Marie-Anne [41] VivianLiuandLydiaB.Chilton.2022.DesignGuidelinesforPromptEngineering Lachaux,TimothéeLacroix,BaptisteRozière,NamanGoyal,EricHambro,Faisal Text-to-ImageGenerativeModels.InCHI.384:1–384:23. Azhar,AurélienRodriguez,ArmandJoulin,EdouardGrave,andGuillaumeLam- [42] XiaoLiu,YananZheng,ZhengxiaoDu,MingDing,YujieQian,ZhilinYang,and ple.2023. LLaMA:OpenandEfficientFoundationLanguageModels. arXiv JieTang.2021.GPTUnderstands,Too.arXivPreprint(2021). https://arxiv.org/ Preprint(2023). https://arxiv.org/abs/2302.13971 abs/2103.10385 [65] HuantingWang,GuixinYe,ZhanyongTang,ShinHweiTan,SongfangHuang, DingyiFang,YansongFeng,LizhongBian,andZhengWang.2021.CombiningPrompt-EnhancedSoftwareVulnerabilityDetectionUsingChatGPT Conference’17,July2017,Washington,DC,USA Graph-BasedLearningWithAutomatedDataCollectionforCodeVulnerability [73] JunZhang,YangXiang,YuWang,WanleiZhou,YongXiang,andYongGuan. Detection.IEEETrans.Inf.ForensicsSecur.16(2021),1943–1958. 2013.NetworkTrafficClassificationUsingCorrelationInformation.IEEETrans. [66] SongWang,DevinChollak,DanaMovshovitz-Attias,andLinTan.2016.Bugram: ParallelDistributedSyst.24,1(2013),104–117. bugdetectionwithn-gramlanguagemodels.InASE.708–719. [74] SusanZhang,StephenRoller,NamanGoyal,MikelArtetxe,MoyaChen,Shuohui [67] SongWang,TaiyueLiu,andLinTan.2016. Automaticallylearningsemantic Chen,ChristopherDewan,MonaT.Diab,XianLi,XiVictoriaLin,TodorMihaylov, featuresfordefectprediction.InICSE.297–308. MyleOtt,SamShleifer,KurtShuster,DanielSimig,PunitSinghKoura,Anjali
[68] JasonWei,XuezhiWang,DaleSchuurmans,MaartenBosma,BrianIchter,Fei Sridhar,TianluWang,andLukeZettlemoyer.2022. OPT:OpenPre-trained Xia,EdH.Chi,QuocV.Le,andDennyZhou.2022.Chain-of-ThoughtPrompting TransformerLanguageModels.arXivPreprint(2022). https://arxiv.org/abs/2205. ElicitsReasoninginLargeLanguageModels.InNeurIPS,Vol.35.24824–24837. 01068 [69] ShengWen,MohammadSayadHaghighi,ChaoChen,YangXiang,WanleiZhou, [75] WayneXinZhao,KunZhou,JunyiLi,TianyiTang,XiaoleiWang,YupengHou, andWeijiaJia.2015.ASwordwithTwoEdges:PropagationStudiesonBothPosi- YingqianMin,BeichenZhang,JunjieZhang,ZicanDong,YifanDu,ChenYang, tiveandNegativeInformationinOnlineSocialNetworks.IEEETrans.Computers YushuoChen,ZhipengChen,JinhaoJiang,RuiyangRen,YifanLi,XinyuTang, 64,3(2015),640–653. ZikangLiu,PeiyuLiu,Jian-YunNie,andJi-RongWen.2023.ASurveyofLarge [70] JulesWhite,SamHays,QuchenFu,JesseSpencer-Smith,andDouglasC.Schmidt. LanguageModels.arXivPreprint(2023). https://arxiv.org/abs/2303.18223 2023.ChatGPTPromptPatternsforImprovingCodeQuality,Refactoring,Re- [76] ZihaoZhao,EricWallace,ShiFeng,DanKlein,andSameerSingh.2021.Calibrate quirementsElicitation,andSoftwareDesign. arXivPreprint(2023). https: BeforeUse:ImprovingFew-shotPerformanceofLanguageModels.InICML, //arxiv.org/abs/2303.07839 Vol.139.12697–12706. [71] AohanZeng,XiaoLiu,ZhengxiaoDu,ZihanWang,HanyuLai,MingDing, [77] KaiyangZhou,JingkangYang,ChenChangeLoy,andZiweiLiu.2022.Learning ZhuoyiYang,YifanXu,WendiZheng,XiaoXia,WengLamTam,ZixuanMa, toPromptforVision-LanguageModels.Int.J.Comput.Vis.130,9(2022),2337– YufeiXue,JidongZhai,WenguangChen,ZhiyuanLiu,PengZhang,YuxiaoDong, 2348. andJieTang.2023.GLM-130B:AnOpenBilingualPre-trainedModel.InICLR. [78] YaqinZhou,ShangqingLiu,JingKaiSiow,XiaoningDu,andYangLiu.2019.De- https://openreview.net/forum?id=-Aw0rrrPUF vign:EffectiveVulnerabilityIdentificationbyLearningComprehensiveProgram [72] JianZhang,XuWang,HongyuZhang,HailongSun,XudongLiu,ChunmingHu, SemanticsviaGraphNeuralNetworks.InNeurIPS.10197–10207. andYangLiu.2023.DetectingCondition-RelatedBugswithControlFlowGraph [79] Deqing Zou, Sujuan Wang, Shouhuai Xu, Zhen Li, and Hai Jin. 2021. NeuralNetwork.InISSTA.1370–1382. $\mu$𝜇VulDeePecker:ADeepLearning-BasedSystemforMulticlassVulnerabil- ityDetection.IEEETrans.DependableSecur.Comput.18,5(2021),2224–2236.
2308.13062 ZeroLeak: Using LLMs for Scalable and Cost Effective Side-Channel Patching M. Caner Tol Berk Sunar Worcester Polytechnic Institute Worcester Polytechnic Institute mtol@wpi.edu sunar@wpi.edu Abstract 1. Introduction The advent of microarchitectural attacks has instigated efforts to mitigate vulnerabilities in hardware/firmware and Security critical software, e.g., OpenSSL, comes with in deployed software libraries. Earlier vulnerabilities, such numerous side-channel leakages left unpatched due to a as those exploiting secret dependent execution time and lack of resources or experts. The situation will only worsen cache/memory access patterns, were followed by more ad- as the pace of code development accelerates, with devel- vanced attacks exploiting microarchitectural optimizations opers relying on Large Language Models (LLMs) to au- such as out-of-order and speculative execution [31], [28], tomatically generate code. In this work, we explore the transientwriteforwardingandsharedbuffers[45],[7],[41]. use of LLMs in generating patches for vulnerable code One of the earliest and still most accessible forms of with microarchitectural side-channel leakages. For this, we side-channel leakage is execution time. If a developer in- investigate the generative abilities of powerful LLMs by advertently writes code, e.g., with secret data-dependent carefully crafting prompts following a zero-shot learning branches, by measuring the execution time, an attacker approach. All generated code is dynamically analyzed by can deduce secret information. Therefore, identifying vul- leakage detection tools which are capable of pinpointing nerable software and replacing them with their constant- information leakage at the instruction level leaked either time versions has been a goal of security researchers. This from secret dependent accesses or branches or vulnerable is challenging in practice since repositories have complex Spectre gadgets, respectively. Carefully crafted prompts are interdependence with many potentially vulnerable pieces, usedtogeneratecandidatereplacementsforvulnerablecode while their execution time is also dependent on many fac- which are then analyzed for correctness and for leakage tors, e.g., the platform and its configuration, the compiler. resilience. Spectre was first discovered and publicly disclosed After extensive experimentation, we determined that the by security researchers in the original Spectre paper in waypromptsareformedandstackedoveraseriesofqueries 2018 [28]. Spectre v1 occurs when attackers can trick plays a critical role in the LLMs’ ability to generate correct the CPU into speculatively executing code that would not and leakage-free patches. We develop a number of tricks normally be run during normal program execution. By ex- to improve the chances of correct and side-channel secure ploiting this vulnerability, attackers can potentially access code.Moreover,whenwecomparevariousLLMs,wefound sensitive data or information stored in the memory of other that OpenAI’s GPT4 is far superior compared to Google applications or the operating system. The attack leverages PaLM and Meta LLaMA in generating patches with nearly the processor’s speculative execution to infer this sensitive all leakages fixed in a microbenchmark of vulnerable codes data and exfiltrate it. as well as Spectre v1 gadgets. We also found that GPT4 is Inhisblog,Kocher[27]shared15codesnippetsvulner- moresuccessfulthanGPT3.5ingeneratingbothcorrectand abletovariationsofSpectrev1(Spectregadgets)totestout securecode,withmanyfailedattemptsobservedinthelatter. a new version of Microsoft VC/C++ compiler with built- As for efficiency, GPT4 provides a far more efficient patch in mitigation [38] based on the addition of the LFENCE with up to 10 times less overhead when compared to the instruction to sensitive parts of the code identified by Mi- clang compiler-supported lfence Spectre mitigation. From a crosoft’sstaticanalyzer.Thecompileronlymanagestomit- cost/performanceperspective,theGPT4-basedconfiguration igateSpectreinthefirsttwogadgets.Kocherpointsoutthat costs in API calls a mere few cents per vulnerability fixed. his code samples are far from comprehensive, e.g., they all We note, however, that there is great variability in cost, rely on cache modification as a covert channel, and they all dependingonthetypeofvulnerability(leakvs.Spectregad- reside in simple functions more amenable to static analysis. get) and length of the vulnerable code patched. Regardless Cauligietal.[11]presentacomprehensivesurveyofexisting our results show that LLM-based patching is far more cost- Spectre v1 defenses and non-constant time detection tools effective and thus provides a scalable solution. Finally, the e.g.oo7[47],Spectector[20],SpecFuzz[36],Pitchfork[9]. framework we propose will improve in time, especially as Code with microarchitectural vulnerabilities, e.g., secret vulnerability detection tools and LLMs mature. dependent non-constant time or code vulnerable to Spectre 1 3202 guA 42 ]RC.sc[ 1v26031.8032:viXrav1hassincebeenasignificantconcernforthetechindustry. financial resources, they go unpatched. Our goal is to make Hardwareandsoftwarevendorshavereleasedmitigationsto useofthemassiverecentadvancesinLLMssuchasOpenAI reduce the risk of exploitation, but fully addressing these GPT, Google PaLM, and Meta LLaMA to generate patches vulnerabilities remains an ongoing challenge. Moreover, automatically. Note that LLMs are fairly large, and it takes these mitigations often come at the cost of decreased per- weeks to months to train on massive datasets, resources formance, as they may disable or limit certain speculative that only large companies have access to. Our goal is to
execution features. utilizeLLMsviaAPIaccesstobringdownthecostofpatch Inastudyamongthecryptolibrarydevelopers,61.4%of deployment to cents per microarchitectural leakage. the participants stated that they are either not aware or they do not use the tools for testing and verifying the constant- 1.1. Contributions timeness [24] – a necessary but insufficient condition for side-channelsecurity.Tomakemattersworse,manyofthese • We present the first comprehensive study of state-of-the- librariesthatareusedbymillionsofend-usersaremanaged art LLMs, i.e., OpenAI GPT, Google PaLM 2, and Meta by a small number of developers in open-source projects. LLaMA,toautomaticallypatchmicroarchitecturalvulner- They neither possess the knowledge nor the resources to abilitiessuchassecretdependent(non-constanttime)code patch their software against such low-level leakages. Often and Spectre v1 gadgets. times reported vulnerabilities go ignored and unpatched in • We build a toolchain that tests binaries for leakage publicly available open-source crypto libraries used by mil- and Spectre detection tools, specifically Microwalk [52], lions, e.g., see Microwalk-CI [52], due to lack of resources. Pitchfork [9], Spectector [20], and KLEESpectre [46], Another striking exampleis inthe OpenSSLBlog Post[13] and then automatically generates security patches to be explaining their decision on why they chose not to patch included in the source files using LLMs. for newly discovered Spectre gadgets reported in [35] : • From a Continuous Integration/Continuous Development “Mostpotentiallyvulnerablecodeisextremelynon-obvious, (CI/CD) perspective in the software development life cy- even to experienced security programmers. It would thus be cle,theproposedframeworkallowsustopatchthesource quite easy to introduce new attack vectors or fix existing code(e.g.,C/C++,Javascript,etc.)whiletestingthebinary onesunknowingly.”and“Automatedverificationandtesting aftercompilationonatargetmachine.Comparedtobinary of the attacks is necessary but not sufficient. We do not patching, we retain the ability to review and revise the have automated detection for this family of vulnerabilities source. At the same time, we are also taking into account and if we did, it is likely that variations would escape the effect of the compiler and platform configuration on detection.”. These comments highlight the need for reliable security and efficiency by testing the binary for leakage. and transparent patch automation. This approach allows us to continuously improve the In this work, we study the use of LLMs for automated softwareashardwaresystemsandsoftwarestacksevolve. patching of security-critical software. Indeed, it is expected • On a microbenchmark of C code we compiled from that 80% of the software development lifecycle will use known vulnerabilities, GPT4 excels in patching 97% of generative AI, i.e., LLMs, by 2025 [17]. Thus, evaluating all leakages successfully of every type of patching points LLMs’ capability to generate security-critical implementa- in the benchmark, while the total cost of patching 33 tions is an urgent need. What happens if we use ordinary leaks is at $1.34. GPT3.5 was able to fix 62% of the prompts to generate crypto code, and how can we improve leakage points while costing 19 times less than GPT4. code generation to improve side-channel security while en- Googlechat-bisonandMetaLLaMa2patch56%and suring functional correctness? We are encouraged by rapid 35%acrossallvulnerabilities,respectively,albeitatmuch advances in LLMs. Fueled by recent innovations in Trans- lower cost. former networks, generative models, and the availability of • Our framework is only limited by the capability of the massive datasets and large compute clusters, it has become detection tools, e.g., false positives and negatives, and possible to train Large Language Models (LLMs). LLMs will rapidly improve further with better detection tools. such as GPT3 [6] and GPT4 [37] by OpenAI, BERT [14] Similarly, LLMs are improving at an astounding rate andPaLM2[3]byGoogle,RoBERTa[33]andLLaMA[43], (almost every month, a new LLM is released), and we [44] by Meta AI have shown impressive performance in expectsignificantimprovementintheoverallperformance AI applications and in natural language processing (NLP). of our tool. These tools are also trained using code snippets, allowing • From an efficiency perspective, with up to ∼ 10× faster one to parse and even generate code in common program- than Spectre v1 patches generated with existing methods, ming languages flexibly. our toolchain significantly outperforms compiler-based In this work, we study the use of LLMs in a zero-shot techniques such as in clang lfence injection. Hence, approach in concert with state-of-the-art leakage and vul- theproposedapproachprovidesanopportunitytoremove nerabilitydetectiontoolstofixdata-dependentnon-constant unnecessary inefficiencies while retaining security. time behavior, as well as secret-dependent branching and • Since we are patching the source code with the output Spectre v1 gadgets. Such vulnerabilities are known to exist generative LLM, the patches are also commented, which in numerous security libraries deployed on millions of ma- makes it easier to make sense of the patch and maintain chines. Yet, due to the lack of resources, i.e., experts and the code. 22. Background Microwalk-CI [52] is a dynamic side-channel analysis framework for easy integration into a JavaScript devel- 2.1. Constant-Time Implementations opment workflow. Microwalk-CI adapts the existing Mi- crowalk [51] framework, which was originally designed for Constant-time implementations refer to cryptographic finding leakages in binary software. For this, Microwalk
algorithmsandmethodsthattakeaconstantamountoftime generates a number of execution traces for a set of random to execute, regardless of the input size or values. This type inputs and then compares them using mutual information of implementation is essential for securing systems against (MI), a robust measure that allows quantitatively assess the timingattacks,whichareatypeofside-channelattackwhere extent of information leakage. MI can capture a wide range an attacker can gain information about a system’s secret of potential leakages, including those from the execution data by observing the execution times. A practical example path and memory accesses. However, it is worth noting that of this could be seen in the RSA decryption algorithm, Microwalk requires the tester to generate an input template where different execution paths can be chosen based on the file for each function tested and requires interpretation of secretkeybit.Anattackercanutilizethistimingdiscrepancy the report file as it generates entropy estimates. to infer the secret key [29]. The implementation process ofconstant-timecryptographicalgorithmstypicallyrequires 2.2. Spectre v1 meticulous programming to ensure that no branches (such as if-then-else constructs), loops, or other operations are Spectre v1 (CVE-2017-5753), also known as Bounds contingent on the secret data. For instance, cryptographic Check Bypass, affects a wide range of modern processors, algorithms like AES should avoid data-dependent branches including those from Intel, AMD, and ARM. It allows an andemploybit-wiseoperations,whichareknowntoexecute attackertotrickaprogramintospeculativelyexecutingcode in constant time on most platforms. that should not have been executed, potentially leaking sen- sitive data. Figure 2 provides a simple Spectre v1 example. 1 bool equals(byte a[], size_t a_len, Modern CPUs have components for predicting conditional 2 byte b[], size_t b_len) { branch outcomes to execute the instructions speculatively. 3 for (size_t i = 0; i < a_len; i++) The attacker fills the branch history table with malicious 4 if (a[i] != b[i]) // data dependent! entries such that the branch predictor has a high chance 5 return false 6 return true; of misprediction when the victim runs the branch. The 2nd 7 } Figure 1: An example of a data-dependent equality check 1 void victim_function(size_t x){ 2 if(x < size) logic that violates the constant-time property. Adapted 3 temp &= array2[array1[x] * 512]; from [23]. 4 } Challenges exist in guaranteeing a truly constant-time Figure 2: Sample Spectre-V1 C Code implementation, particularly on contemporary CPUs that possess features like out-of-order execution and speculative line checks whether the user input x is in the bound of execution. This necessitates an in-depth understanding of array1. During a regular execution environment, if the both the cryptographic algorithm and the hardware it func- condition is satisfied, the program retrieves xth element of tions on. array1,andamultipleoftheretrievedvalue(512)isused There are several examples of constant-time crypto- as an index to access the data in array2. However, under graphic algorithms, such as the constant-time carry-less some conditions, the size variable might not be present multiplication utilized in AES-GCM implementations and in the cache. In such occurrences, instead of waiting for the constant-time modular inversion employed in elliptic sizetobeavailable,theCPUexecutesthenextinstructions curve cryptography. speculatively.Toeliminateunnecessarypipelinestallswhen A plethora of tools exist for automated verification of sizebecomesavailable.OncetheCPUnoticesthemispre- the constant-time criterion. However, there is a significant diction, it rolls back and follows the correct execution path. discrepancy between academic research and cryptographic Although the results of speculatively executed instructions engineering practice. Despite the availability of tools for are not observable in architectural components, the access checkingconstant-timeexecution,developersoftenoverlook to the array2 leaves a footprint in the cache, making it this due to resource constraints [24]. possible to leak the data through side-channel analysis. Consideringtheescalatingsophisticationofside-channel Spectre v1 is challenging to mitigate because it is a attacks,theincreasingheterogeneity,andtheconstantevolu- hardware-levelissue,andtraditionalsoftware-basedsecurity tionofcomputingplatforms,security-criticalsoftwareneeds measures are not sufficient to fully protect against it. Since to be continuously reevaluated for constant-time execution. Spectre v1 is a complex vulnerability with widespread im- Future research and developmental efforts will perpetually plications across different processor architectures and gen- focus on generating more secure and efficient constant-time erations, it has been an ongoing challenge for the industry algorithms. to address comprehensively. 32.2.1. TestingforSpectre-v1.WebrieflysummarizePitch- a significant percentage of errors uncorrected, pointing to- fork [9], Spectector [20], and KLEESpectre [46]. wards a potential need for better training methods and error KLEESpectre [46] aims to model cache usage with diversity.TheGraph2DiffmodelintroducedbyTarlowetal. symbolicexecutiontodetectspeculativeinterference,which [42] extends the focus to build errors but continues to over- isbasedonKLEEsymbolicexecutionengine.KLEESpectre look security vulnerabilities. The model’s effectiveness is is evaluated on Kocher’s Spectre v1 variants [27] and on also potentially limited in complex scenarios, where precise
cryptographic libraries libTomCrypt, Linux-tegra, diff prediction might not be sufficient or even feasible. openssl and hpn-ssh. ThestudybyPearceetal.[39]isparticularlynoteworthy Pitchfork [9] is a symbolic analysis tool that verifies asitforayedintotherealmofsecurityvulnerabilities.Their that code is constant-time with respect to secret values use of LLMs for zero-shot vulnerability repair is indeed such as encryption keys or message plaintexts. Pitchfork promising. However, their focus is largely limited to basic uses underconstrained symbolic execution augmented with software bugs, which, while important, is only a subset dynamic taint tracking to verify constant-time execution. of the challenges developers face. Despite the potential In particular, it uses a shadow memory to track secrets demonstratedbyLLMs,thestudydidnotextendtheiruseto even as they are stored and loaded from memory. Pitchfork morecomplexandcriticalissues,suchasmicroarchitectural also allows the specification of function hooks. This allows vulnerabilities and sophisticated crypto implementations. Pitchforktoverifyacodeattheprotocollevelwhileignoring Comingfromthehardwareperspective,Ahmadetal.[2] theimplementationofcryptoprimitives.Pitchforkwasused consider how LLMs may be leveraged to repair security- toverifythatalargeportionofMozilla’sNSScryptographic relevant bugs present in Verilog models automatically. In library is constant-time while also finding several constant- particular, they explore the prompt space to show that by time vulnerabilities. using OpenAI’s Codex, one may outperform the Cirfix Spectector [20] introduces the notion of speculative hardware bug repair tool on its own suite of bugs. For non-interference (SNI), and develops an algorithm based Java code repair, Wu et al. [56] analyze five LLMs and on symbolic execution to automatically prove SNI or de- existing automatic program repair (APR) tools on two real- tect violations indicating Spectre vulnerabilities which then world benchmark tools. They find that out of the box, both can be patched. SNI requires that speculatively executed LLMs and APR fix only a small fraction of vulnerabilities instructions do not leak more information into the microar- (about 20% for Codex) but also note that fine-tuning LLMs chitectural state than what the intended behavior does, i.e., using APRs does improve the performance. The study by what is leaked by the standard, non-speculative semantics. Charalambous et al. [12] investigates us of LLMs, specif- To capture “leakage into the microarchitectural state”, we ically GPT3.5-turbo, and formal verification checkers, consider an observer of the program execution that sees the i.e., Efficient SMT-based Context-Bounded Model Checker locations of memory accesses and jump targets. Under this (ESBMC), to fix vulnerabilities in C. The proposed method observer model, an adversary may distinguish two initial achieves an impressive success rate of up to 80% in re- program states if they yield different traces of memory pairing vulnerable code with buffer overflow and pointer locations and jump targets. Spectector is able to detect all dereference failures. leaks in the 15 Spectre v1 variants by Kocher [27] and also Garg et al. [16] focus on fixing hard-to-detect perfor- detect novel, subtle leaks that are out of scope of oo7 [47], mance bugs in C# software with zero-shot LLMs. They andevenidentifycaseswherecompilersunnecessarilyinject take a slightly different approach: given a line of code that countermeasures. contains a performance bug, the line is compared to lines in a pre-constructed knowledge base to retrieve a prompt 3. Related Work command that can be used to convey what change needs to be fed into an LLM. Using OpenAI’s Codex, their tool can The field of automated program repair has seen various generate performance improvement suggestions equivalent advances, but these studies typically focus on syntactic and to or better than a developer in 60% of the cases. build errors, with fewer exploring the domain of security Kande et al. [25] study the use of LLMs for the au- vulnerabilities, and none, to date, have addressed the issue tomatic generation of hardware assertions (in SystemVer- of microarchitectural vulnerabilities. ilog) for vulnerability testing of production-grade hard- DeepFix, as Gupta et al. [21] proposed, aims to au- ware. Their proof of concept study uses OpenAI’s Codex tomatically correct common programming errors using a code-davinci-002 LLM, generating 75,600 assertions sequence-to-sequence neural network model. However, this and generating correct assertions 4.53% of the time. They method is fundamentally limited in scope, as it does not note that while the assertion rate is small, further optimiza- tackle any security vulnerabilities. Its performance is also tion can improve the rate. contingent on the accuracy of error location prediction, Despite substantial advances in automatic program re- whichisinherentlychallenging.Similarly,theBreak-It-Fix- pair, a clear gap persists in addressing complex security It (BIFI) method by Yasunaga et al. [57] primarily targets and especially microarchitectural vulnerabilities in intricate syntactic errors, leaving the important domain of security cryptographicimplementations.WhileLLMsshowpromise, vulnerabilities unaddressed. Moreover, despite improving their capabilities need to be further explored and expanded over previous methods, BIFI’s repair accuracy still leaves to tackle these complex and critical challenges effectively. 4This forms a compelling motivation for our work. the generated code is modular, testing and verification, becomestraightforwardaswell.Togenerateacryptographic
4. Threat Model and Scope algorithm named <A>, we prompt an LLM as shown in Figure 3. Giving context in the zero-shot setting of LLMs is critical to the quality of the generated samples. Since In this work, we focus on preventing secrets from being many of the language models include publicly available leaked through the changes observable to software. Using naturallanguagesourcessuchastextbooks,Wikipedia,etc., microarchitectural side-channels, attackers can obtain sen- they tend to generate long informative texts in the inference sitive information such as encryption keys, passwords, etc. time. The System Prompt in many of the state-of-the- We assume that the attacker wants to exploit a certain side art LLMs acts as high-level and generic commands that channel on the system, and the attack requires security- control the style of generated samples. Since we examine critical software that exhibits one or more of the following automation with as little human interaction as possible, we properties, try to minimize the need for post-processing. We instruct • Code access patterns depend on the secret, the models not to give redundant explanations and inform • Data access patterns depend on the secret, which programming language to be used in the system • The execution time of the code depends on the secret. prompt. Then, we provide the user prompts iteratively. In Although it is possible that even if none of these prop- the first iteration, we instruct the model first to generate a erties exist in logical channels, the underlying hardware list of functions and constants that is required to implement implementation can cause physically visible leakages, such a certain algorithm <A>. This creates a road map for the as through power and electromagnetic emanation, we only next iterations. At every iteration, we instruct the model to consider software-enabled leakages in this work. implement a function that was returned as a list as part of We also assume that the software is free of bugs and the response of the first iteration. Finally, we generate the works in the intended way. Therefore, common software driver function with an example input and key in the last bugs, such as buffer overflow, use-after-free, etc, are not iteration, which helps us to run and test the code. considered in this work. We assume that the attacker has thecapabilitytomeasuretheexecutiontimeofthesoftware System Prompt: or collect other kinds of metadata through shared system You are an expert at implementing cryptographic components such as CPU cache and deduce sensitive in- algorithms in C. Do not give detailed explanations. formation through secret data-dependent branches, memory Just do what the user says. access patterns, or by exploiting speculative execution. User Prompt: We explore the use of state-of-the-art LLMs to improve <Iter 1> List the functions to be the resiliency of security-critical software against these mi- implemented and constants to be defined for the croarchitectural attacks. Since training LLMs from scratch following algorithm: <A> iscostly,time,andenergy-consumingandbearsanenviron- Assume the other functions and constants are defined. mental impact [43], we leave custom-trained LLMs out of <Iter 2> Implement <f_1> function. scope and focus on only zero-shot learning. ... <Iter i> Implement <f_i> function. 5. Generating Crypto Implementations <Iter i+1> Implement the main function with an example input and key. Crypto algorithms are complex and notoriously hard to Figure 3: Prompt template for generating crypto implemen- implement right from scratch. A tedious review process tations.Portions written in <bold> represent variables in is needed to consider all possible corner cases that may the prompt. lead to a security vulnerability. We consider the scenario when one uses LLM-enabled code assistants to generate Wemanuallyinitializetheconstants,e.g.,S-boxentries, crypto code from scratch. Making LLMs generate a whole accordingtothetargetalgorithm’sstandards.Generatingthe cryptographicalgorithmwouldlikelyfailsincethelengthof functions in an iterative way increases the quality of the theresultingcodeismuchlongerthanthetokencapacityof implementation. We also test for functional correctness by popular models. For instance, state-of-the-art GPT4 models verifying if the encryption algorithm generates the correct have a maximum token capacity of 32K, including prompts ciphertext for a certain input and if the plain text and and responses when this work is done. Inspired by the decrypted ciphertext match. chain-of-thought[49]promptingtechniquewhichshowsthat LLMs perform better when it generates intermediate steps rather than the end result directly, we adopt a divide-and- 6. Ensuring Constant-Time Execution conquer strategy by forcing the model to generate smaller pieces of the algorithm one by one. This way, we overcome Sincetheemergenceoftimingside-channelattacks[29], the challenge of creating a large and coherent implemen- manytoolshavebeenproposedtovalidatetheconstant-time tation. Specifically, we generate the algorithm function by (data oblivious) property of software. Nevertheless, the bur- function to preserve the coherence between pieces. Since denofimplementingconstant-timecodepredominantlyrests 5on software engineers to this day. Consequently, numerous security-critical libraries lack any form of testing within Software FFuFnuucnntcicotitnoiosnn Patch Library their CI/CD pipelines for constant-time property [9]. To the best of our knowledge, for the first time, we propose an Compiler/Parser LLM automated tool that generates constant-time implementation based on LLMs. Unit Tests Yes Syntactically No correct? Prompt 6.1. Evaluating Side-Channel Leakage Functionally Prompt Yes No We address a side-channel leakage by assuming a ro- correct? Generator bust adversary (evaluator) with extensive access to runtime Yes events, including memory accesses and the execution path. The adversary can also select and modify any secret system PProrofiflielerrss
L RFeF euau pnkn ocac rtgi tto sieonn Leakage? No Patched input. In the context of cache attacks, the adversary treats memory accesses as a leakage vector, gathering all memory Figure 4: ZeroLeak framework overview. accessesthroughouttheexecutionwithvarioussecretvalues. If a relationship between different secrets and memory access variation is found, the adversary can pinpoint in- few lines of code, which LLMs were shown to be capable structions related to secret-dependent memory accesses and of [39]. However, making a software implementation of an revealpotentialleakages.Varioustoolsexistinthesoftware algorithmconstant-timeisfarmorecomplexsinceitrequires verification landscape to detect such leakages, each capable a deep understanding of algorithm logic, and keeping track of ascertaining the constant-timeness of software [24]. The of how and where the secret is used. Also, a single code selection of a specific tool is contingent upon the particular may have multiple points which contribute to the overall needs and constraints of the task at hand. In our case, we leakage. Therefore, LLMs do not perform well in fixing employ Microwalk [51] due to its blend of benefits while a side-channel leakage in a complex implementation in a acknowledging its limitations. Microwalk leverages mutual single shot. information,arobustmeasurethatallowsustoquantitatively Challenge C2. Second, simply stating that the code is assess the extent of information leakage, providing a clear showing observable traces that are correlated to the secret and interpretable metric. Additionally, Microwalk can cap- is not enough to patch a complex logic. This is also one of tureawiderangeofpotentialleakages,includingthosefrom the reasons why human developers have difficulty creating the execution path and memory accesses. Most importantly a constant-time code without localizing the leakage points. for our use case, it can localize the source of leakage in the Therefore,itisessentialtolocalizetheleakagepointsinthe binary and source code (if available). However, it is worth code for efficient and effective patches for LLMs as well. noting that Microwalk requires executing the target binary multiple times to accurately estimate mutual information, Challenge C3. Finally, prompts should be crafted in the which can increase the computational costs. Hence, our proper way that explains the reason for the leakage in choice balances comprehensive leakage detection, quanti- the most precise and clear manner without leaving any tative assessment capability, and computational feasibility. ambiguity. For example, instructing the LLM to “make the Microwalk first generates arbitrary inputs for a given code constant-time” alone in the prompt without giving any secret. Following this, the target binary is run on each input security context can cause misinterpretation of constant- collecting data on memory allocations, branches, calls, re- timeness in the context of time complexity, i.e., that the turns,memoryreadsandwrites,andstackoperationsineach run-time complexity of the algorithm should be O(1). This run. Ideally, constant-time implementations should have a is clearly insufficient since we want the run-time to be linear execution path for secret input. Secret-dependent independent of the actual input values. conditional branches leak information about the secret. By We overcome C1 by adopting an iterative approach. considering the execution path as a leakage vector, we can Since many of the LLMs are designed as a chatbot, they confirm whether the same operations are performed for any perform better in a conversation with back-and-forth mes- secret input. Another common leakage source, memory ac- sage exchange and with feedback from a human. Since we cess,shouldfollowasecret-independentpatterninconstant- aim to replace humans in the patching process with a tool, time implementations. Hence, we ensure memory accesses we can run the generated code on the target platform with are either constant or at least not correlated to the input. the analysis tool and get feedback without any cost. We use a patching loop that is illustrated in Figure 4 that works as 6.2. Patching for Constant-timeness follows: • Assuming we are testing a function in a library, we Threemainchallengesneedtobeaddressedforautomat- first make sure the function is called from within the ing the constant-time patches using LLMs. Microwalk template and unit tests are ready to verify the Challenge C1. First, patching common software bugs in correctnessofthecode.Theanalysistemplatecanalsobe simple programs often can be resolved by changes in a generated using LLMs with the prompt in Figure 5. 6of the assembly lines to C lines for use in prompts later. User Prompt: Implement a driver code using the following For C3, we use Microwalk’s analysis results, which template. Do not implement any other functions. show the exact leakage points as code lines and categorize #include <stdint.h> the leakage mechanism to certain classes, such as memory #include <stdio.h> access-based and conditional execution. We incorporate the #include <crypto.h> analysis results into natural language, which LLMs can understandbetter,asshowninFigure6.SimilartoSection5, extern void RunTarget(FILE* input){ // Read the input file and assign it to the we give a system prompt to the model but with additional // secret key commands that prevent common mistakes. We identified // Initialize other variables with random data mistakes such as // Execute the primitive // Verify If the primitive works } • generatingonlythepatchedportionofthecodebecause the rest is unchanged, extern void InitTarget(FILE* input){ • calling a hypothetical function or variables that are not // Initialize library defined, // If there isn’t a dedicated initialization // function, just run the first test case for • changing the number and types of arguments to the // the first test case file: givenfunction,andchangingthenameof thefunction, // RunTarget(input); } which all break the program’s compatibility with the rest
of the library. We also describe how new functions can be Figure 5: Prompt for generating the driver code for Mi- added if required. Without this command, the model can crowalk. giveanewfunctionwithoutintegratingitintothemainfunc- tion, which also causes crashes when we directly overwrite the main function. Finally, we include tool and language- specific commands which are not necessary to generate • Then, we compile the code if necessary and run Mi- a secure/functional code but are required to resolve the crowalk on it. Assuming the first version is already cor- compatibilityissues,e.g.,newfeatureslikelet,whichwas rect, our tool starts parsing the analysis files and passes introducedwithES6toJavascriptcausescrashesinJalangi2 the vulnerable functions to LLMs together with prompts which Microwalk backend is based on for Javascript. so they can generate patched code. • The patched code is verified if it is syntactically correct Whenformulatingpromptsforpatchingtheside-channel using parsers/compilers. If the syntax is wrong, we give leakage, we consider the following options in the user feedback to LLM until it generates a syntactically correct prompt: code. If the syntactically correct code fails the functional correctness tests embedded in the Microwalk template, it Option 1 – Leaky Memory Access Pattern: Aftergiving is forwarded to LLM again as well. the full function, we list the name of arrays in the line of • The loop ends when there is no vulnerability found, code and give the full line and instruct the model to make but under limited resources, iteration counts and total the memory accesses independent of the secret. execution times can be limited. Option 2 – Leaky conditional executions: For this case, we parse the if/ternary from the line and instruct the LLM We also append the responses given by the LLM when it toimplementitwithoutifstatementsandternaryoperators. is syntactically correct. As the loop continues, the context Option 3 – Secret dependent loop size: Weparsetheter- giventoLLMlookslike[System, User, Response, minationconditionintheloopandinstructthemodeltokeep User, Response,...],whichisacommonpracticein the number of iterations fixed for every input. chatbot applications. If the context size reaches the maxi- Option 4 – Syntactically/Functionally incorrect code: mum token count of the model, we start dropping from the Some iterations may generate syntactically incorrect code, third message and forward to keep the system prompt and which can be detected even without running it. We use the the original function in the context all the time. feedback from the parser/compiler for the next iteration’s We address C2 by choosing an analysis tool that is prompttoavoidlosingtheattempttopatchotherbugssince capable of localizing the leakage points in the binary and they might still be logically correct. Some iterations may source code. Microwalk is a suitable selection for this pur- generate functionally incorrect code, which can be detected pose. The Javascript version can tell exactly which line in during the run time. For that, we use assert statements in the source doe causes the leakage. The C version, on the the test benches and set the <crash reason> as The other hand, can mark the leakage source at the assembly code is not working correctly.. level. To translate the assembly lines to C source code, we compile it with debug symbols and disassembly the binary Since options are limited in this scenario, semi-adaptive using objdump. More advanced reverse engineering tools, promptcraftingbasedonatemplateworkswell.Foramore such as Ghidra [18] or IDA [22], can also be used for more adaptive system, prompt design can be outsourced from accurate results. After disassembling, we create a mapping generative AI and by chaining LLMs [55], [54]. 7attack mitigation. Hence, in this section, we will focus on System Prompt: You are an expert at implementing constant-time how we can automate low-overhead software mitigations cryptographic algorithms in <language>. using LLMs that are reliably verified on the binary. Patch the given functions according to user′s instructions. Do not give detailed explanations. 7.1. Finding Spectre-v1 Gadgets The generated code should be complete, do not omit any part of the code. It should be able to run without any post-processing. You can implement new FindingSpectre-v1gadgetsinascalableandsoundway functions and integrate them with the original remains an ongoing research area. However, to automate function. Do not introduce new arguments to the the patching process for Spectre-v1 gadgets, we need a given function. Do not change the name of the function. <specifics> tool that is both scalable and sound. In this work, we evaluate the usage of several analysis tools, such as Pitch- User Prompt: fork [9], Spectector [20], and KLEESpectre [46], which <Option 1> covers different aspects of state-of-the-art detection tools, <function to patch> <array names> array is accessed dependent on the secret in line <line>. such as security guarantees, scalability, detection method, Patch the code such that the array access is made out-of-order execution support, handling non-determinism, input independent. and leakage model [10]. Although Pitchfork also supports <Option 2> the Spectre STL (Store-to-Load) variant, we only consider <function to patch> The condition in <if statement> is secret dependent and causes PHT(PageHistoryTable),thecommonvariantsupportedby side channel vulnerability. Patch the code such allthreetools.Spectectorproposesthenotionofspeculative that it does not require any conditional execution. non-interference(SNI),whichrequiresthetargetprogramto <Option 3> have no more leakage than its non-speculative state. This <function to patch> The termination condition in <loop statement> is secret dependent. Patch the property is also classified as relative non-interference [10]. code such that loops execute the same amount of Pitchfork introduces speculative constant time (SCT) notion time for every input. that requires a direct non-interference property which is
<Option 4> stronger than the relative non-interference property. Both <crash reason> The generated code must be complete. Generate everything even if you do not make any Spectector and Pitchfork use a hardware-agnostic constant changes. Try the same patch again. time leakage model. KLEESpectre detects if data leakage causedbythespeculativeexecutionisvisibletotheattacker Figure 6: Prompt template for constant time patch. We re- by extending symbolic execution with micro-architectural place <language> with the programming language, such features,i.e.,cache,andtestseachwayofeveryconditional as C or Javascript. We use <specifics> for instructing branch (taken or not taken). It assumes the branch predictor workarounds for the tool or language-specific compatibility will always mispredict. issues. Other variables are self-explanatory. 7.2. Patching Spectre-v1 Gadgets 7. Mitigating Spectre-v1 Although discovering Spectre-v1 gadgets presents sig- Transientexecutionattacksallowtheattackerstobypass nificant challenges, devising mitigation strategies for these bound checks in array accesses and potentially read any gadgets is equally challenging. In this work, for the first location in the memory, including secret values. Although time,weproposeusingLLMstopatchfunctionswithknown many hardware and software defenses were proposed to leakage points in the transient domain. mitigate these attacks [8], they come with significant over- MostofthechallengesinpatchingSpectregadgetsover- head since the fixes are not precise or are not deployed lap with generating constant time crypto implementations at all due to several reasons, such as lack of resources, that we explained in Section 5 and 6. Therefore overall performance impact, and scalability. Usually, scalable mit- ZeroLeak framework in constant time will apply here as igations come with a cost of high overhead due to too well, with different tools instead of Microwalk in Figure 4. generic design. On the other hand, low-overhead solutions Since all the tools we analyzed are capable of extracting such as index masking require manually changing code. symbolic execution trees, they can pinpoint leakage sources Even after manually adding the mitigation in the source at the assembly level. From assembly, we use the same code, the effect of the mitigation on the binary is often approach in 6.2 to trace it back to the source code. overlooked. One such example of the failure of relying on Our design in prompt template changes according to manual fixes on source code without testing on binary was the speculative leakage mechanism caused by conditional discoveredby[19]ontheLinuxkernel.Aftertheemergence branches. The system prompt we use is very similar, except of Spectre attacks, Linux developers added a new API that we replace “constant-time” with “secure” since we do not implements array_index_nospec macro to clamp the want to instruct the model that there is a non-speculative indexes to the arrays to maximum array size. Although it is leakageinthegivencode.Notethattheleakagemechanism a correct fix, in one case, it was found to be eliminated by in non-speculative scenarios involves secret inputs given the compiler because the compiler semantics is not aware to the program. However, the inputs are controlled by the of speculative execution, and it can optimize out a critical attacker in Spectre-PHT and are not considered secret. For 8User Prompt: Model T maxtoken top-p top-k bestof <Option 1> GPT4-0613 1.0 2048 1.0 - 1 <function to patch> GPT3.5-turbo-0613 1.2 2048 1.0 - 1 <conditional statement> can be speculatively text-davinci-003 0.2 256 0.8 - 5 executed when the condition inside is wrong. Fix code-davinci-edit-001 0.7 - 1.0 - 1 the code such that the condition is checked without an if statement or ternary operator. chat-bison-001 0.2 2048 - - 1 <Option 2> codechat-bison-001 0.2 1024 - - 1 <crash reason> The generated code must be complete. code-bison-001 0.2 1024 - - 1 Generate everything even if you do not make any text-bison-001 0.2 256 0.8 40 1 changes. Try the same patch again. TABLE1:ParameterconfigurationsofdifferentLLMsused in this work. T stands for temperature. max token limits Figure 7: Prompt template for patching Spectre-v1 gadgets. the number of generated responses. top-p and top-k control the diversity in the sampling method by considering probabilities and token counts, respectively. theuserprompts,weconsiderthefollowingtwooptionsthat are illustrated in Figure 7: Option 1 – Spectre-v1 Violation: After giving the full AI5 demo interface for Meta’s model. For the complete function, we parse the statement that includes if condition automation of patching the real-world examples, we use or ternary operators, which are translated as conditional OpenAI API for GPT4. The configuration parameters for branches in the binary by the compiler. We mention that models used in the experiments are given in Table 1. Since speculative execution may cause incorrect executions even we used a readily deployed demo of LLaMA2, we did not if the condition is wrong and instruct the model to replace have access to configuration parameters. the conditional statement. Although more detailed prompts that include further details, such as which array is indexed 8.1. Generating Constant Time AES in C andhowitisdecoded,maysoundmoreintuitive,wechoose amoregenericandprecisepromptthatislessliketoconfuse We start our investigation by evaluating LLMs for gen- low-capacity models; see Section 8.3. erating a constant time crypto algorithm with the help of Option 2 – Syntactically/Functionally incorrect code: analysis tools, such as Microwalk. We prompt the GPT4 We use the same approach as in Section 6.2. modeltogenerateanAES-128implementationasexplained in Section 5, which resulted in an end-to-end implementa-
tion with ten functions for both encryption and decryption. 8. Experiments WeinitializedtheS-box,InverseS-box,androundconstants manually as we instructed the model. Then, we tested the implementation for constant-timeness with Microwalk. We Experiment Setup.Forleakagequantificationforconstant- observed that the implementation followed AES T-table time code, we have used docker images of Microwalk packages with version 3.1.1-pin1 for C, and version implementation, which is known to be leaky. Indeed, Key- 3.1.1-jalangi22 for Javascript code. To compile the Expansion, SubBytes, and MixColumns functions that are used in the encryption contain 11 code lines with memory Spectre gadgets, we used clang version 14.0.0. The ex- access-basedside-channelleakagethatinvolvessixdifferent periments were conducted on a machine equipped with an arrays, including S-box and multiplication tables. Inverse IntelCorei9-7900XCPU,runningUbuntu22.04withkernel functions of SubBytes and MixColumns included 18 lines version5.19.0-50-generic.WeanalyzedninedifferentLLMs with memory access-based leakage. Next, we experimented releasedbyOpenAI,Google,andMeta.Oftheseninemod- with how the prompt template given in Section 6.2 works els, only LLaMA2 with 70B parameters is entirely open- to patch these functions. We observed that our tool was source. For the remaining models, low-level details such as abletopatchallleakagepointsinKeyExpansion,SubBytes, model architecture and training data were not released to MixColumns,andInvSubBytes,makingthemconstanttime. the public. Although we expect the latest model versions However, It was not able to patch InvMixColumns, which to perform better, we choose fixed models that do not get leaks through the multiplication tables. For the Key Ex- upgrades for better reproducibility. Note that all these mod- pansion function, the difference between the original and els are multimodal and support multiple programming and patched versions is given in Figure 8. We see that it natural languages. For the comparison experiments, we use Playground3 web interface of OpenAI models, Vertex AI4 completely eliminates the use of multiplication tables and implements a new function for MixColumn that integrates prompt design interface for Google models, and Perplexity both original and new functions. Thus, we conclude that LLMs can patch implementations with severe leakage by 1.https://github.com/microwalk-project/Microwalk/pkgs/container/ microwalk/92526450?tag=3.1.1-pin changing the design choice. It is also possible to regenerate 2.https://github.com/microwalk-project/Microwalk/pkgs/container/ a given function if there is no leak-free solution can be microwalk/92526123?tag=3.1.1-jalangi2 found. 3.https://platform.openai.com/playground 4.https://cloud.google.com/vertex-ai 5.https://LLaMA.perplexity.ai/ 91 +uint8_t xtime(uint8_t x) { 1 void case_1(uint64_t idx) { 2 + return ((x << 1) ˆ (((x >> 7) & 1) * 0x1b)); 2 if (idx < publicarray_size) { 3 +} 3 asm volatile ("lfence"); 4 void MixColumns(uint8_t *state) { 4 temp &= publicarray2[publicarray[idx] * 512]; 5 - uint8_t i, a, b, c, d, tmp[4]; 5 } 6 + uint8_t i, tmp, tm, t; 6 } 7 8 9 + - - f fo o ar r =( (i i st= = at0 0 e; ; [ii i *< < 41 4 ];6 ;; ii ++)+= {4){ 1 2 v /o /id Ma tc s ha k ese i r_ d a1 x n( gu t ei on ot e f6 n4 s t_ u ht r eei pd i ux t b) la i{ l cw aa ry rs ayfalls within 1 1 1 10 1 2 3 - - - + b c d t = = = = s s s st t t ta a a at t t te e e e[ [ [ [i i i i]* * * ; 4 4 4 + + + 1 2 3] ] ]; ; ; 3 4 5 / // u /iA Ans t c os 6 c pu 4 e em _ s re st as ts t ip a h ou ef nb el _ p ii i u sc d ba x l sr i ar = c fa a ey ri_ d r ns x a oi y wz &e ( w ap i si u ts b h il ta i sc a dp a f oo r e ew r _ se a ir y d n_ x oo s , tf iz t d2 e h e- i p1 s e) n; d 14 + tmp = state[i]ˆstate[i + 1]ˆstate[i + 2] on the condition 1 1 15 6 7 + + + t tm m = =ˆs s xt t ta a it t me e e[ [ (i i t] m+ ˆ )s ;3 ta]; te[i + 1]; 6 7 /u /i Nnt o e6 w v4 a_ p let ur aa f tr o err sa my t_ t ov ha e tl ru c uoe en ,= di tp t hu i eb o nl ni pc c ra h or e cr c ea k ey , d[s aa nf de_ ii fdx i] t; 1 1 2 2 28 9 0 1 2 + - + + + s t t t st m m m ta p at [ = = te 0 e[ ] s x [i t t ia i] = t m +ˆ ( e e= u [ ( 1i i t ]t n mm t + ) ˆˆ 8 ; =t _ 1m t ] tp ) ˆ m; ( s ˆm ttu a ml pt2 e ;[ [a i]ˆ +mu 2l ]3 ;[b]ˆcˆd); 1 18 9 0 1 }i }f t( ei md px &< = p pu ub bl li ic ca ar rr ra ay y_ 2s [i az re r) ay{ _value * 512]; 23 - tmp[1] = (uint8_t)(aˆmul2[b]ˆmul3[c]ˆd); 24 + tm = state[i + 2]ˆstate[i + 3]; Figure 9: Spectre v1 patch examples on source code. The 25 + tm = xtime(tm); top one shows inline lfence mitigation. The bottom one 26 + state[i + 2] ˆ= tmˆtmp; shows the patch generated after our framework. 27 - tmp[2] = (uint8_t)(aˆbˆmul2[c]ˆmul3[d]); 28 + tm = state[i + 3]ˆt; 29 + tm = xtime(tm); 30 + state[i + 3] ˆ= tmˆtmp; pare our method for patching Spectre-v1 gadgets with other 31 - tmp[3] = (uint8_t)(mul3[a]ˆbˆcˆmul2[d]); methodsonamodifiedsetofKocher’sexamples[27],which
32 - state[i * 4] = tmp[0]; includes 16 functions written in C from [9]. To verify if a 33 - state[i * 4 + 1] = tmp[1]; 34 - state[i * 4 + 2] = tmp[2]; code snipped is a Spectre-v1 gadget, we use three different 35 - state[i * 4 + 3] = tmp[3]; tools: Pitchfork, Spectector, and KLEESpectre. USLH has 36 }} a built-in gadget detection tool as well; however, after our evaluation, we observed that it does not detect any of the Figure 8: Constant-time patch for the MixColumns step baseline functions as Spectre-v1 gadget. After we contacted implementation in AES128 generated by GPT4. the authors, they stated that one of the baselines is in their definitionofaSpectregadget,butthetoolneedstobemodi- fied.Therefore,wedidnotincludeitinourexperiments.We 8.2. Patching Spectre-v1 Gadgets also omitted KLEESpectre for compiler-based models due to version incompatibility that requires significant updates Since there are already existing compiler mitigations in the tool, such as new KLEE and LLVM versions. The and software guidelines suggested by hardware vendors, results for leakage evaluation and execution time for each we compare the performance of our approach with them. mitigationoneachcasearelistedinTable2.Wenoticedthat For example, adding an inline lfence statement after if Spectector marks some of cases with inline lfences mark as statements that act as a speculation barrier by waiting until Spectregadgetwhileothersmarkthemassafe.Sincelfence the conditional branch is resolved to continue execution. afterconditionalbranchesareproposedastheultimatemiti- Figure 9 illustrates two different methods for patching a gationbyhardwarevendors,suchasIntel,weconcludethey Spectregadget inthe sourcecode.The firstmethod addsan arefalsepositives.Wemarkedthecaseswith*ifSpectector lfenceinstructionbetweentheifconditionthatchecksif does not terminate. In case 8, inline lfence from the source theuserinputidxiswithinthearrayboundsandwherethat code is not possible since a ternary operator was used as index is used. This way, even if the branch predictor would an array index. We observe that ZeroLeak achieves the mispredict the branch for idx>=publicarray_size, bestperformanceamongthecomparedmitigationtechnique the malicious index would not be used in the array spec- whilestillbeingverifiedassecurebymultipletools.Innine ulatively. The second patch is generated automatically by out of sixteen cases, the overhead caused by our approach GPT4. The method used for this patch is often called index is two cycles or less, which shows us that intelligent and masking, which clamps the value of the attacker-controlled automated patches perform better than generic mitigations. index to the size of the array to be indexed. This way, the attacker cannot read out of bounds. Although from a developerperspective,thecodedoesnotlookveryappealing 8.3. Comparison of LLMs since it has a redundant if condition in line 8, the code is secure.Wealsoconsiderseveralcompiler-basedmitigations To evaluate the effect of selected model, we compare such as clang SLH, clang lfence, and USLH [58]. We com- ninestate-of-the-artLLMsfromprominentcompanies,Ope- 10Cases Baseline(cc) Inlinelfence(cc) clangSLH(cc) clanglfence(cc) USLH(cc)[58] ZeroLeak (cc) 1 6✗p ✗s ✗k 22✓p ✓s ✓k 17✗p ✓s 54✓p ✓s 14✗p ✓s 6✓p ✓s ✓k 2 6✗p ✗s ✗k 30✓p ✓s ✓k 33✗p ✓s 56✓p ✓s 35✗p ✓s 7✓p ✓s ✓k 3 7✗p ✗s ✗k 29✓p ✓s ✓k 32✗p ✓s 57✓p ✓s 34✗p ✓s 9✓p ✓s ✓k 4 6✗p ✗s ✗k 24✓p ✓s ✓k 16✗p ✓s 54✓p ✓s 14✗p ✓s 7✓p ✓s ✓k 5 78✗p ✗s ✗k 105✓p✗s ✓k 170✗p ✓s∗ 399✓p ✓s∗ 148✗p ✓s∗ 88✓p ✓s ✗k† 6 6✗p ✗s ✗k 24✓p ✓s ✓k 16✗p ✓s 58✓p ✓s 14✗p ✓s 6✓p ✓s ✓k 7 6✗p ✗s ✗k 24✓p ✓s ✓k 25✗p ✓s 76✓p ✓s 20✗p ✓s 9✓p ✓s ✓k 8 5✗p ✗s ✗k N/A 17✗p ✓s 42✓p ✓s 15✗p ✓s 16✓p ✓s ✓k 9 4✗p ✗s ✗k 22✓p ✓s ✓k 15✗p ✓s 50✓p ✓s 14✗p ✓s 9✓p ✓s ✓k 10 6✗p ✗s ✗k 21✓p ✓s ✓k 23✗p ✓s 66✓p ✓s 22✗p ✓s 7✓p ✓s ✓k 11gcc 14✗p ✗s ✗k 35✓p ✗s ✓k 65✗p ✓s 98✓p ✓s 64✗p ✓s 17✓p ✓s ✓k 11ker 15✗p ✗s ✗k 35✓p ✗s ✓k 69✗p ✓s 100✓p✓s 66✗p ✓s 20✓p ✓s ✗k† 11sub 12✗p ✗s ✗k 35✓p ✗s ✓k 64✗p ✓s 100✓p✓s 61✗p ✓s 12✓p ✓s ✓k 12 5✗p ✗s ✗k 25✓p ✓s ✓k 16✗p ✓s 55✓p ✓s 14✗p ✓s 7✓p ✓s ✓k 13 5✗p ✗s ✗k 25✓p ✓s ✓k 24✗p ✓s 74✓p ✓s 21✗p ✓s 7✓p ✓s ✓k 14 6✗p ✗s ✗k 25✓p ✓s ✓k 16✗p ✗s 54✓p ✓s 14✗p ✗s 6✓p ✓s ✓k TABLE2:MitigationoverheadoftheSpectre-v1microbenchmark[9]inclockcycles(cc)fordifferentmitigationtechniques. The binaries are compiled with clang. GPT4 was used as the patching agent. ✓ represents the case that is not detected as a Spectre gadget, and ✗ represents the case that is detected as a Spectre gadget. The superscripts p, s, and k represent Pitchfork [9], Spectector [20], and KLEESpectre [46] tools, respectively. Results with † are false positives. Model-Version ReleaseDate Publisher Open-Sourced MemoryLeakage BranchLeakage Spectre-V1 EstimatedCost[USD] GPT4-0613 06/13/2023 ✗ 5/5 12/13 16/16 $1.34 GPT3.5-turbo-0613 06/13/2023 ✗ 2/5 9/13 10/16 $0.07 text-davinci-003 10/28/2022 OpenAI ✗ 0/5 7/13 12/16 $2.29 code-davinci-edit-001 03/15/2022 ✗ 0/5 8/13 5/16 $0† chat-bison-001 07/10/2023 ✗ 0/5 5/13 14/16 $0.06 codechat-bison-001 06/29/2023 ✗ 0/5 6/13 0/16 $0.28 code-bison-001 06/29/2023 Google ✗ 1/5 4/13 0/16 $0.04 text-bison-001 06/07/2023 ✗ 1/5 5/13 0/16 $0.10 LLaMA2-70B 07/18/2023 Meta ✓ 1/5 8/13 3/16 $0‡ TABLE3:PatchingtheLLMgeneratedAESimplementationwithdifferentmodels.Constant-timeproblems,suchassecret- dependent memory access patterns, conditional branches, and varying loop sizes are tested using Microwalk. Spectre-V1 was tested using Pitchfork. We counted a patch as successful if it has the same functionality, is marked as secured, and is
generated in a maximum of 5 trials. †Edit models are free to use by OpenAI. ‡Since we used a demo website, this does not include the cost of deploying the model on a local server and related costs to that. nAI, Google, and Meta, which released their models be- tokens used per model and the current pricing given by the tween March 2022 and July 2023. While LLaMA2 is the publishers. The results are summarized in Table 3. Overall, only fully open-sourced model, we have only API and/or GPT4excelsinpatchingeverytypeofleakageweevaluated webinterfaceaccesstotheotherevaluatedmodels.Wehave compared to other models by successfully patching 97% of only evaluated the LLaMA2 model with 70B number of all leakage points in the benchmark, while the total cost of parameters since the size and capabilities of 7B and 13B patching 33 leaks remains at $1.34. In OpenAI models, we versions are much more limited compared to the 70B one. see an improving trend with the newer releases. GPT3.5 was able to fix 62% of the leakage points while costing 19 For comparing the performance on Spectre-v1, we have times less than GPT4. Models other than GPT4 perform used the same set of examples as used in Section 8.2. better when the LLM commands are simpler and direct, For constant-time patches, i.e., leaky memory access leaving less room for interpretation and easing the burden patterns and leaky conditional branches, we curated a new of understanding. For example, while GPT4 can understand microbenchmarkfromtheearlierresearchpapers[40],[15], the following prompt and remove branches, other models [9], [50], [48], [4], [30], [53], which includes 4 functions fail to understand. Fix the problem such that with memory access pattern leakage, 12 functions with publicarray[idx] does not encode data in branch leakage and 1 function that has both vulnerabilities. publicarray2. But when they are directly instructed The functions are available in Appendix A. We also to avoid conditional statements, they can perform the task prepared a unit test for each of the leaky functions, which to some degree. Therefore, we conclude that as model allows us to ensure functional correctness during patching. capacityisdiminished,thepromptsneedtobemoreprecise We also calculate the estimated cost from the number of 11and clear. Original function: Interestingly, although text-davinci is an older int memory_leakage_case_2_transform(int kval) { model, it gives competent results similar to Google’s return LUT[kval % 16]; } chat-bison model, which was released almost a year Patch: later. We claim it is because it generates five comple- 1 int memory_leakage_case_2_transform(int kval) { tions and selects the best one. Generating five com- 2 // This function is constant-time because the array access is input-independent. pletions at a time also reflects on the cost. Specif- 3 // The array is indexed by a constant value, ically, chat-bison can show a similar performance which does not depend on the secret. with text-davinci and cost 38 times less. Google 4 return LUT[kval % 16]; text-bisonandcodechat-bisonmodelsdonotgen- 5 } erate variations in default temperature (0.2), and even with Figure 10: A failed example from codechat-bison higher temperature levels (0.7), the performance is poor compared to other models. Most of the time, they return the same code back as the “fixed code”. We also observe has no if statement or ternary operator, yet, the compiler that increasing the temperature value does not increase generatesthreedifferentconditionaljumpinstructionsafter the quality of the generated code, and they still generate each comparison to increase the performance. equally unsecure or functionally/syntactically broken code int equal(char *p, char *q) { with higher temperatures. Also, in general, *-bison-001 return (p[0]==q[0])&&(p[1]==q[1])&&(p[2]==q[2]); models do not handle newline characters well, resulting in } all code generated in a single line. Despite being syntacti- Since our framework takes the binary and analyzes it dy- cally/functionally correct, it makes it harder to localize the namically, thesecases are capturedas well andget rejected. leakage and generate a precise prompt. Therefore, we use a code formatter, clang-format, to standardize the format 8.4. Case Study 1: Patching a Real World Spectre- and give better readability for patching agents. v1 Gadget If the interface of the model allows, we continue the patching process by giving the next vulnerable line in the In our experiments in earlier sections, LLMs showed functionafterthepreviousoneisfixed.Ifnot,werestartthe promising performance in Spectre examples. Now, we in- conversation by giving the new version in the user prompt. vestigate how well they can perform on a real-world target. Forfunctionally/syntacticallyincorrectfunctions,wedonot We selected a target implemented in OpenSSL, which was give feedback on the error since it might cause an unfair previouslypointedoutby[35].Inresponse,OpenSSLstated evaluation of the models. Some of the model interfaces are they would not deploy mitigations for Spectre for several designed better to get feedback, e.g., GPT models. In this reasons, including “maintaining code with mitigations in scenario,weregeneratethecodeusingthelastgivencontext. placewouldbesignificantlymoredifficult”and“mitigations Since the models are probabilistic with a temperature value themselves obscure the code, which increases the mainte- ofT ̸=0,itsamplesanewseriesoftokensaccordingtothe nance burden.” [13]. probabilitydistribution.Werarelyseesyntacticallyincorrect Since we observed that LLM-generated patches for responses from all of the models. Although Google models Spectre-v1 gadgets tend to use similar methods, such as
usually generate the same response over and over again, index masking which is commonly used for large commer- since OpenAI and Meta models showed better diversity cial products, such as browsers, We evaluate its potential in the generated code, we tried multiple iterations until on OpenSSL. We use the same system and user prompt we reached the maximum number of trials. We observed templatethatweproposedinSection7.WeuseGPT4asthe that most of the leakage points get fixed in the first patching with the same configuration as before. GPT4 gen- few trials, if they will get fixed at all. Thus, increasing eratesthepatchgiveninFigure11inthe3rd iteration.Note the number of trials in this experiment would not change that the code is generated with the comments that make the the results significantly. We provide an example of failure patch easy to understand. After careful review, we see that fromGoogle’scodechat-bisonmodelinFigure10.The theifconditioniseliminated,andthechecklogicisaccumu- model adds a comment stating the function is constant time latedonthemaskvariable.Whens->shared_sigalgs eventhoughitisthesameexactfunctionwithoutanypatch. array is accessed in line 24, the index is masked with the Surprisingly,weobservedthatcode-specificmodelsperform mask variable. For malicious indices, the function accesses far worse than more generic multimodal chat models such the 0th element instead of a random location, even under as GPT4, GPT3.5, and chat-bison. We hypothesize the speculative execution. The rest of the code is masked with reason is that these generic models have been trained with the same variable as well for functional correctness. more parameters, resulting in a higher capacity for under- standing. Also, they interpret natural language better, which 8.5. Case Study 2: Patching Javascript Crypto Li- is how we translate the feedback from the analysis tools. braries for Constant-Timeness We observe that even if the LLM generates a “constant- time looking” C code in most cases, a verification on the There has been an exponentially growing interest in binarylevelisrequired.Forexample,thefollowingfunction crypto libraries implemented on Javascript over the last 12decade [1] following the trend that is also known as At- wood’s Law which claims if a program can be written User prompt: in Javascript, it will eventually be written in Javascript. <function body> Although the popularity of some of the security-critical if (s->shared_sigalgs == NULL packages seems to follow this law, they are not necessarily || idx < 0 || idx >= (int)s->shared_sigalgslen maintained well, if at all. || s->shared_sigalgslen > INT_MAX) can be In this section, we focus on evaluating our framework speculatively executed when the condition inside on some of the most popular packages available on npm, is wrong. Fix the problem such that the condition whicharepreviouslyshowntobevulnerabletoside-channel is checked without the if or ternary statement. Patch: leakage but have not been patched in years due to the lack of resources. Since the training sets of the state-of-the-art 1 int SSL_get_shared_sigalgs(SSL *s, int idx, int * psign, int *phash, int *psignhash, unsigned LLMs usually include scraped repositories on Github [26], char *rsig, unsigned char *rhash){ theycanprocessmultipleprogramminglanguages,including 2 const SIGALG_LOOKUP *shsigalgs; Javascript. For the evaluation, we selected some of the 3 - if (s->shared_sigalgs == NULL targetsanalyzedbyMicrowalk[52]earlierbutstillremained 4 - || idx < 0 5 - || idx >= (int)s->shared_sigalgslen vulnerable, such as aes-js [34], base64-js [32] and 6 - || s->shared_sigalgslen > INT_MAX) node-forge [5]. Each of these packages has weekly 7 - return 0; downloads ranging from 1M to 15M, which makes their 8 +/* If any of the conditions are true, the mask vulnerability impactful. We used GPT4 on these libraries 9 + * will be set to all 1s (i.e., -1). 10 + * If all conditions are false, using the prompt template explained in Section 6.2. The 11 + * the mask will be 0. */ results are summarized in Table 4. We observed that out 12 + int mask = -((s->shared_sigalgs == NULL) | of 127 unique leakage points across the libraries and files, 13 + (idx < 0) | 117 of them were successfully patched with constant-time 14 + (idx >= (int)s->shared_sigalgslen) | 15 + ((unsigned int)s->shared_sigalgslen >INT_MAX)); implementation in ∼90 minutes. We have detected a new 16 - shsigalgs = s->shared_sigalgs[idx]; branch leakage that was introduced during the patching 17 - if (phash != NULL) process; however, the overall number of unique leakage 18 - *phash = shsigalgs->hash; points has converged to the lowest in this state which is 19 + /* Apply the mask to idx and then use the 20 + * result to index the array. why we stopped further iterations. 21 + * If the mask is all 1s (any of the conditions 22 + * are true), the array is not accessed. Time MemoryLeakage BranchLeakage 23 + * If the mask is 0, idx is used unmodified. */ Library [mins] Patched Patched 24 + shsigalgs = s->shared_sigalgs[idx & ˜mask]; 25 - if (psign != NULL) Total Unique Total Unique 26 - *psign = shsigalgs->sig; aes-js[34] 27 + /* Use the mask to conditionally write the AES-ECB 12.8 16/24 16/24 0/1* 0/1* 28 + * output values. If the mask is 0, the output 29 + * values are written. */ base64-js[32] 30 + *phash = (shsigalgs->hash & mask) base64-encode 17.5 4/4 4/4 - - 31 + | (*phash & ˜mask); base64-decode 4/4 4/4 - -
32 + *psign = (shsigalgs->sig & mask) 33 + | (*psign & ˜mask); node-forge[5] 34 - if (psignhash != NULL) AES-ECB 80/80 40/40 1/1 1/1 35 - *psignhash = shsigalgs->sigandhash; AES-GCM 61.2 284/294 47/49 2/2 1/1 36 + *psignhash = (shsigalgs->sigandhash & mask) base64-decode 4/4 4/4 - - 37 + | (*psignhash & ˜mask); TABLE 4: Patching vulnerable Javascript libraries. Total 38 - if (rsig != NULL) 39 - *rsig = (unsigned char) leakage includes how many times each unique code line 40 - (shsigalgs->sigalg & 0xff); is triggered during the high-level algorithm which also rep- 41 + *rsig = ((unsigned char) resents the importance of each unique leakage. *Introduced 42 + (shsigalgs->sigalg & 0xff) during patching. 43 + & mask) | (*rsig & ˜mask); 44 - if (rhash != NULL) 45 - *rhash = (unsigned char)((shsigalgs->sigalg 46 - >> 8) & 0xff); 9. Ethical Questions with AI Contributions 47 + *rhash = ((unsigned char)((shsigalgs->sigalg 48 + >> 8) & 0xff) & mask) | (*rhash & ˜mask); 49 - return (int)s->shared_sigalgslen; Although the code generated by LLMs is verified as 50 + return (s->shared_sigalgslen & ˜mask) 51 + | (0 & mask); secure by multiple tools, we did not push any code to 52 } security-critical libraries used by millions since it may raise ethical and legal concerns considering the ongoing debate Figure 11: Patching OpenSSL Spectre gadget example on AI ethics and regulations. We instead will share the code with the library authors for their revision with a full disclaimer that they are not generated by human. 1310. Conclusion [6] BROWN, T., MANN, B., RYDER, N., SUBBIAH, M., KAPLAN, J. D., DHARIWAL, P., NEELAKANTAN, A., SHYAM, P., SASTRY, In this work, we introduced ZeroLeak, the first frame- G., ASKELL, A., ET AL. Language models are few-shot learners. Advancesinneuralinformationprocessingsystems33(2020),1877– work that uses LLMs to automatically detect and patch 1901. side-channel vulnerabilities in software. We demonstrated [7] CANELLA, C., GENKIN, D., GINER, L., GRUSS, D., LIPP, M., the effectiveness and efficiency of our framework with an MINKIN,M.,MOGHIMI,D.,PIESSENS,F.,SCHWARZ,M.,SUNAR, extensiveevaluationofseveralleakagetypes,suchassecret- B., VAN BULCK, J., AND YAROM, Y. Fallout: Leaking data on dependent memory access patterns, conditional execution, meltdown-resistant cpus. In Proceedings of the ACM SIGSAC Con- varying loop sizes as well as Spectre-v1 gadgets. We show ference on Computer and Communications Security (CCS) (2019), ACM. thatourtoolcanautomaticallypatchleakagepointsinCand Javascript. Our tool was able to patch side-channel leakage [8] CANELLA, C., VAN BULCK, J., SCHWARZ, M., LIPP, M., VONBERG,B.,ORTNER,P.,PIESSENS,F.,EVTYUSHKIN,D.,AND in security-critical libraries that are not maintained but used GRUSS,D.Asystematicevaluationoftransientexecutionattacksand by millions of people, such as aes-js, base64-js and node- defenses.In28thUSENIXSecuritySymposium(USENIXSecurity19) forgeinlessthan1.5hoursforonlycentsperpatch.Finally, (2019),pp.249–266. we showed our tool can automatically patch a real-world [9] CAULIGI,S.,DISSELKOEN,C.,GLEISSENTHALL,K.V.,TULLSEN, Spectre-v1 instance in OpenSSL. D.,STEFAN,D.,REZK,T.,ANDBARTHE,G. Constant-time foun- dations for the new spectre era. In Proceedings of the 41st ACM SIGPLANConferenceonProgrammingLanguageDesignandImple- Acknowledgements mentation(2020),pp.913–926. [10] CAULIGI, S., DISSELKOEN, C., MOGHIMI, D., BARTHE, G., AND WethankJanWichelmannforhishelpwithrunningMi- STEFAN,D.Sok:Practicalfoundationsforsoftwarespectredefenses. crowalk. This work was supported by the National Science In2022IEEESymposiumonSecurityandPrivacy(SP)(2022),IEEE, Foundation grantCNS-2026913 and inpart by agrant from pp.666–680. the Qatar National Research Fund. [11] CAULIGI, S., DISSELKOEN, C., MOGHIMI, D., BARTHE, G., AND STEFAN,D. SoK:PracticalFoundationsforSpectreDefenses. References [12] CHARALAMBOUS, Y., TIHANYI, N., JAIN, R., SUN, Y., FERRAG, M. A., AND CORDEIRO, L. C. A new era in software security: Towardsself-healingsoftwarevialargelanguagemodelsandformal [1] npm-stat:downloadstatisticsfornpmpackages.https://npm-stat.com/ verification. arXivpreprintarXiv:2305.14752(2023). charts.html?package=aes-js&from=2013-08-03&to=2023-08-03. Accessed:2023-08-03. [13] COMMITTEE,O.T. Spectre and meltdown attacks against openssl. PublishedonOpenSSLBlog:05/13/2022. [2] AHMAD,B.,THAKUR,S.,TAN,B.,KARRI,R.,ANDPEARCE,H. Fixing hardware security bugs with large language models. arXiv [14] DEVLIN,J.,CHANG,M.-W.,LEE,K.,ANDTOUTANOVA,K. Bert: preprintarXiv:2302.01215(2023). Pre-training of deep bidirectional transformers for language under- standing,2019. [3] ANIL, R., DAI, A. M., FIRAT, O., JOHNSON, M., LEPIKHIN, D.,
PASSOS, A., SHAKERI, S., TAROPA, E., BAILEY, P., CHEN, Z., [15] DOYCHEV, G., KO¨PF, B., MAUBORGNE, L., AND REINEKE, J. CHU, E., CLARK, J. H., SHAFEY, L. E., HUANG, Y., MEIER- Cacheaudit: A tool for the static analysis of cache side channels. HELLSTERN, K., MISHRA, G., MOREIRA, E., OMERNICK, M., ACMTransactionsoninformationandsystemsecurity(TISSEC)18, ROBINSON, K., RUDER, S., TAY, Y., XIAO, K., XU, Y., ZHANG, 1(2015),1–32. Y.,ABREGO,G.H.,AHN,J.,AUSTIN,J.,BARHAM,P.,BOTHA,J., [16] GARG,S.,MOGHADDAM,R.Z.,ANDSUNDARESAN,N. Rapgen: BRADBURY,J.,BRAHMA,S.,BROOKS,K.,CATASTA,M.,CHENG, Anapproachforfixingcodeinefficienciesinzero-shot.arXivpreprint Y., CHERRY, C., CHOQUETTE-CHOO, C. A., CHOWDHERY, A., arXiv:2306.17077 (2023). CREPY,C.,DAVE,S.,DEHGHANI,M.,DEV,S.,DEVLIN,J.,D´IAZ, M., DU, N., DYER, E., FEINBERG, V., FENG, F., FIENBER, V., [17] GARTNER. Emergingtech:Generativeaicodeassistantsarebecom- FREITAG,M.,GARCIA,X.,GEHRMANN,S.,GONZALEZ,L.,GUR- ingessentialtodeveloperexperience,2023. ARI,G.,HAND,S.,HASHEMI,H.,HOU,L.,HOWLAND,J.,HU,A., [18] GHIDRA.Ghidrasoftwarereverseengineering(sre)framework,2023. HUI, J., HURWITZ, J., ISARD, M., ITTYCHERIAH, A., JAGIELSKI, M.,JIA,W.,KENEALY,K.,KRIKUN,M.,KUDUGUNTA,S.,LAN, [19] GRSECURITY. Teardown of a failed linux lts spectre fix, 2019. C., LEE, K., LEE, B., LI, E., LI, M., LI, W., LI, Y., LI, J., LIM, Available at: https://grsecurity.net/teardown of a failed linux lts H., LIN, H., LIU, Z., LIU, F., MAGGIONI, M., MAHENDRU, A., spectre fix(Accessed:2023-08-02). MAYNEZ, J., MISRA, V., MOUSSALEM, M., NADO, Z., NHAM, [20] GUARNIERI, M., KO¨PF, B., MORALES, J. F., REINEKE, J., AND J., NI, E., NYSTROM, A., PARRISH, A., PELLAT, M., POLACEK, SA´NCHEZ,A. Spectector: Principled detection of speculative infor- M., POLOZOV, A., POPE, R., QIAO, S., REIF, E., RICHTER, B., mationflows.In2020IEEESymposiumonSecurityandPrivacy(SP) RILEY,P.,ROS,A.C.,ROY,A.,SAETA,B.,SAMUEL,R.,SHELBY, (2020),IEEE,pp.1–19. R., SLONE, A., SMILKOV, D., SO, D. R., SOHN, D., TOKUMINE, S., VALTER, D., VASUDEVAN, V., VODRAHALLI, K., WANG, X., [21] GUPTA, R., PAL, S., KANADE, A., AND SHEVADE, S. Deepfix: Fixingcommonclanguageerrorsbydeeplearning. InProceedings WANG, P., WANG, Z., WANG, T., WIETING, J., WU, Y., XU, K., oftheaaaiconferenceonartificialintelligence(2017),vol.31. XU,Y.,XUE,L.,YIN,P.,YU,J.,ZHANG,Q.,ZHENG,S.,ZHENG, C.,ZHOU,W.,ZHOU,D.,PETROV,S.,ANDWU,Y.Palm2technical [22] HEX-RAYS. Idapro,2023. report,2023. [23] INTEL. Guidelinesformitigatingtimingsidechannelsagainstcryp- [4] ANTONOPOULOS, T., GAZZILLO, P., HICKS, M., KOSKINEN, E., tographicimplementations,v2.1,2022-06-29. TERAUCHI, T., AND WEI, S. Decomposition instead of self- [24] JANCAR,J.,FOURNE´,M.,BRAGA,D.D.A.,SABT,M.,SCHWABE, composition for proving the absence of timing channels. ACM P.,BARTHE,G.,FOUQUE,P.-A.,ANDACAR,Y. “they’re not that SIGPLANNotices52,6(2017),362–375. hardtomitigate”:Whatcryptographiclibrarydevelopersthinkabout [5] BAZAAR, D. Forge. https://github.com/digitalbazaar/forge, 2023. timing attacks. In 2022 IEEE Symposium on Security and Privacy Accessed:2023-07-19. (SP)(2022),IEEE,pp.632–649. 14[25] KANDE,R.,PEARCE,H.,TAN,B.,DOLAN-GAVITT,B.,THAKUR, [43] TOUVRON, H., LAVRIL, T., IZACARD, G., MARTINET, X., S., KARRI, R., AND RAJENDRAN, J. Llm-assisted generation of LACHAUX,M.-A.,LACROIX,T.,ROZIE`RE,B.,GOYAL,N.,HAM- hardwareassertions. arXivpreprintarXiv:2306.14027 (2023). BRO,E.,AZHAR,F.,RODRIGUEZ,A.,JOULIN,A.,GRAVE,E.,AND LAMPLE,G. Llama:Openandefficientfoundationlanguagemodels, [26] KOCETKOV, D., LI, R., BEN ALLAL, L., LI, J., MOU, C., 2023. MUN˜OZ FERRANDIS, C., JERNITE, Y., MITCHELL, M., HUGHES, S., WOLF, T., BAHDANAU, D., VON WERRA, L., AND DE VRIES, [44] TOUVRON,H.,MARTIN,L.,STONE,K.,ALBERT,P.,ALMAHAIRI, H. The stack: 3 tb of permissively licensed source code. Preprint A., BABAEI, Y., BASHLYKOV, N., BATRA, S., BHARGAVA, P.,
(2022). BHOSALE, S., BIKEL, D., BLECHER, L., FERRER, C. C., CHEN, M.,CUCURULL,G.,ESIOBU,D.,FERNANDES,J.,FU,J.,FU,W., [27] KOCHER, P. Spectre mitigations in microsoft’s c/c++ com- FULLER, B., GAO, C., GOSWAMI, V., GOYAL, N., HARTSHORN, piler. RetrievedJuly27,2023fromhttps://www.paulkocher.com/doc/ A., HOSSEINI, S., HOU, R., INAN, H., KARDAS, M., KERKEZ, MicrosoftCompilerSpectreMitigation.html,2018. V., KHABSA, M., KLOUMANN, I., KORENEV, A., KOURA, P. S., [28] KOCHER,P.,HORN,J.,FOGH,A.,GENKIN,D.,GRUSS,D.,HAAS, LACHAUX, M.-A., LAVRIL, T., LEE, J., LISKOVICH, D., LU, Y., W., HAMBURG, M., LIPP, M., MANGARD, S., PRESCHER, T., MAO,Y.,MARTINET,X.,MIHAYLOV,T.,MISHRA,P.,MOLYBOG, ET AL. Spectre attacks: Exploiting speculative execution. In 2019 I.,NIE,Y.,POULTON,A.,REIZENSTEIN,J.,RUNGTA,R.,SALADI, IEEESymposiumonSecurityandPrivacy(SP)(2019),IEEE,pp.1– K.,SCHELTEN,A.,SILVA,R.,SMITH,E.M.,SUBRAMANIAN,R., 19. TAN,X.E.,TANG,B.,TAYLOR,R.,WILLIAMS,A.,KUAN,J.X., XU, P., YAN, Z., ZAROV, I., ZHANG, Y., FAN, A., KAMBADUR, [29] KOCHER, P. C. Timing attacks on implementations of diffie- M.,NARANG,S.,RODRIGUEZ,A.,STOJNIC,R.,EDUNOV,S.,AND hellman, rsa, dss, and other systems. In Advances in Cryptol- SCIALOM,T. Llama2:Openfoundationandfine-tunedchatmodels, ogy—CRYPTO’96:16thAnnualInternationalCryptologyConference 2023. SantaBarbara,California,USAAugust18–22,1996Proceedings16 (1996),Springer,pp.104–113. [45] VAN SCHAIK, S., MILBURN, A., O¨ STERLUND, S., FRIGO, P., [30] LANGLEY, A. ctgrind: Checking that functions are constant time MAISURADZE, G., RAZAVI, K., BOS, H., AND GIUFFRIDA, C. RIDL:Roguein-flightdataload. InS&P(May2019). with valgrind. https://github.com/agl/ctgrind, 2013. Available: https://github.com/agl/ctgrind. [46] WANG,G.,CHATTOPADHYAY,S.,BISWAS,A.K.,MITRA,T.,AND [31] LIPP, M., SCHWARZ, M., GRUSS, D., PRESCHER, T., HAAS, W., ROYCHOUDHURY, A. Kleespectre: Detecting information leakage through speculative cache attacks via symbolic execution. ACM FOGH, A., HORN, J., MANGARD, S., KOCHER, P., GENKIN, D., Trans.Softw.Eng.Methodol.29,3(jun2020). YAROM,Y.,ANDHAMBURG,M.Meltdown:Readingkernelmemory from user space. In 27th USENIX Security Symposium (USENIX [47] WANG, G., CHATTOPADHYAY, S., GOTOVCHITS, I., MITRA, T., Security18)(2018). AND ROYCHOUDHURY, A. oo7: Low-overhead defense against spectreattacksviaprogramanalysis. IEEETransactionsonSoftware [32] LITTLE,J.base64-js.https://github.com/beatgammit/base64-js,2023. Engineering(2019). Accessed:2023-07-19. [33] LIU,Y.,OTT,M.,GOYAL,N.,DU,J.,JOSHI,M.,CHEN,D.,LEVY, [48] WANG, S., WANG, P., LIU, X., ZHANG, D., AND WU, D. O.,LEWIS,M.,ZETTLEMOYER,L.,ANDSTOYANOV,V. Roberta: {CacheD}:Identifying{Cache-Based}timingchannelsinproduction Arobustlyoptimizedbertpretrainingapproach,2019. software. In26thUSENIXsecuritysymposium(USENIXsecurity17) (2017),pp.235–252. [34] MOORE,R.aes-js.https://github.com/ricmoo/aes-js,2023.Accessed: 2023-07-19. [49] WEI,J.,WANG,X.,SCHUURMANS,D.,BOSMA,M.,XIA,F.,CHI, E.,LE,Q.V.,ZHOU,D.,ETAL. Chain-of-thoughtpromptingelicits [35] MOSIER, N., LACHNITT, H., NEMATI, H., AND TRIPPEL, C. Ax- reasoninginlargelanguagemodels. AdvancesinNeuralInformation iomatic hardware-software contracts for security. In Proceedings of ProcessingSystems35(2022),24824–24837. the49thAnnualInternationalSymposiumonComputerArchitecture (NewYork,NY,USA,2022),ISCA’22,AssociationforComputing [50] WEISER,S.,ZANKL,A.,SPREITZER,R.,MILLER,K.,MANGARD, Machinery,p.72–86. S., AND SIGL, G. {DATA}–differential address trace analysis: Findingaddress-based{Side-Channels}inbinaries. In27thUSENIX [36] OLEKSENKO,O.,TRACH,B.,SILBERSTEIN,M.,ANDFETZER,C. SecuritySymposium(USENIXSecurity18)(2018),pp.603–620. Specfuzz: Bringing spectre-type vulnerabilities to the surface. In Proceedingsofthe29thUSENIXConferenceonSecuritySymposium [51] WICHELMANN, J., MOGHIMI, A., EISENBARTH, T., AND SUNAR, (USA,2020),SEC’20,USENIXAssociation. B. Microwalk: A framework for finding side channels in binaries. In Proceedings of the 34th Annual Computer Security Applications [37] OPENAI. Gpt-4technicalreport,2023. Conference (New York, NY, USA, 2018), ACSAC ’18, Association [38] PARDOE,A. Spectremitigationsinmsvc,Jan.2018. forComputingMachinery,p.161–173.
[39] PEARCE, H., TAN, B., AHMAD, B., KARRI, R., AND DOLAN- [52] WICHELMANN, J., SIECK, F., PA¨TSCHKE, A., AND EISENBARTH, GAVITT,B. Examining Zero-Shot Vulnerability Repair with Large T. Microwalk-ci:practicalside-channelanalysisforjavascriptappli- LanguageModels.In2023IEEESymposiumonSecurityandPrivacy cations. In Proceedings of the 2022 ACM SIGSAC Conference on (SP)(2023),IEEE. ComputerandCommunicationsSecurity(2022),pp.2915–2929. [40] RODRIGUES,B.,QUINTA˜OPEREIRA,F.M.,ANDARANHA,D.F. [53] WU, M., GUO, S., SCHAUMONT, P., AND WANG, C. Eliminating Sparse representation of implicit flows with applications to side- timing side-channel leaks using program repair. In Proceedings of channel detection. In Proceedings of the 25th International Con- the27thACMSIGSOFTInternationalSymposiumonSoftwareTesting ferenceonCompilerConstruction(2016),pp.110–120. andAnalysis(2018),pp.15–26. [41] SCHWARZ,M.,LIPP,M.,MOGHIMI,D.,VANBULCK,J.,STECK- [54] WU,T.,JIANG,E.,DONSBACH,A.,GRAY,J.,MOLINA,A.,TERRY, LINA, J., PRESCHER, T., AND GRUSS, D. ZombieLoad: Cross- M.,ANDCAI,C.J. Promptchainer:Chaininglargelanguagemodel privilege-boundarydatasampling. InCCS(2019). promptsthroughvisualprogramming. InCHIConferenceonHuman FactorsinComputingSystemsExtendedAbstracts(2022),pp.1–10. [42] TARLOW, D., MOITRA, S., RICE, A., CHEN, Z., MANZAGOL, P.- A.,SUTTON,C.,ANDAFTANDILIAN,E. Learningtofixbuilderrors [55] WU, T., TERRY, M., AND CAI, C. J. Ai chains: Transparent and with graph2diff neural networks. In Proceedings of the IEEE/ACM controllable human-ai interaction by chaining large language model 42nd international conference on software engineering workshops prompts. In Proceedings of the 2022 CHI Conference on Human (2020),pp.19–20. FactorsinComputingSystems(2022),pp.1–22. 15[56] WU,Y.,JIANG,N.,PHAM,H.V.,LUTELLIER,T.,DAVIS,J.,TAN, 1 // getelement-taken from CacheAudit, Doychev et L.,BABKIN,P.,ANDSHAH,S. How effective are neural networks al for fixing security vulnerabilities. arXiv preprint arXiv:2305.18607 2 unsigned int A[16] = {0, 1, 2, 3, 4, 5, 6, 7, (2023). 3 8, 9, 10, 11, 12, 13, 14, [57] YASUNAGA,M.,ANDLIANG,P. Break-it-fix-it:Unsupervisedlearn- 15}; ing for program repair. In International Conference on Machine 4 int memory_leakage_case_5(int secret) { Learning(2021),PMLR,pp.11941–11952. 5 if (secret < 16) 6 return A[secret]; [58] ZHANG, Z., BARTHE, G., CHUENGSATIANSUP, C., SCHWABE, P., 7 } ANDYAROM,Y. Ultimateslh:Takingspeculativeloadhardeningto 8 // isDiffVul1 - taken from FlowTracker https:// thenextlevel. CryptologyePrintArchive(2022). dl.acm.org/doi/pdf/10.1145/2892208.2892230 9 int branch_leakage_case_1(char *pw, char *in) { Appendix A. 10 int i; 11 for (i=0; i<16; i++) { Microbenchmark of leaky functions compiled 12 if (pw[i]!=in[i]) { from literature 13 return 0; 14 } 15 } 16 return 1; 1 // taken from Pitchfork, Cauligi, et al. 17 } 2 int m oe pm to ir oy n_ )le {akage_case_1(int x, int y, int 1 18 9 // InsertionSort-taken from CacheAudit, Doychev , et al. 3 4 v zo [l 2a ]ti =le y;int z[3] = { 0, 2, 300 }; 20 uint8_ at rr* ayb _r sa in zc eh )_ {leakage_case_2(uint8_t *a, int 5 6 7 8 9 i } }f e( lo r s rp e e et t ti u { uo r rn n n > z z[ [3 1 x) ]; %{ 3]; 2 2 2 21 2 3 4 i f -n o -t r ) i ( i f, i n od rj = e, x (1 ji ; =n =d i ae [ ix < i ;; ]a ; jrr >ay 0_s &i &ze a; [j+ -+ 1i ]){ > index; j 1 1 1 1 1 10 1 2 3 4 5 } / u/ nst ia gb nl ee d l co ho ak rup LU- T[f 1r 6o ] 0 0 0m = x x x{ 0 3 6D 0 C F CA x , , ,T 5A 2 0 0 0, x x x- 5 1 50 A A BW x , , ,e 1 0 0 0i 9 x x xs , 6 7 0e D E Dr 0 , , ,xe 3 0 0 0t E x x x, 2 5 3a B 3 7l 0 , , }. x ;7F, 2 2 2 2 25 6 7 8 9 r }etu} rn a;a[j]a[ =j] in= dea x[ ;j-1]; 16 int me rm eo tr uy r_ nle La Uk Ta [g ke v_ ac las %e_ 12 6_ ]t ;ra }nsform(int kval) { 3 30 1 // eq - Time variant - taken from FlowTracker https://dl.acm.org/doi/pdf 17 int memory_leakage_case_2(int key){ /10.1145/2892208.2892230 18 i (n 0t );val = memory_leakage_case_2_transform 32 int branch_leakage_case_3(char *p, char *q) { 1 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 39 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 } / i } c/ n ot nf sv r r m i f } i i f } r t (a e o e n o n n o e 6l t t r t t r tm m u 4+ u uo i )= r C r t ( t i i ( i t t r n )m n a y a i a , n i n n t )e c _ b n b d = d = = 8h l _m v l t l t e 0 e t =o a e e e ; x ; ; te x t tD ar l [ i [ a a {y ; k 1 = = i bi = b b_ p a 2 0 ] < l l o 5l a g 8 ; 0 2 o( e e 2e p e ] = ; 0 i [ [ k
,a e _ i 0 [n i (k r c = < i ; d n i 1 4- a 0a 1 ; e d n 8g s { 2 i x e d ] ,e W e 0 8 + + x e_ a _ } ; + s ] x _ 5n 3 _c ; ) e ; ) 5a g ( i { ac ,s i + tr %e e n + e t 5_ t t ) t 7 r 12 { ) 9 i ,_ ]a s bt % ;l e u 5r c t 6a 1r e ,2n e _8s t _ 5;f ) ( 4o { ( ,r am l 5( i 0k g ,e ny e 4) d 9; , 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 5 5 53 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 } / i }i e e / nf l l tes s( r e r e r x b i i } e } rp e e e a r n f l e[ t i t t m a t s tu u u ( e u0 f p nr r r l c i h r] i w i wn ( n n e h ; i { nh h! p _ g = i = i= f [ f p 1 l h l l ia a [ - e ;1 0 e l eq l ] l 2 f a = ; ( o ([ s s ] r k = i w i0 e ! e o a ;; ; = 0] = m g < >) = e )q B _ l 0[ q l c { o )[ a a1 w2 z s] ) i) ] e e -; r _ i -, 4 + ;( +A i ;n nt ton ho ip go hu ,lo us i, ntet loa wl ). { 57, 53 }; 53 // example 2-from Blazer, Antonopoulos, et al. 38 uint8 u_ nt s* igm ne em dor ly e_ nl )ea {kage_case_4(uint8_t* msg, 5 54 5 int b ir na tnc ih ;_leakage_case_5(int high, int low) { 3 49 0 for ( mu sgn [si ig ]ne =d bi oo= k[0 m; sgi [i< ]-l 4e 8n ]; ; ++i) 5 5 56 7 8 if (l i wo hw = il> 0 e; (0 i) <l{ ow/ )/ iO +( +2 ;*low) 4 4 41 2 3 r }eturn msg; 5 6 69 0 1 } elsw ieh fil { (e h/( i/i g> hO0 () =1 =)i- 0- ); { i = 5; } 62 else { i = 0; i++; } 63 } 64 return i; 65 } 161 // taken from https://github.com/PLSysSec/ haybale-pitchfork 2 int branch_leakage_case_6(int x) { 3 if (x > 10) { 4 return x % 200 * 3; 5 } else { 1 // taken from https://github.com/PLSysSec/ 6 return x + 10; haybale-pitchfork 7 } 2 uint8_t branch_leakage_case_10(uint8_t* 8 } public_arr, uint8_t public_arr_len, uint8_t 9 // taken from https://github.com/PLSysSec/ * secret_arr, uint8_t i) { haybale-pitchfork 3 uint8_t x = public_arr[i]; 10 int branch_leakage_case_7(int x, int y, int 4 for (int j = 0; j < public_arr_len; j++) { option) { 5 secret_arr[j] += x; 11 volatile int z[3] = { 0, 2, 300 }; 6 } 12 z[2] = y; 7 if (x > 10) { 13 if (option > 3) { 8 return public_arr[0] + secret_arr[0]; 14 return z[1]; 9 } else { 15 } else { 10 return public_arr[1] + secret_arr[1]; 16 return z[2]; 11 } 17 } 12 } 18 } 13 // bubblesort- taken from CacheAudit https:// 19 // from ctgrind tool github repo www.usenix.org/system/files/conference/ 20 char branch_leakage_case_8(unsigned char *a, usenixsecurity13/sec13-paper_doychev.pdf unsigned char *b) { 14 uint8_t * branch_leakage_case_11(uint8_t *a, 21 unsigned i; int n){ 22 for (i = 0; i < 16; i++) { 15 int i, j, temp; 23 if (a[i] != b[i]) 16 for (i = 0; i < n - 1; ++i) 24 return 0; 17 for (j = 0; j < n - 1 - i; ++j) 25 } 18 if (a[j] > a[j+1]){ 26 return 1; 19 temp = a[j+1]; 27 } 20 a[j+1] = a[j]; 28 // mu - taken from SC-Eliminator https://dl.acm 21 a[j] = temp; .org/doi/pdf/10.1145/3213846.3213851 22 } 29 // the C code of a textbook implementation of a 23 return a; 3-way cipher. 24 } 30 int32_t * branch_leakage_case_9(int32_t *a) { 25 // SelectionSort - taken from CacheAudit https 31 int i; ://www.usenix.org/system/files/conference/ 32 int32_t b[3]; usenixsecurity13/sec13-paper_doychev.pdf 33 b[0] = b[1] = b[2] = 0; 26 uint8_t * branch_leakage_case_12(uint8_t *a, 34 for (i=0; i<32; i++) { int array_size){ 35 b[0] <<= 1; 27 int i; 36 b[1] <<= 1; 28 for (i = 0; i < array_size - 1; ++i){ 37 b[2] <<= 1; 29 int j, min, temp; 38 if(a[0]&1) 30 min = i; 39 b[2] |= 1; 31 for (j = i+1; j < array_size; ++j){ 40 if(a[1]&1) 32 if (a[j] < a[min]) 41 b[1] |= 1; 33 min = j; 42 if(a[2]&1) 34 } 43 b[0] |= 1; 35 temp = a[i]; 44 a[0] >>= 1; 36 a[i] = a[min]; 45 a[1] >>= 1; 37 a[min] = temp; 46 a[2] >>= 1; 38 } 47 } 39 return a; 48 a[0] = b[0]; 40 } 49 a[1] = b[1]; 50 a[2] = b[2]; 51 52 return a; 53 } 17
2308.14434 The ISC Int'l Journal of Information Security ManuscripttemplateofISeCureJournal(pp.1–8) IS C e ure http://www.isecure-journal.org UsingChatGPTasaStaticApplicationSecurityTestingTool AtiehBakhshandeh1,∗ , AbdalsamadKeramatfar1, AmirNorouzi1,and MohammadMahdiChekidehkhoun1 1ResearchCenterforDevelopmentofAdvancedTechnologies,Tehran,Iran ARTICLE INFO. Abstract Keywords: In recent years, artificial intelligence has had a conspicuous growth in almost ArtificialIntelligence-basedCode review,ChatGPTModel, everyaspectoflife.Oneofthemostapplicableareasissecuritycodereview,in CommonWeaknessEnumeration, which a lot of AI-based tools and approaches have been proposed. Recently, StaticApplicationSecurity Testing,VulnerabilityDetection ChatGPT has caught a huge amount of attention with its remarkable performance in following instructions and providing a detailed response. Regardingthesimilaritiesbetweennaturallanguageandcode,inthispaper,we study the feasibility of using ChatGPT for vulnerability detection in Python source code. Toward this goal, we feed an appropriate prompt along with vulnerabledatatoChatGPTandcompareitsresultsontwodatasetswiththe resultsofthreewidelyusedStaticApplicationSecurityTestingtools(Bandit, Semgrep and SonarQube). We implement different kinds of experiments with ChatGPTandtheresultsindicatethatChatGPTreducesthefalsepositiveand false negative rates and has the potential to be used for Python source code vulnerabilitydetection. ©2023ISC.Allrightsreserved. 1 Introduction Softwarevulnerabilityisatechnicalvulnerabilitythat can be used for violating its security policies. Such Today,almostalltechnologiesarestronglydependent vulnerabilities can be exploited which in turn leads onsourcecode.Therefore,codeisofincreasingimpor- to data leakage and tampering and even denial of tance.Aglanceatthenumberoflinesofusedcodesin services. somewell-knowntoolsisevidenceforthisclaim.For instance,thenumberofGitHubrepositoriesincreased Staticsourcecodeanalysisisamethodforfinding from100millionin2018to200millionin2022[1].It code vulnerabilities that isdone by automaticallyex- is clear that the increase in the amount of code will aminingthesourcecodewithouthavingtoexecutethe leadtomoresecurityrequirementsinprogramming. program.StaticApplicationSecurityTesting(SAST) MITRE1 andotherstudiesindicatethegrowthinthe tools analyze a piece of code or a compiled version numberofvulnerabilitiesinrecentyears[2–8].Specif- of it in order to identify its security problems. Cov- ically, software vulnerability is of great importance. ering a wide range of errors and high accuracy are twoimportantfeaturesofSASTtools[9].Mostofthe well-knownSASTtoolssuchasSemgrep,Bandit,and ∗ Correspondingauthor. SonarQube often use rule-based techniques to find Emailaddresses: bakhshandeh@rcdat.com, the vulnerable patternsof code.However, these tools keramatfar@rcdat.ir,norouzi@rcdat.ac.ir, have shownto havetheir ownflaws, including a high chekidekhoon@rcdat.ir rateoffalsepositivesandfalsenegatives[4].Themore ISSN:2008-2045©2023ISC.Allrightsreserved. 1 MassachusettsInstituteofTechnologyResearchandEngi- falsepositivesaSASTtoolreturns,themoretimeand neering (cid:73)(cid:83)(cid:101)(cid:67)(cid:117)(cid:114)(cid:101) 3202 guA 82 ]RC.sc[ 1v43441.8032:viXra2 effortarerequiredbyasecurityexperttovalidatethe analysisoftheobtainedresults2.InSection6wedis- findingsoftheSASTtool.Moreover,thiswillincrease cuss some factors that may threaten the validity of theerrorratebyhumans,whichmaythenleadtoig- theresults.Finally,Section7concludesthepaper. noringsomevulnerabilities.Ontheotherhand,ahigh 2 RelatedWork rateoffalsenegativeleadstocatastrophicevents. Inrecentyears,MachineLearning(ML)anddeep In this section, we review some of the works that learninghave had remarkable advancesin various ar- useddifferentkindsofAImodelsforvulnerabilityde- eassuchasnaturallanguageprocessing[10,11].There- tection. Note that we did not focus on works which fore,consideringthehighsimilaritybetweencodeand proposedmodels for repairing theidentified vulnera- natural languages, the deep learning-based models bilities. When it comes to artificial intelligence, the areexpectedtobesuccessfulincodeprocessingtasks. mainideaistheuseofsupervisedlearning.Therefore, Likewise,studiesinthisareahaveshowntheinterest variousmachinelearningmodelsusedmethodsoffea- ofresearchersinusingdeeplearningtechniquesinvul- ture engineering such as the number of lines of the nerabilitydetection[12,13].Machinelearningmodels code,codecomplexityandthenumberofoperations can automaticallylearn the patternsof software vul- andalsoutilizedtextualfeatures[15,17].Ingeneral, nerabilitiesbasedondatasets.Furthermore,research research shows that text-based models have better indicates that ML models have fewer false positives performanceoverfeature engineering andthe studies comparedtoSASTtools[6,14].Resultsofanewre- alsoadmitthatmachinelearningmodelsoutperform searchhaveshownthesuperiorperformanceofdeep theexistingSASTtools. learning-basedmodelsoverthreeopen-sourcetoolsin Recently,moreresearchhasbeendevotedtodeep C/C++, reducing false positives and negatives rate learning.Inthisscope,researchersoftenuseddifferent atthesametime[15]. deep learning models such as Convolutional Neural
Recently, ChatGPT, an AI-powered chatbot tool Network(CNN),LongShort-TermMemory(LSTM), that uses Natural Language Processing (NLP) and andMultilayerPerceptron(MLP)[13,18–20].Someof machine learning algorithms to understand and re- themodelswerebasedondifferentkindsofcodeprop- spondtocustomerinquiries,hasdrawnalotofatten- ertygraphsandusedGraphNeuralNetwork[13,14], tion.ChatGPTisvitalfor businessprofessionalsfor while some others only relied on tokens [20]. A new severalreasons.Itcanhelpsavetimeandresourcesby studyhasinvestigatedthewaydeeplearningmodels automatingtasksrequiringhumanintervention.An function invulnerability detectiontasks. The results importantpointtonoteisthat,ChatGPThasbeen of this study reveal some points: first, the results of trainedwithahugeamountofdatatill2021sothatit differentmodelsarenotcompatiblewitheachother. canbeagreathelpinfindingknownpatternsinthou- Second,fine-tunedmodelshaveshownbetterperfor- sands of packages in automated way. The model is mance in this field. Third, usually 1000 samples of alsotrainedonalargeamountofcodeandisthusable eachclassareenoughforthetrainingofaneuralnet- recognizecommonpatterns.Inthispaper,weevaluate workandfinally,modelsusuallyusethesamefeatures theperformanceofChatGPTinidentifyingsecurity for prediction [21]. Although studies approved the vulnerabilities of Python codes and compare the re- superiorityofgraph-basedmodels,anewstudyindi- sults with three well-known SAST tools for Python catesthesuperiorperformanceoftransformer-based vulnerabilitydetection(Bandit,SemgrepandSonar- modelsovergraph-basedones[22].In2022,Hanifand Qube).ThereasonforchoosingthePythonlanguage MaffeisproposedamodelnamedVulBERTa[23].This isthatin2022,Pythonwasknowntobethemostpop- modelisbasedonRoBERTaandisusedforvulnerabil- ularprogramminglanguagesalongwithJava,based itydetectioninC/C++codes.Anotherrecentstudy on the Popularity of Programming Language Index alsohasusedBERTarchitectureandCodeBERTvec- (PYPL) and IEEE reports. Also, Stackscale ranked tors for predicting code vulnerabilities. The results Python at the third place [16]. Although Python is ofthisstudyapprovethesuperiorityoftransformer- mainlyusedinthescopeofmachinelearninganddata based models over traditional deep learning models science,itsapplicationsarenotonlylimitedtothese and also graph-based models [24]. Overall, it seems fieldsandwithitsfamousframeworkssuchasDjango that transformer-based models are effective in this and Flask, it is prone to vulnerabilities. The rest of area.AnotherrecentworkhasevaluatedChatGPTas thepaperisorganizedasfollows:InSection2,wepro- a large language model for detecting vulnerabilities videabrief literature review ofthisarea.Section3 is inJavasourcecodesandcomparedtheresultswitha dedicatedtodatasetsweused.Section4providesthe dummyclassifierandachievednobetterresultsthan details of the experiments we performed with Chat- it[25].However,thereisstillnoacademicstudyabout GPT. In Section 5, we present the evaluation and 2 https://github.com/abakhshandeh/ChatGPTasSAST.git (cid:73)(cid:83)(cid:101)(cid:67)(cid:117)(cid:114)(cid:101)3 comparing the results of the ChatGPT model with no."}]sowecancompareourresultswiththose traditional SAST tools for Python, and this paper ofSASTtools. aimstoanswerthequestionofwhethertheChatGPT (3) Inthethirdexperiment,foreachofvulnerable modelisoutperformingSASTtoolsornot? files, we give the model all the labels returned fromBandit, Semgrep andSonarQubetoolsfor 3 DatasetsDescription thePythoncode,astheclassesthatChatGPT shoulduse.Wethenaskthemodelwhethereach Inthissection,weprovidethedetailsaboutourdataset vulnerablefilecontainsanyofthosevulnerabili- and the labels we used. Our dataset consists of 156 tiesornot?Here,themaindifferencewithour Pythoncodefiles.Thesefilescontain130filesofthe secondexperimentisthatwespecifytheclasses securityEvaldatasetwhichisproposedin[26].Asthe pervulnerablefileseparately.Inotherwords,we authors mentioned, these 130 files cover 75 vulnera- usethemodelasanassistantfortheSASTtools bilitytypesthataremappedtoCommonWeakness to verify the detected vulnerabilities by them. Enumeration(CWE).Theremaining26filesbelong Inthisexperiment,weusethesameJSONfor- toaprojectcalledPyTinwhichtheauthordeveloped matas the secondexperiment fortheresponses. a tool for Python code vulnerability detection and Notethatinthisexperiment,althoughwepro- usedthese 26vulnerable code files forevaluatinghis videthelabels’listbeforehandforeachvulnera- tool[27,28].Sincetheuseddatasetsdonotprovide blefile,insomecasesthemodelhasreturneda thespecificlineofvulnerability,asecurityexpertof newCWEwhichisnotamongitsinputlabels. ourteamrecheckedthedataandspecifiedthevulner- Thisisanaturalbehaviorseenfromalanguage ableline.Weidentifiedthecorrespondinglineofcode modelandinordertoaddressthisissueinour ofCWEsthatwereassignedinthelabelsofthesefiles evaluation, we consider two cases: In one case, with the help of a security expert. The datasets’ in- weignorethenewlabelsandcalculatethemet- formationandthedistributionoftheircorresponding ricswithoutconsideringthem.Thispolicycan labelsarepresentedinTableA.1inappendixA. reduce the number of false positives of SAST 4 WorkingwithChatGPTAPI tools.Inanothercase,weconsiderthemaswell andthistimethenumberoffalsenegativesmay
Inthissection,weprovidethedetailsoftheprocess decrease. of utilizing the ChatGPT model API for identifying (4) In our fourth experiment, we do not provide vulnerabilities. In this study, we used the GPT-3.5- anylabellistforthemodelandaskittodetect turbomodel.TheGPT-3.5-Turbomodelcanaccepta the vulnerabilities in the files and determine seriesofmessagesasinput,unlikethepreviousversion theircorrespondingCWEsfromitsowntrained thatonlyallowedasingletextprompt.Thiscapability knowledge.Here,theformatoftheresponsesis providessomeinterestingfeatures,suchastheability thesameJSONstructureinthepreviousexper- tostorepriorresponsesorquerywithapredefinedset iments. of instructions with context. This is likely toimprove thegeneratedresponse.TheGPT-3.5-Turbomodelis To use the model for our experiments, we put all asuperioroptioncomparedtotheGPT-3model,as the vulnerable python codes of our dataset in a di- it offers better performance across all aspects while rectory and called GPT-3.5 API with an optimized being10timesmorecost-effectivepertoken.Wedid prompt for each of the vulnerable python files. The fourkindsofexperimentsusingtheGPT-3.5-Turbo choiceofpromptisthemostchallengingtaskinthis model. process,asithasdirecteffectontheresultsthemodel provides.Weoptimizeourpromptsaccordingto[29]. (1) Inourfirstexperiment,wegivethemodelthe Table 2providesthe listof prompts weused foreach vulnerable files and ask it whether they con- experiment. tainany securityvulnerabilitiesor not,without specifyingthecorrespondingCWEs.Weaskthe 4.1 Parameters modeltojustreturnthelinenumberofthevul- nerabilityifitcontainsany.Then,wecompare The parameters of the experiment are the prompt these lines with ground truth labels. In effect, whichcontainstheinstructionsthemodelwillexecute thisexperimentisabinaryclassification. andaparametercalledtemperaturethatdetermines (2) Inoursecondexperiment,weprovidethelistof therandomnesslevelofthemodelresponse.Thetem- thecorrespondingCWEsandaskthemodelto perature can take the values between 0 to 6 with 6 find the vulnerabilities from the labels’ list in givingthemostrandomoutput.Becausewewantto thePythonvulnerablefile.Inthisexperiment, specifylabelsforapieceofcode,thenatureofourjob we ask the model to respond in JSON format isdeterministic,sowesetthetemperaturetozeroto like [{"label": "CWE-X", "line of Code": "line getthemoststablebehavior.Anotherimportantpa- (cid:73)(cid:83)(cid:101)(cid:67)(cid:117)(cid:114)(cid:101)4 Table1.ComparisonoftheresponsesoftwoPromptswith Table 2. GPT-3.5 prompts used. Vul_code refers to the minorchange vulnerablecodeandlabels1isthelistoflabelsofallvulnerable files and labels2 is the labels of each vulnerable file that is Prompt Response iteratedthroughaloop. findallthevulnerabilitieswith[{”label”:”CWE-78:Improper ExperimentNo. Prompt the CWE standard in theNeutralization of Special Ele- python code which is delim-mentsusedinanOSCommand Experiment1 You will be provided with a python itedwithtriplebackticks.also(′OS Command Injection′)”, codedelimitedbytriplebackticks.If give the line of the vulner-”line of Code”: ”command itcontainsanysecurityvulnerability, ability in the code. python= ′echo′ + param + ′ » ′ + identify the lines of vulnerable code code:′′′{Vul_code}′′′ Format′menu.txt′”},{”label”:”CWE- andonlywritethelineinquotationIf yourresponseasalistofJSON78: Improper Neutralization of thecodedoesnotcontainavulnera- objectswith ”label”and”lineSpecial Elements used in an bility,thensimplywriteNone.python ofCode”asthekeysforeachel-OSCommand(′OSCommand code:′′′{Vul_code}′′′ ement.onlyanswerwithJSON.Injection′)”, ”line of Code”: Experiment2 Whichofthefollowingvulnerabilities ”subprocess.call(command, fromlistofvulnerabilitiesexistinthe shell=True)” }, { ”label”: pythoncode which isdelimitedwith ”CWE-78: Improper Neu- triplebackticks.alsogivethelineof tralization of Special El- thevulnerabilityinthecode.python ements used in an OS code:′′′{Vul_code}′′′ list of vulnera- Command (′OS Command bilities: {”, ”.join(labels1)} Format Injection′)”, ”line of Code”: your response as a list of JSON ob- ”subprocess.call(′echoMenu:> jectswith ”label”and”lineofCode” menu.txt′,shell=True)”}] asthekeysforeachelement.onlyan- findallthevulnerabilitieswith[ { ”label”: ”Command swerwithJSON. the CWE standard in theInjection”, ”line of Code”: Experiment3 Whichofthefollowingvulnerabilities pythoncode.alsogivetheline”subprocess.call(command, fromlistofvulnerabilitiesexistinthe ofthevulnerabilityinthecode.shell=True)” }, { ”label”: pythoncode which isdelimitedwith python code: ′′′{Vul_code}′′′”CommandInjection”,”lineof triplebackticks.alsogivethelineof FormatyourresponseasalistCode”: ”subprocess.call(′echo thevulnerabilityinthecode.python of JSON objects with ”label”Menu: > menu.txt′, code:′′′{Vul_code}′′′ listofvulnera- and”lineofCode”asthekeysshell=True)”}] bilities: {”, ”.join((labels2)} Format for each element. only answer your response as a list of JSON ob- withJSON. jectswith ”label”and”lineofCode” asthekeysforeachelement.onlyan- swerwithJSON.
rameteristhepromptwhichisveryinfluentialinthe resultsandadjustingittogetthebestresultsisachal- Experiment4 Yourtaskistodeterminewhetherthe lengingtask.Weusedthepromptsgivenin Table 2. followingpythoncodewhichisdelim- itedwithtriplebackticks,isvulnerable Wechoseourpromptsbasedon[29].Accordingto[29], or not? identify the following items: someofthekeypointstocreateanoptimizedprompt - CWE of its vulnerabilities. - lines are: using delimiters such as triple quotes or triple ofvulnerablecode. Formatyourre- backtickstospecifythepieceofcode,askingforstruc- sponseasalistofJSONobjectswith turedoutputsuchasJSON,HTML,etc.,specifying ”label”and”lineofCode”asthekeys for each vulnerability. If the infor- thestepstocompleteataskinaclearway,instructing mationisn’tpresent,use”unknown” themodeltoworkoutitsownsolutionsbeforerush- asthevalue.Makeyourresponseas ingtoaconclusion.Inordertoshowthesensitivityof shortaspossibleandonlyanswerwith ChatGPTtoitsprompts,anexampleisprovidedin JSON.pythoncode:′′′{Vul_code}′′′ Table 1 where a prompt with minor modification is giventothemodelandthemodelresponseswithdif- SonarQubeSASTtoolsandwealsoquerytheChat- ferentanswersinwhichthesecondresponsecontains GPT model with our dataset using the appropriate onelessvulnerabilitycomparedtothefirstone. prompts.Wethencalculatethefollowingmetricsfor 5 Results eachofthetools’resultsandthemodelresultbased onourgroundtruthlabels.Finally,wecomparethe In this section, we provide the results of our experi- resultsofthetoolswithGPT-3.5model. ments.Firstweexplainthemetricsweuseforevalu- atingourworkandthenwepresentGPT-3.5results 5.1 EvaluationMetrics andcomparethemwiththreepopularSASTtoolsfor Python vulnerability detection. To be more precise, In classification, we have condition positive which weperformthefollowingactions:Wegiveadatasetof indicates the number of real positive cases in the 156vulnerablepythoncodestoBandit,Semgrepand data.Similarly,thereisaconditionnegativewhichis (cid:73)(cid:83)(cid:101)(cid:67)(cid:117)(cid:114)(cid:101)5 thenumberofrealnegativecasesinthedata.Based on these conditions, there will be four parameters: true positive (TP) which is the number of positive exampleslabeledassuch,truenegative(TN)thatis thenumberofnegativeexampleslabeledassuch,false positive(FP)thatisthenumberofnegativeexamples labeledaspositiveandfalsenegative(FN)thatisthe numberofpositiveexampleslabeledasnegative.We define precision, recall and F-measure according to thefollowingformulas[30]. • Precision:Itanswersthequestionthatoutofall theexamplestheclassifierlabeledpositive,what proportionwerecorrect?Itisdefinedaccording tothefollowingequation: TP precision= (1) TP +FP • Recall:Itanswersthequestionthatoutofreal positiveexamples,whatproportiondidtheclas- sifier labeled as positive? It is defined as the Figure 1. F1-score of top 6 CWE classes in experiment 3 followingformula: (case2) TP recall= (2) TP +FN Precision Recall F1 Semgrep 0.6694 0.15040.2457 • F-measure:Itisameasurewhichcombinespre- Bandit 0.7450 0.1447 0.2424 cisionandrecallandisdefinedaccordingtothe SonarQube 0.9104 0.1161 0.2060 followingformula: GPT-3.5 0.7413 0.0819 0.1475 precision×recall Table3.ResultsofExperiment1(Binaryclassification) F =2× (3) precision+recall Precision Recall F1 5.2 AnalyzingResults Semgrep 0.4682 0.1123 0.1812 In this section, we present the results based on the Bandit 0.3168 0.0609 0.1022 mentionedmetricsintheprevioussection.Theresults SonarQube 0.3283 0.0419 0.0743 GPT-3.5 0.1659 0.0761 0.1044 forexperiment1inwhichwedidnotaskthemodelto return the CWEs, are provided in Table 3. The pre- Table4.ResultsofExperiment2(Selectingfromthelist) cisionforthemodelinthisexperimentisnotbetter than other three tools. Furthermore, the low recall suggeststhatusingthismodelforonlydetectingvul- Theresultsofexperiment3inwhichweprovided nerablelinesofacodedoesnotgiveanybetterresults the classes per vulnerable file, are given in Table 5. than SAST tools since low recall leads to high false Herethefiguresindicatethatcase1,inwhichwedo negative rate. Likewise, the results of experiment 2, not accept the new labels returned from the model, which are presented in Table 4, indicate that using hasproducedbetterresultsthancase2.Theseresults GPT-3.5 model with all the classes given as labels, areevensignificantlybetterthanthoseofSASTtools doesnotprovidesuperiorresultsincomparisonwith inthisexperiment.TheF1-scoreforthetop6CWEs the SAST tools. Note that in this experiment, the intermsoffrequencyareillustratedinFigure1forthis orderof thegiven labels toGPT-3.5 modelhas high experiment.ThisbehaviorshowsthatusingChatGPT impactinthegeneratedresultsfromthemodel.This asanassistantalongwithSASTtoolscanbeagood isbecausewhentheorderofthelabelsischanged,in idea. Moreover, if we do not provide any labels for factthepromptismodifiedandaswementionedbe- the model and ask it to return the CWEs of the fore,theprompthasgreateffectonthemodel’sresults. vulnerablecodesfromitsownknowledge,aswedidin Therefore,wegavethelabelsinarandomorder.Here, experiment4,weobtaintheresultsinTable6which
wereachthesameconclusionas[25]inwhichtheau- arecomparabletotheSASTtools.Byandlarge,our thorsconcludedthatthecapabilitiesoftheChatGPT experimentsshowthatusingChatGPTmodelasan modelfordetectingvulnerabilitiesincodearelimited. assistantforSASTtoolscanprovidehopefulresults. (cid:73)(cid:83)(cid:101)(cid:67)(cid:117)(cid:114)(cid:101)6 Precision Recall F1 andprovidesprimarystepstowardthispath.Infuture Semgrep 0.4682 0.1123 0.1812 studies,thebehaviorofthelatestmodelofChatGPT Bandit 0.3168 0.0609 0.1022 (GPT-4)whichismorepowerfulthanGPT-3.5model, SonarQube 0.3283 0.0419 0.0743 can be examined in vulnerability detection of codes Experiment3,GPT-3.5-Case1 0.7807 0.2781 0.4101 withthehopeofobtainingbetterresults.Moreover, Experiment3,GPT-3.5-Case2 0.333 0.1542 0.2109 theTemperatureparameterofthemodelcanbeset Table5.ResultsofExperiment3(SASTassistant) to values otherthanzero andinnovativerules canbe passedtodecideforthemostefficientobtainedresults. Anothersuggestioncanbeusingone-shotlearningin Precision Recall F1 Semgrep 0.4682 0.1123 0.1812 futureworks.Moreover,itshouldbeconsideredthat, Bandit 0.3168 0.0609 0.1022 there isa securitycaution about using ChatGPTas SonarQube 0.3283 0.0419 0.0743 as a SAST tool because it is required to upload the GPT-3.5 0.3350 0.1238 0.1808 sourcecodeontheOpenAIservers. Table6.ResultsofExperiment4(FreeClassification) A Appendix 6 ThreatstoValidity Thedistributionoflabelsofourdatasetisprovided inTableA.1 InthisSection,wediscusssomefactorsinourexperi- mentsthatcouldaffectthecorrectnessoftheresults. References Ourbiggestchallengewasthechoiceofthepromptsof [1] Wikipedia. https://en.wikipedia.org/wiki/ ChatGPT.Therearesomemetricsformeasuringthe GitHub,2023. Accessed:2023-03-27. effectivenessofapromptforLLMs.In[31]naturalness [2] cvedetails. https://www.cvedetails.com/ and expressiveness are mentioned as two important browse-by-date.php,2023. Accessed:2015-08- factors for a prompt. Here, we tried to choose the 23. mostefficientpromptsintermsof these metrics and [3] Kumar V, Anjum M, Agarwal V, and Kapur basedonwhatwasexplainedin4.1[29].However,it PK. A hybrid approach for evaluation and pri- ispossiblethatamorecarefulselectionoftheprompt oritizationofsoftwarevulnerabilities. Predictive canaffecttheresults.Anotherfactorwhichmayalso Analytics in System Reliability. Cham: Springer affecttheresultsisthesizeofthedatasetanditsacces- InternationalPublishing,--:39–51,2023. sibilityontheInternet.Furthermore,thedistribution [4] SharmaA.ZhouY. Automatedidentificationof oftheCWEsofthedatasetisofgreatimportance.To security issues from commit messages and bug overcomethisthreat,wechosethreedifferentdatasets reports. In Proceedings of the 2017 11th Joint for better generalization of the vulnerabilities they MeetingonFoundationsofSoftwareEngineering, cover,buttheremaybestillfewcoveragesofthevul- 2017. nerabilities. Moreover, we only compare this model [5] ZhouY.,LiuS.,SiowJ,DuX,andLiuY.Devign. withthreeSASTtoolsforPythonlanguage.Perhaps, Effective vulnerability identification by learning furtherSASTtoolsaffecttheresults.Andfinally,we comprehensiveprogramsemanticsviagraphneu- onlytestGPT-3.5modelofChatGPTanditispossi- ral networks. Advances in neural information ble that the new billable version (GPT-4) performs processingsystems,32,2019. betterthanthisversion. [6] PerlH,DechandS,SmithM,ArpD,Yamaguchi, 7 Conclusion RieckK,and etal. Vccfinder:Findingpotential vulnerabilities in open-source projects to assist Inthispaper,wedidfourtypesofexperimentswith code audits. In Proceedings of the 22nd ACM ChatGPTmodeltodetectthesecurityvulnerabilities SIGSACConferenceonComputerandCommu- ofPythoncodes.WecomparedthismodelwithBandit, nicationsSecurity,2015. SemgrepandSonarQubethatarepopularSASTtools [7] JabeenG,RahimS,AfzalW,KhanD,KhanA, forPythoncodes.WeconcludedthatusingGPT-3.5 HussainZ,andetal.Machinelearningtechniques model for vulnerability detection of codes in some for software vulnerability prediction: a compara- especialmannersgivespromisingresults.Specifically, tivestudy. AppliedIntelligence,52,2022. if we use it as SAST tool assistant, it will produce [8] MaffeisS.HanifH. Vulberta:Simplifiedsource resultsthatcanhelptoimprovethereturnedresults codepre-trainingforvulnerabilitydetection. In ofSASTtools.Overall,webelievethismodelhasthe 2022 International Joint Conference on Neural potentialtobeusedinvulnerabilitydetectiontasks Networks(IJCNN),pages1–8,2022. regarding thefactors that may effect the correctness [9] BerabiB,HeJ,RaychevV,andVechevM. Tfix: of the results which we described in 6. However, we Learningtofixcodingerrorswitha text-to-text admitthatthisstudyisnotgeneralfromallaspects (cid:73)(cid:83)(cid:101)(cid:67)(cid:117)(cid:114)(cid:101)7 transformer. In Proceedings of the 38th Inter- TableA.1.DetailsofDatasets nationalConferenceonMachineLearning;Pro- Vulnerability Occurrencein[26] Occurrencein[27] ceedingsofMachineLearningResearch:PMLR,
CWE-15 15 0 pages78–91,2021. CWE-1004 1 0 CWE-614 1 0 [10] Lorenz Hüther, Bernhard J. Berger, Stefan CWE-489 22 0 Edelkamp,SebastianEken,LaraLuhrmann,and CWE-20 0 18 CWE-22 3 11 et al Hendrik Rothe. Machine learning in the CWE-78 25 5 context of static application security testing - CWE-79 26 11 CWE-80 0 3 ml-sast. FederalOfficeforInformationSecurity CWE-89 2 6 (BSI),2021. CWE-90 0 15 CWE-94 0 7 [11] AbdalsamadKeramatfar,MohadesehRafiee,and CWE-95 0 2 Hossein Amirkhani. Graph neural networks: a CWE-99 0 2 CWE-113 0 5 bibliometricsoverview. MachineLearningwith CWE-116 0 7 Applications,10:100401,2022. CWE-117 0 6 CWE-1204 0 3 [12] ChakrabortyS,KrishnaR,andDingYandRayB. CWE-193 0 4 Deep learning based vulnerability detection: Are CWE-200 0 5 CWE-209 0 4 wethereyet? InIEEETransactionsonSoftware CWE-215 0 4 Engineering,pages3280–96.IEEE,2022. CWE-250 0 3 CWE-252 0 2 [13] FuMichaelandetal. Vulrepair:At5-basedauto- CWE-259 0 2 matedsoftwarevulnerabilityrepair. InProceed- CWE-269 0 4 CWE-283 0 2 ings of the 30th ACM Joint European Software CWE-284 0 3 Engineering Conference and Symposiumon the CWE-285 0 5 CWE-295 1 8 Foundationsof Software Engineering,pages935– CWE-297 0 10 947,2022. CWE-306 0 4 CWE-312 0 3 [14] etal.Zhou,Yaqin.Devign:Effectivevulnerability CWE-319 0 2 identificationbylearningcomprehensiveprogram CWE-321 0 1 CWE-326 0 4 semanticsviagraphneuralnetworks.Advancesin CWE-327 0 7 neuralinformationprocessingsystemsy,32,2019. CWE-329 0 4 CWE-330 0 1 [15] etal.Ding,Yangruibo. Velvet:anovelensemble CWE-331 0 1 learning approach to automatically locate vul- CWE-339 0 4 CWE-347 0 3 nerablestatements. In2022IEEEInternational CWE-352 0 1 ConferenceonSoftwareAnalysis,Evolutionand CWE-367 0 3 CWE-377 0 3 Reengineering (SANER), pages 959–970.IEEE, CWE-379 0 4 2022. CWE-384 0 4 CWE-385 0 6 [16] spectrum. https://spectrum.ieee.org/top- CWE-400 0 3 programming-languages-2022, 2022. CWE-406 0 9 CWE-414 0 7 Accessed:2023-06-23. CWE-425 0 4 [17] et al. Lomio, Francesco. Just-in-time software CWE-434 0 9 CWE-454 0 6 vulnerabilitydetection:Arewethereyet?Journal CWE-462 0 5 ofSystemsandSoftware,--:111283,2022. CWE-477 0 2 CWE-488 0 4 [18] RebeccaRussellandetal.Kim. Automatedvul- CWE-502 0 15 nerability detection in source code using deep CWE-521 0 5 CWE-522 0 12 representationlearning. In201817thIEEEinter- CWE-595 0 4 nationalconferenceonmachinelearningandap- CWE-601 0 14 CWE-605 0 4 plications(ICMLA),pages757–762.IEEE,2018. CWE-611 0 22 [19] Zhen Li and et al. Zou. Vuldeepecker: A deep CWE-641 0 3 CWE-643 0 8 learning-basedsystemforvulnerabilitydetection. CWE-703 0 13 arXivpreprintarXiv:1801.01681,2018. CWE-730 0 10 CWE-732 0 4 [20] Laura Wartschinski and et al. Nollers. Vudenc: CWE-759 0 4 Vulnerabilitydetectionwithdeeplearningona CWE-760 0 2 CWE-776 0 3 natural codebase for python. Information and CWE-798 0 4 SoftwareTechnology,144:106809,2022. CWE-827 0 3 CWE-835 0 5 [21] etal.Steenhoek,Benjamin.Anempiricalstudyof CWE-841 0 10 deeplearningmodelsforvulnerabilitydetection. CWE-918 0 8 CWE-941 0 8 arXivpreprintarXiv:2212.08109,2022. CWE-943 0 7 [22] et al. Chen, Yizheng. Diversevul: A new vul- (cid:73)(cid:83)(cid:101)(cid:67)(cid:117)(cid:114)(cid:101)8 nerable source code dataset for deep learning based vulnerability detection. arXiv preprint arXiv:2304.00409,2023. [23] HazimHanifandSergioMaffeis. Vulberta:Sim- Abdalsamad Keramatfar re- plifiedsourcecodepre-trainingfor vulnerability ceivedhisPhDin Information Tech- detection. InInternationalJointConferenceon nology engineering in 2021 with a NeuralNetworks(IJCNN),pages1–8,2022. focus on Natural Language Process- [24] Michael Fu and Chakkrit Tantithamthavorn. ing and Deep Learning. He worked Linevul:atransformer-basedline-levelvulnera- asaDataScientistfor6yearsatSID bilityprediction. InProceedingsofthe19thInter- andiscurrentlyworkingasanAIre- nationalConferenceonMiningSoftwareReposi- searcheratRCDAT. tories,pages608–620,2022. [25] Pavel Zadorozhny Cheshkov, Anton and Ro- Amir Norouzi is a data scientist dion Levichev. Evaluation of chatgpt model witha Master’sdegreeinBioelectric for vulnerability detection. arXiv preprint Engineeringfrom Amirkabir Univer- arXiv:2304.07232,2023. sityofTechnology.Heisexperienced [26] MohammedLatifSiddiqandJoannaCSSantos. in machine learning, data engineer- Securityevaldataset:miningvulnerabilityexam- ing,deeplearning,anddataanalysis. plestoevaluatemachinelearning-basedcodegen- HehasbeenworkinginAIsince2017 erationtechniques.InProceedingsofthe1stInter- andiscurrentlyworkingasaresearcherinRCDAT. nationalWorkshoponMiningSoftwareReposito- riesApplicationsforPrivacy andSecurity,pages 29–33,2022. Mohammad Mahdi [27] BrunoThalmannStefanMicheelsen.Pyt:Astatic Chekidehkhoun graduated from analysistoolfordetectingsecurityvulnerabilities Telecommunications engineering in
inpythonwebapplications,2016. 2016 with a focus on identifying [28] python-security. https://github.com/python- threatsinthemobilenetwork.Hehas security/pyt/tree/master/examples, 2018. beenworkingasasecurityspecialist Accessed:2023-06-15. atRCDATfor12years,focusingon [29] Isa Fulford Andrew Ng. Chatgpt prompt penetrationtestingandcodesecurityreviews. engineering for developers. https://www. deeplearning.ai/short-courses/chatgpt- prompt-engineering-for-developers, April 2023. Accessed:2023-04-27. [30] Atieh Bakhshandeh and Zahra Eskandari. An efficient user identification approach based on netflowanalysis. In201815thInternationalISC (Iranian Society of Cryptology) Conference on InformationSecurityandCryptology(ISCISC), pages1–5.IEEE,2018. [31] CatherineTony,MarkusMutas,NicolásEDíaz Ferreyra, and Riccardo Scandariato. Llmse- ceval: A dataset of natural language prompts for security evaluations. arXiv preprint arXiv:2303.09384,2023. AtiehBakhshandehisacybersecu- rityresearcherinRCDATsince2014. ShehasamasterdegreeinComputer Science and her interested research areasincludedataanalysisforsecu- ritythreatdetectionandpenetration testing. (cid:73)(cid:83)(cid:101)(cid:67)(cid:117)(cid:114)(cid:101)
2309.02391 1 Empirical Review of Smart Contract and DeFi Security: Vulnerability Detection and Automated Repair Peng Qian, Rui Cao, Zhenguang Liu, Wenqing Li, Ming Li, Lun Zhang, Yufeng Xu, Jianhai Chen, and Qinming He Abstract—DecentralizedFinance(DeFi)isemergingasapeer- in a peer-to-peer network following a consensus protocol [6], to-peer financial ecosystem, enabling participants to trade prod- [7]. Each block in the blockchain consists of a number of ucts on a permissionless blockchain. Built on blockchain and transactions. Every time a new transaction occurs, a record of smart contracts, the DeFi ecosystem has experienced explosive that transaction is added to the ledger of every bookkeeping growth in recent years. Unfortunately, smart contracts hold a massive amount of value, making them an attractive target node [8]. The duplicate ledgers stored in the worldwide for attacks. So far, attacks against smart contracts and DeFi participating nodes ensure that transactions are immutable protocols have resulted in billions of dollars in financial losses, once recorded, endowing the blockchain with tamper-proof severely threatening the security of the entire DeFi ecosystem. and decentralized nature [9]. Researchers have proposed various security tools for smart Smart contracts are programs running on a blockchain contracts and DeFi protocols as countermeasures. However, a comprehensiveinvestigationoftheseeffortsisstilllacking,leaving system.Theyencodepredefinedtermsintoexecutablecontract acrucialgapinourunderstandingofhowtoenhancethesecurity code.Onceasmartcontractisdeployedontheblockchain,its posture of the smart contract and DeFi landscape. definedruleswillbestrictlyfollowedduringexecution.Smart To fill the gap, this paper reviews the progress made in the contracts make the automatic execution of contract terms field of smart contract and DeFi security from the perspective possible, facilitating complex decentralized applications [10], of both vulnerability detection and automated repair. First, we analyze the DeFi smart contract security issues and challenges. [11]. So far, tens of millions of contracts have been deployed Specifically, we lucubrate various DeFi attack incidents and onEthereum,oneofthemostprominentblockchainplatforms, summarize the attacks into six categories. Then, we present enabling a variety of applications, such as wallet [12], gam- an empirical study of 42 state-of-the-art techniques that can blinggame[13],supplychain[14],healthcare[15],andcross- detect smart contract and DeFi vulnerabilities. In particular, industry finance [16]. we evaluate the effectiveness of traditional smart contract bug detectiontoolsinanalyzingcomplexDeFiprotocols.Additionally, Recently, we have witnessed a dramatic rise in the popu- we investigate 8 existing automated repair tools for smart con- larity of decentralized finance (DeFi) applications [17]–[20]. tractsandDeFiprotocols,providinginsightintotheiradvantages The total value locked (TVL) in DeFi has increased to as and disadvantages. To make this work useful for as wide of an high as $248.84 billion due to the rapid growth of these audience as possible, we also identify several open issues and applications. DeFi has shown its potential to expand the use challengesintheDeFiecosystemthatshouldbeaddressedinthe future. As a side contribution, we release an annotated dataset of blockchain from simple value transfer to complex financial that consists of 99 DeFi protocols (7,340 DeFi smart contracts) services [21]. Popular DeFi protocols now enable a variety of and concerns six types of DeFi attacks, hoping to facilitate the decentralized services, including lending and borrowing [22], DeFi community. portfolio management [23], [24], asset exchanges [25], and Index Terms—Smart Contract; Decentralized Finance (DeFi); derivatives [26], all without the need for trusted parties. Blockchain; Vulnerability Detection; Automated Repair MotivationI:UnderstandingDeFiAttacks. WhileDeFi has been constantly improving, it is still in its infancy and I. INTRODUCTION the new DeFi ecosystem is crude, leaving a large room for securityattacks[27],[28].Forexample,inFebruary2020,the Blockchain and its killer applications, e.g., Bitcoin [1] and well-known DeFi protocol bZx suffered from two consecutive smart contract [2], are taking the world by storm, giving rise attacks [29]. Attackers made use of the logic flaws in bZx to a variety of interesting and compelling decentralized appli- to achieve arbitrage (i.e., stealing over $8 million ETH at cations [3]–[5]. A blockchain is essentially a replicated and that time) at a low cost. This case is not isolated, and distributed ledger that is shared among all bookkeeping nodes attacks on DeFi protocols happen every few months [30]. Peng Qian is with College of Computer Science and Technology, Zhe- In April 2020, cybercriminals hacked into the DeFi proto- jiang University, Hangzhou 310058, China and Goplus Security (e-mail: col UniswapV1 and exploited the reentrancy vulnerability to pqian@zju.edu.cn). steal 1,278 ETH [31]. In October 2021, the DeFi protocol Rui Cao is with School of Computer Science and Technology, Zhejiang GongshangUniversity,Hangzhou,China(e-mail:primercrui@gmail.com). Cream.Finance suffered from an external attack, yielding Zhenguang Liu, Wenqing Li, Jianhai Chen, and Qinming He are losses of more than $130 million [32]. Recently, DeFi cross- with College of Computer Science and Technology, Zhejiang University, chain project Poly Network [33] and NFT game Ronin [34] Hangzhou 310058, China (e-mail: liuzhenguang2008@gmail.com, lwqfight-
ing@zju.edu.cn;chenjh919@zju.edu.cn;hqm@zju.edu.cn). were attacked by hackers, losing $611 million and $622 Ming Li, Lun Zhang, and Yufeng Xu are with Goplus Security, million respectively, which are the two most severe attacks in Hangzhou, China (e-mail: Mike@gopluslabs.io; Allen@gopluslabs.io; es- DeFiatthetimeofwriting.Accordingtothestatisticsfromthe kil@gopluslabs.io). (Correspondingauthor:JianhaiChen) REKTDatabase[35],DeFiprotocolshavelostatotalof$77.1 3202 peS 6 ]RC.sc[ 2v19320.9032:viXra2 $100B $80B $40B $20B $10B $0B Jan2019 Dec2019Jan2020 Dec2020 Jan2021 Dec2021 Jan2022 Month-Year iFeDnOskcattAyBdesuaCssoLevitalumuC in DeFi attack detection is increasing, there is no systematic overview to probe the state-of-the-art DeFi attack detection approaches and gauge their effectiveness. Another line of work focuses on identifying and patching $75.99B vulnerabilities in smart contracts and DeFi protocols. For example, SGUARD [56] compiles a smart contract into the $23.56B bytecode, source map, and abstract syntax tree (AST). The $22.93B bytecode is used to find bugs, while the source map and $11.98B $13.59B $13.75B AST help fix the contract at the source code level. [57] $11.96B develop an automated repair approach for DeFi protocols that $8.47B can fix violations of functional specifications expressed as a property while providing solid correctness guarantees. To our Dec2022 knowledge, the review of existing automated repair tools for smart contracts and DeFi protocols is yet to be explored. Fig.1. ThecumulativelossescausedbyattackstargetingDeFiprotocols. OurWork. Inthispaper,weaimtoprovideacomprehen- sive understanding of various DeFi attacks and an empirical billion due to scams, hacks, and exploits, out of which only review of state-of-the-art smart contract and DeFi security $6.5 billion has been returned. Fig. 1 shows the cumulative tools. On the one hand, we study 57 reported DeFi attack financial losses caused by attacks on DeFi over the past three incidents, from which we summarize six common categories years. Obviously, frequent attacks have caused huge losses to ofDeFiattacks.Inparticular,wepresentconcreteexamplesto the DeFi ecosystem and severely hindered its development. illustrate the attack flow of each type of DeFi attack. Notably, Notwithstanding recent efforts have been directed towards we construct and release an annotated dataset consisting of investigating DeFi attacks [21], [36], [37], a broad and well- 99 DeFi protocols (a total of 7,340 smart contracts). We structured overview of this important research topic is still ensurethetraceabilityofeachprojectbyprovidingitsaddress missing. In particular, current studies mostly revolve around or URL. For each DeFi protocol, we annotate the type of financial applications and services of DeFi [38], [39], while attack or vulnerability it suffered. On the other hand, we lackinganin-depthreviewonDeFiattacks.Motivatedbythis, investigate 50 security analysis tools that can either detect or westrivetoprovideacomprehensiveunderstandingofvarious repair vulnerabilities in smart contracts and DeFi protocols. DeFi attacks, hoping to facilitate the DeFi community. Specifically, we first review the principles of bug detection MotivationII:InvestigatingState-of-the-ArtSmartCon- toolsfortraditionalsmartcontracts,andthenconductextensive tract and DeFi Security Tools. Like traditional computer experiments to evaluate their performance when applied to programs, smart contracts contain vulnerabilities. Distinct complex DeFi protocols. Then, we illustrate the design of from the traditional programs, exposed bugs in the on-chain existing DeFi attack hunting techniques and DeFi smart con- smart contracts cannot be patched due to the immutability of tract automated repair approaches, as well as their workflow. the blockchain [40]. Since DeFi protocols typically consist Finally, we analyze the limitations of existing security tools of multiple smart contracts, they inevitably carry the risk of when dealing with DeFi protocols, and provide overall novel externalattacks.Therefore,itisimportanttoidentifypotential insights. Our study also identifies several open issues and vulnerabilities in smart contracts. A number of works [41]– challenges in the DeFi ecosystem that need to be addressed [43] have been developed to automatically detect flaws in by future work. smartcontracts.Theymainlyfocusonstaticanalysis[44]–[46] Contributions. The key contributions of this paper are: and fuzzing techniques [47]–[49] to discover vulnerabilities. For example, Slither [50] converts smart contracts into an in- • This work, to the best of our knowledge, is the first to present a comprehensive review of various DeFi attacks termediaterepresentationandperformstaintanalysistodetect and a systematic evaluation of the state-of-the-art smart vulnerabilities.ContractFuzzer[51]appliesfuzzingtechniques contract and DeFi security tools, empirically revealing both to smart contracts and reveals vulnerabilities by monitoring the capabilities and limitations of existing approaches. runtime behavior during fuzzing. However, most of these approaches are tailored for traditional smart contracts that • Inlightof57reportedDeFiattackincidents,wesummarize sixcategoriesofDeFiattacksorvulnerabilities.Further,we usually comprise a single contract. Their ability to perform also construct a benchmark dataset, which contains a total vulnerability analysis on complex DeFi protocols has yet to
of7,340DeFismartcontracts.Tofacilitatethecommunity, be investigated. we have released this dataset for public use at https://gith Several recent efforts [52]–[54] are devoted to detecting ub.com/Messi-Q/DeFi-Protocol. DeFi attacks by analyzing the transactions in DeFi proto- cols, from which they extract transaction patterns to expose • We empirically study 42 bug detection tools and 8 au- potential attacks. For example, PROMUTATOR [30] detects tomated repair techniques for smart contracts and DeFi thepricemanipulationattackbyreconstructingprobableDeFi protocols, with the analysis of their performance. We also use patterns from historical transactions. DEFIRANGER [55] discuss several open issues and challenges in the DeFi identifies DeFi price oracle attacks according to recovered ecosystem that need to be tackled by future research. high-levelDeFisemantics.Unfortunately,althoughtheinterest Paper Organizations. The remainder of the paper is3 organized as follows. In Section II, we give a brief intro- the involvement of a trusted third party. They are compiled duction to the background of blockchain, smart contract, and to bytecode and executed within a virtual machine called decentralized finance (DeFi). Thereafter, we summarize six the Ethereum Virtual Machine (EVM). Once deployed, smart common types of DeFi attacks and present concrete examples contracts are uploaded to the blockchain and broadcast to all in Section III. In Section IV, we investigate state-of-the-art ledger nodes for backup. bug detection and repair techniques for smart contracts and A smart contract can implement arbitrary rules for manip- DeFi protocols. Section V describes the dataset construction, ulating digital assets [2]. The rules defined in a smart con- and presents the evaluation results of available automated tract are strictly and automatically followed during execution, vulnerabilitydetectiontoolsonDeFiprotocols.InSectionVI, effectuating the ‘code is law’ logic [9]. While Ethereum is we discuss several open issues and challenges. Finally, we becoming one of the most influential blockchains, it has been conclude the paper in Section VII. exposed to a large number of smart contract security vulner- abilities [71]. Since DeFi protocols are usually composed of II. BACKGROUND multiple smart contracts, it inevitably becomes an attractive attacktarget,whichhascausednumerousfinanciallosses[72]. Before diving into the key components, please allow us to introduce the required background on blockchain, smart C. DeFi: Decentralized Finance contract, and decentralized finance. Decentralized finance, a peer-to-peer financial system powered by the blockchain, is flourishing [73]. With the A. Blockchain In A Nutshell widespread adoption of smart contracts, the concept of de- Blockchain, a distributed ledger maintained in a decentral- centralized finance truly came to fruition, even to the point ized manner, was first popularized as the technology behind of hosting an economy exceeding $200 billion [38], [74]. Bitcoin [58]. The ledger is shared among all participating DeFi builds upon the permissionless foundation provided by nodesintheblockchainnetwork.Apublicblockchainnetwork blockchains. Anyone is free to propose a novel financial hasanopenandtransparentinfrastructure,whichisnotowned contract, and anyone can interact with, transfer assets to, and or controlled by any centralized organization [59]. Put differ- withdraw assets from it, as long as the participants abide ently,blockchaincanguaranteethefidelityandsecurityofthe by the immutable contract rules. A DeFi protocol typically recorded data without the need for a trusted intermediary. consists of multiple interactive smart contracts that run on Morespecifically,thedistributedledgercontainsasequence top of the blockchain’s state machine. Currently, a variety of blocks, each of which records a set of transactions. Every of financial services are migrating to the DeFi ecosystem, blocklinkstoitspreviousblock,formingachain.Whenauser including lending and borrowing, decentralized exchanges, wants to add a new transaction to the ledger, the transaction portfoliomanagement,derivatives,andmanyothers[21],[75]– data is verified by the so-called miners (bookkeeping nodes) [77]. To provide an intuition of what DeFi is and what DeFi andputintoanewblock[60].Oncethenewblockisconfirmed can do, we present a high-level overview of DeFi in Fig. 2. by miners that follow a consensus protocol, it is added to Explicitly, we summarize the applications of DeFi into six the chain [61]. Each miner stores a duplicate transaction categories. ledger, which endows the blockchain with decentralized and 1) Lending and Borrowing: Lending and borrowing of immutablenature,thatis,nobodycanalteranddeletethedata assets in a DeFi application are realized through protocols for recorded in the ledger. fundsloaning,whicharereferredtoastheDeFilendingproto- cols [78]. Decentralized lending services constitute the largest Evolution of Blockchain. The first implementation of class of DeFi applications, with a cumulative TVL of over a blockchain system was Bitcoin, i.e., decentralized digital $40 billion [79]. They offer loans to individuals or businesses currencyverifiedusingcryptography[62].Thesecondwaveof usingsmartcontractsasnegotiatorsorintermediaries,assmart decentralized blockchain applications started with the advent contracts automate the lending and borrowing process [80]. of Ethereum [63], which introduced smart contracts and en- InDeFiapplications,loansaregenerallyoftwoforms.One abled multiple types of dapps. In recent years, a new subfield is the over-collateralized loan, where the borrower is required of blockchain, decentralized finance [64], which specializes to post collateral, i.e., provide something of value as security
in advancing financial technologies and services on top of a to cover the debt [81]. In this way, collateralization ensures permissionless blockchain (typically Ethereum), has attracted that the lender can recover the loaned value and provides the considerable attention worldwide. For a thorough background borrower with an incentive to repay the loan. Another inter- on blockchain, readers can refer to SoKs, such as [65]–[67]. esting form is the non-collateralized loan, i.e., flash loan [36]. Flash loans allow users to borrow any available amount of B. Ethereum and Smart Contract assets from a liquidity pool without upfront collateral, as long Ethereumisoneofthemostprevalentblockchainplatforms, as the loan is repaid at the end of the transaction. Flash which is the first to introduce the functionality of smart loansleveragetheatomicityoftheblockchaintransaction(i.e., contracts [68]. Ethereum smart contracts are developed in a transaction reverts to its previous state if the loan is not high-level programming languages such as Solidity [69] and repaid within the current transaction) to facilitate several use Vyper [70]. Smart contracts are essentially a set of digital cases,e.g.,decentralizedexchangearbitrage[82]andcollateral agreements with encoded rules that can be enforced without swaps [73].4 DeFi Applications MarketMechanisms Portfolio Management Derivative • 1 Governance • 2 Arbitrage DEX • 3 Lending Liquidation Stablecoin • 4 SecurityDeposit Aggregator Node Infrastructure and Consensus Cross-Chain Side Chain State Channel Interoperability Blockchain Bitcoin Ethereum EOS Network Fig.2. Ahigh-leveloverviewofDeFiecosystem.DeFibuildsuponadistributedblockchainnetwork,enablingvariousDeFiapplications,suchasportfolio management,decentralizedexchanges,derivatives,lendingandborrowing,stablecoin,andaggregator. In general, a transaction reverts due to three possible traders who are willing to provide liquidity to the market, reasons: 1) the transaction sender does not specify sufficient to deposit assets into a liquidity pool. The market maker transactionfees,2)thetransactiondoesnotsatisfyacondition can deposit two or more tokens into a liquidity pool with a setforthbytheinteractingsmartcontract,or3)thetransaction self-defined weight. The trade rate between cryptocurrencies conflicts(e.g.,doublespending)withanothertransaction[83]. in the pool is automatically calculated based on the pricing Flash loans, therefore, entail two interesting properties. First, mechanism [89]. AMM has become the most popular mode the lender is guaranteed that the borrower will repay the in DEXs due to its flexible liquidity [90], [91]. loan. If the repayment is not performed, the loan will not 3) Portfolio Management: As more and more DeFi pro- be given. Second, the borrower can technically request any tocols motivate clients to provide liquidity, a new type of amount of capital, up to the number of funds available in a project, known as portfolio management, debuts to help users flashloanpool.Whileprovidingconvenience,flashloansallow (i.e., liquidity providers) invest their assets [92], [93]. They adversariestolaunchmaliciousattackswithalargenumberof automatically find the DeFi protocols that provide the highest assets that they do not actually own. Undesirable trades using annual percentage yield (APY). However, liquidity allocation the flash loan have resulted in numerous notorious attacks on is an arduous task for liquidity providers who seek to maxi- DeFi applications, such as [84]–[86]. mize their profits due to the complex and expansive space of 2) Decentralized Exchange: Decentralized exchange yield-generating options. Therefore, the management of on- (DEX) is essentially a kind of DeFi protocol that enables chain assets that serve as decentralized investment funds can the on-chain exchange of digital assets [87]. Users can trade be automated through DeFi protocols. An investment strategy different tokens in a decentralized manner by interacting with that entails transacting with other DeFi protocols is encoded smart contracts. Decentralized exchanges have accumulated in the smart contracts, and the invested assets are deposited over $25 billion locked funds. For example, one of the largest into the contract [94]. DEXs is Uniswap [88], whose users have locked up around 4) Derivative: DeFi derivatives are built upon the smart $8 billion in token value. Compared to traditional centralized contracts that derive value from the performance of an under- exchanges, DEXs have advantages in privacy protection and lying entity, such as currencies, bonds, and interest rates [95]. asset management. There are two modes in DEXs, i.e., list Tokenized derivatives can be created without trusted third of booking (LOB) and automated market maker (AMM). parties and are able to prevent the influence of malicious DEXs in LOB mode maintain an off-chain order book to attacks. While approximately 99% of the derivative trading record users’ bids and asks, namely, the order matching is volume is created on centralized exchanges, a number of performed off-chain. DEXs in AMM mode achieve a fully DeFi protocols have emerged that provide similar function- decentralized exchange. AMM allows liquidity providers, the ality, with a particular focus on futures, perpetual swaps, and5 options [96]. Popular examples of DeFi derivatives include CompliFi [97], dYdX [98], and BarnBridge [99], etc. dYdX 5) Stablecoin: Stablecoins are a class of cryptocurrencies designed to ensure price stability [100], [101]. Typically, stablecoins are stabilized by either being directly/indirectly 1 FlashLoan2.048M USDC 4 Repay 2.048M USDC backed or intervened through various stabilization mecha-
nisms. The popular stablecoins, such as USDC or USDT, are c r c theu hl as ay tt lo le aod n cni hgal iea ea vfn ot erd r su tsf h pa te e rll id cpo ertu oht stis o tri ad cd boe ilp lt ia dh tyr ee t sys i i. g nc no In ep ar ne d io se ef c ctoe oD n nce t oorF ma ni l, si iz cta re as ud lc lt yh tse aey st estp t ci anr ubi g rm l es e,a c ar oti nhl iny de 2 Ex Fc oh r a 2n .g 0e 2 82. M0 4 D8 AM I U SD C Attacker FoE rx 2c .h 0a 6n 4g Me 2 U.0 S2 D8 CM DAI 3 stable manner and where all necessary parties can continue to participateprofitably[102].Pricestabilityisachievedthrough Exchange Rate: Exchange Rate: 1.010 USDC/DAI 1.018 USDC/DAI on-chaincollateralthatprovidesafoundationofsecuredloans Profit:16KUSDC from which the stablecoin derives its economic value. Non- CurveY CurvesUSD custodial stablecoins aim to be independent of the societal Fig.3. ApumpandarbitrageattackontheDeFiprotocol—dYdX. institutions that custodial designs rely on. Popular stablecoins in DeFi include Tether [103], DAI [104], Diem [105], etc. 6) Aggregator: DeFi aggregator is essentially a platform A. Flash Loan Attack that consolidates trades from various decentralized platforms AsanemergingserviceintheDeFiecosystem,theflashloan into one place, increasing the efficiency of cryptocurrency allowsuserstoapplyforanon-collateralloan.Whileproviding trading [106]. Typically, a DeFi aggregator leverages multiple convenience,itenablesadversariestolaunchmaliciousattacks DEXs and implements various buying and selling strategies withalargenumberofassetsthattheydonothave[27].After to help users maximize profits, while mitigating gas fees and scrutinizing existing DeFi attacks, we found that around 50% DEXstradingcommissions[64].Notonlydoaggregatorspull of DeFi attack incidents involve flash loans [36]. Flash loan thebestprices,butsomeDeFiaggregatorsevenofferaunique, attack has become the most prominent form among various user-friendlywaytoanalyzeandcombineotherusers’trading DeFi attacks. In particular, we summarize three major types strategiesviaaconvenientdrag-and-dropmechanism[107].In of flash loan attacks, namely, pump and arbitrage [28], price particular,withtheadventofDeFiaggregators,newentrantsto manipulation[55],andreentrancy[32].Foreachtypeofflash the industry can benefit from DeFi without understanding the loan attack, we present the intuition to identify the essence of complex technologies such as trading, decentralized services, the attack. We then deliver a concrete example to clarify the and blockchain. Overall, an aggregator helps users make attack. better trading decisions. Popular DeFi aggregators include 1) Pump and Arbitrage: Generally speaking, arbitrage is 1inch [108], Matcha [109], and Plasma.Finance [110]. the practice of making a profit by trading on different ex- changes that provide different prices for the same asset. III. OVERVIEWOFDEFIATTACK Since the DeFi market reacts more slowly to events on the blockchain network than the real-world market, attackers can DeFihastakenanincrediblewaveofpopularityandenabled takeadvantageofmarketinefficienciestobuyandsellanasset growing penetration in various industries. Nevertheless, due at different prices, gaining financial benefits. With the flash to the trillion dollars wealth it holds, DeFi attracts numerous loan, attackers can achieve arbitrage without any pre-owned external attacks, which severely threaten the security of the asset.Particularly,oncethepricedifferenceisfound,attackers entire DeFi ecosystem [111], [112]. While multifarious DeFi can instantly borrow a considerable amount of assets with a attacks have attracted considerable attention, there is still flash loan service and further achieve arbitrage. a lack of a well-structured overview for providing an in- Intuition. Thenucleusofthepumpandarbitrageattackis depth review and analysis of DeFi attacks. Motivated by this, thattheattackerleveragesthedifferentpricesofthesameasset we present a comprehensive review of various DeFi attacks, on different exchanges. For example, the attacker pumps the hoping to inspire the readers. Specifically, we examine the ETH/WBTC exchange rate on a constant product AMM (e.g., well-known DeFi attack incidents over the past three years, Uniswap) with the leveraged funds of ETH in a margin trade. which are listed in Table I. We summarize these attacks into Afterwards, the attacker purchases ETH at a cheaper price on sixcategories,i.e.,flashloanattack(pumpandarbitrage,price the distorted price market with the borrowed WBTC from a manipulation, reentrancy), deflation token attack, sandwich lending platform. attack, and rug pull attack. It is worth noting that many Example. We present, as an example, the specific details existing works have investigated a variety of vulnerabilities of the pump and arbitrage attack on the DeFi protocol dYdX1, in traditional smart contracts, such as timestamp dependency which is shown in Fig. 3. Specifically, the attacker first and unhandled exception [66], [113], [114]. Instead, in this borrowsaflashloanof2.048millionUSDCfromtheexchange work,wemainlytakeaninsightintoattacksandvulnerabilities dYdXinstep❶.Then,theattackerexchangesallholdingUSDC targeting DeFi protocols. Next, we will go through the details of the DeFi attacks one by one. 1dYdX: https://dydx.exchange6
DecentralizedProtocol bZx Example. To further elaborate on the price manipulation (Flash Loan Provider) attack, we present a real-world attack example on the DeFi protocol bZx2, as shown in Fig. 4. In this case, the attacker 1 Borrow 4,418 ETH 6 Pay Back 4,418 ETH 5 Borrow 6,799 ETHUsing exploits the dependency of bZx on other DeFi protocols (i.e., All 1,099,842 sUSD Uniswap and Kyber) to manipulate the asset exchange rates, makingprofitswithinasingleatomictransaction.Inparticular, the attacker takes a sequence of six transactions, consisting 2 E 92x ,c 4h 2a 0ng sUe S54 D0 ETH For Attacker 3 E 63x ,c 5h 8a 4n g sUe S36 D0 ETH For of borrowing, exchanging, and repaying assets (e.g., ETH and sUSD). Note that these transactions are packed into the same 4 Deposit 3,518 ETH For 943,838 sUSD transaction in the exact order. Decentralized Exchange Stablecoin Decentralized Exchange Specifically, the attacker first borrows 4,418 ETH from bZx Uniswap Synthetix Kyber (step ❶ in Fig. 4), then the attacker uses the 4,418 borrowed ETH to exchange for sUSD using other DeFi protocols, i.e., Fig.4. ApricemanipulationattackontheDeFiprotocol—bZx. Uniswap, Synthetix, and Kyber, respectively (steps ❷–❹ in Fig. 4). Since bZx relies on Uniswap and Kyber for price oracles,whicharesusceptibletolargeamountsoftransactions, for 2.028 million DAI in another exchange Curve Y with an exchangerateof1.010USDC/DAIinstep❷.Thereafter,he/she the attacker can thus heavily skew the exchange rate of ETH/sUSD in bZx in his/her favor. After that, the attacker exchangesallDAIfor2.064millionUSDCinthethirdexchange triggersstep❺,namely,borrowing6,799ETHusingallholding Curve sUSD with an exchange rate of 1.018 USDC/DAI in step ❸. Finally, the attacker repays the original borrowed 1,099,842 sUSD. Finally, the attacker pays back 4,418 ETH in 2.048 million USDC in step ❹. With the two exchanges, the step❻,whichisborrowedattheverybeginning.Theoutcome of steps ❶–❻ is that the attacker gains a net profit of 2,381 attacker finally gains an arbitrage of 16 thousand USDC (i.e., ETH (i.e., 2,381 = 6,799 - 4,418), with only a small amount 16 thousand = 2.064 million - 2.048 million). of ETH to pay a gas fee. 2) Price Manipulation: Price manipulation is one of the 3) Reentrancy: In traditional smart contracts, reentrancy is mostcommonflashloanattacks.Insuchattacks,theadversary a well-known vulnerability that caused the notorious DAO distortsthereportedpriceandpropagatesthedistortionusinga attack [115]. When a function F of a victim contract trans- vulnerable customized function, causing the victim to receive fers money to a malicious attack contract C, due to the inaccurate price information. As a result, the victim is tricked default settings of smart contracts, the fallback function of into overvaluing or undervaluing the target asset. Typically, C is automatically triggered. The attack contract C can set the process of a price manipulation attack consists of the a malicious operation in its fallback function, i.e., calling followingfoursteps,allofwhichareexecutedwithinthesame F again to perform an illegal second-time transfer. As the transactiontoavoidbeinginterruptedbyotheroperations[30]. current execution of F is waiting for the first-time transfer to • Prepare Target Asset. First, an attacker prepares a target finish, the balance of C may not be reduced yet, making F asset, whose price the attacker intends to inflate. Further- wrongly believe that C still has enough balance and transfer more, the attacker borrows a large number of funds with a to C again. Therefore, the attack contract C can exploit the flash loan for the next phase. reentrancyvulnerabilitytosuccessfullystealadditionalmoney • InflateAssetPrice.Then,theattackermanipulatestheprice from the victim contract. Similarly, DeFi protocols have also of the target asset by significantly reducing its reserves in suffered from such a reentrancy attack [116]. However, unlike the corresponding AMM liquidity pools. This is typically a traditional reentrancy attack on a single smart contract, the done by swapping a large amount of the target asset for flashloanreentrancyattackonDeFiprotocolsusuallyinvolves another token. The attacker reports the manipulated price multiple smart contracts. of the target asset to the victim. Intuition. In essence, a reentrancy attack is caused by • Profit From Victim. Since the victim may overvalue the someuntrustedexternalcallsthatinterruptsomeatomictrans- target asset, the attacker makes a profit by exchanging the actions (e.g., transferring and accounting), resulting in incon- target asset for another asset through the victim’s services sistent variable states. The core of the flash loan reentrancy (e.g., collateralized borrowing). attack is that the attacker exploits the inconsistent state of • Recover Asset Price. Finally, the attacker performs the different loan pools before and after a contract’s lending (i.e., reverse actions to restore the unbalanced AMM liquidity transferring) to achieve multiple unregistered loans. pools to their original state. As a result, the attacker avoids Example. To further illustrate the flash loan reentrancy the losses caused by the second-step price slippage and attack, we present a typical example of the DeFi proto- repaysallhisoriginalassets,payingonlyfortheswapfees. col Cream.Finance3 in Fig. 5. Specifically, attacker A Intuition. The core of the price manipulation attack is borrows 500 wETH from UniSwapV2 with a flash loan in
that the attacker lowers the token exchange rate by using a step ❶. Then, A collateralizes the borrowed 500 wETH to flash loan. In the second step, the adversary benefits from Cream.Finance in exchange for 24,172 crETH in step ❷. the decreased exchange rate. As an example, the attacker can gain a profit from the decreased ETH/sUSD exchange rate by 2bZx: https://bzx.network borrowing ETH against sUSD as collateral. 3Cream.Finance: https://cream.finance7 2 Mortgage 500wETHto Exchange For24,172 crETH Contract 3 1 Bor (rA o Fwt lat s a 5 h 0c L0k oe aw nr E )4 THS3 te (a cl rEE TxB Htro a Pr 3r oA 5o o5lw l(l )c ch1 rr Eo A,9 TRl Md4 Hei8 n P eM g nP tc oA rr o aEM l n)T cP H ywith F b }ou r …n rc o .t .wion (){ F b }ou r …n rc o .t .wion (){ 1 1 4Create Create ConA At1 2ract 21 D 2eD poe sp it o WM is K a tiW n hEt y dAK ri Tit aNh E m wU d eA sr Ka N Ew U A NK UEAN MU emestake FigD .ec 5en .tr U Aa nli isz rwe ed a ep E V nx 2 trc ah nan cg ye attackontheDeFiprotocol—Cr… ea… m.Finance. Attacker KE AE Nx Uch Fan og r e E M TFund, 4 Transfer H Note that Cream.Finance consists of multiple loan pools, each of which is essentially a smart contract. Thereafter, A Fig.6. Areal-worlddeflationtokenattackonDeFiprotocol—Sanshu Inu. invokesthefunctionborrowinthecrAMPpoolandexchanges for1,948millionAMPwithallholdingcrETHinstep❸.How- than the registered number in user.amount maintained by ever, the transfer of an AMP automatically triggers the fallback function in the attacker’s contract. Since the borrowing status Memestake. However, when A 2 performs the withdrawal operation, Memestake still transfers the recorded amount of A in the crAMP pool has not been updated, attacker A of tokens to A , which leads to the continuous reduction of calls the function borrow in another pool crETH in step ❹, 2 the token holdings of KEANU in the Memestake pool. thus gaining an extra crETH from the pool. • Next, the attacker uses A 2 to modify the value of accMfundPerShareintheMemestake.Thisvaluedepends B. Deflation Token Attack onthenumberofKEANUtokensinthepoolthattheattacker Deflation is a term used in crypto finance to describe a manipulated in Step ❷. That is, the real number of KEANU drop in the value of an asset due to certain factors such as tokens in the Memestake has been reduced to a small one. over-minting [117]. Token deflation refers to the phenomenon Thus, when A 1 withdraws the KEANU tokens deposited in that the total supply of tokens decreases each time a token Step❶,itcanreceivearewardofMFundtokensfarinexcess transfer happens. With the rise of decentralized finance, var- of the normal value. ious deflation tokens are emerging. Some types of deflation • Finally, the attacker swaps the extracted MFund and KEANU tokens in DeFi are implemented in the form of deducting a tokens to ETH, and transfers them away through Tornado, certain percentage of tokens for destruction and redistribution making a net profit of 56 ETH. each time a user performs a transaction transfer [21]. This may result in the actual number of tokens received by the C. Sandwich Attack recipient being less than the amount paid by the sender. The A sandwich attack is a typical predatory trading strategy in principle of the deflation token attack is that the attacker which a trader wraps a victim transaction with two malicious exploits such characteristics to reduce the number of a target transactions, one before the victim transaction and one after token by performing multiple in and out transfers, in order to the victim transaction [54], [79], [89], [118]. In such attacks, profitfromthedifferenceintheamountofthedeflationtoken. the malicious attacker first scans the mempool for pending Example. Fig. 6 presents a real-world example to illus- transactions and finds that a user (i.e., the victim) is trying to trate the deflation token attack on the Memestake contract of the DeFi protocol Sanshu Inu4. The overall attack process trade an asset X for another asset Y. Then, the attacker buys assetYatalowprice.Thistransactionmaybeearlierthanthe can be summarized into the following four steps. victim’stransaction.Oncethistransactioniscompletedbefore • First, the attacker creates two contracts and initializes the victim’s transaction, the price of asset Y will increase themaccordingly.Specifically,contractA isaninvestment 1 accordingly5. When the victim’s transaction is carried out, contract that deposits 2,049 billion KEANU tokens into the he/she will receive a smaller quantity of asset Y than he/she Memestake pool, and A 2 is the attack contract that is used wassupposedtoreceiveduetotheincreaseinthepriceofasset to manipulate the reward calculation of Memestake. Y. Finally, the attacker sandwiches the victim’s transaction • Then, the attacker calls A 2 to deposit/withdraw a large by selling off asset Y at a higher price than he/she bought number of KEANU tokens to/from Memestake many times, it, thereby profiting from the manipulated price. This attack forcing Memestake to trade KEANU in large quantities. sequenceallowstheattackertopocketaprofitbyfront-running Since KEANU is a deflation token, each transaction costs and back-running a trader, creating an artificial price rise. 2% of the transaction amount, resulting in the real number of tokens that users deposit to Memestake being smaller 5Theexchangerateofeachtransactionisdeterminedbypresetalgorithms andmarketliquidityreserves[119].Abuyorderwillincreasethepriceofan
4Sanshu Inu: https://sanshuinufinance.com asset,whileasellorderdecreasesthepriceoftheasset.8 A typical type of rug pull attack involves manipulating the 100ETH 300,000 USDT tokenpricewiththeattacker’sreserves,suchasprovokingthe token value to drop precipitously to zero. The rug pull attacks 3 5 BuyETHwith14,286USDT 1 BuyUSDTwith20ETH in DeFi have caused more than $2.8 billion in losses in 2021, BuyUSDTwith5ETH 4 6 Get 7 ETH Back makingitthebiggestscamintheDeFiecosystem(accounting 2 Get 45,714 USDT Back for 37% of all scam revenue in 2021) [124]. Get14,286USDTBack Example. In July 2021, the digital collectible platform Bondly Finance was compromised [125]. According to the Financial Loss: 50,000-45,714=4,286 USDT disclosure of the project, the attacker gained access to the Attacker password account of the CEO of Bondly Finance through Revenue:7-5=2ETH a carefully planned strategy. The password account contains the mnemonic recovery phrase of his hardware wallet, which Fig.7. AsimplifiedexampleofthesandwichattackonAMMDEXs. allows the attacker to access the BONDLY smart contract after copyingthepassword.Theattackerexploitedthisvulnerability to mint 373 million BONDLY on Ethereum, resulting in a It is worth mentioning that, in the blockchain, the miners significant drop in the token price and a loss of $5.9 million. sort the transactions in the memory pool according to the gas DuetothecomplexityanddiversityoftheDeFiecosystem, price, and then select the transactions in the order of the gas we are unable to describe each type of DeFi attack and price from high to low when creating a block [120], [121]. vulnerability in detail. We have listed the well-known DeFi Therefore,anattackercanachievethesandwichattackaslong protocols that have suffered from a DeFi attack over the as the gas price of the front-running transaction is set slightly past three years in Table I. Additionally, we refer the readers higher than that of the victim transaction, and the gas price of to [187] for more hacks, frauds, and scams in DeFi. the back-running transaction is lower than that of the victim transaction. Summary: Why are various DeFi attack incidents Intuition. The core of the sandwich attack is that the emerging? attacker hunts for a victim transaction. Then, he/she quickly (1) DeFi is open-source, suggesting that its code buys the asset at a low price and ensures that this transaction is available to everyone, which inevitably introduces is scheduled just before the victim transaction (i.e., front- security risks. running). Finally, the attacker sells the asset shortly after the (2)ADeFiprotocolisvulnerabletoexternalexploita- victim’s transaction (i.e., back-running) to make a profit. tion due to its complexity and composability. Example. As shown in Fig. 7, the attacker front-runs the (3) DeFi protocols tend to be launched in a rush. In victimtransactionwithabuyorderofUSDTandback-runsthe ordertoearnthenewfinancialmarketsharepromptly, victim transaction with a sell order. Specifically, the victim some developers did not perform adequate security transaction aims to buy USDT with 20 ETH. If there are no checks of the DeFi protocol, leaving a potential risk attackers, the trader will get back 500,000 USDT. However, of security vulnerabilities. the attacker front-runs to exchange 14,286 USDT for 5 ETH in steps ❶–❷ and sandwiches the victim transaction. Since the reserves in the liquidity pool change after each transaction. IV. REVIEWOFSMARTCONTRACTANDDEFISECURITY TheoriginalstateofETH/USDTis1/3,000.Aftertheattacker’s TOOLS first transaction, the state of ETH/USDT becomes 1/2,721. Tosafeguardthesecurityofparticipantfundsandprivacyin Therefore,insteps❸–❹,thevictimcanonlyexchange45,714 smart contracts and DeFi protocols, recent advancements put USDT for 20 ETH, resulting in a loss of 4,286 USDT. After the forwardcorrespondingsolutionsbyincorporatingvulnerability victim’s transaction, the state of ETH/USDT in the liquidity detection and automated repair techniques. pool changes to 1/1,920. Finally, the attacker uses all holding • Vulnerability Detection. A plethora of work has been 14,286 USDT to exchange for 7 ETH in steps ❺–❻, gaining a designed to automatically identify vulnerabilities in smart profit of 2 ETH. contracts. Existing surveys have provided a relatively com- prehensive overview of current bug-finding tools for smart contracts. However, a fine-grained classification and empir- D. Rug Pull Attack ical comparison of existing methods is still lacking. More- Rug pull refers to the draining of investments from DEX over, many of these approaches are tailored for traditional liquiditypoolsorthesuddenderelictionofaproject,sweeping smart contracts, which are typically single contracts. It awayinvestors’fundswithoutanywarningsigns[122],[123]. is necessary and critical to verify whether these methods The rug pull attack occurs mostly in decentralized exchanges can effectively handle complex DeFi protocols. Towards (DEXs)andisatypicalscaminDeFi.Scammersinvestalotof these,wenotonlyperformanempiricalanalysisofexisting moneyinliquiditypoolsandpublishattractiveadvertisements smart contract bug detection tools but also evaluate their on social media to attract investors. Once investors deposit effectiveness in detecting vulnerabilities in DeFi protocols. tokens into these liquidity pools, the scammers will “sweep Furthermore, several recent efforts have explored detect-
the carpet”, namely, withdraw all the tokens from the pools. ing attacks against DeFi protocols by analyzing the DeFi9 TABLEI ASUMMARYOFWELL-KNOWNDEFIPROTOCOLSTHATHAVESUFFEREDFROMEXTERNALATTACKS.SPECIFICALLY,CATEGORYMEANSTHECATEGORY OFDEFIFINANCIALSERVICES.ATTACKTYPEDENOTESTHEATTACKTYPETHATADEFIPROTOCOLSHADENDURED.LOSSINDICATESTHE CORRESPONDINGFINANCIALLOSSESCAUSEDBYTHEATTACK.DATEINDICATESTHETIMEWHENTHEATTACKOCCURRED. # DeFi Protocols Category Attack Type Loss Date Ref. 1 bZx-V1 Lending and Borrowing $9.4 Million 2020.02.17 [126] 2 MakerDAO Other $9 Million 2020.03.12 [127] 3 UniSwap Decentralized Exchange $0.3 Million 2020.04.18 [128] 4 bZx-V2 Lending and Borrowing $8.1 Million 2020.09.15 [129] 5 Eminence Finance Gaming $15 Million 2020.09.29 [130] 6 Harvest Finance Derivative $33.8 Million 2020.10.26 [131] 7 Akropolis Aggregator $2 Million 2020.11.12 [132] 8 Pickle Finance Yield Aggregator $20 Million 2020.11.22 [133] 9 Warp Finance Lending and Borrowing $7.7 Million 2020.12.17 [134] 10 Alpha Homora Derivative $37.5 Million 2021.02.13 [135] 11 Spartan Decentralized Exchange $40 Million 2021.05.02 [136] 12 Value DeFi Derivative $28 Million 2021.05.07 [137]–[139] 13 Venus Lending and Borrowing $300 Million 2021.05.19 [140] Flash Loan Attack 14 PancakeBunny Aggregator $47.1 Million 2021.05.20 [141], [142] 15 Burgerswap Decentralized Exchange $7.2 Million 2021.05.28 [143] 16 JulSwap Decentralized Exchange $0.7 Million 2021.05.28 [144] 17 Belt Finance Decentralized Exchange $50 Million 2021.05.30 [145] 18 SushiSwap Decentralized Exchange $0.11 Million 2021.07.21 [146] 19 THORChain Cross-Chain Bridge $5.8 Million 2021.07.22 [147] 20 Vee Finance Lending and Borrowing $13.5 Million 2021.09.21 [148] 21 Indexed Finance Aggregator $16 Million 2021.10.14 [149] 22 Cream Finance Lending and Borrowing $130 Million 2021.10.27 [150] 23 Nerve Portfolio Management $8 Million 2021.11.15 [151] 24 Beanstalk Stablecoin $182 Million 2022.04.17 [152] 25 Saddle Finance Decentralized Exchange $10 Million 2022.04.30 [153] 26 Balancer Portfolio Management $0.5 Million 2020.06.28 [154] 27 Sanshu Inu Gaming Deflation Token Attack $5 Million 2020.12.28 [155] 28 Ankr Other $5 Million 2022.12.02 [156] 29 Lendf.Me Lending and Borrowing $25 Million 2020.04.18 [157] 30 Origin Other $7 Million 2020.11.17 [158] Reentrancy Attack 31 Grim Finance Derivative $30 Million 2021.12.19 [159] 32 Rari Capital Lending and Borrowing $90 Million 2022.04.30 [160], [161] 33 FEI protocol Stablecoin $80 Million 2022.04.30 [162] 34 Mango Decentralized Exchange Sandwich Attack $100 Million 2022.10.12 [163] 35 BONDLY Stablecoin Rug Pull Attack $22 Million 2021.07.15 [164] 36 Bancor Decentralized Exchange $23.5 Million 2020.06.16 [165] 37 DODO Pool Decentralized Exchange $3.8 Million 2021.03.09 [166] 38 Uranium Finance Decentralized Exchange $50 Million 2021.04.28 [167] 39 ChainSwap Cross-Chain Bridge Smart Contract Logic Bug $4.8 Million 2021.07.11 [168], [169] 40 Popsicle Derivative $25 Million 2021.08.04 [170] 41 Poly Network Cross-Chain Bridge $611 Million 2021.08.10 [171] 42 Compound Finance Lending and Borrowing $160 Million 2021.10.03 [172] 43 PAID Network Decentralized Exchange $160 Million 2021.03.05 [173] Compromised Private Key 44 Ronin Gaming $622 Million 2022.03.23 [34] 45 Oypn Insurance $0.37 Million 2020.08.04 [174] 46 Chainlink Stablecoin $0.34 Million 2020.08.30 [175] 47 Cover Insurance $5 Million 2020.12.28 [176] 48 yCredit Finance Decentralized Exchange $326 Million 2021.01.02 [177] 49 Yearn Finance Aggregator $11 Million 2021.02.04 [178] 50 Furucombo Aggregator $15 Million 2021.02.27 [179] 51 EasyFi Lending and Borrowing Other $80 Million 2021.04.20 [180] 52 VaultSX Other $13.5 Million 2021.05.16 [181] 53 AnySwap Decentralized Exchange $7.9 Million 2021.07.10 [182] 54 SafeDollar Stablecoin $0.25 Million 2021.07.28 [183] 55 BadgerDAO Other $120 Million 2021.12.02 [184] 56 Wormhole Message Passing $7.7 Million 2022.02.02 [185] 57 Nomad Cross-chain Bridge $190 Million 2022.08.02 [186]10 transactions and restoring the high-level DeFi semantics. through state-space searching and then checks whether the Given the lack of review of attack detection tools on DeFi contracthascorrespondingsecurityproperties.Deductiveveri- protocols, we illustrate the design of existing DeFi attack ficationuseslogicalformulastodescribeaverificationsystem hunting techniques, as well as their workflow. and then proves whether the system has certain security prop- • AutomatedRepair.Whileexistingtoolsareabletoidentify erties through predefined rules. In general, formal verification vulnerabilitiesandhighlighttheaffectedcodelinesinsmart techniques mainly propose a formal model and define the contracts, they exhibit certain limitations in automatically formal semantics of contracts to verify the security properties providingpatches.Inthiscontext,smartcontractautomated in smart contracts. We review existing formal verification repair is emerged as a countermeasure. Unfortunately, due methods for smart contract bug detection and give their brief to the immutability of the underlying blockchain, the smart principles as follows. contractcannotbeupdatedoncedeployed.Therefore,tradi- • SECURIFY[188]extractsthesemanticinformationfromthe
tionalprogramrepairtechniquescannotbeappliedtosmart bytecode of smart contracts and then takes advantage of a contracts. This makes it challenging to fix vulnerabilities setofcomplianceandviolationsecuritypatternsthatcapture in smart contracts. Recently, several efforts have been sufficient conditions to prove the presence or absence of proposed to automatically patch vulnerabilities in smart vulnerabilities. contracts and DeFi protocols, leading to a new branch of • VERISMART [190] is an accurate verifier for ensuring smart contract security. However, a systematic review of arithmetic safety of smart contracts. Particularly, it takes existing automated repair methods for smart contracts is advantage of a domain-specific algorithm to automatically still missing. Towards this, we conduct a comprehensive discoverandexploittransactioninvariants,whichareessen- review of current automated repair approaches, expecting tial for precisely analyzing smart contracts. to provide overall insights and facilitate future work. • VERISOL [191] is a highly automated formal verifier that Inwhatfollows,wewillintroducetheexistingbugdetection checks the semantic compliance of smart contracts against and automated repair techniques for smart contracts and DeFi a state machine model with an access control policy. protocols, respectively. • ZEUS [192] employs abstract interpretation and symbolic model checking to ascertain verification conditions, and A. Vulnerability Detection verifiesthecorrectnessofsmartcontractsduringtheformal verification process. Inthissubsection,weinvestigate42well-knownapproaches Symbolic Execution. Symbolic execution methods ana- that are able to detect smart contract vulnerabilities and DeFi lyzesoftwareprogramsusingsymbolicvaluesasinputsrather attacks,whicharelistedinTableII.Morespecifically,wefirst than specific values during execution [234]. Once a program demonstrate the principles of the smart contract vulnerability branchisreached,theanalyzercollectsthecorrespondingpath detection tools, organized by the specific analysis techniques constraints following a constraint solver to obtain specific on which they are mainly based on. Furthermore, we sum- values that can trigger each branch. Notably, symbolic exe- marize the vulnerability types supported by the smart contract cution is capable of exploring multiple paths simultaneously. vulnerabilitydetectiontoolsandlisttheminTableIII.Finally, However, it also faces unavoidable problems such as path we elaborate on the design of existing DeFi attack hunting explosion.Inmostcases,thesymbolicexecutorfirstconstructs approaches as well as their workflow, hoping to push forward a control flow graph (CFG) from the Bytecode. It then the boundaries of this research direction. designs appropriate constraints based on the characteristics of 1) Static Analysis: Static analysis refers to the technique the vulnerabilities. Finally, the executor uses the constraint of analyzing programs without actually executing them. It solver to analyze the control flow graph and generate the examinescodeintheabsenceofrealinputdataandiscapable bug report. We present well-known symbolic execution-based of detecting potential security violations, runtime errors, and vulnerabilitydetectionmethodsforsmartcontractsasfollows. logical inconsistencies. Static analysis techniques have been widelyappliedtosmartcontractvulnerabilitydetection,which • DEFECTCHECKER [193] is a symbolic execution-based can be broadly divided into two categories, i.e., formal ver- bugcheckerthatanalyzesthesmartBytecodetogeneratethe ification [228] and symbolic execution [229]. In particular, CFG,stackevent,andthreecodefeatures(i.e.,MoneyCall, whenperformingstaticanalysisonsmartcontracts,researchers Loop Block, and Payable Function), and combines them to often utilize intermediate representation-based analysis meth- detect vulnerabilities. ods [230], which can store and preserve the rich semantics of • HONEYBADGER [194]isbuiltonataxonomyofhoneypot the Source Code. techniques. It adopts symbolic execution and well-defined a) Formal Verification: Formal verification eliminates heuristics to pinpoint various types of honeypots in smart the ambiguity and incompatibility in a smart contract by contracts. transforming its concepts, judgments, and logic into a formal • MAIAN [195]keepstrackofcontractsthatcanself-destruct model [231]. It cooperates with rigorous proofs to verify ordrainEtherfromarbitraryaddresses,orthosethataccept the correctness and security of functions in smart contracts. Ether but have no payout functionality. It performs inter- Common formal verification methods include model check- procedural symbolic analysis and uses a concrete validator ing[232]anddeductiveverification[233].Specifically,model to expose vulnerabilities. checking enumerates all possible states of a smart contract • MANTICORE [196] is a dynamic symbolic execution11 TABLEII OVERVIEWOFSTATE-OF-THE-ARTMETHODSFORDETECTINGVULNERABILITIESANDATTACKSTARGETINGSMARTCONTRACTSANDDEFIPROTOCOLS. # Tool Type AnalysisLevel PublicAvailable Reference 1 SECURIFY Bytecode https://github.com/eth-sri/securify2 [188],[189] 2 VERISMART SourceCode https://github.com/kupl/VeriSmart-public [190] FormalVerification 3 VERISOL SourceCode https://github.com/microsoft/verisol [191] 4 ZEUS SourceCode NotAvailable [192] 5 DEFECTCHECKER Bytecode https://github.com/Jiachi-Chen/DefectChecker [193] 6 HONEYBADGER Bytecode https://github.com/christoftorres/HoneyBadger [194] 7 MAIAN Bytecode https://github.com/MAIAN-tool/MAIAN [195]
8 MANTICORE Bytecode https://github.com/trailofbits/manticore [196] 9 MYTHRIL Bytecode https://github.com/ConsenSys/mythril [197] SymbolicExecution 10 OYENTE Bytecode https://github.com/melonproject/oyente [198] 11 OSIRIS Bytecode https://github.com/christoftorres/Osiris [199] 12 SEREUM Bytecode https://github.com/uni-due-syssec/eth-reentrancy-attack-patterns [200] 13 TEETHER Bytecode https://github.com/nescio007/teether [201] 14 VERX SourceCode https://github.com/eth-sri/verx-benchmarks [202] 15 ETHIR Bytecode https://github.com/costa-group/ethIR [203] 16 SMARTCHECK SourceCode https://github.com/smartdec/smartcheck [204] IntermediateRepresentation 17 SLITHER SourceCode https://github.com/crytic/slither [50] 18 VANDAL Bytecode https://github.com/usyd-blockchain/vandal [205] 19 CONTRACTFUZZER Bytecode https://github.com/gongbell/ContractFuzzer [51] 20 CONTRAMASTER SourceCode https://github.com/ntu-SRSLab/vultron [206],[207] 21 REGURAD SourceCode NotAvailable [208] 22 ILF SourceCode https://github.com/eth-sri/ilf [209] 23 HARVEY SourceCode NotAvailable [47],[210] 24 CONFUZZIUS Bytecode https://github.com/christoftorres/ConFuzzius [211] FuzzingTest 25 SFUZZ Bytecode https://github.com/duytai/sFuzz [212] 26 XFUZZ SourceCode https://github.com/ToolmanInside/xfuzz_tool [213] 27 SMARTIAN Bytecode https://github.com/SoftSec-KAIST/Smartian [214] 28 RLF SourceCode https://github.com/Demonhero0/rlf [215] 29 IR-FUZZ SourceCode https://github.com/Messi-Q/IR-Fuzz [216] 30 ITYFUZZ SourceCode https://github.com/fuzzland/ityfuzz [217] 31 SAFERSC Bytecode https://github.com/wesleyjtann/Safe-SmartContracts [218] 32 RECHECKER SourceCode https://github.com/Messi-Q/ReChecker [219] 33 CONTRACTWARD Bytecode NotAvailable [220] 34 S-GRAM SourceCode https://github.com/njaliu/sgram-artifact [221] DeepLearning 35 TMP SourceCode https://github.com/Messi-Q/GNNSCVulDetector [9],[222] 36 DEESCVHUNTER SourceCode NotAvailable [223] 37 CODENET SourceCode NotAvailable [224] 38 DL-MDF SourceCode NotAvailable [225] 39 BLOCKEYE DeFiprotocol NotAvailable [53] 40 DEFIRANGER DeFiprotocol NotAvailable [55] DeFiAttackHunting 41 FLASHOT DeFiprotocol NotAvailable [52] 42 PROMUTATOR DeFiprotocol https://github.com/csienslab/ProMutator [30] framework for analyzing bytecode of smart contracts, pro- exploit for a contract given only its bytecode. vidinganeffectivewaytomaximizecodecoverageandfind • VERX [202] is a automated verifier prove functional spec- execution paths that lead to vulnerabilities and reachable ifications of smart contracts. It incorporates the delayed self-destruct operations. predicate abstraction approach, which combines symbolic • MYTHRIL [197], developed by ConsenSys [235], relies on execution during transaction execution with abstraction at concolic analysis, taint analysis, and control flow checking transaction boundaries, facilitating the automatic verifica- of the bytecode to prune the search space and expose tion of the security properties of smart contracts. vulnerabilities in smart contracts. Intermediate Representation. As the logic of smart • OYENTE[198]isoneofthepioneersmartcontractanalysis Source Code becomes more complex, it becomes increasingly tools. It uses symbolic execution to identify smart contract difficult to deal with the source code directly [236]. A family vulnerabilities based on the control flow graph. OYENTE of works, instead, can deal with pure bytecode [237], [238]. is also used as a basis for several other tools, such as However, they still suffer from low accuracy due to the HONEYBADGER, MAIAN, and OSIRIS. inherent difficulty of interpreting bytecode and restoring com- • OSIRIS [199] extends OYENTE and supports to detect the prehensive data and control flow dependencies in the missing integer overflow vulnerability of smart contracts. source code. To facilitate the analysis of smart contracts, • SEREUM [200] employs dynamic taint tracking to monitor researchers probe to convert the source code or bytecode thedataflowduringthecontractexecution,avoidingincon- of a smart contract into an abstract code structure that is sistent states and effectively preventing reentrancy attacks. conduciveforfurtherprocessing,referredtoasanintermediate • TEETHER [201]searchesforvulnerableexecutiontracesin representation (IR), and then analyze the IR to discover acontract’scontrolflowgraphandautomaticallycreatesan securityproblems.Anintermediaterepresentationofthesmart12 TABLEIII ASUMMARYOFBUGTYPESSUPPORTEDBYEACHTOOL.FOREACHTYPE:ACISSHOTFORACCESSCONTROL;AFIMPLIESASSERTIONFAILURE;BD INDICATESBLOCKDEPENDENCY(BLOCK.TIMESTAMP,BLOCK.NUMBER,BLOCK.BLOCKHASH,ETC);DSREFERSTODENIALOFSERVICE;DDDENOTES DANGEROUSDELEGATECALL;FEREPRESENTSFREEZINGETHER;GSMEANSGASLESSSEND;LEISLEAKINGETHER;RESTANDSFORREENTRANCY; IODENOTESINTEGEROVER-/UNDER-FLOW;SCIMPLIESSUICIDALCONTRACT;SAREFERSTOSHORTADDRESSES;TOISTRANSACTIONORDER DEPENDENCY;TXMEANSTRANSACTIONORIGINUSE;UCINDICATESUNCHECKEDLOW-LEVELCALL;UEISUNHANDLEDEXCEPTION.FORMORE DETAILSOFVARIOUSSMARTCONTRACTVULNERABILITIES,WEREFERINTERESTEDREADERSTO[66],[226],[227]. Vulnerability Type Tool AC AF BD DS DD FE GS LE RE IO SC SA TO TX UC UE CODENET [224] ✗ ✗ ✓ ✗ ✗ ✗ ✗ ✗ ✓ ✗ ✗ ✗ ✗ ✓ ✓ ✗ CONFUZZIUS [211] ✗ ✓ ✓ ✗ ✓ ✓ ✗ ✓ ✓ ✓ ✓ ✗ ✓ ✗ ✗ ✓ CONTRACTFUZZER [51] ✓ ✗ ✓ ✗ ✓ ✓ ✓ ✗ ✓ ✗ ✗ ✗ ✗ ✗ ✗ ✓
CONTRAMASTER [206],[207] ✗ ✗ ✗ ✗ ✗ ✗ ✓ ✗ ✓ ✓ ✗ ✗ ✗ ✗ ✗ ✓ CONTRACTWARD [220] ✗ ✗ ✓ ✗ ✗ ✗ ✗ ✗ ✓ ✓ ✗ ✗ ✓ ✗ ✗ ✗ DEESCVHUNTER [223] ✗ ✗ ✓ ✗ ✗ ✗ ✗ ✗ ✓ ✗ ✗ ✗ ✗ ✗ ✗ ✗ DEFECTCHECKER [193] ✗ ✗ ✓ ✓ ✗ ✓ ✗ ✓ ✓ ✗ ✗ ✗ ✓ ✗ ✓ ✗ DL-MDF [225] ✗ ✗ ✓ ✗ ✗ ✓ ✗ ✗ ✓ ✓ ✗ ✗ ✗ ✗ ✗ ✗ ETHIR [203] ✓ ✓ ✓ ✗ ✓ ✗ ✗ ✗ ✓ ✗ ✗ ✗ ✓ ✗ ✗ ✗ HARVEY [47],[210] ✗ ✓ ✗ ✗ ✗ ✗ ✗ ✗ ✓ ✓ ✗ ✗ ✗ ✗ ✓ ✓ HONEYBADGER [194] ✗ ✗ ✗ ✗ ✗ ✓ ✗ ✓ ✗ ✓ ✗ ✗ ✗ ✗ ✗ ✗ ILF [209] ✓ ✗ ✓ ✗ ✓ ✓ ✗ ✓ ✓ ✗ ✓ ✗ ✗ ✗ ✗ ✓ IR-FUZZ [216] ✓ ✗ ✓ ✗ ✓ ✓ ✓ ✗ ✓ ✓ ✓ ✗ ✗ ✓ ✓ ✓ ITYFUZZ [217] ✓ ✗ ✗ ✓ ✗ ✗ ✗ ✗ ✓ ✗ ✗ ✗ ✗ ✗ ✓ ✗ MAIAN [195] ✓ ✗ ✗ ✗ ✗ ✓ ✗ ✓ ✗ ✗ ✓ ✗ ✗ ✗ ✗ ✗ MANTICORE [196] ✓ ✓ ✓ ✗ ✓ ✗ ✗ ✓ ✓ ✓ ✓ ✗ ✗ ✓ ✓ ✓ MYTHRIL [197] ✓ ✓ ✓ ✗ ✓ ✗ ✗ ✓ ✓ ✓ ✓ ✗ ✗ ✓ ✓ ✓ OYENTE [198] ✓ ✓ ✓ ✓ ✗ ✗ ✗ ✗ ✓ ✗ ✗ ✗ ✓ ✗ ✗ ✗ OSIRIS [199] ✗ ✓ ✓ ✓ ✗ ✗ ✗ ✗ ✓ ✓ ✗ ✗ ✗ ✗ ✗ ✗ RECHECKER [219] ✗ ✗ ✗ ✗ ✗ ✗ ✗ ✗ ✓ ✗ ✗ ✗ ✗ ✗ ✗ ✗ REGURAD [208] ✗ ✗ ✗ ✗ ✗ ✗ ✗ ✗ ✓ ✗ ✗ ✗ ✗ ✗ ✗ ✗ RLF [215] ✗ ✗ ✓ ✗ ✓ ✓ ✗ ✓ ✗ ✗ ✓ ✗ ✗ ✗ ✗ ✓ SAFERSC [218] ✗ ✗ ✗ ✗ ✗ ✓ ✗ ✓ ✗ ✗ ✓ ✗ ✗ ✗ ✗ ✗ SECURIFY [188],[189] ✓ ✗ ✓ ✗ ✓ ✓ ✗ ✓ ✓ ✓ ✓ ✗ ✓ ✓ ✓ ✓ SEREUM [200] ✗ ✗ ✗ ✗ ✗ ✗ ✗ ✗ ✓ ✗ ✗ ✗ ✗ ✗ ✗ ✗ S-GRAM [221] ✗ ✓ ✓ ✗ ✗ ✓ ✗ ✗ ✓ ✓ ✗ ✗ ✗ ✗ ✗ ✗ SFUZZ [212] ✓ ✗ ✓ ✗ ✓ ✓ ✓ ✗ ✓ ✓ ✗ ✗ ✗ ✗ ✗ ✓ SMARTCHECK [204] ✓ ✗ ✓ ✓ ✗ ✓ ✗ ✗ ✓ ✓ ✗ ✗ ✗ ✓ ✗ ✓ SMARTIAN [214] ✗ ✓ ✓ ✗ ✓ ✓ ✗ ✓ ✓ ✓ ✓ ✗ ✗ ✓ ✓ ✓ SLITHER [50] ✓ ✗ ✓ ✓ ✓ ✓ ✗ ✓ ✓ ✗ ✓ ✗ ✗ ✓ ✓ ✓ TEETHER [201] ✗ ✗ ✗ ✗ ✓ ✗ ✗ ✓ ✗ ✗ ✓ ✗ ✗ ✗ ✗ ✗ TMP [9],[222] ✗ ✗ ✓ ✗ ✗ ✗ ✗ ✗ ✓ ✗ ✗ ✗ ✗ ✗ ✗ ✗ VANDAL [205] ✗ ✗ ✗ ✗ ✗ ✗ ✗ ✓ ✓ ✗ ✓ ✗ ✗ ✓ ✓ ✓ VERISMART [190] ✗ ✗ ✗ ✗ ✗ ✗ ✗ ✓ ✗ ✓ ✗ ✗ ✗ ✗ ✗ ✗ VERISOL [191] ✗ ✓ ✗ ✗ ✗ ✗ ✗ ✗ ✗ ✗ ✗ ✗ ✗ ✗ ✗ ✗ VERX [202] ✓ ✓ ✗ ✗ ✗ ✗ ✗ ✗ ✗ ✓ ✗ ✗ ✗ ✗ ✗ ✗ XFUZZ [213] ✗ ✗ ✓ ✗ ✓ ✗ ✗ ✗ ✓ ✗ ✗ ✗ ✗ ✓ ✗ ✗ ZEUS [192] ✗ ✗ ✓ ✗ ✗ ✗ ✗ ✗ ✓ ✓ ✗ ✗ ✓ ✓ ✓ ✓ contract is an arbitrary representation of a program between • SMARTCHECK [204] is an extensible static analysis tool the source code and the bytecode [50], [230], [239]–[241]. for smart contracts, which converts the source code of a Since the intermediate representation abandons the complex smart contract into an XML-based intermediate represen- logicinthesourcecodewhilepreservingrichdataandcontrol tation. It uses the lexical and syntactic analysis of the flow semantics, it can be favorable to further processing Solidity source code, looking for vulnerability patterns and and analysis. We conclude intermediate representation-based bad coding practices. analysis techniques for smart contracts as follows. • SLITHER [50] converts the smart Source Code into an intermediate representation of SlithIR. SlithIR uses a static • ETHIR [203] converts the control flow graph of smart single allocation (SSA) form and a reduced instruction set contracts into the rule-based intermediate representation to simplify the contract analysis process while preserving (RBP), and then infers the security properties of smart the semantic information of the source code. contracts based on the RBP.13 • VANDAL [205] is composed of an analysis pipeline and fuzzer to generate vulnerable transaction sequences. a decompiler. The decompiler performs an abstract in- • IR-FUZZ [216] extends sFuzz, which engages in a se- terpretation to convert the bytecode into an intermediate quencegenerationstrategythatcontainsinvocationordering representationintheformoflogicalrelations,andthenuses andprolongationtotriggerdeeperstatesinasmartcontract. novellogic-drivenmethodstodetectvulnerabilitiesinsmart • ITYFUZZ [217] is a snapshot-based fuzzer for testing contracts. smart contracts, which incorporates new waypoint mech- 2) Fuzzing Test: Fuzzing has proven to be a success- anisms optimized to prioritize the exploration of interesting ful technique for discovering software bugs over the past snapshot states, allowing for efficient program exploitation. decades [242]. A wide variety of fuzzing methods have In particular, ITYFUZZ is able to analyze complex DeFi emerged, such as whitebox, blackbox, and greybox [243]– protocols and identify the price manipulation vulnerability. [245]. The main idea of fuzzing techniques is to feed a mass 3) Deep Learning-based Methods: In recent years, there of test inputs (i.e., test cases) into the program under test and has been a growing practice of detecting program security expose vulnerabilities by monitoring the reported abnormal vulnerabilities using deep learning technologies [246], [247]. results or exceptions [51]. When applied to smart contracts, a The advancement of deep learning has promoted the emer- fuzzingenginefirstattemptstogenerateinitialseedsandform gence of various vulnerability detection methods [248], [249]. executable transactions. With the assistance of the feedback Existing deep learning-based methods usually convert smart of test results, it will dynamically adjust the generated test contractsintointermediaterepresentationsandthenconstructa cases to explore as much contract state space as possible. deep neural network as the detection model. As deep learning This process is repeated until a stopping criterion is satisfied. technology has demonstrated its superiority in handling so- Finally, the fuzzer will analyze the results generated during phisticateddata,itcanalsobeappliedtodealwiththecomplex fuzzing and report to users. We review current smart contract business logic of DeFi protocols. We provide existing deep
fuzzing methods and summarize their principles as follows. learning-based smart contract vulnerability detection methods • CONTRACTFUZZER [51] is one of the earliest fuzzing as follows, hoping to inspire others. frameworks for smart contracts, which identifies vulnera- • SAFERSC [218]isthefirstdeeplearning-basedvulnerabil- bilities by monitoring runtime behavior during a fuzzing ity detection model for smart contracts, which analyzes the campaign. operation code (i.e., opcode) of smart contracts and trains a • CONTRAMASTER [206] is an oracle-supported dynamic long short-term memory network (LSTM) as the detection exploit generation framework for detecting vulnerabilities model. in smart contracts. It combines the analysis of data-flows, • RECHECKER [219]constructsthebidirectionallongshort- control-flows, and contract state information to guide seed term memory network based on an attention mechanism to mutation. precisely detect the reentrancy vulnerability. • REGUARD [208] is a fuzzing-based analyzer to automat- • CONTRACTWARD [220] extracts bigram features from the ically detect reentrancy vulnerabilities in Ethereum smart smart contract opcode and adopts a variety of machine contracts. It dynamically identifies reentrancy bugs by iter- learning algorithms to detect bugs in smart contracts. atively generating random but diverse transactions. • S-GRAM [221] introduces a novel semantic-aware security • ILF[209]proposesanewapproachforlearninganeffective auditing technique for analyzing smart contracts. The key yet fast fuzzer from symbolic execution by phrasing the insightbehindS-gramisacombinationofN-gramlanguage learning task in the framework of imitation learning. modeling and lightweight static contract analysis. • HARVEY [210] extends standard greybox fuzzing for pre- • TMP[222]proposestocastthesourcecodeofasmartcon- dicting new test inputs that are more likely to cover new tract into a contract graph and builds a temporal-message- paths or reveal vulnerabilities in smart contracts. propagation graph model to identify vulnerabilities. • CONFUZZIUS [211] is a hybrid fuzzer for smart contracts • DEESCVHUNTER [223] uses a modularized and system- thatusesevolutionaryfuzzingtoexerciseshallowpartsofa aticdeeplearning-basedframeworktodetectvulnerabilities smartcontract.Specifically,itemploysconstraintsolvingto in smart contracts. It employs the proposed vulnerability generate test cases, enforcing the fuzzer to reach complex candidate slice (VCS) to guide the model to capture the and deep branches. critical part of the vulnerability. • SFUZZ [212] presents an efficient and lightweight multi- • CODENET [224] is a code-targeted convolutional neural objective adaptive strategy to dig out potential vulnerabili- network (CNN) architecture that detects vulnerable smart ties hidden in the hard-to-cover branches. contracts while preserving their semantics and context. • XFUZZ [213] is a machine learning-guided smart contract • DL-MDF [225] identifies smart contract vulnerabilities fuzzing framework that uses machine learning predictions based on deep learning and multimodal decision fusion. to guide fuzzers for vulnerability detection. Specifically, it extracts the features of the source code, • SMARTIAN [214] employs a novel feedback mechanism, operationcode,andcontrolflowofasmartcontractthrough i.e., data-flow-based feedback, to guide the greybox fuzzer multiple models respectively, and then adopts a multimodal to systematically generate critical transaction sequences. decision fusion strategy to output the detection results. • RLF [215] introduces a reinforcement learning-guided 4) DeFi Attack Hunting: Generally speaking, detecting fuzzing framework for smart contracts, which drives the DeFi attacks requires the ability to recover and understand14 the logical semantics of DeFi protocols, which is typically missing in the aforementioned solutions that find bugs only in traditional smart contracts. Current DeFi attack hunting methods[30],[53],[55]considersimulatingtheattackprocess to detect potential DeFi attack behaviors. Technically, they monitor the contract transactions during the attack simulation and reveal DeFi attacks using the patterns with the recovered high-level semantics of DeFi protocols. In what follows, we will elaborate on the specific design and workflow of existing DeFi attack hunting tools. Phase1:OracleAnalysis CFG DeFiProject AttackReport Smart DeFi VulnerableDeFi Smart Contract Protocol Contract Phase2:AttackMonitoring sisylanAcilobmyS Attack DEFIRANGER Pattern Data CFT Semantic Attack Collection Construction Lifting Detection Raw CashFlow DeFi Transactions Tree Semantics Ethereum Attack Report Analysis Fig.9. ThegeneralworkflowofDEFIRANGER. OracleDependency ones. After that, DEFIRANGER detects price manipulation attacks using the patterns expressed with recovered DeFi se- mantics.Theworkflowof DEFIRANGER isdepictedinFig.9. DEFIRANGER initially collects raw Ethereum transactions, and then constructs the cash flow tree that is used to convert raw transactions to token transfers. Then, DEFIRANGER uses aliftingalgorithmtorecovertheDeFisemanticsfromtheCFT. Finally, DEFIRANGER detects price manipulation attacks by matching recovered semantics with attack patterns or rules. Transaction 0 Analysis Monitor Engine Feature 1 Pre-defined Extraction … Heuristics RawTransaction ModifiedEVM Transaction End-to-End Collection k Analysis Normal Normal Detection Execution Trace Rules Fig.8. TheoverallworkflowofBLOCKEYE,whichconsistsoforacleanalysis andattackmonitoring. Decoding Mutation Mutation Analysis Traces a) BLOCKEYE: BLOCKEYE [53]isareal-timeattack detection system for DeFi protocols. It models interdependen-
cies between DeFi protocols and flags potential DeFi attacks Contract Mutation Report with an end-to-end analysis in real-time. The key insights ABI Rules behind BLOCKEYE are symbolic oracle analysis and pattern- based runtime transaction validation. To illustrate the overall Fig.10. Thehigh-levelworkflowofPROMUTATOR. insights of BLOCKEYE, we further describe its workflow in Fig. 8, where BLOCKEYE works in two phases. In the c) PROMUTATOR: PROMUTATOR [30] is a scalable first phase, BLOCKEYE performs symbolic analysis on smart security analysis framework that can detect price oracle vul- contracts of a given DeFi protocol. Specifically, the goal of nerabilities in DeFi protocols. PROMUTATOR simulates price this phase is to model the inter-DeFi oracle dependency, i.e., oracle attacks on a DeFi protocol locally and observes how a how the oracle data provided by one DeFi protocol affects price oracle handles abnormal price data feeds. Fig. 10 shows the services of another. Once oracle-dependent state updates the high-level workflow of PROMUTATOR, which processes are found, BLOCKEYE identifies the DeFi protocols as po- eachtransactionthroughthreephases:decoding,mutation,and tentially vulnerable. In the second phase, BLOCKEYE installs analysis. PROMUTATOR detects the price oracle bug by using a runtime monitor for vulnerable DeFi protocols to detect built-in mutation and detection rules, which can be extended external attacks. Specifically, BLOCKEYE employs a transac- to cover other types of vulnerabilities using custom mutation tion monitor to collect related transactions based on extracted and detection rules. PROMUTATOR outputs whether a target characteristics. Then, the end-to-end analysis of transactions DeFi protocol is vulnerable based on the detection rules and is performed according to predefined heuristics, e.g., a large the analysis of mutated traces. profit is made in a short period. Potential attacks are flagged d) FLASHOT: FLASHOT [52] is a framework that is by BLOCKEYE if an abnormal sequence of transactions is able to reveal the microscopic process of the flash loan attack detected. Finally, BLOCKEYE generates an analysis report for in a clear and precise way. Specifically, FLASHOT is designed attack verification. to illustrate the precise asset flows intertwined with smart b) DEFIRANGER: DEFIRANGER [55] is designed to contracts in a standardized diagram. In addition, FLASHOT detect price manipulation attacks on DeFi protocols. Specifi- performs an in-depth analysis of a typical flash loan attack cally, DEFIRANGER restoresthehigh-levelsemanticsofDeFi (e.g., pump and arbitrage), with a more accurate model and protocols by constructing the cash flow tree (CFT) from solution regarding the optimization problem, as well as some transactions and lifting the low-level semantics to high-level economic explanations for the attacker’s malicious behavior.15 TABLEIV OVERVIEWOFSTATE-OF-THE-ARTTOOLSFORREPAIRINGVULNERABILITIESINSMARTCONTRACTSANDDEFIPROTOCOLS. VULNERABILITYNUMBERREPRESENTSTHATTHENUMBEROFVULNERABILITYTYPESCANBEREPAIREDBYEACHTOOL. Tool Analysis Level Vulnerability Number Public Available Reference SCREPAIR SourceCode 4 https://github.com/xiaoly8/SCRepair [250] SMARTSHIELD Bytecode 3 NotAvailable [251] SGUARD SourceCode 4 https://github.com/duytai/sGuard [252] EVMPATCH Bytecode 2 https://github.com/uni-due-syssec/evmpatch-developer-study [253] AROC SourceCode 4 NotAvailable [254] HCC SourceCode 2 NotAvailable [255] ELYSIUM Bytecode 7 https://github.com/christoftorres/Elysium [256] DEFINERY1 SourceCode 4 https://sites.google.com/view/ase2022-definery [257] 1DEFINERY isbuilton SCREPAIR. DEFINERY enablesproperty-basedautomatedrepairofsmartcontractswhileprovidingformalcorrectness guarantees. contract to capture its bytecode-level semantic information; Summary: 2) generating the patches to repair the insecure control flows (1) Most state-of-the-art vulnerability detection ap- and data operations based on the semantic information; 3) proaches are tailored for traditional smart contracts outputting the patched bytecode and a bug repair report. or a single contract. DeFi protocols present unique c) SGUARD: [252] propose an automatic fixing ap- challengesforanalysiscomparedtothoseintraditional proachthatcantransformsmartcontractstobefreeof4kinds smart contracts due to the composability of DeFi of vulnerabilities. Given a smart contract, SGUARD works in applications.SinceDeFiprotocolsarebuiltonmultiple twophases:1)collectsafinitesetofsymbolicexecutiontraces interactive smart contracts, it is difficult for them to of the smart contract and then performs static analysis on detect DeFi attacks and vulnerabilities. the collected traces to identify potential vulnerabilities, and (2) Existing DeFi attack hunting techniques are still 2) applies specific fixing patterns for each type of bug at the in their infancy, leaving a large room for improve- source code level. Unfortunately, SGUARD performs source ment. So it is necessary to design scalable tools for code rewriting without further analysis of the interactions identifyingvariousattacksandvulnerabilitiesonDeFi between different functions and the global dependencies of protocols. memoryvariables.Thelackofsuchanalysisinsmartcontract patchingtypicallyresultsinthedestructionofthefunctionality of the original contract. B. Automated Repair d) EVMPATCH: [253] present an automated repair In this subsection, we review 8 existing automated repair framework, called EVMPATCH, to patch faulty smart con-
tools for smart contracts and DeFi protocols, which are listed tracts. EVMPATCH works in two main steps. In the first step, inTableIV.Inparticular,wesummarizetheprinciplesofeach based on designed patch rules, EVMPATCH uses a bytecode automated repair tool, and then present their advantages and rewriting engine to fix a basic block that has a vulnerability disadvantages. and appends the fixed block to the end of the contract. In a) SCREPAIR: [250] propose an automated smart con- the second step, after fixing a contract, EVMPATCH replays tract repair tool SCREPAIR using a genetic programming someofthehistoricaltransactionsoftheoriginalcontractona searchmethod. SCREPAIR performsparallelgeneticrepairby localEthereumclienttoverifythatthefixedcontractiscorrect partitioning the large search space of candidate patches into by observing whether attack transactions are blocked and smallermutuallyexclusivesearchspacesthatcanbeprocessed whether other transactions are normal. However, EVMPATCH individually. Considering the gas consumption of patches, only works when the vulnerability is located within a single SCREPAIRintegratesagas-awarenesstechniquethatcompares bytecode basic block, while having difficulties in handling candidate patches in terms of gas cost, thus screening out the vulnerabilities across separated basic blocks. patchesthatareusefulandlowergascost.Notably,SCREPAIR e) AROC: [254]proposeasmartcontractrepairernamed suffers from the inherent problems: 1) the generated patches AROC thatcanautomaticallyfixvulnerableon-chaincontracts are incomplete, which can sometimes lead to ineffectiveness, without updating the contract code. AROC consists of three 2) the selected patches may break the functionality of the maincomponents:1)aninformationextractionmodule,which original contract, and 3) it is unable to repair the off-chain captures the variable dependencies, path constraints, and con- contracts. tract metadata to synthesize patches given vulnerable contract b) SMARTSHIELD: [251] develop a bytecode rec- source code and bug types; 2) a patch generation module, tification system SMARTSHIELD to automatically fix three which produces patches according to the repair templates; 3) types of bugs in smart contracts. The overall workflow of an enhanced EVM, which binds the generated patches to fix SMARTSHIELD consists of three steps: 1) extracting the the vulnerable contract and block the malicious transactions. abstractsyntaxtree(AST)andtheunfixedbytecodeofasmart However, AROC only works on its own enhanced EVM, and16 TaintAnalysis BugReport Osiris Oyente Mythril Original Provided? Patched Contract No Report ① Bug ② Context ③ Patch ④Bytecode Localization Inference Generation Rewriting Yes CFGBuilder Template BugReport Patching Report Fig.11. TheoverallworkflowandarchitectureofELYSIUM. the binding features cannot yet be accepted by the official Summary: Ethereum. (1)Currentautomatedsmartcontractrepairtechniques only address limited types of vulnerabilities and are difficult to deal with complex smart contracts, such as f) HCC: [255]developasmartcontractcompilercalled DeFi protocols. HCCthatcaninsertsecurityhardeningchecksintothecontract (2) There is still a lack of effective verifiers to prove sourcecodeautomatically.HCCdesignsacodepropertygraph the correctness of patches and to validate whether (CPG)tomodelthecontrolanddataflowsofthecontractand the intended functionality of the patched contract is find potential bugs. HCC then mitigates the discovered bugs equivalent to the original contract. by inserting hardening patches. Hardening patches in HCC are expressed as graph patterns that are used as templates for CPG-level patches against bugs. However, HCC has difficulty C. Other Pioneering Work for DeFi Security repairing vulnerabilities in complex DeFi protocols because it There is a growing body of literature taking care of DeFi is unable to recover complete CPGs from intertwined DeFi securityfromotherdimensions.Forexample,[27]explorehow protocols. tosolveweaknessesinDeFiprotocolsthatcouldleadtoaDeFi securityproblem.[258]provideanoverviewoftheblockchain front-running attacks. [82] study the front-running attacks in g) ELYSIUM: [256] propose ELYSIUM, a scalable tool decentralized exchanges and propose the concept of Miner towards automated repair for smart contracts at the bytecode Extractable Value (MEV), that is, miners can extract finan- level.TheoverallworkflowofthistoolisillustratedinFig.11, cial income by manipulating transaction orders. [18] present which consists of four phases: 1) bug location, which is a framework called DEFIPOSER, which can automatically responsible for detecting and localizing bugs in the bytecode; create revenue-generating transactions given the blockchain 2) context inference, which extracts the control flow graph of state. [37] develop a formal process-algebraic technique that thebytecodeandinfersthecontextinformationoftheCFG;3) models DeFi protocols in a compositional manner to enable patch generation, which produces patches by inserting previ- efficient verification of security properties. [259] introduce a ously inferred context information into given patch templates; formal verification framework called Clockwork Finance for 4)bytecoderewriting,whichinjectsthegeneratedpatchesinto mechanized reasoning about the economic security proper- the CFG and transforms it back into bytecode. ties of composed DeFi protocols. [28] study the flash loan attacks and propose an optimization approach to maximize the profit of DeFi attacks. [89] analyze sandwich attacks in h) DEFINERY: [257] design an approach that enables decentralized exchanges. [79] quantify the extracted MEV
property-based automated repair of DeFi protocols while pro- on the Ethereum, including fixed spread liquidations, and viding formal correctness guarantees. DEFINERY is the first present a generalized front-running algorithm, i.e., transaction attempt to repair functional specification violations in DeFi replay. They also measure various risks faced by liquidation smart contracts. DEFINERY consists of two main modules: 1) participants and quantify the instabilities of existing lending a semantic analysis part, which symbolically executes a smart protocols [81]. [112], formalizing a model for undercollater- contractwithrespecttoapropertyandasequenceoffunctions alized DeFi lending platforms to assess the risks of leverage- that lead to its violation; 2) a patch generation part, which engaging borrowers. providesapatchedversionofasmartcontractthatsatisfiesthe a) DeFi Risk Rating Tools: Providing a credible risk property. Notably, the patch generation module of DEFINERY assessmentisconducivefordevelopersorinvestorstofindpo- is built on SCREPAIR. DEFINERY extends a set of statements tentialrisksinaDeFiprotocoltimely[260].Notonlydoesthis thataredefinedinSCREPAIR,combinesthesemanticanalysis help the crypto participants make more intelligent decisions, module to perform the patch, and adds heuristics to select but it also incentivizes DeFi protocols to boost their overall changes that are likely to repair the problem. security and trustworthiness. Explicitly, developers offering17 a risk rating tool hope that the sharing of tools, standards, TABLEV and development patterns will support the safe growth of the STATISTICALANALYSISOFTHEDEFIPROTOCOLDATASET.CATEGORY REPRESENTSTHECLASSIFICATIONOFDEFIFINANCIALSERVICES.FL DeFi ecosystem, making DeFi more secure for current and INDICATESTHEFLASHLOANATTACK;DTREFERSTODEFLATIONTOKEN futureadopters.Here,weexaminetwoprominentratingtools, ATTACK;SWDENOTESDEFISANDWICHATTACK;RPMEANSRUGPULL i.e., DEFI-SCORE and DEFI-SAFETY. DEFI-SCORE [261] ATTACK;OTHERATTACKDESIGNATESUNCOMMONTYPESOFATTACKS; NORMALMEANSADEFIPROTOCOLTHATHASNOREPORTEDATTACK. is a framework for assessing risk in permissionless lending platforms. It is a comparable value for measuring the risk Category FL DT SW RP OtherAttack Normal Total of DeFi protocols, based on factors such as smart contract LendingandBorrowing 9 2 3 – 1 3 18 DecentralizedExchange 12 1 3 2 3 19 40 risk,collateralization,andliquidity.DEFI-SAFETY[262]isan PortfolioManagement 3 – 1 – 1 2 7 independent rating organization that evaluates DeFi protocols Derivative 6 – 2 1 5 11 25 to produce an overall safety score based on transparency and Aggregator 1 1 – – 1 3 6 adherence to best practices. Other – – – – – 3 3 Total 31 4 9 3 11 41 99 Summary: (1)ImprovingthesecurityofDeFiprotocolsisbecom- annotations facilitate the evaluation of DeFi protocol analysis ing one of the most critical and urgent tasks for Web tools extensively. 3.0. Current researchers have proposed various solu- 1) Dataset Collection and Processing: We create the tions for the security of DeFi protocols, such as smart dataset by collecting DeFi protocols from three different contract security audits, risk assessment mechanisms, sources: (i) Ethereum official platform (more than 98%), (ii) transaction replay verification, and so on. GitHub repositories, and (iii) blog posts that analyze DeFi (2) DeFi provides tremendous potential for innovation protocols. Note that all the DeFi protocols are collected from and growth in the financial world. Nevertheless, this trusted entities in the field. We also ensure the traceability of potential comes with significant risks and challenges each DeFi protocol by providing the address or URL, from that must be addressed to ensure the long-term devel- which they are extracted as much as possible. opment of the DeFi ecosystem. In particular, we construct the dataset from different do- mains of DeFi financial services, including lending and borrowing, decentralized exchange, portfolio management, V. PERFORMANCEEVALUATION derivative, and aggregator, which are the common types of In this section, we aim to evaluate the performance of DeFi applications. Moreover, we label the dataset by inspect- existing bug detection tools in handling DeFi protocols. We ing the smart source code and historical transactions of each seek to answer the following questions. DeFi protocol. • RQ1: How do traditional smart contract vulnerability de- 2) Dataset Statistic and Analysis: We collected 99 open- tection tools perform when applied to DeFi protocols? sourceDeFiprotocolsintothedataset,whichconsistsofatotal • RQ2: What is the performance of state-of-the-art tools in of 7,340 smart contracts. In the dataset, 58 DeFi protocols detecting DeFi attacks or vulnerabilities? haveexperiencedatleastoneexternalattack.TableVpresents the statistics of the dataset. Specifically, 31 protocols are The following parts of this section present the setup and affected by a flash loan attack, of which pump and arbitrage, procedure of our experimental evaluations. First, we construct price manipulation, and reentrancy account for 26%, 58%, a benchmark dataset of DeFi protocols and select candidate and 16%, respectively. 4 protocols are struck by a deflation vulnerability detection tools for the experiments. Then, we token attack. Additionally, 9 protocols have suffered from present the experimental setup, including metrics that are a DeFi sandwich attack, and 3 protocols have suffered a commonly used to evaluate vulnerability detection tools and rug pull attack. There are also 11 protocols that have been
the execution environment. Next, in a unified execution envi- influenced by other uncommon types of DeFi attacks, such as ronment,eachtoolanalyzesDeFiprotocolsandgeneratesbug reports. Finally, we count the total number of bugs, manually yCredit.Finance [263], Oypn [264], Furucombo [179]. To embracetheDeFicommunity,wehavereleasedthebenchmark confirmtheauthenticityofeachbug,andcalculatethevalueof dataset at https://github.com/Messi-Q/DeFi-Protocol. relevant metrics, followed by the analysis of the experimental results. B. Experimental Setup A. Dataset Construction 1) Candidate Tools: After reviewing all of the tools in We construct and release a benchmark dataset, which con- Table II, we select the fully open-sourced tools for further sists of real-world DeFi protocols and concerns six types experiments. Specifically, for static analysis tools, we fo- of DeFi attacks, namely, flash loan (pump and arbitrage, cus on the most frequently compared tools, namely, SECU- price manipulation, reentrancy) attack, deflation token attack, RIFY, VERISOL, MAIAN, MYTHRIL, MANTICORE, OYENTE, sandwichattack,andrugpullattack.Accordingtothereported OSIRIS, TEETHER, VERX, SMARTCHECK, and SLITHER. DeFi attack incidents, we manually label the dataset, i.e., For fuzzing test methods, we choose CONTRACTFUZZER, whether a DeFi protocol suffers from an external attack CONFUZZIUS, ILF, SFUZZ, SMARTIAN, and IR-Fuzz. For or has a certain type of smart contract vulnerability. Our deep learning-based methods, RECHECKER and TMP are18 precisionvalueindicatesahigherpercentageofcorrectalarms Real Value and fewer false alarms, making bug verification and code Confusion Matrix modification easier. Positive Negative TP Precision= (2) TP +FP TP FP Positive (TruePositive)) (FalsePositive) Recall. Recall is the fraction of the total number of Predict relevant instances that are actually detected. A higher recall Value FN TN value indicates that more real vulnerabilities are found, fewer Negative (FalseNegative))(TrueNegative)) hidden vulnerabilities are missed, and lower risk of unknown attacks. TP Fig.12. Confusionmatrixthatreflectstheperformanceofinvestigatedtools. Recall= (3) TP +FN F1-score. F1-score is the harmonic average of precision selected for experiments. For DeFi security tools, we select and recall, and it is usually treated as the critical evaluation PROMUTATOR and DEFI-SCORE. indicator for some classification missions, e.g., bug detection. 2) Execution Environment: A unified execution environ- Precision·Recall ment is extremely important for evaluating different tools, F1=2· (4) Precision+Recall including the unified platform and consistency of runtime Furthermore, we follow the settings of previous parameters.Consideringthateachtoolhasanarbitrarynumber works [226], [227] and select the unique bug and execution of self-defined settings, we choose the general settings that time as metrics to measure the performance of the tools. theyallsupporttocarryoutexperiments,suchasthecompiler Unique Bug. It refers to the total number of bug types type and the data dependency analyzer. All experiments are reported by each tool after deduplication. When using the performed on the same computer equipped with an Intel Core candidate tools to analyze DeFi protocols, we count the i9CPUat3.3GHz,anNVIDIARTX2080TiGPU,and64GB number of bug types reported by each tool. RAM. We repeat each experiment three times and report the Execution Time. Execution time is also a significant indi- average results for each method. cator among all methods of evaluating vulnerability detection tools. Currently, long audit time of detection tools leads to C. Evaluation Metric low efficiency of vulnerability analysis. In order to measure To measure the performance of the vulnerability detection the time of execution, we record the latency that identifies tools, we adopt the widely used metrics, including accuracy, the time interval between the analysis starts and ends. We precision,recall,andF1-score.Weruneachtoolinthedataset. present the average execution time of each DeFi protocol in When the execution is finished, each tool generates a bug the dataset. report that contains the results of the vulnerability analysis. By matching it with the manually tagged labels of the DeFi D. Results and Analysis protocols,wecancalculatethetruepositive(TP),truenegative In this subsection, we present the experimental results of (TN), false positive (FP), and false negative (FN) values of ourempiricalstudyandtheanswerstotheresearchquestions. each tool. Fig. 12 illustrates all four possible outcomes with a First, we verify the scalability of traditional smart contract 2×2 confusion matrix. TP represents the number of data ele- bug detection tools in analyzing DeFi protocols. Then, we ments for which the detection tool correctly predicts samples evaluate all available tools in terms of accuracy, precision, withvulnerabilities.TNisthenumberofsamplesthatthetool recall, F1-score, unique bug, and execution time. Finally, we successfully detected without vulnerabilities. FP represents provide an in-depth analysis of these tools and offer possible the number of samples that were falsely detected as having improvements for future work. vulnerabilities. FN refers to the number of samples that were 1) ScalabilityEvaluation(AnswertoRQ1): First,werunall wrongly detected as protocols without vulnerabilities. Using the candidate tools on the DeFi protocol dataset to determine
these data, we further calculate the corresponding evaluation whetherthesetoolscaneffectivelyanalyzecomplexDeFipro- metrics as follows. tocols.Tobemorespecific,weevaluatethescalabilityofeach Accuracy. Accuracy is one of the most common metrics tool by testing it on both DeFi protocols and smart contracts used to evaluate the pros and cons of the bug detection tools. written in different Solidity versions. Table VI shows the ex- Generally,itcanobjectivelyreflectthemostdirectramification perimentalresults.Accordingtotheprinciplebehindeachtool, of a detection tool. Bug detection is essentially a binary we refer to tools 1 to 19 as traditional bug detection methods, classificationproblem,thatis,thetoolpredictswhetheraDeFi whiletools20to21areconsideredasDeFianalysismethods. protocol endures an external attack or has a certain type of We can observe that: 1) most of the traditional vulnerability smart contract vulnerability. detection methods for smart contracts only support detecting TP +TN low-version (i.e., solc-0.4.x) smart contracts, while only Accuracy= (1) TP +FP +FN+TN four of them are able to analyze DeFi protocols and generate Precision. Precisionisdefinedastheratiooftruepositives detection results (i.e., TEETHER, SMARTCHECK, SLITHER, andthetotalnumberofpositivespredictedbyatool.Agreater and RECHECKER), and 2) the DeFi analysis methods such as19 TABLEVI TABLEVIII SCALABILITYEVALUATIONOFEACHTOOLINANALYZINGDEFI AVERAGEEXECUTIONTIMEOFEACHTOOL. PROTOCOLSANDSMARTCONTRACTSWITHDIFFERENTSOLCVERSIONS. ExecutionTime(s) # Tools # Tools 0.4.x 0.5.x 0.6.x 0.7.x 0.8.x DeFiprotocols Average Total 1 SECURIFY ✓ ✗ ✗ ✗ ✗ ✗ 1 HONEYBADGER 111.68 11056.63 2 VERISOL ✓ ✗ ✗ ✗ ✗ ✗ 2 MAIAN 436.55 43218.67 3 4 5 6 M M M OSA Y A II T N RA H IT SN R ICIL ORE ✓ ✓ ✓ ✓ ✗ ✗ ✗ ✗ ✗ ✗ ✗ ✗ ✗ ✗ ✗ ✗ ✗ ✗ ✗ ✗ ✗ ✗ ✗ ✗ 3 4 5 M M OSA Y IN T RH IT SI RC IO LRE 1 1 96 2 24 6 .2. .4 6 30 2 1 16 2 92 5 17 3 35 5 0. . .9 0 70 1 7 7 OYENTE ✓ ✗ ✗ ✗ ✗ ✗ 6 OYENTE 208.95 20686.05 8 TEETHER ✓ ✓ ✗ ✗ ✗ ✓ 7 SECURIFY 208.87 20678.13 9 VERX ✓ ✓ ✗ ✗ ✗ ✗ 8 SLITHER 216.26 21409.97 10 SMARTCHECK ✓ ✓ ✓ ✓ ✓ ✓ 9 SMARTCHECK 528.69 52339.97 11 SLITHER ✓ ✓ ✗ ✗ ✗ ✓ 10 TEETHER 331.89 32856.88 12 CONTRACTFUZZER ✓ ✗ ✗ ✗ ✗ ✗ 11 ILF 190.93 18902.03 13 CONFUZZIUS ✓ ✗ ✗ ✗ ✗ ✗ 12 RECHECKER 8.02 793.95 14 ILF ✓ ✓ ✗ ✗ ✗ ✗ 13 DEFI-SCORE 10.05 994.54 1 15 6 SSF MU AZ RZ TIAN ✓ ✓ ✗ ✗ ✗ ✗ ✗ ✗ ✗ ✗ ✗ ✗ 14 PROMUTATOR 11.11 1100.28 17 IR-FUZZ ✓ ✗ ✗ ✗ ✗ ✗ 18 RECHECKER ✓ ✓ ✓ ✓ ✓ ✓ 19 TMP ✓ ✗ ✗ ✗ ✗ ✗ 20 DEFI-SCORE ✓ ✓ ✓ ✓ ✗ ✓ groups of execution times: the tools that take a few seconds 21 PROMUTATOR ✓ ✓ ✓ ✗ ✗ ✓ toexecuteandthetoolsthattakeafewminutes.Forexample, all the traditional vulnerability detection tools (lines 1-11 in TABLEVII Table VIII) take a long time to analyze a DeFi protocol, rang- PERFORMANCEEVALUATIONOFEACHTOOLINTERMSOFACCURACY, ing from 92.23s to 528.69s per protocol. In contrast, the DeFi RECALL,PRECISION,F1-SCORE,ANDUNIQUEBUG. analysis methods such as DEFI-SCORE and PROMUTATOR are much faster, taking only 10.05s and 11.11s per protocol, # Tools Accuracy(%) Recall(%) Precision(%) F1-score(%) UniqueBug respectively. This may stem from two facts: (1) traditional 1 SLITHER 58.37 4.50 83.33 8.54 25 2 SMARTCHECK 58.91 26.96 35.65 30.70 12 vulnerability detection tools still have inherent difficulties in 3 TEETHER 63.13 31.32 75.55 44.28 1 understanding the complex logic of DeFi protocols; (2) the 4 RECHECKER 50.48 86.02 43.28 57.59 1 5 DEFI-SCORE 73.27 75.94 63.14 68.95 1 specially designed DeFi analysis methods are able to recover 6 PROMUTATOR 68.45 72.30 68.69 70.45 1 the high-level semantics of DeFi protocols. Interestingly, the deep learning-based method RECHECKER isafasttoolthattakesonaverageonly8.02stoanalyzeaDeFi PROMUTATOR can handle not only DeFi protocols but also protocol. We explain that the deep learning model spends a other versions of smart contracts. lot of time in the training phase, while the trained model can 2) PerformanceEvaluation(AnswertoRQ2): Wethencon- quickly identify the key characteristics of the DeFi protocols ductexperimentstoevaluatetheperformanceofavailabletools in the detection phase. However, we would like to point out that can analyze DeFi protocols. Quantitative experimental thattheexecutiontimedoesnotreflectthecompletepictureof results of each tool are summarized in Table VII. From the the performance of these tools. For example, most traditional table, we obtain the following observations. (1) Comparing vulnerability detection tools carry out invalid runs as their different tools, DeFi analysis methods gain a higher accuracy output is either empty or unavailable. than other methods.For example, DEFI-SCORE and PROMU- Based on the experimental results, it is not difficult to find TATORachieveaccuraciesof73.27%and68.45%,respectively, thattheperformanceoftraditionalsmartcontractbugdetection which is 10.14% and 5.32% higher than the state-of-the- methodsonDeFiprotocolsisfarfromsatisfactory.Theysuffer art tool TEETHER. (2) In terms of F1-Score, DEFI-SCORE fromtheinherentissuesinunderstandingthelogicalsemantics
and PROMUTATOR achieve 68.95% and 70.45% F1-score, of DeFi protocols. Particularly, a DeFi protocol typically outperforming state-of-the-art methods by a large margin. We consistsofmultipleinteractivecontracts,makingitdifficultfor attribute the superior performance of DeFi analysis methods thesetoolstowork.Ontheotherhand,whiletheexistingDeFi to the ability to recover high-level semantics from DeFi pro- analysis methods achieve promising performance in detecting tocols. (3) For unique bug, traditional vulnerability detection certain attacks, they are still unable to handle multiple types methods (e.g., SLITHER and SMARTCHECK) generate more ofattacksanddiscoverhigh-levellogicvulnerabilitiesinDeFi unique bugs, while DEFI-SCORE is used to assess risk in protocols. lending protocols and PROMUTATOR can only identify one specific DeFi attack, i.e., the price manipulation attack. VI. DISCUSSION:OPENISSUESANDFUTURE Further, we evaluate the execution time required by the CHALLENGES tools to analyze the DeFi protocols in the dataset. Table VIII presents the average and total time used by each tool. The While the interest in DeFi security is growing and con- average execution time is per project. It considers the execu- siderable progress has been made in this area over the past tion of the tool on a DeFi protocol, including compilation, few years [265], there are still several open issues that need construction of intermediate representation, analysis, and re- to be addressed in future research activities. In this section, sult parsing. From the table, we can observe two different we discuss the main issues that users and developers in the20 intertwined DeFi space face, and provide a summary of the to embrace the composable nature of smart contracts, which current challenges associated with DeFi security from our makes it impossible for such tools to reason about scenar- perspective. ios where the issue happens due to a change in something external to smart contracts, such as a sudden change in a A. Underlying Infrastructure price returned by an oracle (which often occurs in the DeFi protocols).Furthermore,mosttoolsreasonverylittleaboutthe One of the most critical security issues in DeFi is asso- semanticpropertiesofsmartcontracts,suchashowaparticular ciated with the underlying blockchain platform. Since DeFi execution path can influence ERC-20 token balances. Here, applications are composed of smart contracts running on the we summarize the limitation of existing vulnerability detec- blockchain system, their executions are affected by potential tion techniques for smart contracts from five aspects: formal blockchain vulnerabilities. For instance, eclipse attacks [266], verification, symbolic execution, intermediate representation, [267] to the blockchain could separate the network, which fuzzing test, and deep learning, respectively. results in churning logic among different market transactions. a) FormalVerification: Formalverificationmethodsrely Feather forking [268] and block reorganization [269] may on rigorous mathematical derivation and verification, they cause consensus vulnerabilities, and thus lead to double- fail to perform path analysis of smart contracts. Therefore, spending issues in DeFi markets. Furthermore, the limited they lack the detection and judgment of executable paths in throughput of the blockchain may cause network conges- the contract, resulting in a high rate of false positives and tion [270], delaying the DeFi transactions. negatives. Owingtotheopenandtransparentnatureoftheblockchain b) Symbolic Execution: Although the symbolic execu- system, all market states of DeFi protocols can be observed tion approach effectively improves vulnerability detection, it publicly in real-time. Meanwhile, users’ transactions will be significantly increases the computational resources and time broadcasttotheblockchainnetworkandstoredinamempool. overhead during analysis. In particular, symbolic execution The transactions in this mempool can be accessed by anyone suffersfromtheinherentproblemsofstatespaceandexecution before miners package them in a block. Therefore, attackers path explosion. can forecast the future market states based on non-executed c) IntermediateRepresentation: Intermediaterepresenta- transactions and utilize this knowledge to manipulate the tionmethodsmostlyrelyonpredefinedsemanticrules,theyare marketoperation.Forinstance,attackersmayobserveavictim unabletodetectthecomplexbusinesslogicofsmartcontracts transaction in the mempool and then front-run [82] or back- and are prone to false positives. In addition, they cannot run [271] them to gain profit. Moreover, DeFi protocols are traverse the execution paths that may exist in the contract. isolatedfromoutsideoftheblockchainsystem,whileexternal d) Fuzzing Test: Current fuzzing approaches for smart information cannot be utilized by these applications in real- contracts tend to generate function invocation sequences ran- time. As a result, DeFi protocols rely on each other and share domly, ignoring data dependencies between functions. More- information to maintain the market operation. For example, over, most existing methods fail to steer fuzzing towards the some lending borrowing protocols utilize the real-time ex- branchesthatarerareormorelikelytopossessbugs,resulting change rate in DEXs to determine the collateral rate [55]. in inefficient fuzzing where resources are wasted in normal Nevertheless,someattackersmaytargetdependenciesbetween branches.Meanwhile,itisstillchallenginghowtointelligently platforms by manipulating the state of one application and adjust seed mutation such that the generated test cases could profiting from another one [18]. reach a target conditional branch efficiently.
Security challenges related to DeFi protocols involve inter- e) Deep Learning: Deep learning-based methods detect actions between traders and DeFi protocols, it is difficult to vulnerabilitiesinsmartcontractsbytrainingalargenumberof detectthemeffectivelybeforelaunchingapplications.Further- vulnerablecontractsandconstructingalearnedneuralnetwork more, such security issues are associated with DeFi markets as the detection model. However, the absence of high-quality and continuously impact DeFi users in the long term [54]. smart contract vulnerability dataset severely hinders the per- Therefore, it is important to understand how users become formance and credibility of deep learning-based approaches. aware, perceive, and prevent security issues in DeFi markets. Furthermore, due to the black-box nature of neural networks, deep learning-based methods endure the inherent problems of B. DeFi Smart Contract inferior interpretability. Another key factor impacting on DeFi security is related to smart contracts. Like traditional programs, smart contracts C. Maximal Extractable Value may contain vulnerabilities. Smart contracts from various The notion of maximal extractable value (MEV) was in- fields now hold over one trillion dollars worth of virtual troduced by [82]. It refers to the total value that miners coins,attractingnumerousattacks.Cybercriminalshavemined could extract from the manipulation of transactions within a a variety of vulnerabilities in smart contracts, leading to giventimeframe,whichmayincludemultipleblocks’worthof substantial losses [42], [198], [272]. A large number of works transactions. MEV is predominantly captured by DeFi traders are designed, both in academia and industry, to unearth smart through structural arbitrage trading strategies, and miners contract bugs and vulnerabilities [46], [188], [253]. They indirectly profit from traders’ transaction fees. mainly revolve around static analysis and fuzzing techniques Traders on Ethereum express their willingness to pay for todiscovervulnerabilities.However,theyhavenotevolvedyet inclusion in a block through their transaction’s gas price, and21 theyindicatehowmuchtheyarewillingtopayminersthrough to many participants of the ecosystem. Finally, the impact of the transaction fee. Miners, as economically rational actors, a potentially malicious oracle (or a group of oracles) on the undoubtedly pick the transactions with the highest gas price DeFi ecosystem is still not investigated. and order them by gas spend in the block they are producing. While the interaction between two on-chain entities (e.g., Unfortunately, the financial system that is built on Ethereum smart contracts) is simple, transferring information from ex- createsmanypureprofitopportunitiessuchasliquidationsand ternal sources like websites to a smart contract introduces arbitrages of many kinds. new challenges. Many DeFi applications rely on external Obadia et al. [273], [274] propose to construct a permis- information, such as exchange rates and price information, sionless, transparent, and fair ecosystem for MEV extraction whichareprovidedbyDeFioracles.Sincethedataoriginating to preserve the ideals of Ethereum, mitigating the negative from these oracles impact the behavior of smart contracts and externalities and existential risks posed by MEV. Their ap- users, the challenges posed by transferring external data on- proach to mitigating the MEV crisis can be broken down into chainshowamajorconcern.Inparticular,thesecurityofthese three parts, namely, illuminate the dark forest, democratize DeFi applications is based on the reliability, accuracy, and extraction, and distribute benefits. correctness of the provided information from oracles. D. Composability F. Privacy Composability is one of the core features of decentralized The privacy and anonymity of DeFi protocols is at present finance [96], [102], [259], which allows applications and a significantly understudied area [277]–[279]. A common protocolstointeractwithoneanotherinapermissionlessway. view is emerging, that is the DeFi protocols cannot hit the Benefiting from the open nature of DeFi, these applications mainstream until the problem of privacy is addressed. Since are leveraging one another to create a synergistic effect and financial data is highly sensitive for many individuals, privacy create new forms of financial services never thought pos- is a relevant topic. In particular, users aim for private transac- sible. For example, cryptoassets in DeFi can be easily and tions such that no unauthorized party can obtain information repeatedlytokenizedandinterchangedbetweendifferentDeFi about users’ financial activities. Obviously, users may enjoy protocols in a fashion akin to rehypothecation. Unfortunately, complete privacy when trading for cryptoassets in the DeFi although the composability of DeFi offers the potential to market. However, a large proportion of DeFi transactions at construct complex, interconnected financial systems, it also present occur in projects built on Ethereum, wherein agents bearsthedangerofexposingtraderstopossiblecomposability at best have pseudo-anonymity [19]. This indicates that if risks [27]. A typical example of composability risk is the a trader’s real-world identity can be linked to an on-chain use of flash loans for manipulating instantaneous automated address, all the actions undertaken by the trader through market makers (AMMs) and financially exploiting protocols that address are observable. While recent advances in zero- thatusethoseAMMsas pricefeeds.Thishasrepeatedlybeen knowledge proofs [280], [281] and multi-party computations exploited in past attacks (e.g., [131], [275]). [282], [283] hold many promises, these technologies are yet Todealwithcomposabilityrisks,recentworks[37]propose to gain traction in the context of DeFi. One of the main chal-
a process-algebraic technique to achieve property verifica- lenges is the large computational cost of these technologies, tion by modeling DeFi protocols in a compositional manner. which makes them very expensive to use and deploy in the Nonetheless, a critical gap in DeFi research towards taxon- context of DeFi. Therefore, a decrease in the computational imizing and formalizing models to quantify composability cost of the underlying blockchain may be critical to how risks remains. Although regarded as a fundamental basis of widely privacy-preserving technologies can be deployed by DeFi, there are still considerable risks to the composability of DeFi protocols. the ecosystem. In particular, ensuring the safety of protocol composition will be close to impossible for any protocol VII. CONCLUSIONANDOUTLOOK designerandformsamajorchallengeforDeFigoingforward. With further expansion of the DeFi ecosystem and its deployment in a constantly increasing number of application E. Oracle domains,securityconcerns(e.g.,DeFiattacks)associatedwith DeFi oracles are essentially a third-party service that can DeFi are only expected to increase in the years to come. enable blockchain smart contracts to access external and real- A considerable amount of DeFi attacks, causing billions of world (i.e., off-chain) resources, such as price information dollarsinfinanciallosses,haveseverelythreatenedthesecurity and token exchange rates [64], [276]. While oracles play a of the whole DeFi ecosystem. critical role in the DeFi ecosystem, they also involve a degree This paper aims to provide a comprehensive understanding of security risks. To be even more specific, the underlying of various DeFi attacks and present an empirical review mechanics of DeFi oracles are vague and unexplored. First, of the state-of-the-art techniques that can detect or repair their deployment practices, such as how frequently the price vulnerabilities in smart contracts and DeFi protocols. As seen updates and how to aggregate the price value from multiple from the literature review, a plethora of techniques have been nodes, are not transparent nor accountable, leaving room for proposed over the years that are able to identify smart con- various external malicious behaviors. Second, the level of tract vulnerabilities automatically. Unfortunately, since most trust placed in oracles is unclear and most likely unknown of them are designed for handling traditional smart contracts22 or a single contract, they can only discover low-level bugs in [13] T.Hu,X.Liu,T.Chen,X.Zhang,X.Huang,W.Niu,J.Lu,K.Zhou, smart contracts while failing to analyze complex DeFi pro- and Y. Liu, “Transaction-based classification and detection approach forethereumsmartcontract,”InformationProcessing&Management, tocols. Although recent efforts can capture attack patterns in vol.58,no.2,p.102462,2021. DeFi protocols by recovering high-level DeFi semantics from [14] J. Moosavi, L. M. Naeni, A. M. Fathollahi-Fard, and U. Fiore, raw transactions, they still face obstacles in distinguishing “Blockchaininsupplychainmanagement:areview,bibliometric,and networkanalysis,”EnvironmentalScienceandPollutionResearch,pp. compound attacks and vulnerabilities. On the other side, the 1–15,2021. immutabilityoftheunderlyingblockchainmakesitdifficultto [15] C.C.Agbo,Q.H.Mahmoud,andJ.M.Eklund,“Blockchaintechnol- fixvulnerabilitiesintheon-chaincontracts.Currentautomated ogy in healthcare: a systematic review,” in Healthcare, vol. 7, no. 2. MultidisciplinaryDigitalPublishingInstitute,2019,p.56. repairtoolscanfixlimitedtypesofvulnerabilitiesandstruggle [16] I.Williams,Cross-industryUseofBlockchainTechnologyandOppor- to handle complex DeFi protocols. tunitiesfortheFuture. IGIglobal,2020. Therearestillmultiplekeyissuesthathavetobeaddressed [17] Y.ChenandC.Bellavitis,“Decentralizedfinance:Blockchaintechnol- ogy and the quest for an open financial system,” Stevens Institute of inthefuturetomakethemapplicablewidelyinvariousattack TechnologySchoolofBusinessResearchPaper,2019. detection,riskassessment,andautomatedrepair.Asdiscussed [18] L.Zhou,K.Qin,A.Cully,B.Livshits,andA.Gervais,“Onthejust- above, understanding the dependencies between intertwined in-time discovery of profit-generating transactions in defi protocols,” in2021IEEESymposiumonSecurityandPrivacy(SP). IEEE,2021, DeFi spaces is critical to figuring out the logic rules of DeFi pp.919–936. protocols. Furthermore, enhancing scalability is important for [19] S.M.Werner,D.Perez,L.Gudgeon,A.Klages-Mundt,D.Harz,and existing analysis tools to support more types of attack detec- W. J. Knottenbelt, “Sok: Decentralized finance (defi),” arXiv preprint tion and automated fixing. These and related challenges will arXiv:2101.08778,2021. [20] J.R.Jensen,V.vonWachter,andO.Ross,“Anintroductiontodecen- undoubtedly represent research priorities related to DeFi safe tralized finance (defi),” Complex Systems Informatics and Modeling ecological construction in the forthcoming year. Quarterly,no.26,pp.46–54,2021. [21] H.Amler,L.Eckey,S.Faust,M.Kaiser,P.Sandner,andB.Schlosser, “Defi-ning defi: Challenges & pathway,” in 2021 3rd Conference on REFERENCES Blockchain Research & Applications for Innovative Networks and Services(BRAINS). IEEE,2021,pp.181–184.
[1] S.Nakamoto,“Bitcoin:Apeer-to-peerelectroniccashsystem,”Decen- [22] M.Bartoletti,J.H.-y.Chiang,andA.L.Lafuente,“Sok:lendingpools tralizedBusinessReview,p.21260,2008. in decentralized finance,” in International Conference on Financial [2] W. Zou, D. Lo, P. S. Kochhar, X.-B. D. Le, X. Xia, Y. Feng, CryptographyandDataSecurity. Springer,2021,pp.553–578. Z. Chen, and B. Xu, “Smart contract development: Challenges and [23] A. Raheman, A. Kolonin, B. Goertzel, G. Hegykozi, and I. Ansari, opportunities,” IEEE Transactions on Software Engineering, vol. 47, “Architecture of automated crypto-finance agent,” arXiv preprint no.10,pp.2084–2106,2019. arXiv:2107.07769,2021. [3] R. V. Rosa and C. E. Rothenberg, “Blockchain-based decentralized [24] M. Bartoletti, J. H.-y. Chiang, and A. Lluch-Lafuente, “A theory of applications meet multi-administrative domain networking,” in Pro- automated market makers in defi,” in International Conference on ceedings of the ACM SIGCOMM 2018 Conference on Posters and CoordinationLanguagesandModels. Springer,2021,pp.168–187. Demos,2018,pp.114–116. [25] M.Bartoletti,H.-y.Chiang,James,andA.Lluch-Lafuente,“Maximiz- [4] J.Gao,H.Liu,Y.Li,C.Liu,Z.Yang,Q.Li,Z.Guan,andZ.Chen, ing extractable value from automated market makers,” arXiv preprint “Towardsautomatedtestingofblockchain-baseddecentralizedapplica- arXiv:2106.01870,2021. tions,”in2019IEEE/ACM27thInternationalConferenceonProgram [26] M.Bartoletti,J.H.-y.Chiang,andA.L.Lafuente,“Towardsatheory Comprehension(ICPC). IEEE,2019,pp.294–299. of decentralized finance,” in International Conference on Financial [5] N.Z.Benisi,M.Aminian,andB.Javadi,“Blockchain-baseddecentral- CryptographyandDataSecurity. Springer,2021,pp.227–232. ized storage networks: A survey,” Journal of Network and Computer [27] L. Gudgeon, D. Perez, D. Harz, B. Livshits, and A. Gervais, “The Applications,vol.162,p.102656,2020. decentralized financial crisis,” in 2020 Crypto Valley Conference on [6] B.Yu,J.Liu,S.Nepal,J.Yu,andP.Rimba,“Proof-of-qos:Qosbased BlockchainTechnology(CVCBT). IEEE,2020,pp.1–15. blockchain consensus protocol,” Computers & Security, vol. 87, p. [28] K. Qin, L. Zhou, B. Livshits, and A. Gervais, “Attacking the defi 101580,2019. ecosystemwithflashloansforfunandprofit,”inInternationalConfer- [7] Z. Liu, P. Qian, X. Wang, L. Zhu, Q. He, and S. Ji, “Smart contract enceonFinancialCryptographyandDataSecurity. Springer,2021, vulnerability detection: From pure neural network to interpretable pp.3–32. graph feature and expert pattern fusion,” in IJCAI, 2021, pp. 2751– [29] K. Oosthoek, “Flash crash for cash: Cyber threats in decentralized 2759. finance,”arXivpreprintarXiv:2106.10740,2021. [8] F. M. Bencˇic´ and I. P. Žarko, “Distributed ledger technology: [30] S.-H. Wang, C.-C. Wu, Y.-C. Liang, L.-H. Hsieh, and H.-C. Hsiao, Blockchain compared to directed acyclic graph,” in 2018 IEEE 38th “Promutator: Detecting vulnerable price oracles in defi by mutated InternationalConferenceonDistributedComputingSystems(ICDCS). transactions,” in 2021 IEEE European Symposium on Security and IEEE,2018,pp.1569–1570. PrivacyWorkshops(EuroS&PW). IEEE,2021,pp.380–385. [9] Z.Liu,P.Qian,X.Wang,Y.Zhuang,L.Qiu,andX.Wang,“Combining [31] A. Group, “Preventing re-entrancy attacks — lessons from history,” graph neural networks with expert knowledge for smart contract Website,Accessed:08-08-2023, https://medium.com/amber-group/pre vulnerability detection,” IEEE Transactions on Knowledge and Data venting-re-entrancy-attacks-lessons-from-history-c2d96480fac3. Engineering,vol.35,no.2,pp.1296–1310,2023. [32] Inspex,“Reentrancyattackoncreamfinance,”Website,Accessed:08- [10] W.Chen,Z.Xu,S.Shi,Y.Zhao,andJ.Zhao,“Asurveyofblockchain 08-2023, https://inspexco.medium.com/reentrancy-attack-on-cream-f applications in different domains,” in Proceedings of the 2018 Inter- inance-incident-analysis-1c629686b6f5. nationalConferenceonBlockchainTechnologyandApplication,2018, [33] Wikipedia, “Poly network exploit,” Website, Accessed: 08-08-2023, pp.17–21. https://en.wikipedia.org/wiki/Poly_Network_exploit. [11] P. Qian, Z. Liu, X. Wang, J. Chen, B. Wang, and R. Zimmermann, [34] A.Hayward,“Hackerdrains$622mfromaxieinfinity’sroninethereum “Digitalresourcerightsconfirmationandinfringementtrackingbased sidechain,”Website,Accessed:08-08-2023, https://decrypt.co/96322/ on smart contracts,” in 2019 IEEE 6th International Conference on hacker-622-million-axie-infinity-ronin-ethereum. CloudComputingandIntelligenceSystems(CCIS). IEEE,2019,pp. [35] Rekt, “Rekt news,” Website, Accessed: 08-08-2023, https://de.fi/rekt 62–67. -database.
[12] Y.-P.ChenandJ.-C.Ko,“Cryptoarwallet:Ablockchaincryptocurrency [36] D. Wang, S. Wu, Z. Lin, L. Wu, X. Yuan, Y. Zhou, H. Wang, and wallet application that uses augmented reality for on-chain user data K. Ren, “Towards a first step to understand flash loan and its appli- display,” in Proceedings of the 21st International Conference on cations in defi ecosystem,” in Proceedings of the Ninth International Human-ComputerInteractionwithMobileDevicesandServices,2019, WorkshoponSecurityinBlockchainandCloudComputing,2021,pp. pp.1–5. 23–28.23 [37] P. Tolmach, Y. Li, S.-W. Lin, and Y. Liu, “Formal analysis of Conference on Automated Software Engineering, ser. ASE ’22, New composabledefiprotocols,”inInternationalConferenceonFinancial York,NY,USA,2023. CryptographyandDataSecurity. Springer,2021,pp.149–161. [58] R. Böhme, N. Christin, B. Edelman, and T. Moore, “Bitcoin: Eco- [38] K. Qin, L. Zhou, Y. Afonin, L. Lazzaretti, and A. Gervais, “Cefi vs. nomics, technology, and governance,” Journal of economic Perspec- defi–comparing centralized to decentralized finance,” arXiv preprint tives,vol.29,no.2,pp.213–38,2015. arXiv:2106.08157,2021. [59] R. Chatterjee and R. Chatterjee, “An overview of the emerging [39] U. W. Chohan, “Decentralized finance (defi): an emergent alternative technology: Blockchain,” in 2017 3rd International Conference on financialarchitecture,”CriticalBlockchainResearchInitiative(CBRI) Computational Intelligence and Networks (CINE). IEEE, 2017, pp. WorkingPapers,2021. 126–127. [40] B. Marino and A. Juels, “Setting standards for altering and undoing [60] S. Dos Santos, C. Chukwuocha, S. Kamali, and R. K. Thulasiram, smart contracts,” in International Symposium on Rules and Rule “Anefficientminerstrategyforselectingcryptocurrencytransactions,” MarkupLanguagesfortheSemanticWeb. Springer,2016,pp.151– in 2019 IEEE International Conference on Blockchain (Blockchain). 166. IEEE,2019,pp.116–123. [41] Y. Xue, M. Ma, Y. Lin, Y. Sui, J. Ye, and T. Peng, “Cross-contract [61] S. M. H. Bamakan, A. Motavali, and A. B. Bondarti, “A survey static analysis for detecting practical reentrancy vulnerabilities in of blockchain consensus algorithms performance evaluation criteria,” smartcontracts,”in202035thIEEE/ACMInternationalConferenceon ExpertSystemswithApplications,vol.154,p.113385,2020. AutomatedSoftwareEngineering(ASE). IEEE,2020,pp.1029–1040. [62] H. Wang, D. He, and Y. Ji, “Designated-verifier proof of assets for [42] D. Perez and B. Livshits, “Smart contract vulnerabilities: Vulnerable bitcoinexchangeusingellipticcurvecryptography,”FutureGeneration does not imply exploited,” in 30th USENIX Security Symposium ComputerSystems,vol.107,pp.854–862,2020. (USENIXSecurity21),2021,pp.1325–1341. [63] R. Tas¸ and Ö. Ö. Tanrıöver, “Building a decentralized application [43] L. Brent, N. Grech, S. Lagouvardos, B. Scholz, and Y. Smaragdakis, on the ethereum blockchain,” in 2019 3rd International Symposium “Ethainter: a smart contract security analyzer for composite vulner- on Multidisciplinary Studies and Innovative Technologies (ISMSIT). abilities,” in Proceedings of the 41st ACM SIGPLAN Conference on IEEE,2019,pp.1–4. Programming Language Design and Implementation, 2020, pp. 454– [64] B.Liu,P.Szalachowski,andJ.Zhou,“Afirstlookintodefioracles,” 469. in2021IEEEInternationalConferenceonDecentralizedApplications [44] A. Ghaleb and K. Pattabiraman, “How effective are smart contract andInfrastructures(DAPPS). IEEE,2021,pp.39–48. analysistools?evaluatingsmartcontractstaticanalysistoolsusingbug [65] J.Bonneau,A.Miller,J.Clark,A.Narayanan,J.A.Kroll,andE.W. injection,” in Proceedings of the 29th ACM SIGSOFT International Felten, “Sok: Research perspectives and challenges for bitcoin and SymposiumonSoftwareTestingandAnalysis,2020,pp.415–427. cryptocurrencies,” in 2015 IEEE symposium on security and privacy. [45] I. Grishchenko, M. Maffei, and C. Schneidewind, “Foundations and IEEE,2015,pp.104–121. tools for the static analysis of ethereum smart contracts,” in Interna- [66] N. Atzei, M. Bartoletti, and T. Cimoli, “A survey of attacks on tional Conference on Computer Aided Verification. Springer, 2018, ethereumsmartcontracts(sok),”inPrinciplesofSecurityandTrust:6th pp.51–78. International Conference, POST 2017, Held as Part of the European [46] C.Schneidewind,I.Grishchenko,M.Scherer,andM.Maffei,“ethor: Joint Conferences on Theory and Practice of Software, ETAPS 2017, Practical and provably sound static analysis of ethereum smart con- Uppsala,Sweden,April22-29,2017,Proceedings6. Springer,2017, tracts,” in Proceedings of the 2020 ACM SIGSAC Conference on pp.164–186. ComputerandCommunicationsSecurity,2020,pp.621–640. [67] S.Bano,A.Sonnino,M.Al-Bassam,S.Azouvi,P.McCorry,S.Meik- [47] V.WüstholzandM.Christakis,“Targetedgreyboxfuzzingwithstatic lejohn, and G. Danezis, “Sok: Consensus in the age of blockchains,” lookahead analysis,” in 2020 IEEE/ACM 42nd International Confer- inProceedingsofthe1stACMConferenceonAdvancesinFinancial enceonSoftwareEngineering(ICSE). IEEE,2020,pp.789–800.
Technologies,2019,pp.183–198. [48] P. Zong, T. Lv, D. Wang, Z. Deng, R. Liang, and K. Chen, [68] V.Buterinetal.,“Anext-generationsmartcontractanddecentralized “{FuzzGuard}: Filtering out unreachable inputs in directed grey-box application platform. 2014,” URL: https://github.com/ethereum/wiki fuzzingthroughdeeplearning,”in29thUSENIXSecuritySymposium /wiki/White-Paper,2019. (USENIXSecurity20),2020,pp.2255–2269. [69] Solidity, “Solidity documentation,” Website, Accessed: 08-08-2023, [49] G. Grieco, W. Song, A. Cygan, J. Feist, and A. Groce, “Echidna: https://vyper.readthedocs.io. effective,usable,andfastfuzzingforsmartcontracts,”inProceedings [70] Vyper,“Vyperdocumentation,”Website,Accessed:08-08-2023, https: of the 29th ACM SIGSOFT International Symposium on Software //docs.soliditylang.org. TestingandAnalysis,2020,pp.557–560. [71] D.PerezandB.Livshits,“Smartcontractvulnerabilities:Doesanyone [50] J.Feist,G.Grieco,andA.Groce,“Slither:astaticanalysisframework care?”arXivpreprintarXiv:1902.06710,pp.1–15,2019. for smart contracts,” in 2019 IEEE/ACM 2nd International Workshop on Emerging Trends in Software Engineering for Blockchain (WET- [72] Y. Huang, Y. Bian, R. Li, J. L. Zhao, and P. Shi, “Smart contract SEB). IEEE,2019,pp.8–15. security: A software lifecycle perspective,” IEEE Access, vol. 7, pp. 150184–150202,2019. [51] B.Jiang,Y.Liu,andW.Chan,“Contractfuzzer:Fuzzingsmartcontracts for vulnerability detection,” in Proceedings of the 33rd ACM/IEEE [73] F. Schär, “Decentralized finance: On blockchain-and smart contract- InternationalConferenceonAutomatedSoftwareEngineering. ACM, basedfinancialmarkets,”FRBofSt.LouisReview,2021. 2018,pp.259–269. [74] F. I. . Investments, “Tvl (total value locked) across multiple decen- [52] Y.Cao,C.Zou,andX.Cheng,“Flashot:asnapshotofflashloanattack tralized finance (defi) blockchains,” Website, Accessed: 08-08-2023, ondefiecosystem,”arXivpreprintarXiv:2102.00626,2021. https://www.statista.com/statistics/1272181/defi-tvl-in-multiple-block [53] B. Wang, H. Liu, C. Liu, Z. Yang, Q. Ren, H. Zheng, and H. Lei, chains/. “Blockeye:Huntingfordefiattacksonblockchain,”in2021IEEE/ACM [75] R. Moncada, E. Ferro, A. Favenza, and P. Freni, “Next generation 43rd International Conference on Software Engineering: Companion blockchain-basedfinancialservices,”inEuropeanConferenceonPar- Proceedings(ICSE-Companion). IEEE,2021,pp.17–20. allelProcessing. Springer,2020,pp.30–41. [54] Y. Wang, Z. Partick, Y. Yao, Z. Lu, and R. Wattenhofer, “Impact [76] S.A.Abdulhakeem,Q.Huetal.,“Poweredbyblockchaintechnology, and user perception of sandwich attacks in the defi ecosystem,” in defi(decentralizedfinance)strivestoincreasefinancialinclusionofthe ACMConferenceonHumanFactorsinComputingSystems(CHI),New unbankedbyreshapingtheworldfinancialsystem,”ModernEconomy, Orleans,LA,USA,2022. vol.12,no.01,p.1,2021. [55] S.Wu,D.Wang,J.He,Y.Zhou,L.Wu,X.Yuan,Q.He,andK.Ren, [77] Makerdao,“Themakerfoundation,”Website,Accessed:08-08-2023, “Defiranger:Detectingpricemanipulationattacksondefiapplications,” https://makerdao.com/en/. arXivpreprintarXiv:2104.15068,2021. [78] K. Saengchote, “Decentralized lending and its users: Insights from [56] T. D. Nguyen, L. H. Pham, and J. Sun, “SGUARD: towards fixing compound,”AvailableatSSRN3925344,2021. vulnerable smart contracts automatically,” in 42nd IEEE Symposium [79] K.Qin,L.Zhou,andA.Gervais,“Quantifyingblockchainextractable on Security and Privacy, SP 2021, San Francisco, CA, USA, 24-27 value:Howdarkistheforest?”arXivpreprintarXiv:2101.05511,2021. May 2021. IEEE, 2021, pp. 1215–1229. [Online]. Available: [80] L.Gudgeon,S.Werner,D.Perez,andW.J.Knottenbelt,“Defiproto- https://doi.org/10.1109/SP40001.2021.00057 colsforloanablefunds:Interestrates,liquidityandmarketefficiency,” [57] P.Tolmach,Y.Li,andS.-W.Lin,“Property-basedautomatedrepairof inProceedingsofthe2ndACMConferenceonAdvancesinFinancial defi protocols,” in Proceedings of the 37th IEEE/ACM International Technologies,2020,pp.92–112.24 [81] K. Qin, L. Zhou, P. Gamito, P. Jovanovic, and A. Gervais, “An [111] N. Carter and L. Jeng, “Defi protocol risks: the paradox of defi,” empiricalstudyofdefiliquidations:Incentives,risks,andinstabilities,” Regtech,SuptechandBeyond:InnovationandTechnologyinFinancial in Proceedings of the 21st ACM Internet Measurement Conference, Services”RiskBooks–ForthcomingQ,vol.3,2021. 2021,pp.336–350. [112] Z.Wang,K.Qin,D.V.Minh,andA.Gervais,“Speculativemultipliers [82] P. Daian, S. Goldfeder, T. Kell, Y. Li, X. Zhao, I. Bentov, L. Brei- ondefi:Quantifyingon-chainleveragerisks,”FinancialCryptography
denbach,andA.Juels,“Flashboys2.0:Frontrunningindecentralized andDataSecurity,2022. exchanges,minerextractablevalue,andconsensusinstability,”in2020 [113] P. Qian, Z. Liu, Q. He, B. Huang, D. Tian, and X. Wang, “Smart IEEE Symposium on Security and Privacy (SP). IEEE, 2020, pp. contract vulnerability detection technique: A survey,” arXiv preprint 910–927. arXiv:2209.05872,2022. [83] V.Zakhary,D.Agrawal,andA.E.Abbadi,“Atomiccommitmentacross [114] H. Chu, P. Zhang, H. Dong, Y. Xiao, S. Ji, and W. Li, “A survey blockchains,”arXivpreprintarXiv:1905.02847,2019. on smart contract vulnerabilities: Data sources, detection and repair,” [84] Aave,“Aaveprotocol,”Website,Accessed:08-08-2023, https://aave.c InformationandSoftwareTechnology,p.107221,2023. om/. [115] J. Ye, M. Ma, Y. Lin, Y. Sui, and Y. Xue, “Clairvoyance: cross- [85] Balancer,“Balancerexchange,”Website,Accessed:08-08-2023, https: contractstaticanalysisfordetectingpracticalreentrancyvulnerabilities //balancer.fi/. insmartcontracts,”in2020IEEE/ACM42ndInternationalConference [86] Compound, “Compound protocol,” Website, Accessed: 08-08-2023, onSoftwareEngineering:CompanionProceedings(ICSE-Companion). https://compound.finance/. IEEE,2020,pp.274–275. [87] Y. Wang, Y. Chen, H. Wu, L. Zhou, S. Deng, and R. Wattenhofer, [116] CoinCodeCap, “Introduction to flash loans: What is a flash loan “Cyclicarbitrageindecentralizedexchanges,”inTheWebConference attack?” Website, Accessed: 08-08-2023, https://coincodecap.com/fla 2022(WWW),Lyon,France,2022. sh-loan. [88] Uniswap,“Uniswapprotocol,”Website,Accessed:08-08-2023, https: [117] D.Lu,“Freeswapexchangeprotocol,”2021. //uniswap.org/. [118] A.Yüksel,“Mitigatingsandwichattacksinkyberdmm,”2021. [89] L. Zhou, K. Qin, C. F. Torres, D. V. Le, and A. Gervais, “High- [119] H. Adams, N. Zinsmeister, M. Salem, R. Keefer, and D. Robinson, frequencytradingondecentralizedon-chainexchanges,”in2021IEEE “Uniswapv3core,”2021. SymposiumonSecurityandPrivacy(SP). IEEE,2021,pp.428–445. [120] I.Weber,V.Gramoli,A.Ponomarev,M.Staples,R.Holz,A.B.Tran, [90] E.Hertzog,G.Benartzi,andG.Benartzi,“Bancorprotocol,”Continu- andP.Rimba,“Onavailabilityforblockchain-basedsystems,”in2017 ousLiquidityforCryptographicTokensthroughtheirSmartContracts., IEEE36thSymposiumonReliableDistributedSystems(SRDS). IEEE, 2017. 2017,pp.64–73. [91] kyber,“Kyber,”Website,Accessed:08-08-2023, https://kyber.network. [121] A.A.Zarir,G.A.Oliva,Z.M.Jiang,andA.E.Hassan,“Developing [92] L. Heimbach, Y. Wang, and R. Wattenhofer, “Behavior of cost-effectiveblockchain-poweredapplications:Acasestudyofthegas liquidity providers in decentralized exchanges,” arXiv preprint usage of smart contract transactions in the ethereum blockchain plat- arXiv:2105.13822,2021. form,” ACM Transactions on Software Engineering and Methodology [93] T.Chitra,K.Kulkarni,G.Angeris,A.Evans,andV.Xu,“Defiliquidity (TOSEM),vol.30,no.3,pp.1–38,2021. managementviaoptimalcontrol:Ohmasacasestudy,”2022. [122] P.Xia,B.Gao,W.Su,Z.Yu,X.Luo,C.Zhang,X.Xiao,G.Xuetal., [94] V.Mohan,“Automatedmarketmakersanddecentralizedexchanges:a “Demystifyingscamtokensonuniswapdecentralizedexchange,”arXiv defiprimer,”AvailableatSSRN3722714,2020. preprintarXiv:2109.00229,2021. [95] O.AlaoandP.Cuffe,“Towardsablockchainweatherderivativefinan- [123] J. Scharfman, “Decentralized finance (defi) compliance and opera- cialinstrumentforhedgingvolumetricrisksofsolarpowerproducers,” tions,”inCryptocurrencyComplianceandOperations. Springer,2022, in2021IEEEMadridPowerTech. IEEE,2021,pp.1–6. pp.171–186. [96] V. v. Wachter, J. R. Jensen, and O. Ross, “Measuring asset compos- [124] S. Malwa, “Rug pull scams,” Website, Accessed: 08-08-2023, ability as a proxy for defi integration,” in International Conference https://www.coindesk.com/markets/2021/12/17/defi-rug-pull-scams-p on Financial Cryptography and Data Security. Springer, 2021, pp. ulled-in-28b-this-year-chainalysis. 109–114. [125] Bondly, “Bondly.finance protocol,” Website, Accessed: 08-08-2023, [97] CompliFi,“Complifiprotocol,”Website,Accessed:08-08-2023, https: https://www.bondly.finance/. //compli.fi/. [126] K. J. Kistner, “Post-mortem,” Website, Accessed: 08-08-2023, https: [98] dYdX,“dydxprotocol,”Website,Accessed:08-08-2023, https://dydx //bzx.network/blog/postmortem-ethdenver. .exchange/. [127] MakerDAO, “The market collapse of march 12-13, 2020: [99] BarnBridge, “Tokenized risk protocol,” Website, Accessed: 08-08-
How it impacted makerdao,” Website, Accessed: 08-08-2023, 2023, https://barnbridge.com/. https://blog.makerdao.com/the-market-collapse-of-march-12-2020-h [100] A. Klages-Mundt, D. Harz, L. Gudgeon, J.-Y. Liu, and A. Minca, ow-it-impacted-makerdao/. “Stablecoins 2.0: Economic foundations and risk-based models,” in Proceedings of the 2nd ACM Conference on Advances in Financial [128] pNetwork Team, “Is a new token standard really to blame for Technologies,2020,pp.59–79. the imbtc/uniswap and dforce attacks?” Website, Accessed: 08-08- [101] M. Mita, K. Ito, S. Ohsawa, and H. Tanaka, “What is stablecoin?: A 2023, https://medium.com/pnetwork/is-a-new-token-standard-really-t survey on price stabilization mechanisms for decentralized payment o-blame-for-the-imbtc-uniswap-and-dforce-attacks-31c62e2bc799. systems,” in 2019 8th International Congress on Advanced Applied [129] K.J.Kistner,“itokenduplicationincidentreport,”Website,Accessed: Informatics(IIAI-AAI). IEEE,2019,pp.60–66. 08-08-2023, https://bzx.network/blog/incident. [102] K. Saengchote, “Where do defi stablecoins go? a closer look at [130] rekt,“Eminence-rektinprod,”Website,Accessed:08-08-2023, https: what defi composability really means.” A closer look at what DeFi //rekt.news/eminence-rekt-in-prod/. composabilityreallymeans.(July26,2021),2021. [131] H. Finance, “Harvest flash loan economic attack post-mortem,” Web- [103] Tether, “Tether token,” Website, Accessed: 08-08-2023, https://tether site,Accessed:08-08-2023, https://medium.com/harvest-finance/harve .to/. st-flashloan-economic-attack-post-mortem-3cf900d65217. [104] DAI,“Daitoken,”Website,Accessed:08-08-2023, https://en.wikiped [132] Akropolis, “Delphi savings pool exploit,” Website, Accessed: 08-08- ia.org/wiki/Dai_(cryptocurrency). 2023, https://akropolis.substack.com/p/delphi-savings-pool-exploit?s [105] Diem, “Diem token,” Website, Accessed: 08-08-2023, https://en.wik =r. ipedia.org/wiki/Diem_(digital_currency). [133] W. Gottsegen, “Defi protocol pickle finance hacked for $20 million,” [106] S. Cousaert, J. Xu, and T. Matsui, “Sok: Yield aggregators in defi,” Website,Accessed:08-08-2023, https://decrypt.co/49149/pickle-finan arXivpreprintarXiv:2105.13891,2021. ce-hack. [107] J.Li,“Defiasaninformationaggregator,”inInternationalConference [134] W.Finance,“Warpfinance—exploitsummary&recoveryoffunds,” on Financial Cryptography and Data Security. Springer, 2021, pp. Website, Accessed: 08-08-2023, https://warpfinance.medium.com/wa 171–176. rp-finance-exploit-summary-recovery-of-funds-5b8fe4a11898. [108] 1inch, “1inch protocol,” Website, Accessed: 08-08-2023, https://app. [135] C.Williams,“Alphafinanceexploitedin$37.5millionattack,”Website, 1inch.io. Accessed: 08-08-2023, https://cryptobriefing.com/alpha-finance-suffe [109] Matcha, “Matcha protocol,” Website, Accessed: 08-08-2023, https: rs-37-5-million-loss-major-attack/. //matcha.xyz. [136] SpartanProtocol, “Post mortem analysis,” Website, Accessed: 08-08- [110] Plasma.Finance,“Plasma.financeprotocol,”Website,Accessed:08-08- 2023, https://spartanprotocol.medium.com/today-spartan-protocol-was 2023, https://plasma.finance. -subject-to-an-exploit-targeting-the-liquidity-pools-8589b2069cef.25 [137] REKT, “Value defi (1),” Website, Accessed: 08-08-2023, https://rekt [163] S. Malwa, “How market manipulation led to $100m exploit .news/value-defi-rekt/. on solana defi exchange mango,” Website, Accessed: 08-08- [138] ——,“Valuedefi(2),”Website,Accessed:08-08-2023, https://rekt.n 2023, https://www.coindesk.com/markets/2022/10/12/how-market-m ews/value-rekt2/. anipulation-led-to-a-100m-exploit-on-solana-defi-exchange-mango/. [139] ——,“Valuedefi(3),”Website,Accessed:08-08-2023, https://rekt.n [164] M.DAO,“Bondlyexploit—howitunfoldedonzenterestpostmortem,” ews/value-rekt3/. Website, Accessed: 08-08-2023, https://medium.com/mantra-dao/bon [140] autofarm.network,“Venusvaultspost-mortem,”Website,Accessed:08- dly-exploit-how-it-unfolded-on-zenterest-postmortem-d8120d8d784b. 08-2023, https://medium.com/autofarm-network/21-april-2021-venus [165] J.Russell,“Thecryptoworld’slatesthackseesbancorlose$23.5m,” -vaults-post-mortem-1518ae7399c6. Website,Accessed:08-08-2023, https://techcrunch.com/2018/07/10/ba [141] B.Finance,“Postmortemanalysis,”Website,Accessed:08-08-2023, ncor-loses-23-5m/.
https://pancakebunny.medium.com/hello-bunny-fam-a7bf0c7a07ba. [166] DODO, “Dodo pool incident postmortem: With a little [142] ——,“Polybunnypost-mortem&compensation,”Website,Accessed: help from our friends,” Website, Accessed: 08-08-2023, 08-08-2023, https://pancakebunny.medium.com/polybunny-post-mor https://blog.dodoex.io/dodo-pool-incident-postmortem-with-a-littl tem-compensation-42b5c35ce957. e-help-from-our-friends-327e66872d42. [143] E.Genç,“Burgerswapexplains$7.2millionflashloanattackinpost- [167] S.Foundation,“Uraniumfinanceexploitanalysis,”Website,Accessed: mortem,”Website,Accessed:08-08-2023, https://decrypt.co/72194/bu 08-08-2023, https://medium.com/shentu-foundation/uranium-finance rgerswap-explains-7-2-million-flash-loan-attack-in-post-mortem. -exploit-analysis-d135055d6a6a. [144] JustLiquidity,“Flashloanfarming/julb/bnb,”Website,Accessed:08- [168] ChainSwap, “Chainswap post-mortem and compensation plan,” Web- 08-2023, https://justliquidity.medium.com/flash-loan-farming-julb-b site, Accessed: 08-08-2023, https://chain-swap.medium.com/chainsw nb-14c6c128f5dd. ap-post-mortem-and-compensation-plan-90cad50898ab. [145] B. Finance, “May 29 incident report,” Website, Accessed: 08-08- [169] ——, “Chainswap exploit 11 july 2021 post-mortem,” Website, Ac- 2023, https://medium.com/belt-finance/may-29-incident-report-865d cessed:08-08-2023, https://chain-swap.medium.com/chainswap-explo 20cc46ca. it-11-july-2021-post-mortem-6e4e346e5a32. [146] SlowMist,“Abriefanalysisofthestoryofthesushiswapattack,”Web- [170] Popsicle.Finance, “Popsicle finance post mortem- after fragola hack,” site, Accessed: 08-08-2023, https://slowmist.medium.com/slowmist-a Website, Accessed: 08-08-2023, https://popsiclefinance.medium.com/ -brief-analysis-of-the-story-of-the-sushi-swap-attack-c7bc6709adea. popsicle-finance-post-mortem-after-fragola-hack-f45b302362e0. [147] THORChain, “Certik completes thorchain audit,” Website, Accessed: [171] T.Gagliardoni,“Thepolynetworkhackexplained,”Website,Accessed: 08-08-2023, https://medium.com/thorchain/certik-completes-thorchain 08-08-2023, https://research.kudelskisecurity.com/2021/08/12/the-pol -audit-c6d88fad3613. y-network-hack-explained/. [148] V.Finance,“Vee.financeincidentannouncement,”Website,Accessed: [172] J.Gogo,“$160matriskduetobugindefilendingprotocolcompound,” 08-08-2023, https://veefi.medium.com/vee-finance-accident-announc Website,Accessed:08-08-2023, https://decrypt.co/82499/compound-e ement-5e75ff197da6. xploit-drains-21m-from-lending-protocol. [149] I. Finance, “Indexed attack post-mortem,” Website, Accessed: [173] P.NETWORK,“Paidnetworkattackpostmortem,”Website,Accessed: 08-08-2023, https://ndxfi.medium.com/indexed-attack-post-mortem-b 08-08-2023, https://paidnetwork.medium.com/paid-network-attack-p 006094f0bdc. ostmortem-march-7-2021-9e4c0fef0e07. [150] A. Thurman, “Cream finance suffers third hack, loses over $130 [174] PeckShield, “Opyn hacks: Root cause analysis,” Website, Accessed: million,” Website, Accessed: 08-08-2023, https://decrypt.co/84590/cr 08-08-2023, https://peckshield.medium.com/opyn-hacks-root-cause-a eam-finance-suffers-third-hack-losing-over-130-million. nalysis-c65f3fe249db. [151] BlockSec, “The analysis of nerve bridge security incident,” Website, [175] M. Dalton, “Chainlink endures spam attack: Congestion, high fees,” Accessed: 08-08-2023, https://blocksecteam.medium.com/the-analysi Website,Accessed:08-08-2023, https://cryptobriefing.com/chainlink-e s-of-nerve-bridge-security-incident-ead361a21025. ndures-spam-attack-congestion-high-fees/. [152] J. Benson, “Ethereum defi protocol beanstalk hacked for $182 [176] C. Protocol, “12/28 post-mortem,” Website, Accessed: 08-08-2023, million—what you need to know,” Website, Accessed: 08-08- https://coverprotocol.medium.com/12-28-post-mortem-34c5f9f718d4. 2023, https://decrypt.co/98118/ethereum-defi-protocol-beanstalk-hac [177] BlockSec, “Deposit less, get more: ycredit attack details,” Website, ked-182-million-what-you-need-know. Accessed: 08-08-2023, https://blocksecteam.medium.com/deposit-les [153] P. Boyle, “Saddle finance loses over $10 million in hack,” Website, s-get-more-ycredit-attack-details-f589f71674c3.
Accessed:08-08-2023, https://medium.com/coinmonks/saddle-finance [178] D. H. Staff, “yearn.finance reveals details on hack that -loses-over-10-million-in-hack-derev-blog-2ba4b5d66527. triggered $11 million loss,” Website, Accessed: 08-08-2023, [154] M.McDonald,“Incidentwithnon-standarderc20deflationarytokens,” https://dailyhodl.com/2021/02/07/yearn-finance-reveals-details-on-hac Website, Accessed: 08-08-2023, https://medium.com/balancer-proto k-that-triggered-11-million-loss/. col/incident-with-non-standard-erc20-deflationary-tokens-95a0f6d46d [179] FURUCOMBO,“Furucombopost-mortemmarch2021,”Website,Ac- ea. cessed: 08-08-2023, https://medium.com/furucombo/furucombo-pos [155] BlockSec,“Theanalysisofthesanshuinusecurityincident,”Website, t-mortem-march-2021-ad19afd415e. Accessed: 08-08-2023, https://blocksecteam.medium.com/the-analysi [180] EasyFi, “Easyfi security incident. pre-post mortem,” Website, s-of-the-sanshu-inu-security-incident-28c0c7c0e783. Accessed: 08-08-2023, http://web.archive.org/web/20210420195832/ [156] M.Maiboroda,“Anotherhugedefi-exploit,ankrprotocolattackedfor https://medium.com/easify-network/easyfi-security-incident-pre-pos 10 trillion abnbc tokens,” Website, Accessed: 08-08-2023, https://bo t-mortem-33f2942016e9. xmining.com/attack-on-ankr-abnbc/. [181] VaultSX,“Vaultsxhack:Lessonslearnedandotherthoughts,”Website, [157] PeckShield,“Uniswap/lendf.mehacks:Rootcauseandlossanalysis,” Accessed:08-08-2023, https://www.eosgo.io/news/vaultsx-hack-lessn Website, Accessed: 08-08-2023, https://peckshield.medium.com/unis os-learned-and-thoughts. wap-lendf-me-hacks-root-cause-and-loss-analysis-50f3263dcc09. [182] M. P. Anyswap), “Anyswap multichain router v3 exploit statement,” [158] M.Liu,“Urgent:Ousdwashackedandtherehasbeenalossoffunds,” Website, Accessed: 08-08-2023, https://medium.com/multichainorg/a Website,Accessed:08-08-2023, https://blog.originprotocol.com/urgent nyswap-multichain-router-v3-exploit-statement-6833f1b7e6fb. -ousd-has-hacked-and-there-has-been-a-loss-of-funds-7b8c4a7d534c. [183] S. Dollar, “Saddle finance loses over $10 million in hack,” Website, [159] J. Benson, “Grim finance hacked for $30 million in fantom tokens,” Accessed: 08-08-2023, https://safedollar.medium.com/safedollar-pos Website,Accessed:08-08-2023, https://decrypt.co/88727/grim-finance t-mortem-analysis-cb2769fe059. -hacked-30-million-fantom-tokens. [184] Halborn, “Explained: The badgerdao hack,” Website, Accessed: 08- [160] D. Lucid, “Rari capital ethereum pool — post-mortem,” Website, 08-2023, https://halborn.com/explained-the-badgerdao-hack-decembe Accessed: 08-08-2023, https://medium.com/rari-capital/5-8-2021-rar r-2021/. i-ethereum-pool-post-mortem-60aab6a6f8f9. [185] Wormhole, “Wormhole incident report,” Website, Accessed: 08-08- [161] C.Williams,“$80mlostinattackonraricapital,”Website,Accessed: 2023, https://wormholecrypto.medium.com/wormhole-incident-repor 08-08-2023, https://cryptobriefing.com/80m-lost-in-attack-on-rari-cap t-02-02-22-ad9b8f21eec6. ital/. [186] B. B. Sam Kessler, “Crypto bridge nomad drained of [162] CertiK, “Fei protocol incident analysis,” Website, Accessed: 08- nearly $200m in exploit,” Website, Accessed: 08-08-2023, 08-2023, https://certik.medium.com/fei-protocol-incident-analysi https://www.coindesk.com/tech/2022/08/02/nomad-bridge-drained s-8527440696cc. -of-nearly-200-million-in-exploit/.26 [187] Q. Initiative, “Cryptocurrency exchange hacks, frauds, and scams,” contracts,” in Proceedings of the 2019 ACM SIGSAC Conference on Website,Accessed:08-08-2023, https://www.quadrigainitiative.com/e ComputerandCommunicationsSecurity,2019,pp.531–548. ducation.php. [210] V.WüstholzandM.Christakis,“Harvey:Agreyboxfuzzerforsmart [188] P.Tsankov,A.Dan,D.Drachsler-Cohen,A.Gervais,F.Buenzli,and contracts,”inProceedingsofthe28thACMJointMeetingonEuropean M. Vechev, “Securify: Practical security analysis of smart contracts,” SoftwareEngineeringConferenceandSymposiumontheFoundations in Proceedings of the 2018 ACM SIGSAC Conference on Computer ofSoftwareEngineering,2020,pp.1398–1409. andCommunicationsSecurity. ACM,2018,pp.67–82. [211] C. F. Torres, A. K. Iannillo, A. Gervais, and R. State, “Confuzzius:
[189] ——,“Securify2,”Website,Accessed:08-08-2023, https://github.com Adatadependency-awarehybridfuzzerforsmartcontracts,”in2021 /eth-sri/securify2. IEEE European Symposium on Security and Privacy (EuroS&P). [190] S.So,M.Lee,J.Park,H.Lee,andH.Oh,“Verismart:Ahighlyprecise IEEE,2021,pp.103–119. safetyverifierforethereumsmartcontracts,”in2020IEEESymposium [212] T.D.Nguyen,L.H.Pham,J.Sun,Y.Lin,andQ.T.Minh,“sfuzz:An onSecurityandPrivacy(SP). IEEE,2020,pp.1678–1694. efficientadaptivefuzzerforsoliditysmartcontracts,”inProceedingsof [191] Y.Wang,S.K.Lahiri,S.Chen,R.Pan,I.Dillig,C.Born,andI.Naseer, theACM/IEEE42ndInternationalConferenceonSoftwareEngineer- “Formal specification and verification of smart contracts for azure ing,2020,pp.778–788. blockchain,”arXivpreprintarXiv:1812.08829,2018. [213] Y.Xue,J.Ye,W.Zhang,J.Sun,L.Ma,H.Wang,andJ.Zhao,“xfuzz: [192] S.Kalra,S.Goel,M.Dhawan,andS.Sharma,“Zeus:analyzingsafety Machinelearningguidedcross-contractfuzzing,”IEEETransactionson ofsmartcontracts.”inNdss,2018,pp.1–12. DependableandSecureComputing,pp.1–14,2022. [193] J. Chen, X. Xia, D. Lo, J. Grundy, X. Luo, and T. Chen, “De- [214] J. Choi, D. Kim, S. Kim, G. Grieco, A. Groce, and S. K. Cha, fectchecker: Automated smart contract defect detection by analyzing “Smartian:Enhancingsmartcontractfuzzingwithstaticanddynamic evmbytecode,”IEEETransactionsonSoftwareEngineering,vol.48, data-flowanalyses,”in202136thIEEE/ACMInternationalConference no.07,pp.2189–2207,2022. onAutomatedSoftwareEngineering(ASE). IEEE,2021,pp.227–239. [194] C. F. Torres, M. Steichen et al., “The art of the scam: Demystifying [215] J. Su, H.-N. Dai, L. Zhao, Z. Zheng, and X. Luo, “Effectively honeypots in ethereum smart contracts,” in 28th USENIX Security generating vulnerable transaction sequences in smart contracts with Symposium(USENIXSecurity19),2019,pp.1591–1607. reinforcement learning-guided fuzzing,” in Proceedings of the 37th [195] I. Nikolic´, A. Kolluri, I. Sergey, P. Saxena, and A. Hobor, “Finding IEEE/ACMInternationalConferenceonAutomatedSoftwareEngineer- thegreedy,prodigal,andsuicidalcontractsatscale,”inProceedingsof ing,ser.ASE’22,NewYork,NY,USA,2023. the34thannualcomputersecurityapplicationsconference,2018,pp. [216] Z. Liu, P. Qian, J. Yang, L. Liu, X. Xu, Q. He, and X. Zhang, 653–663. “Rethinkingsmartcontractfuzzing:Fuzzingwithinvocationordering [196] M. Mossberg, F. Manzano, E. Hennenfent, A. Groce, G. Grieco, and important branch revisiting,” IEEE Transactions on Information J. Feist, T. Brunson, and A. Dinaburg, “Manticore: A user-friendly ForensicsandSecurity,vol.18,pp.1237–1251,2023. symbolic execution framework for binaries and smart contracts,” in [217] C.Shou,S.Tan,andK.Sen,“Ityfuzz:Snapshot-basedfuzzerforsmart 201934thIEEE/ACMInternationalConferenceonAutomatedSoftware contract,” in Proceedings of the 32nd ACM SIGSOFT International Engineering(ASE). IEEE,2019,pp.1186–1189. Symposium on Software Testing and Analysis, ser. ISSTA 2023, New [197] B.Mueller,“Aframeworkforbughuntingontheethereumblockchain,” York,NY,USA,2023,p.322–333. Website, Accessed: 08-08-2023, https://github.com/ConsenSys/mythr [218] W.J.-W.Tann,X.J.Han,S.S.Gupta,andY.-S.Ong,“Towardssafer il. smart contracts: A sequence learning approach to detecting security [198] L. Luu, D.-H. Chu, H. Olickel, P. Saxena, and A. Hobor, “Making threats,”arXivpreprintarXiv:1811.06632,2018. smart contracts smarter,” in Proceedings of the 2016 ACM SIGSAC [219] P. Qian, Z. Liu, Q. He, R. Zimmermann, and X. Wang, “Towards conference on computer and communications security. ACM, 2016, automatedreentrancydetectionforsmartcontractsbasedonsequential pp.254–269. models,”IEEEAccess,vol.8,pp.19685–19695,2020. [199] C. F. Torres, J. Schütte, and R. State, “Osiris: Hunting for integer [220] W. Wang, J. Song, G. Xu, Y. Li, H. Wang, and C. Su, “Contract- bugsinethereumsmartcontracts,”inProceedingsofthe34thAnnual ward: Automated vulnerability detection models for ethereum smart ComputerSecurityApplicationsConference,2018,pp.664–676. contracts,” IEEE Transactions on Network Science and Engineering, [200] M. Rodler, W. Li, G. O. Karame, and L. Davi, “Sereum: Protecting vol.8,no.2,pp.1133–1144,2020. existing smart contracts against re-entrancy attacks,” arXiv preprint [221] H. Liu, C. Liu, W. Zhao, Y. Jiang, and J. Sun, “S-gram: towards arXiv:1812.05934,2018. semantic-aware security auditing for ethereum smart contracts,” in [201] J. Krupp and C. Rossow, “{teEther}: Gnawing at ethereum to auto- 201833rdIEEE/ACMInternationalConferenceonAutomatedSoftware maticallyexploitsmartcontracts,”in27thUSENIXSecuritySymposium Engineering(ASE). IEEE,2018,pp.814–819.
(USENIXSecurity18),2018,pp.1317–1333. [202] A. Permenev, D. Dimitrov, P. Tsankov, D. Drachsler-Cohen, and [222] Y. Zhuang, Z. Liu, P. Qian, Q. Liu, X. Wang, and Q. He, “Smart M.Vechev,“Verx:Safetyverificationofsmartcontracts,”in2020IEEE contractvulnerabilitydetectionusinggraphneuralnetwork,”inIJCAI, symposiumonsecurityandprivacy(SP). IEEE,2020,pp.1661–1677. 2020,pp.3283–3290. [203] E. Albert, P. Gordillo, B. Livshits, A. Rubio, and I. Sergey, “Ethir: [223] X.Yu,H.Zhao,B.Hou,Z.Ying,andB.Wu,“Deescvhunter:Adeep A framework for high-level analysis of ethereum bytecode,” in In- learning-based framework for smart contract vulnerability detection,” ternational symposium on automated technology for verification and in2021InternationalJointConferenceonNeuralNetworks(IJCNN), analysis. Springer,2018,pp.513–520. 2021,pp.1–8. [204] S. Tikhomirov, E. Voskresenskaya, I. Ivanitskiy, R. Takhaviev, [224] S.-J. Hwang, S.-H. Choi, J. Shin, and Y.-H. Choi, “Codenet: Code- E. Marchenko, and Y. Alexandrov, “Smartcheck: Static analysis of targeted convolutional neural network architecture for smart contract ethereum smart contracts,” in Proceedings of the 1st International vulnerability detection,” IEEE Access, vol. 10, pp. 32595–32607, WorkshoponEmergingTrendsinSoftwareEngineeringforBlockchain, 2022. 2018,pp.9–16. [225] W. Deng, H. Wei, T. Huang, C. Cao, Y. Peng, and X. Hu, “Smart [205] L. Brent, A. Jurisevic, M. Kong, E. Liu, F. Gauthier, V. Gramoli, contractvulnerabilitydetectionbasedondeeplearningandmultimodal R. Holz, and B. Scholz, “Vandal: A scalable security analysis frame- decisionfusion,”Sensors,vol.23,no.16,2023. workforsmartcontracts,”arXivpreprintarXiv:1809.03981,2018. [226] T. Durieux, J. F. Ferreira, R. Abreu, and P. Cruz, “Empirical review [206] H. Wang, Y. Liu, Y. Li, S.-W. Lin, C. Artho, L. Ma, and Y. Liu, of automated analysis tools on 47,587 ethereum smart contracts,” “Oracle-supported dynamic exploit generation for smart contracts,” in Proceedings of the ACM/IEEE 42nd International conference on IEEETransactionsonDependableandSecureComputing,2020. softwareengineering,2020,pp.530–541. [207] H. Wang, Y. Li, S.-W. Lin, L. Ma, and Y. Liu, “Vultron: catching [227] M. Ren, Z. Yin, F. Ma, Z. Xu, Y. Jiang, C. Sun, H. Li, and Y. Cai, vulnerablesmartcontractsonceandforall,”in2019IEEE/ACM41st “Empirical evaluation of smart contract testing: What is the best International Conference on Software Engineering: New Ideas and choice?” in Proceedings of the 30th ACM SIGSOFT International EmergingResults(ICSE-NIER). IEEE,2019,pp.1–4. SymposiumonSoftwareTestingandAnalysis,ser.ISSTA2021,2021, [208] C.Liu,H.Liu,Z.Cao,Z.Chen,B.Chen,andB.Roscoe,“Reguard: p.566–579. finding reentrancy bugs in smart contracts,” in 2018 IEEE/ACM 40th [228] K. Bhargavan, A. Delignat-Lavaud, C. Fournet, A. Gollamudi, InternationalConferenceonSoftwareEngineering:Companion(ICSE- G. Gonthier, N. Kobeissi, N. Kulatova, A. Rastogi, T. Sibut-Pinote, Companion). IEEE,2018,pp.65–68. N. Swamy et al., “Formal verification of smart contracts: Short [209] J. He, M. Balunovic´, N. Ambroladze, P. Tsankov, and M. Vechev, paper,” in Proceedings of the 2016 ACM Workshop on Programming “Learning to fuzz from symbolic execution with application to smart LanguagesandAnalysisforSecurity. ACM,2016,pp.91–96.27 [229] Z. Yang, H. Liu, Y. Li, H. Zheng, L. Wang, and B. Chen, “Seraph: [250] X. L. Yu, O. Al-Bataineh, D. Lo, and A. Roychoudhury, “Smart enabling cross-platform security analysis for evm and wasm smart contract repair,” ACM Trans. Softw. Eng. Methodol., vol. 29, no. 4, contracts,” in 2020 IEEE/ACM 42nd International Conference on 2020. Software Engineering: Companion Proceedings (ICSE-Companion). [251] Y. Zhang, S. Ma, J. Li, K. Li, S. Nepal, and D. Gu, “Smartshield: IEEE,2020,pp.21–24. Automatic smart contract protection made easy,” in 2020 IEEE 27th [230] J. S. Reis, P. Crocker, and S. M. de Sousa, “Tezla, an intermediate InternationalConferenceonSoftwareAnalysis,EvolutionandReengi- representationforstaticanalysisofmichelsonsmartcontracts,”in2nd neering(SANER). IEEE,2020,pp.23–34. WorkshoponFormalMethodsforBlockchains,2020. [252] T. D. Nguyen, L. H. Pham, and J. Sun, “Sguard: towards fixing [231] Y. Murray and D. A. Anisi, “Survey of formal verification methods vulnerable smart contracts automatically,” in 2021 IEEE Symposium for smart contracts on blockchain,” in 2019 10th IFIP International onSecurityandPrivacy(SP). IEEE,2021,pp.1215–1229. Conference on New Technologies, Mobility and Security (NTMS). [253] M.Rodler,W.Li,G.O.Karame,andL.Davi,“{EVMPatch}:Timely IEEE,2019,pp.1–6. andautomatedpatchingofethereumsmartcontracts,”in30thUSENIX [232] R. Gu, R. Marinescu, C. Seceleanu, and K. Lundqvist, “Formal SecuritySymposium(USENIXSecurity21),2021,pp.1289–1306.
verification of an autonomous wheel loader by model checking,” in [254] H. Jin, Z. Wang, M. Wen, W. Dai, Y. Zhu, and D. Zou, “Aroc: Proceedings of the 6th Conference on Formal Methods in Software An automatic repair framework for on-chain smart contracts,” IEEE Engineering,2018,pp.74–83. TransactionsonSoftwareEngineering,vol.48,no.11,pp.4611–4629, [233] J.Liu,B.Zhan,S.Wang,S.Ying,T.Liu,Y.Li,M.Ying,andN.Zhan, 2021. “Formal verification of quantum algorithms using quantum hoare [255] J.-R. Giesen, S. Andreina, M. Rodler, G. O. Karame, and logic,” in International conference on computer aided verification. L. Davi, “Practical mitigation ofsmart contract bugs,” arXiv preprint Springer,2019,pp.187–207. arXiv:2203.00364,2022. [234] R. Baldoni, E. Coppa, D. C. D’elia, C. Demetrescu, and I. Finocchi, [256] C. Ferreira Torres, H. Jonker, and R. State, “Elysium: Context- “Asurveyofsymbolicexecutiontechniques,”ACMComputingSurveys aware bytecode-level patching to automatically heal vulnerable smart (CSUR),vol.51,no.3,pp.1–39,2018. contracts,” in Proceedings of the 25th International Symposium on [235] ConsenSys,“Consensys:amarket-leadingblockchaintechnologycom- ResearchinAttacks,IntrusionsandDefenses,2022,pp.115–128. pany.”Website,Accessed:08-08-2023, https://consensys.net. [257] P.Tolmach,Y.Li,andS.-W.Lin,“Property-basedautomatedrepairof defi protocols,” in Proceedings of the 37th IEEE/ACM International [236] G. A. Pierro and R. Tonelli, “Analysis of source code duplication in ConferenceonAutomatedSoftwareEngineering,2022,pp.1–5. ethreum smart contracts,” in 2021 IEEE International Conference on Software Analysis, Evolution and Reengineering (SANER). IEEE, [258] S.Eskandari,S.Moosavi,andJ.Clark,“Sok:Transparentdishonesty: 2021,pp.701–707. front-running attacks on blockchain,” in International Conference on FinancialCryptographyandDataSecurity. Springer,2019,pp.170– [237] X.Li,T.Chen,X.Luo,T.Zhang,L.Yu,andZ.Xu,“Stan:Towards 189. describing bytecodes of smart contract,” in 2020 IEEE 20th Interna- [259] K. Babel, P. Daian, M. Kelkar, and A. Juels, “Clockwork finance: tionalConferenceonSoftwareQuality,ReliabilityandSecurity(QRS). Automated analysis of economic security in smart contracts,” arXiv IEEE,2020,pp.273–284. preprintarXiv:2109.04347,2021. [238] S.Bistarelli,G.Mazzante,M.Micheletti,L.Mostarda,D.Sestili,and [260] M. Boussard, S. Papillon, P. Peloso, M. Signorini, and E. Waisbard, F. Tiezzi, “Ethereum smart contracts: Analysis and statistics of their “Steward: Sdn and blockchain-based trust evaluation for automated sourcecodeandopcodes,”InternetofThings,vol.11,p.100198,2020. risk management on iot devices,” in IEEE INFOCOM 2019-IEEE [239] N.Lu,B.Wang,Y.Zhang,W.Shi,andC.Esposito,“Neucheck:Amore Conference on Computer Communications Workshops (INFOCOM practical ethereum smart contract security analysis tool,” Software: WKSHPS). IEEE,2019,pp.841–846. PracticeandExperience,vol.51,no.10,pp.2065–2084,2021. [261] L.JordanandC.Jack,“Defiscore:Anopenframeworkforevaluating [240] N. Grech, L. Brent, B. Scholz, and Y. Smaragdakis, “Gigahorse: defiprotocols,”Website,Accessed:08-08-2023, https://github.com/C thorough, declarative decompilation of smart contracts,” in 2019 onsenSys/defi-score. IEEE/ACM 41st International Conference on Software Engineering [262] H. Rex, H. Lucas, A. Mohamed, D. David, S. Nick, V. Nic, and (ICSE). IEEE,2019,pp.1176–1186. C. Carter, “Defi-safety is an independent ratings organization that [241] V. Pérez, M. Klemen, P. López-García, J. F. Morales, and evaluates decentralized finance products,” Website, Accessed: 08-08- M.Hermenegildo,“Costanalysisofsmartcontractsviaparametricre- 2023, https://www.defisafety.com/. sourceanalysis,”inInternationalStaticAnalysisSymposium. Springer, [263] BlockSec, “Deposit less, get more: ycredit attack details,” Website, 2020,pp.7–31. Accessed: 08-08-2023, https://blocksecteam.medium.com/deposit-les [242] V.J.Manès,H.Han,C.Han,S.K.Cha,M.Egele,E.J.Schwartz,and s-get-more-ycredit-attack-details-f589f71674c3. M.Woo,“Theart,science,andengineeringoffuzzing:Asurvey,”IEEE [264] Opyn,“Opynethputexploitpostmortem,”Website,Accessed:08-08- TransactionsonSoftwareEngineering,vol.47,no.11,pp.2312–2331, 2023, https://medium.com/opyn/opyn-eth-put-exploit-post-mortem-1a 2019. 009e3347a8. [243] Y.Zheng,A.Davanian,H.Yin,C.Song,H.Zhu,andL.Sun,“Firm-afl: [265] S.Chaliasos,M.A.Charalambous,L.Zhou,R.Galanopoulou,A.Ger- high-throughput greybox fuzzing of iot firmware via augmented pro- vais,D.Mitropoulos,andB.Livshits,“Smartcontractanddefisecurity: cess emulation,” in 28th {USENIX} Security Symposium ({USENIX} Insightsfromtoolevaluationsandpractitionersurveys,”2023. Security19),2019,pp.1099–1114.
[266] E. Heilman, A. Kendler, A. Zohar, and S. Goldberg, “Eclipse attacks [244] M. Böhme, V.-T. Pham, M.-D. Nguyen, and A. Roychoudhury, “Di- on {Bitcoin’s}{Peer-to-Peer} network,” in 24th USENIX Security rected greybox fuzzing,” in Proceedings of the 2017 ACM SIGSAC Symposium(USENIXSecurity15),2015,pp.129–144. Conference on Computer and Communications Security, 2017, pp. [267] A. Gervais, G. O. Karame, K. Wüst, V. Glykantzis, H. Ritzdorf, 2329–2344. and S. Capkun, “On the security and performance of proof of work [245] W.Xu,H.Moon,S.Kashyap,P.-N.Tseng,andT.Kim,“Fuzzingfile blockchains,”inProceedingsofthe2016ACMSIGSACconferenceon systems via two-dimensional input space exploration,” in 2019 IEEE computerandcommunicationssecurity,2016,pp.3–16. SymposiumonSecurityandPrivacy(SP). IEEE,2019,pp.818–834. [268] R.ZhangandB.Preneel,“Laydownthecommonmetrics:Evaluating [246] Z.Li,D.Zou,S.Xu,X.Ou,H.Jin,S.Wang,Z.Deng,andY.Zhong, proof-of-workconsensusprotocols’security,”in2019IEEESymposium “Vuldeepecker:Adeeplearning-basedsystemforvulnerabilitydetec- onSecurityandPrivacy(SP). IEEE,2019,pp.175–192. tion,”arXivpreprintarXiv:1801.01681,2018. [269] C. Hou, M. Zhou, Y. Ji, P. Daian, F. Tramer, G. Fanti, and [247] G.Lin,S.Wen,Q.-L.Han,J.Zhang,andY.Xiang,“Softwarevulner- A. Juels, “Squirrl: Automating attack analysis on blockchain incen- abilitydetectionusingdeepneuralnetworks:asurvey,”Proceedingsof tive mechanisms with deep reinforcement learning,” arXiv preprint theIEEE,vol.108,no.10,pp.1825–1848,2020. arXiv:1912.01798,2019. [248] S. Chakraborty, R. Krishna, Y. Ding, and B. Ray, “Deep learning [270] S. Ahn, T. Kim, Y. Kwon, and S. Cho, “Packet aggregation scheme based vulnerability detection: Are we there yet?” IEEE Transactions to mitigate the network congestion in blockchain networks,” in 2020 onSoftwareEngineering,vol.48,no.09,pp.3280–3296,2022. International Conference on Electronics, Information, and Communi- [249] D. Zou, S. Wang, S. Xu, Z. Li, and H. Jin, “Vuldeepecker: A deep cation(ICEIC). IEEE,2020,pp.1–3. learning-based system for multiclass vulnerability detection,” IEEE [271] L. Zhou, K. Qin, and A. Gervais, “A2mm: Mitigating frontrunning, Transactions on Dependable and Secure Computing, vol. 18, no. 5, transaction reordering and consensus instability in decentralized ex- pp.2224–2236,2019. changes,”arXivpreprintarXiv:2106.07371,2021.28 [272] L.Su,X.Shen,X.Du,X.Liao,X.Wang,L.Xing,andB.Liu,“Evilun- derthesun:Understandinganddiscoveringattacksonethereumdecen- tralized applications,” in 30th USENIX Security Symposium (USENIX Security21),2021,pp.1307–1324. [273] Flashbots, “Everything there is to know about flashbots,” Website, Accessed:08-08-2023, https://github.com/flashbots/pm. [274] A. Obadia, “Flashbots: Frontrunning the mev crisis,” Website, Ac- cessed:08-08-2023, https://medium.com/flashbots/frontrunning-the-m ev-crisis-40629a613752. [275] A.Thurman,“Valuedefiprotocolsuffers$6millionflashloanexploit (2020),”Website,Accessed:08-08-2023, https://cointelegraph.com/ne ws/value-defi-protocol-suffers-6-million-flash-loan-exploit. [276] W.C.Gu,A.Raghuvanshi,andD.Boneh,“Empiricalmeasurementson pricingoraclesanddecentralizedgovernanceforstablecoins,”Available atSSRN3611231,2020. [277] L. Xu, N. Shah, L. Chen, N. Diallo, Z. Gao, Y. Lu, and W. Shi, “Enabling the sharing economy: Privacy respecting contract based on public blockchain,” in Proceedings of the ACM Workshop on Blockchain,CryptocurrenciesandContracts,2017,pp.15–21. [278] S. Chu, Y. Xia, and Z. Zhang, “Manta: a plug and play private defi stack,”CryptologyePrintArchive,2021. [279] W. Dai, “Flexible anonymous transactions (flax): Towards privacy- preserving and composable decentralized finance,” Cryptology ePrint Archive,2021. [280] T. Xie, J. Zhang, Y. Zhang, C. Papamanthou, and D. Song, “Libra: Succinctzero-knowledgeproofswithoptimalprovercomputation,”in AnnualInternationalCryptologyConference. Springer,2019,pp.733– 764. [281] E.Boyle,N.Gilboa,Y.Ishai,andA.Nof,“Practicalfullysecurethree- partycomputationviasublineardistributedzero-knowledgeproofs,”in Proceedingsofthe2019ACMSIGSACConferenceonComputerand CommunicationsSecurity,2019,pp.869–886. [282] D. Reich, A. Todoki, R. Dowsley, M. De Cock et al., “Privacy- preservingclassificationofpersonaltextmessageswithsecuremulti- party computation,” Advances in Neural Information Processing Sys- tems,vol.32,2019. [283] F.BayatbabolghaniandM.Blanton,“Securemulti-partycomputation,” inProceedingsofthe2018ACMSIGSACConferenceonComputerand CommunicationsSecurity,2018,pp.2157–2159.
2309.05520 When ChatGPT Meets Smart Contract Vulnerability Detection: How Far Are We? CHONGCHEN, SunYat-senUniversity,ChinaandTheStateKeyLaboratoryofBlockchainandData Security,ZhejiangUniversity,China JIANZHONGSU, SunYat-senUniversity,China JIACHI CHEN∗, SunYat-senUniversity,ChinaandTheStateKeyLaboratoryofBlockchainandData Security,ZhejiangUniversity,China YANLINWANG, SunYat-senUniversity,China TINGTINGBI, UniversityofWesternAustralia,Australia JIANXINGYU, SunYat-senUniversity,China YANLIWANG, SunYat-senUniversity,China XINGWEILIN, ZhejiangUniversity,China TINGCHEN, UniversityofElectronicScienceandTechnologyofChina,China ZIBINZHENG, SunYat-senUniversity,China Withthedevelopmentofblockchaintechnology,smartcontractshavebecomeanimportantcomponent ofblockchainapplications.Despitetheircrucialrole,thedevelopmentofsmartcontractsmayintroduce vulnerabilitiesandpotentiallyleadtosevereconsequences,suchasfinanciallosses.Meanwhile,largelanguage models,representedbyChatGPT,havegainedgreatattentions,showcasinggreatcapabilitiesincodeanalysis tasks.Inthispaper,wepresentedanempiricalstudytoinvestigatetheperformanceofChatGPTinidentifying smart contract vulnerabilities. Initially, we evaluated ChatGPT’s effectiveness using a publicly available smartcontractdataset.OurfindingsdiscoverthatwhileChatGPTachievesahighrecallrate,itsprecision inpinpointingsmartcontractvulnerabilitiesislimited.Furthermore,ChatGPT’sperformancevarieswhen detectingdifferentvulnerabilitytypes.Wedelvedintotherootcausesforthefalsepositivesgeneratedby ChatGPT,andcategorizedthemintofourgroups.Second,bycomparingChatGPTwithotherstate-of-the-art smartcontractvulnerabilitydetectiontools,wefoundthatChatGPT’sF-scoreislowerthanothersfor3out ofthe7vulnerabilities.Inthecaseoftheremaining4vulnerabilities,ChatGPTexhibitsaslightadvantage overthesetools.Finally,weanalyzedthelimitationofChatGPTinsmartcontractvulnerabilitydetection, revealingthattherobustnessofChatGPTinthisfieldneedstobeimprovedfromtwoaspects:itsuncertainty inansweringquestions;andthelimitedlengthofthedetectedcode.Ingeneral,ourresearchprovidesinsights ∗correspondingauthor Authors’addresses:ChongChen,SunYat-senUniversity,ChinaandTheStateKeyLaboratoryofBlockchainandData Security,ZhejiangUniversity,China,chench578@mail2.sysu.edu.cn;JianzhongSu,SunYat-senUniversity,China,sujzh3@ mail2.sysu.edu.cn;JiachiChen,SunYat-senUniversity,ChinaandTheStateKeyLaboratoryofBlockchainandDataSecurity, ZhejiangUniversity,China,chenjch86@mail.sysu.edu.cn;YanlinWang,SunYat-senUniversity,China,wangylin36@mail. sysu.edu.cn;TingtingBi,UniversityofWesternAustralia,Australia,Tingting.Bi@uwa.edu.au;JianxingYu,SunYat-sen University,China,yujx26@mail.sysu.edu.cn;YanliWang,SunYat-senUniversity,China,wangyli58@mail2.sysu.edu.cn; XingweiLin,ZhejiangUniversity,China,xwlin.roy@gmail.com;TingChen,UniversityofElectronicScienceandTechnology ofChina,China,brokendragon@uestc.edu.cn;ZibinZheng,SunYat-senUniversity,China,zhzibin@mail.sysu.edu.cn. Permissiontomakedigitalorhardcopiesofallorpartofthisworkforpersonalorclassroomuseisgrantedwithoutfee providedthatcopiesarenotmadeordistributedforprofitorcommercialadvantageandthatcopiesbearthisnoticeand thefullcitationonthefirstpage.CopyrightsforcomponentsofthisworkownedbyothersthanACMmustbehonored. Abstractingwithcreditispermitted.Tocopyotherwise,orrepublish,topostonserversortoredistributetolists,requires priorspecificpermissionand/orafee.Requestpermissionsfrompermissions@acm.org. ©2024AssociationforComputingMachinery. 1049-331X/2024/8-ART$15.00 https://doi.org/10.1145/nnnnnnn.nnnnnnn ACMTrans.Softw.Eng.Methodol.,Vol.1,No.1,Article.Publicationdate:August2024. 4202 guA 12 ]ES.sc[ 4v02550.9032:viXraintothestrengthsandweaknessesofemployinglargelanguagemodels,specificallyChatGPT,forthedetection ofsmartcontractvulnerabilities. AdditionalKeyWordsandPhrases:EmpiricalStudy,SmartContracts,LargeLanguageModels,ChatGPT, Vulnerabilities ACMReferenceFormat: ChongChen,JianzhongSu,JiachiChen,YanlinWang,TingtingBi,JianxingYu,YanliWang,XingweiLin,Ting Chen,andZibinZheng.2024.WhenChatGPTMeetsSmartContractVulnerabilityDetection:HowFarAre We?.ACMTrans.Softw.Eng.Methodol.1,1(August2024),30pages.https://doi.org/10.1145/nnnnnnn.nnnnnnn 1 INTRODUCTION Inrecentyears,withtherapiddevelopmentofblockchainplatforms(e.g.,Ethereum),smartcon- tractshavebeenwidelyadoptedinvariousdomains[81].However,thesecurityissuesarising fromsmartcontractvulnerabilitieshavealsoresultedinsignificanteconomiclosses[61].These securityconcernsnotonlydirectlyharmusers’funds,butalsohaveadverseeffectsontheoverall developmentoftheblockchainecosystem.Therefore,detectingvulnerabilitiesinsmartcontracts hasbecomeanimportanttaskinrecentyears. Meanwhile,theintroductionofChatGPT[50],aLargeLanguageModel(LLM)developedby the OpenAI team [68], has made a significant impact in various fields. ChatGPT’s potential in
computerprogramminghasattractedsignificantattentioninrecentresearch[6].Somerecentstudies haveexploredtheapplicabilityofLLMinvulnerabilitydetection[39,62].Whiletherehasbeen considerableanalysisofChatGPT’scodecapabilitiesinpreviouswork,researchonsmartcontract vulnerabilitydetectionremainsrelativelylimited.InadditiontoChatGPT,commonLLMmodels includeLLaMA[73]andPaLM2[4].LLaMAisacollectionoffoundationlanguagemodelsranging from7Bto65Bparameters.PaLM2isalargelanguagemodelthatbuildsonGoogle’s[67]legacyof breakthroughresearchinmachinelearningandresponsibleartificialintelligence.Consideringthat GPT[51]wasamongthefirstcommerciallyavailablelargelanguagemodelsandcontinuestobe widelyused,itwasourchoiceforthisresearch. Inthiswork,weembarkedonempiricalresearchfocusedonsmartcontractvulnerabilityde- tectionusingChatGPT.ToexplorethecapabilitiesofChatGPTinanalyzing,understanding,and detecting smart contract vulnerabilities, we conducted an empirical study on its effectiveness, limitations,andcomparisonwithotherstate-of-the-artsmartcontractvulnerabilitydetectiontools. InourexplorationofusingtheGPTmodelforsmartcontractvulnerabilitydetection,weinitiated theassessmentbyevaluatingitseffectivenessusingthewildely-usedsmartbugsdataset[16].Sub- sequently,weconductedacomparativeanalysisofthedetectionperformanceoftheGPTmodel against14otherSOTAtools.Lastly,weexaminedthelimitationsassociatedwithapplyingGPTin therealmofsmartcontractvulnerabilitydetection.Figure1providesanoverviewofourresearch methodology.Wefocusonthefollowingresearchquestions: RQ1.HoweffectiveisChatGPTindetectingvulnerabilitiesinsmartcontracts? Weselectedthewidely-usedsmartbugs-curateddataset[16],whichcomprises142vulnerable smartcontracts.ThedatasetcontainsninecategoriesofvulnerabilitiesasdescribedinDASP10[78]. WedesignedapromptforChatGPTtodetecttheseninecategoriesofvulnerability.Theeffectiveness ofvulnerabilitydetectionisevaluatedthroughvariousmetrics(i.e.,precision,recall,andF-score). OurfindingsindicatedthatwhileChatGPTachievesapromisingrecallrate(i.e.,51.4%,83.6%and 88.2%forGPT-3.5,GPT-4oandGPT-4,respectively),itsprecisioninpinpointingsmartcontract vulnerabilitiesisrelativelylow(19.7%,20.2%and22.6%forGPT-3.5,GPT-4oandGPT-4,respectively). Inaddition,thedetectionperformanceofChatGPTvariesacrossdifferenttypesofvulnerabilities. Forexample,GPT-3.5,GPT-4oandGPT-4allperformwellindetectingUncheckedReturnValues[29],WhenChatGPTMeetsSmartContractVulnerabilityDetection:HowFarAreWe? 3 Non-binary Reentrancy Binary GPT-3.5-turbo Prompt Formalization & GPT-4o … Effectiveness & GPT-4 Short Address RQ1 Attack Oyente Vulnerability Detect Smart Contract RQ2 Selection Detection ChatGPT Other Tools … Comparison Vulnerabilities Slither RQ3 Reproducibility Sampling GPT-3.5-turbo Testing Dataset & GPT-4o Limitation & GPT-4 Fig.1. Theoverviewofourresearch. however,allofthemperformpoorlyinidentifyingShortAddressAttack [10].Furthermore,we conductedasystematicanalysisoffalsepositiveswithinChatGPT,categorizingtheminto4distinct types:ProtectedMechanismBias,DevelopmentIntentBias,InterferedbyCommentsandInterference withDeadCode. RQ2.HowdoesChatGPTperformcomparedtoothertools? In RQ1, we focus only on ChatGPT’s effective in detecting certain vulnerabilities. To fully understandthelevelofcapabilityofChatGPT,itisimportanttocompareitsperformanceagainst otherstate-of-the-arttools.Throughcomparativeanalysis,wecanelucidatetherelativestrengths andlimitationsofChatGPTwithinthedomainofvulnerabilitydetection,therebyprovidinginsights to inform future tool selection and development efforts. To evaluate ChatGPT’s performance comparedtootherstate-of-the-artsmartcontractvulnerabilitydetectiontools,weemployed14 vulnerabilitytools(e.g.,Mythril[12]andConfuzzius[70])onthesamesmartbugs-curated[16] dataset.OurresultsshowthatalthoughChatGPToutperformedother14toolsindetectingspecific vulnerabilitieslikeFrontRunninganddenialofservice,theF1scoresarerelativelylow,measuring only12.8%and15.9%,respectively.Forothervulnerabilitytypes,severaltoolsdemonstratemore effective detection capabilities than ChatGPT. However, in terms of detection speed, ChatGPT surpassesallothertools.Still,ChatGPT’sdetectionfailureratesurpassesthatof10othertools,due tothetokenlimitationsoflargelanguagemodels. RQ3.WhatarethelimitationsofChatGPTindetectingsmartcontractvulnerabilities? Asanartificialintelligencedialoguemodel,ChatGPTmayproducedifferentvulnerabilityde- tection results for the same smart contract when provided with the same prompt, potentially diminishingitsreliability.Toevaluateitsreliability,werandomlysampled50smartcontractsin thesmartbugs-curated[16]datasetandconductedvulnerabilitydetectiononthemforfivetimes withthesameprompt.Ouranalysisshowedthatonly29outof50contractsdisplayedentirely consistentresultsacrossallfiveroundofdetection.Thissuggeststhat42%oftheevaluatedsmart contractsexhibitunstabledetectionoutcomes.Additionally,theofficialdocumentationspecifies
themaximumtokenlimitthattheGPTmodelcanhandle.However,itdoesnotprovideprecise informationaboutlimitoftheassociatedcodesize,leavingdeveloperswithoutclearguidanceon thisaspect.Asaresult,weconductedexperimentsonboththegpt-3.5-turboandgpt-4modelsto approximatethemaximumcodesizetheycanaccommodate. Wesummarizedourmaincontributionsasfollows:ChongChen,JianzhongSu,JiachiChen,YanlinWang,TingtingBi,JianxingYu,YanliWang,XingweiLin,TingChen, 4 andZibinZheng • Weappliedthegpt-3.5-turbo,thegpt-4oandthegpt-4modeltoperformvulnerabilitydetec- tiononthesmartbugs-curateddatasettoevaluatetheireffectiveness.Weprovidedevidence thatChatGPThasdifferentdetectionperformancefordifferentvulnerabilities,witharel- atively high recall rate but low precision. We also summarized 4 root causes of the false positivesgeneratedbyChatGPT. • We compared ChatGPT with 14 smart contract vulnerability detection tools in terms of effectivenessandefficiency.Byconductingtestson142smartcontracts,weidentifiedtwo keyinsightsintothestrengthsandlimitationsofChatGPT.Theseinsightsrepresentvalu- ablecontributionstotheongoingresearchinleveraginglargelanguagemodels(LLM)for vulnerabilitydetection. • WeevaluatdedstabilityofChatGPTindetectingsmartcontractvulnerabilities,revealingthat itisstilluncertainingeneratingresultsofvulnerabilitydetection.Additionally,weestimated themaximumcodesizethatcanbeaccommodatedbybothgpt-3.5-turboandgpt-4. • Wemadeallexperimentaldatapublicly(i.e.,Zenodorepository:https://zenodo.org/record/ 8332273.),whichcouldprovideaguidelinefordevelopersandresearcherstoconductthe similarexperimentsforsmartcontactvulnerabilitydetection. Theorganizationoftherestofthispaperisasfollows.InSection2,weprovidedbackground informationonsmartcontractsandsomecommonvulnerabilitiesinthem.InSections3,4,and5, weelaboratedontheexperimentsandconclusionsofeachRQindetail.Specifically,inSection3, weelaboratedontheresearchontheeffectivenessofChatGPTindetectingsmartcontractvul- nerabilities.InSection4,wecomparedtheperformanceofChatGPTwithmultiplecurrentsmart contractvulnerabilitydetectiontoolsonthesamedataset.InSection5,weconductedresearchon thelimitationsofChatGPTindetectingsmartcontractvulnerabilities.InSection6,someaspectsof thisstudyarediscussed.InSection7,wepresentedsomerelatedwork.InSection8,wesummarized thisstudyandprovidefutureprospects. 2 BACKGROUND Inthissection,webrieflyintroducedbackgroundinformationaboutsmartcontractsandsome commonvulnerabilities. 2.1 SmartContract Smartcontractsareautomatedexecutionprotocolsbasedonblockchaintechnology,whoseresults canbewidelyrecognizedandagreedupon.Theconceptofsmartcontractswasinitiallyintroduced bySzaboin1997[66].Thisconceptdescribessmartcontractsasprogramsthatfacilitatedigital verification without the need for trust and are self-executing. Accordingly, unlike traditional programs,smartcontractscanbeexecutedwithouttheinvolvementofarbitratorsorthird-party institutions.Smartcontractsaretypicallydevelopedusinghigh-levelprogramminglanguages,such asSolidity[13],themostpopularlanguageforprogrammingEthereumsmartcontracts. 2.2 SmartContractVulnerabilities Smartcontractvulnerabilitiesrefertosecurityflawsorloopholespresentinthesmartcontract, whichcanbeexploitedtomanipulatecontractrulesorstealassets[31].Duetotheimmubilityof blockchian,oncethesmartcontractisdeployedontheblockchain,thecodecannotbechanged anymore,eventhevulnerabilityisdetected.Therefore,itmaybemaliciouslyexploitedorcause irreparableeconomiclosses[61].WhenChatGPTMeetsSmartContractVulnerabilityDetection:HowFarAreWe? 5 Table 1. Top 9 smart contract vulnerabilities in DASP10 and their corresponding descriptions and lev- els(“Solidity” level vulnerabilities are issues in how the contract is coded. “EVM” level ones come from theEVMexecutionmodel.“Blockchain”levelonesareinherenttopublicblockchains.) Vulnerability Description Level Reentrancy(RE) Reentrantfunctioncallsmakeacontracttobehaveinanunexpectedway Solidity AccessControl(AC) Failuretousefunctionmodifiersoruseoftx.origin Solidity ArithmeticIssues(AI) Integerover/underflows Solidity UncheckedReturnValues(UR) call(),callcode(),delegatecall()orsend()failsanditisnotchecked Solidity DenialOfService(DoS) Thecontractisoverwhelmedwithtime-consumingcomputations Solidity BadRandomness(BR) Maliciousminerbiasestheoutcome Blockchain FrontRunning(FR) Twodependenttransactionsthatinvokethesamecontractareincludedinoneblock Blockchain TimeManipulation(TM) Thetimestampoftheblockismanipulatedbytheminer Blockchain ShortAddressAttack(SAA) EVMitselfacceptsincorrectlypaddedarguments EVM DASP[78](DecentralizedApplicationSecurityProject)isaninitiativeoftheNationalComputing Centre(NCC)Group.Itisanopenandcollaborativeprojecttojoineffortstodiscoversmartcontract vulnerabilitieswithinthesecuritycommunity.DASP10introduces10commonvulnerabilitiesin smartcontracts,suchasreentrancy,accesscontrol,etc.Table1liststhetop9vulnerabilitiesinthis list.The10thtypeofvulnerability,knownasUnknownUnknowns,referstoothervulnerabilities
thatmayoccurduringiterativeupdatesofsmartcontractsandwillnotbediscussedfurtherhere. Smartbugs-curateddataset[16]isbasedontheDASPtaxonomy.Itprovidesacollectionofvul- nerableSoliditysmartcontractsorganizedaccordingtotheDASPtaxonomy,asshowninTable1. Thefirstcolumnofthetableisthevulnerabilityname,thesecondcolumnisthecorresponding description,andthethirdcolumnistheseveritylevel.Specifically,Smartbugs-curatedisadataset providedbytheSmartbugsprojectteamcontaining142smartcontracts,eachcontractcodelabeled withthespecifiedvulnerabilitytype.Thesecontractshavecertainrepresentativenessandimpor- tanceandcanbeusedtotestandverifytheeffectivenessofvulnerabilitydetectiontools.There aremultiplesourcesofcontractsinthedataset,includingEthereumandotherpublicblockchain applications.OurresearchisbasedontheDASP10andsmartbugs-curateddatasets. 2.3 ChatGPT LargeLanguageModels(LLMs)representapivotaladvancementinnaturallanguageprocessing (NLP),revolutionizingvarioustasksliketextgeneration,questionanswering,anddialoguesystems. Amongthese,ChatGPT[50],developedbyOpenAI[68],standsoutasaleadingLLM,buildingupon thesuccessesoftheGPTseries,notablyGPT-3.5andGPT-4[50].WhilenumerousLLMscontinue toemerge,includingChatGLM[15],Xunfei-Xinghuo[3],andChatYuan-Large[1],etc.,studies indicatethatChatGPTconsistentlyoutperformsthesemodelsintermsofperformanceacrossmost tasks[80]. ChatGPT [50] is a large language model developed by OpenAI [68] company, which is an upgradedproductoftheGPT[51]seriesofmodels.ChatGPTusesdeeplearningstructuressuchas transformers[40]topre-trainandlearnthestatisticallawsoflanguageonlarge-scaletextdatasets. Onthisbasis,performtaskfine-tuningtogainpowerfullanguageprocessingcapabilitiessuchas textgeneration,questionanswering,anddialogue.Duringthetrainingprocess,ChatGPTcollected alargeamountoftextdatafromtheInternet.ThecoreprincipleofChatGPTistheuseofthe Transformer[40]architecture,whichisanadvancedneuralnetworkstructurethatenablesthe modeltounderstandcontext,capturesemanticcorrelations,andexhibitimpressiveintelligence whenansweringquestionsorgeneratingtext.TheemergenceofChatGPTmarksfurtherprogress inlanguageunderstandingandthegenerationoflargemodels.Currently,therearetwowidely usedmodelsfortheGPTseries:GPT-3.5andGPT-4.ChongChen,JianzhongSu,JiachiChen,YanlinWang,TingtingBi,JianxingYu,YanliWang,XingweiLin,TingChen, 6 andZibinZheng GPT-3.5.GPT-3.5isanupgradedversionofGPT-3withfewerparametersthatincludesafine-tuning processformachinelearningalgorithms[42].Thefine-tuningprocessinvolvesReinforcement Learning[35]withhumanfeedback,whichhelpstoimprovetheaccuracyandeffectivenessofthe algorithms.Themostcapableandcost-effectivemodelintheGPT-3.5familyisgpt-3.5-turbowhich hasbeenoptimizedforchat,butalsoworkswellfortraditionalcompletiontasks[48]. GPT-4.LikepreviousGPTmodels,theGPT-4basemodelwastrainedtopredictthenextword in a document and was trained using publicly available data (such as internet data) and data theOpenAIteamhaslicensed[52].Moreover,itisalarge-scalemultimodalmodelthataccepts input of image and text and outputs text [50]. The GPT-4 model has a larger model size (1.76 trillionparameters[52])andbetterarchitecture,whichcanhelpitbetterunderstandthecode,thus identifyingpotentialproblemsmoreaccurately.GPT-4o[53]isanoptimizedversionofGPT-4, designedtobemoreefficientintermsofcomputationalresourceswhilemaintainingasimilaror slightlyreducedperformancelevel.ItâĂŹsoftenusedincontextswherethefullpowerofGPT-4is notnecessary,allowingforfasterinferencetimesandreducedcosts. Thisstudyonlyfocusedonthegpt-3.5-turbo[48],gpt-4o[53]andgpt-4[49]modelsmentioned above;nonetheless,updatedversionsofthemodelswillemerge.Evenwithmodelupdates,there existsadegreeofstability.Whiletheperformanceofmodelsmayundergoslightchanges,some insightsanddiscoveriesremainsignificant.Modelupdatesoftenenhancetheiroverallunderstanding oflarge-scalecorporabutmaynotnecessarilyyieldsubstantialperformanceimprovementsin specifictasks.Therefore,ourresearchresultsretaintheirreferencevalue.Additionally,ourfindings also offer insights for other models, such as Claude [5] and Llama [73], as they share training principleswiththemodelsweutilized. 3 (RQ1)ONEFFECTIVENESSOFCHATGPTINDETECTINGVULNERABILITIES Inthissection,weexploretheeffectivenessofChatGPTindetectingsmartcontractvulnerabilities withvariousmetrics(i.e.,precision,recall,andF1score).WeevaluatetheperformanceofChatGPT basedonthetop9smartcontractvulnerabilitiesfromtheDASP10. 3.1 Dataset Weusethesmartbugs-curated[16]forouranalysis.Thisdatasetwaschosenforthefollowingkey reasons:1)itsprevalentusewithinthesmartcontractvulnerabilitydetectioncommunity[16,24]; 2)eachcontractismeticulouslylabeledwithassociatedvulnerabilities,ensuringthehigh-quality ofdata;3)thestraightforwardnatureofthedatasetmakesitsuitablefortheinitialassessmentof
ChatGPT’svulnerabilitydetectioncapabilities.Specifically,theaveragelineofcodeofthecontracts inthedatasetisabout101.5rows.Smartbugs-curatedprovidesacollectionofvulnerableSolidity smartcontractsorganizedaccordingtotheDASPtaxonomy,asshowninTable1.Formoreinfor- mationonthetypesofvulnerabilitydetectedanddatasetinthisexperiment,refertoSection2.2. Itisimportanttonotethatallcontractsinthedatasetareflaggedwithvulnerabilities(positive), albeitwithdifferenttypespresentineach.Ourexperimentfocusesonspecificvulnerabilitytypes withinthecontracts(e.g.,whendetectingreentrancyvulnerability,contractslackingsuchvulnera- bilityareconsiderednegative).Therefore,duringtesting,weevaluatetheentiredatasetasaunit. Contractsfeaturingaparticularvulnerabilitytypearelabeledaspositive,whilethosedevoidof saidvulnerabilityarelabeledasnegative. 3.2 Experiment InordertoevaluatetheeffectivenessofChatGPTindetectingsmartcontractvulnerabilities,weuse theGPTmodelAPI[51]toestablishdialoguewiththemodel.ThemodelsusedinourexperimentareWhenChatGPTMeetsSmartContractVulnerabilityDetection:HowFarAreWe? 7 thegpt-3.5-turbo-0613model[48],thegpt-4o-2024-05-13model[53]andthegpt-4-0613model[49]. They are all the latest models in their respective series by the time of writing the paper. The parameterof𝑡𝑒𝑚𝑝𝑒𝑟𝑎𝑡𝑢𝑟𝑒 wasconfiguredat0.7tostrikeadelicateequilibriumbetweenfostering innovationandensuringstabilityduringtextgeneration.Allotherparametersweremaintainedat theirdefaultvalues(e.g.,𝑇𝑜𝑝𝑃setto1and𝐹𝑟𝑒𝑞𝑢𝑒𝑛𝑐𝑦𝑃𝑒𝑛𝑎𝑙𝑡𝑦setto0).Table2providesinformation onthethreemodels. ModelsbasedonGPTarchitecturerelyonaprompt-basedlearningapproach[41].Theeffec- tivenessofthepromptssignificantlyaffectstheoverallperformanceofthemodels.Toenhance thequalityoftheprompts,weemployChatGPTtooptimizeourinitialpromptsandsubsequently consolidatethegeneratedprompts.Inourstudy,weinstructChatGPTtobeapromptoptimizer withthetaskofoptimizingthegivenprompt.Thisprocesshelpsustogeneraterefinedprompts. WeusetheGPTmodeltogeneratemultipledraftprompts,whichundergomanualevaluationusing sampleddatatodiscernvariancesandderivehigh-qualityprompts.Figure2providesanillustration of prompt optimization using the GPT-4 model. In the context of smart contract vulnerability detection,weinitiatetheprocessbycomposinganinitialtaskdescription.Thisdraftpromptis thenfedintotheGPT-4modelforoptimization,resultinginanoptimizedversionofthedraft.We sampled20smartcontractsfromthesmartbugs-curateddataset[16],andtriedtousedifferent versionsoftheGPT-optimizedpromptstoinstructitselftoperformvulnerabilitydetectiontasks. Intheend,theoptimalprompttemplatewasdistilledasfollows: You are [ROLE]. [TASK DESCRIPTION]. Think step by step, carefully. The input is [INPUT]. wheretheplaceholder[ROLE]denotesthespecificroleassignedtoChatGPT.Inthisstudy,two mainrolesweredesignated:smartcontractvulnerabilitydetector andtextsemanticanalyzer.smart contractvulnerabilitydetector isusedtodetectsmartcontractvulnerabilitytasks.Thefunctionof textsemanticanalyzer istoperformsemanticanalysisontheconclusionofGPTdetectingsmart contract vulnerabilities, and achieve binary output of the detection conclusion (i.e., use “1” to indicate the existence of the vulnerability, and “0” to indicate the absence). We have created a newsessiontousethisrole,withtheaimofavoidingtheimpactofcontextonthemodel.[TASK DESCRIPTION] describes the expected task that ChatGPT will perform. [INPUT] serves as a placeholderforthecodeunderanalysis. Youareapromptop�mizer.Pleaseop�mizethefollowingprompt: “You are a vulnerability detector for a smart contract. Please check forthefollowingninetypesofvulnerabili�esinthiscontract:[VULS]. Let’sthinkstepbystep.Thesourcecodeforthesmartcontractisas follows:[Input].” Noproblem.Myop�mizedpromptisasfollows: “You are a smart contract vulnerability detector, please analyze the provided source code for the following nine vulnerabili�es: [VULS]. Thinkstepbystepcarefully.Thecontractsourcecode:[Input].” Fig.2. AnexampleofpromptoptimizationusingtheGPT-4model.ChongChen,JianzhongSu,JiachiChen,YanlinWang,TingtingBi,JianxingYu,YanliWang,XingweiLin,TingChen, 8 andZibinZheng Weusedthetemplateaboveandprovidethecorrespondingcontractsourcecodeandcommand modeltoperformvulnerabilitydetectiontasks.Inaddition,intheprompt,welimitedthescope ofvulnerabilitiestobedetectedforcomparisonwiththegroundtruthinthedataset.Theprompt templateusedisshownasfollows: You are a vulnerability detector for a smart contract. Here are nine common vulnerabilities. [VULS]. Check the following smart contract for the above vulnerabilities. Think step by step, carefully. The input is [INPUT]. where[VULS]representsanintroductiontothe9vulnerabilitiesthatneedtobedetectedinthis study.Theintroductionprovidesthenamesofeachvulnerabilityalongwiththeiraliases,andthis informationissourcedfromtheofficialDASP10website[78].[INPUT]representsthesourcecode ofthesmartcontracttobedetected. Table2. Introductiontothetwomodelsusedintheexperiment. Model Description MaxTokens TrainingData gpt-3.5-turbo-0613 Snapshotofgpt-3.5-turbofromJune 4,096tokens UptoSep2021
13th2023withfunctioncallingdata. gpt-4o-2024-05-13 High-intelligence flagship model 4,096tokens UptoOct2023 forcomplex,multi-steptasks.GPT- 4oischeaperandfasterthanGPT-4 Turbo. gpt-4-0613 Snapshot of gpt-4 from June 13th 8,192tokens UptoSep2021 2023withfunctioncallingdata. Withoutspecificconstraints,ChatGPTcanproduceresponsesinanon-standardizedformat, whichposeschallengesforextractingcoherentandmeaningfulinsights.Toenableamoresystematic analysisofvulnerabilitydetectionresults,oneeffectiveapproachistoincludecommandsinthe prompttolimittheoutputformat.However,imposingsuchformatrestrictionsdirectlywithin prompts may also affect the performance of vulnerability detection in large language models. ToexplorewhetherrestrictingtheformatoftheChatGPToutputwouldaffectitsvulnerability detectionperformance,weconductedanexperimentontheentiredatasetusingthegpt-3.5-turbo model,whilelimitingtheoutputformat. Under the condition of limited output, the experimental result of gpt-3.5-turbo is shown in Table3.FromthecomparisonbetweenTable3andtheleftpartofTable5,itcanbeseenthat, exceptforthevulnerabilityofArithmeticIssues,thelimitationoftheoutputformathasanegative impactonthevulnerabilitydetectionperformanceofChatGPTinallothervulnerabilities. Finding1:Acrossthespectrumofeightvulnerabilitytypes,thevulnerabilitydetectionperfor- manceofChatGPTmaydecreaseduetooutputformatlimitations,indicatingthatlimitations onChatGPToutputformatmayaffectitsability. Based on Finding 1, we attempted to use the inherent capabilities of large language models torefinetheoutput.Specifically,onceweobtainthevulnerabilitydetectionresultsfromalarge languagemodel,weinitiatedanewconversation,feedingthoseresultsbackintothemodelfor semanticanalysis.Thisensuresthatthevulnerabilitydetectionoutputadherestoaunifiedformat of“[VUL]:0/1”.Theprompttemplateforthisroundofconversationisasfollows:WhenChatGPTMeetsSmartContractVulnerabilityDetection:HowFarAreWe? 9 Table3. Evaluationofgpt-3.5-turbodetectionresultsonthedataset(restrictedoutput). Vulnerability Precision Recall F-measure Reentrancy 26.0% 38.0% 31.5% AccessControl 12.5% 65.0% 21.0% ArithmeticIssues 92.0% 60.0% 72.5% UncheckedReturnValues 75.0% 25.0% 37.5% DenialofService 9.5% 80.0% 17.0% BadRandomness 95.0% 20.0% 33.3% FrontRunning 2.0% 15.0% 3.6% Timemanipulation 8.0% 70.0% 14.5% ShortAddressAttack 0.0% 0.0% 0.0% You are a semantic analyzer of text. Here are nine common vulnerabilities. [VULS]. The following text is a vulnerability detection result for a smart contract. Use 0 or 1 to indicate whether there are specific types of vulnerabilities. For example: “Reentrancy: 1”. Think step by step, carefully. The input is [INPUT]. Theeffectivenessofthesemanticanalysisprocessrequiresvalidation.Forexample,iftheGPT modelidentifiesacontractashavingbothReentrancyandArithmeticIssuesvulnerabilities,butthe semanticanalysisoutcomeindicates“Reentrancy:1,ArithmeticIssues:0”,thisrendersthesemantic analysis ineffective. To verify the effectiveness of the semantic analysis of the GPT model, we manuallycheckeditsstandardizedoutput.Outofallthe142smartcontracts,50weresampled fromthedatasetforevaluation.AfternormalizationbytheGPTmodel,47resultswerecompletely consistentwiththeoriginalresults.Tworesultsshowomissions,meaningthatthenormalized outputdidnotincludeallthevulnerabilitiesintheoriginalresults.Oneresultshowshallucinations, meaning that the original results did not indicate the existence of the vulnerability, while the normalizedoutputindicatedtheexistenceofthevulnerability.Theoverallperformanceisshown inTable4.ThisresultindicatesthattheGPTmodeloffersgreatreliabilityinsemanticanalyzing textualresultsandinstandardizingoutputformats. Table4. ResultofsemanticanalysisandstandardizingoutputformatsoftheGPTmodelon50sampleddata. Result Number Description Correct 47 Completelyconsistent Omissions 2 Missingsomevulnerabilitiesinferenceincludedinoriginalcon- clusions Hallucination 1 Generatingsomevulnerabilitiesinferencenotincludedinorigi- nalconclusion 3.3 Evaluation WeusedninemetricstoevaluatethedetectionresultsofChatGPT,namelytruepositive(TP),true negative(TN),falsepositive(FP),falsenegative(FN),precision,recall,specificity,F1scoreandstan- darddeviation.TPandTNrepresentsmartcontractswithcertainvulnerabilitiescorrectlydetected byChatGPTandsmartcontractswithoutcertainvulnerabilities,respectively.FPandFNindicate that ChatGPT has incorrectly detected smart contracts with or without certain vulnerabilities. Precision,recall,specificity,standarddeviationandF1scorecanbecalculatedasfollows:ChongChen,JianzhongSu,JiachiChen,YanlinWang,TingtingBi,JianxingYu,YanliWang,XingweiLin,TingChen, 10 andZibinZheng #TP Precision= (1) #TP+#FP #TP Recall= (2) #TP+#FN #TN Specificity= (3) #TN+#FP 2∗Precision∗Recall F1= (4) Precision+Recall √︄ (cid:205)5 (F1 −F¯1)2 Std.= i=1 i (5) 5 Theeffectivenessofgpt-3.5-turboindetectingvulnerabilitiesonthedatasetisshowninthe leftpartofTable5.Werepeatedthesameexperimentsonthesmartbugdatasetforfiveroundsto
reducetheimpactoftheinstabilityoftheGPTmodel. Wereplicatedthesametestbyusingthemodelgpt-4oandgpt-4-0613.Themiddleandrightpart ofTable7showstheresultsoftheseexperimentsrespectively.Itcanbeseenthatgpt-4oandgpt-4 hasasignificantimprovementintheaveragerecallrateofvulnerabilitydetection.However,the precisionhasnotchangedmuchcomparedtogpt-3.5,leadingtoonlyaslightimprovementofthe overallF1score. Furthermore,itisworthnotingthatwhileusingthegpt-3.5-turbomodel,fivesmartcontracts (3.5%)werefailedtobeanalyzed.Similarly,duringtheexperimentalphaseinvolvingthegpt-4 model,twosmartcontracts(1.4%)encouterdetectionfailures.Theseinstancesofdetectionfailure canbeattributedtoChatGPT’stokenlimitationsconcerninginputtext.Thegpt-3.5-turbomodel hasamaximumtokenlimitof4,096,whilethegpt-4-0613modelcanaccommodateupto8,192 tokens[51].Thelengthofsmartcontractcodesfortheseunsuccessfuldetectionsexceededthe tokenthreshold. Finding2:GPTmodelsmayencounterdetectionfailuresinlongsmartcontractcodedueto inherenttokenlimitations. Table5. Comparisonofgpt-3.5-turboandgpt-4detectionresultsonthedataset(Thevaluesintablerepresent percentages,andthecolumn“Std.”representsthestandarddeviationoftheF1scoreindicatorsforfive experiments.) gpt-3.5-turbo gpt-4o gpt-4 Vul. Pre. Re. Spec. F1 Std. Pre. Re. Spec. F1 Std. Pre. Re. Spec. F1 Std. RE 28.3 41.9 77.5 33.8 0.0484 30.0 96.6 43.6 45.8 0.0224 33.5 96.8 41.4 49.8 0.0271 AC 14.3 72.2 20.2 23.9 0.0191 14.4 79.9 40.9 24.4 0.0237 16.7 95.6 29.8 28.4 0.0437 AI 25.8 53.3 77.2 34.8 0.0311 18.0 91.5 61.6 30.0 0.0231 22.0 96.0 63.0 35.7 0.0294 UR 58.5 59.6 73.3 59.0 0.0715 59.0 98.1 69.4 73.6 0.0338 53.6 92.7 67.6 67.9 0.0459 DoS 11.9 83.3 64.0 20.8 0.0195 4.8 96.0 36.6 9.1 0.0121 6.8 96.7 41.9 12.8 0.0168 BR 21.9 87.5 75.4 35.0 0.0800 38.0 100.0 91.9 54.8 0.0622 40.4 98.0 91.0 57.0 0.0418 FR 4.5 25.0 76.8 7.7 0.0000 4.9 70.0 63.9 9.1 0.0358 9.0 70.0 81.2 15.9 0.0080 TM 12.5 40.0 85.4 19.0 0.0088 12.1 100.0 76.6 21.5 0.0296 17.0 88.0 83.2 28.4 0.0447 SAA 0.0 0.0 78.7 0.0 0.0000 0.6 20.0 80.4 1.1 0.0256 4.5 60.0 90.8 8.4 0.0000 Avg. 19.7 51.4 69.8 26.0 0.0309 20.2 83.6 62.8 29.9 0.0298 22.6 88.2 65.5 33.8 0.0286WhenChatGPTMeetsSmartContractVulnerabilityDetection:HowFarAreWe? 11 Table5showsthatChatGPTachievesthebestperformanceindetectingthe“UncheckedReturn Values”vulnerability,withanF-scoreof0.59,0.74and0.68,respectively.ExceptforFrontRunning and Short Address Attack, gpt-4 achieves a good recall rate of more than 80% for each type of vulnerability.However,theprecisionofbothmodelsisaround22%,whichindicatesthatChatGPT hasalargenumberoffalsepositivesduringvulnerabilitydetection. Finding3:ChatGPTdisplaysdistinctdetectionperformancesacrossvariousvulnerabilities.Of the9vulnerabilitiesexamined,ChatGPTshowsitsstrongestdetectionperformanceindetecting “UncheckedReturnValues"vulnerability. 3.4 FalsePositiveAnalysis InordertoclarifythereasonsforthefalsepositivesinChatGPT,wemanuallyanalyzedeachfalse positivecaseandclassifiedthereasonsforthefalsepositivesasfollows: ProtectedMechanismBias.WefoundthatmostfalsepositivesgeneratedbyChatGPTstemmed from its excessive attention to the protected mechanisms embedded within the code. In smart contracts,somespecifictypesofvulnerabilityhaverelatedprotectedmechanisms.Forexample, to prevent the occurrence of the “Access Control” vulnerability, developers often add relevant modifiersintheircode,suchas“onlyOwner”,whichstrictlylimitsobjectsthatcancallspecific functions,effectivelypreventingaccesscontrolissues. Listing1. Exampleofusingtheonlyownermodifierinsmartcontracts. 1 pragmasolidity^0.4.15; 2 contractUnprotected{ 3 addressprivateowner; 4 modifieronlyowner{ 5 require(msg.sender==owner); 6 _; 7 } 8 functionUnprotected()public{ 9 owner=msg.sender; 10 } 11 functionProtected(address_new)onlyowner{ 12 owner=_new; 13 } 14 } Listing1isanexamplethatusesthe“onlyowner”modifier.Thiscontractrequiresafunctionthat isusedtochangetheownerofthiscontract,andthisfunctioncanonlybecalledbythecurrent contractowner.Line4isthe“onlyowner”modifier.Thefunctiontochangethecontractowner inline8isanincorrectexamplebecauseitisapublicfunctionthatanyonecancall.Line11is a correct example, which adds the “onlyowner” modifier to ensure that only the owner of the contractcancall.Moreover,topreventArithmeticIssuesvulnerability,developersoftenaddthe SafeMath[54]librarytoprotecttheircode.AsshowninListing2,line7isanexampleofadeveloperChongChen,JianzhongSu,JiachiChen,YanlinWang,TingtingBi,JianxingYu,YanliWang,XingweiLin,TingChen, 12 andZibinZheng
callingtheSafeMathlibrarytoperformarithmeticoperations,whichcanpreventintegeroverflow vulnerabilities. However,ChatGPToveremphasizestheseprotectedmechanisms.Itmightflagvulnerabilities (generate false positives) in contracts where such protected mechanisms are unnecessary. For example,ifasmartcontractdevoidofarithmeticoperations,itinherentlyavoidsintegeroverflow vulnerabilities.Nevertheless,ChatGPTmayincorrectlyidentifyanintegeroverflowvulnerability insuchcases,duetoitsassumptionthatthesmartcontractlackstheSafeMathlibrary.Likewise, certain smart contracts, such as Listing 2, might be designed solely for deposit or withdrawal actions,withnoowner-specificfunctions.Suchsmartcontractsdonotnecessitatemodifierslike “onlyOwner”todefendagainstvulnerabilities.Unfortunately,ChatGPTdoesnotfullyunderstand this,asitstillusesvulnerabilityprotectedmechanismsasanimportantevaluationindicatorin manycasesandfurtherreportsfalsepositiveswhendetectingvulnerabilities. Listing2. ExampleoffalsepositivesinsmartcontractsduetoProtectedMechanismBias. 1 contractPersonal_Bank{ 2 //HereistheSafeMathlibrary. 3 mapping(address=>uint256)publicbalances; 4 functionDeposit(uint256amount)publicpayable{ 5 require(amount>0,"Amountmustbegreaterthan0"); 6 //balances[msg.sender]+=amount; 7 balances[msg.sender]=balances[msg.sender].add(amount); 8 } 9 functionWithdraw(uint256amount)publicpayable{ 10 require(amount>0,"Amountmustbegreaterthan0"); 11 balances[msg.sender]=balances[msg.sender].sub(amount); 12 } 13 } Finding4:ThedetectionofcertainsmartcontractvulnerabilitiesbyChatGPToveremphasizes onprotectedmechanismsinthecode,whichmayproducefalsepositives. Listing3. Exampleoffalsepositivecausedbyinsufficientunderstandingof“msg.value". 1 functionDeposit()publicpayable{ 2 balances[msg.sender]+=msg.value; 3 Log.AddMessage(msg.sender,msg.value,"Put"); 4 } Development Intent Bias. In smart contract, variables such as “msg.value” carry specific meanings,signifyingthemonetaryvalueconveyedbythetransactionsender[19].Thesevariables, unlikegeneralvariables,aresubjecttoupperlimitsdeterminedbyfactorssuchasthesender’s availablefundsandthetotalcurrencysupply[20].Consequently,arithmeticoperationsinvolving thesevariablescannotresultinoverflowconcerns.Nevertheless,ChatGPT’scomprehensionofWhenChatGPTMeetsSmartContractVulnerabilityDetection:HowFarAreWe? 13 thisdistinctionislimited.Ittreatsthesevariablesasconventionalones,incorrectlyassumingtheir modifiability,andthuscausingfalsepositivesregardingintegeroverflow.AsofSeptember2023, thetotalamountofETHflowinginEthereumis24.97M[2],equivalenttoapproximately405.6 billionUSdollars,withanorderofmagnitudeof10.However,thethresholdforArithmeticIssues is2tothe256power[10],anditsorderofmagnitudeis77.Thereexistsasignificantdisparity betweenthesetwovalues.EvenifthetotalETHsupplycontinuestogrow,itishighlyimprobable thatthebalanceofanaccountortheamountsentinatransactionapproachestheArithmeticIssues thresholdundernormalcircumstances.Listing3showstheDeposit functioninasmartcontract, andline2implementsanadditionoperation.Duetotheupperlimitofthevariable“msg.value”, thisstatementdoesnotresultintheArithmeticIssuesvulnerability.However,GPT-4believedthat thecontracthasanArithmeticIssuesvulnerability. Listing4. ExampleoffalsepositivesinsmartcontractsduetoDevelopmentIntentBias. 1 contractMyContract{ 2 mapping(address=>uint256)publicbalances; 3 functiontransferAndCheck(addressto,uint256amount)internalreturns(boolsuccess){ 4 //Checkreturnvalues. 5 require(balances[msg.sender]>=amount,"Insufficientbalance"); 6 //Executetransferoperation. 7 balances[msg.sender]−=amount; 8 balances[to]+=amount; 9 emitTransferSuccessful(msg.sender,to,amount); 10 success=true; 11 } 12 eventTransferSuccessful(addressfrom,addressto,uint256amount); 13 functiontransferTokens(addressto,uint256amount)public{ 14 //CallingthetransferAndCheckfunction. 15 transferAndCheck(to,amount); 16 } 17 } Inadditiontospecialvariables,somesmartcontractsmayalsocontainspecialfunctions.Listing4 is an example. The transferAndCheck function (line 3) is used to check the return value of the transferandperformthetransferoperation,recordingrelevanteventsbasedonthereturnresults. ThefunctiontransferTokens(line13)onlyneedstocallthetransferAndCheckfunctiontoexecute thetransfer,withouttheneedtocheckthereturnvalueofthetransfer.Thisapproachcanmakethe codemoreconciseandclear,withcentralizedprocessingofreturnvaluechecking.Infact,many tokentransferfunctions(ERC-20[18],ERC-721[17],etc.)insmartcontractsaredesignedinthis way.Therefore,suchcontractsareusuallysecure,butGPTmaybelievethatthereisaUnchecked ReturnValuesvulnerabilityinfunctiontransferTokens(line13)duetoitsdevelopmentintentbias.ChongChen,JianzhongSu,JiachiChen,YanlinWang,TingtingBi,JianxingYu,YanliWang,XingweiLin,TingChen, 14 andZibinZheng Finding5:ChatGPT’sanalysisofsmartcontractsuffersfromdevelopmentintentbias,resulting
inmisunderstandingsofspecificvariablesandfunctions,consequentlygeneratingfalsepositives forcertainvulnerabilities. Interfered by Comments. To aid comprehension, smart contract code typically includes commentswrittenbydevelopers.Thecontentinthesecommentsisusuallyanexplanationofa certain piece of code. However, ChatGPT, as a dialogue model of natural language processing, cannotdistinguishbetweencommentsandcodeitselfwhenanalyzingcodecontainingcomments. Therefore,itisofteninterferedwithbycommentsduringvulnerabilitydetection.Specifically,when analyzingapieceofcodethatdoesnotcontainvulnerabilities,iftherelevantcommentscontain somelogicorstatementsthatcontainvulnerabilities,ChatGPTwillstilldeterminethecodetohave vulnerabilities.AsshowninListing2,adeveloperoriginallywrotea“balances[msg.sender]+= msg.value;”statementinthecodewithanIntegerOverflowvulnerability(line6),butfoundthe vulnerabilityafterauditing,changedtheoriginalstatementtoacomment,andcorrectlyadded thesecure“balances[msg.sender]=balances[msg.sender].add(msg.value);”statement.However, ChatGPTcanmisinterpretthesefragments,yieldingfalsepositives. Finding6:ChatGPT’svulnerabilitydetectionisinfluencedbycodecomments,ofteninterpreting themasactualcode,leadingtopotentialfalsepositives. InterferencewithDeadCode.Althoughsomecodeappearstohavesomevulnerabilities,this doesnotmeanthattheexecutionofthiscodeisunsafe.Becausethecodefragmentcontainingthe vulnerabilitymaybelocatedinasectionthatwillnotbeexecuted,suchaswithinan“if”conditional statement,butthisconditionwillneverbemet.Inactualexecution,suchvulnerabilitiescannot occurandattackerscannottakethecorrespondingexploit.However,withoutthecapabilityto executecode,ChatGPTcanmisinterpretthesefragments,leadingtofalsepositives. Finding7:Duetothelackofactualexecutioncapabilityofthecode,ChatGPTispronetofalse positivesduetosomedeadcode. Distribution.Inaddition,wealsocountedtheproportionoffalsepositivescausedbytheabove reasonsinatotalof375falsepositives(becauseeachvulnerabilitygeneratesFPs,somecontracts arerecalculated)generatedbygpt-4,inordertohaveamorecomprehensiveunderstandingofthe logicofdetectingsmartcontractvulnerabilitiesinChatGPT.Thestatisticalresultsareshownin Table6. Table6. Theproportionoffalsepositivescausedbyvariousreasons. Reasonforfalsepositive Number proportion ProtectedMechanismBias 124 33.1% Lackofunderstandingofactualmeaning 191 50.9% Disturbedbycomments 11 2.9% Interferencewithunexecutedcode 45 12.0% Others 4 1.1%WhenChatGPTMeetsSmartContractVulnerabilityDetection:HowFarAreWe? 15 Inadditiontotheabovereasons,therearealsosomefalsepositivescausedbyotherreasons, representedby“others”inTable6.Itcanbeseenthattheproportionoffalsepositivesisthehighest duetoa“lackofunderstandingoftheactualmeaning”,indicatingthatChatGPTismorelikelyto generatefalsepositiveswhendetectingsmartcontractvulnerabilitiesbecauseitcannotunderstand the actual meaning of code fragments. On the contrary, among the four reasons we identified, theproportionoffalsepositivescausedby“commentinterference”isthelowest.Thisisbecause the smart contracts in the dataset are all from the real world and developers generally do not intentionally leave interfering comments in the code. Nonetheless, this should not undermine theimportanceoftheissue,asitcouldpotentiallybeexploitedbyunscrupulousdevelopers.For example,theymaystrategicallyinsertseeminglysecurecommentsalongsidemaliciouscodeto evadevulnerabilitydetectionofLLMs. FromtheperspectiveofLLMs,ChatGPTproducesfalsepositiveswhendetectingsmartcontract vulnerabilities primarily for the following reasons: 1) Lack of execution context. As an LLM, ChatGPT cannot truly execute code and can only treat code as text, using semantic analysis todetectvulnerabilities[65].However,forcodethatonlyexhibitsvulnerabilitiesunderspecific executionpathsorconditionscaneasilyleadtofalsepositiveswhenanalyzedsemanticallyalone. Scenariossuchas“InterferencewithDeadCode”and“InterferedbyComments”mentionedfall intothiscategory.2)Insufficientunderstandingofspecializedsemantics.Smartcontractsemploy certainspecialvariables(e.g.,msg.value)andfunctionsthatdifferinmeaningandfunctionalityfrom ordinaryvariablesandfunctions.Duetothelackofrelevantdomainknowledge[27],LLMsoften struggletoaccuratelycomprehendthesespecializedsemantics,leadingtoerroneousjudgments suchas“DevelopmentIntentBias”.3)Localpreferenceinfluence.Duringtraining,LLMscanform alocalpreference[38].Inthefieldofsmartcontractvulnerabilitydetection,thiscanbereflectedin focusingtoomuchoncertainvulnerabilityprotectionmechanisms(e.g.,onlyOwner),leadingto excessiverelianceonthesemechanismsduringdetectionandresultinginbiasedevaluations.This reflectsthelocalitypreferenceexhibitedbyLLMs. Overall, the ability of LLMs to perform domain-specific tasks is constrained by the lack of anexecutionenvironment,professionalknowledge,andcontextualunderstandingcapabilities. Futureimprovementsintheirperformanceonsuchtaskscouldbeimprovedbyintegratingdomain knowledgeandenhancingmodelarchitectures. AnswertoRQ1:Overall,theeffectivenessofChatGPTindetectingvulnerabilitiesinsmart
contractsdoesnotsatisfypracticalapplications.Ithasahighrecallrate(51.4%forgpt-3.5-turbo, 83.6%forgpt-4oand88.2%forgpt-4),butlowprecision(19.7%forgpt-3.5-turbo,20.2%forgpt-4o and22.6%forgpt-4),oftengivingfalsepositivestoasmartcontract. 4 (RQ2)COMPARISONWITHOTHERDETECTIONTOOLS To compare the detection performance of ChatGPT against other tools, we selected 14 smart contractvulnerabilitydetectiontoolsandtestedthemonthesmartbug-cruateddataset.These14 toolsareasfollows:Conkas[76],Oyente[44],Smartcheck[69],Honeybadger[72],Maian[47], Securify[74],Slither[23],Osiris[71],Smartian[11],Confuzzius[70],Sailfish[7],Mythril[12], Solhint[56],AChecker[28].Therearethreereasonsforchoosingthese14tools:1)Theirsource codeareavailable.2)TheysupporttodetectatleastonetypeofvulnerabilitywithinDASP10.3) Theyarepublishedontopvenuesorwildlyusedbysmartcontractcommunity. 4.1 Effectiveness Table7showsthedetectionperformanceofdifferenttoolsinthesmartbug-cruateddataset.Each tool’svalueisrepresentedbyF-measureforaspecificvulnerabilitytype.VulnerabilitiesbeyondaChongChen,JianzhongSu,JiachiChen,YanlinWang,TingtingBi,JianxingYu,YanliWang,XingweiLin,TingChen, 16 andZibinZheng tool’sdetectionscopearemarkedwith“/”.Additionally,thetwovulnerabilitiesBadRandomness andShortAddressAttackarenotsupportedbyallthe14tools,sotheyareomittedinTable7. Table7. ComparisonofdetectionperformancebetweenChatGPTandothertools. Reentrancy Access Arithmetic Unchecked Denial Front Time Con- Issues Return of Ser- Run- Manipu- trol Values vice ning lation Conkas 44.0% / 16.8% 91.1% / 7.7% 27.0% Oyente 87.5% 0.0% 23.0% / 3.7% / 0.0% Smartcheck 84.1% 18.2% 6.7% 92.9% 7.7% / 33.3% Honeybadger 76.0% / 0.0% / / / / Maian / 51.9% / / / / / Securify 72.0% 8.7% / 91.7% / 7.1% / Slither 87.0% 23.1% / 72.7% 10.0% / 60.0% Osiris 64.4% / 28.6% / 6.7% / 36.4% Smartian 30.8% 18.2% 60.0% 84.9% 0.0% / 23.5% Confuzzius 76.4% 46.7% 61.1% 86.3% / 10.5% / Sailfish 71.7% / / / 5.9% 5.9% / Mythril 37.2% 13.3% 51.4% 67.5% / 0.0% / Solhint 51.3% 27.5% / 72.7% 0.0% / 22.7% AChecker / 50.0% / / / / / Ave. 65.2% 25.8% 30.6% 82.5% 4.9% 4.7% 29.0% ChatGPT 49.8% 28.4% 35.7% 67.9% 12.8% 15.9% 28.4% TheresultsinTable7revealthatChatGPT’sdetectioncapabilities,particularlyforvulnerabilities, suchasReentrancyandAccessControlisnotasgoodasothercurrenttools.However,theperfor- manceofChatGPTisrelativelyoptimalonDenialofServiceandFrontRunning.Thissuperiority likelyderivesfromtheinherentcomplexitythatcharacterizesthesevulnerabilities.DoSattacks usuallyleadstocontractfailurebecauseofexcessiveresourceuseunderspecificconditions.For example,anattackermightfloodthecontractwithrequests,causingittorunoutofgasandthe failureofexecution.FrontRunninginvolvesgainingaccesstotransactiondetailsbeforetheyare officiallysubmittedandthentakingadvantageofthisinformationtomaximizeprofitsbyminers. Duetointricatenatureofthetwovulnerabilities,itischallengingtodefinerulestocoverallthe patternsforthembasedontraditionalprogramanalysismethods.However,ChatGPT’sability tounderstandcodesemanticsenhancesitsperformanceinvulnerabilitydetection.Unlikemany programanalysistoolsthatrelyonpatternmatching,ChatGPTcangraspcomplexlogicalstructures, makingitmoreeffectiveatdetectingvulnerabilitiessuchasDoSandFrontRunning.Evenso,its F-measureisnotveryhigh.It’snotablethatwhile14selectedtoolsperformbetterinsometypesof vulnerability,theyarecompletelyunabletodetectvulnerabilityoutsidetheirpredefinedscopes.On thecontrary,ChatGPTisnotlimitedtospecificvulnerabilitytypesandcandetectawiderrangeof vulnerabilities,althoughsuccessratesmayvary.ThisindicatesthatChatGPThasagoodbreadth indetectingsmartcontractvulnerabilities,butitsaccuracyneedstobeimproved. Finding8:Amongtheninevulnerabilitiesthatwehaveexamined,ChatGPTdemonstrates anotablecapabilitybysuccessfullydetectingallninetypesofvulnerabilities,showcasingits comprehensivecoverageinvulnerabilitydetection.WhenChatGPTMeetsSmartContractVulnerabilityDetection:HowFarAreWe? 17 Finding9:Incomparisontotheother14tools,ChatGPTdemonstratesbetterdetectionper- formanceintwovulnerabilities:DenialofServiceandFrontRunning.However,in3outof7 vulnerabilities,thedetectionperformanceofChatGPTisinferiortotheaveragelevelofother tools. 4.2 Efficiency Theefficiencyofthesetoolsisacrucialfactorinassessingtheirpracticalutilityinthefieldofsmart contractsecurity.Therefore,werecordedthetimeittookforeachtoolandGPTmodelstoconduct experimentsontheentiredataset.Itisusedasthemetrictoevaluatetheirefficiency.Table8shows
thetimeperformanceofvarioustoolsandChatGPTforvulnerabilitydetectiononthedataset.In general,theefficiencyofChatGPTisgood.gpt-3.5-turbo,gpt-4oandgpt-4completedthedetection ofthewholedatasetin9minutesand21seconds,9minutesand55seconds,11minutesand9 seconds, respectively. It’s worth highlighting that the efficiency demonstrated by all three gpt modelssurpassedthatoftheother11specializedtools(78.6%)listedinTable8,onlyinferiorto thatofSmartCheck,Solhint andAChecker. Table8. ComparisonoftimeperformancebetweenChatGPTandothertoolsindetecting142smartcontracts onSmartBugsDataset. Tools Time(h:m:s) errors Conkas 1:05:23 0 Oyente 0:12:44 0 Smartcheck 0:05:31 0 Honeybadger 1:09:38 0 Maian 2:53:22 0 Securify 0:52:04 0 Slither 0:38:50 0 Osiris 1:11:14 0 Smartian 0:22:44 0 Confuzzius 0:11:23 7 Sailfish 0:25:12 27 Mythril 7:10:02 4 Solhint 0:04:43 0 AChecker 0:06:49 2 gpt-3.5-turbo 0:09:21 5 gpt-4o 0:09:55 5 gpt-4 0:11:09 2 Finding10:Intherealmofvulnerabilitydetection,gpt-3.5-turbo,gpt-4oandgpt-4allexcelin termsofefficiency,outperforming11outof14othertools. AnswertoRQ2:Comparedtoothertools,ChatGPTcandetectmorediversetypesofvulnera- bility,butitsdetectionperformancescoreisnotveryideal.Inaddition,ChatGPToutperformsmost toolsintermsofefficiency.ChongChen,JianzhongSu,JiachiChen,YanlinWang,TingtingBi,JianxingYu,YanliWang,XingweiLin,TingChen, 18 andZibinZheng 5 (RQ3)LIMITATIONSOFCHATGPTINDETECTINGVULNERABILITIES AlthoughChatGPTcanbeusedtodetectvulnerabilitiesinsmartcontracts,italsoexhibitsmany limitations. The first limitation is the uncertainty output. For example, under the same input conditions,ChatGPTmayproducedifferentdetectionresults,thusintroducingacertaindegreeof variability.ThisuncertaintycanbederivedfromthedesignandtrainingmethodsoftheChatGPT model. Inaddition,thelengthofthesmartcontractwillalsohaveanimpactonthedetectionperformance ofChatGPT.Whenthecontractistoolong,ChatGPTmayencounterdetectionfailures.Thisis becauseChatGPTisapretrainedlanguagemodel,anditsinputlimitationsareusuallylimitedby themaximuminputlengthofthemodel.AsshowninTable8,5contractsfailedtobedetected duetothelimitationoftheinputtokenoftheGPTmodel,while10othertools(71.4%)didnot haveanyfailurecasesonthedataset.Whenthecontractexceedsthelimitonthelengthofthe code,ChatGPTmaynotbeabletofullyunderstandandprocessthecontextoftheentirecontract, resultinginadetectionfailure. 5.1 Uncertainty As a language model-based AI model, ChatGPT determines the vulnerabilities in input smart contractsprobabilistically.Therefore,evenwiththesamesmartcontractinputs,ChatGPTmight generatedivergentvulnerabilitydetectionresultsindifferentruns.Suchvariabilitycanbeattributed tothemodel’sinternalstate,randomness,andminusculeinputvariations. All different 2 consistent 0% 6% 3 consistent 14% 5 consistent 4 consistent 58% 22% Fig.3. TheuncertaintytestresultsofChatGPT.Eachpartdisplaysthenumberofcontractswithconsistent results,forexample,5consistentrepresentsthenumberofcontractswithconsistentresultsfromall5tests. TodelvedeeperintoChatGPT’sresultuncertaintywhendetectingsmartcontractvulnerabilities, werandomlyselected50smartcontractsfromthedatasetandconductedfiveroundsofvulnera- bilitydetectionsoneachofthe50smartcontractsusingthegpt-4model.Wethenexaminedthe consistencyacrossthefiveoutcomesforeverycontract.Tosomeextent,forasmartcontract,the moreconsistentthenumberofresults,thestrongerthecertaintyofChatGPTontheresult,and viceversa.TheuncertaintyofvulnerabilitydetectionresultsofChatGPTonsmartcontractsis showninFigure3.EachblockofFigure3displaysthenumberofcontractswithconsistentresults (e.g.,5consistentrepresentsthenumberofcontractswithconsistentresultsfromall5tests).InWhenChatGPTMeetsSmartContractVulnerabilityDetection:HowFarAreWe? 19 thisexperiment,wesettheconfidenceleveloftheresultsgeneratedbytheGPTmodelto80%(i.e., ifnolessthan4outof5resultsareconsistent,webelievethatthisresultisreliable).Amongthe 50randomlyselectedsmartcontracts,ChatGPTonlygavereliableresultson80%ofthecontracts, whiletheremaining20%wereunreliable.Itcanbeseenthat,insomecases,regardlessofwhether theconclusionisrightorwrong,ChatGPTcannotguaranteethecertaintyoftheconclusionit provides. GPTScan[64]employstwostrategiestomitigatetheambiguityintheresponsesgeneratedby ChatGPT:adjustthemodeltemperatureandemploythe“mimic-in-the-background”prompting technique.TheformerinvolvessettingthetemperatureparameteroftheGPTmodelto0,thereby ensuring consistent outputs for identical prompts. The latter employs a prompt methodology, leveraging the GPT system’s prompt instruction model to simulate responding to aquery five timesinthebackground,ultimatelydeliveringthemostfrequentlyrecurringresponsetoenhance consistency. Both of these methods contribute to the refinement of ChatGPT’s output results. Hence,weconductedcomparativeexperimentsusingthesamesettingsanddatasetstoassesstheir
respectiveimpacts,withdetailedresultspresentedinTable9. It can be seen that for gpt-3.5-turbo, while both methods can produce some improvements in the detection performance of specific vulnerabilities, the overall efficacy has diminished. In contrast,inthecaseofgpt-4,thesetwomethodscanmarginallyenhancevulnerabilitydetection performancewhilemaintainingthecertaintyoftheresults.Thisdiscrepancymaybeattributed totheinherentimprovementsinthegpt-4architecture,whichbetterleveragesthesestrategiesto balanceperformanceandconsistency,unliketheearliergpt-3.5-turbomodel. Table 9. Results after using methods to reduce uncertainty, where “temp-adj” represents adjusting the temperatureto0,“MITB”representsmimicin-the-backgroundprompting. gpt-3.5-turbo gpt-4 original temp-adj MITB original temp-adj MITB Reentrancy 33.8 54.5↑ 45.7↑ 49.8 59.8↑ 54.1↑ AccessControl 23.9 29.5↑ 28.6↑ 28.4 32.2↑ 31.7↑ ArithmeticIssues 34.8 21.1 30.8 35.7 44↑ 40↑ UncheckedReturnValues 59 41.6 34.7 67.9 68.2↑ 64.4 DenialofService 20.8 5.9 16.7 12.8 19.4↑ 16.9↑ BadRandomness 35 7.4 27.3 57 60.9↑ 52.2 FrontRunning 7.7 0 0 15.9 7.6 30.8↑ Timemanipulation 19 28.6↑ 28.6↑ 28.4 24 29.6↑ ShortAddressAttack 0 0 0 0 0 22.2↑ Avg. 26.0 21.0 23.6 32.9 35.1↑ 38.0↑ 5.2 ContextLength ChatGPT has token restrictions for contextual input, and it may face detection failure when detectingsmartcontractsduetotheexcessivelylongcodelength.Despitethetokenlimitguidance providedbyGPT,real-worldscenariosoftenintroducevariouscomplexities,suchascomments, statementlengths,andotherfactorsthatcanimpacttheeffectivecodelengththatthemodelcan handle.Therefore,anexperimentwasconductedbyustoapproximatethemaximumcodesize theycanaccommodate.Wecalculatedthetokenlengthofthepromptdesignedinthisstudyand analyzedthesmartcontractcodethatfaileddetectiontoexplorethethresholdcodelengththatthe modelcandetect.ChongChen,JianzhongSu,JiachiChen,YanlinWang,TingtingBi,JianxingYu,YanliWang,XingweiLin,TingChen, 20 andZibinZheng Forgpt-4,themaximumnumberoftokensitcanacceptis8192.Inthisstudy,thenumberof tokensoccupiedbyourdesignedpromptis107,whichmeansthatthemaximumlengthoccupied bytheinputcodecanbe8085tokens.Wehavereviewedtwosmartcontractsthatfaileddetection, withlengthsof2470and897linesofcode,andfilesizesof94.4KBand35.5KB,respectively.Among allsuccessfullydetectedsmartcontracts,thelongestcodelengthis771lines,correspondingtoa filesizeof27KB.Weareattemptingtoextendthe771linecodebyaddingsomeuselesscomments orcodefragments.Whenthefilesizereaches33KBandthenumberofcodelinesreaches857,gpt-4 detectioncannotproceedproperly.Similarly,weconductedthesameexperimentongpt-3.5and foundthatthemaximumsmartcontractsizethatthegpt-3.5modelcandetectis16KB.Itsvalueis muchlowerthangpt-4becausethemaximumnumberoftokensthatthegpt-3.5modelcanaccept istwicethatofgpt-4.Therefore,wecandrawaroughconclusionthatundertheexperimental conditionsofthisstudy,themaximumcodesizethatthegpt-4modelandgpt-3.5modelcandetect isaround33KBinfilesizeand16KBinfilesize,respectively. Answer to RQ3: ChatGPT exhibits certain limitations in detecting vulnerabilities in smart contracts,notablyintheuncertaintyofdetectionconclusionsandtheinabilitytodetectlengthy contractsduetotokenlimitationsinthemodel. 6 DISCUSSION InthecourseofusingChatGPTforthedetectionofvulnerabilityinsmartcontracts,ourpaper uncoveredintriguingphenomena,ledtoinsightfulreflectionsandrelevantexperiments.First,we delvedintoChatGPT’scapabilitytograspvulnerabilitiesandshowcasedthepotentialforenhancing itsdetectionprowessbyinjectingexternalknowledgethroughillustrativeexamples.Following that,weembarkedonanexplorationofmulti-roundconversationexperimentstoascertainwhether ChatGPT’smulti-roundinteractionswithuserswieldinfluenceoveritsvulnerabilitydetection performance.Additionally,weorchestratedcodepoisoningattackexperimentstoassessChatGPT’s responsetoprotectedmechanismswithinthecode.Lastly,weorchestratedcharacterobfuscation attackexperimentstoinvestigatewhetherChatGPTreliessolelyoncharacter-levelsemanticsfor codeanalysis. 6.1 Vulnerabilitylearning BasedontheexperimentalresultsinSection3,wefoundthattheeffectivenessofChatGPTin detectingsmartcontractvulnerabilitiesislimited.Asapre-trainedlargelanguagemodel,ChatGPT mayonlyhavelimitedknowledgeofsmartcontractvulnerabilities.Inotherwords,somenew vulnerabilitiesthatappearafteraspecificdate(thedateforthecorpususedtopre-traintheGPT model)cannotbedetectedbyChatGPT.Inaddition,ifthereislessinformationaboutacertain vulnerabilityinthepre-traineddata,itwillalsoleadtopoordetectionperformanceofChatGPTfor thevulnerability.Therefore,weattempttoidentifyvulnerabilitieswithpoorChatGPTdetection performanceandimprovethedetectionperformanceofsuchvulnerabilitiesbyinjectingexternal knowledge.Forexample,PriceOracleManipulationisakindofvulnerabilitywithapoordetection
effectofChatGPT.Thepriceoraclemachineisacomponentthatcanprovideassetpricedataonthe chain.ManyDeFiprojectswillusepriceoraclemachinecontractstoobtainprices.ThePriceOracle Manipulationistomanipulatethepriceoraclemachinethroughvariousmeanstoreturnwrong pricedata,therebyaffectingDeFiprojectsthatrelyonthesedataandcausingfinanciallosses. Listing5isasmartcontractcontainingaPriceOracleManipulationvulnerability.TheMyContract contract obtains (line 9) on chain price data through the PriceOracle contract. The priceFeed addresscanbesetinPriceOracle(line5).AttackerscansetamaliciouspriceFeedaddressthrough governanceproposalsorothermethods.ThemaliciousOraclemachinecontractcanmanipulatethe priceatwill,sothatkeyoperationsinMyContractwillproduceunexpectedresults.WesuccessivelyWhenChatGPTMeetsSmartContractVulnerabilityDetection:HowFarAreWe? 21 gavefivedifferentsmartcontractscontainingthisvulnerabilitytoChatGPTandaskedthemto detectit.ChatGPTdidnotdetectthisvulnerabilityonce.Figure4showsthedetectionresultsofa certaincontractforthisvulnerability.Thisdetectionresultpointsouttwosecondaryproblemsin thesmartcontract,whileignoringthemainPriceOracleManipulationvulnerability. Thereareacoupleofvulnerabili�esintheprovidedsmartcontract: 1.NoCheckforNega�vePrices: In the `PriceOracle` contract, the `getPrice()` func�on returns an integer which can be nega�ve. However, in `MyContract`, the `myFunc�on()` func�on assigns the poten�ally nega�ve price to an unsigned integer (`uint`) variable. This can cause underflow if a nega�vepriceisreturnedwhichcouldleadtounexpectedbehaviors orevencontractfailure. 2.OutdatedCompilerVersion The solidity compiler version used in this smart contract is 0.4.19, which is a rela�vely outdated compiler version. Developers should considerusingahigherversionofthecompiler. Fig.4. GPT-4’soriginaldetectionresultsofsmartcontractscontainingPriceOracleManipulationvulnerabili- ties. Listing5. ExampleofsmartcontractcontainingPriceOracleManipulationvulnerability. 1 contractPriceOracle{ 2 AggregatorV3InterfacepublicpriceFeed; 3 constructor(address_priceFeed){ 4 priceFeed=AggregatorV3Interface(_priceFeed);} 5 functiongetPrice()publicviewreturns(int){ 6 returnpriceFeed.latestRoundData().answer;} 7 } 8 contractMyContract{ 9 PriceOraclepriceOracle; 10 functionmyFunction()external{ 11 uintprice=priceOracle.getPrice(); 12 //Usethevariabletoperformsomekeyoperations.} 13 } Theefficacyofemployingpre-existingknowledgefordirectlydetectingPriceOracleManipu- lationvulnerabilityhasbeenunsatisfactory.Therefore,itisworthexploringtheintegrationof externalknowledgeascontextualhintswithinpromptstoenhanceperformance.Akeyfactoris findingtheappropriateamountofhintstoguideChatGPTeffectively.Therefore,weattemptto improvethedetectionperformanceofthisvulnerabilitybyinjectingexternalinformation,andourChongChen,JianzhongSu,JiachiChen,YanlinWang,TingtingBi,JianxingYu,YanliWang,XingweiLin,TingChen, 22 andZibinZheng approachinvolvedcategorizingtheinformationinthepromptsintothreelevelstoassessChatGPT’s performance(GPT-4wasselectedforthisexperiment):1)NoInformationProvided:Intheinitial testswithoutspecificprompts,ChatGPTfailedtoidentifyPriceOracleManipulationvulnerabilities presentin5smartcontracts.2)VulnerabilityNameOnly:Whentheterm“PriceOracleManip- ulation Vulnerability” was explicitly mentioned in the prompt, ChatGPT successfully detected thevulnerabilityin2outof5contracts.3)VulnerabilityNameandCodeExample:Byadopting atechniqueofprovidingafew-shotexampleprompt,whichincorporatesboththevulnerability nameandacodesample,ChatGPTwasabletoaccuratelyidentifythePriceOracleManipulation vulnerabilityacrossall5smartcontracts.Figure5showsoneoftheChatGPTdetectionresults forthisvulnerabilityafteraddingexternalknowledge.ThisfindingsuggeststhatChatGPThas theabilitytoincorporateandlearnfromexternalknowledgeeffectively,makingitapplicablefor subsequentdetectiontasks. Thesmartcontractyoupostedhasapoten�alvulnerabilityinit.Price oracle manipula�on vulnerability can occur in the way the getPrice func�on is set up. It directly returns the latest price from the priceFeed, which can be manipulated if the priceFeed oracle is compromised.Thisissuecouldbemi�gatedbyusingmul�plereliable oracles. Fig.5. GPT-4’simproveddetectionresultsofsmartcontractscontainingPriceOracleManipulationvulnerabil- ities. 6.2 Multi-roundConversation DuetoChatGPT’sabilityofmultipleroundsconversations,weattemptedtoredotheexperiment inthiswayandaddmoreinformationduringeachroundofconversations.Figure6isanexample ofamulti-roundconversation.Weconductedninesuccessiveroundsofconversationswithgpt-3.5- turbo.Ineveryinteraction,inadditiontothenameandaliasofeachvulnerability,wealsoprovide definitions of the vulnerability (information is sourced from the official DASP10 website [78]). ChatGPTacknowledgeditsawarenessofthisinformationuponreceivingitineachroundofthe conversation.Subsequently,wepresentedacontractsourcecodetoChatGPTforassessmentafter theconversationrounds.Acomparativeanalysisbetweentheresultsofthisnewmethodandthe previousexperimentisshowninFigure7. Theexperimentalresultsrevealthatthereisnoobviousenhancementinthedetectionperfor-
manceofChatGPTaftermulti-roundconversation.Thisobservationsuggeststhatthemodeof interactionhasalimitedinfluenceonChatGPT’scapacitytodetectvulnerabilities.Comparedto thesingle-roundconversation-basedexperiments,themulti-roundconversation-basedapproach introducedspecificvulnerabilitydefinitions,therebyfurnishingadditionalinformationtoChatGPT. Despitethisaugmentation,uponinspectingthegraphicaldata,itbecomesevidentthatthedetection performancescoresforcertainvulnerabilitygroups,suchas“ArithmeticIssues”and“Unchecked ReturnValues”,exhibitadeclineratherthananincrease.FromtheperspectiveofanLLM,several reasonsmaycontributetothisphenomenon.Firstly,whilemultipleroundsofconversationinject additionalexternalinformationintotheprompt,anoverloadofinformationmayconfusethemodel, makingitchallengingtoeffectivelyprocessalargeamountofdetaileddata.Secondly,external informationmaybeinconsistentordifficulttointegratewithChatGPT’sexistingknowledgebase,WhenChatGPTMeetsSmartContractVulnerabilityDetection:HowFarAreWe? 23 Youareavulnerabilitydetectorforasmartcontract.Therearenine common types of vulnerabili�es in smart contracts. Next, I will tell you their defini�ons and scenarios separately, learn and remember them.A�er that,Iwillprovide youwithasmartcontract code,and you can judge whether there are the above vulnerabili�es in the code. Sure,I'dbehappytolearnaboutthecommontypesofvulnerabili�es in smart contracts and then help you analyze a smart contract for thesevulnerabili�es. First,Reentrancy.[Descrip�ons]. Thank you for providing the defini�on of the first common vulnerability, Reentrancy. Please proceed with the defini�ons and scenarios for the remaining eight common vulnerabili�es in smart contracts, and once you've done that, you can share the smart contractcodeforanalysis. Second,AccessControl.[Descrip�ons]. Thankyou… … Myteachingisover.Checkthefollowingsmartcontractfortheabove vulnerabili�es.Thinkstepbystep,carefully.Theinputis[INPUT]. Fig.6. SchematicdiagramformultipleroundsofconversationwithChatGPT. resultinginknowledgeconflicts.Finally,over-specializationinspecificinformationmaydiminish themodel’sabilitytogeneralizeacrossdifferentcontexts,therebyimpactingvulnerabilitydetection performance.Hence,whenusingLLMsfortasks,itiscrucialtocarefullyconsiderthemannerand quantityofinformationprovidedtomitigateadverseeffectsonmodelperformance. 6.3 CodePoisoning AselucidatedinSection3.4,ChatGPThastheriskofgeneratingfalsepositivesforvulnerabilitiesin smartcontractsduetotheabsenceofprotectedmechanismswithinthecode.Fromtheperspective ofattackers,theymayexploremethodstocircumventChatGPT’svulnerabilitydetection.Forexam- ple,theycoulddeceiveChatGPTbyincorporatingprotectedmechanisms(e.g.,SafeMath),leading the models to overlook vulnerabilities during detection. In addition, attackers have the ability toincorporatepermissioncontrolmechanisms,suchastheonlyOwner modifier,intocontracts harboringAccessControlvulnerability,thuscircumventingdetectionbyChatGPT.Tosubstanti- atethisnotionfromanattack-orientedpointofview,weconductedanevaluation.Specifically, in all contracts containing Arithmetical Issues vulnerability, we artificially added the SafeMath librarywithoutcallingit(i.e.,weonlyadded“importSafeMath”tothecontractwithoutanyotherChongChen,JianzhongSu,JiachiChen,YanlinWang,TingtingBi,JianxingYu,YanliWang,XingweiLin,TingChen, 24 andZibinZheng Single-round Mul�-round 70 60 50 40 30 20 10 0 Reentrancy Access Cont Ar ro il thme� hc eI css keue d s Return Valu De es nial of Servi Bc ae d Randomness Front Run Tini mn eg Manip Sul ha or� t on Address A�ack nc U Fig.7. Experimentalresultsofmulti-roundconversation. modification,whichwouldnotchangethelogicofthecontract).Inparallel,wehaveintegrated theonlyOwner modifierintoallcontractsidentifiedwithAccessControlvulnerabilitywheresaid modifierswerenotused.Underthiscondition,welettheGPTmodeldetectvulnerabilitiesinthese contractsagain.Inthiscase,ChatGPTislikelytofalselyreportthesmartcontractasnegativedue toprotectedmechanismbias. Table 10 illustrates the results of the code poisoning experiment. The symbol “×” denotes contractsthatfailedthecodepoisoningtest,whichimpliesthatwhileChatGPTcouldhaveoriginally identifiedvulnerabilitieswithinthesecontracts,itwasunabletodosoaftertheprotectedmechanism wasincorporated.Ontheotherhand,contractsthatsuccessfullyunderwentthecodepoisoning experimentareindicatedbythe“✓”symbol.Furthermore,contractsthatexhibitedaninabilityto detectvulnerabilitiesbothbeforeandaftercodepoisoningarerepresentedbythe“◦”symbol.In particular,theseresultsrevealthatapproximately46.7%ofthesmartcontractswereinfluencedby theintroductionofSafeMathlibraryand61.1%bythatofonlyOwner modifier.Itshouldbenoted thatthisexperiment,whileasimpleexplorationofcodepoisoning,underscoredthepotentialfor moresophisticatedmechanismstobypassGPT-baseddetection.Itispossibleforthistobeexploited formaliciouspurposes. 6.4 CodeConfusionAttack Since code comments can potentially disrupt the functioning of large models (as discussed in Section3.4),wehypothesizethatGPTanalyzescodebasedonitscharacter-levelsemantics.To
explorethishypothesis,weconductedcharacter-obfuscationattackexperiments.Inthisseriesof experiments,weintroduceddeliberateobfuscationintoeachcontractwithinourdataset.Specifically, weappliedobfuscationrulestoallidentifierswithinthecontracts,includingfunctionnamesand variablenames.Theserulesinvolvedreplacingcertaincharacterswithvisuallysimilarglyphs(i.e., “l”with“1”,“o”with“0”,“i”with“l”,“s”with“5”,“g”with“9”),andifthereplacedidentifierbegan withanumber,weprependedanunderscorebeforethenumber.Theexperimentalresultsfollowing thisobfuscationprocessarepresentedinTable11.WhenChatGPTMeetsSmartContractVulnerabilityDetection:HowFarAreWe? 25 (a)AfteraddingtheSafeMathlibrary,thedetection (b)AfteraddingtheonlyOwnermodifier,thedetection resultsofcontractscontainingArithmeticIssues. resultsofcontractscontainingAccessControl. ContractName Result ContractName Result BECToken.sol × arbitrary_location_write_simple.sol × insecure_transfer.sol ✓ FibonacciBalance.sol ◦ integer_overflow_1.sol ✓ incorrect_constructor_name1.sol × integer_overflow_add.sol ✓ incorrect_constructor_name2.sol ✓ integer_overflow_benign_1.sol × incorrect_constructor_name3.sol × mapping_sym_1.sol ✓ mapping_write.sol ✓ integer_overflow_minimal.sol × multiowned_vulnerable.sol × integer_overflow_mul.sol ✓ mycontract.sol × multitx_multifunc_feasible.sol × parity_wallet_bug_1.sol ◦ multitx_onefunc_feasible.sol ✓ parity_wallet_bug_2.sol ◦ overflow_simple_add.sol ✓ phishable.sol ✓ overflow_single_tx.sol ✓ proxy.sol × timelock.sol × rubixi.sol × token.sol × simple_suicide.sol × tokensalechallenge.sol ◦ unprotected0.sol × wallet_02_refund_nosub.sol ✓ wallet_03_wrong_constructor.sol × wallet_04_confused_sign.sol × Table10. Experimentalresultsofcodepoisoning. Table11. ComparisonofVulnerabilitydetectionresults(F1score)beforeandaftercharobfuscation. Vulnerability Raw Obfuscation Reentrancy 49.8% 64.2% AccessControl 28.4% 23.5% ArithmeticIssues 35.7% 51.6% UncheckedReturnValues 67.9% 69.1% DenialofService 12.8% 17.9% BadRandomness 57.0% 35.0% FrontRunning 15.9% 8.0% TimeManipulation 28.4% 20.5% ShortAddressAttack 8.4% 0.0% Average 33.8% 32.2% Afterapplyingcharacterobfuscation,thedetectionperformanceofonlyfourvulnerabilities (44.4%) decreased, indicating susceptibility to obfuscation attacks. Surprisingly, the detection performanceoftheremainingfivevulnerabilitiesremainedrelativelystableorevenshowedslight improvements.Althoughourstudyshowsthatcharacterobfuscationhasvaryingeffectsondifferent vulnerabilitiesandalimitedimpactontheoverallaverageperformanceofvulnerabilitydetection, itisimportanttonotethattheunderlyingmechanismsexplainingtheseobservationsarebeyond thescopeofthispaper.Furtherin-depthresearchisneededtoexploretheseunderlyingprinciples.ChongChen,JianzhongSu,JiachiChen,YanlinWang,TingtingBi,JianxingYu,YanliWang,XingweiLin,TingChen, 26 andZibinZheng 7 RELATEDWORK 7.1 VulnerabilityDetection Inrecentyears,therehavebeenmanyrelatedworksonvulnerabilitydetectioninsmartcontracts. Avarietyoftoolsandapproacheshavebeenusedtopinpointvulnerabilitiesintheecosystemof smartcontracts.Aprevalentmethodologyisstaticverification,whichevaluatesthesourcecode orbytecodewithoutrunningit[8,9,22,36,75].Ontheotherhand,dynamicanalysisprovides more profound discernment by surveying smart contracts during execution. Automated tools, suchasfuzzing[30,33,79]cangenerateinputtocomprehensivelyassesstheperformanceofthe system.Symbolicexecution[12,25,43,46]andformalverification[55,63]arecommendedfortheir effectiveness,althoughformalverificationcharacteristicallyrequiresspecificationsgivenbytheuser. Furthermore,Zhengetal.[82]investigatedtheeffectivenessofvariouscurrenttoolsindetecting reentryvulnerabilitiesandsummarizedthereasonsfortheirfalsepositives.Insummary,automated toolsandtechniquescanbeusedtouncoverpotentialvulnerabilitiesinsmartcontracts.Recent studieshavepioneerednewtechniquesforidentifyingprofitablemanipulationsandsecuritythreats indecentralizedfinance(DeFi)systems.Novelmethodologiesutilizingdynamicprogramanalysis fromQinetal.[57,59]canautomaticallyreplicateandsynthesizemoney-makingtransactionson blockchainsinrealtime.Suchtechniquescouldbedeployedaftersmartcontractsarereleasedto serveason-chainintrusionmonitoring.OtherworkslikeDeFiPoser[83]haveintroduceduniversal frameworkstodetectattackvectorsinDeFibymodelingprotocollogicandemployingalgorithms like Z3 or Bellman-Ford. Large language models (LLMs) also show the potential for anomaly detection in blockchain networks when properly trained [26]. Advanced representations such as Qin et al. [58] execution property graphs can encode runtime details to complement static analysisandimprovesecurityforsmartcontractsinonlineandforensicsettings.Insummary, cutting-edgestudiesarepushingtheboundariesofdynamicallyanalyzing,modeling,andsecuring DeFiecosystemsagainstexploitation. 7.2 LargeLanguageModels
Due to the rise of large models, many scholars have recently conducted in-depth research on them.Maetal.[45]evaluatedtheperformanceofChatGPTinvarioussubdomainsofsoftware engineering.Davidetal.[14]studiedthedetectionabilityoflargemodelssuchasClaude[5]and GPT [49]foractualattacksonsmartcontracts.Unlikethis,ourresearchfocusedonseveralcommon vulnerabilitiesinthefieldofsmartcontracts,evaluatedtheeffectivenessandlimitationsofChatGPT indetectingsmartcontractvulnerabilities,analyzedthereasonswhyChatGPTproducedfalse positives,andcompareditwithothertools.Lietal.[39]studiedthelimitationsoflargelanguage modelsingeneratingsoftwarefailure-inducedtestcasesandproposedadifferentialpromptmethod toimproveeffectiveness.Fanetal.[21]studiedwhetherautomaticprogramrepairtechnologycan fixtheerrorsolutionsgeneratedbyLLMsintheLeetCodecompetition.Wangetal.[77]analyzed 52relatedstudiesusingLLMforsoftwaretestingfromtheperspectiveofsoftwaretesting.Joshi etal.presentedanLLM-basedapproachtomultilingualrepairthatenablesaflippedinteraction modelforAI-assistedprogramminginwhichtheuserwritescodeandtheassistantsuggestsfixes forlast-milemistakes[34]. 8 CONCLUSIONANDFUTUREWORKS In this paper, we assessed ChatGPT’s capability in detecting smart contract vulnerability. We formulatedthreeresearchquestions(RQs)toexploretheefficacyofChatGPTindetectingsmart contractvulnerabilities,compareitwithothervulnerabilitydetectiontools,andidentifylimitations in its performance. For RQ1, we devised an optimized prompt to acquire ChatGPT’s detectionWhenChatGPTMeetsSmartContractVulnerabilityDetection:HowFarAreWe? 27 outcomes, consisting of two steps: vulnerability detection and semantic analysis. The findings suggestthat,althoughChatGPTdemonstratedstrengthsinpinpointingcertainvulnerabilities,it alsoencounteredprecision-relatedchallenges.Weconductedananalysisoftherootcausesbehind ChatGPT’sfalsepositives,categorizingthemintofourdistinctgroups.ForRQ2,weranother14 state-of-the-artvulnerabilitydetectiontoolsonthedataset,andcomparedChatGPTwiththem, revealingthatalthoughChatGPTcandetectthemosttypesofvulnerability,thedetectionperfor- manceofChatGPTisnotasgoodasotherstate-of-the-arttoolsfor71.4%(5/7)ofvulnerabilities. ChatGPT demonstrates excellent efficiency, but also exhibits a higher proportion of detection failurescomparedto71.4%(10/14)ofthetoolsweevaluated.ForRQ3,weevaluatedtheuncertainty ofChatGPTbysubmittingthesamesmartcontracttothemodelformultiplevulnerabilitydetection andrecordingthefrequencyofconsistentconclusions.Theresultsindicatethatapproximately20% oftheconclusionsareuncertain.Additionally,weemployedChatGPTtoassesssmartcontractsof varyinglengths,aimingtodeterminethefilesizethresholdthatthemodelcaneffectivelyanalyze. Weconcludethatthemaximumcodesizethatthegpt-4modelandgpt-3.5modelcandetectis around33KBinfilesizeand16KBinfilesize,respectively.Thesefindingsunderscoreitspotential as a vulnerability detection tool, but improvements are still needed for a broader adoption in blockchainsecurity. In the future, we intend to dive deeper into exploring the capabilities of alternative Large Language Models (LLMs) for smart contract vulnerability detection, including but not limited to Code llama [60]. Furthermore, our objectives include leveraging more intricate and diverse datasetstofurthertestthecapabilitiesboundaryofLLMswithinthisdomain.Wealsoplanto applytechniquessuchasfine-tuning[32]andretrieval-augmentedgeneration[37]toenhancethe performanceofChatGPTindetectingsmartcontractvulnerabilities.Furthermore,asnewversions ofLLMsbecomeavailable,wewillreevaluateourresearchusingtheseupdatedmodels. ACKNOWLEDGEMENTS ThisworkissupportedbytheOpenResearchFundofTheStateKeyLaboratoryofBlockchainand DataSecurity,ZhejiangUniversityandtheNationalNaturalScienceFoundationofChina(62332004, 62276279)andGuangdongBasicandAppliedBasicResearchFoundation(2024B1515020032). REFERENCES [1] 2023.Chat-Yuan. https://modelscope.cn/studios/ClueAI/ChatYuan-large-v2/summary [2] 2023.Ethereum. https://ethereum.org/en/ [3] 2023.Xunfei-Xinghuo. https://xinghuo.xfyun.cn/ [4] RohanAnil,AndrewM.Dai,OrhanFirat,andetal.2023.PaLM2TechnicalReport. arXiv:2305.10403[cs.CL] [5] anthropic.2023.Claude.https://claude.ai/chats. [6] S.Biswas.2023.RoleofChatGPTinComputerProgramming.MesopotamianJournalofComputerScience(2023),8–16. https://doi.org/10.58496/MJCSC/2023/002 [7] PriyankaBose,DipanjanDas,YanjuChen,YuFeng,ChristopherKruegel,andGiovanniVigna.2022.Sailfish:Vetting smartcontractstate-inconsistencybugsinseconds.In2022IEEESymposiumonSecurityandPrivacy(SP).IEEE,161–178. [8] LexiBrent,NevilleGrech,SifisLagouvardos,BernhardScholz,andYannisSmaragdakis.2020. Ethainter:ASmart ContractSecurityAnalyzerforCompositeVulnerabilities.InProceedingsofthe41stACMSIGPLANConferenceon ProgrammingLanguageDesignandImplementation,PLDI2020.AssociationforComputingMachinery,NewYork,NY,
USA,454–469. https://doi.org/10.1145/3385412.3385990 [9] LexiBrent,AntonJurisevic,MichaelKong,EricLiu,FrancoisGauthier,VincentGramoli,RalphHolz,andBernhard Scholz.2018.Vandal:AScalableSecurityAnalysisFrameworkforSmartContracts.arXivpreprintarXiv:1809.03981 (2018). https://doi.org/10.48550/ARXIV.1809.03981 [10] JiachiChen,MingyuanHuang,ZeweiLin,PeilinZheng,andZibinZheng.2023.ToHealthierEthereum:ACompre- hensiveandIterativeSmartContractWeaknessEnumeration. arXiv:2308.10227[cs.SE] [11] JaeseungChoi,DoyeonKim,SoominKim,GustavoGrieco,AlexGroce,andSangKilCha.2021.Smartian:Enhancing smartcontractfuzzingwithstaticanddynamicdata-flowanalyses.In202136thIEEE/ACMInternationalConferenceonChongChen,JianzhongSu,JiachiChen,YanlinWang,TingtingBi,JianxingYu,YanliWang,XingweiLin,TingChen, 28 andZibinZheng AutomatedSoftwareEngineering(ASE).IEEE,227–239. [12] ConsenSys.2021.Consensys/mythril:Securityanalysistoolforevmbytecode. https://github.com/ConsenSys/mythril [13] ChrisDannen.2017.IntroducingEthereumandsolidity.Vol.1.Springer. [14] IsaacDavid,LiyiZhou,KaihuaQin,DawnSong,LorenzoCavallaro,andArthurGervais.2023.Doyoustillneeda manualsmartcontractaudit? arXiv:2306.12338[cs.CR] [15] ZhengxiaoDu,YujieQian,XiaoLiu,MingDing,JiezhongQiu,ZhilinYang,andJieTang.2022.GLM:GeneralLanguage ModelPretrainingwithAutoregressiveBlankInfilling.InProceedingsofthe60thAnnualMeetingoftheAssociationfor ComputationalLinguistics(Volume1:LongPapers).320–335. [16] ThomasDurieux,JoãoF.Ferreira,RuiAbreu,andPedroCruz.2020.Empiricalreviewofautomatedanalysistoolson 47,587Ethereumsmartcontracts.InProceedingsoftheACM/IEEE42ndInternationalconferenceonsoftwareengineering. 530–541. [17] WilliamEntriken,DieterShirley,JacobEvans,andNastassiaSachs.2018.ERC-721:Non-FungibleTokenStandard. https://eips.ethereum.org/EIPS/eip-721. [18] Ethereum.2023.ERC-20TokenStandard.https://ethereum.org/en/developers/docs/standards/tokens/erc-20/. [19] Ethereum.2023.SolidityDocumentation.https://docs.soliditylang.org/en/v0.8.21/. [20] Ethereum.2023.UnitsandGloballyAvailableVariables.https://docs.soliditylang.org/en/develop/units-and-global- variables.html. [21] ZhiyuFan,XiangGao,MartinMirchev,AbhikRoychoudhury,andShinHweiTan.2023.Automatedrepairofprograms fromlargelanguagemodels.In2023IEEE/ACM45thInternationalConferenceonSoftwareEngineering(ICSE).IEEE, 1469–1481. [22] JosselinFeist,GustavoGrieco,andAlexGroce.2019.Slither:astaticanalysisframeworkforsmartcontracts.In2019 IEEE/ACM2ndInternationalWorkshoponEmergingTrendsinSoftwareEngineeringforBlockchain(WETSEB).IEEE, 8–15. [23] JosselinFeist,GustavoGrieco,andAlexGroce.2019.Slither:astaticanalysisframeworkforsmartcontracts.In2019 IEEE/ACM2ndInternationalWorkshoponEmergingTrendsinSoftwareEngineeringforBlockchain(WETSEB).IEEE, 8–15. [24] JoãoFFerreira,PedroCruz,ThomasDurieux,andRuiAbreu.2020.SmartBugs:Aframeworktoanalyzesoliditysmart contracts.InProceedingsofthe35thIEEE/ACMInternationalConferenceonAutomatedSoftwareEngineering.1349–1352. [25] JoelFrank,CorneliusAschermann,andThorstenHolz.2020.ETHBMC:Aboundedmodelcheckerforsmartcontracts. In29thUSENIXSecuritySymposium(USENIXSecurity20).USENIXAssociation,2757–2774. https://www.usenix.org/ conference/usenixsecurity20/presentation/frank [26] YuGai,LiyiZhou,KaihuaQin,DawnSong,andArthurGervais.2023. BlockchainLargeLanguageModels. arXiv preprintarXiv:2304.12749(2023). [27] YingqiangGe,WenyueHua,KaiMei,jianchaoji,JuntaoTan,ShuyuanXu,ZelongLi,andYongfengZhang.2023. OpenAGI:WhenLLMMeetsDomainExperts.InAdvancesinNeuralInformationProcessingSystems,A.Oh,T.Neumann, A.Globerson,K.Saenko,M.Hardt,andS.Levine(Eds.),Vol.36.CurranAssociates,Inc.,5539–5568. https://proceedings. neurips.cc/paper_files/paper/2023/file/1190733f217404edc8a7f4e15a57f301-Paper-Datasets_and_Benchmarks.pdf [28] AsemGhaleb,JuliaRubin,andKarthikPattabiraman.2023.Achecker:Staticallydetectingsmartcontractaccesscontrol vulnerabilities.In2023IEEE/ACM45thInternationalConferenceonSoftwareEngineering(ICSE).IEEE,945–956. [29] PuneetGill,IndraniRay,AlirezaLotfiTakami,andMaheshTripunitara.2022.FindingUncheckedLow-LevelCalls withZeroFalsePositivesandNegativesinEthereumSmartContracts.InInternationalSymposiumonFoundationsand PracticeofSecurity.Springer,305–321. [30] GustavoGrieco,WillSong,andArturCygan.2020.Echidna:Effective,usable,andfastfuzzingforsmartcontracts. InProceedingsofthe29thACMSIGSOFTInternationalSymposiumonSoftwareTestingandAnalysis.ACM,787–801. https://agroce.github.io/issta20.pdf
[31] DaojingHe,ZhiDeng,YuxingZhang,SammyChan,YaoCheng,andNadraGuizani.2020.SmartContractVulnerability AnalysisandSecurityAudit.IEEENetwork34,5(2020),276–282. https://doi.org/10.1109/MNET.001.1900656 [32] JeremyHowardandSebastianRuder.2018.Universallanguagemodelfine-tuningfortextclassification.arXivpreprint arXiv:1801.06146(2018). [33] BoJiang,YeLiu,andWKChan.2018.Contractfuzzer:Fuzzingsmartcontractsforvulnerabilitydetection.InProceedings ofthe33rdACM/IEEEInternationalConferenceonAutomatedSoftwareEngineering.ACM,259–269. https://doi.org/10. 1145/3238147.3238177 [34] HarshitJoshi,JosÃľCambroneroSanchez,SumitGulwani,VuLe,GustVerbruggen,andIvanRadiÄŊek.2023.Repair IsNearlyGeneration:MultilingualProgramRepairwithLLMs. ProceedingsoftheAAAIConferenceonArtificial Intelligence37,4(Jun.2023),5131–5140. https://doi.org/10.1609/aaai.v37i4.25642 [35] LesliePackKaelbling,MichaelLLittman,andAndrewWMoore.1996.Reinforcementlearning:Asurvey.Journalof artificialintelligenceresearch4(1996),237–285.WhenChatGPTMeetsSmartContractVulnerabilityDetection:HowFarAreWe? 29 [36] SukritKalra,SeepGoel,MohanDhawan,andSubodhSharma.2018. Zeus:Analyzingsafetyofsmartcontracts.In NDSS.1–12. [37] PatrickLewis,EthanPerez,AleksandraPiktus,FabioPetroni,VladimirKarpukhin,NamanGoyal,HeinrichKüttler, MikeLewis,Wen-tauYih,TimRocktäschel,etal.2020.Retrieval-augmentedgenerationforknowledge-intensivenlp tasks.AdvancesinNeuralInformationProcessingSystems33(2020),9459–9474. [38] JunlongLi,FanZhou,ShichaoSun,YikaiZhang,HaiZhao,andPengfeiLiu.2024. DissectingHumanandLLM Preferences. arXiv:2402.11296[cs.CL] [39] T.Li,W.Zong,Y.Wang,H.Tian,Y.Wang,S.Cheung,andJ.Kramer.2023.FindingFailure-InducingTestCaseswith ChatGPT.InIEEE. [40] TianyangLin,YuxinWang,XiangyangLiu,andXipengQiu.2022.Asurveyoftransformers.AIOpen3(2022),111–132. https://doi.org/10.1016/j.aiopen.2022.10.001 [41] PengLiu,WeizhenYuan,JieFu,ZhengbaoJiang,HiroakiHayashi,andGrahamNeubig.2023.Pre-train,prompt,and predict:Asystematicsurveyofpromptingmethodsinnaturallanguageprocessing. Comput.Surveys55,9(2023), 1–35. [42] ItemperanceConsultingPvt.Ltd.2023.gpt-3-vs-gpt-3-5.https://www.iffort.com/2023/03/31/gpt-3-vs-gpt-3-5. [43] LoiLuu,Duc-HiepChu,HrishiOlickel,PrateekSaxena,andAquinasHobor.2016.Makingsmartcontractssmarter.In Proceedingsofthe2016ACMSIGSACConferenceonComputerandCommunicationsSecurity.ACM,254–269. https: //doi.org/10.1145/2976749.2978309 [44] LoiLuu,Duc-HiepChu,HrishiOlickel,PrateekSaxena,andAquinasHobor.2016.Makingsmartcontractssmarter.In Proceedingsofthe2016ACMSIGSACconferenceoncomputerandcommunicationssecurity.254–269. [45] WeiMa,ShangqingLiu,WenhanWang,QiangHu,YeLiu,CenZhang,LimingNie,andYangLiu.2023.TheScopeof ChatGPTinSoftwareEngineering:AThoroughInvestigation. arXiv:2305.12138[cs.SE] [46] MarkMossberg,FelipeManzano,EricHennenfent,AlexGroce,GustavoGrieco,JosselinFeist,TrentBrunson,and ArtemDinaburg.2019.Manticore:Auser-friendlysymbolicexecutionframeworkforbinariesandsmartcontracts.In 201934thIEEE/ACMInternationalConferenceonAutomatedSoftwareEngineering(ASE).1186–1189. https://doi.org/10. 1109/ASE.2019.00133 [47] IvicaNikolić,AashishKolluri,IlyaSergey,PrateekSaxena,andAquinasHobor.2018.Findingthegreedy,prodigal,and suicidalcontractsatscale.InProceedingsofthe34thannualcomputersecurityapplicationsconference.653–663. [48] OpenAI.2023.GPT-3.5.https://platform.openai.com/docs/models/gpt-3-5. [49] OpenAI.2023.GPT-4.https://platform.openai.com/docs/models/gpt-4. [50] OpenAI.2023.GPT-4TechnicalReport. arXiv:2303.08774[cs.CL] [51] OpenAI.2023.GPT-OpenAIAPI.https://platform.openai.com/docs/guides/gpt. [52] OpenAI.2023.research-gpt4.https://openai.com/research/gpt-4. [53] OpenAI.2024.GPT-4o. https://openai.com/index/hello-gpt-4o/ [54] openzeppelin solidity. 2018. SafeMath. https://github.com/ConsenSysMesh/openzeppelin-solidity/blob/master/ contracts/math/SafeMath.sol. [55] AntonPermenev,DimitarDimitrov,PetarTsankov,DanaDrachsler-Cohen,andMartinVechev.2020.VerX:Safety VerificationofSmartContracts.In2020IEEESymposiumonSecurityandPrivacy(SP).1661–1677. https://doi.org/10. 1109/SP40000.2020.00024 [56] Protofire.2020.Solhint. https://github.com/protofire/solhint [57] KaihuaQin,StefanosChaliasos,LiyiZhou,BenjaminLivshits,DawnSong,andArthurGervais.2023.TheBlockchain ImitationGame.InUSENIXSecuritySymposium.
[58] KaihuaQin,ZheYe,ZhunWang,WeilinLi,LiyiZhou,ChaoZhang,DawnSong,andArthurGervais.2023.Towards AutomatedSecurityAnalysisofSmartContractsBasedonExecutionPropertyGraph.arXivpreprintarXiv:2305.14046 (2023). [59] KaihuaQin,LiyiZhou,andArthurGervais.2022.QuantifyingBlockchainExtractableValue:HowDarkistheForest?. In2022IEEESymposiumonSecurityandPrivacy(SP).IEEE,198–214. [60] BaptisteRozière,JonasGehring,FabianGloeckle,StenSootla,ItaiGat,XiaoqingEllenTan,YossiAdi,JingyuLiu,Tal Remez,JérémyRapin,etal.2023. CodeLlama:OpenFoundationModelsforCode. arXivpreprintarXiv:2308.12950 (2023). [61] SarwarSayeed,HectorMarco-Gisbert,andTomCaira.2020.SmartContract:AttacksandProtections.IEEEAccess8 (2020),24416–24427. https://doi.org/10.1109/ACCESS.2020.2970495 [62] NigarM.ShafiqSurameeryandMohammedY.Shakor.2023.UseChatGPTtoSolveProgrammingBugs.International JournalofInformationTechnology&ComputerEngineering(IJITC)3,01(Jan.2023),17–22. https://doi.org/10.55529/ ijitc.31.17.22 [63] SunbeomSo,MyunghoLee,JisuPark,HeejoLee,andHakjooOh.2019.VeriSmart:AHighlyPreciseSafetyVerifierfor EthereumSmartContracts.arXivpreprintarXiv:1908.11227(2019).ChongChen,JianzhongSu,JiachiChen,YanlinWang,TingtingBi,JianxingYu,YanliWang,XingweiLin,TingChen, 30 andZibinZheng [64] YuqiangSun,DaoyuanWu,YueXue,HanLiu,HaijunWang,ZhengziXu,XiaofeiXie,andYangLiu.2023.Whengpt meetsprogramanalysis:Towardsintelligentdetectionofsmartcontractlogicvulnerabilitiesingptscan.arXivpreprint arXiv:2308.03314(2023). [65] YuqiangSun,DaoyuanWu,YueXue,HanLiu,HaijunWang,ZhengziXu,XiaofeiXie,andYangLiu.2024.GPTScan: DetectingLogicVulnerabilitiesinSmartContractsbyCombiningGPTwithProgramAnalysis.InProceedingsof theIEEE/ACM46thInternationalConferenceonSoftwareEngineering(,Lisbon,Portugal,)(ICSE’24).Associationfor ComputingMachinery,NewYork,NY,USA,Article166,13pages. https://doi.org/10.1145/3597503.3639117 [66] NickSzabo.1997.Formalizingandsecuringrelationshipsonpublicnetworks.Firstmonday(1997). [67] Googleteam.2023.Google.https://about.google/. [68] OpenAIteam.2023.OpenAI.https://openai.com/. [69] SergeiTikhomirov,EkaterinaVoskresenskaya,IvanIvanitskiy,RamilTakhaviev,EvgenyMarchenko,andYaroslav Alexandrov.2018. Smartcheck:Staticanalysisofethereumsmartcontracts.InProceedingsofthe1stinternational workshoponemergingtrendsinsoftwareengineeringforblockchain.9–16. [70] ChristofFerreiraTorres,AntonioKenIannillo,ArthurGervais,andRaduState.2021.Confuzzius:Adatadependency- awarehybridfuzzerforsmartcontracts.In2021IEEEEuropeanSymposiumonSecurityandPrivacy(EuroS&P).IEEE, 103–119. [71] ChristofFerreiraTorres,JulianSchütte,andRaduState.2018. Osiris:Huntingforintegerbugsinethereumsmart contracts.InProceedingsofthe34thannualcomputersecurityapplicationsconference.664–676. [72] ChristofFerreiraTorres,MathisSteichen,etal.2019.Theartofthescam:Demystifyinghoneypotsinethereumsmart contracts.In28thUSENIXSecuritySymposium(USENIXSecurity19).1591–1607. [73] HugoTouvron,ThibautLavril,GautierIzacard,XavierMartinet,Marie-AnneLachaux,TimothÃľeLacroix,Baptiste RoziÃĺre,NamanGoyal,EricHambro,FaisalAzhar,AurelienRodriguez,ArmandJoulin,EdouardGrave,andGuillaume Lample.2023.LLaMA:OpenandEfficientFoundationLanguageModels. arXiv:2302.13971[cs.CL] [74] PetarTsankov,AndreiDan,DanaDrachsler-Cohen,ArthurGervais,FlorianBuenzli,andMartinVechev.2018.Securify: Practicalsecurityanalysisofsmartcontracts.InProceedingsofthe2018ACMSIGSACconferenceoncomputerand communicationssecurity.67–82. [75] PetarTsankov,AndreiDan,DanaDrachsler-Cohen,ArthurGervais,FlorianB"unzli,andMartinVechev.2018.Securify: Practicalsecurityanalysisofsmartcontracts.InProceedingsofthe2018ACMSIGSACConferenceonComputerand CommunicationsSecurity (CCS’18).AssociationforComputingMachinery,NewYork,NY,USA,67–82. https: //doi.org/10.1145/3243734.3243780 [76] NunoVeloso.2021.Conkas.https://github.com/nveloso/conkas. [77] JunjieWang,YuchaoHuang,ChunyangChen,ZheLiu,SongWang,andQingWang.2023.Softwaretestingwithlarge languagemodel:Survey,landscape,andvision.arXivpreprintarXiv:2307.07221(2023). [78] DavidWongandMasonHemmel.2018.DecentralizedApplicationSecurityProjectTop10of2018.https://dasp.co/ index.html. [79] ValentinW"ustholzandMariaChristakis.2020.Harvey:Agreyboxfuzzerforsmartcontracts.InProceedingsofthe 28thACMJointMeetingonEuropeanSoftwareEngineeringConferenceandSymposiumontheFoundationsofSoftware Engineering.ACM,1398–1409. https://doi.org/10.1145/3368089.3417064 [80] YueZhang,MingZhang,HaipengYuan,ShichunLiu,YongyaoShi,TaoGui,QiZhang,andXuanjingHuang.2024.
Llmeval:Apreliminarystudyonhowtoevaluatelargelanguagemodels.InProceedingsoftheAAAIConferenceon ArtificialIntelligence,Vol.38.19615–19622. [81] ZibinZheng,ShaoanXie,Hong-NingDai,WeiliChen,XiangpingChen,JianWeng,andMuhammadImran.2020.An overviewonsmartcontracts:Challenges,advancesandplatforms.FutureGenerationComputerSystems105(2020), 475–491. [82] Z.Zheng,N.Zhang,J.Su,Z.Zhong,M.Ye,andJ.Chen.2023.TurntheRudder:ABeaconofReentrancyDetectionfor SmartContractsonEthereum.InIEEE. [83] LiyiZhou,KaihuaQin,AntoineCully,BenjaminLivshits,andArthurGervais.2021.OntheJust-in-TimeDiscoveryof Profit-GeneratingTransactionsinDeFiProtocols.arXivpreprintarXiv:2103.02228(2021).
2309.05867 SkillScanner: Detecting Policy-Violating Voice Applications Through Static Analysis at the Development Phase SongLiao LongCheng HaipengCai ClemsonUniversity ClemsonUniversity WashingtonStateUniversity UnitedStates UnitedStates UnitedStates liao5@g.clemson.edu lcheng2@clemson.edu haipeng.cai@wsu.edu LinkeGuo HongxinHu ClemsonUniversity UniversityatBuffalo UnitedStates UnitedStates linkeg@clemson.edu hongxinh@buffalo.edu ABSTRACT KEYWORDS TheAmazonAlexamarketplaceisthelargestVoicePersonalAssis- AmazonAlexa,PolicyViolationDetection,StaticAnalysis tant(VPA)platformwithover100,000voiceapplications(i.e.,skills) ACMReferenceFormat: publishedtotheskillsstore.Inanefforttomaintainthequality SongLiao,LongCheng,HaipengCai,LinkeGuo,andHongxinHu.2023. andtrustworthinessofvoice-apps,AmazonAlexahasimplemented SkillScanner:DetectingPolicy-ViolatingVoiceApplicationsThroughStatic asetofpolicyrequirementstobeadheredtobythird-partyskill AnalysisattheDevelopmentPhase.InProceedingsofthe2023ACMSIGSAC developers.However,recentworksrevealtheprevalenceofpolicy- ConferenceonComputerandCommunicationsSecurity(CCS’23),November violatingskillsinthecurrentskillsstore.Tounderstandthecauses 26–30,2023,Copenhagen,Denmark.ACM,NewYork,NY,USA,16pages. ofpolicyviolationsinskills,wefirstconductauserstudywith34 https://doi.org/10.1145/3576915.3616650 third-partyskilldevelopersfocusingonwhethertheyareaware ofthevariouspolicyrequirementsdefinedbytheAmazonAlexa 1 INTRODUCTION platform.Ouruserstudyresultsshowthatthereisanotablegapbe- AmazonAlexaisoneoftheleadingVoicePersonalAssistant(VPA) tweenVPA’spolicyrequirementsandskilldevelopers’practices.As platformsthatallowthird-partydeveloperstobuildnewvoiceap- aresult,itisinevitablethatpolicy-violatingskillswillbepublished. plications(i.e.,calledskills)andpublishthemtotheskillsstore[10]. Topreventtheinflowofnewpolicy-breakingskillstotheskills TheopennessoftheAmazonAlexaplatformhasgreatlyattracted storefromthesource,itiscriticaltoidentifypotentialpolicyvio- skilldevelopersandinflatedVPA’scapabilities.Currently,more lationsatthedevelopmentphase.Inthiswork,wedesignandde- than100,000Alexaskillsareavailable[5],withfunctionssuchas velopSkillScanner,anefficientstaticcodeanalysistooltofacilitate orderingpizza,listeningtothenewsandweather,lockingdoors,or third-partydeveloperstodetectpolicyviolationsearlyintheskill checkingcreditcardbalance.However,suchanopenVPAecosys- developmentlifecycle.ToevaluatetheperformanceofSkillScan- teminevitablyprovidesunscrupulousorinexperienceddevelop- ner,weconductedanempiricalstudyon2,451opensourceskills ers an opportunity to publish buggy or dangerous skills in the collectedfromGitHub.SkillScannereffectivelyidentified1,328dif- store[32,62].Consequently,thesepoor-qualityandproblematic ferentpolicyviolationsfrom786skills.Ourresultssuggestthat32% skillscouldcauseuserfrustration,stirupnegativeeffectsonen- ofthesepolicyviolationsareintroducedthroughcodeduplication gagement,andevenplaceendusersinavulnerableposition. (i.e.,codecopyandpaste).Inparticular,wefoundthat42skillcode ToensurethecontentsafetyandprivacyofskillsinAlexaskills examplesfrompotentialAlexa’sofficialaccounts(e.g.,“alexa”and store,Amazonhasdefinedvariouspolicyrequirements,including7 “alexa-samples”onGitHub)containpolicyviolations,whichlead privacyrequirements[7],14mainsectionsofcontentguidelines[6], to81policyviolationsinotherskillsduetothecopy-pastedcode andcodeinconsistency[1]tobeadheredtobythird-partyskill snippetsfromtheseAlexa’scodeexamples. developers.Forexample,skillsshouldnothaveadvertisementsor promotealcohol.Althoughthesepoliciesarecheckedduringthe CCSCONCEPTS skillcertificationprocess(whichrejectsaskillifitviolatesanyofthe pre-definedpolicies),priorworkdemonstratedtheeaseofpolicy- •Softwareanditsengineering→Automatedstaticanalysis; violatingskillsbeingcertified[32,55].Severalrecentworks[39, •Securityandprivacy→Privacyprotections. 41,42,53,59]developedtoolstomeasurethepolicycomplianceof skillsontheAmazonAlexaplatformthroughadynamicanalysis Permissiontomakedigitalorhardcopiesofpartorallofthisworkforpersonalor approach(i.e.,byexploringtheoutcomesofskills).Forexample, classroomuseisgrantedwithoutfeeprovidedthatcopiesarenotmadeordistributed SkillExplorer[39]found1,141skillsthatcollectdifferenttypesof forprofitorcommercialadvantageandthatcopiesbearthisnoticeandthefullcitation privateinformationbutwithoutdisclosingthedatacollectionin onthefirstpage.Copyrightsforthird-partycomponentsofthisworkmustbehonored. Forallotheruses,contacttheowner/author(s). theirprivacypolicies. CCS’23,November26–30,2023,Copenhagen,Denmark Inparticular,researchersinSkillDetective[59]found3,473Alexa ©2023Copyrightheldbytheowner/author(s). skills violating the same policy whereby skills are forbidden to ACMISBN979-8-4007-0050-7/23/11. https://doi.org/10.1145/3576915.3616650 “explicitlyrequestthatusersleaveapositiveratingoftheskill”.Itis 3202 peS 11
]RC.sc[ 1v76850.9032:viXraCCS’23,November26–30,2023,Copenhagen,Denmark SongLiao,LongCheng,HaipengCai,LinkeGuo,andHongxinHu likelythatmanythird-partydeveloperswerenotcompletelyaware policyviolationsinotherskillsduetothecodeduplication. ofsuchpolicyrequirements,andinadvertentlyviolatedthemin WediscusstheresponsibledisclosureinSection6.8.3. theirskills.Pastresearchhasshownthatsoftwaredevelopersfindit difficulttounderstandvariouspoliciesandrequirementswhenthey 2 BACKGROUNDANDCHALLENGES developsoftwareapplications[50,52],andareoftenunawareofall 2.1 SkillCodeStructure therelatedpolicies[48].Inthiswork,wearecuriousaboutwhether A skill has a front-end interaction model (i.e., front-end code2) developersareawareofthevariouspolicyrequirementsdefined andback-endcodethatprocessesrequestsandtellsaVPAdevice bytheVPAplatform.Tothisend,wefirstconductanin-depth whattorespond.AmazonAlexaCloudprovideshostingforthe userstudytounderstandthird-partyskilldevelopers’perceptions front-end interface of a skill [16], but its back-end code can be andinterpretationsregardingVPA’spolicyrequirements.Ouruser hostedonthedeveloper’sserver(e.g.,eitherhostedbyAWSLambda studyresultsshowthatthereexistsanotablegapbetweenVPA’s under the developer’s account or other third-party servers). In policy requirements and skill developers’ practices. To prevent addition,theskillcodealsocontainsaskillmanifestfile(i.e.,named theinflowofnewpolicy-violatingskillstothepublic,itiscritical “skill.json”)[17],whichstorestheskillname,category,description, to identify potential policy violations in skills early in the skill privacypolicy,aswellaspermissioninformation.Onceaskillis developmentlifecycle. certifiedandpublishedintheAlexa’sskillsstore,suchinformation Inthiswork,weseektodevelopstaticanalysistechniquesto willbeshownontheskill’swebpage. facilitatethedevelopmentofpolicy-compliantskillsbythird-party Front-endcode.Therearemainlythreetypesofdatadefined developers.However,theuniquecodestructureofskillsposeschal- inthefront-endcode:intent,slotandsampleutterances.Anintent lengesforperformingastaticanalysisoftheskillcodesinceweneed representsanactionthatfulfillsauser’sspokenrequest.Intents toconsidertheinteractionbetweenthefront-endcodeandback-end normallyhavetwovalues:theintentnameandsampleutterances. codeduringouranalysis.Thediversenatureofpolicyrequirements Sampleutterancesareasetoflikelyspokenphrasesmappedtothe definedbyAmazonAlexaisanotherchallengefordetectingpolicy intentsanddevelopersshouldincluderepresentativephrasesso violationsinskillcode.Toaddressthesechallenges,wepropose thattheinteractionmodelcanbetterlearnthesentencepattern.In SkillScannertoautomaticallyevaluateskills’conformitytovari- addition,intentscanoptionallyhaveargumentscalledslots.Slotis ouspolicyrequirementsbeforetheirdeployment.Comparedwith thevariablethatcancaptureaspecifictypeofuser’sverbalreply, existingdynamicanalysisworks[39,53,59],SkillScannertakes suchasusernameoruseraddress. astaticanalysisapproachandisexpectedtoidentifymorecode- When a skill is created, several default Amazon Alexa built- specificviolationsthatthedynamicanalysisapproachcannotfind. in intents are created automatically for basic functionality, e.g., Insummary,wemakethefollowingcontributions: Amazon.StopIntentforstoppingaskill,andAMAZON.CancelIntent • Toourbestknowledge,SkillScanneristhefirststaticanal- forcancelinganinstruction[20].Developerscanalsocreatenew ysistooltofacilitatethedevelopmentofpolicy-compliant intentsbyusinganAlexa’spre-definedintentorcreatingacustom skillsbythird-partydevelopers.SkillScannerisabletode- intent.Inthelattercase,developersdefinetheintentnameandthen tectvariouspolicyviolationsandcodedefects,whichcan providesomesampleutterancessothatwhenusersgiveareply effectivelyhelpdevelopersimprovethequalityoftheircode, semanticallyclosetotheseutterances,theintentwillbematched forasustainableVPAecosystem.WesharedtheSkillScan- andinvokedtoprocesstheuser’srequest.Anintentcaneitherbe nertool,relateddatasetsandresultswiththecommunityto usedforprovidingservices(e.g.,tellingastory)orcollectingdata facilitatefutureresearch1. fromusers(e.g.,askingfornamesfromusers).Ifdeveloperswant • Tounderstandtherootcausesoftheprevalenceofpolicy- tousetheintenttocollectdatafromusers,theyneedtodefineslots violatingskillsintheskillsstore,weconductedauserstudy andspecifytheslottype.Theslottypedefineswhatdatatheslot with34third-partyskilldevelopers.Theresultssuggestthat collects,anddeveloperscanuseAlexa’sbuilt-inslottypes,such mostskilldevelopersinourstudywerenotcompletelyaware as“Amazon.FirstName”trainedwiththousandsofpopularfirst ofthepolicyrequirementsdefinedbyAmazonAlexa. namesand“Amazon.City”forlocalandworldcities.Forexample, • WecollectedabenchmarkdatasetforAlexaskillcodewith inFigure1,GetNameIntentisacustomintent.Itcontainsaslot 2,451open-sourceskillsfromtheGitHub.Weconducteda “name”withthetype“Amazon.FirstName”,andthesampleutterance comprehensiveanalysisoftheseskillsusingSkillScanner is“Mynameis{name}”.Then,whenauserreplies“Mynameis
andevaluatedtheperformanceof SkillScanner.Weidenti- Jack”,“Jack”willbeextractedasaslotvalueandthenpassedtothe fied1,328differenttypesofpolicyviolationsamong786skills. back-endcode. 694ofthemareaboutprivacyissuesand298skillsviolatethe Back-endcode.Askill’sback-endcodeincludesalistofintent contentguidelinesdefinedbyAmazonAlexa.32%ofthese handlerfunctionsforprocessingdifferentintentsdefinedinthe policyviolationsarebecauseofcodeduplication(i.e.,code front-endcode.Forexample,GetNameIntentHandlerinFigure1 copy&paste).Table9summarizesourdetectionresults.Sur- isanintenthandlercorrespondingtotheintentGetNameIntentin prisingly,wefoundthat42skillcodeexamplesfromAlexa’s thefront-endcode.Severalbuilt-inintenthandlersareprovided officialaccountscontainpolicyviolations,whichledto81 byAmazonAlexacorrespondingtothebuilt-inintents,suchas 2AccordingtoAlexaDeveloperDocumentation[18],askillpackageincludestheskill’s 1Thedetailsofourtoolimplementation,evaluationresultsandrepresentativeskills front-endinteractionmodelfile,back-endsourcecodefiles,andskillmanifestfile.We areavailableathttps://github.com/CUSecLab/SkillScanner. refertothefront-endinteractionmodelasfront-endcodeinouranalysis.SkillScanner:DetectingPolicy-ViolatingVoiceApplicationsThroughStaticAnalysisattheDevelopmentPhase CCS’23,November26–30,2023,Copenhagen,Denmark 1 { 1 'LaunchIntentHandler': function() { 2 "name" : "GetNameIntent", 2 this.emit(':ask', '...please tell me your name? '); 3 "slots" : 3 }; 4 "name" : "name", Data collection 4 'GetNameIntentHandler':function() { 5 "type": "Amazon.FirstName", in output 5 if intent.name!= 'GetNameIntent': return 6 "samples": 6 name = request.intent.slots.name.value; 7 "my name is {name}" 7 save_name(name); 8 }, 8 this.emit(':tell', 'Thanks ' + name + '!'); 9 { 9 }; 10 "name" : "GetPermissionIntent", 10 'GetPermissionIntentHandler':function() { 11 "samples": Data collection 11 this.emit(':tell', 'You can set your name in the Alexa 12 "I don't know" with permission 12 companion app.'); 13 }, 13 name = AskForPermission(['read::alexa:name']) 14 { 14 save_name(name); 15 "name" : "Amazon.CancelIntent", 15 }; 16 "samples": 16 'save_name':function(name) { 17 "stop", Data storage 17 var ddb= new AWS.DynamoDB({Time}); 18 "cancel" 18 ddb.putItem(name) 19 } 19 }; Interaction model (Front-end code) Back-end code Figure1:Exampleofthefront-endandback-endcodeofanAlexaskill. HelpIntentHandlerforprovidinghelpfulinformation.Ifnointent only focused on the dynamic testing [39, 53, 59] and analyzing istriggered,theFallbackIntentHandlerwillbeinvokedandpro- the metadata of skills, such as permission information [35, 36], videanoutput“Sorry,Idon’tknowaboutthat.Pleasetryagain”by toidentifypotentialissuesinskills.Weaddressthischallengeby default.Typically,anintenthandlerprocessesthereceiveddata,per- collecting a skill code dataset from the GitHub. We have made formsskillfunctionsandprovidesareplytousers.InFigure1,the ourbenchmarkskillcodedatasetavailabletothecommunityto GetNameIntentHandlerretrievesthereceivednamevaluefrom facilitatefutureresearch. theuser’sverbalinput,storesitinalocaldatabase,andgenerates anoutputtothanktheuserforprovidingthename. 3 UNDERSTANDDEVELOPERS’PERCEPTION ANDPRACTICEREGARDINGPOLICY 2.2 Challenges COMPLIANCE The unique code structure of skills poses a challenge for WeconductauserstudytounderstandthegapbetweenVPA’s dataflowanalysis. Theback-endcodeofskillistightlycoupled policyrequirementsandskilldevelopers’practices.Theuserstudy withthefront-endcode.Userinputisfirstsenttothefront-end hasbeenapprovedbyouruniversity’sIRBoffice.Webrieflydescribe interactionmodel,matchedwithintent,andthenprocessedbythe therecruitment,surveyquestions,andresultsofouruserstudy. back-endcode,asshowninFigure1.Inthisexample,thereisa datacollectionrequestinline2oftheback-endcode.Fromthe 3.1 RecruitmentandSurveyQuestions front-endcode,weknowthatifusersprovideaname,itwillbe matchedwiththeintentGetNameIntent(lines2-8inthefront-end Thereareskilldevelopersleavingtheiremailsintheskilldescrip- code)andthentransferredtothefunctionGetNameIntentHandler tionsforuserfeedback.Webuiltacrawlertocollectskilldevelopers’ in the back-end code. Then, inside the function, the name data contactemailsfromtheUSskillsstoreandobtained1,568developer isstoredinalocaldatabaseandusedforoutput(lines16-18and emails.WeusedtheQualtricsplatform[13]tobuildsurveyques- line 8 in the back-end code). The Amazon Alexa platform also tionsandreachouttothesedeveloperstoinvitethemtoparticipate providesAPIsforskillstocollecttheinformationofdeviceaddress, inouruserstudy.Weincludedapre-screeningphasetoensurethat customer name, email address, phone number and location. In theparticipantsdohaveskilldevelopmentexperience.Finally,we Figure1,iftheuserdoesn’tprovideaname(e.g.,saying“Idon’t received44responsesbut10participants’responseshadtobere- know”),theGetNamePermissionIntentwillbeinvokedandthe movedduetothemeaninglessanswers.Oursurveywasconducted
skillwillcollecttheuser’snameinformationusingAlexa’sbuilt-in inAugust2022,andweprovideda$10Amazongiftcardtoeach permissionAPIAskForPermissioninline13oftheback-endcode. validparticipant.Theaveragetimeforcompletingthesurveywas Duetotheuniquecodestructureofskills,existingstaticanalysis 16minutes.AlthoughmostoftheparticipantsarefromtheUnited toolscannotbedirectlyappliedtoanalyzetheskillcodesincethey States,therewereafewdevelopersfromothercountriessuchas areunabletoadequatelymodeltheinteractionbetweenthefront- IndiaandItaly.10participantsdevelopedmorethan10skillsand endandback-endcode.InSkillScanner,wedevelopstaticanalysis theaveragenumberofskillsdevelopedbytheseparticipantsisover techniquestoextractconnectionsbetweenthefront-endcodeand 5,whichindicatesthattheyhaveenoughcodingexperienceinskill back-endcode. development.8participantsalsohaveexperienceofdeveloping Noexistingbenchmarksofskillcodeforstaticanalysis Googleactions. research.AsdiscussedinSection2.1,theback-endcodeofskills Table1listsseveralselecteduserstudyquestionsduetospace. ishostedonthedeveloper’sserveranddevelopersdon’tneedto The complete survey questions and responses are available in submitthecodeforskillcertification.Forthisreason,existingworks ourGitHubrepository(https://github.com/CUSecLab/SkillScanner),CCS’23,November26–30,2023,Copenhagen,Denmark SongLiao,LongCheng,HaipengCai,LinkeGuo,andHongxinHu whichiscomposedofthreesections.First,weaskeddevelopers #ofusersthat whethertheyareawareofAmazon’spolicyrequirements.Next,we Skill Violationtype Skilloutputthatcontains reporteda index apolicyviolation askeddeveloperswhethertheycouldidentifyanypolicyviolation violation Welcome to cake walk for inskilloutputsfrom8exampleskills(inwhichthereare5policy S2 Collectkidsdata kids!Canyoutellmeyour 21(62%✓) violationsintheseskills).Finally,weaskeddeveloperswhetherthey birthday? routinelyperformconsistencycheckingduringtheirskilldevelop- Askforapositive Ifyoulikethisskill,please S3 13(38%✓) ment,suchascode,content,privacypolicyandwhethertheythink rating giveusa5starrating. Call emergency Wecanalsocallhospitalor thatastaticanalysistoolcanbehelpfulforthemindeveloping S6 7(21%✓) responder emergencyresponders. policy-compliantskills. WouldyoulikeAlexatopre- S7 Predictgender 1(3%✓) dictthegenderofyourbaby? Disallowedinvoca- S8 thebirthday 5(15%✓) Question Response Developers tionname Completelyaware 65% S1,S4,S5 Noviolation N/A 21intotal(21%✗) Q1:Areyouawarethatthere Somewhataware 32% Table2:Policyviolationsinexampleskillsandtheresponses aresomeplatformrequiredpoli- Neitherawarenorunaware 0% from34participants(✓meansacorrectanswerand✗means cies? Somewhatunaware 3% anincorrectanswer). Completelyunaware 0% Always 24% Q2:DoyoureadtheAlexa’spol- Mostofthetime 26% toolforcheckingskillcodecouldbe“extremely”or“very”useful icyrequirementsbeforedevel- Abouthalfthetime 32% forpolicy-compliantskilldevelopment. opingskills? Sometimes 9% Never 9% Table2liststhepolicyviolationsinourexampleskillsaswell Q3:DoyouthinktheAmazon DefinitelyYes 29% asusers’responseresults.Foreachskill,weaskeddevelopers,“Do Alexaplatformshouldprovide ProbablyYes 47% youthinkthisskillviolatesanyAmazonpolicyrequirements?Ifso, apolicycompliancetrainingfor Itdoesn’tmattertome 6% whichpolicydoesitviolate?”. 21(62%)participantsreportedthat developersbeforetheydevelop Probablynot 18% thesecondskill(S2)containsapolicyviolation(i.e.,collectingkids skills? Definitelynot 0% DefinitelyYes 24% personaldata)andgavetherightreason.Only13(38%)developers Q4:DoyouthinktheAmazon ProbablyYes 47% wereawarethat“askingforapositiverating”isapolicyviolation Alexa platform should check the skill code to determine Itdoesn’tmattertome 18% (S3).Thispartiallyexplainswhythereareconsiderablepublished Probablynot 6% whetheritviolatesanypolicies? skillsintheskillsstoreviolatingthispolicy[59].Fortheotherthree Definitelynot 6% policy-violatingskillsthat“callemergencyresponder”,“predictgen- Always 26% Q5:Doyoucheckwhetheryour Mostofthetime 24% der”and“haveadisallowedinvocationname”(invocationname privacypolicyandcodearecon- Abouthalfthetime 35% hastwowordsandonewordisadefinitearticle“the”),only7,1 sistent? Sometimes 3% and5developerscorrectlyreportedtheviolations,respectively.In Never 12% addition,forthe3skillswithoutaviolation,21developerswrongly Always 35% Q6:Doyoufullyinspectyour Mostofthetime 32% thoughttheycontainedsomepolicyviolations. Ouruserstudy codeandremoveanyinconsis- Abouthalfthetime 9% resultsshowthatthereisanotablegapbetweenVPA’spolicyre- tentcodebeforesubmission? Sometimes 18% quirementsandskilldevelopers’practicesandperceptions.Such Never 6% observationsmotivateustodevelopastaticanalysistooltofacili- Table1:Selecteduserstudyquestionsandresponses. tatethird-partydevelopersindevelopingpolicy-compliantskillsas wellasimprovingthequalityoftheircode. 3.2 SurveyResults 4 SKILLSCANNEROVERVIEW Although33skilldevelopers(outof34participants)claimedthat
theyare“completelyaware”or“somewhataware”thatthereare ThreatModel.TheproposedSkillScannerismainlydesignedfor someplatformrequiredpolicies(Q1inTable1),mostparticipants benignthird-partydeveloperstoidentifypotentialpolicyviolations couldn’tcorrectlyrecognizethe5policyviolationsinourexample inskillsatthedevelopmentphase.Weassumethatinexperienced skills(resultsareshowninTable2).Whenasked“Doyouread developersmayunknowinglydevelopandpublishpolicy-breaking Alexa’spolicyrequirementsbeforedevelopingskills?”(Q2),only skillstothepublic,sinceouruserstudyresultsinSection3demon- 8developersselected“alwaysread”and3evenselected“never”. stratethattheyarenotcompletelyawareoftherelatedpolicies. 26participantsagreedthat“VPAplatformshouldprovideapolicy Theseproblematicskillscouldposeprivacy,safety,andsecurity compliancetrainingfordevelopersbeforetheydevelopskills”(Q3) threatstoVPAusers.SkillScannerisdesignedtorunlocally(which and24participantsthought“VPAplatformshouldchecktheskill alsoprotectsdevelopers’proprietarycode)toidentifypotential codeaboutpolicyviolation”(Q4).Although17developersselected policyviolationsandinconsistenciesinskillcode.Thus,weassume theywould“always”or“mostofthetime”checkwhetherprivacy thatthesourcecodeofskillsisprovidedbydevelopersasinputsof policyandcodeareconsistent(Q5),and23developersmentioned thetool.SinceSkillScanneraimstohelpbenigndevelopersimprove theywould“always”or“mostofthetime”checktheircodeconsis- thepolicycomplianceoftheirskills,foradversarialapplicationsce- tencybeforesubmission(Q6),SkillScanneridentifiedhundredsof nariossuchasadeveloperintendstoviolatethepolicy,itisout skillswithinconsistencyissuesinourskillcodedataset(detailsin ofthiswork’sscope.SkillScannercanbepotentiallyusedbythe Section6).Atlast,mostparticipantsthoughtthatastaticanalysis AmazonAlexaplatformforpolicyviolationdetectionifdevelopersSkillScanner:DetectingPolicy-ViolatingVoiceApplicationsThroughStaticAnalysisattheDevelopmentPhase CCS’23,November26–30,2023,Copenhagen,Denmark Interaction model Back-end code Skillmanifest file (Front-end code) Invocation Name Match Answer Question DataCollectionRequests Samples Description DataCollection PermissionValues Permission CaptureSlot Passing Slot Value Slot Values Privacy Policy Intent … Sensitive DataCollection 2 Data Flow Analysis 1 ActivityAnalysis 3 Detecting Privacy Using User Data Storing User Data Violation In Response In Database Detecting Inconsistency 4 5 Between the Front-end DetectingViolation of AllSkillOutputs Code and Back-end Code Content Guidelines Figure2:SystemOverviewofSkillScanner. provideaccesstotheirskillcodetoAmazonAlexaduringtheskill guideline(❹).Atlast,apoorly-writteninteractionmodel(i.e.,the certificationprocess. front-endcode)maytriggerincorrectintentandreturnuserswith SystemOverview.Withthegoalofensuringprivacyandpolicy contenttheydon’texpect.Suchpooruserexperiencecanleadto complianceintheAmazonAlexaecosystem,SkillScannermainly userfrustrationandadecreaseinuserengagement.Tofacilitate focusesondetectingviolationsofprivacyrequirements[7]andskill developerstoimprovethequalityoftheircode,SkillScanneralso contentguidelines[6](whichallskillsmustadheretoaccording detects inconsistencies in the back-end and front-end code (❺). totheAmazonAlexadocumentation),aswellasinconsistencies Withthehelpof SkillScanner,developerscanimprovetheircode inskillcode.Figure2showsthedesignoverviewof SkillScanner. qualitybasedonthepolicyviolationreportandprovideabetter Todetectdatacollectionrelatedissues,wefirstextractdatacollec- userexperienceofskills. tionactivitiesbyanalyzingboththeback-endcodeandfront-end code(❶).Askillcancollectuserdatathroughtheconversational 5 SYSTEMDESIGNANDIMPLEMENTATION interfaceorusingAlexa’sbuilt-inpermissionAPIs.Forcollecting 5.1 SensitiveDataCollectionActivityAnalysis userdatathroughtheconversationalchannel,askillnormallyasks questionssuchas“Howoldareyou?”intheback-endcode.We Tolearnwhatdataaskillisabletocollect,weneedtoanalyzeboth extractallpotentialskilloutputsandthenconductanNLPanalysis theback-endandfront-endcode.Thefront-endcodeisstoredina oftheseoutputstocheckwhethertheycollectanyuserdata.Then JSONfileandtheback-endcodeiswritteninJavaScriptorPython wefindcorrespondingdatacollectionslotsinthefront-endcode language.Wefirstdefinethesensitive/personaldatatypesthatare bycheckingwhethertheslotnameandslottypecontainanydata consideredinSkillScanner,including1)24typesofPII(personally collectionkeywords.Developerscanalsodirectlycollectuserdata identifiableinformation)fromaNIST(NationalInstituteofStan- byrequestingforspecificpermissionstoaccessuserdatainthe dardsandTechnology)report[46]andAmazon[14],2)Amazon’s back-endcode.Weidentifysuchdatacollectionactivitiesbycheck- built-inslottypes[19]suchas“Amazon.Person”forgettingthe ingifanypermissionAPIisusedinthecode.Next,SkillScanner usernameand“Amazon.US_City”forUScities;3)specifictypesof trackshowthecollecteddataisusedinskillcodebyconductinga datathatcanbecollectedthroughthepermissionAPIs[2];and4) taintanalysis(❷).Thesourceoftaintanalysiscanbeadatacollec- commonhealthinformation.Thekeywordsaboutdatacollection
tionslotvalueorthereturnedvaluefromapermissionAPIinthe arelistedinTable3. back-endcode.Askillmayusethecollecteduserdatainresponse (e.g.,toestablisharapportwithusers),storethedatainalocal 5.1.1 Identifyingconversationalsensitivedatacollectionactivities. database,orneverusethedataintheback-endcode. Ouranalysisstartsfromidentifyingdatacollectionrequests(e.g., Afterthetaintanalysis,wecheckwhetherthedatacollection “Whatisyourname”or“Pleasetellmeyourname”)fromaskill’s anddatausageincodeareconsistentwithwhatdevelopersclaimed possibleoutputs.Wesearchforallstringsintheback-endcode intheskillmanifestfile(❸).Forexample,developersarerequired (excludingcomments).Givenanoutputextractedfromastring,we toprovideaprivacypolicydocumenttooutlinedatacollection applyanNLP-basedmethodandusetheSpacylibrary[21]tocheck andusage,andtheremightbeinconsistenciesbetweentheprivacy ifanydatacollectionkeywordisusedasanounbecausesome policyandtheactualdatacollectionactivitiesinthecode.Inad- keywordslike“address”canbeusedasaverb.Developersmayalso dition,developersmayrequestformoreorlesspermissionsthan providetheirowndata,sowecheckwhetheranyPIIdataisused theyactuallyneed.Amazonalsodefinesadiverserangeofcontent asanounfollowingtheword“your”.Ifasentencecontains“your+ guidelines,rangingfromskilloutputcontentsafetytouserreview sensitivedatacollectionnoun”,weconsideritasadatacollection manipulation(e.g.,explicitlyrequesting5-starratings).Toensure request.Inaddition,wechecktheoutputwithalistofcommon compliancewithcontentguidelines,SkillScanneranalyzesallskill sentencesofpersonaldatacollection[59],suchas“howoldareyou” outputstocheckwhetherthereexistsanyviolationofthecontent or“whatcanIcallyou”toimproveaccuracy.Totrackwhetheruser provideddatacanbeproperlyprocessedandpassedtothefront-endCCS’23,November26–30,2023,Copenhagen,Denmark SongLiao,LongCheng,HaipengCai,LinkeGuo,andHongxinHu 5.2 DataFlowAnalysis Address,Name,Email,Birthday,Age,Gender,Account, Location,Contact,Phonebook,Profession,Income, Personally Ifaskillcontainsanydatacollectionactivity,wetrackhowthe Zipcode,Postalcode,Phonenumber,Passportnumber, Identifiable Driverlicensenumber,Bankaccountnumber,Debitcard collecteduserdataisusedbyconductingataintanalysisintheback- Information number,Creditcardnumber,Creditcardverificationcode, endcode.Ourobjectiveistocheckwhetheruserdataisproperly (PII)[14,46] Taxpayeridentificationnumber,SocialSecuritynumber usedorsavedintodatabases,whichisusefulfordetectingprivacy (SSN),Vehicleidentificationnumber(VIN) relatedviolationsinSection5.3.Forexample,inListing1,weknow FirstName,Person,US_FirstName,PhoneNumber, theslotvalueuserNameandpermissionvalueprofileEmail(in Amazon’s PostalAddress,Region,RelativePosition,City,US_City, built-inslottypes AdministrativeArea,StreetAddress,StreetName,US_State, lines 8 and 18) are data collected from users. By tracking their Professional,ProfessionalType dataflows,welearnthatthesetwovaluesareusedforgenerating Datatypes customizedresponses(inlines12and20)andstoringtothedatabase Profile:Name,Given_name,Email,Mobile_number supportedby Devices:Address,CountryAndPostalCode,Geolocation (inline10). permissionAPIs Height,Weight,Bloodgroup,Bloodpressure,Blood 1 const LaunchRequestHandler = { Health glucose,BloodOxygen,Heartrate,Bodytemperature, 2 handle(handlerInput){ Information Sleepdata,Fatpercentage,Massindex,Waist 3 const speakOutput = 'Hello! What is your name?'; // Ask circumference,Menstruation,Period for user name 4 return handlerInput.responseBuilder.speak(speakOutput). Table3:Keywordsrelatedtopersonaldatacollection. reprompt(speakOutput).getResponse(); 5 },}; 6 const CaptureUserNameHandler = { code,weneedtoanalyzeslotsandsampleutterancesofeachintent 7 handle(handlerInput){ inthefront-endcode.AsintroducedinSection2,whenusershear 8 const userName = handlerInput.requestEnvelope.request. intent.slots.name.value; // Get name from slot aquestionandmakeareply,thereshouldbeanintentandslotfor 9 const sessionAttributes = handlerInput.attributesManager. getSessionAttributes(); processingthereply.Ifaslotincludesanydatacollectionkeyword 10 sessionAttributes.name = userName; // Store name in listedinTable3initsnameorslottype,wedefinesuchslotasa database sensitivedatacollectionslot,e.g.,aslotnamedas“username”with 11 const speakOutput = 'Thanks ${userName}'; 12 return handlerInput.responseBuilder.speak(speakOutput). theslottype“Amazon.FirstName”.Similartoidentifyingsensitive reprompt(speakOutput).getResponse(); // Use name datacollectionrequests,ifasampleutteranceincludes“my+{data for response 13 },}; collectionslot}”,weconsideritasadatacollectionutterance. 14 const EmailIntentHandler = { Wecaptureconversationaldatacollectionactivitiesofaskillby 15 handle(handlerInput){ 16 const { serviceClientFactory, responseBuilder } = checkingthefollowingthreeconditions:1)whetherthereexists handlerInput; adatacollectionrequestaskingforuserdata;2)whetherthereis 17 const upsServiceClient = serviceClientFactory. getUpsServiceClient(); anysampleutterancethatcanbematchedtopotentialuserreplies 18 const profileEmail = await upsServiceClient.
tothisdatacollectionrequest;and3)whetheraslotofthesam- getProfileEmail(); // Get email from permission 19 const speechResponse='Your email is ${profileEmail}'; pleutteranceisusedtocapturesensitiveuserdata.Theback-end 20 return handlerInput.responseBuilder.speak(speechResponse) codecouldnotcorrectlygetuserdatathroughtheconversational .reprompt(speechResponse).getResponse(); // Use email for response interfaceifmissinganyoneoftheseconditions.Onceweidentify 21 },}; conversationaldatacollectionactivitiesintheskillcode,thecor- Listing1:Real-worldskillcodewithsensitivedatacollection. respondingslotvaluesareusedastaintsourcesinourdataflow analysisinSection5.2.1. 5.2.1 Taintsources. Askillcanobtainuserdatabyretrievingslot valuesorpermissionvalues,whicharethesourcesofourtaint 5.1.2 Identifyingdatacollectionpermissionrequests. Anotherway analysis.WedescribehowSkillScannerlocatestaintsourcesinthe foraskilltocollectuserdataistorequestpermissionsforcustomer back-endcode. information,whichisfromtheuser’sAlexaaccount.Amazonstates Slotvaluesastaintsources.Therearetwowaysinaskill’s that“Alexaskillsmightrequirepersonalinformationfromthecus- back-end code to retrieve slot values. 1) The first method is to tomerinordertoproviderelevantinformationinskillresponses sendrequestsandgetslotvalues.Theback-endcodecanusea ortocompletetransactions”.Table3liststhedatatypesthatare requesthandlertohandleintentandgetslotvalueswith“handler- consideredforpermission-baseddatacollectionactivityanalysis Input.requestEnvelope.request.intent.slots”.2)Thesecondmethod inSkillScanner.Inthismethod,developersfirstrequestforper- isusingtheAlexaSkillsKit(ASK)SDK,whichprovidesseveral missionsintheAmazonAlexadeveloperconsole,andpermission functionsforretrievingslotvalues.Developerscandirectlycall requestinformationisstoredintheskillmanifestfile.Beforeac- “Alexa.getSlotValue”anduseslotnameasparametertogetaslot cessingdata,askillneedstogetauser’sgranttoaccesspermission value.Accordingly,afteridentifyingconversationaldatacollection data when a user first enables the skill. Once granted, the skill activitiesinaskill(inSection5.1.1),weusethe“intent.slots”and canretrievetherequestedpermissiondatausingdifferentmeth- “Alexa.getSlotValue”assourcesinourtaintanalysis. odsintheback-endcode:eitherdirectlyusingcertainpre-defined Permissionvaluesastaintsources.Askillobtainspermis- endpointsorcallingpermissionAPIs.Sincetheyexhibitdistinct sionvalueseitherthroughpre-definedendpointsorpermission patterns,wecaneasilyidentifydatacollectionpermissionrequests APIsintheback-endcode.1)Askillcandirectlyaccesspre-defined intheback-endcode.Forexample,inline18ofListing1,theuser endpointstogetcustomers’contactinformationandsettinginfor- emaildataisobtainedfromapermissionrequest,andthuswetake mationsuchasaddressorpostalcode.Table4liststhepre-defined thisvalueasthetaintsourceofthedataflowanalysis. endpointsinAlexa,includingtwotypesofuserdata:deviceaddressSkillScanner:DetectingPolicy-ViolatingVoiceApplicationsThroughStaticAnalysisattheDevelopmentPhase CCS’23,November26–30,2023,Copenhagen,Denmark 5.3 DetectingPrivacyViolation RequestedInformation Endpoints Device Address/ Device /v1/devices/{deviceId}/settings/address Amongthevariouspolicyviolationproblemsreportedbyrecent CountryandPostalCode (/countryAndPostalCode) research[36,39,41,43,53,59],manyissuesarerelatedtothepri- FullName/GivenName/ /v2/accounts/~current/settings/Profile.name vacypolicy.Inparticular,Jideetal.[36]performedalongitudinal Email/PhoneNumber (/givenName/email/mobileNumber) measurementofprivacypoliciesofskillsacrossthreeyears.They FullName/GivenName/ /v2/persons/~current/profile/name PhoneNumber (/givenName/mobileNumber) showthatmanydeveloperswerenotengagingingooddataprac- Table4:Pre-definedendpointstoobtainpermissiondata tices,whichisstillanunresolvedissue.Intheskillmanifestfile, wecanobtainseveraltypesofskillinformationsuchasskillname, (denotedas“/v1/”)andcustomerprofile(denotedas“/v2/”).Forthe category,description,privacypolicy,permission,etc.SkillScanner customerprofile,Alexaprovidesinformationaboutthename(full detectsproblematicprivacypoliciesandinconsistenciesbetween nameandgivename),emailandmobilephonenumber.SkillScan- theback-endcodeandthedisclosedinformationprovidedbyde- nersearchesforallstringvaluesincodewithendpointslistedin velopersaccordingtotheskillmanifestfile. Table4andtreatsthereturnedvaluesoftheseendpointsasthetaint sources.2)Thesecondapproachofobtainingpermissionvaluesis 5.3.1 Problematicprivacypolicy. AccordingtoAlexa’sprivacyre- touseAlexaServiceAPIs.Amazonprovides“DeviceAddressSer- quirements[7],itrequiresthatskillswithdatacollectionactivities viceClient”forgettingdeviceaddressesand“UpsServiceClient”for mustprovideaprivacypolicyURLthatlinkstoalegallyadequate customerprofiles.Forexample,askillcangetthedeviceaddress privacypolicywebpage.TheprivacypolicyURLwillbedisplayed through“DeviceAddressServiceClient.getFullAddress()”orobtain toendusersonaskill’swebpageintheskillsstore.Givenaskill
user email with “UpsServiceClient.getProfileEmail()” (as shown sourcecodepackage,SkillScannerfirstchecksiftheskillprovides inline18ofListing1).Wealsotakethereturnedvaluesofthese avalidprivacypolicylink(i.e.,notabrokenlinkorleadingtoan permissionrequestsasthetaintsources. unrelatedwebpage).Basedontheresultsofthesensitivedatacollec- tionactivityanalysisinSection5.1andtaintanalysisinSection5.2, 5.2.2 Taintsinks. Wemainlytracktwodatausagecasesinaskill,1) wecheckwhetheraskill’sdatacollectionandusageareproperly usingthecollecteduserdataintheresponseor2)storingthedatain disclosedinitsprivacypolicy.Ifaprivacypolicyisprovidedbut alocaldatabase.Typically,askilluses“handlerInput.reponseBuilder” thedatapracticesarenotmentionedinit,suchprivacypolicyis togenerateaverbalresponsebycalling“.ask(output)”,“.speak(out- incompletesinceitdoesn’tdisclosethesufficientinformation.Fig- put)”,or“.reprompt(output)”.Totrackifthecollecteddataisused ure4showstwoskillsthatmissaprivacypolicyorprovidean ingeneratingcustomizedskillresponses,wesearchforthesefunc- incompleteprivacypolicy.Foreachsentenceinaprivacypolicy, tionsintheback-endcodeandusethemastaintsinks.Skillscan wecheckwhetheritmentionsanysensitivedatacollectionordata alsosavetheuserdatatoadatabasesothattheycanusethem storageactivity.Forthedatacollectionactivity,wecheckwhether forotherpurposes.Ifaskillneedstostoredatainadatabase,it adatacollectionverb,suchas“collect”,“ask”or“access”andthe usuallyfirstbuildsthedatabaseconnection.Developersneedtocall collecteddataappearinthesamesentence.Forthedatastorage specificAPIstocreateorretrievedatafromaDynamoDBdatabase activity,wecheckifthe“store”verbs,suchas“keep”,“retain”or providedbyAmazon,orsavedatatotheAlexasessionattribute. “store”,andcollecteddataareinthesamesentence[28,60]. ThesedatabaseAPIsareconsideredastaintsinksinSkillScanner. "permissions": [ Taint Sink Taint Source 1 store name { "name": "alexa::profile:given_name:read" }, 1 to database ], asking for user name slot.value userName use name "privacyAndCompliance": { There should be a 2 2 for response "locales": { privacy policy link "en-US": { }}} permission use email for value 3 profileEmail 3 response (a)Missingaprivacypolicy(fromskill“BobaMaker”) Figure3:DataflowscorrespondingtoListing1. 5.2.3 Trackingdataflows. Sinceaskillcanbewrittenindifferent programminglanguages,weusetheCodeQLtool[8]thatsupports multipleprogramminglanguagestotrackdataflowsofdifferent User nameand phone number are used in code but not variablesinskillcode.WedemonstratetheperformanceofCodeQL mentioned in privacy policy inSection6.3anditperformswellinourresults.Figure3shows thedataflowanalysisresultscorrespondingtothecodeinListing1. SkillScanneridentifiesthreedataflows,thefirstoneisfromthe (b)Incompleteprivacypolicy(fromskill“feedmenow”) sensitivedatacollectionslotvalue(userNameinline8ofListing1) Figure4:Examplesofproblematicprivacypolicies. tothedatabaseusage(line10ofListing1)andtheseconddataflow goestoaspeakeroutput(line12ofListing1).Thethirddataflowis 5.3.2 Over-privileged data collection permission requests. Over- fromthepermissionrequestofuseremailaddress(profileEmail privilegeddatacollectionpermissionrequestsrefertoaskillre- line18ofListing1)toaspeakeroutput(line20ofListing1). questingmorepermissionsthanitrequires[54],andthustheskillCCS’23,November26–30,2023,Copenhagen,Denmark SongLiao,LongCheng,HaipengCai,LinkeGuo,andHongxinHu violates the principle of least privilege. With the taint analysis, andcheckedwhetheritincludesanypolicyviolationsuchasdata SkillScannerchecksifaskillrequestsforpermissiondatabutnever collectionortoxiccontent.Wealsodetectifanoutsidewebsiteis usesitintheback-endcode.SkillScanneralsodetectsifaskilltries flaggedbyViruslTotal[23]asasuspiciousormaliciouswebsite. touseapermissiontoretrieveuserdatabutdoesn’taskforthat For the skills retrieving data from external websites, we check permissionfirst. whetherthewebpagecontainsanyinappropriatecontentaccording toAmazonAlexa’scontentguidelines. 5.3.3 InconsistentdatacollectiondisclosuretoAlexaplatform. Ama- zonprovidesaselectionfordevelopersbeforesubmittingaskillfor 5.4.2 Non-compliance of invocation names. Under the Amazon certificationthatasks“DoesthisAlexaskillcollectusers’personal Alexa’scontentguidelines,thereisaspecialcategoryforskillinvo- information?”anddeveloperscanselect“yes”or“no”(theycan cationnamesandseveralrequirementsarelisted,suchas“one-word alsochoosetonotanswerthisquestion).Differentfromaprivacy invocationnamesarenotallowed”and“theinvocationnamemust policy,whichisprovidedforendusers,suchaquestionisfordevel- notcontainanyoftheAlexaskilllaunchphrases”.Moredetails operstodisclosedatacollectionbehaviortotheAlexaplatformand aboutinvocationnamerequirementsanddisallowedwordsaswell certificationteam.Researchersin[32]observedthatifadeveloper asrepresentativeviolationcaseswefoundusingSkillScannerare selectsnotothisquestionbuthis/herskillcollectsdatathrough listedinTable5.Sinceaskill’sinvocationnameinformationis
theconversationalinterface,itismorelikelytheskillcouldby- storedinthefront-endcode,SkillScannerextractsaskill’sinvoca- passthecertificationprocess.Thedeveloper’sanswerinformation tionnameandcheckswhetheritviolatesthepolicyrequirements. canbefoundintheskillmanifestfile.Basedontheresultsofour datacollectionactivityanalysis,SkillScannerchecksifanyincon- Exampleinvocation sistentdatacollectiondisclosurebetweentheback-endcodeand RequirementsonInvocationName nameswithviolation developers’answers. One-wordinvocationnamesarenotallowed,unlessthe beeper, invocationnameisuniquetoyourbrand/intellectual jokes 5.4 DetectingViolationofContentGuidelines property. Two-wordinvocationnamesarenotallowedifoneof thetemplate, TheAmazonAlexaplatformhasdefinedalistofcontentguide- thewordsisadefinitearticle(“the”),indefinitearticle theradiator lines[6],describingtheinappropriatecontentthatskillshouldnot orpreposition. delivertousers.Theseinvolvedisturbingcontent,falseinformation, TheinvocationnamemustnotcontainanyoftheAlexa playradio, skilllaunchphrases(suchas“play”,“launch”,“open”), profanity,etc.Inthissection,wefocusonensuringthecontent tojeff, connectingwords(suchas“to”,“about”,“and”)orwake videoapp safetyandcomplianceofinvocationnames. words(suchas“Alexa”,“skill”,“app”). Theinvocationnamemustcontainonlylower-caseal- AlTranslate, 5.4.1 Contentsafetyviolations. SkillScannermainlychecksthreetypes phabeticcharacters,spacesbetweenwords,andposses- Ryan’snote ofcontentviolations:toxiccontent,userreviewmanipulationand siveapostrophes. Theinvocationnameshouldbedistinctivetoensure helloworld contentsafetyofexternalwebsitesinvolvedinaskill’sback-end userscanenableyourskill. (usedby85skills) code.SkillScannerdetectswhetherthereexistspotentialtoxiccon- Table5:Invocationnamerequirements[6]. tentinskilloutputsbyusingGoogle’sPerspectivetool[11],whichis amachinelearningbasedtoolfordetectingtoxiccontent.SkillScan- 5.4.3 Category-specificviolations. Amazondefinesspecificpoli- nerextractsallpossibleskilloutputsfromaskill’sback-endcode. ciesforselectedcategories,suchas“Kids”and“Health&Fitness” Ifanyskilloutput’sToxicityandProfanityscoresarehigherthan categories.ForskillsintheKidscategory,theycan’tincludeun- thethreshold(0.9),SkillScannergeneratesawarningofpossible suitablecontent,directuserstoexternalwebsites,orcollectany toxiccontentfordevelopers. personalinformation[3],regardlessofwhetheraprivacypolicy Toavoiduserreviewmanipulation,AmazonAlexaenforcesa isprovided.FordatacollectioninKidsskills,weusedthesame policyprohibiting“Explicitlyrequeststhatusersleaveapositive methodasdescribedinSection5.1todetectdatacollectionrequests ratingoftheskill”.SkillScannercheckswhetheraskillexplicitly andthemethodinSection5.4.1tocheckskilloutputsaboutexternal asksfortheusertoprovideapositiveratingintheskilloutputs websitesandtoxiccontent.FortheHealthcategory,Alexarequires aswellastheskilldescription.Wedetectthisviolationusingan thattheskillmust“includeadisclaimerintheskilldescription NLP-basedmethodbycheckingwhetherkeywordssuchas“5star” statingthattheskillisnotasubstituteforprofessionalmedical or“fivestar”areusedfollowedbyverbs“give”or“leave”. advice”[4].Wecheckedwhetherthewords“medicaladvice”,“edu- A skill’s back-end code may contain external websites from cationalpurpose”or“informationpurpose”,whicharekeywords whichtheskillcancallHTTPrequeststogetdata(e.g.,pre-recorded takenfromanexampledisclaimerprovidedbyAlexa,showupina audiostreamsandimages)fromanexternaldatasource.Modern skill’sdescription. VPAdevices(e.g.,AmazonEchoShow)candisplaydifferentmedia filesincludingtext,imagesandevenmovies.Weconsiderthree 5.5 DetectingInconsistencyBetweenthe differentcasesthatwebsitesareinvolvedinskillcode:1)retrieving Front-endCodeandBack-endCode audiodatasuchas“mp3”files;2)retrievingimagedatasuchas“jpg” files;or3)retrievingtextualcontentfromexternalwebsites.For AsmentionedinSection2.1,intents(aswellassampleutterances audioandimagefiles,wefirstdownloadthemandthenusespeech- andslots)inaskill’sfront-endcodeandtheback-endcodeare to-text[22]andimage-to-texttools[12]toextractthetextualdata tightlycoupled.Typically,developersdefineadatacollectionre- fromthesefiles.Theoutputdataistreatedasnormalskilloutput questintheback-endcode(e.g.,what’syourname),createanintentSkillScanner:DetectingPolicy-ViolatingVoiceApplicationsThroughStaticAnalysisattheDevelopmentPhase CCS’23,November26–30,2023,Copenhagen,Denmark basedonpossibleuserrepliesinthefront-endcode,andthencre- codefromGitHub,whichisoneofthelargestopen-sourceproject atethecorrespondingintenthandlerforprocessinguserreplies platforms.Theuniquefilestructure(e.g.,everyskillcomeswith intheback-endcode.Inconsistencyamongthemcouldtriggerin- afront-endcodefile“en-US.json”)ofskillpackagesallowsusto correctintentsandimpactuserexperience.Forexample,ifaskill accuratelylocateskillcodeinGitHub.Specifically,wesearcheda
asksforuserdatathroughtheconversationbutdoesn’thavean combinationofkeywords“en-US.json”(front-endcodefilename), intentforprocessingtheuserreply,theskillwilltriggerabuilt- “interactionModel”,“languageModel”and“intents”forthefront- inintent“FallbackIntent”whichreplies“Sorry,Idon’tknowthat. endcodefileusingGitHubsearchAPI.Finally,wewereableto Pleasetryagain”.Amazonrequiresdevelopers“reviewingthein- find2,451skillrepositoriesafterremovingduplicateskillsandwe tentschema,thesetofsampleutterances,andthelistofvalues sharedthedatasettofacilitatefutureresearch(https://github.com/ foranycustomslottypesdevelopershavedefinedtoensurethat CUSecLab/SkillScanner).Table6showsthestatisticsofskillcode theyarecorrect,complete,andadheretovoicedesignbestprac- inourdataset. tices”[1].So,SkillScanneralsodetectspotentialbugsandimproves thecodequalityearlyintheskilldevelopmentlifecyclebecauseof Total#ofcustomintents 7,880 itsinfluenceonskillfunctionanduserexperience. Front-endcode Total#ofslots 5,702 SkillScanner detects three cases of code inconsistency. 1) A Total#ofsampleutterances 67,884 Back-endcode Total#offunctions 26,216 skill’sback-endcodehasarequestaskingforuserdata,butthere Total#ofskills 2,451 isnoslotinthefront-endcodeforprocessingtheuserreply.2) Table6:Statisticsofskillcodeinourdataset. A skill defines a slot to obtain users’ possible data but there is norequestintheback-endcodeaskingforuserdata.3)Adata SincetheskillsinourdatasetwerewritteneitherinPythonor collectionslotoranintentdoesn’thaveanysampleutterances.If Node.js,ourdataflowanalysismodulehastwoversions.Weran so,theycouldnotmatchwithanyuserreply,andthustheslot SkillScanneronaserverwith3.0GHz6-coreCPUand16GBRAM. or intent will never be triggered. The second case is actually a Finally,SkillScanneranalyzed2,451skillsintotalandobtained codevulnerability[32,54]duetothefactthattheAmazonAlexa 797,501skilloutputs,1,656HTMLwebpages,1,439mp3filesand platformdoesnotrequireare-certificationwhenachangeismade 932imagesinourexperiments.Theoutputof SkillScannerisa intheback-endcodeofaskill.Ifaskillhasadatacollectionslot reportthatnotifiesdevelopersaboutpotentialpolicyviolationsor but doesn’t have a data collection request asking for user data, bugsandthecorrespondingcodelocation.Then,developerscanfix aftertheskillhasbeencertifiedandpublishedintheskillsstore, theseissues,otherwisetheskillmayfailinthecertificationprocess. developerscanarbitrarilychangetheback-endcodeandaskfor Bycomparingskills’names,developersanddescriptionsofskills anytypeofuserdata.Benigndevelopersmaycollectuserdatafor inourdatasetandskillsintheAlexaskillsstore,wefoundthat93 non-maliciouspurposesbutunintentionallyviolatepolicyafterthe skillsinourdatasethavebeenpublishedintheskillsstore.Wedid codeupdate(e.g.,collectingusernamesandusingthemtoestablish noticethatthereexists“toy”projectsinourdataset,whichhave arapportwithusers).SkillScannerremindsdevelopersofsuch asinglecontributor,fewcommits,andnon-informativereadme potentialpolicyviolations.SinceAmazonAlexacannotcheckthese files.Aspreviousworksdemonstrate,mostskillsaredevelopedby consistenciesattheskillcertificationphase,SkillScannerfacilitates third-partydevelopersandtheseskillsareeasytobepublished[32], developerstodetectpotentialcodedefectsthataredifficulttofind andalsothequalityofthesepublishedskillsisnotgood[39,59]. forimprovements. Inourdataset,15%ofskillsthatarepublishedhavearepository with1contributor,lessthan10commitsandlackareadmefile. 6 EVALUATION Sincetheselow-qualityskillsarealsopossibletobepublishedto Inthissection,weevaluateSkillScannerbyansweringthefollow- theskillsstore,wedidn’tremovethemfromourdataset. ingthreeresearchquestions: 6.2 SensitiveDataCollectionActivityAnalysis RQ1:HoweffectiveisSkillScannerincapturingsensitivedata collectionandusagebehaviorsinskills?(§6.2and§6.3) Aftergettingallpossibleoutputsfromeachskill’sback-endcode, RQ2:HoweffectiveisSkillScannerinidentifyingpolicyviolations we observed that 321 skills contain sensitive data collection re- inopensourceskills?(§6.4,§6.5,and§6.6) questsaskingforuserdatathroughtheconversationalinterface. RQ3:SkillScannerfoundmanysimilarviolationsindifferentskills. 197ofthemhavesensitivedatacollectionslotsinfront-endcode What’sthemainreasonforthesesimilarpolicyviolations?(§6.7) toprocessthecollecteddata.Fortheother124skillsthatdon’t haveadatacollectionslot,wewilldiscussthisissueinSection6.6.1. 6.1 SkillSourceCodeCollection&Setup Overhalfoftheskillsaskforthenameinformationfollowedbythe Beforediscussingtheevaluationresults,weexplainhowwecol- birthday,emailandaddressinformation.Skillsalsoaskforseven lectedopensourceskillcodefromGitHubandthesetupthatwe othertypesofdatasuchasage,gender,location,phonenumber usedtoperformtheevaluation. orzipcode.Themostcommondatacollectionrequestsare“You Incontrasttotraditionalappsonsmartphoneplatforms(e.g., canintroduceyourselfbytellingmeyourname”and“Whatisyour Android or iOS) where apps run on host smartphones, a skill’s name?”.Forexample,theskill“E-Nurse”speaksout“Kindlytell
back-endcoderunsonthedeveloper’sserver,andisnotavailable meyourname”whenitisinvoked.Inthefront-endcode,itde- evenfortheAmazonAlexaplatform.Wecannotobtainskillcode finesanintentcalled“NameIntent”andoneslot“name”withslot fromtheAlexa’sskillsstore.Instead,wecollectedopen-sourceskill type“Amazon.FirstName”.Twosampleutterancesare“mynameisCCS’23,November26–30,2023,Copenhagen,Denmark SongLiao,LongCheng,HaipengCai,LinkeGuo,andHongxinHu {name}”and“Iam{name}”.Inaddition,wefoundthat133skillsre- theemailandusernameinformationbutonlythenameisusedin questforpermissiondata.Forexample,askillnamed“PizzaSearch” theskillresponse,andthusitisflaggedasanover-privilegedskill. requestsfor7permissionsincludingfivesensitivedatacollection SkillScannercaneffectivelydetectsuchissuesandwarndevelopers permissionsforaddress,location,email,mobilenumberandname tofixthemduringthedevelopmentphase. information.Overall,SkillScannerachieveshighaccuracyforthe sensitivedatacollectionactivityanalysis.Aftermanuallycheck- 6.4 PrivacyViolationDetection ingalltheresults,only15sentencesarefalsepositivecasesout Whenskillscollectdatafromusers,theyshouldalsoprovidecom- of767sensitivedatacollectionrequests,withanaccuracyof98%. pleteandinformativeprivacypoliciesfordisclosingsuchdatacol- SkillScannerachieves99.7%accuracyinidentifyingdatacollection lectionactivities.AmazonAlexaalsoasksdevelopers“Doesthis slotsand100%forpermissionrequests.Mostfalsepositivesoccur Alexaskillcollectusers’personalinformation?”duringtheskill insentencesthatinclude“your+sensitivedatacollectionnoun” submissionphrase.However,weobservedthatmanyskillsfailed butdonotaskfordata,suchas“Yourlocationisaround...”.The indisclosingtheirdatapracticesintheirprivacypolicydocuments. recallratesforeachpartare84%,93%,and91%,respectively.The falsenegativesarebecauseofthediversewaystoaskforuserdata #of #ofskillsmissing #ofskillshavingan (e.g.,“HowshouldIcallyou?”and“Pleasespecifyanaddress.”)or skills aprivacypolicy incompleteprivacypolicy inabilitytolocateandreadtheskillfile. Datacollection 321 240(75%) 19(6%) request 6.3 DataFlowAnalysis Askforpermission 133 94(71%) 23(17%) Storeslotvaluein 89 81(91%) 4(4%) database 1 //back-end code: Storepermission 2 const ScheduleTripIntentHandler = { valueindatabase 57 45(79%) 6(11%) 3 ... 4 const email = await upsServiceClient.getProfileEmail(); Table7:Numberofskillswithprivacypolicyissues. // Get user email 5 co Gn is vt eng Ni av me en (N )a ;me = await //up Gs eS ter uv si ec reC nl ai me ent.getProfile 6.4.1 Problematicprivacypolicy. Aprivacypolicyshouldclearly 6 ... describehowuserdataiscollected,usedandshared.However,after 7 const speechText = 'Enjoy your trip, ${givenName}!'; checkingtheprivacypoliciesofalldatacollectionskills,wefound // Only name is used, thus here is an over-privilege issue in the skill. thatonly19%oftheskillsprovideacompleteprivacypolicy.Table7 8 return handlerInput.responseBuilder.speak(speechText). showsthebreakdownofprivacypolicyissuesindifferenttypesof reprompt(speechText).getResponse(); 9 }; datacollection.Forthe321skillswithdatacollectionrequests,most 10 ofthemhaveinconsistencyissuesbetweentheirdatacollection 11 //manifest file: 12 "permissions": [ requestandprivacypolicies.75%ofskillsdon’tprovideaprivacy 13 {"name": "alexa::profile:given_name:read"}, policyand6%ofskillsprovideanincompleteprivacypolicythat 14 {"name": "alexa::profile:email:read" 15 ], doesn’tclaimtheiractualdatacollectionbehavior.Forthe133skills 16 "privacyAndCompliance": { askingfordatawithpermissions,71%ofthemlackaprivacypolicy 17 "locales": { and17%ofthemhaveanincompleteprivacypolicy. 18 "en-US": {} // Here should be a privacy policy link but it is missing Whenitcomestohowdataisstoredindatabases,fewskills 19 }}, mentionthatinprivacypolicies.Forthe89skillsthatstoredata Listing2:Anexampleskillthatrequeststheemailanduser collectionslotvalue,91%ofthemlackaprivacypolicyandonly4 namebutdoesn’tfullyusetherequesteddataandlacksa skills(4%)mentionthedatawouldbestored.Forthe57skillsthat privacypolicy. askforpermissionsandstoredatainadatabase,only21%providea privacypolicyand10%allareuseful.Other6skillsprovidebroken Forthe197skillscontainingslotsforsensitivedatacollection orunrelatedwebsiteswhileoneskillevensaysthatit“willnot and133skillsaskingforatleastonepermission,weconducted retaindata”,whichisdeceptive. a taint analysis of these sensitive data sources. After manually Sincetheprivacypolicylinkisextractedfromtheskillmanifest checkingtheresults,SkillScannerachievesanaccuracyof95%for file,askilllacksaprivacypolicyifwecouldn’tfindit.Soforskills slotdataflowanalysisand89%forpermissiondataflowanalysis. missingaprivacypolicy,SkillScannerachieves100%accuracy.For Thefailureofdataflowanalysisoftenresultsfromoverlookedsinks skillsprovidinganincompleteprivacypolicy,wemanuallychecked thatSkillScannerdoesn’tconsider,suchasusingauser’snameto
theirprivacypolicycontent.Thereare3falsepositivecases(already makeanappointmentorusingtheirlocationtofindthenearest removed in Table 7) for data collection skills and SkillScanner restaurant.Forthe187skills(afterremovingfalsepositivesfrom achievesanaccuracyof93%.Therecallfordetectingproblematic 197skills)thatcontainslotsforsensitivedatacollection,wefound privacypolicyis86%andit’spartiallybecauseofthefalsenegatives that8skillsdon’tusethedata,121skillsusethecollecteddatain indetectingdatacollectionrequests(detailsinSection6.2)orfailure theiroutputs/responsesand91skillssavedatatodatabases(one toreadthemanifestfiletoobtaintheprivacypolicylink. skillmaycontainmultipledatausages).Forthe118skillsasking forpermissiondata,42skillsdon’tuseatleastonepermissiondata, 6.4.2 Over-privilegeddatarequests. Therequestedpermissionin- which are over-privilege skills. 57 skills store data in databases formationcanbeextractedfromtheskillmanifestfile.Todetect and30skillsusedataforoutputsorresponses.Listing2showsan over-privilegedpermissiondatarequests,wecheckedwhetherthese examplethatdoesn’tfullyusethedataitasksfor.Theskillrequests permissionsareusedintheback-endcodeornot.Thereare42skillsSkillScanner:DetectingPolicy-ViolatingVoiceApplicationsThroughStaticAnalysisattheDevelopmentPhase CCS’23,November26–30,2023,Copenhagen,Denmark thatrequestforpermissionsbutdon’tusethem.Therearealso18 findandenablethatskill,sothatitcanbecorrectlyinvokedfrom skillsthatgetpermissiondatawithoutrequestingforpermissions. multiplecandidateskills.However,wefoundsuchaviolationis verycommoninbothourdatasetandAmazonAlexaskillsstore. 6.4.3 InconsistentdatacollectiondisclosuretoAlexaplatform. Ama- So,wedecidednottoincludeitinourresults.Wefoundthat202 zonasksdeveloperswhethertheirskillscollectuserdatabefore invocationnamesusedby990skills(40%)inourdataset,and16,020 submissionanddeveloperscanselectyesornobythemselves.The publishedskillshavethisviolationinAlexa’sskillsstore. answerswillbestoredintheskillmanifestfileifadeveloperselects it.Thereare126skillswithdatacollectioninourdatasetmakinga 6.5.3 Category-specificviolations. Forpolicyviolationsrelatedto selection,inwhich99skillsclaimnotusingpersonalinfowhileonly differentcategories,wefoundoneskillasksforuserdatainthe 27developerscorrectlyselecttheyusepersonalinfo.However,for Kidscategory.13skillsintheHealthcategorylackadisclaimerin the27skills,4skillsdon’tprovideaprivacypolicyand16provide theirdescription.Forexample,oneskillnamed“UCSDHealth”in anincompleteone. the“Health”categoryprovidesadescription“AskUCSDHealth tosaveyourspotatthenearestclinic”anditdoesn’tcontaina 6.5 ContentGuidelineViolationDetection disclaimerwhichisrequiredbyAlexa. 6.5.1 Contentsafetyviolations. Aftercheckingtoxiccontentwith 6.6 CodeInconsistencyDetection the Perspective tool in skill outputs, we found one skill named “Wiredlifehacks”thatoutputs“Anythingelseyouwouldliketo 6.6.1 Askillwithadatacollectionrequestbutwithoutaslotfor know,motherf*ckers?”and“youf*ckedup!youf*ckedup!you processing user reply. When a skill asks for user data, it should defineanintentandslotforcapturingandprocessingsuchdata, f*ckedup!”.Suchoutputscanbeharmfultousers.Nextwechecked suchas“NameIntent”withslot“name”.However,wefoundthat whetheranyskillasksforapositiverating.Oneskillnamed“Word 124skillsaskforuserdatabutdon’thavecorrespondingintentand Cyclopedia”says“Ifyoulikethisskill,pleasegivethisskillfivestar slot.Forexample,theskill“awsFact”tellsuser“Youcanintroduce andwriteyourvaluablefeedback”inthedescription. yourselfbytellingmeyourname”,butitonlycontainsfourAmazon Skillsmaygetfunctionalcontentfromawebsiteorprovideusers built-inintents.Forsuchaskillwithoutproperintentandslot,if withanaudio/imageasoutput.Afterextractingandprocessing usersprovidedatafollowingtheinstruction,theskillwillinvoke mediafilesseparately,wegot1,656websites,1,439mp3filesand awrongintentortriggerbuilt-in“FallbackIntent”withthereply 932imagesfromskillcode.Forwebsites,wecheckedwhetherthey “Sorry,Idon’tknowthat.Pleasetryagain”.Suchanincorrectreply aremaliciouswebsitesandwhetherthecontentofawebsitehas willnodoubtinfluenceuserexperience.Wefoundthatover50 toxiccontent.Wedidn’tfindanysuchcaseinourdataset.Forthe skillsusethesamesentence(“Youcanintroduceyourselfbytelling extractedaudioandimagefiles,wedidn’tfindanyviolationeither. meyourname”)inthe“HelpIntent”butdon’thaveanintentorslot Detectingcontentsafetyfromthedynamicandchangingexternal forprocessingthedata. websites(whereskillsobtaindata)canbechallenging.However, uponrevisitingandcomparingthecontentofallwebsitesusedin 6.6.2 Askillwithadatacollectionslotbutwithoutdatacollection skillsinasix-monthperiod,wefoundthatthemajorityofthese requeststotriggertheslot. Wefound147skillsthatdefineaslotfor websites(85%)didn’tchangetheircontent. datacollection,buttheydon’thaveanydatacollectionrequests. For example, a skill named “theStudyBar” has an intent named
6.5.2 Non-complianceofinvocationnames. Wefound281skills “myNameIs”.Theslotdefinedinthisintentis“firstName”andthe withdifferenttypesofinvocationnameviolations.Amongthese sampleutterancesare“{firstName}”and“mynameis{firstName}”. skills,53%ofskillshaveaninvocationnamewithonlyoneword, When we checked the skill back-end code, there didn’t exist a suchas“greeter”,“eva”or“jokes”;4%ofthemhavetwo-wordinvo- requestaskingfortheusername.Thismakesthedatacollection cationnameswithanarticleorpreposition,like“thecar”or“the activityhiddenwhentheskillissubmittedduringthecertification helper”;35%ofskillsusedaninvocationnamethatcontainsAlexa- phase.However,developerscanupdatethecodeaftertheskillis relatedwords,suchas“playradio”,andtheother8%skillsdon’tuse published,thentheskillcancollectuserdataagain. invocationnameinlowercaselike“AlTranslate”or“Ryan’snote”. ExampleinvocationnameswithviolationsareprovidedinTable5. 6.6.3 Datacollectionslotandintentwithoutsampleutterances. We SkillScannersuccessfullydetectedinvocationnameviolationswith found24skillswith95sensitivedatacollectionslotsand40skills anaccuracyof96%andrecallof99%.SkillScannerincorrectlyre- with87intents(notfordatacollection)don’thaveanycorrespond- portedskillswithinvocationnamesthatareone-wordbrandnames ingsampleutterances.Thiscanbeabugorerrorbecausetheinter- asviolations.Thefalsenegativesaremainlyduetothefailureto actionmodeldoesn’tknowhowtomatchauser’sreplywiththe readtheskillfilewitherrors. intentandslot.Whenauserprovidesareply,nointentorawrong AmazonAlexaalsorequiresthat“theinvocationnameshouldbe intentwillbeinvokedandtheslotvaluewillneverbecaptured. distinctivetoensureuserscanenableyourskill”.Suchviolationsof Suchcasesaresimilartomissinganintentbecausealthoughthe theinvocationnamecannegativelyinfluenceuserexperienceorbe intentisdefined,itwillnotbetriggered. usedforsquattingattack[40].Forexample,oneskill’sinvocation Forcodeinconsistencydetection,wealsomanuallycheckedall nameis“weatherapp”.Whenuserstrytoinvokethe“weather” ourresults.Forskillswithdatacollectionrequestsbutwithouta skillwith“Alexa,opentheweatherapp”,thisskillwillbeinvoked slot,theaccuracyis91%.Forskillswithdatacollectionslotsbut instead of the “weather” skill. For users who want to invoke a withoutdatacollectionrequests,theaccuracyis84%becausesome skillwithcommonlyusedinvocationname,he/shefirstneedsto datacollectionoutputscannotbecorrectlyrecognizedduetotheCCS’23,November26–30,2023,Copenhagen,Denmark SongLiao,LongCheng,HaipengCai,LinkeGuo,andHongxinHu complexityofNLP.Fordetectingdatacollectionslotsandintents indifferentstandardsregardingpolicycompliance.Foratemplate withoutsampleutterances,SkillScannerachieves100%accuracy. named“zerotohero”,whichincludes10differentversionsofskill Since the inconsistency detection is reliant on the results from templates,onlythetenthskillprovidesaprivacypolicywhilethe sensitivedatacollectionactivitydetection,thereasonsforfalse othersdonot,althoughalltenskillsaskforthesameuserdata.In negativesarethesamewithSection6.2andtherecallratesforthe total,wefound42officialskillswithviolationsandtheyinfluenced threepartsare82%,92%,93%,respectively. 71otherskillswith81policyviolations. 6.7 ImpactofCodeDuplication 6.8 PerformanceandResponsibleDisclosure 6.7.1 ImpactofcodesnippetCopy&Paste. Althoughwehavere- 6.8.1 Performance. Table8summarizestheperformanceofeach movedtheduplicateskillsbeforetheanalysis,westillfoundmany componentinSkillScannerandTable9summarizesourdetection differentskillswiththesamepolicyviolations.Forexample,67 results.Foreachcomponent,wemanuallycheckedallthedetected skillsoutput“Youcanintroduceyourselfbytellingmeyourname” resultstogettheaccuracyof SkillScanner.Inaddition,wealso intheirHelpIntent,whichisdesignedtoprovidehelpfulinforma- randomlyselected100skillsfromourdatasetandmanuallylabeled tionforusers.However,theydon’tprovideaprivacypolicywhile them to evaluate the overall performance of SkillScanner. The collectinguserdata.SincethedefaultsentenceinHelpIntentis“You resultsshowthatSkillScannerachievesoverall90%precisionand cansayhellotome!HowcanIhelp?”,itispossiblethattheseskills 87%recall. didn’tuseAlexa’sdefaulttemplatebutcopiedthecodesnippet fromotherplacesfortheirfunctions. Tofindsuchcasesinskillviolations,weusedthecopydetect[9] Analysis SkillScannerComponent Accuracy Recall tooltodetectthesimilaritybetweenthesourcecodefileswhere Data Sensitivedatacollectionrequestdetection 98% 84% Collection Sensitivedatacollectionslotdetection 99.7% 93% skillviolationsappeared.Then,wegroupedsimilarskillswiththe Activity Sensitivedatacollectionpermissiondetection 100% 91% sameviolationsandcheckedwhetherthereexistsanytemplate DataFlow Slotdataflowanalysis 95% - skill,especiallyskilltutorialsortemplates,whichwerepotentially Analysis Permissiondataflowanalysis 89% - copiedbyotherskillsinthesamegroup.Asaresult,wefoundthere Privacy Missingaprivacypolicy 100% 86% Violation Havinganincompleteprivacypolicy 93% 86% exist453violations(38%)becauseofcopyingcodefromotherskills.
Content Invocationnameviolation 96% 99% Suchcasesweremoreseriousintwotypesofviolations:“sensitive Datacollectionrequestbutmissingaslot 91% 82% datacollectioninoutputbutmissingaprivacypolicy”(53%ofthe Code Datacollectionslotbutmissingarequest 84% 92% skillswithsuchissueareduetothecodesnippetcopy&paste)and Inconsistency Datacollectionslotbutmissinganutterance 100% 93% Intentbutmissinganutterance 100% 93% “sensitivedatacollectioninoutputbutwithoutaslotforprocessing OverallperformanceofSkillScanner 90% 87% it”(67%oftheskillsthatviolatethispolicyareduetothecode Table8:PerformanceofdifferentcomponentsinSkillScan- snippetcopy&paste).Asforthesourceofcopiedskills,wefound ner. themostcommonlycopiedskillswerefromtheGitHubaccounts “dabblelab”and“alexa-samples”,whichleadtoviolationsinanother 87and65skills,respectively.Notethat“alexa-samples”seemsto 6.8.2 Latency. Foreachskill,SkillScannerneedsonly75sonav- beanAlexaofficialaccountanditcontains109skilltutorials.More erageforscanningallsourcefiles,performingthepolicyviolation detailsaboutAlexa’sofficialaccountswillbediscussedinthenext detection,andreportinganalysisresults.Figure5showstheCu- section. mulative Distribution Fraction (CDF) of SkillScanner’s latency performance.Over85%ofskillsneedlessthantwominutesfora 6.7.2 CodesnippetCopy&PasteinpotentialAlexa’sofficialskills. comprehensivedetection.ComparedtoSkillDetective[59],which Aftertracingthesourcesofcopiedskills,wefoundthattheGitHub usesadynamictestingmethodthatneedstowaitforskillresponses accounts“alexa-samples”,“alexa”,“alexa-dev-hub”,“alexa-labs” andtakesaround10minutestotestoneskill,SkillScannerhasa and“aws-samples”(whicharepotentialAmazonAlexa’saccounts significantlylowertimecost.Themajorityoftimeconsumedby onGitHub),publishedskillsthatwereoftencopiedbyotherskills SkillScannerisontoxiccontentdetection(sendingoutputstoPer- andtheyleadtoviolationsintensofskills.AlthoughtheseAlexa- spective)anddownloadingaudio,images,andwebsites. providedskillsaimtoprovidetutorialsfordeveloperstolearnhow todevelopskills,afewissuesintheseskillscouldleadtoviolations 1 inotherskillsandprovidebadexamplesforthird-partydevelopers. Tounderstandwhethertheseofficialskills’codehasviolations,we 0.8 checkedalltheirskillsandfoundtheseaccountsdon’tprovidea 0.6 goodexampleforothers.Theaccount“alexa-samples”published 125 skills, in which 20 skills are supposed to provide a privacy 0.4 policybutonly1skillprovidestheprivacypolicy.Thisaccount influenced62otherskills.What’smore,insteadofleavingablank 0.2 for the privacy policy link, as shown in Listing 2, some official 0 0 1 2 3 4 5 skillsdon’tevenhavethe“privacyAndCompliance”attributeinthe manifestfile,whichmakesdevelopersnotnoticethereshouldbe aprivacypolicylink.Anotherissueisthatthetutorialskillsare )FDC( noitcarF evitalumuC Processing Time (minute) Figure5:LatencyperformanceofSkillScanner.SkillScanner:DetectingPolicy-ViolatingVoiceApplicationsThroughStaticAnalysisattheDevelopmentPhase CCS’23,November26–30,2023,Copenhagen,Denmark 6.8.3 Responsibledisclosure. Weperformedaresponsibledisclo- tousersintheback-endcode.Accountlinking[15]canbeanother sureprocesswithseveralsteps.1)Wereportedtheidentifiedissues wayofuserdataleakageandwewillconsiderthatinourfuture inAlexa’ssamplecodetotheAmazonAlexateam.2)Wenotified research.Second,thecurrentdesignofSkillScannerdoesnotcover 83developerswhoprovidedemailaddressesontheirGitHubpages allAlexa’sprivacyrequirementsandcontentguidelines.Inaddition, aboutthepotentialpolicyviolationsintheircode.3)Wecreated thepolicyviolationdetectionperformancecanbefurtherimproved new issues on the GitHub repositories to notify the developers byusingadvancedmachinelearningtechniques.However,itisnon- whohadmultipleproblematicskillsbutdidn’tprovideanemail trivialtocollecthigh-qualitydatasetsformodeltraining.Third, address.Itisworthmentioningthatwereceivedfeedbackfrom SkillScanneronlyfocusesontheAmazonAlexaplatform,whichis 6developers(amongthe83developerswereachedoutto).They themostpopularVPAplatform.WeplantoextendSkillScanner expressedappreciationforourworkandacknowledgedthatsuch toanalyzeGoogleActionsasourfuturework.Forth,mostofthe astaticanalysistoolishelpfulinfacilitatingtheirdevelopment skillsinourdatasetwerenotpublishedintheskillsstoreandthey ofpolicy-compliantskills.Theyalsomentionedthereasonsfor needtopassacertificationprocessbeforebeingpublished.Asa thepolicyviolations,suchasbeingunawareofpolicies,usinga result,theskillsinourdatasetmayhavemoreissuesthantheskills templatethatdoesnothaveaprivacypolicyordevelopingskillsfor inthestore.However,wedon’tclaimtheidentifiedissuesinour learningpurposes.Threerespondentsmentionedthattheywere resultsarerepresentativeofactualskillsinproduction.Rather,the impressedbyourSkillScannertool.Tworespondentsplannedto mainpurposeofourevaluationinSection6istodemonstratethe fixtheissuesandonehadalreadyfixedtheissue.Tworespondents efficiencyof SkillScannerinfindingpolicyviolationsgivenskill
explainedthattheskillswerejustdevelopedforlearningpurposes. code.SinceSkillScannerisdesignedforfacilitatingthird-partyde- velopersindevelopingpolicy-compliantskills,itisimportantto 7 DISCUSSION evaluatethedeveloperacceptancerateof SkillScanner.Wealso plantoconductuserstudiestogetfeedbackfromskilldevelopers 7.1 PotentialImpactofProblematicSkills abouttheusabilityof SkillScanner. Problematic skills could have a negative impact on users, VPA platforms,anddevelopers.1)End-usersareconcernedaboutpolicy violations in skills. We collected a user review dataset from the 8 RELATEDWORK skills store and we did find negative reviews talking about the There has been an increasing number of studies on VPA secu- policy violations in skills that impacted their experience. 2,383 rityandprivacy[33,37,57,58].Themajorityofresearchefforts userscomplainedaboutthedatacollectionand107usersmentioned havebeenundertakentoidentifyvariousacoustic-basedattacks thatskillsrepeatedlyaskedforapositiveratinginreviews.2)VPA (e.g.,out-of-bandsignalattacksandadversarialexampleattacks) platformsareconcernedaboutpolicyviolationsinskills.TheAmazon againsttheAutomaticSpeechRecognition(ASR)modulesinVPA Alexaplatformenforcesacertificationprocesstoensurethateach systems [25, 29, 30, 58] and the corresponding defenses in mit- skillmeetstherequiredcontentandprivacyrequirementsbeforeit igatingtheseattacks[26,31,47,61].Ashundredsofthousands becomespubliclyavailable.Accordingtorecentworks[35,36,59], of skills have been published in VPA platforms, the security of afterresearchersreportedthepolicy-violatingskillsintheskills skillshasattractedattentionfromtheresearchcommunity.Since storetotheAmazonAlexateam,VPAplatformswouldremove attacksthatexploitskills’vulnerabilitiescanbelaunchedremotely, theseskillsfromthestore.Outof93skillsinourdatasetpublished theycouldpotentiallybemorepowerfulthanacoustic-basedat- intheAlexaskillsstore,SkillScannerdetected14problematicskills tacks[38,56,63].Inthissection,webrieflydiscussrecentresearch thateithermissedaprivacypolicyorhadaninvalidinvocation onidentifyingproblematic(e.g.,privacy-invasive)skillsinAmazon name.Interestingly,thepolicyviolationsintheseskillswerefixedin AlexaandGoogleAssistantplatforms. theirpublishedversions.ItispossibletheyfailedtopassAmazon’s Kumaretal.[40]presentedtheskillsquattingattackandthey certificationprocesswithpolicyviolationsandthenthedevelopers found381pairsofskillswerelikelytobesquatted.Lentzschet hadtoresolvetheissuesforpublishingthem.3)Developersare al.[41]discovered262skillswithpermissionsprovideanincom- concernedaboutpolicyviolationsinskills.Sincepolicy-violating pleteprivacypolicy.In[36],theauthorsreported675skillsthat skills may be rejected at the certification phase and developers requestpermissiondatahaveprivacyissuesaboutprivacypoli- needtofixissuesinskillsandwaitseveraldaystogetfeedback cies.SkillVet[35]presentedamachinelearningbasedmethodfor fromthecertificationteam,policyviolationsinskillsinevitably checkingdatapracticesandprivacyissues.SkillExplorer[39]tested slowdowntheskilldevelopmentandpublishing. 28,904Amazonskillsandidentified1,141skillsrequestingusers toprovidepersonalinformationwithoutdisclosingintheirpri- 7.2 Limitations vacy policies. VerHealth [53] analyzed 813 health-related skills DespitethelimitednumberofskillpackagesfromGitHub,SkillScan- ontheAmazonAlexaplatform.Vitas[42]interactedwith41,581 nerisabletoidentify1,328violationsin786policy-noncompliance skillsandfoundthat51%ofskillssufferedfromproblemssuch skills.4policy-violatingskillshavebeenpublishedontheskills asunexpectedexit/startandprivacyviolation.SkillDetective[59] storewithoutfixingthem(2skillshaveanincompleteprivacypol- identified6,079policy-violatingskillsinthecurrentskillsstores icyand2skillsintheHealthcategorylackadisclaimer).However, byevaluatingskills’conformitytomorethan50differentpolicy SkillScannerhasseverallimitations.First,forthedataflowanal- requirements.Manyresearcheffortshavebeenundertakentostudy ysis,moretypesoftaintsourcesandsinkscanbeconsidered.For userconcerns(humanfactors)aboutthesecurityandprivacyof example,askillmaycollectusers’emailaddressesandsendemails VPAdevices[24,27,34,64].Malkinetal.[45]conductedauserCCS’23,November26–30,2023,Copenhagen,Denmark SongLiao,LongCheng,HaipengCai,LinkeGuo,andHongxinHu studyabouthowpeoplereacttotheruntimepermission.Sharmaet [2] AlexaPermissions. https://developer.amazon.com/en-US/docs/alexa/custom- al.[51]focusedonGoogleAssistantandshowedthatmostpartici- skills/configure-permissions-for-customer-information-in-your-skill.html. [3] AlexaPolicyforChild-Directedskill.https://developer.amazon.com/fr-FR/docs/ pantshavesuperficialknowledgeaboutthedatacollectedbythe alexa/custom-skills/policy-testing-for-an-alexa-skill.html#cert-child-directed.
platform.Liuetal.[44]studied214participantsaboutwhetherthey [4] AlexaPolicyforHealthskill.https://developer.amazon.com/fr-FR/docs/alexa/ considerprivacypermissionswhileinstallingapps.Sabiretal.[49] custom-skills/policy-testing-for-an-alexa-skill.html#3-health. [5] AlexaSkillCountsSurpass80KinUS.https://voicebot.ai/2021/01/14/alexa-skill- didauserstudytoanalyzeusers’awarenessofthird-partyskills. counts-surpass-80k-in-us-spain-adds-the-most-skills-new-skill-introduction- However,noneofthemconducteduserstudytounderstandskill rate-continues-to-fall-across-countries. developers’perceptionsandpracticesregardingpolicycompliance [6] Alexa Skills Policy Testing. https://developer.amazon.com/fr/docs/custom- skills/policy-testing-for-an-alexa-skill.html. inskilldevelopment. [7] AlexaSkillsPrivacyRequirements.https://developer.amazon.com/fr/docs/custom- Distinctionfromexistingworks.SkillScannerdistinctsitself skills/security-testing-for-an-alexa-skill.html#25-privacy-requirements. [8] CodeQL.https://codeql.github.com/. fromexistingpolicyviolationdetectionworks(includingSkillEx- [9] copydetect. https://github.com/blingenf/copydetect. plorer[39],VerHealth[53],Vitas[42]andSkillDetective[59])in [10] First Alexa Third-Party Skills Now Available for Amazon Echo. threeways.First,differentfromrecentskilltestingtoolsthatuti- https://developer.amazon.com/es/blogs/alexa/post/TxC2VHKFEIZ9SG/first- alexa-third-party-skills-now-available-for-amazon-echo. lizedynamicanalysisandcanonlydetectviolationsexercisedby [11] Perspective.https://www.perspectiveapi.com/home. run-timeinputs,SkillScanneristhefirst-of-its-kindstaticanal- [12] pytesseract0.3.7.https://pypi.org/project/pytesseract/. ysistoolanditdetectsmorepossibleviolations/inconsistencies [13] Qualitrics. https://www.qualtrics.com/. [14] Sensitivedatatypes:Personalinformation.https://docs.aws.amazon.com/macie/ in the code. Second, SkillScanner identifies policy violations of latest/user/managed-data-identifiers.html#managed-data-identifiers-pii. skillsdevelopedbyinexperiencedbenigndevelopersinthedevel- [15] Skill Account Linking Schemas. https://developer.amazon.com/en- US/docs/alexa/smapi/account-linking-schemas.html. opmentphasewhileexistingworksdetectpolicyviolationsinthe [16] Skill Interaction Model Schemas. https://developer.amazon.com/en- post-deploymentphase.Third,SkillScannerdetectsmoretypes US/docs/alexa/smapi/interaction-model-schema.html. ofviolationsexistingintheskillcode(suchasdatastorage,over- [17] Skill Manifest Schema. https://developer.amazon.com/en- US/docs/alexa/smapi/skill-manifest.html. privilegeddata,andcodeinconsistency)thatexistingworkscan’t [18] SkillPackageFormat.https://developer.amazon.com/en-US/docs/alexa/hosted- find.Forexample,comparedtoSkillDetective,SkillScannerdetects skills/alexa-hosted-skills-git-import.html. 12newtypesofviolations.Evenforthe8typesofviolationsthat [19] Skill Slot Type Reference. https://developer.amazon.com/en- US/docs/alexa/custom-skills/slot-type-reference.html. SkillDetective can find, such as skill output and content safety, [20] Skill Standard Built-in Intents. https://developer.amazon.com/en- SkillScannercanfindmorepotentialoutputsthatmightnotappear US/docs/alexa/custom-skills/standard-built-in-intents.html. [21] spaCy.https://spacy.io. indynamictesting.Asaresult,934/1328(70%)ofviolationsarenew [22] SpeechRecognition3.8.1.https://pypi.org/project/SpeechRecognition/. andcan’tbefoundbySkillDetective. [23] VirusTotal.https://www.virustotal.com/gui/home/search. [24] NouraAbdi,KopoMRamokapane,andJoseMSuch.Morethansmartspeakers: 9 CONCLUSION Securityandprivacyperceptionsofsmarthomepersonalassistants.InSOUPS@ USENIXSecuritySymposium,2019. Inthiswork,wefirstconductedauserstudytounderstandthegap [25] HadiAbdullah,KevinWarren,VincentBindschaedler,NicolasPapernot,and PatrickTraynor. Sok:Thefaultsinourasrs:Anoverviewofattacksagainst betweenVPA’spolicyrequirementsandskilldevelopers’practices. automaticspeechrecognitionandspeakeridentificationsystems.In2021IEEE Informedbyouruserstudyresults,wedesignedandimplemented SymposiumonSecurityandPrivacy(SP),pages730–747,2021. thefirststaticanalysistoolnamedSkillScanner,whichhelpsdevel- [26] ShimaaAhmed,IliaShumailov,NicolasPapernot,andKassemFawaz.Towards morerobustkeywordspottingforvoiceassistants. In31stUSENIXSecurity opersautomaticallyidentifypotentialpolicyviolationsinskillsat Symposium(USENIXSecurity22),2022. thedevelopmentphase.Toevaluatetheperformanceof SkillScan- [27] TawfiqAmmari,JofishKaye,JaniceY.Tsai,andFrankBentley.Music,search, andiot:Howpeople(really)usevoiceassistants.ACMTransactionsonComputer- ner,wecollected2,451opensourceskillsfromGitHub,andcon- HumanInteraction(TOCHI),26(3):1–28,2019.