Skip to content
Business logic Audit finding Intermediate

PoolAction::_balancerExit returns wrong token out amount

The `_balancerExit` function returns the recipient's entire token balance instead of the amount received from the exit, causing an exaggerated return value. This can lead to reverts in `PositionAction4626::_onDecreaseLever` when the contract tries to send more tokens than it holds.

0xAlix2 Follow

Originally disclosed on Code4rena

Submitted by 0xAlix2

Users use PoolAction::exit to exit a Balancer pool position, it calls _balancerExit to do the job. It is expected to exit the pool and return the amount out of the token; however, it returns the whole recipient’s balance, without considering the case where the recipient is holding an amount of the same token from different sources. It’ll return an exaggerated amount rather than the amount out.

This will cause PositionAction4626::_onDecreaseLever to revert sometimes. In this case, the user is leveraging down, exiting a Balancer pool, and holds some tokenOut amount. In PositionAction::onCreditFlashLoan, withdrawnCollateral would be an unreal exaggerated amount, and the contract will try to send back residualAmount which will be greater than its balance.

Proof of Concept

Add the following test in src/test/integration/PoolAction.t.sol:

function test_wrongBalancerExitAmount() public {
    uint256 amount = 10 ether;

    deal(wstETH, user, amount * 2);

    (uint8 v, bytes32 r, bytes32 s) = PermitMaker.getPermit2TransferFromSignature(
        address(wstETH),
        address(poolAction),
        amount,
        NONCE,
        block.timestamp,
        userPk
    );

    PermitParams[] memory permitParamsArray = new PermitParams[](3);
    permitParamsArray[1] = PermitParams(ApprovalType.PERMIT2, amount, NONCE, block.timestamp, v, r, s);

    address[] memory tokens = new address[](3);
    tokens[0] = wstETH_bb_a_WETH_BPTl;
    tokens[1] = wstETH;
    tokens[2] = bbaweth;

    uint256[] memory maxAmountsIn = new uint256[](3);
    maxAmountsIn[0] = 0;
    maxAmountsIn[1] = amount;
    maxAmountsIn[2] = 0;

    uint256[] memory tokensIn = new uint256[](2);
    tokensIn[0] = amount;
    tokensIn[1] = 0;

    uint256[] memory minAmountsOut = new uint256[](3);
    minAmountsOut[0] = 0;
    minAmountsOut[1] = 0;
    minAmountsOut[2] = 0;

    vm.startPrank(user);

    // Joins Balancer pool with 10 WSTETH
    poolAction.transferAndJoin(
        user,
        permitParamsArray,
        PoolActionParams(Protocol.BALANCER, 0, user, abi.encode(poolId, tokens, tokensIn, maxAmountsIn))
    );

    uint256 balancerLP = ERC20(wstETH_bb_a_WETH_BPTl).balanceOf(user);

    // Receives 11 Balancer LP tokens
    assertEq(balancerLP / 1 ether, 11);
    // Balance is 10 WSTETH
    assertEq(ERC20(wstETH).balanceOf(user), amount);

    // Transfer Balancer LP tokens to PoolAction
    ERC20(wstETH_bb_a_WETH_BPTl).transfer(address(poolAction), balancerLP);

    // Exits the Balancer pool
    uint256 amountOut = poolAction.exit(
        PoolActionParams(
            Protocol.BALANCER,
            0,
            user,
            abi.encode(poolId, wstETH_bb_a_WETH_BPTl, balancerLP, 0, tokens, minAmountsOut)
        )
    );

    // Amount returned by the function is 19 WSTETH instead of 9 WSTETH
    assertEq(amountOut / 1 ether, 19);
    // Balance is 19 WSTETH
    assertEq(ERC20(wstETH).balanceOf(user) / 1 ether, 19);
}

Recommended Mitigation Steps

Instead of returning the whole recipient’s balance, return the difference between his balances before and after the exit.

function _balancerExit(PoolActionParams memory poolActionParams) internal returns (uint256 retAmount) {
    (
        bytes32 poolId,
        address bpt,
        uint256 bptAmount,
        uint256 outIndex,
        address[] memory assets,
        uint256[] memory minAmountsOut
    ) = abi.decode(poolActionParams.args, (bytes32, address, uint256, uint256, address[], uint256[]));

    if (bptAmount != 0) IERC20(bpt).forceApprove(address(balancerVault), bptAmount);

+   uint256 tmpOutIndex = outIndex;
+   for (uint256 i = 0; i <= tmpOutIndex; i++) if (assets[i] == bpt) tmpOutIndex++;
+   uint256 balanceBefore = IERC20(assets[tmpOutIndex]).balanceOf(poolActionParams.recipient);

    balancerVault.exitPool(
        poolId,
        address(this),
        payable(poolActionParams.recipient),
        ExitPoolRequest({
            assets: assets,
            minAmountsOut: minAmountsOut,
            userData: abi.encode(ExitKind.EXACT_BPT_IN_FOR_ONE_TOKEN_OUT, bptAmount, outIndex),
            toInternalBalance: false
        })
    );

-   for (uint256 i = 0; i <= outIndex; ) {
-       if (assets[i] == bpt) {
-           outIndex++;
-       }
-
-       unchecked {
-           ++i;
-       }
-   }

-   return IERC20(assets[outIndex]).balanceOf(address(poolActionParams.recipient));
+   return IERC20(assets[tmpOutIndex]).balanceOf(poolActionParams.recipient) - balanceBefore;
}

Assessed type

DoS

amarcu (LoopFi) confirmed

Koolex (judge) commented:

Could you please adjust the PoC to support this claim in PJQA please?

This will cause PositionAction4626::_onDecreaseLever to revert sometimes. In this case, the user is leveraging down, exiting a Balancer pool, and holds some tokenOut amount. In PositionAction::onCreditFlashLoan, withdrawnCollateral would be an unreal exaggerated amount, and the contract will try to send back residualAmount which will be greater than it’s balance

0xAlix2 (warden) commented:

@Koolex - My bad for not providing it in the original issue, but I wanted to keep it as simple as possible as this POC is a bit more complicated.

The following test assuming 3 reported bugs are fixed, similar to issue #240, to workaround this:

  1. In PositionAction4626::_onDecreaseLever, replace:

    uint256 withdrawnCollateral = ICDPVault(leverParams.vault).withdraw(address(this), subCollateral);
    

with:

uint256 withdrawnCollateral = ICDPVault(leverParams.vault).withdraw(leverParams.position, subCollateral);
  1. In PositionAction4626::_onIncreaseLever, replace:
return ICDPVault(leverParams.vault).deposit(address(this), addCollateralAmount);

with:

return addCollateralAmount;
  1. At the top of PoolAction::updateLeverJoin, add:
poolToken = balancerVault.getPool(poolId);
contract PositionAction4626_Lever_Test is IntegrationTestBase {
    using SafeERC20 for ERC20;

    PRBProxy userProxy;
    address user;
    CDPVault vault;
    StakingLPEth stakingLPEth;
    PositionAction4626 positionAction;
    PermitParams emptyPermitParams;
    SwapParams emptySwap;
    PoolActionParams emptyPoolActionParams;

    bytes32[] weightedPoolIdArray;

    address constant wstETH_bb_a_WETH_BPTl = 0x41503C9D499ddbd1dCdf818a1b05e9774203Bf46;
    address constant wstETH = 0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0;
    address constant bbaweth = 0xbB6881874825E60e1160416D6C426eae65f2459E;
    bytes32 constant poolId = 0x41503c9d499ddbd1dcdf818a1b05e9774203bf46000000000000000000000594;

    function setUp() public override {
        super.setUp();
        setGlobalDebtCeiling(15_000_000 ether);

        token = ERC20PresetMinterPauser(wstETH);

        stakingLPEth = new StakingLPEth(address(token), "Staking LP ETH", "sLPETH");
        stakingLPEth.setCooldownDuration(0);
        vault = createCDPVault(stakingLPEth, 5_000_000 ether, 0, 1.25 ether, 1.0 ether, 1.05 ether);
        createGaugeAndSetGauge(address(vault), address(stakingLPEth));

        user = vm.addr(0x12341234);
        userProxy = PRBProxy(payable(address(prbProxyRegistry.deployFor(user))));

        positionAction = new PositionAction4626(
            address(flashlender),
            address(swapAction),
            address(poolAction),
            address(vaultRegistry)
        );

        weightedUnderlierPoolId = _createBalancerPool(address(token), address(underlyingToken)).getPoolId();

        oracle.updateSpot(address(token), 1 ether);
        oracle.updateSpot(address(stakingLPEth), 1 ether);
        weightedPoolIdArray.push(weightedUnderlierPoolId);
    }

    function test_wrongBalancerExitAmount_2() public {
        uint256 depositAmount = 250 ether;
        uint256 borrowAmount = 100 ether;

        uint256 flashLoanAmount = borrowAmount / 2;

        deal(address(token), user, depositAmount);

        address[] memory assets = new address[](2);
        assets[0] = address(underlyingToken);
        assets[1] = address(token);

        address[] memory tokens = new address[](3);
        tokens[0] = wstETH_bb_a_WETH_BPTl;
        tokens[1] = wstETH;
        tokens[2] = bbaweth;

        vm.startPrank(user);

        // Deposit `wstETH` to get `sLPETH`
        // Deposit 250 `sLPETH` to vault
        {
            token.approve(address(stakingLPEth), depositAmount);
            stakingLPEth.approve(address(userProxy), depositAmount);

            stakingLPEth.deposit(depositAmount, user);

            userProxy.execute(
                address(positionAction),
                abi.encodeWithSelector(
                    positionAction.deposit.selector,
                    address(userProxy),
                    address(vault),
                    CollateralParams({
                        targetToken: address(stakingLPEth),
                        amount: depositAmount,
                        collateralizer: address(user),
                        auxSwap: emptySwap
                    }),
                    emptyPermitParams
                )
            );
        }

        // Borrow 100 ETH
        {
            userProxy.execute(
                address(positionAction),
                abi.encodeWithSelector(
                    positionAction.borrow.selector,
                    address(userProxy),
                    address(vault),
                    CreditParams({amount: borrowAmount, creditor: user, auxSwap: emptySwap})
                )
            );

            // Collateral is 250 ETH, debt is 100 ETH
            (uint256 collateral, uint256 debt, , , , ) = vault.positions(address(userProxy));
            assertEq(collateral, depositAmount);
            assertEq(debt, borrowAmount);
        }

        // Increase leverage
        // Takes a flash loan of 50 ETH borrow tokens (adds that as a debt)
        // Swap the borrow tokens to collateral tokens, and join Balancer pool
        // (around 49 collateral tokens are deposited into the balancer position)
        {
            uint256[] memory maxAmountsIn = new uint256[](3);
            maxAmountsIn[0] = 0;
            maxAmountsIn[1] = borrowAmount / 2 - 1 ether;
            maxAmountsIn[2] = 0;
            uint256[] memory tokensIn = new uint256[](2);
            tokensIn[0] = borrowAmount / 2 - 1 ether;
            tokensIn[1] = 0;

            userProxy.execute(
                address(positionAction),
                abi.encodeWithSelector(
                    positionAction.increaseLever.selector,
                    LeverParams({
                        position: address(userProxy),
                        vault: address(vault),
                        collateralToken: address(stakingLPEth),
                        primarySwap: SwapParams({
                            swapProtocol: SwapProtocol.BALANCER,
                            swapType: SwapType.EXACT_IN,
                            assetIn: address(underlyingToken),
                            amount: flashLoanAmount,
                            limit: 0,
                            recipient: address(positionAction),
                            deadline: block.timestamp,
                            args: abi.encode(weightedPoolIdArray, assets)
                        }),
                        auxSwap: emptySwap,
                        auxAction: PoolActionParams(
                            Protocol.BALANCER,
                            0,
                            user,
                            abi.encode(poolId, tokens, tokensIn, maxAmountsIn)
                        )
                    }),
                    address(0),
                    0,
                    address(user),
                    emptyPermitParams
                )
            );

            // Collateral remains the same, debt increases by 50 ETH
            // User has around 56 Balancer LP tokens
            (uint256 collateral, uint256 debt, , , , ) = vault.positions(address(userProxy));
            assertEq(collateral, depositAmount);
            assertEq(debt, borrowAmount + flashLoanAmount);
            assertEq(IERC20(wstETH_bb_a_WETH_BPTl).balanceOf(user) / 1 ether, 56);
        }

        {
            // Verify that the position action contract and the user don't hold any collateral tokens
            assertEq(token.balanceOf(address(positionAction)), 0);
            assertEq(token.balanceOf(user), 0);

            uint256[] memory minAmountsOut = new uint256[](3);
            minAmountsOut[0] = 0;
            minAmountsOut[1] = 0;
            minAmountsOut[2] = 0;

            // Send the Balancer LP tokens to the position action contract, to exit the Balancer pool
            uint256 bptAmount = IERC20(wstETH_bb_a_WETH_BPTl).balanceOf(user);
            IERC20(wstETH_bb_a_WETH_BPTl).transfer(address(positionAction), bptAmount);

            deal(address(token), user, depositAmount);

            // User holds 100 tokens
            assertEq(token.balanceOf(user), depositAmount);

            // Leverage down the position
            // Takes a flash loan of 40 ETH borrow tokens (decreases the debt), withdraws 70 ETH collateral tokens (residual should be sent to the user)
            // Swap collateral tokens to borrow tokens, to repay the flash loan
            // Exits the Balancer pool, and sends the residual collateral tokens to the user
            // REVERTS
            vm.expectRevert(bytes("ERC20: transfer amount exceeds balance"));
            userProxy.execute(
                address(positionAction),
                abi.encodeWithSelector(
                    positionAction.decreaseLever.selector,
                    LeverParams({
                        position: address(userProxy),
                        vault: address(vault),
                        collateralToken: address(stakingLPEth),
                        auxSwap: emptySwap,
                        primarySwap: SwapParams({
                            swapProtocol: SwapProtocol.BALANCER,
                            swapType: SwapType.EXACT_OUT,
                            assetIn: address(token),
                            amount: 40 ether,
                            limit: 50 ether,
                            recipient: address(positionAction),
                            deadline: block.timestamp,
                            args: abi.encode(weightedPoolIdArray, assets)
                        }),
                        auxAction: PoolActionParams(
                            Protocol.BALANCER,
                            0,
                            user,
                            abi.encode(poolId, wstETH_bb_a_WETH_BPTl, bptAmount, 0, tokens, minAmountsOut)
                        )
                    }),
                    70 ether,
                    address(user)
                )
            );
        }
    }

    function _createBalancerPool(address t1, address t2) internal returns (IComposableStablePool pool_) {
        uint256 amount = 5_000_000_000 ether;
        deal(t1, address(this), amount);
        deal(t2, address(this), amount);

        uint256[] memory maxAmountsIn = new uint256[](2);
        address[] memory assets = new address[](2);
        assets[0] = t1;
        uint256[] memory weights = new uint256[](2);
        weights[0] = 500000000000000000;
        weights[1] = 500000000000000000;

        bool tokenPlaced;
        address tempAsset;
        for (uint256 i; i < assets.length; i++) {
            if (!tokenPlaced) {
                if (uint160(assets[i]) > uint160(t2)) {
                    tokenPlaced = true;
                    tempAsset = assets[i];
                    assets[i] = t2;
                } else if (i == assets.length - 1) {
                    assets[i] = t2;
                }
            } else {
                address placeholder = assets[i];
                assets[i] = tempAsset;
                tempAsset = placeholder;
            }
        }

        for (uint256 i; i < assets.length; i++) {
            maxAmountsIn[i] = ERC20(assets[i]).balanceOf(address(this));
            ERC20(assets[i]).safeApprove(address(balancerVault), maxAmountsIn[i]);
        }

        pool_ = weightedPoolFactory.create(
            "50WETH-50TOKEN",
            "50WETH-50TOKEN",
            assets,
            weights,
            3e14, // swapFee (0.03%)
            address(this) // owner
        );

        balancerVault.joinPool(
            pool_.getPoolId(),
            address(this),
            address(this),
            JoinPoolRequest({
                assets: assets,
                maxAmountsIn: maxAmountsIn,
                userData: abi.encode(JoinKind.INIT, maxAmountsIn),
                fromInternalBalance: false
            })
        );
    }

    function getForkBlockNumber() internal pure virtual override(IntegrationTestBase) returns (uint256) {
        return 17870449; // Aug-08-2023 01:17:35 PM +UTC
    }
}

Koolex (judge) commented:

@0xAlix2 - Could you please explain why should we update the code according to point 3 above?

0xAlix2 (warden) commented:

@Koolex - The third point refers to another issue that is reported, Issue 241, it just bypasses that issue and makes sure it doesn’t revert because of that issue. Issue #241 just shows a more sophisticated mitigation.


The original report as published on Code4rena, by 0xAlix2. 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 returns the recipient's total balance of the output token instead of the difference between the balance before and after the exit.

Impact

This can cause `PositionAction4626::_onDecreaseLever` to revert sometimes, as the contract may try to send more tokens than it holds.

What the attacker needed

User holds tokens from other sources; User exits a Balancer pool

The fix

The fix is to return the difference between the recipient's balance before and after the exit, rather than the total balance.

How it was found

  1. User joins a Balancer pool with 10 WSTETH, receiving LP tokens.
  2. User transfers the LP tokens to the PoolAction contract.
  3. User calls `poolAction.exit` to exit the Balancer pool.
  4. The function returns 19 WSTETH instead of the expected 9 WSTETH, as shown by the test assertion.

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.

When you exit a Balancer pool, the contract should tell you how many tokens you just received. Instead, it tells you your total balance of that token, which includes tokens you already had. This wrong number can cause later steps to fail because the contract thinks it has more tokens than it actually does.

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

View all

39 more disclosed reports, best first.

More from LoopFi

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.