Versions Compared

Key

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

...

In this example, sensitive information in stored in the buffer secret is copied to the dynamically allocated buffer, new_buffsecret, which is then processed and eventually marked for deallocation with free(). However, the contents of new_buffsecret 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_buffsecret may be exposed to another, unintended section of the program, or another program entirely.

Code Block
bgColor#FFcccc
...
char *new_buffsecret;
size_t size = malloc(strlen(secret);
if (size == SIZE_MAX || size == 0) {
  /* Handle Error */
}

new_secret = malloc(size+1); /* allocate space + NULL Terminator */
if (!new_buffsecret) {
  /* Handle Error */
}
strcpy(new_buffsecret, secret);

/* Process new_buffsecret... */

free(new_buffsecret);
...

Compliant Solution 1

...

Code Block
bgColor#ccccff


...
char *new_secret;
size_t size = strlen(secret);
if (size == SIZE_MAX || size == 0) {
  /* Handle Error */
}

new_secret = malloc(size+1); /* allocate space + NULL Terminator */
if (!new_secret) {
  /* Handle Error */
}
strcpy(new_secret, secret);

/* Process new_secret... */

memset(new_secret,'\0',size); /* sanitize memory  */
free(new_secret);
...

Non-Compliant Code Example 2

...