Skip to content

Latest commit

 

History

History
813 lines (606 loc) · 23.6 KB

vulnerability-patterns.md

File metadata and controls

813 lines (606 loc) · 23.6 KB

Vulnerability Patterns

Catalog of Solidity vulnerability categories with detection patterns and secure implementations.


Reentrancy Variants

1. Single-Function Reentrancy

The most basic reentrancy: an external call allows the callee to re-enter the same function before state is updated.

❌ Bad: State update after external call

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

contract VulnerableBank {
    mapping(address => uint256) public balances;

    function withdraw(uint256 amount) external {
        require(balances[msg.sender] >= amount, "Insufficient balance");

        // INTERACTION before EFFECT - attacker re-enters here
        (bool success, ) = msg.sender.call{value: amount}("");
        require(success, "Transfer failed");

        // State updated too late - attacker already re-entered
        balances[msg.sender] -= amount;
    }
}

✅ Good: Checks-Effects-Interactions pattern

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";

contract SecureBank is ReentrancyGuard {
    mapping(address => uint256) public balances;

    function withdraw(uint256 amount) external nonReentrant {
        // CHECKS
        require(balances[msg.sender] >= amount, "Insufficient balance");

        // EFFECTS - state updated before external call
        balances[msg.sender] -= amount;

        // INTERACTIONS
        (bool success, ) = msg.sender.call{value: amount}("");
        require(success, "Transfer failed");
    }
}

Rule: Always update state before making external calls. Use ReentrancyGuard as defense-in-depth.


2. Cross-Function Reentrancy

The attacker re-enters through a different function that shares the same state variable. CEI on one function alone is insufficient.

❌ Bad: Two functions sharing state, only one protected

contract VulnerableToken {
    mapping(address => uint256) public balances;

    function withdraw(uint256 amount) external {
        require(balances[msg.sender] >= amount);
        balances[msg.sender] -= amount;
        // Attacker re-enters transfer() during this call
        (bool success, ) = msg.sender.call{value: amount}("");
        require(success);
    }

    function transfer(address to, uint256 amount) external {
        // This reads the not-yet-decremented balance during reentrancy
        require(balances[msg.sender] >= amount);
        balances[msg.sender] -= amount;
        balances[to] += amount;
    }
}

✅ Good: ReentrancyGuard on all state-mutating functions

contract SecureToken is ReentrancyGuard {
    mapping(address => uint256) public balances;

    function withdraw(uint256 amount) external nonReentrant {
        require(balances[msg.sender] >= amount);
        balances[msg.sender] -= amount;
        (bool success, ) = msg.sender.call{value: amount}("");
        require(success);
    }

    function transfer(address to, uint256 amount) external nonReentrant {
        require(balances[msg.sender] >= amount);
        balances[msg.sender] -= amount;
        balances[to] += amount;
    }
}

Rule: Apply nonReentrant to every function that reads or writes shared state, not just the one making external calls.


3. Cross-Contract Reentrancy

Reentrancy through an intermediary contract. Contract A calls Contract B, which calls back into Contract A.

❌ Bad: No protection against callbacks from trusted contracts

contract VulnerableVault {
    mapping(address => uint256) public deposits;
    IERC20 public token;

    function withdraw(uint256 amount) external {
        require(deposits[msg.sender] >= amount);
        // Token contract could trigger a callback (e.g., ERC-777 hook)
        // that re-enters this vault before deposits is updated
        token.transfer(msg.sender, amount);
        deposits[msg.sender] -= amount;
    }
}

✅ Good: CEI pattern + reentrancy guard even for token transfers

contract SecureVault is ReentrancyGuard {
    mapping(address => uint256) public deposits;
    IERC20 public token;

    function withdraw(uint256 amount) external nonReentrant {
        require(deposits[msg.sender] >= amount);
        deposits[msg.sender] -= amount;  // Effect before interaction
        token.transfer(msg.sender, amount);
    }
}

Rule: Treat every external call as a potential re-entry point, including calls to trusted contracts and token transfers.


4. Read-Only Reentrancy

View functions return stale state during a reentrant call. External protocols reading your contract's state mid-operation get incorrect values.

❌ Bad: View function readable during state transition

contract VulnerablePool {
    uint256 public totalShares;
    uint256 public totalAssets;

    // External protocols use this to price shares
    function getSharePrice() external view returns (uint256) {
        return totalAssets / totalShares;
    }

    function withdraw(uint256 shares) external {
        uint256 assets = (shares * totalAssets) / totalShares;
        totalShares -= shares;
        // During this call, getSharePrice() returns a stale value
        // because totalAssets hasn't been updated yet
        (bool success, ) = msg.sender.call{value: assets}("");
        require(success);
        totalAssets -= assets;
    }
}

✅ Good: Reentrancy guard that also blocks view functions

contract SecurePool is ReentrancyGuard {
    uint256 public totalShares;
    uint256 public totalAssets;

    function getSharePrice() external view nonReentrant returns (uint256) {
        return totalAssets / totalShares;
    }

    function withdraw(uint256 shares) external nonReentrant {
        uint256 assets = (shares * totalAssets) / totalShares;
        totalShares -= shares;
        totalAssets -= assets;  // Both state changes before external call
        (bool success, ) = msg.sender.call{value: assets}("");
        require(success);
    }
}

Rule: If external protocols depend on your view functions for pricing, apply reentrancy guards on those views too.


Access Control Flaws

5. Missing Function Protection

Privileged functions left public without access control modifiers.

❌ Bad: Critical function without access control

contract VulnerableAdmin {
    address public feeRecipient;

    // Anyone can call this and redirect fees
    function setFeeRecipient(address _recipient) external {
        feeRecipient = _recipient;
    }

    function pause() external {
        // Anyone can pause the contract
        _pause();
    }
}

✅ Good: Role-based access control

import "@openzeppelin/contracts/access/AccessControl.sol";

contract SecureAdmin is AccessControl {
    bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
    address public feeRecipient;

    constructor() {
        _grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
        _grantRole(ADMIN_ROLE, msg.sender);
    }

    function setFeeRecipient(address _recipient) external onlyRole(ADMIN_ROLE) {
        require(_recipient != address(0), "Zero address");
        feeRecipient = _recipient;
    }
}

Rule: Every external and public function that modifies state must have explicit access control.


6. tx.origin Authentication

Using tx.origin for authentication allows phishing through intermediary contracts.

❌ Bad: tx.origin used for authorization

contract VulnerableWallet {
    address public owner;

    function transfer(address to, uint256 amount) external {
        // If owner interacts with a malicious contract,
        // that contract can call this function and tx.origin == owner
        require(tx.origin == owner, "Not owner");
        payable(to).transfer(amount);
    }
}

✅ Good: msg.sender for authorization

contract SecureWallet {
    address public owner;

    function transfer(address to, uint256 amount) external {
        require(msg.sender == owner, "Not owner");
        payable(to).transfer(amount);
    }
}

Rule: Never use tx.origin for authorization. Always use msg.sender.


7. Unprotected Initializer

Proxy patterns with initialize() functions that can be called by anyone, or called multiple times.

❌ Bad: Initializer callable by anyone, no protection against re-initialization

contract VulnerableProxy {
    address public owner;
    bool public initialized;

    function initialize(address _owner) external {
        // Missing: check if already initialized
        // Anyone can call this and become owner
        owner = _owner;
    }
}

✅ Good: OpenZeppelin Initializable pattern

import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";

contract SecureProxy is Initializable, OwnableUpgradeable {
    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor() {
        _disableInitializers();  // Prevent initialization on implementation
    }

    function initialize(address _owner) external initializer {
        __Ownable_init(_owner);
    }
}

Rule: Use OpenZeppelin's Initializable with the initializer modifier. Call _disableInitializers() in the constructor of implementation contracts.


8. Centralization Risks

A single owner address with unlimited power over funds and configuration. Compromised key means total loss.

❌ Bad: Single owner can drain all funds

contract CentralizedProtocol {
    address public owner;

    function emergencyWithdraw() external {
        require(msg.sender == owner);
        payable(owner).transfer(address(this).balance);
    }

    function setParameters(uint256 fee, uint256 limit) external {
        require(msg.sender == owner);
        // No bounds checking, no timelock
        protocolFee = fee;
        withdrawLimit = limit;
    }
}

✅ Good: Multisig + timelock + bounded parameters

import "@openzeppelin/contracts/governance/TimelockController.sol";

contract DecentralizedProtocol {
    TimelockController public timelock;
    uint256 public constant MAX_FEE = 500; // 5% max

    function setParameters(uint256 fee, uint256 limit) external {
        require(msg.sender == address(timelock), "Only timelock");
        require(fee <= MAX_FEE, "Fee too high");
        require(limit >= MIN_LIMIT, "Limit too low");
        protocolFee = fee;
        withdrawLimit = limit;
    }
}

Rule: Use multisig wallets for ownership, timelocks for parameter changes, and bounded ranges for critical values.


Oracle Manipulation

9. Spot Price Manipulation

Using an AMM's spot price (current reserves ratio) as a price oracle. Flash loans can manipulate this within a single transaction.

❌ Bad: Reading Uniswap reserves directly for pricing

contract VulnerableLending {
    IUniswapV2Pair public pair;

    function getPrice() public view returns (uint256) {
        (uint112 reserve0, uint112 reserve1, ) = pair.getReserves();
        // Spot price - manipulable via flash loan in same block
        return (uint256(reserve1) * 1e18) / uint256(reserve0);
    }

    function borrow(uint256 collateralAmount) external {
        uint256 price = getPrice();  // Manipulated price
        uint256 borrowable = collateralAmount * price / 1e18;
        // Attacker borrows far more than collateral is worth
        _transferTokens(msg.sender, borrowable);
    }
}

✅ Good: Chainlink oracle with TWAP fallback

import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";

contract SecureLending {
    AggregatorV3Interface public priceFeed;
    uint256 public constant MAX_PRICE_AGE = 1 hours;

    function getPrice() public view returns (uint256) {
        (, int256 price, , uint256 updatedAt, ) = priceFeed.latestRoundData();
        require(price > 0, "Invalid price");
        require(block.timestamp - updatedAt <= MAX_PRICE_AGE, "Stale price");
        return uint256(price);
    }
}

Rule: Never use AMM spot prices as oracles. Use Chainlink, TWAP, or other manipulation-resistant price feeds.


10. Stale Oracle Data

Accepting oracle data without freshness validation. If the oracle stops updating, the contract uses outdated prices.

❌ Bad: No freshness check

function getPrice() public view returns (uint256) {
    (, int256 price, , , ) = priceFeed.latestRoundData();
    return uint256(price);  // Could be hours or days old
}

✅ Good: Freshness validation with fallback

function getPrice() public view returns (uint256) {
    (
        uint80 roundId,
        int256 price,
        ,
        uint256 updatedAt,
        uint80 answeredInRound
    ) = priceFeed.latestRoundData();

    require(price > 0, "Negative or zero price");
    require(updatedAt > 0, "Round not complete");
    require(answeredInRound >= roundId, "Stale round");
    require(block.timestamp - updatedAt <= MAX_STALENESS, "Price too old");

    return uint256(price);
}

Rule: Always validate oracle freshness, round completeness, and price bounds.


Signature Issues

11. Signature Replay

A valid signature is reused across transactions, chains, or contracts because the signed message lacks uniqueness constraints.

❌ Bad: No nonce or chain ID in signed message

contract VulnerableRelay {
    function executeWithSig(
        address to,
        uint256 amount,
        bytes memory signature
    ) external {
        // Same signature valid forever, on any chain
        bytes32 hash = keccak256(abi.encodePacked(to, amount));
        address signer = ECDSA.recover(hash, signature);
        require(signer == owner, "Invalid signer");
        payable(to).transfer(amount);
    }
}

✅ Good: EIP-712 typed data with nonce and domain separator

import "@openzeppelin/contracts/utils/cryptography/EIP712.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";

contract SecureRelay is EIP712 {
    mapping(address => uint256) public nonces;

    bytes32 private constant EXECUTE_TYPEHASH =
        keccak256("Execute(address to,uint256 amount,uint256 nonce)");

    constructor() EIP712("SecureRelay", "1") {}

    function executeWithSig(
        address to,
        uint256 amount,
        bytes memory signature
    ) external {
        uint256 nonce = nonces[owner]++;
        bytes32 structHash = keccak256(
            abi.encode(EXECUTE_TYPEHASH, to, amount, nonce)
        );
        bytes32 hash = _hashTypedDataV4(structHash);
        address signer = ECDSA.recover(hash, signature);
        require(signer == owner, "Invalid signer");
        payable(to).transfer(amount);
    }
}

Rule: Use EIP-712 typed data with a domain separator (includes chain ID and contract address) and an incrementing nonce.


12. Signature Malleability

ECDSA signatures have two valid forms (s and n-s). Without checking the s-value range, attackers can submit alternative valid signatures.

❌ Bad: No malleability protection

function verify(bytes32 hash, bytes memory sig) internal pure returns (address) {
    (uint8 v, bytes32 r, bytes32 s) = splitSignature(sig);
    return ecrecover(hash, v, r, s);  // Both (v, r, s) and (v', r, n-s) are valid
}

✅ Good: OpenZeppelin ECDSA with s-value check

import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";

function verify(bytes32 hash, bytes memory sig) internal pure returns (address) {
    // OpenZeppelin ECDSA.recover rejects malleable signatures
    // by requiring s to be in the lower half of the curve order
    return ECDSA.recover(hash, sig);
}

Rule: Use OpenZeppelin's ECDSA.recover which rejects malleable signatures. Never use raw ecrecover.


Storage and Proxy Issues

13. Storage Collision in Proxies

When a proxy and its implementation define state variables at the same storage slots, they overwrite each other.

❌ Bad: Proxy and implementation with conflicting storage

// Proxy stores admin at slot 0
contract VulnerableProxy {
    address public admin;       // slot 0
    address public implementation; // slot 1

    fallback() external payable {
        // delegatecall to implementation
    }
}

// Implementation also uses slot 0 for a different purpose
contract Implementation {
    address public owner;       // slot 0 - COLLIDES with proxy's admin
    uint256 public value;       // slot 1 - COLLIDES with implementation address
}

✅ Good: EIP-1967 random storage slots

contract SecureProxy {
    // EIP-1967 slot: keccak256("eip1967.proxy.implementation") - 1
    bytes32 private constant IMPLEMENTATION_SLOT =
        0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;

    // EIP-1967 slot: keccak256("eip1967.proxy.admin") - 1
    bytes32 private constant ADMIN_SLOT =
        0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;

    function _getImplementation() internal view returns (address impl) {
        bytes32 slot = IMPLEMENTATION_SLOT;
        assembly {
            impl := sload(slot)
        }
    }
}

Rule: Use EIP-1967 standard storage slots for proxy state. Never use sequential slots in proxy contracts.


14. Uninitialized Storage Pointers

In older Solidity versions, local struct variables defaulted to storage, potentially pointing to unexpected slots.

❌ Bad: Implicit storage pointer (Solidity < 0.5.0 behavior)

// In Solidity < 0.5.0, this was possible:
contract VulnerableStruct {
    struct Wallet {
        address owner;
        uint256 balance;
    }

    mapping(uint256 => Wallet) wallets;

    function createWallet(uint256 id) external {
        // This created an uninitialized storage pointer at slot 0
        Wallet wallet;  // Pointed to storage slot 0 by default!
        wallet.owner = msg.sender;  // Overwrote slot 0
        wallet.balance = msg.value;
        wallets[id] = wallet;
    }
}

✅ Good: Explicit memory or direct storage access

contract SecureStruct {
    struct Wallet {
        address owner;
        uint256 balance;
    }

    mapping(uint256 => Wallet) wallets;

    function createWallet(uint256 id) external payable {
        // Solidity 0.8+ requires explicit data location
        wallets[id] = Wallet({
            owner: msg.sender,
            balance: msg.value
        });
    }
}

Rule: Always use Solidity 0.8+ which requires explicit data location. When using structs, assign directly to storage mappings or use memory for local computation.


15. Delegatecall to Untrusted Target

delegatecall executes external code in the caller's storage context. If the target is attacker-controlled, they can overwrite any storage.

❌ Bad: Delegatecall to user-provided address

contract VulnerableRouter {
    address public owner;

    function execute(address target, bytes calldata data) external {
        // Attacker provides a target that sets owner to their address
        (bool success, ) = target.delegatecall(data);
        require(success);
    }
}

✅ Good: Whitelist of allowed targets

contract SecureRouter {
    address public owner;
    mapping(address => bool) public allowedTargets;

    function execute(address target, bytes calldata data) external onlyOwner {
        require(allowedTargets[target], "Target not whitelisted");
        (bool success, ) = target.delegatecall(data);
        require(success);
    }

    function addTarget(address target) external onlyOwner {
        allowedTargets[target] = true;
    }
}

Rule: Never delegatecall to addresses provided by users. Maintain a strict whitelist of allowed targets.


Denial of Service

16. Gas Limit in Loops

Unbounded loops that grow with user count will eventually exceed the block gas limit, making the function permanently uncallable.

❌ Bad: Loop over unbounded array

contract VulnerableDistributor {
    address[] public recipients;

    function distribute() external {
        uint256 share = address(this).balance / recipients.length;
        // If recipients grows to thousands, this exceeds block gas limit
        for (uint256 i = 0; i < recipients.length; i++) {
            payable(recipients[i]).transfer(share);
        }
    }
}

✅ Good: Paginated processing with pull pattern

contract SecureDistributor {
    mapping(address => uint256) public pendingWithdrawals;

    function allocateShares(address[] calldata recipients, uint256 amount) external onlyOwner {
        uint256 share = amount / recipients.length;
        // Bounded by calldata size, not storage array
        for (uint256 i = 0; i < recipients.length; i++) {
            pendingWithdrawals[recipients[i]] += share;
        }
    }

    // Users pull their own funds - never blocked by others
    function withdraw() external {
        uint256 amount = pendingWithdrawals[msg.sender];
        require(amount > 0, "Nothing to withdraw");
        pendingWithdrawals[msg.sender] = 0;
        (bool success, ) = msg.sender.call{value: amount}("");
        require(success);
    }
}

Rule: Never iterate over unbounded arrays in a single transaction. Use pull patterns or pagination.


17. External Call Failure DoS

When pushing payments in a loop, one failed transfer blocks all subsequent transfers.

❌ Bad: One failed transfer blocks everyone

contract VulnerableAuction {
    address[] public bidders;
    mapping(address => uint256) public bids;

    function refundAll() external {
        for (uint256 i = 0; i < bidders.length; i++) {
            // If one bidder is a contract that reverts, no one gets refunded
            payable(bidders[i]).transfer(bids[bidders[i]]);
        }
    }
}

✅ Good: Pull payment pattern

import "@openzeppelin/contracts/utils/Address.sol";

contract SecureAuction {
    mapping(address => uint256) public pendingReturns;

    function withdraw() external {
        uint256 amount = pendingReturns[msg.sender];
        require(amount > 0, "No pending return");
        pendingReturns[msg.sender] = 0;
        (bool success, ) = msg.sender.call{value: amount}("");
        require(success, "Transfer failed");
    }
}

Rule: Use the pull payment pattern. Let users withdraw their own funds instead of pushing payments to them.


Quick Reference

# Vulnerability Key Fix Severity
1 Single-Function Reentrancy CEI pattern + ReentrancyGuard Critical
2 Cross-Function Reentrancy ReentrancyGuard on all state-mutating functions Critical
3 Cross-Contract Reentrancy CEI + guard even for token transfers Critical
4 Read-Only Reentrancy Guard on view functions used externally High
5 Missing Function Protection Access control modifiers on all state-changing functions Critical
6 tx.origin Authentication Use msg.sender instead High
7 Unprotected Initializer OpenZeppelin Initializable + disableInitializers Critical
8 Centralization Risks Multisig + timelock + bounded parameters Medium
9 Spot Price Manipulation Chainlink or TWAP oracle Critical
10 Stale Oracle Data Freshness + round + bounds validation High
11 Signature Replay EIP-712 + nonce + chain ID in domain High
12 Signature Malleability OpenZeppelin ECDSA.recover Medium
13 Storage Collision in Proxies EIP-1967 standard storage slots Critical
14 Uninitialized Storage Pointers Solidity 0.8+ with explicit data location High
15 Delegatecall to Untrusted Target Whitelist of allowed targets Critical
16 Gas Limit in Loops Pagination and bounded iterations High
17 External Call Failure DoS Pull payment pattern High