...
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_secret
, which is then processed and eventually marked for deallocation with free()
. However, the contents of new_secret
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_secret
may be exposed to another, unintended section of the program, or another program entirely.
Code Block | ||
---|---|---|
| ||
... char *new_secret; size_t size = strlen(secret); if (size == SIZE_MAX) { /* Handle Error */ } new_secret = malloc(size+1); /* allocate space + NULL Terminator */ if (!new_secret) { /* Handle Error */ } strcpy(new_secret, secret); /* Process new_secret... */ free(new_secret); ... |
Compliant Solution 1
To prevent information leakage, dynamic memory containing sensitive information should be sanitized before it is marked for deallocation. Below, this is done by filling the allocated space with '\0'
characters.
Code Block | ||
---|---|---|
| ||
... char *new_secret; size_t size = strlen(secret); if (size == SIZE_MAX) { /* 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
Using realloc()
to resize dynamic memory may inadvertently expose sensitive data. 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 Block | ||
---|---|---|
| ||
... buffer = realloc(buffer,new_size); ... |
Compliant Solution 2
Code Block | ||
---|---|---|
| ||
Risk Assessment
Failure to clear dynamic memory can result in leaked information.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
MEM33-C | 2 (medium) | 1 (unlikely) | 3 (low) | P6 | L2 |
Refernces
http://vulncat.fortifysoftware.com/2/HI.html
http://samate.nist.gov/docs/SAMATE_source_code_analysis_tool_spec_09_15_06.pdf
MEM33-C. Do not assume memory allocation routines initialize memory