Doubly Freeing Memory

From Guidance Share

Jump to: navigation, search

Contents

Description

Freeing or deleting the same memory chunk twice may result in an application crash. It may also, when combined with other flaws on a system that does not perform heap-chunk checking, allow an attacker access to arbitrary memory.

Applies To

  • Language: C, C++, Assembly
  • Operating system: All

Example

The following example shows double freeing of memory (note that the following code could also result in a buffer overrun):

#include <stdio.h>
#include <unistd.h>
#define BUFSIZE 512

int main(int argc, char **argv) { 
char *buf;
buf = (char *) malloc(BUFSIZE);
free(buf);
strncpy(buf, argv[1], BUFSIZE);
free(buf);
}

Impact

  • Availability: If heap chunk checking is performed, double freeing may result in an application crash.
  • Access control: If heap chunk checking is not performed, double freeing may result in an attacker gaining access to arbitrary memory locations.

Vulnerabilities

  • Failure to ensure that each memory allocation is freed once and only once.

Countermeasures

  • Implementation: Ensure that each allocation is freed only once. After freeing a chunk, set the pointer to NULL to ensure the pointer cannot be freed again. In complicated error conditions, be sure that clean-up routines respect the state of allocation properly. If the language is object oriented, ensure that object destructors delete each chunk of memory only once.

Vulnerability Patterns

How Tos

Personal tools