Skip to content
Access control Write-up Intermediate

[web3] Sense Finance Access Control Issue Bugfix Review. This is a postmortem of a vulnerability… | by Immunefi | Aug, 2022 | Medium

The onSwap() function in the Sense Balancer pool lacked access control, allowing anyone to call it directly and supply arbitrary price and reserve data to the oracle. This could let an attacker manipulate the oracle price and timestamp, potentially enabling theft of borrowable collateral from Rari pools that relied on the oracle.

medium.com

Published on medium.com

Sense Finance

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

Sense Finance is decentralised, permissionless infrastructure on which teams build yield primitives for DeFi: bond-like assets, yield tokens and tranche-like instruments. Its first application, yield-stripping, lets users lend at a fixed rate and take capital-efficient long or short positions on the future yield of existing yield-bearing assets.

At the centre of the report is Sense Space, an AMM contract built on top of Balancer V2 that implements the yieldspace invariant and serves as the market for trading Principal Tokens (PTs) and Yield Tokens (YTs). Balancer itself acts as an automated portfolio manager, liquidity provider and price sensor. When the Balancer vault handles a swap between tokens, it calls back into the onSwap() function of the Space AMM pool to determine output amounts using all token balances. That callback does more than price the trade: it also updates the oracle information stored on the pool contract, alongside the reserve information supplied by the Balancer vault.

From the original on medium.com

Setup

No special accounts, tooling or versions are described. The relevant actors and components are:

  • The Balancer vault, which is the legitimate caller of the pool's callback functions.
  • The Space AMM pool contract, which holds the oracle state and exposes onSwap(), onJoin() and onExit().
  • The Sense Fuse pools at Rari Capital, which relied on the Space AMM contract oracle.
  • The onlyVault() modifier on the pool, intended to restrict calls to the Balancer vault.

The precondition for the issue is simply that a caller other than the vault can reach onSwap() with attacker-controlled request data.

Finding it

The whitehat, Reptile71590, identified that the onSwap() function on the Space AMM pool contract did not validate whether the caller was the Balancer vault. The pool already had an onlyVault() modifier, which allows calls from the Balancer vault contract, and it was applied to the onJoin() and onExit() functions. It was not applied to onSwap().

That asymmetry is what made the callback interesting: the same function that prices swaps is also the path by which oracle data is written into the pool's state, so an unauthenticated caller could reach a state-changing oracle update.

Exploitation

Step 1: call onSwap() directly

Because there was no caller check, a malicious actor could call the onSwap() function on the pool directly, bypassing the Balancer vault entirely.

Step 2: supply arbitrary price and reserve data

The attacker could provide any price and reserves information to the oracle through that call.

Step 3: let the oracle persist it

The oracle would then set that supplied information into the state. From that point the oracle would read out as having that price recorded arbitrarily far into the past or future, From that point the oracle would read out as having that price recorded arbitrarily far into the past or future..

From the original on medium.com

In short, anyone could call onSwap() with attacker-controlled request data to manipulate the stored oracle data.

Root cause

The mistake is a missing authorisation check on a state-changing callback. The onlyVault() modifier existed and was correctly placed on onJoin() and onExit(), but the developer omitted it on onSwap(). Since onSwap() both computes output amounts and writes oracle and reserve information into the pool's storage, the omission turned a vault-only callback into a publicly writable oracle update path. The existing defence, the modifier itself, did not stop the attack because it was never attached to the vulnerable function.

Impact

The immediate consequence was that a malicious actor could update the oracle data of the Space AMM contract with arbitrary prices and timestamps. The report states that there were no assets at risk at the time, because the pools relying on the Space AMM oracle were paused by the Sense team upon disclosure.

Had those pools been live, the impact would have been severe. The Sense Fuse pools at Rari Capital relied on the Space AMM contract oracle, so manipulating the oracle price and timestamp could have allowed an attacker to steal any borrowable collateral provided to the Rari pools, and to steal assets of users that had been borrowed against. The report describes this as liquidation of collateral and taking a bad loan, all achieved by manipulating the oracle price and timestamp.

Sense paid the full $50,000 bounty to the whitehat and has already deployed a fix to the mainnet.

Fix

The Sense team fixed the vulnerability by adding a condition so that the oracle update of the pool is performed only if the caller is the Balancer vault. The fix adds a condition so the oracle update happens only if the caller is the Balancer vault.

From the original on medium.com

Variants to test

  • Callback functions on AMM pools built on Balancer V2. Enumerate every function the vault is expected to call (onSwap, onJoin, onExit and any others the pool exposes) and check each one for a caller check. A positive result is a function that writes to storage, including oracle or reserve state, and can be invoked successfully from an address other than the vault.
  • Modifier coverage audits. Where a codebase defines a guard such as onlyVault(), list every function that mutates the guarded state and confirm the modifier is present on each. A positive result is a state-changing function that lacks the modifier while its siblings have it.
  • Oracle write paths reachable from pricing callbacks. Trace what a swap callback writes, not just what it returns. A positive result is a callback that accepts caller-supplied price, reserve or timestamp values and persists them without authenticating the caller.
  • Timestamp handling in oracle updates. Check whether a caller can influence the timestamp recorded with a price. A positive result is an oracle entry that can be placed arbitrarily far in the past or future, which is what makes stale or future-dated prices exploitable by downstream lending markets.
  • Downstream consumers of the oracle. Identify lending pools that read the oracle, as the Rari Fuse pools did, and assess what a manipulated price and timestamp would allow: borrowing against inflated collateral, triggering liquidations, or taking undercollateralised loans.

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

A security researcher (in this world, often called a "whitehat", meaning someone who finds bugs and reports them to the people who can fix them rather than exploiting them) found a serious flaw in a piece of software called Sense Finance. The researcher reported it through a bug bounty platform called Immunefi. A bug bounty is a programme where a company offers money to anyone who finds and responsibly reports a security problem in its software. The company then fixes the problem and pays the reward.

The flaw was a missing check. In simple terms: a piece of the software was supposed to answer only when a specific, trusted part of the system knocked on its door, but in fact it answered anyone who knocked. Because that piece of software also records price information (an "oracle"), anyone could walk up and write whatever price they liked into it.

No money was lost. The team had paused the parts of the system that depended on this price feed as soon as the report came in, so there was nothing to steal at that moment. Sense paid the full $50,000 reward and shipped a fix to the live network (the "mainnet", meaning the real, production version of the blockchain rather than a test one).

From the original on medium.com

Background: the pieces involved

Before the bug makes sense, you need to know what the moving parts are. None of them require any special software to understand; they are just programs running on a blockchain.

What a blockchain and a smart contract are

A blockchain is a shared record book that many computers keep copies of, and that nobody can quietly edit after the fact. A smart contract is a small program that lives on that record book. Anyone can send it a message asking it to do something, and it does that thing according to its code. Because the code is public, anyone can read it and look for mistakes. That is exactly what happened here.

What Sense Finance is

Sense Finance is described as decentralised, permissionless infrastructure. "Decentralised" means no single company sits in the middle controlling it; "permissionless" means anyone can use it without asking for an account. Teams build on top of it to create new financial building blocks for DeFi (decentralised finance, meaning financial services built on blockchains rather than run by banks).

The first application built on Sense is called yield-stripping. It lets users lend at a fixed interest rate and make bets, in a capital-efficient way, on what the future yield of an existing yield-bearing asset will be. "Yield" here simply means the return an asset earns over time. You do not need the financial detail to follow the bug; what matters is that prices feed into these products.

What an AMM is

AMM stands for Automated Market Maker. It is a program that lets people trade one token for another without a human market maker sitting in the middle. Instead of matching buyers and sellers by hand, it uses a mathematical formula to work out prices. The report says Sense Space is an AMM built on top of Balancer V2, implements the "yieldspace invariant" (the particular formula it uses to price trades), and is the central market for trading Principal Tokens (PTs) and Yield Tokens (YTs). Those two token types are the instruments the yield-stripping application produces; you can think of them as two halves of a yield-bearing asset that can be traded separately.

What Balancer and its vault are

Balancer is described as an automated portfolio manager, liquidity provider and price sensor. In plain terms, it is another trading system that holds pools of tokens and lets people swap between them. Its central component is the Balancer vault: a single contract that holds the tokens and handles swaps on behalf of many different pools.

When someone asks the Balancer vault to swap tokens in a particular pool, the vault does not do all the maths itself. It calls back into that pool's own contract, asking it to work out how many tokens should come out. This kind of "call back and ask" is what the report calls a callback. The function the vault calls is named onSwap().

What an oracle is

An oracle is a program that supplies outside information, usually a price, to a smart contract. Other contracts read from the oracle instead of working out prices themselves. If an attacker can write into the oracle, every contract that trusts it is fooled. That is the heart of this story.

The specific contracts

  • The Balancer vault, which is the legitimate caller of the pool's callback functions.
  • The Space AMM pool contract, which holds the oracle state and exposes onSwap(), onJoin() and onExit(). onJoin() is called when someone adds tokens to the pool, onExit() when someone takes tokens out, and onSwap() when someone trades.
  • The Sense Fuse pools at Rari Capital, which relied on the Space AMM contract oracle. These are lending pools: places where users deposit assets to lend and borrow against collateral. They read the price from the Sense oracle to decide how much can be borrowed and when a loan is unsafe.
  • The onlyVault() modifier on the pool. A modifier is a small guard attached to a function that runs before the function body and can refuse the call. onlyVault() is meant to allow calls only from the Balancer vault.

No special accounts, tooling or software versions are described in the report. The only precondition for the bug is that someone other than the vault can reach onSwap() with data they control.

How the swap callback works

When the Balancer vault handles a swap between tokens, it calls the onSwap() function on the Space AMM pool to determine the output amounts, using all token balances. That callback does more than price the trade: it also updates the oracle information stored on the pool contract, alongside the reserve information supplied by the Balancer vault.

From the original on medium.com

That second job is the important one. A function that only calculated a number would be harmless to call. A function that writes a price into permanent storage is a different matter entirely, because everything downstream will believe whatever it wrote.

Finding the bug

The whitehat, Reptile71590, identified that the onSwap() function on the Space AMM pool contract did not validate whether the caller was the Balancer vault.

The pool already had an onlyVault() modifier, which allows calls from the Balancer vault contract, and it was applied to the onJoin() and onExit() functions. It was not applied to onSwap().

That asymmetry is what made the callback interesting. The same function that prices swaps is also the path by which oracle data is written into the pool's state, so an unauthenticated caller (someone with no right to call it) could reach a state-changing oracle update. "State" here means the data the contract keeps stored between calls; changing it is what makes a bug matter.

A useful everyday comparison: a building has a reception desk that is supposed to serve only staff, and the guard checks badges at two of the three doors. The third door has the same guard post but nobody standing at it. Anyone can walk through that door and change the noticeboard inside.

Exploitation, step by step

Step 1: call onSwap() directly

Because there was no caller check, a malicious actor could call the onSwap() function on the pool directly, bypassing the Balancer vault entirely. Normally the vault is the only thing that ever calls this function, so the pool's code never expected a stranger to arrive. Calling a public function on a smart contract is not exotic: anyone with a wallet and the function's details can send it a message.

Step 2: supply arbitrary price and reserve data

The attacker could provide any price and reserves information to the oracle through that call. "Arbitrary" means chosen freely by the attacker, not checked against reality. The reserves are the amounts of each token the pool is supposed to hold; the price is what the oracle will report to anyone who asks.

Step 3: let the oracle persist it

The oracle would then set that supplied information into the state. From that point the oracle would read out as having that price recorded arbitrarily far into the past or future. A timestamp is simply the date and time recorded with a piece of data. Lending systems often care about how fresh a price is, so being able to set the clock is as dangerous as being able to set the number.

From the original on medium.com

In short, anyone could call onSwap() with attacker-controlled request data to manipulate the stored oracle data.

Why it happened

The mistake is a missing authorisation check on a state-changing callback. Authorisation means deciding whether the caller is allowed to do the thing they are asking for; authentication would be proving who they are. Here the pool never asked the question at all.

The onlyVault() modifier existed and was correctly placed on onJoin() and onExit(), but the developer omitted it on onSwap(). Since onSwap() both computes output amounts and writes oracle and reserve information into the pool's storage, the omission turned a vault-only callback into a publicly writable oracle update path. The existing defence, the modifier itself, did not stop the attack because it was never attached to the vulnerable function.

This is a common pattern in real bugs: the protection is present and correct, just not everywhere it needs to be. The guard at two doors does nothing for the third.

What could have happened

The immediate consequence was that a malicious actor could update the oracle data of the Space AMM contract with arbitrary prices and timestamps.

The report states that there were no assets at risk at the time, because the pools relying on the Space AMM oracle were paused by the Sense team upon disclosure. Pausing a pool means switching it off so nobody can deposit, borrow or trade through it while the problem is fixed.

Had those pools been live, the impact would have been severe. The Sense Fuse pools at Rari Capital relied on the Space AMM contract oracle, so manipulating the oracle price and timestamp could have allowed an attacker to steal any borrowable collateral provided to the Rari pools, and to steal assets of users that had been borrowed against. The report describes this as liquidation of collateral and taking a bad loan, all achieved by manipulating the oracle price and timestamp.

Two of those terms are worth spelling out. Collateral is an asset a borrower pledges so the lender can take it if the loan is not repaid. Liquidation is the lender seizing that collateral, usually because the loan has become unsafe. If you can set the price the lending pool believes, you can make a healthy loan look unsafe and trigger a liquidation on your own terms, or make an unsafe loan look safe and walk away with the borrowed funds.

Sense paid the full $50,000 bounty to the whitehat and has already deployed a fix to the mainnet.

The fix

The Sense team fixed the vulnerability by adding a condition so that the oracle update of the pool is performed only if the caller is the Balancer vault. The fix adds a condition so the oracle update happens only if the caller is the Balancer vault.

From the original on medium.com

In everyday terms: the guard was moved to stand at the third door as well. The function may still be reachable, but the oracle write inside it now refuses to happen unless the vault is the one asking.

What to look for in similar code

These are the checks a beginner can carry into other code after reading this report.

  • Callback functions on AMM pools built on Balancer V2. List every function the vault is expected to call (onSwap, onJoin, onExit and any others the pool exposes) and check each one for a caller check. A positive result is a function that writes to storage, including oracle or reserve state, and can be invoked successfully from an address other than the vault.
  • Modifier coverage audits. Where a codebase defines a guard such as onlyVault(), list every function that changes the guarded state and confirm the modifier is present on each. A positive result is a state-changing function that lacks the modifier while its siblings have it.
  • Oracle write paths reachable from pricing callbacks. Trace what a swap callback writes, not just what it returns. A positive result is a callback that accepts caller-supplied price, reserve or timestamp values and saves them without checking who the caller is.
  • Timestamp handling in oracle updates. Check whether a caller can influence the timestamp recorded with a price. A positive result is an oracle entry that can be placed arbitrarily far in the past or future, which is what makes stale or future-dated prices exploitable by downstream lending markets.
  • Downstream consumers of the oracle. Identify lending pools that read the oracle, as the Rari Fuse pools did, and assess what a manipulated price and timestamp would allow: borrowing against inflated collateral, triggering liquidations, or taking undercollateralised loans.

Glossary

  • AMM (Automated Market Maker): a smart contract that lets people trade tokens using a formula instead of matching buyers and sellers by hand.
  • Arbitrary: chosen freely by whoever is supplying it, with no check against reality.
  • Authorisation: deciding whether a caller is allowed to perform an action.
  • Balancer: a trading system that holds pools of tokens and lets people swap between them; described in the report as an automated portfolio manager, liquidity provider and price sensor.
  • Balancer vault: the central Balancer contract that holds tokens and handles swaps on behalf of many pools, and the legitimate caller of the pool's callbacks.
  • Blockchain: a shared record book kept by many computers that cannot be quietly edited after the fact.
  • Bug bounty: a programme that pays people for responsibly reporting security problems in software.
  • Callback: a function that one contract calls on another to ask it to do part of the work, here the vault calling the pool.
  • Collateral: an asset pledged by a borrower that the lender can seize if the loan is not repaid.
  • DeFi (decentralised finance): financial services built on blockchains rather than run by banks.
  • Fuse pools (Rari Capital): lending pools that read the Sense Space oracle to decide borrowing limits and loan safety.
  • Liquidation: the lender seizing collateral, usually because a loan has become unsafe.
  • Mainnet: the real, production version of a blockchain, as opposed to a test network.
  • Modifier: a small guard attached to a function that runs before it and can refuse the call, such as onlyVault().
  • onExit(): the pool function called when tokens are taken out of the pool.
  • onJoin(): the pool function called when tokens are added to the pool.
  • onSwap(): the pool function the Balancer vault calls to price a trade; in this report it also wrote oracle and reserve data into storage.
  • onlyVault(): the modifier intended to allow calls only from the Balancer vault.
  • Oracle: a program that supplies outside information, usually a price, to smart contracts that read it.
  • Permissionless: usable by anyone without needing an account or approval.
  • Principal Tokens (PTs) and Yield Tokens (YTs): the two token types traded on Sense Space, produced by the yield-stripping application.
  • Reserves: the amounts of each token a pool holds.
  • Smart contract: a small program that lives on a blockchain and runs according to its public code.
  • State: the data a contract keeps stored between calls; changing it is what makes a bug matter.
  • Timestamp: the date and time recorded alongside a piece of data, used by lending systems to judge how fresh a price is.
  • Whitehat: a security researcher who reports bugs to the people who can fix them instead of exploiting them.
  • Yield: the return an asset earns over time.
  • Yield-stripping: the first application built on Sense, letting users lend at a fixed rate and bet on the future yield of yield-bearing assets.
  • Yieldspace invariant: the particular formula Sense Space uses to price trades.

Similar reports

View all

Same bug class and techniques, clearest first.

Broken access control

The lesson behind this report.

A user can do something their role should not allow: reach an admin function, act on a feature they have not paid for, or skip a permission check. IDOR is the special case where the object belongs to someone else.