The Reentrancy Attack is a very dangerous vulnerability in smart contracts where an attacker exploits a recursive call of a contract (before its previous transaction is fully executed). Essentially, a function of the contract is exploited that makes external calls to other contracts but does not immediately update the state of the contract before completing these external calls. The attacker calls the same function multiple times (in a recursive, loop-like fashion) before the smart contract can update its state, thus performing multiple withdrawals (or operations that should not be possible).
METHODS OF ATTACK
The contract has a function that allows users to withdraw funds (e.g., a withdraw function), based on their balance. The contract makes an external call to transfer funds to another address (e.g., using the call or send function). The state of the contract is not updated immediately: the external call happens, allowing the attacker to perform other actions before the balance is reduced. The attacker, with the ability to use an external call, re-executes the withdraw function, causing multiple withdrawals before the balance is updated.
If we consider a wallet smart contract that allows users to deposit and withdraw funds, an attacker can exploit this contract using this recursive function. Users can deposit funds into the contract and withdraw them via the withdraw function, which sends the funds to the user and then updates the user's balance. The attacker creates a contract that exploits the withdraw function to call it multiple times. The attacker calls the attack function in the malicious contract, depositing funds into the vulnerable contract. The vulnerable contract's withdraw function sends the funds to the attacker's address, and the attacker can make another recursive call to withdraw before the balance is updated.
This allows the attacker to repeat the operation multiple times, withdrawing multiples of the funds in his or her balance. Each time the attacker calls the withdraw function, the vulnerable contract has not yet updated the attacker's balance. This allows the attacker to withdraw more funds than were actually deposited. Suppose you deposit 3 ETH into the contract, when the attacker calls the withdraw function for the first time, he receives 3 ETH but the contract state is not updated yet. The attacker recursively calls withdraw and receives another 3 ETH and so on. Each call cycle drains funds from the contract (of other users), which fails to properly update the attacker's balance in real time.
PREVENTING THESE ATTACKS
To prevent these dangerous attacks, the basic rule is to update the contract state before making any external calls i.e. just move the row that updates the user's balance before the external call. Check functions check the conditions (for example, if the user has enough balance).
Are you interested in ways to earn crypto bonus? Check it out here: Some Sites To Earn Crypto Bonus (Old & New)