Skip to content
Business logic Audit finding Advanced

Full Liquidation Won't Sweep the Whole Debts With Leaving Some, And Will Wrongly Set Borrowing as False

The liquidation function incorrectly treats debt and collateral shares as asset amounts, so a full liquidation leaves residual debt and wrongly marks the borrowing status as false. This can corrupt debt, LTV, and health factor calculations for the pool.

000000 Follow with 0xAlix2, 0xc0ffEE and 19 others

Originally disclosed on Sherlock

Source: https://github.com/sherlock-audit/2024-06-new-scope-judging/issues/107

Found by

000000, 0xAlix2, 0xc0ffEE, A2-security, Bigsam, Honour, JCN, KupiaSec, Nihavent, Obsidian, TessKimy, Varun_05, almurhasan, coffiasd, dany.armstrong90, dhank, ether_sky, iamnmt, silver_eth, stuart_the_minion, trachev, zarkk01

Full Liquidation Won't Sweep the Whole Debts With Leaving Some, And Will Wrongly Set Borrowing as False

Summary

When a liquidator tries to full liquidation (to cover full debts), there will leave some uncovered debts and the liquidation will wrongly set borrowing status of the debt asset as false.

Vulnerability Detail

According to the comment in IPoolSetters.sol, debtToCover parameter of the liquidate() function is intended to be debt assets, not shares.

The caller (liquidator) covers debtToCover amount of debt of the user getting liquidated, and receives a proportionally amount of the collateralAsset plus a bonus to cover market risk

But the _calculateDebt function call in the executeLiquidationCall() do the operations on debt shares to calculate debt amount to cover and collateral amount to buy.

Solidity
  function _calculateDebt(
    DataTypes.ExecuteLiquidationCallParams memory params,
    uint256 healthFactor,
    mapping(address => mapping(bytes32 => DataTypes.PositionBalance)) storage balances
  ) internal view returns (uint256, uint256) {
    uint256 userDebt = balances[params.debtAsset][params.position].debtShares;

    uint256 closeFactor = healthFactor > CLOSE_FACTOR_HF_THRESHOLD ? DEFAULT_LIQUIDATION_CLOSE_FACTOR : MAX_LIQUIDATION_CLOSE_FACTOR;

    uint256 maxLiquidatableDebt = userDebt.percentMul(closeFactor);

    uint256 actualDebtToLiquidate = params.debtToCover > maxLiquidatableDebt ? maxLiquidatableDebt : params.debtToCover;

    return (userDebt, actualDebtToLiquidate);
  }

According to this function, the return values userDebt and actualDebtToLiquidate are debt shares because they are not multiplied by borrow index.

Meanwhile, on the collateral reserve side, the vars.userCollateralBalance value that is provided as collateral balance to the _calculateAvailableCollateralToLiquidate() function, is collateral shares not assets. (pool/logic/LiquidationLogic.sol#L136-L148)

Solidity
    vars.userCollateralBalance = balances[params.collateralAsset][params.position].supplyShares;

    (vars.actualCollateralToLiquidate, vars.actualDebtToLiquidate, vars.liquidationProtocolFeeAmount) =
      _calculateAvailableCollateralToLiquidate(
        collateralReserve,
        vars.debtReserveCache,
        vars.actualDebtToLiquidate,
        vars.userCollateralBalance, // @audit-info Supply shares not assets
        vars.liquidationBonus,
        IPool(params.pool).getAssetPrice(params.collateralAsset),
        IPool(params.pool).getAssetPrice(params.debtAsset),
        IPool(params.pool).factory().liquidationProtocolFeePercentage()
      );

As there is no shares-to-assets conversion in the _calculateAvailableCollateralToLiquidate() function, the return values of the function vars.actualCollateralToLiquidate, vars.actualDebtToLiquidate, vars.liquidationProtocolFeeAmount are shares.

The remaining liquidation flow totally treat these share values as asset amounts. e.g. _repayDebtTokens() function calls the repayDebt function whose input is supposed to be assets:

Solidity
  function _repayDebtTokens( ... ) internal {
    uint256 burnt = balances[params.position].repayDebt(totalSupplies, vars.actualDebtToLiquidate, vars.debtReserveCache.nextBorrowIndex); // <-- @audit `vars.actualDebtToLiquidate` is shares at this moment
    vars.debtReserveCache.nextDebtShares = burnt;
  }

Thus, when a liquidator tries to cover full debts, the liquidation will leave ((borrowIndex - 1) / borrowIndex) * debtShares debt shares and will set the borrowing status of the debt asset as false via the following code snippet.

Solidity
  function executeLiquidationCall(...) external {
    ... ...
    if (vars.userDebt == vars.actualDebtToLiquidate) {
      userConfig.setBorrowing(debtReserve.id, false);
    }
    ... ...
  }

Proof-Of-Concept

To make a test case simple, I simplified the oracle price feeds like the below in the CorePoolTests.sol file:

Diff
  function _setUpCorePool() internal {
    ... ...
    oracleA = new MockV3Aggregator(8, 1e8);
-   oracleB = new MockV3Aggregator(18, 2 * 1e8);
+   oracleB = new MockV3Aggregator(8, 1e8);
    ... ...
  }

And created a new test file PoolLiquidationTest2.sol:

Solidity
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.19;

import "../../../../lib/forge-std/src/console.sol";

import './PoolSetup.sol';

import {ReserveConfiguration} from './../../../../contracts/core/pool/configuration/ReserveConfiguration.sol';

import {UserConfiguration} from './../../../../contracts/core/pool/configuration/UserConfiguration.sol';

contract PoolLiquidationTest2 is PoolSetup {
  using UserConfiguration for DataTypes.UserConfigurationMap;
  using ReserveConfiguration for DataTypes.ReserveConfigurationMap;
  using ReserveConfiguration for DataTypes.ReserveData;

  address alice = address(1);
  address bob = address(2);

  uint256 mintAmountA = 200 ether;
  uint256 mintAmountB = 200 ether;
  uint256 supplyAmountA = 60 ether;
  uint256 supplyAmountB = 60 ether;
  uint256 borrowAmountB = 45 ether;

  function setUp() public {
    _setUpPool();
    pos = keccak256(abi.encodePacked(alice, 'index', uint256(0)));
  }

  // @audit-poc
  function testLiquidationInvalidUnits() external {
    oracleA.updateAnswer(1e8);
    oracleB.updateAnswer(1e8);

    _mintAndApprove(alice, tokenA, mintAmountA, address(pool));
    _mintAndApprove(bob, tokenB, mintAmountB, address(pool));

    vm.startPrank(alice);
    pool.supplySimple(address(tokenA), alice, supplyAmountA, 0);
    vm.stopPrank();

    vm.startPrank(bob);
    pool.supplySimple(address(tokenB), bob, supplyAmountB, 0);
    vm.stopPrank();

    vm.startPrank(alice);
    pool.borrowSimple(address(tokenB), alice, borrowAmountB, 0);
    vm.stopPrank();

    // Advance time to make the position unhealthy
    vm.warp(block.timestamp + 360 days);
    oracleA.updateAnswer(1e8);
    oracleB.updateAnswer(1e8);

    // Print log of borrow rate before liquidation
    pool.forceUpdateReserve(address(tokenB));
    DataTypes.ReserveData memory reserveDataB = pool.getReserveData(address(tokenB));
    console.log("reserveDataB.borrowIndex before Liq.", reserveDataB.borrowIndex);

    DataTypes.PositionBalance memory positionBalance = pool.getBalanceRawByPositionId(address(tokenB), pos);
    console.log('debtShares Before Liq.', positionBalance.debtShares);

    DataTypes.UserConfigurationMap memory userConfig = pool.getUserConfiguration(alice, 0);
    console.log('TokenB isBorrowing Before Liq.', UserConfiguration.isBorrowing(userConfig, reserveDataB.id));

    vm.startPrank(bob);
    vm.expectEmit(true, true, true, false);
    emit PoolEventsLib.LiquidationCall(address(tokenA), address(tokenB), pos, 0, 0, bob);
    pool.liquidateSimple(address(tokenA), address(tokenB), pos, 100 ether); // @audit Tries to cover full debts
    vm.stopPrank();

    positionBalance = pool.getBalanceRawByPositionId(address(tokenB), pos);
    console.log('debtShares After Liq.', positionBalance.debtShares);

    userConfig = pool.getUserConfiguration(alice, 0);
    console.log('TokenB isBorrowing After Liq.', UserConfiguration.isBorrowing(userConfig, reserveDataB.id));
  }
}

And here are the logs:

Bash
$ forge test --match-test testLiquidationInvalidUnits -vvv
[⠒] Compiling...
[⠊] Compiling 1 files with Solc 0.8.19
[⠒] Solc 0.8.19 finished in 4.83s
Compiler run successful!

Ran 1 test for test/forge/core/pool/PoolLiquidationPocTests2.t.sol:PoolLiquidationTest2
[PASS] testLiquidationInvalidUnits() (gas: 1172963)
Logs:
  reserveDataB.borrowIndex before Liq. 1252660064369089319656921640
  debtShares Before Liq. 45000000000000000000
  TokenB isBorrowing Before Liq. true
  debtShares After Liq. 9076447170314674990
  TokenB isBorrowing After Liq. false

As can be seen from the logs, there are significant amount of debts left but the borrowing flag was set as false.

Impact

Wrongly setting borrowing status as false will affect the calculation of total debt amount, LTV and health factor, and this incorrect calculation will affect the whole ecosystem of a pool.

Code Snippet

pool/logic/LiquidationLogic.sol#L136

pool/logic/LiquidationLogic.sol#L264

Tool used

Manual Review

Recommendation

Update the issued lines in the LiquidationLogic.sol file:

Diff
  function executeLiquidationCall(
    ... ...
  ) external {
    ... ...
-   vars.userCollateralBalance = balances[params.collateralAsset][params.position].supplyShares;
+   vars.userCollateralBalance = balances[params.collateralAsset][params.position].getSupplyBalance(collateralReserve.liquidityIndex);
    ... ...
  }

  function _calculateDebt(
    ... ...
  ) internal view returns (uint256, uint256) {
-   uint256 userDebt = balances[params.debtAsset][params.position].debtShares;
+   uint256 userDebt = balances[params.debtAsset][params.position].getDebtBalance(borrowIndex);
  }

I tried the above POC testcase to the update and the logs are:

Bash
$ forge test --match-test testLiquidationInvalidUnits -vv
[⠒] Compiling...
[⠊] Compiling 7 files with Solc 0.8.19
[⠒] Solc 0.8.19 finished in 5.90s
Compiler run successful!

Ran 1 test for test/forge/core/pool/PoolLiquidationPocTests2.t.sol:PoolLiquidationTest2
[PASS] testLiquidationInvalidUnits() (gas: 1137920)
Logs:
  reserveDataB.borrowIndex before Liq. 1252660064369089319656921640
  debtShares Before Liq. 45000000000000000000
  TokenB isBorrowing Before Liq. true
  debtShares After Liq. 0
  TokenB isBorrowing After Liq. false

Discussion

DemoreXTess

Escalate

There are two distinct issues that have been grouped into the same issue pool. While the impact is similar, the root causes of the issues are completely different. This categorization is also unfair to the Watsons who reported both issues.

sherlock-admin3

Escalate

There are two distinct issues that have been grouped into the same issue pool. While the impact is similar, the root causes of the issues are completely different. This categorization is also unfair to the Watsons who reported both issues.

You've created a valid escalation!

To remove the escalation from consideration: Delete your comment.

You may delete or edit your escalation comment anytime before the 48-hour escalation window closes. After that, the escalation becomes final.

Tomiwasa0

Again i agree with @DemoreXTess , These are two different functions, A fix for A doesn't solve B although the seem similar. Hence 2 different Root cause, similar impact. They should be Duplicated into

  1. Wrong debt amount
  2. Wrong Collateral amount

samuraii77

Escalate

There are two distinct issues that have been grouped into the same issue pool. While the impact is similar, the root causes of the issues are completely different. This categorization is also unfair to the Watsons who reported both issues.

No, it's unfair for watsons who reported both as one if they are split into 2. The issue caused by a single root cause.

DemoreXTess

@samuraii77 People who submitted both issues at ones should be the duplicate of both two unique issues. There is nothing wrong about that.

cvetanovv

I disagree with the escalation and thought the Lead Judge correctly duplicated them.

The root cause is that the liquidation will be called with wrong values. And those Watsons who correctly judged the root cause would be harmed by a potential separation.

Planning to reject the escalation and leave the issue as is.

DemoreXTess

@cvetanovv I don't understand. What is your argument for your rejection ? Some of watsons will suffer from that or issues are really same ?

The root cause are completely different. Solving one of those problems doesn't solve the other issue. They are not even in same block scope.

If the reason of rejection is the reports who mentioned both issues, we should also consider the watsons who submitted both issues in separate. There are 2 different high issues and it reduces the worth of submissions significantly which is far worse in this situation.

DemoreXTess

@cvetanovv If you system doesnt support 1 report 2 duplicate system, we can't do anything for them but it is Watson's responsibility to identify which issue is duplicate of another issue. Those issues are definitely different as I stated above.

cvetanovv

@DemoreXTess This is not the main reason.

As I have written, the root cause is that the liquidation will be called with wrong values.

You can also see my comment on your other similar escalation https://github.com/sherlock-audit/2024-06-new-scope-judging/issues/473#issuecomment-2426173895

The same principle is grouped when there are reentrancy vulnerabilities, lack of slippage protection, or unsafe cast. Even if they are different functions and contracts, we duplicate them together.

DemoreXTess

@cvetanovv Okay, then my escalations are invalid for both. I didn't know that rule in Sherlock. Thank you for clarification.

WangSecurity

Result: High Has duplicates

sherlock-admin4

Escalations have been resolved successfully!

Escalation status:

The original report as published on Sherlock, by 000000. 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 liquidation logic uses debt and collateral shares directly as if they were asset amounts, without converting them using the borrow or liquidity index.

Impact

The incorrect debt and borrowing status can distort total debt, LTV, and health factor calculations, potentially affecting the entire pool ecosystem.

What the attacker needed

A lending pool with liquidation enabled; an unhealthy borrower position; a liquidator calls liquidate

The fix

The code should convert shares to assets using the appropriate index before using them in liquidation calculations.

How it was found

  1. Set up a pool with two tokens and equal prices.
  2. Alice supplies tokenA and borrows tokenB.
  3. Time passes, making the position unhealthy.
  4. Bob calls liquidateSimple with a debtToCover larger than the actual debt.
  5. After liquidation, debtShares remain nonzero but the borrowing flag is false.

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 pool, when someone's collateral is liquidated, the code should work with actual token amounts, not with internal share units. Here, the code mixed up shares and assets, so after a supposed full repayment, some debt remained but the system marked the loan as fully repaid. This could make the pool's accounting wrong and affect other users.

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 000000

View all

32 more disclosed reports, best first.

More from ZeroLend One

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.