Halborn Logo

Hub/Spokes Library V1 - Concrete


Prepared by:

Halborn Logo

HALBORN

Last Updated 10/15/2024

Date of Engagement by: August 12th, 2024 - September 10th, 2024

Summary

100% of all REPORTED Findings have been addressed

All findings

5

Critical

2

High

1

Medium

0

Low

1

Informational

1


1. Introduction

Concrete engaged Halborn to conduct a security assessment on their smart contracts related to Hub/Spokes libraries beginning on 2024-08-12 and ending on 2024-09-10. The security assessment was scoped to the smart contracts provided in directly be the team.

Commit hashes and further details can be found in the Scope section of this report.

2. Assessment Summary

Halborn was provided four weeks for the engagement and assigned one full-time security engineer to check the security of the smart contract. The security engineer is a blockchain and smart-contract security expert with advanced penetration testing, smart-contract hacking, and deep knowledge of multiple blockchain protocols.

The purpose of this assessment is to:

    •  Ensure that smart contract functions operate as intended.

    • Identify potential security issues with the smart contracts.

In summary, Halborn identified several security concerns that were mostly addressed by the Concrete team.

3. Test Approach and Methodology

Halborn performed a combination of manual review of the code and automated security testing to balance efficiency, timeliness, practicality, and accuracy in regard to the scope of the smart contract assessment. While manual testing is recommended to uncover flaws in logic, process, and implementation; automated testing techniques help enhance coverage of smart contracts and can quickly identify items that do not follow security best practices. The following phases and associated tools were used throughout the term of the assessment:

    • Research into the architecture, purpose, and use of the platform.

    • Smart contract manual code review and walkthrough to identify any logic issue.

    • Thorough assessment of safety and usage of critical Solidity variables and functions in scope that could lead to arithmetic related vulnerabilities.

    • Manual testing by custom scripts.

    • Graphing out functionality and contract logic/connectivity/functions (solgraph).

    • Static Analysis of security for scoped contract, and imported functions. (Slither).

    • Local or public testnet deployment (Foundry, Remix IDE).


4. RISK METHODOLOGY

Every vulnerability and issue observed by Halborn is ranked based on two sets of Metrics and a Severity Coefficient. This system is inspired by the industry standard Common Vulnerability Scoring System.
The two Metric sets are: Exploitability and Impact. Exploitability captures the ease and technical means by which vulnerabilities can be exploited and Impact describes the consequences of a successful exploit.
The Severity Coefficients is designed to further refine the accuracy of the ranking with two factors: Reversibility and Scope. These capture the impact of the vulnerability on the environment as well as the number of users and smart contracts affected.
The final score is a value between 0-10 rounded up to 1 decimal place and 10 corresponding to the highest security risk. This provides an objective and accurate rating of the severity of security vulnerabilities in smart contracts.
The system is designed to assist in identifying and prioritizing vulnerabilities based on their level of risk to address the most critical issues in a timely manner.

4.1 EXPLOITABILITY

Attack Origin (AO):
Captures whether the attack requires compromising a specific account.
Attack Cost (AC):
Captures the cost of exploiting the vulnerability incurred by the attacker relative to sending a single transaction on the relevant blockchain. Includes but is not limited to financial and computational cost.
Attack Complexity (AX):
Describes the conditions beyond the attacker’s control that must exist in order to exploit the vulnerability. Includes but is not limited to macro situation, available third-party liquidity and regulatory challenges.
Metrics:
EXPLOITABILIY METRIC (mem_e)METRIC VALUENUMERICAL VALUE
Attack Origin (AO)Arbitrary (AO:A)
Specific (AO:S)
1
0.2
Attack Cost (AC)Low (AC:L)
Medium (AC:M)
High (AC:H)
1
0.67
0.33
Attack Complexity (AX)Low (AX:L)
Medium (AX:M)
High (AX:H)
1
0.67
0.33
Exploitability EE is calculated using the following formula:

E=meE = \prod m_e

4.2 IMPACT

Confidentiality (C):
Measures the impact to the confidentiality of the information resources managed by the contract due to a successfully exploited vulnerability. Confidentiality refers to limiting access to authorized users only.
Integrity (I):
Measures the impact to integrity of a successfully exploited vulnerability. Integrity refers to the trustworthiness and veracity of data stored and/or processed on-chain. Integrity impact directly affecting Deposit or Yield records is excluded.
Availability (A):
Measures the impact to the availability of the impacted component resulting from a successfully exploited vulnerability. This metric refers to smart contract features and functionality, not state. Availability impact directly affecting Deposit or Yield is excluded.
Deposit (D):
Measures the impact to the deposits made to the contract by either users or owners.
Yield (Y):
Measures the impact to the yield generated by the contract for either users or owners.
Metrics:
IMPACT METRIC (mIm_I)METRIC VALUENUMERICAL VALUE
Confidentiality (C)None (I:N)
Low (I:L)
Medium (I:M)
High (I:H)
Critical (I:C)
0
0.25
0.5
0.75
1
Integrity (I)None (I:N)
Low (I:L)
Medium (I:M)
High (I:H)
Critical (I:C)
0
0.25
0.5
0.75
1
Availability (A)None (A:N)
Low (A:L)
Medium (A:M)
High (A:H)
Critical (A:C)
0
0.25
0.5
0.75
1
Deposit (D)None (D:N)
Low (D:L)
Medium (D:M)
High (D:H)
Critical (D:C)
0
0.25
0.5
0.75
1
Yield (Y)None (Y:N)
Low (Y:L)
Medium (Y:M)
High (Y:H)
Critical (Y:C)
0
0.25
0.5
0.75
1
Impact II is calculated using the following formula:

I=max(mI)+mImax(mI)4I = max(m_I) + \frac{\sum{m_I} - max(m_I)}{4}

4.3 SEVERITY COEFFICIENT

Reversibility (R):
Describes the share of the exploited vulnerability effects that can be reversed. For upgradeable contracts, assume the contract private key is available.
Scope (S):
Captures whether a vulnerability in one vulnerable contract impacts resources in other contracts.
Metrics:
SEVERITY COEFFICIENT (CC)COEFFICIENT VALUENUMERICAL VALUE
Reversibility (rr)None (R:N)
Partial (R:P)
Full (R:F)
1
0.5
0.25
Scope (ss)Changed (S:C)
Unchanged (S:U)
1.25
1
Severity Coefficient CC is obtained by the following product:

C=rsC = rs

The Vulnerability Severity Score SS is obtained by:

S=min(10,EIC10)S = min(10, EIC * 10)

The score is rounded up to 1 decimal places.
SeverityScore Value Range
Critical9 - 10
High7 - 8.9
Medium4.5 - 6.9
Low2 - 4.4
Informational0 - 1.9

5. SCOPE

Files and Repository
(b) Assessed Commit ID: db3349a
(c) Items in scope:
  • src/libraries/AddressLib.sol
  • src/libraries/CompactEncodeLib.sol
  • src/libraries/CreditInfo.sol
↓ Expand ↓
Out-of-Scope:
Remediation Commit ID:
Out-of-Scope: New features/implementations after the remediation commit IDs.

6. Assessment Summary & Findings Overview

Critical

2

High

1

Medium

0

Low

1

Informational

1

Security analysisRisk levelRemediation Date
Inconsistent Bit Shifting Leading To Incorrect Permission HandlingCriticalSolved - 09/25/2024
Incorrect Encoding Due To Operation PrecedenceCriticalSolved - 09/25/2024
Incorrect Logical Operator In Tranche ValidationHighSolved - 09/26/2024
Missing Total Tranche Amount ValidationLowSolved - 09/25/2024
Inadequate Bit Encoding In encodeRightsFromFlags FunctionInformationalAcknowledged

7. Findings & Tech Details

7.1 Inconsistent Bit Shifting Leading To Incorrect Permission Handling

// Critical

Description

In the permission management system defined in the Uint8CodecLib contract there is an inconsistency in how byte positions are handled between encoding and decoding functions.

In the _updateNthByte function, which is responsible for updating a specific byte within a 256-bit encoding, the position is treated as a bit index. Bitwise operations use position directly without converting it to bits (i.e., without multiplying by 8).

    function _updateNthByte(uint256 encoding, uint8 newValue, uint8 position) private pure returns (uint256) {
        // Create a mask with the relevant bits set to 0
        uint256 mask = ((uint256(type(uint8).max)) << position);
        // Clear the relevant bits in the originalValue and set them to the new value
        return (encoding & ~mask) | ((uint256(newValue) << position) & mask);
    }

However, the _decodeNthByte function treats n (equivalent to position) as a byte index and multiplies it by 8 to shift by the correct number of bits during decoding.

    function _decodeNthByte(uint256 data, uint8 n) private pure returns (uint8) {
        return uint8((data >> (8 * n)) & 0xFF);
    }

This inconsistency causes the encoding and decoding processes to operate on different bit positions. As a result, when attempting to set a permission value in a specific byte, the value is stored in an unexpected location within the provided encoding. Consequently, retrieving the permission using the decoding function returns incorrect results, leading to broken permissions system.

Proof of Concept
    function test_updateProtocolPermission() public pure {
        uint256 encoding = 0;
        uint256 encodeConcreteerPermissions = Uint8CodecLib.updateConcreteerPermission(0, 3);
        uint256 encodeHubAnyonePermissions = Uint8CodecLib.updateHubAnyonePermission(encodeConcreteerPermissions, 3);
        uint256 encodeRemoteAnyonePermissions = Uint8CodecLib.updateRemoteAnyonePermission(encodeHubAnyonePermissions, 3);
        uint256 encodeRemoteProtocolPermission = Uint8CodecLib.updateRemoteProtocolProxyPermission(encodeRemoteAnyonePermissions, 3);


        uint8 decodedConcreteerPermision = Uint8CodecLib.getConcreteerPermission(encodeConcreteerPermissions);
        assertNotEq(decodedConcreteerPermision, 3);

        uint8 decodeHubAnyonePermissions = Uint8CodecLib.getHubAnyonePermission(encodeHubAnyonePermissions);
        assertNotEq(decodeHubAnyonePermissions, 3);

        uint8 decodeRemoteAnyonePermissions = Uint8CodecLib.getRemoteAnyonePermission(encodeRemoteAnyonePermissions);
        assertNotEq(decodeRemoteAnyonePermissions, 3);

        uint8 decodeRemoteProtocolPermission = Uint8CodecLib.getRemoteProtocolProxyPermission(encodeRemoteProtocolPermission);
        assertNotEq(decodeRemoteProtocolPermission, 3);
    }

Captura de pantalla 2024-10-15 a las 12.25.44.png
BVSS
Recommendation

Standardize the bit-shifting operations in both encoding and decoding functions to use consistent units.

function _updateNthByte(uint256 encoding, uint8 newValue, uint8 position) private pure returns (uint256) {
    uint256 shift = uint256(position) * 8; // Convert position to bits
    uint256 mask = (uint256(0xFF) << shift);
    // Clear the target byte and set the new value
    return (encoding & ~mask) | (uint256(newValue) << shift);
}
Remediation

SOLVED: The Concrete team fixed the issue as recommended.

Remediation Hash
References

7.2 Incorrect Encoding Due To Operation Precedence

// Critical

Description

The function encodeFeesAreBorrowedAndCreditInterestsAccrueOnUser is intended to encode two uint8 values,feesAreBorrowed and creditInterestsAccrueOnUser, into a single uint256 by placing them in separate bytes. The feesAreBorrowed should occupy the least significant byte, and creditInterestsAccrueOnUser should be shifted left by 8 bits to occupy the second byte.

    function encodeFeesAreBorrowedAndCreditInterestsAccrueOnUser(
        uint8 feesAreBorrowed,
        uint8 creditInterestsAccrueOnUser
    ) internal pure returns (uint256) {
        return uint256(feesAreBorrowed) | (creditInterestsAccrueOnUser) << 8;
    }

However the shift operation is not executed as intended. This is becauses the bitwise OR operation occurs before the shift, resulting in the creditInterestsAccrueOnUser value being encoded incorrectly then shifted, which leads to improper encoding and decodeCreditInterestsAccrueOnUser check always returns false.

Proof of Concept
    function test_encodeFeesAreBorrowedAndCreditInterestsAccrueOnUser() public pure{
        for(uint256 i; i<type(uint8).max; i++){
            uint256 encoded = Uint8CodecLib.encodeFeesAreBorrowedAndCreditInterestsAccrueOnUser(1, 1);
            assertNotEq(Uint8CodecLib.decodeCreditInterestsAccrueOnUser(encoded), true);
        }
    }

Captura de pantalla 2024-10-15 a las 12.30.08.png
BVSS
Recommendation

Modify the encoding function to enforce the correct order of operations by adding explicit parentheses and appropriate type casting:

return uint256(feesAreBorrowed) | (uint256(creditInterestsAccrueOnUser) << 8)
Remediation

SOLVED: The Concrete team fixed the issue. The function was removed from the contract.

Remediation Hash
References

7.3 Incorrect Logical Operator In Tranche Validation

// High

Description

The getTrancheAmountFractionInWad and getTrancheFeeFractionInWad functions from ProtectionLibV1 aims to extract a fraction value associated with a specific tranche from a packed uint256 encoding. They both uses the same condition to validate the tranche.

        if ((tranche < 1) && (tranche > numberOfTranches)) revert Errors.InvalidTrancheNumber(tranche);

The condition uses the logical AND operator (&&), which means the revert statement will only be executed if both conditions are true simultaneously. A tranche number cannot be both less than 1 and greater than numberOfTranches at the same time. These two conditions are mutually exclusive.

As a result, invalid tranche numbers that are either less than 1 or greater than numberOfTranches will not trigger the revert, potentially leading to incorrect calculations or out-of-bounds errors later in the function.

BVSS
Recommendation

The correct logical operator to use in this context is the OR operator (||):

if ((tranche < 1) || (tranche > numberOfTranches)) revert Errors.InvalidTrancheNumber(tranche);
Remediation

SOLVED: The Concrete team fixed the issue as recommended.

Remediation Hash
References

7.4 Missing Total Tranche Amount Validation

// Low

Description

The function encodeProtectionDataFromAbsoluteValues and encodeProtectionData from ProtectionLibV1 contract, currently checks individual tranche amounts and fees to ensure they do not exceed the promisedAmountInBase.

    function encodeProtectionDataFromAbsoluteValues(
        uint256 promisedAmountInBase,
        ProtectionDataAbsolute memory protectionData
    ) internal pure returns (uint256) {
        if (protectionData.numberOfTranches > 3) revert Errors.NumberOfProtectionClaimsTooHigh();
        if (protectionData.ltvProtectForClaimsInBP > MILLION) revert Errors.FractionExceedsUnityInBP();
        if (protectionData.ltvProtectForForeclosureInBP > MILLION) revert Errors.FractionExceedsUnityInBP();
        if (protectionData.openingFeeInBase > promisedAmountInBase) {
            revert Errors.OpeningFeeExceedsPromisedAmount();
        }
        if (protectionData.cancellationFeeInBase > promisedAmountInBase) {
            revert Errors.CancellationFeeExceedsPromisedAmount();
        }
        if (protectionData.trancheAmountInBase.length != protectionData.numberOfTranches) {
            revert Errors.InvalidTrancheNumber(uint8(protectionData.trancheAmountInBase.length));
        }
        if (protectionData.trancheFeeInBase.length != protectionData.numberOfTranches) {
            revert Errors.InvalidTrancheNumber(uint8(protectionData.trancheFeeInBase.length));
        }
        for (uint8 i = 0; i < protectionData.numberOfTranches; i++) {
            if (protectionData.trancheAmountInBase[i] > promisedAmountInBase) {
                revert Errors.TrancheAmountExceedsPromisedAmount(i + 1);
            }
            if (protectionData.trancheFeeInBase[i] > promisedAmountInBase) {
                revert Errors.TrancheFeeExceedsPromisedAmount(i + 1);
            }
    function encodeProtectionData(ProtectionData memory protectionData) internal pure returns (uint256) {
        if (protectionData.numberOfTranches > 3) revert Errors.NumberOfProtectionClaimsTooHigh();
        if (protectionData.ltvProtectClaims > MILLION) revert Errors.FractionExceedsUnityInMillionth();
        if (protectionData.ltvProtectForeclosure > MILLION) revert Errors.FractionExceedsUnityInMillionth();
        if (protectionData.openingFeeRate > MILLION) revert Errors.FractionExceedsUnityInMillionth();
        if (protectionData.cancellationFeeRate > MILLION) revert Errors.FractionExceedsUnityInMillionth();
        if (protectionData.trancheAmountFractionInMillionth.length != protectionData.numberOfTranches) {
            revert Errors.InvalidTrancheNumber(uint8(protectionData.trancheAmountFractionInMillionth.length));
        }
        if (protectionData.trancheFeeRateInMillionth.length != protectionData.numberOfTranches) {
            revert Errors.InvalidTrancheNumber(uint8(protectionData.trancheFeeRateInMillionth.length));
        }
        for (uint8 i = 0; i < protectionData.numberOfTranches; i++) {
            if (protectionData.trancheAmountFractionInMillionth[i] > MILLION) {
                revert Errors.FractionExceedsUnityInMillionth();
            }

However, it fails to verify whether the cumulative sum of all tranche amounts exceeds the promisedAmountInBase. This oversight could allow the total amount of tranches to surpass the promised amount, leading to potential discrepancies in the contracts logic.

Proof of Concept
    function test_tranchesShouldNoGreaterPromisedAmount() external {
        uint256 promisedAmountInCollateral = 100 ether;
        
        uint256[] memory trancheAmountInCollateral = new uint256[](3);
        uint256[] memory trancheFeeInCollateral = new uint256[](3);

        trancheAmountInCollateral[0] = 100 ether;
        trancheAmountInCollateral[1] = 100 ether;
        trancheAmountInCollateral[2] = 100 ether;

        trancheFeeInCollateral[0] = 10 ether;
        trancheFeeInCollateral[1] = 10 ether;
        trancheFeeInCollateral[2] = 10 ether;

        ProtectionDataAbsolute memory protectionDataAbsolute = ProtectionDataAbsolute({
            endTime: uint40(block.timestamp + DURATION), 
            numberOfTranches: 3,
            protocolRights: 0,
            remoteProxyRights: 0,
            remoteConcreteerRights: 0,
            remotePublicRights: 0,
            ltvProtectForClaimsInBP: concreteClaimBufferInBP, 
            ltvProtectForForeclosureInBP: concreteForeclosureBufferInBP,
            openingFeeInBase: 1 ether,  
            cancellationFeeInBase: 1 ether,
            trancheAmountInBase: trancheAmountInCollateral,
            trancheFeeInBase: trancheFeeInCollateral
        });
        //This should revert
        ProtectionLibV1.encodeProtectionDataFromAbsoluteValues(promisedAmountInCollateral, protectionDataAbsolute);
    }
BVSS
Recommendation

It is recommended to add checks to validate the cumulative sum of all tranche amounts does not exceed the promisedAmountInBase.

Remediation

SOLVED: The Concrete team resolved the issue as recommended.

Remediation Hash
References

7.5 Inadequate Bit Encoding In encodeRightsFromFlags Function

// Informational

Description

The encodeRightsFromFlags function aims to encode four boolean flags into specific bits within a uint8 value.

    function encodeRightsFromFlags(
        bool protocolCanIntervene,
        bool remoteProxyCanIntervene,
        bool remoteConcreteerCanIntervene,
        bool remotePublicCanIntervene
    ) internal pure returns (uint8) {
        return (protocolCanIntervene ? 0 : 3) | (remoteProxyCanIntervene ? (3 << 2) : 0)
            | (remoteConcreteerCanIntervene ? (3 << 4) : 0) | (remotePublicCanIntervene ? (3 << 6) : 0);
    }

However, the ternary operations are applied inconsistently:

  • For protocolCanIntervene, when the flag is true, it sets the bits to 0 - when false, it sets them to 3.

  • For the other flags, when the flag is true, it sets the bits to shifted 3 - when false, it sets them to 0.


This reversal of logic causes the bits to be incorrectly set, leading to potential misinterpretation of access rights.

Score
Recommendation

Consider adjusting the function to use consistent logic across all flags.

Remediation

ACKNOWLEDGED: The Concrete team acknowledged the issue. This is intention. The default rights setting ought to be that the rights for the protocol are enabled, but for the others not. Since in the EVM by default every uint256 value (such as the protocol Info encoding) is zero, it would be great to reflect the default rights encoding also in this case, e.g. where no protection exists (i.e. the protocol Info = 0). The team solved this issue by reversing the rights encoding for the protocol vs. the other parties. For the protocol, the default is that it can close and foreclose and claim and reclaim.

References

Halborn strongly recommends conducting a follow-up assessment of the project either within six months or immediately following any material changes to the codebase, whichever comes first. This approach is crucial for maintaining the project’s integrity and addressing potential vulnerabilities introduced by code modifications.

© Halborn 2024. All rights reserved.