Malicious user can control premium emissions to steal margin from other traders
The premium calculation in the perpetual market relies too heavily on the last traded price, allowing a malicious user to place orders that manipulate the time-weighted average price (TWAP) and generate premiums in their favour. This lets them steal margin from other traders who take the opposite side of their positions.
Source: https://github.com/sherlock-audit/2023-04-hubble-exchange-judging/issues/87
Found by
dirk_y
Summary
A malicious user can force premiums to be applied in a positive direction for their positions. They can effectively steal margin from other traders that have filled the other side of their positions.
Vulnerability Detail
This vulnerability stems from how the premiums are calculated when settleFunding is called in AMM.sol:
int256 premium = getMarkPriceTwap() - underlyingPrice;
Effectively, the premium for a position is calculated based on the difference between the perpetual maker TWAP and the oracle TWAP. Under the hood, getMarkPriceTwap calls _calcTwap, which calculates the TWAP price from the last hour to the current block timestamp:
uint256 currentPeriodStart = (_blockTimestamp() / spotPriceTwapInterval) * spotPriceTwapInterval;
uint256 lastPeriodStart = currentPeriodStart - spotPriceTwapInterval;
// If there is no trade in the last period, return the last trade price
if (markPriceTwapData.lastTimestamp <= lastPeriodStart) {
return markPriceTwapData.lastPrice;
}
/**
* check if there is any trade after currentPeriodStart
* since this function will not be called before the nextFundingTime,
* we can use the lastPeriodAccumulator to calculate the twap if there is a trade after currentPeriodStart
*/
if (markPriceTwapData.lastTimestamp >= currentPeriodStart) {
// use the lastPeriodAccumulator to calculate the twap
twap = markPriceTwapData.lastPeriodAccumulator / spotPriceTwapInterval;
} else {
// use the accumulator to calculate the twap
uint256 currentAccumulator = markPriceTwapData.accumulator + (currentPeriodStart - markPriceTwapData.lastTimestamp) * markPriceTwapData.lastPrice;
twap = currentAccumulator / spotPriceTwapInterval;
}
This method works closely in conjunction with _updateTWAP which is called every time a new position is opened based on the fill price. I'll talk more about his in the "Recommendation" section, but the core issue is that too much weight is placed on the last price that was filled, along with the fact the user can open uncapped positions. As can be seen from the _calcTwap method above, if there has not been a recently opened position, then the TWAP is determined as the last filled price. And naturally, a time weighted price isn't weighted by the size of a fill as well, so the size of the last fill has no impact.
As a result of this, a malicious user can place orders (which should then be executed by the validators) at a price that maximises the difference between the market TWAP and the oracle TWAP in order to maximise the premiums generated in the market. If the malicious user opens up a large enough position, the premiums generated exceed the taker/maker fees for opening positions. And since the same user can place orders for both sides of the market, they do not need to increase their margin requirement over time in order to meet the minimum margin requirements. Effectively the user is able to generate free revenue assuming the price of the underlying asset doesn't significantly deviate in the opposite direction of the large position held by the user.
Below is a diff to the existing test suite with a test case that shows how a malicious user could control premiums to make a profit. It can be run with forge test -vvv --match-path test/foundry/OrderBook.t.sol:
diff --git a/hubble-protocol/test/foundry/OrderBook.t.sol b/hubble-protocol/test/foundry/OrderBook.t.sol
index b4dafdf..f5d36b2 100644
--- a/hubble-protocol/test/foundry/OrderBook.t.sol
+++ b/hubble-protocol/test/foundry/OrderBook.t.sol
@@ -228,6 +228,60 @@ contract OrderBookTests is Utils {
assertPositions(bob, -size, quote, 0, quote * 1e18 / stdMath.abs(size));
}
+ function testUserCanControlEmissions() public {
+ uint256 price = 1e6;
+ oracle.setUnderlyingPrice(address(wavax), int(uint(price)));
+
+ // Calculate how much margin required for 100x MIN_SIZE
+ uint256 marginRequired = orderBook.getRequiredMargin(100 * MIN_SIZE, price) * 1e18 / uint(defaultWethPrice) + 1e10; // required weth margin in 1e18, add 1e10 for any precision loss
+
+ // Let's say Alice is our malicious user, and Bob is a normal user
+ addMargin(alice, marginRequired, 1, address(weth));
+ addMargin(bob, marginRequired, 1, address(weth));
+
+ // Alice places a large legitimate long order that is matched with a short order from Bob
+ placeAndExecuteOrder(0, aliceKey, bobKey, MIN_SIZE * 90, price, true, false, MIN_SIZE * 90, false);
+
+ // Alice's free margin is now pretty low
+ int256 availabeMargin = marginAccount.getAvailableMargin(alice);
+ assertApproxEqRel(availabeMargin, 200410, 0.1e18); // Assert within 10%
+
+ // Calculate what's the least we could fill an order for given the oracle price
+ uint256 spreadLimit = amm.maxOracleSpreadRatio();
+ uint minPrice = price * (1e6 - spreadLimit) / 1e6;
+
+ // Alice can fill both sides of an order at the minimum fill price calculated above, with the minimum size
+ // Alice would place such orders (and hopefully have them executed) just after anyone else makes an order in a period (1 hour)
+ // The goal for Alice is to keep the perpetual TWAP as low as possible vs the oracle TWAP (since she holds a large long position)
+ // In quiet market conditions Alice just has to make sure she's the last person to fill
+ // In busy market conditions Alice would fill an order immediately after anyone else fills an order
+ // In this test Alice fills an order every 2 periods, but in reality, if nobody was trading then Alice wouldn't have to do anything provided she was the last filler
+ for (uint i = 0; i < 100; i++) {
+ uint256 currentPeriodStart = (block.timestamp / 1 hours) * 1 hours;
+
+ // Warp to before the end of the period
+ vm.warp(currentPeriodStart + 3590);
+
+ // Place and execute both sides of an order as Alice
+ // Alice can do this because once both sides of the order are executed, the effect to her free margin is 0
+ // As mentioned above, Alice would place such orders every time after another order is executed
+ placeAndExecuteOrder(0, aliceKey, aliceKey, MIN_SIZE, minPrice, true, false, MIN_SIZE, false);
+
+ // Warp to the start of the next period
+ vm.warp(currentPeriodStart + (3600 * 2) + 10);
+
+ // Funding is settled. This calculates the premium emissions by comparing the perpetual twap with the oracle twap
+ orderBook.settleFunding();
+ }
+
+ // Alice's margin is now significantly higher (after just 200 hours) because she's been pushing the premiums in her direction
+ availabeMargin = marginAccount.getAvailableMargin(alice);
+ assertApproxEqRel(availabeMargin, 716442910, 0.1e18); // Assert within 10%
+
+ }
+
function testLiquidateAndExecuteOrder(uint64 price, uint120 size_) public {
vm.assume(price > 10 && size_ != 0);
oracle.setUnderlyingPrice(address(wavax), int(uint(price)));
Impact
A user can effectively steal funds from other traders that are filling the other side of their positions. The larger the position the malicious user is able to fill and the longer the period, the more funds can be credited to the malicious user's margin account.
Code Snippet
https://github.com/sherlock-audit/2023-04-hubble-exchange/blob/main/hubble-protocol/contracts/AMM.sol#L255-L258 https://github.com/sherlock-audit/2023-04-hubble-exchange/blob/main/hubble-protocol/contracts/AMM.sol#L501-L503
Tool used
Manual Review
Recommendation
I originally thought the best way to mitigate this kind of attack is to scale the TWAP calculation based on the filled amount vs the total fill amount of the whole market. However the downside with this approach is that the fill amount will perpetually increase (given it's a perpetual market after all!) and so the market TWAP deviations from the oracle TWAP would decrease and so the premium emissions would also decrease over time. This could be argued as a feature in that early users receive a larger premium than later users.
Upon further thought I think the best way to prevent this kind of attack is simply to disincentivise the malicious user from doing so; by making this a net-loss situation. This can be done with a combination of the following:
- Increasing minimum order size
- Increasing trader/maker fees
- Introducing another fixed fee per order (rather than only variable rate fees)
- Capping the maximum position size (both long and short)
- Reducing the maximum price deviation of fill prices from oracle price
- Increasing the minimum margin requirements
This will vary per perpetual market, but the key thing that needs to be accomplished is that the cost to a user to place orders to control the market TWAP is greater than the premium that can be obtained from their position. This will also require some estimates as to how frequently users are going to be placing orders. If orders are relatively infrequent then increasing the TWAP calculation from 1 hour will also help with this.
It is also worth considering whether the following lines in _calcTwap are overly weighted towards the last fill price:
// If there is no trade in the last period, return the last trade price
if (markPriceTwapData.lastTimestamp <= lastPeriodStart) {
return markPriceTwapData.lastPrice;
}
You could make the argument that if no trades have occurred in a significant period of time then the market TWAP should revert back to the oracle TWAP and premium emissions should halt. This could either be after one empty period, or X number of empty periods to be defined by Hubble.
Finally, having a trader able to hold both sides of the same perpetual in the same order makes this attack easier to implement, so it might be worth adding an extra check to prevent this. However it's worth noting the same could be achieved with 2 accounts assuming they alternated the long/short positions between them to avoid excessive margin requirements. So I'm not sure this is strictly necessary.
Discussion
asquare08
This is a scenario of low liquidity where no trade has happened in the last 1 hour and if happened, a malicious user has made a trade just after that to move the price up/down. Many other systems might also fail in such a scenario.
Also, only validators can match the placed orders and the malicious user will not always get their desired price unless the validator picks their short and long orders. Hence we can change the severity to medium
ctf-sec
Changed the severity to medium
MarkuSchick
Escalate
The market manipulation the user is referring to is a dublicate of the funding rate manipulation raised in https://github.com/sherlock-audit/2023-04-hubble-exchange-judging/issues/183:
2. Manipulation of funding rate.
According to other comments funding rate manipulation is a low severity issue.
sherlock-admin2
Escalate
The market manipulation the user is referring to is a dublicate of the funding rate manipulation raised in https://github.com/sherlock-audit/2023-04-hubble-exchange-judging/issues/183:
2. Manipulation of funding rate.According to other comments funding rate manipulation is a low severity issue.
You've created a valid escalation!
To remove the escalation from consideration: Delete your comment.
You may delete or edit your escalation comment anytime before the 48-hour escalation window closes. After that, the escalation becomes final.
djb15
In my (biased) opinion I think the medium (not low) severity argument for the other issue is that you would need multiple validators to be malicious which is highly unlikely (in a normal market environment).
In this issue any user can open orders to manipulate the funding rate, but this is only possible in low liquidity scenarios which is why it is a medium severity issue.
A single malicious validator would be able to do the same thing as is detailed in this report in low liquidity market environments, which would make these two issues identical. Hence why I think both should be medium severity.
asquare08
As mentioned in the comment here, its a valid medium issue. Also refer to this comment
hrishibhat
Result: Medium Unique Considering this a valid medium issue
sherlock-admin2
Escalations have been resolved successfully!
Escalation status:
- MarkuSchick: rejected
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 TWAP calculation gives excessive weight to the last traded price and does not account for trade size, allowing manipulation through small trades.
Impact
A user could steal funds from other traders, with the amount increasing with position size and duration, but only in low-liquidity scenarios where the attacker is the last to trade in a period.
What the attacker needed
Low liquidity market; attacker can place orders on both sides; attacker is last to trade in a period
The fix
The report recommends disincentivising the attack by making it a net loss through measures such as increasing minimum order size, fees, capping position size, reducing maximum price deviation, and increasing margin requirements.
How it was found
- Alice opens a large long position, matched with Bob's short, leaving her with low free margin.
- Alice places and executes both sides of a small order at the minimum allowed price just before the end of each funding period.
- Funding is settled, and the premium is calculated using the manipulated TWAP, crediting Alice's margin account.
- Alice repeats this over multiple periods, significantly increasing her margin.
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 perpetual market, traders pay or receive a premium based on the difference between the market price and an oracle price. The market price is calculated as a time-weighted average (TWAP) of recent trades. If the TWAP is too influenced by the last trade, a trader can make small trades to push the TWAP in their favour and earn premiums at the expense of other traders.
What is Business logic?
The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.