Skip to content
DoS Audit finding Advanced

ShortOrders can be created with ercAmount == minAskEth/2 , increasing the gas costs for matching large orders and disincentivizing liquidators from liquidating them

A user can create a ShortOrder with an ercAmount of minAskEth/2 by matching a bid that leaves that amount and then exiting the ShortRecord using a cancelled ShortOrder ID that still points to it. This can increase gas costs for matching large orders and disincentivize liquidators from liquidating small orders.

nonseodion Follow with 0xbepresent

Originally disclosed on Code4rena

Submitted by nonseodion, also found by 0xbepresent

A user can create a ShortOrder with ercAmount == minAskEth/2 by matching the ShortOrder with a bid that fills it up to minAskEth/2 and exiting the ShortRecord leaving only minAskEth/2 in the ShortOrder with an empty ShortRecord.

Description

This issue makes use of two properties in the codebase.

  1. A ShortOrder can be matched such that only minAskEth/2 remains in the ShortOrder.

A ShortOrder on the market can be matched by an incoming bid. This match is done in the call to bidMatchAlgo() function. Which tries to fill the bid with asks or shorts in the market.

BidOrdersFacet.sol#L106-L111

        if (incomingBid.price >= lowestSell.price && (lowestSell.orderType == O.LimitAsk || lowestSell.orderType == O.LimitShort)) {
            // @dev if match and match price is gt .5% to saved oracle in either direction, update startingShortId
            LibOrders.updateOracleAndStartingShortViaThreshold(asset, LibOracle.getPrice(asset), incomingBid, shortHintArray);
            b.shortHintId = b.shortId = Asset.startingShortId;
            b.oraclePrice = LibOracle.getPrice(asset);
❌          return bidMatchAlgo(asset, incomingBid, orderHintArray, b);

In the call to bidMatchAlgo(), it goes through a loop and on each iteration, it first tries to match lowestSell in line 155 below. lowestSell is the current lowest bid or ask. After matching it compares the ercAmount in the bid and lowest sell.

If the ercAmount in the lowest sell exceeds that in the bid, the bid is filled and executes the else statement in line 179 below. If the amount left in the lowest sell is >= LibAsset.minAskEth(asset).mul(C.DUST_FACTOR), b.dustShortId and b.dustAskId are set to zero in line 191 below. This ensures the lowest sell isn’t deleted in the call to matchIncomingBid() function.

BidOrdersFacet.sol#L155-L197

155:                 matchlowestSell(asset, lowestSell, incomingBid, matchTotal);
156:                 if (incomingBid.ercAmount > lowestSell.ercAmount) {
157:                     incomingBid.ercAmount -= lowestSell.ercAmount;
158:                     lowestSell.ercAmount = 0;
159:                     if (lowestSell.isShort()) {
160:                         b.matchedShortId = lowestSell.id;
161:                         b.prevShortId = lowestSell.prevId;
162:                         LibOrders.matchOrder(s.shorts, asset, lowestSell.id);
163:                         _shortDirectionHandler(asset, lowestSell, incomingBid, b);
164:                     } else {
165:                         b.matchedAskId = lowestSell.id;
166:                         LibOrders.matchOrder(s.asks, asset, lowestSell.id);
167:                         b.askId = lowestSell.nextId;
168:                     }
169:                 } else {
170:                     if (incomingBid.ercAmount == lowestSell.ercAmount) {
171:                         if (lowestSell.isShort()) {
172:                             b.matchedShortId = lowestSell.id;
173:                             b.prevShortId = lowestSell.prevId;
174:                             LibOrders.matchOrder(s.shorts, asset, lowestSell.id);
175:                         } else {
176:                             b.matchedAskId = lowestSell.id;
177:                             LibOrders.matchOrder(s.asks, asset, lowestSell.id);
178:                         }
179:                     } else {
180:                         lowestSell.ercAmount -= incomingBid.ercAmount;
181:                         if (lowestSell.isShort()) {
182:                             b.dustShortId = lowestSell.id;
183:                             STypes.Order storage lowestShort = s.shorts[asset][lowestSell.id];
184:                             lowestShort.ercAmount = lowestSell.ercAmount;
185:                         } else {
186:                             b.dustAskId = lowestSell.id;
187:                             s.asks[asset][lowestSell.id].ercAmount = lowestSell.ercAmount;
188:                         }
189:                         // Check reduced dust threshold for existing limit orders
190:                         if (lowestSell.ercAmount.mul(lowestSell.price) >= LibAsset.minAskEth(asset).mul(C.DUST_FACTOR)) {
191:                             b.dustShortId = b.dustAskId = 0;
192:                         }
193:                     }
194:                     incomingBid.ercAmount = 0;
195:                     return matchIncomingBid(asset, incomingBid, matchTotal, b);
196:                 }
197:             } else {

If the amount in lowestSell is less than LibAsset.minAskEth(asset).mul(C.DUST_FACTOR), matchIncomingBid() deletes in the code section below.

BidOrdersFacet.sol#L292-L296

        if (b.dustAskId > 0) {
            IDiamond(payable(address(this)))._cancelAsk(asset, b.dustAskId);
        } else if (b.dustShortId > 0) {
            IDiamond(payable(address(this)))._cancelShort(asset, b.dustShortId);
        }

LibAsset.minAskEth(asset).mul(C.DUST_FACTOR) translates to minAskEth/2 because C.DUST_FACTOR is a constant and is 0.5 ether. So if a ShortOrder has minAskEth/2 it won’t be deleted.

  1. A ShortRecord can be exited with the id of a cancelled ShortOrder that still points to it.

When a call is made to the exitShortWallet() or exitShortErcEscrowed() function, shortOrderId is passed which is expected to be the order id of the ShortRecord currently being exited. exitShortWallet() function calls checkShortMinErc() and passes the shortOrderId.

ExitShortFacet.sol#L67-L73

        LibSRUtil.checkShortMinErc({
            asset: asset,
            initialStatus: initialStatus,
            shortOrderId: shortOrderId,
            shortRecordId: id,
            shorter: msg.sender
        });

In the call to checkShortMinErc(), the shortOrderId is verified in line 94 below by checking if the shortOrder currently points to ShortRecord or if its address points to the shorter, i.e. the owner of the ShortRecord.

LibSRUtil.sol#L81-L99

091:         if (initialStatus == SR.PartialFill) {
092:             // Verify shortOrder
093:             STypes.Order storage shortOrder = s.shorts[asset][shortOrderId];
094:             if (shortOrder.shortRecordId != shortRecordId || shortOrder.addr != shorter) revert Errors.InvalidShortOrder();
095:
096:             if (shortRecord.status == SR.Closed) {
097:                 // Check remaining shortOrder
098:                 if (shortOrder.ercAmount < minShortErc) {
099:                     // @dev The resulting SR will not have PartialFill status after cancel
100:                     LibOrders.cancelShort(asset, shortOrderId);
101:                     isCancelled = true;
102:                 }
103:             } else {
104:                 // Check remaining shortOrder and remaining shortRecord
105:                 if (shortOrder.ercAmount + shortRecord.ercDebt < minShortErc) revert Errors.CannotLeaveDustAmount();
106:             }
107:         } else if (shortRecord.status != SR.Closed && shortRecord.ercDebt < minShortErc) {
108:             revert Errors.CannotLeaveDustAmount();
109:         }

Note: it doesn’t check if the ShortOrder is cancelled. This means we can use a cancelled ShortOrder that points to the ShortRecord and is owned by the owner of the ShortRecord being exited.

A malicious user can use these two properties of the codebase to create a ShortOrder that has minAskEth/2 as ercAmount and 0 debt in its ShortRecord by following these setps:

  1. Create 1 shortOrder with address A and another with address B. They shouldn’t get matched.
  2. Cancel address A’s shortOrder than cancel address B’s. This order is strict and is to ensure Address B’s ShortOrder is reused before address A’s.
  3. Create another ShortOrder with address A of 3000 DUSD that doesn’t get matched. This short will reuse the id of the ShortRecord associated with its first ShortOrder but will reuse address B’s ShortOrder as its ShortOrder. This leaves address A’s former ShortOrder cancelled but still pointing to its ShortRecord.
  4. Create a Bid of 3000 - minAskEth/2 DUSD to match the ShortOrder and leave minAskEth/2 in the ShortOrder. This also lets the ShortOrder have a PartiallyFilled status to pass the check on line 91 above.
  5. Exit the ShortOrder with 3000 - minAskEth/2 DUSD as buybackAmount and the former id of address A’s cancelled ShortOrder. The buybackAmount is the amount of debt (DUSD) to pay back. So we’ll be paying everything back.
  6. After paying back we’ll have an empty ShortRecord and the ShortOrder will have an ercAmount of minAskEth/2.

If the minAskEth is small, we’ll end up creating small ShortOrders in the market. ShortOrders like this may make a transaction trying to fill a large order run out of gas and may disincentivize liquidators from liquidating them if they become liquidatable.

Impact

The issue above has the following effects:

  1. Large orders may run out of gas if a malicious user puts many orders with minAskEth/2 erc amounts on the market.
  2. Liquidators are disincentivized from liquidating them because of their small amounts.

Proof of Concept

The test below can be run in the Shorts.t.sol file. It shows how a malicious user can create a ShortOrder with a small amount.

Make sure to import the library below:

import {STypes, MTypes, O, SR} from "contracts/libraries/DataTypes.sol";

    function test_CreateTinySR() public {
        // create two short orders
        fundLimitShortOpt(0.5 ether, 2000 ether, receiver);
        fundLimitShortOpt(1 ether, 5000 ether, sender);

        vm.prank(sender);
        cancelShort(101); // cancel sender's short order so it won't be the first reused order

        vm.startPrank(receiver);
        cancelShort(100); // cancel receiver's short order so it will be the first reused order
        vm.stopPrank();

        // 1. Create a short add it to the market, the short reuses id 100 (receiver's former short).
        // 2. Create a bid and let it match the short leaving minAskEth/2 i.e. minAskEth*dustFactor.
        //    The dust factor is 0.5.
        uint minAskEth = diamond.getAssetNormalizedStruct(asset).minAskEth;
        uint88 debt = uint88(3000 ether - minAskEth/2);
        fundLimitShortOpt(1 ether, 3000 ether, sender);
        fundLimitBidOpt(1 ether, debt, receiver);

        // The sender's Short Record is reused and partially filled. It also has a new short Order.
        // The old cancelled short Order still references this ShortRecord.
        STypes.ShortRecord memory short = getShortRecord(sender, C.SHORT_STARTING_ID);
        assertTrue(short.status == SR.PartialFill);
        // The Short Record's new Short Order
        STypes.Order[] memory shortOrders = getShorts();
        assertEq(shortOrders.length, 1);
        assertEq(shortOrders[0].id, 100);
        assertEq(shortOrders[0].ercAmount, minAskEth/2); // order has minAsk/2

        // give sender the amount needed to exit
        deal(asset, sender, debt);
        vm.prank(sender);

        // exit with the old short order id which has > minShortErc
        diamond.exitShortWallet(asset,  C.SHORT_STARTING_ID, debt, 101);
        // short Order still exists
        shortOrders = getShorts();
        assertEq(shortOrders[0].id, 100);
        assertEq(shortOrders[0].ercAmount, minAskEth/2);
        // short Record has been closed and will only be filled up to minAskEth/2
        short = getShortRecord(sender, C.SHORT_STARTING_ID);
        assertEq(uint(short.status), uint(SR.Closed));
    }

Recommended Mitigation Steps

Consider checking if the ShortOrder being validated in checkShortMinErc() is cancelled.

LibSRUtil.sol#L84

-    if (shortOrder.shortRecordId != shortRecordId || shortOrder.addr != shorter) revert Errors.InvalidShortOrder();
+    if (shortOrder.shortRecordId != shortRecordId || shortOrder.addr != shorter || shortOrder.orderType == O.Cancelled) revert Errors.InvalidShortOrder();

Assessed type

DoS

ditto-eth (DittoETH) confirmed and commented:

I think the new check should be shortOrder.orderType != O.LimitShort, but otherwise great find.

hansfriese (judge) decreased severity to Medium and commented:

Medium is more appropriate as there is no direct fund loss.


The original report as published on Code4rena, by nonseodion. 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.

How it worked

Root cause

Likely the check in checkShortMinErc() does not verify that the ShortOrder used for validation is not cancelled, allowing a cancelled order that still points to the ShortRecord to be used.

Impact

Large orders may run out of gas if many tiny orders are placed, and liquidators may be disincentivized from liquidating them due to their small amounts.

What the attacker needed

Ability to create and cancel short orders; ability to create bids; ability to exit short records

The fix

The check in checkShortMinErc() should also verify that the ShortOrder is not cancelled, for example by checking its orderType.

How it was found

  1. Create two short orders with different addresses that do not get matched.
  2. Cancel the first address's short order, then cancel the second address's short order to control reuse order.
  3. Create a new short order with the first address that reuses the ShortRecord but uses the second address's cancelled ShortOrder.
  4. Create a bid that matches the new short order leaving minAskEth/2 in the ShortOrder and setting the ShortRecord to PartiallyFilled.
  5. Exit the ShortRecord using the cancelled ShortOrder ID and the full debt amount as buybackAmount.
  6. The ShortRecord becomes empty and the ShortOrder remains with ercAmount minAskEth/2.

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.

The report describes a way to create very small orders on a trading platform. By carefully cancelling and reusing order IDs, an attacker can leave a tiny order in the system that is hard to process and not worth liquidating.

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.

More by nonseodion

View all

8 more disclosed reports, best first.

More from DittoETH Invitational

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Denial of service

The lesson behind this report.

A request that exhausts resources or crashes a component. Many programs forbid testing it; reports usually show it from code, not by attacking.