Skip to content
Business logic Audit finding Advanced

Attacker can utilize function CdpManager.redeemCollateral() to break the order of sortedCdps

The redeemCollateral function reinserts a partially redeemed CDP into the sorted list before fully redeemed CDPs are removed, allowing an attacker to supply crafted hints that place the CDP in the wrong position. This can disrupt the sorted order, potentially causing incorrect returns from HintHelpers and unfair priority redemption of high-NICR CDPs.

TrungOre Follow

Originally disclosed on Code4rena

Submitted by TrungOre

https://github.com/code-423n4/2023-10-badger/blob/f2f2e2cf9965a1020661d179af46cb49e993cb7e/packages/contracts/contracts/CdpManager.sol#L434-L443

https://github.com/code-423n4/2023-10-badger/blob/f2f2e2cf9965a1020661d179af46cb49e993cb7e/packages/contracts/contracts/CdpManager.sol#L209-L214

The CdpManager.redeemCollateral() function is used to send the _debt amount of EBTC to the system and redeem the corresponding amount of stETH. There are two important features to note about this function before delving into the problem:

  • The function begins redemption from the Cdp with the smallest ICR, where the ICR is greater than or equal to MCR. The subsequently redeemed Cdps will follow the ascending order of NICR in the SortedCdps list.
  • All Cdps that are redeemed, with the likely exception of the last one, will end up with no remaining debt and will be closed. If the last Cdp does have some remaining debt and collateral (indicating a valid and meaningful ICR), it will be reinserted into the SortedCdps list using the “hint” provided by the users/front-end.

The protocol utilizes a new technique by employing a sortedCdps.batchRemove() function to remove a consecutive sequence of Cdps in the sorted list after the redemption loop, instead of removing each one individually in each iteration of the loop for gas-saving purposes.

while (
    currentBorrower != address(0) && totals.remainingDebtToRedeem > 0 && _maxIterations > 0
) {
    ...
    SingleRedemptionValues memory singleRedemption = _redeemCollateralFromCdp(
        _redeemColFromCdp
    );
    ...
}

// remove from sortedCdps
if (_numCdpsFullyRedeemed == 1) {
    sortedCdps.remove(_firstRedeemed);
} else if (_numCdpsFullyRedeemed > 1) {
    bytes32[] memory _toRemoveIds = _getCdpIdsToRemove(
        _lastRedeemed,
        _numCdpsFullyRedeemed,
        _firstRedeemed
    );
    sortedCdps.batchRemove(_toRemoveIds);
}

As we observe, in each iteration of the loop, the internal function CdpManager._redeemCollateralFromCdp() is triggered, executing the following logic:

  • If there is no remaining debt, the Cdp should be closed. To accomplish this, the function CdpManagerStorage._closeCdpByRedemption() will be triggered, assigning the new STORAGE debt and collateral for the corresponding Cdp:

    • Cdps[_cdpId].coll = 0;
    • Cdps[_cdpId].debt = 0;

    However, no “remove” operation will be executed for the Cdp in the SortedCdps list. Consequently, the removed Cdp will remain in the same position in the sorted list after the for-loop, with the new collateralization ratio (NICR), which is type(uint256).max following these lines of code.

  • Otherwise, the Cdp will be assigned a remaining value of debt and collateral and will immediately be reinserted into the SortedCdps list.

The flaw arises when the partially redeemed Cdp is reinserted while the fully redeemed Cdps haven’t been removed from the sorted list yet.

Note: please see scenario in warden’s original submission.

Impact

The sequence of the sortedCdps list will be disrupted, and given that essential protocol functions operate in accordance with this sequence, the severity of the issue is significant.

Recommended Mitigation Steps

Instead of inserting the partially redeemed Cdp back in the for-loop, the function should reinsert it after removing the fully redeemed Cdp.

Alex the Entreprenerd (Badger) disputed and commented:

The finding is known and part of the known broken invariants + cantina report.

We would be more lenient if any impact was demonstrated but afaict there’s only an edge case for Redemptions not working when liquidations are more profitable which would lead me to dispute even in that case.

We are interested in more impacts if those were found.

We would want to ask the Warden for the POC as we have a concern for the issue being valid, but it seems like the finding is impossible in practice.

rayeaster (Badger) commented:

Here is a working POC to verify the finding.

ronnyx2017 (Judge) commented:

The finding is known and part of the known broken invariants + cantina report.

I have noticed that a pull request https://github.com/ebtc-protocol/ebtc/pull/725 has been submitted to the main repo for this issue. Is this really OOS, @Alex the Entreprenerd?

Alex the Entreprenerd (Badger) commented:

The breaking of sorting is known but the mechanism through which this was achieved was not, so we believe the finding to be in scope.

The impact of this finding is unclear.

ronnyx2017 (Judge) commented:

The attack scenario provided by the warden is very clear, but I don’t see any actual profit or loss from it. Warden might argue that the CDP’s position is incorrect after partial redemption, leading to damage upon the next redemption. However, in reality, it could have been fully redeemed initially, and the attacker wouldn’t have gained any additional profits from it. But this clearly violates a critical invariant, especially when carefully crafted inputs are used as attack vectors. Therefore, I believe this falls into a med category.

CodingNameKiki (Warden) commented:

Currently working alongside the Badger team on some mitigations.

So on short explanation I understood that this issue:

  • Have no impact that I am aware of.
  • Messes up only the first redeemable node after the attack.
  • The node ordering is back to normal when someone else redeems after the attack.

The attack scenario provided by the warden is very clear, but I don’t see any actual profit or loss from it.

Agree with you on this one, at the same time an interesting question is why would anyone want to do this if there is no profit from it, no impact and the sorted order is back to normal on the next redeem.

https://gist.github.com/CodingNameKiki/b3f36aacc704c082df2b974b2db89c78

ronnyx2017 (Judge) decreased severity to Low/Non-critical and commented:

Thanks for the poc and verification from @CodingNameKiki . And the sponsor finally convinced me. The invariant was only temporarily broken, and whatever the attacker does during this intermediate stage will get back to the previous state. This impact is so minimal that it can be downgraded to a QA.

WelToHackerLand (Warden) commented:

Hello @ronnyx2017 & @rayeaster, thank you for reviewing the issue.

I would like to respectfully question the severity of the problem for the following reasons:

  • Initially, there doesn’t seem to be an attacker involved in this issue, as a regular user seeking partial redemption could potentially disrupt the sorted cdps. The provided Proof of Concept (POC) demonstrates that the hints used by the sender are derived from the hintHelpers contract rather than being predetermined by an attacker.
  • Additionally, the POC presented by @CodingNameKiki might be applicable only when the redemption occurs immediately after. What if other transactions take place before the fixed redemption? For instance, consider a scenario where the NICR of sortedCdps post-redemption disrupts the order, such as [8, 12, 5]. If a user intends to open a new CDP with NICR = 9, the provided hints could be before NICR = 8, resulting in the new sorted cdps as [9, 8, 12, 5]. In this case, there are now two incorrect positions in the sorted list instead of one. The more openCdp() transactions are initiated, the more incorrect positions could emerge, and the cost to rectify the order becomes higher.

Considering these factors, I believe the severity of this issue should be classified as medium.

CodingNameKiki (Warden) commented:

Initially, there doesn’t seem to be an attacker involved in this issue, as a regular user seeking partial redemption could potentially disrupt the sorted cdps. The provided Proof of Concept (POC) demonstrates that the hints used by the sender are derived from the hintHelpers contract rather than being predetermined by an attacker.

Do you mean providing wrong _firstRedemptionHint or wrong _partialRedemptionHintNICR, if that’s the case the system will manually find the correct redeemable hint which is the first node with ICR >= MCR, on the other hand if you provide a wrong partial hint NICR the partial redeeming will be cancelled.

        if (_isValidFirstRedemptionHint(_firstRedemptionHint, totals.price)) {
            currentBorrower = sortedCdps.getOwnerAddress(_firstRedemptionHint);
        } else {
            _cId = sortedCdps.getLast();
            currentBorrower = sortedCdps.getOwnerAddress(_cId);
            // Find the first cdp with ICR >= MCR
            while (currentBorrower != address(0) && getSyncedICR(_cId, totals.price) < MCR) {
                _cId = sortedCdps.getPrev(_cId);
                currentBorrower = sortedCdps.getOwnerAddress(_cId);
            }
        }
            if (
                newNICR != _redeemColFromCdp.partialRedemptionHintNICR ||
                collateral.getPooledEthByShares(newColl) < MIN_NET_STETH_BALANCE
            ) {
                singleRedemption.cancelledPartial = true;
                return singleRedemption;
            }

In case you are talking about the upper and lower hints used in the POC, I tried every other possible hints and the system is working correctly. So this scenario is only possible if someone provided the exact hints and only when the system fully redeems a node and partially redeems from another.

We would be more lenient if any impact was demonstrated but afaict there’s only an edge case for Redemptions not working when liquidations are more profitable which would lead me to dispute even in that case We are interested in more impacts if those were found

As mentioned we are already aware and it’s known that wrong sorting can happen from the broken invariants, the question should be what impact does this issue lead to? Would suggest for a further research on the impact here and coded POC.

huuducsc (Warden) commented:

@ronnyx2017, @rayeaster, & @Alex the Entreprenerd - I would like to explain the reasons why I believe this issue should be considered at least a medium severity. I also believe that these explanations can address the concerns raised from @codingnamekiki and others to downgrade this issue.

  1. I believe the provided attack vector is very clear, indicating that an attacker can disrupt the sorting order of CDPs through partial redemption. The attacker just needs to call the function redeemCollateral with malicious values for _upperPartialRedemptionHint and _lowerPartialRedemptionHint to place the partially redeemed CDP in the wrong position. The scenario was described very clearly in the report, and there is another proof of concept (POC) mentioned in the comment by @rayeaster. Additionally, I believe it’s not a known issue because the known scenario that also breaks the order is from redistribution of debt and yield, which is different. This scenario allows an external attacker to interact with and manipulate the broken invariants. It has a significant impact, which will be described below.
  2. An attacker can increase the NICR of a partially redeemed CDP to a very large value and place it in the wrong position. To achieve this, the attacker can calculate the redemption amount to leave the remaining debt of the partially redeemed CDP at 1. For example, if a CDP has $15e18 in collateral and $10e18 in debt, the attacker can calculate a partial redemption with a debt of $10e18 - 1, resulting in a remaining debt of 1 and remaining collateral of 5e18 (assuming remaining collateral can bypass MIN_NET_STETH_BALANCE). This manipulation causes the new NICR to become very large.

Note: please see warden’s original comment for full details.

  1. Due to the above scenario, I disagree with the statement made by @ronnyx2017: “The invariant was only temporarily broken, and whatever the attacker does during this intermediate stage will get back to the previous state.” The attacker can open numerous new Cdps into incorrect positions using dummy upperHint and invalid lowerHint (details are described in the scenario and PoC of section 2), disrupting the order of protocols. Moreover, the attacker can front-run any opening CDP transaction by users to break the order, make it becomes the first position to be redeemed. Here are the details of the impacts that cause significant damage to protocol:
  2. The attacker can break the order of sortedCdps and disrupt it by opening many new CDPs with _upperHint is dummy, placing them in incorrect positions (as described above). Therefore, sortedCdps will have many incorrect positions that are not easy to resolve. This disruption can mess up the protocol’s data and may result in incorrect returns from the HintHelpers contract.
  3. After the mentioned manipulation, any new CDP will be at risk of being redeemed with priority, even though its NICR is still good. This can happen if the _upperHint passed to the openCdp function of users is dummy or invalid, which can occur normally due to changes in on-chain data like front-running or incorrect returns from the HintHelper contract. It creates an unfair situation for protocol users, as they may be compelled to redeem their assets (acquiring debt assets and losing collateral assets) even when they have a CDP with a high NICR.

In conclusion, this issue has a significant impact that can disrupt the ordered state of the protocol and put users at risk of having their assets forcibly redeemed. However, the severity may increase if attackers identify other attack vectors (which I haven’t found until now) to manipulate the state and exploit vulnerabilities since attackers are able to break order invariants externally.

CodingNameKiki (Warden) commented:

^ Thanks for the reply, check the below POC which confirms the above statements.

https://gist.github.com/CodingNameKiki/0f4bc68802cfcbfe255759554b735b38

ronnyx2017 (Judge) increased severity to Medium and commented:

Thank you warden for providing additional information on the impact. This has made the report ultimately comprehensive and clear.

I have discussed the final rating based on the following facts, rules, and input from two senior judges. We ultimately elevate this issue to MEDIUM. Record I (recommendations from senior judges):

As the original submission doesn’t contain a PoC of the final impact, I think Medium is more appropriate.

Record II (my assessment):

  1. For the impact I.

This disruption can mess up the protocol’s data and may result in incorrect returns from the HintHelpers contract.

it meets the criteria of MED. Although it is not dos, it affected the availability of the protocol for normal users.

but the function of the protocol or its availability could be impacted

  1. For impact II.

It creates an unfair situation for protocol users, as they may be compelled to redeem their assets (acquiring debt assets and losing collateral assets) even when they have a CDP with a high NICR.

It’s based on impact I, but I think it can be a HIGH according to the criteria:

Assets can be stolen/lost/ compromised directly or indirectly if there is a valid attack path that does not have hand-wavy hypotheticals

Because attackers are able to break order invariants externally, we can believe the attack path is explicit (include front run). And the redemption from high NICR cdp won’t result in a direct loss of assets, but it is clearly a form of compromise.

Note: For further discussion, see here.


The original report as published on Code4rena, by TrungOre. 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 sorted order can be broken, which may lead to incorrect returns from HintHelpers and unfair priority redemption of high-NICR CDPs, though the impact was initially disputed and later rated Medium.

What the attacker needed

Ability to call redeemCollateral; crafted hints

The fix

The partially redeemed CDP should be reinserted after the fully redeemed CDPs are removed from the sorted list.

How it was found

  1. Call redeemCollateral with malicious values for _upperPartialRedemptionHint and _lowerPartialRedemptionHint.
  2. The function fully redeems some CDPs and partially redeems another, reinserting the partial one with the wrong hints.
  3. The sorted list order is disrupted, placing the partially redeemed CDP in an incorrect position.

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 sorted list is used to order loans by their risk (collateral-to-debt ratio). When a loan is partially repaid, it is put back into the list, but the code does this before removing loans that were fully repaid. An attacker can give wrong hints about where to put the partially repaid loan, so it ends up in the wrong place. This can confuse the system and cause unfair redemptions.

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 TrungOre

View all

7 more disclosed reports, best first.

More from eBTC Zap Router

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.