Skip to content
Smart contracts Write-up Advanced

Beanstalk

The Beanstalk convert function failed to validate the Well address provided by the user, allowing an attacker to supply a malicious contract that returns an arbitrary amount of BEANs. This could let the attacker deposit BEANs without withdrawing any tokens, potentially stealing all BEANs from the contract.

medium.com

Published on medium.com

Cybersecurity

Immunefi Editor, 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

Beanstalk is a credit-based stablecoin protocol on Ethereum. Its stablecoin, BEAN, sits at the centre of an Ethereum-native, rent-free economy, and the protocol tries to keep the BEAN price around $1 by adjusting supply according to its creditworthiness. When BEAN trades below $1 the protocol attracts lenders to stabilise the value; when it trades too high, new BEANs are minted and distributed.

One of the protocol's five major components is the Silo, which functions as the Beanstalk DAO. Depositors put BEANs and other whitelisted LP tokens into the Silo in exchange for passive yield. Conversion between BEAN Deposits and LP Deposits inside the Silo is what keeps the peg in place, and it is carried out through the convertFacet. The convert feature lets users swap BEANs for LP tokens when prices are high and LP tokens for BEANs when prices are low, provided the type of conversion is whitelisted.

The report examines the convert function in ConvertFacet.sol and the internal functions it calls.

Setup

On 8 November 2023 the whitehat @nicolecraw reported the issue to the Beanstalk bug bounty program through Immunefi. At the time of submission there were approximately $22.9 million worth of BEANs at risk. The report does not describe any particular account, tool or version used to find the bug; the analysis walks through the convert path in the Beanstalk repository.

Finding it

The convert function invokes two internal functions, and each one contributes to the problem.

1. convertData.convertWithAddress()

convertData.convertWithAddress() From the original on medium.com

The screenshot shows the convertData.convertWithAddress() code path. Here the input data supplied by the user (convertData) is decoded to obtain token amounts and an address, which is essentially the wellLp address. The issue is that there is no validation on this Well address, so anyone can supply a malicious contract in its place.

2. _wellRemoveLiquidityTowardsPeg

_wellRemoveLiquidityTowardsPeg From the original on medium.com

The screenshot shows _wellRemoveLiquidityTowardsPeg. In this function the decoded Well address is used to obtain the BEANs amount (amountOut). Because that address is attacker-controlled, a malicious contract can return the entire BEAN balance of the Beanstalk contract as amountOut.

The lpToPeg() function also makes calls to the same Well address, and the lpConverted amount is determined from the data it returns. That puts lpConverted under the attacker's control, allowing them to set it to zero, which in turn makes amountIn zero.

When the process returns to _withdrawTokens inside convertFacet.convert, it can be bypassed entirely by submitting empty stems and amounts arrays.

In essence the call ends up as:

  • toToken = BEAN
  • fromToken = Malicious Well
  • toAmount = anything the malicious Well returns, for example bean.balanceOf(beanstalk)
  • fromAmount = 0

Insufficient input validation therefore allowed a deposit of beans without withdrawing any tokens from the Silo, and that deposit could later be withdrawn easily.

Exploitation

Step 1: supply a malicious Well address

The attacker passes a convertData payload whose decoded Well address points at a contract they control. No check rejects it.

Step 2: make the Well report a large amountOut

When _wellRemoveLiquidityTowardsPeg asks the Well for the BEAN amount, the malicious contract answers with the whole BEAN balance of the Beanstalk contract.

Step 3: force lpConverted and amountIn to zero

The same malicious Well is queried by lpToPeg(). By choosing the returned data, the attacker sets lpConverted to zero, which makes amountIn zero.

Step 4: bypass the withdrawal

With amountIn at zero, _withdrawTokens in convertFacet.convert is skipped by submitting empty stems and amounts arrays. The conversion completes with toAmount set to the reported BEAN balance and fromAmount at zero, so beans are deposited without any tokens leaving the Silo.

Step 5: withdraw the deposit

The resulting deposit can later be withdrawn normally.

The Immunefi team prepared a proof of concept to demonstrate the vulnerability. The report shows only its output:

From the original on medium.com

Root cause

The decoded Well address from user-supplied convertData is used without validation. Both the amountOut calculation in _wellRemoveLiquidityTowardsPeg and the lpConverted value derived from lpToPeg() trust data returned by that address, so an attacker-controlled contract can dictate both the amount credited and the amount debited. Because amountIn can be driven to zero, the _withdrawTokens step can be skipped with empty stems and amounts arrays, and the accounting no longer ties the deposit to any tokens taken from the Silo.

Impact

A malicious user could potentially steal all of the BEANs from the Beanstalk contract. At the time of the submission approximately $22.9 million worth of BEANs were at risk. The report does not describe any funds actually being lost; the issue was addressed quickly through cooperation between the whitehat and the Beanstalk Immunefi Committee, and the whitehat received the maximum possible payout of 1,100,000 BEAN tokens ($1.1 million) from the Beanstalk DAO.

Fix

Beanstalk committed checks to ensure that the provided address is indeed a valid Well address.

From the original on medium.com

They also added a check for fromAmount, ensuring that it is always greater than zero, at a separate commit.

From the original on medium.com

Variants to test

  1. Unvalidated address fields in decoded user input. Look for structs decoded from calldata where an address is later used to make external calls. A positive result is a path where an arbitrary contract can be substituted and its return values feed into accounting.
  2. External calls whose return values set credited amounts. Trace any function that derives a credit (amountOut, lpConverted and similar) from a contract address the caller influences. A positive result is a credit that can be inflated or a debit that can be zeroed by a contract you deploy.
  3. Zero-amount withdrawals. Check whether a withdrawal or transfer step can be skipped by passing empty arrays or zero amounts while the corresponding deposit is still recorded. A positive result is a deposit that exists without any tokens having left the protocol.
  4. Missing lower bounds on input amounts. Where a computed amountIn or similar is used for accounting, test whether it can reach zero. A positive result is a state change that succeeds with a zero input amount.

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. 12 min read.

What happened, in plain words

Imagine a shop where you can swap one kind of voucher for another. The shop assistant is supposed to check that the voucher you hand over is real before giving you anything in return. Now imagine the assistant never checks, and instead asks you, the customer, "how much is your voucher worth?" You could answer "a million pounds", and the shop would believe you and hand over the goods. That is roughly what went wrong in Beanstalk.

Beanstalk is a piece of software that runs on Ethereum, a public blockchain. It manages a digital currency called BEAN, which is designed to stay close in value to one US dollar. On 8 November 2023, a security researcher who goes by the handle @nicolecraw reported a flaw in Beanstalk through a bug bounty platform called Immunefi. A bug bounty platform is a website where companies offer money to people who find and report security problems in their software, instead of exploiting them. The flaw was a case of insufficient input validation, which means the software accepted information from a user without checking whether that information made sense. In this case, the unchecked information could have let a malicious user steal all of the BEANs held by the Beanstalk contract. At the time of the submission, there were approximately $22.9 million worth of BEANs at risk.

The report was handled quickly. The researcher and the Beanstalk Immunefi Committee, a group that manages Beanstalk's bug bounty programme, worked together, and no user funds were lost. The researcher was awarded the maximum possible payout of 1,100,000 BEAN tokens, worth $1.1 million, by the Beanstalk DAO. A DAO, or decentralised autonomous organisation, is a group that makes decisions through votes recorded on a blockchain rather than through a traditional company structure.

From the original on medium.com

The image above is the header of the original article, titled "Beanstalk Insufficient Input Validation Bugfix Review", published by Immunefi Editor on 12 January 2024. It also carries a notice that the article has moved to the Immunefi Blog and that this version is archived.

What Beanstalk is

Before looking at the bug, it helps to understand what Beanstalk does. Beanstalk is a credit-based stablecoin protocol on Ethereum. A stablecoin is a digital currency whose value is meant to stay steady, usually tied to a real-world currency such as the US dollar. A protocol, in this context, is simply a set of rules written as computer code that runs on the blockchain and that anyone can use.

Most stablecoins keep their value by holding collateral: for every unit of the stablecoin, the issuer holds a dollar or something equivalent in reserve. Beanstalk works differently. It uses a credit system instead of collateral, aiming to create a decentralised and liquid asset. Decentralised means no single company or person is in charge; liquid means it is easy to buy, sell or exchange.

The protocol introduces BEAN, its stablecoin, as the core of an Ethereum-native, rent-free economy. Ethereum-native means it lives on the Ethereum blockchain. Beanstalk mainly tries to keep the BEAN price around $1 by adjusting how much BEAN exists, based on how creditworthy the protocol is judged to be. When BEAN prices fall below $1, the protocol attracts lenders to help stabilise the value. When prices rise too high, new BEANs are minted, meaning new units are created, and distributed. This inflationary mechanism, where the supply of a currency grows, is the foundation of the Beanstalk economy.

The Silo and the convert feature

Beanstalk has five major components. One of them is the Silo, which works like the Beanstalk DAO. Depositors put their BEANs and other whitelisted LP tokens into the Silo in exchange for passive yield. Let us unpack those terms.

  • A depositor is someone who puts assets into the protocol.
  • An LP token is a token you receive for providing liquidity. Liquidity means putting assets into a pool so that other people can trade against them; the LP token is a receipt for your share of that pool.
  • Whitelisted means explicitly approved by the protocol. Only tokens on the approved list can be used.
  • Passive yield means earnings that accumulate over time without you having to do anything active.

Converting between BEAN Deposits and LP Deposits inside the Silo is vital for keeping the peg, meaning keeping the price of BEAN close to its target of $1. This conversion is carried out through a piece of code called convertFacet. The convert feature works like a tool that lets users swap their BEANs for LP tokens when prices are high, and LP tokens for BEANs when prices are low, as long as the type of conversion is whitelisted. This helps balance things out and keep the price stable.

The report examines the convert function in a file called ConvertFacet.sol, and the internal functions it calls. A function is a named block of code that does a specific job. An internal function is one that is called from inside the same program rather than from outside.

Finding the flaw

The convert function calls two internal functions, and each one plays a part in the problem.

1. convertData.convertWithAddress()

convertData.convertWithAddress() From the original on medium.com

The screenshot shows the code of convertData.convertWithAddress(). Here, the input data supplied by the user, called convertData, is decoded to obtain token amounts and an address. Decoding means turning a packed bundle of data back into readable values. The address obtained is essentially the wellLp address. An address here is the identifier of a contract on the blockchain, similar to an account number.

The problem is that there is no validation on this Well address. Validation means checking that a value is legitimate before using it. Because there is no check, anyone can supply a malicious contract in place of the real Well address. A malicious contract is a piece of code written specifically to misbehave, for example by lying about values when asked.

2. _wellRemoveLiquidityTowardsPeg

_wellRemoveLiquidityTowardsPeg From the original on medium.com

The screenshot shows the _wellRemoveLiquidityTowardsPeg function. In this function, the decoded Well address is used to obtain the BEANs amount, stored in a variable called amountOut. A variable is a named place in the code where a value is kept.

Because that address is controlled by the attacker, a malicious contract can return the entire BEAN balance of the Beanstalk contract as amountOut. In other words, when the protocol asks "how many BEANs should this user get?", the attacker's contract answers "all of them", and the protocol believes it.

The lpToPeg() function also makes calls to the same Well address, and the lpConverted amount is determined from the data it returns. That puts lpConverted under the attacker's control, allowing them to set it to zero, which in turn makes amountIn zero. amountIn is the amount the user is supposed to be putting in; setting it to zero means the protocol thinks the user contributed nothing.

When the process returns to _withdrawTokens inside convertFacet.convert, that step can be bypassed entirely by submitting empty stems and amounts arrays. An array is an ordered list of values. An empty array is a list with nothing in it. stems and amounts are the lists that describe which deposits to take tokens from and how many; if both lists are empty, there is nothing to withdraw, and the withdrawal step does nothing.

In essence, the call ends up as:

  • toToken = BEAN
  • fromToken = Malicious Well
  • toAmount = anything the malicious Well returns, for example bean.balanceOf(beanstalk)
  • fromAmount = 0

Here toToken is what the user receives, fromToken is what the user gives, toAmount is how much is received and fromAmount is how much is given. bean.balanceOf(beanstalk) is a standard way of asking the BEAN token contract how many BEANs a particular address holds; here it asks how many the Beanstalk contract itself holds.

Insufficient input validation therefore allowed a deposit of beans without withdrawing any tokens from the Silo, and that deposit could later be withdrawn easily. A deposit here is a record inside the protocol saying the user has put in a certain amount.

How the attack would work, step by step

Step 1: supply a malicious Well address

The attacker passes a convertData payload whose decoded Well address points at a contract they control. A payload is the bundle of data sent to a function. No check rejects it, so the protocol accepts the fake address without question.

Step 2: make the Well report a large amountOut

When _wellRemoveLiquidityTowardsPeg asks the Well for the BEAN amount, the malicious contract answers with the whole BEAN balance of the Beanstalk contract. The protocol has no way of knowing the answer is false, because it never verifies the Well.

Step 3: force lpConverted and amountIn to zero

The same malicious Well is queried by lpToPeg(). By choosing the returned data, the attacker sets lpConverted to zero, which makes amountIn zero. This matters because the protocol uses amountIn to decide how much the user must give up.

Step 4: bypass the withdrawal

With amountIn at zero, _withdrawTokens in convertFacet.convert is skipped by submitting empty stems and amounts arrays. The conversion completes with toAmount set to the reported BEAN balance and fromAmount at zero, so beans are deposited without any tokens leaving the Silo.

Step 5: withdraw the deposit

The resulting deposit can later be withdrawn normally, as if it had been earned legitimately.

The Immunefi team prepared a proof of concept to demonstrate the vulnerability. A proof of concept, often shortened to PoC, is a small demonstration that shows a bug is real and can actually be triggered. The report shows only its output:

From the original on medium.com

The screenshot shows the output produced when the proof of concept was run.

Why it happened

The decoded Well address from user-supplied convertData is used without validation. Both the amountOut calculation in _wellRemoveLiquidityTowardsPeg and the lpConverted value derived from lpToPeg() trust data returned by that address. Trusting data from an untrusted source is the heart of the problem: an attacker-controlled contract can dictate both the amount credited to the user and the amount debited from them. Because amountIn can be driven to zero, the _withdrawTokens step can be skipped with empty stems and amounts arrays, and the accounting no longer ties the deposit to any tokens taken from the Silo. Accounting here means the internal bookkeeping that records who owes what to whom.

What the impact could have been

A malicious user could potentially steal all of the BEANs from the Beanstalk contract. At the time of the submission, approximately $22.9 million worth of BEANs were at risk. The report does not describe any funds actually being lost. The issue was addressed quickly through cooperation between the whitehat and the Beanstalk Immunefi Committee. A whitehat is a security researcher who finds vulnerabilities and reports them responsibly rather than exploiting them. The whitehat received the maximum possible payout of 1,100,000 BEAN tokens, worth $1.1 million, from the Beanstalk DAO.

The fix

Beanstalk committed checks to ensure that the provided address is indeed a valid Well address. A commit is a saved change to a code repository, the shared store of a project's code, and it records exactly what was changed and when.

From the original on medium.com

The screenshot shows the checks that were committed to ensure the provided address is a valid Well address.

They also added a check for fromAmount, ensuring that it is always greater than zero, at a separate commit.

From the original on medium.com

The screenshot shows the additional check on fromAmount, ensuring it is always greater than zero.

Similar patterns worth testing

If you are learning to review code, the same mistakes tend to reappear in different projects. These are the patterns to look for.

  1. Unvalidated address fields in decoded user input. Look for structures decoded from user-supplied data where an address is later used to make external calls. A positive result is a path where an arbitrary contract can be substituted and its return values feed into accounting.
  2. External calls whose return values set credited amounts. Trace any function that derives a credit, such as amountOut or lpConverted, from a contract address the caller influences. A positive result is a credit that can be inflated, or a debit that can be zeroed, by a contract you deploy.
  3. Zero-amount withdrawals. Check whether a withdrawal or transfer step can be skipped by passing empty arrays or zero amounts while the corresponding deposit is still recorded. A positive result is a deposit that exists without any tokens having left the protocol.
  4. Missing lower bounds on input amounts. Where a computed amountIn or similar is used for accounting, test whether it can reach zero. A positive result is a state change that succeeds with a zero input amount.

Glossary

  • Address: the identifier of an account or contract on a blockchain, similar to an account number.
  • Array: an ordered list of values in code; an empty array contains nothing.
  • Beanstalk: a credit-based stablecoin protocol on Ethereum that issues the BEAN stablecoin.
  • BEAN: the stablecoin issued by Beanstalk, designed to stay close in value to one US dollar.
  • Bug bounty: a programme that pays people for finding and reporting security problems instead of exploiting them.
  • Bug bounty platform: a website that hosts bug bounty programmes for many companies, such as Immunefi.
  • Collateral: assets held in reserve to back the value of a currency.
  • Commit: a saved change to a code repository, recording what changed and when.
  • Contract: a piece of code deployed on a blockchain that can hold assets and respond to calls.
  • Convert: the Beanstalk feature that swaps BEAN Deposits for LP Deposits and back.
  • DAO: decentralised autonomous organisation, a group that makes decisions through blockchain votes.
  • Decentralised: having no single company or person in charge.
  • Decode: turning a packed bundle of data back into readable values.
  • Deposit: a record inside the protocol saying a user has put in a certain amount.
  • Depositor: someone who puts assets into the protocol.
  • Ethereum: a public blockchain on which programs and tokens can run.
  • Ethereum-native: built to live on the Ethereum blockchain.
  • Function: a named block of code that performs a specific job.
  • Inflationary: describing a mechanism where the supply of a currency grows.
  • Input validation: checking that data supplied by a user is legitimate before using it.
  • Internal function: a function called from inside the same program rather than from outside.
  • Liquid: easy to buy, sell or exchange.
  • Liquidity: assets placed in a pool so that others can trade against them.
  • LP token: a token received for providing liquidity, acting as a receipt for a share of the pool.
  • Malicious contract: code written specifically to misbehave, for example by lying about values.
  • Mint: to create new units of a currency.
  • Passive yield: earnings that accumulate over time without active effort.
  • Payload: the bundle of data sent to a function.
  • Peg: the target value a stablecoin tries to hold, here $1 per BEAN.
  • Proof of concept (PoC): a small demonstration showing that a bug is real and can be triggered.
  • Protocol: a set of rules written as code that runs on a blockchain and that anyone can use.
  • Silo: the Beanstalk component that works like the Beanstalk DAO and holds deposits.
  • Stablecoin: a digital currency whose value is meant to stay steady, usually tied to a real-world currency.
  • Variable: a named place in code where a value is kept.
  • Well: the contract that Beanstalk queries to work out conversion amounts; its address is supplied in user input.
  • Whitehat: a security researcher who finds vulnerabilities and reports them responsibly rather than exploiting them.
  • Whitelisted: explicitly approved by the protocol.

Similar reports

View all

Same bug class and techniques, clearest first.

Smart contract vulnerabilities

The lesson behind this report.

Flaws in on-chain code that let an attacker drain funds, freeze them or break the protocol's accounting.