Patch Thursday — Retrospecting Liquidation Fee Vulnerability in Perpetual Protocol

ChainLight
ChainLight Blog & Research
8 min readOct 5, 2023

Summary

On July 27, 2022, ChainLight reported a critical vulnerability in Perpetual Protocol through Immunefi. The vulnerability existed in the ClearingHouse contract’s liquidation logic, allowing the bypassing of the checks on bad debt occurrence. Although exploiting this vulnerability required a substantial amount of assets, the possibility of large-scale attacks on DeFi projects cannot be ruled out since the attackers with massive equity are present in the cryptocurrency ecosystem. At that time, cases of manipulating prices through so-called “highly profitable trading strategy” were depleting lending pools, resulting in the sequence of 8-figures exploits.

If the reported vulnerability had not been fixed, Perpetual Protocol’s Total Value Locked (TVL), approximately $22 million at the time of reporting (July 2022), could have been entirely drained through a few trials of attack. Currently, Perpetual Protocol has been secured from this vulnerability through our report. Through this article, we are sharing the logic of this vulnerability.

What is Perpetual Protocol?

source: https://perp.com/

Perpetual Protocol is a perpetual futures trading platform on Optimism. Users can take long or short positions in perpetual futures trading based on various cryptocurrencies, using leverage of up to 10x.

Optimism is a Layer 2 project for Ethereum, utilizing the technology of Optimistic Roll-up to save gas fees for transactions and provide high scalability.

Perpetual futures trading means trading rights to buy/sell the underlying assets at a specific price at a fixed expiration date, and perpetual futures trading refers to trades that do not have a fixed expiration date. It tends to track the asset price of the spot market.

Perpetual Protocol uses vAMM (virtual Automated Market Maker), an AMM built on the Uniswap V3 pool, to ensure that all transactions on the pool are executed using a special-purpose ERC-20 token called a virtual token, which is designed to circulate only within the Perpetual Protocol’s contracts and the Uniswap V3 pool. This structure ensures exclusive trading governed by exchange contracts without violating Uniswap V3’s BSL license.

Uniswap V3’s Business Source License (BSL) — BSL is a business license with an expiration period, allowing renewal upon updates. Uniswap introduced Business Source License 1.1 with the release of V3, restricting short-term usage for businesses and transitioning to open source after the license expires.

Thanks to Uniswap V3’s Concentrated Liquidity feature, users can experience minimal slippage due to the high capital efficiency of liquidity providers. Within Perpetual Protocol, users can trade tokens with leverage up to 10x or provide liquidity to individual token pairs.

Implementing On-Chain Leverage Trading and Related Issues

source: https://pixabay.com/vectors/leverage-money-proporsion-coins-4386208/

Leverage trading is considered a high-risk investment strategy due to the trading risks users encounter, such as high loss rates and liquidation risks. Therefore, trading with leverage requires a trader’s careful consideration.

To take a leverage position, users need to deposit collateral equal to the partial amount of value of the total traded amount, which is called the Initial Margin (IM). To avoid (forced) liquidation (covering — trading against the holding position), users must maintain the minimum amount of margin that exceeds Maintenance Margin (MM) in the margin account.

Implementation Challenges of Liquidation

To support leverage trading, DeFi protocols need to implement the liquidation function mentioned earlier without issues. There are two main challenges to ensuring the liquidation function works smoothly:

  • Determining the liquidation point
  • Selecting the entity to execute and the process for liquidation

1. Determining the Liquidation Point

Determining the liquidation point for unhealthy positions is relatively straightforward. Liquidation occurs when the value of margin + unrealized Profit and Loss (PnL) falls below the maintenance margin requirement.

However, determining the liquidation point in an on-chain environment is much more complex and challenging than traditional finance. High volatility of underlying assets leads to more frequent liquidations, and on-chain environments with low performance (e.g., Ethereum) produce difficulties in the determination of the liquidation point accurately at the exact moment. Although no perfect solution exists, Perpetual Protocol aims to mitigate this scalability issue through developing on Ethereum L2 chain, Optimism.

DeFi protocols apply various mechanisms to implement liquidation logic in on-chain environments. Depending on the implementation, protocols sell the total amount of collateral at once, or the partial amount to satisfy the maintenance margin. Setting the sell price of the collateral, protocols choose to trade in market price or the best limit price that makes the remaining margin nearly zero.

2. Selecting the Entity for Liquidation and the Process

Another challenge exists in selecting the entity to execute the liquidation. Persistent evaluation of the entire positions in on-chain environments is nearly infeasible due to the same issue with the liquidation point determination and the associated costs as executing liquidations incurs expenses. Several DeFi protocols incentivize off-chain actors to monitor and execute liquidations as Backstop Liquidity Providers (BLP). Unlike traditional financial systems, protocols should offer incentives directly to induce participation of the liquidators. Perpetual Protocol imposes a penalty of a portion of the liquidation amount as liquidation fees, and passes them to the liquidators as incentives.

3. Bad Debt-Related Attacks and Risks

When the liquidation system malfunctions, bad debt attacks can occur, leading to various risks. Those include an imbalance in PnL settlements and the protocol’s loss of profit.

Malicious debt refers to the debt incurred through the significant drop of the collateralized asset’s price within a short time, rendering it impossible to cover the value of issued positions. Protocols offering positions with highly volatile assets as underlying assets or collateral are exposed to a higher risk of bad debt occurrence. In contrast, high volatility of users’ positions can lead to bad debts as the required liquidity of the underlying assets for covering lacks, which also happened in Perpetual Protocol’s case.

Attackers can exploit bad debt in several ways. For example, by creating multiple accounts and performing cross-trading, attackers can produce significant losses to a group of users, shifting the burden entirely to the system.

To mitigate such attacks, Perpetual Protocol allows only approved and authorized accounts to perform the liquidation procedure for bad debt and imposes a penalty on the liquidated account as a liquidation fee, transferring it to the liquidator.

Vulnerability Description

Liquidation Fee-Related Vulnerability

Perpetual Protocol denies liquidation when the balance of the target account is negative to prevent intentional bad debt attacks. The accepted group of liquidity providers, Backstop Liquidity Providers (BLPs), are exceptionally allowed to execute liquidation in this case.

Unfortunately, Perpetual Protocol did not consider the liquidation fee that the liquidated user pays to the liquidator. In this scenario, if the account’s funds are insufficient to pay the liquidation fee, bad debt can be produced. Consequently, the protocol and users suffer losses due to the liquidation fee, paradoxically benefiting the liquidator.

To exploit this mistake, attackers can create a delta-neutral position intentionally and wait for significant price fluctuations to occur before liquidating the losing position. By manipulating market liquidity, the attacker aims to make the value of the target account close to zero after liquidation.

Attack Scenario

Perpetual Protocol compensates liquidators with 2.5% of the liquidation amount as a liquidation fee. When the account balance approaches zero after liquidation, the fee becomes bad debt, providing profits to the liquidator. Consequently, attackers can intentionally liquidate their positions and siphon the fee.

The attacker can follow these steps to exploit the protocol and steal its funds:

  1. Split $28 million (Protocol’s deposit cap — TVL) into three accounts.
  2. Choose the pair with the lowest liquidity for the attack, which needs the least effort for the liquidity manipulation.
  3. Add liquidity to the pair and promptly open 10x leveraged positions.(Account 1: Massive short position, Account 2: Small long position, Account 3: Massive long position)
    Note: At this stage, the attacker’s risk is minimal since a delta-neutral position is established by opening both long/short positions. This means the risk related to price volatility is mitigated.
  4. Wait for sufficient price fluctuations that incurs the liquidation of the long position.
  5. Provide liquidity at a carefully selected price (about -10% from Account 3’s entry price) and liquidate the Account 2’s position to manipulate the price range to include the selected price.
  6. Liquidate Account 3’s position and receive the liquidation fees.
    Note: The liquidation fee of Account 3’s position produces a bad debt, and the penalty becomes the attacker’s profit.
  7. Liquidate the remaining positions and withdraw all funds.
  8. The attacker’s potential profit from this attack is estimated to be about 10% of the initial investment, approximately $2.96 million.

While the required amount of assets to exploit the liquidation fee vulnerability in Perpetual Protocol is expected to be high. However, for some attackers who have already succeeded in significant fund theft from similar attacks in other DeFi protocols, it remains as a feasible option despite the high cost. Protocols must consider the possibility of attacks when the potential profit significantly outweighs the attack cost.

Impact

If this vulnerability is exploited, the attacker can generate profits equivalent to 10% * (attacker’s available assets — TVL) within a single attack, which is approximately $2.96 million based on TVL of about $28.6 million at the time of the report. In the scenario of 6 sequential attacks, up to 98% of the TVL could have been stolen.

Proof of Concept

Running 1 test for test/Contract.t.sol:ContractTest
[PASS] test() (gas: 12072036)
Logs:
initial accountValue (1): 13878416573031000000000000
initial accountValue (2): 200000000000000000000000
initial accountValue (3): 13878416573031000000000000
initial accountValue (total): 27956833146062000000000000
initial accountValue (total in USDC): 27956833.146062
currentTick: 4659
oraclePrice: 159700000

setupLargePositions()
tick: 4680
tick: 4739

simulatePriceMove()
targetTick: 4502
tick: 4710
tick: 4680
tick: 4646
tick: 4612
tick: 4578
tick: 4544
tick: 4510
tick: 4476
oraclePrice: 151715000

manipulatePriceLimitForNextBlock()
tick after partial liquidation of account 2: 3706

triggerLiqudationFeeBadDebt()
tick after full liquidation of account 3: 3606
accountValue (1): 30824545959434000000000000
accountValue (2): 67352661236000000000000
accountValue (3): -2986557798065000000000000
accountValue (total): 30891898620670000000000000

closeOutRemainingPositions()
final accountValue (1): 30924735356045000000000000
final accountValue (2): -33230438139000000000000
final accountValue (3): -2986557798065000000000000
final accountValue (total, negative values excluded): 30924735356045000000000000
final accountValue (total in USDC, negative values excluded): 30924735.356045
account 1 free collateral (USDC): 30921618.300402
profit (USDC): 2964785.154340
OK

✨ We are ChainLight!

ChainLight explores new and effective blockchain security technologies with rich practical experience and deep technical understanding. Our innovative security audits built upon such research proactively identify and eliminate various security risks and vulnerabilities in the Web3 ecosystem. To ensure continuous security even after the audit, we provide a digital asset risk management solution using on-chain data monitoring and automated vulnerability detection services.

ChainLight serves to guide and protect all users of decentralized services, lighting the way for a safer Web3 ecosystem.

  • Want to see more from the ChainLight team? 👉 Check out our Twitter account.

🌐 Website: chainlight.io | 📩 TG: @chainlight | 📧 chainlight@theori.io

--

--

ChainLight
ChainLight Blog & Research

Established in 2016, ChainLight's award-winning experts provide tailored security solutions to fortify your smart contract and help you thrive on the blockchain