Malicious code adversarial perturbation method fusing abstract syntax tree and large language model
Patent Information
- Application Number
- CN202611153439.7
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- Filing Date
- 2026-07-31
- Publication Date
- 2026-10-30
- Estimated Expiration
- 2046-07-31
AI Technical Summary
[0007]本发明的目的在于解决现有技术中代码空间对抗扰动技术存在的语法破坏、循环崩溃以及局部密集注入等问题,并提出一种融合抽象语法树与大语言模型的恶意代码对抗扰动方法
[0044]本发明与现有技术相比,其显著优点为:(1)首次融合了AST静态语法约束与LLM(Large Language Model,大语言模型)动态生成能力,配合全局失败黑名单闭环反馈,极大提高代码编译成功率。(2)在全局决策阶段引入了循环规避约束与常规嵌套深度奖励,有效防止高耗时API误入高频循环导致的沙箱检测超时或宕机。(3)创新性引入API注入频次的动态离散切分机制。将对抗特征非均匀地散布在全局执行流的多个分支中,规避了单点密集注入触发的异常警报,又阻断了因特定执行分支未触发而导致对抗特征丢失的风险。
Smart Images

Figure CN122655072B_ABST
Abstract
Description
Technical Field
[0001] This invention relates to artificial intelligence and cybersecurity technologies, specifically to a method for combating malicious code perturbations that integrates abstract syntax trees and large language models. Background Technology
[0002] With the rapid mutation and obfuscation techniques of malware, detection methods based on dynamic API (Application Programming Interface) sequence analysis and deep learning have become the mainstream defense approach in the industry. However, these high-accuracy deep learning models have significant robustness flaws and are highly vulnerable to deception attacks using adversarial examples. Attackers can inject carefully calculated micro-perturbations into the feature space of malware code (such as API call frequency vectors) to induce misjudgments in the target detection model. Although adversarial algorithms for the "feature space" are relatively mature, how to non-destructively and covertly map and implement these abstract "feature perturbations" (i.e., the specific API calls that need to be added) into the real "code space" (i.e., directly modifying the malware source code) remains a major technical challenge in the field of cybersecurity attack and defense.
[0003] Existing automated code space perturbation methods suffer from the following three major technical shortcomings:
[0004] First, there is a lack of understanding of deep semantics. Existing technologies mostly rely on coarse-grained regular expression matching or random insertion of plain text positions, which can easily destroy the original abstract syntax tree (AST) structure of the source code, resulting in serious syntax errors and compilation failures in the injected code.
[0005] Second, it ignores the control flow and execution cost of the code. Existing strategies cannot perceive the execution logic of the program. If time-consuming target APIs are blindly and mechanically inserted into frequently executed loops (such as for and while statements), the generated adversarial samples will cause a surge in CPU usage or even program crashes during sandbox operation, directly destroying the original core functionality of the malware.
[0006] Third, localized intensive injection is highly likely to trigger anomaly alerts and feature failures. Existing methods typically tend to insert multiple calls to the same API into a single local code block. This intensive sensitive call not only easily triggers the sandbox's local behavior anomaly monitoring; more critically, if the local code block is in a conditional branch that is not triggered during program execution, the injected adversarial features will not be executed, causing the adversarial attack to completely fail. Summary of the Invention
[0007] The purpose of this invention is to address the problems of syntax violation, loop collapse, and local dense injection in existing code space adversarial perturbation techniques, and to propose a malicious code adversarial perturbation method that integrates abstract syntax trees (ASTs) and large language models. It introduces an AST code block-level fragmentation mechanism, combined with stateful Monte Carlo tree search to avoid high-frequency loops and achieve globally optimal position scheduling; simultaneously, it introduces a cluster search algorithm to drive a large language model, coupled with a dynamic frequency segmentation mechanism and static syntax pruning, to automatically generate syntactically correct and highly concealed local variant code.
[0008] To achieve the above objectives, the technical solution provided by this invention is as follows:
[0009] A method for combating malicious code perturbations that integrates abstract syntax trees and large language models includes:
[0010] Extract the API call frequency feature vector of the target malicious code sample, perturb the API call frequency feature vector through adversarial attack algorithm to generate adversarial feature vector that meets the preset hard constraints, and extract the difference vector between the adversarial feature vector and the API call frequency feature vector to determine the category of the API to be inserted and the corresponding insertion frequency.
[0011] The source code of the target malicious code sample is parsed to generate an abstract syntax tree. Based on the abstract syntax tree, the source code is divided into multiple code segments, and the structural depth feature labels of each code segment are extracted. The structural depth feature labels include the nesting depth of loops and the nesting depth of regular loops.
[0012] Construct a Monte Carlo tree search model, combine it with structural depth feature labels, calculate the comprehensive score of each API to be inserted to be assigned to each code segment, and obtain the optimal insertion strategy based on the comprehensive score;
[0013] Based on the optimal insertion strategy, the API to be inserted is integrated into the target code fragment using a large language model combined with a bundle search algorithm to generate candidate variant code.
[0014] Static syntax checking is performed on each candidate variant code using an abstract syntax tree, and the optimal variant code is selected. If all candidate variant codes fail the static syntax check, the insertion is abandoned.
[0015] By writing the optimal variant code into the source code, we obtain anti-malicious source code that can bypass the detection model.
[0016] Furthermore, the step of extracting the API call frequency feature vector of the target malicious code sample, perturbing the API call frequency feature vector using an adversarial attack algorithm to generate an adversarial feature vector that satisfies preset hard constraints, and extracting the difference vector between the adversarial feature vector and the API call frequency feature vector to determine the category of the API to be inserted and its corresponding insertion frequency, includes:
[0017] The target malware sample was simulated using a sandbox analysis tool to obtain the API sequence called by the target malware sample, and the bag-of-words model was used to transform the API sequence into an API call frequency feature vector.
[0018] Construct a proxy detection model and train the proxy detection model based on the feedback labels of the API call frequency feature vector from the target detection model;
[0019] The API call frequency feature vector is normalized using MinMax. An adversarial attack algorithm is used to perturb the normalized API call frequency feature vector on the proxy detection model. Then, a non-negative truncation mechanism is used to ensure that the perturbation increment is non-negative, and the adversarial feature vector is output.
[0020] Calculate the difference vector between the adversarial feature vector and the API call frequency feature vector. In the difference vector, the index of the feature dimension with a value greater than zero corresponds to the category of the API to be inserted, and the value corresponds to the frequency of insertion.
[0021] Furthermore, before dividing the source code into multiple code fragments based on the abstract syntax tree, the following steps are also included:
[0022] A high-frequency keyword library is built based on frequently called functions;
[0023] Check if the name of each target function in the source code contains keywords from the high-frequency keyword library, and if the number of child nodes of the target function is less than a preset threshold. If so, add the current target function to the global failure blacklist and prohibit the insertion of APIs into the code segment to which the current target function belongs in subsequent steps.
[0024] Furthermore, the construction of the Monte Carlo tree search model, combined with structural depth feature labels, calculates a comprehensive score for assigning each API to be inserted to various code snippets, and obtains the optimal insertion strategy based on the comprehensive score, including:
[0025] A pre-defined mapping dictionary between APIs and feature keywords;
[0026] Iterate through the abstract syntax tree nodes of each code snippet, and check whether there are any feature keywords that are the same as the API to be inserted according to the mapping dictionary. If there are, assign different semantic confidence to the API to be inserted according to the node type and the preset semantic label rule table. If not, directly assign the preset semantic confidence to the API to be inserted.
[0027] Construct a Monte Carlo tree search model and initialize the evaluation environment;
[0028] Code snippets with a regular nesting depth greater than 0 will receive bonus points, while code snippets with a loop nesting depth greater than 0 will receive deduction points.
[0029] Based on semantic confidence, bonus points, and penalty points, a comprehensive score is calculated for each pairing scheme of API and code snippet to be inserted;
[0030] The pairing scheme with the highest overall score is selected as the optimal insertion strategy.
[0031] Furthermore, the provision of bonus points for code snippets with a regular nesting depth greater than 0 and penalty points for code snippets with a loop nesting depth greater than 0 includes:
[0032] When the regular nesting depth is greater than 0 and less than or equal to 5, the bonus points increase for each additional level of regular nesting depth. When the regular nesting depth is greater than 5, the bonus points no longer increase.
[0033] When the nesting depth of the loop is greater than 0, the penalty for each additional layer of nesting depth increases accordingly.
[0034] Furthermore, based on the optimal insertion strategy, the API to be inserted is integrated into the target code fragment using a large language model combined with a beam search algorithm to generate candidate variant code, including:
[0035] The insertion frequency of a single actual allocation is calculated using the following formula:
[0036]
[0037] in, This represents the insertion frequency in a single actual allocation. Indicates the remaining number of insertions. Indicates will Halve and round down. Represents a random perturbation function;
[0038] Based on the preset search width K of the cluster search algorithm, an obfuscation strategy is assigned to K search branches from the predefined obfuscation strategy pool;
[0039] Based on the API to be inserted, the actual insertion frequency in a single instance, the obfuscation strategy bound to the K search branches, and the context source code of the code snippet, construct K prompt words;
[0040] The large language model outputs K candidate variant codes based on K cue words.
[0041] Furthermore, the step of using an abstract syntax tree to perform static syntax checks on each candidate variant code and selecting the optimal variant code, and abandoning the insertion if all candidate variant codes fail the static syntax check, includes:
[0042] Static syntax checking is performed on each candidate variant code using an abstract syntax tree. Syntax pruning is performed on candidate variant codes with illegal syntax. A comprehensive score is calculated for candidate variant codes with legal syntax. The candidate variant code with the highest comprehensive score is selected as the optimal variant code.
[0043] If all candidate variant codes are syntactically invalid, then abandon the current insertion and add the current best insertion strategy to the global failure blacklist.
[0044] Compared with existing technologies, the present invention has the following significant advantages: (1) It integrates AST static syntax constraints with LLM (Large Language Model) dynamic generation capabilities for the first time, and with the closed-loop feedback of the global failure blacklist, it greatly improves the code compilation success rate. (2) It introduces loop avoidance constraints and regular nesting depth rewards in the global decision-making stage, effectively preventing sandbox detection timeouts or crashes caused by high-time-consuming APIs accidentally entering high-frequency loops. (3) It innovatively introduces a dynamic discrete segmentation mechanism for API injection frequency. It distributes adversarial features non-uniformly in multiple branches of the global execution flow, avoiding abnormal alarms triggered by single-point dense injections, and blocking the risk of losing adversarial features due to the failure of specific execution branches to trigger. Attached Figure Description
[0045] Figure 1 The flowchart shows the malicious code anti-perturbation method of this invention that integrates abstract syntax trees and large language models;
[0046] Figure 2 This is a flowchart of the candidate variant code generation process based on a large language model and beam search. Detailed Implementation
[0047] To make the objectives, technical solutions, and advantages of this invention clearer, the invention will be further described in detail below with reference to the accompanying drawings and embodiments. It should be understood that the specific embodiments described herein are merely illustrative and not intended to limit the invention.
[0048] like Figure 1As shown, this embodiment proposes a method for combating malicious code perturbations by integrating abstract syntax trees and large language models, including the following steps:
[0049] (1) Malware code feature adversarial perturbation: construct feature vectors based on the API call sequence of the target malware code sample, and perturb the feature vectors through adversarial attack algorithms. Without affecting the functionality of the malware, the target malware detection model will make a misjudgment, and the API call changes corresponding to the perturbed feature vectors will be extracted.
[0050] Step (1) aims to perform adversarial perturbation on the features of malware code. The goal is to make the target malware detection model misjudge by making minor modifications to the feature vectors of the malware without affecting the functionality of the malware.
[0051] First, given a malware sample S, the detailed steps for adversarial perturbation of malware code features are as follows:
[0052] (1-1) Feature Vector Extraction: First, a sandbox (such as Cuckoo Sandbox) is used to simulate the operation of S, obtaining the API call sequence of S, denoted as Seq. Then, the "bag-of-words model" is used to transform Seq into an API call frequency feature vector, denoted as v. ori .
[0053] (1-2) Proxy Model Training: Using a large number of API call frequency feature vector samples as query inputs, the target detection model Mtarget is accessed through the interface to collect and record the labels it responds to for each set of inputs. These query inputs and response labels are used as the training set to train a proxy detection model Magent, making its decision boundary approximate that of the target detection model Mtarget.
[0054] (1-3) Feature space perturbation generation: Input API call frequency feature vector v ori Adversarial attack algorithms (such as Fast Gradient Signed Method (FGSM) and Jacobian Matrix-based Satisfactory Graph Attack (JSMA)) are used to perturb the API call frequency feature vector in the proxy detection model. The API call frequency feature vector v is then normalized by introducing a MinMax normalization mechanism. ori The discrete API frequencies are mapped to the interval [0,1]. Then, through a non-negative truncation mechanism, if the calculated feature difference (increment) is less than or equal to 0, the system filters it out, ensuring the perturbation increment is non-negative. The output is an adversarial feature vector v that can stably deceive the agent detection model Magent into outputting a "benign" label and strictly satisfies the hard constraint that API frequencies "only increase and never decrease." adv .
[0055] (1-4) Target API (API to be inserted) difference extraction: Calculate the difference vector v between the perturbed adversarial feature vector and the API call frequency feature vector. diff (i.e. v) diff = v adv -v ori ), filter out v diff Identify the feature dimensions that are greater than zero, locate the feature dimensions that have changed and their specific increases, in order to determine the target API set required to resist code rewriting.
[0056] (2) Malware code adversarial rewriting: Based on the API call changes corresponding to the malware feature perturbation, the malware source code is fragmented based on the abstract syntax tree. The Monte Carlo tree search algorithm is used to calculate the best API insertion strategy. On this basis, the malware source code is rewritten using a large language model to realize the mapping of malware adversarial perturbation from the feature space to the code space, and obtain the malware source code that can bypass the detection model.
[0057] Step (2) aims to rewrite the malware's source code using a large language model based on the malware's feature perturbation results (i.e., inserting v). diff The system adds an API to enable malware adversarial perturbations by mapping the feature space to the code space, thus obtaining the source code of malware that can actually bypass detection models. The detailed steps are as follows:
[0058] (2-1) Source code fragmentation based on Abstract Syntax Tree (AST): Since large language models have difficulty processing extremely long code, this step aims to semantically decompose the extremely long source code into smaller fragments so that the large language model can process these fragments separately. The detailed steps are as follows:
[0059] (2-1-1) Abstract Syntax Tree Construction: Using an abstract syntax tree construction tool (such as tree-sitter), the complete source code of the malware is input into the construction tool to obtain the abstract syntax tree (AST) corresponding to the source code.
[0060] (2-1-2) Candidate Function Evaluation: This step aims to evaluate whether each function in the malware's source code is suitable for API insertion. For example, functions specifically for printing logs, such as `debug_log`, are called frequently during code execution. Blindly inserting target APIs into these functions can cause significant performance and time overhead for the malware when running in the sandbox, leading to sandbox detection timeouts and program termination or crashes. First, a high-frequency keyword library is built by statistically analyzing the names of frequently called functions to identify common keywords (such as `print` and `debug`). Second, regular expressions are used to check whether all function names in the malware's source code contain high-frequency keywords, and the number of child nodes under the function node in the abstract syntax tree is counted simultaneously. If the number of child nodes is extremely small, the function is likely a lightweight leaf function with very few lines of code and lacking branching logic. Finally, if the currently checked target function matches a high-frequency keyword and is determined to have a very simple structure, it is added to the global failure blacklist of unsuitable API insertion.
[0061] (2-1-3) Code Segmentation and Feature Extraction: A depth-first recursive traversal is performed from the root node of the AST downwards. When a valid function definition or compound statement block is identified, the corresponding source code segment is extracted based on the start and end positions of that node in the source code and encapsulated into an independent code segment. After obtaining the code segment, the following features can be extracted:
[0062] (1) The start and end positions of the code fragment in the source code; During the AST traversal, since the AST will give the code fragment a start byte position and an end byte position, you can directly read the corresponding two attributes in the code node to obtain it.
[0063] (2) Which function does the code snippet belong to? When traversing the AST from top to bottom, a variable is used to record the name of the function currently being processed. When a function definition node is reached, the function name is extracted from that node and the record variable is updated; when a code block inside that function is reached, the currently recorded function name is directly assigned to the code snippet. If the code snippet is not inside any function, this field is left blank.
[0064] (3) The normal nesting depth (depth) and loop nesting depth (loop_depth) are calculated as follows: During the AST traversal, when a compound statement block (i.e. a local independent code block enclosed in curly braces {} in the source code, such as a complete function body, if conditional branch, while loop branch, etc.) node is parsed, depth increases by 1; when a loop control statement node (such as for, while, or do, etc., which control the code body to be executed frequently) is parsed, loop_depth increases by 1.
[0065] Below is an example of "candidate function evaluation" and "code segmentation and feature extraction":
[0066] / / Function 1: Log printing function
[0067] void debug_log(std::string msg) {
[0068] std::cout << "[LOG] " << msg << std::endl;
[0069] }
[0070] / / Function 2: Core logic function of the Trojan horse
[0071] void run_trojan_module() {
[0072] bool connected = true;
[0073] if (connected) {
[0074] int heartbeat_count = 0;
[0075] while (heartbeat_count < 5) {
[0076] std::this_thread::sleep_for(std::chrono::milliseconds(500));
[0077] heartbeat count++;
[0078] }
[0079] }
[0080] debug_log("trojan end\n");
[0081] }
[0082] First, an abstract syntax tree (AST) is constructed, followed by the evaluation of candidate functions. For the function `debug_log`, its identifier is found to contain the high-frequency keyword "debug," and statistical analysis reveals that the number of statement child nodes under this function's AST is extremely small, classifying it as a lightweight leaf function. Therefore, `debug_log` is highly likely a frequently executed but simple auxiliary function. To avoid inserting APIs into such high-frequency functions and causing sandbox monitoring timeouts, it is identified as an injection risk and added to the global failure blacklist.
[0083] Subsequently, for the evaluated function `run_trojan_module`, a depth-first traversal is initiated to perform code segmentation and feature extraction. When the outermost compound statement block of the function is identified (the first `{` in the `run_trojan_module` function), it is encapsulated as "code fragment 1", and its normal nesting depth `depth = 1` is recorded. Since it has not yet entered the loop structure, its loop nesting depth `loop_depth = 0`. When traversing to the `if(connected)` conditional branch statement block inside, it is truncated as "code fragment 2", at which point the fragment's depth = 2, and its loop nesting depth `loop_depth = 0`. Finally, when the algorithm delves into the `while(heartbeat_count<5)` loop branch statement block, it is encapsulated as "code fragment 3", this fragment's depth = 3, and its loop nesting depth `loop_depth = 1`. Through this process, the system not only filters dangerous injection areas but also provides structural depth feature labels containing execution risk indicators (loop nesting depth) and concealment indicators (normal nesting depth) for subsequent MCTS (Monte Carlo Tree Search) global location decisions.
[0084] (2-2) Insertion Position Decision Based on Monte Carlo Tree Search (MCTS): This step aims to solve the problem of "which code snippet to insert the target API into". By constructing a stateful MCTS model as a global scheduling center, and combining feature confidence scores and code depth risk, the most covert and safest code snippet insertion is planned for each target API. The detailed steps are as follows:
[0085] (2-2-1) MCTS Search Environment Initialization: Before starting the MCTS algorithm, the system needs to establish an evaluation environment. Environment initialization includes the following three parts:
[0086] (1) All APIs that need to be inserted and the remaining number of insertions;
[0087] (2) Set a "crowding count" for each parent function (to avoid inserting APIs into a single function in a concentrated manner and to ensure that adversarial features are evenly distributed in the global code).
[0088] (3) A global failure blacklist (used to record and avoid insertion combinations that cause syntax conflicts in subsequent steps).
[0089] The above three pieces of information are used to initialize the root node state of the MCTS search environment, serving as the global constraints and context basis for subsequent tree search processes.
[0090] (2-2-2) Semantic Confidence Scoring Based on Feature Keywords: When attempting to insert a target API into a code snippet, the "semantic rationality" of this insertion is first evaluated. First, a mapping dictionary between APIs and feature keywords is predefined; for example, WSASend (Windows Sockets Asynchronous Send), a network communication API, has the "network communication" feature. Then, the AST nodes of the candidate code snippets are traversed to check if there are any feature keywords matching the target API. If so, different semantic confidence levels are assigned based on the node type and the predefined semantic labeling rule table; for example, a high confidence level is assigned as a function call, and a low confidence level as a comment. If the target API does not match any predefined feature keywords, it is assigned a predefined low confidence level.
[0091] (2-2-3) Comprehensive scoring combining two types of nesting depth: After calculating the basic semantic confidence score, MCTS will add or subtract points based on the two types of nesting depth of the code snippet. A higher "normal nesting depth" will result in more bonus points, because hiding code in deep nesting (such as multi-level nested if branches) makes API insertion more covert. However, once the normal nesting depth reaches 5 levels or more, the bonus points become the same, and no further bonuses will be awarded based on higher levels. However, if the "loop nesting depth" of the code snippet is greater than 0, it means that the snippet is inside a repeatedly executed loop, and the system will penalize it by deducting points. The higher the "loop nesting depth," the more severe the penalty, and there is no upper limit to the penalty. This evaluation rule can prevent the insertion of time-consuming APIs into high-frequency loops, which would generate huge time overhead.
[0092] (2-2-4) Score summary and output of optimal decision: Using the MCTS algorithm, by simulating a large number of combinations of "target API and code snippets", the comprehensive score generated in step (2-2-3) is summarized, and the code snippet with the highest comprehensive score (i.e., taking into account both semantic concealment and execution security) is finally selected as the insertion position of the target API (i.e. the optimal insertion strategy) and handed over to the subsequent code generation module for processing.
[0093] (2-3) Local Code Generation Based on Large Language Model and Beam Search: After locking the insertion position, this step aims to address the problem of writing code as naturally as the original. Utilizing the code generation capabilities of the large language model, the target API call is integrated into the source code while conforming to the contextual syntax, avoiding semantic incoherence or structural abruptness caused by direct insertion. The detailed steps are as follows:
[0094] (2-3-1) Dynamic discrete segmentation of API insertion frequency: When calling Beam Search, first check the remaining number of insertions for the current target API. Inserting all insertions at once not only easily triggers alerts from sandboxes or security software, but also carries the risk of missing execution branches (i.e., the segment happens to be located within a conditional branch that was not triggered during program execution), causing the API to fail to trigger. Therefore, a dynamic frequency segmentation mechanism is introduced, calculating the actual insertion frequency allocated per insertion according to the following formula. This ensures that adversarial features are distributed in a non-uniform, randomized manner across multiple branches of the global execution flow.
[0095]
[0096] in, Indicates will Halve and round down. The introduced random perturbation function is used to simulate the irregular distribution in the natural programming process.
[0097] (2-3-2) Prompt word construction and code variant generation based on large model: In order to ensure that the large language model can accurately integrate the target API into the source code and has a high degree of concealment, the system first allocates obfuscation strategies to K search branches in a loop according to the preset search width K of the cluster search (i.e., the maximum number of candidate variants that can be generated and explored in parallel at the same level), so that each search branch is bound to an obfuscation strategy. The predefined obfuscation strategy pool includes three obfuscation strategies: (1) Context semantic fusion, which requires that the API call be embedded between the preceding and following statements in a way that conforms to the context syntax and logic, avoiding the structural abruptness caused by placing it at the beginning or end of the code block; (2) Opaque predicate wrapping, which introduces a tautological fake condition such as if(sizeof(int)=4) judgment and nests the target API in it; (3) Spurious variable masking, which declares harmless local variables and accompanies the target API to perform redundant calculations without actual function. When K is greater than the capacity of the strategy pool, the strategy is reused in a fixed order to ensure that branch binding can be completed under any value of K.
[0098] After establishing the multi-path obfuscation strategy, the system will determine the target API and the actual insertion frequency allocated in a single instance. The obfuscation strategy bound to the current search branch and the context source code of the code snippet are assembled into prompts for the larger model according to a strict structured template. The prompts consist of two parts: "system instructions" responsible for global constraints and "user instructions" responsible for dynamic generation. Taking the allocation of two native system calls NtClose (Native API Close, used to close kernel object handles) and the use of an "opaque predicate wrapping" strategy as an example, the underlying prompt framework actually invoked is as follows:
[0099] System Prompt
[0100] You are an expert C++ developer targeting the Windows Platform (MSVC / MinGW).
[0101] Your task is to insert a function call into the provided C++ codesnippet.
[0102] CRITICAL RULES:
[0103] ONLY modify the provided snippet by inserting the requested functioncall.
[0104] DO NOT output the definition of the called function. (It is handledexternally).
[0105] PRESERVE ALL existing logic, braces, and variable declarations.
[0106] Return ONLY the updated C++ code snippet. No markdown wrappers.
[0107] NO HEADERS: Do not add any #include statements.
[0108]
User Prompt
[0109] Task: Insert a function call to call_NtClose into the Target Snippet.
[0110] [POSITION INFO]
[0111] Preferred insertion strategy: Wrap the function call inside analways-true 'if' condition that looks like legitimate system code (e.g., if(sizeof(int) == 4) or if (GetTickCount() > 0)). Insert this entire blocknaturally into the snippet.
[0112] [TARGET SNIPPET]
[0113] if (connected) {
[0114] int heartbeat_count = 0;
[0115] while (heartbeat_count < 5) {
[0116] std::this_thread::sleep_for(std::chrono::milliseconds(500));
[0117] heartbeat_count++;
[0118] }
[0119] }
[0120] [INSTRUCTION]
[0121] Output the FULL updated Target Snippet with call_NtClose(2);inserted.
[0122] CRITICAL: DO NOT output the definition of call_NtClose. Only insertthe call statement!
[0123] CRITICAL: Keep all original variables, braces, and logic EXACTLY asthey are.
[0124] NO #include statements.
[0125] Driven by this highly structured cue word, the large language model can accurately understand the context and output K candidate variant codes with equivalent core functions but different code forms in parallel.
[0126] (2-3-3) Syntax pruning and optimal variant selection: Using the AST in step (2-1), static syntax checks are performed on all candidate variant codes, and candidate variant codes with basic syntax errors are eliminated (i.e., syntax pruning). Subsequently, for the legal candidate variant codes that pass the detection, semantic confidence scores are calculated using the method in step (2-2-2), and a comprehensive score is calculated. The codes are sorted in descending order of comprehensive score, and only the optimal variant code with the highest quality is retained as the candidate code to be written into the final source code.
[0127] (2-3-4) Failure memory feedback: If all generated candidate variant codes fail the AST static syntax check, the insertion is abandoned to protect the source code, and the combination of "(target API, code snippet ID)" is recorded in the global failure blacklist of step (2-2-1) so that these combinations are avoided in subsequent iterations.
[0128] (2-4) Source Code Rewriting: After the screening in step (2-3-3), if the optimal variant code is successfully captured, the system will officially integrate the local variant generated by the large model into the global source code. Using the first and last byte offsets recorded in the AST, the generated optimal variant code segment containing the target API is overwritten back into the source code. At the same time, the remaining number of times the API is used is deducted and the congestion of the parent function is updated, driving MCTS into the next round of scheduling iterations until all feature perturbation requirements have been injected.
[0129] To verify the effectiveness of the proposed method in the adversarial variant generation task, the performance of this invention is evaluated against current mainstream methods. The comparative evaluation covers both non-large language models and large language models, and employs the following three core evaluation metrics: BR (Bypass Rate), which refers to the proportion of processed malicious samples that are judged as benign by the detector, used to measure the escape capability of the adversarial method; CR (Compilation Rate), which refers to the proportion of code that, after perturbation injection, can still be successfully compiled into an executable file, used to evaluate the syntactic validity of the variant code generated by the adversarial method; and FRR (Function Retention Rate), which refers to the proportion of processed samples that retain the original malicious function, used to verify that the adversarial method does not destroy the core semantics of the sample.
[0130] The specific experimental data are shown in Table 1. As can be seen from the data in the table, the present invention outperforms the current mainstream methods in all indicators of BR, CR and FRR, which fully demonstrates that the present invention significantly improves the escape effect of adversarial samples on black box detectors while ensuring the integrity of malicious functions and compilation availability.
[0131] Table 1 Comparison of Method Performance
[0132]
[0133] Among them, GADGET is the method proposed in the paper "Generic Black-Box End-to-End Attack Against State of the Art API Call Based Malware Classifiers"; Badger is the method proposed in the paper "Generic Black-Box End-to-End Attack Against State of the Art API Call Based Malware Classifiers"; MalGuise-style is the method proposed in the paper "Practical Black-box Adversarial Attacks for Evading Learning-based Windows Malware Detection"; EaTVul-style is the method proposed in the paper "EaTVul: ChatGPT-based EvasionAttack Against Software Vulnerability Detection"; and RLEF-style is the method proposed in the paper "RLEF: Grounding Code LLMsin The method proposed in "Execution Feedback with Reinforcement Learning (RLEF: Using Reinforcement Learning to Establish Real Execution Basis for Code-Large Language Models)" is as follows.
[0134] The embodiments described above are merely illustrative of several implementations of the present invention, and while the descriptions are relatively specific and detailed, they should not be construed as limiting the scope of the invention patent. It should be noted that those skilled in the art can make various modifications and improvements without departing from the concept of the present invention, and these all fall within the protection scope of the present invention. Therefore, the protection scope of this invention patent should be determined by the appended claims.
Claims
1. A method for combating malicious code perturbations that integrates abstract syntax trees and large language models, characterized in that, The malicious code perturbation method that integrates abstract syntax trees and large language models includes: Extract the API call frequency feature vector of the target malicious code sample, perturb the API call frequency feature vector through adversarial attack algorithm to generate adversarial feature vector that meets the preset hard constraints, and extract the difference vector between the adversarial feature vector and the API call frequency feature vector to determine the category of the API to be inserted and the corresponding insertion frequency. In the difference vector, the index of the feature dimension with a value greater than zero corresponds to the category of the API to be inserted, and the value corresponds to the insertion frequency. The source code of the target malicious code sample is parsed to generate an abstract syntax tree. Based on the abstract syntax tree, the source code is divided into multiple code segments, and the structural depth feature labels of each code segment are extracted. The structural depth feature labels include the nesting depth of loops and the nesting depth of regular loops. Construct a Monte Carlo tree search model, combine it with structural depth feature labels, calculate the comprehensive score of each API to be inserted to be assigned to each code segment, and obtain the optimal insertion strategy based on the comprehensive score; Based on the optimal insertion strategy, the API to be inserted is integrated into the target code fragment using a large language model combined with a bundle search algorithm to generate candidate variant code. Static syntax checking is performed on each candidate variant code using an abstract syntax tree, and the optimal variant code is selected. If all candidate variant codes fail the static syntax check, the insertion is abandoned. By writing the optimal variant code into the source code, we can obtain anti-malicious source code that can bypass the detection model; in, The construction of the Monte Carlo tree search model, combined with structural depth feature labels, calculates a comprehensive score for assigning each API to be inserted to various code snippets, and obtains the optimal insertion strategy based on the comprehensive score, including: A pre-defined mapping dictionary between APIs and feature keywords; Iterate through the abstract syntax tree nodes of each code snippet, and check whether there are any feature keywords that are the same as the API to be inserted according to the mapping dictionary. If there are, assign different semantic confidence to the API to be inserted according to the node type and the preset semantic tag rule table. If not, directly assign the preset semantic confidence to the API to be inserted. Construct a Monte Carlo tree search model and initialize the evaluation environment; Code snippets with a regular nesting depth greater than 0 will receive bonus points, while code snippets with a loop nesting depth greater than 0 will receive deduction points. Based on semantic confidence, bonus points, and penalty points, a comprehensive score is calculated for each pairing scheme of API and code snippet to be inserted; The pairing scheme with the highest overall score is selected as the optimal insertion strategy.
2. The method for combating malicious code perturbations by integrating abstract syntax trees and large language models according to claim 1, characterized in that, The process involves extracting the API call frequency feature vector from the target malicious code sample, perturbing the API call frequency feature vector using an adversarial attack algorithm to generate an adversarial feature vector that satisfies preset hard constraints, and extracting the difference vector between the adversarial feature vector and the API call frequency feature vector to determine the category and corresponding insertion frequency of the API to be inserted. This includes: The target malware sample was simulated using a sandbox analysis tool to obtain the API sequence called by the target malware sample, and the bag-of-words model was used to transform the API sequence into an API call frequency feature vector. Construct a proxy detection model and train the proxy detection model based on the feedback labels of the API call frequency feature vector from the target detection model; The API call frequency feature vector is normalized using MinMax. An adversarial attack algorithm is used to perturb the normalized API call frequency feature vector on the proxy detection model. Then, a non-negative truncation mechanism is used to ensure that the perturbation increment is non-negative, and the adversarial feature vector is output. Calculate the difference vector between the adversarial feature vector and the API call frequency feature vector.
3. The method for combating malicious code perturbations by integrating abstract syntax trees and large language models according to claim 1, characterized in that, Before dividing the source code into multiple code fragments based on the abstract syntax tree, the following is also included: A high-frequency keyword library is built based on frequently called functions; Check if the name of each target function in the source code contains keywords from the high-frequency keyword library, and if the number of child nodes of the target function is less than a preset threshold. If so, add the current target function to the global failure blacklist and prohibit the insertion of APIs into the code segment to which the current target function belongs in subsequent steps.
4. The method for combating malicious code perturbations by integrating abstract syntax trees and large language models according to claim 1, characterized in that, The provision of bonus points for code snippets with a regular nesting depth greater than 0 and penalty points for code snippets with a loop nesting depth greater than 0 includes: When the regular nesting depth is greater than 0 and less than or equal to 5, the bonus points increase for each additional level of regular nesting depth. When the regular nesting depth is greater than 5, the bonus points no longer increase. When the nesting depth of the loop is greater than 0, the penalty for each additional level of nesting depth increases accordingly.
5. The method for combating malicious code perturbations by integrating abstract syntax trees and large language models according to claim 1, characterized in that, The step of using a large language model combined with a beam search algorithm to integrate the API to be inserted into the target code fragment according to the optimal insertion strategy, and generating candidate variant code, includes: The insertion frequency of a single actual allocation is calculated using the following formula: in, This represents the insertion frequency in a single actual allocation. Indicates the remaining number of insertions. Indicates will Halve and round down. Represents a random perturbation function; Based on the preset search width K of the cluster search algorithm, an obfuscation strategy is assigned to K search branches from the predefined obfuscation strategy pool; Based on the API to be inserted, the actual insertion frequency in a single instance, the obfuscation strategy bound to the K search branches, and the context source code of the code snippet, construct K prompt words; The large language model outputs K candidate variant codes based on K cue words.
6. The method for combating malicious code perturbations by integrating abstract syntax trees and large language models according to claim 1, characterized in that, The process involves using an abstract syntax tree to perform static syntax checks on each candidate variant code and selecting the optimal variant code. If all candidate variant codes fail the static syntax check, the insertion is abandoned. This includes: Static syntax checking is performed on each candidate variant code using an abstract syntax tree. Syntax pruning is performed on candidate variant codes with illegal syntax. A comprehensive score is calculated for candidate variant codes with legal syntax. The candidate variant code with the highest comprehensive score is selected as the optimal variant code. If all candidate variant codes are syntactically invalid, then abandon the current insertion and add the current best insertion strategy to the global failure blacklist.
