Halborn Logo

icon

Rover Protocol - Hydrogen Labs


Prepared by:

Halborn Logo

HALBORN

Last Updated 06/14/2024

Date of Engagement by: April 15th, 2024 - April 17th, 2024

Summary

100% of all REPORTED Findings have been addressed

All findings

6

Critical

0

High

0

Medium

1

Low

0

Informational

5


1. Introduction

Hydrogen Labs engaged Halborn to conduct a security assessment on their smart contracts beginning on April 15th, 2024 and ending on April 17th, 2024. The security assessment was scoped to the smart contracts provided in the Hydrogen-Labs/rover-contracts GitHub repository. Commit hashes and further details can be found in the Scope section of this report.

1.1 Assessment Summary

Halborn was provided 3 days for the engagement and assigned 1 full-time security engineer to review the security of the smart contracts in scope. The engineer is a blockchain and smart contract security expert with advanced penetration testing and smart contract hacking skills, and deep knowledge of multiple blockchain protocols.

The purpose of the assessment is to:

    • Identify potential security issues within the smart contracts.

    • Ensure that smart contract functionality operates as intended.

In summary, Halborn identified some issues that were mostly addressed by the Hydrogen Labs team.

1.2 Test Approach and Methodology

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

    • Research into architecture and purpose.

    • Smart contract manual code review and walkthrough.

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

    • Manual assessment of use and safety for the critical Solidity variables and functions in scope to identify any arithmetic related vulnerability classes.

    • Manual testing by custom scripts.

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

    • Testnet deployment (Foundry).


1.3 Out-of-scope

    • External libraries and financial-related attacks.

    • New features/implementations after/with the remediation commit IDs

    • Changes that occur outside of the scope of PRs/Commits.


2. 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.

2.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

2.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}

2.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

3. SCOPE

Files and Repository
(a) Repository: rover-contracts
(b) Assessed Commit ID: 06a64a5
(c) Items in scope:
  • contracts/StakeManager/StakeManagerStorage.sol
  • contracts/StakeManager/IStakeManager.sol
  • contracts/StakeManager/StakeManager.sol
↓ Expand ↓
Out-of-Scope:
Remediation Commit ID:
Out-of-Scope: New features/implementations after the remediation commit IDs.

4. Assessment Summary & Findings Overview

Critical

0

High

0

Medium

1

Low

0

Informational

5

Security analysisRisk levelRemediation Date
Lack of withdraw or un-stake mechanism leads to Locked EtherMediumRisk Accepted
Use internal accounting instead of `address(this).balance` for TVL trackingInformationalSolved - 04/24/2024
New opcodes are not supported by all chains (solidity version >= 0.8.20)InformationalAcknowledged
Missing input validation when assigning address to state variableInformationalSolved - 04/24/2024
Functions unused Internally could be marked ExternalInformationalAcknowledged - 04/24/2024
Event field is missing `indexed` attributeInformationalSolved - 04/24/2024

5. Findings & Tech Details

5.1 Lack of withdraw or un-stake mechanism leads to Locked Ether

// Medium

Description

During the analysis of the StakeManager.sol smart contract, it was identified that it holds two payable functions: depositBTC() and depositBTC(uint256). These two functions can be considered entry-points of the contract, and their main functionality is to provide an interface for users to deposit native currency in exchange for Rover BTC token, in an 1:1 proportion.

- contracts/StakeManager/StakeManager.sol [Lines: 70-90]

    /// @notice Deposits Bitcoin into the protocol without a referral ID, minting rovBTC in return.
    /// @dev This overload serves as a convenience for users without a referral code.
    function depositBTC() external payable {
        depositBTC(0);
    }

    /// @notice Deposits Bitcoin into the protocol, minting rovBTC to represent the deposited value.
    /// @dev Accounts for the total value locked (TVL) and enforces any set maximums. Emits a Deposit event upon success.
    /// @param _referralId Optional referral ID for tracking or rewards.
    function depositBTC(uint256 _referralId) public payable nonReentrant notPaused {
        if (msg.value == 0) revert InvalidZeroInput();

        uint256 totalTVL = calculateTVL();
        if (maxDepositTVL != 0 && totalTVL + msg.value > maxDepositTVL) {
            revert MaxTVLReached();
        }

        uint256 rovBTCToMint = msg.value;
        rovBTC.mint(msg.sender, rovBTCToMint);
        emit Deposit(msg.sender, msg.value, rovBTCToMint, _referralId);
    }

While the staking mechanism is working effectively, by calling the mint function within the scope of the depositBTC(uint256) function, there is no mechanism that allows withdrawals of the deposited amounts.

In summary, there is no handling of the native currency deposited into the contract, whether through an unstaking mechanism, where users could do the opposite transition - depositing Rover BTC tokens and receiving native currency in exchange, or using any other administrative/non-administrative method.

This effectively leads to a scenario where funds are deposited and locked forever into the contract.

Proof of Concept

The following Proof of Concept demonstrates that it is possible to deposit native currency into the contract, while there is no handling for the deposited ether.

- Forge test (forge test --mt testDeposit -vvvv)

    function testDeposit() public {
        vm.deal(seraph, mockAmount);
        vm.startPrank(seraph);
        stakeManager.depositBTC{value: mockAmount}();

        assertEq(rovBTC.balanceOf(address(seraph)), mockAmount);
    }

- Stack traces

  [105572] Halborn_RoverBtc_T::testDeposit()
    ├─ [0] VM::deal(0x0000000000000000000000000000000000000C0a, 1000000000000000000 [1e18])
    │   └─ ← [Return] 
    ├─ [0] VM::startPrank(0x0000000000000000000000000000000000000C0a)
    │   └─ ← [Return] 
    ├─ [84474] TransparentUpgradeableProxy::depositBTC{value: 1000000000000000000}()
    │   ├─ [79538] StakeManager::depositBTC{value: 1000000000000000000}() [delegatecall]
    │   │   ├─ [64714] TransparentUpgradeableProxy::mint(0x0000000000000000000000000000000000000C0a, 1000000000000000000 [1e18])
    │   │   │   ├─ [59772] RovBtcToken::mint(0x0000000000000000000000000000000000000C0a, 1000000000000000000 [1e18]) [delegatecall]
    │   │   │   │   ├─ [7709] TransparentUpgradeableProxy::isRovBTCMinterBurner(TransparentUpgradeableProxy: [0x1d1499e622D69689cdf9004d05Ec547d650Ff211]) [staticcall]
    │   │   │   │   │   ├─ [2767] RoleManager::isRovBTCMinterBurner(TransparentUpgradeableProxy: [0x1d1499e622D69689cdf9004d05Ec547d650Ff211]) [delegatecall]
    │   │   │   │   │   │   └─ ← [Return] true
    │   │   │   │   │   └─ ← [Return] true
    │   │   │   │   ├─ emit Transfer(from: 0x0000000000000000000000000000000000000000, to: 0x0000000000000000000000000000000000000C0a, value: 1000000000000000000 [1e18])
    │   │   │   │   └─ ← [Stop] 
    │   │   │   └─ ← [Return] 
    │   │   ├─ emit Deposit(depositor: 0x0000000000000000000000000000000000000C0a, amount: 1000000000000000000 [1e18], rovBTCMinted: 1000000000000000000 [1e18], referralId: 0)
    │   │   └─ ← [Stop] 
    │   └─ ← [Return] 
    ├─ [1069] TransparentUpgradeableProxy::balanceOf(0x0000000000000000000000000000000000000C0a) [staticcall]
    │   ├─ [627] RovBtcToken::balanceOf(0x0000000000000000000000000000000000000C0a) [delegatecall]
    │   │   └─ ← [Return] 1000000000000000000 [1e18]
    │   └─ ← [Return] 1000000000000000000 [1e18]
    ├─ [0] VM::assertEq(1000000000000000000 [1e18], 1000000000000000000 [1e18]) [staticcall]
    │   └─ ← [Return] 
    └─ ← [Stop] 
traces(01)
BVSS
Recommendation

To remediate this issue and prevent the permanent locking of funds within the contract, it should be implemented an unstaking mechanism or another administrative/non-administrative method to handle the native currency deposited through the depositBTC() and depositBTC(uint256) functions.


Remediation Plan

RISK ACCEPTED: The Hydrogen Labs team has accepted the risk related to this issue.

5.2 Use internal accounting instead of `address(this).balance` for TVL tracking

// Informational

Description

The StakeManager.sol contract relies on the address(this).balance method for fetching the protocol's current TVL. While this represents a straight-forward strategy for Total Value Locked (TVL) calculation, it can lead to inaccuracies, considering that in some edge cases.

For example, in cases where the StakeManager.sol contract receives ether from self-destruction, the native balance in the contract will not reflect the actual Total Value Locked into the protocol through user deposits.

- contracts/StakeManager/StakeManager.sol [Lines: 95-97]

    function calculateTVL() public view returns (uint256 totalTVL) {
        totalTVL = address(this).balance;
    }

Also, ensuring a more sophisticated approach for mapping the users' positions across the protocol would benefit the ecosystem in the long term, providing a more efficient and reliable TVL tracking mechanism.

Score
Recommendation

It is recommended to use an internal accounting mechanism instead of relying on methods like balance or balanceOf when performing operations that calculate the Total Value Locked (TVL).


Remediation Plan

SOLVED: The Hydrogen Labs team has solved this issue by creating an internal accounting mechanism for deposits.

Remediation Hash

5.3 New opcodes are not supported by all chains (solidity version >= 0.8.20)

// Informational

Description

Solc compiler version 0.8.20 switches the default target EVM version to Shanghai. The generated bytecode will include PUSH0 opcodes. The recently released Solc compiler version 0.8.25 switches the default target EVM version to Cancun, so it is also important to note that it also adds-up new opcodes such as TSTORE, TLOAD and MCOPY.

Be sure to select the appropriate EVM version in case you intend to deploy on a chain apart from mainnet, like L2 chains that may not support PUSH0, TSTORE, TLOAD and/or MCOPY, otherwise deployment of your contracts will fail.

Score
Recommendation

It is important to consider the targeted deployment chains before writing smart contracts because, in the future, there might exist a need for deploying the contracts in a network that could not support new opcodes from Shanghai or Cancun EVM versions.


Remediation Plan

ACKNOWLEDGED: The Hydrogen Labs team has acknowledged the risk related to this issue.

5.4 Missing input validation when assigning address to state variable

// Informational

Description

The assessment of the smart contracts in-scope revealed instances where input validation is missing when assigning an address to a state variable. Failing to validate user-provided addresses can lead to unintended consequences and potential security vulnerabilities.

- contracts/RoverBtcToken/RovBtcToken.sol [Line: 39]

	        roleManager = _roleManager;

- contracts/StakeManager/StakeManager.sol [Line: 53]

	        roleManager = _roleManager;

- contracts/StakeManager/StakeManager.sol [Line: 54]

	        rovBTC = _rovBTC;

When an address is not properly validated, it may be assigned an incorrect or malicious value, such as the zero address (address(0)). This can result in broken contract logic, lost funds, or other unintended behavior.


Score
Recommendation

To prevent unintended behavior and potential security vulnerabilities, it is essential to include checks for address(0) when assigning values to address state variables. This can be achieved by adding a simple check to ensure that the assigned address is not equal to address(0) before proceeding with the assignment.


Remediation Plan

SOLVED: The Hydrogen Labs team has solved this issue as recommended.

Remediation Hash

5.5 Functions unused Internally could be marked External

// Informational

Description

Functions that are not called internally can be marked as external instead of public. By doing so, it is possible to optimize gas consumption and improve contract efficiency.

External functions are more gas-efficient than public functions, as they do not create an additional internal function call within the contract.

- contracts/AccessControl/RoleManager.sol [Line: 22]

	    function initialize(address roleManagerAdmin) public initializer {

- contracts/RoverBtcToken/RovBtcToken.sol [Line: 35]

	    function initialize(IRoleManager _roleManager) public initializer {

- contracts/RoverBtcToken/RovBtcToken.sol [Line: 74]

	    function name() public view virtual override returns (string memory) {

- contracts/RoverBtcToken/RovBtcToken.sol [Line: 79]

	    function symbol() public view virtual override returns (string memory) {

- contracts/StakeManager/StakeManager.sol [Line: 51]

	    function initialize(IRoleManager roleManager, IRovBtcToken rovBTC) public initializer {

Score
Recommendation

For functions that are only called externally, and never internally, it is recommended to change the function visibility modifier from public to external.

This small change can lead to gas savings, especially in contracts with high transaction volumes or complex functionality. By marking functions as external when appropriate, developers can enhance the overall performance and cost-effectiveness of their smart contracts.


Remediation Plan

ACKNOWLEDGED: The Hydrogen Labs team has acknowledged this issue.

5.6 Event field is missing `indexed` attribute

// Informational

Description

Indexed event fields facilitate faster access to off-chain tools that analyze events. However, it is important to note that each indexed field consumes additional gas during event emission. Therefore, it is not always advisable to index the maximum number of fields allowed per event (three fields).

If an event has three or more fields and gas usage is not a significant concern, it is recommended to index three fields. On the other hand, if an event has fewer than three fields, it is best to index all of them. By making a well-informed decision on which fields to index, developers can balance the need for quick access to event data with the gas costs associated with event emission.

- contracts/StakeManager/StakeManager.sol [Line: 22]

 	    event Deposit(address indexed depositor, uint256 amount, uint256 rovBTCMinted, uint256 referralId); 	
Score
Recommendation

It is recommended to add the indexed keyword when declaring events, considering the following example:

    event Indexed(
        address indexed from,
        bytes32 indexed id,
        uint indexed value
    );

Remediation Plan

SOLVED: The Hydrogen Labs team has solved this issue by adding the indexed attribute to the field.

Remediation Hash

6. Automated Testing

Introduction

Halborn used automated testing techniques to enhance the coverage of certain areas of the smart contracts in scope. Among the tools used was Slither, a Solidity static analysis framework. After Halborn verified the smart contracts in the repository and was able to compile them correctly into their ABIs and binary format, Slither was run against the contracts. This tool can statically verify mathematical relationships between Solidity variables to detect invalid or inconsistent usage of the contracts' APIs across the entire code-base.


slither(01)

The findings obtained as a result of the Slither scan were reviewed, and the issue related to Locked Ether was included in the report. The other findings were not included in the report because they were determined false positives.

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.