Malicious code advanced identification method based on static analysis and semantic generation
By using static analysis and semantic generation methods, the control flow graph of the binary program is extracted and a sequence of function names is generated, which solves the problems of interpretability and cross-platform adaptability in existing malicious code detection technologies, and achieves efficient and interpretable malicious code identification.
Patent Information
- Application Number
- CN202511566263.3
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2025-10-30
- Publication Date
- 2026-02-03
AI Technical Summary
Existing malware detection methods struggle to effectively integrate structural and semantic information when faced with highly obfuscated, polymorphic, and cross-platform attacks. This results in insufficient model generalization ability and poor interpretability, and traditional static analysis methods are unable to generate high-level semantic representations.
We employ a method based on static analysis and semantic generation. We use a disassembler to extract the function-level control flow graph of the binary file, learn node embedding representations through a graph convolutional network, and generate function name sequences through a memory-enhanced sequence generation model. We then combine an expert knowledge base and a large language model to determine malicious intent.
It significantly improves the adaptability to obfuscated code and cross-architecture binaries, enhances the interpretability of model output, provides intuitive decision support, and can efficiently identify known and unknown malware variants.
Smart Images

Figure CN121456876A_ABST
Abstract
Description
Technical Field
[0001] This invention belongs to the technical field of network security and malicious code detection, and mainly relates to an advanced method for identifying malicious code based on static analysis and semantic generation, which is applicable to the functional identification and malicious behavior detection of binary programs. Background Technology
[0002] In recent years, with the continuous evolution of cyberattack methods, malicious code has exhibited characteristics such as high obfuscation, polymorphism, and cross-platform compatibility, posing a severe challenge to traditional detection methods based on signature-based or dynamic behavior analysis. While dynamic analysis methods can capture runtime behavioral characteristics, they are susceptible to interference from anti-debugging and environment-aware technologies, resulting in low detection efficiency and limited coverage. On the other hand, existing static analysis methods mostly rely on manually defined features or shallow machine learning models, making it difficult to extract semantically meaningful deep features from binary code, leading to insufficient model generalization ability and poor interpretability.
[0003] Currently, deep learning-based static analysis methods are increasingly being applied to malware detection. Some methods treat binary files as images or sequences, improving automation to some extent, but limitations remain. For example, while image-based methods are highly efficient, they lose the structural semantics of the code; sequence-based methods struggle to effectively model the control flow structure of a program and are less robust to code obfuscation and variant attacks. Furthermore, most existing methods fail to effectively integrate structural and semantic information, hindering end-to-end mapping from code structure to behavioral semantics, thus limiting their application in advanced threat identification.
[0004] Although existing research has attempted to introduce graph neural networks to process structural information such as control flow graphs, there are still shortcomings in semantic representation and generation. Most methods only stay at the graph structure embedding level and fail to generate interpretable high-level semantic representations, such as function names and behavioral descriptions. This results in a lack of interpretability in the model output, making it difficult for security analysts to support in-depth understanding and verification of malicious behavior.
[0005] Therefore, there is an urgent need for a new malicious code identification method that can combine static analysis and semantic generation, which can automatically extract structural features from binary programs and generate high-level semantic representations, thereby improving the ability to identify and interpret unknown malicious code and its variants. Summary of the Invention
[0006] This invention addresses the shortcomings of existing technologies, such as insufficient semantic understanding of binary code, poor interpretability, and poor adaptability to code obfuscation and variants. It provides an advanced malware identification method based on static analysis and semantic generation. First, a disassembler is used to disassemble the binary file and convert it to P-Code intermediate representations, extracting function-level control flow graphs and their basic block features. Then, the control flow graph is encoded using a graph convolutional network, learning the embedded representations of nodes and the global graph. Next, by introducing a node attention mechanism and a memory-enhanced sequence generation model, the graph structure information is decoded into a sequence of function names in natural language. Finally, an expert knowledge base and a large language model are used to determine the malicious intent of the generated semantic content, completing the identification and classification of malware. This invention not only significantly improves adaptability to obfuscated code and cross-architecture binary files but also enhances the interpretability of the model output, providing security analysts with intuitive and reliable decision support.
[0007] To achieve the above objectives, the technical solution adopted by this invention is: an advanced malicious code identification method based on static analysis and semantic generation, comprising the following steps:
[0008] S1: Input the binary file into the disassembler, disassemble the binary program, and extract the function control flow graph and P-Code intermediate representation instructions;
[0009] S2: Based on the function control flow graph and P-Code intermediate representation instructions obtained in step S1, construct graph structure data. ,in, This represents a set of nodes, corresponding to the basic blocks of a function; The edge set represents the control flow transfer relationship between basic blocks; It represents the set of node features, which consists of the statistical quantity features of various P-Code instructions within each basic block;
[0010] S3: Use a graph convolutional network to encode the graph structure data constructed in step S2, learn the structural information of nodes and their neighbors, generate node embedding vectors, and generate global graph embedding vectors through an aggregation function;
[0011] S4: By using a memory-enhanced Long Short-Term Memory network, the node embedding vectors generated in step S3 and the global graph embedding vectors are fused together to decode and generate a sequence of function names;
[0012] S5: Based on the sequence of function names generated in step S4, semantic parsing and malicious intent judgment are performed using an expert knowledge base or a large language model to identify functions with malicious behavior.
[0013] As an improvement of the present invention, the disassembler in step S1 is Ghidra, and the disassembly process includes at least identifying function boundaries, parsing function signatures, and disassembling instructions;
[0014] The function boundary identification method is based on symbol information extraction, instruction pattern matching, control flow analysis and heuristic methods to determine the start and end positions of functions in binary code, forming the basic unit of program execution logic.
[0015] The function signature parsing method works as follows: when symbolic information is available, the function information is read directly; when symbolic information is lacking, the function information is inferred based on the calling convention and through data flow analysis.
[0016] The disassembly instructions parse the binary code into low-level assembly instructions and convert them into hardware-independent general intermediate representation P-Code.
[0017] As another improvement of the present invention, in the graph structure data G of step S2,
[0018] Node set The middle part is the basic block that divides continuously executed instructions without internal jumps by traversing the P-Code instruction sequence;
[0019] edge set This establishes the control flow transfer relationships between basic blocks based on jump, call, and return instructions.
[0020] Node feature set The specific method for obtaining the features of all nodes is as follows: P-Code instructions are divided into six categories: data operation, memory access, transformation operation, special operation, comparison operation, and control flow operation. A six-dimensional counter vector is initialized, corresponding to the above six categories respectively. All P-Code instructions within the basic block are traversed, and the corresponding dimension in the counter vector is incremented according to the category to which the opcode belongs. The counter vector corresponding to each basic block is the feature of that node.
[0021] The graph structure data ,in For the set of basic block nodes, Let be the set of edges. This is the node feature matrix.
[0022] As another improvement of the present invention, in step S3, a graph convolutional network is used to encode the graph structure, and the feature information of nodes and their neighbors is aggregated through multi-layer convolutional operations. The node representation is updated layer by layer to learn the node embedding vector; in the layer-by-layer node update, the first... The formula for updating the node features of a layer is as follows:
[0023]
[0024] in, To add the adjacency matrix after adding self-loops, For the image The adjacency matrix, Let n be the identity matrix. It is by The calculated degree matrix contains elements on its diagonal. Represents a node The degree, , For matrix The element in the i-th row and j-th column, For the first The node feature matrix of the layer, , For the first Layer-trainable weight matrix, It is the ReLU activation function;
[0025] go through After the layer graph convolution operation, the final node embedding matrix is obtained as follows: Global graph embedding vectors are generated using the max-pooling aggregation function. .
[0026] As another improvement of the present invention, in step S4, the memory-enhanced long short-term memory network uses a node attention module to embed nodes into a vector sequence. This is converted into the candidate cell state at each step of the decoder, the node attention weights, and the candidate cell state at time t. The calculation method is as follows:
[0027]
[0028]
[0029]
[0030] in, This represents the hidden state of the decoder at time t-1. For learnable parameters, For the first The embedding vector of each node, the global graph embedding vector As the initial hidden state of the Long Short-Term Memory (LSTM) network for decoders The MALSTM unit at time Cellular state The updated formula is as follows:
[0031]
[0032]
[0033]
[0034]
[0035] in, For the Gate of Oblivion For input gate, For output gate, The input at time t, The ReLU activation function is used. For learnable parameters, the output gate and cell state Calculate the output at the current time. and hidden state This generates a sequence of function names step by step.
[0036] As a further improvement of the present invention, step S5 specifically includes the following steps:
[0037] S51: Divide the sequence of function names generated in step S4 into a sequence of tokens according to a predetermined naming convention;
[0038] S52: Build a predefined expert knowledge base containing a set of keywords related to malicious behavior. The keyword categories include, but are not limited to, code execution, process injection, file tampering, network communication, privilege escalation, anti-identification, keylogging, driver loading, and sandbox identification;
[0039] S53: Match the word token sequence from step S41 with the keywords in the expert knowledge base from step S52. If any word token exists in the sequence... satisfy If so, it is determined that the function corresponding to the sequence of function names has malicious intent;
[0040] S54: Input the sequence of function names from step S51 into the large language model. Prompt it to generate explanatory text about the function's functionality and judge malicious intent through preset prompt words. For functions that the large language model determines have potential security risks or ambiguous attack intent, mark them as having malicious intent.
[0041] Compared with the prior art, the present invention has the following beneficial effects:
[0042] (1) This invention combines static analysis of binary code, graph structure modeling, and semantic generation to construct an end-to-end malicious code identification framework. This method uses reverse analysis tools such as Ghidra to convert binary files into architecture-independent P-Code intermediate representations, and constructs function control flow graphs accordingly. This effectively overcomes the differences caused by different instruction sets and compilation optimization options, and significantly improves the generalization ability of cross-platform analysis and the robustness to code obfuscation techniques.
[0043] (2) This invention employs a semantic generation model that combines a graph convolutional network encoder with a memory-enhanced long short-term memory network decoder to automatically learn and generate a sequence of function names describing the high-level semantics of functions from the control flow graph structure. Compared to traditional black-box models that only output classification labels, this method provides intuitive and interpretable semantic output, enabling analysts to understand the basis for the model's judgments and greatly enhancing the credibility and verifiability of the recognition results.
[0044] (3) This invention integrates a dual judgment mechanism of keyword matching based on expert knowledge and semantic reasoning based on a large language model. This method can not only efficiently identify known keywords with obvious attack characteristics, but also utilize the deep semantic understanding capabilities of LLM to perform contextual analysis on ambiguous, novel or disguised malicious intents, thereby effectively reducing the false positive rate while ensuring a high recall rate, and achieving efficient and accurate identification of known and unknown malicious code variants. Attached Figure Description
[0045] Figure 1 This is a flowchart of the steps of the method of the present invention;
[0046] Figure 2 This is a schematic diagram of the P-Code instruction sequence structure extracted in Embodiment 1 of the present invention;
[0047] Figure 3 This is a schematic diagram of the structure of the dictionary-style control flow graph constructed in Embodiment 1 of the present invention;
[0048] Figure 4 This is a schematic diagram of the disassembly and representation construction stage of steps S1 and S2 in Embodiment 2 of the present invention;
[0049] Figure 5 This is the control flow graph composed of assembly instructions in Embodiment 2 of the present invention;
[0050] Figure 6 This is the control flow graph composed of P-code instructions in Embodiment 2 of the present invention;
[0051] Figure 7 This is a diagram of the graph parsing and semantic generation model framework in Embodiment 3 of the present invention;
[0052] Figure 8 This is a schematic diagram of an attack identification experiment based on expert knowledge in the test examples of this invention;
[0053] Figure 9 This is a heatmap of the confusion matrix of different models in the test examples of this invention;
[0054] Figure 10 This is a schematic diagram of attack identification based on a large language model in the test examples of this invention. Detailed Implementation
[0055] The present invention will be further illustrated below with reference to the accompanying drawings and specific embodiments. It should be understood that the following specific embodiments are for illustrative purposes only and are not intended to limit the scope of the invention.
[0056] Example 1
[0057] An advanced method for identifying malicious code based on static analysis and semantic generation can be applied to network security analysis scenarios.
[0058] like Figure 1 As shown, the malicious code identification process is as follows: "Input of binary file data to be detected (mainly .o format files) → Ghidra static analysis → Extraction of function control flow information → Data preprocessing (extraction of control flow graph structural features to reduce redundancy) → Graph parsing and semantic generation model (generation of semantically meaningful function names) → Parsing function semantics → Malicious code identification → Malicious code label output (output of whether it belongs to malicious code and marking its malicious family)". This method realizes end-to-end processing from binary code parsing to threat identification, effectively responding to code obfuscation and variant attacks, and ultimately generating a security strategy to form a complete protection closed loop.
[0059] This embodiment uses 10,764 binary files compiled from a large open-source project (such as OpenSSL) as the analysis object to systematically verify the end-to-end processing capability and feature extraction effectiveness of the method of this invention in large-scale real code data. This dataset was compiled using both GCC and Clang compilers, applying O1, O2, and O3 three-level optimization strategies respectively, forming a set of binary variants with significant structural differences. Different compilers have fundamental differences in underlying optimization strategies such as instruction scheduling, register allocation, and control flow layout. These binary variants from the same source code exhibit significant differentiation at the machine instruction sequence and control flow structure levels, effectively simulating the typical scenario of semantically equivalent but structurally heterogeneous programs caused by structural obfuscation techniques used by real malicious code to evade detection. The binary files were batch disassembled using the Ghidra reverse engineering platform, successfully identifying a total of 11,340 function bodies.
[0060] Step S1: The compiled binary file is used as input, and the input binary program is disassembled using the disassembler Ghidra. This process successfully identified a total of 11,340 function bodies by identifying function boundaries and basic block divisions; further, the control flow graph of each function is extracted, where nodes represent basic blocks and edges represent control flow transfer relationships; simultaneously, based on the intermediate representation P-Code instructions of the selected disassembler, the P-Code instruction sequence within each basic block is extracted and stored as a JSON file, such as... Figure 2 As shown.
[0061] The input binary program was disassembled using the reverse engineering tool Ghidra. The process included identifying function boundaries, parsing function instructions, and converting the assembly instructions into hardware-independent P-Code intermediate representation instructions. Based on the P-Code instruction sequence, a control flow graph for each function was constructed. By traversing the P-Code instruction sequence, continuously executed instructions without internal jumps were divided into basic blocks as nodes, and directed edges were established between these basic blocks based on jump, call, and return instructions to represent control flow transfer relationships. The graph structure information of the control flow graph was output along with the P-Code instruction sequence.
[0062] Step S2: Based on the function control flow graph and P-Code instructions, construct graph structure data. ,in This represents a set of nodes, corresponding to the basic blocks of a function; The edge set represents the control flow transfer relationship between basic blocks; The node feature set is composed of the statistical quantity characteristics of various P-Code instructions within each basic block, as shown in the table below:
[0063]
[0064] P-Code opcodes are functionally categorized into six classes: data manipulation, memory access, transformation, special operations, comparison, and control flow. Data manipulation opcodes are formed by combining arithmetic and logical opcodes. For each basic block node in the function control flow graph, a six-dimensional counter vector is initialized, corresponding to each of the six categories. All P-Code instructions within the basic block are traversed, and the corresponding dimension in the counter vector is incremented based on the opcode's category. The counter vector corresponding to each basic block is used as the feature of that node, and the features of all nodes constitute a node feature matrix. The graph structure data is ultimately represented as ,in For the set of basic block nodes, Let be the set of edges. This is the node feature matrix.
[0065] To construct a high-quality dataset suitable for graph model processing, the original function set was filtered, removing functions with overly simple control flow structures, such as those containing only a single basic block. Ultimately, the experiment retained 6593 functions with complex control flow structures. The P-Code instructions within each basic block were categorized and statistically analyzed according to operation type, forming a multi-dimensional feature vector. These features were then standardized to eliminate dimensional differences. Simultaneously, all valid control transfer edges in the control flow graph were retained, constructing a directed graph structure.
[0066] This invention stores the directed graph in the form of a dictionary, containing directed edges between basic blocks and feature information about the opcode categories of the basic blocks. Finally, it stores this information in a JSON file named after the function names. This dictionary-like storage is as follows: Figure 3 As shown.
[0067] Figure 3 As can be seen, this dictionary-style data represents a directed graph with 8 nodes and 8 edges. Each edge is represented by a tuple, which indicates the index of the starting basic block and the index of the basic block it points to. The node feature vector is a hexagram, which contains the instruction-level semantic features within the basic block.
[0068] Step S3: Encode the graph structure data using a graph convolutional network, learn the structural information of nodes and their neighbors, generate node embedding vectors, and generate global graph embedding vectors through an aggregation function.
[0069] A multi-layer graph convolutional network is used to perform message passing and feature aggregation on the constructed graph structure. Each layer updates the current node representation by aggregating the feature information of neighboring nodes, and finally obtains the low-dimensional embedding vector of each node. On this basis, the node-level embeddings are fused into a global graph embedding vector through max pooling to capture the overall structural features of the function.
[0070] Step S4: By using a memory-enhanced Long Short-Term Memory network, the node embedding vector and the global graph embedding vector are fused to decode and generate a natural language text sequence describing the function behavior, i.e., a sequence of function names.
[0071] The node embedding sequence is weighted and fused with the global graph embedding as the context input of the memory-enhanced LSTM decoder. The LSTM unit dynamically accesses the external memory module during the decoding process to enhance the ability to model long sequences and complex function behavior. Through time-step unfolding, a sequence of natural language words describing the semantics of the function is gradually generated, and the function name prediction result is finally output.
[0072] Step S5: Based on the generated sequence of function names, semantic parsing and malicious intent judgment are performed in conjunction with a predefined expert knowledge base or large language model to identify functions with malicious behavior.
[0073] The generated sequence of function names is input into a pre-built malicious behavior knowledge base and a large language model for semantic matching and intent analysis, and its similarity with known malicious function patterns is calculated. If the similarity exceeds a set threshold, the function is determined to have malicious behavior, and the corresponding malicious type is output. At the same time, it supports the detection of unknown malicious patterns and identifies potential suspicious functions through an anomaly scoring mechanism, providing a basis for subsequent manual analysis.
[0074] The method of this invention performs deep static analysis on binary files using the Ghidra reverse engineering platform, including key steps such as function boundary identification, function signature parsing, instruction disassembly, and P-Code conversion. Function boundary identification comprehensively utilizes symbol table information, instruction pattern matching, control flow analysis, and heuristic methods. Function signature parsing infers parameter information based on multiple calling conventions. Finally, a function control flow graph is constructed and P-Code operation features are extracted to form a structured feature representation.
[0075] Building upon this foundation, a graph-sequence generation model is employed to achieve advanced semantic extraction. First, a graph convolutional network is used to learn node embedding representations and a graph Laplacian regularization term is introduced to enhance structural consistency. Second, a feedforward neural network in the node attention module calculates attention weights, providing local node information to the encoder. Subsequently, a memory-enhanced long short-term memory network initializes the hidden state through global graph embedding and gradually generates function noun sequences by combining candidate cell states provided by node attention. The model is trained using the Adam optimizer and employs cross-entropy loss and graph regularization weighting as the objective function. Finally, malicious attack identification is performed on the generated function names. An expert knowledge-based method uses a security-sensitive keyword library for string matching, while a large language model-based method leverages the semantic understanding capabilities of a pre-trained model to analyze operation types, concealment characteristics, and call relationships through a multi-level evaluation strategy. The combination of these two methods achieves high-precision, interpretable malicious code detection, effectively addressing advanced threats such as code obfuscation and variant attacks, ultimately forming a complete technical loop from binary code parsing to advanced semantic understanding and malicious intent identification.
[0076] Example 2
[0077] As described in Example 1, a method for extracting malicious code features based on static analysis involves steps S1 and S2 performing reverse analysis and structured representation of a binary program. Using a compiled binary file as input, it is first reverse-engineered into an intermediate decompiled data structure, P-Code. These intermediate structures are then transformed into graph vector representations suitable for subsequent tasks, providing high-quality feature input for subsequent malicious code identification. The method specifically includes two stages: disassembly and representation construction. Its workflow framework is as follows: Figure 4 As shown.
[0078] First, in the disassembly stage of step S1, the compiled binary file is taken as input and disassembled using a reverse engineering platform, converting it into an intermediate decompiled data structure, P-Code. The disassembly stage of step S1 includes:
[0079] (1) Identify function boundaries: By comprehensively utilizing symbol information extraction, instruction pattern matching, control flow analysis (CFA) and heuristic methods, the start and end positions of functions in binary code are determined, forming the basic units of program execution logic.
[0080] (2) Parse function signature: When symbolic information is available, directly read the function name, return type, parameter type and number, etc.; when symbolic information is lacking, infer the number, type and passing method of the function parameters based on the calling convention and through data flow analysis (DFA).
[0081] (3) Disassembling instructions: The binary code is parsed into low-level assembly instructions, and then converted into hardware-independent general intermediate representation P-Code. P-Code expresses operations in a three-address code form that is closer to the semantic structure of high-level languages by abstracting low-level register operations, conditional jumps, function calls and memory access.
[0082] (4) During the disassembly process, maintain reference information for registers and memory resources.
[0083] Step S2 represents the construction phase. Building upon the results of the disassembly phase, it further explores the internal structure of the code and constructs a structured feature representation for subsequent analysis. This phase specifically includes:
[0084] (5) Extract reference information: Further extract reference information of registers and memory.
[0085] (6) Constructing the function control flow graph: The control flow graph is used to describe the execution path and control structure within a function. Its basic components include nodes and edges. Nodes correspond to a sequence of instructions that are executed continuously in the program without internal jumps, i.e., basic blocks. Edges represent the control flow transfer relationship between basic blocks, such as jumps and call instructions.
[0086] In constructing a control flow graph, the assembly instruction sequence is first traversed, dividing consecutively executed instructions into basic blocks. When a jump, function call, or return instruction is encountered, the end of the current basic block is marked and stored in the basic block list. Subsequently, based on the jump target of the instruction at the end of each basic block and its sequential relationship with adjacent basic blocks, edges are established between the basic blocks, thus forming a complete control flow graph that visually reflects the program's execution logic and path information. Figure 5 As shown, each block diagram represents a basic block, and each edge represents a control flow transition, including unconditional jumps, conditional jumps, and sequential execution. The first dashed box represents the starting basic block, and the last dashed box represents the ending basic block.
[0087] Based on this, the present invention first converts assembly instructions into P-Code instructions and then constructs the control flow graph. The control flow graph construction algorithm based on P-Code is similar to the control flow graph construction method based on assembly instructions, such as... Figure 6 As shown, this is a control flow graph constructed using Ghidra intermediate representation P-Code instructions. Unlike assembly instructions, it includes more semantics and is closer to high-level natural language.
[0088] This invention extracts function-level information from a program using the Ghidra decompiler and stores it in JSON format for subsequent analysis and processing. It first iterates through all functions in the current program and uses the DecompInterface provided by Ghidra for decompilation. To improve data validity, for functions that meet certain criteria, its basic information, including function name and entry address, is extracted, and its internal basic block structure is further parsed. The information for each basic block includes its index, start address, end address, size, and potential target blocks.
[0089] (7) Extracting Basic Block Features: Feature extraction is performed on each basic block in the control flow graph. First, the P-Code instructions within the basic block are categorized into six types based on their functions: data operations, memory access, translation operations, special operations, comparison operations, and control flow operations. Then, the list of P-Code instructions within each basic block is traversed, and the number of instructions in each category is counted based on their opcodes (op_code), forming a six-tuple feature vector (data_operations, memory_access, translate_operations, special_operations, compare_operations, control_flow_operations). This feature vector represents the instruction-level semantic features within the basic block. Finally, the control flow graph is represented as a directed graph structure. ,in For a set of nodes, Let be the set of edges. This is a set of node features. The graph structure data is stored in the form of a dictionary containing an array of edges and an array of node feature vectors, which serves as a feature representation of malicious code for subsequent analysis.
[0090] Example 3
[0091] A high-level semantic extraction method for malicious code based on graph structure parsing and semantic generation, in steps S3 and S4, performs deep modeling of the control flow graph of the binary program and generates semantic text describing the function behavior, such as... Figure 7 As shown, it mainly includes three main modules: graph coding network, node attention module, and decoder network.
[0092] After the graph structure obtained in step S2 is input into the graph encoding network, node embeddings are learned, and global graph embeddings are learned through max pooling aggregation. The node embeddings are then processed by a node attention module to learn the candidate cell states required for prediction at each step of the encoder network. This allows local node information to be stored as a long-term state to guide each prediction step. Simultaneously, the learned graph embeddings are input as the initial hidden state into the encoder network, progressively generating the target sequence, i.e., the function name.
[0093] In step S3, a graph convolutional network (GCN) is used to encode the graph structure. Through multiple convolutional operations, the feature information of nodes and their neighbors is aggregated, and the node representation is updated layer by layer to learn the node embedding vector. Specifically, to include the node's own information during the convolution process, the GCN modifies the original adjacency matrix... Add self-loops to form a new adjacency matrix. ,in It is the identity matrix. Secondly, GCN introduces a degree matrix D, whose diagonal elements... Represents a node Determine the degree and calculate the normalized degree matrix. Then, the adjacency matrix is symmetrically normalized to obtain... This ensures the stability and appropriate numerical range of feature aggregation. Finally, the core operation of GCN is to update the feature representation of nodes layer by layer. The node feature representation of a layer is calculated using the following formula:
[0094]
[0095] in, It is the first The node feature matrix of the layer, It is the first The trainable weight matrix of the layer, This is the activation function. The formula represents the weighted aggregation of node features in the current layer using a normalized adjacency matrix, multiplied by the weight matrix, and then passed through the activation function to obtain the node feature representation for the next layer. By updating nodes layer by layer, GCN can effectively capture the feature information of nodes and their neighbors in the graph, enabling deep learning of graph data.
[0096] To further differentiate between different function bodies and aggregate similar function bodies, a graph-based semi-supervised learning approach is adopted, which involves adding a graph Laplacian regularization term to the loss function.
[0097]
[0098] in, This represents the supervision loss defined for subsequent tasks. The weighting factor is the graph Laplace regularization term. The expression is:
[0099]
[0100] in, The feature matrix representing the node, Representing an undirected graph The unnormalized graph Laplacian matrix, with N nodes. ,side Adjacency matrix (Can be binary or weighted), and degree matrix In this way, the structural information of the graph is introduced into the model's learning process, so that similar nodes in the graph have similar prediction results in the model, thereby improving the model's performance.
[0101] Graph embeddings that express the entire graph information using max pooling aggregation are used, where the feature representation of each neighbor is passed through a fully connected neural network and then element-wise max pooling is applied.
[0102]
[0103] in, This indicates a maximum value operation for each element. It is a non-linear activation function. Through max pooling, the model can extract different feature information from the neighborhood set and generate a global graph embedding vector that represents the structure of the entire function.
[0104] In step S4, the node embedding vector sequence is converted into the candidate cell state, node attention weights, and... Candidate cell state at time 1 The calculation method is as follows:
[0105]
[0106]
[0107] Finally, the candidate cell state at the current moment is obtained by weighted summation. This state aggregates all nodes, focusing on the parts most relevant to the current decoding state:
[0108]
[0109] in, This represents the hidden state of the decoder at time t-1. For learnable parameters, For the first The embedding vectors of each node are used to construct a MALSTM decoder network, which utilizes the node attention module. It serves as external memory to update the cell state. At each time step Receive input word embedding And perform the following calculations:
[0110] The forgetting gate controls the degree to which the cell's state from the previous moment is preserved:
[0111]
[0112] Input gates control the degree to which new information is added:
[0113]
[0114] The output gate controls the proportion of cell states in the final output:
[0115]
[0116] The cell state update formula integrates external memory. :
[0117]
[0118] The final output in the hidden state is:
[0119]
[0120] Initial hidden state of the decoder Embedded by global graph Initialization after linear transformation: Ultimately, the hidden state... Predict the probability distribution of the vocabulary through the output layer. This generates a sequence of function names. .
[0121] Test Case
[0122] This test case is used to determine malicious intent for the method in this case, achieving automated and highly accurate malicious code recognition, including three stages: model training, function name prediction, and malicious determination. The overall process and experimental settings are as follows:
[0123] The experimental software environment is Python 3.8, PyTorch 2.4.1, CUDA 11.8, and cuDNN 8.6.
[0124] The experimental dataset for this test is sourced from the binary files extracted in Example 1, containing 6,593 function bodies. To verify the generalization ability of the model, the dataset is divided into 9,843 training samples and 2,468 test samples at a ratio of 20%. Different compilation variants of the same function are randomly assigned to the training set and the test set to ensure that the test set may contain all variant forms of the function, thus effectively testing the model's semantic understanding ability for unseen functions.
[0125] (1) In the semantic generation stage, 1,121 keyword Tokens with semantic representation significance are extracted from 6,593 function bodies. Before inputting into the semantic generation network, the discrete Token indices are first mapped to continuous high-dimensional vector representations through an encoding network. Let the vocabulary size be N = 1,121 and the word embedding dimension be D = 64. The encoding network maintains a trainable weight matrix , for the input Token index i (satisfying 0 <= i < N), the encoding network obtains the corresponding word embedding vector through a lookup table operation. This design abandons the traditional one-hot encoding scheme, avoiding both the computational overhead brought by explicit matrix multiplication and enabling the word embedding to adaptively learn semantic features through trainable parameters. Compared with the sparse high-dimensional representation of one-hot encoding, the dense low-dimensional vectors generated by this method significantly improve computational efficiency while retaining semantic information.
[0126] (2) In the training stage, the Adam optimizer is used for training. The initial learning rate is 0.001, the batch size (BatchSize) is set to 64, and training is carried out for 500 epochs. The learning rate decays to 0.5 of the original value every 100 epochs. The loss function is composed of the weighted cross-entropy loss and the graph Laplacian regularization term. Since the final task is sequence prediction, the cross-entropy term calculates the loss for each time step in the sequence and then takes the average:
[0127]
[0128] where is the length of the function sequence, Vocabulary size, that is, the number of word categories. It is a one-hot vector of the real word category. It is the probability distribution output by the model after passing through the softmax layer. Here are the weights of the regularization term. Represents the node feature matrix, Representation diagram Unnormalized graph Laplace matrix.
[0129] (3) In the function name prediction stage, to fully verify the technical solution of this invention, this test case constructed several baseline methods for comparative analysis. First, to verify the effectiveness of the graph coding network design, the GraphSAGE unsupervised learning algorithm was used to replace the original graph convolutional network (GCN), and a GraphSAGE-MALSTM comparative model was constructed. Second, to verify the necessity of the node attention module, a GCN-LSTM model without a node attention mechanism was constructed. This model only uses the global graph embedding as the initial cell state and no longer includes local node memory information. Finally, to verify the advantages of the memory-enhanced long short-term memory network (MALSTM) in the semantic generation stage, semantic generation networks based on RNN and Transformer were constructed as comparative benchmarks.
[0130] A semantic generative network based on RNN (GCN-RNN) outputs candidate cell states through node attention modules. With current input Perform the stitching, and then update the hidden state:
[0131]
[0132] in, and This is the weight matrix. As the bias vector, the semantic generative network based on Transformer (GCN-Transformer) adopts a multi-head attention mechanism, using the node embedding sequence as the query and the encoder output as the key and value, to achieve effective attention to local node information.
[0133] Finally, the model was evaluated on a real-world application task—function name prediction—and the results are shown in the table below.
[0134]
[0135] As shown in the table above, the GCN-MALSTM model proposed in this invention achieved the highest BLEU-4 score, significantly outperforming other baseline models. The GraphSAGE-MALSTM model, due to its inductive node embedding learning algorithm, cannot be fine-tuned for specific tasks, resulting in slightly inferior learning performance compared to GCN. The GCN-LSTM model suffers a significant performance degradation due to the lack of a node attention mechanism, demonstrating the crucial role of the node attention module in this invention. Regarding semantic generation networks, MALSTM significantly outperforms RNNs and slightly surpasses Transformers, showcasing the advantages of memory enhancement mechanisms in semantic generation tasks.
[0136] (4) Malicious attack identification stage: In order to verify the effectiveness of the present invention in malicious attack identification, this embodiment marks 1156 malicious functions from 12311 functions. This identification task can be regarded as a graph classification problem, that is, classification is performed based on learning graph embedding.
[0137] This test case implements four baseline models based on graph neural networks for comparative analysis. The classification model based on GCN aggregates the features of nodes and their neighborhoods through convolution operations; the model based on GraphSAGE adopts a neighbor sampling and feature aggregation strategy; the model based on Graph Attention Network (GAT) uses a self-attention mechanism to distinguish the importance of neighboring nodes; and the model based on Graph Autoencoder (GAE) learns the embedding representation of the graph through an autoencoder architecture.
[0138] The GCN-MALSTM model first generates a semantic sequence of function names describing the function's behavior, and then determines malicious intent based on an expert knowledge base. The system breaks down the generated function names into a sequence of lexical tokens and matches them against a predefined database of security-sensitive keywords. For example... Figure 8 As shown, when a function name sequence contains keywords such as "exec" or "injector", the function is considered to have a risk of malicious behavior. For example, the functions "handle_input_exec_with_params" and "command_line_injector" were accurately identified as malicious functions because they contain the keywords "exec" and "injector" respectively.
[0139] like Figure 9As shown, the confusion matrices for different models are illustrated. Experimental results demonstrate that the proposed GCN-MALSTM model performs optimally in malicious sample identification, achieving 855 true positive (TP) samples, significantly outperforming all baseline models. Specifically, the GCN and GraphSAGE models exhibit good accuracy in processing structured graph data, but have limited recall in complex graph structures. The GAT model performs exceptionally well in complex graph structures through its attention mechanism, while the GAE model exhibits relatively weak classification performance due to the imperfect match between its reconstruction target and the classification task. In contrast, the GCN-MALSTM model not only inherits the advantages of GCN in graph structure learning but also achieves more comprehensive feature learning through semantic generation tasks, ultimately achieving the best overall performance in malicious attack identification, fully demonstrating the practical value of the technical solution of this invention in the field of network security.
[0140] As a supplementary solution to rule matching based on expert knowledge base, the sequence of function names is input into ChatGPT-4.0, such as... Figure 10 As shown, by using preset prompts such as "What does this function name mean?" and "Does this function have malicious intent?", the model generates explanatory text about the function's functionality and judges malicious intent. LLM can provide richer contextual semantic analysis. For functions that are ambiguous in the expert knowledge base or have potential security risks, it provides deeper semantic explanations and risk assessments, and ultimately makes a comprehensive judgment on whether they have malicious intent.
[0141] In summary, this invention provides an advanced malware identification method based on static analysis and semantic generation. This method integrates static reverse analysis, graph structure modeling, and semantic generation techniques to construct an end-to-end malware identification framework. It can automatically extract control flow structure features from binary programs and generate semantically interpretable function name sequences, thereby achieving high-precision and highly interpretable identification of malware.
[0142] It should be noted that the above content merely illustrates the technical concept of the present invention and should not be construed as limiting the scope of protection of the present invention. For those skilled in the art, various improvements and modifications can be made without departing from the principle of the present invention, and all such improvements and modifications fall within the scope of protection of the claims of the present invention.
Claims
1. An advanced method for identifying malicious code based on static analysis and semantic generation, characterized in that... It includes the following steps: S1: Input the binary file into the disassembler, disassemble the binary program, and extract the function control flow graph and P-Code intermediate representation instructions; S2: Based on the function control flow graph and P-Code intermediate representation instructions obtained in step S1, construct graph structure data. ,in, This represents a set of nodes, corresponding to the basic blocks of a function; The edge set represents the control flow transfer relationship between basic blocks; It represents the set of node features, which consists of the statistical quantity features of various P-Code instructions within each basic block; S3: Use a graph convolutional network to encode the graph structure data constructed in step S2, learn the structural information of nodes and their neighbors, generate node embedding vectors, and generate global graph embedding vectors through an aggregation function; S4: By using a memory-enhanced Long Short-Term Memory network, the node embedding vectors generated in step S3 and the global graph embedding vectors are fused together to decode and generate a sequence of function names; S5: Based on the sequence of function names generated in step S4, semantic parsing and malicious intent judgment are performed using an expert knowledge base or a large language model to identify functions with malicious behavior.
2. The advanced malware identification method based on static analysis and semantic generation as described in claim 1, characterized in that: The disassembler in step S1 is Ghidra, and the disassembly process includes at least identifying function boundaries, parsing function signatures, and disassembling instructions. The function boundary identification method is based on symbol information extraction, instruction pattern matching, control flow analysis and heuristic methods to determine the start and end positions of functions in binary code, forming the basic unit of program execution logic. The function signature parsing method works as follows: when symbolic information is available, the function information is read directly; when symbolic information is lacking, the function information is inferred based on the calling convention and through data flow analysis. The disassembly instructions parse the binary code into low-level assembly instructions and convert them into hardware-independent general intermediate representation P-Code.
3. The advanced malware identification method based on static analysis and semantic generation as described in claim 2, characterized in that: In the graph structure data G of step S2 Node set The middle part is the basic block that divides continuously executed instructions without internal jumps by traversing the P-Code instruction sequence; edge set This establishes the control flow transfer relationships between basic blocks based on jump, call, and return instructions; Node feature set The specific method for obtaining the features of all nodes is as follows: P-Code instructions are divided into six categories: data operation, memory access, transformation operation, special operation, comparison operation, and control flow operation. A six-dimensional counter vector is initialized, corresponding to the above six categories respectively. All P-Code instructions within the basic block are traversed, and the corresponding dimension in the counter vector is incremented according to the category to which the opcode belongs. The counter vector corresponding to each basic block is the feature of that node. The graph structure data ,in For the set of basic block nodes, Let be the set of edges. This is the node feature matrix.
4. The advanced malware identification method based on static analysis and semantic generation as described in claim 1, characterized in that: In step S3, a graph convolutional network is used to encode the graph structure. The feature information of nodes and their neighbors is aggregated through multi-layer convolutional operations, and the node representation is updated layer by layer to learn the node embedding vector. In the layer-by-layer update node, the first The formula for updating the node features of a layer is as follows: ; in, To add the adjacency matrix after adding self-loops, For the image The adjacency matrix, Let n be the identity matrix. It is by The calculated degree matrix contains elements on its diagonal. Represents a node The degree, , For matrix The element in the i-th row and j-th column, For the first The node feature matrix of the layer, , For the first Layer-trainable weight matrix, It is the ReLU activation function; go through After the layer graph convolution operation, the final node embedding matrix is obtained as follows: Global graph embedding vectors are generated using the max-pooling aggregation function. .
5. The advanced malware identification method based on static analysis and semantic generation as described in claim 1, characterized in that: In step S4, the memory-enhanced Long Short-Term Memory Network uses a node attention module to embed nodes into a vector sequence. This is converted into the candidate cell state at each step of the decoder, the node attention weights, and the candidate cell state at time t. The calculation method is as follows: ; ; ; in, This represents the hidden state of the decoder at time t-1. For learnable parameters, For the first The embedding vector of each node, the global graph embedding vector As the initial hidden state of the Long Short-Term Memory (LSTM) network for decoders The MALSTM unit at time Cellular state The updated formula is as follows: ; ; ; ; in, For the Gate of Oblivion For input gate, For output gate, The input at time t, The ReLU activation function is used. For learnable parameters, the output gate and cell state Calculate the output at the current time. and hidden state This generates a sequence of function names step by step.
6. The advanced malware identification method based on static analysis and semantic generation as described in claim 1, characterized in that: Step S5 specifically includes the following steps: S51: Divide the sequence of function names generated in step S4 into a sequence of tokens according to a predetermined naming convention; S52: Build a predefined expert knowledge base containing a set of keywords related to malicious behavior. The keyword categories include, but are not limited to, code execution, process injection, file tampering, network communication, privilege escalation, anti-identification, keylogging, driver loading, and sandbox identification; S53: Match the word token sequence from step S41 with the keywords in the expert knowledge base from step S52. If any word token exists in the sequence... satisfy If so, it is determined that the function corresponding to the sequence of function names has malicious intent; S54: Input the sequence of function names from step S51 into the large language model. Prompt it to generate explanatory text about the function's functionality and judge malicious intent through preset prompt words. For functions that the large language model determines have potential security risks or ambiguous attack intent, mark them as having malicious intent.