Platform: Code4rena
Start Date: 08/06/2022
Pot Size: $115,000 USDC
Total HM: 26
Participants: 72
Period: 11 days
Judge: leastwood
Total Solo HM: 14
Id: 132
League: ETH
Rank: 7/72
Findings: 4
Award: $3,165.42
🌟 Selected for report: 1
🚀 Solo Findings: 1
🌟 Selected for report: xiaoming90
_swapAssetOut() performs one step approval for an arbitrary _assetIn before calling pool's swapExactOut(). As ERC20 that do not allow approval race condition prohibit setting approval to a new positive value when allowance is positive already, this call will fail if _assetIn happens to be such a token.
It can happen as _swapAssetOut has to deal with arbitrary tokens and swapping can produce leftover allowance for the next runs by not utilizing current amount fully.
Setting severity to medium as that situation will render _swapAssetOut and all the upstream functionality unavailable for such a tokens: all successive calls will be reverted until allowance be used up or reset.
_swapAssetOut() approves positive _amountIn
of _assetIn
in one step:
// perform the swap SafeERC20.safeApprove(IERC20(_assetIn), address(pool), _amountIn); amountIn = pool.swapExactOut(_amountOut, _assetIn, _assetOut, _maxIn); }
Some tokens do not let to approve new positive allowance from current positive allowance to protect against race condition when the allowance can be double spent, simply reverting any attempt to approve positive from positive:
https://github.com/d-xo/weird-erc20#approval-race-protections
For example current USDT contract, L205:
https://etherscan.io/address/0xdac17f958d2ee523a2206206994597c13d831ec7#code
The recommendation is to set approval to zero first, then to set it to _amountIn
.
It's the same as described in the another occurrence of the same issue in BridgeFacet:
#0 - jakekidd
2022-06-26T19:10:20Z
#1 - 0xleastwood
2022-08-13T22:46:11Z
While this issue does not exactly describe how bridge transfers are impacted, it does a great job of describing how the issue might arise.
🌟 Selected for report: hyh
2598.127 USDC - $2,598.13
_executePortalTransfer can introduce underlying token deficit by accounting for full underlying amount received from Aave unconditionally on what was actually withdrawn from Aave pool. Actual amount withdrawn is returned by IAavePool(s.aavePool).withdraw()
, but currently is not used.
Setting the severity to medium as this can end up with a situation of partial insolvency, when where are a surplus of atokens, but deficit of underlying tokens in the bridge, so bridge functionality can become unavailable as there will be not enough underlying tokens, which were used up in the previous operations when atokens wasn't converted to underlying fully and underlying tokens from other operations were used up instead without accounting. I.e. the system in this situation supposes that all atokens are in the form of underlying tokens while there will be some atokens left unconverted due to withdrawal being only partial.
Call sequence here is execute() -> _handleExecuteLiquidity() -> _executePortalTransfer().
BridgeFacet._executePortalTransfer() mints the atokens needed, then withdraws them from Aave pool, always accounting for the full withdrawal:
/** * @notice Uses Aave Portals to provide fast liquidity */ function _executePortalTransfer( bytes32 _transferId, uint256 _fastTransferAmount, address _local, address _router ) internal returns (uint256, address) { // Calculate local to adopted swap output if needed (uint256 userAmount, address adopted) = AssetLogic.calculateSwapFromLocalAssetIfNeeded(_local, _fastTransferAmount); IAavePool(s.aavePool).mintUnbacked(adopted, userAmount, address(this), AAVE_REFERRAL_CODE); // Improvement: Instead of withdrawing to address(this), withdraw directly to the user or executor to save 1 transfer IAavePool(s.aavePool).withdraw(adopted, userAmount, address(this)); // Store principle debt s.portalDebt[_transferId] = userAmount;
Aave pool's withdraw() returns the amount of underlying asset that was actually withdrawn:
https://github.com/aave/aave-v3-core/blob/master/contracts/protocol/pool/Pool.sol#L196-L217
If a particular lending pool has liquidity shortage at the moment, say all underlying is lent out, full withdrawal of the requested underlying token amount will not be possible.
Consider adjusting for the amount actually withdrawn. Also the buffer that stores minted but not yet used atoken amount, say aAmountStored, can be introduced.
For example:
+ uint256 amountNeeded = userAmount < aAmountStored ? 0 : userAmount - aAmountStored; - IAavePool(s.aavePool).mintUnbacked(adopted, userAmount, address(this), AAVE_REFERRAL_CODE); + if (amountNeeded > 0) { + IAavePool(s.aavePool).mintUnbacked(adopted, amountNeeded, address(this), AAVE_REFERRAL_CODE); + } // Improvement: Instead of withdrawing to address(this), withdraw directly to the user or executor to save 1 transfer - IAavePool(s.aavePool).withdraw(adopted, userAmount, address(this)); + uint256 amountWithdrawn = IAavePool(s.aavePool).withdraw(adopted, userAmount, address(this)); // Store principle debt - s.portalDebt[_transferId] = userAmount; + s.portalDebt[_transferId] = amountWithdrawn; // can't exceed userAmount + aAmountStored = (userAmount < aAmountStored ? aAmountStored : userAmount) - amountWithdrawn; // we used amountWithdrawn
#0 - jakekidd
2022-06-24T23:38:49Z
To clarify for this: We should check to make sure the full amount is withdrawn. If the full amount is not withdrawn (bc not available), revert. This way, the execute
call can be treated in our off-chain network the same way an execute
call using a router with insufficient funds would be treated.
#1 - jakekidd
2022-06-27T02:53:40Z
Fixed by https://github.com/connext/nxtp/commit/b99f9cf54b5d03029c6665776dc434d744758339
(Using the solution described in the above comment, not the exact code from the mitigation step above.)
#2 - 0xleastwood
2022-08-15T08:12:13Z
I agree that this improvement would provide better guarantees against insufficient unbacked funds from Aave's pools.
🌟 Selected for report: BowTiedWardens
Also found by: 0x1f8b, 0x29A, 0x52, 0xNazgul, 0xNineDec, 0xf15ers, 0xkatana, 0xmint, Chom, ElKu, Funen, IllIllI, JMukesh, Jujic, Kaiziron, Lambda, MiloTruck, Ruhum, SmartSek, SooYa, TerrierLover, TomJ, WatchPug, Waze, _Adam, asutorufos, auditor0517, bardamu, c3phas, catchup, cccz, ch13fd357r0y3r, cloudjunky, cmichel, cryptphi, csanuragjain, defsec, fatherOfBlocks, hansfriese, hyh, jayjonah8, joestakey, k, kenta, obtarian, oyc_109, robee, sach1r0, shenwilly, simon135, slywaters, sorrynotsorry, tintin, unforgiven, xiaoming90, zzzitron
141.8552 USDC - $141.86
Race condition issue isn't addressed, open TODO:
// TODO: Should we call approve(0) and approve(totalRepayAmount) instead? or with a try catch to not affect gas on all cases? // Example: https://github.com/aave/aave-v3-periphery/blob/ca184e5278bcbc10d28c3dbbc604041d7cfac50b/contracts/adapters/paraswap/ParaSwapRepayAdapter.sol#L138-L140 SafeERC20.safeIncreaseAllowance(IERC20(adopted), s.aavePool, totalRepayAmount);
Another TODO comment:
// TODO: do we need to keep this bytes32 details = action.detailsHash(); IBridgeToken(token).setDetailsHash(details);
Consider choosing and implementing the method to address the approval issue, i.e. either do two step 0 -> amount approval or try-catch, before release.
It's advised to remove TODO comments in either way from production version of the code.
_swapAsset() function description omits _slippageTol argument:
/** * @notice Swaps assetIn t assetOut using the stored stable swap or internal swap pool * @dev Will not swap if the asset passed in is the adopted asset * @param _canonicalId - The canonical token id * @param _assetIn - The address of the from asset * @param _assetOut - The address of the to asset * @param _amount - The amount of the local asset to swap * @return The amount of assetOut * @return The address of assetOut */ function _swapAsset( bytes32 _canonicalId, address _assetIn, address _assetOut, uint256 _amount, uint256 _slippageTol ) internal returns (uint256, address) {
Add the description, for example:
/** * @param _amount - The amount of the local asset to swap * @param _slippageTol - Slippage tolerance with LIQUIDITY_FEE_DENOMINATOR decimals * @return The amount of assetOut * @return The address of assetOut */
There is a typo and success return value is omitted:
/** * @notice Swaps assetIn t assetOut using the stored stable swap or internal swap pool * @dev Will not swap if the asset passed in is the adopted asset * @param _canonicalId - The canonical token id * @param _assetIn - The address of the from asset * @param _assetOut - The address of the to asset * @param _amountOut - The amount of the _assetOut to swap * @return The amount of assetIn * @return The address of assetOut */ function _swapAssetOut( bytes32 _canonicalId, address _assetIn, address _assetOut, uint256 _amountOut, uint256 _maxIn )
Consider updating to:
* @notice Swaps assetIn to assetOut using the stored stable swap or internal swap pool ... * @return Swap success flag * @return The amount of assetIn ...
Filtering on unindexed events is disabled, which makes it harder to programmatically use and analyse the system.
AssetFacet's events don't have any indices:
/** * @notice Emitted when the wrapper variable is updated * @param oldWrapper - The wrapper old value * @param newWrapper - The wrapper new value * @param caller - The account that called the function */ event WrapperUpdated(address oldWrapper, address newWrapper, address caller); /** * @notice Emitted when the tokenRegistry variable is updated * @param oldTokenRegistry - The tokenRegistry old value * @param newTokenRegistry - The tokenRegistry new value * @param caller - The account that called the function */ event TokenRegistryUpdated(address oldTokenRegistry, address newTokenRegistry, address caller); /** * @notice Emitted when a new stable-swap AMM is added for the local <> adopted token * @param canonicalId - The canonical identifier of the token the local <> adopted AMM is for * @param domain - The domain of the canonical token for the local <> adopted amm * @param swapPool - The address of the AMM * @param caller - The account that called the function */ event StableSwapAdded(bytes32 canonicalId, uint32 domain, address swapPool, address caller); /** * @notice Emitted when a new asset is added * @param canonicalId - The canonical identifier of the token the local <> adopted AMM is for * @param domain - The domain of the canonical token for the local <> adopted amm * @param adoptedAsset - The address of the adopted (user-expected) asset * @param supportedAsset - The address of the whitelisted asset. If the native asset is to be whitelisted, * the address of the wrapped version will be stored * @param caller - The account that called the function */ event AssetAdded(bytes32 canonicalId, uint32 domain, address adoptedAsset, address supportedAsset, address caller); /** * @notice Emitted when an asset is removed from whitelists * @param canonicalId - The canonical identifier of the token removed * @param caller - The account that called the function */ event AssetRemoved(bytes32 canonicalId, address caller);
Consider adding indexes to ids and addresses in the all important events to improve their usability
#0 - jakekidd
2022-07-02T01:11:34Z
incomplete function descriptors are not low risk, should be considered QA only here
TODOs have been resolved/patched
🌟 Selected for report: IllIllI
Also found by: 0x1f8b, 0x29A, 0xKitsune, 0xNazgul, 0xf15ers, 0xkatana, 0xmint, BowTiedWardens, ElKu, Fitraldys, Funen, Kaiziron, Lambda, Metatron, MiloTruck, Randyyy, Ruhum, SmartSek, TomJ, Tomio, UnusualTurtle, Waze, _Adam, apostle0x01, asutorufos, c3phas, catchup, csanuragjain, defsec, fatherOfBlocks, hansfriese, hyh, ignacio, joestakey, k, kaden, nahnah, oyc_109, rfa, robee, sach1r0, simon135, slywaters
84.4973 USDC - $84.50
details is used only when !s.tokenRegistry.isLocalOrigin(token) holds:
bytes32 details = action.detailsHash(); // if the token is of remote origin, mint the tokens. will either // - be credited to router (fast liquidity) // - be reserved for execution (slow liquidity) if (!s.tokenRegistry.isLocalOrigin(token)) { IBridgeToken(token).mint(address(this), amount); // Tell the token what its detailsHash is IBridgeToken(token).setDetailsHash(details); } // NOTE: if the token is of local origin, it means it was escrowed // in this contract at xcall // mark the transfer as reconciled s.reconciledTransfers[transferId] = true; return (amount, token, transferId); }
Move into the if
scope:
// if the token is of remote origin, mint the tokens. will either // - be credited to router (fast liquidity) // - be reserved for execution (slow liquidity) if (!s.tokenRegistry.isLocalOrigin(token)) { bytes32 details = action.detailsHash(); IBridgeToken(token).mint(address(this), amount); // Tell the token what its detailsHash is IBridgeToken(token).setDetailsHash(details); }