Skip to content
Business logic Audit finding Intermediate

Zero rates on new quoted tokens allow an attacker to take an interest free quota

When a new token is added to the quota system, its interest rate defaults to zero until the next epoch update. An attacker can borrow a large amount of that token and pay no quota interest for that period, causing a loss of interest revenue for the protocol.

Bauchibred Follow

Originally disclosed on Code4rena

Submitted by Bauchibred

Take a look here:

function addQuotaToken(address token) external override gaugeOnly {
  if (quotaTokensSet.contains(token)) {
    revert TokenAlreadyAddedException();
  }
  quotaTokensSet.add(token); //@audit rates here are `0` by default.
  totalQuotaParams[token].cumulativeIndexLU = 1;
  emit AddQuotaToken(token);
}

This function is used to add a new token, when the token is added the rates are set to 0 by default up until a general epoch update before the real rate gets set for the token here.

function _checkAndUpdateEpoch() internal {
  uint16 epochNow = IGearStakingV3(voter).getCurrentEpoch(); // U:[GA-14]

  if (epochNow > epochLastUpdate) {
    epochLastUpdate = epochNow; // U:[GA-14]

    if (!epochFrozen) {
      // The quota keeper should call back to retrieve quota rates for needed tokens
      _poolQuotaKeeper().updateRates(); //@audit
    }

    emit UpdateEpoch(epochNow); // U:[GA-14]
  }
}

Which calls this:

function updateRates()
  external
  override
  gaugeOnly // U:[PQK-3]
{
  address[] memory tokens = quotaTokensSet.values();
  uint16[] memory rates = IGaugeV3(gauge).getRates(tokens); // U:[PQK-7]

  uint256 quotaRevenue; // U:[PQK-7]
  uint256 timestampLU = lastQuotaRateUpdate;
  uint256 len = tokens.length;

  for (uint256 i; i < len; ) {
    address token = tokens[i];
    uint16 rate = rates[i];

    TokenQuotaParams storage tokenQuotaParams = totalQuotaParams[token]; // U:[PQK-7]
    (uint16 prevRate, uint192 tqCumulativeIndexLU, ) = _getTokenQuotaParamsOrRevert(
      tokenQuotaParams
    );

    tokenQuotaParams.cumulativeIndexLU = QuotasLogic.cumulativeIndexSince(
      tqCumulativeIndexLU,
      prevRate,
      timestampLU
    ); // U:[PQK-7]

    tokenQuotaParams.rate = rate; // U:[PQK-7]

    quotaRevenue +=
      (IPoolV3(pool).creditManagerBorrowed(creditManagers[token]) * rate) /
      PERCENTAGE_FACTOR; // U:[PQK-7]

    emit UpdateTokenQuotaRate(token, rate); // U:[PQK-7]

    unchecked {
      ++i;
    }
  }

  IPoolV3(pool).setQuotaRevenue(quotaRevenue); // U:[PQK-7]
  lastQuotaRateUpdate = uint40(block.timestamp); // U:[PQK-7]
}

However, the problem is the fact that once this new token is added, and the rate is 0, an attacker can request a huge quota even up to the configured limit without having to pay any interest to the protocol all through the period where rate = 0.

Impact

A malicious user can request a very high quota and not pay any interest all through the period when the rate is defaulted to 0.

Recommended Mitigation Steps

Consider atomically updating the rates in the instance where a new quoted token is added.

Assessed type

Context

0xtj24 (LoopFi) confirmed

Koolex (judge) decreased severity to Medium and commented:

an attacker can request a huge quota even up to the configured limit without having to pay any interest to the protocol.

Requesting from the Warden to elaborate on this, only in PJQA please.

Bauchibred (warden) commented:

@Koolex, what that snippet means is the malicious user can take a completely risk free position while exposing the system since the rate is defaulted to 0; i.e., they can just request a very high quota, which in this case would be the configured maximum for said asset thats’s to be used to limit protocol’s exposure. So in this case they do not pay any interest all throughout this period when these rates are 0, which is why I submitted this as High.

To go into a bit more details on the whole context of the quota logic:

In the current implementation, quotas are used to limit the system’s exposure to some assets, so having zero rates is a direct loss on the protocol since no interest accrues over time with these rates and as such 0 payments get made for the requested quota; allowing the malicious users access to risk-free leveraging on the maximum amount of quota they can get.

Koolex (judge) increased severity to High and commented:

@Bauchibred - can you please provide a PoC on how a user can request a huge quota on zero rate? Not necessarily with code. but a breakdown of the call flow. The above proof lacking this.

Bauchibred (warden) commented:

@Koolex, requesting a huge quota is by just taking up a borrow position against the collateral and whenever calculating the debt from the borrowed position or the revenue change, the methods shown in the report above and dropdown below from PoolQuotaKeeper are used.

Call flow breakdown with code snippets

A user can request a borrow credit against the collateral token here we’d have the deltaDebt to be non-zero which is what I mean by a huge quota. Now for each position there are two fees to be charged, one based on pool utilisation and another based on the quota fees from PoolQuotaKeeperV3 and since the quota interest has been defaulted to zero before the next epoch as hinted in the report whenever paying back the protocol loses out on this interest, (i.e., the quota interest):

https://github.com/code-423n4/2024-07-loopfi/blob/57871f64bdea450c1f04c9a53dc1a78223719164/src/CDPVault.sol#L256-L266

    function borrow(address borrower, address position, uint256 amount) external {
        int256 deltaDebt = toInt256(amount);
        modifyCollateralAndDebt({
            owner: position,
            collateralizer: position,
            creditor: borrower,
            deltaCollateral: 0,
            deltaDebt: deltaDebt
        });
    }

That’s to say when the user decides to repay, or their position is being interacted with the amount of debt is gotten by _calcDebt, but no quota interest is being calculated for them cause while calculating the debt for the position we have 0 interest rate being returned for cumulativeQuotaInterest. As such, it’s not being considered for the overall accrued interest:

https://github.com/code-423n4/2024-07-loopfi/blob/57871f64bdea450c1f04c9a53dc1a78223719164/src/CDPVault.sol#L467-L481

    function _calcDebt(Position memory position) internal view returns (DebtData memory cdd) {
        uint256 index = pool.baseInterestIndex();
        cdd.debt = position.debt;
        cdd.cumulativeIndexNow = index;
        cdd.cumulativeIndexLastUpdate = position.cumulativeIndexLastUpdate;
        cdd.cumulativeQuotaIndexLU = position.cumulativeQuotaIndexLU;
        // Get cumulative quota interest
        (cdd.cumulativeQuotaInterest, cdd.cumulativeQuotaIndexNow) = _getQuotedTokensData(cdd);

        cdd.cumulativeQuotaInterest += position.cumulativeQuotaInterest;

        cdd.accruedInterest = CreditLogic.calcAccruedInterest(cdd.debt, cdd.cumulativeIndexLastUpdate, index);

        cdd.accruedInterest += cdd.cumulativeQuotaInterest;
    }

Note that the cumulativeQuotaInterest that’s been used to define the overall accrued interest is gotten directly from:

https://github.com/code-423n4/2024-07-loopfi/blob/57871f64bdea450c1f04c9a53dc1a78223719164/src/CDPVault.sol#L484-L495

    function _getQuotedTokensData(
        DebtData memory cdd
    ) internal view returns (uint128 outstandingQuotaInterest, uint192 cumulativeQuotaIndexNow) {
        cumulativeQuotaIndexNow = IPoolQuotaKeeperV3(poolQuotaKeeper()).cumulativeIndex(address(token));
        uint128 outstandingInterestDelta = QuotasLogic.calcAccruedQuotaInterest(
            uint96(cdd.debt),
            cumulativeQuotaIndexNow,
            cdd.cumulativeQuotaIndexLU
        );

        outstandingQuotaInterest = outstandingInterestDelta; // U:[CM-24]
    }

Which queries the Quota keeper to get the current index, that’s defined by the rate:

https://github.com/code-423n4/2024-07-loopfi/blob/57871f64bdea450c1f04c9a53dc1a78223719164/src/quotas/PoolQuotaKeeperV3.sol#L87-L93

    function cumulativeIndex(address token) public view override returns (uint192) {
        TokenQuotaParams storage tokenQuotaParams = totalQuotaParams[token];
        (uint16 rate, uint192 tqCumulativeIndexLU, ) = _getTokenQuotaParamsOrRevert(tokenQuotaParams);

        return QuotasLogic.cumulativeIndexSince(tqCumulativeIndexLU, rate, lastQuotaRateUpdate);
    }

https://github.com/code-423n4/2024-07-loopfi/blob/57871f64bdea450c1f04c9a53dc1a78223719164/src/quotas/PoolQuotaKeeperV3.sol#L259-L276

    function _getTokenQuotaParamsOrRevert(
        TokenQuotaParams storage tokenQuotaParams
    ) internal view returns (uint16 rate, uint192 cumulativeIndexLU, uint16 quotaIncreaseFee) {
        // rate = tokenQuotaParams.rate;
        // cumulativeIndexLU = tokenQuotaParams.cumulativeIndexLU;
        // quotaIncreaseFee = tokenQuotaParams.quotaIncreaseFee;
        assembly {
            let data := sload(tokenQuotaParams.slot)
            rate := and(data, 0xFFFF)//@audit rate here
            cumulativeIndexLU := and(shr(16, data), 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
            quotaIncreaseFee := shr(208, data)
        }

        if (cumulativeIndexLU == 0) {
            revert TokenIsNotQuotedException(); // U:[PQK-14]
        }
    }

Also in the same light revenue change for quota would always be 0 during modification of collateral/debt or even liquidation that’s queried in the vault by the _calcQuotaRevenueChange() helper function:

https://github.com/code-423n4/2024-07-loopfi/blob/57871f64bdea450c1f04c9a53dc1a78223719164/src/CDPVault.sol#L462-L466

    function _calcQuotaRevenueChange(int256 deltaDebt) internal view returns (int256 quotaRevenueChange) {
        uint16 rate = IPoolQuotaKeeperV3(poolQuotaKeeper()).getQuotaRate(address(token));
        return QuotasLogic.calcQuotaRevenueChange(rate, deltaDebt);
    }

https://github.com/code-423n4/2024-07-loopfi/blob/57871f64bdea450c1f04c9a53dc1a78223719164/src/quotas/QuotasLogic.sol#L38-L41

    /// @dev Computes the pool quota revenue change given the current rate and the quota change
    function calcQuotaRevenueChange(uint16 rate, int256 change) internal pure returns (int256) {
        return change * int256(uint256(rate)) / int16(PERCENTAGE_FACTOR);
    }

Edit: Took consideration of @0xAlix2’s comment below and explicitly attached the fact that the interest which Loopfi is losing out on is their “quota interest” and not the whole debt’s interest as they assume. To note, why we are talking about debt in this discussion is cause I needed to showcase where the huge quota is requested since asked by the judge. Do check the diffs for the edit. In my opinion, this fact can also be seen clearly even from the title of the report that the user is getting an “interest free quota” and not an interest free debt.

NB: This same issue was reported and fixed in the original Gearbox protocol, see 7.3 which this is a fork of. Albeit in that instance it was assessed as a Medium, I submitted as high cause per C4 standards and as hinted here already, it doesn’t need any hypothetical path to be actualised.

0xAlix2 (warden) commented:

There’s some confusion here, having 0 cdd.cumulativeQuotaInterest doesn’t mean no interest. Let me explain, Loopfi has 2 separate interest rates, there’s the quota interest and the default credit interest, as seen the credit interest calculation has nothing to do with the Quota’s logic, you can confirm this from Loopfi’s docs.

I also had this fuzzing test that confirms this, that you can add in src/test/unit/CDPVault.t.sol:

function test_someFuzzzz() public {
    CDPVault vault = createCDPVault(token, 150 ether, 0, 1.25 ether, 1.0 ether, 0);
    createGaugeAndSetGauge(address(vault));
    address position = address(new PositionOwner(vault));

    uint256 depositAmount = 100 ether;
    uint256 borrowAmount = 80 ether;

    token.mint(address(this), depositAmount);
    token.approve(address(vault), depositAmount);
    underlyingToken.mint(address(this), depositAmount);
    underlyingToken.approve(address(vault), depositAmount);

    uint256 initialInterestRate = vault.pool().baseInterestRate();

    vault.deposit(position, depositAmount);

    vault.borrow(address(this), position, borrowAmount);

    vm.warp(block.timestamp + 30 days);

    console.log("repay");

    vault.repay(address(this), position, vault.virtualDebt(position));
}
function _calcDebt(Position memory position) internal view returns (DebtData memory cdd) {
    uint256 index = pool.baseInterestIndex();
    cdd.debt = position.debt;
    cdd.cumulativeIndexNow = index;
    cdd.cumulativeIndexLastUpdate = position.cumulativeIndexLastUpdate;
    cdd.cumulativeQuotaIndexLU = position.cumulativeQuotaIndexLU;
    // Get cumulative quota interest
    (cdd.cumulativeQuotaInterest, cdd.cumulativeQuotaIndexNow) = _getQuotedTokensData(cdd);

    cdd.cumulativeQuotaInterest += position.cumulativeQuotaInterest;

+   console.log("cdd.cumulativeQuotaInterest", cdd.cumulativeQuotaInterest);

    cdd.accruedInterest = CreditLogic.calcAccruedInterest(cdd.debt, cdd.cumulativeIndexLastUpdate, index);

+   console.log("cdd.accruedInterest", cdd.accruedInterest);

    cdd.accruedInterest += cdd.cumulativeQuotaInterest;
}
Logs:
  cdd.cumulativeQuotaInterest 0
  cdd.accruedInterest 0
  cdd.cumulativeQuotaInterest 0
  cdd.accruedInterest 0
  cdd.cumulativeQuotaInterest 0
  cdd.accruedInterest 0
  repay
  cdd.cumulativeQuotaInterest 6575342465753424
  cdd.accruedInterest 657658017727639000
  cdd.cumulativeQuotaInterest 6575342465753424
  cdd.accruedInterest 657658017727639000

As seen the quota interest did accumulate.

Assuming the test is wrong (which I don’t think so), and the quota interest is 0, we can manually manipulate the quota index (so that it matches the initially set index here) so that the resulting quota interest is 0:

function _getQuotedTokensData(
    DebtData memory cdd
) internal view returns (uint128 outstandingQuotaInterest, uint192 cumulativeQuotaIndexNow) {
-   cumulativeQuotaIndexNow = IPoolQuotaKeeperV3(poolQuotaKeeper()).cumulativeIndex(address(token));
+   cumulativeQuotaIndexNow = 1;
    uint128 outstandingInterestDelta = QuotasLogic.calcAccruedQuotaInterest(
        uint96(cdd.debt),
        cumulativeQuotaIndexNow,
        cdd.cumulativeQuotaIndexLU
    );

    outstandingQuotaInterest = outstandingInterestDelta; // U:[CM-24]
}
Logs:
  cdd.cumulativeQuotaInterest 0
  cdd.accruedInterest 0
  cdd.cumulativeQuotaInterest 0
  cdd.accruedInterest 0
  cdd.cumulativeQuotaInterest 0
  cdd.accruedInterest 0
  repay
  cdd.cumulativeQuotaInterest 0
  cdd.accruedInterest 657658017727639000
  cdd.cumulativeQuotaInterest 0
  cdd.accruedInterest 657658017727639000

We can see that the Quota interest is indeed 0, but the user is casually paying the other “credit” interest.

As a result, there’s always some interest being paid to the protocol.

Edit: My response mainly refuted the following, showing that interest will always be paid regardless of the Quota.

an attacker can request a huge quota even up to the configured limit without having to pay any interest to the protocol

Assuming that the Quotas interest will always be 0 (I still doubt it, as the above test shows this, unless I’m missing something), for this to be high, assets need to be “stolen/lost/compromised”, how is this happening here?

Koolex (judge) commented:

@Bauchibred - I’m already aware that the issue was already reported elsewhere; in fact, if you search the in the codebase (in the lib) you would find the fixed version. Somehow, the devs overlooked it.

     quotaChange = (rate == 0) ? int96(0) : QuotasLogic.calcActualQuotaChange(totalQuoted, limit, quotaChange); // U:[PQK-15]

To summarize the impact, quota interest won’t be paid during the period where rate = 0, max time of this is one epoch. In normal cases, I would consider this as a Medium. However, I have re-assessed it above as High for the following reasons:

  • It can happen on each new token added.
  • Can be done at scale (i.e., many users) or one user with a huge amount, as a result loss of interest for LPs who voted for it.
  • It undermines the intended functionality from voting (CA vs LP) on quota rate, if there is any.

The original report as published on Code4rena, by Bauchibred. 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

Impact

The protocol loses quota interest revenue for the period when the rate is zero, which can be up to one epoch, and this can happen for each new token added and at scale.

What the attacker needed

A new token is added to the quota system; attacker borrows before the next epoch update

The fix

The rates should be updated atomically when a new quoted token is added, so that the zero-rate period does not exist.

How it was found

  1. A new token is added to the quota system via addQuotaToken, which sets its rate to zero.
  2. Before the next epoch update, an attacker borrows a large amount of that token, up to the configured quota limit.
  3. The attacker repays after the epoch update, having paid no quota interest for the period when the rate was zero.

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.

In this lending protocol, users pay two kinds of interest: a base interest on borrowed assets and an extra 'quota interest' that depends on how much of a particular token is borrowed. When a new token is added, its quota interest rate is set to zero until the next scheduled update. This means a user can borrow a lot of that token and, for that short period, pay no quota interest at all, which costs the protocol money.

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 Bauchibred

View all

22 more disclosed reports, best first.

More from LoopFi

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.