The selfdestruct function is a potentially dangerous feature of smart contracts, which hackers can exploit for malicious attacks. This article will analyze the selfdestruct attack method through code examples and discuss how to prevent such attacks through secure coding.
Attackers can destroy a contract by calling the selfdestruct function of the target contract. For example:
contract Target {
address owner;
function selfDestruct() public {
require(msg.sender == owner);
selfdestruct(owner);
}
}
contract Attacker {
function attack(Target target) public {
target.selfDestruct();
}
}
In the above example, the attacker calls the public selfDestruct function and can delete the Target contract if they have owner permissions.
Another scenario is when attackers gain access to selfdestruct through inheritance. For example:
contract Base {
function selfDestruct() internal {
selfdestruct(msg.sender);
}
}
// Malicious inheritance
contract Attacker is Base {
function attack() public {
selfDestruct();
}
}
Solution:
Add access control to the selfdestruct function and only allow the owner to call it.
Do not set a publicly callable selfdestruct function to avoid being inherited by malicious contracts.
Set the dangerous function as an internal function.