Format String Attacks: How Printf Vulnerabilities Enable Memory Exploitation

Format String Attacks exploit C/C++ formatting functions (printf, fprintf, sprintf, syslog) when user-controlled data is passed directly as the format string parameter. Attackers inject format specifiers to read memory, disclose stack data, or write arbitrary values — potentially achieving full code execution.

Dangerous Format Specifiers

SpecifierAttack Effect
%xReads and displays a word from the stack (memory disclosure)
%sReads character strings from arbitrary memory addresses
%nWrites byte count to an int* argument — enables arbitrary memory writes
%pPrints pointer values (address space disclosure)

The Fundamental Programming Error

// SAFE:
printf("%s", str);
// VULNERABLE — user-controlled str parsed as format string:
printf(str);
// If str = "%x %x %x" → stack values leaked to attacker

Prevention Guidance

  • Always use an explicit format string: printf("%s", str) — never printf(str).
  • Avoid the %n specifier entirely in production code.
  • Enable compiler-level warnings: -Wformat-security in GCC.
  • Restrict format strings to static compile-time values where possible.


Leave a comment