DeFi Vulnerabilities [2]

In the previous post, we talked about the traditional software exploits that exist in the realm of smart contracts and have a reputation of being the root cause of some big DeFi hacks in the recent years. In this article, we dive deeper into the DeFi landscape. To start, we’ll familiarize ourselves with key terms and definitions essential for understanding DeFi attacks. Following that, we’ll explore and analyze some well-known exploits and incidents, examining their root causes as well as the methods for mitigation and prevention.

1. Some DeFi concepts

1.1. Liquidity Pools

Liquidity pool is a collection of funds locked in a smart contract that facilitates trading, lending, and other financial activities in a decentralized fashion. Liquidity pools can contain various types of assets, including cryptocurrencies, stablecoins, and tokenized assets. Users, known as liquidity providers, add their funds to these pools. In return, they typically receive liquidity provider tokens (LP tokens) that represent their share of the pool. These tokens can be redeemed for the underlying assets at any time. LPs often earn fees from the trades that occur in their pool. This can be a form of passive income, as a percentage of the trading fees is distributed to the LPs based on their share in the pool. This practice is commonly referred to as yield farming or liquidity mining.

Since liquidity pools are governed by smart contracts, they are subject to risks such as bugs in the contract code or vulnerabilities that could be exploited.

1.2. Automated Market Making (AMM)

Automated Market Makers (AMMs) differ from traditional exchanges by not using an order book; traders interact directly with a smart contract for trades. This system allows for decentralized, permissionless trading without intermediaries. However, in AMMs, prices are algorithmically determined based on the ratio of assets in a liquidity pool, a key feature in many decentralized exchanges (DEXs).

AMMs use a mathematical formula, typically the constant product formula (x * y = k), to set asset prices for the liquidity pool. This formula ensures the product of the quantities of two different tokens in a liquidity pool remains constant, determining their relative prices.

1.3. Flash loans

Flash loans are a unique financial instrument in the Web3 and DeFi ecosystem. They allow users to borrow any available amount of assets from a liquidity pool without providing collateral, under one main condition: the loan must be borrowed and repaid within the same transaction block. Flash loans, which allow borrowing without collateral for a very short time, have been used in front-running attacks. An attacker borrows a large amount of assets, manipulates the market (e.g., by increasing the price of an asset on a DEX), and then profits from this manipulation, all within a single transaction block.

Here’s how flash loans typically work:

  1. Borrowing Without Collateral: Unlike traditional loans, flash loans don’t require the borrower to put up any collateral. This is possible because of the unique mechanics of blockchain transactions.
  2. Single Transaction Execution: The borrower takes out the loan and executes their intended operations (like arbitrage, swapping, or other DeFi strategies) within the same transaction. This might involve interacting with various smart contracts.
  3. Repayment in the Same Transaction: By the end of the transaction, the borrowed amount plus any associated fees must be returned. If the borrower fails to return the funds, the entire transaction is reversed as if it never happened, thanks to the atomicity of blockchain transactions. This means no change is made to the blockchain, effectively negating the risk of default for the lender.

1.4. Miner Extractable Value (MEV)

MEV, or Miner Extractable Value or Maximal Extractable Value, is a concept in the Web3 and decentralized finance (DeFi) ecosystem. It refers to the potential profit a miner (or validator, in proof-of-stake systems) can make through their ability to arbitrarily include, exclude, or reorder transactions within the blocks they produce.

1.5. Web3 Money Legos

Web3 Money Lego is a term that refers to the concept of web3 composability, where different financial services and products in the DeFi ecosystem can be combined and recombined like Lego blocks. This analogy is used to describe how various decentralized applications (DApps) and protocols can seamlessly integrate and interact with each other in the blockchain space, particularly in Ethereum and other smart contract-enabled blockchains.

Examples of how Money Lego work in DeFi:

  • Lending and Borrowing: Users can deposit their crypto assets into a lending protocol to earn interest, and these same assets can be used as collateral for borrowing in another protocol.
  • Yield Farming: Users can provide liquidity to a DEX’s liquidity pool and earn LP (Liquidity Provider) tokens, which can then be staked in another protocol to earn additional rewards.
  • Combinations for Arbitrage: Traders can leverage flash loans from one protocol to take advantage of arbitrage opportunities in another, all within a single transaction.
Created by: Dall.E

2. Cryptoeconomic Exploits

2.1. Oracle Manipulation

Oracles bridge off-chain real-world data with blockchain networks, providing essential information like asset prices in real-time for liquidity pools or other external data for the smart contracts. These smart contracts, which run on blockchain networks like Ethereum, are only as reliable as the data they operate on. The accuracy and integrity of this data are paramount for the proper functioning of DeFi platforms, which manage millions, if not billions, of dollars in assets.

Oracle exploits occur when attackers manipulate the data provided by oracles. Attackers typically execute these exploits by artificially inflating or deflating the value of an asset, often using methods like large-scale trading or flash loans, to alter the data being fed by the oracle to a smart contract. This manipulated data can then be leveraged to open under-collateralized loans or execute trades that would otherwise not be possible under normal market conditions. The impact of oracle manipulation is profound, as it not only leads to direct financial losses in affected protocols but also undermines the trust in the overall reliability and integrity of the DeFi infrastructure.

The vulnerability lies in the fact that hackers can manipulate the data relayed by oracles. This is possible because oracles primarily verify and relay external data, rather than being the source of the information themselves. A typical oracle exploit works like this: Initially, the attacker manipulates pools used as price oracles by a DeFi protocol. This is done by artificially inflating a token’s price through large-scale buying or swapping. The attacker uses the inflated price to open under-collateralized positions in lending pools connected to the manipulated oracle, allowing the hacker to extract more money than legitimately possible.

Real-world exploits
  1. Synthetix Trading Platform Exploit (2019): Synthetix, a trading platform, used the average of two data feeders as their aggregation method. An attacker manipulated one of these feeders, inflating the real price by 1000 times. This vulnerability in the mean aggregation method, which is highly sensitive to outlier data, led to a significant financial loss for Synthetix, amounting to several million dollars​​.
  2. MakerDao Incident on Black Thursday (2020): During the event known as Black Thursday in 2020, MakerDao experienced a critical issue where its data feeders couldn’t update their feeds due to extremely high network congestion. Once the feeds were finally updated after a significant delay, there was a large shift in the price. This sudden and substantial change in reported data caused massive liquidations that were not properly auctioned off, leading to significant losses​​.
  3. bZx Flash Loan Attack (2020): The lending and margin trading platform bZx fetched prices from KyberSwap, a decentralized exchange, to determine the amount of collateral needed for different crypto assets. An attacker exploited this system by using a flash loan to manipulate the sUSD/ETH exchange rate on KyberSwap. This manipulation led bZx to believe that the collateralized sUSD was worth much more than its real value, allowing the attacker to borrow ETH with insufficient collateral. The attacker profited by absconding with the borrowed ETH and unwinding other positions before repaying the flash loan. This incident highlighted the vulnerability of the KyberSwap oracle contract to manipulation, which was not fully understood at the time. In response, decentralized exchanges began to adopt more robust price oracle mechanisms, such as the Time-Weighted Average Price (TWAP) to prevent such manipulations
Mitigation tips
  1. Decentralized Oracles: Using multiple independent oracles to fetch data, reducing the impact of any single compromised oracle.
  2. Time-Weighted Average Prices (TWAP): Implementing TWAP to smooth out price feeds over time, making manipulation more difficult.
  3. Using On-Chain Data Where Possible: Reducing reliance on external data sources when on-chain data can serve the purpose.

2.2. Front-running

Front-running attacks in DeFi exploit the transparent nature of blockchain transactions, where attackers manipulate the order of transactions for profit. Front-running attacks can be performed with different techniques.

  • Displacement Attacks: Picture this: you’ve discovered a financial reward concealed within the labyrinth of Web3 financial graphs. Just as you’re about to submit a transaction to claim this bonus, an attacker, capable of mining blocks, intervenes. By offering a higher gas price, they can strategically position their transaction to be processed ahead of yours. In such a scenario, they could snatch away the reward that you initially uncovered.
  • Insertion Attacks: Known as “sandwich attacks,” involve placing transactions before and after the victim’s transaction. This is a specific type of front-running where an attacker sees a large pending transaction on a DEX and places two transactions – one before (buy) and one after (sell) the victim’s transaction. This “sandwiches” the victim’s transaction, allowing the attacker to profit from the price impact caused by the victim’s trade.
  • Suppression Attacks: In this form of attack, the attacker can congest the block with their own transactions, effectively blocking the victim’s transaction from being processed. Picture a scenario where you need to cancel an exchange offer before it gets liquidated, but an attacker’s actions prevent you from doing so. This tactic can result in various types of Denial-of-Service attacks.
Real-world exploits

In the world of Web3 and decentralized finance (DeFi), front-running attacks have become a significant concern due to the transparent and immutable nature of blockchain transactions. Here are some real-world examples of front-running attacks in the DeFi ecosystem:

  • Ethereum Gas Price Auctions: One of the most common forms of front-running in DeFi involves manipulating Ethereum gas prices. Traders or bots observe the transaction pool (mempool) for high-value transactions and then place their own transactions with a higher gas price to get them mined first. This was notably seen in decentralized exchanges (DEXes) where traders would front-run large trades to profit from price movements.
  • Uniswap and Slippage Manipulation: In one reported case on Uniswap, a decentralized exchange, a user noticed a large upcoming transaction and placed an order just before it, with a slightly higher gas price, to ensure their transaction was processed first. This front-running caused the original large transaction to experience more slippage (price movement), and the front-runner profited from the price difference.
  • Bancor Front-Running (2018): In 2018, a front-running attack was observed on the Bancor network, where a user exploited the price update mechanism. The attacker could see a large transaction about to be processed and executed a trade just before it, benefiting from the price difference.
Mitigation tips
  1. Commit-Reveal Schemes: Implementing commit-reveal schemes can ensure that transaction orders do not give away critical information.
  2. Using Private Transactions: Employing privacy solutions like zk-SNARKs to conceal transaction details until they are mined.
  3. Transaction Ordering: Randomizing transaction order or using protocols that mitigate the predictability of transaction inclusion can reduce front-running risks.

These attacks undermine the fairness and integrity of the network, leading to losses for regular users.

2.3. Rug-Pulls

Rug-pull events in the Web3 decentralized finance (DeFi) sector represent a significant and deceptive form of cyber threat. A rug-pull occurs when the developers of a DeFi project abruptly withdraw all their funds from the liquidity pool, absconding with the investors’ money. These incidents typically happen in the less regulated and more anonymous environment of blockchain technology, making them a prominent risk in the crypto world.

These events are often premeditated, where developers create a seemingly legitimate project, build trust among investors, and then execute the scam. They tend to happen in projects that lack transparency or have not undergone thorough audits. Rug-pulls not only result in substantial financial losses for investors but also damage trust in the DeFi ecosystem.

Real-world exploits
  1. IVY Rugpull: The IVY token experienced a rug pull resulting in a loss of $1.8 million. This involved liquidity removal and token sales, highlighting the deployer’s role in enabling the theft​​.
  2. FSL Rugpull: FSL token on PancakeSwap suffered a rug pull, losing $1.7 million. The deployer minted and transferred tokens to a scammer’s address, which were then sold and converted, complicating traceability​​.
  3. Eigenlayer (Fake Token) Rugpull: The fake EigenLayer token conducted an exit scam resulting in a loss of $835k through liquidity removals from PancakeSwap​​.
  4. Linea (Fake Token) Rugpull: LINEA, a copycat token, experienced a rug pull with a loss of $741k, involving liquidity removal from the UniSwap pool​​.
  5. MEME (Fake Token) Rugpull: The MEME token faced a rug pull leading to a $188k loss, with the deployer draining the UniSwap liquidity pool​​.
  6. BIGTIME Token Rugpull: BIGTIME token lost $169k in a rug pull, where the scammer distributed funds among multiple addresses after swapping tokens for WBNB​​.
Mitigation

Preventing rugpulls is challenging due to the pseudonymous nature of blockchain transactions. However, measures such as thorough vetting of project teams, understanding the liquidity locking mechanisms, and the use of smart contract audits can help mitigate the risk. Despite these efforts, the inherent risks of emerging and unregulated technologies like DeFi make rugpulls a persistent threat.

Created by: Dall.E

3. Observations

  • The DeFi ecosystem, while innovative, is fraught with vulnerabilities that have been exploited in numerous incidents. It’s crucial for the DeFi community to focus on enhancing security measures, including thorough code audits, secure price oracles, and vigilant monitoring to safeguard against these vulnerabilities.
  • Bridges are crucial for communication between blockchains but were often inadequately secured, leading to significant losses. Smart contract vulnerabilities were the primary source of exploitation, often due to errors in code or logic.
  • Most Web3-based attacks take more than an hour to complete, yet 98% of hacked protocol operators do not respond within the first hour, underscoring the need for real-time monitoring and rapid response capabilities.
  • Auditing smart contracts is common but not always sufficient. The same number of audited and non-audited protocols were hacked, indicating that audits alone cannot prevent hacks. Real-time monitoring is emerging as a necessary proactive security measure.
  • The industry needs to adopt proactive measures for smart contract monitoring, internal security procedures, and best practices to enhance the security of decentralized applications.

References

  1. Defining the Ethereum Virtual Machine for Interactive Theorem Provers. Springer. (2017) Link​​.
  2. Precise Attack Synthesis for Smart Contracts. arXiv. (2019) Link.
  3. SoK: Transparent Dishonesty: Front-running Attacks on Blockchain. arXiv. (2021) Link​​.
  4. Compositional Security for Reentrant Applications. arXiv. (2021) Link​​.
  5. Frontrunner Jones and the Raiders of the Dark Forest: An Empirical Study of Frontrunning on the Ethereum Blockchain. USENIX. (2021) Link
  6. On the Just-In-Time Discovery of Profit-Generating Transactions in DeFi Protocols. arXiv . (2021) Link.
  7. Quantifying Blockchain Extractable Value: How dark is the forest? arXiv. (2021) Link​​.
  8. DeFi hacks in 2022: Causes, cases & cautionary tales. blaize.tech.(2022) Link​​.
  9. Web3 Security in 2023: A Billion Dollar Problem. Hackernoon (2023) Link​​.
  10. De.Fi Rekt Report – $20,8m Funds Lost in October 2023: Top DeFi Scams and Exploits. de.fi (2023) Link​​.
  11. Lanturn: Measuring Economic Security of Smart Contracts Through Adaptive Learning. IACR (2023) Link​​.

Tagged in :

Mahdi Avatar

More Articles & Posts