A lightweight large model vulnerability detection method and system based on graph enhancement retrieval
By generating code attribute graphs and control flow graphs, and combining them with graph vector knowledge bases and vulnerability knowledge graphs, personalized prompt words are dynamically generated. This solves the problems of high false negative rates and insufficient structured perception capabilities in code vulnerability detection by lightweight large language models, and achieves efficient vulnerability detection.
Patent Information
- Application Number
- CN202611423149.X
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-09-14
- Publication Date
- 2026-11-24
AI Technical Summary
Existing lightweight large language models lack the ability to perceive program structure in code vulnerability detection, resulting in a high false negative rate. Traditional static analysis tools struggle to understand the deep semantics of code, and lightweight models are prone to producing illusions when detecting complex vulnerabilities.
By generating code attribute graphs, extracting control flow graphs, performing graph traversal and slicing, and serializing them into a text structured format, similarity retrieval and association reasoning are performed by combining graph vector knowledge base and vulnerability knowledge graph, and personalized prompt words are dynamically generated to drive a lightweight large language model for vulnerability detection.
It significantly improves the accuracy and recall rate of vulnerability detection, enhances the ability to identify complex vulnerabilities, provides a logical deduction process, and improves the credibility and usability of detection results.
Smart Images

Figure CN123158646A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of interdisciplinary technology of network security and artificial intelligence, specifically to a lightweight large-model vulnerability detection method and system based on graph augmentation retrieval. Background Technology
[0002] As software continues to grow in scale and complexity, software vulnerabilities pose a serious threat to network security. Among them, memory security vulnerabilities such as stack-based buffer overflows (e.g., CWE-121) have always been a key focus and challenge in the field of automated code auditing due to their strong concealment and destructive power.
[0003] Currently, existing vulnerability detection methods mainly face the following technical problems: (1) Limitations of traditional static analysis techniques: Traditional static application security testing (SAST) tools mainly rely on manually defined rules or pattern matching. Although such methods can extract the control flow or data flow structure of the program, they lack an understanding of the deep semantics of the code, and due to the solidification of rules, they are prone to generating a large number of false positives and easily miss complex logical vulnerabilities. (2) Shortcomings of large language models (LLM) in application: In recent years, large language models based on the Transformer architecture have been introduced into the field of code auditing. However, in actual engineering and edge computing scenarios where computing power resources are limited, only lightweight large models (e.g., 1.3B parameter scale) can usually be deployed. When lightweight large models directly process the original source code in plain text format, due to the large number of irrelevant identifiers and comment noise in the text sequence of the code, and the lack of explicit logical structure information, the model has difficulty in accurately perceiving the control flow direction and key check nodes (such as if statements for boundary checks). This makes lightweight models prone to "illusions" when detecting complex vulnerabilities, often resorting to probabilistic guessing rather than rigorous reasoning, resulting in extremely high false negative rates, and even complete failure. Summary of the Invention
[0004] To address the shortcomings of existing technologies, this invention provides a lightweight large-scale model vulnerability detection method and system based on graph augmentation retrieval. It solves the technical problems of existing lightweight large-scale language models, which are prone to producing illusions and having high false negative rates in code vulnerability detection due to a lack of program structure perception capabilities, as well as the technical problems of traditional static analysis tools relying on fixed rules and having difficulty understanding the deep semantics of code.
[0005] To achieve the above objectives, the present invention provides the following technical solution: a lightweight large-model vulnerability detection method and system based on graph augmentation retrieval, comprising the following steps: Obtain the target source code, parse the target source code using a static analysis platform to generate a code attribute graph, and extract the control flow graph from it; Locate potential risk functions in the target source code, perform graph traversal and slicing on the potential risk functions based on the control flow graph, extract the corresponding target control flow subgraph, and serialize the target control flow subgraph into a text structured format; The serialized target control flow subgraph is converted into a query vector, and a similarity search is performed in a pre-built graph vector knowledge base to obtain historical code cases that are similar to the target control flow subgraph structure. The historical code cases include vulnerability cases and fix cases. Based on a pre-built vulnerability knowledge graph, the retrieved historical code cases are correlated and inferred to obtain supplementary analysis cases related to the current vulnerability type; The search results are sorted and filtered using a multi-dimensional similarity weighted fusion strategy; By combining the target control flow subgraph with historical code cases obtained from retrieval, a search enhancement prompt keyword containing few-sample demonstrations and thought chain instructions is constructed; Dynamically generate personalized prompt word templates based on the vulnerability type and complexity characteristics of the target code; The search enhancement prompts are input into a lightweight large language model, which then uses this model to infer by comparing the structural differences of historical code cases, and outputs the vulnerability detection results of the target source code.
[0006] As a further aspect of the present invention: the potential risk function is a target function that contains calls to sensitive functions, including memory operation functions, string processing functions, and formatted output functions; The vulnerability knowledge graph is constructed in the following way: Extract vulnerability type entities, vulnerability cause entities, and remediation strategy entities from historical vulnerability datasets. The vulnerability type entities include buffer overflow, integer overflow, and format string vulnerabilities. The vulnerability cause entities include missing boundary checks and type conversion errors. The remediation strategy entities include adding length checks and using secure functions as alternatives. Parse vulnerability reports and code fix submission records to establish relationship edges between entities. These relationship edges include cause relationships, fix relationships, and association relationships. Cause relationships indicate that the cause of a vulnerability leads to the occurrence of a vulnerability type. Fix relationships indicate that a fix strategy can fix the corresponding vulnerability type. Association relationships indicate the correlation between different vulnerability types. All entities and their corresponding edges are stored as a graph structure to generate the vulnerability knowledge graph.
[0007] As a further aspect of the present invention: the multi-dimensional similarity includes control flow graph structure similarity, vulnerability type semantic similarity, and code context similarity, and the comprehensive similarity calculation formula is as follows: Similarity total =α×Sim structure+β×Sim semantic+γ×Sim context; Sim structure represents the control flow graph structural similarity, obtained by calculating the graph edit distance or subgraph isomorphic matching degree between the target control flow subgraph and the historical control flow subgraph; Sim semantic represents the vulnerability type semantic similarity, obtained by extracting vulnerability type labels from the target code and historical code and calculating the cosine similarity between their label vectors; Sim context represents the code context similarity, obtained by inputting the complete context of the target code and historical code into the code embedding model and calculating the cosine similarity between the resulting embedding vectors. α, β, and γ are weighting coefficients.
[0008] As a further aspect of the present invention, the specific method for dynamically generating personalized prompt word templates is as follows: Analyze the vulnerability types and complexity characteristics of the target code. The vulnerability type characteristics include the vulnerability types corresponding to the potentially risky functions, and the complexity characteristics include the number of control flow branches, function call depth, and number of basic blocks. Based on the analysis results, personalized prompt word templates are selected from the predefined prompt word template library. For buffer overflow vulnerabilities, prompt word templates containing inference instructions that the bootstrap model focuses on verifying the data length boundary conditions in the target code are selected. For integer overflow vulnerabilities, prompt word templates containing inference instructions that the bootstrap model focuses on verifying whether there is an overflow risk in arithmetic operations in the target code are selected. The selected prompt word template is combined with the corresponding reasoning instruction to generate a personalized prompt word template.
[0009] As a further aspect of the present invention, the thought chain reasoning includes the following three steps: The first step is execution path tracing: starting from the variable declaration node in the target control flow subgraph, trace along the directed edges of the control flow node by node to the sensitive function call node, and output the complete execution path sequence; The second step is constraint comparison and verification: the execution path of the target control flow subgraph is compared node by node with the control flow subgraph of the retrieved repair case to identify whether the target control flow subgraph is missing a key control flow node for data length verification. If the repair case has a condition judgment node for boundary check but the target subgraph does not have a corresponding node, it is determined that the key verification node is missing. The third step is to output the vulnerability conclusion: based on the missing key verification nodes, the vulnerability judgment result is output. If a key verification node is missing, it is determined that a vulnerability exists; otherwise, it is determined that no vulnerability exists. An explanation based on the code graph structure is also output, which includes information on the specific missing nodes and a description of the security risks they cause.
[0010] As a further aspect of the present invention, the graph vector knowledge base is pre-constructed in the following manner: Collect vulnerability samples and patch samples from historical software vulnerability datasets, extract control flow subgraphs in the same way as the target source code, and serialize them into text format; A pre-trained code embedding model is used to map the serialized historical subgraphs into high-dimensional graph vectors. All historical graph vectors are stored in a high-dimensional vector database and a similarity retrieval index is established to form the graph vector knowledge base. The similarity retrieval is performed using the K-nearest neighbor algorithm.
[0011] A lightweight large-model vulnerability detection system based on graph augmentation retrieval includes: The graph generation module is used to obtain the target source code and generate a control flow graph. The subgraph extraction and serialization module is used to extract the target control flow subgraph corresponding to the risk function and serialize it. The similarity retrieval module is used to match structurally similar historical code examples in the graph vector knowledge base; The knowledge graph reasoning module is used for association reasoning based on vulnerability knowledge graphs; The multi-dimensional fusion filtering module is used to sort and filter search results using a multi-dimensional similarity weighted fusion strategy; The dynamic prompt word generation module is used to generate personalized prompt words based on the characteristics of the target code; An enhanced generative reasoning module is used to construct enhanced search prompts and input them into a lightweight large language model for vulnerability determination.
[0012] As a further aspect of the present invention: the knowledge graph reasoning module includes: a knowledge graph construction unit, used to extract entities and relationships from historical vulnerability data to construct a vulnerability knowledge graph; The graph query reasoning unit is used to perform association queries and logical reasoning based on the vulnerability knowledge graph. The dynamic prompt word generation module includes: a feature analysis unit, used to analyze the vulnerability type and complexity characteristics of the target code; The template generation unit is used to generate personalized prompt word templates based on the feature analysis results.
[0013] A computer device includes a memory and a processor, the memory storing a computer program, characterized in that the processor executes the computer program to implement the steps of the method according to any one of claims 1 to 5.
[0014] A computer-readable storage medium having a computer program stored thereon, characterized in that, when the computer program is executed by a processor, it implements the steps of the method according to any one of claims 1 to 5.
[0015] This invention provides a lightweight method and system for detecting vulnerabilities in large models based on graph augmentation retrieval. Compared with existing technologies, it has the following advantages: (1) This invention does not require expensive parameter fine-tuning training of existing large language models. By injecting structured program control flow graph knowledge and historical vulnerability reference cases into the model, it can significantly stimulate the logical reasoning potential of lightweight large language models in deployment environments with severely limited computing power, greatly improve the accuracy and recall of vulnerability detection, and effectively overcome the technical defects of the model being prone to hallucination under the traditional pure text input method. (2) The present invention innovatively uses control flow graphs to structurally represent the target code and serializes it into a text format that retains complete topological information. This effectively removes redundant semantic noise in the source code and presents the actual execution path and key branch logic of the program to the large language model clearly and without distortion, which significantly enhances the ability to identify complex vulnerability types such as memory security vulnerabilities. (3) This invention constructs a two-way comparison sample by retrieving historical vulnerability cases and repair cases, and combines the thinking chain reasoning mechanism to guide the lightweight large language model to gradually compare the differences between the key security verification nodes between the target code and the repair code, so that the final vulnerability judgment result of the model not only contains clear conclusions, but also has a complete logical deduction process based on the code graph structure, which greatly enhances the credibility and usability of the detection results. (4) By constructing a vulnerability knowledge graph containing multiple entities such as vulnerability types, causes and repair strategies and their causal and relational relationships, and combining it with a multi-dimensional similarity weighted fusion strategy, the present invention not only makes the search results highly matched with the target code at the structural level, but also discovers hidden supplementary cases with similar types but different structures through the association reasoning of the knowledge graph, which significantly improves the quality and comprehensiveness of the search results. (5) The present invention dynamically generates personalized prompt word templates based on the vulnerability type and complexity characteristics of the target code, making the reasoning process more targeted, effectively avoiding the reasoning deviation problem caused by fixed templates, and further improving the detection accuracy of the model in various vulnerability types. Attached Figure Description
[0016] Figure 1 This is an overall flowchart of the method of the present invention; Figure 2 This is a schematic diagram of target code control flow subgraph extraction and serialization transformation provided in an embodiment of the present invention; Figure 3 This is a schematic diagram illustrating the graph vector knowledge base retrieval and enhanced prompt word construction process provided in an embodiment of the present invention; Figure 4 This is a schematic diagram illustrating the construction and association reasoning of a vulnerability knowledge graph provided in an embodiment of the present invention; Figure 5 This is a schematic diagram of the dynamic prompt word generation process provided in an embodiment of the present invention. Detailed Implementation
[0017] 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.
[0018] Example 1 Please see Figure 1 This application provides a lightweight large-model vulnerability detection method based on graph augmentation retrieval, including the following steps: Obtain the target source code, parse the target source code using a static analysis platform to generate a code attribute graph, and extract the control flow graph from it; Locate potential risk functions in the target source code, perform graph traversal and slicing on the potential risk functions based on the control flow graph, extract the corresponding target control flow subgraph, and serialize the target control flow subgraph into a text structured format; The serialized target control flow subgraph is converted into a query vector, and a similarity search is performed in a pre-built graph vector knowledge base to obtain historical code cases that are similar to the target control flow subgraph structure. The historical code cases include vulnerability cases and fix cases. Based on a pre-built vulnerability knowledge graph, the retrieved historical code cases are correlated and inferred to obtain supplementary analysis cases related to the current vulnerability type; The search results are sorted and filtered using a multi-dimensional similarity weighted fusion strategy; By combining the target control flow subgraph with historical code cases obtained from retrieval, a search enhancement prompt keyword containing few-sample demonstrations and thought chain instructions is constructed; Dynamically generate personalized prompt word templates based on the vulnerability type and complexity characteristics of the target code; The search enhancement prompts are input into a lightweight large language model, which then uses this model to infer by comparing the structural differences of historical code cases, and outputs the vulnerability detection results of the target source code.
[0019] Example 2 This embodiment provides a lightweight large-model vulnerability detection method based on graph augmentation retrieval, such as... Figure 1 As shown, the method specifically includes the following steps: Step S101: Obtain the target source code and parse the code attribute graph.
[0020] In this step, the target C / C++ source code to be tested is first obtained. The open-source static code analysis platform Joern is called to parse the obtained source code into a code property graph (CPG). CPG is a joint representation that includes three graph structures: abstract syntax tree (AST), control flow graph (CFG), and program dependency graph (PDG).
[0021] In order to focus on the execution logic of the program and effectively control the length of the data input to the large model, this embodiment focuses on extracting the edge relationships of the control flow graph from the CPG, including the jump relationships between basic blocks, conditional branch relationships, and function call relationships.
[0022] Specifically, the control flow graph uses basic blocks as nodes and the control transfer relationships between basic blocks as directed edges, which can completely reflect all possible paths in the program's execution process. For example, for a code segment containing if-else conditional statements, the control flow graph will draw two directed edges from the condition node, pointing to the execution paths of the true branch and the false branch respectively, thus completely preserving the program's branching logic in the form of a graph structure.
[0023] Step S102: Locating the potential risk function and slicing the control flow subgraph.
[0024] In the control flow graph extracted in step S101, target functions containing calls to specific sensitive functions are scanned and located, and marked as potentially risky functions. Sensitive functions include, but are not limited to: memory manipulation functions such as strcpy, sprintf, gets, memcpy, etc.; string processing functions such as strcat, strncat, etc.; and formatted output functions such as printf, sprintf, etc. These functions, lacking automatic boundary checking mechanisms, are prone to causing stack-based buffer overflow vulnerabilities.
[0025] As a preferred embodiment of the present invention, a graph traversal query language, such as the Cypher query language provided by the Joern platform, is used to perform context slicing on the marked potential risk functions.
[0026] Specifically, starting from the node where the sensitive function call originates and ending at the node where the variable allocation within that function begins, the control flow graph is traversed in reverse order to extract a local control flow subgraph from the variable allocation start point to the sensitive function call endpoint. This subgraph preserves all control flow paths that affect the sensitive function call during the execution of the risky function, including any possible boundary check branches.
[0027] Step S103: Target control flow subgraph serialization.
[0028] Since large language models cannot directly process the topology of graphs, this step requires converting the local control flow subgraph extracted in step S102 into a text format that large language models can understand.
[0029] like Figure 2 As shown: This invention serializes local control flow subgraphs into DOT language format. DOT language is a plain text graph description language that can fully describe the node and edge relationships of a graph in a structured text format.
[0030] Specifically, each basic block node in the control flow subgraph is mapped to a node declaration in the DOT language. Each node contains a node identifier and node label, such as assignment operation, memory allocation operation, condition judgment, function call, etc. The directed control flow edges between basic blocks are mapped to edge declarations in the DOT language. Each edge identifies the flow relationship of the execution order.
[0031] For example, for a piece of risky code that contains a strcpy call, its corresponding control flow subgraph, after being serialized into DOT format, will clearly show the complete execution path: variable declaration node, length calculation node, condition judgment node (if len> boundary value), and function call node (strcpy).
[0032] Step S104: Pre-construction of graph vector knowledge base and similarity retrieval.
[0033] This step is divided into two sub-steps: the pre-construction stage of the graph vector knowledge base and the online retrieval stage.
[0034] The pre-construction of the graph vector knowledge base involves several steps. First, a large number of historical vulnerability samples and fixes are collected from historical software vulnerability datasets, such as NIST SARD and CVE vulnerability databases. For each historical sample, its source code is parsed and the control flow subgraph is extracted, then serialized into DOT format text, following the same procedure as steps S101 to S103. Next, pre-trained code embedding models, such as CodeBERT and UnixCoder, are used to map the serialized historical subgraph text into high-dimensional graph vectors. Finally, all historical graph vectors are stored in high-dimensional vector databases, such as FAISS and Milvus, and an efficient similarity retrieval index is built using clustering or indexing structures, thus forming the graph vector knowledge base.
[0035] Online similarity search, such as Figure 3 As shown, during the detection phase, the DOT format subgraph obtained by transforming the current target source code through steps S101 to S103 is mapped to a query vector using the same code embedding model. Then, in the pre-built graph vector knowledge base, the K-nearest neighbor algorithm is used for similarity calculation and retrieval.
[0036] Set the search quantity K=3, and retrieve the K historical code cases that are most similar to the current target subgraph structure. Each historical code case contains a corresponding vulnerability case (Vulnerable) and a fixed case (Fixed), forming a reference sample pair for vulnerability remediation. The vulnerability case is the source code with the vulnerability and its corresponding control flow subgraph, and the fixed case is the source code and its corresponding control flow subgraph after fixing the same vulnerability.
[0037] Step S104a: Construction and correlation reasoning of vulnerability knowledge graph.
[0038] like Figure 4 As shown, this step, as a supplement and enhancement to step S104, expands the coverage of the retrieval results through the association reasoning of the knowledge graph.
[0039] Vulnerability knowledge graph pre-construction: Extract the following three types of entity nodes from historical vulnerability datasets: Vulnerability type entities, such as buffer overflow, integer overflow, format string vulnerability, use after release, etc.; Vulnerability-causing entities, such as lack of boundary checks, type conversion errors, insufficient memory allocation due to integer overflow, and failure to set memory to null after deallocation; Repair strategy entities, such as adding length checks, using safe functions as replacements, such as replacing strcpy with strncpy, and adding boundary check branches.
[0040] Based on this, by analyzing historical vulnerability reports and code fix submission records, relationships between entities are established.
[0041] Specifically, the relationship edges include, but are not limited to, the following types: cause relationship (cause entity → vulnerability type entity, indicating that a certain cause leads to the occurrence of a certain type of vulnerability), remediation relationship (remediation strategy entity → vulnerability type entity, indicating that a certain remediation strategy can fix a certain type of vulnerability), and association relationship (between different vulnerability type entities, indicating the interrelationship between different vulnerability types, such as integer overflow leading to buffer overflow). All entities and relationship edges are stored as a graph structure to generate a vulnerability knowledge graph.
[0042] Association Reasoning: After retrieving historical code cases in step S104, the vulnerability type tags involved in these cases are extracted. Then, using these vulnerability type tags as query conditions, graph queries and association reasoning are performed in the pre-built vulnerability knowledge graph.
[0043] Specifically, by using the correlation edges in the graph, other vulnerability types associated with the current vulnerability type and their corresponding analysis cases are obtained as supplementary analysis cases.
[0044] For example, when a buffer overflow vulnerability is detected, a knowledge graph can be used to link it to buffer overflow cases caused by integer overflows, thereby providing the model with a more comprehensive analytical perspective and avoiding the omission of related security risk patterns due to the retrieval of a single type of case.
[0045] Step S104b: Multi-dimensional similarity fusion and filtering.
[0046] This step uses multi-dimensional similarity weighted fusion to reorder and filter the preliminary search results from step S104.
[0047] Specifically, multi-dimensional similarity includes the following three dimensions: Control flow graph structural similarity (Sim structure) is measured by calculating the graph edit distance or subgraph isomorphic matching degree between the target control flow subgraph and historical control flow subgraphs. The smaller the graph edit distance, the more similar the structures of the two graphs are.
[0048] Sentence similarity (Sim semantic): This is measured by extracting vulnerability type labels from the target code and historical code, and then calculating the cosine similarity between their label vectors.
[0049] Sim context similarity is measured by calculating the cosine similarity between the resulting embedding vectors by inputting the complete context of the target code and the historical code into the code embedding model.
[0050] The total similarity score is calculated using the following weighted formula: Similarity total =α×Sim structure+β×Sim semantic+γ×Sim context Wherein, α, β, and γ are weight coefficients, with values of α=0.5, β=0.3, and γ=0.2. Based on the calculated comprehensive similarity, the search results in step S104 are sorted in descending order, and the top N (preferably N=3) most relevant cases are selected as the final search results.
[0051] Step S105: Dynamic prompt word construction and large model inference judgment.
[0052] This step is the core reasoning step of the method of this invention, such as... Figure 5 As shown, the specific steps include the following: Code Feature Analysis: First, the target code is analyzed to extract the following feature information: (1) Vulnerability type characteristics, that is, the vulnerability type corresponding to the potential risk function located in step S102, such as buffer overflow, integer overflow, format string vulnerability, etc.; (2) Complexity features, including the number of control flow branches, i.e., the number of condition judgment nodes, the function call depth, i.e., the number of nested function calls, the number of basic blocks, etc. These features will be used for subsequent personalized template selection.
[0053] Personalized template generation: Based on the results of code feature analysis, personalized prompt word templates are generated by selecting or combining them from a predefined prompt word template library. This predefined template library stores dedicated inference instruction templates for different vulnerability types.
[0054] Specifically: For buffer overflow vulnerabilities, generate prompt word templates emphasizing boundary check logic to guide the model to focus on whether there are conditional judgment nodes for length verification in the target subgraph; for integer overflow vulnerabilities, generate prompt word templates emphasizing arithmetic operation verification logic to guide the model to focus on whether there are overflow checks before and after arithmetic operations; for format string vulnerabilities, generate prompt word templates emphasizing format parameter verification.
[0055] Few-shot suggestion assembly: The historical vulnerability cases and remediation cases selected in step S104b are used as comparison samples for the few-shot demonstration. Combined with the control flow subgraph of the current target (DOT format text) and the generated personalized template, they are assembled into complete search enhancement suggestions.
[0056] By embedding Chain-of-Thought (CoT) instructions into the prompts, lightweight large language models such as DeepSeek-Coder-1.3B and CodeLlama-1.3B are required to perform step-by-step reasoning in the following three steps: The first step is execution path tracing: the model is required to start from the variable declaration node of the target control flow subgraph, trace along the directed edges of the control flow node by node to the sensitive function call node, and output the complete execution path sequence.
[0057] The second step is constraint comparison and verification: The model is required to compare the execution path of the target control flow subgraph with the control flow subgraph of the retrieved repair cases node by node to identify whether the target subgraph is missing key control flow nodes used for data length verification, such as if conditional branch nodes. Specifically, if the repair case has an if node for boundary checks but the target subgraph does not have a corresponding node, it is determined that a key verification node is missing.
[0058] The third step is to output the vulnerability conclusion: the model is required to output the final vulnerability judgment result (vulnerability exists / vulnerability does not exist) based on the missing key verification nodes, and provide an explanation based on the code graph structure, including the specific node information and a description of the potential security risks.
[0059] Guided by prompts, the lightweight large language model performs the above three-step reasoning and finally outputs the vulnerability detection results of the target source code, including whether a vulnerability exists, the type of vulnerability, the location of the vulnerability, and a graph-based explanation.
[0060] Example 3 This embodiment provides a lightweight large-model vulnerability detection system based on graph augmentation retrieval, which corresponds to the method in Embodiment 2 and is applied to implement the method in Embodiment 2.
[0061] The system includes the following modules: The graph generation module is used to obtain the target source code, parse the target source code through a static analysis platform and generate a code attribute graph, from which the control flow graph is extracted.
[0062] The subgraph extraction and serialization module is used to locate potential risk functions in the target source code. Based on the control flow graph, it performs graph traversal and slicing on the potential risk functions, extracts the corresponding target control flow subgraph, and serializes the target control flow subgraph into a text structured format.
[0063] The similarity retrieval module is used to convert the serialized target control flow subgraph into a query vector and match historical code cases with similar structures to the target control flow subgraph in a pre-built graph vector knowledge base. This module includes a vector transformation unit and a K-nearest neighbor retrieval unit.
[0064] The knowledge graph reasoning module is used to perform correlation reasoning on retrieved historical code cases based on a pre-built vulnerability knowledge graph, obtaining supplementary analysis cases related to the current vulnerability type. This module includes: a knowledge graph construction unit, used to extract vulnerability type entities, vulnerability cause entities, remediation strategy entities, and the cause, remediation, and correlation relationships between entities from historical vulnerability data to construct a vulnerability knowledge graph; and a graph query reasoning unit, used to perform correlation queries and logical reasoning based on the vulnerability knowledge graph.
[0065] The multi-dimensional fusion filtering module is used to sort and filter search results by controlling the weighted fusion of flow graph structure similarity, vulnerability type semantic similarity, and code context similarity.
[0066] The dynamic vulnerability warning generation module generates personalized vulnerability warning templates based on the vulnerability type and complexity characteristics of the target code. This module includes: a feature analysis unit, used to analyze the vulnerability type and complexity characteristics of the target code; and a template generation unit, used to select or combine from a predefined template library to generate personalized vulnerability warning templates based on the feature analysis results.
[0067] The enhanced generative reasoning module combines the target control flow subgraph with retrieved historical code cases to construct enhanced search suggestions with few-sample demonstrations and thought chain instructions. These suggestions are then input into a lightweight large language model to complete vulnerability determination.
[0068] Example 4 This embodiment provides a computer device, including a memory and a processor. The memory stores a computer program, and when the processor executes the computer program, it implements all the steps of the lightweight large model vulnerability detection method based on graph augmentation retrieval in Embodiment 1.
[0069] Example 5 This embodiment provides a computer-readable storage medium storing a computer program. When executed by a processor, the computer program implements all the steps of the lightweight large-model vulnerability detection method based on graph augmentation retrieval in Embodiment 1. The computer-readable storage medium can be any form of non-volatile storage medium, such as a disk, optical disk, flash memory, read-only memory (ROM), or random access memory (RAM).
[0070] Some of the data in the above formulas are numerical calculations with dimensions removed, and the contents not described in detail in this specification are all prior art known to those skilled in the art.
[0071] The above embodiments are only used to illustrate the technical methods of the present invention and are not intended to limit it. Although the present invention has been described in detail with reference to preferred embodiments, those skilled in the art should understand that modifications or equivalent substitutions can be made to the technical methods of the present invention without departing from the spirit and scope of the technical methods of the present invention.
Claims
1. A lightweight large-model vulnerability detection method based on graph augmentation retrieval, characterized in that, Includes the following steps: Obtain the target source code, parse the target source code using a static analysis platform to generate a code attribute graph, and extract the control flow graph from it; Locate potential risk functions in the target source code, perform graph traversal and slicing on the potential risk functions based on the control flow graph, extract the corresponding target control flow subgraph, and serialize the target control flow subgraph into a text structured format; The serialized target control flow subgraph is converted into a query vector, and a similarity search is performed in a pre-built graph vector knowledge base to obtain historical code cases that are similar to the target control flow subgraph structure. The historical code cases include vulnerability cases and fix cases. Based on a pre-built vulnerability knowledge graph, the retrieved historical code cases are correlated and inferred to obtain supplementary analysis cases related to the current vulnerability type; The search results are sorted and filtered using a multi-dimensional similarity weighted fusion strategy; By combining the target control flow subgraph with historical code cases obtained from retrieval, a search enhancement prompt keyword containing few-sample demonstrations and thought chain instructions is constructed; Dynamically generate personalized prompt word templates based on the vulnerability type and complexity characteristics of the target code; The search enhancement prompts are input into a lightweight large language model, which then uses this model to infer by comparing the structural differences of historical code cases, and outputs the vulnerability detection results of the target source code.
2. The lightweight large model vulnerability detection method based on graph augmentation retrieval according to claim 1, characterized in that, The potential risk function is a target function that contains calls to sensitive functions, including memory operation functions, string processing functions, and formatted output functions; The vulnerability knowledge graph is constructed in the following way: Extract vulnerability type entities, vulnerability cause entities, and remediation strategy entities from historical vulnerability datasets. The vulnerability type entities include buffer overflow, integer overflow, and format string vulnerabilities. The vulnerability cause entities include missing boundary checks and type conversion errors. The remediation strategy entities include adding length checks and using secure functions as alternatives. Parse vulnerability reports and code fix submission records to establish relationship edges between entities. These relationship edges include cause relationships, fix relationships, and association relationships. Cause relationships indicate that the cause of a vulnerability leads to the occurrence of a vulnerability type. Fix relationships indicate that a fix strategy can fix the corresponding vulnerability type. Association relationships indicate the correlation between different vulnerability types. All entities and their corresponding edges are stored as a graph structure to generate the vulnerability knowledge graph.
3. The lightweight large model vulnerability detection method based on graph augmentation retrieval according to claim 1, characterized in that, The multi-dimensional similarity includes control flow graph structure similarity, vulnerability type semantic similarity, and code context similarity. The comprehensive similarity calculation formula is as follows: Similarity total =α×Sim structure+β×Sim semantic+γ×Sim context; Sim structure represents the control flow graph structural similarity, obtained by calculating the graph edit distance or subgraph isomorphic matching degree between the target control flow subgraph and the historical control flow subgraph; Sim semantic represents the vulnerability type semantic similarity, obtained by extracting vulnerability type labels from the target code and historical code and calculating the cosine similarity between their label vectors; Sim context represents the code context similarity, obtained by inputting the complete context of the target code and historical code into the code embedding model and calculating the cosine similarity between the resulting embedding vectors. α, β, and γ are weighting coefficients.
4. The lightweight large model vulnerability detection method based on graph augmentation retrieval according to claim 1, characterized in that, The specific method for dynamically generating personalized prompt word templates is as follows: Analyze the vulnerability types and complexity characteristics of the target code. The vulnerability type characteristics include the vulnerability types corresponding to the potentially risky functions, and the complexity characteristics include the number of control flow branches, function call depth, and number of basic blocks. Based on the analysis results, personalized prompt word templates are selected from the predefined prompt word template library. For buffer overflow vulnerabilities, prompt word templates containing inference instructions that the bootstrap model focuses on verifying the data length boundary conditions in the target code are selected. For integer overflow vulnerabilities, prompt word templates containing inference instructions that the bootstrap model focuses on verifying whether there is an overflow risk in arithmetic operations in the target code are selected. The selected prompt word template is combined with the corresponding reasoning instruction to generate a personalized prompt word template.
5. A lightweight large-model vulnerability detection method based on graph augmentation retrieval according to claim 1, characterized in that, The thought chain reasoning includes the following three steps: The first step is execution path tracing: starting from the variable declaration node in the target control flow subgraph, trace along the directed edges of the control flow node by node to the sensitive function call node, and output the complete execution path sequence; The second step is constraint comparison and verification: the execution path of the target control flow subgraph is compared node by node with the control flow subgraph of the retrieved repair case to identify whether the target control flow subgraph is missing a key control flow node for data length verification. If the repair case has a condition judgment node for boundary check but the target subgraph does not have a corresponding node, it is determined that the key verification node is missing. The third step is to output the vulnerability conclusion: based on the missing key verification nodes, the vulnerability judgment result is output. If a key verification node is missing, it is determined that a vulnerability exists; otherwise, it is determined that no vulnerability exists. An explanation based on the code graph structure is also output, which includes information on the specific missing nodes and a description of the security risks they cause.
6. The lightweight large model vulnerability detection method based on graph augmentation retrieval according to claim 1, characterized in that, The graph vector knowledge base is pre-built in the following way: Collect vulnerability samples and patch samples from historical software vulnerability datasets, extract control flow subgraphs in the same way as the target source code, and serialize them into text format; A pre-trained code embedding model is used to map the serialized historical subgraphs into high-dimensional graph vectors. All historical graph vectors are stored in a high-dimensional vector database and a similarity retrieval index is established to form the graph vector knowledge base. The similarity retrieval is performed using the K-nearest neighbor algorithm.
7. A lightweight large-model vulnerability detection system based on graph augmentation retrieval, characterized in that, include: The graph generation module is used to obtain the target source code and generate a control flow graph. The subgraph extraction and serialization module is used to extract the target control flow subgraph corresponding to the risk function and serialize it. The similarity retrieval module is used to match structurally similar historical code examples in the graph vector knowledge base; The knowledge graph reasoning module is used for association reasoning based on vulnerability knowledge graphs; The multi-dimensional fusion filtering module is used to sort and filter search results using a multi-dimensional similarity weighted fusion strategy; The dynamic prompt word generation module is used to generate personalized prompt words based on the characteristics of the target code; An enhanced generative reasoning module is used to construct enhanced search prompts and input them into a lightweight large language model for vulnerability determination.
8. A lightweight large-model vulnerability detection system based on graph augmentation retrieval according to claim 7, characterized in that, The knowledge graph reasoning module includes: a knowledge graph construction unit, used to extract entities and relationships from historical vulnerability data to construct a vulnerability knowledge graph; The graph query reasoning unit is used to perform association queries and logical reasoning based on the vulnerability knowledge graph. The dynamic prompt word generation module includes: a feature analysis unit, used to analyze the vulnerability type and complexity characteristics of the target code; The template generation unit is used to generate personalized prompt word templates based on the feature analysis results.
9. A computer device comprising a memory and a processor, wherein the memory stores a computer program, characterized in that, When the processor executes a computer program, it implements the steps of the method according to any one of claims 1 to 5.
10. A computer-readable storage medium having a computer program stored thereon, characterized in that, When the computer program is executed by a processor, it implements the steps of the method according to any one of claims 1 to 5.
