Skip to content
Business logic Audit finding Intermediate

Some protection buyers might not be able to renew their protections due to delayed expiration processing

A bug in the premium accrual logic causes protections to never be marked as expired when no payments have been made for a long time. As a result, buyers cannot renew their protections because the renewal check requires an expired protection record.

chaduke Follow

Originally disclosed on Sherlock

Source: https://github.com/sherlock-audit/2023-02-carapace-judging/issues/27

Found by

chaduke

Summary

Some protection buyers will never be able to renew their protection due to delayed expiration processing.

Vulnerability Detail

We show below how some buyers will not be able to renew their protection due to delayed expiration process caused by the the wrong implementation of verifyAndAccruePremium(). Due to the bug, they might miss the deadline and grace period for renewal.

  1. First the verifyBuyerCanRenewProtection() function checks whether it is too late to renew the protection (before the grace period expires). In addition, verifyBuyerCanRenewProtection() also checks whether there exists an expired protection with the same lending pool and position token ID at protectionBuyerAccounts[msg.sender].expiredProtectionIndexByLendingPool[_protectionPurchaseParams.lendingPoolAddress][_protectionPurchaseParams.nftLpTokenId] in L371. If such an existing expired protection is not there, renewal will be rejected.

https://github.com/sherlock-audit/2023-02-carapace/blob/main/contracts/libraries/ProtectionPoolHelper.sol#L360-L399

  1. In order for the expired protection to be stored in protectionBuyerAccounts[msg.sender].expiredProtectionIndexByLendingPool[_protectionPurchaseParams.lendingPoolAddress][_protectionPurchaseParams.nftLpTokenId], the expireProtection() must be called at L1004 of function _accruePremiumAndExpireProtections().

https://github.com/sherlock-audit/2023-02-carapace/blob/main/contracts/core/pool/ProtectionPool.sol#L963-L1021

  1. the expireProtection() function stores such expired protection at L311-315:

https://github.com/sherlock-audit/2023-02-carapace/blob/main/contracts/libraries/ProtectionPoolHelper.sol#L293-L321

  1. However, before expireProtection() can be called, function verifyAndAccruePremium() needs to be called first to decide whether a protection has expired or not (L990).

https://github.com/sherlock-audit/2023-02-carapace/blob/main/contracts/core/pool/ProtectionPool.sol#L963-L1021

  1. However, when there is no payment for a while, for example, when the last payment is made before a protection P starts (_latestPaymentTimestamp < _startTimestamp), P will not be considered as expired see L215-220 of verifyAndAccruePremium() below:

https://github.com/sherlock-audit/2023-02-carapace/blob/main/contracts/libraries/ProtectionPoolHelper.sol#L201-L284

  1. Therefore, if there is no payment for a long time, then verifyAndAccruePremium() will always consider a protection P has not expired. expireProtection() will never process it. So the actually expired protection will not be stored in protectionBuyerAccounts[msg.sender].expiredProtectionIndexByLendingPool[_protectionPurchaseParams.lendingPoolAddress][_protectionPurchaseParams.nftLpTokenId]. The buyer for P will not be able to renew P because verifyBuyerCanRenewProtection() will fail to find an existing expired protection P. If there is no payment for a long time, then the buyer for P might miss the deadline and grace period and will never be able to renew P anymore.

Impact

Some protection buyers might never be able to renew their protections due to delayed expiration processing as a result of a bug of verifyAndAccruePremium().

getActiveProtections() might return some protections that are supposed to have expired, but not processed due to the above bug.

Code Snippet

See above

Tool used

VSCode

Manual Review

Recommendation

We revise verifyAndAccruePremium() so that it will process and return the right value when a protection expires.

Diff
 function verifyAndAccruePremium(
    ProtectionPoolInfo storage poolInfo,
    ProtectionInfo storage protectionInfo,
    uint256 _lastPremiumAccrualTimestamp,
    uint256 _latestPaymentTimestamp
  )
    external
    view
    returns (uint256 _accruedPremiumInUnderlying, bool _protectionExpired)
  {
    uint256 _startTimestamp = protectionInfo.startTimestamp;

+    uint256 _expirationTimestamp = protectionInfo.startTimestamp +
+      protectionInfo.purchaseParams.protectionDurationInSeconds;
+    _protectionExpired = block.timestamp > _expirationTimestamp;


    /// This means no payment has been made after the protection is bought or protection starts in the future.
    /// so no premium needs to be accrued.
-    if (
-      _latestPaymentTimestamp < _startTimestamp ||
-      _startTimestamp > block.timestamp
-    ) {
+    if (!_protectionExpired                                              // @audit: only if it has not expired
+      (_latestPaymentTimestamp < _startTimestamp ||
+      _startTimestamp > block.timestamp)
+    ) {
 
      return (0, false);
    }

    /// Calculate the protection expiration timestamp and
    /// Check if the protection is expired or not.
-    uint256 _expirationTimestamp = protectionInfo.startTimestamp +
-      protectionInfo.purchaseParams.protectionDurationInSeconds;
-    _protectionExpired = block.timestamp > _expirationTimestamp;

    /// Only accrue premium if the protection is expired
    /// or latest payment is made after the protection start & last premium accrual
    if (
      _protectionExpired ||
      (_latestPaymentTimestamp > _startTimestamp &&
        _latestPaymentTimestamp > _lastPremiumAccrualTimestamp)
    ) {
      /**
       * <-Protection Bought(second: 0) --- last accrual --- now(latestPaymentTimestamp) --- Expiration->
       * The time line starts when protection is bought and ends when protection is expired.
       * secondsUntilLastPremiumAccrual is the second elapsed since the last accrual timestamp.
       * secondsUntilLatestPayment is the second elapsed until latest payment is made.
       */

      // When premium is accrued for the first time, the _secondsUntilLastPremiumAccrual is 0.
      uint256 _secondsUntilLastPremiumAccrual;
      if (_lastPremiumAccrualTimestamp > _startTimestamp) {
        _secondsUntilLastPremiumAccrual =
          _lastPremiumAccrualTimestamp -
          _startTimestamp;
      }

      /// if loan protection is expired, then accrue premium till expiration and mark it for removal
      uint256 _secondsUntilLatestPayment;
      if (_protectionExpired) {
        _secondsUntilLatestPayment = _expirationTimestamp - _startTimestamp;
        console.log(
          "Protection expired for amt: %s",
          protectionInfo.purchaseParams.protectionAmount
        );
      } else {
        _secondsUntilLatestPayment = _latestPaymentTimestamp - _startTimestamp;
      }

      /// Calculate the accrued premium amount scaled to 18 decimals
      uint256 _accruedPremiumIn18Decimals = AccruedPremiumCalculator
        .calculateAccruedPremium(
          _secondsUntilLastPremiumAccrual,
          _secondsUntilLatestPayment,
          protectionInfo.K,
          protectionInfo.lambda
        );

      console.log(
        "accruedPremium from second %s to %s: ",
        _secondsUntilLastPremiumAccrual,
        _secondsUntilLatestPayment,
        _accruedPremiumIn18Decimals
      );

      /// Scale the premium amount to underlying decimals
      _accruedPremiumInUnderlying = scale18DecimalsAmtToUnderlyingDecimals(
        _accruedPremiumIn18Decimals,
        poolInfo.underlyingToken.decimals()
      );
    }
  }

Discussion

vnadoda

@clems4ev3r @hrishibhat This will be fixed with daily premium accrual change for #294

vnadoda

@clems4ev3r Fix for this issue is in PR: https://github.com/carapace-finance/credit-default-swaps-contracts/pull/57

clems4ev3r

Fix looks good

The original report as published on Sherlock, by chaduke. 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 function verifyAndAccruePremium() returns early when the latest payment timestamp is before the protection start timestamp, without checking whether the protection has actually expired.

Impact

Some protection buyers might never be able to renew their protections, and getActiveProtections() might return protections that should have expired.

What the attacker needed

No payment made for a long time; protection start timestamp after last payment

The fix

The function verifyAndAccruePremium() was revised to check expiration before the early return, and the fix was confirmed by the team.

How it was found

  1. The renewal check verifyBuyerCanRenewProtection() looks for an expired protection record for the same lending pool and position token ID.
  2. The expired protection record is only created when expireProtection() is called.
  3. expireProtection() is called only if verifyAndAccruePremium() returns that the protection has expired.
  4. verifyAndAccruePremium() returns false for expiration when the latest payment timestamp is before the protection start timestamp.
  5. If no payment is made for a long time, the protection is never marked as expired.
  6. The buyer cannot renew because the renewal check fails to find an expired protection.

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.

In this smart contract, a protection is like an insurance policy. To renew it, the system must first recognise that the old policy has expired. A mistake in the code means that if no payments were made for a while, the system never marks the policy as expired, so the buyer cannot renew it.

What is Business logic?

The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.

More by chaduke

View all

21 more disclosed reports, best first.

More from Carapace

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Business logic flaws

The lesson behind this report.

The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.