Rust Unsound Wrapper Detection Method and Device Based on Large Language Model
Through a method based on the large language model, the security of Rust insecure functions is described as a fine-grained contract. Combined with multiple rounds of pattern analysis, the limitations of traditional detection methods are solved, and intelligent detection of imperfect packages in the Rust code base is realized, which improves the security and reliability of the software.
Patent Information
- Application Number
- CN202510652149.6
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- Filing Date
- 2025-05-20
- Publication Date
- 2025-08-01
- Estimated Expiration
- 2045-05-20
AI Technical Summary
The existing technology is difficult to effectively detect insecure call encapsulation in Rust language, resulting in latent vulnerabilities and complex defects. Traditional natural language processing technology is difficult to analyze complex security descriptions and contract inspections for errors.
Using a method based on a large language model, the code context is obtained through static analysis tools, and the security description of the unsafe functions is decomposed as a fine-grained contract. Combined with the example library and multiple rounds of guarantee mode analysis, we check whether each contract is guaranteed, and use the large language model for intelligent detection.
It significantly improves the detection accuracy and applicability of imperfect packaging in the Rust code base, assists developers in reviewing codes, and improves software security and reliability.
Smart Images

Figure CN120179529B_ABST
Abstract
Description
Technical Field
[0001] The present invention relates to the field of computer program analysis based on large language models, and in particular to a method and device for detecting Rust unsound encapsulation based on large language models. Background Art
[0002] In the software field, system software is computer software that directly executes or controls hardware, and supports the development and operation of upper-layer application software as underlying software; ensuring the stability and security of system software is of great significance. In the past, C / C++ was the mainstream language for developing system software; however, the C / C++ language does not restrict the use of memory and pointers, resulting in software developed in the C / C++ language being prone to hidden memory leaks and pointer usage security issues, bringing great maintenance pressure to software development and maintenance personnel.
[0003] Rust is a new general-purpose system-level programming language. Through unique ownership and lifetime mechanisms, it can effectively avoid introducing memory problems during programming while maintaining high performance similar to the C / C++ language. Rust provides a security guarantee through strict checks during the compilation stage: programs written in safe Rust are guaranteed to be memory-safe as long as they can pass compilation verification. However, in actual development, in order to optimize performance or call underlying system functions, developers usually require more flexibility, and these operations are prohibited in safe Rust. For this reason, Rust provides explicit unsafe blocks that allow developers to bypass compiler checks and perform unsafe operations. Existing research has shown that calling unsafe functions is the main purpose of using unsafe code. Usually, a Rust function is declared as unsafe to emphasize that it has additional security requirements for function callers, and these requirements are called contracts by the community. Callers must ensure that all these contracts are met, otherwise calling an unsafe function may lead to undefined behavior and introduce latent vulnerabilities.
[0004] The official "Unsafe Code Guidelines" advocate encapsulating unsafe code into safe functions, enabling users to directly use the safe encapsulation without concerning about the underlying security details. The call correctness of a sound encapsulation of an unsafe call should be verifiable by the Rust compiler, meaning it should not have any additional requirements for the caller other than the formal parameter types. To this end, the encapsulation itself must ensure that all contracts of its internal unsafe functions are guaranteed. If an unsafe call is encapsulated in a safe function that does not guarantee all contracts, it will introduce unsoundness. An unsound encapsulation means that the caller can input specific values to this encapsulation in safe Rust and trigger undefined behavior, thus undermining Rust's security promise. Additionally, the unsoundness of the encapsulation may spread through function calls and data flows, leading to complex bugs and undermining Rust's advantages. Therefore, unsoundness is intolerable in the Rust community, and some partially unsound encapsulations of unsafe calls have even been disclosed as security vulnerabilities. In summary, detecting unsound unsafe encapsulations is very important.
[0005] The contracts of unsafe functions are described in an unstructured and flexible natural language form in the security notes section of the documentation. An unsafe function usually contains multiple contracts, making the security notes long and complex. Additionally, this section may also include extended descriptions (such as examples and consequences), making the content overly cumbersome. Therefore, traditional natural language processing techniques are difficult to effectively analyze various security notes. Moreover, some contracts that need to be independently checked may be mixed in one sentence, increasing the risk of omission in subsequent checks. Besides the complexity of the security notes, verifying these contracts themselves is also challenging. First, this task requires familiarity with Rust features and an in-depth understanding of the contracts of unsafe functions. Checking the contracts may require reasoning in complex contexts, involving numerous structs, functions, traits, and variable types. Overall, verifying the soundness of an unsafe call by checking whether all contracts are guaranteed is a cumbersome and error-prone task. Summary of the Invention
[0006] The purpose of the present invention is to provide a method and device for detecting unsound encapsulations in Rust based on large language models in view of the deficiencies of the prior art.
[0007] To achieve the above purpose, the present invention provides a method for detecting unsound encapsulations in Rust based on large language models, including the following steps:
[0008] (1) By analyzing the documentation and code of unsafe calls in the standard library and popular open-source projects, summarize the types of contracts and the corresponding guarantee modes for each contract type, and design examples for each guarantee mode;
[0009] (2) Obtain the relevant context of the target encapsulation through a static analysis tool, including code hints and reference information;
[0010] (3) Decompose the original security description of the insecure functions within the encapsulation into multiple fine-grained contracts through a large language model, and classify each contract into the types defined in step (1);
[0011] (4) Use the large language model to analyze each fine-grained contract, and provide corresponding examples for the large language model in combination with the contract types and corresponding safeguard modes classified in step (3) to analyze whether the encapsulation provides safeguards for the target fine-grained contract; the examples include requests and reference answers, and the requests include reference information, the code of the encapsulation, and the fine-grained contract to be inspected;
[0012] (5) Summarize the analysis results of all fine-grained contracts. If there are contracts that are not safeguarded, determine that the insecure call encapsulation is an unsound encapsulation; otherwise, determine it to be a sound encapsulation.
[0013] Further, the reference information includes the functions, structures, and their documents called; the code hints include formal parameter name hints and variable type hints.
[0014] Further, it also includes trimming the reference information:
[0015] (1) Retain the code fragments of the structure;
[0016] (2) In the code of the functions and macros being referenced, the implementation details will be omitted, and only their function signatures will be retained;
[0017] (3) Retain the descriptive part of the document, which provides a brief overview of the functions of the elements.
[0018] Further, step (3) also includes: improving the quality of contract splitting and classification through the large language model's self-review and optimization process iteration, specifically:
[0019] The large language model reviews whether the currently decomposed fine-grained contracts meet all the requirements of consistency, non-overlap, atomicity, unique classification, and clarity, provides detailed review opinions for each requirement, and finally decides whether to optimize the decomposition results; if optimization is needed, the large language model optimizes the decomposition results based on the original security description, the current decomposition and classification results, and the review opinions and outputs the optimized fine-grained contracts and corresponding types.
[0020] Further, in step (4), the large language model checks each fine-grained contract alone; when checking a certain fine-grained contract, it will conduct multiple rounds of checks according to the type of the fine-grained contract, with each round corresponding to a safeguard mode of the contract type, and provide examples of the corresponding safeguard mode when using the large language model for inspection.
[0021] Further, it further includes a pre-built example library; the examples in the example library are divided into two categories: positive examples and negative examples of the safeguard mode, which are used as demonstrations to be added to the prompt; the positive examples of the safeguard mode correspond to a certain safeguard mode, describing how the encapsulation safeguards the establishment of the contract in this safeguard mode; the negative examples are used to explain the reason why a certain fine-grained contract is considered to be unsecured.
[0022] Further, in step (5), first summarize the analysis results corresponding to the safeguard mode in step (4). As long as the fine-grained contract is safeguarded by any one mode, it is considered that the contract is safeguarded, otherwise it is unsecured; then summarize the results of each fine-grained contract to obtain the soundness of the encapsulation. If any one fine-grained contract is unsecured, the encapsulation is unsound.
[0023] Further, when the model does not output as expected, corresponding measures are taken to improve the usability of the system, including:
[0024] For the unknown classification result in step (3), determine the contract type through vector similarity;
[0025] If the large language model in step (4) does not give an affirmative answer, it is determined to be unsecured.
[0026] To achieve the above object, the present invention also provides a Rust unsound encapsulation detection device based on a large language model, including one or more processors for implementing the above method.
[0027] To achieve the above object, the present invention also provides an electronic device, including a memory and a processor, the memory is coupled to the processor; wherein, the memory is used to store program data, and the processor is used to execute the program data to implement the above-mentioned Rust unsound encapsulation detection method based on a large language model.
[0028] To achieve the above object, the present invention also provides a computer-readable storage medium, on which a computer program is stored, and when the program is executed by the processor, it implements the above-mentioned Rust unsound encapsulation detection method based on a large language model.
[0029] The beneficial effects of the present invention are: existing methods have great limitations in detecting unsound encapsulations of unsafe calls in the Rust language, while the present invention uses a large language model combined with static analysis technology to achieve intelligent detection of the soundness of encapsulation code. Through fine-grained contract splitting, classification, and multi-round safeguard mode analysis, the present invention significantly improves the accuracy and applicability of detection, can effectively detect unsound encapsulations in the Rust code library, assist developers in reviewing code, and improve software security and reliability. Description of the Drawings
[0030] To more clearly illustrate the technical solutions in the embodiments of the present invention, the following will briefly introduce the drawings required for the description of the embodiments. Obviously, the drawings in the following description are only some embodiments of the present invention. For those of ordinary skill in the art, without creative efforts, other drawings can also be obtained based on these drawings.
[0031] Figure 1 is the overall framework diagram of the method of the present invention;
[0032] Figure 2 is the flow chart of the decomposition and classification of the security description including iterative self-check in the present invention;
[0033] Figure 3 is the structural schematic diagram of the device of the present invention;
[0034] Figure 4 is the schematic diagram of an electronic device of the present invention. Specific embodiments
[0035] The following will clearly and completely describe the technical solutions in the embodiments of the present invention with reference to the drawings in the embodiments of the present invention. Obviously, the described embodiments are only some embodiments of the present invention, rather than all embodiments. Based on the embodiments of the present invention, all other embodiments obtained by those of ordinary skill in the art without creative efforts belong to the protection scope of the present invention.
[0036] A Rust unsound encapsulation detection method based on a large language model of the present invention, see Figure 1 , includes the following steps:
[0037] (1) By analyzing the documents and codes of unsafe calls in the standard library and popular open-source projects, summarize the types of contracts and the possible guarantee modes corresponding to each contract type, and design examples for each guarantee mode;
[0038] In one embodiment, open-source Rust code is first crawled from the GitHub open-source code hosting platform as an experimental data set. Specifically, the present invention first analyzes the unsafe call encapsulations in the Rust standard library and the top 500 packages with the highest download volume on the central repository. All code libraries are cloned from the latest commits on GitHub on May 25, 2024. These packages cover multiple fields and have been extensively reviewed to ensure the quality and comprehensiveness of the preliminary research.
[0039] After collecting the documentation of all insecure call wrappers and the insecure functions they reference, the present invention introduces two rounds of manual analysis. The goal of the first round of analysis is to classify the content in the security specifications into different contract types, while the second round of analysis is dedicated to refining the safeguard patterns for each contract type. In the first round of analysis, the researchers read through the documentation of the involved insecure APIs one by one, summarized the contract types, and classified the contracts in the documentation. In the second round of analysis, based on the results of the first round, the researchers refined the corresponding safeguard patterns for each contract type. For a specific contract type, we manually examined the code and documentation of all relevant insecure call wrappers and grouped these wrappers into several subgroups according to the way the safeguard patterns hold.
[0040] Referring to Table 1 and Table 2, the embodiments of the present invention finally define 16 contract types and their corresponding 34 safeguard patterns. These 16 contract types focus on different aspects of security requirements, including memory and pointers, values, concurrency, lifecycle, ownership, data flow, and environment.
[0041] Table 1: Some Contract Types and Their Corresponding Safeguard Patterns
[0042]
[0043] Table 2: The Remaining Contract Types and Their Corresponding Safeguard Patterns
[0044]
[0045] To fully activate the context learning ability of the large language model, the present invention pre-constructs an example library, and the examples in the example library can be added to the prompt as demonstrations. These examples are divided into two categories: positive examples and negative examples of safeguard patterns. Positive examples of safeguard patterns correspond to specific safeguard patterns and describe how the wrapper safeguards the establishment of the contract in that safeguard pattern. On the contrary, negative examples are used to explain why a certain contract is considered unprotected. According to the previously summarized 16 contract types and 34 safeguard patterns, the example library contains 34 positive examples of patterns and 16 negative examples. Both positive examples and negative examples of safeguard patterns consist of requests and reference answers. Among them, the requests include reference information, the code of the wrapper, and the fine-grained contract to be inspected. The reference answers are step-by-step analyses written by humans, implicitly demonstrating a specific safeguard pattern or explaining why the contract cannot be protected.
[0046] (2) Obtain the relevant context of the target wrapper through a static analysis tool, including code hints and reference information;
[0047] In one embodiment, for the encapsulation of unsafe calls to be inspected, the embodiments of the present invention first use a static analysis tool to retrieve relevant context information, including code hints and reference information. Code hints are code snippets that can be attached to the original code to provide richer information, such as the deduced variable types and the parameter names shown in function calls. Reference information includes relevant information about elements such as structures, functions, and features involved in the target unsafe call encapsulation.
[0048] Rust is an implicitly statically typed language, meaning that variable types can be deduced from the code context without explicit annotation. Additionally, the contracts of unsafe functions are usually described in terms of parameter names, so when checking whether the contract is guaranteed, it is necessary to match the function formal parameters with specific variables. However, this matching process is error-prone for large language models, resulting in inaccurate generated answers. For example, assume an unsafe function " " stipulates that "a must be greater than b", and the call pattern is " ". Then the large language model may incorrectly map variables b and a to parameters a and b, making it difficult to correctly check this unsafe call. Additionally, the type of the new variable c is also not clear, and variable types contain some semantic information that is crucial when providing guarantees for the contract. For example, variables of a certain type must be non-negative. After adding code hints, the call code will become " ", making the variable types clearer and the correspondence between variables and parameters more obvious.
[0049] To accurately and efficiently obtain variable types, the present invention includes a retriever that can extract type deduction results from the compiler and attach the deduced types to the original code in a format that conforms to Rust syntax. Specifically, for a new variable declared in a " " statement, its type will be attached after the variable in the format " "; for the return type of a closure, the format is " ". Additionally, to establish the matching relationship between function formal parameters and the specific variables passed in, the present invention analyzes the parameter list declared in the function signature and adds the parameter name in front of the variable name in the format " ".
[0050] In one embodiment, considering that the warehouse to be inspected is a real project with a large amount of code and is relatively complex, the target non-safe call encapsulation usually involves a large number of external elements, such as structures and functions. Without providing the reference information of these elements, the large language model often gives wrong answers with serious hallucinations. To retrieve the reference information, the present invention extends the Rust language server Rust Analyzer. First, by analyzing the abstract syntax tree of the target non-safe call encapsulation, the present invention extracts all the referenced elements. Subsequently, Rust Analyzer combines the analysis results of the entire project to retrieve the documentation and code of these elements.
[0051] However, since the reference information may grow exponentially, the present invention only includes directly referenced elements. Even so, the retrieved information may still be too redundant and not conducive to the large language model's retrieval of information. Therefore, the present invention adopts the following rules to prune the reference information:
[0052] (a) The code snippet of the structure (i.e., the structure definition) will be completely retained because its field information is very important and can provide information such as field types and the association relationships between attributes.
[0053] (b) The overly long implementation details in the code of the referenced functions and macros will be omitted, and only their function signatures will be retained.
[0054] (c) Although the documentation information is valuable, it is usually too long to be directly used. To balance the amount of information, the present invention retains the description part of the documentation, which provides a brief overview of the function of the element.
[0055] In addition, for the used unsafe functions, the present invention extracts the security instructions in their documentation for further inspection.
[0056] (3) Decompose the original security instructions of the unsafe functions in the encapsulation into multiple fine-grained contracts through the large language model, and classify each contract into the types defined in step (1);
[0057] In one embodiment, the embodiment of the present invention uses the large language model to decompose the original security instructions into fine-grained contracts so that each contract can be independently inspected. This decomposition process needs to meet the following requirements:
[0058] Consistency: The decomposed contracts must be derived from the original security instructions and cover all the described security requirements.
[0059] Non-overlap: The decomposed contracts cannot overlap with each other.
[0060] Atomicity: The decomposed contracts cannot be further disassembled.
[0061] Unique Classification: Each decomposed contract can only belong to one contract category.
[0062] Clarity: The decomposed contracts should be concise but clearly expressed.
[0063] To meet the unique classification requirement and facilitate subsequent analysis, the present invention adds the names and definitions of all contract types to the prompt information for the large language model and requires the large language model to complete classification while decomposing the contracts. The prompt information also contains seven examples to fully stimulate the context learning ability of the large language model to further improve the accuracy of classification. By decomposing and classifying the security instructions, the present invention can obtain multiple fine-grained contracts and their corresponding types.
[0064] See Figure 2 Since the quality of decomposition and classification directly affects the accuracy of subsequent inspections, the present invention further uses the large language model to self-check and optimize the results of decomposition and classification. Specifically, the present invention uses specific prompt words to let the large language model review whether the currently decomposed contracts meet all the requirements of consistency, non-overlap, atomicity, unique classification, and clarity:
[0065] """
[0066] ## Role Description:
[0067] You are a senior software engineer proficient in Rust.
[0068] ## Background:
[0069] {Omit the specific description of the background}
[0070] ## Task Definition: Your task is to strictly check whether the "Safety" section of the unsafe Rust function is correctly and faithfully decomposed into fine-grained contracts. Be skeptical of the given contracts and adopt the strictest and most conservative analysis method. Assume that each contract may have hidden problems and analyze it critically. Do not accept any contract without fully verifying its correctness. You must traverse all the decomposed contracts and analyze whether each contract meets the following criteria:
[0071] {Omit the specific description of the decomposition requirements}
[0072] Finally, you must give a summary and a final judgment, indicating whether the decomposed contracts are perfect and require no modification in bold "Yes" or "No".
[0073] ## Contract Type Definition:
[0074] {Omit the names and definitions of the contract types}
[0075] """
[0076] The large language model will provide detailed review comments for each requirement and finally decide whether the decomposition result needs to be optimized. If optimization is required, the present invention will further let the large language model optimize the decomposition result according to the original security description, the current decomposition and classification results, and the review comments given by the large language model, and output the optimized fine-grained contract and the corresponding type. The specific prompt words are as follows:
[0077] """
[0078] ## Role description:
[0079] You are a senior software engineer proficient in Rust
[0080] ## Background:
[0081] In Rust, unsafe functions always declare their contract requirements to the caller through the "Safety" section. Programmers must satisfy all the required contracts, otherwise unsafe calls may lead to undefined behavior. However, the content of the "Safety" section may be redundant and not easy to read. To improve clarity, we need to decompose the "Safety" section into fine-grained contracts and classify them according to clearly defined contract types. The decomposition process must meet the following criteria:
[0082] {Omit the specific description of the decomposition criteria}
[0083] ## Task definition:
[0084] You will receive: 1) information about an unsafe Rust function, including the original "Safety" section; 2) the decomposed fine-grained contracts and their types; 3) an analysis of the decomposed contracts based on the decomposition criteria. Your task is to improve these contract decompositions based on all the information provided (especially the analysis comments). You must 1) carefully analyze each analysis point and determine the appropriate modification plan; 2) modify the contract accordingly if the analysis is correct; 3) clarify the contract on the premise of ensuring correctness if the analysis is incorrect or the expression is ambiguous.
[0085] ## Response format:
[0086] The response content should only contain the list of refined fine-grained contracts in the following format: "- bytes must contain valid UTF-8 encoding (Encoding)". Each entry corresponds to a specific contract and its type.
[0087] ## Contract type definition:
[0088] {Omit the name and definition of the contract type}
[0089] """
[0090] The above process will be iteratively executed until the large language model determines that no further optimization is required. To avoid self-checking for infinite loops, the present invention sets a limit on the maximum number of iterations to ensure that the decomposition and classification processes are completed within a reasonable range.
[0091] (4) Analyze each fine-grained contract using the large language model, and provide corresponding examples for the large language model in combination with the contract types classified in step (3) and the corresponding safeguard modes, and analyze whether the encapsulation provides safeguards for the target fine-grained contract;
[0092] In one embodiment, the embodiment of the present invention checks whether each fine-grained contract is safeguarded within the encapsulation by sending a request to the large language model. This request is generated by filling in a template, and the filled content includes the cropped reference information, the code with code hints, and the description of the target fine-grained contract.
[0093] To provide accurate domain knowledge to the large language model, the present invention selects corresponding examples from the example library according to the type of the target contract. However, due to the significant differences between different safeguard modes, it is difficult for the large language model to learn the domain knowledge of all safeguard modes simultaneously from the context. Therefore, the present invention designs multi-round mode-oriented checks, and each round of check corresponds to a single safeguard mode related to the target contract type. Specifically, in each round of check, the present invention selects a mode example related to this safeguard mode and a counterexample corresponding to the target contract type. In this round of check, the large language model will finally make a judgment on whether the contract is safeguarded by the non-secure call encapsulation under this safeguard mode.
[0094] To effectively stimulate the reasoning ability of the large language model, the present invention instructs it to use the chain-of-thought method for checking, rather than simply requiring it to analyze step by step. The present invention requires the large language model to follow the following steps for reasoning:
[0095] (I) Locate the code segment of the non-secure call.
[0096] (II) List the variables related to the contract.
[0097] (III) Analyze step by step around the contract.
[0098] (IV) Judge whether the contract is safeguarded.
[0099] In the first step, the large language model clarifies its analysis objective and repeats relevant code snippets to reduce hallucination phenomena caused by input conflicts. The second step extracts key expressions in the code to facilitate subsequent reasoning steps. The third step is the core analysis phase, where the large language model uses its inherent capabilities and domain knowledge learned from examples to perform detailed step-by-step reasoning. Finally, the large language model needs to give a clear "yes" or "no" as the final judgment to automate the output processing. This chain of checks is not only specified in the system prompt of the request but also demonstrated through few-shot examples. The difficulty of the four steps increases gradually, and each step depends on the output of the previous step. In addition to enhancing the reasoning ability of the large language model, the chain-of-thought method also enhances the interpretability of the output, enabling human reviewers to more easily determine whether it is a false positive by reading the output of the large language model.
[0100] After all the pattern-oriented checks, the judgment results for each safeguard pattern can be obtained. Through the "OR" operation, these judgment results are combined into the overall judgment result for the contract. Finally, considering that a sound non-secure call encapsulation must provide safeguards for all contracts, the present invention further aggregates the judgment results of all contracts through the "AND" operation as the final judgment on whether the non-secure call encapsulation is sound. If the final judgment result of a certain contract is unprotected, it means that the contract is not protected by the non-secure call encapsulation and corresponding repairs are required. The present invention defines such unprotected fine-grained contracts as contract-level unsoundness.
[0101] In addition to the above three parts, namely the encapsulation context acquirer, the security description splitter, and the fine-grained contract discriminator, the present invention also implements solutions for abnormal situations that may affect automation in actual scenarios, thereby improving the usability of the present invention.
[0102] First, since the present invention checks reliability based on security instructions, insecure functions lacking documentation or security instructions will be directly skipped. During the decomposition and classification stage, the large language model may misclassify the contract as an undefined type or directly output "unknown". In response to these situations, the present invention will obtain the vector representation of the contract through the encoding model and match the contract in the example library that is most similar to it through cosine similarity to determine its type. During the contract inspection process, although the large language model ultimately needs to answer "yes" or "no", it may output "unknown" in uncertain situations. During the result aggregation, the present invention treats "unknown" as a variant of "not guaranteed". For insecure call encapsulations involving multiple insecure calls, the present invention will separately decompose the security instructions of each call and perform pattern-based inspections on all fine-grained contracts. Similarly, only when all contracts are determined to be "guaranteed" will the insecure call encapsulation be considered "reliable". In addition, if any contract of an insecure call is determined to be "not guaranteed", the insecure call will be considered unreliable at the function level.
[0103] Corresponding to the foregoing embodiment of a method for detecting Rust unsound encapsulation based on a large language model, the present invention also provides an embodiment of a device for detecting Rust unsound encapsulation based on a large language model.
[0104] See Figure 3 , an embodiment of a device for detecting Rust unsound encapsulation based on a large language model provided by an embodiment of the present invention includes one or more processors for implementing a method for detecting Rust unsound encapsulation based on a large language model in the foregoing embodiment.
[0105] An embodiment of a device for detecting Rust unsound encapsulation based on a large language model of the present invention can be applied to any device with data processing capabilities, and the any device with data processing capabilities can be a device or apparatus such as a computer. The device embodiment can be implemented through software, or through hardware or a combination of software and hardware. Taking software implementation as an example, as a logically meaningful device, it is formed by the processor of any device with data processing capabilities where it is located reading the corresponding computer program instructions in the non-volatile memory into the memory for operation. From a hardware perspective, as Figure 3 shown, it is a hardware structure diagram of any device with data processing capabilities where the device for detecting unsound encapsulation of insecure calls in the Rust language based on a large language model of the present invention is located. In addition to Figure 3 the processor, memory, network interface, and non-volatile memory shown, any device with data processing capabilities where the device in the embodiment is located usually also includes other hardware according to the actual functions of the any device with data processing capabilities, which will not be elaborated here.
[0106] For the implementation processes of the functions and roles of each unit in the above device, please refer to the implementation processes of the corresponding steps in the above method for details, which will not be elaborated here.
[0107] For the device embodiments, since they basically correspond to the method embodiments, the relevant parts can be referred to the partial descriptions of the method embodiments. The device embodiments described above are only illustrative. The units described as separate components may or may not be physically separated, and the components shown as units may or may not be physical units, that is, they may be located in one place or distributed to multiple network units. Some or all of the modules can be selected according to actual needs to achieve the purpose of the solution of the present invention. Those of ordinary skill in the art can understand and implement it without creative efforts.
[0108] Corresponding to the foregoing embodiments of a method for detecting unsound Rust encapsulation based on a large language model, an embodiment of the present application further provides an electronic device, including: one or more processors; a memory for storing one or more programs; when the one or more programs are executed by the one or more processors, the one or more processors implement a method for detecting unsound Rust encapsulation based on a large language model as described above. As Figure 4 shown, it is a hardware structure diagram of a device with any data processing ability where the method for detecting unsound Rust encapsulation based on a large language model provided by an embodiment of the present application is located. In addition to Figure 4 the processors, memory, DMA controller, disk, and non-volatile memory shown, any device with data processing ability where the device in the embodiment is located usually includes other hardware according to the actual functions of the device with any data processing ability, which will not be elaborated here.
[0109] Corresponding to the foregoing embodiments of a method for detecting unsound encapsulation of unsafe calls in Rust language based on a large language model, an embodiment of the present invention further provides a computer-readable storage medium, on which a program is stored. When the program is executed by a processor, it implements the method for detecting unsound encapsulation of unsafe calls in Rust language based on a large language model in the above embodiments.
[0110] The computer-readable storage medium may be an internal storage unit of any device with data processing capabilities described in any of the foregoing embodiments, such as a hard disk or memory. The computer-readable storage medium may also be any device with data processing capabilities, such as a plug-in hard disk, a Smart Media Card (SMC), an SD card, a Flash Card, etc. equipped on the device. Further, the computer-readable storage medium may also include both an internal storage unit of any device with data processing capabilities and an external storage device. The computer-readable storage medium is used to store the computer program and other programs and data required by any device with data processing capabilities, and may also be used to temporarily store data that has been output or is to be output.
[0111] The above are only the preferred embodiments of the present invention and are not intended to limit the present invention. Any modifications, equivalent replacements, improvements, etc. made within the spirit and principles of the present invention shall be included within the scope of protection of the present invention.
[0112] The above embodiments are only used to illustrate the design concept and features of the present invention, and their purpose is to enable those skilled in the art to understand the content of the present invention and implement it accordingly. The scope of protection of the present invention is not limited to the above embodiments. Therefore, any equivalent changes or modifications made based on the principles and design concepts disclosed by the present invention are within the scope of protection of the present invention.
Claims
1. A method for detecting unsound encapsulation in Rust based on large language models, characterized in that, It includes the following steps: (1) By analyzing the documents and codes of insecure calls in the standard library and popular open-source projects, summarize the types of contracts and the corresponding safeguard modes for each contract type, and design examples for each safeguard mode; (2) Obtain the relevant context of the target encapsulation through a static analysis tool, including code hints and reference information; (3) Use a large language model to decompose the original security description of the insecure functions within the encapsulation into multiple fine-grained contracts, and classify each contract into the types defined in step (1); (4) Use a large language model to analyze each fine-grained contract, and provide corresponding examples for the large language model in combination with the contract types and corresponding safeguard modes classified in step (3) to analyze whether the encapsulation provides safeguards for the target fine-grained contract; the examples include requests and reference answers, and the requests include reference information, the code of the encapsulation, and the fine-grained contract to be inspected; (5) Summarize the analysis results of all fine-grained contracts. If there are contracts that are not safeguarded, determine that the insecure call encapsulation is an unsound encapsulation; otherwise, determine it as a sound encapsulation.
2. The method according to claim 1, wherein The reference information includes the functions, structures called and their documents; the code hints include parameter name hints and variable type hints.
3. The method according to claim 1, characterized in that, It also includes trimming the reference information: (1) Retain the code snippets of the structures; (2) In the code of the functions and macros being referenced, the implementation details will be omitted, and only their function signatures will be retained; (3) Retain the descriptive part of the document, which provides a brief overview of the functions of the elements.
4. The method according to claim 1, characterized in that Step (3) also includes: improving the quality of contract splitting and classification through the self-review and optimization process iteration of the large language model. Specifically: The large language model reviews whether the currently decomposed fine-grained contracts meet all the requirements of consistency, non-overlap, atomicity, unique classification, and clarity, provides detailed review opinions for each requirement, and finally decides whether it is necessary to optimize the decomposition results; if optimization is needed, the large language model optimizes the decomposition results according to the original security description, the current decomposition and classification results, and the review opinions, and outputs the optimized fine-grained contracts and corresponding types.
5. The method according to claim 1, wherein In step (4), the large language model checks each fine-grained contract alone; when checking a certain fine-grained contract, it will conduct multiple rounds of checks according to the type of the fine-grained contract, with each round corresponding to a safeguard mode of the contract type, and examples of the corresponding safeguard mode are provided when using the large language model for the check.
6. The method according to claim 1 or 5, characterized in that It also includes a pre-built example library; the examples in the example library are divided into two categories: positive examples and negative examples of safeguard modes, which are used as demonstrations to be added to the prompts; the positive examples of safeguard modes correspond to a certain safeguard mode and describe how the encapsulation safeguards the establishment of the contract in that safeguard mode; The negative examples are used to explain the reasons why a certain fine-grained contract is considered not to be safeguarded.
7. The method according to claim 1, characterized in that In step (5), first summarize the analysis results of the corresponding safeguard modes in step (4). As long as a fine-grained contract is safeguarded by any one mode, it is considered that the contract is safeguarded, otherwise it is not; then summarize the results of each fine-grained contract to obtain the soundness of the encapsulation. If any one fine-grained contract is not safeguarded, the encapsulation is unsound.
8. The method according to claim 1, wherein When the model fails to output as expected, corresponding measures are taken to improve the availability of the system, including: For the unknown classification result in step (3), the contract type is determined by vector similarity; If the large language model in step (4) does not give an affirmative answer, it is considered unguaranteed.
9. A Rust unsound encapsulation detection device based on a large language model, characterized in that, Comprising one or more processors for implementing a method for detecting Rust unsound encapsulation based on a large language model according to any one of claims 1-8.
10. A computer-readable storage medium having a computer program stored thereon, characterized in that, When the program is executed by the processor, it implements a method for detecting Rust unsound encapsulation based on a large language model according to any one of claims 1-8.
Citation Information
Patent Citations
Automatic Rust program defect detection method and system based on feature extraction
CN116680705A
Secure transport software update
US20240004639A1