[Solidity] Reentrancy vulnerability
Reentrancy vulnerability is a type of vulnerability that occurs when a contract calls an external contract in a way that allows the external contract to call back into the original contract before the original contract has finished executing. This can lead to unexpected and potentially malicious behavior.
The problem is the withdraw function updates balance after transfered successfully to sender. Thefore, if an attacker were to create a malicious version of the IERC20
contract that calls the withdraw
function of the Fund
contract as part of its own execution, it could potentially create an infinite loop in this step (transfering step).
Attacker’s contract will look like:
Here is a summary of how an attacker could use a malicious contract to create an infinite loop in the DepositFunds
contract:
- The attacker creates a malicious contract that calls the
withdraw
function of theDepositFunds
contract as part of its own execution. - The attacker calls the
deposit
function of theDepositFunds
contract, sending some Ether to the contract. - The attacker calls the
withdraw
function of theDepositFunds
contract using the malicious contract. - The
DepositFunds
contract calls thecall
function of the malicious contract, sending the Ether to the attacker. - The malicious contract calls the
withdraw
function of theDepositFunds
contract again as part of its own execution. - This process repeats indefinitely, creating an infinite loop.
How to prevent this type of attack
To prevent this type of attack, it is important to carefully consider the potential interactions between contracts and to ensure that any external contract calls are properly guarded against reentrancy. This can be done by marking this process is handing.
For example: