You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 135 Next »

Do not evaluate any pointers into freed memory after an allocated block of dynamic storage has 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 to memory that has 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 the value of a pointer that refers to space deallocated by a call to the free() or realloc() function is undefined. (See undefined behavior 177 of Annex J.)  

Reading a pointer to deallocated memory is undefined behavior because the pointer value is indeterminate and can have a trap representation. In the latter case, doing so may cause a hardware trap.

When memory is freed, its contents may remain intact and accessible because it is at the memory manager's discretion when to reallocate or recycle the freed chunk. The data at the freed location may appear valid. However, this can change unexpectedly, leading to unexpected program behavior. As a result, it is necessary to guarantee that memory is not 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 incorrect solution, p is freed before the p->next is executed, so p->next reads memory that has already been freed.

#include <stdlib.h>
 
struct node {
  int value;
  struct node *next;
};
 
void free_list(struct node *head) {
  for (struct node *p = head; p != NULL; p = p->next) {
    free(p);
  }
}

Compliant Solution

Kernighan and Ritchie also show the correct solution. To correct this error, a reference to p->next is stored in q before freeing p.

#include <stdlib.h>
 
struct node {
  int value;
  struct node *next;
};
 
void free_list(struct node *head) {
  struct node *q;
  for (struct node *p = head; p != NULL; p = q) {
    q = p->next;
    free(p);
  }
}

Noncompliant Code Example

In this noncompliant code example, buff is written to after it has been freed. These 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.

#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[1]) + 1;
  char *buf = (char *)malloc(bufsize);
  if (!buf) {
    return EXIT_FAILURE;
  }
  /* ... */
  free(buf);
  /* ... */
  return_val = strncpy(buf, argv[1], 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, and the pointer is zeroed in compliance with MEM01-C. Store a new value in pointers immediately after free():

#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[1]) + 1;
  char *buf = (char *)malloc(bufsize);
  if (!buf) {
    return EXIT_FAILURE;
  }

  /* ... */

  return_val = strncpy(buf, argv[1], 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 committee response to Defect Report #400 makes it implementation-defined whether the old object is deallocated if size is zero and memory for the new object is not allocated, and the current implementation of realloc() in glibc 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 exploit" [Seacord 2013].

#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. 

#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); 
    }
  }
  return;
}

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 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].

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 compliant solution simply reassigns im->clip->list to the value of more after the call to realloc:

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++;

Risk Assessment

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 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. (See MEM30-C. Do not access freed memory.) First, reading a pointer to deallocated memory is undefined because the pointer value is indeterminate and can have a trap representation. In the latter case, doing so can cause a hardware trap. When reading a freed pointer doesn't cause a trap, the underlying data structures that manage the heap can become corrupted in a way that can introduce security vulnerabilities into a program. These types of issues are called double-free vulnerabilities. In practice, double-free vulnerabilities can be exploited to execute arbitrary code. 

To eliminate double-free vulnerabilities, it is necessary to guarantee that dynamic memory is freed exactly one time. 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 MEM04-C. Do not perform zero-length allocations.)

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

MEM30-C

High

Likely

Medium

P18

L1

Automated Detection

Tool

Version

Checker

Description

Compass/ROSE

 

 

 

Coverity

2017.07

USE_AFTER_FREE

Can detect the specific instances where memory is deallocated more than once or read/written to the target of a freed pointer

Fortify SCA

5.0

Double Free

 

Klocwork

2024.3

UFM.DEREF.MIGHT
UFM.DEREF.MUST
UFM.RETURN.MIGHT
UFM.RETURN.MUST
UFM.USE.MIGHT
UFM.USE.MUST

 

LDRA tool suite

9.7.1

51 D

Fully implemented

Splint

3.1.1

 

 

Related Vulnerabilities

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.

Related Guidelines

Bibliography

[ISO/IEC 9899:2011]Subclause 7.22.3, "Memory Management Functions"
Annex J, J.2, "Undefined Behavior"
[Kernighan 1988]Section 7.8.5, "Storage Management"
[OWASP Freed Memory] 
[MIT 2005] 
[Seacord 2013]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()

 


  • No labels