CWE-682 Pilar Borrador High likelihood

Incorrect Calculation

This vulnerability occurs when software performs a calculation that produces wrong or unexpected results, which are then used to make security decisions or manage critical resources.

Definición

What is CWE-682?

This vulnerability occurs when software performs a calculation that produces wrong or unexpected results, which are then used to make security decisions or manage critical resources.
Incorrect calculations can directly lead to serious security flaws, such as misallocating memory, granting incorrect permissions, or failing authentication checks. These errors often stem from issues like integer overflows, off-by-one mistakes, or incorrect type conversions during critical operations. When these flawed results feed into security mechanisms, the consequences can escalate significantly. A simple math error might disable a protection feature, allow unauthorized access, or in severe cases, create conditions that enable remote code execution or complete system compromise.
Impacto en el mundo real

Real-world CVEs caused by CWE-682

  • chain: mobile phone Bluetooth implementation does not include offset when calculating packet length (CWE-682), leading to out-of-bounds write (CWE-787)

  • substitution overflow: buffer overflow using environment variables that are expanded after the length check is performed

Cómo lo explotan los atacantes

Ruta del atacante paso a paso

  1. 1

    The following image processing code allocates a table for images.

  2. 2

    This code intends to allocate a table of size num_imgs, however as num_imgs grows large, the calculation determining the size of the list will eventually overflow (CWE-190). This will result in a very small list to be allocated instead. If the subsequent code operates on the list as if it were num_imgs long, it may result in many types of out-of-bounds problems (CWE-119).

  3. 3

    This code attempts to calculate a football team's average number of yards gained per touchdown.

  4. 4

    The code does not consider the event that the team they are querying has not scored a touchdown, but has gained yardage. In that case, we should expect an ArithmeticException to be thrown by the JVM. This could lead to a loss of availability if our error handling code is not set up correctly.

  5. 5

    This example attempts to calculate the position of the second byte of a pointer.

Ejemplo de código vulnerable

Vulnerable C

The following image processing code allocates a table for images.

Vulnerable C
img_t table_ptr; /*struct containing img data, 10kB each*/
  int num_imgs;
  ...
  num_imgs = get_num_imgs();
  table_ptr = (img_t*)malloc(sizeof(img_t)*num_imgs);
  ...
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-682

  • Implementation Understand your programming language's underlying representation and how it interacts with numeric calculation. Pay close attention to byte size discrepancies, precision, signed/unsigned distinctions, truncation, conversion and casting between types, "not-a-number" calculations, and how your language handles numbers that are too large or too small for its underlying representation.
  • Implementation Perform input validation on any numeric input by ensuring that it is within the expected range. Enforce that the input meets both the minimum and maximum requirements for the expected range.
  • Implementation Use the appropriate type for the desired action. For example, in C/C++, only use unsigned types for values that could never be negative, such as height, width, or other numbers related to quantity.
  • Architecture and Design Use languages, libraries, or frameworks that make it easier to handle numbers without unexpected consequences. Examples include safe integer handling packages such as SafeInt (C++) or IntegerLib (C or C++).
  • Architecture and Design Use languages, libraries, or frameworks that make it easier to handle numbers without unexpected consequences. Examples include safe integer handling packages such as SafeInt (C++) or IntegerLib (C or C++).
  • Implementation Examine compiler warnings closely and eliminate problems with potential security implications, such as signed / unsigned mismatch in memory operations, or use of uninitialized variables. Even if the weakness is rarely exploitable, a single failure may lead to the compromise of the entire system.
  • Testing Use automated static analysis tools that target this type of weakness. Many modern techniques use data flow analysis to minimize the number of false positives. This is not a perfect solution, since 100% accuracy and coverage are not feasible.
  • Testing Use dynamic tools and techniques that interact with the product using large test suites with many diverse inputs, such as fuzz testing (fuzzing), robustness testing, and fault injection. The product's operation may slow down, but it should not become unstable, crash, or generate incorrect results.
Señales de detección

How to detect CWE-682

Manual Analysis High

This weakness can be detected using tools and techniques that require manual (human) analysis, such as penetration testing, threat modeling, and interactive tools that allow the tester to record and modify an active session. Specifically, manual static analysis is useful for evaluating the correctness of allocation calculations. This can be useful for detecting overflow conditions (CWE-190) or similar weaknesses that might have serious security impacts on the program.

Auto-corrección de Plexicus

Plexicus detecta automáticamente CWE-682 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-682?

This vulnerability occurs when software performs a calculation that produces wrong or unexpected results, which are then used to make security decisions or manage critical resources.

¿Qué gravedad tiene CWE-682?

MITRE califica la probabilidad de explotación como Alta — esta debilidad se explota activamente en la práctica y debe priorizarse para su remediación.

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

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

¿Cómo puedo prevenir CWE-682?

Understand your programming language's underlying representation and how it interacts with numeric calculation. Pay close attention to byte size discrepancies, precision, signed/unsigned distinctions, truncation, conversion and casting between types, "not-a-number" calculations, and how your language handles numbers that are too large or too small for its underlying representation. Perform input validation on any numeric input by ensuring that it is within the expected range. Enforce that the…

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

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

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

Debilidades relacionadas

Weaknesses related to CWE-682

CWE-170 Puede preceder

Improper Null Termination

This weakness occurs when software fails to properly end a string or array with the required null character or equivalent terminator.

CWE-128 Hijo

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 Hijo

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 Hijo

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 Hijo

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 Hijo

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 Hijo

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 Hijo

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 Hijo

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…

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.