CWE-122: Heap-based Buffer Overflow

Description

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().

Submission Date :

July 19, 2006, midnight

Modification Date :

2023-10-26 00:00:00+00:00

Organization :

MITRE
Example Vulnerable Codes

Example - 1

While buffer overflow examples can be rather complex, it is possible to have very simple, yet still exploitable, heap-based buffer overflows:



char *buf;buf = (char *)malloc(sizeof(char)*BUFSIZE);strcpy(buf, argv[1]);#define BUFSIZE 256int main(int argc, char **argv) {}

The buffer is allocated heap memory with a fixed size, but there is no guarantee the string in argv[1] will not exceed this size and cause an overflow.

Example - 2

This example applies an encoding procedure to an input string and stores it into a buffer.


die("user string too long, die evil hacker!");

dst_buf[dst_index++] = '&';dst_buf[dst_index++] = 'a';dst_buf[dst_index++] = 'm';dst_buf[dst_index++] = 'p';dst_buf[dst_index++] = ';';

// /* encode to < */// 

if( '&' == user_supplied_string[i] ){}else if ('<' == user_supplied_string[i] ){}else dst_buf[dst_index++] = user_supplied_string[i];
int i, dst_index;char *dst_buf = (char*)malloc(4*sizeof(char) * MAX_SIZE);if ( MAX_SIZE <= strlen(user_supplied_string) ){}dst_index = 0;for ( i = 0; i < strlen(user_supplied_string); i++ ){}return dst_buf;char * copy_input(char *user_supplied_string){}

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.

Related Weaknesses

This table shows the weaknesses and high level categories that are related to this weakness. These relationships are defined to give an overview of the different insight to similar items that may exist at higher and lower levels of abstraction.

Visit http://cwe.mitre.org/ for more details.