Skip to content

Signed/Unsigned Conversion

Description

The software uses a signed primitive and performs a cast to an unsigned primitive, or uses an unsigned primitive and performs a cast to a signed primitive, which can produce an unexpected value. When the result of a function is to be used as a size parameter, using negative return values can have unexpected results. Although less frequent an issue, unsigned-to-signed conversion can be the precursor to buffer underwrite conditions. Buffer underwrites occur frequently when large unsigned values are cast to signed values, and then used as indexes into a buffer or for pointer arithmetic.

Examples

Insecure Code

c
unsigned int unsignedVar = (unsigned int) -1; int signedVar = (int) unsignedVar;

Secure Code

c
unsigned int unsignedVar = 1; int signedVar = (int) unsignedVar; // Ensure unsignedVar is not negative

Remediation

Avoid casting between signed and unsigned primitives. Ensure that the type of the variable matches the type of the value being assigned to it.

Rule Details

FieldValue
IDCODE-0289
CategoryGeneric
SeverityMEDIUM
CWECWE-195
ConfidenceMEDIUM
ImpactMEDIUM
LikelihoodMEDIUM
ExploitabilityMODERATE
Tagssigned-unsigned-conversion, buffer-underwrite
OWASPN/A

References