A source code vulnerability detection method based on sequence and graph dual-channel model
By adopting a dual-channel model based on sequence and graph in source code vulnerability detection, combined with BLSTM and Transformer encoder, the problem of lack of structural information in the sequence model and lack of syntax and semantic information in the graph model in the existing technology is solved, and the accuracy of vulnerability detection is improved rate and fine-grained size.
Patent Information
- Application Number
- CN202410495528.4
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- Filing Date
- 2024-04-24
- Publication Date
- 2024-11-01
- Estimated Expiration
- 2044-04-24
AI Technical Summary
In the source code vulnerability detection, the lack of source code structure information based on the sequence model and the lack of syntax and semantic information based on the graph model, resulting in low detection accuracy.
Using a dual-channel model based on sequence and graphs, program slices are generated through data preprocessing, sequence and graph features are extracted using BLSTM and Transformer encoder, and vulnerability detection is performed by combining the maximum pooling layer and classification module.
It improves the accuracy of vulnerability detection, enhances the feature extraction capability of source code, and realizes fine-grained vulnerability detection.
Smart Images

Figure CN118296612B_ABST
Abstract
Description
Technical Field
[0001] The present invention relates to the field of software source code vulnerability detection, and in particular to a source code vulnerability detection method based on a sequence and graph dual-channel model. Background Art
[0002] Traditional rule-based vulnerability detection methods usually rely on internal databases and vulnerability rules pre-established by experts. They match the entries through lexical analysis algorithms to mine vulnerabilities in the code. Therefore, they consume high labor costs and have a high false alarm rate. Vulnerability detection methods based on machine learning do not require the formulation of vulnerability rules, but usually need to extract features from the source code and input them into the machine learning model for learning and classification. This method not only has a certain dependence on domain knowledge, but also the vulnerability detection granularity is often coarse and the overall detection accuracy is not high. Deep learning models can automatically extract high-level features from structured data, thereby reducing the workload of feature extraction and freeing human experts from the arduous task of constructing manual features. At the same time, the abstract features automatically extracted by deep learning methods have better generalization capabilities than manually extracted features, so they are widely used in vulnerability detection tasks and are a new idea to solve the bottleneck problem of traditional rule-based vulnerability mining.
[0003] Vulnerability detection based on deep learning is divided into sequence-based vulnerability detection and graph-based vulnerability detection according to the way it extracts source code features. Recurrent Neural Network (RNN) has excellent processing capabilities for time series data, and source code as text is also a kind of time series data. Therefore, in recent years, a large number of studies have applied various variants of RNN to sequence-based vulnerability detection. For example, the bidirectional long short-term memory network BLSTM and the bidirectional gated recurrent unit BGRU can achieve good vulnerability detection results because they can alleviate the problem of gradient vanishing through the gating mechanism and capture the long-term dependencies of the source code context through a bidirectional network form. Li et al. (Li Z, Zou D, Xu S, et al. VulDeePecker: A DeepLearning-Based System for Vulnerability Detection[C]. 2018.) and Zou et al. (Zou D, Wang S, XuS, et al. µVulDeePecker: A Deep Learning-Based System for Multiclass Vulnerability Detection[J], 2019) extracted source code into code gadgets. These code gadgets depend on control relations or data relations. In order to reduce the size of the code vocabulary, user-defined variable and function names are mapped to symbol names to generate standardized code snippets, reducing the noise of the model. These code snippets are ultimately represented as a series of tokens. The token here can be a whole line of code or a divided coding unit. Finally, these token sequences are used to extract source code features. These two methods extract the grammatical and semantic features of the source code more comprehensively, but the extraction of source code structural features is insufficient.The method FUNDED (H. Wang, G. Ye, Z. Tang et al., “Combining graph-based learningwithautomated data collection for code vulnerability detection,” IEEE Transactions on Information Forensics and Security, vol. 16, pp. 1943–1958, 2021) proposed an augmented AST, adding eight additional types of edges based on AST, including control flow, Jump, ComputedFrom, GuardedBy, NextToken, LsatUse, and LastLexicalUse. The method VulSPG (W. Zheng, Y. Jiang, and X. Su, “Vulspg: Vulnerability Detection Basedon Slice PropertyGraph Representation Learning,” in Proceedings of the 2021 IEEE 32ndInternational Symposium on SoftwareReliability Engineering (ISSRE), Wuhan, China, October 2021) defines a new slice property graph (SPG) to alleviate the redundancy problem of a large number of structures irrelevant to the vulnerability in CPG, and extracts SPG through the standard program slicing technology of predefined SyVCs. Both methods are based on graph-based vulnerability detection. Representing the source code as a graph structure greatly improves the ability to extract source code structure features, but the extraction of grammatical and semantic features is insufficient. Patent CN201910447971 proposes to use deep learning technology to learn vulnerability features, avoiding the manual definition of vulnerability features and improving the efficiency of vulnerability detection. However, the above method uses the Skip-Gram model in Word2Vec in the word vector generation stage. This model cannot encode the contextual relationship in the text and can only encode a single word. Therefore, when learning the entire code block, the context dependency is not fully learned, resulting in low detection accuracy of the trained model. Patent CN2022105191584 proposes to use BGRU and CNN dual network models to detect multiple types of vulnerabilities in a fine-grained manner, which improves the detection accuracy. However, both models consider the extraction of grammatical and semantic information of the code, and lack the extraction of structural relationship features between code statements.Patent CN202110770650 proposes to use BERT and BLSTM models to detect vulnerabilities in source code, but this method only considers vulnerabilities caused by single syntax calls to library / API functions. Patent CN111259394A discloses a fine-grained source code vulnerability detection method based on graph neural networks, which uses a graph attention network to extract code features, processes all statements to obtain the final data set, and the effect on the test set determines the final model.
[0004] In general, the above methods are mostly based on sequence or Figure 1 This feature extraction method is used to detect vulnerabilities, but its feature extraction capability for source code is limited. Summary of the invention
[0005] The present invention proposes a source code vulnerability detection method based on a sequence and graph dual-channel model, the goal of which is to achieve fine-grained vulnerability detection of source code while ensuring the comprehensive performance of the vulnerability detection model.
[0006] The technical solution adopted by the present invention is:
[0007] A source code vulnerability detection method based on a sequence and graph dual-channel model mainly includes the following steps:
[0008] Step A: includes data preprocessing and generating program slices;
[0009] Data preprocessing: Split the MSR dataset into a sub-dataset containing only C language. Then, rename the func_before column to func, rename the vul column to target, delete the lang column, and save the processed data in JSON format.
[0010] Generate program slices: Based on the sub-datasets, use the open source static analysis tool Joern to generate the program dependency graph PDG, Program Dependence Graph, and abstract syntax tree AST, Abstract SyntaxTree corresponding to the source code; PDG contains the control dependency graph CDG, ControlDependence Graph and data dependency graph DDG, DataDependence Graph between codes, and AST contains the syntax information between program statements; slice the code based on the control dependency information and data dependency information in CDG and DDG and the vulnerability rules, and finally obtain the desired program slices and store them in the Neo4j graph database; the vulnerability rules include API / library function call FC, array use AU, pointer use PU, and arithmetic expression AE.
[0011] Step B: Sequence-based source code feature vector representation. First, the PDG nodes generated in step A are represented by vectors. Each statement, that is, each line of code, is converted into a sub-token sequence, that is, some sequence tokens are further divided into sub-tokens. Then, the Glove tool is used to vectorize the single sub-token sequence, and the BLSTM neural network is used to extract the long-distance dependencies of the entire source code sequence, and finally a sequence-based feature vector representation is obtained.
[0012] Step C: Based on the source code feature vector representation of the graph, the PDG generated in step A is decomposed into unbounded subgraphs based on the intimacy sampling matrix to obtain the central node, and then the top-k relationship value method is used to calculate the top k nodes with the largest relationship value as the adjacent points; the sampled subgraph is embedded in four parts of the node feature sequence, namely the original node feature embedding representation, the Weisfeiler-Lehman position embedding representation, the relative position embedding representation based on the intimacy relationship, and the relative distance embedding representation based on the hop. Finally, these four embedding representations are aggregated and sent to the Transformer encoder to gradually update the node representation, and finally a graph-based feature vector representation is obtained.
[0013] Step D: Fusion module: The feature vectors generated in step B and step C are connected together through a fully connected layer, and the fused result is input into the maximum pooling layer and then into the classification module.
[0014] Step E: Classification detection module. The classification module includes a linear calculation layer and a Softmax layer. The last layer uses Softmax to output the result of binary classification: an output of 0 means that the target program has no vulnerability, and an output of 1 means that the target program has a vulnerability.
[0015] Step B further comprises:
[0016] In the sub-token sequence sub-token, only variable names, function names, and class names are saved; the sequence token will extract sub-tokens according to the uppercase and lowercase naming method or the Hungarian notation, and delete single-character sub-tokens.
[0017] Step C further comprises:
[0018] C1: First, the PDG graph generated in step A is subgraph sampled. Specifically, the original PDG is decomposed into unbounded subgraphs based on the intimacy sampling matrix. Each subgraph contains a central node and a fixed number of neighbor nodes. The neighbor nodes represent the context information of the central node. After the central node is obtained, the top-k relationship value method is used to calculate the degree of association with other nodes. The first k nodes with the largest relationship value are used as adjacent points; the nodes after sampling are unordered, and the neighbor nodes are selected by sorting them according to the intimacy score with the target node.
[0019] C2: After obtaining the sampled subgraph, the node input feature is embedded. The input node feature vector includes four parts: ① The original node feature vector is embedded: a mapping operation is used to embed the node, that is, the fully connected layer conversion; ② The position embedding of the Weisfeiler-Lehman algorithm: each sampled subgraph is reassigned a label number through the algorithm, and the subgraphs with the same label sequence are isomorphic graphs, which are removed; ③ Relative position embedding based on intimacy: The local information in the subgraph is extracted in the order of the serialized list based on the intimacy score for relative position embedding; ④ Relative distance embedding based on hop: Embedding is performed according to the distance between two nodes in the subgraph in the original graph;
[0020] C3: After the node input features are embedded, the four embedded representations are aggregated as the input of the Transformer encoder, and then the node representation is gradually updated through multi-layer Transformer encoding operations; and an additional mask matrix is added to learn the contextual information of the subgraph; the output vector of the encoder is used as the feature representation of the learned graph.
[0021] The present invention introduces a dual-channel feature extraction model based on sequence and graph to characterize the feature vector of the source code, effectively solving the problem that the traditional sequence-based model lacks source code structure information and the graph-based model lacks source code syntax and semantic information. In addition, by designing a fusion model, the accuracy of vulnerability detection is improved. BRIEF DESCRIPTION OF THE DRAWINGS
[0022] Figure 1 It is a schematic diagram of the framework of the present invention;
[0023] Figure 2 It is a sequence-based vulnerability detection model of the present invention;
[0024] Figure 3 This is a graph-based vulnerability detection model of the present invention. DETAILED DESCRIPTION
[0025] The implementation steps and experimental verification of the method will be described in detail below based on the accompanying drawings of the present invention.
[0026] Reference Figure 1-Figure 3,A dual-channel source code vulnerability detection method based on sequence and graph, named VulD-SG, mainly includes the following steps:
[0027] Step A: includes data preprocessing and generating program slices;
[0028] Data preprocessing: It splits the MSR dataset into a sub-dataset containing only C language. Then, it renames the "func_before" column to "func", the "vul" column to "target", and deletes the "lang" column. Then, it saves the processed data in JSON format.
[0029] Generate program slices: Based on the sub-datasets, the open source static analysis tool Joern is used to generate the program dependency graph PDG (Program Dependence Grap) and abstract syntax tree AST (Abstract SyntaxTree) corresponding to the source code; PDG contains the control dependency graph CDG (Control Dependence Graph) and data dependency graph DDG (Data Dependence Graph) between codes, and AST contains the syntax information between program statements; based on the control dependency information and data dependency information in CDG and DDG and the vulnerability rules, the code is sliced to finally obtain the desired program slices and store them in the Neo4j graph database; the vulnerability rules include API / library function call FC, array use AU, pointer use PU, and arithmetic expression AE.
[0030] Step B: Sequence-based source code feature vector representation. First, the PDG nodes generated in step A are represented by vectors. Each statement, that is, each line of code, is converted into a sub-token sequence, that is, some sequence tokens are further divided into sub-tokens. Then, the Glove tool is used to vectorize a single sub-token, and the BLSTM neural network is used to extract the long-distance dependencies of the entire source code sequence, and finally a sequence-based feature vector representation is obtained.
[0031] Step C: Based on the source code feature vector representation of the graph, the PDG generated in step A is decomposed into unbounded subgraphs based on the intimacy sampling matrix to obtain the central node, and then the top-k relationship value method is used to calculate the top k nodes with the largest relationship value as the adjacent points; the sampled subgraph is embedded in four parts of the node feature sequence, namely the original node feature embedding representation, the Weisfeiler-Lehman position embedding representation, the relative position embedding representation based on the intimacy relationship, and the relative distance embedding representation based on the hop. Finally, these four embedding representations are aggregated and sent to the Transformer encoder to gradually update the node representation, and finally a graph-based feature vector representation is obtained.
[0032] Step D: Fusion module: The feature vectors generated in step B and step C are connected together through a fully connected layer, and the fused result is input into the maximum pooling layer and then into the classification module.
[0033] Step E: Classification detection module. The classification module includes a linear calculation layer and a Softmax layer. The last layer uses Softmax to output the result of binary classification: an output of 0 means that the target program has no vulnerability, and an output of 1 means that the target program has a vulnerability.
[0034] Wherein, step B further comprises:
[0035] In the sub-token sequence, only variable names, function names, and class names are saved; tokens are extracted into sub-tokens according to the uppercase and lowercase notation or the Hungarian notation, and single-character sub-tokens are deleted.
[0036] The sub-token sequence extraction method shortens the size of the vocabulary when embedding word vectors and reduces the computational overhead. At the same time, compared with Word2Vec, Glove can focus on the global word co-occurrence information and better capture the semantic relationship between words.
[0037] Step C further comprises:
[0038] C1: First, the PDG graph generated in step A is subgraph sampled. Specifically, the original PDG is decomposed into unbounded subgraphs based on the intimacy sampling matrix. Each subgraph contains a central node and a fixed number of neighbor nodes. The neighbor nodes represent the context information of the central node. After the central node is obtained, the top-k relationship value method is used to calculate the degree of association with other nodes. The first k nodes with the largest relationship value are used as adjacent points; the nodes after sampling are unordered, and the neighbor nodes are selected by sorting them according to the intimacy score with the target node.
[0039] C2: After obtaining the sampled subgraph, the node input features are embedded and represented. The input node feature vector includes four parts: ① Embedding of the original node feature vector: Use a mapping operation to embed the node, that is, the fully connected layer conversion; ② Position embedding of the Weisfeiler-Lehman algorithm: This step mainly embeds the global node information. Each sampled subgraph is reassigned a label number through the algorithm. Subgraphs with the same label sequence are isomorphic graphs and are removed; ③ Relative position embedding based on intimacy: Extract local information in the subgraph in the order of the serialized list based on the intimacy score for relative position embedding. This step obtains local node information embedding; ④ Relative distance embedding based on hop: Embedding is performed according to the distance between two nodes in the subgraph in the original graph.
[0040] C3: After the node input features are embedded, the four embedded representations are aggregated as the input of the Transformer encoder, and then the node representation is gradually updated through multi-layer Transformer encoding operations; and an additional mask matrix is added to learn the contextual information of the subgraph; the output vector of the encoder is used as the feature representation of the learned graph.
[0041] The verification results of VulD-SG of the present invention are shown in Tables 1 and 2. Table 1 is the experimental results of the detection performance comparison between VulD-SG of the present invention and other vulnerability detection methods; Table 2 is the sequence-based and graph-based ablation experiments.
[0042] Refer to Table 1. The experimental data set is the MSR data set. Various types of vulnerabilities based on C language are collected in the data set. The target is marked as 0 as a negative sample, indicating that there is no vulnerability, and the target is marked as 1 as a positive sample, indicating that there is a vulnerability. The vulnerability training data set is constructed with functions as the basic unit. The traditional vulnerability detection tool Flawfinder method and the deep learning-based VulDeePecker, SySeVR, Reveal method and VulD-SG are selected for comparative experiments. The data set is divided into training set, validation set and test set in a ratio of 8:1:1 and sample balancing is performed. The table shows the comparative experimental results of the VulD-SG method and other methods. From the results, VulD-SG is 25.7% and 28.9% higher than the graph-based vulnerability detection method Reveal and the sequence-based vulnerability detection method SySeVR in average F1 index, and 26.2% and 29.5% higher in average ACC index, respectively.
[0043] Table 1
[0044]
[0045] Refer to Table 2. In order to prove the effectiveness of BLSTM and sampling subgraph for VulD-SG of the present invention, the present invention designs to use sequence channel (BLSTM) alone, graph channel (sampling subgraph) alone, and two channels based on graph and sequence (BLSTM+GNN). Three groups of experiments were conducted with the original VulD-SG under the MSR vulnerability dataset, and the comprehensive detection performance of each model was evaluated using the test set precision P, accuracy Acc, and weighted F1 value as indicators. VulD-SG has an F1 value that is 22% and 11.1% higher than that of using sequence channel (BLSTM) alone and graph channel (sampling subgraph) alone, respectively, and an F1 value that is 8.1% higher than that of using dual channels (BLSTM+GNN). In general, VulD-SG uses sequence-based (BLSTM) and graph-based (sampling subgraph) to provide rich features for the model. After the model is fused, the key features are assigned higher weights by adding the attention mechanism, which improves the detection model's ability to identify different types of vulnerabilities. The dual-channel method significantly improves all indicators compared to the sequence-based and graph-based methods alone.
[0046] Table 2
[0047]
Claims
1. A source code vulnerability detection method based on sequence and graph dual-channel model, It is characterized in that The main steps include: Step A: includes data preprocessing and generating program slices; Data preprocessing: Split the MSR dataset into a sub-dataset containing only C language. Then, rename the func_before column to func, rename the vul column to target, delete the lang column, and save the processed data in JSON format. Generate program slices: Based on the sub-datasets, use the open source static analysis tool Joern to generate the program dependency graph PDG and abstract syntax tree AST corresponding to the source code, including the control dependency graph CDG and data dependency graph DDG between codes. AST contains the syntax information between program statements. Slice the code based on the control dependency information and data dependency information in CDG and DDG and the vulnerability rules, and finally obtain the desired program slices and store them in the Neo4j graph database. The vulnerability rules include API / library function call FC, array use AU, pointer use PU, and arithmetic expression AE. Step B: Sequence-based source code feature vector representation. First, the PDG nodes generated in step A are represented by vectors. Each statement, that is, each line of code, is converted into a sub-token sequence, that is, some sequence tokens are further divided into sub-tokens. Then, the Glove tool is used to vectorize a single sub-token sequence, and the BLSTM neural network is used to extract the long-distance dependency of the entire source code sequence, and finally a sequence-based feature vector representation is obtained. Step C: Based on the source code feature vector representation of the graph, the PDG generated in step A is decomposed into boundless subgraphs based on the intimacy sampling matrix to obtain the central node, and then the top-k relationship value method is used to calculate the top k nodes with the largest relationship value as the adjacent points; the sampled subgraph is embedded in four parts of the node feature sequence, namely the original node feature embedding representation, the Weisfeiler-Lehman position embedding representation, the relative position embedding representation based on the intimacy relationship, and the relative distance embedding representation based on the hop. Finally, these four embedding representations are aggregated and sent to the Transformer encoder to gradually update the node representation, and finally a feature vector representation based on the graph is obtained; Step D: Fusion module: The feature vectors generated in step B and step C are fused together through a fully connected layer to form a new feature vector, and the fused new feature vector is input into the maximum pooling layer and then into the classification detection module; Step E: Classification detection module: The classification detection module includes a linear calculation layer and a Softmax layer. The last layer of the module is the Softmax layer, which is responsible for outputting the results of the two classifications: an output of 0 means that the target program has no vulnerabilities, and an output of 1 means that the target program has vulnerabilities.
2. According to claim 1, a source code vulnerability detection method based on a sequence and graph dual-channel model, It is characterized in that Step B further comprises: In the sub-token sequence sub-token, only variable names, function names, and class names are saved; the sequence token will extract sub-tokens according to the uppercase and lowercase naming method or the Hungarian notation, and delete single-character sub-tokens.
3. According to claim 1, a source code vulnerability detection method based on a sequence and graph dual-channel model, It is characterized in that Step C further comprises: C1: First, the PDG graph generated in step A is subgraph sampled. Specifically, the original PDG is decomposed into edgeless subgraphs based on the intimacy sampling matrix. Each subgraph contains a central node and a fixed number of neighbor nodes. The neighbor nodes represent the context information of the central node. After the central node is obtained, the top-k relationship value method is used to calculate the degree of association with other nodes. The first k nodes with the largest relationship value are used as neighboring points. The nodes after sampling are unordered, and the neighbor nodes are selected by sorting them according to the intimacy score with the target node. C2: After obtaining the sampled subgraph, the node input feature is embedded. The input node feature vector includes four parts: ① The original node feature vector is embedded: a mapping operation is used to embed the node, that is, the fully connected layer conversion; ② The position embedding of the Weisfeiler-Lehman algorithm: each sampled subgraph is reassigned a label number through the algorithm, and the subgraphs with the same label sequence are isomorphic graphs, which are removed; ③ Relative position embedding based on intimacy: The local information in the subgraph is extracted in the order of the serialized list based on the intimacy score for relative position embedding; ④ Relative distance embedding based on hop: Embedding is performed according to the distance between two nodes in the subgraph in the original graph; C3: After the node input features are embedded, the four embedded representations are aggregated as the input of the Transformer encoder, and then the node representation is gradually updated through multi-layer Transformer encoding operations; and an additional mask matrix is added to learn the contextual information of the subgraph; the output vector of the encoder is used as the feature representation of the learned graph.
