The collateral remainder cap is incorrectly calculated during liquidation
The liquidation function incorrectly calculates the collateral remainder cap by using the full liquidation collateral ratio instead of the excess over 100%, causing users with higher collateral ratios to lose more collateral to the protocol. An attacker could exploit this to unfairly penalise users with higher collateral ratios, discouraging healthy collateralisation.
ether_sky Follow with hyh, samuraii77 and 6 others
Originally disclosed on Code4rena
Submitted by ether_sky, also found by hyh, samuraii77, m4k2, KupiaSec, stakog, AMOW, jsmi, and Bob
When a position is overdue, it can be liquidated even if the owner has a sufficient collateral ratio. Some rewards are sent to the liquidator as an incentive and some fees are assigned to the protocol. However, the calculation of the protocol fee is flawed due to an incorrect collateral remainder cap calculation.
Imagine the collateral ratio for liquidation is set at 130%. The collateral equivalent to the debt should be paid to the protocol, and the excess collateral (30%) can be the remainder cap. Currently, the entire 130% is treated as the remainder cap, leading to an unfair situation where a user with a 150% collateral ratio experiences more loss than a user with a 140% CR.
This discourages users with higher CRs, who generally contribute to the protocol’s health. If higher CRs result in greater losses, it disincentivizes users from providing sufficient collateral to the protocol.
Proof of Concept
Imagine Bob and Candy have the same debt position, and these positions are overdue.
- The collateral ratio for liquidation is 130%.
- Candy has a 150% collateral ratio, and Bob has a 140% CR.
Both positions are liquidated by liquidators:
function executeLiquidate(State storage state, LiquidateParams calldata params)
external
returns (uint256 liquidatorProfitCollateralToken)
{
DebtPosition storage debtPosition = state.getDebtPosition(params.debtPositionId);
LoanStatus loanStatus = state.getLoanStatus(params.debtPositionId);
uint256 collateralRatio = state.collateralRatio(debtPosition.borrower)
uint256 collateralProtocolPercent = state.isUserUnderwater(debtPosition.borrower)
? state.feeConfig.collateralProtocolPercent
: state.feeConfig.overdueCollateralProtocolPercent;
uint256 assignedCollateral = state.getDebtPositionAssignedCollateral(debtPosition); // @1
uint256 debtInCollateralToken = state.debtTokenAmountToCollateralTokenAmount(debtPosition.futureValue); // @2
uint256 protocolProfitCollateralToken = 0;
// profitable liquidation
if (assignedCollateral > debtInCollateralToken) {
uint256 liquidatorReward = Math.min(
assignedCollateral - debtInCollateralToken,
Math.mulDivUp(debtPosition.futureValue, state.feeConfig.liquidationRewardPercent, PERCENT)
); // @3
liquidatorProfitCollateralToken = debtInCollateralToken + liquidatorReward;
// split the remaining collateral between the protocol and the borrower, capped by the crLiquidation
uint256 collateralRemainder = assignedCollateral - liquidatorProfitCollateralToken; // @4
// cap the collateral remainder to the liquidation collateral ratio
// otherwise, the split for non-underwater overdue loans could be too much
uint256 cllateralRemainderCap =
Math.mulDivDown(debtInCollateralToken, state.riskConfig.crLiquidation, PERCENT); // @5
collateralRemainder = Math.min(collateralRemainder, collateralRemainderCap);
protocolProfitCollateralToken = Math.mulDivDown(collateralRemainder, collateralProtocolPercent, PERCENT); // @6
}
}
@1: Calculate assigned collaterals to the debt position. The amount assigned from Candy’s collateral is larger than that from Bob’s.
@2: Convert the debt token to the collateral token. The converted amounts are the same for both users.
@3: Calculate the reward for liquidation. These amounts are the same because the debt sizes are the same and both users have enough CR to cover the profit.
@4: Calculate the collateral remainder. Candy obviously has a larger amount.
@5: Calculate the collateral remainder cap. The cap should be 30%, but it is currently calculated as 130%, which is the CR for liquidation itself.
@6: As a result, Candy will experience more loss than Bob due to their excess amounts (50%, 40%) being below the cap (130%).
If users know that they will experience more loss when they have a larger CR, they will tend to maintain their CR as low as possible. While they will try to avoid liquidation, there will be no users with a CR higher than, for example, 200%. This is detrimental to the protocol.
Please check below log:
future value of Bob => 60000000
future value of Candy => 60000000
assigned collateral of Bob => 100000000000000000000
assigned collateral of Candy => 120000000000000000000
debt in collateral token of Bob => 60000000000000000000
debt in collateral token of Candy => 60000000000000000000
liquidator reward of Bob => 3000000
liquidator reward of Candy => 3000000
liquidator profit of collateral token of Bob => 60000000000003000000
liquidator profit of collateral token of Candy => 60000000000003000000
collateral remainder of Bob => 39999999999997000000
collateral remainder of Candy => 59999999999997000000
collateral remainder cap of Bob => 78000000000000000000
collateral remainder cap of Candy => 78000000000000000000
collateral remainder of Bob => 39999999999997000000
collateral remainder of Candy => 59999999999997000000
protocol profit collateral token of Bob => 399999999999970000
protocol profit collateral token of Candy => 599999999999970000
Please add below test to the test/local/actions/Liquidate.t.sol: (use --var-ir flag):
function test_liquidate_protocol_profit() public {
_deposit(alice, usdc, 300e6);
_deposit(bob, weth, 100e18);
_deposit(candy, weth, 120e18);
_deposit(liquidator, weth, 1000e18);
_deposit(liquidator, usdc, 1000e6);
_buyCreditLimit(alice, block.timestamp + 365 days, YieldCurveHelper.pointCurve(365 days, 0.03e18));
uint256 debtPositionIdOfBob = _sellCreditMarket(bob, alice, RESERVED_ID, 60e6, 365 days, true);
uint256 debtPositionIdOfCandy = _sellCreditMarket(candy, alice, RESERVED_ID, 60e6, 365 days, true);
vm.warp(block.timestamp + 365 days + 1 days);
// 1 WETH = 1 USDC for test
_setPrice(1e18);
// loan is not underwater, but it's overdue
uint256 collateralProtocolPercent = size.feeConfig().overdueCollateralProtocolPercent;
uint256 futureValueOfBob = size.getDebtPosition(debtPositionIdOfBob).futureValue;
uint256 futureValueOfCandy = size.getDebtPosition(debtPositionIdOfCandy).futureValue;
console2.log('future value of Bob => ', futureValueOfBob);
console2.log('future value of Candy => ', futureValueOfCandy);
// uint256 assignedCollateral = state.getDebtPositionAssignedCollateral(debtPosition); (Line 90)
uint256 assignedCollateralOfBob = size.getDebtPositionAssignedCollateral(debtPositionIdOfBob);
uint256 assignedCollateralOfCandy = size.getDebtPositionAssignedCollateral(debtPositionIdOfCandy);
console2.log('assigned collateral of Bob => ', assignedCollateralOfBob);
console2.log('assigned collateral of Candy => ', assignedCollateralOfCandy);
// uint256 debtInCollateralToken = state.debtTokenAmountToCollateralTokenAmount(debtPosition.futureValue); (Line 91)
uint256 debtInCollateralTokenOfBob = size.debtTokenAmountToCollateralTokenAmount(futureValueOfBob);
uint256 debtInCollateralTokenOfCandy = size.debtTokenAmountToCollateralTokenAmount(futureValueOfCandy);
console2.log('debt in collateral token of Bob => ', debtInCollateralTokenOfBob);
console2.log('debt in collateral token of Candy => ', debtInCollateralTokenOfCandy);
// Line 96
uint256 liquidatorRewardOfBob = Math.min(
assignedCollateralOfBob - debtInCollateralTokenOfBob,
Math.mulDivUp(futureValueOfBob, size.feeConfig().liquidationRewardPercent, PERCENT)
);
uint256 liquidatorRewardOfCandy = Math.min(
assignedCollateralOfCandy - debtInCollateralTokenOfCandy,
Math.mulDivUp(futureValueOfCandy, size.feeConfig().liquidationRewardPercent, PERCENT)
);
console2.log('liquidator reward of Bob => ', liquidatorRewardOfBob);
console2.log('liquidator reward of Candy => ', liquidatorRewardOfCandy);
// liquidatorProfitCollateralToken = debtInCollateralToken + liquidatorReward; (Line 100)
uint256 liquidatorProfitCollateralTokenOfBob = debtInCollateralTokenOfBob + liquidatorRewardOfBob;
uint256 liquidatorProfitCollateralTokenOfCandy = debtInCollateralTokenOfCandy + liquidatorRewardOfCandy;
console2.log('liquidator profit of collateral token of Bob => ', liquidatorProfitCollateralTokenOfBob);
console2.log('liquidator profit of collateral token of Candy => ', liquidatorProfitCollateralTokenOfCandy);
// uint256 collateralRemainder = assignedCollateral - liquidatorProfitCollateralToken; (Line 103)
uint256 collateralRemainderOfBob = assignedCollateralOfBob - liquidatorProfitCollateralTokenOfBob;
uint256 collateralRemainderOfCandy = assignedCollateralOfCandy - liquidatorProfitCollateralTokenOfCandy;
console2.log('collateral remainder of Bob => ', collateralRemainderOfBob);
console2.log('collateral remainder of Candy => ', collateralRemainderOfCandy);
// Line 107
uint256 cllateralRemainderCapOfBob = Math.mulDivDown(debtInCollateralTokenOfBob, size.riskConfig().crLiquidation, PERCENT);
uint256 cllateralRemainderCapOfCandy = Math.mulDivDown(debtInCollateralTokenOfBob, size.riskConfig().crLiquidation, PERCENT);
console2.log('collateral remainder cap of Bob => ', cllateralRemainderCapOfBob);
console2.log('collateral remainder cap of Candy => ', cllateralRemainderCapOfCandy);
// collateralRemainder = Math.min(collateralRemainder, collateralRemainderCap);(Line 110)
collateralRemainderOfBob = Math.min(collateralRemainderOfBob, cllateralRemainderCapOfBob);
collateralRemainderOfCandy = Math.min(collateralRemainderOfCandy, cllateralRemainderCapOfCandy);
console2.log('collateral remainder of Bob => ', collateralRemainderOfBob);
console2.log('collateral remainder of Candy => ', collateralRemainderOfCandy);
// protocolProfitCollateralToken = Math.mulDivDown(collateralRemainder, collateralProtocolPercent, PERCENT); (Line 112)
uint256 protocolProfitCollateralTokenOfBob = Math.mulDivDown(collateralRemainderOfBob, collateralProtocolPercent, PERCENT);
uint256 protocolProfitCollateralTokenOfCandy = Math.mulDivDown(collateralRemainderOfCandy, collateralProtocolPercent, PERCENT);
console2.log('protocol profit collateral token of Bob => ', protocolProfitCollateralTokenOfBob);
console2.log('protocol profit collateral token of Candy => ', protocolProfitCollateralTokenOfCandy);
uint256 balanceOfProtocolForBobBefore = size.data().collateralToken.balanceOf(size.feeConfig().feeRecipient);
_liquidate(liquidator, debtPositionIdOfBob, 0);
uint256 balanceOfProtocolForBobAfter = size.data().collateralToken.balanceOf(size.feeConfig().feeRecipient);
uint256 balanceOfProtocolForCandyBefore = size.data().collateralToken.balanceOf(size.feeConfig().feeRecipient);
_liquidate(liquidator, debtPositionIdOfCandy, 0);
uint256 balanceOfProtocolForCandyAfter = size.data().collateralToken.balanceOf(size.feeConfig().feeRecipient);
// The actual profit matches the calculation above.
assertEq(protocolProfitCollateralTokenOfBob, balanceOfProtocolForBobAfter - balanceOfProtocolForBobBefore);
assertEq(protocolProfitCollateralTokenOfCandy, balanceOfProtocolForCandyAfter - balanceOfProtocolForCandyBefore);
}
Recommended Mitigation Steps
function executeLiquidate(State storage state, LiquidateParams calldata params)
external
returns (uint256 liquidatorProfitCollateralToken)
{
if (assignedCollateral > debtInCollateralToken) {
uint256 liquidatorReward = Math.min(
assignedCollateral - debtInCollateralToken,
Math.mulDivUp(debtPosition.futureValue, state.feeConfig.liquidationRewardPercent, PERCENT)
);
liquidatorProfitCollateralToken = debtInCollateralToken + liquidatorReward;
uint256 collateralRemainder = assignedCollateral - liquidatorProfitCollateralToken;
- uint256 cllateralRemainderCap =
Math.mulDivDown(debtInCollateralToken, state.riskConfig.crLiquidation, PERCENT);
+ uint256 cllateralRemainderCap =
Math.mulDivDown(debtInCollateralToken, state.riskConfig.crLiquidation - PERCENT, PERCENT);
}
}
Assessed type
Math
aviggiano (Size) confirmed via duplicate Issue #140
hansfriese (judge) increased severity to High and commented:
Marking this report as primary with the detailed POC.
MotokoKusanagi-aka-Major (Size) commented:
We acknowledge the severity of these issues being high since they impact the users negatively and are not unlikely to happen, but we want to share a bit more context of how these bugs have been introduced into the code
H-03 and H-04 are two incorrect implementations of formulas correctly specified in the tech documentation, much like H-01. Note that this means that three of the four high-severity issues were simply incorrect implementations of formulas.
Incorrect implementations of this sort are usually easily caught by simple unit tests relying on pre-computed expected values so it is uncommon to find them in audit reports–and indeed numerous wardens also caught these bugs during the C4 competition–so we want to explain why this happened to avoid incorrect conclusions about our development process.
One finding of the Spearbit Audit (the one before the C4) required us to redesign and reimplement the fee mechanism entirely.
The changes required were quite significant and we had a tight deadline since we had already defined C4 start date and the launch date. This required us to be very judicious with our time and focus on the actual implementation and be light on tests to avoid having to reschedule the C4 competition.
However, since what ultimately matters the most for us is the security of our code, we worked on the tests in parallel with the competition and we were able to identify these bugs even before they were also discovered by the C4 competitors.
In conclusion, we were aware the strategy we had chosen would have increased the risk of having more bugs found during the competition–we did not optimize for receiving “high grades” from the competition (even though overall the “grades” we received seem pretty much aligned with the ones of other protocols). We chose the strategy to be able to meet the deadlines for the competition, and ultimately it did not come at the cost of less code security.
See also Issue #21.
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 collateral remainder cap is calculated as debtInCollateralToken * crLiquidation / PERCENT, but it should be debtInCollateralToken * (crLiquidation - PERCENT) / PERCENT to cap only the excess over the debt.
Impact
Users with higher collateral ratios suffer greater losses upon liquidation, which could incentivise users to maintain lower collateral ratios, potentially harming the protocol's health.
What the attacker needed
Overdue loan; liquidator available
The fix
The collateral remainder cap should be calculated as debtInCollateralToken * (crLiquidation - PERCENT) / PERCENT instead of using the full crLiquidation.
How it was found
- Set up two users, Bob and Candy, with the same debt but different collateral ratios (140% and 150%).
- Make the loans overdue and liquidate both positions.
- Observe that the protocol profit (and thus the borrower's loss) is higher for Candy despite her higher collateral ratio.
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 a lending protocol, if a loan is overdue, anyone can liquidate it to get a reward. The protocol also takes a fee from the remaining collateral. The bug is that the fee is calculated using the wrong cap, so users who put up more collateral (which is safer) end up paying more fees when liquidated. This is unfair and could discourage people from over-collateralising.
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.