Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

To prevent information leakage, dynamic memory containing sensitive information should be sanitized before it is marked for deallocationbeing freed. This is commonly accomplished by clearing the allocated space (that is, filling the space with '\0' characters).

...

Non-Compliant Code Example: realloc()

Reallocating memory using the realloc() function is a degenerative case of freeing memory. The realloc() function function deallocates the old object and returns a pointer to a new object.

Wiki Markup
Using {{realloc()}} to resize dynamic memory may inadvertently expose sensitive information, or allow heap inspection as is described in Fortify's Taxonomy of Software Security Errors \[[vulncat|http://vulncat.fortifysoftware.com/2/HI.html]\] and NIST's Source Code Analysis Tool Functional Specification \[[SAMATE|http://samate.nist.gov/docs/SAMATE_source_code_analysis_tool_spec_09_15_06.pdf]\]. When {{realloc()}} is called it may allocate a new, larger block of memoryobject, copy the contents, of {{secret}} to this new blockobject, {{free()}} the original blockobject, and assign the newly allocated blockobject to {{secret}}. However, the contents of the original blockobject may remain in heap memory after being marked for deallocation.

Code Block
bgColor#FFcccc
...
secret = realloc(secret, new_size);
...

Compliant Solution: realloc()

Correcting this example requires the programmer to write a custom routine A compliant program cannot rely on realloc() because it is not possible to clear the memory prior to the call.
Instead, a custom function that operates similar to realloc(), but sanitizes sensitive information as heap-based buffers are resized. Again, this is done by overwriting the space to be deallocated with '\0' characters.

Code Block
bgColor#ccccff
...
temp_buff = calloc(newsecret_size * 2,sizeof(char)); /* use calloc() initializes memory to zero-out allocated space */
if (temp_buff == NULL) {
 /* Handle Error */
}

if (secret_size > new_size)  /* may lead to truncation */
secret_size = new_size;

memcpy(temp_buff, secret, secret_size);
memset(secret, '\0', secret_size);         /* sanitize the buffer */

free(secret);
secret = temp_buff;                      /* install the resized buffer */
temp_buff = NULL;
...

...