Skip to content
Audit finding Advanced

`updateLocked()` locks a rounded down value

The `updateLocked()` function in the UToken contract rounds down the locked amount when adding a fee, which can cause the locked amount to be slightly less than the borrowed principal. This can prevent the full write-off of a debt, leaving a small residual principal and causing the borrower's position to be marked as overdue, blocking future borrows.

hyh Follow

Originally disclosed on Sherlock

Source: https://github.com/sherlock-audit/2024-06-union-finance-update-2-judging/issues/133

Found by

hyh

Summary

Since decimalReducing() rounds down and fee can use all the precision space the UToken's updateLocked() call performed on borrowing will effectively lock less then is borrowed.

Vulnerability Detail

decimalReducing(actualAmount + fee, underlyingDecimal) performed on locking can lose precision, i.e. since fee is added the rounding down can have a material impact.

Impact

User can have borrowed value slightly exceeding the cumulative lock amount due to rounding of the fee added.

Code Snippet

updateLocked() will lock a rounded down number for a user:

UToken.sol#L656-L660

Solidity
        IUserManager(userManager).updateLocked(
            msg.sender,
            decimalReducing(actualAmount + fee, underlyingDecimal),
            true
        );

Tool used

Manual Review

Recommendation

Consider introducing an option for rounding the decimalReducing() output up, e.g.:

UToken.sol#L656-L660

Diff
        IUserManager(userManager).updateLocked(
            msg.sender,
-           decimalReducing(actualAmount + fee, underlyingDecimal),
+           decimalReducing(actualAmount + fee, underlyingDecimal, true),
            true
        );

https://github.com/sherlock-audit/2024-06-union-finance-update-2/blob/main/union-v2-contracts/contracts/ScaledDecimalBase.sol#L19-L27

Diff
-   function decimalReducing(uint256 actualAmount, uint8 decimal) internal pure returns (uint256) {
+   function decimalReducing(uint256 actualAmount, uint8 decimal, bool roundUp) internal pure returns (uint256) {
        if (decimal > 18) {
            uint8 diff = decimal - 18;
            return actualAmount * 10 ** diff;
        } else {
            uint8 diff = 18 - decimal;
            uint256 rounding = roundUp ? 10 ** diff - 1 : 0;
-           return actualAmount / 10 ** diff;
+           return (actualAmount + rounding) / 10 ** diff;
        }
    }

Discussion

sherlock-admin3

1 comment(s) were left on this issue during the judging contest.

0xmystery commented:

Low QA on rounding direction

dmitriia

Low QA on rounding direction

Similarly, there is no such rule.

dmitriia

Escalate It looks like the locked < principal state reached with locking slightly less than it was borrowed leads to inability to fully close a position with write off as, since repayAmount is locked amount derived, it will be less than principal:

UserManager.sol#L866-L867

Solidity
        IAssetManager(assetManager).debtWriteOff(stakingToken, amount);
>>      uToken.debtWriteOff(borrowerAddress, amount);

UToken.sol#L785-L800

Solidity
    function debtWriteOff(address borrower, uint256 amount) external override whenNotPaused onlyUserManager {
        if (amount == 0) revert AmountZero();
        uint256 actualAmount = decimalScaling(amount, underlyingDecimal);

        uint256 oldPrincipal = _getBorrowed(borrower);
        uint256 repayAmount = actualAmount > oldPrincipal ? oldPrincipal : actualAmount;

        accountBorrows[borrower].principal = oldPrincipal - repayAmount;
        _totalBorrows -= repayAmount;

>>      if (repayAmount == oldPrincipal) {
            // If all principal is written off, we can reset the last repaid time to 0.
            // which indicates that the borrower has no outstanding loans.
            accountBorrows[borrower].lastRepay = 0;
        }
    }

Since it breaks this workflow and lastRepay has a material impact on the users (this borrower will have checkIsOverdue() == true for a next borrow, i.e. will not be able to create a non-dust position thereafter), it looks like it's a medium probability (writing-off is a requirement) and impact (credit line is unavailable with the corresponding material impact on the borrower), i.e. it's a medium severity issue.

sherlock-admin3

Escalate It looks like the locked < principal state reached with locking slightly less than it was borrowed leads to inability to fully close a position with write off as, since repayAmount is locked amount derived, it will be less than principal:

UserManager.sol#L866-L867

Solidity
        IAssetManager(assetManager).debtWriteOff(stakingToken, amount);
>>      uToken.debtWriteOff(borrowerAddress, amount);

UToken.sol#L785-L800

Solidity
    function debtWriteOff(address borrower, uint256 amount) external override whenNotPaused onlyUserManager {
        if (amount == 0) revert AmountZero();
        uint256 actualAmount = decimalScaling(amount, underlyingDecimal);

        uint256 oldPrincipal = _getBorrowed(borrower);
        uint256 repayAmount = actualAmount > oldPrincipal ? oldPrincipal : actualAmount;

        accountBorrows[borrower].principal = oldPrincipal - repayAmount;
        _totalBorrows -= repayAmount;

>>      if (repayAmount == oldPrincipal) {
            // If all principal is written off, we can reset the last repaid time to 0.
            // which indicates that the borrower has no outstanding loans.
            accountBorrows[borrower].lastRepay = 0;
        }
    }

Since it breaks this workflow and lastRepay has a material impact on the users (this borrower will have checkIsOverdue() == true right after next borrow, i.e. for a non-dust position), then it has medium probability and impact, i.e. it's a medium severity issue.

You've created a valid escalation!

To remove the escalation from consideration: Delete your comment.

You may delete or edit your escalation comment anytime before the 48-hour escalation window closes. After that, the escalation becomes final.

mystery0x

Please see comment on #122.

dmitriia

Please see comment on #122.

It's not relevant here as, while the rounding is not limited to 1 wei, the issue is not about the size of rounding, but about the logic break up. The logic expects precise amounts match and is not working otherwise (lastRepay isn't set).

WangSecurity

This report is about precision loss and it falls under the following rule:

PoC is required for all issues falling into any of the following groups: issues related to precision loss

I believe this report lacks POC (coded or written) and sufficient proof rounding down precision loss.

Planning to reject the escalation and leave the issue as it is, since it doesn't fulfil the POC requirements.

dmitriia

Schematic POC:

  1. Let's examine USDC market with originationFee = 1e-8, which is 1e10 in 18 dp representation. Bob has no loans, Alice opened trust for him only

  2. Bob borrows 99 USDC from Alice's trust, his principal is set to this amount converted to 18 dp, actualAmount, with calculatingFee(actualAmount) = (originationFee * actualAmount) / WAD added on top. The principal for their loan position is 99e18 + 1e10 * 99e18 / 1e8 = 99 * (1e18 + 1e10)

  3. Locking operation deals with 6 dp figures and uses decimalReducing(actualAmount + fee, underlyingDecimal), so it locks only 99 * (1e18 + 1e10) / 1e12 = 99e6

  4. A substantial time passes and this debt ends up being written off, for example via an arrangement between Bob and Alice for some OTC repayment, say Bob will give a similarly priced item to Alice off chain and she will write off the debt

  5. Writing off uses 99e6 only (being based on underlying amount, 6 dp figure) and will not clear Bob's principal fully, he will still have the 99e10 part (it's an internal 18 dp figure). Since principal was not cleared, Bob's lastRepay was not reset, it still holds the value set in (1), i.e. the system treats his position as being borrowed long time ago and not repaid since. It's not material for now as position remainder is dust sized

  6. However, when Bob try to borrow again from Alice's trust (which is tied to Bob's address) it will be denied as his position will be deemed overdue, so the existing trust will be unavailable for borrowing

WangSecurity

Unfortunately, POC and the proof of precision loss should have been described in the report. Hence, I cannot accept this as a rewarded finding based on the rules.

dmitriia

Well, in this case the issue can be excluded as incomplete per initial submission. Please refrain from implying the need of any additional actions in such cases in the future. Note that excluding the issues from contest report also exclude them from the fix review, which scope is contest defined.

WangSecurity

in this case the issue can be excluded as incomplete per initial submission

Good suggestion, I'm unsure it can be automated, but will look into that.

Please refrain from implying the need of any additional actions in such cases in the future

Excuse me, I didn't imply anything is needed and it was poor phrasing from my side then.

Note that excluding the issues from contest report also exclude them from the fix review, which scope is contest defined.

As far as I know, it doesn't and the sponsor can fix any issue they desire by just adding a "Will fix" label through their dashboard.

Hence, the decision remains the same, planning to reject the escalation and leave the issue as it is, based on the same arguments above.

dmitriia

Your can imply basically anything, there is no such obligation and I will be checking only issues from the report. If any others are deemed not important enough to be in the report, then their fix is not important either.

WangSecurity

After further considering the rule about the POC, decision is that submitting it after the contest when the lead judge requests or during the contest is sufficient. Excuse me for the confusion previously. The POC shows how the precision leads Bob’s position being counted as opened and leaving the trust unavailable for Bob.

Planning to accept the escalation and validate with medium severity. @mystery0x @dmitriia are there any duplicates?

WangSecurity

Result: Medium Unique

sherlock-admin4

Escalations have been resolved successfully!

Escalation status:

sherlock-admin2

The protocol team fixed this issue in the following PRs/commits: https://github.com/unioncredit/union-v2-contracts/pull/176

dmitriia

The protocol team fixed this issue in the following PRs/commits: unioncredit/union-v2-contracts#176

Fix looks ok.

It looks like 1 wei of locked will remain in some cases, as one described above, after {borrow} -> {full repay}, since borrow rounds up, while repay rounds down in updateLocked(...) arguments. As of now I see no issue in that as there won't be any material accumulation, this and further workflow remain operational, particularly lastRepay is correctly reset, being conditional on principal, which is fully cleared. Writing off will be functional as well due to repayAmount = actualAmount > oldPrincipal ? oldPrincipal : actualAmount logic.

The original report as published on Sherlock, by hyh. Images and videos are our own copies; raw HTML is shown as text. View it on Sherlock.

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 use of a rounding-down function (`decimalReducing`) when calculating the locked amount, without considering that the fee addition can cause a loss of precision that makes the locked amount less than the principal.

Impact

A borrower may be unable to fully close a position with write-off, leaving a small residual principal that causes the position to be marked overdue and prevents future borrowing from the same trust.

What the attacker needed

Borrower has a trust with a lender; origination fee is set; debt is written off

The fix

The issue was fixed by introducing an option to round up in `decimalReducing()` and using it when locking.

How it was found

  1. Bob borrows 99 USDC from Alice's trust, and his principal is set to the borrowed amount plus fee in 18 decimal precision.
  2. The locking operation uses `decimalReducing` on the sum, which rounds down to 6 decimal places, locking slightly less than the principal.
  3. After some time, the debt is written off, but the write-off amount is based on the locked amount, which is less than the principal, so a small residual principal remains.
  4. Because the principal is not fully cleared, Bob's `lastRepay` is not reset, and his position is considered overdue.
  5. When Bob tries to borrow again, the system denies the loan due to the overdue status.

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 borrow, the system records the amount you owe and also 'locks' a corresponding amount as collateral or debt. Due to rounding down, the locked amount can be a tiny bit smaller than what you borrowed. Later, if the debt is written off, the small difference remains, and the system thinks you still owe something, which can block you from borrowing again.

More by hyh

View all

137 more disclosed reports, best first.

More from Union Finance Update #2

View all

The newest disclosed reports for this program.

Similar reports

Same bug class and techniques, clearest first.