You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 7 Next »

Calling free() on a block of dynamic memory marks that memory for deallocation. Once deallocated, the block of memory is made available for future allocation. However, the data stored in the block of memory to be recycled may be preserved. If this memory block contains sensitive information, that information may be unintentionally exposed. This phenomenon is referred to as heap inspection [ref]. To prevent heap inspection it is necessary to clear sensitive information from dynamically allocated buffers before they are freed.

This type of defect can lead to information leakage as is stated in Rule: MEM33-C. Do not assume memory allocation routines initialize memory.

Non-Compliant Code Example 1

In this example, sensitive information in stored in the buffer secret is copied to the dynamically allocated buffer, new_buff, which is then processed and eventually marked for deallocation with free(). However, the contents of new_buff may remain in heap memory after being marked for deallocation. Furthermore, if this memory is recycled by the heap manager, the information stored in new_buff may be exposed to another, unintended section of the program, or another program entirely.

...
new_buff = malloc(strlen(secret)+1);
if (!new_buff) {
  /* Handle Error */
}
strcpy(new_buff, secret);
/* Process new_buff... */
free(new_buff);
...

Compliant Solution 1

h2. Non-Compliant Code Example 2

Using {{realloc()}} to resize dynamic memory may allow heap inspection attacks. {{realloc()}} may allocate a new, larger block of memory, copy the contents, of {{buffer}} to this new block, {{free()}} the original block, and assign the newly allocated block to {{buffer}}. However, the contents of the original block may remain in heap memory after being marked for deallocation.
{code:bgColor=#FFcccc}
...
buffer = realloc(buffer,new_size);
...

Compliant Solution 2


  • No labels