Fuzz testing (fuzzing) is a powerful technique for generating large numbers of diverse inputs - either randomly or algorithmically - and dynamically invoking the code with those inputs. Even with random inputs, it is often capable of generating unexpected results such as crashes, memory corruption, or resource consumption. Fuzzing effectively produces repeatable test cases that clearly indicate bugs, which helps developers to diagnose the issues.
Numeric Truncation Error
A numeric truncation error happens when a program converts a number to a smaller data type, cutting off its higher-order bits and corrupting the original value.
What is CWE-197?
Real-world CVEs caused by CWE-197
-
Chain: integer truncation (CWE-197) causes small buffer allocation (CWE-131) leading to out-of-bounds write (CWE-787) in kernel pool, as exploited in the wild per CISA KEV.
-
Integer truncation of length value leads to heap-based buffer overflow.
-
Size of a particular type changes for 64-bit platforms, leading to an integer truncation in document processor causes incorrect index to be generated.
Trajeto do atacante passo a passo
- 1
This example, while not exploitable, shows the possible mangling of values associated with truncation errors:
- 2
The above code, when compiled and run on certain systems, returns the following output:
- 3
This problem may be exploitable when the truncated value is used as an array index, which can happen implicitly when 64-bit values are used as indexes, as they are truncated to 32 bits.
- 4
In the following Java example, the method updateSalesForProduct is part of a business application class that updates the sales information for a particular product. The method receives as arguments the product ID and the integer amount sold. The product ID is used to retrieve the total product count from an inventory object which returns the count as an integer. Before calling the method of the sales object to update the sales count the integer values are converted to The primitive type short since the method requires short type for the method arguments.
- 5
However, a numeric truncation error can occur if the integer values are higher than the maximum value allowed for the primitive type short. This can cause unexpected results or loss or corruption of data. In this case the sales database may be corrupted with incorrect data. Explicit casting from a from a larger size primitive type to a smaller size primitive type should be prevented. The following example an if statement is added to validate that the integer values less than the maximum value for the primitive type short before the explicit cast and the call to the sales method.
Vulnerable C
This example, while not exploitable, shows the possible mangling of values associated with truncation errors:
int intPrimitive;
short shortPrimitive;
intPrimitive = (int)(~((int)0) ^ (1 << (sizeof(int)*8-1)));
shortPrimitive = intPrimitive;
printf("Int MAXINT: %d\nShort MAXINT: %d\n", intPrimitive, shortPrimitive); Secure Java
However, a numeric truncation error can occur if the integer values are higher than the maximum value allowed for the primitive type short. This can cause unexpected results or loss or corruption of data. In this case the sales database may be corrupted with incorrect data. Explicit casting from a from a larger size primitive type to a smaller size primitive type should be prevented. The following example an if statement is added to validate that the integer values less than the maximum value for the primitive type short before the explicit cast and the call to the sales method.
...
```
// update sales database for number of product sold with product ID*
public void updateSalesForProduct(String productID, int amountSold) {
```
```
// get the total number of products in inventory database*
int productCount = inventory.getProductCount(productID);
*// make sure that integer numbers are not greater than*
*// maximum value for type short before converting*
if ((productCount < Short.MAX_VALUE) && (amountSold < Short.MAX_VALUE)) {
```
```
// convert integer values to short, the method for the*
*// sales object requires the parameters to be of type short*
short count = (short) productCount;
short sold = (short) amountSold;
*// update sales database for product*
sales.updateSalesCount(productID, count, sold);
else {
*// throw exception or perform other processing*
```
...
}
}
... How to prevent CWE-197
- Implementation Ensure that no casts, implicit or explicit, take place that move from a larger size primitive or a smaller size primitive.
How to detect CWE-197
Automated static analysis, commonly referred to as Static Application Security Testing (SAST), can find some instances of this weakness by analyzing source code (or binary/compiled code) without having to execute it. Typically, this is done by building a model of data flow and control flow, then searching for potentially-vulnerable patterns that connect "sources" (origins of input) with "sinks" (destinations where the data interacts with external components, a lower layer such as the OS, etc.)
O Plexicus deteta automaticamente o CWE-197 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-197?
A numeric truncation error happens when a program converts a number to a smaller data type, cutting off its higher-order bits and corrupting the original value.
Qual a gravidade do CWE-197?
A MITRE classifica a probabilidade de exploração como Baixa — a exploração é pouco comum, mas a fraqueza deve mesmo assim ser corrigida quando descoberta.
Que linguagens ou plataformas são afetadas pelo CWE-197?
MITRE lists the following affected platforms: C, C++, Java, C#.
Como posso prevenir o CWE-197?
Ensure that no casts, implicit or explicit, take place that move from a larger size primitive or a smaller size primitive.
Como é que o Plexicus deteta e corrige o CWE-197?
O motor SAST do Plexicus correlaciona a assinatura de fluxo de dados do CWE-197 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-197?
A MITRE publica a definição canónica em https://cwe.mitre.org/data/definitions/197.html. Pode também consultar a documentação da OWASP e do NIST para orientações adjacentes.
Weaknesses related to CWE-197
Incorrect Conversion between Numeric Types
This vulnerability occurs when a program converts a value from one numeric type to another (like a 64-bit integer to a 32-bit integer) and…
Integer Coercion Error
An integer coercion error occurs when a program incorrectly converts, extends, or truncates a number between different data types, leading…
Unexpected Sign Extension
This vulnerability occurs when a signed number from a smaller data type is moved or cast to a larger type, causing its sign bit to be…
Signed to Unsigned Conversion Error
This vulnerability occurs when a signed integer (which can hold negative values) is converted to an unsigned integer (which holds only…
Unsigned to Signed Conversion Error
This vulnerability occurs when a program takes an unsigned integer and converts it directly to a signed integer. If the original unsigned…
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.