CWE-197 Base Incompleto Low likelihood

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.

Definición

What is 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.
This vulnerability occurs because converting a larger integer (like a 32-bit `int`) to a smaller one (like a 16-bit `short`) doesn't raise an error—it silently discards the most significant bits. The resulting truncated value is often completely different from what the developer intended. This corrupted data can then cause critical failures if it's used as a buffer index, a loop counter, or a piece of application state, putting the system into an unpredictable and dangerous condition. While bitmasking to intentionally isolate low bits is a valid technique, unintentional truncation is almost always a coding bug. These errors can be subtle and spread across large codebases. Managing this at scale is difficult; an ASPM like Plexicus can help you track and remediate these flaws across your entire stack by correlating SAST findings with runtime data and suggesting precise fixes.
Impacto en el mundo real

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.

Cómo lo explotan los atacantes

Ruta del atacante paso a paso

  1. 1

    This example, while not exploitable, shows the possible mangling of values associated with truncation errors:

  2. 2

    The above code, when compiled and run on certain systems, returns the following output:

  3. 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. 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. 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.

Ejemplo de código vulnerable

Vulnerable C

This example, while not exploitable, shows the possible mangling of values associated with truncation errors:

Vulnerable C
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);
Ejemplo de código seguro

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.

Seguro Java
...
```
// 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* 
  		
  		```
  			...
  		}
  }
  ...
What changed: the unsafe sink is replaced (or the input is validated/escaped) so the same payload no longer triggers the weakness.
Lista de prevención

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.
Señales de detección

How to detect CWE-197

Fuzzing High

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.

Automated Static Analysis High

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.)

Auto-corrección de Plexicus

Plexicus detecta automáticamente CWE-197 y abre un PR de corrección en menos de 60 segundos.

Codex Remedium escanea cada commit, identifica esta debilidad concreta y entrega un pull request listo para revisión con el parche. Sin tickets. Sin traspasos.

Preguntas frecuentes

Frequently asked questions

¿Qué es 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.

¿Qué gravedad tiene CWE-197?

MITRE califica la probabilidad de explotación como Baja — la explotación es poco frecuente, pero la debilidad debe corregirse cuando se descubra.

¿Qué lenguajes o plataformas se ven afectados por CWE-197?

MITRE lists the following affected platforms: C, C++, Java, C#.

¿Cómo puedo prevenir CWE-197?

Ensure that no casts, implicit or explicit, take place that move from a larger size primitive or a smaller size primitive.

¿Cómo detecta y corrige Plexicus CWE-197?

El motor SAST de Plexicus detecta la firma de flujo de datos para CWE-197 en cada commit. Cuando hay coincidencia, nuestro agente Codex Remedium abre un PR de corrección con el código corregido, las pruebas y un resumen de una línea para el revisor.

¿Dónde puedo aprender más sobre CWE-197?

MITRE publica la definición canónica en https://cwe.mitre.org/data/definitions/197.html. También puedes consultar la documentación de OWASP y NIST para guías relacionadas.

Listo cuando tú lo estés

Deja de pagar por desarrollador.
Empieza a cerrar el bucle.

Plexicus es el ASPM nativo de IA que escanea, filtra, corrige, pentestea y explica — de forma autónoma. Desarrolladores ilimitados, repos ilimitados, acciones de IA de uso justo. Nivel gratuito real, €269/mo anual cuando estés listo.