Reentracy attack

From DefiLlama
Revision as of 18:54, 7 May 2022 by Eru (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

A reentrancy attack occurs when a function makes an external call to another untrusted contract. Then the untrusted contract makes a call back to the original function in an attempt to drain funds.

If a contract uses call, send or transfer which may cause control flow to an external contract, with a fallback function, and then updates the state afterward then this causes the state of the contract to be incomplete when flow control is transferred. Therefore, when this fallback function is triggered, the flow of control may not return as the called contract expects and the caller might do any number of unexpected things such as calling the function again, calling another function or even calling another contract.

At it’s core a reentrancy vulnerability is an unsafe external call and occurs with contract A calls contract B, and contract B calls contract A, when A still has not updated its state.

Reentracy vulnerabilities violate the “checks -> Interaction —> Effects” pattern. That is, functions which call external contracts should execute in the following order:

1. Checks -First perform some checks (who called the function, are the arguments in range, did they send enough Ether, does the person have tokens, etc.).

2. Effects -As the second step, if all checks passed, effects to the state variables of the current contract should be made. This updates the contract state

3. Interaction - Interaction with other contracts should be the very last step in any function.

To illustrate the above consider a smart contract with only two (2) functions as follows:

deposit() - Increases a user’s balance; withdraw() - Checks a user’s balance, makes transfers, and then updates the users balance.

The contract is vulnerable to reentrancy attacks as a malicious attacker can prepare a contract that can recursively call the withdraw function before the balance is updated.