The withdrawal of Multi strategies vault could be DoSed while asset deposits remain unaffected
A multi-strategy vault's withdrawal function could be blocked because it calls undeploy(0) on a strategy with no assets, which reverts. An attacker could add such a strategy, causing all withdrawals to fail until assets are deposited or the strategy is removed.
Submitted by 0xpiken, also found by klau5
https://github.com/code-423n4/2024-12-bakerfi/blob/main/contracts/core/MultiStrategy.sol#L173
Finding description and impact
The MultiStrategy#_deallocateAssets() function will be DoSed if IStrategy#undeploy(0) is called.
Proof of Concept
When withdrawing user assets from a multi-strategies vault, it will be withdrawn pro-rata from the strategies base on their deployed assets: https://github.com/code-423n4/2024-12-bakerfi/blob/main/contracts/core/MultiStrategyVault.sol:
function _undeploy(uint256 assets) internal virtual override returns (uint256 undeployedAmount) {
undeployedAmount = _deallocateAssets(assets); // Deallocates assets from the strategies and returns the undeployed amount
}
https://github.com/code-423n4/2024-12-bakerfi/blob/main/contracts/core/MultiStrategy.sol:
function _deallocateAssets(uint256 amount) internal returns (uint256 totalUndeployed) {
uint256[] memory currentAssets = new uint256[](_strategies.length);
uint256 totalAssets = 0;
uint256 strategiesLength = _strategies.length;
for (uint256 i = 0; i < strategiesLength; i++) {
currentAssets[i] = IStrategy(_strategies[i]).totalAssets();
totalAssets += currentAssets[i];
}
totalUndeployed = 0;
for (uint256 i = 0; i < strategiesLength; i++) {
uint256 fractAmount = (amount * currentAssets[i]) / totalAssets;
totalUndeployed += IStrategy(_strategies[i]).undeploy(fractAmount);
}
}
If a strategy has not yet deployed any assets, its totalAssets() call will return zero. Subsequently, the system will attempt to execute IStrategy.undeploy(0). However, this call is likely to revert, potentially leading to a denial-of-service condition for the entire withdrawal function: StrategySupplyBase.sol reverts ZeroAmount() when amount is 0:
function undeploy(uint256 amount) external nonReentrant onlyOwner returns (uint256 undeployedAmount) {
@> if (amount == 0) revert ZeroAmount();
// Get Balance
uint256 balance = getBalance();
if (amount > balance) revert InsufficientBalance();
// Transfer assets back to caller
uint256 withdrawalValue = _undeploy(amount);
// Check withdrawal value matches the initial amount
// Transfer assets to user
ERC20(_asset).safeTransfer(msg.sender, withdrawalValue);
balance -= amount;
emit StrategyUndeploy(msg.sender, withdrawalValue);
emit StrategyAmountUpdate(balance);
return amount;
}
StrategyLeverage.sol reverts NoCollateralMarginToScale() because totalCollateralInDebt is equal to totalDebtBalance(both of them are 0):
function undeploy(uint256 amount) external onlyOwner nonReentrant returns (uint256 undeployedAmount) {
undeployedAmount = _undeploy(amount, payable(msg.sender));
}
function _undeploy(uint256 amount, address receiver) private returns (uint256 receivedAmount) {
// Get price options from settings
IOracle.PriceOptions memory options = IOracle.PriceOptions({
maxAge: getPriceMaxAge(),
maxConf: getPriceMaxConf()
});
// Fetch collateral and debt balances
(uint256 totalCollateralBalance, uint256 totalDebtBalance) = getBalances();
uint256 totalCollateralInDebt = _toDebt(options, totalCollateralBalance, false);
// Ensure the position is not in liquidation state
@> if (totalCollateralInDebt <= totalDebtBalance) revert NoCollateralMarginToScale();
// Calculate percentage to burn to accommodate the withdrawal
uint256 percentageToBurn = (amount * PERCENTAGE_PRECISION) / (totalCollateralInDebt - totalDebtBalance);
// Calculate delta position (collateral and debt)
(uint256 deltaCollateralInDebt, uint256 deltaDebt) = _calcDeltaPosition(
percentageToBurn,
totalCollateralInDebt,
totalDebtBalance
);
// Convert deltaCollateralInDebt to deltaCollateralAmount
uint256 deltaCollateralAmount = _toCollateral(options, deltaCollateralInDebt, true);
// Calculate flash loan fee
uint256 fee = flashLender().flashFee(_debtToken, deltaDebt);
// Approve the flash lender to spend the debt amount plus fee
if (!IERC20Upgradeable(_debtToken).approve(flashLenderA(), deltaDebt + fee)) {
revert FailedToApproveAllowance();
}
// Prepare data for flash loan execution
bytes memory data = abi.encode(deltaCollateralAmount, receiver, FlashLoanAction.PAY_DEBT_WITHDRAW);
_flashLoanArgsHash = keccak256(abi.encodePacked(address(this), _debtToken, deltaDebt, data));
// Execute flash loan
if (!flashLender().flashLoan(IERC3156FlashBorrowerUpgradeable(this), _debtToken, deltaDebt, data)) {
_flashLoanArgsHash = 0;
revert FailedToRunFlashLoan();
}
// The amount of Withdrawn minus the repay ampunt
emit StrategyUndeploy(msg.sender, deltaCollateralInDebt - deltaDebt);
// Reset hash after successful flash loan
_flashLoanArgsHash = 0;
// Update deployed assets after withdrawal
receivedAmount = _pendingAmount;
uint256 undeployedAmount = deltaCollateralInDebt - deltaDebt;
_deployedAssets = _deployedAssets > undeployedAmount ? _deployedAssets - undeployedAmount : 0;
// Emit strategy update and reset pending amount
emit StrategyAmountUpdate(_deployedAssets);
// Pending amount is not cleared to save gas
//_pendingAmount = 0;
}
Copy below codes to VaultMultiStrategy.ts and run npm run test:
it.only('Withdraw is DoSed', async () => {
const { vault, usdc, owner, park1, park2 } = await loadFixture(deployMultiStrategyVaultFixture);
const amount = 10000n * 10n ** 18n;
await usdc.approve(vault.target, amount);
await vault.deposit(amount, owner.address);
//@audit-info deploy a erc4626 vault for StrategySupplyERC4626
const ERC4626Vault = await ethers.getContractFactory("ERC4626VaultMock");
const erc4626Vault = await ERC4626Vault.deploy(usdc.getAddress());
await erc4626Vault.waitForDeployment();
// Deploy StrategySupply contract
const StrategySupply = await ethers.getContractFactory('StrategySupplyERC4626');
const strategy = await StrategySupply.deploy(
owner.address,
await usdc.getAddress(),
await erc4626Vault.getAddress(),
);
await strategy.waitForDeployment();
await strategy.transferOwnership(await vault.getAddress());
//@audit-info add the new strategy to vault
await vault.addStrategy(await strategy.getAddress());
//@audit-info the new strategy has been added
expect(await vault.strategies()).to.include(await strategy.getAddress());
//@audit-info withdrawal is DoSed
await expect(vault.withdraw(amount, owner.address, owner.address)).to.be.revertedWithCustomError(
strategy,
'ZeroAmount',
);
});
Recommended mitigation steps
Check if the amount is 0 before undeploying it:
function _deallocateAssets(uint256 amount) internal returns (uint256 totalUndeployed) {
uint256[] memory currentAssets = new uint256[](_strategies.length);
uint256 totalAssets = 0;
uint256 strategiesLength = _strategies.length;
for (uint256 i = 0; i < strategiesLength; i++) {
currentAssets[i] = IStrategy(_strategies[i]).totalAssets();
totalAssets += currentAssets[i];
}
totalUndeployed = 0;
for (uint256 i = 0; i < strategiesLength; i++) {
uint256 fractAmount = (amount * currentAssets[i]) / totalAssets;
+ if (fractAmount == 0) continue;
totalUndeployed += IStrategy(_strategies[i]).undeploy(fractAmount);
}
}
chefkenji (BakerFi) confirmed
MrPotatoMagic (warden) commented:
There is no DOS issue here. The
VAULT_MANAGERcan simply remove the strategy in that case. Having a strategy without any assets deposited means the strategy is unused and should be removed.
VAULT_MANAGERmay add a new strategy with no assets allocated yet. All withdrawals since then will be DoS’ed.
MrPotatoMagic (warden) commented:
add a new strategy with no assets allocated yet.- You’ve added it to allow users to deposit. I do not see this being any more than Low/Info finding. The availability of the protocol is only impacted till the time you deposit assets into the new strategy.
First and foremost: this was confirmed by the sponsor. Let’s now discuss about the severity.
The availability of the protocol is only impacted till the time you deposit assets into the new strategy.
The protocol’s availability and functionality is indeed impacted unexpectedly. But there exist a workaround for this not to be permanent. Still, users’ assets can be affected quite badly (all withdrawals). This is an edge case, but it indeed qualifies as a Medium.
Status: Mitigation confirmed. Full details in reports from 0xlemon and shaflow2.
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 withdrawal loop does not skip strategies whose calculated share is zero, so it calls undeploy(0), which reverts.
Impact
All withdrawals from the vault could be blocked until the empty strategy is removed or receives assets; deposits are unaffected.
What the attacker needed
Vault manager adds a strategy with no assets
The fix
The withdrawal loop should skip strategies when the calculated share is zero.
How it was found
- Deploy a vault and deposit assets.
- Deploy a new strategy with no assets and transfer ownership to the vault.
- Add the new strategy to the vault.
- Attempt to withdraw; the transaction reverts with ZeroAmount.
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 vault spreads user money across several strategies. When someone withdraws, the vault asks each strategy to return a share. If a strategy holds nothing, the vault still asks it to return zero, and that strategy refuses, so the whole withdrawal fails. Adding an empty strategy therefore stops everyone from withdrawing.
What is DoS?
A request that exhausts resources or crashes a component. Many programs forbid testing it; reports usually show it from code, not by attacking.