text
stringlengths
64
2.99M
andcontentstogetthemostrelevantandhigh-qualityresearchpapers.Tomakehumaneffort manageable,wedevelopedascripttoautomaticallygethigh-qualityrecordsclosetothesoftware vulnerabilitydetectionproblem.Tosummarize,inthefirststage,webeganwithatotalof3,154 papersobtainedfromthedatabasesearch.Fromthisinitialpool,880paperswerechosenforfurther evaluationinthesecondstage.Duringthesecondstage,thesepaperswerereviewedbasedontheir abstracts,resultingintheselectionof116paperswithrelevantabstracts.Finally,inthethirdstage, afterreadingthefullpapers,67paperswereultimatelychosenforinclusioninthestudy. 3.4 StudyQualityAssessment Foreachofthefinalselectedstudies,weansweredthequestionsbelowtoassessitsquality: • Isthereaclearlystatedresearchgoalrelatedtosoftwarevulnerabilitydetection? • IstheproposedvulnerabilitydetectionapproachusedMLorDLtechniques? • Isthereadefinedandrepeatabletechnique? • Isthereanyexplicitcontributiontovulnerabilitydetection? • Isthereaclearmethodologyforvalidatingthetechnique? • Arethesubjectprojectsselectedforvalidationsuitablefortheresearchgoals? • Aretherecontroltechniquesorbaselinestodemonstratetheeffectivenessofthevulnerability detectiontechnique? • Aretheevaluationmetricsrelevant(e.g.,evaluatetheeffectivenessoftheproposedtechnique) totheresearchobjectives? • Dotheresultspresentedinthestudyalignwiththeresearchobjectivesandaretheypresented inaclearandrelevantmanner? 3.5 SelectionVerification The process of creating a taxonomy for the selected 67 primary studies involves several steps. Initially,theleadauthorestablishesapreliminarytaxonomythatgroupsthestudiestogetherbased ontheirresearchquestions.Thistaxonomyprovidesabasicframeworkfororganizingthestudiesin ameaningfulandsystematicmanner.Next,theleadauthorexpandsthetaxonomybyassigningnew J.ACM,Vol.37,No.4,Article111.Publicationdate:August2018.ASurveyonAutomatedSoftwareVulnerabilityDetectionUsingMachineLearningandDeepLearning 111:11 Fig.1. Theworkflowofoursurvey. paperstothepreliminarytaxonomy.Ifanewpapercannotfitintoanyoftheexistingcategories within the taxonomy, a new category is created that reflects the unique characteristics of that paper.Toensuretheaccuracyofthetaxonomy,thesecondandthirdauthors(whoarenotinvolved inthetaxonomycreationprocess)randomlyselect20papersfromtheworkflowandcheckthe createdtaxonomiesforanydiscrepancies.Theythenmarkanydisagreementstheyfind,andall threeauthorsdiscussandresolvethesedisagreements.Initially,thedisagreementratewas30%,but afterasecondroundofreviewandcross-checkingofthepapers,theauthorswereabletoeliminate alldisagreements. 4 RESULTS Wepresentouranalysesandfindingsinthissectiontoaddresstheresearchquestionswedevised inSection1. 4.1 RQ1.WhatisthetrendofstudiesusingML/DLmodelsforvulnerabilitydetection? Tocomprehendthetrendofpublications,weexaminedthepublicationdatesalongwiththevenues inwhichtheywerepresented. 4.1.1 RQ1.1.Whatarethetrendsofstudiesinsoftwarevulnerabilitydetectionovertime? Figure2 demonstratesthepublicationtrendofvulnerabilitydetectionstudiespublishedinelevenyears,i.e., between2011and2022.Itisobservablethatthenumberofpublicationshasincreasedgradually overtheyears.Thereisonlyonepublicationfrom2011to2016,andthenumberofpublications increasedto18in2021.However,thereisadecreaseinthenumberofpublicationsin2022compared J.ACM,Vol.37,No.4,Article111.Publicationdate:August2018.11N1:i1m2aShiriharzevili,AlvineBoayeBelle,JunjieWang,SongWang,ZhenMing(Jack)Jiang,andNachiappanNagappan 20 18 15 14 10 9 9 6 6 5 1 1 1 1 1 0 20112013201420152016201720182019202020212022 Year snoitacilbuPforebmuN 1 1 0.79 0.5 1·102−2·104−2·105−2·107−2·10−20.160.290.430.52 0 20112013201420152016201720182019202020212022 Year noitubirtsiDevitalumuC Fig.2. Publicationtrendofvulnerabilitydetectionstudies. Table2. Conferencepublicationvenuesformanualsearch. No Acronym Fullname 1 ICSE InternationalConferenceonSoftwareEngineering 2 ECSE/FSE ACMSIGSOFTSymposiumontheFoundationofSoftwareEngineering 3 ASE IEEE/ACMInternationalConferenceonAutomatedSoftwareEngineering 4 USENIX USENIX 5 OOPSLA Object-orientedProgramming,Systems,Languages,andApplications 6 ISSTA ACMSIGSOFTInternationalSymposiumonSoftwareTestingandAnalysis 7 MSR IEEEWorkingConferenceonMiningSoftwareRepositories 8 SANER IEEEInternationalConferenceonSoftwareAnalysis,EvolutionandReengineering 9 ISSRE IEEEInternationalSymposiumonSoftwareReliabilityEngineering 10 ICSME IEEEInternationalConferenceonSoftwareMaintenanceandEvolution 11 IJCAI InternationalJointConferencesonArtificialIntelligenceOrganization 12 CCS ACMSIGSACConferenceonComputerandCommunicationsSecurity 13 ICLR InternationalConferenceonLearningRepresentations 14 NIPS InternationalConferenceonNeuralInformationProcessingSystems 15 MASCOT Modelling,Analysis,andSimulationofComputerandTelecommunicationSystems 16 QRS IEEEInternationalConferenceonSoftwareSecurityandReliability 17 KDDM Pacific-AsiaConferenceonKnowledgeDiscoveryandDataMining 18 NDSS NetworkandDistributedSystemsSecuritySymposium 19 ARES ACMInternationalConferenceonAvailability,ReliabilityandSecurity 20 INFOCOM IEEEInternationalWorkshoponSecurityandPrivacyinBigData 21 ICTAI IEEEInternationalConferenceonToolswithArtificialIntelligence 22 ICDM IEEEInternationalConferenceonDataMining 23 GLOBCOM IEEEGlobalCommunicationsConference
24 TrustCom IEEEInternationalConferenceonTrust,SecurityandPrivacyinComputingandCommunications 25 DSAA IEEEInternationalConferenceonDataScienceandAdvancedAnalytic tothepreviousyear.Wehavealsoexaminedthecumulativenumberofpublicationsshownin Figure2.Itisnoticeablethatthecurvefittingthedistributionshowsasignificantincreaseinslope between2018and2022suggestingthattheuseofML/DLtechniquesforsoftwarevulnerability detection has become a prevalent trend since 2017, and a broad range of studies have utilized ML/DLmodelstoaddresschallengesinthisfield. 4.1.2 RQ1.2:Whatisthedistributionofthepublicationvenues? Inthisstudy,overall,weanalyzed andreviewed67papersfromvariouspublicationvenuesincluding43conferenceandsymposium papers along with 24 journal papers. We have included the conference and journal acronyms andtheircompletenamesforreferenceinTable2andTable3.Table4showsthedistributionof primarystudiesforeachpublicationvenue.64.1%ofpublicationsarepublishedinconferencesand symposiumswhile35.8%ofpapershavebeenpublishedasjournalpapers.Itisobservablethat MSR,IJCAI,andECSE/FSEarethemostpopularvenuesthathavethehighestnumberofprimary studies,eachofwhichcontains4papers.Meanwhile,amongthejournals,TDSCandTSEinclude thehighestnumberofstudies,i.e.,6and4studiesrespectively. J.ACM,Vol.37,No.4,Article111.Publicationdate:August2018.ASurveyonAutomatedSoftwareVulnerabilityDetectionUsingMachineLearningandDeepLearning 111:13 Table3. Journalpublicationvenuesformanualsearch. No JournalAcronym FullName 1 TSE IEEETransactiononSoftwareEngineering 2 TOSEM ACMTransactiononSoftwareEngineeringandMethodology 3 IST InformationandSoftwareTechnology 4 ESM EmpiricalSoftwareEngineering 5 JSS JournalofSystemandSoftware 6 TDSC IEEETransactiononDependableandSecureComputing 7 CSJ ComputerandSecurityJournal 8 TIFS IEEETransactionsonInformationForensicsandSecurity 9 ISJ InformationSciencesJournal 10 TFS IEEETransactiononFuzzySystems 11 TKDE IEEETransactiononKnowledgeandDataEngineering 12 KBS Knowledge-BasedSystems AnswertoRQ1 (1) The results indicate that the application of ML/DL techniques for software vulner- ability detection has had a remarkable rising trend in the past few years. (2) A large proportion of papers are published in recent two years, i.e., 2021 and 2022. (3) MSR, IJCAI, and ECSE/FSE are the most popular conference venues. On the other hand, TDSC and TSE are the most popular journal venues. 4.2 RQ2.Whatarethecharacteristicsofsoftwarevulnerabilitydetectiondatasets? Data is important for building and evaluating ML/DL-based software vulnerability detection models[30,32,37,90,92].Thequalityofdatasetscanbeassessedbydifferentfactorssuchasthe sourceofdata,datasizeandscale,datatypes,andpreprocessingstepsperformedondata.For example,inappropriatepreprocessing(representation)ondatamayresultinpoorperformance ofDLmodels[121].Inthissection,weexaminedatausedinvulnerabilitydetectionstudiesand conductedacomprehensiveanalysisofthestepsofdatasource,datatype,anddatarepresentation. 4.2.1 RQ2.1.Whatarethesourcesofdatasets? OneofthemainchallengesinML/DL-basedsoftware vulnerabilitydetectionistheinsufficientamountofdataavailablefortrainingoperations[24,92]. Consequently,thereexistsagapinresearchonhowtoobtainsufficientdatasetstofacilitatethe trainingofML/DLmodelsforsoftwaresecurityvulnerabilitydetection.Tothisend,weanalyze thesourcesofdatasetsinthestudied67primarystudies.Ouranalysisrevealsthatdatasetsfor thispurposecanbebroadlyclassifiedintothreecategories,i.e.,Benchmark,Collected,andHybrid sources.Benchmarkcontainsstandardizeddatasetsusedtoevaluatetheperformanceofvulnerability detectionmethodsandtechniques[32,33,55,60,62,64,72,95,98,109,116,123,134,138,144,145, 150,161]. Benchmarkdatasetsforsoftwarevulnerabilitydetectionareoftenbuiltfromthreemainsources. Thefirstsourceofdataiscollectingcodesnippetsfromopensources.Thiscanincludeopen-source softwareprojects[67],publicvulnerabilitydatabases[11],andbugrepositories[14].Thegoalis togatheradiversesetofprogramsorcodesnippetsthatrepresentdifferentapplicationdomains, J.ACM,Vol.37,No.4,Article111.Publicationdate:August2018.11N1:i1m4aShiriharzevili,AlvineBoayeBelle,JunjieWang,SongWang,ZhenMing(Jack)Jiang,andNachiappanNagappan Table4. Distributionofpublicationsbasedonconferenceandjournalvenues. ConferenceVenue #Studies References JournalVenue #Studies References MSR 4 [24,45,58,60] TDSC 6 [86,87,90,95,159,160] IJCAI 4 [31,38,97,157] TSE 4 [25,32,33,124] ECSE/FSE 4 [84,108,110,155] CSJ 2 [64,145] CCS 3 [29,91,114,144] IST 2 [128,134] ISSRE 3 [140,150,153] TIFS 2 [61,136] ICLR 2 [35,76] TOSEM 2 [28,161] ICSE 2 [17,138] ESM 1 [120] OOPSLA 2 [85,118] ISJ 1 [49] NIPS 2 [55,154] JSS 1 [113] ASE 2 [79,152] TFS 1 [94] QRS 1 [82] TKDE 1 [98] KDDM 1 [109] KBS 1 [156] NDSS 1 [88] SUM 24 ARES 1 [72] INFOCOM 1 [158] MASCOT 1 [42] ICTAI 1 [116] ICSME 1 [123] ICDM 1 [62] GLOBCOM 1 [147] USENIX 1 [143] DSAA 1 [108] ISSTA 1 [30] SANER 1 [36] TrustCom 1 [146] SUM 43 programminglanguages,andvulnerabilitytypes.Fromthecollecteddata,specificprogramsor
codesnippetsareselectedtobeincludedinthebenchmarkdataset.Theselectionprocessconsiders factorssuchasprogramcomplexity,vulnerabilitydiversity,andcodequality.Theaimistocreatea datasetthatcoversawiderangeofvulnerabilitiesandrepresentsreal-worldscenarios.Insome cases,benchmarkdatasetsmayincludeautomaticallygeneratedsyntheticprograms[12].These programs are typically created using code generation techniques and follow certain patterns or templates. Synthetic generation allows for the creation of large-scale datasets and can help coverabroaderrangeofvulnerabilitiessystematically.Alongsidesyntheticprograms,benchmark datasetsoftenincludereal-worldsoftwareapplicationsorcodesnippetswrittenbyhand.These manuallycreatedcasesensurethatthedatasetcontainsrealisticvulnerabilitiesthatreflectactual codingpractices.Manualcreationinvolvesidentifyingvulnerablepointsinthecode,introducing appropriateweaknesses,andmaintainingabalancebetweencodequalityandrealism. Collected datasetsaregatheredfrompubliclyavailableprojectshostedonrepositorywebsites suchasGithuborStackOverflow[24,28,94,118,154,155].Also,somestudiesusethecombination ofdifferentsourcesforvulnerabilitydetectiontoincreasetheexternalvalidityoftheirfindings[24, 58,79,84,122,136,155],whichreferstoHybrid sourceinthiswork. J.ACM,Vol.37,No.4,Article111.Publicationdate:August2018.ASurveyonAutomatedSoftwareVulnerabilityDetectionUsingMachineLearningandDeepLearning 111:15 Benchmark 65.7% 9% Hybrid 25.4% Collected Fig.3. Thesourceofthedatasetsusedinprimarystudypapers. Thedistributionofdatasetsourcesintheprimarystudiesisillustratedinfigure3.Aswecan see,65.7%ofprimarystudieshaveutilizedBenchmarkdatasetsforsoftwarevulnerabilitydetection. Therationalebehindthistrendisthatbenchmarkdatasetsarereadilyaccessibletoallresearchers andcanfacilitatethereproducibilityofpriorstudies.ResearchersoftenusedCollected datasets inevaluatingtheproposedMLorDL-basedsecurityvulnerabilitydetectionmodels.According toourobservation,25.4%ofstudiesbuildvulnerabilitydetectionmodelsusingcollecteddatasets. There are a couple of reasons, first of all, open-source repositories like GitHub contain a vast amountofreal-worldcodewrittenbydevelopersfromdiversebackgrounds.Thisdatareflects the real-world coding practices, patterns, and vulnerabilities present in software projects. By analyzing such data, researchers can gain insights into the prevalent types of vulnerabilities andtheiroccurrencefrequenciesinreal-worldsoftware.Second,open-sourcerepositoriesoffer theopportunitytoidentifynewvulnerabilitiesthatmaynotbepresentinbenchmarkdatasets. Byanalyzingdiversecodebases,researcherscanuncoverpreviouslyunknownvulnerabilitiesor variationsofknownvulnerabilities,whichhelpsinadvancingthestate-of-the-artinvulnerability detectionandexpandingtheknowledgebaseofsoftwaresecurity. The third major source of data is Hybrid accounting for 9% of primary studies which is the combinationofdifferentsources.Researchersoftenusehybridsourcesforsoftwarevulnerability detectiontoaddresssomeofthelimitationsofindividualdatasourcesandtoobtainmorediverse andcomprehensivedatasets.Forexample,researchersmaycombinedatafrombenchmarkdatasets with data from other sources such as Github, open-source projects, or data from commercial companiestocreateahybriddatasetthatismorerepresentativeofreal-worldscenarios.Bydoing so,theycanimprovethegeneralizabilityoftheirmodelsandincreasetheirchancesofdetectinga widerrangeofvulnerabilities. Table5showsthedetaileddistributionofbenchmarkdatausedintheprimarystudies.Asit isobservable,NVDandSARDisthemostwidelyusedsourceofdataintheBenchmarkcategory. ThisisbecauseSARDandNVDarepubliclyavailablebenchmarksourcestowhichresearchers haveunrestrictedaccess.Theygivealotofvulnerabilitydata,allowingresearcherstogetabroad varietyofvulnerabilitiesfortheirexperimentsandanalyses.Theavailabilityofthesematerials promotesrepeatabilityandcollaborationamongresearchersinsoftwarevulnerabilitydetection. Overall,thereare35uniqueprimarystudiesthatusebenchmarkdatasetsfromdifferentsources. Table6showsthedetaileddistributionoftheCollected sourceofdata.Asshown,Githubisthe mostpopularsourceofdataforsoftwarevulnerabilitydetection,accountingfor14primarystudies. ResearcherscancollectdatasetsfromGithubbycrawlingtheplatformandextractingrelevantcode repositoriesorbyusingGithub’sAPItoaccessdataprogrammatically.Oneadvantageofusing GitHubasasourceofdataisthatitprovidesaccesstoreal-worldcodewrittenbydevelopers,which J.ACM,Vol.37,No.4,Article111.Publicationdate:August2018.11N1:i1m6aShiriharzevili,AlvineBoayeBelle,JunjieWang,SongWang,ZhenMing(Jack)Jiang,andNachiappanNagappan Table5. Detaileddistributionofbenchmarksources. No Source #Studies References 1 SARD 17 [17,28,38,42,64,84,86,87,90,95,134,136,146,153, 158,160,160] 2 NVD 13 [17,42,58,64,72,79,86,87,95,136,153,160,160] 3 ESCandVSC 3 [97,98,157] 4 SmartBugsWild 3 [107,108,140] 5 Juliettestsuit 3 [36,84,145] 6 SmartBugs 2 [107,108] 7 PROMISE 2 [138,150] 8 D2A 2 [30,36] 9 NDSS 2 [76,109] 10 NIST 1 [55] 11 OWASP 1 [55] 12 SAMATE 1 [72] 13 MozillaFirefoxprojects 1 [147] 14 ICLR2019 1 [147] 15 FQ 1 [30]
16 BugsWildDataset 1 [152] 17 Others 1 [109] - SUM 53(35) - Table6. DetaileddistributionofCollectedsources. No Source #Studies References 1 Github 14 [24,25,28,35,45,85,94,110,113,114,118,120,154,155] 2 Jira 2 [24,155] 3 CVE 2 [24,159] 4 Bugzilla 2 [24,155] 6 Others 2 [60,61] - SUM 22(17) - canbeusedtotrainandtestvulnerabilitydetectionmodels.Thisdatacanbeparticularlyusefulfor detectingnewandemergingvulnerabilitiesthatmaynotbecoveredbybenchmarkdatasets.Jira, CVE,andBugzillacomeafterwith2primarystudiesforeach.Overall,thereare17uniqueprimary studiesthatusecollectedsourcesofdataforsoftwarevulnerabilitydetection. 4.2.2 RQ2.2.Whatarethetypesofsoftwarevulnerabilitydetectiondatasetsusedinpriorstudies? Whenitcomestodetectingsoftwarevulnerabilities,datasetscanhavevaryingdatatypes,e.g., existingsoftwarevulnerabilitydetectionmodelscanfindvulnerabilitiesinsourcecodeorcommits. Itiscrucialtocarefullyexaminethedatatypes,astheyrequiredifferentpreprocessingtechniques andmustberepresenteddifferentlywhenusingML/DLmodels.Additionally,distinctdatatypes necessitatedifferentarchitecturalapproachesforML/DLmodels.Thissectionprovidesanoverview ofthevariousdatatypesandtheirdistributions.Weclassifiedthedatatypesofemployeddatasets intothreebroadcategories,i.e.,code-based,repository-based,andhybrid. J.ACM,Vol.37,No.4,Article111.Publicationdate:August2018.ASurveyonAutomatedSoftwareVulnerabilityDetectionUsingMachineLearningandDeepLearning 111:17 Code 70.1% 4.5% Hybrid 25.4% Repository Fig.4. Thetypeofdatasetsinprimarystudies. Table7. Datatypesofdatasetsinvolvedinprimarystudies. Category DataType #Studies Total References Code-based Sourcecode 42 47 [17, 30–33, 36, 38, 42, 49, 55, 62, 64,72,82,84,86–88,90,91,95,97, 98,107,108,124,128,134,138,140, 143, 144, 146, 150, 152, 153, 156– 161] Binarycode 5 [61,76,109,116,145] Repository-based Codechange 8 13 [25,35,45,58,85,94,118,154] Commit 5 [110,113,114,120,147] Hybrid SourceCode+Codechange 3 7 [28,79,136] Commits+CodeChange 2 [60,123] Commits+Bugreports 1 [155] Bugreport+Commits+Emails 1 [24] SUM - - 67(67) - Figure4showsthedistributionofthedatatypesinprimarystudies.Wecanobservethatthe majorityofprimarystudies(70.1%)primarilyfocusonanalyzingthesourcecodeforsoftwarevulner- abilitydetection.Thisindicatesthesignificanceofcode-levelanalysisinidentifyingvulnerabilities. Theutilizationofrepository-leveldata,suchascommithistoryandchangelogs,isalsoprominent, representingasubstantialportion(25.4%)ofprimarystudies.Thissuggeststhatrepository-level informationisconsideredvaluableinvulnerabilitydetection.Additionally,asmallerportion(4.5%) ofthestudiesadoptahybridapproach,combiningbothcode-levelanalysisandrepository-level information.Thesetechniquesleveragethestrengthsofbothdatasourcestoimprovetheaccuracy andeffectivenessofvulnerabilitydetection. Table7elaboratesthedetaileddatatypescategoriesusedinprimarystudies.Thetableshows that 42 primary studies used code-based category and the major data type of this category is Sourcecode[38,42,82,84,86,87,90,143,153,157,158,160].Binarycodeisthesecondmajordata typeincode-basedcategory[61,109,116,145]accountingfor5primarystudies.Regardingthe Repositorybasedcategory,13primarystudiesfocusedonextractingusefulinformationandpatterns bycrawlingdifferentartifactsfromsoftwarerepositoriesfromopensource.Themajorartifactis Codechangeaccountingfor8primarystudies[25,35,45,58,85,94,118,154],andCommit comes asthesecondwith5primarystudies.ThelastcategoryofdatatypesisHybrid wherethestudies usedacombinationofdifferentdatatypesforsoftwaresecurityvulnerabilitydetection,accounting J.ACM,Vol.37,No.4,Article111.Publicationdate:August2018.11N1:i1m8aShiriharzevili,AlvineBoayeBelle,JunjieWang,SongWang,ZhenMing(Jack)Jiang,andNachiappanNagappan Token 29.9% Graph 38.8% 4.5% CommitMetrics 10.4% 16.4% Hybrid Tree t! Fig.5. Differentrepresentationusedbyprimarystudies. for7primarystudies.Ascanbeseen,Sourcecode+Codechangeisthemostdominantdatatype combination[28,79,136]. 4.2.3 RQ2.3.Howinputdataarerepresented? Asnotedinearliersections,researchstudiesfocused onsoftwarevulnerabilitydetectionrelyondiversesourcesofdataanddatatypes.Thishetero- geneitynecessitatestheuseofvariedrepresentationtechniques,whichinturnrequiresdifferent architecturalapproachesanddesignassumptionsforML/DLmodels.Weclassifiedtheinputrepre- sentationofemployeddatasetsintofivebroadcategories,i.e.,Graph-based,Tree-based,Token-based, Metric-based andHybrid.Figure5showsthedistributionofdifferentinputrepresentationsused inprimarystudies.Fromthepiechart,wecanobservethatthemostpopularinputrepresenta- tionistheuseofGraph/Tree-basedrepresentation,accountingforthelargestslice(i.e.,38.8%for Graph-basedand16.4%forTree-based).Token-basedrepresentationfollowsclosely,representinga
substantialportion(29.9%)ofprimarystudies.Hybridrepresentationcombinesmultiplerepresenta- tionsorapproaches,whichmakesupasmallerportion(10.4%).Finally,theuseofCommitMetrics invulnerabilitydetectionhasthesmallestportion(4.5%).Inthefollowingparagraphs,weelaborate oneachcategoryindetail.Graph/Tree-basedrepresentation[17,28,30,36,38,49,61,64,72,85, 87,97,98,107,108,116,134,140,146,150,153,154,157,159,160,160]:allowsforthedetectionof complexpatternsandrelationshipsbetweendifferentcodeelements.Byrepresentingsourcecode asagraphortree,itbecomespossibletocapturenotonlythesyntaxandstructureofthecodebut alsoitssemantics,controlflow,anddataflow.Therearemanygraph/tree-basedrepresentation techniqueslikeAbstractSyntaxTrees(AST)[35,86,90,91,102,142]andCodePropertyGraph (CPG)[38,49,154]usedtotransformsourcecodeintoASTandCPGrepresentations. Token-basedrepresentation[3,33,37,60,79,94,109,118,122,144,155]:treatthesourcecode asstringtokensequencesandthentransformssourcecodeintotokensvectors.Theinputdatais firstsplitintoasequenceoftokens,whicharethenconvertedintonumericalvectorsthatcanbe processedbymachinelearningalgorithms.Tokenizationinvolvesbreakingdownastringoftextor sourcecodeintosmallerunits,ortokens,whichcanthenbeusedasthebasisforfurtheranalysis. Inthecaseofsourcecode,tokensmightincludekeywords,operators,variables,andotherelements oftheprogramminglanguagesyntax. CommitMetrics[110,113,147]:leveragesthemetricsextractedfromcommitstorepresentcode commits.Featuresderivedfromcommits,suchasthesizeofcodechanges,thenumberofmodified lines,thecomplexityofthechanges,ortheprogramminglanguageused,canbeusedasinputs totrainML/DLmodels.Thesemodelscanthenlearnpatternsandrelationshipsbetweencommit characteristicsandthepresenceofvulnerabilities,enablingautomateddetectionbasedonnew commits. J.ACM,Vol.37,No.4,Article111.Publicationdate:August2018.ASurveyonAutomatedSoftwareVulnerabilityDetectionUsingMachineLearningandDeepLearning 111:19 Table8. Distributionofinputrepresentationsinprimarystudies. Category Artifact #Studies Total References Graph/Tree-baSsoeudrcecodeasagraph 22 32(32) [17,30,36,38,49,64,72,85,87,88, 97,98,107,108,134,140,146,150, 153,157,159,160] Sourcecodeasatree 9 [32,82,86,90,91,95,128,138,156] Binarycodeasgraph 2 [61,116] Token-based Sourcecodeasatoken 10 14(14) [33,42,55,60,62,124,143,144,158, 161] Binarycodeasatoken 3 [76,109,145] Textasatoken 1 [155] Hybrid TokenSequence+CommitMetrics 4 8(8) [24,110,114,120] TokenSequence+Termfrequency 1 [123] TokenSequence+Graph 1 [45] Graph+Tree+TokenSequence 1 [84] Token+Tree 1 [152] Commits CommitMetrics 3 3 [110,113,147] SUM - - 57(55) [110,113,147] Hybridrepresentation[24,28,60,79,122,123,136,155]:usesacombinationofdifferentrep- resentationsforsoftwaresecurityvulnerabilitydetection.Combiningdifferentrepresentations ofinputdatacanleadtoamorecomprehensiveandricherinputrepresentationofsourcecode, whichcanimprovetheperformanceofvulnerabilitydetectionmodelsintaskssuchasprediction ordetection.Combiningdifferentrepresentationssuchastoken-basedrepresentationsandgraph- basedrepresentationscanhelpcaptureboththesyntaxandsemanticsofthecode,aswellasthe relationshipsbetweendifferentcomponentsofthecode. Table8showstherepresentationtechniquesdistributedbydifferentartifactsusedbyML/DL models.ItisobservablethatGraph/Tree-basedrepresentationisthemostdominanttechniqueused byprimarystudies,accountingfor32uniqueprimarystudiesintotal.Thesestudiesrepresent theinputtoML/DLmodelsviaSourcecodeasagraph,Sourcecodeasatree,andBinarycodeasa graph.Sourcecodeasagraphisthemajorrepresentationtechniqueusedbyprimarystudies[17,28, 30,36,38,49,61,64,72,85,87,97,98,107,108,116,134,140,146,150,153,154,157,159,160,160] accountingfor22studies.Sourcecodeasatree[32,35,82,86,90,91,95,128,136,138,156]isthe secondmajorrepresentationtechniqueaccountingfor9primarystudies.Someresearchersused Binarycodeasagraph[61,116]tobuildbinary-levelvulnerabilitydetectionmodels,accountingfor 2primarystudies.Thereare14primarystudiesthatusedToken-basedrepresentation,inwhich10 primarystudiesrepresentedsourcecodeasatokensequence,threeprimarystudiesmodeledbinary codeasatoken,andonestudyrepresentedtextastokensequences[155].Hybrid representation has5differenttypesaccountingfor8primarystudies.TokenSequence+CommitMetricsisthemajor artifactusedtoenhancetheinputrepresentationinsoftwarevulnerabilitydetection,accounting for4primarystudies.Itcombinesinformationfromthetokensequenceofthecodeandadditional metricsderivedfromsoftwarecommits.Thisapproachleveragesboththestructuralandhistorical aspectsofthecodetoprovideamorecomprehensiverepresentationforbuildingvulnerability detectionmodels. Commitsisthefourthleastinputrepresentationusedby3primarystudies.Inthisrepresentation, commitcharacteristicsareusedtobuildsoftwarevulnerabilitydetectionmodels.
J.ACM,Vol.37,No.4,Article111.Publicationdate:August2018.11N1:i2m0aShiriharzevili,AlvineBoayeBelle,JunjieWang,SongWang,ZhenMing(Jack)Jiang,andNachiappanNagappan 20 2 15 4 Tree 2 Token 2 2 Hybrid 10 2 Graph 1 2 Commits 4 3 1 5 2 10 7 2 1 2 3 1 1 3 2 1 1 1 1 1 1 1 1 0 2 0 1 1 2 0 1 3 2 0 1 4 2 0 1 5 2 0 1 6 2 0 1 7 2 0 1 8 2 0 1 9 2 0 2 0 2 0 2 1 2 0 2 2 Fig.6. Distributionofdatatyperepresentationsinsoftwarevulnerabilitydetectionstudiesovertime. Figure6showsthedistributionofdatatyperepresentationinsoftwarevulnerabilitydetection studiesovertime.Asshowninthefigure,Graph-basedrepresentationshowsasubstantialpresence comparedtootherinputrepresentationtechniques.Thereareacoupleofreasonsforthistrend. First,graphsprovideanaturalandintuitivewaytorepresentthestructuralrelationshipswithin thesourcecode.Bymodelingthecodeasagraph,therelationshipsbetweenfunctions,classes, methods,andvariablescanbecapturedeffectively.Thisallowsvulnerabilitydetectionalgorithmsto analyzethecodeatahigherlevelofabstractionandcapturecomplexdependenciesandinteractions betweencodeelements.Second,graph-basedrepresentationsenableabetterunderstandingofthe contextinwhichvulnerabilitiesmayexist.Byconsideringthesurroundingcodestructureand dependencies,graph-basedapproachescancapturetheflowofinformationandidentifypotential paths that can lead to vulnerabilities. This contextual understanding helps in identifying code patterns,controlflowpaths,anddatadependenciesthatmayintroducesecurityvulnerabilities. Token-based representationhasalsogainedpopularity,withapeakoccurrencein2021.Thisis becauseitprovidesafine-grainedrepresentationofthecode.Itsimplifiesthecodeanalysisprocess byreducingthecomplexityofthecodetoasequenceoftokens,makingiteasiertoapplytraditional naturallanguageprocessingtechniquesorMLmodels.Itisalsoeasilyapplicabletoawiderangeof programminglanguages.Whilethetokensthemselvesmaydifferacrosslanguages,theconceptof breakingthecodeintodiscreteunitsremainsthesame.Thisversatilityallowsvulnerabilitydetection techniquesbasedontokenrepresentationtobeappliedtodifferentprogramminglanguagesand codebases,whichfurtherincreasestheexternalvalidityofvulnerabilitydetectionmodels.However, thereisaslightdeclinein2022,indicatingpotentialshiftsordiversificationintheselectionof inputrepresentations.Hybrid representationisgainedattentionsince2021,whichsuggeststhat combiningdifferentrepresentationsisfavoredbyresearchersinsoftwarevulnerabilitydetection, potentiallyduetothecomplementarybenefitsprovidedbymultiplerepresentations. 4.2.4 RQ2.4.Howinputdataareembeddedforfeaturespace? Intheprevioussection,wediscussed variousrepresentationtechniques,andinthissection,wefurtherlookatembeddingmethodsthat cantransformtheserepresentationsintoinputsthatcanbeunderstoodbyML/DLmodels.The representationtechniquesareinahuman-readableformat,theycannotbedirectlyinterpretedby machines.Therefore,researchersusedifferentembeddingtechniquestoconverttheserepresenta- tionsintoanumericformat.Wediscusstheembeddingtechniquesinthefollowingparagraphs J.ACM,Vol.37,No.4,Article111.Publicationdate:August2018.ASurveyonAutomatedSoftwareVulnerabilityDetectionUsingMachineLearningandDeepLearning 111:21 Graphembedding Word2vec 25.4% 25.4% 3.0% 11.9% 4.5% N-gramfeatures 6.0% Codetokenembedding Tokenvectorembedding 16.4% 7.5% Onehotembedding Hybrid Others Fig.7. Differentfeatureembeddingtechniquesusedinprimarystudies. basedonthedistributionshowninFigure7.Thefigureillustratesthedistributionoffeatureem- beddingtechniquesusedinprimarystudies.Thechartshowsthefollowingcategoriesandtheir correspondingpercentages:Word2vec(25.4%),Graphembedding(25.4%),Tokenvectorembedding (11.9%),Others(16.4%),Hybrid(7.5%),Onehotembedding(6.0%),Codetokenembedding(4.5%), andN-gramfeatures(3.0%). Word2vec[24,37,62,64,84,85,90,92,94,114,118,120,123,124,144,145,154,155,160,161]:isone ofthemostwidely-usedembeddingtechniquesforsourcecodeembeddingintheexaminedpapers, accountingfor25.4%ofprimarystudies.Thiscanbebecauseithasbeenshowntobeeffective incapturingthesemanticsandrelationshipsbetweendifferentcodecomponents.Word2veccan betrainedoncodecorpustolearnembeddingsfordifferentcodecomponents,suchasvariables, functions,andoperators.Byconsideringthecontextinwhichthesecomponentsappear,Word2vec cancapturethesemanticrelationshipsbetweenthem.Furthermore,Word2vecisacomputationally efficientandscalabletechnique,whichcanbetrainedonlargecodecorpora.Thisisimportantfor sourcecodeembedding,asthecodecorpuscanbemuchlargerthanthetextcorpustypicallyused innaturallanguageprocessing. Graphembedding[17,35,38,49,98,116,136,140,150,153,157]:isanotherwidely-usedembedding techniqueamongtheprimarystudies,accountingfor25.4%ofprimarystudies,whichismostlyused bygraphneuralnetworks.Thiscanbebecauseitcancapturethestructuralrelationshipsbetween differentcodecomponents,suchasfunctions,classes,andmethods.Incontrasttotoken-based
representationsorsequence-basedrepresentations,graphembeddingcanexplicitlyrepresentthe connectionsanddependenciesbetweendifferentcodecomponents.Inagraph-basedrepresentation, codecomponentsarerepresentedasnodes,andtherelationshipsbetweenthemarerepresentedas edges.Thisallowsforamorefine-grainedrepresentationofthecodestructure. Token vector embedding [25, 32, 33, 45, 58, 60, 91, 95, 102, 138, 142, 143]: is also a popular techniqueusedbyprimarystudiesaccountingfor11.9%ofexaminedpapers.Inthistechnique, inputisconvertedintoasequenceoftokensandeachtokenistransformedintoanumericvalue. Then,thesevaluesarefedintoML/DLmodelsforfurthercomputations. Onehotembedding[55,60,76,109]:isatypicalwayforencodingcategoricaldata,inwhich eachcategoryisrepresentedbyabinaryvectorofzerosandones.Thismethodcanalsobeusedto encodesourcecodeforvulnerabilitydetection,whichaccountsfor6%ofstudies. Codetokenembedding[32,33,95]:isusedtorepresentsourcecodetokensasdensevectorsina continuousvectorspace.Codetokenembeddingcapturesthesemanticandsyntacticlinksbetween tokensbytransferringthemtoalower-dimensionalvectorspace,asopposedtoonehotencoding, whichrepresentseachtokenasasparsebinaryvector. J.ACM,Vol.37,No.4,Article111.Publicationdate:August2018.11N1:i2m2aShiriharzevili,AlvineBoayeBelle,JunjieWang,SongWang,ZhenMing(Jack)Jiang,andNachiappanNagappan N-gramfeatures[79,128]:isamethodofexpressingcodesnippetsasfixed-lengthdensevectors, eachvectorrepresentingann-gramoftokens.N-gramsaresequencesofntokens,suchaswordsor letters,thatcapturelocalcontextandinterdependencebetweenneighboringtokens.Weobserved that3%ofprimarystudiesuseN-gramfeaturesforembedding. Hybrid[28,64,84,85,154]:Wefindthat7.5%ofprimarystudiesusemultipleembeddingtechniques toconvertinputstoML/DLmodels.Differentembeddingtechniquescapturedifferentaspectsofthe data.Bycombiningmultipletechniques,researcherscanleveragethecomplementaryinformation providedbyeachtechnique.Forexample,someembeddingtechniquesmayfocusonsyntax,while othersmaycapturesemanticorcontextualinformation. Others[30,42,61,72,110,113,123,147,152,156,158]:Theremaining16.4%thatemergeseldom anddonotbelongtoanygroupareclassifiedasOthers.Forexample,Zhangetal.[152]customizes thegraphCodeBERT[54]toproposeagraph-guidedmaskedattentionmechanismforvulnerability detectioninwhichitcapturesvariabledependencyrelationshipsandintegratesthegraphstructure intotheTransformermodel. AnswertoRQ2 (1) 65.7% of primary studies use benchmark data for software vulnerability detection. This can be because benchmark datasets are readily accessible to all researchers and can facilitate the reproducibility of studies. (2) The most common data type among the examined vulnerability detection studies is Code-based data type, accounting for 47 studies. In this category, Source code is the most prominent sub-type accounting for 42 studies. (3) Graph-based and Token-based input representations are the most popular input representation techniques used by primary studies accounting for 38.8% and 29.9% of primary studies respectively. (4) Graph embedding and Word2vec are the two most widely used embedding tech- niques used in primary studies accounting for 25.4% of studies respectively. 4.3 RQ3.WhataretheML/DLmodelsusedforsoftwarevulnerabilitydetection? In this section, we provide detailed information about the various ML/DL models utilized for software vulnerability detection. Initially, we present an analysis of the usage distribution of ML/DLmodelsbasedonprimarystudies.Subsequently,wedelveintothedistributionoftheusage of DL models used in primary studies over time. However, we have not extensively analyzed thedistributionofMLmodelssincetheirprevalenceisrelativelysmallcomparedtoDLmodels. Nonetheless, we provide a comprehensive list of classic ML models that have been commonly employedinprimarystudies. FromFigure8,itisobservablethat79.1%ofstudiesareusingDLmodelsforsoftwarevulnerability detection[4,28,32,33,60,64,79,92,94,95,98,116,118,122,134,136,138,154]whilemerely16.4% ofstudiesuseclassicMLmodels[72,109,113,114,120,124,142,143].Also,alimitednumberof studiesuseLanguagemodelsdenotedasLM [112,128]andDistanceMeasuresdenotedasDM [61,144]. ThegraphinFigure9illustratestheusagetrendofDLmodelsindetectingsoftwarevulnerabilities from2016to2022.Accordingtothetrend,DLmodelswerefirstintroducedin2016forvulnerability detection,sincethentheuseofRNNsforvulnerabilitydetectionshowedanupwardtrend.The graphalsodemonstratesarisingtrendinusingGNNsforvulnerabilitydetectionfrom2020to2022. J.ACM,Vol.37,No.4,Article111.Publicationdate:August2018.ASurveyonAutomatedSoftwareVulnerabilityDetectionUsingMachineLearningandDeepLearning 111:23 DL 79.1% 1.5% 3.0% LM DM 16.4% ML Fig.8. Distributionofmodelsusedinprimarystudies.DMstandsforDistanceMeasureandLMstandsfor LanguageModel. 25 1 20 Transformers 8 RNN 15 Hybrid 2 3 General GNN 10 3 CNN Attention 5 3 2 1 6 11 5 1 1 1 1 1 1 0 2 0 1 61 2 0 1 71 1 2 0 1 81 1 2 0 1 92 2 0 2 02 2 0 2 11 2 0 2 23 Fig.9. TrendofDLmodelsovertime.
ThiscanbebecauseGNNsaremorepowerfulthanRNNsindetectingvulnerabilities,astheycan capturemoremeaningfulandsemanticrepresentationsofinputsourcecode.Sincevulnerability typesoftenhavecomplexstructures,GNNsareanexcellentfitfordetectinghiddenstructural information. Table9showsthedistributionofDLmodelsusedinprimarystudies.Asshowninthetable, LSTMisthemostfrequentlyusedrecurrentmodel,appearingin8studies.BiLSTMandBGRUare alsopopularmodelswith8and6studiesrespectively.ItisalsoobservablethatGGNNisthemost prevalentgraph-basedmodel,appearingin4studies.GCN,GAT,andDR-GCNarealsocommonly usedaccountingfor4,3,and2studiesrespectively.Thepresenceofthesemodelshighlightsthe importanceofcapturinggraphstructuresandrelationshipsbetweencodeelementsinvulnerability detection. Attention models were also used in 7 primary studies. Attention mechanisms allow modelstopaymoreattentiontospecificpartsofthecodeorinputthataremorelikelytocontain vulnerability-related patterns. This ability to localize relevant information helps identify and understandthefactorscontributingtovulnerabilitiesmoreeffectively.CNNsareusedin6studies. Whilenotasprevalentasrecurrentorgraphmodels,CNNsarestillconsideredeffectiveforcapturing localpatternsandfeaturesinvulnerabilitydetectiontasks.GeneralmodelslikeDBN,AutoEncoders, Memory Neural Networks, GAN, and Para2Vec are also used to a lesser extent, indicating the explorationofdiversedeeplearningtechniquesinvulnerabilitydetection.Transformersarethe leastfrequentfamilyofDLmodelsusedinprimarystudies.Thisisbecausetheyhavebeenrecently introducedforsoftwarevulnerabilitydetection.Transformersareeffectiveinthisdomainsince J.ACM,Vol.37,No.4,Article111.Publicationdate:August2018.11N1:i2m4aShiriharzevili,AlvineBoayeBelle,JunjieWang,SongWang,ZhenMing(Jack)Jiang,andNachiappanNagappan theygeneratecontextualizedrepresentationsforeachtokenintheinputsequence.Byconsidering thesurroundingtokensandtheirinteractions,transformerscapturerichcontextualinformation, whichiscrucialforunderstandingvulnerabilitiesthatdependontheoverallcontextofthecodeor vulnerability-relatedtext. Table10showsthedistributionofMLmodelsusedinprimarystudies.Asshowninthefigure, RandomForestisthemostfrequentlyusedMLmodel,appearingin7studies.SVM,NaiveBayes,and LogisticRegressionarepopularchoices,with6,5,and4occurrences,respectively.N-Grammodels areusedin1study,indicatingtheirapplicationincapturingsequentialpatternsandlanguage- basedfeaturesinvulnerabilitydetection.N-Grammodelsarecommonlyusedfortextanalysis and have been adapted for code analysis tasks. Distance measures are utilized in 2 studies for vulnerabilitydetection.Thesemetricshelpquantifythesimilarityordissimilaritybetweencode elementsorfeatures,enablingtheidentificationofpotentiallyvulnerablecodesegmentsbasedon theirproximitytoknownvulnerabilities. Table9. DistributionofDLmodelsinprimarystudies. Category ModelName #Studies Total References RecurrentModels LSTM 8 31(21) [32,33,94,95,134,138,156,158] BiLSTM 8 [64,86,88,90,91,134,160,161] BGRU 6 [64,86,87,134,145,161] GRU 4 [58,64,85,134] RNN 3 [42,76,134] BRNN 2 [76,134] GraphModels GGNN 4 18(15) [35,36,136,159] GCN 4 [28,49,84,150] GAT 3 [28,45,49] DR-GCN 2 [98,157] RGCN 1 [153] FS-GNN 1 [17] K-GNN 1 [28] DGCNN 1 [116] GGRN 1 [154] AttentionModels - 7 7 [30,38,79,85,97,152,160] ConvolutionalModels CNN 6 6 [42,60,62,82,145,161] GeneralModels DBN 1 5(4) [138] AutoEncoders 1 [76] MemoryNeuralNetwork 1 [60] GAN 1 [55] Para2Vec 1 [76] Transformers Seq2SeqTransformer 1 4(4) [25] GraphCodeBERT 1 [140] CodeBERT 1 [110] HGT 1 [146] SUM - - 71(49) - J.ACM,Vol.37,No.4,Article111.Publicationdate:August2018.ASurveyonAutomatedSoftwareVulnerabilityDetectionUsingMachineLearningandDeepLearning 111:25 Table10. DistributionofMLandothermodelsinprimarystudies. Category ModelName Studies Total References ClassicMLModels RandomForest 7 35(11) [24,72,113,123,124,147,155] SVM 6 [24,114,120,123,124,155] NaiveBayes 5 [24,72,113,124,155] LogisticRegression 4 [72,113,123,155] K-NN 3 [24,124,155] GradientBoosting 2 [24,155] DecisionTree 2 [72,124] AdaBoost 2 [24,155] PCA 1 [143] KernelMachine 1 [109] ADTree 1 [113] MLP 1 [113] LanguageModels N-Gram 1 1 [128] DistanceMetrics DistanceMeasure 2 2 [61,144] SUM - - 38(14) - AnswertoRQ3 (1) 79.1% of primary studies use DL models for vulnerability detection while merely 16.4% of the primary studies use classic ML models. (2) RNNs and GNNs are by far the most popular DL-based models in software vulner- ability detection accounting for 28% and 22% of primary studies. (3) LSTM is the most popular architecture in RNN-based models. (4) Graph-based models are the second most popular models used in software security vulnerability detection accounting for 15 studies. In this family, GGNN is the most popular architecture. (5) Besides DL models, ML models are popular for software vulnerability detection. Random Forest is the most popular model accounting for 7 studies.
4.4 RQ4.Whatisthemostfrequenttypeofvulnerabilitycoveredinprimarystudies? Softwarevulnerabilitydetectiondatasetssupportdifferentvulnerabilitytypes.Forexample,NVD andSARDbenchmarktogethersupport96typesofvulnerabilities.Thisresearchquestionintends tosummarizewhatisthemostpopularvulnerabilitytypescoveredbyprimarystudiesandwhat is their frequency. Table 11 shows the statistics regarding the vulnerability types. The column CWE-TypeindicatesthetypeofCWE4.TherealsoexistsanumericalscoreforsometypesofCWEs, whichindicatetheweakness’severity.Alargervalueindicatesahigherlevelofdangerousness andseverity5.PleasenotethatsomefrequenttypesdonothaveaCWEscore,sowedenotethem as“-”.TherearemanycategoriesontheCWEwebsiteforvulnerabilitycategorizationincluding 4https://cwe.mitre.org/ 5https://cwe.mitre.org/top25/archive/2021/2021_cwe_top25.html J.ACM,Vol.37,No.4,Article111.Publicationdate:August2018.11N1:i2m6aShiriharzevili,AlvineBoayeBelle,JunjieWang,SongWang,ZhenMing(Jack)Jiang,andNachiappanNagappan categorizationbysoftwaredevelopment,categorizationbyHardwaredesign,andcategorizationby research concepts. The categorization shown in Table 11 is based on categorization by research conceptsasthiscategorizationisaperfectmatchforvulnerabilitytypesreportedinprimarystudies. Table11indicatesthatthevulnerabilitycategorythatreceivesthehighestattendanceisrelated totheimpropercontrolofaresourcethroughitslifetime(CWE-664),withatotalof42studies(18 uniquestudies).Thiscategoryprimarilyinvolvesmanagingasystem’sresources,whicharecreated, utilized,anddisposedofaccordingtoapredefinedsetofinstructions.Whenasoftwaresystem failstofollowtheseguidelinesforresourceusage,itcanleadtounexpectedbehaviorsthatcreate potentiallyhazardoussituations.Attackerscantakeadvantageofthesesituationstoexploitthe softwaresystemfortheirownpurposes.ItisobservablethatCWE-119[17,25,28,38,42,45,76,88, 90,95,109,122,136,145]isthemostfrequentvulnerabilitytypeaddressedbytheprimarystudies. Thisvulnerabilityoccurswhenasoftwaresystemattemptstoaccessorwritetoamemorylocation outsidethepermittedboundaryofthesystem’sbuffer.Attackerscanexploitthisvulnerabilityby controllingmemorylocationsandexecutingtheirowncodeorcommands,effectivelymanipulating thesystem’smemory.Althoughthescoreforthisvulnerabilitytypeisnothigh,thefrequencyof primarystudiesaddressingitcanbeavaluableindicatorofitssignificanceintermsofdetecting andaddressingthevulnerability.Withinthiscategory,themostseverevulnerabilitytypewitha scoreof65.93isCWE-787,whichisdiscussedin5primarystudies.Thisvulnerabilityisconsidered severeandcriticalbecauseitcanresultinthecorruptionofdata,systemcrashes,ortheexecution ofmaliciouscode.Itoccurswhenasoftwaresystemattemptstowritedatabeyondtheintended buffer, either before the beginning or past the end of the buffer. CWE-22 is another frequent vulnerabilitytypeaddressedbyprimarystudiesaccountingfor4primarystudies[17,28,45,49]. Thisvulnerabilityisreferredtoas“PathTraversal”,whereattackersexploitspecialelements,such as “..” or “/”, to construct their own path and gain unauthorized access to restricted locations. Thisvulnerabilityisparticularlycriticalbecauseattackerscanuseittomodifyrestrictedfilesor directoriesinvulnerablesoftwaresystems,potentiallyleadingtosystemcrashesbyuploading maliciouscodeorcommands.Incriticalfinancialsoftwaresystems,attackerscanevengainaccess tocustomers’bankaccountinformation.Giventheseverityofthisvulnerabilitytypewithascore of14.69andthefrequencyofpaperscoveringit,detectingandaddressingthisvulnerabilityis ofutmostimportance.Therefore,moreadvancedML/DLmodelsareneededtoeffectivelydetect thistypeofvulnerability.TheleastfrequentvulnerabilitytypeofthisfamilyisCWE-120[17,122] whichisaclassicbufferoverflow,accountingfor2primarystudies.Thisvulnerabilityoccurswhen thesoftwareattemptstocopyavaluetotheoutputbufferwithoutfirstvalidatingitssize.Ifthe rangeofthevalueistoolargeforthelengthoftheoutputbuffer,abufferoverflowcanoccur.While thedetectionofbufferoverflowcanbechallenginginsomecases,staticbugdetectiontoolshave alreadyaddressedthisvulnerability,anddetectionmethodsarecurrentlyavailable. ImproperNeutralization-(CWE-707)Isthesecondmajorfamilyofvulnerabilitytypescovered by16primarystudies,including9uniqueprimarystudies.Inthistype,theattackersexploitinput andoutputdatawhentheyaremalformedornotvalidatedproperly.Thereareseveralscenarios that can lead to data neutralization weaknesses. The first scenario involves checking whether inputandoutputdataaresafe,whilethesecondscenarioinvolvesfilteringtheinputandoutput datatoensurethatanydatatransformationisdonesafely.Thethirdscenarioinvolvespreventing externalattackersfromdirectlymanipulatingtheinputandoutputdata,whilethefourthscenario relatestothelackofprocessinginputandoutputdatainanycircumstances.Allofthesescenarios canbetherootcausesofdataneutralizationweaknesses.Ascanbeseen,CWE-20isthemost
frequenttypeofvulnerabilityaccountingfor6primarystudies.CWE-20referstoasituationwhere inputvalidationisnotdoneproperlyinsoftwaresystems,makingthemvulnerabletoattacksby maliciousindividualswhocanexploitinputdata.Thisoccurswhentheinputdataisnotverified J.ACM,Vol.37,No.4,Article111.Publicationdate:August2018.ASurveyonAutomatedSoftwareVulnerabilityDetectionUsingMachineLearningandDeepLearning 111:27 Table11. Differentvulnerabilitytypescoveredinprimarystudies. Category CWE-Type SeverityScore #Studies Total References CWE-664 CWE-119 5.84 14 42(18) [17,25,28,38,42,45,76,88,90,95,109,122,136,145] CWE-787 65.93 5 [17,28,45,136,146] CWE-22 14.69 4 [28,45,49,136] CWE-125 24.9 4 [17,25,28,136] CWE-400 - 4 [28,136,146,160] CWE-200 4.74 3 [25,45,136] CWE-121 - 3 [17,122,145] CWE-122 - 3 [17,31,122] CWE-120 - 2 [17,122] CWE-707 CWE-20 20.47 6 16(9) [25,28,45,122,136,146] CWE-78 19.55 5 [28,49,86,136,146] CWE-89 19.54 3 [49,72,136] CWE-79 46.84 2 [72,136] CWE-682 CWE-190 7.12 5 5 [28,45,136,146,160] CWE-703 CWE-476 6.54 4 4 [17,25,122,136] CWE-284 CWE-284 - 2 2 [3,25] CWE-691 CWE-362 - 2 2 [25,160] CWE-1215 CWE-129 - 1 1 [146] - CWE-789 - 1 1 [146] SUM - - - 73(21) - tobesafeorinlinewiththepredefinedspecifications.Theseverityandoccurrenceofthisissue aresignificant,highlightingtheneedforitsdetectionasitcanposecriticalrisks.CWE-78isthe secondmajorvulnerabilitytypecoveredby5primarystudies[28,49,86,136,146].Thiscategory of security vulnerability pertains to OS command injection, in which an external attacker can constructanOScommandbyusinginputdatafromcomponentsthathavenotbeenadequately verified. The attacker can then execute harmful commands, potentially causing the system to behaveunexpectedlyorcrash,andputtingitinahazardousstate. AnswertoRQ4 (1) The most frequent type of vulnerabilities covered in primary studies is Improper Control of a Resource Through its Lifetime-(CWE-664) accounting for 18 unique pri- mary studies. CWE-119: Improper Restriction of Operations within the Bounds of a Memory Buffer is the most frequent type of vulnerability in this category account- ing for 14 primary studies, and CWE-787: Out-of-bounds Write comes subsequently covered by 5 primary studies. The least frequent type of vulnerability is CWE-120 covered by 2 studies. (2) Improper Neutralization(CWE-707) is the second major family of vulnerability types covered by 9 unique primary studies in total. In this family, CWE-20: Improper In- put Validation is the most frequent type covered by 6 primary studies, and CWE-78: Improper Neutralization of Special Elements used in an OS Command (‘OS Command Injection’) comes next with 5 primary studies. (3) Some vulnerability types have a high CVSS score while not sufficiently addressed by existing vulnerability detection studies including but not limited to CWE-79 and CWE-89. J.ACM,Vol.37,No.4,Article111.Publicationdate:August2018.11N1:i2m8aShiriharzevili,AlvineBoayeBelle,JunjieWang,SongWang,ZhenMing(Jack)Jiang,andNachiappanNagappan 4.5 RQ5.Whatarepossiblechallengesandopendirectionsinsoftwarevulnerability detection? Wehavesummarizedthechallengesfrompreviousstudiesintofivedifferentcategories,whichare discussedasfollows. Challenge1:SemanticRepresentation.Thebiggestchallengeinvulnerabilitydetectionthrough learningistheinadequatemodelingofthecomprehensivesemanticsofcomplexvulnerabilitiesby currentmodels[28,30,32,33,38,60,64,82,86,87,97,107,108,116,128,138,140,146,153,154,156]. Thesevulnerabilitiesoftenexhibitintricatecharacteristicsandpatternsthatarenotfullycaptured byexistingML/DLmodelsthattreatsourcecodesnippetsasalinearsequencelikenaturallanguage, oronlypartiallyrepresentsourcecodesnippets.Unlikenaturallanguage,thesourcecodeofreal- world projects contains structural and logical information that must be considered by ML/DL modelsusingAST,dataflow,andcontrolflow.Therefore,currentML/DLapproachesfallshortof identifyingcomplexvulnerabilitypatterns. Challenge 2: Prediction Granularity. The ability of DL models to identify the location of vulnerabilities is influenced by the level of granularity in their inputs. Current DL models use a coarser level of granularity, such as method and file, for vulnerability detection. To achieve finer-grainedinputs,programslicingisnecessary,butitposesachallenge.Thecrucialquestionis howtoperformprogramslicingeffectivelytoeliminateunwantednoiseininputdataandprovide morespecificinputs.Currenttools[17,35,36,45,84,91,113,159,160]concentrateonlibrary/API functioncalls,arithmeticoperations,andpointerusages,butthisapproachisnotsufficientsince notallvulnerabilitiesoriginatefromtheseslicingcriteria. Challenge3:FalsePositiveRemoval.Themostcommonlyusedtoolsfordetectingsoftware vulnerabilitiesandbugsarestaticanalyzers[55,72,85,150,155,158,160].Thesetoolsutilizehard- codedrulesthataredefinedbyexpertstomodeltheruntimebehaviorofaprogramwithoutthe
needforcompilation.Thisapproachhasseveralbenefits,suchaseffectivelyidentifyingthelocation ofvulnerabilitiesinsourcecodes,whichischallenginginlarge-scaleprojectswiththousandsoffiles andartifacts.Additionally,staticanalyzersareusedattheearlystageofthesoftwaredevelopment process,whichhelpsreducesoftwaremaintenancecosts.However,relyingonexpert-definedrules comeswithahighfalse-positiverate,astheserulesmaynotbegeneralizabletonewvulnerabilities thathaveintricateandsophisticatedprogramsemantics.Anothersignificantissueisthatdefining andupdatingrulesisalabor-intensiveandtime-consumingprocessthatrequiresexpertstohave in-depthknowledgeofemergingvulnerabilities.Thatiswhydata-drivenvulnerabilitydetection hasemergedtoovercometheaforementionedchallenges[55,72,85,150,155,158,160]. Challenge 4: Lack of Training Data. A significant weakness of DL models, particularly in softwarevulnerabilitydetection,istheirinsatiableneedfordata[24,90,95,110,147].Indomains suchasimageclassification,thereisanamplesupplyoflabeleddata,makingitpossibletotrain DLmodelseffectively.Furthermore,therearemanypre-trainedmodelsavailablethatcanbefine- tunedfordetectiontasks.However,insoftwarevulnerabilitydetection,datascarcityisamajor problemsincelabelinggroundtruthinformationisachallengingtask.Toobtaintrainingdata, multiple online platforms such as Stack Overflow, GitHub, and issue tracking or bug tracking systemsareused.Whiletheseplatformscontainbillionsofrecords,thelabelingprocessisdifficult and is often done manually. One possible solution is the automatic labeling of data, but this approachischallengingasitoftengeneratesmanyfalsepositives.Additionally,someresearchers useunsupervisedclassificationforvulnerabilitydetection,butthismethodalsosuffersfromlimited precision. J.ACM,Vol.37,No.4,Article111.Publicationdate:August2018.ASurveyonAutomatedSoftwareVulnerabilityDetectionUsingMachineLearningandDeepLearning 111:29 Challenge5:LackofModelInterpretability.InterpretabilityinDLmodelsreferstotheabilityto understandandexplainthedecisionsmadebythemodel[40,105].Inthecontextofsoftwarevulner- abilitydetection[84,97,161],thereareseveralchallengesthatmakeinterpretabilitychallengingfor DLmodels.First,sourcecodecanbehighlycomplex,especiallyinlargesoftwareprojects.Itoften consistsofmultiplefiles,functions,anddependencies,makingitdifficulttoextractmeaningful andconciseexplanationsfromthecode[66].Softwaresystemsaredynamicandundergochanges overtime.Codeisoftenmaintained,updated,andrefactored,whichcanintroducecomplexitiesin interpretingthedecisionsmadebyAImodels.Themodel’sexplanationsmaynotbeapplicableto thecurrentversionofthecodeifithasevolvedsincethemodel’straining. AnswertoRQ5 (1) Current models inadequately capture the comprehensive semantics of complex vul- nerabilities, as they fail to consider the structural and logical information present in source code snippets. Existing ML/DL models treat source code as a linear sequence, which limits their ability to identify intricate vulnerability patterns. (2) DL models often use a coarse level of granularity for vulnerability detection, such as method and file level. Achieving finer-grained inputs requires effective program- slicing techniques to eliminate noise and provide more specific inputs. Current ap- proaches focus on certain slicing criteria, but vulnerabilities can originate from other sources as well. (3) DL models require a significant amount of labeled data for effective training. How- ever, in software vulnerability detection, there is a scarcity of labeled data due to the challenging task of manual labeling. Automatic labeling approaches often generate false positives, and unsupervised classification suffers from limited precision. 5 THREATSTOVALIDITY External Validity. One of the major threats to the external validity of our work is the data collection internal. We collect data in an 11 years old period from 2011 to 2022 to coverall all possiblestudiespublishedduringthisperiod.Anothersourceofthreattoexternalvalidityisthe coverage of the input data types in software vulnerability detection. To tackle this threat, we focusedonsourcecodesnippetsaswellasrepositorydata,i.e.,datathatcanbeextractedfrom opensourceincludingGitHubandCVE. InternalValidity.Oneofthemajorthreatstotheinternalvalidityofourworkistheautomatic collectionofdataforanalysis.Ourtechniquefordatacollectionisautomatedatitsinitialstepsin whichwemaymisssomeimportantvulnerabilitydetectionpapers.Infact,wedevelopedasetof scriptsthatallowedustoextractpapersgivenan11-yearperiod.Eventhoughthesubsequentsteps aremanuallysupervised,stilltheautomaticfilteringsuffersfromthisissue.Thesecondimportant issuewithourdatacollectionispossiblebias.Therootcauseofbiasisunavoidabledisagreements duringpaperclassificationastworesearchershaveworkedtogethertocategorizepapersbasedon title,abstract,andcontentofpapers.Incasetheresearcherscouldnotcomeupwithanagreement, thethirdresearcherjointoresolvethedifferenceswhichsomehowrelaxestheissue. Construct Validity. The major threat to the construct validity of our survey is the level of granularity of the analysis we conducted for each primary study. For each study, we deeply analyzedtheartifactsexplainedinthepaperandshowtheirdistributionastablesandgraphs.For
example,intermsofsourcesforbenchmarkdata,wedeeplyanalyzed17sourcesaccountingfor53 J.ACM,Vol.37,No.4,Article111.Publicationdate:August2018.11N1:i3m0aShiriharzevili,AlvineBoayeBelle,JunjieWang,SongWang,ZhenMing(Jack)Jiang,andNachiappanNagappan primarystudiesoverall.Thesecondthreattotheconstructvalidityisthedegreeofcoveragefor eachprimarystudy.Weanalyzedeachprimarystudyfrom5aspectsincludinginputdata,input representation,embeddingtechniques,models,vulnerabilitytypes,andwhetherthestudysupports theinterpretabilityofvulnerabilitydetectionmodelsornot. 6 CONCLUSION Inthisstudy,weconductedasystematicsurveyon67primarystudiesusingML/DLmodelsfor software security vulnerability detection. We collected the papers from different journals and conferencevenuesincluding25conferencesand12journals.Ourreviewisestablishedbasedonfive majorresearchquestionsandasetofsub-researchquestions.Wedevisedtheresearchquestionsin acomprehensivemannerwheretocovervariousdimensionsofsoftwarevulnerabilitydetection. Ouranalysisofprimarystudiesindicatedthatthereisaboomingtrendinthegrowthofusing ML/DLmodelsforsoftwarevulnerabilitydetection.Ourdeepanalysisofdatasourcesofprimary studiesrevealedthat65.7%ofstudiesusebenchmarkdataforsoftwarevulnerabilitydetection. Wealsofind6broadcategoriesofDLmodelsalongwith14classicMLmodelsusedinsoftware vulnerability detection. The categories of DL models are classified as recurrent models, graph models,attentionmodels,convolutionalmodels,generalmodels,andtransformermodels.RNNs arebyfarthemostpopularDNNsinsoftwarevulnerabilitydetection.Ouranalysisalsofindsthat RNNswithLSTMcellsarethemostpopularnetworkarchitecturesinrecurrentmodels,accounting for8primarystudies.Inthecategoryofgraphmodels,GGNNisthemostpopularDLmodelused by 4 primary studies. Our results on vulnerability types reveal that the most frequent type of vulnerabilitycoveredinexistingstudiesisImproperControlofaResourceThroughitsLifetime -(CWE-664)accountingfor18primarystudies.Inconclusion,wehaveidentifiedacollectionof ongoingchallengesthatnecessitatefurtherexplorationinfuturestudiesinvolvingtheutilization ofML/DLmodelsforsoftwarevulnerabilitydetection. REFERENCES [1] AleksiAaltonenandYiwenGao.2021. DoestheOutsiderHelp?TheImpactofBugBountyProgramsonData Breaches. TheImpactofBugBountyProgramsonDataBreaches(August20,2021).FoxSchoolofBusinessResearch Paper(2021). [2] FaranakAbri,SimaSiami-Namini,MahdiAdlKhanghah,FahimehMirzaSoltani,andAkbarSiamiNamin.2019.Can machine/deeplearningclassifiersdetectzero-daymalwarewithhighaccuracy?.In2019IEEEinternationalconference onbigdata(BigData).IEEE,3252–3259. [3] GeorgiosAivatoglou,MikeAnastasiadis,GeorgiosSpanos,AntonisVoulgaridis,KonstantinosVotis,andDimitrios Tzovaras.2021.Atree-basedmachinelearningmethodologytoautomaticallyclassifysoftwarevulnerabilities.In 2021IEEEInternationalConferenceonCyberSecurityandResilience(CSR).IEEE,312–317. [4] WenyanAn,LiweiChen,JinxinWang,GewangziDu,GangShi,andDanMeng.2020.AVDHRAM:AutomatedVulner- abilityDetectionbasedonHierarchicalRepresentationandAttentionMechanism.In2020IEEEIntlConfonParallel& DistributedProcessingwithApplications,BigData&CloudComputing,SustainableComputing&Communications, SocialComputing&Networking(ISPA/BDCloud/SocialCom/SustainCom).IEEE,337–344. [5] PaulineAnthonysamy,AwaisRashid,andRuzannaChitchyan.2017.Privacyrequirements:present&future.In2017 IEEE/ACM39thinternationalconferenceonsoftwareengineering:softwareengineeringinsocietytrack(ICSE-SEIS).IEEE, 13–22. [6] ÖmerAslan,SemihSerkantAktuğ,MerveOzkan-Okay,AbdullahAsimYilmaz,andErdalAkin.2023.Acomprehensive reviewofcybersecurityvulnerabilities,threats,attacks,andsolutions.Electronics12,6(2023),1333. [7] AlbertoBacchelliandChristianBird.2013.Expectations,outcomes,andchallengesofmoderncodereview.In2013 35thInternationalConferenceonSoftwareEngineering(ICSE).IEEE,712–721. [8] GuruBhandari,AmaraNaseer,andLeonMoonen.2021.CVEfixes:automatedcollectionofvulnerabilitiesandtheir fixesfromopen-sourcesoftware.InProceedingsofthe17thInternationalConferenceonPredictiveModelsandData AnalyticsinSoftwareEngineering.30–39. [9] YingzhouBi,JiangtaoHuang,PenghuiLiu,andLianmeiWang.2023.BenchmarkingSoftwareVulnerabilityDetection Techniques:ASurvey.arXivpreprintarXiv:2303.16362(2023). J.ACM,Vol.37,No.4,Article111.Publicationdate:August2018.ASurveyonAutomatedSoftwareVulnerabilityDetectionUsingMachineLearningandDeepLearning 111:31 [10] LeylaBilgeandTudorDumitraş.2012.Beforeweknewit:anempiricalstudyofzero-dayattacksintherealworld.In Proceedingsofthe2012ACMconferenceonComputerandcommunicationssecurity.833–844. [11] PaulEBlack.2017.Sard:asoftwareassurancereferencedataset.(2017). [12] HaroldBooth,DougRike,andGregoryAWitte.2013.Thenationalvulnerabilitydatabase(nvd):Overview.(2013). [13] MehranBozorgi,LawrenceKSaul,StefanSavage,andGeoffreyMVoelker.2010.Beyondheuristics:learningtoclassify
vulnerabilitiesandpredictexploits.InProceedingsofthe16thACMSIGKDDinternationalconferenceonKnowledge discoveryanddatamining.105–114. [14] UIBugzilla’s.2021.Bugzilla.(2021). [15] CristianCadar,DanielDunbar,DawsonREngler,etal.2008. Klee:unassistedandautomaticgenerationofhigh- coveragetestsforcomplexsystemsprograms..InOSDI,Vol.8.209–224. [16] GerardoCanfora,AndreaDiSorbo,SaraForootani,MatiasMartinez,andCorradoAVisaggio.2022.Patchworking: Exploringthecodechangesinducedbyvulnerabilityfixingactivities.InformationandSoftwareTechnology142(2022), 106745. [17] SicongCao,XiaobingSun,LiliBo,RongxinWu,BinLi,andChuanqiTao.2022.MVD:Memory-RelatedVulnerability DetectionBasedonFlow-SensitiveGraphNeuralNetworks.arXivpreprintarXiv:2203.02660(2022). [18] BengtCarlssonandDejanBaca.2005. Softwaresecurityanalysis-executionphaseaudit.In31stEUROMICRO ConferenceonSoftwareEngineeringandAdvancedApplications.IEEE,240–247. [19] SaikatChakraborty,RahulKrishna,YangruiboDing,andBaishakhiRay.2021. Deeplearningbasedvulnerability detection:Arewethereyet.IEEETransactionsonSoftwareEngineering(2021). [20] Yung-YuChang,PavolZavarsky,RonRuhl,andDaleLindskog.2011. Trendanalysisofthecveforsoftware vulnerabilitymanagement.In2011IEEEthirdinternationalconferenceonprivacy,security,riskandtrustand2011IEEE thirdinternationalconferenceonsocialcomputing.IEEE,1290–1293. [21] HaipengChen,JingLiu,RuiLiu,NoseongPark,andVSSubrahmanian.2019. VEST:ASystemforVulnerability ExploitScoring&Timing..InIJCAI.6503–6505. [22] HaipengChen,RuiLiu,NoseongPark,andVSSubrahmanian.2019.Usingtwittertopredictwhenvulnerabilitieswill beexploited.InProceedingsofthe25thACMSIGKDDinternationalconferenceonknowledgediscovery&dataMining. 3143–3152. [23] JinfuChen,PatrickKwakuKudjo,SolomonMensah,SelasieAformaleyBrown,andGeorgeAkorfu.2020.Anautomatic softwarevulnerabilityclassificationframeworkusingtermfrequency-inversegravitymomentandfeatureselection. JournalofSystemsandSoftware167(2020),110616. [24] YangChen,AndrewESantosa,AngMingYi,AbhishekSharma,AsankhayaSharma,andDavidLo.2020.Amachine learningapproachforvulnerabilitycuration.InProceedingsofthe17thInternationalConferenceonMiningSoftware Repositories.32–42. [25] ZiminChen,SteveKommrusch,andMartinMonperrus.2021. NeuralTransferLearningforRepairingSecurity VulnerabilitiesinCCode.arXivpreprintarXiv:2104.08308(2021). [26] ZiminChen,SteveKommrusch,andMartinMonperrus.2022. Neuraltransferlearningforrepairingsecurity vulnerabilitiesinccode.IEEETransactionsonSoftwareEngineering49,1(2022),147–165. [27] ZhongqiangChen,YuanZhang,andZhongrongChen.2010. Acategorizationframeworkforcommoncomputer vulnerabilitiesandexposures.Comput.J.53,5(2010),551–580. [28] XiaoCheng,HaoyuWang,JiayiHua,GuoaiXu,andYuleiSui.2021. DeepWukong:Staticallydetectingsoftware vulnerabilitiesusingdeepgraphneuralnetwork.ACMTransactionsonSoftwareEngineeringandMethodology(TOSEM) 30,3(2021),1–33. [29] XiaoCheng,HaoyuWang,JiayiHua,MiaoZhang,GuoaiXu,LiYi,andYuleiSui.2019.Staticdetectionofcontrol- flow-relatedvulnerabilitiesusinggraphembedding.In201924thInternationalConferenceonEngineeringofComplex ComputerSystems(ICECCS).IEEE,41–50. [30] XiaoCheng,GuanqinZhang,HaoyuWang,andYuleiSui.2022. Path-sensitivecodeembeddingviacontrastive learningforsoftwarevulnerabilitydetection.InProceedingsofthe31stACMSIGSOFTInternationalSymposiumon SoftwareTestingandAnalysis.519–531. [31] Min-JeChoi,SehunJeong,HakjooOh,andJaegulChoo.2017.End-to-EndPredictionofBufferOverrunsfromRaw SourceCodeviaNeuralMemoryNetworks.InProceedingsofthe26thInternationalJointConferenceonArtificial Intelligence(Melbourne,Australia)(IJCAI’17).AAAIPress,1546–1553. [32] HoaKhanhDam,TruyenTran,TrangPham,ShienWeeNg,JohnGrundy,andAdityaGhose.2017.Automaticfeature learningforvulnerabilityprediction.arXivpreprintarXiv:1708.02368(2017). [33] HoaKhanhDam,TruyenTran,TrangPham,ShienWeeNg,JohnGrundy,andAdityaGhose.2018.Automaticfeature learningforpredictingvulnerablesoftwarecomponents. IEEETransactionsonSoftwareEngineering47,1(2018), 67–85. J.ACM,Vol.37,No.4,Article111.Publicationdate:August2018.11N1:i3m2aShiriharzevili,AlvineBoayeBelle,JunjieWang,SongWang,ZhenMing(Jack)Jiang,andNachiappanNagappan [34] JacobDevlin,Ming-WeiChang,KentonLee,andKristinaToutanova.2018.Bert:Pre-trainingofdeepbidirectional transformersforlanguageunderstanding.arXivpreprintarXiv:1810.04805(2018). [35] ElizabethDinella,HanjunDai,ZiyangLi,MayurNaik,LeSong,andKeWang.2020. Hoppity:Learninggraph transformationstodetectandfixbugsinprograms.InInternationalConferenceonLearningRepresentations(ICLR). [36] YangruiboDing,SahilSuneja,YunhuiZheng,JimLaredo,AlessandroMorari,GailKaiser,andBaishakhiRay.2022.VEL-
VET:anoVelEnsembleLearningapproachtoautomaticallylocateVulnErablesTatements.In2022IEEEInternational ConferenceonSoftwareAnalysis,EvolutionandReengineering(SANER).IEEE,959–970. [37] XiaotingDu,ZenghuiZhou,BeibeiYin,andGuanpingXiao.2020.Cross-projectbugtypepredictionbasedontransfer learning.SoftwareQualityJournal28,1(2020),39–57. [38] XuDuan,JingzhengWu,ShoulingJi,ZhiqingRui,TianyueLuo,MutianYang,andYanjunWu.2019.VulSniper:Focus YourAttentiontoShootFine-GrainedVulnerabilities..InIJCAI.4665–4671. [39] AndrewDunham.2009. rough-auditing-tool-for-security. https://github.com/andrew-d/rough-auditing-tool-for- security [40] RudreshDwivedi,DevamDave,HetNaik,SmitiSinghal,RanaOmer,PankeshPatel,BinQian,ZhenyuWen,Tejal Shah,GrahamMorgan,etal.2023.ExplainableAI(XAI):Coreideas,techniques,andsolutions.Comput.Surveys55,9 (2023),1–33. [41] Facebook.2013.Infer. https://fbinfer.com/ [42] KatarzynaFilus,MiltiadisSiavvas,JoannaDomańska,andErolGelenbe.2020. Therandomneuralnetworkasa bondingmodelforsoftwarevulnerabilityprediction.InSymposiumonModelling,Analysis,andSimulationofComputer andTelecommunicationSystems.Springer,102–116. [43] ParkForeman.2019.Vulnerabilitymanagement.CRCPress. [44] StefanFrei,MartinMay,UlrichFiedler,andBernhardPlattner.2006.Large-scalevulnerabilityanalysis.InProceedings ofthe2006SIGCOMMworkshoponLarge-scaleattackdefense.131–138. [45] MichaelFuandChakkritTantithamthavorn.2022.LineVul:ATransformer-basedLine-LevelVulnerabilityPrediction. (2022). [46] CongGao,GengWang,WeisongShi,ZhongminWang,andYanpingChen.2021.Autonomousdrivingsecurity:State oftheartandchallenges.IEEEInternetofThingsJournal9,10(2021),7572–7595. [47] MarianGawron,FengCheng,andChristophMeinel.2018. Automaticvulnerabilityclassificationusingmachine learning.InRisksandSecurityofInternetandSystems:12thInternationalConference,CRiSIS2017,Dinard,France, September19-21,2017,RevisedSelectedPapers12.Springer,3–17. [48] SeyedMohammadGhaffarianandHamidRezaShahriari.2017.Softwarevulnerabilityanalysisanddiscoveryusing machine-learninganddata-miningtechniques:Asurvey.ACMComputingSurveys(CSUR)50,4(2017),1–36. [49] SeyedMohammadGhaffarianandHamidRezaShahriari.2021. Neuralsoftwarevulnerabilityanalysisusingrich intermediategraphrepresentationsofprograms.InformationSciences553(2021),189–207. [50] MatthíasPállGissurarson,LeonhardApplis,AnnibalePanichella,ArievanDeursen,andDavidSands.2022.PropR: property-basedautomaticprogramrepair.InProceedingsofthe44thInternationalConferenceonSoftwareEngineering. 1768–1780. [51] XiGong,ZhenchangXing,XiaohongLi,ZhiyongFeng,andZhuobingHan.2019. Jointpredictionofmultiple vulnerabilitycharacteristicsthroughmulti-tasklearning.In201924thInternationalConferenceonEngineeringof ComplexComputerSystems(ICECCS).IEEE,31–40. [52] IanGoodfellow,JeanPouget-Abadie,MehdiMirza,BingXu,DavidWarde-Farley,SherjilOzair,AaronCourville,and YoshuaBengio.2020.Generativeadversarialnetworks.Commun.ACM63,11(2020),139–144. [53] KaterinaGoseva-PopstojanovaandJacobTyo.2017. Experiencereport:Securityvulnerabilityprofilesofmission criticalsoftware:Empiricalanalysisofsecurityrelatedbugreports.In2017IEEE28thInternationalSymposiumon SoftwareReliabilityEngineering(ISSRE).IEEE,152–163. [54] Daya Guo, Shuo Ren, Shuai Lu, Zhangyin Feng, Duyu Tang, Shujie Liu, Long Zhou, Nan Duan, Alexey Svy- atkovskiy,ShengyuFu,etal.2020.Graphcodebert:Pre-trainingcoderepresentationswithdataflow.arXivpreprint arXiv:2009.08366(2020). [55] JacobA.Harer,OnurOzdemir,TomoLazovich,ChristopherP.Reale,RebeccaL.Russell,LouisY.Kim,andPeterChin. 2018.LearningtoRepairSoftwareVulnerabilitieswithGenerativeAdversarialNetworks.InProceedingsofthe32nd InternationalConferenceonNeuralInformationProcessingSystems(Montréal,Canada)(NIPS’18).CurranAssociates Inc.,RedHook,NY,USA,7944–7954. [56] NimaShiriHarzevili,JihoShin,JunjieWang,andSongWang.2022. CharacterizingandUnderstandingSoftware SecurityVulnerabilitiesinMachineLearningLibraries.arXivpreprintarXiv:2203.06502(2022). [57] DaojingHe,ZhiDeng,YuxingZhang,SammyChan,YaoCheng,andNadraGuizani.2020.Smartcontractvulnerability analysisandsecurityaudit.IEEENetwork34,5(2020),276–282. J.ACM,Vol.37,No.4,Article111.Publicationdate:August2018.ASurveyonAutomatedSoftwareVulnerabilityDetectionUsingMachineLearningandDeepLearning 111:33 [58] DavidHin,AndreyKan,HuamingChen,andMAliBabar.2022.LineVD:Statement-levelVulnerabilityDetection usingGraphNeuralNetworks.arXivpreprintarXiv:2203.05181(2022). [59] GeoffreyEHinton,SimonOsindero,andYee-WhyeTeh.2006.Afastlearningalgorithmfordeepbeliefnets.Neural computation18,7(2006),1527–1554. [60] ThongHoang,HoaKhanhDam,YasutakaKamei,DavidLo,andNaoyasuUbayashi.2019.DeepJIT:anend-to-end
deeplearningframeworkforjust-in-timedefectprediction.In2019IEEE/ACM16thInternationalConferenceonMining SoftwareRepositories(MSR).IEEE,34–45. [61] JianjunHuang,SongmingHan,WeiYou,WenchangShi,BinLiang,JingzhengWu,andYanjunWu.2021.Hunting vulnerablesmartcontractsviagraphembeddingbasedbytecodematching.IEEETransactionsonInformationForensics andSecurity16(2021),2144–2156. [62] XuanHuo,YangYang,MingLi,andDe-ChuanZhan.2018. LearningSemanticFeaturesforSoftwareDefect PredictionbyCodeCommentsEmbedding.In2018IEEEInternationalConferenceonDataMining(ICDM).1049–1054. https://doi.org/10.1109/ICDM.2018.00133 [63] JayJacobs,SashaRomanosky,OctavianSuciuo,BenjaminEdwards,andArminSarabi.2023.EnhancingVulnerability Prioritization:Data-DrivenExploitPredictionswithCommunity-DrivenInsights.arXivpreprintarXiv:2302.14172 (2023). [64] SanghoonJeonandHuyKangKim.2021.AutoVAS:Anautomatedvulnerabilityanalysissystemwithadeeplearning approach.Computers&Security106(2021),102308. [65] YuningJiangandYacineAtif.2020. Anapproachtodiscoverandassessvulnerabilityseverityautomaticallyin cyber-physicalsystems.In13thinternationalconferenceonsecurityofinformationandnetworks.1–8. [66] YanjieJiang,HuiLiu,YuxiaZhang,WeixingJi,HaoZhong,andLuZhang.2022.Dobugsleadtounnaturalnessof sourcecode?.InProceedingsofthe30thACMJointEuropeanSoftwareEngineeringConferenceandSymposiumonthe FoundationsofSoftwareEngineering.1085–1096. [67] MatthieuJimenez,MikePapadakis,andYvesLeTraon.2016.Anempiricalanalysisofvulnerabilitiesinopenssland thelinuxkernel.In201623rdAsia-PacificSoftwareEngineeringConference(APSEC).IEEE,105–112. [68] StaffsKeeleetal.2007. Guidelinesforperformingsystematicliteraturereviewsinsoftwareengineering. Technical Report.Technicalreport,Ver.2.3EBSETechnicalReport.EBSE. [69] SaadKhanandSimonParkinson.2018. Reviewintostateoftheartofvulnerabilityassessmentusingartificial intelligence.InGuidetoVulnerabilityAnalysisforComputerNetworksandSystems.Springer,3–32. [70] TaegyuKim,ChungHwanKim,JunghwanRhee,FanFei,ZhanTu,GregoryWalkup,XiangyuZhang,XinyanDeng, andDongyanXu.2019.RVFuzzer:FindingInputValidationBugsinRoboticVehiclesthroughControl-GuidedTesting.. InUSENIXSecuritySymposium.425–442. [71] KyriakosKritikos,KostasMagoutis,ManosPapoutsakis,andSotirisIoannidis.2019. Asurveyonvulnerability assessmenttoolsanddatabasesforcloud-basedwebapplications.Array3(2019),100011. [72] JorritKronjee,ArjenHommersom,andHaraldVranken.2018.Discoveringsoftwarevulnerabilitiesusingdata-flow analysisandmachinelearning.InProceedingsofthe13thinternationalconferenceonavailability,reliabilityandsecurity. 1–10. [73] PatrickKwakuKudjo,JinfuChen,SolomonMensah,RichardAmankwah,andChristopherKudjo.2020.Theeffect ofBellwetheranalysisonsoftwarevulnerabilityseveritypredictionmodels. SoftwareQualityJournal28(2020), 1413–1446. [74] PatrickKwakuKudjo,JinfuChen,MinminZhou,SolomonMensah,andRubingHuang.2019.Improvingtheaccuracy ofvulnerabilityreportclassificationusingtermfrequency-inversegravitymoment.In2019IEEE19thInternational ConferenceonSoftwareQuality,ReliabilityandSecurity(QRS).IEEE,248–259. [75] ChrisLattner.2008.LLVMandClang:Nextgenerationcompilertechnology. [76] TueLe,TuanNguyen,TrungLe,DinhPhung,PaulMontague,OlivierDeVel,andLizhenQu.2018. Maximal divergencesequentialautoencoderforbinarysoftwarevulnerabilitydetection.InInternationalConferenceonLearning Representations. [77] TrietHMLe,HuamingChen,andMAliBabar.2021.Asurveyondata-drivensoftwarevulnerabilityassessmentand prioritization.arXivpreprintarXiv:2107.08364(2021). [78] TrietHMLe,HuamingChen,andMAliBabar.2022.Asurveyondata-drivensoftwarevulnerabilityassessmentand prioritization.Comput.Surveys55,5(2022),1–39. [79] TrietHuynhMinhLe,DavidHin,RolandCroft,andMAliBabar.2021.Deepcva:Automatedcommit-levelvulnerability assessmentwithdeepmulti-tasklearning.In202136thIEEE/ACMInternationalConferenceonAutomatedSoftware Engineering(ASE).IEEE,717–729. [80] TrietHuynhMinhLe,BushraSabir,andMuhammadAliBabar.2019.Automatedsoftwarevulnerabilityassessment withconceptdrift.In2019IEEE/ACM16thInternationalConferenceonMiningSoftwareRepositories(MSR).IEEE, 371–382. J.ACM,Vol.37,No.4,Article111.Publicationdate:August2018.11N1:i3m4aShiriharzevili,AlvineBoayeBelle,JunjieWang,SongWang,ZhenMing(Jack)Jiang,andNachiappanNagappan [81] DanielLehmannandMichaelPradel.2019. Wasabi:Aframeworkfordynamicallyanalyzingwebassembly.In ProceedingsoftheTwenty-FourthInternationalConferenceonArchitecturalSupportforProgrammingLanguagesand OperatingSystems.1045–1058. [82] JianLi,PinjiaHe,JiemingZhu,andMichaelRLyu.2017.Softwaredefectpredictionviaconvolutionalneuralnetwork. In2017IEEEInternationalConferenceonSoftwareQuality,ReliabilityandSecurity(QRS).IEEE,318–328. [83] LepingLi,HuiLiu,KejunLi,YanjieJiang,andRuiSun.2022. GeneratingConcisePatchesforNewlyReleased
ProgrammingAssignments.IEEETransactionsonSoftwareEngineering(2022). [84] YiLi,ShaohuaWang,andTienNNguyen.2021. Vulnerabilitydetectionwithfine-grainedinterpretations.In Proceedingsofthe29thACMJointMeetingonEuropeanSoftwareEngineeringConferenceandSymposiumonthe FoundationsofSoftwareEngineering.292–303. [85] YiLi,ShaohuaWang,TienN.Nguyen,andSonVanNguyen.2019.ImprovingBugDetectionviaContext-BasedCode RepresentationLearningandAttention-BasedNeuralNetworks.Proc.ACMProgram.Lang.3,OOPSLA,Article162 (oct2019),30pages. https://doi.org/10.1145/3360588 [86] ZhenLi,DeqingZou,ShouhuaiXu,ZhaoxuanChen,YaweiZhu,andHaiJin.2021.Vuldeelocator:adeeplearning- basedfine-grainedvulnerabilitydetector.IEEETransactionsonDependableandSecureComputing(2021). [87] ZhenLi,DeqingZou,ShouhuaiXu,HaiJin,YaweiZhu,andZhaoxuanChen.2021.Sysevr:Aframeworkforusing deeplearningtodetectsoftwarevulnerabilities.IEEETransactionsonDependableandSecureComputing(2021). [88] ZhenLi,DeqingZou,ShouhuaiXu,XinyuOu,HaiJin,SujuanWang,ZhijunDeng,andYuyiZhong.2018.Vuldeepecker: Adeeplearning-basedsystemforvulnerabilitydetection.arXivpreprintarXiv:1801.01681(2018). [89] GuanjunLin,ShengWen,Qing-LongHan,JunZhang,andYangXiang.2020.Softwarevulnerabilitydetectionusing deepneuralnetworks:asurvey.Proc.IEEE108,10(2020),1825–1848. [90] GuanjunLin,JunZhang,WeiLuo,LeiPan,OlivierDeVel,PaulMontague,andYangXiang.2019.Softwarevulnerability discoveryvialearningmulti-domainknowledgebases.IEEETransactionsonDependableandSecureComputing18,5 (2019),2469–2485. [91] GuanjunLin,JunZhang,WeiLuo,LeiPan,andYangXiang.2017.POSTER:Vulnerabilitydiscoverywithfunction representationlearningfromunlabeledprojects.InProceedingsofthe2017ACMSIGSACConferenceonComputerand CommunicationsSecurity.2539–2541. [92] GuanjunLin,JunZhang,WeiLuo,LeiPan,YangXiang,OlivierDeVel,andPaulMontague.2018. Cross-project transferrepresentationlearningforvulnerablefunctiondiscovery.IEEETransactionsonIndustrialInformatics14,7 (2018),3289–3297. [93] ChaoLiu,CuiyunGao,XinXia,DavidLo,JohnGrundy,andXiaohuYang.2021.Onthereproducibilityandreplicability ofdeeplearninginsoftwareengineering.ACMTransactionsonSoftwareEngineeringandMethodology(TOSEM)31,1 (2021),1–46. [94] ShigangLiu,GuanjunLin,Qing-LongHan,ShengWen,JunZhang,andYangXiang.2019.DeepBalance:Deep-learning andfuzzyoversamplingforvulnerabilitydetection.IEEETransactionsonFuzzySystems28,7(2019),1329–1343. [95] ShigangLiu,GuanjunLin,LizhenQu,JunZhang,OlivierDeVel,PaulMontague,andYangXiang.2020.CD-VulD: Cross-domainvulnerabilitydiscoverybasedondeepdomainadaptation.IEEETransactionsonDependableandSecure Computing(2020). [96] YinhanLiu,MyleOtt,NamanGoyal,JingfeiDu,MandarJoshi,DanqiChen,OmerLevy,MikeLewis,LukeZettlemoyer, andVeselinStoyanov.2019.Roberta:Arobustlyoptimizedbertpretrainingapproach.arXivpreprintarXiv:1907.11692 (2019). [97] ZhenguangLiu,PengQian,XiangWang,LeiZhu,QinmingHe,andShoulingJi.2021.Smartcontractvulnerability detection:frompureneuralnetworktointerpretablegraphfeatureandexpertpatternfusion. arXivpreprint arXiv:2106.09282(2021). [98] ZhenguangLiu,PengQian,XiaoyangWang,YuanZhuang,LinQiu,andXunWang.2021.Combininggraphneural networkswithexpertknowledgeforsmartcontractvulnerabilitydetection. IEEETransactionsonKnowledgeand DataEngineering(2021). [99] NingLu,BinWang,YongxinZhang,WenboShi,andChristianEsposito.2021.NeuCheck:AmorepracticalEthereum smartcontractsecurityanalysistool.Software:PracticeandExperience51,10(2021),2065–2084. [100] QianLuo,YuruiCao,JiajiaLiu,andAbderrahimBenslimane.2019. Localizationandnavigationinautonomous driving:Threatsandcountermeasures.IEEEWirelessCommunications26,4(2019),38–45. [101] VinodMahor,KiranPachlasiya,BhagwatiGarg,MukeshChouhan,ShrikantTelang,andRomilRawat.2022.Mobile OperatingSystem(Android)VulnerabilityAnalysisUsingMachineLearning.InProceedingsofInternationalConference onNetworkSecurityandBlockchainTechnology:ICNSBT2021.Springer,159–169. [102] YiMao,YunLi,JiataiSun,andYixinChen.2020.ExplainableSoftwarevulnerabilitydetectionbasedonAttention- basedBidirectionalRecurrentNeuralNetworks.In2020IEEEInternationalConferenceonBigData(BigData).IEEE, 4651–4656. J.ACM,Vol.37,No.4,Article111.Publicationdate:August2018.ASurveyonAutomatedSoftwareVulnerabilityDetectionUsingMachineLearningandDeepLearning 111:35 [103] DanielMarjamäki.2016.Cppcheck. https://cppcheck.sourceforge.io/ [104] NadiaMedeiros,NaghmehIvaki,PedroCosta,andMarcoVieira.2023.Trustworthinessmodelstocategorizeand prioritizecodeforsecurityimprovement.JournalofSystemsandSoftware(2023),111621. [105] DangMinh,HXiangWang,YFenLi,andTanNNguyen.2022.Explainableartificialintelligence:acomprehensive review.ArtificialIntelligenceReview(2022),1–66.
[106] NicholasNethercoteandJulianSeward.2007.Valgrind:aframeworkforheavyweightdynamicbinaryinstrumentation. ACMSigplannotices42,6(2007),89–100. [107] HoangHNguyen,Nhat-MinhNguyen,Hong-PhucDoan,ZahraAhmadi,Thanh-NamDoan,andLingxiaoJiang. 2022.MANDO-GURU:vulnerabilitydetectionforsmartcontractsourcecodebyheterogeneousgraphembeddings. InProceedingsofthe30thACMJointEuropeanSoftwareEngineeringConferenceandSymposiumontheFoundationsof SoftwareEngineering.1736–1740. [108] HoangHNguyen,Nhat-MinhNguyen,ChunyaoXie,ZahraAhmadi,DanielKudendo,Thanh-NamDoan,andLingxiao Jiang.2022.MANDO:Multi-LevelHeterogeneousGraphEmbeddingsforFine-GrainedDetectionofSmartContract Vulnerabilities.arXivpreprintarXiv:2208.13252(2022). [109] TuanNguyen,TrungLe,KhanhNguyen,OlivierdeVel,PaulMontague,JohnGrundy,andDinhPhung.2020.Deep cost-sensitivekernelmachineforbinarysoftwarevulnerabilitydetection.InPacific-AsiaConferenceonKnowledge DiscoveryandDataMining.Springer,164–177. [110] ChaoNi,WeiWang,KaiwenYang,XinXia,KuiLiu,andDavidLo.2022.Thebestofbothworlds:integratingsemantic featureswithexpertfeaturesfordefectpredictionandlocalization.InProceedingsofthe30thACMJointEuropean SoftwareEngineeringConferenceandSymposiumontheFoundationsofSoftwareEngineering.672–683. [111] YuNong,RainySharma,AbdelwahabHamou-Lhadj,XiapuLuo,andHaipengCai.2022.OpenScienceinSoftware Engineering:AStudyonDeepLearning-BasedVulnerabilityDetection.IEEETransactionsonSoftwareEngineering (2022). [112] YuleiPang,XiaozhenXue,andAkbarSiamiNamin.2015. Predictingvulnerablesoftwarecomponentsthrough n-gramanalysisandstatisticalfeatureselection.In2015IEEE14thInternationalConferenceonMachineLearningand Applications(ICMLA).IEEE,543–548. [113] LucaPascarella,FabioPalomba,andAlbertoBacchelli.2019.Fine-grainedjust-in-timedefectprediction.Journalof SystemsandSoftware150(2019),22–36. [114] HenningPerl,SergejDechand,MatthewSmith,DanielArp,FabianYamaguchi,KonradRieck,SaschaFahl,and YaseminAcar.2015. Vccfinder:Findingpotentialvulnerabilitiesinopen-sourceprojectstoassistcodeaudits.In Proceedingsofthe22ndACMSIGSACConferenceonComputerandCommunicationsSecurity.426–437. [115] KaiPetersen,SairamVakkalanka,andLudwikKuzniarz.2015.Guidelinesforconductingsystematicmappingstudies insoftwareengineering:Anupdate.Informationandsoftwaretechnology64(2015),1–18. [116] AnhVietPhan,MinhLeNguyen,andLamThuBui.2017.Convolutionalneuralnetworksovercontrolflowgraphs forsoftwaredefectprediction.In2017IEEE29thInternationalConferenceonToolswithArtificialIntelligence(ICTAI). IEEE,45–52. [117] ValentinaPiantadosi,SimoneScalabrino,andRoccoOliveto.2019.Fixingofsecurityvulnerabilitiesinopensource projects:Acasestudyofapachehttpserverandapachetomcat.In201912thIEEEConferenceonsoftwaretesting, validationandverification(ICST).IEEE,68–78. [118] MichaelPradelandKoushikSen.2018.Deepbugs:Alearningapproachtoname-basedbugdetection.Proceedingsof theACMonProgrammingLanguages2,OOPSLA(2018),1–25. [119] AliRazaandWaseemAhmed.2022. ThreatandVulnerabilitymanagementlifecycleinoperatingsystems.A systematicreview.JournalofMultidisciplinaryEngineeringScienceandTechnology(JMEST)9,1(2022). [120] TimothéRiom,ArthurSawadogo,KevinAllix,TegawendéFBissyandé,NaouelMoha,andJacquesKlein.2021. RevisitingtheVCCFinderapproachfortheidentificationofvulnerability-contributingcommits.EmpiricalSoftware Engineering26,3(2021),1–30. [121] AnnachiaraRuospo,AlbertoBosio,AlessandroIanne,andErnestoSanchez.2020.Evaluatingconvolutionalneural networksreliabilitydependingontheirdatarepresentation.In202023rdEuromicroConferenceonDigitalSystem Design(DSD).IEEE,672–679. [122] RebeccaRussell,LouisKim,LeiHamilton,TomoLazovich,JacobHarer,OnurOzdemir,PaulEllingwood,andMarc McConley.2018.Automatedvulnerabilitydetectioninsourcecodeusingdeeprepresentationlearning.In201817th IEEEinternationalconferenceonmachinelearningandapplications(ICMLA).IEEE,757–762. [123] AntoninoSabettaandMicheleBezzi.2018.Apracticalapproachtotheautomaticclassificationofsecurity-relevant commits.In2018IEEEInternationalconferenceonsoftwaremaintenanceandevolution(ICSME).IEEE,579–582. [124] RiccardoScandariato,JamesWalden,AramHovsepyan,andWouterJoosen.2014.Predictingvulnerablesoftware componentsviatextmining.IEEETransactionsonSoftwareEngineering40,10(2014),993–1006. J.ACM,Vol.37,No.4,Article111.Publicationdate:August2018.11N1:i3m6aShiriharzevili,AlvineBoayeBelle,JunjieWang,SongWang,ZhenMing(Jack)Jiang,andNachiappanNagappan [125] AbubakarOmariAbdallahSemasaba,WeiZheng,XiaoxueWu,andSamuelAkwasiAgyemang.2020. Literature surveyofdeeplearning-basedvulnerabilityanalysisonsourcecode.IETSoftware14,6(2020),654–664. [126] LwinKhinSharandHeeBengKuanTan.2010.Auditingthedefenseagainstcrosssitescriptinginwebapplications. In2010InternationalConferenceonSecurityandCryptography(SECRYPT).IEEE,1–7.
[127] LwinKhinSharandHeeBengKuanTan.2012.AuditingtheXSSdefencefeaturesimplementedinwebapplication programs.IETsoftware6,4(2012),377–390. [128] ThomasShippey,DavidBowes,andTracyHall.2019.Automaticallyidentifyingcodefeaturesforsoftwaredefect prediction:UsingASTN-grams.InformationandSoftwareTechnology106(2019),142–160. [129] SpotBugs.2021.SpotBugs. .https://spotbugs.github.io/ [130] MiroslawStaron,MirosławOchodek,WilhelmMeding,andOlaSöder.2020.Usingmachinelearningtoidentifycode fragmentsformanualreview.In202046thEuromicroConferenceonSoftwareEngineeringandAdvancedApplications (SEAA).IEEE,513–516. [131] OctavianSuciu,ConnorNelson,ZhuoerLyu,TiffanyBao,andTudorDumitras,.2022. Expectedexploitability: Predictingthedevelopmentoffunctionalvulnerabilityexploits.In31stUSENIXSecuritySymposium(USENIXSecurity 22).377–394. [132] NanSun,JunZhang,PaulRimba,ShangGao,LeoYuZhang,andYangXiang.2018. Data-drivencybersecurity incidentprediction:Asurvey.IEEEcommunicationssurveys&tutorials21,2(2018),1744–1772. [133] YoushuaiTan,SijieXu,ZhaoweiWang,TaoZhang,ZhouXu,andXiapuLuo.2020.Bugseveritypredictionusing question-and-answerpairsfromStackOverflow.JournalofSystemsandSoftware165(2020),110567. [134] JunfengTian,WenjingXing,andZhenLi.2020. BVDetector:Aprogramslice-basedbinarycodevulnerability intelligentdetectionsystem.InformationandSoftwareTechnology123(2020),106289. [135] MichałWalkowski,JacekOko,andSławomirSujecki.2021. VulnerabilityManagementModelsUsingaCommon VulnerabilityScoringSystem.AppliedSciences11,18(2021),8735. [136] HuantingWang,GuixinYe,ZhanyongTang,ShinHweiTan,SongfangHuang,DingyiFang,YansongFeng,Lizhong Bian,andZhengWang.2020.Combininggraph-basedlearningwithautomateddatacollectionforcodevulnerability detection.IEEETransactionsonInformationForensicsandSecurity16(2020),1943–1958. [137] SongWang,TaiyueLiu,JaechangNam,andLinTan.2018. Deepsemanticfeaturelearningforsoftwaredefect prediction.IEEETransactionsonSoftwareEngineering46,12(2018),1267–1293. [138] SongWang,TaiyueLiu,andLinTan.2016.Automaticallylearningsemanticfeaturesfordefectprediction.In2016 IEEE/ACM38thInternationalConferenceonSoftwareEngineering(ICSE).IEEE,297–308. [139] DavidA.Wheeler.2013.Dlawfinder. http://dwheeler.com/flawfinder/ [140] HongjunWu,ZhuoZhang,ShangwenWang,YanLei,BoLin,YihaoQin,HaoyuZhang,andXiaoguangMao.2021. Peculiar:SmartContractVulnerabilityDetectionBasedonCrucialDataFlowGraphandPre-trainingTechniques.In 2021IEEE32ndInternationalSymposiumonSoftwareReliabilityEngineering(ISSRE).IEEE.378–389. [141] ChunqiuStevenXia,YuxiangWei,andLingmingZhang.2023.Automatedprogramrepairintheeraoflargepre- trainedlanguagemodels.InProceedingsofthe45thInternationalConferenceonSoftwareEngineering(ICSE2023). AssociationforComputingMachinery. [142] FabianYamaguchi,MarkusLottmann,andKonradRieck.2012.Generalizedvulnerabilityextrapolationusingabstract syntaxtrees.InProceedingsofthe28thAnnualComputerSecurityApplicationsConference.359–368. [143] FabianYamaguchi,KonradRieck,etal.2011.Vulnerabilityextrapolation:Assisteddiscoveryofvulnerabilitiesusing machinelearning.In5thUSENIXWorkshoponOffensiveTechnologies(WOOT11). [144] FabianYamaguchi,ChristianWressnegger,HugoGascon,andKonradRieck.2013. Chucky:Exposingmissing checksinsourcecodeforvulnerabilitydiscovery.InProceedingsofthe2013ACMSIGSACconferenceonComputer& communicationssecurity.499–510. [145] HanYan,SenlinLuo,LiminPan,andYifeiZhang.2021. HAN-BSVD:ahierarchicalattentionnetworkforbinary softwarevulnerabilitydetection.Computers&Security108(2021),102286. [146] HongyuYang,HaiyunYang,LiangZhang,andXiangCheng.2022. SourceCodeVulnerabilityDetectionUsing VulnerabilityDependencyRepresentationGraph.In2022IEEEInternationalConferenceonTrust,SecurityandPrivacy inComputingandCommunications(TrustCom).IEEE,457–464. [147] LiminYang,XiangxueLi,andYuYu.2017.Vuldigger:Ajust-in-timeandcost-awaretoolfordiggingvulnerability- contributingchanges.InGLOBECOM2017-2017IEEEGlobalCommunicationsConference.IEEE,1–7. [148] JiaoYin,MingJianTang,JinliCao,HuaWang,andMingshanYou.2022. Areal-timedynamicconceptadaptive learningalgorithmforexploitabilityprediction.Neurocomputing472(2022),252–265. [149] SuanHsiYongandSusanHorwitz.2005.Usingstaticanalysistoreducedynamicanalysisoverhead.FormalMethods inSystemDesign27(2005),313–334. [150] ChengZeng,ChunYingZhou,ShengKaiLv,PengHe,andJieHuang.2021. GCN2defect:GraphConvolutional NetworksforSMOTETomek-basedSoftwareDefectPrediction.In2021IEEE32ndInternationalSymposiumonSoftware J.ACM,Vol.37,No.4,Article111.Publicationdate:August2018.ASurveyonAutomatedSoftwareVulnerabilityDetectionUsingMachineLearningandDeepLearning 111:37 ReliabilityEngineering(ISSRE).IEEE,69–79. [151] PengZeng,GuanjunLin,LeiPan,YonghangTai,andJunZhang.2020.Softwarevulnerabilityanalysisanddiscovery usingdeeplearningtechniques:Asurvey.IEEEAccess8(2020),197158–197172.
[152] ZhuoZhang,YanLei,MengYan,YueYu,JiachiChen,ShangwenWang,andXiaoguangMao.2022. Reentrancy VulnerabilityDetectionandLocalization:ADeepLearningBasedTwo-phaseApproach.In37thIEEE/ACMInternational ConferenceonAutomatedSoftwareEngineering.1–13. [153] WeiningZheng,YuanJiang,andXiaohongSu.2021.VulSPG:Vulnerabilitydetectionbasedonslicepropertygraph representationlearning.arXivpreprintarXiv:2109.02527(2021). [154] YaqinZhou,ShangqingLiu,JingkaiSiow,XiaoningDu,andYangLiu.2019.Devign:Effectivevulnerabilityidentifi- cationbylearningcomprehensiveprogramsemanticsviagraphneuralnetworks.Advancesinneuralinformation processingsystems32(2019). [155] YaqinZhouandAsankhayaSharma.2017.Automatedidentificationofsecurityissuesfromcommitmessagesand bugreports.InProceedingsofthe201711thjointmeetingonfoundationsofsoftwareengineering.914–919. [156] WeiyuanZhuang,HaoWang,andXiaofangZhang.2022. Just-in-timedefectpredictionbasedonASTchange embedding.Knowledge-BasedSystems248(2022),108852. [157] YuanZhuang,ZhenguangLiu,PengQian,QiLiu,XiangWang,andQinmingHe.2020.SmartContractVulnerability DetectionusingGraphNeuralNetwork..InIJCAI.3283–3290. [158] NoahZiemsandShaoenWu.2021.SecurityVulnerabilityDetectionUsingDeepLearningNaturalLanguageProcessing. InIEEEINFOCOM2021-IEEEConferenceonComputerCommunicationsWorkshops(INFOCOMWKSHPS).IEEE,1–6. [159] DeqingZou,YutaoHu,WenkeLi,YuemingWu,HaojunZhao,andHaiJin.2022.mVulPreter:AMulti-Granularity VulnerabilityDetectionSystemWithInterpretations.IEEETransactionsonDependableandSecureComputing(2022). [160] DeqingZou,SujuanWang,ShouhuaiXu,ZhenLi,andHaiJin.2019. muVulDeePecker:ADeepLearning-Based SystemforMulticlassVulnerabilityDetection.IEEETransactionsonDependableandSecureComputing18,5(2019), 2224–2236. [161] DeqingZou,YaweiZhu,ShouhuaiXu,ZhenLi,HaiJin,andHengkaiYe.2021.InterpretingDeepLearning-Based VulnerabilityDetectorPredictionsBasedonHeuristicSearching. 30,2,Article23(mar2021),31pages. https: //doi.org/10.1145/3429444 J.ACM,Vol.37,No.4,Article111.Publicationdate:August2018.
2306.14168 FastBCSD: Fast and Efficient Neural Network for Binary Code Similarity Detection ChensenHuang GuiboZhu GuojingGe UniversityofChineseAcademyof InstituteofAutomation,Chineseof InstituteofAutomation,Chineseof Sciences Academy Academy TaihaoLi JinqiaoWang ZhejiangLab InstituteofAutomation,Chineseof Academy ABSTRACT learning methods to learn a vector representation. Another ap- Binarycodesimilaritydetection(BCSD)hasvariousapplications, proachisInstruction2Vec[16],whichsplitsoperandsandopcodes includingbutnotlimitedtovulnerabilitydetection,plagiarismde- intheinstructionintoseparatewords(tokens),assignseachtoken tection,andmalwaredetection.Previousresearcheffortsmainly alearnablevector,andtrainsadeeplearningmodelontheresulting focusontransformingbinarycodetoassemblycodestringsusing vectorrepresentations.Inrecentyears,pre-trainingmodelshave reversecompilationandthenusingpre-traineddeeplearningmod- gainedpopularityinthefieldofbinarycodesimilaritydetection elswithlargeparameterstoobtainfeaturerepresentationvector (BCSD).PalmTree[17],jTrans[23],andUniASM[10]arethree ofbinarycode.Whilethesemodelshaveproventobeeffective suchmodelsthatusecleanedassemblytextasasequenceofto- in representing binary code, their large parameter size leads to kens,alongwithpre-trainingtaskslikeMaskedLanguageModel considerablecomputationalexpensesduringbothtrainingandin- (MLM)[4]andContextWindowPrediction(CWP)[17]toconduct ference.Inthispaper,wepresentalightweightneuralnetwork, unsupervisedtraining.Thesemodelshaveshownpromisingresults calledFastBCSD,thatemploysadynamicinstructionvectorencod- inBCSD.Therepresentationvectoroftheentireassemblytextcan ingmethodandtakesonlyassemblycodeasinputfeaturetoachieve beobtainedbyfine-tuningtheassemblycodepair.Thepre-training comparableaccuracytothepre-trainingmodelswhilereducing approachhasdemonstratedsignificantperformancegainsoverpre- the computational resources and time cost. On the BinaryCorp vioustechniques,buttherearestillsomelimitationsthatneedto dataset,ourmethodachievesasimilaraverageMRRscoretothe beaddressed. state-of-the-artpre-training-basedmethod(jTrans),whileonthe Firstly,thelargenumberofparametersinrecentmodelsbased BinaryCorp3Mdataset,ourmethodevenoutperformsthelatest onBERTandotherTransformerstructureshavemadeitdifficult technologyby0.01.Notably,FastBCSDhasamuchsmallerparam- toapplytheminreal-worldscenarios. etersize(13.4M)comparedtojTrans(87.88M),anditslatencytime Secondly,theTransformer[22]haslimitationsthatthelength is1/5ofjTransonNVIDIAGTX1080Ti. ofinputsequencescannotexceed512atatime.Asaresult,when thelengthofinputsequencesexceeds512,somesequenceswillbe discarded,resultinginalossofinformation. KEYWORDS Thirdly,inordertoaddresstheOut-Of-Vocabulary(OOV)prob- BinaryCode,SimilarityDetection,NeuralNetworks lem,tokennormalizationiscommonlyapplied,whichmapsdif- ferenttokenstothesametoken,butexcessivenormalizationcan resultininformationloss. 1 INTRODUCTION Inresponsetotheaforementionedissues,thispaperintroducesa Binary code similarity detection (BCSD) is a technique used in noveldynamicinstructionvectorencodingapproachandutilizesa computersecurityfields,suchasvulnerabilitydetection,clonal lightweightneuralnetworkmodeltoextractinstructioncharacter- detection[5,13],andmalwaredetection[1,2],thatcalculatesthe istics.IncontrasttoUniASM[10],whereeachinstructionconsists similaritybetweentwobinarycodefragments.Asbinaryanalysis ofbothoperandsandopcodesasasingletoken,weembedthe tasksbecomemorewidespread,thereisaclearneedtodevelop operandsandopcodesasseparatetokensandconcatenatetheop- fasterandmoreefficientBCSDsolutions. codevector,operandvector,andinstructionpositionvectoralong Gemini[25]andGenius[8]areearlierworksthatmanuallyex- the feature dimension. Additionally, the length of the dynamic tractstatisticalfeaturesfromtheinstructionandcombinethem instructionvectorisproportionaltothenumberofinstructions, withcontrolflowdiagrams(CFG)tomodelthistask.Incontrast, which is much smaller than the number of tokens, resulting in 𝛼Diff[18]directlyfeedsbinarydataintotheneuralnetworkto reducedtrainingandinferencetime,aswellasmitigatingtherisk extractrepresentationfeatures.Asnaturallanguageprocessing ofOOVissues.Duringtokengeneration,variousdelimiters(e.g.,",", (NLP)technologyhasdeveloped,recentresearchhasexplorednew ":",";",etc.)areemployedtosplittheassemblycodeintomultiple approachestobinarycodesimilaritydetection(BCSD).Onesuch tokens.Low-frequencytokensarethenfilteredoutbasedontheir approachisSAFE[19],whichtreatstheentireinstruction(includ- ingbothoperandandopcode)asaword(token)andappliesdeep 3202 nuJ 52 ]RC.sc[ 1v86141.6032:viXra, , Huangetal. occurrencefrequency.Incontrasttonormalizingtokens,thisap- totrainfunctionandinstructiontokenstoobtainrepresentation proachreducesthenumberoftokenswhilepreservingmoretoken vectors.Pre-trainedmodelshaveachievedremarkableresultsin information.weselectedTextCNN[14]andLSTM[12],whichare thefieldofNLP,andhavealsobeenappliedtotheBCSDtaskin
well-establishedandwidely-usedmodelsfortextclassificationand recentyearswithfavorableoutcomes.Thestudybyresearchers othernaturallanguageprocessingtasks,asourbasicmodel.The inOrderMatters[26]proposesasemantic-awareneuralnetwork TextCNNmodel,whichisbasedonone-dimensionalconvolution, toextractsemanticinformationfrombinarycode.Bypre-training hastheadvantagesofhavingasmallnumberofparametersand binarycodeusingBERT[4]attoken,block,andgraphleveltasks, fastinferencespeed.Ontheotherhand,theLSTMmodelbasedon theresearchersfoundthattheorderofControlFlowGraph(CFG) RNNcaneasilyextracttheoverallfeaturesofthetokensequence. nodesplaysacrucialroleindetectinggraphsimilarity.Toaddress RecentstudieshaveshownthattheMLP-Mixer[21]modelbased theissueoftheimportanceoftheorderofCFGnodesingraph onMLPachievedcomparableperformancetoTransformerona similaritydetection,theauthorsoftheOrderMattersstudyutilized seriesofvisiontasks[24]andlanguagetasks[9].Comparedtothe aConvolutionalNeuralNetwork(CNN)toextractorderinforma- Transformer,theMLP-Mixerhasasimplerarchitecturethatuti- tionfromtheadjacencymatrix.Theextractedfeatureswerethen lizesonlymulti-layerperceptronsandlackstheincorporationof integratedtoformthefinalrepresentationvectorforbinarycode. self-attention.WewillmodifytheMLP-Mixerusedinvisiontasks PalmTree[17]isanassemblylanguagemodelpre-trainedusingthe tomakeitapplicabletotheBCSDtask. BERTmodelarchitecture.Inthestudy,theresearchersperformed Insummary,ourstudyoffersthefollowingcontributions: self-supervisedtrainingonavastunlabeledbinarycorpustogener- ateuniversalinstructionembeddings.InthestudyofPalmTree[17], • FastBCSDiseasytofollowcomparedtootherresearchmeth- researchersproposedapre-trainingmodelbasedonBERTcalled ods,asitonlyrequiresassemblingtextstringsandalighten PalmTree,whichutilizesthreepre-trainingtasks:MaskedLanguage neuralnetwork,whileothermethodsnecessitateadditional Model(MLM),ContextWindowPrediction(CWP),andDef-Use features,numeroustrainingtechniques,andcomplexarchi- Prediction(DUP)toextractvariousfeaturesofassemblylanguage. tecture. Although the model generated general instruction embeddings • TheperformanceofFastBCSDusingTextCNNiscomparable throughself-supervisedtrainingonalarge-scaleunlabeledbinary tothestate-of-the-art(SOTA)model:jTrans[23]basedon corpus,theefficiencyofthePalmTreepre-trainedlanguagemodel pre-trainedmodels,butwithasignificantlyreducedcompu- isnotedtobelowerthanthatoftraditionaldeeplearningschemes tationaltimeofapproximately1/5ofjTransandasmaller likeInstruction2Vec[16]whicharenotpre-trained.Inthestudyof numberofparameters,whichisapproximately1/5ofjTrans. jTrans[16],theresearchersutilizedaTransformer-basedlanguage modeltoembedcontrolflowinformationofbinarycode,witha 2 RELATEDWORK basicstructuresimilartoBERT[4],andtraineditforthebinary Inpriorresearch,researcherscommonlyemployeddirectanalysis codesimilaritydetectiontask.Moreover,theresearchersintroduced ofspecificfeaturesofbinarycode.Forinstance,𝛼Dif[18]useda anewbinarydatasetcalledBinaryCorp[23],whichiscurrently CNN[15]modeltoextractinternalfeaturesofeachbinaryfunction, themostdiversedataset.Notably,thispaperemployedtheBina- whichprocessedrawbyteswithoutadditionalfeaturerequirements. ryCorpdatasetfortheexperiments.TheauthorsofUniASM[10] Subsequentresearchschemes,however,typicallyfocusedonseek- introducedanovelpre-trainingmodelforanalyzingassemblycode, ingavectortorepresentbinarycode,withtheidentificationof inspiredbyUniLM[7].Themodelwastrainedonaself-constructed asuitablerepresentationvectorservingasthecruxoftheseap- datasetandachievedpromisingresults. proaches.TheauthorsofDeepVSA[11]employOne-hotencoding ontherawbytestoobtaintherepresentationvectorofeachin- 3 DESIGNOFFASTBCSD struction,usingittoclassifymalicioussoftware.Incontrast,the 3.1 TextPreprocessing authorsofGemini[25]constructanattributecontrolflowgraph (ACFG)bymanuallyextractingstatisticalfeaturesoftheassembly Eachassemblyfunctionconsistsofmultipleinstructions,eachcom- code,suchasthenumberofconstants.Agraphembeddingnet- prisinganopcodeandoperands.Whileopcodes’usageininstruc- workistrainedtogeneraterepresentationvectorsinthisapproach. tionsisfixed,operandcanvaryduetotheformatcharacteristics Theauthorof[27]hasproposedatechniquetorepresentbinary ofassemblylanguage.Inpriorworks,UniASM[10]treatedthe codeasasequenceofinstructions,andthenappliedtheword2vec entireinstructionasasingletoken,resultinginahighnumberof algorithm[20]toobtainavectorrepresentationforeachinstruc- tokentypesandtheOOV(Out-Of-Vocabulary)problem.Inprior tion.ArecurrentneuralnetworkbasedonLSTM[12]wasthen studies,separatingtheopcodeandoperandsfromtheinstruction usedtoidentifysimilarbinarycode.Thismethodsharessimilar- intodistincttokenswasexploredasameansofreducingthenum- itywiththeapproachadoptedinSAFE[19].Instruction2Vec[16] beroftokentypesinassemblycodeanalysis.Tofurthermitigatethe
firstpre-trainedtokensforopcodesandoperandsusingword2vec impactofvaryinginstructioncontentontokentypes,normaliza- [20],andrepresentedeachinstructionasavectorthatcombines tiontechniqueswereemployed.Forexample,specialtokenssuch anopcodevectorandeightoperandvectors.Theresultingvector as[str]wereusedinthePalmTree[17]andjTrans[23]studies sizeisNx9xvector-size,whereNistheinstructionlength.The torepresentstringsininstructions.Inourstudy,wehypothesize researchersthenusedaCNN[14]modelfortraining.Asm2Vec thattheOOVproblemdoesnothaveasubstantialimpactonthe [6]employsrandomwalksontheCFG(ControlFlowGraph)to effectivenessofourmodel.Ratherthanapplyingextensivenormal- sampleinstructionsandusesamodelsimilartothePV-DMmodel izationtechniquestotheoperands,wehavepursuedastrategyof, , FastBCSD:FastandEfficientNeuralNetworkforBinaryCodeSimilarityDetection Figure1:Inthepre-processingstageofthecodetext,low-frequencytokensareremovedandthenumberoftokensineach instructionisadjusted,followingwhichtheremainingtokensareconvertedintotokenembeddings.Subsequently,thetoken embeddingsandapositionembeddingofeachinstructionareconcatenatedintoanone-dimensionalvector,servingasthe instructionrepresentationvector.Allinstructionvectorsintheassemblycodeareconcatenatedintoatwo-dimensionalvector, whichisusedastheinputvectorofthemodel. tokenmining,expandingthevarietyoftokensusedinouranalysis. adiscardoftokensequenceslongerthan512,andinturn,resulting DelimitersbasedoncommonlyusedsymbolsinInstructions,such inpoorerrepresentationperformanceforlengthierassemblytexts. as"+",":",",",";",andspaces,wereutilizedtodecomposeinstructions Inthispaper,eachassemblyinstructionistreatedasadynamic intoamultitudeoftokens,resultinginhundredsofthousandsof vector,andthelengthoftheinputsequenceisdeterminedbythe distincttokens.Weadoptafrequency-basedfilteringapproachto numberofinstructionsintheassemblycode.Thedynamicvector selectasubsetoftokensfromthelargepooloftokensobtainedby is obtained by concatenating an opcode token vector, multiple decomposingoperandsusingvariousdelimiters.Specifically,we operandtokenvectors,andapositionalvectoralongthefeature increasethefrequencyofatokenbyoneeachtimeitappearsina dimension.Tohandlewiththevaryinglengthofinstructions,a trainingsample,andfilterouttokenswithafrequencylessthan thresholdKisusedtotruncateinstructionswithtokensequences apre-definedhyperparameterF(inourfinalexperiments,Fisset longerthanK,whilespecialtokenvectorsareusedforpadding to32),resultinginamoremanageablesetoftokenswithasizeof when the number of tokens is less than K. In our experiments, approximately40,000.Theproposedapproachpreservesagreater wesetthethresholdKto5.Thisvaluewaschosenbecausethe quantityofsemanticinformationthroughretainingmoretoken useofmanysymbolsasseparatorsinpreprocessingcanresultin typesandmorecommonlyoccurringtokens.Figure1depictsthe theparsingofmanytokensforasingleinstruction.Therefore,a specificdetailsofthepreprocessingprocedure. largervalueofKistypicallysettopreservemoreinformationfor mostinstructions.Inthisapproach,anassemblytextcomposed of S instructions is represented as a two-dimensional vector of initializedembeddingvectorswithdimensionsofSxH.Here,H 3.2 EmbeddingVectorConstruction denotesthedimensionalityofasingletokenvectormultipliedbyK InthejTrans[23]study,researcherstransformedtheassemblytext +1.ThisvectorisdirectlyfedintoTextCNN,LSTM,andMLP-Mixer intoasequenceoftokensbyconcatenatingtheopcodeandoperands fortraining.Theassembledtextvectorcanbeconvenientlyutilized intheorderoftheirappearancewithineachinstruction.Thelength fortrainingwithTextCNN,LSTM,andMLP-Mixermodels,asthey ofthetokensequenceisdeterminedbythenumberofopcodesand don’tposeanyrestrictionontheinputsequencelength,incontrast operandsintheassemblytext.However,thisapproachpresentsa totheTransformermodel,whichonlysupportsinputsequences notableissue:asinstructionsinassemblylanguageusuallyconsist oflengthlessthan512.Figure1depictsthedimensionalityofthe ofanopcodeandmultipleoperands,thenumberofparsedtokens instructionvectorandtheassembledtextvector. caneasilyexceed512whenthenumberofinstructionssurpasses 256.AsjTransemploystheBERTarchitecture,itcanonlyprocess tokensequenceswithamaximumlengthof512tokens,leadingto, , Huangetal. Figure2:ExtracttextfeaturesusingtheTextCNNmodelwith6one-dimensionalconvolutionalkernels,astrideof1,andan outputchannelof192. 3.3 ModelTraining Ct=ft∗Ct−1+it∗C˜ t (5) Fortraining,aSiamesenetworkframework[3]isutilized,with TextCNNservingasthemodelforfeatureextraction.Asatype ht=ot∗tanh(Ct) (6) oftextclassificationmodel,TextCNNisusedinthisstudytoex- tract the representation vector of assembly code. TextCNN fol- Theactivationfunctionsigmoidisdenotedas𝜎,andtanhisalso lowsastraightforwardimplementationapproach.Itreceivesatwo- anactivationfunction.xtrepresentsthecurrentinputinstruction dimensionaltextvector(textlengthxvectordimension)asinput vector,andWandbarelearnableparameters.Theoutputvector
andproducesatextrepresentationvectorbysequentiallypassing "ht"ofthelasttimestepservesastherepresentationvectorofthe throughconvolutionallayers,activationfunctions,poolinglayers, assemblytext. featureconcatenation,andfullyconnectedlayers.Therunningpro- TheoriginalMLP-Mixerconsistsofper-patchlinearembeddings, cessoftheTextCNNmodelispresentedinFigure2.Inadditionto Mixerlayers,andaclassifierhead.Inthispaper,weremovethe TextCNN,forcomparisoninfeatureextraction,weemployedtwo per-patchlinearembeddingsasourinputisnotimagedataandour othernon-Transformermodels,namelyLSTM[12]andMLP-Mixer assemblytextvectorscanbedirectlyfedintotheMixerlayers.The [21]. Mixerlayersconsistofonetoken-mixingMLPandonechannel- LSTM(long-shorttermmemory)isatypeofrecurrentneural mixingMLP,eachcontainingafully-connectedlayerandaGELU network(RNN)modelthatiswell-suitedforhandlingandpredict- nonlinearity.Thetoken-mixingMLPisusedforfeaturemixing, ingimportanteventsintimeserieswithlongintervalsanddelays, whilethechannel-mixingMLPisusedfortokenmixing,which thankstoitsuniquedesignstructure.TheapplicationofLSTM canextractglobalinformation.Othercomponentsincludeskip- forextractingtherepresentationvectorofassemblytexthasbeen connections,dropout,andlayernormalization.Thestructureofthe reportedinpreviousstudies,whereitsinputisatwo-dimensional MLP-mixerusedinthisarticleisshowninFigure3. vector,suchastheinputvectorshowninFigure1.Itsoutputisa During the training process of the siamese network, a large numberofpositiveandnegativesamplepairsarerequired.The one-dimensionalvectorcontainingglobalinformation,servingas labelofthepositivesamplepairis1,andthelabelofthenegative therepresentationvectorofassemblytext.Thecalculationformula sample pair is -1. The same TextCNN model is used to extract forthet-thtimestepofLSTMisasfollows: representationvectorsforbothfunctionsineachsamplepair,which it=𝜎(Wi·[ht−1,xt]+bi) (1) aredenotedas𝐸 1and𝐸 2.Afterobtainingtherepresentationvectors andlabels,thecosinelossfunctionisusedtocalculatethelossand ft=𝜎(W f ·[ht−1,xt]+b f) (2) updatethenetwork.Theformulaforthecosinelossfunctionisas follows: C˜ t=tanh(WC·[ht−1,xt]+bC) (3) ot=𝜎(Wo·[ht−1,xt]+bo) (4) m 𝜃inL𝐹(𝜃)=(cid:0)(1−cos(𝐸 1,𝐸 2))+max(cid:0) 0,cos(cid:0)𝐸 f,𝐸 g(cid:1)−margin(cid:1)(cid:1)∗𝑦 2+1, , FastBCSD:FastandEfficientNeuralNetworkforBinaryCodeSimilarityDetection Figure3:MLP-Mixer Table1:Statisticsonthenumberofprojects,binariesand 4.2 DataSamplingandParameterConfiguration functionsofthedatasets. IntheBinaryCorpdataset,eachoriginalbinaryprogramiscom- piledatdifferentoptimizationlevels(O0,O1,O2,O3,OS)bythe Datasets #Projects #Binaries #Functions compiler,generatingupto5functionallyequivalentbinarypro- BinaryCorp-3MTrain 1,612 8,357 3,126 grams.Wepairbinaryprogramswiththesamefunctionalitybut BinaryCorp-3MTest 364 1,908 444,574 differentoptimizationlevelstogeneratepositivesamples(filtering BinaryCorp-26MTrain 7,845 38,455 21,085,338 outpositivesampleswiththesameassemblytext),andrandomly BinaryCorp-26MTest 1,974 9,675 4,791,673 sampleRfunctionallydifferentbinaryprogramsforeachbinary programtoformnegativesamples.Wefoundthattheperformance is better when R is around 30. We used this method to sample thetrainingsetofBinaryCorp-3M,generatingabout47.6million negativesamplesand2.45millionpositivesamples,withapositive- where𝜃 representstheparametersofthemodel,andmarginisa to-negativeratioofapproximately1:19.The50millionsampleswill hyper-parameterusuallychosenbetween0and1,wefoundthat beusedasthefinaltrainingsamples.Thedimensionofboththe settingarelativelylargevalueforthemarginachievedthebest wordembeddingandpositionembeddingis192.InTextCNN,we results.Intheexperiments,wesetitto0.9. usefourone-dimensionalconvolutionalkernelswithasizeof5 andtwoone-dimensionalconvolutionalkernelswithasizeof3. Eachone-dimensionalconvolutionalkernelhasaninputchannelof 4 EXPERIMENTALSETUP 192*6andanoutputchannelof192,withastrideof1.Thelearning 4.1 Dataset rateissetto0.001,eachbatchcontains384samples,andthemodel istrainedforoneepoch. Thisstudyusedapubliclyavailablelarge-scalebinarydataset,Bi- naryCorp,whichwasfirstintroducedinthejTrans[23]paper.Bina- ryCorpconsistsofalargenumberofbinarydocuments,including 4.3 EvaluationMetrics officialArchLinuxsoftwarepackagesandArchuserrepositories, TheapplicationscenariooftheBCSDmodelistosearchforthe and48,130binaryprogramscompiledwithgccandg++atdifferent functionwiththehighestsimilaritytotheinputfunctionfroma optimization levels, with approximately 26 million functions in largenumberoffunctions.ResearchersusuallyusetheMRRand total.DuetothelargesizeoftheBinaryCorp-26Mdataset,jTrans Recall@kmetricstoevaluatetheperformanceofthemodel.Inour extractedasubsetfromitcalledBinaryCorp-3M.Table1shows experiments,wesetasourcefunctionpoolF,whichhasthesame
somestatisticsforthesetwodatasets,withBinaryCorp-3Mcon- sizeasthenumberoffunctions,andtheinputfunctionisselected tainingapproximately3.6millionfunctions.Inthisstudy,weused fromthispool.Atthesametime,wealsosetatargetfunctionpool thetrainingportionofBinaryCorp-3Masthetrainingsetforthe GwiththesamesizeasthesourcefunctionpoolF.Thedefinitions entiremodel,andtestedthetrainedmodelonthetestsetsofboth ofthesourcefunctionpoolFandthetargetfunctionpoolGareas BinaryCorp-3MandBinaryCorp-26M.Itshouldbenotedthatthe follows: testsetusedinthisstudyisthesameastheoneusedinthejTrans article. 𝐹 ={𝑓 1,𝑓 2,𝑓 3,...,𝑓 i,...,𝑓 n} (7), , Huangetal. 𝐺 ={𝑔 1,𝑔 2,𝑔 3,...,𝑔 i,...,𝑔 n} (8) modelsintermsofMRRandrecallvalues,exceptforjTrans.Par- where𝑔 1∈Gand𝑓 1∈Fhavethesamefunctionalitybutdifferent ticularly,whenthefunctionpoolsizeis10000,theMRRvalueof optimizationlevels,theyformapositivesamplepair.Whencalcu- FastBCSD-TextCNNishigherby0.31comparedtoSAFE,amodel latingMeanReciprocalRank(MRR)andRecall@k,thesimilarity constructedwiththeSiamesenetworkframeworkandbidirectional between𝑓 1andeachfunctioninGisfirstcalculated,andthenthe LSTM.BasedontheresultsshowninFigure6,itcanbeobserved functionsinGarerearrangedindescendingorderaccordingto thattheparametersizeofFastBCSD-TextCNNisonly15%ofthatof t lih se t.ir Ts hi em fi ola rr mit uy l. a𝑅 s𝑎 f𝑛 o𝑘 r𝑔 c1 ald ce un lao tt ie ns gt Mhe Rp Ro asi nt dio Rn eo cf a𝑔 ll1 @i kn ath ree ar seo ford lle or wed s: j iT nfr ea rn es n, ca end timits ei on ffe Fr ae sn tc Be Ct Sim D-e Mis Lo Pn il sy e1 v/ e5 no lf ej sT sr ,a an bs o. uM te 1a /n 7w ofhi jl Te r, at nh se . Incontrast,theslowestmodelisFastBCSD-LSTM,whichisdueto 1 ∑︁ 1 𝑀𝑅𝑅= |𝐹| 𝑓 i∈𝐹 (cid:12) (cid:12)Rank𝑔 i(cid:12) (cid:12) (9) the Tr he ecu pr er re fn ot rmne au nr ca eln coet mw po ar rk isa or nch oi fte dc it ffu er re eu ns te md. odelsispresented inTables2-3.TheresultsdemonstratethatFastBCSD-TextCNN (cid:26) 0,𝑥 >0 𝐼(𝑥)= (10) outperformsallothermodels,whileFastBCSD-MLPbasedonMLP- 1,𝑥 ≤0 Mixerexhibitstheworstperformance.Nevertheless,itisobserved Recall@k= 1 ∑︁ I(cid:0) Rank𝑔 −𝐾(cid:1) (11) thateventheworst-performingmodel,FastBCSD-MLP,isnotsignif- |𝐹| i icantlybehindjTrans.Table3showsthatFastBCSD-MLPachieves 𝑓∈𝐹 i anMRRscorethatisonly0.033lowerthanjTrans,whileoutper- formingtheSAFEmodelby0.27.TheSAFEmodelisbasedonthe 5 EVALUATION bidirectionalLSTMplustheSiamesenetworkframework,whichis Inordertoestablishastandardizedevaluationframework,weem- similartothemodelusedinFastBCSD-LSTM.However,theMRR ployedthepubliclyavailablecodeofjTranstoconstructthetesting scoreofFastBCSD-LSTMissignificantlyhigherthanthatofSAFE, datasets,BinaryCorp-3MandBinaryCorp-26M.Furthermore,we indicating that our dynamic instruction scheme can effectively appliedourpre-processingandtokenizationtechniquestoprepare adapttosmallermodels. thefunctionsinthetestingdatasets.Themodeltrainingandinfer- encewasconductedonahardwareenvironmentconsistingofan IntelXeon10-core2.20GHzCPU,256GBRAM,and1Nvidia1080Ti 5.2 Reflectiononexperimentalresults GPU. Oneimportantfactorcontributingtothesuccessofsmallmodels inourstudyistheabilitytoconstructalargeamountofsupervised 5.1 BiniarySimilarityDetectionPerformance datainbatchesfortheBCSDtask.Thisallowsforasubstantial ForthetestsetsofBinaryCorp-3MandBinaryCorp-26M,weadopted volumeofdatatobegeneratedandarelativelyuniformdatadis- thesamefunctionpoolsizesasjTrans[23],whichare32and10000, tribution.Theproposedapproachinthisstudy,whichtrainssmall respectively. Our experimental results can be seen in Tables2-5 modelsusingalargeamountofsuperviseddata,canachievecom- (exceptforFastBCSD,theperformancedataofothermodelsare parableperformancetothepre-trainingandfine-tuningapproach from jTrans’ experimental results. Table 2 reports the recall@1 thatuseslargemodels.Itshouldbenotedthatnotallsmallmodel scoresofseveralBCSDmodels,includingjTrans,onBinaryCorp- approachesareabletoachievecomparableresultstopre-trained 3MandBinaryCorp-26Mtestsets.Wenoticedaminorerrorinthe modelswhentrainedonalargeamountofsuperviseddata,asthese recall@1scoreofjTransreportedintheoriginaltable,whichdid approachesmaynottakeintoaccounttheimpactofdatavolumeon notsignificantlyaffecttheresults.However,werecalculatedthe performance.Manystudiesrelyonsmall-scaletrainingdata,which valuebasedontheprovidednumericalinformationandobtaineda issusceptibletooverfitting.Thepresentstudyusesthelargestopen revisedscoreof0.538.OurFastBCSD-TextCNNmethodachieves datasetavailable,whichhelpstoavoidtheoverfittingproblem.The similarperformancetojTransandoutperformsotherBCSDmodels popularityofpre-trainingapproachesinNLPiswell-known,mainly significantly.Forthetesttaskwithafunctionpoolsizeof32,which becausemostNLPtasksarenotaswell-definedasBCSDtasks,and
iseasierbutsignificantlydifferentfromreal-worldscenarios,our acquiringasufficientamountofsuperviseddataforNLPtasksis proposedFastBCSD-TextCNNmethodachievesanMRRvaluethat oftendifficult. isslightlylowerthanthatofjTrans,withadifferenceof0.01to 0.02.However,whenthefunctionpoolsizeis10000,whichiscloser 6 DISCUSSION toreal-worldscenarios,FastBCSD-TextCNNoutperformsthebest- performingjTransmodelonBinaryCorp-3Mwithadifferenceof Inthisarticle,ourresearchisfocusedsolelyonthex86instruction 0.01inMRRvalueand0.012inrecall@1value.Whenevaluatingon set. But FastBCSD could be applied to other types of assembly thelargerBinaryCorp-26Mdataset,FastBCSD-TextCNNachieved languagessuchasARMandMIPS.However,wehavenotconducted anMRRvaluethatis0.02lowerandarecall@1valuethatis0.02 experimentsoncross-platformbinaryfunctionrecognitioninthis lowerthanthejTransmodel.Theperformancegapbetweenthe study.Thistaskismorechallengingsincetherepresentationof twomodelsmaybeattributedtothefactthatweonlyusedthe thesamefunctionvariessignificantlyacrossdifferentinstruction trainingsetofBinaryCorp-3Manddidnotutilizethetrainingset sets,andthereareadditionalissuessuchassemanticalignment ofBinaryCorp-26Mduetoitslargesize.Basedontheexperimental betweendifferentassemblylanguages.Inthefuture,weplanto findings,theperformanceofFastBCSD-TextCNNissimilartothat makemodificationstoFastBCSDtoadaptittothetaskofcross- ofjTrans,yetitshowssignificantimprovementoverotherbaseline platformbinaryfunctionrecognition., , FastBCSD:FastandEfficientNeuralNetworkforBinaryCodeSimilarityDetection Table2:ResultsofdifferentbinarysimilaritydetectionmethodsonBinaryCorp-3M(Poolsize=32) MRR Recall@1 Models O0,O3 O1,O3 O2,O3 O0,Os O1,Os O2,Os Average O0,O3 O1,O3 O2,O3 O0,Os O1,Os O2,Os Average Gemini 0.388 0.580 0.750 0.455 0.546 0.614 0.556 0.238 0.457 0.669 0.302 0.414 0.450 0.422 SAFE 0.826 0.917 0.958 0.854 0.927 0.927 0.902 0.729 0.869 0.933 0.766 0.879 0.880 0.843 Asm2Vec 0.479 0.878 0.961 0.536 0.855 0.900 0.768 0.351 0.828 0.942 0.408 0.796 0.863 0.701 GraphEmb 0.602 0.694 0.750 0.632 0.674 0.675 0.671 0.485 0.600 0.678 0.521 0.581 0.584 0.575 OrderMatters-online 0.542 0.740 0.869 0.638 0.702 0.682 0.695 0.414 0.647 0.822 0.515 0.611 0.593 0.591 OrderMatters 0.601 0.838 0.933 0.701 0.812 0.800 0.777 0.450 0.763 0.905 0.566 0.724 0.715 0.687 Genius 0.377 0.587 0.868 0.437 0.600 0.627 0.583 0.243 0.479 0.830 0.298 0.490 0.526 0.478 jTrans 0.947 0.976 0.985 0.956 0.979 0.977 0.970 0.913 0.960 0.974 0.927 0.964 0.961 0.949 FastBCSD-TextCNN 0.931 0.971 0.981 0.945 0.976 0.970 0.962 0.894 0.953 0.968 0.915 0.960 0.951 0.940 FastBCSD-LSTM 0.909 0.964 0.977 0.932 0.971 0.961 0.952 0.864 0.943 0.963 0.899 0.954 0.941 0.927 FastBCSD-MLP 0.900 0.964 0.978 0.921 0.969 0.961 0.948 0.851 0.943 0.963 0.883 0.950 0.940 0.921 Table3:ResultsofdifferentbinarysimilaritydetectionmethodsonBinaryCorp-3M(Poolsize=10000) MRR Recall@1 Models O0,O3 O1,O3 O2,O3 O0,Os O1,Os O2,Os Average O0,O3 O1,O3 O2,O3 O0,Os O1,Os O2,Os Average Gemini 0.037 0.161 0.416 0.049 0.133 0.195 0.165 0.024 0.122 0.367 0.030 0.099 0.151 0.132 SAFE 0.127 0.345 0.643 0.147 0.321 0.377 0.320 0.068 0.247 0.575 0.079 0.221 0.283 0.246 Asm2Vec 0.072 0.449 0.669 0.083 0.409 0.510 0.366 0.046 0.367 0.589 0.052 0.332 0.426 0.302 GraphEmb 0.087 0.217 0.486 0.110 0.195 0.222 0.219 0.050 0.154 0.447 0.063 0.135 0.166 0.169 OrderMatters 0.062 0.319 0.600 0.075 0.260 0.233 0.263 0.040 0.248 0.535 0.040 0.178 0.158 0.200 Genius 0.041 0.193 0.596 0.049 0.186 0.224 0.214 0.028 0.153 0.538 0.032 0.146 0.180 0.179 jTrans 0.475 0.663 0.731 0.539 0.665 0.664 0.623 0.376 0.580 0.661 0.443 0.586 0.585 0.538 FastBCSD-TextCNN 0.485 0.662 0.742 0.558 0.681 0.679 0.633 0.389 0.577 0.675 0.461 0.599 0.600 0.550 FastBCSD-LSTM 0.437 0.645 0.727 0.530 0.667 0.653 0.610 0.349 0.563 0.659 0.441 0.585 0.573 0.528 FastBCSD-MLP 0.398 0.638 0.721 0.476 0.660 0.652 0.590 0.309 0.557 0.652 0.387 0.582 0.574 0.510 Table4:ResultsofdifferentbinarysimilaritydetectionmethodsonBinaryCorp-26M(Poolsize=32).Itshouldbenotedthat
theFastBCSDmodelusesthetrainingsetfromBinaryCorp-3M,whiletheothermodelsinthetableemployBinaryCorp-26M, whichisasupersetofBinaryCorp-3M. MRR Recall@1 Models O0,O3 O1,O3 O2,O3 O0,Os O1,Os O2,Os Average O0,O3 O1,O3 O2,O3 O0,Os O1,Os O2,Os Average Gemini 0.402 0.643 0.835 0.469 0.564 0.628 0.590 0.263 0.528 0.768 0.322 0.441 0.518 0.473 SAFE 0.856 0.940 0.970 0.874 0.935 0.934 0.918 0.770 0.902 0.951 0.795 0.891 0.891 0.867 Asm2Vec 0.439 0.847 0.958 0.490 0.788 0.849 0.729 0.314 0.789 0.940 0.362 0.716 0.800 0.654 GraphEmb 0.583 0.681 0.741 0.610 0.637 0.639 0.649 0.465 0.586 0.667 0.499 0.541 0.543 0.550 OrderMatters 0.572 0.820 0.932 0.630 0.692 0.771 0.729 0.417 0.740 0.903 0.481 0.692 0.677 0.652 jTrans 0.964 0.983 0.989 0.969 0.980 0.980 0.978 0.941 0.970 0.981 0.949 0.964 0.964 0.962 FastBCSD-TextCNN 0.926 0.968 0.976 0.944 0.972 0.967 0.959 0.888 0.949 0.963 0.916 0.955 0.948 0.9368 Table5:ResultsofdifferentbinarysimilaritydetectionmethodsonBinaryCorp-26M(Poolsize=10000).Itshouldbenotedthat theFastBCSDmodelusesthetrainingsetfromBinaryCorp-3M,whiletheothermodelsinthetableemployBinaryCorp-26M, whichisasupersetofBinaryCorp-3M. MRR Recall@1 Models O0,O3 O1,O3 O2,O3 O0,Os O1,Os O2,Os Average O0,O3 O1,O3 O2,O3 O0,Os O1,Os O2,Os Average Gemini 0.072 0.189 0.474 0.069 0.147 0.202 0.192 0.058 0.148 0.420 0.051 0.115 0.162 0.159 SAFE 0.198 0.415 0.696 0.197 0.377 0.431 0.386 0.135 0.314 0.634 0.127 0.279 0.343 0.305 Asm2Vec 0.118 0.443 0.703 0.107 0.369 0.480 0.370 0.099 0.376 0.638 0.086 0.307 0.413 0.320 GraphEmb 0.116 0.228 0.498 0.133 0.198 0.224 0.233 0.080 0.171 0.465 0.090 0.145 0.175 0.188 OrderMatters 0.113 0.292 0.682 0.118 0.256 0.295 0.292 0.094 0.222 0.622 0.093 0.195 0.236 0.244 jTrans 0.584 0.734 0.792 0.627 0.709 0.710 0.693 0.499 0.668 0.736 0.550 0.648 0.648 0.625 FastBCSD-TextCNN 0.535 0.710 0.772 0.607 0.713 0.709 0.674 0.456 0.643 0.717 0.527 0.647 0.646 0.606, , Huangetal. Table6:Theinferencetimeandmodelparametersizevary [12] Sepp Hochreiter and Jürgen Schmidhuber. 1997. Long Short-Term across different models. The inference time refers to the Memory. Neural Computation 9, 8 (11 1997), 1735–1780. https: averagetimerequiredtoinfereachsampleinthetestset, //doi.org/10.1162/neco.1997.9.8.1735 arXiv:https://direct.mit.edu/neco/article- pdf/9/8/1735/813796/neco.1997.9.8.1735.pdf measuredinseconds. [13] YikunHu,YuanyuanZhang,JuanruLi,andDawuGu.2017.BinaryCodeClone DetectionacrossArchitecturesandCompilingConfigurations.InProceedings ofthe25thInternationalConferenceonProgramComprehension(BuenosAires, model inferencetime modelsize Argentina)(ICPC’17).IEEEPress,88–98. https://doi.org/10.1109/ICPC.2017.22 jTrans 0.0129s 87.88m [14] Yoon Kim. 2014. Convolutional Neural Networks for Sentence Classifica- tion.. In Conference on Empirical Methods in Natural Language Processing, FastBCSD-TextCNN 0.00267s 13.44m Vol.abs/1408.5882.1746–1751. FastBCSD-LSTM 0.00371s 9.77m [15] AlexKrizhevsky,IlyaSutskever,andGeoffreyEHinton.2012.ImageNetClassi- FastBCSD-MLP 0.00195s 13.04m ficationwithDeepConvolutionalNeuralNetworks.InProceedingsofthe25th InternationalConferenceonNeuralInformationProcessingSystems-Volume1 (LakeTahoe,Nevada)(NIPS’12).CurranAssociatesInc.,RedHook,NY,USA, 1097–1105. [16] YoungJunLee,Sang-HoonChoi,ChulwooKim,Seung-HoLim,andKi-Woong 7 CONCLUSION Park.2017.LearningBinaryCodewithDeepLearningtoDetectSoftwareWeak- ness.InInKSIIThe9thInternationalConferenceonInternet(ICONI)2017Sympo- Inthispaper,weproposeanoveldynamicinstructionvectorencod- sium. ingmethodtakingonlyassemblycodeasinputfeaturescombing [17] XuezixiangLi,YuQu,andHengYin.2021. PalmTree:LearninganAssembly withalightweightneuralnetwork,namedFastBCSD,toaddress LanguageModelforInstructionEmbedding.InProceedingsofthe2021ACM SIGSACConferenceonComputerandCommunicationsSecurity(VirtualEvent, somelimitationsofcurrentmethodsinBCSDtask,suchasthe RepublicofKorea)(CCS’21).AssociationforComputingMachinery,NewYork, trainingofpre-trainedmodelsrequiresasignificantamountofcom- NY,USA,3236–3251. https://doi.org/10.1145/3460120.3484587 [18] BingchangLiu,WeiHuo,ChaoZhang,WenchaoLi,FengLi,AihuaPiao,andWei
putationalresources,andnormalizationoftokenscanleadtoloss Zou.2018.𝛼Diff:Cross-VersionBinaryCodeSimilarityDetectionwithDNN.In ofinformation.ExperimentalresultsshowthatFastBCSDachieves Proceedingsofthe33rdACM/IEEEInternationalConferenceonAutomatedSoftware asimilarperformancewiththestate-of-the-artpre-trainingmodel, Engineering(Montpellier,France)(ASE’18).AssociationforComputingMachin- ery,NewYork,NY,USA,667–678. https://doi.org/10.1145/3238147.3238199 butwithsignificantlyfewerparametersandfasterinferencespeed. [19] LucaMassarelli,GiuseppeAntonioDiLuna,FabioPetroni,LeonardoQuerzoni, andRobertoBaldoni.2019.SAFE:Self-AttentiveFunctionEmbeddingsforBinary REFERENCES Similarity..InDetectionofIntrusionsandMalware,andVulnerabilityAssessment. 309–329. [1] SilvioCesareandYangXiang.2011.MalwareVariantDetectionUsingSimilarity [20] TomasMikolov,KaiChen,andGregCorrado.2013.Efficientestimationofword SearchoverSetsofControlFlowGraphs.InProceedingsofthe2011IEEE10th representationsinvectorspace. arXiv:1301.3781 InternationalConferenceonTrust,SecurityandPrivacyinComputingandCom- [21] IlyaOTolstikhin,NeilHoulsby,AlexanderKolesnikov,LucasBeyer,Xiaohua munications(TRUSTCOM’11).IEEEComputerSociety,USA,181–189. https: Zhai,ThomasUnterthiner,JessicaYung,AndreasSteiner,DanielKeysers,Jakob //doi.org/10.1109/TrustCom.2011.26 Uszkoreit,MarioLucic,andAlexeyDosovitskiy.2021.MLP-Mixer:Anall-MLP [2] SilvioCesare,YangXiang,andWanleiZhou.2014.ControlFlow-BasedMalware ArchitectureforVision.InAdvancesinNeuralInformationProcessingSystems, VariantDetection.IEEETransactionsonDependableandSecureComputing11,4 M.Ranzato,A.Beygelzimer,Y.Dauphin,P.S.Liang,andJ.WortmanVaughan (2014),307–317. https://doi.org/10.1109/TDSC.2013.40 (Eds.),Vol.34.CurranAssociates,Inc.,24261–24272. https://proceedings.neurips. [3] SumitChopra,RaiaHadsell,andYannLeCun.2005.LearningaSimilarityMetric cc/paper/2021/file/cba0a4ee5ccd02fda0fe3f9a3e7b89fe-Paper.pdf Discriminatively,withApplicationtoFaceVerification.InProceedingsofthe2005 [22] AshishVaswani,NoamShazeer,NikiParmar,JakobUszkoreit,LlionJones, IEEEComputerSocietyConferenceonComputerVisionandPatternRecognition AidanN.Gomez,ŁukaszKaiser,andIlliaPolosukhin.2017.AttentionisAllYou (CVPR’05)-Volume1-Volume01(CVPR’05).IEEEComputerSociety,USA, Need.InProceedingsofthe31stInternationalConferenceonNeuralInformation 539–546. https://doi.org/10.1109/CVPR.2005.202 ProcessingSystems(LongBeach,California,USA)(NIPS’17).CurranAssociates [4] JacobDevlin,Ming-WeiChang,KentonLee,andKristinaToutanova.2018.Bert: Inc.,RedHook,NY,USA,6000–6010. Pre-trainingofdeepbidirectionaltransformersforlanguageunderstanding. [23] HaoWang,WenjieQu,GiladKatz,WenyuZhu,ZeyuGao,HanQiu,Jianwei arXiv:1810.04805 Zhuge,andChaoZhang.2022. JTrans:Jump-AwareTransformerforBinary [5] StevenH.H.Ding,BenjaminC.M.Fung,andPhilippeCharland.2016.Kam1n0: CodeSimilarityDetection.InProceedingsofthe31stACMSIGSOFTInternational MapReduce-BasedAssemblyCloneSearchforReverseEngineering.InProceed- SymposiumonSoftwareTestingandAnalysis(Virtual,SouthKorea)(ISSTA2022). ingsofthe22ndACMSIGKDDInternationalConferenceonKnowledgeDiscovery AssociationforComputingMachinery,NewYork,NY,USA,1–13. https://doi. andDataMining(SanFrancisco,California,USA)(KDD’16).Associationfor org/10.1145/3533767.3534367 ComputingMachinery,NewYork,NY,USA,461–470. https://doi.org/10.1145/ [24] ZhicaiWang,YanbinHao,XingyuGao,HaoZhang,ShuoWang,TingtingMu, 2939672.2939719 andXiangnanHe.2022.ParameterizationofCross-TokenRelationswithRelative [6] StevenH.H.Ding,BenjaminC.M.Fung,andPhilippeCharland.2019.Asm2Vec: PositionalEncodingforVisionMLP.InProceedingsofthe30thACMInternational BoostingStaticRepresentationRobustnessforBinaryCloneSearchagainstCode ConferenceonMultimedia(Lisboa,Portugal)(MM’22).AssociationforComputing ObfuscationandCompilerOptimization.In2019IEEESymposiumonSecurity Machinery,NewYork,NY,USA,6288–6299. https://doi.org/10.1145/3503161. andPrivacy(SP).472–489. https://doi.org/10.1109/SP.2019.00003 3547953 [7] LiDong,NanYang,WenhuiWang,FuruWei,XiaodongLiu,YuWang,Jianfeng [25] XiaojunXu,ChangLiu,QianFeng,HengYin,LeSong,andDawnSong.2017. Gao,MingZhou,andHsiao-WuenHon.2019. UnifiedLanguageModelPre- NeuralNetwork-BasedGraphEmbeddingforCross-PlatformBinaryCodeSimi- TrainingforNaturalLanguageUnderstandingandGeneration.InProceedings larityDetection.InProceedingsofthe2017ACMSIGSACConferenceonComputer ofthe33rdInternationalConferenceonNeuralInformationProcessingSystems. andCommunicationsSecurity(Dallas,Texas,USA)(CCS’17).Associationfor CurranAssociatesInc.,RedHook,NY,USA,Article1170,13pages. ComputingMachinery,NewYork,NY,USA,363–376. https://doi.org/10.1145/
[8] QianFeng,RundongZhou,ChengchengXu,YaoCheng,BrianTesta,andHeng 3133956.3134018 Yin.2016.ScalableGraph-BasedBugSearchforFirmwareImages.InProceedings [26] ZepingYu,RuiCao,QiyiTang,SenNie,JunzhouHuang,andShiWu.2020.Order ofthe2016ACMSIGSACConferenceonComputerandCommunicationsSecurity Matters:Semantic-AwareNeuralNetworksforBinaryCodeSimilarityDetection. (Vienna,Austria)(CCS’16).AssociationforComputingMachinery,NewYork, ProceedingsoftheAAAIConferenceonArtificialIntelligence34,01(Apr.2020), NY,USA,480–491. https://doi.org/10.1145/2976749.2978370 1145–1152. https://doi.org/10.1609/aaai.v34i01.5466 [9] FrancescoFusco,DamianPascual,andPeterStaar.2022.pNLP-Mixer:anEfficient [27] FeiZuo,XiaopengLi,ZhexinZhang,PatrickYoung,LannanLuo,andQiangZeng. all-MLPArchitectureforLanguage. arXiv:2202.04350 2019.NeuralMachineTranslationInspiredBinaryCodeSimilarityComparison [10] YemingGu,HuiShu,andFanHu.2022.UniASM:BinaryCodeSimilarityDetec- beyondFunctionPairs.(2019). tionwithoutFine-tuning. arXiv:2211.2211 [11] WenboGuo,DongliangMu,XinyuXing,MinDu,andDawnSong.2019.Deep- VSA:Facilitatingvalue-setanalysiswithdeeplearningforpostmortemprogram analysis.InProceedingsofthe28thUSENIXSecuritySymposium.USENIXAssoci- ation,1787–1804.
2306.14726 Can An Old Fashioned Feature Extraction and A Light-weight Model Improve Vulnerability Type Identification Performance? HieuDinhVo, SonNguyen∗ FacultyofInformationTechnology,VNUUniversityofEngineeringandTechnology,Hanoi,Vietnam ARTICLE INFO ABSTRACT Keywords: Recent advances in automated vulnerability detection have achieved potential results in helping Vulnerability type identification, vul- developersdeterminevulnerablecomponents.However,afterdetectingvulnerabilities,investigating nerabilityresolution,softwarevulner- tofixvulnerablecodeisanon-trivialtask.Infact,thetypesofvulnerability,suchasbufferoverflow ability ormemorycorruption,couldhelpdevelopersquicklyunderstandthenatureoftheweaknessesand localizevulnerabilitiesforsecurityanalysis.Inthiswork,weinvestigatetheproblemofvulnerability typeidentification(VTI).Theproblemismodeledasthemulti-labelclassificationtask,whichcouldbe effectivelyaddressedby“pre-training,thenfine-tuning”frameworkwithdeeppre-trainedembedding models.Weevaluatetheperformanceofthewell-knownandadvancedpre-trainedmodelsforVTI onalargesetofvulnerabilities.Surprisingly,theirperformanceisnotmuchbetterthanthatofthe classicalbaselineapproachwithanold-fashionedbag-of-word,TF-IDF.Meanwhile,thesedeepneural networkapproachescostmuchmoreresourcesandrequireGPU.Wealsointroducealightweight independentcomponenttorefinethepredictionsofthebaselineapproach.Ourideaisthatthetypesof vulnerabilitiescouldstronglycorrelatetocertaincodetokens(distinguishingtokens)inseveralcrucial partsofprograms.Thedistinguishingtokensforeachvulnerabilitytypearestatisticallyidentified basedontheirprevalenceinthetypeversustheothers.Ourresultsshowthatthebaselineapproach enhancedbyourcomponentcanoutperformthestate-of-the-artdeeppre-trainedapproacheswhile retainingveryhighefficiency.Furthermore,theproposedcomponentcouldalsoimprovetheneural networkapproachesbyupto92.8%inmacro-averageF1. Forinstance,ifadeveloperidentifiesavulnerablefunction, 1. Introduction asshowninFigure1,andknowsitcontainsabufferoverflow Software vulnerabilities are weaknesses in a software error, she can immediately focus her investigation on the systemthatcouldbeexploitedbyattackers.Thisexploitation code statements responsible for writing or copying data can cause substantial damage, especially for the critical into the buffer. This allows her to assess the likelihood of systems[1].Toreducemanualeffortindiscoveringvulner- thesestatementsexceedingthebuffer’sboundariesandover- abilities,researchershaveinvestedconsiderableeffortinin- writing adjacent memory locations. Consequently, she can vestigatingeffectiveapproachesforautomatedvulnerability initiate security analysis by examining the code statements detection,leadingtomanytechniques[2,3,4,5,6,7,8,9, atlines7,19,and30insteadofanalyzingtheentirefunction. 10,11,12].Recentadvancesinthisfieldhaveresultedina Oncethevulnerablestatement(line30)isidentified,shecan (quite)highaccuracyindeterminingwhetheranentiregiven employ established techniques, such as implementing size method/fileisvulnerableornot[3,5,6,7,8].Forexample, checks before writing or correcting the amount of data to withBigVulbenchmark[13],Fuetal.[3]proposeLineVul, becopied,tomitigatethevulnerability.Thus,bydetermin- which achieves more than 90% accuracy in vulnerability ing the vulnerability types after detecting vulnerable code, detection at the function level. With the support of these developers and code auditors can significantly reduce their state-of-the-art techniques, the next step, security analysis, workload,whichisespeciallybeneficialwhendealingwith thatdevelopershavetoperformisinvestigatingthedetected largesectionsofvulnerablecode. vulnerable functions to determine the actual presence of Despitetheimportanceofvulnerabilitytypeidentifica- the vulnerability. However, even having vulnerable code, tion (VTI) in debugging vulnerable code after being de- investigatingtofixthosefunctionscouldstillbeanon-trivial tected,theproblemhasnotreceivedthedeservedattention. task[14,15,16]. Inthiswork,wemakethefirststeptoexploretheproblemof Meanwhile, the knowledge of vulnerability types, such VTIbyusingtheexistingtechniquesinsoftwareengineering as buffer overflow or memory corruption, can offer signifi- (SE) and natural language processing (NLP). Particularly, cant insights to developers when debugging the vulnerable we model VTI as the multi-label text classification task in code. This information serves as a guide to understanding NLP[18,19,20].Thisisreasonablebecauseeachvulnerable theprinciplesbehindthevulnerability,enablingdevelopers function𝑓couldbeconsideredasadocument𝑑,andthetype toswiftlypinpointtheexactlocationofthevulnerabilityand setofthevulnerabilitiesin𝑓 couldbethelabelsetof𝑑. proposepotentialapproachestorectifytheflawedcode[17]. The NLP community recently witnessed a dramatic ∗Correspondingauthor paradigm shift towards the “pre-training + fine-tuning” hieuvd@vnu.edu.vn(H.D.Vo);sonnguyen@vnu.edu.vn(S.Nguyen) framework. Deep pre-trained models, e.g., BERT [21], in- ORCID(s):0000-0002-9407-1971(H.D.Vo);0000-0002-8970-9870(S. ducepowerfulembeddingsthatcanberapidlyfine-tunedon Nguyen) Vo et al.: PreprintsubmittedtoElsevier Page1of12 3202 nuJ 62 ]ES.sc[
1v62741.6032:viXraCan An Old Fashioned Feature Extraction and A Light-weight Model Improve VIT Performance? does a simple classification model with an old-fashioned 1 static long ec_device_ioctl_xcmd(struct cros_ec_dev *ec, code representation such as TF-IDF work for the VTI task void __user *arg) 2 { comparedtopre-trainedmodels? 3 long ret; Inthispaper,weconductexperimentstoevaluatetheper- 4 struct cros_ec_command u_cmd; formanceofthestate-of-the-artmethodsinnaturallanguage 5 struct cros_ec_command *s_cmd; processing (NLP) and software engineering (SE) for the 6 7 if (copy_from_user(&u_cmd, arg, sizeof(u_cmd))) VTItask.Weselecttwopre-trainedmodels,Word2vec[28] 8 return -EFAULT; and CodeBERT [29], which are the representative non- 9 10 if ((u_cmd.outsize > EC_MAX_MSG_BYTES) || contextual and contextual code embeddings [30]. We pick 11 (u_cmd.insize > EC_MAX_MSG_BYTES)) Word2vec because this model has become one of the most 12 return -EINVAL; popularpre-trainedmodelsforcodeduetoitsefficiency[24, 13 14 s_cmd = kmalloc(sizeof(*s_cmd) + max(u_cmd.outsize, 25].Meanwhile,thereasonsforourselectionofCodeBERT u_cmd.insize), are the model’s reputation and its strong improvements in 15 GFP_KERNEL); many SE tasks [27]. We also compare these state-of-the- 16 if (!s_cmd) 17 return -ENOMEM; artmodelsagainstasimplemulti-labelclassificationmodel, 18 Binary Relevance (BR), with old-fashion TF-IDF features. 19 if (copy_from_user(s_cmd, arg, sizeof(s_cmd) + With the BR classifier and TF-IDF, this approach is con- u_cmd.outsize)) { 20 ret = -EFAULT; sidered as the baseline of multi-label text classification in 21 goto exit; NLP[20](so-calledBASE). 22 } Our experiments on BigVul benchmark [13] show a 23 24 s_cmd->command += ec->cmd_offset; surprisingresult thattheadvancedpre-trainedmodelsjust 25 ret = cros_ec_cmd_xfer(ec->ec_dev, s_cmd); slightly improve the VTI performance of the baseline ap- 26 /* Only copy data to userland if data was received. */ proach by only less than 7% in classification accuracy. 27 if (ret < 0) 28 goto exit; Meanwhile,thedeeppre-trainedmodelsrequireGPUsand 29 costupto40Xand5Xmoretimeintrainingandpredicting 30 if (copy_to_user(arg, s_cmd, sizeof(*s_cmd) + compared to the baseline approach. These show that for u_cmd.insize)) 31 ret = -EFAULT; theVTItask,TF-IDFandclassicalBinaryRelevancecould 32 exit: capture well the features to distinguish vulnerability types 33 kfree(s_cmd); and efficiently achieve performance very competitive with 34 return ret; 35 } thedeeppre-trainedmodelsinVTI. Inthiswork,wealsointroduceasimpletechniquetoim- Figure 1: A buffer overflow in Linux Kernel, CVE-2016-6156 provetheVTIperformanceofBASE.Ourideaisthatcertain code(sub)tokensaremorelikelytoappear/notappearinthe vulnerabilitiesofatypethantheothers.Thesedistinguishing manydownstreamNLPproblemsbyaddingatask-specific tokens are identified beforehand (before predicting) by sta- lightweight linear layer on top of the transformer models. tistically analyzing the syntactic code elements crucial for BERT-like models (e.g., XLNet [22] and RoBERTa [23]) VTI(e.g.,functioncalls,assignments,orcontrolstructures) haveledtostate-of-the-artperformanceonmanyNLPtasks, in previously known vulnerable code. As an independent suchaspart-of-speechtaggingortextclassification.Forthe component, these distinguishing tokens are used to refine SE, pre-trained models have recently shown to be highly the predictions produced by BASE. The intuition is that if effectiveinmanyclassificationtaskssuchasbugdetection, afunctionispredictedtocontainavulnerabilitynotoftype clonedetection,andvulnerabilitydetection[24,25,26,27, 𝑡,yetactuallycontainsthedistinguishingtokensof𝑡which 2, 3]. This naturally raises a question: How are these pre- are prevalent in the cases of 𝑡 but not the other types; then thepredictionwillberefinedtothevulnerabilityof𝑡. trainedmodelseffectivefortheVTItask? Additionally, we suspect that given a set of all pos- Our experimental results show that the combination of sible vulnerability types 𝑇 and a vulnerable function 𝑓, BASE and our component significantly improves the VTI the types of the vulnerability in 𝑓, 𝑆 ⊆ 𝑇 could be performance of BASE and outperforms the advanced pre- determined by the appearance of code tokens in 𝑓. For trainedVTImodels.Meanwhile,thepredictingtimeslightly example, directory traversal vulnerabilities, which allow increases, and identifying distinguishing tokens does not attackers to access files/directories stored outside the web increase the overall training and preparing time. These re- rootdirectory,usuallycontaincertaincode(sub)tokenssuch sultsindicatethatBASE combiningwithaverylightweight as file, base_path, or directory. Another example is that componentcouldimprovetheVTIperformanceofadvanced bufferoverflowerrorsusuallyassociatewithbuffer(buf)or pre-trainedmodelswhileretainingaveryhighefficiency.We copy(cpy).Meanwhile,theimportanceorrelevanceofthese also show that our technique could effectively improve the (sub)tokensindeterminingthetypesofvulnerabilitiescould other VTI approaches when applied on top of them up to becapturedwellbytheold-fashionedcoderepresentations 92.8%F1-score.
such as TF-IDF features. Another natural question is: How Inbrief,thispapermakesthefollowingcontributions: Vo et al.: PreprintsubmittedtoElsevier Page 2 of 12Can An Old Fashioned Feature Extraction and A Light-weight Model Improve VIT Performance? 1. An exploratory study on the performance of both 6000 traditionalandadvancedVTItechniques. 2. Surprisingexperimentalresultsshowingthatasimple 4000 modelwithanold-fashionedfeatureextractioncould achieveaverycompetitiveperformancewiththestate- of-the-artapproaches. 2000 3. A lightweight but effective technique improving the performanceoftheexistingapproaches. 0 The detailed implementation and dataset can be found at: +Info DoS Bypass Overflow Exec. Mem. +Priv XSS Dir. Sql Inj. Http R. Code Corr. Trav. Spl. https://github.com/sonnguyenvnu/VIT-Project. The rest of this paper is organized as follows. Sec- Figure 2: The number of cases by vulnerability types tion2statestheproblemofvulnerabilitytypeidentification (VTI) with a benchmark and evaluation metrics for VTI approaches.Then,severalVTIapproachesmodelingtheVTI 8000 taskasthemulti-labelclassificationtaskandoursurprising results are introduced in Section 3. After that, Section 4 6000 introduces the design of our lightweight independent tech- nique and its effectiveness in improving BASE as well as 4000 theotherapproaches.Somethreatstovalidityarediscussed in Section 5. Section 6 provides the related work. Finally, 2000 Section7concludesthispaper. 0 2. VulnerabilityTypeIdentification 1 type 2 types 3 types 4 types +5 types Givenafinitesetofvulnerabilitytypes𝑇 andavulner- able function 𝑓, the vulnerability type identification (VTI) Figure 3: The number of cases by the number of types task associates a subset of types 𝑆 ⊆ 𝑇 with the function 𝑓.Avulnerablefunctiondataset𝐷consistsof𝑁vulnerable functionswiththeirvulnerabilitytypes(𝑓 ,𝑆 ),(𝑓 ,𝑆 ),..., BigVul.AsseeninFigure3,thevulnerabilitiesinmostofthe 1 1 2 2 (𝑓 ,𝑆 ).Inthiswork,wemodeltheproblemofvulnerabil- functionsbelongtoonlyonetype(about72%).Additionally, 𝑁 𝑁 itytypeidentificationasmulti-labeltextclassification[18]. there are more than 1K vulnerable functions having more Thisisreasonablebecauseeachvulnerablefunctioncouldbe thantwotypes. considered as a document, and the types of vulnerabilities There are some other public vulnerability datasets, but in the function could be considered as the label/tag set of they are not suitable for being used in our experiments. thedocument.Notethateachfunctionin𝐷 isavulnerable Particularly,SATEIVJuliet[32]isasyntheticvulnerability one which could be effectively detected by the existing dataset that is manually created from known vulnerable vulnerabilitydetectiontechniques[4,2,3,5,6,7,8]. patterns. However, Chakraborty et al. [11] have demon- stratedthatthisdatasetcontainsonlysimplevulnerabilities 2.1. Dataset which do not reflect real-world vulnerabilities. Meanwhile, Data selecting. To evaluate VTI approaches, we use Devign [10] and Reveal [11], which are constructed from BigVul,whichisoneofthelargestvulnerabilitydatasetsand thevulnerabilitiesinreal-worldopen-sourceprojects,donot providesthevulnerabilitytypesofeachcase.Thedatasetis providethevulnerabilitytypesforthevulnerablefunctions. collected from 348 real-world C/C++ projects on GitHub, Thus, we do not use these vulnerability datasets in our suchasChromium,Linux,Android,PHP,OpenSSL,QEMU, evaluationexperiments. andFFmpeg.Thedatasetincludesabout10,900vulnerable Datasplitting.ToevaluateVTImethods,weusearan- functions in 13 vulnerability types and 44,603 vulnerable dom training/validation/test split ratio of 80:10:10, i.e., the lines of code. In this dataset, the types of each vulnerable whole BigVul is split into 80% of training data, 10% of functionareextractedfromitscorrespondingCVE-Details. validating/fine-tuningdata,and10%oftestingdata. Fig. 2 and Fig. 3 show the statistical information of BigVul on vulnerability types and the number of types of 2.2. EvaluationMetrics vulnerabilityineachfunction.Particularly,DenialofService To evaluate VTI approaches, we apply the evaluation (DoS) and Overflow are the two most popular types of metrics which are widely used in multi-label classification vulnerabilityinthedataset.ThisisexpectedbecauseDenial studies[19].Foreachfunction𝑓 inthetestset,thetypesof vo uf lS ne er rv ai bc ie li( tD yo tyS p) ea sn [d 31O ]v .e Mrfl eo aw nwa hre iletw ,So qo lf Inth jee cm tioo nst (f Sr qe lqu Ine jn .)t 𝑌𝑓 𝑖 is =re 1pr ie fse 𝑇nte ∈d b 𝑇y ia sv oe nc eto or f𝑌 t𝑖 hs𝑖 eu vch ult nh ea rt abfo ilr it𝑗 y∈ typ[ e1 s, ‖ o𝑇 f‖ 𝑓], , and Http Response Splitting (Http R.Spl) are very rare in 𝑖𝑗 𝑗 Vo et al.: PreprintsubmittedtoElsevier Page 3 of 12Can An Old Fashioned Feature Extraction and A Light-weight Model Improve VIT Performance? otherwise 𝑌 = 0. Let denote vector 𝑍 the vulnerability 𝑖𝑗 𝑖 ∑ type prediction for 𝑓 𝑖 produced by a VTI technique. For 𝑃𝑟𝑒𝑐𝑖𝑠𝑖𝑜𝑛𝑚𝑎𝑐𝑟𝑜 = 𝑡∈𝑇 𝑃𝑟𝑒𝑐𝑖𝑠𝑖𝑜𝑛(𝑡) a test set containing 𝑁 cases (functions), the considering ‖𝑇 ‖ evaluation metrics including exact match ratio, hamming ∑ score, accuracy, macro-average, micro-average, weighted- 𝑅𝑒𝑐𝑎𝑙𝑙𝑚𝑎𝑐𝑟𝑜 = 𝑡∈𝑇 𝑅𝑒𝑐𝑎𝑙𝑙(𝑡) average,sample-average,arecomputedasfollows. ‖𝑇 ‖ Exactmatchratioindicatesthepercentageofvulnerable functions(cases)thathavealllabelspredictedcorrectly: 2×𝑃𝑟𝑒𝑐𝑖𝑠𝑖𝑜𝑛𝑚𝑎𝑐𝑟𝑜×𝑅𝑒𝑐𝑎𝑙𝑙𝑚𝑎𝑐𝑟𝑜 𝐹1𝑚𝑎𝑐𝑟𝑜 = 𝑃𝑟𝑒𝑐𝑖𝑠𝑖𝑜𝑛𝑚𝑎𝑐𝑟𝑜+𝑅𝑒𝑐𝑎𝑙𝑙𝑚𝑎𝑐𝑟𝑜 𝑁 1 ∑ ExactMatchRatio= 𝑁 𝜇(𝑌 𝑖 =𝑍 𝑖) Weighted-averageissimplytheaverageoftheprecision 𝑖=1 andrecallforindividualclassesweightedbythesupportof
where 𝜇 returns 1 if 𝑌 and 𝑍 are exactly matched, ∀𝑗 ∈ that class. Meanwhile, to compute Sample average, preci- t[ h1 e, ‖ m𝑇 o‖ s] t,𝑌 s𝑖 t𝑗 ric= t o𝑍 n𝑖 e𝑗, aa mn𝑖 od n0 go thth e𝑖 er mw ei ts re ic. sE .x Wac et am lsa otc uh sr ea oti to heis r s thio en n, ar ve ec ra al gl, edan td heF m1 .-score are computed for each case and lessstrictmetricsforthemulti-labelsclassificationtask. Hammingscoreisdefinedastheproportionofthecor- 3. VulnerabilityTypeIdentificationas rectlypredictedtypestothetotalnumberofpredictedtypes Multi-labelClassification andactualtypesforeachcase.Theoverallhammingscoreis theaverageacrossallcases. Ingeneral,multi-labelclassificationcouldbeaddressed by two main approaches: problem transformation meth- 1 ∑𝑁 ‖𝑌 𝑖∩𝑍 𝑖‖ odsandadaptedmethods.Problemtransformationmethods HammingScore= transformamulti-labelproblemintomultiplebinaryclassifi- 𝑁 𝑖=1 ‖𝑌 𝑖∪𝑍 𝑖‖ cationproblems.Inthisfashion,thebinaryclassifierofeach Note that ‖𝑌 𝑖 ∩𝑍 𝑖‖ = ∑ ‖ 𝑗=𝑇 1‖(𝑌 𝑖𝑗 ∧𝑍 𝑖𝑗) and ‖𝑌 𝑖 ∪𝑍 𝑖‖ = l ta hb ee sel𝑙 a∈ re𝐿 thc ea nn tb rae ne sm fop rl moy ee dd bt ao cm ka ik ne toth me uc ll ta is -ls aifi bec lat ri eo pn rs e, sa en nd - ∑ 𝑗‖ =𝑇 1‖(𝑌 𝑖𝑗 ∨ 𝑍 𝑖𝑗). As seen, Hamming score only considers tations.Meanwhile,adaptedmethodsadaptexistingbinary label 1 in 𝑌 and 𝑍. We additionally use accuracy, which classification approaches to tag items with multiple labels 𝑖 𝑖 considersmatchingforbothlabels1and0. withoutrequiringproblemtransformations. In this work, accuracy is calculated as the following formula: 3.1. ClassicalBaselineApproach The baseline approach, which is called the binary rele- 1 ∑𝑁 1 ‖∑𝑇‖ vance (BR) method [20], transforms a multi-label problem Accuracy= 𝜇(𝑌 =𝑍 ) 𝑁 𝑇 𝑖𝑗 𝑖𝑗 into one binary classifier for each label. Hence BR inde- ‖ ‖ 𝑖=1 𝑗=1 pendently trains 𝐿 binary classifiers 𝐶 ,...,𝐶 . Each Thereareseveraldifferentmethodstomeasureamulti- classifier𝐶 isres‖ pon‖ sibleforpredictingth1 e0/1a‖ s𝐿 so‖ ciation 𝑖 labelclassifierbyaveragingoutthetypes:micro-averaging, for each corresponding label 𝑙 ∈ 𝐿. This approach is 𝑖 macro-average,weighted-average,andsample-average.For popularbecauseofitsconceptualsimplicity,butthismethod micro-averaging,alltrue-positivecases(TPs),true-negative ignoreslabelcorrelations.Duetothisinformationloss,BR’s cases (TNs), false-positive cases (FPs), and false-negative predicted label sets are likely to contain either too many cases (FNs) for each type are summed up, and then the or too few labels or labels that would never co-occur in averageistaken.Inthemicro-averagingmethod,wesumup practice[20]. theindividualTPs,FPs,andFNsofthesystemfordifferent Forthebaselineapproach,weusesimpleTF-IDF(short setsandthenapplythem. for Term Frequency – Inverse Document Frequency) fea- turestorepresenttheinstances.Basically,everywordinthe ∑ 𝑇𝑃𝑠(𝑡) 𝑃𝑟𝑒𝑐𝑖𝑠𝑖𝑜𝑛𝑚𝑖𝑐𝑟𝑜 = 𝑡∈𝑇 vocabulary set is considered as a feature. Each function is ∑ 𝑇𝑃𝑠(𝑡)+𝐹𝑃𝑠(𝑡) representedasabag-of-wordvector.Inthisvector,thevalue 𝑡∈𝑇 ∑ of a feature (word) increases proportionally to its count in 𝑇𝑃𝑠(𝑡) 𝑅𝑒𝑐𝑎𝑙𝑙𝑚𝑖𝑐𝑟𝑜 = 𝑡∈𝑇 thefunction,butitisinverselyproportionaltothefrequency ∑ 𝑡∈𝑇 𝑇𝑃𝑠(𝑡)+𝐹𝑁𝑠(𝑡) of the word in the corpus. The reason for the selection of Andthemicro-averageF1-scorewillbesimplytheharmonic TF-IDF for the baseline approach is that TF-IDF has been meanoftheabovetwoequations. appliedasthebaselinerepresentationandshownitspoten- tial in various software engineering tasks [25, 26] such as 2×𝑃𝑟𝑒𝑐𝑖𝑠𝑖𝑜𝑛𝑚𝑖𝑐𝑟𝑜×𝑅𝑒𝑐𝑎𝑙𝑙𝑚𝑖𝑐𝑟𝑜 𝐹1𝑚𝑖𝑐𝑟𝑜 = codeauthorshipidentification[33]ordefectprediction[34]. 𝑃𝑟𝑒𝑐𝑖𝑠𝑖𝑜𝑛𝑚𝑖𝑐𝑟𝑜+𝑅𝑒𝑐𝑎𝑙𝑙𝑚𝑖𝑐𝑟𝑜 Indeed,theexistingstudieshaveempiricallyshownthatthe Macro-average is straight forward. We just take the use of TF-IDF could outperform the methods using more averageoftheprecisionandrecallofthesystemondifferent sophisticated approaches for certain tasks [25, 26], such as sets. thetaskofCodeAuthorshipIdentification. Vo et al.: PreprintsubmittedtoElsevier Page 4 of 12Can An Old Fashioned Feature Extraction and A Light-weight Model Improve VIT Performance? ForContextualEmbeddings,weselectCodeBERT[29] asthismodelhasachievedstrongimprovementsonmanySE tasks, showing their great generalizability [27, 25]. Code- BERTsharesthesamearchitectureofBERT(Bidirectional EncoderRepresentationfromTransformer)[21],whichuses the bidirectional transformer encoder to effectively exploit both the left and right contexts of a target token. Two objectives are designed for BERT-liked models: masked languagemodelandnextsentenceprediction.Inthemasked Figure 4: Traditional Baseline Approach (Base) for vulnera- languagemodel,someofthetokensarerandomlymasked, bility type identification andthegoalistopredictthesemaskedtokensbasedontheir surrounding unmasked context tokens. For next-sentence prediction, the goal is to predict whether a sentence is the In this work, we construct the feature set covering uni- nextsentenceofthecurrentonetocapturetherelationships gramsandbigrams.Inordertodropsomeirrelevantfeatures betweensentences. and reduce the dimensionality problem, we apply the Chi- Tothebestofourknowledge,novulnerabilitytypeiden- Square test for feature selection to select the most statisti- tificationstudyhasbeenpublished.Notethat𝜇VulDeePecker[17] cally relevant TF-IDF features, i.e., keep only the features could output vulnerable functions with vulnerability type.
exceedingacertain𝑝-value.Thereducedvectorsarefedto However,thatapproach’sgoalistodetermineifafunction a Binary Relevance Multi-label Classifier with a Gaussian iscleanorofexactlyonevulnerability,thisisfundamentally NaiveBayes-basedClassifier(Fig.4). different from the task of vulnerability type identifica- tion.ThedetaileddifferencesbetweenVTIapproachesand 3.2. DeepLearningApproaches 𝜇VulDeePeckerarediscussedinSection6. Neuralnetworks(NN)canbedirectlyadaptedtosupport In this work, for both deep learning models, we follow multi-label classification by simply specifying the number thetypicalarchitecturesofclassifiersforthegeneralmulti- of target labels as the number of nodes in the output layer. labeltextclassificationtaskinsteadofdesigningacomplex For example, a task that has three output labels (classes) model.Weevaluatetheperformanceofthemulti-labelclas- will require a NN output layer with three nodes in the sificationmodelusingWord2vecproposedby[19].Theyuse output layer. Additionally, till now, the community of SE Word2vectoconstructawordembeddinglayerfollowedby researchershaspaidtremendouseffortstodeveloppowerful two Bi-LSTM layers, an attention layer, a fully connected, coderepresentationsforSEclassificationtasks,suchascode and the sigmoid activation function (Fig. 5). Fig. 6 shows authorshipidentification,codeclonedetection,sourcecode theclassificationmodelwithCodeBERTproposedby[27]. classification, and software defect prediction. In this work, In this model, CodeBERT is used as an embedding layer weinvestigatetheperformanceofmulti-labelclassification encoding every vulnerable function to a vector. The model models for VTI adapted from NN approaches using ad- also feeds the embedding to a fully connected layer and vancedcoderepresentations. eitherthesigmoidfunctiontocomputetheclassification.For WiththerapiddevelopmentofdeeplearninginSEap- both models, we use binary cross entropy [19] to compute plications,variouscoderepresentationtechniqueshavebeen thelossbetweentheclassificationandthegroundtruth. proposed, which can be categorized into two broad cate- gories:Non-contextualEmbeddingsandContextualEmbed- 3.3. ExperimentalResults dings.Non-contextualembeddingssuchasWord2vec[28], Table 1 (Original Performance tab) shows the perfor- GloVe [35], fastText [36], Code2vec [37], produce fixed mance of the studied VTI approaches. Note that all our representations for words in the vocabulary without con- experiments were conducted on a workstation with a P100 sidering the meanings of words/code tokens in different GPU,dualvCPUs,and32GBRAM. contexts. Meanwhile, by contextual embeddings such as As seen in Original Performance tab of Table 1, VTI CodeBERT [29] and CuBERT [38], the representations of withCodeBERTachievedthebestperformanceamongthe tokensareadjustedbasedondifferentcontexts. three approaches. However, the performance of this deep ForNon-contextualEmbeddings,Word2vechasbecome pre-trainedmodelisslightlybetterthanthatofBASE,about one of the most popular code embedding techniques for 4%-7.5% in F1-scores for macro average, micro average, softwareengineeringtasks[24,25]duetoitshighefficiency. weight average, and sample average. Meanwhile, this ad- Word2vec produces a low-dimensional semantic space by vancedmethodimproves5.5%,6.4%,andonly1.1%inexact using two different model architectures: Skip-gram (i.e., match ratio, hamming score, and accuracy, respectively. startingfromasinglewordtopredictitscontext)orContin- BASEevensignificantlyoutperformstheVTIapproachwith uousBag-of-Words(i.e.,startingfromthecontexttopredict Word2vec in all the considering metrics. Especially, the aword).Inthiswork,weuseWord2vecwithSkip-gramas micro-averageofBASEdoublesthecorrespondingfigureof arepresentativenon-contextualembeddingtechnique. Word2vec. Vo et al.: PreprintsubmittedtoElsevier Page 5 of 12Can An Old Fashioned Feature Extraction and A Light-weight Model Improve VIT Performance? Table 1 Vulnerability type identification performance Original Performance After Enhancement Base Word2vec CodeBERT Base Word2vec CodeBERT Prec. 0.71 0.55 0.73 0.72 0.60 0.74 micro-avg Rec. 0.69 0.43 0.73 0.78 0.56 0.79 F1 0.70 0.48 0.73 0.75 0.58 0.77 Prec. 0.65 0.41 0.67 0.69 0.70 0.70 macro-avg Rec. 0.60 0.24 0.65 0.75 0.48 0.76 F1 0.62 0.28 0.65 0.71 0.54 0.72 Prec. 0.71 0.50 0.73 0.73 0.61 0.74 weighted-avg Rec. 0.69 0.43 0.73 0.78 0.56 0.79 F1 0.70 0.47 0.73 0.75 0.55 0.76 Prec. 0.65 0.47 0.71 0.73 0.57 0.75 sample-avg Rec. 0.68 0.42 0.72 0.80 0.60 0.81 F1 0.65 0.42 0.70 0.74 0.55 0.76 ExactMatchRatio 0.54 0.30 0.57 0.60 0.32 0.57 HammingScore 0.62 0.39 0.66 0.69 0.49 0.71 Accuracy 0.89 0.84 0.90 0.91 0.86 0.91 Training time (ms) 148,824 2,610,032 4,938,020 148,851 2,610,035 4,938,035 Predict. time (ms) 4,320 12,349 22,282 5,243 13,841 24,028 GPU required No Yes Yes No Yes Yes Figure 6: Vulnerability type identification with CodeBERT Especially, BASE is much more efficient than the other approaches.Specially,BASEistrained20Xand40Xfaster Figure 5: Vulnerability type identification with Word2vec than the VTI approaches based on Word2vec and Code- BERT. Moreover, BASE is also much faster in predicting vulnerabilitytypeofvulnerablefunctions,3Xand5Xfaster
Table 2 shows the detailed classification performance compared to the Word2vec-based and CodeBERT-based (F1-score) of the three approaches for each vulnerability models. Notably, unlike the neural network approaches, type.BASEachievesF1-scorescomparablewiththoseofthe BASE can be trained and tested without GPU, while the CodeBERT-basedapproach,evenslightlybetterforMemory Word2vec-basedandCodeBERT-basedmodelsrequireGPU Corruption and Others. Additionally, BASE significantly andconsumemuchcomputationalresource.Thisadvantage improves the performance of the Word2vec-based method enables a flexible deployment for BASE on developers’ for all types. These results empirically demonstrate that machines which might not be very powerful with limited BASEwithatraditionalmulti-labelclassificationmodeland resourceswhileretainingacompetitiveVITperformance. theold-fashionedTF-IDFcouldachieveaverycompetitive performancecomparedtotheadvancedVTIapproaches. Vo et al.: PreprintsubmittedtoElsevier Page 6 of 12Can An Old Fashioned Feature Extraction and A Light-weight Model Improve VIT Performance? calls (e.g., copying data larger a buffer’s capacity). These Table 2 distinguishingtokensareusedtorefinethepredictionspro- Performance in F1 score by types ducedbyBASE.Particularly,afunction𝑓 shouldorshould Types Base Word2vec CodeBERT notbeofatype𝑡if𝑓 hasthedistinguishingtokensof𝑡. Information Gain 0.41 0.00 0.47 Definition2. (DistinguishingToken).Foratype𝑡 ∈ 𝑇,a Privilege Gain 0.63 0.13 0.67 distinguishing token in a syntactic code element is a code Bypass 0.42 0.00 0.48 token which is more/less prevalent in the syntactic code elements of the functions having vulnerabilities of type 𝑡 DoS 0.81 0.68 0.83 thaninanyothertypes. Execution Code 0.64 0.34 0.66 Memory Corruption 0.70 0.36 0.68 Among 𝐷 𝑡, which is the collection of cases of type 𝑡, the prevalenceofatoken𝑐 regardingasyntacticcodeelement Overflow 0.67 0.37 0.75 𝑒, (𝑝𝑟𝑒𝑣(𝑐,𝑒,𝐷)), is reflected via the ratio of the syntactic 𝑡 Others 0.69 0.34 0.68 code elements 𝑒 of cases containing 𝑐 in 𝐷. Formally, 𝑡 𝑝𝑟𝑒𝑣(𝑐,𝑒,𝐷) = 𝑐𝑜𝑢𝑛𝑡(𝑐,𝑒,𝐷 𝑡), where 𝑐𝑜𝑢𝑛𝑡(𝑐,𝑒,𝐷) is the number of c𝑡 ases wher‖ e𝐷 𝑡t‖ he elements 𝑒 contain 𝑐.𝑡 Token 𝑐 4. ALight-weightMethodtoImprove isapositivedistinguishingtokensof𝑡,𝑐 ∈ Δ+(𝑡,𝑒),if𝑐 is VulnerabilityTypeIdentification moreprevalentinthecasesoftype𝑡thananyothertypes: AsshowninSection3.3,BASEisveryefficientbecause 𝑝𝑟𝑒𝑣(𝑐,𝑒,𝐷) oftheadoptionofthesimplecoderepresentationandclas- 𝑑𝑖𝑠+(𝑐,𝑒,𝑡,𝐷)= 𝑡 >1 sificationmodel.However,theappearanceofcodetokensin max 𝑡′∈𝑇⧵{𝑡}𝑝𝑟𝑒𝑣(𝑐,𝑒,𝐷 𝑡′) all the parts of vulnerable functions is considered equally Whenmax 𝑝𝑟𝑒𝑣(𝑐,𝑒,𝐷 )=0,then𝑑𝑖𝑠+(𝑐,𝑒,𝑡,𝐷)is important. Meanwhile, we observe that there are certain 𝑡′∈𝑇⧵{𝑡} 𝑡′ infinity.Inthatcase,𝑐appearsin𝐷 only,notintheothers. codesyntacticelements,suchasfunctioncalls,assignments, 𝑡 Meanwhile,regardingasyntacticcodeelement𝑒,there or control structures, which could be more crucial than arecertaintokenswhicharemoreprevalentinthecasesof theothersindeterminingvulnerabilitytypes.Thus,instead theothertypesratherthan𝑡.Suchcodetokensareconsidered of considering code tokens in all code syntactic elements as negative distinguishing tokens of 𝑡 regarding 𝑒, 𝑐 ∈ equallyimportant,focusingonthosecrucialcodesyntactic Δ−(𝑡,𝑒). Formally, 𝑐 ∈ Δ−(𝑡,𝑒) if 𝑐 satisfies the following elementsinvulnerablefunctionscouldimprovetheaccuracy condition: ofVTIpredictions.Weproposeanindependentprediction- refining component to enhance the VIT performance of min 𝑝𝑟𝑒𝑣(𝑐,𝑒,𝐷 ) BASEwhileretainingitsoverallefficiency. 𝑑𝑖𝑠−(𝑐,𝑒,𝑡,𝐷)= 𝑡′∈ 𝑝𝑇 𝑟⧵ 𝑒{ 𝑣𝑡} (𝑐,𝑒,𝐷) 𝑡′ >1 𝑡 4.1. Design If 𝑐 is never in any case of type 𝑡, then 𝑝𝑟𝑒𝑣(𝑐,𝑒,𝐷) = 0 𝑡 Definition1. (Syntactic Code Element). A syntactic code and 𝑑𝑖𝑠−(𝑐,𝑒,𝑡,𝐷) = ∞. Intuitively, regarding a syntactic element is a syntactical part of programs defined by the code element, when a case has a positive distinguishing programminglanguageinuse. token of type 𝑡, then the vulnerable function is likely to haveavulnerabilityof𝑡(𝑅𝑢𝑙𝑒+).Similarly,ifthecasehas Inthiswork,weuseJoern[39],whichiswidelyapplied a negative distinguishing token of type 𝑡, the vulnerable in the existing studies [5, 6, 4, 2, 7], to analyze vulner- function is likely to be a case of any types other than 𝑡 able functions and extract their syntactic code elements. (𝑅𝑢𝑙𝑒−). In BigVul, about 95% of vulnerable statements are/con- Avulnerablefunction𝑓 mightsatisfyneither𝑅𝑢𝑙𝑒+nor taineitherfunctioncalls(78%),assignments(44%),control 𝑅𝑢𝑙𝑒−.Thepredictionfor𝑡hastorelyonthepredictionof structures (38%), or return statements (19%). Instead of BASE.Thus,weapply𝑅𝑢𝑙𝑒+and𝑅𝑢𝑙𝑒−todesignatechnique considering all code elements equally important in VTI, whichcanbeusedasanindependentcomponentcombined focusing on those crucial kinds of elements in vulnerable withtheVTImodel.Particularly,fortheprediction𝑍 of𝑓 functions could improve VTI performance. Based on the producedbyBASE,weapply𝑅𝑢𝑙𝑒+and𝑅𝑢𝑙𝑒−torefine𝑍to observation, we design a lightweight technique that can be producethefinalprediction𝑍′.Particularly,foratype𝑡 ∈ applied as an independent step to improve BASE’s perfor- 𝑇,𝑍′[𝑡],whichisthesyntacticcodeelementcorresponding mance.Ourideaisthatthecodetokens,whichcanbeused 𝑡in𝑍′,isrefinedbasedonthatof𝑍 (i.e.,𝑍[𝑡]): to distinguish each vulnerability type from the others (so- called, distinguishing tokens), are identified by statistically • If a syntactic code element 𝑒 of 𝑓 contains 𝑐 ∈ analyzing the training set on the selective syntactic code Δ+(𝑡,𝑒),yet𝑍[𝑡]=0,then𝑍′[𝑡]=1.
elements which are critical for VTI such as function calls, • If a syntactic code element 𝑒′ of 𝑓 contains 𝑐′ ∈ assignments, control structures, and return statements. For Δ−(𝑡,𝑒),yet𝑍[𝑡]=1,then𝑍′[𝑡]=0. example, Buffer Overflow vulnerabilities usually cause by theassignments(e.g.,assigningtoolargeindex)orfunction • Otherwise,𝑍′[𝑡]=𝑍[𝑡]. Vo et al.: PreprintsubmittedtoElsevier Page 7 of 12Can An Old Fashioned Feature Extraction and A Light-weight Model Improve VIT Performance? In fact, applying the observation, that certain syntactic accuracyofBASEineachcaseisalreadyhigh.Thisleadsto code elements are more important than others in VTI, as a thelowimprovementbyENHANCEDBASEinaccuracy. lightweightindependentcomponentcouldexpandtheappli- Compared to CodeBERT-based approach. As seen in cabilityofourtechnique.Indeed,therefiningstepusingour Table 1, ENHANCED BASE achieved better performance in technique could be applied as an independent component all the metrics (except micro-average precision) compared of any VTI approach. We will show the performance of to the CodeBERT-based approach. For micro-average, al- theotherapproacheswhencombinedwithourtechniquein thoughtheprecisionof ENHANCED BASE isslightlylower Sec.4.2. thanthatofCodeBERT(0.72vs.0.73),theimprovementof ENHANCED BASEintherecallismoresignificant(0.78vs. 4.2. VITPerformanceImprovement 0.73).Thisresultsinanimprovementinmicro-averageF1. Improving BASE’s VTI performance. To evaluate the Analyzing the cases where CodeBERT-based can perform effectivenessofourmethodinimprovingVITperformance, well while ENHANCED BASE did not, we found that these we apply our method as the post-processing step of BASE caseshavequitecomplexlogicandbelongtomultipletypes (so-calledENHANCEDBASE).Notethatallourexperiments which have a causal relationship. For example, DoS vul- were conducted on a workstation with a P100 GPU, dual nerabilitiescouldbecausedbyOverflowones.Meanwhile, vCPUs,and32GBRAM. ENHANCED BASE does not consider the relationship be- After enhancement, 308 predictions in 1,055 cases are tweentypes.Thus,althoughtheyhavecertaindistinguishing affectedwithanaccuracyrateof84%.Inotherwords,there tokensofatype,ENHANCEDBASEmightfailtoinferthata are 260/308 predictions are accurately corrected. Table 1 vulnerablecodealsohasothertypes. (tab After Enhancement) shows the VIT performance of In our implementation, the preparing (prep.) step to BASEwiththepost-processingstep.ComparedtoBASE(tab extract distinguishing tokens and the model training step Original Performance), after applying the post-processing are performed in parallel. Thus, the total time for model step,themacro-averageprecisionincreasesby6.1%,while trainingandpreparingisstill2.48minutes.Meanwhile,the the macro-average recall is significantly improved by 25%. predicting time slightly increases from 4.0 to 5.2 seconds. Thismeansthatforavulnerabilitytype𝑡,ENHANCEDBASE These time costs are much more efficient than those of notonlyidentifiedmuchmorethecasesof𝑡(higherrecall) CodeBERT. but also is more precise in identifying 𝑡 (higher precision). Overall, we can conclude that a simple model com- Indeed,asshowninTable3,theprecisionof5/8typesand bined with a lightweight component could achieve better recallofalltypesareimproved.Especially,theprecisionfor VTIperformanceandbemuchmoreefficientthanadvanced Information Gain is improved by 37%, while ENHANCED deeppre-trainedapproaches.Thiscouldbeverymeaningful BASEdoublestherecallofBASEforthistype. for users who want to achieve both high effectiveness and Forthemicro-averageinTable1,theprecisionandrecall efficiencyinVTI. areslightlyimprovedby1.4%and13.0%.Thereasonisthat Effectivenessinimprovingapproaches.Inspiredbythe forcertaintypes,suchasDoSorOverflow,withmorecases success of our method in improving the performance of thantheothertypes,BASEalreadylearnsbetterinidentify- BASE, we apply the technique to enhance the other ap- ing these types. Thus, ENHANCED BASE did not improve proaches. Table 1 (tab After Enhancement) shows the VTI BASE much for those types. Consequently, micro-average performanceofWord2vecandCodeBERTapproachesafter metrics, which are calculated based on individual TP, FP, applying our method as a post-processing step. Compared andFN,werenotimprovedmuch.Thisreasonexplainsthe to their performance before enhancement (Table 1), the slight improvement in the weighted-average. Meanwhile, performance of all these approaches is improved. The im- forsamples-average,theimprovementsintheprecisionand provements for CodeBERT are minor but still visible by recallaremoresignificant,12%and17%,respectively.This up to 10% in macro-average F1. The numbers of affected demonstrates the effectiveness of the ENHANCED BASE in predictionsandaccuracyratesforWord2vecandCodeBERT improvingtheindividualpredictionsofBASE. are shown in Table 4. As seen, the effect of the post- The improvements in these above metrics result in the processing step on the Word2vec-based approach is more increasesofallexactmatchratio,hammingscore,andaccu- significant, with a higher accuracy rate compared to that racy(Table1).Asseen,ENHANCEDBASEcangive3/5fully of the CodeBERT-based method. The reason could be that correct predictions. Meanwhile, more than 2/3 predicted theadvanceddeeppre-trainedCodeBERTcancapturewell types(hammingscoreof69%)areaccuratelygivenbyEN- certaindegreesofourrules.Thus,ourmethodwasnotvery
HANCED BASE.ComparedtoBASE,boththeexactlymatch effectiveinimprovingtheCodeBERT-basedVITapproach. ratioandhammingscoreofENHANCEDBASEaremorethan However,theimprovementsinallthemicro-average,macro- 10% better. However, the improvement in accuracy is only average, weighted-average, and sample-average metrics for 2.2%.Thisisbecausethecaseswhosevulnerabilitytypeset Word2vec are significant. Among these metrics, macro- is small are very popular, and models tend to predict very average F1 increases by 92.8% after applying our post- fewtypes.Meanwhile,accuracyconsidersbothlabels0and processing step. These results demonstrate that our ap- 1 in prediction vectors and ground-truth vectors. Thus, the proach is very effective in improving the VTI performance ofnotonlyBASE,butalsotheothers. Vo et al.: PreprintsubmittedtoElsevier Page 8 of 12Can An Old Fashioned Feature Extraction and A Light-weight Model Improve VIT Performance? Table 3 VTI performance of Base and Enhanced Base by types Base Enhanced Base Types Precision Recall F1 Precision Recall F1 Information Gain 0.41 0.42 0.41 0.56 0.83 0.67 Privilege Gain 0.75 0.55 0.63 0.80 0.74 0.77 Bypass 0.43 0.42 0.42 0.55 0.75 0.64 DoS 0.81 0.80 0.81 0.81 0.89 0.84 Execution Code 0.68 0.61 0.64 0.70 0.66 0.68 Memory Corruption 0.82 0.62 0.70 0.82 0.63 0.71 Overflow 0.65 0.69 0.67 0.66 0.74 0.70 Others 0.66 0.72 0.69 0.66 0.72 0.69 Table 4 6. RelatedWork The effects of the post-pocessing step on the VTI approaches Vulnerability/BugDetectionandPrevention.Various Base Word2vec CodeBERT methods have been proposed to determine if a code com- ponent (component, file, function/method, or statement/- No. of affected predictions 308 428 237 line) is vulnerable. The rule-based techniques apply static Accuracy rate 0.74 0.80 0.72 analyzers and leverage seen vulnerability patterns, such as FlawFinder [40] or Coverity [41]. Recently, several deep- learning based approaches have been introduced [42, 8, 5, 9, 10, 11, 43, 44]. VulDeePecker [5] and SySeVR [6] introduce tools to detect slice-level vulnerabilities, which 5. ThreatstoValidity aremorefine-grained.IVDetect[4],whichisagraph-based neural network model, is proposed to detect vulnerabili- The main threats to the validity of our work consist of ties at the function level and use a model interpreter to internal,construct,andexternalthreats. identify vulnerable statements in the detected suspicious Threatstointernalvalidityincludetheinfluenceofthe functions. LineVul [3] and LineVD [2] apply CodeBERT method used to identify the code elements (e.g., function in their own way and have been shown that they are more calls, assignments, or control structures). To reduce this effectivethanIVDetectindetectingvulnerablefunctionsand threat,weuseJoern[39]codeanalyzer,whichiswidelyused lines/statements. VelVet [7] builds graph-based models to inexistingstudies[7,5,4,2]. detect vulnerable statements. Our work could complement Threats to construct validity relate to the suitability well with the existing automated vulnerability detection of our evaluation procedure. We used exact match ratio, approaches.Particularly,thetypeidentificationstepcouldbe hamming score, accuracy, macro-average, micro-average, appliedafterdevelopersuseavulnerabilitydetectionmethod weighted-average, and sample-average. They are the clas- to quickly interpret and fix the vulnerable functions. Our sicalevaluationmeasuresformulti-labelclassification[18]. work could also be applied to determine the vulnerability Threatstoexternalvaliditymainlylieintheselection types of a vulnerable code component before applying one ofmulti-labelclassificationmodelsusedinourexperiments. or more vulnerability detection approaches specialized for Tomitigatethisthreat,weselecttherepresentativemodels certainvulnerabilitytypes,suchastheapproachtomemory- whicharewell-knownforNLPandSEtasks.BASE iscon- relatedvulnerabilities[43]. sideredasthebaselineapproachforgeneralmulti-labeltext classification, while all Word2vec, Glove, and CodeBERT OurworkmightrelatedVUDENC[45]Wartschinskiet arereputedandshowntobeeffectiveinmanySEtasks.The al. and 𝜇VulDeePecker [17] by Zou et al. which focus on vulnerability detection and can implicitly indicate the type datasetusedinourexperimentsmightnotberepresentative ofvulnerability.Inotherwords,givenapieceofcode,these ornotveryhigh-quality.Toreducethisthreat,weusedthe techniques determine if the code is benign or belongs to largest public dataset [13], which is collected from a large one/somevulnerabilitytypes.VUDENC[45]usesseparate number of real-world projects and widely used in existing LSTM binary classification models to determine if a piece vulnerability detection studies [2, 3, 4]. Additionally, our of code is neutral/benign or belongs to some vulnerability data has only C/C++ code. Thus, we cannot claim that types. In this paper, we focus on the specific task of vul- similarresultswouldhavebeenobservedinotherprogram- nerability type identification integrated after vulnerability minglanguages.Furtherstudiesareneededtovalidateand generalizeourfindingstootherlanguages. Vo et al.: PreprintsubmittedtoElsevier Page 9 of 12Can An Old Fashioned Feature Extraction and A Light-weight Model Improve VIT Performance?
detection to provide developers with the type of vulnera- programs.Thedistinguishingtokensforavulnerabilitytype bilities effectively identified by the existing vulnerability are statistically identified based on their prevalence in the detection techniques [5, 6, 4, 3, 2] which determine if the type versus the others. Our results show that the baseline givencodeisbenignorvulnerable. Meanwhile,thegoalof approach enhanced by our component can outperform the 𝜇VulDeePecker [17] is to determine if a function is clean state-of-the-art deep pre-trained methods while retaining (not vulnerable) or of exactly one vulnerability. However, very high efficiency. Furthermore, the proposed technique ourworkdiffersfrom𝜇VulDeePeckerinthreefundamental couldalsoimprovetheneuralnetworkapproachesbyupto aspects. First, 𝜇VulDeePecker is a vulnerability detection 92.8%inmacro-averageF1. approach which is designed to decide if a function is vul- nerable. In other words, the input of that approach is a References function that has not known whether it is vulnerable or not. Meanwhile, our work is designed to apply as a step [1] H.Krasner,Thecostofpoorsoftwarequalityintheus:a2020report, after detecting vulnerable functions. Therefore, the input Proc.ConsortiumInf.Softw.QualityTM(CISQTM). [2] D.Hin,A.Kan,H.Chen,M.A.Babar,Linevd:Statement-levelvul- function of our work is assumed to be vulnerable. More- nerabilitydetectionusinggraphneuralnetworks,in:IEEE/ACM19th over, 𝜇VulDeePecker assumes that a vulnerable function International Conference on Mining Software Repositories, MSR has only one type. Thus, the multi-class classification is 2022,Pittsburgh,PA,USA,May23-24,2022,IEEE,2022,pp.596– consideredin𝜇VulDeePecker.Meanwhile,afunctioncould 607. belong to multiple types. Hence, in our work, the VTI [3] M. Fu, C. Tantithamthavorn, Linevul: A transformer-based line- levelvulnerabilityprediction,in:2022IEEE/ACM19thInternational problem is modeled as the multi-label classification task. ConferenceonMiningSoftwareRepositories(MSR),IEEEComputer Finally, 𝜇VulDeePecker is designed for the function call Society,LosAlamitos,CA,USA,2022,pp.608–620. vulnerabilities, while our work has no limit to the kind of [4] Y. Li, S. Wang, T. N. Nguyen, Vulnerability detection with fine- vulnerabilities. grainedinterpretations,in:Proceedingsofthe29thACMJointMeet- Learning-based approaches for SE tasks. Several ingonEuropeanSoftwareEngineeringConferenceandSymposium ontheFoundationsofSoftwareEngineering,2021,pp.292–303. studieshavebeenproposedforspecificSEtasks,including [5] Z.Li,D.Zou,S.Xu,X.Ou,H.Jin,S.Wang,Z.Deng,Y.Zhong, code suggestion/completion [46, 47, 48, 49, 50], program Vuldeepecker: A deep learning-based system for vulnerability de- synthesis[51],pullrequestdescriptiongeneration[52,53], tection, in: 25th Annual Network and Distributed System Security code summarization [54, 55, 56], code clones [57], fuzz Symposium,NDSS2018,SanDiego,California,USA,February18- testing[58], code-text translation [59], and program re- 21,2018,TheInternetSociety,2018. [6] Z.Li,D.Zou,S.Xu,H.Jin,Y.Zhu,Z.Chen,Sysevr:Aframework pair [60, 61]. Recently, several learning techniques have forusingdeeplearningtodetectsoftwarevulnerabilities,IEEETrans- beenproposedtolearnrepresentingsourcecodeforspecific actionsonDependableandSecureComputing19(04)(2022)2244– SEapplications[62,37]orgeneralSEtasks[29,38,63]. 2258. [7] Y.Ding,S.Suneja,Y.Zheng,J.Laredo,A.Morari,G.Kaiser,B.Ray, Velvet:anovelensemblelearningapproachtoautomaticallylocate 7. Conclusion vulnerable statements, in: 2022 IEEE International Conference on Software Analysis, Evolution and Reengineering (SANER), IEEE, Inthiswork,weinvestigatetheproblemofvulnerability 2022,pp.959–970. type identification (VTI) after vulnerability detection. The [8] G.Lin,J.Zhang,W.Luo,L.Pan,Y.Xiang,Poster:Vulnerabilitydis- problem is modeled as the multi-label classification task. coverywithfunctionrepresentationlearningfromunlabeledprojects, Particularly,eachdetectedvulnerablefunctionisconsidered in:Proceedingsofthe2017ACMSIGSACConferenceonComputer andCommunicationsSecurity,2017,pp.2539–2541. asadocument,andthesetofvulnerabilitytypesofthefunc- [9] X.Duan,J.Wu,S.Ji,Z.Rui,T.Luo,M.Yang,Y.Wu,Vulsniper:focus tioncouldbeconsideredasthelabelsetofthecorresponding yourattentiontoshootfine-grainedvulnerabilities,in:Proceedings document.ThisNLPtaskhasbeeneffectivelyaddressedby ofthe28thInternationalJointConferenceonArtificialIntelligence, pre-training,thenfine-tuningtheframeworkwithdeeppre- 2019,pp.4665–4671. trained embedding models. The existing studies show that [10] Y.Zhou,S.Liu,J.Siow,X.Du,Y.Liu,Devign:effectivevulner- abilityidentificationbylearningcomprehensiveprogramsemantics thedeeppre-trainedembeddingmodelsspecializedforcode viagraphneuralnetworks,in:Proceedingsofthe33rdInternational have also shown their effectiveness for many classification Conference on Neural Information Processing Systems, 2019, pp. tasks in software engineering. In this paper, we experi- 10197–10207. mentally evaluate the performance of the well-known and [11] S.Chakraborty,R.Krishna,Y.Ding,B.Ray,Deeplearningbased
advancedpre-trainedmodelsforVTIonalargesetofvulner- vulnerability detection: Are we there yet?, IEEE Transactions on SoftwareEngineering48(09)(2022)3280–3296. abilitiesinvarioustypes.Surprisingly,theirperformanceis [12] X.Cheng,G.Zhang,H.Wang,Y.Sui,Path-sensitivecodeembed- notmuchbetterthantheVTIperformanceofthetraditional dingviacontrastivelearningforsoftwarevulnerabilitydetection,in: baselineclassificationmodelwithanold-fashionedbag-of- Proceedingsofthe31stACMSIGSOFTInternationalSymposiumon wordTF-IDF.Meanwhile,theseneuralnetworkapproaches SoftwareTestingandAnalysis,2022,pp.519–531. cost much more time and require GPU. We also introduce [13] J. Fan, Y. Li, S. Wang, T. N. Nguyen, Ac/c++ code vulnerability dataset with code changes and cve summaries, in: Proceedings of a lightweight independent component to enhance the pre- the17thInternationalConferenceonMiningSoftwareRepositories, dictionsofthebaselineapproach.Ourideaisthatthetypes 2020,pp.508–512. of vulnerabilities could strongly correlate to certain code [14] E.Iannone,R.Guadagni,F.Ferrucci,A.DeLucia,F.Palomba,The tokens (distinguishing tokens) in several crucial parts of secretlifeofsoftwarevulnerabilities:Alarge-scaleempiricalstudy, IEEETransactionsonSoftwareEngineering49(1)(2022)44–63. Vo et al.: PreprintsubmittedtoElsevier Page 10 of 12Can An Old Fashioned Feature Extraction and A Light-weight Model Improve VIT Performance? [15] H.Pearce,B.Tan,B.Ahmad,R.Karri,B.Dolan-Gavitt,Canopenai [34] S.Wang,T.Liu,L.Tan,Automaticallylearningsemanticfeaturesfor codexandotherlargelanguagemodelshelpusfixsecuritybugs?, defectprediction,in:2016IEEE/ACM38thInternationalConference arXivpreprintarXiv:2112.02125. onSoftwareEngineering(ICSE),IEEE,2016,pp.297–308. [16] Z.Chen,S.Kommrusch,M.Monperrus,Neuraltransferlearningfor [35] J. Pennington, R. Socher, C. D. Manning, Glove: Global vectors repairing security vulnerabilities in c code, IEEE Transactions on forwordrepresentation,in:Proceedingsofthe2014conferenceon SoftwareEngineering49(1)(2022)147–165. empiricalmethodsinnaturallanguageprocessing(EMNLP),2014, [17] D. Zou, S. Wang, S. Xu, Z. Li, H. Jin, 𝜇 vuldeepecker: A deep pp.1532–1543. learning-based system for multiclass vulnerability detection, IEEE [36] P. Bojanowski, E. Grave, A. Joulin, T. Mikolov, Enriching word Transactions on Dependable and Secure Computing 18 (5) (2019) vectorswithsubwordinformation,Transactionsoftheassociationfor 2224–2236. computationallinguistics5(2017)135–146. [18] M.-L.Zhang,Z.-H.Zhou,Multilabelneuralnetworkswithapplica- [37] U. Alon, M. Zilberstein, O. Levy, E. Yahav, code2vec: Learning tionstofunctionalgenomicsandtextcategorization,IEEEtransac- distributed representations of code, Proceedings of the ACM on tionsonKnowledgeandDataEngineering18(10)(2006)1338–1351. ProgrammingLanguages3(POPL)(2019)1–29. [19] I.Ameer,N.Bölücü,M.H.F.Siddiqui,B.Can,G.Sidorov,A.Gel- [38] A. Kanade, P. Maniatis, G. Balakrishnan, K. Shi, Learning and bukh,Multi-labelemotionclassificationintextsusingtransferlearn- evaluatingcontextualembeddingofsourcecode,in:Proceedingsof ing,ExpertSystemswithApplications213(2023)118534. the37thInternationalConferenceonMachineLearning,ICML’20, [20] S.Godbole,S.Sarawagi,Discriminativemethodsformulti-labeled JMLR.org,2020. classification, in: Pacific-Asia conference on knowledge discovery [39] F.Yamaguchi,N.Golde,D.Arp,K.Rieck,Modelinganddiscovering anddatamining,Springer,2004,pp.22–30. vulnerabilitieswithcodepropertygraphs,in:2014IEEESymposium [21] J.D.M.-W.C.Kenton,L.K.Toutanova,Bert:Pre-trainingofdeep onSecurityandPrivacy,IEEE,2014,pp.590–604. bidirectionaltransformersforlanguageunderstanding,in:Proceed- [40] Flawfinder. ingsofNAACL-HLT,2019,pp.4171–4186. URLhttps://dwheeler.com/flawfinder/ [22] Z.Yang,Z.Dai,Y.Yang,J.Carbonell,R.R.Salakhutdinov,Q.V. [41] Coverity. Le,Xlnet:Generalizedautoregressivepretrainingforlanguageunder- URLhttp://scan.coverity.com/ standing,in:H.Wallach,H.Larochelle,A.Beygelzimer,F.d'Alché- [42] G.Lin,S.Wen,Q.-L.Han,J.Zhang,Y.Xiang,Softwarevulnerability Buc, E. Fox, R. Garnett (Eds.), Advances in Neural Information detectionusingdeepneuralnetworks:asurvey,Proceedingsofthe ProcessingSystems,Vol.32,CurranAssociates,Inc.,2019,pp.5753– IEEE108(10)(2020)1825–1848. 5763. [43] S.Cao,X.Sun,L.Bo,R.Wu,B.Li,C.Tao,Mvd:Memory-related [23] M.Ott,S.Edunov,A.Baevski,A.Fan,S.Gross,N.Ng,D.Grangier, vulnerabilitydetectionbasedonflow-sensitivegraphneuralnetworks, M.Auli,fairseq:Afast,extensibletoolkitforsequencemodeling,in: in: Proceedings of the 44th International Conference on Software
Proceedingsofthe2019ConferenceoftheNorthAmericanChapter Engineering,ICSE’22,AssociationforComputingMachinery,New oftheAssociationforComputationalLinguistics(Demonstrations), York,NY,USA,2022,p.1456–1468. 2019,pp.48–53. [44] X.Cheng,G.Zhang,H.Wang,Y.Sui,Path-sensitivecodeembed- [24] J.Zhang,X.Wang,H.Zhang,H.Sun,K.Wang,X.Liu,Anovelneural dingviacontrastivelearningforsoftwarevulnerabilitydetection,in: source code representation based on abstract syntax tree, in: 2019 Proceedings of the 31st ACM SIGSOFT International Symposium IEEE/ACM41stInternationalConferenceonSoftwareEngineering on Software Testing and Analysis, ISSTA 2022, Association for (ICSE),IEEE,2019,pp.783–794. ComputingMachinery,NewYork,NY,USA,2022,p.519–531. [25] Z. Ding, H. Li, W. Shang, T.-H. P. Chen, Can pre-trained code [45] L.Wartschinski,Y.Noller,T.Vogel,T.Kehrer,L.Grunske,Vudenc: embeddingsimprovemodelperformance?revisitingtheuseofcode Vulnerabilitydetectionwithdeeplearningonanaturalcodebasefor embeddingsinsoftwareengineeringtasks,EmpiricalSoftwareEngi- python,Inf.Softw.Technol.144(C). neering27(3)(2022)1–38. [46] S.Nguyen,H.Phan,T.Le,T.N.Nguyen,Suggestingnaturalmethod [26] H.J.Kang,T.F.Bissyandé,D.Lo,Assessingthegeneralizabilityof namestochecknameconsistencies,in:2020IEEE42ndInternational code2vectokenembeddings,in:201934thIEEE/ACMInternational ConferenceonSoftwareEngineering,IEEE,2020,pp.1372–1384. ConferenceonAutomatedSoftwareEngineering,2019,pp.1–12. [47] A.Hindle,E.T.Barr,M.Gabel,Z.Su,P.Devanbu,Onthenaturalness [27] X.Zhou,D.Han,D.Lo,Assessinggeneralizabilityofcodebert,in: ofsoftware,CommunicationsoftheACM59(5)(2016)122–131. 2021IEEEInternationalConferenceonSoftwareMaintenanceand [48] S.Nguyen,T.Nguyen,Y.Li,S.Wang,Combiningprogramanalysis Evolution(ICSME),IEEE,2021,pp.425–436. andstatisticallanguagemodelforcodestatementcompletion,in:2019 [28] T. Mikolov, K. Chen, G. Corrado, J. Dean, Efficient estimation of 34th IEEE/ACM International Conference on Automated Software wordrepresentationsinvectorspace,in:Y.Bengio,Y.LeCun(Eds.), Engineering(ASE),IEEE,2019,pp.710–721. 1st International Conference on Learning Representations, ICLR [49] C.T.Manh,K.T.Trung,T.M.Nguyen,T.-T.Nguyen,S.Nguyen, 2013, Scottsdale, Arizona, USA, May 2-4, 2013, Workshop Track H.D.Vo,Apiparameterrecommendationbasedonlanguagemodel Proceedings,2013. andprogramanalysis,in:202128thAsia-PacificSoftwareEngineer- [29] Z.Feng,D.Guo,D.Tang,N.Duan,X.Feng,M.Gong,L.Shou, ingConference(APSEC),IEEE,2021,pp.492–496. B.Qin,T.Liu,D.Jiang,M.Zhou,CodeBERT:Apre-trainedmodel [50] S.Nguyen,C.T.Manh,K.T.Tran,T.M.Nguyen,T.-T.Nguyen,K.- forprogrammingandnaturallanguages,in:FindingsoftheAssoci- T.Ngo,H.D.Vo,Arist:Aneffectiveapiargumentrecommendation ationforComputationalLinguistics:EMNLP2020,Associationfor approach,JournalofSystemsandSoftware(2023)111786. ComputationalLinguistics,Online,2020,pp.1536–1547. [51] T.Gvero,V.Kuncak,Synthesizingjavaexpressionsfromfree-form [30] S. Elder, N. Zahan, R. Shu, M. Metro, V. Kozarev, T. Menzies, queries,in:Proceedingsofthe2015ACMSIGPLANInternational L.Williams,Doireallyneedallthisworktofindvulnerabilities?, ConferenceonObject-OrientedProgramming,Systems,Languages, EmpiricalSoftwareEngineering27(6)(2022)1–78. andApplications,2015,pp.416–432. [31] Vulnerability distribution by types, https://www.cvedetails.com/ [52] X.Hu,G.Li,X.Xia,D.Lo,Z.Jin,Deepcodecommentgeneration, vulnerabilities-by-types.php,accessed:2023-04-23. in:2018IEEE/ACM26thInternationalConferenceonProgramCom- [32] V.Okun,A.Delaitre,P.E.Black,etal.,Reportonthestaticanalysis prehension(ICPC),IEEE,2018,pp.200–20010. toolexposition(sate)iv,NISTSpecialPublication500(2013)297. [53] Z.Liu,X.Xia,C.Treude,D.Lo,S.Li,Automaticgenerationofpull [33] M.Abuhamad,T.AbuHmed,A.Mohaisen,D.Nyang,Large-scale requestdescriptions,in:34thIEEE/ACMInternationalConferenceon andlanguage-obliviouscodeauthorshipidentification,in:Proceed- AutomatedSoftwareEngineering,IEEE,2019,pp.176–188. ingsofthe2018ACMSIGSACConferenceonComputerandCom- [54] S.Iyer,I.Konstas,A.Cheung,L.Zettlemoyer,Summarizingsource municationsSecurity,2018,pp.101–114. code using a neural attention model, in: Proceedings of the 54th Vo et al.: PreprintsubmittedtoElsevier Page 11 of 12Can An Old Fashioned Feature Extraction and A Light-weight Model Improve VIT Performance? Annual Meeting of the Association for Computational Linguistics (Volume1:LongPapers),2016,pp.2073–2083. [55] A.Mastropaolo,S.Scalabrino,N.Cooper,D.N.Palacio,D.Poshy- vanyk,R.Oliveto,G.Bavota,Studyingtheusageoftext-to-texttrans-
fertransformertosupportcode-relatedtasks,in:2021IEEE/ACM 43rd International Conference on Software Engineering (ICSE), IEEE,2021,pp.336–347. [56] Y.Wan,Z.Zhao,M.Yang,G.Xu,H.Ying,J.Wu,P.S.Yu,Improving automaticsourcecodesummarizationviadeepreinforcementlearn- ing,in:Proceedingsofthe33rdACM/IEEEInternationalConference onAutomatedSoftwareEngineering,2018,pp.397–407. [57] L.Li,H.Feng,W.Zhuang,N.Meng,B.Ryder,Cclearner:Adeep learning-basedclonedetectionapproach,in:InternationalConference onSoftwareMaintenanceandEvolution,IEEE,2017,pp.249–260. [58] P.Godefroid,H.Peleg,R.Singh,Learn&fuzz:Machinelearningfor inputfuzzing,in:201732ndIEEE/ACMInternationalConferenceon AutomatedSoftwareEngineering(ASE),IEEE,2017,pp.50–59. [59] H.A.Nguyen,H.D.Phan,S.S.Khairunnesa,S.Nguyen,A.Ya- davally, S. Wang, H. Rajan, T. Nguyen, A hybrid approach for inferencebetweenbehavioralexceptionapidocumentationandim- plementations,anditsapplications,in:37thIEEE/ACMInternational ConferenceonAutomatedSoftwareEngineering,2022,pp.1–13. [60] N. Jiang, T. Lutellier, L. Tan, Cure: Code-aware neural machine translationforautomaticprogramrepair,in:2021IEEE/ACM43rd International Conference on Software Engineering (ICSE), IEEE, 2021,pp.1161–1173. [61] Y.Ding,B.Ray,P.Devanbu,V.J.Hellendoorn,Patchingastransla- tion:thedataandthemetaphor,in:202035thIEEE/ACMInterna- tionalConferenceonAutomatedSoftwareEngineering,IEEE,2020, pp.275–286. [62] Y.Li,S.Wang,T.N.Nguyen,S.VanNguyen,Improvingbugde- tectionviacontext-basedcoderepresentationlearningandattention- based neural networks, Proceedings of the ACM on Programming Languages3(OOPSLA)(2019)1–30. [63] N. D. Bui, Y. Yu, L. Jiang, Infercode: Self-supervised learning of coderepresentationsbypredictingsubtrees,in:2021IEEE/ACM43rd International Conference on Software Engineering (ICSE), IEEE, 2021,pp.1186–1197. Vo et al.: PreprintsubmittedtoElsevier Page 12 of 12
2306.17193 Uncovering the Limits of Machine Learning for Automatic Vulnerability Detection NiklasRisse MarcelBöhme MPI-SP,Germany MPI-SP,Germany Abstract thismeanthattheproblemofdetectingsecurityvulnerabil- Recentresultsofmachinelearningforautomaticvulnerability ities in software is solved? Are these models actually able detection(ML4VD)havebeenverypromising.Givenonlythe to detect security vulnerabilities,ordo the reported scores sourcecodeofafunction f,ML4VDtechniquescandecideif provideafalsesenseofsecurity? f containsasecurityflawwithupto70%accuracy.However, EventhoughML4VDtechniquesachievehighscoreson asevidentinourownexperiments,thesametop-performing vulnerabilitydetectionbenchmarkdatasets,therearestillsitu- modelsareunabletodistinguishbetweenfunctionsthatcon- ationsinwhichtheyfailtomeetexpectationswhenpresented tainavulnerabilityandfunctionswherethevulnerabilityis withnewdata.Forexample,itispossibletoapplysmallse- patched.So,howcanweexplainthiscontradictionandhow manticpreservingchangestoaugmentthetestingdatasetofa canweimprovethewayweevaluateML4VDtechniquesto state-of-the-artmodelandthenmeasurewhetherthemodel getabetterpictureoftheiractualcapabilities? changesitspredictions.Ifitdoes,itwouldindicateadepen- Inthispaper,weidentifyoverfittingtounrelatedfeatures denceofthepredictiononunrelatedfeatures.Examplesof andout-of-distributiongeneralizationastwoproblems,which suchtransformationsareidentifierrenaming[18,38,39,41,42], are not captured by the traditional approach of evaluating insertion of unexecuted statements [18,35,39,41] or re- ML4VDtechniques.Asaremedy,weproposeanovelbench- placementofcodeelementswithequivalentelements[2,21]. markingmethodologytohelpresearchersbetterevaluatethe The impact of augmenting testing data using these trans- truecapabilitiesandlimitsofML4VDtechniques. Specifi- formations has been explored for many different software- cally,wepropose(i)toaugmentthetrainingandvalidation related tasks and the results seem to be clear: Learning- dataset according to our cross-validation algorithm,where based models fail to perform well when testing data gets a semanticpreserving transformation is appliedduring the augmented using semantic preserving transformations of augmentationofeitherthetrainingsetorthetestingset,and code[2,5,18,30,35,38,39,41,42]. (ii)toaugmentthetestingsetwithcodesnippetswherethe In our own experiments,we were able to reproduce the vulnerabilitiesarepatched. findingsoftheliteratureandmadeadditionalobservations: UsingsixML4VDtechniquesandtwodatasets,wefind ML4VDtechniquesthatweretrainedontypicaltrainingdata (a)thatstate-of-the-artmodelsseverelyoverfittounrelated forvulnerabilitydetectionarealsounabletodistinguishbe- featuresforpredictingthevulnerabilitiesinthetestingdata, tweenvulnerablefunctionsandtheirpatchedcounterparts.Ifa (b)thattheperformancegainedbydataaugmentationdoesnot patchedfunctionisalsopredictedasvulnerable,thisindicates generalizebeyondthespecificaugmentationsappliedduring thatthepredictioncriticallydependsonfeaturesunrelatedto training,and(c)thatstate-of-the-artML4VDtechniquesare thepresenceofasecurityvulnerability. unabletodistinguishvulnerablefunctionsfromtheirpatches. Ithaspreviouslybeenproposedtoreducethedependence onunrelatedfeaturesbyaugmentingnotjustthetestingdata 1 Introduction butalsothetrainingdata[5,18,35,38,39,41,42].Indeed,this seemstorestorethelostperformancebacktopreviouslevels, Recently several different publications have reported high butdoesitreallyreducethedependenceonunrelatedfeatures, scoresonvulnerabilitydetectionbenchmarksusingmachine orarethemodelsjustoverfittingtodifferentunrelatedfeatures learning(ML)techniques[1,12–15,28].Theresultingmodels ofthedata? seemtooutperformtraditionalprogramanalysismethods,e.g. Inthispaper,weproposeanovelbenchmarkingmethodol- staticanalysis,evenwithoutrequiringanyhard-codedknowl- ogythatcanbeusedtoevaluatethecapabilitiesofML4VD edgeofprogramsemanticsorcomputationalmodels.So,does techniques by using data augmentation. First, we propose 1 4202 nuJ 6 ]RC.sc[ 2v39171.6032:viXraAlgorithm1,inwhichaselectedsemanticpreservingtrans- on a typicaltraining datasetwere unable to distinguishbe- formationisappliedtothetrainingdatasetofamodel,anda tweenthevulnerablefunctionsandtheirpatchedcounterparts differenttransformationisappliedtothetestingdataset.When inVulnPatchPairs.Onaverage,theaccuracyturnedouttobe repeatedforallpossiblepairsoutofasetoftransformations, worsethanrandomguessing.Thetrainedmodelsareunable the resulting scores provide a bettermeasure ofoverfitting togeneralizefromastandardvulnerabilitydetectiondataset totheunrelatedfeaturesthatareintroducedbythesemantic tothemodifiedsetting. preservingtransformationsduringtrainingdataaugmentation. Insummary,thispapercontributestwonovelalgorithmsthat Second,weproposeAlgorithm2,inwhichatrainedmodelis can be used to uncover major problems of ML4VD tech- evaluatedonatestingdatasetthatcontainsbothvulnerable niques that are not detected using the standard evaluation programs andtheirrespective patches. The results provide setup:Overfittingtosemanticpreservingcodechangesand ameasureofthemodel’sabilitytogeneralizetoamodified theinabilitytogeneralizebetweenrelatedvulnerabilitydetec-
vulnerabilitydetectionsetting. tionsettings.Additionally,weprovideanempiricalevaluation InordertovalidateAlgorithm1andAlgorithm2empir- ofsixstate-of-the-artML4VDtechniquesusingtheproposed ically,we selected six state-of-the-art ML4VD techniques. methodology. AllevaluatedML4VDtechniqueshappentobetoken-based ⋆ Wepresentageneralmethodologyconsistingoftwoalgo- large language models (LLMs). As our selection criterion, rithms,thatcanbeusedtoevaluateML4VDtechniques. we defined the top-performing ML4VD techniques on the mostwidelyknownMLvulnerabilitydetectionbenchmark ⋆ We show empirically,that state-of-the-art ML4VD tech- CodeXGLUE[24,25]thatareavailableasopensource.This niquesoverfittotheunrelatedfeaturesintroducedbyse- gave us ranks 1,2,6,10,and 12 of the leaderboard,all of manticpreservingtransformationsduringdataaugmenta- whicharetoken-basedLLMs.Infact,9oftheTop-10solu- tion. tionsontheleaderboardaretoken-basedLLMs.Byapplying ⋆ WeintroduceVulnPatchPairs,anewdatasetthatcontains Algorithm1andAlgorithm2inourempiricalstudyofsix vulnerableCfunctionandthecorrespondingpatchedver- state-of-the-art ML4VD techniques and three datasets,we sionsofthesamefunctions.Itisavailableat confirmedthatML4VDtechniquescontinuetoleverageunre- https://github.com/niklasrisse/VPP. latedfeatureswhendecidingwhetherafunctioncontainsa vulnerability. ⋆ We demonstrate, that six state-of-the-art ML4VD tech- ForAlgorithm1,weimplemented11differentsemanticpre- niquesarenotabletodistinguishbetweenthevulnerable servingtransformationsfordataaugmentationandevaluated andpatchedfunctionsinVulnPatchPairs. thetrainedmodelsusingtwopopularvulnerabilitydetection datasets. As expected,we find a strong benefit of training ⋆ Wepublishallofourcodeandresultsforreproducibility. dataaugmentation(69.0%and66.2%averagerestorationof Theyareavailableat accuracy/f1-scoreforthetwodatasets)whenthetransforma- https://github.com/niklasrisse/USENIX_2024. tions applied to training and testing datasets are the same. However,wefindnoimprovementinperformancewhenthe 2 RelatedWork transformationsappliedtotrainingandtestingdatasetsare different.Infact,weevenfindanadditional30.2%and77.5% One of the main tools to study the limits of ML4VD tech- averagedecreasein accuracy/f1-scoreforthetwodatasets. niquesaresemanticpreservingtransformationsofcode.Pre- Inotherwords,ML4VDtechniquesstillseverelyoverfitto vious work[2,5,18,21,22,30,35,38,39,41,42] proposed the specific label-unrelatedfeatures introducedby training methodstogeneratesemanticpreservingtransformationsfor dataaugmentation.Theimprovementinperformancegained sourcecodedatasetsandinvestigatedtheirimpactwhenused by data augmentation only applies to the specific type of toaugmenttestingdataoflearnedmodels. transformationsusedduringtraining. Many of the works that reported the failures of learned ForAlgorithm2,weintroduceanewdataset,VulnPatch- modelswhentestingdatawasaugmentedalsoinvestigated Pairs,whichcontains26.2kCfunctionsandisderivedfrom training data augmentation using their respective methods theCodeXGLUE/Devignvulnerabilitydetectiondataset[43]. [5,18,35,38,39,41,42].Acommonfindinginallofthesepub- Exactly halfofthe functions in VulnPatchPairs contain se- licationsisthattrainingdataaugmentationusingaspecific curityvulnerabilities.Theotherhalfarepatchedversionsof typeofsemanticpreservingtransformationleadstoimproved thefirsthalf.1WeinvestigatedsixML4VDtechniquesusing performance on testing sets that have been augmented the VulnPatchPairsandevaluatedtheirabilitytogeneralizefrom sameway.Butdoestheperformancegainedbydataaugmen- theirtypicaltrainingdatatoVulnPatchPairs,andviceversa. tationgeneralizebeyondthespecificaugmentationsapplied Tooursurprise,allsixML4VDtechniquesthatweretrained duringtraining? Some of the publications that propose methods for data 1SeeSection4.4fordetails. augmentation [5,18,35,38,41] take it a step further; they 21 static inline int coeff_unpack_golomb(GetBitContext *gb, int qfactor, int 1 static inline int coeff_unpack_golomb(GetBitContext *gb, int qfactor, int qoffset) qoffset) 2 { 2 { 3 int coeff = dirac_get_se_golomb(gb); 3 int coeff = dirac_get_se_golomb(gb); 4 const int sign = FFSIGN(coeff); 4 const int sign = FFSIGN(coeff); 5 const unsigned sign = FFSIGN(coeff); 5 const unsigned sign = FFSIGN(coeff); 6 if (coeff) 6 if (coeff) 7 coeff = sign*((sign * coeff * qfactor + qoffset) >> 2); 7 coeff = sign*((sign * coeff * qfactor + qoffset) >> 2); 8 if (0) 8 return coeff; 9 coeff = 666; 9 } 10 return coeff; 11 } (a)CodeSnippet (b)TransformedCodeSnippet Figure1:Exampleofasimplesemanticpreservingtransformation.Thechange(orange)hasnoeffectonthevulnerabilitylabel. Bothcodesnippetscontainasecurityvulnerability(integeroverflowinline4).ThecodewastakenfromtheFfmpegGitHub repository(URL:https://github.com/FFmpeg/FFmpeg/commit/92da2309)andispartoftheCodeXGLUE/Devigndataset. augmentthetrainingdatausingaslightlydifferentbutrelated ofourknowledge,wearethefirsttoutilizesuchadatasetto
typeoftransformationthanforthetestingdata.Forexample, evaluatethegeneralcapabilitiesofML4VDtechniques. Henkel et al. [18] apply their gradient-based approach for Tworecentlypublishedpapers[10,36]reportpoorgener- identifierrenamingtothetrainingdataandarandomrenam- alizationcapabilitiesofdifferentML-basedtechniques(e.g. ing strategy to the testing data. Similarly,Yang et al. [38] LLMsandGNNs)whenevaluatedonfunctionsfromunseen applytheirmethodforvariablerenamingtoatrainingdataset gitprojects.OurAlgorithm2alsoinvestigatesthegeneraliza- and the method proposed by Zhang et al. [42] to a testing tioncapabilitiesofML4VDtechniques,butusingadifferent dataset. All of these works find an improved performance setup,inwhichfunctionsintheevaluationdatabelongtoa whenthetrainingdatasetisaugmentedinasimilarwaythan modifiedvulnerabilitydetectionsetting(e.g.vulnerablefunc- the testing dataset. However, the transformations used for tionsandtheirpatches),butcanbefromthesameprojects. augmentingthetrainingandtestingdatainthesepublications areallsimilarintype,e.g.theybothrenameidentifiers.But 3 Methodology doestheperformancealsoimprovewhentrainingdataisaug- mented in a different way than the testing data? Ourwork Weproposeanovelbenchmarkingmethodologytohelpre- aimstofillthisgapintheliteraturebycarryingoutathorough searchers better evaluate advances in ML4VD techniques. empirical study that considers a diverse set of 11 different Themethodologyconsistsoftwoparts,Algorithm1(A1)and transformations,sixstate-of-the-artML4VDtechniques,and Algorithm2(A2). twohigh-qualitydatasets. Similartootherrelatedpublicationslistedabove[18,35, 3.1 DataAugmentation 38],Rahman et al. [31] investigate overfitting of ML4VD techniquestovariableandAPInamesbytransformingthem Acentralcomponentofourmethodologyisdataaugmenta- inthetestingdata.Additionally,theyproposeanewmethod tion,andtheexpectationsforvulnerabilitydetectionmodels toaddresstheoverfittingbasedoncausallearning,whichaims that emerge from using code transformations fordata aug- todisablemodelsfromusingsuperficialfeatures(e.g.variable mentation. names)entirely.Whiletheirapproachseemstobeeffective We define data augmentation as the application of one toavoidoverfittingforconcreteandsimpletransformations or multiple code transformations onto all code snippets of (e.g.changingvariablenames),theauthorsdonotinvestigate a given code snippet datasetCD C, where C is a space howtheirmethodperformswhenfacedwithunseensemantic that represents all possible code s⊂ nippets c C in a given preservingtransformations,thatwerenotspecificallytrained ∈ programminglanguage. for.Ourproposedmethodologycanbeusedasatooltodo Acodetransformationt :C C isafunctionthatmaps this,whichallowstodrawconclusionsaboutoverfittingto fromandtoC.Let’sassumew→ ehaveanoraclefunctiong: unrelatedfeaturesfundamentally,irrespectiveofthetypeof C 0,1 ,whichmapsfromthespaceofcodesnippetsC to transformationappliedtotraining-andtestingdata. eit→ her{ 0or} 1.Theoraclefunctiongrepresentsthegroundtruth, In order to evaluate the general capabilities of ML4VD i.e. itshows whethera code snippetc does (1) ordoes not techniques, we collected a new dataset (VulnPatchPairs), (0)containasecurityvulnerability.Foragivencodesnippet which contains both vulnerable functions and their respec- datasetCD C,acodetransformationt canbecharacterized ⊂ tivepatches.Thecollectionofapairwisevulnerability-patch byitseffectong(t(c)) c CD: ∀ ∈ datasethasbeenproposedbypreviouswork[4,8,29],e.g.for Semantic Preserving Transformation. We calla trans- theresearchfieldofautomatedfixing.However,tothebest formation t semantic preserving w.r.t. CD,if the changes p 3Algorithm1DetectingOverfittingtoCodeChanges Training Data Testing Data Input: TraS ie nm ina gn Dtic atP asre es te Trv ringTransformationsT:= {t1,...,tN} High LLM TRAIN EVAL TestingDatasetTe Accuracy MLTrainingMethodtrain_model MLEvaluationMethodevaluate_model Augmented PerformanceMetricM Training Data Testing Data 1: MLM[Tr]=train_model(Tr) 2: score[MLM[Tr],Te]=evaluate_model(MLM[Tr],Te,M) Low 3 4: : for Tea ec kh =tk tk∈(TT e)do //testingdataaugmentation LLM TRAIN EVAL Accuracy 5: score[MLM[Tr],Tek]=evaluate_model(MLM[Tr],Tek,M) 76 :: Tef rkfe =ct t[ kT (Tr, rT )ek]=s //co trr ae i[ nM inL gM d[ aT tar], aT ue gk m] e−ns tac to ir oe n[MLM[Tr],Te] TA rau ig nm ine gn Dte ad ta TA eu stg im nge n Dt ae td a 1 1 198 0 1 2:: : : : M fs M oc roL Lr TM M ee a e[[ [M c jT T h =r rLk k tM] , tj ̸=T j= ([ keT Tk ∈t r er ]k )a = T]i ,n T ds_ e c /om /k o] tro e= ed s[e tM iel n( v L gT a Mr l duk a[) a T tt are k_ a]m , uT go e md ke e]l n−( tM as tcL io oM r ne[ [T Mrk L], MT [e Tk r, ]M ,T) e] LLM AT uR gA mIN ented E AV uA gL mented AcH cuig rh acy 13: score[MLM[Trk],Tej]=evaluate_model(MLM[Trk],Tej,M) Training Data Testing Data 1 14 5: : ende ff of rect[Trk,Tej]=score[MLM[Trk],Tej] −score[MLM[Tr],Te] ?
16: endfor LLM TRAIN EVAL Output: outputA1.1=(∑keffect[Tr,Tek])/N outputA1.2=(∑keffect[Trk,Tek])/N outputA1.3=(∑k∑j ̸=keffect[Trk,Tej])/(N(N −1)) Figure2:VisualizationofAlgorithm1,whichwecreatedto detectoverfittingofML4VDtechniquestounrelatedfeatures introducedbydataaugmentation.Colorsrepresentthateither introducedbyapplyingitdonotaffectthegroundtruthvul- onlytestingdataisaugmented(blue),training-andtesting nerability label,g(c)=g(t (c)) c CD. Figure 1 shows p ∀ ∈ dataareaugmentedusingthesame(orange),ordifferentaug- anexampleofasimplesemanticpreservingtransformation mentationmethods(green). appliedtoareal-worldcodesnippet. LabelInvertingTransformation.Wecallatransforma- tion t label inverting w.r.t. CD,if the changes introduced d ThegoalofAlgorithm1istomeasure,whetherML4VD by applying it change the ground truth vulnerability label, techniquesoverfittoaugmentationsoftheirtrainingdatathat g(c)=g(t (c)) c CD. In otherwords,alabelinverting d areunrelatedtotherespectivevulnerabilitylabelsandwhether ̸ ∀ ∈ transformationeitheraddsorremovesavulnerabilityfroma the performance gained by data augmentation generalizes codesnippet. beyond the specific augmentations applied during training. In general,we expecta vulnerability detection modelto We provide a simple visualization of the idea behind the correctly predict,whether a given code snippet contains a algorithm in Figure 2,the algorithm itself in Algorithm 1, securityvulnerability,independentofanysemanticpreserving andadescriptionofthemostimportantpartsinthefollowing orlabelinvertingtransformationsthathavebeenpreviously paragraphs. We use the colors blue, orange, and green, to appliedtothecodesnippet. Specifically,wecanformulate connectthebasicideasofthealgorithmwiththeexperimental thefollowingexpectations: resultsacrossthepaper2. What are the inputs? The inputs of Algorithm 1 are a 1. Ifwechangeacodesnippetwithoutaffectingthevulner- set of different semantic preserving transformations T := abilitylabel(semanticpreservingtransformation),we t ,...,t ,atrainingdatasetTr,atestingdatasetTe,aML expectavulnerabilitydetectiontooltocomputethesame {1 N } trainingmethodtrain_model,aMLevaluationmethodeval- correctpredictionasbeforeapplyingthechange. uate_model,andaperformancemetricM.Thetrainingand testingdatasetsTrandTeconsistofcode-labelpairs(c,v), 2. Ifweaddorremoveavulnerabilityfromacodesnippet i i withc C representingcodesnippetsandv 0,1 repre- (labelinvertingtransformation),weexpectavulnerabil- i ∈ i ∈{ } sentinglabelsthatindicatetheabsence(0)orpresence(1)of itydetectiontooltostilldeliveracorrectprediction,or securityvulnerabilitiesintherespectivecodesnippets.The i.e.weexpectittochangeitspredictionwiththeground methodtrain_modelcanutilizethetrainingdatasetTrtotrain truthlabelofthecodesnippet. amachinelearningmodelMLM:C 0,1 ,whichmaps →{ } Inthefollowingsections,wepresenttwoalgorithms,whichal- fromthespaceofcodesnippetsC toeither1(vulnerability) lowtoevaluateML4VDtechniquesusingthetwoformulated or0(novulnerability).Themethodevaluate_modelcanuse expectations. theperformancemetricMtoquantifyandaggregatetheper- formanceofatrainedmodelMLMonatestingdatasetTeinto asinglenumberbetween0(bad)and1(perfect). 3.2 A1:DetectingOverfittingtoCodeChanges 2SeeFigure2,Algorithm1,Figure5,Figure7,Figure7candTable2. 4Standard Training Vulnerability-Patch Algorithm2DistinguishbetweenVulnerabilityandPatch Dataset Pairs Input: StandardTrainingDatasetTr ? StandardTestingDatasetTe LLM TRAIN EVAL Vulnerability-PatchTrainingDatasetVPTr Vulnerability-PatchTestingDatasetVPTe MLTrainingMethodtrain_model MLEvaluationMethodevaluate_model Vulnerability-Patch Standard Testing Pairs Dataset PerformanceMetricM 1: MLM[Tr]=train_model(Tr) ? 2: MLM[VPTr]=train_model(VPTr) LLM TRAIN EVAL 3: score[MLM[Tr],Te]=evaluate_model(MLM[Tr],Te,M) 4: score[MLM[Tr],VPTe]=evaluate_model(MLM[Tr],VPTe,M) 5: score[MLM[VPTr],VPTe]=evaluate_model(MLM[VPTr],VPTe,M) 6: score[MLM[VPTr],Te]=evaluate_model(MLM[VPTr],Te,M) Figure 3: Visualization of Algorithm 2, which we created Output: outputA2.1=score[MLM[Tr],Te] to test whether ML4VD techniques are able to generalize outputA2.2=score[MLM[Tr],VPTe] outputA2.3=score[MLM[VPTr],VPTe] toamodifiedsetting,whichrequirestodistinguishbetween outputA2.4=score[MLM[VPTr],Te] vulnerabilitiesandpatches. thefollowingquestions: Whatis computed? Algorithm 1 computes the average effectsof(a)augmentingthetestingdataoftheselectedML 1. How much does the performance of the selected ML techniqueusingtransformationst T (output ),(b)using technique decrease if we augment the code snippets k A1.1 thesametransformationstoalso∈ augmentthetrainingdata for testing without affecting the vulnerability labels? (output ),and(c)usingdifferenttransformationstoalso Answer:Onaverage,theperformancedoeschangeby A1.2
augmentthetrainingdata(output A1.3). output A1.1points. Inlines4-6,Algorithm1computestheeffectofaugment- 2. HowmuchperformanceoftheselectedMLtechnique ing the testing datasetTe withthe transformationt on the k canberestored,ifweaugmentthetrainingcodesnippets performance of the trained model MLM[Tr]. The result is in a similar way than the testing code snippets? An- effect[Tr,Te ],theabsolutedifferencebetweenthescoresof k swer:Onaverage,output output oftheinitial MLM[Tr]onthecleantestingdatasetTeandtheaugmented A1.2 − A1.1 decreasecanberestored. testingdatasetTe .Inotherwords,effect[Tr,Te ]quantifies k k how many points in score are lost if we augment the test- 3. HowmuchperformanceoftheselectedMLtechnique ingdatasetwithtransformationt .output aggregatesthis k A1.1 canberestored,ifweaugmentthetrainingcodesnippets intermediateresultoveralltransformationst T. k in a differentway than the testing code snippets? An- ∈ In lines 7-10,Algorithm 1 goes a step further and com- swer:Onaverage,output output oftheinitial A1.3 A1.1 putestheeffectofbothaugmentingthetrainingdatasetTr decreasecanberestored. − and the testing dataset Te using the same transformation t k.Theresultiseffect[Tr k,Te k],theabsolutedifferencebe- 4. DoestheselectedMLtechniqueoverfittospecificaug- tweenscoresofMLM[Tr k]ontheaugmentedtestingdataset mentationsofthetrainingdatathatareunrelatedtothere- Te k andMLM[Tr]onthetestingdatasetTe.Inotherwords, spectivevulnerabilitylabels?Answer:Ifoutput A1.2>> effect[Tr k,Te k]quantifieshowmanypointsinscorearelost output A1.3:Yes,otherwiseNo. ifweaugmentboththetrainingandthetestingdatasetwith transformationt .output aggregatesthisintermediatere- k A1.2 sultoveralltransformationst T. k 3.3 A2:DistinguishbetweenVulnerabilityand ∈ Inlines12-14,thealgorithmcomputestheeffectofaug- Patch mentingthetestingdatasetusingadifferenttransformation t j thanforthetrainingdataset.Theresultiseffect[Tr k,Te j], ThemaingoalofAlgorithm2istoevaluate,whetherML4VD theabsolutedifferencebetweenscoresofMLM[Tr]onthe techniquesareabletogeneralizefromtheirtypicaltraining testingdatasetTeandMLM[Tr k]ontheaugmentedtesting datatoamodifiedsetting,whichrequirestodistinguishse- Te j. In other words,effect[Tr k,Te j] quantifies how many curity vulnerabilities from their patches. Additionally, the pointsinscorearelostifweaugmentthetrainingandthetest- algorithmalsoaimstoevaluatethereverse,ori.e. whether ingdatasetwithdifferenttransformationst kandt j.output A1.3 ML4VDtechniquesthatweretrainedtodistinguishbetween aggregatesthisintermediateresultoveralltransformations vulnerabilitiesandtheirpatchesareabletoperformwellon t k T,t j=k T. standardtestingdata.Weprovideasimplevisualizationof ∈ ̸ ∈ Howcan the results be used? Using this algorithm,re- theideabehindthealgorithminFigure3,thealgorithmitself searcherscaneffectivelyevaluatenewML4VDtechniques. inAlgorithm2,andadescriptionofthemostimportantparts Specifically,foraselectedtechniqueresearcherscananswer in the following paragraphs. We use the colors purple and 5yellowtoconnectthebasicideasofthealgorithmwiththe How can the results be used? Using Algorithm 2, re- experimentalresultsacrossthepaper3. searchers can effectively evaluate whether the high scores Whataretheinputs?InadditiontotheinputsofAlgo- of ML4VD techniques are specific to the testing datasets rithm1,Algorithm2requiresaspecialvulnerability-patch on which they were computed. Specifically,for a selected testingdatasetVPTeandavulnerability-patchtrainingdataset techniqueresearcherscananswerthefollowingquestions: VPTr.VPTeandVPTralsoconsistofcodesnippetsc C i ∈ andvulnerabilitylabelsv i 0,1 ,butforeverycodesnip- 1. DoestheperformanceoftheselectedMLtechniquegen- ∈{ } pet c j with label v j = 0, they also contain a snippet c l=j eralizefromastandardvulnerabilitydetectiondatasetto withv l =1whichrepresentsthepatchedversionofc j.Th̸ e amodifiedsetting,whichrequirestodistinguishvulner- relationship between a code snippet and its patched ver- abilitiesfromtheirpatches?Answer:TheselectedML sioncanbecharacterizedasalabelinvertingtransformation technique can distinguishbetween vulnerabilities and t PATCH:C C,whichmapscodesnippetsc jtotheirpatched theirpatcheswithperformanceoutput A2.2,comparedto → versionsc. ascoreofoutput onthestandardtestingdataset. l A2.1 What is computed? The purpose of Algorithm 2 is to quantifytheabilityoftheselectedMLtechniquetogeneral- 2. Does the performance of the selected ML technique izebetweentworelatedvulnerabilitydetectionsettings.The generalizebacktothestandardvulnerabilitydetection firstsetting,representedbythestandardtrainingandtesting settingwhenitisexplicitlytrainedtodistinguishvulner- datasets Tr andTe,consists ofcode snippets,whicheither abilitiesfromtheirpatches?Answer:TheselectedML containordonotcontainavulnerability.Thissettingismost techniqueachievesascoreofoutput onthestandard A2.4 frequentlyusedin the relatedliterature [1,12–15,28]. The testingdataset,comparedtoascoreofoutput inthe A2.3 secondsetting,representedbythevulnerability-patchtraining modifiedsetting. andtestingdatasetsVPTrandVPTe,consistsofvulnerable
codesnippetsandtheirrespectivepatches.Asformulatedin Section3.1,aperfectvulnerabilitydetectionmodelshould 4 ExperimentalSetup beabletoperformwellinbothsettings,irrespectiveofthe settingonwhichitwastrained.Inotherwords,avulnerability 4.1 ResearchQuestions detection model should be able to generalize between the settings. Ourobjectiveistovalidateempirically,whetherthetwopro- Intotal,Algorithm2computesfourscores.Inline3,Al- posed algorithms can be used to evaluate state-of-the-art gorithm2computesthescoreofamodelMLM[Tr],which ML4VDtechniques.Specifically,weaimtoanswerthefol- wastrainedonthestandardtrainingdatasetTr,onthestan- lowingresearchquestions. dard testing dataset Te. This score represents the standard RQ.1HowistheperformanceofML4VDtechniquesaf- evaluationandservesasabaselinefortheotherscores. fected,ifweaugmenttheinputcodesnippetswithout In line 4, Algorithm 2 computes the score of a model affectingthevulnerabilitylabels?(a)Canwemeasure MLM[Tr],whichwastrainedonthestandardtrainingdataset a decrease in performance,if we augment the testing Tr,on the vulnerability-patch testing datasetVPTe. When dataofML4VDtechniquesusingsemanticpreserving comparedtothefirstscore,thisresultservesasameasureof transformations? (b) Does training data augmentation MLM[Tr]sabilitytogeneralizetothemodifiedsetting,which usingthesametransformationsrestoretheinitialperfor- requirestodistinguishvulnerabilitiesfromtheirpatches. mance?(c)Aretheredifferencesbetweentheindividual In line 5, Algorithm 2 computes the score of a model transformations? MLM[VPTr],whichwastrainedonthevulnerability-patch RQ.2DoML4VDtechniquesoverfittospecificaugmen- training dataset VPTr, on the vulnerability-patch testing tations oftheirtraining data thatdo notaffectthe datasetVPTe.Again,thisscoreservesasabaselineforthe respectivevulnerabilitylabels?Canwestillrestorethe otherscores. performance,ifweaugmentthetrainingdatasetwitha In line 6, Algorithm 2 computes the score of a model different semantic preserving transformation than the MLM[VPTr],whichwastrainedonthevulnerability-patch testingdataset? training dataset VPTr, on the standard testing dataset Te. RQ.3ArethehighscoresofML4VDtechniquesspecificto When compared to the third score, this result serves as a benchmarkdatasetsordotheygeneralizetoamodi- measure of MLM[VPTr]s ability to generalize back to the fiedvulnerabilitydetectionsetting?(a)Arestate-of- standardvulnerabilitydetectionsetting. the-artML4VDtechniquesabletodistinguishbetween Thefourcomputedscoresarereturnedastheoutputsofthe vulnerablefunctionsandtheirpatches?(b)Doestraining algorithm(output ,output ,output andoutput ). to distinguish between vulnerable functions and their A2.1 A2.2 A2.3 A2.4 patches improve the performance on standard testing 3SeeFigure3,Algorithm2,andTable3. data? 6Table 1: The semantic preserving transformations that we theCodeXGLUE/DevigndatasetorjustastheCodeXGLUE usedinourexperiments. dataset.TheCodeXGLUEdatasetcontains26.4kCfunctions, fromwhich45.6%containvulnerabilities,i.e.thedatasetis Identifier Type Description fairlybalanced.Thetypesofvulnerabilitieswerenotformally t1 IdentifierRenaming Renameallfunctionparameterstoaran- classified, but based on the collection process the authors domtoken. foundmostvulnerabilitiesinthedatasettobememory-related, t2 StatementReordering Reorderallfunctionparameters. t3 IdentifierRenaming Renamethefunction. e.g.memoryleaks,bufferoverflows,memorycorruption,or t4 StatementInsertion Insertunexecutedcode. crashes. The authors of the CodeXGLUE benchmark also t5 StatementInsertion Insertcomment. t6 StatementReordering Movethecodeofthefunctionintoasep- maintainaleaderboard[25],whichtrackstheperformanceof aratefunction. popularlearning-basedtechniquesonthedifferentdatasetsof t7 StatementInsertion Insertwhitespace. t8 StatementInsertion Defineadditionalvoidfunctionandcall thebenchmark. itfromthefunction. VulDeePecker.Theothervulnerabilitydetectiondataset t9 StatementRemoval Removeallcomments. t10 StatementInsertion Addcodefromtrainingsetascomment. thatweuseinthispaperistheCodeGadgetDatabase,which t11 RandomTransformation One transformation sampled from wasintroducedwiththeVulDeePeckerbugdetector[23].We {t1,...,t10}isappliedtoeachfunction. refertothisdatasetastheVulDeePeckerdataset.Theoriginal datasetcontains61.6kC/C++codesamplesderivedfromthe 4.2 SemanticPreservingTransformations NVD[7]andtheSARD[6],fromwhich17.7kcontainvulner- abilities,mainlybuffer(CWE-119)andresourcemanagement Oneofthecentralcomponentsofalgorithms1and2arese- errors(CWE-399). manticpreservingtransformationsofcode.Themostcommon semanticpreservingtransformationsthatareusedinthelitera- 4.4 NewDataset:VulnPatchPairs turetoinvestigatethelimitsoflearnedmodelsforsourcecode relatedtasksareidentifierrenaming[18,35,38,39,41,42],in- InordertoinvestigatetheabilityofML4VDtechniquesto sertionofunexecutedstatements[18,35,39,41],replacement distinguishbetweenvulnerabilitiesandtheirpatches(RQ3), ofstatementswithequivalentstatements[21],reorderingof wecollectedanewdataset,whichwecallVulnPatchPairs.We unrelatedstatements[27],deletionofunexecutedstatements provideasimplevisualizationofthecollectionprocessfor
(e.g. comments) [21], or combinations of the before men- VulnPatchPairsinFigure4. tioned[18,35,41]. VulnPatchPairsisanextensionoftheCodeXGLUE/Devign Table1showsthe11semanticpreservingtransformations vulnerabilitydetectiondataset[43],whichconsistsofCfunc- thatweimplementedfortheexperimentspresentedinthispa- tionsfromtwopopularopensourcerepositories,FFmpeg4 per.Wetriedtocoveralltypesoftransformationscommonly andQemu5.Thecreatorsofthedatasetdescribethecollec- usedintheliterature.Thetablelistsalltransformations,cate- tionprocessintheiroriginalpublication[43].Asafirststep, gorizesthembytype,andprovidesshortdescriptionsforeach theyfilteredtheselectedrepositoriesforsecurity-relatedcom- ofthem. mitsusingalistofkeywords.Then,theyinvested600work SinceML4VDtechniquesareultimatelyaimedatdetecting hoursofafour-personteamofsecurityresearcherstoclassify securityvulnerabilitiesinreal-worldcode,augmentingcode thesecurity-relatedcommitsintovulnerability-fixcommits using oursemantic preserving transformations shouldalso (VFCs)andnonvulnerability-fixcommits(non-VFCs)and resultincodethatlooksnatural,ori.e.lookslikeitcouldoccur extractedtherespectivefunctionsbeforethecommitswere in real-world software. To address this,we experimentally appliedasvulnerable(beforeVFCs)andnon-vulnerable(be- confirmedthatoursemanticpreservingtransformationsdonot forenonVFCs)functions.Theactualpatchedversionsofthe decreasethenaturalness(measuredbycrossentropy)ofthe functions(aftertheVFCswereapplied)arenotpartoftheir code.Weprovidemoreinformationonthisassupplementary originaldataset.However,foreachfunctionoftheirdataset, materialinAppendixA. theauthorsreleasedtherespectivecommitIDfromthetwo open-sourcerepositoriesasadditionalinformation.Weused thisinformationtoextracttheactualpatchedversionsofthe 4.3 VulnerabilityDetectionDatasets vulnerable functions in the CodeXGLUE dataset from the FFmpeg andQemu repositories andcreateda new dataset: Weusetwopubliclyavailablevulnerabilitydetectiondatasets VulnPatchPairs. forourexperiments. Wemanuallyverified100randomlychosenfunctionsfrom CodeXGLUE/Devign.CodeXGLUEisamachinelearn- theCodeXGLUEdatasetthatwerelabelledasvulnerable.We ingbenchmarkforcodeunderstandingandgeneration[24]. found68outofthese100functionstoactuallycontainasecu- It consists of several datasets for different source code re- rityvulnerability,23tocontainnosecurityvulnerability,and9 lated tasks. In our experiments, we only use the dataset for vulnerability detection, which is based on the Devign 4FFmpegrepository:https://github.com/FFmpeg/FFmpeg dataset[43].Throughoutthispaper,werefertothisdatasetas 5Qemurepository:https://github.com/qemu/qemu 7selectedGraphCodeBERT(abbreviatedasGraphCBinTa- GitHub ble3)[14],atechniquerelatedtoCodeBERT,whichutilizes Remove non Collect graphrepresentationsofsourcecodeduringthetrainingpro- vulnerable functions developer patches cess. Standard Vulnerabilities Vulnerabilities + New Dataset ModelDetails.Sincetheselectedtechniquesbelongtothe Testing Dataset Patches VulnPatchPairs same family of techniques,they also share the same basic architecture: Figure4:Visualizationofthecollectionprocessforournew datasetVulnPatchPairs. 1. Tokenization:Agivencodefunctionissplitintotokens (smallsequenceofcharactersthatformsasemanticen- tity),basedonagivenstrategy. withnodecisionafter10minutesofmanualeffort.Theresults areavailableathttps://github.com/niklasrisse/VPP_ 2. Embedding:Tokensaretransformedintonumbers,usu- label_accuracy.Eventhoughtheseresultsshowthatthere allybyindexingviaalearnedvocabularyandtheaddi- areinaccuratelabelsintheCodeXGLUEdataset,wedonot tionofpositionalinformation. expectanychangestoourmainfindings.Whiletheabsolute performancemightchangeifweusedperfectlylabeleddata, 3. Transformer Network: Several steps of parametrized weexpecttherelativeperformance(e.g.,augmentedvsnon- computationareapplied,resultinginafinalembedding. augmented) to remain comparable forallofourindividual evaluations. 4. Prediction Layer: The final layer of the model is a Intotal,VulnPatchPairsconsistsof26.2kCfunctionsfrom parametrizedpredictionlayer,whichcomputesanoutput thetwoopensourcerepositoriesFFmpegandQemu.Exactly numberbetween0and1basedonthefinalembedding half(13.1k)ofthe26.2kfunctionscontainsecurityvulnerabil- ofthepreviousstep.Theoutputnumberrepresentsthe itiesandwerecopiedfromtheCodeXGLUE/Devignvulner- predictedprobabilitythattheinputfunctioncontainsa abilitydetectiondataset.Theother13.1karetherespective securityvulnerability. patchesofthevulnerablefunctions,whichweextractedfrom theopen-sourcerepositories.WepublishedVulnPatchPairs Duringmodeltraining,theparametrizedcomputationallay- assupplementarymaterialinanopenGitHubrepository6. ers ofsteps 3. and4. are optimizedtocompute the correct predictions for given training data. The six selected tech- niques mainly differin tokenization strategy,training data, 4.5 MachineLearningTechniques optimizationobjective,andthespecifictransformernetwork architectureused.Weprovideadditionalinformationonthe Weselectedsixstate-of-the-artML4VDtechniquesforour specificmodelsinAppendixC. experiments.
SelectionCriteria.Inordertoselecttechniquesthatrepre- Theauthorsofallsixtechniquesprovidepubliclyavailable implementationsoftheirtechniques[1,12–15,28]. sentthestate-of-the-artofmachinelearningforvulnerability detection,wechosethetoptechniquesfromtheCodeXGLUE leaderboard[25]forwhichtheauthorsprovideopen-source 4.6 ModelTrainingPipeline implementations.Measuredbycitations7(496)andGitHub Stars8 (1.2k),CodeXGLUEisthemostwell-knownbench- Weusedasimilartrainingsetupforallmodelinstancesthat mark forsource code related machine learning techniques. wetrainedforourexperiments. Thevulnerabilitydetectiondatasetofthebenchmark[43]is Pre-training.Allmodelsthatwetraininourexperiments alsohighlycited(407citations9)andwidelyusedtoevaluate havebeenpre-trainedbytheauthorsoftherespectivepubli- ML4VDtechniquesforautomaticvulnerabilitydetection. cationsusingvarioussourcecodedatasets. Thesizeofthe Selected Techniques. Based on the described criteria, pre-trainingdatasetsspansfrom2.3million(VulBERTa)to weselectedUniXcoder[13],CoTexT[28],VulBERTa[15], 680 million code snippets (PLBart). The original publica- PLBart [1], and CodeBERT [12] for our experiments. At tionsprovidemoreinformationonthepre-trainingdatasets submissiontimeofthispaper,thesixtechniquesholdrank [1,13,15,28].Weusethepre-trainedmodelsreleasedbythe 1(UniXcoder),rank2(CoTexT),rank6(VulBERTa),rank authorsoftherespectivetechniquesasstartingpointsforour 10(PLBart),andrank12(CodeBERT)ontheCodeXGLUE pipelineandfinetunethemodelsonourselecteddatasets. leaderboard forvulnerability detection [25]. In addition to Datasplit.FortheCodeXGLUE/Devigndataset,weused thefivetechniquesfromtheCodeXGLUEleaderboard,we thetrain-/validation-/testingdatasetsplitprovidedbytheau- thors of the benchmark [24], which resulted in a training 6VulnPatchPairs:https://github.com/niklasrisse/VPP dataset with 21k functions, a validation dataset with 2.7k 7https://api.semanticscholar.org/CorpusID:231855531 8https://github.com/microsoft/CodeXGLUE functions,andatestingdatasetwith2.7kfunctions.Forthe 9https://api.semanticscholar.org/CorpusID:202539112 VulDeePeckerdataset,weusedthesplitprovidedbyHanifet 8al.[15],whichresultedinatrainingdatasetwith128.1kfunc- dataaugmentationusingthesametransformationsrestoresthe tions,avalidationdatasetwith16kfunctions,andatesting performancetowardspreviouslevels,andwhether(c)there datasetwith16kfunctions. The splitforVulnPatchPairs is aredifferencesbetweentheindividualtransformations. derivedfromthesplitofCodeXGLUE,suchthatallandonly Methodology.WeusedAlgorithm1toinvestigateallthree vulnerablefunctionsintraining,validation,andtestingsets, questions.WeranthealgorithmforeachMLtechniqueand respectively,ofCodeXGLUEweretakenastraining,valida- datasetseparatelyandmeasuredtheoutcomesusingthere- tion,andtestingsetsofVulnPatchPairs,augmentedbytheir spectivepreferredperformancemetrics(seeSection4.6).We correspondingpatches. did not only record the outcomes aftercompleting the full Pre-processing. For the VulDeePecker dataset, we re- training of the respective models but also after each train- moved all duplicate functions and also replaced all label- ingepochinordertoobservetheprogressionofthelearning revealingtokens(e.g.commentwithtoken"bad"aboveavul- process. nerablefunction)thatwefoundbymanualinspectionofthe Results.Figure5ashowsthetestsetaccuracyofdifferent datasetwithrandomlyselectedtokens.FortheCodeXGLUE VulBERTa models measured after each of the ten training and VulnPatchPairs datasets,we applied no additional pre- epochs.Wecanobserve,thataugmentingthetestingdataset processingsteps. Tewithtransformationt leadstoasubstantialdropinaccu- 10 Hyperparameters. For all six ML4VD techniques, we racy,representedbythegapbetweenthedottedgrayandblue usedthepre-trainedmodelsandtokenizersprovidedbythere- graphsinthefigure.Wecanalsoobserve,thataugmenting spectiveauthorsasstartingpointsforourexperiments.Similar thetrainingdatasetTrwiththesametransformationt asthe 10 toHanifetal.[15],wenoticedarelativelyquickconvergence testingdataset,restorestheaccuracybacktopreviouslevels ofourperformancemetricsinourinitialexperimentsonthe (orangegraph). validationdataset(after2-7epochs),whichiswhywetrained Figure 5b extends the results of Figure 5a to all seman- each model instance for 10 epochs. For all model-specific ticpreservingtransformationst T,andtoallsixML4VD k hyperparameters,weusedthevaluesthatwerereportedinthe techniques.Insteadofshowingth∈ eaccuracyforeachtraining originalpapers[1,12–15,28].Consultourpublishedtraining epoch,we only use the maximum accuracy across the full scripts10forthecompletelistofhyperparametervaluesthat training.AcrossallsixML4VDtechniques,wecanobserve, weused. thataugmentingthetestingdatasetTewithtransformations Performancemetrics.Wetrackedandquantifiedtheper- t T (representedbytheblueboxplots),onaverage,leads k ∈ formanceofourtrainedmodelsontheselectedtestingdatasets toadropinaccuracycomparedtoevaluationsonthestandard usingseveralcommonlyusedperformancemetrics.Wereport testingdatasetTe(representedbythehorizontallineswith
sixmetricsinthispaper:Accuracy,f1-score,precision,recall, stars).InparalleltoFigure5awecanalsoobservethat,on falsepositiverate(FPR),andfalsenegativerate(FNR). average,trainingdataaugmentationusingthesametransfor- ForCodeXGLUE/Devignasabalanceddataset(45.6%vul- mationasfortestingdataaugmentationleadstoarestoration nerablefunctions),weuseaccuracyasthemainperformance oftheobserveddropsinaccuracy(representedbytheorange metric,sinceitisalsousedexclusivelyintheCodeXGLUE boxplots). benchmark[24]andontheleaderboard[25]. Table 2 summarizes the outputs of Algorithm 1 for all For VulDeePecker as a relatively imbalanced dataset six ML4VD techniques and both datasets. Specifically, it (28.7%vulnerablefunctions)weusethef1-scoreasthemain showstheaveragerecordedchangesintherespectivemetrics, performancemetric.Thef1-scoreisdefinedastheharmonic whenonlythetestingdatasetwasaugmented(bluecolumns, meanofprecisionandrecallandismostsuitablewhenthe output ),whenthetrainingandtestingdatasetswereaug- A1.1 positiveclass(inourcasevulnerablefunctions)istheminority mented using the same transformation (orange columns, classinanimbalanceddataset. output ),andwhenthetrainingandtestingdatasetswere A1.2 Hardware. WeusedasetupoffiveNvidiaA100GPUs, augmentedusingadifferenttransformation(greencolumns, eachequippedwith40GBRAM.Onerunofallourexperi- output ).Weobservethat,onaverage,augmentingthetest- A1.3 mentstakesapproximately60daysonasingleA100GPU. ingdatasetleadstoadropinaccuracy/f1-score( 0.025for − CodeXGLUE, 0.043forVulDeePecker),andaugmenting − the training datasetusing the same transformation restores 5 ExperimentalResults thatdecreasetowardspreviouslevels.Onaverage,approxi- mately69.0%(CodeXGLUE)and66.2%(VulDeePecker)of RQ.1Testing-andTrainingDataAugmentation thelostaccuracy/f1-scoreisrestored. Figure 6 shows the impact on accuracy caused by aug- Weinvestigate,whether(a)testingdataaugmentationusingse- menting only the testing data using the individual trans- manticpreservingtransformationdecreasestheperformance formationst T (impact(t ):=accuracy[MLM[Tr],Te ] ofstate-of-the-artML4VDtechniques,whether(b)training k k k ∈ − accuracy[MLM[Tr],Te]) forallsix ML4VD techniques. In 10GitHub:https://github.com/niklasrisse/USENIX_2024 otherwords,Figure6displaystheseverityoftheperformance 90.68 0.66 0.64 0.62 0.60 0.58 0.56 0.54 0.52 0.50 0.48 1 2 3 4 5 6 7 8 9 10 trainingepoch ycaruccatestset 0.71 Train:Tr,Test:Te Train:Tr10,Test:Te10 0.70 Train:Tr,Test:Te10 RandomGuessing 0.69 0.68 0.67 0.66 0.65 0.64 0.63 0.62 0.61 0.60 0.59 0.58 0.57 0.56 0.55 UniXcoder CoTexT GraphCB CodeBERTVulBERTa PLBart (a)Testsetaccuracyovertentrainingepochsofdifferentmodelstrained withVulBERTaontheCodeXGLUE/Devigndataset.Augmentingthetesting setTewithtransformationt10(blue)decreasestheaccuracy,butapplying thesametransformationalsotothetrainingdatasetTr(orange)restoresthe accuracybacktopreviouslevels. ycaruccatestset Train:Tr,Test:Te Train:Tr,Test:Tek Train:Trk,Test:Tek (b)ExtensionoftheresultsinFigure5a,foralltransformationstk T,and ∈ forallsixML4VDtechniques.Theboxplotsrepresentdistributionsofthe resultingaccuracies.AugmentingthetestingsetTewithtransformations tk T (blueboxplots)decreasestheaccuracy,butapplyingthesametrans- ∈ formationalsotothetrainingdatasetTr(orangeboxplots)partiallyrestores theaccuracy,althoughnotalwaystoitspreviouslevels. Figure5:Effectsofaugmentingthetestingdataandthetrainingdatausingthesamesemanticpreservingtransformations. 0.24 − 0.21 − 0.18 − 0.15 − 0.12 − 0.09 − 0.06 − 0.03 − 0.00 t1 t2 t3 t4 t5 t6 t7 t8 t9 t10 t11 ) t(tcapmi k UniXcoder CoTexT GraphCodeBERT CodeBERT VulBERTa PLBart Figure6:Impactonaccuracycausedbyaugmentingthetestingdatausingtheindividualtransformationst T (impact(t ):= k k ∈ accuracy[MLM[Tr],Te ] accuracy[MLM[Tr],Te]).ThemostimpactfultransformationsforeachMLtechniquearemarkedby k − redstars. declineofthetechniqueswhenonlyapplyingsemanticpre- andt )andremovalofcomments(t ),forwhichtheseverity 3 9 servingtransformationsonthetestingset.Themostimpactful ofimpactisalsobeloworcloseto1%.Themostimpactful transformations for each ML technique are marked by red transformationsarechangingtheorderofthefunctionparam- stars. eters(t ),defininganadditionalvoidfunction(t ),andadding 2 8 code snippets from the training set as comments (t ). For Ifaspecificsemanticpreservingtransformationhasahigh 10 thesetransformations,asubstantialpartofthepredictionsis negative impact on the accuracy of an ML technique, we changedfromcorrecttoincorrect:Between2.3%and10.6% can assume that either (a) the ML technique partly relied fort ,between1.8%and18.1%fort ,andbetween2.1%and onunrelatedfeaturesthatwereremovedormodifiedbythe 2 8 11.5%fort .Overall,transformationsthatinsertstatements transformation (e.g. removal of comments) to achieve its 10
(e.g. t ,t ,t ,andt ) orreorderstatements (e.g. t andt ) originalhighaccuracy,or(b) thatthe ML technique relied 4 5 8 10 2 6 seemtohaveahigherimpactthantheothertypes. onunrelatedfeaturesintroducedbythetransformation(e.g. additionofcomments)toachievethedecreasedaccuracyafter Additionally, there are also differences between the six applyingthetransformation. ML4VD techniques. For example,moving the code into a separatefunction(t )onlyseemstohaveahighimpacton FromtheresultspresentedinFigure6wecanobserve,that 6 CodeBERT,and inserting a simple comment (t ) seems to therearecleardifferencesbothbetweentransformationsand 5 haveamuchhigherimpactonUniXcoderthanontheother ML4VDtechniques.Asonemightexpect,atrivialtransfor- ML4VD techniques. Future work is required to determine mationsuchasaddingwhitespace(t )haslittletonoimpact 7 whytheML4VDtechniquesaremoreorlessrobustagainst ontheaccuracyofallsixML4VDtechniques.Theseverityof specifictransformations. thisimpactis,onaverage,below1%accuracy,whichmeans that below 1% of predictions are changed from correct to Wealsoinvestigatedtheimpactofeachindividualtrans- incorrectbyapplyingthistransformation.TheML4VDtech- formationwhennotonlythetestingdatabutalsothetraining niquesalsoseemtoberobustagainstidentifierrenaming(t dataisaugmentedusingadifferenttransformationthanfor 1 100.72 0.70 0.68 0.66 0.64 0.62 0.60 0.58 0.56 0.54 0.52 0.50 0.48 1 2 3 4 5 6 7 8 9 10 trainingepoch ycaruccatestset 0.71 Train:Tr,Test:Te RandomGuessing 0.70 Train:Tr,Test:Te10 Train:Trj 6=10,Test:Te10 00 .. 66 89 Train:Tr10,Test:Te10 0.67 0.66 0.65 0.64 0.63 0.62 0.61 0.60 0.59 0.58 0.57 0.56 0.55 UniXcoder CoTexT GraphCBCodeBERTVulBERTa PLBart (a)Testsetaccuracyovertentrainingepochsofdifferentmodelstrainedwith VulBERTaontheCodeXGLUE/Devigndataset.Augmentingthetrainingset Trwithdifferenttransformationst j=10thanthetestingdataset(greenlines) doesnotrestoretheaccuracybackt̸opreviouslevels. ycaruccatestset Train:Tr,Test:Te Train:Tr,Test:Tek Train:Trk,Test:Tek Train:Trk,Test:Tej=k 6 (b)ExtensionoftheresultsinFigure7a,foralltransformationstk Tandfor ∈ allsixML4VDtechniques.Theboxplotsrepresentdistributionsoftheresult- ingaccuracies.AugmentingthetrainingsetTrwithdifferenttransformations t k=jthanthetestingdataset(greenboxplots)doesnotrestoretheaccuracy ba̸cktopreviouslevels.Insteadofrestoring,theaccuracysometimeseven dropsfurthercomparedtousingstandardtrainingdata(greenbelowblue). 0.90 0.88 0.86 0.84 0.82 0.80 0.78 0.76 0.74 0.72 0.70 0.68 0.66 0.64 UniXcoder CoTexT GraphCBCodeBERTVulBERTa PLBart 1ftestset 0.71 0.70 0.69 0.68 0.67 0.66 0.65 0.64 0.63 0.62 0.61 0.60 0.59 0.58 0.57 0.56 0.55 UniXcoder CoTexT GraphCBCodeBERTVulBERTa PLBart (c)SamesetupasforFigure7b,butusingtheVulDeePeckerdataset.The boxplotsrepresentdistributionsoftheresultingf1-scores.Augmentingthe trainingsetTrwithdifferenttransformationst k=jthanthetestingdataset (greenboxplots)doesnotrestorethef1-scorebac̸ ktopreviouslevels. ycaruccatestset Train:Tr,Test:Te Train:Tr,Test:Tek Train:Trk,Test:Tek Train:Tr11,Test:Tej (d)SamesetupasforFigure7b,butthegreenboxplotsrepresenttheaccura- ciesachievedbyaugmentingthetrainingdatausingthemetatransformation t11,inthiscasesampledfrom t1,...,t10 tj ,andthetestingdatausinga { }\{ } singleleft-outtransformationtj.AugmentingthetrainingdatasetTrwitht11 partiallyrestorestheaccuracy,althoughnottoitspreviouslevels. Figure7:Effectsofaugmentingthetrainingdatawithdifferentsemanticpreservingtransformationsthanthetestingdata. thetestingdata.However,duetotheresultsbeingverysim- RQ.2OverfittingtoSpecificTransformations ilartoFigure6,wedecidedtoomitthisfromthepaperand We investigate,whether the performance of ML4VD tech- provideitassupplementarymaterialinAppendixB. niquescanstillberestoredifweaugmentthetrainingdataset withadifferentsemanticpreservingtransformationthanthe Acrosstwodatasets,sixML4VDtechniques,and11trans- testingdataset.WeuseAlgorithm1toinvestigateRQ.2,with formations,onaverage,(a)testingdataaugmentationus- thesamesetupasforRQ.1. ingsemanticpreservingtransformationsleadstoadropin Results.Figure7aissimilartoFigure5a,italsoshowsthe accuracy/f1-score(CodeXGLUE: 0.025,VulDeePecker: testsetaccuraciesofdifferentVulBERTamodelsmeasured − 0.043),(b)trainingdataaugmentationusingthesame after each of the ten training epochs. In addition to the re- − transformationsrestores69.0%(CodeXGLUE)and66.2% sultsdisplayedinFigure5a,Figure7ashowstheaccuracies (VulDeePecker)ofthelostaccuracy/f1-score,and(c)trans- (greenlines)ofVulBERTamodelstrainedondatathatwas formations thatinsertorreorderstatements seem to be augmentedusingalltransformationsexceptt ,whichwas 10 moreimpactfulthanothertypesoftransformations. used to augment the testing dataset. We observe,that aug- mentingthetrainingdatasetTrwithdifferenttransformations
RQ.1hasalreadybeenstudiedintheliterature,formany t asthetestingdatasetdoesnotrestoretheaccuracyback j=10 differenttechniques,datasets,andtasks[5,18,22,35,38,39, to̸ previouslevels. 41,42].Basedonourevidence,wecanapprovethefindings Figure 7b visualizes the same extended results for all oftheliterature. semantic preserving transformations t T and for all six k ∈ 11Table 2: Algorithm 1: Average changes when augmenting only the testing data (output ),training and testing data A1.1 using the same (output ), or a different transformation A1.2 (output ). A1.3 CodeXGLUE VulDeePecker cirteM outA1.1 outA1.2 outA1.3 outA1.1 outA1.2 outA1.3 Tr Tr Trk Trk Tr Tr Trk Trk Technique Te Tek Tek Tej=k Te Tek Tek Tej=k ̸ ̸ ycarucca UniXcoder 0.693-0.043 -0.011 -0.050 0.975-0.005 -0.002 -0.010 CoTexT 0.673-0.022 -0.014 -0.030 0.973-0.001 -0.001 -0.003 GraphCB 0.655-0.015 -0.006 -0.021 0.973-0.014 -0.002 -0.015 CodeBERT 0.651-0.034 -0.000 -0.040 0.974-0.007 -0.002 -0.012 VulBERTa 0.639-0.017 -0.004 -0.025 0.973-0.011 -0.002 -0.012 PLBart 0.633-0.021 -0.007 -0.026 0.972-0.003 -0.002 -0.008 -0.025 -0.007 -0.032 -0.007 -0.002 -0.010 erocs-1f UniXcoder 0.680-0.037 -0.007 -0.041 0.880-0.028 -0.012 -0.054 CoTexT 0.635 0.001 0.006 0.006 0.872-0.006 -0.006 -0.020 GraphCB 0.629-0.024 -0.013 -0.033 0.869-0.093 -0.006 -0.091 CodeBERT 0.596-0.005 0.012 0.001 0.873-0.045 -0.007 -0.082 VulBERTa 0.652-0.050 -0.014 -0.048 0.873-0.082 -0.009 -0.073 PLBart 0.618-0.009 -0.006 -0.016 0.865-0.014 -0.007 -0.035 -0.021 -0.004 -0.022 -0.045 -0.008 -0.059 llacer UniXcoder 0.787-0.025 -0.016 -0.009 0.893-0.034 -0.011 -0.041 CoTexT 0.851 0.066 0.074 0.105 0.900-0.004 -0.015 -0.029 GraphCB 0.661-0.023 -0.029 -0.031 0.895-0.153 -0.005 -0.101 CodeBERT 0.572 0.079 0.031 0.106 0.890-0.090 -0.004 -0.103 VulBERTa 0.759-0.097 -0.029 -0.056 0.898-0.094 -0.000 -0.073 PLBart 0.658 0.025 0.003 0.024 0.884-0.008 -0.003 -0.015 0.004 0.006 0.023 -0.064 -0.006 -0.060 noisicerp UniXcoder 0.717-0.033 0.020 -0.033 0.939-0.008 0.030 -0.045 CoTexT 0.684-0.029 -0.027 -0.044 0.955-0.015 0.013 -0.012 GraphCB 0.734-0.026 -0.019 -0.035 0.995-0.016 -0.005 -0.040 CodeBERT 0.847-0.115 -0.009 -0.107 1.000-0.000 -0.007 -0.031 VulBERTa 0.643-0.004 -0.019 -0.034 0.850 0.023 -0.012 -0.010 PLBart 0.675-0.031 -0.015 -0.049 0.971-0.048 0.008 -0.068 -0.040 -0.012 -0.051 -0.011 0.005 -0.034 RPF UniXcoder 0.142 0.033 -0.018 0.049 0.006 0.001 -0.003 0.006 CoTexT 0.211 0.018 0.028 0.034 0.004 0.001 -0.001 0.001 GraphCB 0.079 0.040 -0.003 0.027 0.000 0.002 0.000 0.003 CodeBERT 0.026 0.140 0.005 0.145 0.000 0.000 0.001 0.003 VulBERTa 0.194-0.036 0.028 0.040 0.018-0.004 0.002 -0.001 PLBart 0.137 0.016 0.020 0.026 0.003 0.004 -0.001 0.007 0.035 0.010 0.053 0.001 -0.000 0.003 RNF onaverage,augmentingthetrainingdatasetTrwithadifferent transformationt asthetestingdatasetdoesnotrestorethe k=j accuracybackto̸previouslevels. InFigure7dthegreenboxplotsrepresentthedistributionof accuraciesachievedbyaugmentingthetrainingdatausingour metatransformationt .Slightlydifferenttothedefinitionof 11 t inTable1,eachfunctioninthetrainingsetistransformed 11 using a random transformation t with k [1,10] j,with k ∈ \ oneleft-outtransformationt whichisappliedtothetesting j data.Sinceoursetofimplementedtransformationscontains groupsofsimilartransformations(e.g.addingdifferenttypes ofcomments),wewouldexpecttheaccuraciestobehigher comparedtoapplyingonlyasingledifferenttransformation tothetrainingset(green boxplotsofFigure7d),butlower comparedtoapplyingexactlythesametransformationtothe trainingset(orangeboxplots).BasedonFigure7d,weobserve thatisthecaseacrossallsixML4VDtechniques.Augmenting thetrainingdatasetTrwiththemetatransformationt does 11 notfullyrestoretheaccuracy,butmovesitclosertowardsthe accuracyonunaugmenteddatacomparedtoapplyingonlya singledifferenttransformationtothetrainingset. InadditiontotheresultsforRQ.1,Table2alsoshowsthe averagerecordedchangesintherespectivemetrics,whenthe trainingandtestingdatasetswereaugmentedusingdifferent transformations(greencolumns,output ).Weobservethat, A1.3 onaverage,thescoredropsby0.032accuracy(CodeXGLUE)
and0.059f1-score(VulDeePecker).Acrossthesixtechniques, thedecreaseisonaverage30.2%(CodeXGLUE)and77.5% (VulDeePecker)strongerthanfortrainingonunaugmented data.Inotherwords,augmentingthetrainingdatasetusinga differenttransformationthanforthetestingdatasetdidnotre- storethescoretowardspreviouslevels,butinsteaddecreased UniXcoder 0.213 0.025 0.016 0.009 0.107 0.034 0.011 0.041 itevenfurther. CoTexT 0.149-0.066 -0.074 -0.105 0.100 0.004 0.015 0.029 GraphCB 0.339 0.023 0.029 0.031 0.105 0.153 0.005 0.101 For the other metrics (recall, precision, FPR and FNR), CodeBERT 0.428-0.079 -0.031 -0.106 0.110 0.090 0.004 0.103 VulBERTa 0.241 0.097 0.029 0.056 0.102 0.094 0.000 0.073 wegenerallyobservesimilarpatternsthanforaccuracyand PLBart 0.342-0.025 -0.003 -0.024 0.116 0.008 0.003 0.015 f1-score. However,therearealsoslightdeviations,e.g. for -0.004 -0.006 -0.023 0.064 0.006 0.060 CodeXGLUErecallimprovesonaverageby0.023whentrain- ingdataisaugmentedusingadifferenttransformationthan thetestingdatainsteadofdecreasingasexpected.Thesedevi- ML4VDtechniques.Again,theblueandtheorangeboxplots ationscanbeexplainedbyinnatetradeoffsbetweenrecall/- representthedistributionsofaccuracies,wheneitheronlythe precisionandFPR/FNR,andcanonlybeintepretedincontext testingdataset(blue)ortrainingandtestingdatasetswereaug- oftheothermetrics.Accuracyandf1-scoreprovideabetter mentedusingthesametransformation(orange).Thegreen summaryoftheperformance,whichiswhytheyareusedas boxplotsrepresentthedistributionofaccuraciesachievedby thepreferredmetricsforthetwodatasets. modelsthatweretrainedondata,whichwasaugmentedusing a differenttransformation than forthe testing data. Across Acrosstwodatasets,sixML4VDtechniques,and11trans- allsixML4VDtechniques,weobservethat,onaverage,aug- formations,augmentingthetrainingdatasetusingadif- mentingthetrainingdatasetTrwithadifferenttransformation ferent transformation than for the testing dataset does t k=jthanthetestingdatasetdoesnotrestoretheaccuracyback not restore the performance back to previous levels. In to̸ previouslevels. otherwords,theML4VDtechniquesoverfittothelabel- Figure 7c visualizes the same results as Figure 7b, but unrelated features introduced by semantic preserving using the VulDeePecker dataset. In this figure, the y-axis transformationsduringtrainingdataaugmentation. measures the f1-score, since it is the preferred evaluation metricfortheVulDeePeckerdataset.Again,weobservethat, Insummary,wecanobservethatacrossthetestedML4VD 12Table 3: Algorithm 2: Performance of six ML4VD tech- niquesevaluatedonthestandardCodeXGLUE/Devigntesting datasetTeorthevulnerability-patchtestingdatasetVPTe. cirteM outA2.1 outA2.2 outA2.3 outA2.4 Tr Tr VPTr VPTr Technique Te VPTe Test:VPTe Te ycarucca UniXcoder 0.693 0.414 0.616 0.546 CoTexT 0.673 0.503 0.607 0.575 GraphCB 0.655 0.342 0.596 0.546 CodeBERT 0.651 0.294 0.571 0.548 VulBERTa 0.639 0.527 0.602 0.564 PLBart 0.633 0.524 0.598 0.572 0.657 0.434 0.598 0.559 erocs-1f UniXcoder 0.680 0.582 0.662 0.613 CoTexT 0.635 0.667 0.665 0.616 GraphCB 0.629 0.508 0.654 0.603 CodeBERT 0.596 0.455 0.629 0.613 VulBERTa 0.652 0.610 0.651 0.615 PLBart 0.618 0.583 0.633 0.575 0.635 0.567 0.649 0.606 llacer UniXcoder 0.787 0.819 0.870 0.896 CoTexT 0.851 1.000 0.975 0.941 GraphCB 0.661 0.680 0.835 0.873 CodeBERT 0.572 0.589 0.770 0.883 VulBERTa 0.759 0.758 0.909 0.928 PLBart 0.658 0.680 0.741 0.738 0.715 0.754 0.850 0.876 noisicerp UniXcoder 0.717 0.452 0.668 0.518 CoTexT 0.684 0.502 0.724 0.702 GraphCB 0.734 0.406 0.622 0.509 CodeBERT 0.847 0.371 0.656 0.516 VulBERTa 0.643 0.531 0.781 0.647 PLBart 0.675 0.535 0.663 0.547 0.717 0.466 0.686 0.573 RPF UniXcoder 0.142 0.816 0.107 0.172 CoTexT 0.211 0.823 0.060 0.041 GraphCB 0.079 0.840 0.091 0.177 CodeBERT 0.026 0.849 0.102 0.233 VulBERTa 0.194 0.312 0.034 0.061 PLBart 0.137 0.251 0.138 0.213 0.131 0.649 0.089 0.149 RNF whethertrainingtodistinguishbetweenvulnerabilitiesand patchesimprovestheperformanceonstandardtestingdata. Methodology. We used Algorithm 2 to investigate both questions.Asinputstothealgorithm,weselectedthetraining andtestingsubsetsoftheCodeXGLUE/Devigndatasetasthe standardtrainingandtestingdatasetsTrandTe,andthetrain- ingandtestingsubsetsofVulnPatchPairsasthevulnerability- patchtrainingandtestingdatasetsVPTrandVPTe.Weran thealgorithmforallsixML4VDtechniquesseparately. Results.Table3showstheresultsofrunningAlgorithm2. Specifically, it shows the performance of different mod- els evaluatedon the standardCodeXGLUE/Devign testing
datasetTeorthevulnerability-patchtestingdatasetVPTe.We focusouranalysisontheresultsmeasuredinaccuracysince itisthepreferredperformancemetricforbalanceddatasets suchasCodeXGLUEandVulnPatchPairs. Weobserve,thattheaccuracyofallsixML4VDtechniques ishighest(between0.633and0.693)whentrainedandeval- uatedonstandardtrainingandtestingdata(secondcolumn, output ).Thisisexpectedandconsistentwiththefindings A2.1 intheliterature[1,12–15,28].Whentrainedandevaluatedon VulnPatchPairs (fourthcolumn,output ) the accuracyis A2.3 consistentlylowerthaninthestandardsetting(between0.558 and 0.617),but still significantly higher than the expected accuracyofarandomguesser11.However,whentrainedon standardtrainingdataandevaluatedontheVulnPatchPairs testingdataset(thirdcolumn,output ),theaccuracydrops A2.2 dramatically(between0.294and0.527).Eventhebestmodel (VulBERTa)isonly0.027pointsbetterthanarandomguesser. Onaverage,theaccuracyisworsethanrandomguessing.In UniXcoder 0.213 0.181 0.130 0.104 otherwords,allsixML4VDtechniquesthatweevaluatedare CoTexT 0.149 0.000 0.025 0.059 GraphCB 0.339 0.320 0.165 0.127 unabletodistinguishbetweenvulnerabilitiesandtheirpatches CodeBERT 0.428 0.411 0.230 0.117 whentrainedonatypicalvulnerabilitydetectiondataset. VulBERTa 0.241 0.242 0.091 0.072 PLBart 0.342 0.320 0.259 0.262 WhentrainedonVulnPatchPairsandevaluatedonstandard 0.285 0.246 0.150 0.124 testingdata(fifthcolumn,output ),wegetasimilarpicture. A2.4 Theperformanceissignificantlyworse(between0.546and 0.575)comparedtomodelstrainedonstandardtrainingdata techniques,transformations,anddatasets,trainingdataaug- (secondcolumn). However,theperformanceinthiscaseis mentationonlyrestorestheperformancetopreviouslevels notablybetterthanrandomguessing. whenthetestingdatasetisaugmentedinasimilarwaythan thetrainingdataset. (a)AllsixML4VDtechniquesarenotabletodistinguish between vulnerabilities and their patches when trained Theperformancegainedbydataaugmentationonlyap- on standardtraining data. On average,the accuracy is pliestothespecifictransformationsusedduringthetrain- lowerthantheexpectedaccuracyofarandomguesser.(b) ingofthemodel.ML4VDtechniquescontinuetoleverage Whentrainedtodistinguishbetweenvulnerabilitiesand unrelatedfeatureswhendecidingwhetherafunctioncon- theirpatches,theML4VDtechniquesareabletopredict tainsasecurityvulnerability. standardtestingdatabetterthanarandomguesser,but still significantly worse than when trained on standard RQ.3GeneralizationtoVulnPatchPairs trainingdata.Inotherwords,theML4VDtechniquesare unabletogeneralizefromtheirtrainingdatatoaslightly We investigate, whether (a) ML4VD techniques are able modifiedvulnerabilitydetectionsetting. to generalize from typical vulnerability detection training datasetstoamodifiedsetting,inwhichtheyarerequiredto 11SinceVPTeisperfectlyclassbalanced(50%vulnerable,50%clean),a distinguishbetweenvulnerabilitiesandtheirpatches,and(b) randomguesser(coinflip)wouldbeexpectedtoachieveanaccuracyof0.5. 136 ThreatstoValidity we decided to focus our experiments on the CodeXGLUE andVulDeePeckerdatasets,eventhoughtheydonotreflecta As forany empirical study,there are various threats to the realisticclassdistribution. validityofourresultsandconclusions. Internalvalidity.Acommonsourceofsystematicerrorin 7 DiscussionandFutureWork empiricalstudiesonML4VDtechniquesishyperparameterse- lection.Givenaparticulardesiredoutcome,hyperparameters In summary, our results demonstrate that state-of-the-art canbeoptimizedtomovetheresultinthedesireddirection. ML4VD techniques overfit to the label-unrelated features Wetriedtominimizethisriskbytakingthevaluesforhyper- thatareintroducedbysemanticpreservingtransformations parametersprovidedbytheauthorsofthechosenML4VD duringtrainingandthatML4VDtechniquesarenotableto techniques. generalizetoamodifiedsetting,inwhichtheyhavetodistin- Anotherpotentialsourceofsystematicerroristhetraining- guishbetweenvulnerabilitiesandtheirpatches. /testing dataset split. Similar to hyperparameter selection, Overfitting oflearnedmodels is a well-known problem datasetsplitcanalsobevariedtochangearesultinadesired inthemachinelearningresearchfield[11,40].However,as direction.Wetriedtoavoidthisriskbytakingtheprovided showninourexperiments,thetraditionalapproachtoevalu- splitsoftheCodeXGLUEbenchmark[24]andbyHanifet atingML4VDtechniquesoftenfailstodetectoverfittingto al.[26]. label-unrelated features in the training data. Our proposed External validity. The degree to which our results gen- Algorithm1isanovelwaytomeasureoverfittingofML4VD eralizetootherlearning-basedtechniques,vulnerabilityde- techniques,thatgoesbeyondthetraditionalapproach,andcan tection datasets, semantic preserving transformations, and evendetectoverfittingifthereisnogapinthestandardsetup performance metrics,are concerns ofexternalvalidity. We atall. There are severalcommon strategies to reduce over- triedtominimizetheriskattachedtotheseconcernsbyevalu- fittinginthestandardevaluationsetup,e.g. early-stopping,
atingawidesetofsixstate-of-the-arttechniques,twodatasets, dropout,orlargepre-trainingdatasets[40],whicharealready sixperformancemetrics,and11semanticpreservingtrans- integratedintheML4VDtechniquesthatweusedinourex- formations.ForRQ.3,weonlyinvestigatethegeneralization periments. However,ourexperiments demonstrate that the betweenCodeXGLUE/DevignandVulnPatchPairs.Tomax- techniquesarestillseverelyoverfittingtolabel-unrelatedfea- imizegenerality,wetriedtokeepbothAlgorithm1andAl- turesintroducedbysemanticpreservingtransformationsdur- gorithm2asgeneralaspossible,sothattheycaneasilybe ing training data augmentation. Finding ways to robustify adapted to other techniques,datasets,transformations,and ML4VDtechniqueswithoutorwithminimaloverfittingwill metrics. be a central challenge of the machine learning for vulner- Simplicity of Transformations. Some of the semantic ability detection researcharea. We hope thatourproposed preservingtransformationsthatweused(seeTable1)could algorithmscanbeusedtounderstandtheproblem,todevelop beeasilyaddressedbyaddingadditionaldatapre-processing newapproaches,andtotracktheprogressinthisdirection. (e.g. mappingidentifierstostandardizednames).However, Generalization.TheresultsforRQ.3(seeSection5)re- thespecifictransformationsthatweimplementedaremerely veal,thatstate-of-the-artML4VDtechniqueslacktheability atooltodemonstrate,thattheperformancegainedbytraining togeneralizefrom theirtrainingdatatoamodifiedsetting, dataaugmentationonlyappliestothespecifictransformations whichrequirestodistinguishbetweenvulnerabilitiesandtheir usedfortrainingandthatthetechniquesthatweinvestigated patches. Sincewecannotassumethatreal-worldsoftware overfit to the label-unrelated features introduced by these systemswouldbesimilartothetrainingdataofthesetech- transformations.Foranewtechnique,theycouldbereplaced niques,theabilitytogeneralizetomodifiedsettingswouldbe byadifferentsetoftransformations. requiredforthesetechniquestobesafelyintegratedintoreal Classbalance.Multipleworkshaveshownthatlearning- softwareengineeringenvironments. basedvulnerabilitydetectiontechniquestrainedonfairlybal- TheabilityofaMLtechniquetogeneralizetotestingdata anceddatasets(suchasCodeXGLUE)oftenfailtogeneralize that is differently distributed than the training data is also toreal-worldcoderepositories[3,9,16],whichusuallycontain calledout-of-distributiongeneralization,andthelackofitfor amuchsmallerratioofsecurityvulnerabilities[20].However, learning-basedtechniqueshasbeenrecentlyidentified(e.g. measuredbycitations,class-balanceddatasetsarestillbyfar inthecomputervisiondomain[17,34]).OurproposedAlgo- the most popular datasets to evaluate learning-based tech- rithm2canbeseenasatooltomeasureout-of-distribution niquesforvulnerabilitydetection.Toourcurrentknowledge, generalizationforthedomainofautomaticvulnerabilitydetec- thereisnovulnerabilitydetectiondatasetwithsufficientsize tion.Itwouldbeaninterestingavenueforfutureworktotry (morethan10kcodesnippets),high-qualitylabels(manually approachesthathavebeenusedtoaddressout-of-distribution providedbysecurityexperts),andarealisticdistributionof generalization in otherdomains (e.g. causalrepresentation vulnerabletonon-vulnerablecodesnippetsthatiswidelyused learning[32])onthetaskofautomaticvulnerabilitydetection intheresearchcommunity(atleast50citations).Thisiswhy andmeasurethesuccessusingourAlgorithm2. 14References [10] YizhengChen,ZhoujieDing,LamyaAlowain,Xinyun Chen,andDavidWagner. Diversevul:Anewvulnerable [1] WasiAhmad,SaikatChakraborty,BaishakhiRay,and sourcecodedatasetfordeeplearningbasedvulnerabil- Kai-WeiChang. Unifiedpre-trainingforprogramun- itydetection. InProceedingsofthe26thInternational derstandingandgeneration. InProceedingsofthe2021 SymposiumonResearchinAttacks,IntrusionsandDe- ConferenceoftheNorthAmericanChapteroftheAssoci- fenses,RAID’23,page654–668,NewYork,NY,USA, ationforComputationalLinguistics:HumanLanguage 2023.AssociationforComputingMachinery. Technologies,pages2655–2668,Online,June2021.As- sociationforComputationalLinguistics. [11] Tom Dietterich. Overfitting and undercomputing in machinelearning. ACMComput.Surv.,27(3):326–327, [2] Leonhard Applis, Annibale Panichella, and Arie van sep1995. Deursen. Assessing robustness of ml-based program analysistoolsusingmetamorphicprogramtransforma- [12] ZhangyinFeng,DayaGuo,DuyuTang,NanDuan,Xi- tions. In202136thIEEE/ACMInternationalConfer- aochengFeng,MingGong,LinjunShou,BingQin,Ting enceonAutomatedSoftwareEngineering(ASE),pages Liu,Daxin Jiang,and Ming Zhou. Codebert: A pre- 1377–1381,2021. trainedmodelforprogrammingandnaturallanguages, 2020. [3] DanielArp,ErwinQuiring,FeargusPendlebury,Alexan- derWarnecke,FabioPierazzi,ChristianWressnegger, [13] Daya Guo,Shuai Lu,Nan Duan,Yanlin Wang,Ming LorenzoCavallaro,andKonradRieck.Dosanddon’tsof Zhou,andJian Yin. Unixcoder: Unifiedcross-modal machinelearningincomputersecurity. In31stUSENIX pre-training for code representation. arXiv preprint SecuritySymposium(USENIXSecurity22),pages3971– arXiv:2203.03850,2022. 3988,2022.
[14] DayaGuo,ShuoRen,ShuaiLu,ZhangyinFeng,Duyu [4] GuruBhandari,AmaraNaseer,andLeonMoonen. Cve- Tang,ShujieLiu,LongZhou,NanDuan,AlexeySvy- fixes:Automatedcollectionofvulnerabilitiesandtheir atkovskiy, Shengyu Fu, et al. Graphcodebert: Pre- fixes from open-source software. In Proceedings of training code representations with data flow. arXiv the17thInternationalConferenceonPredictiveModels preprintarXiv:2009.08366,2020. andDataAnalyticsinSoftwareEngineering,PROMISE [15] Hazim Hanif and Sergio Maffeis. Vulberta: Simpli- 2021,page30–39,NewYork,NY,USA,2021.Associa- fiedsourcecodepre-trainingforvulnerabilitydetection. tionforComputingMachinery. In2022InternationalJointConferenceonNeuralNet- works(IJCNN),pages1–8,2022. [5] Pavol Bielik and Martin Vechev. Adversarial robust- nessforcode. InProceedingsofthe37thInternational [16] JingxuanHe,LucaBeurer-Kellner,andMartinVechev. ConferenceonMachineLearning,ICML’20.JMLR.org, Ondistributionshiftinlearning-basedbugdetectors. In 2020. KamalikaChaudhuri,StefanieJegelka,LeSong,Csaba Szepesvari,GangNiu,andSivanSabato,editors,Pro- [6] Paul Black. A software assurance reference dataset: ceedingsofthe39thInternationalConferenceonMa- Thousandsofprogramswithknownbugs,2018-04-16 chineLearning,volume162ofProceedingsofMachine 2018. Learning Research,pages 8559–8580. PMLR,17–23 [7] Harold Booth, Doug Rike, and Gregory Witte. The Jul2022. nationalvulnerabilitydatabase(nvd):Overview,2013- [17] Dan Hendrycks, Steven Basart, Norman Mu, Saurav 12-182013. Kadavath, Frank Wang, Evan Dorundo, Rahul Desai, [8] Quang-CuongBui,RiccardoScandariato,andNicolás Tyler Zhu, Samyak Parajuli, Mike Guo, Dawn Song, E.DíazFerreyra. Vul4j:Adatasetofreproduciblejava JacobSteinhardt,andJustin Gilmer. The manyfaces vulnerabilitiesgearedtowardsthestudyofprogramre- ofrobustness:Acriticalanalysisofout-of-distribution pairtechniques.InProceedingsofthe19thInternational generalization. InProceedingsoftheIEEE/CVFInter- ConferenceonMiningSoftwareRepositories,MSR’22, nationalConferenceonComputerVision(ICCV),pages page464–468,NewYork,NY,USA,2022.Association 8340–8349,October2021. forComputingMachinery. [18] JordanHenkel,GouthamRamakrishnan,ZiWang,Aws [9] Saikat Chakraborty, Rahul Krishna, Yangruibo Ding, Albarghouthi,SomeshJha,andThomasReps. Semantic andBaishakhiRay. Deeplearningbasedvulnerability robustnessofmodelsofsourcecode. In2022IEEEIn- detection: Are we there yet? IEEE Transactions on ternationalConferenceonSoftwareAnalysis,Evolution SoftwareEngineering,PP:1–1,062021. andReengineering(SANER).IEEE,mar2022. 15[19] AbramHindle,EarlT.Barr,ZhendongSu,MarkGabel, Multi-tasklearningwithcode-texttransformer. InPro- andPremkumarDevanbu. Onthenaturalnessofsoft- ceedingsofthe1stWorkshoponNaturalLanguagePro- ware. In201234thInternationalConferenceonSoft- cessingforProgramming(NLP4Prog2021),pages40– wareEngineering(ICSE),pages837–847,2012. 47,Online,August2021.AssociationforComputational Linguistics. [20] Rafael-MichaelKarampatsisandCharlesSutton. How oftendosingle-statementbugsoccur?themanysstubs4j [29] Serena E. Ponta, Henrik Plate, Antonino Sabetta, dataset. In 2020 IEEE/ACM 17th International Con- MicheleBezzi,andCédricDangremont. Amanually- ferenceonMiningSoftwareRepositories(MSR),pages curateddatasetoffixestovulnerabilitiesofopen-source 573–577,2020. software. InProceedingsofthe16thInternationalCon- ference on Mining Software Repositories, MSR ’19, [21] Yaoxian Li,Shiyi Qi,Cuiyun Gao,Yun Peng,David page383–387.IEEEPress,2019. Lo,Zenglin Xu,and Michael R. Lyu. A closer look intotransformer-basedcodeintelligencethroughcode [30] MdRafiqulIslamRabin,NghiD.Q.Bui,KeWang,Yi- transformation:Challengesandopportunities,2022. junYu,LingxiaoJiang,andMohammadAminAlipour. Onthegeneralizabilityofneuralprogrammodelswith [22] ZhenLi,JingTang,DeqingZou,QianChen,Shouhuai respecttosemantic-preservingprogramtransformations. Xu,ChaoZhang,YichenLi,andHaiJin. Towardsmak- InformationandSoftwareTechnology,135:106552,jul ingdeeplearning-basedvulnerabilitydetectorsrobust, 2021. 2021. [31] MdMahbuburRahman,IraCeka,ChengzhiMao,Saikat [23] ZhenLi,DeqingZou,ShouhuaiXu,XinyuOu,HaiJin, Chakraborty, Baishakhi Ray, and Wei Le. Towards SujuanWang,ZhijunDeng,andYuyiZhong. VulDeeP- causal deep learning for vulnerability detection. In ecker:Adeeplearning-basedsystemforvulnerability Proceedings of the 46th International Conference on detection.InProceedings2018NetworkandDistributed SoftwareEngineering,ICSE’24.IEEEPress,2024. SystemSecuritySymposium.InternetSociety,2018. [32] B.Schölkopf,F.Locatello,S.Bauer,N.R.Ke,N.Kalch- brenner,A.Goyal,andY.Bengio. Towardcausalrepre- [24] Shuai Lu, Daya Guo, Shuo Ren, Junjie Huang, sentationlearning.ProceedingsoftheIEEE,109(5):612– AlexeySvyatkovskiy,AmbrosioBlanco,ColinClement, 634,2021. Dawn Drain, Daxin Jiang, Duyu Tang, Ge Li, Li-
dongZhou,LinjunShou,LongZhou,MicheleTufano, [33] Rico Sennrich, Barry Haddow, and Alexandra Birch. MINGGONG,MingZhou,NanDuan,NeelSundare- Neuralmachinetranslationofrarewordswithsubword san, Shao Kun Deng, Shengyu Fu, and Shujie LIU. units. InKatrinErkandNoahA.Smith,editors,Pro- Codexglue:Amachinelearningbenchmarkdatasetfor ceedingsofthe54thAnnualMeetingoftheAssociation codeunderstandingandgeneration. InJ.Vanschoren forComputationalLinguistics(Volume1:LongPapers), and S. Yeung, editors, Proceedings of the Neural In- pages1715–1725,Berlin,Germany,August2016.As- formationProcessingSystemsTrackonDatasetsand sociationforComputationalLinguistics. Benchmarks,volume1,2021. [34] Zheyan Shen,Jiashuo Liu,Yue He,Xingxuan Zhang, [25] Codexglueleaderboards,2021. https://microsoft. Renzhe Xu,Han Yu,and Peng Cui. Towards out-of- github.io/CodeXGLUE/#LB-DefectDetection. distributiongeneralization:Asurvey,2021. [26] Vuldeepecker function-level dataset, 2022. [35] ShashankSrikant,SijiaLiu,TamaraMitrovska,Shiyu https://github.com/ICL-ml4csec/VulBERTa/ Chang, Quanfu Fan, Gaoyuan Zhang, and Una-May tree/main/data. O’Reilly. Generatingadversarialcomputerprogramsus- ingoptimizedobfuscations.InInternationalConference [27] PedroOrvalho,MikolášJanota,andVascoManquinho. onLearningRepresentations,2021. Multipas:applyingprogramtransformationstointroduc- toryprogrammingassignmentsfordataaugmentation. [36] BenjaminSteenhoek,MdMahbuburRahman,Richard InProceedingsofthe30thACMJointEuropeanSoft- Jiles,andWeiLe. Anempiricalstudyofdeeplearning wareEngineeringConferenceandSymposiumonthe modelsforvulnerabilitydetection.InProceedingsofthe FoundationsofSoftwareEngineering,pages1657–1661, 45thInternationalConferenceonSoftwareEngineering, 2022. ICSE’23,page2237–2248.IEEEPress,2023. [28] LongPhan,HieuTran,DanielLe,HieuNguyen,James [37] Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Annibal, Alec Peltekian, and Yanfang Ye. CoTexT: Uszkoreit,LlionJones,AidanNGomez,ŁukaszKaiser, 167.0 6.5 6.0 5.5 5.0 4.5 4.0 3.5 3.0 2.5 2.0 None t1 t2 t3 t4 t5 t6 t7 t8 t9 t10 t11 yportnessorc A Naturalness Meancrossentropycleantestingset Since vulnerability detection techniques are ultimately de- signedtobeappliedtoreal-worldcode,wealsoneedtoen- surethatourtransformationsleadtocodesnippetsthatcould occurintherealworld,ori.e.,leadtonaturalcode.Wemea- suredthenaturalnessofourtransformationsusingthemethod introducedbyHindleetal.[19](implementedasa2-gram markov model) and present the results in Figure 8. Using themethodintroducedbyHindleetal.,wecancomputethe crossentropyofagivencodesnippet,whichrepresentshow surprisingorunnaturalthecodesnippetisrelativetothecode Figure8:Naturalnessofthesemanticpreservingtransforma- snippets observedin the training dataset(fora detailedex- tions,thatweusedinourexperiments.Lowercrossentropy planationconsulttheworkofHindleetal.[19]).Usingthis meanshighernaturalness.Alltransformationsexceptt (iden- 1 approach,wecomputedthecrossentropyforallcodesnippets tifierrenaming)leadtolowerorequalcrossentropythanno intheCodeXGLUEtestingdataset(darkgrayboxplot),and transformation(None). fortransformedversionsoftheCodeXGLUEtestingdataset (lightgrayboxplots).Thehorizontalblacklinerepresentsthe average cross entropy for all code snippets in the untrans- and Illia Polosukhin. Attention is all you need. In formedCodeXGLUEtestingdataset.Wecanobserve,thatfor I. Guyon, U. Von Luxburg, S. Bengio, H. Wallach, alltransformationsexceptt (identifierrenaming),thecross R. Fergus, S. Vishwanathan, and R. Garnett, editors, 1 entropyissimilarorlowerthanfortheuntransformeddataset. Advances in Neural Information Processing Systems, In other words, all transformations except t (identifier re- volume30.CurranAssociates,Inc.,2017. 1 naming)leadtocodesnippetsthataresimilarinnaturalness [38] ZhouYang,JiekeShi,JundaHe,andDavidLo. Natural comparedtothereal-worldcodeoftheCodeXGLUEtesting attackforpre-trainedmodelsofcode. InProceedings dataset. ofthe 44thInternationalConference on Software En- gineering,ICSE’22,page1482–1493,NewYork,NY, B ImpactofIndividualTransformations USA,2022.AssociationforComputingMachinery. Figure 9 shows the impact on accuracy caused [39] Noam Yefet,Uri Alon,and Eran Yahav. Adversarial by augmenting the testing data with a dif- examples for models of code. Proc. ACM Program. ferent transformation than the training data Lang.,4(OOPSLA),nov2020. [40] XueYing. Anoverviewofoverfittinganditssolutions. ( ai cm cp ua rac ct( yt [k L) LM: [= Tr j],( TN −1 e k1 ]) )∑ . Ttj ∈ hT ea mcc ou sr ta ic my p[M acL tfM ul[T trr aj n], sT foe] rm− a- JournalofPhysics:ConferenceSeries,1168(2):022022, tionsforeachLLMaremarkedbyredstars.Theresultsare feb2019. very similar to Figure 6, which is why we chose to omit Figure9fromthemainpaperandprovideitassupplementary [41] Huangzhao Zhang,Zhiyi Fu,Ge Li,Lei Ma,Zhehao material. Zhao,Hua’anYang,YizheSun,YangLiu,andZhiJin.
Towardsrobustnessofdeepprogramprocessingmod- C ModelArchitectureDetails els—detection, estimation, and enhancement. ACM Trans.Softw.Eng.Methodol.,31(3),apr2022. AllselectedML4VDtechniqueshappentobetoken-based [42] HuangzhaoZhang,ZhuoLi,GeLi,L.Ma,YangLiu,and large language models (LLMs),specialized for the task of ZhiJin. Generatingadversarialexamplesforholding vulnerabilitydetection.LLMsarebasedonthetransformer robustnessofsourcecodeprocessingmodels. InAAAI architecture,which is a neural network model architecture ConferenceonArtificialIntelligence,2020. forsequence-to-sequencetasksbasedontheattentionmecha- nism[37].Theattentionmechanismisessentiallyaweighted [43] YaqinZhou,ShangqingLiu,JingkaiSiow,XiaoningDu, dotproductthatallowsmodelstofocusonspecificpartsof andYangLiu. Devign:EffectiveVulnerabilityIdentifi- theinputdatathataremostrelevanttothetaskathand,im- cationbyLearningComprehensiveProgramSemantics provingtheirabilitytocapturedependenciesandcontext.In via Graph Neural Networks. Curran Associates Inc., atransformermodel,theattentionmechanismiscombined RedHook,NY,USA,2019. withparametrizedfeed-forwardlayersandrepeatedmultiple times,resultinginacomplexmulti-layernetwork.Adetailed 170.18 −0.16 −0.14 −0.12 −0.10 −0.08 −0.06 −0.04 −0.02 −0.00 t1 t2 t3 t4 t5 t6 t7 t8 t9 t10 t11 ) t(tcapmi k UniXcoder CoTexT GraphCodeBERT CodeBERT VulBERTa PLBart Figure 9: Impact on accuracy caused by augmenting the testing data with a different transformation than the training data ( Mim Lp ta ec ct h( nt k i) qu:= ea( rN e−1 m1) a∑ rkt ej ∈ dT ba ycc reu dra sc tay r[M s.LM[Tr j],Te] −accuracy[MLM[Tr j],Te k]).Themostimpactfultransformationsforeach 00000000000000000 ................. 55555666666666677 56789012345678901 UniXcoderCoTexTGraphCBCodeBERTVulBERTaPLBart ycaruccatestset TTTTrrrraaaaiiiinnnn::::TTTTrrrrkk,,,,TTTTeeeessttss::tt::TTTTeeeekkj6=k 0000 .... 6666 0369 0.57 0.54 0.51UniXcoderCoTexTGraphCBCodeBERTVulBERTaPLBart (a)Accuracy 1ftestset 000000000001 ............ 455667788990 505050505050 UniXcoderCoTexTGraphCBCodeBERTVulBERTaPLBart (b)F1-Score noisicerptestset 0000000000000011 ................ 3344556677889900 0505050505050505 UniXcoderCoTexTGraphCBCodeBERTVulBERTaPLBart (c)Precision llacertestset 0000000000000000001 ................... 1122334455667788990 0505050505050505050 UniXcoderCoTexTGraphCBCodeBERTVulBERTaPLBart (d)Recall RPFtestset 0000000000000000001 ................... 1122334455667788990 0505050505050505050 UniXcoderCoTexTGraphCBCodeBERTVulBERTaPLBart (e)FPR RNFtestset (f)FNR Figure10:AdditionalmetricsforRQ.2usingtheCodeXGLUE/Devigndataset.Theresultssupporttheconclusionsthatwe generatedbasedonthemainmetric(accuracy). 00000000000001 .............. 99999999999990 34455667788990 50505050505050 UniXcoderCoTexTGraphCBCodeBERTVulBERTaPLBart ycaruccatestset TTTTrrrraaaaiiiinnnn::::TTTTrrrrkk,,,,TTTTeeeessttss::tt::TTTTeeeekkj6=k 00000000000000 .............. 66677777888889 46802468024680 UniXcoderCoTexTGraphCBCodeBERTVulBERTaPLBart (a)Accuracy 1ftestset 00000001 ........ 67788990 50505050 UniXcoderCoTexTGraphCBCodeBERTVulBERTaPLBart (b)F1-Score noisicerptestset 000000000000 ............ 445566778899 050505050505 UniXcoderCoTexTGraphCBCodeBERTVulBERTaPLBart (c)Precision llacertestset 0000000000000000 ................ 0000000000111111 0123456789012345 UniXcoderCoTexTGraphCBCodeBERTVulBERTaPLBart (d)Recall RPFtestset 000000000000000000001 ..................... 001122334455667788990 050505050505050505050 UniXcoderCoTexTGraphCBCodeBERTVulBERTaPLBart (e)FPR RNFtestset (f)FNR Figure11:AdditionalmetricsforRQ.2usingtheVulDeePeckerdataset.Theresultssupporttheconclusionsthatwegenerated basedonthemainmetric(f1-score). descriptionofthetransformerarchitecturecanbefoundinthe bereversedbythemodel. originalpaper[37].Whilethebasearchitectureisthesamefor CodeBERT.CodeBERTusesapre-trainingsetupinwhich allofthesixtechniques,therearesomenotabledifferences naturallanguage(e.g.documentation)andcodearecombined inthepre-trainingsetup,size,orspecificpartsofthemodel toproduceamoresemanticallystablerepresentationofthe training: input. VulBERTa. VulBERTa leverages a custom tokenization GraphCodeBERT.GraphCodeBERTusesapre-training strategy,whichisbasedonthebytepairencodingalgorithm task,whereinadditiontonaturallanguageandthecode,a [33] combinedwitha setofpre-definedcode tokens (stan- graph-basedrepresentationofthedataflowofthefunctionis dard C/C++ keywords,punctuation,and library API calls) provided. to achieve better code encodings through maintaining the
syntacticalstructureofsourcecode. D AdditionalMetricsforRQ.2 CoTexT.CoTexTusesmulti-tasklearningforpre-training, whichmeans thatthe modelis trainedto perform multiple Figure10andFigure11showadditionalresultsforRQ.2us- code-relatedtasks(e.g.vulnerabilitydetection,codesumma- ingallofouravailablemetrics(accuracy,f1-score,precision, rization,andcodegeneration)inparallel.Themodelarchitec- recall,FPR,andFNR).Generally,theresultssupportthecon- turealsocontainssignificantlymoretrainableparametersthan clusionsthatwegeneratedbasedontherespectivepreferred theothertechniques(222Mparameters),becauseitcontains metricsonthetwodatasets(accuracyforCodeXGLUE/De- moremoremulti-headattentionlayers.CoTexTalsousesa vign and f1-score for VulDeePecker). While the observed differenttokenizerthantheothertechniques. patterns deviate forsome ofthe metrics (e.g. precision,re- UniXcoder. UniXcoder introduces a new pre-training call,FPR,orFNR),thesedeviationscanbeexplainedbythe setup,whichincludestokenizationoftheabstractsyntaxtrees relationshipsbetweenthem.Forexample,amodelcanhave (ASTs)ofthecode,andthreedifferent’trainingmodes’that a really high precision, but low recall. Similarly, a model leveragedifferentself-attentionmasks. canhavereallylowfalse-negative-rate,butthecorresponding PLBart. PLBart uses a special pre-training procedure false-positive-rateisreallyhigh.Accuracyandf1-scorepro- called’denoisingautoencoding’,whichisacombinationof videabettersummaryoftheperformance,whichiswhythey tokenmasking,tokendeletion,andtokeninfilling,thathasto areusedasthepreferredmetricsforthetwodatasets. 18
2307.02192 THE FORMAI DATASET: GENERATIVE AI IN SOFTWARE SECURITY THROUGH THE LENS OF FORMAL VERIFICATION ∗ NorbertTihanyi TamasBisztray RidhiJain TechnologyInnovationInstitute TheUniversityofOslo TechnologyInnovationInstitute AbuDhabi Oslo AbuDhabi UAE Norway UAE tihanyi.pgp@gmail.com tamasbi@ifi.uio.no ridhij@iiitd.ac.in MohamedAmineFerrag LucasC.Cordeiro VasileiosMavroeidis TechnologyInnovationInstitute UniversityofManchester TheUniversityofOslo AbuDhabi Manchester Oslo UAE UK Norway mohamed.amine.ferrag@gmail.com lucas.cordeiro@manchester.ac.uk vasileim@ifi.uio.no ThispaperhasbeenpublishedatPROMISE2023: Proceedingsofthe19thInternationalConferenceon PredictiveModelsandDataAnalyticsinSoftware. https://doi.org/10.1145/3617555.3617874 ABSTRACT ThispaperpresentstheFormAIdataset,alargecollectionof112000AI-generatedcompilable andindependentCprogramswithvulnerabilityclassification. Weintroduceadynamiczero-shot promptingtechniqueconstructedtospawnadiversesetofprogramsutilizingLargeLanguage Models(LLMs). ThedatasetisgeneratedbyGPT-3.5-turboandcomprisesprogramswithvarying levelsofcomplexity. Someprogramshandlecomplicatedtaskslikenetworkmanagement,table games,orencryption,whileothersdealwithsimplertaskslikestringmanipulation. Everyprogram islabeledwiththevulnerabilitiesfoundwithinthesourcecode,indicatingthetype,linenumber, andvulnerablefunctionname. Thisisaccomplishedbyemployingaformalverificationmethodus- ingtheEfficientSMT-basedBoundedModelChecker(ESBMC),whichexploitsmodelchecking, abstractinterpretation,constraintprogramming,andsatisfiabilitymodulotheories,toreasonover safety/securitypropertiesinprograms. Thisapproachdefinitivelydetectsvulnerabilitiesandoffers aformalmodelknownasacounterexample,thuseliminatingthepossibilityofgeneratingfalse positivereports. Thispropertyofthedatasetmakesitsuitableforevaluatingtheeffectivenessof variousstaticanddynamicanalysistools. Furthermore,wehaveassociatedtheidentifiedvulnera- bilitieswithrelevantCommonWeaknessEnumeration(CWE)numbers. Wemakethesourcecode availableforthe112,000programs,accompaniedbyacomprehensivelistdetailingthevulnerabil- itiesdetectedineachprogram,makingthedatasetidealfortrainingLLMsandmachinelearning algorithms. Keywords Dataset·VulnerabilityClassification·LargeLanguageModels·FormalVerification. ∗Citation:https://doi.org/10.1145/3617555.3617874 4202 raM 82 ]BD.sc[ 3v29120.7032:viXraTheFormAIDataset 1 Introduction TheadventofLargeLanguageModels(LLMs)isrevolutionizingthefieldofcomputerscience,heavilyimpact- ingsoftwaredevelopmentandprogrammingasdevelopersandcomputerscientistsenthusiasticallyuseAItools forcodecompletion,generation,translation,anddocumentation[Buietal.(2023),Rossetal.(2023)]. Researchre- latedtoprogramsynthesisusingGenerativePre-trainedTransformers(GPT)[Chavezetal.(2023)]isgainingsignif- icanttraction,whereinitialstudiesindicatethattheGPTmodelscangeneratesyntacticallycorrectyetvulnerable code[Maetal.(2023a),Charalambousetal.(2023)]. ArecentstudyconductedatStanfordUniversitysuggeststhat softwareengineersassistedbyOpenAI’scodex-davinci-002modelduringdevelopmentwereatahigherriskofin- troducingsecurityflawsintotheircode[Perryetal.(2022)]. AstheusageofAI-basedtoolsforcodegenerationcon- tinuestoexpand,understandingtheirpotentialtointroducesoftwarevulnerabilitiesbecomesincreasinglyimportant. ConsideringthatGPTmodelsaretrainedonfreelyavailabledatafromtheinternet,whichcanincludevulnerable code,AItoolscanpotentiallyrecreatethesamepatternsthatfacilitatedthosevulnerabilities. OurprimaryobjectiveistoexplorehowproficientlyLLMscanproducesecurecodefordifferentcodingobjectives withoutrequiringsubsequentadjustmentsorhumanintervention. Additionally,weaimtouncoverthemostfrequent vulnerabilitiesthatLLMstendtointroduceinthecodetheygenerate,identifyingcommonpatternsinrealisticexam- plestocomprehendtheirbehaviorbetter. Thisbringsforwardthefollowingresearchquestions: • RQ1: HowlikelyispurelyLLM-generatedcodetocontainvulnerabilitiesonthefirstoutputwhenusing simplezero-shottext-basedprompts? • RQ2: WhatareLLMs’mosttypicalcodingerrors? Figure1: AI-drivendatasetgenerationandvulnerabilitylabelingframework. Arandomtypeandstylecombination isselectedforeachprompt,instructingtheLLMmoduletogenerateaCprogram. Thecompilableprogramsarefed totheBMCmodule,whichperformstheclassificationbasedonformalverificationtechniques. Inparticular,weexploretheseresearchquestionsinthecontextofGPT-3.5generatingCprograms. GPT-3.5is themostwidelyusedLLMavailabletosoftwaredeveloperswithafreewebinterface[Somoye(2023)]. Moreover, Cisoneofthemostpopularlow-levelprogramminglanguagesforembeddedsystems,criticalsecuritysystems, andInternetofThings(IoT)applications[Avila(2022)]. Forourpurposes,simplyshowingthroughahandfulof empiricalexamplesthatLLMscanproducevulnerablecodeisnotgratifyingandhasbeendemonstratedbeforefor variousprogramminglanguages[Charalambousetal.(2023),Perryetal.(2022),Umawing(2023)].
Twothingsarerequiredtoaddresstheoutlinedresearchquestionsaccurately. First,alargedatabasecontainingadi- versesetofCprograms. Second,weneedtogaininsightintothevarietyanddistributionofdifferentvulnerabilities. Atthesametime,wemustdeterminewhetheravulnerabilityispresentinthecode. Ifwelabelthecodeasvulner- able,itshouldnotbeafalsepositive. Thelatterisessentialwhencreatingdatasetsformachinelearningpurposes [Picardetal.(2020),Hutchinsonetal.(2021)]. Onthatnote,deeplearningapplicationsalsoneedlargedatasetsof vulnerablesourcecodefortrainingpurposes[Chenetal.(2023)]. Here,wedevelopedasimpleyeteffectivepromptingmethodtoobtainadiversedataset,proddingtheLLMto tackleamixedbagoftasks. Thisresultedinacollectionof112,000Cprogramsaddressingvariousprogram- 2TheFormAIDataset mingscenarios. Manuallylabelingtheentiredatasetisunfeasibleforsuchalargecorpusofdata. Therefore,we usetheEfficientSMT-basedBoundedModelChecker(ESBMC)[Gadelhaetal.(2018)],whichcanformallyfal- sifytheexistenceofcertainvulnerabilities. Thisstate-of-the-arttoolshowcasedexceptionalperformanceinthe SV-COMP2023[Beyer(2023)]competitionbyefficientlysolvingmanyverificationtaskswithinalimitedtime- frame[Gadelhaetal.(2018)]. Althoughitcanonlydetectformallyverifiableerrorsthroughsymbolicexecution,it doesnotproducefalsepositives. Onelimitationofthismethodisthatduetoitsresource-intensivenature,itcanonlydetectvulnerabilitieswithina predefinedsearchdepthboundedbytheavailablecomputationalcapacity. Supposethecomplexityofthecodedoes notallowthemoduletocheckallthenodesinthecontrol-flowgraph(CFG)[Ahoetal.(2006)]exhaustivelyunder areasonabletime. Inthatcase,wecanonlyknowthepresenceorabsenceofvulnerabilitieswithinthepredefined bound. Ifwedonotfindanyvulnerabilitiesuptothatdepth,thecodemightstillcontainsome. Ontheupside,which iswhyweusethismethod,wecandefinitivelyconfirmthepresenceofthedetectedvulnerabilitiesuptoabound,as wecanprovidea“counterexample”asaformalmodel. Suchdatabasescanbeusefulforvariousresearchactivities, especiallyinmachinelearning,whichweremarkoninourdiscussion. Figure1illustratesthemethodologyemployedinthispaper. Initially,weprovideinstructionstoGPT-3.5toconstruct aCprogramforvarioustasks. ThisstepwillbeelaboratedthoroughlyinSection5. Next,eachoutputisfedtothe GNUC2compilertocheckiftheprogramiscompilable. ThecompilablesourcecodeconstitutestheFormAIdataset. TheseprogramsareusedasinputfortheESMBCmodulewhichperformsthelabelingprocess. Thelabeleddatais savedina.csvfile,whichincludesdetailssuchasthenameofthevulnerablefile,thespecificlineofcodecontaining thevulnerability,thefunctionname,andthetypeofvulnerability. Tosummarize,thispaperholdsthefollowingoriginalcontributions: • WepresentFormAI,thefirstAI-generatedlarge-scaledatasetconsistingof112000independentcompi- lableCprogramsthatperformvariouscomputingtasks. Eachoftheseprogramsislabeledbasedonthe vulnerabilitiesidentifiedbyformalverification,namely,theESBMCmodule; • Acomprehensiveanalysisontheidentificationandprevalenceofvulnerabilitiesaffectingthesafetyand securitypropertiesofCprogramsgeneratedbyGTP-3.5-turbo. TheESBMCmoduleprovidesthedetection andcategorizationofvulnerabilities. Weconnecttheidentifiedvulnerabilityclasseswithcorresponding CommonWeaknessEnumeration(CWE)numbers. Theremainingsectionsarestructuredasfollows: Section2discussesthemotivationforourwork. Section3 overviewstherelatedliterature. Section4presentsashortintroductiontoformalverificationandtheESBMCmod- ule. Section5outlinestheapproachweemployedtocreateandcategorizeourdataset,whereSection6providesan in-depthevaluationofourfindings. Section7overviewslimitationsrelatedtoourwork. Finally,Section8concludes thepaperwithanoutlookonpossiblefutureresearchdirections. 2 Motivation Throughoutsoftwaredevelopment,itisparamounttoguaranteethecreatedprograms’correctness,safety,andse- curity. Functionallycorrectcodeproducestheexpectedoutputforeachgiveninput. Safetyaimstoproducefailure tolerantandfail-safecode,resistantagainstaccidentalorunexpectedinputsthatresultincorrectbutundesiredout- puts,whichmaycausesystemfailureorerroneoushumandecisions[reyVoas(1996)]. Finally,softwaresecurity embodiesrobustnessagainstexternalhazardsanddeliberateattacks. Ourobjectiveinthispaperistoexaminethe safetyandsecuritypropertiesofAI-generatedsourcecode. Theterm“generatedcode”signifiescomputercodecreatedbyanLLM,capableofusingmultipleformsofdataas input. Textualpromptsaresegmentedintoindividualunitsknownastokens. LLMsgeneratetheirresponseonetoken atatime,whereapre-definedtokencaplimitstheoutputlength. Duetothis,asoftoday,LLMscannotbeusedto spawnlargeapplicationsonasingleprompt. ThemainwaydevelopersutilizeAItoolsisbycreatingsmallprograms orcodesnippetsincorporatedintotheirprojects. TheStanfordstudymentionedearlier[Perryetal.(2022)]captured thisimportantaspect. Someassignmentsgiventostudentswere,forexample,creating: • twofunctionsinPythonwhereoneencryptsandtheotherdecryptsagivenstringusingagivensymmetric key;
• afunctioninPythonthatsignsagivenmessageusingagivenECDSAsigningkey. 2https://gcc.gnu.org 3TheFormAIDataset WeaimtoprompttheLLMtoproducecodefortaskswithsimilarcomplexitylevels. Furthermore,fortheESBMC module,itisbeneficialtohavesmallerindependentprograms. Theseallowthemoduletoexecutetheverification processpiecebypiece,adheringtoasetboundary,thusmakingtheprocessmanageableandmoreefficient. Ifthe programswereheavilyinterdependent,accuratelyestimatingthetimerequiredforthemoduletofinishtheverifi- cationprocesswouldbehardlyfeasible. ThemainareaofinterestinLLM-basedcodegenerationhasbeenrelated tocorrectness. DatasetssuchasHumanEvalprovideprogrammingchallengestoassesstheperformanceofmodels. Forexample,GPT-4achievesa67%successrateinsolvingtaskscomparedto48.1%forGPT-3.5[OpenAI(2023)]. MeasuringcorrectnessisnotourgoalwiththeFormAIdataset. Forexample,ifthepromptsays“Createaboard gameusingtheCprogramminglanguageinanartisticstyle”,correctnesswouldbedifficulttoverify,especiallyfor alargedataset. Theonlyrequirementisthattheprogramshouldbesyntacticallycorrectanditmustbepossibleto compileit. Torestateourresearchobjective,weaimtouncovertheproportionandtypeoffrequentcodingerrorsin CsourcecodegeneratedbyGPT-3.5whenpromptedtoperformsimpletasksusingnaturallanguage. Thefollowing real-lifeexampledemonstratesandunderscoresthenecessityofthisresearchquestion. ImagineasituationwhereaprogrammersubmitsthefollowingprompttoGPT-3.5: “ProvideasmallCprogramthat addstwonumberstogether.”. Figure2: Insecurecodegeneratedbygpt-3.5-turbo. Theprogramreadstwonumbers,wheretheadditioncanresult inavalueoutsideoftherange“int”canrepresent,whichmayleadtointegeroverflow. TheresultingcodeshowninFigure2isvulnerable,asitcontainsanintegeroverflowonthescanf()function. In 32-bitcomputingarchitectures,integersarecommonlystoredas4bytes(32bits),whichresultsinamaximum integervalueof2147483647,equivalentto231−1. Ifoneattemptstoadd2147483647+1usingthissmallprogram, theresultwillbeincorrectduetointegeroverflow. Theincorrectresultwillbe-2147483648insteadoftheexpected 2147483648. Theadditionexceedsthemaximumrepresentablevalueforasigned32-bitinteger231−1,causingthe integertowraparoundandbecomenegativeduetothetwo’scomplementrepresentation. EvenwhenGPT-3.5isrequestedtowriteasecureversionofthiscode–withoutspecifyingthevulnerability–itonly attemptstoverifyagainstenteringnon-integerinputsbyaddingthefollowingcodesnippet: if (scanf("%d", &num1) != 1) {...}. Clearly,aftersanitizingtheinput,theissueofintegeroverflowisstillpresent. When promptedtocreateaCprogramthataddstwonumbers,itappearsthatbothGPT-3.5andGPT-4generatecodewith thisinsecurepattern. Whenaskedforasecureversion,bothmodelsperforminputsanitization. ByusingtheESBMC moduletoverifythisprogram,thevulnerabilityisimmediatelyfoundthroughacounterexample,andthefollowing messageiscreatedasshowninFigure3. In[Charalambousetal.(2023)],theauthorsdemonstratedthatGPT-3.5couldefficientlyfixerrorsiftheoutputofthe ESBMCmoduleisprovided. Givenonlygeneralinstructionas“writesecurecode”,oraskedtofindvulnerabilities, GPT-3.5strugglestopinpointthespecificvulnerabilityaccurately,letaloneifmultiplearepresent. Whileadvanced modelsmightperformbetterforcertainvulnerabilities,thisprovidesnoguaranteethatallcodingmistakeswillbe found[Pearceetal.(2022)]. Themainchallengeistheinitialdetectionwithoutanypriorhintorindicator. Doing thisefficientlyforalargecorpusofCcodewhileavoidingfalsepositivesandfalsenegativesisstillchallengingfor LLMs[Pearceetal.(2022)]. Basedonthisobservation,wewanttocreateanextensiveanddiversedatasetofproperly labeledLLM-generatedCprograms. SuchadatasetcanreproducecodingerrorsoftencreatedbyLLMsandserveas avaluableresourceandstartingpointintrainingLLMsforsecurecodegeneration. 4TheFormAIDataset Figure3: ThecounterexampleprovidedforFigure2. usingESBMCversion7.2.0. Notethisisonlypartofthe outputspecificallyforintegeroverflow,whichwewantedtobringforwardforthisexample. 3 RelatedWork Thissectionoverviewsautomatedvulnerabilitydetectionandnotableexistingdatasetscontainingvulnerablecode samplesforvarioustrainingandbenchmarkingpurposes. 3.1 ChatGPTinSoftwareEngineering In[Maetal.(2023b)]Meetal. assessedthecapabilitiesandlimitationsofChatGPTforsoftwareengineering(SE), specificallyinunderstandingcodesyntaxandsemanticstructureslikeabstractsyntaxtrees(AST),controlflow graphs(CFG),andcallgraphs(CG).ChatGPTexhibitsexcellentsyntaxunderstanding,indicatingitspotentialfor staticcodeanalysis. Theyhighlightedthatthemodelalsohallucinateswheninterpretingcodesemantics,creat- ingnon-existentfacts. ThisimpliesaneedformethodstoverifyChatGPT’soutputstoenhanceitsreliability. This studyprovidesinitialinsightsintowhythecodesgeneratedbylanguagemodelsaresyntacticallycorrectbutpo- tentiallyvulnerable. FrameworksandtechniquesforturningpromptsintoexecutablecodeforSoftwareEngineer- ingarerapidlyemerging,butthemainfocusisoftenfunctionalcorrectnessomittingimportantsecurityaspects
[Xingetal.(2023),Whiteetal.(2023),Yaoetal.(2023),Weietal.(2023)]. In[Liuetal.(2023)],Liuetal. questions thevalidityofexistingcodeevaluationdatasets,suggestingtheyinadequatelyassessthecorrectnessofgenerated code. In[Khouryetal.(2023)]theauthorsgenerated21smallprogramsinfivedifferentlanguages: C,C++,Python, HTMLandJava. CombiningmanualverificationwithChatGPT-basedvulnerabilitydetection,thestudyfoundthat only5ofthe21generatedprogramswereinitiallysecure. ArecentstudybyMicrosoft[Imanietal.(2023)]found thatGPTmodelsencounterdifficultieswhenattemptingtoaccuratelysolvearithmeticoperations. Thisalignswith thefindingswepresentedinthemotivationSection. Inasmallstudyinvolving50students[Sandovaletal.(2023)],theauthorsfoundthatstudentsusinganAIcodingas- sistantintroducedvulnerabilitiesatthesamerateastheirunassistedcounterparts. Still,notably,theexperimentwas limitedbyfocusingonlyonasingleprogrammingscenario. Contrarytothepreviousstudyin[Pearceetal.(2021)] Pearceetal. concludethatthecontrolgroup,whichutilizedGitHub’sCopilot,incorporatedmorevulnerabilities intotheircode. Insteadofasinglecodingscenariolikein[Sandovaletal.(2023)],theauthorsexpandedthestudy’s comprehensivenessbychoosingadiversesetofcodingtaskspertinenttohigh-riskcybersecurityvulnerabilities,such asthosefeaturedinMITRE’s“Top25”CommonWeaknessEnumeration(CWE)list. Thestudyhighlightsanim- portantlesson: toaccuratelymeasuretheroleofAItoolsincodegenerationorcompletion,itisessentialtochoose codingscenariosmirroringadiversesetofrelevantreal-worldsettings,therebyfacilitatingtheoccurrenceofvarious vulnerabilities. Thisnecessitatesthecreationofcodebasesreplicatingawiderangeofsettings,whichisoneofthe primarygoalstheFormAIdatasetstrivestoachieve. ThesestudiesindicatethatAItools,andinparticularChatGPT, asoftoday,canproducecodecontainingvulnerabilities. Inarecentstudy,Shumailovetal. highlightedaphenomenonknownas“modelcollapse”[Shumailovetal.(2023)]. TheirresearchdemonstratedthatintegratingcontentgeneratedbyLLMscanleadtopersistentflawsinsubsequent 5TheFormAIDataset modelswhenusingthegenerateddatafortraining. Thishintsthattrainingmachinelearningmodelsonlyonpurely AI-generatedcontentisinsufficientifoneaimstopreparethesemodelsfordetectingvulnerabilitiesinhuman- generatedcode. Thisisessentiallyduetousingadatasetduringthetrainingphase,whichisnotdiverseenough andmisrepresentsedgecases. Weuseourdynamiczero-shotpromptingmethodtocircumventthehighlightedis- suetoensurediversity. Moreover,ourresearchgoalistofindandhighlightwhatcodingmistakesAImodelscan create,whichrequiresathoroughinvestigationofAI-generatedcode. Ontheotherhand,AImodelsthemselves weretrainedonhuman-generatedcontent;thus,thevulnerabilitiesproducedhaverootsinincorrectcodecreatedby humans. Yet,asdiscussedinthenextsection,existingdatasetsnotoriouslyincludesyntheticdata(differentfrom AI-generated),whichcanbeusefulforbenchmarkingvulnerabilityscanners,buthasquestionablevaluefortraining purposes[Chenetal.(2023)]. Table1: Comparisonsofvariousdatasetsbasedontheirlabelingclassifications. Only #Code #Vuln. Multiple Compiles/ Vuln. #AvgLine Labelling Dataset Source C-code Snippets Snippets Vulns/Snippet Granularity Labelling ofCode Method Big-Vul ✘ Real-World 188,636 100% ✘ ✘/Function CVE/CVW 30 PATCH Draper ✘ Synthetic+Real-World 1,274,366 5.62% ✔ ✘/Function CWE 29 STAT SARD ✘ Synthetic+Real-World 100,883 100% ✘ ✔/Program CWE 114 BDV/STAT/MAN Juliet ✘ Synthetic 106,075 100% ✘ ✔/Program CWE 125 BDV Devign ✘ Real-World 27,544 46.05% ✘ ✘/Function CVE 112 ML REVEAL ✘ Real-World 22,734 9.85% ✘ ✘/Function CVE 32 PATCH DiverseVul ✘ Real-World 379,241 7.02% ✘ ✘/Function CWE 37 PATCH FormAI ✔ AI-generated 112,000 51.24% ✔ ✔/Program CWE 79 ESBMC Legend: PATCH:GitHubCommitsPatchingaVuln.Man:ManualVerification,Stat:StaticAnalyser,ML:MachineLearningBased,BDV:Bydesignvulnerable 3.2 ExistingdatabasesforVulnerableCcode WeshowhowtheFormAIdatasetcomparestosevenwidelystudieddatasetscontainingvulnerablecode. Theexamineddatasetsare: Big-Vul[Fanetal.(2020)],Draper[Russelletal.(2018),KimandRussell(2018)], SARD[Black(2018)],Juliet[JrandBlack(2012)],Devign[Zhouetal.(2019b),Zhouetal.(2019a)],REVEAL [Chakrabortyetal.(2022)],andDiverseVul[Chenetal.(2023)]. Table1presentsacomprehensivecompari- sonofthedatasetsacrossvariousmetrics. Someofthisdataisderivedfromreviewpapersthatevaluatethese datasets[Jainetal.(2023),Chenetal.(2023)]. Big-Vul,Draper,Devign,REVEAL,andDiverseVulcomprisevulnerablereal-worldfunctionsfromopen-source applications. Thesefivedatasetsdonotincludealldependenciesofthesamples;therefore,theyarenon-compilable. SARDandJulietcontainsynthetic,compilableprograms. Intheirgeneralcomposition,theprogramscontaina vulnerablefunction,itsequivalentpatchedfunction,andamainfunctioncallingthesefunctions. Alldatasetsindicate
whetheracodeisvulnerable. Thementioneddatasetsusethefollowingvulnerabilitylabelingmethodologies: • PATCH:FunctionsbeforereceivingGitHubcommitsfordetectedvulnerabilitiesaretreatedasvulnerable. • MAN:Manuallabeling • STAT:Staticanalyzers • ML:Machinelearning-basedtechniques • BDV:Bydesignvulnerable Inthelattercase,novulnerabilityverificationtoolisused. Notethatthesizeofthedatasetscanbemisleading,as manyofthedatasetscontainsamplesfromotherlanguages. Forexample,SARDcontainsC,C++,Java,PHP,and C#. Moreover,newlyreleasedsetsoftenincorporatepreviousdatasetsorscrapethesameGitHubrepositories,mak- ingthemredundant. Forexample,DrepercontainsCandC++codefromtheSATEIVJulietTestSuite,DebianLinuxdistribution,and publicGitrepositories. Sincetheopen-sourcefunctionsfromDebianandGitHubwerenotlabeled,theauthors usedasuiteofstaticanalysistools: Clang,Cppcheck,andFlawfinder[Russelletal.(2018)]. However,thepaper doesnotmentionifvulnerabilitiesweremanuallyverifiedorifanyconfirmationhasbeenperformedtorootout falsepositives. In[Chenetal.(2023)],ontopofcreatingDiverseVul,Chenetal. mergedalldatasetsthatwerebased 6TheFormAIDataset onGitHubcommitsandremovedduplicates,thusmakingthemostcomprehensivecollectionofGitHubcommits containingvulnerableCandC++code. 3.3 VulnerabilityScanningandRepair Softwareverificationiscriticaltoensuringcorrectness,safety,andsecurity. Theprimarytechniquesaremanual verification,staticanalysis,anddynamicanalysis,whereafourthemergingtechniqueismachinelearning-basedde- tection[Cordeiroetal.(2012),D’Silvaetal.(2008),WallaceandFujii(1989),Maetal.(2023b)]. Manualverification techniquessuchascodereviewormanualtestingrelyonhumaneffortandarenotscalable. Staticanalysiscantest thesourcecodewithoutrunningit,usingtechniquessuchasstaticsymbolicexecution,dataflowanalysis,control flowanalysis,andstylechecking. Ontheotherhand,dynamicanalysisaimsatobservingsoftwarebehaviorwhile runningthecode. Itinvolvesfuzzing,automatedtesting,run-timeverification,andprofiling. Thefourthtechnique isapromisingfieldwhereLLMscanbeusefulinawiderangeoftasks,suchascodereviewandbugdetection, vulnerabilitydetection,testcasegeneration,anddocumentationgeneration;however,asoftoday,eachareahascer- tainlimitations. Researchrelatedtotheapplicationofverificationtoolsinanalyzingcodespecificallygeneratedby LLMsremainsratherlimited. Anearlierworkfrom2022examinedtheabilityofvariousLLMstofixvulnerabilities, wherethemodelsshowedpromisingresults,especiallywhencombined. Still,theauthorsnotedthatsuchtoolsare notreadytobeusedinaprogramrepairframework,wherefurtherresearchisnecessarytoincorporatebuglocaliza- tion. Theyhighlightedchallengesinthetool’sabilitytogeneratefunctionallycorrectcode[Pearceetal.(2022)]. 4 FormalVerification Thissectionpresentsthecrucialfoundationalknowledgerequiredtounderstandthetechnologyemployedinthis research,specificallyBoundedModelChecking(BMC).Anintuitivequestionarises: CouldBMCpotentiallyintro- ducefalsepositivesintoourdataset? Theanswerisno,andunderstandingwhyiscriticaltoourwork. Toclarifythis theory,wewillexplaincounterexamplesandthoroughlydiscussthemathbehindboundedmodelchecking. BoundedModelChecking(BMC)isatechniqueusedinformalverificationtocheckthecorrectnessofasystem withinafinitenumberofsteps. Itinvolvesmodelingthesystemasafinitestatetransitionsystemandsystemati- callyexploringitsstatespaceuptoaspecifiedboundordepth. ThelatestBMCmodulescanhandlevariouspro- gramminglanguages[SadowskiandYi(2014),Gadelhaetal.(2019),Whiteetal.(2016),ZhaoandHuang(2018), Gadelhaetal.(2023)]. Thistechniquefirsttakestheprogramcode,fromwhichacontrol-flowgraph(CFG)iscreated [Ahoetal.(2006)]. InCFG,eachnodesignifiesadeterministicornon-deterministicassignmentoraconditional statement. Eachedgerepresentsapotentialshiftintheprogram’scontrolposition. Essentially,everynodeisablock representinga“setofinstructionswithasingularentryandexitpoint”. Edgesindicatepossiblepathstootherblocks towhichtheprogram’scontrollocationcantransition. TheCFGisfirsttransformedintoStaticSingleAssignment (SSA)andconvertedintoaStateTransitionSystem(STS).ThiscanbeinterpretedbyaSatisfiabilityModuloTheo- ries(SMT)solver. Thissolvercandetermineifasetofvariableassignmentsmakesagivenformulatrue,i.e.,thisfor- mulaisdesignedtobesatisfiableifandonlyifthere’sacounterexampletothepropertieswithinaspecifiedboundk. Ifthereisnoerrorstateandtheformulaisunsatisfiableuptotheboundk,thereisnosoftwarevulnerabilitywithin thatbound. Ifthesolverreachesterminationwithinabound≤k,wecandefinitivelyprovetheabsenceofsoftware errors. Tobemoreprecise,letagivenprogramP underverificationbeafinitestatetransitionsystem,denotedbya tripleST = (S,R,I),whereS representsthesetofstates,R ⊆ S × S representsthesetoftransitionsand (s ,···,s ) ∈ I ⊆ S representsthesetofinitialstates. Inastatetransitionsystem,astatedenotedass ∈ S n m consistsoftheprogramcountervalue,referredtoaspc,andthevaluesofallprogramvariables. Theinitialstate denotedass ,assignstheinitialprogramlocationwithintheControlFlowGraph(CFG)topc. Eachtransition 1
T = (s ,s ) ∈ Rbetweentwostates,s ands ,isidentifiedwithalogicalformulaT(s ,s ). Thisformula i i+1 i i+1 i i+1 capturestheconstraintsgoverningthevaluesoftheprogramcounterandprogramvariablesrelevanttothetransition. WithinBMC(BoundedModelChecking),propertiesunderverificationaredefinedasfollows: ϕ(s)representsa logicalformulathatencodesstatessatisfyingasafety/securityproperty. Incontrast,ψ(s)representsalogicalformula thatencodesstatessatisfyingthecompletenessthreshold,indicatingstatescorrespondingtoprogramtermination. ψ(s),containsunwindingssothatitdoesnotexceedthemaximumnumberofloopiterationsintheprogram. Itis worthnotingthat,inournotation,termination,anderroraremutuallyexclusive: ϕ(s) ∧ ψ(s)isbyconstruction unsatisfiable. IfT(s ,s )∨ϕ(s)isunsatisfiable,statesisconsideredadeadlockstate. Theboundedmodelchecking i i+1 problem,denotedbyBMC isformulatedbyconstructingalogicalformula,andthesatisfiabilityofthisformula Φ determineswhetherP hasacounterexampleoflengthkorless. Specifically,theformulaissatisfiableifandonlyif suchacounterexampleexistswithinthegivenlengthconstraint,i.e.: 7TheFormAIDataset k−1 k (cid:94) (cid:95) BMC (k)=I(s )∧ T(s ,s )∧ ¬ϕ(s ). (1) Φ 1 i i+1 i i=1 i=1 Inthiscontext,I denotesthesetofinitialstatesofST,andT(s ,s )representsthetransitionrelationofST, i i+1 betweentimestepsiandi+1. Hence,thelogicalformulaI(s )∧(cid:86)k−1T(s ,s )representstheexecutionsofST 1 i=1 i i+1 withalengthofkandBMC (k)canbesatisfiedifandonlyifforsomei≤kthereexistsareachablestateattime Φ stepiinwhichϕisviolated. IfBMC (k)issatisfiable,itimpliesthatϕisviolated,andanSMTsolverprovidesa Φ satisfyingassignmentfromwhichwecanextractthevaluesoftheprogramvariablestoconstructacounterexample. Acounterexample,ortrace,foraviolatedpropertyϕ,isdefinedasafinitesequenceofstatess ,...,s ,where 1 k s ,...,s ∈ S andT(s ,s )holdsfor0 ≤ i < k. Ifequation(1)isunsatisfiable,wecanconcludethatnoerror 1 k i i+1 stateisreachablewithinkstepsorless. Thisvaluableinformationleadsustoconcludethatnosoftwarevulnerability existsintheprogramwithinthespecifiedboundofk. Withthismethodology,weaimtoclassifyeverygeneratedC programaseithervulnerableornot,withinagivenboundk. Bysearchingforcounterexampleswithinthisbound,we canestablish,basedonmathematicalproofs,whetheracounterexampleexistsandwhetherourprogramP containsa securityvulnerability. Thisapproachallowsustoidentifysecurityissuessuchasbufferoverflowsoraccess-bound violations. 4.1 TheESBMCmodule ThisworkusestheEfficientSMT-basedContext-BoundedModelChecker(ESBMC)[Gadelhaetal.(2018)]asour chosenBMCmodule. ESBMCisamature,permissivelylicensedopen-sourcecontext-boundedmodelcheckerfor verifyingsingle-andmultithreadedC/C++,Kotlin,andSolidityprograms. Itcanautomaticallyverifybothprede- finedsafetypropertiesanduser-definedprogramassertions. Thesafetypropertiesincludeout-of-boundsarrayaccess, illegalpointerdereferences(e.g.,dereferencingnull,performinganout-of-boundsdereference,double-freeofmal- locedmemory,misalignedmemoryaccess),integeroverflows,undefinedbehavioronshiftoperations,floating-point forNaN,dividebyzero,andmemoryleaks. Inaddition,ESBMCsupportstheClangcompilerasitsC/C++frontend, theSootframeworkviaJimpleasitsJava/Kotlinfrontend,IEEEfloating-pointarithmeticforvariousSMTsolvers, implementstheSoliditygrammarproductionrulesasitsSolidityfrontend. Inaddition,ESBMCimplementsstate-of- the-artincrementalBMCandk-inductionproof-rulealgorithmsbasedonSatisfiabilityModuloTheories(SMT)and ConstraintProgramming(CP)solvers. 5 TheFormAIdataset TheFormAIdatasetconsistsoftwomaincomponents: AI-generatedCprogramsandtheirvulnerabilitylabeling. Inthedatagenerationphase,wecreateatotalof112,000samples. Intheclassificationphase,weutilizeESBMC toidentifyvulnerabilitiesinthesamples. Toensurethereproducibilityofthedatasetcreationprocess,theexact methodologyisthoroughlyexplainedinthissection. 5.1 Codegeneration TogeneratethedatasetofsmallCprograms,weutilizedtheGPT-3.5-turbomodel[OpenAI(2022)]. WeemployGPT- 3.5togenerateCcodeinsteadofGPT-4asthelattercanbeupto60timesmoreexpensivethantheformermodel. Duringthecreationprocess,specialattentionwasgiventoensuringthediversityoftheFormAIdataset,which contains112,000compilableCsamples. RequestingthemodeltogenerateauniqueCprogramfrequentlyyields similaroutcomes,suchasaddingtwonumbersorperformingbasicstringmanipulation,whichdoesnotalignwith ourobjectives. Ourfocusliesinsystematicallygeneratingacomprehensiveandvariedcollectionofsmallprograms thatemulatesthecodecreationprocessundertakenbydevelopers. Therefore,weneedamethodologytocircumvent thegenerationofelementaryCprograms. Toaddressthisissue,wehavedevelopedapromptingmethodconsisting oftwodistinctparts: adynamicpartandastaticpart. Thestaticcomponentremainsconsistentandunchanged,while thedynamicportionofthepromptundergoescontinuousvariation. Anexampleofhowasinglepromptlooksis shownunderListing??.
Thedynamicpartoftheprompt,highlightedas[Type]and[Style],representdistinctcategorieswithintheprompt, eachencompassingdifferentelements. IneachAPIcall,adifferenttypeisselectedfromasetof200elementsfor the“Type”category. Thiscategorycontainsdifferenttopics,suchasWi-FiSignalStrengthAnalyzer,QRcode reader,ImageSteganography,PixelArtGenerator,ScientificCalculatorImplementation,etc. Inasimilarfashion, 8TheFormAIDataset Figure4: Dynamiccodegenerationprompt duringeachquery,acodingstyleischosenfromasetof100elementswithinthe“Style”category. Thishelpsmin- imizerepetition,asspecificcodingstylessuchas“excited”,“relaxed”,or“mathematical”arecombinedwitheach Typecategory. Byemployingthismethod,wecangenerate200×100=20,000distinctcombinations. This,together withthetemperatureparameterwhichregulatesthedegreeofrandomnessinthemodel’sresponses,canenhance diversityamongtheprogramscreated. TheconceptofpromptcreationcanbeseeninFigure5. Figure5: Dynamicpromptcreation. Decreasingthenumberofunsuccessfulqueriesisanimportantfactorfromanefficiencyperspective,astheprice forgpt-3.5-turbois0.002USD\1Ktokenatthetimeofwriting. Hence,refiningtheprompttoreducethenumber ofunsuccessfulqueriesholdssignificantimportance. Tominimizetheerrorwithinthegeneratedcode,wehave establishedfiveinstructionsineachspecificprompt: a. Minimum 50 lines: ThisencouragestheLLMtoavoidthegenerationofoverlysimplisticcodewithonly afewlines(whichoccasionallystillhappens); b. Be creative!:Thepurposeofthisinstructionistogenerateamorediversedataset; c. Do not say I am sorry:Theobjectiveofthisinstructionistoconsistentlygeneratecode,therebyavoid- ingresponsessuchas“AsanAImodel,Icannotgeneratecode”,andsimilarstatements. d. Make sure the program compiles:Thisinstructionencouragesthemodeltoincludeheaderfilesand createacompleteandcompilableprogram. e. Generate a code snippet that starts with “‘c: EnableeasyextractionoftheCcodefromthe response. OnceaCcodeisgenerated,theGNUCcompilerisemployedtoverifywhetherthecorrespondingcodeiscom- pilable. Duringtheexperiment,over90%ofthegeneratedcodewascompilable. Theprimaryreasonforhaving non-compilablecodewasduetotheabsenceofnecessaryheaders,suchasmath.h,ctype.h,orstdlib.h. During thecodegenerationprocess,weensurethattheFormAIdatasetexclusivelyconsistsofcompilablecode,whileex- cludinganyothercodethatdoesnotmeetthiscriterion. Codegenerationdoesnotrequirehighcomputationalpower, andforthistask,weutilizedastandardMacBookPro2017with16GBofRAM.Thegenerationof112,000code 9TheFormAIDataset sampleswascompletedwithin24hours. ByleveragingAPIrequests,weranthecreationprocessinparallelusinga singleAPIkey. Asofthetimeofwriting,thetotalcostforthecreationprocesswasapproximately200USD. 5.2 Experimentalsetupforclassification WerantheclassificationexperimentusinganAMDRyzenThreadripperPRO3995WXprocessorwith32CPU cores. Intheworst-casescenario,ifweallocate30secondsforverificationpersampleandutilizeall32threads concurrently,theentireverificationprocessonthismachinewouldtakeapproximately1.2days,calculatedas 112,000×30/3600/24/32. Forvulnerabilityclassification,wehaveselectedESBMCsincewithina10-30secondtime-limit,thisverifiersolves thehighestamountofverificationtasksaccordingtoSV-COMP20233. Therefore,weusethistoolwithaverification timeoutsetto30secondsoneachsample. esbmc filename.c --unwind 1 --overflow --multi-property --timeout 30 Althoughitwouldbepossibletocollectthevulnerabilitylabelsitfindsuptothatpoint,weonlykeepthelabels wheretheverifierfinisheswithin30seconds;otherwise,wejumptothenextprogram. 5.3 Vulnerabilityclassification LetusdenotethesetofallthegeneratedCsamplesbyΣ,suchthatΣ = {c ,c ,...,c },whereeachc repre- 1 2 112000 i sentsanindividualsample. ByanalyzingtheESBMCverificationoutput,wecanclassifyallthesamplesintothree distinctcategories: • VS ⊆Σ: thesetofsamplesforwhichverificationwassuccessful. • VU ⊆Σ: thesetofsamplesforwhichtheverificationstatusisunknown. • VF ⊆Σ: thesetofsamplesforwhichtheverificationstatusfailed. Thesecategoriesaremutuallyexclusive,meaningasinglesamplecannotbelongtomorethanonecategory. Clearly, VS ∩VU = VS ∩VF = VF ∩VU = ∅. Thecategorylabeledas“verificationunknown”(VU)encompassesall sampleswhereitwasnotpossibletodetermineacounterexampleusingESBMC.Thisistypicallyduetothelimited searchdepth,makingituncertainwhetheravulnerabilityexistsinthecode. ItisworthnotingthattheVU category issignificantlyinfluencedbytheruntimedurationandtheloopunwindingparameterusedduringESBMCexecu- tion. Forinstance,iftheloopunwindingparameterissetto30andthetimeoutissetto1second,manysamplesare expectedtofallintotheunknowncategory. Thisoccursbecauseonlyasubsetofloopscanbeunwounduptothe specifiedboundof30withinthegiven1-secondtimeframe. Likewise,thecategoryof“Verificationsuccessful”(VS)indicatesthatusingformalverificationmethodsuptoa certainsearchdepth(bound),nocounterexamplewasfoundintheprogram. However,itisimportanttonotethat increasingtheverificationtimeortheunwindingparametercanpotentiallyleadtoachangeinclassificationto“veri- ficationfailed.”
Onthecontrary,“Verificationfailed”representsacompletelydifferentscenarioandisthemainfocusofourinterest. IfasampleisclassifiedasfailedbyESBMC,wecanbe100%certainthatthereisaviolationofpropertiesinthe program. Additionally,ESBMCprovidesacounterexampletodemonstratethespecificpropertyviolation. Wedi- vided“Verificationfailed”into9categories,wherethefirst8arethemostfrequentlyoccurringvulnerabilities,while “Other”encompassestheremainingresultsfromESBMC. • AO ⊆VF: Arithmeticoverflow • BO ⊆VF: Bufferoverflowonscanf()/fscanf() • ABV ⊆VF: Arrayboundsviolated • DFN ⊆VF : Dereferencefailure: NULLpointer • DFF ⊆VF : Dereferencefailure: forgottenmemory • DFI ⊆VF : Dereferencefailure: invalidpointer • DFA⊆VF : Dereferencefailure: arrayboundsviolated 3https://sv-comp.sosy-lab.org/2023/results/results-verified/quantilePlot-Overall.svg 10TheFormAIDataset • DZ ⊆VF : Divisionbyzero • O ⊆VF : Othervulnerabilities Thesubsequentsubsectionwilloutlinetheprecisedistributionofvulnerabilitiesandtheevaluationofthedataset. 6 EvaluationoftheFormAIDataset Asperourmethodology,weverifiedthecompilabilityofeverycodepiecebyutilizingtheGNU Ccompiler. Outof thecompletedataset,109,757samplefiles(≈ 98%)canbecompiledwithoutanydependenciessolelyusingthe simplecommandgcc -lm -o <filename>. Theremaining2%ofsamplesposegreatercomplexity,including multithreadedapplications,databasemanagementapplications,andcryptographicapplicationssuchasAESen- cryption. Asaresult,thesesamplesutilizetendistinctexternallibraries,includingOpenSSL,sqlite3,pthread,and others. Uponsuccessfullyinstallingthefollowingdependencies,allthefilescanbecompiledwithoutanyissues: libsqlite3-dev,libssl-dev,libportaudio2,portaudio19-dev,libpcap-dev,libqrencode-dev,libsdl2-dev,freeglut3-dev, libcurl4-openssl-dev,libmysqlclient-dev. ESBMCisusingtheclang4compilerinsteadofgccfortheverificationprocess. Amongthe112,000samplesana- lyzed,asubsetof786samplescouldnotbesuccessfullycompiledusingclang;therefore,theseparticularsamples wereexcludedfromtheclassification. Additionally,inafewcases,theESBMCmodulecrashedwhenattempting tohandlecodesamples,leadingtotheexclusionofthosesamplesfromthe“.csv”filecontainingthevulnerability labels. Despitethis,weintentionallychosenottoeliminatethesesamplesfromthedataset,astheyholdvaluefor furtherresearch. Wehaveexaminedover8,848,765linesofCcode,withanaverageof79linespersample. Programswith47lines arethemostcommon,withatotalof1405samples. Amongtheprogramsinourdataset,onlyonesurpassesaline countof600. ItisworthmentioningthattheFormAIdatasetincludesall32differentCkeywords5,whereforcom- parisoninJuliet,5oftheCkeywordsarenotpresent. Thefrequencyofif-statements,loops,andvariablesinthis contextmimicsthedistributionfoundinactualreal-worldprojects. Weattributethesimilarityinpatternsexhibited byFormAItothefactthatthetrainingdataofGPTmodelsincludedactualprojectsfromGitHub,whichwerewritten byhumandevelopers. Fortheclassification,inthecsvfiles,wedenotedthecategoryVS: as“NOTVULNERABLEuptoboundk”. The rationalebehindthisdecisionistocircumventpotentialmisinterpretations. Wecanonlyconfidentlyassertthata programisdevoidofvulnerabilitiesdetectablebyESBMCifweconfigureboththe–unwindandtimeoutparam- eterstoinfinite,andsubsequentlyobtainsuccessfulverification. ThiscategorytogetherwithVU constitutes48749 Cprograms. Intotal,fromthe112,000Cprogramsweperformedtheverificationprocesson106139files. From thisset57389uniqueprogramswerefoundvulnerable,whichisover54%oftheexaminedprograms. Theoverall numberofvulnerabilitiesdetectedbyESBMCis197800. 6.1 CWEclassification Next,weconnectedthevulnerabilitiestoCommonWeaknessEnumeration(CWE)identifiers. Theinterconnected andmultifacetednatureofsoftwareflawsoftenresultsinasinglevulnerabilitybeingassociatedwithmultipleCWE identifiers. Table2showcasesacategorizationofthemostprevalentvulnerabilitiesandthedistributionofthe42 uniqueCWEsweidentifiedacrossthesecategories. The“Othervulnerabilities”categoryincludes: Assertionfailure,Sameobjectviolation,Operandoffreemusthave zeropointeroffset,functioncall: notenougharguments,andseveraltypesofdeferencefailureissues. It’svitaltoemphasizethat,inourparticularsituation,classifyingtheCprogramsbasedonCWEidentifiersisnot practical,contrarytowhatisdoneforotherdatabaseslikeJuliet. AsshowninTable1,mostdatasetscontainonly onevulnerabilitypersample. Asnoted,inthedatasetsReVeal,BigVul,Diversevul,afunctionisvulnerableifthe vulnerability-fixingcommitchangedit. InJuliet,asinglevulnerabilityisintroducedforeachprogram. Inourcase,a singlefileoftencontainsnotonlyonebutmultiplevulnerabilities. Moreover,asinglevulnerabilitycanbeassociated withmultipleCWEs. Inmostcases,multipleCWEsarerequiredasprerequisitesforavulnerabilitytomanifest. For exampleinthecaseof“CWE-120: BufferCopywithoutCheckingSizeofInput(ClassicBufferOverflow)”,there canbeothervulnerabilitiesfacilitatingthemainissue. Forexample: “CWE-676: UseofPotentiallyDangerous
Function”,whichmightbetheuseofscanf,andontopofwhichneed“CWE-20: ImproperInputValidation”. 4https://clang.llvm.org 5https://www.programiz.com/c-programming/list-all-keywords-c-language 11TheFormAIDataset #Vulns Vuln. AssociatedCWE-numbers 23,312 AO CWE-190,CWE-191,CWE-754, CWE-680,CWE-681,CWE-682 11,088 ABV CWE-119,CWE-125,CWE-129, CWE-131,CWE-193,CWE-787, CWE-788 88,049 BO CWE-20,CWE-120,CWE-121,CWE- 125,CWE-129,CWE-131,CWE-676, CWE-628,CWE-754,CWE-788 31,829 DFN CWE-391,CWE-476 24,702 DFA CWE-119,CWE-125,CWE-125, CWE-131,CWE-129,CWE-755, CWE-787 9823 DFI CWE-416,CWE-476,CWE-690, CWE-822,CWE-824,CWE-825 5810 DFF CWE-401,CWE-404,CWE-459, CWE-775 1567 DZ CWE-369 1620 O CWE-119,CWE-125,CWE-158, CWE-362,CWE-389,CWE-401, CWE-415,CWE-459,CWE-416, CWE-469,CWE-590,CWE-617, CWE-664,CWE-662,CWE-685, CWE-704,CWE-761,CWE-787, CWE-823,CWE-825,CWE-843 Table2: ThevulnerabilitiesidentifiedbyESBMC,linkedtoCommonWeaknessEnumerationidentifiers. Labelingthevulnerablefunctionname,linenumber,andvulnerabilitytypeidentifiedbytheESBMCmodulepro- videsgranularinformationthatcanbemorebeneficialtothelearningprocessofthemodels. Thislevelofdetailcan allowmodelstodiscernpatternsandcorrelationswithhigherprecision,therebyimprovingvulnerabilityprediction anddetectioncapabilities. Asourprogramscontainseveralvulnerabilitiesandinsomecasesmultipleinstances ofthesamevulnerability,classifyingeachintoasingleCWEgroup,asdoneforJuliet,wouldbelessoptimalfor trainingpurposes. WealsonotethatwhileotherdatasetslikeDiversVulandJulietfocusmoreonCWEsrelatedto softwaresecurityandvulnerabilitiesthatcouldpotentiallybeexploited,ESBMCdetectsissuesrelatedtosoftware safetyaswell. 6.2 EmergingResearchDirections Thedatasetcontainingall112,000Cprogramfiles,alongwiththetwo.csvfilesarepublishedonGitHubunderthe followinglink: https://github.com/FormAI-Dataset. ThediversestructureoftheCprogramsgeneratedintheFormAIdatasetmadeitexcellentforanunexpecteduse case,namely: fuzzingdifferentapplications. WhilerunningESBMConthedataset,wediscoveredandreported sevenbugsinthemodule. Aftervalidatingtheseissues,ESBMCdevelopersmanagedtoresolvedthem. Thesein- cludederrorsinthegoto-ccconversionandthecreationofinvalidSMTsolverequations. Additionally,weidentified bugsintheCBMCmodelchecker–whichisanotherBMCmodule–andtheClangcompilerwhichfailedtocom- pileseveralprogramsthatGNUChadnoissuewith. Wepromptlycommunicatedthesefindingstotherespective developers. 7 LimitationsandThreatstoValidity WhileESBMCisarobusttoolfordetectingmanytypesoferrorsinC,asoftodayitisnotsuitedtodetectdesign flaws,semanticerrors,orperformanceissues. Assuch,morevulnerabilitiesmightbepresentinthecodebesides thedetectedones. Also,tofindallerrorsdetectablebyESBMC,theunwindlimitandverificationtimemustbe settoinfinite. AsweprovidedtheoriginalCprogramsandtheinstructionsonhowtorunESBMC,researchers 12TheFormAIDataset whoinvestadditionalcomputationalresourceshavethepotentialtoenhanceourfindings. Ourresultswerereached with: “–unwind1–overflow–multi-property–timeout30”. EvenwiththesamesettingsbutusingaweakerCPU, forexample,ESBMCmightnotbeabletocompletetheverificationprocessforaseveralprograms,resultingin “ERROR:Timedout”. Wewereabletoruntheverificationprocessfor106,139programs. The5861differenceis becauseapproximately1%ofthesampleswerenotcompilablebyClangwhileESBMCencounteredcrashesonthe rest;assuch, 5%ofsampleswerenotclassified. Inadditiontothereportedfindings,wefoundseveralinstancesof“CWE-242: UseofInherentlyDangerousFunc- tion”. AlthoughESBMCcorrectlyreportsseveralrelatedfunctionsasvulnerable,thereportedlinenumberofthe vulnerabilityisoftenmisleading. Forinstance,whenthegets()functionisinvoked–whichisdeclaredinio.c– ESBMCmarksalinenumberinio.castheplaceofthevulnerability. Thiswouldbemisleadingformachinelearn- ingapplicationsaimingtodetectorfixvulnerabilitiesinthesourcecode;therefore,weexcludedsuchreportsfrom thetwocsvfiles. 8 Conclusions ThispapershowsthatGPT-3.5-turbonotoriouslyintroducesvulnerabilitieswhengeneratingCcode. Thebroad rangeofprogrammingscenarioswasinstrumentalinunveilingavarietyofcodingstrategiesandevaluatinghow GPT-3.5managesspecifictasks. Thisprovidedanopportunitytopinpointsituationswhereitmightutilizequestion- abletechniquesthatcouldpotentiallyintroduceavulnerability. Tofacilitateawiderangeofprogrammingscenarios wecreatedazero-shotpromptingtechniqueandusedGPT-3.5-turbotogenerateCcode. Theseprogramsconstitute theFormAIdataset,containing112,000independentcompilableCprograms. WeusedtheESBMCboundedmodel checkertoproduceformallyverifiablelabelsforbugsandvulnerabilities. Inourexperiment,weallocatedaverifica-
tiontimeof30secondstoeachprogram,withtheunwindingparametersetto1. Intotal197800vulnerablefunctions weredetectedbyESBMC.Someprogramscontainmultipledifferenterrors. Thelabelingisprovidedina.csvfile whichincludes: Filename,Vulnerabilitytype,Functionname,Linenumber,andErrortype. Inaddition,weprovide anadditional.csvfilecontainingtheCcodeasaseparatecolumn. Next,weconnectedtheidentifiedvulnerabilities toCWEidentifiers. TheFormAIdatasetisavaluableresourceforbenchmarkingvulnerabilitydetectiontools,orto trainmachinelearningalgorithmstopossessthecapabilitiesoftheESBMCmodule. TheFormAIdatasetprovesto beavaluableinstrumentforfuzzingdifferentapplications,aswehavedemonstratedbyidentifyingmultiplebugsin theESBMCandCBMCmodules,aswellastheClangcompiler. References [Ahoetal.(2006)] AlfredV.Aho,MonicaS.Lam,RaviSethi,andJeffreyD.Ullman.2006. Compilers: Principles, Techniques,AndTools(2nded.). Addison-WesleyLongmanPublishingCo.,Inc. [Avila(2022)] RistoAvila.2022. EmbeddedSoftwareProgrammingLanguages: Pros,Cons,and ComparisonsofPopularLanguages. https://www.qt.io/embedded-development-talk/ embedded-software-programming-languages-pros-cons-and-comparisons-of-popular-languages [Beyer(2023)] DirkBeyer.2023. CompetitiononSoftwareVerificationandWitnessValidation: SV-COMP2023. InToolsandAlgorithmsfortheConstructionandAnalysisofSystems,SriramSankaranarayananandNatasha Sharygina(Eds.).SpringerNatureSwitzerland,Cham,495–522. [Black(2018)] PaulE.Black.2018. ASoftwareAssuranceReferenceDataset: ThousandsofProgramsWithKnown Bugs. JournalofResearchoftheNationalInstituteofStandardsandTechnology123(April2018),1–3. https: //doi.org/10.6028/jres.123.005 [Buietal.(2023)] NghiD.Q.Bui,HungLe,YueWang,JunnanLi,AkhileshDeepakGotmare,andStevenC.H. Hoi.2023. CodeTF:One-stopTransformerLibraryforState-of-the-artCodeLLM. (May2023). http: //arxiv.org/abs/2306.00029 arXiv:2306.00029[cs]. [Chakrabortyetal.(2022)] SaikatChakraborty,RahulKrishna,YangruiboDing,andBaishakhiRay.2022. Deep LearningBasedVulnerabilityDetection: AreWeThereYet? IEEETransactionsonSoftwareEngineering48, 9(Sept.2022),3280–3296. https://doi.org/10.1109/TSE.2021.3087402 ConferenceName: IEEE TransactionsonSoftwareEngineering. [Charalambousetal.(2023)] YiannisCharalambous,NorbertTihanyi,RidhiJain,YouchengSun,MohamedAmine Ferrag,andLucasC.Cordeiro.2023. ANewErainSoftwareSecurity: TowardsSelf-HealingSoftwareviaLarge LanguageModelsandFormalVerification. (May2023). https://doi.org/10.48550/arXiv.2305.14752 arXiv:2305.14752[cs]. 13TheFormAIDataset [Chavezetal.(2023)] MartinR.Chavez,ThomasS.Butler,PatriciaRekawek,HyeHeo,andWendyL.Kinzler. 2023. ChatGenerativePre-trainedTransformer: whyweshouldembracethistechnology. AmericanJournal ofObstetricsandGynecology228,6(June2023),706–711. https://doi.org/10.1016/j.ajog.2023.03. 010 [Chenetal.(2023)] YizhengChen,ZhoujieDing,XinyunChen,andDavidWagner.2023. DiverseVul: ANew VulnerableSourceCodeDatasetforDeepLearningBasedVulnerabilityDetection. (April2023). http: //arxiv.org/abs/2304.00409 arXiv:2304.00409[cs]. [Cordeiroetal.(2012)] LucasCordeiro,BerndFischer,andJoaoMarques-Silva.2012. SMT-BasedBoundedModel CheckingforEmbeddedANSI-CSoftware. IEEETransactionsonSoftwareEngineering38,4(July2012), 957–974. https://doi.org/10.1109/TSE.2011.59 ConferenceName: IEEETransactionsonSoftware Engineering. [D’Silvaetal.(2008)] VijayD’Silva,DanielKroening,andGeorgWeissenbacher.2008. ASurveyofAutomatedTech- niquesforFormalSoftwareVerification. IEEETransactionsonComputer-AidedDesignofIntegratedCircuits andSystems27,7(July2008),1165–1178. https://doi.org/10.1109/TCAD.2008.923410 Conference Name: IEEETransactionsonComputer-AidedDesignofIntegratedCircuitsandSystems. [Fanetal.(2020)] JiahaoFan,YiLi,ShaohuaWang,andTienN.Nguyen.2020. AC/C++CodeVulnerabilityDataset withCodeChangesandCVESummaries.InProceedingsofthe17thInternationalConferenceonMining SoftwareRepositories(MSR’20).AssociationforComputingMachinery,NewYork,NY,USA,508–512. https://doi.org/10.1145/3379597.3387501 [Gadelhaetal.(2018)] MikhailRGadelha,FelipeRMonteiro,JeremyMorse,LucasCCordeiro,BerndFischer, andDenisANicole.2018. ESBMC5.0: anindustrial-strengthCmodelchecker.InProceedingsofthe33rd ACM/IEEEInternationalConferenceonAutomatedSoftwareEngineering.888–891. [Gadelhaetal.(2023)] MikhailR.Gadelha,FelipeR.Monteiro,JeremyMorse,LucasC.Cordeiro,BerndFischer, andDenisA.Nicole.2023. ESBMC:5.0: AnIndustrial-StrengthModelChecker. https://github.com/ esbmc/esbmc original-date: 2015-06-20T19:35:34Z. [Gadelhaetal.(2019)] MikhailY.R.Gadelha,EnricoSteffinlongo,LucasC.Cordeiro,BerndFischer,andDenisA.
Nicole.2019. SMT-basedrefutationofspuriousbugreportsintheclangstaticanalyzer.InProceedingsof the41stInternationalConferenceonSoftwareEngineering: CompanionProceedings,ICSE2019,Montreal, QC,Canada,May25-31,2019,JoanneM.Atlee,TevfikBultan,andJonWhittle(Eds.).IEEE/ACM,11–14. https://doi.org/10.1109/ICSE-Companion.2019.00026 [Hutchinsonetal.(2021)] BenHutchinson,AndrewSmart,AlexHanna,EmilyDenton,ChristinaGreer,Oddur Kjartansson,ParkerBarnes,andMargaretMitchell.2021. TowardsAccountabilityforMachineLearning Datasets: PracticesfromSoftwareEngineeringandInfrastructure.InProceedingsofthe2021ACMConference onFairness,Accountability,andTransparency(FAccT’21).AssociationforComputingMachinery,NewYork, NY,USA,560–575. https://doi.org/10.1145/3442188.3445918 [Imanietal.(2023)] ShimaImani,LiangDu,andHarshShrivastava.2023. Mathprompter: Mathematicalreasoning usinglargelanguagemodels. arXivpreprintarXiv:2303.05398(2023). [Jainetal.(2023)] RidhiJain,NicoleGervasoni,MthandazoNdhlovu,andSanjayRawat.2023. ACodeCentric EvaluationofC/C++VulnerabilityDatasetsforDeepLearningBasedVulnerabilityDetectionTechniques.In Proceedingsofthe16thInnovationsinSoftwareEngineeringConference.1–10. [JrandBlack(2012)] FrederickE.BolandJrandPaulE.Black.2012. TheJuliet1.1C/C++andJava TestSuite. NIST 45,10(Oct.2012),88–90. https://www.nist.gov/publications/ juliet-11-cc-and-java-test-suite LastModified: 2021-10-12T11:10-04:00Publisher: Frederick E.BolandJr.,PaulE.Black. [Khouryetal.(2023)] RaphaëlKhoury,AndersonR.Avila,JacobBrunelle,andBabaMamadouCamara.2023. HowSecureisCodeGeneratedbyChatGPT? (April2023). http://arxiv.org/abs/2304.09655 arXiv:2304.09655[cs]. [KimandRussell(2018)] LouisKimandRebeccaRussell.2018. DraperVDISCDataset-VulnerabilityDetectionin SourceCode. (Nov.2018). https://osf.io/d45bw/ Publisher: OSF. [Liuetal.(2023)] JiaweiLiu,ChunqiuStevenXia,YuyaoWang,andLingmingZhang.2023. IsYourCodeGenerated byChatGPTReallyCorrect? RigorousEvaluationofLargeLanguageModelsforCodeGeneration. (May2023). https://doi.org/10.48550/arXiv.2305.01210 arXiv:2305.01210[cs]. [Maetal.(2023a)] WeiMa,ShangqingLiu,WenhanWang,QiangHu,YeLiu,CenZhang,LimingNie,andYang Liu.2023a. TheScopeofChatGPTinSoftwareEngineering: AThoroughInvestigation. arXivpreprint arXiv:2305.12138(2023). 14TheFormAIDataset [Maetal.(2023b)] WeiMa,ShangqingLiu,WenhanWang,QiangHu,YeLiu,CenZhang,LimingNie,andYang Liu.2023b. TheScopeofChatGPTinSoftwareEngineering: AThoroughInvestigation. (May2023). https: //doi.org/10.48550/arXiv.2305.12138 arXiv:2305.12138[cs]. [OpenAI(2022)] OpenAI.2022. GPT-3.5. AccessedMay17,2023.https://platform.openai.com/docs/ models/gpt-3-5. [OpenAI(2023)] OpenAI.2023. GPT-4TechnicalReport. TechnicalReport. http://arxiv.org/abs/2303. 08774 arXiv:2303.08774[cs]. [Pearceetal.(2021)] HammondPearce,BaleeghAhmad,BenjaminTan,BrendanDolan-Gavitt,andRameshKarri. 2021. AsleepattheKeyboard? AssessingtheSecurityofGitHubCopilot’sCodeContributions. (Dec.2021). https://doi.org/10.48550/arXiv.2108.09293 arXiv:2108.09293[cs]. [Pearceetal.(2022)] HammondPearce,BenjaminTan,BaleeghAhmad,RameshKarri,andBrendanDolan-Gavitt. 2022. ExaminingZero-ShotVulnerabilityRepairwithLargeLanguageModels. (Aug.2022). http://arxiv. org/abs/2112.02125 arXiv:2112.02125[cs]. [Perryetal.(2022)] NeilPerry,MeghaSrivastava,DeepakKumar,andDanBoneh.2022. DoUsersWriteMore InsecureCodewithAIAssistants? (Dec.2022). http://arxiv.org/abs/2211.03622 arXiv:2211.03622 [cs]. [Picardetal.(2020)] S.Picard,C.Chapdelaine,C.Cappi,L.Gardes,E.Jenn,B.Lefevre,andT.Soumarmon.2020. EnsuringDatasetQualityforMachineLearningCertification.In2020IEEEInternationalSymposiumonSoft- wareReliabilityEngineeringWorkshops(ISSREW).275–282. https://doi.org/10.1109/ISSREW51248. 2020.00085 [reyVoas(1996)] JereyVoas.1996. Testingsoftwareforcharacteristicsotherthancorrectness: Safety,failure tolerance,andsecurity. (1996). [Rossetal.(2023)] StevenI.Ross,FernandoMartinez,StephanieHoude,MichaelMuller,andJustinD.Weisz.2023. TheProgrammer’sAssistant: ConversationalInteractionwithaLargeLanguageModelforSoftwareDevelop- ment.InProceedingsofthe28thInternationalConferenceonIntelligentUserInterfaces(IUI’23).Association forComputingMachinery,NewYork,NY,USA,491–514. https://doi.org/10.1145/3581641.3584037 [Russelletal.(2018)] RebeccaRussell,LouisKim,LeiHamilton,TomoLazovich,JacobHarer,OnurOzdemir, PaulEllingwood,andMarcMcConley.2018. AutomatedVulnerabilityDetectioninSourceCodeUsingDeep
RepresentationLearning.In201817thIEEEInternationalConferenceonMachineLearningandApplications (ICMLA).757–762. https://doi.org/10.1109/ICMLA.2018.00120 [SadowskiandYi(2014)] CaitlinSadowskiandJaeheonYi.2014. Howdevelopersusedataracedetectiontools.In Proceedingsofthe5thWorkshoponEvaluationandUsabilityofProgrammingLanguagesandTools.43–51. [Sandovaletal.(2023)] GustavoSandoval,HammondPearce,TeoNys,RameshKarri,SiddharthGarg,andBrendan Dolan-Gavitt.2023. LostatC:AUserStudyontheSecurityImplicationsofLargeLanguageModelCode Assistants. (Feb.2023). http://arxiv.org/abs/2208.09727 arXiv:2208.09727[cs]. [Shumailovetal.(2023)] IliaShumailov,ZakharShumaylov,YirenZhao,YarinGal,NicolasPapernot,andRoss Anderson.2023. TheCurseofRecursion: TrainingonGeneratedDataMakesModelsForget. (May2023). http://arxiv.org/abs/2305.17493 arXiv:2305.17493[cs]. [Somoye(2023)] FunmiLooiSomoye.2023. IsChatGPTfreeandunlimited? Inshort-yes. https://www. pcguide.com/apps/chat-gpt-free/ [Umawing(2023)] JoviUmawing.2023. ChatGPTwritesinsecurecode. https://www.malwarebytes.com/ blog/news/2023/04/chatgpt-creates-not-so-secure-code-study-finds [WallaceandFujii(1989)] D.R.WallaceandR.U.Fujii.1989. Softwareverificationandvalidation: anoverview. IEEESoftware6,3(May1989),10–17. https://doi.org/10.1109/52.28119 [Weietal.(2023)] JasonWei,XuezhiWang,DaleSchuurmans,MaartenBosma,BrianIchter,FeiXia,EdChi,Quoc Le,andDennyZhou.2023. Chain-of-ThoughtPromptingElicitsReasoninginLargeLanguageModels. (Jan. 2023). https://doi.org/10.48550/arXiv.2201.11903 arXiv:2201.11903[cs]. [Whiteetal.(2023)] JulesWhite,QuchenFu,SamHays,MichaelSandborn,CarlosOlea,HenryGilbert,Ashraf Elnashar,JesseSpencer-Smith,andDouglasC.Schmidt.2023. APromptPatternCatalogtoEnhancePromptEn- gineeringwithChatGPT. (Feb.2023). https://doi.org/10.48550/arXiv.2302.11382 arXiv:2302.11382 [cs]. [Whiteetal.(2016)] MartinWhite,MicheleTufano,ChristopherVendome,andDenysPoshyvanyk.2016. Deeplearn- ingcodefragmentsforcodeclonedetection.InProceedingsofthe31stIEEE/ACMinternationalconferenceon automatedsoftwareengineering.87–98. 15TheFormAIDataset [Xingetal.(2023)] ZhenchangXing,QingHuang,YuCheng,LimingZhu,QinghuaLu,andXiweiXu.2023. Prompt Sapper: LLM-EmpoweredSoftwareEngineeringInfrastructureforAI-NativeServices. (June2023). https: //doi.org/10.48550/arXiv.2306.02230 arXiv:2306.02230[cs]. [Yaoetal.(2023)] ShunyuYao,DianYu,JeffreyZhao,IzhakShafran,ThomasL.Griffiths,YuanCao,andKarthik Narasimhan.2023. TreeofThoughts: DeliberateProblemSolvingwithLargeLanguageModels. (May2023). http://arxiv.org/abs/2305.10601 arXiv:2305.10601[cs]. [ZhaoandHuang(2018)] GangZhaoandJeffHuang.2018. Deepsim: deeplearningcodefunctionalsimilarity.InPro- ceedingsofthe201826thACMJointMeetingonEuropeanSoftwareEngineeringConferenceandSymposium ontheFoundationsofSoftwareEngineering.141–151. [Zhouetal.(2019a)] YaqinZhou,ShangqingLiu,JingkaiSiow,XiaoningDu,andYangLiu.2019a. Devign. https: //sites.google.com/view/devign [Zhouetal.(2019b)] YaqinZhou,ShangqingLiu,JingkaiSiow,XiaoningDu,andYangLiu.2019b. Devign: Effective VulnerabilityIdentificationbyLearningComprehensiveProgramSemanticsviaGraphNeuralNetworks. (Sept. 2019). http://arxiv.org/abs/1909.03496 arXiv:1909.03496[cs,stat]. 16
2307.02446 Vulnerable Source Code Detection using SonarCloud Code Analysis Alifia Puspaningrum1 a, Muhammad Anis Al Hilmi*1 b, Darsih1, Muhamad Mustamiin1, Maulana Ilham Ginanjar1 1Department of Informatics, Politeknik Negeri Indramayu, Jalan Lohbener Lama No. 08, Indramayu, Indonesia alifia.puspaningrum@polindra.ac.id, alhilmi@polindra.ac.id, darsih@poindra.ac.id, mustamiin@polindra.ac.id, ilhamginanjar24@gmail.com Keywords: Source Code, Detection, Vulnerability, Code analysis, SonarCloud Abstract: In Software Development Life Cycle (SDLC), security vulnerabilities are one of the points introduced during the construction stage. Failure to detect software defects earlier after releasing the product to the market causes higher repair costs for the company. So, it decreases the company's reputation, violates user privacy, and causes an unrepairable issue for the application. The introduction of vulnerability detection enables reducing the number of false alerts to focus the limited testing efforts on potentially vulnerable files. UMKM Masa Kini (UMI) is a Point of Sales application to sell any Micro, Small, and Medium Enterprises Product (UMKM). Therefore, in the current work, we analyze the suitability of these metrics to create Machine Learning based software vulnerability detectors for UMI applications. Code is generated using a commercial tool, SonarCloud. Experimental result shows that there are 3,285 vulnerable rules detected. 1 INTRODUCTION products, UMI also provides facilities for offline transaction and facilities which can support the development of UMKM. However, in construction In Software Development Life Cycle (SDLC), process, automated testing to detect vulnerable code security vulnerabilities being one of point introduced is a good way to save money and time. Therefore, in during construction stage. However, vulnerabilities the current work, we perform an analysis of the being one of issue which difficult to be detected until suitability of these metrics to create Machine it becomes apparent as security failures in the Learning based software vulnerability detectors for operational stage of SDLC [1]. Failure to detect UMI application. Code is generated using a software defect earlier after releasing product to the commercial tool, SonarCloud. market causes higher repairing cost for the company. So, it decreases company reputation, violate user privacy, and cause unrepairable issue for the application [2]. In addition, techniques to detect 2 LITERATURE REVIEW software vulnerabilities are needed before releasing product [3]. To solve those problems, dedicated tools 2.1 Software Testing are available on the market: e.g., Veracode [4] and SonarCode [5]. The introduction of vulnerability Testing is an activity to evaluate software quality and detection (usually a binary classification of to improve it [7]. In general, testing divided into two vulnerable and neutral parts of the source code) namely black box and white box testing. White box is enables reducing the number of false alerts to focus a testing technique that uses Software Under Test the limited testing efforts on potentially vulnerable (SUT) or the software being tested as a test guide to files [6]. be carried out [8]. In addition, Black Box Testing is UMKM Masa Kini (UMI) is a Point of Sales not an alternative solution to White Box Testing but application to sell any kind Micro, Small and Medium is more of a complement to testing things that are not Enterprises Product (UMKM). Not only selling the covered by White Box Testing. a https://orcid.org/0000-0001-7179-8847 b https://orcid.org/0000-0003-3696-0807 (corresponding author)2.2 Software Quality ISO 25010 under specified conditions for a certain period. Software quality can be assessed through certain 6. Security is a characteristic to measure a metrics, methods, as well as through software tests. system in protecting information and data, One of benchmarks for software quality is so that the system has a data access level (International Organization for Standardization) ISO according to the type and level of 25010. ISO/IEC 25010 has eight characteristics to authorization. measure software quality, including portability, 7. Maintainability is a characteristic to performance efficiency, reliability, security usability, represent the level of effectiveness and maintainability, compatibility, and functional efficiency in the modification process for suitability. system improvement in accordance with adjustments and changes in the operational environment. 8. Portability is a characteristic to represent the level of effectiveness and efficiency of the system in transferring from one device to another. 2.3 SonarCloud SonarCloud is an online automated software quality analysis platform delivered by SonarQube, which is used to collect code quality analysis data on linked software from GitHub [9] SonarCloud calculates several metrics such as number of lines of code and code complexity and verifies code compliance with a specific set of "coding rules" defined for most common development languages. If the analyzed source code violates the coding rules or if the metric falls outside a predefined threshold, SonarCloud generates an "issue". SonarCloud Figure 1. Product Quality Model ISO/IEC 25010 includes 3 quality models from ISO 25010 namely Reliability, Maintainability and Security. Figure 1 is characteristics and sub-characteristics of SonarCloud also classifies rules into five levels of Software product quality model which consists of: code severity, namely Blocker, Critical, Major, Minor, and Info. 1. Functional Suitability is a characteristic to  Blocker: a bug with a high probability of measure which system provides functions affecting the use of the application in according to its requirement when used in production. certain conditions. 2. Performance Efficiency is a characteristic to  Critical: a bug with a low probability of calculate relative performance of the affecting application use in production or a resources when used in certain conditions. weak level of security. 3. Compatibility is a characteristic to measure  Major: lack of quality which can have a huge
how a system share an information to other impact on developer productivity. Like code systems and execute required functions snippets not found and unused parameters. while sharing same hardware or software  Minor: lack of quality which can slightly environment. impact developer productivity. Like too long 4. Usability is a characteristic to measure lines of code and minimal statements which system can be used to achieve the  Info: not a bug or lack of quality but just a specified goals effectively and efficiently. finding from SonarCloud. 5. Reliability is a characteristic to measure how reliable a system can execute functions3 METHOD UMKM Masa Kini (UMI) is marketplace application which store and generate finance administration. This 3.1 SonarCloud Pipeline application has been developed since 2020. There are 19 functions in UMI. For experimental analysis, SonarCloud is used to collect vulnerable source code to obtain analysis of vulnerable code. Figure 2. show how SonarCloud detects insecure in given code. 4 RESULT After scanning using SonarCloud as shown in Figure 4, SonarCloud generate a report, showing three scopes of the application namely Reliability, Maintainability, Security and its severity level as shown in Figure 5. Figure 4. Analyzing Project Process Figure 2. SonarCloud Block Diagram The first step is request SonarCloud REST API. In the second phase, the crawlers collect source code of the application. In the next phase, SonarCloud manipulate by adding vulnerable lines as comments at the end of the source code file. After that, SonarCloud stores the result in the local file of the system. The last step is releasing the dataset to the Figure 5. SonarCloud Report Analysis community. SonarCloud inspects the model according to ISO 25010 Standard, namely: reliability, maintainability, Overall code rating (reliability, maintainability, security and classify into five categories then. security). The detail information of the report is shown in Table 1. 3.2 Dataset Table 1 UMI Severity Level Type Severity Rules All 2,370 Info - Minor 2,000 Bug Major 364 Critical 6 Blocker - All 665 Info - Code Smell Minor 74 Major 356 Figure 3. Landing Page of UMI WebsiteType Severity Rules Critical 233 Blocker 2 All 3 Info - Minor - Vulnerability Major - Critical 1 Blocker 2 Total 3,285 Figure 9 sample code of code smell type After retrieving the source code, for each For other issues such as code smell and bug category vulnerability, a line is appended to the original are also analyzed as shown as Figure 8 and Figure 9. source. Result shows that there are 3.285 rules Every report can help developer to do maintenance detected as vulnerable code. Each issue namely bug, more efficient. However, one of limited of code smell, and vulnerability are categorized into SonarCloud’s web API is the one commonly known severity level, namely: blocker, critical, major, minor, as the 10,000-issue limit. This constraint implies that info. So that, developer can repair the code to get a every single request made will be responded to only safe code. with the first 10,000 results [10]. However, SonarCloud reports starting and ending line and starting and ending offset (column) of the vulnerability instead highlighting the vulnerable code. 5 CONCLUSIONS Figure 6. Vulnerability Analysis This paper analyzes vulnerable for UMI application source code by using SonarCloud. Experimental There are three rules detected in vulnerability issue. result shows that there are 3,285 vulnerable rules As shown as Figure 6, three rules are reported and detected. So that, developer can repair the code to get completed with each severity level. For each rule, a safe code. For the future work, highlighting the SonarCloud describes the issue as shown as Figure 7. vulnerable code instead of starting and ending line and starting and ending offset (column) of the vulnerability. ACKNOWLEDGEMENTS This research has been supported by Pusat Penelitian dan Pengabdian Masyarakat, Politeknik Negeri Figure 7 sample code of vulnerability type Indramayu, as Penelitian Kerjasama Perguruan Tinggi 2022. REFERENCES [1] Kehagias, D.; Jankovic, M.; Siavvas, M.; Gelenbe, E. Investigating the Interaction between Energy Consumption, Quality of Service, Reliability, Security, and Maintainability of Computer Systems and Networks. SN Comput. Sci. 2021, 2, 1–6. Figure 8 sample code of bug type [2] Cisco. Cisco Cybersecurity Series 2019: Consumer Privacy Survey. Available online:https://www.cisco.com/c/dam/global/en_uk/products /collateral/security/cybersecurity-series-2019- cps.pdf (accessed on 5 August 2020). [3] Shin, Y.; Meneely, A.; Williams, L.; Osborne, J.A. Evaluating complexity, code churn, and developer activity metrics as indicators of software vulnerabilities. IEEE Trans. Softw. Eng. 2010, 37, 772–787. [CrossRef] [4] Veracode. Available online: https://www.veracode.com/ (accessed on 5 August 2020) [5] Raducu, R., Costales, G. E., Lera, F. J. R., & Llamas, C. F. (2019). SVCP4C: a tool to collect vulnerable source code from open-source repositories linked to SonarCloud. In Actas de las V Jornadas Nacionales de Ciberseguridad: junio 5-7, 2019. Cáceres (pp. 191-197). Servicio de Publicaciones. [6] Chowdhury, I.; Zulkernine, M. Can complexity, coupling, and cohesion metrics be used as early indicators of vulnerabilities? In Proceedings of the 2010 ACM Symposium on Applied Computing, Sierre, Switzerland, 22–26 March 2010; pp. 1963– 1969. [7] Pan, J. (1999). Software testing. Dependable Embedded Systems, 5, 2006. [8] Touseef, M., Anwer, N., Hussain, A., & Nadeem, A. (2015). Testing from UML design using activity diagram: a comparison of techniques. International Journal of Computer Applications, 975, 8887. [9] SonarSource. SonarQube Docs—/api/issues. 2014. Available online: https://docs.sonarqube.org/pages/ viewpage.action?pageId=239218 (accessed on 2 December 2019).
2307.05758 Formal and Fuzzing Amplification: Targeting Vulnerability Detection in 5G and Beyond Jingda Yang∗, Student Member, IEEE and Ying Wang†, Member, IEEE School of Systems and Enterprises, Stevens Institute of Technology, Hoboken, USA ∗jyang76@stevens.edu, and †ywang6@stevens.edu Abstract—Softwarizationandvirtualizationin5Gandbeyond verification framework, which integrates model checkers and require rigorous testing against vulnerabilities and unintended cryptographic protocol verifiers by applying the abstraction- emergentbehaviorsforcriticalinfrastructureandnetworksecu- refinement principle. In contrast, fuzz testing can offer a rity assurance. Formal methods operates efficiently in protocol- detailedandcomprehensiveexperimentalevaluationanddetect level abstract specification models, and fuzz testing offers com- prehensive experimental evaluation of system implementations. potential vulnerabilities in the 5G code implementation plat- In this paper, we propose a novel framework that leverages form [5] and has been proven to be successful in discovering the respective advantages and coverage of both formal and critical security bugs in implemented software [6]. However, fuzzing methods to efficiently detect vulnerabilities from proto- the limitations of conventional pick-and-choose fuzz testing col logic to implementation stacks hierarchically. The detected and formal analysis still exist, especially with the large-scale attack traces from the formal verification results in critical protocols guide the case generation of fuzz testing, and the software stacks in the system. Given that each approach pos- feedbacks from fuzz testing further broaden the scope of the sesses unique strengths, we have proposed a tandem connec- formal verification. We examine the proposed framework with tion between the fuzz testing and formal methods to achieve the 5G Non Standard-Alone (NSA) security processes, focusing amorecomprehensivevulnerabilitydetectionandenablehigh on the Radio Resource Control (RRC) connection process. We assurance in the security analysis. first identify protocol-level vulnerabilities of user credentials via formal methods. Following this, we implement bit-level fuzzing Further, we propose an integrated framework fortified by to evaluate potential impacts and risks of integrity-vulnerable a reinforcing loop to detect vulnerabilities and unintended identifier variation. Concurrently, we conduct command-level emergent behaviors in system design and implementations. mutation-basedfuzzingbyfixingtheassumptionidentifiertoas- Our approach advocates for a harmonized application of fuzz sess the potential impacts and risks of confidentiality-vulnerable identifiers. During this approach, we established 1 attack model testing and formal analysis, aiming to establish a symbiotic anddetected53vulnerabilities.Thevulnerabilitiesidentifiedused cycle between these two methods. This integrated strategy to fortify protocol-level assumptions could further refine search is designed to facilitate the identification of vulnerabilities space for the following detection cycles. Compared to the state throughout the entire search space, thereby providing a com- ofartfuzztesting,thisunifiedmethodologysignificantlyreduces prehensive and robust mechanism for vulnerability detection. computational complexity, transforming the computational cost from exponential to linear growth. Consequently, it addresses Formal verification provides valuable guidance and assump- the prevalent scalability challenges in detecting vulnerabilities tions in reducing and directing fuzz testing. Conversely, fuzz andunintendedemergentbehaviorsinlarge-scalesystemsin5G testing broaden formal verification’s scope by classifying and beyond. uncertaintyareas.Importantly,thisintegratedapproachenables Index Terms—Formal verification, fuzz testing, reinforcing mutual amplification between the two methodologies. Follow- loop, integrated solution, Non Standard-Alone 5G Network ing this approach, we discover multiple vulnerabilities due to absenceofrudimentaryman-in-the-middle(MITM)protection I. INTRODUCTION within the protocol, which is unexpected considering that the Verticals in 5G and next-generation infrastructure create Transport Layer Security (TLS) solution to this issue has a diverse and intricate environment consisting of software, been in existence for well over a decade [7]. Our framework, hardware,configurations,instruments,data,users,andvarious characterized by robust automation, scalability, and usability, stakeholders [1]. With system complexity and its lack of promises to enhance security assurance and resilience across security emphasis by domain scientists, the formed ecosystem both infrastructure and domain levels, striving to guarantee requires a comprehensive evaluation and in-depth validation the absence of additional security issues within the system. for improving transitional Critical Infrastructure (CI) security Additionally, the proposed approach could be applied to vari- posture [2]. ousopenprogrammablecommunicationplatforms[8],[9]Our Two major state-of-the-art approaches, formal verification major contributions are summarized below: and fuzz testing, have been proposed to detect various vul- nerabilities and unintended emergent behaviors of the 5G • We designed and implemented the integrated formal network. Formal verification provides a high-level protocol guided fuzz testing framework, which significantly im- concept and logical proof of security and vulnerability [3]. proves efficiency and achieves scalability for large-scale For example, Hussian [4] et al. proposed a cross-layer formal 5G systems and discovery of new and exploited vulnera- 3202 luJ 11 ]RC.sc[ 1v85750.7032:viXrabilities in the Non Standard-Alone (NSA) 5G communi- cation authentication process. 2) Formal Verification
• We performed in-depth formal analysis on the NSA 5G Start 3) S Ie sa or lc ah ti oS npace authentication process by converting informal protocols Undefined into a symbolic flowchart (Fig. 2), enabling comprehen- Symbolic attack Transfer Provable sive formal analysis. Security • We discover multiple vulnerabilities due to absence of 1) Protocol Provable Abstraction Attack rudimentaryMITMprotectionthatneedstobeaddressed End the 3GPP technical standards and protocols, despite the 5) Formal Verification TLS solution to this issue has been in existence for well 4)Fuzz Guide Fortification Quantification over a decade. $ISMI • With the proposed integrated formal and fuzz testing Impletation $RA ?/N $D d framework, we connected vulnerabilities detected by for- Code ****** malanalysistoreal-lifeattackmodelsanddiscoverednew Vulnearbility Detection vulnerabilities. Fig. 1: System Design The rest of the paper is organized as follows. Section II-A traces have been detected. Fuzz testing serves a dual introduces the structure of our proposed framework. We then purpose: it is not only deployed to identify runtime discuss our design and formal symbolic transfer of the NSA vulnerabilities, thereby complementing the detection of 5G communication establishment process in Section II-B, vulnerabilities through logical proofs on protocols, but it followed by a detailed analysis and illustration of the formal alsofunctionsasastochasticapproachforthoseuncertain verification results in Section III. Then, we propose proven areas that cannot be verified through formal methods. solutions for each detected formal attack model, along with 5) Fortification of Protocol and Formal Verification : somenovelsuggestions.InSectionIV,weusetheassumptions We verify the vulnerabilities detected by fuzz testing as a guide to apply our proposed fuzz testing framework. and feedback to the formal result and search space. By Lastly,inSectionV,weusemathematicalprooftoanalyzethe definingthespacemoreprecisely,formalverificationcan efficiency of different fuzzing strategies across varied scopes be further optimized, consequently extending the scope of fuzz testing. of the security assurance area. II. SYSTEMDESIGN The proposed framework inter-connected with our previous A. Architecture Overview fuzzingplatform [11][12]iscapableofperformingmutation- based identifiers fuzzing and permutation-based command We design and implement a hybrid multi-model vulnerabil- fuzzing following the direction from the formal method con- ity and unintended emergent behaviors detection framework clusion.Formalverification,guidedfuzzinganalysisofresults for5Gandothercommunicationsystems.AsshowninFig.1, from the actual 5G testbed, and the real-time analysis and toachievetheamplificationandcross-validationoffuzztesting feedback construct a reinforcing loop in our system. and formal verification, the proposed framework composites the following components to build up a reinforcing loop: B. Abstraction of NSA 5G Authentication Protocol 1) Protocol Abstraction: At the beginning of the system, Compared to Standard-Alone (SA) 5G network architec- we abstract the protocol into symbolic language. Logical ture, NSA 5G architecture is still widely adopted but more transfer can easily exploit vulnerabilities in design. vulnerable because the complexity introduced by the Long 2) Formal Analysis: In the formal verification process, Term Evolution (LTE) compatibility in protocol designs and we employed Proverif [10], a robust tool, to conduct infrastructure implementation, especially for authentication an in-depth analysis of our system’s protocols. Proverif and authorization. Therefore, we focus on the authentication offers a logical proof of security properties and potential process in NSA 5G architecture. As shown in Fig. 2, the vulnerabilities, facilitating a robust and comprehensive abstractedprotocolauthenticationprocessinNSAarchitecture evaluation of the system’s security integrity. includesfourparts:RadioResourceControl(RRC)Connec- 3) Search Space Isolation: The output of formal veri- tion Setup, Mutual Authentication, Non-Access Stratum fication divides the search space into three sets: no (NAS) Security Setup and Access Stratum (AS) Security vulnerabilities, attack trace detected, and uncertain areas Setup. Considering the scope of this paper and the critical thatneedfurtherinvestigation.Thedivisionofthesearch level among them, we pilot on the RRC connection setup for spaceeffectivelynarrowsdowntheuncertainregionsand in-depth analysis. enables the scalability of vulnerability detection. The RRC Connection Setup is a pivotal step in the initial 4) FormalGuidedFuzzFramework:Withtheguidanceof establishmentofcommunicationbetweenamobiledeviceand a formal verification conclusion, we initiate fuzz testing thenetworkintheLTEand5GNewRadio(NR)frameworks. on runtime binary systems, focusing particularly on the This procedure is instigated by the network upon receiving a predefined uncertain areas and those areas where attack connectionrequestfromtheUserEquipment(UE),commonlyLegend UE gNB CN UE-identity establishmentCause C Ino tn egfi rd ie tyntiality RRC Connection Setup RRC Connection Request Authentication (UE-identity, establishmentCause) Accounting RRC Connection Setup RRC Same (radioResourceConfigDedicated) Connection radioResource Sequence R IdR eC n tC ifo ien rn , e sc et leio cn te S de Pt Lu Mp NC -o Idm ep nl te itt ye , ( dR eR dC ic- aT tr ea dn Is na foc Ntio An S) Setup ConfogDedocated Integrity Confidentiality Mutual Authentication Attach Request (IMSI, UE Capability, KSIASME = 7) LTE K RAND SQN SN ID
LTE K RAND SQN SN ID A Ku St Ih ASe Mn Et i =c a 1t )i [o nn o tR ce iq pu he es ret d(R , nA oN tD in, tA eU gT riN tyH S pS r, o tected] EPS AKA Algorithm RRC I- dT era nn tis fia ec rtion sel -e Idct ee nd tP ityLMN d Ie nd foic Na Ate Sd Authentication Accounting EPS AKA Algorithm Ch Ae uc tk h e(A nU ticT aN tU ioE n= RA eU sT pN oH nS sS e) (RES) AUTNHSS XRES KASME s* e:D cuee rip tye r l ec vo el lo ir n r e sp pr ee cs iae ln pt rh oi pg eh re tr y AUTNUE RES KASME [not ciphered, not integrity protected] Check (AUTNUE = AUTNHSS) Fig. 3: Dependency Graph of RRC Connection Setup NAS Secuirty Setup Select (encryption/ NAS Security Mode Command ( KSIASME = 1, integrity algorithm) KASME Alg-ID Distinguisher AR le gp ol ra ity he md = U EE E AC 1a ,p Nab Ai Slit Iy n, tN egA rS it yC i Ap lh ge or ri in thg m =EIA1, KASME Alg-ID Distinguisher is depicted in Table I. We specifically focus on the RRC NAS-MAC) [NAS integrity protected] KDF KDF connection setup for an in-depth demonstration. NAS Secuirty mode Complete (NAS-MAC) KNASenc KNASint KNASenc KNASint [NAS integrity protected] Ciphered and Integrity Protected NAS Signaling (KNASenc KNASint) A. User Credentials Disclosure KASME NAS Uplink Count In this attack, the adversary can exploit the transparency of KDF RRC Connection Setup process to effortlessly access critical Attach Accept (UE Capability, KeNB) KeNB user identity information, which includes but is not limited AS Secuirty Setup AS Security Mode Select (encryption/ Command (AS Ciphering integrity algorithm) to the UE identity and establishment cause. This illicit access Algorithm=EEA1, AS KeNB Alg-ID Distinguisher Integrity Algorithm=EIA1, enables the adversary to acquire user information and use the MAC-I) [AS integrity KDF Compute KeNB protected] KRRCenc KRRCint KUPenc ensuingsessionkeyfornefariousactivitiessuchaseavesdrop- KeNB Alg-ID Distinguisher AS Secuirty Mode Complete (MAC-I) ping and manipulation of subsequent communications. KDF [AS integrity protected] Assumption. Analyzing Fig 3, we can conclude that the KRRCenc KRRCint KUPenc Ciphered and Integrity Protected RRC Signaling (KRRCenc KRRCint) adversary can exploit the transparency of RRC Connection Setup process to directly access any identifier within the mes- Ciphered User/ Data Plane (KUPenc) sage. Furthermore, the adversary is also capable of establish a fake UE or a MITM relay to eavesdrop and manipulate the Fig. 2: 5G NSA Security Process. messageswithintheRRCConnectionSetupprocess.Toverify the security properties of identifiers within the RRC Connec- inresponsetoaninitiatingeventsuchasacallordatasession tion Setup process, including aspects such as confidentiality initiation. RRC connection setup process aims to build up andconsistency,weconvertedtheaforementionedassumptions connections in RRC layer. into ProVerif code. Further, we abstract and derive the dependency table, pre- Vulnerability. As depicted in Fig. 2, the UE initiates the sented as Table II, from the defined protocol, considering process by sending an RRC connection request to the core four essential security properties: confidentiality, integrity, network (CN). Upon receiving this request, the CN responds authentication,andaccounting.UtilizingTableII,weconstruct by transmitting the radioResourceConfigDedicated back the corresponding dependency graph, as depicted in Fig 3, to the UE. The UE, in turn, obtains authentication from the to provide a visual representation of the security dependency CN and responds with the RRC−TransactionIdentifier, relationships. selectedPLMN −Identity and dedicatedInfoNAS to fi- nalize the RRC connection setup. Nevertheless, this process C. Formal Guided Fuzz Framework presentsanexploitablevulnerabilityasanadversarycanaccess Compared to traditional fuzz testing, which needs a com- all message identifiers. Such unprotected identifiers run the pleteunderstandingofcodeimplementation,likeLZFUZZ[6], risk of being eavesdropped upon and modified, potentially we propose a novel formal-guided identifier-based fuzzing enabling the adversary to orchestrate a MITM relay attack. framework. In our proposed fuzzing framework, we first fix Attack Trace Description. Employing formal verification, the value of critical identifiers under the assumption proved we analyzed the confidentiality of identifiers within the RRC by the formal verification and collect the communicated com- Connection Setup process. Through this methodical investi- mands. Then we set up a relay attack mechanism on srsRAN gation, we identified two categories of identifiers with the platform [13] following the attack traces, which are detected mostsignificantimpact:useridentitiesandRRCconfiguration by formal verification. identifiers. As illustrated in Fig. 4, an attacker can access the identifiers marked in red, delineating the pathway of the III. FORMALDETECTEDATTACKMODELANDANALYSIS attack. In the initial scenario, an adversary with the access to In this section, we present a proof-of-concept via an il- the user identity, like UE −identity, is capable of launch lustrative attack model detected using Proverif [10]. A com- DoS attack with real UE −identity. Contrary to traditional prehensive summary of all identified attack models in 5G DoS attacks, which aim to overwhelm a system’s capac- authentication and authorization process from our findings ity, an UE −identity-based DoS attack efficiently disruptsAssumpt- New at-
Attack Vulnerability Solution Guidancetofuzz ion tack? Modification of RRC Modified commands known Inspired • HashvalueprotectionforUEidentity Fuzztestingcanstartwithdif- Connection will disable the RRC C-RNTI by[4] • Integrityprotection ferentRRCstatus. functions orTMSI • Ensured confidentiality Authentication Deny of Service andKeyagreement(EC-AKA)[15] Repeat authentication request UE accepts authenti- (DoS) or Disconnect cationrequestwithout No Inspired • Hashed international mobile subscriber commands can be fuzzed at using Authentication by[14] identity(IMSI)[16] random time to test DoS and integrity. Request. • HashedIMSIwithintegritycheck[17] cuttingofdeviceattack. E anx dpo Ksi Nng ASK inN tASenc A w jal i cl l kl eN b deA amS no di nn mif to o or r dm e id fia ,t ei h do i .n - k I MMn Io S Tw I M,n I bn ysp [1ir 8e ]d • • A Hs ay shm em de It Mric SIen bc ar sy ep dti eo nn cryption N w KA i NthS ASkf n iu noz twz .nte Ksti Nng ASc ea nn c s ata nr dt RRC fuzz testing start with All RRC and UP ExposingKRRCenc, information will be known • Asymmetricencryption known KRRCenc and KRRCint and monitored, hijacked IMSI, Yes • HashedIMSIbasedencryption KRRCint; User Plane (UP) KUPenc andmodified. MITM fuzz testing start with known KUPenc. TABLE I: Summary of Findings and undetermined. While the safe area necessitates no further Procedure Command Identifier ConfidentialityIntegrityAuthentication Accounting RRC UE-identity N N N N scrutiny, the non-safe and undetermined areas warrant further Connection Request establishmentCause N N N N investigation using fuzz testing. Specifically, we leverage fuzz Con SR n eR te ucC pt ion C C Co o on n SR R mn n eR Re e t puC Cc c lp et t i i to o en n dC RR e o R s da n eCd ic f lIi -- eo ado IT dcg teR r et eD a n ee dnne t ds Ii tsd nf P io i tai fe yu Lc oc rr Ma Ntc it o N Ae e n- d S N N N N N N N N N N N N N N N N t i le m evs pt ei l ln eg m we it to n ht ia ne tv ioa thl nu ea st rte ea gct ikh ose n, si am ps rp ewa vc e it oll uo saf ls yth t uoe ndn a eo s tcn ee- rrs mta af ii ne n eda tr h .e e Bas ysew c leui vt rh eii t rn y - TABLE II: Dependency Table aging our previously proposed framework [19], we effectively assess the security status of regions initially verified through formal methods. Due to the constraints of page length, we UE Attacker CN present a single example to illustrate the operation of our formallyguidedfuzzingframework.Thisexamplespecifically RRC Connection Request ( demonstrateshowtheframeworkassesstheimpactofprovable UE-identity, Establishment RRC Connection Request Cause) attacks that have been identified through formal verification. RRC Connection Setup RRC Connection Setup (radioResourceConfig- Dedicated) A. MITM bit-level fuzzing RRC Connection Setup Complete (RRC-Transaction RRC Connection Setup In light of the identified vulnerabilities relating to confi- Identifier, selectedPLMN- Complete Identity, dedicatedInfoNAS) dentiality and integrity, we have developed a bit-level fuzzing test to examine the effects of exposed UE − identity and Fig. 4: User Credentials Disclosure EstablishmentCause. The results, as displayed in Table the CN verification mechanism through repeated use of the III, highlight two distinct outcomes. Modification of the same UE − identity, leading to authentication confusion. UE −identity has a minimal impact on authentication and And in second case, with computationally derived RRC − communication, albeit with an introduction of some latency. TransactionIdentifier, the adversary can establish a fake Conversely, alterations to the EstablishmentCause lead to base station or perform a MITM relay attack by manipulating a change in authentication types - a factor critical to the these identifiers. In the latter case, the adversary positions authentication establishment process, such as transforming an between the UE and the CN, intercepting and modifying emergency request to data mode. There are total 8 types communications in real-time. Consequently, this attack model of vulnerabilities that leverage the EstablishmentCause. presents a severe threat to the security and integrity of the Based on these bit-level fuzzing results, we can partition mobile network’s communication. the provably insecure areas of the RRC Connection Request Fortification via Formal Traced Vulnerability Given into two categories: areas with less impact, including UE − the significance and susceptibility of identifiers within the identity, and areas with substantial impact, encompassing RRC Connection Setup process, it is imperative to im- EstablishmentCause. Consequently, in subsequent fuzzing plement integrity protection measures for the RRC − tests, we can strategically exclude UE − identity fuzzing, TransactionIdentifier. Additionally, adopting a hash value focusing instead on the chain effects generated by high-risk approachcanassistinpreventingthedisclosureofUEidentity, identifiers. further reinforcing security measures in this critical process. B. Command-level fuzzing IV. FORMALGUIDEDFUZZINGANALYSIS AssumingcompletedisclosureofallnecessaryUEidentities As detailed in Section III, formal verification delineates the and an unprotected RAND in the Authentication Request of system’s security landscape into three zones: safe, non-safe, theMutualAuthenticationprocess,itisareasonabledeductionsection, we analyze the efficiency of fuzz testing and explore the relationship between formal verification and fuzz testing, underscoring the potential benefits of our innovative strategy. Fuzztestingisamethodical,brute-forceapproachtodetect-
ing vulnerabilities, accomplished by supplying an extensive range of random data to uncover potential security threats. However,duetocomputationalconstraints,exhaustivevulner- ability detection for the entire 5G NSA protocol, even for a singular command, is not practical. To increase the efficiency of fuzz testing, the rule-based mutation fuzz testing strategy hasbeenproposed[20].Thisstrategyrefinesthescopeoffuzz testing to specific identifiers in line with protocol rules. Although the rule-based mutation fuzz testing strategy yields a substantial reduction in computational complexity, it canstillproducemeaningless,randomlygeneratedinputs.Asa response, we introduce a formal-guided fuzz testing strategy. This strategy complies with formal verification assumptions andgeneratesthreecategoriesofrepresentativeinputs:formal- based legal inputs, formal-based illegal inputs, and randomly generatedinputs.Whileformal-basedinputsmustadheretothe TABLE III: Fuzzing Result of User Credentials Disclosure protocol-defined rules or format, randomly generated inputs arenotboundbytheserestrictions.Thecomparativeefficiency thatanadversarycanacquiretheRNTI,whichisderivedfrom of different fuzz strategies across four distinct processes is UE identities, and RAND, a crucial identifier for generating depictedinFigure6.Adetailedperformanceanalysisofthese a session key. Unlike the boundless scenarios possible with varied fuzzing strategies is provided in the following section. black-box fuzzing, our approach uses a fixed session key Based on the guidance of formal verification in Sec- to concentrate on the impact of a MITM attack, thereby tion III-A, the RRC Connection Request command, which in- eliminating the computational waste associated with guessing cludes40bitsofUE-Identity,4bitsofEstablishmentCause, random identifiers and UE identities. and 1 bit of spare, is vulnerable to DoS or MITM attacks. Building on our previously proposed probability-based Traditional brute-force fuzz testing generates more than 245 fuzzing strategy [19], we have established a more efficient fuzzing cases, and rule-based fuzzing generates 240+24+1 method for identifying unintended vulnerabilities that prove fuzzing cases based on the defined identifiers. However, our challenging to detect via formal verification. A comparison formal guided fuzzing strategy requires only 9 fuzzing cases, between random fuzzing and our probability-based approach including one legal UE-Identity case, one illegal UE-Identity (Fig.5)revealsthatourproposedprobability-basedframework case, one random out-of-rule UE-Identity case, 2 legal/il- requires only 36.5% of the number of fuzzing cases used in a legal EstablishmentCause cases, one random out-of-rule random fuzzing strategy to detect all 43 vulnerabilities [19]. EstablishmentCause case, one legal spare case, one illegal spare case, and one out-of-rule spare case. 1077 1067 1057 1047 1037 1027 1017 107 Fig. 5: Comparison of Different Command-level Fuzzing Brute Force Fuzzing Rule-based Fuzzing Formal Guided Fuzzing Strategy Efficiency V. PERFORMANCEANDEFFICIENCYASSESSMENT Our proposed fuzz testing framework, guided by formal verification, affirms the viability of our integrative approach combining both formal and fuzz testing frameworks. In this htiw sesac gnizzuf fo rebmuN seigetarts gnizzuf tnereffid RRC Connection Request command bit-level fuzzing Authentication Request command bit-level fuzzing NAS Security Mode command bit-level fuzzing AS Security Mode command bit-level fuzzing Fig. 6: Comparison of Different Bit-level Fuzzing Strategy Efficiency Our proposed framework has the capacity not only to validatetheimpactandsecurityofidentifiers,butalsotodetect unintended vulnerabilities based on high-risk assumptions, such as an identifier set that is accessible to an adversary. Ascorroborated by the evidence presented in Section IV-B, our [2] M.Shatnawi,H.Altaleb,andR.Zolta´n,“Thedigitalrevolutionwithne- framework proves highly efficient in detecting vulnerabilities, sasassessmentandevaluation,”in2022IEEE10thJubileeInternational ConferenceonComputationalCyberneticsandCyber-MedicalSystems underscoring its potential utility in enhancing system security. (ICCC). IEEE,2022,pp.000099–000104. VI. CONCLUSION [3] A.Peltonen,R.Sasse,andD.Basin,“Acomprehensiveformalanalysis of5ghandover,”inProceedingsofthe14thACMConferenceonSecurity In this paper, we have introduced an innovative framework andPrivacyinWirelessandMobileNetworks,2021,pp.1–12. that integrates formal verification and fuzz testing to fortify [4] S.R.Hussain,M.Echeverria,I.Karim,O.Chowdhury,andE.Bertino, “5Greasoner: A property-directed security and privacy analysis frame- the security of 5G systems, effectively addressing the vulner- work for 5G cellular network protocol,” in Proceedings of the ACM abilitiesfromprotocollogictoimplementationstacks.Thedy- Conference on Computer and Communications Security. Association namic feedback loop within this framework has demonstrated forComputingMachinery,112019,pp.669–684. [5] G. Klees, A. Ruef, B. Cooper, S. Wei, and M. Hicks, “Evaluating its strength in both the refinement of undefined areas and the fuzztesting,”inProceedingsoftheACMConferenceonComputerand exhaustivedetectionofpotentialvulnerabilities.Thisworkhas CommunicationsSecurity,2018. been illuminated through an application on a continuous loop [6] S. Bratus, A. Hansen, and A. Shubina, “Lzfuzz: a fast compression-
basedfuzzerforpoorlydocumentedprotocols,”2008. in the RRC Connection Setup process, illustrating the practi- [7] D. G. Berbecaru and G. Petraglia, “Tls-monitor: A monitor for tls cabilityandeffectivenessofourproposedmethodology.Inthe attacks,”in2023IEEE20thConsumerCommunications&Networking initial phase, our framework identifies a formal attack model Conference(CCNC). IEEE,2023,pp.1–6. [8] O-RANAlliance,“O-RAN:TowardsanOpenandSmartRAN,”O-RAN through the application of formal verification. Subsequently, Alliance,no.October,2018. leveraging the protocol-level exposure of user credentials, the [9] Software Radio Systems, “srsRAN is a 4G/5G software radio suite proposed framework employs bit-level and command-level developedbySRS,”2021. [10] B. Blanchet, “Modeling and verifying security protocols with the fuzzing to execute comprehensive impact identification and appliedpicalculusandproverif,”FoundationsandTrends®inPrivacy simulate plausible attacks. As a result, by relying on the and Security, vol. 1, no. 1-2, pp. 1–135, 2016. [Online]. Available: verified impact and the security status of the identifier or http://dx.doi.org/10.1561/3300000004 [11] J. Yang, Y. Wang, T. X. Tran, and Y. Pan, “5g rrc protocol and stack commanddeterminedbythefuzztest,ourframeworkrobustly vulnerabilities detection via listen-and-learn.” 2023 IEEE Consumer reinforcesprotocol-levelassumptionsandrefinesthedetection Communications&NetworkingConference,January2023. area. Notably, this integrated approach significantly mitigates [12] Y. Wang, A. Gorski, and A. da Silva, “Development of a Data- Driven Mobile 5G Testbed: Platform for Experimental Research,” in computational complexity, transitioning it from exponential IEEEInternationalMediterraneanConferenceonCommunicationsand to linear growth. This scalability ensures that the framework Networking,2021. can accommodate larger datasets or more complex scenarios [13] I. Gomez-Miguelez, A. Garcia-Saavedra, P. D. Sutton, P. Serrano, C. Cano, and D. J. Leith, “srslte: An open-source platform for lte without a drastic increase in computational resources or pro- evolution and experimentation,” in Proceedings of the Tenth ACM cessing time, making it suitable for extensive applications in International Workshop on Wireless Network Testbeds, Experimental 5G security testing. Evaluation,andCharacterization,2016,pp.25–32. [14] J.-K. Tsay and S. F. Mjølsnes, “A vulnerability in the umts and lte Toconclude,ourresearchpresentsapioneeringsteptowards authenticationandkeyagreementprotocols,”inComputerNetworkSe- bolstering5Gsecuritybyemployinganintegrated,hierarchical curity:6thInternationalConferenceonMathematicalMethods,Models approach to vulnerability detection. This work contributes and Architectures for Computer Network Security, MMM-ACNS 2012, St.Petersburg,Russia,October17-19,2012.Proceedings6. Springer, substantially to the ongoing efforts to secure the next genera- 2012,pp.65–76. tion of wireless communications and provides a foundation [15] J.B.BouAbdo,H.Chaouchi,andM.Aoude,“Ensuredconfidentiality for future research in this domain. Further studies might authenticationandkeyagreementprotocolforeps,”in2012Symposium onBroadbandNetworksandFastInternet(RELABIRA),2012,pp.73– explore extending this approach to other advanced wireless 77. technologies to ensure robust security in our increasingly [16] 3GPP, “Universal Mobile Telecommunications System (UMTS); LTE; connected world. Mobility Management Entity (MME) Visitor Location Register (VLR) SGs interface specification,” 3rd Generation Partnership Project ACKNOWLEDGMENT (3GPP), Technical Specification (TS) 29.118, 01 2015, version 8.5.0. [Online]. Available: https://portal.3gpp.org/desktopmodules/ This effort was sponsored by the Defense Advanced Specifications/SpecificationDetails.aspx?specificationId=1601 Research Project Agency (DARPA) under grant no. [17] M. Khan, P. Ginzboorg, K. Ja¨rvinen, and V. Niemi, “Defeating the downgradeattackonidentityprivacyin5g,”inInternationalConference D22AP00144. The views and conclusions contained herein onResearchinSecurityStandardisation. Springer,2018,pp.95–119. are those of the authors and should not be interpreted as [18] M.T.Raza,F.M.Anwar,andS.Lu,“Exposingltesecurityweaknesses necessarily representing the official policies or endorsements, at protocol inter-layer, and inter-radio interactions,” in Security and Privacy in Communication Networks: 13th International Conference, either expressed or implied, of DARPA or the U.S. SecureComm2017,NiagaraFalls,ON,Canada,October22–25,2017, Government. Proceedings13. Springer,2018,pp.312–338. [19] J.Yang,Y.Wang,Y.Pan,andT.X.Tran,“Systematicmeetsunintended: REFERENCES Priorknowledgeadaptive5gvulnerabilitydetectionviamulti-fuzzing,” [1] J.Alcaraz-Calero,I.P.Belikaidis,C.J.B.Cano,P.Bisson,D.Bourse, arXivpreprintarXiv:2305.08039,2023. M. Bredel, D. Camps-Mur, T. Chen, X. Costa-Perez, P. Demestichas, [20] Z.Salazar,H.N.Nguyen,W.Mallouli,A.R.Cavalli,andE.M.Montes M.Doll,S.E.Elayoubi,A.Georgakopoulos,A.Ma¨mmela¨,H.P.Mayer, De Oca, “5Greplay: A 5G Network Traffic Fuzzer - Application to M.Payaro,B.Sayadi,M.S.Siddiqui,M.Tercero,andQ.Wang,“Lead- AttackInjection,”inACMInternationalConferenceProceedingSeries.
ing innovations towards 5G: Europe’s perspective in 5G Infrastructure AssociationforComputingMachinery,82021. Public-PrivatePartnership(5G-PPP),”inIEEEInternationalSymposium on Personal, Indoor and Mobile Radio Communications, PIMRC, vol. 2017-October,2018.
2307.06340 FernUniversität in Hagen Faculty of Mathematics and Computer Science Master’s program in Practical Computer Science Master’s thesis Securely extending and running low-code applications with C# submitted by Lennart Brüggemann, B.Sc. lennart.brueggemann@studium.fernuni-hagen.de Matriculation number 9767045 Reviewers: Dr. Daniela Keller Prof. Dr. Friedrich Steimann In cooperation with Scopeland Technology GmbH Advisor: Dipl.-Inf. Pierre-André Kotulla 28th February 2023iii Eidesstattliche Erklärung Ich erkläre, dass ich die Masterarbeit selbstständig und ohne unzulässige Inanspruch- nahme Dritter verfasst habe. Ich habe dabei nur die angegebenen Quellen und Hilfsmittel verwendet und die aus diesen wörtlich, inhaltlich oder sinngemäß entnommenen Stellen als solche den wissenschaftlichen Anforderungen entsprechend kenntlich gemacht. Die Versicherung selbstständiger Arbeit gilt auch für Zeichnungen, Skizzen oder graphische Darstellungen. Die Arbeit wurde bisher in gleicher oder ähnlicher Form weder derselben noch einer anderen Prüfungsbehörde vorgelegt und auch noch nicht veröffentlicht. Mit der Abgabe der elektronischen Fassung der endgültigen Version der Arbeit nehme ich zur Kenntnis, dass diese mit Hilfe eines Plagiatserkennungsdienstes auf enthaltene Plagiate überprüft und ausschließlich für Prüfungszwecke gespeichert wird. Statement in lieu of an oath I hereby confirm that I have written this thesis on my own and without unauthorized help of third parties. I have used only the indicated sources and tools and have marked all matter taken from them, verbatim, content-related or paraphrased, in accordance to scientific requirements. The declaration of independent work also applies to drawings, sketches or graphical representations. This work or parts thereof have not been presented to the same or any other examination authority and has not yet been published. By submitting the electronic form of the final version of the thesis I acknowledge that it will be checked for plagiarism with the help of a plagiarism detection service and stored exclusively for examination purposes. Place/Date SignatureFor Ruth and GeorgAbstract Low-code development platforms provide an accessible infrastructure for the creation of software by domain experts, also called ‘citizen developers’, without the need for formal programming education. Development is facilitated through graphical user interfaces, although traditional programming can still be used to extend low-code applications, for example when external services or complex business logic needs to be implemented that cannot be realized with the features available on a platform. Since citizen developers are usually not specifically trained in software development, they require additional support when writing code, particularly with regard to security and advanced techniques like debugging or versioning. In this thesis, several options to assist developers of low-code applications are investigated and implemented. A framework to quickly build code editor extensions is developed, and an approach to leverage the Roslyn compiler platform to implement custom static code analysis rules for low-code development platforms using the .NET platform is demonstrated. Furthermore, a sample application showing how Roslyn can be used to build a simple, integrated debugging tool, as well as an abstraction of the version control system Git for easier usage by citizen developers, is implemented. Security is a critical aspect when low-code applications are deployed. To provide an overview over possible options to ensure the secure and isolated execution of low-code applications, a threat model is developed and used as the basis for a comparison between OS-level virtualization, sandboxing, and runtime code security implementations. viiContents List of Acronyms 1 List of Abbreviations 3 Glossary 5 1 Introduction 7 1.1 Background . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 1.2 Motivation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 1.3 Related work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 1.4 Research Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 1.5 Results and contributions . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 1.6 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 2 Low-code 13 2.1 Types of low-code development platforms . . . . . . . . . . . . . . . . . . 13 2.1.1 Local . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 2.1.2 Online/Cloud . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 2.2 Types of low-code applications . . . . . . . . . . . . . . . . . . . . . . . . 15 2.2.1 Hosted in the same application . . . . . . . . . . . . . . . . . . . . 16 2.2.2 Hosted in a separate application . . . . . . . . . . . . . . . . . . . 16 2.2.3 As generated application . . . . . . . . . . . . . . . . . . . . . . . . 17 2.3 Extension of low-code applications . . . . . . . . . . . . . . . . . . . . . . 18 2.4 SCOPELAND. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 3 Supporting citizen developers in writing code 23 3.1 Static code analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 3.2 Mechanisms in code editors . . . . . . . . . . . . . . . . . . . . . . . . . . 25 3.3 Visual Augmentation Framework . . . . . . . . . . . . . . . . . . . . . . . 27
3.3.1 Overview of the AvalonEdit architecture . . . . . . . . . . . . . . . 28 3.3.2 Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 3.3.3 Applications. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 ixx CONTENTS 3.3.4 Discussion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 3.4 Improving access to APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 3.4.1 Wrapping of existing APIs . . . . . . . . . . . . . . . . . . . . . . . 36 3.4.2 API Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . 39 3.5 Custom static code analyzers . . . . . . . . . . . . . . . . . . . . . . . . . 41 3.5.1 Implementation of an analyzer . . . . . . . . . . . . . . . . . . . . 42 3.5.2 Implementation of a code fix . . . . . . . . . . . . . . . . . . . . . 43 3.5.3 Using custom analyzers in RoslynPad . . . . . . . . . . . . . . . . 44 3.6 Summary and discussion . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 4 Code security in low-code applications 49 4.1 Process isolation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 4.2 Threat model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 4.3 Approaches for securely running code . . . . . . . . . . . . . . . . . . . . . 53 4.3.1 Sandboxing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53 4.3.2 Blocking of API calls . . . . . . . . . . . . . . . . . . . . . . . . . . 55 4.4 Implementations of OS-level virtualization . . . . . . . . . . . . . . . . . . 56 4.4.1 Windows Sandbox . . . . . . . . . . . . . . . . . . . . . . . . . . . 56 4.4.2 Docker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59 4.5 Securely running code in C# . . . . . . . . . . . . . . . . . . . . . . . . . . 65 4.5.1 Code Access Security. . . . . . . . . . . . . . . . . . . . . . . . . . 65 4.5.2 Application domains . . . . . . . . . . . . . . . . . . . . . . . . . . 65 4.5.3 AppContainer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65 4.6 Summary and discussion . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72 5 Maintenance and management of custom code 75 5.1 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75 5.1.1 Usage in low-code applications . . . . . . . . . . . . . . . . . . . . 75 5.2 Versioning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77 5.2.1 Usage in low-code applications . . . . . . . . . . . . . . . . . . . . 77 5.3 Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78 5.3.1 Debugging. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78 5.3.2 Versioning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82 5.4 Summary and discussion . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85 6 Conclusions and future work 87 6.1 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87 6.2 Outlook . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89 List of Figures 91CONTENTS xi List of Listings 93 List of Tables 95 Bibliography 97List of Acronyms CVE Common Vulnerabilities and Exposures VSIX Visual Studio integration extension WPF Windows Presentation Foundation WYSIWYG What You See Is What You Get XAML Extensible Application Markup Language 1List of Abbreviations ACL access control list API application programming interface CD citizen developer CMSA code management sample application DSL domain specific language GUI graphical user interface GUID globally unique identifier IDE integrated development environment IL integrity level IPC inter-process communication LCA low-code application LCDP low-code development platform MAC mandatory access control MDM mobile device management MIC mandatory integrity control OS operating system SDK software development kit SID secure identifier UI user interface VCS version control system VM virtual machine 3Glossary Assembly A library or application that contains types and resources for use in .NET, typically a DLL or EXE file. blob An unstructured, binary representation of a data object, such as a picture or audio file. Today commonly referred to as binary large object or basic large object [145]. NuGet Package manager for .NET, developed by Microsoft. Packages fre- quently contain internal or external libraries that can be installed into a .NET project. Roslyn Compiler platform and SDK for .NET, developed by Microsoft. Provides APIs to modify, compile and interact with source code. 5Chapter 1 Introduction 1.1 Background Low-codedevelopmentplatforms(LCDPs)aimtodecreasedevelopmentandtestingcycles of software, and reduce the need for software engineers to create software using traditional programming workflows [135]. Demand outweighs the availability of professional de- velopers in both Germany [155] and the United States [150], thus companies try to fill their positions with domain experts without formal programming experience to develop their software [47]. These professionals are also called citizen developers (CDs), and, while having none or very little experience in software development, they are skilled and experienced in their particular domain [158].
LCDPs enable such experts to develop applications in their area of knowledge, the only additional training necessary is for the platform used itself. These tools usually use some variation of a What You See Is What You Get (WYSIWYG) interface to build the user interface (UI) for an application [60]. For example, by dragging and dropping buttons, text boxes, tables, or images onto a surface that will resemble the front-end later on [135, p. 15], and then setting properties like colours or text using simple editors. This contrasts with manual development of front-end interfaces, which involve programming a UI either fully in code, or combining it with a description language such as XAML (ExtensibleApplicationMarkupLanguage). WYSIWYG-editorsexistaspartofintegrated development environments (IDEs), such as Visual Studio or Eclipse, too, but still directly generate code for the developer to customize and integrate with the rest of the code base. In comparison, a low-code developer has little to no direct interaction with source code. However, what happens if the low-code platform does not provide enough possibilities to cover a domain-specific use case, such as the inability to express a certain logic, or limited options for UI-design? LCDPs still allow a varying degree of customization with additional manually written code (No-code platforms exist as well [60]). For example, the Mendix platform supports extension of their applications via so-called Java actions [83]. Microsoft’s Power Apps 78 CHAPTER 1. INTRODUCTION platform allows for additional code components [22] to be implemented. How custom code is used by the low-code platform differs between each of them. Some platforms generate nativeapplicationsforthetargetsystem(Windowsapplications, AndroidoriOSapps), for exampleMendixorScopeland[141]. Theuser-writtencodeispartofthenativeapplication in this case. Others run inside the low-code environment itself, such as the aforementioned PowerApps [29]. During this thesis, the former type of resulting application will be called generated application, the latter hosted application. The different run-time environments present unique challenges in terms of security, debugging and auditing the resulting code. 1.2 Motivation Traditionally developed software has numerous tools, techniques, and patterns available to tackle issues concerning the mentioned challenges. Debuggers exist standalone and as part of IDEs, security policing is possible through static code analysis during development time, and auditing can be facilitated by rigorous internal or external examination of the writtensourcecode. However,inlow-codeenvironments,theresultingsourcecodeisnotas readilyaccessible, sinceitisonlygeneratedwhenneeded. Whilethecodegeneratorsofthe low-code platform itself can be accessed and evaluated by normal means (since they were usually developed conventionally), the supplemental code written by citizen developers will become either part of the generated application or, in case of hosted applications, be executed during run-time. Adding or running code in an unchecked manner can present both security and maintenance issues. The Open Web Application Security Project (OWASP)1, a non-profit organization known for publishing the OWASP Top 10 [126] (a list of the ten most common security risks for web applications), issued a first draft of the Top 10 for low- and no-code applica- tions in 2021 [8]. Especially the risks ‘LCNC-SEC-06: Injection Handling Failures’ and ‘LCNC-SEC-07: Vulnerable and Untrusted Components’ highlight the possible security vulnerabilities that can be incurred by adding additional code to a low-code application. Supporting citizen developers in writing code, if they want or have to, is another aspect to consider. Instead of only offering the built-in application programming interface (API) provided by the standard library a particular low-code platform uses (like the base class libraries of .NET or Java), additional APIs can be provided. Such custom APIs may allow simplified access to the environment the code will run in (like the currently developed application or the platform itself), or a façade against the standard library (e.g., easier access to image manipulation). Providing more approachable access to common software engineering tools like version control systems such as Git or Subversion also helps in defect finding and auditing, another security hazard highlighted in the OWASP Top 10 as ‘LCNC-SEC-10: Security Logging and Monitoring Failures’ [8]. 1https://owasp.org1.3. RELATED WORK 9 This thesis will investigate the challenges and problems of user-written code in low- code platforms. Specifically, code written in the C# programming language and utilizing the .NET development framework will be the focus of the programming aspect. Possible solutions in terms of integrating user-written C# code into the low-code development environment, and its secure execution, debugging and revision will be examined. The platform SCOPELAND, further introduced in section 2.4, will be used as an example low-code platform. However, the results are not aimed towards a specific product and are discussed in a generalized form. 1.3 Related work Most of the work in the area is relatively recent, according to multiple sources [46, 75, 158] the term low-code was coined in 2014 in a report by the market research company Forrester Research [130]. There has been work on the categorization and comparability of low-code development platforms, for example, Sahay et al. present a taxonomy for LCDPs and classified eight of them [134]. Their categorization is primarily based on concrete features that are required to build an application and the features offered by the examined LCDPs. Frank et al. [46] assessed ten platforms and examined them by their common charac- teristics and features. They use a more theoretical approach based on a model that was defined before the examination of concrete platforms to prevent bias towards a specific vendor [46, p. 5]. In comparison to the other mentioned work, they also evaluate how the vendors market and place their products. As part of their assessment of the extensibility
with additionally written code for each platform, they considered the use of source code editors as well (if available), and highlighted problems with their usage and how users were supported in their use. As a key finding, they state that ‘In general, the more code editing is enabled by an LCDP, the more demanding is its use’ [46, p. 158], which lends itself to additional research, namely how to make code editing in LCDPs less demanding. The understanding and challenges of LCDPs from the perspective of developers was exploredbyLuoetal. [75]byanalysingpostsinonlinecommunities. Theirapproachleans on the extraction of data from posts on StackOverflow2 and from certain communities on Reddit3, which they use to answer several research questions to classify LCDPs based on the experience of practitioners. Testing of applications developed in LCDPs was analysed by Khorram et al. [68], including an evaluation of the support for testing in five low-code platforms and the role 2A QA-platform for professional and enthusiast software developers. Strict moderation, a voting- systemandwiki-styleeditingofotherusers’questionsandanswersaimtocreateadatabaseofhigh-quality canonical answers to problems — https://stackoverflow.com 3A social media platform for discussions of almost every topic. Discussions are thematically ordered in subreddits (a kind of forum), which every user can start and manage — https://reddit.com10 CHAPTER 1. INTRODUCTION of the citizen developer in the creation of tests for their developed applications. Their article also highlights the need to support citizen developers not only in developing an application, but also in further aspects of software development — in this case testing. For the OutSystems platform, Jacinto et al. [64] present an approach for mock-based unit testing. Although not described in detail, their approach of changing the way the OutSystems’ code generator works, adding control flow statements to call the mock code during runtime, is a form of interception also used in aspect-oriented programming. This is interesting because it shows that patching generated code can be an option in LCDPs to alter the resulting application at a low level during runtime. Outside of publications by the respective vendors, there is little independent research on the security of low-code platforms or their applications. Oltrogge et al. [122] analyse the security of Android apps generated by online application generators, by auditing the generated boilerplate code and identifying possible attack vectors and checking them against Google’s security best practices for developing apps. 1.4 Research Questions Assistance for citizen developers in writing code for LCAs varies between platforms, and often aims at more professional developers [46, p. 159]. The first question is thus derived from the issue, how to make writing code more approachable for citizen developers: RQ I: How can citizen developers in low-code environments that offer C#-based extension of their applications be supported? While citizen developers are experienced in their particular domain, they may only have basic training in programming are not expected to have a thorough understanding of software architectures, development patterns and best practices. Supporting them in writing better extensions may not be enough, as, no matter the profession, experience or education, code will always contain minor and major bugs. Since security is one of the perceived concerns in LCDPs [158], a platform must also actively address potential securityissuesthatcanarisefromcustomcode. Thisleadstothesecondresearchquestion: RQ II: How to guard against malicious or unintended harmful C# code that is written to extend low-code applications? However, security problems don’t exclusively stem from additional code written for a LCA. Vulnerabilities can also exist in external libraries used in the LCA or come by misconfiguration of data transport or storage mechanisms. The last research question deals with the collaborative usage of LCDPs, and how to minimize the risk of interference when multiple clients share a server for developing LCAs:1.5. RESULTS AND CONTRIBUTIONS 11 RQ III: How can the execution of low-code applications be isolated in a way, that additionally written C# code cannot adversely affect foreign resources on a system? 1.5 Results and contributions This thesis explores improvements to the usability of code editors for citizen developers in low-code applications. For this purpose, several libraries and example applications were developed by the author: • AframeworkthatcanbeusedtoaddcustomtextdecorationstotheAvalonEditcode editor is presented in section 3.3. This library aims to enable the implementation of as many visual augmentations, as defined and categorized by Sulír et al. [146], as possible. • The framework also provides functions to implement the display of context-based advice, that supports users in the correct usage of APIs. These advice messages are based on the work of Gorski et al. [54] and detailed in section 3.4.2. • An application that shows the benefits of wrapping existing, difficult to use APIs, derived by the work of Jugel et al. [67], was developed as part of section 3.4.1. • An example application that demonstrates the use of an AppContainer, an imple- mentation of process-level isolation using mandatory integrity control (MIC) on Windows, was developed as part of section 4.5.3. • A code management sample application (CMSA) demonstrating on-demand com- pilation of C# scripts during runtime using the Roslyn compiler platform [93] and showing basic debugging possibilities using printf debugging [11] is introduced in section 5.3.1. • The CMSA also shows how the version control system Git can be abstracted to make it more accessible for citizen developers, providing basic versioning of code, including a history and retrieval of older versions. The implementation is detailed in section 5.3.2. 1.6 Overview Chapter 2 provides an overview of low-code technology and introduces the terminology used to distinguish between the types of LCAs and LCDPs. The chapter also explains how the extension of LCAs works in practice and presents the SCOPELAND platform, which is used as an example LCDP throughout the thesis.12 CHAPTER 1. INTRODUCTION
Support mechanisms for CDs, based on static code analysis and extension of code editors, are presented in chapter 3. It also describes the implementation of a framework that enables the development of context-based visual augmentations for code editors in LCDPs, as well as the integration of custom static code analysis rules and automated code fixes. The security aspect of LCDPs is covered in chapter 4. Based on a threat model, two approaches using operating system (OS)-level virtualization to run applications in an isolated environment are examined and evaluated. Furthermore, currently available mechanisms to secure individual processes with C# are discussed, and the implementation of a process-level container using Windows’ built-in mandatory access control (MAC) is detailed. Chapter 5 describes how two commonly used techniques in traditional software de- velopment, version control and debugging, can be simplified and integrated into existing LCDPs to make them more accessible for CDs. Based on a specifically developed sample application, an abstraction of the version control system Git and the integration of the Roslyn compiler toolkit to enable simple debugging features is demonstrated. Chapter 6 summarizes the presented solutions in relation to the research questions posed previously. In addition, several ideas for further research and possible extensions to the applications implemented as part of this thesis are proposed.Chapter 2 Low-code Classifying the types of low-code platforms is a necessary step to contextualize problems and solutions, as not all of them can be applied universally to all low-code approaches. There have been efforts to categorize both low-code application (LCA) and their LCDPs, asdescribedinsection1.3. Sincethisthesisdoesn’tseektocompareoranalyseexistinglow- code platforms by features or specific vendors, a different classification based on technical characteristics is introduced. The first distinction made is between the environment the developed low-code application is running — either as part of a host platform or as a generated, native application on the system it is running on. The former approach can be further distinguished, by whether the host platform runs on a local computer or on a remote server (possibly in the cloud). These characteristics are not mutually exclusive, for example, a LCDP may support both hosted and generated applications. 2.1 Types of low-code development platforms Figure 2.1 shows the relationship between LCDPs and LCAs. LCDPs can be run either locally, as a regular application on the development system, or remotely on a web server or in the cloud. LCAs are built with LCDPs, but can run in different environments: hosted inside the LCDP itself, running in a separate application that serves as a parent for the application, or as a generated application, that runs natively on the target platform. 2.1.1 Local Installing or deploying the LCDP locally on a computer also involves setting up the environment required for developing LCAs. Depending on the types of applications that willbebuilt,thismayrequirefurthercomponents,suchasdriversorsoftwarefordebugging [125]. This can be a limiting factor for organizations, if installing third-party software is subject to security guidelines, such as the German IT-Grundschutz (‘IT base security’) compendium [21, Sec. APP.6.A4], and would require thorough analysis of any installed 1314 CHAPTER 2. LOW-CODE Low-code development platforms Local Online Low-code application types SCOPELAND/Mendix Hosted Power Apps Hosted in client Power Apps SCOPELAND Generated Online Application Generators Figure 2.1: Examples for LCDPs with different LCA output types programs. Since the LCDP would have to be installed on all devices that will be used for development, additional administrative effort is required. Unlike web applications, locally run LCDPs (or more generally: desktop applications) havetheadvantageofhavingaccesstonativeplatformAPIs, suchasWin32(forWindows) or Cocoa (for macOS) and are not limited to only those APIs available to applications running in a browser [138]. This enables direct access to system resources and hardware, which are otherwise only available through specific APIs such as WebUSB [154]. Examples for local LCDPs are Mendix Studio Pro [81] or SCOPELAND Direct Desk, the latter being examined in section 2.4. 2.1.2 Online/Cloud Running a LCDP online removes the need to deploy the development environment to the user’s devices, as only a browser is required to run the platform. An implementation of cloud-based LCDPs is Microsoft’s Power Apps platform. Figure 2.2 shows a page of the Asset Checkout sample app in its web-based designer. The same page, during runtime and populated with concrete data and running on Windows 11, is shown in figure 2.3. These kinds of LCDPs are often provided through a Platform-as-a-Service (PaaS) model running in the cloud [134], although some vendors offer platforms running in a private cloud, such as Mendix [82]. While a web-based designer doesn’t require specific deployment to the devices it will be used on, it presents a different set of issues not equally present in locally run applications: possible privacy and security problems. Workingwithandstoringdatainthe(public)cloud,especiallywhenthedataoriginates fromwithintheEuropeanUnion(EU)andisexpectedtoflowtonon-EUjurisdictions, can present legal challenges [157, p. 16] for organizations and may be undesirable for sensitive2.2. TYPES OF LOW-CODE APPLICATIONS 15 Figure 2.2: Design view of the Asset Checkout app company or user data. Depending on the jurisdiction, including a cloud service into a company’s infrastructure can also involve additional steps to satisfy security guidelines, such as those published by the German Federal Office for Information Security [143], and thus possibly negate advantages in time and effort gained by a system that does not need to run on premises. While security aspects, such as transport security (like HTTPS), are also relevant in locally running applications, they are more difficult to evaluate with PaaS models, as the responsibility for secure LCDP and LCA configuration lies with the vendor of the service.
As Oltrogge et al. discovered [122, p. 10], every examined online service was vulnerable to at least one possible attack vector. Supporting and educating citizen developers in securely configuring their applications is thus of higher importance, when online-hosted LCDPscannotbetrustedwithadequatesecuritydefaults. Securityconcernsandtechnical solution proposals will be further examined in chapter 4. 2.2 Types of low-code applications Running a local LCDP can take two forms, depending on the architecture a platform uses. In the first case, described in section 2.2.1, the LCDP is both the development environment, where the LCA is designed and configured, and the runtime-environment16 CHAPTER 2. LOW-CODE where the LCA is executed. The other way is to host the LCA in a dedicated client application, that is separate from the development environment. In this case, the LCA is developed in the main application and is then deployed to the client application. The client application can either run on the same or other computers, or on additional devices, such as smartphones. This case is discussed in section 2.2.2. 2.2.1 Hosted in the same application Running the LCA inside a host has certain advantages. For one, it simplifies deployment, especially when it’s planned to not only build a single one-off, but multiple applications. Only the host LCDP has to be installed and is used for development and as execution environment. The LCA doesn’t have to be installed separately (with possible additional dependencies), and multiple LCA can be run in the same environment. One example of this is the SCOPELAND Direct Desk, which supports this case in interpreter mode [120, p. 9], and is introduced in detail in section 2.4. The disadvantage of this approach is that it circumvents the native distribution chan- nels of the operating system the application will run on. For example, if a company administrates a fleet of mobile devices remotely, for example via mobile device manage- ment (MDM), it would be more difficult to distribute a LCA through mobile app stores (such as the Google Play Store or Apple’s App Store), since only the host app could be installed on the devices. If the host app does not support provisioning of the apps it should run, it is more difficult to install additional LCAs remotely. If a LCA was available as a generated application (see subsection 2.2.3), the executable or application package (for example APK files1 in Android) could be distributed as any other app on the platform. This issue is not limited to mobile devices, as remote management of client devices is also commonfor regular computers in large networks, for example using softwarelikeMicrosoft Endpoint Manager [110]. 2.2.2 Hosted in a separate application A derivative of running LCA locally within the host LCDP is running it in an additional application (client) outside the host. This is illustrated by Microsoft’s Power Apps application, that runs on Windows, Android, and iOS [29]. The LCAs themselves are developed using a browser-based tool (detailed in section 2.1.2), stored online and can then be downloaded into the Power Apps app on the desired target platform. Figure 2.3 shows the Asset Checkout sample application running inside Power Apps client on Windows 11. Running the LCA in a separate application has the advantage that not the full LCDP has to be installed on the target device, only a smaller client program. Since in this 1An Android package contains the compiled application, resources, and metadata to distribute and install an app on the device — https://developer.android.com/guide/components/fundamentals2.2. TYPES OF LOW-CODE APPLICATIONS 17 Figure 2.3: Power Apps Asset Checkout on Windows 11 example, Power Apps does not offer an on-premises installation, it’s difficult to compare the space and hardware requirements. According to the Windows Store page for the Power Apps app [98], it requires about 140 MB of hard disk space and a device with 1 GiB of RAM — likely less than the full development environment would require. A smaller memory footprint is also beneficial, especially on mobile devices, as installation of large apps is undesirable from a user’s perspective [13]. This approach also offsets some disadvantages of installing the full host application on a device mentioned in subsection 2.2.1. While the LCAs themselves still aren’t distrib- uted through the operating system’s native channels, the client takes care of listing and downloading the apps available online. 2.2.3 As generated application Natively generated applications are the last possible form of LCAs. The LCDP translates the LCA into an application that runs on the target platform as any other conventionally developed program. Examples for this are Mendix, which can generate native Android and iOS apps using React Native [78], or SCOPELAND, which supports building both18 CHAPTER 2. LOW-CODE desktop and web applications (presented in detail in section 2.4). The general advantage of generated LCAs is that they can be deployed and run independently of either the LCDP or a separate client. This minimizes the cost of distributing the LCA, if previous processes, such as technical infrastructure and existing knowledge, from existing (non low-code) applications are already in place and can be quickly adapted for new programs. This independence is also an important aspect for future maintainability: since generating a native application requires source code in some form, this source code can potentially be used and further developed without the original LCDP, for instance, should the vendor stop supporting their product later on. However, altering the generated source code has the drawback that changes to it cannot be ported back into the original LCDP, since that would require essentially a reverse-interpretation of code into the internal format of the LCDP. Thesourcecodecanalsobethestartingpointformoretraditionalsoftware-engineering methods. Static program analysis, gathering information about an application without executing it [32], can for instance be used to check the source code for possible inadequate function calls or parameters, such as insecure methods (for example without or outdated encryption) to connect to remote web servers. This is especially important if additional scripting code, handwritten by the citizen developers, was generated into the LCA. While even the automatically generated code cannot be expected to be free of security issues
[122], code written by users without formal software development training should not be trusted by default either. 2.3 Extension of low-code applications As their name implies, low-code applications can still contain a certain amount of cus- tom code written by the users. Both hosted and generated applications can be extended that way. In SCOPELAND, these extensions are called scripts and are used to imple- ment complex logic, that cannot be expressed with available functionality, or to interface with third-party software [120, p. 68]. In generated applications, the additional code is automatically embedded into the resulting code created by the LCDP [120, p. 47]. Supposethatauserwantstoexecuteadditionallogicwhenabuttonintheirapplication is clicked. The user doesn’t need to know how exactly the button clicked event has to be implemented, the code generator produces the necessary scaffolding code and inserts the additional code written by the user into the method body of the event function. Listing 2.1 shows a simple example how such scaffolding code could look in WPF (Windows Presentation Foundation). Mendix uses a similar process when generating custom Java actions [83]. Unless there are additional checks in place that verify the custom code inserted into the application, this presents possible security risks. For example, a user could leave2.4. SCOPELAND 19 1 public partial class SampleWindow : Window 2 { 3 public SampleWindow() 4 { 5 sampleButton.Click += OnSampleButtonClicked 6 } 7 8 private void OnSampleButtonClicked(object sender, RoutedEventArgs e) 9 { 10 /// User code gets inserted here 11 } 12 } Listing 2.1: Example of scaffolding code for a click event on a button in WPF debugging statements, which print unsanitized user data into a publicly accessible log, in theapplication. Amaliciousdevelopercouldtrytobreakoutoftheapplicationbyreading foreign files off the hard disk, or send sensitive data to a remote web service. Security analysis of user-written script code in generated applications and approaches to run code isolated will be discussed further in chapter 4. While adding some small code fragments to the application may not be a problem for an experienced user, a citizen developer without programming training might struggle even with simple expressions. Supporting citizen developers in writing code, for example by providing specifically customized APIs or visual clues in the editor, is therefore also a responsibility of the LCDPs. A framework for the development of visual augmentations for a code editor and other methods to support developers are introduced in chapter 3. 2.4 SCOPELAND SCOPELANDisalow-codeplatformmadebytheGermancompanyScopelandTechnology GmbH2.Itisprimarilyaimedatbuildingapplicationsfromneworexistingdatabases, that is,thedatabaseistheprimaryelement,andtheapplicationisbuiltaroundit[120,p.12]. In additiontothedatabasethatcontainstheprimarydatafortheapplication, asecondmeta- database is individually created. The meta-database contains supplemental information [120, p. 32], such as allowed ranges for values, calculated columns or plausibility rules. This also enables the assignment of logical names to tables and columns, so user-friendly names, independent of length or character set constraints, can be used. Citizen developers might not be familiar with the technical names used internally to describe the database or the limitations imposed by the database system. For example, a column could have the logical name Supervisor place of residence, which would require special handling (such as 2www.scopeland.com20 CHAPTER 2. LOW-CODE explicit quoting due to spaces, escaping of special characters, or consideration of name length limits) if used as a physical name. Logical names can also be used for localization, since they can be translated to support multiple application languages independent of the physical names from the database. SCOPELANDs primary development environment is called the SCOPELAND Direct Desk [120,p.9],aWindowsprogramusedtobuild,configureandgeneratetheapplications. After a table is described with metadata, it can simply be opened and displayed, including the main columns of tables referenced via foreign keys [120, p. 33]. Figure 2.4 shows such a table opened in Direct Desk. In this case, the referenced sector and country columns are already resolved to the concrete values their foreign keys refer to. Figure 2.4: A table opened in SCOPELAND Direct Desk Based on this table, a simple application can already be created. For example, dis- playing the currently selected data set in a window, with a UI automatically derived from the table’s metadata and enabled editing capabilities, can be achieved by selecting the table to be displayed as a form. As shown in figure 2.5a, the sector and country fields are displayed as a drop-down box, which contain only the values available in their respective table. The data in form can be customized, for example, to display only certain columns or apply custom logic, such as sorting. Visually, all elements can be rearranged freely and formatted (such as fonts and colours). Figures 2.4 and 2.5a show examples of an application that runs locally in a host environment, as introduced in subsection 2.2.1. Hosting an application in a separate application (subsection 2.2.2) is not supported in SCOPELAND; however, it is possible2.4. SCOPELAND 21 to generate a native application as described in subsection 2.2.3. SCOPELAND supports multiple target platforms, such as WPF [140, p. 4], ASP.NET or Java Server Faces (JSF) [120, p. 9]. Figures 2.5b, 2.5c and 2.5d show generated versions for each of the target platforms of the application originally hosted inside the Direct Desk (figure 2.5a). While the WPF version can be told apart by the native Windows title bar and control designs, the ASP.NET and JSF version running in a browser are virtually indistinguishable from each other. Code generation for native applications is internally facilitated by exporting the re- presentation of the hosted version of the application into an XML-based format called XDAML [120, p. 56]. The XDAML file contains no platform or database-specific code.
The code generator for the target platform then translates the XDAML file into source code and uses the platform’s development toolchain (for example Visual Studio [139]) to compile a native application. The availability of the source code also means there is less vendor lock-in, as at least the source for the generated application can also be edited and run outside SCOPELAND [141].22 CHAPTER 2. LOW-CODE (a) SCOPELAND Direct Desk (b) WPF Hosted, same application Generated, native Windows application (c) ASP.NET (d) JSF Generated, native web application Generated, native web application Figure 2.5: Examples of hosted and generated SCOPELAND applicationsChapter 3 Supporting citizen developers in writing code Ungar et al. [151] describe the concept of immediacy in programming, that is, a perceived connectedness of the programmer to the development environment — similar to how a race car driver can feel the connection of their finely tuned vehicle to the track surface, just by subtle changes experienced through the steering wheel. They distinguish between three types of immediacy: temporal, spatial and semantic. Temporal immediacy describes the delay between an event and its effect, for example, how quickly a programming environment can highlight an error made by the developer. Spatial immediacy refers to the physical distance, how close the visual notification of an error is to the faulty line of code. Semantic immediacy is the mental effort required to connect an error message to its cause. Their article concludes with an important point, that is not only relevant to professional software developers, but can be applied to anyone using code editors: ‘ Attaining a reasonable level of immediacy is a precondition for effective debugging and can serve as a useful guide to the design of all aspects of programming environments. ’ This chapterwill presentexisting researchon code editors and APIs, and howthey can be applied to improve the development experience when extending low-code applications with additional code. As part of this thesis, several of these ideas were used to build a programming framework that utilizes the code editor AvalonEdit 1 and allows fast and modular implementation of extensions that can help citizen developers in writing code for LCDPs. 1http://avalonedit.net 2324 CHAPTER 3. SUPPORTING CITIZEN DEVELOPERS IN WRITING CODE 3.1 Static code analysis As discussed before, the code written by citizen developers will either become part of the generated source code of an LCA or stored and run as part of a hosted LCA. This enables the use of static code analysis, an automated evaluation of the information exposed by the source code of an application, without actively executing it. A more formal definition was made by Prähofer et al. [128]: ‘ Static code analysis works by analyzing the static structure and the ele- ments of a program without actually executing it. It is therefore usually based on the source code of a program or an intermediate representation thereof. ’ This contrasts with dynamic code analysis, which gathers information on programs during their runtime, or, as defined by Binkley [14], ‘takes program input into account’. Using static code analysis to find problems in code is not a new concept. In 1969, the group for the standardization of COBOL in the US Navy, led by Grace Hopper, developed a COBOL preprocessor called NAVPREPILE-C. It ran the code of a program against a setof validations, suchas checkingforsyntaxerrors ornon-standard statements, to reduce the time required for debugging and recompilation [16, p. 124]. A more recent example, which lends its name to tools until today 2, is lint, a program to find defects in C source code files, which was published in 1978 [66]. Today, analysers of these kind are common, both directly integrated into IDEs (for example Roslyn [93]) and as separate programs (such as FindBugs, a static code checker for Java [73]). Static code analysis has multiple applications; it can not only be used to find errors in code, but also to check statements for problematic method calls (such as the use of insecure cryptography algorithms [161]) or to enforce a specific code style. A simple example is the concatenation of two strings using the String.Concat() func- tion in C#, which has the signature shown in listing 3.1. 1 public static string Concat (string str0, string str1); Listing 3.1: Signature of the String.Concat() method overload for two strings in C# Thefunctiontakestwostrings(str0andstr1)andreturnsanewstringcontainingthe result of the concatenation (as, just like in Java, strings in C# are immutable). In listing 3.2, this function is invoked, but the return value is ignored, as a user could erroneously assume that the concatenation is performed directly on one of the input variables. Writing this code in Visual Studio will cause a suggestion from the static code analysis (that runs per default in the background) to appear, that looks similar to the one in figure 3.1. 2For example ESLint, a linter for JavaScript — https://eslint.org3.2. MECHANISMS IN CODE EDITORS 25 1 var str0 = "Hello"; 2 var str1 = "World"; 3 string.Concat(str0, str1); Listing 3.2: Ignoring the return value of the String.Concat() function Besides the hint itself, messages like this often also include some tips on how to resolve the issue. Code analysis rules are often assigned a unique identifier (CA18063 in this case) combined with a link to a website with additional information. Method calls Concat but does not use the new string instance that the method returns. Pass the instance as an argument i CA1806 to another method, assign the instance to a variable, or remove the call if it is unnecessary. Figure 3.1: Replica of a Visual Studio static code analysis suggestion, based on [86] Staticcodeanalysiscanalsodetecterrorsthatmakethecodenotcompilablewithoutac- tually having to compile the code. Syntax errors, such as missing semicolons or misspelled (and not existing) functions can be detected during development time, before running the compiler and having to wait for error messages. As mentioned before, potential security issues can also be detected, for example code that is prone to SQL injection4[87] or uses
broken cryptography algorithms such as DES [88]. Implementing custom static code analysis rules is possible and detailed in section 3.5. 3.2 Mechanisms in code editors Both simple and advanced code editors usually have some basic visual aids in common. nano5, a minimalistic text editor for the command line and displayed in figure 3.2a, supports line numbers and syntax highlighting for a selected number of languages (which can be extended). Multipurpose text editors like Notepad++6 may support more features. (cid:12) For example, code folding (the red symbol on the left side), which collapses a certain region (like the body of a function) to temporarily reduce its used space, or highlighting of the currently selected line as shown in 3.2b. MoreadvancededitorsaspartofIDEscanincludeadditionalvisualhintsfromexternal sources, such as code analysis. Figure 3.2c shows an example from Visual Studio 2022, 3‘Do not ignore method results’ [86] 4SpeciallypreparedstringscanbeusedtoinjectcodeintouncheckedSQLstatementstoenableattacks on the underlying database, such as executing arbitrary code or accessing private data [149] 5https://www.nano-editor.org 6https://notepad-plus-plus.org26 CHAPTER 3. SUPPORTING CITIZEN DEVELOPERS IN WRITING CODE (a) nano, text editor for the command line (b) Notepad++, a text editor for Windows (c) Visual Studio 2022 IDE Figure 3.2: Visual features in different code editors which adds numerous extra indicators: • In line 1, an inline parameter name hint is displayed, which shows the name of the method parameter from line 3. • Line 4 displays a warning from static code analysis directly at the affected place (inline diagnostics, an example for spatial immediacy), the relevant code is also underlined. • The opening and closing braces in lines 4 and 9 are connected by a dashed vertical line, indicating their pairing. • The return keyword in line 6 is colourized with the same background colour as the type of the return value (int) in line 3. • To the right of the line numbers is a vertical indicator showing saved (green) and unsaved changes (pale yellow) in the file. • Line 8 shows an indicator for a recursive call on the far left, and a small icon of a screwdriver right of the line numbers signalling an available refactoring action. Sulíretal. callthesekindsofindicators‘visualaugmentations’andpresentanextensive taxonomy [146] with 29 different attributes distributed among 7 dimensions based on the study of over a hundred different tools for code editor augmentations. Taking the inline parameter hint previously shown as an example, it would be classified as an augmentation based on code, representing a string and displaying text directly in the code, at a certain character, which can be not interacted with and is implemented in an existing IDE.3.3. VISUAL AUGMENTATION FRAMEWORK 27 The amount of possible combinations of all attributes is immense, and presents an opportunity to exactly tailor a particular augmentation to an existing use case in a low- code environment. This thesis proposes a framework that enables the quick development of custom augmentations for a code editor to support citizen developers when writing additional code for a LCA. As concrete requirements will vary based on the experience of usersandthescopeofthecodeaddedtotheLCA,theframeworkwillprovideextensibility points, that allow for a wide amount of different visualizations to be developed. 3.3 Visual Augmentation Framework The taxonomy of augmentations for source code editors by Sulír et al. [146] shows the many possibilities for additional visual indicators that can support the user. As shown in section 3.2, even minimalistic editors support basic features like syntax highlighting and line numbers. Advanced IDEs can supply more in-depth information about the code, such as context-dependent content depending on code analysis or visual indicators for specific code elements beyond syntax highlighting. However, these are limited to the IDE itself and are unavailable in embedded editors that a LCDP might use. Extending such an editor is an option to provide a citizen developer with additional information, guide him towards the correct usage of certain APIs or show interactive help texts. Embeddable source code editor controls are available for many programming frame- works. Examples are the Scintilla 7 editor for C++ (with ports available for other languages, such as Java and C#) or RoslynPad 8, a cross-platform C# editor based on AvalonEdit, that can also be embedded in other applications. The framework introduced in the following sections utilizes the extensible rendering process of AvalonEdit [57] to quickly create custom visual augmentations, that can be tailored to the specific use-cases a LCDP wants to help its users with. AvalonEdit was chosenasthefoundationforimplementingtheframework, sinceitisfree, open-source, and provides extension points to customize the rendering process for the text display (detailed in section 3.3.1). Furthermore, as of the time of writing, it is still actively maintained, while other projects, such as a .NET port of Scintilla9, have not received recent updates or maintenance. Other available code editors for .NET, including AvaloniaEdit10 or RoslynPad already use AvalonEdit as basis, and it is widely used with over 4.6 million downloads [121] to date. Whiletheframeworkaimstosupportasmanyofthedimensionsandattributesdefined by Sulír et al. as possible, there are certain limitations, mainly due to the nature of the framework(anextensiontoanexistingeditor)andthelackofusefulnessofseveralpossible 7https://www.scintilla.org 8https://roslynpad.net 9https://github.com/jacobslusser/ScintillaNET 10https://github.com/AvaloniaUI/AvaloniaEdit28 CHAPTER 3. SUPPORTING CITIZEN DEVELOPERS IN WRITING CODE combinations of attributes. For example, the dimension IDE is limited to existing, as the framework was developed with a specific editor in mind and cannot be used as an external tool. The attributes are not arbitrarily combinable, either because they are mutually exclusive (mainly in the target and type dimensions), or because there is no way
to access them (except code, everything from the source dimension). There are also some limitations that stem from the underlying UI framework (WPF). While the visualization canbetheoreticallyanyUIelement(fromsimpletextstringstocomplexdiagramcontrols), not all of them support all interactions, such as tooltips or interactivity in general. 3.3.1 Overview of the AvalonEdit architecture As the frameworks builds on the extensibility points of AvalonEdit, a short overview of its architecture based on [57] will be given. There are three different kinds of objects thatcanbeaddedtoextend theeditor: classesderivedfromVisualLineElementGenerator and implementations of the interfaces IVisualLineTransformer and IBackgroundRenderer. Each instance of an editor has a list for each particular type that will get evaluated during the rendering process. Figure 3.3 shows the transformation sequence that is used to render text from the initial internal structure in the editor to the output on the screen. An instance of the DocumentLine class contains the plain text of a single line as displayed in the editor. At that stage, the text can be modified by inserting additional elements into the text. These can be more text strings, hyperlinks or any custom UI element, from a simple button to more complex layout panels containing multiple other controls. This is enabled by in- stances of the abstract VisualLineElementGenerator class. Derivatives have to implement two methods that will be called automatically for each line during the rendering process: The first is int GetFirstInterestedOffset(int startOffset), which has to return either the offset in text the generator wants to insert an element, or the value -1 if the gen- erator will not modify the text in that particular line. The other is VisualLineElement ConstructElement(int offset), which enables the construction of a VisualLineElement (which contains the UI element to be added) that gets inserted at the supplied offset. At the next stage, a VisualLine is built by the editor, and implementations of IVisualLineTransformer will have their void ColorizeLine(DocumentLine line) method called, which can be used to alter visual elements in the particular VisualLine, such as changing fore- and background colours or setting font-related properties. This can, for example, be used to implement syntax highlighting by colouring specific keywords in the text. The result is a transformed VisualLine, which is then processed into one or more TextLines, which are used to calculate the flow of the text. As the content (and length) of a line might have changed, it is required to fit the text into the space available to the editor to use features such as word-wrapping (if enabled). This is handled by AvalonEdit internally, which uses existing classes from the System.Windows.Media.TextFormatting3.3. VISUAL AUGMENTATION FRAMEWORK 29 DocumentLine Element generator Inserts additional custom controls VisualLine Elements of a line in the document such as text, links or custom controls. Line transformer Transforms elements in the line, like adding syntax hightlighting VisualLine Transformed elements of a line for example due to syntax highlighting. TextLine TextLine Split VisualLines to enable word wrapping Background renderer Performs extra rendering, like drawing Screen arbitrary geometry on the background Figure 3.3: Rendering pipeline of AvalonEdit. Adapted from [56] namespace [105] for that task. The final extension point is the IBackgroundRenderer interface. Implementations canusethevoid Draw(TextView textView, DrawingContext drawingContext)methodto draw arbitrary visual content on various layers (such as the background area, or the layer containing the blinking caret). For example, indicators for errors or warnings (like underlining text with squiggly lines) can be implemented that way. 3.3.2 Implementation The augmentation framework was developed by the author of this thesis, its source code is publicly available on GitHub [18]. This section explains the core concepts and presents two examples on how the framework can be used. The three extension points introduced in section 3.3.1 are the basis used for the im- plementation of the framework. An augmentation is represented by an object of the Augmentation class, which manages instances of the three extension objects internally. Each augmentation is responsible to transform a specific part of the displayed text, which is determined by assigning one or more fixed strings, or one or more regular expressions that match specific sequences of characters or words in the text. To determine what kind of transformation should be applied to the text, a simple fluent API to specify colours, font settings or interactive elements was developed. Internally, these API calls build and configure objects of the three extension classes and add it to the instance of the Augmentation class that gets currently configured. For demonstration purposes, augment-30 CHAPTER 3. SUPPORTING CITIZEN DEVELOPERS IN WRITING CODE ations to provide configurable syntax-highlighting for Smalltalk code were implemented. Smalltalk was chosen for its concise syntax, the sample ‘Smalltalk syntax in a postcard’ [156], shown as part of figure 3.4, shows most of Smalltalk’s keywords and language constructs in a single method and lends itself to show many augmentation styles at once. (a) Smalltalk code without augmentations (b) Smalltalk code with augmentations Figure 3.4: Syntax highlighting augmentation for Smalltalk code The implementation, shown in listing 3.3, consists of six augmentations for each of the syntax elements to be decorated. A regular expression for a particular syntax element was defined and set for each of the augmentation. Afterwards, different styles, such as foreground colours or font options, were added. The result is shown in figures 3.4a (the plain text without syntax highlighting) and 3.4b (with augmentations applied). For example, comments are shown in light green colour with italicized font style and keywords are displayed in blue and with bold font weight. This example uses exclusively the IVisualLineTransformer extension point from AvalonEdit. An example utilizing both the VisualLineElementGenerator class and the IBackgroundRenderer interface is shown in figure 3.5. In this case, a citizen developer may haveusedahashingfunctionusingtheSHA-1algorithm. AsSHA-1isnolongerconsidered
secure [69], an augmentation was developed to warn the user upon usage by underlining the method call and displaying a tooltip showing a text that suggests alternatives. Figure 3.5: Augmentation warning of the use of a SHA-1 method The code required to implement such an augmentation is shown in 3.4 and consists of only five lines, defining the regular expression used to match the function call, the text for3.3. VISUAL AUGMENTATION FRAMEWORK 31 1 public static class SmalltalkHighlighting 2 { 3 public static Augmentation[] GetAugmentations(TextView textView) 4 { 5 var parameterRegex = new Regex(@":\w+"); 6 var symbolRegex = new Regex(@"[$#]\w+"); 7 var numberRegex = new Regex(@"\b\d+(\.\d+)?\b"); 8 var messagesRegex = new Regex(@"\w+:"); 9 var commentRegex = new Regex("\"(.|\r|\n)*?\""); 10 var stringRegex = new Regex(@"\'((.|\r|\n)*?)\'"); 11 var keywordsRegex = new Regex(@"\b(self|super|true|false|nil)\b"); 12 13 var comments = new Augmentation(textView).ForText(commentRegex) 14 .WithForeground(Brushes.LightGreen).WithFontStyle(FontStyles.Italic); 15 16 var keywords = new Augmentation(textView).ForText(keywordsRegex) 17 .WithFontWeight(FontWeights.Bold).WithForeground(Brushes.RoyalBlue); 18 19 var messages = new Augmentation(textView).ForText(messagesRegex) 20 .WithForeground(Brushes.Orange); 21 22 var numbersAndStrings = new Augmentation(textView).ForText(numberRegex, stringRegex) 23 .WithForeground(Brushes.MediumAquamarine); 24 25 var symbols = new Augmentation(textView).ForText(symbolRegex) 26 .WithFontWeight(FontWeights.Bold).WithForeground(Brushes.DarkRed); 27 28 var parameters = new Augmentation(textView).ForText(parameterRegex) 29 .WithFontWeight(FontWeights.Bold); 30 31 return new[] { keywords, messages, numbersAndStrings, symbols, parameters, comments }; 32 } 33 } Listing 3.3: Implementation of the SmalltalkHighlighting class the tooltip, and the definition of a Geometry11 for the decoration. Here, a pre-configured decoration in the shape of a horizontal square bracket is used. Custom geometry can be injected by using a delegate method that takes a Rect as input to define the bounds of the decoration and returns an implementation of the Geometry class. The decoration is drawn by an implementation of IBackgroundRenderer on the background layer of the editor area using the coordinates from the bounding box of the text to adorn. The tooltip 11An abstract class to define the geometry of arbitrary 2D-shapes in WPF — https://docs.microsoft. com/en-us/dotnet/api/system.windows.media.geometry32 CHAPTER 3. SUPPORTING CITIZEN DEVELOPERS IN WRITING CODE isn’t part of the drawing, but a property of a TextBlock12, that is inserted as an inline control (using a VisualLineElementGenerator) and replaces the plain text previously at its offset in the document. 1 var underlineAugmentation = new Augmentation(Editor.TextArea.TextView) 2 .WithDecoration(UnderlineBracket.Geometry) 3 .WithDecorationColor(Brushes.Red) 4 .WithTooltip("SHA1 is cryptographically broken, please use a currently secure function like ,→ SHA-512.") 5 .ForText(new Regex(@"\.HashWithSha1(.*)?\)")); Listing 3.4: Implementation of the SHA-1 warning augmentation Figure 3.6 shows a high-level overview of the augmentation framework. Classes and interfaces that are part of AvalonEdit are coloured in green, implementations of these and additional classes that were developed for the framework are blue. An Augmentation is the core component of the framework. The class manages lists of each individual extension point implementations, and has access to an instance of AvalonEdit’s TextArea class, which exposes properties to add and remove elements to its rendering pipeline. The AugmentationExtensions class contains the methods used to configure each Augmentation in a fluent syntax style, shown in listing 3.4, for example. << >> << >> << >> interface abstract interface IBackgroundRenderer VisualLineElementGenerator IVisualLineTransformer DecorationRenderer OverlayGenerator TextTransformer 0..* 0..* 0..* << >> abstract Augmentation AbstractMargin 0..* 1 configures MarginDecoration TextArea AugmentationExtensions Figure 3.6: Augmentation framework class diagram 12A simple WPF control to display formatted text — https://docs.microsoft.com/en-us/dotnet/api/ system.windows.controls.textblock3.3. VISUAL AUGMENTATION FRAMEWORK 33 3.3.3 Applications While syntax highlighting or text decorations for source code are nothing new, the idea behind the framework is to provide augmentations for specific use-cases that are not common enough to be supported by available editors by default. Although the framework was developed in the context of LCDP, its usage is not limited to them — any interested user or organization using AvalonEdit can utilize it to develop augmentations. A concrete example for an application of the framework is the clear text display and number display mode in SCOPELAND [120, p. 58]. Every table and field in SCOPELAND has a unique numeric identifier with a prefix of the object it refers to (like T1000 for a table), which can be used to express relations between tables. Figure 3.7 shows a simplified database relation between a product that is assigned a single category. If the user wanted to refer to the category of a product in table T1000 for use in a script or as part of a condition, they would use the expression F1001.T2000.F2001. In number display mode, this is both unwieldyandhardtounderstand. Thealternativeclear text display mode, however, would show Category ID.Categories.Name in this case, which is easier to read. Products (T1000) Categories (T2000) PK Product ID F1000 PK Category ID F2000 FK Category ID F1001 Name F2001 Name F1002 Figure 3.7: Simple relation between products and categories This mode can be easily implemented with the augmentation framework. Given a
mapping of the fields of a table and the desired names, the names can be overlaid over the identifiers, as shown in figures 3.8a and 3.8b, with the source in listing 3.5. (a) Number display mode (b) Clear text display mode Figure 3.8: Two different display modes for identifiers in code 3.3.4 Discussion The augmentation framework can be used to improve the different types of immediacy, as introduced at the beginning of this chapter. Augmentations fall primarily in the spatial categories. As all additional visual elements generated by the extensibility classes of34 CHAPTER 3. SUPPORTING CITIZEN DEVELOPERS IN WRITING CODE 1 public static IEnumerable<Augmentation> GetAugmentations(TextView textView) 2 { 3 foreach (var (field, name) in GetFieldMapping()) 4 { 5 yield return new Augmentation(textView) 6 .ForText(field) 7 .WithBackground(Brushes.DarkGray) 8 .WithForeground(Brushes.White) 9 .WithOverlay(name); 10 } 11 } Listing 3.5: Implementation of the augmentation for the clear text mode AvalonEdit as part of the rendering process, they are available as soon as the editor has finished loading. Temporal immediacy is thus not a relevant part of the augmentations built with the framework, as their display is usually instantaneous upon activation, and the developer has little influence (short of explicitly adding delays) over their timing. Spatialimmediacyismosteasilyachievedbythevariouscolouringoptionsprovidedbythe framework, astheydirectlyadornthetextstringstheyareappliedto. Thesameappliesto text decorations, such as the underlined method call from figure 3.5. Semantic immediacy largely depends on the developer adding concise information to the augmentations, such as tooltips or text replacements. Since the editor itself does not support further user interaction (such as debugging, or showing more diagnostics in tool windows or menus), there are limited opportunities to improve the display of semantically related information. The dimensions and their attributes from the taxonomy of Sulír et al. [146] can now be compared against the possible augmentations build with the framework. The following sections give a short explanation of each dimension and how they can be implemented, the attributes of each dimension are denoted in italics. Source The source dimension describes the origin of the data that is represented by the aug- mentation. Searching for character sequences via simple comparison or regular expression is essentially static code analysis. However, since it is possible to pass delegates to an augmentation, it is theoretically possible to execute arbitrary functions which in turn could provide data from other sources. For example, a developer could write a function that passes the code written in the editor to an external library. If the library built and run the code, perform some kind of dynamic analysis, and return specific offsets in the input code that should be augmented, this would be a form of dynamic code analysis. While other attributes of the source dimension would not be impossible to implement, the3.3. VISUAL AUGMENTATION FRAMEWORK 35 primary source for the augmentations is thus code. Type The type denotes the possible states an augmentation can take, for example it can be simply displayed or not (boolean), or show an icon from a fixed collection of images (fixed enumeration). The types are largely dependent on the implemented augmentations them- selves. If the developer creates multiple augmentations to implement syntax highlighting (as in figure 3.4b), the augmentations represent a fixed number of syntax elements (com- ments, symbols, messages and so on). The switch between numeric and clear text display from subsection 3.3.3 is an example of variable enumeration, since the possible field and table identifiers can come from an external source with the exact number of combinations unknown, or even determined during runtime as new fields and tables are created. Visualization The visualization dimension depicts in what way the augmentation is displayed. The framework can be used to implement all types of visualizations. Colour and text are for example shown in figure 3.8b. The underline decoration from figure 3.5 can be substituted for custom icons and graphics, as WPF supports both drawing generic shapes and images loaded from files. Location The location dimension describes the general position an augmentation is placed. In code is shown is most of the previous examples, such as figure 3.5. Left and right can be used to show text, glyphs, or images in the left margin of the editor or on the right end of a line, shown in figure 3.9. Figure 3.9: A star glyph and a floppy disk image shown to the left and right of the code area in the editor Target The positioning of the augmentation in the editor is defined by the target dimension. As the augmentations are generally based on offsets of the text in the editor, it is possible for36 CHAPTER 3. SUPPORTING CITIZEN DEVELOPERS IN WRITING CODE an augmentation to span a single line, line ranges, character ranges or the whole file. The Smalltalk syntax highlighting example from figure 3.4b shows all options, except for an augmentation of the entire file, which can easily be implemented by a regular expression that matches every symbol in a file. Interaction Theinteractiondimensiondescribesthepossibleformsofinteractionwithanaugmentation. All available attributes can be implemented with the framework. Popover functionality is shown in figure 3.4, which displayed a tooltip when hovering with the mouse over an augmentation. It would be possible to display a more sophisticated tooltip, for example containing a link to a help page; thus navigation is also a viable option. In figure 3.8b several strings are replaced with text blocks to show them with different fore- and background colours. As any available control can be inserted in the code, which includes interactive controls like calendars or text boxes, the augmentations also support changes. IDE The IDE dimension denotes whether the augmentation is implemented for an existing IDE or editor, or as an external tool specifically created for the augmentation. As the framework build to extend AvalonEdit, it is implemented for an existing editor. 3.4 Improving access to APIs 3.4.1 Wrapping of existing APIs The augmentation framework introduced in the previous chapter is essentially a wrapper
over the existing extensibility points offered by AvalonEdit. It provides a simplified interface to apply colouring or decoration of text elements with only a few lines of code. Implementation of the necessary classes and logic required to build the augmentations is abstracted away from the user and exposed via an API that is specifically tailored to lower the barrier for creating them. A similar approach can be taken to offer an entry point for APIs that are either difficult to use correctly, or require special knowledge to prevent potential configuration problems, such as security issues. Jugel et al. [67] categorize wrapper libraries as a domain specific language (DSL), ‘which allows expressing the concepts of a specific domain that would be much harder to program’. More specifically, they are a variation of an internal DSL, that, in comparison to an external DSL, does not consist of any new syntactic elements that would require a different development environment. Wrapper libraries exist to ‘provide a mapping, refinement, or reduction of an underlying API’s existing syntax’ [67], which makes them suitable for use in an API that aims primarily towards citizen developers.3.4. IMPROVING ACCESS TO APIS 37 For example, suppose a citizen developer has to write code to calculate the SHA512 hash of a string. This is an easy task, as the .NET API provides readily available functions to hash data with various hashing algorithms. However, usage of the API requiresknowledgeaboutreadingaUTF-8inputstringintoabytearray,callingthecorrect function of the API and converting the resulting hash back into a string — something a citizen developer might not be acquainted with. A correct implementation may look similar to the one in listing 3.6. 1 public static class HashFunctions 2 { 3 ///// <summary> 4 ///// Hashes a string using the SHA512 algorithm. 5 ///// <</summary> 6 ///// <param name="input">An UTF8 string to hash.<</param> 7 ///// <returns> 8 ///// The SHA512-hashed equivalent of <paramref name="input"//>, 9 ///// as a uppercase hex string without dashes. 10 ///// <</returns> 11 public static string HashAsSha512(this string input) 12 { 13 using (var sha512Hash = SHA512.Create()) 14 { 15 var inputBytes = Encoding.UTF8.GetBytes(input); 16 var hashedBytes = sha512Hash.ComputeHash(inputBytes); 17 return Convert.ToHexString(hashedBytes); 18 } 19 } 20 } Listing 3.6: Hashing a string with SHA512 in C# For a developer not familiar with the API, there are a few aspects that are not immediately apparent. An obvious way would be to simply call the constructor of the SHA512 class, which would fail as it is protected and only callable by derived classes. The officialdocumentationfortheSHA512class[103]offersanexampleusingtheSHA512Managed class, which is marked as obsolete [104] and only then points to the correct usage of the Create() method on its parent type. As its base HashAlgorithm class implements the IDisposable interface, it is also important to wrap calls to the Create() method in a using statement, to automatically release all internally allocated resources afterwards. Based on examples of improvable aspects of APIs [67, p. 359], specifically the omission of obsolete or unused classes and the difficulty to choose the correct functions, the SHA512 class is a practical candidate for a simplified API that enables easier access for citizen developers.38 CHAPTER 3. SUPPORTING CITIZEN DEVELOPERS IN WRITING CODE The amount of work involved to design a wrapper library depends on the requirements of the citizen developers. A five-step process is proposed by Jugel et al. [67], which can be summarized as: 1. Import of an existing or creation of a new API-model, i.e., selection of an API to be wrapped. 2. Refinement of the model. Selection of classes and concepts that are of interest for the consumer, while avoiding existing usability problems of the API. 3. Improving the naming and annotations of the selected classes and methods. Tech- nical names are replaced with more readable versions that can be better understood by the consumer. New classes and methods can optionally also be added. 4. Implementation of the actual code for the API. This can be either done manually, or with a special code generator, that was also developed as part of [67]. 5. Testing of the resulting wrapper library. While the underlying code of the original library may have been fully tested previously, the new wrapper can still introduce errors or inconsistencies, and needs to be covered by new unit or integration tests. Providing a library with cryptographic hashing functions to the citizen developer might thus start with a selection of supported algorithms. Functions that are prone to collisions, considered insecure or not applicable to the particular domain can be omitted, the API then only offers implementations that are to be used by the developers. The new functions could be implemented as extension methods, so they can be directly called on string variables and users don’t need to create objects to use them. While the wrapped functions are part of .NET, tests should still be written for the created wrapper functions, to ensure that they perform as expected. Adding support for the wrapper library to the editor is relatively easy. Compared to the previous sections, this example uses RoslynPad as an editor, since its built-in support for Roslyn enables the integration of external libraries, also called assemblies in .NET. Assuming that the library is referenced from the editor project, the assembly, in this case containing the namespace WrapperApiSample.HashFunctions, can be added to a new instance of the class RoslynHost, which is in turn passed to the editor during initialization. Listing 3.7 shows the relevant parts required for the integration of an additional library. When running the editor, the namespace for the desired class can be imported with a using directive, and RoslynPad will detect the used method (as implemented in listing
3.6) and display its documentation 13 as tooltip (figure 3.10). 13.NET uses a special XML syntax, informally called XMLDoc, to decorate code elements with docu- mentation — https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/xmldoc3.4. IMPROVING ACCESS TO APIS 39 1 RoslynCodeEditor editor = new RoslynCodeEditor(); 2 3 var host = new RoslynHost(additionalAssemblies: new[] 4 { 5 Assembly.Load("RoslynPad.Roslyn.Windows"), 6 Assembly.Load("RoslynPad.Editor.Windows") 7 }, RoslynHostReferences.NamespaceDefault.With(assemblyReferences: new[] 8 { 9 typeof(object).Assembly, 10 typeof(WrapperApiSample.HashFunctions).Assembly, 11 })); 12 13 editor.Initialize(host, new ClassificationHighlightColors(), "C:\\WorkingDirectory", ,→ string.Empty); Listing 3.7: Integration of an external library in RoslynPad Figure 3.10: Calling the example wrapper API in RoslynPad 3.4.2 API Documentation Well-structured documentation is also an important aspect for the correct use of APIs, as shown in a study by Gorski et al. [53]. They compared the effects of supplemental security information in official API documentation by adding code comments or a section specifically dedicated to a security feature. Four different variations were evaluated to find the areas the participants read most attentively and their effect on the results of specific programming tasks. They concluded that adding detailed information has a significant impact on the security of the resulting solutions, as none of the participants in thecontrolgroup, usingthestandarddocumentationwithoutsupplementalhelp, managed to implement the security feature correctly. The sample group was composed of students with little programming experience, which shows that users without in-depth knowledge of software development (including citizen developers) profit from further documentation and produce more secure code. Another study [54] showed that displaying advice upon usage of insecure cryptography functionsinPythonimprovedthesecurityofthesolutionsimplementedbythestudygroup. Theadvicemessagescontainedanexplicitwarningandofferedtheusermeaningfuloptions to continue: a secure action with a code example for a secure alternative implementation,40 CHAPTER 3. SUPPORTING CITIZEN DEVELOPERS IN WRITING CODE and an insecure action with a hint how to suppress the warning. They conclude that most of the participants adhered to the advice and improved their formerly insecure code, however the warnings did not have a positive effect on the perceived usability of the API. Implementation of context-based advice The results of the two studies by Gorski et al. [53, 54] can be applied to develop context- based advice implemented with the augmentation framework introduced in section 3.3. As the concrete libraries or code expressions that should be covered by advisories in a LCDP can vary, the framework uses a generic approach to enable custom data sources to supply the information displayed. The classes containing the content of an advice implement the IAdviceModel interface, which includes information similar to the sample from Gorski et al. [54, Figure 1], such as code examples, secure and insecure actions, and hyperlinks to provide the citizen developer with additional resources. Implementations of IAdviceModel can come from any source, so it is possible to build advice models that are defined directly in code, or are supplied from a database or XML files. Suppose a LCDP supports extension with a custom scripting language, which provides specific functions to insert newline characters into string expressions. Users may be accustomed to inserting the escaped newline sequence \n, which has a different meaning in that language. To inform the user to use the provided functions, an augmentation that detects and underlines usages of the newline sequences is developed. Similar to the security advice from Gorski et al. [54] that were printed in a terminal upon usage, the user can click the affected part of the code and is presented with a pop-up that contains details of the issue and is provided with sample code to address the problem, as shown in figure 3.11. Compared to the implementation from [54], where the advice messages are part of the API, the implemented augmentation is an external component that is independent of the API it analyses. The advantage of this approach is that any APIs can be targeted with advice, and it is not necessary to modify the underlying existing libraries, which may not be possible (if the library is not open source) or not desired by its original authors. Advice can be tailored to target audiences and customized with appropriate messages, sample code and hyperlinks. Users can directly copy the sample code from the pop-up window into their editor, and click on the link at the bottom to open the target website in their browser. However, since the advice are implemented as part of an existing editor, they cannot be universally used elsewhere. They have to be deployed as part of a development environment, and, as they are not part of the API, they are also unavailable to developers not using that environment. Implementing advice as part of an API has the advantage that they are generally available to all consumers, as long as they are evaluated by the IDE that is used.3.5. CUSTOM STATIC CODE ANALYZERS 41 Figure 3.11: Advice augmentation triggered by the usage of an unsupported escape sequence. 3.5 Custom static code analyzers Theaugmentationframeworkshowninsection3.3reliesonstringcomparisonsandregular expressionmatchingtoidentifythewordsorstatementstoadorn,andisessentiallyasimple formofsyntaxanalysis. Todistinguish, forexample, whetherastringisexplicitlyassigned to a variable, used as a function parameter, or is part of a comment, a more sophisticated analysis method is required. This section uses Roslyn, .NET’s compiler platform, to implement code analysis rules and matching fixes that can be used to automatically resolve the issues found. Microsoft provides the .NET Compiler Platform SDK [106] to interact with Roslyn and its syntactic and semantic code models. The software development kit (SDK) ships
with the necessary tools to build custom code analysis rules called analyzers, to find, and automated corrections called code fixes, to address code issues. To ease development of analyzers, the SDK offers project templates for Visual Studio that provide the scaffolding and generate the basic infrastructure for analyzers, code fixes, packaging to distribute the analyzers, and unit testing projects. To demonstrate how static code analysis can be used to support citizen developers, a Roslyn analyzer and code fix, that perform similar to the detection of unescaped newline sequences in section 3.4.2, were implemented for this thesis. As these analyzers are primar- ily developed for use in Visual Studio, there is no standard way to offer their functionality in external editors like RoslynPad used in the previous sections, thus limiting their use- fulness for developers not using an IDE. This section also shows how the implemented analyzer can be integrated into RoslynPad, and enabling citizen developers to use them42 CHAPTER 3. SUPPORTING CITIZEN DEVELOPERS IN WRITING CODE as part of an editor in their LCDP. As with previous examples, the full source code is available on GitHub [18]. 3.5.1 Implementation of an analyzer Theprojecttemplatesalreadyincludethebasicscaffoldingcodetobuildasimpleanalyzer, including the definition of a diagnostic rule, its localization and initialization. Therefore, it is only necessary to customize the predefined attributes of the rule, such as its severity and the messages the analyzer will emit (similar to the illustration in figure 3.1), and add the concrete analysis logic. Listing 3.8 shows the essential parts of an analyzer that detects the newline escape sequence (\n) in string literals. 1 public class NewlineAnalyzer : DiagnosticAnalyzer 2 { 3 private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor("DiagnosticId", ,→ "Title", "Message", "Category", DiagnosticSeverity.Warning, true, "Description"); 4 5 public override void Initialize(AnalysisContext context) 6 { 7 context.RegisterSyntaxNodeAction(AnalyzeSyntaxNode, ,→ SyntaxKind.StringLiteralExpression); 8 } 9 10 private static void AnalyzeSyntaxNode(SyntaxNodeAnalysisContext context) 11 { 12 if (context.Node is not LiteralExpressionSyntax node) return; 13 if (!node.Token.ValueText.Contains("\n")) return; 14 15 var diagnostic = Diagnostic.Create(Rule, node.GetLocation(), node.Token.ValueText); 16 context.ReportDiagnostic(diagnostic); 17 18 } 19 } Listing 3.8: Implementation of a Roslyn analyzer to detect unescaped newline sequences in string literals3.5. CUSTOM STATIC CODE ANALYZERS 43 The ID of the rule, along with its messages and severity, is defined in line 3. The Initialize() method is automatically called by the code analysis engine to set up and register the method containing the actual analysis logic, AnalyzeSyntaxNode(). SourcecodeisrepresentedasatreeofsyntacticelementsinRoslyn. TheSDKprovides a syntax visualizer extension for Visual Studio that lets the developer inspect the state of the syntax tree in real time. Figure 3.12 shows how the structure of a simple string assignment to a variable that would trigger a diagnostic warning is structured. The StringLiteralExpression element that represents the text of the string itself is selected. A corresponding enum value is passed to the registration method in line 7 so that the analyzer is not called for the numerous other syntax elements. Figure 3.12: Roslyn’s syntax visualizer showing the structure of a string literal variable assignment If the check for a \n inside the string literal, shown in line 13, is successful, a new diagnostic is created. The diagnostic is supplied with the exact location and statement text of the analyzer violation, which enables the emitted message to be as precise as possible. 3.5.2 Implementation of a code fix Analogous to the analyzer, the project templates already contain the basic infrastructure to implement an (optional) code fix that complements the analyzer. The implementation is similar, though the code fix is dependent on the diagnostic and receives the information reported by the analyzer from listing 3.8, line 16. Listing 3.9 shows how the code fix implementation inspects the string literal and creates replacement values that are applied tothecodeintheeditorwhenthefixisinvokedbytheuser. Anewliteralwiththeupdated44 CHAPTER 3. SUPPORTING CITIZEN DEVELOPERS IN WRITING CODE values is created, while the trivia (such as whitespace or comments [93]) is preserved to keep the string otherwise the same as before. The final step is to replace the old string literal in Roslyn’s syntax tree. The practical application of this code fix is shown as part of the next section in figure 3.13. 1 private async Task<Document> ReplaceNewlineAsync(Document document, LiteralExpressionSyntax ,→ expressionSyntax, CancellationToken cancellationToken) 2 { 3 var token = expressionSyntax.Token; 4 var updatedRawText = token.Text.Replace(@"\n", "\" + Str.Lf + \""); 5 var updatedValue = token.ValueText.Replace("\n", "\" + Str.Lf + \""); 6 var newToken = SyntaxFactory.Literal(token.LeadingTrivia, updatedRawText, updatedValue, ,→ identifierToken.TrailingTrivia); 7 8 var sourceText = await expressionSyntax.SyntaxTree.GetTextAsync(cancellationToken); 9 return document.WithText(sourceText.WithChanges(new TextChange(token.FullSpan, ,→ newToken.ToFullString()))); 10 } Listing 3.9: Implementation of a Roslyn code fix to replace unescaped newline sequences in string literals 3.5.3 Using custom analyzers in RoslynPad The project template for analyzers scaffolds two additional projects: one for a VSIX (Visual Studio integration extension) package, and one for a NuGet package. A VSIX
package can be installed as a global extension in Visual Studio so that the analyzer is used for any kind of project. A NuGet package can be installed into specific .NET projects so that it applies only to the code in that project. Neither of those options are viable for use in LCDPs. A citizen developer doesn’t work with Visual Studio, and the scripts they develop are not part of a .NET project. While additional NuGet packages can be loaded by RoslynPad, the feature is not available in the editor component used in this example. RoslynPad has also rudimentary support for the built-in Roslyn analyzers [6], but there is no official way to add custom analyzers to the editor. However, as the analyzers and code fixes itself are just regular assemblies, they can be added to Roslyn instances independently. ThiscanbeachievedinthesamewayRoslynPadaddstheexistingRoslynanalyzersin- ternally,andrequiresonlyseverallinesofcodethathavetobeadoptedfromitssourcecode [7]. Listing3.10showshowtheassembliesareadded. ThemethodInitializeAnalyzers() takes an instance of IRoslynHost and a DocumentId, both of which are created previously as part of the initialization of the editor. For each analyzer and code fix assembly, an3.6. SUMMARY AND DISCUSSION 45 instance of AnalyzerFileReference is created and added to Roslyn’s internal project re- presentation. As most of Roslyn’s object structure is immutable, an updated instance of the Project object is returned and has to be integrated back into the original RoslynHost (lines 7-10). 1 public void InitializeAnalyzers(IRoslynHost host, DocumentId documentId) 2 { 3 var loader = host.GetService<IAnalyzerAssemblyLoader>(); 4 var analyzerReference = new AnalyzerFileReference("SampleAnalyzer.dll", loader); 5 6 var document = host.GetDocument(documentId); 7 var project = document.Project.AddAnalyzerReferences(new[] { analyzerReference }); 8 document = project.GetDocument(documentId); 9 10 host.UpdateDocument(document); 11 } Listing 3.10: Adding an analyzer to the RoslynPad editor Correctly adding the analyzer assemblies enables RoslynPad to display them in the samewaythedefaultRoslynanalyzersare. Figure3.13showshowtheanalyzerisdisplayed and how a code fix is invoked on the code emitting the diagnostic warning. The custom codeanalyzerdevelopedinsection3.5.1isshowninfigure3.13a,theunescaped\nsequence is detected and underlined, with a tooltip showing details of the warning. Since a code fix is available, a yellow dot in the margin right of the line number indicates that the user can take an action to remedy the warning. Upon clicking the indicator, a context menu, shown in figure 3.13b, opens and shows the available actions. The first action, Replace with compatible newlines, is the code fix developed in section 3.5.2. The other three entries are refactoring actions coming with Roslyn by default. After the menu entry is selected, the code is changed according to the implementation of the code fix (figure 3.13c). 3.6 Summary and discussion Chapter 3 introduced tools that aid citizen developers in writing code by extending the editor they are working with, and making it easier to understand APIs by wrapping them in more refined and approachable functions and providing additional help and documentation for frequently made mistakes. The augmentation framework developed in section 3.3 can be used to create customizable visual clues based on regular expressions in the AvalonEdit code editor. Using RoslynPad, an editor that is based on AvalonEdit and extends it with features of the Roslyn compiler platform, the integration of external API assemblies, custom static code analyzers and code fixes was demonstrated.46 CHAPTER 3. SUPPORTING CITIZEN DEVELOPERS IN WRITING CODE (a) Tooltip and indicator of the analyzer violation (b) Quick action menu showing possible code fix actions (c) Code after invoking the code fix Figure 3.13: Custom analyzer and code fix in RoslynPad These tools contribute primarily to the answer to RQ I posed in section 1.4. The augmentation framework provides an easy way for LCDP developers to build visual aids tailored to their users. Since the framework is specifically written for AvalonEdit’s extensibility pipeline, its usefulness primarily depends on whether AvalonEdit is a viable editorcomponentfortheLCDP.Furthermore,sincetheframeworkusesregularexpressions to determine where augmentations are displayed, more complex syntactic scenarios, such as detecting whether a code expression is inside a static method or part of an internal type, are difficult to detect. For this purpose, static code analysis, for example using the APIs exposed by Roslyn, is more suited. Building static code analysis rules and code fixes based on them is a popular function in many more advanced IDEs, but usually not present in simple code editor components for integration in existing applications. By using the existing scaffolding provided by Roslyn, an approach to develop and integrate analyzersandfixesintoRoslynPadwasdemonstrated,whichcanbeusedtoprovidecitizen3.6. SUMMARY AND DISCUSSION 47 developers with additional support on a syntactic level, albeit with very limited visual customizability. Future work could leverage static code analysis to build augmentations for more advanced syntactic structures. Additionally, both the augmentation framework and wrapper APIs can be used to answer RQ II. By focusing on the detection of potentially insecure or harmful usage of APIs, users can be educated with appropriate messages while also offering them more secure alternatives. Specially prepared APIs, that wrap complex classes or functions susceptible to misuse, can contribute to security as well by providing users with readily madeandeasytouseabstractions. This, however, mayrequiresignificantefforttodevelop and maintain. Unless the affected APIs can be clearly identified, each potentially insecure class or method must be considered for wrapping or has to emit warnings. New releases
of frameworks must be analysed for new, previously not covered APIs. Furthermore, programming language features such as reflection or dynamic types have to be factored in, since they can be used to circumvent restricted APIs by loading or executing arbitrary code and expressions, both at compile- and runtime. Additional discussion of RQ II can be found in the summary of chapter 4 in section 4.6.Chapter 4 Code security in low-code applications Security flaws in LCDPs can potentially affect thousands [122] of applications, as vulner- abilities will be distributed with every instance of a LCA generated. This chapter will present two sources of possible security issues and examine potential mitigation strategies. The first source stems from the code embedded by citizen developers, as it can introduce unintended security problems, and should therefore be analysed for possible weaknesses during development time. The other source of problems can originate on a higher level, when running a shared LCDP on a server for multiple, possibly independent, clients. To prevent users from accidentally or maliciously accessing system resources or data of other users, isolation of the different LCDP instances has to be ensured. This is even more important if the applications use sensitive company data, as data leaks would be critical and customers may demand an audit to prove that the environment is secure. 4.1 Process isolation Several issues listed in the OWASP Top 10 of Low-Code/No-Code Security Risks [8] directly relate to the problems examined in this thesis, namely ‘Data and Secret Handling Failures’, ‘Security Misconfiguration’, ‘Injection Handling Failures’ and ‘Vulnerable and Untrusted Components’. The former two risks are connected to the separation of LCDP instances on a server, while the latter two focus on issues with code written for the LCA. This section will explain the concepts of process isolation, to separate running applications from each other and prevent access to foreign data. 4950 CHAPTER 4. CODE SECURITY IN LOW-CODE APPLICATIONS Process isolation can be implemented on hard- and software-level. Aiken et al. [2] define it for the general case as: ‘ Isolation protects system integrity by preventing one process from interfer- ing with another’s, or the system’s, code or data, and by preventing untrusted code from accessing protected resources. Isolation also contributes to system resilience by providing failure boundaries that permit part of a system to fail without compromising the whole. ’ On hardware level, this isolation is enforced by the memory management unit (MMU) by preventing a process from accessing memory pages outside those allocated to him [148, p. 260] as well as running user processes at a lower permission level than kernel processes (which have the most privileges) [148, p. 479]. High-level programming languages (such as C#) usually do not have access to these hardware intrinsics (outside of device drivers), since they run in user mode, where direct access to the operating system kernel and underlying hardware is not possible [108]. However, this only protects processes and the kernel on a relatively low level and does not stop an application from accessing foreign data that resides, for example, on a hard drive or on a network server. On operating- system level, further access control models, such as discretionary access control (DAC) [148, p. 612] or mandatory access control (MAC) [148, p. 612] may be implemented to selectively allow or deny users access to files and resources or enforce a flow of information. While these may prevent accidental access to data, they do not provide isolation from failure. As Tanenbaum points out that ‘All these ideas about formal models and provably secure systems sound great, but do they actually work? In a word: No.’ [148, p. 615], a more thorough concept for both security and failure is needed. LCAs, with a mixture of generated and user-written code, can be seen as mobile code: code from an external source that is executed as part of an application the user started [65] [148, p. 698]. For example, suppose a user is running a LCA that has been developed collaboratively with colleagues. The user is reasonably sure that none of the colleagues had deliberately included malicious code, but is uncertain whether the application makes use of insecure external code that may have been loaded by a third-party library. Bargury et al. [8] describe this risk as dependency injection. Wahbe et al. [153] highlight a similar issue, where (poorly implemented) additional software modules purchased for an application can make the main application seem unreliable. They propose sandboxing as a solution, where an untrusted module is encapsulated by adding additional instructions so that it can only operate within its address space and not accidentally alter trusted code. A more modern definition from Hoopes [59] describes a sandbox as ‘a monitored and controlled environment, such that the unknown software cannot do any harm to the real hosting computer system’. Sandboxing is common today, for example in browsers such as Chromium. To prevent malicious code from affecting the user’s data, security-critical components are run in4.2. THREAT MODEL 51 the sandboxed rendering engine, which is the common target for exploiting browsers vulnerabilities [55]. The rendering engine runs in a separate target process, while the main browser process is called the broker and manages the sandboxed processes [51]. Figure 4.1 shows the data flow of this architecture: the broker sends the source code of a web page (containing HTML and JavaScript) via inter-process communication (IPC) to the renderer, which in turn generates the web document and sends it back to the browser process for displaying [9]. Sandbox Target/Renderer IPC HTML, JS, ... Rendered Bitmap Broker/Browser process Figure 4.1: Sandboxing architecture in Chromium. Adapted from [9] with terminology from [51]. Barth et al. [9] note that this architecture does not prevent attacks on the renderer by itself, but hinders an attacker from accessing the user’s data outside the sandbox. Chromium’s sandbox contains the malicious code, prevents execution of potentially dam- aging system calls, and limits it to using the browser process’s interface, which provides
a smaller attack surface. More generally, a sandbox itself doesn’t prevent malicious code from executing, but tries to reduce the damage it can inflict by intercepting and mediating system calls (such as direct access to the file system, or creating network connections) [55]. It does not prevent attacks on components outside the process. An example for this are the CVE (Common Vulnerabilities and Exposures)1 issues CVE-2010-2897 [30] and CVE-2010-2898 [31], which use specially prepared CSS to target an issue in the Windows kernel’s font handling, and JavaScript code to cause a crash in glibc2 with very long file paths respectively. 4.2 Threat model Running a shared LCDP on a server for multiple, independent clients is similar to a Platform-as-a-Service (PaaS) offering in a cloud environment. Depending on the imple- mentation, clouds may share the software resources, such as programming libraries and 1A system to catalogue security vulnerabilities — https://cve.org 2The C standard library implementation for GNU/Linux.52 CHAPTER 4. CODE SECURITY IN LOW-CODE APPLICATIONS database engines, between users, or provide isolated environments using virtual machines (VMs) for each tenant [132]. Using virtual machines to isolate individual instances is considered the primary defence mechanism against attackers in the cloud [44], but moves the responsibility for security to the virtualization layer. This presents different threats, for example cross-VM attacks using side-channels to gain information on other VMs run- ning on the same system. These can be used to steal cryptographic keys, inhibit the performance of the attacked VMs or perform denial-of-service attacks [131]. Since the primary concern of this thesis is the code security of LCDPs, a threat model that focuses on risks originating from additional source code written for LCAs is introduced. Whether the application is hosted in a private or public cloud, on premises or in an off-site data centre, an obvious threat is malicious behaviour by either the provider of the services itself, or single actors involved in the administration of the servers. For the purposes of this model, the infrastructure, including possibly used virtual machines, and involved parties are considered trusted. The LCDP is hosted on a single server, set up by a vendor, and offered to customers. Customers use the LCDP to develop and test generated applications (introduced in section 2.2.3). The resulting applications are howevernothostedbythevendor, thecustomersdeploytheirLCAsindividuallyaspartof their infrastructure. This limits the attack surface to the development time of the LCAs, and the possible attackers to those individuals who use the LCDP to built applications. While a generated application may contain code that targets the customer after it is deployed on their infrastructure, an attacker would ultimately try to compromise their own data. In this model, the customer trusts their developers to not threaten their own data. The main interest of the LCDP vendor is thus to isolate each instance of the plat- form against each other. A naïve attack can be, for example, to try to access files and folders outside the directories required for development. Suppose the LCDP is run- ning on a web server on a Unix system. Customers each have their own folder on the server: /var/wwwww/customer-one, /var/wwwww/customer-two, /var/wwwww/customer-three and so on. Unless the server administrator has set appropriate protection bits [148, p. 45] on the folders, so only developers of the respective customer can access a directory, each customer could peek into the files of the others. Current web servers usually provide easy means to set up applications in isolated directories to prevent such issues, IIS3 for example, separates individual websites into application pools [91]. Another possible attack vector is a denial-of-service attack. An adversary could try to exhaust the system resources of the server by spawning numerous processes with the aim of preventing other customers to be able to use their application instances on the server. This scenario can also occur accidentally, when malfunctioning code contains a memory leak and continuously allocates memory until all available RAM on the system is in use. 3Internet Information Services, a web server by Microsoft4.3. APPROACHES FOR SECURELY RUNNING CODE 53 4.3 Approaches for securely running code There are a few general methods for the isolation of code running as part of processes and limiting the impact that code can have on its environment. Neither of these approaches are exclusive to low-code, as in the end, LCAs on a fundamental level are not different from other applications. It is important to distinguish between the two kinds of code that comprise a LCA: the code that is generated by the LCDP (or runs as part of its environment), and the custom code written by the user. Some security technologies, such as sandboxes, often require usage of specific APIs to profit from it [55]. For the code that is part of the LCDP, this can be feasible, if it has already been built with specific security platforms in mind. Otherwise, it would require substantial changes to existing code. ImplementingAppContainers, whichare described in detail in section 4.5.3, requires usage of security tokens and running additional processes or threads, which are no small architectural changes. And since the citizen developer cannot be expected to write specifically secure code, or programming against an API facilitating security, relying on securely written code should not be the primary guard against accidental or malicious threats. Viewing the entire application as untrusted, and isolating it from the operating system and other processes, can help to prevent undesired access to system resources [55]. This section investigates some commonly available techniques to run applications in an isolated environment. 4.3.1 Sandboxing Sandboxing can refer to a broad number of techniques that transparently verify or control the data flowing to and from an application, with the aim to prevent interference with other parts of the system. According to Goldberg et al. [50], who ‘use the term sandboxing
to describe the concept of confining a helper application to a restricted environment, within which it has free reign’, the name originates from Wahbe et al. [153], who used it in the context of sanitizing memory addresses. Al Ameiri et al. [4] distinguish between six types of sandboxes: Applets are run inside an environment that is responsible for isolation, such as Java Applets or Flash objects in a browser. Jails verify and potentially block system calls and decide about access to resources of a ‘prisoner’ process [148, p. 695]. Virtual machines provide an entire guest operating system for an application, and enables access to system resources through a virtualization layer. Rule-based execution lets a user specify how an application is allowed to interact with the system.54 CHAPTER 4. CODE SECURITY IN LOW-CODE APPLICATIONS Standalone applications provide an additional layer above the operating system that intercepts activity of an application and redirects it into isolated objects, so it can’t affect the host system. Examples are Sandboxie [136] for Windows or Firejail for Linux [118]. OS-integrated tools to support sandboxing, such as AASandbox for Android [15], which performs static and dynamic program analysis to detect potential malicious use of system calls, or seccomp [71], a Linux kernel module, which enables applications to filter incoming system calls. Itshouldbenotedthattheirevaluationprecededthebroaduseofcontainerizationtools like Docker, which was first released in 2013, that utilize operating system technologies to partition a host OS to share its resources between multiple containers, and thus would fall into the last category. There is a certain overlap between these categories. For example, jails and operating- system integrated tools both control access to system calls by the sandboxed application. Rule-based execution modules, such as SELinux and AppArmor [4] for Linux systems and AppContainers under Windows, all utilize mandatory access control and are closely integrated with the operating system as well. Java Applets and Silverlight applications run inside the Java Virtual Machine (JVM) and Common Language Runtime (CLR) respectively. Both are examples of high-level language virtual machines (which in turn are a kind of process VM) [144, p. 228], while VMs running a guest operating system on a host are called system VMs. In the context of this thesis, some of these categories can be eliminated as a potential choice to securely run LCAs. Applets are highly dependent on the used programming language and target platform, and require an environment that supervises its applications to be supplied. Specifically, the mentioned technologies Java Applets [123] and Flash [1] have both been deprecated for several years and were mainly used in web browsers. Jails originate from Unix- and BSD-like operating systems and are not universally available, but can be categorized as an early implementation of containers [28]. Tools integrated into the operating system facilitate sandboxes, but, in the case of seccomp for example, aren’t complete sandboxes: ‘System call filtering isn’t a sandbox.[...] It is meant to be a tool for sandbox developers to use.’ [71]. Virtual machines and standalone applications are interesting options, since they don’t need to be specifically supported by the application to be sandboxed, are available on the most common operating systems and not limited to certain types of applications. The drawback of traditional VM solutions, like VMware, is the performance loss of about 10- 20% [42] when compared to a native system. This approach is also relatively heavyweight, requiring an entire OS installation per application. A compromise between ease of use and system requirements is OS-level virtualization. Regular virtualization often uses a hypervisor, or virtual machine monitor (depending on4.3. APPROACHES FOR SECURELY RUNNING CODE 55 the hard- and software capabilities and configuration), to interface the virtual machines with the hardware of the computer, either directly on the hardware (type I) or on a host OS (type II). The VMs itself always contain a guest operating system. OS-level virtualization shares the resources of a host OS, including the kernel, among all virtual- ized instances (containers) [12]. The host OS provides the facilities to implement these containers, for example, Docker utilizes the seccomp kernel module [40] mentioned earlier. Figure 4.2 illustrates the difference between the two types of virtualization. Two concrete implementations of such containers are discussed in detail in section 4.4. Virtual Machine Virtual Machine App 1 App 2 App 3 App 4 libs libs Container Container Container OS OS App App App Hypervisor libs libs libs Host OS (Type II only) Host OS Server Server (a) Type I and II virtualization (b) Container Figure 4.2: Types of virtualization. Adapted from [12] 4.3.2 Blocking of API calls To prevent users from calling certain APIs that can be used to potentially compromise a system, an obvious approach may be to simply disallow usage of the methods in question. For example, APIs that access the file system, security-relevant information or enable usage of reflection, could be detected and blocked from execution, or prevent compilation altogether. Online services that provide compilation of code in a browser, such as SharpLab4 and .NET Fiddle5, which enable testing of small code fragments or analyse the resulting machine code, have a similar problem — the server their software is run on should not be able to be compromised by a malicious actor. Historically, SharpLab used the Unbreakable library6 toselectivelyallowcertainAPIstobecalledandimposedlimitsonexecutiontime and memory usage. This approach was abandoned, as it didn’t scale well and required continuous maintenance of the allowed or denied APIs [142]. Its current implementation uses AppContainers, which are detailed in section 4.5.3. 4https://sharplab.io 5https://dotnetfiddle.net 6https://github.com/ashmind/Unbreakable56 CHAPTER 4. CODE SECURITY IN LOW-CODE APPLICATIONS Both maintaining a list of allowed APIs (allow list), denying everything by default,
or a list of denied APIs (deny list), allowing everything else by default, has its problems. An allow list has to have an appropriate amount of default classes and methods, that are widely used for normal programming tasks. This would have to include a vast amount of the basic API provided by the framework, and can potentially frustrate users if safe classes and methods were forgotten or have to be manually enabled. Likewise, a deny list would have to contain a comprehensive amount of abusable APIs, including reflection, file input and output or the creation of processes. Classes for reading and writing files, for example, can be used both for valid business cases (such as creating files in an allowed folder) and malicious purposes (reading files outside the user’s directory). On API level, it cannot be decided whether calls like this are benign or not. As such, additional security measures, like filesystem-level access control, have to be employed. Future releases of an API or its framework have to be scrutinized for new method calls, or changes in existing behaviour that can be either beneficial to the user (and need to be allowed) or can be misused (and need to be denied). A single oversight can potentially allow the lists to be circumvented altogether. If the intent is to steer the user away from using certain APIs (because they may be obsoleteorinsecure), analternativeapproachistousecontext-basedadvice, asintroduced in section 3.4.2. 4.4 Implementations of OS-level virtualization To test the suitability for the deployment of low-code applications, two implementations of sandboxing environments are evaluated: Windows Sandbox and Docker containers. The following sections explain their isolation and security architecture, effort required to customize and set up an instance, and their ability to run a LCA desktop and web applicationondemand. ThetwoapplicationsweretestedonasystemwithanAMDRyzen 5 3600 CPU, 32 GB RAM, Windows 11 Pro (Build 22623) and an internet connection with 50 Mbit downstream. 4.4.1 Windows Sandbox The Windows Sandbox is a lightweight environment for the isolation of applications for Windows 10 and 11 that runs directly under Windows and uses hardware-based virtualization (Hyper-V) to run a separate kernel for each instance [113]. Instances of the sandbox are transient, i.e., after closing the sandbox its state is not persisted (except for reboots initiated from within the sandbox) and each new instance gets loaded with an unmodifiedinstallationofWindows. Itispossibletomapfoldersfromthehostsysteminto the sandbox, and to execute commands upon loading to automatically install applications or set up a specific environment configuration. The sandbox has network access, and can4.4. IMPLEMENTATIONS OF OS-LEVEL VIRTUALIZATION 57 use resources, such as audio and video input, printers, a battery if present, and even the GPU from the host system. [114, 115]. Architecture Windows Sandbox shares part of the system files with its host system. Microsoft calls this a dynamic base image [114] and differentiates between mutable and immutable system files. Most of the files the OS uses are read-only (immutable), and thus can be shared safely with the sandbox. The files required to be modifiable (mutable) are copied to the sandbox, so that changes don’t affect the host OS. The immutable files are only linked into the sandbox, using a multi-layered structure [61], that draws the files from several sources in the host system. The immutable system files are also shared in memory, called a direct map [114], reusing the same pages to reduce the amount of memory the sandbox requires. The sandbox also doesn’t use a static amount of memory from the host OS, and behaves more similar to a regular process. If the host needs to reclaim memory, it can reallocate memory from the sandbox to the processes that require it. Using integrated scheduling [114], the process scheduler of the host can treat processes insidethesandboxasthreadsandprioritizethemamongtheworkloadoftheentiresystem. In traditional VMs, the hypervisor controls the processors assigned to the virtual machine in its entirety, and has no information or influence about the processes running inside it. Customization By default, there are a limited number of configuration options for the sandbox. Admin- istrators can configure the mapped folders into the host system, the commands to be executed upon logon, disable redirection of certain resources and the amount of memory available to the sandbox [115]. While there was previous effort to customize the image that the sandbox uses as a base [61], the steps outlined in the article could not be reproduced on Windows 11, due to apparent changes in the file and folder structure of the base files. However, placing addi- tional files in %ProgramData%\Microsoft\Windows\Containers\BaseImages\<randomGUID> \BaseLayer\Files\ will make them available inside the sandbox. Tests with a simple text file and a portable version of Notepad++ showed that files and applications added to the sandbox this way are writable and executable, changes to them are contained and not propagated to the host system. While copying files or installing programs can be achieved by running a script on login as well, it would take more time, since the files are not immediately available as part of the base files. Since this is not an officially documented way to customize the sandbox, it is a volatile approach which may not work after subsequent updates to Windows.58 CHAPTER 4. CODE SECURITY IN LOW-CODE APPLICATIONS Usage Reiterating from section 4.2, the threat model involves adding malicious code to a gener- ated LCA and trying to gain access to other data on the server, or disrupting other users working on the same server. Isolating the generated application involves deploying it to a new instance of the Windows Sandbox. Depending on the type of application, this can be relatively easily achieved by configuring a mapped folder to the host system, which contains the generated application, or using a script to copy and install the application and its dependencies. For desktop applications that provide a graphical user interface (GUI), the sandbox would have to be started on a remote server, and the users would need a way to connect to it to test their application. A naïve approach, using an RDP (Remote Desktop Protocol)
connection and the built-in Windows RDP functionality, was unsuccessful, as no connec- tion could be established, although the sandbox was reachable in the network and had remote access enabled. A further test with the third-party tool TeamViewer7 succeeded. This, however, involves additional (paid) software which has also to be deployed in the sandbox and on the computer of the client, and adds more complexity and reduces user experience. A test with a simple ASP .NET Core web application that runs on the integrated, in-process Kestrel web server in the sandbox, was more successful. If configured to accept external connections, it was possible to access the hosted website from different computers in the same network. Evaluation WhetherWindowsSandboxisasuitableenvironmenttodeployLCAsintolargelydepends ontheimpactofthetemporarynatureoftheenvironment. SincetheWindowsinstallation insidethesandboxhastobeconfiguredoneverybootandapplicationshavetobedeployed each time, setting up the sandbox can potentially take a long time, if many or large programs have to be installed. Windows Sandbox does not officially support snapshots or states to start from; thus, a once configured system cannot be reused. Starting the sandbox itself is relatively quick, requiring about six seconds until the desktop is visible and usable. However, only a single instance can be run concurrently — trying to open a second instance fails with the error message, that only one sandbox can be active at a time. Mappedfoldersofthehostcanpresentapotentialsecurityrisk,iftheycontainsensitive data, which could be read by an untrusted application in the sandbox, or are writable, allowing an untrusted application to break into the host system. Network access is by default available in the sandbox, enabling threats to the local network or downloading 7A client-server based remote control software — https://www.teamviewer.com4.4. IMPLEMENTATIONS OF OS-LEVEL VIRTUALIZATION 59 additional malicious code from the internet. As the memory used by the sandbox can be capped via configuration, memory exhaustion attacks can be mitigated. Unless limited by external means, programs running in the sandbox can fully utilize the CPU of the host machine and potentially affect other applications running on the system. Deploying and using applications that require a GUI is possible, but requires an ex- ternal tool for users to be able to connect to the sandbox and interact with the generated application. Hosting web applications inside the sandbox is easier and requires only min- imal configuration effort. However, it is questionable if running sandboxes on more than a small scale is feasible — instances have to be manually started and configured, and there are no tools supplied to facilitate automated deployment and configuration manage- ment. Windows Sandbox is not advertised as a commercial-grade OS-level virtualization solution, and the focus on easy usage and minimal configuration options, as well as the absence of snapshotting and provisioning options, makes it generally more suitable for individual users who require the execution of untrusted applications on a local computer with minimal effort. 4.4.2 Docker Docker is a software suite for the creation, management, and execution of containers [28]. Containers allow for a deterministic and standardized way to define environments in which applications and their dependencies are installed, and can be used to distribute and deploy them on local or remote, physical or virtual machines [34]. Docker builds upon multiple security features that are available in the Linux kernel: cgroups8, namespaces and seccomp[147]. Cgroupsareusedtolimitandisolatetheavailabilityofsystemresourcesfor a collection of processes [77], namespaces enable the assignment of resources to processes without affecting their usage by other processes outside the namespace [72], and seccomp blocks the usage of certain system calls. Architecture Tocreate,administerandruncontainers,Dockerusesaclient-serverarchitectureconsisting of the Docker client (docker), a daemon (dockerd), and a registry. The Docker daemon runs on the host on which the containers will be instantiated and provides a REST API (UNIX sockets or network interfaces are also possible) to enable communication with the client. The registry stores images and makes them available to pull from the host machines. Registries can be publicly available or run privately. Images are templates that define how a container will be created, and contain information such as the underlying operating system, commands to install additional software and further configuration, like the assignment of environment variables. They can be hierarchically connected, so that commonly used operating systems or software are available as a basis for the creation of 8Short for Control Groups [77]60 CHAPTER 4. CODE SECURITY IN LOW-CODE APPLICATIONS user-specific images [34]. Official images for operating systems like Windows or various Linux distributions like Debian or Fedora are distributed by their respective developers, and additional images with preconfigured software environments are often available as well. For example, the official Microsoft Artifact Registry9 supplies images for various Windows and Windows Server systems, .NET SDKs and other tools that can be combined as needed. Figure 4.3 shows a high-level overview of Docker and the relationship of basic com- mands with Docker’s components. The following two sections describe how containers can be customized and used for the deployment of LCDPs and LCAs. Client Docker Host Docker daemon do ck e r b ui l d do ck e r p ul l Containers Images do ck e r r un Container 1 Windows Registry Container 2 Debian Windows Debian .NET Python Figure 4.3: Architecture of Docker. Adapted from [34] While Docker utilizes Linux kernel features to implement OS-level virtualization, it alsorunsonWindowsandmacOS.Historically, DockerusedHyper-VtorunasmallLinux VMtoprovidetheabilitytorunLinuxcontainersonWindows. AfterMicrosoftintroduced the second version of their Windows Subsystem for Linux (WSL2)10, Docker switched its integration on Windows to use WSL2 instead of their own VM [45]. Conceptually, WSL2 still uses Hyper-V to run a Linux in a lightweight VM internally [92], however since it is much more integrated with Windows, it provides better performance and more capabilities than Docker’s original implementation [45]. Customization