Common vulnerabilities
Most real hacks come from a small set of mistakes. Learning to spot them is the fastest way to write safer code. This lesson covers the ones you will meet most often.
Reentrancy lets a receiver call back into your contract before your state is updated. You saw it in the Ether module. Fix it with checks-effects-interactions and a reentrancy guard.
Missing access control is the simplest bug and one of the most costly. A function that changes ownership or moves funds must check msg.sender. Never use tx.origin for this: it is the wallet that started the whole call chain, so a malicious contract can trick a user into starting a call that passes the check.
Unchecked external calls ignore the success flag returned by call, so a failed transfer looks like it worked. Always check the result. Weak randomness is another trap: block.timestamp, blockhash and similar values can be influenced by validators, so never use them to pick winners. Use a verifiable randomness service instead.
Front-running means anyone can see pending transactions and pay more gas to be included first, so do not rely on secrets or transaction order for fairness. Finally, do not trust inputs: validate addresses, amounts and array lengths, and remember that anything stored on-chain, even a private variable, can be read by anyone.
// BAD: tx.origin can be abused by a phishing contract contract TxOriginWallet { address public owner = msg.sender; function sendTo(address payable to, uint256 amount) external { require(tx.origin == owner, "Not owner"); (bool ok, ) = to.call{value: amount}(""); require(ok, "Failed"); } receive() external payable {} } // GOOD: msg.sender is the direct caller contract SafeWallet { address public owner = msg.sender; function sendTo(address payable to, uint256 amount) external { require(msg.sender == owner, "Not owner"); (bool ok, ) = to.call{value: amount}(""); require(ok, "Failed"); } receive() external payable {} } // The trick: the real owner is lured into calling this contract contract Phisher { TxOriginWallet public victim; address payable public attacker; constructor(TxOriginWallet w) { victim = w; attacker = payable(msg.sender); } function claimPrize() external { victim.sendTo(attacker, address(victim).balance); } }
Try it yourself
In Remix on a test network, deploy TxOriginWallet and Phisher, send the wallet some test ETH, then call claimPrize from the wallet owner's account. Next, change the check to msg.sender and see the attack fail.
Press Compile to check your code in the browser. Short fragments are wrapped in a contract automatically.