text
stringlengths
64
2.99M
tionalConferenceonSoftwareEngineering. IEEE,2009,pp.364–374. Intelligence,vol.37,no.4,pp.5131–5140,Jun.2023. [43] A. Nilizadeh, G. T. Leavens, X.-B. D. Le, C. S. Pa˘sa˘reanu, and D. R. [62] M. Jin, S. Shahriar, M. Tufano, X. Shi, S. Lu, N. Sundaresan, and Cok, “Exploring true test overfitting in dynamic automated program A.Svyatkovskiy,“Inferfix:End-to-endprogramrepairwithllms,”arXiv repair using formal methods,” in 2021 14th IEEE Conference on preprintarXiv:2303.07263,2023. SoftwareTesting,VerificationandValidation(ICST),2021,pp.229–240. [63] Z. Fan, X. Gao, M. Mirchev, A. Roychoudhury, and S. H. Tan, [44] M. Fu, C. Tantithamthavorn, T. Le, V. Nguyen, and D. Phung, “Automated repair of programs from large language models,” in 2023 “Vulrepair: A t5-based automated software vulnerability repair,” in IEEE/ACM 45th International Conference on Software Engineering Proceedings of the 30th ACM Joint European Software Engineering (ICSE),2023,pp.1469–1481. ConferenceandSymposiumontheFoundationsofSoftwareEngineering, [64] F. Ribeiro, “Large language models for automated program repair,” ser. ESEC/FSE 2022. New York, NY, USA: Association for in Companion Proceedings of the 2023 ACM SIGPLAN International Computing Machinery, 2022, p. 935–947. [Online]. Available: https: Conference on Systems, Programming, Languages, and Applications: //doi.org/10.1145/3540250.3549098 Software for Humanity, ser. SPLASH 2023. New York, NY, USA: [45] J. Berdine, A. Cox, S. Ishtiaq, and C. M. Wintersteiger, “Diagnosing AssociationforComputingMachinery,2023,p.7–9. abstraction failure for separation logic–based analyses,” in Computer [65] N. Jiang, K. Liu, T. Lutellier, and L. Tan, “Impact of code language Aided Verification, P. Madhusudan and S. A. Seshia, Eds. Berlin, models on automated program repair,” in Proceedings of the 45th Heidelberg:SpringerBerlinHeidelberg,2012,pp.155–173. InternationalConferenceonSoftwareEngineering,ser.ICSE’23. IEEE [46] Y. Wang, W. Wang, S. Joty, and S. C. Hoi, “CodeT5: Identifier-aware Press,2023,p.1430–1442. unifiedpre-trainedencoder-decodermodelsforcodeunderstandingand [66] C.S.XiaandL.Zhang,“Lesstraining,morerepairingplease:Revisiting generation,” in Proceedings of the 2021 Conference on Empirical automated program repair via zero-shot learning,” in Proceedings of Methods in Natural Language Processing. Online and Punta Cana, the 30th ACM Joint European Software Engineering Conference Dominican Republic: Association for Computational Linguistics, Nov. and Symposium on the Foundations of Software Engineering, 2021,pp.8696–8708. ser. ESEC/FSE 2022. New York, NY, USA: Association for [47] J.Fan,Y.Li,S.Wang,andT.N.Nguyen,“Ac/c++codevulnerability Computing Machinery, 2022, p. 959–971. [Online]. Available: https: dataset with code changes and cve summaries,” in Proceedings of the //doi.org/10.1145/3540250.3549101 17th International Conference on Mining Software Repositories, ser. [67] E. Mashhadi and H. Hemmati, “Applying codebert for automated pro- MSR’20. NewYork,NY,USA:AssociationforComputingMachinery, gramrepairofjavasimplebugs,”in2021IEEE/ACM18thInternational 2020,p.508–512. ConferenceonMiningSoftwareRepositories(MSR),2021,pp.505–509. [48] G.Bhandari,A.Naseer,andL.Moonen,“Cvefixes:Automatedcollec- [68] C.Lemieux,J.P.Inala,S.K.Lahiri,andS.Sen,“Codamosa:Escaping tion of vulnerabilities and their fixes from open-source software,” in coverage plateaus in test generation with pre-trained large language Proceedingsofthe17thInternationalConferenceonPredictiveModels models,” in Proceedings of the 45th International Conference on andDataAnalyticsinSoftwareEngineering,ser.PROMISE2021. New Software Engineering, ser. ICSE ’23. IEEE Press, 2023, p. 919–931. York,NY,USA:AssociationforComputingMachinery,2021,p.30–39. [Online].Available:https://doi.org/10.1109/ICSE48619.2023.00085 [49] Z.Zeng,H.Tan,H.Zhang,J.Li,Y.Zhang,andL.Zhang,“Anextensive [69] Y. Deng, C. S. Xia, C. Yang, S. D. Zhang, S. Yang, and L. Zhang, studyonpre-trainedmodelsforprogramunderstandingandgeneration,” “Large language models are edge-case fuzzers: Testing deep learning inProceedingsofthe31stACMSIGSOFTinternationalsymposiumon librariesviafuzzgpt,”arXivpreprintarXiv:2304.02014,2023. softwaretestingandanalysis,2022,pp.39–51. [70] Y. Deng, C. S. Xia, H. Peng, C. Yang, and L. Zhang, “Fuzzing [50] OpenAI. (2023) Chatgpt. Accessed on Date. [Online]. Available: deep-learning libraries via large language models,” arXiv preprint https://openai.com/blog/chatgpt arXiv:2212.14834,2022. [51] Q. Guo and et al., “Exploring the potential of chatgpt in automated [71] M.Tufano,D.Drain,A.Svyatkovskiy,andN.Sundaresan,“Generating code refinement: An empirical study,” arXiv, 2023, accessed 19 Oct. accurate assert statements for unit test cases using pretrained 2023.[Online].Available:https://arxiv.org/abs/2309.08221 transformers,” in Proceedings of the 3rd ACM/IEEE InternationalConferenceonAutomationofSoftwareTest,ser.AST’22. NewYork, NY, USA: Association for Computing Machinery, 2022, p. 54–64.
[Online].Available:https://doi.org/10.1145/3524481.3527220 [72] P.Nie,R.Banerjee,J.J.Li,R.J.Mooney,andM.Gligoric,“Learning deep semantics for test completion,” arXiv preprint arXiv:2302.10166, 2023. [73] E. Dinella, G. Ryan, T. Mytkowicz, and S. K. Lahiri, “Toga: A neural method for test oracle generation,” in Proceedings of the 44th International Conference on Software Engineering, ser. ICSE ’22. New York, NY, USA: Association for Computing Machinery, 2022, p. 2130–2141. [Online]. Available: https://doi.org/10.1145/3510003. 3510141 [74] M.Taeb,A.Swearngin,E.School,R.Cheng,Y.Jiang,andJ.Nichols, “Axnav: Replaying accessibility tests from natural language,” arXiv preprintarXiv:2310.02424,2023.
2310.20067 Vignat: VULNERABILITY IDENTIFICATION BY LEARNING CODE SEMANTICS VIA GRAPH ATTENTION NETWORKS ShuoLiu GailKaiser ColumbiaUniversity ColumbiaUniversity NewYork,NY NewYork,NY sl4921@columbia.edu kaiser@cs.columbia.edu ABSTRACT Vulnerability identification is crucial to protect software systems from attacks for cyber-security. However,hugeprojectshavemorethanmillionsoflinesofcode,andthecomplexdependencies makeithardtocarryouttraditionalstaticanddynamicmethods. Furthermore,thesemanticstructure of various types of vulnerabilities differs greatly and may occur simultaneously, making general rule-basedmethodsdifficulttoextend. Inthispaper, weproposeVignat, anovelattention-based frameworkforidentifyingvulnerabilitiesbylearninggraph-levelsemanticrepresentationsofcode. Werepresentcodeswithcodepropertygraphs(CPGs)infinegrainandusegraphattentionnetworks (GATs)forvulnerabilitydetection. TheresultsshowthatVignatisabletoachieve57.38%accuracy onreliabledatasetsderivedfrompopularClibraries. Furthermore,theinterpretabilityofourGATs providesvaluableinsightsintovulnerabilitypatterns. Keywords Vunerabilityidentification·Graphattentionnetworks·Codepropertygraph 1 Introduction Vulnerability identification is crucial in ensuring the security, integrity, and resilience of systems, networks, and applications. Byproactivelyidentifyingandaddressingvulnerabilities,organizationscanreducetheriskofsecurity breaches, disruption of services and malware propagation. Vulnerability identification has promising applications infieldssuchassoftwaredevelopment, whereitcanbeusedtoimprovecodequalityandreducethelikelihoodof introducingvulnerabilitiesinthefirstplace,andinsecurityresearch,whereitcanbeusedtodevelopnewdefensive technologiesandtechniques. Someworksidentifyvulnerabilitiesbyexecutingtestingprogramsandanalyzingruntimebehaviors,suchas[1],[2], and[3]. However,duetothelimitedcodecoverage,executiondependencies,andsubstantialoverheadassociatedwith dynamic approaches, researchers startto focus on moreefficient static vulnerabilitydetection methods. Thereare severalchallengesthatmakestaticvulnerabilitydetectiondifficult. Sincelarge-scaleprojectsoftenconsistofmillions oflinesandexhibitcomplexcallingrelationshipswithinandbetweenprojects, itishardtoeffectivelyfeatureand analyzethecode. Moreover,real-worldvulnerabilitiesaresparse,whichcancausebiaswhenconfrontedwithnewand unseenpatterns. Somerule-basedstaticanalyzershavebeendevelopedtolocatevulnerabilitiesusingdefinedpatternsorsignatures thatmatchknownvulnerabilitiesorprogrammingerrors,[4],[5],and[6]. Whilethesemethodsareusefulindetecting commontypesofvulnerabilities,theyheavilyrelyonpredefinedrulesandstruggletohandlecomplexprojects,making them unsatisfactory in real-world scenarios. Besides, some transformer-based models are also applied to this task becauseoftheirsequenceprocessingabilityandinterpretability, [7], [8], [9], and[10]. Nonetheless, thesestudies aredifficulttoobtainacomprehensiveunderstandingofprogramsemanticssolely. Because,unlikenaturallanguage sequences, source codes are more structured, and the vulnerabilities can often be subtle flaws that need thorough examinationfromvarioussemanticperspectives. Therefore,itseemsamorereasonablewaytofindthepatternsof vulnerabilitiesbyanalyzingthecomplexrelationshipsinvariouscoderepresentations. 3202 tcO 03 ]RC.sc[ 1v76002.0132:viXraShuoLiu,GailKaiser . . . CPGs Graph Embeddings . . . Transformer . . . . . . GAT Inference Figure1: AnoverviewofVignatframework. In this paper, we address these challenges by constructing graph embeddings of code functions and analyzing the logicalrelationshipsbetweentokenstopredictcodevulnerability. Usingtheself-attentionmechanism[11],ourmodels exhibitexcellentexplainability,enablingustoinfervulnerabilitypatternsinsteadofrelyingonexperiencetodetect vulnerabilities. Ourmaincontributionsare: • WeobtainacomprehensiverepresentationofcodefunctionsbyembeddingthemintoCPGstocapturecode syntacticstructure,controlflow,anddatadependencies. • WeproposeaGATframework,Vignat,forcapturingandmodelingcomplexrelationshipsamongnodesin CPGs,wherehigherattentionedgescanrevealpatternsofvulnerabilities. • WeevaluatetheeffectivenessofVignatonmanuallylabeleddatasetscollectedfrom4large-scaleCprojects. Vignatachievesbetterresultsonthedatasetwithvariousattention-basedmodels,upto10%accuracyand5% F-scoreimprovementoverbaselinemethods. The rest of this paper is organized as follows. Section 2 presents Vignat framework. Section 3 demonstrates the performanceandillustratestheinterpretabilityofourmodel. Section4concludesthispaper. 2 Vignat Framework ThissectionprovidesanoverviewofourVignatframework,asshowninFig. 1. WithintheVignatframework,wefirst tokenizethesourcecodefunctionsandconstructCPGs,acompositerepresentationofcodesemantics. Followingthis, weemployvariousembeddingmethodstoobtainnodeembeddings. Inconjunctionwithgraphconnectivity,thegraphs areinputtedintoaGATforgraph-levelpredictions. Byextractingattentionweightsfromtheoutputoftheattention layer,wecanidentifysalientedges,revealingpatternsassociatedwithvulnerabilities. 2.1 GraphEmbeddingofCode
Asidefromthesemanticsconveyedbycodetokensandthelogicpresentinnaturalcodesequencing(NCS),highly structuredgraphrepresentationsofcodeobscureasignificantamountoflogicalinformation. Theabstractsyntaxtree (AST)isatree-likerepresentationthatencodeshowstatementsandexpressionsarenestedtoproduceaprogram. Inner nodesdenoteoperators,leafnodesdenoteoperands,andedgesspecifycontainerandcontentrelationships. Thecontrol flowgraph(CFG)describestheorderinwhichcodestatementsareexecuted. Italsoshowstheconditionsthatmustbe metforaparticularexecutionpath. InaCFG,nodesrepresentstatementsorpredicates,andedgesdenotethepathsthe programcantraverse. Theprogramdependencegraph(PDG)representsdependenciesamongstatementsandpredicates inaprogram. Datadependenceedgesshowhowanode’soutcomeimpactsavariableinanothernode,whilecontrol dependenceedgesrevealtheeffectofpredicatesonvariablevalues. IntegratingelementsofASTs,CFGs,PDGs,aCPG providesaunifiedrepresentationforprogramanalysisandenablesustosimultaneouslyreasonaboutallperspectivesof codeproperties. ACPGforavulnerablecodesnippetisshowninFig. 2. Inthispaper,wemakeuseofanopen-sourcecodeanalysisplatformJoerntoparsesourcecodefunctionsandconstruct CPGsinbatches. InaCPG,nodesrepresentprogramconstructs,includingvariables,methods,controlstructure,etc. Eachnodecontainsseveraltokensandhassomeattributesaccordingtoitstype,suchasthenameoflocalvariables, thesignatureofthemethod,andthetypeofcontrolstructure. Nodesareconnectedbydirectededgestorepresent relationshipsintheprogramstructure. InVignat,Consideringthatanodemayhavedifferentnumbersoftokensinit, weobtainitsembeddingbyaveragingitstokenembeddings. Tomakethegraphembeddingtractableforgraphneural networks(GNNs),wesimplifytheCPGsbydisregardingtheheterogeneityofvariousrelationshipsandeliminating duplicateedges. OnlytheconnectivityinformationispassedtothesubsequentGATmodel. 2ShuoLiu,GailKaiser ENTRY DECL IF CALL EXIT 0 void func() { 1 int x = source (); 2 if (isEven(x)) { int = CALL CALL AST Edge 3 proceed(10 / x); CFGEdge 4 } 5 } x CALL x isEven / proceed source 10 x Figure2: AvulnerablecodesnippetanditscorrespondingCPG. 2.2 GAT GraphNeuralNetworks(GNNs)haveemergedasafamilyofmodelsforlearningrepresentationsofgraph-structured data. AgraphG = (V,E)consistsofasetofnodesV andedgesE,whereeachedge(i,j)representsaconnection between nodes i and j. The key idea behind GNNs is to iteratively update node representations by aggregating informationfromneighboringnodes. LetXbetheinitialnodefeaturematrix, whereeachrowcorrespondstothe featurevectorofanode. Mathematically,thepropagationofaGNNcanbeexpressedas: (cid:16) (cid:16) (cid:17)(cid:17) h(l) =σ A·ReLU W(l−1)·h(l−1) (1) whereh(l)isthenoderepresentationmatrixatlayerl,W(l)isthelearnableweightmatrix,Aistheadjacencymatrix capturinggraphconnectivity,andσdenotesanactivationfunction. Thislayer-wiseaggregationprocessallowsGNNs tocapturecomplexrelationshipsingraph-structureddataandlearnexpressivenoderepresentations. GATwasintroducedby[12]asanovelapproachforgraphrepresentationlearning,whichcannaturallygeneralize convolutionstoirregulargraphstructures. GATincorporatesself-attentionmechanisms,whichenablesthemodelto weightheimportanceofneighboringnodesforthetargetone,thuscapturingthelocalcodestructureoftheCPG. TheGATmodelconsistsofaseriesofgraphattentionlayers. Eachlayercomputesanewsetofnodeembeddingsbased ontheinputnodefeaturesandthelearnedattentioncoefficients. Theattentioncoefficientsbetweennodesiandj in layerlcanbecomputedasfollows: (cid:16) (cid:104) (cid:105)(cid:17) e(l) =LeakyReLU a(l)T W(l)h(l−1) ∥W(l)h(l−1) , (2) ij i j where∥denotestheconcatenationoperation,anda(l)isalearnablevector. Toensurethatthecoefficientsarenormalizedacrosstheneighboringnodes,weapplythesoftmaxfunction: (cid:16) (cid:17) exp(e(l)) α(l) =softmax e(l) = ij , (3) ij j ij (cid:80) exp(e(l)) k∈N(i) ik whereN(i)denotesthesetofneighboringnodesofnodei. Thenewnodeembeddingsforlayerlarecomputedasa weightedsumoftheinputfeaturesoftheneighboringnodes:   h(l) =σ (cid:88) α(l)W(l)h(l−1) , (4) i ij j j∈N(i) whereσisanactivationfunction,suchastherectifiedlinearunit(ReLU). OneofthekeyadvantagesofGATisitsexplainability. Incontrasttographconvolutionalnetworks(GCNs)[13],where theaggregationofneighboringnodefeaturesisoftenperformeduniformly,makingitdifficulttodiscerntheinfluence ofspecificnodes,GATprovidesaninterpretablemeasureoftheimportanceofneighboringnodesforatargetnode. By investigatingtheattentioncoefficientse(l),weareabletogaininsightsintotherationaleofourmodel,whichisuseful ij foridentifyinginfluentialpathsandaddressingpotentialbiases. 3ShuoLiu,GailKaiser 3 Experiments WeevaluateVignatwiththefollowingresearchquestions. 1. HowdoesVignatcomparetothetransformersthatarebasedontheNCS? 2. HowdoesVignatperformondifferentkindsofcoderepresentations? 3. HowdodifferentkindsofwordembeddingmethodsaffecttheperformanceofVignat?
4. Howdoesattention-mechanismpoweredVignatcomparetoGCNs? 5. Howtoinferpatternsofcodevulnerabilitiesthroughattentioncoefficients? 3.1 Setup WeusetheDevigndatasettoevaluateourmodels[14]. Comparedtodatasetswithlabelsgeneratedbystaticanalyzers and artificial ones, it is more reliable and maintains a sparsity of vulnerabilities and is more reliable by manually labelingvulnerabilitiesinlarge-scale,real-worldCprojects. Specifically,wefocusedontwoprojects,FFmpegand QEMU,andselectedmedium-lengthfunctionscontaininglessthan1200tokensassamplesformodeltrainingandtesting. AstheDFGedgesarelabeledwiththevariablesinvolved,ittremendouslycomplicatesembeddedgraphs. Therefore, weonlyextractedASTsandCFGsandcombinedthemintocompositegraphasCPGsforourdatasetusingJoern. We calculatetheaverageembeddingoftokenswithinanodetoobtainitsembeddingandstandardizeitsembeddingsizeto 768usingpretrainedmodels,BERT,DistilBERT,RoBERTa,andCodeBERT.IfaCPGhasmorethan225nodes,we cutthefirst225ones;otherwise,weusepaddingzerostokeepthesizeofinputcodefeaturessame. WeconfiguretheGATmodelsasfollows. Modelsareconfiguredwiththeinputhiddendimensionof225andlearning rate0.0001. WeimplementourmodelsusingPyTorch2.0.0,CUDA11.8,andtrainthem100epochswithbatchsize8 using16GBTeslaV100-SXM2GPU.Ittakesus0.0358secondstogenerateeachCPGinaverage. Andwetakes116 minutestotrainForVignatwithRobertaembeddingonFFmpeg,wespend116minutestotrain;Ittakesus127minutes totrainVignatwithRobertaembeddingonQEMU. 3.2 ResultAnalysis ToevaluatetheperformanceofVignat,wecompareitwithsomebaselinemethods,includingstate-of-the-arttransformers based on the NCS and GCNs based on graph representation of codes. To avoid the resulting gap caused by data heterogeneity,weprovidethesebaselineswiththesametrainingsetandtestsetaftershuffleandsplit. Wemeasurethe performanceofdifferentmethodsfrom4metrics,accuracy,precision,recall,andF1score. Thecomparisonresultsare showninTable. 1. AsshowninTable. 1,onFFmpegdataset,Vignathasthebestperformanceoverallmodels. Comparedwithtransformer baselines,itimproves4.05%accuracyoverBERTandRoBERTa, and5.71%overCodeBERT.WefindthatCPGs providethemostcomprehensiverepresentationamongthegraphs,astheaccuracyimproves6.56%overASTs,and 4.92% over CFGs. Besides, experiments also show that different embedding methods have an impact on model performance. RoBERTaperformswellonalldatasets. ForVignatusingGCNs,thoughitdoesnotshowasubstantial enhancementcomparedtoalternativeembeddingtechniquesonaccuracy,ithasabetteroverallperformancewithhigher precisionandrecall. 3.3 PatternExplanation Fig. 3illustrates5CPGedgeswiththelargestvaluesofattentioncoefficientse(l) forthesourcecodeinFig. 2. In ij this code example predicted to be vulnerable, the type and operator of a variable are highlighted with red arrows. Theseedgesrevealthevulnerabilitiesthatcouldoccurinthiscodesnippet. Specifically, theintegermayoverflow whendeclaringthevariableandthedivisorcanbezero,andthesevulnerabilitieswillaffectthefollowingproceeding functions. 4 Conclusion ThispaperpresentsVignat,aninnovativeattention-basedframeworkforvulnerabilityidentification.ByleveragingCPGs tocomprehensivelycapturethesyntacticstructure,controlflow,anddatadependenciesofcodefunctions,andemploying GATstomodelcomplexrelationshipsamongnodes,Vignateffectivelypredictsandreasonsthevulnerabilitiesinsource codes. Ourmethoddemonstratesremarkableperformance,achievingupto57.38%accuracyonreliabledatasets,and 4ShuoLiu,GailKaiser FFmpeg Class Embedding Representation Acc Prec Rec F1 BERT 53.33% 55.77% 90.63% 68.89% DistilBERT 56.67% 54.45% 96.88% 69.05% Transformer NCS RoBERTa 53.33% 53.85% 87.50% 66.67% CodeBERT 51.67% 52.83% 87.50% 65.88% AST 54.09% 53.70% 90.63% 67.44% Word2Vec CFG 52.46% 52.46% 100.00% 68.82% CPG 55.74% 56.10% 71.88% 63.10% AST 50.82% 52.00% 81.25% 63.41% BERT CFG 52.46% 52.46% 100.00% 68.82% CPG 57.38% 56.82% 78.13% 65.79% AST 50.82% 51.92% 84.37% 64.29% GCN DistilBERT CFG 54.10% 53.57% 93.75% 68.18% CPG 50.82% 51.92% 84.38% 64.29% AST 50.82% 51.92% 84.37% 64.29% RoBERTa CFG 52.46% 52.46% 100.00% 68.82% CPG 57.38% 56.52% 81.25% 66.67% AST 52.46% 52.46% 56.25% 55.38% CodeBERT CFG 52.46% 52.46% 100.00% 68.82% CPG 57.38% 57.50% 71.88% 63.89% AST 55.74% 56.10% 71.86% 63.01% Word2Vec CFG 52.46% 52.46% 100.00% 68.82% CPG 63.93% 63.16% 75.00% 68.58% GAT AST 59.02% 57.14% 87.50% 69.14% BERT CFG 52.46% 52.46% 100.00% 68.82% CPG 60.66% 59.09% 81.25% 68.42% Table 1: Comparison of different methods. Acc, Prec, Rec, F1 represent accuracy, precision, recall, and F1 score respectively. ENTRY DECL IF CALL EXIT int = CALL CALL AST Edge CFGEdge x CALL x isEven / proceed RemarkableEdge source 10 x Figure3: 5edgeswithhighestattentioninFig. 2.
atleast4%accuracyimprovementovertransformersand1%-5%overotherGNNs. Furthermore,byemployingthe interpretabilityofGATsinVignat,weareabletogetvaluableinsightsintovulnerabilitypatterns,pavingthewayfor futureadvancesinvulnerabilityidentificationandpreventionincybersecurity. 5 Acknowledgements Kaiser is supported in part by DARPA/NIWC-Pacific N66001-21-C-4018 and in part by NSF CNS–2247370 and CCF-2313055. 5ShuoLiu,GailKaiser References [1] MichaelSutton,AdamGreene,andPedramAmini.Fuzzing:BruteForceVulnerabilityDiscovery.Addison-Wesley Professional,2007. [2] CristianCadar,DanielDunbar,andDawsonREngler.Klee:Unassistedandautomaticgenerationofhigh-coverage testsforcomplexsystemsprograms. InProceedingsofthe8thUSENIXConferenceonOperatingSystemsDesign andImplementation,pages209–224.USENIXAssociation,2008. [3] NickStephens,JohnGrosen,ChristopherSalls,AndrewDutcher,RuoyuWang,JacopoCorbetta,YanShoshi- taishvili,ChristopherKruegel,andGiovanniVigna. Driller: Augmentingfuzzingthroughselectivesymbolic execution. InProceedingsoftheNetworkandDistributedSystemSecuritySymposium(NDSS),2016. [4] JuliaLawallandGillesMuller. Coccinelle: AProgramMatchingandTransformationToolforSystemsCode. In Proceedingsofthe20thConferenceonUSENIXSecuritySymposium.USENIXAssociation,2008. [5] ClangTeam. Clangstaticanalyzer. https://clang-analyzer.llvm.org/,2019. Accessed: 2023-05-04. [6] DavidA.Wheeler. Flawfinder. https://dwheeler.com/flawfinder/,2021. Accessed: 2023-05-04. [7] JacobDevlin,Ming-WeiChang,KentonLee,andKristinaToutanova. BERT:pre-trainingofdeepbidirectional transformersforlanguageunderstanding. CoRR,abs/1810.04805,2018. [8] VictorSanh,LysandreDebut,JulienChaumond,andThomasWolf. Distilbert,adistilledversionofbert: smaller, faster,cheaperandlighter. ArXiv,abs/1910.01108,2019. [9] AlexisConneau,KartikayKhandelwal,NamanGoyal,VishravChaudhary,GuillaumeWenzek,FranciscoGuzmán, EdouardGrave,MyleOtt,LukeZettlemoyer,andVeselinStoyanov. Unsupervisedcross-lingualrepresentation learningatscale. CoRR,abs/1911.02116,2019. [10] ZhangyinFeng,DayaGuo,DuyuTang,NanDuan,XiaochengFeng,MingGong,LinjunShou,BingQin,Ting Liu,DaxinJiang,andMingZhou. Codebert: Apre-trainedmodelforprogrammingandnaturallanguages,2020. [11] AshishVaswani,NoamShazeer,NikiParmar,JakobUszkoreit,LlionJones,AidanNGomez,LukaszKaiser,and IlliaPolosukhin. Attentionisallyouneed. InAdvancesinneuralinformationprocessingsystems,volume30, pages5998–6008,2017. [12] PetarVelicˇkovic´,GuillemCucurull,ArantxaCasanova,AdrianaRomero,PietroLiò,andYoshuaBengio. Graph attentionnetworks. InInternationalConferenceonLearningRepresentations,2018. [13] ThomasNKipfandMaxWelling. Semi-supervisedclassificationwithgraphconvolutionalnetworks. arXiv preprintarXiv:1609.02907,2016. [14] YaqinZhou,ShangqingLiu,JingkaiSiow,XiaoningDu,andYangLiu. Devign: Effectivevulnerabilityidentifica- tionbylearningcomprehensiveprogramsemanticsviagraphneuralnetworks. InAdvancesinNeuralInformation ProcessingSystems,pages10197–10207,2019. 6
2311.00270 SurveyonQualityAssuranceofSmartContracts ZHIYUANWEI, BeijingInstituteofTechnology,China JINGSUN, UniversityofAuckland,NewZealand ZIJIANZHANG∗,XIANHAOZHANG,XIAOXUANYANG,andLIEHUANGZHU, BeijingInstituteof Technology,China Asblockchaintechnologycontinuestoadvance,thesecuredeploymentofsmartcontractshasbecomeincreasinglyprevalent, underscoringthecriticalneedforrobustsecuritymeasures.Thissurgeinusagehasledtoariseinsecuritybreaches,oftenresulting insubstantialfinanciallossesforusers.Thispaperpresentsacomprehensivesurveyofsmartcontractqualityassurance,from understandingvulnerabilitiestoevaluatingtheeffectivenessofdetectiontools.Ourworkisnotableforitsinnovativeclassification offortysmartcontractvulnerabilities,mappingthemtoestablishedattackpatterns.Wefurtherexamineninedefensemechanisms, assessingtheirefficacyinmitigatingsmartcontractattacks.Furthermore,wedevelopalabeleddatasetasabenchmarkencompassing tencommonvulnerabilitytypes,whichservesasacriticalresourceforfutureresearch.Wealsoconductcomprehensiveexperiments toevaluatefourteenvulnerabilitydetectiontools,providingacomparativeanalysisthathighlightstheirstrengthsandlimitations.In summary,thissurveysynthesizesstate-of-the-artknowledgeinsmartcontractsecurity,offeringpracticalrecommendationstoguide futureresearchandfosterthedevelopmentofrobustsecuritypracticesinthefield. CCSConcepts:•Generalandreference→Surveysandoverviews;•Securityandprivacy→Distributedsystemssecurity. AdditionalKeyWordsandPhrases:smartcontract,security,vulnerabilities,attacks,defenses ACMReferenceFormat: ZhiyuanWei,JingSun,ZijianZhang,XianhaoZhang,XiaoxuanYang,andLiehuangZhu.2023.SurveyonQualityAssuranceofSmart Contracts.ACMComput.Surv.37,4,Article47(June2023),43pages.https://doi.org/XXXXXXX.XXXXXXX 1 INTRODUCTION Blockchaintechnologyhasgainedprominenceinacademiaandindustryasasecureandprivatesolutionfordiverse applications[63,139].Asadistributedledger,blockchaintechnologyisreplicatedandsharedamonganetworkofpeer- to-peernodes.Iteliminatestheneedforintermediaries,therebyprovidingdecentralization,transparency,immutability, security,andreliability.Bymaintainingachronologicallygrowingandimmutabledatarecord,blockchainsystemshave becomeidealforamultitudeofdomains,rangingfrombusinesstohealthcare.Intherealmofbusiness,blockchain significantlyreducesoperationalcosts[26].Healthcareapplicationsofblockchainrangefromsecuringcloud-based cyber-physicalsystems[53,89]toenhancingprivacyinmonitoringsystems[105].Itsroleinmanaginghealthcare challenges,particularlyduringtheCOVID-19pandemic,furtherexemplifiesitsbroadutilityandadaptability[82]. Authors’addresses:ZhiyuanWei,BeijingInstituteofTechnology,Beijing,China,weizhiyuan@bit.edu.cn;JingSun,UniversityofAuckland,Auckland,New Zealand,jing.sun@auckland.ac.nz;ZijianZhang,zhangzijian@bit.edu.cn;XianhaoZhang,1120191274@bit.edu.cn;XiaoxuanYang,yangxiaoxuan979@ gmail.com;LiehuangZhu,liehuangz@bit.edu.cn,BeijingInstituteofTechnology,Beijing,China. Permissiontomakedigitalorhardcopiesofallorpartofthisworkforpersonalorclassroomuseisgrantedwithoutfeeprovidedthatcopiesarenot madeordistributedforprofitorcommercialadvantageandthatcopiesbearthisnoticeandthefullcitationonthefirstpage.Copyrightsforcomponents ofthisworkownedbyothersthanACMmustbehonored.Abstractingwithcreditispermitted.Tocopyotherwise,orrepublish,topostonserversorto redistributetolists,requirespriorspecificpermissionand/orafee.Requestpermissionsfrompermissions@acm.org. ©2023AssociationforComputingMachinery. ManuscriptsubmittedtoACM ManuscriptsubmittedtoACM 1 4202 guA 11 ]RC.sc[ 3v07200.1132:viXra2 Weietal. Additionally,blockchain’sintegrationwithAIinareaslikeresourceallocationfordrone-terrestrialnetworksindicates itsexpandingscopeinvariousinnovativefields[96]. Smart contracts have emerged as a pivotal component of blockchain technology. Originally conceptualized in theearly1990s,theygainedsignificanttractionwiththeadventofblockchainplatformslikeEthereum.Theseself- executingcontracts,implementedthroughlinesofcode[13,80],havetransformedtraditionalcontractenforcementby automatingitandembeddingitwithintheblockchainnetwork.Theyensuretransparencyandimmutabilityofcontract rules,enforcedbyblockchainnetworkparticipants.Theyallowdecentralizedapplications(DApps)tobebuiltonthe blockchainnetworks,facilitatingapplicationsindiversedomainssuchasfinancialservices[143],healthcare[102,105], theInternetofThings[54],crowdfunding[111],andsupplychainmanagement[116,121]. Typically,smartcontractsareassociatedwiththenativecryptocurrencyoftheblockchain,whichisusedtocom- pensatenetworkparticipantsforcontractexecution.Thisincentivizationmaintainstheblockchain’ssecurityand decentralization.Thenoveltyandpotentialimpactofsmartcontractsinrevolutionizingbusinesstransactionshave attractedsignificantresearchinterest.However,despitegrowingattention,numerousopenresearchquestionsremain tobeaddressedinthisemergingfield. Comparedtotraditionalprograms,smartcontractspossessuniquecharacteristicsthatmakethemmorevulnerable tosoftwareattacks.Firstly,smartcontractsareimmutable,meaningthatoncedeployedontheblockchain,theircode cannotbemodified.Whileimmutabilityensurestrustandtransparency,italsomeansthatanyvulnerabilitiesorerrors
inthecodecannotbeeasilyrectifiedwithoutdeployinganewcontractversion.Secondly,smartcontractsfrequently managevaluabledigitalassets,suchascryptocurrenciesordigitaltokens.Thisconcentrationofvalueassetsattracts malicioususerswhoactivelyseektoexploitvulnerabilitiesinthecontractcode.Thirdly,publicblockchains,suchas Ethereum,arepermissionless,allowinguniversalaccessandinteractionwithdeployedsmartcontracts.Thisopen naturelowersentrybarrierforpotentialattackers,makingiteasierforthemtoidentifyandexploitvulnerabilitiesin smartcontracts.Moreover,thecommonpracticeofpublishingcontractcodeonplatformssuchasEtherscanfurther exposesittopotentialsecuritythreats. The exploitation of these vulnerabilities has led to significant financial losses and broader implications in the blockchainworld.Forinstance,the2016DAOattack,whereattackersdivertedover3.6millionether,resultedinaloss ofaround70millionUSDandtriggeredasubstantialdropinether’svalue[147].TheParityMultisigWalletincidentled toalossofabout30millionUSD[94].In2020,theKuCoinhackresultedinthelossofover280millionUSDworth ofcryptocurrencies.Thisincidentunderscoredtherisksinherentinsmartcontractsandcatalyzeddiscussionson enhancingsecuritymeasuresandpotentialregulatoryframeworks.Furthermore,theFebruary2020reentrancyattack onthebZxDeFiplatform,resultinginlossesofnearly350,000USD,highlightedvulnerabilitiesincomplexDeFismart contractsandemphasizedthenecessityforrigoroustestingandsecurityaudits[37].Beyondtheimmediatefinancial losses,theseincidentshaveraisedconcernsaboutthesecurityandreliabilityofsmartcontracts,impactingusertrust andinvestorconfidence. Duetothenoveltyandpotentialimpactofsmartcontracts,therearesomenotablesurveysinvolvingvulnerable smartcontractsfromvariousperspectives.Table1underscoresthealignmentanddistinctionsbetweenourworkand previoussurveys.Ourstudyspecificallyaddressesvariousaspectsofsmartcontractsecurity,includingvulnerability types,attacks,defensemethods,detectiontechnologies,andrelevantdatasets. Atzerietal.[13]pioneeredthesurveyofsmartcontractsecurity,categorizing12vulnerabilitiesintothreedomains: Solidity,EVMbytecode,andblockchain.Thisclassificationframeworkhasbeenwidelyadoptedinsubsequentresearch andhaspracticalapplicationsinidentifyingandmitigatingsecurityrisksinreal-worldsmartcontractdeployments. ManuscriptsubmittedtoACMSurveyonQualityAssuranceofSmartContracts 3 Table1. ComparisonofSurveysonSmartContractSecurity Research Venue Vulnerability Attacks Defense Tools Datasets Types Methods Atzeietal.[13] ETAPS’17 12 9 3 – – Zhengetal.[145] FGCSJournal’20 ✓ – – – – Chenetal.[30] ACMComput.Surv. 40 29 8 – – Angeloetal.[11] DAPPCON’19 – – – 27 – Durieuxetal.[41] ICSE’20 10 – – 35 ✓ Tolmachetal.[128] ACMComput.Surv. – – 5 34 – Ivanovetal.[64] ACMComput.Surv. 37 – 8 38 – Chuetal.[36] ISTJournal’23 12 – 2 20 ✓ Heetal.[57] IEEEIoTJournal’23 8 – 6 6 – Zhangetal.[144] ICSE’23 14 – 6 5 ✓ Chaliasosetal.[28] ICSE’24 14 – 6 5 ✓ Thiswork – 40 9 9 101 ✓ Zhengetal.[145]conductedacomparativeanalysisofvarioussmartcontractplatformsanddevelopedataxonomyof applications.Theirstudyevaluatedthefeaturesandcharacteristicsofdiverseplatforms,emphasizingthepotential impact of vulnerabilities on sectors such as finance and healthcare, where transaction integrity and security are paramount. Chenetal.[30]expandedthescopebeyondvulnerabilityanalysistoencompassdefensemechanismsforblockchain security.Theirresearchexaminedvariousdefensetechniquesandstrategiesemployedtobolstersmartcontractsecurity. AngeloandSalzer[11]conductedacomprehensivesurveyonvulnerabilitydetectiontoolstailoredforEthereumsmart contracts.Theirstudyencompassedtoolsfrombothacademiaandindustry,offeringinsightsintothearrayofavailable vulnerabilityidentificationtools.Durieuxetal.[41]performedacomprehensiveevaluationofninesmartcontract detectiontools.Theyassessedthesetoolsusingalabeleddatasetandnumerousreal-worldsmartcontracts,yieldinga thoroughanalysisoftheirefficacy. Tolmachetal.[128]concentratedontheformalverificationofsmartcontractsacrossdiverseapplications.Their researchexploredtheapplicationofformalverificationtechniquesforensuringthecorrectnessandsecurityofsmart contracts.Ivanovetal.[64]focusedonsecuritythreatmitigation,developingaconcisevulnerabilitymapencompassing 37knownvulnerabilities.Thismapsynthesizedthevulnerability-addressingcapabilitiesof38distinctclassesofthreat mitigationsolutions.Chuetal.[36]examinedvulnerabilitydatasources,detectionmethods,andrepairtechniques. Throughautomatedvulnerabilityinjectionintocontracts,theyconstructedanobjectivevulnerabilitydataset,enhancing theanalysisofexistingsecuritymethods’performance. Heetal.[57]evaluatedperformancedetectionmethodsandtheirassociatedtools.Theyprimarilytestedsixdetection tools,analyzingthemfrommultipleperspectives:detectionaccuracy,executiontime,andSolidityversioncompatibility. Zhangetal.[144]conductedasystematicinvestigationof462defectsreportedinCodeArenaauditsand54exploits, assessingthedetectioncapabilitiesofexistingtools.Theirsurveyindicatesthatexistingtoolscandetectmachine-
auditablevulnerabilities,withmorethan80%ofexploitablebugsfallingintothiscategory.Somevulnerabilitiesaretoo complexorsubtleandrequiretheexpertiseofmultiplehumanauditors.Chaliasosetal.[28]comparedfivestate-of- the-art(SOTA)automatedsecuritytoolswith49developersandauditorsfromleadingDeFiprotocols.Theirfindings revealedthatthetoolscouldhavepreventedonly8%oftheattacksintheirdataset. Althoughprevioussurveysoffervaluableinsightsintospecificaspectsofsmartcontractsecurity,theyoftenlacka comprehensiveanalysisencompassingallperspectivesofvulnerablesmartcontracts.Itiscrucialtodevelopathorough understandingofvulnerabilities,attacks,defenses,andtoolevaluationtogainaholisticviewofthechallengesand ManuscriptsubmittedtoACM4 Weietal. potentialsolutionsrelatedtosmartcontractsecurity.Ourpaperaimstobridgethisgapbyincorporatingmultiple perspectives,offeringamorecomprehensiveanalysis.Throughasystematicexaminationofvulnerabilities,attacks, defenses,andtools,westrivetoprovideacomprehensiveunderstandingofthechallengesposedbyvulnerablesmart contractsandexploreviablesolutions. Theprimaryobjectiveofourpaperistocontributetotheexistingbodyofresearchonsmartcontractsecurityby providingacomprehensiveandup-to-dateanalysis.Toachievethisobjective,wepresentthefollowingkeycontributions: • NovelVulnerabilityClassification:Weproposeanovelvulnerabilityclassificationthatenhancestheunderstanding oftheunderlyingcausesofvulnerabilitiesinsmartcontracts.Thisclassificationfacilitatesmoreeffectivecategorization andanalysisofvulnerabilitiesbyresearchers,establishingarobustfoundationforsecuritymeasuresandenhanced vulnerabilitymanagement. • In-depthAnalysisofReal-WorldAttacks:Wepresentacomprehensiveanalysisofreal-worldattacksonsmart contractstogainvaluableinsightsintothemethodsemployedbyattackersandthepotentialconsequencesofthese attacks.Byexamininganddissectingtheseattacks,weaimtoprovideaclearerunderstandingoftheexploitationof vulnerabilitiesinpractice,empoweringdevelopersandauditorstoproactivelyaddresspotentialthreats. • ExplorationofDefenseMechanisms:Weconductarigorousassessmentofexistingdefensemechanismsemployed tomitigatesmartcontractattacks.Throughthisexploration,weidentifyareasforimprovementandpotentialnew approachestoenhancethesecurityofsmartcontracts.Byanalyzingthestrengthsandweaknessesofcurrentdefense mechanisms,weaimtocontributetothedevelopmentofmorerobustandeffectivesecuritypractices. • EvaluationofVulnerability-DetectingTools:Weconductacomprehensiveevaluationof14representative vulnerability-detectingtoolsusedinsmartcontractanalysis.Thisevaluationencompassestheaccuracy,performance, andeffectivenessofeachtool.Byprovidinginsightsintothestrengthsandweaknessesofthesetools,weassist researchersandpractitionersinselectingthemostsuitabletoolsforidentifyingvulnerabilitiesinsmartcontracts. • BenchmarkDatasetforToolEvaluation:Weintroduceacomprehensivebenchmarkdataset,encompassing100 vulnerablesmartcontractcasesand10securecontractinstances,tofacilitaterigorousevaluationofvulnerability detectiontools.Thismeticulouslycurateddatasetservesasastandardizedreferencepointforassessingtheefficacy ofvulnerabilitydetectiontools.Itenablesfairandobjectivecomparisons,allowingresearchersandpractitionersto assessthecapabilitiesofdifferenttoolsinaconsistentmanner. Throughthesekeycontributions,ourpaperaimstoserveasacomprehensiveresourceforresearchers,developers, andauditorsinthefieldofsmartcontractsecurity.Weaspiretoadvancesecuresmartcontractdevelopmentpractices andpromotethewidespreadadoptionofsecuresmartcontractsinreal-worldapplications. Therestofthispaperisconstructedasfollows.Section2providesabriefoverviewofsmartcontractplatformsand discussesthemethodologyemployedinthissurveytoensureacomprehensiveanalysis.Section3presentsadetailed analysisof40smartcontractvulnerabilities,examiningtheirrootcausesandsheddinglightontheunderlyingfactors thatcontributetotheirexistence.Section4explores8representativeattacksanddemonstrateshowthesevulnerabilities canbeexploited.Byillustratingreal-worldattackscenarios,weaimtoenhanceourunderstandingofthepotential consequencesofthesevulnerabilities.Section5examinesvariousdefensemethodologiesandrepairtechniquesavailable forsmartcontracts.Wediscusstheeffectivenessofthesedefensivemeasuresinmitigatingvulnerabilitiesandreducing thelikelihoodofsuccessfulattacks.Section6focusesontheevaluationof14commonlyusedtoolsfordetecting vulnerabilitiesinsmartcontracts.Weassesstheaccuracyandperformanceofthesetoolsbysubjectingthemtoa rigorousevaluationagainstacarefullycuratedbenchmarkingdataset.Section7concludesthepaperbysummarizing ManuscriptsubmittedtoACMSurveyonQualityAssuranceofSmartContracts 5 Table2. ComparativeAnalysisofSmartContractEcosystemsAcrossMajorBlockchainPlatforms Feature Bitcoin Ethereum HyperledgerFabric EOSIO Language Script Solidity Go,JavaScript,Java C++,Python,JavaScript Consensus PoW PoW/PoS PBFT/Raft DPoS+BFT Environment Script-based EVM Docker EOSVM Cryptocurrency Bitcoin(BTC) Ether(ETH) None EOS Scalability High High Low High Speed(TPS) 27 30 – 4,000 Confirmation >1000s <100s <10s <10s
Applications Send/receivemessages,verify Finance,supplychain,IoT, Enterpriselicensing,finance Finance,gambling signatures,transactions medical SecurityIssues Informalcryptographic Sourcecode/EVMerrors, Sourcecodeerrors,blockchain Sourcecodeerrors,transaction protocols,poorlydocumented blockchainattacks attacks verificationlacks features Solutions Securecryptographicprotocol Vulnerabilitydetectiontools, Vulnerabilitydetectiontools, Vulnerabilitydetectiontools, design contractmonitoring upgrades upgrades RelatedSurvey [15,17,18] [11,14,30,148] [110,136] [59] thekeyfindingsandcontributions.Wealsodiscussfuturedirectionsandpotentialresearchareastofurtheradvance thefieldofsmartcontractsecurity. 2 OVERVIEWOFSMARTCONTRACTSANDSURVEYMETHODOLOGY 2.1 SmartContracts ThefoundationalconceptofsmartcontractsisattributedtoNickSzabo,whopioneeredtheideain1996,predating thecreationofblockchaintechnology.Szaboenvisionedsmartcontractsascomputerprotocolsthatenablepartiesto engageindigitallyverifiableandself-executingagreements.Thesecontractsarewrittenincodeformatandfacilitate secureandefficienttransactions,reducingcostsandexpeditingexecutioncomparedtotraditionalcontracts[125]. However,thedevelopmentofsmartcontractsfacedchallengesintrustlesssystemsuntiltheemergenceofEthereumin 2015[71].Ethereum’sintroductionofablockchain-basedplatformspecificallydesignedforexecutingsmartcontracts revolutionizedthefield.Ethereum’ssuccesspavedthewayfortheproliferationofotherblockchainplatformsthatalso supportsmartcontractdevelopment.TheseplatformsincludeHyperledger[110],EOSIO[60],Tezos[21],NEO[91], andevenBitcoin,whichimplementeditsownversionofsmartcontracts[19]. Oursurveypresentsacomprehensivecomparativeanalysisoffourprominentblockchainplatforms:Bition,Ethereum, HyperledgerFabric,andEOS.Table2presentsthiscomparison,highlightingthesimilaritiesanddifferencesinterms ofsmartcontractimplementationandsecurityacrossthesediverseplatforms.Oursurveyspecificallytargetsthese platformsduetotheirwidespreadadoptionanddistinctapproachestohandlingsmartcontracts.Bitcoin,although notprimarilyknownforcomplexsmartcontracts,isincludedforitsfoundationalroleintheblockchainspaceandits recentdevelopmentsinenablingbasicsmartcontractfunctionalities.Ethereumisrenownedforitspioneeringrole insmartcontracttechnology,emphasizingdecentralizationanddeveloperaccessibility.HyperledgerFabricoffersa modularandcustomizablearchitecture,makingitmoresuitedtoenterpriseapplications.EOS,whilebearingsome similaritiestoEthereum,differentiatesitselfwithuniquegovernancemodelsandperformanceoptimizations. Thefollowingsectionsanalyzefourblockchainplatforms,highlightingtheiruniquecharacteristicsandapproaches tosmartcontracttechnology. • Bitcoin,thefirstblockchainsystem,primarilyfacilitatesecurepeer-to-peercurrencytransactionswithouttheneed forintermediaries.AlthoughnotoriginallydesignedtosupportextensivesmartcontractfunctionalitieslikeEthereum, ManuscriptsubmittedtoACM6 Weietal. Bitcoinofferslimitedcapabilitiesforexecutingcryptographicprotocols.Thesecapabilitiesincludebasicoperations suchassending/receivingmessages,verifyingsignatures,andsearchingtransactions.Bitcoinsmartcontracts,often calledscript-basedcontracts,areprimarilywritteninScript,asimple,stack-basedlanguagedesignedspecificallyfor transactions.ThesesmartcontractsonBitcoinareoftenreferredtoasscript-basedcontracts.AlthoughBitcoinsmart contractsarerelativelysimpleandhavelimitedfunctionality,theystillserveasavaluabletoolforexecutingbasic transactionalfunctionsinatrustlessanddecentralizedmanner.ResearchershavestudiedBitcoin’sscriptinglanguage constructionandcapabilities,withnotableexamplesincludingIvy,BALZAC,SIMPLICIT,andBITML[19].These studiesexploreddifferentaspectsofBitcoin’sscriptinglanguageanditsapplicationsincryptographicprotocols. • Ehtereumpioneeredthedeploymentofsmartcontractsonblockchainplatforms.Itenablesdeveloperstocreatetheir ownsmartcontractsusingSolidity,aTuring-completeprogramminglanguage.Thesesmartcontractsareexecutedon theEthereumVirtualMachine(EVM),whichprovidesaruntimeenvironmentfortheirexecution.Ethereum’ssmart contractshavesignificantlyexpandedblockchaintechnologyapplications,givingrisetoDecentralizedApplications (DApps)thatenabletrustless,decentralizedinteractions.Ethereumadoptsanaccount-centeredmodelforsmart contracts,contrastingwithBitcoin’sUnspentTransactionOutput(UTXO)model.Ethereum’ssuccesswithsmart contractshasestablisheditasaprominentsecond-generationblockchainplatform,oftenreferredtoasblockchain 2.0[30].SolidityisthemostwidelyusedprogramminglanguageforEthereumsmartcontractsonEthereum,is specificallydesignedtocompileintoEVMbytecode,thelow-levelrepresentationofsmartcontracts. • HyperledgerFabric(HF)isanenterprise-focusedblockchainplatformoperatingonapermissionednetwork.Unlike publicblockchains,HFallowsparticipationoftrustedorganizationsthroughamembershipserviceprovider[10]. Thisapproachsuitsscenariosinvolvingcollaborationamongmultiplebusinessorganizations,offeringenhanced privacy,scalability,andnetworkcontrol.HFsmartcontracts,calledchaincode,offerflexibilityinprogramming
languagesupport.DeveloperscanchoosefromvariousprogramminglanguagessuchasGolang,Java,andJavaScript toimplementtheirsmartcontracts,allowingthemtoleveragetheirexistingexpertiseandusethelanguagemost suitablefortheirapplication[71].PrivacyisanotherkeyfeatureofHFsmartcontracts.HyperledgerFabricsupports privatetransactions,enablingselectedparticipantstoengageinconfidentialtransactionswithoutrevealingsensitive informationtoallnetworkparticipants.HFsmartcontractsalsofeaturemodulardesign,facilitatingeasiermaintenance andupdates[75]. • EOSIOintroducesinnovativefeaturestothefieldofblockchaintechnology,e.g.,delegatedproofofstakeconsensus (DPOS)andupdatablesmartcontracts[60].DPOSelectsalimitednumberoftrustedblockproducerstovalidate transactionsandcreateblocks,resultinginhighthroughputandlowlatency.EOSIOsupportsmultipleprogramming languages,includingC++,Python,andJavaScript,offeringdeveloperstheflexibilitytochoosethelanguagethey aremostcomfortablewithandthatbestsuitstheirapplicationrequirements.Thismulti-languagesupportenables developerstoleveragetheirexistingskillsandexpertise,facilitatingsmartcontractcreationanddeployment.EOSIO smartcontractsexcelinhandlinghightransactionthroughput,withreportedspeedsofnearly4,000transactionsper second(TPS).EOSIOemphasizesdeveloper-friendliness,providingaweb-basedIDEthatsimplifiessmartcontract creationanddeployment.ThismakesitsuitableforDAppsrequiringfast,scalabletransactionprocessing,suchas socialmediaorgamingapplications. Astheuseofsmartcontractsbecomesmorewidespread,ensuringtheirsecurityhasbecomeparamount.Inrecent years,smartcontractshavesufferedfromanincreasingnumberofsecurityissues,resultinginsubstantialfinancial ManuscriptsubmittedtoACMSurveyonQualityAssuranceofSmartContracts 7 Fig.1. PublicationsandToolsOvertheYear lossesandreputationaldamage.Consequently,itiscrucialforbothacademicsandindustryprofessionalstofocuson smartcontractsecurityanddevelopeffectivetechniquesandtoolstosafeguardthesesystems. Figure1illustratesthetrendinsmartcontractsecuritypublicationsandtoolsfrom2016toJuly2024.Thedata showsamarkedincreaseinbothpublicationsandtooldevelopmentfrom2016to2018.Subsequently,thenumbers stabilizedbetween2018and2022.Asecondnotableincreaseoccurredin2023.Thisconsistentgrowthinbothacademic publicationsandtoolscanbeattributedtoadvancementsintechnologieslikeAI,theemergenceofnewvulnerabilities, andtherisingvalueofsmartcontracts.Thesefactorspresentnewchallengesandopportunitiesforsecurityresearch. Thegrowingimportanceofsmartcontractsinmanagingvaluableandsensitiveoperationsintensifiestheneedfor robustsecuritymeasures,furtherdrivingresearchandtooldevelopmentinthisfield. 2.2 SurveyMethodology Theobjectiveofoursurveyistoprovideacomprehensiveanalysisofdifferentapproachestodealingwithvulnerable smartcontracts.Toachievethis,wehaveformulatedasetofResearchQuestions(RQ)thatoutlinethescopeofour review: • RQ1:[Vulnerabilities]Whatarethecommonvulnerabilitiesthatexistinsmartcontracts,andhowcanweclassify thembasedontheircharacteristics? • RQ2:[Attacks]Howdoattackersexploitthesevulnerabilities,andwhataretheconsequencesoftheseattackson smartcontracts? • RQ3:[Defenses]Whatdefensemethodologiesareavailabletoprotectsmartcontractsagainstattacks,andhowdo thesedefensesmitigatetherisksassociatedwithvulnerabilities? • RQ4:[Effectiveness]Howeffectivearetheexistingvulnerabilityanalysistoolsinidentifyinganddetectingvulnera- bilitiesinSoliditysmartcontracts,andwhatarethestrengthsandlimitationsofthesetoolsintermsofaccuracy, performance,andcoverage? • RQ5:[ToolsandBenchmark]Howdoweselectrepresentativevulnerabilityanalysistoolsforevaluation,andhow canwecreateastandardizedbenchmarkofvulnerableandcorrectsmartcontractcasestoevaluatetheeffectiveness ofthesetools? ManuscriptsubmittedtoACM8 Weietal. Byaddressingtheseresearchquestions,oursurveyaimstoprovidecomprehensiveinsightsintothevulnerabilities, attacks,defensemechanisms,effectivenessofanalysistools,andthecreationofabenchmarkforsmartcontracts.To achievethis,weemployedarigorousmethodologytoensurecomprehensivecoverageandrelevanceoftheselected literature.Theprocessbeganwithdefiningclearinclusionandexclusioncriteriatoguideourliteratureselection.These criteriawerebasedontherelevancetosmartcontracts,publicationdate(paperspublishedbetween2015andJuly2024 wereconsidered),andthecredibilityofthepublicationsource. Oursearchstrategyinvolvedqueryingmajoracademicdatabasesandconferenceproceedings,usingkeywords relatedtosmartcontracts.WesearchedthroughdatabasessuchasIEEEXplore,ACMDigitalLibrary,GoogleScholar, SpringerLink,andScopus.Weemployedthefollowingkeywordsandsearchterms:“blockchain"AND“smartcontracts" AND“vulnerabilities"OR“security"OR“attacks".Thisinitialsearchyieldedasubstantialnumberofresults,astabulated inTable3. Table3. SummaryofPapersbyPublicationPlatforms Publisher PrimaryResults GoogleScholar 97,900 IEEEXploreDigitalLibrary 273,574 ACMDigitalLibrary 123,486 SpringerLink 936,311 Scopus 5,004 Thescreeningprocessgenerallyconsistsoftwostages:atitleandabstractscreeningstage,followedbyafull-text
screeningstage[100].Oncewehaveidentifiedtherelevantpapers,weassesstheirqualitybasedonpredefinedinclusion criteria.Thisgenerallyinvolvesassessingtherelevance,methodology,validity,reliability,credibility,clarity,andimpact. Theselectedpapersshouldaddressthetopicofsmartcontractsinameaningfulwayandprovidevaluableinsightsfor ourinvestigation.Themethodologyemployedshouldbesuitableforaddressingourresearchquestions,transparent, andcapableofbeingreplicated.Theresultsshouldbeaccurateandconsistent,andtheconclusionsdrawnshouldbe well-supportedbythedata.Theauthorsshouldpresenttheirideasclearlyandconcisely,withthepaperbeingfreeof errorsandinconsistencies.Furthermore,thepapershouldhavemadeasignificantcontributiontothefieldofsmart contracts. Afterevaluatingthesequalityattributes,wehavecollected308relatedpapersfrom72conferenceproceedings (includingCCS,IEEES&P,NDSS,USENIX,EuroS&P,FinancialCrypto,ASIACCS,ICSE,ASE)and11journals(including IEEETSE,IEEECOMST),aswellasrelevantpreprints.Thenextstepinvolvedextractingdatafromthesepapers, focusingontheirresearchquestions,methodologies,findings,andconclusions.Thisdataextractionwasconducted systematicallytogathercomprehensiveinsightsfromeachstudy.Theextracteddataandouranalysisaredocumented inanonlinerepository(https://github.com/WeiZ-boot/survey-on-smart-contract-vulnerability). 3 VULNERABILITYINSMARTCONTRACTS Thissectionpresentsarobustmethodologyforeffectivelyidentifyingandcategorizingvulnerabilitiesinblockchain smartcontracts.Toensurecomprehensivecoverageofvariousvulnerabilitytypes,ourinvestigationisconducted frommultipleperspectives.Specifically,forEthereumsmartcontracts,weprimarilyreferencetwokeyprojects:the DecentralizedApplicationSecurityProject(DASP)1andtheSmartContractWeaknessClassification(SWC)Registry2. 1https://dasp.co/ 2https://swcregistry.io/ ManuscriptsubmittedtoACMSurveyonQualityAssuranceofSmartContracts 9 Causes Vulnerabilities Typographical Error VE1 Syntax Error Right-To-Left-Override control character VE2 Outdated Compiler Version VE3 Floating Pragma VE4 Version Issue Use of Deprecated Solidity Functions VE5 Improper Adherence to Incorrect Constructor Name VE6 Coding Standards Uninitialized Storage Pointer VE7 Presence of Unused Variables VE8 Irrelevant Code Code with No Effects VE9 Shadowing State Variables VE10 Function Default Visibility VE11 Visibility State Variable Default Visibility VE12 Signature Malleability VE13 Signature Issue Missing Protection against Signature Replay Attacks VE14 Insufficient Verification Lack of Proper Signature Verification VE15 of Data Authenticity Unencrypted Private Data On-Chain VE16 Data Issue Fake EOS VS1 Forged Notification, Fake Receipt VS2 Unsafe Suicide VE17 Unprotected Authorization through tx.origin VE18 Improper Access Control Low-level Function Unsafe Delegatecall VE19 Coding Issue Unprotected Ether Withdrawal VE20 Write to Arbitrary Storage Location VE21 Assert Violation VE22 Input Issue Requirement Violation VE23 Wrong Address VE24 Arithmetic Overflow/Underflow VE25,VH1 Incorrect Call-Stack Overflow VE26 Calculation Asset Overflow VS3 DoS with Failed Call VE27 Denial of Insufficient Gas Griefing VE28 Service DoS with Block Gas Limit VE29 Unchecked Send VE30 Insufficient Control Use of Low-level Arbitrary Jump with Function Type Variable VE31 Flow Management Function Hash Collisions VE32 Message Call with Hardcoded Gas Amount VE33 Reentrancy VE34 Behavioral Unexpected Ether Balance VE35 Workflow Incorrect Inheritance Order VE36 Infinite Loop VE37 Consensus Transaction Order Dependence VE38 Time Manipulation VE39 Issue Bad Randomness VE40,VS4 Fig.2. Aclassificationofsmartcontractsvulnerabilitiesandtheircauses,where meansthevulnerabilityhasalreadybeensolved, meansthevulnerabilityiswidelydiscussed(notsolved),and meansthevulnerabilityhasbeenfixedbyspecificapproachesor (cid:32) (cid:35)tools.VEmeansvulnerabilitiesofEthereum,VHmeansvulnerab (cid:71)(cid:35)ilitiesofHF,VSmeansvulnerabilitiesofESOIO. DASPliststhetop10smartcontractvulnerabilities,whiletheSWCRegistrydetails37vulnerabilities,eachproviding uniqueinsightsintospecificvulnerabilitytypes. Additionally,wealsodrawinsightsfromseveralrelatedresearchpapers,including[15,60,61,81,98,106].By diligentlycollectingandexaminingallidentifiedsmartcontractvulnerabilitiesandtheirrespectivecauses,ouraimisto establishacomprehensivemethodologyforcategorizingtherootcausesofvulnerabilitiesinblockchainsmartcontracts. Thismethodologyisbuiltuponthewell-establishedCommonWeaknessEnumeration(CWE)rulesandeffectively ManuscriptsubmittedtoACM10 Weietal. identifiesfourprimaryrootcausesofvulnerabilities:codingstandards,dataauthenticity,accesscontrol,andcontrol flowmanagement. Toillustrateourclassificationframework,Figure2providesavisualrepresentationofsmartcontractvulnerabilities basedontheirrootcausesandcorrespondingsecondarycauses.Ourclassificationframeworkencompasses14distinct secondarycauses,whichareassociatedwith40specificvulnerabilitiesfoundinEthereum,HyperledgerFabric(HF), andEOSIO.Furthermore,thefigurealsoindicatesthestatusofeachvulnerability,indicatingwhetherithasbeen eliminated,canbemitigatedbyspecificmethods,orremainsunsolved.Itisimportanttonotethatourstudydoesnot encompassBitcoinsmartcontractsecurity.Thisisbecause,unliketheaforementionedplatforms,researchershave primarilyfocusedonstudyingtheconstructionandcapabilitiesofBitcoin’sscriptinglanguage.Duetoitsinherent
limitations,thereisnowidespreadandunifiedsmartcontractlanguageinBitcoin,thusrenderingthetypicalsmart contractvulnerabilitieslesspertinenttoitsecosystem. Recognizingthelackofconsistencyinthenaminganddefinitionofvulnerabilitiesacrossvariousstudies,wehave takenmeasurestoensureclarityanduniformityinouranalysis.Aspartofourresearch,wehavestandardizedthe namesofthesevulnerabilities.Furthermore,weofferdetailedexplanationsforeachvulnerabilitytopromotebetter comprehensionandfacilitatefutureresearchandanalysis. 3.1 ImproperAdherencetoCodingStandards Thistypeofweaknesshappenswhenasmartcontractisnotdevelopedinaccordancewithestablishedcodingrulesand bestpractices.Thisissueoftenarisesduetotherelativenoveltyofprogramminglanguagesusedforsmartcontracts, leadingtoashortageofexperienceddevelopersinthedomain.Additionally,somedevelopersmaypossessinsufficient knowledgeoflanguage-specificcodingstandards,leadingtoerrorsandvulnerabilitiesinsmartcontractimplementation. Improperadherencetocodingstandardscanmanifestinseveralways,including: 3.1.1 Syntax Errors(VE1, VE2). Theseerrorsoccurwhen thecodeviolates thesyntax rulesof theprogramming language,suchasspellingandpunctuationflaws.Twospecificexamplesofsyntaxerrorsaretypographicalerror(VE1) andRight-To-Left-Overridecontrolcharacter(VE2).VE1referstoatypographicalerrorinthecodewhereanincorrect operatorisused.VE2involvesthemisuseoftheU+202Eunicodecharacter,knownastheRight-To-Left-Overridecontrol character.Bothofthesevulnerabilitiescanbemitigatedbyfollowingbestpracticesandemployingpreventivemeasures. FormitigatingVE1,pre-conditionchecksandpropercodereviewprocessescanhelpidentifytypographicalerrorsand incorrectoperators,ensuringthecodefunctionsasintended.ThismethodissupportedbytheworkofKhajwal[70], whodemonstratestheeffectivenessofpre-conditionsinidentifyingtypographicalerrorsinprogramming.Additionally, thoroughcodereviewprocesses,asoutlinedbySykes[124],canserveasaneffectivemeasuretodetectandrectify typographicalerrors.RegardingVE2,usingreliablelibrariessuchasSafeMathcanprovidearobustfoundationfor performingsecuremathematicaloperations,reducingtheriskoferrorsandvulnerabilities. 3.1.2 VersionIssues(VE3,VE4,VE5,VE6,VE7). Versionissuesinsmartcontractscanariseduetotherapidprogress andupdatesinsmartcontracttechnology,includingchangesincompilerversions.Whendeveloperswritecodeusing outdatedordeprecatedfunctions,operators,orcodingstandardsinanewcompilerversion,itcanresultinunexpected behaviorsandpotentiallyexploitablestates.Thiscategoryofvulnerabilitiesincludesfivespecificflaws:outdated compilerversion(VE3),Floatingpragma(VE4),useofdeprecatedSolidityfunctions(VE5),incorrectconstructorname(VE6), anduninitializedstoragepointer(VE7).Toavoidthesevulnerabilities,itisessentialtostayupdatedonthelatestversion ofthecompilerandadheretotherecommendedcodingstandardsandbestpractices.Usingarecentversionofthe ManuscriptsubmittedtoACMSurveyonQualityAssuranceofSmartContracts 11 compilerensurescompatibilitywiththelatestlanguagefeatures,bugfixes,andsecurityenhancements.Additionally, developersshouldreviewandupdatetheircodebasetousetherecommendedfunctions,constructors,andstorage initializationtechniquesspecifiedintheupdatedcompilerversion. 3.1.3 IrrelevantCode(VE8,VE9,VE10). Irrelevantcodeinsmartcontractsreferstocodethatisnotessentialforthe executionorfunctionalityofthecontract.Whilethiscodemaynotdirectlyimpactthecorrectnessofthecontract,it canintroducesecurityvulnerabilitiesormakethemhardertodetect.Itisnotuncommonforprogrammingcodeto containunusedorshadowingparts.Thiscategoryofvulnerabilitiesincludesthreespecificflaws:presenceofunused variables(VE8),codewithnoeffects(VE9),andshadowingstatevariables(VE10).Tomitigatethesevulnerabilities,it isimportantforcontractwriterstothoroughlytestthefunctionalityandbehaviorofthecodebeforedeployment. Thisincludestestingeachintendedbehaviorofthecontracttoensurethatitworksasintendedanddoesnotcontain irrelevantorunusedcode.Byconductingcomprehensivetestingandcodereviews,contractwriterscanreducetherisk ofvulnerabilitiesintroducedbyirrelevantcodeinsmartcontracts. 3.1.4 Visibility(VE11,VE12). Solidityprovidesaccesscontrollabelsforfunctionsandvariablesinsmartcontracts, namelypublic,external,private,orinternal.Eachvisibilitylabeldetermineswhocanaccessorcallspecificfunctionsor variables.ThedefaultvisibilitysettinginSolidityispublic,whichmeansthatifthecontractwriterdoesnotexplicitly specifythevisibility,functionsandvariableswillbetreatedaspublicbydefault.Forgettingtosettheappropriate visibilityforafunctionorvariablecanleadtotwovulnerabilities:functiondefaultvisibility(VE11)andstatevariable defaultvisibility(VE12).Tomitigatetheserisks,contractwritersshouldcarefullyconsiderthesuitablevisibilityfor eachfunctionandvariable.Implementingpre-conditionchecksiscrucialtoensuringthatonlyauthorizedpartieshave accesstocriticalfunctionsorsensitivestatevariables. 3.2 InsufficientVerificationofDataAuthenticity
Thistypeofweaknessoccurswhensystemsfailtoproperlyverifytheoriginorauthenticityofdata,whichcanallow attackerstomanipulateoraccesssensitiveinformation.Thiscanleadtoawiderangeofsecurityissues,including cryptographicsignaturesandcryptographicdata. 3.2.1 CryptographicSignatures(VE13,VE14,VE15). :Cryptographicsignaturesplayacrucialroleinvalidatingthe authenticityandintegrityofdatawithinblockchainsystems.InEthereum(andBitcoin),theEllipticCurveDigital SignatureAlgorithm(ECDSA)iscommonlyusedforcryptographicsignaturegenerationandverification.However,there arecertainvulnerabilitiesrelatedtocryptographicsignaturesthatcanbeexploitedbyattackers:signaturemalleability (VE13),missingprotectionagainstsignaturereplayattacks(VE14),andlackofpropersignatureverification(VE15).To mitigatethesevulnerabilities,itisofutmostimportancetoimplementrobustsignatureverificationmechanisms.In thecontextofEthereum,thebuilt-infunctionecrecover()servesasavaluabletoolforverifyingECDSAsignatures. However,itiscrucialtoexercisediligenceandprecisionwhenutilizingthisfunctiontoensurethethoroughvalidation ofsignatureintegrityandauthenticity.Bydoingso,wecaneffectivelypreventissuessuchassignaturemalleability, replayattacks,andinadequateverification. 3.2.2 CryptographicData(VE16,VS1,VS2). Thistypeofvulnerabilityinsmartcontractsreferstosituationswhere sensitivedata,despitebeingmarkedasprivate,canstillbeaccessedbyunauthorizedparties.Thisvulnerabilityarises duetotheinherenttransparencyofblockchaintransactions,whichallowsthecontentoftransactionstobereadableby anyone.Attackerscaneasilyaccessandacquirethedatastoredinthecontract,leadingtosignificantfinanciallossesfor ManuscriptsubmittedtoACM12 Weietal. thecontractcreatorandparticipants.Thevulnerabilitiesassociatedwithcryptographicdataincludeunencryptedprivate dataon-chain(VE16),fakeEOS(VS1),andforgednotification,fakereceipt(VS2).Toaddressthesevulnerabilities,itis crucialtoprioritizetheproperencryptionofsensitivedatabeforestoringiton-chain.Thisensuresthatthedataremains secureandprotected.Furthermore,developersshouldexercisecautionwhendealingwithcontractsthatinvolveprivate data,takingextracaretothoroughlytesttheircontracts.Bydoingso,theycaneffectivelyminimizetheriskoffalling victimtohoneypotsorothermaliciousschemes. 3.3 ImproperAccessControl Thistypeofweaknessariseswhenunauthorizedusersgainaccesstoacontractandcanperformactionsthatthey shouldnotbeallowedto.Suchvulnerabilitiescanhavesignificantrepercussionsforthesmartcontractecosystem, includingfinanciallossesandotheradverseoutcomes.Improperaccesscontrolvulnerabilitiesmanifestintwoprimary forms:unprotectedlow-levelfunctionandcodingissues.Addressingthesevulnerabilitiesiscrucialtomaintainingthe securityandintegrityofsmartcontracts. 3.3.1 UnprotectedLow-levelFunction(VE17,VE18,VE19). UserscanutilizeSolidity’slow-levelfunctionsSELFDESTRUCT, tx.origin,andDELEGATECALLtocontrolcontracts.Theselow-levelfunctionsprovidepowerfulcapabilitiesbutcan beeasilyabusedbymalicioususersifnotusedwithcaution.Thefollowingarethevulnerabilitiesassociatedwith unprotectedlow-levelfunctions: • Unsafesuicide(VE17)TheSELFDESTRUCTfunctionallowsacontracttoberemovedfromtheblockchain,returningany remainingEthertoadesignatedtargetaddress.Whilethiscanbeusefulincertainscenarios,itcarriesrisks.IfEtheris senttoacontractthathasself-destructed,thefundswillbepermanentlylostandcannotberecovered.Consequently, itisimperativetoexercisecautionwhenutilizingtheSELFDESTRUCT function.Developersshouldcarefullyconsider thevariablesandconditionsinvolvedbeforeemployingthisfunction.Itiscrucialtoavoidreferencingcontract addressesorfundsthatcouldbemanipulatedinawaythatleadstounintendedlossofEther.Byadheringtothese precautions,developerscanmitigatetheriskofirreversibleEtherlossandensuretheintegrityoftheirsmartcontracts. • Authorizationthroughtx.origin(VE18)Thetx.originvariablerepresentstheaddressthatinitiatedatransaction,while msg.sender representstheimmediateinvokerofafunction.Relyingontx.originforauthorizationcanleadtoa vulnerabilityknownas“Authorizationthroughtx.origin"(VE18).Whenonecontractcallsanothercontract,tx.origin doesnotrepresentthecallingaddressbutrathertheoriginalinitiatorofthetransaction.Thiscanresultinfunds beingtransferredtothewrongaddress.Tomitigatethisvulnerability,itisrecommendedtousemsg.senderinsteadof tx.originforauthorizationchecks. • Unsafedelegatecall(VE19)ThisvulnerabilityarisesfromtheDELEGATECALLinstruction,whichallowsthird-party codetobeexecutedwithinthecontextofacurrentcontract.Thisvulnerability,alsoknownas“Delegatecallto UntrustedCallee"(VE19),canbeexploitedbyattackerstotakecontrolofanothercontract,especiallyinproxy contractswherecodecanbedynamicallyloadedfromdifferentaddressesatruntime.Ifanattackercanmanipulate theaddressusedinDELEGATECALL,theymaymodifystorageorexecutemaliciouscode,leadingtounauthorized actionssuchasfundtheftorcontractdestruction.
3.3.2 CodingIssues(VE20,VE21). Duetounintentionallyexposingsomefunctions,maliciouspartiescanwithdraw someorallEtherfromthecontractaccount.ThistypeofflawleadstounprotectedEtherwithdrawal(VE20)andwriteto arbitrarystoragelocation(VE21).InVE20,contractwriterswronglynameafunctionthatisaconstructor,andthenthe ManuscriptsubmittedtoACMSurveyonQualityAssuranceofSmartContracts 13 contractcanbere-initializedbyanyone.InVE21,malicioususerscanwritetosensitivestoragelocations,whichcan overwritetheoriginalcontentandchangethecontracts.Thistypeofflawcanbeavoidedbycarefullydesigningthe codeorstructure. 3.4 InsufficientControlFlowManagement Thistypeofweaknessoccurswhenattackerscanexploittheopennessofthepublicblockchaintogaincontroloverthe program’sexecutioninunexpectedways.Thisweaknesscanmanifestinvariousformsasfollows: 3.4.1 ImproperInput(VE22,VE23,VE24). DuetoerrorhandlinginEVM,improperinputcancauseassertviolation (VE22),requirementviolation(VE23)andwrongaddress(VE24).TheSolidityassert(),require(),asguardfunctionsare introducedtoimprovethereadabilityofcontractcode.However,assert()andrequire()requirestronglogicalconditions, andimproperusewillcauseerrors.Moreover,thelengthofacontractaddressshouldbe40hexadecimalcharacters.If theaddresslengthisincorrect,thecontractcanstillbedeployedwithoutanywarningfromthecompiler.Ethereum automaticallyregistersanewaddressthatisownedbynobody,andanyEthersenttothisaddressbecomesinaccessible. Tomitigatethesevulnerabilities,itisimportanttocarefullyhandleinputvalidation,useassert()andrequire()with appropriateconditions,andvalidatetheformatandlengthofcontractaddresses. 3.4.2 IncorrectCalculation(VE25,VH1,VE26,VS3). Thistypeofweaknesshappenswhencontractsperformacalculation thatgeneratesincorrectresultsandthatmayleadtoalargersecurityissuesuchasarbitrarycodeexecution.Arithmetic overflow/underflow(VE25,VH1) isthemostcommonerrorinsoftware,anditbothhappensinEthereumandHF. Call-stackoverflow(VE26)occursduetotheEthereumVirtualMachine(EVM)imposingalimitonthedepthofthe call-stack,allowingamaximumof1024nestedfunctioncalls.Ifanattackersuccessfullyreachesthislimitbyrepeatedly invokingfunctions,itcanresultinacall-stackoverflowvulnerability.Oncethecall-stackreachesitsmaximumdepth, subsequentinstructions,suchasthesendinstruction,willfail.Assetoverflow(VS3)specificallypertainstotheEOSIO blockchain.Itoccurswhenthereisanoverflowintheassettype,whichrepresentstokenbalancesandotherasset valuesontheEOSIOplatform. • Arithmeticoverflow/underflow(VE25)Thisvulnerability,commonlyknowninsoftwareprogramming,isnotspecific tosmartcontracts.Itoccurswhenanarithmeticoperationproducesavaluethatexceedsthemaximumorminimum rangeofintegerrepresentation.InEthereumcontracts,thisvulnerabilityarisesduetothebehavioroftheEVM’s integerarithmeticandthelackofautomaticchecksforarithmeticalcorrectness.Forinstance,iftheresultofan additionoperationsurpassesthemaximumvaluerepresentablebyaspecificintegertype,itwrapsaroundtoa lower-than-expectedvaluewithoutraisinganerrororwarning.ResearchbyTorresetal.[133]hasidentifiedover 42,000contracts,particularlyERC-20Tokencontracts,vulnerabletoarithmeticoverflow/underflow.Tomitigatethis issue,itisadvisabletoemploylibrariessuchasSafeMath.Theselibrariesoffersecureimplementationsofarithmetic operationswithbuilt-incheckstopreventoverflowandunderflowerrors. 3.4.3 DenialofService(VE27,VE28,VE29). DenialofServicevulnerabilitiescanaffectsmartcontractsandresult inexceptionsthatmayleadtoundesirableconsequencessuchascontractlock-upsorfreezingoffunds.Thereare multiplewaysinwhichDoSattackscanbecarriedout,withtwoprimaryincentives:failedcallsandgasconsumption. OnetypeofDoSvulnerabilityisDoSwithfailedcall(VE27),whereanexternalcall,whetheraccidentalordeliberate, fails.Thisvulnerabilityisparticularlyrelevantinpaymentscenarioswheremultiplecallsareexecutedwithinasingle transaction.Thefailureofanexternalcallcandisrupttheintendedflowofthecontract,potentiallyleadingtoundesired ManuscriptsubmittedtoACM14 Weietal. consequences.AnotherDoSproblemcanbeconcludedasgas-relatedvulnerabilities.Gasisamechanismdesigned topreventresourceabuse,andeachoperationwithinasmartcontractconsumesacertainamountofgas.Onesuch vulnerabilityisinsufficientgasgriefing(VE28),whichoccurswhenthereisnotenoughgastosupportanexternalcall, causingthetransactiontobereverted.Anothergas-relatedvulnerabilityisDoSwithblockgaslimit(VE29),alsoknown asDoSwithUnboundedOperations.MitigatingtheseDoSvulnerabilitiesrequirescarefuldesignandconsiderationof gasusage. • DoSwithblockgaslimit(VE29).Topreventresourceabuse,especiallyDoSattacks,Ethereumproposesgasmechanism tochargeanexecutionfeefromeachoperationpaidbytransactionsenders.Tofurthersafeguardthenetwork,each blockhasapredeterminedmaximumamountofgasthatcanbeconsumed,knownastheBlockGasLimit.The gasconsumptionofatransactionmustbelessthanorequaltotheBlockGasLimit;otherwise,thetransaction
willfailtoexecuteandanychangesmadeduringitsexecutionwillberolledback.Thisensuresthatnosingle transactionmonopolizesexcessiveresourceswithinablock,promotingfairusageandpreventingDoSattacksthat couldoverwhelmthenetwork.ItisimportanttonotethatdifferentEVMinstructionshavevaryinggascosts.Some operations,suchasADD,AND,andPOP,haverelativelylowgascosts,whileothers,likeSSTORE,incurhighergas costs.Thisdifferentiationencouragesefficientandresponsibleuseofgasresources. 3.4.4 UseofLow-levelFunction(VE30,VE31,VE32,VE33). Solidity’slow-levelfunctions,suchascall,transfer,send, mstoreandabi.encodePacked,provideuserswithcontrolandflexibilitywheninteractingwithsmartcontracts.However, improperuseoftheselow-levelfunctionscanintroduceunexpectedbehaviorandvulnerabilitiesintothecontract’s programlogic.Uncheckedsend(VE30)ariseswhendevelopersmakethecommonassumptionthataparticularfunction willneverfail.Ifamalicioususercanforcethefunctiontofail,itcanleavethecontractinanunexpectedstate.Theuse oftransferandsendfunctionscanleadtomessagecallwithhardcodedgasamount(VE33)whenthegascostsignificantly changes,suchasduringhardforksornetworkupgrades.Themstorefunctioncanintroducethearbitraryjumpwith functiontypevariable(VE31)vulnerabilityifanattackercanmanipulateafunctiontypevariabletopointtoanycode instruction.Thiscanpotentiallyallowanattackertoexecutearbitrarycodeandcompromisetheintegrityofthe contract.Hashcollisions(VE32)occurwhentheabi.encodePackedfunctionisusedincorrectlywithmultiplevariable lengtharguments.Tomitigatethesevulnerabilities,itiscrucialtocarefullyreviewandvalidatetheusageoflow-level functions,handleexceptionsappropriately,accountforpotentialchangesingascosts,andimplementrobustinput validationandverificationmechanisms. • Uncheckedsend(VE30)Thisvulnerabilityisalsodescribedasunhandledexceptions,exceptiondisorder,orunchecked low-levelcall.Thisissuehappenswhenthecallfailsaccidentallyoranattackerforcesthecalltofail.Insomecases, developersmayincludecodetocheckthesuccessofthecall,buttheyneglecttohandletheexceptionsproperly. Asaresult,fundsintendedfortransfermaynotreachtheintendedrecipient.Thisvulnerabilitystemsfromthe inconsistentexception-handlingbehaviorinSolidity,whichcanleadtounexpectedoutcomesifnothandledcorrectly. 3.4.5 ImproperBehavioralWorkflow(VE34,VE35,VE36,VE37). Itreferstovulnerabilitiesthatarisewhentheexpected orderorsequenceofoperationswithinasmartcontractismanipulatedbymalicioususers,leadingtounexpected statesorundesiredbehavior.Thesevulnerabilitiesincludereentrancy(VE34),unexpectedEtherbalance(VE35),incorrect inheritanceorder(VE36),andinfiniteloop(VE37).Inreentrancy(VE34),amaliciouscontractcallsbackintothecalling contractbeforethefirstinvocationofthefunctionisover.UnexpectedEtherbalance(VE35)occurswhenmalicioususers intentionallysendfundstoacontractinaspecificmannertodisruptitsintendedbehaviororcauseadenial-of-service ManuscriptsubmittedtoACMSurveyonQualityAssuranceofSmartContracts 15 condition.Bymanipulatingthecontract’setherbalance,attackerscanaffectthecontract’sfunctionalityand,inextreme cases,renderitunusable.Incorrectinheritanceorder(VE36)isavulnerabilitythatarisesfromtheimproperorderingof contractinheritance.InSolidity,contractscaninheritfromothercontracts,andtheorderofinheritancecanimpactthe behaviorandfunctionalityofthederivedcontract.Malicioususerscanmanipulatetheinheritanceordertoachieve unexpectedoutcomesandpotentiallyexploitvulnerabilities.Infiniteloop(VE37)referstoavulnerabilitywhereacontract fallsintoaninfiniteloop,leadingtonon-terminationofcontractexecution.Thisvulnerabilityisoftenassociatedwith thefallbackfunctionbeingincorrectlyinvoked,resultinginrepeatedandendlessexecutionofthefallbackcode.This canexhaustthecontract’sgasanddisrupttheintendedfunctionalityofthecontract. • Reentrancy(VE34)Thisvulnerabilityoccurswhenacontractinvokesafunctionfromanexternalcontract,andthe calledcontracthassufficientgastoinvokeacallbackintothecallingcontract.Thiscreatesaloopwherethecalled contractre-entersthecallingcontractbeforetheinitialinvocationiscompleted.Maliciousattackerscanexploitthis vulnerabilitytomanipulatetheexecutionflowandpotentiallyexploitvulnerabilitiespresentinthecontract.Itis crucialtocarefullyreviewandsecurecontractinteractionstopreventre-entranceattacksandensuretheintegrityand securityofthesmartcontractsystem.Toillustratehowthisvulnerabilityisexploited,weprovideanexampleshown inFigure3.Theexampleinvolvestwocontracts:ContractA,representingtheattacker,andContractB,representing thevictim.Thevulnerabilityisdemonstratedinthreesteps:○1 ContractAinvokesthefunctionftocallthefunction towithdrawContractB;○2 whereBsubsequentlytransferssomeethertoA(msg.senderrepresentstheaddress ofcontractA).Thisstepfollowsacommonwithdrawalpattern[118];○3 Aspartoftheethertransfer,ContractB invokesthefallbackfunctionofContractA,allowingContractAtospecifyanyfunction(“calltotheunknown"). Inthisscenario,ContractAre-entersContractBthroughthefallbackfunction,whichhasnospecificname.This
re-entranceallowsContractAtorepeatedlycallthefallbackfunctionandpotentiallyexploitvulnerabilitieswithin ContractB. contract B call contract A ① B.withdraw () A.f () ③ fallback B transfers Ether to A ② A.() Block state changed Fig.3. Reentrancyattackflow 3.4.6 ConsensusIssues(VE38,VE39,VE40,VS4). Intheblockchain,thesynchronizationofsubsequentblockswith themajorityofthenetworkreliesonfollowingaconsensusprotocol,suchasProofofWork(PoW)orProofofStake (PoS).Thisconsensusprotocolallowsnetworkparticipantssufficienttimetoreachanagreementonwhichtransactions shouldbeincludedintheblocks.However,thesynchronizationprocessitselfintroducesvulnerabilitiesthatcanbe exploitedbyattackers.Thesevulnerabilitiesincludetransactionorderdependency(VE38)(TOD),timemanipulation (VE39),andbadrandomness(VE40,VS4). ManuscriptsubmittedtoACM16 Weietal. • TOD(VE38):Thisvulnerability,alsoknownasFrontrunning,occursduetotheprioritizationmechanismfortransac- tionsinblockchainblocks.Minershavetheabilitytochoosewhichtransactionstoincludeinablockandtheorderin whichtheyarearranged.Sincetransactionsareoftenprioritizedbasedongasprice,amaliciousminerwhocansee andreacttotransactionsbeforetheyareminedmaymanipulatethetransactionordertotheiradvantage.Byvarying theorderoftransactionsandmanipulatingtheoutputofthecontract,theycanmanageundesirableoutcomesor financiallossesforusers. • Timemanipulation(VE39):Thisvulnerabilityariseswhensmartcontractsrelyonthetimestampinformationfrom blockstoperformcertainfunctions.InSolidity,thecurrenttimestampcanbeobtainedusingblock.stampornow. However,thistimestampvaluecanbemanipulatedbyminers.Ifacontract’sfunctionalityisdependentonthe timestamp,minerscanprofitbychoosingasuitabletimestamptomanipulatethecontract’sbehavior.Thisvulnerability isalsoreferredtoas“blockvaluesasaproxyfortime". • Badrandomness(VE40):Thisvulnerabilityreferstovulnerabilitiesinthegenerationofrandomnumberswithin smartcontracts.Randomnumbersareoftenusedtomakedecisionsordetermineoutcomes.Iftherandomnumber generationprocessisflawed,maliciousactorsmaybeabletopredicttheoutcomeofthecontractandexploitit.One exampleofbadrandomnessistheuseofapredictableseedvaluefortherandomnumbergenerator.Ifanattacker canguessordeterminetheseedvalue,theycanpredictthegeneratedrandomnumbersandmanipulatethecontract accordinglytotheiradvantage. 3.5 CommonVulnerabilityRanking Fig.4. VulnerabilitiesFrequencyStatistics SincethelastupdateoftheDASP(DecentralizedApplicationSecurityProject)in2018,wehavecreatedanewlistof thetop10smartcontractvulnerabilitiesthatposesignificantriskstothesecurityandfunctionalityofcontracts.This listisbasedonthefrequencyofoccurrenceamongvariousanalysistoolsavailable3.Figure4providesstatisticsonthe occurrenceof22vulnerabilitycategories.Thetop10smartcontractvulnerabilitiesareasfollows:reentrancy(VE34), arithmeticoverflow/underflow(VE25),DoSwithblockgaslimit(VE29),unsafesuicidal(VE17),unsafedelegatecall(VE19), uncheckedsend(VE30),TOD(VE38),timemanipulation(VE39),authorizationthroughtx.origin(VE18),andvariousother vulnerabilities.Thesevulnerabilitieshavebeenidentifiedasthemostcommonandhigh-riskissuesthatdevelopers shouldprioritizewhenassessingthesecurityoftheirsmartcontracts. 3https://github.com/WeiZ-boot/survey-on-smart-contract-vulnerability ManuscriptsubmittedtoACMSurveyonQualityAssuranceofSmartContracts 17 Thereentrancyvulnerabilityattractssignificantattentionfromresearchersduetoitsdifficultyindetectionand mitigation. The complex and decentralized nature of smart contracts makes it challenging to ensure the atomic executionoffunctionsandproperhandlingofreentrantcalls.Arithmeticoverflow/underflow isacommonissuein softwareprograms,particularlythosewritteninlow-levellanguages.GasusageplaysacrucialroleintheEVMand thesmartcontractecosystem,andaccuratelyestimatingtherequiredgasforanoperationcanbedifficult.Giventhat smartcontractapplicationsoftenhandlesensitivedataandsubstantialamountsofvalue,DoSwithblockgaslimitcan leadtodenial-of-serviceattacks,datacorruption,andfinanciallossesforusers.Unsafesuicidal,unsafedelegatecall,and authorizationthroughtx.originvulnerabilitiesoccurwhentheaccesscontrolofasmartcontractisflawed.Accesscontrol determineswhichentitiescaninteractwiththecontractandwhatactionstheycanperform.Thesevulnerabilitiescan resultinsecurityrisksandpotentialfinanciallosseswhenaccesscontroliscompromised.Uncheckedsendoccurswhena contractfailstohandleexceptionsfromfailedcallsappropriately.Thisvulnerabilitycausesthesmartcontracttobehave unexpectedlyandcompromisesitssecureoperation.TOD,timemanipulation,andbadrandomnessvulnerabilitiesare relatedtoconsensusissuesinfluencedbytheblockchainnetwork.Smartcontractsareexecutedontheblockchain andmustfollowthesametransactionorderastheunderlyingblockchain.Thismeansthatevenifasmartcontractis designedtoberesistanttoTODandtimemanipulation,itcanstillbevulnerableiftheunderlyingblockchainisnot resistanttotheseissues. Inthissection,weperformedacomprehensiveanalysisoftherootcausesofvulnerabilitiesinthesmartcontract
domainandintroducedanovelclassificationsystemtoeffectivelycategorizethem.Furthermore,weconducteda statisticalrankingofthemostfrequentlyencounteredvulnerabilitiesbasedonexistingresearch.Thesefindingsoffer conclusiveandpreciseanswersthateffectivelyaddressourresearchquestion,RQ1,asoutlinedinSection2.2. Bygainingagoodunderstandingofthesevulnerabilitiesinsmartcontractsandtheirranking,developerscan effectivelyallocatetheirtimeandresources,prioritizingtheresolutionofthemostcriticalsecurityconcerns.Additionally, tofullycomprehendthepotentialdamagecausedbythesevulnerabilities,itiscrucialtoexplorethecommontypesof attacksthatcanexploitthem.Bycarefullyexaminingtherelationshipbetweenvulnerabilitiesandattacks,developers canidentifypotentialattackvectorsandproactivelyimplementrobustmeasurestomitigatetheserisks. 4 ATTACKSONSMARTCONTRACTS Arecentsurvey[147]revealsarapidincreaseinthenumberofSoliditycontractsoverthepastfiveyears.Thisgrowth reflectstheexpandingrangeofsmartcontractapplicationsacrosssectorssuchasDeFi[20],insurance,andlending platforms.Unfortunately,thisgrowthhasalsoledtoanincreaseinthenumberofattackersexploitingvulnerabilitiesin smartcontracts.Consequently,severalhigh-profileattackshaveoccurred,resultinginsubstantialfinanciallosses. ThemostnotableamongtheseistheDAOattackin2016,whichledtomillionsofdollarsinEtherbeingdrained fromtheorganization.Sincethen,smartcontractshaveexperiencedseveralhigh-profileattacksfrom2016to2021,as showninFigure5.Togainabetterunderstandingoftheseattacks,wehaveanalyzedandidentifiedeightrepresentative attackpatterns,asshowninFigure6.Thisfigurehighlightsthemajorapplicationdomainsofsmartcontractsandthe correspondingtargetedattackpatterns.Additionally,weconductanexaminationofthevulnerabilitiesthatcontribute totheseattacks.Throughtheclassificationofvulnerabilitiesbasedonknownattackpatterns,wecanidentifycommon weakness thatrequireattention. Following thisanalysis, weprovideacomprehensivebreakdown ofeachattack, sheddinglightonthespecificvulnerabilitiesthatcontributetotheseattacks. ManuscriptsubmittedtoACM18 Weietal. Fig.5. Severalhigh-profileattacksfrom2016to2021 Applications Attacks Vulnerabilities VE34 Reentrancy VE30 Unchecked Send Organization A1 theDAO Attack VE19 Unsafe Delegatecall Wallet A2 Parity Wallet Attack (i,ii) VE17 Unsafe Suicidal Games/ A3 Fomo3D Attack VE40 Block Randomness Gambling A4 KotET Attack VE28 Insufficient Gas Griefing VE25 Arithmetic Overflow A5 BatchaOverflow Attack VE38 TOD ICO/Token A6 DEXs Attack VE11 Function Default Visibility A7 Bancor Attack VE10 Shadowing State Variables Others A8 Honeypots VE36 Incorrect Inheritance Order VE6 Incorrect Constructor Name Fig.6. Therelationshipsbetweenattacksandvulnerabilities 4.1 TheDAOAttack(A1) TheDAO(DecentralizedAutonomousOrganization)wasagroundbreakingprojectlaunchedontheEthereumblockchain in2016.Itaimedtocreateadecentralizedventurecapitalfundwhereparticipantscouldinvestinprojectsandvoteon fundingdecisionsthroughtheuseofsmartcontracts.TheDAOprojectgainedsignificantattentionandraisedover$150 millionUSDinfundingfrominvestors.However,theDAO’ssuccesswasshort-livedasitfellvictimtoacriticalsecurity vulnerability.InJune2016,anattackerexploitedaflawintheDAO’ssmartcontractcode,allowingthemtodrain approximately$60millionUSDworthofetherfromtheorganization[13].Thisevent,knownastheDAOattack,wasa significantsetbackfortheEthereumcommunityandledtoacontentiousdebateabouttheimmutabilityofblockchain transactionsandtheneedforahardforktorecoverthestolenfunds.Ultimately,ahardforkwasimplementedto createanewversionoftheEthereumblockchainthatreversedtheeffectsofthehackandreturnedthestolenfunds totheirrightfulowners.FollowingtheoccurrenceofTheDAOhack,othersmartcontracts,suchasSpankchain[95] andLendf.me[107],alsoexperiencedlossesduetocomparablesecurityvulnerabilities.Atzeietal.[14]providedtwo attackcontractexamples,calledMalloryandMallory2.InMallory,attackermanipulatesthecontrolflowandexploits reentrancy(VE34).InMallory2,attackerefficientlyexploitsarithmeticoverflow/underflow(VE25)anduncheckedsend (VE30)vulnerabilitiesbyusingonlytwocalls. ManuscriptsubmittedtoACMSurveyonQualityAssuranceofSmartContracts 19 4.2 ParityWalletAttack(A2) TheParityWalletattackencompassestwodistinctincidentsthatoccurredin2017.Duringtheseincidents,theParity Multisig Wallet suffered breaches, leading to substantial financial losses. The Parity Wallet is comprised of two components:alibrarycontractandwalletcontracts.Thelibrarycontractcontainstheessentialfunctionsofawallet, whilethewalletcontractsactasproxiesthatdelegatecallstothelibrarycontractthroughthedelegatecallmechanism. Inbothincidents,thevulnerabilitiesenabledtheattackerstoobtainunauthorizedcontroloverthewallets.Thefirst incidentiscausedbyexploitingunsafedelegatecal(VE19)andmorethan30MUSDworthofetherisdrained[94].In thisincident,theattackerinitiatedtwotransactionstomanipulateeachcontractinvolved.Thefirsttransactionwas aimedatgainingownershipofthevictim’swalletcontract.ThesecondincidentontheParityMultisigWalletexploited thevulnerabilityknownassuicide(VE17)andresultedinthelockingofmorethan$280millionUSDworthoffunds
[99].Inthisincident,theattackerleveragedthedelegatecallmechanismtoinitializethemselvesastheownerofthe walletcontract,similartothefirstincident. 4.3 Fomo3DAttacks(A3) TheFomo3DcontractwasanEthereumgamewhereparticipantscouldpurchasekeysusingEtherandreferothersto thegametoearnmoreEther.Theobjectiveofthegamewastobethelastparticipanttopurchaseakeybeforethetimer expired,therebywinningtheentirepotofEther.Theattackerpurchasedaticketandthensentmultipletransactions withhighgaspricesinrapidsuccession,effectivelyconsumingasignificantportionoftheblock’sgaslimit.Thisaction causedothertransactionsrelatedtoFomo3D,includingthekeypurchasesmadebyotherparticipants,tobedelayedor stuckinapendingstateuntilthetimerranout.Theattackersgainanadvantagebyexploitingtwovulnerabilities:bad randomness(VE40)andDoSwithblockgaslimit(V29). 4.4 KotETAttack(A4) TheKingoftheEtherThrone(KotET)contractwasalsoagamecontractwhereparticipantscompetedtowinthe throneandreceivealltheEtherheldinthecontract.Thisgamecontractwasimplementedasacontractaccountonthe Ethereumblockchain.TheKotETattack,whichoccurredinFebruary2016[93],exploitedtwovulnerabilities:unchecked send(VE30)andinsufficientgasgriefing(VE28).Intheattack,whentheKotETcontractattemptedtotransferfundsto anotherwalletcontract,bothcontractsrequiredsufficientgastosuccessfullyprocessthetransaction.However,ifthe walletcontracthadinsufficientgas,itwouldfailtocompletethepayment,resultinginthefundsbeingreturnedtothe KotETcontract.Importantly,theKotETcontractwasnotawareofthepaymentfailure,andthelatestplayerwouldbe crownedastheKing,whilethecompensationpaymentintendedforthepreviousplayerwouldnotbesent. 4.5 BatchOverflowAttack(A5) TheBatchOverflowattack,whichoccurredinApril2018,targetedtheBeautyEcosystemCoin(BEC)token.Theattack exploitedarithmeticoverflow/underflow(VE25)vulnerabilitytoachieveanunauthorizedincreaseindigitalassets.This vulnerabilityresultedinthetheftofBECtokensandatemporaryshutdownoftheexchangeplatform.Accordingto theblockchainsecurityfirm,PeckShield4,theBatchOverflowattackwasnotlimitedtotheBECtoken.Accordingto theblockchainsecurityfirmPeckShield,theydiscoveredsimilarintegeroverflowvulnerabilitiesinaround12other 4https://peckshield.com/ ManuscriptsubmittedtoACM20 Weietal. tokensmartcontracts.SomeexamplesincludeSMT(proxyOverflow),UET(transferFlow),SCA(multiOverflow),HXG (burnOverflow),andothers. 4.6 FrontrunningAttack(A6,A7) BoththeDEXsattackandtheBancorattackcanbecategorizedasFrontrunningattacks.TheconceptofFrontrunning is not exclusive to blockchain and is commonly observed in traditional financial markets. Frontrunning involves manipulatingfinancialmarketsbygainingundisclosedinformationabouttransactionsbeforehand[130].Thispractice isgenerallydeemedillegalinmostcountries.Inthecontextofblockchain,everytransactionispubliclyvisibleinthe pendingpoolbeforebeingincludedinablock.Miners,whohavetheauthoritytochoosewhichtransactionstoinclude, oftenprioritizethosewithhighergasprices.Thiscreatesanopportunityforattackerstomanipulatethetransaction orderandmaximizetheirownprofits.FrontrunningattacksexploitthevulnerabilityknownasTOD(VE38),whichis alsoreferredtoastheFrontrunningvulnerability.Eskandarietal.[43]categorizethisvulnerabilityintothreetypesof attacks:displacement,insertion,andsuppressionattacks,asdepictedinFigure7. BBeeffoorree After BBeeffoorree After BBeeffoorree After TTTT1111 TTT111 TTTT1111 TTT111 TTTT1111 TTT111 TTTTvvvv TTTAAA TTTTvvvv TTTAAA111 TTTTvvvv TTTAAA111 TTTT3333 TTTvvv TTTT3333 TTTvvv TTTT3333 TTTAAA222 TTT333 TTTAAA222 TTTAAA333 TTTTAAAA TTTAAA111 TTT333 TTTAAA111 TTTvvv TTTAAA222 TTTAAA222 TTT333 TTTAAA333 (a) Displacement (b) Insertion (c) Suppression Fig.7. Thethreefrontrunningattackcases • DisplacementAttack:AshighlightedinFigure7(a),theattackerobservesaprofitabletransaction𝑇 𝑉 fromthe victimandcreatesanewtransaction𝑇 𝐴withahighergasprice.Theattackerthenbroadcasts𝑇 𝐴tothenetwork. Whentheminerassemblesthetransactionsintoablock,theyprioritizeincluding𝑇 𝐴before𝑇 𝑉,effectivelydisplacing thevictim’stransaction.Asaresult,theattackercanfront-runthevictimandpotentiallybenefitfromfavorable marketconditions. • InsertionAttack(SandwichAttack):AshighlightedinFigure7(b),theattackerobservesaprofitabletransaction 𝑇 𝑉 andcreatestwotransactions,𝑇 𝐴1and𝑇 𝐴2.𝑇 𝐴1hasahighergaspricethan𝑇 𝑉,and𝑇 𝐴2hasalowergasprice.The attackerbroadcasts𝑇 𝐴1and𝑇 𝐴2tothenetwork.Whentheminerassemblesthetransactionsintoablock,theyplace 𝑇 𝐴between𝑇 𝐴1and𝑇 𝐴2,effectivelysandwichingthevictim’stransaction.Thisallowstheattackertoexploitprice discrepanciesorotherfavorableconditions. • SuppressionAttack:AshighlightedinFigure7(c),theattackerobservesaprofitabletransaction𝑇 𝑉 anddecides toexcludeitfromtheblock.Theattackercreatesmultipletransactionswithhighergaspricesthan𝑇 𝑉 tofillup theblock.Whentheminerassemblesthetransactionsintoablock,theyintentionallyleaveout𝑇 𝑉,suppressingits execution.Thispreventsthevictimfrombenefitingfromthetransactionandallowstheattackertopotentiallytake ManuscriptsubmittedtoACMSurveyonQualityAssuranceofSmartContracts 21 advantageofmarketconditions.Inthisattack,DoSwithblockgaslimit(VE29)vulnerabilityisalsopresent,asthe
attackerfillstheblockwithhighgaspricetransactionstoconsumetheblockgaslimit. 4.6.1 DEXsAttack(A6). Thedecentralizedexchange(DEX)isanexchangeplatformbuiltonsmartcontractswhereusers canexchangetheirERC-20tokensforetherorothertokens.Frontrunningattackshavebecomeasignificantconcernin DEXs.Theseattacksexploitthetransactionorderdependencevulnerabilitytomanipulatetheexecutionoftransactions andgainanunfairadvantageintrading.Whenasearcherdetectsatransactionthatcanyieldaprofit,itattemptsto front-runthattransactionbysubmittingitsowntransactionwithhighergasfeestoensureitsexecutionbeforethe victim’stransaction.Theattacker’stransactionisdesignedtotakeadvantageoftheanticipatedpricemovementcaused bythevictim’stransaction. Forexample,inthecaseofPancakeSwapDEX,theattacker’sbotmayobserveabuyertryingtopurchase1Corgicoin token.ThebotquicklysubmitsitsowntransactiontobuytheCorgicointokenandthenimmediatelysellsitafter someoneelse’stransactiontomaximizeprofits.Sincethesetransactionsoccurwithinthesameblock,theattacker effectivelyfront-runsthevictim’stransactionandbenefitsfromthepricemovementcausedbythevictim’strade.These front-runningattacksareperformedbyhighlycompetitivebotsthataimtomaximizetheirprofitsbyextractingMiner’s ExtractableValue(MEV).AccordingtoFlashbots[46],searchersextractedapproximately691millionUSDworthof valuefromEthereuminJanuary2023alone. 4.6.2 BancorEvent(A7). TheBancorICOisadecentralizedexchangeplatformthatallowsuserstocreateandtrade theirowntokens.Duringtheauditofitsexchangesmartcontract,twovulnerabilitieswerediscovered:TOD(VE38) andfunctiondefaultvisibility(VE11).TheattackerexploitedtheTODvulnerability,whichenabledthemtoexecute transactionsaheadofothers,resultinginaprofitof135,229USDworthofether[141].Fortunately,noreal-worldattack occurred,butthevulnerabilityitselfwasidentifiedandaddressed. 4.7 Honeypots(A8) Honeypotsinthecontextofsmartcontractsareatypeoffraudulentschemethatcapitalizesonsecurityvulnerabilities whileemployingdeceptivetactics.Thefundamentalconceptofahoneypotinvolvesintentionallycreatingasmart contractthatappearstopossessanobviousflaworvulnerability,enticingpotentialvictimstoexploititforfinancial gain.However,thecontractisdeliberatelydesignedinawaythatwhensomeoneattemptstotakeadvantageofthe apparentvulnerability,theyenduplosingtheirfundsinstead.Honeypotsmanipulatehumangreedandthedesire forquickprofits,luringunsuspectingusersintofallingforthetrap.Theaimistopresentanenticingopportunityfor financialgain,whileinreality,itisatraporchestratedbymaliciousactors.AccordingtoTorresetal.[134],honeypots typicallytakeadvantageofspecificvulnerabilitiestocarryouttheirdeceptiveschemessuchasincorrectconstructor name(VE6),shadowingstatevariables(VE10),andincorrectinheritanceorder(VE36). Inthissection,wehavesystematicallyexaminedeightcommonattackpatternsandtheirassociatedlistsofvulnera- bilities.Thisanalysishasallowedustoaddressthesecondresearchquestion,RQ2,asoutlinedinSection2.2,which focusesonhowthesecommonattacksexploitvulnerabilitiesandtheconsequencesofsuchattacks.Ourstudyofpast attacksprovidesvaluableinsightsintocommonvulnerabilitiesandattackpatterns,aswellasemergingtrendsinsmart contractsecurity.Theseinclude: ManuscriptsubmittedtoACM22 Weietal. Attack Defense Methodology Repair Formal Verification Symbolic Execution Contract Contract Analyzer Fuzzing Test Migration Intermediate Representation Machine Learning Proactive Gas Estimation Security Enhancement Upgradable Data Privacy-Preserving Contracts Transactions Monitoring Reactive Monitoring Contracts State Monitoring Fig.8. Researchideasforthedefenseofsmartcontracts • IncreasingComplexityofSmartContractAttacks.Thesophisticationofsmartcontracts,withadvancedfeatures andintegrations,hasledattackerstodevelopmorecomplextechniquesforexploitation.Theseincludeattacksthat leveragemultiplevulnerabilitiessimultaneouslyorthatexploittheinteractionsbetweendifferentsmartcontracts. • RiseinAttacksTargetingDeFiApplications.DeFiplatforms,duetotheirhighliquidityandrapidgrowth,have becomelucrativetargetsforattackers.Vulnerabilitiesintheseplatformscanleadtosignificantfinanciallosses,as seeninvarioushigh-profileincidentsinrecentyears. • PotentialAdventofAI-EnabledAttackers.AI-enabledattackscouldpotentiallyidentifyvulnerabilitiesinsmart contractsmorequicklyandexploitthembeforetheyaredetectedandremediedbydevelopersorsecurityteams.This includestheabilityofAIsystemstoanalyzevastamountsofcodeatanunprecedentedspeed,identifypatternsand weaknessesoverlookedbyhumananalysis,andevenadapttochangingsecurityenvironments. Theseinsightsarecrucialforsmartcontractdevelopersinenhancingthesecurityoftheircontracts.Whileitmay bechallengingtocompletelyeliminateallattacksonvulnerablesmartcontracts,therearestepsthatcanbetakento minimizerisksandimprovecontractsecurity.Byimplementingbestpracticesandemployingappropriatesecurity measures,developerscanreducethelikelihoodoftheircontractsbeingexploitedbyattackers.Buildinguponour understandingofattackpatterns,wecannowexplorevariousdefensemethodologiesinthenextsection. 5 DEFENSEMETHODOLOGIES Defensetechnologiesevolvealongsidetheadvancementofattacks,andthereisasubstantialbodyofworkonsecurity measuresforsmartcontracts[30,130,148].Figure8providesanoverviewofacomprehensivesetofresearchsolutions
forsmartcontractdefense.Generallyspeaking,defensestrategiesforsmartcontractscanbecategorizedintotwomain groups:proactiveandreactive.Proactivedefensestrategiesinvolvetakingpreventivemeasurestomitigateattacksbefore theyoccur,whilereactivedefensestrategiesfocusonrespondingtoattacksaftertheyhavehappened.Proactivedefense strategiesaimtoaddressknownattacksthathavebeenpreviouslyidentifiedandstudied,withdefensemechanisms developedspecificallyforthem.Theseattackscanbepreventedormitigatedusingcontractanalyzersorsecurity enhancements.Reactivedefensestrategies,ontheotherhand,pertaintoattacksthathavenotbeenpreviouslyidentified ManuscriptsubmittedtoACMSurveyonQualityAssuranceofSmartContracts 23 orstudied,andforwhichdefensemechanismsmaynotexist.Monitoringcontractsplayacrucialroleinaddressing suchattacks.However,itisimportanttonotethatidentifyingvulnerabilitiesanddeployingmonitoringcontractsalone areinsufficientforeffectivesmartcontractdefenses.Therepairofvulnerablesmartcontractsisalsoakeytechnology inthedefenseprocess[109,132].Whiledefenseencompassesabroaderrangeofstrategiesandmeasures,repairserves asaspecificactiontofixoraddressvulnerabilities.Thefollowingsectionprovidesadetaileddescriptionofthedefense methodologiesinvolved. 5.1 ContractAnalyzer Contractanalyzersplayacrucialroleinreducingtheriskofvulnerabilitiesinsmartcontractsbeforetheirdeployment. Researchersemployvariousmethodologiestoanalyzesmartcontracts,manyofwhicharepubliclyavailableunder open-sourcelicenses.Therearefivecommonmethodologiesforsmartcontractanalysis,suchasformalverification, symbolicexecution,fuzzing,intermediaterepresentation,andmachinelearning. 5.1.1 FormalVerification. Itisamathematical-basedtechniquetobuildandcheckformalproofsthatsatisfyaparticular property.Formalverificationisappliedtoensurethatsoftwarebehavesandperformsasexpectedinitsspecifications andrequirementsbasedonlargereachablestatespaces.Smartcontractsareoftenwritteninprogramminglanguages thatareamenabletoformalverification[56,66].Forexample,theSolidityprogramminglanguageusedforEthereum smartcontractshasawell-definedsyntaxandsemanticsthatcanbepreciselymodeledandverified.Forsmartcontracts, wedistinguishmainlytwofamiliesofformalverificationmethods,namelymodelcheckingandtheoremproving. ModelcheckingItlistsallpossiblestatesandchecksthemindividuallytoconfirmwhetherthecontracthasthe correspondingcharacteristic.Comparedtootherprograms,smartcontractshavesomeuniquecharacteristicsthat makemodelcheckingparticularlywell-suitedforvulnerabilitydetection[1,3,38,48].First,modelcheckingismost effectiveonsystemswithafinitenumberofstates,andsmartcontractsareoftensmallenoughtobemodeledintheir entirety.Second,smartcontractsareoftendesignedtobedeterministic,whichmakesiteasiertoconstructformal modelstoaccuratelycapturetheirbehavior.Thistechniqueisrelevanttocheckpartialspecificationsearlyinthedesign process[88].Modelcheckers,suchasSIPN[16],FDR[104],andNuSMV[88],areutilizedtosuccessfullyverifythe correctnessandnecessarypropertiesofsmartcontracts[104].Modelcheckingistypicallyusedtodetectspecifictypes ofvulnerabilities,suchasbufferoverflowsorintegeroverflows. TheoremprovingItisatechniquethatdescribesthedesiredpropertiesofasystemusingmathematicallogicand usesatheoremprovertogenerateproofsthatverifythesepropertiesbasedonevidencerules.Inthecontextofsmart contracts,theoremprovingisusedtoensurethatacontractsatisfiesaspecificsetofproperties,suchascorrectness, safety,orliveness.Sincesmartcontractsaretypicallydeterministic,theoremprovingcanconstructmathematicalproofs todemonstratethesatisfactionoftheseproperties.Unlikemodelchecking,whichislimitedtofinitesystems,theorem provingcanhandletheverificationofinfinitesystems.Thismakesitwell-suitedforanalyzingsmartcontractsthatmay involvecomplexinteractionsandpotentialinfinitebehaviors. Severaltheoremprovers,suchasCoqandIsabelle/HOL,havebeendevelopedtoprovideformalsemanticsand supportthetheorem-provingprocessforsmartcontracts.Forinstance,Amanietal.extendedtheexistingdefinitionof theEthereumVirtualMachine(EVM)intoIsabelle/HOLwiththeconsiderationofgas,allowingforformalverification ofEVM-basedsmartcontracts.However,it’sworthnotingthatformalverificationthroughtheoremprovingisa semi-automatedprocess thatoftenrequiresmanualinteraction. It iscommonlyused todetectbroaderclassesof vulnerabilities,includinglogicerrorsanddesignflaws,ratherthanspecificinstancesofvulnerabilities. ManuscriptsubmittedtoACM24 Weietal. 5.1.2 SymbolicExecution. Itsystematicallyexploresmorepossibleexecutionpathssimultaneouslytotriggerdeep programerrors.Thisapproachdoesnotrequireaspecifiedinputvaluebutabstractstheinputvaluesintosymbols. Fromthevulnerabilitydetectionperspective,symbolicexecutionoffersdevelopersspecificinputtothetriggered vulnerability,whichcanbeusedtoconfirmordebug.Symbolicexecutionhastheadvantageofachievinghightest coveragewithasfewtestcasesaspossible,therebydiggingoutdeepprogramerrors.Moreover,symbolicexecutionis oftencombinedwithconstraintsolvingtoreasonwhetheranexecutionpathisreachable.However,whentheprogram islargeandcomplex,symbolicexecutionwillgeneratetoomanypathswhichmayleadtopathexplosion.Asmart
contractcanbeamaximumof24KBoritwillrunoutofgas[25].Therefore,symbolicexecutionisperhapsthemost popularapproachforsmartcontracts.Moreover,Z3SMTsolversareusedtocheckwhichpathsareflexible. Oyente[80]wasthefirstattemptforsmartcontractverification,usingaControlFlowGraph(CFG)representation ofthebytecodetoidentifyvulnerabilitiesliketransaction-orderingdependence,timestampdependence,mishandled exceptionsandreentrancy.Othertools,likeManticoreandMaian,haveextendedthecapabilitiesofsymbolicexecution todetectadditionalvulnerabilitiessuchasarithmeticoverflow/underflow,unsafesuicide,anduncheckedsend.However, scalabilityisaconcernwithsymbolicexecution,especiallyincomplexapplicationscenarios.Theexplorationofdeep programpathscanbeslowandresource-intensive. 5.1.3 Fuzzing. Itisasoftwaretestingtechniquethatinvolvesexecutingtargetprogramswithalargenumberof abnormalorrandomtestcasestodetectvulnerabilities.Ithasgainedsignificantattentioninbothindustryandacademia [58,76]duetoitssimplicityandpracticaleffectivenessinidentifyingsoftwarevulnerabilities.Majorsoftwarevendors likeGoogle[113]andMicrosoft[85]employfuzzingtechniquestouncovervulnerabilitiesintheirproducts. Inthecontextofsmartcontracts,fuzzinghasbeenutilizedasameansofvulnerabilitydetection,althoughthereare relativelyfewerworksspecificallyfocusedonsmartcontractfuzzinginrecentyears.ContractFuzzer[65],forexample, usestheApplicationBinaryInterface(ABI)specificationofcontractsasinputforfuzzingtodetectvulnerabilities.It reliesonuser-providedinputseeds.Echidna[51],ontheotherhand,usesfalsifieduser-definedpredicatesorSolidity assertionsasinputseeds,whicharethensubjectedtogrammar-basedfuzzingtodetectvulnerabilities.Harvey[140] incorporatesapredictioncomponenttogeneratenewinputseedsforgrayboxfuzzing.sFUZZ[90]adoptsanadaptive strategytoselectinputseeds,whicharethenfedintotheprominentfuzzerAFL(AmericanFuzzyLop).However,these methodsaremoreeffectiveinfindingshallowbugsandlesseffectiveinidentifyingbugsthatliedeepintheexecution flow. Thislimitationisduetotheheavyrelianceoninputseedsinfuzzing.Analternativeapproachthathasshown promisingresultsintraditionalprogramsishybridfuzzing,whichcombinesfuzzingwithsymbolicexecution.ILF (ImitationLearningFuzzer)[58]addressesthislimitationbyusingasymbolicexecutionexperttogeneratealarge numberoftrainingsequences,whicharethenfedintoimitationlearningpriortofuzzing.ILFachievesimproved coverageandperformswellonbothlargeandsmallcontracts.However,ILFislimitedtothecontractsusedforimitation learninginitstrainingphase.ConFuzzius[131],ontheotherhand,leverageslightweightsymbolicexecutiontoanalyze executiontracesandemploysaconstraintsolvertoobtaininputseedsforthefuzzer.Thisapproachenhancesthe effectivenessoffuzzingbyincorporatingsymbolicexecution-basedanalysis.Bycombiningfuzzingwithsymbolic executionorothercomplementarytechniques,researchersaimtoenhancetheeffectivenessofvulnerabilitydetection insmartcontracts,addressingbothshallowanddeepvulnerabilities. 5.1.4 IntermediateRepresentation. Toaccuratelyanalyzesmartcontracts,someresearchersalsoexploreconverting contractsintoanintermediaterepresentation(IR)withhighlysemanticinformation,whichismoresuitableforthe ManuscriptsubmittedtoACMSurveyonQualityAssuranceofSmartContracts 25 analysisanddetectionofcommonsecurityissues.Differentfromformalverification,IRreliesonsemantic-based transformation.Theanalysisprocesscanbedividedintofourstages:lexicalanalysis,syntaxanalysis,semanticanalysis, andtransformation.ThelexicalanalysisusesScannertocheckwhethertheinputcodeisacombinationofseveral legitimatewords;thesyntaxanalyzercheckswhetherthecombinationoftheselegitimatewordsmeetsgrammatical rules;semanticanalysischeckswhethersemanticsarereasonable;thetransformerconvertssourcecodeorbytecode intomachinecode,suchasXML.Then,theanalyzerdetectsvulnerabilitiesthroughspecificmethods. Slither[44]transfercontractstoitsinternalrepresentationlanguage(SlithIR)whichusesStaticSingleAssignment (SSA)formtofacilitatethecomputationofcodeanalyses.EthIR[7]basedonOyentetranslatesCFGstoarule-based representation(RBR)ofthebytecode.Smartcheck[127]directlytranslatessourcecodeintoanXML-basedIRandthen checksitagainstXPathpatterns.MadMax[50]basedontheVandal[24]decompilertranslatesEVMbytecodetoa structuredIRtocheckgas-relatedVulnerabilities.NeuCheck[79]employstheSolidityparserANTLRtocompletethe transformationfromsourcecodetoanIR(XMLparsetree). However,therearetwochallengesinIRanalysis:(1)Becauseofsemanticheterogeneity,itisunavoidabletoproduce semanticmissingduringthesecurityanalysis.(2)Comparedwithotheranalysismethodologies,IRtakesmoreprocessing time. 5.1.5 MachineLearning. Machinelearningdemonstratedsignificantpotentialinprogramsecurity,oftenoutperforming traditionalmethodsinvariousaspects[27,55,117].Unliketraditionalmethods,machinelearningcombinesstatic analysisanddynamicdetection.Thiscombinationaddressesthehighfalsenegativerateofstaticanalysisandthelow codecoverageofdynamicanalysis.Furthermore,machinelearningexhibitsexcellentscalabilityandadaptabilityto novelvulnerabilities.
Several prior works have employed machine learning techniques to analyze smart contracts. Tann et al. [126] introducedalongshort-termmemory(LSTM)[117]modeltohandlethesemanticrepresentationsofsmartcontract opcodetodetectcontractsecuritythreats.Theirmodelcanachievehigherdetectionaccuracythansymbolicexecution analyzerMaian[92],wherebotharebasedonthesamevulnerabilitiestaxonomy.Qianetal.[103]appliedabi-directional longshort-termmemorywithattentionmechanism(BLSTM-ATT)intheirsequentialmodeltoreentrancydetection. This framework converts source code into contract snippets and feeds the sequential model with feature vector representationsparsedfromthesesnippets. Zhuangetal.[149]proposedadegree-freegraphconvolutionalneuralnetwork(DR-GCN)andanoveltemporal messagepropagationnetwork(TMP)forvulnerabilitydetection.Intheirapproach,thesourcecodeofacontractis convertedtoacontractedgraph,whichisthennormalizedthroughanodeeliminationprocess.Thenormalizedgraphs arefedtoDR-GCNandTMPforvulnerabilitymodelinganddetection.ContractWard[137]trainsitsmachinelearning modelusingbigramfeaturesextractedfromtheopcodesofthecompiledsmartcontract. SmartMixModel[114]extractshigh-levelsyntacticfeaturesfromsourcecodeaswellaslow-levelbytecodefeatures fromthesmartcontract.Andthenthesefeaturesaretrainedonamachinelearningmodelanddeeplearningmodel todetectvulnerabilities.ESCORT[112]introducesadeeplearning-basedmethodforvulnerabilitydetectioninsmart contracts,combinedwithdistinctbranchesforlearningspecificfeaturesofvariousvulnerabilitytypes.Whenanew vulnerabilitytypeisidentified,ESCORTseamlesslyintegratesanewbranchintotheexistingfeatureextractorand trainsitwithminimaldata. Inadditiontothesemethods,someresearcherssuggestthatcombiningmachinelearningwithfuzzingcouldenhance detectionefficiency.SoliAudit[77]employsmachinelearningtodetectknownvulnerabilitieswithouttheneedfor ManuscriptsubmittedtoACM26 Weietal. expertknowledgeorpredefinedpatterns,whilefuzzingisusedtoidentifypotentialweaknesses.Althoughthereisno directcorrelationbetweenthetwomethods,fuzzingcomplementsmachinelearninginvulnerabilitydetection.ILF[58] utilizesanimitationlearningmodeltodevelopafuzzerfromtrainingsequences,demonstratinganotherinnovative approachtoenhancingvulnerabilitydetectionthroughmachinelearningandfuzzing. Recentstudieshaveexploredthepotentialoflargelanguagemodels(LLMs)inenhancingsoftwaresecurity,leveraging theircapabilitiesincodecomprehension,generation,andanalysis.Researcheshavedemonstratedtheeffectivenessof LLMsinidentifyingvulnerabilities,verifyingcompliance,andassessinglogicalcorrectness.Chenetal.[34]demonstrated thatLLMs(GPT-2,T5)trainedonahigh-qualitydatasetof18,945vulnerableC/C++functionsoutperformedother machinelearningmethods,includingGraphNeuralNetworks,invulnerabilityprediction. TheapplicationofLLMstosmartcontractsecurityhasgainedsignificantattention.Davidetal.[40]investigatedthe utilityofLLMs,likeGPT-4andClaude,inconductingsecurityauditsofDeFismartcontracts.Chenetal.[29]conducted acomparativeanalysisofGPT’sperformanceinidentifyingsmartcontractvulnerabilitiesagainstotherestablished tools,utilizingapubliclyaccessibledataset.Sunetal.[123]testedGPT’sabilitytomatchcandidatevulnerabilitiesusing abinaryresponseformat,whereGPTrespondswith‘Yes’or‘No’topotentialmatcheswithpredefinedscenarios.They alsohighlightedpotentialfalsepositivesduetoGPT’sinherentlimitations.Shouetal.[115]integratedtheLlama-2 modelintothefuzzingprocesstodetectvulnerabilitiesinsmartcontracts,aimingtoaddressinefficienciesintraditional fuzzingmethods.Sunetal.[122]comparedopen-sourcelanguagemodelslikeMixtralandCodeLlamaagainstGPT-4 forsmartcontractvulnerabilitydetection.TheyfoundthatGPT-4,leveragingitsadvancedAssistants’functionalities, significantlyoutperformedopen-sourcealternatives. 5.2 SecurityEnhancement Beforedeployment,somemeasurescanbedonetoenforcethesecurityofsmartcontracts.Gasanddataarethemost importantfactorsforsmartcontracts.Thus,ifgascostanddataprivacyhavebeencarefullycheckedbeforebeing deployed,thesecurityofsmartcontractswillbeenhanced.Therearesomemethodsandtoolsforgascostanddata privacy. 5.2.1 GasEstimationandOptimization. GasisoneofthemostimportantmechanismsinEVMforassigningacostto theexecutionofaninstruction.Thismechanismcaneffectivelypreventresourceabuse(especiallyDoSattack)and avoid“infinite"loops[33].Whenissuingatransaction,thesenderneedstospecifyagaslimitandagaspricebefore submittingittothenetwork. GasrepresentsmuchmorethanjustthecostofprocessingtransactionsontheEthereumnetwork.Itenablessmart contractstorunvariousapplications,formingadecentralizedweb.Thus,whilegascouldtechnicallybedescribedas "transactionfees,"thistermshouldbeusedwithcaution.Severalgas-relatedvulnerabilitiesexist,asdiscussedinSection 3.Ifatransactionrunsoutofgasduringexecution,theEVMthrowsanexception,immediatelyrevertingtothestate beforeexecutionandconsumingallthegasprovidedbythesender.
Topreventrunningoutofgas,manyEthereumwallets,suchasMetamask[84],canstaticallyestimatethecostofa transactionbeforeitisexecuted.However,therearemanyoperationsthataredifficulttoestimateduringexecutions.In ordertoaddressthisproblem,someresearchersproposedsomemethodsthatestimategasandoptimizesmartcontracts [8,12,39]. Albertetal.[8]proposedanautomaticgasanalyzerGastapthatinfersgasupperboundsforallitspublicfunctions. Gastaprequirescomplextransformationandanalysisofthesourcecodethatincludesseveralkeytechniques,including ManuscriptsubmittedtoACMSurveyonQualityAssuranceofSmartContracts 27 Oyente[80],EthIR[7],Saco[4]andPubs[5].Gasol[6],anextensionofGastap,introducesanautomaticoptimization oftheselectedfunctionthatreducesinefficientgasconsumption. Lietal.[32]developedaGasCheckertoolthatidentifiesthegas-inefficientcodeofsmartcontracts.Theysummarized tengas-inefficientprogrammingpatternsthatassistedusersinbettertailoringcontractstoavoidgaswaste.GasGauge [87]canautomaticallyestimatethegascostforthetargetfunctionandtheloop-boundthreshold.Besides,GasGauge canfindalltheloopsandfurnishthegas-relatedinstancestohelpdeveloperswithsuggestions.Lietal.[74]estimated thegasfornewtransactionsbylearningtherelationshipbetweenhistoricaltransactiontracesandtheirgascosts. 5.2.2 DataPrivacy-Preserving. Inadditiontogasconcerns,anothermajorconcernforthesmartcontractisprivate data[69].Sincetheopennessandtransparencyofpublicblockchains,theprivacyoverlayfeatureonthechainisabsent. Thisnotonlyleadstosomesecurityissuesbutalsopreventstheirwideradoption.Itisproblematicforapplicationsthat handlesensitivedatasuchasvotingschemes[83],electronicmedicalrecords[78],orcrowdsensing[97]. Apromisingapproachtohandlingprivatedatainvolvesdesigningnewblockchaininfrastructureswithbuilt-in privacysupport[72].Severalproposedblockchaininfrastructures,includingHawk[72],Arbitrum[69],Ekiden[35], andTownCrier[142],supportprivatedatathroughtrustedthird-partymechanisms.Hawk[72]enablesprogrammers towriteprivatesmartcontractswithoutspecializedknowledgeandgeneratesefficientcryptographicprotocolsfor inter-partyinteractions.Arbitrum[69]facilitatesprivatesmartcontractcreationbyemulatingavirtualmachine (VM)andenableshonestpartiestoupdatetheVMstateon-chain.BothHawkandArbitrumutilizetrustedmanagers, implementablethroughtrustedcomputinghardwareormulti-partycomputationamongusers.Ekiden[35]processes smartcontractswithprivatedataoff-chainintrustedexecutionenvironments(TEEs),whileensuringsecureon-chain interactionsbetweencontracts. Analternativeapproachinvolvesusingcryptographicprimitives,particularlyzero-knowledgeproofs.Hawk[72] employszero-knowledgeproofstoensurecorrectcontractexecutionandmaintainmoneyconservationon-chain. Steffenetal.introducedzkaycontracts,whichincorporateprivatedataprotectedbynon-interactivezero-knowledge (NIZK)proofs[119].Forenhancedblockchainexecutability,zkaycontractsaretransformedintoequivalentcontracts thatmaintainprivacyandfunctionality.Zapper[120]utilizesNIZKproofsforprivatestateupdatesandemploysan obliviousMerkletreetoconcealsenderandreceiveridentities. 5.3 RuntimeMonitoring Thecapabilitytodeploysmartcontractsisoneofthemostimportantfeaturesofblockchains.Oncedeployedona blockchain,smartcontractsbecomeimmutable,includinganyvulnerabilitiestheymayhave.Whiletoolsareavailable forscanningsmartcontractspriortodeployment,theyoftenhavelimitedscopesandmaynotdetectallvulnerabilities, leavingroomforunknownruntimeattacks.Asasolutiontoenhancethesecurityofpost-deploymentsmartcontracts, runtimemonitoringtechniqueshaveemerged.Thesetechniquesanalyzeandmonitortheruntimebehaviorofsmart contracts,providinghighercoverageandprecisionindetectingattackscomparedtopre-deploymentanalysisalone[42]. Runtimemonitoringleveragesreal-timeinformationduringtheexecutionofsmartcontracts,enablingthedetectionof vulnerabilitiesandmaliciousactivitiesthatmayoccuratruntime.Itcanbecategorizedintotwomaintypesbasedon thedetectiontarget:transactionmonitoringandstatemonitoring. 5.3.1 TransactionsMonitoring. AsEthereumcanbeseenasatransaction-basedstatemachine,atransactioncontains muchinformationaimingtochangetheblockchainstate.Thistransactioninformationcanalsobeusedtodetectand preventattacks. ManuscriptsubmittedtoACM28 Weietal. ECFChecker [52] is the first dynamic detection tool designed to identify transactions that include reentrancy vulnerabilities.Itexaminestransactionstodetermineiftheyexhibitthecharacteristicsofareentrancyattack,wherea contractcanbecalledrecursivelybeforepreviousinvocationshavebeencompleted.Sereum[108],ontheotherhand, aimstopreventreentrancyattacksbyemployingtainttrackingtechniques.Ittrackstheflowofdatafromstorage variablestocontrol-flowdecisions,helpingidentifypotentialvulnerabilities[31,62].BothECFCheckerandSereum relyonmodifiedversionsoftheEthereumVirtualMachineandprimarilyfocusondetectingreentrancyattacks. Incontrast,ÆGIS[129]takesabroaderapproachbyprovidinganextensibleframeworkfordetectingnewvulner-
abilitiesinsmartcontracts.Itmaintainsattackpatternsandrevertstransactionsthatmatchthesepatterns,thereby enhancingsecurity.Theframeworkallowsforthestorageandvotingofnewattackpatternsthroughasmartcontract, enablingthecommunitytoactivelycontributetothedetectionandpreventionofnovelattacks. SODA[31],isbasedonamodifiedEVM-basedclientandprovidesaplatformfordevelopingvariousapplicationsto detectmalicioustransactionsinrealtime.Itoffersflexibilityandextensibilityincreatingonlineappsformonitoring andidentifyingpotentiallyharmfultransactions.SODAhasbeenintegratedintopopularblockchainsthatsupportthe EVM,increasingitsaccessibilityandusability.Horus[146]leveragestransactiongraph-basedanalysistoidentifythe flowofstolenassets.Byexaminingthetransactiongraph,Horuscantracethemovementofassetsanddetectpotential theftorunauthorizedtransfers. 5.3.2 StateMonitoring. Inadditiontotransactions,blockchainstatevariablescanprovidevaluableinformationabout thereal-timestatusofasmartcontract.Monitoringandanalyzingthestatevariablescanbeaneffectiveapproachto detectandpreventattacks. Solythesis[73]allowsuserstoinstrumentuser-specifiedinvariantsintosmartcontractcode.Theseinvariants represent specific conditions that should always hold true during the execution of the contract. By tracking the transactionsthatviolatetheseinvariants,Solythesiscanefficientlyenforcepowerfulmonitoringofthecontract’sstate. Thisapproachhelpsidentifyabnormalorunexpectedchangesinthestatevariablesandallowsforproactivedetection ofpotentialvulnerabilities. ContractGuard[138]takesasimilarapproachbutintroducestheconceptofanintrusiondetectionsystem(IDS)to monitorthebehaviorofadeployedsmartcontract.TheIDScontinuouslymonitorsthestatevariablesandlooksfor abnormalorsuspiciousbehaviorsthatdeviatefromexpectedpatterns.Ifanabnormalstateisdetected,ContractGuard canrollbackallthechangestothecontractstateandnotifytherelevantusersaboutthepotentialintrusion. 5.4 Post-deploymentRepair Ideally,smartcontractsshouldbedeployedwiththehighestpossiblelevelofsecurity.However,thispresentsachallenge notonlyforsmartcontractsbutalsoforallsoftwareprograms.Furthermore,theunderlyingblockchaintechnology ensuresimmutability,meaningthatthepastcannotbealtered.Consequently,updatingthecodeofadeployedcontract oraddressingvulnerabilitiesbecomesunfeasible.Apartfromfixingvulnerabilities,therearenumerousotherreasonsto modifycontractcode,includingadaptingbusinesslogicorenhancingfunctionality. 5.4.1 ContractMigration. Inmanycases,eployinganewinstanceofthecontractandmigratingtheoldcontract’sdata toitisaviableapproach.Thisprocess,knownascontractmigration,hasbeensuccessfullyimplementedinvarious tokenmigrationevents,suchasAugur,VeChainThor,andTRON. Atypicalcontractmigrationprocessinvolvestwomainsteps:datarecoveryanddatawriting[68].Duringdata recovery,datafromtheoldcontractisextracted,includingbothpublicandprivatevariables.Whileretrievingpublic ManuscriptsubmittedtoACMSurveyonQualityAssuranceofSmartContracts 29 method_call before upgrade Proxy Contract Logic Contract V1 UI or frontend returndata (Storage Layer) (Logic Layer) Stores address of the logic contract after upgrade Logic Contract V2 (Logic Layer) Fig.9. Contractupgradewithproxy variablesisrelativelystraightforward,handlingprivatevariablesandmappingscanbemorecomplex,requiringspecial measurestoensuredataintegrityandconsistency. Toaddressthechallengesofdatamigration,somedevelopersuseseparatecontractstostoreandmanagedata[9]. Thisapproachsimplifiesthemigrationprocessbyseparatingthelogicfromdatastorage.Bymigratingthelogictoa newcontractwhilekeepingthedatainaseparatecontract,themigrationbecomesmoremanageable.It’simportant tonotethatcontractmigrationprocedurescanbecostly,especiallyfortoken-basedcontractswithalargenumberof accounts[68].Migratingdataformanyaccountsrequirescarefulplanningandexecutiontoavoidpotentialissuesand ensuretheaccuracyandsecurityofthemigrateddata. 5.4.2 UpgradableSmartContracts. Upgradablecontractsofferanotherpromisingapproachtomodifyingsmartcontract code[67].Thismethodincorporatesanupgradabilitymechanismintosmartcontracts,enablingseamlessupgrades withouttheneedfordatamigrationorupdatingexternalreferences. Anupgradablesmartcontractcanbeimplementedusingaproxypatternarchitecture.Inthisarchitecture,asingle contractisdividedintotwoseparatecontracts:oneforlogicexecutionandanotherfordatastorage,asillustratedin Figure9.Thelogiccontractdoesnotstoreanystatebutimplementsallbusinesslogic,whiletheproxycontractholdsall fundsandinternalstateswithoutimplementinganybusinesslogic.Thisseparationallowsforquickandcost-effective upgradesbymodifyingorreplacingonlythelogiccontract,whiletheproxycontractremainsintact,maintainingall existingdataandexternalreferences.Thisensuresseamlessupgradeswithoutdisruptingthecontract’sfunctionality. Severalapproacheshavebeenproposedforimplementingupgradablecontracts.Zeppelin[9]introducedthreeproxy patternarchitectures:inheritedstorage,eternalstorage,andunstructuredstorage.Thesepatternsarecollectivelyknown asdelegate-proxypatternsbecausetheyrelyontheDELEGATECALLinstruction.Basedonthisconcept,EVMPatch [109]usesaproxypatterntofacilitatequickandcost-effectivesmartcontractupgrades.Itprovidesaframeworkfor
patchingvulnerabilitiesoraddingnewfeaturestodeployedcontractswithoutrequiringdatamigrationordisrupting thecontract’sfunctionality. Despitetheirbenefits,upgradablesmartcontractsposenotablesecuritychallenges.Theynecessitateextensive securityknowledgeforsecureimplementationandcanbeexploitedformaliciouspurposes.Tosolvethisissue,Bodell etal.[22]developacompletetaxonomytocomprehensivelycharacterizetheuniquebehaviorsofupgradablesmart contracts. ManuscriptsubmittedtoACM30 Weietal. Fig.10. TrendsinMethodUsageOvertheYears 5.5 EvolvingTrendsinContractAnalyzerUsage Smartcontractanalyzers,astheprimarystrategyforidentifyingvulnerabilitiesinsmartcontracts,havebeenextensively studiedbyresearchers.AsdiscussedinSection5.1,therearefivecommonmethodologiesforsmartcontractanalysis. Theutilizationofthesetechniqueshasvariedsignificantlyovertime. Figure10illustratesasignificantshiftinmethodusagetrendsafter2021.Before2021,methodslikeFormalVerification, SymbolicExecution,andFuzzingshowedsteadyorincreasingusage,peakingbetween2018and2020.Post-2021,however, thesemethodsexperiencedanotabledecline,indicatingadecreaseintheiradoptionorrelevance.FormalVerification andSymbolicExecution,oncewidelyadopted,showedamarkeddecrease,suggestingashiftinresearchfocusor industrypractices.Fuzzingexhibitedasimilartrend,peakingaround2020beforedeclining.IntermediateRepresentation (IR),despiteitsrelativelystableusage,alsodeclinedpost-2021,reinforcingthegeneraldownwardtrendacrossmost methods. Ontheotherhand,MachineLearningstandsoutasanexceptiontothistrend.WhileMachineLearninghadfluctuating usageinearlieryears,itsrelevancesurgeddramaticallyin2023,reflectingitsgrowingimportanceandwidespread applicationincontemporaryfields.TheboostofMachineLearningalsorevealsthatmoreandmoreresearchersare payingattentiontosmartcontractsecurity,leveragingadvancedtechniquestoaddressemergingchallenges. Thissectionhasprovidedacomprehensiveexaminationandcategorizationofdefensemethodologiesdesignedto preventormitigatesmartcontractattacks.ThesefindingsofferacomprehensiveresponsetoRQ3,asdefinedinSection 2.2.However,thereisanotablelackofempiricalevidencetoevaluatetheeffectivenessofthesemethodologiesand theirassociatedtools.Despiteclaimsofsuperiority,empiricalstudiesarenecessarytodeterminewhichmethodsare practicalandbeneficialinreal-worldapplications. 6 EVALUATION ThisstudyaimstoprovideacomprehensiveoverviewofSOTAautomatedanalysistoolsavailableforsmartcontracts. Giventhatthefieldofsmartcontractanalysisisrelativelynewandrapidlyevolving,itcanbechallengingtostay updatedwiththelatestdevelopmentsandunderstandthestrengthsandlimitationsofexistingtools.Therefore,we haveconductedanextensivereviewoftheliteratureandwebsitestocompilealistofthemostpromisinganalysis toolsforsmartcontracts.ToaddressRQ4andRQ5,whichfocusonevaluatingtheperformanceofexistingtools,we ManuscriptsubmittedtoACMSurveyonQualityAssuranceofSmartContracts 31 proposeasystematicevaluationapproachthatinvolvesselectingappropriatetools,utilizingdatasetsofsmartcontracts, definingcriteriafortheassessment,andconductingexperiments. 6.1 ExperimentalSettings 6.1.1 ToolSelection. Vulnerabilitydetectiontoolsarewidelyemployedtoassistdevelopersinidentifyingvulnerabilities withinsmartcontracts.Numerousanalysistoolshasbeendevelopedforthispurpose.Wehavecompiledalistof169such toolsbasedonacademicliteratureandonlinesources.Thecompiledlist,includingkeypropertiessuchaspublication venue,methodology,inputtype,open-sourcerepository,andvulnerabilityidentifier,isavailableinacomprehensive table5. Fortoolselectioninourcomparativeanalysis,weappliedfourcriteria: • Available:Thetoolmustbepubliclyavailableandaccessiblefordownloadorrunningwithacommandlineinterface (CLI). • Functionality:Thetoolmustbedesignedforsmartcontractsandcapableofdetectingvulnerabilities.Thisexcludes toolsthatonlyconstructartifactslikecontrolflowgraphs. • Compatibility:Thetoolmustoperateonthesourcecodeofthesmartcontract,excludingthosethatonlyconsider EVMbytecode. • Documentation:Thetoolmustprovidecomprehensivedocumentationanduserguides. Applicationofthesecriteriatoourcomprehensivetoollistresultedintheidentificationof14toolsmeetingall requirements:ConFuzzius[131],Conkas[47],Maian[92],Manticore[86],Mythril[41],Osiris[133],Oyente[80], Securify[23],sfuzz[90],Slither[45],Smartcheck[127],solhint[101],GPT-4o[2],andMeta-Llama-3.1-8b[135]. 6.1.2 BenchmarkingDataset. Akeyissuewhenevaluatinganalysistoolsisobtainingasufficientnumberofvulnerable smartcontracts.Despitetheavailabilityofnumerousopen-sourceanalysistools,comparingandreproducingresults canbechallengingduetothelackofpubliclyavailabledatasets.Mostanalysistoolsprimarilycheckforonlysomeof thewell-knownEthereumsmartcontractvulnerabilities.Toevaluatetheeffectivenessofanyanalysistool,establishing astandardbenchmarkiscrucial.Whileseveralresearchershavepublishedtheirdatasets[41,49,131],theseoftenhave limitationssuchassmallsamplesizesoranunevendistributionofvulnerablecontracts. Toaddresstheselimitations,wehavecompiledanextensive,annotateddatasetcomprising110distinctsmartcontract
testcases.Thesecasesarecategorizedinto11sub-datasets:10sub-datasetscontainknownvulnerabilitiescorresponding tothetop10vulnerabilitycategoriesmentionedinSection3,andonesub-datasetrepresentssafecontracts. Theselectionofthesecontractswascarefullycuratedtocoverabroadspectrumofcodecomplexitiesandapplication scenarios,ensuringacomprehensivebenchmarkfortoolevaluation.Ourbenchmarkdatasetispubliclyavailableon GitHubforcommunityuseandfurtherresearchdevelopment6. 6.1.3 EvaluationCriteria. Tosystematicallyandobjectivelyassessthequalityofselectedsmartcontractanalysistools, wedevelopedasetofevaluationcriteriabasedontheinternationallyrecognizedISO/IEC25010standard.Thisstandard offersacomprehensiveframeworkforsoftwareproductqualityassessment,focusingoneightkeycharacteristics.For ourstudy,wetailoredthesecharacteristicstothespecificrequirementsofsmartcontractanalysis,concentratingonfour 5https://github.com/WeiZ-boot/survey-on-smart-contract-vulnerability 6https://github.com/WeiZ-boot/Smartcontract-benchmark ManuscriptsubmittedtoACM32 Weietal. ofthemostrelevantaspects:detectionsuitability(functionalsuitability),resourceEfficiency(performanceefficiency), versioncompatibility(compatibility),andcategorycoverage(usability). • DetectionSuitability:Thiscriterionevaluateswhethertheanalysistoolsmeetthefunctionalrequirementsspecified byusers,primarilyfocusingontheirabilitytodetectvulnerabilitiesinsmartcontracts.Itassessesthetools’capability toidentifypotentialsecurityissueswithincontractcode.Thesuitabilityofdetectionencompassesvariousaspects: accuracy,precision,recall,andadaptability. • ResourceEfficiency:Thisaspectassesseswhetherasoftwareproductcaneffectivelymakeuseofgivenresources. Inthecontextofourstudy,thisisquantifiedbyexaminingtheexecutiontimerequiredbyvarioussmartcontract analysistools.Efficientperformanceiscrucialforpracticalapplicability,especiallywhendealingwithlargevolumes ofcontracts. • VersionCompatibility:Thiscriterionconcernswhetherasoftwareproductcanconsistentlyperformitsfunctions whileexchanging.Inourstudy,weexaminesthetools’abilitytofunctionconsistentlyacrossdifferentversionsof theSolidityprogramminglanguage.GiventhefrequentupdatesandchangesinSolidity,highcompatibilityensures broaderapplicabilityandlongevityofthetools. • CategoryCoverage:Thisaspectevaluateswhetheruserscaneffectivelyandefficientlyuseasoftwareproductto completetasks.Inourstudy,wemeasurethetools’abilitytocoverawiderangeofvulnerabilitytypes.Atoolwith extensivecategorycoverageismoreusefultousers,asitenablesthedetectionofvariousvulnerabilitieswithina contract,therebyenhancingoverallusability. Tofurtherelaborate,detectionsuitabilitycanbeseenasabinaryclassificationproblem.Theprimaryobjectiveofthe assessmenttoolistoaccuratelydeterminethepresenceorabsenceofspecificvulnerabilitiesinasmartcontract.This binaryclassificationmethodsimplifiestheevaluationmethodologyandprovidesaneffectivemeasureofthetool’s precisioninvulnerabilityidentification.Theclassificationoutcomesarecategorizedintofourdistinctgroups: • TruePositive(TP):Toolcorrectlyidentifiesavulnerabilityinacontractwhenitactuallyexists. • FalsePositive(FP):Toolincorrectlyidentifiesavulnerabilityinacontractwhennoneexist. • FalseNegative(FN):Toolfailstoidentifyavulnerabilitywhenoneactuallyexists. • TrueNegative(TN):Toolcorrectlyidentifiesthatacontractdoesnothaveavulnerabilitywhenitdoesnot. Toevaluatetool’sdetectioneffectiveness,weemploythreekeymetrics:Precision,whichistheratiooftruepositive resultstoallpositiveresultspredictedbythetool(Precision=TP/(TP+FP));Recallrates,whichistheratiooftrue positiveresultstoallactualpositivecases(Recall=TP/(TP+FN));andF1-score,whichistheharmonicmeanof PrecisionandRecall(F1=(2*Precision*Recall)/(Precision+Recall)). 6.1.4 HardwareConfiguration. Weobtainedthemostrecentversionsoftheselectedanalysistoolsfromtheirrespective publicGitHubrepositories,exceptforversion0.3.4oftheManticoretool.ThetoolswereexecutedonanAliyun-hosted Ubuntu22.04LTSmachine,configuredwithanIntel(R)Core(TM)i5-13400CPUand32GBofRAM.Additionally,for languagemodelvalidation,wemaintainedconsistencybyusingthesameNVIDIAA10GPUswith24GBofVRAM. 6.2 ExperimentalResults 6.2.1 DetectionSuitability. Wefirstmeasurethedetectioneffectivenessoftheselectedtoolsinidentifyingvulnerabilities. Wetesttheselectedtoolsonourbenchmark,andtheresultsaresummarizedinTable4.Thistablepresentsanoverview ManuscriptsubmittedtoACMSurveyonQualityAssuranceofSmartContracts 33 Table4. ComparativeAnalysisofVulnerabilityDetectionAccuracyAcrossSmartContractDetectionTools Category suizzuFnoC saknoC naiaM erocitnaM lirhtyM sirisO etneyO yfiruceS zzuFs rehtilS kcehctramS tnihlos o4-TPG b8-1.3-amalL Reentrancy 9 10 0 8 9 7 7 8 6 9 8 0 10 9 Arithmetic 7 9 0 7 7 9 9 0 6 0 1 0 10 10 GaslessSend 0 0 0 0 0 0 0 0 3 0 7 0 5 2 UnsafeSuicide 4 0 4 0 3 0 0 0 0 6 0 4 9 9 UnsafeDelegatecall 1 0 0 4 6 0 0 0 5 7 0 0 9 10
UncheckedSend 9 10 0 2 9 0 0 0 0 0 8 6 8 6 TOD 2 7 0 0 0 0 2 2 0 0 9 0 3 3 TimestampManipulation 8 8 0 7 6 2 0 0 1 8 0 10 10 7 Authorizationthroughtx.origin 0 0 0 3 6 0 0 0 0 0 0 9 10 6 BadRandomness 2 0 0 0 8 0 0 0 0 0 0 5 10 2 Total 42 44 40 31 54 18 18 10 21 30 33 34 84 64 ofthestrengthsandweaknessesoftheselectedtoolsacrossthecommon10categoriesdiscussedinSection3.The numbersineachcellshowthenumberofTPsidentifiedbyeachtoolforeachvulnerabilitycategory. GPT-4oshowsthehighestoverallperformance,detecting84outof100vulnerabilitiesacrossallcategories.Llama- 3.1-8bisthesecond-bestperformer,detecting64vulnerabilities.Amongtraditionaltools,Mythrilperformsbestwith 54TPs.Theresultsalsorevealsthatdifferenttoolsperformbetteratidentifyingcertainvulnerabilitycategories.For example,GPT-4o,Conkas,andLlama-3.1-8bperformbestatreentrancyvulnerabilities,whileSmartcheckperformsbest atGaslessSendvulnerabilities.LLMs(GPT-4oandLlama-3.1-8b)generallyoutperformtraditionaltoolsacrossmost categories. Tofurtherstudythetools’effectiveness,weaddsafecontractstoourexperiments.Theresultsarepresentedin Table5.GPT-4oshowsthebestoverallperformancewiththehighestAccuracy(79%)andF1-score(0.88).Llama-3.1-8b andMythriltieforsecondplaceinAccuracy(58%),butLlama-3.1-8bhasahigherF1-score(0.74vs0.70).Interestingly, Llama-3.1-8bhasthehighestfalsepositive(FP)count(10),followedbyGPT-4o(7).WhileLLMs(especiallyGPT-4o) showpromisingresultsinoverallvulnerabilitydetection,theymayexhibithighFPrates.Traditionaltools,despite loweroverallperformance,mightbevaluablefortheirhighprecisioninspecificscenarios. ThesefindingssuggestthatwhileLLM-basedtoolsshowgreatpromiseinenhancingsmartcontractsecurity,they shouldbeusedinconjunctionwithtraditionaltoolsandexpertreviewforoptimalresults. 6.2.2 ResourceEfficiency. Executiontimeisacrucialfactorinevaluatingatool’seffectiveness,asitdirectlyimpacts efficiency.Weassessedtheresourceefficiencyofeachtoolbymeasuringtheirexecutiontime,asindicatedinTable6. Ouranalysisrevealedsignificantvariationsinexecutiontimeacrossdifferenttools.Slitherandsolhintemerged asthefastesttools,withanaverageexecutiontimeof1second.GPT-4oalsodemonstratedhighefficiency,withan averageexecutiontimeof2.2seconds.Ontheotherendofthespectrum,Conkaswastheslowest,taking48minuteson averagetocompleteitsanalysis.ConFuzziusandsFuzzalsoexhibitedlongexecutiontime,whichcouldbeattributedto theirutilizationoffuzzingmethods. Ingeneral,weobservedthatstaticanalysistools(suchasSlitherandsolhint)andLLMs(likeGPT-4o)aresignificantly fasterthantoolsemployingmorecomplexanalysistechniques. ManuscriptsubmittedtoACM34 Weietal. Table5. AccuracyandF1-scoreAcrossSmartContractDetectionTools Metric suizzuFnoC saknoC naiaM erocitnaM lirhtyM sirisO etneyO yfiruceS zzuFs rehtilS kcehctramS tnihlos o4-TPG b8-1.3-amalL TP 42 44 4 31 54 18 18 10 21 30 33 34 84 64 FN 58 56 96 69 46 82 82 90 79 70 67 66 16 36 FP 3 4 0 0 0 2 2 0 1 0 0 0 7 10 TN 7 6 10 10 10 8 8 10 9 10 10 10 3 0 Accuracy 45% 46% 13% 37% 58% 24% 24% 18% 27% 36% 39% 40% 79% 58% Recall 0.42 0.44 0.04 0.31 0.54 0.18 0.18 0.1 0.21 0.3 0.33 0.34 0.84 0.64 Precision 0.93 0.92 1 1 1 0.9 0.9 1 0.95 1 1 1 0.92 0.86 F1-score 0.58 0.59 0.08 0.47 0.70 0.3 0.3 0.18 0.34 0.46 0.49 0.51 0.88 0.74 Table6. ExecutionTime,CompatibilityVersion(𝑆𝑣)andCategoryCoverage(𝑆𝑐)ScoresforEachTool Metric suizzuFnoC saknoC naiaM erocitnaM lirhtyM sirisO etneyO yfiruceS zzuFs rehtilS kcehctramS tnihlos o4-TPG b8-1.3-amalL Comp.ver. 0.8.x 0.5.x 0.8.x 0.8.x 0.8.x 0.4.21 0.4.19 0.5.11 0.4.24 0.6.x 0.8.x 0.8.x 0.8.x 0.8.x 𝑆𝑣 5 2 5 5 5 1 1 2 1 3 5 5 5 5 𝑆𝑐 8 5 1 6 7 3 3 2 5 4 5 5 10 10 Avg.Time 18m9s 48m 57s 11m2s 4m17s 1m32s 4s 27s 18m 1s 3s 1s 2.2s 47s 6.2.3 VersionCompatibilityandCategoryCoverage. GivenSolidity’scontinuousupdates,it’sessentialforanalysistools tokeeppacewiththelatestversionstoensureaccuratevulnerabilitydetection.Weassessedeachtool’scompatibility withSolidityversionsupto0.8.19(thelatestversionasofJanuary2023).Weassignedaratingvalue(𝑆 𝑣)todifferent Solidityversionsbasedontheircompatibilitywitheachtool.Theratingvaluestartsfrom1forversion0.4.xand increasesto5forversion0.8.x. Therangeofvulnerabilitycategoriesatoolcandetectiscrucialinevaluatingitseffectiveness.Toolswithwider categorycoveragemaybemoreversatileandeffectiveincomprehensivesmartcontractaudits.Weassignedascore(𝑆 𝑐) toeachtoolbasedonthenumberofvulnerabilitycategoriesitcandetect.Forinstance,atoolcapableofdetecting5 categoriesofvulnerabilitiesreceivesan𝑆 𝑐 scoreof5.
Table6summarizesthe𝑆 𝑣and𝑆 𝑐 scoresforeachevaluatedtool.Mosttools,includingConFuzzius,Maian,Manticore, Mythril,Smartcheck,solhint,GPT-4o,andLlama-3.1-8b,supportSolidityversion0.8.x,achievingthehighest𝑆 𝑣 score of5.GPT-4oandLlama-3.1-8bdemonstratedthehighest𝑆 𝑐 scoreof10,indicatingtheycoverallidentifiedvulnerability categories. 6.2.4 OverallEffectiveness. Toprovideacomprehensiveassessmentofthesmartcontractanalysistools,wedevelopeda weightedsummethodthatbalancesthekeyfactorsevaluatedintheprevioussections:detectioneffectiveness,resource efficiency,versioncompatibility,categorycoverage.Weassignweightstoeachfactorbasedontheirrelativeimportance. 𝛼toaccuracy,𝛽toaverageexecutiontime,𝛾tocompatibilityversion,and𝛿tocategorycoverage,where𝛼+𝛽+𝛾+𝛿 =1. Theoverallscoreforeachtooliscalculatedusingthefollowingformula: ManuscriptsubmittedtoACMSurveyonQualityAssuranceofSmartContracts 35 Table7. OverallScoresforEachToolwithDifferentWeightConfigurations Weights:𝛼,𝛽,𝛾,𝛿 zzuFnoC saknoC naiaM citnaM lirhtyM sirisO etneyO yfiruceS zzuFs rehtilS hCtramS tnihlos o4-TPG b8-1.3-amalL 0.250.25,0.25,0.25 4.37 2.89 1.86 3.69 4.46 1.62 2.22 1.55 2.18 5.16 4.31 6.00 6.86 5.26 0.7,0.1,0.1,0.1 4.42 3.88 1.51 3.71 5.28 2.07 2.30 1.71 2.51 4.25 4.07 4.80 7.49 5.59 0.1,0.7,0.1,0.1 1.75 1.16 0.85 1.48 1.81 0.71 2.39 0.84 0.88 8.06 3.72 8.40 5.47 2.23 0.1,0.1,0.7,0.1 4.75 2.35 3.74 4.47 4.79 1.25 1.49 1.82 1.47 3.86 4.72 5.40 5.75 5.10 0.1,0.1,0.1,0.7 6.55 4.15 1.34 5.07 5.99 2.45 2.69 1.82 3.87 4.46 4.72 5.40 8.75 8.10 𝑆𝑐𝑜𝑟𝑒 =𝛼×𝐴∗10+𝛽×(1/𝐴𝐸𝑋)∗10+𝛾×𝑆 𝑣+𝛿×𝑆 𝑐 where𝐴istheaccuracyvalueand𝐴𝐸𝑋 istheaverageexecutiontime. Table7presentsthescoresforeachtoolunderfivedifferentweightconfigurations,emphasizingdifferentaspects oftoolperformance.GPT-4oconsistentlyachievedthehighestscoresacrossmostweightconfigurations,indicating itswell-roundedperformance.Llama-3.1-8bgenerallyperformedwell,oftenscoringsecondorthirdhighest.Among traditionaltools,solhint,Slither,andMythriltendedtoscorehigherthanothers.Whenemphasiswasplacedonresource efficiency,solhintledwithascoreof8.40,followedcloselybySlither(8.06). Thechoiceoftoolmaydependonspecificprojectpriorities.Forrapid,preliminaryscans,toolslikesolhintorSlither mightbepreferred.Forin-depthsecurityaudits,GPT-4ooracombinationoftoolscouldbemosteffective.Theflexibility providedbydifferentweightconfigurationsinourscoringsystemallowsfortoolselectionbasedonproject-specific requirements. Inaddition,acombinedapproachusingmultipletoolscouldpotentiallyyieldthemostcomprehensiveresults.For example,solhintcouldbeusedforgrammaticalchecksandensuringcodeadherencetostandards.LLMslikeGPT-4oor Llama-3.1-8bcouldidentifyknownvulnerabilitiesandprovidesuggestionstopreventattacks.Slithercouldofferdeeper analysisofthecodeanddetectsemantic-levelissues.Thesefindingsprovideclearandcomprehensiveresponsesto RQ4andRQ5,highlightingtherelativestrengthsandweaknessesofdifferenttooltypesandsuggestingstrategiesfor theireffectiveuseinsmartcontractvulnerabilitydetection. 6.3 Threattovalidity Threatstovalidityarefactorsthathavethepotentialtoimpacttheresultsofanexperimentandthevalidityofits findings.Inourresearch,wehaveidentifiedtwospecificaspectsthatcouldposethreatstothevalidityofourstudy:the categorizationofsmartcontractvulnerabilitiesandthegeneralityoftheevaluationdatasets. Onepotentialthreattothevalidityofourevaluationisthesubjectivityandvariationamongresearchersinevaluating andcategorizingvulnerabilitiesandtheirassociatedsmartcontracts.Differentresearchersmayhavediverseperspectives, criteria,andinterpretationswhenassessingtheseverityandclassificationofvulnerabilities.Thissubjectivitycan introducebiasandaffectthevalidityofthecomparisonspresentedintheevaluation.Tomitigatethisthreat,wehave adoptedasystematicapproachbasedonindustrystandardsandbestpracticesinSection3.Wehavethoroughly reviewedanddiscussedeachvulnerabilitycategorytoensureaconsistentandobjectiveclassification.Thisinvolved extensiveresearch,consultationwithexperts,andcarefulconsiderationofexistingliterature.Wehavealsoprovided ManuscriptsubmittedtoACM36 Weietal. cleardefinitions,criteria,andexplanationsforeachvulnerabilitycategoryconsideredinouranalysis.Byproviding thistransparencyanddocumentationofourevaluationprocess,weaimtominimizeambiguityandfacilitateamore consistentunderstandingofthevulnerabilitiesacrossdifferentresearchersandreaders. Thegeneralityoftheevaluationdatasetsrepresentsanotherpotentialthreattothevalidityofourresearch.This threatreferstotheextenttowhichthedatasetsusedforevaluationaccuratelyreflectreal-worldscenariosandthe usagepatternsofsmartcontracts.Iftheevaluationdatasetsarelimitedinscopeorfailtoencompassthediversityof smartcontractapplications,thefindingsandconclusionsmaylackgeneralizability.Tomitigatethisthreat,wehave madesignificanteffortstoaddressdatasetlimitations.Wehaveconductedanextensivecollectionofcontracttestsfrom varioussources,includingpubliclyavailabledatasetsandourowndevelopedtestcases.Ourdatasetconsistsof110
contracttestcases,whichhavebeencarefullyselectedtocoverawiderangeofapplicationsanddifferentcodesizes. Byincorporatingdiversecontracttestcases,weaimtoprovideamorerepresentativeevaluationofsmartcontract vulnerabilitiesandincreasethegeneralizabilityofourfindings. Whilewehavetakenmeasurestoaddressthesethreats,itisimportanttoacknowledgethatlimitationsmaystill exist.Tofurtherenhancethevalidityoffuturestudies,researcherscanfocusonrefiningvulnerabilitycategorization criteriaandcollectinglarger,morediversedatasetsthatbettercapturereal-worldscenarios. 7 CONCLUSIONS Astheadoptionofsmartcontracttechnologycontinuestosurge,itssecuritybecomesincreasinglycriticalforthe robustnessofblockchainecosystems.Ourcomprehensivesurvey,encompassingvulnerabilities,attacks,defenses,and toolsupport,notonlyadvancesacademicunderstandingbutalsoofferspracticalimplicationsfordevelopersand stakeholdersinblockchaintechnology.Ournovelclassificationsofvulnerabilitytypesandattackpatternsprovide developers with a clearer understanding of potential security risks. This understanding is crucial for developing moresecuresmartcontracts.Bybeingawareofcommonvulnerabilitiesandhowattacksexploitthem,developers can proactively incorporate security measures during the development phase. Additionally, our evaluation of 14 vulnerability-detectingtoolsguidesdevelopersinchoosingthemosteffectivetoolsfortheirspecificneeds,thereby enhancingthesecurityoftheirsmartcontracts.Stakeholders,includingprojectmanagersandinvestorsinblockchain projects,canleverageourfindingstomakeinformeddecisionsaboutthesecurityaspectsoftheprojectstheyare overseeingorinvestingin.Understandingthestrengthsandlimitationsofdifferentsecuritytoolsallowsthemtoassess therobustnessofsecuritypracticesemployedintheirprojectsandadvocatefortheadoptionofthemosteffective methodologies.Additionally,theannotateddatasetof110smartcontractswecreatedservesasavaluableresourcefor thecommunity.Itprovidesastandardizedbenchmarkthatfacilitatescomparativestudiesandongoingevaluationsof tools’effectivenessinvulnerabilitydetection.Thiscontributestoacollectiveeffortinimprovingtheoverallsecurity standardsintheblockchainecosystem. However,thesmartcontractlandscapeisevolvingrapidly,withnewfunctionalitiesandprotocolsleadingtothe emergenceofnewsecurityvulnerabilities.Tomakesmartcontractlanguagesmorerobust,itiscrucialtocontinue investinginresearchanddevelopment.Forinstance,therehasbeenagrowinginterestinusingprogramminglanguages otherthanSolidityforsmartcontractdevelopment.LanguageslikeGoandRusthavegainedattentionduetotheir strongersyntaxandlogicalsoundness,offeringpotentialsolutionstoaddresssomeofthesecurityissuesassociated withSolidity.Furthermore,thereisaneedformorepowerfulanalysistoolscapableofidentifyingdynamicorlogic errorswithinsmartcontracts.Existingtoolsprimarilyfocusonknownvulnerabilitiesandattacks,whileeffective methodologiesfordealingwithunknownattacksarestilllimited.Thus,protectingsmartcontractsfromunknown ManuscriptsubmittedtoACMSurveyonQualityAssuranceofSmartContracts 37 attacksposesasignificantchallengeforfutureresearch.Additionally,developingautomatedapproachesforrepairing vulnerablesmartcontractsafterdeploymentcouldprovetobeafruitfuldirection.Inconclusion,thesecurityofsmart contractsremainsanongoingconcernthatdemandscontinuousattentionandinnovationtoaddressevolvingthreats. ACKNOWLEDGMENTS ThisworkissupportedbyNationalKeyResearchandDevelopmentProgramofChinaunderthegrantNo.2021YFB2701202. ThisworkissupportedbyNationalNaturalScienceFoundationofChina(NSFC)underthegrantNo.62172040,No. 62002094,No.U1836212,andNationalKeyResearchandDevelopmentProgramofChinaunderthegrantNo.2021YFB2701200, 2022YFB2702402,andAnhuiProvincialNaturalScienceFoundationunderthegrantNo.2008085MF196. REFERENCES [1] TesnimAbdellatifandKei-LéoBrousmiche.2018.FormalVerificationofSmartContractsBasedonUsersandBlockchainBehaviorsModels.In9th IFIPInternationalConferenceonNewTechnologies,MobilityandSecurity,NTMS2018,Paris,France,February26-28,2018.IEEE,1–5. [2] JoshAchiam,StevenAdler,SandhiniAgarwal,LamaAhmad,IlgeAkkaya,FlorenciaLeoniAleman,DiogoAlmeida,JankoAltenschmidt,Sam Altman,ShyamalAnadkat,etal.2023.Gpt-4technicalreport.arXivpreprintarXiv:2303.08774(2023). [3] WolfgangAhrendt,RichardBubel,JoshuaEllul,GordonJ.Pace,RaúlPardo,VincentRebiscoul,andGerardoSchneider.2019.VerificationofSmart ContractBusinessLogic-ExploitingaJavaSourceCodeVerifier.InFundamentalsofSoftwareEngineering-8thInternationalConference,FSEN2019, Tehran,Iran,May1-3,2019,RevisedSelectedPapers(LectureNotesinComputerScience,Vol.11761).Springer,228–243. [4] ElviraAlbert,PuriArenas,AntonioFlores-Montoya,SamirGenaim,MiguelGómez-Zamalloa,EnriqueMartin-Martin,GermanPuebla,and GuillermoRomán-Díez.2014.SACO:staticanalyzerforconcurrentobjects.InToolsandAlgorithmsfortheConstructionandAnalysisofSystems: 20thInternationalConference,TACAS2014,HeldasPartoftheEuropeanJointConferencesonTheoryandPracticeofSoftware,ETAPS2014,Grenoble, France,April5-13,2014.Proceedings20.Springer,562–567.
[5] ElviraAlbert,PuriArenas,SamirGenaim,andGermánPuebla.2008.Automaticinferenceofupperboundsforrecurrencerelationsincostanalysis. InStaticAnalysis:15thInternationalSymposium,SAS2008,Valencia,Spain,July16-18,2008.Proceedings15.Springer,221–237. [6] ElviraAlbert,JesúsCorreas,PabloGordillo,GuillermoRomán-Díez,andAlbertRubio.2020.GASOL:GasAnalysisandOptimizationforEthereum SmartContracts.InToolsandAlgorithmsfortheConstructionandAnalysisofSystems-26thInternationalConference,TACAS2020,HeldasPartof theEuropeanJointConferencesonTheoryandPracticeofSoftware,ETAPS2020,Dublin,Ireland,April25-30,2020,Proceedings,PartII(LectureNotesin ComputerScience,Vol.12079).Springer,118–125. [7] ElviraAlbert,PabloGordillo,BenjaminLivshits,AlbertRubio,andIlyaSergey.2018.EthIR:AFrameworkforHigh-LevelAnalysisofEthereum Bytecode.InAutomatedTechnologyforVerificationandAnalysis-16thInternationalSymposium,ATVA2018,LosAngeles,CA,USA,October7-10, 2018,Proceedings(LectureNotesinComputerScience,Vol.11138).Springer,513–520. [8] ElviraAlbert,PabloGordillo,AlbertRubio,andIlyaSergey.2019.RunningonFumes-PreventingOut-of-GasVulnerabilitiesinEthereumSmart ContractsUsingStaticResourceAnalysis.InVerificationandEvaluationofComputerandCommunicationSystems-13thInternationalConference, VECoS2019,Porto,Portugal,October9,2019,Proceedings(LectureNotesinComputerScience,Vol.11847).Springer,63–78. [9] ShaimaALAmri,LeonardoAniello,andVladimiroSassone.2023.AReviewofUpgradeableSmartContractPatternsbasedonOpenZeppelin Technique.TheJournalofTheBritishBlockchainAssociation(2023). [10] ElliAndroulaki,ArtemBarger,VitaBortnikov,ChristianCachin,KonstantinosChristidis,AngeloDeCaro,DavidEnyeart,ChristopherFerris, GennadyLaventman,YacovManevich,SrinivasanMuralidharan,ChetMurthy,BinhNguyen,ManishSethi,GariSingh,KeithSmith,Alessandro Sorniotti,ChrysoulaStathakopoulou,MarkoVukolic,SharonWeedCocco,andJasonYellick.2018.Hyperledgerfabric:adistributedoperating systemforpermissionedblockchains.InProceedingsoftheThirteenthEuroSysConference,EuroSys2018,Porto,Portugal,April23-26,2018.ACM, 30:1–30:15. [11] MonikaDiAngeloandGernotSalzer.2019. ASurveyofToolsforAnalyzingEthereumSmartContracts.InIEEEInternationalConferenceon DecentralizedApplicationsandInfrastructures,DAPPCON2019,Newark,CA,USA,April4-9,2019.IEEE,69–78. [12] ImranAshraf,XiaoxueMa,BoJiang,andWingKwongChan.2020.GasFuzzer:Fuzzingethereumsmartcontractbinariestoexposegas-oriented exceptionsecurityvulnerabilities.IEEEAccess8(2020),99552–99564. [13] NicolaAtzei,MassimoBartoletti,andTizianaCimoli.2017.Asurveyofattacksonethereumsmartcontracts(sok).InPrinciplesofSecurityand Trust:6thInternationalConference,POST2017,HeldasPartoftheEuropeanJointConferencesonTheoryandPracticeofSoftware,ETAPS2017,Uppsala, Sweden,April22-29,2017,Proceedings6.Springer,164–186. [14] NicolaAtzei,MassimoBartoletti,andTizianaCimoli.2017.ASurveyofAttacksonEthereumSmartContracts(SoK).InPrinciplesofSecurity andTrust-6thInternationalConference,POST2017,HeldasPartoftheEuropeanJointConferencesonTheoryandPracticeofSoftware,ETAPS2017, Uppsala,Sweden,April22-29,2017,Proceedings(LectureNotesinComputerScience,Vol.10204).Springer,164–186. ManuscriptsubmittedtoACM38 Weietal. [15] NicolaAtzei,MassimoBartoletti,TizianaCimoli,StefanoLande,andRobertoZunino.2018.SoK:UnravelingBitcoinSmartContracts.InPrinciples ofSecurityandTrust-7thInternationalConference,POST2018,HeldasPartoftheEuropeanJointConferencesonTheoryandPracticeofSoftware, ETAPS2018,Thessaloniki,Greece,April14-20,2018,Proceedings(LectureNotesinComputerScience,Vol.10804).Springer,217–242. [16] XiaominBai,ZijingCheng,ZhangboDuan,andKaiHu.2018.FormalModelingandVerificationofSmartContracts.InProceedingsofthe7th InternationalConferenceonSoftwareandComputerApplications,ICSCA2018,Kuantan,Malaysia,February08-10,2018.ACM,322–326. [17] MassimoBartoletti,StefanoLande,MaurizioMurgia,andRobertoZunino.2022.VerifyingliquidityofrecursiveBitcoincontracts.Log.Methods Comput.Sci.18,1(2022). [18] MassimoBartolettiandRobertoZunino.2018.VerifyingliquidityofBitcoincontracts.IACRCryptol.ePrintArch.(2018),1125. [19] MassimoBartolettiandRobertoZunino.2019.FormalModelsofBitcoinContracts:ASurvey.FrontiersBlockchain2(2019),8. [20] JanArvidBerg,RobinFritsch,LiobaHeimbach,andRogerWattenhofer.2022. AnempiricalstudyofmarketinefficienciesinUniswapand SushiSwap.InInternationalConferenceonFinancialCryptographyandDataSecurity.Springer,238–249. [21] BrunoBernardo,RaphaëlCauderlier,GuillaumeClaret,ArvidJakobsson,BasilePesin,andJulienTesson.2020.MakingTezosSmartContracts MoreReliablewithCoq.InLeveragingApplicationsofFormalMethods,VerificationandValidation:Applications-9thInternationalSymposiumon
LeveragingApplicationsofFormalMethods,ISoLA2020,Rhodes,Greece,October20-30,2020,Proceedings,PartIII(LectureNotesinComputerScience, Vol.12478).Springer,60–72. [22] WilliamEBodellIII,SajadMeisami,andYueDuan.2023. Proxyhunting:understandingandcharacterizingproxy-basedupgradeablesmart contractsinblockchains.In32ndUSENIXSecuritySymposium(USENIXSecurity23).1829–1846. [23] LexiBrent,NevilleGrech,SifisLagouvardos,BernhardScholz,andYannisSmaragdakis.2020.Ethainter:asmartcontractsecurityanalyzerfor compositevulnerabilities.InProceedingsofthe41stACMSIGPLANConferenceonProgrammingLanguageDesignandImplementation.454–469. [24] LexiBrent,AntonJurisevic,MichaelKong,EricLiu,FrancoisGauthier,VincentGramoli,RalphHolz,andBernhardScholz.2018.Vandal:Ascalable securityanalysisframeworkforsmartcontracts.arXivpreprintarXiv:1809.03981(2018). [25] VitalikButerinetal.2013.Ethereumwhitepaper.GitHubrepository1(2013),22–23. [26] FranCasino,ThomasKDasaklis,andConstantinosPatsakis.2019.Asystematicliteraturereviewofblockchain-basedapplications:Currentstatus, classificationandopenissues.Telematicsandinformatics36(2019),55–81. [27] SaikatChakraborty,RahulKrishna,YangruiboDing,andBaishakhiRay.2021.Deeplearningbasedvulnerabilitydetection:Arewethereyet?IEEE TransactionsonSoftwareEngineering48,9(2021),3280–3296. [28] StefanosChaliasos,MarcosAntoniosCharalambous,LiyiZhou,RafailaGalanopoulou,ArthurGervais,DimitrisMitropoulos,andBenjamin Livshits.2024.SmartContractandDeFiSecurityTools:DoTheyMeettheNeedsofPractitioners?.InProceedingsofthe46thIEEE/ACMInternational ConferenceonSoftwareEngineering.1–13. [29] ChongChen,JianzhongSu,JiachiChen,YanlinWang,TingtingBi,YanliWang,XingweiLin,TingChen,andZibinZheng.2023.Whenchatgpt meetssmartcontractvulnerabilitydetection:Howfararewe?arXivpreprintarXiv:2309.05520(2023). [30] HuashanChen,MarcusPendleton,LaurentNjilla,andShouhuaiXu.2021.ASurveyonEthereumSystemsSecurity:Vulnerabilities,Attacks,and Defenses.ACMComput.Surv.53,3(2021),67:1–67:43. [31] TingChen,RongCao,TingLi,XiapuLuo,GuofeiGu,YufeiZhang,ZhouLiao,HangZhu,GangChen,ZheyuanHe,YuxingTang,XiaodongLin, andXiaosongZhang.2020.SODA:AGenericOnlineDetectionFrameworkforSmartContracts.In27thAnnualNetworkandDistributedSystem SecuritySymposium,NDSS2020,SanDiego,California,USA,February23-26,2020.TheInternetSociety. [32] TingChen,YouzhengFeng,ZihaoLi,HaoZhou,XiapuLuo,XiaoqiLi,XiuzhuoXiao,JiachiChen,andXiaosongZhang.2021.GasChecker:Scalable AnalysisforDiscoveringGas-InefficientSmartContracts.IEEETrans.Emerg.Top.Comput.9,3(2021),1433–1448. [33] TingChen,XiaoqiLi,YingWang,JiachiChen,ZihaoLi,XiapuLuo,ManHoAu,andXiaosongZhang.2017.Anadaptivegascostmechanismfor ethereumtodefendagainstunder-priceddosattacks.InInformationSecurityPracticeandExperience:13thInternationalConference,ISPEC2017, Melbourne,VIC,Australia,December13–15,2017,Proceedings13.Springer,3–24. [34] YizhengChen,ZhoujieDing,LamyaAlowain,XinyunChen,andDavidWagner.2023.Diversevul:Anewvulnerablesourcecodedatasetfordeep learningbasedvulnerabilitydetection.InProceedingsofthe26thInternationalSymposiumonResearchinAttacks,IntrusionsandDefenses.654–668. [35] RaymondCheng,FanZhang,JernejKos,WarrenHe,NicholasHynes,NoahM.Johnson,AriJuels,AndrewMiller,andDawnSong.2019.Ekiden:A PlatformforConfidentiality-Preserving,Trustworthy,andPerformantSmartContracts.InIEEEEuropeanSymposiumonSecurityandPrivacy, EuroS&P2019,Stockholm,Sweden,June17-19,2019.IEEE,185–200. [36] HantingChu,PengchengZhang,HaiDong,YanXiao,ShunhuiJi,andWenruiLi.2023.Asurveyonsmartcontractvulnerabilities:Datasources, detectionandrepair.InformationandSoftwareTechnology159(2023),107221. [37] TimCopeland.2020.Howageniushackermade$350,000exploitingDeFi. https://decrypt.co/19612/how-a-genius-hacker-made-350000-exploiting- defi [38] GiuseppeCrincoli,GiacomoIadarola,PieraElenaLaRocca,FabioMartinelli,FrancescoMercaldo,andAntonellaSantone.2022.Vulnerablesmart contractdetectionbymeansofmodelchecking.InProceedingsoftheFourthACMInternationalSymposiumonBlockchainandSecureCritical Infrastructure.3–10. [39] PauliusDanielius,PiotrStolarski,andSauliusMasteika.2020.Vulnerabilitiesandexcessgasconsumptionanalysiswithinethereum-basedsmart contractsforelectricitymarket.InBusinessInformationSystemsWorkshops:BIS2020InternationalWorkshops,ColoradoSprings,CO,USA,June8–10, 2020,RevisedSelectedPapers23.Springer,99–110. ManuscriptsubmittedtoACMSurveyonQualityAssuranceofSmartContracts 39 [40] IsaacDavid,LiyiZhou,KaihuaQin,DawnSong,LorenzoCavallaro,andArthurGervais.2023.Doyoustillneedamanualsmartcontractaudit? arXivpreprintarXiv:2306.12338(2023).
[41] ThomasDurieux,JoãoF.Ferreira,RuiAbreu,andPedroCruz.2020.Empiricalreviewofautomatedanalysistoolson47,587Ethereumsmart contracts.InICSE’20:42ndInternationalConferenceonSoftwareEngineering,Seoul,SouthKorea,27June-19July,2020.ACM,530–541. [42] JoshuaEllulandGordonJPace.2018.Runtimeverificationofethereumsmartcontracts.In201814thEuropeanDependableComputingConference (EDCC).IEEE,158–163. [43] ShayanEskandari,SeyedehmahsaMoosavi,andJeremyClark.2019. SoK:TransparentDishonesty:Front-RunningAttacksonBlockchain.In FinancialCryptographyandDataSecurity-FC2019InternationalWorkshops,VOTINGandWTSC,St.Kitts,St.KittsandNevis,February18-22,2019, RevisedSelectedPapers(LectureNotesinComputerScience,Vol.11599).Springer,170–189. [44] JosselinFeist,GustavoGrieco,andAlexGroce.2019.Slither:astaticanalysisframeworkforsmartcontracts.InProceedingsofthe2ndInternational WorkshoponEmergingTrendsinSoftwareEngineeringforBlockchain,WETSEB@ICSE2019,Montreal,QC,Canada,May27,2019.IEEE/ACM,8–15. [45] JosselinFeist,GustavoGrieco,andAlexGroce.2019.Slither:astaticanalysisframeworkforsmartcontracts.In2019IEEE/ACM2ndInternational WorkshoponEmergingTrendsinSoftwareEngineeringforBlockchain(WETSEB).IEEE,8–15. [46] flashbots.2023.MVE-Explorev1. https://explore.flashbots.net/ [47] TerrellFord.2022.BenchmarkingEthereumSmartContractStaticAnalysisTools.Ph.D.Dissertation. [48] IkramGarfatta,KaisKlai,WalidGaaloul,andMohamedGraiet.2021. Asurveyonformalverificationforsoliditysmartcontracts.In2021 AustralasianComputerScienceWeekMulticonference.1–10. [49] AsemGhalebandKarthikPattabiraman.2020.Howeffectivearesmartcontractanalysistools?evaluatingsmartcontractstaticanalysistoolsusing buginjection.InISSTA’20:29thACMSIGSOFTInternationalSymposiumonSoftwareTestingandAnalysis,VirtualEvent,USA,July18-22,2020.ACM, 415–427. [50] NevilleGrech,MichaelKong,AntonJurisevic,LexiBrent,BernhardScholz,andYannisSmaragdakis.2018.Madmax:Survivingout-of-gasconditions inethereumsmartcontracts.ProceedingsoftheACMonProgrammingLanguages2,OOPSLA(2018),1–27. [51] GustavoGrieco,WillSong,ArturCygan,JosselinFeist,andAlexGroce.2020.Echidna:effective,usable,andfastfuzzingforsmartcontracts.In Proceedingsofthe29thACMSIGSOFTinternationalsymposiumonsoftwaretestingandanalysis.557–560. [52] ShellyGrossman,IttaiAbraham,GuyGolan-Gueta,YanMichalevsky,NoamRinetzky,MoolySagiv,andYoniZohar.2018.Onlinedetectionof effectivelycallbackfreeobjectswithapplicationstosmartcontracts.Proc.ACMProgram.Lang.2,POPL(2018),48:1–48:28. [53] BrijBGupta,Kuan-ChingLi,VictorCMLeung,KostasEPsannis,ShingoYamaguchi,etal.2021.Blockchain-assistedsecurefine-grainedsearchable encryptionforacloud-basedhealthcarecyber-physicalsystem.IEEE/CAAJournalofAutomaticaSinica8,12(2021),1877–1890. [54] SunilGupta,HiteshKumarSharma,andMonitKapoor.2023.BlockchainforSecureHealthcareUsingInternetofMedicalThings(IoMT).Springer. [55] HazimHanif,MohdHairulNizamMdNasir,MohdFaizalAbRazak,AhmadFirdaus,andNorBadrulAnuar.2021.Theriseofsoftwarevulnerability: Taxonomyofsoftwarevulnerabilitiesdetectionandmachinelearningapproaches. JournalofNetworkandComputerApplications179(2021), 103009. [56] DominikHarzandWilliamKnottenbelt.2018.Towardssafersmartcontracts:Asurveyoflanguagesandverificationmethods.arXivpreprint arXiv:1809.09805(2018). [57] DaojingHe,RuiWu,XinjiLi,SammyChan,andMohsenGuizani.2023.Detectionofvulnerabilitiesofblockchainsmartcontracts.IEEEInternetof ThingsJournal10,14(2023),12178–12185. [58] JingxuanHe,MislavBalunovic,NodarAmbroladze,PetarTsankov,andMartinT.Vechev.2019.LearningtoFuzzfromSymbolicExecutionwith ApplicationtoSmartContracts.InProceedingsofthe2019ACMSIGSACConferenceonComputerandCommunicationsSecurity,CCS2019,London, UK,November11-15,2019.ACM,531–548. [59] NingyuHe,HaoyuWang,LeiWu,XiapuLuo,YaoGuo,andXiangqunChen.2022.Asurveyoneosiosystemssecurity:Vulnerability,attack,and mitigation.arXivpreprintarXiv:2207.09227(2022). [60] NingyuHe,RuiyiZhang,HaoyuWang,LeiWu,XiapuLuo,YaoGuo,TingYu,andXuxianJiang.2021.{EOSAFE}:securityanalysisof{EOSIO} smartcontracts.In30thUSENIXsecuritysymposium(USENIXSecurity21).1271–1288. [61] BinHu,ZongyangZhang,JianweiLiu,YizhongLiu,JiayuanYin,RongxingLu,andXiaodongLin.2021.Acomprehensivesurveyonsmartcontract constructionandexecution:paradigms,tools,andsystems.Patterns2,2(2021),100179. [62] TengHu,XiaoleiLiu,TingChen,XiaosongZhang,XiaomingHuang,WeinaNiu,JiazhongLu,KunZhou,andYuanLiu.2021.Transaction-based classificationanddetectionapproachforEthereumsmartcontract.InformationProcessing&Management58,2(2021),102462.
[63] LaurieHughes,YogeshKDwivedi,SantoshKMisra,NripendraPRana,VishnupriyaRaghavan,andViswanadhAkella.2019.Blockchainresearch, practiceandpolicy:Applications,benefits,limitations,emergingresearchthemesandresearchagenda. InternationalJournalofInformation Management49(2019),114–129. [64] NikolayIvanov,ChenningLi,QibenYan,ZhiyuanSun,ZhichaoCao,andXiapuLuo.2023.SecurityThreatMitigationForSmartContracts:A ComprehensiveSurvey.Comput.Surveys(2023). [65] BoJiang,YeLiu,andW.K.Chan.2018.ContractFuzzer:fuzzingsmartcontractsforvulnerabilitydetection.InProceedingsofthe33rdACM/IEEE InternationalConferenceonAutomatedSoftwareEngineering,ASE2018,Montpellier,France,September3-7,2018.ACM,259–269. [66] JiaoJiao,ShuanglongKan,Shang-WeiLin,DavidSanan,YangLiu,andJunSun.2020.Semanticunderstandingofsmartcontracts:Executable operationalsemanticsofsolidity.In2020IEEESymposiumonSecurityandPrivacy(SP).IEEE,1695–1712. ManuscriptsubmittedtoACM40 Weietal. [67] josselinfeist.2018.Contractupgradeanti-patterns. https://blog.trailofbits.com/2018/09/05/contract-upgrade-anti-patterns/ [68] josselinfeist.2018.Howcontractmigrationworks. https://blog.trailofbits.com/2018/10/29/how-contract-migration-works/ [69] HarryA.Kalodner,StevenGoldfeder,XiaoqiChen,S.MatthewWeinberg,andEdwardW.Felten.2018.Arbitrum:Scalable,privatesmartcontracts. In27thUSENIXSecuritySymposium,USENIXSecurity2018,Baltimore,MD,USA,August15-17,2018.USENIXAssociation,1353–1370. [70] BasimKhajwal,C-HLukeOng,andDominikWagner.2023.FastandCorrectGradient-BasedOptimisationforProbabilisticProgrammingvia Smoothing.InEuropeanSymposiumonProgramming.SpringerNatureSwitzerlandCham,479–506. [71] ShafaqNaheedKhan,FaizaLoukil,ChirineGhediraGuegan,ElhadjBenkhelifa,andAnoudBani-Hani.2021. Blockchainsmartcontracts: Applications,challenges,andfuturetrends.Peer-to-PeerNetw.Appl.14,5(2021),2901–2925. [72] AhmedE.Kosba,AndrewMiller,ElaineShi,ZikaiWen,andCharalamposPapamanthou.2016.Hawk:TheBlockchainModelofCryptographyand Privacy-PreservingSmartContracts.InIEEESymposiumonSecurityandPrivacy,SP2016,SanJose,CA,USA,May22-26,2016.IEEEComputer Society,839–858. [73] AoLi,JeminAndrewChoi,andFanLong.2020. Securingsmartcontractwithruntimevalidation.InProceedingsofthe41stACMSIGPLAN InternationalConferenceonProgrammingLanguageDesignandImplementation,PLDI2020,London,UK,June15-20,2020.ACM,438–453. [74] ChunmiaoLi,ShijieNie,YangCao,YijunYu,andZhenjiangHu.2020.Trace-BasedDynamicGasEstimationofLoopsinSmartContracts.IEEE OpenJ.Comput.Soc.1(2020),295–306. [75] PeiruLi,ShanshanLi,MengjieDing,JiapengYu,HeZhang,XinZhou,andJingyueLi.2022.AVulnerabilityDetectionFrameworkforHyperledger FabricSmartContractsBasedonDynamicandStaticAnalysis.InEASE2022:TheInternationalConferenceonEvaluationandAssessmentinSoftware Engineering2022,Gothenburg,Sweden,June13-15,2022.ACM,366–374. [76] YuweiLi,ShoulingJi,YuanChen,SizhuangLiang,Wei-HanLee,YueyaoChen,ChenyangLyu,ChunmingWu,RaheemBeyah,PengCheng, KangjieLu,andTingWang.2021.UNIFUZZ:AHolisticandPragmaticMetrics-DrivenPlatformforEvaluatingFuzzers.In30thUSENIXSecurity Symposium,USENIXSecurity2021,August11-13,2021.USENIXAssociation,2777–2794. [77] Jian-WeiLiao,Tsung-TaTsai,Chia-KangHe,andChin-WeiTien.2019.SoliAudit:SmartContractVulnerabilityAssessmentBasedonMachine LearningandFuzzTesting.InSixthInternationalConferenceonInternetofThings:Systems,ManagementandSecurity,IOTSMS2019,Granada,Spain, October22-25,2019.IEEE,458–465. [78] JingweiLiu,XiaoluLi,LinYe,HongliZhang,XiaojiangDu,andMohsenGuizani.2018.BPDS:ABlockchainBasedPrivacy-PreservingDataSharing forElectronicMedicalRecords.InIEEEGlobalCommunicationsConference,GLOBECOM2018,AbuDhabi,UnitedArabEmirates,December9-13, 2018.IEEE,1–6. [79] NingLu,BinWang,YongxinZhang,WenboShi,andChristianEsposito.2021.NeuCheck:AmorepracticalEthereumsmartcontractsecurity analysistool.Softw.Pract.Exp.51,10(2021),2065–2084. [80] LoiLuu,Duc-HiepChu,HrishiOlickel,PrateekSaxena,andAquinasHobor.2016.MakingSmartContractsSmarter.InProceedingsofthe2016 ACMSIGSACConferenceonComputerandCommunicationsSecurity,Vienna,Austria,October24-28,2016.ACM,254–269. [81] PenghuiLv,YuWang,YazheWang,andQihuiZhou.2021.PotentialRiskDetectionSystemofHyperledgerFabricSmartContractbasedonStatic Analysis.InIEEESymposiumonComputersandCommunications,ISCC2021,Athens,Greece,September5-8,2021.IEEE,1–7. [82] JoséManuelGuaitaMartínez,PatriciaCarracedo,DoloresGorguesComas,andCarlosHSiemens.2022. Ananalysisoftheblockchainand COVID-19researchlandscapeusingabibliometricstudy.SustainableTechnologyandEntrepreneurship1,1(2022),100006. [83] PatrickMcCorry,SiamakF.Shahandashti,andFengHao.2017.ASmartContractforBoardroomVotingwithMaximumVoterPrivacy.InFinancial
CryptographyandDataSecurity-21stInternationalConference,FC2017,Sliema,Malta,April3-7,2017,RevisedSelectedPapers(LectureNotesin ComputerScience,Vol.10322).Springer,357–375. [84] METAMASK.2023.Acryptowallet&gatewaytoblockchainapps. https://metamask.io/ [85] Miscrosoft.2019.onefuzz. https://github.com/microsoft/onefuzz [86] MarkMossberg,FelipeManzano,EricHennenfent,AlexGroce,GustavoGrieco,JosselinFeist,TrentBrunson,andArtemDinaburg.2019.Manticore: Auser-friendlysymbolicexecutionframeworkforbinariesandsmartcontracts.In201934thIEEE/ACMInternationalConferenceonAutomated SoftwareEngineering(ASE).IEEE,1186–1189. [87] BehkishNassirzadeh,HuaiyingSun,SebastianBanescu,andVijayGanesh.2022.Gasgauge:Asecurityanalysistoolforsmartcontractout-of-gas vulnerabilities.InTheInternationalConferenceonMathematicalResearchforBlockchainEconomy.Springer,143–167. [88] ZeinabNehai,Pierre-YvesPiriou,andFrédéricF.Daumas.2018.Model-CheckingofSmartContracts.InIEEEInternationalConferenceonInternetof Things(iThings)andIEEEGreenComputingandCommunications(GreenCom)andIEEECyber,PhysicalandSocialComputing(CPSCom)andIEEE SmartData(SmartData),iThings/GreenCom/CPSCom/SmartData2018,Halifax,NS,Canada,July30-August3,2018.IEEE,980–987. [89] GiaNhuNguyen,NinHoLeViet,MohamedElhoseny,KShankar,BBGupta,andAhmedAAbdEl-Latif.2021. Secureblockchainenabled Cyber–physicalsystemsinhealthcareusingdeepbeliefnetworkwithResNetmodel.Journalofparallelanddistributedcomputing153(2021), 150–160. [90] TaiD.Nguyen,LongH.Pham,JunSun,YunLin,andQuangTranMinh.2020.sFuzz:anefficientadaptivefuzzerforsoliditysmartcontracts.In ICSE’20:42ndInternationalConferenceonSoftwareEngineering,Seoul,SouthKorea,27June-19July,2020.ACM,778–788. [91] T.Q.Nguyen,A.K.Das,andTranL.T.2019.NEOSmartContractforDrought-BasedInsurance.In2019IEEECanadianConferenceofElectricaland ComputerEngineering,CCECE2019,Edmonton,AB,Canada,May5-8,2019.IEEE,1–4. ManuscriptsubmittedtoACMSurveyonQualityAssuranceofSmartContracts 41 [92] IvicaNikolić,AashishKolluri,IlyaSergey,PrateekSaxena,andAquinasHobor.2018.Findingthegreedy,prodigal,andsuicidalcontractsatscale. InProceedingsofthe34thannualcomputersecurityapplicationsconference.653–663. [93] KingoftheEtherThrone.2016.KotET–Post-MortemInvestigation. https://www.kingoftheether.com/postmortem.html [94] SantiagoPalladino.2017.TheParityWalletHackExplained. https://blog.openzeppelin.com/on-the-parity-wallet-multisig-hack-405a8c12e8f7/ [95] DanielPalmer.2018.SpankChainLoses$40KinHackDuetoSmartContractBug. https://www.coindesk.com/markets/2018/10/09/spankchain-loses- 40k-in-hack-due-to-smart-contract-bug/ [96] QianqianPan,JunWu,AliKashifBashir,JianhuaLi,SahilVashisht,andRaheelNawaz.2022.Blockchainandaienabledconfigurablereflection resourceallocationforirs-aidedcoexistingdrone-terrestrialnetworks.IEEEWirelessCommunications29,6(2022),46–54. [97] AlfredoJ.PerezandSheraliZeadally.2022.Secureandprivacy-preservingcrowdsensingusingsmartcontracts:Issuesandsolutions.Comput.Sci. Rev.43(2022),100450. [98] DanielPerezandBenjaminLivshits.2021.SmartContractVulnerabilities:VulnerableDoesNotImplyExploited.InUSENIXSecuritySymposium. 1325–1341. [99] SergeyPetrov.2017.AnotherParityWallethackexplained. https://medium.com/@Pr0Ger/another-parity-wallet-hack-explained-847ca46a2e1c [100] JoshuaRPolanin,TerriDPigott,DorothyLEspelage,andJenniferKGrotpeter.2019.Bestpracticeguidelinesforabstractscreeninglarge-evidence systematicreviewsandmeta-analyses.ResearchSynthesisMethods10,3(2019),330–342. [101] PurathaniPraitheeshan,LeiPan,XiZheng,AlirezaJolfaei,andRobinDoss.2021.SolGuard:Preventingexternalcallissuesinsmartcontract-based multi-agentroboticsystems.InformationSciences579(2021),150–166. [102] SarahQahtan,KhaironiYatimSharif,HazuraZulzalil,MohdHafeezOsman,A.A.Zaidan,andHassanA.Alsattar.2023.Reviewofhealthcare industry4.0application-basedblockchainintermsofsecurityandprivacydevelopmentattributes:Comprehensivetaxonomy,openissuesand challengesandrecommendedsolution.J.Netw.Comput.Appl.209(2023),103529. [103] PengQian,ZhenguangLiu,QinmingHe,RogerZimmermann,andXunWang.2020.Towardsautomatedreentrancydetectionforsmartcontracts basedonsequentialmodels.IEEEAccess8(2020),19685–19695. [104] MeixunQu,XinHuang,XuChen,YiWang,XiaofengMa,andDaweiLiu.2018.FormalVerificationofSmartContractsfromthePerspectiveof Concurrency.InSmartBlockchain-FirstInternationalConference,SmartBlock2018,Tokyo,Japan,December10-12,2018,Proceedings(LectureNotesin ComputerScience,Vol.11373).Springer,32–43. [105] AnuRajandShivaPrakash.2022.Aprivacy-preservingauthentichealthcaremonitoringsystemusingblockchain.InternationalJournalofSoftware
ScienceandComputationalIntelligence(IJSSCI)14,1(2022),1–23. [106] HeidelindeRameder,MonikaDiAngelo,andGernotSalzer.2022.ReviewofautomatedvulnerabilityanalysisofsmartcontractsonEthereum. Front.Blockchain5(2022). [107] DuncanRiley.2020.$25MincryptocurrencystoleninhackofLendf.meandUniswap. https://siliconangle.com/2020/04/19/25m-cryptocurrency- stolen-hack-lendf-uniswap/ [108] MichaelRodler,WentingLi,GhassanO.Karame,andLucasDavi.2019.Sereum:ProtectingExistingSmartContractsAgainstRe-EntrancyAttacks. In26thAnnualNetworkandDistributedSystemSecuritySymposium,NDSS2019,SanDiego,California,USA,February24-27,2019.TheInternet Society. [109] MichaelRodler,WentingLi,GhassanO.Karame,andLucasDavi.2021.EVMPatch:TimelyandAutomatedPatchingofEthereumSmartContracts. In30thUSENIXSecuritySymposium,USENIXSecurity2021,August11-13,2021.USENIXAssociation,1289–1306. [110] MuhammadSaad,JeffreySpaulding,LaurentNjilla,CharlesA.Kamhoua,SachinShetty,DaeHunNyang,andDavidMohaisen.2020.Exploringthe AttackSurfaceofBlockchain:AComprehensiveSurvey.IEEECommun.Surv.Tutorials22,3(2020),1977–2008. [111] MdNazmusSaadat,SyedAbdulHalimSyedAbdulRahman,RasheedMohammadNassr,andMegatFZuhiri.2019.Blockchainbasedcrowdfunding systemsinMalaysianPerspective.InProceedingsofthe201911thinternationalconferenceoncomputerandautomationengineering.57–61. [112] ChristophSendner,HuiliChen,HosseinFereidooni,LukasPetzi,JanKönig,JasperStang,AlexandraDmitrienko,Ahmad-RezaSadeghi,andFarinaz Koushanfar.2023.SmarterContracts:DetectingVulnerabilitiesinSmartContractswithDeepTransferLearning..InNDSS. [113] KostyaSerebryany.2017.{OSS-Fuzz}-Google’scontinuousfuzzingserviceforopensourcesoftware.(2017). [114] SupriyaShakya,ArnabMukherjee,RajuHalder,AbyayanandaMaiti,andAmritaChaturvedi.2022.Smartmixmodel:machinelearning-based vulnerabilitydetectionofsoliditysmartcontracts.In2022IEEEinternationalconferenceonblockchain(Blockchain).IEEE,37–44. [115] ChaofanShou,JingLiu,DoudouLu,andKoushikSen.2024. Llm4fuzz:Guidedfuzzingofsmartcontractswithlargelanguagemodels. arXiv preprintarXiv:2401.11108(2024). [116] RajeshKumarSingh,RuchiMishra,ShivamGupta,andArchanaA.Mukherjee.2023.Blockchainapplicationsforsecuredandresilientsupply chains:Asystematicliteraturereviewandfutureresearchagenda.Comput.Ind.Eng.175(2023),108854. [117] CamilaSitonioandAlbertoNucciarelli.2018.Theimpactofblockchainonthemusicindustry.(2018). [118] Solidity.2023.CommonPatterns-WithdrawalfromContracts. https://coinmarketcap.com/currencies/ethereum/ [119] SamuelSteffen,BenjaminBichsel,MarioGersbach,NoaMelchior,PetarTsankov,andMartinT.Vechev.2019.zkay:SpecifyingandEnforcingData PrivacyinSmartContracts.InProceedingsofthe2019ACMSIGSACConferenceonComputerandCommunicationsSecurity,CCS2019,London,UK, November11-15,2019.ACM,1759–1776. [120] SamuelSteffen,BenjaminBichsel,andMartinT.Vechev.2022.Zapper:SmartContractswithDataandIdentityPrivacy.InProceedingsofthe2022 ACMSIGSACConferenceonComputerandCommunicationsSecurity,CCS2022,LosAngeles,CA,USA,November7-11,2022.ACM,2735–2749. ManuscriptsubmittedtoACM42 Weietal. [121] JakiaSultana,SayYenTeoh,StanKaranasios,etal.2022.Theimpactofblockchainonsupplychains:asystematicreview.AustralasianJournalof InformationSystems26(2022). [122] YuqiangSun,DaoyuanWu,YueXue,HanLiu,WeiMa,LyuyeZhang,MiaoleiShi,andYangLiu.2024.LLM4Vuln:AUnifiedEvaluationFramework forDecouplingandEnhancingLLMs’VulnerabilityReasoning.arXivpreprintarXiv:2401.16185(2024). [123] YuqiangSun,DaoyuanWu,YueXue,HanLiu,HaijunWang,ZhengziXu,XiaofeiXie,andYangLiu.2023.Whengptmeetsprogramanalysis: Towardsintelligentdetectionofsmartcontractlogicvulnerabilitiesingptscan.arXivpreprintarXiv:2308.03314(2023). [124] JenniferSykes,MickGrierson,RebeccaFiebrink,etal.2023.SeeingProgrammingSeeing:ExploringthePedagogicalValuesofFunctionalErrorsin CreativeCoding.(2023). [125] NickSzabo.1996.Smartcontracts:buildingblocksfordigitalmarkets.EXTROPY:TheJournalofTranshumanistThought,(16)18,2(1996),28. [126] WesleyJoon-WieTann,XingJieHan,SouravSenGupta,andYew-SoonOng.2018.Towardssafersmartcontracts:Asequencelearningapproach todetectingsecuritythreats.arXivpreprintarXiv:1811.06632(2018). [127] SergeiTikhomirov,EkaterinaVoskresenskaya,IvanIvanitskiy,RamilTakhaviev,EvgenyMarchenko,andYaroslavAlexandrov.2018.SmartCheck: StaticAnalysisofEthereumSmartContracts.In1stIEEE/ACMInternationalWorkshoponEmergingTrendsinSoftwareEngineeringforBlockchain, WETSEB@ICSE2018,Gothenburg,Sweden,May27-June3,2018.ACM,9–16.
[128] PalinaTolmach,YiLi,ShangweiLin,YangLiu,andZengxiangLi.2022.ASurveyofSmartContractFormalSpecificationandVerification.ACM Comput.Surv.54,7(2022),148:1–148:38. [129] ChristofFerreiraTorres,MathisBaden,RobertNorvill,andHugoJonker.2019.ÆGIS:SmartShieldingofSmartContracts.InProceedingsofthe 2019ACMSIGSACConferenceonComputerandCommunicationsSecurity,CCS2019,London,UK,November11-15,2019.ACM,2589–2591. [130] ChristofFerreiraTorres,RamiroCamino,andRaduState.2021.FrontrunnerJonesandtheRaidersoftheDarkForest:AnEmpiricalStudyof FrontrunningontheEthereumBlockchain.In30thUSENIXSecuritySymposium,USENIXSecurity2021,August11-13,2021.USENIXAssociation, 1343–1359. [131] ChristofFerreiraTorres,AntonioKenIannillo,ArthurGervais,andRaduState.2021.Confuzzius:Adatadependency-awarehybridfuzzerfor smartcontracts.In2021IEEEEuropeanSymposiumonSecurityandPrivacy(EuroS&P).IEEE,103–119. [132] ChristofFerreiraTorres,HugoJonker,andRaduState.2022.Elysium:Context-AwareBytecode-LevelPatchingtoAutomaticallyHealVulnerable SmartContracts.In25thInternationalSymposiumonResearchinAttacks,IntrusionsandDefenses,RAID2022,Limassol,Cyprus,October26-28,2022. ACM,115–128. [133] ChristofFerreiraTorres,JulianSchütte,andRaduState.2018.Osiris:Huntingforintegerbugsinethereumsmartcontracts.InProceedingsofthe 34thannualcomputersecurityapplicationsconference.664–676. [134] ChristofFerreiraTorres,MathisSteichen,andRaduState.2019.TheArtofTheScam:DemystifyingHoneypotsinEthereumSmartContracts.In 28thUSENIXSecuritySymposium,USENIXSecurity2019,SantaClara,CA,USA,August14-16,2019.USENIXAssociation,1591–1607. [135] HugoTouvron,ThibautLavril,GautierIzacard,XavierMartinet,Marie-AnneLachaux,TimothéeLacroix,BaptisteRozière,NamanGoyal,Eric Hambro,FaisalAzhar,etal.2023.Llama:Openandefficientfoundationlanguagemodels.arXivpreprintarXiv:2302.13971(2023). [136] AnnaVacca,AndreaDiSorbo,CorradoAaronVisaggio,andGerardoCanfora.2021. Asystematicliteraturereviewofblockchainandsmart contractdevelopment:Techniques,tools,andopenchallenges.J.Syst.Softw.174(2021),110891. [137] WeiWang,JingjingSong,GuangquanXu,YidongLi,HaoWang,andChunhuaSu.2021.ContractWard:AutomatedVulnerabilityDetectionModels forEthereumSmartContracts.IEEETrans.Netw.Sci.Eng.8,2(2021),1133–1144. [138] XinmingWang,JiahaoHe,ZhijianXie,GansenZhao,andShing-ChiCheung.2020. ContractGuard:DefendEthereumSmartContractswith EmbeddedIntrusionDetection.IEEETrans.Serv.Comput.13,2(2020),314–328. [139] GavinWoodetal.2014.Ethereum:Asecuredecentralisedgeneralisedtransactionledger.Ethereumprojectyellowpaper151,2014(2014),1–32. [140] ValentinWüstholzandMariaChristakis.2020.Harvey:agreyboxfuzzerforsmartcontracts.InESEC/FSE’20:28thACMJointEuropeanSoftware EngineeringConferenceandSymposiumontheFoundationsofSoftwareEngineering,VirtualEvent,USA,November8-13,2020.ACM,1398–1409. [141] ZenGo.2020.Bancorsmartcontractsvulnerability:It’snotover. https://zengo.com/bancor-smart-contracts-vulnerability-its-not-over/ [142] FanZhang,EthanCecchetti,KyleCroman,AriJuels,andElaineShi.2016.Towncrier:Anauthenticateddatafeedforsmartcontracts.InProceedings ofthe2016aCMsIGSACconferenceoncomputerandcommunicationssecurity.270–282. [143] LuyaoZhang,TianyuWu,SaadLahrichi,Carlos-GustavoSalas-Flores,andJiayiLi.2022.ADataSciencePipelineforAlgorithmicTrading:A ComparativeStudyofApplicationsforFinanceandCryptoeconomics.InIEEEInternationalConferenceonBlockchain,Blockchain2022,Espoo, Finland,August22-25,2022.IEEE,298–303. [144] ZhuoZhang,BrianZhang,WenXu,andZhiqiangLin.2023.Demystifyingexploitablebugsinsmartcontracts.In2023IEEE/ACM45thInternational ConferenceonSoftwareEngineering(ICSE).IEEE,615–627. [145] ZibinZheng,ShaoanXie,Hong-NingDai,WeiliChen,XiangpingChen,JianWeng,andMuhammadImran.2020.Anoverviewonsmartcontracts: Challenges,advancesandplatforms.FutureGenerationComputerSystems105(2020),475–491. [146] LiyiZhou,KaihuaQin,ChristofFerreiraTorres,DucVietLe,andArthurGervais.2021.High-FrequencyTradingonDecentralizedOn-Chain Exchanges.In42ndIEEESymposiumonSecurityandPrivacy,SP2021,SanFrancisco,CA,USA,24-27May2021.IEEE,428–445. [147] LiyiZhou,XihanXiong,JensErnstberger,StefanosChaliasos,ZhipengWang,YeWang,KaihuaQin,RogerWattenhofer,DawnSong,andArthur Gervais.2023.Sok:Decentralizedfinance(defi)attacks.In2023IEEESymposiumonSecurityandPrivacy(SP).IEEE,2444–2461. ManuscriptsubmittedtoACMSurveyonQualityAssuranceofSmartContracts 43 [148] ShunfanZhou,MalteMöser,ZheminYang,BenAdida,ThorstenHolz,JieXiang,StevenGoldfeder,YinzhiCao,MartinPlattner,XiaojunQin,etal. 2020.Anever-evolvinggame:Evaluationofreal-worldattacksanddefensesinethereumecosystem.In29thUSENIXSecuritySymposium(USENIX
Security20).2793–2810. [149] YuanZhuang,ZhenguangLiu,PengQian,QiLiu,XiangWang,andQinmingHe.2020.SmartContractVulnerabilityDetectionusingGraphNeural Network.InProceedingsoftheTwenty-NinthInternationalJointConferenceonArtificialIntelligence,IJCAI2020.ijcai.org,3283–3290. Received31Jun2024;revised10Aug2024;accepted5September2024 ManuscriptsubmittedtoACM
2311.00943 S￿￿￿￿￿: Taint-Based Call Graph Construction for Java Object Deserialization JOANNAC.S.SANTOS,UniversityofNotreDame,USA MEHDIMIRAKHORLI,UniversityofHawaiiatManoa,USA ALISHOKRI,VirginiaTech,USA Objectserializationanddeserializationarewidelyusedforstoringandpreservingobjectsin￿les,memory, ordatabaseaswellasfortransportingthemacrossmachines,enablingremoteinteractionamongprocesses andmanymore.Thismechanismreliesonre￿ection,adynamiclanguagethatintroducesseriouschallenges forstaticanalyses.Currentstate-of-the-artcallgraphconstructionalgorithmsdonotfullysupportobject serialization/deserialization,i.e.,theyareunabletouncoverthecallbackmethodsthatareinvokedwhen objectsareserializedanddeserialized.Sincecallgraphsareacoredatastructureformultipletypesofanalysis (e.g.,vulnerabilitydetection),anappropriateanalysiscannotbeperformedsincethecallgraphdoesnot capturehidden(vulnerable)pathsthatoccurviacallbackmethods.Inthispaper,wepresentS￿￿￿￿￿,an approachforhandlingserializationwithimprovedsoundnessinthecontextofcallgraphconstruction.Our approachreliesontaintanalysisandAPImodelingtoconstructsoundcallgraphs.Weevaluatedourapproach withrespecttosoundness,precision,performance,andusefulnessindetectinguntrustedobjectdeserialization vulnerabilities.OurresultsshowthatS￿￿￿￿￿cancreatesoundcallgraphswithrespecttoserializationfeatures. Theresultingcallgraphsdonotincursigni￿cantruntimeoverheadandwereshowntobeusefulforperforming identi￿cationofvulnerablepathscausedbyuntrustedobjectdeserialization. CCSConcepts:•Softwareanditsengineering Automatedstaticanalysis;Softwareveri￿cationand ! validation. AdditionalKeyWordsandPhrases:objectserialization,untrustedobjectdeserialization,taintanalysis,call graphs ACMReferenceFormat: JoannaC.S.Santos,MehdiMirakhorli,andAliShokri.2024.S￿￿￿￿￿:Taint-BasedCallGraphConstruction forJavaObjectDeserialization.Proc.ACMProgram.Lang.8,OOPSLA1,Article134(April2024),29pages. https://doi.org/10.1145/3649851 1 INTRODUCTION Staticprogramanalysisisakeycomponentoftoday’ssoftwareanalysistoolsthatbringautomation into activities such as defect localization and/or ￿nding (e.g., [Dolby et al. 2007; Thaller et al. 2020]), vulnerability detection (e.g., [Jovanovic et al. 2006; Liu Ping et al. 2011]), information ￿ow analysis [Sridharan et al. 2011], code refactoring (e.g., [Khatchadourian et al. 2019]), code navigation(e.g.,[Feldthausetal.2013]),codeclone￿nding(e.g.,[WyrichandBogner2019]),and optimization [Hines et al. 2005]. Such tools often perform multiple types of inter-procedural analysis,thatleveragecallgraphs–datastructuresthatindicatecaller-calleerelationships[Grove Authors’addresses:JoannaC.S.Santos,DepartmentofComputerScienceandEngineering,UniversityofNotreDame, NotreDame,IN,46556,USA,joannacss@nd.edu;MehdiMirakhorli,DepartmentofInformationandComputerSciences, UniversityofHawaiiatManoa,Honolulu,HI,96822,USA,mehdi23@hawaii.edu;AliShokri,DepartmentofElectricaland ComputerEngineering,VirginiaTech,Blacksburg,VA,24061,USA,Email:ashokri@vt.edu. Permissiontomakedigitalorhardcopiesofpartorallofthisworkforpersonalorclassroomuseisgrantedwithoutfee providedthatcopiesarenotmadeordistributedforpro￿torcommercialadvantageandthatcopiesbearthisnoticeand thefullcitationonthe￿rstpage.Copyrightsforthird-partycomponentsofthisworkmustbehonored.Forallotheruses, contacttheowner/author(s). ©2024Copyrightheldbytheowner/author(s). ACM2475-1421/2024/4-ART134 https://doi.org/10.1145/3649851 Proc.ACMProgram.Lang.,Vol.8,No.OOPSLA1,Article134.Publicationdate:April2024.134:2 JoannaC.S.Santos,MehdiMirakhorli,andAliShokri andChambers2001].However,priorworkshavedemonstratedthatconstructingacallgraphfor object-orientedprogramsisoftennon-trivial,expensiveand/ornon-feasibleduetotheusageof manydynamicprogramminglanguageconstructs.Forinstance,nativecalls,re￿ection,andobject serializationmakeitchallengingtostaticallyconstructasoundcallgraph[Alietal.2019;Kummita etal.2021;Reifetal.2019,2018;Smaragdakisetal.2015;Sridharanetal.2013]. Theseprogrammingconstructsareheavilyusedincontemporarysoftwaresystemsastheyenable the developers to link/load new class libraries, methods, and objects and extend the programs’ functionalities[Landmanetal.2017;Reifetal.2019].Ignoringsuchconstructsleadstounsound callgraphsinwhichfeasibleruntimepathsaremissed,andcallgraphscannotbeusedtoinferthe possibleexecutionfromthecode[Reifetal.2019,2018;Sridharanetal.2013].Totacklethisproblem, previousworksexploredcertainclassesoflanguagefeatures,suchasre￿ectionfeatures[Bodden etal.2011;Lietal.2014,2019;Smaragdakisetal.2015],native(opaque)code[Smaragdakisetal. 2015],dynamicproxies[Fourtounisetal.2018],andprogramswithRemoteMethodInvocation (RMI)[SharpandRountev2006].However,asdemonstratedbyReifetal.[Reifetal.2019,2018],a powerfulandfrequentlyusedprogrammingconstructthathasbeenleftoutfromtheprogramming analysistechniquesisserialization(anddeserialization)ofobjects. Objectserializationistheprocessofconverting(thestateof)anobjectintoanabstractrepre- sentation(e.g.,abytestreamorJSON,etc.).Thereverseprocessofreconstructingobjectsfromits abstractrepresentationiscalleddeserialization.Thisisawidelyusedmechanismforstoringand preservingobjectsin￿les,memory,ordatabaseaswellasfortransportingthemacrossmachines, enabling remote interaction among processes and many more. For example, the Android API providesaBundleobjectwhichcanbeusedforinter-processcommunicationbetweenappsas
wellasAndroid’sOSwithanindividualappviatheirserializationanddeserialization[Arztetal. 2014; Enck et al. 2014]. Moreover, object (de)serialization is also used to improve the system’s performancebysavingobjectsforlaterretrieval,e.g.,savingatrainedmachinelearningmodelto beusedlaterwithouttheneedtoretrainthealgorithm.Serializinganobjecthasotheradvantages, suchasbeingreadablebyapplicationsinotherlanguages.Forinstance,JavaScriptrunningina webbrowsercannativelyserializeanddeserializeobjectstoandfromJSON,thereforeinteract withotherapplicationswrittennon-JavaScriptlanguages. Although object serialization is widely used in many languages and commonly adopted by programmers,staticanalyzersdonotfullycoveranalysisofprogramswiththisconstructyet[Reif etal.2019,2018].Thisisparticularlyimportantconsideringthespikeofvulnerabilitiesrelated to untrusted object deserialization [Muñoz and Schneider 2018; Sayar et al. 2023; Schneider and Muñoz2016]thatcannotbeautomaticallydetectedbecausecallgraphsareunsound.Forexample, Apache’sLog4jsoftwarelibrary(versions2.0-beta9to2.14.1)hadanuntrustedobjectdeserialization vulnerabilitythatallowedremotecodeexecution.Thiswasacriticalvulnerabilitythata￿ected severalsoftwaresystems. Asdemonstratedbypreviousstudiesonthesoundnessofcallgraphconstructionapproaches[Reif etal.2019,2018]—guaranteeingthatallpossiblebehaviorsaremodeledinacallgraph—state-of-the- arttechniquesdonotsupportserialization-relatedoperations.Theyfallshortinhavingnodesand edgesthatrepresentcallback methodsthatareinvokedduringtheserializationordeserialization ofobjects.Therearemultiplereasonsonwhyitishardtohandlethislanguageconstruct: — Serializationanddeserializationuseseveraloverridablecallbackmethod(s).Thesecallbackmeth- odsareinvokedbytheJavaAPIusing“non-trivial”re￿ectivecallsthatcurrenttechniques[Land- manetal.2017]fortamingre￿ectiondonotaddress.Therefore,theresultingcallgraphunder- approximatestheprogram’sbehavior;theymisspotentialprogrampathsthroughthesecallback methods. Proc.ACMProgram.Lang.,Vol.8,No.OOPSLA1,Article134.Publicationdate:April2024.S￿￿￿￿￿:Taint-BasedCallGraphConstructionforJavaObjectDeserialization 134:3 — Theinvokedcallbacksduringdeserializationmethodsdependonthereceivedobject,whichis comingfromanexternalstream.Thevaluesandinternal￿eldtypesareonlyknownatruntime whentheobjectdeserializationoccurs. — Theexternalstreammayincludeobjectswhosetypesarenotobservedstatically,i.e.,theyare availableintheclasspath(importedlibraries,orJavabuilt-inAPI)butwereneveractuallyused (instantiated)intheapplicationscope.Atypicalstaticanalysiswouldconsiderthesetypesas unused. Therefore,existingtechniquesonaddressingre￿ectionshadfailedtoaddresscall-graphgenera- tionwiththepresenceofobjectserialization/de-serialization[Reifetal.2019].Assuch,potential program￿owsaredisregardedinexistingcallgraphconstructionalgorithms.Sincethecallgraph isacoredatastructureinperformingmanyinter-proceduralcodeanalyses,theunderlyingclient would su￿er with the unsoundness. In use-cases such as detection of untrusted deserialization vulnerabilities,anappropriateanalysiscannotbeperformedsincethecallgraphdoesnotcapture hidden(vulnerable)pathsthatoccurviacallbackmethods.Therearetwoalgorithmsthat(partially) handleserializationconstructs(i.e.,CHA[Deanetal.1995]andRTA[BaconandSweeney1996])but theyareimprecise;theyabstractprogramexecutionstoconsidermorepathsthanthosefeasiblein theprogram.Therefore,theyintroducespuriousnodesandedges,renderinglargecallgraphs.Relying on such algorithms for downstream analyses (e.g., vulnerability detection) makes the analysis imprecise,resultinginahighamountoffalsepositives. A recent line of work [Santos et al. 2021, 2020], presented an approach (named S￿￿￿￿) for providing support for serialization-related features. Although S￿￿￿￿ aids the static analyses of programsthatuseJava’sserialization/deserializationAPI,itisnotenoughto￿ndhidden(poten- tially)maliciouspathsintheprogram.S￿￿￿￿reliesonAPImodelingforabstractingtheserializa- tion/deserializationprotocolwhichdictatescallbackmethodscontrolanddata￿ow.Speci￿cally,it reliesondowncastsintheprogramtoinferthecallbacksinvokedduringdeserialization.However, maliciousobjectsoftenviolatedowncastsandarecraftedinsuchwaythatittriggerstheexploit during deserialization,i.e.,theexploitexecutesbeforethedowncastisperformed[Dietrichetal. 2017a]. Therefore,weintroduceinthispaperS￿￿￿￿￿,anovelapproachthathandlesthechallengeof constructingcallgraphsforprogramsthatuseserializationfeatures.Speci￿cally,wearefocusing onimprovingthecallgraph’ssoundnessforJavaprogramswithrespecttoserializationanddeserial- izationcallbackswithoutgreatlya￿ectingitsprecision.S￿￿￿￿￿performsanoveltaint-basedcall graph construction, which relies on the taint state of variables when computing possible dispatchesforcallbackmethods. Thecontributionsofthisworkare: — a novel taint-based call graph construction algorithm to improve call graphs’ soundness with respecttodeserializationcallbacks.Itisagnostictotheunderlyingpointeranalysismethodused toconstructacallgraph,anditismeanttocomplementthem. — anevaluationoftheapproach’ssoundness,precision,andscalability.Ourexperimentsdemon- stratedthatourapproachsoundlyhandledallthesixdi￿erentcallbacksthatcanbeinvoked duringserializationordeserialization. — apubliclyavailableimplementationof S￿￿￿￿￿1 Therestofthispaperisorganizedasfollows:Section2describestheserializationanddeserial- izationmechanismandthechallengesincreatingacallgraphthatissoundwithrespecttothis feature.Section3explainsourapproach.Subsequently,Section4presentstheevaluationofthe 1ThescriptstoreproducethepaperresultsandS￿￿￿￿￿’simplementationareavailableonourGitHubrepositoryhttps:
//github.com/s2e-lab/seneca/andZenodohttps://zenodo.org/doi/10.5281/zenodo.10464129. Proc.ACMProgram.Lang.,Vol.8,No.OOPSLA1,Article134.Publicationdate:April2024.134:4 JoannaC.S.Santos,MehdiMirakhorli,andAliShokri approachwhereasSection5presentstheresults.Section6contextualizesourapproachwithinthe state-of-theart.Section7elaboratesonthethreatstothevalidityofthiswork.Section8concludes thepaperandmakes￿nalconsiderations. 2 BACKGROUND Multipleprogramminglanguages(e.g.,Ruby,Python,PHP,andJava)allowobjectstobeconverted intoanabstractrepresentation,aprocesscalledobjectserialization(or“marshalling”).Theprocess of reconstructing an object from its underlying abstract representation is called object deseri- alization (or “unmarshalling”). Serialization and deserialization of objects are widely used for inter-processcommunicationandforimprovingthecodes’performancebysavingobjectstobe reusedlater(e.g.,savingmachinelearningmodels[Ten2023]). Duringobjectserialization/deserialization,methodsfromtheobjects’classesmaybeinvoked. For instance, classes’ constructors, getter/setter methods, or methods with speci￿c signatures maybeinvokedwhenreconstructingtheobject.Thesearethecallbackmethodsoftheserializa- tion/deserializationmechanism.Eachprogramminglanguagehastheirownobjectserialization and deserialization protocol, abstract representation, and callback methods. The Java’s default serializationanddeserializationprotocolisthoroughlydescribedattheirspeci￿cationpage[Oracle 2010].Webrie￿ypresentthismechanisminthenextsubsection. 2.1 JavaSerializationAPI The default Java’s Serialization API converts a snapshot of an object graph into a byte stream. Duringthisprocess,onlydataisserialized(i.e.,theobject’s￿elds)whereasthecodeassociated withtheobject’sclass(i.e.,methods)iswithintheclasspathofthereceiver[SchneiderandMuñoz 2016].Allnon-transient andnon-static￿eldsareserializedbydefault. TheclassesObjectInputStreamandObjectOutputStreamcanbeusedfordeserializingand serializinganobject,respectively.Theycanonlyserialize/deserializeobjectswhoseclassimplements thejava.io.Serializableinterface.IfimplementedbyaSerializableclass,themethodslisted belowcanbeinvokedbyJavaduring objectserializationand/ordeserialization: void writeObject(ObjectOutputStream):itcustomizestheserializationoftheobject’sstate. • Object writeReplace(): this method replaces the actual object that will be written in the • stream. void readObject(ObjectInputStream):itcustomizestheretrievalofanobject’sstatefrom • thestream. void readObjectNoData(): in the exceptional situation that a receiver has a subclass in its • classpathbutnotitssuperclass,thismethodisinvokedtoinitializetheobject’sstate. Object readResolve(): this is the inverse of writeResolve. It allows classes to replace a • speci￿cinstancethatisbeingreadfromthestream. void validateObject():itvalidatesanobjectafteritisdeserialized.Forthiscallbacktobe • invoked,theclasshastoalsoimplementtheObjectInputValidationinterfaceandregisterthe validatorbyinvokingthemethodregisterValidationfromtheObjectInputStreamclass. Figures1and2depictthesequenceofthesecallbackmethodinvocations.Asdepictedinthis ￿gure, during serialization of an object, the callback methods writeReplace and writeObject are invoked(iftheseareimplementedbytheclassoftheobjectbeingdeserialized).Similarly,during objectdeserializaton,fourcallbackmethodscanbeinvoked,namely,readObject,readObjectNoData, readResolve,andvalidateObject. Proc.ACMProgram.Lang.,Vol.8,No.OOPSLA1,Article134.Publicationdate:April2024.S￿￿￿￿￿:Taint-BasedCallGraphConstructionforJavaObjectDeserialization 134:5
(cid:29)(cid:36)(cid:83)(cid:83)(cid:79)(cid:76)(cid:70)(cid:68)(cid:87)(cid:76)(cid:82)(cid:81)(cid:38)(cid:79)(cid:68)(cid:86)(cid:86) (cid:29)(cid:50)(cid:69)(cid:77)(cid:72)(cid:70)(cid:87)(cid:50)(cid:88)(cid:87)(cid:83)(cid:88)(cid:87)(cid:54)(cid:87)(cid:85)(cid:72)(cid:68)(cid:80) (cid:29)(cid:54)(cid:72)(cid:85)(cid:76)(cid:68)(cid:79)(cid:76)(cid:93)(cid:68)(cid:69)(cid:79)(cid:72)(cid:38)(cid:79)(cid:68)(cid:86)(cid:86) (cid:29)(cid:36)(cid:83)(cid:83)(cid:79)(cid:76)(cid:70)(cid:68)(cid:87)(cid:76)(cid:82)(cid:81)(cid:38)(cid:79)(cid:68)(cid:86)(cid:86) (cid:29)(cid:50)(cid:69)(cid:77)(cid:72)(cid:70)(cid:87)(cid:44)(cid:81)(cid:83)(cid:88)(cid:87)(cid:54)(cid:87)(cid:85)(cid:72)(cid:68)(cid:80) (cid:29)(cid:54)(cid:72)(cid:85)(cid:76)(cid:68)(cid:79)(cid:76)(cid:93)(cid:68)(cid:69)(cid:79)(cid:72) (cid:29)(cid:50)(cid:69)(cid:77)(cid:72)(cid:70)(cid:87)(cid:44)(cid:81)(cid:83)(cid:88)(cid:87)(cid:57)(cid:68)(cid:79)(cid:76)(cid:71)(cid:68)(cid:87)(cid:76)(cid:82)(cid:81) (cid:20) (cid:58)(cid:85)(cid:76)(cid:87)(cid:72)(cid:3)(cid:82)(cid:69)(cid:77)(cid:72)(cid:70)(cid:87)(cid:3)(cid:87)(cid:82)(cid:3)(cid:76)(cid:81)(cid:83)(cid:88)(cid:87)(cid:3)(cid:86)(cid:87)(cid:85)(cid:72)(cid:68)(cid:80) (cid:20) (cid:53)(cid:72) (cid:76)(cid:68) (cid:81)(cid:71) (cid:83)(cid:3) (cid:88)(cid:82) (cid:87)(cid:69) (cid:3)(cid:86)(cid:77)(cid:72) (cid:87)(cid:85)(cid:70) (cid:72)(cid:87) (cid:68)(cid:3)(cid:73) (cid:80)(cid:85)(cid:82)(cid:80) (cid:90)(cid:85)(cid:76)(cid:87)(cid:72)(cid:50)(cid:69)(cid:77)(cid:72)(cid:70)(cid:87)(cid:11)(cid:31)(cid:3)(cid:82)(cid:69)(cid:77)(cid:72)(cid:70)(cid:87)(cid:3)(cid:33)(cid:12) (cid:85)(cid:72)(cid:68)(cid:71)(cid:50)(cid:69)(cid:77)(cid:72)(cid:70)(cid:87)(cid:11)(cid:12) (cid:90)(cid:85)(cid:76)(cid:87)(cid:72)(cid:38)(cid:79)(cid:68)(cid:86)(cid:86)(cid:39)(cid:72)(cid:86)(cid:70)(cid:11)(cid:17)(cid:17)(cid:17)(cid:12) (cid:53)(cid:72)(cid:68)(cid:71)(cid:3)(cid:70)(cid:79)(cid:68)(cid:86)(cid:86)(cid:3)(cid:71)(cid:72)(cid:86)(cid:70)(cid:85)(cid:76)(cid:83)(cid:87)(cid:82)(cid:85) (cid:85)(cid:72)(cid:68)(cid:71)(cid:38)(cid:79)(cid:68)(cid:86)(cid:86)(cid:39)(cid:72)(cid:86)(cid:70)(cid:11)(cid:17)(cid:17)(cid:17)(cid:12) (cid:21)(cid:58)(cid:85)(cid:76)(cid:87)(cid:72)(cid:3)(cid:70)(cid:79)(cid:68)(cid:86)(cid:86)(cid:3)(cid:71)(cid:72)(cid:86)(cid:70)(cid:85)(cid:76)(cid:83)(cid:87)(cid:82)(cid:85) (cid:21) (cid:73)(cid:85)(cid:82)(cid:80)(cid:3)(cid:87)(cid:75)(cid:72)(cid:3)(cid:86)(cid:87)(cid:85)(cid:72)(cid:68)(cid:80) (cid:87)(cid:82)(cid:3)(cid:87)(cid:75)(cid:72)(cid:3)(cid:86)(cid:87)(cid:85)(cid:72)(cid:68)(cid:80)
(cid:22) (cid:53)(cid:72)(cid:83)(cid:79)(cid:68)(cid:70)(cid:72)(cid:3)(cid:90)(cid:85)(cid:76)(cid:87)(cid:87)(cid:72)(cid:81)(cid:3)(cid:50)(cid:69)(cid:77)(cid:72)(cid:70)(cid:87) (cid:22) (cid:53)(cid:72)(cid:86)(cid:87)(cid:82)(cid:85)(cid:72)(cid:3)(cid:82)(cid:69)(cid:77)(cid:72)(cid:70)(cid:87)(cid:10)(cid:86)(cid:3)(cid:73)(cid:76)(cid:72)(cid:79)(cid:71)(cid:86) (cid:90)(cid:85)(cid:76)(cid:87)(cid:72)(cid:53)(cid:72)(cid:83)(cid:79)(cid:68)(cid:70)(cid:72)(cid:11)(cid:17)(cid:17)(cid:17)(cid:12) (cid:85)(cid:72)(cid:68)(cid:71)(cid:50)(cid:69)(cid:77)(cid:72)(cid:70)(cid:87)(cid:11)(cid:17)(cid:17)(cid:17)(cid:12) (cid:23) (cid:53)(cid:72)(cid:86)(cid:87)(cid:82)(cid:85)(cid:72)(cid:3)(cid:82)(cid:69)(cid:77)(cid:72)(cid:70)(cid:87)(cid:10)(cid:86)(cid:3)(cid:73)(cid:76)(cid:72)(cid:79)(cid:71)(cid:86) (cid:90)(cid:85)(cid:76)(cid:87)(cid:72)(cid:50)(cid:69)(cid:77)(cid:72)(cid:70)(cid:87)(cid:11)(cid:17)(cid:17)(cid:17)(cid:12) (cid:23) (cid:44)(cid:81)(cid:76)(cid:87)(cid:76)(cid:68)(cid:79)(cid:76)(cid:93)(cid:72)(cid:3)(cid:82)(cid:69)(cid:77)(cid:72)(cid:70)(cid:87)(cid:10)(cid:86)(cid:3)(cid:73)(cid:76)(cid:72)(cid:79)(cid:71)(cid:86) (cid:85)(cid:72)(cid:68)(cid:71)(cid:50)(cid:69)(cid:77)(cid:72)(cid:70)(cid:87)(cid:49)(cid:82)(cid:39)(cid:68)(cid:87)(cid:68)(cid:11)(cid:17)(cid:17)(cid:17)(cid:12) (cid:24) (cid:53)(cid:72)(cid:83)(cid:79)(cid:68)(cid:70)(cid:72)(cid:3)(cid:85)(cid:72)(cid:86)(cid:87)(cid:82)(cid:85)(cid:72)(cid:71)(cid:3)(cid:82)(cid:69)(cid:77)(cid:72)(cid:70)(cid:87) (cid:85)(cid:72)(cid:68)(cid:71)(cid:53)(cid:72)(cid:86)(cid:82)(cid:79)(cid:89)(cid:72)(cid:11)(cid:17)(cid:17)(cid:17)(cid:12) (cid:25) (cid:57)(cid:68)(cid:79)(cid:76)(cid:71)(cid:68)(cid:87)(cid:72)(cid:3)(cid:82)(cid:69)(cid:77)(cid:72)(cid:70)(cid:87) (cid:89)(cid:68)(cid:79)(cid:76)(cid:71)(cid:68)(cid:87)(cid:72)(cid:50)(cid:69)(cid:77)(cid:72)(cid:70)(cid:87)(cid:11)(cid:12) (cid:26) (cid:38)(cid:68)(cid:86)(cid:87)(cid:3)(cid:68)(cid:81)(cid:71) (cid:88)(cid:86)(cid:72)(cid:3)(cid:87)(cid:75)(cid:72)(cid:3)(cid:82)(cid:69)(cid:77)(cid:72)(cid:70)(cid:87) (cid:85)(cid:72)(cid:70)(cid:82)(cid:81)(cid:86)(cid:87)(cid:85)(cid:88)(cid:70)(cid:87)(cid:72)(cid:71)(cid:3)(cid:82)(cid:69)(cid:77)(cid:72)(cid:70)(cid:87) Fig.1. Callbacksinvokedduringserialization Fig.2. Callbacksinvokedduringdeserialization 1class Pet implements Serializable { 19class SerializationExample{ 2 protected String name; 20 public static void main(String[] args) throws Exception { 3} 21 Shelter s1 = new Shelter(Arrays.asList(new Dog(Max), 4class Cat extends Pet{ 22 new Cat(Joy))); 5 private void readObject(ObjectInputStream s){ 23 File f = new File(pets.txt); 6 /* ... */ 24 FileOutputStream fos = new FileOutputStream(f); 7 } 25 ObjectOutputStream out = new ObjectOutputStream(fos); 8 private void writeObject(ObjectOutputStream s){26 out.writeObject(s1); 9 /* ... */ 27 } 10 } 28} 11} 29class DeserializationExample{ 12class Dog extends Pet{ 30 public static void main(String[] args) throws Exception { 13 private Object readResolve(){ /* ... */ } 31 File f = new File(pets.txt);
14 private Object writeReplace(){ /* ... */ } 32 FileInputStream fs = new FileInputStream(f); 15} 33 ObjectInputStream in = new ObjectInputStream(fs); 16class Shelter implements Serializable{ 34 Shelter s2 = (Shelter) in.readObject(); 17 private List<Pet> pets; 35 } 18} 36} Listing1. Objectserializationanddeserializationexample DemonstrativeExample. Listing1hasthreeserializableclasses2:Dog,CatandShelter.Twoofthese classeshaveserializationcallbackmethods(lines5-10and13-14).Thecodeatlines21-26serializes aShelterobjects1intoa￿le,whosepathisprovidedasprogramarguments.Thecodeinstantiates aFileOutputStreamandpassestheinstancetoanObjectOutputStream’sconstructorduringits instantiation.Then,itcallswriteObject(s1),whichserializess1asabytestreamandsavesit into a ￿le. Since the object s1 has a list ￿eld (pets) that contains two objects (a Cat and a Dog instance)thecallbackmethodsoftheseclassesinvoked. Themainmethodatline30deserializesthisobjectfromthe￿le.ItcreatesanObjectInputStream instanceandinvokesthemethodreadObject(),whichreturnsanobjectconstructedfromthe text￿le.ThereturnedobjectiscastedtotheShelterclasstype.Duringthedeserialization,the methodsreadObjectandreadResolvefromtheCatandDogclassesareinvoked,respectively. UntrustedObjectDeserialization. Toillustratehowaseeminglyharmlessmechanismcanleadto seriousvulnerabilities,considerthecasethattheprograminListing1containstwomoreserializable 2Weonlyshowtheir￿eldsandcallbackmethodsduetospaceconstraints. Proc.ACMProgram.Lang.,Vol.8,No.OOPSLA1,Article134.Publicationdate:April2024.8 InetSocketAddress a = new InetSocketAddress(bis); 9 if (channel.connect(true)!= null) { 10 InputStream is = channel.socket().getInputStream(); 11 ObjectInput in = new ObjectInputStream("localhost", 12345); 12 User u = (User) in.readObject(); 13 //... 14 } else { 15 // … 16 } 17 18 } //... 19 20 } CacheManager cmdTask = new CommandTask("calc.exe"); CacheManager cm = new CacheManager(cmdTask); ⇩ Serialized Malicious Object (in Base 64): rO0ABXNyAAxDYWNoZU1hbmFnZXKJEnhhKTAgjQIAAUwACGluaXR Ib29rdAAUTGphdmEvbGFuZy9SdW5uYWJsZTt4cHNyAAtDb21tYW 5kVGFza+/CvHajIAP1AgABTAAHY29tbWFuZHQAEkxqYXZhL2xhb mcvU3RyaW5nO3hwdAAIY2FsYy5leGU= ⇩ Call Stack: IndexServlet.doGet(…) java.io.ObjectInputStream.readObject() CacheManager.readObject() CommandTask.run() Runtime.exec(…) 1 34:6 JoannaC.S.Santos,MehdiMirakhorli,andAliShokri Malicious Object: File.ser: Call Stack: Task t = new Task("rm -rf . "); rO0ABXNyAAxDYWNoZU1hbmFnZ DeserializationExample.main(…) CacheManager cm = new CacheManager(t); ⇨ XKJEnhhKTAgjQIAAUwACGluaX⇨ java.io.ObjectInputStream.readObject() RIb29rdAAUTGphdmEvbGFuZy9 CacheManager.readObject() SdW5uYWJsZTt4c… Task.run() Runtime.exec(…) Fig.3. Maliciousserializedobjectusedtotriggeraremotecodeexecution classes(CacheManagerandTask),asshowninListing2.AnattackerwouldcreateaCacheManager object(cm)asshowninFigure3.Then,theattackerserializesandencodesthismaliciousobject (cm)intoatext￿leandspeci￿esitasaprogramargumentforthemainmethodinListing1.When theprogramreadstheobjectfromthe￿le,ittriggersthechainofmethodcallsdepictedinFigure3. Thissequenceofmethodcallsendsinanexecutionsink(Runtime.getRuntime.exec()online8 oftheTaskclassinListing2). 1public class CacheManager implements Serializable { 1public class Task implements Runnable, Serializable { 2 private Runnable initHook; 2 private String command; 3 public CacheManager(Runnable initHook) { 3 4 this.initHook = initHook; 4 public Task(String command) { 5 } 5 this.command = command; 6 private void readObject(ObjectInputStream ois) { 6 } 7 ois.defaultReadObject(); 7 public void run() { 8 initHook.run(); 8 Runtime.getRuntime().exec(command); 9 } 9 } 10} 10} Listing2. Gadgetclassesthatcanbeusedtoexploitanuntrustedobjectdeserializationvulnerablity Although this request with a malicious serialized object results in a ClassCastException, themaliciouscommandwillbeexecutedanyway,becausethetypecastcheckoccursa￿er the deserialization process took place. As we can see from this example, classes can be specially combinedtocreateachainofmethodcalls.Theseclassesarecalled“gadgetclasses” astheyare usedtobootstrapachainofmethodcallsthatwillendinanexecutionsink. 2.2 ChallengesforCallGraphConstruction FromtheexamplesshowninSection2.1,weobservetwomajorchallengesthatshouldbehandled byastaticanalyzerinordertoconstructasoundcallgraphwithrespecttoserialization-related features:(i)thecallbackmethodsthatareinvokedduringobjectserialization/deserialization;and (ii)the￿eldswithintheclasscanbeallocatedinunexpectedways,andtheydictatewhich callbacksareinvokedatruntime.Forinstance,ifthecodesnippetinListing1hadonlythecat objectinthelist(line22),thenthecallstoreadResolve/writeReplacemethodsinDogwouldnot bemade. Existingpointeranalysisalgorithmsleverageallocationinstructions(i.e.,new T())withinthe programtoinferthepossibleruntimetypesforobjects[Bastanietal.2019;Fengetal.2015;Heintze andTardieu2001;Hind2001;KastrinisandSmaragdakis2013;LhotákandHendren2006;Rountev etal.2001;SmaragdakisandKastrinis2018].However,aswedemonstratedintheexamples,the allocationsofobjectsandtheir￿eldsandinvocationstocallbackmethodsaremadeon-the-￿yby Java’sserialization/deserializationmechanism.Duringstaticanalysis,wecanonlypinpointthat thereisanInputStreamobjectthatprovidesastreamofbytesfromasource(e.g.,a￿le,socket,
etc.)toanObjectInputStreaminstance,butthecontentsofthisstreamareuncertain.Hence,the Proc.ACMProgram.Lang.,Vol.8,No.OOPSLA1,Article134.Publicationdate:April2024.S￿￿￿￿￿:Taint-BasedCallGraphConstructionforJavaObjectDeserialization 134:7 deserialized object and its state are unknown (i.e., the allocations within its ￿elds). As a result, existingstaticanalysesfailtosupportserialization-relatedfeatures. 3 SENECA:TAINT-BASEDCALLGRAPHCONSTRUCTIONFOROBJECT DESERIALIZATION (cid:24)(cid:96)(cid:108)(cid:115)(cid:114) (cid:48)(cid:72)(cid:87)(cid:75)(cid:82)(cid:71) (cid:82)(cid:88)(cid:87)(cid:17)(cid:90)(cid:85)(cid:76)(cid:87)(cid:72)(cid:50)(cid:69)(cid:77)(cid:72)(cid:70)(cid:87)(cid:11)(cid:82)(cid:12) (cid:76)(cid:81)(cid:17)(cid:85)(cid:72)(cid:68)(cid:71)(cid:50)(cid:69)(cid:77)(cid:72)(cid:70)(cid:87)(cid:11)(cid:12) (cid:62)(cid:73)(cid:73)(cid:2)(cid:95)(cid:99)(cid:111)(cid:75)(cid:2)(cid:95)(cid:75)(cid:114)(cid:82)(cid:99)(cid:73)(cid:112) (cid:39)(cid:76)(cid:86)(cid:83)(cid:68)(cid:87)(cid:70)(cid:75) (cid:51)(cid:85)(cid:82)(cid:74)(cid:85)(cid:68)(cid:80) (cid:62)(cid:73)(cid:73) (cid:114)(cid:99)(cid:2)(cid:70)(cid:75)(cid:2)(cid:75)(cid:122)(cid:108)(cid:93)(cid:99)(cid:111)(cid:75)(cid:73) (cid:49)(cid:75)(cid:111)(cid:83)(cid:62)(cid:93)(cid:83)(cid:126)(cid:62)(cid:114)(cid:83)(cid:99)(cid:96)(cid:2)(cid:108)(cid:99)(cid:83)(cid:96)(cid:114)(cid:112) (cid:14)(cid:75)(cid:112)(cid:75)(cid:111)(cid:83)(cid:62)(cid:93)(cid:83)(cid:126)(cid:62)(cid:114)(cid:83)(cid:99)(cid:96)(cid:2)(cid:108)(cid:99)(cid:83)(cid:96)(cid:114)(cid:112) (cid:75)(cid:96)(cid:114)(cid:111)(cid:123)(cid:108)(cid:99)(cid:83)(cid:96)(cid:114)(cid:112) (cid:71)(cid:99)(cid:96)(cid:114)(cid:75)(cid:122)(cid:114)(cid:185)(cid:2)(cid:99)(cid:70)(cid:90)(cid:75)(cid:71)(cid:114)(cid:185)(cid:2)(cid:83)(cid:96)(cid:120)(cid:99)(cid:71)(cid:62)(cid:114)(cid:83)(cid:99)(cid:96) (cid:36)(cid:115)(cid:114)(cid:108)(cid:115)(cid:114) (cid:114)(cid:99)(cid:2)(cid:121)(cid:99)(cid:111)(cid:92)(cid:93)(cid:83)(cid:112)(cid:114)(cid:223)
(cid:40)(cid:81)(cid:87)(cid:85)(cid:92)(cid:83)(cid:82)(cid:76)(cid:81)(cid:87)(cid:86) (cid:40) (cid:40)(cid:81) (cid:91)(cid:87) (cid:87)(cid:85) (cid:85)(cid:92) (cid:68)(cid:83) (cid:70)(cid:82) (cid:87)(cid:76)(cid:76) (cid:82)(cid:81) (cid:81)(cid:87)(cid:86) (cid:89)(cid:3) (cid:3)(cid:96)(cid:3) (cid:3)(cid:82)(cid:3) (cid:3)(cid:87) (cid:18)(cid:76)(cid:75) (cid:18)(cid:71) (cid:3)(cid:85) (cid:17)(cid:3) (cid:17)(cid:82)(cid:80) (cid:17)(cid:90)(cid:68)(cid:86)(cid:76)(cid:3)(cid:81)(cid:40)(cid:11)(cid:91)(cid:54)(cid:70)(cid:87)(cid:85)(cid:72)(cid:76)(cid:83)(cid:81)(cid:87)(cid:74)(cid:76)(cid:82)(cid:62)(cid:64)(cid:81)(cid:3)(cid:68)(cid:3)(cid:94)(cid:85)(cid:74)(cid:86)(cid:12) (cid:36)(cid:51) (cid:81)(cid:82) (cid:68)(cid:76)(cid:81) (cid:79)(cid:92)(cid:87) (cid:86)(cid:72) (cid:76)(cid:85) (cid:86) (cid:70)(cid:68)(cid:79)(cid:79)(cid:3)(cid:74)(cid:85)(cid:68)(cid:83)(cid:75)(cid:3)(cid:76) (cid:50)(cid:88) (cid:48)(cid:87)(cid:83) (cid:82)(cid:88) (cid:71)(cid:87)(cid:3) (cid:72)(cid:54) (cid:79)(cid:76)(cid:87) (cid:81)(cid:85)(cid:72) (cid:74)(cid:68)(cid:80) (cid:44)(cid:81)(cid:55)(cid:68) (cid:48)(cid:83)(cid:76) (cid:88)(cid:81) (cid:82)(cid:87)(cid:87) (cid:71)(cid:3)(cid:16) (cid:54) (cid:72)(cid:69) (cid:87) (cid:79)(cid:68) (cid:85) (cid:76)(cid:81)(cid:86) (cid:72) (cid:74)(cid:72) (cid:68)(cid:71) (cid:80) (cid:58)(cid:82)(cid:85)(cid:78)(cid:3)(cid:79)(cid:76)(cid:86)(cid:87)(cid:3) (cid:51)(cid:82)(cid:76)(cid:81)(cid:87)(cid:72)(cid:85) (cid:55)(cid:68)(cid:76)(cid:81)(cid:87)(cid:72)(cid:71)(cid:3)(cid:51)(cid:82)(cid:76)(cid:81)(cid:87)(cid:72)(cid:85)(cid:86) (cid:38)(cid:68)(cid:79)(cid:79)(cid:3)(cid:74)(cid:85)(cid:68)(cid:83)(cid:75) (cid:36)(cid:81)(cid:68)(cid:79)(cid:92)(cid:86)(cid:76)(cid:86) (cid:82)(cid:73)(cid:3)(cid:80)(cid:72)(cid:87)(cid:75)(cid:82)(cid:71)(cid:86) (cid:55)(cid:68)(cid:76)(cid:81)(cid:87) (cid:48)(cid:72)(cid:87)(cid:75)(cid:82)(cid:71) (cid:36)(cid:81)(cid:68)(cid:79)(cid:92)(cid:86)(cid:76)(cid:86) Fig.4. Ourserialization-awareapproachforconstructingcallgraphs(S￿￿￿￿￿) To support serialization-related features, S￿￿￿￿￿ employs an on-the-￿y iterative call graph constructiontechnique[Groveetal.1997],asdepictedinFigure4.Itinvolvestwomajorphases: 1 Iteratingoveraworklistofmethodstocreatetheinitialcallgraphusinganunderlyingpointer analysismethod; 2 Re￿nementoftheinitialcallgraphbymakingasetofassumptionsperformed iterativelyuntila￿xpointisreached(i.e.,whentherearenomoremethodsleftintheworklistto bevisited). 3.1 Phase1:InitialCallGraphConstruction S￿￿￿￿￿ ￿rst takes as input a CSV ￿le with method signatures for the program’s entrypoints, whicharethemethodsthatstarttheprogram’sexecution(e.g.,main()).Theresultofthisstepisa setofentrypointmethods< ⇢ addedtoourworklist .Thisworklisttracksthemethods< 2 W underacontext2 thathavetobetraversedandanalyzed,i.e., <,2 ,whereacontext2 is h i 2W anabstractionoftheprogram’sstate.Sincetheworklist tracksmethodswithinacontext,the W entrypointsmethodsaddedto areassignedaglobalcontext,whichwedenoteas .Hence,the W ; worklistisinitializedas: = <, < ⇢ W {h ;i |8 2 } Startingfromtheentrypointmethodsidenti￿ed,S￿￿￿￿￿constructsaninitial(unsound)call graph (i.e., call graph ) using the underlying pointer analysis algorithm selected by the client 0 analysis(e.g.,n-CFA).Eachmethodintheworklist <,2 isconvertedintoanIntermediary h i 2W Representation(IR)inStaticSingleAssignmentform(SSA)[Cytronetal.1991].Eachinstructionin
thisIRisvisitedfollowingtherulesbytheunderlyingpointeranalysisalgorithm3.Whenanalyzing aninstancemethodinvocationinstruction(i.e.,x = o.g(0 1,0 2,...,0 =)),S￿￿￿￿￿computesthe possibledispatches(calltargets)forthemethod6asfollows:targets = 38B?0C2⌘ ?C >,2 ,6 . ( (h i) ) Thisdispatchmechanismtakesintoaccountthecurrentpoints-tosetfortheobject> atthecurrent context2 aswellasthedeclaredtarget6.Iftheinvocationinstructionoccursataserialization or deserialization point, then the38B?0C2⌘ function implemented by our approach creates a synthetic method to model the runtime behavior for the readObject() and writeObject() fromtheclassesObjectInputStreamandObjectOutputStream,respectively. These synthetic models are initially created without instructions. Their instructions are con- structed during the call graph re￿nement phase (Phase 2). It is important to highlight that the 3WepointthereadertotheworkbySridharanetal.[Sridharanetal.2013]whichprovidesagenericformulationformultiple points-toanalysispolicies. Proc.ACMProgram.Lang.,Vol.8,No.OOPSLA1,Article134.Publicationdate:April2024.134:8 JoannaC.S.Santos,MehdiMirakhorli,andAliShokri calls to synthetic methods (models) are 1-callsite-sensitive [Sridharan et al. 2013]. We use this context-sensitiveness policy to account for the fact that one can use the same ObjectInput- Stream/ObjectOutputStream instance to read/write multiple objects. Thus, we want to disam- biguatethesepathsinthecallgraph. Asaresultofthis￿rstiterationoverPhase1,weobtaintheinitialcallgraph(6 0)andalistof thecallsitesattheserializationanddeserializationpoints. 3.2 Phase2:CallGraphRefinement Inthisphase,wetakeasinputthecurrentcallgraph6 whichcontainsasnodesactualmethodsin 8 theapplicationandsyntheticmethodscreatedbyourapproachinthepreviousphase. 3.2.1 ObjectSerializationAbstraction. Algorithm1indicatestheprocedureformodelingobject serialization.Foreachinstructionattheserializationpoints,weobtainthepoints-tosetfortheobject > passedasthe￿rstargumenttowriteObject(Object).Thepoints-toset?C > ,2 indicatesthe 8 8 (h i) setofallocatedtypesC for> undercontext2.SincethewriteObject’sargumentisoftypeObject, 8 we￿rstaddto< atypecastinstructionthatre￿nesthe￿rstparametertothetypeC.Incasethe B classtypeC implementsthewriteObject(ObjectInputStream)callback,weaddaninvocation instructionfrom< targetingthiscallbackmethod. B Subsequently,weiterateoverallnon-static￿elds 5 fromtheclassC andcomputetheirpoints-to sets(seetheforeachinline10).Iftheconcretetypesallocatedtothe￿eldcontaincallbackmethods, weaddthreeinstructions:(i)aninstructiontogettheinstance￿eld5 fromtheobject;(ii)adowncast tothe￿eld’stype;(iii)aninvocationtothecallbackmethodfromthe￿eld’sdeclaringclass. Itisimportanttohighlighttheedgecasescenariowhenthetypeoftheobjectbeingserializedis ajava.util.Collectionorajava.util.Map.Inthiscase,S￿￿￿￿￿trackswhatobjectswereadded tothe collectioninordertoaddinvocationstotheircallbackmethods(ifprovided). Afteraddingalltheneededinstructionstothesyntheticmethod< ,were-addthesynthetic B methodtoS￿￿￿￿￿’sworklist(asdepictedinFigure4). Algorithm1:Objectserializationmodeling Input:SetofinvocationinstructionstowriteObject:I; Project’sinitialcallgraph:G; Output:Setofre￿nedsyntheticmodels"B 1 foreach8=BCAD2C8>=indo 2 >8 argument(1,8=BCAD2C8>=) 3 2 context(8=BCAD2C8>=) 4 <B target(8=BCAD2C8>=) 5 foreachC 2?C (h>8,2 i)do 6 addTypeCast(<B,C) 7 ifChasacallbackmethodthen 8 addInvoke(<B,C.20;;102:) 9 end 10 foreach5 584;3B C do 2 ( ) 1 11 2 forea ic fh 55 8484 ;3;3 )) ~~ ?? 44 ha2 s? cC a(lhl> b8 a. c5, k2 ti h) ed no 13 addGetField(<B,5) 14 addTypeCast(<B,584;3)~?4) 15 addInvoke(<B,584;3)~?4.20;;102: ) 16 end 17 end 18 end 19 end 20 addToWorkList(<B,c) 21 end Proc.ACMProgram.Lang.,Vol.8,No.OOPSLA1,Article134.Publicationdate:April2024.S￿￿￿￿￿:Taint-BasedCallGraphConstructionforJavaObjectDeserialization 134:9 Table1. TaintpropagationrulesemployedbyS￿￿￿￿￿whenbuildingcallgraphs. Instructionatmethod TaintpropagationRule <inacontext2 x = T.f g G =g G g ).5 [Load-Static] ( ) ( )_ ( ) x = y.f g G =g G g ~ g ~.5 [Load-Instance] ( ) ( )_ ( )_ ( ) x.f = y g G.5 =g G.5 g ~ [Store-Instance] ( ) ( )_ ( ) T.f = y g ).5 =g ).5 g ~ [Store-Static] ( ) ( )_ ( ) 08 9, ?8 %6 :g ?8 =g ?8 g 08 ,g 6C⌘8B =g 6C⌘8B g > [Instance-Call-Args] 8 2 8 2 ( ) ( )_ ( ) ( ) ( )_ ( ) g G =g G g 6A4C [Instance-Call-Return] ( ) ( )_ ( ) x = o.g(a1, ,an) SideE￿ect:g > =CAD4 ?C >,2 =?C >,2 C0A64C)~?4B >,2,6 [Call-Side-E￿ect] ··· ( ) ! (h i) (h i)[ ( ) x = T.g(a1, ···,an) g80 G8 2 = g9, G8?8 g2% 66 A4: Cg (?8 ) =g (?8 )_ g (08 ) [St[ aS tt ia ct -i Cc- aC lla -Rll- eA tur rg ns ]] ( ) ( )_ ( ) g <A4C =g <A4C g G [Return] ( ) ( )_ ( ) return x SideE￿ect: = ⇠< [Return-Side-E￿ect] W W[ x = y[i] g G =g G g ~ [Array-Load] ( ) ( )_ ( ) x[i] = y g G =g G g ~ [Array-Store] ( ) ( )_ ( ) = v1,v2, ,vn g q =g E1 g E2 ... g E= [Phi] ··· ( ) ( )_ ( )_ _ ( ) x = (TypeCast) y g G =g G g ~ [Checkcast] ( ) ( )_ ( ) 3.2.2 Taint-BasedObjectDeserializationAbstraction. Startingfromthedeserializationpoints identi￿ed,S￿￿￿￿￿computesthecallgraphon-the-￿ybyiterativelysolvingconstraintsoverthe
instructions.Eachmethodintheworklist <,2 isconvertedintoanIntermediaryRepresen- h i 2W tation(IR)inSingleStaticAssignmentform(SSA)[Cytronetal.1991;Rosenetal.1988].Moreover, thesemethodshavespecialvariablestodenotetheirreturnvalue< andthethispointer<.C⌘8B A4C (fornon-staticmethods). For each method in the worklist , S￿￿￿￿￿ performs pointer analysis in parallel with taint W analysistocomputethetaintstateofvariablesandpoints-tosets.Eachinstructioninthemethod’s IRisvisitedfollowingtherulesbytheunderlyingpointeranalysis[Sridharanetal.2013]andour taintanalysisalgorithm.Thus,eachpointerinaprogramhasanassociatedtaintstateg ? ,where ( ) g ? =CAD4 denotesataintedpointerandg ? = 50;B4 denotesanuntainted(safe)pointer.Below, ( ) ( ) weprovidetheformulationofourtaintanalysispolicy[Schwartzetal.2010]. TaintIntroduction. Asdescribedbefore,deserializationpointsarereplacedbyasyntheticmethod, i.e.,a“fakecallgraphnode”[Sridharanetal.2013].Itisasyntheticmethodcreatedon-the-￿yto model:(i)theinstantiationoftheclass⌧ thatcontainsacallbackmethod(s)< ;(ii)theinvocationto 2 2 thecallbackmethod(s)usingthenewlycreatedobject;and(iii)theinstantiationofanyparameters for the magic methods. It is important to highlight that in the Step (i), when instantiating the callback method’s object, we invoke the class’ default constructor. This is to follow the Java’s deserializationprocess(seeSection2). Therefore,S￿￿￿￿￿initializesthefollowingpointersastainted: - Thepointerforxintheinstructionx = new ⌧ (),where⌧ denotesaclassthatcontainsa 2 2 deserializationcallbackmethod(e.g.,readResolve): g G =true ( ) - Thepointersforallthe￿eldsof x: 5 584;3B G :g G.5 =true 8 8 8 2 ( ) ( ) - Thethispointerinthecallbackmethod< thatisinvoked: 2 g < .C⌘8B =true. 2 ( ) Proc.ACMProgram.Lang.,Vol.8,No.OOPSLA1,Article134.Publicationdate:April2024.134:10 JoannaC.S.Santos,MehdiMirakhorli,andAliShokri TaintPropagationRules. Asthemethod’sinstructionsareparsed,weemploytheruleslistedin Table1tocomputethetaintstatesoftheprogram’svariables.AsshowninTable1,therulesfor assignmentinstructionsareasfollows: lhs = rhs g ;⌘B =g ;⌘B g A⌘B ! ( ) ( )_ ( ) Thatis,thepointerfortheleft-handsideistaintedifthepointerfortheright-handsideisalso tainted(ortheleft-handsideitselfwasalreadypreviouslytainted).Thisisthecasefortherules L￿￿￿￿S￿￿￿￿￿,L￿￿￿￿I￿￿￿￿￿￿￿,S￿￿￿￿￿I￿￿￿￿￿￿￿,S￿￿￿￿￿S￿￿￿￿￿,S￿￿￿￿￿￿C￿￿￿￿R￿￿￿￿￿,R￿￿￿￿￿, A￿￿￿￿￿L￿￿￿,A￿￿￿￿￿S￿￿￿￿,andC￿￿￿￿￿￿￿￿. Phifunctions(q)arespecialstatementsthatareinsertedintoamethod’sSSAformtorepresent possiblevaluesforavariabledependingonthecontrol￿owpathtaken.Thetaintforthepointerof phig q willbetaintedifany ofthepossiblevariables’pointersaretainted. ( ) When there is a method invocation, it can either be a static invocation or an invocation to an instance method. In both cases, each passed parameter ? is assigned to the corresponding 8 argument0 fromtheinvokedmethod.Consequently,therulesI￿￿￿￿￿￿￿￿C￿￿￿￿A￿￿￿,andS￿￿￿￿￿￿ 8 C￿￿￿￿A￿￿￿arepropagatedlikewiseassignmentinstructions.Notice,however,thatforinstance methods,thereisaspecialvariable< denotingthe“this”pointerforthatmethod.Hence,the C⌘8B ruleI￿￿￿￿￿￿￿￿C￿￿￿￿A￿￿￿propagatesthetaintfromthecallerobjecttothe“this”pointerg 6 . C⌘8B ( ) Itisimportanttohighlightthattaintisneverremovedfromapointer.Althoughthiscanmake theunderlyingcallgraphmoreimprecise,ourgoalistosoundlyreasonoverall possibleruntime paths. —SideE￿ectstothePointerAnalysisEngine:Methodinvocationsandreturninstructionsintroduce side-e￿ectstothestaticanalysisenginestate,labelledinTable1asC￿￿￿￿S￿￿￿￿E￿￿￿￿￿andR￿￿￿￿￿￿ S￿￿￿￿E￿￿￿￿￿,respectively. Instancemethodinvocations(C￿￿￿￿S￿￿￿￿E￿￿￿￿￿):Whenthereisaninstancemethodinvocation • >.6 ... andtheobject> istainted,thenS￿￿￿￿￿computesthepossiblemethodtargetsforthecall ( ) >.6 ... soundly.Thedispatchiscomputedasdescribedbelow: ( ) (1) itobtainsthestatictypeC for>,i.e.C =C~?4 > ; ( ) (2) itextractsthesetofclassesbasedontheinheritancehierarchyfor) (i.e.,) =2>=4 C ,where ( ) 2>=4 C returnsthelistofalldescendantsofC,includingC itself[TipandPalsberg2000]). ( ) (3) itcomputesthesubset⇠ ) thatincludesonlythetypes(classes)whichprovideaconcrete ✓ implementationmatchingthesignatureoftheinvokedmethod6. (4) itcomputesthesubset ⇠ whichincludesonlyclassesthatareaccessibletoC according C ✓ toJava’svisibilityrules4. (5) ￿nally,thepossibletargetmethodsareallthemethodsfromtheset inwhichtheirclasses C areserializable(i.e.,implementstheserializableinterfacedirectlyorviainheritance). Asonecannotice,thisdispatchissimilartotheoneemployedbyClassHierarchyAnalysis(CHA). Themaindi￿erenceareinsteps(4)and(5),whereS￿￿￿￿￿takesintoaccountclassvisibilityrules aswellaswhetherthetypeisserializable. Oncethedispatchiscomputed(targetTypes(o,g)inC￿￿￿￿S￿￿￿￿E￿￿￿￿￿)thepointstosetfor ?C >,2 addsalltheelementsfromC0A64C)~?4B >,6 . (h i) ( ) Methodreturnvalues(R￿￿￿￿￿￿S￿￿￿￿E￿￿￿￿￿):Inascenariowhereamethod<hasataintedreturn • valueg < = true, all the callers of< are re-added to the . Since the return is tainted, A4C ( ) W we need to back propagate this information to all the callers of < to ensure that the rules I￿￿￿￿￿￿￿￿C￿￿￿￿R￿￿￿￿￿andS￿￿￿￿￿￿C￿￿￿￿R￿￿￿￿￿areappliedcorrectly. 4Visibilityrulesarethoroughlydescribedinthelanguagespeci￿cationhttps://docs.oracle.com/javase/specs/jvms/se7/html/ jvms-4.html#jvms-4.1-200-E.1 Proc.ACMProgram.Lang.,Vol.8,No.OOPSLA1,Article134.Publicationdate:April2024.S￿￿￿￿￿:Taint-BasedCallGraphConstructionforJavaObjectDeserialization 134:11 —Context-sensitivityforTaintedMethodCalls:Ourtaint-basedcallgraphconstructionalgorithm is agnostic to the pointer analysis policy (e.g., k-l-CFA, n-CFA, etc.5). This means that a client
analysiscouldchoosetouseacontextinsensitiveanalysis(e.g.,0-CFA).Sincetaintedpointersare likelytohavealargepoints-tosetbecauseweuseasoundanalysistocomputeallpossibilitiesfor methoddispatcheswhenthereceiverobjectistainted,weshouldavoidmergingpoint-to-setsof thesetaintedvariables.Otherwise,theresultingpointeranalysiswouldbetooimprecisetobeused bydownstreamclientanalyses.Therefore,weuse1-callsite-sensitivity fortaintedmethodcalls (evenifweuseaninsensitiveanalysisforalltheotherpointers). Demonstrative Example. Consider the code snippet in Listing 3. The class Main has a main method that reads an object from a ￿le, whose path is provided as a program argument. This programcontainsotherfourclasses(CacheManager,TaskExecutor,CommandTask,andConfig). WedemonstrateS￿￿￿￿￿’staint-baseddeserializationmodelingstrategyconsideringthatweselected 0-1-CFAasthemainpointeranalysismethod. 1 class Main { 1class CacheManager implements Serializable { 2 public static void main(String[] a) 2 private Runnable task; 3 throws Exception { 3 private Runnable[] taskArray; 4 FileInputStream f=new FileInputStream(a[0]); 5 ObjectInputStream in=new ObjectInputStream(f);4 private List<Runnable> taskList; 6 Config obj = (Config) in.readObject(); 5 private Set<Runnable> taskSet; 7 } 6 private Map<String, Runnable> taskMap; 8} 7 private String os; 9class CommandTask 10 implements Runnable, Serializable { 8 private long timestamp; 11 private String cmd; 9 public void readObject(ObjectInputStream ois) 12 private TaskExecutor taskExecutor; 10 throws IOException, ClassNotFoundException { 13 @Override 11 ois.defaultReadObject(); 14 public void run() { 12 Runnable r; 15 if (!cmd.isEmpty() && taskExecutor != null) 13 if(os.equals(windows) && task instanceof CommandTask){ 14 r = getInitHook(); /* site @32 */ 16 taskExecutor.executeCmd(cmd); /* site @24 */ 17 } 15 r.run(); 18} 16 }else { 19class TaskExecutor implements Serializable { 17 r = getFromArray(); 20 public void executeCmd(String cmd) { 18 r.run(); /* site @46 */ 21 try { 19 r = getFromList(); 22 Runtime rt = Runtime.getRuntime(); 20 r.run(); /* site @57 */ 23 rt.exec(cmd); 21 r = getFromSet(); 24 } catch (IOException e) { } 22 r.run(); /* site @68 */ 25 } 23 r = getFromMap(); 26} 24 r.run(); /* site @79 */ 27class Config implements Serializable { 25 } 28 private String page; 26 } 29 public void readObject(ObjectInputStream ois) 27 Runnable getInitHook(){ return task; } 3 30 1 oit sh .r do ew fs aulI tO RE ex ac de Op bt ji eo cn t, ()C ;lassNotFoundException { 28 Runnable getFromArray() { return taskArray[0]; } 32 Runtime rt = Runtime.getRuntime(); 29 Runnable getFromList() { return taskList.get(0); } 33 rt.exec(open http://localhost/ + page); 30 Runnable getFromSet() { return taskSet.iterator().next(); } 34 } 31 Runnable getFromMap() { return taskMap.get(xyz); } 35} 32} Listing3. Walk-throughexampletodemonstrateS￿￿￿￿￿’sapproach 5k-l-CFAisafamilyofalgorithmsinwhichkdelimitsthecontextforhowmanymethodsinthecallstackthealgorithm tracksandlisthecontextsizelimitwhichincludestheobjectcreationsiteanduptol-1previouslyinvokedmethods toreachtothecreationsite[Groveetal.1997;Viteketal.1992].Thus,0-1-CFAisanalgorithmthatdistinguishesthe allocationsofanobjectbasedonitsallocationsiteonly(i.e.,new ClassA()),andignoresthecallstackwhentheobject instantiationismade.Incontrast,n-CFAisanalgorithmthatdistinguishestheallocationofanobjectbasedonitsallocation siteanduptonpriormethodsinthecallstack Proc.ACMProgram.Lang.,Vol.8,No.OOPSLA1,Article134.Publicationdate:April2024.134:12 JoannaC.S.Santos,MehdiMirakhorli,andAliShokri S￿￿￿￿￿￿rstextractstheprogram’sentrypoints,providedaspartoftheanalysiscon￿guration. In this example, the Main.main(String a[]) is speci￿ed as the main method. Therefore, the S￿￿￿￿￿’sworklistisinitializedas: = "08=.<08= (CA8=60 , .S￿￿￿￿￿thenproceedsto W {h ( []) ;i} iterativelycomputethecallgraphbytraversingeachinstructionforeachmethodintheworklist. There are three method invocations on Main.main(): two invocations to the constructors (<init>) of FileInputStream and ObjectInputStream classes followed by a call to the read- Object()methodfromtheObjectInputStreamclass.ThemethodinvocationtoObjectInput- Stream.readObject()isreplacedbyS￿￿￿￿￿withamodel(synthetic)methodthathasthesame signature,butitisinitializedwithoutanyinstructions.Atthisstage,thecallgraphforthisprogram aftertraversingthemainmethodlookslikeasshowninFigure5.Allthesethreecallgraphnodes discoveredafterparsingMain.main()areaddedtotheworklisttobeprocessed(i.e.,,FileInput- Stream.<init>(),ObjectInputStream.<init>(),andObjectInputStream.readObject(). (cid:41)(cid:76)(cid:79)(cid:72)(cid:44)(cid:81)(cid:83)(cid:88)(cid:87)(cid:54)(cid:87)(cid:85)(cid:72)(cid:68)(cid:80)(cid:17)(cid:31)(cid:76)(cid:81)(cid:76)(cid:87)(cid:33)(cid:11)(cid:54)(cid:87)(cid:85)(cid:76)(cid:81)(cid:74)(cid:12)
(cid:189)(cid:3)(cid:72)(cid:81)(cid:87)(cid:85)(cid:92)(cid:83)(cid:82)(cid:76)(cid:81)(cid:87)(cid:3)(cid:190) (cid:38)(cid:82)(cid:81)(cid:87)(cid:72)(cid:91)(cid:87)(cid:29)(cid:3)(cid:145) (cid:48)(cid:68)(cid:76)(cid:81)(cid:17)(cid:80)(cid:68)(cid:76)(cid:81)(cid:11)(cid:54)(cid:87)(cid:85)(cid:76)(cid:81)(cid:74)(cid:62)(cid:64)(cid:12) (cid:50)(cid:69)(cid:77)(cid:72)(cid:70)(cid:87)(cid:44)(cid:81)(cid:83)(cid:88)(cid:87)(cid:54)(cid:87)(cid:85)(cid:72)(cid:68)(cid:80)(cid:17)(cid:31)(cid:76)(cid:81)(cid:76)(cid:87)(cid:33)(cid:11)(cid:44)(cid:81)(cid:83)(cid:88)(cid:87)(cid:54)(cid:87)(cid:85)(cid:72)(cid:68)(cid:80)(cid:12) (cid:38)(cid:82)(cid:81)(cid:87)(cid:72)(cid:91)(cid:87)(cid:29)(cid:3)(cid:145) (cid:38)(cid:82)(cid:81)(cid:87)(cid:72)(cid:91)(cid:87)(cid:29)(cid:3)(cid:145) (cid:80)(cid:82)(cid:71)(cid:72)(cid:79)(cid:3)(cid:80)(cid:72)(cid:87)(cid:75)(cid:82)(cid:71) (cid:50)(cid:69)(cid:77)(cid:72)(cid:70)(cid:87)(cid:44)(cid:81)(cid:83)(cid:88)(cid:87)(cid:54)(cid:87)(cid:85)(cid:72)(cid:68)(cid:80)(cid:17)(cid:85)(cid:72)(cid:68)(cid:71)(cid:50)(cid:69)(cid:77)(cid:72)(cid:70)(cid:87)(cid:11)(cid:12) (cid:38)(cid:82)(cid:81)(cid:87)(cid:72)(cid:91)(cid:87)(cid:29)(cid:3)(cid:48)(cid:68)(cid:76)(cid:81)(cid:17)(cid:80)(cid:68)(cid:76)(cid:81)(cid:11)(cid:54)(cid:87)(cid:85)(cid:76)(cid:81)(cid:74)(cid:62)(cid:64)(cid:12)(cid:3)(cid:35)(cid:3)(cid:21)(cid:20) (cid:11)(cid:86)(cid:92)(cid:81)(cid:87)(cid:75)(cid:72)(cid:87)(cid:76)(cid:70)(cid:3)(cid:80)(cid:72)(cid:87)(cid:75)(cid:82)(cid:71)(cid:12) Fig.5. Initialcallgrapha￿erparsingtheMain.main()methodinListing3 TheinstructionsthatareaddedtoObjectInputStream.readObject()relyontaintstatesto infercallbackmethodsthatmightbeinvokedduringdeserialization.Thus,whenre￿ningamethod model,S￿￿￿￿￿considersthatall serializableclassesintheclasspathcouldhavetheircallbacks invoked.Byusingthisstrategy,therearetwopossiblecallbacksthatcanbeinvoked:onefrom ConfigandonefromCacheManager.Hence,allofitsinstance￿eldsaremarkedastainted perthe taintintroductionrulespreviousdescribed(thesearehighlightedinredonListing3).Basedonthe taintpropagationrulesspeci￿edonListing1,variablesarethenmarkedastainted(thesevariables thataretaintedduetopropagationarehighlightedincyanonListing3). Recall that tainted invocations (i.e., an instruction such as obj.aMethod() in which obj is tainted)arehandleddi￿erently.Whereasthedispatchofnon-taintedinvocationwillfollowthe rulesfromtheunderlyingpointeranalysispolicy,thedispatchfortaintedinvocationsiscomputed usingamodi￿edversionoftheCHAalgorithm.Therefore,thecomputedcallgraphwhenusing the taint-based approach looks like as Figure 6. As shown in this image6, the model method includesthefollowinginstructions:anobjectinstantiationforConfigaswellasCacheManager, theirconstructors’invocation,andinvocationstotheircallbackmethods.Finally,themodelmethod returns a value that can either be an instance of Config or CacheManager. Notice that the phi function(q)isaddedtoindicatethispossibility. 4 EVALUATION Inthissection,weintroduceourresearchquestionsanddescribeourexperimentsetupanddesign toanswerthose. 4.1 Research￿estions Thispaperaddressesthefollowingresearchquestions: RQ1 S￿￿￿￿￿￿￿￿.DoesS￿￿￿￿￿handleobjectdeserializationsoundly? 6Forclarity,weelidethe“getter”callsaswellasinnercallsfromprimordialnodes(e.g.,String.isEmpty()). Proc.ACMProgram.Lang.,Vol.8,No.OOPSLA1,Article134.Publicationdate:April2024.S￿￿￿￿￿:Taint-BasedCallGraphConstructionforJavaObjectDeserialization 134:13 (cid:48)(cid:68)(cid:76)(cid:81)(cid:17)(cid:80)(cid:68)(cid:76)(cid:81)(cid:11)(cid:54)(cid:87)(cid:85)(cid:76)(cid:81)(cid:74)(cid:62)(cid:64)(cid:12) (cid:189)(cid:3)(cid:72)(cid:81)(cid:87)(cid:85)(cid:92)(cid:83)(cid:82)(cid:76)(cid:81)(cid:87)(cid:3)(cid:190)
(cid:38)(cid:82)(cid:81)(cid:87)(cid:72)(cid:91)(cid:87)(cid:29)(cid:3)(cid:145) (cid:47)(cid:72)(cid:74)(cid:72)(cid:81)(cid:71) (cid:41)(cid:76)(cid:79)(cid:72)(cid:44)(cid:81)(cid:83)(cid:88)(cid:87)(cid:54)(cid:87)(cid:85)(cid:72)(cid:68)(cid:80)(cid:17)(cid:31)(cid:76)(cid:81)(cid:76)(cid:87)(cid:33)(cid:11)(cid:54)(cid:87)(cid:85)(cid:76)(cid:81)(cid:74)(cid:12) (cid:31)(cid:86)(cid:92)(cid:81)(cid:87)(cid:75)(cid:72)(cid:87)(cid:76)(cid:70)(cid:3)(cid:80)(cid:72)(cid:87)(cid:75)(cid:82)(cid:71)(cid:33) (cid:31)(cid:68)(cid:83)(cid:83)(cid:79)(cid:76)(cid:70)(cid:68)(cid:87)(cid:76)(cid:82)(cid:81)(cid:3)(cid:80)(cid:72)(cid:87)(cid:75)(cid:82)(cid:71)(cid:33) (cid:31)(cid:83)(cid:85)(cid:76)(cid:80)(cid:82)(cid:85)(cid:71)(cid:76)(cid:68)(cid:79)(cid:3)(cid:80)(cid:72)(cid:87)(cid:75)(cid:82)(cid:71)(cid:33) (cid:38)(cid:82)(cid:81)(cid:87)(cid:72)(cid:91)(cid:87)(cid:29)(cid:3)(cid:145) (cid:31)(cid:70)(cid:82)(cid:81)(cid:87)(cid:72)(cid:91)(cid:87)(cid:33) (cid:31)(cid:70)(cid:82)(cid:81)(cid:87)(cid:72)(cid:91)(cid:87)(cid:33) (cid:31)(cid:70)(cid:82)(cid:81)(cid:87)(cid:72)(cid:91)(cid:87)(cid:33) (cid:50)(cid:69)(cid:77)(cid:72)(cid:70)(cid:87)(cid:44)(cid:81)(cid:83)(cid:88)(cid:87)(cid:54)(cid:87)(cid:85)(cid:72)(cid:68)(cid:80)(cid:17)(cid:31)(cid:76)(cid:81)(cid:76)(cid:87)(cid:33)(cid:11)(cid:44)(cid:81)(cid:83)(cid:88)(cid:87)(cid:54)(cid:87)(cid:85)(cid:72)(cid:68)(cid:80)(cid:12) (cid:38)(cid:82)(cid:81)(cid:87)(cid:72)(cid:91)(cid:87)(cid:29)(cid:3)(cid:145) (cid:56)(cid:86)(cid:72)(cid:85)(cid:17)(cid:31)(cid:76)(cid:81)(cid:76)(cid:87)(cid:33)(cid:11)(cid:12) (cid:50)(cid:69)(cid:77)(cid:72)(cid:70)(cid:87)(cid:44)(cid:81)(cid:83)(cid:88)(cid:87)(cid:54)(cid:87)(cid:85)(cid:72)(cid:68)(cid:80)(cid:17)(cid:85)(cid:72)(cid:68)(cid:71)(cid:50)(cid:69)(cid:77)(cid:72)(cid:70)(cid:87)(cid:11)(cid:12) (cid:38)(cid:82)(cid:81)(cid:87)(cid:72)(cid:91)(cid:87)(cid:29)(cid:3)(cid:62)(cid:3)(cid:50)(cid:69)(cid:77)(cid:72)(cid:70)(cid:87)(cid:44)(cid:81)(cid:83)(cid:88)(cid:87)(cid:54)(cid:87)(cid:85)(cid:72)(cid:68)(cid:80)(cid:17)(cid:85)(cid:72)(cid:68)(cid:71)(cid:50)(cid:69)(cid:77)(cid:72)(cid:70)(cid:87)(cid:11)(cid:12)(cid:35)(cid:23)(cid:3)(cid:64) (cid:50)(cid:69)(cid:77)(cid:72)(cid:70)(cid:87)(cid:17)(cid:31)(cid:76)(cid:81)(cid:76)(cid:87)(cid:33)(cid:11)(cid:12)
(cid:38)(cid:82)(cid:81)(cid:87)(cid:72)(cid:91)(cid:87)(cid:29)(cid:3)(cid:48)(cid:68)(cid:76)(cid:81)(cid:17)(cid:80)(cid:68)(cid:76)(cid:81)(cid:11)(cid:54)(cid:87)(cid:85)(cid:76)(cid:81)(cid:74)(cid:62)(cid:64)(cid:12)(cid:3)(cid:35)(cid:3)(cid:21)(cid:20) (cid:38)(cid:68)(cid:70)(cid:75)(cid:72)(cid:48)(cid:68)(cid:81)(cid:68)(cid:74)(cid:72)(cid:85)(cid:17)(cid:31)(cid:76)(cid:81)(cid:76)(cid:87)(cid:33)(cid:11)(cid:12) (cid:38)(cid:82)(cid:81)(cid:87)(cid:72)(cid:91)(cid:87)(cid:29)(cid:3)(cid:145) (cid:38)(cid:82)(cid:81)(cid:87)(cid:72)(cid:91)(cid:87)(cid:29)(cid:3)(cid:62)(cid:3)(cid:50)(cid:69)(cid:77)(cid:72)(cid:70)(cid:87)(cid:44)(cid:81)(cid:83)(cid:88)(cid:87)(cid:54)(cid:87)(cid:85)(cid:72)(cid:68)(cid:80)(cid:17)(cid:85)(cid:72)(cid:68)(cid:71)(cid:50)(cid:69)(cid:77)(cid:72)(cid:70)(cid:87)(cid:11)(cid:12)(cid:35)(cid:20)(cid:3)(cid:64) (cid:38)(cid:68)(cid:70)(cid:75)(cid:72)(cid:48)(cid:68)(cid:81)(cid:68)(cid:74)(cid:72)(cid:85)(cid:17)(cid:85)(cid:72)(cid:68)(cid:71)(cid:50)(cid:69)(cid:77)(cid:72)(cid:70)(cid:87)(cid:11)(cid:50)(cid:69)(cid:77)(cid:72)(cid:70)(cid:87)(cid:44)(cid:81)(cid:83)(cid:88)(cid:87)(cid:54)(cid:87)(cid:85)(cid:72)(cid:68)(cid:80)(cid:12) (cid:54)(cid:87)(cid:85)(cid:76)(cid:81)(cid:74)(cid:17)(cid:72)(cid:84)(cid:88)(cid:68)(cid:79)(cid:86)(cid:11)(cid:50)(cid:69)(cid:77)(cid:72)(cid:70)(cid:87)(cid:12) (cid:50)(cid:69)(cid:77)(cid:72)(cid:70)(cid:87)(cid:3)(cid:50)(cid:69)(cid:77)(cid:72)(cid:70)(cid:87)(cid:44)(cid:81)(cid:83)(cid:88)(cid:87)(cid:54)(cid:87)(cid:85)(cid:72)(cid:68)(cid:80)(cid:17)(cid:85)(cid:72)(cid:68)(cid:71)(cid:50)(cid:69)(cid:77)(cid:72)(cid:70)(cid:87)(cid:11)(cid:12)(cid:94) (cid:38)(cid:82)(cid:81)(cid:87)(cid:72)(cid:91)(cid:87)(cid:29)(cid:3)(cid:62)(cid:3)(cid:50)(cid:69)(cid:77)(cid:72)(cid:70)(cid:87)(cid:44)(cid:81)(cid:83)(cid:88)(cid:87)(cid:54)(cid:87)(cid:85)(cid:72)(cid:68)(cid:80)(cid:17)(cid:85)(cid:72)(cid:68)(cid:71)(cid:50)(cid:69)(cid:77)(cid:72)(cid:70)(cid:87)(cid:11)(cid:12)(cid:35)(cid:21)(cid:3)(cid:64) (cid:38)(cid:82)(cid:81)(cid:87)(cid:72)(cid:91)(cid:87)(cid:29)(cid:3)(cid:62)(cid:38)(cid:68)(cid:70)(cid:75)(cid:72)(cid:48)(cid:68)(cid:81)(cid:68)(cid:74)(cid:72)(cid:85)(cid:17)(cid:85)(cid:72)(cid:68)(cid:71)(cid:50)(cid:69)(cid:77)(cid:72)(cid:70)(cid:87)(cid:11)(cid:17)(cid:17)(cid:17)(cid:12)(cid:35)(cid:20)(cid:19)(cid:64) (cid:3)(cid:3)(cid:3)(cid:89)(cid:23)(cid:3)(cid:32)(cid:3)(cid:81)(cid:72)(cid:90)(cid:3)(cid:38)(cid:68)(cid:70)(cid:75)(cid:72)(cid:48)(cid:68)(cid:81)(cid:68)(cid:74)(cid:72)(cid:85)(cid:30)(cid:3)(cid:18)(cid:13)(cid:3)(cid:86)(cid:76)(cid:87)(cid:72)(cid:3)(cid:35)(cid:19)(cid:3)(cid:13)(cid:18)
(cid:3)(cid:3)(cid:3)(cid:89)(cid:23)(cid:17)(cid:31)(cid:76)(cid:81)(cid:76)(cid:87)(cid:33)(cid:11)(cid:12)(cid:30)(cid:3)(cid:3)(cid:3)(cid:3)(cid:3)(cid:3)(cid:3)(cid:3)(cid:3)(cid:3)(cid:3)(cid:18)(cid:13)(cid:3)(cid:86)(cid:76)(cid:87)(cid:72)(cid:3)(cid:35)(cid:20)(cid:3)(cid:13)(cid:18) (cid:38)(cid:82)(cid:80)(cid:80)(cid:68)(cid:81)(cid:87)(cid:55)(cid:68)(cid:86)(cid:78)(cid:17)(cid:85)(cid:88)(cid:81)(cid:11)(cid:12) (cid:3) (cid:3)(cid:3) (cid:3)(cid:3) (cid:3)(cid:89) (cid:89)(cid:23) (cid:26)(cid:17) (cid:3)(cid:85) (cid:32)(cid:72) (cid:3)(cid:68) (cid:81)(cid:71) (cid:72)(cid:50) (cid:90)(cid:69) (cid:3)(cid:77) (cid:38)(cid:72) (cid:82)(cid:70) (cid:81)(cid:87) (cid:73)(cid:11) (cid:76)(cid:89) (cid:74)(cid:20) (cid:30)(cid:12) (cid:3)(cid:30) (cid:3)(cid:3) (cid:3)(cid:3) (cid:3)(cid:3) (cid:3)(cid:3) (cid:3)(cid:3) (cid:3)(cid:18) (cid:18)(cid:13) (cid:13)(cid:3) (cid:3)(cid:86) (cid:86)(cid:76) (cid:76)(cid:87) (cid:87)(cid:72) (cid:72)(cid:3) (cid:3)(cid:35) (cid:35)(cid:21) (cid:22)(cid:3) (cid:3)(cid:13) (cid:13)(cid:18) (cid:18) (cid:38)(cid:82)(cid:81)(cid:87)(cid:72)(cid:91)(cid:87)(cid:29)(cid:3)(cid:62)(cid:3)(cid:38)(cid:68)(cid:70)(cid:75)(cid:72)(cid:48)(cid:68)(cid:81)(cid:68)(cid:74)(cid:72)(cid:85)(cid:17)(cid:85)(cid:72)(cid:68)(cid:71)(cid:50)(cid:69)(cid:77)(cid:72)(cid:70)(cid:87)(cid:11)(cid:17)(cid:17)(cid:17)(cid:12)(cid:3)(cid:35)(cid:22)(cid:21)(cid:3)(cid:64) (cid:38)(cid:82)(cid:81)(cid:87)(cid:72)(cid:91)(cid:87)(cid:29)(cid:3)(cid:54) (cid:62)(cid:38)(cid:87)(cid:85) (cid:82)(cid:76)(cid:81) (cid:80)(cid:74) (cid:80)(cid:17)(cid:76)(cid:86) (cid:68)(cid:40) (cid:81)(cid:80) (cid:71)(cid:55)(cid:83) (cid:68)(cid:87)(cid:92) (cid:86)(cid:11) (cid:78)(cid:12) (cid:17)(cid:85)(cid:88)(cid:81)(cid:11)(cid:12)(cid:35)(cid:23)(cid:64) (cid:3)(cid:3)(cid:3)(cid:89)(cid:26)(cid:17)(cid:31)(cid:76)(cid:81)(cid:76)(cid:87)(cid:33)(cid:11)(cid:12)(cid:30)(cid:3)(cid:3)(cid:3)(cid:3)(cid:3)(cid:3)(cid:3)(cid:3)(cid:3)(cid:3)(cid:3)(cid:18)(cid:13)(cid:3)(cid:86)(cid:76)(cid:87)(cid:72)(cid:3)(cid:35)(cid:23)(cid:3)(cid:13)(cid:18) (cid:38)(cid:82)(cid:80)(cid:80)(cid:68)(cid:81)(cid:87)(cid:55)(cid:68)(cid:86)(cid:78)(cid:17)(cid:85)(cid:88)(cid:81)(cid:11)(cid:12)
(cid:3)(cid:3)(cid:3)(cid:89)(cid:26)(cid:17)(cid:85)(cid:72)(cid:68)(cid:71)(cid:50)(cid:69)(cid:77)(cid:72)(cid:70)(cid:87)(cid:11)(cid:89)(cid:20)(cid:12)(cid:30)(cid:3)(cid:3)(cid:3)(cid:3)(cid:3)(cid:18)(cid:13)(cid:3)(cid:86)(cid:76)(cid:87)(cid:72)(cid:3)(cid:35)(cid:24)(cid:3)(cid:13)(cid:18)(cid:3) (cid:38)(cid:82)(cid:81)(cid:87)(cid:72)(cid:91)(cid:87)(cid:29)(cid:3)(cid:62)(cid:3)(cid:38)(cid:68)(cid:70)(cid:75)(cid:72)(cid:48)(cid:68)(cid:81)(cid:68)(cid:74)(cid:72)(cid:85)(cid:17)(cid:85)(cid:72)(cid:68)(cid:71)(cid:50)(cid:69)(cid:77)(cid:72)(cid:70)(cid:87)(cid:11)(cid:17)(cid:17)(cid:17)(cid:12)(cid:3)(cid:35)(cid:23)(cid:25)(cid:3)(cid:64) (cid:3)(cid:3)(cid:3)(cid:89)(cid:20)(cid:19)(cid:3)(cid:32)(cid:3)(cid:301)(cid:11)(cid:89)(cid:23)(cid:15)(cid:89)(cid:26)(cid:12)(cid:30)(cid:3)(cid:3)(cid:3)(cid:18)(cid:13)(cid:3)(cid:83)(cid:75)(cid:76)(cid:3)(cid:73)(cid:88)(cid:81)(cid:70)(cid:87)(cid:76)(cid:82)(cid:81)(cid:3)(cid:13)(cid:18) (cid:3)(cid:3)(cid:3)(cid:85)(cid:72)(cid:87)(cid:88)(cid:85)(cid:81)(cid:3)(cid:89)(cid:20)(cid:19)(cid:30) (cid:38)(cid:82)(cid:80)(cid:80)(cid:68)(cid:81)(cid:87)(cid:55)(cid:68)(cid:86)(cid:78)(cid:17)(cid:85)(cid:88)(cid:81)(cid:11)(cid:12) (cid:96) (cid:38)(cid:82)(cid:81)(cid:87)(cid:72)(cid:91)(cid:87)(cid:29)(cid:3)(cid:62)(cid:3)(cid:38)(cid:68)(cid:70)(cid:75)(cid:72)(cid:48)(cid:68)(cid:81)(cid:68)(cid:74)(cid:72)(cid:85)(cid:17)(cid:85)(cid:72)(cid:68)(cid:71)(cid:50)(cid:69)(cid:77)(cid:72)(cid:70)(cid:87)(cid:11)(cid:17)(cid:17)(cid:17)(cid:12)(cid:3)(cid:35)(cid:24)(cid:26)(cid:3)(cid:64) (cid:54)(cid:87)(cid:85)(cid:76)(cid:81)(cid:74)(cid:37)(cid:88)(cid:76)(cid:79)(cid:71)(cid:72)(cid:85)(cid:17)(cid:31)(cid:76)(cid:81)(cid:76)(cid:87)(cid:33)(cid:11)(cid:12) (cid:38)(cid:82)(cid:80)(cid:80)(cid:68)(cid:81)(cid:87)(cid:55)(cid:68)(cid:86)(cid:78)(cid:17)(cid:85)(cid:88)(cid:81)(cid:11)(cid:12) (cid:55)(cid:68)(cid:86)(cid:78)(cid:40)(cid:91)(cid:72)(cid:70)(cid:88)(cid:87)(cid:82)(cid:85)(cid:17)(cid:72)(cid:91)(cid:72)(cid:70)(cid:88)(cid:87)(cid:72)(cid:38)(cid:80)(cid:71)(cid:11)(cid:54)(cid:87)(cid:85)(cid:76)(cid:81)(cid:74)(cid:12)
(cid:38)(cid:82)(cid:81)(cid:87)(cid:72)(cid:91)(cid:87)(cid:29)(cid:3)(cid:145) (cid:38)(cid:82)(cid:81)(cid:87)(cid:72)(cid:91)(cid:87)(cid:29)(cid:3)(cid:62)(cid:3)(cid:38)(cid:68)(cid:70)(cid:75)(cid:72)(cid:48)(cid:68)(cid:81)(cid:68)(cid:74)(cid:72)(cid:85)(cid:17)(cid:85)(cid:72)(cid:68)(cid:71)(cid:50)(cid:69)(cid:77)(cid:72)(cid:70)(cid:87)(cid:11)(cid:17)(cid:17)(cid:17)(cid:12)(cid:3)(cid:35)(cid:25)(cid:27)(cid:3)(cid:64) (cid:38)(cid:82)(cid:81)(cid:87)(cid:72)(cid:91)(cid:87)(cid:29)(cid:3)(cid:62)(cid:3)(cid:38)(cid:82)(cid:80)(cid:80)(cid:68)(cid:81)(cid:71)(cid:55)(cid:68)(cid:86)(cid:78)(cid:17)(cid:85)(cid:88)(cid:81)(cid:11)(cid:12)(cid:3)(cid:35)(cid:21)(cid:23)(cid:3)(cid:64) (cid:38)(cid:82)(cid:80)(cid:80)(cid:68)(cid:81)(cid:87)(cid:55)(cid:68)(cid:86)(cid:78)(cid:17)(cid:85)(cid:88)(cid:81)(cid:11)(cid:12) (cid:53)(cid:88)(cid:81)(cid:87)(cid:76)(cid:80)(cid:72)(cid:17)(cid:74)(cid:72)(cid:87)(cid:53)(cid:88)(cid:81)(cid:87)(cid:76)(cid:80)(cid:72)(cid:11)(cid:12) (cid:54)(cid:87)(cid:85)(cid:76)(cid:81)(cid:74)(cid:37)(cid:88)(cid:76)(cid:79)(cid:71)(cid:72)(cid:85)(cid:17)(cid:68)(cid:83)(cid:83)(cid:72)(cid:81)(cid:71)(cid:11)(cid:54)(cid:87)(cid:85)(cid:76)(cid:81)(cid:74)(cid:12) (cid:38)(cid:82)(cid:81)(cid:87)(cid:72)(cid:91)(cid:87)(cid:29)(cid:3)(cid:62)(cid:3)(cid:38)(cid:68)(cid:70)(cid:75)(cid:72)(cid:48)(cid:68)(cid:81)(cid:68)(cid:74)(cid:72)(cid:85)(cid:17)(cid:85)(cid:72)(cid:68)(cid:71)(cid:50)(cid:69)(cid:77)(cid:72)(cid:70)(cid:87)(cid:11)(cid:17)(cid:17)(cid:17)(cid:12)(cid:3)(cid:35)(cid:26)(cid:28)(cid:3)(cid:64) (cid:38)(cid:82)(cid:81)(cid:87)(cid:72)(cid:91)(cid:87)(cid:29)(cid:3)(cid:145) (cid:38)(cid:82)(cid:81)(cid:87)(cid:72)(cid:91)(cid:87)(cid:29)(cid:3)(cid:145) (cid:38)(cid:82)(cid:81)(cid:73)(cid:76)(cid:74)(cid:17)(cid:85)(cid:72)(cid:68)(cid:71)(cid:50)(cid:69)(cid:77)(cid:72)(cid:70)(cid:87)(cid:11)(cid:50)(cid:69)(cid:77)(cid:72)(cid:70)(cid:87)(cid:44)(cid:81)(cid:83)(cid:88)(cid:87)(cid:54)(cid:87)(cid:85)(cid:72)(cid:68)(cid:80)(cid:12) (cid:54)(cid:87)(cid:85)(cid:76)(cid:81)(cid:74)(cid:37)(cid:88)(cid:76)(cid:79)(cid:71)(cid:72)(cid:85)(cid:17)(cid:87)(cid:82)(cid:54)(cid:87)(cid:85)(cid:76)(cid:81)(cid:74)(cid:11)(cid:12) (cid:53)(cid:88)(cid:81)(cid:87)(cid:76)(cid:80)(cid:72)(cid:17)(cid:72)(cid:91)(cid:72)(cid:70)(cid:11)(cid:54)(cid:87)(cid:85)(cid:76)(cid:81)(cid:74)(cid:12)
(cid:38)(cid:82)(cid:81)(cid:87)(cid:72)(cid:91)(cid:87)(cid:29)(cid:3)(cid:62)(cid:3)(cid:50)(cid:69)(cid:77)(cid:72)(cid:70)(cid:87)(cid:44)(cid:81)(cid:83)(cid:88)(cid:87)(cid:54)(cid:87)(cid:85)(cid:72)(cid:68)(cid:80)(cid:17)(cid:85)(cid:72)(cid:68)(cid:71)(cid:50)(cid:69)(cid:77)(cid:72)(cid:70)(cid:87)(cid:11)(cid:12)(cid:35)(cid:24)(cid:3)(cid:64) (cid:38)(cid:82)(cid:81)(cid:87)(cid:72)(cid:91)(cid:87)(cid:29)(cid:3)(cid:145) (cid:38)(cid:82)(cid:81)(cid:87)(cid:72)(cid:91)(cid:87)(cid:29)(cid:3)(cid:145) Fig.6. CallgraphforListing3computedbyS￿￿￿￿￿(0-1-CFA) RQ2 P￿￿￿￿￿￿￿￿.Doesanincreaseinthecallgraph’ssoundnessincurasigni￿cantlossinitsprecision? RQ3 S￿￿￿￿￿￿￿￿￿￿.DoesS￿￿￿￿￿scalewellforrealsoftwaresystems? RQ4 U￿￿￿￿￿￿￿￿￿.IsS￿￿￿￿￿usefulforaclientanalysisfocusedonvulnerabilitydetection? Toanswertheaforementionedresearchquestions,wedevelopedaprototypeforS￿￿￿￿￿inJava usingtheT.J.WatsonLibrariesforAnalysis(W￿￿￿)[WALA2024].Ourprototypeallowsclient analyses to select a pointer analysis method that can either be 0-n-CFA, or n-CFA, where n is provided.Weexplaininthenextsubsectionsthemethodologyanddatasetsusedtoanswereach RQ. 4.2 AnsweringRQ1:Soundness WeaimtoverifywhetherS￿￿￿￿￿improvesacallgraph’ssoundnesswithrespecttoserialization anddeserializationcallbacksandhowitcompareswithexistingapproaches[Reifetal.2019,2018; Santosetal.2021,2020].Thesoundnessofacallgraphconstructionalgorithmcorrespondstobeing abletocreateacallgraphthatincorporateallpossiblepaths(nodesandedges)thatcanariseat runtime[Alietal.2019;Kummitaetal.2021].Inthiswork,wearespeci￿callylookingatimproving acallgraph’ssoundnesstocoverpossibleinvocationsthatariseduringobjectserializationand deserialization.Therefore,weusetwodatasetstoanswerthis￿rstresearchquestion. Call Graph Assessment & Test Suite (CATS) [Eichberg 2020]: This dataset was released • as part of recent empirical studies [Reif et al. 2019, 2018] to investigate the soundness of the callgraphscomputedbyexistingalgorithmswithrespecttoparticularprogramminglanguage constructs. The CATS test suite7 was derived by an extensive analysis of real Java projects tocreatetestcasesthatarerepresentativeofcommonwaysthatprojectsusetheselanguage constructs (e.g., lambdas, re￿ection, serialization, etc.). The dataset includes 9 test cases for verifyingthesoundnessofcallgraphsduringserializationanddeserializationofobjects.Each testcaseisaJavaprogramwithannotationsthatindicatetheexpectedtargetforagivenmethod 7ThisprojectwasformerlyknownastheJavaCallGraphTestSuite(JCG). Proc.ACMProgram.Lang.,Vol.8,No.OOPSLA1,Article134.Publicationdate:April2024.134:14 JoannaC.S.Santos,MehdiMirakhorli,andAliShokri Table2. TestcasesfromtheCATSTestSuite[Eichberg2020]andwhichsoundnessaspecttheyaimtoverify. ID Description Ser1 ThecodeserializesanobjectwhoseclasscontainsacustomwriteObjectmethod.Ittestswhetherthecallgraphcreatesanode forthewriteObject(...)callbackmethodthatcanbeinvokedbythewriteObjectmethodfromtheObjectOutputStreamclass. Ser2 TestswhetherthecallgraphhasnodesandedgesforthewriteObjectcallbackmethodunderthescenariothatthecallmaybe invokedifaconditionistrue. Ser3 Testswhetherthecallgraphconstructionalgorithmconsidersinter-procedural￿owtosoundlyinferthattheobject’swriteOb- ject(...)callbackmethodwillbeinvokedbythewriteObjectmethodfromtheObjectOutputStreamclass. Ser4 Thecodedeserializesanobject(withoutperformingadowncast)whoseclasscontainsacustomreadObjectmethod.Ittests whetherthecallgraphcreatesanodeforthereadObject(...)callbackmethodthatcanbeinvokedbythereadObjectmethod fromtheObjectInputStreamclass. Ser5 ThecodedeserializesanobjectwhoseclasscontainsacustomredObjectmethod.Ittestswhetherthecallgraphcreatesanodefor thereadObject(...)callbackmethodthatcanbeinvokedbythereadObjectmethodfromtheObjectInputStreamclass.Unlike Ser4,thistestcasehasadowncasttotheexpectedtypeofthereadobject. Ser6 TestswhetherthecallgraphhasnodesandedgesforthewriteReplacecallbackmethodthatwillbeinvokedduringserialization. Ser7 TestswhetherthecallgraphhasnodesandedgesforthereadResolvecallbackmethodthatwillbeinvokedduringdeserialization. Ser8 TestswhetherthecallgraphhasnodesandedgesforthevalidateObjectcallbackmethodthatwillbeinvokedduringdeserial- ization. Ser9 Testswhetherconstructorsofserializableclassesarehandledsoundly.Itcheckswhetherthecallgraphmodelstheruntimebehavior, whichinvokesthe￿rstdefaultconstructorthatisnotfromaserializablesuperclass. call.Table2providesanoverviewofthetestcasesavailableintheCATStestsuiteandwhat aspectstheyaimtoprobe.Hence,inthis￿rstexperiment,werunS￿￿￿￿￿usingtwopointer analysiscon￿gurations:0-1-CFA,and1-CFA.Then,wecompareitagainstS￿￿￿￿(0-CFA,1-CFA), a state-of-the-art tool, as well as the same algorithms used in the empirical study by Reif et al. [Reif et al. 2019], namely S￿￿￿ (CHA, RTA, VTA, and Spark), W￿￿￿ (RTA, 0-CFA, 1-CFA, and 0-1-CFA),D￿￿￿(context-insensitive),andO￿￿￿(RTA). —Metric:LikewisetothepriorempiricalstudybyReifetal.[Reifetal.2019,2018],wecompute thenumberoffailedandpassedtestcasesforeachapproachasawaytoinvestigatethesoundness ofourapproach.Atestcasethatpassesindicatesthatthecallgraphcontainstheexpectednodes andedgesthatariseduringobjectserialization/deserialization.Afailing testcasesindicatesthat thesenodes/edgesaremissinginthecallgraph. XCorpus dataset: Although the CATS dataset was carefully constructed to test call graph • construction algorithms with respect to programming language features, the test cases are smallprograms(i.e.,withfewserializableclasses).Thereisalackofabenchmarkcontaining
realsoftwaresystemstoverifyhowwellcallgraphconstructionalgorithmscanhandleobject serialization/deserialization features Therefore, to enhance our analysis, we used programs availableontheXCorpusdataset[Dietrichetal.2017b].Wechosethisdatasetbecauseithas beenwidelyusedinpriorrelatedworks[Fourtounisetal.2018;Santosetal.2021,2020]andit wasmanuallycuratedtoberepresentativeofrealJavaprojects. Fromthisdataset,weselectedatotalof10programsfromtheXCorpusdataset(listedinTable3). Wechosetheseprojectsbecausetheymatchedthefollowingcriteria:(i)theyperformobject serialization/deserialization;(ii)theycontainserializableclassesthatprovidecustomimple- mentationforcallbackmethods;hence,theywouldbesuitabletoverifywhetherourapproach canproperlycomputeacallgraphthatuncoverhiddenpathsviacallbackmethods. AlthoughtheXCorpusdatasethasrealprograms,theydonotcontaintestcasesthatexerciseall possiblecallpathsthatcangothroughserialization/deserializationcallbacks.Thus,foreachof these10projects,wecreatedasetoftestcasesthatexercisedtheserializationanddeserialization ofobjectsfromtheclassesthatcontainedcustomcallbackmethods.Eachtestcaseserializesan objectintoa￿le,andthendeserializesitbackfromthis￿le,asshowninListing4. Proc.ACMProgram.Lang.,Vol.8,No.OOPSLA1,Article134.Publicationdate:April2024.S￿￿￿￿￿:Taint-BasedCallGraphConstructionforJavaObjectDeserialization 134:15 1public class TC<number> { 2 private static Object getObject() { 3 Object object = <initialization> 4 return object; 5 } 6 public static void main(String[] args) throws Exception { 7 Object obj = getObject(); 8 FileOutputStream fOut = new FileOutputStream(args[0]); 9 ObjectOutputStream objOut = new ObjectOutputStream(fOut); 10 objOut.writeObject(obj); 11 FileInputStream fs = new FileInputStream(args[0]); 12 ObjectInputStream objIn = new ObjectInputStream(fs); 13 Object deserializedObj = objIn.readObject(); 14 new File(filepath).delete(); 15 } 16} Listing4. TestCasetemplate Thesystematicprocesswefollowedtocreatethesetestcaseswereasfollows.Foreachclass intheXCorpusprogramthathadacustomcallbackmethod(“gadgetclasses”),wecreatedwe created5testcasesasfollows: – Wecreateda“simple”testcase.This“simple”testcasereturnsasingleinstancefromtheclass insidethemethodgetObject().Thatis,theobjectinline3inListing4isinstantiatedtothe typeofthegadgetclass.Wereadtheproject’sdocumentationtoinitializetheobject’s￿elds correctlyandavoidexceptionsthrownbytheclass’constructor.Moreover,weensuredthat eachobject’sreference￿eldsarenon-nulls.Thiswillguaranteethatcallstothe￿eld’sclass’ callbackswouldalsoshowupintheruntimecallgraph. – Wealsocreated“composite”testcasesinwhichtheclassinstanceisaddedintoacollection. ThesecollectionsareanArrayList,aHashSet,aHashMap,oranarray. Byfollowingthissystematicprocess,wecreated5testcases(one“simple”testcase,andfour “composite”ones)foreachclasswithacustomcallbackinanXCorpusproject.Weobtaineda totalof 210testcases.ThenumberoftestcasesperXCorpusprogramsisshowninTable3. Thissystematicprocessensuresthatourtestcasesaresu￿cientlycomprehensivetoenablea reliablecomparisonofprecisionandsoundness.Withourtestcases,all possiblede/serialization- relatedcallbackmethodsintheprogram’sclasspathareexecutedatleastonce.Moreover,this alsoensuresthatwetestthecomputedcallgraphswithrespecttohandlingserializablecollections containingotherserializableobjects. Aftercreatingthesetestcases,weexecutethemtoextracttheirdynamiccallgraph(runtime callgraph).WeimplementedaJVMTI(JavaVirtualMachineToolInterface)agentinCtocompute theseruntimecallgraphs.Thisimplementationhasaninstrumentationagentthatisattachedto theprogram’sexecution.Itcaptureseverymethodthatisinvokedintheprogramanditscaller method. Sinceweaimtoinvestigatewhetherourtaint-basedcallgraphalgorithmhandleobjectdese- rializationsoundlyorwouldunsoundassumptionsbeableto￿ndvulnerabilities,wecompare S￿￿￿￿￿againstS￿￿￿￿[Santosetal.2021,2020],astate-of-the-artapproachthatcomputescall graphsforobjectdeserializationbasedondowncastswithintheprogram,whichyieldstoless soundcallgraphs. Metric: Similar to prior works [Ali et al. 2019; Ali and Lhoták 2012; Kummita et al. 2021; Li etal.2014;Smaragdakisetal.2015],weverifyourapproach’ssoundnessbasedonthenumber ofedgesintheruntimecallgraphthataremissing inthestaticcallgraph.Inourcomparison, Proc.ACMProgram.Lang.,Vol.8,No.OOPSLA1,Article134.Publicationdate:April2024.134:16 JoannaC.S.Santos,MehdiMirakhorli,andAliShokri we di￿erentiate application-to-application edges, application-to-library, and library-to-library edges.Thatmeansthatwedisregardmissingedgesdueto:(a)classinitializers(because<clinit> methods are modeled by W￿￿￿ using a synthetic method that invokes all class initializers at once), (b) native code (because it cannot be statically analyzed), (c) explicitly excluded classes (i.e.,classesinsideourlistofexclusions￿lethatareremovedfromthestaticcallgraph),and(d) library-to-library edges(i.e.,edgesfromabuilt-inJavaclasstoanotherbuilt-inlanguageclass). Table3. XCorpusprograms[Dietrichetal.2017b]usedinourexperimentsandthenumberoftestcases createdforeachofthem. batik castor james jgraph jpf log4j openjms pooka xalan xerces Project (1.7) (1.3.1) (2.2.0) (5.13.0.0) (1.5.1) (1.2.16) (0.7.7-beta-1) (3.0-080505) (2.7.1) (2.10.0)
#Classes 2,560 1,639 340 187 152 308 808 1,617 1,621 1,034 #Classesin 1,209 947 274 0 1 0 28 0 0 0 Dependencies #TestCases 25 65 5 30 5 15 5 30 25 5 4.3 AnsweringRQ2:Precision Although soundness is a desirable property for static analysis, in practice, however, creating a soundanalysisalsoimpliesalossofprecision.Duetotheundecidabilityofprogramveri￿cation,it isimpossibletocreateananalysisthatisbothsound andprecise[Rice1953].Therefore,asound analysisisanover-approximationthatmayincludespuriousresults(e.g.,unrealisticpaths). Whileourapproachaimstoenhanceanexistingcallgraphconstructionalgorithmtohandle serialization-relatedcallbackssoundly,weneedtoverifywhetherourapproachintroducesimpre- cisionandtowhatextent.Imprecisioninthisworkreferstoaddingnodesandedgesthatwillnot ariseattheprogram’sruntimeduringobjectserializationanddeserialization[Alietal.2019]. Toanswerthisquestion,weuseourJVMTIagenttocomputetheruntimecallgraphforeach programintheCATStestsuite[Eichberg2020]andourmanuallyconstructedtestcasesderived fromtheXCorpusdataset[Dietrichetal.2017b].Subsequently,wecomputethenumberofedges inthestaticcallgraphthatdidnotexistintheruntimecallgraph. —Metric:WecalculatethenumberofnodesandedgesthatappearedinS￿￿￿￿￿’scallgraph but did not appear on the dynamic call graph. Similar to prior works [Smaragdakis et al. 2015; SmaragdakisandKastrinis2018],whenperformingthiscalculation,weonlyconsiderapplication- to-applicationedgesandapplication-to-library edgesaslongastheseedgesdonotincludenodes thatareaclassinitializer,anativecodemethod,oramethodfromanexplicitlyexcludedclass. 4.4 AnsweringRQ3:Performance Ourserialization-awarecallgraphconstructionapproachintroducesextraiterationsontheunder- lyingpointeranalysismethods.Assuch,weinvestigatewhethertheseextraiterationsintroduce signi￿cantoverheadthatrenderstheanalysisimpracticalforreallarge-scaleprograms. Toverifytheoverheadofincurredbyourapproach,we￿rstuseS￿￿￿￿￿tobuildthecallgraphs forthetestcasescreatedforthe10programsextractedfromtheXCorpusdataset[Dietrichetal. 2017b].Subsequently,werunthe0-1-CFAand1-CFAcallgraphconstructionalgorithmsavailable inW￿￿￿withandwithout ourserialization-awareapproachenabled.Forcomparison,wealso ranS￿￿￿￿con￿guredwith0-1-CFAand1-CFAtobuildcallgraphs.Foralloftheseapproaches,we Proc.ACMProgram.Lang.,Vol.8,No.OOPSLA1,Article134.Publicationdate:April2024.S￿￿￿￿￿:Taint-BasedCallGraphConstructionforJavaObjectDeserialization 134:17 usedastandardlistofclassexclusions8;theseclassesareignoredduringcallgraphconstructionby W￿￿￿,S￿￿￿￿,andS￿￿￿￿￿. —Metric:Wemeasure(i)therunningtimetocomputethecallgraphswhenusingourapproach,and (ii)theextraaddednumberofiterationsovertheworklistofthecallgraphconstructionalgorithm. Weruntheseanalysesonamachinewitha2.9GHzIntelCorei7processorand32GbofRAM memory. 4.5 AnsweringRQ4:E￿iciency Oneofthepremisesofthisworkisthatataint-basedcallgraphconstructionenablesthecomputation ofsoundcallgraphswithrespectto(de)serialization,whichcanbeusefulforclientanalyses,such as vulnerability detection. In this question, we aim to verify whether S￿￿￿￿￿ can help a static analysistechniquein￿ndingpotentialvulnerablepathsintheprogram. Toanswerthisquestion,weobtained3open-sourceprojectswithknowndiscloseddeserialization vulnerabilities.Weselectedtheseprojectsbecausetheirexploitshavebeenwidelydiscussedby practitionersandareavailableontheYSoSerialGitHubrepository[Froho￿2018].Thatis,these projectshavewell-known“gadgetchains”whichwerepreviouslydisclosedinvulnerabilityreports. ToanswerthisRQ,weusedS￿￿￿￿￿andS￿￿￿￿tocomputethecallgraphsoftheseprojects.Each techniquewascon￿guredtouse0-1-CFAand1-CFA.Subsequently,weusethesecallgraphsto extractvulnerablepathswhicharepathsfromObjectInputStream.readObject()tosinks,i.e., methodinvocationstosecurity-sensitiveoperations. Toidentifysinks,wemanuallycuratedalistofsecurity-sensitivemethodsignatures.Todoso, weextractedthelistofsinkmethodsfromapriorpublishedwork[Thoméetal.2017].Moreover, we parsed the manifest ￿le from the Juliet Test Suite [NSA Center for Assured Software 2017]. ThistestsuiteisadatasetfromNIST(NationalInstituteofStandardsandTechnology)whichhasa collectionofsyntheticC/C++andJavacodesampleswithdi￿erentsoftwareweaknesses(CWEs). Theirmanifest￿leindicatesallthe￿lesforatestcase,thekindofweaknessitcontains,andits locationinthecode.Thus,weparsedthemanifesttoextractthelinesthatare￿aggedasvulnerable, ￿lteredoutthelinesthatarenotmethodinvocations,groupedthembysignature,andmanually identi￿edtheonesthataresinks.Afterperformingthesetwocomplementarycurationsteps,we obtainedatotalof 101methodssignaturesforsinks. —Metric:Wemeasuredhowmanyvulnerablepathseachapproachwasabletoidentify. 5 RESULTS 5.1 RQ1:CallGraphSoundness Thissectiondescribestheresultsoftheexperimentsformeasuringthesoundnessofthecall graphscomputedbyS￿￿￿￿￿. 5.1.1 Dataset#1:CATS. Table4reportstheprogramsinwhicheachapproachsoundlyinferredthe callgraph(3)andtheonesitfailedtodoso(7).Asshowninthistable,webuiltcallgraphsusing twodi￿erentpointeranalysispolicies:0-1-CFA,and1-CFA.Forthesakeofcomparison,thistable alsoincludesthesamealgorithmsandresultspresentedbyReifetal.[Reifetal.2019]andthatwe wereabletoreproduceusingtheDockerimage[Reif2023]providedbytheirwork.Thereleased artifactsofReifetal.study[Reifetal.2019]includesadaptersforconstructingcallgraphsusing S￿￿￿(CHA,RTA,VTA,andSpark),W￿￿￿(RTA,0-CFA,1-CFA,and0-1-CFA),andO￿￿￿(RTA).Wealso includedacomparisonwitharecentpublishedwork,S￿￿￿￿[Santosetal.2021,2020],con￿gured
withthesamepointeranalysispoliciesasours,i.e.,0-1-CFA,and1-CFA. 8https://github.com/wala/WALA/blob/master/com.ibm.wala.core/src/main/resources/Java60RegressionExclusions.txt Proc.ACMProgram.Lang.,Vol.8,No.OOPSLA1,Article134.Publicationdate:April2024.134:18 JoannaC.S.Santos,MehdiMirakhorli,andAliShokri Table4. Passed/failedtestcasesfromCATS S￿￿￿￿ S￿￿￿￿ S￿￿￿￿￿ S￿￿￿￿￿ O￿￿￿ S￿￿￿ S￿￿￿ S￿￿￿ S￿￿￿ W￿￿￿ W￿￿￿ W￿￿￿ W￿￿￿ (0-1-CFA)(1-CFA)(0-1-CFA)(1-CFA)(RTA)(CHA)(RTA)(Spark)(VTA)(0-1-CFA)(0-CFA)(1-CFA)(RTA) Ser1 3 3 3 3 3 7 7 7 7 7 7 7 7 Ser2 3 3 3 3 3 7 7 7 7 7 7 7 7 Ser3 3 3 3 3 7 7 7 7 7 7 7 7 7 Ser4 3 3 3 3 7 7 7 7 7 7 7 7 7 Ser5 3 3 3 3 3 7 7 7 7 7 7 7 7 Ser6 3 3 3 3 7 7 7 7 7 7 7 7 7 Ser7 3 3 3 3 3 7 7 7 7 7 7 7 7 Ser8 3 3 3 3 7 3 3 7 7 7 7 7 7 Ser9 3 3 3 3 3 3 3 7 7 7 7 7 7 AsshowninTable4,onlyourserialization-awarecallgraphconstruction(S￿￿￿￿￿)andS￿￿￿￿ passedalloftheninetestcases.Onlythreeotheralgorithmspartiallyprovidedsupportforcallback methods,namelyS￿￿￿ andS￿￿￿ (2outof9)andO￿￿￿ (5outof9)[Reifetal.2019].The ') ⇠ ') remainingalgorithms,i.e.,S￿￿￿(VTA,andSpark),W￿￿￿(RTA,0-CFA,1-CFA,0-1-CFA),didnot providesupportatallforserialization-relatedcallbackmethods. Itisalsoimportanttohighlightthattheframeworksthatprovidedpartialsupportforserialization- relatedfeatures(S￿￿￿ ,S￿￿￿ ,andO￿￿￿ )useimprecisecallgraphconstructionalgorithms RTA CHA RTA (CHA[Deanetal.1995]orRTA[BaconandSweeney1996]).Table5showsacomparisonofcall graphs’sizesintermsofnodesandedges.Aswecaninferfromthesecharts,theonlycallgraph constructionalgorithmsusedbyS￿￿￿,andO￿￿￿thatprovidedpartialsupportforserialization createmuchlargercallgraphs(intermsofthenumberofnodesandedges).Sincethesealgorithms onlyrelyonstatictypeswhencomputingthepossibletargetsofamethodinvocation,theyintroduce spuriousnodesandedges,therebyincreasingthecallgraph’ssize. Table5. Callgraphsizesforeachapproachandtestcase(TC)fromtheCATSbenchmark. TC Approach #Nodes #Edges TC Approach #Nodes #Edges TC Approach #Nodes #Edges OPALRTA 5,983 39,580 S￿￿￿￿1-CFA 1,590 2,841 Ser7 S￿￿￿￿￿0-1-CFA 722 1,323 S￿￿￿￿0-1-CFA 771 1,527 Ser4 S￿￿￿￿￿0-1-CFA 722 1,323 S￿￿￿￿￿1-CFA 1,590 2,841 Ser1 S￿￿￿￿1-CFA 1,876 3,538 S￿￿￿￿￿1-CFA 1,590 2,841 S￿￿￿￿0-1-CFA 729 1,333 S￿￿￿￿￿0-1-CFA 771 1,527 OPALRTA 6,461 44,773 S￿￿￿￿1-CFA 1,601 2,855 S￿￿￿￿￿1-CFA 1,876 3,538 S￿￿￿￿0-1-CFA 722 1,323 Ser8 S￿￿￿￿￿0-1-CFA 729 1,333 Ser5 OPALRTA 5,985 39,583 S￿￿￿￿1-CFA 1,590 2,841 S￿￿￿￿￿1-CFA 1,601 2,855 S￿￿￿￿0-1-CFA 772 1,529 S￿￿￿￿￿0-1-CFA 722 1,323 SootCHA 17,570 261,274 Ser2 S￿￿￿￿1-CFA 1,878 3,540 S￿￿￿￿￿1-CFA 1,590 2,841 SootRTA 17,449 259,257 S￿￿￿￿￿0-1-CFA 772 1,529 S￿￿￿￿0-1-CFA 546 940 OPALRTA 6,463 44,775 S￿￿￿￿￿1-CFA 1,878 3,540 Ser6 S￿￿￿￿1-CFA 1,068 1,718 S￿￿￿￿0-1-CFA 724 1,325 S￿￿￿￿0-1-CFA 772 1,528 S￿￿￿￿￿0-1-CFA 546 940 Ser9 S￿￿￿￿1-CFA 1,592 2,843 Ser3 S￿￿￿￿1-CFA 1,877 3,539 S￿￿￿￿￿1-CFA 1,068 1,718 S￿￿￿￿￿0-1-CFA 724 1,325 S￿￿￿￿￿0-1-CFA 772 1,528 OPALRTA 6,458 44,763 S￿￿￿￿￿1-CFA 1,592 2,843 S￿￿￿￿￿1-CFA 1,877 3,539 Ser7 S￿￿￿￿0-1-CFA 722 1,323 SootCHA 17,570 261,302 Ser4 S￿￿￿￿0-1-CFA 722 1,323 S￿￿￿￿1-CFA 1,590 2,841 SootRTA 17,449 259,286 Proc.ACMProgram.Lang.,Vol.8,No.OOPSLA1,Article134.Publicationdate:April2024.S￿￿￿￿￿:Taint-BasedCallGraphConstructionforJavaObjectDeserialization 134:19 %5.2 %4.2 %4.0 %5.2 %5.2 %8.0 %3.4 %3.4 %0.0 %3.4 %3.4 %0.0 %2.9 %7.8 %0.0 %2.9 %2.9 %3.2 %2.45 %1.45 %2.93 %2.45 %2.45 %4.93 %1.4 %4.5 %0.0 %1.4 %4.5 %4.0 %5.32 %0.02 %5.0 %5.32 %5.32 %1.81 %4.26 %4.26 %0.93 %4.26 %4.26 %0.93 %3.4 %8.3 %1.1 %3.4 %1.4 %1.2 %4.52 %4.52 %8.01 %4.52 %4.52 %8.01 %4.5 %4.5 %6.3 %4.5 %4.5 %6.3 PERCENTAGEOFMISSINGEDGESINTHESTATICCALLGRAPH WALA 0-1-CFA SALSA 0-1-CFA SENECA 0-1-CFA 100% WALA 1-CFA SALSA 1-CFA SENECA 1-CFA 50% 0% batik castor james jgraph jpf log4j openjms pooka xalan xerces Fig.7. PercentageofmissingedgesinthestaticcallgraphscomputedbyW￿￿￿,S￿￿￿￿,andS￿￿￿￿￿forthe projectsintheXCorpusdataset Our approach enhances the underlying pointer analysis policy in order to strike a balance between improving soundness while not greatly a￿ecting the call graph’s precision by adding spuriousnodesandedges.Amorerecentwork,S￿￿￿￿,alsoproducedcallgraphswithreasonable sizessimilartoours.However,thissimilarperformanceiscausedbythefactthatthetestcasesin theCATSdatasetarerathersimple;theyareuptotwoclassesthatexerciseonecustomcallback methodatatime.Aswewilldiscussinthenextsubsection,S￿￿￿￿’sabilitytocreatesoundcall graphsisgreatlydiminishedwhenbuildingthecallgraphforrealsoftwareprojects. 5.1.2 Dataset#2:XCorpusDataset. Figure7depictsthepercentageofedgesintheruntimecall
graphoftheprojects,thataremissingonthestaticcallgraphcomputedbyeachapproach.Fromthis chart,wenoticethatS￿￿￿￿￿outperformedW￿￿￿andS￿￿￿￿.Ourapproachhaslessmissingedges comparedtoothertheapproaches,i.e.,itisabletosoundlyinferhiddenpathsthroughserialization callbacks. Forthecastor project,S￿￿￿￿￿didnotmissanyruntimeedge.Incontrast,W￿￿￿andSalsa (0-1-CFAand1-CFA)missed4.3%oftheruntimeedges.S￿￿￿￿￿ alsodidnotmissanyruntime 0-1-CFA edgesfortwootherprojects(james,andjpf),whereasW￿￿￿ andS￿￿￿￿ missed8.7% 0-1-CFA 0-1-CFA and5.4%ofedges,respectively.Thebiggestimprovementsincomparisontootherapproacheswere observedforthetestcasescreatedforthejgraph,openjms,log4j,andxalanprojects.Thepercentage di￿erencebetweenS￿￿￿￿￿andW￿￿￿aswellasS￿￿￿￿rangedfrom5%to23.4%. WheninspectingtheedgesthatS￿￿￿￿￿missed,weobservedthattheseedgeswereunrelated to serializationcallbacks.Thatis,thesewereedgestowhichtheunderlyingpointeranalysisalgorithm cannotsoundlyinferthepoints-tosetsofvariables.Forexample,weobservededgesthatwere missedbecauseinstructionswereusingre￿ectiontoinvokemethods.Thesewereconstructsthat theunderlying0-1-CFAand1-CFApointeranalysisprovidedbyW￿￿￿(ourbaselineframework) couldnotcorrectlyinferthedispatch. OneofthereasonsastowhyS￿￿￿￿performedsimilartoS￿￿￿￿￿withtheCATStestsuitebut performedpoorlyontheXCorpusdatasethastodowithitsinabilitytocomputepotentialmethod dispatchesfromclassesintheclasspath.Asdescribedintheirwork[Santosetal.2021,2020],the approachreliesondowncastsofobjectstoinferwhataretheobject(s)beingdeserialized.When downcasts are unavailable, the approach relies on a simple approach of computing all possible dispatches,butlimitedtoclassesontheapplicationscope.Ourapproach,ontheotherhand,follows Java’sserializationspeci￿cationandincludesall classesintheclasspath,irrespectiveofitsscope (i.e.,extension,primordial,orapplicationscope). Proc.ACMProgram.Lang.,Vol.8,No.OOPSLA1,Article134.Publicationdate:April2024.134:20 JoannaC.S.Santos,MehdiMirakhorli,andAliShokri SummaryofFindingsforRQ1 – Ourexperimentsshowedthatourapproachimprovedacallgraphs’soundnesswithrespect toserialization-relatedfeatures.Itaddednodesandedgesinthecallgraphthatcouldariseat runtimeduringserializationanddeserializationofobjects. – Our approach passed all test cases, whereas other approaches, namely Soot RTA, Soot RTA passedonly2,andOPAL passed5. RTA – TheonlycallgraphconstructionalgorithmsusedbySoot,andOpalthatprovidedpartial supportforserializationusedalgorithmsthatonlyrelyonthemethod’ssignaturesfordispatch (i.e.,CHAandRTA).Hence,theycreatedmuchlargercallgraphsbecausetheyintroduced spuriousnodesandedges. – AlthoughS￿￿￿￿,arecentlypublishedwork,alsopassedallthetestcasesintheCATStest suite,itfailedtosoundlyinferthecallbacksinrealapplicationsfromtheXCorpusdataset. 5.2 RQ2:Precision ThissectiondescribestheevaluationresultsoftheprecisionofthecallgraphscomputedbyS￿￿￿￿￿. 1500 1000 500 0 8reS 9reS 8reS 9reS 1reS 2reS 5reS 7reS 9reS 1reS 2reS 3reS 4reS 5reS 6reS 7reS 8reS 9reS 1reS 2reS 3reS 4reS 5reS 6reS 7reS 8reS 9reS 1reS 2reS 3reS 4reS 5reS 6reS 7reS 8reS 9reS 1reS 2reS 3reS 4reS 5reS 6reS 7reS 8reS 9reS # INCORRECTEDGESPERAPPROACH Soot Soot OPAL (RTA) Salsa (0-1-CFA) Salsa (1-CFA) Seneca (0-1-CFA) Seneca (1-CFA) (CHA) (RTA) Fig.8. PrecisionresultsforthetestcasesfromtheCATStestsuite. 5.2.1 Dataset#1:CATS. Figure8depictsthenumberofedgesinthestatic callgraphthatwere notfoundintheruntimecallgraphforthetestcasesintheCATStestsuite[Reifetal.2019].As showninthischart,S￿￿￿￿￿wasabletoprovidefullsupportforserializationcallbacks(passingall testcases,seeTable4)whilemaintainingreasonablysizedcallgraphs.SootandOPALderivedcall graphsthatwerefarmoreimprecise.WhileO￿￿￿andS￿￿￿hadover800impreciseedges(false positives-FP),S￿￿￿￿￿hadbetween95and343incorrectedges.Therefore,S￿￿￿andO￿￿￿had,on average,8.8 timesand4.8 timesincorrectedgesthanS￿￿￿￿￿,respectively. ⇥ ⇥ ThiscomparisonalsoshowsthatS￿￿￿￿’sperformancewassimilartoS￿￿￿￿￿.Asexplainedin theprevioussection,however,thissimilarperformanceiscausedbythefactthattheprogramsin theCATStestsuitearesmall;theydonotincludescenarioswhereS￿￿￿￿’sunsoundassumptions fallshort. 5.2.2 Dataset#2:XCorpusDataset. Figure9plotsthepercentageofedgesthatareintheruntime callgraph,butthatarenotinthestaticcallgraphofeachapproach.Asobservedonthischart, unsurprisingly,increasingthesoundnessofthecallgraphalsoincreasedthenumberofimprecise edges(i.e.,edgesthatdidnotariseatruntime).Theincreaseofmissededgesiscomparabletothe onebyS￿￿￿￿. Whenweinspectedtheimpreciseedges,wenoticedthatthosewererelatedtoserializationnodes, i.e.,casesinwhichourcallgraphincludedall possibleobjectsthatcanbeserialized.Indeed,asour testcasesserializedonlyoneobjectatatime,alltheseedgesaredeemedasincorrect.However,as theJavaAPIallowsthedeserializationofarbitrarytypes(i.e.,anyserializabletypeavailableonthe Proc.ACMProgram.Lang.,Vol.8,No.OOPSLA1,Article134.Publicationdate:April2024.S￿￿￿￿￿:Taint-BasedCallGraphConstructionforJavaObjectDeserialization 134:21 %4.3 %1.4 %3.8 %2.1 %6.1 %5.3 %4.0 %2.0 %4.72 %2.0 %1.0 %2.51 %4.0 %2.0 %5.01 %1.0 %1.0 %5.4 %3.2 %7.2 %6.71 %8.0 %3.1 %3.9 %8.0 %7.0 %7.0 %3.0 %3.0 %3.0 %9.02 %9.42 %3.42 %8.6 %9.8 %4.9 %2.5 %2.6 %7.21 %8.1 %6.2 %4.5 %6.0 %5.0 %4.72 %2.0 %2.0 %3.41 %4.0 %2.0 %8.01 %1.0 %1.0 %7.4 %5.0 %2.0 %4.71
%2.0 %1.0 %7.7 100% WALA 0-1-CFA SALSA 0-1-CFA SENECA 0-1-CFA PERCENTAGEOFINCORRECTEDGESINTHESTATICCALLGRAPH WALA 1-CFA SALSA 1-CFA SENECA 1-CFA 80% 60% 40% 20% 0% batik castor james jgraph jpf log4j openjms pooka xalan xerces Fig.9. Percentageofincorrectedges(i.e.,edgesintheruntimeCGnotinthestaticCG)foreachapproach classpath),theedgesinS￿￿￿￿￿couldariseatruntimeifanobjectbeingreadusesoneoftheother serializableclasses(otherthantheonefromthetestcase). SummaryofFindingsforRQ2 – FortheCATSdataset,S￿￿￿andO￿￿￿computedcallgraphsthatwerefarmoreimprecise thanS￿￿￿￿￿,anaverageof8.8 and4.8 moreincorrectedges,respectively. ⇥ ⇥ – WhileS￿￿￿￿andS￿￿￿￿￿hadasimilaramountofincorrectedgesfortheCATSbenchmark, S￿￿￿￿producedcallgraphswithmoreimpreciseedgesthanS￿￿￿￿￿forthetestcasescreated fortheprojectsintheXCorpusdataset. 5.3 RQ3:Performance We measured the running time observed when computing the call graphs using W￿￿￿, S￿￿￿￿, andS￿￿￿￿￿,con￿guredwith0-1-CFAand1-CFApointeranalysispolicies.Theresultsforthese experimentsareshowninFigure10.Aswewouldexpect,S￿￿￿￿￿takeslongertocomputecall graphsasithastoprocessnodesandedgesrelatedserialization. Theobserveddi￿erences,however,donothindertheoverallscalabilityoftheapproach.The approachstill￿nisheswithinsecondsofexecution.Moreover,whenfurtherinspectingtheworklist ofouralgorithm,wenoticedthatS￿￿￿￿￿incursbetween3–6extraiterationsoverW￿￿￿’sworklist. Theseextraiterationsalongwiththetaintanalysisaretherootcausefortheextrarunningtime neededforS￿￿￿￿￿to￿nish. AVERAGERUNNINGTIME(MS) FOREACHAPPROACH 5000 WALA 0-1-CFA SALSA 0-1-CFA SENECA 0-1-CFA 4000 WALA 1-CFA SALSA 1-CFA SENECA 1-CFA 3000 2000 1000 0 batik castor james jgraph jpf log4j openjms pooka xalan xerces Fig.10. Thetotalrunningtime(milliseconds)thatittookeachapproachtocomputeacallgraph. SummaryofFindingsforRQ3 – S￿￿￿￿￿’sperformance,whenevaluatedagainstanestablishedbenchmark,hasbeenfoundto notinducegreatoverheadontheunderlyingcallgraphconstructionapproach.Thismakes S￿￿￿￿￿aviableoptionfordevelopersandresearchersinneedofsoundcallgraphforanalyzing programsthatheavilyuseserializationconstructs. Proc.ACMProgram.Lang.,Vol.8,No.OOPSLA1,Article134.Publicationdate:April2024.134:22 JoannaC.S.Santos,MehdiMirakhorli,andAliShokri 5.4 RQ4:UsefulnessforVulnerabilityDetection Wehaveimplementedaclientanalysesthatattemptsto￿ndvulnerablepathscausedbyuntrusted objectdeserializationinaprogram.Wethenveri￿edhowwellthisclientanalysiscoulddetect vulnerablepathsbycomparingitsperformanceusingthecallgraphcomputedbyS￿￿￿￿andthe onegeneratedbyS￿￿￿￿￿.TheresultsforthisexperimentareshowninTable6. Table6. NumbervulnerablepathsfoundbyaclientanalysesthatusedS￿￿￿￿’sandS￿￿￿￿￿’scallgraphs FileUpload Vaadin Wicket SALSA SENECA SALSA SENECA SALSA SENECA 0-1-CFA 1-CFA 0-1-CFA 1-CFA 0-1-CFA 1-CFA 0-1-CFA 1-CFA 0-1-CFA 1-CFA 0-1-CFA 1-CFA #Vuln.Paths 0 0 14 12 0 0 4 0 0 0 20 34 As shown in this table, S￿￿￿￿’s call graphs were not suitable for performing vulnerability detection. The key issue lies on the unsoundness of S￿￿￿￿. This approach relies on type casts (downcasts) to infer what object is being deserialized from a stream. However, as explained in Section2.1,untrustedobjectdeserializationvulnerabilitiesarecausedbytheabilityofanattacker tocraftarbitraryobjectsusingany serializableclassavailableintheclasspath.Thus,evenifthe programperformsadowncastovertheserializedobject,theexploitwouldhavebeenexecuted anyway,asthevulnerabilityarisesduring deserializationandnotafterit. UnlikeS￿￿￿￿,ourapproachwasableto￿ndvulnerablepathswithinourallocatedtimebudget(of 15minutesandupto15callgraphnodesinapath).Theidenti￿edpathsincludedthevulnerablepaths frompreviouslydisclosedgadgetchains,documentedontheYSoSerialrepositoryofdeserialization exploits[Froho￿2018]. SummaryofFindingsforRQ4 – Weshowedthebene￿tsofasoundcallgraphwithrespecttodeserializationbyimplementa clientstaticanalysisthatdetectvulnerablepathscausedbyuntrustedobjectdeserialization. OurresultsshowedthatwhileS￿￿￿￿￿isableto￿ndpreviouslydisclosedvulnerablepaths, anexistingapproach(S￿￿￿￿)fallsshortingeneratingcallgraphsthatcaninferthesehidden vulnerablepaths. – Theexperimentshighlighttheimportanceofbuildingcallgraphsthataresoundwithrespect to deserialization features and demonstrate that S￿￿￿￿￿ can be suitable for downstream analysesthatrequirethehandlingofserializationconstructsinasoundfashion. 6 RELATEDWORK Thissectiondiscussesrelevantworksrelatedtoobjectdeserializationandcallgraphconstruction. 6.1 CallgraphConstruction&TamingChallengingProgrammingFeatures Call graphs are a core data structure for multiple analyses. Thus, previous works focused on devisingalgorithmsfortheirconstruction.Amongtheseworks,wehaveCHA[Deanetal.1995] andRTA[BaconandSweeney1996],whicharetwowell-knownalgorithmsthatover-approximates possiblecallpathsbyrelyingonmethods’signatures.Sincethesealgorithmsareoverlyconservative, multiple works discussed frameworks to make them more precise [Grove and Chambers 2001; Groveetal.1997;TipandPalsberg2000].Moreover,previousresearchalsofocusedoncreating application-onlycallgraphs,thatdisregardunnecessarylibraryclasses,whilekeepingonthegraph thenodesandedgesthatareimportantfortheunderlyinganalysis[AliandLhoták2012].Inthis Proc.ACMProgram.Lang.,Vol.8,No.OOPSLA1,Article134.Publicationdate:April2024.S￿￿￿￿￿:Taint-BasedCallGraphConstructionforJavaObjectDeserialization 134:23 paper,wefocusedonsolvingthechallengeofcomputingcallgraphsthataresoundconcerning objectserializationanddeserialization. Previousresearchonstaticanalysisalsoexploredthechallengesinvolvingsupportingre￿ection features[Boddenetal.2011;Lietal.2014,2019;Smaragdakisetal.2015],dynamicproxies[Four- tounisetal.2018],enterpriseframeworks[Antoniadisetal.2020]andRMI-basedprograms[Sharp andRountev2006].Theseapproachesinvolvemakingassumptionswhenperformingtheanalysis, tocreateanalysesthatarenotoverlyimprecise.Unlikethesepriorworks,however,wefocusedon objectdeserializationthathasitsownuniquechallenges,asdescribedinSection2.2. 6.2 EmpiricalStudiesonCallGraphs Multiplecharacteristicsofcallgraphs(e.g.,precision,soundness,performance,andrecall)have
beenwidelystudiedinthepast[Alietal.2019;Kummitaetal.2021;Murphyetal.1998;Suietal. 2020].Murphyetal.[Murphyetal.1998]studiedmultiplecallgraphconstructionapproachesfor Cprograms,￿ndingdiscrepanciesamongthegeneratedcallgraphsacrossdi￿erentapproaches. Suietal.[Suietal.2018]focusedonthesupportfordynamiclanguagefeatures,aimingtocreatea benchmarkfordynamicfeaturesforJava. Thereisalineofresearchthatexploredcallgraph’ssoundnessofJava(orJVM-like)programs[Ali et al. 2019; Reif et al. 2019, 2018]. In particular, recent empirical studies [Reif et al. 2019, 2018] showthatalthoughserialization-relatedfeaturesarewidelyused,theyarenotwell-supportedin existingapproaches.Thus,webuiltanapproachtoenhanceexistingpoints-toanalysistosupport theconstructionofsoundcallgraphswithrespecttoserialization-relatedfeatures. 6.3 PointerAnalysis Manyworksexploredtheproblemofperformingpointeranalysisofprograms[Bastanietal.2019; Fengetal.2015;HeintzeandTardieu2001;Hind2001;KastrinisandSmaragdakis2013;Lhotákand Hendren2006;Rountevetal.2001;SmaragdakisandKastrinis2018].Theseapproachesfocuson computingover-orunder-approximationstoimproveoneormoreaspectsoftheanalysis,suchas itssoundness,precision,performance,andscalability.Existingpointeranalysisapproachesmake thesets￿nitesuchthattheproblemcanbealgorithmicallysolvable.Inthispaper,however,we focusonaidingpointstoanalysistosoundlyhandleserialization-relatedfeaturesinaprogram, whicharecurrentlynotwell-supportedbecauseitreliesonre￿ection[Reifetal.2018]. 6.4 DetectingUntrustedObjectDeserialization Morerecentlytherewereapproachespublishedthataimedatdetectinguntrustedobjectdeserial- izationforPHP[Koutroumpouchosetal.2019;ShahriarandHaddad2016]and.NET[Shcherbakov andBalliu2021].ShcherbakovandBalliu[ShcherbakovandBalliu2021]describedanapproachto semi-automaticallydetectandexploitobjectinjectionvulnerabilities.NETapplications.Itrelieson existingpubliclyavailablegadgetstoperformthedetectionandexploitation.Koutroumpouchoset al. described ObjectMap [Koutroumpouchos et al. 2019] which is tool that performs black-box analysisofWebapplicationstopinpointpotentialinsecuredeserializationvulnerabilities.Itworks byinsertingpayloadsintotheparametersofHTTPGET/POSTrequestsandthenmonitoringthe targetwebapplicationforerrorstoinferwhethertheapplicationisvulnerableornot. Recentworks[Caoetal.2023;Haken2018;RasheedandDietrich2020]focusedondeserialization vulnerabilitiesinJavaprograms.RasheedandDietrich[RasheedandDietrich2020]describeda hybridapproachthat￿rstperformsastaticanalysisofaJavaprogramto￿ndpotentialcallchains thatcanleadtosinks,wherere￿ectivemethodcallsaremade.Itthenusestheresultsofthestatic analysistoperformfuzzinginordertogeneratemaliciousobjects. Proc.ACMProgram.Lang.,Vol.8,No.OOPSLA1,Article134.Publicationdate:April2024.134:24 JoannaC.S.Santos,MehdiMirakhorli,andAliShokri Unlikethesepriorworks,weaimedtocreateanapproachthatcancreatesoundcallgraphswith respecttoserialization-relatedfeatures.Ourcallgraphisintendedtobeusedbydownstreamclient analyses,including,butnotlimitedto,vulnerabilitydetection. 6.5 EmpiricalStudiesonUntrustedObjectDeserialization In the past few years, we observed a spike of vulnerabilities associated with deserialization of objects[Cifuentesetal.2015].Thus,existingworksalsostudiedvulnerabilitiesrootedatuntrusted deserializationvulnerabilities[Dietrichetal.2017a;PelesandHay2015;Sayaretal.2023].Peles et al. [Peles and Hay 2015] conducted an empirical investigation of deserialization of pointers thatleadtovulnerabilitiesinAndroidapplicationsandSDKs.Dietrichetal.[Dietrichetal.2017a] demonstratedhowseeminglyinnocuousobjectstriggervulnerabilitieswhendeserialized,leading todenialofserviceattacks.Inthispaper,wedescribeanapproachthatcouldhelpclientanalyses focusedondetectinginstancesofuntrustedobjectdeserialization.Sayaretal.[Sayaretal.2023]in- vestigateddeserializationvulnerabilitiesinJavaapplications,showingthatasigni￿cantproportion oflibrariescontainunpatchedexploitablecodefragments(gadgets)aswellasmanyofthestudied vulnerabilitieswereimproperly￿xedoronlymitigatedthroughworkarounds. Whilethesepreviousworkshighlightedthecriticalnatureofuntrustedobjectdeserialization, ourpaperaimstocreatecallgraphsthataresoundwithrespecttoserialization/deserialization featuresinJavaprograms.Ourapproachcanbeusedasabuildingblockfordownstreamstatic analyzerstodetectuntrustedobjectdeserializationinJavacodebases. 7 THREATSTOVALIDITY Themainconstructvaliditythreat[RunesonandHöst2009]tothisworkrelatestohowwemeasure soundness and precision of the constructed call graphs. To compute these metrics, we followed similarmethodologyemployedbyseveralpriorworks[Alietal.2019;AliandLhoták2012;Kummita etal.2021;Lietal.2014;Smaragdakisetal.2015].Speci￿cally,wemeasuresoundnessandprecision bycomparingstaticcallgraphstoruntimecallgraphs. One of the key challenges when it comes to computing soundness and precision is that it is di￿culttocreateaprogram’sgroundtruth,thatis,thecallgraphthatrepresentsallpossibleruntime behaviorsatruntime.Tomitigatethisthreatandensurethatourruntimecallgraphsareasuitable approximationofthegroundtruth,wecreated210testcasesinwhichwehadrealprogramswith severalobjectsbeingserialized/deserialized,suchthatwecoverall possibleserializationcallbacks availableintheprogram’sclasspath(asdescribedinSection4).Eachtestcaseisaprogramthat
serializes/deserializesoneobject(thisobjectcanbeanindividualserializableobject,oraserializable collectioncontaininganotherserializableobject).Thisway,thecomputedruntimecallgraphscan enableareliablecomparisonofsoundnessandprecisionofforthecallgraphsunderevaluation. Another threat to the validity of this work is that in RQ1 (Section 5.1, Table 5) we compare thecallgraphs’sizesasmeanstoapproximatehowprecisetheyare(i.e.,smallercallgraphsare likelymoreprecisethanbiggerones).Whileitispossiblethatthesmallercallgraphsaremissing requirededges,inthisparticularexperiment,weusedamanuallycuratedbenchmark(CATS)which includesmall programsthatcontainuptotwoclasseseachandareenrichedwithannotationsthat indicatetheexpectedtargetforagivenmethodcall.Assuch,sinceweveri￿edwhethereachcall graphcontainedtheexpectedserialization-relatedcallbacknodesandedgesandtheprogramsare expectedtobesmall,abiggercallgraphthatismissingrequirededgesis,consequently,imprecise. Infact,whileO￿￿￿andS￿￿￿didnotincludealltheexpectednodes/edges(seeTable4),theyhad muchlargercallgraphsthanS￿￿￿￿andS￿￿￿￿￿(Table5). An external validity threat [Runeson and Höst 2009] to this work concerns the fact that we evaluatedS￿￿￿￿￿’sperformanceonprogramsthatusedserializationfeatures.Thatis,wehave Proc.ACMProgram.Lang.,Vol.8,No.OOPSLA1,Article134.Publicationdate:April2024.S￿￿￿￿￿:Taint-BasedCallGraphConstructionforJavaObjectDeserialization 134:25 notmeasuredtheperformanceimpactonprogramsthatdonotuse(orrarelyuse)serialization features.However,itisimportanttohighlightthatS￿￿￿￿￿doesnothaveanadditionaloverheadin programsthatdonotuseserialization.S￿￿￿￿￿only incursextraiterationsontheunderlyingcall graphconstructionalgorithmuponencounteringaserialization/deserializationpoint(asdescribed inSection3).Thus,whenaprogramdoesnotperformserialization/deserializationorusethese sparingly,theoverheadissimilarastoWALA;itsbaselinetechnique. 8 CONCLUSION Wepresentedanapproachtosupportthestaticanalysisofserialization-relatedfeaturesinJava programs.Itworksundertheassumptionthatonlyclassesintheclasspathareserialized/deserialized, alloftheirinstance￿eldsarenon-nullsandcanbeallocatedwithanytypethatissafe.Byapplying theseassumptionsandrelyingonAPImodeling,ourapproachaddssyntheticnodesintoapreviously computedcallgraphtoimproveitssoundnesswithrespecttoserialization-relatedfeatures. Weevaluatedourapproachwithrespecttoitssoundness (RQ1),precision(RQ2),performance (RQ3),andusefulnessforadownstreamclientanalysis(RQ4).Weused9programsfromtheCATS TestSuite[Reifetal.2018]and10projectsfromtheXCorpusdataset[Dietrichetal.2017b].We compared our approach soundness and precision against o￿-the-shelf construction algorithms availableonSoot[Vallée-Raietal.1999],Wala[WALA2024],OPAL[EichbergandHermann2014] andDoop[BravenboerandSmaragdakis2009]. Inourexperiments,wefoundthatonlythecallgraphsthatusedCHAorRTAcould(partially) inferthecallbackmethodsthatcouldariseatruntime.Ourapproach,ontheotherhand,provided support for all the callback methods in the serialization and deserialization . In an analysis by comparing runtime call graphs with the statically build call graphs, our approach introduced lessspuriousedges.Finally,bymeasuringtherunningtimesofourapproach,comparedwithits counterpartcallgraphconstructionalgorithm(S￿￿￿￿andW￿￿￿),wefoundthatourapproachdid notincursigni￿cantoverhead. DATA-AVAILABILITYSTATEMENT The scripts and data to obtain the experimental results described in Section 4 and S￿￿￿￿￿’s implementationareavailableinourGitHubrepository(https://github.com/s2e-lab/seneca/)and Zenodo(https://zenodo.org/doi/10.5281/zenodo.10464129). ACKNOWLEDGMENTS This material is based upon work supported by the National Science Foundation under Grant No.CCF-1943300. REFERENCES 2023. TensorFlow. https://www.tensor￿ow.org [Online;accessed21.Oct.2023]. KarimAli,XiaoniLai,ZhaoyiLuo,OndrejLhotak,JulianDolby,andFrankTip.2019.AStudyofCallGraphConstructionfor JVM-HostedLanguages.IEEETransactionsonSoftwareEngineering(2019),1–1. https://doi.org/10.1109/TSE.2019.2956925 KarimAliandOndřejLhoták.2012. Application-onlycallgraphconstruction.InEuropeanConferenceonObject-Oriented Programming.Springer,688–712. AnastasiosAntoniadis,NikosFilippakis,PaddyKrishnan,RaghavendraRamesh,NicholasAllen,andYannisSmaragdakis. 2020.StaticanalysisofJavaenterpriseapplications:frameworksandcaches,theelephantsintheroom..InPLDI.794–807. StevenArzt,SiegfriedRasthofer,ChristianFritz,EricBodden,AlexandreBartel,JacquesKlein,YvesLeTraon,Damien Octeau,andPatrickMcDaniel.2014. FlowDroid:PreciseContext,Flow,Field,Object-SensitiveandLifecycle-Aware TaintAnalysisforAndroidApps.InProceedingsofthe35thACMSIGPLANConferenceonProgrammingLanguage Design and Implementation (Edinburgh, United Kingdom) (PLDI ’14). ACM, New York, NY, USA, 259–269. https: //doi.org/10.1145/2594291.2594299 Proc.ACMProgram.Lang.,Vol.8,No.OOPSLA1,Article134.Publicationdate:April2024.134:26 JoannaC.S.Santos,MehdiMirakhorli,andAliShokri DavidFBaconandPeterFSweeney.1996. FaststaticanalysisofC++virtualfunctioncalls.InProceedingsofthe11thACM SIGPLANconferenceonObject-orientedprogramming,systems,languages,andapplications.324–341. https://doi.org/10. 1145/236337.236371
OsbertBastani,RahulSharma,LazaroClapp,SaswatAnand,andAlexAiken.2019. EventuallySoundPoints-ToAnalysis withSpeci￿cations.In33rdEuropeanConferenceonObject-OrientedProgramming(ECOOP2019).SchlossDagstuhl- Leibniz-ZentrumfuerInformatik. https://doi.org/10.4230/LIPIcs.ECOOP.2019.11 EricBodden,AndreasSewe,JanSinschek,HelaOueslati,andMiraMezini.2011. TamingRe￿ection:AidingStaticAnalysis inthePresenceofRe￿ectionandCustomClassLoaders.InProceedingsofthe33rdInternationalConferenceonSoftware Engineering(ICSE’11).ACM,NewYork,NY,USA,241–250. https://doi.org/10.1145/1985793.1985827 MartinBravenboerandYannisSmaragdakis.2009. StrictlyDeclarativeSpeci￿cationofSophisticatedPoints-toAnalyses.In Proceedingsofthe24thACMSIGPLANConferenceonObjectOrientedProgrammingSystemsLanguagesandApplications (Orlando,Florida,USA)(OOPSLA’09).AssociationforComputingMachinery,NewYork,NY,USA,243–262. https: //doi.org/10.1145/1640089.1640108 SicongCao,BiaoHe,XiaobingSun,YuOuyang,ChaoZhang,XiaoxueWu,TingSu,LiliBo,BinLi,ChuanleiMa,etal. 2023. ODDFUZZ:DiscoveringJavaDeserializationVulnerabilitiesviaStructure-AwareDirectedGreyboxFuzzing. arXiv preprintarXiv:2304.04233(2023). CristinaCifuentes,AndrewGross,andNathanKeynes.2015. UnderstandingCaller-SensitiveMethodVulnerabilities: AClassofAccessControlVulnerabilitiesintheJavaPlatform.InProceedingsofthe4thACMSIGPLANInternational WorkshoponStateOftheArtinProgramAnalysis(Portland,OR,USA)(SOAP2015).ACM,NewYork,NY,USA,7–12. https://doi.org/10.1145/2771284.2771286 RonCytron,JeanneFerrante,BarryK.Rosen,MarkN.Wegman,andF.KennethZadeck.1991. E￿cientlyComputingStatic SingleAssignmentFormandtheControlDependenceGraph. ACMTrans.Program.Lang.Syst.13,4(1991),451–490. https://doi.org/10.1145/115372.115320 Je￿reyDean,DavidGrove,andCraigChambers.1995.Optimizationofobject-orientedprogramsusingstaticclasshierarchy analysis.InEuropeanConferenceonObject-OrientedProgramming.Springer,77–101. https://doi.org/10.1007/3-540-49538- X_5 JensDietrich,KamilJezek,ShawnRasheed,AmjedTahir,andAlexPotanin.2017a.EvilPickles:DoSAttacksBasedonObject- GraphEngineering.In31stEuropeanConferenceonObject-OrientedProgramming(ECOOP2017),Vol.74.SchlossDagstuhl– Leibniz-ZentrumfuerInformatik,Dagstuhl,Germany,10:1–10:32. https://doi.org/10.4230/LIPIcs.ECOOP.2017.10 JensDietrich,HenrikSchole,LiSui,andEwanTempero.2017b.XCorpus–AnexecutableCorpusofJavaPrograms.Journal ofObjectTechnology16,4(Aug.2017),1:1–24. https://doi.org/10.5381/jot.2017.16.4.a1 JulianDolby,MandanaVaziri,andFrankTip.2007. Findingbugse￿cientlywithaSATsolver.InProceedingsofthethe6th jointmeetingoftheEuropeansoftwareengineeringconferenceandtheACMSIGSOFTsymposiumonThefoundationsof softwareengineering.195–204. MichaelEichberg.2020. JCG-SerializableClasses. https://bitbucket.org/delors/jcg/src/master/jcg_testcases/src/main/ resources/Serialization.md. (Accessedon06/01/2020). MichaelEichbergandBenHermann.2014.ASoftwareProductLineforStaticAnalyses:TheOPALFramework.InProceedings ofthe3rdACMSIGPLANInternationalWorkshopontheStateoftheArtinJavaProgramAnalysis(Edinburgh,United Kingdom)(SOAP’14).AssociationforComputingMachinery,NewYork,NY,USA,1–6. https://doi.org/10.1145/2614628. 2614630 WilliamEnck,PeterGilbert,SeungyeopHan,VasantTendulkar,Byung-GonChun,LandonP.Cox,JaeyeonJung,Patrick McDaniel,andAnmolN.Sheth.2014.TaintDroid:AnInformation-FlowTrackingSystemforRealtimePrivacyMonitoring onSmartphones. ACMTrans.Comput.Syst.32,2,Article5(June2014),29pages. https://doi.org/10.1145/2619091 A.Feldthaus,M.Schäfer,M.Sridharan,J.Dolby,andF.Tip.2013. E￿cientconstructionofapproximatecallgraphs forJavaScriptIDEservices.In201335thInternationalConferenceonSoftwareEngineering(ICSE).752–761. https: //doi.org/10.1109/ICSE.2013.6606621 YuFeng,XinyuWang,IsilDillig,andThomasDillig.2015. Bottom-UpContext-SensitivePointerAnalysisforJava.In ProgrammingLanguagesandSystems-13thAsianSymposium,APLAS2015,Pohang,SouthKorea,November30-December 2,2015,Proceedings(LectureNotesinComputerScience,Vol.9458),XinyuFengandSungwooPark(Eds.).Springer,465–484. https://doi.org/10.1007/978-3-319-26529-2_25 GeorgeFourtounis,GeorgeKastrinis,andYannisSmaragdakis.2018. StaticanalysisofJavadynamicproxies.InProceedings ofthe27thACMSIGSOFTInternationalSymposiumonSoftwareTestingandAnalysis.209–220. ChrisFroho￿.2018. froho￿/ysoserial:Aproof-of-concepttoolforgeneratingpayloadsthatexploitunsafeJavaobject deserialization. https://github.com/froho￿/ysoserial. (Accessedon05/26/2018). DavidGroveandCraigChambers.2001. Aframeworkforcallgraphconstructionalgorithms. ACMTransactionson ProgrammingLanguagesandSystems(TOPLAS)23,6(2001),685–746. Proc.ACMProgram.Lang.,Vol.8,No.OOPSLA1,Article134.Publicationdate:April2024.S￿￿￿￿￿:Taint-BasedCallGraphConstructionforJavaObjectDeserialization 134:27
DavidGrove,GregDeFouw,Je￿reyDean,andCraigChambers.1997. Callgraphconstructioninobject-orientedlanguages. InProceedingsofthe12thACMSIGPLANconferenceonObject-orientedprogramming,systems,languages,andapplications (OOPSLA’97).ACM,NewYork,NY,USA,108–124. https://doi.org/10.1145/263698.264352 IanHaken.2018. AutomatedDiscoveryofDeserializationGadgetChains. NevinHeintzeandOlivierTardieu.2001. Demand-drivenpointeranalysis. ACMSIGPLANNotices36,5(2001),24–34. https://doi.org/10.1145/381694.378802 MichaelHind.2001.Pointeranalysis:Haven’twesolvedthisproblemyet?.InProceedingsofthe2001ACMSIGPLAN-SIGSOFT workshoponProgramanalysisforsoftwaretoolsandengineering.54–61. https://doi.org/10.1145/379605.379665 StephenHines,PrasadKulkarni,DavidWhalley,andJackDavidson.2005. UsingDe-OptimizationtoRe-OptimizeCode (EMSOFT’05).AssociationforComputingMachinery,NewYork,NY,USA,114–123. https://doi.org/10.1145/1086228. 1086251 N.Jovanovic,C.Kruegel,andE.Kirda.2006.Pixy:astaticanalysistoolfordetectingWebapplicationvulnerabilities.In2006 IEEESymposiumonSecurityandPrivacy(SP’06).6pp.–263. https://doi.org/10.1109/SP.2006.29 GeorgeKastrinisandYannisSmaragdakis.2013.Hybridcontext-sensitivityforpoints-toanalysis.ACMSIGPLANNotices48, 6(2013),423–434. https://doi.org/10.1145/2499370.2462191 R.Khatchadourian,Y.Tang,M.Bagherzadeh,andS.Ahmed.2019.SafeAutomatedRefactoringforIntelligentParallelization ofJava8Streams.In2019IEEE/ACM41stInternationalConferenceonSoftwareEngineering(ICSE).619–630. https: //doi.org/10.1109/ICSE.2019.00072 NikolaosKoutroumpouchos,GeorgiosLavdanis,EleniVeroni,ChristoforosNtantogian,andChristosXenakis.2019. Ob- jectMap:detectinginsecureobjectdeserialization.InProceedingsofthe23rdPan-HellenicConferenceonInformatics. 67–72. SritejaKummita,GoranPiskachev,JohannesSpäth,andEricBodden.2021. QualitativeandQuantitativeAnalysisof CallgraphAlgorithmsforPython.In2021InternationalConferenceonCodeQuality(ICCQ).IEEE,1–15. https://doi.org/ 10.1109/ICCQ51190.2021.9392986 DavyLandman,AlexanderSerebrenik,andJurgenJ.Vinju.2017.ChallengesforStaticAnalysisofJavaRe￿ection:Literature ReviewandEmpiricalStudy.InProceedingsofthe39thInternationalConferenceonSoftwareEngineering(BuenosAires, Argentina)(ICSE’17).IEEE,NewYork,NY,USA,507–518. https://doi.org/10.1109/ICSE.2017.53 OndřejLhotákandLaurieHendren.2006. Context-sensitivepoints-toanalysis:isitworthit?.InInternationalConferenceon CompilerConstruction.Springer,47–64. https://doi.org/10.1007/11688839_5 YueLi,TianTan,YuleiSui,andJinglingXue.2014.Self-InferencingRe￿ectionResolutionforJava.InProceedingsofthe28th EuropeanConferenceonECOOP2014—Object-OrientedProgramming-Volume8586.Springer-Verlag,Berlin,Heidelberg, 27–53. https://doi.org/10.1007/978-3-662-44202-9_2 YueLi,TianTan,andJinglingXue.2019. UnderstandingandanalyzingJavare￿ection. ACMTransactionsonSoftware EngineeringandMethodology(TOSEM)28,2(2019),1–50. https://doi.org/10.1145/3295739 LiuPing,SuJin,andYangXinfeng.2011. Researchonsoftwaresecurityvulnerabilitydetectiontechnology.InProceedings of2011InternationalConferenceonComputerScienceandNetworkTechnology,Vol.3.1873–1876. https://doi.org/10.1109/ ICCSNT.2011.6182335 AlvaroMuñozandChristianSchneider.2018. Serialkiller:SilentlypwningyourJavaendpoints. http://www.slideshare.net/ cschneider4711/owasp-benelux-day-2016-serial-killer-silently-pwning-your-java-endpoints. (Accessedon11/15/2019). GailCMurphy,DavidNotkin,WilliamGGriswold,andEricaSLan.1998.Anempiricalstudyofstaticcallgraphextractors. ACMTransactionsonSoftwareEngineeringandMethodology(TOSEM)7,2(1998),158–191. NSACenterforAssuredSoftware.2017. JulietJava1.3. https://samate.nist.gov/SARD/test-suites/111 [Online;accessed1. May.2022]. Oracle. 2010. Java Object Serialization Speci￿cation - version 6.0. https://docs.oracle.com/javase/8/docs/platform/ serialization/spec/serialTOC.html. (Accessedon04/07/2020). OrPelesandRoeeHay.2015. OneClasstoRuleThemAll:0-DayDeserializationVulnerabilitiesinAndroid.In9thUSENIX WorkshoponO￿ensiveTechnologies(WOOT15).USENIXAssociation,Washington,D.C.,12. ShawnRasheedandJensDietrich.2020. AhybridanalysistodetectJavaserialisationvulnerabilities.InProceedingsofthe 35thIEEE/ACMInternationalConferenceonAutomatedSoftwareEngineering.1209–1213. MichaelReif.2023. mreif/jcg-DockerImage DockerHub. https://hub.docker.com/r/mreif/jcg [Online;accessed20.Oct. | 2023]. MichaelReif,FlorianKübler,MichaelEichberg,DominikHelm,andMiraMezini.2019. Judge:Identifying,Understanding, andEvaluatingSourcesofUnsoundnessinCallGraphs.InProceedingsofthe28thACMSIGSOFTInternationalSymposium onSoftwareTestingandAnalysis(Beijing,China)(ISSTA2019).ACM,NewYork,NY,USA,251–261. https://doi.org/10. 1145/3293882.3330555 MichaelReif,FlorianKübler,MichaelEichberg,andMiraMezini.2018. SystematicEvaluationoftheUnsoundnessofCall
GraphConstructionAlgorithmsforJava.InCompanionProceedingsfortheISSTA/ECOOP2018Workshops(ISSTA’18). Proc.ACMProgram.Lang.,Vol.8,No.OOPSLA1,Article134.Publicationdate:April2024.134:28 JoannaC.S.Santos,MehdiMirakhorli,andAliShokri ACM,NewYork,NY,USA,107–112. https://doi.org/10.1145/3236454.3236503 HenryGordonRice.1953. Classesofrecursivelyenumerablesetsandtheirdecisionproblems. Trans.Amer.Math.Soc.74,2 (1953),358–366. BarryKRosen,MarkNWegman,andFKennethZadeck.1988. Globalvaluenumbersandredundantcomputations.In Proceedingsofthe15thACMSIGPLAN-SIGACTsymposiumonPrinciplesofprogramminglanguages.12–27. AtanasRountev,AnaMilanova,andBarbaraGRyder.2001. Points-toanalysisforJavausingannotatedconstraints. ACM SIGPLANNotices36,11(2001),43–55. https://doi.org/10.1145/504311.504286 P.RunesonandM.Höst.2009. GuidelinesforConductingandReportingCaseStudyResearchinSoftwareEngineering. EmpiricalSoftw.Engg.14,2(apr2009),131–164. https://doi.org/10.1007/s10664-008-9102-8 JoannaC.S.Santos,ReeseA.Jones,ChinomsoAshiogwu,andMehdiMirakhorli.2021. Serialization-AwareCallGraph Construction.InProceedingsofthe10thACMSIGPLANInternationalWorkshopontheStateoftheArtinProgramAnalysis. JoannaC.S.Santos,ReeseA.Jones,andMehdiMirakhorli.2020.Salsa:StaticAnalysisofSerializationFeatures.InProceedings ofthe22thACMSIGPLANInternationalWorkshoponFormalTechniquesforJava-LikePrograms(FTfJP’20)(Virtual) (FTfJP2020).ACM,NewYork,NY,USA,18–25. https://doi.org/10.1145/3427761.3428343 ImenSayar,AlexandreBartel,EricBodden,andYvesLeTraon.2023. Anin-depthstudyofjavadeserializationremote-code executionexploitsandvulnerabilities. ACMTransactionsonSoftwareEngineeringandMethodology32,1(2023),1–45. ChristianSchneiderandAlvaroMuñoz.2016. JavaDeserializationAttacks. https://owasp.org/www-pdf-archive/GOD16- Deserialization.pdf. (Accessedon11/15/2019). EdwardJSchwartz,ThanassisAvgerinos,andDavidBrumley.2010. Allyoueverwantedtoknowaboutdynamictaint analysisandforwardsymbolicexecution(butmighthavebeenafraidtoask).In2010IEEEsymposiumonSecurityand privacy.IEEE,317–331. HossainShahriarandHishamHaddad.2016. Objectinjectionvulnerabilitydiscoverybasedonlatentsemanticindexing.In Proceedingsofthe31stAnnualACMSymposiumonAppliedComputing.801–807. M.SharpandA.Rountev.2006. StaticAnalysisofObjectReferencesinRMI-BasedJavaSoftware. IEEETransactionson SoftwareEngineering32,9(2006),664–681. https://doi.org/10.1109/TSE.2006.93 MikhailShcherbakovandMusardBalliu.2021. Serialdetector:Principledandpracticalexplorationofobjectinjection vulnerabilitiesfortheweb.InNetworkandDistributedSystemsSecurity(NDSS)Symposium202121-24February2021. YannisSmaragdakis,GeorgeBalatsouras,GeorgeKastrinis,andMartinBravenboer.2015. MoreSoundStaticHandlingof JavaRe￿ection.InProgrammingLanguagesandSystems,XinyuFengandSungwooPark(Eds.).SpringerInternational Publishing,Cham,485–503. https://doi.org/10.1007/978-3-319-26529-2_26 YannisSmaragdakisandGeorgeKastrinis.2018. DefensivePoints-ToAnalysis:E￿ectiveSoundnessviaLaziness.In32nd EuropeanConferenceonObject-OrientedProgramming(ECOOP2018).SchlossDagstuhl-Leibniz-ZentrumfuerInformatik. https://doi.org/10.4230/LIPIcs.ECOOP.2018.23 ManuSridharan,ShayArtzi,MarcoPistoia,SalvatoreGuarnieri,OmerTripp,andRyanBerg.2011. F4F:TaintAnalysis ofFramework-BasedWebApplications.InProceedingsofthe2011ACMInternationalConferenceonObjectOriented ProgrammingSystemsLanguagesandApplications(Portland,Oregon,USA)(OOPSLA’11).ACM,NewYork,NY,USA, 1053–1068. https://doi.org/10.1145/2048066.2048145 ManuSridharan,SatishChandra,JulianDolby,StephenJ.Fink,andEranYahav.2013. AliasAnalysisforObject-Oriented Programs. SpringerBerlinHeidelberg,Berlin,Heidelberg,196–232. https://doi.org/10.1007/978-3-642-36946-9_8 LiSui,JensDietrich,MichaelEmery,ShawnRasheed,andAmjedTahir.2018. Onthesoundnessofcallgraphconstruction inthepresenceofdynamiclanguagefeatures-abenchmarkandtoolevaluation.InAsianSymposiumonProgramming LanguagesandSystems.Springer,69–88. LiSui,JensDietrich,AmjedTahir,andGeorgeFourtounis.2020.OntheRecallofStaticCallGraphConstructioninPractice. https://doi.org/10.1145/3377811.3380441 H.Thaller,L.Linsbauer,A.Egyed,andS.Fischer.2020. TowardsFaultLocalizationviaProbabilisticSoftwareModeling. In2020IEEEWorkshoponValidation,AnalysisandEvolutionofSoftwareTests(VST).24–27. https://doi.org/10.1109/ VST50071.2020.9051635 JulianThomé,LwinKhinShar,DomenicoBianculli,andLionelCBriand.2017. Joanaudit:Atoolforauditingcommon injectionvulnerabilities.InProceedingsofthe201711thJointMeetingonFoundationsofSoftwareEngineering.1004–1008. FrankTipandJensPalsberg.2000.Scalablepropagation-basedcallgraphconstructionalgorithms.InProceedingsofthe15th
ACMSIGPLANconferenceonObject-orientedprogramming,systems,languages,andapplications.281–293. RajaVallée-Rai,PhongCo,EtienneGagnon,LaurieHendren,PatrickLam,andVijaySundaresan.1999.Soot-aJavaBytecode OptimizationFramework.InProceedingsofthe1999ConferenceoftheCentreforAdvancedStudiesonCollaborativeResearch (Mississauga,Ontario,Canada)(CASCON’99).IBMPress,13. JanVitek,RNigelHorspool,andJamesSUhl.1992. Compile-timeanalysisofobject-orientedprograms.InCompiler Construction:4thInternationalConference,CC’92Paderborn,FRG,October5–7,1992Proceedings4.Springer,236–250. Proc.ACMProgram.Lang.,Vol.8,No.OOPSLA1,Article134.Publicationdate:April2024.S￿￿￿￿￿:Taint-BasedCallGraphConstructionforJavaObjectDeserialization 134:29 WALA.2024. wala/WALA:T.J.WatsonLibrariesforAnalysis,withfrontendsforJava,Android,andJavaScript,andmany commonstaticprogramanalyses. https://github.com/wala/WALA [Online;accessed8.Mar.2024]. MarvinWyrichandJustusBogner.2019.TowardsanAutonomousBotforAutomaticSourceCodeRefactoring.InProceedings ofthe1stInternationalWorkshoponBotsinSoftwareEngineering(Montreal,Quebec,Canada)(BotSE’19).IEEEPress, 24–28. https://doi.org/10.1109/BotSE.2019.00015 Received21-OCT-2023;accepted2024-02-24 Proc.ACMProgram.Lang.,Vol.8,No.OOPSLA1,Article134.Publicationdate:April2024.
2311.04109 Do Language Models Learn Semantics of Code? A Case Study in Vulnerability Detection BenjaminSteenhoek MdMahbuburRahman IowaStateUniversity IowaStateUniversity Ames,Iowa,USA Ames,Iowa,USA benjis@iastate.edu mdrahman@iastate.edu ShailaSharmin WeiLe IowaStateUniversity IowaStateUniversity Ames,Iowa,USA Ames,Iowa,USA ssharmin@iastate.edu weile@iastate.edu ABSTRACT andtypesofbugsandmaintainingstableperformance[33].These Recently,pretrainedlanguagemodelshaveshownstate-of-the-art issuesmakeithardforthesemodelstofindvulnerabilitiesinreal- performanceonthevulnerabilitydetectiontask.Thesemodelsare worldprojects.Inthispaper,weseektoanalyzethemodelsinorder pretrainedonalargecorpusofsourcecode,thenfine-tunedona tounderstandthereasonsforthemodels’limitationssothatwe smallersupervisedvulnerabilitydataset.Duetothedifferenttrain- canfindwaystoimprovethem. ingobjectivesandtheperformanceofthemodels,itisinteresting Atpresent,pre-trainedlanguagemodelsareexclusivelytrained toconsiderwhetherthemodelshavelearnedthesemanticsofcode ontextualdataandlackexplicitintegrationofprogramsemantics. relevanttovulnerabilitydetection,namelybugsemantics,andifso, Severalstudieshaveshownthatdeeplearning-basedvulnerability howthealignmenttobugsemanticsrelatestomodelperformance. detectionmodelstendtofocusonspuriousfeatures,e.g.,variable Inthispaper,weanalyzethemodelsusingthreedistinctmethods: names,whicharenotrelatedtobugsatall[6,33].Withoutleverag- interpretability tools, attention analysis, and interaction matrix ingbugsemantics,wearguethatthemodelwillbeunabletoreliably analysis.Wecomparethemodels’influentialfeaturesetswiththe andpreciselydetectbugs.Forexample,considerasnippetcode bugsemanticfeatureswhichdefinethecausesofbugs,including thatconsistsofabufferallocationchar buf[10];,abenignprint buggypathsandPotentiallyVulnerableStatements(PVS).Wefind statementprintf("%d\n",sizeof(buf)),andanout-of-bounds that(1)better-performingmodelsalsoalignedbetterwithPVS,(2) accessbuf[11];.ModelAmaylearntousespuriousfeatures,e.g. themodelsfailedtoalignstronglytoPVS,and(3)themodelsfailed theprintftoken,orevenfutureunrelatedprintf,topredicta toalignatalltobuggypaths.Basedonouranalysis,wedeveloped vulnerability.ModelB,whichusespartialbugsemantics,mayrec- twoannotationmethodswhichhighlightthebugsemanticsinside ognizethebufferallocationandaccessasapotentialvulnerability themodel’sinputs.Weevaluatedourapproachonfourdistinct andflagthem,butmayhaveafalsepositiveifitcannotfurther transformermodelsandfourvulnerabilitydatasetsandfoundthat reasonwhethertheindexisin-bounds.ModelC,whichusesfull ourannotationsimprovedthemodels’performanceinthemajority bugsemantics,willfollowthebuggypathstotrackthesizeofthe ofsettings–11outof16,withupto9.57pointsimprovementin bufferandcheckeveryaccesstopreciselydetectoverflows.We F1scorecomparedtoconventionalfine-tuning.Wefurtherfound believethatmodelCcanbestdetectthevulnerability.Especially thatwithourannotations,themodelsalignedupto232%betterto insituationswherewecannotobtainalargedataset,suchasvul- potentiallyvulnerablestatements.Ourfindingsindicatethatitis nerabilitydetection,themodel’spredictivequalityhingesonits helpfultoprovidethemodelwithinformationofthebugsemantics, knowledgeofbugsemantics.Therefore,itiscrucialtounderstand thatthemodelcanattendtoit,andmotivatefutureworkinlearning whetherandhowstate-of-the-artdeeplearningmodelslearnbug morecomplexpath-basedbugsemantics.Ourcodeanddataare semantics. availableatthisURL:https://figshare.com/s/4a16a528d6874aad51a0. Recently,Wanetal.analyzedtheself-attentionmechanismin transformersandshowedthatpre-trainedmodelsofcodecancap- KEYWORDS tureandreconstructbasicsyntacticstructures[36].Thisbuildson workinotherdomains,whichstudytherelationshipofattention deeplearning,vulnerabilitydetection withthestructuresofproteins[35]andnaturallanguage[19].In anothervein,Paltenghietal.[27]foundthattheCodeGentrans- 1 INTRODUCTION formermodelpaidattentiontosimilarpartsofcodeasdiddevelop- ers.Theseandrelatedresearch[28]showthatthemodels,beyond Vulnerabilitiescausegreatharmtopeopleandcorporationseach processingsequencesoftokens,learnsomehigh-levelproperties year[2,39].Thenumberofreportedvulnerabilitiescontinuesto ofthesourcecode.However,itisnotknownwhetherpre-trained grow[1],whichnecessitateseffectivemethodsofdetectingvul- modelsofcodecanfurthercaptureprogramsemantics,especially nerabilities.Recently,pre-trainedlanguagemodelshaveachieved whenfine-tunedforataskwhichrequiresthemodeltolearnbug thestate-of-the-artvulnerabilitydetectionperformanceof91F1 semantics,suchasvulnerabilitydetection.Bugsemanticsinvolve score[16]onareal-worldvulnerabilitydataset[14].However,deep learningmodelsfacedifficultiesingeneralizingtonewprojects 3202 voN 7 ]GL.sc[ 1v90140.1132:viXraBenjaminSteenhoek,MdMahbuburRahman,ShailaSharmin,andWeiLe
morecomplexconstraintsandarelessrelatedtothetextrepresen- performsowell,dotheyreallylearnbugsemantics,andcanthey tationcomparedtotheAST[40],sothemodelislesslikelytolearn beimproved? thembydefault. Inthispaper,wedefineasetoffeaturesrelatedtobugseman- 2.2 Transformersandself-attention ticsandanalyzehowdeeplearning-basedlanguagemodelsuse The transformer model architecture, introduced by Vaswani et thesefeatures,inordertoanswerthefollowingquestions:Towhat al. [34], has recently revolutionized the field of text processing, extentdothemodelsusebugrootcausestomakepredictions?Do includingsourcecodeunderstanding.Thekeyinnovationofthe modelsperformbetterwhenusingmorecausallines? Tothisend, transformermodelisthatitreliessolelyontheself-attentionmech- westudiedfourpre-trainedlanguagemodelsusinginterpretation anismwithoutusingrecurrentneuralnetworks(RNNs)orconvo- tools,attentionanalysis[36],andinteractionmatrixanalysis[27]. lutions.Thisarchitectureallowsgreatercomputationalefficiency, Wecomparedwithtwotypesofbugsemanticsusedinthepro- allowingittoscaletolargeparametersizesandtrainingcorpora. gramanalysisliterature:buggypaths(inthispaper,weusedpaths reportedbytheInferstaticanalyzer[41];inthefuture,wewillcon- Self-attentionrelatesdifferentelementsofasequence𝑐 = [𝑤 1,...,𝑤 𝑛] ofsize𝑛inordertocomputearepresentationofthesequence.The siderotherapproachesofobtainingbuggypaths)andPotentially transformermodelismadeupofanembeddinglayerand𝐿sequen- Vulnerable Statements (PVS), based on the framework proposed tialself-attentionlayers.Theembeddingconvertsthesequence byLeetal.[21].WefoundthatthemodelsalignedtothePVSin somecases,butmostmodelshadlessthan50%alignmentwith oftokensintovectorrepresentations𝑥0 = [ℎ0 1,...,ℎ 𝑛0].Eachat- tentionlayer𝑙 takesthepreviouslayer’soutputandgeneratesa potentiallyvulnerablestatements.However,themodelsdidnot substantiallyaligntobuggypaths,havingmedianalignmentscores vectorrepresentation𝐻𝑙 = [ℎ𝑙 1,...,ℎ𝑙 𝑛].Eachattentionlayerhas multipleself-attentionheadswhicheachcomputeaseparateoutput evenbelow7%.Basedonthisanalysis,wedevelopedtwomethods representation.Multipleheadsallowthemodeltofocusondiffer- toannotatethePVSinsidethemodelinput.Ourbestannotation enttokens,resultinginimprovedperformance;infact,sometimes methodimprovedthemodelF1scoreinthemajorityofcases,byup individualheadswilltendtoalignwithasemanticfunction,as to9.57points,andimprovedmodelalignmenttoPVSby36-232%. shownbyWanetal.[36].Intuitively,ahigherscoreforanindex Inthispaper,wemakethefollowingcontributions: 𝑗 meansthatmoreofthepreviouslayer’srepresentationoftoken (1) Weadaptandharmonizethreedistinctapproachestoana- 𝑗 will be preserved. To compute the attention in parallel, most lyzedeeplearningmodelsusinginterpretationtools,atten- implementationsusethevectorizedformulainEquation2.2. tionanalysis,andinteractionmatrixanalysis. (2) Usingtheseanalysisapproaches,weinvestigatewhether deeplearningmodelsencodetwotypesofbugsemantics: 𝑄𝐾𝑇 PotentiallyVulnerableStatements(PVS)andbuggypaths. 𝐴𝑡𝑡𝑒𝑛𝑡𝑖𝑜𝑛(𝑄,𝐾,𝑉)=𝑠𝑜𝑓𝑡𝑚𝑎𝑥( √ )·𝑉 (1) 𝑑 (3) Weshowthatbetter-performingmodelsalignedbetterto bugsemantics,andwhilethemodelssomewhataligned where𝑑 isahyperparameterspecifyingthedimensionofthe withPVS,theyfailedtoalignstrongly,andfailedtoalign model’shiddenrepresentationandQ,K,andVarelinearmappings substantiallytobuggypaths. oftheprevioushiddenrepresentation.Theoutputofthesoftmaxis (4) Therefore,wedevelopanovelmethodofannotatingbug theattentionscorewhichscalesthevalueof𝑉;ahighscorefora semanticsandshowthatwiththisannotation,modelscan token𝑗 willmostlypreservethepreviouslayer’srepresentationof performsignificantlybetterandindeedalignedmorewith 𝑗,andalowscorewillmaketherepresentationclosetozero.The PVS. outputoftheattentionheadissummed,thenconcatenatedwith theotherattentionheadsandprojected,andsenttoafeed-forward 2 BACKGROUND neuralnetworktoproducetheoutputofthelayer. 2.1 Vulnerabilitydetection Toproducetheinputsequence𝑐,textinputsequencesarecom- monlysplitintoinputtokensusingaBytePairEncoding(BPE)[29]. Avulnerabilityisadefectinaprogramwhichcanbeexploited Thistokenizationtechniqueisusedtoaddresstheout-of-vocabulary forharmtotheprogram’suserorsystem.Thesecanbecausedby problembysplittingwordsintocommonfragments–“subwords”– erroneousoperationssuchasmemoryallocations,pointermanipu- allowingthemodeltogeneralizetounseenvocabulary. lation,lackofinputvalidation.Westudiedvulnerabilitydetection inthesettingofclassifyingfunction-levelsourcecodeexamples 2.3 Pre-trainedsourcecodemodels intovulnerableornon-vulnerable. Critically,vulnerabilitiescanbeanalyzedanddetectedaccording Transformer models are especially effective when they are pre- toconditionsunderwhichavulnerabilitymanifests[40],which trainedonlargecorporaoftextandsourcecode,thenfine-tuned we term as bug semantics. Static vulnerability analyzers utilize forspecifictasks.ThemostcommonBERT-basedmodelsareusu- bugsemantics,suchasbuggypathswithpre-andpost-conditions, allytrainedwiththeMaskedLanguageModeling(MLM)objective, toidentifylikelysecurityvulnerabilitiesinsoftwaresourcecode. wherethemodeltakesasinputasequenceoftokens𝑐,afraction Recenttransformermodelscanoutperformpriorapproaches,but ofthetokensarehidden,andthemodelistaskedwithfillingthem
thesemodelsrelyontextualrepresentationswhichdonotdirectly in.Pre-trainingcanintegrateotherinputsandobjectives,suchas representbugsemantics,leadingustoask:howdothesemodels includingASTsintheinputortaskingthemodelwithidentifierDoLanguageModelsLearnSemanticsofCode?ACaseStudyinVulnerabilityDetection reconstruction[17,37].Surprisingly,themodelscanstilllearnhigh- Table1:Datasetinformation levelpatternsfromthecodeduringpre-traininginordertofulfill theMLMobjective. Dataset #data %vulnerable Buggypaths PVS Recently,Wanetal.[36]haveshownthatpre-trainedsourcecode D2A[41] 5,239 53.35% ✓ ✓ modelscanencodethesyntacticstructureofthecode.Weapplyand extendtheattentionanalysistechniquetheyintroducedinorder Devign[42] 27,318 45.61% ✗ ✓ tocompareinsteadwithbugsemantics.Ratherthanstudyingthe Big-Vul[14] 188,636 5.78% ✗ ✓ pre-trainedmodels,westudiedthemodelsafterfine-tuningthem ReVeal[6] 22,734 9.85% ✗ ✓ forvulnerabilitydetection,inordertounderstandiftheylearned thebugsemantics. theC/C++programs,asidefromexceptionalcaseslikepreprocessor Tofine-tunethemodelforvulnerabilitydetection,weloadthe macros. pre-trainedweightsandreplacetheMLMpredictionlayerwitha feed-forwardclassificationlayer.Thenwefine-tunethemodelon Table2:Reproducedmodelperformance asmallerbinaryclassificationdatasetforvulnerabilitydetection, followingtheprocedureintroducedbyFuetal.[16]. F1score 3 STUDYSETUP Model D2A Devign Big-Vul ReVeal 3.1 Models CodeBERT 66.76 56.90 40.65 42.69 WestudiedthefollowingSOTApre-trainedlanguagemodels:Code- UniXcoder 57.19 56.81 39.55 40.53 BERT[15]isamodelpretrainedonpairsofsourcecodeandnatural CodeT5 57.33 58.79 40.20 40.56 language.Itisanearlyandcommonbaselinemodel[23]uponwhich LineVul 68.22 54.15 39.46 42.92 otherworkshavebuiltmoreadvancedapproaches.LineVul[16] isbasedontheCodeBERTbackboneand,furthermore,produces line-levelexplanationsbasedonself-attention.UniXCoder[17] 3.3 Computingbugsemantics incorporatesASTandcodecommentsintoitsmodelinputandadds pretrainingtaskssuchascontrastivelearningandPL→NLcom- Inordertoidentifythestatementswhicharerelevanttothebug,we mentgeneration.CodeT5[37]annotatesidentifiersinitsmodel definebugsemanticfeatures,orbugfeatures,aselementsfromthe input and adds identifier-aware and dual NL→PL and PL→NL sourcecodewhichcauseabug;oncetheseelementsareeliminated, generationpretrainingtasks. thebugceasestoexist.Wehypothesizethatreliableandrobust bugdetectionmodelsshouldconcentrateonbugsemanticfeatures 3.2 Datasets tomaketheirpredictions.Forexample,whendetectingabuffer overflow,amodelshouldtrackbuffersizeandstringlength,and Wefine-tunedthemodelsonthefollowingdatasetsofbugsinC detectingmemoryleak,weshoulddetermineifafreeisperformed andC++sourcecode,whichwealsouselaterinourstudies.We afteramemoryallocation.Ifthemodelsoverlooktherootcauseof chosethesedatasetsbecausetheyarewidelyusedandrepresent thebug,thepredictioncannotbereliableandrobust[40]. diversedatasetcollectionmethods.Table1liststhedetailsofeach InSection4,wewillanalyzethemodels’importantfeaturesand dataset.D2A[41]usedtheInferstaticanalyzeranddifferential attention,comparingthemwiththebugsemanticfeatures.This analysistocollectbuggyandthecorrespondingfixedfunctions. willhelpusunderstandwhetherthemodelslearntoconcentrateon Weusedthefunction-levelleaderboarddataset1,whichisbalanced. bugsemanticstomakepredictions(§4)andhowwecanleverage Devign[42]usedcommitfilteringandfurthermanualanalysis bugsemanticstoimprovethemodels(§5). togatherabalanceddatasetofbuggyandnon-buggyfunctions. Weextractbugfeaturesusingalightweightstaticanalysisona WeusedthepartitionsreleasedbytheCodeXGLUEdataset[23]. program’sAbstractSyntaxTree(AST).Givenadatasetoffunctions Big-Vul[14]crawledtheCommonVulnerabilitiesandExposures 𝐷,weparseeachfunctionintoanAST𝑇 =⟨𝑉,𝐸⟩.Terminalnodes (CVE)databasetocollectanimbalanceddatasetofbuggyandnon- arethenodesin𝑉 whichhavenochildren.Wethenextracttwo buggyfunctions.WeusedthepartitionsreleasedbyFuetal.[16]. typesofbugfeaturesasfollows: ReVeal[6]crawledpublicbugrepositoriesforChromeandDebian toproduceanimbalanceddatasetofbuggy/fixedfunctionsand Buggypaths. Abuggypathconsistsofasequenceofstatements unrelatedfunctionsinthesamecommit,whichareassumednon- insourcecodethatleadtoabuggycondition.TheD2Adataset vulnerable. directlyusedthebuggypathreportedbytheInferstaticanalyzer Wereporttheperformancesofthereproducedmodelsfine-tuned as the ground-truth to distinguish buggy and non-buggy func- oneachdatasetinTable2.Forfaircomparison,wecomparedall tions [41]. Therefore, in our static analysis tool, we compute a modelarchitecturesusingacontextlengthof512inallofourexper- buggypathasanorderedsetofterminalASTnodesin𝑉 whichare iments.Inordertogivethesameinputstoallthemodels,wealso insidethelinesidentifiedinthebuggypathreportedbyInfer.Note normalizedthewhitespaceinsidetheprogramsbyjoiningallAST thatitisundecidabletoautomaticallyextractground-truthbuggy tokenswithasinglespace;thisdoesnotchangethesemanticsof pathsthattracktherootcauseabug.Here,weusethebuggypaths
reportedbyInferasanapproximation.Sincethestaticanalysis 1https://developer.ibm.com/exchanges/data/all/d2a/ toolsarerobustandaccurateenoughtobeusedwidelyinindustry,BenjaminSteenhoek,MdMahbuburRahman,ShailaSharmin,andWeiLe weexpectthataccuratevulnerabilitydetectionmodelsshouldmake canlogmultiplebuggypathspermethod,thoughtheexamplesin decisionsbasedonmanyofthesamefeatures.Infact,thebuggy theevaluationdatasetarenotduplicated;onaverage,eachprogram pathswereusedtogeneratethelabelsfortheD2Adataset,sowhen has5.29overlappingbuggypaths.Wecountallbuggypathsas trainingonD2A,themodelshaveahighincentivetodirectlyfocus separatebugswhencalculatingthealignmentmetrics. onthebuggypaths. Table4:StatisticsofPVSinthedatasets. PotentiallyVulnerableStatements(PVS). Tofurtherstudychar- acteristicsofbugs,weidentifiedPotentiallyVulnerableStatements (PVS)–statementswhereavulnerabilityconditioncanmanifest, Mean#PVSperprogram followingtheframeworkproposedbyLeetal.[21].Toselectthe Label D2A Devign Big-Vul ReVeal PVS,wesurveyedcommonbuggyfunctioncallsandoperationsin C[4,10,25]andcategorizedthembasedonthetypesofbugswhich Vulnerable 111.1 103.6 146.2 85.5 theymightcause.Table3liststhefunctioncallsandoperations Non-vulnerable 111.4 85.8 50.3 27.4 whichweconsideredtoindicateaPVS.Inourstaticanalysistool, Vul:Non-vulratio 1.00 1.21 2.90 3.12 wecomputePVSasanunorderedsetofterminalASTnodesin 𝑉 whicharedescendantsoftheselectedPVSstatement.Thisisa heuristicwhichisinsufficienttodetectbugsbyitself;itcaninclude 4 ALIGNMENTOFMODELFEATURESWITH statementswhichdonotreallycauseabug,orexcludestatements BUGSEMANTICS whichdocausebugs.PVSwouldusuallybefollowedupbyamore precisestaticanalyzer,butindicatestheverysimplestlevelofbug In this section, we analyze the alignment between the models’ semanticswhichweintendthemodeltoalignto;weintendforthe importantfeatures/attentionandbugsemanticfeatures.Ourgoal modeltobeabletousePVSasastartingpointforamoreprecise istounderstandwhetherthemodelslearnedtomakepredictions analysis. basedonbugsemanticfeatures,ratherthanunrelatedspurious features.Tothisend,wecorroboratedthreedistinctapproaches. Table3:ListofPotentiallyVulnerableStatements(PVS) (1) Interpretationanalysis:Weappliedstate-of-the-artinter- pretabilitytoolstoattributetheimportanceofeachfeature, thenmeasuredtheagreementbetweenfeatureswithhigh Statement VulnerabilityType attributionscoresandbugsemanticfeatures. Calltomalloc,calloc, (2) Attentionanalysis:Wemeasuredtheagreementbetween realloc,aligned_alloc, themodel’sself-attentionscoresandbugsemanticfeatures, Memoryleak kalloc,kcalloc,krealloc, adaptingthemethodestablishedbyWanetal.[36]andVig valloc,vcalloc,vrealloc etal.[35]. Calltofree,kfree, (3) Interactionmatrixanalysis:Wecomparedthefeatures Doublefree,memoryleak, free_sized, whichthemodel’sattentionmechanismwaslikelytofocus useafterfree free_aligned_sized oninsequencewiththebugsemanticfeatures,usingthe interactionmatrixproposedbyPaltenghietal.[27]. Calltogets,puts,scanf, ForasingleprogramAST𝑇 =⟨𝑉,𝐸⟩,wedenotethebugsemantic sprintf,strcpy,strncpy, Bufferoverflow featuresasaset𝐵 ⊆𝑉 anddenotethefeaturesidentifiedasimpor- strlen,strcat,strncat tantbyananalysisasaset𝑀 ⊆𝑉.Weusedthissharedinterfaceto Arrayindex(buf[]) corroboratetheresultsfromeachapproach.Eachalignmentmetric Pointerdereference(*ptr) producesascalarscorewhichquantifiestheagreementbetween𝑀 Pointermemberaccess NULLpointerdereference and𝐵.Forallanalyses,weusedtheIntersection-over-Union(IoU) (ptr->field) indextomeasurethesimilaritybetween𝑀and𝐵;thiscontrolsfor +,+=, ++, -, Integeroverflow/underflow thesizeof𝐵,whichvariesbetweendifferentprogramsanddatasets. -=, –, *, *= Wefine-tunedeachmodeloneachdatasetandchosethebest /, /=, %, %= Divide-by-zero checkpointbasedonvalidationperformancetocomputethealign- mentmetrics;Table2reportsthemodelperformancecomparison. Table4liststhefrequenciesofPVSinthedatasets.ThePVS Whencomputingthemetrics,weconsideredonlytheprograms are more frequent in vulnerable examples than non-vulnerable where𝐵≠∅,i.e.whichcontainedatleastonePVSorabuggypath. examplesinalldatasetsexceptD2A,thoughthenon-vulnerable 4.1 Interpretationanalysis exampleshavePVSinthem;thisshowsthatPVSisnecessarybut notsufficientconditionsforvulnerability.Forexample,whena Motivation. Many bugs can only be detected reliably if certain programcontainsagoodbounds-check,thebufferaccess(PVS)is individualstatementsareconsidered.Forexample,abufferoverflow safe.WespeculatethattheD2AdatasethasmanyPVSinitsnon- detectorwhichignoresthestatementscontainingbufferaccesses vulnerable examples because it is collected from differentiating cannotpreciselydeterminewhetherabufferoverflowmayoccur. bugsreportedbytheInferstaticanalyzerwiththecorresponding Althoughitmaymakesomecorrectpredictionsbasedonheuristics fixedversion.Duetoitsdifferentialdatacollection,theD2Adataset or spurious signals, its predictions will always have additionalDoLanguageModelsLearnSemanticsofCode?ACaseStudyinVulnerabilityDetection 100% 80% 60% 40% 20% 0% UniXcoder CodeT5 CodeBERT LineVul Model terpretnitnemngilA D2A-bp
100 80 60 40 20 0 1F Alignment Interpretation analysis F1 100% 80% 60% 40% 20% 0% UniXcoder CodeT5 CodeBERT LineVul model noitnettatnemngilA D2A-bp 100 80 60 40 20 0 1F Alignment Attention analysis F1 100% 80% 60% 40% 20% 0% UniXcoder CodeT5 CodeBERT LineVul model MItnemngilA D2A-bp 100 80 60 40 20 0 1F Alignment Interaction matrix analysis F1 Figure1:ModelsdidnotaligntoD2Abuggypaths. uncertaintyarisingsolelyfromoversightofthefaultlocation.Using 4.2 Attentionanalysis interpretationtools,weseektodetectwhethertheexistingmodels Motivation. Weanalyzethetransformerarchitecture’sself-attention considerindividualbugfeaturesintheirpredictions. mechanismtoprovideanexplanationofthemodel’sprediction usingmethodsdifferentfrominterpretationtools.Incontrastto Approach. Manymethodshaverecentlybeenproposedtogenerate gradient-basedinterpretationmethodswhichareappliedpost-hoc, interpretationsofmodelpredictionsintheformoffeatureattribu- attentionistheprimarymechanismoftransformermodels,soitcan tionscores.Thesetoolsgenerateascalarscoreforeachfeature(in beusedasadirectexplanationofthemodel’sprediction.Inaddi- ourcase,inputtokens)whichindicatesthefeature’simportance tion,theattentionscoresignifiestheconnectionsbetweenmultiple forthemodel’sprediction.Becausedifferentinterpretationtools locations.Infuturework,weplantoanalyzethemodels’attention canyielddiverseinsightsandcanbedifficulttocompare[13],we scorestounderstandwhetherthemodelscanconnectbetween appliedfourstate-of-the-artinterpretationtools:Saliency,InputX- multiple-locationbugsemantics. Gradient,DeepLift,andSHAP[24,30–32]whichwereavailable intheversatileCaptumlibrary[20].WepresentourIoUformula Approach. Intuitively,ahighattentionscorefromtoken𝑖totoken inEquation2,where𝑀 𝑡𝑜𝑝𝐼𝑛𝑡𝑒𝑟𝑝𝑟𝑒𝑡(𝑘) representsthesetoftokens 𝑗 causesthemodeltofocusmoreonthepreviouslayer’sencoding withthetop-𝑘highestattributionscoresintheprogram,and𝑘 =|𝐵|. of token 𝑗 as it encodes token𝑖 [3]. Thus, if a layer has a high Finally,weaveragedtheresultsof𝐴𝑙𝑖𝑔𝑛𝑚𝑒𝑛𝑡 𝐼𝑛𝑡𝑒𝑟𝑝𝑟𝑒𝑡 foreachtool attentionscorebetweentwotokens,thenweconcludethatthe toproduceasinglescoreforeachprogram. modelhaslearnedthatthesetwotokensareimportantinrelation to each other. If one of the tokens is inside 𝐵, this is evidence 𝐴𝑙𝑖𝑔𝑛𝑚𝑒𝑛𝑡 𝐼𝑛𝑡𝑒𝑟𝑝𝑟𝑒𝑡 = | |𝑀 𝑀𝑡 𝑡𝑜 𝑜𝑝 𝑝𝐼 𝐼𝑛 𝑛𝑡 𝑡𝑒 𝑒𝑟 𝑟𝑝 𝑝𝑟 𝑟𝑒 𝑒𝑡𝑡( (𝑘 𝑘) ) ∩ ∪𝐵 𝐵| | (2) t mh ea at st uh re em tho isd ee vl ih da es ncle e,a wrn eed adp aa pr tt edof thth ee ms ee tm hoa dnt ei sc ts abo lf ist hh ei dsb bu yg W.T ano Becausetheinterpretabilitytoolsoperateattheinputtoken-level, wecannotdirectlycomparethemwiththebugfeatures,whichare highlightedatASTtoken-level.Inordertocompare𝑀and𝐵atthe samegranularity,weaveragedtheattributionscoreswithineach ASTtokentoproduceasinglescoreforeachtoken. 100% Results. Figure2reportsthe𝐴𝑙𝑖𝑔𝑛𝑚𝑒𝑛𝑡 𝐼𝑛𝑡𝑒𝑟𝑝𝑟𝑒𝑡scoresofindividual 80% examplesineachdataset,comparedwithPVSbugfeatures.The 60% X-axisissortedbymodelF1scoreonthetestdataset. 40% Withineachmodel,inmostcases,ahigherperformanceona 20% datasetcorrespondstoahighermedian𝐴𝑙𝑖𝑔𝑛𝑚𝑒𝑛𝑡 𝐼𝑛𝑡𝑒𝑟𝑝𝑟𝑒𝑡 score. 0% Big-Vul ReVeal Devign D2A Thissuggeststhathigher-performingmodelslearnedtofocussome- dataset whatonindividualbugfeatures.However,wenotethatallmodels’ medianalignmentsliewithin10-20%,andthatsomedatasets(e.g. Big-Vul)hadmanyexampleswith0%alignment.Thisindicatesthat themodelsoftenfailedtofocusonbugsemanticfeaturesandrather focusedonspuriousfeatures;weattempttorepairthismisalign- mentbyannotatingthebugfeaturesinSection5. Figure1(left)showsthealignmentofthemodeltothebuggy pathsintheD2Adataset.Allmodelshadamedianalignmentscore of5%orbelow,andtherewasnocleardifferencebetweendifferent models’alignment;therefore,weconcludethatthemodelsweren’t abletoaligntobuggypaths. terpretnitnemngilA CodeBERT Big-Vul ReVeal D2A Devign dataset terpretnitnemngilA CodeT5 100% 80% 60% 40% 20% 0% Big-Vul ReVeal Devign D2A dataset terpretnitnemngilA LineVul Big-Vul ReVeal Devign D2A dataset terpretnitnemngilA 100 80 60 40 20 0 UniXcoder 1F 100 80 60 40 20 0 1F 100 80 60 40 20 0 1F 100 80 60 40 20 0 1F Alignment Interpretation analysis F1 Figure 2: Alignment of model interpretations to PVS bug semantics;datasetsareorderedbymodelF1score.BenjaminSteenhoek,MdMahbuburRahman,ShailaSharmin,andWeiLe 100% 80% 60% 40% 20% 0% Big-Vul ReVeal Devign D2A dataset noitnettatnemngilA CodeBERT Big-Vul ReVeal D2A Devign dataset noitnettatnemngilA CodeT5 100% 80% 60% 40% 20% 0% Big-Vul ReVeal Devign D2A dataset noitnettatnemngilA LineVul Big-Vul ReVeal Devign D2A dataset noitnettatnemngilA 100 80 60 40 20 0 UniXcoder 1F 100 80 60 40 20 0 1F 100 80 60 40 20 0 1F 100 80 60 40 20 0 1F Alignment Attention analysis F1 100% 80% 60% 40% 20% 0% Big-Vul ReVeal Devign D2A dataset Figure3:AlignmentofmodelattentiontoPVSbugsemantics, aggregatedbydatasetexample. etal.[36]andVigetal.[35].Thepreviousapproach,namelyWan etal.,directlycomparedthehigh-attentionedgeswithedgesin anAST.Bugsemanticsaredefinedassetsofnodes,soweextend theapproachtoconsideranynodeincidenttoanyhigh-attention edge;thisrequiresthemodelattentiontoaligncloselytothebug features. WecomputedtheIoUformulainEquation3foreachprogram, separatelyforeachself-attentionlayer/head,where𝑀 𝑡𝑜𝑝𝐴𝑡𝑡𝑒𝑛𝑡𝑖𝑜𝑛(𝑘)
representsthesetof𝑘 tokensincidenttothetopmostattention scores,and𝑘 =|𝐵|. |𝑀 𝑡𝑜𝑝𝐴𝑡𝑡𝑒𝑛𝑡𝑖𝑜𝑛(𝑘) ∩𝐵| 𝐴𝑙𝑖𝑔𝑛𝑚𝑒𝑛𝑡 𝐴𝑡𝑡𝑒𝑛𝑡𝑖𝑜𝑛 = |𝑀 𝑡𝑜𝑝𝐴𝑡𝑡𝑒𝑛𝑡𝑖𝑜𝑛(𝑘) ∪𝐵| (3) Inordertocompare𝑀and𝐵atthesamegranularity,weaveraged theattentionscoresincidenttothetokenswithineachASTtoken. Wanetal.appliedathresholdtoexcludeanyattentionheadswith fewerthan100high-attentionedges;becausewecomputetheIoU, wedisablethisthreshold. Results. Figure3reportsthemean𝐴𝑙𝑖𝑔𝑛𝑚𝑒𝑛𝑡 𝑎𝑡𝑡𝑒𝑛𝑡𝑖𝑜𝑛scoresaggre- gatedoverthedataset.Theresultsofattentionanalysiscorroborate theresultsofinterpretationanalysis.Weseethatmodelstendto alignbetteronbetter-performingdatasets.Themedianalignment scoresforallmodelsanddatasetswerebetween10-20%.Thisshows thatbeyondhighlightingtheimportantfeaturesindividually,the modelsalsohighlightedrelationshipsbetweentheimportantfea- turesusingtheattentionmechanism. Figure4showstheresultsofthesameattentionscores,aggre- gatedbyheadratherthanbydatasetexample.Astheattention analysiscomputesscoresperself-attentionheadandlayer,wecan observedifferent“specialized”partsofthesamemodelbyconsid- eringoneattentionheadatatime.Allmodels,onalldatasets,had someheadswithlowalignment(15%),indicatingthatnotallat- tentionheadsalignedtobugsemantics;theseheadsmayattendto otherrelationships,suchassyntacticrelationshipsintheAST[36], noitnettatnemngilA CodeBERT Big-Vul ReVeal D2A Devign dataset noitnettatnemngilA CodeT5 100% 80% 60% 40% 20% 0% Big-Vul ReVeal Devign D2A dataset noitnettatnemngilA LineVul Big-Vul ReVeal Devign D2A dataset noitnettatnemngilA 100 80 60 40 20 0 UniXcoder 1F 100 80 60 40 20 0 1F 100 80 60 40 20 0 1F 100 80 60 40 20 0 1F Alignment Attention analysis F1 Figure4:AlignmentofmodelattentiontoPVSbugsemantics, aggregatedbyhead. delimiters,ortherelativepositionsoftokens[9].Afewattention headshadrelativelyhighalignmentscores–upto40%inthecase oftheBig-Vuldatasetand50%inthecaseoftheD2Adataset.On theotherhand,mostattentionheadswereclusteredinabellcurve around20-30%alignment,indicatingthatmostpartsofthemodel didnotfocussolelyonbugsemantics. Similartointerpretationanalysis,themodelsallhadlowalign- menttobuggypaths(Figure1,middle),showingthatwhilemodels attendedtopotentiallyvulnerablestatements,theydidnotlearn thesignificanceofbuggypaths. 4.3 InteractionMatrix Motivation. Thepreviousapproachesanalyzedtheeffectsofindi- vidualtokensandconnectionsbetweentokens,butdidnotconsider theorderofcomputationinthemodel.Transformermodelscom- putehigh-levelrepresentationsoftheirsequencesandtheirfocus canmovefromonetokentoanotherthroughouttheircomputation. Paltenghietal.[27]proposedtheinteractionmatrixtorepresent thisnavigationofamodelthroughthesourcecode.Inorderto provideathirddistinctperspectiveonexplainingthemodel,we usedtheinteractionmatrixtoanalyzethemodel. Approach. Wecomputedaninteractionmatrix,definedas𝐼𝑀 ∈ 𝑉×𝑉.Itmeasureswhichtokenwilllikelybeattendedbythemodel afterthecurrenttoken. Concretely,eachcellof𝐼𝑀 assignsaprobability𝐼𝑀(𝑣 𝑖,𝑣 𝑗) to eachpairin𝑉 ×𝑉 whichrepresentstheprobabilitythatthenode inposition 𝑗 willbefocusedonthemodelsoonafterthenodein position𝑖.Theauthorsoriginallyusedtheinteractionmatrixto comparetheattentionoflargelanguagemodelswiththecodenavi- gationofhumandevelopers.Werepurposedthisanalysismethodin ordertounderstandwhetherthemodelislikelytojumptoorfrom bugsemanticfeatureswhenpredictinganexample.Weextended thedefinitiontobidirectionalmodelssincewestudiedmodelswith theBERTarchitecture,whichattendstobothfutureandpasttokens,DoLanguageModelsLearnSemanticsofCode?ACaseStudyinVulnerabilityDetection 100% 80% 60% 40% 20% 0% Big-Vul ReVeal Devign D2A dataset MItnemngilA CodeBERT Big-Vul ReVeal D2A Devign dataset MItnemngilA CodeT5 100% 80% 60% 40% 20% 0% Big-Vul ReVeal Devign D2A dataset MItnemngilA LineVul Big-Vul ReVeal Devign D2A dataset MItnemngilA 100 80 60 40 20 0 UniXcoder 1F 100 80 60 40 20 0 1F 100 80 60 40 20 0 1F 100 80 60 40 20 0 1F 4.4 FindingsfromAlignmentStudies:a Alignment Interaction matrix analysis F1 Summary Finding 1: Better-performing models aligned better to PVS. All modelsshowedthelowestalignmentwiththeBig-Vuldataset;the modelsdemonstratedhigheralignmentwiththebalancedDevign andD2AdatasetscomparedtotheimbalancedBig-VulandReVeal datasets.Thistrendmatchestheperformanceaswell,withmod- elsperformingworseontheimbalanceddatasetsthanbalanced datasets.Imbalanceddatasetshavealowerratioofvulnerableto non-vulnerableexamples;thismakesitmorechallengingforthe modeltolearntodistinguishbuggyfromnon-buggycodeandmay causethemodelstofocuslesson(bugsemantic)featureswhich occurinbuggycode[6].However,weexpecttoseeanimbalanced labeldistributioninreal-worldcode[14],sowehopetoimprove themodels’abilitytofocusonbugfeatures,eveninanimbalanced setting. Finding2:ThemodelsdidnotalignstronglytoPVS. Thoughthe modelsdidfocussomewhatonPVS,theabsolutescoresofalign- Figure5:AlignmentofinteractionmatrixtoPVSbugseman- mentwerealmostallbelow50%,indicatingthatthemostinfluential tics. featuresandattentionscoresdidnotalignstronglywithPVS.We positthatifthemodelswouldaligntothePVSmorestrongly,they wouldexhibitimprovedperformance.Tothisend,inthenextsec- tion,weupgradedthemodelstomakethemfocusmorestrongly
unlikeGPT-like(decoder-only)models,andratherthanapplying onthePVS. tothegenerationtask,weappliedtothebinaryclassificationtask. Tocorroborateourresultswiththeprevioustwometrics,we Finding3:ThemodelsdidnotaligntobuggypathsintheD2A generatedtheinteractionmatrix𝐼𝑀,thencomputedtheIoUmetric dataset. ShowninFigure1,allmodelsfailedtoaligntothebuggy ontheedgeswiththehighestprobabilityasestimatedby𝐼𝑀.We pathsreportedinD2A.Thesebuggypathsindicatethebugsemantic list the formula in Equation 4, where𝑀 𝑡𝑜𝑝𝐼𝑀(𝑘) is the set of𝑘 featuresmorepreciselythanPVSbecausetheyareconstrained tokensincidenttohighesttransitionprobabilitiesestimatedbythe byasequenceofstatementsinsteadofonestatement.Thelack interactionmatrix,and𝑘 =|𝐵|. ofalignmentindicatesthatthemodelsdidnotlearnthesemore precisebugsemanticsandopensupthisareaforfuturework. |𝑀 𝑡𝑜𝑝𝐼𝑀(𝑘) ∩𝐵| 5 IMPROVETHEMODELSUSINGBUG 𝐴𝑙𝑖𝑔𝑛𝑚𝑒𝑛𝑡 𝐼𝑀 = |𝑀 𝑡𝑜𝑝𝐼𝑀(𝑘) ∪𝐵| (4) SEMANTICS BasedontheresultsofthealignmentwithPVS,wesawthatthe Weaveragedtheprobabilitiesintheinteractionmatrixwithin eachASTtokeninordertocompare𝑀and𝐵atthesamegranular- models’mostimportantfeaturesalignedslightlywithPVS,and thathigheralignmentwasrelatedtohigherperformanceacross ity. differentdatasets.However,themodels’alignmentscoreswere Results. Figure5reportsthe𝐴𝑙𝑖𝑔𝑛𝑚𝑒𝑛𝑡 𝐼𝑀 scoresfromeachexam- relativelylow–mostlybelow50%alignment.Wehypothesizedthat pleinthedataset,comparedwithPVSbugfeatures. improvingalignmenttoPVSwouldimprovetheperformanceofthe Theresultsoftheinteractionmatrixcorroboratetheresultsofthe model.Toachievetheimprovedalignment,weannotatedthePVS interpretabilityandattentionanalysis,wheretoolswhichearned inthemodelinputs,andthenstudyhowthemodelperformance higher performance also aligned better on more examples. The changes. overallscoresfortheinteractionmatrixwerelowerthantheprevi- ousapproaches,asthehighestmedianscoreof𝐴𝑙𝑖𝑔𝑛𝑚𝑒𝑛𝑡 𝐼𝑀 was 5.1 AnnotatingPVSinmodelinputs around10%whilethehighestmedianscoreof𝐴𝑙𝑖𝑔𝑛𝑚𝑒𝑛𝑡 𝐼𝑛𝑡𝑒𝑟𝑝𝑟𝑒𝑡 Severalpriorapproacheshaveannotatedlanguagemodelinput wasaround20%.Thisindicatesthatwhilethemodelscoulduse togiveguidanceorextrainformationtothemodel[5,7,8].We theindividualbugfeaturesfortheirpredictionsandrelatethebug proposetoannotatethePotentiallyVulnerableStatements(PVS) featureswithinsomeattentionheads,theywerenotlikelytofocus insidetheprograminordertomakethemodelmorestronglyfocus onthebugfeaturesthroughoutthecomputationofthemodel.The ontheseforitspredictions.Thiscanbeconsideredasinserting modelsmaybefocusingonsomespecificfeatureswhicharecom- domainknowledgeintothemodel’sinput.Duetothelargedesign montoPVS,withoutrelatingthemtothecontextspecifictothe spaceoftheannotations,wedevelopedseveralapproachesand program. narroweddowntothetwohighest-performingannotationmethods. Themodelsallhadrelativelylowalignmenttobuggypathsusing TheseapproachesarepicturedinFigure6,incontrasttotheoriginal theinteractionmatrix(Figure1(right)). exampleprograminthetoprow.BenjaminSteenhoek,MdMahbuburRahman,ShailaSharmin,andWeiLe Originalprogram:[BOS] int main () { malloc(10); } [EOS] (cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32) (cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32) (cid:124) (cid:123)(cid:122) (cid:125) PotentiallyVulnerableStatement(PVS) Mark:[BOS] int main () { beginmallendbeginocendbegin(endbegin10endbegin);end} [EOS]
(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32) (cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32) (cid:124) (cid:123)(cid:122) (cid:125) Insertedmarkers Prepend:[BOS] malloc(10); [SEP] int main () { malloc(10); } [EOS] (cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32) (cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32)(cid:32) (cid:124) (cid:123)(cid:122) (cid:125) PrependedPVS Figure6:ExamplesofPVSannotations. Mark. Inspiredbytheusageofboundarytokensintheoriginal Table5:PVSannotationsimprovedmodelperformancein BERTmodel,weinsertspecial“marker”tokens(begin,end)before 56%ofmodelsanddatasets. andaftereachBPEtokeninsidethePVS[12].Themarkertokens allow the model to use its positional encoding to attend to the Model Setting D2A Devign Big-Vul Reveal tokenswhichareclosetothemarkers[9].Figure6(middle)shows thebeginandendtokensinsertedaroundeachtokeninthePVS.To CodeBERT Baseline 66.76 56.90 40.65 42.69 representthesenewtokens,weinsertednewrandomlyinitialized CodeBERT Mark 58.69 59.04 37.96 37.27 indicesintothemodel’sembeddingmatrixandtrainedthenew CodeBERT Prepend 67.04 53.46 38.14 43.66 indicesduringfine-tuning.Sincethemodelinputtokensarebroken UniXcoder Baseline 57.19 56.81 39.55 40.53 upbytheBPEtokenizer,thismethodtendstoinsertmultiplemarker UniXcoder Mark 60.10 59.56 39.63 43.67 tokensperstatement. UniXcoder Prepend 66.76 62.04 39.12 42.67 CodeT5 Baseline 57.33 58.79 40.20 40.56 Prepend. InspiredbythehintsprovidedtotheMODITmodel CodeT5 Mark 52.63 4.67 39.78 42.73 proposedbyChakraborthyetal.[7],weprependthetokensinside CodeT5 Prepend 65.68 60.53 40.96 43.88 PVSatthebeginningofthecode.Figure6(bottom)showsthat theoriginalprogram’ssourcecodeisunchanged,butweprepend LineVul Baseline 68.22 54.15 39.46 42.92 the sequence malloc(10); [SEP] before the program’s source LineVul Mark 63.49 58.78 32.69 42.89 code.[SEP]issimplyaseparatortokenusedtoseparatethetwo LineVul Prepend 67.69 58.66 36.44 45.45 semanticallydifferentsequences.TheplacementofthePVSasa differentmodalitybeforetheinputsequenceallowthemodelto easilyfocusontheseimportantstatements[7]Duetothemod- input,withoutchanges.MarkandPrepend denoteourproposed els’limitedcontextlengthof512tokens[15],wetruncatedthe approaches. prependedsequencetothefirst100BPEtokens. ThePrependannotationincreasedmodelperformanceabovethe baselinein11/16cases;Markdidnotperformaswell,improving only7/16cases.Infact,ontheDevign,D2A,andReVealdatasets, 5.2 Results thePrependannotationimprovedtheperformanceofthreeoutof Performance. InTable5,wepresenttheperformanceofPVSannota- fourmodels.Thisshowsthat,whileitdoesnotimproveallcases, tionsinthreedifferentsettings.Baselinedenotestheoriginalmodel annotatingthebugsemanticscanhelpmodelperformanceinthe 100% 80% 60% 40% 20% 0%
CodeT5 UniXcoder CodeBERT LineVul model terpretnitnemngilA D2A-bp 100 80 60 40 20 0 1F Baseline Interpretation analysis Prepend PVS Baseline F1 Prepend F1 100% 80% 60% 40% 20% 0% CodeT5 UniXcoder CodeBERT LineVul model noitnettatnemngilA D2A-bp 100 80 60 40 20 0 1F Baseline Attention analysis Prepend PVS Baseline F1 Prepend F1 100% 80% 60% 40% 20% 0% CodeT5 UniXcoder CodeBERT LineVul model MItnemngilA D2A-bp 100 80 60 40 20 0 1F Baseline Interaction matrix analysis Prepend PVS Baseline F1 Prepend F1 Figure7:PVS-annotatedmodelsdidnotaligntoD2Abuggypaths.DoLanguageModelsLearnSemanticsofCode?ACaseStudyinVulnerabilityDetection 100% 80% 60% 40% 20% 0% Big-Vul ReVeal Devign D2A dataset terpretnitnemngilA CodeBERT Big-Vul ReVeal Devign D2A dataset terpretnitnemngilA CodeT5 100% 80% 60% 40% 20% 0% Big-Vul ReVeal Devign D2A dataset terpretnitnemngilA LineVul Big-Vul ReVeal Devign D2A dataset terpretnitnemngilA 100 80 60 40 20 0 UniXcoder 1F 100 80 60 40 20 0 1F 100 80 60 40 20 0 1F 100 80 60 40 20 0 1F Baseline Interpretation analysis Prepend PVS Baseline F1 Prepend F1 1.00% 0.80% 0.60% 0.40% 0.20% 0.00% Big-Vul ReVeal Devign D2A dataset Figure8:Alignmentofbaselinevs.annotatedmodelinter- pretationstoPVSbugsemantics. majorityofcases.Inthebestcase(UniXcoder/PrependonD2A),the annotationimprovedtheF1scoreby9.57pointsabovethebaseline. However,insomecasessuchasCodeT5/MarkonDevign,the modelperformancereducesorcollapses.Thismaybecausedby excessiveannotationsreplacingsomeoftheoriginalcodetokens inthemodelinput,thuscausingthesignaltobeunstableduring training;sincetheinsertionofannotationsrequirestruncationof theoriginalcodetokens,thisisatradeoffduetothelimitations ofcurrentmodelarchitectures.However,newermodelssupport alargercontextlength,whichmayallowmoreflexibleandstable performancefromannotationschemes.BasedonTable4,theMSR datasethasthefewestPVSperprogram;thismaycontributeto reducingtheperformanceoftheannotationmethod.Futurework shouldseektoimprovethislimitationbyprovidingamorerobust annotationmethodorincludingmorefunctioncallsinthelistof PVS. Alignment. Wemeasuredthealignmentonthebest-performing approach,Prepend.SincethePrependapproachcopy-pastesthe PVSfromthecode,weconsideredallthetokensintheprepended annotationsaspartofthebuggyset𝐵.Figures8,9,and11showthe results;theBaselineandPrependperformanceareoverlaidusing dottedlines.ThePVSannotationincreasedthemodels’alignment scoresonallmodelsanddatasets.Themeanalignmentincreased from36-111%oninterpretabilityanalysis,51-232%onattention analysis,and38-79%oninteractionmatrixanalysis.Thisisstrong evidence that the models learned to use bug semantic features fromtheannotatedinputstomaketheirpredictions.Investigating further,Figure10showsthealignmentscoresaggregatedbyeach attentionheadacrossallexamples.Allpartsofthemodellearnedto alignwithPVS,evidencedbythehigherminimumandmaximum alignmentscores.Additionally,themodelstilllearnedto“specialize” withsomeattentionheadslearningtofocusonPVS,upto65% alignmentscore.However,insomecases,suchasCodeBERT,the PVSannotationfailedtoincreasethemodelperformance,even noitnettatnemngilA CodeBERT Big-Vul ReVeal Devign D2A dataset noitnettatnemngilA CodeT5 1.00% 0.80% 0.60% 0.40% 0.20% 0.00% Big-Vul ReVeal Devign D2A dataset noitnettatnemngilA LineVul Big-Vul ReVeal Devign D2A dataset noitnettatnemngilA 100 80 60 40 20 0 UniXcoder 1F 100 80 60 40 20 0 1F 100 80 60 40 20 0 1F 100 80 60 40 20 0 1F Baseline Attention analysis Prepend PVS Baseline F1 Prepend F1 Figure9:Alignmentofbaselinevs.annotatedmodelatten- tion to PVS bug semantics, aggregated over all attention headsbydatasetexample. thoughalignmenttoPVSincreased.Thisconfirmsouroriginalidea thatalignmenttoPVSisnotsufficienttodetectallbugs. Next,wemeasuredalignmentoftheannotatedmodelwithD2A buggypaths.Figure7showsthatthePVSannotationsreducedthe baselinemodel’salignmenttobuggypaths.Itisunclearwhythis occurred;butweplantofurtherstudytherelationshipbetween PVSandbuggypathsinfuturework. Wenotethattheannotationsweproposedareonlyaprototype, andfurtherdevelopmentofthisideacouldfurtherimprovethe alignmentand/orperformance.Weleavesuchimprovementsto 100% 80% 60% 40% 20% 0% Big-Vul ReVeal Devign D2A dataset noitnettatnemngilA CodeBERT Big-Vul ReVeal Devign D2A dataset noitnettatnemngilA CodeT5 100% 80% 60% 40% 20% 0% Big-Vul ReVeal Devign D2A dataset noitnettatnemngilA LineVul Big-Vul ReVeal Devign D2A dataset noitnettatnemngilA 100 80 60 40 20 0 UniXcoder 1F 100 80 60 40 20 0 1F 100 80 60 40 20 0 1F 100 80 60 40 20 0 1F Baseline Attention analysis Prepend PVS Baseline F1 Prepend F1 Figure10:Alignmentofbaselinevs.annotatedmodelatten- tiontoPVSbugsemantics,aggregatedbyattentionhead.BenjaminSteenhoek,MdMahbuburRahman,ShailaSharmin,andWeiLe 100% 80% 60% 40% 20% 0% Big-Vul ReVeal Devign D2A dataset MItnemngilA CodeBERT Big-Vul ReVeal Devign D2A dataset MItnemngilA CodeT5 100% 80% 60% 40% 20% 0% Big-Vul ReVeal Devign D2A dataset MItnemngilA LineVul Big-Vul ReVeal Devign D2A dataset MItnemngilA 100 80 60 40 20 0 UniXcoder 1F 100 80 60 40 20 0 1F 100 80 60 40 20 0 1F 100 80 60 40 20 0 1F 7 RELATEDWORK Baseline
Interaction matrix analysis P Br ae sp ee lin nd e P FV 1S EmpiricalstudiesofdeeplearninginSE. Niuetal.[26]compared Prepend F1 theperformancesof19pre-trainedsourcecodemodelson13differ- entsoftwareengineeringtasks.Croftetal.[11]analyzedthequality oftheopen-sourcedatasetspublishedintheSEliteratureandeval- uatedtheperformanceafterdatacleaning.Chakraborthyetal.[6] studiedtheperformanceofdeeplearningmodelsinareal-world vulnerabilitypredictionscenario.Steenhoeketal.[33]explored theimportantanddifficultfeaturesfordeeplearningmodels,and evaluatedtheirperformanceundernoveltrainingdatasizes,bug types,open-sourceprojects.Incontrasttothesestudies,wewent beyondperformancemetricsandcomparedthemodels’influential featureswithbugsemantics. Modelguidance. Fortheprogramrepairtask,MODIT[7],CODIT[5], andSequenceR[8]wrappedthebuggycodewithspecialtokens suchas<START_BUG>,<END_BUG>toguidethemodeltowardthe buggylines.Inspiredbytheseapproaches,wedesignedanapproach Figure11:Alignmentofbaselinevs.annotatedmodelinter- to guide the model to focus on PVS. Liu et al. [22] introduced actionmatrixtoPVSbugsemantics. Highlight-Transformer,whichassignsgreaterattentionweights tokeyphrasesinordertoimprovedocumentsummarization.We triedtodirectlyapplytheirapproachtoassignhigherweightsto futurework.WealsotriedtoannotatethePVSusingHighlight- thePVS,butournaiveapproachdidnotimprovetheperformance. Transformer[22],whichassignshigherattentionweightstospecial tokens,butcouldn’tincreasetheperformancewiththisapproach.In Modelanalysis. Variousworkshaveanalyzedself-attentionweights additiontoannotatingthePVS,wehavealsotriedtoannotatepath- tounderstandtheinteractionbetweenattentionandthestructureof basedbugsemanticsbyannotatingstaticallydetectablesource/sink thedata.Wanetal.[36]conductedattentionanalysistoinvestigate bugfeatures,butinourinitialexperiments,thesimpleannotation howattentionalignswiththesyntacticstructureofsourcecode. techniquecouldn’tincreasetheperformanceinmostcases.We Paltenghietal.[27]studieddeveloper’sandhuman’sattentiondur- viewalignmenttopath-basedbugsemanticsasanimportantnext ingcodeexploration.Theyproposedaninteractionmatrixfrom stepandencouragefutureworkinthisarea. theattentionweightsofthemodelswhichcapturesthelikelihood ofthemodel’sfocusmovingfromonelinetoanother.Weextended 6 THREATSTOVALIDITY thesemethodstoexplainhowthetransformermodelslearnbug Therehavebeenmanytechniqueswhichattempttounderstand semantics. modelbehaviors,butevaluationofthesetechniquesoftenfaces challengesandhaslimitations.Toincreasethereliabilityofour 8 CONCLUSIONSANDFUTUREWORK conclusions, we corroborated three distinct techniques – inter- pretabilitytools,attentionanalysis,andinteractionmatrixanalysis Westudiedthealignmentbetweeninfluentialmodelfeatures,de- –eachofwhichprovidesdifferentperspectivesofthemodel. finedbyinterpretationtools,attentionanalysis,andinteraction Weusedinterpretabilitytools,whichmaynotfaithfullyestimate matrixanalysis,andbugfeatures,definedbyPotentiallyVulner- theattributionsoffeatures.Tomitigatethisconcern,weaggregated ableStatements(PVS)andbuggypaths.Weshowthatthebetter- theattributionscoresfrommultipletoolswhichuseddistincttech- performingmodelsalignedbettertoPVS;however,themodelsdid niques.Furthermore,interpretationsoftheattentionscoredonot notstronglyaligntoPVS.Additionally,themodelsdidnotalign fullyexplainmodelpredictions–theycanonlyshowcorrelation substantiallytobuggypaths.Basedonouranalysis,wedeveloped withhigh-attentionedges[18,38].Tounderstandtheexplanations twomethodsforannotatingthePVSinsidethemodelinputs.We ofthemodel’spredictions,westudiedbothinterpretabilitytools showedthattheannotationsimprovedtheperformanceandalign- andtheattentionmechanism. mentinthemajorityofsettings;annotatedmodelsimprovedtheir Wegeneratedourlistofpotentiallyvulnerablestatementsfrom F1scorebyupto9.57pointsandalignedupto232%bettertoPVS. theCstandardlibrarycombinedwithourdomainknowledge.How- OurannotationapproachisapreliminaryattemptatusingPVS ever,somefunctioncallsmaybemissingfromthelistofPVS,which toimprovethemodelperformanceandalignment.Inthefuture,we mayimpactthemeasurementofalignmentwithbugsemantics. willalsodevelopotherapproachestomakethemodelsattendto Finally,itwouldbeinterestingtostudylargerlanguagemodels bugsemantics.Anotherhighly-motivatedfutureworkistostudy suchasChatGPTandGPT-4,whichhaveexhibitedsuperiorcapa- thealignmenttopath-basedbugsemanticsratherthancomparing bilitiestoBERTfamilymodelsonsourcecodeunderstandingtasks. individualstatementsandtomakethemodelaligntobuggypathsin However,thesemodelsareclosed-source,sowearenotabletouse ordertoimproveitsperformance.Thesecanincludestaticanalysis interpretabilitytoolsoranalyzetheirattentionscoresindetail. pathsaswellasexecutiontraces.DoLanguageModelsLearnSemanticsofCode?ACaseStudyinVulnerabilityDetection REFERENCES Multi-DocumentSummarization.InFindingsoftheAssociationforComputational [1] 2021. Browse vulnerabilities by date. https://web.archive.org/web/ Linguistics:ACL-IJCNLP2021.AssociationforComputationalLinguistics,Online,
20211014235218/https://www.cvedetails.com/browse-by-date.php. Accessed 5021–5027. https://doi.org/10.18653/v1/2021.findings-acl.445 November52021. [23] ShuaiLu,DayaGuo,ShuoRen,JunjieHuang,AlexeySvyatkovskiy,Ambrosio [2] 2021.IBMCostofaDataBreachReport2021. AccessedOctober292021. Blanco,ColinClement,DawnDrain,DaxinJiang,DuyuTang,GeLi,Lidong [3] JayAlammar.2018.Theillustratedtransformer.TheIllustratedTransformer–Jay Zhou,LinjunShou,LongZhou,MicheleTufano,MingGong,MingZhou,Nan Alammar–VisualizingMachineLearningOneConceptataTime27(2018). Duan,NeelSundaresan,ShaoKunDeng,ShengyuFu,andShujieLiu.2021. [4] PanBian,BinLiang,JianjunHuang,WenchangShi,XidongWang,andJian CodeXGLUE:AMachineLearningBenchmarkDatasetforCodeUnderstanding Zhang.2020.SinkFinder:harvestinghundredsofunknowninterestingfunction andGeneration.(2021). http://arxiv.org/abs/2102.04664 pairswithjustoneseed.InProceedingsofthe28thACMJointMeetingonEuropean [24] ScottMLundbergandSu-InLee.2017. AUnifiedApproachtoInterpreting SoftwareEngineeringConferenceandSymposiumontheFoundationsofSoftware ModelPredictions.InAdvancesinNeuralInformationProcessingSystems,Vol.30. Engineering(ESEC/FSE2020).AssociationforComputingMachinery,NewYork, CurranAssociates,Inc. NY,USA,1101–1113. https://doi.org/10.1145/3368089.3409678 [25] SaraMoshtari,AhmetOkutan,andMehdiMirakhorli.2022.Agroundedtheory [5] SaikatChakraborty,YangruiboDing,MiltiadisAllamanis,andBaishakhiRay. basedapproachtocharacterizesoftwareattacksurfaces.InProceedingsofthe 2022.CODIT:CodeEditingwithTree-BasedNeuralModels.IEEETransactions 44thInternationalConferenceonSoftwareEngineering(ICSE’22).Associationfor onSoftwareEngineering48,4(April2022),1385–1399. https://doi.org/10.1109/ ComputingMachinery,NewYork,NY,USA,13–24. https://doi.org/10.1145/ TSE.2020.3020502arXiv:1810.00314[cs] 3510003.3510210 [6] SaikatChakraborty,RahulKrishna,YangruiboDing,andBaishakhiRay.2022. [26] ChanganNiu,ChuanyiLi,VincentNg,DongxiaoChen,JidongGe,andBinLuo. DeepLearningBasedVulnerabilityDetection:AreWeThereYet?IEEETrans- 2023. Anempiricalcomparisonofpre-trainedmodelsofsourcecode. arXiv actionsonSoftwareEngineering48,9(Sept.2022),3280–3296. https://doi.org/ preprintarXiv:2302.04026(2023). 10.1109/TSE.2021.3087402 ConferenceName:IEEETransactionsonSoftware [27] MatteoPaltenghi,RahulPandita,AustinZ.Henley,andAlbertZiegler.2022.Ex- Engineering. tractingMeaningfulAttentiononSourceCode:AnEmpiricalStudyofDeveloper [7] SaikatChakrabortyandBaishakhiRay.2021.OnMulti-ModalLearningofEditing andNeuralModelCodeExploration. https://doi.org/10.48550/arXiv.2210.05506 SourceCode. arXiv:2108.06645[cs.SE] arXiv:arXiv:2210.05506 [8] ZiminChen,SteveKommrusch,MicheleTufano,Louis-NoëlPouchet,Denys [28] AnnaRogers,OlgaKovaleva,andAnnaRumshisky.2020.APrimerinBERTology: Poshyvanyk,andMartinMonperrus.2021.SequenceR:Sequence-to-Sequence WhatWeKnowAboutHowBERTWorks. TransactionsoftheAssociationfor LearningforEnd-to-EndProgramRepair.IEEETransactionsonSoftwareEngi- ComputationalLinguistics8(Dec.2020),842–866. https://doi.org/10.1162/tacl_ neering47,9(2021),1943–1959. https://doi.org/10.1109/TSE.2019.2940179 a_00349 [9] KevinClark,UrvashiKhandelwal,OmerLevy,andChristopherD.Manning.2019. [29] RicoSennrich,BarryHaddow,andAlexandraBirch.2016. NeuralMachine WhatDoesBERTLookat?AnAnalysisofBERT’sAttention.InProceedingsofthe TranslationofRareWordswithSubwordUnits.InProceedingsofthe54thAnnual 2019ACLWorkshopBlackboxNLP:AnalyzingandInterpretingNeuralNetworks MeetingoftheAssociationforComputationalLinguistics(Volume1:LongPapers). forNLP.AssociationforComputationalLinguistics,Florence,Italy,276–286. AssociationforComputationalLinguistics,Berlin,Germany,1715–1725. https: https://doi.org/10.18653/v1/W19-4828 //doi.org/10.18653/v1/P16-1162 [10] TheMITRECorporation.2022.CWETop25MostDangerousSoftwareWeak- [30] AvantiShrikumar,PeytonGreenside,andAnshulKundaje.2019. Learning nesses. https://cwe.mitre.org/top25/archive/2022/2022_cwe_top25.html ImportantFeaturesThroughPropagatingActivationDifferences. https://doi. [11] RolandCroft,MAliBabar,andMMehdiKholoosi.2023.Dataqualityforsoftware org/10.48550/arXiv.1704.02685arXiv:1704.02685[cs] vulnerabilitydatasets.In2023IEEE/ACM45thInternationalConferenceonSoftware [31] AvantiShrikumar,PeytonGreenside,AnnaShcherbina,andAnshulKundaje. Engineering(ICSE).IEEE,121–133. 2017. Not Just a Black Box: Learning Important Features Through Prop- [12] JacobDevlin,Ming-WeiChang,KentonLee,andKristinaToutanova.2019.BERT: agatingActivationDifferences. https://doi.org/10.48550/arXiv.1605.01713 Pre-trainingofDeepBidirectionalTransformersforLanguageUnderstanding. arXiv:1605.01713[cs]
https://doi.org/10.48550/arXiv.1810.04805arXiv:1810.04805[cs] [32] KarenSimonyan,AndreaVedaldi,andAndrewZisserman.2014.DeepInside [13] FinaleDoshi-VelezandBeenKim.2017. TowardsARigorousScienceofIn- ConvolutionalNetworks:VisualisingImageClassificationModelsandSaliency terpretable Machine Learning. https://doi.org/10.48550/arXiv.1702.08608 Maps. https://doi.org/10.48550/arXiv.1312.6034arXiv:1312.6034[cs] arXiv:1702.08608[cs,stat] [33] BenjaminSteenhoek,MdMahbuburRahman,RichardJiles,andWeiLe.2023. [14] JiahaoFan,YiLi,ShaohuaWang,andTienN.Nguyen.2020. AC/C++Code An Empirical Study of Deep Learning Models for Vulnerability Detection. VulnerabilityDatasetwithCodeChangesandCVESummaries. Proceedings- arXiv:2212.08109[cs.SE] 2020IEEE/ACM17thInternationalConferenceonMiningSoftwareRepositories, [34] AshishVaswani,NoamShazeer,NikiParmar,JakobUszkoreit,LlionJones, MSR2020(2020),508–512. https://doi.org/10.1145/3379597.3387501 AidanN.Gomez,LukaszKaiser,andIlliaPolosukhin.2017. AttentionIsAll [15] ZhangyinFeng,DayaGuo,DuyuTang,NanDuan,XiaochengFeng,MingGong, YouNeed. arXiv:1706.03762[cs](Dec.2017). http://arxiv.org/abs/1706.03762 LinjunShou,BingQin,TingLiu,DaxinJiang,andMingZhou.2020.CodeBERT:A arXiv:1706.03762. Pre-TrainedModelforProgrammingandNaturalLanguages.(2020),1536–1547. [35] JesseVig,AliMadani,LavR.Varshney,CaimingXiong,RichardSocher,and https://doi.org/10.18653/v1/2020.findings-emnlp.139 NazneenFatemaRajani.2021.BERTologyMeetsBiology:InterpretingAtten- [16] MichaelFuandChakkritTantithamthavorn.2022. LineVul:ATransformer- tioninProteinLanguageModels. https://doi.org/10.48550/arXiv.2006.15222 basedLine-LevelVulnerabilityPrediction.In2022IEEE/ACM19thInternational arXiv:arXiv:2006.15222 ConferenceonMiningSoftwareRepositories(MSR).608–620. https://doi.org/10. [36] YaoWan,WeiZhao,HongyuZhang,YuleiSui,GuandongXu,andHaiJin.2022. 1145/3524842.3528452ISSN:2574-3864. WhatDoTheyCapture?AStructuralAnalysisofPre-TrainedLanguageModels [17] DayaGuo,ShuaiLu,NanDuan,YanlinWang,MingZhou,andJianYin.2022. forSourceCode.InProceedingsofthe44thInternationalConferenceonSoftware UniXcoder:UnifiedCross-ModalPre-trainingforCodeRepresentation. https: Engineering(ICSE’22).AssociationforComputingMachinery,NewYork,NY, //doi.org/10.48550/arXiv.2203.03850Number:arXiv:2203.03850arXiv:2203.03850 USA,2377–2388. https://doi.org/10.1145/3510003.3510050 [cs]. [37] YueWang,WeishiWang,ShafiqJoty,andStevenC.H.Hoi.2021. CodeT5: [18] SarthakJainandByronC.Wallace.2019.AttentionIsNotExplanation. https: Identifier-awareUnifiedPre-trainedEncoder-DecoderModelsforCodeUn- //doi.org/10.48550/arXiv.1902.10186arXiv:1902.10186[cs] derstanding and Generation. https://doi.org/10.48550/arXiv.2109.00859 [19] GaneshJawahar,BenoîtSagot,andDjaméSeddah.2019.WhatDoesBERTLearn arXiv:2109.00859[cs]. abouttheStructureofLanguage?.InProceedingsofthe57thAnnualMeetingof [38] SarahWiegreffeandYuvalPinter.2019. AttentionIsNotNotExplanation. theAssociationforComputationalLinguistics.AssociationforComputational https://doi.org/10.48550/arXiv.1908.04626arXiv:1908.04626[cs] Linguistics,Florence,Italy,3651–3657. https://doi.org/10.18653/v1/P19-1356 [39] Wikipedia. 2021. List of data breaches. https://web.archive.org/web/ [20] NarineKokhlikyan,VivekMiglani,MiguelMartin,EdwardWang,BilalAlsallakh, 20211011144237/https://en.wikipedia.org/wiki/List_of_data_breaches. Accessed JonathanReynolds,AlexanderMelnikov,NataliaKliushkina,CarlosAraya,Siqi October292021. Yan,andOrionReblitz-Richardson.2020.Captum:Aunifiedandgenericmodel [40] FabianYamaguchi,NicoGolde,DanielArp,andKonradRieck.2014.Modeling interpretabilitylibraryforPyTorch. arXiv:2009.07896[cs.LG] andDiscoveringVulnerabilitieswithCodePropertyGraphs.Proceedings-IEEE [21] WeiLeandMaryLouSoffa.2008. Marple:ademand-drivenpath-sensitive SymposiumonSecurityandPrivacy(2014),590–604. https://doi.org/10.1109/SP. bufferoverflowdetector.InProceedingsofthe16thACMSIGSOFTInterna- 2014.44 tionalSymposiumonFoundationsofsoftwareengineering(SIGSOFT’08/FSE- [41] YunhuiZheng,SaurabhPujar,BurnLewis,LucaBuratti,EdwardEpstein,Bo 16). Association for Computing Machinery, New York, NY, USA, 272–282. Yang,JimLaredo,AlessandroMorari,andZhongSu.2021. D2A:ADataset https://doi.org/10.1145/1453101.1453137 BuiltforAI-BasedVulnerabilityDetectionMethodsUsingDifferentialAnalysis. [22] ShuaiqiLiu,JiannongCao,RuosongYang,andZhiyuanWen.2021.Highlight- (2021),111–120. https://doi.org/10.1109/icse-seip52600.2021.00020
Transformer:LeveragingKeyPhraseAwareAttentiontoImproveAbstractive [42] YaqinZhou,ShangqingLiu,JingkaiSiow,XiaoningDu,andYangLiu.2019. Devign:EffectivevulnerabilityidentificationbylearningcomprehensiveprogramBenjaminSteenhoek,MdMahbuburRahman,ShailaSharmin,andWeiLe semanticsviagraphneuralnetworks.AdvancesinNeuralInformationProcessing Systems32(2019),1–11.
2311.08066 Noname manuscript No. (will be inserted by the editor) How to get better embeddings with code pre-trained models? An empirical study Yu Zhao · Lina Gong · Haoxiang Zhang · Yaoshen Yu · Zhiqiu Huang Received:date/Accepted:date Abstract Pre-trained language models have demonstrated powerful capabil- ities in the field of natural language processing (NLP). Recently, code pre- trained model (PTM), which draw from the experiences of the NLP field, have also achieved state-of-the-art results in many software engineering (SE) downstreamtasks.ThesecodePTMstakeintoaccountthedifferencesbetween programming languages and natural languages during pre-training and make adjustments to pre-training tasks and input data. However, researchers in the SE community still inherit habits from the NLP field when using these code PTMs to generate embeddings for SE downstream classification tasks, such as generating semantic embeddings for code snippets through special tokens and inputting code and text information in the same way as pre-training the PTMs. In this paper, we empirically study five different PTMs (i.e. Code- BERT, CodeT5, PLBART, CodeGPT and CodeGen) with three different ar- chitectures (i.e. encoder-only, decoder-only and encoder-decoder) on four SE downstream classification tasks (i.e. code vulnerability detection, code clone detection, just-in-time defect prediction and function docstring mismatch de- tection) with respect to the two aforementioned aspects. Our experimental YuZhao·LinaGong·YaoshenYu·ZhiqiuHuang College of Computer Science and Technology, Nanjing University of Aeronautics and Astronautics, and State Key Lab. for Novel Software Technology, Nanjing University, and Key Laboratory of Safety-Critical Software, Nanjing University of Aeronautics and Astronautics. E-mail: zhao yu@nuaa.edu.cn, linagong@nuaa.edu.cn, yaoshen.yu@outlook.com, zqhuang@nuaa.edu.cn HaoxiangZhang SoftwareAnalysisandIntelligenceLab(SAIL),Queen’sUniversity,Kingston,ON,Canada E-mail:haoxiang.zhang@acm.org Corresponding author: Zhiqiu Huang and Lina Gong, Email: zqhuang@nuaa.edu.cn, gonglina@nuaa.edu.cn 3202 voN 41 ]ES.sc[ 1v66080.1132:viXra2 YuZhaoetal. resultsindicatethat(1)regardlessofthearchitectureofthecodePTMsused, embeddings obtained through special tokens do not sufficiently aggregate the semanticinformationoftheentirecodesnippet;(2)thequalityofcodeembed- dings obtained by combing code data and text data in the same way as pre- training the PTMs is poor and cannot guarantee richer semantic information; (3) using the method that aggregates the vector representations of all code tokens, the decoder-only PTMs can obtain code embeddings with semantics as rich as or even better quality than those obtained from the encoder-only and encoder-decoder PTMs. Based on our findings, we recommend that re- searchers in the SE community (1) pay attention to the vector representation of each code token when generating code embeddings for downstream clas- sification tasks, for example, obtaining richer semantic embeddings through simple average-pooling of all code tokens; (2) adopt the unimodal input ap- proach when generating code embeddings for downstream classification tasks with both code and text information to obtain competitive and higher qual- ity code embeddings; and (3) use larger-scale decoder architecture PTMs to aggregatevectorrepresentationsofallinputcodetokenstoobtainhigherqual- ity code embeddings with richer implied semantic information. Our research provides SE researchers with guidance on how to obtain higher-quality code embeddings when using code PTMs, thereby advancing future research on SE downstream classification tasks. Keywords Semantics · Code tokens · Code embeddings · Higher-quality · Code pre-trained models · SE downstream classification tasks 1 Introduction Distributedrepresentationsofcodehaveplayedacrucialroleinharnessing thepowerofdeeplearningforsoftwareengineeringtasks[1,2].Thesemethods aim to learn low-dimensional vector representations [3–5], known as code em- beddings,tocapturetheessenceofsourcecode.Withintheseembeddings,the meaningofthecodeisdistributedacrossmultiplevectorcomponents,allowing semanticallysimilarcodesnippetstobemappedtocloselypositionedvectors. This property empowers code embeddings to perform exceptionally well in a variety of downstream software engineering tasks, including program compre- hension tasks like vulnerability detection [6], as well as program generation tasks like code comment generation [7]. Recently, pre-trained language models (PTM) have gained immense pop- ularity in the field of natural language processing (NLP) [8–11]. These pre- trained models are machine learning models that are pre-trained on vast amountsoftrainingdatatolearngeneralfeaturesandpossesspowerfulrepre- sentational capabilities [12,13]. They can generate sentence embeddings that encapsulate rich semantic information, which can be used for various down- streamNLPtasks[14–16].Inordertoadvanceresearchinthedomainofcode, researchers in the Software Engineering (SE) community have developed var- ious code PTMs based on the similarity between programming languages andHowtogetbetterembeddingswithcodepre-trainedmodels?Anempiricalstudy 3 natural languages. For instance, following the release of the natural language PTM BERT [17], SE researchers subsequently introduced several PTMs ca- pableoflearningprogramminglanguages.TheseincludeCuBERT[18],Code- BERT [19], TreeBERT [20], GraphCodeBERT [21], and more. These code PTMs can generate code embeddings that convey abundant semantic infor- mation for tasks such as programming comprehension and generation [22,23]. We know that SE researchers have taken into account the specific char- acteristics of code when training code PTMs, leading to the design of novel
pre-training tasks to better accommodate these characteristics. For example, Feng et al. [19] took into account code-specific annotation information when training the CodeBERT model and designed a bimodal input method of code and annotation to input data and trained PL-NL pairs on the Masked Lan- guage Modeling task during training. Wang et al. [24], on the other hand, focused on identifiers in code when training CodeT5, tailoring specific train- ing tasks for them. However, current researchers often still follow the habit of usinglanguagemodelstoobtainembeddingsintheNLPfieldwhenusingcode PTMs to generate embeddings for code snippets [25,26]. Sharma et al. [27] retrained BERT on Java code and found that, in clone detection tasks, the retrainedBERTpaidmoreattentiontosyntacticentities,especiallyidentifiers and delimiters in Java code, compared to the widely focused [CLS] token in NLP. Inspired by their work, we realized that despite previous studies in the SE field indicating similarities between programming languages and natural languages,itmaynotbeentirelyappropriateforcurrentresearcherstodirectly apply NLP knowledge to assume similar behavior in code. This is especially crucial when generating code embeddings using PTMs as the embedding is the first critical step in leveraging deep learning techniques to solve SE down- stream tasks. Using an inappropriate approach may result in lower-quality code embeddings, which may fail to capture the rich semantic information in the code and subsequently impact the performance of downstream tasks. To this end, this paper focuses on the classification task in the SE field to study the practices of researchers in the SE community when using code PTMs to generate embedding representations. Based on previous literature surveys, we found: (1)Currently,whenmanyresearchersusecodePTMstogenerateembed- ding representations for code snippets on SE classification tasks, they often followthepracticeofNLPresearchersinusingcertainspecialtokenstoobtain semanticaggregationembeddingsofcodesnippets[28,29].TheNLPPTMscan use the special token to extract a semantic embedding representing its mean- ing from a piece of natural language and then convert it into an equivalent natural language description. This approach has been successful in obtaining semantic representations of sentences in the NLP domain, as it can capture semantic relationships between words in a sentence. But for a piece of code of classification tasks, the semantic embedding aggregated through such a spe- cialtokenmaynotberichenoughtocapturethedifferentinformationofcode between different categories.4 YuZhaoetal. (2) For code-related classification tasks with textual information such as naturallanguageannotations,SEresearchersdonotparticularlyfocusonhow codeandtextarecombinedwheninputtingcodeandtextinformationastoken sequences into those PTMs [18,30]. This can impact the richness of seman- tic information encoded in the resulting code embeddings. Many researchers, when using code PTMs to generate embeddings for code snippets containing comments, employ the method of combining code and comments as they were duringpre-training.Forinstance,recentstudies[30]utilizingCodeBERTsepa- ratecodeandcommentsusingspecialtokensastheywereduringpre-training, and then pair them as input into the CodeBERT to obtain code embeddings. InordertoobtainhigherqualitycodeembeddingswhenusingcodePTMs and provide guidance to researchers in the SE community, this study ex- plores the above two aspects using a total of five PTMs (i.e. CodeBERT [19], CodeT5 [24], PLBART [31], CodeGPT [32] and CodeGen [33]) from three different architectures (i.e. encoder-only, decoder-only and encoder-decoder) acrossfourSEclassificationtasks(i.e.codevulnerabilitydetection,codeclone detection, just-in-time defect prediction and function docstring mismatch de- tection) using three performance evaluated metrics (i.e. Accuracy, F1 and MCC).Specifically,weformulatethefollowingtworesearchquestionstoguide our investigation: – RQ1: Can the embedding obtained through a particular token sufficiently aggregate the semantic information of the entire code snippets? – RQ2: How do the way code and text are combined affect the quality of semantic embeddings generated by code pre-trained models? Our experimental results demonstrate: • No matter which architecture of the code PTM is used, the embedding obtained through a special token cannot fully aggregate the semantic in- formation of the entire code snippets. Conversely, focusing on the vector representations of each code token, for instance, through a simple average pooling method, leads to embeddings with richer semantic information. This approach benefits the PTMs in encoder-only architectures to a lesser extent, followed by encoder-decoder architectures, and provides the most benefit to models in decoder-only architectures. • NomatterwhicharchitectureofthecodePTMisused,thequalityofcode embedding obtained by inputting data according to the way of combining code and text information during pre-training is generally poor, and it is notguaranteedtoobtaincodeembeddingwithrichersemanticinformation. Incontrast,inputtingcodeinformationandtextinformationseparatelyi.e. unimodal input proves to be a competitive approach for obtaining higher- quality code embeddings. Significance of Study. Our study provides new insights into the use of code PTMs by researchers in the current SE community to generate codeHowtogetbetterembeddingswithcodepre-trainedmodels?Anempiricalstudy 5 embeddings. This includes the current SE field’s thinking on the use of PTms borrowed from the NLP field and how to use these code PTMs to exert their capabilities to generate code embeddings with richer semantic information to support downstream classification tasks. SE researchers can leverage the find- ings presented in this paper to effectively employ current code PTMs and
potentially achieve improved results. We have open-sourced our experimental code and data, facilitating replication, result validation, and further dissemi- nation within the SE community. Paper Organization. Section 2 discusses the background and motiva- tionforthisstudy.Section3introducestheexperimentalsetupoftheempirical study and provides an overview of our study. Section 4 describes the two re- searchquestions ofourwork,includingresearchmethods,resultsanalysisand discussion. Section 5 shows the implications of the experimental conclusions. Section 6 discusses threats to the validity of our experimental conclusions. Finally, Section 7 concludes the paper. 2 Motivation and Related work Pre-trained language models have shown great promise in the NLP field. BERT, as a representative example, has achieved advanced performance in various downstream NLP tasks. Drawing parallels between programming lan- guagesandnaturallanguages,researchersintheSEcommunityhaveexplored code PTMs based on their studies of BERT. CuBERT [18] was the first to propose a programming language-based PTM for learning code embedding representations. It employs the same architecture and pre-training tasks as BERT to model the Python language for obtaining code embeddings. Unlike natural language, programming language possesses unique semantic informa- tion. To generate distributed vector representations for code, CodeBERT [19] employs a structure similar to BERT, but with different training tasks, mod- eling six programming languages to obtain a unified code representation. In contrast to natural language, the structural information of code in the pro- gramming language is more crucial. Therefore, some researchers have incor- porated code structure information into the training data to obtain universal code PTMs such as TreeBERT [20] and GraphCodeBERT [21]. These PTMs have demonstrated superior performance in downstream tasks related to pro- gram comprehension and program generation. For example, the CodeBERT proposedbyFengetal.[19]hasshowngoodperformanceincodesearchtasks, whiletheCodeT5proposedbyWangetal.[24]hasperformedwellintaskslike code translation, defect detection, and code summarization. Nijkamp et al.’s CodeGen [33] has also shown strong performance in code generation tasks. InadditiontodirectlyapplyingPTMstospecificdownstreamtasks,many researchers also utilize these PTMs to generate code embeddings for further integration into the training pipeline of task-specific models. Zhou et al. [30] extractedinformationfromthecodeembeddingsgeneratedbyCodeBERTus- ingconvolutionalneuralnetworksandachievedperformancecomparabletothe6 YuZhaoetal. current state-of-the-art method inthe just-in-time defect prediction task. Sun et al. [34]utilized the BERT model to obtain feature representations of smart contract code, and combined active learning techniques with uncertain sam- pling strategies to learn information related to contract vulnerabilities from these feature representations, achieving good performance in contract vulner- ability detection. Tang et al. [35] proposed the CSGVD method, which com- binesBiLSTMwithembeddingsgeneratedbyCodeBERTtoeffectivelydetect vulnerabilities based on code embeddings. Dingetal.[36]extendedtheexperimentsconductedbyKangetal.[37]on sixdownstreamSEtasks,includingcodecommentgeneration,codeauthorship identification, code clone detection, source code classification, log statement prediction, and software defect prediction. They found that using code em- bedding techniques indeed contributed to achieving better performance in SE downstream tasks. However, we observed that researchers often acquire the embeddings generated for code classification tasks in a manner similar to how NLP researchers use special tokens to obtain semantic embeddings for text snippets. For example, when Feng et al. [19] released the CodeBERT model, they recommended and used a special token, [CLS], representing the vector at the first position as the semantic embedding for the entire input. Similarly, when Lu et al. [32] released the CodeGPT model, they used a special token, [SEP], representing the vector at the last position as the semantic embedding for the entire input. Subsequent researchers often followed this approach to obtain code embeddings. This method of obtaining embeddings using special tokens stems from the NLP field and may not be suitable for the SE domain, potentially leading to lower-quality embeddings [25,26]. Therefore, we pose the first research question: RQ1:Cantheembeddingobtainedthroughaparticulartokensufficiently aggregate the semantic information of the entire code snippets? Furthermore, we observe that many researchers have not paid particular attention to how code snippets with accompanying text information are com- bined [30,38]. Different methods of combining them as input to PTMs can also impact the quality of the resulting code embeddings. Therefore, we raise the second research question: RQ2: How do the way code and text are combined affect the quality of semantic embeddings generated by code pre-trained models? Code embedding is a crucial step in downstream tasks, as high-quality code embeddings can encapsulate rich semantic information and facilitate the practicalityofsubsequenttasks.Toaddresstheaforementionedresearchissues, weconductedastudyonhowtoobtainhigher-qualitycodeembeddingsacross four SE classification tasks using a total of five pre-trained models with three differentarchitectures.Thenextsectionwillprovideadetailedoverviewofthe techniques involved.Howtogetbetterembeddingswithcodepre-trainedmodels?Anempiricalstudy 7 3 Experimental Design In this section, we provide a detailed description of the key components involvedintheexperimentaldesignofthispaper.ThisincludesthePTMsuti- lized for generating code embeddings, the downstream SE classification tasks employed for experimental research, as well as the associated task datasets and the metrics used for performance evaluation.
3.1 Pre-trained Models Toensurethecomprehensivenessoftheexperimentsinthispaperandthe applicability of the conclusions, we examine code PTMs across all three dif- ferent architectures: encoder-only, encoder-decoder, and decoder-only. Specif- ically, we select CodeBERT [19] for the encoder-only architecture, and for the decoder-only architecture, we employ CodeGPT [32] and CodeGen [33]. In the case of the encoder-decoder architecture, our choices are CodeT5 [24] and PLBART [31]. Note that these five code PTMs are all pre-trained on multiple programminglanguagesandthepre-trainingdataincludesbothcodedataand text data. These code-related PTMs are widely utilized by researchers in the recent SE community for various downstream tasks. A brief introduction to these five models is provided in Table 1. Table 1 FivecodePTMsofthreearchitecturesforgeneratingembeddings Name Architecture ParameterSize EmbeddingDimension CodeBERT Encoder 125M 768 PLBART Encoder-Decoder 140M 768 CodeT5 Encoder-Decoder 220M 768 CodeGPT Decoder 124M 768 CodeGen Decoder 350M 1024 3.2 Evaluation Tasks We choose four currently prominent SE classification tasks: code vulner- ability detection (CVD), code clone detection (CCD), just-in-time software defect prediction (JIT), and function-docstring mismatch detection (FDMD). The first two tasks, code vulnerability detection and code clone detection, exclusively pertain to the source code. The latter two tasks, just-in-time soft- waredefectpredictionandfunction-docstringmismatchdetectioninvolveboth source code data and textual information like natural language annotations. These tasks are outlined briefly below. Code vulnerability detection is a method used to check and discover security vulnerabilities in software systems [39,40]. Its purpose is to identify8 YuZhaoetal. potential vulnerabilities in software code blocks that could be exploited by attackers. For instance, the CWE119 vulnerability type could allow for the execution of arbitrary code and access to sensitive information. This task has been a long-standing research focus in the SE field. In work related to vul- nerability detection based on deep learning, the input typically consists of a code snippet, and the output is a label indicating the presence or absence of a vulnerability [41,42]. Code clone detection involves measuring the semantic or structural similarity between two code snippets [43,44]. The code clone technique can enhanceefficiency,butitmayalsoinadvertentlyintroduceexternalvulnerabil- ities.Hence,codeclonedetectionishighlyessentialandcanhaveasubstantial impact on practice. This task also draws attention from researchers in the SE community. In prior related studies, the input typically consists of two code snippets,andtheoutputisalabelindicatingwhethertheyaresimilar[45,46]. Just-in-time software defect prediction aims to forecast whether a developer’scommits,madeduringsoftwaredevelopment,willpotentiallyintro- ducedefectsinthefuture[47,48].Thiscommit-leveldefectpredictionprovides a valuable tool for testers to prioritize their limited software quality assur- ance resources towards the highest-risk commits. As a highly time-effective testingaid,just-in-timesoftwaredefectpredictionhasgarneredsignificantat- tention from numerous researchers. In related works on just-in-time defect predictionbasedondeeplearning,theinputtypicallycomprisescodesnippets changed before and after a commit and the comments associated with that commit [30,49,50]. Function-docstringmismatchdetectionisemployedtoassesswhether thefunctionanditsassociateddocstringmatch.Intheengineeringpracticeof software development, developers are encouraged to provide descriptive natu- rallanguagedocumentationthatelucidatesthepurposeandusageoffunctions. This practice establishes a parallel corpus between code snippets and natu- ral language sentences [51]. Many researchers evaluate various SE application tasks on such corpora, including machine translation and code search. Aditya et al. [18] curated this data and devised a sentence pair classification task, where a function and its corresponding docstring are treated as distinct sen- tences.Thepositiveinstancerepresentsthecorrectfunction-docstringpairing, while the negative instance is a function-docstring pair whose docstring is re- placedbythatofanotherfunctionrandomlyselectedfromthedataset.Clearly, theinputforthistaskconsistsofcodesnippetsalongwiththeircorresponding natural language descriptions. We initiate our investigation of RQ1 by examining the first three tasks introducedearlier:codevulnerabilitydetection,codeclonedetection,andjust- in-time software defect prediction. Although the input of the JIT task is code snippets and commit messages, the JIT task can also be completed relying only on code data, while the FDMD task cannot be performed only on code data.Consequently,inourexplorationofRQ1,weconcentrateontaskswhere the input comprises solely code snippets, and when JIT tasks are used to studyRQ1weonlyinputcodesnippets.MovingontoRQ2,wedelveintotwoHowtogetbetterembeddingswithcodepre-trainedmodels?Anempiricalstudy 9 Table 2 CodeVulnerabilityDetectionDatasetStatistics Project Examples Vulnerableratio Language Devign 22361 45.02% C/C++ CWE119 39753 26.26% C/C++ CWE399 21885 33.29% C/C++ Table 3 CodeCloneDetectionDatasetStatistics Project Examples Clonetype Language BigCloneBench 1731860 Type-1,2,3,4 Java Table 4 Just-in-timeSoftwareDefectPredictionDatasetStatistics Project Changes Defectratio Language qt 95978 15.16% C++ openstack 66065 31.68% C++ platform 39365 37.74% Java gerrit 34610 8.64% Java go 61224 36.75% Golang Table 5 FunctionDocstringMismatchDetectionDatasetStatistics
Project Examples Mismatchratio Language ETH-Py150 260892 50.00% Python tasks:just-in-timesoftwaredefectpredictionandfunction-docstringmismatch detection, both of which require the simultaneous input of code snippets and their corresponding text information. 3.3 Experimental Datasets We gathered the dataset necessary for this paper from the open-source community. Thanks to the spirit of open sharing, we were able to readily acquire the datasets for the four classification tasks chosen for this paper. For the CVD task, we utilized three datasets: Devign, CWE119, and CWE399.Devign[52]consistsentirelyofreal-worldvulnerabilitycodes,metic- ulously compiled by Zhou et al. CWE119 and CWE399, collected by Li et al.[42],incorporatebothreal-worldandsyntheticexamples.Inthecaseofthe CCDtask,weconductedexperimentsonthewidelyrecognizedBigCloneBench dataset[53].ThisdatasetcontainsfourdifferenttypesofJavacodeclonesfrom Type-1 to Type-4 and is employed to ascertain whether two given Java code snippets share similar semantics. For the JIT task, we employed five datasets: openstack, qt, platform, gerrit, and go. These encompass three different pro- gramminglanguages:C++,Java,andGoLang.Thedataset,compiledbyZeng etal.[49],primarilycomprisesrecordsfromthesoftwaredevelopmentprocess.10 YuZhaoetal. It includes details of code changes, commit messages, and a label indicating whether the commit contains defects. In the case of the FDMD task, we re- lied on the dataset published by Aditya et al. [18], referred to as the ETH- Py150 dataset. This dataset predominantly features combinations of Python functions along with their corresponding correct or incorrect documentation strings. It serves as training material for a classifier aimed at distinguishing between correctly and incorrectly matched pairs. In summary, Tables 2-5 provide concise overviews of the datasets under scrutiny. It’s worth noting that these chosen datasets display diversity from multipleperspectives,includingprogramminglanguageanddatasetsize.This diversity serves to guard against unstable conclusions and ensures that the results we derive can be generalized across a broader spectrum of tasks and datasets. 3.4 Performance Metrics Given that this paper centers around SE-related classification tasks, we employ commonly used classification metrics from the field of machine learn- ing to assess task performance. While the tasks mentioned earlier have been evaluated by previous researchers using only one evaluation metric, such as Accuracy often being used in vulnerability detection [24,32], relying on only one single metric can potentially lead to biased conclusions [54]. Therefore, this paper opts for three evaluation metrics: Accuracy, F1-Score, and MCC. Accuracy, the simplest and most intuitive metric, gauges the proportion ofcorrectlyclassifiedinstancestothetotalnumberofinstances.Precisionand Recall correspond to the model’s ability to detect accurately and completely, respectively, but these two indicators are contradictory to each other. F1- Score, calculated as the harmonic mean of Precision and Recall, strikes a balance between these two factors, offering a comprehensive assessment of themodel’sperformance.MCC,ontheotherhand,takesintoaccountallfour possibleoutcomesinclassification:TP,TN,FN,andFP,presentingarelatively balanced metric. Formulas 1-5 are used to calculate these three metrics. TP +TN Accuracy= (1) TP +TN +FP +FN TP Precision= (2) TP +FP TP Recall= (3) TP +FN 2×Precision×Recall F1-Score= (4) Precision+Recall TP ×TN −FP ×FN MCC= (5) (TP +FP)(TP +FN)(TN +FP)(TN +FN)Howtogetbetterembeddingswithcodepre-trainedmodels?Anempiricalstudy 11 Among them, TP and TN represent correct predictions, signifying pos- itive samples being classified as positive and negative samples as negative, respectively. Conversely, FP and FN denote prediction errors, with FP indi- catingnegativesamplesbeingclassifiedaspositive,andFNindicatingpositive samples being classified as negative. 4 Experimental Methods and Results In this section, we first introduce the detailed methodological steps to explore the two research questions of this paper. We then present quantita- tive results on code embeddings derived from previously identified PTMs on several downstream classification tasks. Finally, based on the analysis of the experimental results, we address the two research questions that are the focus of this paper. 4.1 RQ1: Can the embedding obtained through a particular token sufficiently aggregate the semantic information of the entire code snippets? Fig. 1 Different ways to obtain code embeddings of PTMs with three architectures when performingclassificationtasks. Approach To address this question and ensure the generalizability of our conclusions, we examined five code PTMs encompassing all three dis- tinct architectures, as outlined in Table 1. These architectures include the encoder-only architecture, decoder-only architecture, and encoder-decoder ar- chitecture. Wefirstutilizethemethodcommonlyemployedbyresearchers[25,26,28, 29], as well as used when the PTM is released, to obtain the code embeddings12 YuZhaoetal. Table 6 Evaluation results on the test set of three downstream tasks, where F, L and A respectively represent the performance of the classifier built based on the code embedding obtainedbythefirstspecialtoken,thelastspecialtokenandtheaverage-poolingofallcode tokens.TheboldvalueindicatestheoptimalperformancevalueunderthesamePTM.
Tasks Datasets Metrics C FodeBE ART F Cod LeT5 A F PLB LART A C LodeGP AT C LodeGe An ACC 0.619 0.613 0.601 0.600 0.616 0.610 0.602 0.619 0.586 0.612 0.604 0.618 go F1 0.582 0.583 0.5420.583 0.573 0.566 0.558 0.581 0.561 0.581 0.561 0.574 MCC 0.259 0.255 0.212 0.246 0.246 0.233 0.217 0.257 0.206 0.250 0.230 0.249 ACC 0.654 0.665 0.612 0.629 0.663 0.659 0.647 0.669 0.617 0.647 0.611 0.661 platform F1 0.587 0.600 0.560 0.586 0.592 0.589 0.592 0.606 0.582 0.598 0.562 0.594 MCC 0.347 0.370 0.306 0.342 0.355 0.350 0.352 0.379 0.332 0.364 0.312 0.359 ACC 0.813 0.787 0.760 0.779 0.812 0.806 0.813 0.824 0.743 0.806 0.770 0.825 JIT gerrit F1 0.167 0.164 0.157 0.149 0.178 0.165 0.175 0.187 0.150 0.193 0.149 0.200 MCC 0.097 0.092 0.087 0.072 0.111 0.094 0.107 0.122 0.074 0.129 0.074 0.137 ACC 0.585 0.574 0.572 0.567 0.599 0.583 0.616 0.628 0.553 0.603 0.579 0.621 openstack F1 0.388 0.392 0.377 0.383 0.390 0.379 0.368 0.395 0.368 0.401 0.379 0.398 MCC 0.195 0.203 0.182 0.186 0.198 0.180 0.166 0.208 0.159 0.217 0.186 0.212 ACC 0.638 0.623 0.582 0.606 0.672 0.637 0.675 0.672 0.607 0.644 0.584 0.683 qt F1 0.337 0.335 0.3300.342 0.340 0.312 0.321 0.339 0.325 0.333 0.336 0.339 MCC 0.196 0.195 0.1940.210 0.200 0.156 0.17270.197 0.178 0.190 0.205 0.198 ACC 0.568 0.561 0.546 0.557 0.593 0.571 0.549 0.592 0.531 0.580 0.557 0.599 Devign F1 0.551 0.542 0.510 0.540 0.573 0.551 0.523 0.579 0.504 0.569 0.506 0.587 MCC 0.139 0.125 0.093 0.118 0.187 0.142 0.096 0.187 0.061 0.164 0.111 0.202 ACC 0.758 0.766 0.561 0.790 0.879 0.800 0.747 0.857 0.640 0.769 0.647 0.865 CVD CWE119 F1 0.720 0.736 0.600 0.740 0.826 0.735 0.678 0.817 0.605 0.705 0.660 0.820 MCC 0.542 0.569 0.298 0.578 0.737 0.579 0.478 0.707 0.325 0.523 0.437 0.716 ACC 0.704 0.742 0.6940.751 0.735 0.756 0.754 0.782 0.745 0.734 0.708 0.740 CWE399 F1 0.416 0.408 0.272 0.393 0.479 0.447 0.405 0.525 0.374 0.464 0.356 0.483 MCC 0.236 0.249 0.088 0.238 0.319 0.295 0.252 0.389 0.216 0.300 0.192 0.325 ACC 0.687 0.722 0.635 0.665 0.726 0.735 0.675 0.727 0.640 0.911 0.582 0.930 CCD BigCloneBench F1 0.403 0.427 0.376 0.395 0.449 0.427 0.379 0.455 0.355 0.730 0.346 0.778 MCC 0.310 0.343 0.286 0.308 0.378 0.337 0.277 0.388 0.244 0.692 0.248 0.747 [19,24,32]. This involves acquiring code embeddings through a specific token, asshowninsubfigures(a),(b)and(c)inFigure1.ForCodeBERT,weextract the embedding of the first token (known as [CLS]) from the final hidden layer of the model to serve as the aggregated semantic representation of the input code. Similarly, for CodeGen, we utilize the embedding of the last token from the final hidden layer as the aggregated semantic representation of the input code.InthecaseofCodeT5,duetoitsencoder-decoderarchitecture,boththe embeddingsofthefirstandlasttokensfromthefinalhiddenlayerofthemodel can aggregate the semantic representation of the input code. We then exclude these specific tokens, as illustrated in subfigure (d) in Figure 1, and adopt an alternate approach, which involves aggregating the vector representations of eachinputcodetoken.Wederivethesemanticrepresentationoftheinputcode by employing a straightforward method of average-pooling the embeddings of all code tokens. Basedontheobtainedaggregatedsemanticembeddingsoftheinputcode snippets, we construct and train a simple fully connected layer for classifica- tion. We compare the performance of the classifier to determine whether the methodofusingspecialtokenscaneffectivelyaggregatethesemanticinforma- tion of the entire code snippet. To mitigate performance biases resulting from experimental randomness, we conducted the experiment 50 times and then averaged the performance metrics. To ensure the significance of experimental performance, we subjected the performance value distribution to statistical testing using the Wilcoxon Signed Rank Test method [55]. Results Table 6 displays the performance of three indicators on three downstream SE classification tasks for five code PTMs with three differentHowtogetbetterembeddingswithcodepre-trainedmodels?Anempiricalstudy 13 Table 7 Statistical test results of the performance of classifiers built based on code em- beddingsobtainedindifferentways,whereF&Arepresentstheperformancecomparisonof the first special token and the average-pooling of all code tokens. L&A is similar. % rep- resents the performance improvement percentage of the average-pooling of all code tokens relativetoothermethods,andprepresentsthep-valueofthesignificancetest.#represents
p ≥ 0.05, * represents p < 0.05, ** represents p < 0.01, *** represents p < 0.001. Bold valuesrepresentthemaximumperformanceimprovementratioforeachrow. Tasks Datasets Metrics Cod Fe &B AERT F&ACodeT5 L&A F&APLBART L&A Co Ld &eG APT Co Ld &eG Aen % p % p % p % p % p % p % p ACC -0.90 # 2.61 *** 2.73 *** 1.59 *** 2.89 *** 4.50 *** 2.26 *** go F1 0.19 # 5.68 *** -1.75 *** 2.58 *** 4.12 *** 3.53 *** 2.35 * MCC -1.50 # 15.99 *** 0.24 # 10.30 ***18.32*** 21.69 *** 8.07 *** ACC 1.62 ** 8.38 *** 5.40 *** 1.53 *** 3.52 *** 4.94 *** 8.17 *** platform F1 2.23 *** 5.69 *** 1.01 *** 2.83 *** 2.35 *** 2.78 *** 5.84 *** MCC 6.59 *** 15.97 *** 3.85 *** 8.28 *** 7.48 *** 9.50 *** 14.80 ** ACC -3.12 *** 6.89 *** 4.30 *** 2.26 *** 1.35 *** 8.52 *** 7.16 *** JIT gerrit F1 -2.09 # 13.37 ***19.99*** 13.33 *** 7.00 *** 28.07 *** 34.00 *** MCC -4.43 # 27.52 ***53.17*** 28.96 ***14.02*** 72.86 *** 84.45 *** ACC -1.91 * 4.68 * 5.58 *** 7.66 *** 2.00 ** 9.07 *** 7.32 *** openstack F1 1.16 ** 3.47 *** 1.93 *** 4.13 *** 7.24 *** 9.07 *** 4.98 *** MCC 4.36 *** 8.81 *** 6.60 *** 15.43 ***25.00*** 36.52 *** 13.96 *** ACC -2.29 * 15.44 ***10.76*** 5.46 *** -0.49 # 6.05 *** 16.93 *** qt F1 -0.44 # 3.12 *** -0.61 * 8.58 *** 5.38 *** 2.58 *** 1.13 *** MCC -0.51 *** 2.88 # -4.76 *** 25.69***14.19*** 6.44 *** -3.50 *** ACC -1.25 *** 8.68 *** 6.44 *** 3.75 *** 7.86 *** 9.23 *** 7.52 *** Devign F1 -1.70 # 12.16 *** 6.09 *** 5.06 ***10.67*** 13.03 *** 15.84 *** MCC -10.04 *** 100.97 ***58.33*** 31.51 ***93.60*** 168.57*** 81.00 *** ACC 1.09 # 56.75 ***11.23*** 7.13 ***14.71*** 20.02 *** 33.83 *** CVD CWE119 F1 2.17 # 37.65 ***11.63*** 11.22 ***20.60*** 16.52 *** 24.16 *** MCC 4.86 # 147.08***27.56*** 22.16 ***48.02*** 61.01 *** 63.94 *** ACC 5.45 *** 5.89 *** -2.05 *** 3.48 *** 3.81 *** -1.46 ** 4.59 *** CWE399 F1 -1.92 # 75.84 ***22.06*** 17.36 ***29.42*** 24.09 *** 35.55 *** MCC 5.24 # 262.36***33.78*** 31.72 ***54.14*** 39.03 *** 69.32 *** ACC 5.15 ** 14.26 *** 9.15 *** -1.10 ** 7.64 *** 42.26 *** 59.75 *** CCD BigCloneBench F1 5.89 *** 19.53 ***13.75*** 6.40 ***19.94*** 105.55 *** 125.09*** MCC 9.54 *** 32.48 ***22.74*** 14.92 ***39.94*** 183.63 *** 200.36*** architectures using code embeddings obtained in different ways. The bolded valuesrepresentthebestperformancevaluesobtainedusingdifferentmethods to obtain code embedding under the same code PTM. Table 7 shows the p- value of the significance test between the performance of the same code PTM using code embedding obtained in different ways, as well as the percentage improvement in three indicators using the average-pooling method to get the embedding. Figure 2 visualizes the percentage improvements from Table 7 for a clearer comparative observation. Regardless of the architecture of the code PTMs, embeddings obtained through a specific token do not sufficiently aggregate the semantic information of the entire code snippet. Instead, focusing on the vector representation of each code token, such as through a simple average pooling of all code tokens, leads to more enriched code embeddings with richer semantic information. In Table 6, out of a total of 27 records across the three metrics on nine datasets for three classification tasks, CodeBERT achieved the best performance 14 times when obtaining code embeddings through average-pooling of all code tokens, while aggregate embeddings using the first special token yielded the best perfor- mance 13 times. Considering the significance test results from Table 7, it can be observed that average-pooling of all code tokens led to significantly better performance in 9 cases, whereas the special token approach only resulted in significantlybetterperformance4times.Intheremaining14experiments,the14 YuZhaoetal. two methods of obtaining code embeddings can be considered equivalent. For PLBART, CodeGPT, and CodeGen, embeddings obtained through average- pooling demonstrated significantly better performance in 26 cases, while spe- cial token embeddings only outperformed once. In the case of PLBART, em- beddings obtained through the last special token consistently performed the worst. For CodeT5, embeddings obtained through the last special token only outperformed four times, while those obtained through the first special token
consistently performed the worst. On the other hand, embeddings obtained through average-pooling showed significantly better performance in 22 cases. This indicates that code PTMs differ from models used in the NLP field. The common NLP approach of obtaining embeddings through special tokens does not effectively aggregate the semantic information of code snippets. Instead, employing a straightforward method like average-pooling across all code to- kens results in higher-quality code embeddings, consequently enhancing the performance of SE classification tasks. Thequalityofcodeembeddingsobtainedthroughdifferentmeth- odsofPTMsisinfluencedbythecodedataofdownstreamclassifica- tiontasks.IfthePTMincludestheprogramminglanguageofthedownstream task during its pre-training, then the quality of the semantic embeddings ob- tained by aggregating the vector representations of all code tokens is higher. Ifthislanguageisnotincluded,thenthequalityofcodeembeddingsobtained throughspecialtokensandthoseobtainedbyaggregatingthevectorrepresen- tations of all code tokens is similar. Taking the CVD task and CCD task as examples, the codes of the three datasets of the CVD task are composed of C/C++language,andthedatasetoftheCCDtaskiswritteninJavalanguage. Theencoder-onlyarchitectureofCodeBERT,duringpre-training,includessix programming languages: Python, Java, JavaScript, PHP, Ruby, and Golang, but does not include C and C++. Therefore, we observe that CodeBERT exhibits a comprehensive and significant advantage in code clone detection tasks when classifiers are constructed based on embeddings obtained through average-poolingofallcodetokens,comparedtoembeddingsobtainedthrough special tokens. In the code vulnerability detection task, embeddings obtained byaverage-poolingofallcodetokensonlydemonstrateasignificantadvantage in the Accuracy of CWE399, while showing a significant disadvantage in the MCC of Devign. In the remaining code vulnerability detection datasets and metrics,codeembeddingsobtainedthroughaverage-poolingofallcodetokens do not exhibit a significant difference in quality compared to those obtained with special tokens. For code PTMs like CodeT5 and CodeGen, these models use C and C++ languages during pre-training. Consequently, the semantic embeddings acquired by averaging pooling of all code tokens contain richer information, resulting in better model performance for classifiers constructed based on these embeddings. Aggregating the vector representations of all code tokens to ob- tain semantic embeddings is more effective for PTMs of encoder- decoder and decoder-only architectures, while PTMs of decoder- only architecture benefit the most. As shown in Table 7 and FigureHowtogetbetterembeddingswithcodepre-trainedmodels?Anempiricalstudy 15 Fig.2 Illustrationoftheperformanceimprovementpercentageoftheclassifierconstructed basedonthecodeembeddingsobtainedbytheaverage-poolingofallcodetokenscompared tothespecialtoken. 2, for the encoder-only architecture of CodeBERT, compared to embeddings obtained through special tokens, the performance improvement of classifiers constructed based on embeddings obtained through average-pooling is within 10% across all three metrics. In contrast, for PTMs with encoder-decoder and decoder-only architectures, classifiers constructed based on embeddings obtained through average-pooling generally exhibit higher performance im- provements across all three metrics. Among all the experimental records, the experimental records with higher performance improvement ratios all appear in the PTMs of encoder-decoder architecture and the decoder-only architec- ture, and some performance improvement ratios even reach more than 200%. Forinstance,ontheCWE399datasetinthecodevulnerabilitydetectiontask, the classifier constructed based on CodeT5’s embeddings obtained through average-pooling shows a 262.36% improvement in the MCC metric compared to the classifier constructed based on embeddings obtained through the first specialtoken.Similarly,ontheBigCloneBenchdatasetinthecodeclonedetec- tion task, the classifier constructed based on CodeGen’s embeddings obtained through average-pooling exhibits a 200.36% improvement in the MCC metric comparedtotheclassifierconstructedbasedonembeddingsobtainedthrough the last special token. However, among the 27 records, there are 16 records where CodeGPT and CodeGen of the decoder-only architecture achieved the highest performance improvement ratio, among which CodeGPT and Code- Gen each achieved the highest performance improvement ratio 8 times. The remaining11recordsarethehighestperformanceimprovementratiosachieved by the encoder-decoder architecture CodeT5 and PLBART, of which CodeT5 contributed 9 times and PLBART contributed 2 times. Therefore, while all16 YuZhaoetal. three architecture types of PTMs benefit from aggregating the vector rep- resentations of all code tokens to obtain semantic embeddings, the encoder- decoder and decoder-only architectures gain more, with decoder-only archi- tectures benefiting the most significantly. By utilizing the aggregation of vector representations from all code tokens to obtain semantic embeddings, code PTMs of the decoder-only architecture can achieve embeddings that are equally rich in semantic information as those obtained from the encoder- only or encoder-decoder architecture, and in some cases, even of higher quality. Currently, researchers tend to prefer using encoder-only ar- chitecture code PTM rather than decoder-only architecture for generating embeddings when working on SE classification tasks. This preference may stem from previous experiences where embeddings obtained using the spe-
cial token method in decoder-only architecture PTMs did not encapsulate as rich semantic information as those obtained from encoder-only and encoder- decoderarchitectures.Forinstance,asshowninTable6,classifiersconstructed based on code embeddings derived from CodeBERT using the special to- ken method outperformed other PTMs across most tasks and metrics. Even the larger-scale decoder-only architecture PTMs did not yield higher-quality embeddings, as seen in the case of CodeGen. However, when we adopt the strategy of average-pooling the embeddings of all code tokens, the scenario changes. Classifiers built on embeddings generated by decoder-only archi- tecture PTMs can outperform those built on encoder-only architecture and encoder-decoderarchitecture.Moreover,thisadvantagemaypotentiallywiden with the increase in model scale. For instance, in the task of code clone de- tection, classifiers constructed using the average-pooling embeddings of all codetokensfromCodeGPTandCodeGenoutperformCodeBERT,PLBART, and CodeT5 across all metrics. This illustrates that semantic embeddings ob- tained through the aggregation of vector representations from all code tokens allowthedecoder-onlyarchitecturePTMstoacquirecodeembeddingsthatare equally rich in semantic information as those obtained from the encoder-only or encoder-decoder architecture and even better. The fundamental reason be- hindthisisthatbothdecoder-onlyandencoder-olyarchitecturePTMsemploy the same self-attention layer to encode word tokens, endowing them with the capabilitytogeneratesemanticembeddingsfortext.Consideringthatdecoder- onlyarchitecturePTMshavebecomethecurrentmainstream,withincreasing scales [8,56], we recommend researchers use decoder-only architecture code PTMs for generating embeddings of code snippets. DiscussionBycomparingtheperformanceofclassifiersconstructedbased on code embeddings obtained through different methods, we confirm that ag- gregating vector representations of all code tokens leads to embeddings with richer semantic information compared to using special tokens across all three architectures of code PTMs. One possible explanation for this phenomenon is that the method of obtaining code embeddings through special tokens fails to effectively distinguish the classification boundaries of the dataset, while em- beddingsobtainedbyaggregatingvectorrepresentationsofallcodetokensareHowtogetbetterembeddingswithcodepre-trainedmodels?Anempiricalstudy 17 (a) CodeBERT (b) CodeT5 (c) CodeGen Fig. 3 Negative dot product values between code embeddings of different categories in eight projects obtained using special tokens or average-pooling all code tokens of three different architecture PTMs. Among them, subfigures (a), (b) and (c) represent encoder- onlyCodeBERT,encoder-decoderCodeT5anddecoder-onlyCodeGenrespectively.18 YuZhaoetal. of higher quality and can effectively discern the boundaries between different categories. To investigate further, we employ the previous two different methods to obtain code embeddings for different categories of data in the test dataset andcalculatethedistancesbetweencodeembeddingsofdifferentcategoriesin the test set. Figure 3 displays the negative dot product values between code embeddings of different categories in the test set obtained using two different methods for three different architecture PTMs (namely CodeBERT, CodeT5, andCodeGen).Thismetricisusedtomeasurethesimilaritybetweendifferent embeddings, with smaller negative dot product values indicating closer distri- bution. We observe that the negative dot product values between code em- beddingsofdifferentcategoriesinthetestsetobtainedthroughspecialtokens are smaller, implying that the embeddings obtained through special tokens for different categories exhibit similar distributions. On the other hand, the negative dot product values between code embeddings of different categories in the test set obtained through aggregating vector representations of all code tokens, i.e., average-pooling, are relatively larger. This suggests that the code embedding obtained by average-pooling of all code tokens maps different cat- egories of data into the same high-dimensional space that is far away, while the code embedding obtained by special tokens cannot effectively distinguish samples of different categories. Aggregating vector representations of all code tokens, such as simple average-pooling, results in more semantically informative code embeddings on code PTMs of all three architectures compared to embeddings aggregated by a particular token. Among them, the encoder-only architecture of PTMs benefits the least, followed by the encoder-decoder architecture, while the decoder-only architecture benefits the most. 4.2 RQ2: How do the way code and text are combined affect the quality of semantic embeddings generated by code pre-trained models? ApproachToaddressthisquestion,weconductastudyonsixdatasetsof twoSEclassificationtasks,asshowninTables4and5.Thesetwoclassification tasks involve both code and text data as inputs. In the JIT task, the text information serves as auxiliary data, meaning that the JIT task can still be performed without this text information. On the other hand, for the FDMD task, both the text and code information are equally crucial, and both are requiredtocompletethetask.SimilartoRQ1,wealsoinvestigateallfivecode PTMs with three different architectures, as presented in Table 1. The three different architecture code PTMs have variances in how they combine code data and corresponding text data during pre-training. For the encoder-onlymodelCodeBERTand the encoder-decodermodelsCodeT5and PLBART, they adopt a pairing approach during pre-training for code data withaccompanyingtextinformation.ThismeansthatcodeandtextareinputHowtogetbetterembeddingswithcodepre-trainedmodels?Anempiricalstudy 19
Fig. 4 Three ways of combining code and text into PTMs to obtain embeddings when performingclassificationtasks.Amongthem,subfigures(a),(b)and(c)representbimodal input,concatenatedinputandunimodalinputrespectively. together with a special token acting as a delimiter, referred to as a ”bimodal input”. Additionally, they also support inputting code without paired natural languagetext,andviceversa,knownasa”unimodalinput”[19,24].Therefore, codedatawithaccompanyingtextinformationcanbeinputseparatelyascode andtext,andthenintegratedafterobtainingembeddings.Forthedecoder-only models CodeGPT and CodeGen, there is no special treatment for code data withaccompanyingtextduringpre-training.Instead,thesedataareuniformly inputtedintothemodelandexhibitaninterleavedpatternofnaturallanguage andprogramminglanguage,referredtoasa”concatenatedinput”[33].Figure 4illustratesthethreedifferentwaysofcombiningcodedataandcorresponding text information. We apply all three combination methods as inputs to each PTM of all architecture to obtain different embeddings. Since the experimental results of RQ1 show that embeddings obtained by aggregating the vector representations of all code tokens contain richer semanticinformation,similartoRQ1,weexcludesomespecialtokensanduse a simple average-pooling method to obtain embeddings. To ensure an equal amount of input information, we control the lengths of both code and text to be the same. Based on the obtained embeddings, we construct and train a simplefullyconnectedlayerforclassification.Weanalyzehowthecombination ofcodeandtextinfluencesthequalityofgeneratedembeddingsbycomparing the performance of the classifiers. Similar to the process in RQ1, in order to reduce performance bias caused by experimental randomness, we conduct 50 experiments and then take the average values of the performance metrics. Additionally,toensurethevariabilitybetweenexperimentalperformances,we20 YuZhaoetal. Table 8 Evaluation results on the test sets of two downstream tasks, where C, B and U represent the performance of the classifier built based on the embeddings obtained from the code information and text information of the concatenated input, bimodal input and unimodalinput,respectively.Boldvaluesrepresentthebestperformancevaluesforthesame PTM. Tasks Datasets Metrics CCode BBERT U C Cod BeT5 U CPLB BART U CCode BGPT U CCod BeGen U ACC 0.6180.6190.6390.6200.6230.6370.6260.6260.6390.6240.6270.6500.6270.6360.645 go F1 0.5800.5840.5960.5780.5760.5840.5850.5870.5940.5820.5840.6030.5780.5870.597 MCC 0.2570.2620.2920.2550.2550.2780.2680.2690.2880.2620.2670.3070.2610.2790.297 ACC 0.6440.6430.6620.6390.6360.6550.6410.6430.6570.6240.6290.6320.6500.6550.674 platform F1 0.5820.5830.5870.5780.5790.5830.5800.5840.568 0.5870.5880.5860.5880.5920.574 MCC 0.3380.3400.3500.3280.3290.3420.3310.3380.320 0.3410.3450.3410.3470.3550.337 ACC 0.7950.7960.8090.8080.8050.8160.8120.8030.8220.8000.8050.8160.8260.8210.838 JIT gerrit F1 0.1730.1720.1800.2010.1900.192 0.1920.1960.187 0.1990.2050.1970.2150.2170.208 MCC 0.1050.1030.1140.1410.1270.128 0.1290.1340.122 0.1380.1450.1350.1560.1590.147 ACC 0.5880.6000.6000.6210.6110.6300.6300.6300.6430.6140.6200.6210.6250.6230.640 openstack F1 0.3930.3940.3930.4020.4010.397 0.4040.4060.393 0.4010.4040.3980.3980.4070.405 MCC 0.2040.2050.2040.2180.2170.213 0.2220.2240.206 0.2160.2210.2120.2130.2260.224 ACC 0.6310.6290.6460.6720.6790.6960.6940.6950.7150.6680.6700.7060.7030.6980.716 qt F1 0.3260.3270.323 0.3290.3330.3260.3300.3230.3080.3290.3250.3260.3420.3450.337 MCC 0.1790.1810.175 0.1830.1890.1810.1860.1750.1610.1830.1780.1820.2020.2070.197 ACC 0.8610.8590.8710.8360.8380.725 0.7260.8680.737 0.6730.6830.6970.8160.8280.921 FDMDETH-Py150 F1 0.8600.8570.8700.8340.8370.725 0.7240.8670.732 0.6670.6800.6970.8140.8280.920 MCC 0.7250.7220.7460.6730.6770.453 0.4540.7360.477 0.3480.3670.3960.6330.6580.843 also use the Wilcoxon Signed Rank Test to perform a significance test on the data distribution of performance values. ResultsTable8illustratestheperformanceofclassifiersconstructedfrom embeddingsobtainedthroughvariouscombinationmethodsofinputcodeand textdataforfivecodePTMsacrosstwodownstreamclassificationtasks,span- ning three different architecture models. Bolded values indicate the best per- formance achieved using different combination methods for the same code PTM. Table 9 showcases the p-values from significance tests comparing the performancedistributionsofclassifiersconstructedfromembeddingsobtained through different combination methods of input code and text for the same code PTM. Inputtingdataaccordingtohowcodeandtextinformationwere combined during pre-training of the code PTMs can not guarantee the acquisition of code embeddings with richer semantic informa- tion. For the encoder-only architecture CodeBERT, bimodal input is used to
inputcodedataandcorrespondingtextinformationduringpre-training.How- ever,amongthe18recordsshowninTable8,wefoundthatthebimodalinput approach on the CodeBERT model only achieved the best performance four times.Yet,thesignificancetestresultsinTable9indicatethatthesefourbest performance values are not significantly different from the concatenated in- put approach. This means that for the encoder-only architecture CodeBERT, bimodal input of code and text information in the way it is pre-trained will result in poor code embedding quality. Similarly, for the decoder-only archi- tecture models CodeGPT and CodeGen, following their pre-training method ofconcatenatedinputofcodeandtextinformationdidnotyieldthebestper- formance.TheembeddingsobtainedfromtheCodeGenmodeldidnotachieve the best performance once, and the embeddings from the CodeGPT model only achieved the best performance twice. However, these two instances ofHowtogetbetterembeddingswithcodepre-trainedmodels?Anempiricalstudy 21 Table 9 Statisticaltestresultsoftheperformanceofclassifiersbuiltbasedonembeddings obtainedindifferentwaysofinputtingcodeandtext,whereC&Brepresentstheperformance comparisonoftheconcatenatedinputandbimodalinput.C&UandB&Uarealsosimilar. Among them, # represents p ≥ 0.05, * represents p < 0.05, ** represents p < 0.01, *** representsp<0.001. Tasks Datasets MetricsC&C Bod Ce &B UER BT &UC&BC Cod &e UT5 B&UC&BPL CB &A URT B&UC&C Bo Cd &eG UP BT &UC&BCo Cd &eG Ue Bn &U ACC # *** *** # *** *** # *** *** * *** *** *** *** *** go F1 # *** *** # * ** # *** *** # *** *** *** *** *** MCC * *** *** # *** *** # *** *** # *** *** *** *** *** ACC # *** *** # *** *** # *** *** # ** # * *** *** platform F1 # ** # # * * * *** *** # # # # *** *** MCC # *** ** # *** *** * ** *** # # # * ** *** ACC # ** * # # ** * * *** * *** *** # ** *** JIT gerrit F1 # *** *** *** *** # # * ** ** # ** # *** *** MCC # *** *** *** *** # # * *** * # ** # *** *** ACC # # # # # ** # *** *** # # # # * *** openstack F1 # # # # ** * # *** *** * * *** *** *** # MCC # # # # * # # *** *** * # *** *** *** # ACC # # * # *** ** # *** *** # *** *** # ** *** qt F1 # # ** ** # *** *** *** *** ** # # ** ** *** MCC # # ** ** # *** *** *** *** ** # # ** * *** ACC # *** *** *** *** *** *** *** *** *** *** *** *** *** *** FDMDETH-Py150 F1 # *** *** *** *** *** *** ** *** *** *** *** *** *** *** MCC # *** *** *** *** *** *** *** *** *** *** *** *** *** *** best performance values were not significantly superior to the unimodal input approach.Fortheencoder-decoderarchitecturemodelsCodeT5andPLBART, utilizingthebimodalinputapproachaspertheirpre-trainingmethodtoinput codedataandcorrespondingtextinformationalsodidnotyieldadominantly significant advantage in the quality of the obtained embeddings. Among the 18 records, the bimodal input approach obtained the best performance em- beddings from the CodeT5 model only five times. While the PLBART model achieved the best performance nine times, Table 9 shows that four of these performance values were not significantly different from the concatenated ap- proach. Similarly, only five instances of the best performance values were sig- nificantly superior. This implies that the proportion of classifiers constructed fromembeddingsobtainedbyinputtingcodeinformationandtextinformation in a bimodal way from these two models that achieved the best performance is less than 30%. Therefore, regardless of the architecture of the code PTMs, inputting data according to how code and text information were combined during pre-training cannot guarantee obtaining code embeddings with richer semantic information. Regardless of the architecture of the code PTMs, employing the unimodal input approach for code and text information proves to be acompetitivemethodforobtaininghigher-qualitycodeembeddings. The bimodal input approach comes next in effectiveness, while the concatenated input approach yields code embeddings with the least amount of semantic information. Among the 18 records shown in Table 8, the performance of the classifier built by code embedding obtained by con- catenating the input on the five PTMs of the three architectures is generally low.Specifically,onCodeBERTandCodeGen,theconcatenatedapproachdid not achieve the best performance for code embeddings once. On CodeT5 and PLBART, it only achieved the best performance twice, and on CodeGPT, it22 YuZhaoetal. achievedthebestperformancetwicebutwithoutsignificance.ForCodeBERT intheencoder-onlyarchitecture,theunimodalinputapproachachievedsignifi- cantlysuperiorperformancevalues11times,whilethebimodalinputapproach did not achieve it even once. In the case of the encoder-decoder architecture of CodeT5 and PLBART, the unimodal input approach achieved significantly superior performance values seven times, while the bimodal input approach achieveditfivetimes.Inthedecoder-onlyarchitectureofCodeGPTandCode-
Gen,theunimodalinputapproachrespectivelyachievedsignificantlysuperior performance values eight and ten times, while the bimodal input approach achieved it four and three times. Therefore, irrespective of the architecture of the pre-trained model, employing the unimodal input approach allows for the fullutilizationofbothcodeandtextinformation,resultingincodeembeddings that encapsulate richer semantic information. DiscussionWedemonstratethatobtainingembeddingsaccordingtothe way of inputting both code and text information during the pretraining of the PTMs results in lower-quality embeddings. In contrast, using unimodal input of code information and text information proves to be a competitive way to acquire higher-quality code embeddings. One possible reason is that employing bimodal input of both code and text, or concatenation, increases theinputlength.ThisleadstothePTMsnotfocusingoneachindividualcode tokenitselfwhengeneratingcodeembeddings,butratherdispersingattention to other tokens. To illustrate this phenomenon, we analyze the model’s attention towards each input token itself during embedding generation. As our embeddings are derivedfromtheoutputofthelastlayer’shiddenstates,wecapturetheatten- tionofallattentionheadsinthefinallayerofthetransformer.Figure5displays the average attention scores of all attention heads towards each input token itself when generating code embeddings using three different combinations of codeandtextforthreedifferentarchitecturecodePTMs(namely,CodeBERT, CodeT5, and CodeGen). We observe that for unimodal input data, almost all attentionheadsofthethreearchitecturePTMsshowhigheraverageattention scores towards each input token itself compared to bimodal input or concate- nated input. This suggests that each token in unimodal input data garners increased attention from the model which means a richer embedded syntactic and semantic content, facilitating the final classifier in learning patterns spe- cific to the corresponding classification task [57,58]. On the other hand, with bimodalorconcatenatedinput,duetothelongerinputlength,themodelpays attentionnotonlytoeachtokenitselfbutalsotomoredistantcontexttokens. However, these distant context tokens may not contribute semantically to the token itself that requires attention, resulting in relatively lower quality of the generated embeddings. No matter which architecture of the code PTMs is used, the quality of code embedding obtained by inputting data according to the way of inputting code and text information during pre-training tends to be subpar. This method cannot guarantee obtaining code embeddings with richer semantic information. On the other hand,Howtogetbetterembeddingswithcodepre-trainedmodels?Anempiricalstudy 23 (a) CodeBERT (b) CodeT5 (c) CodeGen Fig. 5 Average attention scores of all attention heads on each input token itself using three different combinations of code and text of three different architecture code PTMs. Among them, subfigures (a), (b) and (c) represent encoder-only CodeBERT, encoder- decoderCodeT5anddecoder-onlyCodeGenrespectively.24 YuZhaoetal. the unimodal input of code information and text information proves to be a competitive approach for obtaining higher-quality code em- beddings. 5 Implications In this section, based on the experimental results of our above study, the following implications are drawn to guide researchers in further research. Implication 1) When researchers generate code embeddings for code snippets of classification tasks using code PTMs, it is advisable to aggregate vector representations of all code tokens to obtain the embeddings, rather than using the special token method commonly employedintheNLPfield. Inthispaper’sexperimentalresultsofRQ1,we observed that classifiers constructed based on embeddings obtained through averagingthepoolingofallcodetokensoutperformthosebuiltonembeddings obtained through special tokens in most cases. This trend holds on five PTMs of three different architectures across three distinct classification tasks. The performance improvement is evident across various metrics. This means that generating code embeddings should focus on all code tokens, rather than re- lying on empirical knowledge in the NLP domain. In addition, just a simple average-poolingofallcodetokenscanproduceembeddingsthatcontainricher semantic information. Therefore, focusing on all code tokens to obtain code embeddings is more in line with the data characteristics of SE classification task scenarios. Implication 2) Researchers should use decoder-only architec- ture code PTMs for generating embeddings of code snippets when dealing with classification tasks. In the experimental results of RQ1, we also observed that when using special tokens to obtain embeddings, the em- beddings generated by decoder architecture code PTMs do not surpass the classicalencoder-onlyCodeBERT.Thisistrueevenfordecoder-onlyarchitec- ture PTMs with larger parameters. However, by leveraging the aggregation of vector representations from all code tokens to obtain semantic embeddings, codePTMsofthedecoder-onlyarchitecturecanachievesemanticembeddings that are equally rich or even of higher quality compared to those obtained from encoder-only or encoder-decoder architectures. Given that decoder-only architecture PTMs have become the prevailing mainstream and are continu- allyexpandinginparametersize,wefurtherrecommendresearcherstoemploy decoder-onlyarchitecturecodePTMsforgeneratingembeddingsofcodesnip- pets. Implication3)ResearchersusingcodePTMsforgeneratingcode embeddings when processing classification tasks with code and text information should opt for unimodal input of code information and text information, followed by aggregation of these two parts to ob- tain higher-quality embeddings. In the experimental results of RQ2 in
thisarticle,weobservedthatinputtingdatainthesamewayascodeandtextHowtogetbetterembeddingswithcodepre-trainedmodels?Anempiricalstudy 25 information during pre-training does not guarantee a code embedding with richer semantic information. However, the unimodal input method performs moreprominently.Thismeansthatbothcodedataandtextdatacontainrich information. Connecting code and text will make the model focus too long and easily miss key information. The unimodal input enables the model to capture key information, and the generated embeddings contain pattern in- formation of code and text respectively, which helps train the model for SE classification tasks. Therefore, when utilizing code PTMs to generate embed- dings, we recommend unimodal input code and text, separately embedding and subsequently fusing them. 6 Threats to Validity Although the experiments in this study demonstrate the sufficiency and effectivenessofourconclusions,thebroadervalidityofthesefindingsmaystill besubjecttocertainthreats.Thissectiondiscussesinternalthreats,construct threats and external threats to the validity of our work. 6.1 Internal Validity Internal validity pertains to potential threats posed by objective factors to the conclusions of the experiments. The first concern is the dataset used forexploratoryexperiments.Forbothresearchquestionsinthispaper,weuti- lized datasets that have been widely adopted by previous researchers. These datasets are publicly available and have undergone no tampering. Moreover, they stem from various projects and encompass different programming lan- guages. The complexity and diversity of these datasets are sufficient to mit- igate the related threats they might pose to the experimental conclusions. Furthermore, even though some research within their respective domains may rely solely on one or two evaluation metrics [50,59], we evaluate all classifica- tion tasks with three metrics. To ensure a comprehensive assessment of task performanceandtoeliminateanythreatthechoiceofevaluationmetricmight pose to the experimental conclusions, we calculated the averages of Accuracy, F1, and MCC across 50 experiments for all tasks. Additionally, we performed statistical tests to guarantee a thorough and unbiased evaluation. 6.2 Construct Validity Constructvaliditypertainstopotentialthreatsposedbytheexperimental setup and procedures on the conclusions of the experiments. Since this paper primarily focuses on code embeddings, for classification tasks, we employ the same fully connected layer for classification across different embeddings. The performance of this classifier is used to gauge the quality of code embeddings. To mitigate any potential impact of data preprocessing on task performance,26 YuZhaoetal. wefollowcommonpracticesinthetaskdomain[18,38,50].Thisinvolvesusing source code data and text data as inputs to obtain the corresponding em- beddings, without the need for intricate preprocessing, as our goal is not to enhance the performance of downstream tasks. Additionally, we ensure that each task inputs code data and text data of the same length into different models, to guarantee that the richness of semantic information in the embed- dings will not be affected by variations in input information volume. Finally, in the process of obtaining code embeddings using each pre-trained model, we make every effort to utilize previously open-sourced code to ensure correct- ness. However, the possibility of manual errors still exists. We make all data and code used in the experiments publicly available and deposit them into an open-source repository to ensure the replicability of the experiments and promote future research. We hope to engage researchers in related fields and continue to integrate more in-depth studies. 6.3 External Validity External validity pertains to factors affecting the generalizability of our conclusions. The experimental findings in this paper are derived from using five code PTMs that generate code embeddings across four SE classification tasks. However, we still cannot guarantee that these experimental conclusions can be extrapolated to all SE classification tasks and other code PTMs. In terms of generating embeddings, we utilize code PTMs covering all three dif- ferent architectures, making the conclusions valid for different architectures. For code PTMs, we employ popular models belonging to these three differ- ent architectures: CodeBERT, CodeT5, PLBART, CodeGPT, and CodeGen. These five models generate embeddings of varying scales. However, with the rising popularity of PTMs, future research should also consider more types of embeddings, such as GraphCodeBERT [21] and LLaMA [56]. The former em- ploysrichercodestructuralinformationtogenerateembeddings,whilethelat- ter is an extremely large-scale universal language model. Regarding SE tasks, this paper selects four classification tasks that involve different input content and programming languages. Nevertheless, exploring more SE classification tasks would further enrich our conclusions. Furthermore, recent studies indi- cate that different computing devices may affect task performance [60]. All experiments in this paper are conducted on a consumer-grade NVIDIA GTX 2080Ti GPU. However, we believe that conducting experiments on the same computingdeviceshouldyieldconclusionssimilartoours.Sincewedonoten- gageinanyadjustmentstotheembeddingsthroughouttheentireexperiment, different computing devices only affect the speed of the experiment, not the experimental conclusions.Howtogetbetterembeddingswithcodepre-trainedmodels?Anempiricalstudy 27 7 Conclusion In this paper, we conduct a systematic study on how to generate higher- qualitycodeembeddingsonfourcodeunderstandingtasksusingatotaloffive codePTMswiththreedifferentarchitectures.Specifically,westudiedwhether two commonly used methods for obtaining code embeddings by researchers
in the current SE field are effective. Our experimental results show that the method commonly used by researchers to obtain code embeddings through specialtokensisnotsuitableforcodeclassificationtasks,anditisalsodifficult to obtain high-quality embeddings by inputting code information and text informationaccordingtothecombinationofcodeandtextduringpre-training ofthepre-trainedmodel.WerecommendthatSEresearchersandpractitioners payattentiontoallcodetokensoftheinputdatawhengeneratingembeddings forcodesnippetsandunimodallyinputcodeinformationandtextinformation to obtain semantically richer embeddings for downstream tasks. Our findings provideguidancefortheSEfieldonhowtousecodePTMstogeneratebetter embeddings as well as clues for future research on reusing code PTMs. References 1. J. K. Siow, S. Liu, X. Xie, G. Meng, and Y. Liu, “Learning program semantics with coderepresentations:Anempiricalstudy,”in2022 IEEE International Conference on Software Analysis, Evolution and Reengineering (SANER),pp.554–565,IEEE,2022. 2. A. Kanade, P. Maniatis, G. Balakrishnan, and K. Shi, “Learning and evaluating con- textual embedding of source code,” in International conference on machine learning, pp.5110–5121,PMLR,2020. 3. T. Hoang, H. J. Kang, D. Lo, and J. Lawall, “Cc2vec: Distributed representations of code changes,” in Proceedings of the ACM/IEEE 42nd International Conference on Software Engineering,pp.518–529,2020. 4. U. Alon, M. Zilberstein, O. Levy, and E. Yahav, “code2vec: Learning distributed rep- resentations of code,” Proceedings of the ACM on Programming Languages, vol. 3, no.POPL,pp.1–29,2019. 5. V.J.Hellendoorn,C.Sutton,R.Singh,P.Maniatis,andD.Bieber,“Globalrelational modelsofsourcecode,”inInternational conference on learning representations,2019. 6. X. Cheng, G. Zhang, H. Wang, and Y. Sui, “Path-sensitive code embedding via con- trastivelearningforsoftwarevulnerabilitydetection,”inProceedings of the 31st ACM SIGSOFT International Symposium on Software Testing and Analysis, pp. 519–531, 2022. 7. X.Hu,G.Li,X.Xia,D.Lo,andZ.Jin,“Deepcodecommentgeneration,”inProceedings of the 26th conference on program comprehension,pp.200–210,2018. 8. R. Dale, “Gpt-3: What’s it good for?,” Natural Language Engineering, vol. 27, no. 1, pp.113–118,2021. 9. T.L.Scao,A.Fan,C.Akiki,E.Pavlick,S.Ili´c,D.Hesslow,R.Castagn´e,A.S.Luccioni, F.Yvon,M.Gall´e,etal.,“Bloom:A176b-parameteropen-accessmultilinguallanguage model,”arXiv preprint arXiv:2211.05100,2022. 10. C. Raffel, N. Shazeer, A. Roberts, K. Lee, S. Narang, M. Matena, Y. Zhou, W. Li, and P. J. Liu, “Exploring the limits of transfer learning with a unified text-to-text transformer,” The Journal of Machine Learning Research, vol. 21, no. 1, pp. 5485– 5551,2020. 11. H. Touvron, L. Martin, K. Stone, P. Albert, A. Almahairi, Y. Babaei, N. Bashlykov, S. Batra, P. Bhargava, S. Bhosale, et al., “Llama 2: Open foundation and fine-tuned chatmodels,”arXiv preprint arXiv:2307.09288,2023.28 YuZhaoetal. 12. F. Feng, Y. Yang, D. Cer, N. Arivazhagan, and W. Wang, “Language-agnostic bert sentenceembedding,”inProceedingsofthe60thAnnualMeetingoftheAssociationfor Computational Linguistics (Volume 1: Long Papers),pp.878–891,2022. 13. N.ReimersandI.Gurevych,“Sentence-bert:Sentenceembeddingsusingsiamesebert- networks,”arXiv preprint arXiv:1908.10084,2019. 14. C. Sun, L. Huang, and X. Qiu, “Utilizing bert for aspect-based sentiment analysis via constructingauxiliarysentence,”inProceedings of NAACL-HLT,pp.380–385,2019. 15. T. Khot, P. Clark, M. Guerquin, P. Jansen, and A. Sabharwal, “Qasc: A dataset for questionansweringviasentencecomposition,”inProceedings of the AAAI Conference on Artificial Intelligence,vol.34,pp.8082–8090,2020. 16. R. Zeng, H. Liu, S. Peng, L. Cao, A. Yang, C. Zong, and G. Zhou, “Cnn-based broad learning for cross-domain emotion classification,” Tsinghua Science and Technology, vol.28,no.2,pp.360–369,2022. 17. J.D.M.-W.C.KentonandL.K.Toutanova,“Bert:Pre-trainingofdeepbidirectional transformers for language understanding,” in Proceedings of NAACL-HLT, pp. 4171– 4186,2019. 18. A. Kanade, P. Maniatis, G. Balakrishnan, and K. Shi, “Learning and evaluating con- textual embedding of source code,” in International conference on machine learning, pp.5110–5121,PMLR,2020. 19. Z.Feng,D.Guo,D.Tang,N.Duan,X.Feng,M.Gong,L.Shou,B.Qin,T.Liu,D.Jiang, et al., “Codebert: A pre-trained model for programming and natural languages,” in Findings of the Association for Computational Linguistics: EMNLP 2020, pp. 1536– 1547,2020. 20. X. Jiang, Z. Zheng, C. Lyu, L. Li, and L. Lyu, “Treebert: A tree-based pre-trained modelforprogramminglanguage,”inUncertainty in Artificial Intelligence,pp.54–63, PMLR,2021. 21. D.Guo,S.Ren,S.Lu,Z.Feng,D.Tang,L.Shujie,L.Zhou,N.Duan,A.Svyatkovskiy, S. Fu, et al., “Graphcodebert: Pre-training code representations with data flow,” in International Conference on Learning Representations,2020. 22. C. Ni, K. Yang, X. Xia, D. Lo, X. Chen, and X. Yang, “Defect identification, catego-
rization,andrepair:Bettertogether,”arXiv preprint arXiv:2204.04856,2022. 23. B. Wei, G. Li, X. Xia, Z. Fu, and Z. Jin, “Code generation as a dual task of code summarization,”Advances in neural information processing systems,vol.32,2019. 24. Y.Wang,W.Wang,S.Joty,andS.C.Hoi,“Codet5:Identifier-awareunifiedpre-trained encoder-decodermodelsforcodeunderstandingandgeneration,”inProceedings of the 2021ConferenceonEmpiricalMethodsinNaturalLanguageProcessing,pp.8696–8708, 2021. 25. K. Liu, G. Yang, X. Chen, and Y. Zhou, “El-codebert: Better exploiting codebert to supportsourcecode-relatedclassificationtasks,”inProceedingsofthe13thAsia-Pacific Symposium on Internetware,pp.147–155,2022. 26. C. Niu, C. Li, V. Ng, and B. Luo, “Comparing the pretrained models of source code by re-pretraining under a unified setup,” IEEE Transactions on Neural Networks and Learning Systems,2023. 27. R. Sharma, F. Chen, F. Fard, and D. Lo, “An exploratory study on code attention inbert,”inProceedings of the 30th IEEE/ACM International Conference on Program Comprehension,pp.437–448,2022. 28. Y. Chai, H. Zhang, B. Shen, and X. Gu, “Cross-domain deep code search with meta learning,”inProceedingsofthe44thInternationalConferenceonSoftwareEngineering, pp.487–498,2022. 29. Z.Zeng,H.Tan,H.Zhang,J.Li,Y.Zhang,andL.Zhang,“Anextensivestudyonpre- trainedmodelsforprogramunderstandingandgeneration,”inProceedings of the 31st ACMSIGSOFTinternationalsymposiumonsoftwaretestingandanalysis,pp.39–51, 2022. 30. X. Zhou, D. Han, and D. Lo, “Assessing generalizability of codebert,” in 2021 IEEE International Conference on Software Maintenance and Evolution (ICSME),pp.425– 436,IEEE,2021. 31. W. Ahmad, S. Chakraborty, B. Ray, and K.-W. Chang, “Unified pre-training for pro- gram understanding and generation,” in Proceedings of the 2021 Conference of theHowtogetbetterembeddingswithcodepre-trainedmodels?Anempiricalstudy 29 North American Chapter of the Association for Computational Linguistics: Human Language Technologies,pp.2655–2668,2021. 32. S. Lu, D. Guo, S. Ren, J. Huang, A. Svyatkovskiy, A. Blanco, C. Clement, D. Drain, D.Jiang,D.Tang,etal.,“Codexglue:Amachinelearningbenchmarkdatasetforcode understandingandgeneration,”arXiv preprint arXiv:2102.04664,2021. 33. E.Nijkamp,B.Pang,H.Hayashi,L.Tu,H.Wang,Y.Zhou,S.Savarese,andC.Xiong, “Codegen:Anopenlargelanguagemodelforcodewithmulti-turnprogramsynthesis,” arXiv preprint arXiv:2203.13474,2022. 34. X. Sun, L. Tu, J. Zhang, J. Cai, B. Li, and Y. Wang, “Assbert: Active and semi- supervised bert for smart contract vulnerability detection,” Journal of Information Security and Applications,vol.73,p.103423,2023. 35. W.Tang,M.Tang,M.Ban,Z.Zhao,andM.Feng,“Csgvd:Adeeplearningapproach combining sequence and graph embedding for source code vulnerability detection,” Journal of Systems and Software,vol.199,p.111623,2023. 36. Z. Ding, H. Li, W. Shang, and T.-H. P. Chen, “Can pre-trained code embeddings im- provemodelperformance?revisitingtheuseofcodeembeddingsinsoftwareengineering tasks,”Empirical Software Engineering,vol.27,no.3,p.63,2022. 37. H. J. Kang, T. F. Bissyand´e, and D. Lo, “Assessing the generalizability of code2vec tokenembeddings,”in201934thIEEE/ACMInternationalConferenceonAutomated Software Engineering (ASE),pp.1–12,IEEE,2019. 38. Z. Liu, Z. Tang, X. Xia, and X. Yang, “Ccrep: Learning code change representations viapre-trainedcodemodelandqueryback,”arXiv preprint arXiv:2302.03924,2023. 39. G. Lin, S. Wen, Q.-L. Han, J. Zhang, and Y. Xiang, “Software vulnerability detec- tion using deep neural networks: a survey,” Proceedings of the IEEE, vol. 108, no. 10, pp.1825–1848,2020. 40. S. Chakraborty, R. Krishna, Y. Ding, and B. Ray, “Deep learning based vulnerability detection:Arewethereyet,”IEEE Transactions on Software Engineering,2021. 41. R.Russell,L.Kim,L.Hamilton,T.Lazovich,J.Harer,O.Ozdemir,P.Ellingwood,and M.McConley,“Automatedvulnerabilitydetectioninsourcecodeusingdeeprepresen- tationlearning,”in201817thIEEEinternationalconferenceonmachinelearningand applications (ICMLA),pp.757–762,IEEE,2018. 42. Z. Li, D. Zou, S. Xu, X. Ou, H. Jin, S. Wang, Z. Deng, and Y. Zhong, “Vuldeep- ecker: A deep learning-based system for vulnerability detection,” arXiv preprint arXiv:1801.01681,2018. 43. M.Lei,H.Li,J.Li,N.Aundhkar,andD.-K.Kim,“Deeplearningapplicationoncode clone detection: A review of current knowledge,” Journal of Systems and Software, vol.184,p.111141,2022. 44. C. Tao, Q. Zhan, X. Hu, and X. Xia, “C4: Contrastive cross-language code clone de- tection,”inProceedings of the 30thIEEE/ACM InternationalConference on Program Comprehension,pp.413–424,2022. 45. A. Zhang, L. Fang, C. Ge, P. Li, and Z. Liu, “Efficient transformer with code token learnerforcodeclonedetection,”JournalofSystemsandSoftware,vol.197,p.111557, 2023. 46. M. Zakeri-Nasrabadi, S. Parsa, M. Ramezani, C. Roy, and M. Ekhtiarzadeh, “A sys-
tematic literature review on source code similarity measurement and clone detection: Techniques,applications,andchallenges,”JournalofSystemsandSoftware,p.111796, 2023. 47. Y. Zhao, K. Damevski, and H. Chen, “A systematic survey of just-in-time software defectprediction,”ACM Computing Surveys,vol.55,no.10,pp.1–35,2023. 48. L.SongandL.L.Minku,“Aproceduretocontinuouslyevaluatepredictiveperformance of just-in-time software defect prediction models during software development,” IEEE Transactions on Software Engineering,vol.49,no.2,pp.646–666,2022. 49. Z.Zeng,Y.Zhang,H.Zhang,andL.Zhang,“Deepjust-in-timedefectprediction:how fararewe?,”inProceedings of the 30th ACM SIGSOFT International Symposium on Software Testing and Analysis,pp.427–438,2021. 50. T. Hoang, H. K. Dam, Y. Kamei, D. Lo, and N. Ubayashi, “Deepjit: an end-to-end deep learning framework for just-in-time defect prediction,” in 2019 IEEE/ACM 16th International Conference on Mining Software Repositories (MSR), pp. 34–45, IEEE, 2019.30 YuZhaoetal. 51. H. Husain, H.-H. Wu, T. Gazit, M. Allamanis, and M. Brockschmidt, “Code- searchnet challenge: Evaluating the state of semantic code search,” arXiv preprint arXiv:1909.09436,2019. 52. Y. Zhou, S. Liu, J. Siow, X. Du, and Y. Liu, “Devign: Effective vulnerability iden- tification by learning comprehensive program semantics via graph neural networks,” Advances in neural information processing systems,vol.32,2019. 53. J.Svajlenko,J.F.Islam,I.Keivanloo,C.K.Roy,andM.M.Mia,“Towardsabigdata curated benchmark of inter-project code clones,” in 2014 IEEE International Confer- ence on Software Maintenance and Evolution,pp.476–480,IEEE,2014. 54. A.Agrawal,T.Menzies,L.L.Minku,M.Wagner,andZ.Yu,“Bettersoftwareanalyt- ics via “duo”: Data mining algorithms using/used-by optimizers,” Empirical Software Engineering,vol.25,pp.2099–2136,2020. 55. R.F.Woolson,“Wilcoxonsigned-ranktest,”Wileyencyclopediaofclinicaltrials,pp.1– 3,2007. 56. H.Touvron,T.Lavril,G.Izacard,X.Martinet,M.-A.Lachaux,T.Lacroix,B.Rozi`ere, N.Goyal,E.Hambro,F.Azhar,etal.,“Llama:Openandefficientfoundationlanguage models,”arXiv preprint arXiv:2302.13971,2023. 57. Y. Wan, W. Zhao, H. Zhang, Y. Sui, G. Xu, and H. Jin, “What do they capture? a structural analysis of pre-trained language models for source code,” in Proceedings of the 44th International Conference on Software Engineering,pp.2377–2388,2022. 58. K. Clark, U. Khandelwal, O. Levy, and C. D. Manning, “What does bert look at? an analysisofbert’sattention,”inProceedingsofthe2019ACLWorkshopBlackboxNLP: Analyzing and Interpreting Neural Networks for NLP,pp.276–286,2019. 59. S.Dou,J.Shan,H.Jia,W.Deng,Z.Xi,W.He,Y.Wu,T.Gui,Y.Liu,andX.Huang, “Towardsunderstandingthecapabilityoflargelanguagemodelsoncodeclonedetection: Asurvey,”arXiv preprint arXiv:2308.01191,2023. 60. Z.Tang,Y.Wang,Q.Wang,andX.Chu,“Theimpactofgpudvfsontheenergyand performance of deep learning: An empirical study,” in Proceedings of the Tenth ACM International Conference on Future Energy Systems,pp.315–325,2019.
2311.08621 Cross Device Federated Intrusion Detector for Early Stage Botnet Propagation in IoT Angela Grace Famera∗, Raj Mani Shukla†, Suman Bhunia∗ ∗ Department of Computer Science and Software Engineering, Miami University, Oxford, Ohio † Computing and Information Science, Anglia Ruskin University, Cambridge Email: fameraag@miamioh.edu, raj.shukla@aru.ac.uk, bhunias@miamioh.edu Abstract—Abotnetisanarmyofzombifiedcomputersinfected botnets on a packet-by-packet basis using federated learning with malware and controlled by malicious actors to carry out before an attack can take place. tasks such as Distributed Denial of Service (DDoS) attacks. Bil- A typical IDS sees all the network traffic coming into lionsofInternetofThings(IoT)devicesareprimarilytargetedto a network. Federated learning is most popularly explained beinfectedasbotssincetheyareconfiguredwithweakcredentials orcontaincommonvulnerabilities.Detectingbotnetpropagation in the medical setting, given its ability to keep patient data by monitoring the network traffic is difficult as they easily confidential between different organizations. But why would blend in with regular network traffic. The traditional machine we want to keep network data private to the device? Packets learning (ML) based Intrusion Detection System (IDS) requires hold an array of information that could be used to cause the raw data to be captured and sent to the ML processor to harm if it falls into the wrong hands. We want to use fed- detect intrusion. In this research, we examine the viability of a cross-device federated intrusion detection mechanism where erated learning to aggregate more information from multiple each device runs the ML model on its data and updates the networks. Our approach allows us to connect to multiple modelweightstothecentralcoordinator.Thismechanismensures networks and process more data without actually seeing the the client’s data is not shared with any third party, terminating data. More data from different networks allows us to build privacyleakage.Themodelexamineseachdatapacketseparately better models because they will have more content to learn and predicts anomalies. We evaluate our proposed mechanism on a real botnet propagation dataset called MedBIoT. Overall, from.Moreover,thenatureofanomalydetectionwillbemore the proposed method produces an average accuracy of 71%, robust. Rather than building a model to recognize “normal” precision78%,recall71%,andf1-score68%.Inaddition,wealso traffic and flag everything that does not fit that standard, we examined whether any device taking part in federated learning also want our model to recognize hard-to-detect malicious can employ a poisoning attack on the overall system. traffic.Forexample,duringbotnetpropagation,itisveryeasy Index Terms—IoT, Botnet, Federated Learning, Mirai forthattraffictoblendinwithnormaltraffic.Whileitisgood to be able to predict attack traffic, ideally, we would like to I. INTRODUCTION take a more proactive approach to recognize anomalies before harmcanbedone.Especiallysincethemainattackmechanism Computer security plays an imperative role in our techno- of botnets is DDoS attacks, there is not much someone can logically advanced society. 65% of business leaders in 2019 do to mitigate that circumstance in the heat of the moment. felt their cybersecurity risks were increasing, and the average The main contributions of this research are the following: cost of a malware attack on a company is currently $2.6 • Weproposeanewintrusiondetectionsystemmechanism million[1].Withtheadvancementofsmarttechnology,attacks basedonfederatedlearningtopreservedataprivacy.Each on IoT devices also tripled in the first half of 2019, and the device takes part in federated learning by training the Mirai Distributed Denial of Service (DDoS) worm (the Mirai model locally, so no data is shared. botnet) was the third most common IoT threat in 2018 [1]. • Usageofrawpacketdatafromrealandemulatednetwork By 2025, there will be 41.6 billion connected IoT devices traffic captures during propagation and C&C communi- generating 79 zettabytes of data [2], and damage related to cation for three popular IoT botnets. cybercrime is projected to hit $10.5 trillion annually [1]. • We propose an online model analyzing network data on Effective techniques to actively detect malicious network a per-packet basis traffic are firewalls, Intrusion Detection Systems (IDS), and • We perform the novel feature selection on the network Intrusion Prevention Systems (IPS). These defense techniques data for efficient anomaly detection 1. require analyzing raw network traffic data, which can cause • We designed a neural network model to identify botnet privacy concerns when multiple devices and data silos are traffic at its early stages (i.e. pre-attack) owned by independent individuals and organizations. As ef- • We examined whether poisoning attacks have an impact fective as they are, firewalls, IDS, and IPS are not built to on model performance. A poisoning attack occurs when conserve data privacy or learn independently from the data an adversary injects bad data into a model. We simulate they are fed. Federated learning can address both privacy and self-learning.ThisresearchaimstocreateanIDStodetectIoT 1Allsourcecodepostedathttps://github.com/sbhunia/ml-malware 3202 voN 51 ]IN.sc[ 1v12680.1132:viXrathis kind of attack using label-flipping based on known malware trends. • Overall, the proposed method produces an average ac- curacy of 71%, precision 78%, recall 71%, and f1-score 68%. II. BACKGROUND&RELATEDWORK A. Botnet Overview While botnets often serve the hacker today, they were orig- inally developed to assist with the administration of Internet (a) Cros-Device (b) Cross-silo Relay Chat (IRC) servers [3]. IRC is a text-based protocol developed in 1988 used by connected computers for real- Fig. 1: Federated Learning Architectures time text messaging [4]. The IRC consisted of five main
becomespartofthebotmaster’sbotnet.Thisphaseoccurs components: servers, clients, operators, channels, and channel every time the host is restarted to let the botmaster know operators [5]. Botnets developed into an attack mechanism thatthedeviceisstillabletoreceiveandactonmalicious used by cybercriminals to perform various malicious actions, commands. most commonly being Distributed Denial of Service (DDoS) attacks, spam distribution, and network scanning, exploration, • Performance: The bot is able to receive commands and perform attacks. The C&C enables the botmaster to andexploitation[6].Abotnetisacollectionofbotsconnected monitor and control the botnet however seen fit. toandcontrolledbyaC&Cchannel[7].Botsareconstitutedof host machines, devices, and computers infected by malicious • Maintenance: The bot’s malware is updated for the bot- master to maintain the botnet. Here binary’s are updated code that enslaves them to the C&C [7]. The C&C updates toensureaconnectionwiththeC&Cremainsestablished. and guides bots to perform the desired task by acting as the communicationlinkbetweenthebotsandanindividualknown Methods of propagation include but are not limited to email as a botmaster [7]. The botmaster’s primary purpose is to attachments, infected websites, and previously installed back- control the botnet by issuing commands through the C&C to doors [7]. perform malicious and illegal activities. B. Federated Learning The most critical part of a botnet is the C&C architecture [7]. The C&C is the only way to control the bots within a Federated learning is a machine learning method where botnetandisresponsiblefortheirsmoothandcollectiveopera- multiple clients collectively train a model using their own tion.Therefore,iftheC&Cwasdestroyed,thebotnetwouldno datainadecentralizedmannerundertheguidanceofacentral longerbeabletocarryoutitsintendedpurpose.Thethreemost server[9].In2016,theterm“FederatedLearning”wascoined commonbotnetC&Cstructuresarecentralized,decentralized, by McMahan et al. in [10] as a learning task is solved by a and hybridized control [7], [8]. Centralized C&C primarily loose federation of participating devices. Federated learning usesHTTPandIRCbasedprotocols.UnlikecentralizedC&C, differs from distributed learning in the sense that a traditional decentralizedC&CusesPeer-to-Peer(P2P)protocolsinwhich distributed system encompasses distributed computation and all the bots are connected. These protocols focus on hiding storage [11]. The primary advantage of the federated learning the C&C channels, and botmasters can call different bots approach is to remove a model’s need for direct access to raw for different issues. Hybridized botnets use a combination of trainingdata,resultinginenhancedprivacy[10].Itsadvantages the centralized and decentralized C&C structure, often using are often described for the medical setting, where medical encryption to hide botnet traffic. organizations can train models on patient data without vio- Botnets have a unique life cycle [7]: lating privacy laws or exposing clients’ medical history. The • Initial Injection: The host device is infected and be- emphasis on privacy makes the federated learning framework comesapotentialbot.Duringthisphase,theattackermay attractiveforcybersecurity,givenitwillinherentlyprotectdata use an array of different infection mechanisms, such as security and confidentiality [12]. There are two notable types infected files and removal disks or forced downloads of of federated learning, 1) Cross-device and 2) Cross-silo (see malware from various websites. Figure 1). The following section will discuss each one more • Secondary Injection: The infected host runs a program in-depth. thattransformsthedeviceintoabot.Scriptsareexecuted In Crossed Device Federated Learning, The clients are a by the infected host that fetches the device’s binary code verylargenumber(i.e.thousandsormillions)ofmobile,edge, viaFTP,HTTP,orP2Pprotocol.Thisbinarycontainsthe or IoT devices [13]. Here each client stores its own data and addresses of the machines and may be encoded directly is unable to see the data produced by another client, and ashard-codedIPaddressesordomainnames.Duringthis the data is not independently or identically distributed [13]. phase, the host becomes a bot. There is a central server that supervises training but does • Connection: Through a process known as rallying, the not have access to the raw data, only the model parameters bot establishes a connection with the C&C server and returned by the clients. We use the Cross-device approach inour research. We use a labeled dataset and feed it through distributed clients, sharing a simple neural network model for training. We aim to reduce the complexity of our network giventhelowprocessingorcomputingpowerIoTdevicesmay exhibit. In our simulation, each client acts as an IoT device and stores network packet data. Cross-Silo Federated Learning used data silos which are repositories of data stored in a standalone system controlled byasingledepartmentorbusinessunitwithinanorganization (a) Standard IDS Setup (b) Federated IDS Setup . As the name suggests, Cross-silo federated learning trains a model on siloed data, making the clients different organiza- Fig. 2: IDS architecture tions or geographically distributed data centers (typically 2 - APK files from the Opera Mobile Store. Zhao et al. propose 100 clients) [9]. a multi-task deep neural network in federated learning (MT- The steps in the federated learning process are as follows DNN-FL) to perform network anomaly detection tasks, VPN [13]: (Tor) traffic recognition tasks, and traffic classification tasks 1) Identifying the problem to be solved with federated simultaneously [16]. learning. Rey et al. use federated learning to detect malware in 2) Training data is distributed among clients (simulation IoT devices [17]. The researchers perform both supervised environment).
and unsupervised federated learning using N-BaIoT, a dataset 3) Federated model training begins. compiledin2018containingattackdatafromnineIoTdevices a) The server samples a set of clients. infected by Mirai and Bashlite. They achieve accuracies, True b) Selected clients download current model weights Positive Rates (TPR), and True Negative Rates (TNR) of and a training program. +99%intheirMulti-EpochandMini-Batchsupervisedmodels. c) Clients locally compute and update the model. There are a few key differences between Rey et al. and our d) The server collects an aggregate of the device research. Two of the most important are: first, we are using updates. an entirely different dataset; and, second, we are examining e) The server locally updates its model based on the our instances on a packet-by-packet basis, similar to how an aggregated data computed from the clients. intrusion detection system would. We do not use statistics 4) Thefederatedmodelisevaluatedaftersufficienttraining. collected from the packet streams but rather examine each 5) Themodelisdeployedwithinthedatacenterornetwork packet and its contents independently. The analysis of per- using a staged rollout. packet makes the proposed IDs much faster as opposed to using the stream information. C. Related Work III. PROPOSEDCROSS-DEVICEFLINTRUSION Malware detection and machine learning are widely re- DETECTION(ID)ARCHITECTURE searched topics. Ghimire et al. compile a comprehensive survey on federated learning for cybersecurity in relation to Figure2adisplaysageneralIDSasitismostwidelyusedin IoT devices [12]. They present a detailed study on federated the market. When a router connects to the internet, a firewall learning models used for cybersecurity and their associated is commonly put up to block specified malicious traffic. An performance metrics and challenges. They discuss the limita- IDS can be placed before or after a firewall, but it is optimal tions of federated learning in the IoT space, such as limited to put it after so the firewall takes the brunt of the action, and device memory, battery power, and computing power. In the IDS can catch malicious stragglers the firewall may miss. summary, it appears to be the most recent survey of all things Then, whatever traffic passes through the IDS is allowed to federatedlearninginrelationtocybersecurityandIoTdevices. enter the private network. Galvez et al. present a malware classifier leveraging fed- Anomaly-based IDS solutions model “normal” behavior erated learning for Android applications called LiM (‘Less within the system, labeling packets as potential threats if they is More’) [14]. LiM uses a safe semi-supervised learning present anomalous behavior. This is beneficial for a closed or ensemble (SSL) to maximize accuracy with respect to a private organizational network where there could be such a baseline classifier on the cloud by ensuring unlabeled data thing as “normal” traffic behavior, but this becomes difficult does not worsen the performance of a fully supervised clas- to pinpoint as open networks and IoT devices grow in size. sifier. Prior to [14], Hsu et al. present a privacy-preserving We propose a slightly different architecture. federated learning (PPFL) android malware detection system A. Detecting Botnet Propagation [15]. Implementing the PPFL using support vector machines, the researchers demonstrate its feasibility using an Android The phases of the botnet lifecycle are initial injection, sec- malware dataset by the National Institute of Information and ondary injection, connection, performance, and maintenance. Communication Technology (NCIT) containing over 87,000 During the initial and secondary injection, the host device isinfected by either weak credentials or system vulnerabilities. C. Poisoning Attack by Participant Node Forexample,Miraiwouldinfectdevicesbyperformingabrute Poisoning attacks happen when a hacker tries to inject fake force attack at guessing common or insecure credentials, such trainingdataintoamodeltoreduceorhinderitsperformance. as “admin” and “admin” for username and password. Mirai There are four main categories of poisoning attacks: 1) logic hadalistof60commonusernamesandpasswords,andwould corruption, 2) data manipulation, 3) data injection, and 4) randomly to chose 10 from that list. Bashlite would infect DomainNameSystem(DNS)cachepoisoning[18].Logiccor- devices via Shellshock, a bash vulnerability that allowed the ruption is where the attacker changes the logic of the systems execution of arbitrary commands to gain unauthorized access to disrupt how the system learns [18]. Data manipulation is when concatenated to the end of function definitions. Torii where the attacker manipulates the data rather than the logic is more sophisticated in the sense it will download different [18]. Data injection is when fake data is inserted into the binary payloads based on the architecture of the targeted actual dataset to skew model results and weaken outcomes device. More sophisticated botnets are sneaky when infecting [18].Last,DNScachepoisoningiswhentheattackercorrupts devices, and it is difficult to tell when a device has been DNS data, causing the name server to return incorrect results infected. After infection, the device is then connected to the [18].Thetypeofpoisoningattackwetrytoreplicateisadata C&C,anditawaitsinstruction.Onceitreceivestheinstruction manipulation attack. Since we are using supervised learning, to do so, it can then carry out attacks. we emulate an attack as if a malicious user switched the Theabilitytodetecttheearlybotnetphasesbeforereceiving malware labels to benign to cover up bad traffic. We tried instruction from the C&C to attack is important. We believe tobesophisticatedwithourapproachusinglabel-flipping.We analyzing the individual network packets may be one of the researched the most popular source port among the malicious bestwaystodothis.Ifwecanidentifycommunicationtraffic, datainthedatasetandfoundport23tobeontop.Asaresult,
we can more likely identify the C&C and put up defenses we flipped all the labels from 1 to 0 for packets with a source against it. To analyze the individual packets, we examine the port equal to 23 in the first client. information stored in the packet headers. We believe a system thatanalyzesonaper-packetbasisisabeneficialwaytodetect D. Feature Selection discrepancies between normal and malicious traffic. We use MedBIoT data focusing on the early stages of botnet deployment: propagation and C&C communication B. Federated Machine Learning Approach [19]. In this dataset, a combination of real and emulated Figure 2b displays a holistic overview of our proposed devices are used, making up for a total of 83 devices. architecture. The components of the architecture are listed The real devices include a Sonoff Tasmota smart switch, below: TPLink smart switch, and a TPLink light bulb. The • Federated IDS:Theintrusiondetectionsystemsthatuti- Emulated devices include locks, switches, fans, and lights. lizes federated learning to differentiate between anoma- These devices are infected with the Mirai, Bashlite, and lous and normal network data on a per-packet basis. Torii botnet malware. The packet attributes we initially • Devices:UnlikethestandardIDSsystem,ourIDSwould analyzed using Wireshark are : frame.encap type, frame.time, be able to connect to multiple devices on multiple net- frame.time epoch, frame.offset shift, frame.time delta, works.Thedeviceswouldtrainourmodel,thenreportthe frame.time delta displayed, frame.time relative, model weights back to the IDS without having to share frame.number, frame.len, frame.cap len, frame.marked, data. frame.ignored, frame.protocols, frame.coloring rule.name, • Internet Routers:Whatallowsthedevicestoconnectto eth.dst, eth.src, eth.type, ip.dsfield, ip.len, ip.id, the internet. ip.flags, ip.ttl, ip.proto, ip.checksum, ip.checksum.status, We want to use federated learning because it conserves data ip.src, ip.dst, tcp.srcport, tcp.dstport, tcp.stream, privacy. In theory, our IDS would be connected to different tcp.len, tcp.seq, tcp.seq raw, tcp.nxtseq, tcp.ack, routers, therefore being connected to different networks. The tcp.ack raw, tcp.hdr len, tcp.flags, tcp.window size value, central IDS or server will distribute its model to the selected tcp.window size, tcp.window size scalefactor, devices,andeachdevicewillrunthemodelonitsownnetwork tcp.checksum, tcp.checksum.status, tcp.urgent pointer, data. Devices would not have to share their network data tcp.time relative, tcp.time delta, tcp.analysis.bytes in flight, with other devices or the IDS. To avoid exposing private tcp.analysis.push bytes in flight, udp.srcport, udp.dstport, information across devices or through the internet, all data udp.length, udp.checksum, udp.time relative, udp.time delta. remains local to the device, and only the model weights We first generated a large, singular dataset from the bulk are updated and adjusted. We take the approach of trying data containing all the features, then randomly selected a to differentiate between “normal” and “anomalous” traffic little over 3,700 rows to produce a subset dataset to gain a since normal traffic may be hard to define in larger networks more holistic view of the values each feature contained. After that are open or have many devices connected to them. We analyzing these features in the subset, we decided to discard propose training our model on pre-attack data to help it focus a handful of them as they did not have variable information. on learning the discrepancies between malicious and benign Now that we had the features we wanted, we then added network traffic when they are hard to tell apart. a few additional features to use as labels. The first featureTABLE I: Reason for Removing Features We removed all of the features containing null values since Key ReasonforRemoval it would be difficult to fill this data in. We ended up with frame.encap type LackofVariability a mildly unbalanced dataset containing 23,793 samples in frame.time Date/Time frame.time epoch Continuous total out of the original 24,000. Out of the 23,793 samples, frame.offset shift LackofVariability 11,942 were labeled as malware, and 11,851 were labeled as frame.time delta Continuous frame.time delta displayed Interchangeable(frame.time delta) benign.Whilewetriedtokeepthingsasbalancedaspossible, frame.time relative Continuous we didn’t stress too much about this because we inevitably frame.number Continuous frame.cap len Interchangeable(frame.len) would have to shuffle the data and distribute it randomly frame.marked LackofVariability amongst the clients. Each client, therefore, will more likely frame.ignored LackofVariability frame.coloring rule.name N/A have unbalanced data when training their local model. In the eth.dst Categorical real world, it is also unlikely each client will be processing eth.src Categorical eth.type LackofVariability balanced network traffic. ip.dsfield LackofVariability ip.id Identification IV. RESULTS ip.checksum Variability ip.checksum.status LackofVariability We ran our model using various number if clients, epochs, tcp.stream Identification tcp.seq Variability learning rate, and iterations. The following sections discusses tcp.seq raw Variability the results obtained using these hyperparameters and metrics. tcp.nxtseq Variability tcp.ack Variability tcp.ack raw Variability A. Hyperparameter: Epochs (200 vs 400) tcp.checksum Variability tcp.checksum.status LackofVariability Using four clients, a batch size of 64, 30 iterations, and a tcp.urgent pointer LackofVariability learningrateof0.01,wefoundanegligibledifferencebetween udp.srcport Nulls