Skip to content
DoS Audit finding Intermediate

The Vault Manager is unable to delete the last strategy from MultiStrategyVault

The removeStrategy function in MultiStrategyVault fails when removing the last strategy because it sets totalWeight to zero before reallocating assets, causing a division-by-zero panic. This prevents the vault manager from deleting the last strategy, leaving the vault in a state where funds may be stuck until a rebalance.

pfapostol Follow

Originally disclosed on Code4rena

Submitted by pfapostol

The removeStrategy function in the MultiStrategy contract allows the removal of a strategy and redistributes the withdrawn funds among the remaining strategies.

  • Refered code:

        if (strategyAssets > 0) {
            IStrategy(_strategies[index]).undeploy(strategyAssets);
            _allocateAssets(strategyAssets);
        }
    

The issue arises when the last strategy is removed. The weight (_weights[index]) of the last strategy is first subtracted from _totalWeight, which results in _totalWeight being zero, and it is then set to zero.

Later, when _allocateAssets is called: for each of the active _strategies (the last strategy has not yet been removed), it attempts to calculate the fraction of the input amount. However, since _totalWeight is zero, the execution is reverted with a “panic: division or modulo by zero” error.

  • Vulnerable logic:

    function _allocateAssets(uint256 amount) internal returns (uint256 totalDeployed) {
        totalDeployed = 0;
        for (uint256 i = 0; i < _strategies.length; ) {
            uint256 fractAmount = (amount * _weights[i]) / _totalWeight;
            if (fractAmount > 0) {
                totalDeployed += IStrategy(_strategies[i]).deploy(fractAmount);
            }
            unchecked {
                i++;
            }
        }
    }
    

Impact

The VAULT_MANAGER_ROLE would be unable to delete the last strategy.

Proof of Concept

This PoC follows these steps:

  1. Deploy the StrategyUniV3SwapAnd strategy (or any other strategy) and initialize the MultiStrategyVault with this strategy to emulate the state where only one strategy remains in the vault.
  2. Deposit a certain amount into the vault.
  3. The VAULT_MANAGER_ROLE, in this case the same person as the DEPLOYER, attempts to remove the strategy.

However, the execution fails with:

    │   ├─ [109194] MultiStrategyVault::removeStrategy(0) [delegatecall]
...
    │   │   └─ ← [Revert] panic: division or modulo by zero (0x12)
    │   └─ ← [Revert] panic: division or modulo by zero (0x12)
// SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.24;

import {Test} from "lib/forge-std/src/Test.sol";
import {console} from "lib/forge-std/src/console.sol";
import {MockERC20} from "lib/forge-std/src/mocks/MockERC20.sol";

import {Command} from "contracts/core/MultiCommand.sol";
import {MultiStrategy} from "contracts/core/MultiStrategy.sol";
import {MultiStrategyVault} from "contracts/core/MultiStrategyVault.sol";
import {BakerFiProxy} from "contracts/proxy/BakerFiProxy.sol";
import {BakerFiProxyAdmin} from "contracts/proxy/BakerFiProxyAdmin.sol";
import {StrategyUniV3SwapAnd} from "contracts/core/strategies/StrategyUniV3SwapAnd.sol";
import {OracleMock} from "contracts/mocks/OracleMock.sol";
import {UniV3RouterMock} from "contracts/mocks/UniV3RouterMock.sol";
import {StrategyPark} from "contracts/core/strategies/StrategyPark.sol";
import {IStrategy} from "contracts/interfaces/core/IStrategy.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {UseUnifiedSwapper} from "contracts/core/hooks/swappers/UseUnifiedSwapper.sol";

contract PoCs is Test {
    address immutable DEPLOYER = makeAddr("DEPLOYER");
    address immutable USER1 = makeAddr("USER1");

    address constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;

    address constant WstETH = 0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0;

    function setUp() public {
        vm.label(WETH, "WETH");
        vm.label(WstETH, "WstETH");

        vm.createSelectFork("https://rpc.ankr.com/eth");
    }

    function test_removeStrategy_last_not_removed() public {
        vm.startPrank(DEPLOYER);
        address bakerFiProxyAdmin = address(new BakerFiProxyAdmin(DEPLOYER));

        // @note strategy deployment logic from test/core/strategies/StrategyUniV3SwapPark.ts
        uint256 WETH_SUPPLY = 100000 ether;
        deal(address(WETH), DEPLOYER, WETH_SUPPLY);

        uint256 WstETH_SUPPLY = 30000000 ether;
        deal(address(WstETH), DEPLOYER, WstETH_SUPPLY);

        OracleMock mockOracle = new OracleMock();
        mockOracle.setDecimals(18);
        mockOracle.setLatestPrice(1e16);

        UniV3RouterMock mockUniV3 = new UniV3RouterMock(
            IERC20(address(WETH)),
            IERC20(address(WstETH))
        );

        MockERC20(WETH).transfer(address(mockUniV3), WETH_SUPPLY);
        MockERC20(WstETH).transfer(address(mockUniV3), WstETH_SUPPLY);
        mockUniV3.setPrice(1e11);

        StrategyPark strategyPark = new StrategyPark(DEPLOYER, address(WstETH));

        StrategyUniV3SwapAnd strategyUniV3SwapAnd = new StrategyUniV3SwapAnd(
            DEPLOYER,
            IERC20(address(WETH)),
            strategyPark,
            mockOracle,
            mockUniV3,
            3000
        );

        strategyPark.transferOwnership(address(strategyUniV3SwapAnd));
        vm.label(address(strategyUniV3SwapAnd), "StrategyUniV3SwapAnd");
        // @note End of strategy deployment

        strategyUniV3SwapAnd.setMaxSlippage(1e8 /* 10% */);

        address impl = address(new MultiStrategyVault());

        IStrategy[] memory istrategies = new IStrategy[](1);
        istrategies[0] = strategyUniV3SwapAnd;
        uint16[] memory iweights = new uint16[](1);
        iweights[0] = 100;

        MultiStrategyVault msVault = MultiStrategyVault(
            payable(
                address(
                    new BakerFiProxy(
                        impl,
                        bakerFiProxyAdmin,
                        abi.encodeWithSelector(
                            MultiStrategyVault.initialize.selector,
                            DEPLOYER,
                            "AuditPoC",
                            "APC",
                            WETH,
                            istrategies,
                            iweights,
                            WETH
                        )
                    )
                )
            )
        );

        vm.startPrank(DEPLOYER);
        deal(address(WETH), DEPLOYER, 10 ether);
        MockERC20(WETH).approve(address(msVault), 10 ether);
        msVault.deposit(10 ether, DEPLOYER);

        msVault.removeStrategy(0);
    }
}

Recommended Mitigation Steps

There are several ways to improve the code to fix the issue (such as adding a check for zero, etc.). However, the most straightforward and direct approach is to remove the strategy from _strategies before calling _allocateAssets:

    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;

        IStrategy cache_strategy = _strategies[index];

        // 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 has assets, undeploy them and allocate accordingly
        if (strategyAssets > 0) {
            IStrategy(cache_strategy).undeploy(strategyAssets);
            _allocateAssets(strategyAssets);
        }
    }3

chefkenji (BakerFi) confirmed

0xpiken (warden) commented:

The last strategy should not be allowed to be removed since MultiStrategyVault allocates assets accordingly to its strategies. Removing the last strategy will leads DoS on MultiStrategyVault. The worse is that no user can withdraw their assets since _deallocateAssets() will return totalUndeployed as 0.

pfapostol (warden) commented:

Yes, but that sounds more like a second problem, unrelated to this one. The order of operations in the function is clearly incorrect.

Dravee (judge) commented:

Per the sponsor:

I understand both points but for me is an issue because it leaves the vault on a weird state (funds are waiting for a rebalance) that could only be unlocked by the vault manager with a rebalance

This finding is still valid.

BakerFi mitigated:

PR-18

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


The original report as published on Code4rena, by pfapostol. 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

The function updates _totalWeight to zero before calling _allocateAssets, which divides by _totalWeight, leading to a division-by-zero panic.

Impact

The vault manager cannot remove the last strategy, and the vault may be left in a state where funds are stuck until a rebalance, as noted by the sponsor.

What the attacker needed

Vault manager role; only one strategy in vault

The fix

The strategy should be removed from the arrays before calling _allocateAssets, or a zero-check should be added to prevent division by zero.

How it was found

  1. Deploy a strategy and initialize the vault with only that strategy.
  2. Deposit funds into the vault.
  3. As the vault manager, call removeStrategy on the only strategy.
  4. The transaction reverts with a division-by-zero panic.

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 contract lets a manager add or remove investment strategies. When removing the last strategy, the code divides by the total weight, which becomes zero, causing an error. This means the manager cannot remove the final strategy, and the vault may get stuck.

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.

More by pfapostol

View all

5 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.

Denial of service

The lesson behind this report.

A request that exhausts resources or crashes a component. Many programs forbid testing it; reports usually show it from code, not by attacking.