CWE-1339 Base Rascunho

Insufficient Precision or Accuracy of a Real Number

This vulnerability occurs when a program uses a data type or algorithm that cannot accurately represent or calculate the fractional part of a real number, leading to incorrect results in…

Definição

What is CWE-1339?

This vulnerability occurs when a program uses a data type or algorithm that cannot accurately represent or calculate the fractional part of a real number, leading to incorrect results in security-critical operations.
Many security decisions, like financial transactions or cryptographic calculations, depend on extreme numerical precision. When a system uses floating-point arithmetic or other imprecise representations for these tasks, tiny rounding errors can create exploitable gaps. Attackers can manipulate these inaccuracies to trigger incorrect authorization, cause financial loss, or corrupt data. Computers fundamentally struggle to store certain fractional values exactly. Issues arise from finite storage (like limited bits in a float), repeating decimals in binary (like 0.1), or irrational numbers (like pi). The chosen representation may truncate or round the number, causing the program's internal calculation to drift from the mathematically correct result. Developers must therefore select numeric types and libraries that guarantee the required precision for their specific domain.
Impacto no mundo real

Real-world CVEs caused by CWE-1339

  • Chain: series of floating-point precision errors (CWE-1339) in a web browser rendering engine causes out-of-bounds read (CWE-125), giving access to cross-origin data

  • Chain: rounding error in floating-point calculations (CWE-1339) in image processor leads to infinite loop (CWE-835)

  • Chain: machine-learning product can have a heap-based buffer overflow (CWE-122) when some integer-oriented bounds are calculated by using ceiling() and floor() on floating point values (CWE-1339)

  • Chain: insufficient precision (CWE-1339) in random-number generator causes some zero bits to be reliably generated, reducing the amount of entropy (CWE-331)

  • Chain: web browser crashes due to infinite loop - "bad looping logic [that relies on] floating point math [CWE-1339] to exit the loop [CWE-835]"

Como os atacantes a exploram

Trajeto do atacante passo a passo

  1. 1

    Muller's Recurrence is a series that is supposed to converge to the number 5. When running this series with the following code, different implementations of real numbers fail at specific iterations:

  2. 2

    The chart below shows values for different data structures in the rust language when Muller's recurrence is executed to 80 iterations. The data structure f64 is a 64 bit float. The data structures IF are fixed representations 128 bits in length that use the first number as the size of the integer and the second size as the size of the fraction (e.g. I16F112 uses 16 bits for the integer and 112 bits for the fraction). The data structure of Ratio comes in three different implementations: i32 uses a ratio of 32 bit signed integers, i64 uses a ratio of 64 bit signed integers and BigInt uses a ratio of signed integer with up to 2^32 digits of base 256. Notice how even with 112 bits of fractions or ratios of 64bit unsigned integers, this math still does not converge to an expected value of 5.

  3. 3

    On February 25, 1991, during the eve of the Iraqi invasion of Saudi Arabia, a Scud missile fired from Iraqi positions hit a US Army barracks in Dhahran, Saudi Arabia. It miscalculated time and killed 28 people [REF-1190].

  4. 4

    Sleipner A, an offshore drilling platform in the North Sea, was incorrectly constructed with an underestimate of 50% of strength in a critical cluster of buoyancy cells needed for construction. This led to a leak in buoyancy cells during lowering, causing a seismic event of 3.0 on the Richter Scale and about $700M loss [REF-1281].

Exemplo de código vulnerável

Vulnerable Rust

Muller's Recurrence is a series that is supposed to converge to the number 5. When running this series with the following code, different implementations of real numbers fail at specific iterations:

Vulnerável Rust
fn rec_float(y: f64, z: f64) -> f64 
 {

```
   108.0 - ((815.0 - 1500.0 / z) / y);
 }
 fn float_calc(turns: usize) -> f64 
 {
   let mut x: Vec<f64> = vec![4.0, 4.25];
   (2..turns + 1).for_each(|number| 
   {
  	 x.push(rec_float(x[number - 1], x[number - 2]));
   });
   x[turns]
 }
Exemplo de código seguro

Secure Rust

The chart below shows values for different data structures in the rust language when Muller's recurrence is executed to 80 iterations. The data structure f64 is a 64 bit float. The data structures IF are fixed representations 128 bits in length that use the first number as the size of the integer and the second size as the size of the fraction (e.g. I16F112 uses 16 bits for the integer and 112 bits for the fraction). The data structure of Ratio comes in three different implementations: i32 uses a ratio of 32 bit signed integers, i64 uses a ratio of 64 bit signed integers and BigInt uses a ratio of signed integer with up to 2^32 digits of base 256. Notice how even with 112 bits of fractions or ratios of 64bit unsigned integers, this math still does not converge to an expected value of 5.

Seguro Rust
Use num_rational::BigRational;

 fn rec_big(y: BigRational, z: BigRational) -> BigRational
 {

```
   BigRational::from_integer(BigInt::from(108))
  	 - ((BigRational::from_integer(BigInt::from(815))
  	 - BigRational::from_integer(BigInt::from(1500)) / z)
  	 / y)
 }
 fn big_calc(turns: usize) -> BigRational 
 {
   let mut x: Vec<BigRational> = vec![BigRational::from_float(4.0).unwrap(), BigRational::from_float(4.25).unwrap(),];
   (2..turns + 1).for_each(|number| 
   {
  	 x.push(rec_big(x[number - 1].clone(), x[number - 2].clone()));
   });
   x[turns].clone()
 }
What changed: the unsafe sink is replaced (or the input is validated/escaped) so the same payload no longer triggers the weakness.
Lista de verificação de prevenção

How to prevent CWE-1339

  • Implementation / Patching and Maintenance The developer or maintainer can move to a more accurate representation of real numbers. In extreme cases, the programmer can move to representations such as ratios of BigInts which can represent real numbers to extremely fine precision. The programmer can also use the concept of an Unum real. The memory and CPU tradeoffs of this change must be examined. Since floating point reals are used in many products and many locations, they are implemented in hardware and most format changes will cause the calculations to be moved into software resulting in slower products.
Sinais de deteção

How to detect CWE-1339

SAST High

Executar análise estática (SAST) na base de código à procura do padrão inseguro no fluxo de dados.

DAST Moderate

Executar testes dinâmicos de segurança de aplicações (DAST) contra o endpoint em execução.

Runtime Moderate

Monitorizar os registos em tempo de execução para traços de exceção invulgares, input malformado ou tentativas de contornar a autorização.

Code review Moderate

Revisão de código: sinalizar qualquer novo código que trate input desta superfície sem usar os ajudantes validados do framework.

Correção automática do Plexicus

O Plexicus deteta automaticamente o CWE-1339 e abre um PR de correção em menos de 60 segundos.

O Codex Remedium analisa cada commit, identifica esta fraqueza exata e entrega um pull request pronto para revisão com o patch. Sem tickets. Sem transferências.

Perguntas frequentes

Frequently asked questions

O que é o CWE-1339?

This vulnerability occurs when a program uses a data type or algorithm that cannot accurately represent or calculate the fractional part of a real number, leading to incorrect results in security-critical operations.

Qual a gravidade do CWE-1339?

A MITRE não publicou uma classificação de probabilidade de exploração para esta fraqueza. Trate-a como impacto médio até o seu modelo de ameaças provar o contrário.

Que linguagens ou plataformas são afetadas pelo CWE-1339?

MITRE lists the following affected platforms: Not OS-Specific, Not Architecture-Specific, Not Technology-Specific.

Como posso prevenir o CWE-1339?

The developer or maintainer can move to a more accurate representation of real numbers. In extreme cases, the programmer can move to representations such as ratios of BigInts which can represent real numbers to extremely fine precision. The programmer can also use the concept of an Unum real. The memory and CPU tradeoffs of this change must be examined. Since floating point reals are used in many products and many locations, they are implemented in hardware and most format changes will cause…

Como é que o Plexicus deteta e corrige o CWE-1339?

O motor SAST do Plexicus correlaciona a assinatura de fluxo de dados do CWE-1339 em cada commit. Quando é encontrada uma correspondência, o nosso agente Codex Remedium abre um PR de correção com o código corrigido, testes e um resumo de uma linha para o revisor.

Onde posso saber mais sobre o CWE-1339?

A MITRE publica a definição canónica em https://cwe.mitre.org/data/definitions/1339.html. Pode também consultar a documentação da OWASP e do NIST para orientações adjacentes.

Fraquezas relacionadas

Weaknesses related to CWE-1339

CWE-682 Pai

Incorrect Calculation

This vulnerability occurs when software performs a calculation that produces wrong or unexpected results, which are then used to make…

CWE-128 Irmão

Wrap-around Error

A wrap-around error happens when a variable exceeds the maximum value its data type can hold, causing it to unexpectedly reset to a very…

CWE-131 Irmão

Incorrect Calculation of Buffer Size

This vulnerability occurs when a program miscalculates the amount of memory needed for a buffer, potentially leading to a buffer overflow…

CWE-1335 Irmão

Incorrect Bitwise Shift of Integer

This vulnerability occurs when a program attempts to shift an integer's bits by an invalid amount—either a negative number or a value…

CWE-135 Irmão

Incorrect Calculation of Multi-Byte String Length

This vulnerability occurs when software incorrectly measures the length of strings containing multi-byte or wide characters, leading to…

CWE-190 Irmão

Integer Overflow or Wraparound

Integer overflow or wraparound occurs when a calculation produces a numeric result that exceeds the maximum value a variable can hold.…

CWE-191 Irmão

Integer Underflow (Wrap or Wraparound)

Integer underflow occurs when a subtraction operation results in a value smaller than the data type's minimum limit, causing the value to…

CWE-193 Irmão

Off-by-one Error

An off-by-one error occurs when a program incorrectly calculates a boundary, such as a loop counter or array index, by being one unit too…

CWE-369 Irmão

Divide By Zero

A divide-by-zero error occurs when software attempts to perform a division operation where the denominator is zero.

Pronto quando você estiver

Pare de pagar por desenvolvedor.
Comece a fechar o ciclo.

O Plexicus é o ASPM nativo de IA que verifica, filtra, corrige, pentesta e explica — de forma autónoma. Programadores ilimitados, repos ilimitados, ações de IA de utilização justa. Nível gratuito real, €269/mo anual quando estiver pronto.