[web3] Sewer Pass Flash-claim Vulnerability & Fix. A bug in the Sewer Pass claiming contract… | by BendDAO | Feb, 2023 | Medium
The flash claim contract checked the airdrop contract against a whitelist but did not validate the airdrop token address, allowing an attacker to supply a malicious token contract. This let the NFT owner withdraw staked ApeCoin without unstaking, though the attack was limited to the NFT owner and often economically unviable.
medium.com
Published on medium.com
Nft
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.
Context
BendDAO runs a lending protocol for NFTs. One of its features is Flash Claim: a holder of a boundNFT can use the underlying NFT to claim an airdrop, such as a Sewer Pass, without unstaking that NFT from Ape Staking. The claim happens inside a flash loan: the registry lends the NFT to a receiver contract, the receiver calls the airdrop contract, and the NFT comes back in the same transaction.
The Sewer Pass Flash Claim had been live for four weeks when, on 11 February 2023, the team received a critical vulnerability report (ID 16841) against the Flash Claim contracts. The report describes a path that would let BAYC and MAYC holders withdraw the staked ApeCoin on the paired staking without unstaking, which the service design does not allow: in normal operation ApeCoin can only be withdrawn by unstaking. The deposited ETH and NFTs in the protocol were not affected and kept running safely.
Setup
The attack can only be performed by the NFT owner, who needs a flash claim receiver. The report's summary of the attack path lists the preconditions:
- Create flash claim receiver;
- Deploy malicious contract;
- Borrow ETH using BAYC;
- Stake BAYC with paired ApeCoin;
- Do Flash claim using malicious contract;
The report does not name specific contract versions or tooling beyond the contract names below.
Finding it
The researcher looked at the FlashClaimRegistry contract and its call flow, then went inside the registry and the receiver contract. The registry's entry point is flashLoan, which takes the NFT asset, a list of token IDs and an opaque params blob:
contract UserFlashclaimRegistryV3 { function flashLoan( address nftAsset, uint256[] calldata nftTokenIds, bytes calldata params ) public override nonReentrant {
Before lending, the registry validates the airdrop contract named in params:
// check airdrop contract MUST in the whitelist _checkValidAirdropContract(nftAsset, params); // check owner and set locking flag // ... // doing flash loan IBNFT(bnftProxy).flashLoan(receiverAddress, nftTokenIds, params); // clear locking flag // ... } function _checkValidAirdropContract(address nftAsset, bytes calldata params) internal view { // decode parameters (, , , address airdropContract, , ) = abi.decode( params, (uint256[], address[], uint256[], address, bytes, uint256) ); require(isAirdropContractInWhiteList(nftAsset, airdropContract) == true, "invalid airdrop contract"); }}
The params blob is decoded as (uint256[], address[], uint256[], address, bytes, uint256). The fourth field, airdropContract, is checked against a per-asset whitelist. The second field, airdropTokenAddresses, is not checked at all.
On the receiver side, executeOperation decodes the same blob and calls the whitelisted airdrop contract with the caller-supplied calldata and ETH value:
contract AirdropFlashLoanReceiverV3 { function executeOperation( address nftAsset, uint256[] calldata nftTokenIds, address initiator, address operator, bytes calldata params ) external override returns (bool) { // ... // decode parameters ( vars.airdropTokenTypes, vars.airdropTokenAddresses, vars.airdropTokenIds, vars.airdropContract, vars.airdropParams, vars.ethValue ) = abi.decode(params, (uint256[], address[], uint256[], address, bytes, uint256)); // call project aidrop contract AddressUpgradeable.functionCallWithValue( vars.airdropContract, vars.airdropParams, vars.ethValue, "call airdrop method failed" ); vars.airdropKeyHash = getClaimKeyHash(targetOwner, nftAsset, nftTokenIds, params); airdropClaimRecords[vars.airdropKeyHash] = true; // transfer airdrop tokens to borrower for (uint256 typeIndex = 0; typeIndex < vars.airdropTokenTypes.length; typeIndex++) { require(vars.airdropTokenAddresses[typeIndex] != address(0), "invalid airdrop token address"); if (vars.airdropTokenTypes[typeIndex] == 1) { // ERC20 } else if (vars.airdropTokenTypes[typeIndex] == 2) { // ERC721 with Enumerate } else if (vars.airdropTokenTypes[typeIndex] == 3) { // ERC1155 } else if (vars.airdropTokenTypes[typeIndex] == 4) { // ERC721 without Enumerate but can know the droped token id // !!! The attack will occur in following code !!! IERC721EnumerableUpgradeable(vars.airdropTokenAddresses[typeIndex]).safeTransferFrom( address(this), targetOwner, vars.airdropTokenIds[typeIndex] ); } else if (vars.airdropTokenTypes[typeIndex] == 5) { // ERC721 without Enumerate and can not know the droped token id } } return true; }function approveERC721( address token, address operator, uint256 tokenId ) external nonReentrant onlyOwner { IERC721Upgradeable(token).approve(operator, tokenId); emit ApproveERC721(token, operator, tokenId); }}
After the airdrop call, the receiver loops over the declared airdrop tokens and moves them to the borrower. For type 4 (ERC721 without Enumerate where the dropped token ID is known) it calls safeTransferFrom on the address taken from airdropTokenAddresses. That address is attacker-controlled, so the receiver will call safeTransferFrom on an arbitrary contract while it still holds the borrowed NFT. The report marks this line as the point where the attack occurs.
Exploitation
Step 1: deploy a malicious token contract
The attacker deploys a contract that implements safeTransferFrom with the signature the receiver expects. The report's example:
contract MalicousContract { function safeTransferFrom( address, address, uint256 ) public { collection.safeTransferFrom(msg.sender, address(this), tokenId);
apeStaking.withdrawBAYC(nfts, address(this)); //apeStaking.withdrawMAYC(nfts, address(this)); //transfer NFT back to receiver collection.safeTransferFrom(address(this), msg.sender, nftId); }}
When the receiver calls this function, the malicious contract pulls the BAYC or MAYC out of the receiver into itself, calls the ApeCoinStaking contract's withdraw function (withdrawBAYC, or withdrawMAYC for the other collection), and then transfers the NFT back to the receiver so the flash loan can complete.
Step 2: approve the NFT to the malicious contract
The attacker approves the NFT token to the malicious token contract, so the contract can move the NFT when it is called.
Step 3: call flashLoan with the malicious contract as a token address
The malicious contract's address is supplied as airdropTokenAddresses in params when the attacker calls flashLoan. The airdropContract field still points at a whitelisted airdrop contract, so _checkValidAirdropContract passes. The receiver then calls safeTransferFrom on the malicious contract, which triggers the withdrawal described above.
Root cause
The registry validates airdropContract against the whitelist but does not validate airdropTokenAddresses. The receiver therefore trusts an arbitrary address supplied by the external caller and calls safeTransferFrom on it while holding the borrowed NFT. Because the call happens inside the flash loan, the attacker's contract can use the borrowed NFT to reach the staking contract and withdraw the paired ApeCoin without an unstake, which the service design does not permit.
The report's own recommendation states the general lesson: the protocol should never trust and directly call an arbitrary contract inputted by an external caller.
Impact
The report is explicit about the limits:
- Only the NFT owner can trigger the flash loan and make the attack; there is no way for other users to perform it.
- NFTs solo staked with their own ApeCoin cannot be used for the attack.
- For NFTs paired with other users' ApeCoin, if the NFT owner makes the attack, the attacker will fail to perform an unstake. The attack cannot unstake the NFT unless the attacker returns the ApeCoin.
- The funds at risk should be calculated using each NFT's fair market value rather than the collection floor price, compared with the borrowed ETH and paired ApeCoin. According to NFT marketplace listing prices, for most staked NFTs the fair market value is much higher than the floor price, so the attack is not economically viable for NFT holders.
All deposited ETH and NFTs in the protocol were unaffected.
Fix
The immediate fix was to remove the Sewer Pass claim contract from the whitelist in the flash claim registry, so no user could execute the registry's flashLoan function. The next step was to upgrade the contract so that the new contract also checks that the airdrop token contract is on the whitelist. As a precaution, the team committed to ensuring that future feature updates never trust and directly call an arbitrary contract inputted by an external caller.
Timeline:
- 11 February: DevTeam was notified of the issue.
- 11 February: the issue was fixed.
- 13 February: $50,000 was sent to the white hat according to the bounty rule.
Variants to test
- Unvalidated token address lists in flash-loan receivers. Look for receiver contracts that decode a caller-supplied list of token addresses and then call transfer functions on each entry. A positive result is a receiver that calls
safeTransferFromortransferFromon an address the caller controls while it holds borrowed assets. - Whitelist checks that cover only one field of a decoded struct. Where a registry decodes a parameter blob and checks one address against a whitelist, check whether sibling fields (token addresses, operators, calldata) are also constrained. A positive result is a whitelisted call whose side effects reach an attacker-controlled contract.
- Callback hooks invoked during a flash loan. Any external call made by the receiver before the loan is returned is a candidate. A positive result is a callback that lets the attacker move the borrowed NFT into a contract that can interact with a staking or reward contract.
- Staking withdrawals reachable from a borrowed NFT. Test whether a contract holding a borrowed NFT can call the staking contract's withdraw functions and keep the proceeds while returning the NFT in the same transaction. A positive result is a withdrawal that succeeds without a corresponding unstake by the legitimate staker.
What happened, in plain words
BendDAO is a service that lets people borrow and lend money against NFTs. An NFT (non-fungible token) is a unique digital item recorded on a blockchain, for example a picture of a cartoon ape. BendDAO also offered a feature called Flash Claim, which let the owner of a staked NFT claim a free reward (an airdrop) without taking the NFT out of staking first.
On 11 February 2023, four weeks after the Sewer Pass Flash Claim feature went live, the team received a critical vulnerability report, numbered 16841, about the Flash Claim contracts connected to the Sewer Pass. The report described a way for holders of BAYC and MAYC NFTs (two collections of cartoon apes) to pull out the ApeCoin that was staked alongside their NFT, without going through the normal unstaking step. In normal use, ApeCoin can only be withdrawn by unstaking, so this was not supposed to be possible. The ETH and NFTs that people had deposited into the protocol were not affected and kept running safely.
This article walks through the report from the beginning, explaining each idea as it comes up.
Background: the pieces involved
Before the bug makes sense, you need a picture of the moving parts. None of these are deep technical ideas; they are mostly names for things you already know from ordinary websites.
- Blockchain and smart contracts. A blockchain is a shared record book that many computers keep copies of. A smart contract is a small program stored on that blockchain. Once deployed, anyone can call it, and it runs exactly as written. Think of it as a vending machine: you put in a request, it follows its own rules, and nobody can quietly change those rules afterwards.
- NFT. A unique digital item on the blockchain. Each one has an owner, and ownership can be transferred from one address to another.
- Address. A blockchain account identifier, similar to a bank account number. It can belong to a person or to a contract.
- Token. A digital asset on the blockchain. Some tokens are fungible (each unit is the same, like money); others are NFTs (each one is unique).
- ApeCoin. The token used in the Ape staking system. Holders can stake it, meaning they lock it up to earn rewards.
- Staking. Locking an asset in a contract for a period. To get it back you normally unstake, which is the official exit step.
- BAYC and MAYC. Two NFT collections of cartoon apes. Their owners can pair their NFT with ApeCoin in a staking arrangement.
- boundNFT. A representation of an NFT that has been deposited into BendDAO. The protocol holds the real NFT, and the depositor holds a boundNFT that stands in for it.
- Flash loan. A loan that must be borrowed and repaid within a single transaction. A transaction is one bundle of actions on the blockchain: either all of it happens, or none of it does. Because the loan is repaid in the same bundle, no collateral is needed. Think of a friend lending you a rare book for ten seconds so you can photocopy a page, as long as the book is back in their hands before the ten seconds end.
- Airdrop. A free distribution of tokens to certain holders. Here, the Sewer Pass is the reward being claimed.
- Whitelist. A list of addresses that are explicitly allowed. Anything not on the list is refused.
- Registry and receiver. The registry is the contract users call to start a flash claim. The receiver is a separate contract that actually performs the claim while it temporarily holds the NFT.
params. A blob of data passed into a function. It is a bundle of values packed together; the contract unpacks (decodes) it to read the individual fields.- Calldata. The raw data attached to a call to a contract: which function to run and with what arguments.
safeTransferFrom. A standard function on NFT contracts for moving a token from one address to another. Because it is a standard name, any contract can implement a function with that name and be called as if it were an NFT contract.
What Flash Claim does
Through Flash Claim, a boundNFT holder can use their NFT to claim the Sewer Pass without unstaking it from Ape Staking. The claim happens inside a flash loan: the registry lends the NFT to a receiver contract, the receiver calls the airdrop contract, and the NFT comes back in the same transaction. The user gets the reward, and the NFT never leaves the staking arrangement for longer than that one bundle of actions.
The setup the attacker needs
The attack can only be performed by the NFT owner, who needs a flash claim receiver. The report summarises the attack path as five preconditions:
- Create flash claim receiver;
- Deploy malicious contract;
- Borrow ETH using BAYC;
- Stake BAYC with paired ApeCoin;
- Do Flash claim using malicious contract;
Why each step: the receiver is the contract that will temporarily hold the NFT during the flash loan. The malicious contract is the trap that will be called at the wrong moment. Staking the BAYC with paired ApeCoin creates the pot of ApeCoin that the attack is aimed at. The flash claim is the trigger that makes the protocol hand the NFT to the receiver and then call out to addresses the attacker chose.
The report does not name specific contract versions or tooling beyond the contract names below.
Finding it
The researcher looked at the FlashClaimRegistry contract and its call flow, then went inside the registry and the receiver contract. The registry's entry point is flashLoan, which takes the NFT asset, a list of token IDs and an opaque params blob:
contract UserFlashclaimRegistryV3 { function flashLoan( address nftAsset, uint256[] calldata nftTokenIds, bytes calldata params ) public override nonReentrant {
Line by line:
contract UserFlashclaimRegistryV3starts the definition of the registry contract. The name tells you this is the third version of the user-facing flash claim registry.function flashLoan(begins a function calledflashLoan. This is the door users knock on to start a flash claim.address nftAssetis which NFT collection is involved, for example BAYC.uint256[] calldata nftTokenIdsis a list of token IDs, meaning which specific NFTs in that collection. The square brackets mean a list.bytes calldata paramsis the opaque blob mentioned above. The registry decodes it to check the airdrop contract, then passes it along.public override nonReentrantdescribes who can call it and adds a guard.publicmeans anyone can call it.nonReentrantis a lock that stops the same function being entered again while it is still running, a common defence against certain looping attacks.
Before lending, the registry validates the airdrop contract named in params:
// check airdrop contract MUST in the whitelist _checkValidAirdropContract(nftAsset, params); // check owner and set locking flag // ... // doing flash loan IBNFT(bnftProxy).flashLoan(receiverAddress, nftTokenIds, params); // clear locking flag // ... } function _checkValidAirdropContract(address nftAsset, bytes calldata params) internal view { // decode parameters (, , , address airdropContract, , ) = abi.decode( params, (uint256[], address[], uint256[], address, bytes, uint256) ); require(isAirdropContractInWhiteList(nftAsset, airdropContract) == true, "invalid airdrop contract"); }}
Line by line:
// check airdrop contract MUST in the whitelistis a comment saying the next call enforces the whitelist._checkValidAirdropContract(nftAsset, params);runs that check, passing the asset and the blob.// check owner and set locking flagand the// ...lines are placeholders: the report is showing only the relevant parts, not every line of the function.IBNFT(bnftProxy).flashLoan(receiverAddress, nftTokenIds, params);is the actual lending step. It tells the boundNFT contract to lend the listed NFTs to the receiver, passing the same blob along.// clear locking flagand// ...are more placeholders for cleanup.function _checkValidAirdropContract(address nftAsset, bytes calldata params) internal view {defines the checking function.internalmeans only this contract can call it;viewmeans it only reads, it does not change anything.(, , , address airdropContract, , ) = abi.decode(unpacks the blob. The commas with nothing between them mean those positions are skipped. The fourth position is pulled out and namedairdropContract.params,is the blob being unpacked.(uint256[], address[], uint256[], address, bytes, uint256)is the shape of the blob: a list of numbers, a list of addresses, another list of numbers, one address, some bytes, and one number. The fourth item, the single address, is the airdrop contract.require(isAirdropContractInWhiteList(nftAsset, airdropContract) == true, "invalid airdrop contract");is the check itself. If the airdrop contract is not on the whitelist for this asset, the whole call stops with the messageinvalid airdrop contract.
The params blob is decoded as (uint256[], address[], uint256[], address, bytes, uint256). The fourth field, airdropContract, is checked against a per-asset whitelist. The second field, airdropTokenAddresses, is not checked at all. That second field is a list of addresses that the receiver will later treat as token contracts. Nothing in the registry confirms that those addresses are real, expected token contracts.
On the receiver side, executeOperation decodes the same blob and calls the whitelisted airdrop contract with the caller-supplied calldata and ETH value:
contract AirdropFlashLoanReceiverV3 { function executeOperation( address nftAsset, uint256[] calldata nftTokenIds, address initiator, address operator, bytes calldata params ) external override returns (bool) { // ... // decode parameters ( vars.airdropTokenTypes, vars.airdropTokenAddresses, vars.airdropTokenIds, vars.airdropContract, vars.airdropParams, vars.ethValue ) = abi.decode(params, (uint256[], address[], uint256[], address, bytes, uint256)); // call project aidrop contract AddressUpgradeable.functionCallWithValue( vars.airdropContract, vars.airdropParams, vars.ethValue, "call airdrop method failed" ); vars.airdropKeyHash = getClaimKeyHash(targetOwner, nftAsset, nftTokenIds, params); airdropClaimRecords[vars.airdropKeyHash] = true; // transfer airdrop tokens to borrower for (uint256 typeIndex = 0; typeIndex < vars.airdropTokenTypes.length; typeIndex++) { require(vars.airdropTokenAddresses[typeIndex] != address(0), "invalid airdrop token address"); if (vars.airdropTokenTypes[typeIndex] == 1) { // ERC20 } else if (vars.airdropTokenTypes[typeIndex] == 2) { // ERC721 with Enumerate } else if (vars.airdropTokenTypes[typeIndex] == 3) { // ERC1155 } else if (vars.airdropTokenTypes[typeIndex] == 4) { // ERC721 without Enumerate but can know the droped token id // !!! The attack will occur in following code !!! IERC721EnumerableUpgradeable(vars.airdropTokenAddresses[typeIndex]).safeTransferFrom( address(this), targetOwner, vars.airdropTokenIds[typeIndex] ); } else if (vars.airdropTokenTypes[typeIndex] == 5) { // ERC721 without Enumerate and can not know the droped token id } } return true; }function approveERC721( address token, address operator, uint256 tokenId ) external nonReentrant onlyOwner { IERC721Upgradeable(token).approve(operator, tokenId); emit ApproveERC721(token, operator, tokenId); }}
Line by line:
contract AirdropFlashLoanReceiverV3 {starts the receiver contract. This is the contract that holds the NFT during the flash loan.function executeOperation(is the function the registry calls on the receiver once the NFT has been lent.address nftAsset,uint256[] calldata nftTokenIds,address initiator,address operatorare context values: which collection, which token IDs, who started it, and who is acting.bytes calldata paramsis the same blob from the registry.external override returns (bool)means it can be called from outside, it implements an expected interface, and it declares a boolean return value.// ...is a placeholder for omitted code.(vars.airdropTokenTypes, vars.airdropTokenAddresses, vars.airdropTokenIds, vars.airdropContract, vars.airdropParams, vars.ethValue) = abi.decode(params, (uint256[], address[], uint256[], address, bytes, uint256));unpacks the blob into six named pieces. The second piece,vars.airdropTokenAddresses, is the unchecked list of addresses.AddressUpgradeable.functionCallWithValue(calls the airdrop contract, passing along the calldata and ETH value the caller supplied. The comment above it,// call project aidrop contract, says this is the legitimate claim step.vars.airdropKeyHash = getClaimKeyHash(targetOwner, nftAsset, nftTokenIds, params);computes a fingerprint for this claim.airdropClaimRecords[vars.airdropKeyHash] = true;records that the claim happened.for (uint256 typeIndex = 0; typeIndex < vars.airdropTokenTypes.length; typeIndex++) {starts a loop over every declared airdrop token. A loop is just doing the same steps for each item in a list.require(vars.airdropTokenAddresses[typeIndex] != address(0), "invalid airdrop token address");rejects the zero address, which is the blockchain equivalent of an empty field. It does not check anything else about the address.- The
ifandelse ifbranches handle different token types:1for ERC20 (fungible tokens),2for ERC721 with Enumerate (NFTs that can be listed),3for ERC1155 (multi-copy tokens),4for ERC721 without Enumerate where the dropped token ID is known, and5for ERC721 without Enumerate where the token ID is not known. - The comment
// !!! The attack will occur in following code !!!marks the dangerous branch. IERC721EnumerableUpgradeable(vars.airdropTokenAddresses[typeIndex]).safeTransferFrom(takes the address from the unchecked list and callssafeTransferFromon it, as if it were an NFT contract.address(this),is the receiver itself, the current holder of the borrowed NFT.targetOwner,is where the token is meant to go.vars.airdropTokenIds[typeIndex]is which token ID to move.return true;reports success.function approveERC721(address token, address operator, uint256 tokenId) external nonReentrant onlyOwner {is a separate helper that lets the owner approve someone else to move a specific NFT.onlyOwnerrestricts it to the contract owner.IERC721Upgradeable(token).approve(operator, tokenId);performs the approval.emit ApproveERC721(token, operator, tokenId);writes a log entry so the approval is visible on the blockchain.
After the airdrop call, the receiver loops over the declared airdrop tokens and moves them to the borrower. For type 4 (ERC721 without Enumerate where the dropped token ID is known) it calls safeTransferFrom on the address taken from airdropTokenAddresses. That address is attacker-controlled, so the receiver will call safeTransferFrom on an arbitrary contract while it still holds the borrowed NFT. The report marks this line as the point where the attack occurs.
Exploitation
Step 1: deploy a malicious token contract
The attacker deploys a contract that implements safeTransferFrom with the signature the receiver expects. The report's example:
contract MalicousContract { function safeTransferFrom( address, address, uint256 ) public { collection.safeTransferFrom(msg.sender, address(this), tokenId);
apeStaking.withdrawBAYC(nfts, address(this)); //apeStaking.withdrawMAYC(nfts, address(this)); //transfer NFT back to receiver collection.safeTransferFrom(address(this), msg.sender, nftId); }}
Line by line:
contract MalicousContract {starts the attacker's contract. The name is spelled that way in the report.function safeTransferFrom(address, address, uint256) public {defines a function with the same name and argument shape as the standard NFT transfer function. The three arguments are unnamed here, which is fine: the function only needs to match the shape so the receiver will call it.publicmeans anyone can call it.collection.safeTransferFrom(msg.sender, address(this), tokenId);moves the NFT from the caller (the receiver, which is holding the borrowed NFT) into the malicious contract.msg.senderis whoever called this function, andaddress(this)is the malicious contract itself.apeStaking.withdrawBAYC(nfts, address(this));calls the staking contract's withdraw function for BAYC, sending the withdrawn ApeCoin to the malicious contract.//apeStaking.withdrawMAYC(nfts, address(this));is the same call for the other collection, commented out in the example.//transfer NFT back to receiveris a comment explaining the next line.collection.safeTransferFrom(address(this), msg.sender, nftId);sends the NFT back to the receiver, so the flash loan can finish and be repaid.
When the receiver calls this function, the malicious contract pulls the BAYC or MAYC out of the receiver into itself, calls the ApeCoinStaking contract's withdraw function (withdrawBAYC, or withdrawMAYC for the other collection), and then transfers the NFT back to the receiver so the flash loan can complete. The withdrawal is the goal; returning the NFT is what keeps the whole transaction valid.
Step 2: approve the NFT to the malicious contract
The attacker approves the NFT token to the malicious token contract, so the contract can move the NFT when it is called. An approval is a permission slip recorded on the blockchain: it says a particular address may move a particular token.
Step 3: call flashLoan with the malicious contract as a token address
The malicious contract's address is supplied as airdropTokenAddresses in params when the attacker calls flashLoan. The airdropContract field still points at a whitelisted airdrop contract, so _checkValidAirdropContract passes. The receiver then calls safeTransferFrom on the malicious contract, which triggers the withdrawal described above.
This is the heart of the trick: the registry checks one field of the blob and ignores another. The attacker keeps the checked field honest and puts the trap in the unchecked field.
Root cause
The registry validates airdropContract against the whitelist but does not validate airdropTokenAddresses. The receiver therefore trusts an arbitrary address supplied by the external caller and calls safeTransferFrom on it while holding the borrowed NFT. Because the call happens inside the flash loan, the attacker's contract can use the borrowed NFT to reach the staking contract and withdraw the paired ApeCoin without an unstake, which the service design does not permit.
The report's own recommendation states the general lesson: the protocol should never trust and directly call an arbitrary contract inputted by an external caller.
A useful everyday comparison: a bank teller who checks the name on a withdrawal slip but not the account number written next to it. The name looks right, so the teller proceeds, and the money goes wherever the unchecked number points.
Impact
The report is explicit about the limits:
- Only the NFT owner can trigger the flash loan and make the attack; there is no way for other users to perform it.
- NFTs solo staked with their own ApeCoin cannot be used for the attack.
- For NFTs paired with other users' ApeCoin, if the NFT owner makes the attack, the attacker will fail to perform an unstake. The attack cannot unstake the NFT unless the attacker returns the ApeCoin.
- The funds at risk should be calculated using each NFT's fair market value rather than the collection floor price, compared with the borrowed ETH and paired ApeCoin. According to NFT marketplace listing prices, for most staked NFTs the fair market value is much higher than the floor price, so the attack is not economically viable for NFT holders.
All deposited ETH and NFTs in the protocol were unaffected.
Two terms in that list are worth spelling out. The floor price is the cheapest asking price for any NFT in a collection. The fair market value is what a particular NFT is realistically worth, which for a rare item can be far above the floor. The report's point is that for most staked NFTs the attack is not economically viable.
Fix
The immediate fix was to remove the Sewer Pass claim contract from the whitelist in the flash claim registry, so no user could execute the registry's flashLoan function. The next step was to upgrade the contract so that the new contract also checks that the airdrop token contract is on the whitelist. As a precaution, the team committed to ensuring that future feature updates never trust and directly call an arbitrary contract inputted by an external caller.
Timeline:
- 11 February: DevTeam was notified of the issue.
- 11 February: the issue was fixed.
- 13 February: $50,000 was sent to the white hat according to the bounty rule.
A white hat is a security researcher who finds and reports a flaw responsibly instead of exploiting it. A bug bounty is a programme that pays researchers for such reports.
Variants to test
These are patterns a security tester can look for in other projects, based on the same mistake:
- Unvalidated token address lists in flash-loan receivers. Look for receiver contracts that decode a caller-supplied list of token addresses and then call transfer functions on each entry. A positive result is a receiver that calls
safeTransferFromortransferFromon an address the caller controls while it holds borrowed assets. - Whitelist checks that cover only one field of a decoded struct. Where a registry decodes a parameter blob and checks one address against a whitelist, check whether sibling fields (token addresses, operators, calldata) are also constrained. A positive result is a whitelisted call whose side effects reach an attacker-controlled contract.
- Callback hooks invoked during a flash loan. Any external call made by the receiver before the loan is returned is a candidate. A positive result is a callback that lets the attacker move the borrowed NFT into a contract that can interact with a staking or reward contract.
- Staking withdrawals reachable from a borrowed NFT. Test whether a contract holding a borrowed NFT can call the staking contract's withdraw functions and keep the proceeds while returning the NFT in the same transaction. A positive result is a withdrawal that succeeds without a corresponding unstake by the legitimate staker.
Glossary
- Airdrop: a free distribution of tokens to a group of holders.
- ApeCoinStaking: the contract that holds staked ApeCoin and handles withdrawals.
- Approval: a recorded permission allowing one address to move a specific token owned by another.
- BAYC / MAYC: two NFT collections of cartoon apes whose owners can pair their NFT with ApeCoin in staking.
- Blockchain: a shared, replicated record book that many computers keep copies of.
- boundNFT: a token representing an NFT deposited into BendDAO; the protocol holds the real NFT.
- Bug bounty: a programme that pays researchers for responsibly reporting security flaws.
- Calldata: the raw data attached to a contract call, naming the function and its arguments.
- Callback: an external call a contract makes out to another contract during its own operation.
- Contract: a program stored on a blockchain that runs according to its own fixed rules.
- Decode: unpacking a blob of data into its individual fields.
- Deploy: publishing a contract to the blockchain so it can be called.
- ERC20: a standard for fungible tokens, where each unit is interchangeable.
- ERC721: a standard for NFTs, where each token is unique.
- ERC1155: a standard for tokens that can exist in multiple copies.
- ETH: the cryptocurrency used on the Ethereum blockchain.
- Fair market value: the realistic worth of a specific item, as opposed to the cheapest price in its collection.
- Flash Claim: BendDAO's feature for claiming an airdrop with a staked NFT without unstaking it.
- Flash loan: a loan borrowed and repaid within a single transaction, needing no collateral.
- Floor price: the cheapest asking price for any NFT in a collection.
- Fungible: interchangeable, where each unit is the same as any other.
flashLoan: the registry function users call to start a flash claim.executeOperation: the receiver function that performs the claim while holding the borrowed NFT.params: an opaque blob of data passed into a function and decoded inside it.safeTransferFrom: a standard NFT function for moving a token between addresses.nonReentrant: a guard that prevents a function being re-entered while it is still running.- NFT: a unique digital item on a blockchain with a single owner.
- Receiver: the contract that temporarily holds the NFT during a flash claim.
- Registry: the contract users call to start a flash claim.
- Sewer Pass: the reward being claimed in this feature.
- Smart contract: see contract.
- Staking: locking an asset in a contract, usually to earn rewards.
- Token: a digital asset on a blockchain, fungible or unique.
- Transaction: one bundle of blockchain actions that either all succeed or all fail.
- Unstake: the official step for withdrawing a staked asset.
- Vulnerability: a flaw in a system that lets it behave in a way its designers did not intend.
- White hat: a security researcher who reports flaws responsibly rather than exploiting them.
- Whitelist: a list of addresses explicitly allowed; anything else is refused.
- Withdraw: in this context, taking staked ApeCoin out of the staking contract.