Skip to content
Business logic Write-up Advanced

Mushrooms

A flashloan function in the Strategy contract could be called by anyone and allowed an attacker to repay a flashloan taken from the Vault using the Strategy's own funds, generating profit. This could have led to the loss of 19 wBTC, worth about $635,000 at the time.

medium.com

Published on medium.com

Immunefi

Immunefi, on medium.com

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 5 min read.

Context

Mushrooms Finance is a yield aggregator whose contracts hold user funds and put them to work in external lending markets. This report concerns two of its contracts: StrategyCmpdWbtcV1 (the Strategy) and MMVault (the Vault). The Strategy holds wBTC cTokens from Compound and is meant to supply the underlying wBTC to the Vault. It exposes a flashloan function, mushroomsFlashloan(), whose original purpose was to serve as a callback for the Vault only, not to be called by arbitrary users.

The Vault is the contract users interact with: they deposit wBTC and receive shares of Mushroom cTokens. The Vault also offers a flashloan facility, and the Strategy's mushroomsFlashloan() is the function through which the Vault's flashloan is repaid. The interaction between these two contracts is where the logic error lives.

From the original on medium.com

Setup

The whitehat is CKK Sec, a recipient of Immunefi's Whitehat Scholarship. The report was disclosed to Immunefi on 8 June 2021. No special accounts, roles or tooling are described: the attack is carried out by an attacker contract calling public functions.

Finding it

The researcher noticed that mushroomsFlashloan() on the Strategy can be called by any user. That is wrong on its own terms, because the function exists only to be invoked by the Vault when the Vault's own flashloan is called. Because it is publicly callable, an attacker can flashloan from the Vault and repay it through the Strategy instead of repaying it themselves.

The function also contains a balance check intended to ensure the Strategy can cover the flashloan taken from the Vault:

Text
require(balanceOfWant() >= _amount, '!invalidFlashAmount');

That check is bypassable because the caller controls both _amount and the fee _fee passed with the flashloan. The _fee parameter was not meant to be attacker-controlled, since the function was designed to be called only by the Vault. With control over _fee, the attacker can sidestep several checks that would otherwise make the attack harder, and the net effect is that the Strategy withdraws wBTC from Compound, wBTC it had supplied earlier, and hands it over.

Exploitation

The attack uses three flash loans. The steps are as follows.

Step 1: Flash loan wBTC from elsewhere

The attacker takes a wBTC flash loan from an external source, for example Uniswap.

Step 2: Deposit into the Vault

The borrowed wBTC is deposited into MMVault, and the attacker receives shares of Mushroom cTokens. Steps 1 and 2 are only needed because the Vault does not normally hold wBTC; the deposit is what puts wBTC inside the Vault so that the next flash loan has something to lend.

Step 3: Flash loan from the Vault

With wBTC now in the Vault, the attacker flash loans wBTC from MMVault to the attack contract. This wBTC becomes the attack profit and stays in the attack contract.

Step 4: Repay through the Strategy

The attack contract calls mushroomsFlashloan on StrategyCmpdWbtcV1, repaying the Vault flash loan just taken, in wBTC. In effect the Strategy repays the flash loan, not the attacker, and that is where the profit comes from. The repayment works because the Strategy first withdraws the underlying wBTC from Compound:

Text
require(ICToken(cwbtc).redeemUnderlying(total) == 0, "!redeemFlashDeleverage");

Here total is _amount + _fee. Since _amount is 0, total is just _fee. The Strategy then transfers the withdrawn wBTC to the Vault in the last line of mushroomsFlashloan():

Text
IERC20(want).transfer(mwbtc, total);

Step 5: Vault flash loan completes

The Vault's flash loan finishes and control returns to the caller, the attack contract.

Step 6: Withdraw shares

The attacker withdraws the shares from the wBTC MMVault and receives additional wBTC. The wBTC supplied in step 2 is no longer wholly owned by the attacker; after the withdrawal the attacker owns it only partially, in proportion to its shares. The main profit was already realised in step 4.

Step 7: Repay the external flash loan

The attacker repays the wBTC flash loan taken from elsewhere, for example Uniswap.

Root cause

The mistake is a design error: a function intended solely as a Vault callback, mushroomsFlashloan(), was left callable by anyone. Its balance guard, require(balanceOfWant() >= _amount, '!invalidFlashAmount');, assumes the caller is the Vault and therefore does not defend against a caller who chooses _amount and _fee freely. Because _fee is attacker-controlled, the attacker can drive the Strategy's redeemUnderlying(total) against Compound and have the Strategy transfer the redeemed wBTC to the Vault, settling the Vault's flash loan with the Strategy's funds. The existing check did not stop this because it validates a balance against an amount the attacker also supplies.

Impact

The report states the attack vector could have resulted in the loss of 19 wBTC, which at the market rate at the time of the report came to $635,000.

Fix

Flashloan support was disabled on all Mushrooms Vaults, and the flashloan-related logic was re-implemented according to EIP-3156. Mushrooms Finance paused the contracts after receiving the report. The whitehat received a bounty of $60,000, of which $18,000 went to the Immunefi Whitehat Scholarship; the programme lists $50,000 for critical bugs, and Mushrooms Finance paid $10,000 above that in recognition of the size of the funds at risk.

Variants to test

  1. Look for callback-style functions on strategy or vault contracts that are meant to be invoked only by a paired contract but carry no caller check. A positive result is a public function that moves funds or redeems from an external market when called directly by an arbitrary address.
  2. Check flashloan repayment functions where the fee is a caller-supplied parameter. A positive result is a path where a caller-chosen fee changes the amount redeemed or transferred, or bypasses a balance or accounting check.
  3. Test balance guards of the form require(balanceOfX() >= amount) where amount is also an argument. A positive result is a call that satisfies the guard while still causing a withdrawal or transfer larger than the caller's own funds.
  4. Trace the interaction between a vault's flashloan and its strategy's repayment callback. A positive result is a sequence in which the strategy, not the borrower, settles the vault's loan.
  5. On forked or test deployments, replay the three-flash-loan sequence with _amount set to 0 and a non-zero _fee, and confirm whether the strategy redeems underlying from the external market and transfers it to the vault.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 10 min read.

What happened, in plain words

Mushrooms Finance is a service that takes cryptocurrency from users and puts it to work elsewhere to earn interest. Think of it like a savings app that pools everyone's money and lends it out. The money is held by small programs on a blockchain called smart contracts, which run automatically and cannot be changed once deployed.

One of those programs, called the Strategy, had a function (a piece of code anyone can trigger) that was supposed to be used only by another program, the Vault. But the door was left open: anyone could call it. A security researcher called CKK Sec spotted this and worked out that an attacker could use it to make the Strategy pay back a loan the attacker had taken from the Vault, effectively stealing the Strategy's funds. The report says this could have led to the loss of 19 wBTC, worth $635,000 at the time.

Mushrooms Finance paused the contracts after receiving the report and paid the researcher a $60,000 bounty. This article walks through how the bug worked, step by step, in plain language.

From the original on medium.com

Background: the pieces involved

Before the attack makes sense, you need to know what the main parts are.

Smart contract: a program that lives on a blockchain. It runs exactly as written, and anyone can send it instructions (called calls) by sending a transaction. There is no login or password; if a function is public, anyone can call it.

wBTC: a token that represents Bitcoin on another blockchain (Ethereum). It behaves like a digital coin you can move around and deposit.

cToken: when you supply an asset to Compound (a lending market), you get a cToken in return. It is a receipt that says "I supplied this much, and I can redeem it later, plus interest." The Strategy holds wBTC cTokens from Compound, meaning it has supplied wBTC there.

Vault (MMVault): the contract users interact with. You deposit wBTC and receive shares of Mushroom cTokens. The Vault also offers flash loans.

Strategy (StrategyCmpdWbtcV1): a contract that holds the wBTC cTokens in Compound and is meant to supply the underlying wBTC to the Vault when needed. It has a function called mushroomsFlashloan().

Flash loan: a loan that must be borrowed and repaid within the same transaction. If it is not repaid by the end, the whole transaction is undone as if it never happened. It is like borrowing a book from a library, reading it, and putting it back on the shelf before you leave the building. Flash loans are useful because they let you borrow large amounts without collateral, as long as you return them immediately.

Callback: a function that one contract calls on another to say "I have done my part, now you do yours." In this case, mushroomsFlashloan() was meant to be a callback that the Vault calls when its own flash loan needs to be repaid. It was not meant to be called by random users.

Finding the bug

The researcher noticed that mushroomsFlashloan() on the Strategy can be called by any user. That is wrong on its own terms, because the function exists only to be invoked by the Vault when the Vault's own flash loan is called. Because it is publicly callable, an attacker can flash loan from the Vault and repay it through the Strategy instead of repaying it themselves.

The function also contains a balance check intended to ensure the Strategy can cover the flash loan taken from the Vault:

Text
require(balanceOfWant() >= _amount, '!invalidFlashAmount');

Line by line:

  • require(...) is a guard. If the condition inside is false, the whole transaction stops and is undone.
  • balanceOfWant() asks the Strategy how much of the wanted token (wBTC) it currently holds.
  • >= _amount checks that the balance is at least the amount being flash loaned.
  • '!invalidFlashAmount' is the error message shown if the check fails.

That check is bypassable because the caller controls both _amount and the fee _fee passed with the flash loan. The _fee parameter was not meant to be attacker-controlled, since the function was designed to be called only by the Vault. With control over _fee, the attacker can sidestep several checks that would otherwise make the attack harder, and the net effect is that the Strategy withdraws wBTC from Compound, wBTC it had supplied earlier, and hands it over.

In plain terms: the guard compares the Strategy's balance against a number the attacker chooses. If the attacker sets that number to something convenient, the guard passes even though the attacker is about to take funds that are not theirs.

The attack, step by step

The attack uses three flash loans. Here is each step and why it is needed.

Step 1: Flash loan wBTC from elsewhere

The attacker takes a wBTC flash loan from an external source, for example Uniswap. Uniswap is a decentralised exchange where you can swap tokens; it also offers flash loans. The attacker needs wBTC to put into the Vault in the next step, and borrowing it temporarily is cheaper than buying it.

Step 2: Deposit into the Vault

The borrowed wBTC is deposited into MMVault, and the attacker receives shares of Mushroom cTokens. Steps 1 and 2 are only needed because the Vault does not normally hold wBTC; the deposit is what puts wBTC inside the Vault so that the next flash loan has something to lend.

Think of it like putting money into a cash machine so that you can then withdraw it as a "loan" from the same machine.

Step 3: Flash loan from the Vault

With wBTC now in the Vault, the attacker flash loans wBTC from MMVault to the attack contract. This wBTC becomes the attack profit and stays in the attack contract. The attack contract is a small program the attacker wrote to carry out the steps automatically.

Step 4: Repay through the Strategy

The attack contract calls mushroomsFlashloan on StrategyCmpdWbtcV1, repaying the Vault flash loan just taken, in wBTC. In effect the Strategy repays the flash loan, not the attacker, and that is where the profit comes from. The repayment works because the Strategy first withdraws the underlying wBTC from Compound:

Text
require(ICToken(cwbtc).redeemUnderlying(total) == 0, "!redeemFlashDeleverage");

Line by line:

  • ICToken(cwbtc) treats the cToken contract at address cwbtc as an interface, so the Strategy can call its functions.
  • .redeemUnderlying(total) asks Compound to give back total worth of the underlying wBTC in exchange for the cTokens.
  • == 0 checks that the redeem call returned 0, which in Compound means success.
  • "!redeemFlashDeleverage" is the error message if the redeem fails.

Here total is _amount + _fee. Since _amount is 0, total is just _fee. The Strategy then transfers the withdrawn wBTC to the Vault in the last line of mushroomsFlashloan():

Text
IERC20(want).transfer(mwbtc, total);

Line by line:

  • IERC20(want) treats the token at address want (the wBTC token) as an ERC-20 token, the standard interface for tokens.
  • .transfer(mwbtc, total) sends total tokens to the address mwbtc, which is the Vault.

So the Strategy pulls wBTC out of Compound and sends it to the Vault, settling the Vault's flash loan. The attacker did not repay anything from their own pocket; the Strategy did.

Step 5: Vault flash loan completes

The Vault's flash loan finishes and control returns to the caller, the attack contract. Because the loan was repaid (by the Strategy), the Vault considers the flash loan successful.

Step 6: Withdraw shares

The attacker withdraws the shares from the wBTC MMVault and receives additional wBTC. The wBTC supplied in step 2 is no longer wholly owned by the attacker; after the withdrawal the attacker owns it only partially, in proportion to its shares. The main profit was already realised in step 4.

In other words, the attacker put in some wBTC, got shares, and now takes out wBTC based on those shares.

Step 7: Repay the external flash loan

The attacker repays the wBTC flash loan taken from elsewhere, for example Uniswap.

Why it worked

The mistake is a design error: a function intended solely as a Vault callback, mushroomsFlashloan(), was left callable by anyone. Its balance guard, require(balanceOfWant() >= _amount, '!invalidFlashAmount');, assumes the caller is the Vault and therefore does not defend against a caller who chooses _amount and _fee freely. Because _fee is attacker-controlled, the attacker can drive the Strategy's redeemUnderlying(total) against Compound and have the Strategy transfer the redeemed wBTC to the Vault, settling the Vault's flash loan with the Strategy's funds. The existing check did not stop this because it validates a balance against an amount the attacker also supplies.

A simple comparison: imagine a bank teller who is supposed to accept withdrawal slips only from the bank manager. If anyone can walk up and hand in a slip, and the teller checks "is the amount on the slip less than the balance?" but the customer writes the amount themselves, the customer can write a small number to pass the check and then take out more than they should.

Impact

The report states the attack vector could have resulted in the loss of 19 wBTC, which at the market rate at the time of the report came to $635,000.

The fix

Flash loan support was disabled on all Mushrooms Vaults, and the flash loan related logic was re-implemented according to EIP-3156. EIP-3156 is a standard that describes how flash loans should be implemented. Mushrooms Finance paused the contracts after receiving the report. The whitehat received a bounty of $60,000, of which $18,000 went to the Immunefi Whitehat Scholarship; the programme lists $50,000 for critical bugs, and Mushrooms Finance paid $10,000 above that in recognition of the size of the funds at risk.

What to look for in similar code

If you are learning to review smart contracts, here are the patterns this bug illustrates.

  1. Look for callback-style functions on strategy or vault contracts that are meant to be invoked only by a paired contract but carry no caller check. A positive result is a public function that moves funds or redeems from an external market when called directly by an arbitrary address.
  2. Check flash loan repayment functions where the fee is a caller-supplied parameter. A positive result is a path where a caller-chosen fee changes the amount redeemed or transferred, or bypasses a balance or accounting check.
  3. Test balance guards of the form require(balanceOfX() >= amount) where amount is also an argument. A positive result is a call that satisfies the guard while still causing a withdrawal or transfer larger than the caller's own funds.
  4. Trace the interaction between a vault's flash loan and its strategy's repayment callback. A positive result is a sequence in which the strategy, not the borrower, settles the vault's loan.
  5. On forked or test deployments, replay the three-flash-loan sequence with _amount set to 0 and a non-zero _fee, and confirm whether the strategy redeems underlying from the external market and transfers it to the vault.

Glossary

  • Smart contract: a program that lives on a blockchain and runs automatically when called.
  • Blockchain: a shared, tamper-resistant record of transactions maintained by many computers.
  • wBTC: a token on Ethereum that represents Bitcoin.
  • cToken: a receipt token you get for supplying an asset to Compound; it can be redeemed later for the underlying asset plus interest.
  • Compound: a lending market where users supply and borrow crypto assets.
  • Vault (MMVault): the contract users deposit into and receive shares from; it also offers flash loans.
  • Strategy (StrategyCmpdWbtcV1): a contract that holds wBTC cTokens in Compound and supplies wBTC to the Vault.
  • Flash loan: a loan that must be borrowed and repaid within the same transaction, or the whole transaction is undone.
  • Callback: a function one contract calls on another to complete a multi-step operation.
  • Function: a named piece of code in a contract that can be called.
  • Parameter: an input value passed to a function when it is called.
  • require: a guard in Solidity that stops the transaction if its condition is false.
  • ERC-20: the standard interface for tokens on Ethereum, defining functions like transfer and balanceOf.
  • EIP-3156: a standard for implementing flash loans safely.
  • Bounty: a reward paid to a security researcher for finding and reporting a bug.
  • Whitehat: a security researcher who finds bugs and reports them responsibly rather than exploiting them.
  • Immunefi: a bug bounty platform for web3 projects.
  • Whitehat Scholarship: a programme that supports new security researchers with time and funding to hunt for bugs.
  • Uniswap: a decentralised exchange where tokens can be swapped and flash loans taken.
  • Transaction: a single action sent to a blockchain; if any part fails, the whole transaction is reverted.
  • Revert: undoing all changes made by a transaction when a check fails.
  • Fork: a copy of a blockchain's state used for testing.
  • Deployment: an instance of a contract running on a blockchain.

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.