Heap-based Buffer Overflow
A heap overflow condition is a buffer overflow, where the buffer that can be overwritten is allocated in the heap portion of memory, generally meaning that the buffer was allocated using a routine such as malloc().
The following examples help to illustrate the nature of this weakness and describe methods or techniques which can be used to mitigate the risk.
Note that the examples here are by no means exhaustive and any given weakness may have many subtle varieties, each of which may require different detection methods or runtime controls.
While buffer overflow examples can be rather complex, it is possible to have very simple, yet still exploitable, heap-based buffer overflows:
The buffer is allocated heap memory with a fixed size, but there is no guarantee the string in argv will not exceed this size and cause an overflow.
This example applies an encoding procedure to an input string and stores it into a buffer.
The programmer attempts to encode the ampersand character in the user-controlled string, however the length of the string is validated before the encoding procedure is applied. Furthermore, the programmer assumes encoding expansion will only expand a given character by a factor of 4, while the encoding of the ampersand expands by 5. As a result, when the encoding procedure expands the string it is possible to overflow the destination buffer if the attacker provides a string of many ampersands.
Weaknesses in this category are related to memory safety.
Weaknesses in this category are related to the rules and recommendations in the Characters and Strings (STR) section of the SEI CERT C Coding Standard.
This category identifies Software Fault Patterns (SFPs) within the Faulty Buffer Access cluster (SFP8).
This view (slice) covers all the elements in CWE.
This view (slice) lists weaknesses that can be introduced during implementation.
This view (slice) covers issues that are found in C++ programs that are not common to all languages.