Source code vulnerability detection method and system based on Transform language model
Through the source code vulnerability detection method based on the Transformer language model, the CodeBERT model and RoBERTa word segmenter extract the deep semantic features of the source code are solved, and the problem of insufficient accuracy and recall in the existing technology is realized efficient source code vulnerability detection , improves the efficiency of software security testing.
Patent Information
- Application Number
- CN202410916122.9
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2024-07-09
- Publication Date
- 2024-11-01
AI Technical Summary
The existing software vulnerability detection model fails to fully consider the deep semantic characteristics of the source code, resulting in insufficient accuracy and recall, and the vulnerability classification process is cumbersome, affecting the efficiency of software security testing.
The source code vulnerability detection method based on the Transformer language model is adopted. By constructing a multi-classified CodeBERT model, the source code is pre-trained and fine-tuned using the RoBERTa word segmenter and the Transformer language model, deep semantic features are extracted, and the code differences between the new and old versions are analyzed through the diff file. Build a multi-label vulnerability data set to achieve efficient detection of source code vulnerabilities.
It significantly improves the accuracy of source code vulnerability mining and vulnerability classification, with an accuracy rate of 97%-99%, a recall rate of 94%-98%, and an average accuracy rate of 98%. It has good application prospects in the field of software security.
Smart Images

Figure CN118886016A_ABST
Abstract
Description
Technical Field
[0001] The present invention relates to the field of Internet security technology, and in particular to a source code vulnerability detection method and system based on a Transformer language model. Background Art
[0002] The rapid development of the Internet has profoundly changed people's production and lifestyle, bringing unprecedented convenience to individuals and society. At the same time, the number of software vulnerabilities and potential risks have also shown a significant upward trend. Traditional manual vulnerability detection methods are inefficient and can no longer meet the current urgent needs for software security. Source code vulnerability detection, as a strategy that can effectively respond to network attacks, has gradually occupied an important position in the field of network security research and has become the focus of scholars.
[0003] There are many tools for vulnerability mining, such as ScanDal, HybriDroid, and PREfix. Most of them are used to detect vulnerabilities in C or Java, and there are very few studies on Python vulnerability mining. There are mainly the following methods. Micheelsen proposed a Python vulnerability detection tool based on static taint analysis, PyT. Peng et al. proposed a Python source code vulnerability detection method based on code similarity. Wartschinski et al. proposed a method for vulnerability detection in Python source code based on a deep learning model of LSTm. Guo et al. innovatively proposed a method for vulnerability detection and classification in Python source code based on BiLSTM and OVO SVMs models. However, none of the above schemes fully considers the contextual semantic information of the vulnerability dataset, and the model does not extract deep semantic features from the source code. In addition, in vulnerability classification, the vulnerability type classifier is constructed by extracting relevant text features and combining the OVO SVMs algorithm, and finally the code snippet of the vulnerability type is given. The operation is cumbersome and inefficient, which affects the deployment and implementation in software security testing. Summary of the invention
[0004] To this end, the present invention provides a source code vulnerability detection method and system based on the Transformer language model, which solves the limitations of existing software vulnerability detection models and the fact that the deep semantic features of the source code are not fully considered, resulting in certain deficiencies in accuracy and recall, thereby improving the effect of software source code vulnerability mining.
[0005] According to the design scheme provided by the present invention, on the one hand, a source code vulnerability detection method based on a Transformer language model is provided, comprising:
[0006] Obtain code sample data and annotate category labels for vulnerability types in the code sample data to construct a vulnerability detection sample dataset;
[0007] Construct a multi-classification CodeBERT model, and use the vulnerability detection sample data set to train the multi-classification CodeBERT model, and use the trained multi-classification CodeBERT model as the vulnerability detection target model, wherein the multi-classification CodeBERT model is constructed based on the RoBERTa word segmenter and the Transformer language model;
[0008] The source code to be detected is input into the vulnerability detection target model, and the vulnerability detection target model is used to identify and output the vulnerability category in the source code to be detected.
[0009] As a source code vulnerability detection method based on the Transformer language model of the present invention, further, code sample data is obtained, and category labels are annotated for vulnerability types in the code sample data, including:
[0010] Obtain a first version of a code sample and a second version of a code sample, wherein the first version of the code sample is a current secure version of the code, and the second version of the code sample is a previous version of the code with a vulnerability;
[0011] Use the diff file to compare the code lines in the two versions of the code sample, and obtain the vulnerable code lines in the second version of the code sample and the safe code lines in the first version of the code based on the comparison results;
[0012] Vulnerability category labels are added to vulnerable code lines and secure code lines, and a vulnerability detection sample dataset is constructed based on the vulnerable code lines and secure code lines.
[0013] As the source code vulnerability detection method based on the Transformer language model of the present invention, further, constructing a vulnerability detection sample data set also includes:
[0014] Traversing the code sample with a focus window of a specified step size to divide the code sample into data blocks;
[0015] When labeling the vulnerability type in the code with a category label, if a data block overlaps with an adjacent code line corresponding to a vulnerability category label, the data block is labeled with the vulnerability category label corresponding to the adjacent code line.
[0016] As a source code vulnerability detection method based on the Transformer language model of the present invention, further, the RoBERTa tokenizer is used to extract the context semantics of the input code and generate a code token sequence, and the Transformer language model captures the dependency between each position in the code token sequence based on the self-attention mechanism and outputs feature embeddings, so as to classify the feature embeddings in the multi-classification CodeBERT model output and convert them into the vulnerability category probability space.
[0017] As a source code vulnerability detection method based on the Transformer language model of the present invention, further, the Transformer language model includes an encoder for converting an input into a context-aware encoded representation and a decoder for converting the encoded representation into feature embedding.
[0018] As a source code vulnerability detection method based on the Transformer language model of the present invention, further, a multi-classification CodeBERT model is trained using a vulnerability detection sample data set, including:
[0019] Pre-training the multi-classification CodeBERT model using a pre-training strategy, wherein the pre-training strategy is to pre-train the model using mixed data consisting of source code and natural language so that the model can understand source code syntax and semantics;
[0020] The pre-trained multi-classification CodeBERT model is fine-tuned using vulnerability detection sample data, and the fine-tuned multi-classification CodeBERT model is used as the vulnerability detection target model.
[0021] As a source code vulnerability detection method based on the Transformer language model of the present invention, further, a multi-classification CodeBERT model is pre-trained using a pre-training strategy, including:
[0022] Generate a natural language masking position marker sequence and a code masking position marker sequence respectively according to the source code context by using a natural language generator and a code generator, wherein both the natural language generator and the code generator are built based on the BERT language model;
[0023] Natural language masked position marker sequences and code masked position marker sequences are sampled to form mixed data of natural language and source code. The mixed data is used to train a natural language-code discriminator, and the trained natural language-code discriminator is used as the target model in fine-tuning of the multi-classification CodeBERT model, where the natural language-code discriminator is built based on the RoBERTa word segmenter.
[0024] On the other hand, the present invention also provides a source code vulnerability detection system based on the Transformer language model, comprising: a sample acquisition module, a model training module and a vulnerability detection module, wherein:
[0025] The sample acquisition module is used to obtain code sample data and annotate the vulnerability types in the code sample data with category labels to construct a vulnerability detection sample data set;
[0026] A model training module is used to build a multi-classification CodeBERT model, and train the multi-classification CodeBERT model using a vulnerability detection sample data set, and use the trained multi-classification CodeBERT model as a vulnerability detection target model, wherein the multi-classification CodeBERT model is built based on the RoBERTa word segmenter and the Transformer language model;
[0027] The vulnerability detection module is used to input the source code to be detected into the vulnerability detection target model, and use the vulnerability detection target model to identify and output the vulnerability category in the source code to be detected.
[0028] Beneficial effects of the present invention:
[0029] The present invention creates a multi-label vulnerability dataset by analyzing the differences between new and old software versions, uses RoBERTaTokenizer to obtain high-quality expressions of code keywords, builds a multi-classification CodeBERT model, and performs pre-training and fine-tuning, so that the model can fully consider the deep semantics, structure, and grammatical features of the source code, and uses the fine-tuned model to achieve target source code vulnerability mining and detection. Compared with the traditional detection method based on the LSTM model, the effect of source code vulnerability mining and vulnerability classification in this case is significantly improved, with an accuracy rate of 97%-99%, a recall rate of 94%-98%, and an average accuracy rate of 98%, which has a good application prospect in the field of software security. BRIEF DESCRIPTION OF THE DRAWINGS
[0030] Figure 1 The following is a schematic diagram of the source code vulnerability detection process based on the Transformer language model in the embodiment;
[0031] Figure 2 This is a schematic diagram of the model training framework in the embodiment;
[0032] Figure 3 The diff file comparison fragment of the source code in the embodiment is shown;
[0033] Figure 4 This is a schematic diagram of labeling code blocks in the embodiment;
[0034] Figure 5 This is a schematic diagram of the principle of the multi-head attention mechanism in the embodiment;
[0035] Figure 6 Schematic diagram of the CodeBERT pre-training principle in the embodiment. DETAILED DESCRIPTION
[0036] In order to make the purpose, technical solutions and advantages of the present invention clearer and more understandable, the present invention is further described in detail below in conjunction with the accompanying drawings and technical solutions.
[0037] Source code vulnerability mining for programming languages is very important for improving software system security, however, most of the research in this field is focused on the C language. Since Python is an interpreted language with a concise and clear grammatical structure and is closer to natural language, it has greater advantages over C language in source code vulnerability mining for Python. In addition, although the previous detection system based on the LSTM model has achieved certain results in Python source code vulnerability detection, the accuracy and recall rates are still insufficient due to the limitations of the model and the failure to fully consider the deep semantic features of the source code. The multi-classification process is relatively cumbersome and inefficient. For this reason, in the embodiments of the present invention, see Figure 1 As shown, a source code vulnerability detection method based on the Transformer language model is provided, including:
[0038] S101, obtaining code sample data, and labeling the vulnerability types in the code sample data with category labels to construct a vulnerability detection sample data set.
[0039] like Figure 2 As shown in the figure, the goal of code vulnerability detection is to detect whether there are vulnerabilities in the source code and the types of vulnerabilities. The first step is to label the vulnerability dataset and define the problem as a multi-classification problem. c represents the label category, where c = (1, 2...9, 10) represents the label number corresponding to different vulnerability types, and c = 0 indicates that the code snippet is safe. The second step is vulnerability model fine-tuning. The pre-trained model is fine-tuned with the labeled vulnerability dataset to obtain a multi-classification detection model f(). The third step is vulnerability detection. The label of the given code snippet si is detected by the fine-tuned model f(), where f(si) = (1, 2...9, 10) indicates that si is a vulnerable code. The type can be identified by the label number, and f(si) = 0 indicates that si is a safe code.
[0040] Among them, in the vulnerability data set marking, a first version of code samples and a second version of code samples can be obtained, wherein the first version of code samples is the current secure version of code, and the second version of code samples is the previous vulnerable version of code; the code lines in the two versions of code samples are compared using diff files, and the vulnerability code lines in the second version of code samples and the security code lines in the first version of code are obtained based on the comparison results; vulnerability category labels are added to the vulnerability code lines and the security code lines, and a vulnerability detection sample data set is constructed based on the vulnerability code lines and the security code lines.
[0041] diff files to build a vulnerability dataset, such as Figure 3 As shown, using diff(ai)=pi, ai represents the code line of fragment i of the current version (not vulnerable), and pi represents the code line of fragment i of the previous version (vulnerable). diff(ai)=pi means that by comparing the diff file with the code line of the current version, the vulnerable code line of the previous version is deduced, thereby obtaining the vulnerability data set.
[0042] The dataset used can be re-collected and organized based on the real-world vulnerability dataset collected and annotated by Wartschinski et al., and expanded from the original 7 datasets to 10.
[0043] The Github open source community crawls a large amount of source code and diff files about Python files, then filters out all irrelevant content, analyzes the differences between the new and old versions through diff files to create a vulnerability dataset, and then pre-trains and fine-tunes the Transformer model, using multi-classification label categories to identify vulnerable fragments and types and non-vulnerable fragments.
[0044] In order to collect data from the Github open source community, a script can be used to first check whether the commit contains keywords related to a given python vulnerability, and then check the diff file to see if any python files related to it are affected. If not, the commit can be ignored. The commit is then compared with the already downloaded commit to exclude duplicates. Each change in the commit affects the python file. For each change, the file name is checked in turn to see if it contains the vulnerability keyword. The difference between the new and old versions is analyzed through the diff file, that is, whether any code lines are actually deleted or replaced to determine the vulnerable code snippet.
[0045] The CodeBERT model is a model that directly learns and analyzes source code. The dataset must contain contextual semantic information of the training data to better play the role of the model. Therefore, the context of each vulnerable code is taken into account when labeling. The dataset is created by creating a "previous version" and "later version" of the relevant code snippets through diff files. Each code snippet contains the changed line and the three lines above and below. The part of the code that was changed or deleted in such a submission is marked as a "vulnerable label number" and the code closest to it (taking into account the context). The remaining code and the new version after the repair are marked as "not vulnerable" to create a vulnerability dataset.
[0046] In addition, after determining which lines of code in the diff file contain vulnerabilities, if the code snippets and the upper and lower parts are directly marked as "vulnerable label numbers", then the rest of the file is split into even-numbered blocks of the same average length as the vulnerable code snippets and marked as "non-vulnerable", which will lead to inconsistent code block sizes. In order to process the data correctly and avoid unbalanced datasets, vulnerable and non-vulnerable parts must be treated in the same and proportional manner in the labeling step. So, the idea is to split the data into chunks, and if the chunks overlap with the vulnerable code snippets, they are also marked with vulnerable type labels, otherwise, they are marked with non-vulnerable type labels.
[0047] Among them, in the component vulnerability dataset, a focus window with a specified step size can be used to traverse the code samples to divide the code samples into data blocks; when labeling the vulnerability types in the code, if the data block coincides with the code line corresponding to the adjacent vulnerability category label, the data block will be labeled as the vulnerability category label corresponding to the adjacent code line.
[0048] like Figure 4 As shown in the figure, a focus window is used to traverse the entire source code with a step length of c. The focus window is represented by a small blue box. The focus window starts and ends at the characters where single tokens of the Python code end (for example, colons, brackets, or spaces) to prevent the token from being cut in half. For the focus window, the surrounding context of approximately length m is determined and regarded as a code block. If the code block contains code statements with some security risks, it is marked as containing vulnerabilities, otherwise it is marked as normal code.
[0049] S102. Construct a multi-classification CodeBERT model, and use the vulnerability detection sample data set to train the multi-classification CodeBERT model, and use the trained multi-classification CodeBERT model as the vulnerability detection target model, wherein the multi-classification CodeBERT model is constructed based on the RoBERTa word segmenter and the Transformer language model.
[0050] Source code and language have many similarities. Both language and source code are used to express meaning and convey information. Language expresses ideas and concepts through language rules, while source code expresses the logic and behavior of computer programs through the rules of programming languages. Both language and source code are structured. Language organizes words and sentences through grammatical rules to make them meaningful and logical, while source code organizes variables, functions, classes and other elements through the grammatical rules of programming languages to form the structure of the program. In addition, code is written by humans, who tend to repeat traditional patterns and typical structures.
[0051] Deep neural networks are designed to model a variety of sequence data, including natural language, sensor data, and even music, and have achieved excellent results in these fields. Therefore, they have been successfully applied to model source code directly as text. The CodeBERT model built by Transformer directly uses the source code as a dataset directly into the model for pre-training. It improves the ability to understand the code by pre-training on large-scale source code. Taking all of this into account, the option is to process the source code directly in text form without relying on AST.
[0052] CodeBERT uses a Transformer architecture similar to BERT and adopts a pre-training strategy that combines mixed data of source code and natural language. This means that during the pre-training process, CodeBERT's input may include multiple forms of data such as code snippets, code comments, and natural language descriptions, allowing the model to better understand the semantics and context of the code. Taking all of this into account, the source code can be selected directly as the dataset without other forms of data representation for the source code.
[0053] The mapping of words to numeric data vectors encodes the meaning of words in a predefined vector space, known as word embedding. This process consists of two main related operations: tokenization and embedding. Tokenization converts the input sentence into characters, words, or subwords, which are semantically viable fragments. These smaller fragments are called tokens. In embedding, these tokens are mapped to associated vectors using various trained embedding methods, capturing the context around the token in the sentence.
[0054] In the embodiment of this case, the RoBERTa tokenizer is used to extract the contextual semantics of the input code and generate a code token sequence. The Transformer language model captures the dependencies between the positions in the code token sequence based on the self-attention mechanism and outputs feature embeddings to classify the feature embeddings in the multi-classification CodeBERT model output and convert them into the vulnerability category probability space.
[0055] RoBERTaTokenizer model tokenizer, which is responsible for converting the input text into tokens that the model can understand and preparing the input sequence that the model can process. The techniques used by this tokenizer usually include tokenization, which is to split the input text into words, subwords or characters, and add special tags to mark the beginning and end of sentences, and to separate different sentences or text fragments. RoBERTaTokenizer is optimized for the RoBERTa model to better handle various types of text, including code. When processing code, RoBERTaTokenizer pays special attention to the structure and grammar of the code to ensure that the generated tokens can fully reflect the meaning and context of the code. When using RoBERTaTokenizer, it is generally necessary to input the code text into the tokenizer and obtain the sequence of tokens it generates. These tokens can then be passed to the RoBERTa model to obtain the model's understanding and representation of the code. RoBERTaTokenizer can be expressed by the following formula:
[0056] RobertaTokenizer
[0057] Tokens = Tokenizer(Text)
[0058] RobertaTokenizer:Tokens=Tokenizer(Text)
[0059] in:
[0060] RobertaTokenizer is RoBERTaTokenizer.
[0061] Tokens are sequences of tokens generated by a tokenizer.
[0062] Tokenizer is a function used for word segmentation and encoding.
[0063] Text is the input text.
[0064] Transformer is a deep learning model architecture based on the attention mechanism. It completely abandons the traditional recurrent neural network (RNN) structure and uses the self-attention mechanism to capture the dependencies between positions in the input sequence. The transformer architecture mainly consists of two parts: the encoder and the decoder. The encoder is responsible for converting the input sequence into a context-aware encoded representation, while the decoder uses the encoded representation to generate the output sequence. Figure 5 As shown, the core elements in the two blocks are position encoding, multi-head attention, and fully connected layers.
[0065] Positional encoding provides the relative or exact position of a token (data point) in the input sequence and is applied to embeddings to convert the input tokens (encoder block) and output tokens (decoder block) into vectors of dimension dmodel. A sine function can be used for positional encoding, for example, even positions are Odd positions are Where i and pos are the dimension and position index respectively. Applying attention mechanism represents the input sequence by relating each word / token to the related words / tokens in the input sequence, which is called self-attention. One of its examples is scaled dot product attention. First, each output vector of the position encoding is converted into three vectors; query q, key k and value v. By multiplying the output vectors by the matrix W Q , W K and WV to perform the transformation. These matrices are constantly updated during the training process to obtain better predictions. V ) with all the keys (all vectors k) of the input sequence to generate the score S i ,i∈{1,2,3,...}. The scores are normalized and then softmax is calculated. This provides a weight for the rest of the input sequence while encoding the word at a specific position. Finally, each value vector is multiplied by the corresponding softmax score and added together to get the attention value of the token. The following equation represents all these operations in matrix form:
[0066]
[0067] in is the dimension of the key vector, Q, K, and V are matrices containing all (multi-head) queries, (multi-head) keys, and (multi-head) values, respectively.
[0068] The output of the attention function is further improved by jointly focusing on information from different representation subspaces. This is called multi-head attention and is performed as follows: (i) the query, value, and key are linearly projected h times, (ii) the attention function is computed in parallel in each projection, and (iii) the outputs of all attention functions are concatenated and projected through a linear layer, which is represented in matrix form as follows:
[0069] MultiHead(Q,K,V)=Concat(head1,...,head h )W O
[0070] in W O is the weight matrix.
[0071] In the Transformer architecture, unlike the encoder block, the decoder block has two layers of multi-head attention. The first is masked multi-head attention, enabling the target sequence, which is its previous output shifted right, to focus on itself and ignore future decoder inputs. Next is multi-head attention, enabling the target sequence to focus on the input sequence.
[0072] Therefore, considering the attention scores of the input sequence (from the encoder block), attention scores for each target sequence are generated, and these attention scores are converted from the embedding space to the probability space through the final fully connected layer and softmax layer.
[0073] Among them, Figure 2 As shown, the multi-classification CodeBERT model is trained using the vulnerability detection sample dataset, which can be designed to include:
[0074] Pre-training the multi-classification CodeBERT model using a pre-training strategy, wherein the pre-training strategy is to pre-train the model using mixed data consisting of source code and natural language so that the model can understand source code syntax and semantics;
[0075] The pre-trained multi-classification CodeBERT model is fine-tuned using vulnerability detection sample data, and the fine-tuned multi-classification CodeBERT model is used as the vulnerability detection target model.
[0076] Specifically, the pre-training strategy is used to pre-train the multi-classification CodeBERT model, which may include:
[0077] Generate a natural language masking position marker sequence and a code masking position marker sequence respectively according to the source code context by using a natural language generator and a code generator, wherein both the natural language generator and the code generator are built based on the BERT language model;
[0078] Natural language masked position marker sequences and code masked position marker sequences are sampled to form mixed data of natural language and source code. The mixed data is used to train a natural language-code discriminator, and the trained natural language-code discriminator is used as the target model in fine-tuning of the multi-classification CodeBERT model, where the natural language-code discriminator is built based on the RoBERTa word segmenter.
[0079] CodeBERT is a bimodal pre-trained transformer model for programming and natural language that can be trained on bimodal data (code and documents), and the code can come from Python, Java, JavaScript, Ruby, Go, and PHP. Figure 6As shown, its architecture follows BERT and RoBERTa. During pre-training, its architecture has two generators, namely NL generator and code generator, and an NL-code discriminator. The NL generator and code generator generate reasonable tokens for masked positions based on the surrounding context for natural language input and code input respectively. The NL-Code discriminator is trained on tokens sampled from NL-generator and Code-generator. Its architecture is the same as RoBERTa, and it is the target model for fine-tuning. In addition, it has 125M parameters, 12 layers, 768 hidden size, and 12 attention heads.
[0080] In source code snippet vulnerability mining, it is necessary to identify whether the code snippet is safe, but it is impossible to determine the vulnerability type. It is also necessary to determine the code vulnerability type, which is helpful for further patching the vulnerability. In the embodiment of this case, in the construction of the vulnerability dataset, the corresponding digital labels are marked according to the vulnerability type, and the last layer of the model is modified to add an output layer suitable for multi-classification tasks.
[0081] S103: input the source code to be detected into the vulnerability detection target model, and use the vulnerability detection target model to identify and output the vulnerability category in the source code to be detected.
[0082] Furthermore, based on the above method, an embodiment of the present invention also provides a source code vulnerability detection system based on the Transformer language model, comprising: a sample acquisition module, a model training module and a vulnerability detection module, wherein:
[0083] The sample acquisition module is used to acquire code sample data and annotate the vulnerability types in the code sample data with category labels to construct a vulnerability detection sample data set;
[0084] A model training module is used to build a multi-classification CodeBERT model, and train the multi-classification CodeBERT model using a vulnerability detection sample data set, and use the trained multi-classification CodeBERT model as a vulnerability detection target model, wherein the multi-classification CodeBERT model is built based on the RoBERTa word segmenter and the Transformer language model;
[0085] The vulnerability detection module is used to input the source code to be detected into the vulnerability detection target model, and use the vulnerability detection target model to identify and output the vulnerability category in the source code to be detected.
[0086] In order to verify the effectiveness of this solution, the following is a further explanation based on experimental data:
[0087] The dataset used is based on the real-world vulnerability dataset collected and annotated by Wartschinski et al., and is collected and organized by using the differences between the old and new versions of the diff file and the Security and Python keyword retrieval methods to create 10 categories of datasets. At the same time, in order to train the vulnerability detection model and the code vulnerability type classification model, the data is filtered and labeled. There are (434040) training data labels in the 10 categories of code features, including (309682) vulnerability codes and (124358) security codes. The collected dataset is divided according to 0.7:0.15:0.15.
[0088] Evaluation indicators are of great significance for machine learning evaluation. Different machine learning models generally require different evaluation systems to be built, and the same model also has different evaluation indicators. Each indicator has a different focus. For the purpose of prediction and classification, the following four key concepts are usually the basis of evaluation: true positive (TP), true negative (TN), false positive (FP), and false negative (FN). Positive and negative refer to predictions, which means that a "fragile" prediction will be positive and a "non-fragile" prediction will be negative. The terms "true" and "false" refer to whether the prediction is consistent with the actual value or external judgment.
[0089] Precision is the ratio of true positives among all positives, and it measures how accurate the model is, i.e. how many predicted positives are actually positives, or in other words, how much confidence is placed in the classification of positives and how many false positives are produced. If a positive overlaps with a known vulnerability, it is interpreted as true, which is reasonable since the snippet is very short.
[0090] Recall, also known as sensitivity, is a measure of the percentage of positives correctly identified compared to the actual total number of positives.
[0091] The F1 score is a balanced score (harmonic mean) that takes into account both precision and recall.
[0092] Accuracy is the fraction of correct predictions compared to all predictions. Accuracy is defined as follows:
[0093] Ideally, the model’s false positive and false negative rates are close to 0%, which means that the precision and recall, as well as the F1 score, are close to 1.
[0094] The experiments were conducted using an Ubuntu server equipped with four Intel(R) Xeon(R) Silver 4210 CPUs @ 2.20 GHz, two 24 GB NVIDIA A10 Tensor graphics processing units (GPUs), and 64 GB of memory.
[0095] Vulnerability Code Detection Model: In the vulnerability code detection experiment, the dataset is randomly shuffled, with the training set accounting for 70%, the test set accounting for 15%, and the validation set accounting for 15%.
[0096] In the Transformer architecture, unlike the encoder module, the decoder module has two layers of multi-head attention. The first is the masked multi-head attention, which enables the target sequence, i.e. the previous output of its right shift, to focus on itself and ignore future decoder inputs. Next is the multi-head attention that enables the target sequence to focus on the input sequence. Thus, attention scores are generated given the input sequence (from the encoder block), and these are derived from their spatial embeddings into the probability space through the final fully connected layer and softmax layer.
[0097] Hyperparameters have a great impact on the predictive ability of deep learning models. This study compared the changes in the accuracy, precision, recall and F1Score evaluation indicators of the model under certain batches and different training times.
[0098] The number of model trainings has a great impact on the model's prediction effect. When the number of trainings is set too small, the model's learning of sample features is not perfect, the model is in an underfitting state, and the prediction effect is very poor. When the number of trainings is set too large, the model not only learns the general features of the samples, but also learns the special features of the samples. The model is in an overfitting state and the generalization ability of the model is poor. Therefore, the experiment selects 1 / 2 / 3 / 4 / 5 / 6 / 7 / 8 / 9 / 10 training times for testing, and analyzes them by comparing their accuracy, precision, recall, and F1Score.
[0099] When the model is trained 5 times, the accuracy, precision, recall, F1Score and other indicators are all stable at a high level. Therefore, the model is trained 5 times.
[0100] In addition, the experiment shows that the batch size has little effect on the accuracy, precision, and F1Score of the model. After comprehensive consideration, the batch size is set to 16. In addition, since the BERT and CodeBERT models are used, the hidden layer size, number of hidden layers, Dropout ratio, and activation function selection are fixed. Parameters In summary, the hyperparameter settings of the model are as follows:
[0101] BERTBase has 110M parameters, 12 layers, 768 hidden layer size, and 12 attention heads, batch_size=16.
[0102] CodeBERT has 125M parameters, 12 layers, 768 hidden dimensions and 12 attention heads, batch_size = 16, activation function = AdamW, training epochs = 10
[0103] In order to verify the effectiveness of the CodeBERT model, a comparative experiment was conducted with the BERT and LSTM deep learning models on 10 different types of vulnerability datasets, while ensuring the same dataset, the same data preprocessing method, and the optimal hyperparameters.
[0104] From the comparison of multiple indicators of the three vulnerability models under different data sets, it can be seen that compared with the LSTM model used by Wartschinski et al. and Guo et al. in source code vulnerability detection, the CodeBERT and BERT models used in this study have improved in terms of Accuracy, F1Score and Recall, with Accuracy reaching 95.89%-98.63% and F1Score reaching 94.74%-98.33%. This shows that in terms of source code vulnerability detection, compared with LSTM, BERT and CodeBERT based on the Transformer model can not only learn the sequence features of the source code, but also use the characteristics of the attention mechanism to enhance the model's attention to the key features of the vulnerability, thereby further improving the performance of vulnerability detection.
[0105] In the vulnerability type classification experiment, the accuracy of CodeBERT multi-classification in 10 vulnerability types is about 96%-98%, the precision is above 94%-98%, the recall rate is 94%-99% and the F1-score is 95%-98%, and all indicators have achieved excellent results.
[0106] The above experimental data show that this solution can extract learning semantic information at a deeper level, improve the effect of source code vulnerability mining, and facilitate deployment and implementation in software security protection.
[0107] Unless otherwise specifically stated, the relative steps, numerical expressions and values of the components and steps set forth in these embodiments do not limit the scope of the present invention.
[0108] In this specification, each embodiment is described in a progressive manner, and each embodiment focuses on the differences from other embodiments. The same or similar parts between the embodiments can be referred to each other. For the system disclosed in the embodiment, since it corresponds to the method disclosed in the embodiment, the description is relatively simple, and the relevant parts can be referred to the method part.
[0109] The units and method steps of each example described in conjunction with the embodiments disclosed herein can be implemented by electronic hardware, computer software, or a combination of the two. In order to clearly illustrate the interchangeability of hardware and software, the composition and steps of each example have been generally described in the above description according to function. Whether these functions are performed in hardware or software depends on the specific application and design constraints of the technical solution. A person of ordinary skill in the art may use different methods to implement the described functions for each specific application, but such implementation is not considered to be beyond the scope of the present invention.
[0110] Those skilled in the art will appreciate that all or part of the steps in the above method can be completed by instructing related hardware through a program, and the program can be stored in a computer-readable storage medium, such as a read-only memory, a disk or an optical disk. Optionally, all or part of the steps in the above embodiment can also be implemented using one or more integrated circuits, and accordingly, each module / unit in the above embodiment can be implemented in the form of hardware or in the form of software function modules. The present invention is not limited to any specific form of combination of hardware and software.
[0111] Finally, it should be noted that the above-described embodiments are only specific implementations of the present invention, which are used to illustrate the technical solutions of the present invention, rather than to limit them. The protection scope of the present invention is not limited thereto. Although the present invention is described in detail with reference to the above-described embodiments, ordinary technicians in the field should understand that any technician familiar with the technical field can still modify the technical solutions recorded in the above-described embodiments within the technical scope disclosed by the present invention, or can easily think of changes, or make equivalent replacements for some of the technical features therein; and these modifications, changes or replacements do not make the essence of the corresponding technical solutions deviate from the spirit and scope of the technical solutions of the embodiments of the present invention, and should be included in the protection scope of the present invention. Therefore, the protection scope of the present invention shall be subject to the protection scope of the claims.
Claims
1. A source code vulnerability detection method based on Transformer language model, characterized in that: Include: Obtain code sample data and annotate category labels for vulnerability types in the code sample data to construct a vulnerability detection sample dataset; Construct a multi-classification CodeBERT model, and use the vulnerability detection sample data set to train the multi-classification CodeBERT model, and use the trained multi-classification CodeBERT model as the vulnerability detection target model, wherein the multi-classification CodeBERT model is constructed based on the RoBERTa word segmenter and the Transformer language model; The source code to be detected is input into the vulnerability detection target model, and the vulnerability detection target model is used to identify and output the vulnerability category in the source code to be detected.
2. The source code vulnerability detection method based on the Transformer language model according to claim 1 is characterized in that: Obtain code sample data and label the vulnerability types in the code sample data with category labels, including: Obtain a first version of a code sample and a second version of a code sample, wherein the first version of the code sample is a current secure version of the code, and the second version of the code sample is a previous version of the code with a vulnerability; Use the diff file to compare the code lines in the two versions of the code sample, and obtain the vulnerable code lines in the second version of the code sample and the safe code lines in the first version of the code based on the comparison results; Vulnerability category labels are added to vulnerable code lines and secure code lines, and a vulnerability detection sample dataset is constructed based on the vulnerable code lines and secure code lines.
3. The source code vulnerability detection method based on the Transformer language model according to claim 1 or 2, characterized in that: Construct a vulnerability detection sample dataset, which also includes: Traversing the code sample with a focus window of a specified step size to divide the code sample into data blocks; When labeling the vulnerability type in the code with a category label, if a data block overlaps with an adjacent code line corresponding to a vulnerability category label, the data block is labeled with the vulnerability category label corresponding to the adjacent code line.
4. The source code vulnerability detection method based on the Transformer language model according to claim 1 is characterized in that: The RoBERTa tokenizer is used to extract the contextual semantics of the input code and generate a code token sequence. The Transformer language model captures the dependencies between positions in the code token sequence based on the self-attention mechanism and outputs feature embeddings to classify the feature embeddings in the multi-classification CodeBERT model output and convert them into vulnerability category probability space.
5. The source code vulnerability detection method based on the Transformer language model according to claim 1 is characterized in that: The Transformer language model includes an encoder for converting an input into a context-aware encoded representation and a decoder for converting the encoded representation into a feature embedding.
6. The source code vulnerability detection method based on the Transformer language model according to claim 1 is characterized in that: The multi-classification CodeBERT model is trained using the vulnerability detection sample dataset, including: Pre-training the multi-classification CodeBERT model using a pre-training strategy, wherein the pre-training strategy is to pre-train the model using mixed data consisting of source code and natural language so that the model can understand source code syntax and semantics; The pre-trained multi-classification CodeBERT model is fine-tuned using vulnerability detection sample data, and the fine-tuned multi-classification CodeBERT model is used as the vulnerability detection target model.
7. The source code vulnerability detection method based on the Transformer language model according to claim 6 is characterized in that: Pre-train the multi-classification CodeBERT model using a pre-training strategy, including: Generate a natural language masking position marker sequence and a code masking position marker sequence respectively according to the source code context by using a natural language generator and a code generator, wherein both the natural language generator and the code generator are built based on the BERT language model; Natural language masked position marker sequences and code masked position marker sequences are sampled to form mixed data of natural language and source code. The mixed data is used to train a natural language-code discriminator, and the trained natural language-code discriminator is used as the target model in fine-tuning of the multi-classification CodeBERT model, where the natural language-code discriminator is built based on the RoBERTa word segmenter.
8. A source code vulnerability detection system based on Transformer language model, characterized in that: It includes: sample acquisition module, model training module and vulnerability detection module, among which, The sample acquisition module is used to obtain code sample data and annotate the vulnerability types in the code sample data with category labels to construct a vulnerability detection sample data set; A model training module is used to build a multi-classification CodeBERT model, and train the multi-classification CodeBERT model using a vulnerability detection sample data set, and use the trained multi-classification CodeBERT model as a vulnerability detection target model, wherein the multi-classification CodeBERT model is built based on the RoBERTa word segmenter and the Transformer language model; The vulnerability detection module is used to input the source code to be detected into the vulnerability detection target model, and use the vulnerability detection target model to identify and output the vulnerability category in the source code to be detected.
9. An electronic device, characterized in that: include: at least one processor, and a memory coupled to the at least one processor; The memory stores a computer program, and the computer program can be executed by the at least one processor to implement the method according to any one of claims 1 to 7.
10. A computer-readable storage medium, characterized in that: The computer-readable storage medium stores a computer program, and when the computer program is executed, the method according to any one of claims 1 to 7 can be implemented.
Citation Information
Cited By
Intelligent software security vulnerability mining method and system based on large language model
CN119150302A
Information security vulnerability assessment method and system
CN119442253A
Code search method, system and equipment based on large language model classification and prototype integration
CN119961381A
Automatic code security optimization method based on large language model
CN120046149A
Intelligent contract vulnerability detection and auditing method and system based on large language model
CN121302379A
