Smart contracts make it easier to execute digital agreements, but they can introduce security risks that compromise financial transactions. The Open Worldwide Application Security Project has developed the OWASP Smart Contact Top 10 to identify today's leading vulnerabilities and their mitigations. Unchecked, these vulnerabilities potentially can drain all funds from an account, alter contract terms, crash systems, or wreak other mischief.
In this blog, we'll provide an overview of today's leading smart contract security risks and their mitigations. We'll cover:
- Reentrancy attacks
- Integer overflow and underflow
- Timestamp dependence
- Access control vulnerabilities
- Front-running attacks
- Denial of service (DoS) attacks
- Logic errors (business logic vulnerabilities)
- Insecure randomness
- Gas limit vulnerabilities
- Unchecked external calls
1. Reentrancy Attacks
Reentrancy attacks exploit coding vulnerabilities that enable external contracts to reenter functions before updating contract states.
Smart contracts that make external calls to other contracts before updating their own states face exposure to this vulnerability. External contracts can exploit this vulnerability to repeat actions such as withdrawals or introduce malicious code. For example, an external contract can use a reentrancy attack to perform repeated withdrawals and drain an account of funds.
Mitigation
- Complete state changes before calling external contracts.
- Use function modifiers to prevent reentry, such as OpenZeppelin ReentrancyGuard.
2. Integer Overflow and Underflow
This vulnerability, characteristic of blockchain virtual machines such as Ethereum Virtual Machine (EVM), occurs when a smart contract hacker introduces a value that falls outside the integer range allowed by a contract's defined fixed-size data types.
Overflows exceed maximum values, while underflows fall below them. If the integer is signed, overflow yields the maximum positive value, while for unsigned integers, underflow yields the maximum value. Integer overflows and underflows allow attackers to increase account and token amounts and make excessive withdrawals or to alter contact logic for purposes such as multiplying tokens or stealing funds.
Mitigation
- Use Solidity compiler version 0.8.0 or higher which automatically checks for overflows and underflows.
- Use the latest SafeMath libraries.
3. Timestamp Dependence
This vulnerability manipulates the block.timestamp value, which represents the timestamp recording when a block was mined.
This variable often supports time-sensitive functions such as auctions, lotteries, and token vesting. By manipulating timestamps, hackers can delay or accelerate actions, alter conditions for triggering functions, or executing actions before others. For example, a hacker could end an auction before others have a chance to bid.
Mitigation
- Use trusted external time sources or multiple time sources to ensure reliable timing.
- Add time buffers to reduce opportunities for manipulation.
4. Access Control Vulnerabilities
This vulnerability occurs when contract code fails to apply user permission levels to restrict access. Unauthorized users then can access or modify contract data or functions or steal funds or assets managed by the contract.
Mitigation
- Only allow authorized entities to call initialization functions a maximum of one time.
- Use access control patterns such as Ownable or RBAC (Role-Based Access Control) to add access control modifiers such as onlyOwner and restrict unauthorized users from gaining permission to access sensitive functions.
5. Front-running Attacks
Front-running attack vulnerabilities occur when malicious actors gain knowledge of pending transactions and leverage them for unfair advantage.
This typically occurs when attackers can see the blockchain memory pool (mempool), which stores unconfirmed data about unconfirmed transactions that have been verified by available blockchain network nodes but have yet to be approved by miners. When hackers can see mempool data, they can increase the gas fee paid to miners to ensure their transaction takes processing priority over target transactions. This can allow attackers to make victims pay more for tokens, reduce funds paid to victims, or alter token prices.
Mitigation
- Prevent front-runners from exploiting higher slippage rates by Implementing slippage restrictions between 0.1% and 5%, depending on network fees and swap size.
- Hinder attackers from anticipating and manipulating transactions by using a two-step process where users commit to an action without revealing details and disclose the exact information later.
- Prevent attackers from targeting individual trades by bundling multiple transactions together and processing them as a unit.
Intercept automated bots and scripts that might exploit front-running opportunities by deploying continuous monitoring.
6. Denial of Service (DoS) Attacks
A DoS attack targeting vulnerabilities in smart contracts to exhaust critical resources such as gas, CPU cycles, or storage.
For example, an attacker might create transactions requiring excessive gas, use reentrancy to exploit contract call sequences and access unauthorized funds, or impose gas limit constraints to consume excessive block gas. Denial of service attacks can render smart contracts unusable, trigger financial losses, and damage platform reputation.
Mitigation
- Maintain smart contract integrity and prevent undesired behavior by ensuring contracts can handle consistent failures, such as asynchronous processing of failing external calls.
- Take precautions when using calls for external calls, loops, and traversals that can trigger excessive gas consumption.
- To prevent over-authorizing single roles in contract permissions or permission loss by private key compromise, divide permissions and use multi-signature wallet management for roles with critical permissions.
7. Logic Errors (Business Logic Vulnerabilities)
Logic errors occur when smart contracts contain code that diverges from desired behavior. Depending on the nature of the error, this can cause unexpected behavior or disrupt functionality. For example, errors can trigger loss of funds or misallocation of tokens.
Mitigation
- Validate your code by writing comprehensive test cases to cover all possible business logic scenarios.
- Run comprehensive code reviews and audits to identify and fix logic errors.
- Document intended behavior for all functions and modules and confirm consistency with actual execution.
8. Insecure Randomness
This vulnerability exploits the fact that blockchain networks rely on pseudorandom numbers. Blockchain networks follow deterministic patterns, making it challenging to generate true random numbers. Additionally, complex calculations can cost excessive gas.
This allows miners to manipulate functions developers use to generate random numbers, including:
- block.timestamp, defining the current block timestamp
- blockhash(uint blockNumber), defining the hash of a given block for the last 256 blocks
- block.difficulty, defining current block difficulty
- block.number, defining the current block number.
- block.coinbase, defining the address of the current block’s miner
Attackers can exploit insecure to gain an unfair advantage in games, lotteries, random-seed generation, or other contracts dependent on random number generation. This allows attackers to win unfairly while causing other participants to lose money and sowing distrust of contract fairness.
Mitigation
- Use oracle services such as Oracalize to connect to external random number sources.
- Use the Chainlink VRF random number generator to cryptographically provide random values
Use a public-key cryptosystem such as the Signidice Algorithm to generate random numbers for contracts involving two parties - Use oracles such as BTCRelay that employ Bitcoin block hash cryptographic fingerprints when bridging Ethereum and Bitcoin, while taking steps to safeguard miner incentive issues
- Use commitment scheme cryptographic protocols to commit to values while concealing them from observers.
9. Gas Limit Vulnerabilities
This attack exploits limits on the amount of gas available to a single block.
Gas limits constrain smart contract computations per transaction. Functions exceeding block gas limits can exhaust resources and trigger transaction failure. This frequently occurs when contracts contain loops that iterate over dynamic data structures such as lists and arrays over an indefinite number of iterations. Gas limit vulnerabilities can render contract functions unexecutable, freezing contracts or locking funds.
Mitigation
- Program functions to validate that users can’t control variable lengths within loops to traverse large data amounts or, when this is not feasible, to limit loop length
- When using loops in Solidity, the developers, ensure that in-loop transactions stay within gas limits and don't consume excessive gas
10. Unchecked External Calls
This vulnerability occurs when smart contracts verify outcomes of external function calls.
This can allow calls to fail without generating an exception error, causing the contract to proceed as if the call was successful. When this happens, funds can be lost if transactions fail to complete, and attackers can exploit resulting inconsistencies in the contract state, potentially setting the stage to launch reentry attacks that drain funds or disrupt contract logic.
Mitigation
- Use transfer() instead of send() to ensure the contract reverts the transaction if the external call fails
- Check return values of send() or call() functions to ensure proper handling of returns with a false value
Keep Your Smart Contracts Secure with Cobalt
As cryptocurrency and blockchain continue to grow in popularity, smart contract security vulnerabilities will become increasingly critical. Cobalt's application security services can help you protect your smart contracts from common vulnerabilities. Our team of expert pentesters works with OWASP and other industry leaders to develop and maintain security standards safeguarding applications and networks against today's top risks.
Our user-friendly pentesting platform makes it easy for your security team to collaborate with our experts in planning and scheduling tests of your attack surface. Contact us to discuss how we can help you keep your smart contracts secure.
For more on this subject, explore the differences between Bitcoin Ordinals and Ethereum Smart Contracts.