A software vulnerability detection method based on code attribute graph and graph neural network

CN122987019APending Publication Date: 2026-10-27HUBEI UNIV
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202611161398.6
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-08-03
Publication Date
2026-10-27

AI Technical Summary

Benefits of technology

通过工业级代码属性图按边类型分解为抽象语法树、控制流图和数据流图三个独立子图,使不同编码器能够分别捕获语法结构异常、控制路径缺陷和数据传播风险等不同维度的漏洞线索,避免了语义混合造成的特征稀释,显著提升了漏洞检测精度。

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122987019A_ABST
    Figure CN122987019A_ABST
Patent Text Reader

Abstract

The application provides a software vulnerability detection method based on code attribute graph and graph neural network. The method extracts a unified code attribute graph from source code through an industrial code analysis tool Joern, and decomposes the code attribute graph into three independent subgraphs of abstract syntax tree, control flow graph and data flow graph according to edge types. A hybrid node representation is constructed for each subgraph node, which fuses learnable embedding, graph structure features and explicit security domain knowledge. Three independent graph neural network encoders are used to learn vulnerability clues in syntax, control and data dependency, and global statistical features are fused for joint classification. When facing new vulnerability types, a three-dimensional score (prototype proximity, boundary information amount and sample diversity) based on prototype guidance is used to select playback samples, and a prototype regularization loss is combined to inhibit catastrophic forgetting, so as to realize the continuous learning ability under limited storage resources.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the fields of software security, static program analysis, and software vulnerability detection, specifically to a software vulnerability detection method based on code attribute graphs and graph neural networks. Background Technology

[0002] Software vulnerabilities pose a significant security risk to modern software systems. With the rapid development of cloud computing, the Internet of Things (IoT), industrial control systems, connected vehicles, and the open-source software supply chain, software systems are becoming increasingly large-scale and their code dependencies increasingly complex. Security flaws such as buffer overflows, command injection, out-of-bounds access, memory release errors, privilege escalation, and deserialization vulnerabilities are constantly emerging. Once exploited by attackers, these vulnerabilities can lead to sensitive data leaks, remote code execution, service interruptions, or privilege escalation. Therefore, vulnerability detection of source code before software development and release is of paramount importance.

[0003] Existing deep learning-based code vulnerability detection methods mainly fall into two categories: sequence models and graph neural network models. Sequence models treat source code as a text sequence and use recurrent neural networks or convolutional neural networks for representation learning. However, source code is not only a sequence of characters, but also contains syntactic levels, control paths, variable definition and usage relationships, and cross-statement dependencies. Serialization weakens program structure information, making it difficult for models to identify complex vulnerability patterns formed by control conditions, loop boundaries, data propagation paths, and calling context. Graph neural network methods utilize program graph structures for vulnerability detection, capturing richer program semantics than sequence models. However, existing technologies still have significant shortcomings: First, the quality of program graph construction is insufficient. Many solutions rely on language-level parsers or manual rule-based graph construction, resulting in graphs that often only cover syntactic structures or local control relationships, making it difficult to obtain complete program semantics. Second, mixing different semantic relationships (syntactic levels, control flow, data dependencies) in a single adjacency structure makes it difficult for graph neural networks to learn vulnerability clues from different dimensions. Third, insufficient utilization of security domain knowledge makes it difficult for pure end-to-end learning to reliably capture prior features related to vulnerabilities, such as dangerous function calls, buffer operations, and abnormal control. Fourth, in incremental learning scenarios, the model is prone to catastrophic forgetting after learning new vulnerability types. Existing random replay methods tend to retain redundant samples when replay budgets are limited, leading to insufficient maintenance of old class decision boundaries.

[0004] Therefore, there is a need for a vulnerability detection technology that can fully utilize high-quality program graph representations, explicitly inject security domain knowledge, and continuously learn new vulnerability types under limited storage and computing resources. Summary of the Invention

[0005] The technical problem this invention aims to solve is to address the shortcomings of existing vulnerability detection schemes based on graph neural networks in terms of program graph construction quality, multi-semantic feature learning, utilization of security prior knowledge, and incremental learning to prevent forgetting. This invention provides a software vulnerability detection method based on code attribute graphs and graph neural networks. Through industrial-grade code attribute graph decomposition, multi-dimensional node feature fusion, multi-graph independent encoding and global statistical feature fusion, as well as prototype-guided replay selection and regularization mechanisms, the method improves detection accuracy while enabling the model to continuously learn new vulnerability types and maintain its ability to recognize older types.

[0006] The technical solution of the present invention is as follows: A software vulnerability detection method based on code attribute graphs and graph neural networks includes the following steps: Step S1: Extract the code attribute graph from the source code to be detected, and decompose the unified code attribute graph into abstract syntax tree subgraph, control flow graph subgraph and data flow graph subgraph according to the edge type; Step S2: For nodes in each subgraph, construct a node representation that integrates learnable embeddings, structural features, and semantic security features; the semantic security features explicitly encode at least one security domain knowledge among dangerous function calls, buffer operations, and exception handling; Step S3: Using multiple independent graph neural network encoders, the abstract syntax tree subgraph, control flow graph subgraph, and data flow graph subgraph are encoded respectively, and graph-level statistical features are fused to output the vulnerability detection results; Step S4: When a new vulnerability type appears, perform incremental learning based on prototype-guided replay selection: select replay samples through a three-dimensional scoring system of category prototype, boundary information content, and sample diversity, and combine prototype regularization loss to suppress catastrophic forgetting in order to adapt to new vulnerability patterns and reduce forgetting of old vulnerability types.

[0007] Furthermore, step S1 specifically includes: A. Use the code analysis tool Joern to analyze the source code to be tested and generate a unified code attribute graph; clean and standardize the nodes in the code attribute graph, including removing invalid nodes, unifying node type names, truncating excessively long identifiers, mapping rare identifiers to unknown identifiers, and creating an independent graph sample for each function or code snippet. B. Based on the edge type, the syntax-related edges in the code attribute graph are divided into the abstract syntax tree subgraph, the control-related edges are divided into the control flow graph subgraph, and the data dependency-related edges are divided into the data flow graph subgraph. Each subgraph is constructed as a directed graph, and nodes belonging to multiple subgraphs are allowed to appear repeatedly in different subgraphs, so that different graph neural network encoders can learn independent representations related to graph type.

[0008] In step S2, constructing the node representation specifically includes: Construct learnable node type embeddings based on node types, wherein the node types include at least one of CALL, IDENTIFIER, LITERAL, CONTROL_STRUCTURE, METHOD, LOCAL, RETURN, PARAMETER, BLOCK, and FIELD_IDENTIFIER; Construct learnable identifier embeddings based on the function name, variable name, literal, or code value corresponding to the node; The structural features of the nodes are calculated. These structural features are obtained by normalizing the in-degree, out-degree, and total degree of the nodes and adding a constant bias term. They are used to describe the local topological position of the nodes in the subgraph. Construct multidimensional binary semantic security features, which are used to indicate at least one of dangerous function calls, dangerous module usage, buffer-related identifiers, function call expressions, member access, import references, Try blocks, exception handlers, loop structures, conditional statements, return statements, and function parameters. The node type embedding, identifier embedding, structural features, and semantic security features are concatenated into a node feature vector that integrates multi-dimensional information.

[0009] Step S3 specifically includes: Independent graph neural network encoders are set up for the abstract syntax tree subgraph, control flow graph subgraph, and data flow graph subgraph respectively. Each encoder adopts a graph convolutional network and outputs the graph-level embedding of the corresponding subgraph through multi-layer message passing and global pooling. Extract graph-level global statistical features, including code size features, structural complexity features, and semantic security features, from the code attribute graph, and generate global feature representations through linear projection; The graph-level embeddings of the abstract syntax tree subgraph, the control flow graph subgraph, and the data flow graph subgraph, along with the global feature representation, are concatenated and processed by a fusion network to generate the final code representation. Based on this final code representation, classification is performed, and the vulnerability detection probability is output.

[0010] In step S4, incremental learning based on prototype-guided selection of playback specifically includes: Extract the embedding vectors of the trained task samples into the fusion network, and calculate the mean of the embedding vectors for each category as the category prototype; For old task candidate samples, the prototype proximity score, boundary information content score and sample diversity score are calculated respectively. Based on the weighted sum of the three-dimensional scores, the sample with the highest comprehensive score is selected and added to the replay buffer using a greedy strategy. The new task samples are mixed with the selected replay samples to perform incremental training on the model; the training loss includes cross-entropy classification loss and prototype regularization loss, which is used to constrain the sample embeddings to move closer to their corresponding class prototypes in order to suppress the spatial drift of old class embeddings.

[0011] Compared with the prior art, the present invention has the following beneficial effects: By decomposing the industrial-grade code attribute graph into three independent subgraphs—an abstract syntax tree, a control flow graph, and a data flow graph—based on edge type, different encoders can capture vulnerability clues from different dimensions, such as syntax structure anomalies, control path defects, and data propagation risks. This avoids feature dilution caused by semantic mixing and significantly improves vulnerability detection accuracy.

[0012] By explicitly injecting multi-dimensional semantic security features such as dangerous function calls, buffer operations, and exception handling into the node representation, the model is provided with security prior knowledge that does not rely on training sample statistics. Even with limited training samples or imbalanced class distribution, the model can still stably capture vulnerability-related clues, improving robustness in small sample scenarios.

[0013] By integrating graph-level global statistical features with local graph embeddings, the model can simultaneously utilize global prior information such as code size, structural complexity, and security pattern density, as well as local structural information captured by message passing. This compensates for the limited receptive field of graph neural networks and enables comprehensive vulnerability assessment across scales.

[0014] During the incremental learning phase, a prototype-guided three-dimensional scoring replay selection mechanism is adopted, which synergistically utilizes prototype proximity, boundary information, and sample diversity to ensure that representative, boundary-oriented, and diverse old samples are retained first under a limited replay budget, effectively maintaining the decision boundary of the old category. At the same time, prototype regularization loss constrains embedding drift, significantly reducing catastrophic forgetting, enabling the model to maintain a high accuracy in identifying old vulnerability types while continuously absorbing new vulnerability types. Attached Figure Description

[0015] Figure 1 This is a framework diagram of the method of the present invention. Detailed Implementation

[0016] To make the objectives, technical solutions, and advantages of this invention clearer, the technical solutions of this invention will be clearly and completely described below in conjunction with embodiments. Obviously, the described embodiments are only some, not all, of the embodiments of this invention. All other embodiments obtained by those skilled in the art based on the embodiments of this invention without creative effort are within the scope of protection of this invention.

[0017] The following is for reference Figure 1This embodiment will be described in detail. The method of the present invention includes the following steps: Step S1: Extract the code attribute graph from the source code to be inspected, and decompose the unified code attribute graph into abstract syntax tree subgraphs, control flow graph subgraphs, and data flow graph subgraphs according to edge type, including the following steps: A. Code attribute map generation, including the following sub-steps: Step A1: Receive the source code file, function snippet, code commit change snippet, or target function set from the code repository to be tested. Call the code analysis tool Joern to parse the source code and generate a CodeProperty Graph (CPG). The CPG integrates the abstract syntax tree, control flow graph, and data flow graph into the same graph structure to describe the syntax hierarchy, execution path, variable definition and usage relationships, and control dependencies of the source code.

[0018] Step A2: Extract node and edge information from the generated CPG, recording node identifier, node type, node code value, associated method, function call relationship, variable definition and usage relationship, control structure relationship, and edge type label. For code fragments that cannot be parsed, the system records the reason for the parsing failure and can transfer them to manual auditing or a backup parsing process to avoid abnormal input affecting subsequent model training.

[0019] Step A3: Clean and normalize the nodes in the CPG, including removing invalid nodes, standardizing node type names, truncating excessively long identifiers, mapping rare identifiers to unknown identifiers, and creating independent graph samples for each function or code snippet. These processes reduce the interference of noisy nodes on model training and improve representation consistency across different code projects.

[0020] Step A4: In this embodiment, the frequency of identifiers is counted only for node code values ​​with a character length of less than 50. The identifier vocabulary size is set to 32, with one position reserved for an unknown identifier. The top 31 valid identifiers are retained based on their frequency of occurrence in the training data. Identifiers with a character length of 50 or more, or those not registered or not included in the top 31 positions, are mapped to unknown identifiers. The node type vocabulary size is set to 64. Each AST, CFG, or DFG subgraph retains a maximum of 256 nodes to control single-sample memory usage and batch processing overhead.

[0021] B. CPG subgraph decomposition, including the following sub-steps: Step B1 involves partitioning the syntax-related edges in the CPG into Abstract Syntax Tree (AST) subgraphs based on edge type. These syntax-related edges include at least one of AST parent-child relationship edges, parameter edges, binding edges, and receiver edges. The AST subgraph is used to express the hierarchical organization between declarations, expressions, calls, literals, and control structures.

[0022] Step B2 involves dividing the control-related edges in the CPG into control flow graph (CFG) subgraphs based on edge type. These control-related edges include at least one of conditional edges, true branch edges, false branch edges, dominating edges, and post-dominant edges. The CFG subgraph is used to represent program execution paths and can depict information such as input validation, loop boundaries, resource allocation and release order, and whether dangerous calls are subject to conditional constraints.

[0023] Step B3 involves partitioning data dependency edges in the CPG into data flow graph (DFG) subgraphs based on edge type. These data dependency edges include at least one of reach-definition edges, variable capture edges, and control dependency edges. The DFG subgraph expresses the propagation relationship of data from its source to its point of use, helping to identify whether external input propagates to dangerous functions, whether buffer lengths are validated, and whether pointers or resource objects are being misused.

[0024] Step B4 involves constructing each subgraph as a directed graph, preserving relevant edges and their associated nodes. For nodes belonging to multiple subgraphs simultaneously, repetition in different subgraphs is allowed, enabling different graph neural network encoders to learn independent representations related to graph type. This decomposition method avoids mixing different semantic relationships into a single adjacency structure, facilitating the model's separate learning of linguistic, control, and data dependency cues.

[0025] Step S2 involves constructing node representations that fuse learnable embeddings, structural features, and semantically safe features for each node in each subgraph, including the following steps: C. Node-based embedding construction, including the following sub-steps: Step C1: Construct learnable node type embeddings based on node types. The node types include at least one of CALL, IDENTIFIER, LITERAL, CONTROL_STRUCTURE, METHOD, LOCAL, RETURN, PARAMETER, BLOCK, and FIELD_IDENTIFIER. The node type embeddings are used to express the basic semantic roles of nodes in the program structure.

[0026] Step C2 involves constructing learnable identifier embeddings based on the function names, variable names, literals, or code values ​​corresponding to the nodes. For identifiers that are not logged in or have low frequency of occurrence, they can be mapped to a predefined unknown identifier vector; for numeric, string, and boolean literals, normalization mapping can be performed according to the literal category to reduce data sparsity.

[0027] D. Construction of structural and semantic security features, including the following sub-steps: Step D1 involves calculating the structural features of the nodes. Specifically, this is done by normalizing the node's in-degree by dividing it by 10, its out-degree by dividing it by 10, and its total degree by dividing it by 20, while adding a constant bias term of 1.0. These structural features describe the node's local topological position within the subgraph. For example, a high-out-degree control node may correspond to multiple execution branches, and a high-in-degree node may correspond to multiple data source convergence points. These structural patterns are related to the vulnerability formation process.

[0028] Specifically, assuming the node's in-degree is d_in and its out-degree is d_out, the four-dimensional structural features are min(d_in / 10,1), min(d_out / 10,1), min((d_in+d_out) / 20,1), and 1.0, respectively. The first three dimensions are truncated using an upper bound to prevent a very small number of highly connected nodes from generating excessively large values ​​and dominating subsequent graph convolutions.

[0029] Step D2: Construct semantic security features. These semantic security features are multi-dimensional binary indicator vectors used to explicitly encode security domain knowledge related to vulnerability detection, including at least one of the following: dangerous function calls, dangerous module usage, buffer-related identifiers, function call expressions, attribute or member access, imports or type references, try-catch blocks, exception handlers, loop structures, conditional statements, return statements, and function parameters.

[0030] Step D3: When the node is a function call node and the function name belongs to the dangerous function set, set the dangerous function call indicator to a valid value. The dangerous function set includes at least one of strcpy, sprintf, memcpy, gets, system, eval, popen, malloc, free, strcat, scanf, and exec, and can also be expanded according to the target language, enterprise security specifications, or historical vulnerability databases.

[0031] In one alternative implementation, the set of dangerous functions is externalized via a YAML or JSON configuration file. The configuration items include at least the target language, the name of the dangerous function, the name of the dangerous module, and a security-sensitive identifier. The system reads the configuration at startup, merges it with the built-in default set, lowers and deduplicates function names, and records any unrecognized configuration items, thus expanding the rules without retraining or modifying the feature extraction code.

[0032] Step D4: When a node identifier contains security-sensitive substrings such as buf, buffer, size, length, index, offset, ptr, cmd, query, path, file, and socket, the corresponding semantic indicator is set to a valid value. This type of feature is used to enhance the model's sensitivity to patterns such as buffer operations, command concatenation, path access, and external input propagation.

[0033] Step D5 involves concatenating the 32-dimensional node type embedding, the 32-dimensional identifier embedding, the 4-dimensional structural features, and the 12-dimensional semantic safety features to form a node feature vector with a total dimension of 80. This vector serves as the input to the multi-graph neural network encoder. Since the node representation simultaneously contains learnable information and explicit safety priors, it maintains good generalization ability even with limited training samples or imbalanced class distributions.

[0034] Step S3 involves using multiple independent graph neural network encoders to encode the AST subgraph, CFG subgraph, and DFG subgraph respectively, and then fusing graph-level statistical features to output the vulnerability detection results. This includes the following steps: E. Multi-graph neural network encoding, including the following sub-steps: Step E1 involves setting up independent graph neural network encoders for the AST, CFG, and DFG subgraphs. Each encoder receives node features and edge connections from the corresponding subgraph, and aggregates neighbor node information through multi-layer message passing to obtain node-level hidden representations. Independent encoders avoid information interference between different graph types, enabling the model to learn vulnerability patterns in syntactic structures, control paths, and data dependencies separately.

[0035] Step E2: The graph neural network encoder preferably employs a graph convolutional network (GCN). In this embodiment, each encoder uses four layers of graph convolution, with dimensions sequentially 80→256→256→256→256; each graph convolution is followed by layer normalization (LayerNorm), the first three layers further use the ELU activation function and Dropout with a dropout rate of 0.2, and finally, a 256-dimensional graph-level embedding is output through global mean pooling.

[0036] Step E3 involves performing global pooling on the node-level output of each subgraph encoder to obtain the AST graph embedding, CFG graph embedding, and DFG graph embedding. Global pooling can employ mean pooling, max pooling, attention pooling, or combinations thereof to map function graphs of different sizes to fixed-dimensional vectors.

[0037] F. Integration and classification, including the following sub-steps: Step F1 involves extracting multi-dimensional graph-level global statistical features from the code attribute graph. These features include: code size features (such as code length and number of lines), structural complexity features (such as control structure density, parameter-to-method ratio, and edge-to-node ratio), and semantic and security features (such as call density, identifier / literal density, dangerous mode indication, and assignment density). These features form the initial statistical feature vector. Subsequently, the vector is mapped to a high-dimensional latent space via linear projection to generate a global feature representation. The introduction of such features aims to effectively compensate for the difficulty of graph neural networks (GNNs) in directly and stably capturing global-scale prior and macroscopic security pattern density information during local message passing.

[0038] In the network structure of this embodiment, the initial graph-level global statistical feature vector is 16-dimensional, and a 256-dimensional global feature representation is generated through linear projection from 16 to 256, ReLU activation function, and Dropout with a dropout rate of 0.2.

[0039] Step F2 involves concatenating the 256-dimensional AST graph embedding, 256-dimensional CFG graph embedding, 256-dimensional DFG graph embedding, and 256-dimensional graph statistical features. The concatenated 1024-dimensional features are then input into the fusion network, mapped to a final 256-dimensional code representation through a linear layer from 1024 to 256. This process utilizes layer normalization (LayerNorm), ReLU activation function, and a dropout rate of 0.2 to reduce the risk of overfitting.

[0040] Step F3 inputs the final code representation into a classifier consisting of two multilayer perceptrons, with the feature dimensions decreasing sequentially from 256 to 128, ultimately reducing to a 2-dimensional class output. During this process, the ReLU activation function and a dropout rate of 0.2 are applied. The output is then converted into vulnerability detection probabilities using Softmax.

[0041] Step S4, when a new vulnerability type or a new training task appears, performs incremental learning based on prototype-guided selection replay to adapt to the new vulnerability pattern and reduce forgetting of old vulnerability types, including the following steps: G. Category prototype extraction, including the following sub-steps: Step G1 involves inputting the training samples into a multi-graph neural network model after completing training for a task, and extracting the embedding vectors output by the fusion network. These embedding vectors reside in a unified representation space and reflect the semantic relationship between the samples and security or vulnerability categories.

[0042] Step G2: For each learned category, calculate the mean of the embedding vectors of samples within the same category, which serves as the category prototype for that category. The category prototype represents the typical embedding pattern of that vulnerability or security category. In subsequent incremental training, the category prototype is used both to select old samples and to constrain embedding drift during the new training process.

[0043] H. Replay sample selection, including the following sub-steps: Step H1: Calculate the distance between the embedding of a candidate sample from the old task and its corresponding class prototype using the L2 norm (Euclidean distance). The smaller the distance, the more representative the sample is of the typical pattern of its class. The prototype proximity score is expressed as follows: ; in, This represents the prototype proximity score of the candidate sample. This represents the i-th candidate sample. The parameter is The feature extraction function of a graph neural network. Indicate category The corresponding category prototype, This represents the L2 norm.

[0044] Step H2: Calculate the distance difference between the candidate sample and its class prototype and other class prototypes using the L2 norm. The boundary information score is represented as follows: ; in Indicates the score of boundary information content. Indicates candidate samples, This represents the absolute value operation. This represents the class prototype of other classes that are opposite to the true class of the candidate sample.

[0045] Step H3: Calculate the candidate sample and the selected sample set. The diversity score is obtained by calculating the minimum L2 distance between all samples, as shown below: ; in Indicates candidate samples Diversity score This indicates the operation of finding the minimum value. This indicates the set of samples that have been selected and added to the replay buffer. Represents a set Selected samples This represents the embedding vector.

[0046] Step H4, the formula for calculating the comprehensive score based on the weighted sum of the scores is as follows: ; in This represents the final score of the candidate sample. The weighting coefficients represent the prototype proximity scores. The weighting coefficients representing the boundary information content score. The weighting coefficients represent the diversity scores, and these weighting coefficients satisfy the following conditions: The preferred weighting coefficient is set to , , The model uses a greedy strategy to select the comprehensive score at each step. The highest-scoring sample is added to the replay buffer.

[0047] Step H5: Before calculating the comprehensive score, minimum-maximum normalization is performed on the prototype proximity score and boundary information content score to ensure they fall within the [0,1] interval. The first selection is based on the weighted sum of prototype proximity and boundary information content; thereafter, the minimum embedding distance from the candidate sample to the selected sample set is added as the diversity term. In this embodiment, the weights are set to 0.5, 0.3, and 0.2, a combination determined by the three-dimensional ablation experiments described later. The replay buffer uses a dynamic capacity: the replay quantity for the second task is 50% of the number of training samples for the new task, and for the third task, it is 30%; in this embodiment, 280 and 168 old samples are selected respectively.

[0048] I. Incremental training and prototype regularization, including the following sub-steps: Step I1: Mix the new task samples with the replay buffer samples to form the current incremental training set, and perform incremental training on the model. The new task may correspond to a new CWE type, new project code, a new language subset, or a new version vulnerability sample.

[0049] This embodiment uses the AdamW optimizer, with an initial task learning rate of 5×10. ﹣4 The learning rate for subsequent incremental tasks is halved to 2.5 × 10⁻⁶. ﹣4 The weight decays to 1×10 ﹣5 The batch size was 64, the maximum number of training epochs was 20, the early stopping patience value was 8, and the gradient norm pruning threshold was 1.0. The mixed training set was reshuffled randomly in each training epoch; the ratio of new samples to replay samples in the second and third tasks was 1:0.5 and 1:0.3, respectively, to balance learning new data and retaining old knowledge.

[0050] Step I2 involves adding a prototype regularization loss in addition to the cross-entropy classification loss. This loss constrains the current sample embedding to be close to its corresponding class prototype, reducing the risk of drift in the old class embedding space when learning new vulnerability types. The formula for the prototype regularization loss is: ; in This represents the set of categories that actually appear in the current batch and have historical prototypes. The sample set of category c within the batch, Indicates sample embedding, Represents the category prototype; Total loss is ,in Cross-entropy classification loss, For prototype regularization loss, This is the regularization weight. In this embodiment, we take... Sensitivity verification was performed within the range of 0.01 to 0.5.

[0051] Step I3: After incremental training is complete, the category prototypes of the learned categories are recalculated, and the replay buffer is updated based on the new comprehensive score for use in the next round of incremental learning. By repeatedly executing the above process, the model can continuously absorb new vulnerability knowledge while maintaining its ability to identify old vulnerability types.

[0052] J. Experimental Verification Step J1: Dataset and Basic Detection Experiments. Function-level code attribute graphs were constructed using SARD Juliet C / C++ vulnerability samples, resulting in 7500 samples, including 3750 vulnerability samples and 3750 secure samples. These were then divided into a training set of 5250 samples, a validation set of 1125 samples, and a test set of 1125 samples, with a 70%:15%:15% ratio. The basic detection experiments used five random seeds (42, 123, 456, 789, and 1024) for repeated training, with the AdamW optimizer and a learning rate of 5×10⁻⁶. ﹣4 Weight decay 1×10 ﹣5 The batch size is 64, the maximum number of training rounds is 30, and the early stopping patience value is 8. Table 1 shows the mean and standard deviation of the test set and baseline.

[0053]

[0054] Step J2: Incremental Tasks and Comparative Experiments. Three incremental tasks were constructed from different CWE groups in arrival order: Task 1 included integer overflow, integer underflow, and heap buffer overflow, totaling 1200 samples; Task 2 included operating system command injection and buffer underflow, totaling 800 samples; Task 3 included null pointer dereference and null pointer dereference caused by return values, totaling 800 samples. The number of vulnerability samples and secure samples in each task was equal, and they were divided into 70%:15%:15% respectively. Here, "new vulnerability type" refers to the training tasks continuously arriving according to the new CWE group. Each task still performs a security / vulnerability binary classification, consistent with the classifier's 2D output. Using random seeds 42, 123, and 456, the prototype-guided selection replay method of this invention was compared with direct fine-tuning, elastic weight solidification (EWC), and random replay.

[0055]

[0056] The F1 decrease in Table 2 is defined as the F1 value after the first learning of the corresponding task minus the F1 value after the third task. The smaller the value, the less forgetting. The results show that on the Juliet incremental task in this embodiment, the final average F1 of prototype-guided selective playback is 0.876, which is 0.014 higher than that of random playback, and the average F1 decrease for tasks 1 and 2 is 0.009 and 0.002, respectively.

[0057] Step J3, Ablation and Sensitivity Experiments. In independent three-random seed ablation reproduction experiments, only prototype proximity, boundary information, or sample diversity were retained, and compared with the combined full score of the three factors. The results are shown in Table 3.

[0058]

[0059] Under the same ablation settings, when the replay ratios were set to 0.1, 0.3, 0.5, and 0.7, the final average F1 scores were 0.852, 0.865, 0.886, and 0.870, respectively. Therefore, this embodiment preferably uses 0.5 as the replay ratio for the second task; in subsequent tasks, the ratio is reduced to 0.3 to limit buffer growth. When the prototype regularization weight λ was set to 0.01, 0.05, 0.1, 0.2, and 0.5, the final average F1 scores were 0.880, 0.878, 0.881, 0.867, and 0.871, respectively, indicating that the results are more stable within the range of 0.01 to 0.1. This embodiment selects 0.1. The above experiments are used to illustrate the feasibility of the present invention under this specific data composition and parameter settings, and are not to be interpreted as an unconditional performance guarantee for all datasets or all engineering scenarios.

[0060] The above embodiments are merely illustrative of the technical concept of the present invention and should not be construed as limiting the scope of protection of the present invention. Any equivalent substitutions or improvements made based on the technical concept of the present invention should be considered as falling within the scope of protection of the present invention.

Claims

1. A software vulnerability detection method based on code attribute graphs and graph neural networks, characterized in that, include: Step S1: Extract the code attribute graph from the source code to be detected, and decompose the unified code attribute graph into abstract syntax tree subgraph, control flow graph subgraph and data flow graph subgraph according to the edge type; Step S2: Construct node representations that integrate learnable embeddings, structural features, and semantically safe features for each node in each subgraph; Step S3: Encode the abstract syntax tree subgraph, control flow graph subgraph, and data flow graph subgraph using multiple independent graph neural network encoders, and then fuse graph-level statistical features to output the vulnerability detection results; Step S4: When a new vulnerability type emerges, perform incremental learning based on prototype-guided selection playback to adapt to the new vulnerability pattern and reduce forgetting of old vulnerability types.

2. The method according to claim 1, characterized in that, Step S1 includes: The code analysis tool Joern is used to parse the source code to be detected, generate a unified code attribute graph, and clean and standardize the nodes in the code attribute graph, including removing invalid nodes, unifying node type names, truncating excessively long identifiers, mapping rare identifiers to unknown identifiers, and creating independent graph samples for each function or code snippet. Based on edge type, syntax-related edges in the code attribute graph are divided into abstract syntax tree subgraphs, control-related edges are divided into control flow graph subgraphs, and data dependency-related edges are divided into data flow graph subgraphs. Each subgraph is constructed as a directed graph, and nodes belonging to multiple subgraphs are allowed to appear repeatedly in different subgraphs.

3. The method according to claim 2, characterized in that, The syntax-related edges include at least one of AST parent-child relationship edges, parameter edges, binding edges, and receiver edges; the control-related edges include at least one of conditional edges, true branch edges, false branch edges, dominating edges, and post-dominating edges; the data dependency-related edges include at least one of reach-definition edges, variable capture edges, and control dependency edges.

4. The method according to claim 1, characterized in that, The construction of node representations in step S2 includes: Construct learnable node type embeddings based on node types, wherein the node types include at least one of CALL, IDENTIFIER, LITERAL, CONTROL_STRUCTURE, METHOD, LOCAL, RETURN, PARAMETER, BLOCK, and FIELD_IDENTIFIER; Construct learnable identifier embeddings based on the function name, variable name, literal, or code value corresponding to the node; The structural features of the nodes are calculated. These structural features are obtained by normalizing the node's in-degree, out-degree, and total degree and adding a constant bias term. They are used to describe the local topological position of the nodes in the subgraph. Construct semantic security features, which are multi-dimensional binary indicator vectors used to explicitly encode at least one security domain knowledge among dangerous function calls, buffer operations, and exception handling; The node type embedding, identifier embedding, structural features, and semantic security features are concatenated to obtain a node feature vector that integrates multi-dimensional information.

5. The method according to claim 4, characterized in that, The semantic security features include at least one of the following indicative dimensions: dangerous function calls, dangerous module usage, buffer-related identifiers, function call expressions, attribute or member access, import or type references, Try blocks, exception handlers, loop structures, conditional statements, return statements, and function parameters; When a node is a function call node and the function name belongs to a preset dangerous function set, the dangerous function call indicator is set to a valid value; the dangerous function set includes at least one of strcpy, sprintf, memcpy, gets, system, eval, popen, malloc, free, strcat, scanf, and exec.

6. The method according to claim 1, characterized in that, Step S3 includes: Independent graph neural network encoders are set up for the abstract syntax tree subgraph, the control flow graph subgraph, and the data flow graph subgraph, respectively. Each graph neural network encoder adopts a graph convolutional network and outputs the graph-level embedding of the corresponding subgraph through multi-layer message passing and global pooling. Extract graph-level global statistical features from the code property graph and generate a global feature representation by linear projection; The graph-level embeddings of the abstract syntax tree subgraph, the control flow graph subgraph, and the data flow graph subgraph, along with the global feature representation, are concatenated and a final code representation is generated through a fusion network. Based on the final code representation, the vulnerability detection results are classified and output.

7. The method according to claim 6, characterized in that, The graph-level global statistical features include code size features, structural complexity features, and semantic safety features; the code size features include at least the total number of nodes, AST depth, and number of lines of code; the structural complexity features include at least the control structure density, parameter-to-method ratio, and edge-to-node ratio; the semantic safety features include at least the call density, identifier density, literal density, and average of dangerous pattern aggregation.

8. The method according to claim 6, characterized in that, The incremental learning based on prototype-guided selection of playback in step S4 includes: Extract the embedding vectors of the trained task samples into the fusion network, and calculate the mean of the embedding vectors for each category as the category prototype; For old task candidate samples, scores are calculated for three dimensions: prototype proximity, boundary information, and sample diversity. Replay samples are then selected based on a weighted average of these three scores. Incremental training is performed by mixing new task samples with selected replay samples, and prototype regularization loss is used during training to constrain sample embeddings to converge toward their corresponding class prototypes in order to reduce forgetting.

9. The method according to claim 8, characterized in that, The prototype proximity score is determined based on the L2 distance between the candidate sample embedding and the prototype of its class; the closer the distance, the higher the score. The boundary information score is determined based on the difference between the distance of the candidate sample embedding to the prototype of its class and the distance to prototypes of other classes; the smaller the difference, the higher the score. The sample diversity score is determined based on the minimum L2 distance between the candidate sample embedding and the samples in the selected sample set; the larger the distance, the higher the score. The weighting coefficients of the weighted sum are: prototype proximity score weight 0.5, boundary information content score weight 0.3, and sample diversity score weight 0.

2. The sample with the highest comprehensive score is selected and added to the replay buffer in turn by a greedy strategy.

10. The method according to claim 8, characterized in that, The total loss of the incremental training is composed of a weighted sum of the cross-entropy classification loss and the prototype regularization loss; the prototype regularization loss is defined as the mean of the squared Euclidean distance between the current batch sample embedding vector and its corresponding class prototype.