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

Compare with Current View Page History

« Previous Version 132 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.

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.

Accessing memory once it is freed may corrupt the data structures used to manage the heap. References to memory that has been deallocated are referred to as dangling pointers. Accessing a dangling pointer can result in exploitable vulnerabilities.

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 unintended program behavior. As a result, it is necessary to guarantee that memory is not written to or read from once 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.

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

 

 

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

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Related Guidelines

Bibliography

[Kernighan 1988]Section 7.8.5, "Storage Management"
[OWASP Freed Memory] 
[Seacord 2013]Chapter 4, "Dynamic Memory Management"
[Viega 2005]Section 5.2.19, "Using Freed Memory"
[xorl 2009]CVE-2009-1364: LibWMF Pointer Use after free()

 


  • No labels