Back to all stories
Reports
Educational
Lending Contract Exploits: A Retrospective
9/27/2023
Lending Contract Exploits: A Retrospective

TL;DR

• DeFi lending protocols operate similarly to traditional finance but use smart contracts, leading to unique vulnerabilities.

• Euler Finance and Platypus Protocol exploits highlighted the lack of solvency checks in specific functions, leading to large-scale losses. In Euler's case, a complex scheme involving recursive borrowing and flash loans led to a $200 million loss.

• Price oracles, crucial for validating asset prices, have their own set of vulnerabilities. BentoBox and Rodeo Finance suffered from outdated or manipulated pricing data, impacting the protocols' solvency checks.

• The concept of "stacked external dependency" was illustrated through the thwarted ParaSpace exploit, where multiple secure components, when combined, led to unforeseen vulnerabilities.

Introduction

The rapid pace of innovation in DeFi demands equally advanced security measures to counteract vulnerabilities, particularly as interoperability among projects can create hidden risks.

Exploits of lending protocols often lead to substantial losses. The average losses incurred are second only to exploits targeting cross-chain bridges.

In traditional finance, lenders provide funds in return for interest on their deposits, while borrowers pay interest for immediate access to funds. DeFi lending operates on the same principle, but uses smart contracts. This approach means DeFi is accessible to everyone without the need for personal details or trusting a third party to hold funds.

Screenshot 2023-09-27 at 5.25.41 PM

Users who want to become lenders supply their tokens to a money market and receive interest on their tokens according to the platform’s current supply annual percentage yield (APY). The supplied tokens are sent to a smart contract and become available for other users to borrow. In exchange for the supplied tokens, the smart contract issues other tokens that represent the supplied tokens plus interest. These tokens are called cTokens in Compound and aTokens in Aave and they can be redeemed for the underlying tokens.

The number and quality of these tokens held by the borrowers also limit how much can be borrowed. If a user decides to borrow funds, the value of the borrowed amount must always stay lower than the value of their collateral. If this condition holds there is no limit on how long a user can borrow funds for. If the value of the collateral falls below the required collateral level, the user would have their collateral liquidated in order for the protocol to repay the borrowed amount.

CertiK analysts have examined 39 exploits against lending contracts in 2023 and identified 22 code vulnerabilities, 12 price manipulations, and five private key compromises. Some design defects are common amongst the largest lending contract attacks.

While some of the projects started as forks of Aave and Compound, innovative features were later added to promote accessibility and yield. Although many of the original projects have undergone security reviews, the external dependencies that forked projects add expose the protocols to new types of vulnerabilities.

Screenshot 2023-09-27 at 5.28.32 PM

Lending Contract Exploit Examples

  1. Vulnerable Functions Called to Circumvent Checks on Solvency (Euler, Platypus)

Euler Finance

The fundamental principle of any lending economic model is maintaining a balance between the assets deposited as collateral and the debt generated through loans. This balance serves as an indicator of the project's solvency—its capability to fulfill long-term financial obligations and sustain operations. To ensure this, rigorous validation of each user's solvency is essential before permitting any asset withdrawals. Failure to do so can lead to liquidity issues and eventual breakdown of the protocol.

Two leading protocols in the lending sector, Compound and Aave, address this requirement in distinct ways. Compound relies on a comptroller contract that is invoked during high-risk operations to revert transactions deemed overly risky. In contrast, Aave uses a debt token to monitor the user's borrowing activities. This token can only move in conjunction with the borrowed assets and after passing multiple checks. Both methods contribute to the secure management of funds by making sure that liquidity outflows are scrutinized for solvency, a standard that Compound implemented following audits in 2020.

The most significant exploit of 2023, against Euler Finance, underlines the vital importance of these checks. Euler operates as a non-custodial protocol on the Ethereum blockchain, allowing users to lend and borrow cryptocurrency. On March 13, 2023, the protocol was compromised, resulting in a loss nearing $200 million. The attacker executed a complex scheme involving recursive borrowing, underpinned by 30 million DAI obtained through a flash loan. This loan was secured using Euler's unique mint() function, exemplifying how flash loans—quick loans that are both taken and repaid within the same transaction—can be used in such exploits.

Screenshot 2023-09-27 at 5.35.06 PM

The attacker then executes the vulnerable _donateToReserve() function to leave the position insolvent.

Screenshot 2023-09-27 at 5.36.44 PM

The _donateToReserve() function lacked a proper check of the user’s collateralization status. The attacker then liquidates the leveraged insolvent position and profits from the liquidation bonus.

Screenshot 2023-09-27 at 5.36.54 PM

Platypus Protocol

On February 16, Platypus Protocol fell victim to a $9 million exploit. The protocol offers a novel form of open liquidity via StableSwap, an automated market maker geared towards stablecoins. Implemented as a series of smart contracts, Platypus is designed to emphasize censorship resistance, security, self-custody, and optimal capital efficiency.

The vulnerability originated in the _emergencyWithdraw function of the MasterPlatypusV4 contract. This function was programmed to validate only whether a user's borrowed assets surpassed their borrowing limit before transferring all deposited assets back to the user. Critically, it did not account for the volume of assets the user had already borrowed.

Screenshot 2023-09-27 at 5.40.19 PM

As a result, the attacker was able to borrow up to the allowed limit and then exploit the _emergencyWithdraw function to withdraw all the assets they had deposited.

In both Euler Finance and Platypus Protocol, the vulnerabilities lie not in the primary functions such as deposit, withdraw, borrow, repay, or liquidation, but in supplementary methods. Whether due to negligence or convenience, these methods lacked comprehensive solvency checks.

  1. External Dependencies for Prices (BentoBox / Rodeo Finance)

The validation of external price dependencies is heavily reliant on external price oracles, which supply real-time pricing data used to calculate collateral-to-debt ratios. Price oracles serve as gateways, enabling decentralized Web3 platforms to access external data, legacy systems, and complex calculations. Given that the data oracles deliver directly influences the outcomes of smart contracts, the accuracy and reliability of these oracles are of utmost importance for contracts to function as intended. The ideal price data should be decentralized, accurate, and supported by extensive trading volumes. Unfortunately, this isn't always the case.

BentoBox

A recent example involves BentoBox and its fork, CoffinBox. Both suffered vulnerabilities several months ago. In these cases, the KashiPairMediumRisk contract stored an exchange rate value calculated from oracle-derived prices. This rate was used by the lending protocol to assess a user’s solvency.

Screenshot 2023-09-27 at 5.42.53 PM

This value remains current only as long as someone is willing to spend the gas to update it. When significant price slippage occurs in a collateralized asset—often ETH or BNB—the stored exchange rate becomes outdated, as it was calculated based on the pre-drop price. An opportunist user can exploit this by borrowing at the outdated rate, calling updateExchangeRate() to deliberately make their account insolvent, and then triggering a liquidation to claim a bonus reward.

While developers have attempted to mitigate this issue by periodically querying the price oracle, the inherent volatility of asset prices still leaves room for arbitrage.

Rodeo Finance

Even price oracles, which serve as crucial elements in these ecosystems, are susceptible to manipulation. On July 11, 2023, Rodeo Finance was exploited for approximately 479 ETH through a price oracle attack. The oracle in question calculated a time-weighted average price across the last four time frames, which varied from 30 to 45 minutes each. Notably, each individual price data point was sourced from a specific, low-volume decentralized exchange pair.

Screenshot 2023-09-27 at 5.45.32 PM

The attacker meticulously timed the manipulation of the pair balance to coincide with the moments when the price data was being queried. These inflated prices were then used by Rodeo Finance's strategy contract to falsely validate a borrowing and swapping strategy. The attacker capitalized on this to make off with a substantial sum. As a preventative measure, the protocol was paused to safeguard remaining funds, with a relaunch planned following new security audits.

  1. Leverage and Stacked External Dependency

Paraspace

DeFi's drive for innovation often leads to elaborate setups aiming to seize any available market opportunities. As was evident in the Euler exploit, borrowed assets are sometimes recursively used to multiply profits or losses from price volatility. In 2021 and 2022, during the peak of the NFT mania, attempts were made to incorporate NFTs as collateral. The idea was to incentivize NFT holders to borrow and trade fungible tokens, capitalizing on the high valuations of some NFTs. However, the price instability of NFTs increased the risk of insolvency.

An exploit aimed at ParaSpace was thwarted by whitehat hackers on March 17, 2023. ParaSpace is a decentralized lending protocol that accommodates both fungible and non-fungible tokens as collateral. What sets it apart is its implementation of an interface for elastic tokens, which have algorithmically adjusted supplies aimed at controlling their price.

This ParaSpace exploit serves as an illustration of what's called "stacked external dependency," a situation in which independently secure elements, when combined, lead to unexpected vulnerabilities. Elastic tokens had been integrated into lending contracts as collateral. The size of the 'cApe' token collateral was tied to the balance of the elastic token, which in turn was linked to the token address's staked value in the ApeCoinStaking contract. The attacker manipulated the staked value in the ApeCoinStaking contract, thereby inflating the collateral size and borrowing more tokens than were actually staked on ParaSpace.

Screenshot 2023-09-27 at 5.47.20 PM

The exploit involving ParaSpace and ApeCoin underscores the absence of control and responsibility inherent in stacked external dependencies. Both ParaSpace and ApeCoin operated in good faith, focusing on their individual responsibilities. The auditing teams identified external dependencies but were unable to anticipate the stacked dependencies that eventually led to the exploit. This points to an intricate problem where each project is responsible to its stakeholders, but the interconnectedness of projects creates vulnerabilities that are often unforeseen.

The interoperability among DeFi projects creates a complex web of dependencies. While collaboration, particularly in marketing, has increased, this interoperability can also introduce hidden risks. These 'stacked external dependencies' emerge when multiple projects intertwine their logic but aren't aware of or don't have control over each other's internal configurations. This creates new and unpredictable attack vectors that may not be readily identifiable during security audits.

Conclusion

Decentralized lending protocols, although rooted in the ancient concept of lending, have introduced a unique set of challenges in the blockchain and cryptocurrency landscape. The rapid pace of innovation coupled with ease of contract deployment and market volatility have necessitated equally innovative security solutions.

CertiK employs a comprehensive set of scanning rules tailored to identify validation issues at multiple levels in lending contracts. Apart from traditional auditing services offered by our experienced security engineers—who have audited 110 lending projects collectively—CertiK also continuously monitors the on-chain and social activity of 184 lending contracts. This data is presented in Skynet, which helps users better understand and contextualize the risk profile of a project.

Web3 is essentially a battleground of contrasting objectives: regulation versus efficiency, decentralization versus centralization, and yield versus risk. As we advance in this volatile, yet exciting, terrain, it's crucial to maintain a balance. CertiK is committed to leveraging cutting-edge technical solutions to ensure a secure future for the DeFi space.

If your project could benefit from an in-depth security audit, we strongly recommend getting in touch to safeguard against hidden vulnerabilities and ensure the long-term stability and success of your project.

;