Safeguard
Application Security•

CWE-196 Unsigned to Signed Conversion Error: Underwrite Risk

Casting a large unsigned value to a signed type turns it negative, and negative indexes read or write below a buffer. CWE-196 explained.

Safeguard Security Team
2 min read

CWE-196, Unsigned to Signed Conversion Error, happens when a product casts an unsigned value to a signed type and the value cannot be represented there. It affects C and C++.

How it happens

MITRE describes this as a less frequent issue than signed to unsigned conversion, but a dangerous one. Large unsigned values cast to signed become negative, and when used as an index or in pointer arithmetic they lead to buffer underwrite conditions. That lets an attacker move down the stack, somewhere a normal buffer overflow would not reach.

// Vulnerable
unsigned int idx = get_index_from_packet();   // attacker sends 0xFFFFFFF0
int i = (int)idx;                             // becomes -16
if (i < MAX) {                                // passes
    table[i] = value;                         // writes before the array
}
// Fixed
unsigned int idx = get_index_from_packet();
if (idx >= MAX) {
    return -1;
}
table[idx] = value;

The record lists no observed CVE examples for this entry.

What an attacker gains

MITRE lists crashes from undefined behavior, memory modification when a bad cast leads to a buffer overflow or similar, and potential execution of unauthorized code or bypass of protections.

How to find it

MITRE says automated static analysis (SAST) can find some instances by modelling data flow. Review code where an unsigned value from a file, packet or API is assigned to an int, and where an upper bound check exists without a lower bound check.

How to fix it

The record lists no mitigations, so these are general steps.

  1. Keep indexes and sizes in unsigned types and check the upper bound.
  2. If you must use signed values, check both bounds.
  3. Enable compiler sign conversion warnings.

Quick check

Why does a check against a maximum not catch this? After the cast the value is negative, so it is smaller than the maximum and passes.

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.