SharkTeam: Top 10 Smart Contract Security Threats of Reentrancy Attacks

SharkTeam
9 min readSep 6, 2022

Q: Are the smart contract vulnerabilities we often mention really the most threatening and frequent security breaches in practice?

A: Not at all. For example, “overflow”, “external call” and other commonly mentioned smart contract security vulnerabilities are not the most frequent and most threatening.

What are the top 10 security threats in terms of frequency of occurrence and harm? Lesson 1 [Explaining Reentrancy Attacks].

I. What is a reentrancy attack

A computer program or subroutine that is interrupted during execution and then called again before its previous call completes execution is called a re-entrant program. An interruption may be caused by an internal operation (such as a jump or call) or an external operation (such as an interrupt or signal). Once the re-entrant call has completed, the previous call will resume normal execution. Performing this operation with certain code segments will result in a reentrant attack.

In an Ethereum smart contract, the contract can call and make use of code from other external contracts. Contracts can perform calls to other contracts during normal execution by executing function calls or simply transferring Ether. These external calls can be hijacked by an attacker to force the contract to execute the next code step (i.e. via the fallback function), including the callback itself. In this case, we can say that the contract has been reentered.

Types of reentrant attacks can be classified as.

(1) Single function re-entry

(2) Cross-function reentry

(3) Cross-contract reentry

1.1 Single Function Reentry

A single function reentry attack occurs when a vulnerable function is the same function that the attacker is trying to call recursively.

In this example, the funds transfer is made in the comment (1) section before the comment (2) account balance status is modified. This would then allow the hacker to use the fallback() function to call the function multiple times before the status is modified until the entire balance in the contract account is taken.

1.2 Cross-Function Reentry

Cross-function reentry occurs when a vulnerable function shares state with a function that can be exploited by an attacker.

In this example the hacker can manipulate the contract using fallback(), an external call to the transfer() function, to transfer funds before the contract balance status is set to 0. Although the contract can receive withdrawals, it can also transfer funds.

Cross-functional reentrancy and single-functional reentrancy can occur in the same contract, or not in the same contract, and reentrancy can occur across multiple contracts, that is, multiple contracts sharing the same state.

1.3 Cross-contract re-entry

Cross-contract re-entry may occur when a state in one contract is used in another contract, but is not fully updated before being invoked.

The following conditions are required for a cross-contract re-entry.

(1) state in one contract is shared or used in another contract

(2) An attacker can manipulate the state of the contract by exploiting the execution flow

II. Analysis of reentrancy attacks

Reentrancy attacks are one of the most common attacks on smart contracts this has been seen in many previous attacks.

The DeFi project XSURGE on BSC suffered a lightning loan attack on August 17, 2021. On 16 August local time, XSURGE officials had released a statement prior to the attack about the SurgeBNB vulnerability, which could not be patched as the SurgeBNB contract was immutable and abandoned. XSURGE said it did not disclose any specific details about the nature of the vulnerability, but strongly advised users to migrate out of SurgereBnb as soon as possible, as the vulnerability could at any time could be triggered by an attacker at any time. Following the statement, XSURGE was subsequently attacked and the attackers stole $5 million from SurgeBNB.

This attack transaction hash: 0x7e2a6ec08464e8e0118368cb933dc64ed9ce36445ecf9c49cacb970ea78531d2

The attack process is as follows.

(1) First the attacking contract borrows 10,000 BNB from PancakeSwap via a lightning loan

(2) The attack contract uses the 10,000 BNB to buy SURGE, sells the bought BURGE and calls the sell function in the BurgeToken contract. At the time of the BNB transfer, the attack contract again transfers the received BNB to the BurgeToken contract, triggering the purchase of BURGE again. Based on the code of the sell function and the receive function of the BurgeToken contract, it is indeed possible that the transfer occurs during the sell process and then the BURGE is purchased again before the sell function has modified the state variable.

(3) The PURCHASE function is reinserted in the SELL function, and in the reinserted PURCHASE function, _totalSupply does not subtract the amount of BNB sold in the SELL function, causing more SURGE to be available for purchase.

(4) The attacker contract acquired a whopping 3,896,288,852,239,440,000 BURGE, which was converted into BNB with 22,191 BNB, repaid the lightning loan and the fee of 10,030 BNB, and the remaining 12,161 BNB was the profit gained by the attacker from this attack, and finally the BNB gained was transferred to the attacker’s account.

Both Hundred Finance and Agave, the lending protocols on the Gnosis chain, were hit by the lightning lending attack on 16 March 2022, including Agave, a branch of AAVE, and Hundred Finance, a branch of Compound. Losses exceeded US$11 million.

This attack transaction hash:

0x534b84f657883ddc1b66a314e8b392feb35024afdec61dfe8e7c510cfac1a098

The attack process was as follows.

(1) Borrow USDC and wXDAI from SushiSwap via Lightning Cash

(2) Pledge 1,200,000 USDC and borrow 59,999,789.075 hUSDC

(3) Continue to overborrow other tokens and repeat the same attack multiple times

(4) Return the lightning loan and complete the attack

We can see that the root cause of the attack is an overborrowing vulnerability in the contract, and by analysing the specific contract we find that there is a re-entry problem in the contract that allows the attacker to complete the attack and overborrow.

On 27 March 2022, Revest Finance was hacked. The hackers exploited a logic flaw in the Revest contract and stole nearly 7.7 million ECOs, 579 LYXe, nearly 715 million BLOCKS and over 350,000 RENAs, worth approximately $2 million. The hack was launched using funds taken from Tornado Cash, exchanging the stolen Tokens for ETH via SushiSwap and Uniswap, and finally transferring the ETH to other accounts via the Tornado Cash platform.

This attack transaction hash: 0xe0b0c2672b760bef4e2851e91c69c8c0ad135c6987bbf1f43f5846d89e691428

The attack process is as follows.

(1) First, the attacker calls the mintAddressLock function in the Revest contract through the lightning exchange function of UniswapV2

(2) The first call to the mintAddressLock function minted two Tokens with ID 1027. The second call to the mintAddressLock function minted 360,000 Tokens with ID 1028.

(3) When the _mint function was called before the mintAddressLock function completed, the attacker reentered the depositAdditionalToFNFT function [ERC1155 onERC1155Received reentered].

(4) Since the NFT nextId (i.e. FNFTHandler.fnftsCreated) casts NFT completion and updates in the mint function. Therefore, on the reentrant call to the depositAdditionalToFNFT function, the NFT Id remains 1027 and the nextId any remains 1028. furthermore, the contract does not verify that the number of Tokens for 1028 is 0 and the attacker successfully minted 1 NFT with ID 1028 again.

On July 10, 2022, Omni, a decentralized financial protocol NFT marketplace, was attacked by hackers in a lightning loan attack due to a smart contract vulnerability, depleting 1,300 ETH, or approximately $1.43 million.

This attack transaction hash:0x264e16f4862d182a6a0b74977df28a85747b6f237b5e229c9a5bbacdf499ccb4

The attack process is as follows.

(1) First, the attacker makes a lightning loan of 1000 ETH through the Balancer lending platform

(2) through the function flashLoan lightning loan 20 DOODLE

(3) Redeemed 1 DOODLE through the SushiSwap platform using WETH

(4) Redeemed 20 NFTs with tokenId = 2574, 2595, 6851, 8522, 8883, ……

(5) Pledge NFT (supplyERC721), tokenId = 5251, 4777, 3693, then mint nDOODLE

(6) Borrow WETH (borrow), quantity is 12.15 ETH

(7) withdraw 2 of the 3 NFTs pledged, tokenId = 5251, 4777

(8) Destroy the nDOODLE minted when the pledged NFTs are destroyed, then call the safeTransferFrom function to transfer the pledged NFTs to the attack contract, and the attacker launches a re-entry attack using the onERC721Received function

(9) Two of the three pledged NFTs are withdrawn, leaving one NFT with tokenID = 3693, at which point the pledged position is pledged and the attacker implements a self-liquidation in the re-entry attack, setting the debit to false after the liquidation is complete.

(10) A re-entry occurs again when the remaining NFTs are transferred, this time the attacker pledges all 20 NFTs and then mint nDOODLE, which is used as collateral to borrow 81 WETH. finally, all 20 NFTs are extracted.

(11) Repeating the above operations of pledging, minting and destroying, the attacker finally made a profit of 148.8 ETH.

The reentry vulnerability in this incident was caused by the safeTransferFrom function calling the onERC721Received function. The attacker used the vulnerability to launch a re-entry attack and eventually made a profit.

Having reviewed so many re-entry attacks, one can imagine how common re-entry vulnerabilities are in smart contracts.

“At the 2022 China International Finance Annual Forum held in Beijing on 2 September 2022, Mu Changchun, Director of the Institute of Digital Currency of the People’s Bank of China, delivered a keynote speech on “Smart Contracts and the Digital RMB”. Mu Changchun said that smart contracts for digital RMB are widely used in a wide range of scenarios, which can reduce the cost of performance in economic activities, optimize the business environment and promote the deepening development of the digital economy. Thanks to the trustworthiness and interoperability of smart contracts, they can better support the digital economy.

With the promotion of smart contracts and digital RMB on one side and frequent contract security issues on the other, what effective preventive measures should we take to avoid losses and ensure security?

III. Preventive measures

(1) For single function reentrancy and cross-function reentrancy, a mutually exclusive lock can be implemented in the contract and used to prevent repeated calls to functions in the same contract, thus preventing reentrancy. A widely used method of implementing locks is to inherit OpenZeppelin’s ReentrancyGuard and use the nonReentrant modifier.

(2) Check and try to update all states before calling an external contract or the so-called “check-validate-interact” mode. This will have no effect even if it is reentered, as all states are already updated

(3) Preventing attackers from exploiting the control flow of a contract. Setting up a set of whitelisted addresses can prevent an attacker from injecting unknown malicious contracts into the contract

(4) Use pull-payment, which achieves security by sending funds through an intermediary escrow and avoiding direct contact with potentially hostile contracts, such as OpenZeppelin’s PullPayment, which is a simple implementation of the pull-payment strategy

(5) Gas restrictions can prevent re-entry attacks, but this should not be considered a security strategy, as the cost of gas depends on Ethernet opcodes, which are subject to change. On the other hand smart contract code is immutable. In any case it is necessary to understand the difference between these functions: send, transfer and call. the functions of send and transfer are essentially the same, but if the transaction fails, transfer will recover, while send will not. With regard to re-entry, both send and transfer have a gas limit of 2300 units. Using these functions should prevent a reentrant attack from occurring, as this is not enough to recursively call back the source function to exploit the funds

(6) Using an automated smart contract audit scanning tool or requiring the help of a specialist third party audit team can also help detect re-entry errors.

About Us

Our vision is to improve security globally. We believe that by building this security barrier, we can significantly improve lives around the world.SharkTeam composes of members with many years of cyber security experiences and blockchain, team members are based in Suzhou, Beijing, Nanjing and Silicon Valley, proficient in the underlying theories of blockchain and smart contracts, and we provide comprehensive services including threat modeling, smart contract auditing, emergency response, etc. SharkTeam has established strategic and long-term cooperations with key players in many areas of the blockchain ecosystem, such as Huobi Global, OKX, polygon, Polkadot, imToken, ChainIDE, etc

--

--

SharkTeam

The world’s leading Web3 security service provider. Offer smart contract audit, chain analytics and emergency response services.