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.
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 dataUAF Harm
- Data leakage: Freed memory may be read by other code
- Arbitrary code execution (most severe): Attacker can place fake vtable in freed memory, hijacking control flow
- Crash: Memory may be overwritten by other code
Detecting UAF Tools
- valgrind –track-origins=yes: Detects invalid memory reads
- AddressSanitizer (ASan) : Compile with -fsanitize=address, checks each access against quarantine
- 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
Comments