Submitted by Bobface
An overflow in TradingLibrary.pnl() enables all funds from the vault contracts to be drained given a certain fee configuration is present.
When opening a position, any value can be passed as take-profit price. This value is later used in the PNL calculation in an unchecked block. Setting this value specifically to attack the vault leads to the Trading contract minting a huge (in the example below 10^36) Tigris tokens, which can then be given to the vault to withdraw assets.
The exploiter starts by setting himself as referrer, in order to later receive the referrer fees.
The next step is to open a short position at the current market price by calling initiateLimitOrder(). Here, the malicious value which will later bring the arithmetic to overflow is passed in as take-profit price. For the example below, the value has been calculated by hand to be 115792089237316195423570985008687907854269984665640564039467 for this specific market price, leverage and margin.
The order is then immediately executed through executeLimitOrder().
The final step is to close the order through limitClose(), which will then mint over 10^36 Tigris tokens to the attacker.
The bug takes place in TradingLibrary.pnl(), line 46. The function is called during the process of closing the order to calculate the payout and position size. The malicious take-profit is passed as _currentPrice and the orders original opening price is passed as _price. The take-profit has been specifically calculated so that 1e18 * _currentPrice / _price - 1e18 results in 0, meaning _payout = _margin (accInterest is negligible for this PoC).
Line 48 then calculates the position size. Margin and leverage have been chosen so that _initPositionSize * _currentPrice does not overflow, resulting in a huge _positionSize which is returned from the function.
Later, Trading._handleCloseFees() is called, under the condition that _payout > 0, which is why the overflow had to be calculated so precisely, as to not subtract from the _payout but still create a large _positionSize. _positionSize is passed in to this function, and it is used to calculate DAO and referral fees. Line 805 is what requires the specific fee configuration to be present, as otherwise this line would revert. The fees have to be daoFees = 2*referralFees  not exactly, but close to this relationship. Then line 792 will set the DAO fees close to zero, while the huge referralFees are directly minted and not included in the calculation in line 805.
The core issue is that the arithmetic in TradingLibrary.pnl() overflows. I recommend removing the unchecked block.
Insert the following code as test into test/07.Trading.js and run it with npx hardhat test test/07.Trading.js:
TriHaz (Tigris Trade) confirmed
Alex the Entreprenerd (judge) commented:
GainsGoblin (Tigris Trade) resolved:
