A method and system for detecting and fixing re - entry vulnerabilities

Through static detection and template repair methods, combined with lock and reordering strategies, the shortcomings of reentry vulnerability detection and repair in the existing technology are solved, and efficient and secure repair of smart contracts is achieved to ensure that the contract semantics remains unchanged.

CN115408689BActive Publication Date: 2025-07-04PEKING UNIV +1
View PDF 2 Cites 0 Cited by

Patent Information

Application Number
CN202110577018.8
Authority / Receiving Office
CN · China
Patent Type
Patents(China)
Current Assignee / Owner
Filing Date
2021-05-26
Publication Date
2025-07-04
Estimated Expiration
2041-05-26

AI Technical Summary

Technical Problem

The existing reentry vulnerability detection methods have problems with missed detection and misjudgment, and the existing repair system cannot cover all branches and cannot modify on-chain contracts, resulting in insufficient security of smart contracts.

Method used

Static detection and template-based repair methods are adopted, combined with locking and reordering strategies, reentry vulnerabilities in smart contracts are detected and repaired, semantic equivalent repair code is generated, and repair results are verified through test cases.

Benefits of technology

A 100% reentry vulnerability detection rate and repair rate is achieved, ensuring that the contract semantics remains unchanged, improving the security of smart contracts, and preventing attackers from maliciously modifying the blockchain state.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN115408689B_ABST
    Figure CN115408689B_ABST
Patent Text Reader

Abstract

The present invention discloses a method and a system for detecting and fixing reentrancy vulnerabilities. The detection method of the present invention is as follows: perform single reentrancy path detection and combined reentrancy path detection on the smart contract source code to be processed; among them, the single reentrancy path detection method is as follows: first, compile the smart contract source code to generate Ethereum Virtual Machine bytecode, Application Binary Interface, source code mapping, and Abstract Syntax Tree, and then traverse the Ethereum Virtual Machine bytecode to obtain the execution path of the smart contract source code and generate a control flow graph, and identify the reentrancy pattern of the path according to the reentrancy pattern mapping table during the traversal process; among them, the combined reentrancy path detection method is as follows: traverse the main reentrancy path, combine each main reentrancy path with each reentered path in pairs, and determine whether the path after each combination meets the connectivity and the read-write pattern of the reentrancy vulnerability. If it meets, it is considered that there is a reentrancy vulnerability. The present invention can fix vulnerabilities on the premise of ensuring the contract semantics remain unchanged.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] The present invention relates to the field of smart contract security, and specifically to a method and system for detecting and fixing reentrancy vulnerabilities. Background Art

[0002] In recent years, the cryptocurrency market has been booming. There are approximately 5,392 cryptocurrencies in circulation, with a total market capitalization of $201 billion as of April 22, 2020 (reference: R. Bagshaw. Top 10 cryptocurrencies by market capitalization, 2020). The blockchain platform, Ethereum, as a widely used public blockchain, supports the execution of smart contracts. Smart contracts are programs stored on the blockchain that can assist and verify the negotiation and execution of contracts. Due to the immutable nature of the blockchain and its transparency, if a smart contract has security vulnerabilities, the resulting losses can be substantial and irreparable. Therefore, this paper aims to detect and fix reentrancy vulnerabilities in smart contracts before they are deployed on the blockchain.

[0003] Reentrancy Vulnerability Detection and Fixing

[0004] The currently commonly used method for detecting reentrancy vulnerabilities is static analysis. Oyente, Zeus, and Securify all use static analysis methods (see L. Luu, D.-H. Chu, H. Olickel et al., “Making smart contracts smarter”. In: Proceedings of the 2016 ACM SIGSAC conference on computer and communications security, 2016: 254–269; S. Kalra, S. Goel, M. Dhawan et al., “ZEUS: Analyzing Safety of Smart Contracts.” In: NDSS, 2018; P. Tsankov, A. Dan, D. Drachsler-Cohen et al., “Securify: Practical security analysis of smart contracts”. In: Proceedings of the 2018 ACM SIGSAC Conference on Computer and Communications Security, 2018: 67–82). However, for the first two, due to the incomplete definition of the reentrancy vulnerability pattern, they can only detect reentrancy vulnerabilities that re-enter their own functions, resulting in missed detections. For the latter, due to the overly conservative definition of the reentrancy vulnerability pattern, it will misjudge contracts that have added reentrancy locks and no longer contain reentrancy vulnerabilities. Sereum uses a dynamic detection method (see M. Rodler, W. Li, G. O. Karame et al., “Sereum: Protecting Existing Smart Contracts Against Re-Entrancy Attacks”. In: 26th Annual Network and Distributed System Security Symposium, NDSS 2019, San Diego, California, USA, February 24-27, 2019). However, its limitation is that it cannot cover all branches in the contract. If some execution processes of a function are not called in a transaction, then the reentrancy vulnerabilities in these execution processes will not be discovered.

[0005] Traditional software automation repair frameworks are divided into "generation and verification" frameworks and "semantic-driven" frameworks. Yu et al. implemented the SCRepair system to automatically repair reentrancy vulnerabilities by referring to the "generation and verification" framework (see X.L. Yu, O. Al-Bataineh, D. Lo et al. "Smart contract repair". ACM Transactions on Software Engineering and Methodology (TOSEM), 2020, 29(4): 1–32). However, the current system can only detect and repair publicly available contracts on the blockchain (modifying the downloaded copy without modifying the content on the blockchain) because the test cases rely on transactions that have been executed on the blockchain, making it difficult to detect and repair vulnerable contracts that have not been uploaded to the blockchain and generate transactions. In addition, a relatively random method is used to generate patches in the system, lacking formal verification of semantic equivalence of the repair results. Therefore, this paper adopts a template-based repair method to complete the repair of reentrancy vulnerabilities and formal verification of semantic equivalence. Summary of the Invention

[0006] Aiming at the technical problems existing in the prior art, the purpose of the present invention is to provide a method and system for detecting and repairing reentrancy vulnerabilities. The present invention uses static detection and template-based repair methods, and designs lock-based repair templates and reordering-based repair templates for three types of reentrancy vulnerabilities, namely RRW-Self, RRW-Cross, and RWR-Cross, and implements a detection and repair system. With the help of this tool, users only need to provide the Solidity source code of the smart contract to generate a reentrancy vulnerability detection and repair report, including detection results, repaired code, and verification test cases. Subsequently, users can use the test cases to check the semantic equivalence of the repaired code on the test blockchain. Reentrancy vulnerabilities in smart contracts can be exploited by attackers to maliciously modify the blockchain state, including repeated transfers, contract variable modifications, and abnormal log records, resulting in financial risks. The purpose of the present invention is to detect reentrancy vulnerabilities in smart contracts using static detection methods and repair the vulnerabilities while ensuring the contract semantics remain unchanged, generating contract source code and test cases without reentrancy vulnerabilities.

[0007] The technical solution of the present invention is as follows:

[0008] A method for detecting and repairing reentrancy vulnerabilities that combines static detection and template repair, the steps of which include:

[0009] 1) The user provides the Solidity source code of the smart contract to be analyzed and uploads it to the detection and repair system.

[0010] 2) The detection and repair system performs re - entry vulnerability detection on the source code. Specifically, it is divided into two parts: single - re - entry path detection and combined re - entry path detection. After 21) and 22) are completed, the re - entry vulnerability repair steps in 4) are carried out.

[0011] 21) Single - re - entry path detection: First, compile the source code and generate information such as EVM (Ethereum Virtual Machine) bytecode, ABI (Application Binary Interface), SourceMapping

[0012] (source code mapping), AST (Abstract Syntax Tree), etc. Then, use the Z3

[0013] (https: / / github.com / Z3Prover / z3) constraint solver to traverse the EVM bytecode, obtain the execution paths of the contract and generate a control flow graph. During the traversal, identify the re - entry patterns of single paths according to the key instructions on the path. The definition of the re - entry pattern and the key instructions can be seen in the re - entry pattern mapping table, and record the main re - entry path patterns (RCW, RCR) and the re - entered path patterns (RC, RW, RL, RJ) in units of paths. After each path traversal is completed, if the path contains a state - modifying node, generate a semantically equivalent test case for this path, that is, perform step 31).

[0014] 22) Combined re - entry path detection: First, remove duplicates from the paths with the same path conditions in the main re - entry path patterns in 21). Then, traverse the main re - entry paths, combine each main re - entry path with each re - entered path pairwise, and use the Z3 constraint solver and stain - tracking technology to judge whether the connectivity of the combined path and the read - write mode of the re - entry vulnerability are satisfied (use stain analysis technology to judge the dependency relationship between instructions, use the Z3 constraint solver to divide the constraint conditions in the execution path into sub - problems, and perform constraint solving to judge connectivity). The judgment method can be seen in Algorithm 1. If it is satisfied, it is considered to have a re - entry vulnerability, and according to the function signature information in the constraint conditions on the path, record the function pairs <main re - entry function, re - entered function> corresponding to the main re - entry path and the re - entered path, as well as information such as the ID of the main re - entry path and the instruction numbers related to the re - entry vulnerability (such as the external call instruction CALL, the state - modifying instruction SSTORE, the log - recording instruction LOG). When the detection result is that there is a re - entry vulnerability, calculate the re - entry vulnerability repair test case, that is, perform step 32).

[0015] 3) The detection and repair system generates semantically equivalent test cases and vulnerability repair test cases for the source code.

[0016] 31) Semantic equivalence test cases: Receive the calculation request of semantic equivalence test cases generated during single reentry path detection. In a subprocess, use the Z3 constraint solver to calculate and solve for the variable values required for the test cases according to the conditional constraints in the calculation request, forming a list of state initialization numerical values corresponding to the function under test, a list of input parameters for function calls under test, and a list of states to be compared after the function under test runs.

[0017] 32) Vulnerability repair test cases: Use the Z3 constraint solver to calculate and solve for the variable values required for the test cases according to the conditional constraints of the main reentry path and the reentered path in the detection result.

[0018] 33) After the repair is completed, that is, after step 4), based on the list of test case variable values obtained in 31) and 32), generate Solidity code for test cases that can run in Truffle based on the test case template. The template contains 4 parts for each test case: creation of the contract before and after modification; initialization of the contract state before and after modification;

[0019] function calls of the function under test for the contract before and after modification; comparison of whether the states in the contract before and after modification are the same after the function under test runs. Without changing the semantics, fine-tune the contract before modification and the contract after modification to meet the needs of the test input. The content that needs to be fine-tuned for both the contract before modification and the contract after modification includes: adding a fallback function to the contract that lacks a fallback function; adding a state initialization function; The content that only needs to be fine-tuned in the contract after modification includes: for the contract with the same name as the contract before modification but with modified content, modify the contract name and add "_patch" at the end, and for the contract with the same name as the contract before modification but without modified content, delete it; add a reference (import statement) to the contract before modification.

[0020] 4) The detection and repair system repairs the source code containing reentry vulnerabilities. There are two repair templates in this article: a lock-based repair template and a reordering-based repair template. When applying the lock-based repair template for repair, the reordering-based repair template is not used. When applying the reordering-based repair template for repair, if semantic equivalence repair cannot be performed, the lock-based repair template is used instead. Although the lock strategy has a higher repair rate, the repair result will significantly increase the gas consumption during contract operation and increase the contract operation cost. Therefore, the present invention uses two strategies for repair.

[0021] 41) Lock-based repair template: Based on the reentry function pairs generated in 22), add function decorators to the functions in the reentry function pair <main reentry function, reentered function>. The addition principle is as follows: Find the AST node of the function according to the function name, and add the function decorator of "acquire lock - release lock" to the main reentry function; add the function decorator of "check lock occupancy" to the reentered function. The function pair number is passed as the lock number in the function decorator, and a unique lock id is assigned to each main reentry function. When a function needs to add both the "acquire lock - release lock" and "check lock occupancy" function decorators, the lock check occupancy is used as the outer function decorator. Generate a lock addition information list, which includes the function name, the type of function decorator that the function needs to add, and the lock id.

[0022] 42) Reordering-based repair template: Utilize the information such as the ID of the main reentry path and the critical instruction number generated in 22). According to the instruction number and the sourceMapping in 21), find the source code range of the statement corresponding to the critical instruction in the detection result, and then combine the AST information in 21) to find the AST node of the corresponding statement. Record the original AST number of the statement to be moved and the AST number of the destination of the move, record the AST number of the statement to be replaced and the replacement content, and record the AST number of the position corresponding to the statement to be added and the added content. Generate a reordering information list. The statement to be moved is the source code statement corresponding to the write operation (SSTORE instruction) in the RCW mode. The determination method of the move destination is as follows: Find the AST node c of the statement corresponding to the external call (CALL instruction) in the RCW mode and the AST node w of the statement corresponding to the write operation (SSTORE instruction) in the RCW mode. Use the AST structure of the source code to find the nearest common AST parent node of node c and node w. The move destination is the position immediately before the nearest common AST parent node. The statement to be replaced is the source code statement corresponding to the second read operation (SLOAD instruction) in the RCR mode, specifically the statement for reading the value of the storage variable. The added statement is a local variable declaration and initialization. The local variable name contains the name of the storage variable to be replaced, and the initialization value is the value of the storage variable to be replaced. The determination method of the position of the added statement is as follows: Find the AST node c of the statement corresponding to the external call (CALL instruction)

[0023] corresponding to the RCR mode and the AST node r of the statement corresponding to the read operation (SLOAD instruction) in the RCR mode. Use the AST structure of the source code to find the nearest common AST parent node of node c and node r. The added position is the position immediately before the nearest common AST parent node. The content of the statement to be replaced is the statement for reading the value of the added local variable.

[0024] 43) Call the open-source tool prettier-plugin-solidity to modify the source code and generate a repaired smart contract based on the lock addition information list generated in 41) and the reordering information list generated in 42).

[0025] 5) The detection and repair system verifies the test cases for the repaired contract.

[0026] Advantages of the present invention:

[0027] Based on the above detection and repair solution of the static detection and repair template, the present invention realizes sub-modules for detection, repair, test case generation, and repair result verification.

[0028] For the necessary conditions leading to the reentrancy vulnerability, the present invention summarizes two repair templates based on locks and reordering. In the verification stage, a total of 8 real contracts and example contract files containing reentrancy vulnerabilities were collected from the network to test the reentrancy vulnerability detection and repair tool proposed in this paper. The results show that the detection rate of the system for reentrancy vulnerabilities is 100%. Among them, 4 real contract files all contain RRW-Self vulnerabilities, 2 real contracts contain RRW-Cross type vulnerabilities, and 1 real contract contains RWR-Cross type vulnerabilities; for the test set in this paper, the repair rate of the system for reentrancy vulnerabilities is 100%. Without changing the original semantics, the lock template successfully repaired all vulnerabilities, and only one vulnerability could not be successfully repaired by the reordering template. This unrepaired vulnerability was successfully repaired using the lock template, demonstrating the effectiveness of the repair template and ensuring the security of smart contracts against reentrancy vulnerabilities. Description of the Drawings

[0029] Figure 1 It is a flowchart for single-path reentrancy mode detection;

[0030] Figure 2 It is a flowchart for combined-path reentrancy mode detection;

[0031] (a) Combined-path constraint solving process, (b) Total process of combined-path reentrancy detection;

[0032] Figure 3 It is a flowchart for repairing reentrancy vulnerabilities based on the lock strategy;

[0033] Figure 4 It is a flowchart for repairing reentrancy vulnerabilities based on the reordering strategy;

[0034] Figure 5 It is a flowchart for test case code generation;

[0035] Figure 6 It is a flowchart for verifying the repair result;

[0036] Figure 7 Schematic diagram for solving the sub-problem of combined reentry path division Detailed implementation method

[0037] The present invention realizes sub-modules for detection, repair, test case generation, and repair result verification. The reentry vulnerability detection module is divided into two parts: single-path reentry detection and combined reentry path detection. The reentry vulnerability repair module includes lock-based repair and reordering-based repair. In the experiment, the Solidity version is 0.5.13 and the Z3 version is 4.8.9

[0038] Single-path reentry pattern detection

[0039] The flowchart of single-path reentry pattern detection is as Figure 1 shown. To analyze cross-function reentry vulnerabilities, this paper first needs to analyze the reentry patterns on each reentry path. After constructing the CFG basic blocks and edges based on the EVM bytecode, it starts to traverse each path one by one and symbolically execute each instruction on the path. This paper uses the stain tracking technology to analyze the dependency relationship between instruction data, extracts stains before each instruction execution, and propagates stains after execution. Specifically, the SLOAD instruction is the source of stain generation. For key instructions related to reentry, a pattern judgment process is added. For example, for the contract variable modification instruction SSTORE, external call instructions (CALL, DELEGATECALL, STATICCALL), and log recording instructions (LOG0~LOG4), it is judged whether these instructions form part of the reentrant path, and the SLOAD read instructions on which these instructions depend are recorded to form the RC, RW, RL, and RJ sets, and it is judged whether these instructions form part of the RCR mode of the main reentry path. For the SSTORE instruction, it is also necessary to judge whether it forms part of the RCW mode of the main reentry path. After each path traversal is completed, if the path contains state modification nodes, semantic equivalence test case calculation is performed

[0040] Combined reentry path detection

[0041] The flowchart of combined reentry path detection is as Figure 2As shown in the figure. In this step, this paper combines the reentry modes in the main reentry path with those in the reentered path one by one to complete the judgment of cross-function reentry vulnerabilities. For each main reentry path, it is respectively judged whether it meets the RCW mode and the RCR mode. The two modes are respectively combined with the modes in the reentered path, and the conditional constraints in the combined modes are solved. The solution of conditional constraints is divided into three parts. The first part is the solution of the conditional constraints before the external call in the main reentry path and the test initial constraints. The second part is the solution of the conditional constraints on the reentered path and the constraints of the solution results of the first part. The third part is the solution of the storage variable address equality constraint, the RJ conditional constraint and the solution results constraint of the second part. When the solution sets of all three parts are not empty, this paper believes that a reentry vulnerability is formed and needs to be repaired. This paper uses the Z3 constraint solver for solving. In order to improve the success rate of solving, this paper uses a custom configuration strategy for solving, including simplify, solve-eqs, bit-blast, aig, sat.

[0042] Reentry Vulnerability Repair Based on Lock Strategy

[0043] The reentry vulnerability repair process based on the lock strategy is as follows Figure 3 As shown in the figure. Adding a lock does not affect the reading and writing of existing data values within a function, but it will affect the executability of the function, that is, when there is a nested call relationship between the main reentry function and the reentered function itself. Therefore, the semantic equivalence check content for the lock strategy is to check whether there is a nested call relationship between the functions where the lock is about to be added. If there is, the semantic equivalence repair cannot be completed. If not, the repair steps are as follows: Add a function decorator of "acquire lock - release lock" to the main reentry function, and add a function decorator of "check lock occupancy" to the reentered function paired with this main reentry function, and use the same lock number. The lock information is recorded in a key-value pair with the function signature as the key and the function decorator type and lock ID as the values. When generating the repaired source code, first read the function decorator template, replace the parameters in the decorator template with the lock ID, then find the AST node of the corresponding function according to the function signature, and add the function decorator with the modified lock ID under the modifiers attribute of the AST node. After all function AST modifications and additions are completed, use prettier-plugin-solidity to generate the repaired code.

[0044] Reentry Vulnerability Repair Based on Reordering Strategy

[0045] The flowchart of the reentry vulnerability repair based on the reordering strategy is as follows Figure 4As shown below. It is divided into two steps: RCW repair information generation and RCR repair information generation. For RCW type reentrancy vulnerabilities, a statement rearrangement sequence list will be generated during detection. According to the SSTORE instruction and the external call instruction number that cause the reentrancy vulnerability, through the mapping relationship between the instruction and the source code in the source mapping and the mapping relationship between the source code and the AST nodes in the AST, find the AST nodes corresponding to the statements (statement type) of the instruction, and record the information of the parent nodes on the path of the AST nodes in the abstract syntax tree. The write statement AST is the starting position of the movement, and the external call statement is the ending position of the movement.

[0046] Semantic equivalence detection during statement movement needs to check whether the affected subgraph in the contract CFG after movement contains read and write nodes. The source point of the affected subgraph is the node corresponding to the first instruction in the external call AST, and the end point is the node corresponding to the last instruction in the write statement AST. When the affected subgraph contains neither read nodes nor write nodes, the semantics will not change and no semantic equivalence maintenance is required. When the affected subgraph contains write nodes, it will cause a semantic change. In this case, this paper switches to using the lock strategy for repair. When the affected subgraph contains only read nodes, it will cause a semantic change. In this case, this paper replaces the storage variables corresponding to these read nodes with local variables. The initialization of the local variables is added immediately before the write statement after movement, and the AST position of the replaced variable and the replaced content are recorded, and the position and initial value of the newly added local variable initialization are recorded.

[0047] For RCR type reentrancy vulnerabilities, a statement replacement list will be generated during detection. Replace the storage variable corresponding to the second read node in the RCR with a local variable. The local variable initialization statement is added immediately before the external call statement. During semantic equivalence detection, the source point of the affected subgraph is the node corresponding to the first instruction in the external call AST, and the end point of the subgraph is the node corresponding to the last instruction in the replaced read statement AST. If the subgraph contains write nodes, it will cause a semantic change. In this case, this paper switches to using the lock strategy for repair.

[0048] When generating the repaired source code, read the reordering statement list and the replacement statement list and modify the AST: For the movement statement operation, copy the content of the movement statement AST and add it to the position after movement; for the replacement statement operation, first create a local variable initialization statement AST according to the template, then replace the original storage variable AST with the local variable AST, and then add the local variable initialization AST to the function AST. After all the function AST modifications and additions are completed, use prettier - plugin - solidity to generate the repaired code.

[0049] Test case code generation

[0050] The test case code generation process is as follows Figure 5 shown. The module first receives a test case generation request during the detection process, and uses the Z3 constraint solver to calculate the test case parameters, forming a JSON format file. Then it reads the Solidity template of the test case, fills in the test data in the JSON file, and implements the logic of creating the contract to be tested, running the function to be tested, and comparing the running results. For the contract to be tested, since the variable values need to be read during the comparison stage, a variable value reading function needs to be added to the contract to be tested; since the contract consumes gas during operation, a small amount of Ether needs to be passed in when creating the contract to be tested, and a callback function also needs to be added to the contract to be tested without a callback function.

[0051] Verification of repair results

[0052] The repair result verification process is as follows Figure 6 shown. In this paper, the Truffle framework and the Ganache test network are used to complete the test. First, the original contract and the repaired contract are placed in the contract directory, and the test case code is placed in the test directory. Then the contract is deployed to the blockchain, and then the test case code is run. Finally, the Ganache running output information is viewed. If there is no error message, it means that the test case passes.

[0053] Reentry mode mapping table

[0054]

[0055]

[0056] Algorithm 1 (Algorithm for judging the read / write mode and connectivity of combined reentry paths)

[0057] The read / write mode of the reentry path in the present invention is defined as follows:

[0058] 1) In the RCW reentry mode: the main reentry mode is RCW, the reentrant mode is any one of RC / RW / RL / RJ, and the read operation R and write operation W in the main reentry mode correspond to the same storage variables as the read operation R in the reentrant mode.

[0059] 2) In the RCR reentry mode: the main reentry mode is RCR, the reentrant mode is any one of RC / RW / RL / RJ, and the two read operations R in the main reentry mode correspond to the same storage variables as the read operation R in the reentrant mode.

[0060] The algorithm for judging the read / write mode and connectivity of combined reentry paths is as follows:

[0061] The combined path is divided into three segments for solution: The first part is from the starting point of the main re - entry path to before the external call. The solution parameters are the conditional constraints on the path, the initial state before the path execution (empty set), and the write operation records in the path. The second part is the re - entered path. The solution parameters are the conditional constraints on the path, the initial state before the path execution (the state before the external call of the main re - entry path), and the write operation records in the path. The third part is from after the external call of the main re - entry path to the end point. The solution parameters are the conditional constraints for the consistency of read - write variables in the main re - entry path and the re - entered path and the conditional constraints of RJ, the initial state before the path execution (the state after the re - entered path execution), and the write operation records (empty set). If the solution of any one of the three segments fails, it is considered that there is no re - entry vulnerability. If the solutions of all three path segments are successful, it is considered that there is a re - entry vulnerability.

[0062] The solution idea for each path segment is to divide the conditional constraints on the path according to the write operations on the path. If any sub - problem has no solution, an empty set is returned. First, all write operations are divided according to the storage variable names. There may be one or more write operations under each storage variable. Then, according to each storage variable, the conditional constraints are divided into sub - problems in turn. The division process is as Figure 7 shown. The example in the figure includes one initial state (the value of c is 3), three conditional constraints, and two write operations (assigning 1 to variable a and assigning 2 to variable b). The values of variables a and b in the conditional constraints depend on the two write operations. First, the conditional constraints are divided into conditional constraints dependent on a and conditional constraints independent of a according to variable a, and then divided according to variable b, resulting in four sub - problems, which are solved using the Z3 constraint solver. In this example, all four sub - problems have solutions, so the solution of this path is successful.

[0063] The above embodiments are only used to illustrate the technical solutions of the present invention and are not intended to limit them. Those of ordinary skill in the art can modify the technical solutions of the present invention or make equivalent replacements without departing from the spirit and scope of the present invention. The protection scope of the present invention shall be subject to what is described in the claims.

Claims

1. A method for detecting a re - entry vulnerability, the steps of which include: The detection and repair system first performs single re - entry path detection on the source code of the smart contract to be processed, and then performs combined re - entry path detection; Among them, the single re - entry path detection method is as follows: First, compile the source code of the smart contract to generate Ethereum Virtual Machine bytecode, Application Binary Interface, source code mapping, and Abstract Syntax Tree (AST). Then, use the Z3 constraint solver to traverse the Ethereum Virtual Machine bytecode to obtain the execution path of the source code of the smart contract and generate a control flow graph. During the traversal process, identify the re - entry mode of the path according to the re - entry mode mapping table, and record the main re - entry path mode and the re - entered path mode in units of paths. The re - entry mode mapping table records the key instructions corresponding to each main re - entry mode and re - entered mode. After each path traversal is completed, if the path contains a state modification node, generate a semantically equivalent test case for this path. Among them, the combined re - entry path detection method is as follows: First, de - duplicate the paths with the same path conditions in the main re - entry path mode. Then, traverse the main re - entry paths, combine each main re - entry path with each re - entered path pairwise, and use the Z3 constraint solver and stain tracking technology to determine whether each combined path meets the connectivity and re - entry vulnerability read - write mode. If it meets, it is considered that there is a re - entry vulnerability in the source code of the smart contract.

2. The method according to claim 1, wherein When it is considered that there is a re - entry vulnerability in the source code of the smart contract, according to the function signature information in the constraint conditions on the path, record the function pair <main re - entry function, re - entered function> corresponding to the main re - entry path and the re - entered path in this combined re - entry path, as well as the ID of the main re - entry path and the instruction number related to the re - entry vulnerability.

3. A method for detecting and repairing re - entry vulnerabilities, the steps of which include: 1) Input the source code of the smart contract to be processed into the detection and repair system; 2) The detection and repair system first performs single re - entry path detection on the source code of the smart contract to be detected, and then performs combined re - entry path detection; The single re - entry path detection method is as follows: First, compile the smart contract source code to generate Ethereum Virtual Machine bytecode, Application Binary Interface, source code mapping, and Abstract Syntax Tree (AST). Then, use the Z3 constraint solver to traverse the Ethereum Virtual Machine bytecode to obtain the execution path of the smart contract source code and generate a control flow graph. During the traversal process, identify the re - entry mode of the path according to the re - entry mode mapping table, and record the main re - entry path mode and the re - entered path mode in units of paths. The re - entry mode mapping table records the key instructions corresponding to each main re - entry mode and re - entered mode. After each path traversal is completed, if the path contains a state - modifying node, generate a semantically equivalent test case for this path. The combined re - entry path detection method is as follows: First, remove duplicates from the paths with the same path conditions in the main re - entry path mode. Then, traverse the main re - entry paths, combine each main re - entry path with each re - entered path pairwise, and use the Z3 constraint solver and stain - tracking technology to determine whether each combined path meets the connectivity and re - entry vulnerability read - write mode. If it meets the conditions, it is considered to have a re - entry vulnerability. According to the function signature information in the constraint conditions on the path, record the function pair <main re - entry function, re - entered function> corresponding to the main re - entry path and the re - entered path in this combined re - entry path, the ID of the main re - entry path, and the instruction number related to the re - entry vulnerability, and generate a re - entry vulnerability repair test case for this combined re - entry path; 3) According to the detection result, if the smart contract source code contains a re - entry vulnerability, the detection and repair system repairs the smart contract source code to obtain the repaired smart contract; 4) The detection and repair system verifies the repaired smart contract using the semantically equivalent test case and the re - entry vulnerability repair test case.

4. The method according to claim 3, wherein The detection and repair system repairs the source code of the smart contract, including a lock-based repair template and a reordering-based repair template. Among them, for the lock-based repair template, according to the reentry function <main reentry function, reentered function>, function decorators are added to the functions to be repaired. The addition principle is as follows: find the AST node of the function from the abstract syntax tree AST according to the function name, add a "lock acquisition - lock release" function decorator to the main reentry function; add a "lock occupancy check" function decorator to the reentered function; the function number passed in the function decorator is used as the lock number, and each main reentry function is assigned a unique lock id. When a function needs to add both a "lock acquisition - lock release" and a "lock occupancy check" function decorator, the lock occupancy check is used as the outer function decorator. Then, a lock addition information list is generated, which includes the function name, the type of function decorator that the function needs to add, and the lock id. For the reordering-based repair template, the source code range of the corresponding statement is found according to the instruction number related to the reentry vulnerability and the source code mapping, and then the AST node of the corresponding statement is found in combination with the abstract syntax tree AST. Record the original AST number of the statement to be moved and the AST number of the destination of the move, record the AST number of the statement to be replaced and the replacement content, record the AST number of the position corresponding to the statement to be added and the added content, and generate a reordering information list. Then, according to the generated lock addition information list and the reordering information list, modify the source code of the smart contract to generate a repaired smart contract.

5. The method according to claim 3, wherein The method for generating semantic equivalence test cases is as follows: Use the Z3 constraint solver to calculate and solve the variable values required for semantic equivalence test cases according to the conditional constraints in the path, and then generate semantic equivalence test cases based on the variable values required for the semantic equivalence test cases, and form a list of state initialization numerical values corresponding to the function to be tested, a list of input parameters for the function call to be tested, and a list of states that need to be compared after the function to be tested runs.

6. The method according to claim 3, characterized in that The method for generating reentry vulnerability repair test cases: Use the Z3 constraint solver to calculate and solve the variable values required for reentry vulnerability repair test cases according to the conditional constraints of the main reentry path and the reentered path in the detection results, and then generate reentry vulnerability repair test cases based on the variable values required for the reentry vulnerability repair test cases.

7. A detection and repair system for re - entry vulnerabilities, characterized in that, It includes a single-path reentry mode detection module, a combined reentry path detection module, a reentry vulnerability repair module, a test case code generation module, and a repair result verification module; Among them A single-path reentry pattern detection module is used to compile the source code of the smart contract to be processed and generate Ethereum Virtual Machine bytecode, Application Binary Interface, source code mapping, and Abstract Syntax Tree (AST). Then, the Z3 constraint solver is used to traverse the Ethereum Virtual Machine bytecode to obtain the execution path of the smart contract source code and generate a control flow graph. During the traversal process, the reentry pattern of the path is identified according to the reentry pattern mapping table, and the main reentry path pattern and the reentered path pattern are recorded in units of paths. Each main reentry pattern and the corresponding key instructions for the reentered pattern are recorded in the reentry pattern mapping table. After each path traversal is completed, if the path contains a state modification node, a semantically equivalent test case is generated for this path; A combined reentry path detection module is used to remove duplicates from paths with the same path conditions in the main reentry path pattern, and then traverse the main reentry paths. Each main reentry path is combined with each reentered path pairwise, and the Z3 constraint solver and stain tracking technology are used to determine whether each combined path meets the connectivity and reentry vulnerability read-write mode. If it meets the conditions, it is considered that there is a reentry vulnerability in the smart contract source code; A test case code generation module is used to generate a semantically equivalent test case for a path containing a state modification node, and generate a reentry vulnerability repair test case for a combined reentry path with a reentry vulnerability; A reentry vulnerability repair module is used to repair the smart contract source code containing a reentry vulnerability to obtain a repaired smart contract; A repair result verification module is used to verify the repaired smart contract using semantically equivalent test cases and reentry vulnerability repair test cases.

8. The system according to claim 7, wherein The reentry vulnerability repair module includes a lock-based repair template and a reordering-based repair template; among them, the lock-based repair template is used to add function decorators to the functions to be repaired according to the reentry function <main reentry function, reentered function>. The addition principle is as follows: find the AST node of the function from the abstract syntax tree AST according to the function name, and add a "lock acquisition - lock release" function decorator to the main reentry function; add a "lock occupancy check" function decorator to the reentered function; the function number is passed into the function decorator as the lock number, and a unique lock id is assigned to each main reentry function. When a function needs to add both a "lock acquisition - lock release" and a "lock occupancy check" function decorator, the lock occupancy check is used as the outer function decorator; then generate a lock addition information list, which includes the function name, the type of function decorator that the function needs to add, and the lock id; the reordering-based repair template is used to find the source code range of the corresponding statement according to the instruction number related to the reentry vulnerability and the source code mapping, and then find the AST node of the corresponding statement in combination with the abstract syntax tree AST, record the original AST number of the statement to be moved and the AST number of the destination of the move, record the AST number of the statement to be replaced and the replacement content, record the AST number of the position corresponding to the statement to be added and the added content, and generate a reordering information list; then modify the source code of the smart contract according to the generated lock addition information list and the reordering information list to generate a repaired smart contract.

9. The system according to claim 7 or 8, characterized in that, The method for the test case code generation module to generate semantically equivalent test cases is as follows: use the Z3 constraint solver to calculate and solve the variable values required for semantically equivalent test cases according to the conditional constraints in the path, and then generate semantically equivalent test cases based on the variable values required for semantically equivalent test cases, and form a list of state initialization numerical values corresponding to the function to be tested, a list of input parameters for the function call to be tested, and a list of states to be compared after the function to be tested runs.

10. The system according to claim 7 or 8, characterized in that, The method for the test case code generation module to generate reentry vulnerability repair test cases is as follows: use the Z3 constraint solver to calculate and solve the variable values required for reentry vulnerability repair test cases according to the conditional constraints of the main reentry path and the reentered path in the detection results, and then generate reentry vulnerability repair test cases based on the variable values required for reentry vulnerability repair test cases.

Citation Information

Patent Citations

  • Intelligent contract reentry vulnerability detection method based on abstract syntax tree

    CN110162474A

  • Intelligent contract security vulnerability detection method based on machine learning

    CN110737899A