Submitted by carlitox477, also found by minhquanym, gzeon, 9svR6w, Lambda, koxuan, KingNFT, cozzetti, rvierdiiev, and cccz
https://github.com/code-423n4/2022-12-caviar/blob/0212f9dc3b6a418803dbfacda0e340e059b8aae2/src/Pair.sol#L95
https://github.com/code-423n4/2022-12-caviar/blob/0212f9dc3b6a418803dbfacda0e340e059b8aae2/src/Pair.sol#L137
https://github.com/code-423n4/2022-12-caviar/blob/0212f9dc3b6a418803dbfacda0e340e059b8aae2/src/Pair.sol#L172
https://github.com/code-423n4/2022-12-caviar/blob/0212f9dc3b6a418803dbfacda0e340e059b8aae2/src/Pair.sol#L203
Current implementation of functions add, remove, buy and sell first transfer fractional tokens, and then base tokens.
If this base token is ERC777 (extension of ERC20), we can call this function without updating the base token balance, but updating the fractional token balance.
Allows to drain funds of a pairs which implements an ERC-777 token.
The buy quote is used to calculate the amount of fractional token that the user will receive, and it should be less/equal to maxInputAmount sent by parameter in order to achieve a successful execution of function buy.
Current buy quote can be mathematically expressed as: $\frac{outputAmount \times 1000 \times baseTokenReserves}{fractionalTokenReserves - outPutAmount} \times 997$.
Then, about sales
Current sellQuote function can be expressed mathematically as:
$inputAmount = \frac{inputAmount \times 997 \times baseTokenReserves}{fractionalTokenReserves \times 1000 + inputAmountWithFee}$
Then we can think next scenario to drain a pair which use an ERC-777 token as base token:
A simulation of this attack can be visualized in next table
The result of this operation is that the attaker/malicious contract has 350 FRT, while BT777 reserve still has 1000 and FRT reserve has 650 tokens. The success execution needs that the attacker pays 442 BT777 eventually.
To do this, the last operation of the malicious contract is calling sell function
The result is that the attacker now controls 536 BT777, the attacker use this balance to pay the debt of 442 BT77, with a profit of 94 BT77 tokens.
Add openzeppelin nonReentrant modifier to mentioned functions, or state clear in the documentation that this protocol should not be used with ERC777 tokens.
outdoteth (Caviar) acknowledged and commented:
