Security·9 min का पठन·Solingo द्वारा

Flash Loan Attacks Explained — कैसे Millions Steal होते हैं

देखें कैसे flash loan attacks DeFi protocols को oracle manipulation और governance attacks के through exploit करते हैं। TWAP oracles और Chainlink के साथ prevention strategies सीखें।

# Flash Loan Attacks Explained — कैसे Millions Steal होते हैं

Flash loans DeFi की सबसे innovative features में से एक हैं — और सबसे exploited attack vectors में से भी एक। 2021 में अकेले, $300 million से ज्यादा flash loan attacks के through चोरी हुए।

Legitimate DeFi primitive होने के बावजूद, flash loans existing vulnerabilities को amplify करते हैं, attackers को zero capital upfront के साथ markets, oracles और governance को manipulate करने देते हैं।

इस article में, हम dissect करेंगे कि flash loan attacks कैसे काम करते हैं, real-world exploits examine करेंगे, और proven defense strategies सीखेंगे।

Flash Loans क्या हैं?

Flash loan एक uncollateralized loan है जिसे एक single transaction के अंदर borrow और repay करना होता है

Key Characteristics

  • No collateral required — कोई भी instantly millions borrow कर सकता है
  • Atomic transaction — loan + operations + repayment एक block में होते हैं
  • Instant liquidity — बिना owned किए massive capital तक access
  • Lender के लिए zero risk — अगर repay नहीं होता, पूरा transaction revert हो जाता है

Example (Aave Flash Loan)

interface IFlashLoanReceiver {

function executeOperation(

address[] calldata assets,

uint256[] calldata amounts,

uint256[] calldata premiums,

address initiator,

bytes calldata params

) external returns (bool);

}

contract FlashLoanUser is IFlashLoanReceiver {

ILendingPool public lendingPool;

function executeFlashLoan(address asset, uint256 amount) external {

address[] memory assets = new address[](1);

assets[0] = asset;

uint256[] memory amounts = new uint256[](1);

amounts[0] = amount;

uint256[] memory modes = new uint256[](1);

modes[0] = 0; // No debt

lendingPool.flashLoan(

address(this),

assets,

amounts,

modes,

address(this),

"",

0

);

}

function executeOperation(

address[] calldata assets,

uint256[] calldata amounts,

uint256[] calldata premiums,

address initiator,

bytes calldata params

) external override returns (bool) {

// अब आपके पास \amounts[0]\ of \assets[0]\ है

// Flash loaned funds के साथ कुछ करें

// ... आपकी logic यहाँ ...

// Loan + fee repay करें

uint256 amountOwed = amounts[0] + premiums[0];

IERC20(assets[0]).approve(address(lendingPool), amountOwed);

return true;

}

}

Flash Loans क्यों Dangerous हैं

Flash loans खुद malicious नहीं हैं, लेकिन वे existing vulnerabilities को amplify करते हैं provide करके:

  • Unlimited capital — massive scale के साथ small inefficiencies exploit करें
  • Atomic execution — एक transaction में complex multi-protocol attacks
  • Zero risk — अगर attack fail होता है, transaction revert (attacker को कोई loss नहीं)
  • Flash Loan Attack Vectors

    1. Oracle Manipulation

    सबसे common attack type। Price oracles को manipulate करें जो उन पर rely करने वाले protocols को exploit करने के लिए।

    Vulnerable Oracle Pattern

    contract VulnerableLending {
    

    IERC20 public tokenA;

    IUniswapV2Pair public pair; // TokenA/WETH

    // VULNERABLE: DEX से spot price का उपयोग

    function getPrice() public view returns (uint256) {

    (uint112 reserve0, uint112 reserve1,) = pair.getReserves();

    return (reserve1 * 1e18) / reserve0; // Instant price

    }

    function borrow(uint256 amount) external {

    uint256 collateralRequired = (amount * getPrice()) / 1e18;

    require(tokenA.balanceOf(msg.sender) >= collateralRequired);

    // User manipulated price के based पर borrow कर सकता है

    // ...

    }

    }

    Attack Scenario

    contract OracleAttack {
    

    function attack() external {

    // 1. TokenA की large amount flash loan करें

    uint256 loanAmount = 1000000 * 1e18;

    flashLoan(address(tokenA), loanAmount);

    }

    function executeOperation(/*...*/) external {

    // 2. DEX पर TokenA dump करें, price crash करें

    tokenA.approve(address(router), loanAmount);

    router.swapExactTokensForTokens(

    loanAmount,

    0,

    path,

    address(this),

    block.timestamp

    );

    // Price अब artificially low है

    // 3. Lending protocol से massive amount borrow करें

    // (जो सोचता है collateral ज्यादा worth है low TokenA price की वजह से)

    lendingProtocol.borrow(exploitAmount);

    // 4. Price restore करने के लिए वापस swap करें

    router.swapExactTokensForTokens(/*...*/);

    // 5. Flash loan repay करें

    tokenA.transfer(lender, loanAmount + fee);

    // Attacker over-borrowed funds रखता है

    }

    }

    Real example: Harvest Finance (2020) — curve pools पर price manipulation के through $24M चोरी।

    2. Governance Attacks

    Malicious proposals pass करने के लिए governance tokens flash loan करें।

    Vulnerable Governance

    contract VulnerableDAO {
    

    IERC20 public govToken;

    struct Proposal {

    address target;

    bytes data;

    uint256 forVotes;

    uint256 againstVotes;

    bool executed;

    }

    mapping(uint256 => Proposal) public proposals;

    // VULNERABLE: Vote time पर snapshot, proposal creation पर नहीं

    function vote(uint256 proposalId, bool support) external {

    uint256 votes = govToken.balanceOf(msg.sender);

    if (support) {

    proposals[proposalId].forVotes += votes;

    } else {

    proposals[proposalId].againstVotes += votes;

    }

    }

    function execute(uint256 proposalId) external {

    Proposal storage prop = proposals[proposalId];

    require(prop.forVotes > prop.againstVotes);

    require(!prop.executed);

    prop.executed = true;

    (bool success,) = prop.target.call(prop.data);

    require(success);

    }

    }

    Attack

    function governanceAttack() external {
    

    // 1. Governance tokens flash loan करें

    flashLoan(address(govToken), supply का 51%);

    // 2. Malicious proposal बनाएँ

    dao.propose(address(treasury), abi.encodeWithSignature(

    "transfer(address,uint256)",

    attacker,

    treasury.balance

    ));

    // 3. Flash loaned tokens के साथ vote करें

    dao.vote(proposalId, true);

    // 4. Immediately execute करें (अगर कोई timelock नहीं)

    dao.execute(proposalId);

    // 5. Flash loan repay करें

    govToken.transfer(lender, amount + fee);

    }

    Real example: Beanstalk (2022) — flash loaned tokens के साथ governance takeover के through $182M चोरी।

    3. Reentrancy Amplification

    Flash loans poorly protected protocols पर reentrancy attacks के लिए capital provide करते हैं।

    function amplifiedReentrancy() external {
    

    // 1. Large amount flash loan करें

    flashLoan(10000 ether);

    // 2. Vulnerable protocol में deposit करें

    vulnerable.deposit{value: 10000 ether}();

    // 3. Reentrancy exploit करें repeatedly withdraw करने के लिए

    vulnerable.withdraw(10000 ether);

    // Reentrancy deposited से ज्यादा drain करती है

    // 4. Flash loan repay करें

    lender.transfer(10000 ether + fee);

    // Excess रखें

    }

    4. Liquidation Manipulation

    Mass liquidations trigger करने के लिए collateral prices manipulate करें, फिर collateral को cheap में खरीदें।

    Real-World Flash Loan Attacks

    Harvest Finance (October 2020)

    • Stolen: $24M
    • Method: Curve pool price manipulation
    • Flash loan from: Uniswap (उस time कोई fee नहीं थी)
    • Result: Protocol survive किया लेकिन users ने funds खो दिए

    PancakeBunny (May 2021)

    • Stolen: $45M
    • Method: PancakeSwap पर price oracle manipulation
    • Impact: BUNNY token 96% crash हुआ

    Cream Finance (August 2021)

    • Stolen: $18.8M
    • Method: AMP token पर flash loan + price oracle manipulation
    • Repeat: Cream 2021 में 3 बार hack हुआ

    Beanstalk (April 2022)

    • Stolen: $182M
    • Method: Flash loan governance attack
    • Loans from: Aave ($1B borrowed)
    • Execution: Malicious proposal pass किया, treasury drain किया

    Euler Finance (March 2023)

    • Stolen: $197M (बाद में return किया)
    • Method: Debt tracking manipulate करने के लिए flash loan + donation attack
    • 2023 का largest DeFi hack

    Prevention Strategies

    1. TWAP Oracles (Time-Weighted Average Price)

    Spot prices उपयोग न करें। Time-weighted averages उपयोग करें जिन्हें single transaction में manipulate नहीं किया जा सकता।

    contract TWAPOracle {
    

    IUniswapV2Pair public pair;

    uint256 public priceAverage;

    uint256 public lastUpdate;

    uint32 public constant PERIOD = 10 minutes;

    function update() external {

    uint32 timeElapsed = uint32(block.timestamp - lastUpdate);

    require(timeElapsed >= PERIOD, "Too soon");

    (uint256 price0Cumulative, uint256 price1Cumulative,) =

    UniswapV2OracleLibrary.currentCumulativePrices(address(pair));

    priceAverage = (price0Cumulative - price0CumulativeOld) / timeElapsed;

    lastUpdate = block.timestamp;

    price0CumulativeOld = price0Cumulative;

    }

    function getPrice() external view returns (uint256) {

    return priceAverage; // Manipulation-resistant

    }

    }

    क्यों काम करता है: Flash loan attacks एक transaction में होते हैं। TWAP को कई blocks पर price changes चाहिए।

    Decentralized, external price oracles उपयोग करें जिन्हें on-chain trades के through manipulate नहीं किया जा सकता।

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

    contract SecureLending {

    AggregatorV3Interface internal priceFeed;

    constructor(address _priceFeed) {

    priceFeed = AggregatorV3Interface(_priceFeed);

    }

    function getLatestPrice() public view returns (int) {

    (

    uint80 roundID,

    int price,

    uint startedAt,

    uint timeStamp,

    uint80 answeredInRound

    ) = priceFeed.latestRoundData();

    require(timeStamp > 0, "Round not complete");

    return price;

    }

    }

    Benefits:

    • Multiple sources से data aggregated
    • Off-chain updated (flash loans के through manipulable नहीं)
    • Billions in TVL पर battle-tested

    3. Snapshot Governance

    DAOs के लिए, voting start होने से पहले block-based snapshots उपयोग करें।

    contract SecureGovernance {
    

    mapping(uint256 => uint256) public proposalSnapshots;

    function propose(/*...*/) external returns (uint256) {

    uint256 proposalId = proposalCount++;

    // Voting start होने से BEFORE snapshot

    proposalSnapshots[proposalId] = block.number;

    return proposalId;

    }

    function vote(uint256 proposalId, bool support) external {

    // Snapshot block पर balance उपयोग करें

    uint256 votes = govToken.balanceOfAt(

    msg.sender,

    proposalSnapshots[proposalId]

    );

    // Proposal creation के बाद flash loans count नहीं होते

    }

    }

    4. Execution Delays

    Instant execution prevent करने के लिए timelocks add करें।

    contract TimelockDAO {
    

    uint256 public constant DELAY = 2 days;

    struct Proposal {

    uint256 eta; // Earliest execution time

    // ...

    }

    function queue(uint256 proposalId) external {

    require(proposalPassed(proposalId));

    proposals[proposalId].eta = block.timestamp + DELAY;

    }

    function execute(uint256 proposalId) external {

    require(block.timestamp >= proposals[proposalId].eta);

    // Execute

    }

    }

    Flash loans को एक transaction में repay करना होता है, इसलिए वे 2 days wait नहीं कर सकते।

    5. Flash Loan Detection

    Sensitive functions के लिए flash loan usage block करें।

    contract FlashLoanProtected {
    

    mapping(address => uint256) private balanceSnapshot;

    modifier noFlashLoan() {

    uint256 balanceBefore = balanceSnapshot[msg.sender];

    // इस transaction में first interaction

    if (balanceBefore == 0) {

    balanceSnapshot[msg.sender] = token.balanceOf(msg.sender);

    } else {

    // Same transaction में balance spike नहीं होना चाहिए

    require(

    token.balanceOf(msg.sender) <= balanceBefore * 2,

    "Flash loan detected"

    );

    }

    _;

    }

    function sensitiveAction() external noFlashLoan {

    // Protected

    }

    }

    Note: इसमें false positives हो सकते हैं, सावधानी से उपयोग करें।

    Best Practices Summary

    Lending Protocols के लिए

    ✅ Chainlink या TWAP oracles उपयोग करें, spot prices कभी नहीं

    ✅ Price changes पर sanity checks implement करें

    ✅ Abnormal market conditions के लिए circuit breakers add करें

    ✅ Large position changes के लिए multi-block delays require करें

    DAOs के लिए

    ✅ Proposal creation पर balances snapshot करें

    ✅ Timelocks add करें (minimum 24-48 hours)

    ✅ Long-term holders से quorum require करें

    ✅ Last-minute governance attacks prevent करने के लिए vote delegation उपयोग करें

    सभी DeFi Protocols के लिए

    ✅ सभी price dependencies audit करें

    ✅ Flash loan attack scenarios के साथ test करें

    ✅ Unusual transaction patterns के लिए monitor करें

    ✅ Emergency pause mechanisms रखें

    ✅ Bug bounty programs maintain करें

    Conclusion

    Flash loans एक powerful DeFi primitive हैं जो capital तक access को democratize करती हैं — लेकिन वे exploits तक access को भी democratize करती हैं।

    Attacks flash loans खुद से caused नहीं होते, बल्कि underlying vulnerabilities से जिन्हें flash loans amplify करती हैं:

    • Weak oracles (TWAP या Chainlink उपयोग करें)
    • Instant governance (snapshots और timelocks add करें)
    • Reentrancy (guards उपयोग करें)
    • Unprotected liquidations (delays add करें)

    Bottom line: अगर आपके protocol को enough capital के साथ exploit किया जा सकता है, assume करें कि कोई वह capital flash loan करेगा।

    Solingo पर flash loan defense practice करें — हमारे exercises real attacks simulate करते हैं including oracle manipulation और governance takeovers, step-by-step defense implementation के साथ।

    Practice में लगाने के लिए तैयार हैं?

    Solingo पर interactive exercises के साथ इन concepts को apply करें।

    मुफ्त में शुरू करें