A05 — Use-After-Free: The Problem of Accessing Freed Memory

Key insight: Continuing to use a freed memory block is like continuing to build a house on land you’ve already sold — sooner or later someone will come to tear it down.


What is Use-After-Free

Use-After-Free (UAF) refers to accessing memory that has already been freed — the pointer still exists, but the content it points to has been reclaimed and may have been reallocated.

C
char *buf = malloc(100);
strcpy(buf, "hello");
free(buf);          // memory freed

// buf pointer still valid (points to original address)
// but this memory has been returned to the system

printf("%s", buf);  // Dangerous! May read garbage data
strcpy(buf, "world"); // Even more dangerous! May overwrite other program's data

UAF Harm

  1. Data leakage: Freed memory may be read by other code
  2. Arbitrary code execution (most severe): Attacker can place fake vtable in freed memory, hijacking control flow
  3. Crash: Memory may be overwritten by other code

Detecting UAF Tools

  1. valgrind –track-origins=yes: Detects invalid memory reads
  2. AddressSanitizer (ASan) : Compile with -fsanitize=address, checks each access against quarantine
  3. Static analysis: Compiler warnings

Modern mitigations:

  • Heap hardening: write canary bytes after free
  • Safe deletion: zero pointer after free
  • Heap integrity check: tcache/fastbin double-free checking
Last modified: 2024年10月26日

Author

Comments

Write a Reply or Comment

Your email address will not be published.