Underflow in ```_previewWithdraw``` could prevent withdrawals
An underflow in the _previewWithdraw function occurs when totalContractsSold exceeds auction.totalContracts, causing the transaction to revert. This prevents users from withdrawing their options from the auction contract.
yixxas Follow with __141345__, hansfriese and 3 others
Originally disclosed on Sherlock
Source: https://github.com/sherlock-audit/2022-09-knox-judging/issues/106
Found by
yixxas, __141345__, hansfriese, 0x52, dipp, Trumpero
Summary
An underflow in the _previewWithdraw function in AuctionInternal.sol due to totalContractsSold exceeding auction.totalContracts could prevent users from withdrawing options.
Vulnerability Detail
The _previewWithdraw function returns the fill and refund amounts for a buyer by looping over all orders. A totalContractsSold variable is used to track the amount of contracts sold as the loop iterates over all orders. If the current order's size + totalContractsSold exceeds the auction's totalContracts then the order will only be filled partially. The calculation for the partial fill (remainder) is given on line 318. This will lead to an underflow if totalContractsSold > the auction's totalContracts which would happen if there are multiple orders that cause the totalContractsSold variable to exceed totalContracts.
The totalContractsSold variable in _previewWithdraw could exceed the auction.totalContracts due to the contracts sold before the start of an auction through limit orders not being limited. When an order is added, _finalizeAuction is only called if the auction has started. The _finalizeAuction function will call the _processOrders function which will return true if the auction has reached 100% utilization. Since limit orders can be made before the start of an auction, _finalizeAuction is not called and any amount of new orders may be made.
Example: The buyer makes a limit order with size > auction.totalContracts. They then make another order with size of anything. These orders are made before the start of the auction so _processOrders is not called for every new order and totalContractsSold can exceed totalContracts. When _previewWithdraw is called, after the buyer's first order is processed, totalContractsSold > auction.totalContracts so the condition on line 313 passes. Since totalContractsSold > auction.totalContracts the calculation on line 318 underflows and the transaction reverts. The _previewWithdraw function and thus the _withdraw function is uncallable.
Test code added to Auction.behaviour.ts, under the #addLimitOrder(uint64,int128,uint256) section:
it("previewWithdraw reverts if buyer has too many contracts", async () => {
assert.isEmpty(await auction.getEpochsByBuyer(addresses.buyer1));
await asset
.connect(signers.buyer1)
.approve(addresses.auction, ethers.constants.MaxUint256);
const totalContracts = await auction.getTotalContracts(epoch);
await auction.addLimitOrder(
epoch,
fixedFromFloat(params.price.max),
totalContracts.mul(2)
);
await auction.addLimitOrder(
epoch,
fixedFromFloat(params.price.max),
totalContracts.div(2)
);
const epochByBuyer = await auction.getEpochsByBuyer(addresses.buyer1);
assert.equal(epochByBuyer.length, 1);
assert.bnEqual(epochByBuyer[0], epoch);
await expect(auction.callStatic[
"previewWithdraw(uint64)"
](epoch)).to.be.reverted;
});
The test code above shows a buyer is able to add an order with size auction.totalContracts*2 and a subsequent order with size auction.totalContracts/2. The previewWithdraw function reverts when called.
Impact
Users would be unable to withdraw from the Auction contract.
Code Snippet
AuctionInternal.sol:_previewWithdraw#L312-L321
if (
totalContractsSold + data.size >= auction.totalContracts
) {
// if part of the current order exceeds the total contracts available, partially
// fill the order, and refund the remainder
uint256 remainder =
auction.totalContracts - totalContractsSold;
cost = lastPrice64x64.mulu(remainder);
fill += remainder;
AuctionInternal.sol:_validateLimitOrder#L479-L489
function _validateLimitOrder(
AuctionStorage.Layout storage l,
int128 price64x64,
uint256 size
) internal view returns (uint256) {
require(price64x64 > 0, "price <= 0");
require(size >= l.minSize, "size < minimum");
uint256 cost = price64x64.mulu(size);
return cost;
}
AuctionInternal.sol:_addOrder#L545-L562
function _addOrder(
AuctionStorage.Layout storage l,
AuctionStorage.Auction storage auction,
uint64 epoch,
int128 price64x64,
uint256 size,
bool isLimitOrder
) internal {
l.epochsByBuyer[msg.sender].add(epoch);
uint256 id = l.orderbooks[epoch]._insert(price64x64, size, msg.sender);
if (block.timestamp >= auction.startTime) {
_finalizeAuction(l, auction, epoch);
}
emit OrderAdded(epoch, id, msg.sender, price64x64, size, isLimitOrder);
}
Tool used
Manual Review
Recommendation
The loop in _previewWithdraw should check if the current totalContractsSold is >= totalContracts. If it is then the remainder should be set to 0 which would allow the current order to be fully refunded.
Additionally, the orders for an auction should be checked before the auction starts. In _addOrder, consider adding a condition that will call _processOrders if the auction has not started yet. If _processOrders returns true then do not allow the order to be added. Or just allow the auction to be finalized before it starts if the total contracts sold has reached the auction's totalContracts.
Discussion
0xCourtney
https://github.com/KnoxFinance/knox-contracts/pull/80
rcstanciu
Reply from @arbitrary-CodeBeholder
fixes look good
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 _previewWithdraw function does not handle the case where totalContractsSold exceeds auction.totalContracts, leading to an underflow in the remainder calculation.
Impact
Users would be unable to withdraw from the Auction contract.
What the attacker needed
Auction not yet started; Buyer can add limit orders
The fix
The loop in _previewWithdraw should check if totalContractsSold is >= totalContracts and set remainder to 0, and _addOrder should call _processOrders even before the auction starts to prevent orders that exceed totalContracts.
How it was found
- Buyer approves the auction contract to spend their tokens.
- Buyer adds a limit order with size greater than auction.totalContracts before the auction starts.
- Buyer adds another limit order with any size before the auction starts.
- Buyer calls previewWithdraw, which reverts due to underflow.
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 smart contract, numbers have a fixed size, and subtracting a larger number from a smaller one causes an 'underflow' that makes the transaction fail. Here, a calculation error in the withdrawal function means that if too many contracts are sold, the function crashes and users cannot withdraw their funds.
What is Smart contracts?
Flaws in on-chain code that let an attacker drain funds, freeze them or break the protocol's accounting.