Typical vulnerabilities in lending and CDP protocols

Polgemy
Decurity
Published in
13 min readMay 22, 2023

--

Introduction

This article explains the security of a popular pattern in the decentralized finance — the CDP (collateralized debt position). We will analyze the basics of CDPs and how they work. We will consider the features by which CDP protocols are classified. Then, we will analyze typical bugs found in audits and real hacks. Finally, we will provide a checklist that auditors can use for the security audits of the CDP protocols.

What is CDP?

A collateralized debt position (CDP) is a financial pattern that has been adopted by DeFi from the classical financial market. The MakerDAO team was the first to implement the CDP system in DeFi when they released the DAI stablecoin. In order to issue DAI, users are required to lock crypto assets on smart contracts worth more than the value of the issued DAI.

CDP systems offer several advantages:

  1. Decentralization: All business logic is implemented on smart contracts, eliminating the need for a centralized authority to manage liquidity and debt.
  2. Scalability and flexibility: Users have the flexibility to utilize various assets as collateral, expanding the range of options available.
  3. Capital efficiency: With a healthy volume of borrowers and lenders, the Total Value Locked (TVL) is utilized effectively, making capital usage efficient.

In DeFi, the CDP system is primarily employed in two types of protocols: lending and stablecoins. The main distinction between them lies in how they operate:

  1. In stablecoin systems users create new tokens by depositing collateral. The deposited collateral serves as a backing for the minted stablecoins.
  2. In lending systems users borrow assets from a pool that is formed by creditors. The collateral provided by the borrowers acts as security for the loans.

As of now, the Total Value Locked (TVL) of lending and CDP protocols is estimated to be $23.6 billion, surpassing the TVL of Liquid Staking, DEX, and Bridge protocols.

Source: https://defillama.com/categories

How it works?

Source: https://dev.to/yos/decentralized-finance-explained-211o

Let’s analyze the main scenarios of user interaction with CDP protocols.

Scenario 1: User Provides Collateral

In contrast to the traditional financial market, DeFi requires users to provide collateral in order to obtain a loan (excluding protocols with uncollateralized loans). The user cannot receive funds solely based on their reputation; instead, they must provide a deposit. Furthermore, the value of the collateral should be higher than the value of the borrowed funds. This ensures that the protocol maintains financial equilibrium in the event of a decrease in the value of the collateral. The ratio between the value of the collateral and the value of the debt is known as the Collateral Ratio (CR).

Scenario 2: User Closes Position

When a user decides to close their position, they need to return the borrowed assets to the protocol. However, fees in the form of interest are accrued on the debt during the borrowing period. The interest rate can be either fixed or variable, depending on the protocol. The fees collected through the interest rate are then distributed among the creditors of the pool.

Scenario 3: Liquidation of Collateral

When the value of the collateral falls below a certain threshold, the user’s collateral is subject to liquidation. Liquidation is a significant risk in DeFi systems. There are several types of liquidation:

  1. Instant Liquidation: This method involves the immediate sale of the collateral at its market value. It is typically used in protocols where the collateral and debt have equal values.
  2. Auction Liquidation: In this method, the collateral is sold through an auction process. It is employed in protocols where the collateral and debt have different values.
  3. Partial Liquidation: This method involves the sale of only a portion of the collateral to cover the outstanding debt. It is utilized when the value of the collateral exceeds the value of the debt.

These liquidation methods aim to mitigate the risk for the protocol and ensure the lenders are repaid even if the collateral value declines.

To prevent a scenario where the value of the collateral falls below the value of the debt, leading to protocol insolvency, the liquidation process is triggered when the Collateral Ratio exceeds a certain threshold, typically defined as (100 + liquidation bonus)%.

In order to incentivize liquidators to participate in the liquidation process, protocols offer a liquidation bonus. The liquidation bonus is a profit expressed as a percentage of the value of the collateral that is liquidated. This bonus serves as a motivation for individuals or entities to actively engage in the liquidation process and helps maintain the financial stability of the protocol.

Scenario 4: User Provides Liquidity

Users have the option to supply liquidity to CDP protocols by depositing their funds into a shared pool. In return, they receive an interest rate on their deposited funds. The interest earned is distributed among the creditors of the pool based on the amount they have deposited and the duration of their deposit.

The interest rate in CDP protocols can be variable and is calculated using an algorithm that considers the utilization ratio. The utilization ratio is the ratio between the number of assets borrowed and the amount available for lending within the pool. When the utilization ratio reaches a critical value, the interest rate experiences a sharp increase.

This mechanism serves two purposes. First, if the protocol requires additional liquidity, it encourages creditors to supply liquidity by offering a higher Annual Percentage Rate (APR). Second, it motivates borrowers to close their CDPs since they would be paying a higher interest rate for maintaining ownership of their loans.

Source: https://docs.perennial.finance/mechanism/funding-rate-and-utilization-curve

CDP Features

CDP protocols can be classified based on various features. Let’s explore some of these features:

  1. Collateral Type:
  • ERC20 Tokens: This category includes popular ERC20 tokens with significant daily trading volume and sufficient liquidity. These tokens are chosen based on the assumption that their liquidity and trading volume help mitigate volatility, making them suitable as collateral. Examples of such tokens include LINK, WBTC, ETH, DAI, USDT, USDC, and BNB.
  • ERC721 Tokens: Some protocols allow the use of non-fungible tokens (NFTs) as collateral. These NFTs, typically sourced from popular collections, exhibit relatively stable prices and limited susceptibility to manipulation. Examples of collections include Bored Ape Yacht Club (BAYC), Mutant Ape Yacht Club (MAYC), Otherdead, and Azuki.
  • DEX LP Tokens: CDP protocols may also accept liquidity provider (LP) tokens obtained from decentralized exchanges (DEXs) as collateral. These LP tokens represent ownership rights over token pairs within the liquidity pool. As these tokens hold value, they can be utilized as collateral. Examples include ETH-DAI LP and ETH-WBTC LP.
  • Compound cTokens or Aave aTokens: Tokens issued to creditors as a result of depositing funds in a CDP can also serve as collateral. These tokens are typically issued by platforms like Compound or Aave.

2. Oracle Type:

  • ChainLink: ChainLink has gained significant popularity in the DeFi space due to its reliability and ease of integration. ChainLink data feeds provide price information for over 190 token pairs and 14 collections of NFTs. Its extensive coverage and trusted reputation make it a preferred oracle choice for many CDP protocols.
  • TWAP Oracles: Time-Weighted Average Price (TWAP) oracles calculate a weighted average price from Automated Market Maker (AMM) DEX protocols. However, unlike ChainLink, TWAP oracles rely on data from a single AMM DEX to determine the price. It’s important to note that TWAP-derived prices may not always be the most up-to-date due to the time range considered for averaging.
  • Virtual Price (amountTokenA/amountTokenB): In certain cases, some protocols consider the price as the ratio of the quantity of Token A to the quantity of Token B. An example of this is the share/token price. However, it’s crucial to exercise caution when auditing protocols that rely on such virtual price calculations, as they can introduce vulnerabilities if not implemented properly.

3. Market type:

  • Isolated Markets: In isolated markets, borrowers can only provide one token to borrow another token. Lenders can only provide liquidity in specific token pairs. Each token pair operates independently, and the risks associated with hacking or insolvency apply to each pair separately. Examples of isolated markets include MIM, DAI, and Silo Finance.
  • Cross-Collateral Lending Markets: In cross-collateral markets, borrowers can borrow multiple tokens by depositing a single collateral token. Unlike isolated markets, creditors contribute their tokens to a shared pool. Consequently, the risk of default applies to all creditors regardless of the specific token deposited. Examples of cross-collateral lending markets include Aave, ParaSpace, and Compound.
  • Hybrid Markets: Hybrid markets allow borrowers to have flexibility in borrowing and depositing assets without strict limitations. However, these markets often require tokens from a whitelist to be used as collateral. These whitelisted tokens typically exhibit higher liquidity in the market and are less prone to manipulation.

4. Interest rate:

  • Fixed Interest Rate: With a fixed interest rate, the rate remains constant throughout the entire loan period and is not affected by market conditions. This provides creditors with a predictable payment at a stable Annual Percentage Rate (APR). Borrowers and lenders can rely on a consistent interest rate without being subject to market fluctuations.
  • Variable Interest Rate: In contrast, a variable interest rate fluctuates over time and is influenced by market conditions, typically tied to factors such as the utilization ratio. The interest rate can increase or decrease based on the state of the market. Some protocols offer users the option to borrow at both fixed and variable interest rates, providing flexibility to choose the most suitable option based on their preferences and risk appetite.

5. Type of liquidation:

  • Auction Liquidation: In an auction-based liquidation, multiple liquidators compete by offering prices for the collateral being liquidated. This competitive process reduces the profit for the liquidator and increases the remaining collateral. There are different types of auctions, such as English or Dutch auctions. Liquidation through an auction is generally considered the fairest method as it allows for market-driven pricing.
  • Full Liquidation: In a full liquidation, the entire debt of the borrower is closed, and the liquidator takes possession of all the collateral associated with the CDP. This means that the liquidator collects all the assets to cover the outstanding debt and any associated fees.
  • Partial Liquidation: In the case of partial liquidation, only a portion of the collateral held by the borrower is transferred to the liquidator. This method is used when the liquidated collateral is more valuable than the outstanding debt. The liquidator retrieves a portion of the collateral to cover the debt, while the remaining collateral remains with the borrower.

6. Collateral Usage

In some CDP protocols, users have the option to contribute their collateral to third-party protocols in order to generate additional Annual Percentage Rate (APR) rewards. By utilizing these third-party protocols, users can potentially earn extra rewards on top of their existing collateral. However, it’s important to note that this practice carries inherent risks.

Analysis of Bugs in Audits and Hacks of CDP Protocols

CDP protocols have experienced many hacks in the past. Below is an analysis of bugs found in audits and notable hacks. Additionally, a checklist to assess the security of a CDP protocol will be provided, aligning protocol features with corresponding security considerations.

0VIX Protocol Hack (April, 2023)

0VIX is a fork of the Compound protocol on the Polygon network. 0VIX provides a market for 13 tokens, including the vGHST token, which is the vault governance token of the AAVEGotchi protocol. The Oracle obtains the price of vGHST/GHOST through the convertVGHST method, which calculates the price by calling the balanceOf() function of vGHST tokens. The attacker manipulated the price using a flashloan. It’s a red flag if you see balanceOf() in the price calculation method trace, which was spotted by the hacker.

Euler Finance Hack (April, 2023)

Euler Finance is a lending protocol that supports more than 100 tokens. The eToken.sol contract allowed the issuance of an unlimited quantity of tokens for any value of collateral, simultaneously increasing the number of debt tokens (dToken). This means that users could charge themselves with as much collateral as they wanted while increasing their debt. Additionally, the protocol allowed for the donation of assets to the market reserve through the eToken’s donateToReserves function. The mistake was that there was no check on the health ratio of the position in this function. This oversight, combined with the ability to accrue collateral, resulted in the potential for liquidating a position with a substantial profit.

ParaSpace Hack (March, 2023)

ParaSpace is a lending protocol that allows users to collateralize their positions with NFTs from top collections. Additionally, the protocol allowed for collateralizing positions with APE tokens, which were staked on the official Yuga Labs contract from the protocol’s contract address. Instead of receiving APE tokens, users received cAPE tokens. The cAPE balance on any address was calculated based on the user’s share from the ParaSpace staking pool multiplied by the total number of APE tokens locked by the protocol.

The mistake in the system was that the total number of APE tokens staked by the protocol could be manipulated. This was possible because the APE staking contract from Yuga Labs allowed deposits from any address to any address. Taking advantage of a flashloan, the attacker manipulated the total number of APE tokens locked in the protocol, thereby altering their cAPE balance.

Warp Finance Hack (December, 2020)

Warp Finance is a cross-collateral lending protocol that allowed users to collateralize their positions with UNI LP tokens. The value of the LP tokens was calculated based on the formula: tokenA_Price * tokenA_Amount_In_Pool + tokenB_Price * tokenB_Amount_In_Pool. To determine the quantities of TokenA and TokenB, the protocol used the getReserves() function.

However, a vulnerability in the system allowed the attacker to manipulate the collateral price using a flashloan. By exploiting this vulnerability, the attacker was able to manipulate the prices of TokenA and TokenB, thereby impacting the value of the collateralized LP tokens.

Inverse Finance Hack (June, 2022)

Inverse Finance is a lending protocol that operates with hybrid markets. It allowed users to utilize its low-liquid governance token, INV, as collateral. Notably, this hack did not involve any smart contract bugs. The protocol relied on the Time-Weighted Average Price (TWAP) with a small time window for pricing.

The attacker employed a strategy that involved sending 400 ETH to 200 externally owned addresses (EOAs). These addresses were later utilized to exploit arbitrage opportunities as the TWAP increased the price of INV. Subsequently, the attacker collaterized a CDP with INV tokens and borrowed a significant amount of liquidity.

In lending markets, the focus is primarily on the price of an asset rather than its liquidity. This created an opportunity for the attacker to artificially inflate the price of a token with a relatively low market capitalization, making it eligible for lending with a smaller value. By leveraging this strategy, the attacker was able to deposit the inflated token as collateral and borrow assets with a significantly higher value, bypassing the usual liquidity considerations.

ParaSpace Audit (November, 2022)

  • An auditor identified a vulnerability associated with the transfer of NFTs from the CryptoPunks collection. It was discovered that the CryptoPunks collection was created before the establishment of the ERC721 standard and does not possess traditional methods such as transferFrom(). As a result, when depositing collateral into the protocol using tokens from the CryptoPunks collection, an attacker can backrun the transaction and transfer the tokens to their own address. When calling the offerPunkForSaleToAddress() method in the CryptoPunks collection contract, attacker can intercept the ownership of the token by backrunning the transaction if there is no sender verification.
  • An auditor identified a vulnerability related to the acceptance of UNI LP tokens as collateral. It was discovered that the protocol did not account for the possibility of multiple UNI LP tokens representing the same pair but with different fees. This oversight can lead to potential issues as one of the pairs may have low liquidity and be susceptible to manipulation.
  • The calculation of the token cost through the square root utilized a fixed divisor. However, this approach did not consider the possibility that tokens may have varying decimal places.
  • It was discovered that a user can call the setAuctionValidityTime() method during the liquidation, which can invalidate the ongoing auction if their Health Factor is greater than 1.5. However, the problem lies in the fact that the health factor check and the auction validity time setting occur within a single transaction. By utilizing a flashloan, an attacker can borrow a large amount of funds within a single transaction and use it to artificially increase their Health Factor above the required threshold. This manipulation can then be used to invalidate the ongoing auction.

Debt DAO Audit (November, 2022)

The auditor found a problem of insufficient validation of user arguments in the close() function. The bug allows the borrower to close the loan without paying the debt.

Y2K Finance Audit (September, 2022)

Protocol contract used the Oracle Peg to obtain asset prices. The problem was that the contract considers the prices of such pairs as stETH/ETH, WBTC/BTC, FRAX/MIM as constant, without taking into account the possible depeg.

Inverse Finance Audit (October, 2022)

During the audit, a non-compliance issue with the checks-effects-interactions pattern was identified in the withdrawInternal() function. When a position is collateralized with an ERC777 token, the user had the ability to withdraw the collateral while retaining their credit.

Yield Audit (July, 2022)

During the audit, a bug was discovered in the auction() function related to insufficient verification of user data. If the user specifies the address(0) as the payment address for the Liquidation Bonus, the transfer of tokens will always revert.

Another bug related to liquidation was identified in the _calcAuction function. The bug is associated with the incorrect calculation of the liquidated share.

Tigris Trade Audit (December, 2022)

Tigris Trade allowed users to deposit collateral in one stablecoin and withdraw it in another. However, the auditor discovered an arbitrage problem. For example, a user could deposit a depegged stablecoin worth 0.95 USD and withdraw a fully pegged stablecoin worth 1 USD. As a result, the protocol would suffer a loss of 0.05 USD per eatch token.

Canto Audit (September, 2022)

This bug is similar to the previous one. The auditor found that the protocol incorrectly considers the prices of the cUSDC and cUSDT tokens to be the same during a deposit, which is incorrect. This issue can be observed in an example like the one mentioned in the article here, where the protocol incurred significant losses due to a stablecoin depegging.

Astaria Audit (October, 2022)

During the liquidation auction, bids were accepted in the form of token transfers to a contract. If one liquidator interrupts the bid of another, the previous bid was supposed to be returned to the address of the interrupted liquidator. However, a bug was discovered in the cancelAuction() function, which resulted in the last bid not being transferred back to the liquidator, causing the funds to be blocked in the contract.

The checklist

There are way more CDP protocols and bugs which would not fit in this article. We have studied many of them and created a checklist to assist auditors when auditing CDP protocols.

You can find the checklist for the collateralized debt position protocols here: https://github.com/Decurity/audit-checklists/blob/master/cdp.md

We are planning to add more DeFi primitives to the “audit-checklists” repository so that auditors will be able to adapt their audit methodology according to the particular DeFi class.

--

--