Skip to content
Business logic Audit finding Intermediate

Vault `_maxDeposit` incorrect calculation allows to bypass vault deposit cap

The vault's maximum deposit calculation incorrectly adds claimable assets to the cap, allowing users to deposit beyond the vault's deposit cap when there are redeemed but unclaimed assets. An attacker could repeatedly deposit and redeem to bypass the cap and deposit unlimited funds.

panprog Follow

Originally disclosed on Sherlock

Source: https://github.com/sherlock-audit/2023-10-perennial-judging/issues/27

Found by

panprog

Summary

Vault has a deposit cap risk setting, which is the max amount of funds users can deposit into the vault. The problem is that _maxDeposit function, which calculates max amount of assets allowed to be deposited is incorrect and always includes vault claimable assets even when the vault is at the cap. This allows malicious (or even regular) user to deposit unlimited amount bypassing the vault cap, if the vault has any assets redeemed but not claimed yet. This breaks the core protocol function which limits users risk, for example when the vault is still in the testing phase and owner wants to limit potential losses in case of any problems.

Vulnerability Detail

Vault._update limits the user deposit to _maxDeposit() amount:

Solidity
    if (depositAssets.gt(_maxDeposit(context)))
        revert VaultDepositLimitExceededError();
...
function _maxDeposit(Context memory context) private view returns (UFixed6) {
    if (context.latestCheckpoint.unhealthy()) return UFixed6Lib.ZERO;
    UFixed6 collateral = UFixed6Lib.from(totalAssets().max(Fixed6Lib.ZERO)).add(context.global.deposit);
    return context.global.assets.add(context.parameter.cap.sub(collateral.min(context.parameter.cap)));
}

When calculating max deposit, the vault's collateral consists of vault assets as well as assets which are redeemed but not yet claimed. However, the formula used to calculate max deposit is incorrect, it is:

maxDeposit = claimableAssets + (cap - min(collateral, cap))

As can be seen from the formula, regardless of cap and current collateral, maxDeposit will always be at least claimableAssets, even when the vault is already at the cap or above cap, which is apparently wrong. The correct formula should subtract claimableAssets from collateral (or 0 if claimableAssets is higher than collateral) instead of adding it to the result:

maxDeposit = cap - min(collateral - min(collateral, claimableAssets), cap)

Current incorrect formula allows to deposit up to claimable assets amount even when the vault is at or above cap. This can either be used by malicious user (user can deposit up to cap, redeem, deposit amount = up to cap + claimable, redeem, ..., repeat until target deposit amount is reached) or can happen itself when there are claimable assets available and vault is at the cap (which can easily happen by itself if some user forgets to claim or it takes long time to claim).

Impact

Malicious and regular users can bypass vault deposit cap, either intentionally or just in the normal operation when some users redeem and claimable assets are available in the vault. This breaks core contract security function of limiting the deposit amount and can potentially lead to big user funds loss, for example at the initial stages when the owner still tests the oracle provider/market/etc and wants to limit vault deposit if anything goes wrong, but gets unlimited deposits instead.

Proof of concept

Bypass of vault cap is demonstrated in the test, add this to Vault.test.ts:

TS
it('bypass vault deposit cap', async () => {
    console.log("start");

    await vault.connect(owner).updateParameter({
    cap: parse6decimal('100'),
    });

    await updateOracle()

    var deposit = parse6decimal('100')
    console.log("Deposit 100")
    await vault.connect(user).update(user.address, deposit, 0, 0)

    await updateOracle()
    await vault.settle(user.address);

    var assets = await vault.totalAssets();
    console.log("Vault assets: " + assets);

    // additional deposit reverts due to cap
    var deposit = parse6decimal('10')
    console.log("Deposit 10 revert")
    await expect(vault.connect(user).update(user.address, deposit, 0, 0)).to.be.reverted;

    // now redeem 50
    var redeem = parse6decimal('50')
    console.log("Redeem 50")
    await vault.connect(user).update(user.address, 0, redeem, 0);

    await updateOracle()
    await vault.settle(user.address);

    var assets = await vault.totalAssets();
    console.log("Vault assets: " + assets);

    // deposit 100 (50+100=150) doesn't revert, because assets = 50
    var deposit = parse6decimal('100')
    console.log("Deposit 100")
    await vault.connect(user).update(user.address, deposit, 0, 0);

    await updateOracle()
    await vault.settle(user.address);

    var assets = await vault.totalAssets();
    console.log("Vault assets: " + assets);

    var deposit = parse6decimal('50')
    console.log("Deposit 50")
    await vault.connect(user).update(user.address, deposit, 0, 0);

    await updateOracle()
    await vault.settle(user.address);

    var assets = await vault.totalAssets();
    console.log("Vault assets: " + assets);
})

Console log from execution of the code above:

Solidity
start
Deposit 100
Vault assets: 100000000
Deposit 10 revert
Redeem 50
Vault assets: 50000000
Deposit 100
Vault assets: 150000000
Deposit 50
Vault assets: 200000000

The vault cap is set to 100 and is then demonstrated that it is bypassed and vault assets are set at 200 (and can be continued indefinitely)

Code Snippet

_maxDeposit always adds context.global.assets (assets redeemed but not yet claimed) to the returned amount, even when the vault is at or above cap: https://github.com/sherlock-audit/2023-10-perennial/blob/main/perennial-v2/packages/perennial-vault/contracts/Vault.sol#L483

Tool used

Manual Review

Recommendation

The correct formula to _maxDeposit should be:

maxDeposit = cap - min(collateral - min(collateral, claimableAssets), cap)

So the code can be:

Solidity
function _maxDeposit(Context memory context) private view returns (UFixed6) {
    if (context.latestCheckpoint.unhealthy()) return UFixed6Lib.ZERO;
    UFixed6 collateral = UFixed6Lib.from(totalAssets().max(Fixed6Lib.ZERO)).add(context.global.deposit);
    return context.parameter.cap.sub(collateral.sub(context.global.assets.min(collateral)).min(context.parameter.cap));
}

Discussion

panprog

Mitigation Review:

While it's not possible to exceed vault deposit cap now, the opposite problem has now appeared: any user can block all further deposits by depositing, redeeming, but not claiming the assets. This will block the vault from any further deposits while vault position can be very small due to such user not claiming redeemed assets.

Depending on project intended behavior, this might be expected (limit amount of collateral deposited, rather than vault position in underlying market), but it still looks somewhat incorrect and makes it easy to severely limit vault intended functionality (providing liquidity for the underlying markets): malicious user can keep the other users from depositing while not providing any liquidity at all.

kbrizzle

Here's the formula we tried to implement (note that it is different than the one that was proposed as a recommend fix):

totalAssets() = collateral (amount) - deposit - totalClaim

collateral (variable) = totalAssets() + deposit -> collateral (amount) - totalClaim
maxDeposit = cap - collateral (variable) -> cap - (collateral (amount) - totalClaim)

This should take into account the issue you have raised, where idle totalClaim is not counted towards the deposited amount of the vault. Lemme if you see something wrong there or with the implementation.

panprog

@kbrizzle I think totalAssets() doesn't subtract totalClaim - it includes totalClaim. At least I haven't seen any changes in totalAsset() calculations since contest code, where my POC confirms that totalAssets() includes totalClaim. Currently it returns:

Solidity
    function totalAssets() public view returns (Fixed6) {
        Checkpoint memory checkpoint = _checkpoints[_accounts[address(0)].read().latest].read();
        return checkpoint.assets
            .add(Fixed6Lib.from(checkpoint.deposit))
            .sub(Fixed6Lib.from(checkpoint.toAssetsGlobal(checkpoint.redemption)));
    }

So it's checkpoint assets (which includes assets which are redeemed but not claimed yet) + deposits - redemptions. Redemptions != claims, it's different.

If you still think this is correct, I'll need more time to verify how checkpoint assets are calculated and craft a POC to demonstrate it.

kbrizzle

The totalClaim is actually being taken out as part of the checkpoint process itself, not within totalAssets().

The Checkpoint lifecycle works as follows:

  1. initialize() is called when a new underlying version mapping is requested for the first time.
  2. checkpoint.assets is initialized as - (total pending deposits + total pending claims) here.
  3. Later, once the mapping is .ready(), the checkpoint is completed().
  4. This completes checkpoint.assets as total collateral at version - (total pending deposits + total pending claims), which is our expected formula.

Now note that the actual code within totalAssets() is just translating the assets amount from "just before the version snapshot" to "at the version snapshot including its deposits and redemptions".

Additionally, I've added a test case to ensure that totalClaim() is not being included at least in the novel case.

panprog

@kbrizzle Yes, you're right. I've confused checkpoint assets and global assets. Sorry for raising up non-existant issue.

This one is fixed then. My remark on the issue is invalid.

MLON33

Fix: https://github.com/equilibria-xyz/perennial-v2/pull/172

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

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 _maxDeposit function incorrectly adds claimable assets to the result instead of subtracting them from collateral, so the cap is not enforced when there are unclaimed redemptions.

Impact

Users can bypass the vault deposit cap, potentially leading to unlimited deposits and loss of funds if the vault is still being tested or if the cap is meant to limit risk.

What the attacker needed

Vault has a deposit cap set; there are redeemed but unclaimed assets

The fix

The _maxDeposit function should be corrected to subtract claimable assets from collateral, as shown in the recommendation.

How it was found

  1. Set the vault deposit cap to 100.
  2. Deposit 100 into the vault.
  3. Attempt to deposit 10 more, which reverts due to the cap.
  4. Redeem 50, leaving 50 in the vault but 50 claimable.
  5. Deposit 100, which succeeds because the max deposit is calculated as 50 (claimable) + (100 - min(50,100)) = 100, allowing total assets to reach 150.
  6. Deposit 50 more, reaching 200 total assets, and repeat to bypass the cap indefinitely.

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 has a deposit cap to limit how much money users can put in. The code that checks the cap made a mistake: it added money that was already redeemed but not yet claimed, so the cap could be exceeded. This means someone could keep depositing more than the intended limit.

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 panprog

View all

66 more disclosed reports, best first.

More from Perennial V2 Update #1

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.