Potential infinite loop in _borrowLimit function
The _borrowLimit function in the Position contract uses a while loop that can iterate an excessive number of times when the collateral factor is low, potentially causing the openPosition function to become unresponsive or fail. An attacker could exploit this to disrupt the system's performance and usability.
Submitted by bytes032, also found by 0xPkhatri, Udsen, thekmj, anodaram and volodya.
https://github.com/code-423n4/2023-04-rubicon/blob/511636d889742296a54392875a35e4c0c4727bb7/contracts/utilities/poolsUtility/Position.sol#L526-L542 https://github.com/code-423n4/2023-04-rubicon/blob/511636d889742296a54392875a35e4c0c4727bb7/contracts/utilities/poolsUtility/Position.sol#L158-L159
The infinite loop vulnerability could cause the openPosition functionality to become unresponsive or fail, negatively affecting the performance and usability of the whole system.
Proof of Concept
The _borrowLimit function is an internal view function used by openPosition that calculates the maximum number of borrowing loops allowed for a given asset and leverage, taking into account the collateral factor and any previously supplied collateral. It returns the calculated borrowing limit and the amount required to borrow in the last loop to avoid exceeding the desired amount.
The function works as follows:
-
Retrieve the collateral factor for the given
_bathTokenfrom thecomptrollercontract. -
Calculate the desired amount of the asset to borrow based on the given
_assetAmountand_leverage. -
Determine if collateral was already supplied by checking the balance of the
_bathTokenin the contract. -
Initialize a
whileloop that continues until the_assetAmountis less than or equal to the desired amount. -
In each loop iteration:
-
Calculate the amount that can be borrowed in the current loop
_loopBorrowedbased on the collateral factor and any previously supplied collateral. -
Update the total asset amount in the position by adding the borrowed amount from the current loop.
-
Check if the updated asset amount has reached or exceeded the desired amount:
- If it has, calculate the borrowing amount required in the last loop to not exceed the desired amount and increment the borrowing limit.
- If the asset amount perfectly matches the desired amount, increment the borrowing limit.
- In other cases, increment the borrowing limit and proceed to the next iteration.
-
The calculations for the desiredAmount and the _loopBorrowed are performed by using the wmul function.
wmul is designed to multiply two fixed-point numbers (with 18 decimals precision) and return the result as another fixed-point number. Here’s a breakdown of how the function works:
-
mul(uint256 x, uint256 y)is a helper function that multiplies two uint256 valuesxandy. It checks for overflow by ensuring that eitheryis 0 or that the division of the resultzbyyis equal tox. If the condition is not met, it reverts with an error message. -
add(uint256 x, uint256 y)is another helper function that adds two uint256 valuesxandy. It checks for overflow by ensuring that the resultzis greater than or equal tox. If the condition is not met, the transaction will revert. -
wmul(uint256 x, uint256 y)is the primary function that multiplies two fixed-point numbers. The function does the following:- Calls the
mulfunction to multiplyxandy. - Adds half of the fixed-point base (WAD/2) to the result using the
addfunction. This step is crucial for rounding the result correctly. - Finally, it divides the sum by the fixed-point base (WAD) to obtain the final fixed-point result
z.
- Calls the
Now that we know how most of the calculation works let’s assume we call _borrowLimit with the variables used in this test suite:
function _borrowLimit(_bathToken,_asset, 25e18, 23.32e18)
Additionally, the collateral factor stays unchanged:
// collateralFactor = 70% for cTokenStable
await comptroller._setCollateralFactor(
cTokenStable.address,
parseUnits("0.7", 18)
);
// collateralFactor = 70% for cToken
await comptroller._setCollateralFactor(
cToken.address,
parseUnits("0.7", 18)
);
Calculating the desired amount, we get that its 58.3e18, which is the result of wmul(25e18, 23.32e18).
Now, let’s examine what happens within the while loop:
if (_limit == 0) {
// if collateral already provided
if (_minted != 0) {
uint256 _max = _maxBorrow(_bathToken);
// take into account previous collateral
_loopBorrowed = wmul(_assetAmount, _collateralFactor).add(
_max
);
} else {
_loopBorrowed = wmul(_assetAmount, _collateralFactor);
}
} else {
_loopBorrowed = wmul(_loopBorrowed, _collateralFactor);
}
The important thing to note here is that on the first iteration _loopBorrowed is the result of wmul(_assetAmount, _collateralFactor, but going forward it is a result of itself, e.g. wmul(_loopBorrowed, _collateralFactor).
-
On the first iteration: (limit == 0)
_loopBorrowed= wmul(25e18, 0.7e18) = 17.5e18_assetAmount= 25e18 + 17.5e18 = 42.5e18
-
On the second iteration: (limit != 0)
_loopBorrowed= wmul(17.5e18, 0.7e18) = 12.25e18_assetAmount= 42.5e18 + 12.25e18 = 54.75e18
-
On the third iteration: (limit != 0)
_loopBorrowed= wmul(12.25e18, 0.7e18) = 8.575e18_assetAmount= 54.75e18 + 8.575e18 = 63.325e18
So, it takes 3 iterations to reach the required result. However, the vulnerability here though is hiding in plain sight.
Given that _loopBorrowed is “dividing from itself”, what would happen if it goes to 1, or even 0, but the desired amount is big enough?
But… how could that happen? What if the collateralFactor is 0.5e18 instead of 0.7e18?
// collateralFactor = 70% for cTokenStable
await comptroller._setCollateralFactor(
cTokenStable.address,
parseUnits("0.7", 18)
);
// collateralFactor = 70% for cToken
await comptroller._setCollateralFactor(
cToken.address,
parseUnits("0.5", 18)
);
Let’s do the exercise again with a reduced collateral factor:
-
On the first iteration: (limit == 0)
_loopBorrowed= wmul(25e18, 0.5e18) = 12.5e18_assetAmount= 25e18 + 12.5e18 = 37.5e18
-
On the second iteration: (limit != 0)
_loopBorrowed= wmul(12.5e18, 0.5e18) = 6.25e18_assetAmount= 37.5e18 + 6.25e18 = 43.75e18
-
On the third iteration: (limit != 0)
_loopBorrowed= wmul(6.25e18, 0.5e18) = 3.125e18_assetAmount= 43.75e18 + 3.125e18 = 46,875e18
-
On the fourth iteration: (limit != 0)
_loopBorrowed= wmul(3.125e18, 0.5e18) = 1.5625e18_assetAmount= 43.75e18 + 1.5625e18 = 48.4375e18
-
On the fifth iteration: (limit != 0)
_loopBorrowed= wmul(1.5625e18, 0.5e18) = 0.78125e18_assetAmount= 43.75e18 + 6.2e18 = 49,2187e18
Now that _loopBorrowed < 0 I think its pretty clear where this is going. It will take approximately 60 more iterations until wmul(_loopBorrowed, 0.5e18) returns 1.
At this point _assetAmount will be around 50000000000000000020, which means it will take the 8299999999999999980 more iterations to get to the required desired amount.
You can verify these results by running the yarn hardhat test ./test/leverage-wrapper.ts --grep "should open long position" command from the existing test suite, which will produce the following output:
I have added some console logs for you if you want a visual representation:
function _borrowLimit(
address _bathToken,
address _asset,
uint256 _assetAmount,
uint256 _leverage
) internal view returns (uint256 _limit, uint256 _lastBorrow) {
(, uint256 _collateralFactor, ) = comptroller.markets(_bathToken);
// how much is needed to borrow in asset form
uint256 _desiredAmount = wmul(_assetAmount, _leverage);
console.log(_desiredAmount, "desiredAmount");
// check if collateral was already supplied
uint256 _minted = IERC20(_bathToken).balanceOf(address(this));
// how much is borrowed on a current loop
uint256 _loopBorrowed;
while (_assetAmount <= _desiredAmount) {
console.log("****** in loop");
if (_limit == 0) {
// if collateral already provided
if (_minted != 0) {
uint256 _max = _maxBorrow(_bathToken);
console.log("max", _max);
// take into account previous collateral
_loopBorrowed = wmul(_assetAmount, _collateralFactor).add(
_max
);
} else {
_loopBorrowed = wmul(_assetAmount, _collateralFactor);
}
} else {
_loopBorrowed = wmul(_loopBorrowed, _collateralFactor);
}
console.log("_loopBorrowed", _loopBorrowed);
// here _assetAmount refers to the
// TOTAL asset amount in the position
_assetAmount += _loopBorrowed;
console.log("_assetAmount", _assetAmount);
if (_assetAmount > _desiredAmount) {
// in case we've borrowed more than needed
// return excess and calculate how much is
// needed to borrow on the last loop
// to not overflow _desiredAmount
uint256 _borrowDelta = _desiredAmount.sub(
_assetAmount.sub(_loopBorrowed)
);
_lastBorrow = _borrowDelta.mul(WAD).div(_loopBorrowed);
_limit++;
break;
} else if (_assetAmount == _desiredAmount) {
// 1x short or perfect matching
_limit++;
break;
} else {
// default case
_limit++;
}
console.log("limit", _limit);
}
}
In conclusion, when the collateral factor is lower (and the leverage high), the _borrowLimit function becomes highly inefficient and requires a large number of iterations to calculate the desired amount.
This is just one nuance of this vulnerability and it could be triggered in various ways, but I hope this single explanation is good enough to convince you that it should be addressed.
Recommended Mitigation Steps
That’s probably one of my hardest mitigations steps to write, so I’ll brain-dump almost everything I’ve researched and that comes to my mind.
Limit the number of iterations:
Introduce a maximum number of iterations that the while loop can run, preventing the function from running indefinitely.
This approach helps prevent the infinite loop issue, but it means your system won’t be able to work with specific collateral factors.
Instead, the maximum number of iterations can be chosen based on expected usage patterns and system requirements.
uint256 maxIterations = 50;
uint256 currentIteration = 0;
while (_assetAmount <= _desiredAmount && currentIteration < maxIterations) {
// existing logic
currentIteration++;
}
Restrict the minimum _loopBorrowed value:
Define a minimum acceptable value for _loopBorrowed and halt the loop if the value goes below this threshold.
This approach can help prevent the _loopBorrowed value from becoming too small and causing an infinite loop. However, it has the same drawbacks as the previous solution.
uint256 minLoopBorrowed = 1e9; // Choose an appropriate minimum value based on the token decimals
while (_assetAmount <= _desiredAmount) {
// existing logic
if (_loopBorrowed < minLoopBorrowed) {
break;
}
}
Use a more sophisticated algorithm:
Instead of a while loop, consider using a more sophisticated algorithm to calculate the borrowing limit and last borrow amount.
It might be possible to derive a closed-form solution that directly calculates the borrowing limit without needing a loop.
However, this approach requires a deep understanding of the mathematical relationship between the input parameters and the desired borrowing limit.
For instance, if the borrowing limit calculation follows a simple linear relationship, the closed-form solution could be derived as follows:
function borrowLimit(uint256 _desiredAmount, uint256 _collateral, uint256 _loanFactor) public view returns (uint256) {
// Calculate the borrowing limit using the closed-form solution
uint256 borrowLimit = (_desiredAmount * _loanFactor) / (_collateral - _desiredAmount);
return borrowLimit;
}
To apply the closed-form solution to the _borrowLimit function, we would need to adjust the smart contract to directly compute the required number of iterations n and the final borrowed amount.
Instead, we can use the closed-form solution formula to calculate n and then determine the final borrowed amount using the formula for the sum of a geometric series.
For example, consider the scenario where the initial asset amount is A0 = 10,000 tokens, the desired asset amount is Ad = 15,000 tokens (10,000 tokens + 5,000 tokens), and the collateral factor is c = 0.5.
Using the closed-form solution formula: n = log_c((1 - ((Ad * (1 - c)) / A0)) - 1).
Substituting the values: n = log_0.5((1 - ((15,000 * (1 - 0.5)) / 10,000)) - 1).
After calculating, we get: n ≈ 1.58.
Since n should be an integer (as it represents the number of iterations), we round up to the nearest whole number: n = 2.
We can now calculate the final borrowed amount using the formula for the sum of a geometric series: Ad = A0 + A0 * c + A0 * c^2 + ... + A0 * c^n.
Substituting the values: 15,000 = 10,000 + 10,000 * 0.5 + 10,000 * 0.5^2.
Calculating the geometric series: 15,000 = 10,000 + 5,000 + 2,500.
Thus, the final borrowed amount is: 5,000 = 5,000 + 2,500.
Now that we know how it could work, we would need to identify the geometric series that represents the problem and use the closed-form formula for a geometric series to calculate the borrow limit.
If the collateral factor is not equal to 1, we would need to calculate the number of terms using the closed-form formula for a geometric series and the last borrow amount using the geometric series formula.
The pseudocode for the updated _borrowLimit function using the closed-form solution looks like this:
function _borrowLimit(
address _bathToken,
address _asset,
uint256 _assetAmount,
uint256 _leverage
) internal view returns (uint256 _limit, uint256 _lastBorrow) {
(, uint256 _collateralFactor, ) = comptroller.markets(_bathToken);
uint256 _desiredAmount = wmul(_assetAmount, _leverage);
uint256 _minted = IERC20(_bathToken).balanceOf(address(this));
if (_minted != 0) {
uint256 _max = _maxBorrow(_bathToken);
_assetAmount = wmul(_assetAmount, _collateralFactor).add(_max);
}
if (_collateralFactor == WAD) {
// Collateral factor is 1, which means it's a 1x short or perfect matching
_limit = (_desiredAmount.sub(_assetAmount)).div(WAD);
_lastBorrow = wmul(_assetAmount, _collateralFactor);
} else {
// Calculate the number of terms using the closed-form formula for a geometric series
_limit = uint256(
log1p(
wdiv(
(_desiredAmount.mul(WAD.sub(_collateralFactor))).sub(_assetAmount.mul(WAD)),
_assetAmount.mul(_collateralFactor)
)
).div(log1p(_collateralFactor.sub(WAD)))
);
// Calculate the last borrow amount
_lastBorrow = wmul(_assetAmount, pow(_collateralFactor, _limit)).sub(_assetAmount);
}
}
Please note that the provided solution is incomplete and requires additional adjustments.
daoio (Rubicon) acknowledged and commented:
Yeah, it’s correct, it will loop infinitely if
collateralFactor< ~66%, that’s known. The report relies onbathToken'srisk params, which is out-of-scope, though the report itself is just incredibly HQ.
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
Likely the while loop in _borrowLimit does not have a maximum iteration limit and the borrowed amount decreases geometrically, so with a low collateral factor it takes many iterations to reach the desired amount.
What the attacker needed
Collateral factor below ~66%; high leverage
The fix
The function should be fixed by limiting the number of iterations, restricting the minimum _loopBorrowed value, or using a closed-form solution to avoid the loop.
How it was found
- Set the collateral factor to 0.5e18 for the cToken.
- Call _borrowLimit with _assetAmount = 25e18 and _leverage = 23.32e18.
- Observe that the while loop iterates many times because _loopBorrowed becomes very small.
- The function takes a large number of iterations to reach the desired amount, causing a denial of service.
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.
A smart contract function that calculates how many times to borrow in a loop can get stuck if the collateral factor (a percentage) is low. This makes the function run for a very long time, so the system can't process the transaction, effectively breaking that feature.
What is DoS?
A request that exhausts resources or crashes a component. Many programs forbid testing it; reports usually show it from code, not by attacking.