Skip to content
This repository has been archived by the owner on Apr 28, 2024. It is now read-only.

handsomegiraffe - If loan is not liquidated in time, underflow may prevent loan from being liquidated using emergency mode #195

Closed
sherlock-admin opened this issue Oct 23, 2023 · 8 comments
Labels
Duplicate A valid issue that is a duplicate of an issue with `Has Duplicates` label Escalation Resolved This issue's escalations have been approved/rejected Medium A valid Medium severity issue Reward A payout will be made for this issue

Comments

@sherlock-admin
Copy link
Contributor

sherlock-admin commented Oct 23, 2023

handsomegiraffe

high

If loan is not liquidated in time, underflow may prevent loan from being liquidated using emergency mode

Summary

If roughly 500_000 seconds (~5 days) has passed and loan is not liquidated, emergency repayment will fail due to underflow causing repay function to revert

Vulnerability Detail

borrowingStorage.accLoanRatePerSeconds =
holdTokenRateInfo.accLoanRatePerSeconds -
FullMath.mulDiv(
uint256(-collateralBalance),
Constants.BP,
borrowing.borrowedAmount // new amount
);

When collateralBalance grows large enough, this part of the repay function will revert

POC

In line 421 of WagmiLeverageTests.ts, if time is increased to 500_000, the next test that repays will fail with Arithmetic operation underflowed or overflowed outside of an unchecked block.

Impact

Prevention of liquidity providers from recovering their funds from a loan under liquidation. May also have impact on regular liquidation but did not have time to check due submission close to end of contest

Code Snippet

https://github.com/sherlock-audit/2023-10-real-wagmi/blob/main/wagmi-leverage/contracts/LiquidityBorrowingManager.sol#L612C17-L618C23

Tool used

Manual Review

Recommendation

Handle possible underflow with additional checks before the calculation

Duplicate of #119

@github-actions github-actions bot added Medium A valid Medium severity issue Duplicate A valid issue that is a duplicate of an issue with `Has Duplicates` label labels Oct 26, 2023
@cvetanovv cvetanovv removed the Medium A valid Medium severity issue label Oct 30, 2023
@sherlock-admin sherlock-admin changed the title Orbiting Tweed Caterpillar - If loan is not liquidated in time, underflow may prevent loan from being liquidated using emergency mode handsomegiraffe - If loan is not liquidated in time, underflow may prevent loan from being liquidated using emergency mode Oct 30, 2023
@sherlock-admin sherlock-admin added Non-Reward This issue will not receive a payout and removed Duplicate A valid issue that is a duplicate of an issue with `Has Duplicates` label labels Oct 30, 2023
@giraffe0x
Copy link

Escalate

Similar to 119 I think both issues are wrongly classified as invalid.

In repay(), if loan is not liquidated in ~1 day, collateralBalance can grow large enough to cause underflow.

This bug is easily replicated using protocol's own default test file WagmiLeverageTests.tsby changing line 1040

it("emergency repay will be successful for PosManNFT owner if the collateral is depleted", async () => {
        let debt: LiquidityBorrowingManager.BorrowingInfoExtStructOutput[] =
            await borrowingManager.getBorrowerDebtsInfo(bob.address);
        await time.increase(debt[1].estimatedLifeTime.toNumber() + 1);

        let borrowingKey = await borrowingManager.userBorrowingKeys(bob.address, 1);
        let deadline = (await time.latest()) + 60;

        let swap_params = ethers.utils.defaultAbiCoder.encode(
            ["address", "address", "uint256", "uint256"],
            [constants.AddressZero, constants.AddressZero, 0, 0]
        );
        swapData = swapIface.encodeFunctionData("swap", [swap_params]);

        let swapParams: ApproveSwapAndPay.SwapParamsStruct = {
            swapTarget: constants.AddressZero,
            swapAmountInDataIndex: 0,
            maxGasForCall: 0,
            swapData: swapData,
        };

        let params: LiquidityBorrowingManager.RepayParamsStruct = {
            isEmergency: true, //emergency
            internalSwapPoolfee: 0,
            externalSwap: swapParams,
            borrowingKey: borrowingKey,
            swapSlippageBP1000: 0,
        };


        let loans: LiquidityManager.LoanInfoStructOutput[] = await borrowingManager.getLoansInfo(borrowingKey);
        expect(loans.length).to.equal(3);

        await expect(borrowingManager.connect(alice).repay(params, deadline))
            .to.emit(borrowingManager, "EmergencyLoanClosure")
            .withArgs(bob.address, alice.address, borrowingKey);

        expect(await borrowingManager.getLenderCreditsCount(nftpos[0].tokenId)).to.be.equal(0);
        expect(await borrowingManager.getLenderCreditsCount(nftpos[1].tokenId)).to.be.gt(0);
        expect(await borrowingManager.getLenderCreditsCount(nftpos[2].tokenId)).to.be.gt(0);
        expect(await borrowingManager.getLenderCreditsCount(nftpos[3].tokenId)).to.be.gt(0);
        expect(await borrowingManager.getLenderCreditsCount(nftpos[4].tokenId)).to.be.gt(0);
        expect(await borrowingManager.getLenderCreditsCount(nftpos[5].tokenId)).to.be.gt(0);
        expect(await borrowingManager.getBorrowerDebtsCount(bob.address)).to.be.equal(2);

        debt = await borrowingManager.getBorrowerDebtsInfo(bob.address);
        
        loans = await borrowingManager.getLoansInfo(borrowingKey);
        expect(loans.length).to.equal(2);

        await time.increase(100); // @audit change this to 100_000 (~ 1 day)
        deadline = (await time.latest()) + 60;
        await expect(borrowingManager.connect(bob).repay(params, deadline)) // @audit repay will underflow here
            .to.emit(borrowingManager, "EmergencyLoanClosure")
            .withArgs(bob.address, bob.address, borrowingKey); 

Expecting an under-collateralized loan to not be liquidated in ~1 day is not unrealistic, after which the failure of emergency mode represents a significant impact to a critical protocol function.

@sherlock-admin2
Copy link
Contributor

Escalate

Similar to 119 I think both issues are wrongly classified as invalid.

In repay(), if loan is not liquidated in ~1 day, collateralBalance can grow large enough to cause underflow.

This bug is easily replicated using protocol's own default test file WagmiLeverageTests.tsby changing line 1040

it("emergency repay will be successful for PosManNFT owner if the collateral is depleted", async () => {
        let debt: LiquidityBorrowingManager.BorrowingInfoExtStructOutput[] =
            await borrowingManager.getBorrowerDebtsInfo(bob.address);
        await time.increase(debt[1].estimatedLifeTime.toNumber() + 1);

        let borrowingKey = await borrowingManager.userBorrowingKeys(bob.address, 1);
        let deadline = (await time.latest()) + 60;

        let swap_params = ethers.utils.defaultAbiCoder.encode(
            ["address", "address", "uint256", "uint256"],
            [constants.AddressZero, constants.AddressZero, 0, 0]
        );
        swapData = swapIface.encodeFunctionData("swap", [swap_params]);

        let swapParams: ApproveSwapAndPay.SwapParamsStruct = {
            swapTarget: constants.AddressZero,
            swapAmountInDataIndex: 0,
            maxGasForCall: 0,
            swapData: swapData,
        };

        let params: LiquidityBorrowingManager.RepayParamsStruct = {
            isEmergency: true, //emergency
            internalSwapPoolfee: 0,
            externalSwap: swapParams,
            borrowingKey: borrowingKey,
            swapSlippageBP1000: 0,
        };


        let loans: LiquidityManager.LoanInfoStructOutput[] = await borrowingManager.getLoansInfo(borrowingKey);
        expect(loans.length).to.equal(3);

        await expect(borrowingManager.connect(alice).repay(params, deadline))
            .to.emit(borrowingManager, "EmergencyLoanClosure")
            .withArgs(bob.address, alice.address, borrowingKey);

        expect(await borrowingManager.getLenderCreditsCount(nftpos[0].tokenId)).to.be.equal(0);
        expect(await borrowingManager.getLenderCreditsCount(nftpos[1].tokenId)).to.be.gt(0);
        expect(await borrowingManager.getLenderCreditsCount(nftpos[2].tokenId)).to.be.gt(0);
        expect(await borrowingManager.getLenderCreditsCount(nftpos[3].tokenId)).to.be.gt(0);
        expect(await borrowingManager.getLenderCreditsCount(nftpos[4].tokenId)).to.be.gt(0);
        expect(await borrowingManager.getLenderCreditsCount(nftpos[5].tokenId)).to.be.gt(0);
        expect(await borrowingManager.getBorrowerDebtsCount(bob.address)).to.be.equal(2);

        debt = await borrowingManager.getBorrowerDebtsInfo(bob.address);
        
        loans = await borrowingManager.getLoansInfo(borrowingKey);
        expect(loans.length).to.equal(2);

        await time.increase(100); // @audit change this to 100_000 (~ 1 day)
        deadline = (await time.latest()) + 60;
        await expect(borrowingManager.connect(bob).repay(params, deadline)) // @audit repay will underflow here
            .to.emit(borrowingManager, "EmergencyLoanClosure")
            .withArgs(bob.address, bob.address, borrowingKey); 

Expecting an under-collateralized loan to not be liquidated in ~1 day is not unrealistic, after which the failure of emergency mode represents a significant impact to a critical protocol function.

The escalation could not be created because you are not exceeding the escalation threshold.

You can view the required number of additional valid issues/judging contest payouts in your Profile page,
in the Sherlock webapp.

@GeorgeHNTR
Copy link

Escalate

Similar to 119 I think both issues are wrongly classified as invalid.

In repay(), if loan is not liquidated in ~1 day, collateralBalance can grow large enough to cause underflow.

This bug is easily replicated using protocol's own default test file WagmiLeverageTests.tsby changing line 1040

it("emergency repay will be successful for PosManNFT owner if the collateral is depleted", async () => {
        let debt: LiquidityBorrowingManager.BorrowingInfoExtStructOutput[] =
            await borrowingManager.getBorrowerDebtsInfo(bob.address);
        await time.increase(debt[1].estimatedLifeTime.toNumber() + 1);

        let borrowingKey = await borrowingManager.userBorrowingKeys(bob.address, 1);
        let deadline = (await time.latest()) + 60;

        let swap_params = ethers.utils.defaultAbiCoder.encode(
            ["address", "address", "uint256", "uint256"],
            [constants.AddressZero, constants.AddressZero, 0, 0]
        );
        swapData = swapIface.encodeFunctionData("swap", [swap_params]);

        let swapParams: ApproveSwapAndPay.SwapParamsStruct = {
            swapTarget: constants.AddressZero,
            swapAmountInDataIndex: 0,
            maxGasForCall: 0,
            swapData: swapData,
        };

        let params: LiquidityBorrowingManager.RepayParamsStruct = {
            isEmergency: true, //emergency
            internalSwapPoolfee: 0,
            externalSwap: swapParams,
            borrowingKey: borrowingKey,
            swapSlippageBP1000: 0,
        };


        let loans: LiquidityManager.LoanInfoStructOutput[] = await borrowingManager.getLoansInfo(borrowingKey);
        expect(loans.length).to.equal(3);

        await expect(borrowingManager.connect(alice).repay(params, deadline))
            .to.emit(borrowingManager, "EmergencyLoanClosure")
            .withArgs(bob.address, alice.address, borrowingKey);

        expect(await borrowingManager.getLenderCreditsCount(nftpos[0].tokenId)).to.be.equal(0);
        expect(await borrowingManager.getLenderCreditsCount(nftpos[1].tokenId)).to.be.gt(0);
        expect(await borrowingManager.getLenderCreditsCount(nftpos[2].tokenId)).to.be.gt(0);
        expect(await borrowingManager.getLenderCreditsCount(nftpos[3].tokenId)).to.be.gt(0);
        expect(await borrowingManager.getLenderCreditsCount(nftpos[4].tokenId)).to.be.gt(0);
        expect(await borrowingManager.getLenderCreditsCount(nftpos[5].tokenId)).to.be.gt(0);
        expect(await borrowingManager.getBorrowerDebtsCount(bob.address)).to.be.equal(2);

        debt = await borrowingManager.getBorrowerDebtsInfo(bob.address);
        
        loans = await borrowingManager.getLoansInfo(borrowingKey);
        expect(loans.length).to.equal(2);

        await time.increase(100); // @audit change this to 100_000 (~ 1 day)
        deadline = (await time.latest()) + 60;
        await expect(borrowingManager.connect(bob).repay(params, deadline)) // @audit repay will underflow here
            .to.emit(borrowingManager, "EmergencyLoanClosure")
            .withArgs(bob.address, bob.address, borrowingKey); 

Expecting an under-collateralized loan to not be liquidated in ~1 day is not unrealistic, after which the failure of emergency mode represents a significant impact to a critical protocol function.

@sherlock-admin2
Copy link
Contributor

Escalate

Similar to 119 I think both issues are wrongly classified as invalid.

In repay(), if loan is not liquidated in ~1 day, collateralBalance can grow large enough to cause underflow.

This bug is easily replicated using protocol's own default test file WagmiLeverageTests.tsby changing line 1040

it("emergency repay will be successful for PosManNFT owner if the collateral is depleted", async () => {
        let debt: LiquidityBorrowingManager.BorrowingInfoExtStructOutput[] =
            await borrowingManager.getBorrowerDebtsInfo(bob.address);
        await time.increase(debt[1].estimatedLifeTime.toNumber() + 1);

        let borrowingKey = await borrowingManager.userBorrowingKeys(bob.address, 1);
        let deadline = (await time.latest()) + 60;

        let swap_params = ethers.utils.defaultAbiCoder.encode(
            ["address", "address", "uint256", "uint256"],
            [constants.AddressZero, constants.AddressZero, 0, 0]
        );
        swapData = swapIface.encodeFunctionData("swap", [swap_params]);

        let swapParams: ApproveSwapAndPay.SwapParamsStruct = {
            swapTarget: constants.AddressZero,
            swapAmountInDataIndex: 0,
            maxGasForCall: 0,
            swapData: swapData,
        };

        let params: LiquidityBorrowingManager.RepayParamsStruct = {
            isEmergency: true, //emergency
            internalSwapPoolfee: 0,
            externalSwap: swapParams,
            borrowingKey: borrowingKey,
            swapSlippageBP1000: 0,
        };


        let loans: LiquidityManager.LoanInfoStructOutput[] = await borrowingManager.getLoansInfo(borrowingKey);
        expect(loans.length).to.equal(3);

        await expect(borrowingManager.connect(alice).repay(params, deadline))
            .to.emit(borrowingManager, "EmergencyLoanClosure")
            .withArgs(bob.address, alice.address, borrowingKey);

        expect(await borrowingManager.getLenderCreditsCount(nftpos[0].tokenId)).to.be.equal(0);
        expect(await borrowingManager.getLenderCreditsCount(nftpos[1].tokenId)).to.be.gt(0);
        expect(await borrowingManager.getLenderCreditsCount(nftpos[2].tokenId)).to.be.gt(0);
        expect(await borrowingManager.getLenderCreditsCount(nftpos[3].tokenId)).to.be.gt(0);
        expect(await borrowingManager.getLenderCreditsCount(nftpos[4].tokenId)).to.be.gt(0);
        expect(await borrowingManager.getLenderCreditsCount(nftpos[5].tokenId)).to.be.gt(0);
        expect(await borrowingManager.getBorrowerDebtsCount(bob.address)).to.be.equal(2);

        debt = await borrowingManager.getBorrowerDebtsInfo(bob.address);
        
        loans = await borrowingManager.getLoansInfo(borrowingKey);
        expect(loans.length).to.equal(2);

        await time.increase(100); // @audit change this to 100_000 (~ 1 day)
        deadline = (await time.latest()) + 60;
        await expect(borrowingManager.connect(bob).repay(params, deadline)) // @audit repay will underflow here
            .to.emit(borrowingManager, "EmergencyLoanClosure")
            .withArgs(bob.address, bob.address, borrowingKey); 

Expecting an under-collateralized loan to not be liquidated in ~1 day is not unrealistic, after which the failure of emergency mode represents a significant impact to a critical protocol function.

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.

@sherlock-admin sherlock-admin added the Escalated This issue contains a pending escalation label Nov 1, 2023
@HHK-ETH
Copy link

HHK-ETH commented Nov 2, 2023

Thanks for escalating this one!

Like mentioned in the escalation, consider checking #119 for additional details and POCs.

@Czar102
Copy link

Czar102 commented Nov 6, 2023

Will be accepting the escalations and making this a medium.

@Evert0x
Copy link

Evert0x commented Nov 8, 2023

Result:
Medium
Duplicate of #119

@sherlock-admin2
Copy link
Contributor

sherlock-admin2 commented Nov 8, 2023

Escalations have been resolved successfully!

Escalation status:

@Evert0x Evert0x added the Medium A valid Medium severity issue label Nov 8, 2023
@sherlock-admin sherlock-admin added Reward A payout will be made for this issue and removed Non-Reward This issue will not receive a payout Escalated This issue contains a pending escalation labels Nov 8, 2023
@sherlock-admin2 sherlock-admin2 added Escalation Resolved This issue's escalations have been approved/rejected Duplicate A valid issue that is a duplicate of an issue with `Has Duplicates` label labels Nov 8, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate A valid issue that is a duplicate of an issue with `Has Duplicates` label Escalation Resolved This issue's escalations have been approved/rejected Medium A valid Medium severity issue Reward A payout will be made for this issue
Projects
None yet
Development

No branches or pull requests

8 participants