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 being freed. This is commonly accomplished by clearing the allocated space (that is, filling the space with '\0' characters).

Code Block
bgColor#ccccff
langc
char *secret;

/* initialize secret */

char *new_secret;
size_t size = strlen(secret);
if (size == SIZE_MAX) {
  /* Handle error */
}

/* use calloc() to zero-out allocated space */
new_secret = (char *)calloc(size+1, sizeof(char));
if (!new_secret) {
  /* Handle error */
}
strcpy(new_secret, secret);

/* Process new_secret... */

/* sanitize memory  */
memset_s(new_secret, '\0', size);
free(new_secret);
new_secret = NULL;

...

Wiki Markup
Using {{realloc()}} to resize dynamic memory may inadvertently expose sensitive information, or it may allow heap inspection as described in the _Fortify Taxonomy: Software Security Errors_ \[[Fortify 2006|AA. Bibliography#Fortify 06]\] and NIST's _Source Code Analysis Tool Functional Specification_ \[[Black 2007|AA. Bibliography#Black 07]\]. When {{realloc()}} is called it may allocate a new, larger object, copy the contents of {{secret}} to this new object, {{free()}} the original object, and assign the newly allocated object to {{secret}}. However, the contents of the original object may remain in memory.

Code Block
bgColor#FFcccc
langc
char *secret;

/* initialize secret */

size_t secret_size = strlen(secret);
/* ... */
if (secret_size > SIZE_MAX/2) {
   /* handle error condition */
}
else {
secret = (char *)realloc(secret, secret_size * 2);
}

...

A compliant program cannot rely on realloc() because it is not possible to clear the memory prior to the call. Instead, a custom function must be used 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
langc
char *secret;

/* initialize secret */

size_t secret_size = strlen(secret);
char *temp_buff;
/* ... */
if (secret_size > SIZE_MAX/2) {
   /* handle error condition */
}
/* calloc() initializes memory to zero */
temp_buff = (char *)calloc(secret_size * 2, sizeof(char));
if (temp_buff == NULL) {
 /* Handle error */
}

memcpy(temp_buff, secret, secret_size);

/* sanitize the buffer */
memset((volatile char *)secret, '\0', secret_size);

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

...