Post

Decentralized Exchanges - A Security researcher's guide


Introduction

The fundamental basis of trade has always been the exchange of goods or commodities. The first examples of trade revolved around the barter system which involved the direct exchange of goods like rice for wheat or food for cattle, etc. As we evolved and along with us the idea of economics too, we resorted to more complex versions of this trade that involved currencies. Currencies do not have any value of their own but facilitate seamless exchange of goods and commodities. So, now when we want to trade we trade our desired commodity for currency, and the seller in turn exchanges that currency for his desired commodity and so on. In modern finance we don’t only exchange food and cattle but things like shares of companies, futures, options and even currencies. To handle the massive volume of trades we have developed exchanges that use electronics to control and secure the trades. The price of the assets are defined using the simple logic of supply and demand. As we move on to more recent versions of finance, we enter the blockchain space and decentralized finance which also uses exchanges for the trading of digital assets like cryptocurrencies, NFTs, stablecoins, etc. But a user is given the choice of a centralized and a decentralized exchange. A centralized exchange which is very similar to it’s counterparts in traditional finance employs an intermediary who is a central authority and offer custodial services, meaning the users can store their funds in the exchange’s wallet that promise ease of trading but also requires trusting their security practices. On the other hand, a decentralized exchange popularly known as a DEX simply connects buyers and sellers without the need of an intermediary and facilitates exchange by using liquidity pools. In this article, we will dive into the details of how decentralized exchanges work and the common vulnerabilities surrounding them.

What is a Decentralised Exchange?

A decentralized exchange or DEX is a platform that facilitates peer-to-peer trading of digital assets without relying on a central authority or intermediary. It operates on blockchain technology, using smart contracts to automate transactions and ensure security. Unlike centralized exchanges, DEXs give users full control over their funds, as no third party holds custody of assets. Although this enhances privacy and reduces the risks associated with centralization it relies on a more active role from the users and is often associated with problems like lower liquidity, slippage, etc.

How does a DEX work?

Understanding how a decentralized exchange works can be quite a daunting task. A DEX uses various complex concepts that are converted into a number of smart contracts.

1. Liquidity Pool Contract

  • Liquidity pools are smart contracts holding reserves of token pairs (e.g., ETH/USDT).
  • Liquidity providers or LPs deposit equal value of two tokens into the pool, receiving liquidity tokens as proof of their contribution.

2.Automated Market Makers

  • Smart contracts implement pricing algorithms generally known as Constant Function Market Makers or CFMMs like the Constant Product formula that ensures the available amount of x and y tokens always multiply to a constant value k. Find more details on AMMs in my blog.
  • Users invoke a swap function, specifying input/output tokens and amounts.
  • The transaction is validated and the output amount is calculated using the CFMM formula.
  • Tokens are transferrred from the pool to the user.

3. Liquidity, Withdrawl and Fees

  • LPs interact with the smart contract by either adding liquidity or removing liquidity by withdrawing their funds.
  • Adding liquidity involves transferring tokens to the pool and minting liquidity tokens for the LP. While, removing liquidity burns liquidity tokens and returns underlying tokens plus earned fees to LPs.

4. Router contract and multihop trades

  • DEXs often include a router contract to simplify user interactions.
  • For trades between tokens without a direct pool, the router facilitates multi-pool swaps (e.g., Token A → Token B → Token C). But this can icrease gas costs considerably.

These are some of the fundamental bulding blocks of a DEX but much more goes on in the background to make it work properly.

Common Vulnerabilities and Security Pitfalls

Decentralized Exchanges being one of the most popularly used protocols are subject to numerous attacks. Over the years we have learnt how to deal with some of them.

1. Sandwich Attacks

A sandwich attack is a front-running scheme where an attacker places orders on both sides of a target transaction to manipulate the price.

Attack Mechanism :

  1. Attackers continuously monitor the mempool, which is a pool of pending transactions waiting to be processed on the blockchain. They look for large or profitable transactions that they can exploit.
  2. Once a target transaction is identified, the attacker front-runs it by submitting a buy order for the same asset before the victim’s transaction is executed. This order is placed with a higher gas fee to ensure it is processed first. By purchasing the asset at a lower price, the attacker effectively drives up its price.
  3. After the attacker’s buy order is executed, the victim’s transaction goes through. However, due to the price increase caused by the attacker’s earlier buy, the victim receives fewer tokens than expected because their order fills at a higher price.
  4. Finally, the attacker submits a sell order for the asset they just acquired at this inflated price. This is known as back-running. It completes the sandwich, allowing them to profit from the difference between their purchase and sale prices.

Example :

In April 2023, Uniswap fell victim to a sophisticated sandwich attack that resulted in the theft of approximately $25.2 million from eight liquidity pools. This exploit involved a rogue Ethereum validator who had deposited 32 ETH into the network just 18 days prior to executing the attack. The attacker utilized a Maximum Extractable Value (MEV) bot to orchestrate the sandwich attack, effectively replacing several automated trades to profit from the manipulation of asset prices. The mechanics of the attack involved two main transactions: a front-run transaction where the attacker bought assets before the victim’s transaction, and a back-run transaction where they sold those assets immediately after, capitalizing on the price increase caused by their initial purchase. The stolen assets included significant amounts of wrapped Ethereum (WETH), USDC, USDT, Wrapped Bitcoin (WBTC), and DAI stablecoins.

Mitigation :

  1. Setting lower slippage tolerances can help minimize potential losses from price manipulation.
  2. Some platforms offer options for executing trades off-chain or through private channels that are not visible in the public mempool, reducing exposure to front-running bots.
  3. Educating users about how sandwich attacks work can help them recognize and avoid situations where they might be vulnerable.

2. Oracle Manipulation

In blockchain technology, an oracle acts as a bridge between on-chain smart contracts and off-chain data sources, providing essential information such as asset prices, weather data, or other real-world events. They enable smart contracts to execute based on external inputs. Oracle manipulation is one of the most prevalent attack vectors in decentralized finance (DeFi). Attackers can manipulate price data on DEXs by exploiting vulnerabilities in price oracles, particularly if the DEX relies on a single source for price feeds.

Attack Mechanism :

  1. Attackers first identify which oracle a DeFi protocol relies on for price feeds. Oracles can be centralized, i.e. relying on a single source or decentralized, i.e. aggregating data from multiple sources. Centralized oracles are particularly vulnerable to manipulation.
  2. Once the target oracle is identified, attackers manipulate the price data it provides. This can be achieved through various methods. Flash Loans : Attackers often use flash loans to borrow large amounts of cryptocurrency temporarily without collateral. They can quickly inflate the trading volume of low-liquidity tokens, causing significant price increases. Market Manipulation : By executing large trades, attackers can create artificial demand for a token, leading to price spikes that do not reflect the broader market conditions.
  3. After manipulating the price data, attackers can exploit the affected DeFi protocol’s smart contracts. For example: They may use inflated asset prices as collateral to borrow more assets than they should be able to. Alternatively, they can exchange their artificially inflated holdings for more stable assets, profiting from the discrepancy between the manipulated and actual market prices.

Example :

Uwulend was a victim of an Oracle Manipulation attack on 10th June, 2024. Find the complete casestudy and more details about oracle-manipulation attacks in my post-mortem of the attack.

Mitigation :

  1. Using decentralized oracles that aggregate data from multiple sources makes it harder for attackers to manipulate prices significantly.
  2. Implementing Time-Weighted Average Price (TWAP) mechanisms helps smooth out price fluctuations over time, reducing the impact of single transactions on reported prices.

3. Other Security risks

Other than sandwich attacks and oracle manipulation attacks, DEXs are subject to various security risks revolving around slippage, front-running, rug pulls, re-entrancy, upgradeability issues, etc. The mitigation strategy to avoid these should be subjecting the protocol through comprehensive security audits and also mainitianing security best practices while writing the smart contracts.

Conclusion

In this constantly evolving world of defi, DEXs play a pivotal role in the advent of blockchain technology. Steering away from tradfi would be difficult without these. It falls upon us as developers and security researchers to take extra care when writing and auditing smart contracts for DEXs, keeping in mind what we have learnt from past incidents.

Additional Resources

  1. Sandwich attack on Uniswap
  2. Uniswap protocol
  3. Blog on AMMs
  4. Post-mortem of the Uwulend attack
This post is licensed under CC BY 4.0 by the author.