Source code vulnerability detection and positioning method and device, equipment and storage medium

By generating program dependency graphs and code attribute graphs, and combining deep learning models to perform slice analysis on the source code, the problem of high false positive and false negative rates in vulnerability detection in the existing technology is solved, and vulnerability location and efficiency at the code line level are achieved. bug fixes.

CN118709191AInactive Publication Date: 2024-09-27LANG CHAO ZHI HUI KE JI (WU HAN) YOU XIAN GONG SI +1

Patent Information

Application Number
CN202410812344.6
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2024-06-21
Publication Date
2024-09-27
Estimated Expiration
Not applicable · inactive patent

AI Technical Summary

Technical Problem

Existing technologies have high false positive and false negative rates in source code vulnerability detection, and it is difficult for deep learning-based methods to accurately locate specific vulnerability statements and capture long-range dependencies.

Method used

By obtaining the source code files and diff files for training, the program dependency graph and code attribute graph are generated, and the diff files are used to identify vulnerability-sensitive nodes for code slicing. The deep learning model is used to vectorize and analyze the sliced ​​subgraphs to accurately locate vulnerabilities. Location.

Benefits of technology

It significantly improves the accuracy of vulnerability detection, reduces false positives, realizes vulnerability location at the code line level, and improves vulnerability repair efficiency.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN118709191A
    Figure CN118709191A
Patent Text Reader

Abstract

The invention belongs to the technical field of code vulnerability detection, and particularly provides a source code vulnerability detection and positioning method and device, equipment and a storage medium, and the method comprises the steps: obtaining a source code file for training and a diff file containing code modification; segmenting the source code into function generation program dependency graphs and code attribute graphs according to functions; identifying vulnerability sensitive nodes by combining a diff file analysis program dependency graph, performing code slicing, and generating a slice sub-graph of a code attribute graph; performing vectorization processing on nodes in each slice sub-graph, and inputting the processed nodes into a deep learning model for training evaluation to obtain a trained deep learning model; and extracting a program dependency graph from a to-be-detected source code file, generating slice sub-graphs, performing vectorization processing on nodes of each slice sub-graph, inputting the processed nodes into the trained deep learning model for analysis, and detecting vulnerabilities contained in each slice and specific positions of the vulnerabilities. And the vulnerability detection accuracy is improved.
Need to check novelty before this filing date? Find Prior Art

Description

Background Art

[0002] In the process of software development, the security of source code is crucial. However, with the increasing complexity of code and the need for rapid iteration, the problem of vulnerabilities in source code is becoming increasingly prominent.

[0003] Traditional source code vulnerability detection methods, such as static code analysis and dynamic code analysis, can help developers identify potential vulnerabilities to a certain extent, but they still have some limitations. Static code analysis is time-consuming, labor-intensive and error-prone when dealing with complex vulnerability patterns. As the scale of software grows, vulnerability patterns become more and more complex, resulting in high false positive and false negative rates. Dynamic code analysis requires a large number of test cases to cover all possible execution paths, which is often difficult to achieve in reality.

[0004] In recent years, deep learning technology has achieved remarkable results in image processing, natural language processing and other fields, and has gradually been introduced into source code vulnerability detection. However, due to the complexity and structure of source code, although learning-based vulnerability detection methods have improved the adaptability and generalization of detection, most of them are performed at a high granularity, unable to accurately locate the specific statements that cause the vulnerability, and have limitations in capturing long-range dependencies. Summary of the invention

[0005] In a first aspect, the technical solution of the present invention provides a method for detecting and locating a source code vulnerability, comprising the following steps: Get the source code file for training and the diff file containing the code modifications; Split the source code into functions and generate a program dependency graph and code property graph for each function; Combine the diff file to analyze the program dependency graph to identify vulnerability-sensitive nodes and use the vulnerability-sensitive nodes as a basis for code slicing to generate a slice subgraph of the code property graph; After vectorizing the nodes in each slice subgraph, the nodes are input into the deep learning model for training and evaluation to obtain a trained deep learning model. The program dependency graph is extracted from the source code file to be tested to generate related slice subgraphs. The nodes of each slice subgraph are vectorized and input into the trained deep learning model for analysis to detect the vulnerabilities contained in each slice and the specific locations of the vulnerabilities.

[0006] As a further limitation of the technical solution of the present invention, the steps of dividing the source code by function and generating a program dependency graph and a code attribute graph for each function include: Split the source code into functions; Extract the control dependency and data dependency of each function to generate a program dependency graph for each function, and represent the source code function as a code attribute graph; Among them, each node in the program dependency graph represents a source code statement or control predicate, and the directed edges represent the dependency relationship between nodes. Each node is also associated with detailed information on its source code and statement type, and the nodes are identified by the line number in the source code.

[0007] As a further limitation of the technical solution of the present invention, after the step of obtaining the source code file for training and the diff file containing the code modification, the following step is further included: Extract vulnerability sensitive elements based on diff files, including system calls, arithmetic expressions, pointer usage, array usage and sensitive keywords.

[0008] As a further limitation of the technical solution of the present invention, the steps of analyzing the program dependency graph in combination with the diff file to identify vulnerability-sensitive nodes and using the vulnerability-sensitive nodes as a basis for code slicing to generate a slice subgraph of the code attribute graph include: Parse the program dependency graph to identify vulnerability-sensitive nodes containing sensitive elements; Use vulnerability-sensitive nodes as the basis for code slicing and generate slice subgraphs of the code property graph.

[0009] As a further limitation of the technical solution of the present invention, the step of parsing the program dependency graph to identify vulnerability sensitive nodes containing sensitive elements includes: In the program dependency graph, the nodes containing vulnerability-sensitive elements are used as the slicing criteria, and the breadth-first search algorithm is used to perform backward slicing and forward slicing; By combining forward and backward slicing, vulnerability-sensitive nodes containing vulnerability-sensitive elements are identified; Among them, backward slicing traverses all nodes and codes that affect vulnerability-sensitive elements and identifies the statements that trigger the vulnerability; forward slicing traverses all statements affected by vulnerability-sensitive elements.

[0010] As a further limitation of the technical solution of the present invention, the node of the code attribute graph includes a label of the node type and a source code text corresponding to the node; The steps of vectorizing the nodes in each slice subgraph and inputting them into the deep learning model for training and evaluation to obtain the trained deep learning model include: The source code of each slice subgraph node is converted into vector form through the Doc2Vec model, and combined with the node type label to form the initial vector representation of the node; The slice subgraph is converted into a node feature matrix and an edge adjacency matrix and input into the deep learning model for training and evaluation to obtain a trained deep learning model; the dimension of the feature matrix is ​​m×n, where m represents the number of nodes and n represents the dimension of the embedding vector.

[0011] As a further limitation of the technical solution of the present invention, the steps of converting the source code of each slice subgraph node into a vector form through the Doc2Vec model and combining the node type label to form an initial vector representation of the node include: Convert the labels of N different node types into N-dimensional node label vectors through one-hot encoding; Split user-defined function names and variable names into multiple subwords and use the BPE algorithm to compress the vocabulary; Use the Doc2Vec model to embed the token sequence of the code into vectors; By concatenating the node label vector and the source code embedding vector, the initial vector representation of each node is obtained.

[0012] In a second aspect, the technical solution of the present invention further provides a source code vulnerability detection and positioning device, including a file receiving module, a source code segmentation processing module, a slice subgraph generation module, a model training module and a code vulnerability detection module; A file receiving module is used to obtain source code files for training and diff files containing code modifications; The source code segmentation processing module is used to segment the source code by function and generate a program dependency graph and a code attribute graph for each function; Slice subgraph generation module, used to analyze the program dependency graph in combination with the diff file to identify vulnerability-sensitive nodes and use the vulnerability-sensitive nodes as a basis for code slicing to generate a slice subgraph of the code property graph; The model training module is used to vectorize the nodes in each slice subgraph and then input them into the deep learning model for training and evaluation to obtain a trained deep learning model; The code vulnerability detection module is used to extract the program dependency graph from the source code file to be detected to generate relevant slice subgraphs, vectorize the nodes of each slice subgraph and input them into the trained deep learning model for analysis to detect the vulnerabilities contained in each slice and the specific locations of the vulnerabilities.

[0013] As a further limitation of the technical solution of the present invention, the source code segmentation processing module includes a code segmentation unit and a processing unit; Code segmentation unit, used to segment source code by function; A processing unit, configured to extract control dependency and data dependency of each function to generate a program dependency graph for each function, and to represent the source code function as a code attribute graph; Among them, each node in the program dependency graph represents a source code statement or control predicate, and the directed edges represent the dependency relationship between nodes. Each node is also associated with detailed information on its source code and statement type, and the nodes are identified by the line number in the source code.

[0014] As a further limitation of the technical solution of the present invention, the device also includes a diff file processing module for extracting vulnerability sensitive elements based on the diff file, and the vulnerability sensitive elements include system calls, arithmetic expressions, pointer usage, array usage and sensitive keywords.

[0015] As a further limitation of the technical solution of the present invention, the slice subgraph generation module includes a parsing and recognition unit and a code slicing unit; A parsing and identification unit is used to parse the program dependency graph and identify vulnerability-sensitive nodes containing sensitive elements; The code slicing unit is used to perform code slicing based on vulnerability-sensitive nodes and generate a slice subgraph of the code property graph.

[0016] As a further limitation of the technical solution of the present invention, the parsing and identifying unit is specifically used to perform backward slicing and forward slicing in the program dependency graph using the nodes containing vulnerability sensitive elements as the slicing criteria, and adopting the breadth-first search algorithm; by combining the forward and backward slicing, the vulnerability sensitive nodes containing the vulnerability sensitive elements are identified; Among them, backward slicing traverses all nodes and codes that affect vulnerability-sensitive elements and identifies the statements that trigger the vulnerability; forward slicing traverses all statements affected by vulnerability-sensitive elements.

[0017] As a further limitation of the technical solution of the present invention, the node of the code attribute graph includes a label of the node type and a source code text corresponding to the node; The model training module includes an initial vector generation unit and a training execution unit; The initial vector generation unit is used to convert the source code of each slice subgraph node into a vector form through the Doc2Vec model, and combine it with the node type label to form the initial vector representation of the node; The training execution unit is used to convert the slice subgraph into a node feature matrix and an edge adjacency matrix and input them into the deep learning model for training and evaluation to obtain a trained deep learning model; the dimension of the feature matrix is ​​m×n, where m represents the number of nodes and n represents the dimension of the embedding vector.

[0018] As a further limitation of the technical solution of the present invention, the initial vector generation unit is specifically used to convert labels of N different node types into N-dimensional node label vectors through one-hot encoding; split user-defined function names and variable names into multiple sub-words and compress the vocabulary using the BPE algorithm; use the Doc2Vec model to vector embed the token sequence of the code; and obtain the initial vector representation of each node by concatenating the node label vector and the source code embedding vector.

[0019] In a third aspect, the technical solution of the present invention provides an electronic device, comprising: at least one processor; and a memory communicatively connected to the at least one processor; the memory stores computer program instructions executable by the at least one processor, and the computer program instructions are executed by the at least one processor so that the at least one processor can execute the source code vulnerability detection and location method as described in the first aspect.

[0020] In a fourth aspect, the technical solution of the present invention further provides a non-transitory computer-readable storage medium, wherein the non-transitory computer-readable storage medium stores computer instructions, and the computer instructions enable the computer to execute the source code vulnerability detection and location method as described in the first aspect.

[0021] It can be seen from the above technical solutions that the present invention has the following advantages: By combining the program dependency graph and code attribute graph of the source code, as well as the code modification information in the diff file, key program slices are extracted, significantly enhancing the accuracy of vulnerability detection. This helps reduce the false positive problem in traditional static code analysis and improves the accuracy of vulnerability detection. Multi-task learning is implemented to accurately detect and locate vulnerabilities at the code line level. Using deep learning and program dependency graphs, This method uses a deep learning model to analyze the nodes in the slice subgraph, which can quickly detect the vulnerabilities contained in the slice and accurately locate the specific location of the vulnerability. This greatly improves the efficiency of vulnerability repair and reduces the workload of developers.

[0022] In addition, the invention has a reliable design principle, a simple structure and a very broad application prospect.

[0023] It can be seen that compared with the prior art, the present invention has outstanding substantive features and significant progress, and the beneficial effects of its implementation are also obvious. BRIEF DESCRIPTION OF THE DRAWINGS

[0024] In order to more clearly illustrate the embodiments of the present invention or the technical solutions in the prior art, the drawings required for use in the embodiments or the description of the prior art will be briefly introduced below. Obviously, for ordinary technicians in this field, other drawings can be obtained based on these drawings without paying any creative work.

[0025] Figure 1 is a schematic flow chart of a method according to an embodiment of the present invention.

[0026] Figure 2 It is an overall framework diagram provided by an embodiment of the present invention.

[0027] Figure 3 It is a diagram of a vulnerability detection model provided by an embodiment of the present invention.

[0028] Figure 4 is a schematic block diagram of an apparatus according to an embodiment of the present invention. Figure 5 The figure is a schematic block diagram of a source code vulnerability detection and location device according to an embodiment of the present invention. DETAILED DESCRIPTION

[0029] In order to enable those skilled in the art to better understand the technical solutions in the present invention, the technical solutions in the embodiments of the present invention will be clearly and completely described below in conjunction with the drawings in the embodiments of the present invention. Obviously, the described embodiments are only part of the embodiments of the present invention, not all of the embodiments. Based on the embodiments of the present invention, all other embodiments obtained by ordinary technicians in this field without creative work should fall within the scope of protection of the present invention.

[0030] like Figure 1 and Figure 2 As shown, an embodiment of the present invention provides a source code vulnerability detection and location method, comprising the following steps: Step 1: Get the source code file for training and the diff file containing the code modifications; Step 2: Split the source code into functions and generate a program dependency graph and code attribute graph for each function; Step 3: Analyze the program dependency graph with the diff file to identify vulnerability-sensitive nodes and use the vulnerability-sensitive nodes as the basis for code slicing to generate a slice subgraph of the code property graph; Step 4: After vectorizing the nodes in each slice subgraph, input them into the deep learning model for training and evaluation to obtain a trained deep learning model; The parameters of a model usually refer to the weights and biases within the model, which are variables that the model needs to learn during the learning process. The training data set is used for training, and the validation data set is used for validation. The model is validated using various validation indicators, including accuracy, precision, recall, and F1 indicators.

[0031] Step 5: Extract the program dependency graph from the source code file to be tested to generate relevant slice subgraphs. After vectorizing the nodes of each slice subgraph, input them into the trained deep learning model for analysis to detect the vulnerabilities contained in each slice and the specific locations of the vulnerabilities.

[0032] The trained deep learning model here is an inheritance model, which models the vulnerability detection task at the vulnerability line level as a node classification task. It can be considered that each line in the code is mapped to a node in the graph to identify which nodes are vulnerability nodes.

[0033] In some embodiments, the steps of dividing the source code into functions and generating a program dependency graph and a code property graph for each function include: Step 21: Split the source code into functions; Step 22: extract the control dependency and data dependency of each function to generate a program dependency graph for each function, and represent the source code function as a code attribute graph; Among them, each node in the program dependency graph represents a source code statement or control predicate, and the directed edges represent the dependency relationship between nodes. Each node is also associated with detailed information on its source code and statement type, and the nodes are identified by the line number in the source code.

[0034] Specifically in the program slicing stage, we first build a program dependency graph for each function, which represents the control dependency and data dependency in the program. The program dependency graph is a directed graph, where each node represents a source code statement or control predicate, and the directed edges represent the dependencies between nodes. Each node is also associated with detailed information about its source code and statement type. Figure 4 Shows a program dependency graph extracted from a function, where nodes are identified by line numbers in the source code, and solid and dashed lines represent data dependencies and control dependencies, respectively. Figure 4 The example in shows how to extract slice subgraphs from program code and vectorize nodes. Since the code property graph is too complex, only the program dependency graph is used in the example. The code example in the figure shows potential integer overflow issues, such as receiving user input on line 7 and performing arithmetic operations that may cause overflow on line 11.

[0035] In the program slice generation stage, the concept of candidate regions in target detection technology is borrowed to improve the accuracy of vulnerability detection. In target detection, candidate regions refer to regions that may contain target objects identified on the input image by specific methods. Similarly, in vulnerability detection, since most statements in a program may not be related to vulnerabilities, directly classifying the entire function or file as having vulnerabilities or not is too rough. Therefore, program static slicing technology is used to generate a set of subgraphs that may contain vulnerabilities on the input program function, and these subgraphs are used as candidate regions for detecting vulnerabilities.

[0036] In the specific implementation, the source code function is first represented as a code property graph (CPG), and then a static slicing method based on the reachability of the program dependency graph (PDG) is used to remove irrelevant code and graph nodes. This method uses the program slice subgraph as the basic unit of detection, making the detection results more accurate.

[0037] In the program dependency graph of a given code function, the nodes containing vulnerability-sensitive elements are used as the slicing criteria, and the breadth-first search algorithm is used to perform backward slicing and forward slicing. Backward slicing traverses all nodes and codes that may affect vulnerability-sensitive elements and identifies statements that may cause vulnerabilities. Forward slicing traverses all statements that may be affected by vulnerability-sensitive elements. By combining forward and backward slicing, the potential impact of vulnerability-sensitive elements and the vulnerabilities they may cause can be determined.

[0038] Finally, a slice subgraph is generated for the statements containing vulnerability-sensitive elements. For example, Figure 4 The third column shows the code slice subgraph generated with the operation on line 11 as the slice criterion. In this way, the code on lines 5, 13, and 17, which have no data dependency or control dependency on line 11, can be explicitly excluded. At the same time, backward slicing shows that the variable y in line 11 originates from line 7, which is a user-controllable input. Forward slicing reveals that the variable x in line 11 may affect the printf function in line 16, which may cause a string formatting vulnerability.

[0039] It should be noted that the steps of obtaining the source code file for training and the diff file containing the code modification also include: S02: Extract vulnerability sensitive elements based on the diff file. Vulnerability sensitive elements include system calls, arithmetic expressions, pointer usage, array usage and sensitive keywords.

[0040] By analyzing the abstract syntax tree of the program, code elements containing potential vulnerabilities are identified, such as improper library function calls, pointer usage, array operations, and arithmetic operations. For example, some specific library functions such as memcpy and strcpy may cause security issues. Similarly, keywords such as buf and len identified by the diff file help the model identify possible vulnerability-related code, thereby improving the accuracy and efficiency of vulnerability detection.

[0041] In some embodiments, the steps of analyzing the program dependency graph in combination with the diff file to identify vulnerability-sensitive nodes and using the vulnerability-sensitive nodes as a basis for code slicing to generate a slice subgraph of the code property graph include: Step 31: Analyze the program dependency graph to identify vulnerability sensitive nodes containing sensitive elements; Step 32: Use vulnerability-sensitive nodes as a basis for code slicing to generate a slice subgraph of the code property graph.

[0042] The source code is split by function, and a program dependency graph and code attribute graph are generated for each function. Next, the program dependency graph is analyzed to identify nodes with potential vulnerabilities, which may involve sensitive system calls, arithmetic operations, pointer and array usage, and keywords extracted from diff files. After identification, these vulnerability-sensitive nodes are used as the basis for code slicing to generate a subgraph of the code attribute graph.

[0043] In some embodiments, the step of parsing the program dependency graph to identify vulnerability-sensitive nodes containing sensitive elements includes: In the program dependency graph, the nodes containing vulnerability-sensitive elements are used as the slicing criteria, and the breadth-first search algorithm is used to perform backward slicing and forward slicing; By combining forward and backward slicing, vulnerability-sensitive nodes containing vulnerability-sensitive elements are identified; Among them, backward slicing traverses all nodes and codes that affect vulnerability-sensitive elements and identifies the statements that trigger the vulnerability; forward slicing traverses all statements affected by vulnerability-sensitive elements.

[0044] It should be noted that the code property graph (CPG) slices need to be converted into vector form in order to be input into the neural network. The nodes of the code property graph contain the label of the node type and the source code text corresponding to the node; The steps of vectorizing the nodes in each slice subgraph and inputting them into the deep learning model for training and evaluation to obtain the trained deep learning model include: Step 41: The source code of each slice subgraph node is converted into a vector form through the Doc2Vec model, and combined with the node type label to form an initial vector representation of the node; Step 42: Convert the sliced ​​subgraph into a node feature matrix and an edge adjacency matrix and input them into the deep learning model for training and evaluation to obtain a trained deep learning model; the dimension of the feature matrix is ​​m×n, where m represents the number of nodes and n represents the dimension of the embedding vector.

[0045] The initial vectors of multiple nodes generate the feature matrix.

[0046] Specifically, the steps of converting the source code of each slice subgraph node into a vector form through the Doc2Vec model and combining the node type label to form the initial vector representation of the node include: Step 411: convert the labels of N different node types into N-dimensional node label vectors through one-hot encoding; Step 412: split the user-defined function name and variable name into multiple subwords and compress the vocabulary using the BPE algorithm; Step 413: Use the Doc2Vec model to embed the token sequence of the code into vectors; Step 414: Obtain an initial vector representation of each node by concatenating the node label vector and the source code embedding vector.

[0047] Node labels represent specific code unit types, such as arithmetic operations, functions, and parameters, and there are 54 different label types. These labels are represented by converting them into 54-dimensional vectors using one-hot encoding. For the source code text in the node, a common processing method is to treat the code as a text sentence, decompose it into a list of tokens, and use word embedding technology such as Word2Vec to generate a fixed-length vector. However, due to the different naming habits of developers, the actual variable names may be very diverse. Simply adding all possible variable names to the vocabulary may cause the vocabulary to grow infinitely, which is the so-called vocabulary explosion problem. In addition, the OOV (Out-Of-Vocabulary) problem occurs when encountering unknown vocabulary. In this case, the unknown vocabulary will be treated as unknown words, which will affect the performance and accuracy of the model.

[0048] In order to solve these problems, the present invention adopts a sub-word level representation method. According to common naming habits, user-defined function names and variable names are divided into multiple sub-words. In addition, the BPE (Byte Pair Encoding) algorithm is used to compress the vocabulary, effectively controlling the vocabulary size within 30,000. Next, the pre-trained Doc2Vec model is used to embed the token sequence of the code into vectors, and the dimension of the generated feature matrix is ​​m×n, where m represents the number of nodes and n represents the dimension of the embedding vector. According to the experimental results, the dimension n of the vector is set to 50. Finally, the initial vector representation of each node is obtained by concatenating the node label vector and the source code embedding vector.

[0049] In order to accurately capture the long- and short-range dependencies in the source code, this model uses a composite model that combines the functions of the graph neural network (GGNN) and the Transformer model.

[0050] The present invention converts the program slice subgraph into a node feature matrix and an edge adjacency matrix, and inputs them into a model that integrates GGNN and Transformer. This combination enables the model to capture both long-range and short-range dependencies, improving the accuracy of vulnerability detection. Figure 3 As shown in the figure, the model regards the vulnerability detection task as a whole-graph classification problem, extracts full-graph features for classification through the graph pooling layer, and also supports the vulnerability row location task, directly using the node feature matrix for location.

[0051] GGNN iteratively updates node features through a recurrent neural network (RNN). Each iteration includes three steps: information aggregation, conversion, and update, thereby effectively capturing the dependencies between nodes. Overall, this model achieves efficient and accurate detection of source code vulnerabilities through multi-task learning and joint loss function design.

[0052]

[0053] Specifically, for each node , as shown in formula (1), first initialize the node vector , that is, copy the node feature vector generated before and fill it with 0 to a fixed length. is the total number of layers of neighborhood aggregation, at each layer ( , all nodes communicate with their neighboring nodes through edge types and directions (determined by Neighborhood Matrix Description, the number of neighbor matrices is equal to the edge type), the neighborhood aggregation is shown in formula (2), where is a learnable weight parameter. For each type of edge, the information of the nodes adjacent to the current node is aggregated according to its adjacency matrix. Then, as shown in formula (3), GRU (Gated Recurrent Unit) is used to transform the hidden state of the previous time step into and the information of neighboring nodes to update the hidden state of the current node , where AGG is an aggregation function, and summation is used here as an aggregation function to aggregate information from different types of edge neighbor nodes. Finally, as shown in formula (4), in order to solve the over-smoothing problem caused by the increase in depth of the graph neural network, the present invention refers to the JK-Net architecture to splice the node hidden states of each layer, and obtain the final node vector representation through the linear layer. That is, GRU (gated recurrent unit) is used to update the state of the node. This update process combines the node state of the previous time step and the currently aggregated neighborhood information. In order to avoid the over-smoothing problem that occurs as the network depth increases, the strategy of the JK-Net architecture is adopted, that is, the node states of different layers are spliced, and then processed through the linear layer to form the final node representation.

[0054] In the combined use of graph neural networks and Transformer models, the processing of each node begins with initializing node vectors, which are inherited from the previous feature extraction stage and padded to a fixed length as needed. During the neighborhood aggregation process, each node exchanges information with its neighbor nodes through a specific type of edge, which depends on the neighborhood matrix and learnable weight parameters. Through multiple layers of information transfer, each node is able to aggregate neighbor information from different types of edges.

[0055] The Transformer model does not rely on edge relationships, but directly captures long-term dependencies between nodes through the self-attention mechanism. The model includes multiple layers of self-attention mechanisms, each of which consists of a multi-head self-attention sublayer and a feedforward neural network sublayer. The self-attention layer learns the relationship between nodes through position embedding and the output of the previous layer, while the feedforward network further processes this information to optimize the node representation. The model also includes residual connections and layer normalization to promote information flow between different layers and improve model performance.

[0056] Through this composite model structure, vulnerabilities in the code can be effectively processed and identified. Both global and local dependencies can be accurately captured by the model and utilized in vulnerability detection tasks.

[0057]

[0058] The Transformer model used in the present invention takes the node feature vector matrix as input, and can directly capture the long dependency relationship between nodes without the help of edge relationship. The Transformer model is composed of a multi-layer stacked self-attention mechanism layer, and the self-attention mechanism layer is composed of a multi-head self-attention sublayer and a feedforward neural network sublayer. The calculation process of the multi-head self-attention layer is shown in formula (5) to formula (7), and the calculation process of the feedforward neural network is shown in formula (8). There is also a residual connection and layer normalization operation between the two sublayers. The input of the self-attention mechanism is composed of the output and position embedding vector of the previous layer. Specifically, the multi-head self-attention sublayer is responsible for learning the input node sequence representation and learning different attention representations at different positions. The feedforward neural network sublayer is responsible for further converting the output of the multi-head self-attention sublayer to better encode the information of the input sequence. The residual connection and layer normalization operation help to better transfer information between different layers and improve the performance of the model. The final output of the Transformer is the hidden state of each node, which contains all the information in the input node and can be used for vulnerability detection and vulnerability line location tasks.

[0059] The present invention attempts two different strategies for integrating GGNN and Transformer models. The first strategy is to adopt a voting mechanism, independently train the GGNN and Transformer models, and perform weighted average of their outputs, with the weights all set to 0.5. The second strategy is to adopt a stacking structure and stack the layers in the order of Transformer, GGNN, and Transformer. The experimental results show that the performance of the stacking method is slightly better than the voting method, so the stacking structure is selected as the final vulnerability detection model structure. Such a structure can more effectively integrate the advantages of the two models and improve the accuracy and efficiency of vulnerability detection.

[0060]

[0061] The present invention proposes a multi-task model that can simultaneously perform slice-level vulnerability detection and vulnerability line location tasks. For these two tasks, the present invention adopts the cross entropy loss function. Since the difference between vulnerability code and security code is usually small, the present invention introduces a contrast loss function to maximize the distance between vulnerability samples and non-vulnerability samples. During training, it shortens the similarity between positive samples and negative samples as much as possible, and at the same time shortens the similarity between positive samples and all negative samples as much as possible to enhance the classifier's ability to distinguish. The loss function design is shown in formulas (10)-(13). Where is the loss function for the vulnerability detection task, is the loss function for the vulnerability location task. Due to data imbalance in the real world, we use , The corresponding weighted is the contrast loss function. For a given sample, the samples with the same label in the same batch are It is considered as a positive example, and its label is different from The purpose of this contrastive loss function is to map samples of the same category to similar embedding spaces and samples of different categories to different embedding spaces. The final joint loss function is It is the weighted sum of these three loss functions.

[0062] The present invention relates to a multi-task model for simultaneously performing vulnerability detection of code slices and locating specific vulnerable lines. The model combines graph neural networks and self-attention mechanisms for feature extraction, and uses different mechanisms to handle the two tasks: for vulnerability detection, global attention pooling is used to classify the entire code graph; for vulnerability line location, a multi-layer perceptron is used to classify node features. In addition, the model solves the inconsistency of slice and statement level results by element-wise multiplication. In order to improve the model's distinguishing ability, a contrastive loss function is introduced to amplify the difference between vulnerability and non-vulnerability samples, and a cross-entropy loss function is used to handle unbalanced data. Finally, the model optimizes training through a joint loss function that combines the losses of vulnerability detection and location tasks, as well as contrastive loss.

[0063] like Figure 5 As shown, an embodiment of the present invention further provides a source code vulnerability detection and positioning device, including a file receiving module, a source code segmentation processing module, a slice subgraph generation module, a model training module and a code vulnerability detection module; A file receiving module is used to obtain source code files for training and diff files containing code modifications; The source code segmentation processing module is used to segment the source code by function and generate a program dependency graph and a code attribute graph for each function; The slicing subgraph generation module is used to analyze the program dependency graph in combination with the diff file to identify vulnerability-sensitive nodes and use the vulnerability-sensitive nodes as the basis for code slicing to generate a slicing subgraph of the code attribute graph; The model training module is used to vectorize the nodes in each slice subgraph and then input them into the deep learning model for training and evaluation to obtain a trained deep learning model; The code vulnerability detection module is used to extract the program dependency graph from the source code file to be detected to generate relevant slice subgraphs, vectorize the nodes of each slice subgraph and input them into the trained deep learning model for analysis to detect the vulnerabilities contained in each slice and the specific locations of the vulnerabilities.

[0064] In some embodiments, the source code segmentation processing module includes a code segmentation unit and a processing unit; Code segmentation unit, used to segment source code by function; A processing unit, configured to extract control dependency and data dependency of each function to generate a program dependency graph for each function, and to represent the source code function as a code attribute graph; Among them, each node in the program dependency graph represents a source code statement or control predicate, and the directed edges represent the dependency relationship between nodes. Each node is also associated with detailed information on its source code and statement type, and the nodes are identified by the line number in the source code.

[0065] In some embodiments, the device also includes a diff file processing module for extracting vulnerability sensitive elements based on the diff file, and the vulnerability sensitive elements include system calls, arithmetic expressions, pointer usage, array usage and sensitive keywords.

[0066] In some embodiments, the slice subgraph generation module includes a parsing and identification unit and a code slicing unit; A parsing and identification unit is used to parse the program dependency graph and identify vulnerability-sensitive nodes containing sensitive elements; The code slicing unit is used to perform code slicing based on vulnerability-sensitive nodes and generate a slice subgraph of the code property graph.

[0067] In some embodiments, the parsing and identifying unit is specifically used to perform backward slicing and forward slicing in the program dependency graph using a breadth-first search algorithm with nodes containing vulnerability-sensitive elements as slicing criteria; and identify vulnerability-sensitive nodes containing vulnerability-sensitive elements by combining forward and backward slicing; Among them, backward slicing traverses all nodes and codes that affect vulnerability-sensitive elements and identifies the statements that trigger the vulnerability; forward slicing traverses all statements affected by vulnerability-sensitive elements.

[0068] In some embodiments, a node of the code property graph includes a label of the node type and source code text corresponding to the node; The model training module includes an initial vector generation unit and a training execution unit; The initial vector generation unit is used to convert the source code of each slice subgraph node into a vector form through the Doc2Vec model, and combine it with the node type label to form the initial vector representation of the node; The training execution unit is used to convert the slice subgraph into a node feature matrix and an edge adjacency matrix and input them into the deep learning model for training and evaluation to obtain a trained deep learning model; the dimension of the feature matrix is ​​m×n, where m represents the number of nodes and n represents the dimension of the embedding vector.

[0069] In some embodiments, the initial vector generation unit is specifically used to convert labels of N different node types into N-dimensional node label vectors through one-hot encoding; split user-defined function names and variable names into multiple sub-words and compress the vocabulary using the BPE algorithm; use the Doc2Vec model to vector embed the token sequence of the code; and obtain the initial vector representation of each node by concatenating the node label vector and the source code embedding vector.

[0070] The embodiment of the present invention also provides an electronic device, which includes: a processor, a communication interface, a memory and a communication bus, wherein the processor, the communication interface and the memory communicate with each other through the communication bus. The communication bus can be used for information transmission between the electronic device and the sensor. The processor can call the logic instructions in the memory to execute the following method: Step 1: obtain the source code file for training and the diff file containing the code modification; Step 2: divide the source code by function, and generate a program dependency graph and a code attribute graph for each function; Step 3: analyze the program dependency graph in combination with the diff file to identify vulnerability sensitive nodes and use the vulnerability sensitive nodes as a basis for code slicing, and generate a slice subgraph of the code attribute graph; Step 4: vectorize the nodes in each slice subgraph and input them into the deep learning model for training evaluation to obtain a trained deep learning model; Step 5: extract the program dependency graph in the source code file to be detected to generate a related slice subgraph, vectorize the nodes of each slice subgraph and input them into the trained deep learning model for analysis, and detect the vulnerabilities contained in each slice and the specific location of the vulnerability.

[0071] In addition, the logic instructions in the above-mentioned memory can be implemented in the form of software functional units and can be stored in a computer-readable storage medium when sold or used as an independent product. Based on this understanding, the technical solution of the present invention, in essence, or the part that contributes to the prior art or the part of the technical solution, can be embodied in the form of a software product, which is stored in a storage medium and includes several instructions for a computer device (which can be a personal computer, a server, or a network device, etc.) to perform all or part of the steps of the method described in each embodiment of the present invention. The aforementioned storage medium includes: U disk, mobile hard disk, read-only memory (ROM, Read-Only Memory), random access memory (RAM, Random Access Memory), disk or optical disk, etc., which can store program code.

[0072] An embodiment of the present invention provides a non-transitory computer-readable storage medium, which stores computer instructions, and the computer instructions enable a computer to execute the method provided by the above method embodiment, for example, including: Step 1: Obtain a source code file for training and a diff file containing code modifications; Step 2: Divide the source code by function, and generate a program dependency graph and a code attribute graph for each function; Step 3: Analyze the program dependency graph in combination with the diff file to identify vulnerability-sensitive nodes and use the vulnerability-sensitive nodes as a basis for code slicing to generate a slice subgraph of the code attribute graph; Step 4: Vectorize the nodes in each slice subgraph and input them into a deep learning model for training and evaluation to obtain a trained deep learning model; Step 5: Extract the program dependency graph in the source code file to be detected to generate a related slice subgraph, vectorize the nodes of each slice subgraph and input them into the trained deep learning model for analysis to detect the vulnerabilities contained in each slice and the specific locations of the vulnerabilities.

[0073] It should be understood that the order of execution of the steps in the above embodiment does not necessarily mean the order of execution. The execution order of each process should be determined by its function and internal logic, and should not constitute any limitation on the implementation process of the embodiment of the present invention.

[0074] The embodiment of the source code vulnerability detection and positioning device provided in the embodiment of the present invention belongs to the same inventive concept as the source code vulnerability detection and positioning method of the above-mentioned embodiments. For details not described in detail in the embodiment of the source code vulnerability detection and positioning device, reference can be made to the embodiment of the above-mentioned source code vulnerability detection and positioning method.

[0075] The source code vulnerability detection and positioning device is a unit and algorithm step of each example described in combination with the embodiments disclosed herein, and can be implemented by electronic hardware, computer software, or a combination of the two. In order to clearly illustrate the interchangeability of hardware and software, the composition and steps of each example have been generally described in terms of function in the above description. Whether these functions are performed in hardware or software depends on the specific application and design constraints of the technical solution. Professional and technical personnel can use different methods to implement the described functions for each specific application, but such implementation should not be considered to be beyond the scope of the present invention.

[0076] Those skilled in the art will appreciate that various aspects of the source code vulnerability detection and location method can be implemented as a system, method or program product. Therefore, various aspects of the present disclosure can be specifically implemented in the following forms, namely: a complete hardware implementation, a complete software implementation (including firmware, microcode, etc.), or a combination of hardware and software, which can be collectively referred to as "circuit", "module" or "system".

[0077] Although the present invention has been described in detail with reference to the accompanying drawings and in combination with the preferred embodiments, the present invention is not limited thereto. Without departing from the spirit and essence of the present invention, a person of ordinary skill in the art may make various equivalent modifications or substitutions to the embodiments of the present invention, and these modifications or substitutions shall be within the scope of the present invention. Any person of ordinary skill in the art may easily think of changes or substitutions within the technical scope disclosed by the present invention, and these shall be within the scope of protection of the present invention.

Claims

1. A source code vulnerability detection and location method, characterized in that: The steps include: Get the source code file for training and the diff file containing the code modifications; Split the source code into functions and generate a program dependency graph and code property graph for each function; Combine the diff file to analyze the program dependency graph to identify vulnerability-sensitive nodes and use the vulnerability-sensitive nodes as a basis for code slicing to generate a slice subgraph of the code property graph; After vectorizing the nodes in each slice subgraph, the nodes are input into the deep learning model for training and evaluation to obtain a trained deep learning model. The program dependency graph is extracted from the source code file to be tested to generate related slice subgraphs. The nodes of each slice subgraph are vectorized and input into the trained deep learning model for analysis to detect the vulnerabilities contained in each slice and the specific locations of the vulnerabilities.

2. The source code vulnerability detection and location method according to claim 1, characterized in that: The steps of dividing the source code into functions and generating a program dependency graph and a code property graph for each function include: Split the source code into functions; Extract the control dependency and data dependency of each function to generate a program dependency graph for each function, and represent the source code function as a code attribute graph; Among them, each node in the program dependency graph represents a source code statement or control predicate, and the directed edges represent the dependency relationship between nodes. Each node is also associated with detailed information on its source code and statement type, and the nodes are identified by the line number in the source code.

3. The source code vulnerability detection and location method according to claim 2, characterized in that: The steps of obtaining the source code files for training and the diff files containing the code modifications also include: Extract vulnerability sensitive elements based on diff files, including system calls, arithmetic expressions, pointer usage, array usage and sensitive keywords.

4. The source code vulnerability detection and location method according to claim 3, characterized in that: The steps of analyzing the program dependency graph in combination with the diff file to identify vulnerability-sensitive nodes and using the vulnerability-sensitive nodes as a basis for code slicing and generating a slice subgraph of the code property graph include: Parse the program dependency graph to identify vulnerability-sensitive nodes containing sensitive elements; Use vulnerability-sensitive nodes as the basis for code slicing and generate slice subgraphs of the code property graph.

5. The source code vulnerability detection and location method according to claim 4, characterized in that: The steps of parsing the program dependency graph to identify vulnerability-sensitive nodes containing sensitive elements include: In the program dependency graph, the nodes containing vulnerability-sensitive elements are used as the slicing criteria, and the breadth-first search algorithm is used to perform backward slicing and forward slicing; By combining forward and backward slicing, vulnerability-sensitive nodes containing vulnerability-sensitive elements are identified; Among them, backward slicing traverses all nodes and codes that affect vulnerability-sensitive elements and identifies the statements that trigger the vulnerability; forward slicing traverses all statements affected by vulnerability-sensitive elements.

6. The source code vulnerability detection and location method according to claim 5, characterized in that: The nodes of the code attribute graph contain the label of the node type and the source code text corresponding to the node; The steps of vectorizing the nodes in each slice subgraph and inputting them into the deep learning model for training and evaluation to obtain the trained deep learning model include: The source code of each slice subgraph node is converted into vector form through the Doc2Vec model, and combined with the node type label to form the initial vector representation of the node; The slice subgraph is converted into a node feature matrix and an edge adjacency matrix and input into the deep learning model for training and evaluation to obtain a trained deep learning model; the dimension of the feature matrix is ​​m×n, where m represents the number of nodes and n represents the dimension of the embedding vector.

7. The source code vulnerability detection and location method according to claim 6, characterized in that: The steps of converting the source code of each slice subgraph node into a vector form through the Doc2Vec model and combining it with the node type label to form the initial vector representation of the node include: Convert the labels of N different node types into N-dimensional node label vectors through one-hot encoding; Split user-defined function names and variable names into multiple subwords and use the BPE algorithm to compress the vocabulary; Use the Doc2Vec model to embed the token sequence of the code into vectors; By concatenating the node label vector and the source code embedding vector, the initial vector representation of each node is obtained.

8. A source code vulnerability detection and location device, characterized in that: It includes a file receiving module, a source code segmentation processing module, a slice subgraph generation module, a model training module and a code vulnerability detection module; A file receiving module is used to obtain source code files for training and diff files containing code modifications; The source code segmentation processing module is used to segment the source code by function and generate a program dependency graph and a code attribute graph for each function; Slice subgraph generation module, used to analyze the program dependency graph in combination with the diff file to identify vulnerability-sensitive nodes and use the vulnerability-sensitive nodes as a basis for code slicing to generate a slice subgraph of the code property graph; The model training module is used to vectorize the nodes in each slice subgraph and then input them into the deep learning model for training and evaluation to obtain a trained deep learning model; The code vulnerability detection module is used to extract the program dependency graph from the source code file to be detected to generate relevant slice subgraphs, vectorize the nodes of each slice subgraph and input them into the trained deep learning model for analysis to detect the vulnerabilities contained in each slice and the specific locations of the vulnerabilities.

9. An electronic device, characterized in that: The electronic device includes: at least one processor; and a memory communicatively connected to the at least one processor; the memory stores computer program instructions executable by the at least one processor, and the computer program instructions are executed by the at least one processor so that the at least one processor can execute the source code vulnerability detection and location method as described in any one of claims 1 to 7.

10. A non-transitory computer-readable storage medium, characterized in that: The non-transitory computer-readable storage medium stores computer instructions, and the computer instructions enable the computer to execute the source code vulnerability detection and location method according to any one of claims 1 to 7.

Citation Information

Patent Citations

  • Function-level code vulnerability detection method based on slice attribute graph representation learning

    CN112699377A

  • Vulnerability patch existence detection method based on deep learning

    CN116108446A

  • Source code vulnerability detection method based on data dependence enhancement program slicing

    CN116702160A

Cited By

  • Long function-oriented software supply chain vulnerability detection method

    CN119227086A

  • Vulnerability detection method based on source code multi-scale feature extraction and comparative learning

    CN119357974A

  • Source code security verification method and device, equipment and medium

    CN119806995A

  • Intelligent contract vulnerability detection method and device based on granular ball calculation and weight path signature similarity

    CN119939602A

  • Incremental test context generation method and system based on minimum patch graph

    CN120723659A