Messi-Q/SmartContracts

Cross-function Reentrancy Vulnerability In Ethereum Smart Contracts

Closed this issue · 0 comments

Reentrancy_cross_function.sol

Vulnerability Type

Cross Function Reentrancy Bug

Abstract

For this contract, we present a complex but common cross-function attack scenario, exploiting the reentrancy vulnerability. This contract Vulnerable has a function withdraw that can transfer Ether to a user's address. The fallback function hidden in the contract Attacker will be invoked automatically when receiving the transferred Ether. Specifically, there is a cross-function mechanism, which exploits the intermediary to steal money.

Details

At first, the contract Attacker calls the function getBonus to obtain the bonus in the function attack of Vulnerable, aiming to initiates the attack.

# initial attack function
function attack(){
    vul.getBonus(_owner);
}

Due to the operation of getting a bonus, the function getBonus involves the transfer operation (i.e., recipient.call.value(amountToWithdraw)() == false), which will automatically trigger the fallback function of Attacker.

# getBonus function
function getBonus(address recipient) public {
      uint amountToWithdraw = rewardsForA[recipient];
      rewardsForA[recipient] = 0;
      if (recipient.call.value(amountToWithdraw)() == false) {
              throw;
      }
      totalbalance -= amountToWithdraw;
}

Then, the fallback function of contract Attacker maliciously invokes the function withdraw to withdraw its Ether.

# fallback function
function () payable{
     count++;
     if(count<10){
       vul.withdraw(1 ether);
     }
}

# withdraw function
function withdraw(unit _amount) public {   
    msg.sender.call.value(_amount)();
    balances[msg.sender] -=_amount;
    totalbalance -= _amount;
}

However, the function withdraw also trigger the fallback function, which causes the recursive calls. By exploiting the reentrant call, the Attacker can access to the contract Vulnerable to steal Ether until all its Ether is exhausted.

We show that a vivid picture is described as cross-function.pdf

Specific Attack Procedures

First step: attack (Attacker) -> getBonus (Vulnerable);
Second step: withdraw (Vulnerable) -> fallback (Attacker) (Automatically triggered)
Third step: fallback (Attacker) -> withdraw (Vulnerable)
Fourth step: withdraw (Vulnerable) -> fallback (Attacker) -> withdraw (Vulnerable)
......

Conclusion

All in all, this cross-function reentrancy attack is possible when a vulnerable function shares the state with another function that has a desirable effect on the attacker. This reentrancy situation is not uncommon, that is, the use of intermediate functions to trigger the fallback function and a reentrancy attack.

Reference

https://hackernoon.com/smart-contract-attacks-part-1-3-attacks-we-should-all-learn-from-the-dao-909ae4483f0a
https://consensys.github.io/smart-contract-best-practices/known_attacks/