info@cyberlawacademy.com | +91-XXXXXXXXXX
Part 3 of 7

Smart Contract Security & Auditing

Identify critical vulnerabilities, understand audit methodologies, and assess security risks. Over $2 billion has been lost to smart contract exploits - learn to recognize the patterns.

[T] ~120 minutes [S] 5 Sections [E] 6 Case Studies

3.1 Security Landscape

Smart contract security is uniquely challenging: code is immutable once deployed, transactions are irreversible, and exploits can drain millions in seconds. Understanding vulnerabilities is essential for legal due diligence and risk assessment.

Why Smart Contract Security Matters

  • Immutability: Bugs cannot be patched after deployment (usually)
  • High Value Targets: Contracts often hold millions in assets
  • Pseudonymity: Attackers are difficult to identify and prosecute
  • Complexity: Interactions between contracts create emergent vulnerabilities
  • Financial Incentives: Hackers can profit directly from exploits
YearIncidentLossVulnerability Type
2016The DAO$60MReentrancy
2021Poly Network$611MAccess Control
2022Wormhole$326MSignature Verification
2022Ronin Bridge$625MPrivate Key Compromise
2022Nomad Bridge$190MMerkle Proof Validation
2023Euler Finance$197MFlash Loan + Logic Error
Legal Implications

Security vulnerabilities can create legal liability: breach of implied warranties, negligence in development, failure to conduct adequate audits, or misrepresentation of security. Understanding vulnerabilities helps assess potential claims.

3.2 Common Vulnerabilities

Reentrancy Attacks

Reentrancy
A vulnerability where an external call allows the called contract to re-enter the calling contract before its state is updated, potentially draining funds through recursive calls.
The DAO Hack (2016)
$60 Million Lost

The first major smart contract exploit. An attacker exploited a reentrancy vulnerability in The DAO's withdrawal function, recursively draining funds before the balance was updated. This led to the Ethereum hard fork creating Ethereum (ETH) and Ethereum Classic (ETC).

VULNERABLE CODE
// VULNERABLE: State updated AFTER external call
function withdraw(uint256 amount) external {
    require(balances[msg.sender] >= amount);

    // DANGER: External call before state update
    (bool success, ) = msg.sender.call{value: amount}("");
    require(success);

    // State updated AFTER call - attacker can re-enter
    balances[msg.sender] -= amount;  // TOO LATE!
}
SECURE CODE
// SECURE: Checks-Effects-Interactions pattern
function withdraw(uint256 amount) external {
    // 1. CHECKS
    require(balances[msg.sender] >= amount);

    // 2. EFFECTS - Update state BEFORE external call
    balances[msg.sender] -= amount;

    // 3. INTERACTIONS - External call LAST
    (bool success, ) = msg.sender.call{value: amount}("");
    require(success);
}
Checks-Effects-Interactions Pattern

1. Checks: Validate all conditions first
2. Effects: Update contract state
3. Interactions: Make external calls last

This pattern prevents reentrancy by ensuring state is updated before any external calls.

Integer Overflow/Underflow

Prior to Solidity 0.8.0, arithmetic operations could overflow or underflow silently.

VULNERABLE (Pre-0.8.0)
// uint8 max value is 255
uint8 balance = 255;
balance = balance + 1;  // Overflows to 0!

uint8 amount = 0;
amount = amount - 1;    // Underflows to 255!

// Attack: Transfer more than you have
function transfer(address to, uint256 amount) {
    // If balance is 0 and amount is 1:
    // 0 - 1 = MAX_UINT256 (underflow!)
    balances[msg.sender] -= amount;  // No check!
    balances[to] += amount;
}
Solidity 0.8+ Protection

Solidity 0.8.0 and later include built-in overflow/underflow checks. Operations that would overflow now revert automatically. Always verify the Solidity version when reviewing contracts.

Access Control Flaws

VULNERABLE CODE
// VULNERABLE: Missing access control
function setOwner(address newOwner) external {
    owner = newOwner;  // Anyone can call!
}

// VULNERABLE: tx.origin instead of msg.sender
function withdraw() external {
    require(tx.origin == owner);  // Can be phished!
    // If owner calls malicious contract, attacker can call this
}

Flash Loan Attacks

Flash Loan
An uncollateralized loan that must be borrowed and repaid within a single transaction. Used legitimately for arbitrage, but also enables price manipulation attacks by temporarily acquiring massive capital.

Flash loans enable attacks by temporarily providing attackers with enormous capital to manipulate prices or governance votes within a single transaction.

VulnerabilityDescriptionMitigation
ReentrancyRecursive calls before state updateChecks-Effects-Interactions, ReentrancyGuard
Integer OverflowArithmetic exceeds type boundsSolidity 0.8+, SafeMath library
Access ControlMissing or improper authorizationonlyOwner modifiers, role-based access
Front-RunningMiners/MEV bots see pending txsCommit-reveal schemes, private mempools
Oracle ManipulationPrice feed manipulationTWAP oracles, multiple sources
Denial of ServiceMaking contract unusablePull over push, gas limits

3.3 Smart Contract Auditing

A security audit is a systematic examination of smart contract code to identify vulnerabilities, logic errors, and deviations from best practices. Understanding audit processes helps evaluate their quality and limitations.

Audit Process

  1. Scoping: Define what contracts are in scope, expected behavior, and threat model
  2. Documentation Review: Review whitepapers, specifications, and design documents
  3. Manual Code Review: Line-by-line analysis by security experts
  4. Automated Analysis: Static analyzers, fuzzers, and symbolic execution tools
  5. Testing: Unit tests, integration tests, and invariant testing
  6. Report Generation: Document findings with severity ratings
  7. Remediation: Developers fix issues, auditors verify fixes

Severity Classification

SeverityDefinitionExample
CriticalDirect loss of funds, protocol takeoverReentrancy allowing unlimited withdrawals
HighSignificant financial impact or protocol disruptionAccess control allowing unauthorized minting
MediumLimited financial impact or complex exploitationFront-running opportunities
LowMinimal impact, best practice violationsMissing event emissions
InformationalCode quality, gas optimizationUnused variables

Leading Audit Firms

  • Trail of Bits: Known for rigorous, research-oriented audits
  • OpenZeppelin: Major contributor to security standards and libraries
  • Consensys Diligence: Ethereum ecosystem specialists
  • Certik: High-volume auditing with automated tooling
  • Spearbit: Decentralized network of security researchers
Audits Are Not Guarantees

An audit is a point-in-time assessment with limited scope. Audited contracts have been hacked (e.g., Euler Finance, Wormhole). Audits reduce risk but do not eliminate it. Multiple audits from different firms provide better coverage.

3.4 Formal Verification

Formal Verification
Mathematical proof that a program satisfies a formal specification. Unlike testing (which shows bugs exist), formal verification proves their absence for specified properties.

Approaches to Formal Verification

  • Model Checking: Exhaustively explore all possible states
  • Theorem Proving: Mathematical proofs of correctness
  • Symbolic Execution: Analyze code with symbolic inputs
  • SMT Solving: Use satisfiability solvers to find violations

Formal Verification Tools

ToolTypeUse Case
Certora ProverFormal verificationComplex DeFi invariants
EchidnaFuzzerProperty-based testing
MythrilSymbolic executionVulnerability detection
SlitherStatic analysisCode quality and bugs
Foundry/ForgeTesting frameworkFuzz testing, invariants
Due Diligence Checklist

When reviewing a project's security posture:
1. Has the contract been audited? By whom? When?
2. Were all critical/high findings remediated?
3. Has the code changed since the audit?
4. Is there a bug bounty program?
5. Is the contract verified on Etherscan?
6. Has formal verification been performed?

3.5 Smart Contract Insurance

DeFi insurance protocols provide coverage against smart contract failures, offering risk transfer mechanisms for users and protocols.

Insurance Protocols

ProtocolModelCoverage Types
Nexus MutualMutual (membership-based)Smart contract cover, custody cover
InsurAceDecentralizedSmart contract, stablecoin depeg
Unslashed FinanceCapital poolExchange, validator, smart contract
Legal Considerations for Insurance

DeFi insurance raises novel legal questions:
- Are these products "insurance" under regulations?
- What jurisdiction governs claims?
- How are claims adjudicated (often by token voting)?
- Are payouts enforceable if disputed?
- What constitutes a covered "hack" vs. economic exploit?

Key Takeaways

  • Reentrancy is the most famous vulnerability - use Checks-Effects-Interactions pattern
  • Always verify contracts use Solidity 0.8+ for overflow protection
  • Audits are necessary but not sufficient - audited contracts have been hacked
  • Review audit reports for remediation status of all findings
  • Multiple audits from different firms provide better coverage
  • Formal verification provides mathematical proofs but is expensive and limited in scope
  • DeFi insurance is emerging but has unclear legal status