A huge loss of funds for all the users who try to remove liquidity after swapping got disabled at manipulated price.
The report describes an edge case where an asset's tradability state is set to allow only adding and removing liquidity while its price is manipulated, so the price check is skipped and the withdrawal fee becomes 100%, causing liquidity providers to lose all their funds when removing liquidity. The attacker could front-run the setting of this state to exploit the manipulated price.
castle_chain Follow with QiuhaoLi, oakcobalt and 1 other
Originally disclosed on Code4rena
Submitted by castle_chain, also found by QiuhaoLi, oakcobalt, and J4X
https://github.com/code-423n4/2024-02-hydradx/blob/603187123a20e0cb8a7ea85c6a6d718429caad8d/HydraDX-node/pallets/omnipool/src/lib.rs#L1330-L1360 https://github.com/code-423n4/2024-02-hydradx/blob/603187123a20e0cb8a7ea85c6a6d718429caad8d/HydraDX-node/pallets/omnipool/src/lib.rs#L759-L764
Impact
This vulnerability will lead to huge loss of funds for liquidity providers that want to withdraw their liquidity if the safe withdrawal is enabled. The loss of funds can be 100% of the liquidity provider’s shares.
Proof of Concept
Normal Scenario of manipulating price and disabling removing or adding liquidity:
If the price of certain asset got manipulated, there is an ensure function exist in the remove_liquidity() and add_liquidity(), so the function should revert in case of the price of an asset got manipulated.
T::PriceBarrier::ensure_price(
&who,
T::HubAssetId::get(),
asset,
EmaPrice::new(asset_state.hub_reserve, asset_state.reserve),
)
.map_err(|_| Error::<T>::PriceDifferenceTooHigh)?;
This ensure_price() function checks that the difference between spot price and oracle price is not too high, so it has critical role to prevent the profitability from this manipulation.
There is also another security parameter which is the Tradability state which can prevent removing or adding liquidity. There is also withdrawal_fee, which is used to make manipulating price not profitable, and it can prevent the attacker from getting any of assets if the price difference is too high.
Important assumption:
The assumption is that the withdrawal can be done safely without checking the price difference because the swapping of this asset got disabled so the price is stable, as shown here.
let safe_withdrawal = asset_state.tradable.is_safe_withdrawal();
pub(crate) fn is_safe_withdrawal(&self) -> bool {
*self == Tradability::ADD_LIQUIDITY | Tradability::REMOVE_LIQUIDITY || *self == Tradability::REMOVE_LIQUIDITY
}
}
Edge case:
Due to the fact that there is not limitation on setting tradability states to any asset except the hub_asset, the tradability state can be set to prevent swapping on asset at manipulated price, by making the tradability state only contain remove and add liquidity flags, when the difference between spot price and the oracle price is too high.
In such cases, the remove_liquidity() function will not revert with price error because the function ensure-price() will not work, but it will pass and the withdrawal_fee will be equal to 1. So 100% of the liquidity to be removed will be taken from the user as fees and will be distributed on the other liquidity providers.
How this vulnerability can be applied:
- The price of asset got manipulated and the difference between spot and oracle price is too high.
- The tradability state of the asset has been set to
removeandaddliquidity only (buyingandsellingare disabled). - Any user trying to remove his liquidity will be taken as fees and there is no asset will be transferred to the user and the transaction will not revert, since there is no slippage (safety) parameter that can be set by the user to ensure that amount comes from this transaction is equal to what is expected.
The normal scenario here is that the remove_liquidity function should revert instead of taking all user assets as withdrawal_fee.
The code that calculates the withdrawal fee is:
pub fn calculate_withdrawal_fee(
spot_price: FixedU128,
oracle_price: FixedU128,
min_withdrawal_fee: Permill,
) -> FixedU128 {
let price_diff = if oracle_price <= spot_price {
spot_price.saturating_sub(oracle_price)
} else {
oracle_price.saturating_sub(spot_price)
};
let min_fee: FixedU128 = min_withdrawal_fee.into();
debug_assert!(min_fee <= FixedU128::one());
if oracle_price.is_zero() {
return min_fee;
}
// fee can be set to 100%
-> price_diff.div(oracle_price).clamp(min_fee, FixedU128::one())
}
The delta assets that send to the user will be zero in case that withdrawal_fee is 1.
// fee_complement = 0 ;
let fee_complement = FixedU128::one().saturating_sub(withdrawal_fee);
// Apply withdrawal fee
let delta_reserve = fee_complement.checked_mul_int(delta_reserve)?;
let delta_hub_reserve = fee_complement.checked_mul_int(delta_hub_reserve)?;
let hub_transferred = fee_complement.checked_mul_int(hub_transferred)?;
let delta_imbalance = calculate_delta_imbalance(delta_hub_reserve, imbalance, total_hub_reserve)?;
Tools Used
VS Code
Recommended Mitigation Steps
This vulnerability can be mitigated by only one step:
Check that the price is in the allowed Range before disabling the swapping and allow remove and add liquidity on any asset. This mitigation will make sure that the safe_withdrawal is set to true, except if the price in the Range so the price is actually stable and safe to withdraw liquidity on this price.
Consider modifying set_asset_tradable_state() function to ensure that if the state is set to preventing swapping, then ensure the price:
pub fn set_asset_tradable_state(
origin: OriginFor<T>,
asset_id: T::AssetId,
state: Tradability,
) -> DispatchResult {
T::TechnicalOrigin::ensure_origin(origin)?;
if asset_id == T::HubAssetId::get() {
// At the moment, omnipool does not allow adding/removing liquidity of hub asset.
// Although BUY is not supported yet, we can allow the new state to be set to SELL/BUY.
ensure!(
!state.contains(Tradability::ADD_LIQUIDITY) && !state.contains(Tradability::REMOVE_LIQUIDITY),
Error::<T>::InvalidHubAssetTradableState
);
HubAssetTradability::<T>::mutate(|value| -> DispatchResult {
*value = state;
Self::deposit_event(Event::TradableStateUpdated { asset_id, state });
Ok(())
})
} else {
Assets::<T>::try_mutate(asset_id, |maybe_asset| -> DispatchResult {
let asset_state = maybe_asset.as_mut().ok_or(Error::<T>::AssetNotFound)?;
+ if (state == Tradability::ADD_LIQUIDITY | Tradability::REMOVE_LIQUIDITY || state == Tradability::REMOVE_LIQUIDITY){
+
+ T::PriceBarrier::ensure_price(
+ &who,
+ T::HubAssetId::get(),
+ asset_id,
+ EmaPrice::new(asset_state.hub_reserve, asset_state.reserve),
+ )
+ .map_err(|_| Error::<T>::PriceDifferenceTooHigh)?;}
asset_state.tradable = state;
Self::deposit_event(Event::TradableStateUpdated { asset_id, state });
Ok(())
})
}
}
Assessed type
Invalid Validation
Lambda (judge) decreased severity to Low and commented:
Intended behaviour/design that this check is not performed in this state which can only be set by the
AuthorityOrigin, downgrading to QA.
castle_chain (warden) commented:
@Lambda,
- This finding points to the vulnerable function
set_asset_tradable_state, because it does not check that the price of the oracle is not too far from the spot price before activate thesafe modeso it can be front-run by attackers.- The impact of the 100% of the liquidity withdrawn by the user will be taken as the
withdrawal_fee, the impact of the Issue #93 is just a 1% due to the absence of the slippage parameter.
Lambda (judge) increased severity to Medium and commented:
The issue demonstrates that there can be edge cases where a very high fee is charged, therefore, upgrading it to a medium.
enthusiastmartin (HydraDX) acknowledged
Note: For full discussion, see here.
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 `set_asset_tradable_state` function does not verify that the spot price is close to the oracle price before allowing a state that disables swapping but permits liquidity removal, so the safe withdrawal check is bypassed and the withdrawal fee can reach 100%.
Impact
Liquidity providers could lose up to 100% of their withdrawn liquidity as fees if the safe withdrawal mode is enabled at a manipulated price; the judge noted this state can only be set by the AuthorityOrigin, limiting the attack surface.
What the attacker needed
AuthorityOrigin sets tradability state; Price manipulated before state change; User removes liquidity
The fix
The report recommends checking that the price is within the allowed range before disabling swapping and allowing remove and add liquidity, by adding a price check in `set_asset_tradable_state`.
How it was found
- Manipulate the price of an asset so the difference between spot and oracle price is too high.
- Set the tradability state of the asset to allow only adding and removing liquidity (disabling buying and selling).
- A user tries to remove liquidity; the withdrawal fee becomes 100%, so no assets are transferred and the transaction does not revert.
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.
This is about a decentralised exchange where people deposit assets (liquidity providers) and earn fees. Normally, if the price is manipulated, the system blocks withdrawals to protect users. But if the system is put into a special mode that only allows adding and removing liquidity, that protection is skipped, and a user trying to withdraw can lose everything because the fee becomes 100%. The report suggests checking the price before entering that mode.
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.