Source code bug repairing method, electronic equipment and storage medium
By generating vulnerability context feature vectors and code generation models, the problem of insufficient intelligence and automation in vulnerability repair in existing technologies is solved, achieving efficient and accurate source code repair with self-learning capabilities.
Patent Information
- Application Number
- CN202610034115.5
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-01-12
- Publication Date
- 2026-02-06
AI Technical Summary
Existing technologies have low levels of intelligence and insufficient automation in software security vulnerability repair, making it difficult to generate syntactically correct and context-appropriate repair code, and resulting in faulty patches or incomplete repairs.
By parsing source code to generate vulnerability context feature vectors, using graph neural network models to understand vulnerability semantics, and combining a vulnerability-remediation knowledge base and code generation model, candidate remediation code is generated and evaluated, thus achieving an automated and intelligent remediation process.
It significantly improves the automation and accuracy of vulnerability remediation, ensures that the remediation code is syntactically correct and context-appropriate, and has self-learning capabilities, thereby improving the reliability and security of the remediation.
Smart Images

Figure CN121479795A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of vulnerability repair technology, and in particular to a source code vulnerability repair method, electronic device, and storage medium. Background Technology
[0002] With the increasing complexity and accelerated iteration of software systems, automated remediation of software security vulnerabilities has become a key technology for ensuring the security of the software supply chain and improving response efficiency. Current mainstream automated vulnerability remediation solutions mainly rely on static analysis, predefined remediation templates, and pattern matching. However, these solutions have significant limitations in terms of intelligence, adaptability, and reliability: First, their intelligence level is low, failing to understand the deep semantic context of vulnerabilities. This results in rigid remediation strategies, difficulty in handling complex and ever-changing logical vulnerabilities, and a tendency to generate faulty patches or incomplete remediation, with accuracy needing improvement. Second, their automation level is insufficient. Most solutions can only provide remediation suggestions or perform only shallow keyword matching during remediation, failing to directly generate syntactically correct and context-appropriate remediation code, still requiring manual intervention from developers to complete the closed loop.
[0003] Therefore, there is an urgent need to provide a source code vulnerability repair method with a high level of intelligence that can significantly improve the automation level and accuracy of vulnerability repair. Summary of the Invention
[0004] To address the aforementioned technical problems, this invention provides a source code vulnerability repair method, electronic device, and storage medium, which can deeply understand vulnerability semantics and perform intelligent reasoning to generate syntactically correct and context-appropriate repair code, significantly improving the automation level and accuracy of vulnerability repair.
[0005] According to a first aspect of the present invention, a method for fixing source code vulnerabilities is provided, comprising the following steps: S1 parses the source code containing the vulnerability to obtain an abstract syntax tree and a control flow graph. Based on the abstract syntax tree, the control flow graph, and the corresponding vulnerability location information, a given graph neural network model is used to extract the semantic representation of the vulnerability context and generate a vulnerability context feature vector.
[0006] S2, Based on the vulnerability context feature vector, determine the historical vulnerability remediation cases corresponding to the vulnerability context feature vector from the pre-built vulnerability-remediation knowledge base; the vulnerability-remediation knowledge base stores several historical vulnerability remediation cases.
[0007] S3 generates structured suggestions based on vulnerability context feature vectors and retrieved historical vulnerability remediation cases, and inputs them into a pre-trained code generation model so that the code generation model can generate a set of candidate remediation codes corresponding to the source code.
[0008] S4. Evaluate each candidate repair code in the candidate repair code set and select the optimal repair code to automatically repair the source code vulnerability.
[0009] According to a second aspect of the present invention, a non-transitory computer-readable storage medium is provided, wherein at least one instruction or at least one program is stored therein, the at least one instruction or the at least one program being loaded and executed by a processor to implement the above-described source code vulnerability repair method.
[0010] According to a third aspect of the present invention, an electronic device is provided, including a processor and the aforementioned non-transitory computer-readable storage medium.
[0011] The present invention has at least the following beneficial effects: This invention provides a source code vulnerability remediation method. First, an abstract syntax tree (AST) and control flow graph (CLP) are obtained from the source code containing the vulnerability. Combined with vulnerability location information, a graph neural network model is used to generate vulnerability context feature vectors. By constructing the AST and CLP, the business logic of the source code can be determined. The generated vectors encode the complete contextual semantics of the vulnerability, providing a reliable data foundation for subsequent accurate retrieval and intelligent generation. Next, historical vulnerability remediation cases corresponding to the vulnerability context feature vectors are identified from a vulnerability-remediation knowledge base. This process overcomes the limitations of traditional keyword matching and facilitates case-based analogical reasoning. Then, the vulnerability context feature vectors and corresponding historical vulnerability remediation cases are input into a code generation model, outputting a set of candidate remediation codes corresponding to the source code. This process employs intelligent reasoning, rather than simple template filling, guiding the model to creatively generate multiple syntactically correct remediation schemes that fit the current vulnerability context, achieving true code generation and adaptation. Finally, each candidate remediation code is evaluated, and the optimal remediation code is selected for automated remediation of the source code vulnerability. This process uses multi-dimensional indicators for comprehensive evaluation and ranking, significantly improving the automation level, reliability, and security of the final remediation scheme while ensuring the correctness of the remediation. Attached Figure Description
[0012] 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.
[0013] Figure 1 A flowchart of a source code vulnerability repair method provided in an embodiment of the present invention. Detailed Implementation
[0014] 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.
[0015] This invention provides a method for fixing source code vulnerabilities, such as... Figure 1 As shown, the method includes the following steps: S1 involves parsing the vulnerable source code to obtain an abstract syntax tree (AST) and a control flow graph (CLP). Based on the AST, CLP, and corresponding vulnerability location information, a given graph neural network model is used to extract the semantic representation of the vulnerability context, generating a vulnerability context feature vector. In practice, a parser is used to parse the vulnerable source code into mature, existing technologies. For example, modern compilers such as GCC and Roslyn, or language parsing tools such as ANTLR and Java's JDT module, all have built-in functions for parsing source code into ASTs. Existing tools such as Soot for Java and the CodeQL engine can automatically generate a CLP after parsing the source code.
[0016] Specifically, the given graph neural network model is the GNN model.
[0017] Specifically, step S1 includes the following steps: S101, based on the vulnerability points in the source code, maps the corresponding vulnerability location information from the abstract syntax tree and the control flow graph respectively; it can be understood as: the vulnerability points in the source code are the node locations of the vulnerability in the source code.
[0018] S102, the abstract syntax tree, control flow graph, and corresponding vulnerability location information are input into the given graph neural network model, so that the given graph neural network model aggregates the node information in the abstract syntax tree and control flow graph through the message passing mechanism; it can be understood that the given graph neural network model aggregates the global syntax and structure information corresponding to the source code.
[0019] S103 injects vulnerability location information as initial features or attention weights into a given graph neural network model to generate a vulnerability context feature vector corresponding to the source code; this can be understood as: the vulnerability context feature vector is a high-dimensional, numerical vulnerability depth representation vector that encodes the global syntax, structure, and complete contextual semantics of the vulnerability.
[0020] In practical implementation, when using vulnerability location information as initial features as input, when constructing the initial features of the nodes in the graph, for nodes marked as vulnerability points in the abstract syntax tree or the basic block nodes corresponding to vulnerabilities in the control flow graph, a special dimension representing the vulnerability type or the existence of a vulnerability is added to the feature vector. When using vulnerability location information as attention weights as input, the vulnerability location information serves as an attention-guiding signal; for example, in a given graph neural network model, it makes the model pay more attention to message propagation paths originating from or reaching the vulnerability point.
[0021] As described above, by obtaining the abstract syntax tree and control flow graph, the syntactic structure and execution logic of the source code can be obtained. Based on this, combined with precise vulnerability location information, a high-dimensional context vector is generated. This vector encodes the complete contextual semantics of the vulnerability, enabling the system to deeply understand the semantics. This method transforms discrete code and vulnerability information into a unified semantic representation that can be understood by the machine, providing a reliable data foundation for subsequent accurate retrieval and intelligent generation.
[0022] S2, Based on the vulnerability context feature vector, determine the historical vulnerability remediation cases corresponding to the vulnerability context feature vector from the pre-built vulnerability-remediation knowledge base; the vulnerability-remediation knowledge base stores several historical vulnerability remediation cases.
[0023] Specifically, step S2 includes the following steps: S201, calculate the semantic similarity between the vulnerability context feature vector and the historical vulnerability context feature vector in each historical vulnerability remediation case; for example, calculate the cosine similarity between the vulnerability context feature vector and each historical vulnerability context feature vector.
[0024] Each historical vulnerability remediation case includes a historical vulnerability code snippet, a corresponding remediated code snippet, and a historical vulnerability context feature vector corresponding to the historical vulnerability code snippet.
[0025] S202, the historical vulnerability repair case with the highest corresponding semantic similarity is taken as the historical vulnerability repair case corresponding to the determined vulnerability context feature vector.
[0026] The above method performs efficient similarity matching between the semantic vector of the current vulnerability and historical vulnerability repair cases. The retrieved historical vulnerability repair cases are the most similar historical cases at the semantic level. This method breaks through the limitations of traditional keyword matching, that is, simple matching that is not literal, and realizes case-based analogical reasoning, which can draw accurate repair strategy references from massive historical experience.
[0027] S3 generates structured suggestions based on vulnerability context feature vectors and retrieved historical vulnerability remediation cases, and inputs them into a pre-trained code generation model so that the code generation model can generate a set of candidate remediation codes corresponding to the source code.
[0028] Specifically, code generation models can be based on Transformer, such as CodeT5 and InCoder.
[0029] As mentioned above, the code big model, based on its deep understanding of code syntax and semantics, automatically infers and generates repair code according to the questions and cases in the prompts. This process is not a simple template filling, but rather guides the model to integrate the current vulnerability issues with historical experience, creatively generating multiple syntactically correct repair solutions that are adapted to the current vulnerability context, thus achieving true code generation and adaptation.
[0030] S4. Evaluate each candidate repair code in the candidate repair code set and select the optimal repair code to automatically repair the source code vulnerability.
[0031] In one specific embodiment, step S4 includes the following steps: S401, for each candidate repair code in the candidate repair code set, a compilation test and a preset regression test are performed sequentially. Based on the test results, candidate repair codes that pass the tests are selected. This can be understood as: selecting repair codes that are syntactically correct and do not introduce functional regressions. Specifically, the compilation test is used to verify whether the generated candidate repair code is syntactically and semantically correct, that is, whether the candidate repair code can be successfully accepted by the compiler or interpreter of the programming language without producing compilation errors or interpreter syntax errors. In specific implementation, the source code file containing the candidate repair code is submitted to the standard compiler of the corresponding language, such as gcc, javac, etc., for construction. Regression testing is used to verify the functional correctness of candidate fixes. Its core purpose is to ensure that the fix does not break the original correct functionality of the program, i.e., it does not introduce functional regression. During implementation, a pre-defined test suite is run, and the test results before and after the fix are compared. Tests that passed before the fix must still pass after the fix. Automatically generated code may have the following problems: over-fixing, such as modifying code unrelated to the vulnerability, causing other functions to malfunction; inaccurate fixing, such as patching the vulnerability but changing interface behavior or algorithm logic; and side effects, such as introducing concurrency issues, performance degradation, or resource leaks. Regression testing effectively captures these problems, ensuring the correctness of the fix and minimizing its impact.
[0032] S402, for each candidate code patch that passes the test, calculate the evaluation scores of the candidate code patch in three dimensions: code style consistency, code complexity, and patch minimization principle. In specific implementation, when obtaining the code style consistency evaluation score S1, the candidate code patch and several code files randomly sampled from the project corresponding to the source code are parsed, several preset style feature vectors are extracted, and the mean cosine similarity between the style feature vector corresponding to the candidate code patch and the style feature vector corresponding to the several code files is calculated. The calculation result is used as the code style consistency evaluation score. Among them, the several preset style feature vectors include lexical features such as identifier naming patterns, constant naming patterns, layout features such as line length distribution, operator spacing habits, tab characters and width, and comment features such as comment density and comment position patterns.
[0033] Furthermore, the calculation steps for the code complexity evaluation score S2 are as follows: Based on the control flow graph corresponding to the constructed candidate repair code, the cyclomatic complexity of the candidate repair code is calculated; whereby the cyclomatic complexity satisfies the following condition: C = E - N + 2P, where C is the cyclomatic complexity, E and N are the number of edges and nodes in the control flow graph corresponding to the candidate repair code, respectively, and P is the number of connected components, which is usually set to 1.
[0034] Based on the cyclomatic complexity and the preset maximum complexity threshold, the code complexity evaluation score S2 is calculated; wherein the code complexity evaluation score S2 meets the following conditions: S2=1-C / C max , where C max This is a preset maximum complexity threshold.
[0035] Preferably, the calculation steps for the evaluation score S3 of the patch minimization principle are as follows: S4021, construct the abstract syntax tree corresponding to the candidate repair code, and calculate the degree of difference between the abstract syntax tree corresponding to the source code and the abstract syntax tree corresponding to the candidate repair code; where the degree of difference is represented by the edit distance; it can be understood that the edit distance refers to the minimum number of nodes that need to be inserted, deleted and updated in the original abstract syntax tree.
[0036] S4022, Based on the degree of difference and the preset maximum tolerable difference, the evaluation score S3 of the patch minimization principle is calculated; wherein, the evaluation score S3 of the patch minimization principle meets the following conditions: S3 = 1 - D / D max Where D represents the degree of difference between the abstract syntax tree corresponding to the source code and the abstract syntax tree corresponding to the candidate fix code. max This is the preset maximum tolerance difference.
[0037] S403, normalize the evaluation scores of each candidate repair code that passes the test in the three dimensions, and perform weighted fusion based on the preset weight coefficients corresponding to each dimension to calculate the comprehensive quality score corresponding to each candidate repair code that passes the test; it can be understood that: in each dimension, the evaluation score of the candidate repair code corresponding to the dimension is normalized to between 0 and 1, for example, min(1, S3) is used as the normalization result of S3, or the min-max normalization method is used, which will not be elaborated here.
[0038] Preferably, W1 < W2 < W3, and W3 > 0.5, where W1 is the preset weight coefficient corresponding to code style consistency, W2 is the preset weight coefficient corresponding to code complexity, and W3 is the preset weight coefficient corresponding to the patch minimization principle.
[0039] Since the principle of patch minimization aims to fix only vulnerabilities without making any irrelevant changes, it directly relates to the security and correctness of the fix, ensuring the accuracy and security of the fix, which is the primary prerequisite for the patching process. Code complexity affects the readability, testability, and probability of introducing defects in the future. While ensuring the correctness of the fix, controlling complexity is beneficial to maintaining the long-term health and sustainable security of the software. Code style consistency mainly affects the readability of the code and the efficiency of team collaboration, hence the above weighting coefficients are set.
[0040] S404, select the candidate repair code with the highest overall quality score as the optimal repair code.
[0041] The above-mentioned automated compilation and regression testing of multiple candidate repair codes can verify their syntactic correctness without breaking the original functionality. Furthermore, the comprehensive evaluation and ranking based on multi-dimensional indicators avoid the bias that may be caused by a single indicator, ensuring that the optimal repair solution is selected. On the basis of ensuring the correctness of the repair, the reliability, security and engineering usability of the final repair solution are significantly improved.
[0042] Specifically, the method further includes the following steps: S5. Add the source code, the corresponding optimal fix code, and the corresponding vulnerability context feature vector as new historical vulnerability fix cases to the vulnerability-fix knowledge base.
[0043] As described above, by automatically storing successfully verified remediation cases and their complete contexts as new cases into the knowledge base, the system possesses the ability to continuously learn and evolve, which can be used for subsequent retrieval and reasoning, thereby effectively improving the accuracy and efficiency of handling similar or even new vulnerabilities in the future.
[0044] Furthermore, in a preferred embodiment, the source code containing the vulnerability is obtained through the following steps: P1 automatically collects behavioral data of the target application from several preset collection dimensions and builds a state machine behavioral model based on the behavioral data.
[0045] Specifically, the state machine behavior model is constructed based on several business states and the operation transitions between business states; the obtained multi-dimensional behavior data is fused, each business state represents an application interface or data snapshot, and each operation will trigger a state transition, such as clicking a button or calling an API.
[0046] Specifically, the preset data collection dimensions include front-end code parsing, static crawling, interactive traffic monitoring, and API specification document parsing; this can be understood as obtaining behavioral data of the target application from at least four dimensions. Static crawling refers to the process of extracting data from static pages.
[0047] Furthermore, the aforementioned front-end code parsing refers to parsing the target code and constructing a front-end functional tree. Parsing the target code includes extracting front-end routes, API call interfaces, component properties, and state management logic. This can be understood as constructing a front-end functional tree based on the parsed front-end routes, API call interfaces, component properties, and state management logic. In specific implementations, parsing the target code refers to parsing the JavaScript code corresponding to the target application, especially the code corresponding to the front-end framework React or Vue.
[0048] Furthermore, the aforementioned interaction traffic monitoring and API specification document parsing refer to monitoring the interaction traffic between users and the target application in the test environment, and parsing the API specification document to extract several key pieces of information. These key pieces of information include API endpoints, request methods, parameter structures, and response formats. For example, the API specification document could be an OpenAPI specification document or an Owagger specification document. OpenAPI is a standardized API description specification that allows developers to define the structure, parameters, responses, and other information of APIs in a machine-readable manner. Owagger is a suite of tools built around OpenAPI for API documentation generation, testing, and code generation. Those skilled in the art are familiar with the specific implementation methods for parsing API specification documents to obtain the aforementioned key information, and will not be elaborated upon here.
[0049] The above-mentioned approach achieves a comprehensive and structured understanding of complex application behaviors, especially front-end dynamic interactions and back-end APIs, by automatically collecting behavioral data from multiple dimensions. Furthermore, the state machine behavior model built based on the complete behavioral data, with business states and operations at its core, provides accurate and computable business logic context for subsequent testing, enabling security testing to extend deeply from the interface level to the business logic level.
[0050] P2, based on the state machine behavior model, generates several test cases using a preset mutation strategy library; the preset mutation strategy library is built on the basis of business semantic analysis of the several business states and the operation transitions between business states; it can be understood as: by analyzing the business logic corresponding to each business state and each operation in the state machine behavior model, the direction that can be modified or mutated is determined in advance, and based on different mutation directions, several test cases are generated through users or large models.
[0051] Specifically, the preset mutation strategy library includes identity substitution testing, process sequence modification, target parameter tampering, and state anomaly simulation. In specific implementation, identity substitution testing refers to dynamically replacing parameters such as session tokens, user IDs, and accounts in a test sequence to attempt to simulate the identities of users with different permissions, in order to detect horizontal or vertical privilege escalation vulnerabilities. For example, in an order query request, the order ID can be replaced with another user's order ID. Process sequence modification refers to scrambling the order of critical operations or attempting to skip certain verification steps, such as directly attempting to send a payment request in the "add product - checkout - payment" process. Target parameter tampering refers to rule-based modification of business parameters, such as changing the payment amount to a negative number or a very small positive number, or changing the product quantity to a very large value to trigger integer overflow. State anomaly simulation refers to attempting to perform operations in abnormal application states, such as repeatedly submitting forms or accessing the system using expired tokens.
[0052] As mentioned above, since the quality of test cases directly determines the coverage, depth, and accuracy of vulnerability detection, this application, based on the construction of a state machine behavior model, combines business semantics to build a mutation strategy library, which can generate high-value test cases targeting business logic vulnerabilities. This is significantly different from the traditional Fuzzer software testing technology that uses random mutation and random fuzzing, greatly improving the targeting and efficiency of testing. Moreover, this method ensures the legitimacy of test cases in the business context, enabling test simulation to reach the core business logic, thereby achieving efficient and automated discovery of deep business logic vulnerabilities.
[0053] P3 executes several test cases and performs vulnerability analysis on the test response results corresponding to each test case to obtain the vulnerability detection results of the target application; the vulnerability analysis includes the analysis of response content, the analysis of session state changes, and the business impact assessment based on the analysis results of response content and session state changes.
[0054] Specifically, the analysis of the response content includes the following steps: P301, for any test case, compare the test response result of the test case with the given normal response result, and detect whether the test response result contains preset sensitive keywords or operation success keywords. In specific implementations, natural language processing technology or similarity algorithms can be used to analyze the textual differences between the test response result and the given normal response result. For example, it can detect whether the test response result contains data that is not from the current user; sensitive information appearing in the test response result may be other people's email addresses, etc.
[0055] Specifically, the "operation success keyword" refers to the textual identifier that appears in the test response result within the corresponding test context, indicating that the operation that should have failed was successfully executed.
[0056] P302. If a content difference that does not meet the preset conditions is detected based on the difference comparison, or if a preset sensitive keyword or operation success keyword is detected, then a vulnerability is determined to exist; otherwise, a vulnerability is determined not to exist.
[0057] Specifically, content differences that do not meet the preset conditions refer to differences that are determined to be semantically significantly different or have a similarity less than the preset similarity threshold after natural language processing.
[0058] As mentioned above, when analyzing the response content, intelligent comparison and keyword detection can directly and accurately identify potential information leakage and signs of successful unauthorized operations from the response data, so as to obtain vulnerability detection results.
[0059] Specifically, the analysis of session state changes includes the following steps: On page 310, for any test case, when the test response result of the test case indicates that the operation corresponding to the test case has been successfully executed, a verification request is initiated based on the operation corresponding to the test case and the target business state corresponding to the operation itself in the state machine behavior model. This can be understood as: the target business state is the expected state, that is, the result that should be achieved in business logic after executing the corresponding operation, obtained from the state machine behavior model. For example, if the operation is "change password", its target business state is "the specified user's password is updated to a new value".
[0060] P320. If the response to the verification request indicates that the target business state has been achieved, and the execution behavior for achieving the target state conflicts with the permission constraints in the context corresponding to the operation, then a vulnerability is determined to exist; otherwise, no vulnerability is determined to exist. For example, if the operation in the state machine behavior model is "change password," and the test case is "using A's identity to send a request to the change password interface to attempt to change B's password," and the target business state has been achieved, meaning B's password has been changed, a verification request still needs to be initiated, such as logging into B's account with the new password. If the login is successful, then a vulnerability exists.
[0061] As mentioned above, after executing test cases, such as unauthorized password changes, it is necessary to verify whether the target application can log in with the new password. Through the attack-verification chain, it is verified whether a single operation has truly changed the system's business state, fundamentally eliminating false alarms caused by false success responses, which helps improve the accuracy of vulnerability detection.
[0062] In addition to analyzing the response content and session state, it is also necessary to assess whether the abnormal response has indeed caused a security impact on the business logic. For example, analysis can be conducted based on expert experience or a trained large model, combining technical anomalies with business context to determine the actual severity of the vulnerability and transform security findings into business risk conclusions that can guide the prioritization of remediation.
[0063] The above-mentioned multi-layered in-depth analysis technology, which includes response content, session state, and business impact, rather than relying on HTTP status codes, can accurately determine vulnerabilities, effectively distinguish between real business vulnerabilities and apparent anomalies, thereby effectively reducing the false positive rate. Furthermore, through business impact assessment, technical anomalies are correlated with real business security risks, and vulnerability classifications and evidence with clear business significance are output, which helps to improve the operability of test results and the rationality of remediation strategies.
[0064] In another embodiment, the method further includes the following steps: P10, for any operation in the state machine behavior model, generate at least one set of test cases; where each test case in each group is obtained by combining and modifying at least two different business parameters based on a mutation strategy of business semantics. For example, test cases that modify 2 parameters are grouped into one group, test cases that modify 3 parameters are grouped into another group, and each test case includes modifications to the parameters corresponding to the operation itself.
[0065] P20 executes each test case set in the sandbox environment and obtains the execution response of each test case in each test case set.
[0066] P30 performs feature matching on each acquired execution response and counts the number k of abnormal responses that match the preset vulnerability characteristics. For example, the preset vulnerability characteristics are returning data that is not from the current user or the appearance of unexpected success keywords, while the corresponding normal responses are returning "order does not exist" or "empty data".
[0067] P40, perform statistical hypothesis testing based on the total number of test cases n and the number of abnormal responses k corresponding to all test case sets, and calculate the statistical significance index; the statistical significance index is the probability value P of at least k abnormal responses occurring in the total number of test cases n, based on a preset baseline random probability P0; it can be understood that: the baseline random probability is a pre-set maximum acceptable random probability of an abnormal response that meets the characteristics of a vulnerability in a single test under the condition of no vulnerability. For example, when the baseline random probability P0 is 0.01, the statistical significance index is the probability of ≥k abnormal responses occurring under the assumption that P0=0.01.
[0068] Specifically, the statistical significance index meets the following conditions: , where the value of i ranges from k to n.
[0069] P50, when the probability value is less than a preset significance level threshold, it indicates that the occurrence of the abnormal response is statistically significant, and the test case corresponding to the abnormal response is determined to have a vulnerability. Those skilled in the art can set the significance level threshold according to actual needs, which will not be elaborated here.
[0070] As described above, by combining parameter mutations to generate a high-coverage test case set, and using statistical significance tests to adjudicate batch abnormal responses, it is possible to accurately and comprehensively uncover deep business logic vulnerabilities that require multiple conditions to trigger and are difficult to find with traditional single-point testing, and effectively filter false alarms caused by accidental failures, thereby improving the accuracy and reliability of vulnerability detection.
[0071] P4, based on the vulnerability detection results, locates the vulnerability in the source code of the target application and obtains the source code containing the vulnerability.
[0072] Furthermore, the method also includes the following steps: Based on the vulnerability detection results, an API mapping list of the target application and a knowledge graph representing the internal entity relationship network of the target application are output. The API mapping list is a structured data asset catalog that records all exposed interfaces of the target application and their attribute information, and includes rich context, such as API endpoints, HTTP methods, function descriptions, parameter lists, response specifications, and metadata. The knowledge graph is a semantic relationship graph representing the complex relationships between APIs, users, data, states, and business logic. For example, node types may include API nodes, user nodes, data entity nodes, business state nodes, front-end page nodes, and operation nodes, and relationship types may include call relationships, permission relationships, data flow relationships, and state transition relationships.
[0073] As described above, after identifying vulnerabilities through in-depth vulnerability analysis of the response results, the output API mapping list and knowledge graph are comprehensive and structured in-depth analysis results of the tested application. The API mapping list provides enterprises with a continuously updated vulnerability management foundation, and the knowledge graph reveals the location, propagation path and impact scope of the vulnerability in the business context, providing meaningful data reference for security architecture assessment and risk governance.
[0074] Preferably, the method further includes the following steps: S100: After selecting the optimal fix code and automatically fixing the source code vulnerability, return to step P3 to obtain new vulnerability detection results.
[0075] S200: If the new vulnerability detection result indicates that the patched source code still contains vulnerabilities, the patched target code is treated as the source code containing the vulnerabilities, and steps S1-S4 are executed again to select new optimal patching code for automated vulnerability patching. Note that when the patched target code is treated as the source code containing the vulnerabilities, the vulnerability location information in the source code has changed.
[0076] S300 iteratively executes steps S100-S200 until a new vulnerability detection result indicates that the repaired source code does not contain vulnerabilities or the number of iterations reaches a preset iteration threshold. At this point, the final repair result and vulnerability detection result are fed back to the user. Those skilled in the art can set the preset iteration threshold according to actual needs, which will not be elaborated here.
[0077] As described above, by introducing a closed loop of re-detection and iterative repair, we can address secondary vulnerabilities or incomplete repairs caused by improper patching, enabling the entire system to have self-verification and continuous optimization capabilities, and significantly improving the reliability and security of the final repair solution.
[0078] Embodiments of the present invention also provide a non-transitory computer-readable storage medium, which can be disposed in an electronic device to store at least one instruction or at least one program related to implementing a method in the method embodiment, wherein the at least one instruction or the at least one program is loaded and executed by the processor to implement the source code vulnerability repair method provided in the above embodiments.
[0079] Embodiments of the present invention also provide an electronic device, including a processor and the aforementioned non-transitory computer-readable storage medium.
[0080] While specific embodiments of the invention have been described in detail by way of example, those skilled in the art should understand that the examples are for illustrative purposes only and not intended to limit the scope of the invention. It should also be understood that various modifications can be made to the embodiments without departing from the scope and spirit of the invention. The scope of the invention is defined by the appended claims.
Claims
1. A method for fixing source code vulnerabilities, characterized in that, The method includes the following steps: S1. Parse the source code containing the vulnerability to obtain an abstract syntax tree and a control flow graph. Based on the abstract syntax tree, the control flow graph, and the corresponding vulnerability location information, use a given graph neural network model to extract the semantic representation of the vulnerability context and generate a vulnerability context feature vector. S2, Based on the vulnerability context feature vector, determine the historical vulnerability remediation cases corresponding to the vulnerability context feature vector from the pre-built vulnerability-remediation knowledge base; the vulnerability-remediation knowledge base stores several historical vulnerability remediation cases; S3 generates structured suggestions based on vulnerability context feature vectors and retrieved historical vulnerability remediation cases, and inputs them into a pre-trained code generation model so that the code generation model can generate a set of candidate remediation codes corresponding to the source code; S4. Evaluate each candidate repair code in the candidate repair code set and select the optimal repair code to automatically repair the source code vulnerability.
2. The source code vulnerability repair method according to claim 1, characterized in that, Step S1 includes the following steps: S101, based on the vulnerability points in the source code, maps the corresponding vulnerability location information from the abstract syntax tree and the control flow graph respectively; S102, Input the abstract syntax tree, control flow graph and corresponding vulnerability location information into the given graph neural network model so that the given graph neural network model can aggregate the node information in the abstract syntax tree and control flow graph through the message passing mechanism; S103, the vulnerability location information is injected as an initial feature or attention weight into the given graph neural network model to generate the vulnerability context feature vector corresponding to the source code.
3. The source code vulnerability repair method according to claim 1, characterized in that, Step S2 includes the following steps: S201, calculate the semantic similarity between the vulnerability context feature vector and the historical vulnerability context feature vector in each historical vulnerability remediation case; wherein, each historical vulnerability remediation case includes a historical vulnerability code segment, the corresponding remediated code segment, and the historical vulnerability context feature vector corresponding to the historical vulnerability code segment. S202, the historical vulnerability repair case with the highest corresponding semantic similarity is taken as the historical vulnerability repair case corresponding to the determined vulnerability context feature vector.
4. The source code vulnerability repair method according to claim 1, characterized in that, Step S4 includes the following steps: S401, each candidate repair code in the candidate repair code set is sequentially subjected to compilation testing and preset regression testing, and candidate repair codes that pass the tests are selected based on the test results; S402, for each candidate fix code that passes the test, calculate the evaluation scores of the candidate fix code in three dimensions: code style consistency, code complexity, and patch minimization principle; S403, normalize the evaluation scores of each candidate repair code that passes the test in the three dimensions, and perform weighted fusion based on the preset weight coefficients corresponding to each dimension to calculate the comprehensive quality score corresponding to each candidate repair code that passes the test; where W1 < W2 < W3, and W3 > 0.5, W1 is the preset weight coefficient corresponding to code style consistency, W2 is the preset weight coefficient corresponding to code complexity, and W3 is the preset weight coefficient corresponding to the patch minimization principle. S404, select the candidate repair code with the highest overall quality score as the optimal repair code.
5. The source code vulnerability repair method according to claim 4, characterized in that, The calculation steps for the evaluation score S3 of the patch minimization principle are as follows: S4021, Construct the abstract syntax tree corresponding to the candidate repair code, and calculate the degree of difference between the abstract syntax tree corresponding to the source code and the abstract syntax tree corresponding to the candidate repair code; wherein, the degree of difference is represented by the edit distance; S4022, Based on the degree of difference and the preset maximum tolerable difference, the evaluation score S3 of the patch minimization principle is calculated; wherein, the evaluation score S3 of the patch minimization principle meets the following conditions: S3 = 1 - D / D max Where D represents the degree of difference between the abstract syntax tree corresponding to the source code and the abstract syntax tree corresponding to the candidate fix code. max This is the preset maximum tolerance difference.
6. The source code vulnerability repair method according to claim 1, characterized in that, The method further includes the following steps: The source code, the corresponding optimal fix code, and the corresponding vulnerability context feature vector are added as new historical vulnerability fix cases to the vulnerability-fix knowledge base.
7. The source code vulnerability repair method according to claim 1, characterized in that, Obtain the vulnerable source code by following these steps: P1 automatically collects behavioral data of the target application from several preset collection dimensions, and constructs a state machine behavioral model based on the behavioral data; the state machine behavioral model is constructed based on several business states and the operation transitions between business states; P2, based on the state machine behavior model, generates several test cases using a preset mutation strategy library; the preset mutation strategy library is built on the basis of business semantic analysis of the several business states and the operation transitions between business states; P3 executes several test cases and performs vulnerability analysis on the test response results corresponding to each test case to obtain the vulnerability detection results of the target application; the vulnerability analysis includes the analysis of response content, the analysis of session state changes, and the business impact assessment based on the analysis results of response content and session state changes. P4, based on the vulnerability detection results, locates the vulnerability in the source code of the target application and obtains the source code containing the vulnerability.
8. The source code vulnerability repair method according to claim 7, characterized in that, The method further includes the following steps: S100: After selecting the best fix code and automatically fixing the source code vulnerability, return to step P3 to obtain new vulnerability detection results. S200, if the new vulnerability detection result indicates that the repaired source code still contains vulnerabilities, the repaired target code is regarded as the source code containing vulnerabilities, and the execution of steps S1-S4 is returned to select new optimal repair code for automated repair of source code vulnerabilities. S300 iterates through steps S100-S200 until a new vulnerability detection result indicates that the repaired source code does not contain vulnerabilities or the number of iterations reaches a preset threshold. Then, the final repair result and vulnerability detection result are fed back to the user.
9. A non-transitory computer-readable storage medium, wherein the storage medium stores at least one instruction or at least one program segment, characterized in that, The at least one instruction or the at least one program segment is loaded and executed by the processor to implement the source code vulnerability repair method as described in any one of claims 1-8.
10. An electronic device, characterized in that, Includes a processor and the non-transitory computer-readable storage medium as described in claim 9.
Citation Information
Patent Citations
Code vulnerability detection and repair method and system based on general large model
CN120372631A
Vulnerability repair rule generation method based on AI and related equipment
CN120611390A
Similarity comparison-based large model supply chain automatic repair method and device
CN120654241A
System and method for vulnerability localization based on deep learning
US20250077683A1
Cited By
Source code self-adaptive repairing method and related equipment
CN122153892A
A closed-loop system for automated vulnerability repair and verification based on unit test-generated code.
CN122310549A
A closed-loop system for automated vulnerability repair and verification based on unit test-generated code.
CN122310549B