CWE-682 Pilier Brouillon 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.

Définition

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.
Impact réel

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

Comment les attaquants l'exploitent

Parcours de l'attaquant étape par étape

  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.

Exemple de code vulnérable

Vulnerable C

The following image processing code allocates a table for images.

Vulnérable 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);
  ...
Exemple de code sécurisé

Secure pseudo

Sécurisé 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.
Liste de contrôle de prévention

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.
Signaux de détection

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.

Correction automatique Plexicus

Plexicus détecte automatiquement CWE-682 et ouvre une PR de correction en moins de 60 secondes.

Codex Remedium analyse chaque commit, identifie cette faiblesse précise et livre une pull request prête à être relue avec le correctif. Pas de tickets. Pas de transferts.

Questions fréquentes

Frequently asked questions

Qu'est-ce que 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.

Quelle est la gravité de CWE-682 ?

MITRE évalue la probabilité d'exploitation comme Élevée — cette faiblesse est activement exploitée et doit être priorisée pour la remédiation.

Quels langages ou plateformes sont affectés par CWE-682 ?

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

Comment puis-je prévenir 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…

Comment Plexicus détecte et corrige CWE-682 ?

Le moteur SAST de Plexicus reconnaît la signature de flux de données de CWE-682 à chaque commit. Lorsqu'une correspondance est trouvée, notre agent Codex Remedium ouvre une PR de correction avec le code corrigé, les tests et un résumé d'une ligne pour le relecteur.

Où puis-je en savoir plus sur CWE-682 ?

MITRE publie la définition canonique à https://cwe.mitre.org/data/definitions/682.html. Vous pouvez également consulter la documentation OWASP et NIST pour des conseils adjacents.

Faiblesses associées

Weaknesses related to CWE-682

CWE-170 Peut précéder

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 Enfant

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 Enfant

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 Enfant

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 Enfant

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 Enfant

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 Enfant

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 Enfant

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 Enfant

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…

Prêt quand vous l'êtes

Arrêtez de payer par développeur.
Commencez à fermer la boucle.

Plexicus est l'ASPM natif IA qui scanne, filtre, corrige, penteste et explique — de façon autonome. Développeurs illimités, dépôts illimités, actions IA à usage équitable. Vrai niveau gratuit, €269/mo annuel quand vous êtes prêt.