CWE-682 Pilar Rascunho 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.

Definição

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 no 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

Como os atacantes a exploram

Trajeto do atacante passo a passo

  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.

Exemplo de código vulnerável

Vulnerable C

The following image processing code allocates a table for images.

Vulnerável 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);
  ...
Exemplo 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 verificação de prevenção

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.
Sinais de deteção

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.

Correção automática do Plexicus

O Plexicus deteta automaticamente o CWE-682 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.

Perguntas frequentes

Frequently asked questions

O que é o 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.

Qual a gravidade do CWE-682?

A MITRE classifica a probabilidade de exploração como Alta — esta fraqueza é ativamente explorada em campo e deve ser priorizada para remediação.

Que linguagens ou plataformas são afetadas pelo CWE-682?

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

Como posso prevenir o 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…

Como é que o Plexicus deteta e corrige o CWE-682?

O motor SAST do Plexicus correlaciona a assinatura de fluxo de dados do CWE-682 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-682?

A MITRE publica a definição canónica em https://cwe.mitre.org/data/definitions/682.html. Pode também consultar a documentação da OWASP e do NIST para orientações adjacentes.

Fraquezas relacionadas

Weaknesses related to CWE-682

CWE-170 Pode 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 Filho

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 Filho

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 Filho

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 Filho

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 Filho

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 Filho

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 Filho

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 Filho

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…

Pronto quando você estiver

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.