skka3134

skka3134

email
telegram

Smart Contract Security: 5.selfdestruct

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 its selfdestruct function. 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:

  • Implement access control for the selfdestruct function and only allow the owner to call it.
  • Avoid setting a publicly callable selfdestruct function to prevent malicious contract inheritance.
  • Set dangerous functions as internal functions.
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.