CWE-191 Base Borrador

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 wrap around to a large, incorrect number.

Definición

What is CWE-191?

Integer underflow occurs when a subtraction operation results in a value smaller than the data type's minimum limit, causing the value to wrap around to a large, incorrect number.
Integer underflow, also known as wraparound, happens when a program subtracts a larger number from a smaller one, pushing the result below the minimum value the integer type can hold. Instead of throwing an error, the value wraps around to the maximum end of the range—for example, an unsigned 8-bit integer going from 0 to 255 after subtracting 1. This creates a logic flaw where the program operates on a wildly incorrect value, often leading to unexpected behavior. This vulnerability affects both signed and unsigned integers and is a common source of critical security flaws. In signed integers, underflow can flip a positive value to a massive negative one, while in unsigned integers, it creates an unexpectedly large positive value. Developers must validate all subtraction inputs, use safe math libraries, or choose data types with sufficient range to prevent these dangerous wrap-around scenarios.
Impacto en el mundo real

Real-world CVEs caused by CWE-191

  • Integer underflow in firewall via malformed packet.

  • Integer underflow by packet with invalid length.

  • Long input causes incorrect length calculation.

  • Malformed icon causes integer underflow in loop counter variable.

Cómo lo explotan los atacantes

Ruta del atacante paso a paso

  1. 1

    The following example subtracts from a 32 bit signed integer.

  2. 2

    The example has an integer underflow. The value of i is already at the lowest negative value possible, so after subtracting 1, the new value of i is 2147483647.

  3. 3

    This code performs a stack allocation based on a length calculation.

  4. 4

    Since a and b are declared as signed ints, the "a - b" subtraction gives a negative result (-1). However, since len is declared to be unsigned, len is cast to an extremely large positive number (on 32-bit systems - 4294967295). As a result, the buffer buf[len] declaration uses an extremely large size to allocate on the stack, very likely more than the entire computer's memory space.

  5. 5

    Miscalculations usually will not be so obvious. The calculation will either be complicated or the result of an attacker's input to attain the negative value.

Ejemplo de código vulnerable

Vulnerable C

The following example subtracts from a 32 bit signed integer.

Vulnerable C
#include <stdio.h>
  #include <stdbool.h>
  main (void)
  {
  	int i;
  	i = -2147483648;
  	i = i - 1;
  	return 0;
  }
Ejemplo de código seguro

Secure pseudo

Seguro pseudo
// Validate, sanitize, or use a safe API before reaching the sink.
function handleRequest(input) {
  const safe = validateAndEscape(input);
  return executeWithGuards(safe);
}
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-191

  • Architecture Use safe-by-default frameworks and APIs that prevent the unsafe pattern from being expressible.
  • Implementation Validate input at trust boundaries; use allowlists, not denylists.
  • Implementation Apply the principle of least privilege to credentials, file paths, and runtime permissions.
  • Testing Cover this weakness in CI: SAST rules + targeted unit tests for the data flow.
  • Operation Monitor logs for the runtime signals listed in the next section.
Señales de detección

How to detect CWE-191

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-191 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-191?

Integer underflow occurs when a subtraction operation results in a value smaller than the data type's minimum limit, causing the value to wrap around to a large, incorrect number.

¿Qué gravedad tiene CWE-191?

MITRE no ha publicado una calificación de probabilidad de explotación para esta debilidad. Trátala como de impacto medio hasta que tu modelo de amenazas demuestre lo contrario.

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

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

¿Cómo puedo prevenir CWE-191?

Use safe-by-default frameworks, validate untrusted input at trust boundaries, and apply the principle of least privilege. Cover the data-flow signature in CI with SAST.

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

El motor SAST de Plexicus detecta la firma de flujo de datos para CWE-191 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-191?

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

Debilidades relacionadas

Weaknesses related to CWE-191

CWE-682 Padre

Incorrect Calculation

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

CWE-128 Hermano

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 Hermano

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 Hermano

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-1339 Hermano

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…

CWE-135 Hermano

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 Hermano

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-193 Hermano

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 Hermano

Divide By Zero

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

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.