Position closure might always revert in some cases due to allocatedBalances being unsigned, preventing the user from closing its positions
Allocated balances are stored as unsigned integers, so when a position's unrealised loss would make the allocated balance negative, closing that position reverts. This can prevent users from closing positions, locking their funds in the protocol.
Source: https://github.com/sherlock-audit/2023-08-symmetrical-judging/issues/10
Found by
panprog
This is issue 193 from the previous audit contest. The liquidation part was fixed, but the main reason described here is still the same.
Allocated balances are stored as unsigned ints.
Total account value is calculated as allocated balance + unrealized pnl, for example for liquidation purposes it's calculated as:
In the other cases formula is similar. This means that in case of high unrealized profit, allocated balance might be valid to be negative. For example, a simple case is if account has opened position with unrealized profit of 1000 and locked balance of 100, allocated balance can theoretically be -900 with account being safe from liquidation: -900 + 1000 = 100 >= lockedBalance(100). But since balance is unsigned, transaction to deallocate such balance will revert. This might be expected behaviour.
However, there are more complex cases possible where unsigned allocated balance can unexpectedly revert different transactions and block users from doing important actions. For example, if user has 2 opposite positions opened of the same quantity (LONG and SHORT) and price has moved significantly, total user upnl = 0 (because opposite positions hedge each other completely). But the user will be unable to close either of these positions, because closing any position will subract high loss from the position from either partyA or partyB, which will make allocated balance negative and revert the transaction:
Before closing position:
Account Balance = Position 1 UPNL (+1000) + Position 2 UPNL (-1000) + Allocated Balance (100) = +100 (account solvent)
After closing position:
Account Balance should be = Position 1 UPNL (+1000) + Allocated Balance (-900) = +100 (account solvent), but it will revert.
As such, both partyA and partyB will lose funds deposited into the protocol to keep these positions alive. It will also be impossible to finish liquidation of such positions if any account becomes liquidatable, effectively locking the funds for extended time (until price is in the range where positions can be closed without big loss).
Vulnerability Detail
The scenario when user unexpectedly can't close position and loses funds:
- Open 2 large opposite positions between partyA and partyB such that one of them is in a high loss and the other in the same profit. Use minimal allocated balance both for partyA and partyB (because such opposite positions can't be liquidated by themselves as they perfectly hedge each other).
- When price moves significantly, try to close either of these positions, both will revert.
- Both partyA and partyB are stuck with the funds in the protocol which they can't take out until price goes back close to initial value.
There might be the other cases with unexpected reverts and users being unable to close their positions.
Impact
PartyA and PartyB funds can be unexpectedly locked in the protocol for extended time. PartyA or PartyB can allocate additional funds to be able to close positions, then deallocate and withdraw, however depending on situation, required funds to close such position might be orders of magnitude higher than what parties have or are willing to risk (due to leverage).
This is High severity, because the situation can happen by itself for users having multiple positions: naturally some of them will be in profit, some in loss, and total upnl can be much smaller than individual positions, allowing a low allocated balance and making it impossible to close some positions.
Code Snippet
Add this to any test, for example to ClosePosition.behavior.ts.
it("Unable to close positions due to unsigned allocatedBalances", async function () {
const context: RunContext = this.context;
this.user_allocated = decimal(82);
this.hedger_allocated = decimal(80);
this.user = new User(this.context, this.context.signers.user);
await this.user.setup();
await this.user.setBalances(this.user_allocated, this.user_allocated, this.user_allocated);
this.hedger = new Hedger(this.context, this.context.signers.hedger);
await this.hedger.setup();
await this.hedger.setBalances(this.hedger_allocated, this.hedger_allocated);
// open 2 opposite direction positions
await this.user.sendQuote(limitQuoteRequestBuilder()
.quantity(decimal(100))
.price(decimal(1))
.cva(decimal(10)).lf(decimal(5)).mm(decimal(15))
.build()
);
await this.hedger.lockQuote(1, 0, decimal(4, 17));
await this.hedger.openPosition(1, limitOpenRequestBuilder().filledAmount(decimal(100)).openPrice(decimal(1)).price(decimal(1)).build());
await this.user.sendQuote(limitQuoteRequestBuilder()
.positionType(PositionType.SHORT)
.quantity(decimal(100))
.price(decimal(1))
.cva(decimal(10)).lf(decimal(5)).mm(decimal(15))
.build()
);
await this.hedger.lockQuote(2, 0, decimal(4, 17));
await this.hedger.openPosition(2, limitOpenRequestBuilder().filledAmount(decimal(100)).openPrice(decimal(1)).price(decimal(1)).build());
var info = await this.user.getBalanceInfo();
console.log("partyA allocated: " + info.allocatedBalances / 1e18 + " locked: " + info.totalLocked/1e18 + " pendingLocked: " + info.totalPendingLocked / 1e18);
var info = await this.hedger.getBalanceInfo(this.user.getAddress());
console.log("partyB allocated: " + info.allocatedBalances / 1e18 + " locked: " + info.totalLocked/1e18 + " pendingLocked: " + info.totalPendingLocked / 1e18);
// now the price doubles, with upnl still 0
// try to close LONG position
await this.user.requestToClosePosition(
1,
limitCloseRequestBuilder().quantityToClose(decimal(100)).closePrice(decimal(2)).build(),
);
await expect(this.hedger.fillCloseRequest(
1,
limitFillCloseRequestBuilder()
.filledAmount(decimal(100))
.closedPrice(decimal(2))
.build(),
)).to.be.revertedWith("LibSolvency: PartyB will be liquidatable");
console.log("Attempt to close LONG position failed due to partyB being liquidatable");
// try to close SHORT position
await expect(this.user.requestToClosePosition(
2,
limitCloseRequestBuilder().quantityToClose(decimal(100)).closePrice(decimal(2)).build(),
)).to.be.revertedWith("LibSolvency: partyA will be liquidatable");
console.log("Attempt to close SHORT position failed due to partyA being liquidatable");
});
Tool used
Manual Review
Recommendation
Make allocated balances signed ints and change all appropriate parts where allocated balances are changed or verified. This will be more user-friendly (less limiting) and will prevent situations described in this bug report.
Discussion
nevillehuang
@MoonKnightDev, seems possible due to possibility of UPNL being negative causing allocated balance to fall below 0 and reverting since it is an uint. Could you shed some light on why this is disputed?
MoonKnightDev
@MoonKnightDev, seems possible due to possibility of UPNL being negative causing allocated balance to fall below 0 and reverting since it is an uint. Could you shed some light on why this is disputed?
One of the recognized challenges with cross positions relates to the scenario described above. To navigate this predicament:
If PartyA wishes to close the winning position, PartyB must allocate funds to fulfill the close request. Should PartyB act maliciously, PartyA should first allocate funds to close the losing position and then proceed to close the winning one.
panprog
Escalate
I believe this should be valid, because it causes all kinds of nasty underflows, the example I provided is just one scenario. Another scenario is partyA having allocated balance = 0 and positions in loss and profit with different partyBs, and then if partyB tries to call emergencyClosePosition, it will revert due to underflow (partyA position is in loss, but partyA allocated balance = 0, so the loss can not be applied).
One of the recognized challenges with cross positions relates to the scenario described above. To navigate this predicament:
If PartyA wishes to close the winning position, PartyB must allocate funds to fulfill the close request. Should PartyB act maliciously, PartyA should first allocate funds to close the losing position and then proceed to close the winning one.
While it's possible to allocate and then close for partyA, this is still unexpected behavior for partyA: if it has position 1 in profit and position 2 in a loss, and it only wants to close position 1 (to realize profit), partyA will be unable to do so - all transactions will revert due to partyB allocatedBalance underflow when trying to apply position loss. So partyA must close position 2, then position 1.
Another point to consider is that partyA might simply have not enough funds to allocate, close position 2, close position 1. For example, partyA opens huge long and short positions of similar size when ETH = 1000, with leverage = 10: Position 1: long 100 ETH (entry price = 1000) (cva+lf+mm=10000) Position 2: short 99 ETH (entry price = 1000) (cva+lf+mm=10000) Now ETH price shoots up to 2000. Both PartyA and PartyB still have 20000 collateral (which is enough to not be liquidated, because partyB total upnl is just 1000). partyA wants to close Position 1. Since it requires to reduce partyB allocatedBalance by 100 * (2000-1000) = 100000, it reverts.
Now if partyA wants to close Position 1, it first has to close Position 2, but in order to close it, partyA must have allocated balance of 99 * (2000 - 1000) = 99000. But partyA only has 20000, it doesn't have access to such huge amount. So it's still stuck.
sherlock-admin2
Escalate
I believe this should be valid, because it causes all kinds of nasty underflows, the example I provided is just one scenario. Another scenario is partyA having allocated balance = 0 and positions in loss and profit with different partyBs, and then if partyB tries to call
emergencyClosePosition, it will revert due to underflow (partyA position is in loss, but partyA allocated balance = 0, so the loss can not be applied).One of the recognized challenges with cross positions relates to the scenario described above. To navigate this predicament:
If PartyA wishes to close the winning position, PartyB must allocate funds to fulfill the close request. Should PartyB act maliciously, PartyA should first allocate funds to close the losing position and then proceed to close the winning one.
While it's possible to allocate and then close for partyA, this is still unexpected behavior for partyA: if it has position 1 in profit and position 2 in a loss, and it only wants to close position 1 (to realize profit), partyA will be unable to do so - all transactions will revert due to partyB allocatedBalance underflow when trying to apply position loss. So partyA must close position 2, then position 1.
Another point to consider is that partyA might simply have not enough funds to allocate, close position 2, close position 1. For example, partyA opens huge long and short positions of similar size when ETH = 1000, with leverage = 10: Position 1: long 100 ETH (entry price = 1000) (cva+lf+mm=10000) Position 2: short 99 ETH (entry price = 1000) (cva+lf+mm=10000) Now ETH price shoots up to 2000. Both PartyA and PartyB still have 20000 collateral (which is enough to not be liquidated, because partyB total upnl is just 1000). partyA wants to close Position 1. Since it requires to reduce partyB allocatedBalance by 100 * (2000-1000) = 100000, it reverts.
Now if partyA wants to close Position 1, it first has to close Position 2, but in order to close it, partyA must have allocated balance of 99 * (2000 - 1000) = 99000. But partyA only has 20000, it doesn't have access to such huge amount. So it's still stuck.
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.
nevillehuang
Escalate
I believe this should be valid, because it causes all kinds of nasty underflows, the example I provided is just one scenario. Another scenario is partyA having allocated balance = 0 and positions in loss and profit with different partyBs, and then if partyB tries to call
emergencyClosePosition, it will revert due to underflow (partyA position is in loss, but partyA allocated balance = 0, so the loss can not be applied).One of the recognized challenges with cross positions relates to the scenario described above. To navigate this predicament: If PartyA wishes to close the winning position, PartyB must allocate funds to fulfill the close request. Should PartyB act maliciously, PartyA should first allocate funds to close the losing position and then proceed to close the winning one.
While it's possible to allocate and then close for partyA, this is still unexpected behavior for partyA: if it has position 1 in profit and position 2 in a loss, and it only wants to close position 1 (to realize profit), partyA will be unable to do so - all transactions will revert due to partyB allocatedBalance underflow when trying to apply position loss. So partyA must close position 2, then position 1.
Another point to consider is that partyA might simply have not enough funds to allocate, close position 2, close position 1. For example, partyA opens huge long and short positions of similar size when ETH = 1000, with leverage = 10: Position 1: long 100 ETH (entry price = 1000) (cva+lf+mm=10000) Position 2: short 99 ETH (entry price = 1000) (cva+lf+mm=10000) Now ETH price shoots up to 2000. Both PartyA and PartyB still have 20000 collateral (which is enough to not be liquidated, because partyB total upnl is just 1000). partyA wants to close Position 1. Since it requires to reduce partyB allocatedBalance by 100 * (2000-1000) = 100000, it reverts.
Now if partyA wants to close Position 1, it first has to close Position 2, but in order to close it, partyA must have allocated balance of 99 * (2000 - 1000) = 99000. But partyA only has 20000, it doesn't have access to such huge amount. So it's still stuck.
This does seem valid unless it is expected behavior for cross positions, any thoughts @MoonKnightDev ?
Navid-Fkh
We recognize that this is a limitation in our system.
What are we doing about it?
At the moment, nothing. PartyB will remain trusted for this version of contracts. As a result, PartyB will ensure that adequate funds are allocated before executing fillClosingPosition. Moreover, users might need to close another position (like the one in a loss, as per your example) before they can close a profitable one.
Why don't we allow allocatedBalance to go negative?
In the initial stages of designing the system, we chose to make the allocatedBalance unsigned to prevent further potential security threats. For instance, if "muon" were to be compromised, a user would only be able to deallocate up to their allocated amount now. However, if we allowed the allocatedBalance to go negative with a positive UPNL, this could lead to a much more significant challenge. We understand that there are some attack vectors with a compromised version of muon even now, but these are now far more complex, enabling our anomaly detection bots to identify and halt malicious activity more effectively.
Will the system always operate like this, even in subsequent versions?
No. Future versions will introduce mechanisms that allow users to convert their unrealized profits into realized ones, providing a more effective solution for such scenarios.
nevillehuang
We recognize that this is a limitation in our system.
What are we doing about it? At the moment, nothing. PartyB will remain trusted for this version of contracts. As a result, PartyB will ensure that adequate funds are allocated before executing fillClosingPosition. Moreover, users might need to close another position (like the one in a loss, as per your example) before they can close a profitable one.
Why don't we allow allocatedBalance to go negative? In the initial stages of designing the system, we chose to make the allocatedBalance unsigned to prevent further potential security threats. For instance, if "muon" were to be compromised, a user would only be able to deallocate up to their allocated amount now. However, if we allowed the allocatedBalance to go negative with a positive UPNL, this could lead to a much more significant challenge. We understand that there are some attack vectors with a compromised version of muon even now, but these are now far more complex, enabling our anomaly detection bots to identify and halt malicious activity more effectively.
Will the system always operate like this, even in subsequent versions? No. Future versions will introduce mechanisms that allow users to convert their unrealized profits into realized ones, providing a more effective solution for such scenarios.
Very valid design decisions and concerns. I am now leaning towards Medium severity as I believe this is still a risk that users should be made known of before interacting with the protocol, that is the potential inability to close profiting positions without first closing losing ones.
panprog
What are we doing about it? At the moment, nothing. PartyB will remain trusted for this version of contracts. As a result, PartyB will ensure that adequate funds are allocated before executing fillClosingPosition. Moreover, users might need to close another position (like the one in a loss, as per your example) before they can close a profitable one.
There is still a scenario I've outlined in the escalation comment: emergencyClosePosition might always revert for partyB, because partyA might have multiple positions both in profit and in loss with different partyBs so that it doesn't have enough allocated balance to close that position. In this case partyB can't do anything about it and partyA doesn't have any incentive to allocate additional funds to let partyB do emergency close.
I understand sponsor's point and intentions, but it's nonetheless a problem which can pop up in different scenarios unexpectedly, and not all of them might be fixable by actions such as depositing additional funds or closing the other positions first. And making it possible to realize unrealized pnl might also not fix all the problems, like the emergency close (maybe something else too).
In the contest context, I still think this is a valid issue as it's a real problem, which was perhaps overlooked in the previous contest as it was a duplicate to very similar problem which only listed liquidation as impact, but the problem is more general than just liquidations.
As for the impact, I leave it up to sherlock to decide. I think it's high as the situation is quite easy to get into during normal trading flow (I've seen a lot of users opening opposite direction positions to "hedge", there might be trading strategies like statistical arbitrage - going long one asset and short another similar asset etc) and very unexpected for the users (and not always easily fixable). Also, it was a valid high in previous contest and is not fixed but marked "will fix".
hrishibhat
Result: Medium Unique Based on the points raised in the escalation the underlying issue still persists as a limitation and given the possible cases where the underflow can cause problems as mentioned above. Also, I agree with the Lead judge's points. Considering this issue a valid medium
sherlock-admin2
Escalations have been resolved successfully!
Escalation status:
- panprog: accepted
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 allocated balance is stored as an unsigned integer, so any calculation that would make it negative causes an underflow and reverts.
Impact
PartyA and PartyB funds can be unexpectedly locked in the protocol for an extended time, and in some cases even emergency close may revert, leaving funds stuck until the price returns to a range where positions can be closed without a large loss.
What the attacker needed
A trading account with allocated balance; two opposite positions of similar size; significant price movement
The fix
The issue was not fixed; the team acknowledged it as a limitation and stated that future versions will introduce mechanisms to convert unrealised profits into realised ones.
How it was found
- Open two opposite positions (one long, one short) of similar size with minimal allocated balance.
- When the price moves significantly, attempt to close either position.
- Both close attempts revert because the loss from one position would make the allocated balance negative.
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 this trading protocol, each user has an 'allocated balance' (the funds they have deposited) stored as a number that cannot be negative. When a user closes a position, the profit or loss is added to or subtracted from that balance. If a position has a large loss, subtracting it would make the balance negative, which the system cannot represent, so the transaction fails and the position cannot be closed.
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.