Cross Function Reentrancy

From WEB3 Vulnerapedia
Jump to navigation Jump to search

Cross-function reentrancy is a vulnerability in smart contracts within the Web3 ecosystem. It occurs when an attacker exploits the ability to re-enter a contract multiple times in a single transaction, potentially executing unintended functions and causing unexpected behaviors. Such vulnerabilities can result in the loss of assets and are a critical concern in decentralized applications (DApps). Preventing and mitigating cross-function reentrancy vulnerabilities is essential for ensuring the security and reliability of smart contracts in Web3 environments.

Background

Cross-function reentrancy attack is a more complex version of the Single Function Reentrancy. Cross-function reentrancy occurs when a vulnerable function shares state with a function that an attacker can exploit.

// UNSECURE
 function transfer(address to, uint amount) external {
   if (balances[msg.sender] >= amount) {
     balances[to] += amount;
     balances[msg.sender] -= amount;
   }
 }
 
 function withdraw() external {
   uint256 amount = balances[msg.sender];
   (bool success,) = msg.sender.call{value: balances[msg.sender]}("");
   require(success);
   balances[msg.sender] = 0;
 }

In this example, a hacker can exploit this contract by having a fallback function call transfer() to transfer spent funds before the balance is set to 0 in the withdraw() function.

Source

https://github.com/kadenzipfel/smart-contract-vulnerabilities/blob/master/vulnerabilities/reentrancy.md

https://medium.com/coinmonks/protect-your-solidity-smart-contracts-from-reentrancy-attacks-9972c3af7c21