Submitted by cccz.
openPosition creates a leveraged position for the user based on initMargin and leverage, and in _borrowLimit, it calculates the number of borrowing loops needed to reach the desired amount.
For example, if initMargin = 1e18 and leverage = 2, then _desiredAmount = 2e18. If the collateral factor is 0.7, the users position after the first borrowing is 1e18 + 1e18 * 0.7 = 1.7e18, and the users position after the second borrowing is 1e18 + 1e18 * 0.7 + 1e18 * 0.7 * 0.7 = 2.19e18.
For the excess of 0.19e18, _lastBorrow is used as the percentage of the last borrow. It should be noted that when _lastBorrow = 0, it means that the percentage of this borrowing is 100%.
Although the long leverage must be greater than 1e18, the user can make the long leverage = 1e18+1 to make the long leverage small. But in this case, the loss of precision in the calculation will cause the user to have a higher leverage than expected.
Consider the following scenario:
The collateral factor of WBTC is 0.7. Alice provides 4e8 WBTC and 1e18+1 long leverage to call the buyAllAmountWithLeverage function.
Since wmul is rounded rather than rounded up, the _desiredAmount calculated in _borrowLimit is equal to wmul(4e8,1e18+1) = 4e8.
After that, since _borrowDelta == 0, _borrowLimit returns limit == 1 and _lastBorrow == 0.
Then in openPosition, since _lastBorrow = 0, borrowing will be done so that Alices position reaches 4e8+4e8 * 0.7 = 6.8 WBTC, at which point Alices leverage is 1.7e18, much larger than Alices expectations, too high leverage will increase the risk of Alice is liquidated.
The POC and output are as follows. It can be seen that the borrowed amount of 1e18+1 is greater than 1.25e18 and 1.337e18, and the actual leverage of 1e18+1 is 1.7e18.
https://github.com/code-423n4/2023-04-rubicon/blob/511636d889742296a54392875a35e4c0c4727bb7/contracts/utilities/poolsUtility/Position.sol#L526-L583
Hardhat
Consider rounding up in _borrowLimit when calculating _desiredAmount. Or consider not borrowing when _lastBorrow = 0 and modifying the logic of the rest of the code.
daoio (Rubicon) disagreed with severity and commented:
HickupHH3 (judge) commented:
