Safeguard
Application Security•

CWE-682 Incorrect Calculation: When Bad Math Becomes a Security Bug

A wrong offset, a wrong width or a wrong comparison can break allocation, permissions and certificate checks. CWE-682 explained, with fixes.

Safeguard Security Team
4 min read

CWE-682, Incorrect Calculation, covers a calculation that produces incorrect or unintended results which are later used in a security-critical decision or in resource management. It is language and technology neutral. Any product that does arithmetic on sizes, offsets, counts or privileges can have it.

MITRE's extended description lists what goes wrong: incorrect resource allocations, incorrect privilege assignments, failed comparisons. Many direct results of a bad calculation lead to larger problems such as a failed protection mechanism or even arbitrary code execution.

How it happens

The record offers three real chains.

  • CVE-2020-0022: a mobile phone Bluetooth implementation does not include an offset when calculating packet length, leading to an out-of-bounds write.
  • CVE-2010-1378: an incorrect calculation allows attackers to bypass certificate checks.
  • CVE-2004-1363: a substitution overflow, where a buffer overflow occurs through environment variables that are expanded after the length check is performed.

The last one is a nice teaching case. The length was checked, but it was checked at the wrong moment, before the data grew. The calculation was correct for the input it saw and wrong for the input that was used.

A generic version of that mistake, as an illustration:

# Vulnerable: length is measured before expansion
def build_path(template, env):
    if len(template) > 64:
        raise ValueError("too long")
    return expand_vars(template, env)   # result may be much longer than 64

What an attacker gains

MITRE lists four distinct outcomes:

  • Crash, exit or restart if the program lands in an unexpected state.
  • Resource consumption, memory corruption or execution of unauthorized code when the result drives allocation.
  • Gaining privileges or assuming identity when the calculation assigns permissions.
  • Bypassing a protection mechanism when it causes an insufficient comparison, for example a weakened validation routine.

How to find it

MITRE names three techniques. Manual analysis, such as penetration testing and threat modelling, catches logic errors that tools cannot see. Automated static analysis finds some instances by modelling data and control flow. Fuzzing generates many diverse inputs and watches for crashes, which is good at exposing wrong offsets and lengths.

How to fix it

These come straight from the MITRE mitigation list.

  1. Understand how your language represents numbers. Pay attention to byte size, precision, signed versus unsigned, truncation, casting, not-a-number results, and what happens when a value is too large or too small.
  2. Validate numeric input against the expected minimum and maximum.
  3. Use the right type for the job. In C and C++, use unsigned types only for values that can never be negative, such as widths, heights and quantities.
  4. Prefer languages or libraries that make number handling safer. MITRE names SafeInt for C++ and IntegerLib for C and C++.
  5. Read compiler warnings closely and remove those with security implications, like signed and unsigned mismatches in memory operations or use of uninitialized variables. MITRE adds that even if a flaw is rarely exploitable, a single failure may compromise the whole system.

The fix for the substitution example is to measure after the transformation:

# Fixed: check the final value, not the input
def build_path(template, env):
    path = expand_vars(template, env)
    if len(path) > 64:
        raise ValueError("too long")
    return path

If a bad calculation lives in a library you depend on, you will not find it by reading your own code. The free dependency scan at gold.safeguard.sh/scan checks a dependency file against known vulnerabilities in the browser. No login, and the file stays local.

Quick check

Why is checking length before variable expansion wrong?

Because expansion can make the data longer, so the checked length no longer describes what is stored. Validate the final value.

Which fuzzing outcome suggests a calculation error?

Crashes tied to out-of-bounds reads or writes on specific lengths or offsets, since wrong arithmetic usually shows up as a bad size or position.

Sources

Never miss an update

Weekly insights on software supply chain security, delivered to your inbox.

Self-healing security runs on Safeguard.

Your first fix PR is minutes away.

No sales call required, even your agent can complete the purchase over MCP.