Swaylend Protocol - Swaylend


Prepared by:

Halborn Logo

HALBORN

Last Updated 09/20/2024

Date of Engagement: August 26th, 2024 - September 10th, 2024

Summary

100% of all REPORTED Findings have been addressed

All findings

3

Critical

0

High

1

Medium

2

Low

0

Informational

0


1. Introduction

Reserve Labs engaged Halborn to conduct a security assessment on their lending project, beginning on August 26, 2024, and ending on September 10, 2024. The security assessment was scoped to cover their swaylend-monorepo GitHub repository, located at https://github.com/Swaylend/swaylend-monorepo with commit ID 5d7b294035c14e62980c2bdabf9ac51d394235c0.


2. Assessment Summary

The team at Halborn was provided two weeks for the engagement and assigned one full-time security engineer to assess the security of the smart contracts. 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 achieve the following:

    • Ensure that the system operates as intended.

    • Identify potential security issues.

    • Identify lack of best practices within the codebase.

    • Identify systematic risks that may pose a threat in future releases.

In summary, Halborn identified some security issues that were successfully addressed by the Reserve Labs team.

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

    • Manual code review and walkthrough.

    • Manual testing by custom scripts.

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:
EXPLOITABILITY 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
(a) Repository: swaylend-monorepo
(b) Assessed Commit ID: 5d7b294
(c) Items in scope:
  • contracts/token/src/main.sw
  • contracts/market/src/main.sw
Out-of-Scope:
Remediation Commit ID:
Out-of-Scope: New features/implementations after the remediation commit IDs.

6. Assessment Summary & Findings Overview

Critical

0

High

1

Medium

2

Low

0

Informational

0

Impact x Likelihood

HAL-01

HAL-02

HAL-03

Security analysisRisk levelRemediation Date
Missing funds validation in update_price_feedsHighSolved - 09/13/2024
Missing staleness checks in oracle queriesMediumSolved - 09/13/2024
Missing price feed validationMediumSolved - 09/13/2024

7. Findings & Tech Details

7.1 Missing funds validation in update_price_feeds

//

High

Description

The function update_price_feeds is responsible of updating the Pyth oracle by paying a given fee and pushing the most recent price (as Pyth oracles follow a push-like behavior where users are the ones which update the price feed at will). However, it is not checked that the funds sent by the user are indeed the passed update_fee, so such amount is retrieved from the internal balances of the market (which is a loss of funds for depositors).

Proof of Concept

The function update_price_feeds is responsible of updating the Pyth price feed from within the market contract. However, Pyth oracles need a fee being paid upfront, as seen in

https://github.com/pyth-network/pyth-crosschain/blob/e3d8bfeff19906afc9640a52cadc165473560ff1/target_chains/fuel/contracts/pyth-contract/src/main.sw#L422

#[storage(read, write), payable]
fn update_price_feeds(update_data: Vec<Bytes>) {
    require(
        msg_asset_id() == AssetId::base(),
        PythError::FeesCanOnlyBePaidInTheBaseAsset,
    );

    ...

    let required_fee = total_fee(total_number_of_updates, storage.single_update_fee);
    require(msg_amount() >= required_fee, PythError::InsufficientFee);

    ...
}

For that, the function update_price_feeds and its internal version calls update_price_feeds in the oracle endpoint and passes as fee update_fee. However, it does not check that the msg.value is equal to update_fee, so it is possible to update the price feeds by sending funds from the market balance instead of the caller assets.

#[payable, storage(read)]
fn update_price_feeds_internal(update_fee: u64, update_data: Vec<Bytes>) {
    let contract_id = storage.pyth_contract_id.read();
    require(contract_id != ZERO_B256, Error::OracleContractIdNotSet);

    let oracle = abi(PythCore, contract_id);
    oracle.update_price_feeds {
        asset_id: FUEL_ETH_BASE_ASSET_ID, coins: update_fee
    } // @audit not checked update_fee == msg.value
    (update_data);
}
BVSS
Recommendation

Require that the passed value is equal to the update_fee argument to avoid using market's funds.

Remediation

SOLVED: The code now checks for the passed amount to be higher or equal than update_fee and the token passed is ETH.

Remediation Hash

7.2 Missing staleness checks in oracle queries

//

Medium

Description

When using third-party oracles, it is recommended to check the timestamp of a price feed against a staleness factor to avoid using a stale price that did not reflect the real value of the underlying asset. However, this is not done in the lending market in scope, which triggers serious issues as stated in the next section.

Proof of Concept

In Fuel, Pyth price feeds follow the next structure:

https://github.com/pyth-network/pyth-crosschain/blob/e3d8bfeff19906afc9640a52cadc165473560ff1/target_chains/fuel/contracts/pyth-interface/src/data_structures/price.sw#L20C1-L31C2

pub struct Price {
    // Confidence interval around the price
    pub confidence: u64,
    // Price exponent
    // This value represents the absolute value of an i32 in the range -255 to 0. Values other than 0, should be considered negative:
    // exponent of 5 means the Pyth Price exponent was -5
    pub exponent: u32,
    // Price
    pub price: u64,
    // The TAI64 timestamp describing when the price was published
    pub publish_time: u64,
}

to check the staleness of the price feed, the protocol using it must check for publish_time to not be too far in the past. However, it is not done in get_price_internal:

// # 10. Pyth Oracle management
#[storage(read)]
fn get_price_internal(price_feed_id: PriceFeedId) -> Price {
    let contract_id = storage.pyth_contract_id.read();
    require(contract_id != ZERO_B256, Error::OracleContractIdNotSet);
        
    let oracle = abi(PythCore, contract_id);
    let price = oracle.price(price_feed_id);
    price
}

As Pyth oracles follow a push behavior, where the price feed is not updated until a third actor updates it, then it is possible for users to "game" the market by interacting with it where the Pyth oracle returns a favorable price that does not reflect the real value of the asset, update it, and then gain advantage of it by interacting again /for example, borrowing more assets than the real value of its collateral.

BVSS
Recommendation

Check publish_time to not be too far in the past against a staleness factor.

Remediation

SOLVED: The code now checks for the price publish time to not be too far in the future nor in the past.

Remediation Hash

7.3 Missing price feed validation

//

Medium

Description

The get_price_internal function does not perform input validation on the price, confidence, and exponent values returned from the called price feed, which can lead to the contract accepting invalid or untrusted prices. Those values should be checked as clearly stated in the official documentation.

Proof of Concept

The function is as follows:

// # 10. Pyth Oracle management
#[storage(read)]
fn get_price_internal(price_feed_id: PriceFeedId) -> Price {
    let contract_id = storage.pyth_contract_id.read();
    require(contract_id != ZERO_B256, Error::OracleContractIdNotSet);
        
    let oracle = abi(PythCore, contract_id);
    let price = oracle.price(price_feed_id);
    price
}

which can be seen does not perform any type of input validation.

BVSS
Recommendation

The function should revert the transaction if one of the following conditions is triggered:

  • price == 0

  • confidence > 0 && (price / confidence) < MIN_CONF_RATIO for a given MIN_CONF_RATIO

Remediation

SOLVED: The recommended checks are now done in function get_price_internal.

Remediation Hash
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 2025. All rights reserved.