Executar análise estática (SAST) na base de código à procura do padrão inseguro no fluxo de dados.
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…
What is CWE-1339?
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]"
Trajeto do atacante passo a passo
- 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
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
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
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].
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:
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]
} 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.
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()
} 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.
How to detect CWE-1339
Executar testes dinâmicos de segurança de aplicações (DAST) contra o endpoint em execução.
Monitorizar os registos em tempo de execução para traços de exceção invulgares, input malformado ou tentativas de contornar a autorização.
Revisão de código: sinalizar qualquer novo código que trate input desta superfície sem usar os ajudantes validados do framework.
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.
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.
Weaknesses related to CWE-1339
Incorrect Calculation
This vulnerability occurs when software performs a calculation that produces wrong or unexpected results, which are then used to make…
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…
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…
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…
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…
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.…
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…
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…
Divide By Zero
A divide-by-zero error occurs when software attempts to perform a division operation where the denominator is zero.
Further reading
- MITRE — CWE-1339 oficial https://cwe.mitre.org/data/definitions/1339.html
- Is COBOL holding you hostage with Math? https://medium.com/the-technical-archaeologist/is-cobol-holding-you-hostage-with-math-5498c0eb428b
- Intermediate results and arithmetic precision https://www.ibm.com/docs/en/cobol-zos/6.2?topic=appendixes-intermediate-results-arithmetic-precision
- 8.1.2. Arbitrary Precision Numbers https://www.postgresql.org/docs/8.3/datatype-numeric.html#DATATYPE-NUMERIC-DECIMAL
- Muller's Recurrence https://scipython.com/blog/mullers-recurrence/
- An Improvement To Floating Point Numbers https://hackaday.com/2015/10/22/an-improvement-to-floating-point-numbers/
- HIGH PERFORMANCE COMPUTING: ARE WE JUST GETTING WRONG ANSWERS FASTER? https://www3.nd.edu/~markst/cast-award-speech.pdf
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.