Skip to content
Business logic Audit finding Intermediate

MultiStrategy#removeStrategy() cannot remove leverage strategies that still have deployed assets

The removeStrategy function in MultiStrategyVault assumes that undeploying a strategy returns exactly the amount requested, but for leverage strategies the received amount can be less due to flash loan fees and swap slippage. This causes the subsequent allocation to fail because the vault tries to allocate more assets than it actually received.

0xpiken Follow with 0xlemon, pfapostol and 1 other

Originally disclosed on Code4rena

Submitted by 0xpiken, also found by 0xlemon, pfapostol, and shaflow2

https://github.com/code-423n4/2024-12-bakerfi/blob/main/contracts/core/MultiStrategy.sol#L265

Finding description and impact

A leverage strategy with deployed assets can not be removed from MultiStrategyVault due to insufficient assets

Proof of Concept

MultiStrategyVault is used to manage multiple investment strategies. The vault manager can remove an existing strategy by calling MultiStrategy#removeStrategy():

    function removeStrategy(uint256 index) external onlyRole(VAULT_MANAGER_ROLE) {
        // Validate the index to ensure it is within bounds
        if (index >= _strategies.length) revert InvalidStrategyIndex(index);

        // Retrieve the total assets managed by the strategy to be removed
        uint256 strategyAssets = _strategies[index].totalAssets();

        // Update the total weight and mark the weight of the removed strategy as zero
        _totalWeight -= _weights[index];
        _weights[index] = 0;

        // If the strategy has assets, undeploy them and allocate accordingly
        if (strategyAssets > 0) {
@>          IStrategy(_strategies[index]).undeploy(strategyAssets);
@>          _allocateAssets(strategyAssets);
        }

        // Move the last strategy to the index of the removed strategy to maintain array integrity
        uint256 lastIndex = _strategies.length - 1;
        if (index < lastIndex) {
            _strategies[index] = _strategies[lastIndex];
            _weights[index] = _weights[lastIndex];
        }

        emit RemoveStrategy(address(_strategies[lastIndex]));
        // Remove the last strategy and weight from the arrays
        _strategies.pop();
        _weights.pop();
    }

If the strategy to be removed has deployed assets, it will be undeployed first and then allocated to other strategies. It is expected that the equivalent amount of assets will be received when calling IStrategy.undeploy():

          IStrategy(_strategies[index]).undeploy(strategyAssets);
          _allocateAssets(strategyAssets);

However, the amount of received assets could be less than strategyAssets if the strategy is a leverage strategy.

When a leverage strategy is used to undeploy assets:

  1. deltaDebt of debt token will be borrowed from flashLender

  2. Then the borrowed debt token is repaid to the lending protocol to withdraw deltaCollateralAmount of collateral

  3. The withdrawn collateral is swapped to debt token

  4. A certain number (deltaDebt + fee) of debt token will be paid to flashLender

    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;
    }
    

    The amount of received assets can be calculated as below:

Note: please see scenario in warden’s original submission.

Recommended mitigation steps

When removing a strategy from MultiStrategyVault, ensure the amount of assets to be re-allocated is same as the received amount:

    function removeStrategy(uint256 index) external onlyRole(VAULT_MANAGER_ROLE) {
        // Validate the index to ensure it is within bounds
        if (index >= _strategies.length) revert InvalidStrategyIndex(index);

        // Retrieve the total assets managed by the strategy to be removed
        uint256 strategyAssets = _strategies[index].totalAssets();

        // Update the total weight and mark the weight of the removed strategy as zero
        _totalWeight -= _weights[index];
        _weights[index] = 0;

        // If the strategy has assets, undeploy them and allocate accordingly
        if (strategyAssets > 0) {
-           IStrategy(_strategies[index]).undeploy(strategyAssets);
-           _allocateAssets(strategyAssets);
+           _allocateAssets(IStrategy(_strategies[index]).undeploy(strategyAssets));
        }

        // Move the last strategy to the index of the removed strategy to maintain array integrity
        uint256 lastIndex = _strategies.length - 1;
        if (index < lastIndex) {
            _strategies[index] = _strategies[lastIndex];
            _weights[index] = _weights[lastIndex];
        }

        emit RemoveStrategy(address(_strategies[lastIndex]));
        // Remove the last strategy and weight from the arrays
        _strategies.pop();
        _weights.pop();
    }

chefkenji (BakerFi) confirmed

BakerFi mitigated:

PR-16

Status: Mitigation confirmed. Full details in reports from 0xlemon and shaflow2.


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

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 code uses the requested undeploy amount for allocation instead of the actual amount returned by the undeploy call.

Impact

The vault manager cannot remove a leverage strategy that still has deployed assets, potentially locking the strategy in place.

What the attacker needed

Vault manager role; a leverage strategy with deployed assets

The fix

The fix was to allocate the actual amount returned by undeploy instead of the requested amount.

How it was found

  1. A leverage strategy with deployed assets exists in the vault.
  2. The vault manager calls removeStrategy for that strategy.
  3. The function calls undeploy with the strategy's total assets.
  4. The undeploy returns less than requested due to flash loan fees and swap costs.
  5. The function then tries to allocate the original requested amount, which exceeds the received amount, causing a 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.

A vault manages money across different investment strategies. When the manager removes a strategy, the vault first takes back the money from that strategy and then puts it into the remaining ones. For some strategies, taking the money back costs fees, so the vault gets less than expected and the next step fails because it tries to move more money than it has.

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 0xpiken

View all

29 more disclosed reports, best first.

More from BakerFi Invitational

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.