The way fees are accounted can break the sorted list order
The fee accounting mechanism in eBTC can cause the sorted list of CDPs to become unordered because new CDPs receive a higher stake than older ones, leading to different rates of change in their collateral ratios. An attacker could potentially exploit this to cause a denial of service or manipulate redemption order, though the report's proof of concept only shows a tiny ordering break under extreme conditions.
eBTC borrows the corrected stake mechanism from Liquity for reward distributions. (paper)
Doing a pure collateral proportionnal redistribution will over-rewards fresh cdps, and under-rewards older troves. The redistribution must deal with the fact that some fraction of a cdp’s entire collateral is the accumulated reward from previous liquidations, and this fraction varies across cdps.
The corrected stake was introduced by Liquity to correct for this.
The intuition behind the choice of corrected stake is that the corrected stake effectively models the fresh trove’s collateral as a total collateral, which includes ‘virtual’ accumulated rewards. The corrected stake earns rewards for the trove as if the trove had been in the system from the beginning - thus maintaining proportional reward growth.
eBTC makes some modifications to the original design that make the protocol vulnerable to an order break in the sorted list.
Let’s explain why.
Initially totalStake == totalCollateral, this is because no fees have been taken yet. Then, as the stETH value increases the protocol takes 50%. (if stETH apr is 5% then eBTC takes 2,5% as fees): CdpManagerStorage.sol#L509-L521.
function _calcSyncedGlobalAccounting(
uint256 _newIndex,
uint256 _oldIndex
) internal view returns (uint256, uint256, uint256) {
if (_newIndex > _oldIndex && totalStakes > 0) {
/// @audit-ok We don't take the fee if we had a negative rebase
(
uint256 _feeTaken,
uint256 _deltaFeePerUnit,
uint256 _perUnitError
) = calcFeeUponStakingReward(_newIndex, _oldIndex);
// calculate new split per stake unit
uint256 _newPerUnit = systemStEthFeePerUnitIndex + _deltaFeePerUnit;
return (_feeTaken, _newPerUnit, _perUnitError);
} else {
return (0, systemStEthFeePerUnitIndex, systemStEthFeePerUnitIndexError);
}
}
The _feeTaken goes directly to the protocol and reduces the totalCollateral value. (because internal accounting uses shares for internal accounting aka wstETH) CdpManagerStorage.sol#L585:
Now the new CDP stake will be higher than old cdp stakes since totalStakesSnapshot has not moved but totalCollateralSnapshot has decreased.
⇒ Since the debt redistributions and fee payments depend on the stake to distribute funds, we can intuitively understand that new CDPs will pay more fees than the old ones. Therefore, new cpds NICR (Nominal Individual Collateral Ratio = shares/debt) will decrease at a higher rate than old ones.
This can cause old CDPs to cross newer ones and break list order.
This list order break make the insertion position not unique anymore, this can lead to more and more disorder in the list that leads to unexpected behaviours such as DOS and bad redemption order.
Proof of Concept
This poc only takes advantage of splitting fees to break the list order, but note that debt redistribution events exacerbate this problem.
function test_H1() public {
vm.pauseGasMetering();
address firstUser;
address lastUser;
bytes32 firstCdpId;
bytes32 lastCdpId;
uint loop = 100;
/// let's open 100 cdps and save the 1st and last index
for (uint256 i = 0; i < loop; i++) {
(uint256 oldIndex, uint256 newIndex) = _applyIndexChange(2000000000000000); // 0,2% stETH increase
// get a random user
address user = _utils.getNextUserAddress();
vm.startPrank(user);
// Randomize collateral amount used
vm.deal(user, 10 ether * 1000);
collateral.approve(address(borrowerOperations), 10 ether*1000);
collateral.deposit{value: 10 ether * 1000}();
uint shareAmount = 10 ether;
uint256 collAmount = collateral.getPooledEthByShares(shareAmount);
uint256 borrowedAmount;
if (i == loop - 1)
// here we compute borrowedAmount to make lastCdpId NCIR very close to firstCdpId NICR
borrowedAmount = (1e20 * (shareAmount - collateral.getSharesByPooledEth(2e17))) / cdpManager.getSyncedNominalICR(firstCdpId); // borrowedAmount = 0.65764 ether;
else
borrowedAmount = 0.5 ether;
bytes32 id = borrowerOperations.openCdp(borrowedAmount, "hint", "hint", collAmount);
if (i == 0) {firstUser = user; firstCdpId = id;}
if (i == loop - 1) {lastUser = user ; lastCdpId = id;}
vm.stopPrank();
}
logNICR(firstCdpId, lastCdpId);
// NICR 1st trove should be < NICR last trove
assertLe(cdpManager.getSyncedNominalICR(firstCdpId), cdpManager.getSyncedNominalICR(lastCdpId));
/// Let's increase the stETH by 40% and open a last cdp
(uint256 oldIndex, uint256 newIndex) = _applyIndexChange(400000000000000000); // 40% stETH increase
// get a random user
address user = _utils.getNextUserAddress();
vm.startPrank(user);
uint256 collAmount = 10 ether;
// deal ETH and deposit for collateral
vm.deal(user, collAmount * 1000);
collateral.approve(address(borrowerOperations), collAmount);
collateral.deposit{value: collAmount * 1000}();
uint borrowedAmount = 0.5 ether;
borrowerOperations.openCdp(borrowedAmount, "hint", "hint", collAmount);
vm.stopPrank();
logNICR(firstCdpId, lastCdpId);
// NICR 1st trove should be < NICR last cdp but it's not the case
assertLe(cdpManager.getSyncedNominalICR(firstCdpId), cdpManager.getSyncedNominalICR(lastCdpId));
}
function logNICR(bytes32 firstCdpId, bytes32 lastCdpId) public {
console.log("---------------------------------- 1st cdp");
console.log("getCdpStake : ", cdpManager.getCdpStake(firstCdpId));
console.log("getCdpCollShares : ", cdpManager.getCdpCollShares(firstCdpId));
console.log("getSyncedNominalICR : ", cdpManager.getSyncedNominalICR(firstCdpId));
console.log("---------------------------------- last cdp");
console.log("getCdpStake : ", cdpManager.getCdpStake(lastCdpId));
console.log("getCdpCollShares : ", cdpManager.getCdpCollShares(lastCdpId));
console.log("getSyncedNominalICR : ", cdpManager.getSyncedNominalICR(lastCdpId));
console.log("---");
console.logInt(int(int(cdpManager.getSyncedNominalICR(firstCdpId))-int(cdpManager.getSyncedNominalICR(lastCdpId))));
console.log("----------------------------------");
}
This test fails on the last assertion, meaning that the list is no longer sorted.
Recommended Mitigation Steps
This is hard to fix because the sorted list was not designed to work this way.
I haven’t been able to find a quick fix that preserves the list order with a fair redistribution.
Even if it is less fair for borrowers, a proportional distribution (without the corrected stake) can solve this problem but it will be an incomplete solution.
The eBTC team needs to rethink the fee/debt redistribution to maintain the list order.
It is more like a precision issue using Solidity instead of a fundamental design problem.
The following statement is worth more thinking: we can intuitively understand that new CDPs will pay more fees than the old ones. Therefore, new cpds NICR (Nominal Individual Collateral Ratio = shares/debt) will decrease at a higher rate than old ones.
Yes, higher stake leads to more fees, but it is NOT equal to “decrease at a higher rate”, actually the relative ratio of NICR between two CDPs always keep the same “theoretically” by the stake mechanism.
Note: please see sponsor’s original comment for full details regarding this.
If we could manually syncAccounting for the first CDP along the poc test path (i.e., always sync its collateral for every index increase in the loop) or simply set the loop number to 1000 instead of 100, the list order will not break at the end of the poc test.
And the break require some delicate conditions like significant increase of the Lido stETH index, e.g., 40% increase means about 10 years at the current staking reward apr.
Thanks for the careful and clear math prove from @rayeaster, it’s very helpful to show the underlying mechanism of the issue based. It’s amazing. And I want to add a comment for s2 in T3. There is no need to worry about the impact of c and s1 on Sn and Cn1 in T1, as they grow proportionally. The mathematical calculations in T3 are completely correct, and you can further prove this. I have actually done it myself, but I’m not very good at writing mathematical formulas using Markdown. So, I’m only providing this conclusion to prevent any doubts about this.
And I add one line at the end of logNICR function in the original poc:
It helps to spark an interesting idea. Do you think it would help to use sth like cdpManager.getSyncedNominalICR(firstCdpId) * 1e18 / cdpManager.getSyncedNominalICR(lastCdpId) to compare the NICR as an additional check?
Aha, I think this check may be idealistic. The poc we are currently discussing only involves a single rounding situation, but the actual scenario may be much more complex. Each syncAccounting after a rebase introduces rounding, but I believe this will actually alleviate the impact of the issue.
The impact based on bad debt redistribution is valid, but it can’t break the cdp order. Considering the fixes already introduced in Liquity, I suggest considering the impact of this issue in long-running systems. Therefore, I mark this issue as medium.
The original report as published on Code4rena, by 0xBeirao. 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.
Generating the AI write-up for this report.
This usually takes about 30 seconds. You can read the original meanwhile; this page updates itself.
Writing the technical write-up
Writing the version for beginners
Checking every passage against the original
How it worked
Root cause
Likely the fee mechanism reduces totalCollateralSnapshot without updating totalStakesSnapshot, so new CDPs get a higher stake than older ones, causing their collateral ratios to change at different rates and potentially breaking the sorted order.
What the attacker needed
Significant stETH index increase; multiple CDPs opened
The fix
The eBTC team needs to rethink the fee/debt redistribution to maintain the list order, as no quick fix was found.
How it was found
Open 100 CDPs with small stETH index increases between each.
Increase the stETH index by 40%.
Open another CDP with a collateral amount chosen to make its NICR close to the first CDP's NICR.
Check that the first CDP's NICR is less than or equal to the last CDP's NICR; the test fails, showing the list is no longer sorted.
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.
Generating the AI write-up for this report.
This usually takes about 30 seconds. You can read the original meanwhile; this page updates itself.
Writing the technical write-up
Writing the version for beginners
Checking every passage against the original
In eBTC, borrowers open collateralized debt positions (CDPs) that are kept in a sorted list by their collateral ratio. The report found that the way fees are taken can make newer CDPs have a slightly different ratio than older ones, which can break the sorting. This could cause problems like failed transactions or unfair liquidations, but the effect is very small and requires extreme conditions.
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.