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:
- Call
initiateLimitOrder()and create limit order with id equal to ID1 reenter (while_limitOrdersfor ID1 is not yet settled) withcancelLimitOrder(ID1)(nocheckDelay()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 thePosition.burn()code. - Call
initiateMarketOrder()and create a position with ID1 and whileinitId[ID1]has not yet settled reenter the Trading withaddToPosition(ID1)function (bypasscheckDelay()because both action is opening) and increase the position size which would setinitId[ID1]according to new position values but then when code execution returns to rest ofmint()logicinitId[ID1]would set by initial values of the positions which is very lower than what it should be andinitId[ID1]has been used for calculatingaccuredInterestof 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
- Attacker contract would call
initiateLimitOrder()and code would create the limit order and mint it in thePosition._safeMint()with ID1. - Then code would call attacker address in
_safeMint()function because of theonERC721Received()call check. - Variables
_limitOrders[],_limitOrderIndexes[ID1]are not yet updated for ID1 and_limitOrderIndexes[ID1]is 0x0 and ID1 is not in_limitOrder[]list. - Attacker contract would reenter the Trading contract by calling
cancelLimitOrder(ID1). cancelLimitOrder()checks would pass and would try to callPosition.burn(ID1).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.- 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
- Attacker’s contract would call
initiateMarketOrder(lowMargin)to create position with ID1 while the margin is low. - Code would mint position token for attacker and in
_safeMint()would make external call and callonERC721Received()function of attacker address. - The value of
initId[ID1]is not yet set for ID1. - 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. - Code would increase the margin of the position and set the value of the
initId[ID1]by callingposition.addToPosition()and the value would be based on thenewMargin. - The execution flow would receive the rest of
Position.mint()function and code would setinitId[ID1]based on old margin value. - Then the value of
initId[ID1]for attacker position would be very low, which would causeaccInterestto be higher than it’s supposed to be for position(inPosition.trades()function calculations ) and would cause_payoutvalue to be very high (inpnl()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
mintdoesn’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
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
- The attacker contract calls initiateLimitOrder(), which mints a position token with ID1 and triggers the onERC721Received() callback.
- During the callback, the limit order index for ID1 is still zero and ID1 is not yet in the limit orders list.
- The attacker reenters by calling cancelLimitOrder(ID1), which passes its checks and calls Position.burn(ID1).
- burn() removes the limit order at index zero, which belongs to another user, because the index for ID1 is still zero.
- 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.