...
Code Block | ||
---|---|---|
| ||
... secret = realloc(secret ,new_size); ... |
Compliant Solution 2
Correcting this example requires the programmer to write a custom routine that operates similar to realloc()
, but sanitizes sensitive information as heap-based buffers are resized. First, a new, resized block of memory is allocated (note that calloc()
is used to ensure its contents are properly initialized). Second, the contents of secret
are copied to this new space. Next, the memory referred to by secret
is sanitized by overwriting its contents with '\0'
characters. Next, the memory referred to by secret
is then free()
'd. Finally, the newly allocated space is installed, taking care to remove all unneeded references to the new space.
Note that this solution will truncate the contents of original buffer, secret
if the size of the resized buffer is smaller. This behavior is similar to how realloc()
handles resizing to a smaller block of memory.
Code Block | ||
---|---|---|
| ||
...
temp_buff = calloc(new_size,sizeof(char)); /* use calloc() 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;
...
|
Risk Assessment
Failure to clear dynamic memory can result in leaked information.
...