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 negativeRemediation
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
| Field | Value |
|---|---|
| ID | CODE-0289 |
| Category | Generic |
| Severity | MEDIUM |
| CWE | CWE-195 |
| Confidence | MEDIUM |
| Impact | MEDIUM |
| Likelihood | MEDIUM |
| Exploitability | MODERATE |
| Tags | signed-unsigned-conversion, buffer-underwrite |
| OWASP | N/A |
References
- https://github.com/struct/mms
- https://www.sei.cmu.edu/downloads/sei-cert-c-coding-standard-2016-v01.pdf
- https://docs.microsoft.com/en-us/cpp/sanitizers/asan-error-examples
- https://cwe.mitre.org/data/definitions/789
- http://www.phrack.org/issues/60/10.html#article
- https://cwe.mitre.org/data/definitions/196
- https://cwe.mitre.org/data/definitions/681
- https://cwe.mitre.org/data/definitions/194
- https://cwe.mitre.org/data/definitions/195
- https://g.co/kgs/PCHQjJ
- https://cwe.mitre.org/data/definitions/191