Ethereum Security Audit Guide
Overview
Smart contract security is paramount due to the immutable nature of blockchain. This guide covers vulnerabilities, prevention techniques, and audit methodologies.
Common Vulnerabilities
Reentrancy Attack
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
// â VULNERABLE: Reentrancy attack
contract VulnerableVault {
mapping(address => uint256) public balances;
function deposit() public payable {
balances[msg.sender] += msg.value;
}
function withdraw() public {
uint256 balance = balances[msg.sender];
require(balance > 0, "No balance");
// â External call before state update
(bool success, ) = msg.sender.call{value: balance}("");
require(success, "Transfer failed");
balances[msg.sender] = 0; // State updated after external call
}
}
// Attacker contract
contract Attacker {
VulnerableVault public vault;
constructor(address _vault) {
vault = VulnerableVault(_vault);
}
function attack() external payable {
vault.deposit{value: 1 ether}();
vault.withdraw();
}
receive() external payable {
if (address(vault).balance >= 1 ether) {
vault.withdraw(); // Re-enter before balance is set to 0
}
}
}
// â
SECURE: ReentrancyGuard
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
contract SecureVault is ReentrancyGuard {
mapping(address => uint256) public balances;
function deposit() public payable {
balances[msg.sender] += msg.value;
}
function withdraw() public nonReentrant {
uint256 balance = balances[msg.sender];
require(balance > 0, "No balance");
// â
State update before external call
balances[msg.sender] = 0;
(bool success, ) = msg.sender.call{value: balance}("");
require(success, "Transfer failed");
}
}
// â
SECURE: Checks-Effects-Interactions pattern
contract SecureVault2 {
mapping(address => uint256) public balances;
function deposit() public payable {
balances[msg.sender] += msg.value;
}
function withdraw() public {
uint256 balance = balances[msg.sender];
// Checks
require(balance > 0, "No balance");
// Effects
balances[msg.sender] = 0;
// Interactions
(bool success, ) = msg.sender.call{value: balance}("");
require(success, "Transfer failed");
}
}
Access Control Vulnerability
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
// â VULNERABLE: Missing access control
contract VulnerableToken {
address public owner;
mapping(address => uint256) public balances;
constructor() {
owner = msg.sender;
}
// â Anyone can mint tokens
function mint(address to, uint256 amount) public {
balances[to] += amount;
}
// â Anyone can transfer ownership
function transferOwnership(address newOwner) public {
owner = newOwner;
}
}
// â
SECURE: Role-based access control
import "@openzeppelin/contracts/access/AccessControl.sol";
contract SecureToken is AccessControl {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
mapping(address => uint256) public balances;
constructor() {
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
_grantRole(ADMIN_ROLE, msg.sender);
_grantRole(MINTER_ROLE, msg.sender);
}
function mint(address to, uint256 amount) public onlyRole(MINTER_ROLE) {
balances[to] += amount;
}
function transferOwnership(address newOwner) public onlyRole(ADMIN_ROLE) {
_grantRole(DEFAULT_ADMIN_ROLE, newOwner);
_revokeRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
}
// â
SECURE: Ownable pattern
import "@openzeppelin/contracts/access/Ownable.sol";
contract SecureToken2 is Ownable {
mapping(address => uint256) public balances;
function mint(address to, uint256 amount) public onlyOwner {
balances[to] += amount;
}
}
Flash Loan Attack Prevention
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
// â VULNERABLE: Flash loan manipulation
contract VulnerableDEX {
mapping(address => mapping(address => uint256)) reserves;
function swap(
address tokenIn,
address tokenOut,
uint256 amountIn
) external returns (uint256) {
uint256 reserveIn = reserves[tokenIn][tokenOut];
uint256 reserveOut = reserves[tokenOut][tokenIn];
// â No protection against flash loans
uint256 amountOut = (amountIn * reserveOut) / (reserveIn + amountIn);
reserves[tokenIn][tokenOut] += amountIn;
reserves[tokenOut][tokenIn] -= amountOut;
return amountOut;
}
}
// â
SECURE: TWAP (Time-Weighted Average Price)
contract SecureDEX {
mapping(address => mapping(address => uint256)) reserves;
mapping(address => mapping(address => uint256)) priceCumulative;
mapping(address => mapping(address => uint256)) lastTimestamp;
function update() public {
for (uint256 i = 0; i < tokenPairs.length; i++) {
(address tokenA, address tokenB) = tokenPairs[i];
uint256 timeElapsed = block.timestamp - lastTimestamp[tokenA][tokenB];
priceCumulative[tokenA][tokenB] += reserves[tokenB][tokenA] * timeElapsed;
priceCumulative[tokenB][tokenA] += reserves[tokenA][tokenB] * timeElapsed;
lastTimestamp[tokenA][tokenB] = block.timestamp;
}
}
function getTWAP(
address tokenA,
address tokenB,
uint256 period
) public view returns (uint256) {
uint256 priceCumulativeEnd = priceCumulative[tokenA][tokenB];
uint256 timeElapsed = block.timestamp - lastTimestamp[tokenA][tokenB];
require(timeElapsed >= period, "Period not elapsed");
return priceCumulativeEnd / timeElapsed;
}
function swap(
address tokenIn,
address tokenOut,
uint256 amountIn
) external returns (uint256) {
uint256 twap = getTWAP(tokenIn, tokenOut, 1800); // 30 min TWAP
uint256 amountOut = (amountIn * twap) / 1e18;
// Execute swap with TWAP protection
return amountOut;
}
}
Oracle Manipulation Prevention
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
// â VULNERABLE: Single oracle
contract VulnerableLending {
IPriceOracle public oracle;
function getPrice(address token) public view returns (uint256) {
return oracle.getPrice(token); // â Single point of failure
}
function borrow(uint256 amount, address collateral) public {
uint256 price = getPrice(collateral);
uint256 collateralValue = (amount * price) / 1e18;
require(collateralValue >= amount * 150 / 100, "Insufficient collateral");
}
}
// â
SECURE: Multi-oracle with circuit breaker
contract SecureLending {
IPriceOracle[] public oracles;
uint256 public constant MAX_DEVIATION = 10; // 10% max deviation
uint256 public lastValidPrice;
uint256 public lastPriceUpdate;
constructor(address[] memory _oracles) {
for (uint256 i = 0; i < _oracles.length; i++) {
oracles.push(IPriceOracle(_oracles[i]));
}
}
function getMedianPrice(address token) public view returns (uint256) {
uint256[] memory prices = new uint256[](oracles.length);
for (uint256 i = 0; i < oracles.length; i++) {
prices[i] = oracles[i].getPrice(token);
}
// Sort prices
for (uint256 i = 0; i < prices.length - 1; i++) {
for (uint256 j = 0; j < prices.length - i - 1; j++) {
if (prices[j] > prices[j + 1]) {
(prices[j], prices[j + 1]) = (prices[j + 1], prices[j]);
}
}
}
// Return median
return prices[prices.length / 2];
}
function getPriceWithDeviationCheck(address token) public returns (uint256) {
uint256 medianPrice = getMedianPrice(token);
// Check deviation from last valid price
if (lastValidPrice > 0) {
uint256 deviation = (medianPrice > lastValidPrice)
? ((medianPrice - lastValidPrice) * 100) / lastValidPrice
: ((lastValidPrice - medianPrice) * 100) / lastValidPrice;
require(deviation <= MAX_DEVIATION, "Price deviation too high");
}
lastValidPrice = medianPrice;
lastPriceUpdate = block.timestamp;
return medianPrice;
}
function borrow(uint256 amount, address collateral) public {
uint256 price = getPriceWithDeviationCheck(collateral);
uint256 collateralValue = (amount * price) / 1e18;
require(collateralValue >= amount * 150 / 100, "Insufficient collateral");
}
}
interface IPriceOracle {
function getPrice(address token) external view returns (uint256);
}
Audit Checklist
| Category | Check Item | Severity |
|---|---|---|
| Access Control | Owner/admin functions protected | Critical |
| Role-based access implemented | High | |
| No hardcoded addresses | Medium | |
| Reentrancy | Checks-Effects-Interactions | Critical |
| ReentrancyGuard used | High | |
| No external calls in loops | High | |
| Integer Safety | Solidity 0.8+ used | Critical |
| SafeMath for older versions | Critical | |
| No unchecked arithmetic in critical paths | High | |
| Oracle | Multi-oracle implementation | High |
| TWAP for price feeds | High | |
| Circuit breakers | High | |
| Flash Loans | Time-weighted prices | High |
| Delay mechanisms | Medium | |
| Multi-block confirmation | Medium | |
| Upgradeability | Proxy pattern secure | High |
| Storage layout preserved | Critical | |
| Initialization functions | High | |
| Gas | No unbounded loops | Medium |
| Storage packing optimized | Low | |
| Batch operations | Low |
Formal Verification Tools
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
// Certora specification (in .spec file)
// contract MyToken {
// function transfer(address to, uint256 amount) external returns (bool);
// }
// Rule: Total supply should remain constant after transfer
// rule totalSupplyConstant {
// uint256 supplyBefore = totalSupply();
//
// env e;
// address to; uint256 amount;
// transfer(e, to, amount);
//
// uint256 supplyAfter = totalSupply();
// assert supplyBefore == supplyAfter;
// }
// Rule: Balance conservation
// rule balanceConservation {
// env e;
// address from; address to; uint256 amount;
//
// uint256 fromBefore = balanceOf(e, from);
// uint256 toBefore = balanceOf(e, to);
//
// transfer(e, to, amount);
//
// uint256 fromAfter = balanceOf(e, from);
// uint256 toAfter = balanceOf(e, to);
//
// assert fromBefore - amount == fromAfter;
// assert toBefore + amount == toAfter;
// }
// Halmos symbolic testing
contract TokenProperties {
MyToken public token;
function setUp() public {
token = new MyToken("Test", "TST");
}
function testTransferPreservesTotalSupply(
address from,
address to,
uint256 amount
) public {
vm.assume(from != address(0) && to != address(0));
vm.assume(from != to);
token.mint(from, amount);
uint256 supplyBefore = token.totalSupply();
vm.prank(from);
token.transfer(to, amount);
uint256 supplyAfter = token.totalSupply();
assert(supplyBefore == supplyAfter);
}
}
Bug Bounty Programs
| Protocol | Platform | Max Payout | Scope |
|---|---|---|---|
| Uniswap | Immunefi | $3,000,000 | Core contracts |
| Aave | Immunefi | $250,000 | All contracts |
| Compound | Immunefi | $150,000 | All contracts |
| MakerDAO | HackerOne | $10,000 | Governance |
| Lido | Immunefi | $250,000 | Staking |
// Bug bounty submission template
/*
1. Vulnerability Title: [Title]
2. Severity: Critical/High/Medium/Low
3. Vulnerability Type: [e.g., Reentrancy]
4. Affected Contract: [Contract address]
5. Vulnerability Description: [Detailed description]
6. Impact: [What can an attacker do?]
7. Proof of Concept: [Code or steps to reproduce]
8. Recommended Fix: [Suggested solution]
*/
Real-World Attack Examples
| Attack | Date | Loss | Vulnerability |
|---|---|---|---|
| DAO Hack | 2016 | $60M | Reentrancy |
| Parity Wallet | 2017 | $150M | Access Control |
| Cream Finance | 2021 | $130M | Flash Loan |
| Mango Markets | 2022 | $114M | Oracle Manipulation |
| Euler Finance | 2023 | $197M | Flash Loan |
Gas Cost of Security
| Security Measure | Gas Cost | Implementation |
|---|---|---|
| ReentrancyGuard | +2,600 | OpenZeppelin |
| Access Control | +1,500 | OpenZeppelin |
| Pause Mechanism | +2,500 | OpenZeppelin |
| Multi-sig | +5,000 | Custom |
| Time Lock | +5,000 | Custom |
| Circuit Breaker | +3,000 | Custom |
Interview Questions
-
Explain the reentrancy vulnerability and how to prevent it.
- Answer: Reentrancy occurs when a contract makes an external call before updating state, allowing the called contract to re-enter the first function. Prevention includes: using the Checks-Effects-Interactions pattern (validate, update state, then interact), using ReentrancyGuard from OpenZeppelin, and avoiding external calls in loops. The DAO hack in 2016 was a famous reentrancy attack.
-
What is the difference between a flash loan attack and front-running?
- Answer: Flash loan attacks use borrowed funds (must be repaid in same transaction) to manipulate prices or exploit vulnerabilities. Front-running involves observing pending transactions and submitting your own first to profit. Flash loans require technical sophistication but can be atomic; front-running requires monitoring the mempool and quick execution.
-
How would you design a secure oracle system?
- Answer: Use multiple independent oracle sources, implement TWAP (Time-Weighted Average Price) to prevent manipulation, add circuit breakers that halt operations if price deviates too much, use median rather than average to reduce outlier impact, and implement delay mechanisms for large price changes. Chainlink is a common decentralized oracle solution.
Quiz Questions
-
Which OpenZeppelin contract prevents reentrancy attacks?
- A) Ownable
- B) Pausable
- C) ReentrancyGuard
- D) AccessControl
-
What is the recommended pattern to prevent reentrancy?
- A) Checks-Interactions-Effects
- B) Effects-Checks-Interactions
- C) Checks-Effects-Interactions
- D) Interactions-Effects-Checks
-
Which oracle manipulation prevention technique uses average prices over time?
- A) Single oracle
- B) TWAP (Time-Weighted Average Price)
- C) Median price
- D) Circuit breaker