text
stringlengths
64
2.99M
different instructions between two binary reference ver- ToevaluatetheutilityofVulMatch,wepreparedsevenpop- sions (i.e., a vulnerable version and a patched ver- ular open-source projects with well-documented vulnerability sion). Then they normalize the instructions and generate information. In total, there are 906 CVEs, including 1281 traces (i.e., blocks of normalized instructions) to form vulnerable functions. Our results demonstrate that VulMatch the vulnerability or patch signature. However, extracting outperforms two state-of-the-art vulnerability detecting tools signatures directly at the binary level could introduce —Asm2vecandPalmtreebyapproximately9%and6%more instructionsirrelevanttovulnerabilitiesbecausethecom- top-1 score, 80% and 79% less mismatch score, respectively. piler replaces instructions with the same semantic and We also demonstrate how VulMatch assists humans in un- inlines functions. For example, the source code line derstanding its detection results in terms of interpretability. bool fromfile=FALSE; could be compiled to mov We experiment with commercial firmware to demonstrate [rsp+48h+var_39], 0 in one version and xor VulMatch is practical to find real-world vulnerabilities. We r14d, r14d in other versions even using the same perform in-depth research on the vulnerability and signature optimization flags (options). The same variable is stored types and their distribution in the dataset. on the stack in the former version and the register This paper makes the following contributions: r14d in the latter version. If two versions inline another • We propose a novel approach to extract, store, and non-vulnerable function, and the inlined function has match the vulnerability-related signatures. We have im- changedinthepatchedversion,directlydiffingthebinary plemented the approach into a tool called VulMatch that codes will include the changed instruction in the inlined is open-source and publicly accessible on GitHub 1. function. We reproduced the methods to understand such • To facilitate the human to understand VulMatch’s results inaccurate cases and manually analyzed the correspond- and the reason VulMatch decides whether the query ingoutputbinarysignatures.Wefoundthattheirmethods binary contains vulnerability or not, we provide inter- introduce approximately 40% vulnerability-irrelevant in- pretability functionality in VulMatch. structions into the signatures. • Weperformin-depthanalysisonvulnerabilityandsigna- ture types and their distribution across all datasets. We We propose a novel approach to generate accurate and inspect each dataset’s top three vulnerability types and fine-grained vulnerability-related signatures to address those different signature types with the average signature size. research gaps. Firstly, we spend significant manual efforts pre-processing the data to include all the CVEs’ information, II. AMOTIVATINGEXAMPLE each vulnerable function, the source code file it lies in, the affectedversions,andthecorrespondingsourcecodeversions. Terms definition: Block refers to a set of consecutive To generate accurate and fine-grained binary code signatures, binary(assembly)instructionssplitbythecontrol-flow-related we generate source-code-level signatures and align them to instructions (e.g., jump instructions). An assembly function binary-levelsignatureswiththehelpofdebugginginformation. consists of various blocks connected to each other. Blocks are Unlike existing work [43, 44, 45] that directly diff different connected together to represent the assembly code’s control- binary versions to extract vulnerability signatures, we utilize flow graph (CFG), as shown in Figure 2. Note that in this sourcecodetoguideustolocatevulnerablebinarycodemore paper, we will use the terms ‘binary code’ and ‘assembly accurately. Hence, we exclude many vulnerability-irrelevant code’ interchangeably. CVE refers to the vulnerability in the binary code contents. To utilize non-trivial source-code in- function. One CVE may correspond to multiple vulnerability- formation, VulMatch processes the source code to prevent related instructions and multiple signatures. vulnerable functions from being inlined. VulMatch locates Figure 1 shows the source code snippets of the vulnerable binaries from source code by handling different situations as function tftp_connect from CVE-2019-5482 before and describedinsubsectionIII-B.Notethatthesourcecodeisonly afterthepatch,wheregreenlinesarethepatchedinstructions. required for generating the signature and not for matching a Figure 2 shows the corresponding binary code structure. givenbinary.VulMatchaimstofindvulnerabilitiesinthequery Figure 2(a) is the vulnerable version (before patch), and binary, which should not contain any debugging information Figure 2(b) is the patched version. The binary code samples and source code. We combine the information of source code, were built from the source code snippets using an identical binarycode,anddebugginginformationtogenerate(learn)the compilation configuration with additional debugging informa- signature accurately. To match the binary-level signatures, we tion. Since the patch in the example comprises two kinds of propose three signature types (i.e., add, delete, and change). changes through added and modified instructions, they are Tomatchtheexistenceoffine-grainedbinarysignaturesrather listedusingdifferentcolors.Specifically,block1’isamodified thanthewhole-function-levelsimilarityasthesimilarity-based genre, we create the binary signature with local control-flow 1Thesourcecodeisavailableathttps://github.com/Vulmatch/Vulmatch.git3 binary is vulnerable. Existing binary signature-based methods …… …… directlydiffthevulnerableandthepatchedbinaryversionsand return CURLE_OUT_OF_MEMORY return CURLE_OUT_OF_MEMORY
} } assume the different binary instructions are all vulnerability- relevant.However,wereproducedtheirmethodswithamanual if (!state->rpacker.data){ need_blksize= blksize; …… if (need_blksize< tftp_blksize_default) analysisoftheresultsandfoundthatupto40%vulnerability- need_blksize= tftp_blksize_default irrelevant instructions were included. if (!state->rpacker.data){ After manually inspecting the source code snippets and the …… corresponding binary samples, we found that only blocks 3’ (a) (b) and 6’ are the actual patched blocks corresponding to green lines in Figure 1. Other changed blocks (i.e., blocks 1’, 4’, Fig. 1: An example vulnerable function tftp_connect and 5’) are not aligned with any changed source lines, but selectedfromCVE-2019-5482.(a)listspre-patchsourcecode, they map to the unchanged source code lines. The changes and (b) lists post-patch source code. Green lines are the in blocks 1’, 4’, and 5’ were due to replacing instructions patched source lines. Other lines remain intact across the two with the same semantics, which is the indirect impact of the versions. patched instructions. Existing work in [43, 44, 45] failed to identify these blocks as unchanged code. To rectify this issue, modified block VulMatchgeneratesandmatchesthevulnerablesignaturewith added block the guidance of the source code. We introduce the three steps of VulMatch as follows: 1 1’ Step1: Locating Signature Instructions.: We use the diff tool to measure source-code-level differences. Diff can detect and output a list of changed sites, added sites, and deleted sites. In the example shown in Figure 2, diff scans the source 2 2’’ code in Figure 1 and outputs one added site. Subsequently, we use the debugging information in the binary code (i.e., 7 3’ the source-binary lines mapping) to locate the patched binary 4’ lines.Inthediff’soutput,thechangedsitecontainsthesource code lines in both pre-patching and post-patching versions. 5’ 6’ However, the diff output for add site only contains the added source lines in the post-patching version (e.g., green lines in 7’ Figure 1 (b)). Since the added instructions do not exist in the pre-patching version, diff has no outputs for the pre-patching version. Therefore, for add type signature, an additional pro- cess will take place later in step 2 to find vulnerability-related instructions in the pre-patch version. (a) (b) Step2: Constructing Binary-level Signatures.: In this step, we use the located binary instructions in step 1 to construct Fig. 2: Corresponding binary code CFG of function the binary signatures. We store both vulnerable and patched tftp_connectpresentedinFigure1.(a)referstopre-patch signatures in the database. For the added signature, we still version, and (b) refers to post-patch version. Block 1’ is a need to generate its vulnerable binary signature even if diff modified block and blocks 3’, 4’, 5’, and 6’ are added blocks. outputs nothing at the source-code level. We cannot directly Other blocks remain intact. consider the absence of the added (patched) instructions to implyvulnerabilitybecauseanotherrandomfunctiondoesnot necessarilyhavetheadded(patched)instructions.Therandom block of instructions, and blocks 3’, 4’, 5’, and 6’ are added function needs to be not vulnerable. blocks of instructions. Other blocks remain intact. Therefore, we need to use the vulnerability-related instruc- Similarity-basedlinesofworkcomparethewholefunctions’ tionsinFigure2(a)toconstructavulnerabilitysignature.Note similaritiesbeforeidentifyingapotentiallyvulnerablefunction that the added instructions are inserted between block 2 and ifthefunctionissimilartothevulnerablefunction.Theyfocus block 7. Therefore, in the vulnerable version Figure 2(a), the on the whole function similarity rather than vulnerability- controlflowfromblock2toblock7impliesthevulnerability. relatedinstructions,resultinginpoorgranularity.Furthermore, InthepatchedversionFigure2(b),thecontrolflowfromblock they fail to distinguish the vulnerable and the patched func- 2’ to block 3’ and from block 3’ to block 6’ implies patch tions since they are regarded as similar. Patch-detection lines existence.Therefore,westorethecontrolflowfromblock2to of work first use the similarity lines of work to filter potential block7 asthe vulnerablesignature. Additionally,we storethe similar functions. They assume to select a similar function by control flow from block 2’ to block 3’ as the patch signature. name to detect the existence of the patch, where the binaries areLinuxkernelbinaries.However,asmentionedinsectionI, Step3:MatchingSignatures.: Foraquery(unknown)binary, ifthepatchdoesnotexist,itdoesnotnecessarilymeanthatthe we check whether the vulnerability is related to CVE-2019-4 bin CVEs Query Binary Database compile construct Src Bin Src Bin Bin Insn Addition Signature match map insert tags Patched Patched diff construct Delete Signature map compile Open Source Src Bin Src Bin Bin Insn Change construct Signature Projects Vulnerability Database Vulnerable Vulnerable Data preparation Locating Signature Instructions Constructing Context-aware Signature Matching Binary-level Signatures Fig.3:VulMatchconsistsoffoursteps:DataPreparation,LocatingSignatureInstructions,ConstructingContext-awareBinary- levelSignatures,andSignatureMatching.Srcisshortforsourcecode.Binisshortforbinarycode.Insnisshortforinstruction. 5482 stored in the database. If we store multiple signatures in vulnerability database. According to [44], vulnerabilities tend the database for one CVE, we will check each signature and to be fixed in new versions of software releases. Thus, the aggregate an overall score. For the changed or deleted signa- vulnerability-related versions consist of the last pre-patching
tures, we detect the percentage of the matched vulnerability and the first post-patching versions. The last pre-patching and instructions with respect to the query binary. For example, if the first post-patching version will be used later to extract the the changed signature block contains 5 instructions and 3 of signatures. We download all the vulnerability-related versions themexistinsomeblockinthequeryfunction,thenthescore for each project and record each CVE’s information. Specif- of the changed signature is 3/5=0.6. For the added signature, ically, for each CVE, we record its related vulnerable source we check the existence of the control flow (e.g., the stored code file name and the vulnerability-related functions within controlflowfromblock2toblock7inFigure2(a)).Wecount them. We also record each CVE’s affect versions for later howmanymatchedinstructionsexistinthequeryfunctionfor preparing testing binaries for evaluation. eachcontrolflow.Ifthereare10instructionsinblocks2and7, Challenges: Not all vulnerability-related functions exist in andwefoundasimilarcontrolflowinthequeryfunctionwith the compiled binary code due to the automatic function- 8 instructions matched, then the score is 8/10=0.8. However, inlining behavior. Automatic function-inlining refers to merg- if we detect the existence of the patch signature in the query ing a function FuncA into another function FuncB that calls function, we directly consider the query function contains a back FuncA. If vulnerable functions are inlined, it would be patchandoutputthatsignaturescoreas0.Finally,weaverage challengingtolocatetheminthebinarycode.Thiscaseholds all the signature scores according to their weights (instruction even if we manually turn off the function-inline option during sizes) to derive the overall score. compilation.Hence,itischallengingforustogeneratebinary Tosummarise,theinputofourproposedmethodtoproduce signatures. the vulnerable binary signatures are: 1) CVE information, Solution: We need to ensure that the database contains no including the last vulnerable version, first patched version, inlinedfunctionsinthecompiledbinaries.VulMatchautomat- and vulnerable function name. 2) Source code with different ically analyzes the source code files and edits the functions versions. Then, in the query phase, the input could be an un- in the source code files to inform the compiler not to inline knownbinarycodewithoutdebugginginformationandsource the function. Technically, VulMatch inserts a non-inline tag code. The output is a list of potentially matched CVEs with __attribute__((noinline)) before each vulnerable thesimilarityscore.Comparedtoexistingmethods,VulMatch functioninallrelatedversionstopreservethetaggedfunctions yieldsmoreaccuratebinarysignatureswithlessvulnerability- in the compiled binary code. For each CVE, VulMatch loads irrelevant instructions. VulMatch is able to accurately predict the CVE’s information to retrieve its vulnerable source code thevulnerablesitesinthequerybinaryratherthanonlygiving files along with the corresponding vulnerable functions. Then a similar code. VulMatch is able to accurately match the for each related version (i.e., the last pre-patching version real vulnerable binary code with fewer false positives among andthefirstpost-patching),VulMatchanalyzesthevulnerable several similar binary code snippets. sourcecodefiletolocatethevulnerablefunctionsandautomat- ically insert no-inline tags. Finally, we compile these versions III. METHODOLOGY into binaries with the same default compilation options. This section presents the design of VulMatch. VulMatch’s four components are shown as Figure 3. B. Locating Signature Instructions and Challenges A. Data Preparation Wegeneratesignaturesrelatedtovulnerabilitiesandpatches We collect many already well-studied vulnerabilities from using the source codes and compiled binary codes. For each several publicly-available open source projects to build the vulnerable function, we generate its signatures in two steps5 instruction. For example, Figure 4 shows an example of 1225static void j2k_write_sot(opj_j2k_t *j2k) { 1226 int lenp, len; missing mapping between source code and binary code. Lines 1226 and 1228 declare new variables but do not 1228 opj_cio_t*cio= j2k->cio; map to any binary instructions because the variables at the binary level are directly used without explicit type 1230 j2k->sot_start= cio_tell(cio); declaration due to the binary code convention. 1231 cio_write(cio, J2K_MS_SOT, 2); • Solution1: Generally, the source code lines declaring source code new variables (e.g., line 1226 and 1228 in Figure 4) do movrdi, rbx; mov[r14+0x30], eax; not have a mapping binary code because of binary code call379a; convention.However,itdoesnotaffectfindingthebinary signatures. We further elaborate on the following two movedx, 0x2; cases: 1) If a new variable declaration is added, it must movesi, 0xff90; be used later in some other source code lines, implying movrdi,rbx; that the correlated source lines still exist after diffing call37b0 source codes of the patched and vulnerable functions. binary code 2) If a variable’s name is changed, the source code Fig. 4: An example of a missing match between source code referring to that variable must change, which is detected and binary code. The first two lines 1226 and 1228 do not by diffing the source codes. For a variable with type have any mapping instructions in binary code because the change (e.g., change from a defined structure structA assembly code does not need to specify the type information to an updated structure structA’), source code lines for functions and variables. Line 1230 maps to two different using that variable tend to change because of different basicblocks.Line1231mapstoonebasicblock.Thisexample type usage (e.g., defining different fields in the different
is extracted from openjpeg version 1.5.0. structure type). • Challenge2: Identification of vulnerability-specific — 1) generate source-level vulnerability-related instructions, source lines. The add type signature is challenging to 2)locatevulnerability-relatedbinaryinstructionsthroughmap- represent. Because the add type signature only exists ping. in patched versions, the added instructions imply the 1) Generating Source-level Vulnerability-related Instruc- existence of a patch rather than the vulnerability itself. tions: We prepare the last pre-patching and the first post- Therefore,therearenodirectvulnerableinstructionsfrom patching versions using the information we retrieved in sub- the vulnerable version. For example, Figure 5a shows section III-A. Subsequently, we generate vulnerability and an example of the add type signature in the source- patch-related signatures on the source code level. We use the code level. Green lines (lines B2 to B6 on the right- diff tool2 to extract source-code-level patched instructions. hand side) are the added lines in the patched version, Therearethreetypesofsource-code-levelpatchesinthediff and grey lines are the unchanged lines across the two outputs. 1) Added instructions that are used in the patched versions.Theabsenceofthegreenlinesinthevulnerable version and absent in the vulnerable version, as shown in version implies a vulnerability. However, other random Figure 5a. 2) Deleted instructions that are removed from the functions may lack added instructions without the same vulnerableversionandabsentinthepatchedversionasshown vulnerability. Therefore, the lack of added instructions in Figure 5b. 3) Changed instructions that are updated from cannot be directly used as the vulnerable signature. We the vulnerable version to the patched version, as shown in need to infer the vulnerability signature in the vulnerable Figure 5c. The changed instructions usually share the same version to detect vulnerability existence. context instructions among the two versions. • Solution2: To represent add type vulnerability signature, 2) Locating Vulnerability-related Binary Instructions our solution is to focus on the context. For example, through Mapping: We use the source-to-binary mapping with lines A1 and B1 in Figure 5a are unchanged in the thebinary’sdebugginginformationtolocatethesourcecode’s two versions. A1 flows to A2 in the vulnerable version, corresponding assembly instructions. Although VulMatch while B1 flows to B2 in the patched version. The control employs the simple idea, there are practical challenges flow from the unchanged instruction A1 to the following primarily in two aspects. instructionA2isregardedasthevulnerabilitysignaturein 1) Asymmetric source-binary mapping: it is challenging to VulMatch. Conversely, the control flow from B1 to B2 is map source line changes in the source code files (e.g., regardedasapatchsignature.Sincetheaddedinstructions .cpp or .c file) to the corresponding binary file, are inserted at some point within the function, they must 2) Identification of vulnerability-specific source lines. haveidenticalcontextinstructions(e.g.,A1andB1inthe example) with different subsequent instructions (e.g., A2 Two challenges to map source code files: and B2). For simplicity, we explain this concept at the • Challenge1: Asymmetric source-binary mapping. Not source code level. But we extract add type signatures at all the source code lines have a matching binary code thebinarylevel.FormoredetailsrefertosubsectionIII-C. 2https://man7.org/linux/man-pages/man1/diff.1.html6 A1cp->tcps= (opj_tcp_t*) opj_calloc(cp- B1cp->tcps= (opj_tcp_t*) opj_calloc(cp- normal blocks >tw* cp->th, sizeof(opj_tcp_t)); >tw* cp->th, sizeof(opj_tcp_t)); 0 0 added blocks boundary blocks B2if (cp->tcps== NULL) B B3 4 { opj_event_msg(j2k->cinfo, 7 C 1 C le. a F din ind g e bq lou civ ka slent 7 1 B. Find leading D blocks E BV 5T_ER reR tO uR rn, ;"Out of memory\n"); D D bl. o F ci kn sd ’ cle oa nd ti rn og l flow D 9 D 4 A in. strF uin cd ti oa nd sd ed binary B6 } A2cp->tileno= (int*) opj_malloc(cp->tw* B7cp->tileno= (int*) opj_malloc(cp->tw 10 5 6 cp->th* sizeof(int)); * cp->th* sizeof(int)); A3cp->tileno_size= 0; B8cp->tileno_size= 0; 8 2 3 8 2 3 vulnerable source code patched source code vulnerable version binary patched version binary (a) Add Type Fig.6:Anexampleofbinary-code-leveladdsignatureandthe A1cp->tcps= (opj_tcp_t*) opj_calloc(cp- B1cp->tcps= (opj_tcp_t*) opj_calloc(cp- steps to extract the corresponding binary signature. >tw* cp->th, sizeof(opj_tcp_t)); >tw* cp->th, sizeof(opj_tcp_t)); A2if (cp->tcps== NULL) A3 { A4 opj_event_msg(j2k->cinfo, positives). EVT_ERROR, "Out of memory\n"); Since the added instructions in the patched version have A5 return; blocks directly preceding them, the counterpart preceding A6 } A7cp->tileno= (int*) opj_malloc(cp->tw B2cp->tileno= (int*) opj_malloc(cp->tw blocks in the vulnerable version should have different in- * cp->th* sizeof(int)); * cp->th* sizeof(int)); structions following them. Therefore, we capture local control A8cp->tileno_size= 0; B3cp->tileno_size= 0; vulnerable source code patched source code flows around the preceding blocks in the vulnerable version to represent the vulnerability signature. (b) Delete Type We propose to generate the binary-level signature with
A1cp->tcps= (opj_tcp_t*) opj_calloc(cp- B1cp->tcps= (opj_tcp_t*) opj_calloc(cp- control-flow information. Firstly, we define several terms. >tw* cp->th, sizeof(opj_tcp_t)); >tw* cp->th, sizeof(opj_tcp_t)); A2cp->tileno= (int*) opj_malloc(cp->tw B2cp->tileno= (int*) opj_malloc((cp->tw- • Add Batch.Whennewlyaddedsourcecodesnippetsare * cp->th* sizeof(int)); 1) * (cp->th-1) * sizeof(float)* cp->pl); mapped to binary code blocks, the newly added blocks A3cp->tileno_size= 0; B3cp->tileno_size= 0; could either be directly connected to each other (e.g., vulnerable source code patched source code block 4 and 5 in Figure 6) or separate from each other (c) Change Type (e.g., block 4 and 9 in Figure 6). An add batch is made Fig.5:Examplesofadd,deleteandchangetypes.Greenlines up of the added blocks that are strongly connected to are the newly added or changed instructions in the patched each other. As shown in Figure 6, block (4,5,6) and version. Red lines are the deleted or changed lines in the block (9,10) are two add batches. vulnerable version. Grey lines are the intact lines. • Leading Blocks. The leading block is the unchanged block immediately preceding an added batch. As shown in Figure 6, blocks 1 and 7 are two leading basic blocks because they immediately precede two add batches. C. Constructing Context-aware Binary-level Signatures • Parents-children Structure. We define a parents- Weconstructthebinary-code-levelsignaturesbeforestoring children structure to store the control flow and literal them in the database for signature matching. Simply storing information for add and change signatures. Specifically, thesetsofinstructionsinthedatabaseasvulnerablesignatures inoneparents-childrenstructure,wehaveaninitialblock and detecting those signatures’ existence in the query binary from the function as the parent. We include the chosen codemaynotbebeneficial.AsmentionedinsubsectionIII-B, block’s children blocks in the function into the parents- added instructions in the patched binary cannot directly be childrenstructure.Conversely,wecanselectachildblock usedtoformavulnerabilitysignaturebecauseitonlyindicates beforeincludingitsparentstoestablishaparents-children patches. The term context refers to the adjacent blocks’ in- structure. structionsofthevulnerablebinaryinstructions.Thevulnerable • Block List Structure. We define a block list structure to binaryinstructionsareusuallyshort.Ifwegeneratesignatures storeonlytheliteralinformationwhencontrol-flowinfor- bysimplyconcatenatingthoseinstructionsintoasequence,the mation is not available or unnecessary. In one block list signature may carry inadequate information to prevent false structure, we store all the vulnerable binary instructions positives. Therefore, we propose to form new structures by grouped by blocks. combining the context and the vulnerable instructions. Our Westorebothvulnerableandpatchsignatures.Vulnerability newlycombinedstructuregivesthesignatureadequateunique- signatures are generated from the instructions in the vulner- ness to boost the performance of signature matching. We able version. This signature type consists of parents-children propose to build the context around the vulnerable signature structures or block list structures. Patch signature consists of instructions through generalization to reduce false positives. theinstructionsthatonlyexistinthepatchedversionandonly For instance, the extracted signature instructions size is small consists of the block list structure. Patch signature is used (e.g.,only3instructions).Checkingtheexistenceofsignature to reduce the false positives further. Despite the vulnerability instructions without context information makes the signature match score, the patch signature directly implies a patch. The not unique enough, leading to excessive mismatches (false vulnerable signatures contain three types: 1) add, 2) delete,7 TABLE I: Information of the seven selected open-source projects. Project Domain Versions(#) BinaryFiles(#) .cFiles(#) .hFiles(#) CVEs(#) VulnerableFunctions(#) AvgSize Tcpdump PacketAnalyzer 20 152 167 78 192 213 20.45 Curl DataTransferring 67 315 419 197 111 231 44 OpenSSL Protocols 51 755 903 243 114 220 205 Openjpeg ImageProcessing 15 104 205 139 94 187 24.50 LibPNG ImageProcessing 63 39 36 14 52 50 6.90 Libtiff ImageProcessing 30 69 102 24 142 169 12.30 FFmpeg MultimediaProcessing 104 1206 1591 629 201 211 584 Total various 350 2640 3423 1324 906 1281 897.15 and 3) change. Those signatures have different structures One-block-change: Conversely,ifthechangeisaone-block- to capture different information because different signature change, the information is limited because we only have type has different nature. We capture various information for lexical information without control flow information. Thus, different signature types to enrich the signature information. we need to add more control flow information to enhance the For the add type signature, to locate the add type binary signatureandreducepotentialmismatch.Weincludeitsparent signatures, we A) retrieve the added binary instructions in blocksinaparents-childrenstructuretoenhancethesignature. the patched version (i.e., the output of the operations in Weincludethechildrenblocksintheparents-childrenstructure subsection III-B). B) We find the leading basic blocks in the if it has no parent block. patched version binary. C) We find its counterpart leading Patch signatures: We generate signatures for patches. After basic block in the vulnerable version binary. D) We include we generate vulnerable signatures as above, we diff the the vulnerable binary’s leading basic blocks’ children blocks vulnerability-related sites in both versions. We identify the as a parents-children structure in the signature. instructions that only exist in the patched version and store it using a block list structure as the patch signature. For the delete type signature, we directly locate the mapping binary instructions and store those instructions into
block list structures as delete signatures since the deleted D. Signature Matching instructionsusuallymaptomultipleblocks.Sincethemapped We detect the vulnerability’s existence by using both vul- blocks are usually sufficient in amount, lexical information nerability and patched signatures. For the add signature, we alreadymakesthesignatureuniqueformatching.Ifwerecord search for each vulnerable parents-children structure in the their control-flow information we will use excessive parents- query binary code. Then, we check for the existence of a children structures. We exclude any patch signature for this patch signature. If a patch is found, the function is directly signature type because the patched version does not have any considered patched. For the delete signature, we search for uniqueinstructionthatdoesnotexistinthevulnerableversion. the existence of the blocks from the block list structures. We The change type signature has two categories, includ- do not match patch signatures for the delete type because the ing one-block-change and many-blocks-change. Many-block- delete type does not has unique instructions in the patched change means the changed instructions are distributed in version. For the change signature, we search for the existence multiple blocks (i.e., distributed in neighbor blocks or blocks of each parents-children structure or block list structure in the that are not directly connected). One-block-change is the case query binary code. Subsequently, we check the existence of ifallthechangedinstructionsareaccommodatedinoneblock the patch signature. If the patch is found through a query, the in the binary code. functionisconsideredpatched(denotedbyP =1);otherwise, Many-block-change: Ifthechangeismany-block-change,we P =0. will need to record both control-flow and lexical information We propose a measurement of the vulnerability existence in the database since the change sites are usually small in score (Sim) to demonstrate the probability of the query size.Thiscategoryofsignatureprovidesrichinformationasit function containing a given vulnerable signature. Specifically, containsadequatelexicalinformation(i.e.,binaryinstructions) afinalscoreofvulnerabilityexistenceiscalculatedasfollows: from multiple blocks or control-flow information between  those blocks. Therefore, for each block in a many-block- Σl ie =n 1(S)Matched(S[i]) if P =0 Sim= Σlen(S)Total(S[i]) changes structure, if its neighbor (i.e., either predecessor or i=1 0 if P =1 successor block) is a change block, we include this neighbor to form a parents-children structure. If none of its neighbor where Sim represents the result similarity score to the vul- blocks is changed, all changed instructions are grouped as a nerable signature. S represents one vulnerable signature. A block in the signature. Note that if the many-block-change signature consists of one or multiple structures (a structure contains a deeper level other than two levels (i.e., the level of is either parents-children structure or block list structure). parents-children structure), we use multiple parents-children len() calculates the number of structures regarding an input structures to cover all the strongly connected blocks. For signature. S[i] represents a structure. Matched() calculates example, if block A flows to block B, and block B flows the number of instructions matched between the input struc- to block C, we will have two parents-children structures to ture and the given query binary function. If the structure is cover the flow from A to B and from B to A respectively. parents-children structure PS, Matched() searches through8 the query binary to find the similar parents-children structure PS′ with the maximum similarity. Then Matched() counts the instructions shared between PS and PS′. If the structure is a block list structure, Matched() finds all the blocks with cmpdwordptr[rsp+ 0x14], 1 cmpdwordptr[rsp+ 0x14], 1 jbeaddr jbeaddr themaximumsimilaritytoeachblockintheblockliststructure before Total() aggregates the total instruction number of the input structure. IV. EVALUATION mov dwordptr[rsp+ 0x14], 1 A. Experimental Setup mov dwordptr[rsp+ 0x14], 1 mov rdi, qword ptr[rsp+ 0x20] call addr Data Collection: We collected source code for seven open- source projects, including OpenSSL, OpenJPEG, FFmpeg, TCPDUMP, LibTIFF, cURL, and LibPNG. These projects are s i mme al ae ngc ut e ae ld pr af o nr co aem ls ys sd i in siv g ,e wr tos ee old es, xo tm a rana cdi tn es n del ti 9wk 0e o 6rc ko Cm t Vrm a Efu fi sn ci cc a oa n rt rai eo l syn pz op e nrr so d.t io nAc go ftl tes or, m m m cao o o llv v v a r e e dc d s dx ix , r, , 1 q 0w x2o frd ptr[rip + 0xfc246]m m m m cao o o o llv v v v a r e e e dc d s d dx ix i, r, , , 1 q "0 w ix s2o w2rd ri tp tt er n[ r ti op t+ h e0 x ff ilc e2 "2b]m m m cao o o llv v v a r e e dc d s dx ix , r, , 1 q 0w x2o frd ptr[rip + 0xfc236] m m m m cao o o o llv v v v a r e e e dc d s d dx ix i r,, , , 1q "0 w ix s2o w2rd ri tp tt er n[ r ti op t+ h e0 x "fc21b] 1,281 vulnerable functions. Table I lists the versions, appli- Fig. 7: Interpreting a many-block-change signature cation domains, CVE information, vulnerability, and code- matching. The left-hand side is the generated vulnerable related information. signature, and the right-hand side is the matched instructions Baseline Tool Selection and Testbed: We prepared two in the query binary. state-of-the-art baseline tools Asm2Vec [28] and PalmTree [46], because of their popularity and excellent performance in vulnerability detection. We ran VulMatch and Asm2vec on versionsarevulnerablebeforethatspecificversion.Therefore, an Intel NUC kit (NUC8i5BEH) with an i5-8259U processor weselectavulnerablebinaryfunctionf frombinarycodeBto
and 16 GB memory. Since Palmtree is a deep learning-based testhowthetoolsdiscoversimilarvulnerabilities.Weconstruct approach and requires intensive GPU power, we ran it on thevulnerableandpatchsignatureoff fromthelastpre-patch an accelerator cluster of high-performance computer (HPC) versionandthefirstpost-patchversionandstorethesignature systems with 456 NVidia Tesla P100, 114 Dual Xeon 14-core in the database. To test how well the signature in the database E5-2690, and 256 GB memory. can be matched, we prepare a binary version (denoted by B ) v Project Compilation: As mentioned in subsection III-A, we containing the vulnerable version of f (denoted as fv), and a compilealltheversionsrelatingtoeachvulnerability(i.e.,the patchedversionbinary(denotedbyB )containingthepatched p lastversionbeforepatchingandthefirstversionafterpatching) version of f (denoted as fp) for testing purpose. oftheprojecttogeneratebinarycodeinstances.Dependingon B andB shoulddifferfromtheversionsthatgeneratethe V P theproject,weusetheprojects’defaultcompilingflags,either binarysignature.B andB containmanyfunctions,including v p -O2 or -O3. For each project, we use identical compiling the vulnerable and patched version of f, and other functions. flags for building. So when we diff the compiled binary code Forvulnerablefunctionf,weinspecteachfunctionfiinboth to generate vulnerability and patch signatures, the compiling B and B to derive a match score indicating the percentage v p optionsarethesame.Thisminimizesthedifferencesinbinary thatfiissimilartof’svulnerablesignatures.fv inB should v codes and is the common practice as [44, 45] to help find have the highest score among all other functions; conversely, vulnerableinstructions.Atcompiletime,wesetthedebugging fpandallotherfunctionsinB shouldhavelowmatchscore. p symbol option to acquire source-binary instructions mapping It is reasonable for fp in B to have a higher score than other p that will serve as ground truth. functions in B since fp is patched from f. Nevertheless, fp p Research Questions: In the first experiment, we compare should be lower than fv’s score. We use the top-1 score to VulMatch with two state-of-the-art baseline tools to evaluate measure the rate of ranking ground truth vulnerable function how well they find known binary code vulnerabilities. In the in the first place. secondexperiment,wetesthowVulMatchinterpretsthefound Weprovideasimpleexampleofhowthetop-1scoreworks similar vulnerabilities and how VulMatch assists humans in inVulMatch.Supposetherearetenvulnerablefunctions,each understanding the reason it considers the query binary vul- with a vulnerable and a patched binary version B and B . v p nerable. In the third experiment, we match vulnerabilities in B containsfv.B containsfp.BothB andB alsocontain v p v p real-world firmware binaries to test how VulMatch work in a many other functions. We match the vulnerable signature of real-worldapplication.Inthefourthexperiment,weinvestigate f in the database with each function in both B and B . If v p how diverse types of proposed vulnerability signatures (i.e., vulnerable function fv has the highest score, we rank fv at add, delete, and change) distribute. the top-1 place. If 8 out of 10 vulnerable functions rank their testingvulnerableversionfv inthetop-1place,thenthetop-1 B. Performance Metrics score is 0.8. Top-1 Score: Each vulnerable function was patched after Mismatch Score: Merely referring to the top-1 score partly a certain version. And all the versions or a range of function reflects how accurately the tools distinguish ground truth9 TABLE II: Top-1 scores of seven open-source projects. A vulnerable functions from other functions. However, the top-1 higher score indicates a better performance. scorecannotwelldemonstratehowthetoolsconsiderthenon- ground-truthvulnerablefunctionasnon-vulnerable.Atoolthat identifies vulnerable functions well with a high top-1 score Project may not identify non-vulnerable functions as not vulnerable well. If non-vulnerable functions have extremely close match scores to vulnerable functions, this leads to a high mismatch score. Forinstance,sometoolsmayoutputasimilarityscoreofthe ground truth vulnerable function as 0.98, while the score for the ground truth patched function or another random function is 0.97. In this case, even though the ground truth function is ranked first, the two scores are too close to reaching the finalverdict.Thegroundtruthvulnerablefunctionshouldhave a significantly higher score than any other function. If any non-ground-truth vulnerable function has a score close to or higher than the ground-truth vulnerable function, the function receives a non-zero mismatch score. The mismatch score indicates the reliability of the top- 1 score. To keep track of the mismatch score of each vul- nerable function, the α parameter is a threshold to activate the mismatch score. We consider it a mismatch for any non- vulnerable function with a threshold above S −α, where GV S denotes the ground-truth vulnerable function score. If GV S has an extremely low score (e.g., near zero), any non- GV vulnerable function having a score close to or above S is GV not considered a mismatch. Because the root failure occurs in detecting a vulnerability function rather than non-vulnerable functions, we set S <0.6 as an extremely low score. GV C. Vulnerability Detection Since VulMatch aims to find replicated known vulnerabil- ities, and the two baseline tools Asm2vec and Palmtree find vulnerabilities based on binary code similarity, we compare VulMatch with those two baseline tools to test their perfor- manceonthefirstobjective—findingreplicatevulnerabilities.
Moreover, the query binary is non-deterministic in real-world scenarios since it could be either a vulnerable or patched version. Thus, it is vital to the second objective — differenti- ate vulnerable functions from other non-vulnerable functions. Therefore, we design this experiment to test these two goals concurrently. Vulnerable Function Detection Accuracy: Table II lists top-1 scores of VulMatch, Asm2vec, and Palmtree on the seven selected projects. Regarding the top-1 score, VulMatch outperforms both baseline methods in six projects and is marginallylowerthanPalmtreeonOpenSSL.VulMatchranks multipletestingvulnerablefunctionsatthetopafteritextracts accurate vulnerability signatures and matches vulnerable and patched signatures. It is because VulMatch matches the fine- grainedvulnerability-relatedinstruction(signature)ratherthan coarsely matches the whole function. Since the vulnerability signature tends to be small snippets of instructions, matching the whole function similarity fails to detect such fine-grained information. Non-Vulnerable Function Detection Accuracy: Table III lists mismatch measurements of VulMatch, Asm2vec, and Openjpeg FFmpeg Tcpdump Libtiff curl LibPNG OpenSSL Asm2vec 0.673 0.643 0.702 0.675 0.821 0.815 0.536 Palmtree 0.573 0.643 0.702 0.779 0.840 0.837 0.691 VulMatch 0.791 0.714 0.786 0.825 0.872 0.859 0.673 Palmtree with respect to different α values. In the mismatch score perspective, VulMatch achieved the best result with the lowest mismatch score, indicating that VulMatch differenti- ates the vulnerable version and patched versions with the highest confidence level. Conversely, Asm2vec and Palmtree had high mismatch scores, indicating that many decisions between vulnerable and patched versions were made with low confidence. Since α denotes the threshold distance to the vulnerableversionandS <0.6,wevaryαbetween0.1and GV 0.4 to obtain positive mismatch scores. Our evaluation results empirically suggest that alpha=0.1 yields the best result. For FFmpeg, VulMatch achieved mismatch scores as 0 compared with baseline methods’ mismatch scores of ap- proximately 1. For other projects, there are huge contrasts between VulMatch and baseline tools. VulMatch outperforms twobaselinetoolsbecauseVulMatchderivesvulnerablesigna- turesfromthevulnerableandpatchedversions.Anotherreason is VulMatch matches the fine-grained vulnerability signature rather than the coarse whole function similarity. Therefore, subtle vulnerability-related differences are accurately iden- tified, which is superior to whole-function-level similarity matching. D. Interpretability When finding vulnerable functions, a tool’s interpretability is as important as its high accuracy. In practice, vulnerability- detecting tools assist human experts in making a final verdict. Therefore, a good tool should clearly explain why a query resultisconsideredvulnerable.Unfortunately,thestate-of-the- art baselines fail to provide good interpretation functionality. Palmtree outputs only the overall similarity score between the query function and the functions stored in its database. In addition to the overall similarity score, Asm2vec lists similar instructions for the query. Asm2vec fails to highlight the vulnerability-related instructions; instead, it highlights the whole function as different or similar. Figure 7 demonstrates an example of VulMatch’s interpretability. This example is a many-block-change vulnerable signature matching selected from CVE-2016- 9117. The signature (left-hand side) was extracted from the imagetopnm function with versions 2.1.2 and 2.2.0. The matched instructions (right-hand side) in the query binary are from version 2.1.1. For the selected signature, there are 23 instructions in all structures, and 19 of them are matched. The unmatched instructions mov rcx, qword ptr [rip + 0xfc246], mov rcx, qword ptr [rip + 0xfc22b] on the left-hand side and the instructions mov rcx, qword ptr [rip + 0xfc236], mov rcx,10 TABLE III: Mis-match scores of seven open-source projects. A stands for Asm2vec, P for Palmtree, and V for VulMatch. A lower score indicates a better performance. α Project Openjpeg FFmpeg Tcpdump Libtiff curl LibPNG OpenSSL TABLEIV:VulnerabilityCWEtypesofthesevenopensource projects. A 0.700 0.929 0.881 0.968 0.949 0.924 0.945 0.1 P 0.909 0.821 0.905 0.955 0.750 0.946 0.936 V 0.091 0.000 0.190 0.162 0.038 0.098 0.118 A 0.836 0.964 0.988 1.000 1.000 1.000 1.000 0.2 P 0.982 1.000 0.940 1.000 0.885 1.000 0.955 V 0.127 0.000 0.286 0.260 0.103 0.152 0.127 A 0.900 1.000 1.000 1.000 1.000 1.000 1.000 0.3 P 0.991 1.000 0.940 1.000 0.974 1.000 0.955 V 0.155 0.000 0.429 0.312 0.147 0.163 0.182 A 0.962 1.000 1.000 1.000 1.000 1.000 1.000 0.4 P 1.000 1.000 0.976 1.000 1.000 1.000 0.964 V 0.173 0.000 0.500 0.383 0.224 0.196 0.218 qword ptr [rip + 0xfc21b] on the right-hand side havedifferentoffsetsduetostructurefieldsarechanged.Note that this vulnerable function has multiple signatures, and we omit others for clarity. The overall match score combining all signatures exceeds 0.867, indicating VulMatch’s high confidence level for the verdict. E. Real-world Vulnerability Detection Since IoT devices’ firmware reuse open-source projects,
they often contain 1-day vulnerabilities. In this experiment, we evaluate how effectively VulMatch detects a real-world 1-day vulnerability in an IoT device’s firmware. We select four IoT devices’ firmware instances (i.e., DCS-3511, DCS- 6517, DCS-7517, and DCS-6915) collected in the wild. We manually analyze the firmware and prepare 36 ground-truth 1-day vulnerabilities, including 52 vulnerable functions. We generate the vulnerability binary code signatures and store them in the database. For each vulnerable signature in the database,wedetectitagainsteachfunctionFiinthefirmware andassignamatchingscoreforFi.IftheFiwiththetopscore is the ground-truth vulnerable function, a vulnerable function is correctly detected. VulMatch correctly detects 40 out of 52 (77%) vulnerable functions. Again, the high accuracy in find- ing real-world replicate vulnerabilities is due to VulMatch’s concentrationonthefine-grainedvulnerableinstructionsalong withthelocalcontrol-flowinformation.Wemanuallyanalyzed the failed case and found two main failure causes: 1) The binary code contains other function(s) with high similarity to the vulnerable one. 2) The testing binary code contains different structure fields thus at the binary level, the offsets of the structures are different from the signature in the database. Forexample,[esi+0x40]changedto[esi+0x48]where esi is the memory address of the structure. The same field changed from offset 0x40 to offset 0x48 because of adding or deleting other fields in the structure. F. Statistics of Signature Distributions In this experiment, we investigate the distribution of the vulnerability according to 1) the Common Weakness Enumeration (CWE) type and 2) our defined three types openssl openjpeg libtiff libpng ffmpeg curl tcpdump NVD-CWE-Other 0.15 0.01 0.04 0.15 0.03 0.00 0.00 CWE-399 0.12 0.00 0.01 0.12 0.08 0.00 0.00 CWE-310 0.12 0.00 0.00 0.00 0.00 0.00 0.00 CWE-787 0.02 0.15 0.10 0.00 0.02 0.00 0.01 CWE-119 0.11 0.33 0.41 0.31 0.37 0.00 0.27 CWE-190 0.01 0.10 0.03 0.02 0.01 0.00 0.01 CWE-125 0.03 0.06 0.13 0.02 0.03 0.04 0.60 CWE-189 0.04 0.02 0.06 0.19 0.13 0.00 0.02 NVD-CWE-noinfo 0.01 0.01 0.00 0.08 0.14 0.00 0.01 CWE-126 0.00 0.00 0.00 0.00 0.00 0.13 0.01 CWE-122 0.00 0.05 0.00 0.00 0.00 0.09 0.00 CWE-305 0.00 0.00 0.00 0.00 0.00 0.09 0.00 TABLE V: Statistics of signatures in the 7 open source projects. OBC for one-block-change, and MBC for many- block-change. openssl openjpeg libtiff libpng ffmpeg curl tcpdump sig(#) 120 75 48 10 69 74 248 add Avg.size 50 77 257 46 185 103 61 sig(#) 37 17 9 1 9 20 64 delete Avg.size 6 3 6 9 10 4 6 sig(#) 109 172 61 27 61 85 114 OBC Avg.size 6 11 10 7 14 6 7 sig(#) 146 258 91 27 61 109 269 MBC Avg.size 14 23 24 9 20 14 12 (i.e., add, delete, change). Table IV lists the vulnerability distribution according to different CWE types. Specifically, we select the three most popular CWE types for each project and concatenate them into the table. We observe that Improper Restriction of Operations within the Bounds of a Memory Buffer (CWE-119) is the most common vulnerability type in our experiment (5 in 7 projects). Curl contains the most CWE vulnerability types (43 types), while LibPNG contains the least CWE types (11 types). Table V shows the distribution of the four types of vul- nerability signatures (i.e., add, delete, one-block-change, and many-block-change). Originally, there were three types (add, delete, change). We further split the change type into one- block-change and many-block-change for clarity. Sig (#) refers to the number of the signature type in the project. Avg. size refers to the average instruction amount of the specific signature in the project for each CVE. Generally, many-block-change is the dominant type in all datasets. The delete type is the least common type in all datasets. The add type contains the most instruction size because the add type involves at least two complete basic blocks to form the signature. Conversely, the delete type contains the least instruction size because the delete type does not contain control-flow information between multiple blocks that aremadeupofseparateblocks.Thechangetypesmayconsist of parent-children structures or separate blocks.11 V. DISCUSSION VI. RELATEDWORK We present the related work from the following threefold since they are closely related to this work: 1) code similarity detection, 2) patch analysis, and 3) vulnerability detection. Require Source Code: Compared to three state-of-the-art works [43, 44, 45], we require both source code and binary codetoextractthesignature.Allofthethreetools[43,44,45] A. Code Similarity Detection claim to only require binary code, but they require all the 1) Binary-code-level similarity detection: Binary-code- vulnerability-related versions of binary code, and the binary level similarity works are categorized in two directions ac- code must be compiled with the same optimization flag. This cording to their methods. assumptionisstrongbecauseonecannotguaranteethebinary Learning-based methods: Binary code instructions are en- versions (s)he collected from the wild are compiled with the coded into an embedding to compare the similarity. Gemini same options. Therefore, in their actual implementations, they [22], Vulseeker [23], and Genius [14] use graph feature still need the source code to generate different binary codes embeddingstodeterminevectorsimilarity.Safe[25],InnerEye with the same optimization options from which a signature is [26], αDiff [27], Kam1n0 [7], and Asm2Vec [28] learn the extracted.
instructions’ embeddings and generate block embeddings or Cross Architecture: VulMatch only investigates the vulner- function embeddings. able and patched code on the same architecture. However, the Program-analysis based methods: Instructions or blocks same source code could be compiled on different hardware areregardedassequencesinBinsequence[11]andTracy[12] architectures (e.g., ARM, x32, PowerPC, etc.) How to match using sequences-alignment methods to compare the similar- cross-architecture vulnerable signatures remains an open re- ity. Similarly, SIGMA [20], FOSSIL [19], and Beagle [18] search problem. Possible solutions include: 1) translating dif- rely on the instruction semantic categorizations like data ferentarchitectures’instructionsintoanintermediatelanguage, transfer, logic, or arithmetic. Bingo [32] and IMF-SIM [33] and 2) extracting vulnerable binary signatures on different use input-output relations to measure binary code similarity. architectures.However,thisissueisbeyondthispaper’sscope. Expose[10],Binhash[30],Binhunt[34],CoP[21],ESH[35], GITZ [36], and XMATCH [39] symbolically execute the bi- Differences Introduced by Compilation: An important narycodebeforethesimilaritycomparisonbasedonsymbolic challenge is mitigating instruction differences introduced by formulas. different compiling optimization settings, different compilers, anddifferentcompilerversions.Thispaperonlyconsideredthe Limitations: However, similarity-based methods match the project’sdefaultoptimizationoptionsandourtestingsystem’s wholefunctionsimilarity.Vulnerableinstructionsonlyinvolve defaultcompiler.Itispossibletoobservethebinariescompiled severallinesofcodeinthefunction.Therefore,thesimilarity- with different optimization levels or compilers in the wild. A based method can filter similar functions but cannot distin- plausible solution is to utilize symbolic execution to mitigate guish whether the function is vulnerable. the impact of different optimization levels as [40]. However, symbolic execution is time-consuming to execute. Another B. Patch Identification and Analysis possible solution without changing our current methodology FIBER[40]detectspatchexistenceinLinuxkernelbinaries is to increase our training data. The training data refers to based on symbolic execution. Using symbolic execution and the binaries we extract signatures from. Since we only extract memory status, PDiff [41] detects Linux kernel binaries’ vulnerability signatures from vulnerable and patched versions patch existence when binaries are different due to patch compiled by their default optimization level and the default customization,differentbuildconfiguration,andotherreasons. compiler,thecurrenttrainingdataarelimited.Todetectcross- Spain [4] uses binary-level semantic information to identify optimization-level or cross-compiler signatures, a possible thepatchbeforesummarizingpatchandvulnerabilitypatterns. solution is to compile the project using multiple optimization Patchscope [42] identifies patch existence based on memory- levels or compilers and extract their corresponding signatures. object-centric methods and dynamic execution. Patchandvulnerabilitydetectiongenresofworkdirectlyex- Limitations: This category of prior work assumes that the tract assembly instructions and form signatures. The state-of- function names are provided or that some similar candidate the-art whole-function similarity matching adopts many data- functions have already been selected by the code-similarity- driven methods. Asm2vec [28] and Palmtree [46] convert the based method. Moreover, they focus on patch detection rather assembly instructions into vectors to mitigate subtle assembly than vulnerability detection. The lack of a patch does not differences introduced by compilations to some extent. Data- necessarily imply that the function is vulnerable. driven methods usually take less time than other methods. Merging these two methods by generating vectorized fine- C. Vulnerability Detection grained signatures detects fine-grained signatures and miti- gates assembly differences with less time and cost. Graph VMPBL [43] builds a database storing vulnerable and attributes-basedvectorsaregeneratedin[22,23].Therefore,it patched functions to distinguish the pre-patch and post- is possible to extend VulMatch by incorporating fine-grained patched functions. VIVA [44] collects binary with versions graph-based embeddings as the signature. before and after the patch and directly diff the pre-patch12 and post-patch functions to retrieve binary-level vulnerability [6] X. Hu, T.-c. Chiueh, and K. G. Shin, “Large-scale signatures. VIVA further detects vulnerability existence based malware indexing using function-call graphs,” in Pro- on pre-filtering and instruction clustering. BINXRAY [45] ceedings of the 16th ACM Conference on Computer and requires pre-patch and post-patch version binaries to analyze Communications Security, 2009, pp. 611–620. the vulnerability-related instructions in both versions before [7] S. H. H. Ding, B. Fung, and P. Charland, “Kam1n0: storing instructions in the database as vulnerability and patch Mapreduce-based assembly clone search for reverse en- signatures. BINXRAY checks the vulnerability’s existence in gineering,” in Proceedings of the ACM SIGKDD Inter- a query function based on its closest signature version. national Conference on Knowledge Discovery and Data Limitations: This genre of work is most similar to our Mining, 2016.
methods. However, they assume all the different binary codes [8] B. Kang, T. Kim, H. Kwon, Y. Choi, and E. G. Im, between versions are related to the vulnerability, this often “Malware classification method via binary content com- introduces many vulnerability-irrelevant instructions into sig- parison,” in Proceedings of the 2012 ACM Research in natures. Applied Computation Symposium, 2012, pp. 316–321. [9] I. Santos, F. Brezo, J. Nieves, Y. K. Penya, B. Sanz, C. Laorden, and P. G. Bringas, “Idea: Opcode-sequence- VII. CONCLUSION basedmalwaredetection,”inProceedingsoftheInterna- In this paper, we proposed a novel approach called tional Symposium on Engineering Secure Software and VulMatch to extract and match binary-level vulnerability- Systems, 2010, pp. 35–43. related signatures. VulMatch consists of four steps: 1) data [10] B.H.NgandA.Prakash,“Expose:Discoveringpotential preparation, 2) locating signature instruction, 3) construct- binary code re-use,” in Proceedings of the IEEE Annual ing context-aware binary-level signatures, and 4) signature Computer Software and Applications Conference, 2013, matching. Compared to previous work, VulMatch accurately pp. 492–501. locates vulnerability-related instructions and detects vulnera- [11] H. Huang, A. M. Youssef, and M. Debbabi, “Binse- bility within functions. Through our empirical studies, Vul- quence: Fast, accurate and scalable binary code reuse Match outperformed two state-of-the-art similarity-based vul- detection,” in Proceedings of the 2017 ACM on Asia nerability detection tools — Asm2vec [28] and Palmtree [46]. Conference on Computer and Communications Security, Specifically, VulMatch achieved the most accurate results on 2017, pp. 155–166. six out of seven projects with the least ambiguities while [12] Y. David and E. Yahav, “Tracelet-based code search in providing reasons for vulnerable functions. Hence, VulMatch executables,” ACM SIGPLAN Notices, vol. 49, no. 6, pp. effectively facilitates human understanding of its decision 349–360, 2014. processduringvulnerabilitydetection.Ourexperimentonreal- [13] B. S. Baker, U. Manber, and R. Muth, “Compressing world firmware vulnerability detection indicates VulMatch is differences of executable code,” in Proceedings of the practical to find vulnerabilities in real-world scenarios. Our ACMSIGPLAN Workshop on Compiler Support for Sys- analysisofvulnerabilitydistributionsconfirmedthatVulMatch tem Software, 1999, pp. 1–10. isaversatiledetectorwithgoodpotentialforfutureextension. [14] Q.Feng,R.Zhou,C.Xu,Y.Cheng,B.Testa,andH.Yin, “Scalable graph-based bug search for firmware images,” REFERENCES in Proceedings of the 2016 ACM SIGSAC Conference [1] J. Heffley and P. Meunier, “Can source code auditing on Computer and Communications Security, 2016, pp. software identify common vulnerabilities and be used 480–491. to evaluate software security?” in Proceedings of the [15] M. Bourquin, A. King, and E. Robbins, “Binslayer: Ac- 37thAnnualHawaiiInternationalConferenceonSystem curatecomparisonofbinaryexecutables,”inProceedings Sciences. IEEE, 2004, pp. 21:1–10. of the ACM SIGPLAN Program Protection and Reverse [2] S. Haefliger, G. Von Krogh, and S. Spaeth, “Code reuse Engineering Workshop, 2013. in open source software,” Management Science, vol. 54, [16] S. Cesare, Y. Xiang, and W. Zhou, “Control flow-based no. 1, pp. 180–193, 2008. malware variant detection,” IEEE Transactions on De- [3] ——, “Code reuse in open source software,” Manage- pendable and Secure Computing, vol. 11, pp. 307–317, ment Science, vol. 54, no. 1, pp. 180–193, 2008. 2014. [4] Z.Xu,B.Chen,M.Chandramohan,Y.Liu,andF.Song, [17] W. M. Khoo, A. Mycroft, and R. Anderson, “Ren- “Spain: Security patch analysis for binaries towards dezvous: A search engine for binary code,” in Proceed- understanding the pain and pills,” in Proceedings of ingsofthe2013WorkingConferenceonMiningSoftware the 2017 IEEE/ACM 39th International Conference on Repositories, 2013, pp. 329–338. Software Engineering (ICSE). IEEE, 2017, pp. 462– [18] M. Lindorfer, A. Di Federico, F. Maggi, P. M. Com- 472. paretti,andS.Zanero,“Linesofmaliciouscode:Insights [5] M. R. Farhadi, B. C. Fung, P. Charland, and M. Deb- into the malicious software industry,” in Proceedings babi, “Binclone: Detecting code clones in malware,” in of the ACM Annual Computer Security Applications Proceedingsofthe2014EighthInternationalConference Conference, 2012, pp. 349–358. on Software Security and Reliability (SERE), 2014, pp. [19] S. Alrabaee, P. Shirani, L. Wang, and M. Debbabi, 78–87. “Fossil: A resilient and efficient system for identifying13 foss functions in malware binaries,” ACM Transactions Proceedings of the 2017 32nd IEEE/ACM International on Privacy and Security, 2018. Conference on Automated Software Engineering (ASE), [20] ——, “Sigma: A semantic integrated graph matching 2017, pp. 342–352. approachforidentifyingreusedfunctionsinbinarycode,” [32] M. Chandramohan, Y. Xue, Z. Xu, Y. Liu, C. Y. Cho, Digital Investigation, pp. S61–S71, 2015. and H. B. K. Tan, “Bingo: Cross-architecture cross-os [21] L.Luo,J.Ming,D.Wu,P.Liu,andS.Zhu,“Semantics- binary search,” in Proceedings of the ACM SIGSOFT based obfuscation-resilient binary code similarity com- International Symposium on Foundations of Software parison with applications to software plagiarism de- Engineering, 2016.
tection,” in Proceedings of the 22nd ACM SIGSOFT [33] S. Wang and D. Wu, “In-memory fuzzing for binary International Symposium on Foundations of Software code similarity analysis,” in Proceedings of the 2017 Engineering, 2014, pp. 389–400. 32ndIEEE/ACMInternationalConferenceonAutomated [22] X. Xu, C. Liu, Q. Feng, H. Yin, L. Song, and D. Song, SoftwareEngineering(ASE). IEEE,2017,pp.319–330. “Neural network-based graph embedding for cross- [34] S.-C. Wang, C.-L. Liu, Y. Li, and W.-Y. Xu, “Semdiff: platform binary code similarity detection,” in Proceed- Finding semtic differences in binary programs based on ingsof the2017ACMSIGSAC ConferenceonComputer angr,” in Proceedings of the 2017 ITM Web of Confer- and Communications Security, 2017, pp. 363–376. ences, 2017. [23] J.Gao,X.Yang,Y.Fu,Y.Jiang,andJ.Sun,“Vulseeker: [35] Y.David,N.Partush,andE.Yahav,“Statisticalsimilarity Asemanticlearningbasedvulnerabilityseekerforcross- of binaries,” ACM SIGPLAN Notices, vol. 51, no. 6, pp. platform binary,” in Proceedings of the 2018 33rd 266–280, 2016. IEEE/ACMInternationalConferenceonAutomatedSoft- [36] ——, “Similarity of binaries through re-optimization,” ware Engineering (ASE), 2018, pp. 896–899. in Proceedings of the 38th ACM SIGPLAN Conference [24] E. Mengin and F. Rossi, “Binary diffing as a network on Programming Language Design and Implementation, alignment problem via belief propagation,” in Proceed- 2017. ings of the 2021 36th IEEE/ACM International Confer- [37] A. Lakhotia, M. D. Preda, and R. Giacobazzi, “Fast lo- ence on Automated Software Engineering (ASE). IEEE, cation of similar code fragments using semantic ‘juice’,” 2021, pp. 967–978. in Proceedings of the 2013 ACM SIGPLAN Program [25] L. Massarelli, G. A. D. Luna, F. Petroni, R. Baldoni, Protection and Reverse Engineering Workshop, 2013. and L. Querzoni, “Safe: Self-attentive function embed- [38] J. Pewny, F. Schuster, L. Bernhard, T. Holz, and dings for binary similarity,” in Proceedings of the 2019 C. Rossow, “Leveraging semantic signatures for bug International Conference on Detection of Intrusions and searchinbinaryprograms,”inProceedingsoftheAnnual Malware,andVulnerabilityAssessment. Springer,2019, Computer Security Applications Conference, 2014, pp. pp. 309–329. 406–415. [26] F. Zuo, X. Li, Z. Zhang, P. Young, L. Luo, and Q. Zeng, [39] Q. Feng, M. Wang, M. Zhang, R. Zhou, A. Henderson, “Neural machine translation inspired binary code simi- and H. Yin, “Extracting conditional formulas for cross- laritycomparisonbeyondfunctionpairs,”inProceedings platform bug search,” in Proceedings of the 2017 ACM of the 2022 Network and Distributed System Security on Asia Conference on Computer and Communications Symposium (NDSS), 2022. Security, 2017, pp. 346–359. [27] B. Liu, W. Huo, C. Zhang, W. Li, F. Li, A. Piao, and [40] H. Zhang and Z. Qian, “Precise and accurate patch W. Zou, “αdiff: Cross-version binary code similarity de- presence test for binaries,” in Proceedings of the 27th tectionwithdnn,”inProceedingsofthe33rdACM/IEEE USENIX Security Symposium (USENIX Security 18), International Conference on Automated Software Engi- 2018, pp. 887–902. neering, 2018, pp. 667–678. [41] Z. Jiang, Y. Zhang, J. Xu, Q. Wen, Z. Wang, X. Zhang, [28] S. H. Ding, B. C. Fung, and P. Charland, “Asm2vec: X. Xing, M. Yang, and Z. Yang, “Pdiff: Semantic- Boostingstaticrepresentationrobustnessforbinaryclone based patch presence testing for downstream kernels,” search against code obfuscation and compiler optimiza- in Proceedings of the 2020 ACM SIGSAC Conference tion,” in Proceedings of the 2019 IEEE Symposium on on Computer and Communications Security, 2020, pp. Security and Privacy (SP). IEEE, 2019, pp. 472–489. 1149–1163. [29] J. Pewny, B. Garmany, R. Gawlik, C. Rossow, and [42] L. Zhao, Y. Zhu, J. Ming, Y. Zhang, H. Zhang, and T. Holz, “Cross-architecture bug search in binary exe- H. Yin, “Patchscope: Memory object centric patch diff- cutables,” in Proceedings of the 2015 IEEE Symposium ing,” in Proceedings of the 2020 ACM SIGSAC Confer- on Security and Privacy, 2015, pp. 709–724. ence on Computer and Communications Security, 2020, [30] W. Jin, S. Chaki, C. Cohen, A. Gurfinkel, J. Havrilla, pp. 149–165. C. Hines, and P. Narasimhan, “Binary function clus- [43] D. Liu, Y. Li, Y. Tang, B. Wang, and W. Xie, “Vmpbl: tering using semantic hashes,” in Proceedings of the Identifyingvulnerablefunctionsbasedonmachinelearn- 2012InternationalConferenceonMachineLearningand ing combining patched information and binary compari- Applications, 2012, pp. 386–391. son technique by lcs,” in Proceedings of the 2018 17th [31] U. Karge´n and N. Shahmehri, “Towards robust IEEE International Conference On Trust, Security And instruction-level trace alignment of binary code,” in Privacy (TrustCom/BigDataSE). IEEE, 2018, pp. 800–14 807. APPENDIX [44] Y. Xiao, Z. Xu, W. Zhang, C. Yu, L. Liu, W. Zou, A. Considerations of Header Files Z. Yuan, Y. Liu, A. Piao, and W. Huo, “Viva: Binary In Section III B:Locating Signature Instructions and Chal- level vulnerability identification via partial signature,” lenges, when we locate the vulnerable binary code from in Proceedings of the 2021 IEEE International Confer- sourcecode,insomecases,certainCVEsincludesourcecode ence on Software Analysis, Evolution and Reengineering
changes in the corresponding header (.h) files. However, such (SANER). IEEE, 2021, pp. 213–224. CVEs are less frequent in number (i.e., 26 CVEs in total out [45] Y.Xu,Z.Xu,B.Chen,F.Song,Y.Liu,andT.Liu,“Patch of nearly 1000 CVEs). After manually analyzing the changes based vulnerability matching for binary programs,” in in the header (.h) files due to the addition of patching codes, Proceedings of the 29th ACM SIGSOFT International wediscoveredthreetypesofchanges,including1)Changein Symposium on Software Testing and Analysis, 2020, pp. MACRO values, 2) change in structure member variables 376–387. (i.e.,changing,adding,ordeletingstructuremembervariables, [46] X. Li, Y. Qu, and H. Yin, “Palmtree: Learning an and 3) change in the function definition. assembly language model for instruction embedding,” Change of MACRO value.: Diffing the source code in Proceedings of the 2021 ACM SIGSAC Conference versions cannot detect MACRO value changes in the .h on Computer and Communications Security, 2021, pp. file (e.g., #define HAVE_DIRENT_H 1 to #define 3236–3251. HAVE_DIRENT_H 0). However, we omit this concern due to the tiny number of the MACRO changing related CVEs (i.e., 8 out of nearly 1000 CVEs). Change of structure member.: Structure members can be modified in a few ways — changing, adding, or deleting. Fig- ure8demonstratessomeexamplesforeachtype.Specifically, changing structure members include renaming the member and changing the type of existing member. Figure 8 B and C shows two examples of renaming member and changing member type, respectively. The source code with red text font represents the code to be deleted, and the green font means the instructions to be added in the patched version. If a structure member is deleted, the .c files source codes mentioning the member must also be deleted. Those source code line changes can be detected by diffing the .c files. For the adding or changing structure members cases, it is difficult to detect the changes by diffing the .c source codes. For example, assume that we observe a structure member is added, as shown in Figure 8 E, one may think that the added structure member new_member may not have a correspond- ing update in the .c file referencing it. To identify this case’s frequency, we manually inspected all 26 CVEs. We found that when members are added or changed in the structure, there must be corresponding new source code lines updated in the .c files referencing them. Therefore, in approximately 1000 vulnerability functions, we found in 100% cases, the changed or added members have corresponding references in the .c files. A possible explanation is that the newly added or changed structure members are specifically designed to be used in the .c files to avoid vulnerabilities. Figure 8 D and E show two examples of deleting and adding a structure member,respectively.Intheapproximate1000vulnerabilities, we observe that all the structure member changing, adding, or deleting can be detected with the diff tool. Change of function definition.: Changing of func- tion definition refers to changing function calling pa- rameters (e.g., change function definition static void j2k_write_sot(opj_j2k *j2k) to static void j2k_write_sot(opj_j2k *j2k, int lenp)). This category of change can be reflected in the source code. Function calling parameter changes can be detected in the .c15 typedef struct opj_t2 { ChaoChenreceivedhisPhDdegreeinInformation opj_common_ptrcinfo; TechnologyfromDeakinUniversityin2017.Heis opj_image_t*image; focusingonusingAIandadvancedanalyticstosolve opj_cp_t*cp; real-world problems, such as network traffic analy- } opj_t2_t; sis for abnormal behaviour, social spam detection, A. Origin structure insider threat detection, and software vulnerability. He is also conducting research on responsible AI, typedef struct opj_t2 { typedef struct opj_t2 { such as the transparency and trustworthy of AI -opj_common_ptrcinfo; opj_common_ptrcinfo; +opj_common_ptrcstructinfo; opj_image_t*image; applications in enterprises. He has published more opj_image_t*image; -opj_cp_t*cp; than 40 research papers in refereed international opj_cp_t*cp; +opj_image_t*cp; journalsandconferences(with16Q1journals),such } opj_t2_t; } opj_t2_t; as ACM Computing Surveys (CSUR), IEEE Transactions on Information B. Renaming a member C. Changing a member type ForensicsandSecurity(TIFS),PrivacyEnhancingTechnologiesSymposium (PETS)andACMAsiaConferenceonComputer&CommunicationsSecurity typedef struct opj_t2 { (ASIACCS). One of his papers was the featured article of that issue (IT typedef struct opj_t2 { opj_common_ptrcinfo; ProfessionalMar.-Apr.2016). -opj_common_ptrcinfo; opj_image_t*image; opj_image_t*image; opj_cp_t*cp; opj_cp_t*cp; +opj_image_t*new_member; } opj_t2_t; } opj_t2_t; D. Deleting a member E. Adding a member MuhammadEjazAhmedisaSeniorResearchSci- Fig.8:Examplesofstructurememberchanges.Aistheorigi- entistatData61,CSIRO,Australia’snationalscience nalstructureinthevulnerableversion.BtoEaretheexamples agency.Hisresearchinterestsincludemalware(ran- somware)detection,threathunting,digitalforensics, in the patched version. Red fonts mean the instructions to be program analysis, natural language processing, and deleted,andgreenfontmeansthenewinstructionstobeadded machine learning. He received the B.Sc. degree in in the patched version. The example is from openjpeg version computer sciences from Peshawar University, and the M.S. degree from National University of Sci- 1.5.0. encesandTechnology(NUST),Pakistanin2006and 2011, respectively. He completed the Ph.D. degree fromElectronicsandRadioEngineeringDepartment
atKyungHeeUniversityofSouthKoreainFebruary2014.Priortothat,he filesreferencingthatfunctionbecausethesourcecodemustbe waspostdocwithPOSTECHSouthKoreafromJune2014toMay2015.He updatedtohandledifferentparameters.Sinceweareextracting was with Sungkyunkwan University of South Korea as a research professor vulnerable function signatures between the vulnerable and fromJune2015toMay2018. patchedversions,newlyaddedfunctionsanddeletedfunctions are out of scope because they either only exists in the vulnerable version or only in the patched version. ShigangLiu(M’15)receivedhisPhDinComputer SciencefromDeakinUniversity,Australiain2017. He is currently a research fellow at the School of Science, Computing and Engineering Technolo- gies at Swinburne University of Technology. His research primarily focuses on data-driven software ZianLiureceivedthebachelorofinformationtech- security,networksecurity,appliedmachinelearning, nology degree from Deakin University Australia, and fuzzy information processing. In 2019, his re- in 2018. He is currently working towards the PhD search won first place in the World Change Maker degree at the Swinburne University of Technology. PrizeattheSwinburneResearchConference.Hehas His research interests include binary code analysis, served as Program Chair for various international especiallyinvulnerabilitydetection. conferencessuchasCSS2017/2020/2022,NSS2020/2022,ML4CS2019,So- cialSec2022,IEEEBlockchain2022,andsoon. Jun Zhang (M’12-SM’18) received the Ph.D. de- gree in Computer Science from the University of Wollongong, NSW, Australia, in 2011. He is cur- rentlyafullProfessorandtheDirectorofthecyber- Lei Pan received the Ph.D. degree in computer security lab, Swinburne University of Technology, forensicsfromDeakinUniversity,Australia,in2008. Australia. He was recognized in The Australian’s HeiscurrentlyaSeniorLecturerwiththeCentrefor top researchers special edition publication as the CyberResilienceandTrust(CREST),SchoolofIn- leadingresearcherinthefieldofComputerSecurity formation Technology, Deakin University. He leads & Cryptography in 2020. He leaded Swinburne the research theme ‘Securing Data and Infrastruc- cybersecurity research and produced excellent out- ture’ at CREST. His research interests cover broad come including many high impact research papers topicsincybersecurityandprivacy.Hehasauthored and multi-million-dollar research projects. Swinburne was named in The 100researchpapersinrefereedinternationaljournals Australian’s 2021 Research magazine, the top research institution in the and conferences, such as IEEE Transactions on In- field of Computer Security & Cryptography. He has served as a steering formationForensicsandSecurity,IEEETransactions committeememberoftheP-TECHprogramatMelbournesince2019,which on Dependable and Security Computing, IEEE Transactions on Industrial the Australian Government invested in, promoting STEM education. He Informatics,andmanymore. devoteshimselftocommunicationandcommunityengagement,boostingthe awarenessofcybersecurity.16 Dongxi Liu is a Principal Research Scientist in CSIRO’sData61,joinedCSIROsince2008.Hisre- search interests include applied cryptography, post- quantum cryptography, and distributed system se- curity. His work aims to design and build secure systems that are scalable, simple to use, with high trusttosecurityandresilienttoattacks.
2308.03314 GPTScan: Detecting Logic Vulnerabilities in Smart Contracts by Combining GPT with Program Analysis YuqiangSun DaoyuanWu∗ YueXue NanyangTechnologicalUniversity NanyangTechnologicalUniversity MetaTrustLabs Singapore,Singapore Singapore,Singapore Singapore,Singapore suny0056@e.ntu.edu.sg daoyuan.wu@ntu.edu.sg xueyue@metatrust.io HanLiu HaijunWang ZhengziXu EastChinaNormalUniversity Xi’anJiaotongUniversity NanyangTechnologicalUniversity Shanghai,China Xi’an,China Singapore,Singapore hanliu@stu.ecnu.edu.cn haijunwang@xjtu.edu.cn zhengzi.xu@ntu.edu.sg XiaofeiXie YangLiu SingaporeManagementUniversity NanyangTechnologicalUniversity Singapore,Singapore Singapore,Singapore xfxie@smu.edu.sg yangliu@ntu.edu.sg ABSTRACT amountingtobillionsofdollars[66].Thissituationisadisaster Smart contracts are prone to various vulnerabilities, leading to forDeFiserviceproviders,posingasignificantthreattotheentire substantialfinanciallossesovertime.Currentanalysistoolsmainly DeFiecosystemandthesafetyofusers’assets. targetvulnerabilitieswithfixedcontrol-ordata-flowpatterns,such Despitetheavailabilityofnumerousanalysistools[29,30,37,43, asre-entrancyandintegeroverflow.However,arecentstudyon 56],theyoftenfocusonvulnerabilitieswithfixedcontrol-ordata- Web3securitybugsrevealedthatabout80%ofthesebugscannotbe flowpatterns,suchasre-entrancy[52,61],integeroverflow[54], auditedbyexistingtoolsduetothelackofdomain-specificproperty andaccesscontrolvulnerabilities[36,39,46].However,arecent descriptionandchecking.GivenrecentadvancesinLargeLanguage studyconductedbyZhangetal.[65]onWeb3securitybugsre- Models(LLMs),itisworthexploringhowGenerativePre-training vealsthataround80%ofthesevulnerabilitiesremainundetected Transformer(GPT)couldaidindetectinglogicvulnerabilities. byexistingtools.Theseundetectedvulnerabilitiesareprimarily Inthispaper,weproposeGPTScan,thefirsttoolcombiningGPT associatedwiththebusinesslogicofsmartcontracts.Traditional withstaticanalysisforsmartcontractlogicvulnerabilitydetection. staticanddynamicanalysisschemes,suchasSlither[37],donot InsteadofrelyingsolelyonGPTtoidentifyvulnerabilities,which effectivelyaddressthesevulnerabilitiesinsmartcontractsbecause canleadtohighfalsepositivesandislimitedbyGPT’spre-trained theydonotaimtocomprehendtheunderlyingbusinesslogicof knowledge,weutilizeGPTasaversatilecodeunderstandingtool. smartcontracts,nordotheymodelthefunctionalityorconsider Bybreakingdowneachlogicvulnerabilitytypeintoscenariosand therolesofvariousvariablesorfunctions. properties,GPTScanmatchescandidatevulnerabilitieswithGPT.To Inthispaper,weexplorehowrecentadvancesinLargeLan- enhanceaccuracy,GPTScanfurtherinstructsGPTtointelligently guageModels(LLMs)[5]orGenerativePre-trainingTransformer recognizekeyvariablesandstatements,whicharethenvalidatedby (GPT)[44,49]couldaidindetectinglogicvulnerabilitiesinsmart staticconfirmation.Evaluationondiversedatasetswitharound400 contracts.Arecenttechnicalreport[34]attemptedtouseGPTby contractprojectsand3KSolidityfilesshowsthatGPTScanachieves providingitwithhigh-levelvulnerabilitydescriptionsforproject- highprecision(over90%)fortokencontractsandacceptablepreci- wide“Yes-or-No”inquiries,whichisalreadyeasierthantypical sion(57.14%)forlargeprojectslikeWeb3Bugs.Iteffectivelydetects function-levelvulnerabilitydetection.However,thisapproachsuf- ground-truthlogicvulnerabilitieswitharecallofover70%,includ- feredfromahighfalsepositiverateofaround96%andrequired ing9newvulnerabilitiesmissedbyhumanauditors.GPTScanis advancedreasoningcapabilitiesfromGPT,necessitatingtheuseof fastandcost-effective,takinganaverageof14.39secondsand0.01 GPT-4insteadofGPT-3.5.Instead,wetreatGPTasagenericand USDtoscanperthousandlinesofSoliditycode.Moreover,static powerfulcodeunderstandingtoolandinvestigatehowthiscapa- confirmationhelpsGPTScanreducetwo-thirdsoffalsepositives. bilitycanbecombinedwithstaticanalysistocreateanintelligent detectionsystemforlogicvulnerabilities. Tothisend,weproposeGPTScan,thefirsttoolthatcombines 1 INTRODUCTION GPTwithstaticanalysisfordetectinglogicvulnerabilitiesinsmart Smartcontractshaveemergedasthecornerstoneofdecentralized contracts.ToleverageGPT’scodeunderstandingcapability,we finance(DeFi),providingaprogrammableandautomatedsolution breakdowneachlogicvulnerabilitytypeintocode-levelscenar- forexecutingfinancialtransactions.However,thesecurityofthese iosandproperties.Scenariosdescribethecodefunctionalityunder smartcontractshasbecomeamajorconcernduetovariousse- whichalogicvulnerabilitycouldoccur,whilepropertiesexplain curitybreaches[1,4].Thesebreacheshaveledtofinanciallosses thevulnerablecodeattributesoroperations.Thisapproachenables ∗Correspondingauthor. GPTScantodirectlymatchcandidatevulnerablefunctionsbased 4202 yaM 6 ]RC.sc[ 3v41330.8032:viXraICSE2024,April2024,Lisbon,Portugal Sunetal. oncode-levelsemantics.However,sinceGPT-basedmatchingis thatcannotbefilteredoutbystaticfilteringandscenariomatching.
stillcoarse-grained,GPTScanfurtherinstructsGPTtointelligently Furthermore,wediagnosethatGPTScan’sstaticconfirmationre- recognizekeyvariablesandstatements,whicharethenvalidatedby duces65.84%oftheoriginalfalsepositivecasesintheWeb3Bugs dedicatedstaticconfirmationmodules.Moreover,asmartcontract dataset.ThisfindingunderscorestheimportanceofcombiningGPT projectcanconsistofmultipleSolidityfiles,makingitinfeasible withstaticanalysistoachieveaccurateresults. orcostlytodirectlyfeedallofthemtoGPT.Toaddressthisissue, Availability.GPTScanhasbeenintegratedasapartofMetaScan GPTScanemploysamulti-dimensionalfilteringprocesstoeffec- (https://metatrust.io/metascan),anindustry-leadingsmartcontract tivelynarrowdownthecandidatefunctionsforGPTmatching. securityscanningplatform[22,25].Moreover,GPTScan’sevalua- WeimplementedGPTScanwiththewidelyusedGPT-3.5-turbo tiondataisavailableathttps://sites.google.com/view/gptscanfor model[27],whichis20timesmorecost-effective[6]thanthead- facilitatingeasiercomparisonsinfuturework. vancedGPT-4model.Moreover,ourmulti-dimensionalfilteringal- Roadmap.Therestofthispaperisorganizedasfollows.In§2, lowedGPTScantoutilizethedefault4kcontexttokensizeinsteadof weintroducesomebackgroundinformation.In§3,wemotivatethe 16k,resultinginamoreeconomicalsolution.Theparameterswere needofbothGPTandstaticanalysis.Followingthat,in§4,wedetail mainlykeptattheirdefaultvalues,exceptforthetemperature thedesignofGPTScan,whilein§5,weevaluateitsperformance.We parameter,whichwasadjustedfromthedefaultvalueof1to0 thendiscusstheapplicabilityandcurrentlimitationsin§6.Finally, toreducetheimpactofGPT’soutputrandomness.Tofurtheren- wesummarizerelatedworkin§7andconcludein§8. hancethereliabilityofGPT’sanswersandminimizetheinfluence ofoutputrandomness,weproposedatrickcalled“mimic-in-the- background”prompting,inspiredbythesuccessofzero-shotchain- 2 BACKGROUND of-thoughtprompting[44].Forthestaticanalysispart,GPTScan Inthissection,weintroducesomebackgroundaboutsmartcontract reliesonANTLR[21]andcrytic-compiler[7]tosupportcallgraph vulnerabilitiesandGPT’sapplicationinvulnerabilitydetection. anddatadependencyanalysis. Smartcontractvulnerabilitytypes.Smartcontractsareself- TocomprehensivelyevaluateGPTScanunderdifferentscenarios, runningprogramsdeployedonblockchain,writteninahigh-level wecollectedthreediversedatasetsfromreal-worldsmartcontracts. languagecalledSolidity[11].AsdescribedbyZhangetal.[65],there Together, these datasets comprise around 400 contract projects, are26typesofvulnerabilitiesinsmartcontracts,categorizedinto 3KSolidityfiles,472Klinesofcode,andinclude62ground-truth 3groups.Thevulnerabilitiesinthefirstgrouparehardtoexploit, logicvulnerabilities.Thefirstdataset,namedTop200,consistsof doubtful,ornotdirectlyrelatedtothefunctionalitiesofagiven smartcontractswiththetop200marketcapitalization.Thisdataset project.Thesecondgroupofvulnerabilitiesinvolvestheuseof primarilyservestoevaluatethefalsepositiverateofGPTScan.The simpleandgeneraloracles,notrequiringanin-depthunderstanding seconddataset,referredtoasWeb3Bugs,wascollectedfromthe ofthecodesemantics.ExamplesincludeRe-entrancyandArithmetic recentWeb3Bugsdataset[8].Thethirddataset,calledDefiHacks, Overflow.Suchvulnerabilitiescanbedetectedbydataflowtracing is sourced from the well-known DeFi Hacks dataset [9], which (e.g., Slither [37]), static symbolic execution (e.g., Solidity SMT containsvulnerablecontractsthathaveexperiencedpastattack Checker[12]andMythril[13])andotherstaticanalysistools[29,43, incidents.Top200andDefiHacksprimarilycomprisecryptocurrency 47].Thethirdgroupofvulnerabilitiesrequireshigh-levelsemantical tokencontractprojects,whereasWeb3Bugsconsistsoflargecon- oraclesfordetectionandiscloselyrelatedtothebusinesslogic.Most tract projects audited on the Code4rena platform [10], with an ofthesevulnerabilitiesarenotdetectablebyexistingstaticanalysis averageof36Solidityfilesperproject. tools.Thisgroupcomprisessixmaintypesofvulnerabilities:(S1) GPTScanachievesalowfalsepositiverateof4.39%whenanalyz- pricemanipulation,(S2)ID-relatedviolations,(S3)erroneousstate ingnon-vulnerabletopcontractslikeTop200.Italsodemonstrates updates,(S4)atomicityviolation,(S5)privilegeescalation,and(S6) similarperformanceinanalyzinganothersetoftokencontracts, erroneousaccounting. DefiHacks,withaprecisionof90.91%.Theseresultsindicatethat GPTanditsapplicationinvulnerabilitydetection.Genera- GPTScanissuitableformassivescanningofon-chaincontracts. tivePre-trainingTransformer(GPT)models,suchasGPT-3.5[49], Moreover,whenanalyzinglargecontractprojectsinWeb3Bugs, are large language models (LLMs) trained on vast text corpora, GPTScanstillachievesanacceptableprecisionof57.14%.Further- includingsourcecodedescriptionsofdifferentprogramminglan- more,GPTScanshowsitsefficacyindetectingground-truthlogic guagesandvulnerabilities.Withthisknowledge,GPTcanunder-
vulnerabilitiesintheWeb3BugsandDefiHacksdatasets,withare- standandinterpretsourcecode,enablingzero-shotlearning[44], callof83.33%andanF1scoreof67.8%forWeb3Bugs,andarecallof whereexamplesofvulnerabilitiesarenotneededtodetectvulner- 71.43%andanF1scoreof80%forDefiHacks.Inparticular,GPTScan abilitiesinsourcecode.However,GPTstillhasalongwaytogo identifies9newvulnerabilitiesthatwerenotpresentintheaudit beforeitcanfullyreplacehumansincodeauditing[14].Davidet reportsofCode4rena.ThishighlightsthevalueofGPTScanasa al.[34]providedGPTwithvulnerabilitydescriptionsandusedthem usefulsupplementtohumanauditors. todetectvulnerabilitiesinsourcecode.Theyfedtheentireproject AfurtheranalysisofGPTScan’srunninglogsrevealsthatGPTScan intotheGPT-4-32kmodeltodetect38typesofvulnerabilitiesin isfastandcost-effective,takinganaverageofonly14.39seconds smartcontracts.However,theresultswereunsatisfactoryandeven and0.01USDtoscanperthousandlinesofSoliditycodeinthe worsethanarandommodelintermsofrecall.Duetothelimitations testeddatasets.Therelativelyhighercost(around0.018USD)and oftheGPTmodeloncontentlength(from4ktokensinGPT-3.5to slowerspeed(around20seconds)observedforWeb3BugsandDefi- 32ktokensinGPT-4),analyzingcompleteprojectsordocuments Hackscanbeattributedtothepresenceofmorecomplexfunctions usingGPTisnotviable,makingDavidetal.’sapproachunsuitableGPTScan:DetectingLogicVulnerabilitiesinSmartContractsbyCombiningGPTwithProgramAnalysis ICSE2024,April2024,Lisbon,Portugal 1 function deposit(uint256 _amount) external returns (uint256) { wheretheexecutingorderofsomestatementsisincorrect.Thecor- 2 uint256 _pool = balance(); rectordershouldbetofirstperformusercheckpoints(line10-11) 3 uint256 _before = token.balanceOf(address(this)); andthenupdatethebalancesofthesenderandreceiverforthe 4 token.safeTransferFrom(msg.sender, address(this), _amount); 5 uint256 _after = token.balanceOf(address(this)); transfer(lines6-7).Duetothismistake,ausercanstealallrewards 6 _amount = _after.sub(_before); // Additional check for becausethecheckpointisexecutedafterrewardtransfer[17].To deflationary tokens 7 uint256 _shares = 0; detectthisvulnerability,GPTisrequiredtounderstandtheseman- 8 if (totalSupply() == 0) { ticofstatementsandrecognizethosethatperformusercheckpoints 9 _shares = _amount; andthosethatchangeuserbalances.However,wefoundthatGPT 10 } else { 11 _shares = (_amount.mul(totalSupply())).div(_pool); strugglestocomprehendtheconceptof“before,”andasaresult, 12 } relyingsolelyonGPTcouldreportapatchedversion[18]ofthe 13 _mint(msg.sender, _shares); 14 } transferfunctionasvulnerable.Staticanalysisisthusnecessary. Basedontheaboveexamples,wefindthatstaticanalysiscannot Figure1:TheRiskyFirstDeposit(line8-9)vulnerability. understandhigh-levelsemanticinformation,andGPTmayoverlook 1 function transfer(address account, uint256 amount) external somelow-levelinformation,potentiallyleadingtolowrecalland override notPaused returns (bool) { highfalsepositives,respectively.Combiningthesetwotechniques 2 require(msg.sender != account, Error. cancomplementeachotherandenhancedetectionperformance. SELF_TRANSFER_NOT_ALLOWED); 3 require(balances[msg.sender] >= amount, Error. INSUFFICIENT_BALANCE); 4 // Initialize the ILiquidityPool pool variable 4 GPTSCAN 5 pool.handleLpTokenTransfer(msg.sender, account, amount); Inthissection,wepresentGPTScan’soveralldesignanditsthree 6 balances[msg.sender] -= amount; 7 balances[account] += amount; corecomponentsfrom§4.1to§4.4,followedbyasummaryofsome 8 address lpGauge = currentAddresses[_LP_GAUGE]; keyimplementationdetailsin§4.5. 9 if (lpGauge != address(0)) { 10 ILpGauge(lpGauge).userCheckpoint(msg.sender); 11 ILpGauge(lpGauge).userCheckpoint(account); 4.1 OverviewandChallenges 12 } 13 emit Transfer(msg.sender, account, amount); Figure3illustratesGPTScan’shigh-levelworkflow,withblueblocks 14 return true; denotingGPTtasksandgreenblocksrepresentingstaticanalysis. 15 } Givenasmartcontractproject,whichcouldbeastandaloneSolid- Figure2:TheWrongCheckpointOrder(line6-7&line10-11). ityfileoraframework-basedcontractprojectcontainingmultiple forlargeprojects.Moreover,asGPThaslimitedlogicalreasoning Solidityfiles,GPTScanfirstperformscontractparsing,callgraph capabilities,itsresultsmaynotalwaysbeaccurate,necessitating analysistodeterminefunctionreachability,andcomprehensive verificationusingothermethodstoreducethefalsepositiverate. filteringtoextractcandidatefunctionsandtheircorrespondingcon- textfunctions.GPTScanthenutilizesGPTtomatchthecandidate functionswithpre-abstractedscenariosandpropertiesofrelevant vulnerabilitytypes.Forthematchedfunctions,GPTScanfurther 3 MOTIVATINGEXAMPLES recognizestheirkeyvariablesandstatementsviaGPT,whichare Inthissection,weusetworeal-worldsmartcontractexamples subsequentlypassedtospecializedstaticanalysismodulesforvul-
tomotivatewhybothGPTandstaticanalysisareneededinthe nerabilityconfirmation. processofdetectinglogicvulnerabilities. Duringthisthree-stepprocess,weneedtoaddressthefollowing threechallenges: Example1:RequiringGPTtorecognizevariablesandstatic analysistoconfirmthevariabledependency.Thefirstexample C1:AsmartcontractprojectmaycontaintensofSolidityfiles1, inFigure1isfromtheCode4rena[10]project2021-11-yaxis[2].The makingitinfeasibleorcostlytodirectlyfeedallofthemtoGPT. vulnerabilityoccurswhentheLP(LiquidityPool[45])token’sentire Moreover, the presence of non-vulnerable functions may affect shareismintedtothefirstdepositor(line9)whilethecurrentLP GPT’srecognitionofvulnerableones.Therefore,howtoeffectively tokensupplyiszero(line8).Consequently,thefirstdepositorcan narrow down the candidate functions for GPT matching becomes arbitrarilyinflatethepriceperLPshare(e.g.,fromasmall_amount essential. toanextremelylargevalue;seethedetailofanexploitinGitHub C2:ExistingGPT-basedvulnerabilitydetectionworks[14,34,35] issue[15]),leadingtofuturetokendepositsfromvictimuserstobe typicallyfeedGPTwithhigh-levelvulnerabilitydescriptionsfor indirectly“occupied”bythefirstdepositor.Whilestaticanalysis vulnerabilitymatching,whicheitherdemandsadvancedreasoning mayusehard-codedpatternstodetectthetotalSupply()logic capabilities from GPT or relies on the pre-trained vulnerability inline8,GPTisnecessarytointelligentlyrecognizethevariables knowledgeofGPTmodels.Hence,canwebreakdownvulnerabil- responsibleforholdingthedepositamount(_amount)andthetotal itytypesinamannerthatallowsGPT,asagenericandintelligent shareofthepool(_shares)toavoidfalsepositives.Nevertheless, codeunderstandingtool,torecognizethemdirectlyfromcode-level preciselyvalidatingthevulnerablelogicfromline8to9fallsoutside semantics? thescopeofGPT,makingstaticanalysisessentialforthistask. Example2:RequiringGPTtorecognizestatementsand 1Accordingtoourevaluationin§5,aCode4renaprojecthas36Solidityfilesonaverage. staticanalysistoconfirmthestatementorder.Thesecondex- Incontrasttoarecentstudy[34],whichclaimedtofeedentirecontractstotheGPT-4 ampleinFigure2isfromtheCode4Renaproject2022-04-backd[16], modelwith32ktokens,wecannotfeedtheentireprojectintothemodelforanalysis.ICSE2024,April2024,Lisbon,Portugal Sunetal. §4.3: Filtering for §4.2: GPT-based Scenario §4.4: From GPT Recognition Multi- Candidate Functions and Property Matching to Static Confirmation dimensional filtering Scenario- Property- Recognizing Supplied to Smart Candidate Vuln types + Result of Contract Static function based GPT based GPT key var/stmts Key variables static analysis Logic Project Reachability pairs matching matching via GPT & statements for confirmation Vulns Analysis Figure3:Ahigh-leveloverviewofGPTScan,withblueblocksdenotingGPTtasksandgreenblocksrepresentingstaticanalysis. Table1:Breakingdowntencommonlogicvulnerabilitytypesintoscenariosandproperties. VulnerabilityType ScenarioandProperty FilteringType StaticCheck ApprovalNot Scenario:addorcheckapprovalviarequire/ifstatementsbeforethetokentransfer Cleared Property:andthereisnoclear/resetoftheapprovalwhenthetransfer FNI,FCCE VC finishesitsmainbranchorencountersexceptions RiskyFirst Scenario:deposit/mint/addtheliquiditypool/amount/share Deposit Property:andsetthetotalsharetothenumberoffirstdepositwhen FCCE DF,VC thesupply/liquidityis0 PriceManipulation Scenario:havecodestatementsthatgetorcalculateLPtoken’svalue/price byAMM Property:basedonthemarketreserves/AMMprice/exchangeRateORthe FNK,FCCE DF customtokenbalanceOf/totalSupply/amount/liquiditycalculation PriceManipulation Scenario:buysometokens FNK,FCE FA byBuyingTokens Property:usingUniswap/PancakeSwapAPIs VoteManipulation Scenario:calculatevoteamount/number byFlashloan Property:andthisvoteamount/numberisfromavoteweightthatmight FCCE DF bemanipulatedbyflashloan Scenario:mintorvestorcollecttoken/liquidity/earningandassignthemto theaddressrecipientortovariable FrontRunning FNK,FPNC,FPT,FCNE,FNM FA Property:andthisoperationcouldbefrontruntobenefittheaccount/address thatcanbecontrolledbytheparameterandhasnosendercheckinthefunctioncode WrongInterest Scenario:haveinsidecodestatementsthatupdate/accrueinterest/exchangerate RateOrder Property:andhaveinsidecodestatementsthatcalculate/assign/distributethe FCE,CEN OC balance/share/stake/fee/loan/reward Wrong Scenario:haveinsidecodestatementsthatinvokeusercheckpoint CheckpointOrder Property:andhaveinsidecodestatementsthatcalculate/assign/distributethe FCE,CEN OC balance/share/stake/fee/loan/reward Scenario:involvecalculatingswap/liquidityoraddingliquidity,andthereis assetexchangesorpricequeries Slippage FCCE,FCNCE VC Property:butthisoperationcouldbeattackedbySlippage/SandwichAttackduetono sliplimit/minimumvaluecheck Unauthorized Scenario:involvetransferingtokenfromanaddressdifferentfrommessagesender FNK,FCNE,FCE,FCNCE,FPNC VC Transfer Property:andthereisnocheckofallowance/approvalfromtheaddressowner
C3:ConsideringthatGPTmayproduceunreliableanswersorfail vulnerabilitytypesintocode-levelscenariosandproperties.Specif- torecognizedifferencesinsimilarfunctions,furtherconfirmingthe ically,weusescenariostodescribethecodefunctionalityunder matchedpotentialvulnerabilitiesbecomescritical. whichalogicvulnerabilitycouldoccurandpropertiestoexplainthe SincechallengeC1andC3arebothrelatedtochallengeC2,we vulnerablecodeattributesoroperations.Table1showcaseshow firstpresenthowwetackleC2in§4.2,followedbyoursolutionsto webreakdowntencommonlogicvulnerabilitytypesintoscenar- C1andC3in§4.3and§4.4,respectively. iosandproperties.Thesevulnerabilitytypeswereselectedfrom arecentstudy[65]onsmartcontractvulnerabilitiesthatrequire high-levelsemanticoracles[8].Thestudysummarizessixcate- 4.2 GPT-basedScenarioandPropertyMatching goriesoflogicvulnerabilitiesfromS1toS6(see§2),andwechose ExistingGPT-basedvulnerabilitydetectionworks[14,34,35]iden- tenrepresentativecasesfromthesecategories.Forinstance,theAp- tifyvulnerabilitiesbysimplyfeedingGPTwithhigh-levelvulner- provalNotClearedvulnerabilityisfromS3,whichinvolvesmissing abilitydescriptions,suchastheoneprovidedfortheFrontRun- stateupdate,andthetwowrongordervulnerabilitiesarefromS6, ningvulnerability:“Anattackwhereanattackerobservespending relatingtoincorrectcalculatingorder.Notethatinthispaper,we manuallybrokedowntenvulnerabilitytypestopreciselydescribe transactionsandcreatesanewtransactionwithahighergasprice, theircode-levelattributes.Tosupportmorelogicvulnerabilitytypes enablingittobeprocessedbeforetheobservedtransaction.Thisis infuturework,wehavefiguredoutaGPT-basedapproach.This oftendonetogainanunfairadvantageindecentralizedexchangesor othertime-sensitiveoperations.”[34].However,thesedescriptions approachemploysGPT-4toautomaticallyextractinitialscenario arecondensedfromrootcausesratherthancodeproperties,making andpropertysentencesfrompastvulnerabilityreports,validate itchallengingforGPTtodirectlyinterpretcode-levelsemantics. themusingtheoriginalvulnerablecode,anditerativelyregener- atenewsentencesuntilascenarioandpropertysentencepassthe Breakingdownvulnerabilitiesintoscenariosandprop- erties.GPTScanadoptsadifferentapproachbybreakingdown originalvulnerabilityvalidation.However,whilethegenerationGPTScan:DetectingLogicVulnerabilitiesinSmartContractsbyCombiningGPTwithProgramAnalysis ICSE2024,April2024,Lisbon,Portugal Table1aredesignedtoformacompletesentence.Thirdly,consid- PromptTemplate eringthatGPTmodelssometimesprovideambiguousanswersor hard-to-parsetext,scenarioandpropertymatchingaredesigned System:Youareasmartcontractauditor.Youwillbeasked withyesornoquestionsonly,aimingtominimizetheimpactof questionsrelatedtocodeproperties.Youcanmimican- unstructuredGPTresponses.Moreover,weinstructGPTtolearn sweringtheminthebackgroundfivetimesandprovideme theoutputJSONformatforthemultiple-choicescenariomatching, withthemostfrequentlyappearinganswer.Furthermore, leveragingGPT’sinstructionlearningcapability[50]. pleasestrictlyadheretotheoutputformatspecifiedinthe question;thereisnoneedtoexplainyouranswer. Minimizing the impact of GPT output randomness. Al- thoughweuseyes-or-noquestionstorestricttheformatofGPT responses,itdoesnoteliminatetheinherentrandomnessofGPT ScenarioMatching modeloutput.Consequently,GPTmaynotprovidethesamean- Giventhefollowingsmartcontractcode,answertheques- swerforthesamequestion.Toaddressthis,oneapproachistoset tionsbelowandorganizetheresultinajsonformatlike thetemperatureparameterofGPTmodelsto0,makingthemodel {"1":"Yes"or"No","2":"Yes"or"No"}. tendtobedeterministic. Tofurtherenhancethereliabilityofthe "1":[%SCENARIO_1%]? answerandminimizetheinfluenceofGPToutputrandomness, "2":[%SCENARIO_2%]? weproposeatrickcalled“mimic-in-the-background”prompting, [%CODE%] whichisinspiredbythesuccessfulusageof“Let’sthinkstepbystep.” inthezero-shotchain-of-thoughtprompting[44]–evaluatingsuch PropertyMatching promptingisbeyondthescopeofthispaper.AsshowninFigure4, Doesthefollowingsmartcontractcode"[%SCENARIO, weuseaGPTsystemprompttoinstructthemodeltomimican- PROPERTY%]"?Answeronly"Yes"or"No". sweringquestionsinthebackgroundfivetimesandprovidethe [%CODE%] mostfrequentlyappearinganswertoensuregreaterconsistency. Figure4:Promptforscenarioandpropertymatching. 4.3 Multi-dimensionalFunctionFiltering ofscenarioandpropertysentencescanbeautomated,theprompt Asmentionedin§4.1,weneedtofilterthecandidatefunctionsbe- usedforGPTrecognition,whichwewillexplainin§4.4,mustbe foreGPTmatching.Here,weproposeamulti-dimensionalfiltering manuallycraftedfordifferenttypesofvulnerabilities. tosystematicallyselectcandidatefunctionsfordifferentvulnera- Eachscenarioandpropertycanbedividedintotwoparts.The bilitytypes.Moreover,weconductreachabilityanalysistoretain first part includes a description of the function’s functionality, onlythefunctionsthatcouldbeaccessedbypotentialattackers.
whichhelpsGPTScanperformaninitialscreeningofcandidate Project-wide file filtering. Our multi-dimensional filtering functionstoreduceunnecessarysubsequentscanning.UsingFront beginswithproject-widefilefiltering,whichinvolvesexcluding Runningasanexample,functionsaffectedbythisvulnerabilitytype non-Solidityfilese..g,thoseunderthe“node_modules”directory, mustinvolveactionslikeminting,vesting,ortransferringtokens testfiles(e.g.,thosefoundinvarious“test”directories),andthird- ofotherusers.Theapprovalforsuchactionsisgrantedinaprevi- partylibraryfiles(e.g.,thosefromwell-knownlibrariessuchas oustransaction,allowingattackerstofront-runthefunctionand “openzeppelin”,“uniswap”,and“pancakeswap”).Oncethesefiles gainanunfairadvantage.Thesecondpartincludesadescription arefilteredout,GPTScancanconcentrateontheproject’sSolidity ofthefunction’sbehavior,whichisrelatedtotherootcauseofthe filesthemselves. vulnerabilities,suchasthelackofsecuritychecksandincorrect FilteringoutOpenZeppelinfunctions.OpenZeppelin[26] accountingorder.Ifafunctionmeetsthepropertiesofthefirstpart, providesasetoflibrariestobuildsecuresmartcontractsonEthereum, i.e.,scenarios,GPTScanwillsendthefunctiontoGPTagainto widelyusedinthesmartcontractcommunity.Whilewehavefil- checkifitsatisfiesboththescenariosandproperties.Ifbothparts teredoutOpenZeppelincontractsimportedaslibraries,wefound aresatisfied,GPTScanconsidersthefunctionlikelytocontaina thatOpenZeppelinfunctionsareoftendirectlycopiedintomany specifictypeofvulnerabilityandwillconfirmitinthelatersteps. developers’contractcode,makingourproject-widefilefiltering Yes-or-Noscenarioandpropertymatching.Withtheab- ineffective.Toaddressthis,wefirstperformanofflineanalysisof stractedscenariosandproperties,weutilizethemtomatchcan- OpenZeppelin’ssourcecodetoextractallitsAPIfunctionsigna- didatefunctionsusingGPT.Figure4showstheprompttemplate turesasawhitelist.Eachfunctionsignatureinthewhitelistincludes employedbyGPTScanforscenarioandpropertymatching,which theaccesscontrolmodifier,theclassname(sub-contractname), isdesignedwiththreeconsiderations.Firstly,propertymatching functionname,returnvaluetypes,andparametertypes.Forexam- isperformedonlyforfunctionsthatpassourscenariomatching. ple,thesignatureofthetransferfunctionintheERC20contract Thisseparationofscenarioandpropertyenablesustoqueryall ispublic ERC20.transfer(address,uint256).Next,GPTScan scenariosinasingleprompt,thussavingonGPTcosts.Secondly, generatesthesignatureofallcandidatefunctionsinthesameformat duringpropertymatching,wedouble-confirmthescenariowith andcomparesthemwiththesignaturesinthewhitelist.Notethat GPTbyqueryingthecombinationofscenarioandpropertyrather thesignatureofthecandidatefunctionisgeneratedwithboththe than property alone. Indeed, the scenarios and properties from classnameandthenameoftheinheritedclassbecausedevelopers mayimplementtheinheritedclass.Byconductingthiscomparison, GPTScanexcludesfunctionswiththesamesignatureasthoseinICSE2024,April2024,Lisbon,Portugal Sunetal. thewhitelist,whichweconsidersecureinthispaper.Inthefuture, AnExamplePromptforGPTRecognition wewilladdclone-basedfilteringthatcoversfunctionbodies. Vulnerability-specificfunctionfiltering.Afterproject-wide System: (sameasinFigure4,omittedhereforbrevity.) fileandOpenZeppelinfiltering,GPTScanconductsfunction-level filteringfordifferentvulnerabilitytypes,whichconstitutesthema- jorpartofGPTScan’smulti-dimensionalfiltering.Toaccommodate Inthisfunction,whichvariableorfunctionholdsthetotal variousfilteringrequirements,wehavedesignedaYAML-based[3] supply/liquidityANDisusedbytheconditionalbranchto filteringrulespecificationtosupportthefollowingfilteringrules: determinethesupply/liquidityis0?Pleaseanswerina FNK:TheFunctionNameshouldcontainatleastoneKeyword. sectionstartswith"VariableB:". FCE:TheFunctionContentshouldcontainatleastoneExpression. In this function, which variable or function holds the FCNE:TheFunctionContentshouldNotcontainanyExpression. valueofthedeposit/mint/addamount?Pleaseanswerina FCCE:TheFunctionContentshouldcontainatleastoneCombina- sectionstartswith"VariableC:". tionofgivenExpressions. Please answer in the following json format: FCNCE:TheFunctionContentshouldNotcontainanyCombina- {"VariableA":{"Variable name":"Description"}, "Vari- tionofgivenExpressions. ableB":{"Variable name":"Description"}, "Vari- FPT:TheFunctionParametersshouldmatchthegivenTypes. ableC":{"Variablename":"Description"}} FPNC:TheFunctionshouldbePublic,andwewillNotanalyzeit [%CODE%] withitsCaller. FNM:TheFunctionshouldNotcontainModifiersthatwithaccess Figure5:Apromptforfindingrelatedvariables/statements. control(e.g.,onlyOwner). CFN:TheCallersofthisFunctionwillNotbeanalyzed. 4.4 FromGPTRecognitiontoStatic Thesefilteringrulesencompassthebasicfunctionname(FNK), Confirmation thedetailedfunctioncontent(FCE,FCNE,FCCE,andFCNCE),the AlthoughthecandidatefunctionspasstheinitialfilteringandGPT functionparameters(FPT),andthefunction’scallerrelation(FPNC, matchingonfunctionproperties,GPTdoesnotalwayspayatten-
FNM,CFN).Differentvulnerabilitieswillutilizetheirspecificfil- tiontosyntacticdetails,suchasconditionalstatements,require teringrules.Theselectionoffiltersismainlybasedonthedomain statements,assertstatements,revertstatements,etc.Amorefine- knowledgeofthevulnerabilitytypes.Forexample,theRiskyFirst grainedstaticanalysisisnecessarytoidentifypotentiallyvulnera- DepositvulnerabilityshowninFigure1usesonlytheFCCErule blefunctionsatthisstage.Staticanalysistoolstypicallyfocuson typetoselectanycombinationof“total,”“supply,”and“liquidity,” specificvariablesorstatements,whileourcurrentinputsarestill eitherseparatelyortogether,toensurethatthedepositisrelatedto functions.ThisiswhereweneedtheassistanceofGPTtoextract thecalculationoftotalsupplyorliquidityofthetoken.Ontheother thevariablesandstatementsrelatedtothespecificbusinesslogic hand,PriceManipulationbyAMMisrelatedtothecalculationof describedintheprompt.Withthesevariablesandstatements,we tokenprices.Inthisrule,weusedtheFNKruletoselectfunctions canusestaticanalysistoconfirmwhetherthevulnerabilityexists relatedtopricecalculation,andtheFCEruletoselectfunctions ornot.AnexampleofthepromptsenttoGPTtoaskforrelated thatcontainthekeywords“price,”“value,”and“liquidity.” variablesorexpressionsforRiskyFirstDepositisshowninFigure5. Reachabilityanalysis.Afterfiltering,weperformcallgraph Foreachextractedvariableorstatement,GPTScaninstructsGPT analysistodeterminethereachabilityofcandidatefunctions.We toprovideashortdescription.Thisdescriptionhelpsdetermine utilizeANTLR[21],alexerandparsergenerator,toparsethesource whetherthegivenvariablesarerelevanttotheproblemandhelps codeofthesmartcontractprojectandgenerateanabstractsyn- avoidincorrectanswers.IfGPTprovidesvariablesorstatements taxtree(AST).UsingtheAST,webuildacallgraphfortheen- thatdonotexistinthecontextofthefunctionorifthedescrip- tireproject.InSolidity,therearefourtypesofaccesscontrolan- tionisnotrelevanttothequestionasked,GPTScanterminatesthe notations:public,external,internalandprivate.Functions judgmentprocessandconsidersthatthevulnerabilitydoesnot markedaspublicandexternalcanbecalledbyanyone,making exist.Ontheotherhand,iftheprovidedvariablesandstatements themdirectlyreachableforpotentialattackers.Functionsmarked passvalidation,GPTScanfeedsthemintoastaticanalysistoolto asinternalandprivatemightbecalledbyotherreachablefunc- confirmtheexistenceofthevulnerabilityusingmethodssuchas tions,soweanalyzetheirreachabilityandincludethemifthey staticdataflowtracingandstaticsymbolicexecution.Specifically, arereachable.Moreover,Solidityallowsdeveloperstousecustom wehavedesignedthefollowingfourmajortypesofstaticanalysis modifierstoperformpermissionchecksbeforefunctioncalls.Forex- tovalidatethecommonlogicvulnerabilitieslistedinTable1: ample,functionsannotatedwithonlyOwnerareonlyallowedtobe StaticDataFlowTracing(DF):Thismethodtracesthedataflowof calledbytheowner,whichweconsiderasunreachable.Functions variablesintheprogram,wherestaticanalysisdetermineswhether thataredeemedunreachableareexcludedfromthesubsequent thetwovariablesorexpressionsprovidedbyGPThavedatade- GPT-basedmatchingin§4.2. pendencies.Forexample,Figure1showsthatdataflowanalysisis neededtodeterminewhethertheshareiscalculateddirectlywith thedepositamountintheRiskyFirstDepositvulnerability. ValueComparisonCheck(VC):Thismethodcheckswhether twovariablesorexpressionsarecomparedinconditionstatements,GPTScan:DetectingLogicVulnerabilitiesinSmartContractsbyCombiningGPTwithProgramAnalysis ICSE2024,April2024,Lisbon,Portugal suchasrequire,assert,andif.Itisusedtoensurethatvariables Table2:ThreediversedatasetsforGPTScan’sevaluation. orexpressionsareproperlycheckedbeforeusage.InRiskyFirst DatasetName ProjectsP FilesF F/P LoC Vuls Deposit,VCisusedtocheckwhethertheshareiscomparedwith Top200 303 555 1.83 134,322 0 thedepositamount.Likewise,inUnauthorizedTransfer,VCisused Web3Bugs 72 2,573 35.74 319,878 48 toverifywhetherthesenderhasbeencheckedbeforethetransfer. DefiHacks 13 29 2.23 17,824 14 OrderCheck(OC):Thismethodcheckstheexecutionorderof Sum 388 3,157 8.14 472,024 62 twostatements,wherestaticanalysisdeterminestheorderoftwo statementsprovidedbyGPT.Forexample,Figure2showsthatOC Thefirstdataset,calledTop200,comprisessmartcontractswitha isusedtoverifytheexecutionorderofperformingatransferand top200marketcapitalization.Itincludes303open-sourcecontract updatingthecheckpointinWrongCheckpointOrder. projectsfromsixmainstreamEthereum-compatiblechains[62]. FunctionCallArgumentCheck(FA):Thismethodcheckswhether Since these projects are well-audited and widely used, it is rea- anargumentofafunctioncallcanbecontrolledbytheuserormeets sonabletoassumethattheydonotcontainnotablevulnerabilities. specificrequirements.Specifically,GPTprovidesafunctioncalland Thisdatasetisprimarilyusedtostress-testthefalse-positiverateof theindexofanargument,andstaticanalysisdetermineswhether GPTScaninauditedcontracts.Theseconddataset,calledWeb3Bugs,,
theargumentcanbecontrolledbytheuserormeetstherequire- wascollectedfromtherecentWeb3Bugsdataset[8,65],whichcom- mentsdescribedintherules.InPriceManipulationbyBuyingTokens, prises100Code4rena-auditedprojects.Amongthe100projects,we thefunctioncallsneedtobecheckedwithFA,assomesensitive included72projectsthatcanbedirectlycompiled.Theremaining variablesmaybeusedasparametersandcausepricemanipulation. projectseithermisslibrarydependenciesorconfigurationfilesin theiroriginalWeb3Bugsrepository[8].Thethirddataset,calledDe- fiHacks,comefromthewell-knownDeFiHacksdataset[9],which 4.5 Implementation consistsofvulnerabletokencontractsthathaveincurredpastat- GPTScanisimplementedwith3,640linesofcode(LOC)inPython tackincidents.Weincluded13vulnerableprojectsthatcertainly and154LOCinJava/Kotlin.Inthissection,weprovideasummary coverthevulnerabilitiesinourtentypes.Theground-truthvulner- ofsomekeyimplementationdetailsasfollows. abilitiesinthesedatasetsincludethosealreadyreportedandthose GPTmodelanditsparameters.Duringthedevelopmentand newlydetectedbyGPTScanandconfirmedbythecommunity. testingofGPTScan,weutilizedOpenAI’sGPT-3.5-turbomodel[27]. All these projects are compiled with crytic-compiler [7] us- Thankstothemulti-dimensionalfilteringintroducedin§4.3,GPTScan ingthedefaultconfiguration.Notethat17projectsintheTop200 couldusethedefault4kcontexttokensizeinsteadof16k,which datasetcannotbecompiledwithcrytic-compiler.Fortheseprojects, resultedinamorecost-effectivesolution.Theparameterswere GPTScan’sstaticconfirmationcannotbeapplied,andanyinflu- mainlykeptattheirdefaultvalues,includingTopPsetto1,Fre- encedtypesofvulnerabilitieswillbemarkedasnotdetected. quencyPenaltysetto0,andPresencePenaltysetto0.Asdiscussed ResearchQuestions.Withthedatasetsabove,weaimtoanswer in§4.2,weadjustedthetemperatureparameterfromthedefault thefollowingfiveresearchquestions(RQs): valueof1to0tominimizetheimpactofGPToutputrandomness. RQ1: WhatisthefalsepositiverateofGPTScanwhenanalyz- DuringeachGPTquery,thequestionissentwithanemptysession ingadatasetofnon-vulnerabletopcontracts? toensurethatthepreviousquestionsandanswersdonotinfluence RQ2: HowaccurateisGPTScaninanalyzingreal-worddatasets thecurrentquestion. withlogicvulnerabilities,andhoweffectiveisitcompared Staticanalysistoolsupport.Asmentionedin§4.3,weutilized toexistingtools? ANTLR [21] to parse the Solidity source code and generate an RQ3: HoweffectiveisGPTScan’sstaticconfirmationinim- abstractsyntaxtree(AST).ANTLRallowsforsourcecodeanalysis provingtheaccuracyofGPTScan? without the need for compilation, making it more effective for RQ4: Whataretherunningperformanceandfinancialcosts sourcecodewithlimiteddependenciesandbuildscriptscompared ofGPTScan? totoolsrelyingoncompilation,suchasSlither[37].Furthermore,to RQ5: Can GPTScan discover new vulnerabilities that were determinedatadependenciesbetweentwovariablesorexpressions previouslymissedbyhumanauditors? in§4.4,weemployedastaticanalysistool[23]basedontheoutput ofcrytic-compiler[7],aSoliditycompilercapableofproducing 5.1 RQ1:MeasuringFalsePositivesinthe a standard AST for static analysis. With this approach, we can constructbothacontrolflowgraphandadatadependencegraph. Non-vulnerableTopContracts InRQ1,weaimtomeasureGPTScan’sfalsealarmrateinanalyzing non-vulnerablecontracts.Thisisimportantbecausewhenusing 5 EVALUATION GPTScanformassivescanningofon-chaintokencontracts,we Inthissection,weconductexperimentstoevaluateGPTScan’saccu- wanttominimizethefalsealarmsthatrequiremanualchecking. racy,performance,financialoverhead,theeffectivenessofitsstatic Forthispurpose,wehavecollectedtheTop200dataset,which confirmation,anditscapabilitytodiscovernewvulnerabilities. consistsof303contractprojectsthataredeemednon-vulnerable. Datasets.AsshowninTable2,theexperimentswereconducted WepresentGPTScan’sanalysisresultofTop200inTable3.Along onthreedatasetscollectedfromreal-worldsmartcontracts.These withtheresultsofWeb3BugsandDefiHacks,wecalculatetheaccu- datasetsconsistofaround400contractprojects,3KSolidityfiles, racymetricsatthefunctionlevelforeachtestedvulnerabilitytype. 472Klinesofcode,andinclude62ground-truthlogicvulnerabilities. Forexample,ifaprojecthasbeentestedwithfivevulnerabilityICSE2024,April2024,Lisbon,Portugal Sunetal. Table3:OverallresultsofGPTScan’saccuracyevaluation. recallof83.33%andanF1scoreof67.8%onthisdataset.ForDefi- DatasetName TP TN FP FN Sum Hacks,GPTScananalyzedatotalof34vulnerabilitytypesacross Top200 0 283 13 0 296 13projects,detecting10TPsandmissing4FNs,whileincurring1 Web3Bugs 40 154 30 8 232 FP.Onthisdataset,GPTScan’srecallis71.43%andtheF1scoreis DefiHacks 10 19 1 4 34 80%.TheseresultsdemonstratethatGPTScaneffectivelydetects vulnerablecontractsforthecoveredlogicvulnerabilitytypes.Fol- types,thesumofalltruepositives,falsepositives,truenegatives, lowingtheinitialprecisionanalysisin§5.1,wenowanalyzethe andfalsenegativesforthisprojectshouldbe5.Morespecifically,
rootcausesofGPTScan’sfalsenegativesandfalsepositives. TPisthenumberoftruepositives.Onetruepositiveiscounted Inthe12falsenegativecases,4ofthemarePriceManipulation whenGPTScansuccessfullydetectsaground-truthvulnerablefunc- byAMM and3ofthemareRiskyFirstDeposit.Themainreason tionforthetestedvulnerabilitytype. forthesetwokindsoffalsenegativesisthatGPTScandoesnot TNisthenumberoftruenegatives.Onetruenegativeiscounted implement an alias analysis in the static check, causing failure whenGPTScancorrectlydoesnotreportanyvulnerablefunction duringstaticdataflowtracing.Additionally,thereare2casesof forthetestedvulnerabilitytype. FrontRunning,wherethescenariosorpropertiesarenotaccurately FPisthenumberoffalsepositives.Onefalsepositiveiscounted matchedbyGPT.Furthermore,thereare2casesofSlippageand1 whenGPTScanincorrectlyreportsoneormorevulnerablefunctions caseofUnauthorizedTransfer.Similartothefalsepositivecases,The forthetestedvulnerabilitytypethathasnocorrespondingground- mainreasonforthefalsenegativeSlippagecasesistheexistenceof truthvulnerabilitiesinthetestedproject. numerousvariantsofslippagechecks,makingthemchallengingto FNisthenumberoffalsenegatives.Onefalsenegativeiscounted detectusingGPTandstaticanalysis.InthecaseofUnauthorized whenGPTScanfailstodetecttheground-truthvulnerablefunction Transfer,themainreasonforthisfalsenegativeisthatGPTfailed forthetestedvulnerabilitytype. todistinguishtheinconsistencybetweenthecommentandcode. Basedonthecalculationofthesemetrics,GPTScanreports13FPs GPTScanachieveseffectivevulnerabilitydetectionaboveatan and283TNsfortheTop200dataset,asshowninTable3.Asaresult, acceptablefalsealarmrate.Amongthe44falsepositivecasesfrom thefalsepositiverateofGPTScaninanalyzingnon-vulnerabletop thethreedatasets,15(34.09%)wererelatedtoPriceManipulation contractslikeTop200is4.39%.Moreover,wefindthatGPTScanhas byAMM,followedby11(25.00%)casesofUnauthorizedTransfer. asimilarprecisionwhenanalyzingTop200andDefiHacks,bothof Forthesetwotypes,themainreasonforthefalsealarmsisthat whicharetokencontractswitharound2Solidityfilesperproject thesevulnerabilitiesrequirespecifictriggeringconditionsinvolving (seeTable2).WhenanalyzinglargeprojectslikethoseinWeb3Bugs, otherrelatedlogic,whichmaynotbecontainedwithinasingle the precision drops from around 90% (90.91% for DefiHacks) to functionanditscallersorcallees.Forexample,inUnauthorized 60%(57.14%forWeb3Bugs).Thedropinprecisionislikelybecause Transfer,thechecksfortheallowance/approvalfromtheaddress thesmartcontractcodeinWeb3Bugsismorediverse,giventhat ownercanoccuratvariouspositionsinthelogicchainandmay Web3Bugscontainsanaverageof36Solidityfilesperproject(see involvemultiplefunctions.Similarly,thefunctionthatcalculates Table2).Incontrast,smartcontractsinDefiHacksandTop200mainly thepricewithAMMforPriceManipulationmaynotbeusedby implementcommontokenfunctionalitiesusinganaverageof2 otherfunctionsresponsibleforswappingorbuyingtokens,leading Solidityfilesperproject,potentiallytriggeringonlyalimitedsetof tothevulnerabilitiesnotbeingtriggeredinthosecircumstances. falsepositivesinGPTScan.In§5.2,wewillfurtherdiscusstheroot Additionally,therewere5casesofRiskyFirstDepositand5cases causesofGPTScan’sfalsepositives. ofSlippage.ForRiskyFirstDeposit,thefalsealarmsoccurredbe- causethereweremanystatementsrelatedtocheckingthesupply AnswerforRQ1:GPTScanachievesalowfalsepositiverateof andsettingtheshare,makingitchallengingforGPTtounderstand 4.39%whenanalyzingnon-vulnerabletopcontractslikeTop200. ItalsodemonstratessimilarperformanceinanalyzingDefiHacks, lengthycodesegmentsaccurately.RegardingSlippage,thefalse withaprecisionof90.91%.TheseresultsindicatethatGPTScan alarmsweremainlyduetotwofactors.First,similartoUnautho- is suitable for massive scanning of on-chain token contracts. rizedTransfer,thecheckforslippagecanhappenatanypositionin thelogicchain,andsecond,slippagecheckscantakemanydiffer- Moreover,whenanalyzinglargecontractprojectsinWeb3Bugs, entformsandvariants,makingthemdifficulttodetectwithGPT GPTScanstillachievesanacceptableprecisionof57.14%. andstaticanalysis.Forthisvulnerabilitytype,ourfocuswason achievingahigherrecallatthecostofslightlysacrificingpreci- 5.2 RQ2:EfficacyforDetectingVulnerable sion.Therewerealso4casesofWrongInterestRateOrder,3cases Contracts ofApprovalNotCleared,and1caseofWrongCheckpointOrder. InRQ2,weassesstheeffectivenessofGPTScaninanalyzingvul- ForWrongInterestRateOrderandWrongCheckpointOrder,these nerable contracts in the Web3Bugs and DefiHacks datasets, and vulnerabilitiesareintricatelyrelatedtothebusinesslogicofthe compareitseffectivenesswithexistingtools. projectitself,makingitchallengingtoreducefalsealarmswithout AsshowninTable2,theWeb3Bugsdatasetcontains48ground- comprehensiveknowledgeoftheproject’sdesign.AsforApproval truthlogicvulnerabilities,whiletheDefiHacksdatasethas14.Ta- NotCleared,thefalsealarmswereprimarilybecausethefunction
ble 3 presents the scanning results of these two datasets using maynotalwaysbeusedtotransfertokens,causingGPTScanto GPTScan.InthecaseofWeb3Bugs,GPTScananalyzedatotalof232 detectiterroneously. vulnerabilitytypesacross72projects,detecting40TPsandmissing Comparisonwithexistingtools.Whiletherearemanyspe- 8FNs,whileincurring30FPs.Consequently,GPTScanachieveda cificstaticanalysistools(e.g.,[28,29,47,56]),theyalmostdonotGPTScan:DetectingLogicVulnerabilitiesinSmartContractsbyCombiningGPTwithProgramAnalysis ICSE2024,April2024,Lisbon,Portugal coveranyofthelogicvulnerabilitiestargetedinthispaper.We Table4:Rawfunctionsbeforeandafterstaticconfirmation. thusselectedtwocomprehensivevulnerabilitydetectiontools,one VulnerabilityType Before After open-sourcetool,Slither[37],andMetaScan’sonlinestaticscan- ApprovalNotCleared 34 12 ningservice[19,23],referredtoasMScan.Bothtoolshaveover RiskyFirstDeposit 100 21 ahundredvulnerabilitydetectionrules,buttherulesrelatedto PriceManipulationbyAMM 187 114 GPTScanareunchecked-transfer,arbitrary-send-eth,andarbitrary- PriceManipulationbyBuyingTokens 8 8 send-erc20forSlither(correspondingtoUnauthorizedTransferin VoteManipulationbyFlashloan 2 0 GPTScan),andtwoPriceManipulationvulnerabilitiesforMScan. FrontRunning 6 4 WeranSlitheronallthreedatasetsandfoundatotalof13,144 WrongInterestRateOrder 150 11 warnings.Amongthese,only101ofunchecked-transfer,23ofarbitrary- WrongCheckpointOrder 49 1 send-eth,and22ofarbitrary-send-erc20arerelatedtotheUnautho- Slippage 99 42 rizedTransfervulnerabilityinGPTScan.Unfortunately,allofthem UnauthorizedTransfer 12 8 werefalsepositivesaftercarefulmanualchecking.Therearemainly Total 647 221 tworeasonsforthis.Firstly,Slitherdoesnotcorrelatecallchainin- 5.3 RQ3:EffectivenessofStaticConfirmation formation.Manyfalsepositivecasesinvolveinternalorprivate functionsthathavealreadybeencheckedforunauthorizedtransfer InRQ3,weconductafurtheranalysisofGPTScan’sintermediate whentheyarecalled.InGPTScan,weanalyzethecurrentfunction resultsonWeb3Bugstoexaminehowstaticconfirmationreduces anditscallertogether,effectivelyaddressingtheissueofmissing falsepositivesgeneratedbypureGPT-basedmatching. contextualsemantics.Secondly,Slitherisunabletocorrectlydetect Table4showstherawfunctionsreportedbyGPTScanbefore variantsoftransferbehaviorinUnauthorizedTransfer,suchasburn- andafterstaticconfirmation.Notethatonevulnerabilitytypemay ingtokens,leadingtoitsinabilitytodetectvulnerabilitiesinthe havemultiplefunctions(thefinalresultcountseitherTPorFPonce, dataset.GPTScanreliesonGPTtogaintheabilitytoanalyzecode accordingtothecalculationin§5.1),andthesefunctionsarenot semantics,which,whencombinedwithcodecontextandcalling mergedyet(i.e.,afunctionAandthecombinationoffunctionA relationships,canmoreaccuratelyaddresstheseproblems. andallitscallerswouldbecountedmultipletimes)thatwillbedone WealsoranMScanontheDefiHacksdataset,as12ofthetotal inthefinalresult.Hence,sothenumberof“after”casesshownhere 14vulnerabilitiesinthisdatasetarerelatedtoPriceManipulation. ismuchlargerthanthefinalTP+FPinTable3.Fromtheresult,we Among these 12 true Price Manipulation vulnerabilities, MScan observethatstaticconfirmationeffectivelyfiltersoutmostfalse detected7,achievingarecallof58.33%andaprecisionof100%for positivecasesforthevulnerabilitytypes:WrongInterestRateOrder, PriceManipulation.However,MScanfailedtodetectanyothertype WrongCheckpointOrderandRiskyFirstDeposit.Thereasonisthat of logicvulnerabilities. MScan achieved highprecision because thedescriptionofscenariosandpropertiesforthesethreetypes itusedsomeattackincidentsintheDefiHacks datasettoderive is coarse-grained, leading to many candidate functions passing hard-codedpatternsforPriceManipulation,includingthematching theGPT-basedmatchingstep.Instaticconfirmation,GPTScancan ofspecificfunctionandvariablenames.However,incaseswhere furtherinstructGPTtoidentifyrelatedstatementsandvariables, hard-codedpatternsarenotapplicable,MScancannotgeneralize filteringoutthosethatdonotsatisfythevulnerabilitytypes.Overall, todetectvariantsofPriceManipulationvulnerabilities. after static confirmation, only 221 raw functions remain out of ForGPT-basedtools,theonlyavailablestudyatthetimeofour theoriginal647functions.Thisindicatesthatstaticconfirmation submissionwasconductedbyDavidetal.[34].Unfortunately,they successfullyfiltersouttwo-thirdsofthefalsepositives. didnotreleasetheirtool,andtherewasinsufficientinformationfor Wefurtheranalyzethenegativeimpactofstaticconfirmation. ustoreproduceit.Therefore,werelyonthestatisticsprovidedin Amongthe426casesfilteredout,only3ground-truthcaseswere theirpaperforcomparison.Accordingtothepaper,theirpureGPT- initiallymatchedbyGPTbutlaterexcludedbystaticanalysis,re- basedapproachachievedaprecisionof4.14%,arecallof43.84%, sultingin3falsenegatives.Anotherfalsenegativewasrelatedto andanF1scoreof7.57%withtheGPT-4-32kmodel,andapre- compilationproblems.TheremainingfourdidnotpasstheGPT-
cisionof4.30%,arecallof35.62%,andanF1scoreof7.68%with based scenario and property matching step. This indicates that theClaude-v1.3-100kmodel,respectively.Thefalsepositivesare staticconfirmationhasonlyaminorimpactonthefalsenegatives. significantlyhigherthanthoseofGPTScan,mainlybecausetheir tooldidnotvalidatetheGPToutputasGPTScandoesin§4.4,and AnswerforRQ3:Staticconfirmationeffectivelyfilteredout thuscouldbemoreeasilyaffectedbyGPT’sinherentproblemslike 65.84%ofthefalsepositivecasesintheWeb3Bugsdataset,while havingonlyaminorimpactonthefalsenegativecases. hallucination[64],biasintrainingdata,andambiguityinquestions. Indeed,RQ3in§5.3suggestsasimilarfindingbymeasuringthe GPT-onlyresultinGPTScan(seedetailsinTable4). 5.4 RQ4:PerformanceandFinancialOverhead InRQ4,weevaluatetherunningtimeandfinancialcostsofGPTScan whenusingOpenAI’sGPT-3.5-turboAPI.Weconsideredonlythe Answer for RQ2: GPTScan shows its efficacy in detecting costsassociatedwithinteractingwithGPTandconductingstatic ground-truth logic vulnerabilities in the Web3Bugs and Defi- analysis.WemeasuredthetimeandfinancialcostofGPTScanon Hacksdatasets,witharecallof83.33%andanF1scoreof67.8% all three datasets, and the results are shown in Table 5. In this forWeb3Bugs,andarecallof71.43%andanF1scoreof80%for experiment,weusedtiktoken[20],atokenizationtoolpublishedby DefiHacks,betterthanexistingstaticandGPT-basedtools. OpenAIandusedforGPTmodels,toestimatethenumberoftokensICSE2024,April2024,Lisbon,Portugal Sunetal. Table5:RunningtimeandfinancialcostsofGPTScan. 1 function deposit(uint _amount) external { Dataset KL∗ T∗∗ C∗∗∗ T/KL C/KL 2 ... 3 uint _pool = balance(); Top200 134.32 1,437.37 0.7507 10.70 0.005589 4 uint _totalSupply = totalSupply(); Web3Bugs 319.88 4,980.57 3.9682 15.57 0.018658 5 if (_totalSupply == 0 && _pool > 0) { // trading fee DefiHacks 17.82 375.41 0.2727 21.06 0.015303 accumulated while there were no IF LPs 6 vusd.safeTransfer(governance, _pool); Overall 472.02 6,793.35 4.9984 14.39 0.010589 7 _pool = 0; ∗KLforKLoC;∗∗TforTime;∗∗∗CforFinancialCost. 8 } 9 uint shares = 0; sentandreceivedbyGPTScan.Withthenumberoftokenssent 10 if (_pool == 0) { andreceived,wecanestimatethefinancialcostofGPTScan.The 11 shares = _amount; 12 } else { totalnumberoflinesofcodeis472K,andittook6,793.35seconds 13 shares = _amount * _totalSupply / _pool; and4.9984USDtocompletethescan.Onaverage,ittakes14.39 14 } secondsand0.010589USDtoscanperthousandlinesofcode. 15 ... 16 } OnTop200,thescancostperthousandlinesofcodeisthecheap- est,andthescanspeedperthousandlinesofcodeisthefastest.This Figure6:RiskyFirstDepositin2022-02-hubble. isbecausemostcandidatefunctionsarefilteredoutinGPTScan’s 1 function pendingRewards(uint256 _pid, address _user) external firsttwosteps,withouttheneedforfindingrelatedvariablesandex- view returns (uint256) { pressionsforstaticcheck.OnWeb3BugsandDefiHacks,thescancost 2 3 P Uo so el rI In nf fo o s st to or ra ag ge e p uo so el r = = p uo so el rI In nf fo o[ [_ _p pi id d] ]; [_user]; perthousandlinesofcodeisthemostexpensiveandthescanspeed 4 uint256 accRewardsPerShare = pool.accRewardsPerShare; perthousandlinesofcodeistheslowest,respectively.Projectsin 5 uint256 lpSupply = pool.lpToken.balanceOf(address(this)); 6 if (block.number > pool.lastRewardBlock && lpSupply != 0) { Web3BugsandDefiHacksaremorecomplexthanTop200,andthere 7 uint256 multiplier = getMultiplier(pool.lastRewardBlock aremorecomplexcandidatefunctionstobescanned.Thesecom- , block.number); plexfunctionscouldnotbefilteredbystaticfilteringandscenario 8 uint256 rewardsAccum = multiplier.mul(rewardsPerBlock). mul(pool.allocPoint).div(totalAllocPoint); matching,whichcausesmoretimeandfinancialcost. 9 accRewardsPerShare = accRewardsPerShare.add( rewardsAccum.mul(1e12).div(lpSupply)); AnswerforRQ4:GPTScanisfastandcost-effective,takingan 1 10 1 } return user.amount.mul(accRewardsPerShare).div(1e12).sub( averageofonly14.39secondsand0.01USDtoscanperthousand user.rewardDebt); linesofSoliditycodeinthetesteddatasets.Therelativelyhigher 12 } costandslowerspeedforWeb3BugsandDefiHackscanbeattrib- Figure7:PriceManipulationbyAMMin2021-09-sushimiso. utedtothepresenceofmorecomplexfunctionsthatcannotbe filteredoutbystaticfilteringandscenariomatching. 1 /// @notice The lp tokens that the user contributes need to have been transferred previously, using a batchable router. 2 function mint(address to) 5.5 RQ5:NewlyDiscoveredVulnerabilities 3 public InRQ5,weperformathoroughanalysisofGPTScan’sresultsonthe 4 beforeMaturity 5 returns (uint256 minted) Web3Bugsdatasettoseeifitcouldidentifynewvulnerabilitiesthat 6 { werepreviouslymissedbyhumanauditors.Interestingly,GPTScan 7 uint256 deposit = pool.balanceOf(address(this)) - cached; 8 minted = _totalSupply * deposit / cached;
successfully discovered 9 vulnerabilities from 3 different types, 9 cached += deposit; whichdidnotappearintheauditreportsofCode4rena.Among 10 _mint(to, minted); these9newlydiscoveredvulnerabilities,5areRiskyFirstDeposit, 11 } 3arePriceManipulationbyAMM,and1isFrontRunning.Inthe Figure8:FrontRunningin2021-08-yield. following paragraphs, we present one example of each type of pool.However,thetotalsupplycanbecontrolledbyusers,allowing newlydiscoveredvulnerabilityforfurtherdiscussion. themtomanipulatetheredeemedamountandexploitthecontracts. RiskyFirstDeposit.Amongthenewlydiscoveredvulnerabil- FrontRunning.ThereisonecaseofFrontRunningshownin ities,56%ofthemareRiskyFirstDeposit.Intheexampleshown Figure8,inwhichthetokentobemintedshouldbepreviously inFigure6,online11,whenthevariable_poolis0,indicating transferred(line1).However,anyonecancallthemintfunctionto anemptyliquiditypool,thedepositorcanobtainalltheshares minttokensthataretransferredbutnotminted,asthereisonly fromthepool.Thepresenceofboth_totalSupplyand_poolvari- acheckwiththecachedamountofthecontract(line7),butnot ablestorepresenttheliquidityamountinthepoolmayconfuse the cached amount of a specific user. This vulnerability allows humanauditors.Althoughlines5to8properlyhandlethecase an attacker to front run the minting process. When a user has when_totalSupplyis0,thisspecificconditioninvolving_pool transferredatokenbutnotmintedit,theattackercouldfrontrun online11createsavulnerabilitythatcouldbemissed. themintfunctiontomintthetokenbeforethelegitimateuser. PriceManipulationbyAMM.Another33%ofthenewlydis- coveredvulnerabilitiesarePriceManipulationbyAMM.Intheex- ampleshowninFigure7,thependingRewardsfunctionisusedto calculatetherewardsthatcanbeclaimedbytheuser.Online9, AnswerforRQ5:GPTScanidentified9newvulnerabilitiesnot whenthepoolisnotempty,theamountofrewardsthatcanbe presentintheauditreportsofCode4rena.Thishighlightsthe redeemedbytheuseriscalculatedbasedonthetotalsupplyinthe valueofGPTScanasausefulsupplementtohumanauditors.GPTScan:DetectingLogicVulnerabilitiesinSmartContractsbyCombiningGPTwithProgramAnalysis ICSE2024,April2024,Lisbon,Portugal 6 DISCUSSION al.[38]fine-tunedtheGPT-3modelforimprovedperformancein Inthissection,wediscussthecurrentlimitationsinGPTScanand GUIgraphicalinterfacetestingtasksandutilizeditforautomated thepotentialuseofemployingotherGPTmodels. testingofAndroidapplications.Additionally,PentestGPT[24]and Currentlimitationsindesignandimplementation.In§4.3, ChatRepair[60]utilizedfeedbackfromtheexecutionresultsto themodifiersfilteringpartonlyutilizedawhitelisttofilterthemod- enhancetheperformanceoftheGPTmodelduringinteractions. ifierswithaccesscontrol.However,thisfilteringmethodcanleadto falsepositivesornegativesofvulnerabilities.Toenhanceaccuracy, 8 CONCLUSION amorepreciseapproachisrequired,whichinvolvesretrievingthe Inthispaper,weproposedGPTScan,thefirsttoolcombiningGPT definitionofmodifiersandconductingadetailedsemanticanalysis withstaticanalysisforsmartcontractlogicvulnerabilitydetection. onthem.Forthestaticanalysispartin§4.4,asimplemethodwas GPTScanutilizedGPTtomatchcandidatevulnerablefunctions usedtoanalyzethecontrolflowgraphanddatadependencegraph. basedoncode-levelscenariosandproperties,andfurtherinstructed Thisanalysisisnotpath-sensitive,meaningthatsomepath-related GPTtointelligentlyrecognizekeyvariablesandstatements,which issues,suchasthereachabilityofcertainexecutionpathsunder werethenvalidatedbystaticconfirmation.Ourevaluationonthree specificconditions,mightbeoverlooked.Itcouldbeimprovedby diversedatasetswitharound400contractprojectsand3KSolidity introducingsymbolicexecutionenginestothestaticanalysispart. filesshowedthatGPTScanachieveshighprecision(over90%)forto- The use of other GPT models and parameters. As men- kencontractsandacceptableprecision(57.14%)forlargeprojects,as tionedin§4.5,GPTScanemploysthewidelyusedGPT-3.5-turbo wellasarecallofover70%fordetectingground-truthlogicvulner- model[27]asitsGPTmodel.Wealsoconductedapreliminarytest abilities.GPTScanisfast,cost-effective,andcapableofdiscovering usingGPT-4,butwedidnotobserveanotableimprovement,while newvulnerabilitiesmissedbyhumanauditors.Infuturework,we thecostincreased20times.ThisfindingsuggeststhatGPTScan willexpandGPTScan’ssupportformorelogicvulnerabilitytypes. doesnotnecessarilyrequiremorepowerfulGPTmodels. Asthe temperatureparameterissettozero,theanswersoftheGPTmodel tendtobedeterministic.Ahighertemperaturemightleadtomore ACKNOWLEDGEMENTS creativeanswers,butitcouldalsoresultinmorefalsepositives WethankDaweiZhou,ZheWang,GuoruiFan,LiweiTan,Hao orfalsenegatives.However,reproducingresultsbecomesmore Zhang,andothercolleaguesatMetaTrustLabsfortheirhelpwith challengingwithahighertemperature. Inthefuture,weplanto GPTScan,aswellasanonymousreviewersfortheirconstructive conductasystematictestofvariousGPTmodelswithinthecontext feedback.Thisresearch/projectissupportedbytheNationalRe-
ofGPTScan,includingGoogleBard,Claude(whenwehaveAPI searchFoundationSingaporeandDSONationalLaboratoriesunder accesstothem),andtheself-trainedLLaMAmodel,aswellasthe theAISingaporeProgramme(AISGAwardNo:AISG2-RP-2020- influenceofdifferentparametersonGPTScan. 019),theNationalResearchFoundation,Singapore,andtheCyber SecurityAgencyunderitsNationalCybersecurityR&DProgramme (NCRP25-P04-TAICeN).Anyopinions,findingsandconclusionsor 7 RELATEDWORK recommendationsexpressedinthismaterialarethoseoftheau- Inthissection,wediscusssomerelatedwork.Variousresearchand thor(s)anddonotreflecttheviewsofNationalResearchFoundation, toolshavefocusedonvulnerabilitydetectioninsmartcontracts. SingaporeandCyberSecurityAgencyofSingapore. Traditionalstaticanalysistools,suchasSlither[37],Vandal[30], Ethainter[29],Zues[43],andSecurify[56],areusedtoanalyzethe sourcecodeanddetectvulnerabilities.Symbolicexecutiontools REFERENCES likeManticore[47]andMythril[13]canperformboundchecksand [1] 2016. https://www.coindesk.com/learn/understanding-the-dao-attack/ detectvulnerabilitiesinbytecodeandsourcecode.Theseanalysis [2] 2021. https://github.com/code-423n4/2021-11-yaxis [3] 2022. https://www.freecodecamp.org/news/what-is-yaml-the-yml-file-format/ toolshavebeenappliedtodetectvulnerabilitiesinsmartcontracts, [4] 2023. https://blog.openzeppelin.com/on-the-parity-wallet-multisig-hack- suchasre-entrancy[52,61],arithmeticoverflow[54],stateincon- 405a8c12e8f7 [5] 2023. https://openai.com/chatgpt sistencyproblems[28],andaccesscontrolproblems[36,39,46]. [6] 2023. https://openai.com/pricing Dynamicanalysistools,suchasfuzztesting[40,41,59,63],auto- [7] 2023. https://github.com/crytic/crytic-compile maticallygeneratetestcasesorinputsforsmartcontractstofind [8] 2023. https://github.com/ZhangZhuoSJTU/Web3Bugs [9] 2023. https://wooded-meter-1d8.notion.site/ abnormalbehaviorsduringruntime.Formalverificationtechniques 0e85e02c5ed34df3855ea9f3ca40f53b?v=22e5e2c506ef4caeb40b4f78e23517ee likeVerx[51]andVeriSmart[53]canbeusedtocheckuser-provided [10] 2023. https://code4rena.com/ specifications.Nevertheless,Zhangetal.[65]suggestedthatmore [11] 2023. https://soliditylang.org/ [12] 2023. https://docs.soliditylang.org/en/latest/smtchecker.html than80%ofexploitablebugsaremachineundetectable. [13] 2023. https://github.com/Consensys/mythril BeforetheadventofChatGPT(GPT-3.5)[49],mostNLP-based [14] 2023. https://blog.trailofbits.com/2023/03/22/codex-and-gpt4-cant-beat- humans-on-smart-contract-audits/ vulnerabilitydetectionmethods[32,33,48,55,58]involvedfeed- [15] 2023. https://github.com/code-423n4/2022-04-jpegd-findings/issues/12 ingcodeintobinaryormulti-classificationmodels.Now,withthe [16] 2023. https://github.com/code-423n4/2022-04-backd developmentofinstructingGPT[57]andotherresearchproviding [17] 2023. https://github.com/code-423n4/2022-04-backd-findings/issues/36 [18] 2023. https://github.com/code-423n4/2022-05-backd/blob/ few-shotlearningcapabilities[31],interactivesolutionscanbeused 2a5664d35cde5b036074edef3c1369b984d10010/protocol/contracts/StakerVault. fortaskslikecoderepair[42,60]andvulnerabilitydetection[34]. sol However,accordingtotheresearchbyDavidetal.[34],theGPT- [19] 2023. https://app.metatrust.io/ [20] 2023. https://github.com/openai/tiktoken 4 model itself cannot accurately detect vulnerabilities. Chen et [21] 2023.ANTLR. https://www.antlr.org/ICSE2024,April2024,Lisbon,Portugal Sunetal. [22] 2023.BreakingBarriers:GPTScan’sGame-changingRoleinSmartContractSecu- [48] MarwanOmar.2023.DetectingsoftwarevulnerabilitiesusingLanguageModels. rity. https://metatrust.io/company/newsroom/post/breaking-barriers-gptscans- arXivpreprintarXiv:2302.11773(2023). gamechanging-role-in-smart-contract-security [49] LongOuyang,JeffWu,XuJiang,DiogoAlmeida,CarrollL.Wainwright,Pamela [23] 2023.falcon-metatrust:MetaTrustforkofSlitherAnalyzer. https://github.com/ Mishkin,ChongZhang,SandhiniAgarwal,KatarinaSlama,AlexRay,John MetaTrustLabs/falcon-metatrust Schulman,JacobHilton,FraserKelton,LukeMiller,MaddieSimens,Amanda [24] 2023.GreyDGL/PentestGPT. https://github.com/GreyDGL/PentestGPT Askell,PeterWelinder,PaulChristiano,JanLeike,andRyanLowe.2022.Train- [25] 2023. MetaScan v1.6: Unparalleled Visibility and AI Security for Smart inglanguagemodelstofollowinstructionswithhumanfeedback. https: Contracts. https://metatrust.io/company/newsroom/post/metascan-v16- //doi.org/10.48550/arXiv.2203.02155arXiv:2203.02155[cs].
unparalleled-visibility-and-ai-security-for-smart-contracts [50] LongOuyang,JeffWu,XuJiang,DiogoAlmeida,CarrollL.Wainwright,Pamela [26] 2023.OpenZeppelin. https://www.openzeppelin.com Mishkin,ChongZhang,SandhiniAgarwal,KatarinaSlama,AlexRay,John [27] 2023.Overview-OpenAIAPI. https://platform.openai.com Schulman,JacobHilton,FraserKelton,LukeMiller,MaddieSimens,Amanda [28] PriyankaBose,DipanjanDas,YanjuChen,YuFeng,ChristopherKruegel,and Askell,PeterWelinder,PaulChristiano,JanLeike,andRyanLowe.2022.Train- GiovanniVigna.2022.Sailfish:Vettingsmartcontractstate-inconsistencybugs inglanguagemodelstofollowinstructionswithhumanfeedback. (2022). inseconds.In2022IEEESymposiumonSecurityandPrivacy(SP).IEEE,161–178. https://doi.org/10.48550/ARXIV.2203.02155 [29] LexiBrent,NevilleGrech,SifisLagouvardos,BernhardScholz,andYannisSmarag- [51] AntonPermenev,DimitarDimitrov,PetarTsankov,DanaDrachsler-Cohen,and dakis.2020.Ethainter:asmartcontractsecurityanalyzerforcompositevulner- MartinVechev.2020.Verx:Safetyverificationofsmartcontracts.In2020IEEE abilities.InProceedingsofthe41stACMSIGPLANConferenceonProgramming symposiumonsecurityandprivacy(SP).IEEE,1661–1677. LanguageDesignandImplementation.454–469. [52] MichaelRodler,WentingLi,GhassanO.Karame,andLucasDavi.2019.Sereum: [30] LexiBrent,AntonJurisevic,MichaelKong,EricLiu,FrancoisGauthier,Vincent ProtectingExistingSmartContractsAgainstRe-EntrancyAttacks.In26thAn- Gramoli,RalphHolz,andBernhardScholz.2018. Vandal:Ascalablesecurity nualNetworkandDistributedSystemSecuritySymposium,NDSS2019,SanDiego, analysisframeworkforsmartcontracts.arXivpreprintarXiv:1809.03981(2018). California,USA,February24-27,2019.TheInternetSociety. [31] TomBrown,BenjaminMann,NickRyder,MelanieSubbiah,JaredDKaplan, [53] SunbeomSo,MyunghoLee,JisuPark,HeejoLee,andHakjooOh.2020.VeriS- PrafullaDhariwal,ArvindNeelakantan,PranavShyam,GirishSastry,Amanda mart:AhighlyprecisesafetyverifierforEthereumsmartcontracts.In2020IEEE Askell,etal.2020.Languagemodelsarefew-shotlearners.Advancesinneural SymposiumonSecurityandPrivacy(SP).IEEE,1678–1694. informationprocessingsystems33(2020),1877–1901. [54] BryanTan,BenjaminMariano,ShuvenduKLahiri,IsilDillig,andYuFeng.2022. [32] YizhengChen,ZhoujieDing,XinyunChen,andDavidWagner.2023.DiverseVul: SolType:refinementtypesforarithmeticoverflowinsolidity.InProc.ACMPOPL. ANewVulnerableSourceCodeDatasetforDeepLearningBasedVulnerability [55] ChandraThapa,SeungIckJang,MuhammadEjazAhmed,SeyitCamtepe,Josef Detection.arXivpreprintarXiv:2304.00409(2023). Pieprzyk,andSuryaNepal.2022.Transformer-basedlanguagemodelsforsoft- [33] AntonCheshkov,PavelZadorozhny,andRodionLevichev.2023.Evaluationof warevulnerabilitydetection.InProceedingsofthe38thAnnualComputerSecurity ChatGPTModelforVulnerabilityDetection. arXivpreprintarXiv:2304.07232 ApplicationsConference.481–496. (2023). [56] PetarTsankov,AndreiDan,DanaDrachsler-Cohen,ArthurGervais,Florian [34] IsaacDavid,LiyiZhou,KaihuaQin,DawnSong,LorenzoCavallaro,andArthur Buenzli,andMartinVechev.2018.Securify:Practicalsecurityanalysisofsmart Gervais.2023.Doyoustillneedamanualsmartcontractaudit?arXiv:2306.12338 contracts.InProceedingsofthe2018ACMSIGSACconferenceoncomputerand (Jun2023). http://arxiv.org/abs/2306.12338arXiv:2306.12338[cs]. communicationssecurity.67–82. [35] YinlinDeng,ChunqiuStevenXia,HaoranPeng,ChenyuanYang,andLingming [57] YizhongWang,YeganehKordi,SwaroopMishra,AlisaLiu,NoahA.Smith,Daniel Zhang.2023. LargeLanguageModelsAreZero-ShotFuzzers:FuzzingDeep- Khashabi,andHannanehHajishirzi.2022.Self-Instruct:AligningLanguageModel LearningLibrariesviaLargeLanguageModels.InProceedingsofthe32ndACM withSelfGeneratedInstructions. SIGSOFTInternationalSymposiumonSoftwareTestingandAnalysis.ACM,Seattle [58] HongjunWu,ZhuoZhang,ShangwenWang,YanLei,BoLin,YihaoQin,Haoyu WAUSA,423–435. https://doi.org/10.1145/3597926.3598067 Zhang,andXiaoguangMao.2021.Peculiar:Smartcontractvulnerabilitydetection [36] YuzhouFang,DaoyuanWu,XiaoYi,ShuaiWang,YufanChen,MengjieChen, basedoncrucialdataflowgraphandpre-trainingtechniques.In2021IEEE32nd YangLiu,andLingxiaoJiang.2023.Beyond“Protected”and“Private”:AnEmpir- InternationalSymposiumonSoftwareReliabilityEngineering(ISSRE).IEEE,378– icalSecurityAnalysisofCustomFunctionModifiersinSmartContracts.InProc. 389. ACMISSTA. [59] ValentinWüstholzandMariaChristakis.2020. Harvey:Agreyboxfuzzerfor [37] JosselinFeist,GustavoGrieco,andAlexGroce.2019. Slither:astaticanalysis smartcontracts.InProceedingsofthe28thACMJointMeetingonEuropeanSoftware
frameworkforsmartcontracts.In2019IEEE/ACM2ndInternationalWorkshopon EngineeringConferenceandSymposiumontheFoundationsofSoftwareEngineering. EmergingTrendsinSoftwareEngineeringforBlockchain(WETSEB).IEEE,8–15. 1398–1409. [38] SidongFengandChunyangChen.2023.PromptingIsAllYourNeed:Automated [60] ChunqiuStevenXiaandLingmingZhang.2023. KeeptheConversationGo- AndroidBugReplaywithLargeLanguageModels.arXivpreprintarXiv:2306.01987 ing:Fixing162outof337bugsfor$0.42eachusingChatGPT. arXivpreprint (2023). arXiv:2304.00385(2023). [39] AsemGhaleb,JuliaRubin,andKarthikPattabiraman.2023.AChecker:Statically [61] YinxingXue,MingliangMa,YunLin,YuleiSui,JiamingYe,andTianyongPeng. DetectingSmartContractAccessControlVulnerabilities.Proc.ACMICSE(2023). 2020. Cross-ContractStaticAnalysisforDetectingPracticalReentrancyVul- [40] GustavoGrieco,WillSong,ArturCygan,JosselinFeist,andAlexGroce.2020. nerabilitiesinSmartContracts.In35thIEEE/ACMInternationalConferenceon Echidna:effective,usable,andfastfuzzingforsmartcontracts.InProceedingsof AutomatedSoftwareEngineering,ASE2020,Melbourne,Australia,September21-25, the29thACMSIGSOFTInternationalSymposiumonSoftwareTestingandAnalysis. 2020.IEEE,1029–1040. 557–560. [62] XiaoYi,YuzhouFang,DaoyuanWu,andLingxiaoJiang.2023. BlockScope: [41] BoJiang,YeLiu,andWingKwongChan.2018.Contractfuzzer:Fuzzingsmart DetectingandInvestigatingPropagatedVulnerabilitiesinForkedBlockchain contractsforvulnerabilitydetection.InProceedingsofthe33rdACM/IEEEInter- Projects.InProc.ISOCNDSS. nationalConferenceonAutomatedSoftwareEngineering.259–269. [63] WilliamZhang,SebastianBanescu,LeonardoPasos,StevenStewart,andVijay [42] NanJiang,KevinLiu,ThibaudLutellier,andLinTan.2023. Impactofcode Ganesh.2019.Mpro:Combiningstaticandsymbolicanalysisforscalabletest- languagemodelsonautomatedprogramrepair.arXivpreprintarXiv:2302.05020 ingofsmartcontract.In2019IEEE30thInternationalSymposiumonSoftware (2023). ReliabilityEngineering(ISSRE).IEEE,456–462. [43] SukritKalra,SeepGoel,MohanDhawan,andSubodhSharma.2018. ZEUS: [64] YueZhang,YafuLi,LeyangCui,DengCai,LemaoLiu,TingchenFu,Xinting AnalyzingSafetyofSmartContracts.InProceedings2018NetworkandDistributed Huang,EnboZhao,YuZhang,YulongChen,LongyueWang,AnhTuanLuu,Wei SystemSecuritySymposium.InternetSociety,SanDiego,CA. Bi,FredaShi,andShumingShi.2023.Siren’sSongintheAIOcean:ASurveyon [44] TakeshiKojima,ShixiangShaneGu,MachelReid,YutakaMatsuo,andYusuke HallucinationinLargeLanguageModels. arXiv:2309.01219[cs.CL] Iwasawa.2022. Largelanguagemodelsarezero-shotreasoners. Advancesin [65] ZhuoZhang,BrianZhang,WenXu,andZhiqiangLin.2023. Demystifying neuralinformationprocessingsystems35(2022),22199–22213. ExploitableBugsinSmartContracts.In2023IEEE/ACM37thIEEEInternational [45] EmiLacapra.2023. Whatareliquidityprovider(LP)tokens,andhowdothey ConferenceonSoftwareEngineering. work? https://cointelegraph.com/explained/what-are-liquidity-provider-lp- [66] LiyiZhou,XihanXiong,JensErnstberger,StefanosChaliasos,ZhipengWang,Ye tokens-and-how-do-they-work Wang,KaihuaQin,RogerWattenhofer,DawnSong,andArthurGervais.2023. [46] YeLiu,YiLi,Shang-WeiLin,andCyrilleArtho.2022.Findingpermissionbugs SoK:DecentralizedFinance(DeFi)Attacks.InIEEESymposiumonSecurityand insmartcontractswithrolemining.InProceedingsofthe31stACMSIGSOFT Privacy(SP).IEEE. InternationalSymposiumonSoftwareTestingandAnalysis.716–727. [47] MarkMossberg,FelipeManzano,EricHennenfent,AlexGroce,GustavoGreico, JosselinFeist,TrentBrunson,andArtemDinaburg.2019. Manticore:AUser- FriendlySymbolicExecutionFrameworkforBinariesandSmartContracts.In Proc.ACMASE.
2308.06113 A Uniform Representation of Classical and Quantum Source Code for Static Code Analysis 1st Maximilian Kaul 2nd Alexander Ku¨chler 3rd Christian Banse Fraunhofer AISEC Fraunhofer AISEC Fraunhofer AISEC Garching, Germany Garching, Germany Garching, Germany maximilian.kaul@aisec.fraunhofer.de alexander.kuechler@aisec.fraunhofer.de christian.banse@aisec.fraunhofer.de Abstract—The emergence of quantum computing raises the analysis across the boundaries of the two worlds, as proposed question of how to identify (security-relevant) programming by Valenica et al. [5]. errorsduringdevelopment.However,currentstaticcodeanalysis However,duetotheearlystageofdevelopment,neitherthe tools fail to model information specific to quantum computing. bugs and security implications nor the platform technologies Inthispaper,weidentifythisinformationandproposetoextend classical code analysis tools accordingly. Among such tools, we of future quantum computing programs can be completely identify the Code Property Graph to be very well suited for this foreseen. Therefore, a generalized approach to the analysis of taskasitcanbeeasilyextendedwithquantumcomputingspecific quantum programs, as well as their interface to the classical information. For our proof of concept, we implemented a tool parts is needed. This approach must be independent of the whichincludesinformationfromthequantumworldinthegraph actual quantum programming language, since the popularity and demonstrate its ability to analyze source code written in QiskitandOpenQASM.Ourtoolbringstogethertheinformation oflanguagesmightchangeinthefuture,andneedstoofferan from the classical and quantum world, enabling analysis across extensible way to perform analysis tasks for problems which bothdomains.Bycombiningallrelevantinformationintoasingle might not yet be known. detailedanalysis,thispowerfultoolcanfacilitatetacklingfuture In this paper, we propose a static code analysis technique quantum source code analysis challenges. whichcanbeappliedtobothquantumandclassicalprograms. IndexTerms—staticcodeanalysis,softwaresecurity,quantum We believe that an analysis platform for quantum programs code property graph, quantum source code analysis should allow maximal flexibility with a minimal loss of in- formation. One such technique is the so-called Code Property I. INTRODUCTION Graph (CPG) [6], a language-independent graph model com- Inrecentyears,quantumcomputingstartedtogainrelevance biningmultiplegraphsusedinstaticcodeanalysis.Weextend in research and the first real-world implementations of quan- this concept to quantum computing programs by modeling tum computers have been proposed by industry [1], [2]. Since the memory and operations as well as dependencies between quantum computing is a fairly new paradigm and developers the qubits or quantum registers. We also bridge the boundary still need to adjust to the way quantum programs work, one between the classical and quantum parts of the program. In can expect an increasing number of implementations to be summary, our contributions are as follows: error-prone or even vulnerable. • We propose a static program analysis technique which This calls for the need to ensure the quality, safety and spans the classical and quantum parts. Our prototype security of upcoming quantum programs, e.g. mandated by implementation1 can analyze Qiskit and OpenQASM. the “Talavera Manifesto” [3]. Piattini et al. [4] formulate that • We iterate different use-cases for bugs in quantum com- securityandprivacybydesignandthequalityofquantumsoft- puting programs and present graph queries to identify warearekeyaspectsofQuantumSoftwareEngineering.While themusingourprototype.Lastly,weshowthecalculation researchers proposed numerous program analysis techniques of complexity metrics using our approach. for the security and safety of classical computer programs for decades, there is a distinct lack of methodologies to analyze II. BACKGROUND quantum computing code. Currently, quantum programs con- In this section, we present the necessary background on sist of a classical part and a quantum part. This requires an code analysis and quantum programming. ©2023 IEEE. Personal use of this material is permitted. Permission from A. Code Property Graphs IEEE must be obtained for all other uses, in any current or future media, A CPG builds upon previous graph-based program analysis includingreprinting/republishingthismaterialforadvertisingorpromotional purposes,creatingnewcollectiveworks,forresaleorredistributiontoservers techniques which use graph traversals to analyze the code. orlists,orreuseofanycopyrightedcomponentofthisworkinotherworks. Yamaguchietal.[6]combinemultiplegraphssuchastheAb- ThisresearchissupportedbytheBavarianMinistryofEconomicAffairs, stract Syntax Tree (AST), Program-dependence Graph (PDG) Regional Development and Energy with funds from the Hightech Agenda Bayern. DOI:10.1109/QCE57702.2023.00115 1https://github.com/Fraunhofer-AISEC/cpg/tree/quantum-cpg 3202 ceD 21 ]RC.sc[ 2v31160.8032:viXraandControl-flowGraph(CFG)intoasinglesupergraph.Since Classical Classical Hardware Quantum Computer then, numerous frameworks have been proposed by security Local Machine in the Datacenter analysts, e.g., the open-source project cpg [7]. We chose this Classical Parts Quantum Service implementation since it is extensible and provides the ability Local Part Remote Part Quantum Part to analyze Python code which is prevalent in current quantum computing frameworks. The translation of code is split into so-called language frontends which transfer the source code Figure1. Ourunderstandingofdifferentcomponentsofquantumprograms
to the CPG’s AST representation and passes which enrich the (inblack)andthehardwareonwhichtheyrun(blueboxes). CPG with more information like Data-flow Graph (DFG) and Evaluation Order Graph (EOG) edges, among others. • The quantum service embeds the remote classical part B. Quantum Programming Languages andthequantumpart(i.e.,itconsistsofthewholecircuit 1) Qiskit: Qiskit [8] is a popular open-source development including potential context switches). framework for quantum programs implemented in Python. It • The classical parts of the program are all parts ran on offers its users a domain-specific language (DSL) to create classical hardware and include the local and remote part. quantum circuits. The circuit is generated as a Python object, thequbitsarerepresentedasindicesandthegatesaremethods III. REQUIREMENTS called on the circuit and receiving the qubits. The API is Based on the current state of development of the quantum designedtoallowinteractionsbetweenthequantumcomputing computing ecosystem, we identified the following require- code and the classical code (see Listing 1). ments for our analysis platform. circuit = QuantumCircuit(1, 1) 1 R1: Adaptability to Future Changes. As the technological circuit.h(0) 2 circuit.measure([0], [0]) 3 stack of quantum computing is still in a relatively early stage compiled = transpile(circuit, simulator) 4 ofdevelopment,theplatformshouldprovideenoughflexibility job = simulator.run(compiled, shots=1000) 5 to respond to future changes, including new programming result = job.result() # Fetch the results 6 counts = result.get_counts(compiled) 7 languages or software architectures. Access to existing infor- Code Listing 1. A simple code snippet in Qiskit which defines a quantum mation should not suffer from such changes. This requires a circuit where a Hadamard-gate (Line 2) is applied to qubit 0 and the result certain level of abstraction from current implementations. ismeasuredtoclassicalbit0.Thecircuitisexecuted1000times. R2: Considering Classical and Quantum Parts. Currently, 2) OpenQASM: OpenQASM [9] is a low-level language quantum programs are developed as a mixture of classical for quantum computers. The language features many con- and quantum parts where both parts interact with each other cepts of classical computing like branching, comparisons, through well-defined interfaces. The way in which a quantum function calls and classical types. OpenQASM extends this part is embedded in the classical part can provide interesting withquantumcomputingfeaturesbyaddingspecializedtypes, insights to an analyst and thus has to be modeled. If similar qubits, quantum gates, measurements and reset instructions. informationisavailableintheclassicalandquantumpartsofa OpenQASM does not handle the execution of the program program, it should be accessible through a common interface but only defines the code of the quantum service. Executing to simplify the usage of the analysis platform. QASM code can e.g. be scheduled in Qiskit. R3: Scalability. Current implementations of quantum pro- qreg q[1]; 1 grams are still limited with respect to the number of qubits or creg c[1]; 2 h q[0]; 3 gatesandhaveamoderatecomplexity.However,withthefore- measure q[0] -> c[0]; 4 seeableadvancementsinthepracticabilityofthetechnologies, CodeListing2. ThesamecircuitasinListing1butdefinedwithOpenQASM. thequantumcircuitswillgetmorecomplex.This,inturn,will require a highly scalable analysis platforms. C. Architecture of Quantum Programs IV. DESIGN Quantum programs consist of multiple parts which interact We propose to model a quantum program as an extension witheachotherandwhichrunondifferentmachines.Thisim- of a CPG. We call this new quantum-related part of the pacts the design of quantum programs and lets us distinguish graphQuantumCodePropertyGraph(QCPG).Astheclassical the following components as shown in Figure 1: part of the CPG remains unchanged, we can keep existing • The local part is run on the user’s local machine and analysis techniques. We believe that a CPG is a suitable follows the classical computing paradigms. representation as it can abstract from the actual code with a • The remote part runs in the datacenter operating the minimal loss of information. Additionally, the representation quantum computer. It performs classical computing but allows to extend the model with more information without interacts with the quantum parts through built-in APIs. the need to change established interfaces to the CPG. This • The quantum part is the code which is actually executed makes the representation future-proof and allows responding on the quantum computer hardware. to upcoming changes in the technological stack.A. Extending the Graph Model DFG Our model extends the CPG, which has been designed to AST h 0 measure result analyze classical software systems with semantic information ARGUMENTS r ae tla et xe td ent do inq gua Unt Mum Lc di ir ac gu ri ats m. sSi [m 10il ]a ,r [t 1o 1p ],ri wor ew ao dr dk cw oh ni cc eh pta sim os f EOG CPG_NODE CPG_NODE CPG_NODE DFG circuits,qubits,gatesandmeasurements.However,incontrast Qubit 0 DFG Qubit 0 DFG Bit 0 t b c do ee apt tt w ath bee oe efnp twcr d lo eaip ef sfo nse is cr te e had n elt be ctx i iy t rt sp ce . uen s T is ti o ho af en ngs dca l tt t a ho e s es s.U i ccF lM a au l srL st bh ii ce tp asrr lmo a pfi ro ael re re tus , s, sw oew d fee ta t hodd edi e ps xtt rhi c on e h gg a rcu anoi mgs nh e- . CPG_NODE QUANTUM_BIT_0 DFGREFR EE RF EE NR CS E_ STO_QUB QIT ubit 0
REFE RR EE FN EC RE SS _TO_C QPG U_N BO IDTE QU_BIT C_BIT REFERENCES REFERS_TO_CLASSI… We model each of our concepts as a separate type of node RELEVANT_FOR_GATES RELEVANT_FOR_GATES in the graph. The nodes are connected to each other with h EOG measure Bit 0 edges which either represent an input to a gate (including its order), or that a qubit is measured to a classical bit. Overall, Figure 2. The (partial) CPG corresponding to Listing 1. The circuit is this results in a graph holding classical information and one generated with nodes above the dashed green line (the classical CPG) in Qiskit’sPythonDSL(darkgreennodes).Weaddthesemanticinformationand holding the information related to quantum computing code. generatetheQCPGwhichadditionallycontainsthenodesbelowthedashed Figure 2 shows a part of the graph derived from Listing 1. line. This graph consists of classical and quantum bits (orange nodes) and Thedashedlinedepictstheborderbetweenclassicalprogram- the usages of the bits (light green nodes). It also contains the Hadamard gate (beige node - Line 2), and the measurement (blue node - Line 3). The ming (at the top) and the new quantum computing semantics. evaluationorderanddataflowedgesspanboththeclassicalandquantumparts oftheprogramandletthepartsinteractwitheachother.I.e.,theDFGedges B. Interactions between the Classical and Quantum Parts showthedataflowtothecallofresult()afterrunningthecircuit. Most current algorithms are implemented in a hybrid way, i.e., they consist of classical and quantum parts. The local TableI part pre-processes data, interprets the results of the circuit NODETYPESINTHEQUANTUMGRAPH and parametrizes and executes the circuit in a way to retrieve QuantumCircuit Container for classical and quantum bits and the desired results. This requires all parts to interact with oneormoreoperations,whichareexecutedre- each other through dedicated means. With the concept of motelyinthequantumcomputeroritsquantum- classical-interface. classical bits, we already introduce the medium to exchange QuantumGate AgateoperationaspartoftheQuantumCircuit, data between both parts of the program. Executing the circuit forexampleaHadamardgate(QuantumGateH). and passing data to or retrieving the result from a circuit’s QuantumBit Declarationofaqubitinsideacircuit. runs happens through a small set of well-known functions or QuantumBitReference ReferencetoaQuantumBit. QuantumRegister AregisterspanningmultipleQuantumBits. operations. This makes it easy to identify such points where QuantumMeasure AsinglemeasurementfromoneQuantumBitto we add transitions from the QCPG to the classical CPG. aClassicBit.Multiplemeasurementsaresplitup SimilartotheclassicCPG,weaddDFGandEOGedgesto intoseparatenodes. ClassicBit Singlepieceofmemory(1bit)inthequantum- our graph. This is shown by the red and blue edges in Figure classicinterfaceofaquantumcomputer. 2. These edges flow across the classical-quantum boundary. ClassicBitReference ReferencetoaClassicBit. Recently, the term “dynamic circuits” has been used to ClassicRegister AregisterspanningmultipleClassicBits. include controlflow modifying code such as if-statements or ClassicIf A control structure inside the quantum-classic interface,thatoperatesonameasuredClassicBit loops into the languages used for quantum programming. andallowsthedynamicexecutionofQuantum- Essentially,theseinstructionsmeasureaqubit,makeabranch- Gatesbasedonthecomparison. ing decision and continue computing in the quantum part of the algorithm based on the condition. To account for such techniques, we add a branching node with the test condition traversingtheCPGforcircuitdeclarationsandthenfollowthe and a branch statement to the QCPG. This ensures that we do operations on the circuit in order, adding EOG edges along not have to split the circuit and yet includes this controlflow the way. Control structures (ClassicIf, ...) are considered test- in our graph. This emphasizes the relevance of an analysis expression first, then the body. There is an EOG flow from pipeline which considers both parts of the program. the test-expression to the body (the test is true) and a flow Table I summarizes all node types of the graph. As our to the next instruction (the test is false). Overall, the EOG is extensions only add information to the original CPG, we can constructed similarly established as for classical programs. query the graph for the code related to the quantum service, D. DFG whilecompletelyreusingexistingqueriesfortheclassicalpart. Additionally,wecantrackdataflowacrossallpartsofthecode. The DFG depends on the EOG and is more interesting to construct. We keep the DFG out of the QuantumGates, as C. EOG our operations make use of QuantumBitReferences instead of Once the quantum nodes have been created, we can the QuantumBits directly. This enables us to track individual (language-independently) add EOG edges. We achieve this by dataflows. Specifically, we first loop through all operationsand connect their QuantumBitReferences internally (i.e. we VI. USAGESCENARIOS add a DFG from the control bit to the controlled bit for the In this section, we demonstrate the effectiveness of our ap- CX gate). We then identify the first operation acting on each proach and illustrate the capabilities of our analysis platform. qubit and traverse the (potentially multiple) EOG edges from Due to the lack of large-scale datasets that contain security or there, adding DFG edges along the way, thus connecting the programming errors, we tried to come up with potential pro- operations with each other. Finally, we reconnect the classic gramming errors and code smells and created example source CPG to the QCPG by connecting the measure instruction code with these flaws in Qiskit and OpenQASM. Partially,
withtheQiskitresultinstruction(andsubsequentbitsensitive these flaws are inspired by flaws usually found in classical access to it), thus providing dataflow edges from the quantum computing and are adapted to their quantum counterparts. ClassicBit node back to the classic CPG node. Other flaws originate from the distinct interfaces between the remote part and quantum part, as well as interactions with V. IMPLEMENTATION the final result provided by a quantum service to the local We implemented this QCPG using the open source cpg part of the code. Lastly, we also provide exemplary queries to library [7]. We summarize implementation details of the calculate different complexity metrics on our dataset. language frontends and passes which parse Qiskit and Open- a = 0; b = 1 1 QASMcodeandtransfertheinformationintothegraphmodel. # Create a quantum circuit with 4 qubits 2 circuit = QuantumCircuit(4, 4) 3 A. Parsing QC Code # Initialize qubits with local part values 4 circuit.initialize(str(a), 0) 5 As a first step, we extended the cpg with the ability to circuit.initialize(str(a), 1) 6 circuit.initialize(str(b), 2) 7 handleQiskitandOpenQASMcode.Qiskiteasilytranslatesto circuit.initialize(str(b), 3) 8 a classic CPG, as it is pure Python code. E.g., the instruction # Different quantum operations 9 qc.cx(0, 1) translates to a CallExpression to the function cx circuit.h(0); circuit.h(3) 10 circuit.cx(1, 0) 11 receiving the integer parameters 0 and 1. circuit.measure([2], [2]) 12 ForOpenQASM,weimplementedanOpenQASMv3parser circuit.x(1).c_if(2, 0) 13 since we are not aware of any functional off-the-shelf im- circuit.measure([1,3], [1,3]) 14 # Run job on target (hardware or simulator) 15 plementation which provides us with an AST. Our parser cc = transpile(circuit, target) 16 translates the source code to the cpg’s version of the AST. job = target.run(cc, shots=1000) 17 Mappingthelow-levelinstructionsofOpenQASMtothehigh- # Grab results from the job 18 result = job.result() 19 level CPG representation is not straight-forward. Most inter- counts = result.get_counts(cc) 20 estingly,wemapgateinstructionstofunctioncalls.Arithmetic # Evaluate results back in local part 21 instructions and controlflow modifying instructions such as if for bitstring in counts: 22 c0 = int(bitstring[-0-1]) 23 -statements directly map to the classical CPG. For reset and c1 = int(bitstring[-1-1]) 24 measure instructions, we use CallExpressions just as in Qiskit. c2 = int(bitstring[-2-1]) 25 c3 = int(bitstring[-3-1]) 26 # Execute code based on a decision 27 B. Quantum Code Property Graph # of a measured bit for every result 28 if c2 == 1: 29 The challenge is to add the extra semantic information do_something_complex() 30 (Section IV) to the graph. We implemented a pass adding the CodeListing3. Listingforcomplex.py.InLine1,twovariablesrepresenting quantum nodes described in Table I to the classical CPG and individualbitsaredefined.Thesearethenusedtoinitializethestatevectorof thusgeneratingtheQCPG.Thepassfurtherconnectsthenodes differentqubits(Line5-8).Lines10-14representseveralquantumoperations, of the classical and quantum parts of the resulting graph. such as gate operations and measurements. See Figure 3 for a visualization oftheseoperations.Lines16-17containcodethatexecutesthequantumcode For Qiskit, we scan the CPG for variables which hold the (eitheronhardwareorasimulator)andLines19-20fetchtheresultfromthe return value of the method QuantumCircuit. This lets us create quantum service to a local variable. The local result is then split back into theQuantumCircuit,QuantumBitandClassicBitnodesforour individual bits in Lines 23-26. Finally, a (local) code execution decision is madebasedononemeasuredbitinLines29-30. QCPG. We then traverse the CPG to collect all CallExpres- sions on the variable to find all operations and create the Listing 3 shows an example Qiskit source code which respective nodes (e.g., QuantumGate, QuantumMeasure, ...). demonstratestheinteractionbetweenthequantumserviceand For the instruction qc.h(0) in Listing 1, this results in the the local part of the program. following nodes in Figure 2: • a QuantumGateH (beige node) A. Queries to find programming errors • a QuantumBitReference (light green node) connected to In order to find patterns that correspond to programming qubit 0 and the Hadamard gate errorsorcodesmells,weanalyzedthesourcecodeinListing3 • a QuantumBit (orange node) connected to its references using our prototype and stored the resulting graph in a Neo4J Thisresultsinquantumnodeswhicharenowenrichedwith graph database. In the following, we discuss several graph EOGandDFGedgesasdescribedinSectionsIV-CandIV-D. queries to find the following patterns.is explicitly set as an input variable, that the circuit should be q 0: |ψ⟩(0) H split into distinct ones which are executed depending on the q 1: |ψ⟩(0) • X classic variable which is used to initialize the qubit. Once we execute the query in Listing 6, we can determine that the q 2: |ψ⟩(1) ClassicIf only depends on c which is measured on q , but 2 2 q 3: |ψ⟩(1) H has no operations affecting it (see previous scenario). (cid:11)(cid:19) (cid:11)(cid:19) (cid:11)(cid:19) c: / MATCH p=(a:ClassicIf)-[:CONDITION]->()-[:LHS]-> 4 2 3 c2=0x0 1 (r:ClassicBitReference) WHERE NOT EXISTS {
(r)<-[:DFG*3..]-(:QuantumBit)} Figure3. ThequantumcircuitcontainedinListing3. AND NOT EXISTS {(r)<-[:DFG*]-(:QuantumBit) -[:RELEVANT_FOR_GATES]-(:QuantumGate)} RETURN p CodeListing6. Cypherquerytofindnearlyconstantconditionsbyidentifying 1) SUPERFLUOUS OPERATION: Quantum gate does ClassicIf nodeswhichdependonbitsthatarenotmodifiedbygates. not affect measurement: In this scenario we are interested in 4) RESULT BIT NOT USED: Single bit measured but quantum operations, e.g., gates, that affect qubits, but those not used locally: This scenario builds upon the observation qubitarenotmeasuredordonotaffectotherqubitswhichare that the result returned by the Qiskit framework has to be measured. This makes the original gate operation superfluous decomposed and interpreted by the user. We assume that this and can be regarded as a programming error. happens by accessing individual classic bits c which are X MATCH p=(:QuantumGate)-->(r:QuantumBitReference) contained in the key of the result dictionary. In this case, if WHERE NOT EXISTS{(r)-[:DFG*]->(:QuantumBitReference) a user does not access one of the c which are measured in <-[:QU_BIT]-(:QuantumMeasure)} RETURN p X the circuit, there might be a misfit between the circuit and its CodeListing4. Cypherquerytofindsuperfluousoperationsbyidentifying QuantumBitReferenceswhichdonothaveadataflowtoaQuantumMeasure. usage in the program. We can simulate this by commenting Listing 4 shows a possible Cypher (a query language for out one of the Lines 23-26 in Listing 3. This means that Neo4j graph databases) query to find such gate operations. the measure and the preceding operations are irrelevant to Specifically, we look for QuantumGate nodes that do not the further outcome of the program and it might be worth have a dataflow from any of their qubit arguments to a optimizing the circuit. Listing 7 shows a cypher query which QuantumMeasure node. Given the circuit in Figure 3, the detects such issues. This use-case illustrates the need for an query returns that gates H and CX operating on q and q analysis across both parts of the program. 0 1 are ineffective on the result. While the CX gate does have a MATCH p=(r:ClassicBitReference)<-[:C_BIT]- dataflow towards q 0 (its target qubit), the state vector of q 1 (:QuantumMeasure) WHERE NOT EXISTS {(r)-[:DFG] (its control qubit) is not changed and is measured in its initial ->(:ArraySubscriptionExpression)} RETURN p state. Most likely the developer of this circuit made a mistake CodeListing7. Cypherquerytofindunusedresultbits;theyareunusedif theytherespectiveindexisnotaccessedinthefinalbitstringresultarray. in switching control and target qubit of the CX operation or mistakenly measured q instead of q . 5) CONSTANT RESULT BIT: Result bit is constant: 1 0 2) CONSTANT CLASSIC BIT: A bit is measured but Buildinguponthepreviousdataflows,wecanalsodetectifre- has not been transformed: Besides not measuring q , the sultbitsareused,butcontainclassicbitsthatwerenotaffected 0 circuit in Figure 3 contains another potential bug because it by operations in the quantum circuit. The query in Listing 8 measures q which has never been changed. This leads to an traces the DFG from the local function do_something_complex 2 almost constant value for this bit which does not carry much (Line 30 in Listing 3) back to its origin in the quantum part. information but only increases the complexity of the circuit. We can see that the execution is based on the contents of The query in Listing 5 identifies such patterns. c 2, which is measured on q 2, but never changed by any gate operation. Its value is therefore still its original state 1, which MATCH p=(:QuantumBit)-[:DFG]->(:QuantumBitReference) -[:DFG]->(:ClassicBitReference) RETURN p was assigned by the local variable b in Line 7. Code Listing 5. Cypher query to find nearly constant measured qubits MATCH p=(c:CallExpression)<-[:EOG*]-(:IfStatement) – characterized by a direct dataflow from a QuantumBitReference to a -[:DFG*]-(:ArraySubscriptionExpression) ClassicBitReferencewithoutanyotherdataflowedgesinbetween. <-[:DFG]-(:ClassicBitReference) 3) CONSTANT CONDITION: The condition of a classic- <-[:DFG*]-(:QuantumNode) ifalwaysevaluatesto’true’or’false’: Thisscenarioisanex- WHERE c.name = "do_something_complex" RETURN p tension of the CONSTANT CLASSIC BIT use-case. Recently, CodeListing8. QuerytotracebacktheexecutionofaCallExpressiontoan IfStatement,andthenfindingthesourceofthedataflowtothatstatement. quantum computing frameworks added the ability to include if statements in the quantum code. This statement measures a B. Complexity Metrics qubit, compares it to another value (in the classic part of the quantumservice)andexecutesdifferentbranchesbasedonthis Cruz et al. [12] presented several metrics to compare the result (in the quantum part). However, if the qubit to measure complexity of quantum circuits. We model these metrics as has not been transformed by any operations (e.g., gates), it queries (see Listing 9) to fetch complexity information about results in a nearly constant evaluation. This indicates either a circuit automatically. This even works independently of the missingtransformationsinthecircuitor,iftherespectivequbit actual quantum programming language used.MATCH (q:QuantumBit) RETURN COUNT(q) AS value, TableII "Width" AS key UNION COMPARISONOFEXISTINGTOOLSWITHOURAPPROACH
MATCH (p:QuantumGate)<-[:RELEVANT_FOR_GATES]->(b: QuantumBit) RETURN COUNT(p) AS value, Qiskit UMLmodels CPG Ourapproach "Depth" AS key ORDER BY value DESC LIMIT 1 UNION Quantumparts ✓ ✓ ✗ ✓ MATCH (p:QuantumGate) RETURN COUNT(p) AS value, Classicalparts ✗ ✓ ✓ ✓ "NoGates" AS key UNION SuperfluousOperation ✓ ✗ ✗ ✓ MATCH (p:QuantumGateX) RETURN COUNT(p) AS value, ConstantClassicBit ✗ ✗ ✗ ✓ "NoP-X" AS key UNION ConstantCondition ✗ ✗ ✗ ✓ MATCH (p:QuantumGateY) RETURN COUNT(p) AS value, ResultBitNotUsed ✗ ✗ ✓ ✓ "NoP-Y" AS key UNION ConstantResultBit ✗ ✗ ✗ ✓ MATCH (p:QuantumGateZ) RETURN COUNT(p) AS value, Complexitymetrics ✗ ✗ ✗ ✓ "NoP-Z" AS key UNION MATCH (p:QuantumPauliGate) RETURN COUNT(p) AS value, "TNo-P" AS key UNION does not allow users to automatically measure these metrics MATCH (p:QuantumGateH) RETURN COUNT(p) AS value, "NoH" AS key UNION and furthermore they do not account for hybrid concepts. MATCH (q:QuantumBit)-[:DFG]->(:QuantumBitReference) Code Property Graphs. A wide range of works focuses <-[:QUANTUM_BIT_0]-(:QuantumGateH) WITH COUNT(q) AS countH on applying CPGs to different programming languages [6], MATCH (b:QuantumBit) WITH COUNT(b) AS total, countH [7],[33],low-levelcoderepresentationsorbinaries[34],[35], RETURN countH*1.0/total AS value, "% Java bytecode [36], [37] or even cloud applications [38]. CodeListing9. Querytocalculateasubsetofthemetricsproposedin[12]. Furthermore, a wide range of research uses these tools to analyzethesecurityofclassicalprogramse.g.bygraphqueries VII. RELATEDWORK [39],byapplyingmachinelearningtechniques[40],[41]orby extracting privacy properties from the graphs [42]. However, Prior work aims to model quantum circuits or quantum none of these works can be used to model quantum programs programs. Jime´nez et al. [13] generate a Knowledge Discov- astheylacksupportfortheframeworksanddonotmodelany ery Metamodel from Q# code and transfer it to a quantum specifics of these programs. We extend the concept by adding computing-specific extension of the UML representation [11]. more information which is not available in classical programs Similarly,otherresearch[10],[14]proposestomodelquantum and furthermore connect both parts. programs in UML graphs. Burgholzer et al. [15] aim to extract blocks with similar behavior from quantum circuit to VIII. DISCUSSIONANDFUTUREWORK ease further analysis. Qiskit itself provides a tool to visualize We revisit the requirements from Section III, discuss limi- quantum circuits but neither allows for automated analysis on tations of our tool and summarize future research directions. the generated images nor encodes the connection to the local Requirements. The requirements R1 and R3 are inherently part.Allthesemodelsareunsuitableforanautomatedanalysis. met by using a CPG as analysis platform as they scale well Other research models quantum programs as finite state even for large code bases (R3) and provide a language- machines [16]–[18], via abstract interpretation [19] or aim independentcoderepresentationwhichcanbeeasilyextended to apply SAT solving to some classes of quantum circuits (R1). Our solution combines the existing CPG with new [20]. These works require a specialized encoding of the quantum nodes in the QCPG. It keeps the interface consistent quantum circuits which, in many cases is limited in terms across all parts, thus enabling a cross-domain analysis (R2). of scalability [21] and generalizability [20]. Gheorghiu et al. [22] summarize techniques which aim at verifying quantum Limitations. The usage scenarios discussed in Section VI programs. However, researchers found that many bugs in describe an initial set of problems. However, we believe that quantum programs originate from the boundary between the the scientific community will identify more errors in quantum classical and quantum parts and from the quantum computing programs once the technology is more established. These frameworks [23], [24]. problems can be modeled as a query to our graph. At the Cruz-Lemusetal.[12]proposeasetofmetricsforquantum same time, the identified scenarios may not fit all usages of circuits. We showed that our tool can automatically measure quantumalgorithms.Duetothelackofanextensivesetoftest these metrics for a quantum program. Another branch of programs, our experiments are limited to only few examples. research aims to measure the maximal complexity of a circuit Future work. Future work can support more quantum pro- which can be executed on a given quantum computer [25]– gramminglanguages,improvethelevelofdetailfordataflows [29]. Our tool could automatically calculate these metrics and introduce the concept of parallel execution into the EOG. which allows an analyst to compare it with the achievable Once novel error types are identified, new queries should be values of the hardware to identify potential problems with developed to identify them. Furthermore, including hardware- the decoherence. Yet other researchers aim at describing the dependent information into the QCPG is left to future work. errors of individual gates [30], [31] on a physical level. Zhao [32] provides an overview over these metrics, bug types, and IX. CONCLUSION analyses of quantum programs. While these metrics can help We propose a method to analyze quantum and classical
toidentifypotentiallyerror-pronequantumcircuits,priorwork computing code in a unified representation. By adding quan-tumspecificnodesandedges,weenableanalysisoftheentire [19] N. Yu and J. Palsberg, “Quantum abstract interpretation,” in ACM program without hindering existing analyses of the local part SIGPLAN Conference on Programming Language Design and Imple- mentation(PLDI),2021. of the program. We further propose an initial set of analyses [20] L. Berent, L. Burgholzer, and R. Wille, “Towards a sat encoding for detecting potential programming errors, following dataflows quantum circuits: A journey from classical circuits to clifford circuits or calculating complexity metrics of quantum programs. and beyond,” in International Conference on Theory and Applications ofSatisfiabilityTesting,2022. [21] S. Ali and T. Yue, “Modeling quantum programs: Challenges, initial REFERENCES results,andresearchdirections,”inACMSIGSOFTInternationalWork- [1] IBM. Quantum-centric supercomputing: The next wave of shoponArchitecturesandParadigmsforEngineeringQuantumSoftware computing. [Online]. Available: https://research.ibm.com/blog/ (APEQS),2020. next-wave-quantum-centric-supercomputing [22] A.Gheorghiu,T.Kapourniotis,andE.Kashefi,“Verificationofquantum [2] F.Aruteetal.,“Quantumsupremacyusingaprogrammablesupercon- computation:Anoverviewofexistingapproaches,”TheoryofComputing ductingprocessor,”Nature,vol.574,no.7779,pp.505–510,2019. Systems,vol.63,2019. [3] M.Piattini,G.Peterssen,R.Pe´rez-Castillo,J.L.Hevia,M.A.Serrano, [23] P. Zhao, J. Zhao, and L. Ma, “Identifying bug patterns in quantum G.Herna´ndez,I.G.R.deGuzma´n,C.A.Paradela,M.Polo,E.Murina programs,”inIEEE/ACMInternationalWorkshoponQuantumSoftware et al., “The talavera manifesto for quantum software engineering and Engineering(Q-SE),2021. programming.”inQANSWER,2020,pp.1–5. [24] M. Paltenghi and M. Pradel, “Bugs in quantum computing platforms: [4] M.Piattini,G.Peterssen,andR.Pe´rez-Castillo,“Quantumcomputing: Anempiricalstudy,”Proc.ACMProgram.Lang.,vol.6,no.OOPSLA1, Anewsoftwareengineeringgoldenage,”SIGSOFTSoftw.Eng.Notes, apr2022. vol.45,no.3,pp.12–14,jul2020. [25] M.Salm,J.Barzen,F.Leymann,andB.Weder,“AboutaCriterionof [5] D. Valencia, J. Garcia-Alonso, J. Rojo, E. Moguel, J. Berrocal, and SuccessfullyExecutingaCircuitintheNISQEra:Whatwd≪1/ϵ eff J. M. Murillo, “Hybrid classical-quantum software services systems: Really Means,” in ACM SIGSOFT International Workshop on Archi- Exploration of the rough edges,” in Quality of Information and Com- tectures and Paradigms for Engineering Quantum Software (APEQS), munications Technology (QUATIC), A. C. R. Paiva, A. R. Cavalli, 2020. P.VenturaMartins,andR.Pe´rez-Castillo,Eds.,2021. [26] L. S. Bishop, S. Bravyi, A. Cross, J. M. Gambetta, and J. Smolin, [6] F.Yamaguchi,N.Golde,D.Arp,andK.Rieck,“Modelinganddiscov- “Quantumvolume,”Tech.Rep.,2017. eringvulnerabilitieswithcodepropertygraphs,”inIEEESymposiumon [27] M.Amico,H.Zhang,P.Jurcevic,L.S.Bishop,P.Nation,A.Wack,and SecurityandPrivacy(S&P),2014. D.C.McKay,“Definingstandardstrategiesforquantumbenchmarks,” [7] K.WeissandC.Banse,“Alanguage-independentanalysisplatformfor 2023. sourcecode,”2022. [28] A.W.Cross,L.S.Bishop,S.Sheldon,P.D.Nation,andJ.M.Gambetta, [8] Qiskit contributors, “Qiskit: An open-source framework for quantum “Validatingquantumcomputersusingrandomizedmodelcircuits,”Phys. computing,”2023. Rev.A,vol.100,Sep2019. [9] A.Cross,A.Javadi-Abhari,T.Alexander,N.D.Beaudrap,L.S.Bishop, [29] E.A.Sete,W.J.Zeng,andC.T.Rigetti,“Afunctionalarchitecturefor S. Heidel, C. A. Ryan, P. Sivarajah, J. Smolin, J. M. Gambetta, and scalable quantum computing,” in 2016 IEEE International Conference B.R.Johnson,“OpenQASM3:Abroaderanddeeperquantumassembly onRebootingComputing(ICRC),2016. language,”ACMTransactionsonQuantumComputing,vol.3,no.3,pp. [30] M. A. Nielsen, “A simple formula for the average gate fidelity of a 1–50,sep2022. quantum dynamical operation,” Physics Letters A, vol. 303, no. 4, pp. [10] R. Pe´rez-Castillo, L. Jime´nez-Navajas, and M. Piattini, “Modelling 249–252,2002. quantum circuits with uml,” in IEEE/ACM International Workshop on [31] D.Willsch,M.Nocon,F.Jin,H.DeRaedt,andK.Michielsen,“Gate- QuantumSoftwareEngineering(Q-SE),2021. error analysis in simulations of quantum computers with transmon [11] L. Jime´nez-Navajas, R. Pe´rez-Castillo, and M. Piattini, “Kdm to uml qubits,”Phys.Rev.A,vol.96,Dec2017. modeltransformationforquantumsoftwaremodernization,”inQuality [32] J. Zhao, “Quantum software engineering: Landscapes and horizons,” of Information and Communications Technology (QUATIC), A. C. R. 2021.
Paiva, A. R. Cavalli, P. Ventura Martins, and R. Pe´rez-Castillo, Eds., [33] “Joern–thebughunter’sworkbench,”https://github.com/joernio/joern. 2021. [34] A. Ku¨chler and C. Banse, “Representing llvm-ir in a code property [12] J. A. Cruz-Lemus, L. A. Marcelo, and M. Piattini, “Towards a set of graph,” in Information Security: 25th International Conference (ISC), metrics for quantum circuits understandability,” in Quality of Informa- 2022. tionandCommunicationsTechnology(QUATIC),A.C.R.Paiva,A.R. [35] J. Schu¨tte and D. Titze, “lios: Lifting ios apps for fun and profit,” in Cavalli,P.VenturaMartins,andR.Pe´rez-Castillo,Eds.,2021. InternationalWorkshoponSecureInternetofThings,2019. [13] L. Jime´nez-Navajas, R. Pe´rez-Castillo, and M. Piattini, “Reverse en- [36] W. Keirsgieter and W. Visser, “Graft: Static analysis of java bytecode gineering of quantum programs toward kdm models,” in Quality of with graph databases,” in Conference of the South African Institute of InformationandCommunicationsTechnology(QUATIC),M.Shepperd, ComputerScientistsandInformationTechnologists,2020. F. Brito e Abreu, A. Rodrigues da Silva, and R. Pe´rez-Castillo, Eds., [37] D.B.Effendietal.,“Plume,”https://github.com/plume-oss/plume. 2020. [38] C.Banse,I.Kunz,A.Schneider,andK.Weiss,“Cloudpropertygraph: [14] C. A. Pe´rez-Delgado and H. G. Perez-Gonzalez, “Towards a quantum Connecting cloud security assessments with static code analysis,” in software modeling language,” in Proceedings of the IEEE/ACM 42nd IEEEInternationalConferenceonCloudComputing,2021. InternationalConferenceonSoftwareEngineeringWorkshops,2020. [39] F.A.Kassar,G.Clerici,L.Compagna,F.Yamaguchi,andD.Balzarotti, [15] L. Burgholzer, R. Raymond, I. Sengupta, and R. Wille, “Efficient “Testability tarpits: the impact of code patterns on the security testing construction of functional representations for quantum algorithms,” in of web applications,” in Network and Distributed System Security ReversibleComputation,2021. Symposium(NDSS),2022. [16] C. Moore and J. P. Crutchfield, “Quantum automata and quantum [40] W. Xiaomeng, Z. Tao, W. Runpu, X. Wei, and H. Changyu, “Cpgva: grammars,” Theoretical Computer Science, vol. 237, no. 1, pp. 275– Codepropertygraphbasedvulnerabilityanalysisbydeeplearning,”in 306,2000. InternationalConferenceonAdvancedInfocommTechnology,2018. [17] A. C. Say and A. Yakaryılmaz, Quantum Finite Automata: A Modern [41] F.Yamaguchi,A.Maier,H.Gascon,andK.Rieck,“Automaticinference Introduction. Springer,2014,pp.208–222. ofsearchpatternsfortaint-stylevulnerabilities,”inIEEESymposiumon [18] Y. Tian, T. Feng, M. Luo, S. Zheng, and X. Zhou, “Experimental SecurityandPrivacy(S&P),2015. demonstrationofquantumfiniteautomaton,”npjQuantumInformation, [42] I. Kunz, K. Weiss, A. Schneider, and C. Banse, “Privacy property vol.5,no.1,2019. graph:Towardsautomatedprivacythreatmodelingviastaticgraph-based analysis,”ProceedingsonPrivacyEnhancingTechnologies,vol.2,pp. 171–187,2023.
2308.06932 1 DIVAS: An LLM-based End-to-End Framework for SoC Security Analysis and Policy-based Protection Sudipta Paria, Student Member, IEEE, Aritra Dasgupta, Student Member, IEEE Swarup Bhunia, Senior Member, IEEE Department of Electrical and Computer Engineering, University of Florida, Gainesville, Florida Abstract—Securing critical assets in a bus-based System-On-Chip (SoC) is imperative to mitigate po- tentialvulnerabilitiesandpreventunauthorizedaccess, ensuring the system’s integrity, availability, and confi- dentiality. Ensuring security throughout the SoC de- sign process is a formidable task owing to the inherent intricacies in SoC designs and the dispersion of assets across diverse IPs. Large Language Models (LLMs), exemplifiedbyOpenAI’sChatGPTandGoogleBARD, have showcased remarkable proficiency across various domains,includingsecurityvulnerabilitydetectionand prevention in SoC designs. In this work, we propose DIVAS, a novel framework that leverages the knowl- edge base of LLMs to identify security vulnerabilities from user-defined SoC specifications, map them to the relevant Common Weakness Enumerations (CWEs), followed by the generation of equivalent assertions, Fig. 1: A model SoC framework with Trusted and Un- and employ security measures through enforcement of trusted IPs and their interactions. security policies. The proposed framework is imple- mented using multiple ChatGPT and BARD models, and their performance was analyzed while generating automationframeworkstoidentifysecurityvulnerabilities relevant CWEs from the SoC specifications provided. and enforce security requirements. Fixing vulnerabilities The experimental results obtained from open-source SoC benchmarks demonstrate the efficacy of our pro- in the later stages of the design flow can be extremely posed framework. difficult and expensive. In recent years, the collaborative endeavors of the IndexTerms—SoCSecurity,SecurityPolicies,Asser- tion Based Verification, CWEs, ChatGPT, BARD semiconductor industry have introduced hardware-related concerns to the list of Common Weakness Enumera- tions (CWEs) maintained by the MITRE Corporation I. Introduction [1]. CWEs serve as a “common language” for identifying A bus-based System-On-Chip(SoC) integrates multiple and mapping vulnerabilities. Identifying distinct vulnera- functional components into a single chip and utilizes a bilities necessitates varying degrees of understanding re- common bus to facilitate communication between these garding design, secure assets, the threat model, security components. The globalization of the IC supply chain has requirements, etc. [2], [3]. The existing approaches pri- forced the semiconductor industry to adopt a Zero Trust marilyinvolvemanualassessmentofthehardwaredescrip- model for security. Under this model, malicious entities tion language (HDL) code which heavily relies on human can exploit the vulnerabilities at any stage of the design expertise and experience that might not be sufficient to flow. Hence, it is essential to incorporate preventive mea- discover all potential vulnerabilities. Latest works on bug surestoprotectthesecureassetsinanSoCfrompotential fixinginhardwaredesignsinvolvegenericrepairtemplates threats. Fig. 1 depicts an illustrative example using a [4], [5], using static analysis and security-related feedback model SoC to emphasize the importance and criticality [6], Genetic Programming [7], and Large Language Mod- of secure information and authorized access to assets of els (LLMs) [8], [9]. However, the current methodologies theSoC.Securitypoliciesofferactionablespecificationsfor are limited to hardware designs, mainly covering specific SoC designers, architects, and security experts by instan- vulnerabilities but not explicitly addressing security re- tiating Confidentiality, Integrity, and Availability (CIA) quirements for generic bus-based SoC designs. requirements for certain assets. The growing intricacy of Inthispaper,weproposeDIVAS,anLLM-basedend-to- SoC designs has made it challenging for developers to end framework for SoC security analysis and policy-based identify and fix vulnerabilities in complex SoC designs. protection.DIVASleveragestheabilityofLLMstoidentify Despite considerable efforts to ensure functional accuracy the CWEs for a given SoC specification and employs in hardware designs, there needs to be more focus on a novel LLM-based filtering technique to determine the 3202 guA 41 ]RC.sc[ 1v23960.8032:viXra2 relevantCWEs,whicharethenconvertedintoSystemVer- sensitive and confidential data, such as personal infor- ilog Assertions (SVAs) using LLMs for verification. The mation, financial data, and medical records. Therefore, proposed methodology generates 3-tuple security policies securing SoC assets is crucial to protect sensitive data, from these SVAs using DiSPEL [10], an automated tool prevent unauthorized access, theft, or manipulation, and flow to parse the security policies and generate RTL ensure the reliable operation of the system. It involves code for enforcing policies. The DiSPEL tool enforces implementing security mechanisms and protocols that thesepoliciesthroughacentralizedsecuritymoduleacross can detect and prevent security threats, limit the access the bus interconnect for bus-level security policies or by of untrusted entities, and provide secure communication appending the RTL code block in the top-level wrapper channels between different system components. that interacts with the bus interface for IP-level security policies.DIVASprovidesanautomatedframeworkthatcan B. Common Weakness Enumerations take user specifications for any generic SoC, identify rel- evant CWEs using LLMs, generate SVAs for verification, ThelistofCWEsfromMITRECorporation[1]provides
createcorrespondingsecuritypolicies,andincorporatethe acollectionofcommonsoftwareandhardwareweaknesses translated policies through a security module or wrapper. that may cause potential security vulnerabilities main- The proposed DIVAS framework is illustrated in Fig. 2. tained by the CWE community. A software, firmware, In summary, this paper presents the following contribu- or hardware design bug is considered a “weakness” if it tions: can be exploited under any circumstances. The CWEs andassociatedclassification taxonomyserveasa common • Anautomationframeworkforgeneratingqueriesfrom language that can be used to identify and describe these user-given specifications and security requirements to weaknesses in terms of CWEs. These weaknesses can be identify CWEs by leveraging the LLM knowledge recognized and discussed in terms of CWEs using the base. CWE-ID and its related classification taxonomy. The list • Curating an extensive list of CWEs with different ofCWEsiswidelyadoptedintheindustryforverification classificationsforbus-levelandIP-levelvulnerabilities purposes to ensure the design is resistant to common vul- and incorporating a filtering methodology to retain nerabilities. The current industry practices involve expe- only relevant CWEs for a given SoC context. rienced security experts responsible for testing the design • Analyzing and correcting SVAs generated by LLMs against the most common CWEs for the respective IPs. foremploying simulation-basedvalidation andformal The most commonly adopted verification methodologies verification. are:(i)assertion-basedvalidationsand(ii)writingsecurity • Converting SVAs to respective security policies in a properties or policies. Both of these methodologies rely 3-tupleformatrepresentationandemployingDiSPEL on the expertise and manual efforts of the security expert tool for enforcing security policies through a central- personnel. izedsecuritymoduleorbus-levelwrapperasrequired. Assertion-BasedValidation(ABV)iswidelyusedinthe The remainder of this paper is organized as follows: industryforfunctionalverificationinbus-basedSoCs.As- Section II provides the relevant background and describes sertions are condition-based validation checks to identify the motivation behind our work. Section III outlines the any particular event occurrence and generate appropriate overall flow of our proposed framework with a brief de- warningsormessagesiftheconditionismet.Forexample, scriptionofeachstage.SectionIVcontainstheexperimen- we can think of an assertion that verifies the output of an tal results and analysis. Lastly, we conclude and provide adder is always equal to the sum of its input or not. In future directions in Section V. addition to functional validation, assertions are required to detect security vulnerabilities in SoCs. Such security II. Background assertions are intended to identify any deviation from A. Security Requirements in Bus-based SoC the security specifications for a given SoC and identify A bus-based SoC refers to a type of SoC architecture potential vulnerabilities which may lead to future attacks where the different components of the SoC are connected if not fixed. Once the vulnerability is identified for an IP via a bus interconnect. The bus interconnect provides a in the SoC under test, the immediate next step would be communication channel between different IP cores, mem- fixing the respective IP module. Simulation-based valida- ory blocks, and peripheral devices of the SoC. Bus-based tion and formal verification methods can help identify the SoCs are complex systems that contain multiple IP cores vulnerabilities in the system design by activating asser- from different vendors. These IP cores may have differ- tions. However, such methodologies are insufficient due to ent levels of security and trustworthiness, making them limited scope, lack of scalability, and design complexity, vulnerable to attacks. Integrating these IP cores in the which originates the need to incorporate security policies SoCcancreatenewsecurityvulnerabilities,whichneedto through which the security requirements are represented be identified and mitigated to ensure the system’s overall formally. security. SoCs are used in various applications, including A security policy for a SoC is a set of guidelines, rules, mobile devices, wearables, smart homes, medical devices, and procedures that define the security requirements and automotive systems. These applications often handle and protection mechanisms for the SoC. The security3 Fig. 2: DIVAS: Overview of the proposed framework. policy aims to ensure the SoC’s confidentiality, integrity, 1) CommonCWE(s)inHardware: Variouscommercial availability, and data and functionality. The security and community tools offer static analysis for HDL to policy should address various aspects of SoC design, detect errors and bugs. However, they offer limited capa- including hardware, software, and communication bility since these tools primarily focus on functional and interfaces. As part of the design process, most SoC design structural checks only [12], and they do not address the specifications include security policies that define access issue of design security that may be functionally correct constraints to the sensitive data or assets that must butinsecure.Thesearchspaceforexploringpotentialvul- be protected. The policies are defined across multiple nerabilities for any SoC design with multiple IPs is huge, design planning and development stages and then consideringthecomplexdesign,limitedaccess,interaction updated or distilled across development and validation between components, and other constraints. This initiates stages. However, the process of identifying relevant a requirement for a standardized way of identifying and vulnerabilities, defining security requirements through describingrelevantsecurityconcernsfromthedesignspec- policies, and subsequent enforcement remains exceedingly ifications for an SoC design. The introduction of CWEs
intricate and predominantly reliant on manual efforts in has helped to standardize and simplify the process of current practices. identifyingandmitigatingsecurityvulnerabilitiesinSoCs. CWEs are widely adopted by security researchers and Example of Security Policy system developers to identify and classify different types The SoC model depicted in Fig. 1 consists of a Master of security vulnerabilities or weaknesses in H/W designs IP (the processor core) and several 3rd party Slave IPs and deploy necessary countermeasures. like the crypto, DSP, and memory, as well as peripheral The following CWEs are examples of some well-known IPs for external communication through SPI. The SoC is security vulnerabilities for any bus-based SoC: designed to function in a way that restricts access to the secure memory address of on-chip RAM to only trusted • CWE-284: Improper Access Control refers to a weakness where a system does not properly restrict IPs. The crypto IP reads the plaintext, encrypts it using access to its resources or operations. In the context stored keys, and then stores the ciphertext in a trusted of a bus-based SoC security, this can manifest as memory region that other trusted IPs can access. inadequateprotectionofaccesstosensitiveresources, A security policy can be implemented to achieve access such as memory regions or peripherals, when using a control by limiting the access of the bus by untrusted shared bus for communication between components IPs to prevent the unauthorized disclosure of private keys within the SoC. while in transit from memory to crypto IP. Considering the SoC uses AXI4 bus protocol, the bus signals are • CWE-522: Insufficiently Protected Credentials refer representedasaw addr,whichcontainstheaddresswhere to a weakness where a system does not adequately the data is to be written, and w data, which contains protect sensitive data, such as passwords, crypto- graphic keys, or other authentication information. In the data to be written. The security requirement can be thecontextofabus-basedSoCsecurity,thiscanman- achievedbyrestrictingthebusaccessfortheuntrustedIP ifest as inadequate protection or handling of sensitive whilesensitivedataistransmittedthroughthesharedbus. data within the SoC during storage, processing, or Listing 1 depicts how to implement this security policy transmission over the bus. using a centralized security module. • CWE-1245: Improper Finite State Machines if(slave[‘Crypto’].aw_addr >= 32’h93000014 (FSMs) in Hardware Logic refers to a weakness && slave[‘Crypto’].aw_addr <= 32’h93000028) { where an incomplete or incorrect implementation slave[‘SPI’].w_data = 32’h0; of FSMs allows an attacker to put the system in } an undefined state. In the context of a bus-based Listing 1: Security Policy Example SoC security, this can manifest as an inadequate4 TABLE I: Comparison of DIVASwith existing solutions Applicable Uses Mapping Supportfor Generates Performs ProposedSolutions toSoCs? LLMs? toCWEs? GenericSoCs? Assertions? CodeFix? CirFix[7] ✗ ✗ ✗ ✗ ✗ ✓ Don’tCWEATIt[6] ✗ ✗ ✓ ✗ ✗ ✓ Chip-Chat[11] ✗ ✓ ✗ ✗ ✗ ✗ B.Ahmadetal.[8] ✓ ✓ ✓ ✗ ✗ ✓ R.Kandeetal.[9] ✓ ✓ ✓ ✗ ✓ ✗ DIVAS* ✓ ✓ ✓ ✓ ✓ ✓ *currentwork error-detection mechanism that allows the attacker million words of public dialog data and web text, though to cause a Denial of Service (DoS) or gain privileges Google didn’t officially disclose the exact numbers. Unlike on the victim’s system. ChatGPT, BARD can pull from the data available on • CWE-1231: Improper Prevention of Lock Bit Mod- the internet today. While both are built on Transformers ification refers to a weakness where the system does with billions of parameters to fine-tune the model and not prevent the value of the lock bit from being overlappingtrainingdatasources,theirperformancevaries modifiedafterithasbeenset.Inthecontextofabus- withusecases,andbothhavetheirownsetoflimitations. based SoC security, this can manifest as inadequate 2) UsingLLMsforSecurityAutomation: Theresponses protection on a trusted lock bit for restricting access and the capability of articulating answers to different to registers, address regions, or other resources. queries by ChatGPT and BARD were very promising and impressively detailed, even though they lack factual accu- C. Large Language Models racyinmanydomainsandhavealimitedknowledgebase. The development of AI has led to many breakthroughs We have also explored the capability of ChatGPT and in Natural Language Processing (NLP), which the indus- BARD models to produce factual answering to domain- try has widely adopted due to the increasing demand for specific queries related to SoC security. The main goal conversational models. Over the years, LLMs have con- is to identify or map the user-given design specifications sistentlyshowcasedimpressiveperformanceacrossvarious and security requirements to the existing list of CWEs NLP tasks. Pre-trained transformer models have shown available on the web using the knowledge base of LLMs remarkable efficacy in identifying relevant bugs or vulner- like ChatGPT and BARD. We have comprehensively an- abilities from informal or unstructured natural language alyzed the performance of ChatGPT and BARD models descriptions. The evolution in LLMs is evident in the under various attack models prevalent in the SoC security continuous evolution of highly capable models like BERT literature.Thisincludesbutisnotlimitedtobus-basedat- (Bidirectional Encoder Representations from Transform- tacks, side-channel attacks, timing attacks, access control ers) [13], GPT-2 (Generative Pre-trained Transformer violations, etc. 2) [14], GPT-3 (Generative Pre-trained Transformer 3) D. Related Works [15],RoBERTa(ARobustlyOptimizedBERTPretraining
Approach) [16], etc. to name a few. In this work, we Various techniques can bolster the security of hardware have explored the two most popular competing LLMs: designs, like adopting a Security Development Lifecycle ChatGPT by OpenAI [17] and BARD by Google [18]. (SDL) that operates concurrently with the standard de- 1) Conversational LLMs: ChatGPT is a well-known velopment procedure. The SDL involves several stages, AI chatbot developed by OpenAI, which is built on top starting from ‘planning’, where security requirements are of LLMs and fine-tuned using both supervised and re- determined, to ‘architecture’ and ‘design’, where relevant inforcement learning techniques. ChatGPT was launched threatmodelsareconsidered.Thedesignisreviewedusing as a prototype in Nov 2022 and generated huge interest security threat models in the ‘implementation’ and ‘verifi- and attention worldwide due to its performance across cation’stages,withmanualchecksandstaticcodeanalysis manyknowledgedomains.Itisatransformer-basedneural in the ‘implementation’ phase. The bulk of validation network pre-trained with over 175 billion parameters and is carried out through security properties expressed as huge quantities of text data until Sep 2021. It makes it assertionsinHDLsduringthe‘verification’stage.Physical capable of inferring relationships between words within testing is conducted after the fabrication to identify any the text and generating context-sensitive responses. On vulnerabilities that may still be present. thecontrary,BARDisbuiltonPathwaysLanguageModel Severaltechniqueshavebeenproposedforsecurityanal- 2 (PaLM 2), a language model released in late 2022 ysis across the SDL, such as Formal Verification [19]–[22] preceded by LaMDA, which is short for Language Model , Information Flow Tracking [23]–[26] , Fuzz Testing [27]– for Dialogue Applications. These language models were [29] , and Run-time Detection [30]–[32]. Previous work on built by fine-tuning a family of Transformer-based neural security analysis using assertion-based verification [33]– language models, an open-source neural network architec- [36] focused on specific SoC designs. These techniques ture originally developed by Google. BARD is believed are either simulation-based or operate in the field with to have been trained on 137 billion parameters and 1.56 complete or near-complete designs. The identification and5 deploymentofnecessaryfixesmustbemadeearlier(during the ‘implementation’ and ‘verification’ phases) to prevent them from propagating to the following stages. Generic code repair templates are available for fixing bugs in hardware designs [4], [5]. CirFix [7] was proposed as a framework for automatically repairing defects in hardware designs using Genetic Programming. Ahmad et al. [6] explored the CWEs related to H/W designs and provided security-related feedback using static analysis to identify security bugs at the early stage of develop- ment. In the realm of software bug fixes, the software domain delves into the utilization of machine learning- driven methods like Neural Machine Translation [37] and pre-trainedtransformers[37].Pearceetal.[38]employeda similar strategy to rectify instances of security vulnerabil- ities in Verilog code, successfully addressing two distinct scenarios.Ahmadetal.[8]devisedaframeworkforrepair- ing specific hardware security bugs using OpenAI Codex andCodeGenLLMs.Kandeetal.[9]developedaprompt- basedassertiongenerationframeworkusingLLMsforaset ofSoCbenchmarksbutlimitedtoonlythegenerationand correctness evaluation of assertions for a fixed set of SoC benchmarks. Existing techniques are mostly restricted to specific SoC benchmarks and do not fully automate the identification of the relevant vulnerabilities in terms of CWEs and fixing them. Table I provides a comprehensive overview of the existing solutions and demonstrates the necessity of our proposed framework. III. Methodology/Proposed Framework In this section, we describe the main components of the Fig. 3: DIVAS: Flow diagram. DIVAS framework, starting from the design specifications of the SoC under test, followed by the generation & verification of security assertions and enforcing security a JSON file which serves as the design specifications for requirementsthroughtheimplementationofsynthesizable the SoC under test. The automated flow will parse the Verilog code. The overall flow has been depicted in Fig. 3. JSONfileandgeneratequerysentencesusingtheavailable The proposed framework can be categorized into four ma- informationabouttheSoCunderconsideration.Thequery jor stages: (I) Design Specification & Query Generation, will also include assumptions provided by the user, if any. (II)CWEMappingusingLLMs&Filtering,(III)Security The current implementation can generate relevant queries AssertionCreation&Verification,and(IV)Translationto for the IPs available in any bus-based SoC design. The Security Policy & Policy Enforcement using RTL. We will queriesarethenfedintoLLMssuchasChatGPTorBARD now discuss each of these stages in detail. for further steps. A. Design Specification & Query Generation B. CWE Mapping using LLMs & Filtering This marks the initial stage necessitating user engage- Theproposedframeworkleveragescontext-sensitivefac- ment, succeeded by the automated generation of queries tual answering capabilities of LLM, such as ChatGPT or pertinent to the SoC under test. The SoC specifica- BARD, to identify the most relevant CWE for the SoC tions are formally presented in a manner that enables under test. The performance of ChatGPT and BARD DIVAS to tokenize distinct details concerning IPs, bus- in identifying the relevant CWEs solely depends on the level configuration, and the overall SoC, facilitating the context created by some specific words or tokens in generation of corresponding queries. We have prepared a queries generated from the design specifications and user
survey template in the form of a list of common questions responses. We observed that the list of CWEs generated related to available open-source SoCs for better usabil- by ChatGPT and BARD varies with the user’s design ity and easement for a user who may or may not be specifications and assumptions. Table II tabulates CWEs knowledgeable about the exact security requirements or generated by ChatGPT and BARD for different attack common vulnerabilities. The user responses are recorded models. Evidently, the responses from LLMs vary with and translated into a pre-defined format represented in input queries at different time instances, which might be6 TABLE II: List of CWEs generated by ChatGPT and BARD under various threat models AttackAssumptions CWEsgeneratedbyChatGPT CWEsgeneratedbyBARD CWE-506:Timing-basedinformationdisclosure CWE-713: Information Exposure Through Tim- CWE-120:BufferCopywithoutCheckingSizeof ing Channels: Microarchitectural Data Sampling Input(’ClassicBufferOverflow’) (MDS) CWE-121:Stack-basedBufferOverflow CWE-905: Information Exposure Through Tim- Bus-BasedAttacks CWE-125:Out-of-boundsRead ingChannels:BranchPrediction CWE-134: Use of Externally-Controlled Format CWE-135: Sensitive Data Exposure Through String TimingChannels CWE-352:Cross-SiteRequestForgery(CSRF) CWE-196:PowerAnalysisAttack(DataorCon- trolFlow) CWE-126: Time-of-check/time-of-use CWE-319: Cleartext Transmission of Sensitive (TOCTOU)racecondition Information CWE-135: Sensitive Data Exposure Through CWE-311:MissingEncryptionofSensitiveData TimingChannels Side-ChannelAttacks CWE-200:InformationExposure CWE-196:PowerAnalysisAttack(DataorCon- CWE-327: Use of a Broken or Risky Crypto- trolFlow) graphicAlgorithm CWE-327:CacheTimingAttack CWE-769:InefficientAlgorithm CWE-320:Informationexposurethroughtiming CWE-135: Sensitive Data Exposure Through TimingChannels CWE-200:InformationExposure CWE-327:CacheTimingAttack CWE-208:ObservableTimingDiscrepancy CWE-506:Timing-basedinformationdisclosure CWE-710: Improper Adherence to Coding Stan- TimingAttacks CWE-713: Information Exposure Through Tim- dards ing Channels: Microarchitectural Data Sampling CWE-751:ImproperUseofPlatformTimer (MDS) CWE-613:InsufficientSessionExpiration CWE-905: Information Exposure Through Tim- ingChannels:BranchPrediction CWE-400: Uncontrolled Resource Consumption CWE-321: Resource Consumption (CPU Time, (’ResourceExhaustion’)-IPLevel Memory,DiskSpace) CWE-494: Download of Code Without Integrity CWE-509:InsufficientBoundaryChecking Check DoSAttacks CWE-601:BufferOverrun CWE-613:InsufficientSessionExpiration CWE-704:ImproperSynchronization CWE-400: Uncontrolled Resource Consumption CWE-754:ImproperValidationofCryptographic (’ResourceExhaustion’)-BusLevel Inputs CWE-693:ProtectionMechanismFailure CWE-119:Improperinputvalidation CWE-200:InformationExposure CWE-125:Bufferoverflow CWE-311:MissingEncryptionofSensitiveData CWE-200: Information Exposure Through Im- CWE-327: Use of a Broken or Risky Crypto- ConfidentialityAttacks properErrorHandling graphicAlgorithm CWE-201: Information Exposure Through CWE-200:InformationExposure SharedResources CWE-310:CryptographicIssues CWE-284:ImproperAccessControl CWE-285:ImproperAuthorization CWE-306: Missing Authentication for Critical Function CWE-284:ImproperAccessControl CWE-732: Insecure Permission Assignment for CWE-805:SecurityFeaturesBypass AccessControl CriticalResource CWE-895:InsufficientlyProtectedCredentials CWE-250: Execution with Unnecessary Privi- CWE-918:TrustBoundaryViolation leges CWE-928:InsufficientlyProtectedCryptography CWE-724: OWASP Top Ten 2017 Category A6: SecurityMisconfiguration irrelevant and unreliable at times. In addition to that, ing requirements, positioning conditions, and the type bothChatGPTandBARDalsoenlistsomeCWEsrelated of weakness. Table III represents a partial snapshot of to software-level vulnerabilities, which are not directly the Extensive DB with different CWEs and respective related to bus-based SoC design due to the limited knowl- classifications. edge base and training in this particular domain. Hence, Let us first describe the notations used in the algorith- it is required to employ a filtering technique to identify mic steps for better understanding. only the relevant CWEs from the list of CWEs generated by LLMs so that the appropriate security assertions and • SoC Configuration is represented as: S ={IP ,IP ,...IP } necessary logic for ensuring security can be deployed. 1 2 q IP = {NAME, DESC, OP, BASE, RANGE, We have prepared an extensive list of CWEs, referred i PROC ADD R} as Extensive DB (Λ), that will be used in the filtering process. This database has been prepared after rigorously • Extensive DB, denoted by Λ, where, Λ={Λ ,Λ ,...Λ } and analyzing different SoC configurations and the common 1 2 p Λ = < CWE ID, DESC, BUS, IP, SYNC, TYPE, list of H/W and SoC level vulnerabilities available at i MISC > [1]. The classifications have been done in terms of tim- • List of CWEs from LLM Responses, denoted by Ω7 TABLE III: A snapshot of the Extensive DB of CWEs used in DIVAS CWE# BugDescription Classification TimingRequirements TypeofViolation CWE-119 ImproperRestrictionofOperationswithin Bus+IPLevel Asynchronous AccessControl theBoundsofaMemoryBuffer
CWE-120 BufferCopywithoutCheckingSizeofIn- N/A N/A InadequateErrorHandling put(’ClassicBufferOverflow’) CWE-121 Stack-basedBufferOverflow N/A N/A InadequateErrorHandling CWE-125 Out-of-boundsRead Bus+IPLevel Asynchronous InadequateErrorHandling CWE-1059 InsufficientTechnicalDocumentation N/A N/A InadequateErrorHandling CWE-131 IncorrectCalculationofBufferSize N/A N/A InadequateErrorHandling CWE-1390 WeakAuthentication Bus+IPLevel Synchronous AccessControl CWE-1391 UseofWeakCredentials IPLevel Synchronous AccessControl CWE-190 IntegerOverfloworWraparound N/A N/A InadequateErrorHandling CWE-20 ImproperInputValidation IPLevel Synchronous InadequateErrorHandling CWE-200 Exposure of Sensitive Information to an Bus+IPLevel Synchronous InformationFlow UnauthorizedActor CWE-226 SensitiveInformationinResourceNotRe- Bus+IPLevel Synchronous TOCTOU movedBeforeReuse CWE-284 ImproperAccessControl Bus+IPLevel Synchronous AccessControl CWE-285 ImproperAuthorization Bus+IPLevel Synchronous AccessControl CWE-287 ImproperAuthentication Bus+IPLevel Synchronous AccessControl CWE-310 CryptographicIssues IPLevel Synchronous InformationFlow CWE-325 MissingRequiredCryptographicStep IPLevel Asynchronous InformationFlow CWE-326 InadequateEncryptionStrength IPLevel Asynchronous InformationFlow CWE-327 Use of a Broken or Risky Cryptographic IPLevel Asynchronous InformationFlow Algorithm CWE-330 UseofInsufficientlyRandomValues IPLevel Asynchronous InformationFlow CWE-362 Concurrent Execution using Shared Re- BusLevel Synchronous Liveness sourcewithImproperSynchronization CWE-367 Time-of-check Time-of-use (TOCTOU) Bus+IPLevel Synchronous TOCTOU RaceCondition CWE-522 InsufficientlyProtectedCredentials Bus+IPLevel Asynchronous AccessControl CWE-665 ImproperInitialization Bus+IPLevel Asynchronous InformationFlow CWE-667 ImproperLocking Bus+IPLevel Synchronous InformationFlow CWE-787 Out-of-boundsWrite Bus+IPLevel Asynchronous InadequateErrorHandling CWE-798 UseofHard-codedCredentials Bus+IPLevel Synchronous InformationFlow CWE-862 MissingAuthorization Bus+IPLevel Asynchronous AccessControl CWE-863 IncorrectAuthorization Bus+IPLevel Asynchronous AccessControl where, Ω={Ω ,Ω ,...Ω } sification details for a particular CWE from the Extensive 1 2 n • Filtered List of CWEs, denoted by ω DB and mapping to the respective type based on the where, ω ={ω ,ω ,...ω } values.AlltherelevantCWEs,whetherbus-level,IP-level, 1 2 k Algorithm 1 describes the steps of the filtering method or both, are appended to the filtered list ω. for identifying only the relevant CWEs ω from the LLM- C. Security Assertion Creation & Verification generated response Ω. Filtering evaluates the relevance of each CWE for the given SoC context based on the After acquiring the list of relevant CWEs, DIVAS initi- data available in the Extensive DB (Λ). The Extensive atesthecreationofsecurityassertionstoascertainwhether DB, comprising about 180 CWEs and respective classifi- the existing SoC implementation is susceptible to these cations,hasbeenpreparedafterbroadlystudyingdifferent particular vulnerabilities. This step holds significant im- CWEs classified under Common Hardware Design Bugs portance,giventhatcertainvulnerabilitieshavethepoten- (CWEVIEW:H/WDesign(CWE-1194)).TheCWEsare tial to result in potential attacks and subsequently breach matched using the ID value or the description text. We the CIA properties of a system. Assertion-based verifica- usedsemanticcontextmatchingutilizingCosineSimilarity tion is widely popular in SoC design flow for detecting scoresforthedescriptiontexttomaptheCWEdescription anydesignbehaviorthatdeviatesfromthedefinedsecurity texttothemostrelevantentryinExtensiveDB.TableVII requirementsandthusleadstopotentialattacks.SVAsare shows two example description texts and some matching broadly adopted in various phases of the SoC design flow, texts in the Extensive DB with the respective Cosine from specification to verification stages. Security experts Similarityscore.Thetextwiththehighestsimilarityscore or architects are mostly responsible for writing assertions will be selected, and the automated flow will perform manually and verifying the design behavior. In this work, respective mapping for the particular CWE-ID. However, we have explored the capability of both ChatGPT and the current list of CWEs may not be complete. If any BARD to generate SVAs for each of the identified CWEs CWE-ID relevant to H/W or SoC security generated by and the respective IPs of the SoC design. The automated LLMs is not present in Λ, then it can be included using flow involves LLMs for generating initial SVAs and then the automated tool. modifying them using the available design specifications, Algorithm2describestheprocessofextractingtheclas- making it syntactically correct to verify the design under8 Algorithm 1: Filter CWEs Input: List of CWEs from LLM Responses, denoted by Ω Output: Filtered List of CWEs, denoted by ω Data: Extensive DB, denoted by Λ 1 while Ω is not Empty do 2 Parse Ω i ∈Ω 3 Search Ω i in Λ 4 if Ω i.ID ==Λ j.CWE ID then 5 Fetch Λ j.BUS,Λ j.IP,Λ j.TYPE 6 Map CWE(Ω i,Λ j,S.IP,ω) (a) ChatGPT (b) BARD 7 else if Fig. 4: Generalized Assertion Templates. Cosine Sim(Ω .DESC,Λ .DESC)>0.75 i j then 8 Fetch Λ j.CWE ID,Λ j.BUS,Λ j.IP, ing such a well-formatted template for assertions. BARD 9 Λ j.TYPE attempts to utilize UVM-based packages and functions
10 Update Ω i.ID =Λ j.CWE ID by extending a class from a superclass which is more 11 Map CWE(Ω i,Λ j,S.IP,ω) specifictotheSoCdesignarchitectureandhaslimitations in terms of extensibility and usability. Hence, we opted 12 else for the template as depicted in Fig. 4(a), which utilizes 13 Generate Query for LLMs: the property block to define the condition and assert the 14 ‘Is <Ω i.ID,Ω i.DESC > relevant for propertyforverificationpurposes.Wehavetabulatedsome bus-based Soc with <SoC Config >’ example CWEs inferring to different types of Security 15 if is relevant(response) then Policies and their respective SVA with proper templates 16 Λ.append(Ω i) in Table IV. 17 ω.append(Ω i) The SVAs are verifiable in the pre-silicon testing through testbenches to identify any deviation from the 18 return ω securityrequirementsthatmightleadtopotentialattacks. Suppose any assertion is evaluated to be true during Algorithm 2: Map CWEs simulation using open-source or commercial simulation 1 Function Map CWE(Ω i,Λ j,IP,ω): tools,suchasSynopsysVCS,ModelSim,etc.Inthatcase, 2 if Λ j.BUS ==‘YES’ then there is a requirement to employ necessary preventive measures through appropriate checks and assignment of 3 if Ω i.ID ∈/ ω then signal values as required. 4 ω.append(Ω i) 5 if Λ j.IP ==‘YES’ then D. Translation to Security Policy & Policy Enforcement 6 if Λ j.MISC.IP NAME ∈ Each assertion that is found to be activated during the IP .NAME,∀k,k ∈[1,q] then k simulation indicates the presence of respective vulnerabil- 7 if Ω i.ID ∈/ ω then ities in the SoC design. We have employed an automated 8 ω.append(Ω i) translationfromassertiontocorrespondingsecuritypolicy 9 if Λ j.MISC.IP TYPE ∈IP k.OP,∀k,k ∈ for representing the security requirements formally. Each [1,q] then securitypolicyisexpressedina3-tuple<predicate,timing, 10 if Ω i.ID ∈/ ω then action> format. The assertions are formed to check a 11 ω.append(Ω i) specific event, represented in the ‘property...endproperty’ block, which can either be a sequence of events or a 12 return ω static condition-based check. For sequential events, the number of clock cycles between the events is included in the security policy accordingly, while Boolean expression canbeusedforfixedconditionalchecks.DIVASisdesigned test. All the assertions are generated and appended to toaccommodatebothscenarioswhilegeneratingthe‘pred- the respective IP module, followed by verification through icate’ofasecuritypolicy.Additionally,aseparateclocking simulation using standard simulators e.g. Synopsys VCS. block could be present in the assertion to fulfill specific Fig. 4 depicts the generalized structure of an assertion requirements of ‘clock’ or ‘reset’ values. The automated created by ChatGPT and BARD, respectively. As evident flow includes these values in the ‘timing’ section of the from the figures, ChatGPT consistently tries to create security policy and any additional clock cycle require- a module with property with the underlying condition ments. It also appends the operating mode represented for the assertion, while BARD is inconsistent in generat- usinganintegervalue(e.g.,forusermode:0,debugmode:9 TABLE IV: Examples of CWEs and SVAs for Different Types of Security Policies along with the Bug Description Type CWE-ID BugDescription SystemVerilogAssertion propertyp out of bounds read; @(posedge(clk i))$rose(start)|−> (wb adr i>=32′h93000004&&wb adr i <=32′h93000008); AccessControl CWE-125 Out-of-boundsRead endproperty a out of bounds read: assertproperty(p out of bounds read) else$display(“Out-of-boundsAccess!”); propertyp broken algo; @(posedge(clk i))$rose(start)&&key== UseofaBrokenorRisky 32′hABCD1234; InformationFlow CWE-327 CryptographicAlgorithm endproperty a broken algo:assertproperty(p broken algo) else$error(“Keyhasbeenleftatadefaultvalue.”); propertyp sensitive register clear; @(posedge(clk i))(release&&!rst i) SensitiveInformationinResource |−>(sensitive register===32’b0); Liveness CWE-226 endproperty NotRemovedBeforeReuse a sensitive register clear: assertproperty(p sensitive register clear) else$error(“Violationofsensitiveregisterclearrule”); propertyp no race condition; @(posedge(clk i))(!rst i)|−> ConcurrentExecutionusing !(Slave A access&&Slave B access); TOCTOU CWE-362 SharedResourcewithImproper endproperty Synchronization(‘RaceCondition’) a no race condition: assertproperty(p no race condition) else$error(“Violationofnoraceconditionrule”); 1, etc.) in the ‘timing’ tuple if available. The ‘action’ can security module, whereas the IP-level security policies be customized based on security requirements for the SoC are appended in each IP module’s respective top mod- design. The automated flow is designed to parse the user ule wrapper. The updated code with policy enforcement responses and includes the respective action represented logic can be synthesized using any industry standard tool using the assignment of required values for observable package to generate a gate-level netlist. We have also signals. Algorithm 3 includes all the steps for translating employedfunctionalverificationusingsimulationtoverify eachassertiontotherespectiveSecurityPolicyrepresented the correctness of each IP module before and after the in a formal 3-tuple format. inclusion of security policies. Fig. 5 depicts the conversion
from SVA to the respective security policy represented in The automated translation from security policy to Ver- a 3-tuple format followed by the automatic generation of ilog code through DiSPEL framework [10] has been in- RTL code for policy enforcement using DiSPEL tool [10]. tegrated with this workflow for incorporating policy en- IV. Experimental Results forcement in the SoC under consideration. The policies are converted to equivalent Boolean expressions with con- This section describes the experimental setup and anal- ditionalstatements,andtheassignmentofrequiredvalues ysisoftheobtainedresultsforevaluatingtheperformance is defined inside the respective conditional blocks. The of the proposed framework. We have opted for the open- bus-level policies are incorporated through a centralized sourceCommonEvaluationFramework(CEP)benchmark Fig. 5: Conversion of SystemVerilog Assertion to Security Policy followed by Policy Enforcement.10 Algorithm 3: Assertion to Security Policy Fig.6illustratesabus-basedSoCarchitectureconsisting Input: Set of Assertions, denoted by Υ of Master IP, Main Memory, Crypto IPs, DSP IPs, and where, Υ={υ ,υ ,...υ } insecure IPs such as JTAG and UART. The centralized 1 2 n Output: Set of Security Policies, denoted by Φ security policy enforcement module is placed across the where, Φ={ϕ,ϕ ,...ϕ } bus interface where all the IPs communicate with other 2 n 1 for each υ ∈Υ do IPs using the bus while the IP-level security enforcement 2 if υ.clocking block != NULL then logic is realized through a wrapper above the top level 3 ϕ.mode = <υ.clocking block :clock, of each IP. To formalize the design specifications of 4 υ.clocking block :reset> the SoC, we have created a JSON-based template that provides a structured representation of the SoC’s design, 5 else encompassing the overall configuration and IP-level 6 ϕ.mode=0 //default value details. Using this template, we can capture and organize 7 if is sequential(υ.property) then the pertinent information related to the SoC under 8 /* Sequential event */ examination, as depicted in Listing 2. 9 ψ = split(υ.property,|−>) 10 for each ψ i ∈ψ do { 11 τ = fetch cycles(ψ i:Cycles) "SoC": 12 if τ is NULL then { "NAME":"MIT-CEP", 13 τ =1 //default value "TYPE":"Open-source", 14 ψ.predicate.append(ψ i) "USAGE":"Academic Research", "BUS":"AXI4", 15 ψ.predicate.append(## τ ##) "NO_OF_MASTERS":"1", "NO_OF_SLAVES":"11" 16 else }, 17 /* Boolean Expression */ "BUS_INTERFACE": { 18 ψ.predicate = υ.property "INTERFACE_NAME":"Master/Slave", 19 ψ.action = extract action(user input) "NO_OF_PORTS":"17", "SIGNAL_NAMES":"AWVALID,AWADDR,WDATA, 20 return Φ ARREADY,RDATA,..." }, "MASTER_1": { "NAME":"mor1kx", suite from MIT-LL [39] for our experiments. This SoC "TYPE":"OPen RISC-V", "OPERATION":"Processor", benchmark consists of a Mor1kx OpenRISC processor as "ADDRESS_RANGE":"90000000-99000000", the Master IP and several Slave IPs with different func- "BASE_ADDRESS":"90000000", tionalities. The Slave IPs include multiple cryptographic "PROTECTED_ADDRESS_RANGE":"9100001F:9100002D" }, modules, namely AES, DES3, MD5, RSA, and SHA- "SLAVE_1": 256, and several digital signal-processing modules such { as DFT, IDFT, FIR, IIR, and GPS. Additional modules, "NAME":"Advanced Encryption Standard", "ABBREVIATION":"AES", like JTAG, GPIO, UART, etc., are used for external "TYPE":"Open-source", communication with the user that could be an attack "OPERATION":"Crypto", surface to launch an attack and are considered untrusted "ADDRESS_RANGE":"93000000-93FFFFFF", "BASE_ADDRESS":"93000000", IPs. "PROTECTED_ADDRESS_RANGE":"93000014:9300003C" } } Listing 2: SoC Design Specification Example A. Generating CWEs using LLMs Both ChatGPT and BARD are found to be very pow- erful and versatile LLMs due to their advanced archi- tecture, large-scale training data, fine-tuning capabilities, and ongoing research. We have generated context-specific questions from SoC design specifications and explored the capabilities of ChatGPT and BARD models to generate relevantCWEsforagivenSoCdesign.Thefollowingblock depicts an example scenario of generating CWEs for a Fig. 6: The Security Policy Enforcement Wrapper place- given SoC configuration using ChatGPT (GPT-4 model). ment in the SoC architecture.11 TABLE V: Generating CWEs under different assumptions Assumptions LLMResponseundernoassumptions #1 #2 #3 CWE-20:ImproperInputValidation CWE-20 CWE-20 CWE-20 CWE-79:ImproperNeutralizationofInputDuringWebPageGeneration CWE-79 CWE-79 CWE-79 CWE-120:BufferCopywithoutCheckingSizeofInput CWE-120 CWE-120 CWE-120 CWE-125:Out-of-boundsRead CWE-134 CWE-125 CWE-125 CWE-134:UseofExternally-ControlledFormatString CWE-284 CWE-134 CWE-134 CWE-200:ExposureofSensitiveInformationtoanUnauthorizedActor CWE-287 CWE-200 CWE-284 CWE-284:ImproperAccessControl CWE-306 CWE-319 CWE-287 CWE-287:ImproperAuthentication CWE-319 CWE-330 CWE-306 CWE-306:MissingAuthenticationforCriticalFunction CWE-330 CWE-400 CWE-400 CWE-319:CleartextTransmissionofSensitiveInformation CWE-400 CWE-416 CWE-416 CWE-330:UseofInsufficientlyRandomValues CWE-416 CWE-787 CWE-732 CWE-400:UncontrolledResourceConsumption CWE-732 CWE-798 CWE-787 CWE-416:UseAfterFree CWE-798 CWE-798 CWE-732:IncorrectPermissionAssignmentforCriticalResource CWE-862 CWE-862
CWE-787:Out-of-boundsWrite CWE-798:UseofHard-codedCredentials CWE-862:MissingAuthorization Q1: Find the below SoC Configuration: identicalSoCconfigurations.WeobservedthattheCWEs <SoC Config > listedbyagivenLLMgetrefinedbasedontheassumption. Can you generate all possible relevant CWEs for However, this implied that the list of CWEs generated this SoC configuration? underanyassumptionmightnotbecomprehensivedueto the LLM’s limited knowledge base and lack of contextual • CWE-20: Improper Input Validation understanding.Hence,weneedafiltrationstepafterquery • CWE-79: Improper Neutralization of Input generation to identify the relevant CWEs from the list. During Web Page Generation TableVshowsthevariationsinthelistofCWEsgenerated • CWE-89: Improper Neutralization of Special by GPT-4 under different assumption settings: Elements used in an SQL Command • No Assumptions. • CWE-120:BufferCopywithoutCheckingSize • Assumption #1: Bus Transactions are secure. of Input • Assumption#2: ProperAuthentication&Authoriza- • CWE-134: Use of Externally-Controlled For- tions are in place. mat String • Assumption #3: Side Channel Attacks are infeasible. • CWE-190: Integer Overflow or Wraparound • CWE-287: Improper Authentication Limitations of LLMs while identifying CWEs • CWE-306:MissingAuthenticationforCritical During our experiments for generating relevant CWEs Function for a given SoC, we observed that the LLMs have several • CWE-311: Missing Encryption of Sensitive limitations. Some of theselimitations are listedas follows: Data i. Inconsistent Ranking of CWEs. • CWE-319:CleartextTransmissionofSensitive ii. OverlappingresultsfordifferentIPswithsimilarfunc- Information tionality. • CWE-330: Use of Insufficiently Random Val- iii. Incorrect mapping between CWE-ID and the Bug ues description. • CWE-399: Resource Management Errors iv. Generating out-of-context CWEs on multiple occa- • CWE-400: Uncontrolled Resource Consump- sions. tion v. Ambiguity between description and explanation for • CWE-416: Use After Free the same CWE-ID. • CWE-426: Untrusted Search Path vi. Mapping multiple issues to the same CWE-ID. • CWE-601:URLRedirectiontoUntrustedSite vii. Incomplete list of CWEs for any particular configura- • CWE-732: Incorrect Permission Assignment tion under different assumptions. for Critical Resource • CWE-759: Use of a One-Way Hash without a B. Filtering CWEs Salt • CWE-798: Use of Hard-coded Credentials A filtering mechanism is required to identify only rel- • CWE-862: Missing Authorization evant CWEs and discard non-relevant or out-of-context • CWE-918: Server-Side Request Forgery CWEs for a given SoC configuration. The filtering on LLM response helps reduce any bias or ambiguity, main- tain consistency, correctly map CWE-ID to respective de- We have also explored how the LLM response during scriptions, and improve accuracy for better performance. CWE generation can vary under different assumptions for Table VI lists the CWEs obtained from LLM responses12 TABLE VI: Unfiltered vs. Filtered List of CWEs UnfilteredListofCWEs Relevant? FilteredListofRelevantCWEs&Classification CWE-119:ImproperRestrictionofOperationswithinthe BoundsofaMemoryBuffer No {‘CWE-200’,‘InformationExposure’,‘Bus,IP’, CWE-20:ImproperInputValidation No ‘Sync’,‘AccessControl’} CWE-200:InformationExposure Yes {‘CWE-284’,‘ImproperAccessControl’,‘Bus,IP’, CWE-352:Cross-SiteRequestForgery(CSRF) No ‘Async’,‘AccessControl’} CWE-284:ImproperAccessControl Yes {‘CWE-310’,‘CryptographicIssues(e.g.,weak CWE-94:ImproperControlofGenerationofCode algorithmsorinsecureimplementation)’,‘IP’, (’CodeInjection’) No ‘Async’,‘InformationFlow’} CWE-377:InsecureTemporaryFile No {‘CWE-325’,‘MissingRequiredCryptographicStep, CWE-310:CryptographicIssues(e.g.,weakalgorithmsor ‘IP’,‘Async’,‘InformationFlow’} insecureimplementation) Yes {‘CWE-261’,‘WeakCryptographyforPasswords’, CWE-325:MissingRequiredCryptographicStep Yes ‘IP’,‘Async’,‘InformationFlow’} CWE-261:WeakCryptographyforPasswords Yes {‘CWE-362’,‘ConcurrentExecutionusingShared CWE-362:ConcurrentExecutionusingSharedResource ResourcewithImproperSynchronization(‘Race withImproperSynchronization(‘RaceCondition’) Yes Condition’)’,‘Bus’,‘Sync’,‘Liveness’} and the filtered list of relevant CWEs for the MIT-CEP Q2: Can you generate SystemVerilog Assertion for SoC. We quantify the performance of an LLM for a CWE-284 for a bus based SoC which uses AXI4 given SoC configuration by determining the number of bus protocol? relevantCWEsoutofalltheCWEslistedinthegenerated response. The performance metric is calculated for each LLM tested using the DIVAS framework using Equation module improper_access_control_assertion ( input wire clk, 1, and the resulting performance analysis under different input wire rst, assumptions is shown in Fig. 7. input wire [31:0] mid, input wire [31:0] addr ); #CWE Performance= relevant (1) #CWE // Define the clocking and reset total behavior default clocking cb @(posedge clk); default input #1step rst; endclocking // Let’s assume that Master A has an ID of 0, and the secure memory region starts at address 0x80000000 localparam MASTER_A_ID = 32’b0;
localparam SECURE_MEMORY_START_ADDR = 32’h80000000; // Property: Master A should not access the secure memory region property p_improper_access_control; @(cb) (!rst) |-> ((mid === MASTER_A_ID) -> (addr < SECURE_MEMORY_START_ADDR)); endproperty // Assertion: Check that the property Fig. 7: Performance analysis of LLMs in generating rele- holds true throughout the simulation a_improper_access_control: assert vant CWEs for a given SoC configuration. property (p_improper_access_control) else $error("Violation of improper access control rule"); C. Assertion Generation & Correction endmodule We leveraged the capability of LLMs to generate SVAs for a given CWE-ID. The following block illustrates how Limitations of LLMs while generating SVAs to generate the SVA for CWE-284 (Improper Access Control). The SVA generated by ChatGPT checks if a We have thoroughly tested many scenarios to evaluate specific master (Master A) is trying to access a secure theperformanceofbothChatGPTandBARDingenerat- memory region. This example assumes the master can ing SystemVerilog assertions from given CWEs for any IP be accessed using the master ID (‘mid’) and the target in any bus-based SoC. Though it works exceptionally well address using ‘addr’. in generating context-related Verilog and SystemVerilog code for the respective security assertions, it falls short in syntactic correctness and occasionally deviates from the13 TABLE VII: Example Semantic Textual Similarity scores for CWE descriptions DescriptionTextfromLLMResponse DescriptionTextfromExtensiveDB(withScore>0.4) Cosine Similarity CryptographicIssues Score:0.5466 InadequateEncryptionStrength(Weakkeylength) Score:0.5593 WeakCryptographyforPasswords UseofaBrokenorRiskyCryptographicAlgorithm Score:0.4929 UseofHard-codedCredentials Score:0.4371 MissingAuthenticationforCriticalFunction Score:0.4487 MissingRequiredCryptographicStep CryptographicIssues Score:0.5700 UseofaBrokenorRiskyCryptographicAlgorithm Score:0.4147 actual requirements. The generated description text for The assertion mentioned above uses ‘$info’ instead of assertions seems similarly structured, which may be out- ‘$error’ function. of-context for the given query text. We have also found vii. Activatingassertionwiththewrongerrormessagedue thatthegeneratedtextsforsequentiallyrelatedqueriesfor to incorrect conditional statements. thesameIParejustaparaphrasedversionoftheprevious Example: one or sometimes entirely irrelevant in that context. //assertion for CWE-XXX We are listing down some of the common shortcomings assertion_name: assert property (!p_name) based on our observations during the experiment as fol- else $error("CWE-XXX: <Error Message>"); lows: The assertion in the above example generates an i. Generating wrong words which sound similar but are invalid error message due to the wrong construction not valid keywords for SystemVerilog. of the conditional block. Example: ‘bit’, ‘beats’ in place of ‘bits’ ii. Combining Verilog keywords during assertion genera- D. Overhead Analysis after Security Policy Enforcement tion. Example: ‘disable iff’ or ‘disable if’ or ‘disable if’ The IPs were synthesized using the LEDA 250nm (Wrong) standard cell library from Synopsys in Synopsys Design Correct: disable iff Compiler to obtain representative overhead values. Table iii. Using contradicting conditions that may disable the VIII represents the additional overhead incurred in terms assertion during simulation. of area, power, and delay after incorporating security Example: policies in the centralized module and particular IPs. The disable iff(wb_sel_i || wb_we_i || !wb_cyc_i) resultsindicatethattheoverheadsaremostlyminimalun- der default synthesis settings without any constraints. In The value of wb sel i is set as 1’b1 when the cor- somescenarios,theoveralloverheadsarereducedafterre- responding IP is selected, and hence it creates a synthesizing with security policy module implementation contradiction during simulation, and the assertion is due to internal (heuristic-based) optimizations and hence skipped. reported as negligible. Hence, we can conclude that our iv. Missing ‘@’ while generating an assertion that causes proposed methodology of enforcing security requirements a syntax error. throughpoliciesforagenericbus-basedSoCdesignincurs Example: minimal overheads and is practically viable to implement. @(posedge(clk_i)) <condition..> TABLE VIII: Overhead Analysis of Different IPs after @(negedge (rst_i)) <condition..> Security Policy Enforcement v. Invalidorderingofsequentialeventsormissingevents SynthesisOverheads(%) IP #Policies whilegeneratingtheassertionthatskipvalidchecking Area Delay Power AES 5 0.19↑ −3.55↓ 41.57↑ during simulation. DES3 4 8.03↑ −2.05↓ 10.69↑ Example: SHA256 4 2.73↑ 4.39↑ −2.03↓ MD5 3 3.33↑ 8.47↑ −6.63↓ @(posedge(clk_i)) MainMemory 2 −0.021↓ −0.192↓ −0.079↓ $rose(ready && !rst) |-> valid; The above assertion contains an invalid sequence where ‘ready’ is checked before the ‘valid’ signal is E. Discussion set.Theassertionalsoskipsthecheckingonthe‘start’ Identifying the relevant CWEs for a specific SoC con- signal. figuration posed a significant challenge due to the lack of vi. Contrasts while using the system functions like ‘$er- accuracy and contextual listing found in both ChatGPT ror’, ‘$info’, ‘$display’ in assertions. and BARD models. The earlier versions of ChatGPT Example: (v3.x) performed inadequately by generating mostly in-
@(posedge(clk_i)) $rose(start) |-> correct responses, lacking in information, and sometimes $info("< Error_Message >") unrelatedtothegivenSoCcontext.However,theupdated14 ChatGPT models (v4.x) showed considerable improve- [3] M.M.Bidmeshki,Y.Zhang,M.Zaman,L.Zhou,andY.Makris, ment in generating and listing CWEs, although accuracy “Huntingsecuritybugsinsocdesigns:Lessonslearned,”IEEE Design&Test,vol.38,no.1,pp.22–29,2021. remained a primary concern. Google BARD can search [4] S. Sutherland, RTL Modeling with SystemVerilog for Simula- the web in real-time to find the most recent answers, yet tion and Synthesis: Using SystemVerilog for ASIC and FPGA it performs poorly while generating CWEs and assertions Design. CreateSpaceIndependentPublishingPlatform,2017. [5] S. Sudhakrishnan, J. Madhavan, E. Jr, and J. Renau, “Under- foragivenconfiguration.Toaddressthis,weimplemented standingbugfixpatternsinVerilog,”052008,pp.39–42. a filtering technique to exclude non-relevant CWEs and [6] B. Ahmad, W.-K. Liu, L. Collini, H. Pearce, J. M. generatealistofpotentialvulnerabilitiesthatapplytothe Fung, J. Valamehr, M. Bidmeshki, P. Sapiecha, S. Brown, K. Chakrabarty, R. Karri, and B. Tan, “Don’t CWEAT It: givendesign.AnalyzingalltheCWEsrelatedtohardware TowardCWEAnalysisTechniquesinEarlyStagesofHardware designs listed by the community on the MITRE website Design,” in Proceedings of the 41st IEEE/ACM International enabled us to prepare an extensive database of CWEs ConferenceonComputer-AidedDesign,ser.ICCAD’22. New York, NY, USA: Association for Computing Machinery, 2022. with respective classifications, which were then utilized in https://doi.org/10.1145/3508352.3549369 the filtering process. The filtering step can be evaded if [7] H.Ahmad,Y.Huang,andW.Weimer,“CirFix:Automatically the performance of LLMs in generating relevant CWEs is Repairing Defects in Hardware Design Code,” in Proceedings of the 27th ACM International Conference on Architectural improved. Current LLMs are trained on diverse texts and Support for Programming Languages and Operating Systems, topics with fixed domain-specific knowledge, limiting the ser. ASPLOS ’22. New York, NY, USA: Association for contextual boundaries of accurate data and detailed in- Computing Machinery, 2022, p. 990–1003. https://doi.org/10. 1145/3503222.3507763 formation related to SoC security. Incorporating domain- [8] B.Ahmad,S.Thakur,B.Tan,R.Karri,andH.Pearce,“Fixing specific LLMs by fine-tuning general-purpose LLMs like HardwareSecurityBugswithLargeLanguageModels,”2023. ChatGPT or BARD with extensive and accurate domain- [9] R. Kande, H. Pearce, B. Tan, B. Dolan-Gavitt, S. Thakur, R.Karri,andJ.Rajendran,“LLM-assistedGenerationofHard- specific data would yield better performance. wareAssertions,”2023. [10] S. Paria and S. Bhunia, “DiSPEL: Distributed Security Policy EnforcementforBus-basedSoC,”2023. V. Conclusion [11] J. Blocklove, S. Garg, R. Karri, and H. Pearce, “Chip-Chat: ChallengesandOpportunitiesinConversationalHardwareDe- The proposed framework demonstrates that identifying sign,”2023. related CWEs for a particular bus-based SoC configura- [12] K. Nienhuis, A. Joannou, T. Bauereiss, A. Fox, M. Roe, tion using LLMs is attainable with some limitations. The B. Campbell, M. Naylor, R. M. Norton, S. W. Moore, P. G. Neumann,I.Stark,R.N.M.Watson,andP.Sewell,“Rigorous inclusionofthefilteringprocessrefinestheLLMresponses engineeringforhardwaresecurity:Formalmodellingandproof to recognize only the relevant CWEs using the Extensive in the CHERI design and implementation process,” in 2020 DB of CWEs prepared after meticulously studying and IEEESymposiumonSecurityandPrivacy(SP),2020,pp.1003– 1020. conducting several experiments. The adaption of SVA- [13] J. Devlin, M.-W. Chang, K. Lee, and K. Toutanova, “BERT: based verification using simulation helps to detect the Pre-training of Deep Bidirectional Transformers for Language presence of vulnerabilities in the present implementation. Understanding,”2019. [14] P. Budzianowski and I. Vulic, “Hello, It’s GPT-2 - How Can I The automated translation from assertions to respective HelpYou?TowardstheUseofPretrainedLanguageModelsfor security policies paves the way to generate policy en- Task-OrientedDialogueSystems,”CoRR,vol.abs/1907.05774, forcement logic either through a centralized module or 2019.http://arxiv.org/abs/1907.05774 at the respective IP modules to implement the security [15] R. Dale, “GPT-3: What’s it good for?” Natural Language En- gineering,vol.27,no.1,p.113–118,2021. requirements. The experimental results demonstrate the [16] Y. Liu, M. Ott, N. Goyal, J. Du, M. Joshi, D. Chen, O. Levy, security requirements are fulfilled with minimal overhead M. Lewis, L. Zettlemoyer, and V. Stoyanov, “RoBERTa: A incurred.Theend-to-endautomatedflow,fromidentifying RobustlyOptimizedBERTPretrainingApproach,”CoRR,vol. abs/1907.11692,2019.http://arxiv.org/abs/1907.11692 potential vulnerabilities to mitigating them by enforcing [17] “IntroducingChatGPT,”https://openai.com/blog/chatgpt.
respective security policies, can be easily integrated and [18] “Try bard, an AI experiment by Google,” https://bard.google. com/?hl=en. adapted for any standard bus-based SoC configuration, [19] J. B. Nielsen and V. Rijmen, Eds., Advances in Cryptology - which helps reduce the manual efforts by security experts EUROCRYPT 2018 - 37th Annual International Conference andprovidesmoreflexibilityandcontrollabilitytotheend on the Theory and Applications of Cryptographic Techniques, user. While the current study focuses on bus-based SoCs, Tel Aviv, Israel, April 29 - May 3, 2018 Proceedings, Part II, ser.LectureNotesinComputerScience,vol.10821. Springer, the methodology can be extended to other interconnect 2018.https://doi.org/10.1007/978-3-319-78375-8 fabrics, including Network-on-Chip (NoC) based SoCs. [20] J. He, X. Guo, T. Meade, R. G. Dutta, Y. Zhao, and Y. Jin, “Soc interconnection protection through formal verification,” Integration, vol. 64, pp. 143–151, 2019. https://www. References sciencedirect.com/science/article/pii/S016792601830289X [21] S. Ray, N. Ghosh, R. J. Masti, A. Kanuparthi, and J. M. [1] “The MITRE Corporation (MITRE), CWE VIEW: Hardware Fung,“Invited:Formalverificationofsecuritycriticalhardware- Design,” 2021. https://cwe.mitre.org/data/definitions/1194. firmware interactions in commercial socs,” in 2019 56th html ACM/IEEE Design Automation Conference (DAC), 2019, pp. [2] G. Dessouky, D. Gens, P. Haney, G. Persyn, A. Kanuparthi, 1–4. H. Khattri, J. M. Fung, A.-R. Sadeghi, and J. Rajendran, [22] J. Sepulveda, D. Aboul-Hassan, G. Sigl, B. Becker, and “HardFails: Insights into Software-Exploitable hardware M.Sauer,“Towardstheformalverificationofsecurityproperties bugs,” in 28th USENIX Security Symposium (USENIX ofanetwork-on-chiprouter,”in2018IEEE23rdEuropeanTest Security 19). Santa Clara, CA: USENIX Association, Symposium(ETS),2018,pp.1–6. Aug. 2019, pp. 213–230. https://www.usenix.org/conference/ [23] A.Ardeshiricham,W.Hu,J.Marxen,andR.Kastner,“Register usenixsecurity19/presentation/dessouky transfer level information flow tracking for provably secure15 hardware design,” in Design, Automation & Test in Europe Conference&Exhibition(DATE),2017,2017,pp.1691–1696. [24] C. Brant, P. Shrestha, B. Mixon-Baca, K. Chen, S. Varlioglu, N.Elsayed,Y.Jin,J.Crandall,andD.Oliveira,“Challengesand opportunities for practical and effective dynamic information flow tracking,” ACM Comput. Surv., vol. 55, no. 1, nov 2021. https://doi.org/10.1145/3483790 [25] W. Hu, B. Mao, J. Oberg, and R. Kastner, “Detecting hardware trojans with gate-level information-flow tracking,” Computer, vol. 49, no. 8, p. 44–52, aug 2016. https: //doi.org/10.1109/MC.2016.225 [26] D.Zhang,Y.Wang,G.Suh,andA.Myers,“Ahardwaredesign language for timing-sensitive information-flow security,” ACM SIGPLANNotices,vol.50,pp.503–516,052015. [27] S.K.Muduli,G.Takhar,andP.Subramanyan,“Hyperfuzzing for soc security validation,” in Proceedings of the 39th International Conference on Computer-Aided Design, ser. ICCAD’20. NewYork,NY,USA:AssociationforComputing Machinery,2020.https://doi.org/10.1145/3400302.3415709 [28] T.Trippel,K.G.Shin,A.Chernyakhovsky,G.Kelly,D.Rizzo, and M. Hicks, “Fuzzing hardware like software,” CoRR, vol. abs/2102.02308,2021.https://arxiv.org/abs/2102.02308 [29] R. Kande, A. Crump, G. Persyn, P. Jauernig, A.-R. Sadeghi, A. Tyagi, and J. Rajendran, “TheHuzz: Instruction fuzzing of processors using Golden-Reference models for finding Software-Exploitablevulnerabilities,”in31stUSENIXSecurity Symposium (USENIX Security 22). Boston, MA: USENIX Association, Aug. 2022, pp. 3219–3236. https://www.usenix. org/conference/usenixsecurity22/presentation/kande [30] M. Hicks, C. Sturton, S. T. King, and J. M. Smith, “Specs: A lightweight runtime mechanism for protecting software from security-critical processor bugs,” in Proceedings of the Twentieth International Conference on Architectural Support for Programming Languages and Operating Systems, ser. ASPLOS ’15. New York, NY, USA: Association for Computing Machinery, 2015, p. 517–529. https://doi.org/10. 1145/2694344.2694366 [31] M. Mushtaq, J. Bricq, M. K. Bhatti, A. Akram, V. Lapotre, G. Gogniat, and P. Benoit, “Whisper: A tool for run-time detection of side-channel attacks,” IEEE Access, vol. 8, pp. 83871–83900,2020. [32] S. R. Sarangi, A. Tiwari, and J. Torrellas, “Phoenix: Detectingandrecoveringfrompermanentprocessordesignbugs with programmable hardware,” in 39th Annual IEEE/ACM International Symposium on Microarchitecture (MICRO-39 2006), 9-13 December 2006, Orlando, Florida, USA. IEEE Computer Society, 2006, pp. 26–37. https://doi.org/10.1109/ MICRO.2006.41 [33] F. Farahmandi, Y. Huang, and P. Mishra, System-on-Chip Security:ValidationandVerification. Springer,2019. [34] M.Bilzor,T.Huffmire,C.Irvine,andT.Levin,“Evaluatingse- curityrequirementsinageneral-purposeprocessorbycombining assertioncheckerswithcodecoverage,”062012.
[35] Y. Lyu and P. Mishra, “System-on-Chip Security Assertions,” 2020. [36] P. Bhamidipati, S. M. Achyutha, and R. Vemuri, “Security Analysis of a System-on-Chip Using Assertion-Based Verifi- cation,” in 2021 IEEE International Midwest Symposium on CircuitsandSystems(MWSCAS),2021,pp.826–831. [37] D. Drain, C. Wu, A. Svyatkovskiy, and N. Sundaresan, “Generating bug-fixes using pretrained transformers,” in Proceedings of the 5th ACM SIGPLAN International Symposium on Machine Programming, ser. MAPS 2021. New York, NY, USA: Association for Computing Machinery, 2021,p.1–8.https://doi.org/10.1145/3460945.3464951 [38] H. Pearce, B. Tan, B. Ahmad, R. Karri, and B. Dolan-Gavitt, “Examining zero-shot vulnerability repair with large language models,”2022. [39] MIT-LL, “Common Evaluation Platform (CEP),” 2020. https: //github.com/mit-ll/CEP
2308.10523 When Less is Enough: Positive and Unlabeled Learning Model for Vulnerability Detection Xin-Cheng Wen1, Xinchen Wang1, Cuiyun Gao1∗, Shaohua Wang2, Yang Liu3, Zhaoquan Gu1 1 School of Computer Science and Technology, Harbin Institute of Technology, Shenzhen, China 2 Central University of Finance and Economics, China 3 School of Computer Science and Engineering, Nanyang Technological University, China xiamenwxc@foxmail.com, 200111115@stu.hit.edu.cn, davidshwang@ieee.org, yangliu@ntu.edu.sg, {gaocuiyun, guzhaoquan}@hit.edu.cn Abstract— Automated code vulnerability detection has gained increasing attention in recent years. The deep learning (DL)- Positive Negative Unlabeled based methods, which implicitly learn vulnerable code patterns, haveproveneffectiveinvulnerabilitydetection.Theperformance of DL-based methods usually relies on the quantity and quality of labeled data. However, the current labeled data are generally automatically collected, such as crawled from human-generated commits,makingithardtoensurethequalityofthelabels.Prior studies have demonstrated that the non-vulnerable code (i.e., negativelabels)tendstobeunreliableincommonly-useddatasets, while vulnerable code (i.e., positive labels) is more determined. (A)Supervised learning (B)PU learning Consideringthelargenumbersofunlabeleddatainpractice,itis necessary and worth exploring to leverage the positive data and largenumbersofunlabeleddataformoreaccuratevulnerability Fig. 1: (A) illustrates supervised learning model is trained on detection. a set of positive and negative samples. (B) represents Positive In this paper, we focus on the Positive and Unlabeled (PU) learningproblemforvulnerabilitydetectionandproposeanovel andUnlabeled(PU)learningmodelsonthetrainingsetwhich model named PILOT, i.e., PositIve and unlabeled Learning only contains few labeled positive and some unlabeled sam- mOdel for vulnerability deTection. PILOT only learns from ples.Thered,green,andgreycirclesdenotepositive,negative, positiveandunlabeleddataforvulnerabilitydetection.Itmainly and unlabelled samples, respectively. contains two modules: (1) A distance-aware label selection module,aimingatgeneratingpseudo-labelsforselectedunlabeled data, which involves the inter-class distance prototype and progressive fine-tuning; (2) A mixed-supervision representation been present in approximately 350,000 open-source projects, learning module to further alleviate the influence of noise potentially creating a significant security risk due to it going and enhance the discrimination of representations. Extensive unnoticed for so long. Consequently, researchers seek to im- experiments in vulnerability detection are conducted to evaluate prove approaches for software vulnerability detection in order the effectiveness of PILOT based on real-world vulnerability to safeguard computer systems and programs from potential datasets.TheexperimentalresultsshowthatPILOToutperforms thepopularweaklysupervisedmethodsby2.78%-18.93%inthe attacks. PUlearningsetting.Comparedwiththestate-of-the-artmethods, Inrecentyears,withtheincreaseinthenumberofsoftware PILOT also improves the performance of 1.34%-12.46% in F1 vulnerabilities [2], more and more researchers have been score metrics in the supervised setting. In addition, PILOT can using automated methods for software vulnerability detection. identify 23 mislabeled from the FFMPeg+Qemu dataset in the Generally, existing software vulnerability detection methods PU learning setting based on manual checking. can be divided into two categories: program analysis (PA)- Index Terms—Software vulnerability detection, positive and unlabeled learning, source code representation based methods [3]–[5] and learning-based methods [6]–[10]. PA-based methods mainly include static analysis [11]–[13], I. INTRODUCTION dynamic analysis [14], [15], and symbolic execution [16], amongothers.Thesemethodsusuallyutilizeexpertknowledge Software vulnerabilities typically refer to specific flaws or to manually extract features. They primarily focus on specific oversights within software components that enable attackers types of vulnerabilities, e.g. buffer overflow [17] and SQL to disrupt a computer system or program. In 2022, Trellixd’s injection [18], etc. team uncovered a security vulnerability in Python’s tarfile Incomparison,learning-basedmethodscandetectabroader module,knownasCVE-2007-4559[1].Thisvulnerabilityhad rangeofsoftwarevulnerabilitytypes[19],suchasvariousvul- nerability in libraries and API calls. Learning-based methods ∗ Corresponding author. The author is also affiliated with Peng Cheng Laboratory. mainlyincludesequence-based[20]–[22]andgraph-basedap- 3202 guA 12 ]ES.sc[ 1v32501.8032:viXraproaches [7], [23], [24], both of which require a large amount relative improvements at 1.34%, 12.46%, and 3.00% absolute ofannotateddatafortraining.Forinstance,VulDeePecker[21] improvement in the supervised setting. In addition, PILOT and SySeVR [20] treat source code as sequences and extract identifies 23 mislabeled samples from the training set of the code gadgets from the source code and use a bidirectional FFMPeg+Qemu dataset based on manual checking, verifying Long Short-Term Memory (LSTM) network for vulnerability the inaccurate label issue of existing labels. detection. Devign [23] and Reveal [24] extract various graph In summary, the major contributions of this paper are structures (such as Data Flow Graphs [25], and Control Flow summarized as follows:
Graphs [26]) from the code and leverage Gated Graph Neural 1) We are the first to focus on the positive and unlabeled Networks to detect vulnerabilities within the code. learning problem for software vulnerability detection. Although learning-based methods have made significant 2) WeproposePILOT,anovelvulnerabilitydetectionframe- progress in software vulnerability detection, the performance work under the PU setting. PILOT involves a distance- of these methods is still limited due to the lack of high- aware label selection module for providing pseudo-label quality labeled data. Specifically, these methods suffer from and a mixed-supervision representation learning module the following limitations: (1) Lack of labeled data. One for alleviating the influence of noisy labels in vulnerabil- major limitation is that existing vulnerability detection meth- ity detection. ods require a large amount of labeled positive and negative 3) We perform an evaluation of PILOT on two settings and samples.However,manualcodereviewrequiresexpertknowl- three public benchmark datasets, and the results demon- edge [27] and is time-consuming [28], resulting in the lack of stratetheeffectivenessofPILOTinsoftwarevulnerability high-quality labeled data. (2) Inaccurate labeled data. The detection. accuracyofthelabelsinvulnerabilitydetectionisalsoamajor The remaining sections of this paper are organized as challenge. The commonly-used labeling methods crawl the follows. Section II introduces the assumptions of positive labelsfrompubliccommit[29]orrelyonstaticanalyzers[30], and unlabeled learning. Section III presents the architecture which are not foolproof and prone to introducing inaccurate of PILOT, which includes two modules: a distance-aware labels. Croft et al.’s [31] research has also identified the label selection module and a mixed-supervision representa- presenceofnoisydata.Forexample,only80%ofthelabelsin tion learning module. Section IV describes the experimental the FFMPeg+Qemu [23] dataset are reported as accurate. The setup,includingdatasets,baselines,andexperimentalsettings. prior research has also demonstrated that the non-vulnerable Section V presents the experimental results and analysis. labels (i.e., negative labels) are low in quality, while the Section VI discusses why PILOT can effectively detect code vulnerable labels (i.e., positive labels) are more reliable [32], vulnerabilityandthethreatstovalidity.SectionVIIIconcludes [33]. Considering the large numbers of unlabeled data in the paper. practice, it is critical to use the higher-quality positive labels and the unlabeled labels for vulnerability detection. II. ASSUMPTIONSOFPULEARNING Toaddressthechallengesabove,weproposeaPositIveand Positive and Unlabeled (PU) learning setting [34]–[36] is a unlabeled Learning mOdel for vulnerability deTection, called weaklysupervisedclassificationsetupwhereonlyPUsamples PILOT.PILOTmainlycontainstwomodules:(1)Adistance- are used for training. It does not require fully supervised aware label selection module, which generates pseudo-labels data to obtain the same performance as supervised data. In for selecting high-quality unlabeled data. It consists of the this section, we introduce the assumptions of PU learning, inter-class distance prototype and progressive fine-tuning; (2) including data assumption and label assumption. Amixed-supervisionrepresentationlearningmoduletofurther alleviatetheinfluenceofnoiseandenhancethediscrimination A. Data Assumption of the vulnerability representation. As shown in Figure 1, The PU data in this paper originate from a single training- differentfromthesupervisedlearningsetting,thepositiveand set scenario [37], meaning that the data come from one single unlabeled(PU)learningsetting(i.e.,PUsetting)onlyrequires training set. In PU settings, a fraction c from the positive a few labeled positive samples and some unlabeled samples samplesisselectedtobelabeled,followingthedatasethaving for training. a fraction αc of labeled samples. Specifically, the probability We evaluate the effectiveness of PILOT for detecting soft- density functions of the ground truth distribution f(x) is ware vulnerabilities under two settings: PU and supervised following: settings.Threepopularbenchmarkdatasetsareadoptedforthe evaluation, including FFMPeg+Qemu [23], Reveal [24], and x∼f(x) Fanetal.[29].WecomparePILOTwithfourcommonlyused ∼αf (x)+(1−α)f (x) + − weaklysupervisedmethodsinthePUsettingandfiveexisting ∼αcf (x)+(1−αc)f (x). (1) l u software vulnerability detection methods in the supervised setting. The results demonstrate that PILOT outperforms all where α is the fraction of the positive samples in the dataset, the baseline methods with respect to the F1 score metric. f (x), f (x), f (x) and f (x) denote the probability density + − l u In particular, PILOT achieves 2.78%, 18.44%, and 18.93% functions of the positive, negative, labeled and unlabeled in the PU setting on the three datasets, respectively, with samples, respectively. In addition, PU learning is required toInput (A) Distance-aware Label Selection Module ① 我 ① ② Code Fine-tuning Step1:Inter-class Distance Prototype Step2:Progressive Fine-tuning Pseudo Label Representation Label Positive Unlabeled Push + + High-quality Negative Pull High-quality Positive Pretrained Pull Push ℒ Operate Model Prototype (B) Mixed-supervision Representation Learning Module ℒ ℒ Fig. 2: The architecture of PILOT, which mainly contains two modules: (A) a distance-aware label selection module, and (B) a mixed-supervision representation learning module. The different colored circles denote samples under different labels. The
same color scheme denotes the same role. Different shades denote the order of labeling, with darker colors denoting earlier labeling. comply with the separability [38], [39] and smoothness [40], Definition 3 (Selected Completely At Random): Labeled [41] assumptions. samples are selected completely at random, independent of Definition 1 (Separability): In the hypothesis space, there their representations, from the positive samples distribution exists a function that can map positive samples to values f +(x). greater than or equal to a threshold τ, and negative samples to values below τ. e(x)=Pr(s=1|x,y =1)=Pr(s=1|y =1)=c. (2) Undertheseparabilityassumption,theoptimalclassifiercan classifyalllabeledsamplesaspositiveandapartofdissimilar In the SCAR assumption, the probability of selecting a unlabeled samples as negative. Considering that the optimal positive sample is constant and equal to the label frequency classifierishardtobeobtained,onecommonly-usedapproach c. Each sample will have a propensity score e(x) based is to vary the threshold value τ and select a subset of samples on the label frequency c. The vulnerabilities observed by to further train the classifier [34]. programmers are usually independent of the code represen- Definition 2 (Smoothness): If the representations of two tion [43]. One example of a difficult-to-identify vulnerability instances x 1 and x 2 are similar in the hypothesis space, the is CWE-369 (Divide By Zero) [44], in which the vulnerable probabilities Pr(y = 1|x 1) and Pr(y = 1|x 2) will also be statements present only a small fraction in the source code. similar. Suchvulnerabilitiesarehardtobeidentifiedbyrepresentation- The smoothness assumption allows identifying high-quality based vulnerability detection methods [45]. The evaluation of negative samples as those that are far from all the positive PILOT in this paper is based on the SCAR assumption. samples. This can be done by using different similarity (or distance) learning measures. III. PROPOSEDFRAMEWORK B. Label Assumption In this section, we formulate the positive and unlabeled Another important assumption of PU learning is about the learning setting for vulnerability detection and then describe labeling mechanism. It pertains to the selection process for theoverallframeworkofPILOT.AsshowninFigure2,PILOT instances labeled as vulnerable (i.e. positive) in the experi- consists of two main modules: (1) a distance-aware label mental setup. In this paper, we choose the basic assumption selection module for providing high-quality pseudo-labels (2) for most weakly supervised methods [35], [36], [42] in PU a mixed-supervision representation learning module to further setting, called the Selected Completely At Random (SCAR) alleviate the effects of noise and enhance the discriminative assumption [37]: power of the vulnerability representation.A. Problem Formulation C,i ∈ {1,2,...,n}). We generate the sequence vector x0 for eachsourcecodefunctiontocaptureboththeglobalandlocal A positive and unlabeled (PU) setting for vulnerability information, which is calculated as follows: detection is to train a binary classifier in the single-training- set scenario [37], which can distinguish whether a sample is vulnerable or not based on the input source code. In the PU x0 =H0[CLS]+HL[CLS] (5) learning setting, only part of the vulnerable samples in the where H0 and HL denote the first and last layer embedding training data are labeled as positive and none of the non- of CodeBERT [47], respectively. CLS is a special token and vulnerable ones are labeled, as introduced in Section I. is often used as the representation of the sequence [48]. WedenotethePUdatasetcollectedfromtherealworldsce- To seek the inter-class distance prototype, we use the nario as ((x ,y ,l )|x ∈ X,y ∈ Y,l ∈ C,i ∈ {1,2,...,n}), i i i i i i positive samples close to the unlabeled samples. For each where X denotes the set of functions in the raw source code, unlabeled sample i, the distance Dp to all positive samples Y = {0,1} denotes the class of code function (vulnerable ij j is calculated. The top k nearest samples are then selected, or not), C = {0,1} denotes a binary variable representing and the prototype of sample i is the mean vector of the top whetherthesampleisselectedtobelabeled,nisthenumberof k samples. The sum and mean of the prototype distance for codefunctioninthedataset.InthePUsettingofvulnerability sample i are calculated as Dp and Mp: detection, the class of sample y is not observed, but the i i representation of source code can be derived from the label c. k dim (cid:88) (cid:88) Dp =Topk |x0[m]−x0[m]| (6) Thesourcecodelabeledwithc=1indicatesthatitbelongs i i j to the vulnerable function (positive label): m=0 k Pr(y =1|c=1)=1 (3) Mp =|x0[m]− 1 Topk (cid:88) x0[m]| (7) i i k j Forthesourcecodesamplesunlabeledc=0,theycanbelong m=0 to vulnerable or not. where dim denotes the dimension of x0 vector. We sort Dp i Finally, PILOT learns a mapping from X to Y, f :x i (cid:55)→y i and M ip, and set the threshold T = T r ·n u/n p, where n u to predict whether a code function is vulnerable or not. The and n denote the number of unlabeled and positive samples, p prediction function f is learned below: respectively.T isanadjustablehyper-parameter.Thesmallest r min(cid:88)n L(f(x ,yˆ|{x })) (4)
sT amsa pm lep sle as ndof onD lyip than od seM thi ap tw sai tl il sfb ye ts he ele cc ot ned diti in ont she ofu bn ola tb he Dled p i i i i and Mp can be considered as HN samples IHN. i=1 i 2) Progressive Fine-tuning: As vulnerability (positive) where L(·) is the loss function, yˆ is the pseudo label we i samples are often fewer in number compared to samples extract from the input source code x . i without vulnerabilities, it is crucial for PILOT to continually B. Distance-aware Label Selection Module learn vulnerability patterns from labeled (including pseudo- labeled) samples to obtain more pseudo labels. We propose In this section, we elaborate on the proposed distance- progressive fine-tuning to utilize all available unlabeled data aware label selection module. It aims to identify High-quality and identify more high-quality labeled samples. First, we Negative (HN) samples, which can provide pseudo-labeling fine-tune the pre-trained model using labeled samples IP as of unlabeled samples. The module contains two components, positiveandHNsamplesIHN asnegative.Themodelweights i.e., the inter-class distance prototype learning component are kept as Ω and no new samples are added. Then, PILOT and progressive fine-tuning component. In the following, we retains the previous model weights Ω and determines if any first elaborate on the two components and then provide an unlabeled samples can be confidently predicted. If so, these algorithm for the overall process. samples are labeled as High-quality Positive (HP) IHP and 1) Inter-class Distance Prototype: The inter-class distance HN samples IHN according to the model predicted. Both the prototypelearningcomponentaimsatidentifyinghigh-quality HP and HN samples are then used as training data for the pseudo-labels in unlabeled samples. Labeled positive samples next epoch. This process, called progressive, is repeated by typically represent a small percentage of all training samples. L untiltheaccuracyofvalidationsetnolongerincreases.In Unlabeled samples may contain both positive and negative ce the progressive step, the quality of added samples decreases samples. Considering the diversity of vulnerabilities [46], we witheachtrainingepoch.Wereducethehigh-qualitysample’s select the corresponding positive prototype for each unlabeled weights We as the number of progressive steps increases, samplebasedonthesmoothnessassumption(SectionII-A)and i calculated as below: inter-class distance. To select HN samples, we leverage the distance between unlabeled samples and all labeled vulnera- e We =1− ,e={1,2,..,E } (8) bility samples. Only those unlabeled samples that exhibit the i E +1 m m maximum distance difference is selected as HN samples. We use the CodeBERT [47] architecture to initialize the (cid:88)ne L =− Weyˆlog(pˆ),yˆ =IHN ∪IHP ∪IP (9) representationsofcodeinthePUdataset((x ,l )|x ∈X,l ∈ ce i i i i i i i i i=1Algorithm 1: Inter-class Distance Prototype the algorithm selects the inter-class prototype for each un- Input :SourceCode:X,SelectedLabel:C,Threshold: labeled sample, calculates the corresponding distance, and Tmax,Tmin chooses the HN samples based on the inter-class distance. Output:Pseudo-positiveLabel:IHN,Pseudo-negativeLabel:IHP Forprogressivefine-tuning,thealgorithmperformsfine-tuning Ensure:Θdenotesthepre-trainedmodel,Ωdenotesthecurrent model again in labeled and HN samples (Lines 19-23), and then 1 FunctionDistance-awareLabelSelectionModule: selects the HP and HN samples in the training epoch (Lines // Start Training:Inter-class Distance 24-34). Prototype 2 3 fore <ach x0 i< ,hx i0 i ,, cc ii >> ←an Fd inc ei T= un0 ind go C. Mixed-supervision representation learning module 4 InitializeDi foreach<x0 j,cj >andcj =1do Themixed-supervisionrepresentationlearningmoduleaims 5 CalculatedD ip byEq6givenx0 i andx0 j ; to mitigate the problem of poor-quality labels. We first com- 6 CalculatedM ip byEq7givenx0 i andx0 j; bine the CE loss and weakly supervised loss to construct the 7 end 8 end relationbetweenrepresentationandlabels,whichenhancesthe 9 SortedD ip,M ip andchoseTopK samplesindexasnegative inter-class distance and reduces the intra-class distance for samplesIHN,IHN; D M enhancing code representations. To alleviate the problem of 10 C Ial Hcu NlatedI DHN ∩I MHN;andchoseindexasnegativesamples label noise, we then involve an unsupervised loss to learn the // Start Training: Progressive Fine-tuning unsupervised representations for reducing the impact of noisy 11 foreachtrainingepochdo labels. Specifically, we train L by minimizing the loss 1 12 3 fore ia fc ch i< =x 1i, oc ri i> ∈∈ I< HX N,C the> ndo function calculated as below: Metric 14 Ω←FineTuning 15 end L =αLSelf +(1−α)LWeakly+L (10) 16 end Metric i i ce 17 end where α is a trade-off parameter. L is calculated as Eq. 9. 18 foreachtrainingepoche∈E do ce 19 foreach<xi,ci>∈<X,C>do LS ielf andLW i eakly denotetherelationshipsinself-supervised 20 ifci=1ori∈IHN then and weakly-supervised scenario, respectively. The followings 21 Ω←FineTuning are the details of each loss function. 22 32 endend Specifically, LS ielf is mainly used to mine the relation of 24 foreach<xi,ci>∈<X,C>do representation itself, and for each sample i, we give a query
25 if ci=0andi∈/IHN then representation q and a set B = {x ,...x } of B samples 26 pi←Prediction; 1 B 27 if p>Tmax then containing one positive sample and B−1 other samples from // Add high-quality positive the distribution, computed as below: samples; 28 i∈IHP,ei∈E ; exp(q·x /τ) 29 end LSelf =−log i (11) 30 if p<Tmin then i (cid:80)B k=0exp(q·x k/τ) // Add high-quality negative samples; where τ is a temperature hyper-parameter [49]. The sum is 31 i∈IHN,ei∈E over one chosen sample and B−1 contrastive samples. The 32 end purposeoftheLSelf istocharacterizetriestoclassifysample 33 end i 34 end q as a chosen sample through a vulnerability sample. 35 end The weakly supervised loss function LWeak is used to fur- 36 returnIHN,IHP ther establish a relation between represeni tations and pseudo- labels: where e and E denote the current epoch and progressive exp(x ·x /τ) m LWeak =−log i yˆi (12) fine-tuningtrainingepoch,respectively.yˆ i istheconcatenation i (cid:80)B exp(x ·x /τ) k=0 i k set of the pseudo labels we extract and the positive labels, pˆ i where τ is also the same hyper-parameter in Eq. 11, and yˆ denotestheoutputpredictedbythemodel,andn denotesthe i e denotes the pseudo-label of sample i. number of training samples in Epoch e. 3) The Algorithm of Distance-aware Label Selection Mod- IV. EXPERIMENTALSETUP ule: Theoveralldistance-awarelabelselectionmoduleprocess is depicted in Algorithm 1, in which inter-class distance In this section, We evaluate the PILOT and aim to answer prototype selection and progressive fine-tuning correspond to the following research questions (RQs): Lines 2-10 and Lines 11-35, respectively. The algorithm takes RQ1: How does PILOT perform in vulnerability detection all the training data (including labeled or not) as the input, with different weakly supervised methods in PU and outputs pseudo labels (including IHN and IHP). settings? For inter-class distance prototype selection, the algorithm RQ2: How does PILOT perform compared with the state- initializes the representation for each sample (Lines 3). Then, of-the-art vulnerability detection approaches?RQ3: What is the influence of different modules on the 5) LineVul[47]:LineVultrainsontheTransformerarchitec- detection performance of PILOT? ture. To ensure fairness, we use the word-level tokenizer RQ4: How do the different hyper-parameters impact the version for comparison. performance of PILOT? C. Implementation Details A. Datasets To ensure the fairness of the experiment, we use the same To answer the questions above, we choose three widely- data split for all approaches. In the PU learning scenario, we used vulnerability datasets, including FFMPeg+Qemu [23], randomly label 30% of the training positive samples based on Reveal [24] and Fan et al. [29]. FFMPeg+Qemu consists of the assumptions (Section II). We repeat the labeling scenario twoopen-sourceCprojectswithatotalof22ksamples,outof three times and use the mean as the experimental results. In which 10k samples are vulnerable. The Reveal dataset tracks the supervised learning scenario, we randomly partition the historicalvulnerabilitiesintwoopen-sourceprojects,withover datasets into disjoint training, validation, and test sets in a 22k and approximately 2k vulnerable samples. Fan et al.’s ratio of 8:1:1. dataset collects 91 types of vulnerabilities from 348 open- We try our best to reproduce all baseline models from source GitHub projects, with around 188k total samples and publicly available source code and papers, and use the same 10k vulnerable samples. hyper-parameter settings as in the original text whenever possible. B. Baselines We fine-tune the pre-trained model CodeBERT [47] with In this paper, we compare PILOT with four representative a learning rate of 2e−5. The batch size is set to 32. The weakly supervised learning methods in the PU setting and top nearest samples k is set to 30% to choose prototype five state-of-the-art vulnerability detection methods in the samples. The T r is set to 0.3. During each fine-tuning, we supervised setting. trainourmodelonaserverwithNVIDIAA100-SXM4-40GB In RQ1, we compare PILOT with four weakly supervised for maximum epochs E m of 5. learning methods in the PU setting: D. Evaluation Metrics 1) Cosine and Rocchio SVM (CR-SVM) [50]: CR-SVM extracts tf-idf and uses the cosine similarity between We use the following four commonly-used metrics to mea- unlabeled and labeled samples. Then it uses the iterative sure PILOT’s performance: SVM to select the optimal classifier. Precision: Precision = TP . The precision measures TP+FP 2) Unbiased PU (uPU) [51]: uPU treats the unlabeled the percentage of true vulnerabilities out of all the vulnerabil- sample as the sum of positive and negative samples with itiesthatareretrieved.TP andFP denotethenumberoftrue differentweights,andconstructsariskestimatortotrain. positives and false positives, respectively. 3) Non-negative PU (nnPU) [52]: nnPU constructs a non- Recall:Recall= TP .Therecallmeasuresthepercent- TP+FN negative risk estimator based on the uPU, which adds a ageofvulnerablesamplethatareretrievedoutofallvulnerable limitationtothelossfunctionofriskestimatortoalleviate samples.TP andFN denotethenumberoftruepositivesand the overfitting problems. false negatives, respectively.
4) Self-PU [53]: Self-PU is a self-paced learning algorithm, F1 score: F1 score=2× Precision×Recall. The F1 score Precision+Recall self-calibratedinstance-awardedloss,andself-distillation is the harmonic mean of precision and recall metrics. strategy to train the model. Accuracy: Accuracy = TP+TN . The accuracy TP+TN+FN+FP measures the percentage of correctly classified samples out of InRQ2,weadoptfivestate-of-the-artvulnerabilitydetection all samples. TN represents the number of true negatives and approaches for comparison in the supervised learning setting, TP+TN+FN+FP represents the number of all samples. including: 1) SySeVR [20]: SySeVR uses statements, program depen- V. EXPERIMENTALRESULTS dencies,andprogramslicinggeneratedfromsourcecode, A. RQ1. Effectiveness of PILOT in PU setting and utilizes a bidirectional recurrent neural network to vulnerability detection. To answer RQ1, we compare PILOT with the four PU 2) Devign[23]:DevignconstructsajointgraphbyAbstract learning baseline methods with the four performance metrics Syntax Tree (AST), CFG, DFG and Natural Code Se- (i.e. accuracy, precision, recall, and F1 score) on the three quence (NCS) and uses GGNN for vulnerability detec- datasets.Toensurefairnessintheexperiment,thesamelabels tion. are chosen for all the baseline methods, and we choose the 3) Reveal [24]: Reveal divides vulnerability detection into labeledsamples3timesandreporttheaveragedresults.TableI twosteps:featureextractionstepsbyGGNNandtraining shows the results, and the performance of PILOT is shown in steps by multi-layer perceptron and triplet loss. the bottom row. 4) IVDetect[7]:IVDetectconstructsaprogramdependency From Table I, we can find that PILOT outperforms all PU graph and utilizes a feature-attention graph convolutional learning methods in detecting software vulnerabilities across network to learn the graph representation. all three datasets and obtains the best results in 11 out ofTABLE I: Comparison results between PILOT and the weakly supervised learning approaches in the PU setting on the three datasets. The shaded cells represent the performance of the best methods in each metric. Dark cells represent the best performance. Dataset FFMPeg+Qemu [23] Reveal[24] Fanetal.[29] Metrics(%) Baseline Accuracy Precision Recall F1score Accuracy Precision Recall F1score Accuracy Precision Recall F1score CosineandRocchioSVM[50] 48.99 45.83 60.80 52.21 86.10 7.87 9.12 7.80 85.66 9.57 6.18 6.72 UnbiasedPU[51] 56.08 54.43 30.15 38.74 83.09 28.79 26.55 24.75 91.44 24.52 11.22 10.62 Non-negativePU[52] 56.01 50.20 41.96 46.60 83.07 28.93 27.18 25.38 91.45 25.15 10.77 9.79 Self-PU[53] 53.69 50.15 44.30 45.85 84.41 22.01 17.32 18.61 89.52 19.75 9.39 9.04 PILOT 58.38 54.66 55.48 54.99 86.99 40.83 47.34 43.82 91.92 29.05 30.30 29.55 12 metrics. Specifically, PILOT achieves absolute improve- vulnerability detection methods, PILOT achieves absolute im- ments of 2.78%, 18.44%, and 18.93% over the F1 scores provementof4.61%,7.59%,22.32%,and14.88%withrespect of the best baseline method on the FFMPeg+Qemu [23], to the four metrics, respectively. Reveal [24] and Fan et al. [29] datasets, respectively. As Our results also show that the graph-based approaches for accuracy metric, PILOT outperforms baseline methods by (Devign, Reveal, and IVDetect) perform similarly to PILOT at least 2.31%, 0.89%, and 0.47% on these three datasets, when the samples with vulnerabilities or not are balanced. respectively. In the unbalanced dataset (i.e. Reveal and Fan However, in scenarios where the datasets are unbalanced, et al.), PILOT achieves better performance in all four metrics the performance of graph-based approaches is worse than (eight situations). This is due to the ability of PILOT to better PILOT. It may be due to the fact that the graph-based extract high-quality pseudo-labels from unbalanced samples model approaches are hard to capture structural information anddetectvulnerabilities.Overall,PILOTcanbeabletodetect (e.g., data flow graph and control flow graph) in unbalanced more vulnerable samples and therefore proved to be more scenarios [54]. effective in PU settings. The improvement of the experiment is non-trivial, the Our results also show that the existing weakly supervised PILOT only selects positive and unlabeled samples in the PU learning methods have much potential for improvement in setting. In contrast, all of the vulnerability detection baselines the area of software vulnerability detection. They ignore use all labels in the training process. the quality of the extracted pseudo-labels and the possible presence of noise in the vulnerability labels. Overall, our AnswertoRQ2:Inthevulnerabilitydetection,PILOT results demonstrate the superior performance of PILOT in performs better in most cases. Compared to existing detecting vulnerabilities, highlighting its potential to improve methods,thePILOT performs4.61%,7.59%,22.32%, the effectiveness of computer security measures. and 14.88% improvements on average on the four metrics, respectively. Answer to RQ1: In the PU setting, PILOT outper- forms all the baseline methods in terms of precision C. RQ3. Effectiveness of different components in PILOT and F1 score. In particular, PILOT achieves 2.78%,
18.44%, and 18.93% improvements in F1 score over In this section, we explore the impact of different compo- the best-performing baseline method on the three nentsontheperformanceofPILOT.Specifically,westudythe datasets, respectively. twoinvolvedmodulesincludingtheDistance-awareLabelSe- lection (DLS) module and Mixed-supervision Representation Learning module (MRL) module. 1) Distance-awareLabelSelectionModule: Toexplorethe B. RQ2. Effectiveness of PILOT in supervised setting contributionoftheDLSmodule,wecreatetwovariantsofPI- To answer RQ2, we compare PILOT with the five vulner- LOT without inter-class distance prototype (i.e. ID Prototype) ability detection methods on the three datasets in supervised and progressive fine-tuning (i.e. PFine-tuning), respectively. learning settings. All baselines use the labels of the positive TheothersettingsofthesetwovairantsareconsistentwithPI- and negative samples to train the binary classifier. LOT.ThepurposeoftheDLSmoduleistoselecthigh-quality Table II shows the results of the vulnerability detection labels from unlabeled samples, which requires at least one of baselines. We can find that PILOT has the best performance the components to construct a binary classifier. Therefore, we in 8 out of 12 cases. For example, on Reveal, PILOT outper- separate two variants for the ablation experiments. forms the best baseline methods by 1.45%, 5.51%, 21.24%, As shown in Table III, both ID Prototype and PFine- and 12.46% regarding the accuracy, precision, recall, and F1 tuning components can improve the performance of PILOT score, respectively. Compared with the average of previous on all datasets. Specifically, on the unbalanced datasets (i.e.TABLE II: Comparison results between PILOT and the supervised vulnerability detection methods on the three datasets. “-” means that means that the baseline fails to converge in this scenario. The best result for each metric is highlighted in bold. Dataset FFMPeg+Qemu[23] Reveal[24] Fanetal.[29] Metrics(%) Baseline Accuracy Precision Recall F1score Accuracy Precision Recall F1score Accuracy Precision Recall F1score SySeVR 47.85 46.06 58.81 51.66 74.33 40.07 24.94 30.74 90.10 30.91 14.08 19.34 Devign 56.89 52.50 64.67 57.95 87.49 31.55 36.65 33.91 92.78 30.61 15.96 20.98 Reveal 61.07 55.50 70.70 62.19 81.77 31.55 61.14 41.62 87.14 17.22 34.04 22.87 IVDetect 57.26 52.37 57.55 54.84 - - - - - - - - LineVul 62.37 61.55 48.21 54.07 87.51 43.63 56.15 49.10 94.44 50.5 28.53 36.46 PILOT 63.14 58.23 69.88 63.53 88.96 49.14 82.38 61.56 92.70 38.00 42.56 39.46 TABLE III: Impact of the different components on the perfor- datasets, respectively. The results indicate that MRL module mance of PILOT. can enhance the discriminative power of the vulnerability representation and bring a performance improvement in vul- Dataset Module Accuracy F1 score nerability detection. w/o ID Prototype 56.30 47.35 w/o PFine-tuning 56.77 58.17 FFMPeg+Qemu Answer to RQ3: Both DLS and MRL modules con- w/o MRL 58.71 55.49 PILOT 59.30 57.23 tribute significantly to the performance of PILOT. The DLS module average boost the F1 score performance w/o ID Prototype 73.97 41.27 of 4.47%, 17.22%, and 8.74% on the three datasets, w/o PFine-tuning 60.47 32.66 Reveal respectively. The MRL module improves PILOT by w/o MRL 80.43 48.20 PILOT 85.79 54.18 1.74%, 5.98%, and 4.51%, respectively. w/o ID Prototype 72.90 21.83 w/o PFine-tuning 57.43 18.09 D. RQ4: Influences of Hyper-parameters on PILOT Fan w/o MRL 77.77 24.19 To answer RQ4, we explore the impact of different hyper- PILOT 87.62 28.70 parameters, including the labeling ratio and the top k samples chosen in the inter-class distance prototype. 1) Ratio of positive labeling: Table IV shows the per- Reveal and Fan et al.), PFine-tuning component achieves an formance of PILOT on four metrics with different ratios of average improvement of 27.76% and 16.07% in terms of positive labeling samples. It means that all negative sam- accuracy and F1 score, respectively; while ID Prototype only ples and unlabeled positive samples are considered unlabeled boostsby13.27%and9.89%.ThisindicatesthatPFine-tuning samples. As the ratio of labeling increases, the performance has a greater effect on the unbalanced dataset. Conversely, of PILOT also increases gradually. PILOT achieves the best on the balanced dataset (i.e. FFMPeg+Qemu), ID Prototype performancewhenallthepositivesamplesareusedaslabeling obtainsimprovementsof3.00%and9.88%respectively,which samples.Comparedwiththeperformanceofthe10%labeling outweighs the improvements of PFine-tuning. The results ratio, the 100% labeling ratio can improve it by 14.13%, demonstrate that different components of the DLS module 20.62%, 11.00%, and 20.80% on four metrics, respectively. focusonthedifferentsituationstoselecthigh-qualitysamples, It demonstrates that it is important to have a larger number which benefit the performance of vulnerability detection. of positive samples to improve the discriminative ability of 2) Mixed-supervisionRepresentationLearningModule: To prototypesformedbypositivesamples.Additionally,extracted understand the impact of MRL module, we also deploy a high-quality negative samples are more believable by increas-
variant of PILOT without the MRL module. Since the above ing positive samples, leading to better overall performance. modulealreadyconstitutesthetrainingofclassifier,thevariant When dealing with unbalanced datasets such as Reveal (i.e. w/o MRL) directly eliminates the training of the MRL and Fan, we observe that performance increases faster when module. the proportion of labeled samples is below 30%. However, Table III shows the performance of the variant on the three the growth rate of performance decreases as the number of datasets. Overall, the accuracy, and F1 score in three datasets labeled samples continues to increase. In contrast, the growth achieve higher values with the addition of the MRL module. of performance in FFMPeg+Qemu is more balanced since the The MRL module improves the accuracy by 0.59%, 5.36%, limited number of negative samples makes it more difficult to and9.85%onFFMPeg+Qemu,Reveal,andFanetal..datasets, capture high-quality labeled samples. respectively.AsfortheF1score,theMRLmodulealsobrings 2) Topksamplesofinter-classdistanceprototype: Wealso an improvement of 1.74%, 5.98%, and 4.51% on these three exploretheeffectofthenumberofTopk samplesoftheinter-TABLE IV: The effect of different ratios of labeled samples on the performance of the PILOT. Dataset FFMPeg+Qemu [23] Reveal [24] Fan et al. [29] Ratio Accuracy Precision Recall F1 score Accuracy Precision Recall F1 score Accuracy Precision Recall F1 score 10% 55.93 51.93 54.66 53.26 64.69 17.46 61.48 27.20 82.08 14.08 43.22 21.24 30% 58.38 54.66 55.48 54.99 83.96 35.11 47.40 39.75 90.17 23.97 34.84 28.40 50% 59.77 56.54 53.71 55.09 84.43 39.46 84.43 53.79 87.20 22.11 51.09 30.86 70% 60.65 57.38 55.78 56.57 86.41 43.10 83.20 56.78 90.01 27.85 49.38 35.61 100% 63.14 58.23 69.88 63.53 88.96 49.14 82.38 61.56 92.99 37.97 40.10 39.00 class distance prototype of PILOT. As shown in Table V, it Answer to RQ4: In vulnerability detection, the PI- shows the number and its corresponding accuracy in selecting LOT’s performance can be affected by the ratio of high-quality negative samples. The higher the accuracy of the labelingandtopsamples.However,ourdefaultsettings recognition,thehigherqualityoftheidentifiedlabeledsamples have been optimized for results. is. VI. DISCUSSION Overall, the larger the number of k will lead to higher A. Why does PILOT Work? accuracy. However, the number of labels with k greater than 30%ratiooflabeledsamplesreachestherecognitionaccuracy We identify the advantages of PILOT, which can explain of 75.18%, 99.34%, and 99.24% in the three datasets, respec- its effectiveness in software vulnerability detection. We also tively,andthegrowthrategraduallyconvergesto0.Therefore, show the two types of incorrectly labeled samples in FFM- in order to reduce computational resource consumption, we Peg+Qemu [24]. choose the 30% ratio of labeled samples as the value of k. (1) PILOT is able to identify high-quality samples. The proposed DLS module helps PILOT to select high-quality samples from unlabeled samples, which involves the inter- In addition, we also present the number of high-quality classdistanceprototypeandprogressivefine-tuningtoidentify negative samples (i.e. Num) in Table V. From the results, high-quality samples. As shown in Figure 3(A), the T-SNE of we can observe that different selections of k lead to different sum and mean of the prototype distance (i.e. Dp and Mp) sampledistributionillustratesthedistinctclassdiscriminability i i between positive samples and high-quality negative samples. for sample i, leading to differences in the number of high- It demonstrates the effectiveness of PILOT. The experimental quality samples selected. For example, the k value of 100% results show that PILOT can be able to identify 75.18%, selects 7.18%, 7.74%, and 11.76% more high-quality samples 99.34%,and99.24%high-qualitysamplesinFFMPeg+Qemu, than the value of 3. Overall, the higher the value of k, the smaller the difference between the Dp and Mp is, and the Reveal, and Fan et al., respectively. Overall, as the number of i i labeledsamplesincreases,thenumberofhigh-qualitysamples more high-quality samples are selected. and the accuracy rate also increase. (2)PILOTwellleveragesthemislabeleddata.PILOTalso pinpointsthelabelsthatareoriginallymislabeledintheFFM- Peg+Qemu [23]. Specifically, we explore the incorrectly iden- tified high-quality samples in PILOT. By manually examining TABLE V: The number of samples k selected by PILOT and the code and corresponding labels. We randomly select 200 the corresponding accuracy in the inter-class prototype step. codesampleswhichareassociatedwithdifferentpseudo-labels The percentage (%) indicates the number of selected samples generated by PILOT and ground truth from FFMPeg+Qemu among all unlabeled samples. “Num” denotes the number of for manual checking. To guarantee the quality of the manual selecting reliable negative samples in the inter-class prototype checking, one author and two developers joined to label the step. data, and each of them possess over five years of software development experience. The two developers independently Dataset Devign Reveal Fan labeledthesamplesforthepresenceofvulnerabilities.Forthe k Acc(%) Num Acc(%) Num Acc(%) Num disagreement,theauthorintervenedasamediatortoachievea consensus. The manual checking shows that the PILOT finds 3 73.03 5210 99.21 4822 95.67 39564
23 mislabeled samples in the dataset. 5 73.25 5211 99.20 4770 95.67 39438 We broadly classify these mislabeled samples into two 30% 75.18 5560 99.34 5172 99.24 44264 categories:4(2%)nullfunctionsand19(9.5%)unimplemented 50% 75.25 5563 99.42 5194 99.26 44279 functions. Figure 3(B) shows a sample obtained in the FFM- 100% 75.30 5584 99.44 5195 99.28 44217 Peg+Qemu dataset with an empty function for this code(B) Empty function (A) T-SNE void kvm_arch_remove_all_hw_breakpoints(void) { } (C) Incomplete function static int check_video_codec_tag(int codec_tag) { if (codec_tag <= 0 || codec_tag > 15) { return AVERROR(ENOSYS); } else return 0; } Fig. 3: (A) illustrates the T-SNE [55] distribution between vulnerable (pink), high-quality non-vulnerable samples (blue), unlabeled (grey) and part of noisy examples (dark blue) in the FFMPeg+Qemu dataset. (B) and (C) denote the two different types of incorrectly labeled samples, respectively. sample. This sample does not have any syntax errors, but belsbeforeusage.Specifically,PILOTincorporatesadistance- is mislabeled as positive. Figure 3(C) shows an example aware label selection module, which generates pseudo-labels of the unimplemented function, which does not involve any to assist in evaluating the quality of non-vulnerable labels. vulnerability but is labeled as positive in the dataset. The (3) Treatment of the Data Scarcity Issue. Another case analysis shows that PILOT is able to well leverage the noteworthy aspect of PILOT is its ability to achieve high mislabeled data for more accurate vulnerability detection. performancewithonlyasmallamountoflabeleddata.Trovon relies on a large amount of labeled data to build the classifier. B. Comparison with Trovon Conversely,PILOTutilizesasemi-supervisedlearningmethod TherecentapproachTrovon[56]alsoaimsatmitigatingthe that demands only a limited number of labeled data. PILOT data noise issue in vulnerability detection. It trains a Seq2seq involves an inter-class distance prototype component derived model [57] based on the code fragment pairs (i.e., the pairs fromasmallpartofhigh-qualitypositivedata.Subsequently,it of vulnerable and fixed samples). Our proposed PILOT is involvesaprogressivefine-tuningprocessforfurtherlearning. essentially different from Trovon in the following aspects: In summary, the proposed PILOT is novel in its method- (1) Training data. The approaches of Trovon [56] and ology design, and significantly different from Trovon in the PILOT exhibit significant disparities in the training data. trainingdata,handlingofthenoiseissue,andtreatmentofthe Trovon utilizes a training set that comprises both before-fix data scarcity issue. (vulnerable) and after-fix (non-vulnerable) pairs to construct C. Threats and Limitations a classifier, aiming at investigating the distinctions between these two sets. In contrast, PILOT only utilizes the vulnerable One threat to validity comes from the dataset we construct. samples as the training data based on the assumption that Following the positive and unlabeled learning setting, we non-vulnerable samples potentially contain noisy data [32], constructadatasetwithunknownlabelsontheexistingdataset [33]. Remarkably, PILOT pioneers the positive and unla- using only a portion of the positive labels. However, we do beled learning problem in the software vulnerability detection not use external unknown data. In the future, we will further field. The approach involves a distance-aware label selection collect a larger benchmark for evaluation. module and relies on high-quality vulnerable samples in the The second threat to validity is the implementation of training process. Furthermore, PILOT incorporates a mixed- baselines.Wetryourbesttoreplicatetheseweaklysupervised supervision representation learning module to continuously in the PU setting based on the open-source code and the train classifiers. These processes help mitigate the impact of original paper to achieve the best experimental results. noisy labels in vulnerability detection. Another validity to threat comes from the selection of (2) Handling of the Noise Issue. Trovon and PILOT positivesamples.Asweonlyuseapartofthepositivelabeled address the noise issue in different ways. Specifically, Trovon samples,theselectionofthesesamplesaffectstheperformance adopts a methodology to exclusively employ after-fix (non- of PILOT. We therefore repeatedly select these samples at vulnerable) and before-fix (vulnerable) samples for minimiz- random and take the average as the experimental results. ing noise within the training dataset. However, even after the VII. RELATEDWORK fixing process, latent vulnerabilities may still persist in the A. Software Vulnerability Detection data.ThiswasalsohighlightedinCroft’swork[32],whichre- vealed that non-vulnerable labels tend to be of subpar quality. Software vulnerability detection is critical for ensuring Therefore, PILOT evaluates the quality of non-vulnerable la- software security by identifying and mitigating potential se-curity risks. Nowadays, learning-based software vulnerability model, named PILOT. PILOT consists of a distance-aware detection, as opposed to program analysis methods [14]–[16], label selection for generating pseudo-labels and a mixed- [58], has been shown to be more effective in identifying supervision representation learning module to alleviate the more types and numbers of vulnerabilities. Learning-based influence of noise. Compared with the state-of-the-art meth-
vulnerability detection techniques can be broadly classified ods,theexperimentalresultsonthreepopulardatasetsvalidate intotwocategoriesbasedontherepresentationofsourcecode the effectiveness of PILOT in PU and supervised settings. In and the learning model utilized: sequence-based and graph- future, we will further collect a larger benchmark and obtain based methods. more data for vulnerability detection. Sequence-based vulnerability detection methods [59]–[63] Our source code as well as experimental data are available convert code into token sequences. For example, VulDeep- at: https://github.com/PILOT-VD-2023/PILOT. ecker [21] uses code gadgets as the granularity to train a classifier using a bidirectional (Bi)-LSTM network. Russell ACKNOWLEDGMENT et al.[22]utilizeConvolutionalNeuralNetworks(CNNs)and This research is supported by National Key R&D Pro- Recurrent Neural Networks (RNNs) to fuse different features gram of China (No. 2022YFB3103900), National Natural from function-level source code. SySeVR [20] extracts code Science Foundation of China under project (No. 62002084), gadgets by traversing AST generated from code and also uses Natural Science Foundation of Guangdong Province (Project a Bi-LSTM network. No. 2023A1515011959), Shenzhen Basic Research (General Graph-based methods [64]–[70] represent software code as Project No. JCYJ20220531095214031), and the Major Key graphs and use Graph Neutral Networks (GNNs) for software Project of PCL (Grant No. PCL2022A03). vulnerabilitydetection.CPGVA[71]combinestheAST,CFG, and DFG and generates the code property graph (CPG) to REFERENCES vulnerability detection. Devign adds Natural Code Sequence (NCS) to the CPG and leverages the Gated Graph Neutral [1] D. McKee et al., “Trellix advanced research center patches 61,000 vulnerableopen-sourceprojects–globalsecuritymagonline,”2023. Networks (GGNNs), which preserve the programming logic [2] G.Lin,S.Wen,Q.Han,J.Zhang,andY.Xiang,“Softwarevulnerability of the source code. detectionusingdeepneuralnetworks:Asurvey,”Proc.IEEE,vol.108, However, all these existing vulnerability detection methods no.10,pp.1825–1848,2020. [3] D. A. Wheeler, “Flawfinder,” [n.d.]. [Online]. Available: https: requirealargeamountoflabeledpositiveandnegativesamples //dwheeler.com/flawfinder/ andfailtoachievegoodperformancewithasmalllabeledsize. [4] Facebook,“Infer,”[n.d.].[Online].Available:https://fbinfer.com/. In this paper, we propose a positive and unlabeled learning [5] Israel,“Checkmarx,”[n.d.].[Online].Available:https://www.checkmarx. com/. model for vulnerability detection for the scenarios without [6] V. Nguyen, D. Q. Nguyen, V. Nguyen, T. Le, Q. H. Tran, and D. Q. enough labeled data. Phung, “Regvd: Revisiting graph neural networks for vulnerability detection,”CoRR,vol.abs/2110.07317,2021. B. PU Learning [7] Y. Li, S. Wang, and T. N. Nguyen, “Vulnerability detection with fine- grained interpretations,” in ESEC/SIGSOFT FSE. ACM, 2021, pp. Positive and Unlabeled (PU) learning setting is a weakly 292–303. supervised learning scenario that aims to learn a classifier [8] D. Hin, A. Kan, H. Chen, and M. A. Babar, “Linevd: Statement-level vulnerability detection using graph neural networks,” in MSR. ACM, with only positive and unlabeled samples [34], [72]–[75]. An 2022,pp.596–607. effective approach [76]–[78] considers unlabeled samples as [9] S.Cao,X.Sun,L.Bo,R.Wu,B.Li,andC.Tao,“MVD:memory-related negative samples with noise, and it is common practice to vulnerabilitydetectionbasedonflow-sensitivegraphneuralnetworks,” assign small weights to them. For instance, Lee et al. [79] CoRR,vol.abs/2203.02660,2022. [10] S. Gao, C. Gao, C. Wang, J. Sun, D. Lo, and Y. Yu, “Two sides use weighted logistic regression to learn from positive and of the same coin: Exploiting the impact of identifiers in neural code unlabeled examples. Another popular approach [80]–[82] in- comprehension,” in 45th IEEE/ACM International Conference on Soft- volvesincorporatingknowledgeofclasspriorsintothetraining wareEngineering,ICSE2023,Melbourne,Australia,May14-20,2023. IEEE,2023,pp.1933–1945. process, which adjusts the decision threshold of the classifier [11] A. Inc, “Clang static analyzer,” [n.d.]. [Online]. Available: https: based on the estimated class prior probabilities. Ward et //clang-analyzer.llvm.org/scan-build.html al. [83] propose an expectation-maximization algorithm by [12] J. Viega, J. T. Bloch, Y. Kohno, and G. McGraw, “ITS4: A static vulnerability scanner for C and C++ code,” in 16th Annual Computer classprior.Bekkeretal.[84]proposeadecisiontreeinduction SecurityApplicationsConference(ACSAC2000),11-15December2000, methodforstraightforwardandefficientclasspriorestimation. NewOrleans,Louisiana,USA. IEEEComputerSociety,2000,p.257. In this paper, we propose a novel PU setting on software [13] Y. Sui and J. Xue, “SVF: interprocedural static value-flow analysis in LLVM,” in Proceedings of the 25th International Conference on vulnerabilitydetection.Wealsoproposeadistance-awarelabel CompilerConstruction,CC2016,Barcelona,Spain,March12-18,2016,
selection module for correctly providing pseudo-label and a A.ZaksandM.V.Hermenegildo,Eds. ACM,2016,pp.265–266. mixed-supervision representation learning module for better [14] J.Pewny,F.Schuster,L.Bernhard,T.Holz,andC.Rossow,“Leveraging semanticsignaturesforbugsearchinbinaryprograms,”inProceedings alleviating the influence of noise. ofthe30thAnnualComputerSecurityApplicationsConference,ACSAC 2014. ACM,2014,pp.406–415. VIII. CONCLUSION [15] G. Portokalidis, A. Slowinska, and H. Bos, “Argos: an emulator for fingerprintingzero-dayattacksforadvertisedhoneypotswithautomatic This paper focuses on the positive and unlabeled learning signaturegeneration,”inProceedingsofthe2006EuroSysConference, problem for vulnerability detection and proposes a novel Leuven,Belgium,April18-21,2006. ACM,2006,pp.15–27.[16] R.Baldoni,E.Coppa,D.C.D’Elia,C.Demetrescu,andI.Finocchi,“A [32] R. Croft, Y. Xie, and M. A. Babar, “Data preparation for software surveyofsymbolicexecutiontechniques,”ACMComput.Surv.,vol.51, vulnerability prediction: A systematic literature review,” IEEE Trans. no.3,pp.50:1–50:39,2018. SoftwareEng.,vol.49,no.3,pp.1044–1063,2023. [17] D.LarochelleandD.Evans,“Staticallydetectinglikelybufferoverflow [33] R.Croft,M.A.Babar,andH.Chen,“Noisylabellearningforsecurity vulnerabilities,” in 10th USENIX Security Symposium, August 13-17, defects,” in 19th IEEE/ACM International Conference on Mining Soft- 2001,Washington,D.C.,USA,D.S.Wallach,Ed. USENIX,2001. wareRepositories,MSR2022,Pittsburgh,PA,USA,May23-24,2022. [18] S. W. Boyd and A. D. Keromytis, “Sqlrand: Preventing SQL injec- ACM,2022,pp.435–447. tion attacks,” in Applied Cryptography and Network Security, Second [34] J. Bekker and J. Davis, “Learning from positive and unlabeled data: a International Conference, ACNS 2004, Yellow Mountain, China, June survey,”Mach.Learn.,vol.109,no.4,pp.719–760,2020. 8-11, 2004, Proceedings, ser. Lecture Notes in Computer Science, [35] E. Cole, O. M. Aodha, T. Lorieul, P. Perona, D. Morris, and N. Jojic, M.Jakobsson,M.Yung,andJ.Zhou,Eds.,vol.3089. Springer,2004, “Multi-label learning from single positive labels,” in IEEE Conference pp.292–302. onComputerVisionandPatternRecognition,CVPR2021,virtual,June [19] X. Cheng, G. Zhang, H. Wang, and Y. Sui, “Path-sensitive code 19-25,2021. ComputerVisionFoundation/IEEE,2021,pp.933–942. embeddingviacontrastivelearningforsoftwarevulnerabilitydetection,” [36] O. Pantazis, G. J. Brostow, K. E. Jones, and O. M. Aodha, “Focus on inISSTA’22:31stACMSIGSOFTInternationalSymposiumonSoftware the positives: Self-supervised learning for biodiversity monitoring,” in Testing and Analysis, Virtual Event, South Korea, July 18 - 22, 2022, 2021 IEEE/CVF International Conference on Computer Vision, ICCV S.RyuandY.Smaragdakis,Eds. ACM,2022,pp.519–531. 2021,Montreal,QC,Canada,October10-17,2021. IEEE,2021,pp. [20] Z.Li,D.Zou,S.Xu,H.Jin,Y.Zhu,andZ.Chen,“Sysevr:Aframework 10563–10572. forusingdeeplearningtodetectsoftwarevulnerabilities,”IEEETrans. [37] C. Elkan and K. Noto, “Learning classifiers from only positive and DependableSecur.Comput.,vol.19,no.4,pp.2244–2258,2022. unlabeleddata,”inProceedingsofthe14thACMSIGKDDInternational [21] Z.Li,D.Zou,S.Xu,X.Ou,H.Jin,S.Wang,Z.Deng,andY.Zhong, Conference on Knowledge Discovery and Data Mining, Las Vegas, “Vuldeepecker: A deep learning-based system for vulnerability de- Nevada,USA,August24-27,2008,Y.Li,B.Liu,andS.Sarawagi,Eds. tection,” in 25th Annual Network and Distributed System Security ACM,2008,pp.213–220. Symposium,NDSS2018,SanDiego,California,USA,February18-21, [38] B.Liu,W.S.Lee,P.S.Yu,andX.Li,“Partiallysupervisedclassification 2018. TheInternetSociety,2018. oftextdocuments,”inMachineLearning,ProceedingsoftheNineteenth [22] R. L. Russell, L. Y. Kim, L. H. Hamilton, T. Lazovich, J. Harer, InternationalConference(ICML2002),UniversityofNewSouthWales, O.Ozdemir,P.M.Ellingwood,andM.W.McConley,“Automatedvul- Sydney, Australia, July 8-12, 2002, C. Sammut and A. G. Hoffmann, nerabilitydetectioninsourcecodeusingdeeprepresentationlearning,” Eds. MorganKaufmann,2002,pp.387–394. inICMLA. IEEE,2018,pp.757–762. [39] G.Blanchard,G.Lee,andC.Scott,“Semi-supervisednoveltydetection,” [23] Y.Zhou,S.Liu,J.K.Siow,X.Du,andY.Liu,“Devign:Effectivevulner- J.Mach.Learn.Res.,vol.11,pp.2973–3009,2010. abilityidentificationbylearningcomprehensiveprogramsemanticsvia [40] X.LiandB.Liu,“Learningtoclassifytextsusingpositiveandunlabeled graphneuralnetworks,”inAdvancesinNeuralInformationProcessing data,” in IJCAI-03, Proceedings of the Eighteenth International Joint Systems 32: Annual Conference on Neural Information Processing Conference on Artificial Intelligence, Acapulco, Mexico, August 9-15, Systems2019,NeurIPS2019,2019,pp.10197–10207.
2003, G. Gottlob and T. Walsh, Eds. Morgan Kaufmann, 2003, pp. [24] S.Chakraborty,R.Krishna,Y.Ding,andB.Ray,“Deeplearningbased 587–594. vulnerabilitydetection:Arewethereyet?”CoRR,vol.abs/2009.07235, [41] K. Pelckmans and J. A. K. Suykens, “Transductively learning from 2020. positive examples only,” in 17th European Symposium on Artificial [25] C.Cummins,Z.V.Fisches,T.Ben-Nun,T.Hoefler,M.F.P.O’Boyle, Neural Networks, ESANN 2009, Bruges, Belgium, April 22-24, 2009, and H. Leather, “Programl: A graph-based program representation for Proceedings,2009. data flow analysis and compiler optimizations,” in Proceedings of the [42] C. Gong, T. Liu, J. Yang, and D. Tao, “Large-margin label-calibrated 38th International Conference on Machine Learning, ICML 2021, 18- support vector machines for positive and unlabeled learning,” IEEE 24 July 2021, Virtual Event, ser. Proceedings of Machine Learning Trans. Neural Networks Learn. Syst., vol. 30, no. 11, pp. 3471–3483, Research, M. Meila and T. Zhang, Eds., vol. 139. PMLR, 2021, pp. 2019. 2244–2253. [43] H.Assal,S.Chiasson,andR.Biddle,“Cesar:Visualrepresentationof [26] X.Huo,M.Li,andZ.Zhou,“Controlflowgraphembeddingbasedon sourcecodevulnerabilities,”in13thIEEESymposiumonVisualization multi-instancedecompositionforbuglocalization,”inTheThirty-Fourth forCyberSecurity,VizSec2016,Baltimore,MD,USA,October24,2016, AAAI Conference on Artificial Intelligence, AAAI 2020, The Thirty- D.M.Best,D.Staheli,N.Prigent,S.Engle,andL.Harrison,Eds. IEEE Second Innovative Applications of Artificial Intelligence Conference, ComputerSociety,2016,pp.1–8. IAAI 2020, The Tenth AAAI Symposium on Educational Advances in ArtificialIntelligence,EAAI2020,NewYork,NY,USA,February7-12, [44] “Dividebyzero,”[n.d.].[Online].Available:https://cwe.mitre.org/data/ 2020. AAAIPress,2020,pp.4223–4230. definitions/369.html [27] Z. Han, X. Li, Z. Xing, H. Liu, and Z. Feng, “Learning to predict [45] X. Cheng, X. Nie, N. Li, H. W. Z. Zheng, and Y. Sui, “How about severityofsoftwarevulnerabilityusingonlyvulnerabilitydescription,” bug-triggering paths?-understanding and characterizing learning-based in 2017 IEEE International Conference on Software Maintenance and vulnerabilitydetectors.” IEEE,2022. Evolution, ICSME 2017, Shanghai, China, September 17-22, 2017. [46] D. Zou, S. Wang, S. Xu, Z. Li, and H. Jin, “µvuldeepecker: A deep IEEEComputerSociety,2017,pp.125–136. learning-based system for multiclass vulnerability detection,” IEEE [28] N.Jovanovic,C.Kruegel,andE.Kirda,“Precisealiasanalysisforstatic Trans.DependableSecur.Comput.,vol.18,no.5,pp.2224–2236,2021. detectionofwebapplicationvulnerabilities,”inProceedingsofthe2006 [47] Z. Feng, D. Guo, D. Tang, N. Duan, X. Feng, M. Gong, L. Shou, WorkshoponProgrammingLanguagesandAnalysisforSecurity,PLAS B. Qin, T. Liu, D. Jiang, and M. Zhou, “Codebert: A pre-trained 2006, Ottawa, Ontario, Canada, June 10, 2006, V. C. Sreedhar and model for programming and natural languages,” in Findings of the S.Zdancewic,Eds. ACM,2006,pp.27–36. AssociationforComputationalLinguistics:EMNLP2020,OnlineEvent, [29] J. Fan, Y. Li, S. Wang, and T. N. Nguyen, “A C/C++ code vulnera- 16-20November2020,ser.FindingsofACL,T.Cohn,Y.He,andY.Liu, bility dataset with code changes and CVE summaries,” in MSR ’20: Eds., vol. EMNLP 2020. Association for Computational Linguistics, 17thInternationalConferenceonMiningSoftwareRepositories,Seoul, 2020,pp.1536–1547. RepublicofKorea,29-30June,2020,S.Kim,G.Gousios,S.Nadi,and [48] S.Lu,D.He,C.Xiong,G.Ke,W.Malik,Z.Dou,P.Bennett,T.Liu, J.Hejderup,Eds. ACM,2020,pp.508–512. andA.Overwijk,“Lessismore:Pretrainastrongsiameseencoderfor [30] Y. Zheng, S. Pujar, B. L. Lewis, L. Buratti, E. A. Epstein, B. Yang, densetextretrievalusingaweakdecoder,”inProceedingsofthe2021 J. Laredo, A. Morari, and Z. Su, “D2A: A dataset built for ai-based Conference on Empirical Methods in Natural Language Processing, vulnerability detection methods using differential analysis,” in 43rd EMNLP 2021, Virtual Event / Punta Cana, Dominican Republic, 7-11 IEEE/ACMInternationalConferenceonSoftwareEngineering:Software November,2021,M.Moens,X.Huang,L.Specia,andS.W.Yih,Eds. EngineeringinPractice,ICSE(SEIP)2021,Madrid,Spain,May25-28, AssociationforComputationalLinguistics,2021,pp.2780–2791. 2021. IEEE,2021,pp.111–120. [49] K.He,H.Fan,Y.Wu,S.Xie,andR.B.Girshick,“Momentumcontrast [31] R.Croft,M.A.Babar,andM.M.Kholoosi,“Dataqualityforsoftware for unsupervised visual representation learning,” in 2020 IEEE/CVF vulnerabilitydatasets,”CoRR,vol.abs/2301.05456,2023. ConferenceonComputerVisionandPatternRecognition,CVPR2020,Seattle, WA, USA, June 13-19, 2020. Computer Vision Foundation / [70] X.Wen,C.Gao,J.Ye,Z.Tian,Y.Jia,andX.Wang,“Meta-pathbased
IEEE,2020,pp.9726–9735. attentionalgraphlearningmodelforvulnerabilitydetection,”CoRR,vol. [50] X.Li,B.Liu,andS.Ng,“Negativetrainingdatacanbeharmfultotext abs/2212.14274,2022. classification,”inEMNLP. ACL,2010,pp.218–228. [71] X.Wang,T.Zhang,R.Wu,W.Xin,andC.Hou,“CPGVA:codeproperty [51] M.C.duPlessis,G.Niu,andM.Sugiyama,“Analysisoflearningfrom graphbasedvulnerabilityanalysisbydeeplearning,”inICAIT. IEEE, positiveandunlabeleddata,”inNIPS,2014,pp.703–711. 2018,pp.184–188. [52] R. Kiryo, G. Niu, M. C. du Plessis, and M. Sugiyama, “Positive- [72] S.S.KhanandM.G.Madden,“One-classclassification:taxonomyof unlabeled learning with non-negative risk estimator,” in NIPS, 2017, study and review of techniques,” Knowl. Eng. Rev., vol. 29, no. 3, pp. pp.1675–1685. 345–374,2014. [53] X.Chen,W.Chen,T.Chen,Y.Yuan,C.Gong,K.Chen,andZ.Wang, [73] M.Claesen,F.D.Smet,P.Gillard,C.Mathieu,andB.D.Moor,“Build- “Self-pu: Self boosted and calibrated positive-unlabeled training,” in ingclassifierstopredictthestartofglucose-loweringpharmacotherapy ICML, ser. Proceedings of Machine Learning Research, vol. 119. using belgian health expenditure data,” CoRR, vol. abs/1504.07389, PMLR,2020,pp.1510–1519. 2015. [54] G. Du, J. Zhang, M. Jiang, J. Long, Y. Lin, S. Li, and K. C. Tan, [74] K. Zupanc and J. Davis, “Estimating rule quality for knowledge base “Graph-basedclass-imbalancelearningwithlabelenhancement,”IEEE completionwiththerelationshipbetweencoverageassumption,”inPro- TransactionsonNeuralNetworksandLearningSystems,pp.1–15,2021. ceedingsofthe2018WorldWideWebConferenceonWorldWideWeb, [55] V.derMaaten,Laurens,andH.Geoffrey,“Visualizingdatausingt-sne.” WWW2018,Lyon,France,April23-27,2018,P.Champin,F.Gandon, Journalofmachinelearningresearch,vol.9,no.11,2008. M.Lalmas,andP.G.Ipeirotis,Eds. ACM,2018,pp.1073–1081. [56] A.Garg,R.Degiovanni,M.Jimenez,M.Cordy,M.Papadakis,andY.L. [75] Z.WuandJ.He,“Fairness-awaremodel-agnosticpositiveandunlabeled Traon, “Learning from what we know: How to perform vulnerability learning,”inFAccT’22:2022ACMConferenceonFairness,Account- predictionusingnoisyhistoricaldata,”Empir.Softw.Eng.,vol.27,no.7, ability,andTransparency,Seoul,RepublicofKorea,June21-24,2022. p.169,2022. ACM,2022,pp.1698–1708. [57] M.Abadi,A.Agarwal,P.Barham,E.Brevdo,Z.Chen,C.Citro,G.S. [76] T. Ke, B. Yang, L. Zhen, J. Tan, Y. Li, and L. Jing, “Building high- Corrado,A.Davis,J.Dean,M.Devin,S.Ghemawat,I.J.Goodfellow, performance classifiers using positive and unlabeled examples for text A.Harp,G.Irving,M.Isard,Y.Jia,R.Jo´zefowicz,L.Kaiser,M.Kudlur, classification,” in Advances in Neural Networks - ISNN 2012 - 9th J. Levenberg, D. Mane´, R. Monga, S. Moore, D. G. Murray, C. Olah, International Symposium on Neural Networks, Shenyang, China, July M.Schuster,J.Shlens,B.Steiner,I.Sutskever,K.Talwar,P.A.Tucker, 11-14, 2012. Proceedings, Part II, ser. Lecture Notes in Computer V. Vanhoucke, V. Vasudevan, F. B. Vie´gas, O. Vinyals, P. Warden, Science, J. Wang, G. G. Yen, and M. M. Polycarpou, Eds., vol. 7368. M. Wattenberg, M. Wicke, Y. Yu, and X. Zheng, “Tensorflow: Large- Springer,2012,pp.187–195. scale machine learning on heterogeneous distributed systems,” CoRR, [77] T.Ke,L.Jing,H.Lv,L.Zhang,andY.Hu,“Globalandlocallearning vol.abs/1603.04467,2016. frompositiveandunlabeledexamples,”Appl.Intell.,vol.48,no.8,pp. [58] J. Jang, M. Woo, and D. Brumley, “Redebug: Finding unpatched code 2373–2392,2018. clones in entire OS distributions,” login Usenix Mag., vol. 37, no. 6, [78] C. Hsieh, N. Natarajan, and I. S. Dhillon, “PU learning for matrix 2012. completion,” in Proceedings of the 32nd International Conference on [59] H. K. Dam, T. Tran, T. Pham, S. W. Ng, J. Grundy, and A. Ghose, MachineLearning,ICML2015,Lille,France,6-11July2015,ser.JMLR “Automatic feature learning for vulnerability prediction,” CoRR, vol. WorkshopandConferenceProceedings,F.R.BachandD.M.Blei,Eds., abs/1708.02368,2017. vol.37. JMLR.org,2015,pp.2445–2453. [60] F.Wu,J.Wang,J.Liu,andW.Wang,“Vulnerabilitydetectionwithdeep [79] W.S.LeeandB.Liu,“Learningwithpositiveandunlabeledexamples learning,”in20173rdIEEEInternationalConferenceonComputerand usingweightedlogisticregression,”inICML. AAAIPress,2003,pp. Communications(ICCC),2017,pp.1298–1302. 448–455. [61] G.Grieco,G.L.Grinblat,L.C.Uzal,S.Rawat,J.Feist,andL.Mounier, [80] C. Scott, “A rate of convergence for mixture proportion estimation,
“Towardlarge-scalevulnerabilitydiscoveryusingmachinelearning,”in with application to learning from noisy labels,” in Proceedings of CODASPY. ACM,2016,pp.85–96. the Eighteenth International Conference on Artificial Intelligence and [62] X.Li,L.Wang,Y.Xin,Y.Yang,andY.Chen,“Automatedvulnerability Statistics,AISTATS2015,SanDiego,California,USA,May9-12,2015, detection in source code using minimum intermediate representation ser. JMLR Workshop and Conference Proceedings, G. Lebanon and learning,”AppliedSciences,vol.10,no.5,2020. S.V.N.Vishwanathan,Eds.,vol.38. JMLR.org,2015. [63] C. Wang, Y. Yang, C. Gao, Y. Peng, H. Zhang, and M. R. Lyu, “No [81] S. Jain, M. White, M. W. Trosset, and P. Radivojac, “Nonpara- morefine-tuning?anexperimentalevaluationofprompttuningincode metric semi-supervised learning of class proportions,” CoRR, vol. intelligence,”inProceedingsofthe30thACMJointEuropeanSoftware abs/1601.01944,2016. EngineeringConferenceandSymposiumontheFoundationsofSoftware [82] S. Jain, M. White, and P. Radivojac, “Estimating the class prior and Engineering,ESEC/FSE2022,Singapore,Singapore,November14-18, posterior from noisy positives and unlabeled data,” in Advances in 2022,A.Roychoudhury,C.Cadar,andM.Kim,Eds. ACM,2022,pp. Neural Information Processing Systems 29: Annual Conference on 382–394. Neural Information Processing Systems 2016, December 5-10, 2016, [64] Y.Wu,D.Zou,S.Dou,W.Yang,D.Xu,andH.Jin,“Vulcnn:Animage- Barcelona,Spain,2016,pp.2685–2693. inspiredscalablevulnerabilitydetectionsystem,”inICSE. ACM,2022, [83] G.Ward,T.Hastie,S.Barry,J.Elith,andJ.R.Leathwick,“Presence- pp.2365–2376. onlydataandtheemalgorithm,”Biometrics,vol.65,no.2,pp.554–563, [65] X.Duan,J.Wu,S.Ji,Z.Rui,T.Luo,M.Yang,andY.Wu,“Vulsniper: 2009. Focus your attention to shoot fine-grained vulnerabilities,” in IJCAI. [84] J. Bekker and J. Davis, “Estimating the class prior in positive and ijcai.org,2019,pp.4665–4671. unlabeleddatathroughdecisiontreeinduction,”inAAAI. AAAIPress, [66] H.Wang,G.Ye,Z.Tang,S.H.Tan,S.Huang,D.Fang,Y.Feng,L.Bian, 2018,pp.2712–2719. and Z. Wang, “Combining graph-based learning with automated data collectionforcodevulnerabilitydetection,”IEEETrans.Inf.Forensics Secur.,vol.16,pp.1943–1958,2021. [67] A. V. Phan, M. L. Nguyen, and L. T. Bui, “Convolutional neural networks over control flow graphs for software defect prediction,” in ICTAI. IEEEComputerSociety,2017,pp.45–52. [68] S. Cao, X. Sun, L. Bo, Y. Wei, and B. Li, “BGNN4VD: Construct- ingbidirectionalgraphneural-networkforvulnerabilitydetection,”Inf. Softw.Technol.,vol.136,p.106576,2021. [69] X. Wen, Y. Chen, C. Gao, H. Zhang, J. M. Zhang, and Q. Liao, “Vulnerability detection with graph simplification and enhanced graph representation learning,” in 45th IEEE/ACM International Conference on Software Engineering, ICSE 2023, Melbourne, Australia, May 14- 20,2023. IEEE,2023,pp.2275–2286.
2308.11161 Adversarial Attacks on Code Models with Discriminative Graph Patterns Thanh-DatNguyen YangZhou Xuan-BachD.Le UniversityofMelbourne SingaporeManagementUniversity UniversityofMelbourne Melbourne,Australia Singapore,Singapore Melbourne,Australia thanhdatn@student.unimelb.edu.au zyang@smu.edu.sg back.le@unimelb.edu.au Patanamon(Pick) DavidLo Thongtanunam SingaporeManagementUniversity UniversityofMelbourne Singapore,Singapore Melbourne,Australia davidlo@smu.edu.sg patanamon.t@unimelb.edu.au ABSTRACT achievedanASRof0.841,significantlyoutperformingCARROT Pre-trainedlanguagemodelsofcodearenowwidelyusedinvarious andALERT(withASRof0.598and0.615respectively). softwareengineeringtaskssuchascodegeneration,codecomple- KEYWORDS tion,vulnerabilitydetection,etc.This,inturn,posessecurityand reliabilityriskstothesemodels.Oneoftheimportantthreatsis Pre-trainedLanguageModelofCode,AdversarialAttack,Discrim- adversarialattacks,whichcanleadtoerroneouspredictionsand inativeSubgraphMining largelyaffectmodelperformanceondownstreamtasks,necessi- ACMReferenceFormat: tatingathoroughstudyofadversarialrobustnessoncodemodels. Currentadversarialattacksoncodemodelsusuallyadoptfixedsets Thanh-DatNguyen,YangZhou,Xuan-BachD.Le,Patanamon(Pick)Thong- tanunam,andDavidLo.2023.AdversarialAttacksonCodeModelswith ofprogramtransformations,suchasvariablerenaminganddead DiscriminativeGraphPatterns.InProceedingsofACMConference(Con- codeinsertion.Additionally,experteffortsarerequiredtohandcraft ference’17).ACM,NewYork,NY,USA,13pages.https://doi.org/10.1145/ thesetransformationsandarelimitedintermsofcreatingmore nnnnnnn.nnnnnnn complexsemantic-preservingtransformations. Toaddresstheaforementionedchallenges,weproposeanovel 1 INTRODUCTION adversarialattackframework,GraphCodeAttack,tobettereval- uatetherobustnessofcodemodels.Givenatargetcodemodel, Codemodels[11,23,39],especiallythosebuiltonadvanceddeep GraphCodeAttackautomaticallyminesimportantcodepatterns, learningarchitectures,havebecomeincreasinglypopularrecently whichcaninfluencethemodel’sdecisions,toperturbthestructure duetotheirabilitytoeffectivelycomprehendprogramminglan- of input code to the model. To do so, GraphCodeAttack uses guagesbylearningfromlarge-scalecodedata[13,16,49].These a setof input sourcecodes to probethe model’soutputs. From modelshavebeenemployedanddemonstratedstrongperformance thesesourcecodesandoutputs,GraphCodeAttackidentifiesthe invariousapplications,includingcodecompletion[27],vulner- discriminative ASTs patterns that can influence the model deci- abilitydetection[56],authorshipattribution[4],andcodeclone sions.GraphCodeAttackthenselectsappropriateASTpatterns, detection[29].Despitetheirsuccess,recentstudieshaveshown concretizestheselectedpatternsasattacks,andinsertsthemas thatcodemodelsarenotrobusttoadversarialperturbations[50,53] deadcodeintothemodel’sinputprogram.Toeffectivelysynthesize –i.e.,semantic-preservingtransformations(e.g.,renamingthevari- attacksfromASTpatterns,GraphCodeAttackusesaseparate ablesoraddingsomedeadcode)oftheinput,thatmakeacode pre-trainedcodemodeltofillintheASTswithconcretecodesnip- modelchangepredictionsfromcorrecttowrong. pets.Weevaluatetherobustnessoftwopopularcodemodels(e.g., Thevulnerabilityofcodemodelstoadversarialperturbations CodeBERTandGraphCodeBERT)againstourproposedapproach can have serious implications for the security and reliability of onthreetasks:AuthorshipAttribution,VulnerabilityPrediction, downstreamtasksthatemploythesemodels.Considerascenario andCloneDetection.Theexperimentalresultssuggestthatour where a code model is integrated into an open-source library’s proposedapproachsignificantlyoutperformsstate-of-the-artap- contributionreviewprocesstodetectandpreventtheinclusion proachesinattackingcodemodelssuchasCARROTandALERT. ofvulnerableormaliciouscode.Inthissituation,ill-intentioned Basedontheaverageattacksuccessrate(ASR),GraphCodeAttack actorscouldcraftadversarialperturbationstoexploittheweak- achieved30%improvementoverCARROTand33%improvement nessesofthecodemodel,therebycausingittofalselyaccepttheir overALERTrespectively.Notably,intermsofASRonGraphCode- maliciouscontributions[24].Asaconsequence,thelibrarycould BERTmodelandonAuthorshipAttribution,GraphCodeAttack unknowinglyincorporatesecurityvulnerabilitiesorharmfulcode, leadingtosignificantrisksforthelibrary’susersandpotentially damagingthereputationoftheprojectmaintainers.Thisthreat Conference’17,July2017,Washington,DC,USA modelhighlightstheimportanceofassessingandenhancingthe 2023.ACMISBN978-x-xxxx-xxxx-x/YY/MM...$15.00 https://doi.org/10.1145/nnnnnnn.nnnnnnn robustnessofcodemodelsagainstadversarialattacks. 3202 guA 22 ]ES.sc[ 1v16111.8032:viXraConference’17,July2017,Washington,DC,USA Thanh-DatNguyen,YangZhou,Xuan-BachD.Le,Patanamon(Pick)Thongtanunam,andDavidLo Inthispaper,weevaluatethecodemodelrobustnessinablack- codemodelattackssuchasCARROTandALERT.Basedontheav-
boxsetting:theattackeronlyhasaccesstothemodel’soutputand erageattacksuccessrate(ASR),GraphCodeAttackachieved30% cannotaccesstheinternalinformation(e.g.,parameterandgradi- improvementoverCARROTand33%improvementoverALERT entinformation)ofthevictimmodel,northegroundtruthlabel. respectively.Notably,ontheGraphCodeBERTmodelandonAu- Theblack-boxassumptionisrealisticassuchcodemodelsareusu- thorshipAttribution,GraphCodeAttackachievedascoreof0.84 allydeployedremotelyandcanbeaccessedbyAPIs.Manyrecent intermsofaverageASR. works[19,50,52,53]alsoadoptthesameassumption.ALERT[50] Insummary,wepresentGraphCodeAttack,anovelapproach andCARROT[53]arestate-of-the-arttechniquesforadversarial forattackingmodelsofcodebysynthesizingadversarialexamples attacksoncodemodels.Theyfocusonusingafixedsetofhand- fromattackpatternsthatareautomaticallyminedfromasetofprob- craftedpatternstotransformtheinputsofcodemodels.ALERT[50] ingdataandthecorrespondingmodel’soutput.Ourcontributions usesvariablerenamingandCARROT[53]usesadditionaltransfor- canbesummarizedasfollows: mations,e.g.,addingdead-codewithmanually-designedpatterns • OurnovelapproachGraphCodeAttackautomaticallymines such as while(false), if(false), etc. Attacking code models attackpatternsfromamodelandthesetofprobingdata, usinghand-cratedtransformations,however,presentscertainlimi- renderingthederivedattacksflexiblyadaptabletospecific tations.Particularly,thehand-craftedpatternsmaynotstayabreast targetmodelsanddomains. offastlygrowingdatasetstoadequatelyrepresentthediverserange • Weintroduceanovelmethodthatleveragespre-trainedlan- ofreal-worldcodestructuresandmayhavelimitationsinmodeling guagemodelstoautomaticallygenerateeffectiveconcreteat- complexsemantic-preservingtransformations.Hence,thereisa tacksfromdiscoveredabstractASTpatterns.Incomparison needforanautomatedandsystematicprocessofidentifyingpoten- withCARROT’srandomidentifierrenamingandALERT’s tialadversarialattacks,whichwillenablethedevelopersthoroughly code-model-basedidentifierrenaming,GraphCodeAttack testandassurethereliabilityofthecodemodelbeforereleasingit surpassestheirperformancein5outofthe6task-and-model totheusers. combinationsevaluated. WeintroduceGraphCodeAttack,anovelapproachtoattack • Wedemonstratetheeffectivenessofourapproachthrough modelsofcodebyusingautomaticallymined codepatternsthat extensiveexperiments,showingthatGraphCodeAttack canhighlyinfluenceatargetmodel’sdecisions.Doingsoallows cansuccessfullysynthesizeadversarialexamplesthatchal- GraphCodeAttacktoflexiblyadapttodifferentcodemodelswith lengetherobustnessandreliabilityofcodemodels.Particu- varyingtrainingdata,asopposedtotheuseofhandcraftedtrans- larly,GraphCodeAttackachieved30%improvementover formationsbycurrentstate-of-the-artapproaches.Givenatarget CARROTand33%improvementoverALERTonaverage modelofcodeandasetofprobingdata(i.e.,asetofdataused ASRmeasurement.Notably,ontheGraphCodeBERTmodel, totestthemodel’soutput),GraphCodeAttackworksinthree GraphCodeAttackachieved0.84and0.799intermsofASR phases: mining highly influential patterns, synthesizing attacks onAuthorshipAttributionandVulnerabilityPredictionre- frompatterns,andselectingappropriateattacks. spectively. GraphCodeAttackfirstautomaticallyidentifiesdiscriminative ASTpatternsfromtheprobingdata(i.e.,programs’sourcecode) Therestofthepaperisorganizedasfollows:Section2provides thathighlyinfluencethetargetmodel’sprediction.Toachievethis, backgroundoncodemodels,adversarialattacks,andabstractsyntax weemployadiscriminativesubgraphminingtechnique,namely trees.Section3detailstheproposedGraphCodeAttackmethod- thegspan-CORKalgorithm[46].Thisallowsustofindfrequent ology,includingtheprocessofminingASTpatterns,andtheusage subgraphsorpatternsinthedatathatarediscriminativebetween of pre-trained language models for pattern insertion. Section 7 differentclassesorgroupsofdata.Second,GraphCodeAttack presentstherelatedworksontheproblemofadversarialattack synthesizesconcreteattacksbasedonthepatternsminedinthe onthemodelofcode.Sections4and5describeourexperiment previousstep.NotethattheminedASTpatternsprimarilycontain settingsandtheresultsrespectively. structuralinformation,suchasnodetypesandedgetypes,without anyactualconcretecontent(e.g.,specificidentifiersorparticular 2 BACKGROUND binaryoperationsamongexpressionslike+, -,etc.).Tofillthisgap, Inthissection,weprovideessentialbackgroundinformationon weleveragealanguagemodel,whichisdifferentfromthemodel codemodelsandtheuseofAbstractSyntaxTrees(ASTs)forgraph underattack,tosynthesizeconcretecodefromabstractpatterns. mining techniques that form the basis of our proposed system Largelanguagemodels,suchasCodeBERT[13]andCodeT5[8], architectureforattackingcodemodels. havedemonstratedcapabilitiesincompletingcodespansthatare contextuallycoherent.Wethusleveragethesemodelsfortheattack 2.1 CodeModels synthesisstep.GraphCodeAttackthensearchesthroughthesyn- thesizedconcreteattackstofindappropriateattackstobeinserted Code models [13, 16] are machine learning models designed to
intoagivenprogramasinputtothetargetmodel. analyze,understand,andgeneratesourcecode.Theyplayacrucial Weevaluatetherobustnessoftwopopularcodemodels(e.g., roleinvarioussoftwareengineeringtasks,suchascodecompletion, CodeBERTandGraphCodeBERT)againstourproposedapproach codesummarization,bugdetection,andvulnerabilityidentification. onthreetasks:AuthorshipAttribution,VulnerabilityPrediction, Recentadvancesindeeplearninghaveledtothedevelopmentof andCloneDetection.Experimentssuggestthatourproposedap- moresophisticatedcodemodels,suchasTransformer-basedmod- proach significantly outperforms state-of-the-art approaches in els, that can capture complex patterns and structures in sourceAdversarialAttacksonCodeModelswithDiscriminativeGraphPatterns Conference’17,July2017,Washington,DC,USA code. These transformer models can be pre-trained using unla- thatareflexiblyadaptabletoeachmodelusingasetofprobingdata belledcodedatasetstocapturethesemanticrelationsinthesource (2) How to effectively derive concrete attacks from an abstract code[13,16].Afterpre-training,thesemodelscanbefine-tunedto pattern,and(3)Whichpatternstoselectandwheretoinsertitinto achievestate-of-the-artperformanceondownstreamtaskssuchas theinputcode. codecompletion,vulnerabilityprediction,authorshipattribution, Toaddressthesechallenges,GraphCodeAttackoperatesin etc.[10,29].However,thesemodelsarealsosusceptibletoadver- threemainphases.First,GraphCodeAttackformulatestheprob- sarialattacks,wherecarefullycraftedperturbationsintheinput lemofidentifyingeffectiveASTpatternsasdiscriminativesubgraph sourcecodecancausethemtoproduceincorrectpredictionsor mining(theminingphase3.1).TakingasetofinputcodeDandthe outputs[50,53]. correspondingmodel’spredictionsasinput,GraphCodeAttack identifiesasetofdiscriminativeabstractsyntaxtreepatternsP𝐴 2.2 GraphMiningviaAbstractSyntaxTrees thatarehighlycorrelatedwiththemodel’spredictions.Thismeans thatthepresenceorabsenceofthesepatternsiscloselylinkedto AbstractSyntaxTree.AbstractSyntaxTrees(ASTs)representthe specificpredictionsmadebythemodelsbasedonthepreprocessing syntacticstructureofsourcecode,withnodescorrespondingto phase.Baseduponthislink,GraphCodeAttacktriestoalterthe languageconstructsandedgesindicatingtherelationshipsbetween modelpredictionbyinsertingthesepatternsintotheinputsource nodes.Inourcontext,wedescribetheASTsasgraphs.Indetail, code.Notethatthesepatternsareinsertedtoaprograminaway anASTisdenotedasagraph𝐺 = (𝑉,𝐸),wherethevertexset𝑉 thatthesemanticsoftheunderlyingprogramremainintact. consistsofnodescorrespondingtolanguageconstructs,andthe RecallthattheminedASTpatternsareabstract,onlycontaining edgeset𝐸includesdirectededgesindicatingtheirparent-childrela- informationsuchasnodetype,edgetypes,etc,withoutconcrete tionships.Eachnode𝑛∈𝑉 isassociatedwithalabel𝑙 𝑛representing content(e.g.,specificidentifier,specificbinary,unaryoperations thelanguageconstructitdenotes,suchasvariables,expressions, like+, -, >, <,etc.).Tosynthesizeconcreteattacksfromthe orcontrolstructures.Similarly,eachedge𝑒 ∈ 𝐸 canalsohavea abstractASTpatterns,GraphCodeAttackconverteachpattern correspondinglabel𝑙 𝑒 specifyingtherelationshipbetweenthecon- into a textual form, in which parts that need to be filled in are nectednodes,suchasdataorcontroldependencies.Forexample,in indicatedbyaspecialtoken<MASK>.Thistextualrepresentation anASTrepresentingasimpleif-elsestatement,thenodesmight helpfacilitatetheinsertionofthepatternintheattackphase. representtheifkeyword,thecondition,andthebranches,while Finally,theattackphasefocusesondeterminingthevalidpertur- theedgesindicatetheparent-childrelationshipsamongthesenodes. bationoftheinputsourcecodethatmakesthetargetmodelchange ThestructureoftheASTcapturesthehierarchicalorganizationand prediction.Tosearchforthisperturbation,GraphCodeAttackfor- thesyntacticdependenciesinthesourcecode,whichareessential mulatestheproblemasasearchproblemofpositionsinthesource forminingdiscriminativepatterns. codeandthecorrespondingmodificationstoperformateachcorre- DiscriminativePatternsMining.Discriminativesubgraphmin- spondingposition.Wesamplethepositionsbasedonacalculated ing[46]isabranchofgraphminingthatfocusesondiscovering importantscore,whichspecifiestheeffectivenessofhavingthe subgraphsorpatternsthatexhibitsignificantdifferencesbetween statementandnothavingthestatementonthetargetmodel’spre- classesinthedataset.Thegoalistoidentifythemostdistinguishing diction.Followedbythat,weestimatethemostimpactfulpattern substructuresforeachclass,whichcanthenbeusedfortaskssuch toinsertbasedonameta-modeloverthemodel’soutput.Having asclassification,clustering,andanomalydetection.Sincethese determinedthepositionaswellasthecorrespondingpatterns,we subgraphsarediscriminative,theirpresencemightbemorelikely insertthesepatternsintotheinputsourcecode. tochangethepredictionofthetargetmodel.Thus,GraphCodeAt- Toperformtheattack,weimplementagreedystrategy.Ateach tackperturbtheinputsourcecodebyinsertingthesepatterns. greedystep,wechoosetheposition/patterncombinationthatcan GraphCodeAttackworksbyfindingthemostdiscriminative mostreducetheconfidenceofthetargetmodelonitsoutput.This subgraphsfromadatasetandusesthesesubgraphstostructurally assumptionhasalsobeenadoptedbyearlierworks[50,53].We
perturbtheinputcode.OurGraphCodeAttackanalyzesASTs keeptrackofthenumberofmodelqueriesandstopthisprocess sinceASTsprovideamorestructuredandsemanticallyrichrepre- oncethemaximumnumberofqueriesisreached. sentationofsourcecodethanrawtext,facilitatingpatternmining Weexplainindetailthethreemainphasesof GraphCodeAt- andanalysis.Also,ASTsareagenericrepresentation,allowingour tackinthebelowsubsections. approachtobeapplicableacrossdifferentprogramminglanguages. 3.1 MiningAttackPatterns 3 METHODOLOGY In this section, we detail the process of mining attack patterns Inthissection,wepresentthearchitectureofGraphCodeAttack. inGraphCodeAttack.Theprimaryobjectiveistoidentifyaset GraphCodeAttackaimsatderivingadversarialattacksofmodels ofdiscriminativesubgraphsP𝐴thatcaneffectivelyinfluencethe ofcodebyautomaticallyminingattackpatternsfromasetofprob- targetmodel’sprediction. ingdataandthecorrespondingmodel’soutput.Theattackpatterns areintheformofabstractsyntaxtrees(ASTs)thatcanbeusedto 3.1.1 DiscriminativeSubgraphMining. Givenasetofinputcode perturbthestructureofamodel’sinputcodewhichinfluencethe samples𝑆 =𝑠 1,𝑠 2,...,𝑠 𝑛andtheircorrespondingmodelpredictions model’sdecisions. 𝑌 =𝑦 1,𝑦 2,...,𝑦 𝑛,weformulatethetaskoffindingeffectivepat- GraphCodeAttackhastoovercomethreeprimarychallenges: ternstoattackthemodelasadiscriminativesubgraphsminingprob- (1)Howtoautomaticallyobtainthesetofeffectiveabstractpatterns lem.ThegoalistodiscoverasetofsubgraphsP𝐴 =𝑃 1,𝑃 2,...,𝑃 𝑘Conference’17,July2017,Washington,DC,USA Thanh-DatNguyen,YangZhou,Xuan-BachD.Le,Patanamon(Pick)Thongtanunam,andDavidLo Particularly,astheminedgraphsareabstract,weneedtosynthesize concretecodesnippetsfromthepatternsinawaythatthesnippets arecontextuallycoherentwiththeunderlyingprogram. Figure3demonstratesamotivatingexample.Wehaveanattack patternconsistingofabinaryoperationwiththeleftsidecompo- nentpointingtoastringofunknowncontentandtherightside componentpointingtoanunknownnode.Thereareseveralprob- lemswithinsertingthispatternintothecode:(1)Fillinginthe contentoftherightnodeisproblematicaswedonotknowthe actualtype,name,orvalueofthenode.(2)Wedonotknowwhat exactly the operation of Binary Op node and (3) Furthermore, wealsohavetoconsiderwhatvariableorexpressionisbasedon eachcontexttobeputintherightside.GraphCodeAttacktackles thesechallengesusingapre-trainedmodelofcode.Asanexample, considertheabstractsyntaxsubtreedepictedinFigure3. TodeterminewhichoperationscanbeputinBinaryOpnode, weidentifythecorrespondinginstanceofthepatternintheactual sourcecodeandnarrowdownthesetofvaluesthatcanbeputin. Figure1.OverviewofGraphCodeAttack’smethod.M𝑡 is Havingidentifiedtheinstancesofthepatterninthedataset,we thetargetvictimmodel,M𝑓 isthelanguagemodelusedto alsoknowhowtoidentifythecomponentsthatcanbechanged. fillinthe<MASK> Forincompletecomponents(e.g.,stringwithoutstringcontent,a rightnodeofthebinarycomponent),weidentifythetextualspan ofthecorrespondingcomponentandreplaceitstextualcontent thataresignificantlydiscriminative.Thesesubgraphs,whichdis- withthespecial<MASK>token. criminatebetweendifferentclassesorgroupsofdata,empowerus Theresultisthetextualrepresentationoftheminedsubgraph toeffectivelyswaythemodel’sprediction. Toachievethis,wefirstconstructeachASTrepresentation𝑇 𝑖 withunknowncomponentsreplacedbythe<MASK>token.Aswe foreachcodesample𝑠 𝑖 ∈ 𝑆.AfterobtainingtheresultingASTs will see later, this representation facilitates the insertion of the setT = {𝑇 1,𝑇 2,...,𝑇 𝑛},weapplythegSpan-CORKalgorithmto patternintothesourcecodeusingthepre-trainedlanguagemodels. find the set of subgraphs P𝐴 that exhibit a high discriminative 3.3 Attackingwithminedpatterns power.gSpan-CORKaimstogreedilyfindthethesetofsubgraphs P𝐴 = {𝑃 𝐴 1,𝑃 𝐴 2,...,𝑃 𝐴𝑘}thatmaximizesthequalitycriterion𝑞. Havingobtainedthepatternandthecorrespondingtextualrep- Fortwoclasses0and1withthecorrespondingsetofASTsT 0and resentation,weproceedtoperformtheadversarialattackonthe T 1: targetmodel.Takingasourcecodeasaninput,GraphCodeAttack ∑︁ 𝑞(P𝐴)=− (|T 0,𝑃¯|·|T 1,𝑃¯|+|T 0,𝑃|·|T 1,𝑃|) (1) repeatedlychoosesthemostimportantstatementsalongwitha 𝑃∈P𝐴 patternthatlikelyimpactsthemodelpredictionandinsertsthe whereT 0,𝑃¯,T 1,𝑃¯arethesetsofASTsbelongingtoclass0andclass1 patternnexttothestatementuntilitreachesthetokenthreshold thatdonotcontainsubgraph𝑃.T 0,𝑃,T 1,𝑃 isthesetofASTsbelong- limit.WegiveanillustrationinFigure2. ingtoclass0andclass1thatcontains𝑃 respectively.Theintuition 3.3.1 Statement-levelimportantscoreestimation. Tochoosethe behind this function is to maximize the difference in subgraph mostimportantstatement,wequantifytheimpactofastatementby patternsbetweenthetwoclasses. computingthedifferenceinthetargetmodel’sprobabilityestimates botT hh ce lafi sr sst 0t ae nrm dcc lo au ssnt 1s ,t whe hic leas te hs ew seh ce or ne dsu tb erg mrap coh u𝑃 nti ssa thb ese cn at sein s with and without the inclusion of the statement. Let 𝑃 M𝑡,𝑐𝑡(𝑠) denotethetargetmodelM𝑡’soutputprobabilityforagiveninput wheresubgraph𝑃ispresentinbothclasses.Byminimizingthesum codesample𝑠andforthetargetclass𝑐 𝑡.Let𝑎beastatementin𝑠, ofthesecross-interactions,weaimtofindthesetofsubgraphsP𝐴 theimpactof𝑎on𝑠is: thatbestdifferentiatesthetwoclasses.Thesesubgraphsprovide the basis for the subsequent attack phase, where they are used Δ𝑃 M𝑡,𝑐𝑡(𝑠,𝑎)=𝑃 M⊔,𝑐𝑡(𝑠)−𝑃 M𝑡,𝑐𝑡(𝑠\𝑎) (2)
toperturbthesourcecodeandalterthemodel’soutput.Wenote thattherecanbecaseswherethemodelcanperformmulti-class Where𝑠\𝑎representstheinputcodesample𝑠withoutthestatement classificationsthatpredicttheoutputtobeoneof𝐶classes.Inthis 𝑎included.Intuitively,thelargerΔ𝑃 M𝑡,𝑐𝑡(𝑠,𝑎)isthemorepositive case,wesimplyconstruct𝐶one-versus-allgraphdatasets. impactofthestatementtowardsthepredictionofthemodelM𝑡.We employagreedystrategyandchoosethemostimportantstatement 3.2 SynthesizingConcreteAttacksfromAST astheattacklocation. Patterns 3.3.2 Choosingpatternwithmeta-model. Sincethenumberofpat- Recallthateachpattern𝑃inthediscriminativeASTpatternsetP𝐴 ternscanbelarge,thenextquestionishowtochooseaneffec- isasubgraph.Utilizingthesepatternstoguidetheperturbationof tiveattackpatternthatwouldlikelyleadtoadifferentprediction codepresentssomechallenges,astheprocessisnotstraightforward. ofthemodel.Forthis,wetrainadecisiontreeasameta-modelAdversarialAttacksonCodeModelswithDiscriminativeGraphPatterns Conference’17,July2017,Washington,DC,USA Figure2.Attackingwithpattern:Giventheoriginalsourcecode(a),GraphCodeAttackidentifytheimportantstatementon line2:f = sys.stdin.GraphCodeAttackthenchoosesthepattern(𝑏)consistingofanifstatementwithunknowncondition andbody.GraphCodeAttackinsertsthistextpatterninthecode,resultinginthemaskedcode(𝑐).Finally,GraphCodeAttack usesthefillerlanguagemodelM𝑓 tofillinthemaskin(𝑐),resultingintheperturbedcode(𝑑)thatchangesmodelprediciton prediction: 𝑃 𝑐ℎ𝑜𝑠𝑒𝑛 =argmax𝑃(M𝑚𝑒𝑡𝑎(𝑇 𝑛𝑒𝑤∪𝑃 𝑚𝑖𝑠𝑠)≠𝑦 𝑖) (5) 𝑃𝑚𝑖𝑠𝑠 3.3.3 Patterninsertion. Havingdeterminedthelocationandpat- terntoinsert,thefinalquestionishowtoinsertthepatternandfill inthe<MASK>tokensuchthatthefinalcodeissyntacticallyvalid andsemanticallypreserving.Togeneratesyntacticallyvalidcode, Figure3.ExampleofcorrespondingASTpatternandtextual weleverageadifferentpre-trainedlanguagemodelM𝑓 (namely,we pattern usethelanguage-specificCodeBERTprovidedfromCodeBERTScore[55]) tofillinthe<MASK>.Notethatthismodelisseparatedfromthe targetmodelM𝑡.Inordertomakesurethecodedoesnotchange M𝑚𝑒𝑡𝑎 : 𝑠 ↦→ 𝑦. This meta-model istrained topredict thetar- thesemanticsofthecurrentcode,wefollowCARROT’sS-modifier getmodelprediction𝑦,giventhepresenceofeachpatterninthe [53](whicheitherinsertsdeadstatementorwrapsthecodeinside pattern set P𝐴. In detail, as input to the meta-model, we use a aredundantbranching)andmodifythepattern: bag-of-patternencoding. Obtainingthemeta-modelForeachsamplesourcecode𝑠 𝑖,we • Ifthepatternisconditional(e.g.,whileloop,forloop,if constructthefeaturef𝑖 ∈{0,1}|P𝐴|.Where: condition,etc,wemodifytheoriginalconditionofthepat- ternfrom<MASK>tofalse && (<MASK>)). 𝑓 𝑖,𝑗 =(cid:26) 1 if𝑠containsthepattern𝑃 𝑗 (3) • Else,weputthepatterninsideadeadcodeblock. 0 otherwise Finally,weinsertthemodifiedtextpatternintothechosenlocation Giventhefeatures 𝑓 𝑖 andthecorrespondingprediction𝑦 𝑖 for anduseapre-trainedlanguagemodeltofillinthemaskandobtain each source code𝑠 𝑖, we can train a decision tree M𝑚𝑒𝑡𝑎. Each theperturbedcode.Wenotethatthepre-trainedlanguagemodel path𝜋 inthisdecisiontreecorrespondstoapredictedclass𝑐 𝜋 and mightnotalwaysgeneratesyntacticallyvalidcode.Therefore,we thenumberofsupport𝑆𝑃 𝜋 (i.e.,thenumberofsamplesinDthat employtree-sitterparser1 tore-parsethegeneratedcodeandto containsthepatternsindicatedinthepathandreceivedmodel’s checkifthereexisterrorsinthefilledsourcecode.Ifthetree-sitter predictiontobe𝑐 𝜋). detectsanerroneousnode(i.e.,thenodehasthelabel“ERROR”),we ChoosingpatternGiventheinformationon𝑐 𝜋 and𝑆𝑃 𝜋 ofeach retrygeneratingthenodeupto5timesthendiscardthecandidate, path𝜋,wecannowdeterminewhichpatterntobeinsertedinto else,wequerythetargetmodeltoobtainthenewevaluation.The thetargetsourcecode.Foreachnewinput𝑠 𝑛𝑒𝑤 withAST𝑇 𝑛𝑒𝑤, patternsareinserteduntileitherthenumberofmaximumtarget weidentifyitscorrespondingfeatures𝑓 𝑛𝑒𝑤.Furthermore,foreach modelqueriesismet,orthetargetmodelchangesitsprediction. missingpattern𝑃 𝑚𝑖𝑠𝑠 inthesetofmissingpatternsP𝑚𝑖𝑠𝑠 ={𝑃 𝑖 ∈ P𝐴|𝑃 𝑖 ⊈ 𝑇 𝑛𝑒𝑤},wecalculatetheapproximatedprobabilitythat 4 EXPERIMENTSETTINGS addingthismissingpatternleadstoadifferentpredictionusingthe meta-modelM𝑚𝑒𝑡𝑎. TheexperimentresultsreportedherewereobtainedonanInteli5- 𝑃(M𝑚𝑒𝑡𝑎(𝑇 𝑛𝑒𝑤∪𝑃 𝑖)≠𝑦 𝑖)= (cid:205) 𝜋𝑆𝑃 𝜋 ×(1 𝑐𝜋≠𝑦𝑖) (4) 9 G6 T0 X0K 10m 8a 0c Th ii rn ue nw ni it nh g6 L4 inG uB x.ofRAMandequippedwithoneNvidia 𝑛 Where 1 𝑐𝜋≠𝑦𝑖 = (cid:26) 01 oif t𝑐 h𝜋 er≠ wi𝑦 s𝑖 e is the indicator function. We sample the pattern with the probability of changing model 1https://github.com/tree-sitter/tree-sitterConference’17,July2017,Washington,DC,USA Thanh-DatNguyen,YangZhou,Xuan-BachD.Le,Patanamon(Pick)Thongtanunam,andDavidLo 4.1 Dataset Table1.Statisticsoftasksanddatasetsinvestigatedinthe paper,aswellasthevictimmodels’performanceonthese Inourexperiment,wefollowthesettingsofthepreviousstudy[50] datasets.CBandGCBrepresentCodeBertandGraphCode- andselectthreedownstreamtasksfromtheCodeXGLUEbench- BERT,respectively. marks[29]:VulnerabilityPrediction,CloneDetection,andAuthor- shipAttribution.Belowweintroducethedetailsofeachtaskand itscorrespondingdataset. Tasks Train/Dev/Test Class Lang Model Acc. VulnerabilityPrediction.Theobjectiveofthistaskistoproduce Vulnerability CB 63.76% alabelindicatingwhetheraspecifiedcodesnippetcontainsany 21,854/2,732/2,732 2 C Prediction GCB 63.65% vulnerabilities.Zhouetal.[56]labelsourcecodeintwopopular open-sourcedCprojects:FFmpeg2andQemu3tobuildadataset Clone 90,102/4,000/4,000 2 Java CB 96.97%
consistingof27,318functions.Eachfunctionislabeledaseither Detection GCB 97.36% containingvulnerabilitiesorclean.Thisdatasetiswidelyusedtoin- Authorship CB 90.35% 528/-/132 66 Python vestigatetheeffectivenessofvariouscodemodelsinunderstanding Attribution GCN 89.48% codetopredictvulnerability.WefollowthesettingsinCodeXGLUE todividethedatasetintotraining,development,andtestsets. CloneDetectionClonedetectionisalsomodeledasaclassification 4.3 Baselines problem:givenapairoftwocodesnippets,acodemodelshouldpre- dictwhethertheyareclones(i.e.,whethertheyimplementthesame Inthisstudy,wecompareGraphCodeAttackwithtwostate-of- function).WechooseBigCloneBench[45]asthedataset,which the-arttechniquesattackingdeepcodemodels:CARROT[53]and isusedinthepreviousstudy[50]andisawidely-acknowledged ALERT[50].SinceCARROT[53]onlysupportsPython,weextend benchmarkforclonedetection.BigCloneBenchcomprisesaround ittoattackPythonandJavacodeforsufficientcomparison.Fur- 10millionpairsofJavacodesnippets;over6millionofthemare thermore,CARROThas4variants:renamingvariableswiththe clonesandtheremaining260,000arenotclones.Wecreateasubset model’sgradientandbyrandomandinsertingdeadcodeguided ofthedatasetthathasbalancedlabels(i.e.,theratioofclonepairs bythetargetmodel’sgradientandbyrandom.Sincewefollowthe andnon-clonepairsis1:1).Followingthepreviousstudy,weran- black-boxsettingsinourthreatmodel,weuseCARROTI-RW(i.e., domlyselect90,102examplesfortrainingand4,000forvalidating randomidentifierrenaming)whichisthetop-performingcandidate andtestingthecodemodels. towardstransformer-basedmodels[53]. AuthorshipAttributionThetaskofauthorshipattributionin- 5 RESEARCHQUESTIONS. volvesdeterminingtheauthorofagivencodesnippet.Wechoose the Google Code Jam (GCJ) dataset, which is created using the ToinvestigateGraphCodeAttackagainstthebaselines,wepose submissionfromtheGoogleCodeJamchallenge,ayearlyglobal threemainresearchquestions:(1)Theeffectivenessandthestealth- codingcompetitionhostedbyGoogle.GCJdatasetiscollectedand iness of GraphCodeAttack against CARROT and ALERT, (2) made open-source by Alsulami et al. [4], which consists of 700 Which patterns are the most effective on each task and model, Pythonfilesthatarewrittenby70authors.Thedatasetisbalanced, and(3)HowadversarialretrainingusingGraphCodeAttackcom- i.e.,eachauthor(i.e.,class)having10codesnippets.Thisdataset pareswithALERTandCARROTondefendingagainstadversarial containsmainlyPythonfilesbutalsosomeC++code.Weremove attacks.Weexplaineachresearchquestionandresultsbelow. C++sourcecodetoobtain660Pythonfiles.Wefollowan80:20split: 20%offilesareusedfortesting,and80%offilesarefortraining.In 5.1 RQ1.Howeffectiveandstealthyis accordancewithpreviousstudies[50],wedonotuseavalidation GraphCodeAttackagainstthe datasetduetothesmalldatasetsize[50]. state-of-the-artbaselines? Effectiveness.WeusetheALERT’spublishedmodelasthetarget 4.2 TargetModel,FillermodelandProbingData modelforattackingandcomparetheAttackSuccessRate(ASR) FollowingtheexistingworksofALERT[50],weuseCodeBERT[13] of GraphCodeAttackversusCARROT[53]andALERT[50]on andGraphCodeBERT[16]asourtargetmodels.WefollowALERT[50] the3tasks:AuthorshipAttribution,VulnerabilityPrediction,and inthehyperparametersettingsforthesemodelsandretrievethe CloneDetectionofCodeXGLUE[29].Weusethesamenumberof correspondingmodelsfromtheofficialGitHubsiteofALERT.For stepsandsettingstobe2000followingALERT[50].SinceGraph- thefillermodelM𝑓 whichisresponsibletofillinthemask,weuse CodeAttack’sapproachneedstoexecutetwocodemodels(the language-specificCodeBERTsprovidedbyCodeBERTScore[55] targetandthefiller)atthesametime,itcanbeslowerthanthe whichhasbeenpre-trainedspecificallyforeachlanguagePython, baselines.Thus,inordertogivearealistictimeefficiencyconstraint JavaandCrespectively.FortheprobingdatasetD,weuseeach forGraphCodeAttack,wealsoputatimeoutof100secondsfor task’strainingsourcecodewithouttheoriginallabel. eachattack.Wetheseresultsbelow. Table2presentstheASRof GraphCodeAttackcomparedto CARROTandALERTontheCodeXGLUEbenchmarks.Onaverage acrossthethreetasks,intermsofattacksuccessrate(ASR),Graph- 2https://www.ffmpeg.org/ CodeAttackoutperformsCARROT[53]by30.6%andALERTby 3https://www.qemu.org/ 33.1%respectively.AdversarialAttacksonCodeModelswithDiscriminativeGraphPatterns Conference’17,July2017,Washington,DC,USA Table2.AttackSuccessRate(ASR)comparisonforGraphCodeAttack,CARROT,andALERTonCodeXGLUEbenchmarksfor 3tasksand2models(CodeBERTandGraphCodeBERT).Highervaluesindicatebetterperformance. AuthorshipAttribution VulnerabilityPrediction CloneDetection Method CodeBERT GraphCodeBERT CodeBERT GraphCodeBERT CodeBERT GraphCodeBERT GraphCodeAttack 0.612 0.8407 0.774 0.799 0.401 0.053 CARROT[53] 0.485 0.598 0.620 0.746 0.108 0.102 ALERT[50] 0.337 0.615 0.536 0.769 0.273 0.080 Indetail,forthetargetmodelCodeBERT,GraphCodeAttack The change rate of GraphCodeAttack is shown in Table 3.
outperformsCARROTby26%,24%andALERTby81.5%,43.6% Onall3tasks,GraphCodeAttackneedstoinsertapproximately on Authorship Attribution and Vulnerability Prediction respec- 100tokens.ForCodeBERTmodel,GraphCodeAttackinsertson tively.ForGraphCodeBERT,thecorrespondingimprovementsare average90.27tokenswithastandarddeviationof58.38forAu- 40.5%and7%forCARROTand36.65%and3.8%forALERT.For thorshipAttribution,56.33(38.96)forVulnerabilityPrediction,and CloneDetectionandonCodeBERT,GraphCodeAttackoutper- 125.29(72.98)forCloneDetection.Thecorrespondingchangerates formedALERTby46.9%andCARROTby270%respectively.On are0.136,0.570,and0.1455.OnGraphCodeBERT,GraphCodeAt- GraphCodeBERT,GraphCodeAttackperformscomparablywith tackhasaveragechangeratesof112.833,62.06,and124inserted CARROTandALERT.Thisbetterperformancecanbeattributed tokenswithstandarddeviationsof64.4,47.165,and70.2forthe toGraphCodeAttack’scapabilityinleveragingspecificattack threetasksrespectively.Thecorrespondingchangeratesare0.1359, patternstowardsthetargetmodel.Pre-trainedlanguagemodelsof 0.463,and0.144.GraphCodeAttack’snumberofaverageinserted coderelyonbothsyntacticpatternsandtextualtokens[22].Thekey tokensissmallerincomparisonwiththenumberofchangedtokens differencebetweenGraphCodeAttack,ALERT,andCARROTis fromALERTandCARROT,aswellashavinglowervariationin thatGraphCodeAttackaddsvariedcodefragments,whileALERT thenumberofinsertedtokensacrossalltasks.Moreover,Graph- andCARROTI-RWonlychangeexistingvariablenames.Since CodeAttack’schangerateiscomparabletoALERTandCARROT variablesareonlypartofthemodelinput,GraphCodeAttack’s onAuthorshipattributionandCloneDetectionbutishigherin addingnewvaryingcodefragmentsexpandstheattackspaceand VulnerabilityDetection.Thisisduetoidentifierrenamingmeth- resultsinmorecomprehensivemodelperturbation. ods’changeratesgrowwiththenumberofvariableusagesinthe Theperformanceofallattackmethodschangeswhenswitching code.SinceVulnerabilityPrediction’ssourcecodeissmallerthan fromCodeBERTtoGraphCodeBERT:OnGraphCodeBERT[16], thetwoothertasks,thisper-sourcecodechangerateishigher,on GraphCodeAttackmarginallyoutperformsALERT[50]andCAR- thecontrary,whentheprogramsizegrows,GraphCodeAttack ROT[53],whichcanbeattributedtotwofactors:(1)GraphCode- demonstratesbetterchangerates. BERT’s emphasis on variable names, and (2) the perturbations causedbythethreetools.RecallthatGraphCodeBERTaugments RQ1Conclusion:GraphCodeAttackoutperformsCAR- CodeBERTwithexplicitvariablenamesandattentionmasks,mak- ROTandALERTinAuthorshipAttributionandVulner- ingCARROTandALERT’srenamingmoreeffective.Atthesame abilityPredictiontasks,withsimilarresultsinCloneDe- time,sinceGraphCodeBERT’sdataflowdoesnotfilteroutdead tection.Forstealthiness,GraphCodeAttackachievesrea- branches,GraphCodeAttackattacksleveragingsurroundingvari- sonablechangerates.GraphCodeAttackgivesabetter ablescanstillalterthedataflowgraphandslightlyoutperformthe codechangerateonlargersourcecodeswhileALERTand baselines. CARROT’schangeratesgrowwiththelengthoftheinput WhiletheASRonCodeBERTclonedetectionbyGraphCodeAt- code. tackisnearly42%betterthanALERTandfourtimesbetterthan CARROT(i.e.,successratesof0.4,0.27,0.1respectively).Thesuc- 5.2 RQ2.Whatarethemosteffectivepatterns cessratesonGraphCodeBERTarelow.Thissuggeststhatthereis oneachproblemandmodel? stillroomforimprovementsonthecodeclonedetectiontask. Stealthiness. "Stealthiness" measure how hard it is for the de- Tounderstandwhichpatternscontributethemosttothesuccess velopertonoticetheattack.Intuitively,theclosertheresulting of adversarial attacks, we evaluate the frequency with which a attackedsourcecodeistotheoriginalsourcecode,theharderit pattern is added in successful adversarial examples. We report istonotice,hence,theattackisstealthier.Asaproxytomeasure theTop-3mostfrequentlyoccurringpatternsfortaskandmodel stealthinessautomatically,weuseCodeChangeRate.Thelowerthe combination. We do not count the dead code wrapper (e.g., if codechangerateis,thestealthiertheattacks.Assumethateach False)sincetheyarenottheoriginalpatterns.Sincethetasksare sourcecodes𝑠istokenizedinto𝑛 𝑡 numberoftokens,andtheattack doneindifferentlanguages,wegrouptheequivalentASTbetween required𝑛 𝑖 tokenstobemodified.Wecalculatetheaverageand different languages to count the patterns’ frequency. For exam- standarddeviation𝜇 𝑇𝐶 and𝜎 𝑇𝐶 ofthenumberofinsertedtokens ple, comparison_operator in Python between two expressions aswellasthechangerateof𝑛 𝑖/𝑛 𝑡. isequivalenttoabinary_expressioninC++andJava,blockin Pythonisequivalenttocompound_statementinC++andJava.IfConference’17,July2017,Washington,DC,USA Thanh-DatNguyen,YangZhou,Xuan-BachD.Le,Patanamon(Pick)Thongtanunam,andDavidLo Table3.CodeChangeRateofGraphCodeAttack,ALERT,andCarrot,𝜇 and𝜎 arethetotalnumberoftokensaddedand 𝑇𝐶 𝑇𝐶 thestandarddeviation.𝜇 and𝜎 arethetokenchangerateandthestandarddeviationrespectively 𝑇𝐶𝑅 𝑇𝐶𝑅 Method TargetModel AuthorshipAttribution VulnerabilityPrediction CloneDetection 𝜇 𝜎 𝜇 𝜎 𝜇 𝜎 𝜇 𝜎 𝜇 𝜎 𝜇 𝜎 𝑇𝐶 𝑇𝐶 𝑇𝐶𝑅 𝑇𝐶𝑅 𝑇𝐶 𝑇𝐶 𝑇𝐶𝑅 𝑇𝐶𝑅 𝑇𝐶 𝑇𝐶 𝑇𝐶𝑅 𝑇𝐶𝑅
GCA CB 90.27 58.38 0.136 0.149 56.33 38.96 0.570 0.378 98.13 97.98 0.255 0.367 GCB 112.833 64.4 0.1359 0.1724 62.06 47.165 0.463 0.794 40.75 33.75 0.03 0.04 ALERT CB 151.95 144.254 0.1416 0.102 136.14 320.18 0.1295 0.086 69.68 97.191 0.112 0.0644 GCB 325.94 195.98 0.344 0.124 159.302 371.39 0.121 0.086 153.36 193.34 0.264 0.1376 CARROT CB 113.65 120.62 0.24 0.193 107.133 209.8 0.136 0.149 88.87 232 0.103 0.121 GCB 129.101 161.29 0.26 0.18 112.61 179.61 0.215 0.2 170.95 297.866 0.2344 0.168 Table 4. Top frequent patterns in a successful attack, CF meansthepatternscontainacontrol-flowelement(e.g.,if, else-if, else, for, while, etc.)andDFmeansthepat- ternscontaincalculationsrelatingtovariables(e.g.,identifier nodes),LmeansthepatternscontainsLiterals Task Model PatternID Patterntype Frequency A CF 0.987 CB G DF 0.703 Authorship B CF,DF 0.604 Attribution B CF,DF 0.586 GCB D DF 0.432 F CF,DF 0.211 E CF 0.864 CB K CF 0.807 Vulnerability I CF 0.174 Prediction B CF,DF 0.413 GCB H CF,DF 0.283 E CF,DF 0.249 G DF 0.448 CB L CF,DF 0.085 Clone M DF,L 0.023 Detection G DF 0.615 GCB K CF,DF 0.482 Figure4.Topfrequentpatternsamongattacks E CF,DF 0.448 anASTpatternonlyappearsinasinglelanguage,wereportthe originalpattern. Table3andFigure4presentthetopfrequentlyappearingpat- variableanddata-flowoperations(whichisconsistentwiththe ternsinsuccessfulattacksforeachtaskandtargetmodelandFig- designofthemodel). ure 4 depicts these patterns in detail. The results indicate that Amongdifferenttasks,AuthorshipAttributionandCloneDe- patterns’effectivenessvariesacrossdifferenttasksandtargetmod- tectionbothhave4/6patternscontainingcontrolflowand5/6 els.Particularlyonall3tasks,CodeBERThasthe2topfrequently patterns using data flow elements. Vulnerability Prediction has appearedpatternscontainingcontrol-flowelementsand1toppat- 6/6patternscontainingcontrolflowelementsand3/6containing ternthatcontainsdata-flowelements.WhileGraphCodeBERTalso dataflowelements.ThissuggeststhatAuthorshipAttributionand has2/3toppatternscontainingcontrol-flowelements,allofits CloneDetectionhavemorerelianceondataflowelementswhile top-frequentedpatternsinthesuccessfulattackcontaindata-flow theVulnerabilityPredictionmodelleansmoretowardthecontrol elements.ThishintsthatGraphCodeBERTmodelsrelymoreon flowelements.AdversarialAttacksonCodeModelswithDiscriminativeGraphPatterns Conference’17,July2017,Washington,DC,USA variabilityofGraphCodeAttack’sattacks:sincetheinsertedat- RQ2Conclusion:Amongthemostfrequentlyoccurring tacksinGraphCodeAttackarefilledusingapre-trainedlanguage patterns,CodeBERTfrequentlyexhibitscontrol-flowpat- model,thefilledmasksmayvary,makingitchallengingtodefend terns, while GraphCodeBERT relies more on data-flow againsttheproducedattacks. operations.AuthorshipAttributionandCloneDetection Finally,whileretrainingwithGraphCodeAttackandALERT dependondataflowelements,whereasVulnerabilityPre- resultsinasimilardefense,weemphasizethatGraphCodeAttack dictionleanstowardscontrolflowelements. onlyemploysanaugmentationmethodinsteadofperforminga fulladversarialattackonthetargetmodelorthetargetmodel’s 5.3 RQ3.HoweffectiveisGraphCodeAttack responseitself,givingitfinetuninganadvantageofefficiencyand inimprovingtherobustnessofcodemodels? indeployment. Settings.Toanswerthisquestion,weexperimentwithadversarial retraining,aprocessthatinvolvesfine-tuningthetargetmodelwith RQ3Conclusion:GraphCodeAttack’sfine-tuning,al- adversarialexamplestoimproveitsrobustnessagainstpotential thoughnotrequiringthetargetmodels’feedbacknorafull attacks.Todothis,werandomlyinsertthepatternsgeneratedby adversarialattackonthetrainingdatasetlikeALERTand GraphCodeAttackintothetrainingdatasetasadataaugmenta- CARROT,achievessimilarperformancewithALERTand tionstep.Whiletraining,oneachdatasample,wesettheprobability betterperformanceincomparisonwithCARROT. ofapplyingaperturbationto0.5.Thisprobabilityindicateshow likelywewouldapplyaperturbationoneachsample.Settingthis probabilityto0.5balancestheuseoforiginalandperturbedsam- 6 THREATSTOVALIDITY plesinthetrainingprocess.RecallthatGraphCodeAttackcan insertdeadcodemultipletimes,wealsosetthemaximumnumber 6.1 ThreatstoInternalValidity ofperturbationsto5,meaningthatwewillinsertthedeadcodefor TheeffectivenessofGraphCodeAttackreliesontheminedAST themaximumof5times,whichishalfthenumberofgreedysteps patterns.Ifthepatternminingprocessisnotcomprehensiveor thatGraphCodeAttackusesinattacking. biasedtowardsspecificpatterns,itmayaffectthesuccessrateof WeobtaintheALERT[50]’sfine-tunedmodelfromtheofficial GitHubrepository4.ForCARROT[53],wefollowtheoriginalpro- ouradversarialattacks.Wemitigatethisthreatbyusingamodel- agnosticapproachtominediscriminativepatternsandvalidating cedureandobtaintheperturbedsamplesthateitherchangethe ourmethodagainstmultipledatasetsandmodelarchitectures.The
model’spredictionordropthetargetmodel’sconfidencetowards processofinsertingtheASTpatternsintothecodeandtheselection theoriginalprediction,weaugmentthetrainingsetwiththese oftargetmodelsmayintroducerandomness,whichcanpotentially samplesandfine-tuneuntilthemodelconverges. influencetheresults.Weaddressthisissuebyconductingexperi- Wetesttherobustnessofthefine-tunedmodelsontheadversar- mentswith3runsandreportingtheaverageperformance,ensuring ialsamplesinRQ1ofbothALERT,CARROT,andGraphCodeAt- thestabilityandreliabilityofourresults. tackitself.Therobustnessmeasurementofasingleadversarial sampleisdefinedaccordingtoCARROT[53]:wemeasuretheratio ofmakingcorrectpredictionsonthesetofgeneratedadversarial 6.2 ThreatstoExternalValidity examplesinRQ1. Results.TheresultsofadversarialtrainingarepresentedinTable5. Thegeneralizabilityofourfindingsmightbelimitedbythechoice of datasets, models, and evaluation metrics used in our experi- Overall,onAuthorshipAttribution,usingtheWilcoxonRankSum Test,weobtaineda𝑝-valueof0.031forCARROTvsALERT,0.043 ments.Tomitigatethisthreat,weemployedwidely-usedtasksand datasetsthatareincludedintheCodeXGLUEbenchmark,aswell forCARROTvsGraphCodeAttack,and0.893betweenALERTand asthepopularpre-trainedlanguagemodelsforcode:CodeBERT GraphCodeAttack.TheCliff’sDeltaforthethreepairs(CARROT andGraphCodeBERT. vsALERT,CARROTvsGraphCodeAttackandALERTvsGraph- CodeAttack)are−0.444(medium),−0.472(medium),and0.028 (small)respectively.ThisdemonstratesthatALERTandGraph- 6.3 ThreatstoConstructValidity CodeAttackexhibitsimilarperformanceinimprovingrobustness, Thechoiceofevaluationmetricscanimpacttheinterpretationof andbothmethodsoutperformCARROT.Itisworthnotingthatfor ourresults.Inthisstudy,weusedtheAttackSuccessRate(ASR)to bothVulnerabilityPredictionandCloneDetection,therobustness measuretheeffectivenessofourmethod,whichwaswidelyused improvementsacrossdifferentadversarialfine-tuningmethodsare inthepreviousstate-of-the-artpapers[50,53].Moreover,wealso similarforallbaselines. adoptthesamemetricusedtoassesstherobustnessimprovement Interestingly, in the case of Authorship Attribution and Vul- frompreviousstudies[50,53]. nerability Prediction, both CARROT and GraphCodeAttack’s adversarialresultsaredifficulttodefendagainst.ForCARROT,this canbeattributedtothefactthatchangesinvariablescanbemore 7 RELATEDWORK pronouncedthaninALERT,owingtothelackofnaturalconstraints. Thissectionprovidesanoverviewoftherelevantstudiesinthefield. ForGraphCodeAttack,thedifficultyindefensemaybeduetothe Wedividetheserelatedworksintotwocategories:(1)pre-trained 4https://github.com/soarsmu/attack-pretrain-models-of-code modelsofcodeand(2)potentialthreatstothesemodels.Conference’17,July2017,Washington,DC,USA Thanh-DatNguyen,YangZhou,Xuan-BachD.Le,Patanamon(Pick)Thongtanunam,andDavidLo Table5.Robustnessimprovementofthetargetmodelafteradversarialfine-tuning:Eachmajorcolumnindicatesfromwhich methodtheadversarialexamplesaregenerated,andeachminorcolumnindicatesfromwhichmethodthemodelisadversarially fine-tuned. Task Model CARROT ALERT GraphCodeAttack CARROT ALERT GCA CARROT ALERT GCA CARROT ALERT GCA Authorship CodeBERT 0.2528 0.6781 0.3793 0.8095 0.8736 0.8095 0.2916 0.6067 0.7661 Attribution GraphCodeBERT 0.00 0.0253 0.0253 0.5143 0.9621 0.9143 0.0096 0.027 0.4144 Vulnerability CodeBERT 0.5145 0.5364 0.495 0.8518 0.8811 0.7362 0.5957 0.5786 0.6047 Prediction GraphCodeBERT 0.5635 0.5242 0.5257 0.7966 0.8904 0.7893 0.578 0.582 0.5995 Clone CodeBERT 0.9568 0.9606 0.9722 0.9012 0.9190 0.9120 0.9232 0.9341 0.9674 Detection GraphCodeBERT 0.9434 0.9032 0.9322 0.9123 0.9104 0.9089 0.9233 0.9142 0.9258 7.1 Pre-trainedModelsofCode adversarialrobustnessincodemodels,employingFGSM[15]to Largelanguagemodels,suchastheBERT[11,28]andGPT[7,39] renamevariablesandtargetcodemodelslikecode2vec[3].Jordan families,haveachievedremarkableperformanceinvariousnatural etal.[17]extend[52]workbyconsideringadditionaltransforma- language processing tasks. This success inspired researchers to tionssuchasconvertingforlooptowhileloop.Srikantetal.[43] developpre-trainedmodelsforprogramminglanguagestocapture utilizePGD[30]togeneratestrongeradversarialexamples.These codesemanticsandimprovecode-relatedtasks. studiesassumewhite-boxaccesstothecodemodels,meaningthat ThetrendbeganwithCodeBERT[13],basedonRoBERTa[28], the attackerhas access tothe model’sparameters and gradient whichwaspre-trainedonthebimodalCodeSearchNetdataset[18]. information. Ithastwopre-trainingobjectives:maskedlanguagemodelingand Attackscanalsobeconductedinablack-box manner.Zhang replacedtokendetection.GraphCodeBERT[16]furtherincorpo- et al. [54] propose Metropolis-Hastings Modifier (MHM) to for ratescodegraphstructure,addingdataflowedgepredictionand black-boxadversarialexamplegeneration.Rabinetal.[38]and
nodealignment.Othermodels,suchasCuBERT[21]andC-BERT[9], Applisetal.[5]usesemantic-preservingandmetamorphictrans- focusonPythonandCsourcecode,respectively.Theseencoder-only formations, respectively, to assess code model robustness. Tian modelsgeneratecodeembeddingsfordownstreamtasks. etal.[47]employreinforcementlearningforattacks,whileJiaet Anothertypeofcodemodelisdecoder-onlymodels,primarily al.[20]demonstratethatadversarialtrainingimprovescodemodel focusedoncodegenerationtasks.TheGPT-basedcodemodelisa robustnessandcorrectness.Pouretal.[36]proposedleveraging well-knowndecoder-onlyarchitecture.Luetal.introduceCodeGPT renamingvariables,argument,method,andAPInamesaswellas intheCodeXGLUEbenchmark[29],utilizingtheGPT-2architecture addingargument,printstatement,forloop,ifloop,andchanging and pre-trained on CodeSearchNet [18]. Larger models include returnedvariablestogenerateadversarialsourcecodestoimprove InCoder[14]andCodeGen[32]with16.1Bparameters.OpenAI’s codemodels’robustness.Yangetal.[50]emphasizethenatural- Codex[10]powersMicrosoftCoPilot.Arecentstudysuggeststhat nessrequirementforcodemodeladversarialexamplesanddevelop smallermodelstrainedonhigh-qualitydatasetscanoutperform ALERT, which uses genetic algorithms for example generation. largermodels[2]. Zhangetal.[53]proposeCARROT,whichemploysworst-caseper- Researchershavealsoappliedencoder-decoder architectureto formanceapproximationtomeasurecodemodelrobustness.Both code models. Inspired by BART [25] and T5 [40], they propose ALERTandCARROTdemonstratestate-of-the-artperformance. modelslikePLBART[1]andCodeT5[49],experimentingwithpre- GraphCodeAttackfocusesoncraftingmorecomplexadversarial trainingtaskssuchasmaskedspanpredictionandmaskedidenti- examplesratherthanemphasizingnaturalness. fierprediction.OthermodelsincludeDeepDebug[12],Prophetnet- Researchershavealsostudiedthreatslikedatapoisoningand x[37],CoTexT[35],andSPT-Code[34].Thesecodemodelsdemon- backdoorattacks.Ramakrishnanetal.[41]proposefixedandgram- strateremarkableperformanceonvariouscode-relatedtasks,in- martriggerstoinsertbackdoorsintocodemodels,whileWanet cludingcodecompletion,codesummarization,andcodegenera- al. [48] inject similar triggers into code search models. Yang et tion[33]. al.[51]useadversarialexamplesforstealthybackdoorinjection, andLietal.[26]generatedynamictriggersusinglanguagemodels, proposinganeffectivedefensemethod.Schusteretal.[42]conduct 7.2 ThreatstoCodeModels datapoisoningforinsecureAPIusage,whileNguyenetal.[31] assesstheriskofmaliciouscodeinjectioninAPIrecommender Despitetheirimpressiveperformance,codemodelsremainvulnera- systems.Sunetal.[44]demonstratedatapoisoningcanprotect bletovariousattacks.Understandingthesevulnerabilitiesiscrucial open-sourcecodefromunauthorizedtraining. forenhancingtheirsecurityandprotectingtheirdownstreamap- plications. Onesignificantthreatisthesusceptibilityofcodemodelstoad- versarialexamples[6].Yefetetal.[52]wereamongthefirsttostudyAdversarialAttacksonCodeModelswithDiscriminativeGraphPatterns Conference’17,July2017,Washington,DC,USA 8 CONCLUSIONANDFUTUREWORK WepresentedGraphCodeAttack,anadversarialattacktoolfor pre-trainedcodemodelstobetterevaluatetherobustnessofcode models.Weevaluatetherobustnessoftwopopularcodemodels(e.g., CodeBERTandGraphCodeBERT)againstourproposedapproach onthreetasks:AuthorshipAttribution,VulnerabilityPrediction, andCloneDetection.Theexperimentalresultssuggestthatour proposedapproachsignificantlyoutperformsstate-of-the-artap- proachesinattackingcodemodelssuchasCARROTandALERT. Basedontheaverageattacksuccessrate(ASR),GraphCodeAttack achieved30%improvementoverCARROTand33%improvement overALERTrespectively.Wealsoevaluatetheproducedattack qualitywiththeusageofcodechangerateandshowsthatGraph- CodeAttackproducessuccessfulattackswithfewertokenchange ingeneralandthecodechangeratedecreasewithlargercodefiles. Furthermore,GraphCodeAttack’sadversarialfine-tuninghasa similarperformancewithALERTinenhancingmodelrobustness, whilerequiringneitherthetargetmodel’soutputnorconductinga fulladversarialattackonthetrainingdata. For future work, we plan to investigate the impact of differ- entperturbationstoimproveGraphCodeAttack’sperformance. Additionally,weaimtoexploremoreattackscenarios,suchasmulti- labelandmulti-classsettings,tofurtherevaluatetheeffectiveness of GraphCodeAttackandenhanceitsgeneralizabilityacrossa widerrangeofcode-relatedtasks.Conference’17,July2017,Washington,DC,USA Thanh-DatNguyen,YangZhou,Xuan-BachD.Le,Patanamon(Pick)Thongtanunam,andDavidLo REFERENCES AssociationforComputationalLinguistics:EMNLP2020.AssociationforComputa- [1] WasiAhmad,SaikatChakraborty,BaishakhiRay,andKai-WeiChang.2021.Uni- tionalLinguistics,1536–1547. fiedPre-trainingforProgramUnderstandingandGeneration.InProceedingsof [14] DanielFried,ArmenAghajanyan,JessyLin,SidaWang,EricWallace,FredaShi,
the2021ConferenceoftheNorthAmericanChapteroftheAssociationforComputa- RuiqiZhong,ScottYih,LukeZettlemoyer,andMikeLewis.2023. InCoder:A tionalLinguistics:HumanLanguageTechnologies.AssociationforComputational GenerativeModelforCodeInfillingandSynthesis.InTheEleventhInternational Linguistics,Online,2655–2668. ConferenceonLearningRepresentations. https://openreview.net/forum?id=hQwb- [2] LoubnaBenAllal,RaymondLi,DenisKocetkov,ChenghaoMou,Christopher lbM6EL Akiki,CarlosMunozFerrandis,NiklasMuennighoff,MayankMishra,AlexGu, [15] IanGoodfellow,JonathonShlens,andChristianSzegedy.2015.Explainingand MananDey,LogeshKumarUmapathi,CarolynJaneAnderson,YangtianZi, HarnessingAdversarialExamples.InInternationalConferenceonLearningRepre- JoelLamyPoirier,HaileySchoelkopf,SergeyTroshin,DmitryAbulkhanov, sentations. http://arxiv.org/abs/1412.6572 ManuelRomero,MichaelLappert,FrancescoDeToni,BernardoGarcíadelRío, [16] DayaGuo,ShuoRen,ShuaiLu,ZhangyinFeng,DuyuTang,ShujieLiu,LongZhou, QianLiu,ShamikBose,UrvashiBhattacharyya,TerryYueZhuo,IanYu,Paulo NanDuan,AlexeySvyatkovskiy,ShengyuFuandzMicheleTufano,ShaoKun Villegas,MarcoZocca,SourabMangrulkar,DavidLansky,HuuNguyen,Danish Deng,ColinB.Clement,DawnDrain,NeelSundaresan,JianYin,DaxinJiang, Contractor,LuisVilla,JiaLi,DzmitryBahdanau,YacineJernite,SeanHughes, andMingZhou.2021.GraphCodeBERT:Pre-trainingCodeRepresentationswith DanielFried,ArjunGuha,HarmdeVries,andLeandrovonWerra.2023.Santa- DataFlow.In9thInternationalConferenceonLearningRepresentations,ICLR2021, Coder:don’treachforthestars! arXiv:2301.03988[cs.SE] VirtualEvent,Austria,May3-7,2021. [3] UriAlon,MeitalZilberstein,OmerLevy,andEranYahav.2019.Code2vec:Learn- [17] JordanHenkel,GouthamRamakrishnan,ZiWang,AwsAlbarghouthi,Somesh ingDistributedRepresentationsofCode. Proc.ACMProgram.Lang.3,POPL, Jha,andThomasReps.2022.SemanticRobustnessofModelsofSourceCode.In Article40(Jan.2019),29pages. https://doi.org/10.1145/3290353 2022IEEEInternationalConferenceonSoftwareAnalysis,EvolutionandReengi- [4] BanderAlsulami,EdwinDauber,RichardHarang,SpirosMancoridis,andRachel neering(SANER).526–537. https://doi.org/10.1109/SANER53432.2022.00070 Greenstadt.2017.SourceCodeAuthorshipAttributionUsingLongShort-Term [18] HamelHusain,Ho-HsiangWu,TiferetGazit,MiltiadisAllamanis,andMarc MemoryBasedNetworks.InComputerSecurity–ESORICS2017,SimonN.Foley, Brockschmidt.2019.CodeSearchNetchallenge:Evaluatingthestateofsemantic DieterGollmann,andEinarSnekkenes(Eds.).SpringerInternationalPublishing, codesearch.arXivpreprintarXiv:1909.09436(2019). Cham,65–82. [19] AkshitaJhaandChandanK.Reddy.2023.CodeAttack:Code-BasedAdversarial [5] LeonhardApplis,AnnibalePanichella,andArievanDeursen.2021.Assessing AttacksforPre-trainedProgrammingLanguageModels.arXiv:2206.00052[cs.CL] RobustnessofML-BasedProgramAnalysisToolsusingMetamorphicProgram [20] JinghanJia,ShashankSrikant,TamaraMitrovska,ChuangGan,ShiyuChang, Transformations.In202136thIEEE/ACMInternationalConferenceonAutomated SijiaLiu,andUna-MayO’Reilly.2023. CLAWSAT:TowardsBothRobustand SoftwareEngineering(ASE).1377–1381. https://doi.org/10.1109/ASE51524.2021. AccurateCodeModels.In2022IEEEInternationalConferenceonSoftwareAnalysis, 9678706 EvolutionandReengineering(SANER). [6] PavolBielikandMartinVechev.2020.AdversarialRobustnessforCode.InPro- [21] AdityaKanade,PetrosManiatis,GogulBalakrishnan,andKensenShi.2020. ceedingsofthe37thInternationalConferenceonMachineLearning(Proceedings Learningandevaluatingcontextualembeddingofsourcecode.InInternational ofMachineLearningResearch,Vol.119),HalDauméIIIandAartiSingh(Eds.). ConferenceonMachineLearning.PMLR,5110–5121. PMLR,896–907. https://proceedings.mlr.press/v119/bielik20a.html [22] AnjanKarmakarandRomainRobbes.2021.Whatdopre-trainedcodemodels [7] TomBrown,BenjaminMann,NickRyder,MelanieSubbiah,JaredDKaplan, knowaboutcode? arXiv:2108.11308[cs.SE] PrafullaDhariwal,ArvindNeelakantan,PranavShyam,GirishSastry,Amanda [23] NitishShirishKeskar,BryanMcCann,LavR.Varshney,CaimingXiong,and Askell,SandhiniAgarwal,ArielHerbert-Voss,GretchenKrueger,TomHenighan, RichardSocher.2019.CTRL:AConditionalTransformerLanguageModelfor RewonChild,AdityaRamesh,DanielZiegler,JeffreyWu,ClemensWinter,Chris ControllableGeneration. arXiv:1909.05858[cs.CL] Hesse,MarkChen,EricSigler,MateuszLitwin,ScottGray,BenjaminChess,Jack [24] Piergiorgio Ladisa, Henrik Plate, Matias Martinez, and Olivier Barais. Clark,ChristopherBerner,SamMcCandlish,AlecRadford,IlyaSutskever,and 2022. Taxonomy of Attacks on Open-Source Software Supply Chains. DarioAmodei.2020.LanguageModelsareFew-ShotLearners.InAdvancesin arXiv:2204.04008[cs.CR]
NeuralInformationProcessingSystems,H.Larochelle,M.Ranzato,R.Hadsell,M.F. [25] MikeLewis,YinhanLiu,NamanGoyal,MarjanGhazvininejad,Abdelrahman Balcan,andH.Lin(Eds.),Vol.33.CurranAssociates,Inc.,1877–1901. Mohamed,OmerLevy,VeselinStoyanov,andLukeZettlemoyer.2020. BART: [8] NghiD.Q.Bui,YueWang,andStevenHoi.2022.Detect-Localize-Repair:AUni- DenoisingSequence-to-SequencePre-trainingforNaturalLanguageGeneration, fiedFrameworkforLearningtoDebugwithCodeT5. arXiv:2211.14875[cs.SE] Translation,andComprehension.InProceedingsofthe58thAnnualMeetingof [9] LucaBuratti,SaurabhPujar,MihaelaA.Bornea,J.ScottMcCarley,Yunhui theAssociationforComputationalLinguistics.AssociationforComputational Zheng,GaetanoRossiello,AlessandroMorari,JimLaredo,VeronikaThost,Yu- Linguistics,Online,7871–7880. https://doi.org/10.18653/v1/2020.acl-main.703 fanZhuang,andGiacomoDomeniconi.2020.ExploringSoftwareNaturalness [26] JiaLi,ZhuoLi,HuangzhaoZhang,GeLi,ZhiJin,XingHu,andXinXia.2022. throughNeuralLanguageModels.CoRRabs/2006.12641(2020).arXiv:2006.12641 PoisonAttackandDefenseonDeepSourceCodeProcessingModels. arXiv https://arxiv.org/abs/2006.12641 preprintarXiv:2210.17029(2022). [10] MarkChen,JerryTworek,HeewooJun,QimingYuan,HenriquePondede [27] FangLiu,GeLi,YunfeiZhao,andZhiJin.2020. Multi-taskLearningbased OliveiraPinto,JaredKaplan,HarrisonEdwards,YuriBurda,NicholasJoseph, Pre-trainedLanguageModelforCodeCompletion. arXiv:2012.14631[cs.SE] GregBrockman,AlexRay,RaulPuri,GretchenKrueger,MichaelPetrov,Heidy [28] YinhanLiu,MyleOtt,NamanGoyal,JingfeiDu,MandarJoshi,DanqiChen,Omer Khlaaf,GirishSastry,PamelaMishkin,BrookeChan,ScottGray,NickRyder, Levy,MikeLewis,LukeZettlemoyer,andVeselinStoyanov.2019.RoBERTa:A MikhailPavlov,AletheaPower,LukaszKaiser,MohammadBavarian,Clemens RobustlyOptimizedBERTPretrainingApproach.CoRRabs/1907.11692(2019). Winter,PhilippeTillet,FelipePetroskiSuch,DaveCummings,MatthiasPlappert, arXiv:1907.11692 http://arxiv.org/abs/1907.11692 FotiosChantzis,ElizabethBarnes,ArielHerbert-Voss,WilliamHebgenGuss, [29] ShuaiLu,DayaGuo,ShuoRen,JunjieHuang,AlexeySvyatkovskiy,Ambrosio AlexNichol,AlexPaino,NikolasTezak,JieTang,IgorBabuschkin,SuchirBalaji, Blanco,ColinClement,DawnDrain,DaxinJiang,DuyuTang,GeLi,LidongZhou, ShantanuJain,WilliamSaunders,ChristopherHesse,AndrewN.Carr,JanLeike, LinjunShou,LongZhou,MicheleTufano,MingGong,MingZhou,NanDuan, JoshuaAchiam,VedantMisra,EvanMorikawa,AlecRadford,MatthewKnight, NeelSundaresan,ShaoKunDeng,ShengyuFu,andShujieLiu.2021.CodeXGLUE: MilesBrundage,MiraMurati,KatieMayer,PeterWelinder,BobMcGrew,Dario AMachineLearningBenchmarkDatasetforCodeUnderstandingandGeneration. Amodei,SamMcCandlish,IlyaSutskever,andWojciechZaremba.2021. Eval- arXiv:2102.04664[cs.SE] uatingLargeLanguageModelsTrainedonCode.CoRRabs/2107.03374(2021). [30] AleksanderMadry,AleksandarMakelov,LudwigSchmidt,DimitrisTsipras,and arXiv:2107.03374 https://arxiv.org/abs/2107.03374 AdrianVladu.2018. TowardsDeepLearningModelsResistanttoAdversarial [11] JacobDevlin,Ming-WeiChang,KentonLee,andKristinaToutanova.2019.BERT: Attacks.In6thInternationalConferenceonLearningRepresentations,ICLR2018, Pre-trainingofDeepBidirectionalTransformersforLanguageUnderstanding. Vancouver,BC,Canada,April30-May3,2018,ConferenceTrackProceedings. InProceedingsofthe2019ConferenceoftheNorthAmericanChapteroftheAsso- [31] PhuongT.Nguyen,ClaudioDiSipio,JuriDiRocco,MassimilianoDiPenta, ciationforComputationalLinguistics:HumanLanguageTechnologies,Volume1 andDavideDiRuscio.2021. AdversarialAttackstoAPIRecommenderSys- (LongandShortPapers).AssociationforComputationalLinguistics,Minneapolis, tems:TimetoWakeUpandSmelltheCoffee?.In202136thIEEE/ACMInter- Minnesota,4171–4186. https://doi.org/10.18653/v1/N19-1423 nationalConferenceonAutomatedSoftwareEngineering(ASE).253–265. https: [12] DawnDrain,ChenWu,AlexeySvyatkovskiy,andNeelSundaresan.2021.Gen- //doi.org/10.1109/ASE51524.2021.9678946 eratingBug-FixesUsingPretrainedTransformers.InProceedingsofthe5thACM [32] ErikNijkamp,BoPang,HiroakiHayashi,LifuTu,HuanWang,YingboZhou, SIGPLANInternationalSymposiumonMachineProgramming(Virtual,Canada) SilvioSavarese,andCaimingXiong.2023.CodeGen:AnOpenLargeLanguage (MAPS2021).AssociationforComputingMachinery,NewYork,NY,USA,1–8. ModelforCodewithMulti-TurnProgramSynthesis.InTheEleventhInternational https://doi.org/10.1145/3460945.3464951 ConferenceonLearningRepresentations.
[13] ZhangyinFeng,DayaGuo,DuyuTang,NanDuan,XiaochengFeng,MingGong, [33] ChanganNiu,ChuanyiLi,VincentNg,DongxiaoChen,JidongGe,andBin LinjunShou,BingQin,TingLiu,DaxinJiang,andMingZhou.2020.CodeBERT: Luo.2023. AnEmpiricalComparisonofPre-TrainedModelsofSourceCode. APre-TrainedModelforProgrammingandNaturalLanguages.InFindingsofthe arXiv:2302.04026[cs.SE]AdversarialAttacksonCodeModelswithDiscriminativeGraphPatterns Conference’17,July2017,Washington,DC,USA [34] ChanganNiu,ChuanyiLi,VincentNg,JidongGe,LiguoHuang,andBinLuo.2022. [45] JeffreySvajlenko,JudithF.Islam,ImanKeivanloo,ChanchalK.Roy,andMoham- SPT-Code:Sequence-to-SequencePre-TrainingforLearningSourceCodeRepre- madMamunMia.2014.TowardsaBigDataCuratedBenchmarkofInter-project sentations.InProceedingsofthe44thInternationalConferenceonSoftwareEngi- CodeClones.In2014IEEEInternationalConferenceonSoftwareMaintenanceand neering(Pittsburgh,Pennsylvania)(ICSE’22).AssociationforComputingMachin- Evolution.IEEE. https://doi.org/10.1109/icsme.2014.77 ery,NewYork,NY,USA,2006–2018. https://doi.org/10.1145/3510003.3510096 [46] MarisaThoma,HongCheng,ArthurGretton,JiaweiHan,Hans-PeterKriegel, [35] LongPhan,HieuTran,DanielLe,HieuNguyen,JamesAnnibal,AlecPeltekian, AlexSmola,LeSong,PhilipS.Yu,XifengYan,andKarstenM.Borgwardt.2010. andYanfangYe.2021.CoTexT:Multi-taskLearningwithCode-TextTransformer. Discriminativefrequentsubgraphminingwithoptimalityguarantees.Statistical InProceedingsofthe1stWorkshoponNaturalLanguageProcessingforProgram- AnalysisandDataMining3,5(Aug.2010),302–318. https://doi.org/10.1002/sam. ming(NLP4Prog2021).AssociationforComputationalLinguistics,Online,40–47. 10084 https://doi.org/10.18653/v1/2021.nlp4prog-1.5 [47] JunfengTian,ChenxinWang,ZhenLi,andYuWen.2021.GeneratingAdversarial [36] MaryamVahdatPour,ZhuoLi,LeiMa,andHadiHemmati.2021. ASearch- ExamplesofSourceCodeClassificationModelsviaQ-Learning-BasedMarkovDe- BasedTestingFrameworkforDeepNeuralNetworksofSourceCodeEmbedding. cisionProcess.In2021IEEE21stInternationalConferenceonSoftwareQuality,Reli- arXiv:2101.07910[cs.SE] abilityandSecurity(QRS).807–818. https://doi.org/10.1109/QRS54544.2021.00090 [37] WeizhenQi,YeyunGong,YuYan,CanXu,BolunYao,BartuerZhou,Biao [48] YaoWan,ShijieZhang,HongyuZhang,YuleiSui,GuandongXu,Dezhong Cheng, Daxin Jiang, Jiusheng Chen, Ruofei Zhang, Houqiang Li, and Nan Yao,HaiJin,andLichaoSun.2022. YouSeeWhatIWantYoutoSee:Poi- Duan.2021. ProphetNet-X:Large-ScalePre-trainingModelsforEnglish,Chi- soningVulnerabilitiesinNeuralCodeSearch.InProceedingsofthe30thACM nese,Multi-lingual,Dialog,andCodeGeneration.InProceedingsofthe59th JointEuropeanSoftwareEngineeringConferenceandSymposiumontheFoun- AnnualMeetingoftheAssociationforComputationalLinguisticsandthe11th dationsofSoftwareEngineering(Singapore,Singapore)(ESEC/FSE2022).As- InternationalJointConferenceonNaturalLanguageProcessing:SystemDemon- sociationforComputingMachinery,NewYork,NY,USA,1233–1245. https: strations.AssociationforComputationalLinguistics,Online,232–239. https: //doi.org/10.1145/3540250.3549153 //doi.org/10.18653/v1/2021.acl-demo.28 [49] YueWang,WeishiWang,ShafiqJoty,andStevenC.H.Hoi.2021. CodeT5: [38] MdRafiqulIslamRabin,NghiDQBui,KeWang,YijunYu,LingxiaoJiang,and Identifier-awareUnifiedPre-trainedEncoder-DecoderModelsforCodeUnder- MohammadAminAlipour.2021.OnthegeneralizabilityofNeuralProgramMod- standingandGeneration.InProceedingsofthe2021ConferenceonEmpirical elswithrespecttosemantic-preservingprogramtransformations.Information MethodsinNaturalLanguageProcessing,EMNLP2021. andSoftwareTechnology135(2021),106552. [50] ZhouYang,JiekeShi,JundaHe,andDavidLo.2022.Naturalattackforpre-trained [39] AlecRadford,JeffWu,RewonChild,DavidLuan,DarioAmodei,andIlya modelsofcode.InProceedingsofthe44thInternationalConferenceonSoftware Sutskever.2019.LanguageModelsareUnsupervisedMultitaskLearners.(2019). Engineering.ACM. https://doi.org/10.1145/3510003.3510146 [40] ColinRaffel,NoamShazeer,AdamRoberts,KatherineLee,SharanNarang, [51] ZhouYang,BowenXu,JieM.Zhang,HongJinKang,JiekeShi,JundaHe, MichaelMatena,YanqiZhou,WeiLi,andPeterJ.Liu.2020.ExploringtheLimits andDavidLo.2023. StealthyBackdoorAttackforCodeModels. https: ofTransferLearningwithaUnifiedText-to-TextTransformer.JournalofMachine //doi.org/10.48550/ARXIV.2301.02496 LearningResearch21,140(2020),1–67. http://jmlr.org/papers/v21/20-074.html [52] NoamYefet,UriAlon,andEranYahav.2020.Adversarialexamplesformodelsof [41] G.RamakrishnanandA.Albarghouthi.2022. BackdoorsinNeuralModels code.ProceedingsoftheACMonProgrammingLanguages4,OOPSLA(2020).
ofSourceCode.In202226thInternationalConferenceonPatternRecognition [53] HuangzhaoZhang,ZhiyiFu,GeLi,LeiMa,ZhehaoZhao,Hua’anYang,Yizhe (ICPR).IEEEComputerSociety,LosAlamitos,CA,USA,2892–2899. https: Sun,YangLiu,andZhiJin.2022.TowardsRobustnessofDeepProgramProcess- //doi.org/10.1109/ICPR56361.2022.9956690 ingModels—Detection,Estimation,andEnhancement.ACMTrans.Softw.Eng. [42] RoeiSchuster,CongzhengSong,EranTromer,andVitalyShmatikov.2021.You Methodol.31,3,Article50(apr2022),40pages. https://doi.org/10.1145/3511887 AutocompleteMe:PoisoningVulnerabilitiesinNeuralCodeCompletion.In [54] HuangzhaoZhang,ZhuoLi,GeLi,LeiMa,YangLiu,andZhiJin.2020.Gener- 30thUSENIXSecuritySymposium(USENIXSecurity21).USENIXAssociation, atingAdversarialExamplesforHoldingRobustnessofSourceCodeProcessing 1559–1575. Models.ProceedingsoftheAAAIConferenceonArtificialIntelligence34,01(Apr. [43] Shashank Srikant, Sijia Liu, Tamara Mitrovska, Shiyu Chang, Quanfu Fan, 2020),1169–1176. GaoyuanZhang,andUna-MayO’Reilly.2021. GeneratingAdversarialCom- [55] ShuyanZhou,UriAlon,SumitAgarwal,andGrahamNeubig.2023. Code- puterProgramsusingOptimizedObfuscations.ICLR16(2021),209–226. BERTScore: Evaluating Code Generation with Pretrained Models of Code. [44] ZhensuSun,XiaoningDu,FuSong,MingzeNi,andLiLi.2022. CoProtector: arXiv:2302.05527[cs.SE] ProtectOpen-SourceCodeagainstUnauthorizedTrainingUsagewithDataPoi- [56] YaqinZhou,ShangqingLiu,JingkaiSiow,XiaoningDu,andYangLiu.2019.De- soning.InProceedingsoftheACMWebConference2022(VirtualEvent,Lyon, vign:EffectiveVulnerabilityIdentificationbyLearningComprehensiveProgram France)(WWW’22).AssociationforComputingMachinery,NewYork,NY,USA, SemanticsviaGraphNeuralNetworks. arXiv:1909.03496[cs.SE] 652–660. https://doi.org/10.1145/3485447.3512225
2308.11237 Distinguishing Look-Alike Innocent and Vulnerable Code by Subtle Semantic Representation Learning and Explanation ChaoNi XinYin KaiwenYang SchoolofSoftwareTechnology, SchoolofSoftwareTechnology, CollegeofComputerScienceand ZhejiangUniversity ZhejiangUniversity Technology,ZhejiangUniversity Hangzhou,Zhejiang,China Hangzhou,Zhejiang,China Hangzhou,Zhejiang,China chaoni@zju.edu.cn xyin@zju.edu.cn kwyang@zju.edu.cn DehaiZhao ZhenchangXing XinXia∗ Data61,CSIRO ResearchSchoolofComputerScience, ZhejiangUniversity Sydney,Australia AustralianNationalUniversityand Hangzhou,Zhejiang,China dehai.zhao@data61.csiro.au Data61,CSIRO xin.xia@acm.org Canberra,Australia zhenchang.xing@anu.edu.au ABSTRACT CCSCONCEPTS Though many deep learning (DL)-based vulnerability detection •Securityandprivacy→Softwaresecurityengineering. approacheshavebeenproposedandindeedachievedremarkable KEYWORDS performance,theystillhavelimitationsinthegeneralizationaswell asthepracticalusage.Moreprecisely,existingDL-basedapproaches VulnerabilityDetection,Developer-orientedExplanation,Subtle (1)performnegativelyonpredictiontasksamongfunctionsthat SemanticDifference,ContrastiveLearning arelexicallysimilarbuthavecontrarysemantics;(2)provideno intuitivedeveloper-orientedexplanationstothedetectedresults. ACMReferenceFormat: In this paper, we propose a novel approach named SVulD, a ChaoNi,XinYin,KaiwenYang,DehaiZhao,ZhenchangXing,andXinXia. function-levelSubtlesemanticembeddingforVulnerabilityDetection 2023. DistinguishingLook-AlikeInnocentandVulnerableCodebySubtle SemanticRepresentationLearningandExplanation.InProceedingsofthe alongwithintuitiveexplanations,toalleviatetheabovelimitations. 31stACMJointEuropeanSoftwareEngineeringConferenceandSymposium Specifically,SVulDfirstlytrainsamodeltolearndistinguishing ontheFoundationsofSoftwareEngineering(ESEC/FSE’23),December3–9, semanticrepresentationsoffunctionsregardlessoftheirlexicalsim- 2023,SanFrancisco,CA,USA.ACM,NewYork,NY,USA,12pages.https: ilarity.Then,forthedetectedvulnerablefunctions,SVulDprovides //doi.org/10.1145/3611643.3616358 naturallanguageexplanations(e.g.,rootcause)ofresultstohelp developersintuitivelyunderstandthevulnerabilities.Toevaluate 1 INTRODUCTION theeffectivenessofSVulD,weconductlarge-scaleexperimentson awidelyusedpracticalvulnerabilitydatasetandcompareitwith Softwarevulnerabilitieshavecausedmassivedamagetosoftware fourstate-of-the-art(SOTA)approachesbyconsideringfiveper- systemsandmanyautomaticvulnerabilitydetectionapproaches formancemeasures.TheexperimentalresultsindicatethatSVulD have been proposed to prevent software systems from severity outperformsallSOTAswithasubstantialimprovement(i.e.,23.5%- attacksandindeedachievedpromisingresults,whichcanbebroadly 68.0%intermsofF1-score,15.9%-134.8%intermsofPR-AUCand classifiedintotwocategories:staticanalysisapproaches[1,2,17,25, 7.4%-64.4%intermsofAccuracy).Besides,weconductauser-case 26,41]anddeeplearning(DL)approaches[7,8,11,16,28–31,43– studytoevaluatetheusefulnessofSVulDfordevelopersonun- 45].Thestaticanalysisapproachesfocusondetectingtype-specific derstanding the vulnerable code and the participants’ feedback vulnerabilities(i.e.,user-after-free)withthehelpofuser-defined demonstratesthatSVulDishelpfulfordevelopmentpractice. rulesorpatterns,whichhighlydependonexpertknowledgeand havelittlechancetofindawiderrangeofvulnerabilities[7,12].The deeplearningapproaches,benefitingfromthepowerfullearning ∗XinXiaisthecorrespondingauthor. abilityofdeepneuralnetworks,aimatleveragingadvancedmodels tocaptureprogramsemanticstoidentifypotentialtype-agnostic softwarevulnerabilities.Thatis,theseapproachesautomatically Permissiontomakedigitalorhardcopiesofallorpartofthisworkforpersonalor extractimplicitvulnerabilitypatternsfrompreviousvulnerable classroomuseisgrantedwithoutfeeprovidedthatcopiesarenotmadeordistributed forprofitorcommercialadvantageandthatcopiesbearthisnoticeandthefullcitation codeinsteadofrequiringexpertinvolvement,whichmakesdeep onthefirstpage.Copyrightsforcomponentsofthisworkownedbyothersthanthe learning become a good choice to solve vulnerability detection author(s)mustbehonored.Abstractingwithcreditispermitted.Tocopyotherwise,or problems.However,theexistingDL-basedapproachesstillhave republish,topostonserversortoredistributetolists,requirespriorspecificpermission and/orafee.Requestpermissionsfrompermissions@acm.org. twolimitationsthataffecttheireffectivenessofgeneralizationand ESEC/FSE’23,December3–9,2023,SanFrancisco,CA,USA theusefulnessofdevelopmentpractice. ©2023Copyrightheldbytheowner/author(s).PublicationrightslicensedtoACM. The first problem is that existing DL-based approaches have ACMISBN979-8-4007-0327-0/23/12...$15.00 https://doi.org/10.1145/3611643.3616358 limitedabilitytodistinguishsubtlesemanticdifferencesamong 3202 guA 22 ]ES.sc[
1v73211.8032:viXraESEC/FSE’23,December3–9,2023,SanFrancisco,CA,USA ChaoNi,XinYin,KaiwenYang,DehaiZhao,ZhenchangXing,andXinXia lexicallysimilarfunctions.Foraspecificversionofavulnerable Vulnerable Function Fixed/Clean Function function,thevulnerabilitiesareusuallyfixedwithafewmodifi- 01 lookup_bytestring(netdissect_options*ndo, registerconst 01lookup_bytestring(netdissect_options*ndo, registerconst u_char*bs,constunsignedintnlen) u_char*bs,constunsignedintnlen) cationstoit(i.e.,52.6%vulnerablefunctionscanbefixedwithin5 02 { 02{ 03 structenamemem*tp; 03 structbsnamemem*tp; (76.7%within10)linesofcodeinourdataset).Thefixedfunctions …… …… 16 while(tp->e_nxt) 16 while(tp->bs_nxt) canbeconceptuallytreatedasnon-vulnerablefunctions.Meanwhile, 17 if(tp->e_addr0 == i&& 17 if(nlen == tp->bs_nbytes && 18 tp->e_addr1 == j && 18 tp->bs_addr0 == i&& wefindthatthevulnerablefunctionanditscorrespondingfixedfunc- 19 tp->e_addr2 == k && 19 tp->bs_addr1 == j && 20 memcmp((constchar*)bs, (constchar*)(tp- 20 tp->bs_addr2 == k && tionareextremelylexicallysimilar(i.e.,fixing avulnerabilityby >e_bs), nlen) == 0) 21 memcmp((constchar*)bs, (constchar*) returntp; (tp->bs_bytes), nlen) == 0) modifyinglessthan100CHARsaccountsfor46.0%(200for65.1%)) else returntp; 23 tp= tp->e_nxt; else buttheyhavesignificantsemanticdifferences(i.e.,vulnerableornon- 24 tp->e_addr0 = i; 24 tp= tp->bs_nxt; 25 tp->e_addr1 = j; 25 tp->bs_addr0 = i; vulnerable).Ideally,weexpectthatagood-performingDL-based 26 tp->e_addr2 = k; 26 tp->bs_addr1 = j; 27 tp->e_bs= (u_char*) calloc(1, nlen+ 1); 27 tp->bs_addr2 = k; approachcanperformequallywellindetectingvulnerablefunc- 28 if(tp->e_bs== NULL) 28 tp->bs_bytes= (u_char*) calloc(1, nlen+ 1); (*ndo->ndo_error)(ndo, "lookup_bytestring: calloc");29 if(tp->bs_bytes == NULL) tionsandtheircorrespondingfixingpatches.However,wefindthat 31 memcpy(tp->e_bs, bs, nlen); (*ndo->ndo_error)(ndo, "lookup_bytestring: calloc"); 32 tp->e_nxt= (structenamemem*)calloc(1, sizeof(*tp)); 32 memcpy(tp->bs_bytes, bs, nlen); theSOTADL-basedapproachesperformnegativelyonthefixed 33 if(tp->e_nxt== NULL) 33 tp->bs_nbytes = nlen; (*ndo->ndo_error)(ndo, "lookup_bytestring: calloc");34 tp->bs_nxt= (structbsnamemem*)calloc(1, functions(i.e.,non-vulnerableones)andincorrectlyclassifythe returntp; sizeof(*tp)); } 35 if(tp->bs_nxt== NULL) fixedversionasvulnerableones(43.5%-63.1%falsepositive).Thus, (*ndo->ndo_error)(ndo, "lookup_bytestring: calloc"); returntp; itisurgentlyrequiredtopaymoreattentiontosemanticdifferences } amonglexicallysimilarfunctionswithcontrastingsemantics. Figure1:AnOut-of-boundsReadVulnerability(CVE-2017- Thesecondproblemisthatexistingvulnerabilitydetectionap- 12894)intcpdump proachesfocusongivingbinarydetectionresults(i.e.,vulnerable ornot)andignoretheimportanceofprovidingdeveloper-oriented natural-languageexplanationsfortheresults.Forexample,what explanationofthedetectedvulnerablecode,wedesignaquality- isthepossiblerootcauseofsuchvulnerability? whatimpactswill firstsortingstrategytoprioritizetheretrievedsemantic-related becausedbythisvulnerability? Thoseexplanationsmayhelpde- postanswers.Weconductauser-casestudytoevaluatewhether veloperstohaveabetterunderstandingofthedetectedvulnerable ourtoolcanhelpdevelopersunderstandtheproblemsincodeintu- code.However,consideringtheconcealmentofsoftwarevulnerabil- itivelyandtheparticipants’feedbackdemonstratestheusefulness ities,itishardtoobservetwoidenticalvulnerabilities.Itisbelieved ofSVulD.Finally,thispapermakesthemaincontributionsasbelow: thatsimilar/homogeneousvulnerabilitieshavesimilarrootcauses • WeproposeSVulD,anovelfunction-levelapproachforvulnerabil- orleadtosimilarimpacts.Intuitively,wefindthatmanypublicly itydetectionwithintuitiveexplanationsbasedonthepre-trained availabledeveloperforums(i.e.,StackOverflow)sharesemantically semanticembeddingmodel,whichleveragescontrastivelearning similarproblematicsourcecode,andsomeoftheresponsesprovide technologytoobtainthedistinguishingsemanticrepresentations usefulandunderstandablenaturallanguageexplanationsaboutthe amonglexicallysimilarfunctions. issues,whichhelpdeveloperstointuitivelyfigureoutthepotential • WecomprehensivelyinvestigatetheeffectivenessofSVulDon rootcauseinsidetheirproblematiccode. vulnerabilitydetectionandthegeneralizationoffixedfunctions.
Tomitigatetheabovetwolimitations,weproposeanovelap- TheexperimentresultsindicatethatSVulDoutperformsSOTAs proachnamedSVulD,whichisafunction-levelSubtlesemantic withasubstantialimprovement(e.g.,23.5%-68.0%intermsof embeddingforVulnerabilityDetectionalongwithintuitiveexplana- F1-score,15.9%-134.8%intermsofPR-AUC).Especially,SVulD tions.Itistechnicallybasedonpre-trainedsemanticembedding[22] hasbettergeneralizationperformanceonfixedfunctions(e.g., aswellascontrastivelearning[10].Specifically,tosolvethefirst 7.4%-64.4%intermsofAccuracy). issue,SVulDadoptscontrastivelearningtotraintheUniXcoder[22] • Tothebestofourknowledge,wearefirsttoprovideanintu- semanticembeddingmodelinordertolearnthesemanticrepresen- itiveexplanationoftheresultsgivenbyavulnerabilitydetection tationoffunctionsregardlessoftheirlexicallysimilarinformation. approach,andauser-casestudyconfirmsthefeasibilityofintu- Toaddressthesecondissue,webuildaknowledge-basedcrowd- itivelyexplainingtheresultswithcrowdsourcedknowledge. sourcedatasetbycrawlingproblematiccodesfromStackOverflow andfine-tuneaBERTquestion-answeringmodel[14,39]on1,678 2 MOTIVATINGEXAMPLE manuallylabeledpoststoautomaticallyextractthekeyinforma- tionfromhigh-qualityanswers,whichcanprovidedeveloperswith Functionsusuallyconsistofseverallinesofcodeforimplementing intuitiveexplanationsandhelpthemtounderstandthedetected aspecificprogramsemantic(i.e.,functionality)andweusedifferent vulnerablecode. labels(i.e.,vulnerable,non-vulnerable)todescribethesecuritystatus ToevaluatetheeffectivenessofSVulD,weconductextensiveex- offunctions.Avulnerablefunctionincludessecuritydefects(e.g., perimentsonwidelyusedpracticalvulnerabilitydataset[12,27,35]. CWE-125:Out-of-boundsRead)initscodes,whileanon-vulnerable Particularly,ourSVulDiscomparedwithfourSOTAapproaches functionisclean.Afixedfunctionpreviouslycontainsvulnerable (i.e.,Devign,ReVeal,IVDetect,andLineVul)byfiveperformance codesbutthesecodeshavebeenfixedwithsomemodificationson measures(i.e.,Accuracy,Precision,Recall,F1-score,andPR-AUC). thevulnerablecodesnippets.Therefore,thefixedfunctionscanbe TheexperimentalresultsindicatethatSVulDoutperformsallSOTA conceptuallytreatedasnon-vulnerablefunctions. baselineswithasubstantialimprovement(i.e.,23.5%-68.0%interms Fig.1showstwoversions(theleftoneisforthevulnerablever- ofF1-score,15.9%-134.8%intermsofPR-AUCand7.4%-64.4%in sion,whiletherightoneisforthenon-vulnerableversion)ofa termsofAccuracy).Besides,toprovidedeveloperswithanintuitive specificfunctionintcpdumpproject[21].ThisfunctioncontainsDistinguishingLook-AlikeInnocentandVulnerableCode... ESEC/FSE’23,December3–9,2023,SanFrancisco,CA,USA atypicalOut-of-boundsReadvulnerabilityCVE-2017-12894.The Motivating.Twocodesnippetsmaybelexicallysimilarbuthave if condition statement does not detect the length of the address distinctsecuritysemantics(vulnerableornon-vulnerable),which at line 17. Comparing the left vulnerable one with the right non- needstoembedtheirsemanticdifferenceinabetterway.Mean- vulnerable/fixedone,wefindthatthetwoversionsarelexicallysim- while,similarvulnerabilitiesmayhaveasimilarrootcause,which ilarbuthavedistinguishingsemanticdifferencesfromthesecurity canhelpparticipantsunderstandtheproblematiccodesbetter. perspective,whichisnotanaccidentalphenomenon.Weconduct statisticalanalysisaboutthevulnerablefunctionsaswellastheir correspondingfixedfunctionsonthewidelyuseddatasetnamed Big-Vul(10,900vulnerablefunctions)collectedbyFanetal.[18]and Products Search… findthat52.6%vulnerablefunctionscanbefixedwithinfivelines Home Odd runtime error in C? ofcodes(LOCs,addedordeletedlines)and76.7%functionscan Forsomereasonikeepgettinganoddruntimeerrorwhenirunthisprogram. PUBLIC Itcompilesfine,andmostoftheprogramworks. befixedwithlessthan10LOCs.Fromtheviewofmodifiedchars, Questions #include……; fixingavulnerabilitybymodifyinglessthan100charsaccounts Tags main() {printf("This program will show you the scores of the basketball games for 1 for46.0%(200charsfor65.1%).Meanwhile,afunctionhasaratio Companies season.\n"); ofnomorethan5%accountsfor48.7%(10%for63.4%)between COLLECTIVES printf("What is the name of the basketball league? "); ExploreCollectives stringleague = GetLine(); thenumberofmodifiedcharsandthewholenumberofchars.All printf("How may games were played by the group? "); thesestatisticalresultsindicatethatthevulnerablefunctionand TEAMS intgamesplayed= GetInteger(); CreatefreeTeam stringteams[3]; thecorrespondingfixedfunctionareextremelylexicallysimilar. intwonGames[3],a, b, c; for(a = 0; a < 4; a++) Recently,benefitingfromthepowerfullearningabilityofdeep { printf("What is team %d's name? ", a+1); neural networks, many SOTA DL-based vulnerability detection teams[a] = GetLine(); }
approaches (e.g., Devign [45], ReVeal [8], IVDetect [27], and for(b = 0; b < 4; b++) LineVul[19])havebeenproposedtocaptureprogramsemantics { printf("How many times did team %swin? ", teams[b]); wonGames[b] = GetInteger(); inordertoidentifypotentialsoftwarevulnerabilities,andthese } approacheshaveachievedpromisingperformance.Ideally,agood- printf("\n\n----===[%s]===----\n", league); printf("Team Name | Games Played | Games Won | Percentage"); performingDL-basedapproachisexpectedtohaveagoodgeneral- for(c = 0; c < 4; c++) izationability,whichmeansthattheapproachshouldworkwellon { doublepercent = 100* (wonGames[c]/gamesplayed); printf("| %s| %d| %d| %lf|", teams[c], gamesplayed, wonGames[c], bothvulnerableandcorrespondingfixednon-vulnerablefunctions. percent); However,alarge-scaleexperimentonBig-Vulshowsthatallthese } } SOTAapproacheshavenegativeperformanceonpredictingthe Theproblemseemstobewithprintingteams[3]inthelastforloop.Nomatter fixedfunctions(i.e.,non-vulnerableones).Specifically,theyincor- whatidoitcrashesafteritprintsprintf(“TeamName|GamesPlayed|Games rectlyclassifythefixedfunctionsasvulnerableones(43.5%-63.1% Won | Percentage”); The library GetInteger() and GetLine() are the two functionsiusetogetinput,itsfromthesimpio.hlibrary.Anyhelpwouldbe falsepositive,cf.Section5.1fordetails). appreciated. Answer Meanwhile,almostallexistingvulnerabilitydetectionapproaches stringteams[3]; focusonclassifyingwhetherafunctionisvulnerablebutdonot for(a = 0; a < 4; a++) { providedeveloper-orientednatural-languageexplanationstohelp printf("What is team %d's name? ", a+1); developersunderstandthedetectedvulnerablecode.Forexample, teams[a] = GetLine(); } whatisthepossiblerootcauseofsuchvulnerability?whatimpacts Root CauseYou are going out of bounds, since teams has size 3 willbecausedbythisvulnerability?Suchtypesofexplanationsmay andawilleventuallygetthevalue3.Indexingstartsfrom0tosizeof (atleastintuitively)helpdeveloperstohaveadeeperunderstanding array-1.SolutionSochange4with3,orincreasethesizebyone. DothesameforwonGames.Similarly,theloopwiththecountercshould ofthedetectedvulnerablecode.Intuitively,manypubliclyavail- bemodifiedtoo(ifthesizeofthearrayisnotincreased). ableuserforums(i.e.,StackOverflow)sharesimilarproblematic Figure2:Asimplebutsimilarproblematiccodealongwith sourcecodeandtheircorrespondingresponsesmayprovideuseful anacceptedanswerinStackOverflow. andunderstandablenaturallanguageexplanationsabouttheissues, whichcanintuitivelyhelpdeveloperstofigureoutthepotential 3 OURAPPROACH:SVULD rootcauseinsidethevulnerablecode. AsshowninFig.2,thiscodesnippethasasimilarrootcause Toinvestigatethefeasibilityofourintuitivehypothesis,wepro- withthevulnerablefunctioninFig.1.Itcrashesbecauseofthe poseanovelframeworknamedSVulD,whichintegratessoftware limitedsizeofdefinedarrays(i.e.,teamsandwonGames),which vulnerabilitydetectionandintuitivenaturallanguageexplanation. resultsinanOut-of-boundserrorwhenreadingandwritingcontent AsillustratedinFig.3,SVulDconsistsoftwomainphases:❶train- tothelastelement.Similarly,thefunctioninFig.1willcrashwhen ingphase,wherethevulnerabilitydetectoristrainedonthehigh- thelastelementintheiraddressarraydoesnotsatisfythelengthof qualitydatasetandvulnerabilityexplainerisconstructedoncrowd- alegalinternetaddress.Ifdevelopersareprovidedwithanatural sourcedknowledge;❷inferencephase,whereaspecificfunction languageexplanationoftherootcausereferringtotheanswerin isclassifiedasvulnerableornotbythetrainedvulnerabilityde- Fig.2,theprobleminFig.1willbeeasiertosolve. tectorandprovideseveraldeveloper-orientedexplanationstothe detectedvulnerablefunction.WepresentthedetailsofSVulDin thefollowingsubsections.ESEC/FSE’23,December3–9,2023,SanFrancisco,CA,USA ChaoNi,XinYin,KaiwenYang,DehaiZhao,ZhenchangXing,andXinXia Training Phase Vulnerability Detector Vulnerability Explainer [Prefix] FlattenedAST CrowdsourcedKnowledge ExplainableKnowledge Extractor Function +t0 t +1 +t2 ...... tm +-1 t +m TE Post Content Key Knowledges Root 0 1 2 ...... m-1 m PE Post Code BERT-QA Impact UniXcoder Answer Response Solution Content (Pre-trainedWithContrastiveLearning) Function Developer-oriented Outputs Vulnerable Root Vulnerability Vulnerability Impact Detector Explainer Solution Inference Phase Non-Vulnerable Figure3:TheframeworkofSVulD. 3.1 VulnerabilityDetection etal.[24]proposedthetripletnetworkforcontrastivelearning, Inordertodiscriminatethesemanticdifferenceamonglexically whichrequiresatriplet(𝐹,𝑃,𝑁)astheinput,where𝐹 corresponds similar functions effectively, SVulD adopts contrastive learning totheoriginalsourcecodeofthefunction,𝑃 referstothepositive frameworkwiththepre-trainedmodel,UniXcoder[22],asthese- equivalentof𝐹,and𝑁 isthenegativeone.Inourwork,foragiven mantic encoder. The architecture for contrastively training the function𝐹inthetrainingdata,itspositivefunctionsarethevarying
UniXcoder-basedsemanticembeddingmodelisillustratedinFig.4. representationofthesamefunctionsandthenegativefunctions Contrastivelearning[36]isakindofdeepneuralnetworktraining arefunctionsthataredifferentfromthegivenone.Therefore,with processthattakespairedfunctionsasinputandusesthesimilar- agoodsemanticpresentation,similarfunctionsstayclosetoeach itybetweenthepairedfunctionsaslabels.Thetrainingobjective otherwhiledissimilaronesarefarapart. ofcontrastivelearningistolearnwhethertwofunctionsarese- Fig.4showsthearchitectureofthecontrastivelearningused manticallysimilarregardlessoftheirlexicalsimilarity.Elaborately, inthiswork,inwhichtheUniXcoderisthebasemodelforseman- thecontrastivelearningframeworkutilizestheencodertoembed ticembedding.WeuseaPoolinglayertoconnecttheUniXcoder sourcecodeintotheirsemanticrepresentations(i.e.,hiddenvec- modelandthetriplenetwork.Thetriplenetworkhastwolayers. tors)andaimsatminimizingthedistancebetweensimilarfunctions Thefirstlayeristhreeidenticaldeepneuralnetworksforfeature whilemaximizingthedistancebetweendissimilarfunctions.There extractionofinputfunctions,whichcanbeeasilyreplacedwith aretwoimportantcomponentsoftheproposedmodel:anencoder othersemanticlearningmodels.Thesecondlayerofthetriplet forembeddingfunctions’semanticsandalearningstrategyfor networkisalossfunctionbasedonthecosinedistanceoperator discriminatingdifferences. withtransformationoperationsofprojector,whichisusedtomin- imizethedistancebetweensimilarfunctionsandmaximizethe 3.1.1 SemanticEncoder. Consideringmanysuccessfulapplications distancebetweendissimilarfunctions.Thetrainingobjectiveisto ofpre-trainedmodelsinsoftwareengineering(e.g.,defectpredic- fine-tunethenetworksothatthedistancebetweenthefunctions tion[33]andcodesummarization[46]),especiallytherecentwork 𝐹 andthepositivefunctions𝑃 iscloserthanthedistancebetween onvulnerabilitydetection[19],weleverageUniXcoder[22]asour thefunctions𝐹 andthenegativefunctions𝑁,whichisillustrated semanticencoder.Itisaunifiedcross-modal(i.e.,code,comment below: andabstractsyntaxtree(AST))pre-trainedmodelforprogramming languageandutilizesmaskattentionmatriceswithprefixadapters 𝑚𝑎𝑥(||𝐸𝐹 −𝐸𝑃||−||𝐸𝐹 −𝐸𝑁||+𝜖,0) (1) (i.e.,[prefix])tocontrolthebehaviorofthemodel(i.e.,encoderonly ([Enc]),decoderonly([Dec])orencoder-decoder([E2D])).Foreach where𝐸 𝐹,𝐸 𝑃,and𝐸 𝑁 arethesemanticembeddingsoffunction inputfunction,UniXcoderencodestheASTofitintoasequence 𝑆,𝑃,and𝑁 respectively.𝜖isthemarginofthedistancebetween𝑆 whileretainingallstructuralinformationofthetree.Meanwhile, and𝑁.Bydefault,𝜖 issetto1,whichmeansthecosinedistance inourbinaryclassificationsetting,weset [prefix] as [Enc] and betweenafunctionanditsirrelevantfunctionshouldbe1. fine-tuneitonourstudieddatasetstolearnabetterrepresentation ofsourcecodes’semanticinformation. 3.2 VulnerabilityExplanation 3.1.2 SemanticDifferenceLearning. Ourgoalistodiscriminate Vulnerabilityexplanationaimstoprovidedeveloper-orientednat- thesemanticdifferenceamonglexicalsimilarfunctions,whichis urallanguagedescriptionsforproblematicsourcecode,whichin- consistentwiththetargetofcontrastivelearning.Thatis,minimize volvestwoaspects:buildingacode-relatedcrowdsourcedknowl- thedistancebetweensimilarobjects(i.e.,thefunctioninourstudy) edgedatabaseandextractingkeyaspectsforunderstandingvulner- whilemaximizingthedistancebetweendissimilarobjects.Hoffer ablefunctions.DistinguishingLook-AlikeInnocentandVulnerableCode... ESEC/FSE’23,December3–9,2023,SanFrancisco,CA,USA Functionf [ ] Encoder Contrastive Loss Batch Encoder Encoder Projector Projector Projector quality-firstsortingstrategyasfollowstoprioritizethemostuseful FuncF response/explanation. 𝒆𝜽 𝒈𝜽 𝑬𝑭 𝑺𝒊𝒎(𝑬𝑭,𝑬𝑷) 𝑅𝑎𝑛𝑘𝑖𝑛𝑔𝑆𝑐𝑜𝑟𝑒=𝐹𝑢𝑛𝑐_𝑆𝑖𝑚×( 𝑠𝑐𝑜𝑟𝑒𝑖 ×𝐴𝑠𝑝𝑠.) eqP uo is vi ati lv ee nt (cid:205)𝑁 𝑗=1𝑠𝑐𝑜𝑟𝑒𝑗 (2) FuncP 𝐴𝑠𝑝𝑠.=0.5×𝐼(𝐶𝑎𝑢.)+0.3×𝐼(𝐼𝑚𝑝.)+0.1×𝐼(𝑆𝑜𝑙.)+0.1×𝐼(𝐴𝑐𝑝𝑡.) 𝒄𝒐𝒔 where𝐹𝑢𝑛𝑐_𝑆𝑖𝑚representsthesimilaritybetweenthecodein …… 𝒆𝜽 𝒈𝜽 𝑬𝑷 agivenpostandthevulnerablefunction,𝑠𝑐𝑜𝑟𝑒 𝑖 meansthescoreof iN rre eg lea vti av ne t 𝑺𝒊𝒎(𝑬𝑭,𝑬𝑵) ananswer𝑖inapost,whichisvotedbyusers.Ahighscoreusually FuncN reflectsthehighqualityoftheanswer.𝑁 representsthenumberof answersinthegivenpostand𝐼(·)isanindicatorfunction.Itequals 𝒆𝜽 𝒈𝜽 𝑬𝑵 1iftheconditionissatisfiedelseitequals0.Forexample,𝐼(𝐶𝑎𝑢.) Figure4:ArchitectureforcontrastivelytrainingUniXcoder equals1whentheanswercontainstherootcausedescriptionto basedsemanticembeddingmodel explainaproblem.Inaddition,itispossiblethattherootcause (𝐶𝑎𝑢.),theimpact(𝐼𝑚𝑝.),andthepotentialsolution(𝑆𝑜𝑙.)provide differentinformationfordeveloperstounderstandtheproblems 3.2.1 CrowdsourcedKnowledgeDatabase. Thisphaseaimsatman- incodes.Therefore,weassigndifferentweightstoindicatetheir agingdiverseandusefulinformationfromdeveloperforums(i.e., priority.Finally,ifananswerismarkedasAccept(𝐴𝑐𝑝𝑡.),itmeans StackOverflow)sincethedeveloperforumsprovidealotofinfor- theanswerhashighqualityforsolvingtheproblem,andwetakeit mationintheformofquestionandanswer(Q&A)about(usually intoconsiderationandassigntheweightto0.1. problematic)codes.Meanwhile,userscanalsovoteontheanswers Thesecondstepistoextractthekeyaspectsforunderstanding
todistinguishthevalueofthequestionsandthecorresponding theproblem.Asintroducedinthecrowdsourcedknowledgedata- answers. base,thesuggestedanswermaycontainadetaileddescriptionthat Inourknowledgedatabase,wefocusontwoobjects:question- explainskeyaspects(e.g.,rootcause,impact,solution,etc.)ofthe s/posts about a technical problem and answers for solving this probleminsourcecodes.Inourexplanationmodel,wefocuson problem.Foraquestion/post,itusuallycontainsatitleforconcisely thefollowingthreeaspects:rootcause,impact,andsolution,which describingaproblem,thedetailsofthequestion,thesourcecodes areusuallylongclausesorsentences. involvedaswellasanoptionaltag.Forananswer,ithasalabelto Toextracttherootcause,impact,andsolution,weleveragethe indicatewhetheritisasuggestedone.Meanwhile,theanswermay BERT-basedQuestionAnsweringmodel[14,39],whichisbasedon giveadetaileddescriptionaboutwhyitarisestheproblem,wherethe apre-trainedBERTmodelforretrievingquestionsandanswersin rootcauseexists,andhowtosolveit,especiallyforthesuggestedone. agivencontentscope.Theinputofthemodelincludesaquestion Thedescriptionsareusuallypresentedintheformofnaturallan- andthescopeforansweringthequestion.Themodeloutputsthe guage,whilethecodepresentsthepotentialcorrectnesssolutions. startandendwordindexastheanswerclause.Inourapplication Thesolutiondoesnotalwaysworksuccessfullyforeachuserwho ofBERT-QA,weadoptthe𝑐𝑜𝑛𝑡𝑒𝑛𝑡 ofasuggestedanswerasthe isfacingasimilarproblembecauseofenvironmentaldifferences. scopeofquestionanswering,andweinputthreewhat-isquestions However,anexplanationofproblematiccodeswillinspireother (i.e.,“whatisrootcause”,“whatisimpact”and“whatisthesolution”) userswhoencountersimilarproblemstounderstandtherootcause. into the model to find corresponding answers. Benefiting from Additionally,weconnectpostswiththesametagsforretrieving thelanguagemodelingcapabilityofBERT,BERT-QAcanhandle answersmoreefficientlyinthenextphase(i.e.,ResultsExplainer), complexclausesoftherootcause,impact,andsolution,andselect asthisprocesscanfuserelatedpostswithrelevantproblems. themostappropriateinformationfromthelongresponsetexts. WetraintheBERT-QAmodelwith1,678question-answerpairs 3.2.2 ResultExplainer. Thecrowdsourcedcodeknowledgedata- (920 of reasons, 391 of impacts, and 492 of solutions), which is basehelpstofuseusefulinformationwhenaddressingsimilarprob- constructedmanuallyfrom55,627posts(121,635answers)inStack lems,whiletheresultexplaineraimsatbothretrievingrelevant Overflow.Webuildbothpositiveandnegativequestionsforwhich questions/postsinvolvingsimilarsourcecodesandextractingkey theanswerscanorcannotbefoundinthegivenposts.Thenegative aspectsoftheproblemsfromthesuggestedanswers. questionshelpthemodeltolearnwhenitfailstofindanyanswerin Thefirststepistofigureoutthemost(especiallysemantically) thescope.Thischaracteristicisextremelyimportantforextracting relevantsourcecodesexplicitly.Inthispaper,forretrievingthe therootcause,impact,andsolutionsincenotallpostsexactlyand mostsemanticallysimilarproblematicfunctions,weadoptUniX- completely describe all three aspects. Otherwise, the BERT-QA codertoobtainsemanticembeddingoffunctionssincethemodel modelwillhavenoabilitytohandlenegativequestionsandextract hasbeenwellpre-trainedwithcontrastivelearningtechnology. someirrelevantcontentastheanswerforaquestion. Additionally,foragivenretrievedpost,thereusuallyexistsmany responsesfromdifferentuserswithvaryingexperiences.Allthe 4 EXPERIMENTALDESIGN diverseresponsescanbeusefulsincedifferentdevelopersmaygive theirresponsesindifferentdevelopmentenvironments(i.e.,issues Inthissection,wefirstpresentfeaturesofthestudieddatasets,and thatoccurredinWindowsOSorLinuxOS).Therefore,apartfrom thenintroducethebaselineapproaches.Followingthat,wedescribe retrievingsimilarproblematicfunctions,wealsodesignaneffective theperformancemetricsaswellastheexperimentalsettings.ESEC/FSE’23,December3–9,2023,SanFrancisco,CA,USA ChaoNi,XinYin,KaiwenYang,DehaiZhao,ZhenchangXing,andXinXia 4.1 Datasets ReVealproposedbyChakrabortyetal.[8]containstwomain VulnerabilityDataset.Weusethebenchmarkdatasetprovided phases:featureextractionandtraining.Intheformerphase,ReVeal byFanetal.[18]duetothefollowingreasons.Thefirstoneisto translatescodeintoagraphembedding,andinthelatterphase, establishafaircomparisonwithexistingapproaches(e.g.,IVDetect, ReVealtrainsarepresentationlearnerontheextractedfeaturesto LineVul).Thesecondoneistoevaluatewhetherexistingapproaches obtainamodelthatcandistinguishthevulnerablefunctionsfrom have a good generalization performance on detecting the fixed non-vulnerableones. functionssinceFanetal.[18]’sdatasetistheonlyonevulnerability IVDetectproposedbyLietal.[27]involvestwocomponents: datasetthatprovidesthefixedversionofvulnerablefunctions.The coarse-grainedvulnerabilitydetectionandfine-grainedinterpre- lastoneistosatisfythedistinctcharacteristicsoftherealworldas tation.Asforvulnerabilitydetection,theyprocessthevulnerable
wellasthediversityinthedataset,whichissuggestedbyprevious codeandthesurroundingcontextualcodeinafunctiondistinc- works[8,23]. tively,whichcanhelptodiscriminatethevulnerablecodeandthe Fanetal.[18]builtthelarge-scaleC/C++vulnerabilitydataset benignones.Inparticular,IVDetectrepresentssourcecodeinthe namedBig-VulfromCommonVulnerabilitiesandExposures(CVE) formofaprogramdependencegraph(PDG)andtreatsthevulner- databaseandopen-sourceprojects.Big-Vultotallycontains3,754 abilitydetectionproblemasgraph-basedclassificationviagraph codevulnerabilitiescollectedfrom348open-sourceprojectsspan- convolutionnetworkwithfeatureattention.Asforinterpretation, ning91differentvulnerabilitytypesfrom2002to2019.Ithas188,636 IVDetectadoptsaGNNExplainertoprovidefine-grainedinterpre- C/C++functionswithavulnerableratioof5.7%(i.e.,10,900vul- tationsthatincludethesub-graphinPDGwithcrucialstatements nerabilityfunctions).Theauthorslinkedthecodechangeswith thatarerelevanttothedetectedvulnerability. CVEsaswellastheirdescriptiveinformationtoenableadeeper LineVulproposedbyFuetal.[19]isaTransformer-basedline- analysisofthevulnerabilities.Inourwork,somebaselinesneed levelvulnerabilitypredictionapproach.LineVulleveragesBERT toobtainthestructureinformation(e.g.,controlflowgraph(CFG), architecturewithself-attentionlayerswhichcancapturelong-term data flow graph (DFG)) of the studied functions. Therefore, we dependencieswithinalongsequence.Besides,benefitingfromthe adoptthesametoolkitwithJoern[4]totransformfunctions.The large-scale pre-trained model, LineVul can intrinsically capture functionsaredroppedoutdirectlyiftheycannotbetransformed morelexicalandlogicalsemanticsforthegivencodeinput.More- byJoernsuccessfully.Wealsoremovetheduplicatedfunctionsand over,LineVuladoptstheattentionmechanismofBERTarchitecture thestatisticsofthestudieddatasetareshowninTable1. tolocatethevulnerablelinesforfiner-graineddetection. Table1:Thestatisticofstudieddataset 4.3 EvaluationMeasures Datasets #Vul. #Non-Vul. #Total %Vul.:Non-Vul. ToevaluatetheeffectivenessofSVulDonvulnerabilitydetection, OriginalBig-Vul 10,900 177,736 188,636 0.061 weconsiderthefollowingfivemetrics:Accuracy,Precision,Recall, FilteredBig-Vul 5,260 96,308 101,568 0.055 F1-score,andPR-AUC. Training 4,208 4,208 8,416 1 Accuracyevaluatestheperformancethathowmanyfunctions Validating 526 9,631 10,157 0.055 canbecorrectlylabeled.Itiscalculatedas:𝑇𝑃+𝐹𝑇 𝑃𝑃 ++ 𝑇𝑇 𝑁𝑁 +𝐹𝑁. Testing 526 9,631 10,157 0.055 Precisionisthefractionoftruevulnerabilitiesamongthede- 𝑇𝑃 tectedones.Itisdefinedas:𝑇𝑃+𝐹𝑃. Recallmeasureshowmanyvulnerabilitiescanbecorrectlyde- CrowdsourcedDataset.Apartfromthewidelyusedvulnerabil- 𝑇𝑃 tected.Itisdefinedas:𝑇𝑃+𝐹𝑁. itydataset,wealsoneedtobuildacrowdsourceddatasetmanually F1-scoreisaharmonicmeanof𝑃𝑟𝑒𝑐𝑖𝑠𝑖𝑜𝑛and𝑅𝑒𝑐𝑎𝑙𝑙 andcan inordertoprovideexplanationsforthedetectedvulnerabilities.In becalculatedas: 2× 𝑃𝑃 +𝑅×𝑅 . thispaper,wecrawlpostsaswellastheiranswersfromStackOver- PR-AUCistheareaundertheprecision-recallcurveandisa flow,wherethepostsarelabeledwithCorC++andthereisatleast usefulmetricofsuccessfulpredictionwhentheclassdistributionis onecodesnippetintheircontent.Finally,weobtain55,627posts veryimbalanced[23].Theprecision-recallcurveshowsthetrade- with121,635answers,whicharefurtherusedtobuildaknowledge offbetweenprecisionandrecallfordifferentthresholds.Ahigh database. areaunderthecurveindicatesbothhighrecallandhighprecision, wherehighprecisioncorrespondstoalowfalsepositiverate,and 4.2 Baselines highrecallcorrespondstoalowfalsenegativerate. TocomprehensivelycomparetheperformanceofSVulDwithex- istingwork,inthispaper,weconsiderthefourSOTAapproaches: 4.4 ExperimentalSetting Devign [45], ReVeal [8], IVDetect [27], and LineVul [19]. We brieflyintroducethemasfollows. Weimplementourvulnerabilitydetectionandexplanationmodel DevignproposedbyZhouetal.[45]isageneralgraphneural SVulDinPythonwiththehelpofPyTorchframework.Besides, networkbasedmodelforgraph-levelclassificationthroughlearning weutilizeunixcoder-base-nine[22]fromHuggingface[3]asour onarichsetofcodesemanticrepresentationsincludingAST,CFG, basicmodel,whichisapre-trainedmodelonNL-PLpairsofCode- DFG,andcodesequences.Itusesanovel𝐶𝑜𝑛𝑣moduletoefficiently SearchNetdatasetandadditional1.5MNL-PLpairsofC,C++,and extractusefulfeaturesinthelearnedrichnoderepresentationsfor C# programming language. We fine-tune SVulD on the studied graph-levelclassification. datasetstoobtainasetofsuitableparametersforthevulnerabilityDistinguishingLook-AlikeInnocentandVulnerableCode... ESEC/FSE’23,December3–9,2023,SanFrancisco,CA,USA detectiontaskandfine-tuneBERT-QAmodelonthemanuallyla- sametoolkitwithJoerntotransformfunctions.Finally,thefiltered beledquestion-answerdatasets.Allthemodelsarefine-tunedon dataset(showninTable1)isusedforevaluation.Wefollowthe
fourNVIDIAGeForceRTX3090graphiccards.Duringthetraining samestrategytobuildthetrainingdata,validatingdata,andtesting phase,weuseAdamwithabatchsizeof32tooptimizetheparam- datafromtheoriginaldatasetwithpreviousworkdoes[19,34]. etersofSVulD.WealsoleverageGELU astheactivationfunction. Specifically,80%offunctionsaretreatedastrainingdata,10%of Adropoutof0.1isusedfordenselayersbeforecalculatingthe functionsaretreatedasvalidationdata,andtheleft10%offunctions finalprobability.Wesetthemaximumnumberofepochsinour aretreatedastestingdata.Wealsokeepthedistributionassameas experimentas20andadoptanearlystopmechanismtoobtaingood theoriginalonesintraining,validating,andtestingdata. parameters.Themodels(i.e.,SVulDandbaselines)withthebest Meanwhile,foraspecificfunction,SVulDneedstoselectappro- performanceonthevalidationsetareusedfortheevaluations. priatepositiveinstancesandnegativeinstances.Forthepositive instances,weadoptthedifferentembeddingvectorsofthesame 5 EXPERIMENTALRESULTS functionbyrandomlydroppingoutsomeweightsinthenetwork ToinvestigatethefeasibilityofSVulDonsoftwarevulnerability ofthesemanticencoder.Forthenegativeinstances,weconsiderall detectionanddetectionresultexplanation,ourexperimentsfocus theotherinstances(i.e.,functions)inthesamemini-batchwiththe onthefollowingfourresearchquestions: giveninstanceandusetheaveragesemanticvectorrepresentation. • RQ-1.Towhatextentcanthefunction-levelvulnerabilitydetection Weconsiderthreetypesofpairedinstancesselectionstrategies (i.e.,SimCL,SimDFEandR-Drop.cf.Section5.2),andinthisRQ,we performanceSVulDachieve? • RQ-2.Howdoesthepairedinstancebuildingstrategyimpactthe adopttheR-Dropstrategysinceithasoverallbestperformance. Finally, since our target is to build an effective vulnerability performanceofSVulD? • RQ-3.Howdoesthesizeofpairedinstanceimpacttheperformance detectionmodel,especiallyfordiscriminatinglexicallysimilarbut semanticallydistinctfunctions,wefurtherconductananalysison ofSVulD? • RQ-4.HowwelldoesSVulDperformonexplainingthedetection howSVulDperformsonthefixedversionofvulnerablefunctions inthetestingdataset. results? InRQ1,weaimtoinvestigatetheperformanceoftheSVulD Table2:VulnerabilitydetectionresultsofSVulDcompared onvulnerabilitydetectionbyconsideringitwithSOTAbaselines againstfourbaselines. (cf.Section5.1).InRQ2andRQ3,weexploretheimpactofdesign Methods F1-score Recall Precision PR-AUC optionsofcontrastivelearningontheperformanceofSVulD(cf. Section5.2,5.3).InRQ4,weexploretheSVulD’susefulnessfor Devign 0.200 0.660 0.118 0.115 helpingdevelopersunderstandvulnerablefunctions(cf.Section5.4). ReVeal 0.232 0.354 0.172 0.145 IVDetect 0.231 0.540 0.148 0.177 5.1 [RQ-1]:EffectivenessonVulnerability LineVul 0.272 0.620 0.174 0.233 Detection. SVulD 0.336 0.414 0.282 0.270 Objective.Benefitingfromthepowerfulrepresentationcapability Improv. 23.5%-68.0% – 62.1%-139.0% 15.9%-134.8% ofdeepneuralnetworks,manyDL-basedvulnerabilitydetection approacheshavebeenproposed[27,45].However,asvulnerable Results.TheevaluationresultsarereportedinTable2andthe functionsareusuallyfixedwithafewmodifications(52.6%vulnera- bestperformancesarehighlightedinbold.Accordingtotheresults, blefunctionscanbefixedwithin5(76.7%for10)linesofcodes),they wefindthatourapproachSVulDoutperformsallSOTAbaseline havesubtlelexicaldifferenceswiththenon-vulnerablefunctions. methods on almost all performance measures except Recall. In Existing SOTA deep learning approaches (i.e., Devign, ReVeal, particular,SVulDobtains0.336,0.282,and0.270intermsofF1-score, IVDetect,etc.)cannotperformwellonthefixedfunctions(non- Precision,andPR-AUC,whichimprovesbaselinesby23.5%-68.0%, vulnerable).Themainreasonfallsintothelimitationsofeffective 62.1%-139.0%,and15.9%-134.8%intermsofF1-score,Precision,and semanticembeddingamonglexicalsimilarfunctions.Inthispaper, PR-AUC,respectively. weproposeanovelapproachSVulD,whichisbuiltonacontrastive IntermsofRecall,Devignperformsthebest(0.660)andLineVul learningframeworkwithapre-trainedmodelasasemanticencoder performssimilarlywithDevign(0.620),whichmeansthatboththe assuggestedbypreviouswork[9].Theexperimentsareconducted pre-trainedmodelandtheGNN-basedmodelcanachievebetter toinvestigatewhetherSVulDoutperformsSOTAfunction-level performanceofRecall. vulnerabilitydetectionapproaches. ExperimentalDesign.WeconsiderthefourSOTAbaselines:De- The performance comparisons of SVulD and four SOTAs on vign [45], ReVeal [8], IVDetect [27], and LineVul [19]. These thefixedfunctionsarepresentedinTable3.AccordingtoTable3, approachescanbedividedintotwocategories:GNN-basedone(i.e., wefindthatallSOTAshavepoorperformanceonclassifyingthe Devign,ReVealandIVDetect)andPre-trained-basedone(i.e., fixedversions(i.e.,thecleanversion)inthetestingdataset(i.e.,
LineVul).Besides,inordertocomprehensivelycomparetheperfor- 526vulnerablefunctions),whileSVulDcanachievethebestper- manceamongbaselinesandSVulD,weconsiderfivewidelyused formance.Moreprecisely,SVulDcancorrectlyclassify319fixed performancemeasuresandconductexperimentsonthepopular versionsoffunctionsascleanones,whichoutperformsDevign(i.e., dataset.SinceGNN-basedapproachesusuallyneedtoobtainthe 194),ReVeal(i.e.,297),IVDetect(i.e.,209),andLineVul(i.e.,202) structureinformationofthefunction(e.g.,CFG,DFG),weadoptthe by64.4%,7.4%,52.6%,and57.9%,respectively.TheresultsindicateESEC/FSE’23,December3–9,2023,SanFrancisco,CA,USA ChaoNi,XinYin,KaiwenYang,DehaiZhao,ZhenchangXing,andXinXia Positive Instance Negative Instance P 𝑩𝒖𝒈𝒈𝒚𝑭𝒖𝒏𝒄. 𝑭𝒖𝒏𝒄 F 𝑭𝒖𝒏𝒄 F 𝟏 P 𝟏 P …… …… F 𝑩𝒖𝒈𝒈𝒚𝑭𝒖𝒏𝒄. E 𝑭𝒖𝒏𝒄 𝒊 E E N 𝑭𝒖𝒏𝒄 𝒊 E N 𝑭𝒖𝒏𝒄 𝑭𝒖𝒏𝒄 N 𝑪𝒍𝒆𝒂𝒏𝑭𝒖𝒏𝒄. 𝒋 N 𝒋 N batch batch (a) SimCL (b) SimDFE (c) R-Drop Figure5:Threedifferentcontrastivepairedinstancesconstruction Table3:TheeffectivenessofSVulDcomparedagainstfour isinspiredby[20].Thatis,eachfunctionwillhavetwoembedded baselinesonfixedfunctionsintestingdataset vectors,notedas𝑓 11,𝑓 12,𝑓 21,𝑓 22,···,𝑓 𝑛1,𝑓 𝑛2.Take𝑓 1asanexample, Methods #Correct Accuracy #Improv. %Improv. 𝑓 11and𝑓 12areinterchangeablytreatedaspositiveinstancesand 𝑓 𝑖𝑗 aretreatedasnegativeinstances,where𝑖 ∈ [2,𝑛]and𝑗 ∈ [1,2]. Devign 194 36.9% 125 64.4% ReVeal 297 56.5% 22 7.4% Weusetheaveragedifferencebetween𝑓 1andallnegativeinstances astheirdissimilarity. IVDetect 209 39.7% 110 52.6% •R-Drop(randomdropout)meanstoinputonefunction(noted LineVul 202 38.4% 117 57.9% as𝑓 1,𝑓 2,···,𝑓 𝑛,𝑛isthesizeofbatch)inabatchtwiceandtherest SVulD 319 60.6% 22-125 7.4%-64.4% functioninthesamebatchonceintothesameencoder.Forthegiven functionembeddedwithanencodertwice,weadopttherandom dropoutoperationtothenetworktoobtaintheequivalentpositive thatSVulDhasabetterrepresentationoflearningabilitythanthe embedding.Take𝑓 1asanexample,𝑓 11and𝑓 12areinterchangeably fourbaselines. treatedaspositiveinstancesand𝑓 𝑖(𝑖 ∈ [2,𝑛])aretreatedasnega- Answer to RQ-1: SVulD outperforms the SOTA baselines at tiveinstances.Weusetheaveragedifferencebetween𝑓 1withall negativeinstancesastheirdissimilarity. thefunction-levelsoftwarevulnerabilitydetection.Particularly,it TheexperimentaldatasetissetthesameastheexperimentofRQ- achievesoverwhelmingresultsatbothF1-scoreandPR-AUC,which 1(i.e.,80%fortraining,10%forvalidating,and10%fortesting).We indicatesthatSVulDequippedwithcontrastivelearningaswellas alsoconsiderthefiveperformancemeasures(i.e.,Precision,Recall, pre-trainedmodelhasastrongerabilitytolearnthesemanticsof F1-score,PR-AUC,andAccuracy)forcomprehensivelystudyingthe functions,especiallyforthosefunctionswithlexicalsimilaritybut impactofdifferentpairedinstancesbuildingstrategies.Additionally, havedistinctsemantics. inthisstudy,wesetthebatchsize𝑛as32. 5.2 [RQ-2]:ImpactsofContrastivePaired Table4:Theperformancedifferenceamongthreedifferent InstancesConstruction. pairedinstancesconstructionstrategies Objective. The contrastive learning framework needs to build TestingData Fixedfunction tripletpairedinstances,whichareusedtomeasurehowclosethe Strategy F1-score Recall Precision PR-AUC #Num Accuracy twosimilarinstancesareandhowfarthetwodissimilarinstances SVulD 0.303 0.536 0.211 0.245 243 0.462 are.Therefore,itisimportanttoconductastudyonhowthecon- SVulD𝑆𝑖𝑚𝐶𝐿 0.313 0.504 0.227 0.257 269 0.511 structedpositiveinstancesandnegativeinstancesofagivenfunc- SVulD𝑆𝑖𝑚𝐷𝐹𝐸 0.324 0.481 0.244 0.265 268 0.510 SVulD𝑅−𝐷𝑟𝑜𝑝 0.336 0.414 0.282 0.270 319 0.606 tionaffectthelearningofsemanticrepresentation. ExperimentalDesign.Weconsiderthreetypes(i.e.,SimCL,SimDFE, 3.3% 7.6% 4.9% 10.3% Improv. to — to to to andR-Drop)ofpairedinstances(i.e.,positiveinstancesandnegative 10.9% 33.6% 10.2% 31.3% instances)buildingstrategiestotrainourproposedapproachSVulD. ThedifferencesamongthesestrategiesareillustratedinFig.5and weintroducethemindetailasfollows. Results.ThecomparisonresultsarereportedinTable4andthe •SimCL(simplecontrastivelearning)meansbuildingthenega- bestperformancesarehighlightedinboldforeachperformance tiveinstanceofavulnerablefunctionwithitscorrespondingfixed measure. According to the results, we can obtain the following version.Foritspositiveequivalentfunction,weinputtheoriginal observations:(1)Allpairedinstanceconstructionstrategieshave functiontwiceintothesameencoderwithdifferentweights(i.e., the advantage of learning function semantic embedding in the dropoutusedasnoise)insidethemodelandobtaintwoembedded scenarioofvulnerabilitydetection.Particularly,SimCL,SimDFE, vectors.Thetwovectorsareinterchangeablytreatedaspositive andR-Dropimprovethebaseline(UniXcoderwithoutcontrastive instances. learning)by3.3%-10.9%,7.6%-33.6%,4.9%-10.2%,and10.3%-31.3% • SimDFE (simple duplicate function embedding) means in- intermsofF1-score,Precision,PR-AUC,andAccuracy.(2)The
puttingallfunctions(notedas𝑓 1,𝑓 2,···,𝑓 𝑛,𝑛isthesizeofbatch) SimDFE performs better than the SimCL and the R-Drop is the inabatchtwiceintothesameencoderwithdifferentweights,which dominatedoneamongthethreestrategies.(3)TheSimCLperformsDistinguishingLook-AlikeInnocentandVulnerableCode... ESEC/FSE’23,December3–9,2023,SanFrancisco,CA,USA Results.TheevaluationresultsofSVulDwithvaryingbatchsize areillustratedinFig.6.Accordingtotheresults,wehavethefollow- ingresearchfindings:(1)Differentnumberofnegativeinstancehas varyingimpactonSVulD’sperformance.(2)Almostallthemetrics ofSVulD(exceptAccuracy)goupwiththeincreasingofnegative instanceswhenbatchsizeisnolargerthan32.Whenbatchsize equals64,alltheperformancesdroptodifferentdegrees.(3)Larger batchsizemaynotleadtobetterperformanceandassigningabatch sizeof32isagoodchoice. AnswertoRQ-3:Thenumberofnegativeinstanceshasanimpact onSVulD’sperformanceandthelargernumbermaynotalways guaranteebetterperformance.Inoursetting,amediansize(i.e., 32)ismoreappropriate. 5.4 [RQ-4]:UsefulnessforDevelopers. Figure6:ThevaryingperformanceofSVulDwithdifferent Objective.Thoughmanynovelapproacheshavebeenproposed batchsize andindeedachievedremarkableperformance,existingmethods cannotprovideadeveloper-oriented,naturallanguage-described explanation.Forexample,whatisthepossiblerootcauseofsuch worsethantheothertwostrategiesandthemainreasonmaycome vulnerability?Suchtypesofexplanationsmay(atleastintuitively) fromthesmallsizeofnegativeinstances(i.e.,onlyonenegative helpdevelopersunderstandtheidentifiedvulnerabilitybetter.How- instance),whichlimitstheinformationforSVulDtodiscriminate ever,consideringtheconcealmentofsoftwarevulnerabilities,we thedifferencebetweenpositiveinstancesandnegativeinstances. cannotobservetwoidenticalvulnerabilities.Itispossiblethatsimi- (4)Thecontrastivelearningstrategy,tosomedegree,candecrease lar/homogeneousvulnerabilitieshavesimilarrootcausesorlead theperformanceofRecall.However,ithasanimprovementontwo tosimilarimpacts.Meanwhile,manypubliclyavailabledeveloper comprehensiveperformancemeasures(i.e.,F1-scoreandPR-AUC), forums(i.e.,StackOverflow)sharesimilarproblemsandtheirre- especiallyfordistinguishingtwolexicallysimilarfunctionswith sponsesmayprovideunderstandablenaturallanguageexplanations distinctsemantics(i.e.,animprovementonAccuracy). abouttheissues.Therefore,wewanttofurtherutilizethisuseful anddiverseinformationtoprovideparticipantswithdetailedex- Answer to RQ-2: All paired instance construction strategies planationsabouttheidentifiedproblematiccodes. presenttheirownadvantagesinlearningfunctionsemanticem- ExperimentalDesign.WefirstcrawlpostslabeledwithC/C++ beddingandtheR-Dropstrategyperformsthebest. fromStackOverflowandbuildadatabase(cf.Section4.1)tofuse allcrowdsourcedknowledgeforretrievingimportantexplainable information.Consideringthatourworkfocusesoncode-related problems,wefilterthosepostswithnocodesnippetintheirpost 5.3 [RQ-3]:ImpactsofPairedInstancesSize. contentsincethecodesnippetisthecriticalconnectiveelement Objective.InRQ-2,wefindthatthenumberofnegativeinstances whenretrievingsimilarproblematiccodes.Inaddition,forretriev- hasanimpactonSVulD’sperformanceoflearningsemanticem- ingthemostsemanticallysimilarproblematicfunctions,weadopt bedding.Therefore,wewanttoconductadeeperexperimenton SVulDtoobtainsemanticembeddingofbothvulnerablefunction howthebatchsize(i.e.,thenumberofnegativeinstances)impacts andcodesnippetinpostsinceourmodelhasbeenwellpre-trained theperformanceofSVulDondiscriminatingdissimilarinstances withcontrastivelearningtechnology.Then,weadoptthedesigned fromsimilarones. quality-firstsortingstrategy(cf.Section3.2)toprioritizethere- ExperimentalDesign.AccordingtoRQ-2,wefindthattheR- trievedanswers.Finally,thewellpre-trainedBERT-QAmodel(cf. Dropstrategyhasanoverallbetterperformancethantheothers. Section3.2)isadoptedtoextractthreeoptionalimportantdescrip- Meanwhile,consideringthefactthatthelargerthebatchsizeis, tions(i.e.,rootcause,impact,andsolution)insidetheanswer. themorememorySVulDconsumes,were-runSVulDwithR-Drop Finally,werandomlyselect20vulnerablefunctionsintesting strategyonthefollowingvaryingsettingsofbatchsize:1,2,4,8, datasetsandinvite10developersfromaprominentITcompany 16,32,and64.Becauseofthelimitationofgraphmemory(i.e.,four whohave5to8yearsofexperienceinsoftwaresecurityasourpar- NVIDIARTX3090)andthesizeoffunctions,wecannotperform ticipants.Eachdeveloperisaskedtofinishanexperimenttaskthat largerbatchsizes(i.e.,128or256).Besides,theexperimentaldataset includestwovulnerablefunctionsaswellastheircorresponding issetassameasthatinpreviousRQs.Weevaluatetheperformance explanationrecommendedbySVulD.Weevaluatetheusefulness ofSVulDontestingdatawithtwocomprehensiveperformance ofourapproachbyanalyzingtheanswerstothefollowingques-
measures(i.e.,F1-scoreandPR-AUC),andweadoptAccuracyto tionsgivenbyparticipants.Moreprecisely,SVulDpresentseach evaluatetheperformanceonthefixedversionofvulnerablefunc- vulnerablefunctionwithfiveretrievedanswersfromcrowdsourced tions. knowledge.ESEC/FSE’23,December3–9,2023,SanFrancisco,CA,USA ChaoNi,XinYin,KaiwenYang,DehaiZhao,ZhenchangXing,andXinXia (a)Devign (b)ReVeal (c)IVDetect (d)LineVul (e)UniXcoder (f)SVulD Figure7:Visualizationoftheseparationbetweenvulnerable(denotedby●)andnon-vulnerable(denotedby▲). 6 DISCUSSION • Q1:Istheexplanationrelatedtothevulnerablefunction? • Q2:Istheexplanationcomprehensive(i.e.,therootcause,theim- Thissectiondiscussesopenquestionsregardingtheperformance pacts,andthesuggestion.score:1-5’,1(low)-3(middle)-5(high))? andthreadstothevalidityofSVulD. Whichpartismostimportant? • Q3:Istheexplanationusefultounderstandthevulnerability? • Q4:Inwhichresultdoyoufindthemostdesiredanswer?(score: 6.1 WhySVulDoutperformsExistingBaselines? 0-5’,0meansnodesiredanswer.) DL-basedvulnerabilitydetectionapproacheshaveastrongability • Q5:Pleasesorttheexplanationsaccordingtotheirusefulness. tolearnafeaturerepresentationtodistinguishvulnerablefunctions andnon-vulnerableones.Therefore,theefficacyofthemodels’vul- nerabilitydetectiondependslargelyonhowseparablethefeature ForQ1andQ2,weaimtoverifytherelatednessandcomprehen- representationofthetwotypesoffunctions(i.e.,vulnerableand sivenessofSVulD’srecommendation.ForQ3andQ4,weaimto non-vulnerable)are.Thegreatertheseparabilityofthetwofunc- evaluatetheusefulnessofSVulD,andQ5isdesignedtoevaluate tions,theeasieritisforamodeltodistinguishbetweenthem. thedifferencebetweentherecommendationsanddevelopers’ex- WeadoptPrincipalComponentsAnalysis(PCA)[6]toinspect pectations. theseparabilityofthestudiedmodels.PCAisapopulardimension- Results. In Q1, except for 5 negative responses (i.e., providing alityreductiontechniqueandissuitedforprojectingtheoriginal unrelatedexplanations),15responsesarepositivetoindicatethere- featureembeddingintotwoprincipaldimensionalembeddings.Be- latednessofrecommendedposts.InQ2,themajority(i.e.,19/20with sides,werandomlysamplethesamenumberofnon-vulnerable largerthan3’)agreesthatSVulD’srecommendedpostsprovidethe functionswithvulnerablefunctionsinthetestingdatasetformore reasons(rootcause)forproblematiccodes.Besides,allresponses clearvisualization. (i.e., ≥ 3) are positive with the suggestion. However, about half Fig.7illustratestheseparabilityofthestudiedapproaches.From oftheparticipantsgivelessthan3scorestotheimpactsofprob- thevisualizationresults(Fig.7(a)–(d)),wecanseethatthemajority lematiccode,whichisconsistentwithourmanuallylabeleddata ofthefunctionsaremixedandtheboundaryofeachfunctionis (theimpactsofproblematiccodehavetheleastnumber).Mean- notclear,whichindicatesthedifficultyofbaselinesindrawingthe while,everyonebelievesthatgivingtheexplanationofrootcause decisionboundary.Incontrast,UniXcoder(showninFig.7(e))has ismostimportantforexplainingaproblematiccode.InQ3,13par- betterseparabilitythanbaselines,whichindicatesthelarge-scale ticipantsagreethattheexplanationextractedbySVulDcanhelp pre-trainedlanguagemodel(speciallytrainedonC/C++codes)hasa themintuitivelyunderstandthevulnerablecodeandtheremain- strongerabilitytounderstandthesemanticofcodes.Lastly,Fig.7(f) ing7responseshavenegativefeedback,whichalsoconfirmsthe showstheseparabilityofourSVulD.WecanobservethatSVulDhas concealmentofvulnerability.InQ4,wefindthat13responsesrank thebestperformanceindistinguishingvulnerablefunctionsfrom attop-3(5fortop-1,5fortop-2,and3fortop-3),and3responses non-vulnerableones.Equippedwithcontrastivelearning,SVulD arescoredwith0,whichmeansthatnoneoftherecommendedex- canlearnbettersemanticembeddingoffunctions. planationsarerelatedtothevulnerablefunction.Finally,inQ5,we useMeanAveragePrecision(MAP)[27]toqualifythegapbetween ourrecommendationanddevelopers’expectations.Weget0.565of 6.2 ThreatstoValidity MAP,whichmeansSVulD,tosomedegree,cangiveanacceptable ThreatstoInternalValiditymainlycorrespondtothepotential recommendationlist. mistakesintheimplementationofourapproachandotherbase- WeanalyzethenegativeresponsesaboutSVulDandfindthat lines.Tominimizesuchathreat,wefirstimplementourmodelby thebiggestproblemfallsintothecompletenessofourdataset,as pairprogramminganddirectlyutilizethepre-trainedmodelsfor SVulDcannotfindthemostsemanticsimilarproblematiccodes buildingvulnerabilitydetectors.Wealsousetheoriginalsource withvulnerablefunctionsinthebuiltdataset(i.e.,similarity<0.5). codeofbaselinesfromtheGitHubrepositoriessharedbycorre- spondingauthorsandusethesamehyperparametersintheoriginal papers.Theauthorsalsocarefullyreviewtheexperimentalscripts toensuretheircorrectness.
AnswertoRQ-4:Ouruserstudyreveals,tosomeextent,that ThreatstoExternalValiditymainlycorrespondtothestudied SVulDpresentsthepotentialfeasibilityofassistingdevelopersto dataset.Eventhoughwehaveevaluatedmodelsonthosewidely intuitivelyunderstandthedetectedvulnerability. usedvulnerabilitydatasetsinliteraturetoensureafaircomparisonDistinguishingLook-AlikeInnocentandVulnerableCode... ESEC/FSE’23,December3–9,2023,SanFrancisco,CA,USA withbaselines,thediversityofprojectsisalsolimitedinthefol- prediction[33,37].Thisraisestheimportanceofresearchforinter- lowingaspects.Firstly,allthestudiedprojects(i.e.,functions)are pretableAI-basedmodels. developedinC/C++programminglanguage.Therefore,projects However,existingstudiesarelimitedtoprovidingpartialinfor- developedinotherpopularprogramminglanguages(e.g.,Javaand mationfortheexplanationgeneration.Zouetal.[47]introduced Python)havenotbeenconsidered.Secondly,allthestudieddatasets ahigh-fidelitytoken-levelexplanationframework,whichaimsat arecollectedfromopen-sourceprojects,andtheperformanceof identifyingasmallnumberoftokensthatmakesignificantcontri- SVulDoncommercialprojectsisunknown.Thus,morediverse butionstoadetector’sprediction.Lietal.[28]proposedVulDeeLo- datasetsshouldbecollectedandexploredinfuturework. catortosimultaneouslyachievehighdetectioncapabilityandhigh ThreatstoConstructValiditymainlycorrespondtotheperfor- locatingprecisionanditexplainsdetectionresultsatintermediate mancemetricsusedinourevaluations.Tominimizesuchathreat, code.Dingetal.[15]proposedastatement-levelmodelvialocal- weadoptafewperformancemetricswidelyusedinexistingwork. izingthespecificvulnerablestatementswiththeassumptionof Inparticular,wetotallyconsiderfiveperformancemetricsincluding receivingvulnerablesourcecodesatthefunctionlevel.Lietal.[27] Accuracy,Precision,Recall,F1-score,andPR-AUC. adoptedexplainableGNNtoproposeIVDetectandprovidedfine- grainedinterpretations.Fuetal.[19]proposedatransformer-based 7 RELATEDWORK line-levelmodelnamedLineVulandleveragedtheattentionmech- 7.1 AI-basedSoftwareVulnerabilityDetection anismofBERTarchitecturetoexplainthevulnerablecodelines. Recently,Sunetal.[40]conductedthefirstresearchworkonthe Softwarevulnerabilitydetectionhasattractedmuchattentionfrom applicationofExplainableAIinsilentdependencyalertprediction, researchersandmanyDL-basedapproacheshavebeenproposed whichopensthedoortotherelateddomains. toautomaticallylearnthevulnerabilitypatternsfromhistorical DifferentfromexistingworksthatfocusonexplainingwhyAI- data[8,16,28,30,31,44,45],sincethepowerfullearningabilityof modelsgiveoutthepredictedresults,ourpaperaimsatmakingan deepneuralnetworkshasbeenverifiedinmanysoftwareengineer- explanationforthedetectedresultsbyprovidingadevelop-oriented ingscenarios[32,33,46](e.g.,defectprediction,defectrepair). naturallanguagedescribedexplanationinordertoheuristicallyhelp Dametal.[13]proposedavulnerabilitydetectorwithLSTM- developersunderstandtherootcauseofthedetectedvulnerabilities. basedarchitecture.Russelletal.[38]proposedanotherRNN-based architecturetoautomaticallyextractfeaturesfromsourcecodefor 8 CONCLUSIONANDFUTUREWORK vulnerabilitydetection.However,theseapproachesassumesource ThispaperproposesanovelapproachSVulD,whichisafunction- codeisasequenceoftokens,whichignoresthegraphstructure levelsubtlesemanticembeddingforvulnerabilitydetectionalong ofthesourcecode.Therefore,Lietal.[29,30]sequentiallypro- withheuristicexplanations,technicallybasedonpre-trainedse- posedtwoslice-basedvulnerabilitydetectionapproaches,VulDeeP- manticembeddingaswellascontrastivelearning.SVulDfirstly ecker[30]andSySeVR[29],tolearnthesyntaxandsemanticin- adoptscontrastivelearningtotraintheUniXcodersemanticem- formation of vulnerable code. Following that, many graph neu- beddingmodelforlearningdistinguishingsemanticrepresentation ralnetwork(GNN)basedmodels[44,45]areproposed.Chenget offunctionsregardlessoftheirlexicallysimilarinformation.SVulD al. [11] proposed DeepWukong by embedding both textual and secondlybuildsaknowledge-basedcrowdsourcedatasetbycrawl- structuralinformationofcodeintoacomprehensivecoderepre- ing problematic codes in Stack Overflow to provide developers sentation.Wangetal.[42]proposedFUNDEDbycombiningnine withheuristicexplanationsofthedetectedproblematiccodes.The mainstreamgraphs.Caoetal.[7]proposedMVDtodetectfine- experimentalresultsshowtheeffectivenessofSVulDbycomparing grainedmemory-relatedvulnerability. itwithfourSOTAdeeplearning-basedapproaches. Apartfromthecoarse-grainedmodels(e.g.,functionlevel),re- Ourfutureworkwillinvestigatethegeneralizationofcontrastive searchersalsoproposedmanyfine-grainedmodels.Lietal.[28] learning to existing deep learning approaches for vulnerability proposedVulDeeLocatorbyadoptingaprogramslicingtechnique detection. tonarrowdownthescopeofvulnerability-pronelinesofcode.Fu etal.[19]proposedLineVulbyleveragingtheattentionmechanism 9 DATAAVAILABILITY
insidetheBERTarchitectureforline-levelvulnerabilitydetection. Hinetal.[23]proposedLineVDtoformulatestatement-levelvul- Thereplicationofthispaperispubliclyavailable[5]. nerabilitydetectionasanodeclassificationtask. ACKNOWLEDGEMENTS Differentfrompreviouswork,ourpaperfocusesontheeffective semanticembeddingoffunctions,especiallythosethatarelexically ThisresearchissupportedbytheNationalNaturalScienceFounda- similar. tionofChina(No.62202419),theFundamentalResearchFundsfor theCentralUniversities(No.226-2022-00064),theNingboNatural 7.2 InterpretationforAI-basedSoftware ScienceFoundation(No.2022J184),andtheStateStreetZhejiang VulnerabilityDetection UniversityTechnologyCenter. Developingexplainablemodelsisoneofthewaysforvulnerability REFERENCES detection,whichcouldprovideafine-grainedvulnerabilitypredic- tionoutcome.Specifically,manyworkshaveattemptedtodetect [1] 2023.Checkmarx. https://www.checkmarx.com/ [2] 2023.FlawFinder. https://dwheeler.com/flawfinder/ line-levelinformationbyleveragingexplainableAIforsoftware [3] 2023.HuggingFace. https://huggingface.co engineeringtasks,suchasdetectingsourcecodelinesfordefect [4] 2023.Joern. https://github.com/joernio/joernESEC/FSE’23,December3–9,2023,SanFrancisco,CA,USA ChaoNi,XinYin,KaiwenYang,DehaiZhao,ZhenchangXing,andXinXia [5] 2023.Replication. https://github.com/jacknichao/SVulD IEEETransactionsonDependableandSecureComputing(2021). [6] HervéAbdiandLynneJWilliams.2010.Principalcomponentanalysis.Wiley [29] ZhenLi,DeqingZou,ShouhuaiXu,HaiJin,YaweiZhu,andZhaoxuanChen.2021. interdisciplinaryreviews:computationalstatistics2,4(2010),433–459. Sysevr:Aframeworkforusingdeeplearningtodetectsoftwarevulnerabilities. [7] SicongCao,XiaobingSun,LiliBo,RongxinWu,BinLi,andChuanqiTao.2022. IEEETransactionsonDependableandSecureComputing(2021). MVD:Memory-RelatedVulnerabilityDetectionBasedonFlow-SensitiveGraph [30] ZhenLi,DeqingZou,ShouhuaiXu,XinyuOu,HaiJin,SujuanWang,Zhijun NeuralNetworks.arXivpreprintarXiv:2203.02660(2022). Deng,andYuyiZhong.2018.Vuldeepecker:Adeeplearning-basedsystemfor [8] SaikatChakraborty,RahulKrishna,YangruiboDing,andBaishakhiRay.2021. vulnerabilitydetection.InProceedingsofthe25thAnnualNetworkandDistributed Deeplearningbasedvulnerabilitydetection:Arewethereyet.IEEETransactions SystemSecuritySymposium. onSoftwareEngineering(2021). [31] GuanjunLin,JunZhang,WeiLuo,LeiPan,andYangXiang.2017. POSTER: [9] QibinChen,JeremyLacomis,EdwardJSchwartz,GrahamNeubig,Bogdan Vulnerabilitydiscoverywithfunctionrepresentationlearningfromunlabeled Vasilescu,andClaireLeGoues.2022.Varclr:Variablesemanticrepresentation projects.InProceedingsofthe2017ACMSIGSACConferenceonComputerand pre-trainingviacontrastivelearning.InProceedingsofthe44thInternational CommunicationsSecurity.2539–2541. ConferenceonSoftwareEngineering.2327–2339. [32] MartinMonperrus.2018. Automaticsoftwarerepair:abibliography. ACM [10] TingChen,SimonKornblith,MohammadNorouzi,andGeoffreyHinton.2020.A ComputingSurveys(CSUR)51,1(2018),1–24. simpleframeworkforcontrastivelearningofvisualrepresentations.InInterna- [33] ChaoNi,WeiWang,KaiwenYang,XinXia,KuiLiu,andDavidLo.2022. TheBest tionalconferenceonmachinelearning.PMLR,1597–1607. ofBothWorlds:IntegratingSemanticFeatureswithExpertFeaturesforDefect [11] XiaoCheng,HaoyuWang,JiayiHua,GuoaiXu,andYuleiSui.2021.Deepwukong: PredictionandLocalization.InProceedingsofthe202230thACMJointMeetingon Staticallydetectingsoftwarevulnerabilitiesusingdeepgraphneuralnetwork. EuropeanSoftwareEngineeringConferenceandSymposiumontheFoundationsof ACMTransactionsonSoftwareEngineeringandMethodology(TOSEM)30,3(2021), SoftwareEngineering.ACM,672–683. 1–33. [34] ChaoNi,KaiwenYang,XinXia,DavidLo,XiangChen,andXiaohuYang.2022. [12] XiaoCheng,GuanqinZhang,HaoyuWang,andYuleiSui.2022.Path-sensitive DefectIdentification,Categorization,andRepair:BetterTogether.arXivpreprint codeembeddingviacontrastivelearningforsoftwarevulnerabilitydetection. arXiv:2204.04856(2022). InProceedingsofthe31stACMSIGSOFTInternationalSymposiumonSoftware [35] Georgios Nikitopoulos, Konstantina Dritsa, Panos Louridas, and Dimitris TestingandAnalysis.519–531. Mitropoulos.2021.CrossVul:across-languagevulnerabilitydatasetwithcommit [13] HoaKhanhDam,TruyenTran,TrangPham,ShienWeeNg,JohnGrundy,and data.InProceedingsofthe29thACMJointMeetingonEuropeanSoftwareEngi- AdityaGhose.2017. Automaticfeaturelearningforvulnerabilityprediction. neeringConferenceandSymposiumontheFoundationsofSoftwareEngineering. arXivpreprintarXiv:1708.02368(2017). 1565–1569. [14] JacobDevlin,Ming-WeiChang,KentonLee,andKristinaToutanova.2018.Bert: [36] AaronvandenOord,YazheLi,andOriolVinyals.2018.Representationlearning
Pre-trainingofdeepbidirectionaltransformersforlanguageunderstanding.arXiv withcontrastivepredictivecoding.arXivpreprintarXiv:1807.03748(2018). preprintarXiv:1810.04805(2018). [37] ChanathipPornprasitandChakkritTantithamthavorn.2022.DeepLineDP:To- [15] YangruiboDing,SahilSuneja,YunhuiZheng,JimLaredo,AlessandroMorari,Gail wardsaDeepLearningApproachforLine-LevelDefectPrediction.IEEETrans- Kaiser,andBaishakhiRay.2021.VELVET:anoVelEnsembleLearningapproach actionsonSoftwareEngineering(2022). toautomaticallylocateVulnErablesTatements.arXivpreprintarXiv:2112.10893 [38] RebeccaRussell,LouisKim,LeiHamilton,TomoLazovich,JacobHarer,Onur (2021). Ozdemir,PaulEllingwood,andMarcMcConley.2018.Automatedvulnerability [16] XuDuan,JingzhengWu,ShoulingJi,ZhiqingRui,TianyueLuo,MutianYang, detectioninsourcecodeusingdeeprepresentationlearning.InProceedingsof andYanjunWu.2019.VulSniper:FocusYourAttentiontoShootFine-Grained the17thIEEEinternationalconferenceonmachinelearningandapplications.IEEE, Vulnerabilities..InIJCAI.4665–4671. 757–762. [17] GangFan,RongxinWu,QingkaiShi,XiaoXiao,JinguoZhou,andCharlesZhang. [39] JiamouSun,ZhenchangXing,HaoGuo,DehengYe,XiaohongLi,XiweiXu,and 2019.Smoke:scalablepath-sensitivememoryleakdetectionformillionsoflines LimingZhu.2022. GeneratinginformativeCVEdescriptionfromExploitDB ofcode.In2019IEEE/ACM41stInternationalConferenceonSoftwareEngineering postsbyextractivesummarization.ACMTransactionsonSoftwareEngineering (ICSE).IEEE,72–82. andMethodology(TOSEM)(2022). [18] JiahaoFan,YiLi,ShaohuaWang,andTienNNguyen.2020. AC/C++code [40] JiamouSun,ZhenchangXing,QinghuaLu,Xiwei(Sherry)Xu,LimingZhu, vulnerabilitydatasetwithcodechangesandCVEsummaries.InProceedingsof ThongHoang,andDehaiZhao.2023.SilentVulnerableDependencyAlertPredic- the17thInternationalConferenceonMiningSoftwareRepositories.508–512. tionwithVulnerabilityKeyAspectExplanation.InIEEE/ACM45stInternational [19] MichaelFuandChakkritTantithamthavorn.2022.LineVul:ATransformer-based ConferenceonSoftwareEngineering(ICSE).IEEE. Line-LevelVulnerabilityPrediction.(2022). [41] Synopsys.2023.Coverity. https://scan.coverity.com/ [20] TianyuGao,XingchengYao,andDanqiChen.2021.Simcse:Simplecontrastive [42] HuantingWang,GuixinYe,ZhanyongTang,ShinHweiTan,SongfangHuang, learningofsentenceembeddings.arXivpreprintarXiv:2104.08821(2021). DingyiFang,YansongFeng,LizhongBian,andZhengWang.2020. Combin- [21] TheTcpdumpGroup.2023.tcpdump. https://github.com/the-tcpdump-group/ inggraph-basedlearningwithautomateddatacollectionforcodevulnerability tcpdump detection. IEEETransactionsonInformationForensicsandSecurity16(2020), [22] DayaGuo,ShuaiLu,NanDuan,YanlinWang,MingZhou,andJianYin.2022. 1943–1958. UniXcoder:UnifiedCross-ModalPre-trainingforCodeRepresentation.arXiv [43] YuemingWu,DeqingZou,ShihanDou,WeiYang,DuoXu,andHaiJin.2022. preprintarXiv:2203.03850(2022). VulCNN:AnImage-inspiredScalableVulnerabilityDetectionSystem.(2022). [23] DavidHin,AndreyKan,HuamingChen,andMAliBabar.2022. LineVD: [44] FabianYamaguchi,NicoGolde,DanielArp,andKonradRieck.2014.Modelingand Statement-levelVulnerabilityDetectionusingGraphNeuralNetworks.arXiv discoveringvulnerabilitieswithcodepropertygraphs.In2014IEEESymposium preprintarXiv:2203.05181(2022). onSecurityandPrivacy.IEEE,590–604. [24] EladHofferandNirAilon.2015.Deepmetriclearningusingtripletnetwork.In [45] YaqinZhou,ShangqingLiu,JingkaiSiow,XiaoningDu,andYangLiu.2019. Internationalworkshoponsimilarity-basedpatternrecognition.Springer,84–92. Devign:Effectivevulnerabilityidentificationbylearningcomprehensiveprogram [25] SecureSoftwareInc.2023. RoughAuditingToolforSecurity(RATS). https: semanticsviagraphneuralnetworks.InInProceedingsofthe33rdInternational //code.google.com/p/rough-auditing-tool-for-security/ ConferenceonNeuralInformationProcessingSystems.10197–10207. [26] WenLi,HaipengCai,YuleiSui,andDavidManz.2020. PCA:memoryleak [46] YuxiangZhuandMinxuePan.2019.Automaticcodesummarization:Asystematic detectionusingpartialcall-pathanalysis.InProceedingsofthe28thACMJoint literaturereview.arXivpreprintarXiv:1909.04352(2019). MeetingonEuropeanSoftwareEngineeringConferenceandSymposiumonthe [47] DeqingZou,YaweiZhu,ShouhuaiXu,ZhenLi,HaiJin,andHengkaiYe.2021. FoundationsofSoftwareEngineering.1621–1625. Interpretingdeeplearning-basedvulnerabilitydetectorpredictionsbasedon [27] YiLi,ShaohuaWang,andTienNNguyen.2021.Vulnerabilitydetectionwith heuristicsearching.ACMTransactionsonSoftwareEngineeringandMethodology fine-grainedinterpretations.InProceedingsofthe29thACMJointMeetingon (TOSEM)30,2(2021),1–31. EuropeanSoftwareEngineeringConferenceandSymposiumontheFoundationsof SoftwareEngineering.292–303. Received2023-03-02;accepted2023-07-27
[28] ZhenLi,DeqingZou,ShouhuaiXu,ZhaoxuanChen,YaweiZhu,andHaiJin. 2021.Vuldeelocator:adeeplearning-basedfine-grainedvulnerabilitydetector.
2308.12697 Prompt-Enhanced Software Vulnerability Detection Using ChatGPT ChenyuanZhang∗ HaoLiu∗ KeyLaboratoryofMultimediaTrustedPerceptionand KeyLaboratoryofMultimediaTrustedPerceptionand EfficientComputing,MinistryofEducationofChina, EfficientComputing,MinistryofEducationofChina, SchoolofInformatics,XiamenUniversity SchoolofInformatics,XiamenUniversity China China zhangchenyuan@stu.xmu.edu.cn haoliu@stu.xmu.edu.cn JiutianZeng HuiLi KejingYang KeyLaboratoryofMultimediaTrustedPerceptionand YuhongLi EfficientComputing,MinistryofEducationofChina, SchoolofInformatics,XiamenUniversity Alibaba China China hui@xmu.edu.cn {zengjiutian.zjt,kejing.ykj,daniel.lyh}@alibaba-inc.com ABSTRACT ACMReferenceFormat: With the increase in software vulnerabilities that cause signifi- ChenyuanZhang,HaoLiu,JiutianZeng,KejingYang,YuhongLi,andHuiLi. 2024.Prompt-EnhancedSoftwareVulnerabilityDetectionUsingChatGPT. canteconomicandsociallosses,automaticvulnerabilitydetection InProceedingsofACMConference(Conference’17).ACM,NewYork,NY, hasbecomeessentialinsoftwaredevelopmentandmaintenance. USA,13pages.https://doi.org/10.1145/nnnnnnn.nnnnnnn Recently,largelanguagemodels(LLMs)likeGPThavereceived considerableattentionduetotheirstunningintelligence,andsome 1 INTRODUCTION studiesconsiderusingChatGPTforvulnerabilitydetection.How- ever,theydonotfullyconsiderthecharacteristicsofLLMs,since Softwarehasbecomeanindispensablepartofourdigitalsociety. their designed questions to ChatGPT are simple without a spe- However,anincreasingnumberofsoftwarevulnerabilitiesarecaus- cificpromptdesigntailoredforvulnerabilitydetection.Thispaper ingsignificanteconomicandsociallosses[47].Somestudieshave launches a study on the performance of software vulnerability shownthatsecurityvulnerabilitiesexistinasignificantnumber detectionusingChatGPTwithdifferentpromptdesigns.Firstly, ofopen-sourcecoderepositories,andnearlyhalfofthemcontain wecomplementpreviousworkbyapplyingvariousimprovements high-riskvulnerabilities[31,37],suggestingthatsoftwarevulner- tothebasicprompt.Moreover,weincorporatestructuralandse- ability detection needs further improvement and it remains an quentialauxiliaryinformationtoimprovethepromptdesign.Be- unsolvedandchallengingprobleminthesoftwareindustry[33]. sides,weleverageChatGPT’sabilityofmemorizingmulti-round Consequently,itisimperativetoimplementintelligentautomatic dialogue to design suitable prompts for vulnerability detection. softwarevulnerabilitydetectionmethodstoprotectsoftwaresecu- Weconductextensiveexperimentsontwovulnerabilitydatasets ritybetter. todemonstratetheeffectivenessofprompt-enhancedvulnerabil- Traditionalvulnerabilitydetectionapproachesaremainlybased itydetectionusingChatGPT.Wealsoanalyzethemeritandde- onrulesandclassicalmachinelearning(ML)techniques.Rule-based meritofusingChatGPTforvulnerabilitydetection.Repository: approaches[16,25,62]usepre-definedvulnerabilityrulesfordetec- https://github.com/KDEGroup/LLMVulnerabilityDetection. tion.Theseuser-definedfeatureshighlyrelyonexpertknowledge andaregenerallylabor-intensive,makingitdifficulttodeploythem KEYWORDS tocoverdifferentsoftwarevulnerabilities.ML-basedvulnerability detectionapproaches[18,50,55,57]learnlatentfeaturesofthevul- softwarevulnerabilitydetection,prompt,largelanguagemodel, nerablecodesnippets,providingbettergeneralizationanddetection chatgpt accuracycomparedtorule-basedapproaches.Theyusuallyextract codefeaturesbyleveragingWord2vec[45]orcontinuousbag-of- ∗Thefirsttwoauthorscontributedequally. words(CBOW)[45]andthenapplyingclassicalmachinelearning algorithmslikeSupportVectorMachineandLogisticRegression Permissiontomakedigitalorhardcopiesofallorpartofthisworkforpersonalor However,theyrelyoncoarse-grainedpatternsofvulnerabilities classroomuseisgrantedwithoutfeeprovidedthatcopiesarenotmadeordistributed forprofitorcommercialadvantageandthatcopiesbearthisnoticeandthefullcitation duetotheirshallowarchitecturesandtheycannotachieveaccurate onthefirstpage.CopyrightsforcomponentsofthisworkownedbyothersthanACM vulnerabilitydetection. mustbehonored.Abstractingwithcreditispermitted.Tocopyotherwise,orrepublish, Inspiredbythesuccessofdeeplearning(DL),severalattempts[6, topostonserversortoredistributetolists,requirespriorspecificpermissionand/ora fee.Requestpermissionsfrompermissions@acm.org. 11,13,34]aimtodetectvulnerabilitiesusingdeepneuralnetworks. Conference’17,July2017,Washington,DC,USA Comparedtotraditionaltechniques,theycancaptureimplicitand ©2024AssociationforComputingMachinery. complicatedvulnerabilitypatternsfromsourcecodebetter.Inthe ACMISBN978-x-xxxx-xxxx-x/YY/MM...$15.00 https://doi.org/10.1145/nnnnnnn.nnnnnnn meanwhile,varioussophisticatedcodemodelingmethods,suchas 4202 rpA 21 ]ES.sc[ 2v79621.8032:viXraConference’17,July2017,Washington,DC,USA ChenyuanZhang,HaoLiu,JiutianZeng,KejingYang,YuhongLi,andHuiLi
controlflowgraph(CFG),programdependencegraph(PDG)and • WeleverageChatGPT’sabilityofmemorizingmulti-rounddia- dataflowgraph(DFG),areleveragedbyDL-basedmethodstoenrich logueinvulnerabilitydetection.Throughourdesignedchain- codesemantics[11,31,35,58].Therearealsosomestudiesadopting of-thoughtprompting,theperformanceofChatGPTonvulner- textswritteninnaturallanguage(e.g.,codesummaries,instruc- abilitydetectiongetsfurtherimprovements.Thisisalsonot tions,andcommitmessages)toenhancerepresentationlearning consideredinpreviousworks. forDL-basedvulnerabilitydetection[9,27,27,46,51,56,65,78]. • Weconductextensiveexperimentsontwovulnerabilitydatasets Nevertheless,mostexistingDL-basedapproachesarenotgeneral todemonstratetheeffectivenessofprompt-enhancedvulnera- detectionmethods,astheyareprogramming-language-specificor bilitydetectionusingChatGPT.Wealsoanalyzethemeritand vulnerable-type-specific. demeritofusingChatGPTforvulnerabilitydetection. Inrecentyears,large-scalelanguagemodels(LLMs)likeGPT The remainder of this paper is organized as follows: Sec. 2 havereceivedincreasingattentionduetotheirstunningintelli- presentstherelatedworkofthispaper.Sec.3describesthedata gence[75].LLMsaretrainedonlargecorporausingpowerfulcom- usedinourstudy,andSec.4demonstratesourpromptdesignsfor putationresources.Theytypicallycontainbillionsofmodelparam- enhancingsoftwarevulnerabilitydetectionusingChatGPT.Sec.5 eters,allowingthemtocapturecomplexpatternsandrevealgeneral providestheexperimentalresultsanddiscussionsonthevulnera- intelligenceinmanytasksthatwerethoughttobedifficultforAIto bilitydetectioncapabilityofChatGPT.Sec.6describesthepotential completeinthenearfuturesuccessfully.Arepresentativeexample threatsofvalidityforthiswork.Sec.7concludesthiswork. isChatGPT1,aversatilechatbotempoweredbytheLLMGPTthat allowsuserstohavehuman-likeconversationstoreceivedesirable 2 RELATEDWORK answers,includingbutnotlimitedtocomposition(e.g.,music,tele- 2.1 Largelanguagemodels plays,fairytales,andstudentessays),programmingandanswering testquestions.Asaresult,somerecentworkshaveconsideredus- Largelanguagemodels(LLMs)haverecentlyrevolutionizedAI,ex- ingChatGPTtoimprovesoftwarevulnerabilitydetection[5,60]. hibitingremarkableprowessacrossawiderangeoftasks[3,4,61]. Sobaniaetal.[60]evaluateChatGPT’sbug-fixingperformanceon LLMsarebasedontheideaoflanguagemodeling(LM).LMisa astandardbenchmark.Caoetal.[5]exploreChatGPT’sabilityto prevalent approach to model the generative likelihood of word fixDLprograms.However,thesemethodsdonotfullyconsiderthe sequences so as to predict the future tokens. Unlike traditional characteristicsofLLMs,sincetheirdesignedquestionstoChatGPT LMapproaches,LLMsaretrainedonahugevolumeofdatausing aresimplewithoutaspecificpromptdesigntailoredforvulnerabil- powerfulcomputationresources.Theversatilityandadaptability itydetectionusingLLMs.Promptengineeringmodifiestheoriginal ofLLMsaredeemedtobecreditedwiththeirbillion-scaleparame- userinputusingatextualprompt,andtheresultingtexthassome ters[75]thathaveneverbeenachievedinthepast. unfilledslots.Then,LLMsareaskedtofilltheunfilledinformation RepresentativeLLMsincludebutnotlimitedtoOpenAI’sGPT[4, whichisactuallytheanswerthattheuserrequires.Promptengi- 48],Google’sPaLMandBard[1,10]andDeepMind’sChinchilla[24]. neeringhasbeenshowntobepromisinginexploringthepotential However,someofthemcanbeaccessedthroughprovidedAPIs ofLLMs[40],althoughithasnotbeenfullyconsideredinsoftware whileothersarenotaccessible[43].TherearemanyotherLLMsthat vulnerabilitydetection.Besides,unliketraditionalMLorDLmeth- areopen-source.EleutherAIhascontributedGPT-NeoX-20B[2] ods,LLMscansolvecomplicatedtasksthroughmultiplereasoning andGPT-J-6B2.GooglehasreleasedUL2-20B[63].TsinghuaUniver- steps(i.e.,chain-of-thought),whichisignoredbyexistingworks sityhasintroducedGLM-130B[71].TheTransformerarchitecture- onvulnerabilitydetection. basedlanguagemodelsOPT[74]andLLaMA[64]releasedbyMeta Toaddresstheaboveissues,thispaperlaunchesastudyonthe havealsoattractedattentionrecently. performanceofvulnerabilitydetectionusingChatGPT4withdiffer- 2.2 PromptEngineering entpromptdesigns.ChatGPT4isthenewestversionofChatGPT whenweconductthisstudy,andthetermChatGPTreferstoChat- Prompting-basedlearninghasbecomeaprevalentlearningpar- GPT4inthispaper.Thecontributionsofthisworkaresummarised adigmforLM.Insteadofusingpre-trainedlanguagemodelsfor below: downstreamtasksviaobjectiveengineering,prompting-basedlearn- • Wecomplementpreviousworkbyapplyingvariousimprove- ingreformulatesthedownstreamtasksthroughatextualprompt mentstothebasicpromptandinvestigatingthevulnerability sothattheyareclosetotaskssolvedduringtheoriginalLMtrain- detectioncapabilitiesofChatGPTonourcollectedvulnerability ing[40].Well-structuredpromptshavebeenshowntobepromis-
datasetscoveringtwoprogramminglanguages. inginimprovingtheperformanceofLLMsinvariousdownstream • Weincorporatestructuralandsequentialauxiliaryinformation tasks[52,76].Therefore,variouspromptdesignparadigmshave ofthesourcecodeinpromptdesigns,whichisshowntobe proliferated[40]. helpful for ChatGPT to detect vulnerabilities better. To our Regardingtheformatofprompts,someworksexploreprompt bestknowledge,thisisthefirsttimethattraditionalstructural search for appropriately discrete prompt [17, 26, 39, 59]. Mean- andsequentialcodemodelingmethodscanbedirectlyusedin while,someworksutilizecontinuousvector(i.e.,embeddings)as ChatGPT-basedvulnerabilitydetection. prompts[20,28,29,42,53,77]. Someworkhasexaminedtheeffectofpromptsongenerative models.Forexample,Liuetal.[41]investigatehowdifferentprompt 1https://chat.openai.com 2https://github.com/kingoflolz/mesh-transformer-jaxPrompt-EnhancedSoftwareVulnerabilityDetectionUsingChatGPT Conference’17,July2017,Washington,DC,USA keywordsaffectimagegeneration.MaddiganandSusnjakhaveex- leverageBi-LSTMtofusebothfeaturesandconductclassification. ploredusingpromptstohelpLLMsgeneratevisualizations[44]. Chengetal.[8]presentContraFlow,apath-sensitivecodeembed- Liuetal.[38]proposedifferentpromptdesignsfortwocodegener- dingapproachusingapre-trainedvalue-flowpathencoder.They ationtasks.Thereareafewrecentworksstudyingexploringthe designavalue-flowpathselectionalgorithmandapplyfeasibility potentialofChatGPTonthesoftwarevulnerabilitydetectiontask. analysistofiltervaluedsequentialpathsastheinput.Thereare Caoetal.[5]designenhancedprompttemplatestoapplyChatGPT alsoworks[54]applyingCNNstoencodesequentialcodedatafor inDeepLearningprogramrepair.Whiteetal.[70]haveexplored function-levelvulnerabilitydetection. severalpromptpatternsthatcanbeappliedtoimproverequire- Graph-basedmethodsleverageDLmethodstomodelgraphdata mentselicitation,rapidprototyping,codequality,deployment,and ofprograms,includingabstractsyntaxtree(AST),dataflowgraph testing.However,asdiscussedinSec.1,existingworksdonotfully (DFG),controlflowgraph(CFG),projectdependencygraph(PDG), considerthecharacteristicsofLLMswhendetectingvulnerabilities. invulnerabilitydetection.Sharetal.[58]proposetousevarious staticcodeattributesextractedfromCFGstodetectSQLinjection 2.3 SoftwareVulnerabilityDetection andcross-sitescriptingvulnerabilitiesinopensourcePHPprojects. Linetal.[35]utilizeBi-LSTMtoprocessASTsatfunction-levelon 2.3.1 TraditionalVulnerabilityDetection. Traditionalvulnerability threeopensourceprojectsfromGithubforvulnerabilitydetection. detectionmethodsrelyonfeatureengineeringandtraditionalma- AnotherASTbasedapproachproposedinDametal.[12]leverages chinelearningtechniques.Theygenerallylearnthecodepatterns LSTMforfile-levelvulnerabilitydetectioninopen-sourceAndroid fromthehandcraftedfeaturesextractedfromstaticand/ordynamic projects.Lietal.[31]utilizevarioustypesofRNNs(Bi-LSTMand codeanalysis.Someearlystudies[15,30,69,73]applyrulesdrawn Bi-GRU)tomodelCFGs,DFGsandPDGsinordertodetectsoftware fromexperienceas“templates”todetectpotentialvulnerabilities. vulnerabilities.Cuietal.[11]proposeVulDetector,astaticanalysis Sharetal.[57]combinethehybridprogramanalysiswithsuper- toolwherethekeyisaweightedfeaturegraph(WFG)modeltoslice visedclassifierslikelogisticregression(LR)andrandomforest(RF) theCFGs,forvulnerabilitydetection.Hinetal.[23]presentLineVD, forvulnerabilitydetection.Wangetal.[67]firstlyutilizeASTsfor whichusesatransformer-basedmodelforencodingandGraph detectingvulnerabilitiesinJavaprograms.Theycombinefunction- Neural Networks for processing control and data dependencies levelASTsandsemanticrepresentationsgeneratedbydeepbelief amongstatements. network at file-level to train traditional machine learning mod- elslikelogisticregression.Griecoetal.[18]presentVDiscover, whichintegratesbothstaticanddynamicalfeaturesusingLR,RF 3 DATA andmulti-layerperception(MLP)onalarge-scaleDebianprogram Thissectiondescribesthedatausedinourstudy. dataset.Hareretal.[22]proposeadata-drivenapproachspecif- ically applied to C/C++ programs. They leverage features from 3.1 DataCollection boththesourcecodeandthebuildprocess,andusedeepneural networks(DNNs)andconventionalmodelslikerandomforestsfor Weadopttwodatasetscontainingfunctionswithorwithoutvulner- vulnerabilitydetection.Scandariatoetal.[55]usethebag-of-words abilitiesforevaluatingvulnerabilitydetection.Onedatasetcontains representationinwhichasoftwarecomponentisseenasaseriesof JavafunctionsandtheotherdatasetcontainsC/C++functions. termswithassociatedfrequenciesasfeaturesusedinvulnerability FortheJavadataset,wecollectvulnerablecodesamplesfromthe detection.Pengetal.[50]combineN-gramanalysisandfeature SoftwareAssuranceReferenceDataset(SARD)3.SARDisastandard selectionalgorithmsforvulnerabilitydetectionandfeaturesare vulnerabledatabasewherethedataisderivedfromtheSoftware
definedascontinuoussequencesoftokeninsourcecodefiles. AssuranceMetricsAndToolEvaluation(SAMATE)projectofthe NationalInstituteofStandardsandTechnology(NIST).Eachpro- 2.3.2 DeepLearningBasedVulnerabilityDetection. Thesuccess gramintheSARDcontainsboththereal-worldvulnerablesamples of deep learning techniques (DL) in various fields has inspired andsynthetictestcases,andisaccompaniedbyalabelasgood researchers to apply DL in the vulnerability detection task [7]. (i.e.,non-vulnerablecode),bad(i.e,vulnerablecode)ormixed(i.e., Comparedtotraditionalmethods,DLbasedmethodscanautomat- containingbothvulnerablecodeandcorrespondingpatchedver- icallycapturevulnerabilityfeatures,reducingthecostoffeature sion)withauniqueCWEID.WeobtainedallJavavulnerabledata engineering. publishedbeforeJune8th,2023covering46,415projects. ExistingDL-basedmethodscanbeclassifiedintotwocategories: FortheC/C++dataset,weusetherecentresearchreleasebench- sequence-basedmethods[8,32,54,79]andgraph-basedmethods[6, mark[31],whichwascollectedfromtheNationalVulnerability 11–14,23,31,34–36,58]. Database(NVD)4.NVDcontainsvulnerabilitiesinsoftwareprod- Sequence-basedmethodsadoptDNNstomodelsequentialcode ucts(i.e.,softwaresystems)andpossiblydifffilesdescribingthe entities.Lietal.[32]proposethe“codegadget”definitiontorepre- differencebetweenavulnerablepieceofcodeanditspatchedver- senttheprogramfromtheperspectiveofslice.Theyobtaincode sion.Wefocusonthe.cor.cppfilesthatcontainsomevulnerability gadgetsbyextractingandassemblingthelibrary/APIfunctioncalls (correspondingtoaCVEID)oritspatchedversion. andthecorrespondingslicesineachprogram.ThenaBi-LSTM networkisappliedtodetectwhetherthecodeisvulnerablebased oncodegadgetsfeatures.Zouetal.[79]regard“codegadget”as theglobalfeaturesandextendtheideaofLietal.[32]byintroduc- 3https://samate.nist.gov/SARD ingtheso-called“codeattention”asthe“localized”features.They 4https://nvd.nist.gov/Conference’17,July2017,Washington,DC,USA ChenyuanZhang,HaoLiu,JiutianZeng,KejingYang,YuhongLi,andHuiLi 1 public void bad() throws Throwable{ Data Flow Graph Value comes from 2 String data; Value computed by 3 if (privateFive == 5){ 1 2 10 4 data = "7e5tc4s3"; 4 3 5 } else { 3 4 6 data = null; 5 9 7 11 7 } 5 8 if (data != null) { 6 9 KerberosPrincipal principal = new KerberosPrincipal("test"); 2 1 7 8 9 10 6 8 10 KerberosKey key = new KerberosKey(principal, data.toCharArray(), null); 11 11 IO.writeLine(key.toString()); 12 } API call sequence: KerberosPrincipal.new String.toCharArray 13 } KerberosKey.new KerberosKey.toString IO.writeLine Figure1:AnexampleofaJavafunctionanditsauxiliaryinformation. Table1:Thestatisticsofthedata. 3.3 FeatureExtraction Inourpromptdesign,twotypesofauxiliaryinformation,APIcall Language Types #Vul #Non-Vul All sequencesanddataflow,areutilized.Inthissection,weillustrate Java 50 1,171 917 2,088 howweextractthemfromthetwodatasets. C/C++ 39 1,015 922 1,937 3.3.1 API Call Sequence Extraction. To extract the API call se- quences,wefirstleveragethePythonlibrarytree-sitter5toparse 3.2 DataPre-processing codefilesintoAbstractSyntaxTrees(ASTs).ForC/C++,weextract allthenodeswhosetypeis"call_expression"andaddallthenames Weperformthefollowingdatapre-processingstepsonthetwo byorder.ForJava,wefollowthesamestepsasdescribedinDEEP- datasets: API[19]totraverseeachAST.TheAPIcallsequenceofeachJava (1) Weremovedduplicatedcodeandallannotationsineachfunc- functioncanbeextractedasfollows: tionbecausetheyexplicitlyindicatethevulnerability.Inad- • ForeachconstructorinvocationnewC(),weaddC.newtothe dition,wereplace“bad”,“good”,“VULN"and“PATCHED"in APIcallsequence. functionnameswith“func”. • Foreachfunctioncallo.m()whereoisaninstanceoftheclass (2) ConsideringthelimitedinputlengthofChatGPT,wesetthe C,weaddC.mtotheAPIcallsequence. maximumlengthofinputtobe700toensurethattheinputse- • Forafunctioncallpassedasaparameter,weaddthefunctionbe- quenceafterconcatenatingadditionalinformation(i.e.,prompt) isnottruncatedbythesystem. forethecallingfunction.Forexample,for𝑜 1.𝑓 1(𝑜 2.𝑓 2(),𝑜 3.𝑓 3()), (3) Wefilteroutfunctionswithlessthanthreelinesastheypossibly weaddtheAPIcallsequence𝐶 2.𝑓 2-𝐶 3.𝑓 3-𝐶 1.𝑓 1,where𝐶 𝑖 isthe classoftheinstance𝑜 𝑖. donothavesufficientinformationforvulnerabilitydetection. (4) ForJavadata,astheclassnameindatasetcontainsvulnera- • Forasequenceofstatements𝑠 1;𝑠 2;...;𝑠 𝑛,weextracttheAPI callsequence𝑎 𝑖 fromeachstatement𝑠 𝑖,andconcatenatethem bilityinformation(i.e.,vulnerabilitytype)andweonlyfocus onfunction-levelvulnerabilitydetection,wefilteroutthose togetherinordertoconstructtheAPIcallsequence𝑎 1𝑎 2–...-𝑎 𝑛. samplesthatcallfunctionsinotherJavaclasses.ForC/C++, • Forconditionalstatementssuchas𝑖𝑓(𝑠 1){𝑠 2;}𝑒𝑙𝑠𝑒{𝑠 3;},wecre- we removed CVE IDs in function names that have obvious ate a sequence from all possible branches, that is, 𝑎 1-𝑎 2-𝑎 3, where𝑎 𝑖 istheAPIcallsequenceextractedfromthestatement vulnerabilityhints. 𝑠 𝑖.
ForJavadata,a“bad”functioncanbeassociatedwithmultiple • Forloopstatementssuchas𝑤ℎ𝑖𝑙𝑒(𝑠 1){𝑠 2;},weaddthesequence “good”ones(i.e.,patchversions)in“mixed”cases.Werandomly 𝑎 1-𝑎 2,where𝑎 1 and𝑎 2 aretheAPIsequencesextractedfrom selectedaneligible“good’oneforsuchcasestobalancethenumber thestatement𝑠 1and𝑠 2,respectively. ofvulnerableandnon-vulnerablesamples.Byexaminingthedata ThelowerrightpartofFig.1providesanexampleoftheextracted distributionofvulnerabilitiesintheJavadataset,wefindthatmore APIcallsequencefromaJavamethod.Notethat,inourstudy,the than80%ofthesamplesbelongtotop-50largestvulnerabilitytypes. functionname“bad”willbereplacedwith“func”asdescribedin Therefore,weconsidersamplesinthese50vulnerabilitytypessince Sec.3.2. wealsoinvestigatetheeffectivenessofChatGPTondetectingdiffer- entvulnerabilitytypesandtheevaluationresultsonvulnerability 3.3.2 DataFlowGraphExtraction. Dataflowrepresentstherela- typeswithfewsamplesmaynotbeprecise.Finally,asshownin tionof”where-the-value-comes-from”betweenvariables.Given Tab.1,weget1,171vulnerablefunctionsand917non-vulnerable functionsfortheJavadataset,andtheC/C++datasetcontains1,015 vulnerablefunctionsand922non-vulnerablefunctions. 5https://tree-sitter.github.io/tree-sitterPrompt-EnhancedSoftwareVulnerabilityDetectionUsingChatGPT Conference’17,July2017,Washington,DC,USA thesourcecode𝐶,werefertoGraphCodeBERT’s[21]extraction methods[11,31,35,58].Thisinspiresustoconsiderwhetherwecan methodandperformthefollowingstepstoextractthedataflow: utilizethemtoimprovethepromptandachievebettervulnerability • Parse𝐶intoanAbstractSyntaxTree(AST)usingtree-sitter. detection. • Identifythevariablesbyusingthesyntacticinformationandter- minals(leaves)oftheAST,whicharedenotedas𝑉 ={𝑣 1,𝑣 2,...,𝑣 𝑘}. 4.2.1 TheNecessityofAuxiliaryInformation. Beforeincorporating auxiliaryinformationintoprompts,wefirstexaminewhattypesof • Considerthevariablesasnodesofthegraph,andforeachvari- ablein𝑉,addthedirectededge𝜀 =<𝑣 𝑖,𝑣 𝑗 >tothedictionary𝐷 auxiliaryinformationarebeneficialtodetectingvulnerabilitiesusing asatuple(𝑣 𝑖,𝑝 𝑖,𝑣 𝑗,𝑝 𝑗),where𝑝 𝑖 and𝑝 𝑗 denotethepositionof ChatGPT.Foreachdataset,werandomlysample20functionsand 𝑣 𝑖 and𝑣 𝑗.Thetupleindicatesthat𝑣 𝑖 comesfromoriscomputed askChatGPTthefollowingquestion: by𝑣 𝑗. TheupperrightpartofFig.1showstheextracteddataflowgraph Pleaseoutput[dataflow/controlflow/programdependence] ofaJavamethod. ofthefollowingcode:[CODE] 4 PROMPTDESIGN Asanexample,theresponseofChatGPTw.r.t.thecodeshown ThissectionintroducesourdesignedpromptsforenhancingChat- inFig.1isshownbelow: GPTonsoftwarevulnerabilitydetection.Forsimplicity,weuse P𝑥 torepresenteachprompt,where𝑥 denotesthecompositions Theanswerfordataflow: oftheprompt,andwewillexplaineach𝑥 whenweexplainthe 1.thedatavalueofdataat5thtokencomesfromprivateFive correspondingpromptdesignforthefirsttime. at1sttoken 2.thedatavalueofdataat5thtokencomesfromtheconstant 4.1 BasicPrompting “7e5tc4s3”at5thtoken Firstly,toconductvulnerabilitydetectionviaChatGPT,itisessential 3.thedatavalueofdataat8thtokencomesfromprivateFive tohaveabasicprompt(P ).Weusethefollowingbasicpromptin b at1sttoken thisstudy,andweaskChatGPTtogiveanexplicitanswer(Yesor 4.thedatavalueofdataat8thtokencomesfromtheconstant No)toclarifytheresult. nullat8thtoken 5.thedatavalueofprincipalat15thtokencomesfromthe P b:Isthefollowingprogrambuggy?PleaseanswerYesorNo. constant“test”at15thtoken [CODE] 6.thedatavalueofkeyat20thtokencomesfromprincipalat 15thtoken where[CODE]indicatesthetestfunction. 7.thedatavalueofkeyat20thtokencomesfromdataat5th FollowingOpenAI’sgpt-best-practicesdocument[49],wefur- tokenor8thtoken therproposetherole-basedbasicprompt(P )toremindChatGPT 8.thedatavalueofkeyat20thtokencomesfromtheconstant r-b ofitsjob(i.e.,detectvulnerabilities)sothatitfocusesonthevul- nullat20thtoken nerabilityissue: Fortheresponsew.r.t.dataflow,wecanobservethatitdoesnot P r-b:Iwantyoutoactasavulnerabilitydetectionsystem. recognizetwopossiblepathsforthevariable“data”inthesecond Myfirstrequestis“Isthefollowingprogrambuggy?”Please ifstatement.Besides,inthethirdline,thevariable“data”doesnot answerYesorNo.[CODE] comefromthevariable“privateFive”.Theincorrectresponsew.r.t. dataflowshowsthatChatGPTcannotfullyunderstandthedata Whenthepromptcontainssomekeytokens(e.g.,thekeyword flowofafunctionsolelybasedonthesourcecode. “buggy”intheprompt),itispossiblethatChatGPTguessesthe TheanswerofChatGPTw.r.t.controlflowisshownasfollows: answersimplybasedonthekeywordsinsteadofanalyzingthetest function,i.e.,merelyanswering“No”duetothekeyword“buggy”. Theanswerforcontrolflow: ToverifywhetherChatGPTwillmakeabiasedjudgmentdueto 1.CheckifprivateFiveequals5. some key tokens in the prompt, we designed a reverse-question 2.IfprivateFiveis5,setdatato“7e5tc4s3”.Otherwise,setdata prompttoenhancetherole-basedbasicprompt(P r-r-b): tonull. 3.Checkifdataisnotnull.Ifit’snotnull,proceedtostep4.
P r-r-b:Iwantyoutoactasavulnerabilitydetectionsystem. Otherwise,exitthefunction. Myfirstrequestis“Isthefollowingprogramcorrect?”Please 4.CreateanewKerberosPrincipalobjectcalledprincipalwith answerYesorNo.[CODE] theargument“test”. 5.CreateanewKerberosKeyobjectcalledkeywiththeargu- mentsprincipal,data.toCharArray(),andnull. 4.2 PromptingwithAuxiliaryInformation 6.OutputthekeyasastringusingIO.writeLine(). 7.Endoffunction. Auxiliaryinformation,suchasCFG,DFG,PDGandAPIcallse- quences,isprevalentlyusedbyDL-basedvulnerabilitydetectionConference’17,July2017,Washington,DC,USA ChenyuanZhang,HaoLiu,JiutianZeng,KejingYang,YuhongLi,andHuiLi Forcontrolflow,wecanobservethatChatGPTcanaccurately 4.2.2 PromptswithDFGandAPICalls. SinceChatGPTcannotfully identifytheexecutionpathofeachstatement,indicatingthatitcan understanddataflowandAPIcallsequencesoffunctions,based understandthefunction’scontrolflow. ontherole-basedpromptP ,wedesignthefollowingprompts r-b TheanswerofChatGPTw.r.t.programdependenceisshown (P andP )equippedwithauxiliaryinformationondataflow r-b-d r-a-b below: orAPIcalls: Theanswerforprogramdependence: P r-b-d:Iwantyoutoactasavulnerabilitydetectionsystem. 1.ControlDependence: I will provide you with the original program and the data -‘if(privateFive==5)’statementiscontroldependentonthe flowinformation,andyouwillactuponthem.Isthefollowing functionentry(bad()method). programbuggy?[CODE].[DFdescription]. -‘if(data!=null)’statementiscontroldependentonthefunc- tionentry(bad()method). P :Iwantyoutoactasavulnerabilitydetectionsystem.I r-a-b 2.DataDependence: willprovideyouwiththeoriginalprogramandtheAPIcall -‘data’variableisdatadependenton‘if(privateFive==5)’ sequence,andyouwillactuponthem.[APIdescription].Is statement. thefollowingprogrambuggy?[CODE]. -‘KerberosPrincipalprincipal’isdatadependentonthecon- stantstring“test”. where[APIdescription]and[DFdescription]areconstructedbased -‘KerberosKeykey’isdatadependenton‘principal’and‘data’ ontheextractedAPIcallsequencesandDFGsdescribedinSec.3.3. variables. Notethatthepositionoftheletter“d”andletter“a”inthesubscripts -‘IO.writeLine(key.toString())’isdatadependenton‘key’vari- of P andP indicatethepositonof[DFdescription]and able. r-b-d r-a-b [APIdescription]w.r.t.thepartofthetaskrole(“r”)andthepart ofthebasicprompt(“b”).Thereareotheroptionsfortheorderbut Wecanseethattheresponsew.r.t.programdependencyhasthe P andP yieldbetterperformancethanalternativesand r-b-d r-a-b sameissueastheresponsew.r.t.dataflowdescribedabove. weadoptthemasthedefaultorderforpromptswithinformation Forthetotal40sampledcases,wecanobservesimilarresultsas ondataflow/APIcalls.Wealsodiscusstheimpactoftheorderin theaboveresponsestothecodeshowninFig.1.Therefore,wecan Sec.5.5. concludethat,additionalinformationondataflowisbeneficialto Toobtain[APIdescription],onceweobtaintheAPIcallsequence enhancetheunderstandingofChatGPTonthesourcecode. ofeachfunction(seeSec.3.3.1),wecanconcatenateeachfunction WealsoconductasimpletesttoinvestigatewhetherChatGPT callwithspecificwords.WeproposeatemplateforeachAPIcall canextractAPIcallsequencesfromthefunctioncorrectly.Similar sequencetoconstruct[APIdescription]: toprevioustests,werandomlydraw20codesamplesfromeach datasetandaskChatGPTthefollowingquestion: Theprogramfirstcalls𝑎 1,thencalls𝑎 2,···,thencalls𝑎 𝑖,···, andfinallycalls𝑎 𝑛. PleaseoutputalltheAPIcalledbythefollowingcodeinorder. Outputformat:(xx).(xxx).[CODE] where𝑛denotesthenumberoffunctioncallsintheAPIcallse- quence.Forexample,the[APIdescription]fortheAPIcallsequence Asanexample,theresponseofChatGPTw.r.t.thecodeshown inFig.1is: inFig.1isshownbelow: TheprogramfirstcallsKerberosPrincipal.new,thencalls String.toCharArray,thencallsKerberosKey.new,thencalls TheanswerforAPIcallsequence: KerberosKey.toString,andfinallycallsIO.writeLine. 1.KerberosPrincipal.constructor 2.KerberosKey.constructor 3.IO.writeLine Similarly,wecanconstruct[DFdescription]foreachfunction basedontheextractedtupledescribedinSec.3.3.2,wedesigna prompttemplatetointegrateDFGintotheinputstoChatGPT: Fromtheaboveexample,wecanobservethatChatGPTcanonly identifyobviousandsimpleAPIcalls.Thecallspassedasfunction parametersarenotidentifiedbyChatGPT(i.e.,String.toCharArray The data value of the variable 𝑣 𝑖 at the 𝑝 𝑖th token comes andKerberosKey.toString).Besides,basedontheaboveresponse, from/iscomputedbythevariable𝑣 𝑗 atthe𝑝 𝑗thtoken. it is unclear whether ChatGPT can recognize the order of API calls(i.e.,callKerberosKey.toStringfirstandthencallIO.writeLine). Forexample,thepromptofthedataflowinFig.1is: Therefore,wecanconcludethatexplicitlyaddinginformationon APIcallsequencescanbenefitChatGPTandimproveitsabilityto Thedatavalueofthevariabledataatthe17thtokencomes comprehendsourcecode.Forthetotal40sampledcases,wehavea fromthevariabledataatthe11thtokenorthevariabledata
similarobservationastheaboveexample.Prompt-EnhancedSoftwareVulnerabilityDetectionUsingChatGPT Conference’17,July2017,Washington,DC,USA 5.1 ExperimentalSettings at14thtoken.Thedatavalueofthevariabledataatthe11th 5.1.1 VulnerabilityDetectionBaselines. Inourstudy,wecompared tokeniscomputedbythe“7e5tc4s3”atthe12thtoken... ChatGPTwithtwostate-of-the-artvulnerabilitydetectionmethods: • CFGNN6 [72]isthestate-of-the-artcondition-basedbugde- tectionmethod,whichutilizesAPIknowledgeandCFG-based 4.3 Chain-of-ThoughtPrompting GraphNeuralNetwork(CFGNN)todetectcondition-related OneremarkableimprovementofLLMsovertraditionalsmalllan- bugsautomatically. guagemodelsisthatLLMscansolvecomplextasksviamultiple • Bugram[66]adoptsn-gramlanguagemodelsinsteadofrules reasoningsteps.Thekeyisthechain-of-thoughtprompting[68]. todetectbugs.Itfirstmodelsprogramtokenssequentiallyusing A chain of thought is a coherent series of intermediate natural then-gramlanguagemodelandthenrankstokensequencesac- languagereasoningstepsthatleadtothefinalanswerforatask. cordingtotheirprobabilitiesinthelearnedmodel.Low-probability SinceChatGPTcanmemorizemulti-stepinteractions,wecanat- sequencesaremarkedaspotentialbugs. temptchain-of-thoughtprompting(i.e.,designmultipleprompts) Whilethereareothersoftwarevulnerabilitydetectionmethods, forvulnerabilitydetection. theyaredesignedforoneorafewspecificvulnerabilitytypes.We choosetheabovetwobaselinesbecausetheyaregeneraldetection Step1:Intuitively,LLMscancorrectlydeterminewhetherthecode methodsthatcancoverdifferenttypesofvulnerabilitytypes.We snippetisvulnerableornot,providingthatLLMscanfirstunder- usethedefaultconfigurationsofbaselinesinourstudy. standthepurposeofthecodeprecisely.Consequently,wedesign thefirst-steppromptfortheintentionofthetestcode: 5.1.2 EvaluationMetrics. WeuseAccuracy(Acc),Precision(P), Recall(R)andF1score(F1),whicharecommonlyusedtoevaluate (chain) vulnerabilitydetectionmethods,tomeasuretheperformanceof P :Pleasedescribetheintentofthegivencode.[CODE]. 1 ChatGPT. Step2:Followingthefirststep,wecancontinuetoaskChatGPT 5.2 EffectivenessofBasicPrompts(RQ1) aboutthevulnerabilityofthetestfunction.Forinstance,wecan Tab.2illustratesthedetectionperformanceofChatGPTusingdiffer- adopttherole-basedbasicprompt(P r-b)inSec.4.1asthesecond entprompts.InTab.2,wereporttheperformanceonthevulnerable step: samplesetandthenon-vulnerablesamplesetseparately.Wealso providetheresultsonthecompletesamplesetwhicharedenotedby (chain) “All”inTab.2.InTab.2,“Det.”denoteshowmanytestsamplesare P :Iwantyoutoactasavulnerabilitydetectionsystem. 2,r-b correctlypredicted.Forinstance,ChatGPTwithP cancorrectly Istheaboveprogrambuggy?PleaseanswerYesorNo. b predict1,091outof1,171truevulnerablesamplesasvulnerable codeontheJavadataset.Notethatsometestcasesareexcluded Step2withAuxiliaryInformation:SimilartoP /P pro- sincetheirfeaturescannotbeextractedbybaselines/ChatGPTor r-a-b r-b-d posedinSec.4.2.2,wecanalsoenrichthepromptinthesecond ChatGPTrepliesthatitcannothandlethetask.Hence,thetotal stepwithadditionalinformationonAPIcallsanddataflow: numbershowninthe“Det.”columnofTab.2variesindifferent rows. P(chain) :Iwantyoutoactasavulnerabilitydetectionsystem. OverallPerformanceComparedtoBaselines.Wecanseethat 2,aux Istheabovecodebuggy?OnlyanswerYesorNo.Hereisits usingbasicprompts(P b,P r-bandP r-r-b),ChatGPTgenerallyout- API call sequence/data flow information that you may use: performsbaselinesCFGNNandBugram,especiallyontheJava [APIdescription]/[DFdescription]. datasetwheretheaccuracyofChatGPTwithP b is58%and64% higherthanCFGNNandBugram,respectively. Finding1:Comparedtothetwovulnerabilitydetectionbase- 5 EXPERIMENTALRESULTS lines,ChatGPTshowsbetterperformanceonvulnerabilityde- Inthissection,wereportandanalyzetheexperimentalresultsin tectionw.r.t.bothaccuracyandcoverage. ordertoanswerthefollowingresearchquestions(RQ): • RQ1:CanChatGPTdetectsoftwarevulnerabilitywiththehelp ofbasicprompts? ImpactofUsingaTaskRole.Thedocumentationprovidedby • RQ2: Can API calls and data flow information enhance the OpenAI[49]forusingGPTmentionsthatthesystemmessagecan prompting? beusedtospecifythepersonausedbythemodelinitsreplies. • RQ3:Doeschain-of-thoughtpromptingaffecttheaccuracyof Weexpectthatthepromptdesignafterspecifyingthetaskroles vulnerabilitydetection? willperformbetter.AsshowninTab.2,ontheJavadataset,the • RQ4:Doestheorderofcompositionsofthepromptaffectthe accuracyofP r-bisabout5%higherthantheaccuracyofP b.Onthe detection? C/C++dataset,thereisaslightincreaseinthenumberofcorrectly • RQ5:HowdoesChatGPTperformondifferentvulnerability types? 6https://github.com/zhangj111/ConditionBugsConference’17,July2017,Washington,DC,USA ChenyuanZhang,HaoLiu,JiutianZeng,KejingYang,YuhongLi,andHuiLi