Do not evaluate any Evaluating pointers into freed memory after an allocated block of dynamic storage has memory that have been deallocated by a memory management function, including dereferencing or , acting as an operand of an arithmetic operation, type casting, or using the pointer as the right-hand side of an assignment. References , is undefined behavior. Pointers to memory that has have been deallocated are referred to as dangling pointers. Accessing a dangling pointer can result in exploitable vulnerabilities.
According to the C Standard, the behavior of a program that uses tusing the value of a pointer that refers to space deallocated by a call to the free()
or realloc()
function is undefined behavior (see undefined behavior 177).
Reading a pointer to deallocated memory is undefined behavior because the pointer value is indeterminate and might be a trap representation. Fetching a trap representation might perform a hardware trap (but is not required to).
When memory is freed, its contents might remain intact and accessible because it is It is at the memory manager's discretion when to reallocate or recycle the freed chunk. The memory. When memory is freed, all pointers into it become invalid, and its contents might either be returned to the operating system, making the freed space inaccessible, or remain intact and accessible. As a result, the data at the freed location can appear valid. However, this can change unexpectedly, leading to unexpected program behavior. As a result, it is necessary to guarantee that memory is not to be valid but change unexpectedly. Consequently, memory must not be written to or read from once it is freed.Writing to memory after it has been freed may corrupt the data structures used to manage the heap. Freeing memory multiple times has similar consequences to accessing memory after it is freed.
Noncompliant Code Example
This example from Brian Kernighan and Dennis Ritchie [Kernighan 1988] shows both the incorrect and correct techniques for freeing the memory associated with a linked list. In their (intentionally) incorrect solutionexample, p
is freed before p->next
is executed, so that p->next
reads memory that has already been freed.
...
Compliant Solution
Kernighan and Ritchie also correct this error by storing a reference to p->next
in q
before freeing p
:
...
In this noncompliant code example, buff
buf
is written to after it has been freed. These Write-after-free vulnerabilities can be easily exploited to run arbitrary code with the permissions of the vulnerable process and are seldom this obvious. Typically, allocations and frees are far removed, making it difficult to recognize and diagnose these problems.
Code Block | ||||
---|---|---|---|---|
| ||||
#include <stdlib.h> #include <string.h> int main(int argc, char *argv[]) { if (argc < 2) { /* Print usage */ return EXIT_FAILURE; } char *return_val = 0; const size_t bufsize = strlen(argv[10]) + 1; char *buf = (char *)malloc(bufsize); if (!buf) { return EXIT_FAILURE; } /* ... */ free(buf); /* ... */ return_val = strncpystrcpy(buf, argv[10], bufsize); // Undefined behavior if (return_val) { return EXIT_FAILURE; } /* ... */ return EXIT_SUCCESS; } |
Compliant Solution
In this compliant solution, the memory is freed after its final use:
Code Block | ||||
---|---|---|---|---|
| ||||
#include <stdlib.h> #include <string.h> int main(int argc, char *argv[]) { if (argc < 2) { /* Print usage */ return EXIT_FAILURE; } char *return_val = 0; const size_t bufsize = strlen(argv[10]) + 1; char *buf = (char *)malloc(bufsize); if (!buf) { return EXIT_FAILURE; } /* ... */ return_val = strncpystrcpy(buf, argv[10], bufsize); if (return_val) { free(buf); return EXIT_FAILURE; } /* ... */ free(buf); return EXIT_SUCCESS; } |
Noncompliant Code Example
In this noncompliant example, a diagnostic is required because realloc()
may free c_str1
when it returns a null pointer, resulting in c_str1
being freed twice. The WG14 committeeC Standards Committee's proposed response to Defect Report #400 makes it implementation-defined whether or not the old object is deallocated if when size
is zero and memory for the new object is not allocated, and the . The current implementation of realloc()
in glibc the GNU C Library and Microsoft Visual Studio's Runtime Library will free c_str1
and return a null pointer for zero byte allocations. Freeing a pointer twice can result in a potentially exploitable vulnerability commonly referred to as a double-free exploitvulnerability [Seacord 20132013b].
Code Block | ||||
---|---|---|---|---|
| ||||
#include <stdlib.h>
void f(char *c_str1, size_t size) {
char *c_str2 = (char *)realloc(c_str1, size);
if (c_str2 == NULL) {
free(c_str1); // diagnostic required
return;
}
} |
Compliant Solution
This compliant solution does not pass a size argument of zero to the realloc()
function, eliminating the possibility of c_str1
being freed twice:
Code Block | ||||
---|---|---|---|---|
| ||||
#include <stdlib.h> void f(char *c_str1, size_t size) { if (size != 0) { char *c_str2 = (char *)realloc(c_str1, size); if (c_str2 == NULL) { free(c_str1); } } else { return free(c_str1); } } |
If the intent of calling f()
is to reduce the size of the object, then doing nothing when the size is zero would be unexpected; instead, this compliant solution frees the object.
Noncompliant Code Example
In this noncompliant example (CVE-2009-1364) from libwmf
version 0.2.8.4, the return value of gdRealloc
(a simple wrapper around realloc()
that reallocates space pointed to by im->clip->list
) is set to more
. However, the value of im->clip->list
is used directly afterwards in the code, and the C Standard specifies that if realloc()
moves the area pointed to, then the original block is freed. An attacker can then execute arbitrary code by forcing a reallocation (with a sufficient im->clip->count
) and accessing freed memory [xorl 2009].
Code Block | ||||
---|---|---|---|---|
| ||||
void gdClipSetAdd(gdImagePtr im, gdClipRectanglePtr rect) {
gdClipRectanglePtr more;
if (im->clip == 0) {
/* ... */
}
if (im->clip->count == im->clip->max) {
more = gdRealloc (im->clip->list,(im->clip->max + 8) *
sizeof (gdClipRectangle));
/*
* If the realloc fails, then we have not lost the
* im->clip->list value.
*/
if (more == 0) return;
im->clip->max += 8;
}
im->clip->list[im->clip->count] = *rect;
im->clip->count++;
|
Compliant Solution
The This compliant solution simply reassigns im->clip->list
to the value of more
after the call to realloc()
:
Code Block | ||||
---|---|---|---|---|
| ||||
void gdClipSetAdd(gdImagePtr im, gdClipRectanglePtr rect) {
gdClipRectanglePtr more;
if (im->clip == 0) {
/* ... */
}
if (im->clip->count == im->clip->max) {
more = gdRealloc (im->clip->list,(im->clip->max + 8) *
sizeof (gdClipRectangle));
if (more == 0) return;
im->clip->max += 8;
im->clip->list = more;
}
im->clip->list[im->clip->count] = *rect;
im->clip->count++;
|
...
Reading memory that has already been freed can lead to abnormal program termination and denial-of-service attacks. Writing memory that has already been freed can additionally lead to the execution of arbitrary code with the permissions of the vulnerable process.
Freeing memory multiple times has similar consequences to accessing memory after it is freed. First, reading Reading a pointer to deallocated memory is undefined behavior because the pointer value is indeterminate and might be a trap representation. When reading a freed pointer doesn't from or writing to freed memory does not cause a trap, it may corrupt the underlying data structures that manage the heap can become corrupted in a manner that can be exploited to execute arbitrary code. These coding errors are referred to as double-free vulnerabilitiesAlternatively, writing to memory after it has been freed might modify memory that has been reallocated.
Programmers should be wary when freeing memory in a loop or conditional statement; if coded incorrectly, these constructs can lead to double-free vulnerabilities. It is also a common error to misuse the realloc()
function in a manner that results in double-free vulnerabilities . (See see MEM04-C. Beware of zero-length allocations).)
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
MEM30-C | High | Likely | Medium | P18 | L1 |
...
VU#623332 describes a double-free vulnerability in the MIT Kerberos 5 function krb5_recvauth().
Search for other vulnerabilities resulting from the violation of this rule on the CERT website.
...
CERT C Secure Coding Standard | MEM01-C. Store a new value in pointers immediately after free() |
CERT C++ Secure Coding Standard | MEM30-CPP. Do not access freed memory |
ISO/IEC TR 24772:2013 | Dangling References to Stack Frames [DCM] Dangling Reference to Heap [XYK] |
ISO/IEC TS 17961 | Accessing freed memory [accfree] |
MISRA C:2012 | Rule 18.6 (required) |
MITRE CWE |
Bibliography
[ISO/IEC 9899:2011] | Subclause 7.22.3, "Memory Management Functions" |
[Kernighan 1988] | Section 7.8.5, "Storage Management" |
[OWASP Freed Memory] | |
[MIT 2005] | |
[Seacord 20132013b] | Chapter 4, "Dynamic Memory Management" |
[Viega 2005] | Section 5.2.19, "Using Freed Memory" |
[VU#623332] | |
[xorl 2009] | CVE-2009-1364: LibWMF Pointer Use after free() |
...