A method, system and storage medium for building a malicious code detection model
By extracting the metadata of APK files and building a machine learning model, combined with static and dynamic analysis technology, we solve the problem of low interpretability of existing malicious code detection models, improve the accuracy and efficiency of malicious code detection, and enhance the model's Interpretability.
Patent Information
- Application Number
- CN202310923908.9
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- Filing Date
- 2023-07-26
- Publication Date
- 2024-09-13
- Estimated Expiration
- 2043-07-26
AI Technical Summary
The model interpretability of existing malicious code detection methods is low, making it difficult to understand the role of each network layer and the feature extraction process, resulting in detection accuracy and efficiency problems.
By extracting metadata of APK files, including permission requests, component information, code structure and API call information, a malicious code detection model based on machine learning is built, and visualization tools are used to reveal the decision-making process and feature relationships of the model, improving the interpretability of the model. performance and detection accuracy.
It enhances the accuracy and robustness of the malicious code detection model, improves the interpretability of the model, combines static and dynamic analysis technology, saves time and resources, and improves detection efficiency and accuracy.
Smart Images

Figure CN117009967B
Abstract
Description
Technical Field
[0001] The present invention relates to the field of network security technology, and in particular to a malicious code detection model construction method, system and storage medium. Background Art
[0002] Malicious APK (Android Application Package) refers to malicious applications running on the Android platform, usually APK files that contain malicious code, have malicious behaviors, or pose a threat to user privacy and security. Due to the openness and popularity of the Android platform, the number and types of malicious APKs are increasing. Currently, the known and common types of malicious APKs include: privacy infringement, financial fraud, advertising abuse, remote control, denial of service attacks, and malicious code injection, etc. Moreover, as time goes by, the types of malicious APKs are still increasing, and the threats to user privacy and security are also increasing. In order to cope with this situation, malicious APK detection technology has emerged. However, due to the increasing types of malicious APKs, the difficulty of detection is also becoming increasingly greater.
[0003] Traditional malicious APK detection technologies are commonly static analysis and dynamic analysis. Static analysis refers to the method of identifying potential malicious behaviors and determining whether an APK is malicious by analyzing the structure and content of the APK file in order to check the compliance and legality of the application in terms of permission requests, API calls, file operations, etc.; dynamic analysis refers to the method of executing the APK file in a controlled environment and monitoring its behavior to determine whether the APK is malicious. These two detection technologies have their own advantages and disadvantages. The advantages of static analysis are: no actual code execution is required, and less resources are occupied. The disadvantages are: it may be affected by code obfuscation and anti-analysis technology, resulting in blurred features and difficult to detect, that is, easy to miss detection; the advantages of dynamic analysis are: it can capture the behavior of the APK at runtime to obtain higher detection accuracy, and the disadvantages are: it requires a lot of computing resources and time, especially when processing a large number of APK files.
[0004] The invention patent application with application number 2021107102773 discloses a malicious code detection method based on a multi-scale convolutional neural network, such as Figure 1 As shown, the steps include:
[0005] Step 1: Preprocess the malicious code data;
[0006] Step 2: Design and build a multi-scale convolutional neural network model: The model includes convolutional layers and fully connected layers; the first convolutional layer is used as the input layer, and its output dimension is 16, the convolution kernel length is 4, and the activation function is the ReLU function; the second layer is the BN layer, which performs standard normalization on the upper layer output; the third layer is a maximum pooling layer; followed by two convolutional layers, in which the second convolutional layer is connected to a BN layer and a maximum pooling layer; after the first pooling layer, a branch network is added, including a reconstruction layer and two fully connected layers, with dimensions of 512 and 64 respectively; after the second pooling layer, a branch network is also added, including a reconstruction layer and two fully connected layers, with dimensions changed to 256 and 64; after the third convolutional layer, a Flatten layer and a Dropout layer are connected, and the probability of random discarding weights of the Dropout layer is set to 0.5; finally, the fully connected layer is used as the output layer, the output category is 1, and the activation function is 'sigmoid';
[0007] Step 3: Build a traditional convolutional neural network model;
[0008] Step 4: Configure the model's optimizer, loss function, and number of iterations;
[0009] Step 5: Train the model using the training data set;
[0010] Step 6: Use the trained model to predict the data in the test set and record the prediction results of each model.
[0011] The malicious code detection method disclosed in 2021107102773 aims to extract data features of different scales to improve the accuracy of malicious code detection; at the same time, it extracts deeper features through sub-networks to improve the efficiency of training and testing. However, it is precisely because it adopts a deep network structure and input features of multiple scales that the depth and complexity of the network increase the mapping relationship within the model, making it difficult to accurately understand the role of each network layer and the feature extraction process, which leads to low interpretability of the model.
[0012] It can be seen that the existing technology still needs to be improved and developed. Summary of the invention
[0013] In view of the above-mentioned deficiencies in the prior art, the object of the present invention is to provide a method, system and storage medium for constructing a malicious code detection model, aiming to solve the problem of low interpretability of the model constructed by the existing malicious code detection method.
[0014] The technical solution of the present invention is as follows:
[0015] A method for building a malicious code detection model, comprising:
[0016] Collecting APK files as APK samples, wherein the APK samples include known malicious samples and normal samples;
[0017] Parse APK files one by one and extract APK file metadata to obtain APK's permission requests, component information, code structure, resource files, and API call information;
[0018] Preprocess the extracted metadata to generate a data set;
[0019] Building a malicious code detection model based on machine learning, and using the training set to train the malicious code detection model, and optimizing the parameters and weights of the malicious code detection model through iteration;
[0020] Use the test set to evaluate the trained malicious code detection model, calculate the accuracy, recall and precision of the malicious code detection model, and determine whether the calculation result reaches the preset threshold. If so, use the trained malicious code detection model as the final malicious code detection model. If not, continue model training until the calculation result reaches the preset threshold.
[0021] Through visualization tools and techniques, the model's decision-making process, the relationship between features, and malicious code detection rules are presented.
[0022] The effect of the above scheme is that metadata can provide important clues about the structure and behavior of APK files, and has strong distinguishability and correlation. Using it as part of the data set can improve the detection ability and accuracy of malicious code detection models for malicious code. Therefore, the present invention extracts metadata from APK files and uses it as original data to generate training sets and test sets to train and test models, thereby improving the effect and accuracy of malicious code detection; at the same time, since metadata provides important information about the structure and behavior of APK files that can help analysts understand the decision-making basis of the model in the process of malicious code detection, the present invention extracts and analyzes metadata in conjunction with visualization tools and technologies to reveal the model's focus and characteristics on malicious behavior, thereby enhancing the interpretability of the model.
[0023] In a further preferred solution, the step of parsing APK files one by one and extracting APK file metadata to obtain APK permission requests, component information, code structure, resource files and API call information includes:
[0024] Read the collected APK files one by one;
[0025] Extract the list of permissions requested by the application during installation, identify the application's active components, service components, broadcast receivers, and content providers, and parse the DEX file in the APK file to understand the application's code structure and class hierarchy;
[0026] Extract resource files from APK files and identify API calls used in APK through static analysis and decompilation techniques to understand the behavior of the application.
[0027] The effect of the above scheme is that: by extracting the permission request information of the APK file, sensitive permissions that may be abused by malicious code can be identified, such as data access and location tracking without user consent, thereby helping the model to identify potential malicious behaviors; the extracted application component information can reveal component vulnerabilities that malicious code may exploit, helping the model to analyze potential ways of malicious behaviors; on this basis, by parsing the code structure in the APK file, the class hierarchy of the application can be deeply understood, including call relationships, code logic, etc., and such information is crucial for detecting the characteristics and patterns of malicious code; in addition, by extracting the resource files in the APK file, combining static analysis and decompilation technology to identify the API calls used in the APK, the behavior of the application can be analyzed, including network communication, file operations, etc., thereby helping the model to identify potential malicious behavior characteristics; the metadata extracted by the present invention through the above steps not only enriches the data set, but more importantly, provides key features and behavior information for the model, and enhances the accuracy and robustness of the malicious code detection model; at the same time, these metadata can also help analysts understand the decision-making basis of the model in the malicious code detection process, and improve the interpretability of the model.
[0028] In addition, the present invention integrates static analysis technology and dynamic analysis technology, which can provide a more comprehensive, accurate and explainable malicious code detection effect compared to the traditional dynamic and static analysis separation technology, while saving time and resources and improving the efficiency and accuracy of detection.
[0029] In a further preferred embodiment, the step of preprocessing the extracted metadata to generate a data set specifically includes:
[0030] Select malicious code distinguishing features from the extracted metadata according to their ability to distinguish malicious code, and remove redundant and irrelevant features;
[0031] A feature scaling operation is performed on the selected malicious code distinguishing features so that all the selected malicious code distinguishing features have the same scale.
[0032] The effect of the above scheme is that the selection of malicious code distinguishing features and the removal of redundant and irrelevant features is to ensure that the data set only contains features that are meaningful for malicious code detection, reducing noise and unnecessary information, thereby improving the accuracy and generalization ability of the model; and the feature scaling operation is to avoid the weight imbalance problem caused by different scales between different features, ensuring that the model can treat different features more balanced, and improving the stability and reliability of the model.
[0033] In a further preferred embodiment, the malicious code detection model based on machine learning is built, and the training set is used to train the malicious code detection model, and the parameters and weights of the malicious code detection model are optimized through iteration; and the trained malicious code detection model is evaluated using the test set, and the accuracy, recall rate and precision rate of the malicious code detection model are calculated, and it is determined whether the calculation result reaches a preset threshold. If so, the trained malicious code detection model is used as the final malicious code detection model, and if not, the model training is continued until the calculation result reaches the preset threshold. The steps specifically include:
[0034] The data set is divided into k subsets, and the cross-validation method is used to select k-1 subsets of the k subsets as training sets, and the remaining subset as the test set;
[0035] Train each training set to obtain k trained SVM models;
[0036] Calculate the accuracy, recall and precision of k trained SVM models on the corresponding test set respectively, and determine whether the calculation results reach the preset threshold in turn; if the calculation result of only one SVM model reaches the preset threshold, then use this SVM model as the final malicious code detection model; if the calculation results of multiple trained SVM models all reach the preset threshold, calculate the F1 scores of these SVM models, and select the SVM model with the highest F1 score as the final malicious code detection model; if the calculation result of no SVM model reaches the preset threshold, continue model training and optimization until at least one model reaches the preset threshold or reaches the preset number of training rounds.
[0037] The effect of the above scheme is that: the present invention divides the training set multiple times and conducts multiple training by adopting a cross-validation method to effectively optimize the parameters and weights of the malicious code detection model based on machine learning; by training and evaluating the model multiple times, multiple groups of performance indicators such as accuracy, recall rate and precision can be obtained, and then the final malicious code detection model can be selected according to the F1 score, thereby improving the performance of the model on different test sets, enhancing the stability and generalization ability of the model, ensuring the performance and reliability of the model, and thus achieving more reliable, accurate and efficient malicious APK batch analysis and detection.
[0038] In a further preferred embodiment, the calculation formula of the accuracy rate is: accuracy rate = (number of true positive samples + number of true negative samples) / total number of samples, the calculation formula of the recall rate is: recall rate = number of true positive samples / (number of true positive samples + number of false negative samples), the calculation formula of the accuracy rate is: precision rate = number of true positive samples / (number of true positive samples + number of false positive samples), and the calculation formula of the F1 score is: F1 score = (2*precision rate*recall rate) / (precision rate + recall rate).
[0039] The effect of the above scheme is: it can be seen from the above formula that the accuracy reflects the proportion of correct predictions of the model among all samples, the recall rate measures the model's ability to correctly detect malicious samples, and the precision rate indicates the proportion of truly malicious samples among all samples predicted by the model as malicious. The F1 score that comprehensively considers the precision rate and the recall rate can more comprehensively evaluate the performance of the model; by using these indicators, the present invention can evaluate SVM models after different training, and select the model with the highest F1 score as the final malicious code detection model, ensuring that the model has high performance and reliability in malicious code detection, so as to help users more accurately identify malicious APKs, and effectively improve the accuracy and recall rate of malicious code detection, thereby improving security and the ability to protect user devices from malicious attacks.
[0040] In a further preferred embodiment, if the calculation result of no SVM model reaches the preset threshold, the model training and optimization are continued until at least one model reaches the preset threshold or reaches the preset number of training rounds. The processing method comprises the steps of:
[0041] Set initial ranges for the regularization parameter C and the kernel function parameters;
[0042] A grid search method is used to perform discretized parameter search within the set initial range, and multiple sets of candidate parameter combinations are selected;
[0043] The cross-validation method was used to successively combine multiple sets of candidate parameters as the initial parameters of the SVM model, and the training, accuracy, recall and precision of each SVM model were calculated;
[0044] Determine whether the calculation results of the retrained multiple SVM models reach the preset threshold. If only the calculation result of one SVM model reaches the preset threshold, the SVM model is used as the final malicious code detection model. If the calculation results of multiple trained SVM models all reach the preset threshold, the F1 scores of the multiple trained SVM models are calculated, and the SVM model with the highest F1 score is used as the final malicious code detection model. If the calculation result of no SVM model reaches the preset threshold, continue model training and optimization until at least one model reaches the preset threshold or the preset number of training rounds is reached.
[0045] The effect of the above scheme is that: by setting the regularization parameter C of the SVM model and the initial range of the parameters of the kernel function, and using the grid search method for discretized parameter search, the present invention can comprehensively search for possible parameter combinations in the parameter space, find potential optimal parameter settings, optimize the performance of the model, and improve the accuracy and reliability of malicious code detection; at the same time, by adopting the cross-validation method, the training set and the validation set are divided multiple times during the training process, which can make full use of the limited data set to evaluate the performance of the model, reduce the overfitting or underfitting problems caused by uneven data distribution, and effectively improve the generalization ability of the malicious code detection model.
[0046] In a further preferred embodiment, if the calculation result of the SVM model still does not reach the preset threshold, the following steps are performed:
[0047] Construct a logistic regression model and train it using the same training method as the SVM model, and obtain an initial logistic regression model, a quadratic logistic regression model, ..., and a k-fold logistic regression model in turn, and calculate the accuracy, recall, and precision of each logistic regression model after training;
[0048] Using the weight strategy, different weights are assigned to each model according to its performance in cross-validation, and k trained SVM models and k trained logistic regression models are combined to generate an integrated model, which is used as the final malicious code detection model.
[0049] The effect of the above scheme is that when constructing a malicious code detection model, if the initial support vector machine (SVM) model fails to reach the preset threshold, a logistic regression model will be introduced and trained using the same training method. By constructing multiple logistic regression models and calculating their accuracy, recall and precision, different weights are assigned according to the performance of each model in the cross-validation using a weight strategy; finally, the k SVM models and k logistic regression models obtained by training are combined into an integrated model. The goal of this integrated model is to comprehensively consider the opinions of multiple base models, and obtain more robust and accurate prediction results through voting or weighted averaging, thereby greatly improving the performance and robustness of the malicious code detection model.
[0050] A system for implementing a malicious code detection model construction method, comprising a memory and a processor, wherein the memory is used to store a malicious code detection model construction program, and the processor is used to run the malicious code detection model construction program to implement the malicious code detection model construction method as described above. Since the system has all the technical features of the malicious code detection model construction method as described above, it also has all the technical effects of the malicious code detection model construction method as described above, and no further description is given.
[0051] A storage medium having a computer program stored thereon, wherein when the computer program is executed by a processor, the steps of the malicious code detection model construction method described above are implemented. The storage medium includes all the technical features of the malicious code detection model construction method described above, and therefore also has all the technical effects of the malicious code detection model construction method described above, which will not be repeated here.
[0052] Compared with the prior art, the malicious code detection model construction method provided by the present invention improves the effect and accuracy of malicious code detection by extracting metadata from APK files and using them as original data to generate training sets and test sets to train and test the model. At the same time, since the metadata provides important information about the structure and behavior of APK files that can help analysts understand the decision-making basis of the model in the malicious code detection process, the present invention also reveals the model's focus and characteristics on malicious behavior by extracting and analyzing metadata in conjunction with visualization tools and technologies, thereby enhancing the interpretability of the model. BRIEF DESCRIPTION OF THE DRAWINGS
[0053] Figure 1 It is a flowchart of a method for constructing a malicious code detection model provided by a preferred embodiment of the present invention. DETAILED DESCRIPTION
[0054] The present invention provides a malicious code detection model construction method, system and storage medium. In order to make the purpose, technical solution and effect of the present invention clearer and more specific, the present invention is further described in detail with reference to the accompanying drawings and examples. It should be understood that the specific embodiments described herein are only used to explain the present invention and are not used to limit the present invention.
[0055] The present invention provides a method for constructing a malicious code detection model. Figure 1 As shown, it includes:
[0056] S100. Collect APK files as APK samples, where the APK samples include known malicious samples and normal samples.
[0057] The APK sample is the installation package file of the Android application, which contains all the resources and codes of the application. In order to build a malicious code detection model, the present invention collects two types of samples: known malicious samples and normal samples, as follows:
[0058] Known malicious samples: Malicious samples usually come from known malware libraries, malicious websites, or malicious application analysis reports. These samples are identified as containing malicious code and can be used as training sets and test sets to train and evaluate malicious code detection models.
[0059] Normal samples: Normal samples refer to legitimate applications without malicious behaviors. They can be obtained from official app stores, legitimate developer channels, or other trusted sources. Normal samples are used as a comparison group to compare with malicious samples to help the model identify malicious behaviors.
[0060] It should be noted that when collecting samples, the diversity and representativeness of the samples can be ensured to cover different types of applications to ensure that the constructed malicious code detection model has good generalization ability; after the samples are collected, the samples can be marked and classified to separate malicious samples from normal samples, and preprocessed (supplement missing values, etc.) to prepare for subsequent feature extraction and model training; S100 is an important foundation of the present invention, and the quality and quantity of the samples will directly affect the performance and accuracy of the model.
[0061] S200, parsing APK files one by one, extracting APK file metadata to obtain APK's permission request, component information, code structure, resource files, and API call information.
[0062] Metadata: refers to data that describes data. It describes the attributes, characteristics, and relationships of the data, but does not contain specific data content. In the APK file, metadata includes some basic information of the application, such as permission requests, component information, code structure, resource files, and API call information.
[0063] Permission request: In Android applications, permission is a security mechanism used to limit the application's access to system resources and user data. Permission request refers to the access rights that the application requests from the user when it is installed, such as accessing the network, reading storage, and obtaining device information.
[0064] Component information: Components are the basic building blocks in Android applications, such as Activity, Service, BroadcastReceiver, or ContentProvider. Component information describes the properties and configuration information of each component contained in the application.
[0065] Code structure: refers to the organization of code in the APK file, including Java code, XML files, resource files and other organizational structures, which is used to understand the logic and functions of the application.
[0066] Resource files: include images, layouts, strings and other resources used by the application, which play an important role in the appearance and user experience of the application.
[0067] API call information: API calls are the way applications interact with the Android system and other applications. This information describes the various system APIs and third-party APIs called by the APP during runtime.
[0068] The operations in S200 are critical to building a malicious code detection model: by parsing the structure of the APK file and extracting metadata, key information about the application's behavior can be obtained, and this information will be used as features to train the malicious code detection model. For example, malicious applications usually request a lot of permissions and may contain specific API call patterns in the code. By extracting these features, the model can be trained to identify malicious code and distinguish it from normal applications. Therefore, the role of S200 is to provide key metadata information for subsequent model training and construction.
[0069] It should be noted that metadata plays a role in feature extraction: by parsing the APK file and extracting the metadata therein, important information about the behavior of the application can be obtained, and this information will be used as features and input into the machine learning model for training; malicious code and normal code usually show different metadata features, so the malicious code detection model can identify potential malicious applications by analyzing metadata. When constructing a malicious code detection model, the relationship between data and metadata is as follows: first, the present invention extracts metadata from the APK file, and these metadata are information describing the structure and behavior of the application; then, by extracting and preprocessing the data of the APK file, the data is converted into a format that can be processed by the machine learning model. For example, binary data can be feature extracted to obtain numerical feature vectors. These feature vectors and the features extracted from the metadata are used as inputs of the model together for training the malicious code detection model. The prior art usually analyzes data and data streams. It can be seen that the use of metadata makes the malicious code detection model constructed by the present invention substantially different from the prior art, and also brings more significant progress to the malicious code detection model constructed by the present invention.
[0070] In specific implementation, the S200 specifically includes the following steps:
[0071] Read the collected APK files one by one (traverse the collected APK files and read them one by one);
[0072] Extract the list of permissions requested by the application when it is installed (by parsing the manifest file of the APK file, namely AndroidManifest.xml), identify the application's activity components (Activity), service components (Service), broadcast receivers (Broadcast Receiver) and content providers (Content Provider), and parse the DEX (Dalvik Executable) file in the APK file to understand the application's code structure and class hierarchy;
[0073] Extract resource files from APK files and identify API calls used in APK through static analysis and decompilation techniques to understand the behavior of the application.
[0074] In order to make it easier to understand the specific implementation process of the present invention, an example is given here (only for illustration and not for technical solution limitation):
[0075] Assume there is a collected APK file named "malicious_app.apk";
[0076] If the malicious code detection model construction method of the present invention is used, the following operations will be performed: first, the APK file is read, and then its manifest file is parsed to extract the permission list requested by the application, such as "INTERNET" and "ACCESS_FINE_LOCATION"; then, the DEX file of the APK file is parsed to identify the components of the application, such as the activity component "MainActivity" and the service component "MyService"; at the same time, the resource files in the APK are also extracted, such as the image "icon.png" and the sound "alert.wav"; finally, through static analysis and decompilation technology, the API calls in the APK, such as "sendBroadcast()" and "readContacts()", are identified, and these extracted features will be used to build a malicious code detection model.
[0077] If the traditional method is used, the following operations will be performed: first, data features are extracted from the APK file, such as binary instruction frequency and number of function calls; then, these data features are used as training samples to train the model through a machine learning algorithm (such as SVM). During the training process, only these basic data features are focused on without in-depth understanding of the structure and behavior of the application.
[0078] In contrast, in step S200, in addition to extracting data features, the present invention also obtains more metadata information: it reads the manifest file of the APK file, learns that the application has requested the "INTERNET" and "ACCESS_FINE_LOCATION" permissions, and then parses the DEX file of the APK file to identify the activity component "MainActivity" and the service component "MyService"; at the same time, it extracts the resource files in the APK, the image "icon.png" and the sound "alert.wav"; finally, through static analysis and decompilation technology, it also finds the API calls "sendBroadcast()" and "readContacts()" in the APK.
[0079] It can be seen that when only using data to build a malicious code detection model, only basic data features are considered, while the structure and behavior information of the application are ignored; however, this is not the case in step S200. S200 obtains more metadata information, thereby building a more comprehensive and accurate malicious code detection model. Such a model has higher effectiveness and reliability in distinguishing malicious code from normal code.
[0080] S300: pre-process the extracted metadata to generate a data set.
[0081] In specific implementation, the S300 specifically includes the following steps:
[0082] Select malicious code distinguishing features from the extracted metadata according to their ability to distinguish malicious code, and remove redundant and irrelevant features;
[0083] A feature scaling operation is performed on the selected malicious code distinguishing features so that all the selected malicious code distinguishing features have the same scale.
[0084] Assuming that there are 5 malicious samples (marked as 1) and 5 normal samples (marked as 0), and for each sample, the metadata mentioned in S200 has been extracted from the APK file, the implementation process of S300 is as follows:
[0085] From the extracted metadata, select malicious code distinguishing features, such as whether the permission request contains sensitive permissions (such as "SEND_SMS", "READ_CONTACTS", etc.), the number of active components, the type of resource files (images, sounds, etc.), and whether it contains specific API calls (such as "sendBroadcast()", "writeExternalStorage()", etc.);
[0086] Remove redundant and irrelevant features. For example, if the number of active components is highly correlated with the number of service components, one of the features can be removed.
[0087] Perform feature scaling operations on the selected malicious code distinguishing features to ensure that they have the same scale, for example, scaling the number of sensitive permissions in the permission request to a range of 0-1.
[0088] S400, building a malicious code detection model based on machine learning, and using the training set to train the malicious code detection model, optimizing the parameters and weights of the malicious code detection model through iteration; and using the test set to evaluate the trained malicious code detection model, calculating the accuracy, recall and precision of the malicious code detection model, and judging whether the calculation result reaches a preset threshold, if so, using the trained malicious code detection model as the final malicious code detection model, if not, continuing model training until the calculation result reaches the preset threshold.
[0089] In specific implementation, the S400 specifically includes the following steps:
[0090] The data set is divided into k subsets, and the cross-validation method is used to take k-1 subsets of the k subsets as training sets, and the remaining subset as the test set;
[0091] Train each training set to obtain k trained SVM models;
[0092] Calculate the accuracy, recall and precision of k trained SVM models on the corresponding test set respectively, and determine whether the calculation results reach the preset threshold in turn; if the calculation result of only one SVM model reaches the preset threshold, then use this SVM model as the final malicious code detection model; if the calculation results of multiple trained SVM models all reach the preset threshold, calculate the F1 scores of these SVM models, and select the SVM model with the highest F1 score as the final malicious code detection model; if the calculation result of no SVM model reaches the preset threshold, continue model training and optimization until at least one model reaches the preset threshold or reaches the preset number of training rounds.
[0093] Specifically, the calculation formula for the accuracy rate is: accuracy rate = (number of true positive samples + number of true negative samples) / total number of samples, the calculation formula for the recall rate is: recall rate = number of true positive samples / (number of true positive samples + number of false negative samples), the calculation formula for the accuracy rate is: precision rate = number of true positive samples / (number of true positive samples + number of false positive samples), and the calculation formula for the F1 score is: F1 score = (2*precision rate*recall rate) / (precision rate + recall rate).
[0094] True Positive (TP): the number of malicious samples correctly identified as malicious samples; False Positive (FP): the number of normal samples incorrectly identified as malicious samples; True Negative (TN): the number of normal samples correctly identified as normal samples; False Negative (FN): the number of malicious samples incorrectly identified as normal samples.
[0095] Assume that there is a data set containing 5 malicious samples and 5 normal samples. The specific implementation process of the above steps is as follows:
[0096] Divide the data set into 5 subsets, each containing 2 samples;
[0097] First iteration:
[0098] Subset 1 is used as the test set, and subsets 2 to 5 are used as the training sets, and SVM model 1 is obtained;
[0099] Subset 2 is used as the test set, and subsets 1, 3 to 5 are used as the training sets to obtain SVM model 2;
[0100] Subset 3 is used as the test set, and subsets 1, 2, 4-5 are used as the training sets, and SVM model 3 is obtained;
[0101] Subset 4 was used as the test set, and subsets 1 to 3 and 5 were used as the training sets, and SVM model 4 was obtained;
[0102] Subset 5 is used as the test set, and subsets 1 to 4 are used as the training sets, and SVM model 5 is obtained.
[0103] For each model, the present invention uses the test set for evaluation and calculates the accuracy, recall and precision. It is assumed that the calculation results are as follows:
[0104] SVM model 1: accuracy = 0.8, recall = 0.9, precision = 0.75;
[0105] SVM model 2: accuracy = 0.85, recall = 0.75, precision = 0.9;
[0106] SVM model 3: accuracy = 0.75, recall = 0.8, precision = 0.7;
[0107] SVM model 4: accuracy = 0.9, recall = 0.85, precision = 0.95;
[0108] SVM model 5: accuracy = 0.8, recall = 0.7, precision = 0.8.
[0109] Assuming that the calculation result of SVM model 4 reaches the preset threshold, SVM model 4 is used as the final malicious code detection model, which has the highest F1 score of (2*0.95*0.85) / (0.95+0.85)=0.9.
[0110] This process will be iterated and optimized continuously until the preset threshold is reached. If no model reaches the preset threshold, model training and optimization will continue, which will be described in detail below.
[0111] S500, through visualization tools and techniques, presents the model's decision-making process, the relationship between features, and malicious code detection rules.
[0112] In the specific implementation, there are many visualization tools and techniques available, such as SHAP (SHapley Additive exPlanations). It should be noted that the tools listed here and the specific implementation process described below are only for explaining the present invention and should not be regarded as limiting the scope of protection of the present invention. SHAP is an open source library for explaining the prediction of machine learning models. It evaluates the contribution of each feature to the model output based on the Shapley value method, thereby revealing the relationship between the model's decision-making process and features; the following are the specific implementation steps for using the SHAP visualization tool to implement the explanation of the malicious code detection model:
[0113] First, install the SHAP library using the pip command (pip install shap);
[0114] Then, the dataset is divided into training set and test set, and a machine learning algorithm (such as SVM) is used to train a malicious code detection model;
[0115] Then, use the SHAP library to calculate the SHAP value of each sample. These values represent the contribution of each feature to the model prediction. This can be achieved through SHAP's "KernelExplainer". The code is as follows:
[0116] import shap
[0117] # Initialize KernelExplainer
[0118] explainer=shap.KernelExplainer(model.predict,data_train)
[0119] #Calculate SHAP value
[0120] shap_values=explainer.shap_values(data_test)
[0121] Then, use the SHAP library’s visualization tools “summary_plot” and “force_plot” to present the model’s decision process and the relationship between features. The code can be:
[0122] # Draw a summary graph of feature importance
[0123] shap.summary_plot(shap_values,data_test)
[0124] #Draw the decision process of a single sample
[0125] shap.force_plot(explainer.expected_value,shap_values[0],data_test.iloc[0,:])
[0126] In this example, "summary_plot" will show the contribution of each feature to the model output, while "force_plot" will show the feature importance and decision-making process of a single sample; in this way, visualization tools and techniques can help analysts better understand the model's prediction results, discover the model's rules, and improve the trust and interpretability of the malicious code detection model.
[0127] The present invention combines metadata with visualization tools and techniques for the following reasons:
[0128] First, metadata contains relevant information about each feature in the model, such as weight, coefficient, and value range of the feature. Visualization tools can display this information in an intuitive way, helping analysts understand which features play a key role in the model's prediction, thereby identifying the most important features in the malicious code detection model.
[0129] Second, visualization tools can draw a graph of the relationship between features and outputs, showing how feature values affect the model's prediction results, helping analysts understand how the model makes decisions based on different feature values, and further revealing the model's decision-making process;
[0130] Third, through visualization tools, analysts can trace the decision path of a single sample in the model and see how the features contribute to the predicted output cumulatively, thereby understanding how the model classifies malicious code;
[0131] Fourth, by combining metadata and visualization tools, analysts can conduct in-depth analysis of the model's prediction results on the test set, find out which samples the model predicts inaccurately, and explore the causes of the errors, helping analysts to discover the limitations and room for improvement of the model, so that analysts can manually adjust or use automated tools to improve the robustness and accuracy of the model;
[0132] In general, the combination of metadata and visualization tools provides an intuitive and clear way to explain the malicious code detection model, helping analysts understand the internal mechanism and prediction process of the model, and enhancing the trust and interpretability of the model.
[0133] It can be understood that the present invention extracts metadata, generates a data set containing metadata features, trains a model with a training set containing metadata features, and uses visualization tools and techniques to present the model's decision-making process, the relationship between features, and malicious code detection rules, thereby greatly improving the reliability, robustness, accuracy, and interpretability of the generated malicious code detection model, making the generated malicious code detection model very different from the prior art.
[0134] In a further preferred embodiment, if the above content cannot obtain the expected SVM model (some manufacturers may not be able to obtain sufficient samples, resulting in the final trained SVM model not meeting expectations), optimization can be performed through the following steps:
[0135] Set initial ranges for the regularization parameter C and the kernel function parameters;
[0136] A grid search method is used to perform discretized parameter search within the set initial range, and multiple sets of candidate parameter combinations are selected;
[0137] The cross-validation method was used to successively combine multiple sets of candidate parameters as the initial parameters of the SVM model, and the training, accuracy, recall and precision of each SVM model were calculated;
[0138] Determine whether the calculation results of the retrained multiple SVM models reach the preset threshold. If only the calculation result of one SVM model reaches the preset threshold, the SVM model is used as the final malicious code detection model. If the calculation results of multiple trained SVM models all reach the preset threshold, the F1 scores of the multiple trained SVM models are calculated, and the SVM model with the highest F1 score is used as the final malicious code detection model. If the calculation result of no SVM model reaches the preset threshold, continue model training and optimization until at least one model reaches the preset threshold or the preset number of training rounds is reached.
[0139] Assume that the initial range is set as follows:
[0140] Initial range of regularization parameter C: [0.1, 1, 10, 100]
[0141] The initial range of kernel function parameters: ['linear', 'rbf', 'poly'];
[0142] Then, by enumerating all possible parameter combinations within the set range, for example:
[0143] C = 0.1, kernel = 'linear'
[0144] C = 0.1, kernel function = 'rbf'
[0145] C = 0.1, kernel = 'poly'
[0146] C = 1, kernel function = 'linear'
[0147] C = 1, kernel function = 'rbf'
[0148] C = 1, kernel function = 'poly'
[0149] C = 100, kernel function = 'poly'.
[0150] For each of the above parameter combinations, the cross-validation method is used to train the SVM model, and the accuracy, recall and precision are calculated on the test set. A 5-fold cross-validation method can be used, that is, the data set is divided into 5 subsets, 4 of which are used as training sets in turn, and the remaining subset is used as the test set, and 5 rounds of training and evaluation are performed. The specific calculation process and subsequent judgment are the same as above and will not be repeated here.
[0151] In a further preferred embodiment, if the above steps still fail to obtain a model that meets expectations and the number of samples cannot be supplemented, the following steps may be continued:
[0152] Construct a logistic regression model and train it using the same training method as the SVM model, and obtain an initial logistic regression model, a quadratic logistic regression model, ..., and a k-fold logistic regression model in turn, and calculate the accuracy, recall, and precision of each logistic regression model after training;
[0153] Using the weight strategy, different weights are assigned to each model according to its performance in cross-validation, and k trained SVM models and k trained logistic regression models are combined to generate an integrated model, which is used as the final malicious code detection model.
[0154] The training and evaluation process of the logistic regression model is not much different from that of the SVM model, so it will not be described again here. The generation of the integrated model can adopt a simple weighted average method, that is, the prediction results of each model are weighted averaged according to their corresponding weights to obtain the final integrated prediction results; the model with a higher weight has a greater impact on the final prediction results, and the model with a lower weight naturally has a relatively small impact on the final prediction results. Finally, the generated integrated model is used as the final malicious code detection model. Since the generated integrated model combines multiple trained SVM models and logistic regression models, and assigns different weights according to their performance in cross-validation, it comprehensively considers the advantages of each model and improves the overall performance of the model. Therefore, there is a great probability of obtaining a malicious code detection model that meets expectations, and the obtained malicious code detection model also has a high interpretability.
[0155] The present invention also provides a system for implementing a malicious code detection model construction method, which includes a memory and a processor, wherein the memory is used to store a malicious code detection model construction program, and the processor is used to run the malicious code detection model construction program to implement the malicious code detection model construction method as described above.
[0156] The present invention also provides a storage medium on which a computer program is stored, and when the computer program is executed by a processor, the steps of the malicious code detection model construction method described above are implemented. The storage medium includes all the technical features of the malicious code detection model construction method described above, and therefore also has all the technical effects of the malicious code detection model construction method described above, which will not be repeated here.
[0157] Those of ordinary skill in the art can understand that all or part of the processes in the above-mentioned embodiments can be implemented by instructing related hardware through a computer program, and the computer program can be stored in a non-volatile computer-readable storage medium. When the computer program is executed, it can include the processes of the embodiments of the above-mentioned methods. Among them, any reference to memory, storage, database or other media used in the embodiments provided by the present invention may include non-volatile and / or volatile memory. Non-volatile memory may include read-only memory (ROM), programmable ROM (PROM), electrically programmable ROM (EPROM), electrically erasable programmable ROM (EEPROM) or flash memory. Volatile memory may include random access memory (RAM) or external cache memory. By way of illustration and not limitation, RAM is available in a variety of forms, such as static RAM (SRAM), dynamic RAM (DRAM), synchronous DRAM (SDRAM), double data rate SDRAM (DDRSDRAM), enhanced SDRAM (ESDRAM), synchronous link (SyNchliNk) DRAM (SLDRAM), memory bus (Rambus) direct RAM (RDRAM), direct memory bus dynamic RAM (DRDRAM), and memory bus dynamic RAM (RDRAM), etc.
[0158] The algorithm or display provided herein is not inherently related to any particular computer, virtual system or other equipment. Various general purpose systems can also be used together with the teachings based on this. According to the above description, it is obvious to construct the structure required for this type of system. In addition, the embodiment of the present invention is not directed to any specific programming language yet. It should be understood that various programming languages can be utilized to realize the content of the present invention described herein, and the description made to specific languages above is for disclosing the best mode of the present invention.
[0159] In the description provided herein, a large number of specific details are described. However, it is understood that embodiments of the present invention can be practiced without these specific details. In some instances, well-known methods, structures and techniques are not shown in detail so as not to obscure the understanding of this description.
[0160] Similarly, it should be understood that in order to streamline the present invention and aid in understanding one or more of the various inventive aspects, in the above description of exemplary embodiments of the present invention, the various features of the embodiments of the present invention are sometimes grouped together into a single embodiment, figure, or description thereof. However, this disclosed method should not be interpreted as reflecting the following intention: that the claimed invention requires more features than the features explicitly recited in each claim. More specifically, as reflected in the claims below, inventive aspects lie in less than all the features of the individual embodiments disclosed above. Therefore, the claims that follow the specific embodiment are hereby expressly incorporated into the specific embodiment, with each claim itself serving as a separate embodiment of the present invention.
[0161] Those skilled in the art will appreciate that the modules in the devices in the embodiments may be adaptively changed and arranged in one or more devices different from the embodiments. The modules or units or components in the embodiments may be combined into one module or unit or component, and in addition they may be divided into a plurality of submodules or subunits or subcomponents. Except that at least some of such features and / or processes or units are mutually exclusive, all features disclosed in this specification (including the accompanying claims, abstracts and drawings) and all processes or units of any method or device disclosed in this manner may be combined in any combination. Unless otherwise expressly stated, each feature disclosed in this specification (including the accompanying claims, abstracts and drawings) may be replaced by an alternative feature providing the same, equivalent or similar purpose.
[0162] In addition, those skilled in the art will appreciate that, although some embodiments herein include certain features included in other embodiments but not other features, the combination of features of different embodiments is meant to be within the scope of the present invention and form different embodiments. For example, any one of the claimed embodiments may be used in any combination.
[0163] It should be noted that the above embodiments illustrate the present invention rather than limit it, and that those skilled in the art may devise alternative embodiments without departing from the scope of the appended claims. In the claims, any reference symbol between brackets shall not be construed as a limitation on the claims. The word "comprising" does not exclude the presence of elements or steps not listed in the claims. The word "one" or "an" preceding an element does not exclude the presence of a plurality of such elements. The present invention may be implemented by means of hardware comprising a number of different elements and by means of a suitably programmed computer. In a unit claim enumerating a number of devices, several of these devices may be embodied by the same hardware item. The use of the words first, second, and third, etc. does not indicate any order. These words may be interpreted as names. The steps in the above embodiments, unless otherwise specified, should not be understood as limitations on the order of execution.
Claims
1. A method for constructing a malicious code detection model, characterized in that: include: Collecting APK files as APK samples, wherein the APK samples include known malicious samples and normal samples; Parse APK files one by one and extract APK file metadata to obtain APK's permission request, component information, code structure, resource files, and API call information; Preprocess the extracted metadata to generate a data set; Dividing the data set into a training set and a test set, building a malicious code detection model based on machine learning, and using the training set to train the malicious code detection model, and optimizing the parameters and weights of the malicious code detection model through iteration; The trained malicious code detection model is evaluated using the test set, and the accuracy, recall and precision of the malicious code detection model are calculated to determine whether the calculation result reaches the preset threshold. If so, the trained malicious code detection model is used as the final malicious code detection model. If not, the model training is continued until the calculation result reaches the preset threshold. Through visualization tools and techniques, the decision-making process of the model, the relationship between features, and malicious code detection rules are presented; After extracting metadata from the APK file, the malicious code detection model construction method also performs feature extraction and preprocessing on the data of the APK file, converts the data into a feature vector in a predetermined format, and uses the feature vector together with the features extracted from the metadata as input of the model for training the malicious code detection model.
2. The method for constructing a malicious code detection model according to claim 1, characterized in that: The steps of parsing APK files one by one and extracting APK file metadata to obtain APK permission requests, component information, code structure, resource files and API call information include: Read the collected APK files one by one; Extract the list of permissions requested by the application during installation, identify the application's active components, service components, broadcast receivers, and content providers, and parse the DEX file in the APK file to understand the application's code structure and class hierarchy; Extract resource files from APK files and identify API calls used in APK through static analysis and decompilation techniques to understand the behavior of the application.
3. The method for constructing a malicious code detection model according to claim 2, characterized in that: The step of preprocessing the extracted metadata to generate a data set specifically includes: Select malicious code distinguishing features from the extracted metadata according to their ability to distinguish malicious code, and remove redundant and irrelevant features; A feature scaling operation is performed on the selected malicious code distinguishing features so that all the selected malicious code distinguishing features have the same scale.
4. The method for constructing a malicious code detection model according to claim 3, characterized in that: The steps of dividing the data set into a training set and a test set, building a malicious code detection model based on machine learning, using the training set to train the malicious code detection model, using the test set to evaluate the trained malicious code detection model, calculating the accuracy, recall and precision of the malicious code detection model, and judging whether the calculation result reaches a preset threshold, if so, using the trained malicious code detection model as the final malicious code detection model, and if not, continuing model training until the calculation result reaches the preset threshold specifically include: The data set is divided into k subsets, and the cross-validation method is used to select k-1 subsets of the k subsets as training sets, and the remaining subset as the test set; Train each training set to obtain k trained SVM models; Calculate the accuracy, recall and precision of k trained SVM models on the corresponding test set respectively, and determine whether the calculation results reach the preset threshold in turn; if the calculation result of only one SVM model reaches the preset threshold, then use this SVM model as the final malicious code detection model; if the calculation results of multiple trained SVM models all reach the preset threshold, calculate the F1 scores of these SVM models, and select the SVM model with the highest F1 score as the final malicious code detection model; if the calculation result of no SVM model reaches the preset threshold, continue model training and optimization until at least one model reaches the preset threshold or reaches the preset number of training rounds.
5. The method for constructing a malicious code detection model according to claim 4, characterized in that: The calculation formula of the accuracy rate is: accuracy rate = (number of true positive samples + number of true negative samples) / total number of samples, the calculation formula of the recall rate is: recall rate = number of true positive samples / (number of true positive samples + number of false negative samples), the calculation formula of the accuracy rate is: precision rate = number of true positive samples / (number of true positive samples + number of false positive samples), and the calculation formula of the F1 score is: F1 score = (2*precision rate*recall rate) / (precision rate + recall rate).
6. The method for constructing a malicious code detection model according to claim 4, characterized in that: If the calculation result of no SVM model reaches the preset threshold, the model training and optimization are continued until at least one model reaches the preset threshold or reaches the preset number of training rounds. The processing method includes the steps of: Set initial ranges for the regularization parameter C and the kernel function parameters; A grid search method is used to perform discretized parameter search within the set initial range, and multiple sets of candidate parameter combinations are selected; The cross-validation method was used to successively combine multiple sets of candidate parameters as the initial parameters of the SVM model, and the training, accuracy, recall and precision of each SVM model were calculated; Determine whether the calculation results of the retrained multiple SVM models reach the preset threshold. If only the calculation result of one SVM model reaches the preset threshold, the SVM model is used as the final malicious code detection model. If the calculation results of multiple trained SVM models all reach the preset threshold, the F1 scores of the multiple trained SVM models are calculated, and the SVM model with the highest F1 score is used as the final malicious code detection model. If the calculation result of no SVM model reaches the preset threshold, continue model training and optimization until at least one model reaches the preset threshold or the preset number of training rounds is reached.
7. The method for constructing a malicious code detection model according to claim 6, characterized in that: If there is still no calculation result of the SVM model that reaches the preset threshold, perform the following steps: Construct a logistic regression model and train it using the same training method as the SVM model, and obtain an initial logistic regression model, a quadratic logistic regression model, ..., and a k-fold logistic regression model in turn, and calculate the accuracy, recall, and precision of each logistic regression model after training; Using the weight strategy, different weights are assigned to each model according to its performance in cross-validation, and k trained SVM models and k trained logistic regression models are combined to generate an integrated model, which is used as the final malicious code detection model.
8. A system for implementing a method for building a malicious code detection model, characterized in that: It includes a memory and a processor, the memory is used to store a malicious code detection model construction program, and the processor is used to run the malicious code detection model construction program to implement the malicious code detection model construction method as described in any one of claims 1 to 7.
9. A computer-readable storage medium having a computer program stored thereon, characterized in that: When the computer program is executed by a processor, the steps of the malicious code detection model construction method according to any one of claims 1 to 7 are implemented.
