Skip to content

The fuels-ts typescript SDK has no awareness of to-be-spent transactions

Low severity GitHub Reviewed Published Jul 30, 2024 in FuelLabs/fuels-ts • Updated Jul 30, 2024

Package

npm @fuel-ts/account (npm)

Affected versions

< 0.93.0

Patched versions

0.93.0

Description

Brief/Intro

The typescript SDK has no awareness of to-be-spent transactions causing some transactions to fail or silently get pruned as they are funded with already used UTXOs.

The Typescript SDK provides the fund function which retrieves UTXOs, which belong to the owner and can be used to fund the request in question, from fuel's graphql api. These then get added to the request making it possible to send it to the network as it now has inputs which can be spent by its outputs. Now this works when a user only wants to fund one transaction per block as in the next block, the spent UTXO will not exist anymore. However if a user wants to fund multiple transactions within one block, the following can happen:

It is important to note, that the graphql API will return a random UTXO which has enough value to fund the transaction in question.

  • user has 2 spendable UTXOs in their wallet which can cover all expenses
  • user funds transaction tA with an input gotten from the API iA
  • user submits tA to fuel
  • iA is still in possession of the user as no new block has been produced
  • user funds a transaction tB and gets the same input iA from the API
  • user tries to submit transaction tB to fuel but now one of the following can happen:
    • if the recipient and all other parameters are the same as in tA, submission will fail as tB will have the same txHash as tA
    • if the parameters are different, there will be a collision in the txpool and tA will be removed from the txpool

Vulnerability Details

The problem occurs, because the fund function in fuels-ts/packages/account/src/account.ts gets the needed ressources statelessly with the function getResourcesToSpend without taking into consideration already used UTXOs:

 async fund<T extends TransactionRequest>(request: T, params: EstimatedTxParams): Promise<T> {

    // [...]

    let missingQuantities: CoinQuantity[] = [];
    Object.entries(quantitiesDict).forEach(([assetId, { owned, required }]) => {
      if (owned.lt(required)) {
        missingQuantities.push({
          assetId,
          amount: required.sub(owned),
        });
      }
    });

    let needsToBeFunded = missingQuantities.length > 0;
    let fundingAttempts = 0;
    while (needsToBeFunded && fundingAttempts < MAX_FUNDING_ATTEMPTS) {
      const resources = await this.getResourcesToSpend(
        missingQuantities,
        cacheRequestInputsResourcesFromOwner(request.inputs, this.address)
      ); // @audit-issue here we do not exclude ids we already got and used for another transaction in the current block

      request.addResources(resources);

      // [...]
    }

    // [...]

    return request;
  }

Impact Details

This issue will lead to unexpected SDK behaviour. Looking at the scenario in Brief/Intro, it could have the following impacts for users:

  1. A transaction does not get included in the txpool / in a block
  2. A previous transaction silently gets removed from the txpool and replaced with a new one

Recommendation

I would recommend adding a buffer to the Account class, in which retrieved resources are saved. These can then be provided to getResourcesToSpend to be excluded from future queries but need to be removed from the buffer if their respective transaction fails to be included, in order to be able to use those resources again in such cases.

Proof of Concept

The following PoC transfers 100 coins from wallet2 to wallet after which wallet2 has two UTXOs one with value 100 and one with a very high value (this is printed to the console). Afterwards, wallet will attempt transfering 80 coins back to wallet2 twice in one block, each in a separate transaction. This should work perfectly fine as wallet has two UTXOs where each can cover the cost of each respective transaction. Now when running this one of the following will happen:

  1. both transfers from wallet to wallet2 get a different UTXO. This is the case if execution is successful and wallet2 has 80 coins more than wallet in the end.
  2. both transfers get the same UTXO. In this case the script will fail and throw an error as then both transactions will have the same hash

In order to execute this PoC, please deploy a local node with a blocktime of 5secs as I wrote my PoC for that blocktime. Note that with a small change it will also work with other blocktimes. Then add the PoC to a file poc_resources.ts and compile it with tsc poc_resources.ts. Finally execute it with node poc_resources.js.

Since the choice which UTXO is taken as input is random, it might take a few tries to trigger the bug!

import { JsonAbi, Script, Provider, WalletUnlocked, Account, Predicate, Wallet, CoinQuantityLike, coinQuantityfy, EstimatedTxParams, BN, Coin, AbstractAddress, Address, Contract, ScriptTransactionRequest } from 'fuels';

const abi: JsonAbi = {
  'encoding': '1',
  'types': [
    {
      'typeId': 0,
      'type': '()',
      'components': [],
      'typeParameters': null
    }
  ],
  'functions': [
    {
      'inputs': [],
      'name': 'main',
      'output': {
        'name': '',
        'type': 0,
        'typeArguments': null
      },
      'attributes': null
    }
  ],
  'loggedTypes': [],
  'messagesTypes': [],
  'configurables': []
};

const FUEL_NETWORK_URL = 'http://127.0.0.1:4000/v1/graphql';

async function executeTransaction() {

  const provider = await Provider.create(FUEL_NETWORK_URL);
  
  const wallet: WalletUnlocked = Wallet.fromPrivateKey('0x37fa81c84ccd547c30c176b118d5cb892bdb113e8e80141f266519422ef9eefd', provider);
  const wallet2: WalletUnlocked = Wallet.fromPrivateKey('0xde97d8624a438121b86a1956544bd72ed68cd69f2c99555b08b1e8c51ffd511c', provider);
  const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));


  console.log("Balance wallet before: ", await wallet.getBalance());
  console.log("Balance wallet2 before: ", await wallet2.getBalance());

  wallet2.transfer(wallet.address, 100);

  await sleep(5500);


  await wallet.transfer(wallet2.address, 80);
  console.log('wallet -> wallet2');

  await wallet.transfer(wallet2.address, 80);
  console.log('wallet -> wallet2');

  console.log("Balance wallet after: ", await wallet.getBalance());
  console.log("Balance wallet2 after: ", await wallet2.getBalance());
};

executeTransaction().catch(console.error);

References

@arboleya arboleya published to FuelLabs/fuels-ts Jul 30, 2024
Published by the National Vulnerability Database Jul 30, 2024
Published to the GitHub Advisory Database Jul 30, 2024
Reviewed Jul 30, 2024
Last updated Jul 30, 2024

Severity

Low

CVSS overall score

This score calculates overall vulnerability severity from 0 to 10 and is based on the Common Vulnerability Scoring System (CVSS).
/ 10

CVSS v4 base metrics

Exploitability Metrics
Attack Vector Network
Attack Complexity Low
Attack Requirements Present
Privileges Required Low
User interaction None
Vulnerable System Impact Metrics
Confidentiality None
Integrity Low
Availability None
Subsequent System Impact Metrics
Confidentiality None
Integrity None
Availability None

CVSS v4 base metrics

Exploitability Metrics
Attack Vector: This metric reflects the context by which vulnerability exploitation is possible. This metric value (and consequently the resulting severity) will be larger the more remote (logically, and physically) an attacker can be in order to exploit the vulnerable system. The assumption is that the number of potential attackers for a vulnerability that could be exploited from across a network is larger than the number of potential attackers that could exploit a vulnerability requiring physical access to a device, and therefore warrants a greater severity.
Attack Complexity: This metric captures measurable actions that must be taken by the attacker to actively evade or circumvent existing built-in security-enhancing conditions in order to obtain a working exploit. These are conditions whose primary purpose is to increase security and/or increase exploit engineering complexity. A vulnerability exploitable without a target-specific variable has a lower complexity than a vulnerability that would require non-trivial customization. This metric is meant to capture security mechanisms utilized by the vulnerable system.
Attack Requirements: This metric captures the prerequisite deployment and execution conditions or variables of the vulnerable system that enable the attack. These differ from security-enhancing techniques/technologies (ref Attack Complexity) as the primary purpose of these conditions is not to explicitly mitigate attacks, but rather, emerge naturally as a consequence of the deployment and execution of the vulnerable system.
Privileges Required: This metric describes the level of privileges an attacker must possess prior to successfully exploiting the vulnerability. The method by which the attacker obtains privileged credentials prior to the attack (e.g., free trial accounts), is outside the scope of this metric. Generally, self-service provisioned accounts do not constitute a privilege requirement if the attacker can grant themselves privileges as part of the attack.
User interaction: This metric captures the requirement for a human user, other than the attacker, to participate in the successful compromise of the vulnerable system. This metric determines whether the vulnerability can be exploited solely at the will of the attacker, or whether a separate user (or user-initiated process) must participate in some manner.
Vulnerable System Impact Metrics
Confidentiality: This metric measures the impact to the confidentiality of the information managed by the VULNERABLE SYSTEM due to a successfully exploited vulnerability. Confidentiality refers to limiting information access and disclosure to only authorized users, as well as preventing access by, or disclosure to, unauthorized ones.
Integrity: This metric measures the impact to integrity of a successfully exploited vulnerability. Integrity refers to the trustworthiness and veracity of information. Integrity of the VULNERABLE SYSTEM is impacted when an attacker makes unauthorized modification of system data. Integrity is also impacted when a system user can repudiate critical actions taken in the context of the system (e.g. due to insufficient logging).
Availability: This metric measures the impact to the availability of the VULNERABLE SYSTEM resulting from a successfully exploited vulnerability. While the Confidentiality and Integrity impact metrics apply to the loss of confidentiality or integrity of data (e.g., information, files) used by the system, this metric refers to the loss of availability of the impacted system itself, such as a networked service (e.g., web, database, email). Since availability refers to the accessibility of information resources, attacks that consume network bandwidth, processor cycles, or disk space all impact the availability of a system.
Subsequent System Impact Metrics
Confidentiality: This metric measures the impact to the confidentiality of the information managed by the SUBSEQUENT SYSTEM due to a successfully exploited vulnerability. Confidentiality refers to limiting information access and disclosure to only authorized users, as well as preventing access by, or disclosure to, unauthorized ones.
Integrity: This metric measures the impact to integrity of a successfully exploited vulnerability. Integrity refers to the trustworthiness and veracity of information. Integrity of the SUBSEQUENT SYSTEM is impacted when an attacker makes unauthorized modification of system data. Integrity is also impacted when a system user can repudiate critical actions taken in the context of the system (e.g. due to insufficient logging).
Availability: This metric measures the impact to the availability of the SUBSEQUENT SYSTEM resulting from a successfully exploited vulnerability. While the Confidentiality and Integrity impact metrics apply to the loss of confidentiality or integrity of data (e.g., information, files) used by the system, this metric refers to the loss of availability of the impacted system itself, such as a networked service (e.g., web, database, email). Since availability refers to the accessibility of information resources, attacks that consume network bandwidth, processor cycles, or disk space all impact the availability of a system.
CVSS:4.0/AV:N/AC:L/AT:P/PR:L/UI:N/VC:N/VI:L/VA:N/SC:N/SI:N/SA:N

EPSS score

0.043%
(10th percentile)

Weaknesses

CVE ID

CVE-2024-41945

GHSA ID

GHSA-3jcg-vx7f-j6qf

Source code

Credits

Loading Checking history
See something to contribute? Suggest improvements for this vulnerability.