Skip to content
Smart contracts Audit finding Advanced

reentrancy attack during mint() function in Position contract which can lead to removing of the other user’s limit orders or stealing contract funds because initId is set low value

The Position.mint() function updates storage after calling _safeMint(), which invokes the recipient's onERC721Received() callback. An attacker can reenter the Trading contract during that callback to cancel a limit order whose index is still zero, removing another user's order, or to add margin to a position so that initId is later overwritten with a lower value, inflating profit calculations.

unforgiven Follow with wait, rotcivegaf and 6 others

Originally disclosed on Code4rena

Submitted by unforgiven, also found by wait, rotcivegaf, 0xsomeone, hihen, KingNFT, mookimgo, debo, and stealthyz

Function Position.mint() has been used in initiateLimitOrder() and initiateMarketOrder() and it doesn’t follow check-effect-interaction pattern and code updates the values of _limitOrders, initId, _openPositions and position _tokenIds variables after making external call by using safeMint(). This would give the attacker opportunity to reenter the Trading contract logics and perform malicious actions while the contract storage state is wrong. The only limitation of the attacker is that he needs to bypass _checkDelay() checks. Attacker can perform this action:

  1. Call initiateLimitOrder() and create limit order with id equal to ID1 reenter (while _limitOrders for ID1 is not yet settled) with cancelLimitOrder(ID1) (no checkDelay() check) and remove other users limit orders because code would try to remove _limitOrderIndexes[_asset][ID1] position but the value is 0 and code would remove limit order in the index 0 which belongs to another user in the Position.burn() code.
  2. Call initiateMarketOrder() and create a position with ID1 and while initId[ID1] has not yet settled reenter the Trading with addToPosition(ID1) function (bypass checkDelay() because both action is opening) and increase the position size which would set initId[ID1] according to new position values but then when code execution returns to rest of mint() logic initId[ID1] would set by initial values of the positions which is very lower than what it should be and initId[ID1] has been used for calculating accuredInterest of the position which is calculated for profit and loss of position and contract would calculate more profit for position and would pay attacker more profit from contract balances.

Proof of Concept

This is mint() code in Position contract:

    function mint(
        MintTrade memory _mintTrade
    ) external onlyMinter {
        uint newTokenID = _tokenIds.current();

        Trade storage newTrade = _trades[newTokenID];
        newTrade.margin = _mintTrade.margin;
        newTrade.leverage = _mintTrade.leverage;
        newTrade.asset = _mintTrade.asset;
        newTrade.direction = _mintTrade.direction;
        newTrade.price = _mintTrade.price;
        newTrade.tpPrice = _mintTrade.tp;
        newTrade.slPrice = _mintTrade.sl;
        newTrade.orderType = _mintTrade.orderType;
        newTrade.id = newTokenID;
        newTrade.tigAsset = _mintTrade.tigAsset;

        _safeMint(_mintTrade.account, newTokenID);   // make external call because of safeMint() usage
        if (_mintTrade.orderType > 0) { // update the values of some storage functions
            _limitOrders[_mintTrade.asset].push(newTokenID);
            _limitOrderIndexes[_mintTrade.asset][newTokenID] = _limitOrders[_mintTrade.asset].length-1;
        } else {
            initId[newTokenID] = accInterestPerOi[_mintTrade.asset][_mintTrade.tigAsset][_mintTrade.direction]*int256(_mintTrade.margin*_mintTrade.leverage/1e18)/1e18;
            _openPositions.push(newTokenID);
            _openPositionsIndexes[newTokenID] = _openPositions.length-1;

            _assetOpenPositions[_mintTrade.asset].push(newTokenID);
            _assetOpenPositionsIndexes[_mintTrade.asset][newTokenID] = _assetOpenPositions[_mintTrade.asset].length-1;
        }
        _tokenIds.increment();
    }

As you can see by calling _safeMint(), code would make external call to onERC721Received() function of the account address and the code sets the values for _limitOrders[], _limitOrderIndexes[], initId[], _openPositions[], _openPositionsIndexes[], _assetOpenPositions[], _assetOpenPositionsIndexes[] and _tokenIds. So code doesn’t follow check-effect-interaction pattern and it’s possible to perform reentrancy attack.

There could be multiple scenarios that the attacker can perform the attack and do some damage. Two of them are:

Scenario #1 where attacker removes other users limit orders and create broken storage state

  1. Attacker contract would call initiateLimitOrder() and code would create the limit order and mint it in the Position._safeMint() with ID1.
  2. Then code would call attacker address in _safeMint() function because of the onERC721Received() call check.
  3. Variables _limitOrders[], _limitOrderIndexes[ID1] are not yet updated for ID1 and _limitOrderIndexes[ID1] is 0x0 and ID1 is not in _limitOrder[] list.
  4. Attacker contract would reenter the Trading contract by calling cancelLimitOrder(ID1).
  5. cancelLimitOrder() checks would pass and would try to call Position.burn(ID1).
  6. burn() function would try to remove ID1 from _limitOrders[] list but because _limitOrderIndexes[ID1] is 0, the code would remove the 0 index limit order which belongs to another user.
  7. Execution would return to Position.mint() logic and code would add burned id token to _limitOrder[] list.

So there are two impacts here. First, other users limit orders get removed. The second is that contract storage had a bad state and burned tokens get stock in the list.

Scenario #2 where attacker steal contract/users funds by wrong profit calculation

  1. Attacker’s contract would call initiateMarketOrder(lowMargin) to create position with ID1 while the margin is low.
  2. Code would mint position token for attacker and in _safeMint() would make external call and call onERC721Received() function of attacker address.
  3. The value of initId[ID1] is not yet set for ID1.
  4. Attacker contract would call addToPosition(ID1, bigMargin) to increase the margin of the position the _checkDelay() check would pass because both actions are opening position.
  5. Code would increase the margin of the position and set the value of the initId[ID1] by calling position.addToPosition() and the value would be based on the newMargin.
  6. The execution flow would receive the rest of Position.mint() function and code would set initId[ID1] based on old margin value.
  7. Then the value of initId[ID1] for attacker position would be very low, which would cause accInterest to be higher than it’s supposed to be for position(in Position.trades() function calculations ) and would cause _payout value to be very high (in pnl() function’s calculations) and when attacker close position ID1 attacker would receive a lot more profit from it.

So attacker created a position with a lot of profit by reentering the logics and manipulating calculation of the profits for the position.

There can be other scenarios possible to perform and damage the protocol or users because there is no reentrancy protection mechanism and attacker only need to bypass validity checks of functions.

Tools Used

VIM

Recommended Mitigation Steps

Follow the check-effect-interaction pattern.

TriHaz (Tigris Trade) confirmed

Alex the Entreprenerd (judge) commented:

In contrast to other CEI reports, this report shows how control can be gained in the middle of the mint execution to create an inconsistent state.

The warden has shown how, because mint doesn’t follow CEI conventions, by reEntering via safeMint, an attacker can manipulate the state of limit orders, and also benefit by changing profit calculations.

Because the finding shows how to break invariants and profit from it, I agree with High Severity.

GainsGoblin (Tigris Trade) resolved:

Mitigation: https://github.com/code-423n4/2022-12-tigris/pull/2#issuecomment-1419175911


The original report as published on Code4rena, by unforgiven. 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 mint() function performs the external _safeMint() call before updating its own storage, so it does not follow the check-effect-interaction pattern and leaves inconsistent state during the callback.

Impact

An attacker could remove other users' limit orders and leave burned tokens stuck in the list, or could make their own position's initId much lower than it should be so that profit calculations pay them more from contract balances.

What the attacker needed

Attacker deploys a contract that receives NFTs; attacker can call initiateLimitOrder or initiateMarketOrder; reentrant call must pass the function's checks

The fix

The mint() function should follow the check-effect-interaction pattern, updating all storage before making the external _safeMint() call.

How it was found

  1. The attacker contract calls initiateLimitOrder(), which mints a position token with ID1 and triggers the onERC721Received() callback.
  2. During the callback, the limit order index for ID1 is still zero and ID1 is not yet in the limit orders list.
  3. The attacker reenters by calling cancelLimitOrder(ID1), which passes its checks and calls Position.burn(ID1).
  4. burn() removes the limit order at index zero, which belongs to another user, because the index for ID1 is still zero.
  5. Execution returns to mint(), which then adds the already burned token ID to the limit orders list, leaving broken storage state.

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.

When a contract sends an NFT to a smart contract, it calls a function on the receiving contract to let it know. If the sending contract updates its records only after that call, the receiver can call back into the sender while its records are still incomplete. Here that gap let an attacker cancel someone else's order or make their own position look more profitable than it was.

What is Smart contracts?

Flaws in on-chain code that let an attacker drain funds, freeze them or break the protocol's accounting.

More by unforgiven

View all

50 more disclosed reports, best first.

More from Tigris Trade contest

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Smart contract vulnerabilities

The lesson behind this report.

Flaws in on-chain code that let an attacker drain funds, freeze them or break the protocol's accounting.