Halborn Logo

icon

Gorples SOL Chef - Entangle Labs


Prepared by:

Halborn Logo

HALBORN

Last Updated 07/29/2024

Date of Engagement by: June 12th, 2024 - June 25th, 2024

Summary

100% of all REPORTED Findings have been addressed

All findings

4

Critical

0

High

0

Medium

0

Low

2

Informational

2


1. Introduction

Entangle Labs team engaged Halborn to conduct a security assessment on their Gorples Chef (ex Borpa) program beginning on June 12th, 2024 and ending on June 25th, 2024. The security assessment was scoped to the Solana Program provided in the GitHub repository gorples-solana, commit hashes, and further details can be found in the Scope section of this report.

Gorples (ex Borpa) is releasing SOL Chef Solana Program, a middleware software to integrate the Gorples Farm program with the Raydium decentralized exchange. The program consists in both administrative instructions and also one user-facing instruction.

The administrative instructions are able to configure important state in the Gorples Chef program, such as creating a pool through CPI to theraydium_amm_v3 program, add and remove liquidity to/from the pool, withdraw fees from the pool, set a pool admin, and set buyback configuration. Namely, the administrative operations are: initialize, add_pool, add_liquidity, remove_liquidity, set_admin, set_buyback_config and withdraw_fees. The user-facing instruction is the swap instruction.

2. Assessment Summary

Halborn was provided 2 weeks for the engagement and assigned two full-time security engineers to review the security of the Solana Program in scope. The engineers are blockchain and smart contract security experts with advanced smart contract hacking skills, and deep knowledge of multiple blockchain protocols.

The purpose of the assessment is to:

    • Identify potential security issues within the codebase.

    • Validate that the Chef program does not introduce new vulnerabilities or weak spots to the Gorples software ecosystem.

    • Check that the integration with the Raydium exchange does not introduce new vulnerabilities or weak spots to the Gorples software ecosystem.

In summary, Halborn did not identify any significant security risks, but low-severity findings were acknowledged and accepted by the Entangle team. The main ones were:

    • Risky slippage values can lead to financial loss.

    • Potential arithmetic underflow.

3. Test Approach and Methodology

Halborn performed a combination of a manual review of the source code and automated security testing to balance efficiency, timeliness, practicality, and accuracy in regard to the scope of the program assessment. While manual testing is recommended to uncover flaws in business logic, processes, and implementation; automated testing techniques help enhance coverage of programs 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.

    • Manual program source code review to identify business logic issues.

    • Mapping out possible attack vectors

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

    • Scanning dependencies for known vulnerabilities (cargo audit).


As of the completion of this report, Halborn was not provided with significant documentation or a test suite to verify the correct functioning of the software under audit. Most of our efforts were concentrated on building as many unit tests as possible to validate specific edge cases we identified as potential issues. However, these efforts cannot substitute for a comprehensive test suite developed by the team that created the Gorples Chef Solana program.

We strongly recommend that the Entangle Labs team focuses on two key areas: creating comprehensive documentation that details the system's components, and developing robust unit and integration tests to ensure the system behaves as expected.

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
(a) Repository: gorples-solana
(b) Assessed Commit ID: f1ee2c1
(c) Items in scope:
  • programs/gorples-chef/src/instructions/add_liquidity.rs
  • programs/gorples-chef/src/instructions/add_pool.rs
  • programs/gorples-chef/src/instructions/initialize.rs
↓ Expand ↓
Out-of-Scope:
Out-of-Scope: New features/implementations after the remediation commit IDs.

6. Assessment Summary & Findings Overview

Critical

0

High

0

Medium

0

Low

2

Informational

2

Security analysisRisk levelRemediation Date
Risky slippage values can lead to financial lossLowRisk Accepted
Potential arithmetic underflowLowRisk Accepted
Lack of input validation on set_buyback_configInformationalAcknowledged
Lack of event emission in critical state changesInformationalAcknowledged

7. Findings & Tech Details

7.1 Risky slippage values can lead to financial loss

// Low

Description

During the analysis of the Remove Liquidity, Add Pool, and Swap instructions, it was observed that the slippage value is hard-coded in different instances, as demonstrated:

Remove Liquidity

During the analysis of the handle_remove_liquidity function, part of the Remove Liquidity instruction, it was identified that the values for the variables amount_0_with_slippage and amount_1_with_slippage are based on calculations that are considering 1000 (10% - ten percent) as slippage value when performing the calculation through the amount_with_slippage utility function.

These values are subsequently processed through the amount_0_min and amount_1_min variables, that performs checked_sub with transfer_fee_0 and transfer_fee_1 values, and which will be ultimately used in the CPI to decrease_liquidity_v2.

- src/instructions/remove_liquidity.rs

    let amount_0_with_slippage = amount_with_slippage(amount_0, 1000, false);
    let amount_1_with_slippage = amount_with_slippage(amount_1, 1000, false);

    let amount_0_min = amount_0_with_slippage
        .checked_sub(transfer_fee_0)
        .ok_or(CustomError::Overflow)?;
    let amount_1_min = amount_1_with_slippage
        .checked_sub(transfer_fee_1)
        .ok_or(CustomError::Overflow)?;

    let cpi = CpiContext::new_with_signer(ctx.accounts.raydium.to_account_info(), accounts, seeds);
    raydium_amm_v3::cpi::decrease_liquidity_v2(cpi, liquidity, amount_0_min, amount_1_min)?;

The current calculations take into account a slippage tolerance value of 10% (1000 basis points), which is excessively high for a Remove Liquidity operation. It is important to note that with this setting, up to ten percent of the traded amounts could potentially be lost due to slippage.


Add Pool

Likewise, during the assessment of the handle_add_pool function, it is possible to observe the same behavior, as follows:

- src/instructions/add_pool.rs

    let amount_0_with_slippage = amount_with_slippage(amount_0, 1000, true);
    let amount_1_with_slippage = amount_with_slippage(amount_1, 1000, true);

    let amount_0_max = amount_0_with_slippage.checked_add(transfer_fee_0).unwrap();
    let amount_1_max = amount_1_with_slippage.checked_add(transfer_fee_1).unwrap();

    raydium_amm_v3::cpi::open_position_v2(
        cpi,
        pool_config.tick_lower_index,
        pool_config.tick_upper_index,
        pool_config.tick_array_lower_start_index,
        pool_config.tick_array_upper_start_index,
        liquidity,
        amount_0_max,
        amount_1_max,
        false,
        None,
    )?;

The aforementioned calculations take into account a slippage tolerance value of 10% (1000 basis points), which is excessively high for Add Pool and/or Remove Liquidity operations. It is important to note that with this setting, up to ten percent of the traded amounts could potentially be lost due to slippage, resulting in permanent financial loss.


Swap

In the handle_swap function, which is part of the Swap instruction, it was identified that the value for the parameter other_amount_threshold is hard-coded to 0 (zero).

- src/instructions/swap.rs

        swap_v2(cpi, swap_0_amount, 0, 0, true)?;

        swap_v2(cpi, swap_0_amount, 0, 0, true)?;

Accordingly to the swap_v2, Raydium's CLMM program documentation, other_amount_threshold dictates the slippage tolerance for the swap operation.

In the specific implementation of the handle_swap function, that performs a CPI to the swap_v2 instruction on Raydium's CLMM, where is_base_input is set to true, the expected return value is the max_amount_out.

- raydium-clmm/programs/amm/src/instructions/swap_v2.rs

pub fn swap_v2<'a, 'b, 'c: 'info, 'info>(
    ctx: Context<'a, 'b, 'c, 'info, SwapSingleV2<'info>>,
    amount: u64,
    other_amount_threshold: u64,
    sqrt_price_limit_x64: u128,
    is_base_input: bool,
) -> Result<()> {
    let amount_result = exact_internal_v2(
        ctx.accounts,
        ctx.remaining_accounts,
        amount,
        sqrt_price_limit_x64,
        is_base_input,
    )?;
    if is_base_input {
        require_gte!(
            amount_result,
            other_amount_threshold,
            ErrorCode::TooLittleOutputReceived
        );
    } else {
        require_gte!(
            other_amount_threshold,
            amount_result,
            ErrorCode::TooMuchInputPaid
        );
    }

    Ok(())
}

The practice of hard-coding the other_amount_threshold parameter to 0 (zero) could result in undesirable outcomes, such as loss-making (unprofitable) swap operations. This is because amount_result will always be greater or equal than 0, and therefore, even for a relatively small result for max_amount_out, the transaction would still go through, because of lack of slippage check.

It is strongly advised to avoid hard-coding slippage values when executing Cross-Program Invocations (CPIs), as a safe slippage threshold is essential for transactions to be successfully processed without financial damage.

BVSS
Recommendation

For the Add Pool and Remove Liquidity instructions, it is recommended to use a safe threshold, passed as a parameter, to the slippage value, instead of using hard-coded 1000 units.

For the Swap instruction, it is recommended to add the other_amount_threshold parameter to the handle_swap function, so this parameter does not operate under hard-coded 0 value when performing the CPI to swap_v2.

Additionally, it is recommended to enforce a safe threshold for these parameters, for example, requiring a minimum/maximum value for other_amount_threshold (slippage).


Remediation Plan

RISK ACCEPTED: The Entangle team has accepted the risk related to the issue.

7.2 Potential arithmetic underflow

// Low

Description

During the analysis of the handle_add_liquidity function, it is possible to observe that it takes input_amount, deposit_fee_rate, slippage0 and slippage1 values as parameters.

- src/instructions/add_liquidity.rs

pub fn handle_add_liquidity(
    ctx: Context<AddLiquidity>,
    input_amount: u64,
    deposit_fee_rate: u64,
    slippage0: u64,
    slippage1: u64,
) -> Result<u128> {

After, the value of input_amount is calculated taking into consideration the deposit_fee_rate, as follows:

    let input_amount = input_amount - input_amount * deposit_fee_rate / 10000;

As there is no input validation in place, and also because the aforementioned operation is not using checked wrappers, if deposit_fee_rate value provided as parameter is higher than 10_000, then the variable input_amount will underflow.

BVSS
Recommendation

To address this issue and enhance the security of the code, it is recommended to implement the following improvements:

  1. Add input validation to ensure that the deposit_fee_rate value is within a reasonable and expected range (e.g., between 0 and 10_000). This can be achieved by adding a conditional check before performing the calculation.

  2. Utilize Rust's "checked" wrappers, such as checked_sub(), to ensure that the arithmetic operation does not result in an underflow. If an underflow occurs, the function will return a None value.


Remediation Plan

RISK ACCEPTED: The Entangle team has accepted the risk related to the issue.

7.3 Lack of input validation on set_buyback_config

// Informational

Description

The set_buyback_config entry point is used by the platform admin to set multiple parameters, such as:

  • chest_vault_authority: account with the ability to withdraw from the chest vault. Corresponds to the remaining amount after transferring the fees to the buyback vault.

  • buyback_vault_authority: account with the ability to withdraw from the buyback vault.

  • buyback_share: proportion (over 10000) that's going to be transferred to the buyback vault

The set_buyback_config entry point is not implementing any input validation of these values.

Although validating chest_vault_authority and buyback_vault_authority can be eventually updated later without any major risk different from allowing unexpected authorities, the case for buyback_share

buyback_share is used in withdraw_fees as the snippet below shows:


- src/instructions/withdraw_fees.rs

pub fn handle_withdraw_fees<'info>(
    ctx: Context<'_, '_, '_, 'info, WithdrawFees<'info>>,
) -> Result<()> {
    let bumps = &[ctx.bumps.authority];
    let seed = &[FARM_ROOT, b"AUTHORITY", bumps][..];
    let seeds = &[seed];
    // Send this amount to buyback wallet
    let to_bb = ctx.accounts.wsol_vault.amount * ctx.accounts.chef_config.buyback_share / 10000;
    // Transfer to buyback wallet
    let accounts = TransferChecked {
        from: ctx.accounts.wsol_vault.to_account_info(),
        mint: ctx.accounts.wsol_mint.to_account_info(),
        to: ctx.accounts.wsol_buyback_vault.to_account_info(),
        authority: ctx.accounts.authority.to_account_info(),
    };
    let cpi = CpiContext::new_with_signer(
        ctx.accounts.token_program.to_account_info(),
        accounts,
        seeds,
    );
    transfer_checked(cpi, to_bb, ctx.accounts.wsol_mint.decimals)?;

If by any chance the buyback_share is bigger than 10000, the to_bb parameter value would be bigger than the balance of the wsol_vault, and the transfer in the line 78 will be reverted, blocking the withdraw fees process.

BVSS
Recommendation

We recommend to implement an validation to check that the buyback_share input parameter to be smaller than or equal to 10000.

Remediation Plan

ACKNOWLEDGED: The Entangle team has acknowledged the issue.

7.4 Lack of event emission in critical state changes

// Informational

Description

Events emission is considered a good practice to debug situations where it is necessary to check the parameters used to call an entry point.

Events can also be used to create a monitoring system to check the platform integrity in real time (or as real-time as possible).

The majority of platforms and protocols use use-case specific parameters and accounts for certain operations, so implementing events is a common practice.

In the case of CHEF, we identified at least 4 of these parameters and accounts:

  • chest_vault_authority (ChefConfig, changed in set_buyback_config)

  • buyback_vault_authority (ChefConfig, changed in set_buyback_config)

  • buyback_share (ChefConfig, changed in set_buyback_config)

  • admin (ChefConfig, changed in set_admin)

For the cases mentioned above, in none of them an event is emitted.


Score
Recommendation

Implement logic to emit events in the mentioned functions every time any of the mentioned parameters and accounts is changed.

Remediation Plan

ACKNOWLEDGED: The Entangle team has acknowledged the issue.

8. Automated Testing

Description

Halborn used automated security scanners to assist with detection of well-known security issues and vulnerabilities. Among the tools used was cargo audit, a security scanner for vulnerabilities reported to the RustSec Advisory Database. All vulnerabilities published in https://crates.io are stored in a repository named The RustSec Advisory Database. cargo audit is a human-readable version of the advisory database which performs a scanning on Cargo.lock. Security Detections are only in scope. All vulnerabilities shown here were already disclosed in the above report. However, to better assist the developers maintaining this code, the auditors are including the output with the dependencies tree, and this is included in the cargo audit output to better know the dependencies affected by unmaintained and vulnerable crates.

Results

ID

package

Short Description

RUSTSEC-2022-0093

ed25519-dalek

Double Public Key Signing Function Oracle Attack on ed25519-dalek

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.