
Integer values used as a size argument to malloc()
, calloc()
, or realloc()
can be manipulated by an attacker to cause a buffer overflow. Integer overflow or truncation can result in the allocation of an inadequately sized buffer. The programmer must ensure that size arguments to memory allocation functions are valid and have not been corrupted as the result of an exceptional integer condition.
Non-Compliant Code Example
In this non-compliant code example, cBlocks
is multiplied by 16 and the result is stored in the unsigned long long int alloc
.
void* AllocBlocks(size_t cBlocks) { if (cBlocks == 0) return NULL; unsigned long long alloc = cBlocks * 16; return (alloc < UINT_MAX) ? malloc(cBlocks * 16) : NULL; }
If size_t
is implemented as an unsigned int
type, the result of this multiplication can overflow because the multiplication is performed between two values of size int
and the resulting value stored in alloc
is invalid.
If, on the other hand, size_t
is implemented as an unsigned long long
type, the result of the multiplication operation may not be representable as an unsigned long long
value.
Compliant Solution
Upcasting only works when a size is represented using a smaller type. Because we recommend that all sizes be represented using size_t
, upcasting is never a good idea. Instead, check to make sure the multiplication does not overflow using the methods described in INT32-C. Ensure that integer operations do not result in an overflow. In the following example, the multsize_t()
function sets errno
to a non-zero value if the multiplication operation results in an overflow.
void *AllocBlocks(size_t cBlocks) { size_t alloc; if (cBlocks == 0) return NULL; alloc = multsize_t(cBlocks, 16); if (errno) { return NULL; } else { return malloc(alloc); } } /* end AllocBlocks */
Priority: P6 Level: L2
Providing invalid size arguments to memory allocation functions can lead to buffer overflows and the execution of arbitrary code with the permissions of the vulnerable process.
Component |
Value |
---|---|
Severity |
3 (high) |
Likelihood |
2 (probable) |
Remediation cost |
1 (high) |
References
- ISO/IEC 9899-1999 Section 7.20.3 Memory Management Functions
- Seacord 05 Chapter 4 Dynamic Memory Management; Chapter 5 Integers