The withdraw function in the given contract is vulnerable to a reentrancy attack. This vulnerability allows an attacker to recursively call the withdraw function before the initial function execution completes, potentially draining the contract of its funds.
A reentrancy attack occurs when a contract calls an external contract before it updates its state. This allows the external contract to make a recursive call back to the original function, potentially exploiting the contract's state before it is updated. In this case, the vulnerability is present in the withdraw function of the contract.
An attacker can drain the contract’s funds by repeatedly calling the withdraw function before the state is updated, leading to significant financial loss.
Manual analysis
To mitigate the reentrancy attack, follow these recommendations:
1.Update State Before External Call:
Ensure the contract updates its state before making any external calls. This prevents reentrancy because the contract's state is modified before the external call is made.
2.Use Mutex/Guard:
Implement a guard to prevent reentrancy. One common pattern is to use a reentrancyGuard modifier that prevents a function from being called while it is already executing.
3.Solution Implementation
Below is the revised withdraw function implementing both recommendations:
// Adding a reentrancy guard modifier
bool private locked;
modifier noReentrant() {
require(!locked, "No reentrancy");
locked = true;
_;
locked = false;
}
function withdraw() public RamIsSelected OnlyRam RavanKilled noReentrant {
if (totalAmountGivenToRam == 0) {
revert Dussehra__AlreadyClaimedAmount();
}
uint256 amount = totalAmountGivenToRam;
// Update state before external call
totalAmountGivenToRam = 0;
(bool success, ) = msg.sender.call{value: amount}("");
require(success, "Failed to send money to Ram");
}
The `withdraw` function sends the given amount to Ram. If the attacker calls the `withdraw` function again before the state variable is changed, the function will revert because there are no more funds in the contract. This reentrancy has no impact for the protocol. It is recommended to follow the CEI pattern, but this is informational.
The contest is live. Earn rewards by submitting a finding.
This is your time to appeal against judgements on your submissions.
Appeals are being carefully reviewed by our judges.