A vulnerability mining method and system based on an AI code review model
Patent Information
- Application Number
- CN202610827362.0
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-06-09
- Publication Date
- 2026-08-18
AI Technical Summary
其中,静态分析工具多基于正则表达式或预设规则对源代码进行模式匹配,难以处理跨文件、跨函数的复杂数据流与控制流,导致较高的误报率和漏报率,尤其无法有效发现涉及业务逻辑的深层漏洞
本发明的基于AI代码审查模型的漏洞挖掘方法,通过并发构建抽象语法树、控制流图和程序依赖图并进行同构对齐,融合生成统一的代码属性图,再结合图神经网络进行消息传递与聚合,使模型能够同时捕捉代码的语法结构、执行路径和数据依赖关系,显著提升对跨函数、跨文件复杂逻辑漏洞的语义理解能力和检测灵敏度。引入包含特定行业标准化漏洞特征模板的外部知识图谱,并设计动态注意力模块,实时计算当前代码块与已知漏洞模式的相似度得分及注意力权重,使模型能够自适应地将计算资源聚焦于高风险代码区域,避免对常规代码的无效扫描,从而有效降低误报率。采用静态挖掘与轻量级动态轨迹模拟协同验证机制,当静态模型识别出潜在漏洞节点时,自动提取完整上下文路径并在局部隔离沙箱中定向构造测试用例执行验证,无需依赖完整系统环境即可过滤因不可达路径或死代码导致的无效告警,同时输出已验证的异常现场记录,极大减少了人工复核成本。系统可结合标准化修复模板库自动生成修复代码片段,实现从漏洞检测到辅助修复的自动化闭环,提高了软件安全审查的整体效率和可继承性。
Smart Images

Figure CN122595334A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of code vulnerability discovery technology, and in particular to a vulnerability discovery method and system based on an AI code review model. Background Technology
[0002] Traditional software vulnerability discovery methods mainly include Static Application Security Testing (SAST) and Dynamic Application Security Testing (DAST). Static analysis tools, often based on regular expressions or preset rules, perform pattern matching on source code, struggling to handle complex data and control flows across files and functions. This results in high false positive and false negative rates, particularly failing to effectively discover deep vulnerabilities involving business logic. In recent years, deep learning-based code review methods have been proposed, but existing models often treat source code as a one-dimensional text sequence or a pure token stream, ignoring the inherent graph structure characteristics of code (such as abstract syntax trees, control flow graphs, and program dependency graphs), leading to a lack of ability to capture deep semantics. Furthermore, existing automated vulnerability discovery tools still heavily rely on manual intervention in the vulnerability verification stage, unable to automatically verify the authenticity of static alerts, and lack standardized template support in the remediation stage, making it difficult to form an efficient, closed-loop review process. Summary of the Invention
[0003] To address the aforementioned technical problems, the technical solution adopted by this invention is as follows: According to the first aspect of this application, a vulnerability discovery method based on an AI code review model is provided, comprising the following steps: Obtain the source code to be reviewed and construct a multidimensional code semantic graph of the source code concurrently; the multidimensional code semantic graph includes an abstract syntax tree (AST), a control flow graph (CFG), and a program dependency graph (PDG); Using isomorphic alignment techniques, nodes in the AST, CFG, and PDG are aligned across graphs, using lines of code or abstract syntax nodes as anchors, and then merged to generate a unified code attribute graph (CPG). The CPG is formalized as a multi-relation attribute graph. ,in, This is the aligned set of core code nodes. A set of edge relation types, Let be the set of all heterogeneous edges; The CPG is input into the graph neural network (GNN), and through message passing and aggregation mechanisms, the features of each node in the CPG are iterated to obtain a node feature vector that integrates grammatical context, execution path features, and data pollution paths. During the model training or inference phase, a pre-built standardized vulnerability corpus is introduced; the corpus contains standardized vulnerability feature templates for specific industries, and the standardized vulnerability feature templates are transformed into an external knowledge graph. The dynamic attention module is used to extract the context feature vector of the current code block in real time and compare it with the vulnerability feature template in the external knowledge graph to calculate the dynamic attention weight, so as to adjust the model’s attention to suspected high-risk code segments. When a static AI model identifies a potential vulnerability node, it extracts the input source, data propagation path, and execution convergence point associated with the potential vulnerability and transmits them to a lightweight dynamic execution trajectory simulator. The lightweight dynamic execution trajectory simulator, in a local isolation sandbox, automatically constructs corresponding test cases for targeted probing based on the branch conditions on the extracted path, monitors the running status, and records abnormal feedback to verify the authenticity of the vulnerability and output the final review results.
[0004] According to another aspect of this application, a vulnerability discovery system based on an AI code review model is also provided, comprising: The multidimensional code semantic graph construction module is used to concurrently construct the abstract syntax tree (AST), control flow graph (CFG), and program dependency graph (PDG) of the source code, and to integrate the three into a unified code attribute graph (CPG) using isomorphic alignment technology. The graph neural network detection engine is used to receive the CPG, extract multi-dimensional semantic features of nodes through message passing and aggregation mechanisms, and output potential vulnerability nodes and their associated paths. A standardized vulnerability corpus and a dynamic attention module are used to store and retrieve standardized vulnerability feature templates for specific industries, and to calculate the similarity score and dynamic attention weight between the current code block and the vulnerability feature template in real time, so as to guide the graph neural network detection engine to focus on high-risk code regions. A lightweight dynamic trajectory simulator is used to receive potential vulnerability paths identified by the graph neural network detection engine, construct and execute targeted test cases in a local isolation sandbox, and monitor runtime anomalies to verify the authenticity of the vulnerabilities. The results output and visualization module is used to display the vulnerability location, data flow graph, verification status, and generate remediation suggestions.
[0005] The present invention has at least the following beneficial effects: This invention presents a vulnerability discovery method based on an AI code review model. By concurrently constructing and isomorphically aligning abstract syntax trees, control flow graphs, and program dependency graphs, a unified code attribute graph is generated. This graph is then combined with a graph neural network for message passing and aggregation, enabling the model to simultaneously capture the syntactic structure, execution path, and data dependencies of the code. This significantly improves the semantic understanding and detection sensitivity of complex logic vulnerabilities across functions and files. An external knowledge graph containing industry-specific standardized vulnerability feature templates is introduced, and a dynamic attention module is designed to calculate the similarity score and attention weight between the current code block and known vulnerability patterns in real time. This allows the model to adaptively focus computational resources on high-risk code regions, avoiding ineffective scanning of regular code and effectively reducing the false positive rate. A static mining and lightweight dynamic trajectory simulation collaborative verification mechanism is employed. When the static model identifies a potential vulnerability node, it automatically extracts the complete context path and constructs targeted test cases in a local isolated sandbox for verification. This filters out invalid alarms caused by unreachable paths or dead code without relying on a complete system environment, while simultaneously outputting verified anomaly records, greatly reducing the cost of manual review. The system can automatically generate repair code snippets by combining a standardized repair template library, realizing an automated closed loop from vulnerability detection to assisted repair, which improves the overall efficiency and inheritability of software security review. Attached Figure Description
[0006] To more clearly illustrate the technical solutions in the embodiments of the present invention, the accompanying drawings used in the description of the embodiments will be briefly introduced below. Obviously, the accompanying drawings described below are only some embodiments of the present invention. For those skilled in the art, other drawings can be obtained based on these drawings without creative effort.
[0007] Figure 1 A flowchart of a vulnerability discovery method based on an AI code review model provided in an embodiment of the present invention; Figure 2 This is a diagram illustrating the isomorphic alignment and feature extraction architecture of a multidimensional code semantic graph provided in this embodiment of the invention. Figure 3 This is a diagram illustrating the architecture of the dynamic attention guidance mechanism provided in an embodiment of the present invention. Figure 4 This is a diagram of a collaborative verification architecture for static mining and lightweight dynamic trajectory simulation provided in an embodiment of the present invention. Detailed Implementation
[0008] The technical solutions of the embodiments of the present invention will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only some embodiments of the present invention, and not all embodiments. Based on the embodiments of the present invention, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of the present invention.
[0009] It should be noted that, based on this disclosure, those skilled in the art will understand that one aspect described herein can be implemented independently of any other aspect, and two or more of these aspects can be combined in various ways. For example, any number of aspects set forth herein can be used to implement the device and / or practice the method. Furthermore, this device and / or practice the method can be implemented using other structures and / or functionalities besides one or more of the aspects set forth herein.
[0010] The following will refer to Figure 1 The flowchart shown is a vulnerability discovery method based on an AI code review model, which introduces a vulnerability discovery method based on an AI code review model.
[0011] The vulnerability discovery method based on the AI code review model may include the following steps: S100, Obtain the source code to be reviewed and construct a multidimensional code semantic graph of the source code concurrently; the multidimensional code semantic graph includes an abstract syntax tree (AST), a control flow graph (CFG), and a program dependency graph (PDG).
[0012] In this embodiment, the system obtains the source code to be reviewed (such as a network service program written in C / C++, containing multiple .c and .h files), and then starts a concurrent processing pipeline. Figure 2 As shown, the preprocessing stage is divided into three concurrent branches: AST (Abstract Syntax Tree) construction: A parser (such as a C language parser based on ANTLR) is used to parse the source code of each function into an abstract syntax tree. The AST precisely describes the literal syntax rules of the code, such as function declarations, variable definitions, and nested expressions. Consider a simplified user login code example: int login(char*user,char*pwd){ if(strcmp(pwd, getPass(user))==0) return GRANTED; else return DENIED; }
[0013] Its AST root node is FunctionDecl, and its child nodes include parameter declarations ParmVarDecl and CompoundStmt, as well as internal IfStmt, CallExpr (strcmp call), etc.
[0014] CFG Branch Construction: Based on the AST, the execution path of the program is analyzed. Using basic blocks as nodes and control flow directions (sequence, branching, looping) as directed edges, a control flow graph is constructed. In the above login function, the if condition divides the CFG into two branches: one pointing to return GRANTED and the other to return DENIED, finally converging at the function exit.
[0015] PDG builds branches: By analyzing data flow and control dependencies, a program dependency graph is generated. For example, the result of strcmp depends on the return values of pwd and getPass(user), and the return statement depends on the evaluation result of the if branch.
[0016] The three branches execute concurrently, generating the original AST, CFG, and PDG data structures respectively.
[0017] By concurrently constructing three complementary code semantic graphs—AST, CFG, and PDG—this approach overcomes the shortcomings of traditional methods that treat code merely as a text sequence, thus losing graph structure information. Parallel processing significantly reduces the preprocessing time for large-scale codebases. These three graphs provide a comprehensive semantic foundation for subsequent deep fusion at the syntax, execution path, and data flow levels, respectively. This enables AI models to simultaneously understand "what structure the code is written in," "how it might execute," and "how the data flows," laying a solid data foundation for accurate vulnerability discovery.
[0018] S200 utilizes isomorphic alignment technology, using code lines or abstract syntax nodes as anchor points, to perform cross-graph alignment of nodes in AST, CFG, and PDG, fusing them to generate a unified code attribute graph CPG; the CPG is formalized as a multi-relation attribute graph. ,in, This is the aligned set of core code nodes. A set of edge relation types, Let be the set of all heterogeneous edges.
[0019] Furthermore, the isomorphic alignment technique includes: Using line numbers in the source code or node identifiers in the abstract syntax tree as anchors, establish mapping relationships between AST nodes, CFG basic block nodes, and PDG nodes; for nodes with different granularities, adopt node splitting or node merging strategies to ensure that cross-graph nodes maintain semantically consistent alignment units.
[0020] like Figure 2 As shown in the central section, the system employs isomorphic alignment technology to align nodes across the three types of graphs generated in step one. The alignment strategy uses "line number" as the primary anchor and "AST node unique identifier" as the secondary anchor.
[0021] Alignment process: For an expression node in the AST (e.g., strcmp(pwd, getPass(user)) on line 5), the same line corresponds to a basic block containing that expression in the CFG, and one or more definition / use nodes in the PDG (e.g., the definition node of pwd, the call node of getPass). The system establishes a mapping between the three using line number 5. When encountering inconsistent granularity (e.g., an operator node in the AST corresponds to a part of the line number, while the CFG basic block covers the entire line), the system adopts a "node splitting or merging" strategy: the CFG basic block is split into finer-grained sub-blocks according to statements, so that each sub-block is aligned with a single statement node in the AST; if multiple AST nodes correspond to the same CFG node (e.g., consecutive assignment statements within a basic block), these AST nodes are merged into an aggregate node.
[0022] Generate CPG: All aligned nodes form a node set. For the three types of relationships: Syntactic topological edges (type syn): Parent-child and sibling relationships in the AST; Control flow edges (type ctl): Basic block jumps and branch edges in CFG; Data dependency edge (type dep): Definition in PDG - use edge, control dependency edge.
[0023] Add all edges to the edge set And record the type of each edge. Finally, a formalized multi-relation attribute graph is obtained: ,in . Figure 2 The right side illustrates the local structure of the merged CPG: a variable node is simultaneously connected to its user node via a dep edge, to its parent syntax node via a syn edge, and to nodes in subsequent basic blocks via a ctl edge.
[0024] By isomorphic alignment anchored by line numbers and AST nodes, isolated and heterogeneous ASTs, CFGs, and PDGs are seamlessly merged into a unified Code Attribute Graph (CPG). This CPG preserves the hierarchical nature of syntax, the sequential / branching characteristics of control flow, and the dependencies of data flow. This allows subsequent graph neural networks to simultaneously propagate syntax, execution, and data semantics along edges of different types, avoiding the loss of cross-type associations due to graph fragmentation in traditional methods. Formalizing it as a multi-relation attribute graph provides explicit and rich topological guidance for message passing in GNNs, significantly enhancing the ability to model cross-functional data flows and complex control dependencies.
[0025] S300, the CPG is input into the graph neural network GNN, and through message passing and aggregation mechanisms, the features of each node in the CPG are iterated to obtain a node feature vector that integrates the syntax context, execution path features and data pollution path.
[0026] The fused Code Attribute Graph (CPG) is input into a Graph Neural Network (GNN). Through message passing and aggregation mechanisms, each node repeatedly absorbs information from its neighbors. After multiple iterations, the final feature vector of each node can simultaneously reflect the surrounding syntax structure, execution path, and data flow propagation path. Simply put, it enables the AI model to "understand" the ins and outs of variables and function calls in the code, thereby providing node representations rich in contextual semantics for subsequent vulnerability identification.
[0027] Furthermore, the set of edge relationship types in the CPG It includes syntax topology edges, control flow edges, and data dependency edges; among them, syntax topology edges correspond to parent-child or sibling relationships in AST, control flow edges correspond to execution jump relationships in CFG, and data dependency edges correspond to definition-use relationships and data flow constraint relationships in PDG.
[0028] In step two, the AST, CFG, and PDG are merged into a unified code attribute graph (CPG) through isomorphic alignment. The CPG is formally defined using a multi-relation attribute graph. ,in, It is a set of edge relation types.
[0029] The purpose of classifying edges into three distinct types is to preserve the independence of different semantic dimensions in the original heterogeneous graph, while enabling graph neural networks (GNNs) to deliver messages differently based on the edge type. If all edges are treated as the same type without distinction, GNNs will be unable to identify whether an edge represents "syntactic nesting," "control jump," or "data dependency," thus losing important semantic information.
[0030] The specific meanings and examples of the three edge relationships are as follows: 1. Syntax topology edges (corresponding to parent-child or sibling relationships in the AST) Source: Abstract Syntax Tree (AST).
[0031] Parent-child edges: connect a syntax node to its direct child nodes, representing a hierarchical nested structure of code. For example, an IfStatement node has parent-child edges with its internal Condition, ThenStmt, and ElseStmt child nodes.
[0032] Sibling edges (optional): Connect adjacent child nodes belonging to the same parent node, indicating syntactic order. For example, multiple statements in a function body CompoundStmt are connected sequentially as sibling edges.
[0033] In CPG, the type of a syntax topology edge is marked as syn.
[0034] Example: For the code `int a=b+c;`, the AST structure is: DeclStmt (parent node) └─VarDecl(child node, type `syn`) └─BinaryOperator(child node, type `syn`) ├─DeclRefExpr(b)(child node) └─DeclRefExpr(c)(child node) Each parent-child relationship corresponds to a syn edge.
[0035] 2. Control flow to edges (corresponding to execution jump relationships in CFG) Source: Control Flow Graph (CFG).
[0036] Definition: A directed edge connecting basic blocks (or code nodes) represents a possible transition path during program execution. Typical cases include: Sequential execution edge: After one basic block is executed, the process unconditionally jumps to the next basic block.
[0037] Branch edges: Conditional statements (if, switch) generate two or more outgoing edges, which correspond to the execution paths when the condition is true or false.
[0038] Loop edge: A backward edge that jumps back to the beginning of the loop (while, for) after the loop body is executed.
[0039] In CPG, the type of control flow to an edge is marked as ctl.
[0040] Example: For the following code: if(x>0){ y=1; }else{ y=-1; } z=y; Its CFG includes: condition node (x>0) → y=1 block (ctl edge); condition node (x>0) → y=-1 block (ctl edge); y=1 block → z=y block (ctl edge); y=-1 block → z=y block (ctl edge); all these edges are retained as ctl type in the CPG.
[0041] 3. Data dependency edges (corresponding to the definitions in PDG - usage relationships and data flow constraints) Source: Program Dependency Graph (PDG).
[0042] Definition: Divided into two categories: Definition-use edge (data dependence): Connects the node that defines a variable (or memory location) to the node that uses the variable. For example, if `int a = 5;` defines variable `a`, and later `b = a + 1;` uses `a`, then there is a data dependence edge from the definition node to the usage node.
[0043] Control dependence: A control dependence edge connects a branch condition node to a statement node that it controls. For example, if `if (flag)` controls the execution of its internal `foo();`, then there is a control dependence edge from the `flag` condition node to the `foo()` call node.
[0044] In CPG, the type of a data dependency edge is marked as dep.
[0045] Example: char *buf = malloc(100); / / Define a node strcpy(buf, src); / / Use the node (read from buf) free(buf); / / Use the node (read from buf) There is a dep edge from the malloc node to the strcpy node and from the free node. Also, if the execution of strcpy is controlled by a certain if (len<100) statement, there is also a dep edge from that condition node to the strcpy node (control dependency).
[0046] In the merged CPG, a node often connects multiple types of edges simultaneously. For example, a CallExpr node (such as strcpy(dst, src)) might: Connect to its parent node (e.g., ExprStmt) and child node (parameters dst, src) via syn edges; Connect to the predecessor and successor basic blocks in the CFG via the ctl edge; The edge dep connects to the definition node of dst, the definition node of src, and the condition node that may affect its execution.
[0047] This multi-relationship topology allows graph neural networks to distinguish different semantic associations during message passing: syntactic structure information is propagated along the syn edge, execution path information is propagated along the ctl edge, and data flow information is propagated along the dep edge. GNNs can set different aggregation weights or different message passing functions for different types of edges, thus more effectively fusing multi-dimensional features.
[0048] By explicitly classifying edge relationship types in CPG (syntactic topology edges, control flow edges, and data dependency edges), this invention achieves the following beneficial effects: the three types of edges originate from AST, CFG, and PDG respectively, and retain their respective feature labels after fusion, avoiding semantic confusion and enabling graph neural networks to accurately distinguish the semantic types of edges; the model can assign differentiated parameters to different types of edges, such as assigning higher weights to control flow edges to capture key execution paths and using longer propagation steps for data dependency edges to track data contamination across basic blocks, thereby improving detection accuracy; at the same time, the explicit edge types enhance interpretability, allowing reviewers to quickly understand the cause of vulnerabilities by the edge type that triggers them, facilitating review and remediation; furthermore, this classification method gives CPG stronger expressive power, and the same model can adapt to different programming languages without redesigning feature engineering, exhibiting good cross-language generalization ability.
[0049] Furthermore, the graph neural network (GNN) employs a multi-layer graph attention network or a graph isomorphic network, and the message passing and aggregation process is represented as follows: ; in, Represents a node In the The feature vector of the layer, Represents a node In the CPG, the set of neighboring nodes, AGGREGATE is the aggregation function, and UPDATE is the update function; after... After rounds of iteration, the final node feature vector Fusion Topological semantic information of the neighborhood.
[0050] The code attribute graph (CPG) generated in step S200 contains a large number of nodes and three types of heterogeneous edges (syntax topology edges, control flow edges, and data dependency edges). Each node initially carries only local information about the code segment (such as node type, line number, variable name, etc.). However, vulnerability determination often depends on the context of a node—for example, a dangerous function call node may be safe on its own, only constituting a real vulnerability if its parameters come from unvalidated user input (requiring tracing multiple data dependency edges) and the control conditions on that path allow malicious input to reach it. Therefore, a mechanism is needed to allow each node to "see" information about its surrounding and even distant neighbors.
[0051] Graph Neural Networks (GNNs) achieve this goal through layer-by-layer message passing: in each layer, nodes collect information from their neighbors and update their own feature vectors. After multiple iterations, a node's feature vector contains topological semantic information about its K-order neighborhood.
[0052] The explanations of each parameter are as follows: :node In the Feature vectors of layer 0. The initial features are obtained by encoding node attributes.
[0053] :node The set of neighboring nodes in a CPG. Here, "neighbor" includes nodes connected by any type of edge: syn edge, ctl edge, or dep edge. Since a CPG is a multi-relationship graph, Naturally, it encompasses grammatical neighbors, control flow neighbors, and data flow neighbors.
[0054] AGGREGATE: An aggregation function used to aggregate nodes Feature vectors of all neighboring nodes The aggregation functions are combined into a single vector. Common aggregation functions include summation, averaging, maximization, and attention-weighted summation. In Graph Attention Networks (GAT), an attention coefficient is learned for each neighbor during aggregation, enabling the model to automatically distinguish the importance of different neighbors.
[0055] UPDATE: The update function, typically a fully connected layer (or multilayer perceptron) with non-linear activation, updates the nodes... old features Combined with the aggregated neighbor information, a new feature vector is generated. .
[0056] Total number of iterations. In practice, 3 to 5 layers are usually chosen. Too few layers will fail to capture long-distance dependencies, while too many layers may lead to oversmoothing (all node features converge).
[0057] The message passing process is illustrated below: Take a simple CPG local structure as an example: Node This represents the strcpy(dst, src) call; its neighbors include: The definition node of src is connected by the dep edge (from recv(sock,buf,...)); The conditional node in the previous basic block connected by the ctl edge if(len<100); The parent node ExprStmt and child node parameters are connected by a syn edge.
[0058] During aggregation at level 1, nodes It simultaneously collects information from these three neighbors: the `recv` node indicates "data comes from the network," the condition node indicates "length check exists," and the parent node provides the statement context. The update function then merges this information with the characteristics of `strcpy` itself to obtain... After passing the second floor, The neighbor information of the neighbors will also be indirectly absorbed (for example, the neighbors of recv may contain the initial location of sock), thus allowing To gain a more holistic perspective. Ultimately, after... Layer iteration, It integrates the complete path characteristics from the vulnerability source to the sink.
[0059] By employing multi-layer graph attention networks or graph isomorphic networks, the following beneficial effects were achieved: First, long-distance dependency capture—nodes pass through Layer iteration can be aware All nodes within the order neighborhood enable variable nodes deep within functions to receive data source information for input parameters, control flow information across basic blocks, and multi-level syntax nesting information, thereby effectively identifying complex logical vulnerabilities across functions and files; Second, adaptive neighbor importance weighting—when using graph attention networks, the model can automatically learn the contribution weights of different neighbor nodes to the current node. For example, it can assign higher weights to neighbors on data dependency edges to highlight the pollution propagation path, and assign higher weights to condition nodes on control flow edges to emphasize branch constraints, thereby improving the sensitivity and accuracy of vulnerability detection. Third, heterogeneous edge types naturally merge—due to It includes neighbors of all edge types, eliminating the need for additional multi-channel processing. The formula is simple and universal, and different AGGREGATE implementations (such as the attention mechanism in GAT) can implicitly learn the differences between edge types. Fourth, end-to-end trainability—the entire message passing and update process contains learnable parameters (such as the weight matrix in UPDATE and the attention parameters in GAT), which can be jointly optimized with vulnerability classification tasks, so that the feature extraction process is consistent with the final detection target, avoiding the limitations of manually designed features; Fifth, good scalability—this mechanism is not limited to specific GNN variants and is compatible with a variety of mainstream models such as GCN, GraphSAGE, GIN, and GAT. It is easy to select the optimal implementation based on the actual code size and hardware resources, and has strong engineering adaptability.
[0060] S400, during the model training or inference phase, introduces a pre-built standardized vulnerability corpus; the corpus contains standardized vulnerability feature templates for specific industries, and transforms the standardized vulnerability feature templates into an external knowledge graph.
[0061] Before model training or actual code scanning, historical vulnerabilities are collected for specific industries (such as finance and connected vehicles). The triggering conditions, pollution paths, and context of each vulnerability are extracted into standardized feature templates, and these templates are then organized into an external knowledge graph. This knowledge graph is equivalent to equipping the AI model with an "industry vulnerability dictionary," allowing the model to know which code patterns have caused high-risk vulnerabilities in the past, thus focusing on similar patterns in subsequent detection.
[0062] Furthermore, the construction method of the standardized vulnerability corpus includes: Collect verified vulnerabilities from historical security incidents in specific industries, and extract the triggering conditions, pollution paths, and context of each verified vulnerability; The triggering conditions, pollution paths, and context of each verified vulnerability are transformed into structured vulnerability feature templates. Each vulnerability feature template includes at least a vulnerability type identifier, source point features, sink point features, and critical path constraints from source to sink. The external knowledge graph is constructed using vulnerability feature templates as nodes and similarity or co-occurrence relationships between templates as edges.
[0063] The specific implementation of this step is as follows: 1. Collection of historical vulnerabilities in specific industries The system first identifies target industries (e.g., financial transaction systems, connected vehicle T-Boxes, medical device software). It then collects verified (i.e., reliably confirmed) security vulnerabilities that have occurred in these industries over the past 5 to 10 years from publicly available security databases (CVE, NVD), vendor security bulletins, and internal penetration test reports. Each vulnerability record includes: vulnerability type (e.g., SQL injection, unauthorized access, command injection), affected code files / functions, attacker-controllable input point (Source), dangerous operation point that triggers the vulnerability (Sink), a description of the data propagation path between the Source and Sink, and the contextual conditions required to trigger the vulnerability (e.g., whether specific configurations or privileges are required).
[0064] 2. Extract three core elements For each vulnerability collected, the following three types of information are extracted manually or semi-automatically: Triggering conditions: Input characteristics or preconditions that lead to the activation of the vulnerability. For example, the triggering condition for a command injection vulnerability is "the user input contains unescaped special characters (such as ;, |) and the input is directly concatenated into the system command".
[0065] Pollution path: The sequence of code elements that data travels through from Source to Sink. For example, if the Source is getParameter(“cmd”), it passes through the string concatenation function concat(), and is then passed as a parameter to Runtime.exec(). Key nodes along the path (function calls, assignment operations, arithmetic operations) need to be recorded.
[0066] Context: The scope of the code where the vulnerability exists and the surrounding conditions. For example, the vulnerability may only appear in modules that have undergone user authentication, or it may only be triggered when parsing specific XML tags.
[0067] 3. Construct a structured vulnerability feature template The above three types of information are encoded into a template that can be processed by a machine. Each template contains at least four key fields (such as...). Figure 3 (As shown in the "Standardized Vulnerability Feature Template" box) Vulnerability type identifier: such as CWE-78 (OS command injection), CWE-89 (SQL injection). This identifier is used for subsequent classification and retrieval.
[0068] Source feature: Describes the code pattern of the input source. It can be a function name (such as recv, getParameter), an API class name (such as HttpServletRequest), or a specific variable naming rule (such as user_input). Features can be represented as a vector or a set of regular expression patterns.
[0069] Sink point characteristics: Describe code patterns that involve dangerous operations. Examples include function calls like `system()`, `eval()`, and `strcpy()`, or language features such as dynamic concatenation (`$`).
[0070] Critical path constraints from Source to Sink: This is the most critical part, describing the operations that data must or cannot undergo during propagation. For example: "Must pass through" constraint: Data is considered safe only if it passes through a certain filtering function (such as htmlspecialchars()). If it is bypassed, it constitutes a vulnerability.
[0071] "Forbidden Passage" constraint: Data cannot pass through any validation function (such as isValidInteger()) in order to trigger a vulnerability.
[0072] Path constraints can be represented by subgraph patterns or logical expressions on the property graph (e.g., ∃ path:Source→Sink∧no sanitizer on path).
[0073] 4. Construct an external knowledge graph like Figure 3 As shown in the middle section, all vulnerability feature templates are treated as nodes. The attributes of each node include template ID, vector representation (obtained by encoding the template description text through a pre-trained model such as CodeBERT), and the specific content of the above four fields.
[0074] Edges are established between nodes based on similarity or co-occurrence relationships: Similarity Relationship: If two templates share the same CWE type, or their Source / Sink feature vector cosine similarity exceeds a threshold (e.g., 0.8), then a "similar" edge is added between them, with the edge weight being the similarity value.
[0075] Co-occurrence relationship: If two vulnerability templates are discovered simultaneously in the same software system or during the same security audit (for example, SQL injection and XSS vulnerabilities exist in an application at the same time), a "co-occurrence" edge is established, indicating that these two vulnerability types often appear together in business.
[0076] The final external knowledge graph Stored in a vector database or graph database accessible to the model. During the runtime of the dynamic attention mechanism ( Figure 3 (On the right), the model will compare the features of the current code block with... All template nodes are compared, and a high-weight attention is triggered when a similar template is matched.
[0077] By constructing standardized vulnerability feature templates and organizing them into an external knowledge graph, AI models can accumulate industry historical vulnerability experience, accurately distinguish between exploitable vulnerabilities and invalid dependencies using Source, Sink, and path constraints, achieve correlation detection through similarity and co-occurrence relationships between templates, and support incremental updates to adapt to new vulnerabilities, thereby improving the domain vulnerability detection rate, reducing false positives, and possessing good scalability.
[0078] S500 utilizes a dynamic attention module to extract the context feature vector of the current code block in real time, compares it with the vulnerability feature template in the external knowledge graph, and calculates dynamic attention weights to adjust the model's attention to suspected high-risk code segments.
[0079] While the model scans the code, the dynamic attention module extracts the contextual feature vector of the current code block in real time and compares it with the similarity templates of all known vulnerabilities in the external knowledge graph. A score is calculated using bilinear mapping, and then the score is normalized using Softmax to obtain the attention weight. This weight determines the model's level of attention to the code block—the higher the match with known vulnerability patterns, the more the model focuses on it and its associated nodes; conversely, the less attention is given. This is equivalent to enabling the AI model to automatically learn "where to look more closely and where to skip," thereby reducing computational overhead while improving the sensitivity to capturing real vulnerabilities.
[0080] Furthermore, the calculation process of the dynamic attention weights includes: Let the extracted code block context feature vector be... The first in the external knowledge graph The vector representation of a standardized vulnerability feature template is as follows: Calculate similarity score : ; in, For a learnable attention weight matrix, the superscript... Indicates vector transpose; The similarity score is normalized using the Softmax function to obtain the similarity score for the current code block. Dynamic attention weights for vulnerability feature templates : ; in, This represents the total number of vulnerability feature templates recorded in the external knowledge graph; the model is based on... The value adjusts the feature weights of the current code block and its associated control flow and data flow nodes.
[0081] In this embodiment, in step S400, the system has already constructed a system containing... External knowledge graphs of standardized vulnerability signature templates (such as...) Figure 3 (As shown in the middle). However, possessing a knowledge graph does not equate to the model automatically utilizing it. The dynamic attention mechanism in this step is precisely the bridge connecting "knowledge" and "detection." Its core issue is how to quantify the similarity between the currently scanned code snippet and each known vulnerability pattern in the knowledge base, and adaptively allocate the model's computational resources based on the similarity.
[0082] The parameters in the above formula are explained as follows: : The context feature vector of the current code block. During the scanning process, the system aggregates the feature vectors of all nodes within the current code block (from the GNN output of step S300) at the granularity of basic blocks or functions (e.g., using average pooling or GRU encoding) to obtain a fixed-dimensional vector, denoted as . This vector encapsulates the syntax structure, execution path, and data flow characteristics of the current code block.
[0083] : No. This is a vector representation of a vulnerability feature template. It's a vector generated during offline knowledge graph construction by encoding information such as vulnerability type identifiers, Source / Sink features, and path constraints from the templates using a pre-trained model (such as CodeBERT). Each This can be understood as the "standard image" of the vulnerability pattern in vector space.
[0084] : A learnable attention weight matrix. This is a matrix with dimensions of 1. square array ( (This refers to the dimension of the feature vector). During the model training phase, optimization is achieved through backpropagation using a large number of code samples labeled with vulnerability types. The parameters enable it to and Mapped to a space suitable for calculating similarity. Bilinear form. Compared to the simple dot product (equivalent to An identity matrix or cosine similarity is more expressive because it can learn the cross-interaction weights between different dimensions.
[0085] Similarity score. A scalar value representing the similarity between the features of the current code block and the first code block. The score indicates the degree of matching between the current code block and the vulnerability template features. A higher score means the current code block is more similar to the vulnerability pattern.
[0086] Dynamic attention weights. By applying all... Softmax normalization is performed to obtain the result that satisfies This can be understood as the probability or level of attention the model assigns to various vulnerability templates for the current code block.
[0087] The calculation process is illustrated below: Suppose there are three vulnerability templates in the external knowledge graph: SQL injection ( Command injection Unauthorized access () The code block currently being scanned is a web backend function that contains `String cmd=request.getParameter("cmd");Runtime.getRuntime().exec(cmd);`.
[0088] The system extracts the context features of the code block. .
[0089] Calculate the similarity with each of the three templates: (Compared to SQL injection template) → Lower value because there is no SQL operation in the code.
[0090] (Compared to command injection template) → The value is very high because Source is getParameter, Sink is exec, and there is no filtering function.
[0091] (With unauthorized access template) → Medium value.
[0092] Calculate Softmax: Assumptions , , ,but , , This means that the model believes the current code block has a very high probability of matching a command injection vulnerability pattern.
[0093] according to Adjust feature weights: like Figure 3 As shown in the "Dynamic Attention" module on the right, the model obtains... Then, feature weighting will be applied to the current code block and its associated nodes in the CPG. A specific implementation could be: Node Feature Boosting: Multiplies the feature vectors of all nodes within the current code block by... ,in These are hyperparameters. If the maximum attention weight is close to 1, the node features are significantly enhanced; if all... If all values are very small (e.g., all below 0.1), the characteristic remains unchanged or even decays.
[0094] Message passing weight adjustment: In subsequent GNN message passing, for edges originating from the current code block node, their message passing coefficient is multiplied by... A certain function allows the influence of high-risk nodes to propagate more strongly to their upstream and downstream nodes.
[0095] Attention visualization: The final heatmap will highlight high-risk lines of code to help reviewers quickly locate them.
[0096] The model employs learnable bilinear similarity calculation, enabling it to adaptively measure the matching degree between code blocks and vulnerability templates. Softmax normalization is used to achieve soft allocation and automatic balancing of multiple vulnerability patterns. The features of high-risk code blocks are dynamically enhanced based on attention weights, focusing computational resources on suspected areas, thereby improving detection efficiency and reducing false positive rates. At the same time, attention weights directly reflect the model's judgment criteria, enhancing interpretability. Furthermore, the calculation process involves only one bilinear operation and one Softmax operation, resulting in extremely low overhead and suitability for real-time scanning.
[0097] Furthermore, the similarity score In the calculation, the attention weight matrix Implemented through bilinear mapping, and During the model training phase, code samples labeled with vulnerability types are used to update parameters, so that code blocks that match known vulnerability patterns can obtain higher similarity scores.
[0098] In the above embodiments, the similarity score is defined as This form is called a bilinear mapping, where, It is a learnable parameter matrix.
[0099] Compared to simple similarity functions: If we use the dot product ( ), which is equivalent to assuming Since it is an identity matrix, it is impossible to weight the interactions between feature dimensions.
[0100] If cosine similarity is used, it also has a fixed weight.
[0101] Bilinear mapping is achieved through a matrix. Each element Come to learn The Wei and The The importance of interactions between dimensions. For example, when there is a strong correlation between the "Source point type" feature dimension of a code block and the "Sink point type" feature dimension of a vulnerability template, The weights of the corresponding positions will increase during training, thereby improving the matching score.
[0102] Mathematical explanation: Treat it as a linear transformation, first... Projected into a new space ( ), and then with Dot product. Equivalent to: ,in, In this way, different vulnerability templates will be projected into the optimal comparison space aligned with the characteristics of the code block.
[0103] Training phase: Update using labeled samples
[0104] like Figure 3 As shown in the flowchart, the dynamic attention module is part of the overall AI model, and its parameters It needs to be jointly trained with the parameters of the GNN feature extraction layer. The training process is as follows: 1. Training Sample Preparation Collect a large number of labeled code samples. Each sample contains either a piece of code with a vulnerability (positive example) or secure code (negative example). It also includes a vulnerability type label (e.g., "SQL injection," "command injection," "no vulnerability"). For positive examples, it labels the corresponding vulnerability feature template ID (i.e., which one in the knowledge graph it should correspond to). (Highly matched).
[0105] 2. Forward Propagation and Loss Calculation For a training sample, the system performs the following steps: Construct a CPG and extract node features.
[0106] Extract the context feature vector of the current code block .
[0107] Calculation and all Similarity score of vulnerability templates .
[0108] Attention weights are obtained using Softmax. .
[0109] After adjusting node features based on attention weights, the model ultimately outputs a vulnerability type prediction (e.g., through a classification layer).
[0110] The training loss function typically uses cross-entropy loss, which aims to minimize the discrepancy between the model's predicted vulnerability type and the true label. Simultaneously, an auxiliary loss term can be introduced to encourage matching with the correct template. Get as close to 1 as possible, while other templates Approaching 0. That is: ; in, It is the vulnerability template index to which the sample actually belongs.
[0111] 3. Backpropagation and parameter update The loss pair is calculated using the backpropagation algorithm. gradient: ; in, (Outer product). Update using gradient descent (e.g., Adam optimizer). Each element.
[0112] 4. Training effect After multiple iterations It will be optimized to: when This comes from a code block that is actually a command injection vulnerability, and When injecting commands into a template, Significantly greater than other cases. Conversely, for safe code blocks, all The similarity scores are generally low, with attention weights evenly distributed or approaching zero. This allows code blocks that match known vulnerability patterns to achieve higher similarity scores.
[0113] Learnable attention weight matrix implemented through bilinear mapping Under the supervision of vulnerability classification tasks, end-to-end training is performed, enabling the model to adaptively learn the complex dimensional interactions between code block features and vulnerability template features. This results in higher similarity scores for real vulnerability code blocks and lower scores for secure code blocks, effectively improving matching accuracy and reducing false positives. At the same time, this mechanism can still provide a certain generalization ability for known vulnerability variants that are not precisely matched through dimensional cross-weights, and computationally it can be seamlessly integrated with GNN to achieve joint optimization of the overall model.
[0114] S600: When the static AI model identifies a potential vulnerability node, it extracts the input source, data propagation path, and execution convergence point associated with the potential vulnerability and transmits them to the lightweight dynamic execution trajectory simulator. The lightweight dynamic execution trajectory simulator automatically constructs corresponding test cases for targeted detection based on the branch conditions on the extracted path in a local isolation sandbox, monitors the running status, and records abnormal feedback to verify the authenticity of the vulnerability and output the final review result.
[0115] When a static AI model identifies a suspected vulnerability, it doesn't report it directly. Instead, it automatically extracts the complete path from the input source to the dangerous operation point, along with the constraints along the way. Then, it generates targeted test cases (such as boundary values and malformed data) in a lightweight isolated sandbox and executes them. If an exception (such as a crash) is triggered during execution, the vulnerability is confirmed and the risk level is increased; if all test cases run smoothly, the alert level is reduced or it is marked as a false alarm. This collaborative mechanism of "static discovery first, dynamic verification later" effectively filters out false alarms caused by unreachable paths or dead code commonly found in static analysis, while automatically recording the anomaly scenario to provide developers with intuitive remediation guidelines.
[0116] Furthermore, the lightweight dynamic execution trajectory simulator constructs test cases in a local isolation sandbox in the following way: Based on the high-probability vulnerability path from the Source point to the Sink point output by the static AI model, extract the conditional constraints at all branch nodes on the path; use symbolic execution or constraint solving techniques to solve for the input vector that satisfies the path reachability; perform targeted mutation on the variables involved in the path to generate multiple fuzzy test cases, including boundary values, malformed data structures, and empty characters, and inject them into the local sandbox for execution.
[0117] In the collaborative verification process of step S600, the static AI model (i.e., the preceding GNN + attention mechanism) has identified a high-probability vulnerability path from the Source (input source) to the Sink (dangerous operation point). For example, it detects that recv(sock,buf,1024,0) → variable buf is directly passed to strcpy(dst,buf) without any length check in between. However, static analysis cannot guarantee that this path will be reachable in real-world operation—there may be certain branch conditions (such as if(len>1000)) that prevent the input data from reaching the Sink, or there may be implicit security filtering.
[0118] like Figure 4 The “Static Mining and Lightweight Dynamic Trajectory Simulation Collaborative Verification Architecture Diagram” shown illustrates that after the static model outputs the path, the system extracts the branch conditions on the path, generates test cases through constraint solving, and then executes and monitors anomalies in a local sandbox.
[0119] The specific implementation steps are as follows: 1. Extract branch conditions on high-probability vulnerability paths The output path of a static AI model is typically a sequence of nodes from the Source node to the Sink node, for example: Source node: recv(fd, buf, size) ↓ (Data flow) Assigning a value to a node: length = atoi(buf) ↓ (Data flow) Conditional node: if (length < 100) ↓ (Controls the flow direction; branches with true conditions) Sink node: memcpy(dst, src, length).
[0120] The system records the condition constraints of each branch node along the path. For example, the path above contains the constraint length<100. Additionally, if there are loops or indirect calls within the path, the corresponding boundary conditions also need to be extracted.
[0121] 2. Generate an input vector that satisfies reachability using symbolic execution or constraint solving techniques. All extracted branch conditions are combined into a single path condition expression. For example, the path from Source to Sink must simultaneously satisfy: length = atoi(buf) and length < 100. The system calls a symbolic execution engine (such as a Z3-based solver) or a constraint solver to generate a set of input vectors that satisfy all constraints. In the example above, the solver might output buf="50" (because atoi("50") = 50 < 100). This input vector serves as the base test case.
[0122] If there are multiple branches in the path (e.g., if(A) takes the true branch, else if(B) takes the false branch), the constraint solver will attempt to find the specific input values that activate the path. If the constraint cannot be satisfied (e.g., length<0 and length>100 appear simultaneously), it means that the path is logically unreachable, and the static model can immediately determine it as a false alarm without further dynamic simulation.
[0123] 3. Targeted mutation generates multiple fuzzy test cases. A single basic input vector obtained from constraint solving may not be sufficient to expose vulnerabilities (e.g., the path is reachable, but boundary checks pass without triggering a buffer overflow). Therefore, the system performs targeted mutations on the variables involved in the path to generate a set of test cases, including: Boundary values: For integer constraints, generate length=99 (just less than 100), length=100 (equal to the boundary, may trigger an error), length=-1 (negative number), etc.
[0124] Malformed data structures: For string input, generating excessively long strings, containing special characters (such as %n, \x00), or data packets with incorrect formats, etc.
[0125] Null character / null pointer: Injecting empty strings, NULL pointers, etc.
[0126] These mutation use cases perturb the input without violating the basic path conditions in order to test the robustness of the program. For example, for a constraint of length < 100, mutations can generate length = 99 (reachable), length = 100 (the constraint is not satisfied, but it can test whether the branch correctly handles the inequality sign), and length = 500 (although the original path is not followed, it can test whether there are vulnerabilities in other branches).
[0127] 4. Inject into a local isolation sandbox for execution. like Figure 4 As shown on the right, the system does not need to compile the entire target program. Instead, it loads only the affected code modules (such as the source files containing the vulnerable functions and a small number of dependent data structures) into a locally isolated sandbox built in memory. The sandbox simulates necessary system calls (such as memory allocation and string manipulation) but does not rely on a complete operating system environment. The system sequentially injects the generated test cases as input to drive the code modules to execute and monitors the runtime status (memory access, program counter, return values, etc.) in real time. Once an exception such as memory out-of-bounds access, segmentation fault, or unexpected interruption is detected, the system immediately captures and records the event.
[0128] Based on the high-probability path extraction branch constraints output by the static model, the path reachability is first judged by symbolic execution to filter invalid alarms. Then, by combining targeted mutation to generate test cases such as boundary values and malformed data, the authenticity of the vulnerability is accurately verified in a lightweight sandbox. This method avoids the inefficiency of blind fuzz testing, has low resource consumption, and can automatically retain abnormal situations as reproducible vulnerability evidence, effectively reducing false alarms and improving verification efficiency and credibility.
[0129] Furthermore, the verification of the vulnerability's authenticity and the output of the final review result include: When the simulator catches a runtime exception during the execution of test cases, the suspected vulnerability is determined to be a confirmed vulnerability, and its risk confidence score is automatically increased. If none of the test cases trigger an exception, the corresponding risk confidence score is reduced or the case is marked as a false alarm. The final output includes the location of the vulnerability code, the data flow path, the verified exception scene record, and the repair code snippet generated based on the standardized repair template library.
[0130] After executing targeted test cases in the lightweight sandbox, if any runtime exceptions (such as memory out-of-bounds errors, program crashes, or logical errors) are captured, the suspected vulnerability is marked as a confirmed vulnerability and its risk confidence score is automatically increased (e.g., from "medium risk" to "high risk"). If all test cases are executed successfully without triggering any exceptions, its risk confidence score is reduced or it is directly marked as a false positive.
[0131] The final review results output by the system not only include basic information about the vulnerability (code location, data flow path), but also include abnormal situation records captured during dynamic verification (such as the call stack, register state, and input values that caused the exception at the time of the crash), making it easier for developers to reproduce and locate the problem. At the same time, the system will match the built-in standardized repair template library (for example, automatically recommending the replacement of the insecure strcpy with strncpy and calculating the buffer length) to generate a repair code snippet that is provided with the report.
[0132] Furthermore, although the steps of the method in this disclosure are described in a specific order in the accompanying drawings, this does not require or imply that the steps must be performed in that specific order, or that all the steps shown must be performed to achieve the desired result. Additional or alternative steps may be omitted, multiple steps may be combined into one step, and / or a step may be broken down into multiple steps.
[0133] Embodiments of the present invention also provide a vulnerability discovery system based on an AI code review model, comprising: The multidimensional code semantic graph construction module is used to concurrently construct the abstract syntax tree (AST), control flow graph (CFG), and program dependency graph (PDG) of the source code, and to integrate the three into a unified code attribute graph (CPG) using isomorphic alignment technology.
[0134] The graph neural network detection engine is used to receive the CPG, extract multi-dimensional semantic features of nodes through message passing and aggregation mechanisms, and output potential vulnerability nodes and their associated paths.
[0135] A standardized vulnerability corpus and a dynamic attention module are used to store and retrieve standardized vulnerability feature templates for specific industries. The similarity score and dynamic attention weight between the current code block and the vulnerability feature template are calculated in real time to guide the graph neural network detection engine to focus on high-risk code regions.
[0136] A lightweight dynamic trajectory simulator is used to receive potential vulnerability paths identified by the graph neural network detection engine, construct and execute targeted test cases in a local isolation sandbox, and monitor runtime anomalies to verify the authenticity of the vulnerabilities.
[0137] The results output and visualization module is used to display the vulnerability location, data flow graph, verification status, and generate remediation suggestions.
[0138] While specific embodiments of the invention have been described in detail by way of examples, those skilled in the art should understand that the examples are for illustrative purposes only and are not intended to limit the scope of the invention. Those skilled in the art should also understand that various modifications can be made to the embodiments without departing from the scope and spirit of the invention.
Claims
1. A vulnerability discovery method based on an AI code review model, characterized in that, Includes the following steps: Obtain the source code to be reviewed and construct a multidimensional code semantic graph of the source code concurrently; the multidimensional code semantic graph includes an abstract syntax tree (AST), a control flow graph (CFG), and a program dependency graph (PDG); Using isomorphic alignment techniques, nodes in the AST, CFG, and PDG are aligned across graphs, using lines of code or abstract syntax nodes as anchors, and then merged to generate a unified code attribute graph (CPG). The CPG is formalized as a multi-relation attribute graph. ,in, This is the aligned set of core code nodes. A set of edge relation types, Let be the set of all heterogeneous edges; The CPG is input into the graph neural network (GNN), and through message passing and aggregation mechanisms, the features of each node in the CPG are iterated to obtain a node feature vector that integrates grammatical context, execution path features, and data pollution paths. During the model training or inference phase, a pre-built standardized vulnerability corpus is introduced; the corpus contains standardized vulnerability feature templates for specific industries, and the standardized vulnerability feature templates are transformed into an external knowledge graph. The dynamic attention module is used to extract the context feature vector of the current code block in real time and compare it with the vulnerability feature template in the external knowledge graph to calculate the dynamic attention weight, so as to adjust the model’s attention to suspected high-risk code segments. When a static AI model identifies a potential vulnerability node, it extracts the input source, data propagation path, and execution convergence point associated with the potential vulnerability and transmits them to a lightweight dynamic execution trajectory simulator. The lightweight dynamic execution trajectory simulator, in a local isolation sandbox, automatically constructs corresponding test cases for targeted probing based on the branch conditions on the extracted path, monitors the running status, and records abnormal feedback to verify the authenticity of the vulnerability and output the final review results.
2. The method according to claim 1, characterized in that, The isomorphic alignment technique includes: Using line numbers in the source code or node identifiers in the abstract syntax tree as anchors, establish mapping relationships between AST nodes, CFG basic block nodes, and PDG nodes; for nodes with different granularities, adopt node splitting or node merging strategies to ensure that cross-graph nodes maintain semantically consistent alignment units.
3. The method according to claim 1, characterized in that, The set of edge relationship types in the CPG It includes syntax topology edges, control flow edges, and data dependency edges; among them, syntax topology edges correspond to parent-child or sibling relationships in AST, control flow edges correspond to execution jump relationships in CFG, and data dependency edges correspond to definition-use relationships and data flow constraint relationships in PDG.
4. The method according to claim 1, characterized in that, The graph neural network (GNN) employs a multi-layer graph attention network or a graph isomorphic network. The message passing and aggregation process is represented as follows: ; in, Represents a node In the The feature vector of the layer, Represents a node In the CPG, the set of neighboring nodes, AGGREGATE is the aggregation function, and UPDATE is the update function; after... After rounds of iteration, the final node feature vector Fusion Topological semantic information of the neighborhood.
5. The method according to claim 1, characterized in that, The construction methods for the standardized vulnerability corpus include: Collect verified vulnerabilities from historical security incidents in specific industries, and extract the triggering conditions, pollution paths, and context of each verified vulnerability; The triggering conditions, pollution paths, and context of each verified vulnerability are transformed into structured vulnerability feature templates. Each vulnerability feature template includes at least a vulnerability type identifier, source point features, sink point features, and critical path constraints from source to sink. The external knowledge graph is constructed using vulnerability feature templates as nodes and similarity or co-occurrence relationships between templates as edges.
6. The method according to claim 1, characterized in that, The calculation process for the dynamic attention weights includes: Let the extracted code block context feature vector be... The first in the external knowledge graph The vector representation of a standardized vulnerability feature template is as follows: Calculate similarity score : ; in, For a learnable attention weight matrix, the superscript... Indicates vector transpose; The similarity score is normalized using the Softmax function to obtain the similarity score for the current code block. Dynamic attention weights for vulnerability feature templates : ; in, This represents the total number of vulnerability feature templates recorded in the external knowledge graph; the model is based on... The value adjusts the feature weights of the current code block and its associated control flow and data flow nodes.
7. The method according to claim 6, characterized in that, The similarity score In the calculation, the attention weight matrix Implemented through bilinear mapping, and During the model training phase, code samples labeled with vulnerability types are used to update parameters, so that code blocks that match known vulnerability patterns can obtain higher similarity scores.
8. The method according to claim 1, characterized in that, The lightweight dynamic execution trajectory simulator constructs test cases in a local isolation sandbox in the following way: Based on the high-probability vulnerability path from the Source point to the Sink point output by the static AI model, extract the conditional constraints at all branch nodes on the path; use symbolic execution or constraint solving techniques to solve for the input vector that satisfies the path reachability; perform targeted mutation on the variables involved in the path to generate multiple fuzzy test cases, including boundary values, malformed data structures, and empty characters, and inject them into the local sandbox for execution.
9. The method according to claim 1, characterized in that, The verification of the vulnerability's authenticity and the output of the final review result include: When the simulator catches a runtime exception during the execution of test cases, the suspected vulnerability is determined to be a confirmed vulnerability, and its risk confidence score is automatically increased. If none of the test cases trigger an exception, the corresponding risk confidence score is reduced or the case is marked as a false alarm. The final output includes the location of the vulnerability code, the data flow path, the verified exception scene record, and the repair code snippet generated based on the standardized repair template library.
10. A vulnerability discovery system based on an AI code review model, characterized in that, include: The multidimensional code semantic graph construction module is used to concurrently construct the abstract syntax tree (AST), control flow graph (CFG), and program dependency graph (PDG) of the source code, and to integrate the three into a unified code attribute graph (CPG) using isomorphic alignment technology. The graph neural network detection engine is used to receive the CPG, extract multi-dimensional semantic features of nodes through message passing and aggregation mechanisms, and output potential vulnerability nodes and their associated paths. A standardized vulnerability corpus and a dynamic attention module are used to store and retrieve standardized vulnerability feature templates for specific industries, and to calculate the similarity score and dynamic attention weight between the current code block and the vulnerability feature template in real time, so as to guide the graph neural network detection engine to focus on high-risk code regions. A lightweight dynamic trajectory simulator is used to receive potential vulnerability paths identified by the graph neural network detection engine, construct and execute targeted test cases in a local isolation sandbox, and monitor runtime anomalies to verify the authenticity of the vulnerabilities. The results output and visualization module is used to display the vulnerability location, data flow graph, verification status, and generate remediation suggestions.